π 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
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
feat(e2e): three-host integration loop (Claude Code, Codex, OpenRouter); fix MCP resources capability and Codex plugin clone budget
r98f2eb52136e
diff --git a/.github/workflows/e2e-host-matrix.yml b/.github/workflows/e2e-host-matrix.ymlnew file mode 100644index 0000000000..f22db8f283--- /dev/null+++ b/.github/workflows/e2e-host-matrix.yml@@ -0,0 +1,54 @@+name: e2e-host-matrix++# ADR-490: host x assertion matrix for Claude Code, Codex and OpenRouter against the real ruflo CLI and MCP server.+# This workflow runs the KEYLESS mode only: no model call, no secret, $0. Live mode (RUFLO_E2E_LIVE=1) is run by hand.+# Codex is pinned to 0.162.0 (0.162.1 crashes with a #GP). No Claude Code binary is needed for the keyless legs.++on:+ pull_request:+ paths:+ - 'scripts/e2e/**'+ - 'v3/@claude-flow/cli/bin/**'+ - 'v3/@claude-flow/cli/src/mcp-server.ts'+ - 'v3/@claude-flow/codex/src/**'+ - '.github/workflows/e2e-host-matrix.yml'+ schedule:+ - cron: '23 5 * * 1'+ workflow_dispatch:++jobs:+ keyless:+ name: e2e host matrix (keyless)+ runs-on: ubuntu-latest+ timeout-minutes: 40+ steps:+ - uses: actions/checkout@v4+ - uses: pnpm/action-setup@v6+ with:+ version: '8'+ - uses: actions/setup-node@v4+ with:+ node-version: '22'+ cache: 'pnpm'+ cache-dependency-path: v3/pnpm-lock.yaml+ - name: Install workspace+ working-directory: v3+ run: pnpm install --frozen-lockfile --ignore-scripts+ - name: Build the CLI and what it imports+ working-directory: v3+ run: |+ for p in shared security mcp swarm; do (cd @claude-flow/$p && pnpm run build); done+ (cd @claude-flow/cli && pnpm run build)+ - name: Install the pinned Codex (0.162.0)+ run: |+ npm install -g @openai/[email protected]+ codex --version+ echo "RUFLO_E2E_CODEX_BIN=$(command -v codex)" >> "$GITHUB_ENV"+ - name: Matrix (keyless)+ run: node scripts/e2e/host-matrix.mjs --cli-path "$PWD/v3/@claude-flow/cli/bin/cli.js" --json e2e-matrix.json+ - uses: actions/upload-artifact@v4+ if: always()+ with:+ name: e2e-matrix+ path: e2e-matrix.json+ retention-days: 30diff --git a/docs/e2e-host-matrix.md b/docs/e2e-host-matrix.mdnew file mode 100644index 0000000000..a3003845ba--- /dev/null+++ b/docs/e2e-host-matrix.md@@ -0,0 +1,31 @@+# e2e host matrix: Claude Code, Codex, OpenRouter++One command shows whether ruflo works end to end with each host. Design, safety rules and the first results: [ADR-490](../v3/docs/adr/ADR-490-three-host-e2e-integration-loop.md).++```bash+npm run e2e # keyless: no model call, $0 (this is what CI runs)+RUFLO_E2E_LIVE=1 npm run e2e:live # also real sessions, capped at 6 USD (--cap N)+node scripts/e2e/host-matrix.mjs --legs codex --cli-path "$PWD/v3/@claude-flow/cli/bin/cli.js" --json out.json+```++Flags: `--legs claude,codex,openrouter`, `--cli-version latest|X.Y.Z` (default: the published `ruflo`), `--cli-path <cli.js>` (test a workspace+build; build `shared security mcp swarm cli` first), `--json <file>`, `--cap <usd>`. Exit code 1 only when a row is `fail`.++## What you need for the live mode++- **Claude Code** logged in (`~/.claude/.credentials.json`); only the access token is copied into a throwaway config.+- **Codex 0.162.0** under `~/.codex/packages/standalone/releases/` (or `RUFLO_E2E_CODEX_BIN`). Never 0.162.1: it crashes with a #GP.+ Codex authenticates through OpenRouter, so your ChatGPT login is never copied or refreshed.+- **An OpenRouter key**: `OPENROUTER_API_KEY`, or Secret Manager (`ruv-dev`, then `cognitum-20260110`) when `gcloud` is `[email protected]`.+ It is held in memory, passed by environment, and redacted from every report. Without one the OpenRouter and Codex live rows are `blocked`.++## Reading the table++`pass`, `fail`, `blocked` (a credential or the pinned binary is missing), `skipped` (live mode off, or the host cannot do it+non-interactively), `flaky` (the trigger did not occur this run; rerun), `advisory` (a posture question for a person, not a defect).+Evidence is redacted and capped at 600 characters per row. A defect found live needs a failing unit test and a fix, not a harness change.++## Files++`scripts/e2e/host-matrix.mjs` (orchestrator), `leg-claude.mjs`, `leg-codex.mjs`, `leg-openrouter.mjs`, `lib.mjs` (recorder, redaction, sandbox,+MCP stdio client, OpenAI-compatible stub). Workflow: `.github/workflows/e2e-host-matrix.yml` (keyless; PRs touching the seam, weekly, on demand).diff --git a/package.json b/package.jsonindex debd8b7442..80004ebcd6 100644--- a/package.json+++ b/package.json@@ -55,6 +55,8 @@"build:ts": "cd v3/@claude-flow/cli && npm run build || true","prepublishOnly": "node scripts/prepare-root-publish.mjs","test": "vitest",+ "e2e": "node scripts/e2e/host-matrix.mjs",+ "e2e:live": "RUFLO_E2E_LIVE=1 node scripts/e2e/host-matrix.mjs --live","test:ui": "vitest --ui","test:security": "vitest run v3/__tests__/security/","lint": "cd v3/@claude-flow/cli && npm run lint || true",diff --git a/scripts/e2e/host-matrix.mjs b/scripts/e2e/host-matrix.mjsnew file mode 100644index 0000000000..ad485c59af--- /dev/null+++ b/scripts/e2e/host-matrix.mjs@@ -0,0 +1,33 @@+#!/usr/bin/env node+// Three-host e2e loop (ADR-490): Claude Code, Codex and OpenRouter against the real ruflo CLI/MCP/mods, host x assertion matrix.+// node scripts/e2e/host-matrix.mjs keyless + stubbed assertions only (what CI runs): $0, no model call+// RUFLO_E2E_LIVE=1 node scripts/e2e/host-matrix.mjs --live also run the live legs (spend-incurring, capped at --cap USD, default 6)+// Flags: --legs claude,codex,openrouter --cli-version latest|X.Y.Z --cli-path <repo cli.js> --json out.json --cap 6+import { writeFileSync } from 'node:fs'+import { spend, renderTable, redact } from './lib.mjs'+import { claudeLeg } from './leg-claude.mjs'+import { codexLeg } from './leg-codex.mjs'+import { openrouterLeg } from './leg-openrouter.mjs'++const arg = (k, d) => { const i = process.argv.indexOf(`--${k}`); return i > 0 ? process.argv[i + 1] : d }+const live = process.argv.includes('--live') && process.env.RUFLO_E2E_LIVE === '1'+if (process.argv.includes('--live') && !live) console.error('--live ignored: set RUFLO_E2E_LIVE=1 as well (spend guard)')+spend.cap = Number(arg('cap', '6'))+const cliPath = arg('cli-path', process.env.RUFLO_E2E_CLI_PATH)+const cli = cliPath ? { cmd: process.execPath, args: [cliPath], label: `path:${cliPath}` } : { cmd: 'npx', args: ['-y', `ruflo@${arg('cli-version', process.env.RUFLO_E2E_CLI_VERSION ?? 'latest')}`], label: `ruflo@${arg('cli-version', process.env.RUFLO_E2E_CLI_VERSION ?? 'latest')}` }+const legs = (arg('legs', 'claude,codex,openrouter')).split(',')+const ctx = { cli, live, spend }+const fns = { claude: claudeLeg, codex: codexLeg, openrouter: openrouterLeg }++const rows = []+for (const leg of legs) {+ if (!fns[leg]) { console.error(`unknown leg ${leg}`); process.exit(2) }+ const t0 = Date.now()+ try { rows.push(...await fns[leg](ctx)) } catch (e) { rows.push({ leg, name: 'leg ran to completion', status: 'fail', evidence: redact(String(e?.stack ?? e)).slice(0, 400) }) }+ console.error(`# ${leg} done in ${Math.round((Date.now() - t0) / 1000)}s`)+}+console.log(renderTable(rows))+const n = s => rows.filter(r => r.status === s).length+console.log(`\ncli=${cli.label} live=${live} pass=${n('pass')} fail=${n('fail')} blocked=${n('blocked')} skipped=${n('skipped')} advisory=${n('advisory')} flaky=${n('flaky')} spend_usd=${spend.usd.toFixed(4)}/${spend.cap}`)+if (arg('json')) writeFileSync(arg('json'), `${redact(JSON.stringify({ cli: cli.label, live, spend: spend.usd, rows }, null, 2))}\n`)+process.exit(n('fail') ? 1 : 0)diff --git a/scripts/e2e/leg-claude.mjs b/scripts/e2e/leg-claude.mjsnew file mode 100644index 0000000000..a8f0b7cdaa--- /dev/null+++ b/scripts/e2e/leg-claude.mjs@@ -0,0 +1,141 @@+// Claude Code leg (ADR-490). Keyless: init, mods doctor, the generated hook commands, the MCP server round trip.+// Live (RUFLO_E2E_LIVE=1): a real headless `claude -p` (haiku) in an isolated HOME/CLAUDE_CONFIG_DIR with the mods loaded from this checkout.+// Auth: ONLY the access token is copied into the throwaway config (no refresh token, so the real login cannot rotate); shredded at the end.+import { spawn } from 'node:child_process'+import { mkdirSync, writeFileSync, readFileSync, readdirSync, statSync, chmodSync, existsSync } from 'node:fs'+import { join, resolve } from 'node:path'+import { homedir } from 'node:os'+import { recorder, sandbox, run, mcpClient, spend, redact, addSecret, readJson } from './lib.mjs'++const REPO = resolve(new URL('../..', import.meta.url).pathname)+const CANARY = `e2ecanary${Math.random().toString(36).slice(2, 8)}`++export async function claudeLeg({ cli, live }) {+ const rec = recorder('claude')+ const sb = sandbox('e2e-claude.')+ const proj = sb.project('proj')+ await run('git', ['init', '-q'], { cwd: proj, env: sb.env })+ try {+ const init = await run(cli.cmd, [...cli.args, 'init', '--no-plugin-install', '--no-signup', '--no-global'], { cwd: proj, env: sb.env, timeout: 240_000 })+ const settings = readJson(join(proj, '.claude/settings.json'))+ rec.check('init: exits 0 and writes .claude/settings.json + .mcp.json', init.code === 0 && !!settings && existsSync(join(proj, '.mcp.json')), `exit=${init.code} ${init.err.slice(-160)}`)+ const events = Object.keys(settings?.hooks ?? {})+ rec.check('init: lifecycle hooks registered (PreToolUse, PostToolUse, UserPromptSubmit, SessionStart)', ['PreToolUse', 'PostToolUse', 'UserPromptSubmit', 'SessionStart'].every(e => events.includes(e)), events.join(','))+ const cmds = Object.values(settings?.hooks ?? {}).flat().flatMap(g => g.hooks ?? []).map(h => h.command ?? '')+ rec.check('init: no hook command goes through `cmd /c` on this platform (#4045)', process.platform === 'win32' || !cmds.some(c => /\bcmd\s+\/c\b/i.test(c)), `${cmds.length} hook commands`)++ const doctor = await run(cli.cmd, [...cli.args, 'mods', 'doctor'], { cwd: proj, env: sb.env, timeout: 120_000 })+ rec.check('mods doctor: exits 0 and reports ruflo-mods enabled + the classic handshake', doctor.code === 0 && /ruflo-mods plugin: enabled/.test(doctor.out) && /classic handshake/.test(doctor.out), doctor.out.split('\n').slice(0, 2).join(' | '))+ rec.check('mods doctor: says plainly when the marketplace is not cloned (headless -p does not clone it)', /not cloned|loads once Claude Code has cloned/.test(doctor.out), (doctor.out.match(/!.*marketplace.*/) ?? [''])[0])++ const pre = settings?.hooks?.PreToolUse?.find(g => g.matcher === 'Bash')?.hooks?.[0]+ if (pre?.command) {+ const t0 = Date.now()+ const hook = await run('sh', ['-c', pre.command], { cwd: proj, env: { ...sb.env, CLAUDE_PROJECT_DIR: proj }, input: JSON.stringify({ hook_event_name: 'PreToolUse', tool_name: 'Bash', tool_input: { command: 'echo hi >out.txt' }, session_id: 'e2e' }), timeout: 20_000 })+ rec.check('hooks: the generated PreToolUse(Bash) command runs, exits 0 within its declared timeout', hook.code === 0 && Date.now() - t0 < (pre.timeout ?? 5000) + 3000, `exit=${hook.code} ${Date.now() - t0}ms timeout=${pre.timeout}`)+ rec.check('hooks: stdin JSON text is not executed or redirected into files (#4045 class)', !existsSync(join(proj, 'out.txt')) && !readdirSync(proj).some(f => /^cnt\.set|^MAX_/.test(f)), 'no stray files')+ } else rec.fail('hooks: PreToolUse(Bash) command present', 'not found in settings.json')++ const c = await mcpClient(cli.cmd, [...cli.args, 'mcp', 'start'], { cwd: proj, env: sb.env })+ try {+ const tools = await c.tools()+ rec.check('mcp: tools/list answers with the ruflo surface (>= 100 tools)', tools.length >= 100, `${tools.length} tools`)+ const caps = c.init.result?.capabilities ?? {}+ const rl = caps.resources ? await c.rpc('resources/list', {}) : { result: {} }+ rec.check('mcp: every capability initialize advertises is served (resources/list answers instead of -32601; Codex asks for it first)', !caps.resources || (!rl.error && Array.isArray(rl.result?.resources)), `advertised=${JSON.stringify(caps)} resources/list=${rl.error ? `error ${rl.error.code}` : 'ok'}`)+ const st = await c.tool('memory_store', { key: `k-${CANARY}`, value: `value-${CANARY}`, namespace: 'e2e' })+ const se = await c.tool('memory_search', { query: `value-${CANARY}`, namespace: 'e2e' })+ rec.check('mcp: memory_store then memory_search round trip finds the stored value', st.json?.success === true && (se.json?.results ?? []).some(r => r.key === `k-${CANARY}`), `stored=${st.json?.stored} hits=${se.json?.total}`)+ const tc = await c.tool('task_create', { type: 'feature', description: `e2e ${CANARY}` })+ const tl = await c.tool('task_list', {})+ rec.check('mcp: task_create then task_list shows the task', !!tc.json?.taskId && tl.text.includes(tc.json.taskId), `taskId=${tc.json?.taskId}`)+ await c.tool('task_assign', { taskId: tc.json?.taskId, agentIds: ['__proto__'] })+ const after = await c.tool('memory_search', { query: `value-${CANARY}`, namespace: 'e2e' })+ rec.check('mcp: a prototype-named agent id in task_assign leaves the server serving (#3967; pollution itself is covered by the unit test)', after.json?.total >= 1 && !after.isError, `memory_search hits=${after.json?.total}`)+ } finally { c.close() }+ } catch (e) { rec.fail('keyless leg ran to completion', redact(String(e?.stack ?? e)).slice(0, 300)) }++ if (!live) { rec.skipped('live: headless claude -p session with mods + MCP + hooks', 'RUFLO_E2E_LIVE not set'); sb.cleanup(); return rec.rows }+ await liveClaude({ cli, rec, sb, proj })+ sb.cleanup()+ return rec.rows+}++function claudeSession({ env, cwd, args, prompts, timeout = 240_000 }) {+ return new Promise(async resolveSession => {+ const p = spawn('claude', args, { cwd, env, stdio: ['pipe', 'pipe', 'pipe'] })+ let buf = '', err = '', onResult+ const events = []+ p.stderr.on('data', d => { err += d })+ p.stdout.on('data', d => {+ buf += d+ let i+ while ((i = buf.indexOf('\n')) >= 0) {+ const line = buf.slice(0, i); buf = buf.slice(i + 1)+ try { const m = JSON.parse(line); events.push(m); if (m.type === 'result' && onResult) onResult(m) } catch { /* not json */ }+ }+ })+ const results = []+ for (const text of prompts) {+ const done = new Promise(r => { onResult = r })+ p.stdin.write(`${JSON.stringify({ type: 'user', message: { role: 'user', content: text } })}\n`)+ results.push(await Promise.race([done, new Promise(r => setTimeout(() => r({ result: '(timeout)', is_error: true }), timeout))]))+ }+ p.stdin.end()+ await new Promise(r => { const t = setTimeout(() => (p.kill('SIGKILL'), r()), 15_000); p.on('close', () => (clearTimeout(t), r())) })+ resolveSession({ results, events, err })+ })+}++async function liveClaude({ cli, rec, sb, proj }) {+ const cfg = join(sb.home, '.claude')+ mkdirSync(cfg, { recursive: true })+ let tokenOk = false+ try {+ const real = JSON.parse(readFileSync(join(homedir(), '.claude/.credentials.json'), 'utf8')).claudeAiOauth+ addSecret(real.accessToken)+ writeFileSync(join(cfg, '.credentials.json'), JSON.stringify({ claudeAiOauth: { accessToken: real.accessToken, expiresAt: real.expiresAt, scopes: real.scopes, subscriptionType: real.subscriptionType } }), { mode: 0o600 })+ chmodSync(join(cfg, '.credentials.json'), 0o600)+ tokenOk = Date.now() < Number(real.expiresAt)+ } catch { /* handled below */ }+ if (!tokenOk) return rec.blocked('live: headless claude -p session', 'no unexpired Claude access token in ~/.claude/.credentials.json')+ writeFileSync(join(sb.home, '.claude.json'), JSON.stringify({ hasCompletedOnboarding: true, numStartups: 5 }))+ const env = { ...sb.env, CLAUDE_CONFIG_DIR: cfg, CLAUDE_CODE_ENABLE_FUNCTION_HOOKS: '1' }+ const mcp = JSON.stringify({ mcpServers: { ruflo: { command: cli.cmd, args: [...cli.args, 'mcp', 'start'], env: { RUFLO_NO_SKILLS_SH: '1' } } } })+ const base = ['-p', '--input-format', 'stream-json', '--output-format', 'stream-json', '--verbose', '--model', 'haiku', '--max-budget-usd', '0.6',+ '--plugin-dir', join(REPO, 'plugins/ruflo-mods'), '--plugin-dir', join(REPO, 'plugins/ruflo-console'), '--mcp-config', mcp, '--strict-mcp-config', '--setting-sources', 'project,local',+ '--append-system-prompt', 'Answer exactly as asked. No commentary.']++ // L1: MCP tools + classic hooks + the ledger, one session.+ const s1 = await claudeSession({ env, cwd: proj, args: [...base, '--allowedTools', 'mcp__ruflo__memory_store,mcp__ruflo__memory_search', '--disallowedTools', 'Bash,Edit,Write,WebFetch,WebSearch,Task'],+ prompts: [`Call mcp__ruflo__memory_store with key "live-${CANARY}", value "live-value-${CANARY}", namespace "e2elive". Then call mcp__ruflo__memory_search with query "live-value-${CANARY}" and namespace "e2elive". Reply with the key you found, or NOT_FOUND.`] })+ const r1 = s1.results[0]+ spend.add(r1?.total_cost_usd)+ rec.check('live: haiku calls the ruflo MCP tools and finds the stored value', !r1?.is_error && String(r1?.result).includes(`live-${CANARY}`), redact(String(r1?.result)).slice(0, 160), { costUsd: r1?.total_cost_usd })+ const tooluses = s1.events.filter(e => e.type === 'assistant').flatMap(e => e.message?.content ?? []).filter(b => b.type === 'tool_use').map(b => b.name)+ rec.check('live: both tool calls went through the ruflo server', tooluses.includes('mcp__ruflo__memory_store') && tooluses.includes('mcp__ruflo__memory_search'), tooluses.join(','))+ const sys = s1.events.find(e => e.type === 'system' && e.subtype === 'init')+ rec.check('live: ruflo-mods and ruflo-console are loaded from this checkout', JSON.stringify(sys?.plugins ?? []).includes('ruflo-mods') && JSON.stringify(sys?.plugins ?? []).includes('ruflo-console'), JSON.stringify((sys?.plugins ?? []).map(p => p.name ?? p)).slice(0, 160))+ const hookEv = s1.events.filter(e => e.type === 'system' && /hook/.test(String(e.subtype)))+ rec.check('live: Claude Code ran the project hooks (hook_started/hook_response events)', hookEv.length > 0, `${hookEv.length} hook events: ${[...new Set(hookEv.map(e => e.subtype))].join(',')}`)++ // L2: cost ledger sees the run (cost-tracker's own reader, pointed at the throwaway config).+ process.env.CLAUDE_CONFIG_DIR = cfg+ const { claudeRows } = await import(`${REPO}/plugins/ruflo-cost-tracker/scripts/_ledger.mjs`)+ const rows = [...claudeRows({ sinceMs: Date.now() - 3_600_000 })]+ delete process.env.CLAUDE_CONFIG_DIR+ rec.check('live: cost-tracker ledger counts the session (>=1 assistant row, tokens > 0)', rows.length >= 1 && rows.reduce((a, r) => a + r.input + r.output + r.cache_read, 0) > 0, `${rows.length} rows, models=${[...new Set(rows.map(r => r.model))].join(',')}`)++ // L3: console_state model-facing sanity + costHardStop (needs 2 turns: the first crosses the tiny budget, the second tries to spawn a subagent).+ const optsFile = join(sb.home, 'mods-settings.json')+ const o = { options: { costBudgetUsd: 0.00005, costHardStop: true } }+ writeFileSync(optsFile, JSON.stringify({ pluginConfigs: { 'ruflo-mods@inline': o, 'ruflo-mods': o } }))+ const s2 = await claudeSession({ env, cwd: proj, args: [...base, '--settings', optsFile, '--allowedTools', 'mcp__ruflo-console__console_state,Task,Agent', '--disallowedTools', 'Bash,Edit,Write,WebFetch,WebSearch'],+ prompts: ['Call mcp__ruflo-console__console_state once and reply with the first 60 characters of what it returned.', 'Now use the Task (Agent) tool to spawn one subagent that replies with the word hi. Report exactly what happened, including any refusal text.'] })+ s2.results.forEach(r => spend.add(r?.total_cost_usd))+ const consoleOut = s2.events.filter(e => e.type === 'user').flatMap(e => e.message?.content ?? []).filter(b => b.type === 'tool_result').map(b => JSON.stringify(b.content)).join('\n')+ rec.check('live: console_state is model-safe (no ESC/OSC bytes, no other project paths, bounded)', consoleOut.length > 0 && !/\\u001b|\\x1b|\\u009b/i.test(consoleOut) && !consoleOut.includes(homedir()) && consoleOut.length < 20_000, `${consoleOut.length} chars`)+ const toolResults2 = s2.events.filter(e => e.type === 'user').flatMap(e => e.message?.content ?? []).filter(b => b.type === 'tool_result' && b.is_error !== undefined || b.type === 'tool_result').map(b => JSON.stringify(b.content)).join('\n')+ const denied = /new agents are halted|costHardStop/i.test(toolResults2)+ rec.check('live: costHardStop refuses the new subagent past the budget (the deny text is in the tool_result, not just the model\'s words)', denied, redact(toolResults2.split('\n').find(l => /halted|costHardStop|denied/i.test(l)) ?? toolResults2).slice(0, 200))+}diff --git a/scripts/e2e/leg-codex.mjs b/scripts/e2e/leg-codex.mjsnew file mode 100644index 0000000000..a971d8cb0b--- /dev/null+++ b/scripts/e2e/leg-codex.mjs@@ -0,0 +1,143 @@+// Codex leg (ADR-490). PINNED to Codex 0.162.0: the 0.162.1 build crashes with a #GP (stack misalignment), so this leg calls the 0.162.0 binary by+// path, never `codex` from PATH and never touching the `current` links. Isolated CODEX_HOME; auth is copied WITHOUT the refresh token.+import { mkdirSync, writeFileSync, readFileSync, readdirSync, existsSync } from 'node:fs'+import { join, resolve } from 'node:path'+import { homedir } from 'node:os'+import { recorder, sandbox, run, spend, redact } from './lib.mjs'+import { findOpenRouterKey } from './leg-openrouter.mjs'++const REPO = resolve(new URL('../..', import.meta.url).pathname)+const PIN = '0.162.0'++function findCodex() {+ if (process.env.RUFLO_E2E_CODEX_BIN) return process.env.RUFLO_E2E_CODEX_BIN+ const dir = join(homedir(), '.codex/packages/standalone/releases')+ try { const d = readdirSync(dir).find(n => n.startsWith(`${PIN}-`)); return d ? join(dir, d, 'bin/codex') : undefined } catch { return undefined }+}++export async function codexLeg({ cli, live }) {+ const rec = recorder('codex')+ const bin = findCodex()+ const ver = bin && existsSync(bin) ? (await run(bin, ['--version'], { timeout: 20_000 })).out.trim() : ''+ if (!ver.endsWith(PIN)) { rec.blocked('codex 0.162.0 binary available', `pinned binary not found (looked for ${PIN}); 0.162.1 is excluded on purpose (#GP crash)`); return rec.rows }+ rec.pass('codex binary is the pinned 0.162.0 (not the crashing 0.162.1)', ver)+ const sb = sandbox('e2e-codex.')+ const codexHome = join(sb.home, '.codex')+ mkdirSync(codexHome, { recursive: true })+ const env = { ...sb.env, CODEX_HOME: codexHome }+ const proj = sb.project('proj')+ await run('git', ['init', '-q'], { cwd: proj, env })+ try {+ const init = await run(cli.cmd, [...cli.args, 'init', '--dual', '--no-plugin-install', '--no-signup', '--no-global'], { cwd: proj, env, timeout: 300_000 })+ rec.check('init --dual: exits 0 and writes AGENTS.md + .agents/config.toml', init.code === 0 && existsSync(join(proj, 'AGENTS.md')) && existsSync(join(proj, '.agents/config.toml')), `exit=${init.code} ${init.err.slice(-120)}`)+ const local = existsSync(join(proj, '.codex/config.toml')) ? readFileSync(join(proj, '.codex/config.toml'), 'utf8') : ''+ const permissive = /^\s*sandbox_mode\s*=\s*"danger-full-access"/m.test(local) && /^\s*approval_policy\s*=\s*"never"/m.test(local)+ rec.check('init --dual: the generated .codex/config.toml does not default to danger-full-access + approval never', !permissive, permissive ? 'ADVISORY: gitignored local override ships sandbox_mode=danger-full-access, approval_policy=never, web_search=live' : 'restrictive default', permissive ? { advisory: true } : {})++ // `init --dual` registers the ruflo marketplace and installs ruflo-core@ruflo itself (#2801). On a fresh CODEX_HOME that must just work.+ const afterInit = await run(bin, ['plugin', 'list'], { cwd: proj, env, timeout: 60_000 })+ rec.check('init --dual on a fresh CODEX_HOME leaves ruflo-core@ruflo installed (marketplace clone must outlast the init timeout)', /ruflo-core@ruflo\s+installed/.test(afterInit.out), (afterInit.out.match(/ruflo-core@ruflo.*/) ?? [redact(init.out.match(/Failed to install[^\n]*/)?.[0] ?? 'not listed')])[0].slice(0, 180))+ // Then swap in the CHECKOUT as a local marketplace, so the remaining assertions test this tree, not main on GitHub.+ await run(bin, ['plugin', 'marketplace', 'remove', 'ruflo'], { cwd: proj, env, timeout: 60_000 })+ const mk = await run(bin, ['plugin', 'marketplace', 'add', REPO], { cwd: proj, env, timeout: 120_000 })+ rec.check('codex plugin marketplace add <checkout>: accepted', mk.code === 0, redact(`${mk.out}${mk.err}`).split('\n').filter(l => !/PATH aliases/.test(l)).join(' ').slice(0, 160))+ const list = await run(bin, ['plugin', 'list'], { cwd: proj, env, timeout: 60_000 })+ rec.check('codex sees the ruflo plugins (ruflo-core, ruflo-swarm) from the Claude-format marketplace.json', /ruflo-core@ruflo/.test(list.out) && /ruflo-swarm@ruflo/.test(list.out), `${(list.out.match(/@ruflo/g) ?? []).length} plugins listed`)+ const add = await run(bin, ['plugin', 'add', 'ruflo-swarm@ruflo'], { cwd: proj, env, timeout: 60_000 })+ const installed = /Installed plugin root: (.+)/.exec(add.out)?.[1]+ rec.check('codex plugin add ruflo-swarm@ruflo installs, and its Codex hook manifest is present and valid JSON', add.code === 0 && !!installed && (() => { try { JSON.parse(readFileSync(join(installed, 'hooks/codex-hooks.json'), 'utf8')); return true } catch { return false } })(), installed ? 'installed' : redact(add.err).slice(0, 140))+ await run(bin, ['plugin', 'add', 'ruflo-core@ruflo'], { cwd: proj, env, timeout: 60_000 }) // its lifecycle hooks (telemetry only) are what a Codex user gets from init --dual+ const hooks = (() => { try { return JSON.parse(readFileSync(join(REPO, 'plugins/ruflo-swarm/hooks/codex-hooks.json'), 'utf8')).hooks } catch { return undefined } })()+ rec.check('ruflo-swarm Codex manifest is a deliberate no-op (hooks == {}), so no ruflo policy runs on Codex through it', hooks && Object.keys(hooks).length === 0, JSON.stringify(hooks))+ // Registers ruflo as an MCP server exactly as a user would, then reads it back.+ const mcp = await run(bin, ['mcp', 'add', 'ruflo', '--', ...(cli.cmd === 'npx' ? ['npx'] : [cli.cmd]), ...cli.args, 'mcp', 'start'], { cwd: proj, env, timeout: 60_000 })+ const got = await run(bin, ['mcp', 'list'], { cwd: proj, env, timeout: 60_000 })+ rec.check('codex mcp add/list: ruflo registered', mcp.code === 0 && /ruflo/.test(got.out), got.out.split('\n').find(l => /ruflo/.test(l)) ?? redact(mcp.err).slice(0, 120))+ const led = await run(process.execPath, [join(REPO, 'plugins/ruflo-cost-tracker/scripts/test-ledger.mjs')], { cwd: REPO, env: { ...process.env }, timeout: 120_000 })+ rec.check("cost-tracker: Codex rollout ledger tests pass, incl. session ownership (#4047/#4048)", led.code === 0, led.out.trim().split('\n').slice(-1)[0] || led.err.slice(0, 120))+ } catch (e) { rec.fail('keyless leg ran to completion', redact(String(e?.stack ?? e)).slice(0, 300)) }++ if (!live) { rec.skipped('live: codex exec with ruflo MCP + hook-event probe', 'RUFLO_E2E_LIVE not set'); sb.cleanup(); return rec.rows }+ await liveCodex({ bin, cli, rec, sb, env, codexHome, proj })+ sb.cleanup()+ return rec.rows+}++const MODEL = process.env.RUFLO_E2E_CODEX_MODEL ?? 'openai/gpt-5.1-codex-mini' // gpt-5-mini often answered via read_mcp_resource instead of calling the tools; this one called them 3/3++async function usageNow(key) {+ try { const j = await fetch('https://openrouter.ai/api/v1/key', { headers: { authorization: `Bearer ${key}` } }).then(r => r.json()); return Number(j?.data?.usage) } catch { return NaN }+}++async function liveCodex({ bin, cli, rec, sb, env, codexHome, proj }) {+ // Default live path: Codex 0.162.0 with OpenRouter as its model provider (Responses wire). It needs no ChatGPT login, so it cannot disturb the+ // real one: the ChatGPT refresh token is single-use and a throwaway home that refreshed it would invalidate ~/.codex/auth.json. The+ // ChatGPT-auth variant exists only behind RUFLO_E2E_CODEX_AUTH=chatgpt, and is documented in ADR-490 as unsafe to run unattended.+ const key = findOpenRouterKey()+ if (!key) return rec.blocked('live: codex exec via OpenRouter', 'no OPENROUTER_API_KEY in env or GCP Secret Manager')+ env.OPENROUTER_API_KEY = key+ const before = await usageNow(key)+ // Probe hook: records which Codex hook events fire (event name only), so the mods-policy table below is evidence, not documentation.+ const probe = join(sb.home, 'hook-probe.mjs'), log = join(sb.home, 'hook-events.log')+ writeFileSync(probe, `import{appendFileSync}from'node:fs';let s='';process.stdin.on('data',d=>s+=d).on('end',()=>{let j={};try{j=JSON.parse(s)}catch{}appendFileSync(${JSON.stringify(log)},(j.hook_event_name||process.argv[2])+'\\n');process.stdout.write('{}')})\n`)+ const ev = ['SessionStart', 'UserPromptSubmit', 'PreToolUse', 'PostToolUse', 'Stop', 'PreCompact', 'SessionEnd', 'SubagentStart', 'SubagentStop', 'PermissionRequest']+ writeFileSync(join(codexHome, 'hooks.json'), JSON.stringify({ hooks: Object.fromEntries(ev.map(e => [e, [{ hooks: [{ type: 'command', command: `${process.execPath} ${probe} ${e}`, timeout: e === 'SessionEnd' ? 3 : 10 }] }]])) }))+ writeFileSync(join(codexHome, 'config.toml'), [`model = "${MODEL}"`, 'model_provider = "openrouter"', 'model_reasoning_effort = "low"', '[features]', 'hooks = true', '', '[model_providers.openrouter]', 'name = "OpenRouter"', 'base_url = "https://openrouter.ai/api/v1"', 'env_key = "OPENROUTER_API_KEY"', 'wire_api = "responses"', '', '[mcp_servers.ruflo]', `command = ${JSON.stringify(cli.cmd)}`, `args = ${JSON.stringify([...cli.args, 'mcp', 'start'])}`, 'startup_timeout_sec = 120', 'default_tools_approval_mode = "approve"', ''].join('\n'))+ const canary = `cx${Math.random().toString(36).slice(2, 8)}`+ const t0 = Date.now()+ const prompt = `Use the MCP tool memory_store from the server named ruflo (call the tool directly; do not list resources first) with key "${canary}", value "codex-value-${canary}", namespace "e2elive". Then call memory_search from the same server with query "codex-value-${canary}" and namespace "e2elive". Reply with only the key you found, or NOT_FOUND.`+ let r, events, calls, attempts = 0+ do {+ attempts+++ r = await run(bin, ['exec', '--json', '--skip-git-repo-check', '--dangerously-bypass-hook-trust', '-s', 'read-only', prompt], { cwd: proj, env, timeout: 300_000 })+ events = r.out.split('\n').map(l => { try { return JSON.parse(l) } catch { return undefined } }).filter(Boolean)+ calls = events.filter(e => e.type === 'item.completed' && e.item?.type === 'mcp_tool_call' && e.item.server === 'ruflo')+ } while (!calls.some(e => !e.item.error) && attempts < 2) // one retry: a small model sometimes answers without calling the tool; the harness records the attempts+ const text = redact(r.out)+ const final = [...events].reverse().map(e => e.item?.text ?? e.message ?? '').find(Boolean) ?? ''+ const finalMsg = [...events].reverse().find(e => e.item?.type === 'agent_message')?.item?.text ?? ''+ rec.check('live: codex exec (OpenRouter provider, read-only) reports the stored key it found through the ruflo MCP tools', r.code === 0 && String(finalMsg).includes(canary), `exit=${r.code} ${Math.round((Date.now() - t0) / 1000)}s attempts=${attempts} final=${String(final).slice(0, 80)}`)+ const okTools = calls.filter(e => !e.item.error).map(e => e.item.tool)+ rec.check('live: Codex made real mcp_tool_call items to the ruflo server for memory_store and memory_search (not just words in the reply)', okTools.includes('memory_store') && okTools.some(t => t.startsWith('memory_search')), `calls: ${calls.map(e => `${e.item.tool}${e.item.error ? '(error)' : ''}`).join(', ') || 'none'}; attempts=${attempts}`)+ const hookErrs = events.filter(e => e.item?.type === 'error' && /hook/i.test(e.item.message ?? '') && !/dangerously-bypass-hook-trust|clamping/.test(e.item.message ?? '')).map(e => e.item.message)+ rec.check('live: the installed ruflo-core@ruflo plugin hooks run under Codex without a hook error (#2716/#2816 class)', hookErrs.length === 0, hookErrs.length ? redact(hookErrs[0]).slice(0, 160) : 'no hook error items in the event stream')+ const fired = existsSync(log) ? [...new Set(readFileSync(log, 'utf8').split('\n').filter(Boolean))] : []+ rec.check('live: Codex command hooks fire (user-level hooks.json, with --dangerously-bypass-hook-trust in this throwaway home)', fired.length > 0, `fired: ${fired.join(',') || 'none'}; not fired: ${ev.filter(e => !fired.includes(e)).join(',')}`, { firedEvents: fired })+ const after = await usageNow(key)+ const tokens = [...events].reverse().find(e => e.type === 'turn.completed')?.usage+ const est = tokens ? (tokens.input_tokens * 1.0 + tokens.output_tokens * 5.0) / 1e6 : 0.01 // conservative upper bound ($1/$5 per M)+ spend.add(Number.isFinite(before) && Number.isFinite(after) && after - before > 0 ? after - before : est)+ process.env.CODEX_HOME = codexHome+ const { codexRows } = await import(`${REPO}/plugins/ruflo-cost-tracker/scripts/_ledger.mjs`)+ const rows = [...codexRows({ sinceMs: Date.now() - 3_600_000 })]+ delete process.env.CODEX_HOME+ rec.check('live: cost-tracker counts the Codex run (>=1 row with tokens, single owning session)', rows.length >= 1 && rows.some(x => x.input + x.output > 0) && new Set(rows.map(x => x.session)).size === 1, `${rows.length} rows, models=${[...new Set(rows.map(x => x.model))].join(',')}`)++ // Policy probe: can a Codex command hook do what ruflo-mods does on Claude Code? (route -> UserPromptSubmit additionalContext; guard -> PreToolUse deny.)+ const policy = join(sb.home, 'hook-policy.mjs'), plog = join(sb.home, 'policy.log')+ const ctxMark = `CTX-${canary}`, bad = `marker-${canary}`+ writeFileSync(policy, `import{appendFileSync}from'node:fs';let s='';process.stdin.on('data',d=>s+=d).on('end',()=>{let j={};try{j=JSON.parse(s)}catch{}const e=j.hook_event_name||process.argv[2];appendFileSync(${JSON.stringify(plog)},e+'\\n');+if(e==='UserPromptSubmit'){process.stdout.write(JSON.stringify({hookSpecificOutput:{hookEventName:'UserPromptSubmit',additionalContext:'The routing marker for this session is ${ctxMark}.'}}));return}+if(e==='PreToolUse'&&s.includes(${JSON.stringify(bad)})){process.stdout.write(JSON.stringify({hookSpecificOutput:{hookEventName:'PreToolUse',permissionDecision:'deny',permissionDecisionReason:'ruflo guard e2e: blocked'}}));return}+process.stdout.write('{}')})\n`)+ writeFileSync(join(codexHome, 'hooks.json'), JSON.stringify({ hooks: { UserPromptSubmit: [{ hooks: [{ type: 'command', command: `${process.execPath} ${policy} UserPromptSubmit`, timeout: 10 }] }], PreToolUse: [{ hooks: [{ type: 'command', command: `${process.execPath} ${policy} PreToolUse`, timeout: 10 }] }] } }))+ const probe2 = `First run the shell command: echo ${bad}. Then reply with two lines: line 1 the routing marker for this session if you were given one (else NONE), line 2 the output of the shell command (else BLOCKED).`+ let ev2, msg2 = '', tries = 0+ do {+ tries+++ const r2 = await run(bin, ['exec', '--json', '--skip-git-repo-check', '--dangerously-bypass-hook-trust', '-s', 'read-only', probe2], { cwd: proj, env, timeout: 300_000 })+ ev2 = r2.out.split('\n').map(l => { try { return JSON.parse(l) } catch { return undefined } }).filter(Boolean)+ msg2 = String([...ev2].reverse().find(e => e.item?.type === 'agent_message')?.item?.text ?? '')+ const t2 = [...ev2].reverse().find(e => e.type === 'turn.completed')?.usage+ spend.add(t2 ? (t2.input_tokens * 1.0 + t2.output_tokens * 5.0) / 1e6 : 0.01)+ } while (!msg2.includes(ctxMark) && tries < 2) // model-dependent: the hook always fires, but a small model may not repeat the marker+ rec.check('live: a Codex UserPromptSubmit hook can inject context the model then uses (ruflo-mods route equivalent)', msg2.includes(ctxMark), `${redact(msg2).replace(/\s+/g, ' ').slice(0, 120)} (tries=${tries}; hook fired=${(existsSync(plog) ? readFileSync(plog, 'utf8') : '').includes('UserPromptSubmit')})`, { equivalent: 'route' })+ const cmd = ev2.filter(e => e.type === 'item.completed' && /command_execution|exec/.test(e.item?.type ?? '')).map(e => e.item)+ const ran = cmd.some(c => String(c.aggregated_output ?? c.output ?? '').includes(bad) && !/block|denied/i.test(JSON.stringify(c)))+ const fired2 = existsSync(plog) ? readFileSync(plog, 'utf8').split('\n').filter(Boolean) : []+ const line2 = msg2.split('\n').slice(1).join(' ')+ if (!fired2.includes('PreToolUse')) rec.flaky('live: a Codex PreToolUse hook can veto a shell tool call (ruflo-mods guard equivalent)', 'the model never attempted the shell call this run, so the hook had nothing to veto; rerun')+ else rec.check('live: a Codex PreToolUse hook can veto a shell tool call (ruflo-mods guard equivalent)', !ran && !line2.includes(bad), `PreToolUse fired=${fired2.includes('PreToolUse')}; reply line 2: ${redact(line2).slice(0, 80)}`, { equivalent: 'guard' })+ rec.skipped('live: PreCompact / SubagentStart / SubagentStop (compactCarry, costHardStop equivalents)', 'no non-interactive way to force a compaction or a subagent spawn in `codex exec`; hook events exist in the binary but were not exercised')++}diff --git a/scripts/e2e/leg-openrouter.mjs b/scripts/e2e/leg-openrouter.mjsnew file mode 100644index 0000000000..8c48ec3a40--- /dev/null+++ b/scripts/e2e/leg-openrouter.mjs@@ -0,0 +1,69 @@+// OpenRouter leg (ADR-490). Keyless part: ruflo's own provider path (agent_spawn + agent_execute) against a local OpenAI-compatible stub.+// Live part (RUFLO_E2E_LIVE=1): the same path against openrouter.ai with a key read into this process only, redacted everywhere.+import { execFileSync } from 'node:child_process'+import { recorder, sandbox, mcpClient, stubOpenRouter, addSecret, redact, spend } from './lib.mjs'++/** Key lookup: env first, then GCP Secret Manager (ruv-dev, then cognitum-20260110). Returns undefined if none; never prints. */+export function findOpenRouterKey() {+ if (process.env.OPENROUTER_API_KEY) { addSecret(process.env.OPENROUTER_API_KEY); return process.env.OPENROUTER_API_KEY }+ try {+ const acct = execFileSync('gcloud', ['config', 'get-value', 'account'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim()+ if (acct !== '[email protected]') return undefined+ } catch { return undefined }+ for (const project of ['ruv-dev', 'cognitum-20260110']) {+ try {+ const k = execFileSync('gcloud', ['secrets', 'versions', 'access', 'latest', '--secret=OPENROUTER_API_KEY', `--project=${project}`], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim()+ if (k) { addSecret(k); return k }+ } catch { /* try the next project */ }+ }+ return undefined+}++const text = r => `${r.text}`.replace(/\s+/g, ' ')++export async function openrouterLeg({ cli, live }) {+ const rec = recorder('openrouter')+ const sb = sandbox('e2e-or.')+ const stub = await stubOpenRouter({ reply: 'STUB-HELLO' })+ const keyless = { ...sb.env, OPENROUTER_API_KEY: 'sk-or-v1-0000000000000000stub', OPENROUTER_BASE_URL: stub.url, RUFLO_PROVIDER: 'openrouter' }+ let c+ try {+ c = await mcpClient(cli.cmd, [...cli.args, 'mcp', 'start'], { cwd: sb.project(), env: keyless })+ await c.tool('agent_spawn', { agentType: 'coder', agentId: 'e2e-or' })+ const r = await c.tool('agent_execute', { agentId: 'e2e-or', prompt: 'say hi' })+ rec.check('stub: agent_execute returns the provider reply', r.json?.success === true && r.json?.output === 'STUB-HELLO', text(r).slice(0, 200))+ rec.check('stub: request went to the OpenAI-compatible path with a bearer header', stub.seen.at(-1)?.url === '/v1/chat/completions' && stub.seen.at(-1)?.hasAuth === true, JSON.stringify(stub.seen.at(-1)))+ rec.check('stub: usage tokens surfaced', r.json?.usage?.totalTokens === 15, JSON.stringify(r.json?.usage))+ rec.check('stub: key never echoed in the tool output', !text(r).includes('sk-or-v1-0000000000000000stub'), 'checked output text')+ for (const status of [429, 500]) {+ const bad = await stubOpenRouter({ status })+ const c2 = await mcpClient(cli.cmd, [...cli.args, 'mcp', 'start'], { cwd: sb.project('p2'), env: { ...keyless, OPENROUTER_BASE_URL: bad.url } })+ await c2.tool('agent_spawn', { agentType: 'coder', agentId: 'e2e-or' })+ const e = await c2.tool('agent_execute', { agentId: 'e2e-or', prompt: 'x' })+ rec.check(`stub: provider ${status} is reported as a failure, not a success`, e.json?.success === false && /openrouter|${status}|stub/i.test(text(e)) && !text(e).includes('0000000000000000stub'), text(e).slice(0, 200))+ c2.close(); await bad.close()+ }+ } catch (e) { rec.fail('stub leg ran to completion', String(e?.message ?? e)) }+ finally { c?.close(); await stub.close() }++ if (!live) { rec.skipped('live: OpenRouter round trip', 'RUFLO_E2E_LIVE not set'); sb.cleanup(); return rec.rows }+ const key = findOpenRouterKey()+ if (!key) { rec.blocked('live: OpenRouter round trip', 'no OPENROUTER_API_KEY in env or GCP Secret Manager (or gcloud account is not [email protected])'); sb.cleanup(); return rec.rows }+ try {+ const kr = await fetch('https://openrouter.ai/api/v1/key', { headers: { authorization: `Bearer ${key}` } })+ rec.check('live: key is accepted by OpenRouter (GET /api/v1/key)', kr.status === 200, `HTTP ${kr.status}`)+ const env = { ...sb.env, OPENROUTER_API_KEY: key, RUFLO_PROVIDER: 'openrouter', OPENROUTER_DEFAULT_MODEL: 'anthropic/claude-haiku-4.5' }+ const live1 = await mcpClient(cli.cmd, [...cli.args, 'mcp', 'start'], { cwd: sb.project('live'), env })+ await live1.tool('agent_spawn', { agentType: 'coder', agentId: 'e2e-live' })+ const r = await live1.tool('agent_execute', { agentId: 'e2e-live', prompt: 'Reply with exactly the single word: PONG', maxTokens: 16, temperature: 0 })+ rec.check('live: agent_execute via OpenRouter returns model output', r.json?.success === true && /PONG/i.test(String(r.json?.output)), redact(text(r)).slice(0, 220))+ rec.check('live: usage tokens reported', (r.json?.usage?.totalTokens ?? 0) > 0, JSON.stringify(r.json?.usage))+ rec.check('live: key not present in tool output', !text(r).includes(key), 'checked output text')+ spend.add(0.0001) // two-digit-token calls; the real figure is read from OpenRouter below+ live1.close()+ const gen = await fetch('https://openrouter.ai/api/v1/key', { headers: { authorization: `Bearer ${key}` } }).then(x => x.json()).catch(() => ({}))+ rec.pass('live: account usage readable after the call', `usage_daily=${gen?.data?.usage_daily ?? 'n/a'} (account-wide, shared key)`)+ } catch (e) { rec.fail('live leg ran to completion', redact(String(e?.message ?? e))) }+ sb.cleanup()+ return rec.rows+}diff --git a/scripts/e2e/lib.mjs b/scripts/e2e/lib.mjsnew file mode 100644index 0000000000..c5b5fbb711--- /dev/null+++ b/scripts/e2e/lib.mjs@@ -0,0 +1,125 @@+// Shared helpers for the three-host e2e loop (ADR-490). No dependencies. Nothing here prints a credential: every string that reaches the+// report goes through redact(), which knows the secret VALUES this process loaded plus common token shapes.+import { spawn } from 'node:child_process'+import { createServer } from 'node:http'+import { mkdtempSync, mkdirSync, writeFileSync, rmSync, readFileSync, existsSync } from 'node:fs'+import { join } from 'node:path'+import { tmpdir } from 'node:os'++const secrets = new Set()+export const addSecret = v => { if (typeof v === 'string' && v.length >= 8) secrets.add(v) }+const SHAPES = [/(?<![A-Za-z0-9])sk-or-v1-[A-Za-z0-9_-]{8,}/g, /(?<![A-Za-z0-9])sk-ant-[A-Za-z0-9_-]{8,}/g, /(?<![A-Za-z0-9-])sk-[A-Za-z0-9_-]{20,}/g, /eyJ[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{5,}/g,+ /(Bearer\s+)[A-Za-z0-9._~+/=-]{12,}/gi, /("?(?:access_token|refresh_token|id_token|api[_-]?key|authorization)"?\s*[:=]\s*"?)[^"\s,}]{8,}/gi]+export function redact(s) {+ let out = String(s ?? '')+ for (const v of secrets) out = out.split(v).join('[REDACTED]')+ for (const re of SHAPES) out = out.replace(re, (m, p) => (typeof p === 'string' ? `${p}[REDACTED]` : '[REDACTED]'))+ return out+}++/** Assertion recorder: status is pass | fail | blocked | skipped | flaky. Evidence is redacted and capped. */+export function recorder(leg) {+ const rows = []+ const add = (status, name, evidence = '', extra = {}) => {+ rows.push({ leg, name, status, evidence: redact(evidence).slice(0, 600), ...extra })+ return status === 'pass'+ }+ return {+ rows,+ pass: (name, ev, x) => add('pass', name, ev, x),+ fail: (name, ev, x) => add('fail', name, ev, x),+ blocked: (name, why) => add('blocked', name, why),+ skipped: (name, why) => add('skipped', name, why),+ flaky: (name, why) => add('flaky', name, why),+ check: (name, ok, ev, x) => add(ok ? 'pass' : x?.advisory ? 'advisory' : 'fail', name, ev, x),+ }+}++export const spend = { usd: 0, cap: 6, add(n) { this.usd += Number(n) || 0 }, left() { return this.cap - this.usd } }++export function sandbox(prefix = 'ruflo-e2e.') {+ const home = mkdtempSync(join(tmpdir(), prefix))+ const env = {+ ...process.env, HOME: home, XDG_CONFIG_HOME: join(home, '.config'), XDG_DATA_HOME: join(home, '.local/share'), XDG_CACHE_HOME: join(home, '.cache'),+ RUFLO_NO_SKILLS_SH: '1', CI: process.env.CI ?? '', npm_config_update_notifier: 'false', npm_config_cache: process.env.npm_config_cache ?? join(process.env.HOME ?? home, '.npm'),+ }+ for (const k of ['ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'OPENAI_API_KEY', 'OPENROUTER_API_KEY', 'CODEX_HOME', 'CLAUDE_CONFIG_DIR']) delete env[k]+ const project = (name = 'proj') => { const d = join(home, name); mkdirSync(d, { recursive: true }); return d }+ return { home, env, project, cleanup: () => rmSync(home, { recursive: true, force: true }) }+}++/** Run a command, capture stdout+stderr, hard timeout. Never throws. */+export function run(cmd, args, { cwd, env, timeout = 120_000, input } = {}) {+ return new Promise(resolve => {+ const p = spawn(cmd, args, { cwd, env, stdio: ['pipe', 'pipe', 'pipe'] })+ let out = '', err = '', done = false+ const t = setTimeout(() => { if (!done) p.kill('SIGKILL') }, timeout)+ p.stdout.on('data', d => { out += d }); p.stderr.on('data', d => { err += d })+ p.on('close', (code, sig) => { done = true; clearTimeout(t); resolve({ code, sig, out, err, timedOut: sig === 'SIGKILL' }) })+ p.on('error', e => { done = true; clearTimeout(t); resolve({ code: -1, out, err: String(e), timedOut: false }) })+ if (input != null) p.stdin.write(input)+ p.stdin.end()+ })+}++/** Minimal MCP stdio client (newline-delimited JSON-RPC), as Claude Code and Codex both speak it. */+export async function mcpClient(cmd, args, { cwd, env, timeout = 90_000 } = {}) {+ const p = spawn(cmd, args, { cwd, env, stdio: ['pipe', 'pipe', 'pipe'] })+ let buf = '', stderr = '', n = 0+ const waiters = new Map()+ p.stdout.on('data', d => {+ buf += d+ let i+ while ((i = buf.indexOf('\n')) >= 0) {+ const l = buf.slice(0, i); buf = buf.slice(i + 1)+ try { const m = JSON.parse(l); if (m.id != null && waiters.has(m.id)) { waiters.get(m.id)(m); waiters.delete(m.id) } } catch { /* log line */ }+ }+ })+ p.stderr.on('data', d => { stderr += d })+ const call = (method, params) => new Promise(res => {+ const id = ++n+ waiters.set(id, res)+ p.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', id, method, params })}\n`)+ setTimeout(() => { if (waiters.delete(id)) res({ error: { message: `timeout after ${timeout}ms: ${method}` } }) }, timeout)+ })+ const init = await call('initialize', { protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 'ruflo-e2e', version: '1' } })+ p.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' })}\n`)+ return {+ init, stderr: () => stderr,+ tools: async () => (await call('tools/list', {})).result?.tools ?? [],+ tool: async (name, args = {}) => {+ const r = await call('tools/call', { name, arguments: args })+ const text = r.result?.content?.map(c => c.text).join('') ?? ''+ let json; try { json = JSON.parse(text) } catch { /* plain text */ }+ return { raw: r, text, json, isError: !!r.result?.isError || !!r.error }+ },+ rpc: call, close: () => p.kill('SIGKILL'),+ }+}++/** Local OpenAI-compatible stub (what OpenRouter speaks). Records requests (auth header value is dropped, only its presence kept). */+export async function stubOpenRouter({ reply = 'STUB-OK', status = 200, usage = { prompt_tokens: 12, completion_tokens: 3, total_tokens: 15, cost: 0.000042 } } = {}) {+ const seen = []+ const srv = createServer((req, res) => {+ let body = ''+ req.on('data', d => { body += d })+ req.on('end', () => {+ let j; try { j = JSON.parse(body) } catch { /* not json */ }+ seen.push({ method: req.method, url: req.url, hasAuth: /^Bearer\s+\S+/.test(req.headers.authorization ?? ''), model: j?.model, messages: j?.messages?.length, stream: !!j?.stream })+ res.setHeader('content-type', 'application/json')+ if (status !== 200) { res.statusCode = status; return res.end(JSON.stringify({ error: { message: `stub ${status}`, code: status } })) }+ res.end(JSON.stringify({ id: 'gen-stub-1', model: j?.model ?? 'stub', choices: [{ index: 0, finish_reason: 'stop', message: { role: 'assistant', content: reply } }], usage }))+ })+ })+ await new Promise(r => srv.listen(0, '127.0.0.1', r))+ return { url: `http://127.0.0.1:${srv.address().port}`, seen, close: () => new Promise(r => srv.close(r)) }+}++export const readJson = f => { try { return JSON.parse(readFileSync(f, 'utf8')) } catch { return undefined } }+export { existsSync, join, writeFileSync, mkdirSync }++export function renderTable(rows) {+ const icon = { pass: 'PASS', fail: 'FAIL', blocked: 'BLOCKED', skipped: 'skip', flaky: 'FLAKY', advisory: 'ADVISORY' }+ const w = Math.max(...rows.map(r => r.name.length), 10)+ return rows.map(r => `${(icon[r.status] ?? r.status).padEnd(8)} ${r.leg.padEnd(10)} ${r.name.padEnd(w)} ${r.evidence.split('\n')[0].slice(0, 110)}`).join('\n')+}diff --git a/v3/@claude-flow/cli/__tests__/mcp-bin-resources-capability.test.ts b/v3/@claude-flow/cli/__tests__/mcp-bin-resources-capability.test.tsnew file mode 100644index 0000000000..6dddffc72d--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/mcp-bin-resources-capability.test.ts@@ -0,0 +1,53 @@+import { describe, expect, it } from 'vitest';+import { spawn } from 'node:child_process';+import { existsSync } from 'node:fs';+import { join } from 'node:path';++// ADR-490: bin/cli.js (what `ruflo mcp start` runs) and bin/mcp-server.js are independent stdio servers from src/mcp-server.ts. Each declared+// `resources` but answered resources/* with -32601. Driven over real stdio, the way Codex and Claude Code reach them.+const BIN = (f: string) => join(__dirname, '..', 'bin', f);++function rpc(entry: string, args: string[], calls: Array<{ method: string; params?: unknown }>): Promise<Array<{ result?: any; error?: any }>> {+ return new Promise((resolve, reject) => {+ const p = spawn(process.execPath, [BIN(entry), ...args], { stdio: ['pipe', 'pipe', 'ignore'], env: { ...process.env, RUFLO_NO_SKILLS_SH: '1' } });+ const out: Array<{ result?: any; error?: any }> = [];+ let buf = '';+ const timer = setTimeout(() => { p.kill('SIGKILL'); reject(new Error(`timeout; got ${out.length}/${calls.length}`)); }, 60_000);+ p.stdout.on('data', (d) => {+ buf += d;+ let i: number;+ while ((i = buf.indexOf('\n')) >= 0) {+ const line = buf.slice(0, i); buf = buf.slice(i + 1);+ try { const m = JSON.parse(line); if (typeof m.id === 'number') out[m.id - 1] = m; } catch { /* log line */ }+ if (out.filter(Boolean).length === calls.length) { clearTimeout(timer); p.kill('SIGKILL'); resolve(out); }+ }+ });+ calls.forEach((c, i) => p.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', id: i + 1, method: c.method, params: c.params ?? {} })}\n`));+ });+}++// The bin entries import dist/, so this needs a built CLI; the e2e workflow (scripts/e2e) builds one and asserts the same thing over stdio.+const built = existsSync(join(__dirname, '..', 'dist', 'src', 'index.js'));++describe.skipIf(!built).each([+ ['cli.js', ['mcp', 'start']],+ ['mcp-server.js', []],+])('bin/%s stdio MCP resources capability', (entry, args) => {+ it('serves what it advertises', async () => {+ const [init, list, templates, read] = await rpc(entry, args, [+ { method: 'initialize', params: { protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 't', version: '1' } } },+ { method: 'resources/list' },+ { method: 'resources/templates/list' },+ { method: 'resources/read', params: { uri: 'ruflo://nope' } },+ ]);+ const res = init.result.capabilities.resources;+ expect(res?.subscribe).not.toBe(true);+ expect(res?.listChanged).not.toBe(true);+ if (res) {+ expect(list.error).toBeUndefined();+ expect(list.result).toEqual({ resources: [] });+ expect(templates.result).toEqual({ resourceTemplates: [] });+ }+ expect(read.error?.code).toBe(-32002);+ }, 90_000);+});diff --git a/v3/@claude-flow/cli/__tests__/mcp-resources-capability-honesty.test.ts b/v3/@claude-flow/cli/__tests__/mcp-resources-capability-honesty.test.tsnew file mode 100644index 0000000000..7765592157--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/mcp-resources-capability-honesty.test.ts@@ -0,0 +1,42 @@+import { describe, expect, it, vi } from 'vitest';++// ADR-490 e2e finding: `ruflo mcp start` advertised `resources: { subscribe, listChanged }` in `initialize` but answered every resources/*+// request with -32601. Codex 0.162.0 offers the model a list_mcp_resources tool for any MCP server, the model called it first, got+// "Method not found: resources/list", and gave up before reaching the ruflo tools. A server that declares a capability must serve its methods.+vi.mock('../src/mcp-client.js', () => ({ callMCPTool: vi.fn(), hasTool: () => false, listMCPTools: () => [] }));+vi.mock('../src/mcp-tools/request-tracker.js', () => ({ trackRequest: vi.fn() }));+vi.mock('../src/mcp-tools/policy-enforcer.js', () => ({ isPolicyEnforcementEnabled: () => false }));++const { MCPServerManager } = await import('../src/mcp-server.js');+const manager = new MCPServerManager({ transport: 'stdio' });+const send = (method: string, params: unknown = {}) =>+ (manager as any).handleMCPMessage({ jsonrpc: '2.0', id: 1, method, params }, 'test-session');++describe('MCP resources capability is honest', () => {+ it('serves resources/list and resources/templates/list (empty, but answered) as long as it advertises resources', async () => {+ const init = await send('initialize');+ const advertised = Boolean(init.result.capabilities.resources);+ const list = await send('resources/list');+ const templates = await send('resources/templates/list');+ if (advertised) {+ expect(list.error).toBeUndefined();+ expect(list.result).toEqual({ resources: [] });+ expect(templates.error).toBeUndefined();+ expect(templates.result).toEqual({ resourceTemplates: [] });+ }+ // either way, never advertise something the switch cannot serve+ expect(advertised ? list.error : undefined).toBeUndefined();+ });++ it('does not claim subscribe/listChanged for resources it never emits or accepts', async () => {+ const init = await send('initialize');+ const caps = init.result.capabilities.resources ?? {};+ expect(caps.subscribe).not.toBe(true);+ expect(caps.listChanged).not.toBe(true);+ });++ it('answers resources/read for an unknown uri with the spec "resource not found" error, not method-not-found', async () => {+ const read = await send('resources/read', { uri: 'ruflo://nope' });+ expect(read.error.code).toBe(-32002);+ });+});diff --git a/v3/@claude-flow/cli/bin/cli.js b/v3/@claude-flow/cli/bin/cli.jsindex 0c112b0f56..7dad89f160 100755--- a/v3/@claude-flow/cli/bin/cli.js+++ b/v3/@claude-flow/cli/bin/cli.js@@ -257,7 +257,7 @@ if (isMCPMode) {serverInfo: { name: 'ruflo', version: VERSION },capabilities: {tools: { listChanged: true },- resources: { subscribe: true, listChanged: true },+ resources: {},},},};@@ -322,6 +322,16 @@ if (isMCPMode) {}}+ // A declared capability must be served (ADR-490): no resources are exposed, so list answers are empty and a read is "not found".+ case 'resources/list':+ return { jsonrpc: '2.0', id: message.id, result: { resources: [] } };++ case 'resources/templates/list':+ return { jsonrpc: '2.0', id: message.id, result: { resourceTemplates: [] } };++ case 'resources/read':+ return { jsonrpc: '2.0', id: message.id, error: { code: -32002, message: 'Resource not found' } };+case 'notifications/initialized':return null;diff --git a/v3/@claude-flow/cli/bin/mcp-server.js b/v3/@claude-flow/cli/bin/mcp-server.jsindex 6f3944da84..29cbe05e90 100755--- a/v3/@claude-flow/cli/bin/mcp-server.js+++ b/v3/@claude-flow/cli/bin/mcp-server.js@@ -146,7 +146,7 @@ async function handleMessage(message) {serverInfo: { name: 'ruflo', version: VERSION },capabilities: {tools: { listChanged: true },- resources: { subscribe: true, listChanged: true },+ resources: {},},},};@@ -208,6 +208,16 @@ async function handleMessage(message) {}}+ // A declared capability must be served (ADR-490): no resources are exposed, so list answers are empty and a read is "not found".+ case 'resources/list':+ return { jsonrpc: '2.0', id: message.id, result: { resources: [] } };++ case 'resources/templates/list':+ return { jsonrpc: '2.0', id: message.id, result: { resourceTemplates: [] } };++ case 'resources/read':+ return { jsonrpc: '2.0', id: message.id, error: { code: -32002, message: 'Resource not found' } };+case 'notifications/initialized':console.error(`[${new Date().toISOString()}] INFO [claude-flow-mcp] Client initialized`);return null; // No response for notificationsdiff --git a/v3/@claude-flow/cli/src/mcp-server.ts b/v3/@claude-flow/cli/src/mcp-server.tsindex 5bc8197f5f..4d81d97e29 100644--- a/v3/@claude-flow/cli/src/mcp-server.ts+++ b/v3/@claude-flow/cli/src/mcp-server.ts@@ -788,7 +788,7 @@ export class MCPServerManager extends EventEmitter {version: VERSION,capabilities: {tools: { listChanged: true },- resources: { subscribe: true, listChanged: true },+ resources: {},},},},@@ -891,7 +891,7 @@ export class MCPServerManager extends EventEmitter {serverInfo: { name: 'ruflo', version: '3.0.0' },capabilities: {tools: { listChanged: true },- resources: { subscribe: true, listChanged: true },+ resources: {},},},};@@ -955,6 +955,17 @@ export class MCPServerManager extends EventEmitter {};}+ // The server advertises `resources` (so clients such as Codex offer list_mcp_resources), and a declared capability must+ // be served: it exposes no resources, so the answers are empty, and a read is the spec's "resource not found" (ADR-490).+ case 'resources/list':+ return { jsonrpc: '2.0', id: message.id, result: { resources: [] } };++ case 'resources/templates/list':+ return { jsonrpc: '2.0', id: message.id, result: { resourceTemplates: [] } };++ case 'resources/read':+ return { jsonrpc: '2.0', id: message.id, error: { code: -32002, message: 'Resource not found' } };+case 'notifications/initialized':// Client notification - no response neededconsole.error(diff --git a/v3/@claude-flow/codex/src/initializer.ts b/v3/@claude-flow/codex/src/initializer.tsindex edcffba31d..7c25686268 100644--- a/v3/@claude-flow/codex/src/initializer.ts+++ b/v3/@claude-flow/codex/src/initializer.ts@@ -35,6 +35,10 @@ export function resolveBundledSkillsPath(moduleUrl = import.meta.url): string {/*** Main initializer for Codex projects*/+/** `codex plugin marketplace add` clones the repo (~17.5 s measured, ADR-490); `plugin add` is a local copy. */+const MARKETPLACE_ADD_TIMEOUT_MS = 180_000;+const PLUGIN_ADD_TIMEOUT_MS = 60_000;+export class CodexInitializer {private projectPath: string = '';private template: AgentsMdTemplate = 'default';@@ -505,22 +509,29 @@ export class CodexInitializer {}}- // Add the marketplace (idempotent β codex no-ops if already added; any- // error here is non-fatal, the plugin-add below reports the real failure).+ // Add the marketplace (idempotent β codex no-ops if already added). The add is a git clone of+ // the whole repo: ~17.5 s measured on an idle machine, so a 20 s budget was killed under the+ // load init itself creates (ADR-490 e2e). A failure here is remembered, not swallowed: the+ // plugin-add below then fails with "plugin not found in marketplace", which names the wrong cause.+ let marketplaceFailure = '';try {- execSync('codex plugin marketplace add ruvnet/ruflo --ref main', { stdio: 'pipe', timeout: 20000 });- } catch {- // Marketplace may already exist, or the CLI may not support this exact- // verb β let the plugin-add attempt surface the actionable error.+ execSync('codex plugin marketplace add ruvnet/ruflo --ref main', { stdio: 'pipe', timeout: MARKETPLACE_ADD_TIMEOUT_MS });+ } catch (err) {+ const e = err as { code?: string; killed?: boolean; message?: string };+ const timedOut = e.code === 'ETIMEDOUT' || e.killed === true;+ marketplaceFailure = `marketplace add ${timedOut ? 'timed out (ETIMEDOUT)' : 'failed'}: ${(e.message ?? String(err)).split('\n')[0]}`;+ // The marketplace may already exist, or the CLI may not support this exact verb:+ // still try the plugin-add and report both failures if it fails too.}// Install the plugin at user scope.try {- execSync('codex plugin add ruflo-core@ruflo', { stdio: 'pipe', timeout: 20000 });+ execSync('codex plugin add ruflo-core@ruflo', { stdio: 'pipe', timeout: PLUGIN_ADD_TIMEOUT_MS });return { installed: true, activationMessage: ACTIVATION };} catch (err) {const msg = err instanceof Error ? err.message : String(err);- return { installed: false, warning: `Failed to install ruflo-core@ruflo plugin: ${msg}. ${MANUAL}` };+ const cause = marketplaceFailure ? ` (the marketplace ${marketplaceFailure})` : '';+ return { installed: false, warning: `Failed to install ruflo-core@ruflo plugin: ${msg}${cause}. ${MANUAL}` };}} catch {return { installed: false, warning: `Could not install Ruflo plugin. ${MANUAL}` };diff --git a/v3/@claude-flow/codex/tests/plugin-install-timeout.test.ts b/v3/@claude-flow/codex/tests/plugin-install-timeout.test.tsnew file mode 100644index 0000000000..ce3a64f5d6--- /dev/null+++ b/v3/@claude-flow/codex/tests/plugin-install-timeout.test.ts@@ -0,0 +1,54 @@+import { describe, expect, it, vi, beforeEach } from 'vitest';++// e2e finding (ADR-490): on a fresh CODEX_HOME, `ruflo init --dual` ran `codex plugin marketplace add ruvnet/ruflo` under a 20 s execSync+// timeout. Measured on this machine the clone takes ~17.5 s alone and longer under the load init itself creates, so the add was killed, the+// error was swallowed, and `codex plugin add ruflo-core@ruflo` then failed with "plugin ruflo-core was not found in marketplace ruflo".+// The user only saw the second error, which names the wrong cause.++const calls: Array<{ cmd: string; timeout?: number }> = [];+let marketplaceError: Error | undefined;++vi.mock('child_process', () => ({+ execSync: (cmd: string, opts?: { timeout?: number }) => {+ calls.push({ cmd, timeout: opts?.timeout });+ if (cmd.startsWith('which codex')) return Buffer.from('/usr/bin/codex');+ if (cmd.startsWith('codex plugin list')) return JSON.stringify({ plugins: [] });+ if (cmd.startsWith('codex plugin marketplace add')) {+ if (marketplaceError) throw marketplaceError;+ return Buffer.from('');+ }+ if (cmd.startsWith('codex plugin add')) {+ if (marketplaceError) throw new Error('Error: plugin `ruflo-core` was not found in marketplace `ruflo`');+ return Buffer.from('');+ }+ return Buffer.from('');+ },+}));++async function install() {+ const { CodexInitializer } = await import('../src/initializer.js');+ const init = new CodexInitializer() as unknown as { installRufloCorePlugin(): Promise<{ installed: boolean; warning?: string }> };+ return init.installRufloCorePlugin();+}++describe('installRufloCorePlugin marketplace clone budget (e2e finding, ADR-490)', () => {+ beforeEach(() => {+ calls.length = 0;+ marketplaceError = undefined;+ vi.resetModules();+ });++ it('gives the marketplace clone far more than the 17.5 s it measurably takes', async () => {+ await install();+ const add = calls.find((c) => c.cmd.startsWith('codex plugin marketplace add'));+ expect(add?.timeout).toBeGreaterThanOrEqual(120_000);+ });++ it('names the marketplace failure, not only the downstream "plugin not found", when the clone does not finish', async () => {+ marketplaceError = Object.assign(new Error('spawnSync /bin/sh ETIMEDOUT'), { code: 'ETIMEDOUT' });+ const result = await install();+ expect(result.installed).toBe(false);+ expect(result.warning).toMatch(/marketplace/i);+ expect(result.warning).toMatch(/ETIMEDOUT|timed out/i);+ });+});diff --git a/v3/docs/adr/ADR-490-three-host-e2e-integration-loop.md b/v3/docs/adr/ADR-490-three-host-e2e-integration-loop.mdnew file mode 100644index 0000000000..ed36258d1f--- /dev/null+++ b/v3/docs/adr/ADR-490-three-host-e2e-integration-loop.md@@ -0,0 +1,140 @@+# ADR 490: A three-host e2e integration loop (Claude Code, Codex, OpenRouter)++Status: Accepted (implemented in `scripts/e2e/`; first run recorded in section 8)++Date: 2026-10-11++Builds on: ADR-404 (Claude Code mods), ADR-406 (no command removed or renamed), ADR-444, ADR-448 (live validation practice), ADR-451 (mod capability roadmap; item 7 canary).+Related: ADR-491 (mods host integration across Claude Code and Codex), ADR-489 (standalone TUI `Host` interface).++## 1. Context++ruflo is used from three hosts: Claude Code (mods, hooks, MCP), Codex (MCP, plugins, hooks, skills) and OpenRouter (the model behind+`agent_execute`, the console AI terminal and, as a provider, behind Codex itself). Until now each host had unit tests and per-feature live+scripts (`live-ruflo-mods-*.sh`, `live-ruflo-mods-compact.mjs`, `audit-codex-integration.mjs`, `smoke-agent-execute-providers.mjs`), but nothing+drove the three hosts the way a user does and failed when the pieces did not fit. Two defects found by the first run (section 8) had survived+every unit test, because each side of the seam was correct against its own mock.++## 2. Decision++Add one repeatable harness, `scripts/e2e/host-matrix.mjs`, that produces a **host x assertion matrix** against the real ruflo CLI, MCP server,+mods and plugins, with real hosts where a model is needed. Run it in two modes:++- **Keyless** (default; what CI runs): no model call, `$0`. Real CLI, real MCP stdio server, real `claude`/`codex` binaries for the parts that+ need no model (`mods doctor`, `codex plugin list`, `codex mcp list`), a local OpenAI-compatible stub for OpenRouter.+- **Live** (`RUFLO_E2E_LIVE=1` and `--live`; never in CI): the same assertions plus real sessions, capped by `--cap` (default 6 USD).++`npm run e2e` and `npm run e2e:live` wrap the two. The workflow `.github/workflows/e2e-host-matrix.yml` runs the keyless mode on PRs that touch+the harness or the MCP/Codex seam, weekly, and on demand.++## 3. Harness design++One file per leg (`leg-claude.mjs`, `leg-codex.mjs`, `leg-openrouter.mjs`), a shared `lib.mjs` (assertion recorder, redaction, sandbox, MCP stdio+client, OpenAI-compatible stub) and the orchestrator. Every row is `pass | fail | blocked | skipped | flaky | advisory` with captured, redacted+evidence; flaky and environment-dependent rows are marked, never hidden. Exit code 1 only on `fail`.++Isolation, per leg: a throwaway `HOME` (and `CLAUDE_CONFIG_DIR`, `CODEX_HOME`, XDG dirs), a fresh git project, provider keys removed from the+inherited environment. The CLI under test is `npx ruflo@<version>` or, with `--cli-path`, a workspace build, so the same assertions run against the+published artifact (what users have) and against a branch (what is about to ship).++### 3.1 Claude Code leg++Keyless: `ruflo init`; lifecycle hooks registered; no hook command goes through `cmd /c` on this platform (#4045); `mods doctor` exits 0, reports+the mod enabled and the classic handshake, and says plainly that a headless `-p` run does not clone the marketplace; the generated PreToolUse(Bash)+command runs and exits 0 within its declared timeout and does not execute or redirect the hook's stdin JSON; the MCP server answers `tools/list`+(381 tools on 3.56.5), serves every capability it advertises, round-trips `memory_store` / `memory_search`, `task_create` / `task_list`, and+survives a prototype-named agent id in `task_assign` (#3967).++Live: headless `claude -p` (haiku) with `ruflo-mods` and `ruflo-console` loaded from the checkout through `--plugin-dir`, ruflo as the only MCP+server. Haiku calls the ruflo tools and finds the value; Claude Code ran the project hooks (`hook_started` / `hook_response` events); the plugins+are loaded; the cost-tracker ledger counts the session; `console_state` is model-safe (no ESC/OSC bytes, no other project's path, bounded);+`costHardStop` refuses a new subagent past the budget, **asserted on the `tool_result` text, not on the model's description of it**.++### 3.2 Codex leg++Pinned to Codex **0.162.0**: the 0.162.1 build crashes with a #GP (stack misalignment), so the leg calls the 0.162.0 binary by path+(`RUFLO_E2E_CODEX_BIN` overrides) and never reads `codex` from `PATH` or touches the install `current` links. If the pinned binary is absent the+leg is `blocked`, not skipped silently.++Keyless: `init --dual` on a fresh `CODEX_HOME` leaves `ruflo-core@ruflo` installed; Codex reads the Claude-format `.claude-plugin/marketplace.json`+(46 plugins listed) and installs `ruflo-swarm` from the checkout as a local marketplace; ruflo registers as an MCP server; the cost-tracker Codex+ledger tests pass (#4047/#4048); the generated `.codex/config.toml` is checked for permissive defaults (an advisory, section 8).++Live: Codex runs **with OpenRouter as its model provider** (`model_provider = "openrouter"`, Responses wire, model `openai/gpt-5.1-codex-mini`),+read-only sandbox, ruflo as an MCP server with `default_tools_approval_mode = "approve"` (exec otherwise declines every MCP call:+"approval policy is never"). Assertions: `mcp_tool_call` items to the ruflo server for `memory_store` and `memory_search*`, parsed from the event+stream (not words in the reply); the stored key is reported; command hooks fire (with `--dangerously-bypass-hook-trust`, in the throwaway home+only); the installed `ruflo-core` plugin hooks raise no hook error; the cost ledger counts the run under one owning session; and two **policy+probes** that make ADR-491's table evidence instead of documentation: a `UserPromptSubmit` hook's `additionalContext` reaches the model+(ruflo-mods route equivalent) and a `PreToolUse` hook's deny stops a shell call (ruflo-mods guard equivalent). A small model sometimes answers+without calling the tool, so the MCP and route probes get one retry and record the attempt count; a probe whose trigger never occurred is `flaky`.++### 3.3 OpenRouter leg++Keyless: `agent_spawn` + `agent_execute` through ruflo's own provider path (`RUFLO_PROVIDER=openrouter`, `OPENROUTER_BASE_URL` at a local stub): the+reply returns, the request is `POST /v1/chat/completions` with a bearer header, usage tokens surface, the key never appears in tool output, and a+provider 429 / 500 is reported as a failure (not a success) with the key absent. Live: the same path against openrouter.ai with a cheap model.+(`claude-sonnet-5`, the model name ruflo sends, is accepted by OpenRouter as an alias: checked, not a defect.)++## 4. Safety and spend++- Hard cap `--cap` (default 6 USD) summed across legs; each Claude session also has `--max-budget-usd`. Models: haiku; `gpt-5.1-codex-mini`+ (0.25 / 2.00 USD per million tokens); stub for the keyless OpenRouter leg.+- Read-only sandboxes for Codex, tools restricted by `--allowedTools` / `--disallowedTools` for Claude. No destructive action, no network except+ the providers (plus GitHub for `init --dual`'s marketplace clone).+- Spend accounting is conservative: Claude's `total_cost_usd`; for Codex-through-OpenRouter the larger of the key's usage delta and a+ token-based estimate. The key used in development is shared, so its delta includes other traffic: the figure is an **upper bound**.++## 5. Key handling++- `OPENROUTER_API_KEY` from the environment, else Secret Manager (`ruv-dev`, then `cognitum-20260110`) **only if `gcloud` is `[email protected]`**. It is+ read into this process's memory (never a file, never argv), passed to children by environment, and registered with the redactor.+- Every string that reaches a report passes `redact()`, which knows the loaded secret values plus token shapes (`sk-or-v1-`, `sk-ant-`, JWTs,+ Bearer values, `access_token` / `refresh_token` / `api_key` pairs). The JSON report is redacted before it is written.+- Claude: only the **access token** is copied into the throwaway config (no refresh token), mode 0600, removed with the sandbox.+- Codex: **the ChatGPT login is never copied.** A throwaway home that refreshed the refresh token would invalidate the real `~/.codex/auth.json`+ (the refresh token is single-use). Access-token-only copies fail with 401 because the id token expires first (observed: id token 3 days old,+ access token valid to 2026-10-18). The leg therefore authenticates Codex through OpenRouter. A ChatGPT-auth variant would need an explicit+ consent flag and a write-back protocol and is not built.++## 6. CI versus live++| | keyless (CI) | live |+|---|---|---|+| model calls | none | haiku, `gpt-5.1-codex-mini` |+| network | npm, GitHub (marketplace clone) | plus Anthropic, OpenRouter |+| trigger | PR touching `scripts/e2e/**`, the MCP bins, `mcp-server.ts`, the Codex package; weekly; dispatch | by hand: `RUFLO_E2E_LIVE=1 npm run e2e:live` |+| gate | `fail` rows fail the workflow | report only; a person reads it |++Unit tests for each defect the loop finds live with the code they cover (section 8).++## 7. Pass criteria++The loop is green when the matrix has no `fail` row. `blocked` (missing credential or pinned binary) and `flaky` rows must name their reason.+`advisory` rows record a posture question that needs a decision, not a defect. A defect found live is not closed by a harness change: it needs a+failing unit test, a fix, and the matrix row passing on the workspace build.++## 8. Results of the first run (2026-10-11)++Against the **published 3.56.5** (live, Claude + Codex): 33 pass, **2 fail**, 1 advisory, 1 skipped. Against the **workspace build with the fixes**+(all three legs, live): 46 pass, 0 fail, 1 advisory, 1 skipped. Recorded spend, upper bound: under 4 USD across all development runs, of the+6 USD cap.++| # | Finding | Evidence | Disposition |+|---|---|---|---|+| 1 | **`ruflo mcp start` advertised `resources: { subscribe, listChanged }` and answered every `resources/*` with -32601.** Three independent stdio servers carry the same block (`bin/cli.js`, `bin/mcp-server.js`, `src/mcp-server.ts`). Codex offers `list_mcp_resources` for any server; with `gpt-5-mini` the model called it first, got "Method not found", and gave up before reaching the tools. | Unit tests failed first (3 + 2); e2e row failed on 3.56.5 and passes on the workspace build. | Fixed: capability is `resources: {}`; `resources/list` and `resources/templates/list` answer empty, `resources/read` answers -32002. Needs a cli release (`@claude-flow/cli`). |+| 2 | **`init --dual` on a fresh `CODEX_HOME` failed to install `ruflo-core@ruflo`.** `codex plugin marketplace add ruvnet/ruflo` is a git clone: 17.5 s measured alone; the 20 s `execSync` budget was exceeded under init's own load, the error was swallowed, and the user saw only "plugin `ruflo-core` was not found in marketplace `ruflo`". | Reproduced three times in sandboxes; later a quiet machine finished inside 20 s (so the row is timing-dependent, not deterministic). Unit tests failed first (2). | Fixed: 180 s clone budget, 60 s plugin-add, and the marketplace failure is named in the warning. `@claude-flow/codex` is bundled, so it ships with the train. |+| 3 | Advisory: `init --dual` writes a gitignored `.codex/config.toml` with `sandbox_mode = "danger-full-access"`, `approval_policy = "never"`, `web_search = "live"`, labelled "Development profile - more permissive". | Row `advisory`. | **Decision for rUv**, not changed here: it is a documented local override, but it is the default a Codex user gets. |+| 4 | Not defects (checked): OpenRouter accepts the `claude-sonnet-5` name ruflo sends; `--no-codex-detect` gates only *auto*-detection, `--codex` / `--dual` configure Codex by design. | Direct calls; source read. | None. |++Harness bugs found and fixed on the way (not ruflo bugs): the redactor's `sk-` pattern masked task ids (`task-...`) and its callback mis-printed+offsets; a `__proto__` assertion tested the wrong property (the pollution is covered by the unit test from #3967); a costHardStop assertion that+matched the model's prose would also pass on a hallucinated refusal and now reads the `tool_result`.++## 9. Not verified++- Windows and macOS (everything ran on Linux x86_64, Node 22, claude 2.1.289, codex 0.162.0).+- `PreCompact`, `SubagentStart`, `SubagentStop` under Codex: the events exist in the binary but `codex exec` cannot force a compaction or a+ subagent spawn (row `skipped`).+- A Codex run authenticated by ChatGPT; models other than haiku and the two named above; the desktop and terminal UIs.+- `init --dual`'s marketplace clone depends on GitHub and network speed; the fix removes the timing hazard, it cannot remove the network.diff --git a/v3/docs/adr/ADR-491-ruflo-mods-host-integration-claude-and-codex.md b/v3/docs/adr/ADR-491-ruflo-mods-host-integration-claude-and-codex.mdnew file mode 100644index 0000000000..8eebdb2c59--- /dev/null+++ b/v3/docs/adr/ADR-491-ruflo-mods-host-integration-claude-and-codex.md@@ -0,0 +1,109 @@+# ADR 491: ruflo-mods across Claude Code and Codex: a host-neutral core and a thin Codex adapter++Status: Proposed (evidence table is measured; the adapter and `--host` flag are not built)++Date: 2026-10-11++Builds on: ADR-404 (Claude Code mods, function hooks), ADR-406 (no command is removed or renamed), ADR-444, ADR-447 (native guidance), ADR-451 (capability roadmap), ADR-490 (three-host e2e loop; the evidence below comes from it).+Related: ADR-489 (standalone TUI and its `Host` interface), ADR-488 (`compactKeep`).++## 1. Context++`ruflo-mods` is a Claude Code mod: a plugin of **function hooks** (`hooks/hooks.json` -> `"modules": ["./register.ts"]`, ADR-404). It has a+`.claude-plugin/plugin.json` and nothing for Codex. Its README says what it needs: Claude Code >= 2.1.287 (or `CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1`)+and a cloned `ruflo` marketplace; with function hooks off it does nothing and the classic `hook-handler.cjs` hooks keep every event.++On a Codex host a ruflo user gets only what `ruflo init --dual` installs: the `ruflo-core@ruflo` plugin, whose hooks (`plugins/ruflo-core/hooks/+hooks.json`) are best-effort **telemetry** (`scripts/ruflo-hook.cjs` always exits 0, swallows CLI output, and, per its own header comment, returns empty stdout to Codex), and+`ruflo-swarm`, whose Codex manifest `hooks/codex-hooks.json` is a deliberate no-op (`"hooks": {}`; verified by the ADR-490 matrix). None of the+mod's *policies* (routing context, tool checks, budget ladder and hard stop, compaction carry, delivery screen, trust gate) runs under Codex.++Two things make this worth revisiting now. (a) Codex 0.162.0 has a real hook engine: events `PreToolUse`, `PermissionRequest`, `PostToolUse`,+`PreCompact`, `PostCompact`, `SessionStart`, `SessionEnd`, `SubagentStart`, `SubagentStop`, `UserPromptSubmit`, `Stop`, `Interrupt` (names read+from the binary's strings), `hooks.json` at `CODEX_HOME` or in a plugin, hook input shaped like Claude Code's (`hook_event_name`, `tool_name`,+`tool_input`, `transcript_path`, `permission_mode`), and `CLAUDE_PLUGIN_ROOT` honoured for plugin hooks. (b) The ADR-490 loop can now test what a+Codex hook can *do*, instead of arguing it.++## 2. Evidence: which mod policies have a Codex equivalent++"Proven" means a live assertion in the ADR-490 matrix (Codex 0.162.0 through OpenRouter, `openai/gpt-5.1-codex-mini`, Linux, 2026-10-11).+"Event exists" means only that the binary names the event; **no behaviour was exercised**. Everything else is "no equivalent found".++| ruflo-mods policy (Claude function hook) | Codex mechanism | State |+|---|---|---|+| Routing: `prompt.submit` hands the route and ranked memory to the model as context | `UserPromptSubmit` command hook returning `hookSpecificOutput.additionalContext` | **Proven.** A hook returned a marker; the model repeated it (`CTX-...`) in 8 of 9 runs after the probe script was fixed. The one miss was the model ignoring the context; the hook fired in every run where the log was recorded. The harness retries once and records the try count. |+| Tool checks: `tool.check` only tightens (dangerous-command list, `claude-code.*` policy rules) | `PreToolUse` hook returning `permissionDecision: "deny"` | **Proven** for a shell call: the hook fired with `tool_name: "Bash"`, the command did not run, the model reported it blocked. MCP and edit tools **not tested**. |+| Edit learning: `tool.call` records finished edits for the consolidator | `PostToolUse` | Event **fired** live; its payload for edit tools (`apply_patch`) was **not inspected**. |+| Budget ladder (`costBudgetUsd`): live cost via `session.measure`, announced once per rung | none live; `Stop` / `SessionEnd` fire, and `cost-tracker` already reads Codex rollouts after the fact | **Partial, unproven.** Cost is available only post hoc from the rollout ledger (counted live: 5 rows, one owning session). No per-turn cost hook was found. |+| `costHardStop`: deny a new subagent at 100% | `SubagentStart` / `SubagentStop` | **Event exists, not exercised** (`codex exec` cannot force a subagent). Whether a start hook can deny is **unknown**. |+| `compactCarry`: append facts to the compaction instructions | `PreCompact` / `PostCompact` (a `PreCompactCommandOutputWire` type exists) | **Event exists, not exercised** (no non-interactive compaction). Whether a hook can append summarizer instructions is **unknown**. |+| Trust gate (`plugin.register`, `modTrust`) | Codex's own hook trust (`hooks.state."<id>".trusted_hash`, `--dangerously-bypass-hook-trust`) | **Different model.** Codex never auto-trusts a command hook; a person reviews it in `/hooks`. Not equivalent, and the adapter cannot grant it. |+| `deliveryScreen`, `toolHints`, `agentTrim`, `guidanceContext` | no Codex equivalent identified (Codex's permission-request output can rewrite an *input* via `updatedInput`; nothing found rewrites a tool *description* or the agent list) | **No equivalent found.** Not tested beyond reading the event names. |+| `statusLine`, panes, toasts, `$.ruflo.segment`, `/ruflo-mods` | none: Codex's UI is not extensible | **None.** The display surface for Codex users is the standalone TUI (ADR-489), not a hook. |+| Observability options (`capabilityProbe`, `sessionRollup`, `sessionAttention`, `grounding`) | `SessionEnd` / `Stop` hooks plus the ledger | **Plausible, untested.** |++What the proven rows say: the two policies that matter most for safety and value (inject the route, tighten tool calls) are expressible as+ordinary command hooks. What they do not say: that every mod policy is. The budget hard stop and compaction carry hinge on two questions+(can `SubagentStart` deny; can `PreCompact` append instructions) that need a live answer before any promise.++Latency: a command hook is a process spawn. The classic `hook-handler.cjs` measured 23 to 43 ms for a PreToolUse(Bash) call on this machine+(ADR-490 row), against in-process function hooks. Per-tool-call cost is therefore real on Codex and must be budgeted, not assumed.++## 3. Decision (proposed)++### 3.1 A host-neutral policy core++Move the pure logic of the mod's policies out of `register.ts` wiring into a host-neutral module (`plugins/ruflo-mods/core/`): the dangerous-command+and policy-projection check, route text building, the budget ladder arithmetic, the compaction-carry block builder, the screening. These already+take and return plain data (the kit tests exercise them without Claude Code). `register.ts` becomes the Claude Code adapter that calls them with+`$` facts; behaviour on Claude Code is byte-for-byte unchanged (ADR-406).++### 3.2 A thin Codex adapter++Add `plugins/ruflo-mods/.codex-plugin/plugin.json` and `hooks/codex-hooks.json` whose commands run one Node entry (`hooks/codex-runner.mjs`) that+reads the hook JSON from stdin, calls the same core, and prints the Codex output shape. Only the rows marked **Proven** are implemented in the+first phase (routing context, shell tool-check tightening); the rest stay off until their question is answered live. Constraints carried from the+Claude adapter: the adapter **only tightens** (never loosens a verdict), fails open (a crash or timeout never blocks a turn), screens everything it+puts in front of the model through `modelLine` (ADR-481), and never prints a path or branch of another project (#3981).++No double firing: `ruflo-core@ruflo` already installs Codex lifecycle hooks, and its `PreToolUse` hook must keep returning empty stdout. The adapter+joins the existing ownership handshake (`RUFLO_MODS_OWNS`, `.claude-flow/mods/`), so an event the adapter owns is skipped by the classic helper, as+on Claude Code (the #2640 class).++### 3.3 Install and doctor: `--host`++`ruflo mods install [--host claude|codex|both]` and `ruflo mods doctor [--host ...]`, default `claude` so nothing changes for existing users (ADR-406).++- `--host codex` runs `codex plugin marketplace add` (a git clone: allow minutes, see ADR-490 finding 2) then `codex plugin add ruflo-mods@ruflo`,+ and never edits `~/.codex/auth.json` or the `current` install links.+- `doctor --host codex` reports the Codex version (a loud `!` for 0.162.1, the build that crashes with a #GP), the marketplace source, whether the+ plugin is installed, whether `features.hooks` is on (stable, default true in 0.162.0), and hook trust. **Installed but untrusted is a `!` with the+ one-line repair ("open /hooks and review the ruflo-mods definitions"), never a `β`**: the hooks are inactive until a person trusts them.+- `--host both` does both and prints one table.++### 3.4 Relation to ADR-489++ADR-489's `Host` interface is the *display and session* boundary for the console views. This ADR is the *policy* boundary for the mod. They share a+rule (a refused capability is a missing fact, never a crash) and, later, the core: the standalone TUI can run the same policy core as a third+host without Claude Code or Codex. The two are deliberately not merged: views draw; policies decide.++## 4. Phases++1. **Spike (this ADR + ADR-490).** Done: the evidence table above. Remaining questions to answer live before phase 3: can `SubagentStart` deny;+ can `PreCompact` append instructions; what does `PostToolUse` carry for `apply_patch`; do MCP calls reach `PreToolUse`.+2. **Core extraction** with no behaviour change (the existing mods suite is the gate: 152 tests at mods 0.5.1).+3. **Codex adapter for the proven rows**, `--host codex`, doctor, plus ADR-490 matrix rows that fail without it.+4. **Further rows** only as their question is answered by a matrix assertion.++## 5. Risks and non-goals++- **Hook trust is a human step.** An installed-but-untrusted mod does nothing; the doctor must say so. We do not bypass it outside a throwaway test home.+- **Process-spawn latency** per tool call; mitigate by registering only the events and matchers a policy needs.+- **Divergence.** Two adapters can drift; the shared core and the matrix (one assertion per policy per host) are the guard.+- **Codex changes.** Event names and output shapes came from a binary at 0.162.0; the 0.162.1 crash is a reminder that the pin matters. The matrix pins the version.+- Non-goals: function hooks on Codex (it has none); a UI on Codex (ADR-489); rewriting history or vetoing compaction (ADR-488 territory); an agent harness of our own.++## 6. Not verified++Everything marked "Event exists", "unknown" or "untested" above; Windows and macOS; Codex authenticated by ChatGPT (the matrix uses OpenRouter, ADR-490+section 5); any Codex version other than 0.162.0; Claude Code versions other than 2.1.289.diff --git a/v3/docs/adr/INDEX-mod-system.md b/v3/docs/adr/INDEX-mod-system.mdindex 4bf07a7863..4fefa4c02d 100644--- a/v3/docs/adr/INDEX-mod-system.md+++ b/v3/docs/adr/INDEX-mod-system.md@@ -18,6 +18,7 @@ Two files carry the number 430 (the menu's accents, and the menu-design amendmen| 451 | Mod capability roadmap | Proposed (items 1β3, 5β7 shipped, all default off; 4, 8, 9, 10 not built) | 10-04 | 404, 445, 446, 447; related 449, 450, 452 | β | #3716 (ADR + `toolHints`, 0.3.0); `agentTrim` item 2 (0.3.1, `33a60c715`); `deliveryScreen` item 3 (0.3.3, `cd01a4aea`); `capabilityProbe` item 5 #3763 (0.3.7); `sessionRollup` item 6 #3766 (0.3.8); `compactCarry` item 7 #3768 (0.3.9); agentTrim live fixes #3733 and measurement #3760; fixes 0.3.2, 0.3.4 | ruflo-mods 0.3.9 | `describe`, `agents`, `delivery`, `probe`, `rollup`, `compact` tests || 452 | Mod-system overnight hardening: findings, changes, open items | Accepted (record) | 10-05 | 404, 444, 445, 446, 450, 451 | β | #3735; records #3706, #3711, #3713, #3714, #3715, #3717, #3719, #3727, #3732, #3733, #3734 (all merged) | no code of its own | `probe-mod-guards`, `sync-mod-screen --check` || 453 | Project Anatole: an optional, learning watchdog for unattended agents | Proposed | 10-05 | 404, 444, 445, 446, 450, 451, 452; related 449 | β | this PR (ADR only) | not built | β |+| 491 | ruflo-mods across Claude Code and Codex: a host-neutral core and a thin Codex adapter | Proposed | 10-11 | 404, 406, 444, 447, 451, 488, 490; related 489 | β | this PR (ADR only) | not built; evidence table measured by ADR-490's loop | `scripts/e2e/leg-codex.mjs` policy probes |## Console: mission control and Claude control@@ -77,6 +78,7 @@ Other ADRs outside 404-451 that the mod ADRs lean on: 150 (removable integration| ADR | Title | Status | Date | Builds on / extends | Superseded by | PR | Shipped in | Tests ||---|---|---|---|---|---|---|---|---|| 479 | MCP HTTP transport: bearer token, and refusal to serve a network without one | Accepted | 10-07 | related 012, 476 | β | #3599 (#3598) | cli 3.55.0, mcp 3.1.0 | `mcp-http-nonloopback-auth-gate.test.ts`, `http-transport-auth.test.ts` |+| 490 | A three-host e2e integration loop (Claude Code, Codex, OpenRouter) | Accepted | 10-11 | 404, 406, 444, 448, 451; related 489, 491 | β | this PR | `scripts/e2e/`; fixes in cli (MCP resources capability), codex (marketplace clone budget) | `host-matrix.mjs`, `mcp-resources-capability-honesty.test.ts`, `mcp-bin-resources-capability.test.ts`, `plugin-install-timeout.test.ts` |## Notes@@ -86,4 +88,5 @@ Other ADRs outside 404-451 that the mod ADRs lean on: 150 (removable integration- **ADR files whose own Status line differs from this index:** none for 450 and 451, whose Status lines now carry the same implementation summary (section 9 of 450, section 8 of 451 hold the tables). 405, 406 and 449 are "Proposed" in both.- **ADRs with no stated parent:** 434, 436, 437, 438, 439, 440, 441 carry no `Builds on` or `Extends` line.- **2026-10-07 additions.** Rows for 477, 478 and 479 were added. 478's link is to a file added by the change that builds that page. 479 is not a mod ADR; it is listed because 476 (hive-mind gating) and the toasts sit on the same MCP and console surfaces. ADRs 454 to 476 are not in these tables.+- **2026-10-11 additions.** Rows for 490 and 491 were added. 490 is listed under the MCP section because its loop found and fixed an MCP capability defect; it also records the Codex install defect. 491 is Proposed: its evidence table is measured, nothing in it is built.| 487 | Optional ruvnet-brain grounding (detect-only) in the console and mods | Accepted | 10-09 | 404, 443, 444, 481 | β | this PR | console 0.42.0, mods 0.5.0 | `grounding.spec`, `grounding.test.ts` |