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(test): real-binary test tier for ruflo mods (ADR-504) (#4589)

rUv5a008a150a1a
diff --git a/.github/workflows/mod-guidance.yml b/.github/workflows/mod-guidance.yml
index 7c32e851f8..2b39fecdad 100644
--- a/.github/workflows/mod-guidance.yml
+++ b/.github/workflows/mod-guidance.yml
@@ -32,5 +32,46 @@ jobs:
working-directory: v3/@claude-flow/cli
run: ../../../node_modules/.bin/vitest run __tests__/mods/ --exclude '**/mods-cli-bin.test.ts'
+ mods-real-binary:
+ # ADR-504: the real Claude Code binary, headless, against a scripted mock
+ # Anthropic Messages server (no secret, no paid model). It catches what the
+ # harness can only imitate, such as #4485 (a hooks module the real loader
+ # refuses with no error anywhere). The pin moves only by PR, so an engine
+ # change that breaks a contract is caught on the bump, not in users' sessions.
+ name: Real-binary mod contracts (pinned Claude Code)
+ runs-on: ubuntu-latest
+ timeout-minutes: 15
+ env:
+ CLAUDE_CODE_VERSION: '2.1.289'
+ steps:
+ - uses: actions/checkout@v4
+ with:
+ persist-credentials: false
+ - uses: actions/setup-node@v4
+ with:
+ node-version: '20'
+ cache: npm
+ - name: Install locked dependencies without lifecycle scripts
+ run: npm ci --ignore-scripts --legacy-peer-deps
+ - name: Install the pinned Claude Code binary
+ run: npm install --global "@anthropic-ai/claude-code@${CLAUDE_CODE_VERSION}"
+ - name: Check the binary starts and is the pinned version
+ run: |
+ set -euo pipefail
+ if ! actual="$(claude --version)"; then
+ echo "::error::claude --version failed: the pinned Claude Code binary did not start"
+ exit 1
+ fi
+ echo "claude --version: ${actual}"
+ if [ "${actual%% *}" != "${CLAUDE_CODE_VERSION}" ]; then
+ echo "::error::expected Claude Code ${CLAUDE_CODE_VERSION}, got ${actual}"
+ exit 1
+ fi
+ - name: Run the real-binary contracts
+ working-directory: v3/@claude-flow/cli
+ env:
+ RUFLO_REAL_BINARY_CLAUDE: claude
+ run: ../../../node_modules/.bin/vitest run --config vitest.real-binary.config.ts
+
# Claude Code native kit tests require the separately enabled host runtime.
# Built CLI tests still belong to the normal provisioned build gate.
diff --git a/scripts/ci-test-excluded.txt b/scripts/ci-test-excluded.txt
index 1825a17b6a..396b0c99e9 100644
--- a/scripts/ci-test-excluded.txt
+++ b/scripts/ci-test-excluded.txt
@@ -3,6 +3,8 @@
# - plugins/*/tests/*.test.ts import `claude-code/testing`, which only exists inside Claude Code: `claude plugin test <dir>` runs them
# (every plugin's scripts/smoke.sh, and .github/workflows/all-plugins-smoke.yml).
# - the .mjs files use node:test: `node --test` runs them (all-plugins-smoke.yml and the plugin smokes).
+# - v3/@claude-flow/cli/__tests__/real-binary/*.test.ts need the real `claude` binary: `npm run test:real-binary` runs them
+# (ADR-504; the mods-real-binary job in .github/workflows/mod-guidance.yml).
# A listed file that no longer exists fails the ratchet, so this list cannot go stale silently. Never add a file here to make a real
# regression green: a file that vitest CAN run belongs in scripts/ci-test-baseline.txt (and that file may only shrink).
@@ -105,3 +107,5 @@ tests/regression/oct12-coverage.test.cjs
plugins/ruflo-adr/scripts/__tests__/adr-status-forms-4126.test.mjs
scripts/__tests__/probe-mod-guards.test.mjs
plugins/ruflo-core/scripts/witness/__tests__/witness-auth.test.mjs
+v3/@claude-flow/cli/__tests__/real-binary/contracts.test.ts
+v3/@claude-flow/cli/__tests__/real-binary/loads.test.ts
diff --git a/v3/@claude-flow/cli/__tests__/real-binary/contracts.test.ts b/v3/@claude-flow/cli/__tests__/real-binary/contracts.test.ts
new file mode 100644
index 0000000000..e072c9e1b8
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/real-binary/contracts.test.ts
@@ -0,0 +1,170 @@
+/**
+ * Contracts 2-5 of the real-binary tier (ADR-504 §2.3), each a real `claude -p` run against the scripted mock model
+ * with ruflo-mods loaded at its default options.
+ *
+ * 2. Learning loop: a scripted fix turn (npm test fails, edit, npm test passes) is recorded as one verified-success.
+ * 3. Lessons reach the model: with a learned-lessons file present, the request carries the [RUFLO_LESSONS] block.
+ * 4. Guard tightens: a scripted Bash call that deletes the filesystem root is denied before it runs.
+ * 5. Route context: the routing block reaches the request.
+ *
+ * The mock is not a model (ADR-504 §3): these contracts check what reached the model and what the engine did, never
+ * what a model would do with it.
+ */
+import { join } from 'node:path';
+import { afterEach, beforeAll, describe, expect, it } from 'vitest';
+
+import { claudeVersion, describeRun, lastUserText, requestText, resultEvent, runClaude, type RunResult, type Turn } from './run';
+
+const runs: RunResult[] = [];
+afterEach(() => {
+ for (const run of runs.splice(0)) run.cleanup();
+});
+async function run(options: Parameters<typeof runClaude>[0]): Promise<RunResult> {
+ const r = await runClaude(options);
+ runs.push(r);
+ return r;
+}
+
+const say = (text: string): Turn => ({ content: [{ type: 'text', text }] });
+const bash = (command: string): Turn => ({ content: [{ type: 'tool_use', name: 'Bash', input: { command, description: 'run' } }] });
+
+beforeAll(() => {
+ // Fail, never skip, when the binary is missing (ADR-504 §2.4).
+ expect(claudeVersion(), 'the claude binary could not be started').toBeTruthy();
+});
+
+/** A one-function Node project whose `npm test` runs `node --test`; `src/add.js` starts with a bug. */
+const NODE_PROJECT = {
+ 'package.json': JSON.stringify({ name: 'real-binary-fixture', version: '1.0.0', private: true, scripts: { test: 'node --test' } }, null, 2),
+ 'src/add.js': 'exports.add = (a, b) => a - b\n',
+ 'test/add.test.js': "const test = require('node:test')\nconst assert = require('node:assert')\nconst { add } = require('../src/add.js')\ntest('add', () => assert.strictEqual(add(2, 3), 5))\n",
+};
+
+describe('real binary: learning loop records a verified outcome (contract 2)', () => {
+ it('npm test fails, the file is fixed, npm test passes: one verified-success record', async () => {
+ const r = await run({
+ prompt: 'Run npm test, then fix the bug in src/add.js, then run npm test again.',
+ files: NODE_PROJECT,
+ allowedTools: ['Bash', 'Read', 'Edit'],
+ script: (project) => {
+ const file = join(project, 'src/add.js');
+ return [
+ bash('npm test'),
+ { content: [{ type: 'tool_use', name: 'Read', input: { file_path: file } }] },
+ { content: [{ type: 'tool_use', name: 'Edit', input: { file_path: file, old_string: 'a - b', new_string: 'a + b' } }] },
+ bash('npm test'),
+ say('Fixed: add now returns a + b and npm test passes.'),
+ ];
+ },
+ });
+ expect(r.exitCode, describeRun(r)).toBe(0);
+ // The scripted calls really ran: the fix is on disk and the engine asked for every turn.
+ expect(r.file('src/add.js')).toContain('a + b');
+ expect(r.scripted.length).toBe(5);
+ // The first npm test really failed and the last really passed, as the engine reported them to the model.
+ expect(lastUserText(r.scripted[1]!.body)).toMatch(/fail/i);
+
+ const jsonl = r.file('.claude-flow/data/verified-trajectories.jsonl');
+ expect(jsonl, describeRun(r)).toBeDefined();
+ const records = jsonl!.trim().split('\n').map((line) => JSON.parse(line));
+ expect(records).toHaveLength(1);
+ const [record] = records;
+ expect(record.outcome).toBe('verified-success');
+ expect(record.verifier).toMatchObject({ kind: 'test', command: 'npm test', passed: true });
+ expect(record.edits).toBe(1);
+ // The failing run before the edit is a step (ok: false) that did not decide the outcome.
+ expect(record.steps.map((s: { tool: string; ok: boolean }) => `${s.tool}:${s.ok}`)).toEqual(['Bash:false', 'Read:true', 'Edit:true', 'Bash:true']);
+ });
+});
+
+/** A lessons file as the CLI ingest writes it (ADR-502 §2.2), with one lesson above the 0.6 gate. */
+function lessonsFile(confidence: number) {
+ return JSON.stringify({
+ version: 1,
+ gate: 0.6,
+ belowGate: 0,
+ lessons: [{ id: 'L-0123456789', kind: 'lesson', agent: 'coder', keywords: ['add', 'bug', 'fix'], confidence, successes: 4, failures: 0, evidence: 'npm test' }],
+ });
+}
+
+describe('real binary: verified lessons reach the model (contract 3)', () => {
+ const prompt = 'Fix the bug in the add function.';
+
+ it('a lesson above the gate is in the request the model receives', async () => {
+ const r = await run({ prompt, files: { '.claude-flow/data/learned-lessons.json': lessonsFile(0.67) }, script: [say('noted')] });
+ expect(r.exitCode, describeRun(r)).toBe(0);
+ expect(r.scripted.length).toBe(1);
+ const text = requestText(r.scripted[0]!.body);
+ expect(text).toContain('[RUFLO_LESSONS]');
+ expect(text).toContain('[lesson L-0123456789 conf 0.67, 4 passed / 0 failed]');
+ });
+
+ it('negative control: the same lesson below the gate never reaches the model', async () => {
+ const r = await run({ prompt, files: { '.claude-flow/data/learned-lessons.json': lessonsFile(0.4) }, script: [say('noted')] });
+ expect(r.exitCode, describeRun(r)).toBe(0);
+ expect(requestText(r.scripted[0]!.body)).not.toContain('[RUFLO_LESSONS]');
+ });
+});
+
+describe('real binary: the guard denies a root delete before it runs (contract 4)', () => {
+ // Every command here is shadowed on PATH by a recorder, so a guard that failed to fire records the call instead of
+ // running it (for rm, GNU rm's --preserve-root is the second line of defence).
+ const ROOT_DELETE = 'rm -rf /';
+ const denied = (r: RunResult, command: string) =>
+ (resultEvent(r)?.permission_denials ?? []).some((d: any) => d.tool_name === 'Bash' && d.tool_input?.command === command);
+
+ it('the root delete is denied with ruflo’s reason and never executes', async () => {
+ const r = await run({ prompt: 'Clean up the disk.', allowedTools: ['Bash'], shadow: ['rm'], script: [bash(ROOT_DELETE), say('stopped')] });
+ expect(r.exitCode, describeRun(r)).toBe(0);
+ expect(r.shadowed(), 'rm ran: the guard did not deny it').toEqual([]);
+ // The engine hands the denial back to the model as the tool result of the call.
+ expect(r.scripted.length).toBe(2);
+ expect(lastUserText(r.scripted[1]!.body)).toContain('ruflo: dangerous command blocked');
+ expect(denied(r, ROOT_DELETE)).toBe(true);
+ });
+
+ it('control: without ruflo-mods the engine refuses the root delete on its own, with its own reason', async () => {
+ // Claude Code refuses this one itself, so the contract above checks ruflo's reason, not just "some refusal". A
+ // version bump that drops the engine's own refusal shows up here.
+ const r = await run({ prompt: 'Clean up the disk.', allowedTools: ['Bash'], shadow: ['rm'], script: [bash(ROOT_DELETE), say('stopped')], pluginDir: null });
+ expect(r.exitCode, describeRun(r)).toBe(0);
+ expect(r.shadowed()).toEqual([]);
+ expect(lastUserText(r.scripted[1]!.body)).not.toContain('ruflo:');
+ expect(denied(r, ROOT_DELETE)).toBe(true);
+ });
+
+ // A command on ruflo's list that the engine allows: the run where the mod's tightening is the only thing that stops it.
+ const FORMAT = 'format c:';
+
+ it('a listed command the engine would allow is denied by ruflo and never executes', async () => {
+ const r = await run({ prompt: 'Format the drive.', allowedTools: ['Bash'], shadow: ['format'], script: [bash(FORMAT), say('stopped')] });
+ expect(r.exitCode, describeRun(r)).toBe(0);
+ expect(r.shadowed(), 'format ran: the guard did not deny it').toEqual([]);
+ expect(lastUserText(r.scripted[1]!.body)).toContain('ruflo: dangerous command blocked (format c:)');
+ expect(denied(r, FORMAT)).toBe(true);
+ });
+
+ it('negative control: without ruflo-mods the engine runs that allowed call (the recorder catches it)', async () => {
+ const r = await run({ prompt: 'Format the drive.', allowedTools: ['Bash'], shadow: ['format'], script: [bash(FORMAT), say('stopped')], pluginDir: null });
+ expect(r.exitCode, describeRun(r)).toBe(0);
+ expect(r.shadowed()).toEqual(['format c:']);
+ expect(denied(r, FORMAT)).toBe(false);
+ });
+});
+
+describe('real binary: the route block reaches the model (contract 5)', () => {
+ it('the routing recommendation for the prompt is in the request', async () => {
+ const prompt = 'Write unit tests for the payment module.';
+ const r = await run({ prompt, script: [say('ok')] });
+ expect(r.exitCode, describeRun(r)).toBe(0);
+ const text = requestText(r.scripted[0]!.body);
+ expect(text).toContain(`[INFO] Routing task: ${prompt}`);
+ expect(text).toContain('Primary Recommendation');
+ expect(text).toMatch(/\| Agent: [a-z-]+/);
+ });
+
+ it('negative control: outside a ruflo-mods run no route block is added', async () => {
+ const r = await run({ prompt: 'Write unit tests for the payment module.', script: [say('ok')], pluginDir: null });
+ expect(requestText(r.scripted[0]!.body)).not.toContain('Primary Recommendation');
+ });
+});
diff --git a/v3/@claude-flow/cli/__tests__/real-binary/loads.test.ts b/v3/@claude-flow/cli/__tests__/real-binary/loads.test.ts
new file mode 100644
index 0000000000..46b193a3cd
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/real-binary/loads.test.ts
@@ -0,0 +1,84 @@
+/**
+ * Contract 1 (ADR-504 §2.3): with every boolean option on, the REAL Claude Code loader accepts ruflo-mods.
+ *
+ * #4485 shipped because the harness only imitated the loader. A module the real loader refuses gives no error anywhere
+ * a test would look: exit 0, empty stderr, `result: success`, and the plugin still listed in `init.plugins`. What
+ * changes is behaviour, so this contract asserts behaviour: the mod's session-start heartbeat is written, its
+ * `/ruflo-mods` command is registered, and that command is answered by the mod without a single model request.
+ *
+ * The negative control rebuilds the #4485 shape in a throwaway copy (a second `session.start` with no matcher) and
+ * shows the same assertions fail on it, so the contract cannot pass vacuously.
+ */
+import { cpSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterEach, beforeAll, describe, expect, it } from 'vitest';
+
+import { allBooleanOptions, claudeVersion, describeRun, RUFLO_MODS_DIR, runClaude, type RunResult } from './run';
+
+const HEARTBEAT = '.claude-flow/mods/session.json';
+const runs: RunResult[] = [];
+const temps: string[] = [];
+afterEach(() => {
+ for (const run of runs.splice(0)) run.cleanup();
+ for (const dir of temps.splice(0)) rmSync(dir, { recursive: true, force: true });
+});
+
+/** What the real engine shows when the mod's hooks module was accepted. */
+function loadedSignals(run: RunResult) {
+ const init = run.events.find((e) => e.type === 'system' && e.subtype === 'init');
+ const reply = run.events.find((e) => e.type === 'assistant')?.message;
+ const heartbeat = run.file(HEARTBEAT);
+ return {
+ heartbeat: heartbeat !== undefined,
+ events: heartbeat ? (JSON.parse(heartbeat).events as string[] | undefined) : undefined,
+ command: Array.isArray(init?.slash_commands) && init.slash_commands.includes('ruflo-mods'),
+ modelRequests: run.scripted.length,
+ reply: reply?.content?.map((b: any) => b.text ?? '').join('') ?? '',
+ };
+}
+
+describe('real binary: ruflo-mods loads with every option on (contract 1)', () => {
+ beforeAll(() => {
+ // Fail, never skip, when the binary is missing (ADR-504 §2.4).
+ expect(claudeVersion(), 'the claude binary could not be started').toBeTruthy();
+ });
+
+ it('the loader accepts the module: heartbeat written, /ruflo-mods registered and answered by the mod', async () => {
+ const run = await runClaude({ prompt: '/ruflo-mods', options: allBooleanOptions(true) });
+ runs.push(run);
+ expect(run.exitCode, describeRun(run)).toBe(0);
+ const s = loadedSignals(run);
+ expect(s.heartbeat, describeRun(run)).toBe(true);
+ // With capabilityProbe on, the heartbeat names the events the engine actually exposes; session.start must be one.
+ expect(s.events).toContain('session.start');
+ expect(s.command).toBe(true);
+ expect(s.reply).toMatch(/^ruflo-mods: ruflo mods/);
+ expect(s.modelRequests).toBe(0);
+ });
+
+ it('negative control: a #4485-shaped copy (second bare session.start) is refused by the real loader', async () => {
+ const copy = mkdtempSync(join(tmpdir(), 'ruflo-mods-4485-'));
+ temps.push(copy);
+ cpSync(RUFLO_MODS_DIR, copy, { recursive: true, dereference: true });
+ const register = join(copy, 'hooks/register.ts');
+ const source = readFileSync(register, 'utf8');
+ const end = source.lastIndexOf('}');
+ writeFileSync(register, `${source.slice(0, end)} on('session.start', async ($, e, next) => next(e)) // #4485 shape\n${source.slice(end)}`);
+
+ const run = await runClaude({
+ prompt: '/ruflo-mods',
+ options: allBooleanOptions(true, copy),
+ pluginDir: copy,
+ script: [{ content: [{ type: 'text', text: 'the model answered' }] }],
+ });
+ runs.push(run);
+ const s = loadedSignals(run);
+ // Nothing reports the refusal: the run "succeeds". Only behaviour shows the hooks never ran.
+ expect(run.exitCode, describeRun(run)).toBe(0);
+ expect(s.heartbeat).toBe(false);
+ expect(s.command).toBe(false);
+ expect(s.modelRequests).toBe(1);
+ expect(s.reply).toBe('the model answered');
+ });
+});
diff --git a/v3/@claude-flow/cli/__tests__/real-binary/mock-model.mjs b/v3/@claude-flow/cli/__tests__/real-binary/mock-model.mjs
new file mode 100644
index 0000000000..15d8feaa5c
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/real-binary/mock-model.mjs
@@ -0,0 +1,121 @@
+/**
+ * A scripted Anthropic Messages API server for the real-binary test tier (ADR-504 §2.1).
+ *
+ * Claude Code reaches it through `ANTHROPIC_BASE_URL=http://127.0.0.1:<port>` with a dummy key. It is not a model: it
+ * replays a fixed conversation. Each request that offers tools (the main loop asking for its next move) takes the next
+ * scripted assistant turn; anything else (title or summary generation, token counting, an unknown path) gets a minimal
+ * valid answer so an engine-internal call can never hang the run. Every request is logged, so a test can assert on
+ * what context actually reached the model.
+ *
+ * It accepts unknown request fields and only ever reads `messages`, `system`, `tools` and `stream`, so a request-shape
+ * change between Claude Code versions does not break it (ADR-504 §3).
+ *
+ * Script: an array of assistant turns, each `{ content: Block[] }` where a block is `{ type: 'text', text }` or
+ * `{ type: 'tool_use', name, input }`. The stop reason is `tool_use` when a turn carries a tool call, else `end_turn`.
+ * When the script runs out, the server answers `done` with `end_turn`.
+ *
+ * Usage as a module: `const mock = await startMockModel(script); ...; await mock.close()`.
+ * Usage from a shell: `node mock-model.mjs script.json` prints `MOCK_URL=<url>` and serves until killed.
+ */
+import { createServer } from 'node:http'
+import { readFileSync } from 'node:fs'
+import { pathToFileURL } from 'node:url'
+
+const isScripted = body => Array.isArray(body?.tools) && body.tools.length > 0 && Array.isArray(body?.messages)
+
+function materialise(turn, index) {
+ const content = (turn?.content ?? [{ type: 'text', text: 'done' }]).map((block, j) =>
+ block.type === 'tool_use' ? { type: 'tool_use', id: block.id ?? `toolu_mock_${index}_${j}`, name: block.name, input: block.input ?? {} } : { type: 'text', text: String(block.text ?? '') },
+ )
+ return { content, stop: content.some(block => block.type === 'tool_use') ? 'tool_use' : 'end_turn' }
+}
+
+function messageJson(id, model, { content, stop }) {
+ return { id, type: 'message', role: 'assistant', model, content, stop_reason: stop, stop_sequence: null, usage: { input_tokens: 10, output_tokens: 5, cache_creation_input_tokens: 0, cache_read_input_tokens: 0 } }
+}
+
+function sse(res, id, model, { content, stop }) {
+ res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache', connection: 'keep-alive' })
+ const send = (event, data) => res.write(`event: ${event}\ndata: ${JSON.stringify({ type: event, ...data })}\n\n`)
+ send('message_start', { message: { ...messageJson(id, model, { content: [], stop: null }), stop_reason: null } })
+ content.forEach((block, index) => {
+ if (block.type === 'tool_use') {
+ send('content_block_start', { index, content_block: { type: 'tool_use', id: block.id, name: block.name, input: {} } })
+ send('content_block_delta', { index, delta: { type: 'input_json_delta', partial_json: JSON.stringify(block.input) } })
+ } else {
+ send('content_block_start', { index, content_block: { type: 'text', text: '' } })
+ send('content_block_delta', { index, delta: { type: 'text_delta', text: block.text } })
+ }
+ send('content_block_stop', { index })
+ })
+ send('message_delta', { delta: { stop_reason: stop, stop_sequence: null }, usage: { output_tokens: 5 } })
+ send('message_stop', {})
+ res.end()
+}
+
+/**
+ * @param {Array<{content: Array<object>}>} script assistant turns, consumed in order by tool-offering requests
+ * @returns {Promise<{url: string, port: number, requests: Array<object>, scripted: () => Array<object>, close: () => Promise<void>}>}
+ */
+export async function startMockModel(script = []) {
+ const requests = []
+ let next = 0
+ const server = createServer((req, res) => {
+ const chunks = []
+ req.on('data', chunk => chunks.push(chunk))
+ req.on('end', () => {
+ const raw = Buffer.concat(chunks).toString('utf8')
+ let body
+ try { body = raw ? JSON.parse(raw) : undefined } catch { body = undefined }
+ const path = (req.url ?? '/').split('?')[0]
+ const entry = { at: Date.now(), method: req.method, path, body, scripted: false, turn: -1 }
+ requests.push(entry)
+
+ if (req.method === 'POST' && path.endsWith('/messages/count_tokens')) {
+ res.writeHead(200, { 'content-type': 'application/json' })
+ return res.end(JSON.stringify({ input_tokens: 10 }))
+ }
+ if (req.method === 'POST' && path.endsWith('/messages')) {
+ const model = typeof body?.model === 'string' ? body.model : 'mock-model'
+ let turn
+ if (isScripted(body)) {
+ entry.scripted = true
+ entry.turn = next
+ turn = materialise(script[next], next)
+ next++
+ } else {
+ turn = materialise({ content: [{ type: 'text', text: 'ok' }] }, -1)
+ }
+ const id = `msg_mock_${requests.length}`
+ if (body?.stream === true) return sse(res, id, model, turn)
+ res.writeHead(200, { 'content-type': 'application/json' })
+ return res.end(JSON.stringify(messageJson(id, model, turn)))
+ }
+ // Anything else (feature flags, metrics, an endpoint a newer version adds): a valid, empty answer.
+ res.writeHead(200, { 'content-type': 'application/json' })
+ res.end('{}')
+ })
+ })
+ await new Promise((resolve, reject) => {
+ server.once('error', reject)
+ server.listen(0, '127.0.0.1', resolve)
+ })
+ const port = server.address().port
+ return {
+ url: `http://127.0.0.1:${port}`,
+ port,
+ requests,
+ scripted: () => requests.filter(r => r.scripted),
+ close: () => new Promise(resolve => {
+ server.closeAllConnections?.()
+ server.close(() => resolve())
+ }),
+ }
+}
+
+if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) {
+ const script = process.argv[2] ? JSON.parse(readFileSync(process.argv[2], 'utf8')) : []
+ const mock = await startMockModel(script)
+ console.log(`MOCK_URL=${mock.url}`)
+ process.on('SIGTERM', () => mock.close().then(() => process.exit(0)))
+}
diff --git a/v3/@claude-flow/cli/__tests__/real-binary/run.ts b/v3/@claude-flow/cli/__tests__/real-binary/run.ts
new file mode 100644
index 0000000000..e30efb6f3e
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/real-binary/run.ts
@@ -0,0 +1,219 @@
+/**
+ * Runner for the real-binary test tier (ADR-504 §2.2).
+ *
+ * Launches the real `claude` binary headless against the scripted mock model, with ruflo-mods loaded through
+ * `--plugin-dir`, in a throwaway project with its own HOME, CLAUDE_CONFIG_DIR and temp dir. The child gets a minimal
+ * environment built here, never this process's: no real API key, no user settings, no user plugins or MCP servers can
+ * reach it.
+ *
+ * It returns the exit code, the stream-json events, the mock's request log and a reader for the project's files.
+ */
+import { spawn, spawnSync } from 'node:child_process';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync, chmodSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+// @ts-expect-error: plain ESM helper without a declaration file
+import { startMockModel } from './mock-model.mjs';
+
+const here = dirname(fileURLToPath(import.meta.url));
+export const REPO_ROOT = resolve(here, '../../../../..');
+/** The plugin under test; RUFLO_REAL_BINARY_PLUGIN_DIR points the tier at another copy (a packed or fresh checkout). */
+export const RUFLO_MODS_DIR = process.env.RUFLO_REAL_BINARY_PLUGIN_DIR || join(REPO_ROOT, 'plugins/ruflo-mods');
+/** The binary under test. CI installs a pinned version; locally it is whatever `claude` resolves to. */
+export const CLAUDE_BIN = process.env.RUFLO_REAL_BINARY_CLAUDE || 'claude';
+/** Any model id works: the mock answers for every one. A haiku id keeps engine-side cost estimates tiny. */
+const MODEL = 'claude-haiku-4-5';
+
+export type Block = { type: 'text'; text: string } | { type: 'tool_use'; name: string; input: Record<string, unknown>; id?: string };
+export interface Turn {
+ content: Block[];
+}
+export interface MockRequest {
+ at: number;
+ method: string;
+ path: string;
+ body: any;
+ scripted: boolean;
+ turn: number;
+}
+
+export interface RunOptions {
+ /** The prompt passed to `claude -p`. */
+ prompt: string;
+ /** Assistant turns the mock replays, in order, to the main loop's requests; a function gets the project path. */
+ script?: Turn[] | ((project: string) => Turn[]);
+ /** ruflo-mods options, set through `--settings` `pluginConfigs` the way a user would. */
+ options?: Record<string, unknown>;
+ /** The plugin directory to load; defaults to the repository's ruflo-mods. Pass `null` to load no plugin. */
+ pluginDir?: string | null;
+ /** Files to create in the project before the run, relative path → content. `.claude-flow/` always exists. */
+ files?: Record<string, string>;
+ /** Tools the run may use without a permission prompt. */
+ allowedTools?: string[];
+ /** Kill the run after this long. */
+ timeoutMs?: number;
+ /** Commands shadowed on PATH by a recorder that writes `<name>` to `<tmp>/shadowed.log` and exits 0. */
+ shadow?: string[];
+}
+
+export interface RunResult {
+ exitCode: number | null;
+ signal: NodeJS.Signals | null;
+ timedOut: boolean;
+ events: any[];
+ stdout: string;
+ stderr: string;
+ /** Every request the mock received. */
+ requests: MockRequest[];
+ /** Only the requests that consumed a scripted turn (the main loop's). */
+ scripted: MockRequest[];
+ /** The throwaway project directory (the run's cwd). */
+ project: string;
+ /** The private temp root holding project, home and tmp. */
+ root: string;
+ /** Read a project file, relative to the project; undefined when absent. */
+ file(rel: string): string | undefined;
+ /** Commands the PATH shadows recorded, one per line. */
+ shadowed(): string[];
+ /** Remove the temp root (kept when RUFLO_REAL_BINARY_KEEP=1). */
+ cleanup(): void;
+}
+
+/** True when the binary can be started; the tier's CI job fails instead of skipping (ADR-504 §2.4). */
+export function claudeVersion(): string | undefined {
+ const r = spawnSync(CLAUDE_BIN, ['--version'], { encoding: 'utf8', timeout: 30_000 });
+ return r.status === 0 ? r.stdout.trim() : undefined;
+}
+
+/** Every boolean option ruflo-mods declares, set to `value`; read from the manifest so a new option is covered. */
+export function allBooleanOptions(value = true, pluginDir = RUFLO_MODS_DIR): Record<string, boolean> {
+ const manifest = JSON.parse(readFileSync(join(pluginDir, '.claude-plugin/plugin.json'), 'utf8'));
+ const spec = manifest.userConfig as Record<string, { type?: string }>;
+ return Object.fromEntries(Object.entries(spec).filter(([, s]) => s.type === 'boolean').map(([key]) => [key, value]));
+}
+
+/** Text of the last user message of a request: what that request added to the conversation. */
+export function lastUserText(body: any): string {
+ const messages: any[] = Array.isArray(body?.messages) ? body.messages : [];
+ for (let i = messages.length - 1; i >= 0; i--) if (messages[i]?.role === 'user') return textOf(messages[i].content);
+ return '';
+}
+
+/** All text of a request: system prompt and every message, including tool results and system reminders. */
+export function requestText(body: any): string {
+ return [textOf(body?.system), ...(Array.isArray(body?.messages) ? body.messages.map((m: any) => textOf(m?.content)) : [])].join('\n');
+}
+
+function textOf(value: unknown): string {
+ if (typeof value === 'string') return value;
+ if (Array.isArray(value)) return value.map(textOf).join('\n');
+ if (value && typeof value === 'object') {
+ const v = value as { text?: unknown; content?: unknown };
+ return [typeof v.text === 'string' ? v.text : '', v.content !== undefined ? textOf(v.content) : ''].filter(Boolean).join('\n');
+ }
+ return '';
+}
+
+export async function runClaude(opts: RunOptions): Promise<RunResult> {
+ const root = mkdtempSync(join(tmpdir(), 'ruflo-real-binary-'));
+ const project = join(root, 'project');
+ const home = join(root, 'home');
+ const tmp = join(root, 'tmp');
+ const bin = join(root, 'bin');
+ for (const dir of [project, join(project, '.claude-flow'), home, tmp, bin]) mkdirSync(dir, { recursive: true });
+ for (const [rel, content] of Object.entries(opts.files ?? {})) {
+ const path = join(project, rel);
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, content);
+ }
+ const shadowLog = join(tmp, 'shadowed.log');
+ for (const name of opts.shadow ?? []) {
+ const path = join(bin, name);
+ writeFileSync(path, `#!/bin/sh\necho "${name} $*" >> '${shadowLog}'\nexit 0\n`);
+ chmodSync(path, 0o755);
+ }
+
+ const settings = join(root, 'settings.json');
+ const pluginOptions = opts.options ? { options: opts.options } : undefined;
+ // `--plugin-dir` loads the plugin as `<name>@inline`; the bare name is kept for older engines.
+ writeFileSync(settings, JSON.stringify(pluginOptions ? { pluginConfigs: { 'ruflo-mods@inline': pluginOptions, 'ruflo-mods': pluginOptions } } : {}));
+
+ const mock = await startMockModel(typeof opts.script === 'function' ? opts.script(project) : (opts.script ?? []));
+ const env: NodeJS.ProcessEnv = {
+ PATH: `${bin}:${process.env.PATH ?? '/usr/bin:/bin'}`,
+ HOME: home,
+ USER: process.env.USER ?? 'runner',
+ LANG: 'C.UTF-8',
+ SHELL: '/bin/bash',
+ CLAUDE_CONFIG_DIR: join(home, '.claude'),
+ CLAUDE_CODE_TMPDIR: tmp,
+ TMPDIR: tmp,
+ ANTHROPIC_BASE_URL: mock.url,
+ ANTHROPIC_API_KEY: 'sk-ant-real-binary-tier-not-a-key',
+ CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: '1',
+ DISABLE_AUTOUPDATER: '1',
+ CLAUDE_CODE_ENABLE_FUNCTION_HOOKS: '1',
+ };
+ const args = ['-p', opts.prompt, '--output-format', 'stream-json', '--verbose', '--model', MODEL, '--settings', settings, '--strict-mcp-config'];
+ const pluginDir = opts.pluginDir === undefined ? RUFLO_MODS_DIR : opts.pluginDir;
+ if (pluginDir) args.push('--plugin-dir', pluginDir);
+ if (opts.allowedTools?.length) args.push('--allowedTools', opts.allowedTools.join(','));
+
+ const child = spawn(CLAUDE_BIN, args, { cwd: project, env, stdio: ['ignore', 'pipe', 'pipe'] });
+ let stdout = '';
+ let stderr = '';
+ child.stdout.on('data', (d) => (stdout += d));
+ child.stderr.on('data', (d) => (stderr += d));
+ let timedOut = false;
+ const timer = setTimeout(() => {
+ timedOut = true;
+ child.kill('SIGKILL');
+ }, opts.timeoutMs ?? 90_000);
+ const [exitCode, signal] = await new Promise<[number | null, NodeJS.Signals | null]>((done, fail) => {
+ child.on('error', fail);
+ child.on('close', (code, sig) => done([code, sig]));
+ }).finally(() => clearTimeout(timer));
+ await mock.close();
+
+ const events = stdout
+ .split('\n')
+ .filter((line) => line.trim().startsWith('{'))
+ .flatMap((line) => {
+ try {
+ return [JSON.parse(line)];
+ } catch {
+ return [];
+ }
+ });
+
+ return {
+ exitCode,
+ signal,
+ timedOut,
+ events,
+ stdout,
+ stderr,
+ requests: mock.requests,
+ scripted: mock.scripted(),
+ project,
+ root,
+ file: (rel) => (existsSync(join(project, rel)) ? readFileSync(join(project, rel), 'utf8') : undefined),
+ shadowed: () => (existsSync(shadowLog) ? readFileSync(shadowLog, 'utf8').split('\n').filter(Boolean) : []),
+ cleanup: () => {
+ if (process.env.RUFLO_REAL_BINARY_KEEP !== '1') rmSync(root, { recursive: true, force: true });
+ },
+ };
+}
+
+/** The final `result` event of a run, if it reached one. */
+export function resultEvent(run: RunResult): any {
+ return run.events.find((e) => e.type === 'result');
+}
+
+/** A diagnostic string for a failing assertion: exit, result, stderr tail. */
+export function describeRun(run: RunResult): string {
+ const result = resultEvent(run);
+ return `exit=${run.exitCode} signal=${run.signal} timedOut=${run.timedOut} result=${JSON.stringify(result?.result ?? result?.subtype)}\nstderr: ${run.stderr.slice(-2000)}\nroot: ${run.root}`;
+}
diff --git a/v3/@claude-flow/cli/package.json b/v3/@claude-flow/cli/package.json
index 2f44b06dbc..c69ce48dcd 100644
--- a/v3/@claude-flow/cli/package.json
+++ b/v3/@claude-flow/cli/package.json
@@ -86,6 +86,7 @@
"build": "tsc",
"check:metaharness-pins": "node ../../../scripts/check-metaharness-pins.mjs",
"test": "vitest run",
+ "test:real-binary": "vitest run --config vitest.real-binary.config.ts",
"test:plugin-store": "npx tsx src/plugins/tests/standalone-test.ts",
"test:pattern-store": "npx tsx src/transfer/store/tests/standalone-test.ts",
"postinstall": "node ./scripts/postinstall.cjs",
diff --git a/v3/@claude-flow/cli/vitest.config.ts b/v3/@claude-flow/cli/vitest.config.ts
index 934201efe4..4e66a62cb5 100644
--- a/v3/@claude-flow/cli/vitest.config.ts
+++ b/v3/@claude-flow/cli/vitest.config.ts
@@ -1,4 +1,4 @@
-import { defineConfig } from 'vitest/config';
+import { configDefaults, defineConfig } from 'vitest/config';
import { fileURLToPath } from 'node:url';
export default defineConfig({
@@ -57,6 +57,9 @@ export default defineConfig({
test: {
environment: 'node',
include: ['__tests__/**/*.test.ts'],
+ // The real-binary tier (ADR-504) needs the `claude` binary; it has its own config and CI job
+ // (vitest.real-binary.config.ts, `npm run test:real-binary`, mods-real-binary in mod-guidance.yml).
+ exclude: [...configDefaults.exclude, '__tests__/real-binary/**'],
globals: true,
// Vitest's 5s default is unrealistic for this suite: a number of the
// memory/intelligence tests initialise a real ONNX embedder and a SQLite
diff --git a/v3/@claude-flow/cli/vitest.real-binary.config.ts b/v3/@claude-flow/cli/vitest.real-binary.config.ts
new file mode 100644
index 0000000000..001dec8cd5
--- /dev/null
+++ b/v3/@claude-flow/cli/vitest.real-binary.config.ts
@@ -0,0 +1,17 @@
+import { defineConfig } from 'vitest/config';
+
+/**
+ * The real-binary tier (ADR-504): the real `claude` binary against a scripted mock model. It needs the binary, so it
+ * is excluded from the default `vitest run` (vitest.config.ts) and runs only through `npm run test:real-binary` and
+ * the `mods-real-binary` CI job. Files run one after another: each test is a whole Claude Code process.
+ */
+export default defineConfig({
+ test: {
+ environment: 'node',
+ include: ['__tests__/real-binary/**/*.test.ts'],
+ globals: true,
+ testTimeout: 180_000,
+ hookTimeout: 180_000,
+ fileParallelism: false,
+ },
+});
diff --git a/v3/docs/adr/ADR-504-mods-real-binary-test-tier.md b/v3/docs/adr/ADR-504-mods-real-binary-test-tier.md
index 0f6b8a0c80..0e9898f678 100644
--- a/v3/docs/adr/ADR-504-mods-real-binary-test-tier.md
+++ b/v3/docs/adr/ADR-504-mods-real-binary-test-tier.md
@@ -1,6 +1,6 @@
# ADR 504: a real-binary test tier for ruflo mods and hooks
-Status: Proposed (2026-10-29)
+Status: Accepted (implemented in PR #4589, 2026-10-29; see section 5)
Issue: #4581 follow-up 5. Builds on: ADR-404 and the mods harness (`v3/@claude-flow/cli/__tests__/mods/harness.ts`).
@@ -74,3 +74,52 @@ The tier also runs locally with `npm run test:real-binary` from `v3/@claude-flow
## 4. Verification
The tier must be able to catch #4485. Adding a second `session.start` registration without a matcher to a scratch copy of ruflo-mods must make contract 1 fail.
+
+## 5. Implementation notes
+
+Built against Claude Code 2.1.289, the version installed where this was written and the version the CI job pins.
+
+**Files.** `v3/@claude-flow/cli/__tests__/real-binary/`: `mock-model.mjs` (the scripted Messages server), `run.ts` (the runner), `loads.test.ts` (contract 1) and `contracts.test.ts` (contracts 2 to 5). `vitest.real-binary.config.ts` runs them; `npm run test:real-binary` from `v3/@claude-flow/cli` calls it. The tier takes about 6 seconds locally.
+
+**Kept out of every default run.** Three runners would otherwise collect the files: the CLI's `vitest.config.ts` (now excludes `__tests__/real-binary/**`), `v3/vitest.config.ts` (excludes the same path) and the root ratchet (`scripts/ci-test-excluded.txt` lists both files, with the job that runs them).
+
+**What #4485 looks like to the real loader.** The refusal is silent. A copy of ruflo-mods with a second bare `session.start` gives exit 0, empty stderr, a `success` result, and the plugin still listed in `init.plugins`. Only behaviour changes, so contract 1 asserts behaviour:
+- the session-start heartbeat `.claude-flow/mods/session.json` is written, and with `capabilityProbe` on it lists `session.start`;
+- `/ruflo-mods` is in `init.slash_commands`;
+- `/ruflo-mods` is answered by the mod, with zero requests to the model.
+
+The negative control is committed: `loads.test.ts` copies ruflo-mods to a temp directory, adds the bare registration, and asserts the heartbeat is missing, the command is not registered and the prompt goes to the model. Run by hand against a scratch copy first, the same shape made all three positive assertions fail.
+
+**Contract 4 needed a second command.** Claude Code 2.1.289 refuses the root delete on its own ("Dangerous rm operation detected"), even when Bash is allowed. A test that only checked for a refusal would pass without ruflo. So:
+- the root-delete test asserts ruflo's reason (`ruflo: dangerous command blocked`) in the tool result and the run's `permission_denials`;
+- a control without the plugin records the engine's own refusal, so a version bump that drops it shows up;
+- the Windows drive-format entry of ruflo's list, which the engine allows, is denied by ruflo; without the plugin the engine runs it.
+
+Every command in contract 4 is shadowed on `PATH` by a recorder that only logs, so a guard that fails cannot run anything. For `rm`, GNU rm's `--preserve-root` is a second defence.
+
+**Runner environment.** The child process gets a minimal environment built by the runner, never the parent's, so no real key, user settings, plugins or MCP servers reach it. It sets:
+- `HOME`, `CLAUDE_CONFIG_DIR` and the project under a fresh `mkdtemp`;
+- `--strict-mcp-config`;
+- `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1`;
+- `CLAUDE_CODE_TMPDIR`. Without it the engine refused to start: "Temp directory /tmp/claude-1000 is owned by uid 0 … Refusing to use it".
+
+stream-json output with `-p` also needs `--verbose`. Options reach the plugin through `--settings` `pluginConfigs["ruflo-mods@inline"]`, the id `--plugin-dir` gives it.
+
+**Mock behaviour seen.** Besides `POST /v1/messages` (streaming), 2.1.289 sends one `HEAD /api/hello` connectivity probe; the mock answers any unknown path with `{}`. Main-loop requests are the ones that offer `tools`, and each takes the next scripted turn. No title or summary request was seen in `-p` mode. Such a request would offer no tools, so it would get the minimal answer and could not consume a scripted turn.
+
+**Contract 2** runs with default options (`learningLoop` is on by default). The script reads `src/add.js` before editing it, because the engine refuses an Edit of a file not read in the session. The test asserts:
+- exactly one record, `verified-success`, verifier `npm test` passed;
+- the steps `Bash:false, Read:true, Edit:true, Bash:true`, so the failing run before the edit is recorded and did not decide the outcome.
+
+Contracts 3 and 5 each have a negative control: a lesson below the 0.6 gate never reaches the request, and without the plugin no route block is added.
+
+**`.claude-plugin/types`.** It is not in git, and the loader writes it when it loads the plugin. The tier passed against a fresh copy without it (`RUFLO_REAL_BINARY_PLUGIN_DIR` points the tier at another plugin copy), so CI needs nothing extra.
+
+**CI.** The `mods-real-binary` job in `mod-guidance.yml`:
+1. installs `@anthropic-ai/[email protected]` globally;
+2. fails, naming the step, if `claude --version` fails or reports another version;
+3. runs the tier.
+
+It needs no secret.
+
+**Live validation** is the tier itself: every contract runs the real 2.1.289 binary end to end against the mock, at no model cost.
diff --git a/v3/vitest.config.ts b/v3/vitest.config.ts
index 76cc7b64be..6db693f6ee 100644
--- a/v3/vitest.config.ts
+++ b/v3/vitest.config.ts
@@ -88,6 +88,8 @@ export default defineConfig({
// node:test files (run with `npx tsx --test`), not vitest suites: vitest
// executes their top level and then reports "No test suite found".
'__tests__/appliance/**',
+ // The real-binary tier (ADR-504) needs the `claude` binary; its own CI job runs it.
+ '@claude-flow/cli/__tests__/real-binary/**',
...KNOWN_FAILING,
],