Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

feat(plugins): add ruflo-arena β€” competitive ruliology (arenas, tournaments, co-evolution) (#2315)

Ofer Shaal87682a6e78cc
diff --git a/plugins/ruflo-arena/.claude-plugin/plugin.json b/plugins/ruflo-arena/.claude-plugin/plugin.json
new file mode 100644
index 0000000000..be9d7644dc
--- /dev/null
+++ b/plugins/ruflo-arena/.claude-plugin/plugin.json
@@ -0,0 +1,24 @@
+{
+ "name": "ruflo-arena",
+ "version": "0.1.0-alpha.1",
+ "description": "Competitive ruliology for Ruflo swarms β€” arenas, tournaments, and adaptive co-evolution of program strategies (ADR-147/148). Strategies-as-programs compete under payoff games; tournaments produce Wolfram-style competitive arrays; hill-climb and mutual co-evolution discover winners empirically.",
+ "author": {
+ "name": "ruvnet",
+ "url": "https://github.com/ruvnet"
+ },
+ "homepage": "https://github.com/ruvnet/ruflo",
+ "license": "MIT",
+ "keywords": [
+ "ruflo",
+ "claude-flow",
+ "arena",
+ "tournament",
+ "ruliology",
+ "game-theory",
+ "co-evolution",
+ "competition",
+ "mcp"
+ ],
+ "categories": ["intelligence", "swarm", "simulation"],
+ "repository": "https://github.com/ruvnet/ruflo"
+}
diff --git a/plugins/ruflo-arena/.gitignore b/plugins/ruflo-arena/.gitignore
new file mode 100644
index 0000000000..136e73a67d
--- /dev/null
+++ b/plugins/ruflo-arena/.gitignore
@@ -0,0 +1,6 @@
+node_modules/
+dist/
+.ruflo/
+*.tsbuildinfo
+# Lockfile is regenerated inside the ruflo workspace; an isolated install pulls peer deps.
+package-lock.json
diff --git a/plugins/ruflo-arena/README.md b/plugins/ruflo-arena/README.md
new file mode 100644
index 0000000000..dffebf7d83
--- /dev/null
+++ b/plugins/ruflo-arena/README.md
@@ -0,0 +1,78 @@
+# ruflo-arena
+
+Competitive ruliology for Ruflo swarms β€” **arenas**, **tournaments**, and **adaptive
+co-evolution** of program strategies. Implements the first executable slice of Ruflo
+ADR-147/148/150, following Stephen Wolfram's
+[*Games Between Programs: The Ruliology of Competition*](https://writings.stephenwolfram.com/2026/06/games-between-programs-the-ruliology-of-competition/).
+
+Strategies are **programs** (deterministic finite-state machines reading opponent history).
+They compete under payoff games; tournaments produce Wolfram's **competitive array**; hill-climb
+and **mutual co-evolution** discover winners empirically β€” because, per computational
+irreducibility, you have to *run* the competition to find out.
+
+## Install & test
+
+```bash
+cd plugins/ruflo-arena
+npm install # light β€” runtime dep is just zod
+npm run build # tsc -> dist/
+npm test # vitest (engine + MCP tools + persistence)
+npm run lint # eslint (typescript-eslint)
+```
+
+## CLI
+
+```bash
+node dist/cli.js demo # tournament + evolution + co-evolution
+node dist/cli.js tournament --game pd --rounds 200 --seed 1
+node dist/cli.js arena --a tit-for-tat --b always-defect
+node dist/cli.js evolve --game pd --generations 400 --seed 42
+node dist/cli.js coevolve --game pd --generations 400 --seed 7
+```
+
+Sample PD ranking (mean-vs-field): `grim β‰ˆ 2.99`, `always-defect β‰ˆ 2.76`, `tit-for-tat β‰ˆ 2.50`,
+… `always-cooperate β‰ˆ 1.88`. The evolution run climbs from a random FSM (~2.78) to ~3.00 with
+the characteristic plateau→breakthrough fitness curve.
+
+## MCP tools (`ruflo-arena/mcp-tools`)
+
+| Tool | Purpose |
+|------|---------|
+| `arena/run` | one deterministic match between two named strategies |
+| `tournament/run` | round-robin β†’ competitive array + mean-vs-field ranking |
+| `evolve/run` | hill-climb an FSM vs the field; returns program + fitness curve |
+| `coevolve/run` | mutual co-evolution (arms race) trace |
+| `run/get`, `run/list` | fetch/list persisted run records |
+
+All return `{ success, result | error }` and validate inputs with Zod. See
+[`commands/arena.md`](commands/arena.md) and [`docs/adrs/0001-arena-contract.md`](docs/adrs/0001-arena-contract.md).
+
+## Persistence
+
+Full run artifacts are written to `.ruflo/arena/<runId>.json` (exact replay). Each tool result
+also carries an `agentdb` payload so the command layer can store a searchable summary via
+`mcp__claude-flow__memory_store` (namespace `arena`) β€” the local stand-in for the RuVector data
+layer (ADR-196/197), enabling queries like *"tournaments where grim dominated"*.
+
+## Scope
+
+v1 is intentionally Ruflo-only and core-untouched:
+
+- **In:** simple-program + stochastic strategies, PD + zero-sum games, tournaments, hill-climb &
+ co-evolution, file/AgentDB persistence, MCP tools + CLI.
+- **Out (tracked elsewhere):** LLM-agent strategies + distillation (ADR-151), execution
+ sandboxing/resource governance (ADR-153), dashboard UI (ADR-149/154), and the full RuVector
+ data/intelligence layer (ADR-196–198, ADR-200).
+
+## Architecture
+
+```
+src/
+ domain/ types (+ Zod schemas) Β· games Β· strategies (FSM programs, library, mutation)
+ engine/ rng Β· arena (match) Β· tournament (competitive array) Β· evolution (hill-climb, co-evolution)
+ persistence/ RunStore (File + InMemory) + AgentDB record builder
+ report/ competitive-array tables Β· ASCII heatmaps Β· fitness sparklines
+ mcp-tools/ arenaTools: MCPTool[] (the 6 tools above)
+ index.ts export surface + default { tools }
+ cli.ts human-facing CLI
+```
diff --git a/plugins/ruflo-arena/commands/arena.md b/plugins/ruflo-arena/commands/arena.md
new file mode 100644
index 0000000000..399fe083c0
--- /dev/null
+++ b/plugins/ruflo-arena/commands/arena.md
@@ -0,0 +1,59 @@
+---
+name: arena
+description: Competitive ruliology β€” run arenas and tournaments between program strategies, evolve winners, and persist runs (ADR-147/148)
+---
+
+$ARGUMENTS
+
+Run *competitions between programs* and *evolve* winning strategies, following Stephen
+Wolfram's "Games Between Programs: The Ruliology of Competition". Parse `$ARGUMENTS` to pick
+a subcommand. Each subcommand maps to an MCP tool exported by this plugin
+(`arena/run`, `tournament/run`, `evolve/run`, `coevolve/run`, `run/get`, `run/list`).
+
+### Subcommands
+
+**`arena run --a <strategy> --b <strategy> [--game pd] [--rounds 200] [--seed 1]`**
+Run one deterministic match. Strategies come from the classic roster
+(`tit-for-tat`, `always-cooperate`, `always-defect`, `grim`, `pavlov`, `alternate`, `random`, …).
+1. Call MCP tool `arena/run` with the parsed args.
+2. Report cumulative + mean payoffs.
+
+**`arena tournament [--game pd] [--rounds 200] [--seed 1]`**
+Round-robin over the classic roster β†’ Wolfram's **competitive array** (mean-payoff matrix) + mean-vs-field ranking.
+1. Call `tournament/run`.
+2. Display `result.tables.competitiveArray` and `result.tables.ranking`.
+
+**`arena evolve [--game pd] [--generations 300] [--seed 42]`**
+Hill-climb an FSM strategy against the field (mutate → keep-if-fitter). Shows the plateau→breakthrough fitness curve.
+1. Call `evolve/run`; display `result.sparkline`, `finalFitness`, and the evolved program.
+
+**`arena coevolve [--game pd] [--generations 400] [--seed 7]`**
+Mutual co-evolution (arms race) between two evolving strategies.
+1. Call `coevolve/run`; display the payoff trace and range.
+
+**`arena runs [--limit 20]`** / **`arena get <runId>`**
+List or fetch persisted run records.
+
+### Persistence (AgentDB)
+
+The MCP tools persist full artifacts to `.ruflo/arena/<runId>.json` (exact replay). Each tool
+result also includes an `agentdb` payload β€” use it to store a searchable summary in AgentDB so
+runs are queryable later (the local stand-in for the RuVector data layer, ADR-196/197):
+
+```
+mcp__claude-flow__memory_store({
+ namespace: result.agentdb.namespace, // "arena"
+ key: result.agentdb.key, // the runId
+ value: result.agentdb.value, // JSON summary (kind, game, seed, ranking/fitness …)
+ tags: result.agentdb.tags // ["ruliology","competition", kind, game]
+})
+```
+
+Later: `mcp__claude-flow__memory_search({ namespace: "arena", query: "tournaments where grim dominated" })`.
+
+### Notes
+
+- Everything is reproducible under `--seed`. Non-halting programs are out of scope in v1
+ (FSMs always halt); untrusted/evolved-program sandboxing is tracked in ADR-153.
+- See `docs/adrs/0001-arena-contract.md` for the tool/data contract and
+ `../../INTEGRATION-ADRS.md` (in the ruliad meta-repo) for the full ADR map.
diff --git a/plugins/ruflo-arena/docs/adrs/0001-arena-contract.md b/plugins/ruflo-arena/docs/adrs/0001-arena-contract.md
new file mode 100644
index 0000000000..b09ad9f29d
--- /dev/null
+++ b/plugins/ruflo-arena/docs/adrs/0001-arena-contract.md
@@ -0,0 +1,65 @@
+# ADR-0001: ruflo-arena plugin contract
+
+**Status**: Proposed
+**Date**: 2026-06-07
+**Plugin**: ruflo-arena
+
+## Context
+
+`ruflo-arena` implements the first executable slice of the competitive-ruliology initiative
+(Ruflo ADR-147 competitive arena/tournament modes, ADR-148 co-evolution, ADR-150 visualization
+split), following Stephen Wolfram's
+[*Games Between Programs: The Ruliology of Competition*](https://writings.stephenwolfram.com/2026/06/games-between-programs-the-ruliology-of-competition/).
+This ADR pins the plugin's public contract so downstream surfaces (commands, dashboards,
+the RuVector data layer) can depend on stable shapes.
+
+## Decision
+
+### Tool surface (`./mcp-tools`)
+
+| Tool | Purpose |
+|------|---------|
+| `arena/run` | one deterministic match between two named strategies |
+| `tournament/run` | round-robin β†’ competitive array (mean-payoff matrix) + ranking |
+| `evolve/run` | hill-climb an FSM vs the field; returns program + fitness curve |
+| `coevolve/run` | mutual co-evolution (arms race) trace |
+| `run/get`, `run/list` | fetch/list persisted run records |
+
+Every tool returns the Ruflo envelope `{ success: boolean; result?: T; error?: { message } }`
+and validates input with Zod at the boundary. Numeric inputs are coerced (MCP/CLI friendliness).
+
+### Core types (`.` / `./engine`)
+
+- `GameSpec` β€” payoff matrix over an action set (`prisoners-dilemma`, `match-or-not`).
+- `Strategy` β€” `FsmStrategy` (deterministic Moore machine: output on state, transition on
+ opponent action) or `FnStrategy` (closure, e.g. `random`). This is "strategy as program".
+- `MatchResult`, `TournamentResult`, `EvolutionResult`, `CoevolutionResult`, `RunRecord`.
+
+### Persistence contract
+
+- TS code persists full artifacts via `RunStore` (`FileRunStore` β†’ `.ruflo/arena/<runId>.json`;
+ `InMemoryRunStore` for tests). This is the local stand-in for RuVector ADR-197.
+- AgentDB persistence is performed at the **command/agent layer** (Ruflo convention): each tool
+ result carries an `agentdb` payload `{ namespace:"arena", key, value, tags }` for
+ `mcp__claude-flow__memory_store`, making runs semantically searchable.
+
+### Determinism
+
+All runs are reproducible under `seed`. The RunRecord captures `seed` and the full artifact for
+bit-for-bit replay β€” Wolfram's requirement that competitions be re-runnable.
+
+## Consequences
+
+- **Positive**: stable, typed contract; zero runtime deps beyond Zod; engine is pure and
+ unit-tested; no Ruflo-core changes; clean seam for the RuVector data layer and the dashboard.
+- **Negative / Costs**: v1 only ships simple-program + stochastic strategies; LLM strategies
+ (ADR-151), sandboxing (ADR-153), and the dashboard UI (ADR-149) are out of scope here.
+- **Neutral / Risks**: the AgentDB summary schema (`agentdb.value`) is unversioned in v1;
+ formalize with the RuVector integration contract (ADR-152 ↔ ADR-200) before cross-repo use.
+
+## References
+
+- Stephen Wolfram, *Games Between Programs: The Ruliology of Competition*, June 2026 β€”
+ https://writings.stephenwolfram.com/2026/06/games-between-programs-the-ruliology-of-competition/
+- Ruflo ADR-147 (arena/tournament), ADR-148 (co-evolution), ADR-149 (dashboard), ADR-150 (viz split)
+- RuVector ADR-196 (strategy graphs), ADR-197 (payoff/fitness storage)
diff --git a/plugins/ruflo-arena/eslint.config.js b/plugins/ruflo-arena/eslint.config.js
new file mode 100644
index 0000000000..4d2889a033
--- /dev/null
+++ b/plugins/ruflo-arena/eslint.config.js
@@ -0,0 +1,19 @@
+import js from '@eslint/js';
+import tseslint from 'typescript-eslint';
+
+export default tseslint.config(
+ { ignores: ['dist/**', 'node_modules/**'] },
+ js.configs.recommended,
+ ...tseslint.configs.recommended,
+ {
+ rules: {
+ // TypeScript handles undefined identifiers; the base rule misfires on globals.
+ 'no-undef': 'off',
+ '@typescript-eslint/no-explicit-any': 'off',
+ '@typescript-eslint/no-unused-vars': [
+ 'error',
+ { argsIgnorePattern: '^_', varsIgnorePattern: '^_' },
+ ],
+ },
+ },
+);
diff --git a/plugins/ruflo-arena/package.json b/plugins/ruflo-arena/package.json
new file mode 100644
index 0000000000..488ff7e313
--- /dev/null
+++ b/plugins/ruflo-arena/package.json
@@ -0,0 +1,47 @@
+{
+ "name": "ruflo-arena",
+ "version": "0.1.0-alpha.1",
+ "description": "Competitive ruliology for Ruflo swarms β€” arenas, tournaments, and adaptive co-evolution of program strategies (ADR-147/148).",
+ "type": "module",
+ "main": "dist/index.js",
+ "types": "dist/index.d.ts",
+ "exports": {
+ ".": "./dist/index.js",
+ "./mcp-tools": "./dist/mcp-tools/index.js",
+ "./engine": "./dist/engine/index.js"
+ },
+ "bin": {
+ "ruflo-arena": "./dist/cli.js"
+ },
+ "scripts": {
+ "build": "tsc",
+ "dev": "tsc --watch",
+ "test": "vitest run",
+ "test:watch": "vitest",
+ "typecheck": "tsc --noEmit",
+ "lint": "eslint src tests",
+ "demo": "node --experimental-strip-types src/cli.ts demo"
+ },
+ "dependencies": {
+ "zod": "^3.22.4"
+ },
+ "devDependencies": {
+ "@eslint/js": "^9.10.0",
+ "@types/node": "^20.10.0",
+ "eslint": "^9.10.0",
+ "typescript": "^5.3.0",
+ "typescript-eslint": "^8.5.0",
+ "vitest": "^4.0.16"
+ },
+ "keywords": ["ruflo", "arena", "tournament", "ruliology", "co-evolution"],
+ "author": "ruvnet",
+ "license": "MIT",
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/ruvnet/ruflo.git",
+ "directory": "plugins/ruflo-arena"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+}
diff --git a/plugins/ruflo-arena/src/cli.ts b/plugins/ruflo-arena/src/cli.ts
new file mode 100644
index 0000000000..46b6154695
--- /dev/null
+++ b/plugins/ruflo-arena/src/cli.ts
@@ -0,0 +1,116 @@
+#!/usr/bin/env node
+// Human-facing CLI for ruflo-arena. Subcommands mirror the MCP tools (ADR-147).
+// ruflo-arena demo | arena | tournament | evolve | coevolve
+
+import { getGame } from './domain/games.js';
+import { classicRoster, findStrategy } from './domain/strategies.js';
+import { runMatch } from './engine/arena.js';
+import { runTournament } from './engine/tournament.js';
+import { coevolve, evolveVsField } from './engine/evolution.js';
+import {
+ competitiveArrayTable,
+ describeFSM,
+ evolutionSummary,
+ heatmap,
+ rankingTable,
+ sparkline,
+} from './report/render.js';
+
+type Flags = Record<string, string>;
+
+function parseArgs(argv: string[]): { command: string; flags: Flags } {
+ const positional: string[] = [];
+ const flags: Flags = {};
+ for (let i = 0; i < argv.length; i++) {
+ const a = argv[i];
+ if (a.startsWith('--')) {
+ const key = a.slice(2);
+ flags[key] = argv[i + 1] && !argv[i + 1].startsWith('--') ? argv[++i] : 'true';
+ } else positional.push(a);
+ }
+ return { command: positional[0] ?? 'demo', flags };
+}
+
+function cmdArena(flags: Flags): void {
+ const game = getGame(flags.game ?? 'pd');
+ const a = findStrategy(game, flags.a ?? 'tit-for-tat');
+ const b = findStrategy(game, flags.b ?? 'always-defect');
+ const res = runMatch(game, a, b, { rounds: Number(flags.rounds ?? 200), seed: Number(flags.seed ?? 1) });
+ console.log(`\nArena β€” ${game.name} (${res.rounds} rounds, seed ${res.seed})`);
+ console.log(` ${a.name} vs ${b.name}`);
+ console.log(` cumulative : ${res.cumulative[0]} : ${res.cumulative[1]}`);
+ console.log(` mean/round : ${res.mean[0].toFixed(3)} : ${res.mean[1].toFixed(3)}`);
+}
+
+function cmdTournament(flags: Flags): void {
+ const game = getGame(flags.game ?? 'pd');
+ const t = runTournament(game, classicRoster(game), {
+ rounds: Number(flags.rounds ?? 200),
+ seed: Number(flags.seed ?? 1),
+ });
+ console.log(`\nCompetitive array β€” ${game.name} (${t.rounds} rounds, seed ${t.seed})`);
+ console.log('rows = strategy, cols = opponent; cell = mean payoff to row\n');
+ console.log(competitiveArrayTable(t));
+ console.log('\nheatmap:\n' + heatmap(t.matrix));
+ console.log('\nRanking (mean-vs-field):');
+ console.log(rankingTable(t));
+}
+
+function cmdEvolve(flags: Flags): void {
+ const game = getGame(flags.game ?? 'pd');
+ const r = evolveVsField(game, classicRoster(game), {
+ generations: Number(flags.generations ?? 300),
+ seed: Number(flags.seed ?? 42),
+ rounds: Number(flags.rounds ?? 100),
+ });
+ const s = evolutionSummary(r);
+ console.log(`\nEvolve vs field β€” ${game.name} (${r.generations} generations, seed ${flags.seed ?? 42})`);
+ console.log(` start fitness : ${s.startFitness.toFixed(3)}`);
+ console.log(` final fitness : ${s.finalFitness.toFixed(3)} (accepted mutations: ${s.acceptedMutations})`);
+ console.log(` fitness curve : ${sparkline(r.curve.map((c) => c.fitness))}`);
+ console.log('\nEvolved strategy:\n' + describeFSM(r.best));
+}
+
+function cmdCoevolve(flags: Flags): void {
+ const game = getGame(flags.game ?? 'pd');
+ const r = coevolve(game, {
+ generations: Number(flags.generations ?? 400),
+ seed: Number(flags.seed ?? 7),
+ rounds: Number(flags.rounds ?? 100),
+ });
+ const payoffs = r.curve.map((c) => c.payoffA);
+ console.log(`\nCo-evolution (arms race) β€” ${game.name} (${r.generations} generations)`);
+ console.log(" A's head-to-head payoff over time (A maximises, B minimises):");
+ console.log(' ' + sparkline(payoffs));
+ console.log(` range: [${Math.min(...payoffs).toFixed(2)}, ${Math.max(...payoffs).toFixed(2)}]`);
+}
+
+function cmdDemo(): void {
+ console.log('============================================================');
+ console.log(' ruflo-arena β€” competitive ruliology demo (ADR-147/148/150)');
+ console.log('============================================================');
+ cmdTournament({ game: 'pd', rounds: '200', seed: '1' });
+ cmdEvolve({ game: 'pd', generations: '400', seed: '42' });
+ cmdCoevolve({ game: 'pd', generations: '400', seed: '7' });
+ cmdTournament({ game: 'mon', rounds: '200', seed: '1' });
+}
+
+const COMMANDS: Record<string, (flags: Flags) => void> = {
+ arena: cmdArena,
+ tournament: cmdTournament,
+ evolve: cmdEvolve,
+ coevolve: cmdCoevolve,
+ demo: () => cmdDemo(),
+};
+
+function main(): void {
+ const { command, flags } = parseArgs(process.argv.slice(2));
+ const fn = COMMANDS[command];
+ if (!fn) {
+ console.error(`unknown command "${command}". Commands: ${Object.keys(COMMANDS).join(', ')}`);
+ process.exit(1);
+ }
+ fn(flags);
+}
+
+main();
diff --git a/plugins/ruflo-arena/src/domain/games.ts b/plugins/ruflo-arena/src/domain/games.ts
new file mode 100644
index 0000000000..818ace98f2
--- /dev/null
+++ b/plugins/ruflo-arena/src/domain/games.ts
@@ -0,0 +1,61 @@
+// GameSpec library β€” payoff matrices (Ruflo ADR-147). Prisoner's dilemma (symmetric)
+// and match-or-not (zero-sum), per Wolfram's "Games Between Programs".
+
+import type { ActionSymbol, GameSpec, Payoff } from './types.js';
+
+export function makeGame(
+ name: string,
+ actions: readonly ActionSymbol[],
+ table: Record<string, Payoff>,
+ zeroSum = false,
+): GameSpec {
+ return {
+ name,
+ actions,
+ zeroSum,
+ payoff(a, b) {
+ const cell = table[`${a}|${b}`];
+ if (!cell) throw new Error(`${name}: no payoff for (${a}, ${b})`);
+ return cell;
+ },
+ };
+}
+
+/** Iterated Prisoner's Dilemma β€” classic R=3, T=5, S=0, P=1. */
+export const prisonersDilemma: GameSpec = makeGame(
+ 'prisoners-dilemma',
+ ['C', 'D'],
+ {
+ 'C|C': [3, 3],
+ 'C|D': [0, 5],
+ 'D|C': [5, 0],
+ 'D|D': [1, 1],
+ },
+ false,
+);
+
+/** Match-or-not (zero-sum): A scores when actions agree, B when they differ. */
+export const matchOrNot: GameSpec = makeGame(
+ 'match-or-not',
+ ['0', '1'],
+ {
+ '0|0': [1, -1],
+ '1|1': [1, -1],
+ '0|1': [-1, 1],
+ '1|0': [-1, 1],
+ },
+ true,
+);
+
+export const GAMES: Record<string, GameSpec> = {
+ 'prisoners-dilemma': prisonersDilemma,
+ pd: prisonersDilemma,
+ 'match-or-not': matchOrNot,
+ mon: matchOrNot,
+};
+
+export function getGame(key: string): GameSpec {
+ const g = GAMES[key];
+ if (!g) throw new Error(`unknown game "${key}". Known: ${Object.keys(GAMES).join(', ')}`);
+ return g;
+}
diff --git a/plugins/ruflo-arena/src/domain/strategies.ts b/plugins/ruflo-arena/src/domain/strategies.ts
new file mode 100644
index 0000000000..10c2216005
--- /dev/null
+++ b/plugins/ruflo-arena/src/domain/strategies.ts
@@ -0,0 +1,191 @@
+// Strategies-as-programs (Ruflo ADR-147/148, RuVector ADR-196). The core representation is
+// a deterministic Moore machine: OUTPUT depends on the current state, TRANSITION depends on
+// the opponent's last action β€” Wolfram's "strategy = a simple program reading history".
+
+import { randInt, choice } from '../engine/rng.js';
+import type { ActionSymbol, AgentInstance, FsmStrategy, GameSpec, Strategy } from './types.js';
+
+/** Instantiate a runnable agent from a strategy + its own rng stream. */
+export function instantiate(strategy: Strategy, rng: () => number): AgentInstance {
+ if (strategy.kind === 'fn') {
+ let state = strategy.init(rng);
+ return {
+ act: () => strategy.act(state, rng),
+ observe: (own, opp) => {
+ state = strategy.update(state, own, opp, rng);
+ },
+ };
+ }
+ let cur = strategy.start;
+ return {
+ act: () => strategy.states[cur].action,
+ observe: (_own, opp) => {
+ const next = strategy.states[cur].next[opp];
+ cur = next === undefined ? cur : next; // guard: unknown action => stay
+ },
+ };
+}
+
+// --- Classic library (factories parameterized by the game's action set) --------------------
+
+export function constant(actions: readonly ActionSymbol[], idx: number, name?: string): FsmStrategy {
+ const a = actions[idx];
+ const next = Object.fromEntries(actions.map((x) => [x, 0]));
+ return { kind: 'fsm', name: name ?? `always-${a}`, nStates: 1, start: 0, states: [{ action: a, next }] };
+}
+
+export function copyOpponent(actions: readonly ActionSymbol[], startIdx = 0, name?: string): FsmStrategy {
+ const states = actions.map((a) => ({
+ action: a,
+ next: Object.fromEntries(actions.map((x, j) => [x, j])),
+ }));
+ return { kind: 'fsm', name: name ?? 'tit-for-tat', nStates: actions.length, start: startIdx, states };
+}
+
+export function antiCopy(actions: readonly ActionSymbol[], startIdx = 0, name?: string): FsmStrategy {
+ const states = actions.map((a) => ({
+ action: a,
+ next: Object.fromEntries(actions.map((x, j) => [x, (j + 1) % actions.length])),
+ }));
+ return { kind: 'fsm', name: name ?? 'anti-tit-for-tat', nStates: actions.length, start: startIdx, states };
+}
+
+export function alternate(actions: readonly ActionSymbol[], name?: string): FsmStrategy {
+ const states = actions.map((a, i) => ({
+ action: a,
+ next: Object.fromEntries(actions.map((x) => [x, (i + 1) % actions.length])),
+ }));
+ return { kind: 'fsm', name: name ?? 'alternate', nStates: actions.length, start: 0, states };
+}
+
+/** Cooperate until the opponent plays actions[1], then play actions[1] forever. */
+export function grim(actions: readonly ActionSymbol[], name?: string): FsmStrategy {
+ const [nice, mean] = actions;
+ return {
+ kind: 'fsm',
+ name: name ?? 'grim',
+ nStates: 2,
+ start: 0,
+ states: [
+ { action: nice, next: { [nice]: 0, [mean]: 1 } },
+ { action: mean, next: { [nice]: 1, [mean]: 1 } },
+ ],
+ };
+}
+
+/** Win-Stay-Lose-Shift / Pavlov: repeat last action iff actions matched last round. */
+export function pavlov(actions: readonly ActionSymbol[], name?: string): FsmStrategy {
+ const [c, d] = actions;
+ return {
+ kind: 'fsm',
+ name: name ?? 'pavlov',
+ nStates: 2,
+ start: 0,
+ states: [
+ { action: c, next: { [c]: 0, [d]: 1 } },
+ { action: d, next: { [d]: 0, [c]: 1 } },
+ ],
+ };
+}
+
+/** Uniformly random action (exercises the seeded rng; a closure strategy). */
+export function random(actions: readonly ActionSymbol[], name?: string): Strategy {
+ return {
+ kind: 'fn',
+ name: name ?? 'random',
+ init: () => null,
+ act: (_s, rng) => choice(rng, actions),
+ update: (s) => s,
+ };
+}
+
+/** A sensible spread of opponents for a given game. */
+export function classicRoster(game: GameSpec): Strategy[] {
+ const a = game.actions;
+ if (game.name === 'prisoners-dilemma') {
+ return [
+ copyOpponent(a, 0, 'tit-for-tat'),
+ constant(a, 0, 'always-cooperate'),
+ constant(a, 1, 'always-defect'),
+ grim(a, 'grim'),
+ pavlov(a, 'pavlov'),
+ antiCopy(a, 0, 'suspicious-anti-tft'),
+ alternate(a, 'alternate'),
+ random(a, 'random'),
+ ];
+ }
+ return [
+ constant(a, 0, `always-${a[0]}`),
+ constant(a, 1, `always-${a[1]}`),
+ copyOpponent(a, 0, 'copy-opponent'),
+ antiCopy(a, 0, 'anti-copy'),
+ alternate(a, 'alternate'),
+ random(a, 'random'),
+ ];
+}
+
+export function findStrategy(game: GameSpec, name: string): Strategy {
+ const roster = classicRoster(game);
+ const s = roster.find((r) => r.name === name || r.name.startsWith(name));
+ if (!s) throw new Error(`unknown strategy "${name}". Available: ${roster.map((r) => r.name).join(', ')}`);
+ return s;
+}
+
+// --- Evolvable FSMs β€” random genomes + mutation operators (ADR-148) ------------------------
+
+export function randomFSM(game: GameSpec, rng: () => number, nStates = 2, name = 'evolved'): FsmStrategy {
+ const a = game.actions;
+ const states = [];
+ for (let i = 0; i < nStates; i++) {
+ states.push({
+ action: choice(rng, a),
+ next: Object.fromEntries(a.map((x) => [x, randInt(rng, nStates)])),
+ });
+ }
+ return { kind: 'fsm', name, nStates, start: randInt(rng, nStates), states };
+}
+
+function cloneFSM(fsm: FsmStrategy): FsmStrategy {
+ return {
+ kind: 'fsm',
+ name: fsm.name,
+ nStates: fsm.nStates,
+ start: fsm.start,
+ states: fsm.states.map((s) => ({ action: s.action, next: { ...s.next } })),
+ };
+}
+
+const MUTATORS = ['flipAction', 'rewire', 'moveStart', 'addState', 'removeState'] as const;
+
+/** Return a mutated copy of an FSM (one random structural edit). */
+export function mutate(fsm: FsmStrategy, game: GameSpec, rng: () => number): FsmStrategy {
+ const a = game.actions;
+ const m = cloneFSM(fsm);
+ let op: (typeof MUTATORS)[number] = choice(rng, MUTATORS);
+ if (op === 'removeState' && m.nStates <= 1) op = 'addState';
+
+ if (op === 'flipAction') {
+ m.states[randInt(rng, m.nStates)].action = choice(rng, a);
+ } else if (op === 'rewire') {
+ const s = randInt(rng, m.nStates);
+ m.states[s].next[choice(rng, a)] = randInt(rng, m.nStates);
+ } else if (op === 'moveStart') {
+ m.start = randInt(rng, m.nStates);
+ } else if (op === 'addState') {
+ const idx = m.nStates;
+ m.states.push({
+ action: choice(rng, a),
+ next: Object.fromEntries(a.map((x) => [x, randInt(rng, idx + 1)])),
+ });
+ m.nStates += 1;
+ m.states[randInt(rng, idx)].next[choice(rng, a)] = idx; // make new state reachable
+ } else {
+ const victim = randInt(rng, m.nStates);
+ m.states.splice(victim, 1);
+ m.nStates -= 1;
+ const remap = (t: number) => (t === victim ? 0 : t > victim ? t - 1 : t);
+ for (const st of m.states) for (const k of a) st.next[k] = remap(st.next[k]);
+ m.start = remap(m.start);
+ }
+ return m;
+}
diff --git a/plugins/ruflo-arena/src/domain/types.ts b/plugins/ruflo-arena/src/domain/types.ts
new file mode 100644
index 0000000000..8627d578d3
--- /dev/null
+++ b/plugins/ruflo-arena/src/domain/types.ts
@@ -0,0 +1,146 @@
+// Domain contracts for competitive ruliology (Ruflo ADR-147/148).
+// Strategies are *programs*; games are payoff matrices; runs are reproducible artifacts.
+
+import { z } from 'zod';
+
+export type ActionSymbol = string;
+export type Payoff = readonly [number, number];
+
+/** A 2-player, simultaneous-move game defined by its payoff matrix. */
+export interface GameSpec {
+ readonly name: string;
+ readonly actions: readonly ActionSymbol[];
+ readonly zeroSum: boolean;
+ payoff(a: ActionSymbol, b: ActionSymbol): Payoff;
+}
+
+/** One state of a Moore machine: the action it emits + transitions on the opponent's action. */
+export interface FsmState {
+ action: ActionSymbol;
+ next: Record<ActionSymbol, number>;
+}
+
+/** A strategy expressed as a deterministic finite-state (Moore) machine. */
+export interface FsmStrategy {
+ kind: 'fsm';
+ name: string;
+ nStates: number;
+ start: number;
+ states: FsmState[];
+}
+
+/** A strategy expressed as a closure (e.g. a stochastic strategy using the seeded rng). */
+export interface FnStrategy<S = unknown> {
+ kind: 'fn';
+ name: string;
+ init: (rng: () => number) => S;
+ act: (state: S, rng: () => number) => ActionSymbol;
+ update: (state: S, own: ActionSymbol, opp: ActionSymbol, rng: () => number) => S;
+}
+
+export type Strategy = FsmStrategy | FnStrategy;
+
+/** A running instance of a strategy (Moore semantics: emit on state, transition on opponent). */
+export interface AgentInstance {
+ act(): ActionSymbol;
+ observe(own: ActionSymbol, opp: ActionSymbol): void;
+}
+
+export interface MatchResult {
+ game: string;
+ a: string;
+ b: string;
+ rounds: number;
+ seed: number;
+ cumulative: [number, number];
+ mean: [number, number];
+ history: Array<{ round: number; aAct: ActionSymbol; bAct: ActionSymbol; pA: number; pB: number }> | null;
+}
+
+export interface TournamentResult {
+ game: string;
+ rounds: number;
+ seed: number;
+ names: string[];
+ matrix: number[][];
+ meanVsField: number[];
+ ranking: Array<{ name: string; meanVsField: number }>;
+}
+
+export interface EvolutionResult {
+ best: FsmStrategy;
+ bestFitness: number;
+ generations: number;
+ curve: Array<{ gen: number; fitness: number; accepted: boolean; nStates: number }>;
+}
+
+export interface CoevolutionResult {
+ a: FsmStrategy;
+ b: FsmStrategy;
+ generations: number;
+ curve: Array<{ gen: number; side: string; payoffA: number }>;
+}
+
+export type RunKind = 'arena' | 'tournament' | 'evolution' | 'coevolution';
+
+/** A persisted, queryable record of a competition run (local stand-in for RuVector ADR-197). */
+export interface RunRecord {
+ runId: string;
+ kind: RunKind;
+ game: string;
+ seed: number;
+ createdAt: string;
+ summary: Record<string, unknown>;
+ artifact: unknown;
+}
+
+// ---------------------------------------------------------------------------
+// Zod input schemas β€” validated at MCP tool boundaries (Ruflo: validate at boundaries).
+// Numbers are coerced because MCP/CLI inputs may arrive as strings.
+// ---------------------------------------------------------------------------
+
+const gameKey = z.string().min(1);
+
+export const ArenaRunSchema = z.object({
+ game: gameKey.default('pd'),
+ a: z.string().default('tit-for-tat'),
+ b: z.string().default('always-defect'),
+ rounds: z.coerce.number().int().positive().max(100_000).default(200),
+ seed: z.coerce.number().int().default(1),
+ history: z.coerce.boolean().default(false),
+ persist: z.coerce.boolean().default(true),
+});
+
+export const TournamentRunSchema = z.object({
+ game: gameKey.default('pd'),
+ rounds: z.coerce.number().int().positive().max(100_000).default(200),
+ seed: z.coerce.number().int().default(1),
+ includeSelf: z.coerce.boolean().default(true),
+ persist: z.coerce.boolean().default(true),
+});
+
+export const EvolveRunSchema = z.object({
+ game: gameKey.default('pd'),
+ generations: z.coerce.number().int().positive().max(50_000).default(300),
+ seed: z.coerce.number().int().default(42),
+ rounds: z.coerce.number().int().positive().max(100_000).default(100),
+ startStates: z.coerce.number().int().min(1).max(32).default(2),
+ persist: z.coerce.boolean().default(true),
+});
+
+export const CoevolveRunSchema = z.object({
+ game: gameKey.default('pd'),
+ generations: z.coerce.number().int().positive().max(50_000).default(400),
+ seed: z.coerce.number().int().default(7),
+ rounds: z.coerce.number().int().positive().max(100_000).default(100),
+ startStates: z.coerce.number().int().min(1).max(32).default(2),
+ persist: z.coerce.boolean().default(true),
+});
+
+export const RunGetSchema = z.object({ runId: z.string().min(1) });
+export const RunListSchema = z.object({ limit: z.coerce.number().int().positive().max(1000).default(20) });
+
+export type ArenaRunInput = z.infer<typeof ArenaRunSchema>;
+export type TournamentRunInput = z.infer<typeof TournamentRunSchema>;
+export type EvolveRunInput = z.infer<typeof EvolveRunSchema>;
+export type CoevolveRunInput = z.infer<typeof CoevolveRunSchema>;
diff --git a/plugins/ruflo-arena/src/engine/arena.ts b/plugins/ruflo-arena/src/engine/arena.ts
new file mode 100644
index 0000000000..d024fa8a85
--- /dev/null
+++ b/plugins/ruflo-arena/src/engine/arena.ts
@@ -0,0 +1,54 @@
+// Arena β€” a single deterministic, replayable match between two strategies (Ruflo ADR-147).
+
+import { mulberry32, derive } from './rng.js';
+import { instantiate } from '../domain/strategies.js';
+import type { GameSpec, MatchResult, Strategy } from '../domain/types.js';
+
+export interface MatchOptions {
+ rounds?: number;
+ seed?: number;
+ history?: boolean;
+}
+
+export function runMatch(game: GameSpec, stratA: Strategy, stratB: Strategy, opts: MatchOptions = {}): MatchResult {
+ const { rounds = 200, seed = 1, history = false } = opts;
+ const agentA = instantiate(stratA, mulberry32(derive(seed, 1)));
+ const agentB = instantiate(stratB, mulberry32(derive(seed, 2)));
+
+ let sumA = 0;
+ let sumB = 0;
+ const log: MatchResult['history'] = history ? [] : null;
+
+ for (let r = 0; r < rounds; r++) {
+ const aAct = agentA.act();
+ const bAct = agentB.act();
+ const [pA, pB] = game.payoff(aAct, bAct);
+ sumA += pA;
+ sumB += pB;
+ if (log) log.push({ round: r, aAct, bAct, pA, pB });
+ agentA.observe(aAct, bAct);
+ agentB.observe(bAct, aAct);
+ }
+
+ return {
+ game: game.name,
+ a: stratA.name,
+ b: stratB.name,
+ rounds,
+ seed,
+ cumulative: [sumA, sumB],
+ mean: [sumA / rounds, sumB / rounds],
+ history: log,
+ };
+}
+
+/** Mean payoff to A when A plays B for `rounds` (used by tournaments / evolution). */
+export function meanPayoff(
+ game: GameSpec,
+ stratA: Strategy,
+ stratB: Strategy,
+ rounds: number,
+ seed: number,
+): number {
+ return runMatch(game, stratA, stratB, { rounds, seed }).mean[0];
+}
diff --git a/plugins/ruflo-arena/src/engine/evolution.ts b/plugins/ruflo-arena/src/engine/evolution.ts
new file mode 100644
index 0000000000..2addc78108
--- /dev/null
+++ b/plugins/ruflo-arena/src/engine/evolution.ts
@@ -0,0 +1,85 @@
+// Adaptive evolution (Ruflo ADR-148).
+// evolveVsField β€” hill-climb a strategy against a fixed roster (mutate -> keep if fitter).
+// coevolve β€” two strategies evolve against each other (Wolfram's mutual co-evolution).
+// Fitness curves expose the plateau -> breakthrough structure Wolfram highlights.
+
+import { mulberry32, derive } from './rng.js';
+import { meanPayoff } from './arena.js';
+import { randomFSM, mutate } from '../domain/strategies.js';
+import type { CoevolutionResult, EvolutionResult, FsmStrategy, GameSpec, Strategy } from '../domain/types.js';
+
+/** Fitness = mean-vs-field: average mean-payoff against every opponent in the roster. */
+export function fitnessVsField(
+ game: GameSpec,
+ fsm: FsmStrategy,
+ roster: Strategy[],
+ rounds: number,
+ evalSeed: number,
+): number {
+ let sum = 0;
+ for (const opp of roster) sum += meanPayoff(game, fsm, opp, rounds, evalSeed);
+ return sum / roster.length;
+}
+
+export interface EvolveOptions {
+ generations?: number;
+ seed?: number;
+ rounds?: number;
+ startStates?: number;
+}
+
+/** Hill-climb one FSM against a fixed field. Accept a mutation iff it does not lower fitness. */
+export function evolveVsField(game: GameSpec, roster: Strategy[], opts: EvolveOptions = {}): EvolutionResult {
+ const { generations = 300, seed = 42, rounds = 100, startStates = 2 } = opts;
+ const rng = mulberry32(derive(seed, 7));
+ const evalSeed = derive(seed, 99);
+
+ let cur = randomFSM(game, rng, startStates, 'evolved');
+ let curFit = fitnessVsField(game, cur, roster, rounds, evalSeed);
+ const curve: EvolutionResult['curve'] = [{ gen: 0, fitness: curFit, accepted: true, nStates: cur.nStates }];
+
+ for (let g = 1; g <= generations; g++) {
+ const cand = mutate(cur, game, rng);
+ const candFit = fitnessVsField(game, cand, roster, rounds, evalSeed);
+ const accepted = candFit >= curFit;
+ if (accepted) {
+ cur = cand;
+ curFit = candFit;
+ }
+ curve.push({ gen: g, fitness: curFit, accepted, nStates: cur.nStates });
+ }
+
+ return { best: cur, bestFitness: curFit, curve, generations };
+}
+
+export interface CoevolveOptions {
+ generations?: number;
+ seed?: number;
+ rounds?: number;
+ startStates?: number;
+}
+
+/** Mutual co-evolution: A and B take turns; each keeps a mutation iff it helps it head-to-head. */
+export function coevolve(game: GameSpec, opts: CoevolveOptions = {}): CoevolutionResult {
+ const { generations = 400, seed = 7, rounds = 100, startStates = 2 } = opts;
+ const rng = mulberry32(derive(seed, 11));
+ const evalSeed = derive(seed, 23);
+
+ let a = randomFSM(game, rng, startStates, 'A');
+ let b = randomFSM(game, rng, startStates, 'B');
+ const h2hA = () => meanPayoff(game, a, b, rounds, evalSeed);
+
+ const curve: CoevolutionResult['curve'] = [{ gen: 0, side: 'init', payoffA: h2hA() }];
+ for (let g = 1; g <= generations; g++) {
+ if (g % 2 === 1) {
+ const cand = mutate(a, game, rng);
+ if (meanPayoff(game, cand, b, rounds, evalSeed) >= meanPayoff(game, a, b, rounds, evalSeed)) a = cand;
+ } else {
+ const cand = mutate(b, game, rng);
+ // B wants to minimise A's payoff (equivalently maximise its own in a 2-player game)
+ if (meanPayoff(game, a, cand, rounds, evalSeed) <= meanPayoff(game, a, b, rounds, evalSeed)) b = cand;
+ }
+ curve.push({ gen: g, side: g % 2 === 1 ? 'A' : 'B', payoffA: h2hA() });
+ }
+ return { a, b, curve, generations };
+}
diff --git a/plugins/ruflo-arena/src/engine/index.ts b/plugins/ruflo-arena/src/engine/index.ts
new file mode 100644
index 0000000000..df59f72774
--- /dev/null
+++ b/plugins/ruflo-arena/src/engine/index.ts
@@ -0,0 +1,11 @@
+// Engine barrel β€” pure, side-effect-free competition primitives.
+export { mulberry32, randInt, choice, derive } from './rng.js';
+export { runMatch, meanPayoff, type MatchOptions } from './arena.js';
+export { runTournament, type TournamentOptions } from './tournament.js';
+export {
+ evolveVsField,
+ coevolve,
+ fitnessVsField,
+ type EvolveOptions,
+ type CoevolveOptions,
+} from './evolution.js';
diff --git a/plugins/ruflo-arena/src/engine/rng.ts b/plugins/ruflo-arena/src/engine/rng.ts
new file mode 100644
index 0000000000..9b26b10f4c
--- /dev/null
+++ b/plugins/ruflo-arena/src/engine/rng.ts
@@ -0,0 +1,27 @@
+// Deterministic, seedable PRNG (mulberry32). Same seed => same stream, so every run is
+// bit-for-bit reproducible β€” a precondition Wolfram stresses (a competition is only
+// meaningful if it can be re-run).
+
+export function mulberry32(seed: number): () => number {
+ let a = seed >>> 0;
+ return function next() {
+ a |= 0;
+ a = (a + 0x6d2b79f5) | 0;
+ let t = Math.imul(a ^ (a >>> 15), 1 | a);
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+}
+
+export function randInt(rng: () => number, n: number): number {
+ return Math.floor(rng() * n);
+}
+
+export function choice<T>(rng: () => number, arr: readonly T[]): T {
+ return arr[randInt(rng, arr.length)];
+}
+
+/** Derive an independent stream seed from a base seed (keeps player streams uncorrelated). */
+export function derive(seed: number, salt: number): number {
+ return (Math.imul(seed >>> 0, 0x9e3779b1) ^ (salt >>> 0)) >>> 0;
+}
diff --git a/plugins/ruflo-arena/src/engine/tournament.ts b/plugins/ruflo-arena/src/engine/tournament.ts
new file mode 100644
index 0000000000..873fbc4944
--- /dev/null
+++ b/plugins/ruflo-arena/src/engine/tournament.ts
@@ -0,0 +1,41 @@
+// Tournament β€” round-robin over a roster producing Wolfram's "competitive array":
+// the matrix of mean payoffs for every (strategy, opponent) pair (Ruflo ADR-147).
+
+import { meanPayoff } from './arena.js';
+import type { GameSpec, Strategy, TournamentResult } from '../domain/types.js';
+
+export interface TournamentOptions {
+ rounds?: number;
+ seed?: number;
+ includeSelf?: boolean;
+}
+
+export function runTournament(game: GameSpec, roster: Strategy[], opts: TournamentOptions = {}): TournamentResult {
+ const { rounds = 200, seed = 1, includeSelf = true } = opts;
+ const names = roster.map((s) => s.name);
+ const n = roster.length;
+
+ const matrix: number[][] = Array.from({ length: n }, () => new Array<number>(n).fill(0));
+ for (let i = 0; i < n; i++) {
+ for (let j = 0; j < n; j++) {
+ matrix[i][j] = meanPayoff(game, roster[i], roster[j], rounds, seed);
+ }
+ }
+
+ const meanVsField = matrix.map((row, i) => {
+ let sum = 0;
+ let count = 0;
+ for (let j = 0; j < n; j++) {
+ if (!includeSelf && i === j) continue;
+ sum += row[j];
+ count += 1;
+ }
+ return count ? sum / count : 0;
+ });
+
+ const ranking = names
+ .map((name, i) => ({ name, meanVsField: meanVsField[i] }))
+ .sort((x, y) => y.meanVsField - x.meanVsField);
+
+ return { game: game.name, rounds, seed, names, matrix, meanVsField, ranking };
+}
diff --git a/plugins/ruflo-arena/src/index.ts b/plugins/ruflo-arena/src/index.ts
new file mode 100644
index 0000000000..f09f9c1a85
--- /dev/null
+++ b/plugins/ruflo-arena/src/index.ts
@@ -0,0 +1,55 @@
+/**
+ * ruflo-arena β€” Competitive ruliology for Ruflo swarms (ADR-147/148).
+ *
+ * Strategies-as-programs compete under payoff games; tournaments produce Wolfram-style
+ * competitive arrays; hill-climb and mutual co-evolution discover winners empirically.
+ * The presentation/dashboard layer lives in Ruflo (ADR-150); the data/intelligence layer
+ * is RuVector's (ADR-196/197). This plugin is execution + a local data stand-in.
+ */
+
+// Domain
+export * from './domain/types.js';
+export { getGame, makeGame, prisonersDilemma, matchOrNot, GAMES } from './domain/games.js';
+export {
+ instantiate,
+ classicRoster,
+ findStrategy,
+ randomFSM,
+ mutate,
+ constant,
+ copyOpponent,
+ antiCopy,
+ alternate,
+ grim,
+ pavlov,
+ random,
+} from './domain/strategies.js';
+
+// Engine
+export * from './engine/index.js';
+
+// Persistence
+export {
+ FileRunStore,
+ InMemoryRunStore,
+ makeRecord,
+ newRunId,
+ agentdbRecord,
+ type RunStore,
+} from './persistence/run-store.js';
+
+// Reporting
+export {
+ competitiveArrayTable,
+ heatmap,
+ rankingTable,
+ sparkline,
+ describeFSM,
+ evolutionSummary,
+} from './report/render.js';
+
+// MCP tools
+export { arenaTools, createArenaTools, schemas, type MCPTool } from './mcp-tools/index.js';
+
+import { arenaTools } from './mcp-tools/index.js';
+export default { tools: arenaTools };
diff --git a/plugins/ruflo-arena/src/mcp-tools/index.ts b/plugins/ruflo-arena/src/mcp-tools/index.ts
new file mode 100644
index 0000000000..a478392a8b
--- /dev/null
+++ b/plugins/ruflo-arena/src/mcp-tools/index.ts
@@ -0,0 +1,255 @@
+// MCP tools for ruflo-arena (Ruflo ADR-147/148). Tool shape matches the Ruflo convention:
+// { name, description, category, inputSchema, handler } with Zod validation at the boundary
+// and a `{ success, result | error }` return envelope.
+
+import { z } from 'zod';
+import {
+ ArenaRunSchema,
+ CoevolveRunSchema,
+ EvolveRunSchema,
+ RunGetSchema,
+ RunListSchema,
+ TournamentRunSchema,
+} from '../domain/types.js';
+import { getGame } from '../domain/games.js';
+import { classicRoster, findStrategy } from '../domain/strategies.js';
+import { runMatch } from '../engine/arena.js';
+import { runTournament } from '../engine/tournament.js';
+import { coevolve, evolveVsField } from '../engine/evolution.js';
+import { competitiveArrayTable, evolutionSummary, rankingTable, sparkline } from '../report/render.js';
+import {
+ FileRunStore,
+ agentdbRecord,
+ makeRecord,
+ type RunStore,
+} from '../persistence/run-store.js';
+
+export interface MCPTool {
+ name: string;
+ description: string;
+ category: string;
+ inputSchema: {
+ type: 'object';
+ properties: Record<string, unknown>;
+ required?: string[];
+ };
+ handler: (input: Record<string, unknown>) => Promise<unknown>;
+}
+
+const ok = (result: unknown) => ({ success: true as const, result });
+const fail = (err: unknown) => ({
+ success: false as const,
+ error: { message: err instanceof Error ? err.message : String(err) },
+});
+
+const num = (description: string, def?: number) => ({ type: 'number', description: def === undefined ? description : `${description} (default ${def})` });
+const str = (description: string, def?: string) => ({ type: 'string', description: def === undefined ? description : `${description} (default "${def}")` });
+const bool = (description: string, def: boolean) => ({ type: 'boolean', description: `${description} (default ${def})` });
+
+/** Build the tool set against a given RunStore (inject InMemoryRunStore in tests). */
+export function createArenaTools(store: RunStore): MCPTool[] {
+ return [
+ {
+ name: 'arena/run',
+ description:
+ 'Run a single deterministic match between two named strategies under a payoff game. Returns cumulative and mean payoffs; reproducible under --seed.',
+ category: 'arena',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ game: str('Game key: pd | prisoners-dilemma | mon | match-or-not', 'pd'),
+ a: str('Strategy A name (from the classic roster)', 'tit-for-tat'),
+ b: str('Strategy B name', 'always-defect'),
+ rounds: num('Number of rounds', 200),
+ seed: num('PRNG seed for reproducibility', 1),
+ history: bool('Include per-round move log', false),
+ persist: bool('Persist the run via the RunStore', true),
+ },
+ },
+ handler: async (input) => {
+ try {
+ const args = ArenaRunSchema.parse(input);
+ const game = getGame(args.game);
+ const a = findStrategy(game, args.a);
+ const b = findStrategy(game, args.b);
+ const match = runMatch(game, a, b, { rounds: args.rounds, seed: args.seed, history: args.history });
+ const summary = { a: match.a, b: match.b, rounds: match.rounds, mean: match.mean, cumulative: match.cumulative };
+ if (!args.persist) return ok({ ...summary, game: game.name, seed: args.seed });
+ const record = makeRecord('arena', game.name, args.seed, summary, match);
+ await store.save(record);
+ return ok({ runId: record.runId, game: game.name, seed: args.seed, ...summary, agentdb: agentdbRecord(record) });
+ } catch (err) {
+ return fail(err);
+ }
+ },
+ },
+ {
+ name: 'tournament/run',
+ description:
+ "Round-robin tournament over the classic roster, producing Wolfram's competitive array (mean-payoff matrix) and a mean-vs-field ranking.",
+ category: 'arena',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ game: str('Game key', 'pd'),
+ rounds: num('Rounds per match', 200),
+ seed: num('PRNG seed', 1),
+ includeSelf: bool('Include self-play (diagonal) in mean-vs-field', true),
+ persist: bool('Persist the run', true),
+ },
+ },
+ handler: async (input) => {
+ try {
+ const args = TournamentRunSchema.parse(input);
+ const game = getGame(args.game);
+ const t = runTournament(game, classicRoster(game), {
+ rounds: args.rounds,
+ seed: args.seed,
+ includeSelf: args.includeSelf,
+ });
+ const summary = { winner: t.ranking[0], ranking: t.ranking, names: t.names };
+ const result = {
+ game: t.game,
+ rounds: t.rounds,
+ seed: t.seed,
+ ranking: t.ranking,
+ matrix: t.matrix,
+ names: t.names,
+ tables: { competitiveArray: competitiveArrayTable(t), ranking: rankingTable(t) },
+ };
+ if (!args.persist) return ok(result);
+ const record = makeRecord('tournament', game.name, args.seed, summary, t);
+ await store.save(record);
+ return ok({ runId: record.runId, ...result, agentdb: agentdbRecord(record) });
+ } catch (err) {
+ return fail(err);
+ }
+ },
+ },
+ {
+ name: 'evolve/run',
+ description:
+ 'Hill-climb (mutate -> keep-if-fitter) an FSM strategy against the classic field. Returns the evolved program, its fitness, and the fitness curve (plateau -> breakthrough structure).',
+ category: 'arena',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ game: str('Game key', 'pd'),
+ generations: num('Number of generations', 300),
+ seed: num('PRNG seed', 42),
+ rounds: num('Rounds per evaluation match', 100),
+ startStates: num('Initial FSM state count', 2),
+ persist: bool('Persist the run', true),
+ },
+ },
+ handler: async (input) => {
+ try {
+ const args = EvolveRunSchema.parse(input);
+ const game = getGame(args.game);
+ const r = evolveVsField(game, classicRoster(game), {
+ generations: args.generations,
+ seed: args.seed,
+ rounds: args.rounds,
+ startStates: args.startStates,
+ });
+ const summary = { ...evolutionSummary(r), generations: r.generations };
+ const result = {
+ game: game.name,
+ ...summary,
+ best: r.best,
+ sparkline: sparkline(r.curve.map((c) => c.fitness)),
+ };
+ if (!args.persist) return ok(result);
+ const record = makeRecord('evolution', game.name, args.seed, summary, r);
+ await store.save(record);
+ return ok({ runId: record.runId, ...result, agentdb: agentdbRecord(record) });
+ } catch (err) {
+ return fail(err);
+ }
+ },
+ },
+ {
+ name: 'coevolve/run',
+ description:
+ "Mutual co-evolution: two FSM strategies evolve against each other on alternating generations (Wolfram's arms race). Returns the arms-race payoff trace.",
+ category: 'arena',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ game: str('Game key', 'pd'),
+ generations: num('Number of generations', 400),
+ seed: num('PRNG seed', 7),
+ rounds: num('Rounds per evaluation match', 100),
+ startStates: num('Initial FSM state count', 2),
+ persist: bool('Persist the run', true),
+ },
+ },
+ handler: async (input) => {
+ try {
+ const args = CoevolveRunSchema.parse(input);
+ const game = getGame(args.game);
+ const r = coevolve(game, {
+ generations: args.generations,
+ seed: args.seed,
+ rounds: args.rounds,
+ startStates: args.startStates,
+ });
+ const payoffs = r.curve.map((c) => c.payoffA);
+ const summary = {
+ generations: r.generations,
+ payoffRange: [Math.min(...payoffs), Math.max(...payoffs)] as [number, number],
+ finalPayoffA: payoffs[payoffs.length - 1],
+ };
+ const result = { game: game.name, ...summary, sparkline: sparkline(payoffs) };
+ if (!args.persist) return ok(result);
+ const record = makeRecord('coevolution', game.name, args.seed, summary, r);
+ await store.save(record);
+ return ok({ runId: record.runId, ...result, agentdb: agentdbRecord(record) });
+ } catch (err) {
+ return fail(err);
+ }
+ },
+ },
+ {
+ name: 'run/get',
+ description: 'Fetch a persisted run record by runId.',
+ category: 'arena',
+ inputSchema: { type: 'object', properties: { runId: str('Run identifier') }, required: ['runId'] },
+ handler: async (input) => {
+ try {
+ const { runId } = RunGetSchema.parse(input);
+ const record = await store.get(runId);
+ return record ? ok(record) : fail(`run "${runId}" not found`);
+ } catch (err) {
+ return fail(err);
+ }
+ },
+ },
+ {
+ name: 'run/list',
+ description: 'List recent persisted run records (most recent first).',
+ category: 'arena',
+ inputSchema: { type: 'object', properties: { limit: num('Max records', 20) } },
+ handler: async (input) => {
+ try {
+ const { limit } = RunListSchema.parse(input);
+ const records = await store.list(limit);
+ return ok(records.map((r) => ({ runId: r.runId, kind: r.kind, game: r.game, seed: r.seed, createdAt: r.createdAt, summary: r.summary })));
+ } catch (err) {
+ return fail(err);
+ }
+ },
+ },
+ ];
+}
+
+/** Default tool set, persisting to `.ruflo/arena/` on disk. */
+export const arenaTools: MCPTool[] = createArenaTools(new FileRunStore());
+
+// Re-export Zod schemas so hosts can introspect/validate independently.
+export const schemas = {
+ arena: ArenaRunSchema,
+ tournament: TournamentRunSchema,
+ evolve: EvolveRunSchema,
+ coevolve: CoevolveRunSchema,
+} satisfies Record<string, z.ZodTypeAny>;
diff --git a/plugins/ruflo-arena/src/persistence/run-store.ts b/plugins/ruflo-arena/src/persistence/run-store.ts
new file mode 100644
index 0000000000..d0313eeca5
--- /dev/null
+++ b/plugins/ruflo-arena/src/persistence/run-store.ts
@@ -0,0 +1,117 @@
+// Run persistence. A competition run is a reproducible artifact (Ruflo ADR-147; the local
+// stand-in for RuVector ADR-197's payoff/fitness/evolution storage).
+//
+// Two backends ship here:
+// - FileRunStore β€” writes full artifacts to `.ruflo/arena/<runId>.json` (exact replay).
+// - InMemoryRunStore β€” for tests / ephemeral use.
+// AgentDB persistence is handled at the COMMAND layer (Ruflo convention: plugin TS persists
+// artifacts; commands call `mcp__claude-flow__memory_store` with `agentdbRecord(run)`).
+
+import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises';
+import { join } from 'node:path';
+import type { RunKind, RunRecord } from '../domain/types.js';
+
+export interface RunStore {
+ save(record: RunRecord): Promise<RunRecord>;
+ get(runId: string): Promise<RunRecord | null>;
+ list(limit?: number): Promise<RunRecord[]>;
+}
+
+let counter = 0;
+
+/** Generate a run id. Uses crypto.randomUUID when available, else a monotonic fallback. */
+export function newRunId(kind: RunKind): string {
+ const uuid =
+ typeof globalThis.crypto?.randomUUID === 'function'
+ ? globalThis.crypto.randomUUID().slice(0, 8)
+ : `${(counter++).toString(36)}${Math.floor(Math.random() * 1e6).toString(36)}`;
+ return `${kind}-${uuid}`;
+}
+
+export function makeRecord(
+ kind: RunKind,
+ game: string,
+ seed: number,
+ summary: Record<string, unknown>,
+ artifact: unknown,
+ runId = newRunId(kind),
+): RunRecord {
+ return { runId, kind, game, seed, createdAt: new Date().toISOString(), summary, artifact };
+}
+
+export class InMemoryRunStore implements RunStore {
+ private readonly records = new Map<string, RunRecord>();
+ private readonly order: string[] = [];
+
+ async save(record: RunRecord): Promise<RunRecord> {
+ this.records.set(record.runId, record);
+ this.order.unshift(record.runId);
+ return record;
+ }
+ async get(runId: string): Promise<RunRecord | null> {
+ return this.records.get(runId) ?? null;
+ }
+ async list(limit = 20): Promise<RunRecord[]> {
+ return this.order.slice(0, limit).map((id) => this.records.get(id)!).filter(Boolean);
+ }
+}
+
+export class FileRunStore implements RunStore {
+ constructor(private readonly baseDir = join(process.cwd(), '.ruflo', 'arena')) {}
+
+ async save(record: RunRecord): Promise<RunRecord> {
+ await mkdir(this.baseDir, { recursive: true });
+ await writeFile(join(this.baseDir, `${record.runId}.json`), JSON.stringify(record, null, 2), 'utf8');
+ return record;
+ }
+
+ async get(runId: string): Promise<RunRecord | null> {
+ try {
+ const raw = await readFile(join(this.baseDir, `${runId}.json`), 'utf8');
+ return JSON.parse(raw) as RunRecord;
+ } catch {
+ return null;
+ }
+ }
+
+ async list(limit = 20): Promise<RunRecord[]> {
+ let files: string[];
+ try {
+ files = (await readdir(this.baseDir)).filter((f) => f.endsWith('.json'));
+ } catch {
+ return [];
+ }
+ const records = await Promise.all(
+ files.map(async (f) => {
+ try {
+ return JSON.parse(await readFile(join(this.baseDir, f), 'utf8')) as RunRecord;
+ } catch {
+ return null;
+ }
+ }),
+ );
+ return records
+ .filter((r): r is RunRecord => r !== null)
+ .sort((x, y) => y.createdAt.localeCompare(x.createdAt))
+ .slice(0, limit);
+ }
+}
+
+/**
+ * Shape a run for AgentDB persistence via `mcp__claude-flow__memory_store`.
+ * The command layer calls the MCP tool with this payload so runs become semantically
+ * searchable ("tournaments where grim dominated") and feed the RuVector data layer later.
+ */
+export function agentdbRecord(record: RunRecord): {
+ namespace: string;
+ key: string;
+ value: string;
+ tags: string[];
+} {
+ return {
+ namespace: 'arena',
+ key: record.runId,
+ value: JSON.stringify({ kind: record.kind, game: record.game, seed: record.seed, ...record.summary }),
+ tags: ['ruliology', 'competition', record.kind, record.game],
+ };
+}
diff --git a/plugins/ruflo-arena/src/report/render.ts b/plugins/ruflo-arena/src/report/render.ts
new file mode 100644
index 0000000000..d68a4fc782
--- /dev/null
+++ b/plugins/ruflo-arena/src/report/render.ts
@@ -0,0 +1,80 @@
+// Text rendering of results. In the full system these surfaces become Ruflo dashboard
+// panels fed by RuVector read-models (ADR-149/198/202). Here we render to text so the
+// plugin is observable with zero UI dependencies.
+
+import type { EvolutionResult, FsmStrategy, TournamentResult } from '../domain/types.js';
+
+const SHADES = ' .:-=+*#%@'; // low -> high
+
+function pad(s: unknown, w: number): string {
+ const str = String(s);
+ return str.length >= w ? str.slice(0, w) : str + ' '.repeat(w - str.length);
+}
+function padL(s: unknown, w: number): string {
+ const str = String(s);
+ return str.length >= w ? str.slice(0, w) : ' '.repeat(w - str.length) + str;
+}
+
+function shadeOf(v: number, min: number, span: number): string {
+ return SHADES[Math.min(SHADES.length - 1, Math.floor(((v - min) / span) * (SHADES.length - 1)))];
+}
+
+/** The competitive array (mean-payoff matrix) as an aligned table. */
+export function competitiveArrayTable(t: TournamentResult): string {
+ const short = t.names.map((n) => n.slice(0, 6));
+ const w = 7;
+ const head = pad('', 14) + short.map((n) => padL(n, w)).join('');
+ const rows = t.matrix.map((row, i) => {
+ const cells = row.map((v) => padL(v.toFixed(2), w)).join('');
+ return pad(t.names[i].slice(0, 13), 14) + cells;
+ });
+ return [head, ...rows].join('\n');
+}
+
+/** ASCII heatmap of a matrix (auto-scaled to its min/max). */
+export function heatmap(matrix: number[][]): string {
+ const flat = matrix.flat();
+ const min = Math.min(...flat);
+ const span = Math.max(...flat) - min || 1;
+ return matrix.map((row) => row.map((v) => shadeOf(v, min, span).repeat(2)).join('')).join('\n');
+}
+
+export function rankingTable(t: TournamentResult): string {
+ return t.ranking
+ .map((r, i) => `${padL(i + 1, 3)}. ${pad(r.name, 22)} ${r.meanVsField.toFixed(3)}`)
+ .join('\n');
+}
+
+/** One-line sparkline of a numeric series. */
+export function sparkline(values: number[]): string {
+ const min = Math.min(...values);
+ const span = Math.max(...values) - min || 1;
+ return values.map((v) => shadeOf(v, min, span)).join('');
+}
+
+/** Compact description of an FSM strategy. */
+export function describeFSM(fsm: FsmStrategy): string {
+ const lines = [`FSM "${fsm.name}" states=${fsm.nStates} start=${fsm.start}`];
+ fsm.states.forEach((s, i) => {
+ const trans = Object.entries(s.next)
+ .map(([k, v]) => `${k}->${v}`)
+ .join(' ');
+ lines.push(` s${i}: out=${s.action} [${trans}]${i === fsm.start ? ' <= start' : ''}`);
+ });
+ return lines.join('\n');
+}
+
+/** Headline numbers for an evolution run (used in summaries). */
+export function evolutionSummary(r: EvolutionResult): {
+ startFitness: number;
+ finalFitness: number;
+ acceptedMutations: number;
+ states: number;
+} {
+ return {
+ startFitness: r.curve[0].fitness,
+ finalFitness: r.bestFitness,
+ acceptedMutations: r.curve.filter((c) => c.accepted && c.gen > 0).length,
+ states: r.best.nStates,
+ };
+}
diff --git a/plugins/ruflo-arena/tests/evolution.test.ts b/plugins/ruflo-arena/tests/evolution.test.ts
new file mode 100644
index 0000000000..0492b0da40
--- /dev/null
+++ b/plugins/ruflo-arena/tests/evolution.test.ts
@@ -0,0 +1,31 @@
+import { describe, it, expect } from 'vitest';
+import { prisonersDilemma as PD } from '../src/domain/games.js';
+import { classicRoster } from '../src/domain/strategies.js';
+import { coevolve, evolveVsField } from '../src/engine/evolution.js';
+
+describe('evolution', () => {
+ it('hill-climb fitness is monotonic non-decreasing (best-so-far)', () => {
+ const r = evolveVsField(PD, classicRoster(PD), { generations: 200, seed: 42 });
+ for (let i = 1; i < r.curve.length; i++) {
+ expect(r.curve[i].fitness).toBeGreaterThanOrEqual(r.curve[i - 1].fitness - 1e-9);
+ }
+ });
+
+ it('improves on its random starting point', () => {
+ const r = evolveVsField(PD, classicRoster(PD), { generations: 300, seed: 42 });
+ expect(r.bestFitness).toBeGreaterThanOrEqual(r.curve[0].fitness);
+ });
+
+ it('is deterministic under a fixed seed', () => {
+ const a = evolveVsField(PD, classicRoster(PD), { generations: 150, seed: 7 });
+ const b = evolveVsField(PD, classicRoster(PD), { generations: 150, seed: 7 });
+ expect(a.bestFitness).toBe(b.bestFitness);
+ expect(a.best).toEqual(b.best);
+ });
+
+ it('co-evolution records a finite arms-race trace', () => {
+ const r = coevolve(PD, { generations: 200, seed: 7 });
+ expect(r.curve.length).toBe(201);
+ for (const pt of r.curve) expect(Number.isFinite(pt.payoffA)).toBe(true);
+ });
+});
diff --git a/plugins/ruflo-arena/tests/games-arena.test.ts b/plugins/ruflo-arena/tests/games-arena.test.ts
new file mode 100644
index 0000000000..fedf3bcddd
--- /dev/null
+++ b/plugins/ruflo-arena/tests/games-arena.test.ts
@@ -0,0 +1,54 @@
+import { describe, it, expect } from 'vitest';
+import { prisonersDilemma as PD, matchOrNot as MON } from '../src/domain/games.js';
+import { copyOpponent, constant, pavlov } from '../src/domain/strategies.js';
+import { runMatch } from '../src/engine/arena.js';
+
+describe('games', () => {
+ it('PD uses the classic R/T/S/P payoffs', () => {
+ expect(PD.payoff('C', 'C')).toEqual([3, 3]);
+ expect(PD.payoff('D', 'C')).toEqual([5, 0]);
+ expect(PD.payoff('C', 'D')).toEqual([0, 5]);
+ expect(PD.payoff('D', 'D')).toEqual([1, 1]);
+ });
+
+ it('match-or-not is zero-sum', () => {
+ for (const a of MON.actions)
+ for (const b of MON.actions) {
+ const [pa, pb] = MON.payoff(a, b);
+ expect(pa + pb).toBe(0);
+ }
+ });
+});
+
+describe('arena', () => {
+ it('tit-for-tat vs tit-for-tat fully cooperates (mean 3)', () => {
+ const tft = copyOpponent(PD.actions, 0);
+ const r = runMatch(PD, tft, tft, { rounds: 200, seed: 1 });
+ expect(r.mean).toEqual([3, 3]);
+ });
+
+ it('always-cooperate is exploited by always-defect', () => {
+ const allC = constant(PD.actions, 0);
+ const allD = constant(PD.actions, 1);
+ expect(runMatch(PD, allC, allD, { rounds: 100 }).mean[0]).toBe(0);
+ expect(runMatch(PD, allD, allC, { rounds: 100 }).mean[0]).toBe(5);
+ });
+
+ it('tit-for-tat limits losses against always-defect (~1)', () => {
+ const m = runMatch(PD, copyOpponent(PD.actions, 0), constant(PD.actions, 1), { rounds: 200 }).mean[0];
+ expect(m).toBeGreaterThan(0.9);
+ expect(m).toBeLessThanOrEqual(1.0);
+ });
+
+ it('pavlov cooperates with itself', () => {
+ const p = pavlov(PD.actions);
+ expect(runMatch(PD, p, p, { rounds: 100 }).mean[0]).toBe(3);
+ });
+
+ it('is deterministic under a fixed seed', () => {
+ const tft = copyOpponent(PD.actions, 0);
+ const a = runMatch(PD, tft, tft, { rounds: 50, seed: 123, history: true });
+ const b = runMatch(PD, tft, tft, { rounds: 50, seed: 123, history: true });
+ expect(a.history).toEqual(b.history);
+ });
+});
diff --git a/plugins/ruflo-arena/tests/mcp-tools.test.ts b/plugins/ruflo-arena/tests/mcp-tools.test.ts
new file mode 100644
index 0000000000..d4413b1ef9
--- /dev/null
+++ b/plugins/ruflo-arena/tests/mcp-tools.test.ts
@@ -0,0 +1,92 @@
+import { describe, it, expect, beforeEach } from 'vitest';
+import { createArenaTools, type MCPTool } from '../src/mcp-tools/index.js';
+import { InMemoryRunStore } from '../src/persistence/run-store.js';
+
+type Envelope = { success: boolean; result?: any; error?: { message: string } };
+
+let store: InMemoryRunStore;
+let tools: MCPTool[];
+const tool = (name: string) => tools.find((t) => t.name === name)!;
+const call = (name: string, input: Record<string, unknown>) => tool(name).handler(input) as Promise<Envelope>;
+
+beforeEach(() => {
+ store = new InMemoryRunStore();
+ tools = createArenaTools(store);
+});
+
+describe('mcp tool surface', () => {
+ it('exposes the expected tools under the arena category', () => {
+ expect(tools.map((t) => t.name)).toEqual([
+ 'arena/run',
+ 'tournament/run',
+ 'evolve/run',
+ 'coevolve/run',
+ 'run/get',
+ 'run/list',
+ ]);
+ for (const t of tools) {
+ expect(t.category).toBe('arena');
+ expect(t.inputSchema.type).toBe('object');
+ expect(typeof t.handler).toBe('function');
+ }
+ });
+});
+
+describe('arena/run', () => {
+ it('runs a match and persists it', async () => {
+ const r = await call('arena/run', { game: 'pd', a: 'tit-for-tat', b: 'tit-for-tat', rounds: 50 });
+ expect(r.success).toBe(true);
+ expect(r.result.mean).toEqual([3, 3]);
+ expect(r.result.runId).toMatch(/^arena-/);
+ expect(r.result.agentdb.namespace).toBe('arena');
+ expect(await store.get(r.result.runId)).not.toBeNull();
+ });
+
+ it('coerces string numeric inputs (MCP/CLI friendliness)', async () => {
+ const r = await call('arena/run', { game: 'pd', a: 'tit-for-tat', b: 'always-defect', rounds: '200', seed: '1' });
+ expect(r.success).toBe(true);
+ expect(r.result.mean[0]).toBeGreaterThan(0.9);
+ });
+
+ it('fails cleanly on an unknown game or strategy', async () => {
+ expect((await call('arena/run', { game: 'nope' })).success).toBe(false);
+ expect((await call('arena/run', { game: 'pd', a: 'does-not-exist' })).success).toBe(false);
+ });
+});
+
+describe('tournament/run', () => {
+ it('returns a competitive array and ranking, and persists', async () => {
+ const r = await call('tournament/run', { game: 'pd', rounds: 100 });
+ expect(r.success).toBe(true);
+ expect(r.result.ranking.length).toBe(8);
+ expect(r.result.matrix.length).toBe(8);
+ expect(r.result.tables.competitiveArray).toContain('tit-fo');
+ expect(await store.get(r.result.runId)).not.toBeNull();
+ });
+});
+
+describe('evolve/run', () => {
+ it('reports a non-decreasing improvement and an evolved program', async () => {
+ const r = await call('evolve/run', { game: 'pd', generations: 150, seed: 42 });
+ expect(r.success).toBe(true);
+ expect(r.result.finalFitness).toBeGreaterThanOrEqual(r.result.startFitness);
+ expect(r.result.best.kind).toBe('fsm');
+ });
+});
+
+describe('run persistence tools', () => {
+ it('lists and fetches persisted runs', async () => {
+ const a = await call('arena/run', { game: 'pd' });
+ await call('tournament/run', { game: 'pd', rounds: 50 });
+ const list = await call('run/list', { limit: 10 });
+ expect(list.success).toBe(true);
+ expect(list.result.length).toBe(2);
+ const got = await call('run/get', { runId: a.result.runId });
+ expect(got.success).toBe(true);
+ expect(got.result.runId).toBe(a.result.runId);
+ });
+
+ it('run/get fails for a missing id', async () => {
+ expect((await call('run/get', { runId: 'nope-123' })).success).toBe(false);
+ });
+});
diff --git a/plugins/ruflo-arena/tests/tournament.test.ts b/plugins/ruflo-arena/tests/tournament.test.ts
new file mode 100644
index 0000000000..4dd8c29699
--- /dev/null
+++ b/plugins/ruflo-arena/tests/tournament.test.ts
@@ -0,0 +1,37 @@
+import { describe, it, expect } from 'vitest';
+import { prisonersDilemma as PD } from '../src/domain/games.js';
+import { classicRoster } from '../src/domain/strategies.js';
+import { runTournament } from '../src/engine/tournament.js';
+
+describe('tournament', () => {
+ it('produces a square competitive array consistent with the roster', () => {
+ const roster = classicRoster(PD);
+ const t = runTournament(PD, roster, { rounds: 200, seed: 1 });
+ expect(t.matrix.length).toBe(roster.length);
+ for (const row of t.matrix) expect(row.length).toBe(roster.length);
+ expect(t.meanVsField.length).toBe(roster.length);
+ expect(t.ranking.length).toBe(roster.length);
+ });
+
+ it('always-defect is pairwise-unbeatable in PD (dominance)', () => {
+ const t = runTournament(PD, classicRoster(PD), { rounds: 200, seed: 1 });
+ const allD = t.names.indexOf('always-defect');
+ expect(allD).toBeGreaterThanOrEqual(0);
+ for (let j = 0; j < t.names.length; j++) {
+ expect(t.matrix[allD][j]).toBeGreaterThanOrEqual(t.matrix[j][allD] - 1e-9);
+ }
+ });
+
+ it('ranking is sorted by mean-vs-field descending', () => {
+ const t = runTournament(PD, classicRoster(PD), { rounds: 200, seed: 1 });
+ for (let i = 1; i < t.ranking.length; i++) {
+ expect(t.ranking[i - 1].meanVsField).toBeGreaterThanOrEqual(t.ranking[i].meanVsField);
+ }
+ });
+
+ it('is reproducible under a fixed seed', () => {
+ const a = runTournament(PD, classicRoster(PD), { rounds: 100, seed: 5 });
+ const b = runTournament(PD, classicRoster(PD), { rounds: 100, seed: 5 });
+ expect(a.matrix).toEqual(b.matrix);
+ });
+});
diff --git a/plugins/ruflo-arena/tsconfig.json b/plugins/ruflo-arena/tsconfig.json
new file mode 100644
index 0000000000..c0809a56a7
--- /dev/null
+++ b/plugins/ruflo-arena/tsconfig.json
@@ -0,0 +1,21 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "NodeNext",
+ "moduleResolution": "NodeNext",
+ "lib": ["ES2022"],
+ "outDir": "./dist",
+ "rootDir": "./src",
+ "strict": true,
+ "esModuleInterop": true,
+ "skipLibCheck": true,
+ "forceConsistentCasingInFileNames": true,
+ "declaration": true,
+ "declarationMap": true,
+ "sourceMap": true,
+ "resolveJsonModule": true,
+ "isolatedModules": true
+ },
+ "include": ["src/**/*"],
+ "exclude": ["node_modules", "dist", "tests"]
+}
diff --git a/plugins/ruflo-arena/vitest.config.ts b/plugins/ruflo-arena/vitest.config.ts
new file mode 100644
index 0000000000..369787f6f5
--- /dev/null
+++ b/plugins/ruflo-arena/vitest.config.ts
@@ -0,0 +1,9 @@
+import { defineConfig } from 'vitest/config';
+
+export default defineConfig({
+ test: {
+ include: ['tests/**/*.test.ts'],
+ environment: 'node',
+ globals: false,
+ },
+});