Skip to content

armgit / ruflo

Public Imported from GitHub
0

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

test(mods): declaration-faithful harness, parity and no-double-fire suites, latency bench (ADR-404)

ruv5c74f1ecc3eb
diff --git a/scripts/bench-mods-latency.ts b/scripts/bench-mods-latency.ts
new file mode 100644
index 0000000000..3b54c341a9
--- /dev/null
+++ b/scripts/bench-mods-latency.ts
@@ -0,0 +1,127 @@
+/**
+ * ADR-404 benchmark: per-event latency of the classic hook path (a node
+ * process per event, `hook-handler.cjs <event>`) against the ruflo mod's
+ * in-process handler for the same work, on the same inputs and project.
+ *
+ * npx tsx scripts/bench-mods-latency.ts [--spawn-runs 40] [--inproc-runs 2000] [--json]
+ *
+ * What it measures, and what it does not:
+ * - classic: wall time of spawning the helper with the event on stdin, until
+ * it exits (what Claude Code waits for on every prompt / Bash call / edit);
+ * - classic, handed over: the same spawn with RUFLO_MODS_OWNS set, i.e. what
+ * a classic hook still costs while the mod owns its event;
+ * - mod: the mod's hook run through the declaration-faithful harness
+ * (v3/@claude-flow/cli/__tests__/mods/harness.ts) with real files. It does
+ * NOT include Claude Code's own dispatch or worker hop; those were observed
+ * live separately (ADR-404, "Benchmarks").
+ */
+import { spawnSync } from 'node:child_process';
+import { cpSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { cpus, tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { performance } from 'node:perf_hooks';
+import { fileURLToPath } from 'node:url';
+
+import { register } from '../plugins/ruflo-mods/hooks/register';
+import { loadMod, realWorld } from '../v3/@claude-flow/cli/__tests__/mods/harness';
+
+const arg = (name: string, fallback: number) => {
+ const i = process.argv.indexOf(`--${name}`);
+ return i > 0 ? Number(process.argv[i + 1]) : fallback;
+};
+const SPAWN_RUNS = arg('spawn-runs', 40);
+const INPROC_RUNS = arg('inproc-runs', 2000);
+const REPO = resolve(fileURLToPath(new URL('.', import.meta.url)), '..');
+const HELPERS = join(REPO, 'v3', '@claude-flow', 'cli', '.claude', 'helpers');
+
+type Stats = { n: number; median: number; p95: number; mean: number };
+function stats(samples: number[]): Stats {
+ const s = [...samples].sort((a, b) => a - b);
+ const at = (q: number) => s[Math.min(s.length - 1, Math.floor(q * s.length))]!;
+ return { n: s.length, median: at(0.5), p95: at(0.95), mean: s.reduce((a, b) => a + b, 0) / s.length };
+}
+
+// A project like one `ruflo init` leaves: helpers copied in, a ranked memory file.
+const project = mkdtempSync(join(tmpdir(), 'ruflo-mods-bench-'));
+const home = mkdtempSync(join(tmpdir(), 'ruflo-mods-bench-home-'));
+cpSync(HELPERS, join(project, '.claude', 'helpers'), { recursive: true });
+mkdirSync(join(project, '.claude-flow', 'data'), { recursive: true });
+writeFileSync(join(project, '.claude-flow', 'data', 'ranked-context.json'), JSON.stringify({
+ entries: Array.from({ length: 200 }, (_, i) => ({
+ id: `e${i}`, words: [`topic${i % 17}`, 'implement', 'api', `module${i}`], pageRank: (i % 10) / 100, summary: `entry ${i}`, accessCount: i % 5,
+ })),
+}));
+const helper = join(project, '.claude', 'helpers', 'hook-handler.cjs');
+const env = { PATH: process.env.PATH, HOME: home, CLAUDE_PROJECT_DIR: project, CI: '1', RUFLO_HOOK_DEDUP_DIR: join(home, 'dedup') };
+
+function spawnBench(sub: string, input: object, extraEnv: Record<string, string> = {}, mutate?: (i: number) => object): Stats {
+ const samples: number[] = [];
+ for (let i = 0; i < SPAWN_RUNS + 3; i++) {
+ const t = performance.now();
+ spawnSync(process.execPath, [helper, sub], { input: JSON.stringify(mutate ? mutate(i) : input), cwd: project, env: { ...env, ...extraEnv }, encoding: 'utf8' });
+ if (i >= 3) samples.push(performance.now() - t); // first runs warm the page cache
+ }
+ return stats(samples);
+}
+
+async function inprocBench(run: (i: number) => Promise<unknown>): Promise<Stats> {
+ for (let i = 0; i < 50; i++) await run(i); // JIT warm-up
+ const samples: number[] = [];
+ for (let i = 0; i < INPROC_RUNS; i++) {
+ const t = performance.now();
+ await run(i);
+ samples.push(performance.now() - t);
+ }
+ return stats(samples);
+}
+
+async function main() {
+ const prompt = { prompt: 'implement the api for topic3 with tests' };
+ const world = realWorld(project, {});
+ const mod = loadMod(register, world);
+ await mod.dispatch('session.start', { cwd: project, surface: null, isInteractive: false }, (e: any) => ({ cwd: e.cwd }));
+ const passthrough = (e: any) => e;
+
+ const rows = [
+ {
+ event: 'route (UserPromptSubmit / prompt.submit)',
+ classic: spawnBench('route', prompt),
+ handedOver: spawnBench('route', prompt, { RUFLO_MODS_OWNS: 'route,post-edit' }),
+ mod: await inprocBench(() => mod.dispatch('prompt.submit', { text: prompt.prompt, wait: false, origin: { kind: 'composer' } }, passthrough)),
+ },
+ {
+ event: 'pre-bash (PreToolUse / tool.check)',
+ classic: spawnBench('pre-bash', { tool_input: { command: 'npm test' } }),
+ handedOver: null,
+ mod: await inprocBench(() => mod.dispatch('tool.check', { tool: 'Bash', input: { command: 'npm test' }, tool_use_id: 'b' }, () => ({ decision: 'allow' }))),
+ },
+ {
+ event: 'post-edit (PostToolUse / tool.call)',
+ classic: spawnBench('post-edit', {}, {}, (i) => ({ tool_name: 'Edit', tool_input: { file_path: `src/f${i}.ts` }, tool_use_id: `c${i}` })),
+ handedOver: spawnBench('post-edit', {}, { RUFLO_MODS_OWNS: 'route,post-edit' }, (i) => ({ tool_name: 'Edit', tool_input: { file_path: `src/g${i}.ts` }, tool_use_id: `h${i}` })),
+ mod: await inprocBench((i) => mod.dispatch('tool.call', { tool: 'Edit', tool_use_id: `m${i}`, file_path: `src/m${i}.ts` }, () => ({ result: 'ok' }))),
+ },
+ ];
+ const flush = await inprocBench(async (i) => {
+ await mod.dispatch('tool.call', { tool: 'Edit', tool_use_id: `f${i}`, file_path: `src/f${i}.ts` }, () => ({ result: 'ok' }));
+ await mod.dispatch('turn.complete', { reason: 'answer' }, () => ({ text: '' }));
+ });
+
+ const env = { node: process.version, cpu: cpus()[0]?.model, cores: cpus().length, spawnRuns: SPAWN_RUNS, inprocRuns: INPROC_RUNS };
+ if (process.argv.includes('--json')) {
+ console.log(JSON.stringify({ env, rows, flushPerTurn: flush }, null, 2));
+ } else {
+ const ms = (s: Stats | null) => (s ? `${s.median.toFixed(3)} / ${s.p95.toFixed(3)}` : 'n/a');
+ console.log(`node ${env.node}, ${env.cpu} x${env.cores}; spawn n=${SPAWN_RUNS}, in-process n=${INPROC_RUNS}`);
+ console.log('| event | classic spawn ms (median / p95) | classic, handed over ms | mod handler ms (in-process, no engine hop) |');
+ console.log('|---|---|---|---|');
+ for (const r of rows) {
+ console.log(`| ${r.event} | ${ms(r.classic)} | ${ms(r.handedOver)} | ${ms(r.mod)} |`);
+ }
+ console.log(`| edit + per-turn flush (tool.call + turn.complete) | | | ${ms(flush)} |`);
+ }
+ rmSync(project, { recursive: true, force: true });
+ rmSync(home, { recursive: true, force: true });
+}
+
+main();
diff --git a/v3/@claude-flow/cli/__tests__/mods/harness.ts b/v3/@claude-flow/cli/__tests__/mods/harness.ts
new file mode 100644
index 0000000000..de3326462f
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/mods/harness.ts
@@ -0,0 +1,184 @@
+/**
+ * A harness for the ruflo mod (plugins/ruflo-mods), faithful to the Claude
+ * Code function-hook declarations it is typed against (ADR-404).
+ *
+ * Why not `claude plugin test`: the kit runs only where Claude Code's hooks
+ * module rollout switch is on, and it served off for the account these tests
+ * were written on. This harness reproduces the parts of the contract the mod
+ * relies on, so CI can hold them without Claude Code:
+ * - `on(event, [matcher,] hook)` returns a registration taking one `.catch`;
+ * - a dispatch runs the plugin's hooks for the event in registration order,
+ * outermost first, then core (the world beneath, answered by the test);
+ * - `next(e)` runs what is beneath; a hook that throws with no `.catch` is
+ * absent (what is beneath answers); in a `.catch`, `next` is replay-safe
+ * (`next.called`, `next.error`) and its answer stands;
+ * - `e` is frozen; matchers narrow on equal values, arrays (any of) and RegExps;
+ * - `$` ops: fs.stat rejects ENOENT for a missing path, fs.read rejects
+ * over 4 MiB, env.get/set, settings.read, session.root, ui.*, command.register.
+ * What it does not model: tiers above the mod (sec-default is reasoned about,
+ * not run), budgets, streaming events, rendering.
+ */
+
+import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
+import { dirname } from 'node:path';
+
+type AnyHook = ($: any, e: any, next: any) => any;
+type Registration = { event: string; matcher?: Record<string, unknown>; hook: AnyHook; onCatch?: AnyHook };
+
+export interface World {
+ root: string;
+ /** Real files under `root`, or an in-memory map of absolute path → text. */
+ files: 'real' | Map<string, { text: string; mtimeMs: number }>;
+ env: Map<string, string>;
+ settings: unknown | (() => unknown);
+ statuses: (string | undefined)[];
+ logs: string[];
+ toasts: string[];
+ commands: string[];
+ /** Per-op failure injection: `fs.read` → error to throw for a path. */
+ failRead?: (path: string) => Error | undefined;
+ failLog?: boolean;
+}
+
+export function memoryWorld(root = '/work', settings: unknown = {}): World {
+ return { root, files: new Map(), env: new Map(), settings, statuses: [], logs: [], toasts: [], commands: [] };
+}
+
+export function realWorld(root: string, settings: unknown = {}): World {
+ return { root, files: 'real', env: new Map(), settings, statuses: [], logs: [], toasts: [], commands: [] };
+}
+
+const enoent = (path: string) => Object.assign(new Error(`ENOENT: no such file or directory, '${path}'`), { code: 'ENOENT' });
+
+function engineOf(world: World) {
+ const mem = world.files === 'real' ? undefined : world.files;
+ return {
+ fs: {
+ async stat(path: string) {
+ if (mem) {
+ const f = mem.get(path);
+ if (!f) throw enoent(path);
+ return { kind: 'file', size: Buffer.byteLength(f.text), mtimeMs: f.mtimeMs, isLink: false };
+ }
+ if (!existsSync(path)) throw enoent(path);
+ const s = statSync(path);
+ return { kind: s.isFile() ? 'file' : s.isDirectory() ? 'dir' : 'other', size: s.size, mtimeMs: s.mtimeMs, isLink: false };
+ },
+ async read(path: string) {
+ const injected = world.failRead?.(path);
+ if (injected) throw injected;
+ if (mem) {
+ const f = mem.get(path);
+ if (!f) throw enoent(path);
+ return f.text;
+ }
+ if (!existsSync(path)) throw enoent(path);
+ if (statSync(path).size > 4 * 1024 * 1024) throw new Error(`${path} is over 4 MiB`);
+ return readFileSync(path, 'utf8');
+ },
+ async write(path: string, text: string) {
+ if (mem) {
+ mem.set(path, { text, mtimeMs: (mem.get(path)?.mtimeMs ?? 0) + 1 });
+ return;
+ }
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, text);
+ },
+ async exists(path: string) {
+ return mem ? mem.has(path) : existsSync(path);
+ },
+ },
+ env: {
+ async get(name: string) {
+ return world.env.get(name);
+ },
+ async set(name: string, value: string | undefined) {
+ if (value === undefined) world.env.delete(name);
+ else world.env.set(name, value);
+ },
+ },
+ settings: {
+ async read() {
+ return typeof world.settings === 'function' ? (world.settings as () => unknown)() : world.settings;
+ },
+ },
+ session: {
+ async root() {
+ return world.root;
+ },
+ },
+ command: {
+ async register(spec: { name: string }) {
+ world.commands.push(spec.name);
+ return { command: spec.name };
+ },
+ },
+ ui: {
+ status(text: string | undefined) {
+ world.statuses.push(text);
+ },
+ log(text: string) {
+ if (world.failLog) throw new Error('ui.log refused');
+ world.logs.push(text);
+ },
+ toast(text: string) {
+ world.toasts.push(text);
+ },
+ },
+ };
+}
+
+function matches(matcher: Record<string, unknown> | undefined, e: Record<string, unknown>): boolean {
+ if (!matcher) return true;
+ return Object.entries(matcher).every(([k, want]) => {
+ const got = e[k];
+ if (want instanceof RegExp) return typeof got === 'string' && want.test(got);
+ if (Array.isArray(want)) return want.includes(got);
+ return got === want;
+ });
+}
+
+export type Core = (event: string, e: any) => any;
+
+export function loadMod(register: (on: any, options: any) => unknown, world: World, options: Record<string, unknown> = {}) {
+ const regs: Registration[] = [];
+ const on = (event: string, a: unknown, b?: unknown) => {
+ const reg: Registration = b ? { event, matcher: a as Record<string, unknown>, hook: b as AnyHook } : { event, hook: a as AnyHook };
+ regs.push(reg);
+ return {
+ catch(handler: AnyHook) {
+ if (reg.onCatch) throw new Error('a second .catch on one registration');
+ reg.onCatch = handler;
+ },
+ };
+ };
+ register(on, options);
+ const $ = engineOf(world);
+
+ async function dispatch(event: string, e: any, core: (e: any) => any): Promise<any> {
+ const chain = regs.filter((r) => r.event === event && matches(r.matcher, e));
+ const run = async (i: number, ev: any): Promise<any> => {
+ if (i >= chain.length) return core(ev);
+ const reg = chain[i]!;
+ let called = false;
+ let last: Promise<any> | undefined;
+ const next: any = (x: any) => {
+ called = true;
+ last = run(i + 1, x);
+ return last;
+ };
+ try {
+ return await reg.hook($, Object.freeze({ ...ev }), next);
+ } catch (error) {
+ if (!reg.onCatch) return called ? last : run(i + 1, ev);
+ const caught: any = (x: any) => (called ? last : next(x));
+ caught.error = { kind: 'throw', message: String((error as Error)?.message ?? error), budget: 1000 };
+ caught.called = called;
+ return await reg.onCatch($, Object.freeze({ ...ev }), caught);
+ }
+ };
+ return run(0, e);
+ }
+
+ return { $, dispatch, regs, events: () => [...new Set(regs.map((r) => r.event))] };
+}
diff --git a/v3/@claude-flow/cli/__tests__/mods/mods-cli.test.ts b/v3/@claude-flow/cli/__tests__/mods/mods-cli.test.ts
new file mode 100644
index 0000000000..d3a884dda1
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/mods/mods-cli.test.ts
@@ -0,0 +1,175 @@
+/**
+ * ADR-404 — `ruflo mods install|uninstall|status|doctor|sync-policy`, the
+ * policy projection the mod reads, and the doctor probe.
+ */
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+import { installMod, uninstallMod, withModEnabled, withModRemoved, ENABLE_ENV, MOD_PLUGIN_ID } from '../../src/mods/install.js';
+import { projectionOf, syncPolicyProjection, PROJECTION_RELATIVE } from '../../src/mods/policy-projection.js';
+import { probeMods } from '../../src/mods/probe.js';
+import { modsCommand } from '../../src/commands/mods.js';
+import { setPolicyMode, upsertPolicyRule } from '../../src/services/policy-runtime.js';
+import { parseProjection } from '../../../../../plugins/ruflo-mods/hooks/guard/policy';
+
+let root: string;
+let home: string;
+beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), 'ruflo-mods-cli-'));
+ home = mkdtempSync(join(tmpdir(), 'ruflo-mods-cli-home-'));
+});
+afterEach(() => {
+ rmSync(root, { recursive: true, force: true });
+ rmSync(home, { recursive: true, force: true });
+});
+const read = (p: string) => JSON.parse(readFileSync(p, 'utf8'));
+const finding = (name: string, env: NodeJS.ProcessEnv = {}, managedPath = join(home, 'none.json')) =>
+ probeMods({ projectRoot: root, home, env, managedPath }).find((f) => f.name === name)!;
+
+describe('ADR-404 mods install / uninstall', () => {
+ it('enables the plugin, the marketplace and the early-access switch in settings.local.json', () => {
+ const r = installMod(root, 'local');
+ const s = read(join(root, '.claude', 'settings.local.json'));
+ expect(s.enabledPlugins[MOD_PLUGIN_ID]).toBe(true);
+ expect(s.extraKnownMarketplaces.ruflo.source).toEqual({ source: 'github', repo: 'ruvnet/ruflo' });
+ expect(s.env[ENABLE_ENV]).toBe('1');
+ expect(r.added).toEqual({ plugin: true, marketplace: true, env: true });
+ });
+
+ it('keeps everything a person set, backs up, and uninstall removes only what install added', () => {
+ const file = join(root, '.claude', 'settings.json');
+ mkdirSync(join(root, '.claude'), { recursive: true });
+ const before = { hooks: { Stop: [] }, env: { KEEP: 'x' }, extraKnownMarketplaces: { ruflo: { source: { source: 'directory', path: '/mine' } } }, enabledPlugins: { other: true } };
+ writeFileSync(file, JSON.stringify(before));
+ const r = installMod(root, 'project');
+ expect(r.backup && existsSync(r.backup)).toBe(true);
+ expect(read(file).extraKnownMarketplaces.ruflo.source.source).toBe('directory'); // never replaced
+ uninstallMod(root);
+ expect(read(file)).toEqual(before);
+ expect(existsSync(join(root, '.claude-flow', 'mods', 'install.json'))).toBe(false);
+ });
+
+ it('a second install keeps the first record of what ruflo added', () => {
+ installMod(root, 'local');
+ installMod(root, 'local');
+ uninstallMod(root);
+ expect(read(join(root, '.claude', 'settings.local.json'))).toEqual({});
+ });
+
+ it('dry run writes nothing', () => {
+ const r = installMod(root, 'local', true);
+ expect(r.next.enabledPlugins).toEqual({ [MOD_PLUGIN_ID]: true });
+ expect(existsSync(join(root, '.claude'))).toBe(false);
+ });
+
+ it('refuses to overwrite a settings file it cannot parse', () => {
+ mkdirSync(join(root, '.claude'), { recursive: true });
+ writeFileSync(join(root, '.claude', 'settings.local.json'), '{ broken');
+ expect(() => installMod(root, 'local')).toThrow();
+ expect(readFileSync(join(root, '.claude', 'settings.local.json'), 'utf8')).toBe('{ broken');
+ });
+
+ it('never follows an install record outside the project .claude folder', () => {
+ mkdirSync(join(root, '.claude-flow', 'mods'), { recursive: true });
+ for (const target of [join(home, 'settings.json'), join(root, '.claude-flow', 'x.json'), join(root, '.claude', '..', '..', 'evil.json')]) {
+ writeFileSync(join(root, '.claude-flow', 'mods', 'install.json'), JSON.stringify({ version: 1, settingsFile: target, installedAt: 'x', added: { plugin: true, marketplace: true, env: true } }));
+ expect(() => uninstallMod(root)).toThrow(/outside/);
+ }
+ });
+
+ it('pure halves round-trip', () => {
+ const s = { enabledPlugins: { [MOD_PLUGIN_ID]: true } };
+ const { next, added } = withModEnabled(s);
+ expect(added.plugin).toBe(false);
+ expect(withModRemoved(next, added)).toEqual(s);
+ });
+});
+
+describe('ADR-404 policy projection', () => {
+ const ccRule = { id: 'no-push', effect: 'deny' as const, actions: ['claude-code.tool.Bash'], resources: ['git push*'] };
+ const mcpRule = { id: 'mcp', effect: 'deny' as const, actions: ['mcp.tool.call'] };
+ const starRule = { id: 'star', effect: 'deny' as const, actions: ['*'] };
+
+ it('projects only explicit claude-code rules, and nothing in legacy mode', () => {
+ expect(projectionOf({ mode: 'legacy', rules: [ccRule] })).toBeNull();
+ expect(projectionOf({ mode: 'enforce', rules: [mcpRule, starRule] })).toBeNull();
+ expect(projectionOf({ mode: 'enforce', rules: [mcpRule, ccRule, starRule], }, 5)).toEqual({ version: 1, mode: 'enforce', generatedAt: 5, rules: [ccRule] });
+ });
+
+ it('what the CLI writes is what the mod parses', () => {
+ syncPolicyProjection(root, { mode: 'observe', rules: [ccRule] });
+ const text = readFileSync(join(root, PROJECTION_RELATIVE), 'utf8');
+ expect(parseProjection(text)).toEqual({ mode: 'observe', rules: [ccRule] });
+ expect(syncPolicyProjection(root, { mode: 'legacy', rules: [] }).action).toBe('removed');
+ expect(existsSync(join(root, PROJECTION_RELATIVE))).toBe(false);
+ });
+
+ it('every policy state write keeps the projection in step (real policy runtime)', async () => {
+ mkdirSync(join(root, '.claude-flow'), { recursive: true });
+ await upsertPolicyRule({ ...ccRule }, root);
+ expect(existsSync(join(root, PROJECTION_RELATIVE))).toBe(false); // legacy: nothing to project
+ await setPolicyMode('observe', root);
+ expect(read(join(root, PROJECTION_RELATIVE))).toMatchObject({ mode: 'observe', rules: [{ id: 'no-push' }] });
+ await setPolicyMode('legacy', root);
+ expect(existsSync(join(root, PROJECTION_RELATIVE))).toBe(false);
+ });
+});
+
+describe('ADR-404 mods probe and doctor', () => {
+ it('reports not enabled as a pass: classic hooks are the default', () => {
+ expect(finding('ruflo-mods plugin').status).toBe('warn');
+ expect(finding('last mod start').status).toBe('pass');
+ });
+
+ it('reports function hooks off, and the cached rollout switch when Claude Code serves it off', () => {
+ expect(finding('function hooks').status).toBe('warn');
+ writeFileSync(join(home, '.claude.json'), JSON.stringify({ cachedGrowthBookFeatures: { tengu_plugin_hooks_modules: false } }));
+ const f = finding('function hooks', { [ENABLE_ENV]: '1' });
+ expect(f.status).toBe('warn');
+ expect(f.message).toContain('rollout switch cached OFF');
+ writeFileSync(join(home, '.claude.json'), JSON.stringify({ cachedGrowthBookFeatures: { tengu_plugin_hooks_modules: true } }));
+ expect(finding('function hooks', { [ENABLE_ENV]: '1' }).status).toBe('pass');
+ });
+
+ it('reports a refusal by allowManagedModsOnly', () => {
+ const managed = join(home, 'managed.json');
+ writeFileSync(managed, JSON.stringify({ pluginConfigs: { 'cc-plugin-sec-default@builtin': { options: { allowManagedModsOnly: true } } } }));
+ expect(finding('managed policy', {}, managed)).toMatchObject({ status: 'warn' });
+ expect(finding('managed policy', {}, managed).message).toContain('allowManagedModsOnly');
+ });
+
+ it('reports whether the helper honours the handshake', () => {
+ mkdirSync(join(root, '.claude', 'helpers'), { recursive: true });
+ writeFileSync(join(root, '.claude', 'helpers', 'hook-handler.cjs'), '// old');
+ expect(finding('classic handshake').status).toBe('warn');
+ writeFileSync(join(root, '.claude', 'helpers', 'hook-handler.cjs'), '// RUFLO_MODS_OWNS');
+ expect(finding('classic handshake').status).toBe('pass');
+ });
+
+ it('reads the heartbeat the mod writes as the evidence of a load', () => {
+ installMod(root, 'local');
+ expect(finding('last mod start').status).toBe('warn');
+ mkdirSync(join(root, '.claude-flow', 'mods'), { recursive: true });
+ writeFileSync(join(root, '.claude-flow', 'mods', 'session.json'), JSON.stringify({ startedAt: '2026-10-01T00:00:00Z', owned: ['route'] }));
+ expect(finding('last mod start')).toMatchObject({ status: 'pass', message: '2026-10-01T00:00:00Z, owning route' });
+ });
+
+ it('warns when policy is enforced but nothing is projected', () => {
+ mkdirSync(join(root, '.claude-flow', 'policy'), { recursive: true });
+ writeFileSync(join(root, '.claude-flow', 'policy', 'state.json'), JSON.stringify({ mode: 'enforce' }));
+ expect(finding('policy projection')).toMatchObject({ status: 'warn', fix: 'ruflo mods sync-policy' });
+ });
+
+ it('the command runs install, status, doctor and uninstall', async () => {
+ const sub = (name: string) => modsCommand.subcommands!.find((s) => s.name === name)!;
+ const ctx = (flags: Record<string, unknown> = {}) => ({ args: [], flags: { projectRoot: root, ...flags }, cwd: root, interactive: false }) as any;
+ expect((await sub('install').action!(ctx())).success).toBe(true);
+ expect((await sub('install').action!(ctx({ scope: 'global' }))).success).toBe(false);
+ const doctor = await sub('doctor').action!(ctx({ json: true }));
+ expect(doctor.exitCode).toBe(0);
+ expect((await sub('uninstall').action!(ctx())).success).toBe(true);
+ expect(read(join(root, '.claude', 'settings.local.json'))).toEqual({});
+ });
+});
diff --git a/v3/@claude-flow/cli/__tests__/mods/mods-guard.test.ts b/v3/@claude-flow/cli/__tests__/mods/mods-guard.test.ts
new file mode 100644
index 0000000000..9f278373c9
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/mods/mods-guard.test.ts
@@ -0,0 +1,194 @@
+/**
+ * ADR-404 — the mod's `tool.check` only tightens. These tests hold that over
+ * every chain verdict, the fail-closed paths, ruflo policy modes, and parity
+ * with the real policy evaluator and hook-handler.cjs pre-bash list.
+ */
+import { describe, it, expect } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { join, resolve } from 'node:path';
+import { ruleMatches as engineRuleMatches, type PolicyRule, type PolicyRequest } from '@claude-flow/security';
+
+import { register } from '../../../../../plugins/ruflo-mods/hooks/register';
+import { DANGEROUS_COMMANDS } from '../../../../../plugins/ruflo-mods/hooks/guard/dangerous-command';
+import { parseProjection, ruleMatches, toolRequest, type ProjectedRule } from '../../../../../plugins/ruflo-mods/hooks/guard/policy';
+import { stricter } from '../../../../../plugins/ruflo-mods/hooks/guard/verdict';
+import { loadMod, memoryWorld, type World } from './harness';
+
+const HELPERS = join(resolve(__dirname, '../..'), '.claude', 'helpers');
+const PROJECTION = '/work/.claude-flow/policy/claude-code.json';
+const RANK = { allow: 0, ask: 1, deny: 2 } as const;
+type D = keyof typeof RANK;
+
+async function started(world: World) {
+ const mod = loadMod(register, world);
+ await mod.dispatch('session.start', { cwd: world.root, surface: null, isInteractive: false }, (e) => ({ cwd: e.cwd }));
+ return mod;
+}
+
+function withProjection(world: World, mode: string, rules: unknown[]) {
+ (world.files as Map<string, { text: string; mtimeMs: number }>).set(PROJECTION, {
+ text: JSON.stringify({ version: 1, mode, generatedAt: 1, rules }),
+ mtimeMs: Date.now() + Math.random(),
+ });
+}
+
+const check = (mod: Awaited<ReturnType<typeof started>>, tool: string, input: unknown, chain: { decision: D; reason?: string; rule?: string }) =>
+ mod.dispatch('tool.check', { tool, input, tool_use_id: 't1' }, () => chain);
+
+const DENY_BASH_RULE = { id: 'no-push', effect: 'deny', actions: ['claude-code.tool.Bash'], resources: ['git push*'] };
+const ASK_EDIT_RULE = { id: 'review-edits', effect: 'require_approval', actions: ['claude-code.tool.Edit'] };
+
+describe('ADR-404 tool.check never loosens', () => {
+ const calls: Array<[string, unknown]> = [
+ ['Bash', { command: 'ls' }],
+ ['Bash', { command: 'rm -rf /' }],
+ ['Bash', { command: 'git push origin main' }],
+ ['Edit', { file_path: '/work/a.ts' }],
+ ['Read', { file_path: '/work/a.ts' }],
+ ['Bash', null],
+ ['Bash', { command: 42 }],
+ ];
+ const chains = [
+ { decision: 'allow' as D },
+ { decision: 'ask' as D, reason: 'mode asks' },
+ { decision: 'deny' as D, reason: 'Bash(rm:*)', rule: 'Bash(rm:*)' },
+ ];
+
+ for (const mode of ['legacy', 'observe', 'enforce', 'absent', 'garbage']) {
+ it(`in policy mode ${mode}, for every call and chain verdict`, async () => {
+ const world = memoryWorld();
+ if (mode === 'garbage') (world.files as Map<string, any>).set(PROJECTION, { text: '{not json', mtimeMs: 1 });
+ else if (mode !== 'absent') withProjection(world, mode, [DENY_BASH_RULE, ASK_EDIT_RULE]);
+ const mod = await started(world);
+ for (const [tool, input] of calls) {
+ for (const chain of chains) {
+ const out = await check(mod, tool, input, chain);
+ expect(RANK[out.decision as D]).toBeGreaterThanOrEqual(RANK[chain.decision]);
+ // Never rewritten: where ruflo does not tighten, the chain's own object (rule and all) stands.
+ if (RANK[out.decision as D] === RANK[chain.decision]) expect(out).toBe(chain);
+ }
+ }
+ });
+ }
+
+ it('stricter() keeps the chain object on ties and lets nothing loosen', () => {
+ const chain = { decision: 'deny' as const, rule: 'Read(.env)' };
+ expect(stricter(chain, { decision: 'allow' })).toBe(chain);
+ expect(stricter(chain, { decision: 'ask' })).toBe(chain);
+ expect(stricter(chain, { decision: 'deny', reason: 'ours' })).toBe(chain);
+ expect(stricter({ decision: 'allow' }, undefined)).toEqual({ decision: 'allow' });
+ });
+});
+
+describe('ADR-404 ruflo verdicts', () => {
+ it('blocks the pre-bash list whatever the policy', async () => {
+ const mod = await started(memoryWorld());
+ const out = await check(mod, 'Bash', { command: 'sudo RM -RF / --no-preserve-root' }, { decision: 'allow' });
+ expect(out).toMatchObject({ decision: 'deny' });
+ expect(out.reason).toContain('rm -rf /');
+ });
+
+ it('enforce: a deny rule denies, an approval rule asks, an allow rule says nothing', async () => {
+ const world = memoryWorld();
+ withProjection(world, 'enforce', [DENY_BASH_RULE, ASK_EDIT_RULE, { id: 'all-read', effect: 'allow', actions: ['claude-code.tool.Read'] }]);
+ const mod = await started(world);
+ expect(await check(mod, 'Bash', { command: 'git push origin main' }, { decision: 'allow' })).toMatchObject({ decision: 'deny', reason: 'ruflo policy: denied-by:no-push' });
+ expect(await check(mod, 'Edit', { file_path: 'x' }, { decision: 'allow' })).toMatchObject({ decision: 'ask' });
+ const askChain = { decision: 'ask' as D };
+ expect(await check(mod, 'Read', { file_path: 'x' }, askChain)).toBe(askChain);
+ });
+
+ it('enforce never applies the engine default-deny to a tool no rule names', async () => {
+ const world = memoryWorld();
+ withProjection(world, 'enforce', [DENY_BASH_RULE]);
+ const mod = await started(world);
+ const chain = { decision: 'allow' as D };
+ expect(await check(mod, 'WebFetch', { url: 'https://x' }, chain)).toBe(chain);
+ });
+
+ it('observe logs what enforce would do and changes nothing', async () => {
+ const world = memoryWorld();
+ withProjection(world, 'observe', [DENY_BASH_RULE]);
+ const mod = await started(world);
+ const chain = { decision: 'allow' as D };
+ expect(await check(mod, 'Bash', { command: 'git push' }, chain)).toBe(chain);
+ expect(world.logs.join('\n')).toContain('denied-by:no-push');
+ });
+
+ it('a rule with no claude-code action (or only *) never reaches Claude Code tools', () => {
+ const p = parseProjection(JSON.stringify({ version: 1, mode: 'enforce', rules: [
+ { id: 'mcp', effect: 'deny', actions: ['mcp.tool.call'] },
+ { id: 'star', effect: 'deny', actions: ['*'] },
+ { id: 'cc', effect: 'deny', actions: ['claude-code.tool.*'] },
+ ] }));
+ expect(p.rules.map((r) => r.id)).toEqual(['cc']);
+ });
+
+ it('fails closed by one step on a projection that exists but cannot be read', async () => {
+ for (const text of ['{not json', JSON.stringify({ version: 2, mode: 'enforce', rules: [] }), JSON.stringify({ version: 1, mode: 'enforce', rules: [{ id: 1 }] })]) {
+ const world = memoryWorld();
+ (world.files as Map<string, any>).set(PROJECTION, { text, mtimeMs: 1 });
+ const mod = await started(world);
+ expect(await check(mod, 'Read', { file_path: 'x' }, { decision: 'allow' })).toMatchObject({ decision: 'ask' });
+ const deny = { decision: 'deny' as D, rule: 'r' };
+ expect(await check(mod, 'Read', { file_path: 'x' }, deny)).toBe(deny);
+ }
+ });
+
+ it('a hook failure is caught: allow becomes ask, nothing loosens', async () => {
+ const world = memoryWorld();
+ withProjection(world, 'observe', [DENY_BASH_RULE]);
+ world.failLog = true; // observe logs, the log throws, the hook fails
+ const mod = await started(world);
+ expect(await check(mod, 'Bash', { command: 'git push' }, { decision: 'allow' })).toMatchObject({ decision: 'ask' });
+ const deny = { decision: 'deny' as D, rule: 'x' };
+ expect(await check(mod, 'Bash', { command: 'git push' }, deny)).toBe(deny);
+ });
+
+ it('an absent projection is no policy, not a failure', async () => {
+ const mod = await started(memoryWorld());
+ const chain = { decision: 'allow' as D };
+ expect(await check(mod, 'Edit', { file_path: 'x' }, chain)).toBe(chain);
+ });
+});
+
+describe('ADR-404 parity', () => {
+ it('carries hook-handler.cjs pre-bash list exactly', () => {
+ const source = readFileSync(join(HELPERS, 'hook-handler.cjs'), 'utf8');
+ const literal = source.match(/const dangerous = (\[[^\]]*\]);/)?.[1];
+ expect(literal).toBeDefined();
+ expect(new Function(`return ${literal}`)()).toEqual(DANGEROUS_COMMANDS);
+ });
+
+ it('ruleMatches agrees with @claude-flow/security on every rule × request', () => {
+ const rules: ProjectedRule[] = [];
+ const actionsSet = [['claude-code.tool.Bash'], ['claude-code.tool.*'], ['claude-code.*', 'mcp.tool.call'], ['claude-code.tool.Edit']];
+ const optional = {
+ resources: [undefined, ['git push*'], ['/work/*'], ['*']],
+ principals: [undefined, ['claude-code'], ['someone-else']],
+ identityTypes: [undefined, ['agent'], ['user']],
+ roles: [undefined, ['admin']],
+ environments: [undefined, ['prod']],
+ constraints: [undefined, { destructive: false }, { network: false }, { maxCostUsd: 1 }, { requireSignedEvidence: true }, { requiredProvenance: ['tool_result'] }, { allowedNamespaces: ['x'] }, { destructive: true }],
+ enabled: [undefined, false],
+ };
+ let i = 0;
+ for (const actions of actionsSet) for (const resources of optional.resources) for (const principals of optional.principals)
+ for (const identityTypes of optional.identityTypes) for (const constraints of optional.constraints) for (const enabled of optional.enabled) {
+ rules.push({ id: `r${i++}`, effect: 'deny', actions, resources, principals, identityTypes: identityTypes as any, constraints, enabled,
+ ...(i % 3 === 0 ? { roles: ['admin'] } : {}), ...(i % 5 === 0 ? { environments: ['prod'] } : {}) });
+ }
+ const calls: Array<[string, unknown]> = [['Bash', { command: 'git push origin' }], ['Bash', { command: 'ls' }], ['Edit', { file_path: '/work/a.ts' }],
+ ['WebFetch', { url: 'https://e' }], ['Read', {}], ['mcp__x__y', {}]];
+ let compared = 0;
+ for (const [tool, input] of calls) {
+ const req = toolRequest(tool, input);
+ const engineReq: PolicyRequest = { identity: { ...req.identity, roles: undefined } as PolicyRequest['identity'], action: { ...req.action }, context: {} };
+ for (const rule of rules) {
+ expect(ruleMatches(rule, req), `${rule.id} ${tool}`).toBe(engineRuleMatches(rule as unknown as PolicyRule, engineReq));
+ compared++;
+ }
+ }
+ expect(compared).toBeGreaterThan(10_000);
+ });
+});
diff --git a/v3/@claude-flow/cli/__tests__/mods/mods-learn-cost.test.ts b/v3/@claude-flow/cli/__tests__/mods/mods-learn-cost.test.ts
new file mode 100644
index 0000000000..1fab52012b
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/mods/mods-learn-cost.test.ts
@@ -0,0 +1,136 @@
+/**
+ * ADR-404 — edit learning signals in the classic consolidator's format, and
+ * the cost-tracker budget ladder on live session cost.
+ */
+import { describe, it, expect } from 'vitest';
+import { execFileSync } from 'node:child_process';
+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+
+import { register } from '../../../../../plugins/ruflo-mods/hooks/register';
+import { appendRecords, MAX_LINES } from '../../../../../plugins/ruflo-mods/hooks/learn/insights';
+import { alertLevel, budgetOf, LEVELS } from '../../../../../plugins/ruflo-mods/hooks/cost/budget';
+import { loadMod, memoryWorld, type World } from './harness';
+
+const REPO = resolve(__dirname, '../../../../..');
+const PENDING = '/work/.claude-flow/data/pending-insights.jsonl';
+
+async function start(world: World, options: Record<string, unknown> = {}) {
+ const mod = loadMod(register, world, options);
+ await mod.dispatch('session.start', { cwd: world.root, surface: null, isInteractive: false }, (e) => ({ cwd: e.cwd }));
+ return mod;
+}
+const mem = (w: World) => w.files as Map<string, { text: string; mtimeMs: number }>;
+const edit = (mod: Awaited<ReturnType<typeof start>>, file: string, result: object, tool = 'Edit') =>
+ mod.dispatch('tool.call', { tool, tool_use_id: `t-${file}`, file_path: file }, () => result);
+const endTurn = (mod: Awaited<ReturnType<typeof start>>) => mod.dispatch('turn.complete', { reason: 'answer' }, () => ({ text: 'ok' }));
+
+describe('ADR-404 edit records', () => {
+ it('writes recordEdit lines once per turn, failures included, denials never', async () => {
+ const world = memoryWorld();
+ mem(world).set('/work/.claude-flow/sessions/current.json', { text: JSON.stringify({ context: { sessionId: 'ruflo-s1' } }), mtimeMs: 1 });
+ const mod = await start(world);
+ await edit(mod, '/work/a.ts', { result: 'ok', text: 'ok' });
+ await edit(mod, '/work/b.ts', { isError: true, result: 'boom', text: 'boom' }, 'Write');
+ await edit(mod, '/work/c.ts', { deny: 'no' }, 'MultiEdit');
+ await mod.dispatch('tool.call', { tool: 'Read', tool_use_id: 'r', file_path: '/work/d.ts' }, () => ({ result: 'x' }));
+ expect(mem(world).has(PENDING)).toBe(false); // nothing written mid-turn
+ await endTurn(mod);
+ const lines = mem(world).get(PENDING)!.text.trim().split('\n').map((l) => JSON.parse(l));
+ expect(lines.map((l) => [l.file, l.success, l.sessionId])).toEqual([['/work/a.ts', true, 'ruflo-s1'], ['/work/b.ts', false, 'ruflo-s1']]);
+ });
+
+ it('has the key order and types intelligence.cjs recordEdit writes', () => {
+ const project = mkdtempSync(join(tmpdir(), 'ruflo-mods-learn-'));
+ try {
+ execFileSync(process.execPath, ['-e', `require(${JSON.stringify(join(REPO, 'v3/@claude-flow/cli/.claude/helpers/intelligence.cjs'))}).recordEdit('x.ts', false)`], {
+ env: { PATH: process.env.PATH, CLAUDE_PROJECT_DIR: project }, cwd: project,
+ });
+ const classic = JSON.parse(readFileSync(join(project, '.claude-flow/data/pending-insights.jsonl'), 'utf8').trim());
+ const ours = JSON.parse(appendRecords('', [{ type: 'edit', file: 'x.ts', success: false, timestamp: 1, sessionId: null }]).trim());
+ expect(Object.keys(ours)).toEqual(Object.keys(classic));
+ expect(Object.fromEntries(Object.entries(ours).map(([k, v]) => [k, typeof v]))).toEqual(Object.fromEntries(Object.entries(classic).map(([k, v]) => [k, typeof v])));
+ } finally {
+ rmSync(project, { recursive: true, force: true });
+ }
+ });
+
+ it('keeps existing lines and the classic 2000-line cap', () => {
+ const existing = Array.from({ length: MAX_LINES }, (_, i) => JSON.stringify({ i })).join('\n') + '\n';
+ const next = appendRecords(existing, [{ type: 'edit', file: 'z', success: true, timestamp: 1, sessionId: null }]).trim().split('\n');
+ expect(next).toHaveLength(MAX_LINES);
+ expect(JSON.parse(next[0]!)).toEqual({ i: 1 });
+ expect(JSON.parse(next.at(-1)!).file).toBe('z');
+ });
+
+ it('never overwrites a pending file it cannot read; the records wait for the next turn', async () => {
+ const world = memoryWorld();
+ mem(world).set(PENDING, { text: '{"keep":1}\n', mtimeMs: 1 });
+ let fail = true;
+ world.failRead = (p) => (p === PENDING && fail ? new Error('EIO: i/o error') : undefined);
+ const mod = await start(world);
+ await edit(mod, '/work/a.ts', { result: 'ok' });
+ await endTurn(mod);
+ expect(mem(world).get(PENDING)!.text).toBe('{"keep":1}\n');
+ fail = false;
+ await mod.dispatch('session.end', { reason: 'other', sessionId: 's', resume: { id: 's' } }, () => ({ sessionId: 's' }));
+ expect(mem(world).get(PENDING)!.text.trim().split('\n')).toHaveLength(2);
+ });
+
+ it('records nothing when it does not own post-edit', async () => {
+ const world = memoryWorld('/work', { hooks: { PostToolUse: [{ hooks: [{ command: 'node .claude/helpers/hook-handler.cjs post-edit' }] }] } });
+ mem(world).set('/work/.claude/helpers/hook-handler.cjs', { text: '// a helper from before the handshake', mtimeMs: 1 });
+ const mod = await start(world);
+ await edit(mod, '/work/a.ts', { result: 'ok' });
+ await endTurn(mod);
+ expect(mem(world).has(PENDING)).toBe(false);
+ });
+
+ it('a bad file_path records as unknown, as recordEdit does', async () => {
+ const world = memoryWorld();
+ const mod = await start(world);
+ await mod.dispatch('tool.call', { tool: 'Edit', tool_use_id: 'x', file_path: { evil: true } }, () => ({ result: 'ok' }));
+ await endTurn(mod);
+ expect(JSON.parse(mem(world).get(PENDING)!.text.trim()).file).toBe('unknown');
+ });
+});
+
+describe('ADR-404 budget ladder', () => {
+ it('uses budget.mjs thresholds exactly', () => {
+ const source = readFileSync(join(REPO, 'plugins/ruflo-cost-tracker/scripts/budget.mjs'), 'utf8');
+ const theirs = [...source.matchAll(/utilization >= (\d\.\d+)\) return \{ level: '([A-Z_]+)'/g)].map((m) => ({ level: m[2], at: Number(m[1]) }));
+ expect(theirs).toEqual(LEVELS.map((l) => ({ level: l.level, at: l.at })));
+ expect([0, 0.49, 0.5, 0.75, 0.9, 1, 3].map(alertLevel)).toEqual(['OK', 'OK', 'INFO', 'WARNING', 'CRITICAL', 'HARD_STOP', 'HARD_STOP']);
+ });
+
+ it('reads a bad budget as off, never as a zero budget', () => {
+ for (const bad of [0, -1, 'abc', NaN, Infinity, undefined, true]) expect(budgetOf(bad)).toBeUndefined();
+ expect(budgetOf('2.5')).toBe(2.5);
+ });
+
+ it('says each rung once, on the way up, from session.measure', async () => {
+ const world = memoryWorld();
+ const mod = await start(world, { costBudgetUsd: 10 });
+ for (const usd of [1, 5.5, 6, 7.6, 9.2, 9.3, 12]) {
+ await mod.dispatch('session.measure', { context: {}, rateLimits: [], cost: { usd }, changed: ['cost'] }, (e) => ({ changed: e.changed }));
+ }
+ expect(world.toasts.map((t) => t.split(':')[0])).toEqual(['ruflo budget INFO', 'ruflo budget WARNING', 'ruflo budget CRITICAL', 'ruflo budget HARD_STOP']);
+ });
+
+ it('with costHardStop, refuses new agents at HARD_STOP and only then', async () => {
+ const world = memoryWorld();
+ const mod = await start(world, { costBudgetUsd: 1, costHardStop: true });
+ const spawn = () => mod.dispatch('agent.spawn', { prompt: 'p', description: 'd', subagentType: 'coder' }, () => ({ model: 'sonnet' }));
+ expect(await spawn()).toEqual({ model: 'sonnet' });
+ await mod.dispatch('session.measure', { context: {}, rateLimits: [], cost: { usd: 1.01 }, changed: ['cost'] }, (e) => ({ changed: e.changed }));
+ expect((await spawn()).deny).toContain('halted');
+ });
+
+ it('hooks nothing when no budget is set', () => {
+ const mod = loadMod(register, memoryWorld(), {});
+ expect(mod.events()).not.toContain('session.measure');
+ expect(mod.events()).not.toContain('agent.spawn');
+ expect(loadMod(register, memoryWorld(), { costBudgetUsd: 5 }).events()).not.toContain('agent.spawn');
+ });
+});
diff --git a/v3/@claude-flow/cli/__tests__/mods/mods-ownership.test.ts b/v3/@claude-flow/cli/__tests__/mods/mods-ownership.test.ts
new file mode 100644
index 0000000000..1feb1edb08
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/mods/mods-ownership.test.ts
@@ -0,0 +1,207 @@
+/**
+ * ADR-404 — one owner per event. The mod takes route/post-edit over only
+ * where the classic hook-handler hands them over (RUFLO_MODS_OWNS); anything
+ * else leaves the classic hooks in charge. These tests run the real
+ * hook-handler.cjs and ruflo-core ruflo-hook.cjs with the environment the
+ * mod sets, and count what fires.
+ */
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { execFileSync, spawnSync } from 'node:child_process';
+import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+
+import { register } from '../../../../../plugins/ruflo-mods/hooks/register';
+import { classicConfigured, ownedEvents } from '../../../../../plugins/ruflo-mods/hooks/ownership';
+import { loadMod, memoryWorld, realWorld, type World } from './harness';
+
+const REPO = resolve(__dirname, '../../../../..');
+const PKG_HELPERS = join(REPO, 'v3', '@claude-flow', 'cli', '.claude', 'helpers');
+const CORE_HOOK = join(REPO, 'plugins', 'ruflo-core', 'scripts', 'ruflo-hook.cjs');
+
+const CLASSIC = {
+ hooks: {
+ UserPromptSubmit: [{ hooks: [{ type: 'command', command: `sh -c 'D="\${CLAUDE_PROJECT_DIR:-.}"; [ -f "$D/.claude/helpers/hook-handler.cjs" ] || D="\${HOME}"; exec node "$D/.claude/helpers/hook-handler.cjs" route'` }] }],
+ PostToolUse: [{ matcher: 'Write|Edit|MultiEdit', hooks: [{ type: 'command', command: 'node "$CLAUDE_PROJECT_DIR/.claude/helpers/hook-handler.cjs" post-edit' }] }],
+ PreToolUse: [{ matcher: 'Bash', hooks: [{ type: 'command', command: 'node "$CLAUDE_PROJECT_DIR/.claude/helpers/hook-handler.cjs" pre-bash' }] }],
+ },
+};
+
+async function start(world: World, options: Record<string, unknown> = {}) {
+ const mod = loadMod(register, world, options);
+ const next = await mod.dispatch('session.start', { cwd: world.root, surface: 'terminal', isInteractive: true }, (e) => ({ cwd: e.cwd }));
+ return { mod, next };
+}
+
+describe('ADR-404 ownership rule', () => {
+ it('recognises the generated classic commands (sh probe, quoted, Windows cmd)', () => {
+ expect(classicConfigured(CLASSIC, 'route')).toBe(true);
+ expect(classicConfigured(CLASSIC, 'post-edit')).toBe(true);
+ const win = { hooks: { UserPromptSubmit: [{ hooks: [{ command: 'cmd /c "IF EXIST \\"%CLAUDE_PROJECT_DIR%\\.claude\\helpers\\hook-handler.cjs\\" (node \\"%CLAUDE_PROJECT_DIR%\\.claude\\helpers\\hook-handler.cjs\\" route)"' }] }] } };
+ expect(classicConfigured(win, 'route')).toBe(true);
+ expect(classicConfigured({ hooks: { UserPromptSubmit: [{ hooks: [{ command: 'node hook-handler.cjs router-stats' }] }] } }, 'route')).toBe(false);
+ expect(classicConfigured(null, 'route')).toBe(false);
+ });
+
+ it('owns an event only where no classic hook runs it or the helper hands it over', () => {
+ expect(ownedEvents({}, false)).toEqual(['route', 'post-edit']);
+ expect(ownedEvents(CLASSIC, false)).toEqual([]);
+ expect(ownedEvents(CLASSIC, true)).toEqual(['route', 'post-edit']);
+ });
+
+ it('never owns pre-bash or session events', () => {
+ expect(ownedEvents({}, true)).not.toContain('pre-bash');
+ });
+});
+
+describe('ADR-404 session start', () => {
+ it('with a handshake-aware helper: owns both, sets RUFLO_MODS_OWNS, registers /ruflo-mods, writes a heartbeat', async () => {
+ const world = memoryWorld('/work', CLASSIC);
+ (world.files as Map<string, any>).set('/work/.claude/helpers/hook-handler.cjs', { text: '... RUFLO_MODS_OWNS ...', mtimeMs: 1 });
+ const { mod } = await start(world);
+ expect(world.env.get('RUFLO_MODS_OWNS')).toBe('route,post-edit');
+ expect(world.commands).toEqual(['ruflo-mods']);
+ const beat = JSON.parse((world.files as Map<string, any>).get('/work/.claude-flow/mods/session.json').text);
+ expect(beat.owned).toEqual(['route', 'post-edit']);
+ const r = await mod.dispatch('command.run', { command: 'ruflo-mods', args: '' }, () => ({ text: 'core' }));
+ expect(r.text).toContain('owns: route, post-edit');
+ });
+
+ it('with an older helper: stands down, sets nothing', async () => {
+ const world = memoryWorld('/work', CLASSIC);
+ (world.files as Map<string, any>).set('/work/.claude/helpers/hook-handler.cjs', { text: 'old helper', mtimeMs: 1 });
+ await start(world);
+ expect(world.env.has('RUFLO_MODS_OWNS')).toBe(false);
+ });
+
+ it('stands down when either copy a hook could run is too old (new project helper, old $HOME helper)', async () => {
+ const world = memoryWorld('/work', CLASSIC);
+ world.env.set('HOME', '/home/u');
+ (world.files as Map<string, any>).set('/work/.claude/helpers/hook-handler.cjs', { text: 'RUFLO_MODS_OWNS', mtimeMs: 1 });
+ (world.files as Map<string, any>).set('/home/u/.claude/helpers/hook-handler.cjs', { text: 'old', mtimeMs: 1 });
+ await start(world);
+ expect(world.env.has('RUFLO_MODS_OWNS')).toBe(false);
+ });
+
+ it('checks the $HOME helper settings-generator hookCmd falls back to', async () => {
+ const world = memoryWorld('/work', CLASSIC);
+ world.env.set('HOME', '/home/u');
+ (world.files as Map<string, any>).set('/home/u/.claude/helpers/hook-handler.cjs', { text: 'RUFLO_MODS_OWNS', mtimeMs: 1 });
+ await start(world);
+ expect(world.env.get('RUFLO_MODS_OWNS')).toBe('route,post-edit');
+ });
+
+ it('when settings cannot be read: owns nothing and the session still starts', async () => {
+ const world = memoryWorld('/work', () => { throw new Error('refused by a hook beneath'); });
+ world.env.set('RUFLO_MODS_OWNS', 'route');
+ const { mod, next } = await start(world);
+ expect(next).toEqual({ cwd: '/work' });
+ expect(world.env.has('RUFLO_MODS_OWNS')).toBe(false);
+ let seen: any;
+ await mod.dispatch('prompt.submit', { text: 'build', wait: false, origin: { kind: 'composer' } }, (e) => (seen = e));
+ expect(seen.context).toBeUndefined();
+ });
+
+ it('draws no status line where the ruflo statusLine helper is configured', async () => {
+ const world = memoryWorld('/work', { statusLine: { type: 'command', command: 'node .claude/helpers/statusline.cjs' } });
+ const { mod } = await start(world);
+ await mod.dispatch('prompt.submit', { text: 'build', wait: false, origin: { kind: 'composer' } }, (e) => e);
+ expect(world.statuses).toEqual([]);
+ const plain = memoryWorld('/work', {});
+ const started = await start(plain);
+ await started.mod.dispatch('prompt.submit', { text: 'build', wait: false, origin: { kind: 'composer' } }, (e) => e);
+ expect(plain.statuses).toEqual(['ruflo · coder 60%']);
+ });
+});
+
+describe('ADR-404 no double fire with the real classic hooks', () => {
+ let project: string;
+ let home: string;
+ let dedup: string;
+
+ beforeEach(() => {
+ project = mkdtempSync(join(tmpdir(), 'ruflo-mods-own-'));
+ home = mkdtempSync(join(tmpdir(), 'ruflo-mods-own-home-'));
+ dedup = mkdtempSync(join(tmpdir(), 'ruflo-mods-dedup-'));
+ mkdirSync(join(project, '.claude', 'helpers'), { recursive: true });
+ for (const f of ['hook-handler.cjs', 'router.cjs', 'session.cjs', 'memory.cjs', 'intelligence.cjs']) {
+ copyFileSync(join(PKG_HELPERS, f), join(project, '.claude', 'helpers', f));
+ }
+ });
+ afterEach(() => {
+ for (const d of [project, home, dedup]) rmSync(d, { recursive: true, force: true });
+ });
+
+ const classic = (sub: string, input: object, env: Record<string, string>) =>
+ spawnSync(process.execPath, [join(project, '.claude', 'helpers', 'hook-handler.cjs'), sub], {
+ input: JSON.stringify(input),
+ cwd: project,
+ env: { PATH: process.env.PATH, HOME: home, CLAUDE_PROJECT_DIR: project, CI: '1', RUFLO_HOOK_DEDUP_DIR: dedup, ...env },
+ encoding: 'utf8',
+ });
+
+ async function promptRound(prompt: string): Promise<number> {
+ const world = realWorld(project, CLASSIC);
+ const { mod } = await start(world);
+ let blocks = 0;
+ await mod.dispatch('prompt.submit', { text: prompt, wait: false, origin: { kind: 'composer' } }, (e) => {
+ blocks += e.context?.length ?? 0;
+ // The engine runs the UserPromptSubmit settings hooks beneath, in the env the mod set.
+ const out = classic('route', { prompt }, Object.fromEntries(world.env)).stdout.trim();
+ if (out) blocks++;
+ return e;
+ });
+ return blocks;
+ }
+
+ it('exactly one routing block per prompt with a handshake-aware helper (the mod)', async () => {
+ expect(await promptRound('implement the api')).toBe(1);
+ });
+
+ it('exactly one routing block per prompt with an older helper (classic keeps it)', async () => {
+ const helper = join(project, '.claude', 'helpers', 'hook-handler.cjs');
+ writeFileSync(helper, readFileSync(helper, 'utf8').replaceAll('RUFLO_MODS_OWNS', 'RUFLO_X_OWNS'));
+ expect(await promptRound('implement the api')).toBe(1);
+ });
+
+ it('exactly one edit record: classic post-edit and ruflo-core post-edit stand down for the mod', async () => {
+ const world = realWorld(project, CLASSIC);
+ const { mod } = await start(world);
+ const env = Object.fromEntries(world.env);
+ expect(env.RUFLO_MODS_OWNS).toBe('route,post-edit');
+ const event = { tool_name: 'Edit', tool_input: { file_path: join(project, 'a.ts') }, tool_use_id: 'tu-1', session_id: 's1' };
+
+ await mod.dispatch('tool.call', { tool: 'Edit', tool_use_id: 'tu-1', file_path: join(project, 'a.ts') }, () => {
+ classic('post-edit', event, env);
+ spawnSync(process.execPath, [CORE_HOOK, 'post-edit'], {
+ input: JSON.stringify(event), cwd: project, env: { PATH: '/nonexistent', HOME: home, RUFLO_HOOK_DEDUP_DIR: dedup, ...env }, encoding: 'utf8',
+ });
+ return { result: 'edited', text: 'edited' };
+ });
+ await mod.dispatch('turn.complete', { reason: 'answer' }, () => ({ text: 'done' }));
+
+ const pending = readFileSync(join(project, '.claude-flow', 'data', 'pending-insights.jsonl'), 'utf8').trim().split('\n');
+ expect(pending).toHaveLength(1);
+ expect(JSON.parse(pending[0]!)).toMatchObject({ type: 'edit', file: join(project, 'a.ts'), success: true });
+ // Neither classic path claimed the event, so neither ran its side effect.
+ expect(readdirSync(dedup)).toEqual([]);
+ });
+
+ it('without the mod the classic path records as before', () => {
+ const event = { tool_name: 'Edit', tool_input: { file_path: 'b.ts' }, tool_use_id: 'tu-2' };
+ classic('post-edit', event, {});
+ expect(existsSync(join(project, '.claude-flow', 'data', 'pending-insights.jsonl'))).toBe(true);
+ expect(readdirSync(dedup)).toHaveLength(1);
+ });
+
+ it('pre-bash is a guard: it blocks even when the handshake names it', () => {
+ const r = classic('pre-bash', { tool_input: { command: 'rm -rf /' } }, { RUFLO_MODS_OWNS: 'route,post-edit,pre-bash' });
+ expect(r.status).toBe(1);
+ expect(r.stderr).toContain('[BLOCKED]');
+ });
+
+ it('hook-handler exports the ownership check it applies', () => {
+ const require = (id: string) => execFileSync(process.execPath, ['-e', `const h=require(${JSON.stringify(id)});process.stdout.write(JSON.stringify([h.ownedByMod('route',{RUFLO_MODS_OWNS:' route '}),h.ownedByMod('session-end',{RUFLO_MODS_OWNS:'session-end'}),h.ownedByMod('post-edit',{})]))`], { encoding: 'utf8' });
+ expect(JSON.parse(require(join(PKG_HELPERS, 'hook-handler.cjs')))).toEqual([true, false, false]);
+ });
+});
diff --git a/v3/@claude-flow/cli/__tests__/mods/mods-route.test.ts b/v3/@claude-flow/cli/__tests__/mods/mods-route.test.ts
new file mode 100644
index 0000000000..0c643c2a2c
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/mods/mods-route.test.ts
@@ -0,0 +1,123 @@
+/**
+ * ADR-404 — the mod's router is a copy of router.cjs (a hooks module cannot
+ * import outside its plugin), so these tests are what keep it from being a
+ * fork: same table, same matching, same context text as hook-handler.cjs
+ * `route`, and the #3567 no-match semantics.
+ */
+import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest';
+import { execFileSync } from 'node:child_process';
+import { createRequire } from 'node:module';
+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+
+vi.mock('../../src/memory/memory-bridge.js', () => ({ bridgeRouteTask: vi.fn(async () => null) }));
+
+import { NO_MATCH_CONFIDENCE as CLI_NO_MATCH } from '../../src/mcp-tools/hooks-tools.js';
+import { register } from '../../../../../plugins/ruflo-mods/hooks/register';
+import { MATCH_CONFIDENCE, NO_MATCH_CONFIDENCE, routeTask, TASK_PATTERNS } from '../../../../../plugins/ruflo-mods/hooks/route/route-task';
+import { loadMod, memoryWorld, realWorld } from './harness';
+
+const CLI_ROOT = resolve(__dirname, '../..');
+const HELPERS = join(CLI_ROOT, '.claude', 'helpers');
+const require = createRequire(import.meta.url);
+const router = require(join(HELPERS, 'router.cjs')) as {
+ routeTask: (t: string) => { agent: string; confidence: number; reason: string };
+ TASK_PATTERNS: Array<{ tokens: string[]; agent: string }>;
+};
+
+const MATCHED = [
+ 'implement the login flow', 'write tests for the parser', 'please review this PR', 'research vector databases',
+ 'design the architecture', 'add an api endpoint', 'fix the react component css', 'deploy with docker',
+ 'set up the ci/cd pipeline', 'Refactor and DEBUG it', 'unit test coverage', 'audit security of auth',
+];
+const NO_MATCH = ['', ' ', '...', '修复登录崩溃', 'decision about infrastructure-free stuff?'.replace('infrastructure', 'x'), 'hello there'];
+
+describe('ADR-404 mod router parity with router.cjs', () => {
+ it('carries router.cjs TASK_PATTERNS exactly', () => {
+ expect(TASK_PATTERNS).toEqual(router.TASK_PATTERNS);
+ });
+
+ it.each(MATCHED)('routes %j as router.cjs does', (task) => {
+ const theirs = router.routeTask(task);
+ const ours = routeTask(task);
+ expect(ours.matched).toBe(true);
+ expect({ agent: ours.agent, confidence: ours.confidence, reason: ours.reason }).toEqual(theirs);
+ expect(ours.confidence).toBe(MATCH_CONFIDENCE);
+ });
+
+ it.each(NO_MATCH)('%j is an explicit no-match at the #3567 prior', (task) => {
+ const ours = routeTask(task);
+ expect(ours).toMatchObject({ agent: 'coder', matched: false, reason: 'no-match-default' });
+ expect(ours.confidence).toBe(router.routeTask(task).confidence);
+ expect(NO_MATCH_CONFIDENCE).toBe(CLI_NO_MATCH);
+ for (const m of MATCHED) expect(ours.confidence).toBeLessThan(routeTask(m).confidence);
+ });
+
+ it('treats a non-string task as no-match, never throwing', () => {
+ for (const bad of [undefined, null, 42, { text: 'build' }]) expect(routeTask(bad).matched).toBe(false);
+ });
+});
+
+describe('ADR-404 mod route context equals hook-handler.cjs route output', () => {
+ let project: string;
+ let home: string;
+
+ beforeAll(() => {
+ project = mkdtempSync(join(tmpdir(), 'ruflo-mods-route-'));
+ home = mkdtempSync(join(tmpdir(), 'ruflo-mods-home-'));
+ mkdirSync(join(project, '.claude-flow', 'data'), { recursive: true });
+ const words = (s: string) => s.toLowerCase().split(/\s+/);
+ writeFileSync(join(project, '.claude-flow', 'data', 'ranked-context.json'), JSON.stringify({
+ entries: [
+ { id: 'a', words: words('authentication login session token refresh'), pageRank: 0.4, summary: 'JWT refresh tokens for login', accessCount: 3 },
+ { id: 'b', words: words('vector database hnsw index search'), pageRank: 0.2, summary: 'HNSW index for vector search', accessCount: 1 },
+ { id: 'c', words: words('docker deploy pipeline'), pageRank: 0.01, content: 'Deploy via docker compose' },
+ ],
+ }));
+ });
+ afterAll(() => {
+ rmSync(project, { recursive: true, force: true });
+ rmSync(home, { recursive: true, force: true });
+ });
+
+ function classicRoute(prompt: string): string {
+ return execFileSync(process.execPath, [join(HELPERS, 'hook-handler.cjs'), 'route'], {
+ input: JSON.stringify({ prompt }),
+ cwd: project,
+ env: { PATH: process.env.PATH, HOME: home, CLAUDE_PROJECT_DIR: project, CI: '1' },
+ encoding: 'utf8',
+ }).trim();
+ }
+
+ it.each([
+ 'implement login with refresh tokens',
+ 'search the vector database index',
+ 'deploy the docker pipeline',
+ 'hello',
+ ])('%j: same text the model reads', async (prompt) => {
+ const world = realWorld(project, {});
+ const mod = loadMod(register, world);
+ await mod.dispatch('session.start', { cwd: project, surface: null, isInteractive: false }, (e) => ({ cwd: e.cwd }));
+ let context: readonly string[] | undefined;
+ await mod.dispatch('prompt.submit', { text: prompt, wait: false, origin: { kind: 'composer' } }, (e) => {
+ context = e.context;
+ return { text: e.text, context: e.context };
+ });
+ expect(context).toHaveLength(1);
+ expect(context![0]).toBe(classicRoute(prompt));
+ });
+
+ it('adds nothing and passes the prompt through when it does not own route', async () => {
+ const world = memoryWorld('/work', {
+ hooks: { UserPromptSubmit: [{ hooks: [{ command: 'node "$CLAUDE_PROJECT_DIR/.claude/helpers/hook-handler.cjs" route' }] }] },
+ });
+ (world.files as Map<string, any>).set('/work/.claude/helpers/hook-handler.cjs', { text: '// a helper from before the handshake', mtimeMs: 1 });
+ const mod = loadMod(register, world);
+ await mod.dispatch('session.start', { cwd: '/work', surface: null, isInteractive: false }, (e) => ({ cwd: e.cwd }));
+ let seen: any;
+ await mod.dispatch('prompt.submit', { text: 'build it', wait: false, origin: { kind: 'composer' } }, (e) => (seen = e));
+ expect(seen.context).toBeUndefined();
+ expect(seen.text).toBe('build it');
+ });
+});