🌊 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(missions): ADR-406 M1 mission observation via CLI and MCP, e2e gate
ruv0483ac5517b0
diff --git a/v3/@claude-flow/cli/__tests__/missions/adapters.test.ts b/v3/@claude-flow/cli/__tests__/missions/adapters.test.tsnew file mode 100644index 0000000000..986ae85f65--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/missions/adapters.test.ts@@ -0,0 +1,66 @@+/**+ * ADR-406 M1 — CLI and MCP adapters are thin transports over one service+ * (London school: the service port is mocked; the adapters must forward input+ * unchanged, pick the project root from trusted context, and add nothing).+ */+import { describe, it, expect, vi, afterEach } from 'vitest';+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { createMissionTools, type MissionPort } from '../../src/mcp-tools/mission-tools.js';+import { inputFromFlags, missionCommand, setMissionPortFactory } from '../../src/commands/mission.js';+import { classifyMcpTool } from '../../src/services/policy-runtime.js';++function mockPort(): MissionPort & Record<string, ReturnType<typeof vi.fn>> {+ const reply = vi.fn(async () => ({ ok: true as const, data: { stub: true } }));+ return { create: reply, plan: vi.fn(reply), get: vi.fn(reply), events: vi.fn(reply), requestAction: vi.fn(reply) } as never;+}++afterEach(() => setMissionPortFactory(null));++describe('MCP mission tools', () => {+ it('forward input unchanged to the port for the context project root', async () => {+ const port = mockPort();+ const factory = vi.fn(() => port);+ const tools = Object.fromEntries(createMissionTools(factory).map((t) => [t.name, t]));+ expect(Object.keys(tools).sort()).toEqual(['mission_create', 'mission_events', 'mission_get', 'mission_plan', 'mission_request_action']);+ const input = { requestId: 'r', missionId: `msn_${'b'.repeat(24)}`, expectedRevision: 3, action: 'cancel', approved: true };+ await tools.mission_request_action.handler(input, { projectRoot: '/proj' });+ expect(factory).toHaveBeenCalledWith('/proj');+ // The adapter neither strips nor interprets `approved`; the service schema rejects it.+ expect(port.requestAction).toHaveBeenCalledWith(input);+ });++ it('are classified by the existing policy runtime like any MCP tool (no bypass)', () => {+ for (const name of ['mission_create', 'mission_plan', 'mission_get', 'mission_events', 'mission_request_action']) {+ expect(classifyMcpTool(name).actionType).toBe('mcp.tool.call');+ }+ });+});++describe('CLI mission command', () => {+ it('maps flags to the same raw input shape the MCP tools take', () => {+ const dir = mkdtempSync(join(tmpdir(), 'ruflo-mission-cli-'));+ try {+ writeFileSync(join(dir, 'plan.json'), JSON.stringify({ tasks: [] }));+ expect(inputFromFlags('plan', { requestId: 'r1', mission: 'msn_x', expectedRevision: '2', planFile: 'plan.json' }, dir))+ .toEqual({ requestId: 'r1', missionId: 'msn_x', expectedRevision: 2, plan: { tasks: [] } });+ expect(inputFromFlags('events', { mission: 'msn_x', after: '5' }, dir)).toEqual({ missionId: 'msn_x', afterSequence: 5 });+ const created = inputFromFlags('create', { objective: 'o' }, dir);+ expect(created.requestId).toMatch(/^[0-9a-f-]{36}$/);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ it('delegates to the port and reports conflicts with a distinct exit code', async () => {+ const port = mockPort();+ port.plan.mockResolvedValueOnce({ ok: false, code: 'revision-conflict', message: 'm', currentRevision: 4 });+ setMissionPortFactory(() => port);+ const r = await missionCommand.action!({ args: ['plan'], flags: { _: [], requestId: 'r', mission: 'msn_x', expectedRevision: 1 }, cwd: '/tmp', interactive: false });+ expect(port.plan).toHaveBeenCalledWith({ requestId: 'r', missionId: 'msn_x', expectedRevision: 1 });+ expect(r).toMatchObject({ success: false, exitCode: 3 });+ const unknown = await missionCommand.action!({ args: ['explode'], flags: { _: [] }, cwd: '/tmp', interactive: false });+ expect(unknown).toMatchObject({ success: false, exitCode: 1 });+ });+});diff --git a/v3/@claude-flow/cli/scripts/e2e-adr-406.mjs b/v3/@claude-flow/cli/scripts/e2e-adr-406.mjsnew file mode 100644index 0000000000..056ca5cbe5--- /dev/null+++ b/v3/@claude-flow/cli/scripts/e2e-adr-406.mjs@@ -0,0 +1,304 @@+#!/usr/bin/env node+/**+ * ADR-406 end-to-end gate, run against the BUILT CLI (`npm run build` first).+ *+ * Every step runs in throwaway directories: a temp project, a temp HOME and a+ * temp CLAUDE_CONFIG_DIR, so the person's real ~/.claude and ~/.claude-flow are+ * never read or written. Live Claude Code steps run only with RUFLO_E2E_LIVE=1+ * and only call `--version` and `plugin validate` (no model, no spend).+ *+ * node scripts/e2e-adr-406.mjs # exit 0 = every step passed+ * RUFLO_E2E_LIVE=1 node scripts/e2e-adr-406.mjs+ */++import { spawn, spawnSync } from 'node:child_process';+import { createHash } from 'node:crypto';+import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs';+import { homedir, tmpdir } from 'node:os';+import { dirname, join, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';++const CLI_DIR = resolve(dirname(fileURLToPath(import.meta.url)), '..');+const REPO = resolve(CLI_DIR, '../../..');+const BIN = join(CLI_DIR, 'bin', 'cli.js');+const MCP_BIN = join(CLI_DIR, 'bin', 'mcp-server.js');+if (!existsSync(join(CLI_DIR, 'dist', 'src', 'missions', 'index.js'))) {+ console.error('dist/ is missing the missions module: run `npm run build` first');+ process.exit(2);+}++const scratch = mkdtempSync(join(tmpdir(), 'ruflo-e2e-406-'));+const HOME = join(scratch, 'home');+const CONFIG = join(scratch, 'claude-config');+for (const d of [HOME, CONFIG]) spawnSync('mkdir', ['-p', d]);+const ENV = {+ ...process.env,+ HOME,+ USERPROFILE: HOME,+ CLAUDE_CONFIG_DIR: CONFIG,+ RUFLO_DAEMON_AUTOSTART: '0',+ CLAUDE_FLOW_CWD: '',+ NO_COLOR: '1',+};+delete ENV.CLAUDE_FLOW_CWD;++const results = [];+async function step(name, fn) {+ const started = Date.now();+ try {+ const detail = await fn();+ results.push({ step: name, ok: true, ms: Date.now() - started, ...(detail ? { detail } : {}) });+ } catch (error) {+ results.push({ step: name, ok: false, ms: Date.now() - started, error: String(error?.message ?? error) });+ }+}+function assert(cond, message) { if (!cond) throw new Error(message); }++function project(name) {+ const dir = join(scratch, name);+ spawnSync('mkdir', ['-p', join(dir, '.claude-flow')]);+ return dir;+}++/** Run the built CLI; stdout's last JSON object is returned. */+function cli(cwd, args) {+ const r = spawnSync(process.execPath, [BIN, ...args], { cwd, env: ENV, encoding: 'utf8', timeout: 120_000 });+ const out = r.stdout ?? '';+ const start = out.indexOf('{');+ let json = null;+ if (start >= 0) { try { json = JSON.parse(out.slice(start, out.lastIndexOf('}') + 1)); } catch { /* not json */ } }+ return { status: r.status, stdout: out, stderr: r.stderr ?? '', json };+}++/** A stdio MCP session against the built server in `cwd`. */+function mcpSession(cwd) {+ const child = spawn(process.execPath, [MCP_BIN], { cwd, env: ENV, stdio: ['pipe', 'pipe', 'pipe'] });+ let buffer = '';+ let nextId = 1;+ const waiting = new Map();+ child.stdout.setEncoding('utf8');+ child.stdout.on('data', (chunk) => {+ buffer += chunk;+ let nl;+ while ((nl = buffer.indexOf('\n')) >= 0) {+ const line = buffer.slice(0, nl).trim();+ buffer = buffer.slice(nl + 1);+ if (!line.startsWith('{')) continue;+ try {+ const msg = JSON.parse(line);+ if (msg.id !== undefined && waiting.has(msg.id)) { waiting.get(msg.id)(msg); waiting.delete(msg.id); }+ } catch { /* log noise */ }+ }+ });+ const request = (method, params) => new Promise((done, fail) => {+ const id = nextId++;+ const timer = setTimeout(() => fail(new Error(`MCP ${method} timed out`)), 60_000);+ waiting.set(id, (msg) => { clearTimeout(timer); done(msg); });+ child.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', id, method, params })}\n`);+ });+ return {+ async init() { await request('initialize', { protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 'e2e-adr-406', version: '1' } }); },+ async tool(name, args) {+ const msg = await request('tools/call', { name, arguments: args });+ if (msg.error) throw new Error(`${name}: ${JSON.stringify(msg.error)}`);+ return JSON.parse(msg.result.content[0].text);+ },+ close() { child.kill('SIGTERM'); },+ };+}++function hashCommandFiles() {+ const out = {};+ const walk = (dir) => {+ if (!existsSync(dir)) return;+ for (const name of readdirSync(dir)) {+ const full = join(dir, name);+ if (name === 'node_modules') continue;+ if (statSync(full).isDirectory()) walk(full);+ else if (full.includes('/commands/') && name.endsWith('.md')) out[full] = createHash('sha256').update(readFileSync(full)).digest('hex');+ }+ };+ for (const d of ['.claude/commands', 'v3/@claude-flow/cli/.claude/commands', 'plugins']) walk(join(REPO, d));+ return out;+}++const PLAN = {+ tasks: [+ { id: 'produce', title: 'Produce artifact', executor: { mode: 'durable-executor', requirement: 'ruos-job' }, estimatedCostMinor: 100 },+ { id: 'evaluate', title: 'Evaluate artifact', dependsOn: ['produce'], executor: { mode: 'durable-executor', requirement: 'metaharness' }, acceptanceEvidence: ['quality'] },+ { id: 'verify', title: 'Verify acceptance', dependsOn: ['evaluate'], executor: { mode: 'session-bound', requirement: 'claude-session' } },+ ],+ acceptance: [{ id: 'quality', check: 'score >= baseline', producer: 'metaharness', independent: true }],+ budget: { currency: 'USD', ceilingMinor: 1000 },+};++// ---------------------------------------------------------------------------++const before = hashCommandFiles();++await step('catalog: committed catalog is current and deterministic', () => {+ const p = project('catalog');+ const check = cli(p, ['catalog', 'generate', '--check', '--json', '--repo-root', REPO]);+ assert(check.status === 0 && check.json?.upToDate === true, `catalog stale or failed: ${check.stdout.slice(-400)} ${check.stderr.slice(-400)}`);+ const verify = cli(p, ['catalog', 'verify', '--json', '--repo-root', REPO]);+ assert(verify.status === 0 && verify.json?.valid === true, `verify failed: ${verify.stdout.slice(-400)}`);+ return check.json.summary;+});++await step('catalog: legacy command files byte-unchanged', () => {+ const after = hashCommandFiles();+ assert(Object.keys(before).length > 300, 'too few command files found');+ assert(JSON.stringify(after) === JSON.stringify(before), 'a legacy command file changed');+ return { files: Object.keys(after).length };+});++const shared = project('shared');+let missionId = '';+await step('mission: create via CLI, plan via MCP, both read the same state', async () => {+ const created = cli(shared, ['mission', 'create', '--objective', 'Ship a verified artifact', '--request-id', 'e2e-create']);+ assert(created.status === 0 && created.json?.ok, `create failed: ${created.stdout} ${created.stderr.slice(-300)}`);+ missionId = created.json.data.missionId;+ const mcp = mcpSession(shared);+ try {+ await mcp.init();+ const again = await mcp.tool('mission_create', { requestId: 'e2e-create', objective: 'Ship a verified artifact' });+ assert(again.ok && again.data.deduplicated && again.data.missionId === missionId, 'MCP create did not deduplicate to the CLI mission');+ const planned = await mcp.tool('mission_plan', { requestId: 'e2e-plan', missionId, expectedRevision: 1, plan: PLAN });+ assert(planned.ok && planned.data.state === 'planned' && planned.data.revision === 2, `MCP plan failed: ${JSON.stringify(planned)}`);+ const viaMcp = await mcp.tool('mission_get', { missionId });+ const viaCli = cli(shared, ['mission', 'get', '--mission', missionId]).json;+ assert(JSON.stringify(viaMcp.data.record) === JSON.stringify(viaCli.data.record), 'CLI and MCP records differ');+ const evMcp = await mcp.tool('mission_events', { missionId, afterSequence: 0 });+ const evCli = cli(shared, ['mission', 'events', '--mission', missionId, '--after', '0']).json;+ assert(JSON.stringify(evMcp.data.events) === JSON.stringify(evCli.data.events), 'CLI and MCP events differ');+ assert(evCli.data.events.map((e) => e.channel).join(',') === 'cli,mcp', 'event channels not recorded');+ return { missionId, revision: viaCli.data.record.revision, executionMode: viaCli.data.record.executionMode };+ } finally {+ mcp.close();+ }+});++await step('mission: revision conflict is rejected with the current revision', () => {+ const planFile = join(shared, 'plan2.json');+ writeFileSync(planFile, JSON.stringify({ ...PLAN, budget: { currency: 'USD', ceilingMinor: 2000 } }));+ const r = cli(shared, ['mission', 'plan', '--mission', missionId, '--expected-revision', '1', '--plan-file', planFile, '--request-id', 'e2e-stale']);+ assert(r.status === 3 && r.json?.code === 'revision-conflict' && r.json.currentRevision === 2, `expected conflict: ${r.stdout}`);+});++await step('mission: honest refusal of admission without a durable executor', () => {+ const r = cli(shared, ['mission', 'action', '--mission', missionId, '--expected-revision', '2', '--action', 'admit', '--request-id', 'e2e-admit']);+ assert(r.status === 1 && r.json?.code === 'executor-unavailable', `expected executor-unavailable: ${r.stdout}`);+});++await step('mission: kill a writer mid-stream, restart, reconstruct state', async () => {+ const p = project('kill');+ const childSrc = join(scratch, 'kill-writer.mjs');+ writeFileSync(childSrc, `+ import { MissionService } from ${JSON.stringify(join(CLI_DIR, 'dist/src/missions/index.js'))};+ const s = new MissionService({ projectRoot: process.argv[2], channel: 'cli' });+ const c = await s.create({ requestId: 'k', objective: 'survive SIGKILL' });+ let rev = c.data.revision; console.log('ready ' + c.data.missionId);+ const plan = ${JSON.stringify(PLAN)};+ for (let i = 0; ; i++) {+ const r = await s.plan({ requestId: 'k' + i, missionId: c.data.missionId, expectedRevision: rev, plan: { ...plan, budget: { currency: 'USD', ceilingMinor: 1000 + i } } });+ if (!r.ok) throw new Error(r.message); rev = r.data.revision;+ }`);+ const child = spawn(process.execPath, [childSrc, p], { env: ENV, stdio: ['ignore', 'pipe', 'pipe'] });+ const id = await new Promise((done, fail) => {+ child.stdout.on('data', (d) => { const m = String(d).match(/ready (msn_[a-f0-9]{24})/); if (m) done(m[1]); });+ child.on('exit', (code) => fail(new Error(`writer exited ${code}`)));+ });+ const log = join(p, '.claude-flow', 'missions', id, 'events.jsonl');+ const deadline = Date.now() + 20_000;+ while ((existsSync(log) ? readFileSync(log, 'utf8').split('\n').length : 0) < 40 && Date.now() < deadline) await new Promise((r) => setTimeout(r, 25));+ child.kill('SIGKILL');+ await new Promise((r) => child.on('exit', r));+ const got = cli(p, ['mission', 'get', '--mission', id]).json;+ assert(got?.ok, 'get after kill failed');+ const events = cli(p, ['mission', 'events', '--mission', id, '--limit', '500']).json;+ assert(events.ok && events.data.lastEventSequence === got.data.record.lastEventSequence, 'snapshot and log disagree after kill');+ const mcp = mcpSession(p);+ try {+ await mcp.init();+ const next = await mcp.tool('mission_plan', { requestId: 'after-kill', missionId: id, expectedRevision: got.data.record.revision, plan: PLAN });+ assert(next.ok && next.data.revision === got.data.record.revision + 1, `writer after kill failed: ${JSON.stringify(next)}`);+ } finally {+ mcp.close();+ }+ return { eventsBeforeKill: events.data.lastEventSequence, revisionAfterRestart: got.data.record.revision + 1 };+});++await step('§18 fixture replay: mods off vs on leaves permissions, policy and outcomes unchanged', () => {+ const fixture = (p) => {+ const outcomes = [];+ const c = cli(p, ['mission', 'create', '--objective', 'fixture', '--request-id', 'fx-1']).json;+ outcomes.push(c.ok, c.data.state);+ const pf = join(p, 'plan.json');+ writeFileSync(pf, JSON.stringify(PLAN));+ const pl = cli(p, ['mission', 'plan', '--mission', c.data.missionId, '--expected-revision', '1', '--plan-file', pf, '--request-id', 'fx-2']).json;+ outcomes.push(pl.ok, pl.data?.state);+ const stale = cli(p, ['mission', 'plan', '--mission', c.data.missionId, '--expected-revision', '1', '--plan-file', pf, '--request-id', 'fx-3']).json;+ outcomes.push(stale.code);+ const admit = cli(p, ['mission', 'action', '--mission', c.data.missionId, '--expected-revision', '2', '--action', 'admit', '--request-id', 'fx-4']).json;+ outcomes.push(admit.code);+ const cancel = cli(p, ['mission', 'action', '--mission', c.data.missionId, '--expected-revision', '2', '--action', 'cancel', '--request-id', 'fx-5']).json;+ outcomes.push(cancel.data?.state);+ const ev = cli(p, ['mission', 'events', '--mission', c.data.missionId]).json;+ outcomes.push(ev.data.events.map((e) => e.type).join('>'));+ return outcomes;+ };+ const permissions = (p) => {+ const read = (f) => (existsSync(f) ? JSON.parse(readFileSync(f, 'utf8')).permissions ?? null : null);+ const policy = cli(p, ['policy', 'status']).stdout;+ const mode = (policy.match(/"mode":\s*"(\w+)"/) ?? [])[1] ?? 'unknown';+ return JSON.stringify({ local: read(join(p, '.claude', 'settings.local.json')), project: read(join(p, '.claude', 'settings.json')), mode });+ };+ const off = project('mods-off');+ const on = project('mods-on');+ spawnSync('mkdir', ['-p', join(off, '.claude'), join(on, '.claude')]);+ // A real permissions block the mod must neither widen nor drop.+ const seeded = JSON.stringify({ permissions: { allow: ['Bash(npm test)'], deny: ['Bash(rm -rf *)'], ask: ['Bash(git push:*)'] } }, null, 2);+ for (const p of [off, on]) writeFileSync(join(p, '.claude', 'settings.local.json'), seeded);+ const permOffBefore = permissions(off);+ const permOnBefore = permissions(on);+ const install = cli(on, ['mods', 'install']);+ assert(install.status === 0, `mods install failed: ${install.stdout.slice(-300)} ${install.stderr.slice(-300)}`);+ const settings = JSON.parse(readFileSync(join(on, '.claude', 'settings.local.json'), 'utf8'));+ assert(JSON.stringify(settings).includes('ruflo-mods'), 'mods install did not enable the plugin');+ const permOnAfterInstall = permissions(on);+ const outOff = fixture(off);+ const outOn = fixture(on);+ assert(JSON.stringify(outOff) === JSON.stringify(outOn), `outcomes differ: off=${JSON.stringify(outOff)} on=${JSON.stringify(outOn)}`);+ assert(permOnBefore === permOnAfterInstall, `mods install changed permissions or policy mode: ${permOnBefore} -> ${permOnAfterInstall}`);+ assert(permOffBefore === permissions(off), 'permissions drifted with mods off');+ assert(permOnAfterInstall === permissions(on), 'permissions drifted with mods on');+ const uninstall = cli(on, ['mods', 'uninstall']);+ assert(uninstall.status === 0, 'mods uninstall failed');+ assert(permissions(on) === permOnBefore, 'uninstall did not restore permissions');+ return { outcomes: outOff, permissions: JSON.parse(permOnBefore) };+});++await step('no real ~/.claude or ~/.claude-flow touched', () => {+ assert(ENV.HOME !== homedir() && ENV.CLAUDE_CONFIG_DIR.startsWith(scratch), 'HOME or CLAUDE_CONFIG_DIR was not isolated');+ return { home: 'isolated', claudeConfigDir: 'isolated' };+});++if (process.env.RUFLO_E2E_LIVE === '1') {+ await step('live: engine version and plugin validate (no model calls)', () => {+ const claude = join(homedir(), '.local', 'bin', 'claude');+ assert(existsSync(claude), 'claude executable not found');+ const version = spawnSync(claude, ['--version'], { env: ENV, encoding: 'utf8' });+ const validate = ['ruflo-mods', 'ruflo-swarm'].map((p) => spawnSync(claude, ['plugin', 'validate', join(REPO, 'plugins', p)], { env: ENV, encoding: 'utf8' }));+ assert(validate.every((v) => v.status === 0), 'plugin validate failed');+ const engine = cli(project('engine'), ['catalog', 'engine', '--json', '--repo-root', REPO, '--engine', claude]).json;+ assert(engine?.collisions?.find((c) => c.name === 'ruflo')?.verdict === 'free', 'bare /ruflo collision');+ return { version: version.stdout.trim(), validated: ['ruflo-mods', 'ruflo-swarm'] };+ });+} else {+ results.push({ step: 'live: engine steps', ok: true, skipped: 'set RUFLO_E2E_LIVE=1' });+}++rmSync(scratch, { recursive: true, force: true });+const failed = results.filter((r) => !r.ok);+console.log(JSON.stringify({ adr: 406, passed: results.length - failed.length, failed: failed.length, results }, null, 2));+process.exit(failed.length ? 1 : 0);diff --git a/v3/@claude-flow/cli/src/commands/index.ts b/v3/@claude-flow/cli/src/commands/index.tsindex 2bc7875c48..439b5ca835 100644--- a/v3/@claude-flow/cli/src/commands/index.ts+++ b/v3/@claude-flow/cli/src/commands/index.ts@@ -101,6 +101,7 @@ const commandLoaders: Record<string, CommandLoader> = {mods: () => import('./mods.js'),// ADR-406 command catalog and mission control (interim homes until mods.ts follow-up)catalog: () => import('./catalog.js'),+ mission: () => import('./mission.js'),// Ruflo entries in Claude Code's companyAnnouncements startup rotation (ADR-319)announcements: () => import('./announcements.js'),// AGNTCY/Outshift runtime transport selection (ADR-324 §2) — optional,diff --git a/v3/@claude-flow/cli/src/commands/mission.ts b/v3/@claude-flow/cli/src/commands/mission.tsnew file mode 100644index 0000000000..41d123237a--- /dev/null+++ b/v3/@claude-flow/cli/src/commands/mission.ts@@ -0,0 +1,117 @@+/**+ * `ruflo mission` — ADR-406 §19.7 mission operations from the CLI.+ *+ * mission create --objective <text> [--request-id <id>]+ * mission plan --mission <id> --expected-revision <n> --plan-file <json> [--request-id <id>]+ * mission get [--mission <id>]+ * mission events --mission <id> [--after <seq>] [--limit <n>]+ * mission action --mission <id> --expected-revision <n> --action <requestAuthorization|pause|cancel|admit|resume> [--reason <text>]+ *+ * Flags map one-to-one onto the raw input the MCP tools receive; the shared+ * `MissionService` validates both. Output is JSON. A missing request id gets a+ * fresh one: a new id is a new intentional request (ADR-406 §9); pass the same+ * id to retry the same request safely.+ */++import { randomUUID } from 'node:crypto';+import { lstatSync, readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import type { Command, CommandContext, CommandResult } from '../types.js';+import { output } from '../output.js';+import { MissionService } from '../missions/service.js';+import type { MissionPort } from '../mcp-tools/mission-tools.js';++const PLAN_FILE_MAX_BYTES = 256 * 1024;++export type MissionPortFactoryCli = (projectRoot: string) => MissionPort;+let factory: MissionPortFactoryCli = (projectRoot) => new MissionService({ projectRoot, channel: 'cli' });++/** Test seam (London school): substitute the service the command talks to. */+export function setMissionPortFactory(next: MissionPortFactoryCli | null): void {+ factory = next ?? ((projectRoot) => new MissionService({ projectRoot, channel: 'cli' }));+}++function int(value: unknown): number | undefined {+ if (value === undefined || value === null || value === '') return undefined;+ const n = Number(value);+ return Number.isFinite(n) ? n : Number.NaN;+}++function readPlanFile(path: string): unknown {+ const stat = lstatSync(path);+ if (!stat.isFile()) throw new Error('plan-file must be a regular file');+ if (stat.size > PLAN_FILE_MAX_BYTES) throw new Error(`plan-file exceeds ${PLAN_FILE_MAX_BYTES} bytes`);+ return JSON.parse(readFileSync(path, 'utf8'));+}++/** Raw operation input from flags; undefined fields are dropped so defaults apply. */+export function inputFromFlags(op: string, flags: Record<string, unknown>, cwd: string): Record<string, unknown> {+ const raw: Record<string, unknown> = {};+ const set = (key: string, value: unknown) => { if (value !== undefined) raw[key] = value; };+ const requestId = typeof flags.requestId === 'string' ? flags.requestId : randomUUID();+ if (op === 'create') {+ set('requestId', requestId);+ set('objective', flags.objective);+ } else if (op === 'plan') {+ set('requestId', requestId);+ set('missionId', flags.mission);+ set('expectedRevision', int(flags.expectedRevision));+ if (typeof flags.planFile === 'string') set('plan', readPlanFile(resolve(cwd, flags.planFile)));+ } else if (op === 'get') {+ set('missionId', flags.mission);+ } else if (op === 'events') {+ set('missionId', flags.mission);+ set('afterSequence', int(flags.after));+ set('limit', int(flags.limit));+ } else if (op === 'action') {+ set('requestId', requestId);+ set('missionId', flags.mission);+ set('expectedRevision', int(flags.expectedRevision));+ set('action', flags.action);+ set('reason', flags.reason);+ }+ return raw;+}++export const missionCommand: Command = {+ name: 'mission',+ description: 'ADR-406 mission control: create, plan, get, events, action (shared runtime with the mission_* MCP tools)',+ options: [+ { name: 'objective', type: 'string', description: 'create: mission objective' },+ { name: 'mission', type: 'string', description: 'Mission id (msn_…)' },+ { name: 'request-id', type: 'string', description: 'Idempotency key; reuse only to retry the same request' },+ { name: 'expected-revision', type: 'number', description: 'Revision the request was prepared against' },+ { name: 'plan-file', type: 'string', description: 'plan: JSON file with { tasks, acceptance, budget, scope }' },+ { name: 'after', type: 'number', description: 'events: cursor (last sequence seen)' },+ { name: 'limit', type: 'number', description: 'events: page size (max 500)' },+ { name: 'action', type: 'string', description: 'action: requestAuthorization | pause | cancel | admit | resume' },+ { name: 'reason', type: 'string', description: 'action: reason' },+ { name: 'project-root', type: 'string', description: 'Project root (default: cwd)' },+ ],+ examples: [+ { command: 'ruflo mission create --objective "Ship the report" --request-id r1', description: 'Create a draft mission' },+ { command: 'ruflo mission plan --mission msn_… --expected-revision 1 --plan-file plan.json', description: 'Submit a plan' },+ { command: 'ruflo mission events --mission msn_… --after 0', description: 'Read events from a cursor' },+ ],+ async action(ctx: CommandContext): Promise<CommandResult> {+ const flags = ctx.flags as Record<string, unknown>;+ const op = ctx.args[0] ?? 'get';+ const root = resolve(String(flags.projectRoot ?? ctx.cwd ?? process.cwd()));+ const ops: Record<string, keyof MissionPort> = { create: 'create', plan: 'plan', get: 'get', events: 'events', action: 'requestAction' };+ const method = ops[op];+ if (!method) {+ output.printError(`unknown mission operation: ${op} (create | plan | get | events | action)`);+ return { success: false, exitCode: 1 };+ }+ let result;+ try {+ result = await factory(root)[method](inputFromFlags(op, flags, root));+ } catch (error) {+ result = { ok: false as const, code: 'invalid-input', message: error instanceof Error ? error.message : String(error) };+ }+ output.writeln(JSON.stringify(result, null, 2));+ return { success: result.ok, exitCode: result.ok ? 0 : result.code === 'revision-conflict' ? 3 : 1, data: result };+ },+};++export default missionCommand;diff --git a/v3/@claude-flow/cli/src/mcp-client.ts b/v3/@claude-flow/cli/src/mcp-client.tsindex 38a5bf3663..ef9d011a87 100644--- a/v3/@claude-flow/cli/src/mcp-client.ts+++ b/v3/@claude-flow/cli/src/mcp-client.ts@@ -78,6 +78,7 @@ import { businessPodTools } from './mcp-tools/business-pod-tools.js';// for ops-pod synthetic-endpoint benches). Default-rejects private addresses// + auth headers; opt-in via CLAUDE_FLOW_HTTP_FETCH_ALLOW_PRIVATE / _AUTH=1.import { httpFetchTools } from './mcp-tools/http-fetch-tools.js';+import { missionTools } from './mcp-tools/mission-tools.js';// #1916: coverage-aware routing tools — defined in ruvector/coverage-tools.ts// but were never registered, so the `ruflo hooks coverage-*` CLI subcommands// failed with `Tool not found: hooks_coverage-route`.@@ -191,6 +192,8 @@ registerTools([...businessPodTools,// ADR-164 Phase 4 §5.1.8 — http_fetch (1 tool, secure-by-default HTTP probe)...httpFetchTools,+ // ADR-406 — mission semantic operations (create/plan/get/events/request_action)+ ...missionTools,]);// The capability brain consumes the completed live registry. This is injecteddiff --git a/v3/@claude-flow/cli/src/mcp-tools/capability-brain.ts b/v3/@claude-flow/cli/src/mcp-tools/capability-brain.tsindex 69228f1182..5b158e42d2 100644--- a/v3/@claude-flow/cli/src/mcp-tools/capability-brain.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/capability-brain.ts@@ -433,7 +433,7 @@ export const CAPABILITY_DOMAINS: readonly CapabilityDomainDefinition[] = [{id: 'tasks-workflows-sessions',name: 'Tasks, Workflows, Sessions & Progress',- prefixes: ['task_', 'workflow_', 'session_', 'progress_'],+ prefixes: ['task_', 'workflow_', 'session_', 'progress_', 'mission_'],description: 'Task orchestration, reusable workflows, session state, progress, and handoff.',taskSignals: ['task', 'workflow', 'session', 'handoff', 'progress'],commands: ['task create', 'task status', 'workflow run'],diff --git a/v3/@claude-flow/cli/src/mcp-tools/index.ts b/v3/@claude-flow/cli/src/mcp-tools/index.tsindex 6813798fa5..d5a9c86b03 100644--- a/v3/@claude-flow/cli/src/mcp-tools/index.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/index.ts@@ -68,3 +68,5 @@ export { xFederationChannelTools } from './x-federation-channels.js';export { businessPodTools } from './business-pod-tools.js';// ADR-164 Phase 4 §5.1.8 — http_fetch (secure-by-default HTTP probe)export { httpFetchTools } from './http-fetch-tools.js';+// ADR-406 — mission semantic operations+export { missionTools, createMissionTools } from './mission-tools.js';diff --git a/v3/@claude-flow/cli/src/mcp-tools/mission-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/mission-tools.tsnew file mode 100644index 0000000000..98ab818deb--- /dev/null+++ b/v3/@claude-flow/cli/src/mcp-tools/mission-tools.ts@@ -0,0 +1,93 @@+/**+ * ADR-406 §19.7 — MCP adapter for the mission semantic operations.+ *+ * A thin transport: input goes to the same `MissionService` (and the same zod+ * schemas) the CLI uses, unchanged. Policy authorization of the tool call+ * itself happens in `mcp-client.ts` before any handler runs; nothing here+ * accepts an approval, principal or permission flag from input.+ */++import type { MCPTool } from './types.js';+import { getProjectCwd } from './types.js';+import { MissionService, type MissionResult } from '../missions/service.js';++/** The operations an adapter needs; London-school tests substitute it. */+export interface MissionPort {+ create(raw: unknown): Promise<MissionResult<unknown>>;+ plan(raw: unknown): Promise<MissionResult<unknown>>;+ get(raw: unknown): Promise<MissionResult<unknown>>;+ events(raw: unknown): Promise<MissionResult<unknown>>;+ requestAction(raw: unknown): Promise<MissionResult<unknown>>;+}++export type MissionPortFactory = (projectRoot: string) => MissionPort;++const defaultFactory: MissionPortFactory = (projectRoot) => new MissionService({ projectRoot, channel: 'mcp' });++function rootOf(context?: Record<string, unknown>): string {+ return typeof context?.projectRoot === 'string' ? context.projectRoot : getProjectCwd();+}++const MISSION_ID = { type: 'string', pattern: '^msn_[a-f0-9]{24}$', description: 'Mission id' };+const REQUEST_ID = { type: 'string', maxLength: 128, description: 'Caller-chosen idempotency key; reuse only to retry the same request' };+const EXPECTED_REVISION = { type: 'integer', minimum: 1, description: 'Mission revision the request was prepared against' };++export function createMissionTools(factory: MissionPortFactory = defaultFactory): MCPTool[] {+ const call = (op: keyof MissionPort) => async (input: Record<string, unknown>, context?: Record<string, unknown>) =>+ factory(rootOf(context))[op](input);+ return [+ {+ name: 'mission_create',+ description: 'Create a mission (objective only; draft state). Idempotent per requestId. Recording a mission does not execute anything.',+ category: 'mission',+ inputSchema: { type: 'object', properties: { requestId: REQUEST_ID, objective: { type: 'string', maxLength: 2000 } }, required: ['requestId', 'objective'] },+ handler: call('create'),+ },+ {+ name: 'mission_plan',+ description: 'Submit or revise a mission plan (task graph, acceptance criteria, budget). Requires expectedRevision; a stale revision returns a conflict with the current one. Revising invalidates prior authorization.',+ category: 'mission',+ inputSchema: {+ type: 'object',+ properties: { requestId: REQUEST_ID, missionId: MISSION_ID, expectedRevision: EXPECTED_REVISION, plan: { type: 'object', description: '{ tasks[], acceptance[], budget{currency, ceilingMinor}, scope }' } },+ required: ['requestId', 'missionId', 'expectedRevision', 'plan'],+ },+ handler: call('plan'),+ },+ {+ name: 'mission_get',+ description: 'Read one mission (record, plan, budget, tasks, evidence, executor observation) or list missions. Read only; task status is recorded state, only evidence.verified is verified.',+ category: 'mission',+ inputSchema: { type: 'object', properties: { missionId: MISSION_ID } },+ handler: call('get'),+ },+ {+ name: 'mission_events',+ description: 'Mission events after a cursor (afterSequence). Delivery may repeat: deduplicate by (missionId, seq). gap=true means reload with mission_get before replaying.',+ category: 'mission',+ inputSchema: {+ type: 'object',+ properties: { missionId: MISSION_ID, afterSequence: { type: 'integer', minimum: 0 }, limit: { type: 'integer', minimum: 1, maximum: 500 } },+ required: ['missionId'],+ },+ handler: call('events'),+ },+ {+ name: 'mission_request_action',+ description: 'Request a scoped control action: requestAuthorization, pause, cancel (admit/resume report executor-unavailable until a durable executor is admitted). A request is not authorization; the runtime decides.',+ category: 'mission',+ inputSchema: {+ type: 'object',+ properties: {+ requestId: REQUEST_ID, missionId: MISSION_ID, expectedRevision: EXPECTED_REVISION,+ action: { type: 'string', enum: ['requestAuthorization', 'pause', 'cancel', 'admit', 'resume'] },+ reason: { type: 'string', maxLength: 500 },+ },+ required: ['requestId', 'missionId', 'expectedRevision', 'action'],+ },+ handler: call('requestAction'),+ },+ ];+}++export const missionTools: MCPTool[] = createMissionTools();diff --git a/v3/@claude-flow/cli/src/mods/command-registry/catalog.generated.json b/v3/@claude-flow/cli/src/mods/command-registry/catalog.generated.jsonindex 73a909422f..624e55274a 100644--- a/v3/@claude-flow/cli/src/mods/command-registry/catalog.generated.json+++ b/v3/@claude-flow/cli/src/mods/command-registry/catalog.generated.json@@ -11998,7 +11998,7 @@"schemaVersion": 1,"source": {"commit": "8a1e11f3bde0ba6c3855f23e420eeb6f003c8374",- "path": "plugins/ruflo-mods/hooks/register.ts",+ "path": "plugins/ruflo-mods/hooks/session.ts","repository": "ruvnet/ruflo"},"viewId": "ruflo-mods/ruflo-mods"@@ -12011,11 +12011,11 @@{"binding": "mod-register","channel": "mod-registration",- "digest": "sha256:267dec2e2e39444fa3e74090597e744270a4e3895cc9e9cee9a715300c6edb61",+ "digest": "sha256:1e09a065293c6375ba3b3217df30af34c13ac2bb76c45a999481aa0d66d1829d","observedInvocation": "/ruflo-mods","package": "ruflo-mods@ruflo","shippedIn": [],- "sourcePath": "plugins/ruflo-mods/hooks/register.ts"+ "sourcePath": "plugins/ruflo-mods/hooks/session.ts"}],"status": "shipped"@@ -12718,7 +12718,7 @@"schemaVersion": 1,"source": {"commit": "8ceed8810b9bbae9596270f5172935ae62edfe5b",- "path": "plugins/ruflo-swarm/hooks/register.ts",+ "path": "plugins/ruflo-swarm/hooks/commands.ts","repository": "ruvnet/ruflo"},"viewId": "ruflo-swarm/ruflo-swarm-claims"@@ -12731,11 +12731,11 @@{"binding": "mod-register","channel": "mod-registration",- "digest": "sha256:2a743e04846e61d9bce6c9a39c266a8e44977c055d590b53697b950cc21f5bf1",+ "digest": "sha256:881c470446c3b0d20e4930b23001cb20ca2f0689562350546e30737869616234","observedInvocation": "/ruflo-swarm-claims","package": "ruflo-swarm@ruflo","shippedIn": [],- "sourcePath": "plugins/ruflo-swarm/hooks/register.ts"+ "sourcePath": "plugins/ruflo-swarm/hooks/commands.ts"}],"status": "shipped"@@ -12763,7 +12763,7 @@"schemaVersion": 1,"source": {"commit": "8ceed8810b9bbae9596270f5172935ae62edfe5b",- "path": "plugins/ruflo-swarm/hooks/register.ts",+ "path": "plugins/ruflo-swarm/hooks/commands.ts","repository": "ruvnet/ruflo"},"viewId": "ruflo-swarm/ruflo-swarm-consensus"@@ -12776,11 +12776,11 @@{"binding": "mod-register","channel": "mod-registration",- "digest": "sha256:2a743e04846e61d9bce6c9a39c266a8e44977c055d590b53697b950cc21f5bf1",+ "digest": "sha256:881c470446c3b0d20e4930b23001cb20ca2f0689562350546e30737869616234","observedInvocation": "/ruflo-swarm-consensus","package": "ruflo-swarm@ruflo","shippedIn": [],- "sourcePath": "plugins/ruflo-swarm/hooks/register.ts"+ "sourcePath": "plugins/ruflo-swarm/hooks/commands.ts"}],"status": "shipped"@@ -12808,7 +12808,7 @@"schemaVersion": 1,"source": {"commit": "8ceed8810b9bbae9596270f5172935ae62edfe5b",- "path": "plugins/ruflo-swarm/hooks/register.ts",+ "path": "plugins/ruflo-swarm/hooks/commands.ts","repository": "ruvnet/ruflo"},"viewId": "ruflo-swarm/ruflo-swarm-pane"@@ -12821,11 +12821,11 @@{"binding": "mod-register","channel": "mod-registration",- "digest": "sha256:2a743e04846e61d9bce6c9a39c266a8e44977c055d590b53697b950cc21f5bf1",+ "digest": "sha256:881c470446c3b0d20e4930b23001cb20ca2f0689562350546e30737869616234","observedInvocation": "/ruflo-swarm-pane","package": "ruflo-swarm@ruflo","shippedIn": [],- "sourcePath": "plugins/ruflo-swarm/hooks/register.ts"+ "sourcePath": "plugins/ruflo-swarm/hooks/commands.ts"}],"status": "shipped"@@ -12853,7 +12853,7 @@"schemaVersion": 1,"source": {"commit": "8ceed8810b9bbae9596270f5172935ae62edfe5b",- "path": "plugins/ruflo-swarm/hooks/register.ts",+ "path": "plugins/ruflo-swarm/hooks/commands.ts","repository": "ruvnet/ruflo"},"viewId": "ruflo-swarm/ruflo-swarm-status"@@ -12866,11 +12866,11 @@{"binding": "mod-register","channel": "mod-registration",- "digest": "sha256:2a743e04846e61d9bce6c9a39c266a8e44977c055d590b53697b950cc21f5bf1",+ "digest": "sha256:881c470446c3b0d20e4930b23001cb20ca2f0689562350546e30737869616234","observedInvocation": "/ruflo-swarm-status","package": "ruflo-swarm@ruflo","shippedIn": [],- "sourcePath": "plugins/ruflo-swarm/hooks/register.ts"+ "sourcePath": "plugins/ruflo-swarm/hooks/commands.ts"}],"status": "shipped"@@ -12898,7 +12898,7 @@"schemaVersion": 1,"source": {"commit": "8ceed8810b9bbae9596270f5172935ae62edfe5b",- "path": "plugins/ruflo-swarm/hooks/register.ts",+ "path": "plugins/ruflo-swarm/hooks/commands.ts","repository": "ruvnet/ruflo"},"viewId": "ruflo-swarm/ruflo-swarm-topology"@@ -12911,11 +12911,11 @@{"binding": "mod-register","channel": "mod-registration",- "digest": "sha256:2a743e04846e61d9bce6c9a39c266a8e44977c055d590b53697b950cc21f5bf1",+ "digest": "sha256:881c470446c3b0d20e4930b23001cb20ca2f0689562350546e30737869616234","observedInvocation": "/ruflo-swarm-topology","package": "ruflo-swarm@ruflo","shippedIn": [],- "sourcePath": "plugins/ruflo-swarm/hooks/register.ts"+ "sourcePath": "plugins/ruflo-swarm/hooks/commands.ts"}],"status": "shipped"@@ -13435,5 +13435,5 @@}],"sourceCommit": "d3a3979ae64380b39020888de5a89e204a108c75",- "sourceDigest": "sha256:35ef993770e59a8747259cbe2e7e3d689663def006086e1b276cc98e81af3fa9"+ "sourceDigest": "sha256:b11779b021abfb7c79ce96683b2ffd48bce766202de14ef9a13d88e9744817a8"}diff --git a/v3/@claude-flow/cli/src/mods/command-registry/generate.ts b/v3/@claude-flow/cli/src/mods/command-registry/generate.tsindex 399b70d982..e90bfb0bf8 100644--- a/v3/@claude-flow/cli/src/mods/command-registry/generate.ts+++ b/v3/@claude-flow/cli/src/mods/command-registry/generate.ts@@ -110,7 +110,11 @@ export function generate(input: GenerateInput): GenerateResult {proposedNames: PROPOSED_NAMES,existingNames: new Set(preliminary.map((r) => r.key)),});- const engineHooks: ModCommandHook[] = hooksFromValidations(engine.validations);+ // The engine confirms which command hooks exist; the source scan knows which+ // file declares each. Prefer the declaring file so the catalog is the same+ // whether or not an engine was available to confirm it.+ const engineHooks: ModCommandHook[] = hooksFromValidations(engine.validations)+ .map((h) => sourceHooks.find((s) => s.plugin === h.plugin && s.command === h.command) ?? h);const useEngine = engine.validations.length > 0 && engine.validations.every((v) => v.passed === true);const inventory = collectInventory({repoRoot: input.repoRoot,