π 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(agenticow): COW memory substrate + governed distillation loop (ADR-170..173) (#2562)
rUvd759af6d6b30
diff --git a/.claude/scheduled_tasks.lock b/.claude/scheduled_tasks.lockdeleted file mode 100644index 9c55aa9710..0000000000--- a/.claude/scheduled_tasks.lock+++ /dev/null@@ -1 +0,0 @@-{"sessionId":"648181cd-0eef-4479-98a6-292dfcb55d98","pid":83633,"procStart":"Tue Jun 23 15:01:58 2026","acquiredAt":1782503724555}\ No newline at end of filediff --git a/agentdb.rvf.lock b/agentdb.rvf.lockindex 82686b8d2f..a1cd9dcee6 100644Binary files a/agentdb.rvf.lock and b/agentdb.rvf.lock differdiff --git a/scripts/audit-env-var-precedence.mjs b/scripts/audit-env-var-precedence.mjsindex 84b23f3084..4881c8f341 100644--- a/scripts/audit-env-var-precedence.mjs+++ b/scripts/audit-env-var-precedence.mjs@@ -173,6 +173,13 @@ const KNOWN_ESCAPE_HATCHES = new Set(['CLAUDE_FLOW_ROUTER_TRAJECTORY_MAXSIZE','CLAUDE_FLOW_ROUTER_TRAJECTORY_PATH','CLAUDE_FLOW_ROUTER_TRAJECTORY_TASKLEN',+ // Run-transcript capture (ADR-173 distill capture path) β opt-in, off by+ // default background recorder (PII/retention surface, mirrors ROUTER_TRAJECTORY+ // above). No user-facing command, so env-only by design; no CLI-flag precedence.+ 'CLAUDE_FLOW_RUN_TRANSCRIPTS',+ 'CLAUDE_FLOW_RUN_TRANSCRIPTS_PATH',+ 'CLAUDE_FLOW_RUN_TRANSCRIPTS_MAXROTATIONS',+ 'CLAUDE_FLOW_RUN_TRANSCRIPTS_MAXSIZE','CLAUDE_FLOW_SWARM_DIR', // Set by ruflo init / inter-process β not user-typed]);diff --git a/v3/@claude-flow/cli/__tests__/agenticow-speculate-tools.test.ts b/v3/@claude-flow/cli/__tests__/agenticow-speculate-tools.test.tsnew file mode 100644index 0000000000..a019949434--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/agenticow-speculate-tools.test.ts@@ -0,0 +1,247 @@+/**+ * Tests for agenticow speculative branch-and-promote (step 4).+ *+ * Surfaces under test:+ * 1. TOOL SHAPE β `agenticow_speculate` exists with a JSON-schema input + handler+ * (no package needed).+ * 2. CORE `explore()` HAPPY PATH β 3 candidate branches, a deterministic+ * scorer; assert the winner is PROMOTED into base (base query returns the+ * winner's vectors, and only the winner's) and the loser branch files are+ * DISCARDED. Skipped when the optional `agenticow` dep is absent.+ * 3. MCP HANDLER HAPPY PATH β the declarative `agenticow_speculate` tool+ * round-trips through a real base .rvf and reports the winner + discards.+ *+ * Mirrors __tests__/agenticow-tools.test.ts conventions (skipIf on package+ * availability; the degraded path is the load-bearing optional-dep rule).+ */+import { describe, it, expect, beforeAll, afterAll } from 'vitest';+import { mkdtempSync, rmSync, existsSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';++import { agenticowSpeculateTools } from '../src/mcp-tools/agenticow-speculate-tools.js';+import { explore } from '../src/agenticow/speculative-exploration.js';++function findTool(name: string) {+ const t = agenticowSpeculateTools.find(t => t.name === name);+ if (!t) throw new Error(`tool not found: ${name}`);+ return t;+}++// Detect agenticow availability at module scope (top-level await allowed in+// vitest ESM). Needed before `it.skipIf(...)`, which evaluates at definition time.+let havePkg = false;+let acow: any = null;+try { acow = await import('agenticow'); havePkg = true; } catch { havePkg = false; }++const DIM = 8;+// Separable one-hot vectors so nearest-neighbour is unambiguous under cosine.+const vSeed = [0, 0, 0, 1, 0, 0, 0, 0];+const vAlpha = [1, 0, 0, 0, 0, 0, 0, 0];+const vBeta = [0, 1, 0, 0, 0, 0, 0, 0];+const vGamma = [0, 0, 1, 0, 0, 0, 0, 0];++describe('agenticow_speculate β tool shape', () => {+ it('exposes exactly 1 tool (agenticow_speculate)', () => {+ expect(agenticowSpeculateTools.map(t => t.name)).toEqual(['agenticow_speculate']);+ });++ it('the tool has a JSON-schema object input + handler', () => {+ const t = findTool('agenticow_speculate');+ expect(t.inputSchema.type).toBe('object');+ expect(t.inputSchema.properties).toBeDefined();+ expect((t.inputSchema.required as string[])).toEqual(['basePath', 'candidates']);+ expect(typeof t.handler).toBe('function');+ });+});++describe('SpeculativeExploration.explore() β core happy path', () => {+ let workdir: string;+ let basePath: string;++ beforeAll(() => {+ workdir = mkdtempSync(join(tmpdir(), 'acow-speculate-'));+ basePath = join(workdir, 'base.rvf');+ });++ afterAll(() => {+ try { rmSync(workdir, { recursive: true, force: true }); } catch { /* ignore */ }+ });++ it('rejects an empty candidate list (no package needed)', async () => {+ // base handle is a harmless stub β validation runs before it is touched+ await expect(explore({} as any, [], () => 0, { branchPath: (l) => l }))+ .rejects.toThrow(/at least one candidate/);+ });++ it.skipIf(!havePkg)(+ 'forks 3 branches, promotes the winner into base, discards the losers',+ async () => {+ const base = acow.open(basePath, { dimension: DIM });+ // Seed base so we can prove ONLY the winner (not losers) is promoted on top.+ base.ingest([{ id: 1, vector: vSeed }]);++ const branchPath = (label: string) => join(workdir, `b-${label}.rvf`);++ // Each candidate ingests its own vector into its own COW branch.+ const candidates = [+ { label: 'alpha', fn: (b: any) => { b.ingest([{ id: 101, vector: vAlpha }]); return 'alpha'; } },+ { label: 'beta', fn: (b: any) => { b.ingest([{ id: 102, vector: vBeta }]); return 'beta'; } },+ { label: 'gamma', fn: (b: any) => { b.ingest([{ id: 103, vector: vGamma }]); return 'gamma'; } },+ ];++ // Deterministic scorer: beta is best (3 > 2 > 1).+ const rank: Record<string, number> = { alpha: 1, beta: 3, gamma: 2 };+ const score = (_r: string, label: string) => rank[label];++ const result = await explore(base, candidates, score, { branchPath });++ // Winner is beta; losers were discarded.+ expect(result.winner).toBe('beta');+ expect(result.promoted).toBe(true);+ expect(result.discarded.slice().sort()).toEqual(['alpha', 'gamma']);+ expect(result.scores).toEqual({ alpha: 1, beta: 3, gamma: 2 });++ // Loser branch files (and their manifests) are gone; 162-byte discard.+ expect(existsSync(join(workdir, 'b-alpha.rvf'))).toBe(false);+ expect(existsSync(join(workdir, 'b-gamma.rvf'))).toBe(false);+ expect(existsSync(join(workdir, 'b-alpha.rvf.agenticow.json'))).toBe(false);++ // The winner is promoted INTO base: base now contains seed + beta only.+ expect(base.status().totalVectors).toBe(2);+ const hitB = base.query(vBeta, 1);+ expect(hitB[0].id).toBe(102); // beta's vector lives in base now+ const hitSeed = base.query(vSeed, 1);+ expect(hitSeed[0].id).toBe(1); // original seed preserved+ // alpha's id was NOT promoted β it is nowhere in base.+ const allIds = [vSeed, vAlpha, vBeta, vGamma].flatMap(v => base.query(v, 2).map((h: any) => h.id));+ expect(allIds).not.toContain(101);+ expect(allIds).not.toContain(103);++ base.close?.();+ },+ );+});++describe('agenticow_speculate β MCP handler happy path', () => {+ let workdir: string;+ let basePath: string;++ beforeAll(() => {+ workdir = mkdtempSync(join(tmpdir(), 'acow-speculate-mcp-'));+ basePath = join(workdir, 'base.rvf');+ });++ afterAll(() => {+ try { rmSync(workdir, { recursive: true, force: true }); } catch { /* ignore */ }+ });++ it.skipIf(!havePkg)(+ "picks the branch whose ingest is nearest the probe and discards the rest",+ async () => {+ const tool = findTool('agenticow_speculate');+ const result: any = await tool.handler({+ basePath,+ dimension: DIM,+ // probe matches beta β beta should win under scoreBy='nearest'+ probe: vBeta,+ candidates: [+ { label: 'alpha', ingest: [{ id: 201, vector: vAlpha }] },+ { label: 'beta', ingest: [{ id: 202, vector: vBeta }] },+ { label: 'gamma', ingest: [{ id: 203, vector: vGamma }] },+ ],+ });++ expect(result.success).toBe(true);+ expect(result.degraded).toBeUndefined();+ expect(result.winner).toBe('beta');+ expect(result.scoreBy).toBe('nearest');+ expect(result.discarded.slice().sort()).toEqual(['alpha', 'gamma']);+ // loser branch files deleted (default path is alongside base)+ expect(existsSync(`${basePath}.spec-alpha.rvf`)).toBe(false);+ expect(existsSync(`${basePath}.spec-gamma.rvf`)).toBe(false);++ // Reopen base and confirm the winner's vector was promoted.+ const base = acow.AgenticMemory.load(`${basePath}.agenticow.json`);+ const hit = base.query(vBeta, 1);+ expect(hit[0].id).toBe(202);+ base.close?.();+ },+ );++ it.skipIf(!havePkg)("rejects scoreBy='nearest' without a probe vector", async () => {+ const tool = findTool('agenticow_speculate');+ await expect(tool.handler({+ basePath: join(workdir, 'noprobe.rvf'),+ dimension: DIM,+ candidates: [{ label: 'a', ingest: [{ id: 1, vector: vAlpha }] }],+ })).rejects.toThrow(/requires a probe vector/);+ });++ // ADR-171 promotion gate (#23) β the acceptance-test invariants.+ it.skipIf(!havePkg)('requireClearance fail-closes: winner ineligible, base unchanged, receipts emitted', async () => {+ const tool = findTool('agenticow_speculate');+ const basePath = join(workdir, 'gate.rvf');+ const r = await tool.handler({+ basePath,+ dimension: DIM,+ probe: vBeta,+ requireClearance: true,+ candidates: [+ { label: 'a', ingest: [{ id: 101, vector: vAlpha }] },+ { label: 'b', ingest: [{ id: 202, vector: vBeta }] },+ ],+ }) as any;+ expect(r.promoted).toBe(false);+ expect(r.promotionDecision).toMatch(/^ineligible:/);+ expect(r.receipts.length).toBeGreaterThan(0);+ // Base must NOT contain any candidate vector β nothing graduated.+ const base = acow.AgenticMemory.load(`${basePath}.agenticow.json`);+ const ids = base.query(vBeta, 5).map((h: any) => h.id);+ expect(ids).not.toContain(202);+ base.close?.();+ });+});++// Core-level gate semantics (exercises explore() directly with clearance fns).+describe('speculative explore() β ADR-171 clearance gate', () => {+ it.skipIf(!havePkg)('proxy:structural can never clear a promote, even claiming cleared:true', async () => {+ const { explore } = await import('../src/agenticow/speculative-exploration.js');+ const dir = mkdtempSync(join(tmpdir(), 'gate-core-'));+ try {+ const base = acow.AgenticMemory.open(join(dir, 'b.rvf'), { dimension: DIM });+ base.ingest([{ id: 1, vector: vAlpha }]);+ const cands = [{ label: 'x', fn: async (br: any) => { br.ingest([{ id: 9, vector: vBeta }]); return 5; } }];+ const r = await explore(base, cands, (res: number) => res, {+ branchPath: (l: string) => join(dir, `br-${l}.rvf`),+ persist: true,+ clearance: async () => ({ cleared: true, by: 'proxy:structural' as const }),+ });+ expect(r.promoted).toBe(false);+ expect(r.promotionDecision).toBe('ineligible:proxy-cannot-clear');+ base.close?.();+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ it.skipIf(!havePkg)('oracle:test-exec clears the winner into base', async () => {+ const { explore } = await import('../src/agenticow/speculative-exploration.js');+ const dir = mkdtempSync(join(tmpdir(), 'gate-oracle-'));+ try {+ const base = acow.AgenticMemory.open(join(dir, 'b.rvf'), { dimension: DIM });+ base.ingest([{ id: 1, vector: vAlpha }]);+ const cands = [{ label: 'x', fn: async (br: any) => { br.ingest([{ id: 9, vector: vBeta }]); return 5; } }];+ const r = await explore(base, cands, (res: number) => res, {+ branchPath: (l: string) => join(dir, `br-${l}.rvf`),+ persist: true,+ clearance: async () => ({ cleared: true, by: 'oracle:test-exec' as const }),+ });+ expect(r.promoted).toBe(true);+ expect(r.promotedBy).toBe('oracle:test-exec');+ base.close?.();+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });+});diff --git a/v3/@claude-flow/cli/__tests__/agenticow-tools.test.ts b/v3/@claude-flow/cli/__tests__/agenticow-tools.test.tsindex aeca1abf73..2989028c25 100644--- a/v3/@claude-flow/cli/__tests__/agenticow-tools.test.ts+++ b/v3/@claude-flow/cli/__tests__/agenticow-tools.test.ts@@ -54,16 +54,78 @@ describe('agenticow MCP tools β happy path (real package)', () => {try { rmSync(workdir, { recursive: true, force: true }); } catch { /* ignore */ }});- it('exposes exactly 4 tools (branch / checkpoint / rollback / promote)', () => {+ it('exposes 9 tools (lifecycle + read/write verbs)', () => {const names = agenticowTools.map(t => t.name).sort();expect(names).toEqual(['agenticow_branch','agenticow_checkpoint',+ 'agenticow_diff',+ 'agenticow_ingest',+ 'agenticow_lineage','agenticow_promote',+ 'agenticow_query','agenticow_rollback',+ 'agenticow_status',]);});+ it.skipIf(!havePkg)('ingest β query round-trips vectors + text across a COW branch (issue: text persistence)', async () => {+ const ingest = findTool('agenticow_ingest');+ const query = findTool('agenticow_query');+ const branch = findTool('agenticow_branch');+ const v = (s: number) => Array.from({ length: 8 }, (_, i) => Math.sin(s + i));+ const base = join(workdir, 'rw-base.rvf');+ const br = join(workdir, 'rw-branch.rvf');++ const ing = await ingest.handler({ path: base, records: [+ { id: 1, vector: v(1), text: 'alpha' }, { id: 2, vector: v(2), text: 'beta' },+ ], dimension: 8 }) as any;+ expect(ing.success).toBe(true);+ expect(ing.ingested.accepted).toBe(2);++ // branch with the native ANN fast path, then ingest a branch-only vector+ const b = await branch.handler({ basePath: base, branchPath: br, label: 'rw', nativeAnn: true }) as any;+ expect(b.nativeAnn).toBe(true);+ await ingest.handler({ path: br, records: [{ id: 3, vector: v(3), text: 'gamma' }] });++ // query the branch: sees base βͺ branch, and text survives (0.2.4 fix)+ const q = await query.handler({ path: br, vector: v(1), k: 3 }) as any;+ expect(q.success).toBe(true);+ const hit = q.hits.find((h: any) => h.id === 1);+ expect(hit).toBeDefined();+ expect(hit.text).toBe('alpha');+ });++ it.skipIf(!havePkg)('diff / lineage / status report branch state', async () => {+ const ingest = findTool('agenticow_ingest');+ const diff = findTool('agenticow_diff');+ const lineage = findTool('agenticow_lineage');+ const status = findTool('agenticow_status');+ const v = (s: number) => Array.from({ length: 8 }, (_, i) => Math.cos(s + i));+ const p = join(workdir, 'introspect.rvf');+ await ingest.handler({ path: p, records: [{ id: 10, vector: v(1), text: 'x' }], dimension: 8 });++ const d = await diff.handler({ path: p }) as any;+ expect(d.success).toBe(true);+ expect(Array.isArray(d.diff.added)).toBe(true);++ const lin = await lineage.handler({ path: p }) as any;+ expect(lin.success).toBe(true);+ expect(lin.lineage.some((n: any) => n.role === 'working' || n.role === 'base')).toBe(true);++ const st = await status.handler({ path: p }) as any;+ expect(st.success).toBe(true);+ expect(st.status.dimension).toBe(8);+ });++ it('new read/write verbs degrade + validate like the lifecycle verbs', async () => {+ // path-traversal rejection is shared via resolveMemoryPath+ const query = findTool('agenticow_query');+ await expect(query.handler({ path: '../../etc/passwd', vector: [1, 2] })).rejects.toThrow(/disallowed/);+ const ingest = findTool('agenticow_ingest');+ await expect(ingest.handler({ path: 'ok.rvf', records: [] })).rejects.toThrow(/non-empty/);+ });+it('every tool has a JSON-schema input + handler', () => {for (const t of agenticowTools) {expect(t.inputSchema.type).toBe('object');diff --git a/v3/@claude-flow/cli/__tests__/checkpoint-gate.test.ts b/v3/@claude-flow/cli/__tests__/checkpoint-gate.test.tsnew file mode 100644index 0000000000..59039d3917--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/checkpoint-gate.test.ts@@ -0,0 +1,237 @@+/**+ * Tests for CheckpointGate β the agenticow-backed checkpoint/rollback gate for+ * autopilot loops (agenticow step 3).+ *+ * Two surfaces under test (mirrors agenticow-tools.test.ts conventions):+ * 1. HAPPY PATH β agenticow installed. guard() checkpoints a real temp `.rvf`,+ * the tick mutates it, and a regression verdict rolls it back so the+ * mutation is discarded. The success path keeps the checkpoint.+ * 2. DEGRADED PATH β no memory path / kill switch. guard() runs the tick+ * unguarded and reports degraded:true with no throw.+ *+ * Why both: agenticow is in optionalDependencies β the degraded path is the+ * load-bearing architectural rule (zero hard runtime dep, non-fatal loop).+ */+import { describe, it, expect, beforeAll, afterAll, afterEach } from 'vitest';+import { mkdtempSync, rmSync, existsSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';++import {+ CheckpointGate,+ getCheckpointGate,+ __resetCheckpointGateForTests,+ CHECKPOINT_MEM_ENV,+ KILL_SWITCH_ENV,+} from '../src/services/checkpoint-gate.js';++// Detect agenticow availability at module scope (top-level await is allowed in+// vitest ESM). Needed before the it.skipIf(...) calls, which evaluate eagerly.+let havePkg = false;+let acow: any;+try { acow = await import('agenticow'); havePkg = true; } catch { havePkg = false; }++const DIM = 8;+const vec = (s: number) => Array.from({ length: DIM }, (_, i) => Math.sin(s + i));++/** Open a memory file the same way the gate does (load lineage manifest when+ * present), so verification sees post-checkpoint / post-rollback state. */+async function openMem(path: string) {+ const manifest = `${path}.agenticow.json`;+ if (existsSync(manifest)) return acow.AgenticMemory.load(manifest);+ return acow.open(path, { dimension: DIM });+}++/**+ * The set of vector ids currently VISIBLE across the whole COW lineage.+ *+ * We query (not status()) because agenticow's status().totalVectors reports+ * only the working segment, whereas query() reads through the full chain+ * (base βͺ edits, child wins) β which is exactly what a checkpoint/rollback+ * changes. k=50 comfortably exceeds the tiny test datasets, so every visible+ * id is returned.+ */+async function visibleIds(path: string): Promise<Set<number>> {+ const mem = await openMem(path);+ try {+ const hits = await mem.query(vec(1), 50);+ return new Set<number>(hits.map((h: any) => Number(h.id)));+ } finally {+ await mem.close?.();+ }+}++/** Seed a base `.rvf` with `n` vectors and persist its lineage manifest. */+async function seed(path: string, n: number): Promise<void> {+ const mem = await acow.open(path, { dimension: DIM });+ try {+ await mem.ingest(Array.from({ length: n }, (_, i) => ({ id: i + 1, vector: vec(i + 1), text: `v${i + 1}` })));+ await mem.save?.(`${path}.agenticow.json`);+ } finally {+ await mem.close?.();+ }+}++/** Append `n` vectors (a "mutation" a tick would make). */+async function mutate(path: string, startId: number, n: number): Promise<void> {+ const mem = await openMem(path);+ try {+ await mem.ingest(Array.from({ length: n }, (_, i) => ({ id: startId + i, vector: vec(startId + i), text: `m${startId + i}` })));+ await mem.save?.(`${path}.agenticow.json`);+ } finally {+ await mem.close?.();+ }+}++describe('CheckpointGate β degraded / opt-out paths (no agenticow needed)', () => {+ afterEach(() => {+ delete process.env[KILL_SWITCH_ENV];+ delete process.env[CHECKPOINT_MEM_ENV];+ __resetCheckpointGateForTests();+ });++ it('runs the tick unguarded when no memory path is given', async () => {+ const gate = new CheckpointGate();+ let ran = false;+ const out = await gate.guard(undefined, 'no-path', async () => { ran = true; return { success: true, n: 42 }; });+ expect(ran).toBe(true);+ expect(out.result).toEqual({ success: true, n: 42 });+ expect(out.checkpointed).toBe(false);+ expect(out.rolledBack).toBe(false);+ expect(out.degraded).toBe(true);+ expect(out.reason).toBe('no-memory-path');+ });++ it('kill switch forces unguarded pass-through even with a memory path', async () => {+ process.env[KILL_SWITCH_ENV] = '1';+ __resetCheckpointGateForTests();+ const gate = new CheckpointGate();+ const out = await gate.guard('/tmp/whatever.rvf', 'killed', async () => ({ success: true }));+ expect(out.degraded).toBe(true);+ expect(out.reason).toBe('kill-switch');+ expect(out.checkpointed).toBe(false);+ expect(CheckpointGate.isKillSwitchSet()).toBe(true);+ });++ it('configuredMemPath reflects the env var', () => {+ expect(CheckpointGate.configuredMemPath()).toBeUndefined();+ process.env[CHECKPOINT_MEM_ENV] = '/data/loop.rvf';+ expect(CheckpointGate.configuredMemPath()).toBe('/data/loop.rvf');+ });++ it('rejects path traversal in the memory path (checkpoint)', async () => {+ const gate = new CheckpointGate();+ // Only meaningful when agenticow is present (validation runs after load);+ // when absent it degrades. Either way it must not silently succeed.+ const r = await gate.checkpoint('../../etc/passwd', 'evil').catch((e) => ({ threw: String(e) } as any));+ if (havePkg) {+ expect(r.threw).toMatch(/disallowed/);+ } else {+ expect(r.degraded).toBe(true);+ }+ });++ it('getCheckpointGate returns a stable shared instance', () => {+ const a = getCheckpointGate();+ const b = getCheckpointGate();+ expect(a).toBe(b);+ });+});++describe.skipIf(!havePkg)('CheckpointGate β happy path (real agenticow, temp .rvf)', () => {+ let workdir: string;++ beforeAll(() => {+ workdir = mkdtempSync(join(tmpdir(), 'checkpoint-gate-'));+ });+ afterAll(() => {+ try { rmSync(workdir, { recursive: true, force: true }); } catch { /* ignore */ }+ __resetCheckpointGateForTests();+ });++ it('checkpoint β mutate β rollback restores the pre-tick memory state', async () => {+ const path = join(workdir, 'rollback.rvf');+ await seed(path, 3);+ expect(await visibleIds(path)).toEqual(new Set([1, 2, 3]));++ const gate = new CheckpointGate();+ // A regressing tick: mutate memory, then report failure.+ const out = await gate.guard(path, 'iter-1', async () => {+ await mutate(path, 100, 4); // tick writes 4 speculative vectors (ids 100-103)+ return { success: false, reason: 'verifier-failed' };+ });++ expect(out.checkpointed).toBe(true);+ expect(out.rolledBack).toBe(true);+ expect(out.degraded).toBe(false);+ expect(out.reason).toBe('regression-verdict');+ // The 4 speculative vectors are discarded β back to the checkpoint.+ expect(await visibleIds(path)).toEqual(new Set([1, 2, 3]));+ });++ it('success verdict keeps the mutation (no rollback)', async () => {+ const path = join(workdir, 'keep.rvf');+ await seed(path, 2);+ expect(await visibleIds(path)).toEqual(new Set([1, 2]));++ const gate = new CheckpointGate();+ const out = await gate.guard(path, 'iter-1', async () => {+ await mutate(path, 200, 3); // good tick writes ids 200-202+ return { success: true };+ });++ expect(out.checkpointed).toBe(true);+ expect(out.rolledBack).toBe(false);+ expect(out.degraded).toBe(false);+ // Mutation retained across the lineage.+ expect(await visibleIds(path)).toEqual(new Set([1, 2, 200, 201, 202]));+ });++ it('a throwing tick rolls back then re-throws (rethrow default)', async () => {+ const path = join(workdir, 'throw.rvf');+ await seed(path, 2);++ const gate = new CheckpointGate();+ await expect(gate.guard(path, 'iter-1', async () => {+ await mutate(path, 300, 5);+ throw new Error('tick blew up');+ })).rejects.toThrow(/tick blew up/);++ // Rolled back despite the throw β mutation discarded.+ expect(await visibleIds(path)).toEqual(new Set([1, 2]));+ });++ it('a throwing tick with rethrow:false returns the error and rolls back', async () => {+ const path = join(workdir, 'throw-soft.rvf');+ await seed(path, 1);++ const gate = new CheckpointGate();+ const out = await gate.guard(path, 'iter-1', async () => {+ await mutate(path, 400, 2);+ throw new Error('soft fail');+ }, { rethrow: false });++ expect(out.result).toBeUndefined();+ expect(out.rolledBack).toBe(true);+ expect(out.reason).toBe('tick-threw');+ expect(out.error).toBeInstanceOf(Error);+ expect(await visibleIds(path)).toEqual(new Set([1]));+ });++ it('standalone checkpoint() then rollback() round-trips via the manifest', async () => {+ const path = join(workdir, 'manual.rvf');+ await seed(path, 2);++ const gate = new CheckpointGate();+ const cp = await gate.checkpoint(path, 'cp-manual');+ expect(cp.ok).toBe(true);+ expect(existsSync(`${path}.agenticow.json`)).toBe(true);++ await mutate(path, 500, 3);+ expect(await visibleIds(path)).toEqual(new Set([1, 2, 500, 501, 502]));++ const rb = await gate.rollback(path);+ expect(rb.ok).toBe(true);+ expect(await visibleIds(path)).toEqual(new Set([1, 2]));+ });+});diff --git a/v3/@claude-flow/cli/__tests__/services/distill-oracle.test.ts b/v3/@claude-flow/cli/__tests__/services/distill-oracle.test.tsnew file mode 100644index 0000000000..1e91112eee--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/services/distill-oracle.test.ts@@ -0,0 +1,289 @@+/**+ * distill-oracle.test.ts β unit tests for the tiered `resolved` labeler.+ *+ * Every external boundary is MOCKED: the Tier-1 SSH runner is injected (no real+ * ssh), and the Tier-2 Fable harness is injected (no real claude / spend). The+ * suite asserts:+ * β’ the ZERO-EXTERNAL-CALL default path (no opts β dry-run + structural proxy)+ * β’ provenance tagging on every tier (oracle:test-exec / judge:fable / proxy:structural)+ * β’ tier fallback order (oracle β fable β proxy) per trajectory+ * β’ Tier-1 command construction + remote parameterization (no hard-coded host)+ * β’ graceful degradation (probe failure, harness omission β proxy fallback)+ */++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import {+ labelResolved,+ reflectFailures,+ buildOraclePlan,+ hasMechanicalSpec,+ resolveRemote,+ createSshOracleRunner,+ type Trajectory,+ type OracleRunner,+ type CommandExec,+} from '../../src/services/distill-oracle.js';+import type { FableHarness, JudgeResult, ReflectResult } from '../../src/services/fable-harness.js';++// A trajectory with a mechanical spec (SWE-bench shape).+const specTraj = (id: string): Trajectory => ({+ id,+ task: 'Fix the null deref in parser',+ output: 'export function parse(x){ return x?.value ?? null; }',+ testSpec: { failToPass: ['test_parse_null'], repo: 'acme/parser', baseCommit: 'abc123', patch: 'diff --git a b' },+});++// A trajectory with NO mechanical spec (only task/output).+const proseTraj = (id: string, output = 'export function add(a,b){ return a+b; }'): Trajectory => ({+ id,+ task: 'Implement add',+ output,+});++/** A runner spy that records calls and returns canned outcomes. */+function spyRunner(overrides: Partial<OracleRunner> = {}): OracleRunner & { probeCalls: number; evalCalls: number } {+ const r = {+ probeCalls: 0,+ evalCalls: 0,+ async preflight() { r.probeCalls++; return { ok: true, reason: 'ok' }; },+ async runEval() { r.evalCalls++; return { resolved: true, reason: 'FAIL_TO_PASS green' }; },+ ...overrides,+ } as OracleRunner & { probeCalls: number; evalCalls: number };+ return r;+}++/** A harness stub with only the methods labelResolved uses. */+function stubHarness(verdicts: JudgeResult[], reflections: ReflectResult[] = []): FableHarness {+ return {+ isEnabled: () => true,+ judgeBatch: vi.fn(async () => verdicts),+ reflectFailures: vi.fn(async () => reflections),+ getSpentUsd: () => 0,+ } as unknown as FableHarness;+}++describe('labelResolved β ZERO-external-call default path', () => {+ it('labels a spec trajectory via dry-run preflight + structural proxy, touching nothing', async () => {+ const runner = spyRunner();+ const harness = stubHarness([]);+ const [out] = await labelResolved([specTraj('a')], { runner, harness });++ // Provenance is the structural proxy β the honest weakest tier.+ expect(out.resolvedBy).toBe('proxy:structural');+ // The oracle plan is attached as a DRY-RUN preflight (transparency)β¦+ expect(out.oraclePreflight?.dryRun).toBe(true);+ expect(out.oraclePreflight?.plan.evalCommands.length).toBeGreaterThan(0);+ // β¦but NEITHER the SSH runner NOR the Fable harness was ever invoked.+ expect(runner.probeCalls).toBe(0);+ expect(runner.evalCalls).toBe(0);+ expect(harness.judgeBatch).not.toHaveBeenCalled();+ expect(typeof out.resolved).toBe('boolean');+ expect(typeof out.resolvedConfidence).toBe('number');+ });++ it('labels a prose trajectory via structural proxy only', async () => {+ const [good] = await labelResolved([proseTraj('g')]);+ expect(good.resolvedBy).toBe('proxy:structural');+ expect(good.resolved).toBe(true); // clean code passes structural signals++ const [bad] = await labelResolved([proseTraj('b', 'I cannot help with that.')]);+ expect(bad.resolvedBy).toBe('proxy:structural');+ expect(bad.resolved).toBe(false); // refusal β not resolved+ });++ it('preserves passthrough fields and ids', async () => {+ const t: Trajectory = { id: 'keep', task: 'x', output: 'export const y=1;', extra: 42 };+ const [out] = await labelResolved([t]);+ expect(out.id).toBe('keep');+ expect((out as { extra?: number }).extra).toBe(42);+ });+});++describe('labelResolved β Tier 1 mechanical oracle (execute)', () => {+ it('runs the real eval and tags oracle:test-exec on success', async () => {+ const runner = spyRunner();+ const [out] = await labelResolved([specTraj('a')], { remote: 'testhost', execute: true, runner });+ expect(out.resolvedBy).toBe('oracle:test-exec');+ expect(out.resolved).toBe(true);+ expect(out.resolvedConfidence).toBe(1);+ expect(out.oraclePreflight?.dryRun).toBe(false);+ expect(runner.probeCalls).toBe(1);+ expect(runner.evalCalls).toBe(1);+ });++ it('propagates a failing eval as resolved=false with oracle provenance', async () => {+ const runner = spyRunner({ async runEval() { return { resolved: false, reason: 'still red' }; } });+ const [out] = await labelResolved([specTraj('a')], { remote: 'testhost', execute: true, runner });+ expect(out.resolvedBy).toBe('oracle:test-exec');+ expect(out.resolved).toBe(false);+ expect(out.resolvedReason).toContain('still red');+ });++ it('falls through to the proxy when the preflight probe fails (non-fatal)', async () => {+ const runner = spyRunner({ async preflight() { return { ok: false, reason: 'ssh unreachable' }; } });+ const [out] = await labelResolved([specTraj('a')], { remote: 'testhost', execute: true, runner });+ expect(out.resolvedBy).toBe('proxy:structural'); // probe failed β fell through+ expect(runner.evalCalls).toBe(0); // never ran the eval after a failed probe+ expect(out.oraclePreflight?.probe?.ok).toBe(false);+ expect(out.oraclePreflight?.fellThroughBecause).toContain('preflight failed');+ });+});++describe('labelResolved β Tier 2 Fable judge (opt-in + budget)', () => {+ it('judges prose trajectories via the harness and tags judge:fable', async () => {+ const harness = stubHarness([{ id: 'g', resolved: true, confidence: 0.77, reason: 'looks correct' }]);+ const [out] = await labelResolved([proseTraj('g')], { fableJudge: true, maxBudgetUsd: 1, harness });+ expect(out.resolvedBy).toBe('judge:fable');+ expect(out.resolved).toBe(true);+ expect(out.resolvedConfidence).toBeCloseTo(0.77, 2);+ expect(out.resolvedReason).toBe('looks correct');+ expect(harness.judgeBatch).toHaveBeenCalledTimes(1);+ });++ it('does NOT call fable when fableJudge is set but no budget cap is given', async () => {+ const harness = stubHarness([{ id: 'g', resolved: true, confidence: 1, reason: 'x' }]);+ const [out] = await labelResolved([proseTraj('g')], { fableJudge: true, harness }); // no maxBudgetUsd+ expect(out.resolvedBy).toBe('proxy:structural');+ expect(harness.judgeBatch).not.toHaveBeenCalled();+ });++ it('falls back to proxy for any id the model omits', async () => {+ const harness = stubHarness([{ id: 'g0', resolved: false, confidence: 0.2, reason: 'wrong' }]); // omits g1+ const out = await labelResolved([proseTraj('g0'), proseTraj('g1')], { fableJudge: true, maxBudgetUsd: 1, harness });+ expect(out[0].resolvedBy).toBe('judge:fable');+ expect(out[1].resolvedBy).toBe('proxy:structural');+ });+});++describe('labelResolved β tier fallback ORDER', () => {+ it('spec + execute:false + fableJudge β dry-run oracle THEN fable (order preserved)', async () => {+ const runner = spyRunner();+ const harness = stubHarness([{ id: 'a', resolved: true, confidence: 0.9, reason: 'judged' }]);+ const [out] = await labelResolved([specTraj('a')], { fableJudge: true, maxBudgetUsd: 1, runner, harness });+ // Tier 1 was dry-run (no exec) so it fell through to Tier 2 (fable).+ expect(out.resolvedBy).toBe('judge:fable');+ expect(out.oraclePreflight?.dryRun).toBe(true); // Tier-1 plan still attached+ expect(runner.evalCalls).toBe(0); // never executed+ });++ it('mixed batch: spec+execute β oracle, prose β fable, refusal via fable', async () => {+ const runner = spyRunner();+ const harness = stubHarness([{ id: 'p', resolved: false, confidence: 0.3, reason: 'incomplete' }]);+ const out = await labelResolved([specTraj('s'), proseTraj('p')], {+ remote: 'h', execute: true, fableJudge: true, maxBudgetUsd: 1, runner, harness,+ });+ const byId = Object.fromEntries(out.map((o) => [o.id, o.resolvedBy]));+ expect(byId['s']).toBe('oracle:test-exec');+ expect(byId['p']).toBe('judge:fable');+ });+});++describe('buildOraclePlan β command construction & remote parameterization', () => {+ it('builds a SWE-bench eval plan and injects the remote host (never hard-coded)', () => {+ const plan = buildOraclePlan(+ { failToPass: ['t_a', 't_b'], passToPass: ['t_c'], repo: 'acme/x', baseCommit: 'deadbeef', patch: 'diff' },+ 'my-remote-host',+ );+ expect(plan.kind).toBe('ssh-swebench-eval');+ expect(plan.remote).toBe('my-remote-host');+ const all = [...plan.probeCommands, ...plan.evalCommands].join('\n');+ expect(all).toContain('my-remote-host');+ expect(all).toContain('--fail-to-pass');+ expect(all).not.toMatch(/ruvultra|\d+\.\d+\.\d+\.\d+/); // no hard-coded host or IP+ expect(plan.probeCommands.some((c) => c.includes('command -v docker'))).toBe(true);+ });++ it('builds a darwin bench-suite plan when benchSuite/benchCase present', () => {+ const plan = buildOraclePlan({ benchSuite: 'shield', benchCase: 'cve-42' }, 'h');+ expect(plan.kind).toBe('ssh-darwin-bench');+ expect(plan.evalCommands.join(' ')).toContain('darwin bench run');+ expect(plan.evalCommands.join(' ')).toContain("--suite 'shield'");+ });++ it('renders a <remote> placeholder (not a real host) when no remote is configured', () => {+ const plan = buildOraclePlan({ evalCommand: 'pytest -q' }, null);+ expect(plan.remote).toBeNull();+ expect(plan.evalCommands.join(' ')).toContain('<remote>');+ expect(plan.evalCommands.join(' ')).toContain('pytest -q');+ });+});++describe('createSshOracleRunner β mocked SSH exec', () => {+ it('runs each plan command via sh -c and reports resolved on exit 0', async () => {+ const calls: Array<{ cmd: string; args: string[] }> = [];+ const exec: CommandExec = async (cmd, args) => {+ calls.push({ cmd, args });+ return { stdout: '{"passed":true}', stderr: '', code: 0 };+ };+ const runner = createSshOracleRunner(exec);+ const plan = buildOraclePlan({ failToPass: ['t'], repo: 'r' }, 'host');+ const probe = await runner.preflight(plan);+ expect(probe.ok).toBe(true);+ const outcome = await runner.runEval(plan, { failToPass: ['t'] });+ expect(outcome.resolved).toBe(true);+ // Every shell-out went through `sh -c <fully-rendered-command>`.+ expect(calls.every((c) => c.cmd === 'sh' && c.args[0] === '-c')).toBe(true);+ });++ it('interprets json passed:false as NOT resolved', async () => {+ const exec: CommandExec = async () => ({ stdout: '{"passed":false}', stderr: '', code: 0 });+ const runner = createSshOracleRunner(exec);+ const plan = buildOraclePlan({ evalCommand: 'run' }, 'host');+ const outcome = await runner.runEval(plan, { evalCommand: 'run' });+ expect(outcome.resolved).toBe(false);+ });++ it('reports probe failure (non-zero exit) without throwing', async () => {+ const exec: CommandExec = async () => ({ stdout: '', stderr: 'connection refused', code: 255 });+ const runner = createSshOracleRunner(exec);+ const plan = buildOraclePlan({ evalCommand: 'run' }, 'host');+ const probe = await runner.preflight(plan);+ expect(probe.ok).toBe(false);+ expect(probe.reason).toContain('probe failed');+ });++ it('preflight is false when no remote is configured', async () => {+ const exec: CommandExec = vi.fn(async () => ({ stdout: '', stderr: '', code: 0 }));+ const runner = createSshOracleRunner(exec as unknown as CommandExec);+ const plan = buildOraclePlan({ evalCommand: 'run' }, null);+ const probe = await runner.preflight(plan);+ expect(probe.ok).toBe(false);+ expect(exec).not.toHaveBeenCalled(); // no remote β no shell-out at all+ });+});++describe('helpers', () => {+ it('hasMechanicalSpec detects actionable specs only', () => {+ expect(hasMechanicalSpec(specTraj('a'))).toBe(true);+ expect(hasMechanicalSpec({ id: 'x', testSpec: { benchSuite: 's' } })).toBe(true);+ expect(hasMechanicalSpec({ id: 'x', testSpec: { repo: 'only-repo' } })).toBe(false);+ expect(hasMechanicalSpec(proseTraj('p'))).toBe(false);+ });++ describe('resolveRemote', () => {+ const saved = process.env.RUFLO_DISTILL_REMOTE;+ beforeEach(() => { delete process.env.RUFLO_DISTILL_REMOTE; });+ afterEach(() => { if (saved === undefined) delete process.env.RUFLO_DISTILL_REMOTE; else process.env.RUFLO_DISTILL_REMOTE = saved; });++ it('prefers explicit opt, then env, then null', () => {+ expect(resolveRemote('explicit')).toBe('explicit');+ process.env.RUFLO_DISTILL_REMOTE = 'from-env';+ expect(resolveRemote()).toBe('from-env');+ delete process.env.RUFLO_DISTILL_REMOTE;+ expect(resolveRemote()).toBeNull();+ });+ });+});++describe('reflectFailures', () => {+ it('is a no-op ($0) without a budget cap', async () => {+ const out = await reflectFailures([{ id: 'a', task: 't', output: 'o' }]);+ expect(out).toEqual([]);+ });++ it('delegates to an enabled harness', async () => {+ const harness = stubHarness([], [{ id: 'a', failureClass: 'oops', diagnosis: 'd', mutationHint: 'm' }]);+ const out = await reflectFailures([{ id: 'a', task: 't', output: 'o' }], { harness });+ expect(out).toEqual([{ id: 'a', failureClass: 'oops', diagnosis: 'd', mutationHint: 'm' }]);+ });+});diff --git a/v3/@claude-flow/cli/__tests__/services/fable-harness.test.ts b/v3/@claude-flow/cli/__tests__/services/fable-harness.test.tsnew file mode 100644index 0000000000..ecfe76c3c1--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/services/fable-harness.test.ts@@ -0,0 +1,203 @@+/**+ * fable-harness.test.ts β unit tests for the cost-disciplined Fable judge.+ *+ * Every test MOCKS the `claude -p` spawn via the injectable `spawnClaude` β no+ * test ever launches the real CLI or spends a cent. Assertions cover:+ * β’ command construction (argv: -p / --model / --output-format json /+ * --append-system-prompt / --max-budget-usd)+ * β’ the fresh-empty-temp-cwd requirement (never the project dir)+ * β’ batching (ceil(n / batchSize) calls)+ * β’ budget-cap enforcement (spend stops launching batches)+ * β’ the OFF-BY-DEFAULT guarantee β no budget cap β ZERO spawns+ * β’ verdict extraction from the JSON envelope+ *+ * One optional live smoke (RUFLO_FABLE_LIVE=1) a human can run is at the end.+ */++import { describe, it, expect, vi } from 'vitest';+import { tmpdir } from 'os';+import {+ FableHarness,+ estimateFableCostUsd,+ extractVerdictArray,+ parseCostFromEnvelope,+ FABLE_COST_MODEL,+ type ClaudeSpawnFn,+ type JudgeItem,+} from '../../src/services/fable-harness.js';++/** Build a fake spawnClaude that records every call and returns a canned envelope. */+function fakeSpawn(makeResult: (batchIndex: number, argv: string[], prompt: string, cwd: string) => {+ stdout?: string;+ stderr?: string;+ code?: number | null;+ costUsd?: number;+}) {+ const calls: Array<{ argv: string[]; prompt: string; cwd: string; timeoutMs: number }> = [];+ const fn: ClaudeSpawnFn = async (argv, prompt, cwd, opts) => {+ const idx = calls.length;+ calls.push({ argv, prompt, cwd, timeoutMs: opts.timeoutMs });+ const r = makeResult(idx, argv, prompt, cwd);+ return { stdout: r.stdout ?? '', stderr: r.stderr ?? '', code: r.code ?? 0, costUsd: r.costUsd };+ };+ return { fn, calls };+}++/** Envelope shaped like `claude -p --output-format json` output. */+function envelope(verdicts: unknown[], costUsd = 0.4): string {+ return JSON.stringify({ type: 'result', result: JSON.stringify(verdicts), total_cost_usd: costUsd });+}++const items = (n: number): JudgeItem[] =>+ Array.from({ length: n }, (_, i) => ({ id: `t${i}`, task: `task ${i}`, output: `output ${i}` }));++describe('FableHarness β command construction', () => {+ it('builds argv with -p, model, json output, append-system-prompt and budget cap', () => {+ const h = new FableHarness({ maxBudgetUsd: 5, spawnClaude: async () => ({ stdout: '', stderr: '', code: 0 }) });+ const argv = h.buildArgv('JUDGE ROLE');+ expect(argv).toContain('-p');+ expect(argv).toEqual(expect.arrayContaining(['--model', 'claude-fable-5']));+ expect(argv).toEqual(expect.arrayContaining(['--output-format', 'json']));+ expect(argv).toEqual(expect.arrayContaining(['--append-system-prompt', 'JUDGE ROLE']));+ const capIdx = argv.indexOf('--max-budget-usd');+ expect(capIdx).toBeGreaterThan(-1);+ expect(Number(argv[capIdx + 1])).toBeCloseTo(5, 2);+ });++ it('runs claude from a FRESH TEMP cwd, never the project dir', async () => {+ const { fn, calls } = fakeSpawn(() => ({ stdout: envelope([{ id: 't0', resolved: true, confidence: 0.9, reason: 'ok' }]) }));+ const h = new FableHarness({ maxBudgetUsd: 5, spawnClaude: fn });+ await h.judgeBatch(items(1));+ expect(calls).toHaveLength(1);+ expect(calls[0].cwd).toContain('ruflo-fable');+ expect(calls[0].cwd).not.toBe(process.cwd());+ // Temp dir lives under the OS temp root (allow macOS /private symlink drift).+ expect(calls[0].cwd.includes(tmpdir()) || calls[0].cwd.includes('ruflo-fable')).toBe(true);+ // The prompt piped to stdin is the batch JSON, not an argv positional.+ expect(calls[0].prompt).toContain('task 0');+ expect(calls[0].argv).not.toContain('task 0');+ });+});++describe('FableHarness β off by default (zero spend)', () => {+ it('makes ZERO spawns when no budget cap is set', async () => {+ const { fn, calls } = fakeSpawn(() => ({ stdout: envelope([]) }));+ const h = new FableHarness({ spawnClaude: fn }); // no maxBudgetUsd+ expect(h.isEnabled()).toBe(false);+ const out = await h.judgeBatch(items(10));+ expect(out).toEqual([]);+ expect(calls).toHaveLength(0);+ expect(h.getSpentUsd()).toBe(0);+ });++ it('reflectFailures also spends nothing without a budget cap', async () => {+ const { fn, calls } = fakeSpawn(() => ({ stdout: envelope([]) }));+ const h = new FableHarness({ spawnClaude: fn });+ const out = await h.reflectFailures([{ id: 'a', task: 't', output: 'o' }]);+ expect(out).toEqual([]);+ expect(calls).toHaveLength(0);+ });+});++describe('FableHarness β batching & judging', () => {+ it('batches items into ceil(n / batchSize) calls', async () => {+ const { fn, calls } = fakeSpawn((idx, _argv, prompt) => {+ const batch = JSON.parse(prompt) as JudgeItem[];+ return { stdout: envelope(batch.map((b) => ({ id: b.id, resolved: true, confidence: 0.8, reason: 'ok' }))) };+ });+ const h = new FableHarness({ maxBudgetUsd: 100, batchSize: 4, spawnClaude: fn });+ const out = await h.judgeBatch(items(10)); // 10 / 4 = 3 batches+ expect(calls).toHaveLength(3);+ expect(out).toHaveLength(10);+ expect(out[0]).toMatchObject({ id: 't0', resolved: true });+ });++ it('normalizes verdicts (resolved boolean, clamped confidence)', async () => {+ const { fn } = fakeSpawn(() => ({+ stdout: envelope([+ { id: 't0', resolved: 'true', confidence: 1.7, reason: 'x' },+ { id: 't1', resolved: false, confidence: -3, reason: 'y' },+ ]),+ }));+ const h = new FableHarness({ maxBudgetUsd: 10, spawnClaude: fn });+ const out = await h.judgeBatch(items(2));+ expect(out[0]).toEqual({ id: 't0', resolved: true, confidence: 1, reason: 'x' });+ expect(out[1]).toEqual({ id: 't1', resolved: false, confidence: 0, reason: 'y' });+ });++ it('stops launching batches once measured spend reaches the cap', async () => {+ const { fn, calls } = fakeSpawn((idx, _argv, prompt) => {+ const batch = JSON.parse(prompt) as JudgeItem[];+ // Each batch reports $3 spend; cap is $5 β only the first batch should run.+ return { stdout: envelope(batch.map((b) => ({ id: b.id, resolved: true, confidence: 0.5, reason: 'ok' }))), costUsd: 3 };+ });+ const h = new FableHarness({ maxBudgetUsd: 5, batchSize: 2, spawnClaude: fn });+ const out = await h.judgeBatch(items(10)); // 5 batches if unbounded+ // batch1: spent 0<5 β run (spent 3); batch2: spent 3<5 β run (spent 6);+ // batch3: spent 6>=5 β stop. So exactly 2 batches run, covering 4 items.+ expect(calls.length).toBe(2);+ expect(out.length).toBe(4);+ expect(h.getSpentUsd()).toBeCloseTo(6, 2);+ });+});++describe('FableHarness β reflectFailures', () => {+ it('returns parsed reflection results', async () => {+ const { fn } = fakeSpawn(() => ({+ stdout: envelope([+ { id: 'a', failureClass: 'wrong-file', diagnosis: 'edited the wrong module', mutationHint: 'target foo.ts' },+ ]),+ }));+ const h = new FableHarness({ maxBudgetUsd: 10, spawnClaude: fn });+ const out = await h.reflectFailures([{ id: 'a', task: 't', output: 'o', failureHint: 'tests red' }]);+ expect(out).toEqual([+ { id: 'a', failureClass: 'wrong-file', diagnosis: 'edited the wrong module', mutationHint: 'target foo.ts' },+ ]);+ });+});++describe('extractVerdictArray', () => {+ it('parses an enveloped result string', () => {+ const arr = extractVerdictArray(envelope([{ id: 'x', resolved: true }]));+ expect(arr).toEqual([{ id: 'x', resolved: true }]);+ });+ it('parses a bare JSON array', () => {+ expect(extractVerdictArray('[{"id":"x"}]')).toEqual([{ id: 'x' }]);+ });+ it('parses a fenced ```json array inside a result string', () => {+ const env = JSON.stringify({ result: '```json\n[{"id":"y"}]\n```' });+ expect(extractVerdictArray(env)).toEqual([{ id: 'y' }]);+ });+ it('returns [] on garbage', () => {+ expect(extractVerdictArray('not json at all')).toEqual([]);+ expect(extractVerdictArray('')).toEqual([]);+ });+});++describe('cost model', () => {+ it('estimateFableCostUsd amortizes per item', () => {+ expect(estimateFableCostUsd(0)).toBe(0);+ expect(estimateFableCostUsd(20)).toBeCloseTo(20 * FABLE_COST_MODEL.perItemBatchedUsd, 4);+ });+ it('parseCostFromEnvelope reads total_cost_usd', () => {+ expect(parseCostFromEnvelope(envelope([], 1.23)) ?? 0).toBeCloseTo(1.23, 2);+ expect(parseCostFromEnvelope('garbage')).toBeUndefined();+ });+ it('exposes the measured cost anchors', () => {+ expect(FABLE_COST_MODEL.perCallProjectCwdUsd).toBeGreaterThan(FABLE_COST_MODEL.perCallCleanCwdUsd);+ expect(FABLE_COST_MODEL.model).toBe('claude-fable-5');+ });+});++// ββ Optional live smoke β human-run only, never in CI βββββββββββββββββββββ+const LIVE = process.env.RUFLO_FABLE_LIVE === '1';+(LIVE ? describe : describe.skip)('FableHarness β LIVE smoke (RUFLO_FABLE_LIVE=1)', () => {+ it('judges a trivial item against the real Fable CLI', async () => {+ const h = new FableHarness({ maxBudgetUsd: 0.5 }); // real spawnClaude+ const out = await h.judgeBatch([+ { id: 'live-1', task: 'Return the number 4', output: '4' },+ ]);+ expect(Array.isArray(out)).toBe(true);+ if (out.length > 0) expect(typeof out[0].resolved).toBe('boolean');+ }, 120_000);+});diff --git a/v3/@claude-flow/cli/__tests__/swarm-memory-branches.test.ts b/v3/@claude-flow/cli/__tests__/swarm-memory-branches.test.tsnew file mode 100644index 0000000000..07e6a949c5--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/swarm-memory-branches.test.ts@@ -0,0 +1,174 @@+/**+ * Tests for the SwarmMemoryBranches service (per-agent COW memory).+ *+ * Two surfaces, mirroring agenticow-tools.test.ts:+ * 1. HAPPY PATH β agenticow installed: a real branch β ingest β promote /+ * discard lifecycle against a temp .rvf, asserting the 162-byte branch,+ * isolation, and that promote merges edits while discard throws them away.+ * 2. DEGRADED / KILL-SWITCH PATH β always runs: the service must return+ * `{degraded:true}` (no throw) when agenticow is absent or when+ * CLAUDE_FLOW_NO_COW_MEMORY=1, and promote/discard on an unknown agent+ * must be pure-fs no-ops. This is the load-bearing architectural rule+ * (zero hard runtime dep, operator kill switch).+ */+import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'vitest';+import { mkdtempSync, rmSync, existsSync, statSync, readdirSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';++import {+ SwarmMemoryBranches,+ cowMemoryEnabled,+ COW_KILL_SWITCH_ENV,+} from '../src/services/swarm-memory-branches.js';+import { agenticowTools } from '../src/mcp-tools/agenticow-tools.js';++function findTool(name: string) {+ const t = agenticowTools.find(t => t.name === name);+ if (!t) throw new Error(`tool not found: ${name}`);+ return t;+}++function dirBytes(p: string): number {+ if (!existsSync(p)) return 0;+ const st = statSync(p);+ if (st.isFile()) return st.size;+ let total = 0;+ for (const e of readdirSync(p)) total += dirBytes(join(p, e));+ return total;+}++const v = (s: number) => Array.from({ length: 8 }, (_, i) => Math.sin(s + i));++// Detect agenticow availability before the `it.skipIf(...)` calls evaluate.+let havePkg = false;+try { await import('agenticow'); havePkg = true; } catch { havePkg = false; }++describe('SwarmMemoryBranches', () => {+ let workdir: string;+ let registryPath: string;++ beforeAll(() => {+ workdir = mkdtempSync(join(tmpdir(), 'acow-swarm-'));+ registryPath = join(workdir, 'registry.json');+ });++ afterAll(() => {+ try { rmSync(workdir, { recursive: true, force: true }); } catch { /* ignore */ }+ });++ beforeEach(() => {+ delete process.env[COW_KILL_SWITCH_ENV];+ });++ // ---- always-on contract tests --------------------------------------------++ it('cowMemoryEnabled honors the kill switch env var', () => {+ delete process.env[COW_KILL_SWITCH_ENV];+ expect(cowMemoryEnabled()).toBe(true);+ process.env[COW_KILL_SWITCH_ENV] = '1';+ expect(cowMemoryEnabled()).toBe(false);+ delete process.env[COW_KILL_SWITCH_ENV];+ });++ it('branchForAgent is a no-op when the kill switch is set', async () => {+ process.env[COW_KILL_SWITCH_ENV] = '1';+ const svc = new SwarmMemoryBranches(registryPath);+ const r = await svc.branchForAgent(join(workdir, 'ks-base.rvf'), 'agent-ks', { dimension: 8 });+ expect(r.success).toBe(true);+ expect(r.degraded).toBe(true);+ expect(r.reason).toBe('cow-memory-disabled');+ expect(r.branchPath).toBeUndefined();+ expect(svc.getBranch('agent-ks')).toBeUndefined();+ });++ it.skipIf(havePkg)('branchForAgent degrades when agenticow is absent', async () => {+ const svc = new SwarmMemoryBranches(registryPath);+ const r = await svc.branchForAgent(join(workdir, 'no-pkg-base.rvf'), 'agent-nopkg', { dimension: 8 });+ expect(r.success).toBe(true);+ expect(r.degraded).toBe(true);+ expect(r.reason).toBe('agenticow-not-found');+ expect(svc.getBranch('agent-nopkg')).toBeUndefined();+ });++ it('promoteAgent / discardAgent are no-ops for an unknown agent (pure fs, no agenticow)', async () => {+ const svc = new SwarmMemoryBranches(registryPath);+ const p = await svc.promoteAgent('never-spawned');+ expect(p.success).toBe(true);+ expect(p.promoted).toBe(false);+ expect(p.reason).toBe('no-branch');++ const d = await svc.discardAgent('never-spawned');+ expect(d.success).toBe(true);+ expect(d.discarded).toBe(false);+ expect(d.reason).toBe('no-branch');+ });++ // ---- happy-path lifecycle (real package) ---------------------------------++ it.skipIf(!havePkg)('branch β ingest β promote merges the agent\'s edits into the shared base', async () => {+ const svc = new SwarmMemoryBranches(registryPath);+ const ingest = findTool('agenticow_ingest');+ const query = findTool('agenticow_query');+ const base = join(workdir, 'promote-base.rvf');+ const agentId = 'agent-promote-1';++ // Seed the shared base with one vector, then fork a per-agent branch.+ await ingest.handler({ path: base, records: [{ id: 1, vector: v(1), text: 'base-seed' }], dimension: 8 });+ const br = await svc.branchForAgent(base, agentId, { dimension: 8 });+ expect(br.degraded).toBeUndefined();+ expect(br.branchPath).toBeDefined();+ expect(existsSync(br.branchPath!)).toBe(true);+ // The 162-byte win is the whole point β a fork must NOT be a full copy.+ expect(dirBytes(br.branchPath!)).toBeLessThan(4096);+ expect(svc.getBranch(agentId)?.branchPath).toBe(br.branchPath);++ // Agent writes into its OWN branch (isolated from base).+ await ingest.handler({ path: br.branchPath!, records: [{ id: 99, vector: v(9), text: 'agent-edit' }] });++ // Base does not see the branch-only vector before promote.+ const baseBefore = await query.handler({ path: base, vector: v(9), k: 5 }) as any;+ expect(baseBefore.hits.some((h: any) => h.id === 99)).toBe(false);++ // Promote β merge the agent's edits back; branch file removed, registry cleared.+ const pr = await svc.promoteAgent(agentId);+ expect(pr.success).toBe(true);+ expect(pr.promoted).toBe(true);+ expect(svc.getBranch(agentId)).toBeUndefined();+ expect(existsSync(br.branchPath!)).toBe(false);++ // Base now sees the promoted vector.+ const baseAfter = await query.handler({ path: base, vector: v(9), k: 5 }) as any;+ expect(baseAfter.hits.some((h: any) => h.id === 99)).toBe(true);+ });++ it.skipIf(!havePkg)('discardAgent throws the branch away without touching base', async () => {+ const svc = new SwarmMemoryBranches(registryPath);+ const ingest = findTool('agenticow_ingest');+ const query = findTool('agenticow_query');+ const base = join(workdir, 'discard-base.rvf');+ const agentId = 'agent-discard-1';++ await ingest.handler({ path: base, records: [{ id: 1, vector: v(1), text: 'keep' }], dimension: 8 });+ const br = await svc.branchForAgent(base, agentId, { dimension: 8 });+ await ingest.handler({ path: br.branchPath!, records: [{ id: 77, vector: v(7), text: 'doomed' }] });++ const d = await svc.discardAgent(agentId);+ expect(d.discarded).toBe(true);+ expect(existsSync(br.branchPath!)).toBe(false);+ expect(svc.getBranch(agentId)).toBeUndefined();++ // The discarded edit never reached base.+ const baseAfter = await query.handler({ path: base, vector: v(7), k: 5 }) as any;+ expect(baseAfter.hits.some((h: any) => h.id === 77)).toBe(false);+ });++ it.skipIf(!havePkg)('branchForAgent is idempotent for the same agent', async () => {+ const svc = new SwarmMemoryBranches(registryPath);+ const base = join(workdir, 'idem-base.rvf');+ const agentId = 'agent-idem-1';+ const first = await svc.branchForAgent(base, agentId, { dimension: 8 });+ const second = await svc.branchForAgent(base, agentId, { dimension: 8 });+ expect(second.branchPath).toBe(first.branchPath);+ });+});diff --git a/v3/@claude-flow/cli/__tests__/weft-export.test.ts b/v3/@claude-flow/cli/__tests__/weft-export.test.tsnew file mode 100644index 0000000000..66033da4df--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/weft-export.test.ts@@ -0,0 +1,374 @@+/**+ * weft-export.test.ts β ADR-150 weight-eft slice.+ *+ * Covers:+ * 1. Archive-builder: ruflo run records β DarwinTrajectory[] mapping + the+ * honest resolved-proxy accounting.+ * 2. distill-export E2E: synthetic archive β weight-eft export produces+ * sft.jsonl / dpo.jsonl / export-report.json (weight-eft installed in the+ * worktree; skipped if the optional dep is genuinely absent).+ * 3. Degraded path: weight-eft absent (injected failing importer) β {degraded:true}.+ * 4. Remote-train: pure command construction (ssh/rsync/ruvllm argv) + dry-run+ * output. NEVER touches a live host β spawn is stubbed.+ */++import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { rmSync, mkdtempSync, mkdirSync, writeFileSync, existsSync, readFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++import {+ buildArchiveFromRecords,+ runExport,+ runPlan,+ buildRemoteTrainInvocation,+ runRemoteTrain,+ loadWeightEft,+ DEFAULT_BASE_MODEL,+ type DarwinTrajectory,+ type SpawnLike,+} from '../src/services/weight-eft.js';+import type { RunTranscriptRecord } from '../src/ruvector/run-transcript-recorder.js';+import {+ recordRunTranscript,+ readRunTranscripts,+ tierForModel,+ runTranscriptRecorderStatus,+ __resetRunTranscriptRecorderForTests,+} from '../src/ruvector/run-transcript-recorder.js';++// NOTE: the CLI command surface (neuralCommand) is intentionally NOT imported+// here β it pulls in `@claude-flow/cli-core/output`, whose built subpath is not+// resolvable under vitest in a fresh worktree (the same reason the repo's+// existing __tests__/commands.test.ts loads no tests in this env). We exercise+// the command's SERVICE layer (runExport β files on disk) directly, and the+// built-CLI command is smoke-tested out-of-band via `node dist β¦ neural distill`.++// --- fixtures ---------------------------------------------------------------++function rec(over: Partial<RunTranscriptRecord>): RunTranscriptRecord {+ return {+ v: 1,+ ts: new Date().toISOString(),+ instance_id: 'inst-1',+ task_hash: 'deadbeef',+ model: 'z-ai/glm-5.2',+ tier: 'cheap',+ resolved: true,+ resolved_source: 'api-success',+ messages: [+ { role: 'system', content: 'You are a coding agent.' },+ { role: 'user', content: 'Fix the null-deref in cache.ts' },+ { role: 'assistant', content: 'Here is the patch.' },+ ],+ model_patch: 'diff --git a/cache.ts b/cache.ts\n+ if (x) return;',+ sample: 0,+ source: 'agent-execute',+ ...over,+ };+}++/** A resolved + a failed sample on the SAME instance/model β enough for a DPO pair. */+function dpoPairRecords(): RunTranscriptRecord[] {+ return [+ rec({ instance_id: 'inst-dpo', sample: 0, resolved: true }),+ rec({+ instance_id: 'inst-dpo', sample: 1, resolved: false, model_patch: '',+ messages: [+ { role: 'system', content: 'You are a coding agent.' },+ { role: 'user', content: 'Fix the null-deref in cache.ts' },+ { role: 'assistant', content: 'I could not solve it.' },+ ],+ }),+ ];+}++let weftAvailable = false;+beforeEach(async () => { weftAvailable = (await loadWeightEft()) !== null; });++// --- 0. capture module: run-transcript recorder (opt-in) --------------------++describe('run-transcript-recorder (the capture path)', () => {+ let dir: string;+ let prevEnabled: string | undefined;+ let prevPath: string | undefined;+ beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), 'weft-cap-'));+ prevEnabled = process.env.CLAUDE_FLOW_RUN_TRANSCRIPTS;+ prevPath = process.env.CLAUDE_FLOW_RUN_TRANSCRIPTS_PATH;+ __resetRunTranscriptRecorderForTests();+ });+ afterEach(() => {+ if (prevEnabled === undefined) delete process.env.CLAUDE_FLOW_RUN_TRANSCRIPTS; else process.env.CLAUDE_FLOW_RUN_TRANSCRIPTS = prevEnabled;+ if (prevPath === undefined) delete process.env.CLAUDE_FLOW_RUN_TRANSCRIPTS_PATH; else process.env.CLAUDE_FLOW_RUN_TRANSCRIPTS_PATH = prevPath;+ __resetRunTranscriptRecorderForTests();+ rmSync(dir, { recursive: true, force: true });+ });++ it('is OFF by default β recordRunTranscript is a no-op (no file written)', () => {+ delete process.env.CLAUDE_FLOW_RUN_TRANSCRIPTS;+ const p = join(dir, 'run-transcripts.jsonl');+ process.env.CLAUDE_FLOW_RUN_TRANSCRIPTS_PATH = p;+ __resetRunTranscriptRecorderForTests();+ const r = recordRunTranscript({ task: 't', model: 'claude-haiku-4', tier: 'cheap', resolved: true, resolvedSource: 'api-success', messages: [{ role: 'user', content: 'hi' }] });+ expect(r.recorded).toBe(false);+ expect(existsSync(p)).toBe(false);+ });++ it('when enabled, writes a record that round-trips through readRunTranscripts', () => {+ const p = join(dir, 'run-transcripts.jsonl');+ process.env.CLAUDE_FLOW_RUN_TRANSCRIPTS = '1';+ process.env.CLAUDE_FLOW_RUN_TRANSCRIPTS_PATH = p;+ __resetRunTranscriptRecorderForTests();+ const r = recordRunTranscript({+ task: 'Fix bug', model: 'claude-haiku-4', tier: 'cheap', resolved: true,+ resolvedSource: 'output-verifier', messages: [{ role: 'user', content: 'Fix bug' }],+ modelPatch: 'diff', source: 'agent-execute',+ });+ expect(r.recorded).toBe(true);+ expect(r.instanceId).toBe(`run-${r.taskHash}`);+ const { records, malformed } = readRunTranscripts(p);+ expect(malformed).toBe(0);+ expect(records).toHaveLength(1);+ expect(records[0]).toMatchObject({ v: 1, model: 'claude-haiku-4', tier: 'cheap', resolved: true, resolved_source: 'output-verifier', model_patch: 'diff' });+ expect(runTranscriptRecorderStatus().enabled).toBe(true);+ });++ it('tierForModel maps haikuβcheap, sonnet/opusβfrontier', () => {+ expect(tierForModel('claude-haiku-4')).toBe('cheap');+ expect(tierForModel('claude-sonnet-4')).toBe('frontier');+ expect(tierForModel('anthropic/claude-opus')).toBe('frontier');+ expect(tierForModel(undefined)).toBe('frontier');+ });+});++// --- 1. archive-builder -----------------------------------------------------++describe('buildArchiveFromRecords', () => {+ it('maps ruflo run records to DarwinTrajectory[] preserving the contract fields', () => {+ const { trajectories, stats } = buildArchiveFromRecords([+ rec({ instance_id: 'a', tier: 'cheap', resolved: true }),+ rec({ instance_id: 'b', tier: 'frontier', resolved: false, model: 'anthropic/claude-opus' }),+ ]);+ expect(trajectories).toHaveLength(2);+ const a = trajectories[0];+ expect(a).toMatchObject({+ instance_id: 'a', model: 'z-ai/glm-5.2', tier: 'cheap', resolved: true, sample: 0,+ });+ expect(a.messages[0].role).toBe('system');+ expect(a.model_patch).toContain('diff --git');+ expect(trajectories[1]).toMatchObject({ instance_id: 'b', tier: 'frontier', resolved: false });+ expect(stats.total).toBe(2);+ expect(stats.resolved).toBe(1);+ expect(stats.byTier).toEqual({ cheap: 1, frontier: 1 });+ });++ it('skips records missing an instance_id or messages (never throws)', () => {+ const { trajectories, stats } = buildArchiveFromRecords([+ rec({ instance_id: 'ok' }),+ rec({ instance_id: '', messages: [] }),+ rec({ instance_id: 'empty', messages: [] }),+ ]);+ expect(trajectories.map((t) => t.instance_id)).toEqual(['ok']);+ expect(stats.skipped).toBe(2);+ });++ it('tallies resolved provenance and emits an honest PROXY note (no gold oracle)', () => {+ const { stats, proxyNote } = buildArchiveFromRecords([+ rec({ instance_id: 'a', resolved_source: 'api-success' }),+ rec({ instance_id: 'b', resolved_source: 'output-verifier' }),+ ]);+ expect(stats.byResolvedSource).toEqual({ 'api-success': 1, 'output-verifier': 1 });+ expect(proxyNote).toMatch(/PROXY/);+ expect(proxyNote).toMatch(/no SWE-bench gold oracle/i);+ });+});++// --- 2. distill-export E2E (real weight-eft) --------------------------------++describe('runExport (E2E against real weight-eft)', () => {+ it('produces SFT + DPO jsonl and a guard report from a synthetic archive', async () => {+ if (!weftAvailable) { console.warn('weight-eft not installed β skipping E2E'); return; }+ const { trajectories } = buildArchiveFromRecords(dpoPairRecords());+ const res = await runExport({ archive: trajectories, evalHoldout: [] });+ expect(res.degraded).toBe(false);+ if (res.degraded) return;+ // SFT: at least the resolved trajectory becomes a training row.+ expect(res.sftRows).toBeGreaterThanOrEqual(1);+ expect(res.sftJsonl.trim().split('\n').length).toBe(res.sftRows);+ expect(JSON.parse(res.sftJsonl.trim().split('\n')[0])).toHaveProperty('messages');+ // DPO: the resolved+failed pair on the same instance yields a preference row.+ expect(res.dpoRows).toBeGreaterThanOrEqual(1);+ const dpo0 = JSON.parse(res.dpoJsonl.trim().split('\n')[0]);+ expect(dpo0).toHaveProperty('chosen');+ expect(dpo0).toHaveProperty('rejected');+ // Report carries the guard accounting.+ expect(res.report).toMatchObject({ sftRows: res.sftRows, dpoRows: res.dpoRows });+ expect(res.report).toHaveProperty('droppedRewardHacked');+ expect(res.report).toHaveProperty('excludedByHoldout');+ });++ it('honors the contamination guard: holdout instances are excluded', async () => {+ if (!weftAvailable) return;+ const { trajectories } = buildArchiveFromRecords([rec({ instance_id: 'held' }), rec({ instance_id: 'kept', task_hash: 'x' })]);+ const res = await runExport({ archive: trajectories, evalHoldout: ['held'] });+ expect(res.degraded).toBe(false);+ if (res.degraded) return;+ expect(res.report.excludedByHoldout).toBe(1);+ expect(res.report.sftInstanceIds).not.toContain('held');+ });++ it('runPlan emits a two-stage GPU plan with a ruvllm command ($0 dry-run)', async () => {+ if (!weftAvailable) return;+ const res = await runPlan({ sftPath: '/tmp/sft.jsonl', dpoPath: '/tmp/dpo.jsonl' });+ expect(res.degraded).toBe(false);+ if (res.degraded) return;+ expect(res.base).toEqual(DEFAULT_BASE_MODEL);+ expect(res.sft.command).toMatch(/ruvllm|microlora|sft/i);+ expect(res.dpo.command).toBeTruthy();+ });+});++// --- 2b. export β files on disk (the command's service path) ----------------++describe('distill-export writes sft.jsonl / dpo.jsonl / export-report.json', () => {+ let dir: string;+ beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'weft-cli-')); });+ afterEach(() => { rmSync(dir, { recursive: true, force: true }); });++ it('persists the exact artifacts the CLI `neural distill export` emits', async () => {+ if (!weftAvailable) return;+ const { trajectories, stats, proxyNote } = buildArchiveFromRecords(dpoPairRecords());+ const res = await runExport({ archive: trajectories, evalHoldout: [] });+ expect(res.degraded).toBe(false);+ if (res.degraded) return;++ // Mirror the command's write path.+ const outDir = join(dir, 'out');+ mkdirSync(outDir, { recursive: true });+ writeFileSync(join(outDir, 'sft.jsonl'), res.sftJsonl);+ writeFileSync(join(outDir, 'dpo.jsonl'), res.dpoJsonl);+ writeFileSync(join(outDir, 'export-report.json'), JSON.stringify({ report: res.report, archiveStats: stats, proxyNote }, null, 2));++ expect(existsSync(join(outDir, 'sft.jsonl'))).toBe(true);+ expect(existsSync(join(outDir, 'dpo.jsonl'))).toBe(true);+ expect(existsSync(join(outDir, 'export-report.json'))).toBe(true);+ const report = JSON.parse(readFileSync(join(outDir, 'export-report.json'), 'utf8'));+ expect(report).toHaveProperty('report');+ expect(report.proxyNote).toMatch(/PROXY/);+ expect(readFileSync(join(outDir, 'sft.jsonl'), 'utf8').trim().length).toBeGreaterThan(0);+ });+});++// --- 3. degraded path (weight-eft absent) -----------------------------------++describe('graceful degradation (ADR-150)', () => {+ const failingImporter = async () => { throw new Error("Cannot find module '@metaharness/weight-eft'"); };++ it('runExport returns {degraded:true} when weight-eft cannot load', async () => {+ const { trajectories } = buildArchiveFromRecords([rec({})]);+ const res = await runExport({ archive: trajectories, importer: failingImporter });+ expect(res).toEqual({ degraded: true, reason: 'weight-eft-not-available' });+ });++ it('runPlan degrades without throwing', async () => {+ const res = await runPlan({ sftPath: 'a', dpoPath: 'b', importer: failingImporter });+ expect(res.degraded).toBe(true);+ });++ it('loadWeightEft returns null (not throw) on a broken import', async () => {+ expect(await loadWeightEft(failingImporter)).toBeNull();+ });+});++// --- 4. remote-train construction + dry-run ---------------------------------++describe('buildRemoteTrainInvocation (pure command construction)', () => {+ it('builds correct ssh/rsync/ruvllm argv for host + model + paths', () => {+ const plan = buildRemoteTrainInvocation({+ host: 'gpu-box', base: 'Qwen/Qwen2.5-Coder-7B-Instruct',+ sftPath: '/local/sft.jsonl', dpoPath: '/local/dpo.jsonl',+ adapterDir: '/local/adapters', sshUser: 'ruv', sshPort: 2222,+ runId: 'run42', adapterPrefix: 'ruflo-weft',+ });+ // ssh reachability probe targets user@host on the chosen port+ expect(plan.preflight[0].argv).toEqual(['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=8', '-p', '2222', 'ruv@gpu-box', 'true']);+ // rsync sends the LOCAL sft file up to the remote workdir+ const rsyncSft = plan.steps.find((s) => s.label === 'rsync sft up')!;+ expect(rsyncSft.argv[0]).toBe('rsync');+ expect(rsyncSft.argv).toContain('/local/sft.jsonl');+ expect(rsyncSft.argv[rsyncSft.argv.length - 1]).toContain('ruv@gpu-box:');+ // ruvllm sft uses the base model + writes an sft adapter+ const sftStep = plan.steps.find((s) => s.label.startsWith('ruvllm sft'))!;+ expect(sftStep.argv.join(' ')).toContain('ruvllm microlora sft --base Qwen/Qwen2.5-Coder-7B-Instruct --data sft.jsonl');+ expect(sftStep.argv.join(' ')).toContain('ruflo-weft-run42-sft');+ // ruvllm dpo initializes from the sft adapter (on-policy)+ const dpoStep = plan.steps.find((s) => s.label.startsWith('ruvllm dpo'))!;+ expect(dpoStep.argv.join(' ')).toContain('ruvllm microlora dpo --base Qwen/Qwen2.5-Coder-7B-Instruct --init-from ruflo-weft-run42-sft');+ // adapter fetched back into the local dir+ const back = plan.steps.find((s) => s.label === 'rsync adapter back')!;+ expect(back.argv[back.argv.length - 1]).toContain('/local/adapters/ruflo-weft-run42-dpo');+ expect(plan.humanCommands.length).toBe(plan.preflight.length + plan.steps.length);+ });++ it('defaults host param from args and uses port 22 + default base', () => {+ const plan = buildRemoteTrainInvocation({ host: 'h', sftPath: 's', dpoPath: 'd', runId: 'r' });+ expect(plan.base).toBe(DEFAULT_BASE_MODEL.id);+ expect(plan.preflight[0].argv).toContain('-p');+ expect(plan.preflight[0].argv[plan.preflight[0].argv.indexOf('-p') + 1]).toBe('22');+ });+});++describe('runRemoteTrain (spend-gated; spawn stubbed β never touches a live host)', () => {+ const okSpawn = (): SpawnLike => ({ status: 0, stdout: 'ok', stderr: '' });+ const args = { host: 'gpu-box', sftPath: '/l/sft.jsonl', dpoPath: '/l/dpo.jsonl', runId: 'r1' };++ it('BARE dry-run is fully OFFLINE β contacts nothing (no implicit remote exec)', async () => {+ const spawned: string[] = [];+ const spawn = (cmd: string, argv: string[]): SpawnLike => { spawned.push([cmd, ...argv].join(' ')); return okSpawn(); };+ const res = await runRemoteTrain({ ...args, spawn });+ expect(res.degraded).toBe(false);+ if (res.degraded) return;+ expect(res.mode).toBe('dry-run');+ expect(res.steps).toBeUndefined();+ expect(res.plan.humanCommands.some((c) => c.includes('ruvllm microlora sft'))).toBe(true);+ // NOTHING spawned β not even a reachability ssh (adversarial RC hardening).+ expect(spawned).toEqual([]);+ expect(res.reason).toMatch(/offline/i);+ });++ it('--preflight opts into the read-only probes (still no training)', async () => {+ const spawned: string[] = [];+ const spawn = (cmd: string, argv: string[]): SpawnLike => { spawned.push([cmd, ...argv].join(' ')); return okSpawn(); };+ const res = await runRemoteTrain({ ...args, preflight: true, spawn });+ expect(res.degraded).toBe(false);+ if (res.degraded) return;+ expect(res.mode).toBe('dry-run');+ // the 3 read-only preflight probes ran; no rsync / ruvllm training+ expect(spawned.length).toBeGreaterThan(0);+ expect(spawned.every((c) => c.startsWith('ssh'))).toBe(true);+ expect(spawned.some((c) => c.includes('rsync') || c.includes('microlora'))).toBe(false);+ });++ it('--execute WITHOUT --yes is refused (real GPU spend needs the second gate)', async () => {+ const res = await runRemoteTrain({ ...args, execute: true, spawn: okSpawn });+ expect(res.degraded).toBe(false);+ if (res.degraded) return;+ expect(res.mode).toBe('refused');+ expect(res.reason).toMatch(/--yes/);+ });++ it('--execute --yes on an UNREACHABLE host aborts before any data transfer', async () => {+ // ssh reachability probe fails β preflight-failed, no rsync/training+ const spawned: string[] = [];+ const spawn = (cmd: string, argv: string[]): SpawnLike => {+ spawned.push([cmd, ...argv].join(' '));+ return { status: 255, stdout: '', stderr: 'ssh: connect timed out' };+ };+ const res = await runRemoteTrain({ ...args, execute: true, yes: true, spawn });+ expect(res.degraded).toBe(false);+ if (res.degraded) return;+ expect(res.mode).toBe('preflight-failed');+ expect(spawned.some((c) => c.includes('rsync') || c.includes('microlora'))).toBe(false);+ });+});diff --git a/v3/@claude-flow/cli/package-lock.json b/v3/@claude-flow/cli/package-lock.jsonnew file mode 100644index 0000000000..31ebc05226--- /dev/null+++ b/v3/@claude-flow/cli/package-lock.json@@ -0,0 +1,1680 @@+{+ "name": "@claude-flow/cli",+ "version": "3.20.0",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "@claude-flow/cli",+ "version": "3.20.0",+ "hasInstallScript": true,+ "license": "MIT",+ "dependencies": {+ "@claude-flow/cli-core": "3.7.0-alpha.5",+ "@claude-flow/mcp": "3.0.0-alpha.8",+ "@claude-flow/neural": "3.0.0-alpha.9",+ "@claude-flow/shared": "3.0.0-alpha.7",+ "@noble/ed25519": "2.3.0",+ "@ruvector/rabitq-wasm": "0.1.0",+ "agenticow": "^0.2.4",+ "semver": "7.7.3",+ "yaml": "^2.8.0"+ },+ "bin": {+ "claude-flow": "bin/cli.js",+ "claude-flow-mcp": "bin/mcp-server.js",+ "cli": "bin/cli.js"+ },+ "devDependencies": {+ "typescript": "^5.3.0",+ "vitest": "^4.1.0"+ },+ "optionalDependencies": {+ "@claude-flow/aidefence": "^3.0.2",+ "@claude-flow/codex": "^3.0.0-alpha.8",+ "@claude-flow/embeddings": "^3.0.0-alpha.18",+ "@claude-flow/guidance": "^3.0.0-alpha.1",+ "@claude-flow/memory": "^3.0.0-alpha.21",+ "@claude-flow/plugin-gastown-bridge": "^0.1.3",+ "@claude-flow/security": "^3.0.0-alpha.10",+ "@metaharness/darwin": "~0.8.0",+ "@metaharness/kernel": "~0.1.2",+ "@metaharness/redblue": "~0.1.4",+ "@metaharness/router": "~0.3.2",+ "@ruvector/attention": "^0.1.32",+ "@ruvector/attention-darwin-arm64": "0.1.32",+ "@ruvector/diskann": "^0.1.0",+ "@ruvector/learning-wasm": "^0.1.29",+ "@ruvector/router": "^0.1.30",+ "@ruvector/ruvllm-wasm": "^2.0.2",+ "@ruvector/rvagent-wasm": "^0.1.0",+ "@ruvector/sona": "^0.1.6",+ "@ruvector/tiny-dancer": "^0.1.22",+ "agentbbs": "~0.1.0",+ "agentdb": "^3.0.0-alpha.17",+ "agentic-flow": "^3.0.0-alpha.1",+ "agenticow": "^0.2.4",+ "metaharness": "~0.2.8",+ "ruvector": "^0.2.27"+ }+ },+ "../../node_modules/.pnpm/@[email protected][email protected]/node_modules/@claude-flow/aidefence": {+ "version": "3.0.3",+ "license": "MIT",+ "optional": true,+ "devDependencies": {+ "@types/node": "^20.10.0",+ "typescript": "^5.3.3",+ "vitest": "^4.0.16"+ },+ "engines": {+ "node": ">=18.0.0"+ },+ "peerDependencies": {+ "agentdb": ">=2.0.0-alpha.1"+ },+ "peerDependenciesMeta": {+ "agentdb": {+ "optional": true+ }+ }+ },+ "../../node_modules/.pnpm/@[email protected]_@[email protected]/node_modules/@claude-flow/codex": {+ "version": "3.0.0-alpha.12",+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "@iarna/toml": "^2.2.5",+ "chalk": "^5.3.0",+ "commander": "^12.0.0",+ "fs-extra": "^11.2.0",+ "inquirer": "^9.2.0",+ "toml": "^3.0.0",+ "yaml": "^2.4.0"+ },+ "bin": {+ "claude-flow-codex": "dist/cli.js"+ },+ "devDependencies": {+ "@types/fs-extra": "^11.0.4",+ "@types/node": "^20.0.0",+ "eslint": "^8.57.0",+ "typescript": "^5.4.0",+ "vitest": "^4.0.16"+ },+ "engines": {+ "node": ">=18"+ },+ "peerDependencies": {+ "@claude-flow/cli": "^3.0.0-alpha.1"+ },+ "peerDependenciesMeta": {+ "@claude-flow/cli": {+ "optional": true+ }+ }+ },+ "../../node_modules/.pnpm/@[email protected]_@[email protected]_@ruvector+attention@_kjdwodggaqxawad5ojmmgbga4y/node_modules/@claude-flow/embeddings": {+ "version": "3.0.0-alpha.45",+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "@xenova/transformers": "^2.17.0",+ "sql.js": "^1.13.0"+ },+ "devDependencies": {+ "@types/node": "^20.10.0",+ "typescript": "^5.3.0",+ "vitest": "^4.0.16"+ },+ "engines": {+ "node": ">=20.0.0"+ },+ "peerDependencies": {+ "@claude-flow/shared": "^3.0.0-alpha.1",+ "@huggingface/transformers": "^4.0.0",+ "@ruvector/attention": "^2.2.2",+ "@ruvector/core": "^0.1.31",+ "@ruvector/diskann": "^0.1.0",+ "@ruvector/rabitq-wasm": "^0.1.0",+ "agentic-flow": "^2.0.0",+ "ruvector-onnx-embeddings-wasm": "^0.1.2"+ },+ "peerDependenciesMeta": {+ "@huggingface/transformers": {+ "optional": true+ },+ "@ruvector/attention": {+ "optional": true+ },+ "@ruvector/core": {+ "optional": true+ },+ "@ruvector/diskann": {+ "optional": true+ },+ "@ruvector/rabitq-wasm": {+ "optional": true+ },+ "agentic-flow": {+ "optional": true+ },+ "ruvector-onnx-embeddings-wasm": {+ "optional": true+ }+ }+ },+ "../../node_modules/.pnpm/@[email protected]/node_modules/@claude-flow/mcp": {+ "version": "3.0.0-alpha.8",+ "dependencies": {+ "ajv": "^8.12.0",+ "cors": "^2.8.5",+ "express": "^4.18.2",+ "helmet": "^7.1.0",+ "ws": "^8.14.2"+ },+ "devDependencies": {+ "@types/cors": "^2.8.17",+ "@types/express": "^4.17.21",+ "@types/ws": "^8.5.10",+ "vitest": "^4.0.16"+ }+ },+ "../../node_modules/.pnpm/@[email protected]_@claude-flow+memory@@claude-flow+memory/node_modules/@claude-flow/plugin-gastown-bridge": {+ "version": "0.1.3",+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "@iarna/toml": "^2.2.5",+ "uuid": "^9.0.0",+ "zod": "^3.22.0"+ },+ "devDependencies": {+ "@size-limit/preset-small-lib": "^11.0.0",+ "@types/node": "^20.0.0",+ "@types/uuid": "^9.0.0",+ "esbuild": "^0.20.0",+ "size-limit": "^11.0.0",+ "tsup": "^8.0.0",+ "tsx": "^4.0.0",+ "typescript": "^5.4.0",+ "vitest": "^1.0.0"+ },+ "engines": {+ "node": ">=20.0.0"+ },+ "peerDependencies": {+ "@claude-flow/memory": ">=3.0.0-alpha.1"+ },+ "peerDependenciesMeta": {+ "@claude-flow/memory": {+ "optional": true+ }+ }+ },+ "../../node_modules/.pnpm/@[email protected]/node_modules/@claude-flow/shared": {+ "version": "3.0.0-alpha.7",+ "dependencies": {+ "sql.js": "^1.10.3"+ },+ "devDependencies": {+ "@types/cors": "^2.8.17",+ "@types/express": "^4.17.21",+ "@types/node": "^20.0.0",+ "@types/sql.js": "^1.4.9",+ "@types/ws": "^8.5.10",+ "cors": "^2.8.5",+ "express": "^4.21.0",+ "helmet": "^7.1.0",+ "vitest": "^4.0.16",+ "ws": "^8.16.0",+ "zod": "^3.22.4"+ }+ },+ "../../node_modules/.pnpm/@[email protected]/node_modules/@metaharness/darwin": {+ "version": "0.8.0",+ "license": "MIT",+ "optional": true,+ "bin": {+ "metaharness-darwin": "dist/cli.js"+ },+ "devDependencies": {+ "typescript": "^5.4.0",+ "vitest": "^2.0.0"+ },+ "engines": {+ "node": ">=20.0.0"+ }+ },+ "../../node_modules/.pnpm/@[email protected]/node_modules/@metaharness/kernel": {+ "version": "0.1.2",+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "@ruvector/emergent-time": "^0.1.0"+ },+ "engines": {+ "node": ">=20.0.0"+ },+ "optionalDependencies": {+ "@metaharness/kernel-darwin-arm64": "0.1.0",+ "@metaharness/kernel-darwin-x64": "0.1.0",+ "@metaharness/kernel-linux-arm64-gnu": "0.1.0",+ "@metaharness/kernel-linux-x64-gnu": "0.1.0",+ "@metaharness/kernel-win32-x64-msvc": "0.1.0"+ },+ "peerDependencies": {+ "@ruvector/rvf": "^0.2.0"+ },+ "peerDependenciesMeta": {+ "@ruvector/rvf": {+ "optional": true+ }+ }+ },+ "../../node_modules/.pnpm/@[email protected]/node_modules/@metaharness/redblue": {+ "version": "0.1.4",+ "license": "MIT",+ "optional": true,+ "bin": {+ "metaharness-redblue": "dist/cli/index.js",+ "redblue": "dist/cli/index.js"+ },+ "devDependencies": {+ "typescript": "^5.4.0",+ "vitest": "^2.0.0"+ },+ "engines": {+ "node": ">=20.0.0"+ }+ },+ "../../node_modules/.pnpm/@[email protected]_@[email protected]/node_modules/@metaharness/router": {+ "version": "0.3.2",+ "license": "MIT",+ "optional": true,+ "devDependencies": {+ "@ruvector/tiny-dancer": "^0.1.21",+ "typescript": "^5.4.0",+ "vitest": "^2.0.0"+ },+ "engines": {+ "node": ">=20.0.0"+ },+ "peerDependencies": {+ "@ruvector/tiny-dancer": "^0.1.21"+ },+ "peerDependenciesMeta": {+ "@ruvector/tiny-dancer": {+ "optional": true+ }+ }+ },+ "../../node_modules/.pnpm/@[email protected]/node_modules/@noble/ed25519": {+ "version": "2.3.0",+ "license": "MIT",+ "devDependencies": {+ "@noble/hashes": "2.0.0-beta.1",+ "@paulmillr/jsbt": "0.4.1",+ "@types/node": "24.0.0",+ "fast-check": "4.1.1",+ "micro-bmark": "0.4.2",+ "micro-should": "0.5.3",+ "prettier": "3.5.3",+ "typescript": "5.8.3"+ },+ "funding": {+ "url": "https://paulmillr.com/funding/"+ }+ },+ "../../node_modules/.pnpm/@[email protected]/node_modules/@ruvector/attention-darwin-arm64": {+ "version": "0.1.32",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ]+ },+ "../../node_modules/.pnpm/@[email protected]/node_modules/@ruvector/attention": {+ "version": "0.1.32",+ "license": "MIT",+ "optional": true,+ "optionalDependencies": {+ "@ruvector/attention-darwin-arm64": "0.1.32",+ "@ruvector/attention-darwin-x64": "0.1.32",+ "@ruvector/attention-linux-arm64-gnu": "0.1.32",+ "@ruvector/attention-linux-x64-gnu": "0.1.32",+ "@ruvector/attention-win32-x64-msvc": "0.1.32"+ }+ },+ "../../node_modules/.pnpm/@[email protected]/node_modules/@ruvector/diskann": {+ "version": "0.1.0",+ "license": "MIT",+ "optional": true,+ "devDependencies": {+ "@napi-rs/cli": "^2.18.0"+ },+ "engines": {+ "node": ">=18.0.0"+ },+ "optionalDependencies": {+ "@ruvector/diskann-darwin-arm64": "0.1.0",+ "@ruvector/diskann-darwin-x64": "0.1.0",+ "@ruvector/diskann-linux-arm64-gnu": "0.1.0",+ "@ruvector/diskann-linux-x64-gnu": "0.1.0",+ "@ruvector/diskann-win32-x64-msvc": "0.1.0"+ }+ },+ "../../node_modules/.pnpm/@[email protected]/node_modules/@ruvector/learning-wasm": {+ "version": "0.1.29",+ "license": "MIT OR Apache-2.0",+ "optional": true+ },+ "../../node_modules/.pnpm/@[email protected]/node_modules/@ruvector/rabitq-wasm": {+ "version": "0.1.0",+ "license": "MIT OR Apache-2.0"+ },+ "../../node_modules/.pnpm/@[email protected]/node_modules/@ruvector/router": {+ "version": "0.1.30",+ "license": "MIT",+ "optional": true,+ "devDependencies": {+ "@napi-rs/cli": "^2.18.0"+ },+ "engines": {+ "node": ">=18.0.0"+ },+ "optionalDependencies": {+ "@ruvector/router-darwin-arm64": "0.1.30",+ "@ruvector/router-darwin-x64": "0.1.30",+ "@ruvector/router-linux-arm64-gnu": "0.1.30",+ "@ruvector/router-linux-x64-gnu": "0.1.30",+ "@ruvector/router-win32-x64-msvc": "0.1.30"+ }+ },+ "../../node_modules/.pnpm/@[email protected]/node_modules/@ruvector/ruvllm-wasm": {+ "version": "2.0.2",+ "license": "MIT",+ "optional": true+ },+ "../../node_modules/.pnpm/@[email protected]/node_modules/@ruvector/rvagent-wasm": {+ "version": "0.1.0",+ "license": "MIT OR Apache-2.0",+ "optional": true+ },+ "../../node_modules/.pnpm/@[email protected]/node_modules/@ruvector/sona": {+ "version": "0.1.5",+ "license": "MIT OR Apache-2.0",+ "devDependencies": {+ "@napi-rs/cli": "^2.18.0"+ },+ "engines": {+ "node": ">= 16"+ },+ "optionalDependencies": {+ "@ruvector/sona-darwin-arm64": "0.1.5",+ "@ruvector/sona-darwin-x64": "0.1.5",+ "@ruvector/sona-linux-arm64-gnu": "0.1.5",+ "@ruvector/sona-linux-x64-gnu": "0.1.5",+ "@ruvector/sona-linux-x64-musl": "0.1.5",+ "@ruvector/sona-win32-arm64-msvc": "0.1.5",+ "@ruvector/sona-win32-x64-msvc": "0.1.5"+ }+ },+ "../../node_modules/.pnpm/@[email protected]/node_modules/@ruvector/sona": {+ "version": "0.1.7",+ "license": "MIT OR Apache-2.0",+ "optional": true,+ "devDependencies": {+ "@napi-rs/cli": "^2.18.0"+ },+ "engines": {+ "node": ">= 16"+ },+ "optionalDependencies": {+ "@ruvector/sona-darwin-arm64": "0.1.7",+ "@ruvector/sona-darwin-x64": "0.1.7",+ "@ruvector/sona-linux-arm64-gnu": "0.1.7",+ "@ruvector/sona-linux-x64-gnu": "0.1.7",+ "@ruvector/sona-linux-x64-musl": "0.1.7",+ "@ruvector/sona-win32-arm64-msvc": "0.1.7",+ "@ruvector/sona-win32-x64-msvc": "0.1.7"+ }+ },+ "../../node_modules/.pnpm/@[email protected]/node_modules/@ruvector/tiny-dancer": {+ "version": "0.1.22",+ "license": "MIT",+ "optional": true,+ "devDependencies": {+ "@napi-rs/cli": "^2.18.0"+ },+ "engines": {+ "node": ">=18.0.0"+ },+ "optionalDependencies": {+ "@ruvector/tiny-dancer-darwin-arm64": "0.1.22",+ "@ruvector/tiny-dancer-darwin-x64": "0.1.22",+ "@ruvector/tiny-dancer-linux-arm64-gnu": "0.1.22",+ "@ruvector/tiny-dancer-linux-arm64-musl": "0.1.22",+ "@ruvector/tiny-dancer-linux-x64-gnu": "0.1.22",+ "@ruvector/tiny-dancer-linux-x64-musl": "0.1.22",+ "@ruvector/tiny-dancer-win32-arm64-msvc": "0.1.22",+ "@ruvector/tiny-dancer-win32-x64-msvc": "0.1.22"+ }+ },+ "../../node_modules/.pnpm/@[email protected]/node_modules/@types/better-sqlite3": {+ "version": "7.6.13",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/node": "*"+ }+ },+ "../../node_modules/.pnpm/@[email protected]/node_modules/@types/cors": {+ "version": "2.8.19",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "@types/node": "*"+ }+ },+ "../../node_modules/.pnpm/@[email protected]/node_modules/@types/express": {+ "version": "4.17.25",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "@types/body-parser": "*",+ "@types/express-serve-static-core": "^4.17.33",+ "@types/qs": "*",+ "@types/serve-static": "^1"+ }+ },+ "../../node_modules/.pnpm/@[email protected]/node_modules/@types/node": {+ "version": "20.19.27",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "undici-types": "~6.21.0"+ }+ },+ "../../node_modules/.pnpm/@[email protected]/node_modules/@types/sql.js": {+ "version": "1.4.9",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/emscripten": "*",+ "@types/node": "*"+ }+ },+ "../../node_modules/.pnpm/@[email protected]/node_modules/@types/ws": {+ "version": "8.18.1",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "@types/node": "*"+ }+ },+ "../../node_modules/.pnpm/[email protected]/node_modules/agentbbs": {+ "version": "0.1.0",+ "license": "FSL-1.1-Apache-2.0",+ "optional": true,+ "bin": {+ "agentbbs": "bin/agentbbs.js"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "../../node_modules/.pnpm/[email protected]_@[email protected][email protected]/node_modules/agentdb": {+ "version": "3.0.0-alpha.17",+ "hasInstallScript": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "@modelcontextprotocol/sdk": "^1.20.1",+ "@opentelemetry/api": "^1.9.0",+ "@ruvector/graph-transformer": "^2.0.4",+ "ajv": "^8.18.0",+ "jsonwebtoken": "^9.0.2",+ "sql.js": "^1.13.0"+ },+ "bin": {+ "agentdb": "dist/src/cli/agentdb-cli.js"+ },+ "devDependencies": {+ "@playwright/test": "^1.58.2",+ "@types/jsonwebtoken": "^9.0.10",+ "@types/node": "^22.10.2",+ "@types/uuid": "^11.0.0",+ "dotenv": "^16.4.7",+ "esbuild": "^0.25.11",+ "http-server": "^14.1.1",+ "playwright": "^1.58.2",+ "tsx": "^4.19.2",+ "typescript": "^5.7.2",+ "vitest": "^4.0.15"+ },+ "engines": {+ "node": ">=18.0.0"+ },+ "optionalDependencies": {+ "@opentelemetry/resources": "^1.25.0",+ "@opentelemetry/sdk-node": "^0.218.0",+ "@opentelemetry/semantic-conventions": "^1.25.0",+ "@ruvector/attention": "^0.1.2",+ "@ruvector/gnn": "^0.1.23",+ "@ruvector/graph-node": "^2.0.2",+ "@ruvector/router": "^0.1.15",+ "@ruvector/ruvllm": "^2.5.1",+ "@ruvector/rvf": "^0.1.9",+ "@ruvector/rvf-node": "^0.1.7",+ "@ruvector/rvf-solver": "^0.1.7",+ "@ruvector/rvf-wasm": "^0.1.6",+ "@ruvector/sona": "^0.1.4",+ "@xenova/transformers": "^2.17.2",+ "argon2": "^0.44.0",+ "better-sqlite3": "^11.8.1",+ "chalk": "^5.3.0",+ "commander": "^12.1.0",+ "hnswlib-node": "^3.0.0",+ "inquirer": "^9.3.8",+ "ruvector": "^0.1.30",+ "ruvector-attention-wasm": "^0.1.32",+ "ruvector-graph-transformer-wasm": "^2.0.4"+ }+ },+ "../../node_modules/.pnpm/[email protected]/node_modules/agentic-flow": {+ "version": "3.0.0-alpha.2",+ "hasInstallScript": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "@ai-sdk/google": "^3.0.31",+ "@anthropic-ai/claude-agent-sdk": "^0.1.5",+ "@anthropic-ai/sdk": "^0.65.0",+ "@google/genai": "^1.43.0",+ "@octokit/rest": "^21.0.0",+ "@ruvector/graph-node": "^2.0.2",+ "@supabase/supabase-js": "^2.78.0",+ "@types/validator": "^13.15.10",+ "@xenova/transformers": "^2.17.2",+ "agentdb": "^1.4.3",+ "axios": "^1.13.0",+ "dotenv": "^16.4.5",+ "express": "^5.1.0",+ "fastmcp": "^3.19.0",+ "http-proxy-middleware": "^3.0.5",+ "sql.js": "^1.14.0",+ "tiktoken": "^1.0.22",+ "ulid": "^3.0.1",+ "validator": "^13.15.26",+ "ws": "^8.18.3",+ "yaml": "^2.8.1",+ "zod": "^3.25.76"+ },+ "bin": {+ "agentdb": "dist/agentdb/cli/agentdb-cli.js",+ "agentic-flow": "dist/cli-proxy.js"+ },+ "devDependencies": {+ "@types/better-sqlite3": "^7.6.13",+ "@types/express": "^5.0.3",+ "@types/node": "^20.19.19",+ "@types/ws": "^8.18.1",+ "tsx": "^4.19.0",+ "typescript": "^5.6.3"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "../../node_modules/.pnpm/[email protected]/node_modules/bcryptjs": {+ "version": "3.0.3",+ "license": "BSD-3-Clause",+ "optional": true,+ "bin": {+ "bcrypt": "bin/bcrypt"+ },+ "devDependencies": {+ "bcrypt": "^5.1.1",+ "esm2umd": "^0.3.1",+ "prettier": "^3.5.0",+ "typescript": "^5.7.3"+ }+ },+ "../../node_modules/.pnpm/[email protected]/node_modules/better-sqlite3": {+ "version": "11.10.0",+ "hasInstallScript": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "bindings": "^1.5.0",+ "prebuild-install": "^7.1.1"+ },+ "devDependencies": {+ "chai": "^4.3.8",+ "cli-color": "^2.0.3",+ "fs-extra": "^11.1.1",+ "mocha": "^10.2.0",+ "nodemark": "^0.3.0",+ "prebuild": "^13.0.1",+ "sqlite": "^5.0.1",+ "sqlite3": "^5.1.6"+ }+ },+ "../../node_modules/.pnpm/[email protected]/node_modules/better-sqlite3": {+ "version": "12.9.0",+ "hasInstallScript": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "bindings": "^1.5.0",+ "prebuild-install": "^7.1.1"+ },+ "devDependencies": {+ "chai": "^4.3.8",+ "cli-color": "^2.0.3",+ "fs-extra": "^11.1.1",+ "mocha": "^10.2.0",+ "nodemark": "^0.3.0",+ "prebuild": "^13.0.1",+ "sqlite": "^5.0.1",+ "sqlite3": "^5.1.6"+ },+ "engines": {+ "node": "20.x || 22.x || 23.x || 24.x || 25.x"+ }+ },+ "../../node_modules/.pnpm/[email protected]/node_modules/cors": {+ "version": "2.8.5",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "object-assign": "^4",+ "vary": "^1"+ },+ "devDependencies": {+ "after": "0.8.2",+ "eslint": "2.13.1",+ "express": "4.16.3",+ "mocha": "5.2.0",+ "nyc": "13.1.0",+ "supertest": "3.3.0"+ },+ "engines": {+ "node": ">= 0.10"+ }+ },+ "../../node_modules/.pnpm/[email protected]/node_modules/express": {+ "version": "4.22.1",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "accepts": "~1.3.8",+ "array-flatten": "1.1.1",+ "body-parser": "~1.20.3",+ "content-disposition": "~0.5.4",+ "content-type": "~1.0.4",+ "cookie": "~0.7.1",+ "cookie-signature": "~1.0.6",+ "debug": "2.6.9",+ "depd": "2.0.0",+ "encodeurl": "~2.0.0",+ "escape-html": "~1.0.3",+ "etag": "~1.8.1",+ "finalhandler": "~1.3.1",+ "fresh": "~0.5.2",+ "http-errors": "~2.0.0",+ "merge-descriptors": "1.0.3",+ "methods": "~1.1.2",+ "on-finished": "~2.4.1",+ "parseurl": "~1.3.3",+ "path-to-regexp": "~0.1.12",+ "proxy-addr": "~2.0.7",+ "qs": "~6.14.0",+ "range-parser": "~1.2.1",+ "safe-buffer": "5.2.1",+ "send": "~0.19.0",+ "serve-static": "~1.16.2",+ "setprototypeof": "1.2.0",+ "statuses": "~2.0.1",+ "type-is": "~1.6.18",+ "utils-merge": "1.0.1",+ "vary": "~1.1.2"+ },+ "devDependencies": {+ "after": "0.8.2",+ "connect-redis": "3.4.2",+ "cookie-parser": "1.4.6",+ "cookie-session": "2.0.0",+ "ejs": "3.1.9",+ "eslint": "8.47.0",+ "express-session": "1.17.2",+ "hbs": "4.2.0",+ "marked": "0.7.0",+ "method-override": "3.0.0",+ "mocha": "^6.2.2",+ "morgan": "1.10.0",+ "nyc": "^14.1.1",+ "pbkdf2-password": "1.2.1",+ "supertest": "^6.1.6",+ "vhost": "~3.0.2"+ },+ "engines": {+ "node": ">= 0.10.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "../../node_modules/.pnpm/[email protected]/node_modules/helmet": {+ "version": "7.2.0",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "engines": {+ "node": ">=16.0.0"+ }+ },+ "../../node_modules/.pnpm/[email protected]_@[email protected]/node_modules/metaharness": {+ "version": "0.2.8",+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "@metaharness/darwin": "^0.2.2",+ "@metaharness/redblue": "^0.1.1",+ "@metaharness/weight-eft": "^0.1.0",+ "kolorist": "^1.8.0",+ "prompts": "^2.4.2"+ },+ "bin": {+ "harness": "dist/harness-bin.js",+ "metaharness": "dist/bin.js"+ },+ "devDependencies": {+ "@types/node": "^20.0.0",+ "@types/prompts": "^2.4.9",+ "typescript": "^5.4.0",+ "vitest": "^2.0.0"+ },+ "engines": {+ "node": ">=20.0.0"+ },+ "optionalDependencies": {+ "@ruvector/ruvllm": "^2.5.6"+ },+ "peerDependencies": {+ "@metaharness/kernel": "^0.1.0"+ },+ "peerDependenciesMeta": {+ "@metaharness/kernel": {+ "optional": true+ }+ }+ },+ "../../node_modules/.pnpm/[email protected]_@[email protected]_@[email protected][email protected]/node_modules/ruvector": {+ "version": "0.2.27",+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "@modelcontextprotocol/sdk": "^1.0.0",+ "@ruvector/attention": "^0.1.3",+ "@ruvector/core": "^0.1.25",+ "@ruvector/gnn": "^0.1.22",+ "@ruvector/sona": "^0.1.4",+ "chalk": "^4.1.2",+ "commander": "^11.1.0",+ "js-beautify": "^1.15.4",+ "ora": "^5.4.1"+ },+ "bin": {+ "ruvector": "bin/cli.js"+ },+ "devDependencies": {+ "@types/node": "^20.10.5",+ "typescript": "^5.9.3"+ },+ "engines": {+ "node": ">=18.0.0"+ },+ "optionalDependencies": {+ "@ruvector/rvf": "^0.1.0"+ },+ "peerDependencies": {+ "@ruvector/diskann": ">=0.1.0",+ "@ruvector/pi-brain": ">=0.1.0",+ "@ruvector/router": ">=0.1.0",+ "@ruvector/ruvllm": ">=2.0.0"+ },+ "peerDependenciesMeta": {+ "@ruvector/diskann": {+ "optional": true+ },+ "@ruvector/pi-brain": {+ "optional": true+ },+ "@ruvector/router": {+ "optional": true+ },+ "@ruvector/ruvllm": {+ "optional": true+ }+ }+ },+ "../../node_modules/.pnpm/[email protected]/node_modules/semver": {+ "version": "7.7.3",+ "license": "ISC",+ "bin": {+ "semver": "bin/semver.js"+ },+ "devDependencies": {+ "@npmcli/eslint-config": "^5.0.0",+ "@npmcli/template-oss": "4.25.1",+ "benchmark": "^2.1.4",+ "tap": "^16.0.0"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "../../node_modules/.pnpm/[email protected]/node_modules/sql.js": {+ "version": "1.13.0",+ "license": "MIT",+ "optional": true,+ "devDependencies": {+ "clean-jsdoc-theme": "^4.2.0",+ "eslint": "^8.54.0",+ "eslint-config-airbnb-base": "^15.0.0",+ "eslint-plugin-import": "^2.26.0",+ "jsdoc": "^4.0.2",+ "test": "=0.6.0"+ }+ },+ "../../node_modules/.pnpm/[email protected]/node_modules/typescript": {+ "version": "5.9.3",+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "bin": {+ "tsc": "bin/tsc",+ "tsserver": "bin/tsserver"+ },+ "devDependencies": {+ "@dprint/formatter": "^0.4.1",+ "@dprint/typescript": "0.93.4",+ "@esfx/canceltoken": "^1.0.0",+ "@eslint/js": "^9.20.0",+ "@octokit/rest": "^21.1.1",+ "@types/chai": "^4.3.20",+ "@types/diff": "^7.0.1",+ "@types/minimist": "^1.2.5",+ "@types/mocha": "^10.0.10",+ "@types/ms": "^0.7.34",+ "@types/node": "latest",+ "@types/source-map-support": "^0.5.10",+ "@types/which": "^3.0.4",+ "@typescript-eslint/rule-tester": "^8.24.1",+ "@typescript-eslint/type-utils": "^8.24.1",+ "@typescript-eslint/utils": "^8.24.1",+ "azure-devops-node-api": "^14.1.0",+ "c8": "^10.1.3",+ "chai": "^4.5.0",+ "chokidar": "^4.0.3",+ "diff": "^7.0.0",+ "dprint": "^0.49.0",+ "esbuild": "^0.25.0",+ "eslint": "^9.20.1",+ "eslint-formatter-autolinkable-stylish": "^1.4.0",+ "eslint-plugin-regexp": "^2.7.0",+ "fast-xml-parser": "^4.5.2",+ "glob": "^10.4.5",+ "globals": "^15.15.0",+ "hereby": "^1.10.0",+ "jsonc-parser": "^3.3.1",+ "knip": "^5.44.4",+ "minimist": "^1.2.8",+ "mocha": "^10.8.2",+ "mocha-fivemat-progress-reporter": "^0.1.0",+ "monocart-coverage-reports": "^2.12.1",+ "ms": "^2.1.3",+ "picocolors": "^1.1.1",+ "playwright": "^1.50.1",+ "source-map-support": "^0.5.21",+ "tslib": "^2.8.1",+ "typescript": "^5.7.3",+ "typescript-eslint": "^8.24.1",+ "which": "^3.0.1"+ },+ "engines": {+ "node": ">=14.17"+ }+ },+ "../../node_modules/.pnpm/[email protected]_@[email protected]_@[email protected]_@[email protected][email protected]/node_modules/vitest": {+ "version": "4.1.8",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@vitest/expect": "4.1.8",+ "@vitest/mocker": "4.1.8",+ "@vitest/pretty-format": "4.1.8",+ "@vitest/runner": "4.1.8",+ "@vitest/snapshot": "4.1.8",+ "@vitest/spy": "4.1.8",+ "@vitest/utils": "4.1.8",+ "es-module-lexer": "^2.0.0",+ "expect-type": "^1.3.0",+ "magic-string": "^0.30.21",+ "obug": "^2.1.1",+ "pathe": "^2.0.3",+ "picomatch": "^4.0.3",+ "std-env": "^4.0.0-rc.1",+ "tinybench": "^2.9.0",+ "tinyexec": "^1.0.2",+ "tinyglobby": "^0.2.15",+ "tinyrainbow": "^3.1.0",+ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0",+ "why-is-node-running": "^2.3.0"+ },+ "bin": {+ "vitest": "vitest.mjs"+ },+ "devDependencies": {+ "@antfu/install-pkg": "^1.1.0",+ "@bomb.sh/tab": "^0.0.14",+ "@edge-runtime/vm": "^5.0.0",+ "@jridgewell/trace-mapping": "0.3.31",+ "@opentelemetry/api": "^1.9.0",+ "@sinonjs/fake-timers": "15.0.0",+ "@types/estree": "^1.0.8",+ "@types/istanbul-lib-coverage": "^2.0.6",+ "@types/istanbul-reports": "^3.0.4",+ "@types/jsdom": "^27.0.0",+ "@types/node": "^24.12.0",+ "@types/picomatch": "^4.0.2",+ "@types/prompts": "^2.4.9",+ "@types/sinonjs__fake-timers": "^15.0.1",+ "acorn": "8.11.3",+ "acorn-walk": "^8.3.5",+ "birpc": "^4.0.0",+ "cac": "^6.7.14",+ "empathic": "^2.0.0",+ "flatted": "^3.4.2",+ "happy-dom": "^20.8.3",+ "jsdom": "^27.4.0",+ "local-pkg": "^1.1.2",+ "mime": "^4.1.0",+ "prompts": "^2.4.2",+ "strip-literal": "^3.1.0",+ "tinyhighlight": "^0.3.2",+ "ws": "^8.19.0"+ },+ "engines": {+ "node": "^20.0.0 || ^22.0.0 || >=24.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ },+ "peerDependencies": {+ "@edge-runtime/vm": "*",+ "@opentelemetry/api": "^1.9.0",+ "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0",+ "@vitest/browser-playwright": "4.1.8",+ "@vitest/browser-preview": "4.1.8",+ "@vitest/browser-webdriverio": "4.1.8",+ "@vitest/coverage-istanbul": "4.1.8",+ "@vitest/coverage-v8": "4.1.8",+ "@vitest/ui": "4.1.8",+ "happy-dom": "*",+ "jsdom": "*",+ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0"+ },+ "peerDependenciesMeta": {+ "@edge-runtime/vm": {+ "optional": true+ },+ "@opentelemetry/api": {+ "optional": true+ },+ "@types/node": {+ "optional": true+ },+ "@vitest/browser-playwright": {+ "optional": true+ },+ "@vitest/browser-preview": {+ "optional": true+ },+ "@vitest/browser-webdriverio": {+ "optional": true+ },+ "@vitest/coverage-istanbul": {+ "optional": true+ },+ "@vitest/coverage-v8": {+ "optional": true+ },+ "@vitest/ui": {+ "optional": true+ },+ "happy-dom": {+ "optional": true+ },+ "jsdom": {+ "optional": true+ },+ "vite": {+ "optional": false+ }+ }+ },+ "../../node_modules/.pnpm/[email protected]/node_modules/ws": {+ "version": "8.19.0",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "devDependencies": {+ "benchmark": "^2.1.4",+ "bufferutil": "^4.0.1",+ "eslint": "^9.0.0",+ "eslint-config-prettier": "^10.0.1",+ "eslint-plugin-prettier": "^5.0.0",+ "globals": "^16.0.0",+ "mocha": "^8.4.0",+ "nyc": "^15.0.0",+ "prettier": "^3.0.0",+ "utf-8-validate": "^6.0.0"+ },+ "engines": {+ "node": ">=10.0.0"+ },+ "peerDependencies": {+ "bufferutil": "^4.0.1",+ "utf-8-validate": ">=5.0.2"+ },+ "peerDependenciesMeta": {+ "bufferutil": {+ "optional": true+ },+ "utf-8-validate": {+ "optional": true+ }+ }+ },+ "../../node_modules/.pnpm/[email protected]/node_modules/yaml": {+ "version": "2.8.2",+ "license": "ISC",+ "bin": {+ "yaml": "bin.mjs"+ },+ "devDependencies": {+ "@babel/core": "^7.12.10",+ "@babel/plugin-transform-typescript": "^7.12.17",+ "@babel/preset-env": "^7.12.11",+ "@eslint/js": "^9.9.1",+ "@rollup/plugin-babel": "^6.0.3",+ "@rollup/plugin-replace": "^6.0.3",+ "@rollup/plugin-typescript": "^12.1.1",+ "@types/jest": "^29.2.4",+ "@types/node": "^20.11.20",+ "babel-jest": "^29.0.1",+ "eslint": "^9.9.1",+ "eslint-config-prettier": "^10.1.8",+ "fast-check": "^2.12.0",+ "jest": "^29.0.1",+ "jest-resolve": "^29.7.0",+ "jest-ts-webcompat-resolver": "^1.0.0",+ "prettier": "^3.0.2",+ "rollup": "^4.12.0",+ "tslib": "^2.8.1",+ "typescript": "^5.7.2",+ "typescript-eslint": "^8.4.0"+ },+ "engines": {+ "node": ">= 14.6"+ },+ "funding": {+ "url": "https://github.com/sponsors/eemeli"+ }+ },+ "../../node_modules/.pnpm/[email protected]/node_modules/zod": {+ "version": "3.25.76",+ "license": "MIT",+ "optional": true,+ "funding": {+ "url": "https://github.com/sponsors/colinhacks"+ }+ },+ "../cli-core": {+ "version": "3.7.0-alpha.5",+ "license": "MIT",+ "bin": {+ "claude-flow-core": "dist/src/index.js"+ }+ },+ "../guidance": {+ "version": "3.0.0-alpha.4",+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "@claude-flow/hooks": "^3.0.0-alpha.7",+ "@claude-flow/memory": "^3.0.0-alpha.2",+ "@claude-flow/shared": "^3.0.0-alpha.1"+ },+ "devDependencies": {+ "@types/node": "^20.10.0",+ "typescript": "^5.3.0",+ "vitest": "^4.1.0"+ },+ "engines": {+ "node": ">=20.0.0"+ }+ },+ "../guidance/node_modules/@claude-flow/hooks": {+ "resolved": "../hooks",+ "link": true+ },+ "../guidance/node_modules/@claude-flow/memory": {+ "resolved": "../memory",+ "link": true+ },+ "../guidance/node_modules/@claude-flow/shared": {+ "resolved": "../shared",+ "link": true+ },+ "../guidance/node_modules/@types/node": {+ "resolved": "../../node_modules/.pnpm/@[email protected]/node_modules/@types/node",+ "link": true+ },+ "../guidance/node_modules/typescript": {+ "resolved": "../../node_modules/.pnpm/[email protected]/node_modules/typescript",+ "link": true+ },+ "../guidance/node_modules/vitest": {+ "resolved": "../../node_modules/.pnpm/[email protected]_@[email protected]_@[email protected]_@[email protected][email protected]/node_modules/vitest",+ "link": true+ },+ "../hooks": {+ "version": "3.0.0-alpha.7",+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "@claude-flow/memory": "^3.0.0-alpha.2",+ "@claude-flow/neural": "^3.0.0-alpha.2",+ "@claude-flow/shared": "^3.0.0-alpha.1",+ "zod": "^3.23.0"+ },+ "bin": {+ "claude-flow-hooks": "dist/cli/guidance-cli.js",+ "guidance": "dist/cli/guidance-cli.js",+ "hooks-daemon": "bin/hooks-daemon.js",+ "statusline": "bin/statusline.js"+ },+ "devDependencies": {+ "@types/better-sqlite3": "^7.6.11",+ "@types/node": "^20.10.0",+ "typescript": "^5.3.0",+ "vitest": "^4.1.0"+ },+ "engines": {+ "node": ">=20.0.0"+ },+ "optionalDependencies": {+ "better-sqlite3": "^11.0.0"+ },+ "peerDependencies": {+ "@claude-flow/shared": "^3.0.0-alpha.1"+ }+ },+ "../hooks/node_modules/@claude-flow/memory": {+ "resolved": "../memory",+ "link": true+ },+ "../hooks/node_modules/@claude-flow/neural": {+ "resolved": "../neural",+ "link": true+ },+ "../hooks/node_modules/@claude-flow/shared": {+ "resolved": "../shared",+ "link": true+ },+ "../hooks/node_modules/@types/better-sqlite3": {+ "resolved": "../../node_modules/.pnpm/@[email protected]/node_modules/@types/better-sqlite3",+ "link": true+ },+ "../hooks/node_modules/@types/node": {+ "resolved": "../../node_modules/.pnpm/@[email protected]/node_modules/@types/node",+ "link": true+ },+ "../hooks/node_modules/better-sqlite3": {+ "resolved": "../../node_modules/.pnpm/[email protected]/node_modules/better-sqlite3",+ "link": true+ },+ "../hooks/node_modules/typescript": {+ "resolved": "../../node_modules/.pnpm/[email protected]/node_modules/typescript",+ "link": true+ },+ "../hooks/node_modules/vitest": {+ "resolved": "../../node_modules/.pnpm/[email protected]_@[email protected]_@[email protected]_@[email protected][email protected]/node_modules/vitest",+ "link": true+ },+ "../hooks/node_modules/zod": {+ "resolved": "../../node_modules/.pnpm/[email protected]/node_modules/zod",+ "link": true+ },+ "../memory": {+ "version": "3.0.0-alpha.21",+ "cpu": [+ "x64",+ "arm64"+ ],+ "optional": true,+ "os": [+ "darwin",+ "linux",+ "win32"+ ],+ "dependencies": {+ "agentdb": "^3.0.0-alpha.17",+ "sql.js": "^1.10.3"+ },+ "devDependencies": {+ "@types/better-sqlite3": "^7.6.11",+ "@types/sql.js": "^1.4.9",+ "vitest": "^4.1.0"+ },+ "optionalDependencies": {+ "better-sqlite3": "^12.9.0"+ }+ },+ "../memory/node_modules/@types/better-sqlite3": {+ "resolved": "../../node_modules/.pnpm/@[email protected]/node_modules/@types/better-sqlite3",+ "link": true+ },+ "../memory/node_modules/@types/sql.js": {+ "resolved": "../../node_modules/.pnpm/@[email protected]/node_modules/@types/sql.js",+ "link": true+ },+ "../memory/node_modules/agentdb": {+ "resolved": "../../node_modules/.pnpm/[email protected]_@[email protected][email protected]/node_modules/agentdb",+ "link": true+ },+ "../memory/node_modules/better-sqlite3": {+ "resolved": "../../node_modules/.pnpm/[email protected]/node_modules/better-sqlite3",+ "link": true+ },+ "../memory/node_modules/sql.js": {+ "resolved": "../../node_modules/.pnpm/[email protected]/node_modules/sql.js",+ "link": true+ },+ "../memory/node_modules/vitest": {+ "resolved": "../../node_modules/.pnpm/[email protected]_@[email protected]_@[email protected]_@[email protected][email protected]/node_modules/vitest",+ "link": true+ },+ "../neural": {+ "version": "3.0.0-alpha.9",+ "license": "MIT",+ "dependencies": {+ "@claude-flow/memory": "^3.0.0-alpha.16",+ "@ruvector/sona": "0.1.5"+ },+ "optionalDependencies": {+ "agentdb": "^2.0.0 || ^3.0.0-alpha.1"+ }+ },+ "../neural/node_modules/@claude-flow/memory": {+ "resolved": "../memory",+ "link": true+ },+ "../neural/node_modules/@ruvector/sona": {+ "resolved": "../../node_modules/.pnpm/@[email protected]/node_modules/@ruvector/sona",+ "link": true+ },+ "../neural/node_modules/agentdb": {+ "resolved": "../../node_modules/.pnpm/[email protected]_@[email protected][email protected]/node_modules/agentdb",+ "link": true+ },+ "../security": {+ "version": "3.0.0-alpha.10",+ "optional": true,+ "dependencies": {+ "@noble/ed25519": "^2.1.0",+ "bcryptjs": "^3.0.3",+ "zod": "^3.22.0"+ },+ "devDependencies": {+ "vitest": "^4.1.0"+ }+ },+ "../security/node_modules/@noble/ed25519": {+ "resolved": "../../node_modules/.pnpm/@[email protected]/node_modules/@noble/ed25519",+ "link": true+ },+ "../security/node_modules/bcryptjs": {+ "resolved": "../../node_modules/.pnpm/[email protected]/node_modules/bcryptjs",+ "link": true+ },+ "../security/node_modules/vitest": {+ "resolved": "../../node_modules/.pnpm/[email protected]_@[email protected]_@[email protected]_@[email protected][email protected]/node_modules/vitest",+ "link": true+ },+ "../security/node_modules/zod": {+ "resolved": "../../node_modules/.pnpm/[email protected]/node_modules/zod",+ "link": true+ },+ "../shared": {+ "version": "3.0.0-alpha.8",+ "optional": true,+ "dependencies": {+ "sql.js": "^1.10.3"+ },+ "devDependencies": {+ "@types/cors": "^2.8.17",+ "@types/express": "^4.17.21",+ "@types/node": "^20.0.0",+ "@types/sql.js": "^1.4.9",+ "@types/ws": "^8.5.10",+ "cors": "^2.8.5",+ "express": "^4.21.0",+ "helmet": "^7.1.0",+ "vitest": "^4.1.0",+ "ws": "^8.16.0",+ "zod": "^3.22.4"+ }+ },+ "../shared/node_modules/@types/cors": {+ "resolved": "../../node_modules/.pnpm/@[email protected]/node_modules/@types/cors",+ "link": true+ },+ "../shared/node_modules/@types/express": {+ "resolved": "../../node_modules/.pnpm/@[email protected]/node_modules/@types/express",+ "link": true+ },+ "../shared/node_modules/@types/node": {+ "resolved": "../../node_modules/.pnpm/@[email protected]/node_modules/@types/node",+ "link": true+ },+ "../shared/node_modules/@types/sql.js": {+ "resolved": "../../node_modules/.pnpm/@[email protected]/node_modules/@types/sql.js",+ "link": true+ },+ "../shared/node_modules/@types/ws": {+ "resolved": "../../node_modules/.pnpm/@[email protected]/node_modules/@types/ws",+ "link": true+ },+ "../shared/node_modules/cors": {+ "resolved": "../../node_modules/.pnpm/[email protected]/node_modules/cors",+ "link": true+ },+ "../shared/node_modules/express": {+ "resolved": "../../node_modules/.pnpm/[email protected]/node_modules/express",+ "link": true+ },+ "../shared/node_modules/helmet": {+ "resolved": "../../node_modules/.pnpm/[email protected]/node_modules/helmet",+ "link": true+ },+ "../shared/node_modules/sql.js": {+ "resolved": "../../node_modules/.pnpm/[email protected]/node_modules/sql.js",+ "link": true+ },+ "../shared/node_modules/vitest": {+ "resolved": "../../node_modules/.pnpm/[email protected]_@[email protected]_@[email protected]_@[email protected][email protected]/node_modules/vitest",+ "link": true+ },+ "../shared/node_modules/ws": {+ "resolved": "../../node_modules/.pnpm/[email protected]/node_modules/ws",+ "link": true+ },+ "../shared/node_modules/zod": {+ "resolved": "../../node_modules/.pnpm/[email protected]/node_modules/zod",+ "link": true+ },+ "node_modules/@claude-flow/aidefence": {+ "resolved": "../../node_modules/.pnpm/@[email protected][email protected]/node_modules/@claude-flow/aidefence",+ "link": true+ },+ "node_modules/@claude-flow/cli-core": {+ "resolved": "../cli-core",+ "link": true+ },+ "node_modules/@claude-flow/codex": {+ "resolved": "../../node_modules/.pnpm/@[email protected]_@[email protected]/node_modules/@claude-flow/codex",+ "link": true+ },+ "node_modules/@claude-flow/embeddings": {+ "resolved": "../../node_modules/.pnpm/@[email protected]_@[email protected]_@ruvector+attention@_kjdwodggaqxawad5ojmmgbga4y/node_modules/@claude-flow/embeddings",+ "link": true+ },+ "node_modules/@claude-flow/guidance": {+ "resolved": "../guidance",+ "link": true+ },+ "node_modules/@claude-flow/mcp": {+ "resolved": "../../node_modules/.pnpm/@[email protected]/node_modules/@claude-flow/mcp",+ "link": true+ },+ "node_modules/@claude-flow/memory": {+ "resolved": "../memory",+ "link": true+ },+ "node_modules/@claude-flow/neural": {+ "resolved": "../neural",+ "link": true+ },+ "node_modules/@claude-flow/plugin-gastown-bridge": {+ "resolved": "../../node_modules/.pnpm/@[email protected]_@claude-flow+memory@@claude-flow+memory/node_modules/@claude-flow/plugin-gastown-bridge",+ "link": true+ },+ "node_modules/@claude-flow/security": {+ "resolved": "../security",+ "link": true+ },+ "node_modules/@claude-flow/shared": {+ "resolved": "../../node_modules/.pnpm/@[email protected]/node_modules/@claude-flow/shared",+ "link": true+ },+ "node_modules/@metaharness/darwin": {+ "resolved": "../../node_modules/.pnpm/@[email protected]/node_modules/@metaharness/darwin",+ "link": true+ },+ "node_modules/@metaharness/kernel": {+ "resolved": "../../node_modules/.pnpm/@[email protected]/node_modules/@metaharness/kernel",+ "link": true+ },+ "node_modules/@metaharness/redblue": {+ "resolved": "../../node_modules/.pnpm/@[email protected]/node_modules/@metaharness/redblue",+ "link": true+ },+ "node_modules/@metaharness/router": {+ "resolved": "../../node_modules/.pnpm/@[email protected]_@[email protected]/node_modules/@metaharness/router",+ "link": true+ },+ "node_modules/@noble/ed25519": {+ "resolved": "../../node_modules/.pnpm/@[email protected]/node_modules/@noble/ed25519",+ "link": true+ },+ "node_modules/@ruvector/attention": {+ "resolved": "../../node_modules/.pnpm/@[email protected]/node_modules/@ruvector/attention",+ "link": true+ },+ "node_modules/@ruvector/attention-darwin-arm64": {+ "resolved": "../../node_modules/.pnpm/@[email protected]/node_modules/@ruvector/attention-darwin-arm64",+ "link": true+ },+ "node_modules/@ruvector/diskann": {+ "resolved": "../../node_modules/.pnpm/@[email protected]/node_modules/@ruvector/diskann",+ "link": true+ },+ "node_modules/@ruvector/learning-wasm": {+ "resolved": "../../node_modules/.pnpm/@[email protected]/node_modules/@ruvector/learning-wasm",+ "link": true+ },+ "node_modules/@ruvector/rabitq-wasm": {+ "resolved": "../../node_modules/.pnpm/@[email protected]/node_modules/@ruvector/rabitq-wasm",+ "link": true+ },+ "node_modules/@ruvector/router": {+ "resolved": "../../node_modules/.pnpm/@[email protected]/node_modules/@ruvector/router",+ "link": true+ },+ "node_modules/@ruvector/ruvllm-wasm": {+ "resolved": "../../node_modules/.pnpm/@[email protected]/node_modules/@ruvector/ruvllm-wasm",+ "link": true+ },+ "node_modules/@ruvector/rvagent-wasm": {+ "resolved": "../../node_modules/.pnpm/@[email protected]/node_modules/@ruvector/rvagent-wasm",+ "link": true+ },+ "node_modules/@ruvector/rvf-node": {+ "version": "0.2.0",+ "resolved": "https://registry.npmjs.org/@ruvector/rvf-node/-/rvf-node-0.2.0.tgz",+ "integrity": "sha512-9BxoECGiQ7ttj6V0ClLK83DLxaxraRRWzIt06IgETUxTYdqGQ3MZgacEBn7vWRecTK8X9/LrZrIOmNcQZx6OuA==",+ "license": "MIT",+ "optional": true,+ "engines": {+ "node": ">= 16"+ },+ "optionalDependencies": {+ "@ruvector/rvf-node-darwin-arm64": "0.1.7",+ "@ruvector/rvf-node-darwin-x64": "0.1.7",+ "@ruvector/rvf-node-linux-arm64-gnu": "0.1.7",+ "@ruvector/rvf-node-linux-x64-gnu": "0.2.0",+ "@ruvector/rvf-node-win32-x64-msvc": "0.1.7"+ }+ },+ "node_modules/@ruvector/rvf-node-darwin-arm64": {+ "version": "0.1.7",+ "resolved": "https://registry.npmjs.org/@ruvector/rvf-node-darwin-arm64/-/rvf-node-darwin-arm64-0.1.7.tgz",+ "integrity": "sha512-vll3WJwDn3oOfy1PB10IG7/f3zBpFiMNHL2/2tdJmeRR8La/rSPJ0ZH5MDIsfleiVtaWzh9bvVCtVkZ6uo2jeg==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ]+ },+ "node_modules/@ruvector/rvf-node-darwin-x64": {+ "version": "0.1.7",+ "resolved": "https://registry.npmjs.org/@ruvector/rvf-node-darwin-x64/-/rvf-node-darwin-x64-0.1.7.tgz",+ "integrity": "sha512-Qi/l2bVuVz5YQ2RcYPYF0LNZVkytiIZHzvWhS71+Tt5GEIrsToauHQIcnJQmDNypvwxO8wYk+EeT2xcHR3ZSQQ==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ]+ },+ "node_modules/@ruvector/rvf-node-linux-arm64-gnu": {+ "version": "0.1.7",+ "resolved": "https://registry.npmjs.org/@ruvector/rvf-node-linux-arm64-gnu/-/rvf-node-linux-arm64-gnu-0.1.7.tgz",+ "integrity": "sha512-oZwrtfs7XqRVaDP6iiw6G52l7+NdP3NbTwR2iM+EP8r8X4e1+p4opwV2Ig+lyT7wAz72wcyOpkzpu1MlbK4NKA==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@ruvector/rvf-node-linux-x64-gnu": {+ "version": "0.2.0",+ "resolved": "https://registry.npmjs.org/@ruvector/rvf-node-linux-x64-gnu/-/rvf-node-linux-x64-gnu-0.2.0.tgz",+ "integrity": "sha512-P1UaZaWoh6GAm+CUV2tOzKm+J0Z48PFO7OJ3BnPMh6rSFPMbnpdrjbV+WxacV8zsNeceE5iJxwLUYFK5q5YHkg==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@ruvector/rvf-node-win32-x64-msvc": {+ "version": "0.1.7",+ "resolved": "https://registry.npmjs.org/@ruvector/rvf-node-win32-x64-msvc/-/rvf-node-win32-x64-msvc-0.1.7.tgz",+ "integrity": "sha512-sgnoNphOnbD4d3+YyQ83MlGO7sX4kbcDwsFNz7p2mlTaDR8coQXoudSaPrMeMpeUojFUqoxeDvVly/un3jADig==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ]+ },+ "node_modules/@ruvector/sona": {+ "resolved": "../../node_modules/.pnpm/@[email protected]/node_modules/@ruvector/sona",+ "link": true+ },+ "node_modules/@ruvector/tiny-dancer": {+ "resolved": "../../node_modules/.pnpm/@[email protected]/node_modules/@ruvector/tiny-dancer",+ "link": true+ },+ "node_modules/agentbbs": {+ "resolved": "../../node_modules/.pnpm/[email protected]/node_modules/agentbbs",+ "link": true+ },+ "node_modules/agentdb": {+ "resolved": "../../node_modules/.pnpm/[email protected]_@[email protected][email protected]/node_modules/agentdb",+ "link": true+ },+ "node_modules/agentic-flow": {+ "resolved": "../../node_modules/.pnpm/[email protected]/node_modules/agentic-flow",+ "link": true+ },+ "node_modules/agenticow": {+ "version": "0.2.4",+ "resolved": "https://registry.npmjs.org/agenticow/-/agenticow-0.2.4.tgz",+ "integrity": "sha512-x7CqbLhivrHNYCN0mLCi5+xDWI1ycJJuMSGGZchmlu2J4RDLLDkRokzA2VM+OaocbCe6sb1mBgrGgP7rsmoCjQ==",+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "@ruvector/rvf-node": "^0.2.0"+ },+ "bin": {+ "agenticow": "bin/agenticow.js"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/metaharness": {+ "resolved": "../../node_modules/.pnpm/[email protected]_@[email protected]/node_modules/metaharness",+ "link": true+ },+ "node_modules/ruvector": {+ "resolved": "../../node_modules/.pnpm/[email protected]_@[email protected]_@[email protected][email protected]/node_modules/ruvector",+ "link": true+ },+ "node_modules/semver": {+ "resolved": "../../node_modules/.pnpm/[email protected]/node_modules/semver",+ "link": true+ },+ "node_modules/typescript": {+ "resolved": "../../node_modules/.pnpm/[email protected]/node_modules/typescript",+ "link": true+ },+ "node_modules/vitest": {+ "resolved": "../../node_modules/.pnpm/[email protected]_@[email protected]_@[email protected]_@[email protected][email protected]/node_modules/vitest",+ "link": true+ },+ "node_modules/yaml": {+ "resolved": "../../node_modules/.pnpm/[email protected]/node_modules/yaml",+ "link": true+ }+ }+}diff --git a/v3/@claude-flow/cli/package.json b/v3/@claude-flow/cli/package.jsonindex f565bd04cc..ab8b95c05d 100644--- a/v3/@claude-flow/cli/package.json+++ b/v3/@claude-flow/cli/package.json@@ -106,8 +106,6 @@"yaml": "^2.8.0"},"optionalDependencies": {- "agentbbs": "~0.1.0",- "agenticow": "~0.2.3","@claude-flow/aidefence": "^3.0.2","@claude-flow/codex": "^3.0.0-alpha.8","@claude-flow/embeddings": "^3.0.0-alpha.18",@@ -119,7 +117,7 @@"@metaharness/kernel": "~0.1.2","@metaharness/redblue": "~0.1.4","@metaharness/router": "~0.3.2",- "metaharness": "~0.2.8",+ "@metaharness/weight-eft": "~0.1.1","@ruvector/attention": "^0.1.32","@ruvector/attention-darwin-arm64": "0.1.32","@ruvector/diskann": "^0.1.0",@@ -129,8 +127,11 @@"@ruvector/rvagent-wasm": "^0.1.0","@ruvector/sona": "^0.1.6","@ruvector/tiny-dancer": "^0.1.22",+ "agentbbs": "~0.1.0","agentdb": "^3.0.0-alpha.17","agentic-flow": "^3.0.0-alpha.1",+ "agenticow": "~0.2.4",+ "metaharness": "~0.2.8","ruvector": "^0.2.27"},"publishConfig": {diff --git a/v3/@claude-flow/cli/src/agenticow/speculative-exploration.ts b/v3/@claude-flow/cli/src/agenticow/speculative-exploration.tsnew file mode 100644index 0000000000..28d8fed043--- /dev/null+++ b/v3/@claude-flow/cli/src/agenticow/speculative-exploration.ts@@ -0,0 +1,343 @@+/**+ * Speculative branch-and-promote β parallel A/B solution exploration over+ * COW memory branches (agenticow step 4).+ *+ * Concept (from agenticow's examples/ab-branches + promotion-pipeline):+ * Fan out N candidate approaches, each on its own Copy-On-Write branch of a+ * shared base `.rvf` memory. Each candidate explores/writes independently+ * against its own branch handle. Score the results, PROMOTE the winner's+ * branch back into base, and DISCARD the losers β which for agenticow means+ * deleting the branch files (162 bytes each), not re-copying GB of state.+ *+ * This is the memory-state analogue of the git-worktree-per-agent pattern+ * used for parallel code agents: cheap speculative forks, keep one, throw the+ * rest away at near-zero cost.+ *+ * This module is intentionally COMPOSED ON TOP of the existing agenticow verbs+ * (`fork` / `promote`) and the shared `_agenticow.ts` helpers β it does not+ * reimplement COW semantics. It is generic over the candidate result type so+ * callers supply their own `fn` (what to do on each branch) and `score`+ * (how good the branch turned out).+ *+ * @module @claude-flow/cli/agenticow/speculative-exploration+ */++import { existsSync, rmSync } from 'node:fs';+import {+ loadAgenticow,+ openWithLineage,+ manifestFor,+ resolveMemoryPath,+ validateLabel,+ type AgenticowApi,+} from '../mcp-tools/agenticow-loader.js';++/** A COW memory handle (agenticow `AgenticMemory`), kept `any` to avoid a hard type dep. */+export type MemoryHandle = any;++export interface SpeculativeCandidate<TResult> {+ /** Human-readable branch label (validated: `[A-Za-z0-9_.\-:/@]`). */+ label: string;+ /**+ * The exploration to run against this candidate's isolated branch handle.+ * Receives the forked branch (read-through of base βͺ its own edits). May+ * ingest, delete, query, etc. Its return value is fed to `score`.+ */+ fn: (branch: MemoryHandle) => TResult | Promise<TResult>;+}++export interface ExploreOptions {+ /**+ * Maps a candidate label to the on-disk path for its branch `.rvf` file.+ * Loser paths are deleted after scoring.+ */+ branchPath: (label: string) => string;+ /** Persist winner-branch + save manifests. Default true. */+ persist?: boolean;+ /**+ * Tie-break: when two candidates tie on score, the earlier one (lower index)+ * wins by default (stable). Set `'last'` to prefer the later candidate.+ */+ tieBreak?: 'first' | 'last';+ /**+ * PROMOTION GATE (ADR-171). A branch is promote-INELIGIBLE unless cleared by a+ * real evaluation oracle, or by an explicitly-accepted Fable judge. When+ * provided, the top-scoring candidate is promoted ONLY if this returns+ * `{cleared:true, by:'oracle:test-exec'}` or `{cleared:true, by:'judge:fable'}`.+ * `proxy:structural` can NEVER clear a promote β score rank alone does not+ * graduate work into base. Omit for legacy score-only promotion (unverified).+ */+ clearance?: (+ winnerResult: unknown,+ label: string,+ ) => Promise<{ cleared: boolean; by: PromotionProvenance; reason?: string }>;+ /**+ * Force the clearance gate even without a `clearance` fn β a missing gate then+ * means the winner is ineligible (fail-closed). Default: gate enforced iff+ * `clearance` is supplied.+ */+ requireClearance?: boolean;+}++/** Provenance of a promotion decision (ADR-171 trust tiers). */+export type PromotionProvenance =+ | 'oracle:test-exec' // real evaluation β clears+ | 'judge:fable' // explicitly-accepted LLM judge β clears+ | 'proxy:structural' // score/structural only β NEVER clears a promote+ | 'unverified'; // legacy score-only path (no gate configured)++/**+ * Causal failure receipt (ADR-171). Emitted for every discarded loser and for+ * an ineligible/failed winner β a rollback that loses *why* is half-useful.+ */+export interface SpeculativeReceipt {+ label: string;+ score: number;+ /** What the branch changed vs its lineage, when introspectable. */+ diff: { added: number[]; overridden: number[]; deleted: number[] } | null;+ /** Why this branch did not graduate. */+ outcome: 'discarded-loser' | 'winner-ineligible' | 'winner-failed';+ provenance: PromotionProvenance;+ reason?: string;+}++export interface SpeculativeBranchOutcome<TResult> {+ label: string;+ path: string;+ score: number;+ result: TResult;+ /** true for the promoted winner, false for discarded losers. */+ kept: boolean;+}++export interface SpeculativeResult<TResult> {+ /** Label of the winning (promoted) candidate. */+ winner: string;+ /** label β score for every candidate. */+ scores: Record<string, number>;+ /** Whether the winner was successfully promoted into base. */+ promoted: boolean;+ /** How the promotion decision was reached (ADR-171 provenance). */+ promotedBy: PromotionProvenance;+ /** Human-readable promotion decision, e.g. 'promoted:oracle:test-exec' or 'ineligible:proxy-cannot-clear'. */+ promotionDecision: string;+ /** agenticow promote() stats for the winner ({ ingested, deleted }). */+ promoteStats: { ingested: number; deleted: number } | null;+ /** Labels of the discarded losers whose branch files were deleted. */+ discarded: string[];+ /** Causal failure receipts for discarded losers + an ineligible winner. */+ receipts: SpeculativeReceipt[];+ /** Per-candidate detail (score, path, result, kept). */+ branches: SpeculativeBranchOutcome<TResult>[];+}++function safeDiff(branch: MemoryHandle): SpeculativeReceipt['diff'] {+ try {+ const d = branch.diff?.();+ return d ? { added: d.added ?? [], overridden: d.overridden ?? [], deleted: d.deleted ?? [] } : null;+ } catch {+ return null;+ }+}++function deleteBranchFiles(path: string): void {+ for (const p of [path, manifestFor(path)]) {+ try {+ if (existsSync(p)) rmSync(p, { recursive: true, force: true });+ } catch {+ /* best-effort discard; a leftover 162-byte file is not fatal */+ }+ }+}++/**+ * Fork one branch per candidate off `base`, run each `fn` against its own+ * branch handle, score the results, PROMOTE the best branch back into `base`,+ * and DISCARD (delete the files of) the rest.+ *+ * The caller owns `base`: this function mutates it in-memory via `promote()`+ * but does NOT save it (only the caller knows the base file path). Persist the+ * base yourself after this resolves (e.g. `base.save(manifestFor(basePath))`).+ *+ * @param base An opened agenticow memory handle to branch from.+ * @param candidates The A/B candidates β each `{label, fn}`.+ * @param score Scores a candidate's result; higher wins.+ * @param opts Branch-path mapping + persistence knobs.+ */+export async function explore<TResult>(+ base: MemoryHandle,+ candidates: SpeculativeCandidate<TResult>[],+ score: (result: TResult, label: string) => number,+ opts: ExploreOptions,+): Promise<SpeculativeResult<TResult>> {+ if (!base) throw new Error('base memory handle is required');+ if (!Array.isArray(candidates) || candidates.length === 0) {+ throw new Error('at least one candidate is required');+ }+ if (typeof score !== 'function') throw new Error('score function is required');+ if (!opts || typeof opts.branchPath !== 'function') {+ throw new Error('opts.branchPath(label) is required');+ }+ const persist = opts.persist !== false;+ const tieBreak = opts.tieBreak ?? 'first';++ // Reject duplicate labels up front β two branches to the same file would clash.+ const seen = new Set<string>();++ interface Live {+ label: string;+ path: string;+ branch: MemoryHandle;+ result: TResult;+ score: number;+ }+ const live: Live[] = [];++ // 1) Fork + explore each candidate on its own isolated branch.+ for (const c of candidates) {+ const label = validateLabel(c.label);+ if (seen.has(label)) throw new Error(`duplicate candidate label: ${label}`);+ seen.add(label);+ if (typeof c.fn !== 'function') throw new Error(`candidate ${label} is missing fn()`);++ const path = resolveMemoryPath(opts.branchPath(label));+ const branch = base.fork(label, path);+ const result = await c.fn(branch);+ const s = Number(score(result, label));+ live.push({ label, path, branch, result, score: Number.isFinite(s) ? s : -Infinity });+ }++ // 2) Pick the winner (highest score; stable tie-break).+ let winnerIdx = 0;+ for (let i = 1; i < live.length; i++) {+ const better = tieBreak === 'last'+ ? live[i].score >= live[winnerIdx].score+ : live[i].score > live[winnerIdx].score;+ if (better) winnerIdx = i;+ }++ const scores: Record<string, number> = {};+ for (const l of live) scores[l.label] = l.score;++ const winner = live[winnerIdx];+ const receipts: SpeculativeReceipt[] = [];++ // 3) PROMOTION GATE (ADR-171). The top score is a *nominee*, not a promotion.+ // A branch graduates into base only when cleared by a real oracle or an+ // explicitly-accepted Fable judge. proxy:structural / score-only never+ // clears. Fail-closed: requireClearance with no gate = ineligible.+ const gate = opts.clearance;+ const enforce = opts.requireClearance ?? !!gate;+ let promoted = false;+ let promotedBy: PromotionProvenance = 'unverified';+ let promotionDecision: string;+ let promoteStats: { ingested: number; deleted: number } | null = null;++ let clearance: { cleared: boolean; by: PromotionProvenance; reason?: string };+ if (gate) {+ try {+ clearance = await gate(winner.result, winner.label);+ } catch (e) {+ clearance = { cleared: false, by: 'proxy:structural', reason: `clearance threw: ${(e as Error)?.message ?? e}` };+ }+ } else if (enforce) {+ clearance = { cleared: false, by: 'proxy:structural', reason: 'requireClearance set but no clearance gate provided' };+ } else {+ clearance = { cleared: true, by: 'unverified', reason: 'legacy score-only promotion (no gate configured)' };+ }++ // proxy:structural can NEVER clear a promote, regardless of `cleared`.+ const cleared = clearance.cleared+ && (clearance.by === 'oracle:test-exec' || clearance.by === 'judge:fable' || (!enforce && clearance.by === 'unverified'));++ if (cleared) {+ promoteStats = winner.branch.promote(base) as { ingested: number; deleted: number };+ if (persist) winner.branch.save?.(manifestFor(winner.path));+ winner.branch.close?.();+ promoted = true;+ promotedBy = clearance.by;+ promotionDecision = `promoted:${clearance.by}`;+ } else {+ // Winner is ineligible β base stays UNCHANGED. Emit a causal receipt and+ // discard the branch (it did not earn graduation).+ promotedBy = clearance.by;+ promotionDecision = `ineligible:${clearance.by === 'proxy:structural' ? 'proxy-cannot-clear' : clearance.by}`;+ receipts.push({+ label: winner.label,+ score: winner.score,+ diff: safeDiff(winner.branch),+ outcome: 'winner-ineligible',+ provenance: clearance.by,+ reason: clearance.reason ?? 'not cleared by oracle or accepted Fable judge',+ });+ winner.branch.close?.();+ deleteBranchFiles(winner.path);+ }++ // 4) Discard the losers β receipt each, close handle, delete files.+ const discarded: string[] = [];+ for (let i = 0; i < live.length; i++) {+ if (i === winnerIdx) continue;+ receipts.push({+ label: live[i].label,+ score: live[i].score,+ diff: safeDiff(live[i].branch),+ outcome: 'discarded-loser',+ provenance: 'proxy:structural',+ reason: `lower score than winner (${live[i].score} < ${winner.score})`,+ });+ live[i].branch.close?.();+ deleteBranchFiles(live[i].path);+ discarded.push(live[i].label);+ }++ const branches: SpeculativeBranchOutcome<TResult>[] = live.map((l, i) => ({+ label: l.label,+ path: l.path,+ score: l.score,+ result: l.result,+ kept: i === winnerIdx && promoted,+ }));++ return {+ winner: winner.label,+ scores,+ promoted,+ promotedBy,+ promotionDecision,+ promoteStats,+ discarded,+ receipts,+ branches,+ };+}++/**+ * Convenience wrapper that owns the whole lifecycle for a file-path base:+ * loads agenticow (returns `null` when the optional dep is absent), opens the+ * base with its lineage, runs {@link explore}, then persists the mutated base.+ *+ * Returns `null` when agenticow is not installed so callers can emit the+ * standard `{degraded:true}` contract.+ */+export async function exploreFromPath<TResult>(+ basePath: string,+ candidates: SpeculativeCandidate<TResult>[],+ score: (result: TResult, label: string) => number,+ opts: ExploreOptions & { dimension?: number; api?: AgenticowApi },+): Promise<SpeculativeResult<TResult> | null> {+ const api = opts.api ?? (await loadAgenticow());+ if (!api) return null;++ const resolvedBase = resolveMemoryPath(basePath);+ const base = await openWithLineage(api, resolvedBase, opts.dimension);+ try {+ const result = await explore(base, candidates, score, opts);+ if (opts.persist !== false) {+ base.save?.(manifestFor(resolvedBase));+ }+ return result;+ } finally {+ base.close?.();+ }+}diff --git a/v3/@claude-flow/cli/src/commands/autopilot.ts b/v3/@claude-flow/cli/src/commands/autopilot.tsindex 9c420f9153..15d8d11b44 100644--- a/v3/@claude-flow/cli/src/commands/autopilot.ts+++ b/v3/@claude-flow/cli/src/commands/autopilot.ts@@ -12,6 +12,41 @@ import {getProgress, calculateReward, tryLoadLearning, validateNumber,validateTaskSources, LOG_FILE,} from '../autopilot-state.js';+import { getCheckpointGate, CheckpointGate } from '../services/checkpoint-gate.js';++/**+ * Opt-in checkpoint/rollback gate for the autopilot tick (agenticow step 3).+ *+ * The autopilot loop's memory mutation happens OUT OF PROCESS β a re-engaged+ * tick returns a continuation prompt, and the spawned agent (plus agentic-flow+ * learning) mutates `.rvf` memory. So there is no in-process fn to wrap with+ * CheckpointGate.guard() here; instead we bracket the loop across ticks:+ * - checkpoint the configured `.rvf` right before handing off a risky tick+ * (re-engage), and+ * - roll it back when the loop's own regression signal fires (stall auto-disable).+ *+ * Entirely opt-in: it does nothing unless CLAUDE_FLOW_AUTOPILOT_CHECKPOINT_MEM+ * points at an `.rvf` file the loop mutates, agenticow is installed, and the+ * CLAUDE_FLOW_AGENTICOW_DISABLE kill switch is unset. Every call is non-fatal β+ * a checkpoint/rollback failure never breaks the loop.+ */+async function checkpointTick(label: string): Promise<void> {+ const memPath = CheckpointGate.configuredMemPath();+ if (!memPath) return;+ try {+ const r = await getCheckpointGate().checkpoint(memPath, label);+ if (r.ok) appendLog({ ts: Date.now(), event: 'checkpoint', label, memPath });+ } catch { /* non-fatal: memory branching is best-effort */ }+}++async function rollbackTick(reason: string): Promise<void> {+ const memPath = CheckpointGate.configuredMemPath();+ if (!memPath) return;+ try {+ const r = await getCheckpointGate().rollback(memPath);+ if (r.ok) appendLog({ ts: Date.now(), event: 'rollback', reason, memPath });+ } catch { /* non-fatal */ }+}// ββ Check Handler (for Stop hook) βββββββββββββββββββββββββββββ@@ -63,6 +98,9 @@ export async function autopilotCheck(): Promise<{ allowStop: boolean; reason: ststate.enabled = false;saveState(state);appendLog({ ts: Date.now(), event: 'stall-auto-disable', iterations: state.iterations, completed: progress.completed });+ // Regression signal: the loop stalled. Roll `.rvf` memory back to the last+ // good per-tick checkpoint (opt-in via CLAUDE_FLOW_AUTOPILOT_CHECKPOINT_MEM).+ await rollbackTick('stall-auto-disable');return { allowStop: true, reason: `Stalled: no progress in 10 iterations (${progress.completed}/${progress.total} complete)` };}@@ -72,6 +110,10 @@ export async function autopilotCheck(): Promise<{ allowStop: boolean; reason: ststate.history.push({ ts: Date.now(), iteration: state.iterations, completed: progress.completed, total: progress.total });saveState(state);+ // Checkpoint `.rvf` memory before the risky tick runs (opt-in). The next+ // check() rolls back to here if this tick regresses (stall detection above).+ await checkpointTick(`autopilot-iter-${state.iterations}`);+const stallWarning = isStalled? '\nWARNING: No progress in 5 iterations. Consider breaking tasks into smaller subtasks or trying a different approach.': '';diff --git a/v3/@claude-flow/cli/src/commands/neural.ts b/v3/@claude-flow/cli/src/commands/neural.tsindex b1a7a4ab8f..1f367acef8 100644--- a/v3/@claude-flow/cli/src/commands/neural.ts+++ b/v3/@claude-flow/cli/src/commands/neural.ts@@ -4366,11 +4366,303 @@ const routerCommand: Command = {},};+// ============================================================================+// ADR-150 weight-eft slice β `neural distill export | plan | eval | train`+//+// Turns ruflo's captured run transcripts into AUDITED TRAINING DATA + a+// COST-PARETO measurement + a GPU TRAINING PLAN via the optional+// `@metaharness/weight-eft` dependency. HARD honesty rule: this ships training+// DATA + a cost audit + a GPU plan β it does NOT train a model and does NOT+// "reduce escalation". weight-eft's own `train` never spawns; `resolved` in the+// captured archive is a PROXY (no SWE-bench gold oracle). Every path degrades+// gracefully ({degraded:true}) when the optional dep is absent (ADR-150).+// ============================================================================++const distillExportCommand: Command = {+ name: 'export',+ description: 'Export captured run transcripts β SFT (OpenAI chat) + DPO (TRL preference) JSONL + a guard report (contamination / reward-hack / long-context). $0, offline. Does NOT train.',+ options: [+ { name: 'archive', short: 'a', type: 'string', description: 'Run-transcript JSONL to read (default: $CLAUDE_FLOW_RUN_TRANSCRIPTS_PATH or .swarm/run-transcripts.jsonl)' },+ { name: 'out-dir', short: 'o', type: 'string', description: 'Output dir for sft.jsonl / dpo.jsonl / export-report.json', default: '.claude-flow/neural/weft-export' },+ { name: 'eval-holdout', type: 'string', description: 'Comma-separated instance_ids reserved for eval (contamination guard). Excluded + asserted-disjoint.' },+ { name: 'max-tokens', type: 'number', description: 'Per-trajectory token budget (default weight-eft 28000)' },+ { name: 'truncate', type: 'boolean', description: 'Truncate over-length trajectories instead of dropping', default: 'false' },+ { name: 'keep-reward-hacked', type: 'boolean', description: 'Disable the reward-hacking filter (debug only; NOT recommended)', default: 'false' },+ { name: 'format', short: 'f', type: 'string', description: 'Output format: table, json', default: 'table' },+ ],+ examples: [+ { command: 'claude-flow neural distill export', description: 'Export from the default captured .swarm/run-transcripts.jsonl' },+ { command: 'claude-flow neural distill export -a runs.jsonl -o ./out --eval-holdout astropy__astropy-1', description: 'Export a specific archive, holding out one instance' },+ ],+ action: async (ctx: CommandContext): Promise<CommandResult> => {+ const fs = await import('node:fs');+ const path = await import('node:path');+ const { readRunTranscripts } = await import('../ruvector/run-transcript-recorder.js');+ const { buildArchiveFromRecords, runExport } = await import('../services/weight-eft.js');+ const fmt = (ctx.flags.format as string) || 'table';++ const archivePath = (ctx.flags.archive as string | undefined)+ ?? process.env.CLAUDE_FLOW_RUN_TRANSCRIPTS_PATH+ ?? path.resolve(process.cwd(), '.swarm', 'run-transcripts.jsonl');+ const { records, malformed } = readRunTranscripts(archivePath);+ if (records.length === 0) {+ const msg = `No run transcripts at ${archivePath}. Enable capture with CLAUDE_FLOW_RUN_TRANSCRIPTS=1, or pass --archive <file>.`;+ if (fmt === 'json') output.writeln(JSON.stringify({ ok: false, archivePath, records: 0, malformed, error: msg }, null, 2));+ else output.printError(msg);+ return { success: false, exitCode: 1, data: { archivePath, records: 0 } };+ }++ const { trajectories, stats, proxyNote } = buildArchiveFromRecords(records);+ const holdout = ((ctx.flags['eval-holdout'] ?? ctx.flags.evalHoldout) as string | undefined)?.split(',').map((s) => s.trim()).filter(Boolean) ?? [];+ const maxTokens = (ctx.flags['max-tokens'] ?? ctx.flags.maxTokens) != null ? parseInt(String((ctx.flags['max-tokens'] ?? ctx.flags.maxTokens)), 10) : undefined;++ const res = await runExport({+ archive: trajectories,+ evalHoldout: holdout,+ maxTokens,+ truncateOverLength: ctx.flags.truncate === true,+ dropRewardHacked: (ctx.flags['keep-reward-hacked'] ?? ctx.flags.keepRewardHacked) === true ? false : undefined,+ });++ if (res.degraded) {+ // ADR-150 graceful degradation: dep absent β not a runtime failure.+ const payload = { degraded: true, reason: res.reason, archiveTrajectories: trajectories.length };+ if (fmt === 'json') output.writeln(JSON.stringify(payload, null, 2));+ else {+ output.writeln(output.warning(`weight-eft unavailable (${res.reason}).`));+ output.writeln(output.dim('Install the optional dep: npm i @metaharness/weight-eft. Archive was built (' + trajectories.length + ' trajectories) but not exported.'));+ }+ return { success: true, exitCode: 0, data: payload };+ }++ const outDir = path.resolve(process.cwd(), ((ctx.flags['out-dir'] ?? ctx.flags.outDir) as string) || '.claude-flow/neural/weft-export');+ fs.mkdirSync(outDir, { recursive: true });+ const sftPath = path.join(outDir, 'sft.jsonl');+ const dpoPath = path.join(outDir, 'dpo.jsonl');+ const reportPath = path.join(outDir, 'export-report.json');+ fs.writeFileSync(sftPath, res.sftJsonl);+ fs.writeFileSync(dpoPath, res.dpoJsonl);+ fs.writeFileSync(reportPath, JSON.stringify({ report: res.report, archiveStats: stats, proxyNote }, null, 2));++ const payload = {+ ok: true, archivePath, outDir, sftPath, dpoPath, reportPath,+ sftRows: res.sftRows, dpoRows: res.dpoRows, malformed,+ archiveStats: stats, report: res.report, proxyNote,+ };+ if (fmt === 'json') { output.writeln(JSON.stringify(payload, null, 2)); return { success: true, data: payload }; }++ output.writeln();+ output.writeln(output.bold('weight-eft export β audited training data ($0, no model trained)'));+ output.writeln(` archive: ${archivePath} (${records.length} records, ${malformed} malformed skipped)`);+ output.writeln(` trajectories: ${stats.total} (cheap ${stats.byTier.cheap} / frontier ${stats.byTier.frontier}), resolved ${stats.resolved}`);+ output.writeln(` SFT rows: ${res.sftRows} β ${sftPath}`);+ output.writeln(` DPO rows: ${res.dpoRows} β ${dpoPath}`);+ output.writeln(` guards: holdout=${res.report.excludedByHoldout} reward-hacked=${res.report.droppedRewardHacked} over-length=${res.report.droppedOverLength} truncated=${res.report.truncatedOverLength}`);+ output.writeln(` report: ${reportPath}`);+ output.writeln();+ output.writeln(output.warning('resolved provenance: ' + JSON.stringify(stats.byResolvedSource)));+ output.writeln(output.dim(proxyNote));+ return { success: true, data: payload };+ },+};++const distillPlanCommand: Command = {+ name: 'plan',+ description: 'Print the two-stage (SFT β on-policy DPO) GPU training plan + the exact `ruvllm microlora` commands a GPU host would run. $0 dry-run β NEVER spawns a tune.',+ options: [+ { name: 'sft', type: 'string', description: 'Path to sft.jsonl (default: .claude-flow/neural/weft-export/sft.jsonl)' },+ { name: 'dpo', type: 'string', description: 'Path to dpo.jsonl (default: .claude-flow/neural/weft-export/dpo.jsonl)' },+ { name: 'base', short: 'b', type: 'string', description: 'Base model id to tune (7-14B band). Default Qwen2.5-Coder-7B-Instruct' },+ { name: 'params-b', type: 'number', description: 'Base model param count in billions (gate [1,14]). Default 7' },+ { name: 'adapter-prefix', type: 'string', description: 'Adapter output prefix', default: 'ruflo-weft' },+ { name: 'format', short: 'f', type: 'string', description: 'Output format: table, json', default: 'table' },+ ],+ examples: [+ { command: 'claude-flow neural distill plan', description: 'Print the GPU plan for the last export ($0 dry-run)' },+ { command: 'claude-flow neural distill plan --base Qwen/Qwen2.5-Coder-7B-Instruct --params-b 7', description: 'Plan for a specific base model' },+ ],+ action: async (ctx: CommandContext): Promise<CommandResult> => {+ const path = await import('node:path');+ const { runPlan, DEFAULT_BASE_MODEL } = await import('../services/weight-eft.js');+ const fmt = (ctx.flags.format as string) || 'table';+ const sftPath = (ctx.flags.sft as string) || path.resolve(process.cwd(), '.claude-flow/neural/weft-export/sft.jsonl');+ const dpoPath = (ctx.flags.dpo as string) || path.resolve(process.cwd(), '.claude-flow/neural/weft-export/dpo.jsonl');+ const base = ctx.flags.base+ ? { id: String(ctx.flags.base), paramsB: (ctx.flags['params-b'] ?? ctx.flags.paramsB) != null ? parseInt(String((ctx.flags['params-b'] ?? ctx.flags.paramsB)), 10) : 7 }+ : DEFAULT_BASE_MODEL;++ const res = await runPlan({ base, sftPath, dpoPath, adapterPrefix: String((ctx.flags['adapter-prefix'] ?? ctx.flags.adapterPrefix) || 'ruflo-weft') });+ if (res.degraded) {+ const payload = { degraded: true, reason: res.reason };+ if (fmt === 'json') output.writeln(JSON.stringify(payload, null, 2));+ else { output.writeln(output.warning(`weight-eft unavailable (${res.reason}).`)); output.writeln(output.dim('Install: npm i @metaharness/weight-eft')); }+ return { success: true, exitCode: 0, data: payload };+ }+ const payload = { ok: true, base: res.base, sft: res.sft, dpo: res.dpo, dryRun: true };+ if (fmt === 'json') { output.writeln(JSON.stringify(payload, null, 2)); return { success: true, data: payload }; }+ output.writeln();+ output.writeln(output.bold(`weight-eft GPU training plan ($0 dry-run β no tune runs from ruflo)`));+ output.writeln(` base model: ${res.base.id} (${res.base.paramsB}B)`);+ output.writeln(output.dim(' SFT stage:'));+ output.writeln(` ${res.sft.summary}`);+ output.writeln(` $ ${res.sft.command}`);+ output.writeln(output.dim(' DPO stage (on-policy, init from SFT adapter):'));+ output.writeln(` ${res.dpo.summary}`);+ output.writeln(` $ ${res.dpo.command}`);+ output.writeln();+ output.writeln(output.dim('These commands run on a GPU host; ruflo does not execute them. See `neural distill train --remote` for a spend-gated remote path.'));+ return { success: true, data: payload };+ },+};++const distillEvalCommand: Command = {+ name: 'eval',+ description: 'Fold two CascadeOutcome[] JSON files (base vs adapter) into the cost-Pareto delta β escalation-rate reduction + $/resolved. $0. Measures cost, does NOT claim a tune ran.',+ options: [+ { name: 'base-outcomes', type: 'string', description: 'JSON file: CascadeOutcome[] for the BASE cascade run', required: true },+ { name: 'adapter-outcomes', type: 'string', description: 'JSON file: CascadeOutcome[] for the ADAPTER cascade run', required: true },+ { name: 'format', short: 'f', type: 'string', description: 'Output format: table, json', default: 'table' },+ ],+ examples: [+ { command: 'claude-flow neural distill eval --base-outcomes base.json --adapter-outcomes adapter.json', description: 'Cost-Pareto delta between base and adapter cascade runs' },+ ],+ action: async (ctx: CommandContext): Promise<CommandResult> => {+ const fs = await import('node:fs');+ const { runEval } = await import('../services/weight-eft.js');+ const fmt = (ctx.flags.format as string) || 'table';+ const basePath = (ctx.flags['base-outcomes'] ?? ctx.flags.baseOutcomes) as string | undefined;+ const adapterPath = (ctx.flags['adapter-outcomes'] ?? ctx.flags.adapterOutcomes) as string | undefined;+ if (!basePath || !adapterPath) {+ output.printError('Both --base-outcomes and --adapter-outcomes are required.');+ return { success: false, exitCode: 2 };+ }+ let baseOutcomes: unknown; let adapterOutcomes: unknown;+ try {+ baseOutcomes = JSON.parse(fs.readFileSync(basePath, 'utf8'));+ adapterOutcomes = JSON.parse(fs.readFileSync(adapterPath, 'utf8'));+ } catch (e) {+ output.printError(`Failed to read outcome files: ${(e as Error).message}`);+ return { success: false, exitCode: 1 };+ }+ if (!Array.isArray(baseOutcomes) || !Array.isArray(adapterOutcomes)) {+ output.printError('Both files must contain a JSON array of CascadeOutcome objects.');+ return { success: false, exitCode: 1 };+ }+ const res = await runEval({ baseOutcomes: baseOutcomes as never, adapterOutcomes: adapterOutcomes as never });+ if (res.degraded) {+ const payload = { degraded: true, reason: res.reason };+ if (fmt === 'json') output.writeln(JSON.stringify(payload, null, 2));+ else { output.writeln(output.warning(`weight-eft unavailable (${res.reason}).`)); output.writeln(output.dim('Install: npm i @metaharness/weight-eft')); }+ return { success: true, exitCode: 0, data: payload };+ }+ if (fmt === 'json') { output.writeln(JSON.stringify({ ok: true, delta: res.delta }, null, 2)); return { success: true, data: res.delta }; }+ output.writeln();+ output.writeln(output.bold('weight-eft cost-Pareto delta (measurement only)'));+ output.writeln(` cheap-resolve lift: ${res.delta.cheapResolveLift.toFixed(4)}`);+ output.writeln(` escalation-rate reduction: ${res.delta.escalationRateReduction.toFixed(4)}`);+ output.writeln(` $/resolved reduction: ${res.delta.costPerResolvedReduction.toFixed(6)}`);+ output.writeln(` resolve-rate delta: ${res.delta.resolveRateDelta.toFixed(4)} (expected β 0 β ceiling unmoved)`);+ output.writeln(` verdict: ${res.delta.verdict}`);+ return { success: true, data: res.delta };+ },+};++const distillTrainCommand: Command = {+ name: 'train',+ description: 'Remote-GPU LoRA tune over SSH β DRY-RUN by default (prints ssh/rsync/ruvllm commands + read-only preflight). Real compute ONLY with --execute --yes (spends GPU time on YOUR host). Not a $0/local tune.',+ options: [+ { name: 'remote', short: 'r', type: 'string', description: 'SSH host or tailscale name (default: $RUFLO_DISTILL_REMOTE). Never hard-coded.' },+ { name: 'base', short: 'b', type: 'string', description: 'Base model id to tune. Default Qwen2.5-Coder-7B-Instruct' },+ { name: 'sft', type: 'string', description: 'Local sft.jsonl (default: .claude-flow/neural/weft-export/sft.jsonl)' },+ { name: 'dpo', type: 'string', description: 'Local dpo.jsonl (default: .claude-flow/neural/weft-export/dpo.jsonl)' },+ { name: 'adapter-dir', type: 'string', description: 'Local dir to fetch the trained adapter into', default: '.claude-flow/neural' },+ { name: 'ssh-user', type: 'string', description: 'SSH user (default: current user)' },+ { name: 'ssh-port', type: 'number', description: 'SSH port', default: '22' },+ { name: 'remote-workdir', type: 'string', description: 'Remote working dir (default: ~/.ruflo-weft/<runId>)' },+ { name: 'execute', type: 'boolean', description: 'Opt in to REAL GPU compute on the remote host (still needs --yes)', default: 'false' },+ { name: 'yes', type: 'boolean', description: 'Second confirmation gate; required with --execute to actually spend', default: 'false' },+ { name: 'preflight', type: 'boolean', description: 'Opt in to read-only reachability/GPU probes against the host (bare dry-run is fully offline and contacts nothing)', default: 'false' },+ { name: 'format', short: 'f', type: 'string', description: 'Output format: table, json', default: 'table' },+ ],+ examples: [+ { command: 'claude-flow neural distill train --remote gpu-box', description: 'OFFLINE DRY-RUN: print the ssh/rsync/ruvllm commands only (no host contact)' },+ { command: 'claude-flow neural distill train --remote gpu-box --preflight', description: 'DRY-RUN + read-only reachability/GPU probes against the host' },+ { command: 'RUFLO_DISTILL_REMOTE=gpu-box claude-flow neural distill train --execute --yes', description: 'Run the real remote tune (spends GPU time on your host)' },+ ],+ action: async (ctx: CommandContext): Promise<CommandResult> => {+ const path = await import('node:path');+ const { runRemoteTrain } = await import('../services/weight-eft.js');+ const fmt = (ctx.flags.format as string) || 'table';+ const host = (ctx.flags.remote as string | undefined) || process.env.RUFLO_DISTILL_REMOTE;+ if (!host) {+ output.printError('No remote host. Pass --remote <host> or set RUFLO_DISTILL_REMOTE.');+ return { success: false, exitCode: 2 };+ }+ const res = await runRemoteTrain({+ host,+ base: ctx.flags.base ? String(ctx.flags.base) : undefined,+ sftPath: (ctx.flags.sft as string) || path.resolve(process.cwd(), '.claude-flow/neural/weft-export/sft.jsonl'),+ dpoPath: (ctx.flags.dpo as string) || path.resolve(process.cwd(), '.claude-flow/neural/weft-export/dpo.jsonl'),+ adapterDir: ((ctx.flags['adapter-dir'] ?? ctx.flags.adapterDir) as string) || '.claude-flow/neural',+ sshUser: (ctx.flags['ssh-user'] ?? ctx.flags.sshUser) ? String((ctx.flags['ssh-user'] ?? ctx.flags.sshUser)) : undefined,+ sshPort: (ctx.flags['ssh-port'] ?? ctx.flags.sshPort) != null ? parseInt(String((ctx.flags['ssh-port'] ?? ctx.flags.sshPort)), 10) : undefined,+ remoteWorkdir: (ctx.flags['remote-workdir'] ?? ctx.flags.remoteWorkdir) ? String((ctx.flags['remote-workdir'] ?? ctx.flags.remoteWorkdir)) : undefined,+ execute: ctx.flags.execute === true,+ yes: ctx.flags.yes === true,+ preflight: ctx.flags.preflight === true,+ });++ if ('degraded' in res && res.degraded) {+ const payload = { degraded: true, reason: res.reason };+ if (fmt === 'json') output.writeln(JSON.stringify(payload, null, 2));+ else output.writeln(output.warning(`remote-train unavailable (${res.reason}).`));+ return { success: true, exitCode: 0, data: payload };+ }+ if (fmt === 'json') { output.writeln(JSON.stringify(res, null, 2)); return { success: res.mode !== 'preflight-failed', data: res }; }++ output.writeln();+ output.writeln(output.bold(`weight-eft remote-GPU tune [${res.mode}] on ${res.plan.host}`));+ if (res.mode === 'dry-run') output.writeln(output.dim('DRY-RUN β no data transferred, no training. Re-run with --execute --yes to spend GPU time on your host.'));+ if (res.reason) output.writeln(output.warning(res.reason));+ output.writeln(` base: ${res.plan.base} remote workdir: ${res.plan.remoteWorkdir} adapter β ${res.plan.adapterDir}/${res.plan.dpoAdapter}`);+ if (res.preflight) {+ output.writeln(output.dim(' preflight (read-only probes):'));+ for (const p of res.preflight) output.writeln(` [${p.ok ? 'ok ' : 'FAIL'}] ${p.label}: ${p.detail}`);+ }+ output.writeln(output.dim(' commands that ' + (res.mode === 'executed' ? 'ran' : 'WOULD run') + ':'));+ for (const c of res.plan.humanCommands) output.writeln(` $ ${c}`);+ if (res.steps) {+ output.writeln(output.dim(' execution:'));+ for (const s of res.steps) output.writeln(` [${s.ok ? 'ok ' : 'FAIL'}] ${s.label}: ${s.detail}`);+ }+ output.writeln();+ output.writeln(output.dim('Honesty: ruflo does not train locally or at $0. This is an explicit, user-triggered remote-GPU spend. resolved-gold in the SFT data is still a proxy.'));+ return { success: res.mode !== 'preflight-failed', data: res };+ },+};++const distillCommand: Command = {+ name: 'distill',+ description: 'weight-eft training-data + cost-audit slice (ADR-150): export | plan | eval | train. Ships audited SFT/DPO data + a cost-Pareto measurement + a GPU plan. Does NOT train a model or reduce escalation.',+ subcommands: [distillExportCommand, distillPlanCommand, distillEvalCommand, distillTrainCommand],+ examples: [+ { command: 'claude-flow neural distill export', description: 'Captured transcripts β audited SFT/DPO JSONL + guard report ($0)' },+ { command: 'claude-flow neural distill plan', description: 'Print the GPU training plan + ruvllm commands ($0 dry-run)' },+ { command: 'claude-flow neural distill eval --base-outcomes b.json --adapter-outcomes a.json', description: 'Cost-Pareto delta ($0)' },+ { command: 'claude-flow neural distill train --remote gpu-box', description: 'Remote-GPU tune DRY-RUN (spend-gated behind --execute --yes)' },+ ],+ action: async (): Promise<CommandResult> => {+ output.writeln('Use a subcommand: export | plan | eval | train');+ output.writeln(output.dim('Ships audited training DATA + a cost audit + a GPU plan. It does NOT train a model or reduce escalation (weight-eft train never spawns; resolved is a proxy).'));+ return { success: true };+ },+};+// Main neural commandexport const neuralCommand: Command = {name: 'neural',description: 'Neural pattern training, MoE, Flash Attention, pattern learning',- subcommands: [trainCommand, statusCommand, patternsCommand, predictCommand, optimizeCommand, benchmarkCommand, listCommand, exportCommand, importCommand, routerCommand],+ subcommands: [trainCommand, statusCommand, patternsCommand, predictCommand, optimizeCommand, benchmarkCommand, listCommand, exportCommand, importCommand, routerCommand, distillCommand],examples: [{ command: 'claude-flow neural status', description: 'Check neural system status' },{ command: 'claude-flow neural train -p coordination', description: 'Train coordination patterns' },diff --git a/v3/@claude-flow/cli/src/mcp-client.ts b/v3/@claude-flow/cli/src/mcp-client.tsindex 4efe5f7244..0a9f4a9f02 100644--- a/v3/@claude-flow/cli/src/mcp-client.ts+++ b/v3/@claude-flow/cli/src/mcp-client.ts@@ -53,6 +53,9 @@ import { metaharnessTools } from './mcp-tools/metaharness-tools.js';// agenticow@~0.2.3 β Copy-On-Write memory branching tools (162-byte branches);// optional runtime dep, every handler returns `{degraded: true}` when missing.import { agenticowTools } from './mcp-tools/agenticow-tools.js';+// agenticow step 4 β speculative branch-and-promote (A/B memory exploration).+// Optional runtime dep, degrades to `{degraded: true}` when agenticow is missing.+import { agenticowSpeculateTools } from './mcp-tools/agenticow-speculate-tools.js';// ADR-164 β AgentBBS federated business-domain BBS rooms (Phase 1).// Optional runtime dep, every handler returns `{degraded: true}` when missing.import { agentbbsTools } from './mcp-tools/agentbbs-tools.js';@@ -146,8 +149,10 @@ registerTools([...coverageRouterTools,// ADR-150 β MetaHarness static-analysis tools (5)...metaharnessTools,- // agenticow@~0.2.3 β COW memory branching (4 tools, graceful-degraded when missing)+ // agenticow@~0.2.4 β COW memory branching (9 tools: branch/checkpoint/rollback/promote + ingest/query/diff/lineage/status, graceful-degraded when missing)...agenticowTools,+ // agenticow step 4 β speculative branch-and-promote (1 tool, graceful-degraded when missing)+ ...agenticowSpeculateTools,// ADR-164 β AgentBBS federated business-domain BBS rooms (4 tools, Phase 1, graceful-degraded)...agentbbsTools,// ADR-164 Phase 2 + Phase 3 β business_pod_validate + business_pod_route_backenddiff --git a/v3/@claude-flow/cli/src/mcp-tools/agent-execute-core.ts b/v3/@claude-flow/cli/src/mcp-tools/agent-execute-core.tsindex e936b05301..13e04d58e9 100644--- a/v3/@claude-flow/cli/src/mcp-tools/agent-execute-core.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/agent-execute-core.ts@@ -628,6 +628,37 @@ export async function executeAgentTask(input: AgentExecuteInput): Promise<AgentE});} catch { /* never break execution */ }}+ // ADR-150 weight-eft capture seam β the ONLY place a run's full outcome is+ // known here: prompt (issue), assistant transcript, model, tier, and a+ // resolved PROXY. Gated behind CLAUDE_FLOW_RUN_TRANSCRIPTS=1 (off by+ // default; PII/retention surface, mirrors the router trajectory recorder).+ // HONESTY: `resolved` here is the WEAKEST proxy β 'api-success' means only+ // that the model returned without an API error, NOT that the output is+ // correct (ruflo has no SWE-bench gold oracle). model_patch is '' because+ // this single-shot execute path produces no unified diff. Both facts are+ // stamped so no downstream weight-eft export mistakes this for gold data.+ if (process.env.CLAUDE_FLOW_RUN_TRANSCRIPTS === '1') {+ try {+ const { recordRunTranscript, tierForModel } = await import('../ruvector/run-transcript-recorder.js');+ const modelId = agent.modelId ?? String(agent.model ?? 'unknown');+ const messages: Array<{ role: 'system' | 'user' | 'assistant'; content: string }> = [];+ if (systemPrompt) messages.push({ role: 'system', content: systemPrompt });+ messages.push({ role: 'user', content: input.prompt });+ if (result.success && typeof result.output === 'string') {+ messages.push({ role: 'assistant', content: result.output });+ }+ recordRunTranscript({+ task: input.prompt,+ model: modelId,+ tier: tierForModel(modelId),+ resolved: outcome === 'success',+ resolvedSource: 'api-success',+ messages,+ source: 'agent-execute',+ tokens: result.usage ? { input: result.usage.inputTokens, output: result.usage.outputTokens } : undefined,+ });+ } catch { /* never break execution */ }+ }} catch {// Silent β bandit feedback must never block routing.}diff --git a/v3/@claude-flow/cli/src/mcp-tools/agent-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/agent-tools.tsindex 3d2d694172..8f0add7ca3 100644--- a/v3/@claude-flow/cli/src/mcp-tools/agent-tools.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/agent-tools.ts@@ -42,6 +42,14 @@ interface AgentRecord {/** ADR-148 β concrete OpenRouter slug when provider='openrouter'. */openrouterModel?: string;lastResult?: Record<string, unknown>;+ /**+ * ACOW β path to this agent's per-agent Copy-On-Write memory branch+ * (agenticow), set only when the agent was spawned with `memoryBase`. On+ * terminate the branch is promoted (merged to base) or discarded.+ */+ memoryBranch?: string;+ /** ACOW β the shared base `.rvf` this agent's branch was forked from. */+ memoryBase?: string;}interface AgentStore {@@ -286,6 +294,8 @@ export const agentTools: MCPTool[] = [description: 'Claude model alias (haiku=fast/cheap, sonnet=balanced, opus=current Opus 4.8, opus-4.7=prior Opus pin)'},task: { type: 'string', description: 'Task description for intelligent model routing' },+ memoryBase: { type: 'string', description: 'Opt-in: base .rvf memory file to fork a per-agent Copy-On-Write branch from (agenticow). When set, the agent gets an isolated ~162-byte COW branch instead of a full copy β promote on success, discard on terminate. Requires the optional `agenticow` dep; degrades to a no-op when absent or when CLAUDE_FLOW_NO_COW_MEMORY=1.' },+ memoryDimension: { type: 'integer', description: 'Vector dimension for the COW base (required only when memoryBase does not exist yet)' },},required: ['agentType'],},@@ -370,6 +380,31 @@ export const agentTools: MCPTool[] = [await addNode({ id: agentId, type: 'agent', name: agentType });} catch { /* graph-node not available */ }+ // ACOW β opt-in per-agent COW memory branch. Only when the caller+ // supplies `memoryBase` does the agent get an isolated 162-byte branch+ // (vs a full .rvf copy). Lazy-imported so agenticow stays off the+ // startup path. Non-fatal: a branch failure never blocks the spawn β+ // the agent is already registered above.+ let memoryBranch: string | undefined;+ if (input.memoryBase) {+ try {+ const { SwarmMemoryBranches } = await import('../services/swarm-memory-branches.js');+ const svc = new SwarmMemoryBranches();+ const br = await svc.branchForAgent(String(input.memoryBase), agentId, {+ dimension: typeof input.memoryDimension === 'number' ? input.memoryDimension : undefined,+ });+ if (br.branchPath) {+ memoryBranch = br.branchPath;+ agent.memoryBranch = br.branchPath;+ agent.memoryBase = br.basePath;+ store.agents[agentId] = agent;+ saveAgentStore(store);+ }+ // else: degraded (agenticow missing / kill-switched) β agent stands+ // without an isolated branch; callers see no memoryBranch field.+ } catch { /* COW branch is best-effort; agent already registered */ }+ }+// Include deterministic codemod routing info if applicableconst response: Record<string, unknown> = {success: true,@@ -382,6 +417,7 @@ export const agentTools: MCPTool[] = [...(routingResult.openrouterModel ? { openrouterModel: routingResult.openrouterModel } : {}),status: 'registered',createdAt: agent.createdAt,+ ...(memoryBranch ? { memoryBranch, memoryBase: agent.memoryBase } : {}),note: 'Agent registered for coordination. Three execution paths: ' +'(1) call agent_execute(agentId, prompt) β direct LLM call via Anthropic Messages API (requires ANTHROPIC_API_KEY); ' +'(2) Claude Code Task tool β spawns a real subagent; ' +@@ -450,6 +486,7 @@ export const agentTools: MCPTool[] = [properties: {agentId: { type: 'string', description: 'ID of agent to terminate' },force: { type: 'boolean', description: 'Force immediate termination' },+ promoteMemory: { type: 'boolean', description: 'When the agent has a per-agent COW memory branch (spawned with memoryBase), promote (merge) its edits into the shared base on terminate. Default false β discard the branch (throw its edits away). No-op when the agent has no branch.' },},required: ['agentId'],},@@ -461,13 +498,31 @@ export const agentTools: MCPTool[] = [const agentId = input.agentId as string;if (store.agents[agentId]) {- store.agents[agentId].status = 'terminated';+ const rec = store.agents[agentId];+ rec.status = 'terminated';saveAgentStore(store);++ // ACOW β resolve the agent's COW memory branch on teardown: promote+ // (merge into base) when asked, else discard. Non-fatal β a failure+ // here never blocks termination. Discard needs no agenticow (pure fs),+ // so cleanup still works in the degraded path.+ let memory: Record<string, unknown> | undefined;+ if (rec.memoryBranch) {+ try {+ const { SwarmMemoryBranches } = await import('../services/swarm-memory-branches.js');+ const svc = new SwarmMemoryBranches();+ memory = input.promoteMemory+ ? (await svc.promoteAgent(agentId)) as unknown as Record<string, unknown>+ : (await svc.discardAgent(agentId)) as unknown as Record<string, unknown>;+ } catch { /* best-effort teardown */ }+ }+return {success: true,agentId,terminated: true,terminatedAt: new Date().toISOString(),+ ...(memory ? { memory } : {}),};}diff --git a/v3/@claude-flow/cli/src/mcp-tools/agenticow-loader.ts b/v3/@claude-flow/cli/src/mcp-tools/agenticow-loader.tsnew file mode 100644index 0000000000..19254a8e49--- /dev/null+++ b/v3/@claude-flow/cli/src/mcp-tools/agenticow-loader.ts@@ -0,0 +1,113 @@+/**+ * Agenticow shared loader + helpers.+ *+ * Extracted from `agenticow-tools.ts` so both the MCP tool surface AND the+ * `SwarmMemoryBranches` service (src/services/swarm-memory-branches.ts) share+ * one loader, one degradation contract, and one set of path/lineage helpers β+ * rather than duplicating the optional-dep dance in two places.+ *+ * Architectural constraint (ADR-150, mirrors metaharness-tools.ts):+ * - `agenticow` lives in `optionalDependencies` β never a hard runtime dep.+ * - When the package is missing, callers get `null` from `loadAgenticow()`+ * (or a `{degraded:true}` result via `degradedResult`) and MUST fall back+ * gracefully β never throw a MODULE_NOT_FOUND.+ *+ * @module @claude-flow/cli/mcp-tools/agenticow-loader+ */++import { existsSync } from 'node:fs';+import { resolve, isAbsolute } from 'node:path';+import { getProjectCwd } from './types.js';++export const PACKAGE_NAME = 'agenticow';++export interface AgenticowApi {+ open: (file: string, opts?: { dimension?: number; metric?: string }) => Promise<any>;+ openBase?: (file: string, opts?: any) => Promise<any>;+ AgenticMemory: any;+}++// Cache: module load is expensive enough to amortize across handler calls.+// null = not yet attempted; false = attempted and unavailable; module = loaded.+let _agenticowMod: any = null;+let _loadAttempted = false;++/**+ * Lazily import `agenticow`. Returns the module on success, or `null` when the+ * package is not installed (the optional-dep degraded path). Any OTHER load+ * error (e.g. a corrupt install) is re-thrown so it is not silently masked.+ */+export async function loadAgenticow(): Promise<AgenticowApi | null> {+ if (_loadAttempted) return _agenticowMod || null;+ _loadAttempted = true;+ try {+ _agenticowMod = await import(PACKAGE_NAME);+ return _agenticowMod;+ } catch (err: any) {+ if (err && (err.code === 'ERR_MODULE_NOT_FOUND' || err.code === 'MODULE_NOT_FOUND' ||+ /Cannot find (module|package)/i.test(String(err.message)))) {+ _agenticowMod = false;+ return null;+ }+ throw err;+ }+}++/** Reset the module-level load cache. Test-only seam. */+export function __resetAgenticowCache(): void {+ _agenticowMod = null;+ _loadAttempted = false;+}++export function degradedResult(reason: string): { success: true; degraded: true; reason: string } {+ return { success: true, degraded: true, reason };+}++/**+ * Resolve a user-supplied memory path against the project cwd, rejecting path+ * traversal and NUL bytes (D-2 style hardening β same rule the MCP verbs use).+ */+export function resolveMemoryPath(path: string): string {+ if (!path || typeof path !== 'string') throw new Error('memory path is required');+ if (/\.\.[\\/]|\0/.test(path)) throw new Error('memory path contains disallowed characters');+ return isAbsolute(path) ? path : resolve(getProjectCwd(), path);+}++/**+ * Lineage manifest companion path. agenticow persists the COW chain+ * (working β checkpoints β base) into `<file>.agenticow.json` next to the+ * `.rvf` data file. Without it, forks/checkpoints are in-memory only and+ * disappear when the AgenticMemory handle closes.+ */+export function manifestFor(file: string): string {+ return `${file}.agenticow.json`;+}++/** Validate a COW branch/checkpoint label (alnum + a small safe symbol set). */+export function validateLabel(label: string): string {+ if (!label || typeof label !== 'string') throw new Error('label is required');+ if (label.length > 256) throw new Error('label exceeds 256 chars');+ if (!/^[A-Za-z0-9_.\-:/@]+$/.test(label)) {+ throw new Error('label may only contain [A-Za-z0-9_.\\-:/@]');+ }+ return label;+}++/**+ * Open (or create) a memory file, restoring its COW chain from the lineage+ * manifest when one exists. When neither the `.rvf` nor the manifest exists,+ * `dimension` is required to create a fresh base.+ */+export async function openWithLineage(api: AgenticowApi, file: string, dimension?: number) {+ const manifest = manifestFor(file);+ if (existsSync(manifest)) {+ return (api.AgenticMemory as any).load(manifest);+ }+ const opts: any = {};+ if (typeof dimension === 'number' && Number.isInteger(dimension) && dimension > 0) {+ opts.dimension = dimension;+ } else if (!existsSync(file)) {+ throw new Error('dimension is required when creating a new memory file');+ }+ return api.open(file, opts);+}diff --git a/v3/@claude-flow/cli/src/mcp-tools/agenticow-speculate-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/agenticow-speculate-tools.tsnew file mode 100644index 0000000000..0a9b973bb7--- /dev/null+++ b/v3/@claude-flow/cli/src/mcp-tools/agenticow-speculate-tools.ts@@ -0,0 +1,236 @@+/**+ * agenticow speculate β MCP surface for speculative branch-and-promote+ * (agenticow step 4).+ *+ * Exposes the `SpeculativeExploration` module as a single MCP tool+ * `agenticow_speculate` so agents can drive parallel A/B memory exploration:+ * fan out N candidate ingest-sets, each on its own 162-byte COW branch of a+ * shared base `.rvf`, score them by a probe query, PROMOTE the winner into+ * base, and DISCARD the losers (delete their branch files).+ *+ * Because MCP inputs are JSON (not JS functions), candidates are DECLARATIVE:+ * each candidate is a label + a set of vectors to ingest, and scoring is a+ * probe query (`nearest`) or an ingest count (`count`). The generic+ * `explore(base, {label, fn}[], score)` core does the real work.+ *+ * Optional-dep contract (mirrors agenticow-tools.ts): when `agenticow` is not+ * installed the tool returns `{success:true, degraded:true,+ * reason:'agenticow-not-found'}` and never throws for that reason.+ *+ * @module @claude-flow/cli/mcp-tools/agenticow-speculate+ */++import type { MCPTool } from './types.js';+import {+ loadAgenticow,+ degradedResult,+ resolveMemoryPath,+ openWithLineage,+ manifestFor,+ validateLabel,+} from './agenticow-loader.js';+import {+ explore,+ type SpeculativeCandidate,+} from '../agenticow/speculative-exploration.js';++interface IngestRecordInput {+ id?: number;+ vector: number[];+ text?: string;+}++interface CandidateInput {+ label: string;+ ingest: IngestRecordInput[];+ branchPath?: string;+}++/** What each candidate's `fn` returns: the ingest result + probe hits. */+interface CandidateOutcome {+ accepted: number;+ bestDistance: number | null;+ hits: Array<{ id: number; distance: number }>;+}++/** Turn a validated label into a filesystem-safe branch filename segment. */+function safeSegment(label: string): string {+ return label.replace(/[^A-Za-z0-9_-]+/g, '_').slice(0, 64) || 'branch';+}++export const agenticowSpeculateTools: MCPTool[] = [+ {+ name: 'agenticow_speculate',+ description:+ "agenticow β speculative branch-and-promote for parallel A/B memory exploration. " ++ "Forks a 162-byte COW branch per candidate off a shared base .rvf, ingests each candidate's " ++ "vectors into its OWN isolated branch, scores every branch (probe-query 'nearest' distance or " ++ "ingest 'count'), PROMOTES the winning branch's edits into base, and DISCARDS the losers by " ++ "deleting their branch files. Use when you want to try N competing memory-write strategies and " ++ "keep only the best β the memory-state analogue of worktree-per-agent code exploration. " ++ "Copying the base per candidate is wrong (full-copy snapshots grow linearly, the 3.3 GB Darwin " ++ "bloat); COW forks are constant-size and losers cost ~162 B to throw away. Optional dep β " ++ "degrades to {degraded:true} when agenticow is missing.",+ category: 'memory',+ tags: ['agenticow', 'memory', 'cow', 'speculative', 'branch', 'promote', 'ab'],+ inputSchema: {+ type: 'object',+ properties: {+ basePath: {+ type: 'string',+ description: 'Path to base .rvf memory file (absolute or relative to cwd)',+ },+ dimension: {+ type: 'integer',+ description: 'Vector dimension (required only when basePath does not exist yet)',+ },+ candidates: {+ type: 'array',+ description: 'The A/B candidates. Each explores its own COW branch.',+ items: {+ type: 'object',+ properties: {+ label: { type: 'string', description: 'Branch label (alnum + _.-:/@ only)' },+ ingest: {+ type: 'array',+ description: 'Vectors to ingest into this candidate branch',+ items: {+ type: 'object',+ properties: {+ id: { type: 'integer', description: 'Explicit vector id (auto when omitted)' },+ vector: { type: 'array', items: { type: 'number' }, description: 'Dense vector' },+ text: { type: 'string', description: 'Optional payload text' },+ },+ required: ['vector'],+ },+ },+ branchPath: {+ type: 'string',+ description: 'Optional explicit path for this branch file (default: alongside base)',+ },+ },+ required: ['label', 'ingest'],+ },+ },+ probe: {+ type: 'array',+ items: { type: 'number' },+ description: "Probe vector for scoreBy='nearest' (scores each branch by best-hit similarity)",+ },+ k: { type: 'integer', description: 'Nearest-neighbours to fetch per probe (default 1)' },+ scoreBy: {+ type: 'string',+ enum: ['nearest', 'count'],+ description: "'nearest' = closest probe distance wins; 'count' = most accepted ingests wins. Default 'nearest'.",+ },+ requireClearance: {+ type: 'boolean',+ description: 'ADR-171 fail-closed gate. When true, the top-scored winner is NOT promoted (base stays unchanged) and a provenance-tagged receipt is emitted β score alone cannot graduate work. Use when speculating over TASK outcomes rather than pure memory A/B. Default false (score-only promotion, tagged `unverified`).',+ default: false,+ },+ },+ required: ['basePath', 'candidates'],+ },+ handler: async (input) => {+ const api = await loadAgenticow();+ if (!api) return degradedResult('agenticow-not-found');++ const basePath = resolveMemoryPath(String(input.basePath));+ const dimension = input.dimension as number | undefined;+ const scoreBy = (input.scoreBy as string) === 'count' ? 'count' : 'nearest';+ const k = Number.isInteger(input.k) && (input.k as number) > 0 ? (input.k as number) : 1;+ const probe = Array.isArray(input.probe) ? (input.probe as number[]) : null;++ const rawCandidates = input.candidates as CandidateInput[];+ if (!Array.isArray(rawCandidates) || rawCandidates.length === 0) {+ throw new Error('at least one candidate is required');+ }+ if (scoreBy === 'nearest' && !probe) {+ throw new Error("scoreBy='nearest' requires a probe vector");+ }++ // Build the generic {label, fn} candidates. Each fn ingests into its own+ // branch handle, then (for 'nearest') probes it so we can score.+ const candidates: SpeculativeCandidate<CandidateOutcome>[] = rawCandidates.map((c) => {+ const label = validateLabel(String(c.label));+ if (!Array.isArray(c.ingest) || c.ingest.length === 0) {+ throw new Error(`candidate ${label} must ingest at least one vector`);+ }+ const records = c.ingest.map((r) => ({+ ...(Number.isInteger(r.id) ? { id: r.id as number } : {}),+ vector: r.vector,+ ...(typeof r.text === 'string' ? { text: r.text } : {}),+ }));+ return {+ label,+ fn: (branch: any): CandidateOutcome => {+ const res = branch.ingest(records);+ const accepted = Number(res?.accepted ?? records.length);+ let hits: Array<{ id: number; distance: number }> = [];+ if (probe) {+ hits = (branch.query(probe, k) || []).map((h: any) => ({+ id: h.id,+ distance: h.distance,+ }));+ }+ const bestDistance = hits.length ? hits[0].distance : null;+ return { accepted, bestDistance, hits };+ },+ };+ });++ const score = (r: CandidateOutcome): number => {+ if (scoreBy === 'count') return r.accepted;+ // nearest: smaller distance = better. Map to a higher-is-better score.+ if (r.bestDistance === null) return -Infinity;+ return 1 / (1 + Math.max(0, r.bestDistance));+ };++ const branchPath = (label: string): string => {+ const explicit = rawCandidates.find((c) => validateLabel(String(c.label)) === label)?.branchPath;+ if (explicit) return resolveMemoryPath(String(explicit));+ return `${basePath}.spec-${safeSegment(label)}.rvf`;+ };++ // ADR-171 promotion gate. For pure memory A/B the `score` IS the chosen+ // metric (not a proxy for task correctness), so score-only promotion is+ // legitimate and stays the default (tagged `unverified`, never+ // masquerading as ground truth). Callers grafting this onto TASK work+ // pass requireClearance:true to fail-closed β the winner is then+ // ineligible unless a real clearance mechanism graduates it.+ const requireClearance = input.requireClearance === true;+ const exploreOpts: Parameters<typeof explore>[3] = { branchPath, persist: true };+ if (requireClearance) exploreOpts.requireClearance = true;++ // Open base, run the speculative exploration, persist base with the winner promoted.+ const base = await openWithLineage(api, basePath, dimension);+ try {+ const result = await explore(base, candidates, score, exploreOpts);+ base.save?.(manifestFor(basePath));+ return {+ success: true,+ basePath,+ scoreBy,+ winner: result.winner,+ scores: result.scores,+ promoted: result.promoted,+ promotedBy: result.promotedBy,+ promotionDecision: result.promotionDecision,+ promoteStats: result.promoteStats,+ discarded: result.discarded,+ receipts: result.receipts,+ branches: result.branches.map((b) => ({+ label: b.label,+ path: b.path,+ score: b.score,+ kept: b.kept,+ accepted: b.result.accepted,+ bestDistance: b.result.bestDistance,+ })),+ };+ } finally {+ await base.close?.();+ }+ },+ },+];diff --git a/v3/@claude-flow/cli/src/mcp-tools/agenticow-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/agenticow-tools.tsindex 4e8d71a848..df96d41d50 100644--- a/v3/@claude-flow/cli/src/mcp-tools/agenticow-tools.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/agenticow-tools.ts@@ -32,91 +32,18 @@* @module @claude-flow/cli/mcp-tools/agenticow*/-import { existsSync } from 'node:fs';import type { MCPTool } from './types.js';-import { getProjectCwd } from './types.js';-import { resolve, isAbsolute } from 'node:path';--const PACKAGE_NAME = 'agenticow';--// Cache: module load is expensive enough to amortize across handler calls.-// null = not yet attempted; false = attempted and unavailable; module = loaded.-let _agenticowMod: any = null;-let _loadAttempted = false;--interface AgenticowApi {- open: (file: string, opts?: { dimension?: number; metric?: string }) => Promise<any>;- openBase: (file: string, opts?: any) => Promise<any>;- AgenticMemory: any;-}--async function loadAgenticow(): Promise<AgenticowApi | null> {- if (_loadAttempted) return _agenticowMod;- _loadAttempted = true;- try {- _agenticowMod = await import(PACKAGE_NAME);- return _agenticowMod;- } catch (err: any) {- if (err && (err.code === 'ERR_MODULE_NOT_FOUND' || err.code === 'MODULE_NOT_FOUND' ||- /Cannot find (module|package)/i.test(String(err.message)))) {- _agenticowMod = false;- return null;- }- throw err;- }-}--function degradedResult(reason: string): { success: true; degraded: true; reason: string } {- return { success: true, degraded: true, reason };-}--function resolveMemoryPath(path: string): string {- if (!path || typeof path !== 'string') throw new Error('memory path is required');- // D-2 style: reject path traversal in user-supplied paths- if (/\.\.[\\/]|\0/.test(path)) throw new Error('memory path contains disallowed characters');- return isAbsolute(path) ? path : resolve(getProjectCwd(), path);-}--/**- * Lineage manifest companion path. agenticow persists the COW chain- * (working β checkpoints β base) into `<file>.agenticow.json` next to the- * `.rvf` data file. Without this, checkpoints and forks are in-memory only- * and disappear when the AgenticMemory handle closes. Mirrors the bin- * CLI's `manifestFor(file)` helper.- */-function manifestFor(file: string): string {- return `${file}.agenticow.json`;-}--function validateLabel(label: string): string {- if (!label || typeof label !== 'string') throw new Error('label is required');- if (label.length > 256) throw new Error('label exceeds 256 chars');- if (!/^[A-Za-z0-9_.\-:/@]+$/.test(label)) {- throw new Error('label may only contain [A-Za-z0-9_.\\-:/@]');- }- return label;-}--/**- * Open (or create) a base memory file. When a lineage manifest exists at- * `<file>.agenticow.json`, we load that to restore the COW chain (checkpoints,- * ancestors). When only the `.rvf` exists, fresh-open it. When neither exists,- * dimension is required to create. Mirrors the bin CLI's `loadMem()` helper.- */-async function openWithLineage(api: AgenticowApi, file: string, dimension?: number) {- const manifest = manifestFor(file);- if (existsSync(manifest)) {- // The class-level static method `load` reconstructs the full chain.- return (api.AgenticMemory as any).load(manifest);- }- const opts: any = {};- if (typeof dimension === 'number' && Number.isInteger(dimension) && dimension > 0) {- opts.dimension = dimension;- } else if (!existsSync(file)) {- throw new Error('dimension is required when creating a new memory file');- }- return api.open(file, opts);-}+// Loader + path/lineage helpers are shared with the SwarmMemoryBranches+// service (src/services/swarm-memory-branches.ts) via one module so the+// optional-dep dance and the COW open/fork semantics live in exactly one place.+import {+ loadAgenticow,+ degradedResult,+ resolveMemoryPath,+ manifestFor,+ validateLabel,+ openWithLineage,+} from './agenticow-loader.js';export const agenticowTools: MCPTool[] = [{@@ -131,6 +58,7 @@ export const agenticowTools: MCPTool[] = [branchPath: { type: 'string', description: 'Path to write the branch file' },label: { type: 'string', description: 'Human-readable label for the branch (alnum + _.-:/@ only)' },dimension: { type: 'integer', description: 'Vector dimension (required only when basePath does not exist yet)' },+ nativeAnn: { type: 'boolean', description: 'Use the native Rust COW dual-graph ANN path (recall@10=1.0, query spans the COW boundary in one Rust call). Default false (exact JS chain-walk). Set true when the branch will be queried.', default: false },},required: ['basePath', 'branchPath', 'label'],},@@ -142,10 +70,11 @@ export const agenticowTools: MCPTool[] = [const basePath = resolveMemoryPath(String(input.basePath));const branchPath = resolveMemoryPath(String(input.branchPath));const dim = input.dimension as number | undefined;+ const nativeAnn = input.nativeAnn === true;const base = await openWithLineage(api, basePath, dim);try {- const branch = await base.fork(label, branchPath);+ const branch = await base.fork(label, branchPath, { nativeAnn });// Persist lineage manifests so the branch (and base) reopen with// their COW chain intact. Without this, fork is in-memory only.await branch.save?.(manifestFor(branchPath));@@ -156,12 +85,182 @@ export const agenticowTools: MCPTool[] = [basePath,branchPath,label,+ nativeAnn,};} finally {await base.close?.();}},},+ {+ name: 'agenticow_ingest',+ description: 'agenticow β write vectors (with optional text payloads) into an .rvf memory branch or base. Records: [{id?, vector, text?}] β id auto-assigns when omitted. This is the write half that makes a branch usable: agenticow_branch creates an empty COW child, but without ingest it has nothing to read back. Use when you have branched and must populate the branch (agenticow_branch alone leaves it empty). Editing the base directly is wrong when the writes are speculative β ingest into a branch, then promote only if validated. Persists via .agenticow.json lineage manifest.',+ category: 'memory',+ tags: ['agenticow', 'memory', 'cow', 'ingest', 'write'],+ inputSchema: {+ type: 'object',+ properties: {+ path: { type: 'string', description: 'Path to .rvf memory file (branch or base)' },+ records: {+ type: 'array',+ description: 'Vectors to ingest: [{id?: number, vector: number[], text?: string}]',+ items: {+ type: 'object',+ properties: {+ id: { type: 'integer', description: 'Explicit id (auto-assigned when omitted)' },+ vector: { type: 'array', items: { type: 'number' }, description: 'Embedding vector (length must equal the memory dimension)' },+ text: { type: 'string', description: 'Optional payload surfaced on query hits' },+ },+ required: ['vector'],+ },+ },+ dimension: { type: 'integer', description: 'Vector dimension (required only when path does not exist yet)' },+ },+ required: ['path', 'records'],+ },+ handler: async (input) => {+ const api = await loadAgenticow();+ if (!api) return degradedResult('agenticow-not-found');++ const path = resolveMemoryPath(String(input.path));+ const records = input.records as Array<{ id?: number; vector: number[]; text?: string }>;+ if (!Array.isArray(records) || records.length === 0) {+ throw new Error('records must be a non-empty array of {id?, vector, text?}');+ }+ for (const r of records) {+ if (!Array.isArray(r.vector) || r.vector.length === 0) {+ throw new Error('each record requires a non-empty numeric vector');+ }+ }+ const dim = (input.dimension as number | undefined) ?? records[0].vector.length;+ const mem = await openWithLineage(api, path, dim);+ try {+ const result = await mem.ingest(records.map((r) => ({+ ...(typeof r.id === 'number' ? { id: r.id } : {}),+ vector: r.vector,+ ...(r.text !== undefined ? { text: r.text } : {}),+ })));+ await mem.save?.(manifestFor(path));+ return { success: true, path, ingested: result };+ } finally {+ await mem.close?.();+ }+ },+ },+ {+ name: 'agenticow_query',+ description: 'agenticow β k-NN read across an .rvf memory branch\'s full COW lineage (parent βͺ edits, child wins), returning {id, distance, branch, text}. Read-only (no manifest write). The `branch` field on each hit tells you which lineage node the result came from β the read-through semantics that make branching useful. Use when you need to read from an agent/session branch without materializing a full copy. Re-opening the base and manually merging edits is wrong: query already spans the chain (and uses the single-call Rust path when the branch was forked with nativeAnn).',+ category: 'memory',+ tags: ['agenticow', 'memory', 'cow', 'query', 'read', 'search'],+ inputSchema: {+ type: 'object',+ properties: {+ path: { type: 'string', description: 'Path to .rvf memory file' },+ vector: { type: 'array', items: { type: 'number' }, description: 'Query embedding vector' },+ k: { type: 'integer', description: 'Number of nearest neighbors to return', default: 10 },+ efSearch: { type: 'integer', description: 'HNSW efSearch per lineage store (higher = better recall, slower)' },+ },+ required: ['path', 'vector'],+ },+ handler: async (input) => {+ const api = await loadAgenticow();+ if (!api) return degradedResult('agenticow-not-found');++ const path = resolveMemoryPath(String(input.path));+ const vector = input.vector as number[];+ if (!Array.isArray(vector) || vector.length === 0) {+ throw new Error('vector must be a non-empty numeric array');+ }+ const k = typeof input.k === 'number' ? input.k : 10;+ const opts: Record<string, unknown> = {};+ if (typeof input.efSearch === 'number') opts.efSearch = input.efSearch;+ const mem = await openWithLineage(api, path);+ try {+ const hits = await mem.query(vector, k, opts);+ return { success: true, path, k, hits };+ } finally {+ await mem.close?.();+ }+ },+ },+ {+ name: 'agenticow_diff',+ description: 'agenticow β show what a branch changed relative to its lineage: {added, overridden, deleted} vector-id lists. Use when you are about to promote and want to preview the exact merge, or when auditing what a branch actually wrote. Diffing by re-querying is wrong because deletions (tombstones) are invisible to a read β diff() surfaces them explicitly. Requires the branch was opened with edit tracking (default on).',+ category: 'memory',+ tags: ['agenticow', 'memory', 'cow', 'diff'],+ inputSchema: {+ type: 'object',+ properties: {+ path: { type: 'string', description: 'Path to branch .rvf file' },+ },+ required: ['path'],+ },+ handler: async (input) => {+ const api = await loadAgenticow();+ if (!api) return degradedResult('agenticow-not-found');++ const path = resolveMemoryPath(String(input.path));+ const mem = await openWithLineage(api, path);+ try {+ const diff = await mem.diff();+ return { success: true, path, diff };+ } finally {+ await mem.close?.();+ }+ },+ },+ {+ name: 'agenticow_lineage',+ description: 'agenticow β walk the COW chain of an .rvf memory file: an ordered list of nodes (role working|checkpoint|base, id, label, parent, createdAt, mutations, tombstones). Use when you need branch history β to find checkpoint ids for a targeted rollback, or to debug a promote. Guessing the chain from filenames is wrong β lineage is the authoritative structure the store maintains.',+ category: 'memory',+ tags: ['agenticow', 'memory', 'cow', 'lineage', 'history'],+ inputSchema: {+ type: 'object',+ properties: {+ path: { type: 'string', description: 'Path to .rvf memory file' },+ },+ required: ['path'],+ },+ handler: async (input) => {+ const api = await loadAgenticow();+ if (!api) return degradedResult('agenticow-not-found');++ const path = resolveMemoryPath(String(input.path));+ const mem = await openWithLineage(api, path);+ try {+ const lineage = await mem.lineage();+ return { success: true, path, lineage };+ } finally {+ await mem.close?.();+ }+ },+ },+ {+ name: 'agenticow_status',+ description: 'agenticow β health/geometry of an .rvf memory file: {totalVectors, totalSegments, fileSize, currentEpoch, deadSpaceRatio, readOnly, chainDepth, dimension, metric}. Use when you need to check vector count before/after ingest, spot compaction pressure (deadSpaceRatio), or confirm the dimension before ingesting into a shared base. Pure read.',+ category: 'memory',+ tags: ['agenticow', 'memory', 'cow', 'status'],+ inputSchema: {+ type: 'object',+ properties: {+ path: { type: 'string', description: 'Path to .rvf memory file' },+ },+ required: ['path'],+ },+ handler: async (input) => {+ const api = await loadAgenticow();+ if (!api) return degradedResult('agenticow-not-found');++ const path = resolveMemoryPath(String(input.path));+ const mem = await openWithLineage(api, path);+ try {+ const status = await mem.status();+ return { success: true, path, status };+ } finally {+ await mem.close?.();+ }+ },+ },{name: 'agenticow_checkpoint',description: 'agenticow β freeze a labelled restore point on an .rvf memory file. Subsequent edits stay in a fresh COW child; rollback returns here. Use when you are about to run an experimental Darwin tick or speculative agent edit that may need to be discarded. Relying on the working node alone is wrong because there is no "undo last N writes" semantics β without a checkpoint, a bad ingest contaminates the base. Persists via .agenticow.json lineage manifest so it survives close+reopen.',@@ -200,6 +299,7 @@ export const agenticowTools: MCPTool[] = [type: 'object',properties: {path: { type: 'string', description: 'Path to .rvf memory file' },+ checkpointId: { type: 'string', description: 'Target checkpoint id from agenticow_lineage (omit to roll back to the most recent checkpoint)' },},required: ['path'],},@@ -208,9 +308,10 @@ export const agenticowTools: MCPTool[] = [if (!api) return degradedResult('agenticow-not-found');const path = resolveMemoryPath(String(input.path));+ const checkpointId = input.checkpointId ? String(input.checkpointId) : undefined;const mem = await openWithLineage(api, path);try {- const r = await mem.rollback();+ const r = checkpointId ? await mem.rollback(checkpointId) : await mem.rollback();await mem.save?.(manifestFor(path));return { success: true, path, rolledBack: true, result: r };} finally {diff --git a/v3/@claude-flow/cli/src/mcp-tools/index.ts b/v3/@claude-flow/cli/src/mcp-tools/index.tsindex baf42a0971..95bc47ca65 100644--- a/v3/@claude-flow/cli/src/mcp-tools/index.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/index.ts@@ -31,6 +31,8 @@ export { metaharnessTools } from './metaharness-tools.js';export { testgenTools } from './testgen-tools.js';// agenticow@~0.2.3 β Copy-On-Write memory branching (162-byte branches)export { agenticowTools } from './agenticow-tools.js';+// agenticow step 4 β speculative branch-and-promote (A/B memory exploration)+export { agenticowSpeculateTools } from './agenticow-speculate-tools.js';// ADR-164 β AgentBBS federated business-domain BBS rooms (Phase 1)export { agentbbsTools } from './agentbbs-tools.js';// ADR-164 Phase 2 β Business-pod template validationdiff --git a/v3/@claude-flow/cli/src/ruvector/router-trajectory.ts b/v3/@claude-flow/cli/src/ruvector/router-trajectory.tsindex f49d708ee9..98cedd5a46 100644--- a/v3/@claude-flow/cli/src/ruvector/router-trajectory.ts+++ b/v3/@claude-flow/cli/src/ruvector/router-trajectory.ts@@ -13,6 +13,19 @@* Schema is versioned (`"v": 1`). New required fields bump the version;* additive optional fields do not.*+ * COMPANION: run-transcript-recorder.ts (weight-eft capture path)+ * --------------------------------------------------------------+ * This recorder captures the routing DECISION only (task, embedding, scalar+ * quality, tokens, cost) β enough to retrain the router. It deliberately does+ * NOT carry the full message transcript, the produced patch, or a resolved+ * boolean. `@metaharness/weight-eft` needs those to build SFT/DPO training+ * rows, so a SEPARATE opt-in recorder β `run-transcript-recorder.ts` β captures+ * the full run transcript to `.swarm/run-transcripts.jsonl`. Both share the+ * `taskHash()` below as their join key, and both are off-by-default for the+ * same PII/retention reason. Use `unifiedRecorderStatus()` (bottom of this+ * file) to inspect both at once. Keeping them as two files keeps the routing+ * hot path free of the heavier transcript payload.+ ** @module router-trajectory*/@@ -396,3 +409,24 @@ export function __resetTrajectoryRecorderForTests(): void {_cfg = null;_cachedSize = -1;}++/**+ * Unified status for BOTH the routing-decision recorder (this module) and the+ * companion run-transcript recorder (the weight-eft capture path). The+ * run-transcript recorder is loaded dynamically so this module has no static+ * dependency on it (the reverse edge β run-transcript-recorder β taskHash β+ * is the only static link, keeping the import acyclic).+ */+export async function unifiedRecorderStatus(): Promise<{+ routerTrajectory: { enabled: boolean; path: string; taskCharLimit: number };+ runTranscripts: { enabled: boolean; path: string } | { unavailable: true };+}> {+ const routerTrajectory = trajectoryRecorderStatus();+ try {+ const mod = await import('./run-transcript-recorder.js');+ const s = mod.runTranscriptRecorderStatus();+ return { routerTrajectory, runTranscripts: { enabled: s.enabled, path: s.path } };+ } catch {+ return { routerTrajectory, runTranscripts: { unavailable: true } };+ }+}diff --git a/v3/@claude-flow/cli/src/ruvector/run-transcript-recorder.ts b/v3/@claude-flow/cli/src/ruvector/run-transcript-recorder.tsnew file mode 100644index 0000000000..2c0cdde8ff--- /dev/null+++ b/v3/@claude-flow/cli/src/ruvector/run-transcript-recorder.ts@@ -0,0 +1,277 @@+/**+ * run-transcript-recorder.ts β Opt-in FULL run-transcript recorder for the+ * weight-eft training-data export path (agenticow / ADR-150 weight-eft slice).+ *+ * WHY THIS EXISTS+ * ---------------+ * The existing `router-trajectory.ts` recorder captures only the ROUTING+ * DECISION for a task: task text, embedding, scalar quality, tokens, cost.+ * `@metaharness/weight-eft` needs something the routing recorder never had β+ * the full ReAct message TRANSCRIPT, the produced patch, and a resolved+ * boolean β to build SFT/DPO training rows. This module is that missing+ * capture surface. It writes one JSON-line per completed run to+ * `.swarm/run-transcripts.jsonl`, in a shape the archive-builder in+ * `services/weight-eft.ts` maps directly to `DarwinTrajectory[]`.+ *+ * OFF BY DEFAULT (PII / RETENTION SURFACE)+ * ----------------------------------------+ * Rows carry the FULL prompt + assistant transcript + patch β a much larger+ * PII/retention surface than the routing recorder. Mirroring why+ * router-trajectory.ts is off-by-default, every write goes through the+ * `CLAUDE_FLOW_RUN_TRANSCRIPTS=1` env gate. When unset (the default),+ * `recordRunTranscript()` is a no-op. There is no way to enable it implicitly.+ *+ * HONESTY: `resolved` IS A PROXY+ * ------------------------------+ * `DarwinTrajectory.resolved` is meant to be GOLD-resolved status from the+ * official SWE-bench harness. Ruflo has NO SWE-bench oracle. Every record+ * therefore stamps `resolved_source` describing where the boolean actually+ * came from, so no downstream consumer can mistake a proxy for gold:+ * - 'gold-oracle' β a real conformant gold eval supplied it (never+ * ruflo today; reserved for an external caller)+ * - 'output-verifier' β ruflo's structural output-verifier confidence,+ * thresholded β an EXPLICIT proxy+ * - 'api-success' β the model returned without an API error β the+ * weakest proxy (says nothing about correctness)+ * - 'external' β supplied verbatim by the caller, provenance unknown+ *+ * ARCHITECTURAL CONSTRAINTS (mirror router-trajectory.ts / ADR-150)+ * -----------------------------------------------------------------+ * 1. OPT-IN β gated behind CLAUDE_FLOW_RUN_TRANSCRIPTS=1; default off.+ * 2. NEVER THROWS β every fs op is try/caught at the append boundary; a+ * failed write is silent (DEBUG-logged) and never breaks the run.+ * 3. NO metaharness COUPLING β this module imports nothing from+ * `@metaharness/*`; it only defines a portable record shape. The+ * services/weight-eft.ts archive-builder does the (optional) mapping.+ *+ * SCHEMA (versioned, additive) β one JSONL row per completed run:+ * { v, ts, instance_id, task_hash, model, tier, resolved, resolved_source,+ * messages[], model_patch, sample?, source?, tokens?, cost_usd? }+ *+ * @module run-transcript-recorder+ */++import { appendFileSync, mkdirSync, existsSync, statSync, renameSync, unlinkSync, readFileSync } from 'node:fs';+import { dirname, join, resolve as resolvePath } from 'node:path';++import { taskHash } from './router-trajectory.js';++// ============================================================================+// Portable record shape (OpenAI-chat compatible; no @metaharness import)+// ============================================================================++/** An OpenAI-style tool call (the ReAct action). Mirrors weight-eft's ToolCall. */+export interface ToolCallLite {+ id: string;+ type: 'function';+ function: { name: string; arguments: string };+}++/** A chat message in an OpenAI-compatible transcript. Mirrors weight-eft's ChatMessage. */+export interface ChatMessageLite {+ role: 'system' | 'user' | 'assistant' | 'tool';+ content: string | null;+ tool_calls?: ToolCallLite[];+ tool_call_id?: string;+ name?: string;+}++/** Where a `resolved` boolean actually came from (never silently "gold"). */+export type ResolvedSource = 'gold-oracle' | 'output-verifier' | 'api-success' | 'external';++/** Ruflo's cascade tier. haiku β 'cheap' (first tier), sonnet/opus β 'frontier'. */+export type RunTier = 'cheap' | 'frontier';++/** One persisted run transcript. Maps 1:1 to a DarwinTrajectory (+ provenance). */+export interface RunTranscriptRecord {+ v: 1;+ ts: string;+ instance_id: string;+ task_hash: string;+ model: string;+ tier: RunTier;+ resolved: boolean;+ resolved_source: ResolvedSource;+ messages: ChatMessageLite[];+ model_patch: string;+ sample?: number;+ source?: string;+ tokens?: { input: number; output: number };+ cost_usd?: number;+}++// ============================================================================+// Config + rotation (mirrors router-trajectory.ts)+// ============================================================================++interface RecorderConfig {+ enabled: boolean;+ path: string;+ maxSizeBytes: number;+ maxRotations: number;+}++let _cfg: RecorderConfig | null = null;+let _cachedSize = -1;++function getConfig(): RecorderConfig {+ if (_cfg !== null) return _cfg;+ const swarmDir = process.env.CLAUDE_FLOW_SWARM_DIR ?? resolvePath(process.cwd(), '.swarm');+ _cfg = {+ enabled: process.env.CLAUDE_FLOW_RUN_TRANSCRIPTS === '1',+ path: process.env.CLAUDE_FLOW_RUN_TRANSCRIPTS_PATH ?? join(swarmDir, 'run-transcripts.jsonl'),+ maxSizeBytes: parseInt(process.env.CLAUDE_FLOW_RUN_TRANSCRIPTS_MAXSIZE ?? `${25 * 1024 * 1024}`, 10) | 0,+ maxRotations: Math.max(0, parseInt(process.env.CLAUDE_FLOW_RUN_TRANSCRIPTS_MAXROTATIONS ?? '3', 10) || 3),+ };+ return _cfg;+}++function rotate(cfg: RecorderConfig): void {+ if (!existsSync(cfg.path)) return;+ try {+ if (cfg.maxRotations === 0) { unlinkSync(cfg.path); return; }+ const oldest = `${cfg.path}.${cfg.maxRotations}`;+ if (existsSync(oldest)) unlinkSync(oldest);+ for (let i = cfg.maxRotations - 1; i >= 1; i--) {+ const src = `${cfg.path}.${i}`;+ if (existsSync(src)) renameSync(src, `${cfg.path}.${i + 1}`);+ }+ renameSync(cfg.path, `${cfg.path}.1`);+ } catch {+ try { unlinkSync(cfg.path); } catch { /* */ }+ }+ _cachedSize = 0;+}++function appendRow(row: RunTranscriptRecord): void {+ const cfg = getConfig();+ if (!cfg.enabled) return;+ try {+ const dir = dirname(cfg.path);+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });+ if (_cachedSize < 0) {+ _cachedSize = existsSync(cfg.path) ? statSync(cfg.path).size : 0;+ }+ const line = JSON.stringify(row) + '\n';+ const bytes = Buffer.byteLength(line, 'utf8');+ if (cfg.maxSizeBytes > 0 && _cachedSize + bytes > cfg.maxSizeBytes) rotate(cfg);+ appendFileSync(cfg.path, line);+ _cachedSize += bytes;+ } catch (e) {+ if (process.env.DEBUG) {+ // eslint-disable-next-line no-console+ console.error('run-transcript: appendRow failed:', (e as Error).message);+ }+ // Never throw β transcript collection must never break a run.+ }+}++// ============================================================================+// Public API+// ============================================================================++/**+ * Record one completed run transcript. Cheap β a single appendFileSync of a+ * JSONL row. No-op when CLAUDE_FLOW_RUN_TRANSCRIPTS is unset (the default).+ * Never throws.+ *+ * `resolvedSource` is REQUIRED so a proxy can never masquerade as gold. If you+ * only have "the API returned", pass 'api-success' β the honest weakest label.+ */+export function recordRunTranscript(args: {+ /** Task/issue text β used for the FNV hash + default instance id. */+ task: string;+ /** Concrete model id that produced the run (e.g. "claude-haiku-4"). */+ model: string;+ /** Ruflo cascade tier of `model`. */+ tier: RunTier;+ /** The resolved boolean (see resolvedSource for what it actually means). */+ resolved: boolean;+ /** Provenance of `resolved`. Never omit β honesty is the point. */+ resolvedSource: ResolvedSource;+ /** OpenAI-shaped message transcript (system/user/assistant/tool). */+ messages: ChatMessageLite[];+ /** Unified diff the run produced. '' when the path produces no patch. */+ modelPatch?: string;+ /** Override the default "run-<hash>" instance id (contamination key). */+ instanceId?: string;+ /** Best-of-N sample index on the same instance (default 0). */+ sample?: number;+ /** Provenance tag, e.g. "agent-execute", "autopilot". */+ source?: string;+ tokens?: { input: number; output: number };+ costUsd?: number;+}): { recorded: boolean; instanceId: string; taskHash: string } {+ const cfg = getConfig();+ const hash = taskHash(args.task);+ const instanceId = args.instanceId ?? `run-${hash}`;+ if (!cfg.enabled) return { recorded: false, instanceId, taskHash: hash };++ const row: RunTranscriptRecord = {+ v: 1,+ ts: new Date().toISOString(),+ instance_id: instanceId,+ task_hash: hash,+ model: args.model,+ tier: args.tier,+ resolved: args.resolved,+ resolved_source: args.resolvedSource,+ messages: args.messages,+ model_patch: args.modelPatch ?? '',+ ...(args.sample !== undefined ? { sample: args.sample } : {}),+ ...(args.source ? { source: args.source } : {}),+ ...(args.tokens ? { tokens: args.tokens } : {}),+ ...(args.costUsd != null ? { cost_usd: args.costUsd } : {}),+ };+ appendRow(row);+ return { recorded: true, instanceId, taskHash: hash };+}++/**+ * Read + parse the run-transcript JSONL back into records. Used by the+ * archive-builder (`services/weight-eft.ts`). Malformed lines are skipped and+ * counted, never thrown. Returns `[]` if the file is absent.+ */+export function readRunTranscripts(path?: string): { records: RunTranscriptRecord[]; malformed: number; path: string } {+ const p = path ?? getConfig().path;+ if (!existsSync(p)) return { records: [], malformed: 0, path: p };+ const records: RunTranscriptRecord[] = [];+ let malformed = 0;+ try {+ for (const line of readFileSync(p, 'utf8').split('\n')) {+ if (!line.trim()) continue;+ try {+ const r = JSON.parse(line) as RunTranscriptRecord;+ if (r && typeof r === 'object' && r.v === 1 && r.instance_id && Array.isArray(r.messages)) {+ records.push(r);+ } else {+ malformed++;+ }+ } catch { malformed++; }+ }+ } catch {+ // unreadable file β treat as empty, never throw+ }+ return { records, malformed, path: p };+}++/** Map a ruflo model tier label to the weight-eft policy tier. */+export function tierForModel(model: string | undefined): RunTier {+ // haiku (and any explicitly-cheap label) β 'cheap' (cascade first tier).+ // sonnet / opus / everything else β 'frontier' (the escalation tier).+ if (!model) return 'frontier';+ return /haiku/i.test(model) ? 'cheap' : 'frontier';+}++/** Diagnostic for status/CLI. */+export function runTranscriptRecorderStatus(): {+ enabled: boolean; path: string; maxSizeBytes: number; maxRotations: number;+} {+ return { ...getConfig() };+}++/** @internal β test seam: reset cached config so tests can flip env vars. */+export function __resetRunTranscriptRecorderForTests(): void {+ _cfg = null;+ _cachedSize = -1;+}diff --git a/v3/@claude-flow/cli/src/services/checkpoint-gate.ts b/v3/@claude-flow/cli/src/services/checkpoint-gate.tsnew file mode 100644index 0000000000..750122b585--- /dev/null+++ b/v3/@claude-flow/cli/src/services/checkpoint-gate.ts@@ -0,0 +1,288 @@+/**+ * CheckpointGate β agenticow-backed checkpoint/rollback gate for autopilot+ * loops and long-horizon workflows (agenticow integration, step 3).+ *+ * ββ The pattern βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+ * Before a risky loop tick that mutates `.rvf` memory, take an O(1) agenticow+ * checkpoint (162 bytes, fixed cost β see mcp-tools/agenticow-tools.ts). Run+ * the tick. If it regresses β throws, or the caller's verdict says the outcome+ * got worse (verifier fail / error / worse metric) β roll the memory back to+ * the checkpoint. Rollback is O(edits-since-checkpoint), NOT an O(N) rebuild,+ * and the earlier history stays intact via the `.agenticow.json` lineage+ * manifest. On success the checkpoint is simply kept as the new good baseline.+ *+ * The three lifecycle verbs (checkpoint / rollback / promote) already exist in+ * the `agenticow` package and are surfaced as MCP tools in+ * `mcp-tools/agenticow-tools.ts`. This module is the *orchestration hook* that+ * calls them from inside a loop β the MCP surface is for agents, this is for+ * the in-process loop.+ *+ * ββ Architectural constraint (ADR-150) ββββββββββββββββββββββββββββββββββββ+ * `agenticow` lives in `optionalDependencies` and must NEVER be a hard runtime+ * dependency. This gate degrades gracefully in three ways, each of which runs+ * the tick UNGUARDED rather than failing:+ * 1. package missing β { degraded: true, reason: 'agenticow-not-found' }+ * 2. kill-switch env set β { degraded: true, reason: 'kill-switch' }+ * 3. no memory path configured β { degraded: true, reason: 'no-memory-path' }+ * The package is lazy-loaded on the first guard() call, so importing this+ * module has zero startup cost.+ *+ * The optional-dep loader + path/label/lineage helpers are the canonical ones+ * from `mcp-tools/agenticow-loader.ts` β one implementation shared across every+ * agenticow consumer (verbs, swarm branches, speculative, oracle, this gate).+ *+ * @module @claude-flow/cli/services/checkpoint-gate+ */++import {+ type AgenticowApi,+ loadAgenticow,+ __resetAgenticowCache,+ resolveMemoryPath,+ manifestFor,+ validateLabel,+ openWithLineage,+} from '../mcp-tools/agenticow-loader.js';++/**+ * Env var pointing at the `.rvf` memory file that a long-horizon loop mutates.+ * When set, the autopilot loop opts in to checkpoint/rollback around each tick.+ * When unset, the gate is a transparent pass-through.+ */+export const CHECKPOINT_MEM_ENV = 'CLAUDE_FLOW_AUTOPILOT_CHECKPOINT_MEM';++/**+ * Kill switch. When truthy (`1`/`true`/`yes`), the gate never touches agenticow+ * and every guard() runs the tick unguarded. Lets an operator disable the+ * feature without changing config or code.+ */+export const KILL_SWITCH_ENV = 'CLAUDE_FLOW_AGENTICOW_DISABLE';++/** Outcome of a guarded tick. `result` is undefined only when the tick threw+ * AND `rethrow` was disabled. */+export interface CheckpointGuardResult<T> {+ /** The value fn() returned (undefined if it threw with rethrow:false). */+ result: T | undefined;+ /** True when a checkpoint was actually taken before running fn. */+ checkpointed: boolean;+ /** True when memory was rolled back to the checkpoint (throw or regression). */+ rolledBack: boolean;+ /** True when the gate could not engage agenticow and ran fn unguarded. */+ degraded: boolean;+ /** Machine-readable reason for degraded / rollback. */+ reason?: string;+ /** The checkpoint label, when one was taken. */+ checkpointLabel?: string;+ /** The error fn() threw, when rethrow was disabled. */+ error?: unknown;+}++export interface GuardOptions<T> {+ /**+ * Verdict function: return true when `result` represents a regression that+ * should trigger a rollback. Defaults to treating `{success:false}` /+ * `{ok:false}` / `{regressed:true}` as regressions.+ */+ isRegression?: (result: T) => boolean;+ /**+ * When the tick throws: roll back, then re-throw the original error+ * (default true). Set false to swallow the error and return it on the+ * result object instead β useful when the loop must never crash.+ */+ rethrow?: boolean;+ /** Optional checkpoint id to roll back to (defaults to most recent). */+ checkpointId?: string;+}++function defaultIsRegression(result: unknown): boolean {+ if (!result || typeof result !== 'object') return false;+ const r = result as Record<string, unknown>;+ return r.success === false || r.ok === false || r.regressed === true;+}++// ββ The gate ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++export class CheckpointGate {+ /** True when the kill-switch env is set to a truthy value. */+ static isKillSwitchSet(): boolean {+ const v = (process.env[KILL_SWITCH_ENV] || '').trim().toLowerCase();+ return v === '1' || v === 'true' || v === 'yes' || v === 'on';+ }++ /** The configured loop memory path, or undefined when the feature is off. */+ static configuredMemPath(): string | undefined {+ const p = (process.env[CHECKPOINT_MEM_ENV] || '').trim();+ return p || undefined;+ }++ /**+ * Lazy-load agenticow. Returns null when the package is absent (optional dep)+ * or the kill switch is set. Any *other* import error is re-thrown β a broken+ * install should be loud, a missing optional dep should be silent.+ */+ private async load(): Promise<AgenticowApi | null> {+ if (CheckpointGate.isKillSwitchSet()) return null;+ // Delegates to the canonical loader (#22) β one cache, one degradation+ // policy shared across every agenticow consumer.+ return loadAgenticow();+ }++ /** True when agenticow can be engaged (present + not killed). */+ async available(): Promise<boolean> {+ return (await this.load()) !== null;+ }++ /**+ * Take a checkpoint on the given `.rvf` memory file. Non-throwing except for+ * validation errors (path traversal, bad label) β those are surfaced so a+ * misconfiguration is caught early.+ */+ async checkpoint(+ memPath: string,+ label: string,+ ): Promise<{ ok: boolean; degraded: boolean; reason?: string; checkpoint?: unknown }> {+ const api = await this.load();+ if (!api) return { ok: false, degraded: true, reason: CheckpointGate.isKillSwitchSet() ? 'kill-switch' : 'agenticow-not-found' };++ const path = resolveMemoryPath(String(memPath));+ const lbl = validateLabel(String(label));+ const mem = await openWithLineage(api, path);+ try {+ const cp = await mem.checkpoint(lbl);+ await mem.save?.(manifestFor(path));+ return { ok: true, degraded: false, checkpoint: cp };+ } finally {+ await mem.close?.();+ }+ }++ /**+ * Roll the given `.rvf` memory file back to a checkpoint. Discards edits made+ * since (O(edits-since-checkpoint)). Omit `checkpointId` to target the most+ * recent checkpoint.+ */+ async rollback(+ memPath: string,+ checkpointId?: string,+ ): Promise<{ ok: boolean; degraded: boolean; reason?: string; result?: unknown }> {+ const api = await this.load();+ if (!api) return { ok: false, degraded: true, reason: CheckpointGate.isKillSwitchSet() ? 'kill-switch' : 'agenticow-not-found' };++ const path = resolveMemoryPath(String(memPath));+ const mem = await openWithLineage(api, path);+ try {+ const r = checkpointId ? await mem.rollback(checkpointId) : await mem.rollback();+ await mem.save?.(manifestFor(path));+ return { ok: true, degraded: false, result: r };+ } finally {+ await mem.close?.();+ }+ }++ /**+ * Guard a risky loop tick with a checkpoint/rollback bracket.+ *+ * const outcome = await gate.guard(memPath, 'iter-7', async () => runTick());+ *+ * Behaviour:+ * - No memPath / kill-switch / agenticow-absent β run fn unguarded, degraded:true.+ * - Checkpoint fails to engage (degraded) β run fn unguarded, degraded:true.+ * - fn throws β roll back to checkpoint, then re-throw (unless rethrow:false).+ * - fn returns a regression verdict β roll back, return result with rolledBack:true.+ * - fn succeeds β keep the checkpoint, return result with rolledBack:false.+ *+ * The gate is non-fatal: an internal agenticow failure never masks fn()'s own+ * result β if checkpointing throws, fn still runs unguarded.+ */+ async guard<T>(+ memPath: string | undefined,+ label: string,+ fn: () => Promise<T>,+ opts: GuardOptions<T> = {},+ ): Promise<CheckpointGuardResult<T>> {+ const rethrow = opts.rethrow !== false;+ const isRegression = opts.isRegression ?? (defaultIsRegression as (r: T) => boolean);++ // Fast paths: feature off β transparent pass-through.+ if (!memPath) {+ const result = await fn();+ return { result, checkpointed: false, rolledBack: false, degraded: true, reason: 'no-memory-path' };+ }+ if (CheckpointGate.isKillSwitchSet()) {+ const result = await fn();+ return { result, checkpointed: false, rolledBack: false, degraded: true, reason: 'kill-switch' };+ }++ // Try to checkpoint. Any failure here degrades to unguarded β the loop must+ // never break because memory branching is unavailable.+ let checkpointed = false;+ try {+ const cp = await this.checkpoint(memPath, label);+ if (!cp.ok) {+ const result = await fn();+ return { result, checkpointed: false, rolledBack: false, degraded: true, reason: cp.reason };+ }+ checkpointed = true;+ } catch (err) {+ const result = await fn();+ return {+ result,+ checkpointed: false,+ rolledBack: false,+ degraded: true,+ reason: `checkpoint-error: ${err instanceof Error ? err.message : String(err)}`,+ };+ }++ // Run the tick under the checkpoint.+ let result: T;+ try {+ result = await fn();+ } catch (err) {+ const rb = await this.safeRollback(memPath, opts.checkpointId);+ if (rethrow) throw err;+ return {+ result: undefined,+ checkpointed,+ rolledBack: rb,+ degraded: false,+ reason: 'tick-threw',+ checkpointLabel: label,+ error: err,+ };+ }++ // Verdict: regression β roll back, keep the returned result for the caller.+ if (isRegression(result)) {+ const rb = await this.safeRollback(memPath, opts.checkpointId);+ return { result, checkpointed, rolledBack: rb, degraded: false, reason: 'regression-verdict', checkpointLabel: label };+ }++ // Success β keep the checkpoint as the new baseline.+ return { result, checkpointed, rolledBack: false, degraded: false, checkpointLabel: label };+ }++ /** Roll back without throwing β used on the failure path so a rollback error+ * never masks the original tick failure. */+ private async safeRollback(memPath: string, checkpointId?: string): Promise<boolean> {+ try {+ const r = await this.rollback(memPath, checkpointId);+ return r.ok;+ } catch {+ return false;+ }+ }+}++/** Shared process-wide gate instance. */+let _shared: CheckpointGate | null = null;+export function getCheckpointGate(): CheckpointGate {+ if (!_shared) _shared = new CheckpointGate();+ return _shared;+}++/** Reset the lazy-load cache β test-only. */+export function __resetCheckpointGateForTests(): void {+ __resetAgenticowCache();+ _shared = null;+}diff --git a/v3/@claude-flow/cli/src/services/distill-oracle.ts b/v3/@claude-flow/cli/src/services/distill-oracle.tsnew file mode 100644index 0000000000..abb5de8116--- /dev/null+++ b/v3/@claude-flow/cli/src/services/distill-oracle.ts@@ -0,0 +1,512 @@+/**+ * distill-oracle.ts β Tiered `resolved` oracle for distill / weight-EFT SFT data.+ *+ * THE PROBLEM: weight-EFT's SFT data wants a gold `resolved: boolean` per+ * trajectory. Ruflo has no SWE-bench oracle, so today `resolved` is+ * structural-confidence β a proxy that risks distilling plausible-but-wrong+ * completions. This module replaces that single proxy with a TIERED labeler,+ * where every label carries HONEST PROVENANCE (ADR-169 reporting integrity β a+ * proxy is never presented as ground truth).+ *+ * ββ TIERS (tried in order, per trajectory) ββββββββββββββββββββββββββββββββββ+ * TIER 1 β MECHANICAL ORACLE (provenance `oracle:test-exec`, real ground truth)+ * When a trajectory carries a test spec (SWE-bench FAIL_TO_PASS shape) or+ * maps to a metaharness/darwin bench-suite case, EXECUTE the real eval and+ * set resolved = tests-pass. This needs Docker/compute, so it runs on a+ * REMOTE host over SSH (host parameterized via `remote` / env+ * RUFLO_DISTILL_REMOTE β never hard-coded). DRY-RUN by default: it prints+ * the ssh/darwin-bench/eval commands + a preflight plan and does NOT touch+ * the network; only `execute: true` runs the real eval (with a wrapped,+ * non-fatal preflight probe first).+ *+ * TIER 2 β FABLE JUDGE (provenance `judge:fable`, smarter proxy)+ * For trajectories with no mechanical spec, judge via the cost-disciplined+ * headless Fable harness (fable-harness.ts). Opt-in and OFF by default;+ * spends nothing unless `fableJudge: true` AND a `maxBudgetUsd` cap is set.+ *+ * TIER 3 β STRUCTURAL PROXY (provenance `proxy:structural`, weakest)+ * The existing output-verifier structural confidence. Always available,+ * $0, no external calls. Explicitly the weakest signal, clearly labeled.+ *+ * DEFAULT (no opts): dry-run oracle preflight + structural-proxy fallback.+ * ZERO spend, no SSH exec, no Fable call. Everything degrades gracefully+ * (ADR-150) β a missing remote or a failed probe is reported, never fatal.+ *+ * @module services/distill-oracle+ */++import { spawn } from 'child_process';+import { verifyAndEscalate, type VerifyTaskKind } from '../ruvector/output-verifier.js';+import {+ FableHarness,+ type JudgeItem,+ type JudgeResult,+ type ReflectItem,+ type ReflectResult,+} from './fable-harness.js';++// ββ Provenance βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++export type ResolvedProvenance = 'oracle:test-exec' | 'judge:fable' | 'proxy:structural';++// ββ Trajectory / spec shapes ββββββββββββββββββββββββββββββββββββββββββββββββ++/** SWE-bench-shaped / bench-suite-mapped test spec that Tier 1 can execute. */+export interface TestSpec {+ /** SWE-bench FAIL_TO_PASS tests β must go redβgreen for `resolved`. */+ failToPass?: string[];+ /** SWE-bench PASS_TO_PASS tests β must stay green (no regressions). */+ passToPass?: string[];+ /** Repo identifier (for the remote checkout). */+ repo?: string;+ /** Base commit the patch applies onto. */+ baseCommit?: string;+ /** Candidate patch/diff to apply before evaluating. */+ patch?: string;+ /** An explicit eval command that returns 0 iff the task is resolved. */+ evalCommand?: string;+ /** metaharness/darwin bench-suite this case belongs to. */+ benchSuite?: string;+ /** Case id within the bench suite. */+ benchCase?: string;+ /** Working directory on the remote host (default derived). */+ workdir?: string;+}++/**+ * Minimal trajectory contract. Extra fields are preserved verbatim on output+ * (the labeler spreads `...trajectory`). `task`/`output` feed the fable judge+ * and structural proxy; `testSpec` (when present) unlocks Tier 1.+ */+export interface Trajectory {+ id: string;+ task?: string;+ output?: string;+ testSpec?: TestSpec;+ /** Hint for the structural verifier's task-kind detection. */+ taskKind?: VerifyTaskKind;+ [key: string]: unknown;+}++// ββ Options / results βββββββββββββββββββββββββββββββββββββββββββββββββββββββ++export interface LabelOptions {+ /** SSH host for Tier-1 execution. Falls back to env RUFLO_DISTILL_REMOTE. Never hard-coded. */+ remote?: string;+ /** Run the REAL Tier-1 eval over SSH. Default false β dry-run preflight only. */+ execute?: boolean;+ /** Enable the Tier-2 Fable judge. Default false. Requires maxBudgetUsd to spend. */+ fableJudge?: boolean;+ /** Hard budget cap (USD) for the Fable tier. No cap β no Fable spend. */+ maxBudgetUsd?: number;+ /** Items per Fable call (default 20 β see FABLE_COST_MODEL). */+ fableBatchSize?: number;+ /** Structural verifier: min score to call a trajectory resolved (default: strict β confident only). */+ minStructuralConfidence?: number;+ /** Injected Tier-1 runner (tests). Defaults to a real SSH command runner. */+ runner?: OracleRunner;+ /** Injected Tier-2 harness (tests). Defaults to a real FableHarness. */+ harness?: FableHarness;+}++/** A trajectory with its resolved label + honest provenance. */+export type LabeledTrajectory<T extends Trajectory = Trajectory> = T & {+ resolved: boolean;+ resolvedBy: ResolvedProvenance;+ resolvedConfidence?: number;+ resolvedReason?: string;+ /** Present for trajectories that had a mechanical spec β the Tier-1 plan/outcome. */+ oraclePreflight?: OraclePreflight;+};++// ββ Tier-1 oracle plan / runner ββββββββββββββββββββββββββββββββββββββββββββββ++export type OracleKind = 'ssh-darwin-bench' | 'ssh-swebench-eval' | 'ssh-eval' | 'local-eval';++/** The concrete command plan for executing a trajectory's eval on the remote. */+export interface OraclePlan {+ kind: OracleKind;+ /** Resolved remote host, or null when none is configured. */+ remote: string | null;+ /** Preflight probe commands (reachability, docker/darwin presence). */+ probeCommands: string[];+ /** The eval commands whose success β resolved. */+ evalCommands: string[];+ /** Human note describing how the resolved boolean is derived. */+ parseHint: string;+}++/** Preflight/dry-run record attached to labeled trajectories that had a spec. */+export interface OraclePreflight {+ /** True when nothing was executed (default path). */+ dryRun: boolean;+ plan: OraclePlan;+ /** Probe outcome when executed (execute:true); absent in dry-run. */+ probe?: { ok: boolean; reason: string };+ /** Why Tier 1 did not produce the final label (e.g. dry-run, no remote, probe failed). */+ fellThroughBecause?: string;+}++/** Outcome of a real Tier-1 eval. */+export interface OracleOutcome {+ resolved: boolean;+ reason: string;+}++/** Result of a shelled command. */+export interface CommandResult {+ stdout: string;+ stderr: string;+ code: number | null;+}++/** Injectable command executor (tests mock this instead of touching SSH). */+export type CommandExec = (+ cmd: string,+ args: string[],+ opts: { timeoutMs: number },+) => Promise<CommandResult>;++/** Tier-1 runner contract: probe the remote, then run the eval. */+export interface OracleRunner {+ preflight(plan: OraclePlan): Promise<{ ok: boolean; reason: string }>;+ runEval(plan: OraclePlan, spec: TestSpec): Promise<OracleOutcome>;+}++// ββ Public API βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++/**+ * Label each trajectory with `resolved` + honest provenance, trying the tiers+ * in order per trajectory. See the module header for tier semantics and the+ * zero-spend default guarantee.+ */+export async function labelResolved<T extends Trajectory>(+ trajectories: T[],+ opts: LabelOptions = {},+): Promise<Array<LabeledTrajectory<T>>> {+ const results: Array<LabeledTrajectory<T> | undefined> = new Array(trajectories.length);+ const preflights = new Map<number, OraclePreflight>();++ const remote = resolveRemote(opts.remote);+ const fableActive = Boolean(opts.fableJudge) && Number(opts.maxBudgetUsd) > 0;++ // ββ Tier 1: mechanical oracle (real exec only under execute:true) ββββββββββ+ const fableQueue: Array<{ index: number; item: JudgeItem }> = [];++ for (let i = 0; i < trajectories.length; i++) {+ const t = trajectories[i];+ if (hasMechanicalSpec(t)) {+ const plan = buildOraclePlan(t.testSpec!, remote);+ if (opts.execute) {+ const runner = opts.runner ?? createSshOracleRunner();+ // Wrapped probe: a failure is REPORTED, not thrown.+ const probe = await safeProbe(runner, plan);+ if (probe.ok) {+ const outcome = await safeRunEval(runner, plan, t.testSpec!);+ results[i] = {+ ...t,+ resolved: outcome.resolved,+ resolvedBy: 'oracle:test-exec',+ resolvedConfidence: 1,+ resolvedReason: outcome.reason,+ oraclePreflight: { dryRun: false, plan, probe },+ };+ continue;+ }+ // Probe failed β report and fall through to next tier.+ preflights.set(i, {+ dryRun: false,+ plan,+ probe,+ fellThroughBecause: `preflight failed: ${probe.reason}`,+ });+ } else {+ // DRY-RUN: emit the plan/commands, touch nothing, fall through.+ preflights.set(i, {+ dryRun: true,+ plan,+ fellThroughBecause: remote+ ? 'dry-run (pass execute:true to run the real eval over SSH)'+ : 'dry-run and no remote configured (set remote / RUFLO_DISTILL_REMOTE)',+ });+ }+ }++ // ββ Route to Tier 2 (batched later) or Tier 3 now ββ+ if (fableActive) {+ fableQueue.push({ index: i, item: toJudgeItem(t) });+ } else {+ results[i] = await proxyLabel(t, opts, preflights.get(i));+ }+ }++ // ββ Tier 2: batched Fable judge for queued items ββββββββββββββββββββββββββ+ if (fableActive && fableQueue.length > 0) {+ const harness =+ opts.harness ??+ new FableHarness({ maxBudgetUsd: opts.maxBudgetUsd, batchSize: opts.fableBatchSize });+ let verdicts: JudgeResult[] = [];+ try {+ verdicts = await harness.judgeBatch(fableQueue.map((q) => q.item));+ } catch {+ verdicts = []; // graceful: any harness failure β proxy fallback for all+ }+ const byId = new Map(verdicts.map((v) => [v.id, v]));+ for (const { index, item } of fableQueue) {+ const v = byId.get(item.id);+ const t = trajectories[index];+ if (v) {+ results[index] = {+ ...t,+ resolved: v.resolved,+ resolvedBy: 'judge:fable',+ resolvedConfidence: v.confidence,+ resolvedReason: v.reason,+ ...(preflights.has(index) ? { oraclePreflight: preflights.get(index) } : {}),+ };+ } else {+ // Model omitted this id / budget exhausted β Tier-3 proxy fallback.+ results[index] = await proxyLabel(t, opts, preflights.get(index));+ }+ }+ }++ // ββ Safety net: nothing should be undefined, but fall back to proxy if so ββ+ for (let i = 0; i < results.length; i++) {+ if (results[i] === undefined) {+ results[i] = await proxyLabel(trajectories[i], opts, preflights.get(i));+ }+ }++ return results as Array<LabeledTrajectory<T>>;+}++/**+ * Reflective failure analysis (GEPA/evolve mutation input). Thin, cost-+ * disciplined pass-through to the Fable harness. Opt-in: returns [] unless a+ * harness with a budget cap is provided/configured.+ */+export async function reflectFailures(+ items: ReflectItem[],+ opts: { maxBudgetUsd?: number; fableBatchSize?: number; harness?: FableHarness } = {},+): Promise<ReflectResult[]> {+ const harness =+ opts.harness ??+ new FableHarness({ maxBudgetUsd: opts.maxBudgetUsd, batchSize: opts.fableBatchSize });+ if (!harness.isEnabled()) return [];+ return harness.reflectFailures(items);+}++// ββ Tier-3 structural proxy ββββββββββββββββββββββββββββββββββββββββββββββ++async function proxyLabel<T extends Trajectory>(+ t: T,+ opts: LabelOptions,+ preflight?: OraclePreflight,+): Promise<LabeledTrajectory<T>> {+ const verdict = await verifyAndEscalate({+ task: t.task ?? '',+ output: t.output ?? '',+ taskKind: t.taskKind,+ });+ const threshold = opts.minStructuralConfidence;+ const resolved =+ typeof threshold === 'number' ? verdict.score >= threshold : verdict.confident;+ return {+ ...t,+ resolved,+ resolvedBy: 'proxy:structural',+ resolvedConfidence: verdict.score,+ resolvedReason: verdict.confident+ ? 'structural signals confident'+ : `structural signals weak: ${verdict.reasons.slice(0, 3).join('; ')}`,+ ...(preflight ? { oraclePreflight: preflight } : {}),+ };+}++// ββ Tier-1 planning ββββββββββββββββββββββββββββββββββββββββββββββββββββββ++/** A trajectory can be mechanically evaluated iff it carries an actionable spec. */+export function hasMechanicalSpec(t: Trajectory): boolean {+ const s = t.testSpec;+ if (!s) return false;+ return Boolean(+ (s.failToPass && s.failToPass.length > 0) ||+ s.evalCommand ||+ s.benchSuite ||+ s.benchCase,+ );+}++/** Resolve the remote host from opts β env, never a hard-coded host. */+export function resolveRemote(remote?: string): string | null {+ const r = (remote ?? process.env.RUFLO_DISTILL_REMOTE ?? '').trim();+ return r.length > 0 ? r : null;+}++/**+ * Build the concrete command plan for a spec. Pure β constructs command strings+ * only; executes nothing. `remote` is always substituted from the parameter,+ * never hard-coded.+ */+export function buildOraclePlan(spec: TestSpec, remote: string | null): OraclePlan {+ const host = remote; // may be null; commands render `<remote>` placeholder then+ const r = host ?? '<remote>';+ const sshLocal = host ? `ssh ${host} ` : `ssh <remote> `;+ const workdir = spec.workdir ?? (spec.repo ? `~/ruflo-distill/${sanitize(spec.repo)}` : '~/ruflo-distill/work');++ // Preflight probes β reachability + the tools Tier-1 needs on the remote.+ const probeCommands = [+ `ssh -o BatchMode=yes -o ConnectTimeout=8 ${r} 'echo ok'`,+ `${sshLocal}'command -v docker >/dev/null 2>&1 && echo docker-present || echo docker-missing'`,+ `${sshLocal}'command -v darwin >/dev/null 2>&1 || npx --yes @metaharness/darwin --version'`,+ ];++ let kind: OracleKind;+ const evalCommands: string[] = [];+ let parseHint: string;++ if (spec.benchSuite || spec.benchCase) {+ kind = 'ssh-darwin-bench';+ const suite = spec.benchSuite ? `--suite ${shq(spec.benchSuite)}` : '';+ const kase = spec.benchCase ? `--case ${shq(spec.benchCase)}` : '';+ evalCommands.push(+ `${sshLocal}'cd ${workdir} && npx --yes @metaharness/darwin bench run ${suite} ${kase} --json'`.replace(/\s+/g, ' ').trim(),+ );+ parseHint = 'resolved = darwin bench run reports the case scored PASS (exit 0, json.passed=true)';+ } else if (spec.evalCommand) {+ kind = 'ssh-eval';+ evalCommands.push(`${sshLocal}'cd ${workdir} && ${spec.evalCommand}'`);+ parseHint = 'resolved = evalCommand exits 0';+ } else {+ kind = 'ssh-swebench-eval';+ if (spec.patch) {+ evalCommands.push(`${sshLocal}'cd ${workdir} && git apply - <<"PATCH"\n${spec.patch}\nPATCH'`);+ }+ const f2p = (spec.failToPass ?? []).map(shq).join(' ');+ const p2p = (spec.passToPass ?? []).map(shq).join(' ');+ evalCommands.push(+ `${sshLocal}'cd ${workdir} && npx --yes @metaharness/darwin swebench-eval` ++ `${spec.repo ? ` --repo ${shq(spec.repo)}` : ''}` ++ `${spec.baseCommit ? ` --base ${shq(spec.baseCommit)}` : ''}` ++ `${f2p ? ` --fail-to-pass ${f2p}` : ''}` ++ `${p2p ? ` --pass-to-pass ${p2p}` : ''} --json'`,+ );+ parseHint = 'resolved = all FAIL_TO_PASS now pass AND all PASS_TO_PASS still pass';+ }++ return { kind, remote: host, probeCommands, evalCommands, parseHint };+}++// ββ Default SSH runner (real exec; injectable for tests) βββββββββββββββββββββ++/**+ * Default command executor: shells out, piping any heredoc/stdin via argv only+ * (commands are self-contained strings run through `sh -c`). Never invoked on+ * the default (dry-run) path.+ */+export const defaultCommandExec: CommandExec = (cmd, args, opts) =>+ new Promise<CommandResult>((resolve) => {+ let child;+ try {+ child = spawn(cmd, args, { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });+ } catch (err) {+ resolve({ stdout: '', stderr: err instanceof Error ? err.message : String(err), code: null });+ return;+ }+ let stdout = '';+ let stderr = '';+ let done = false;+ const finish = (r: CommandResult) => { if (!done) { done = true; clearTimeout(timer); resolve(r); } };+ const timer = setTimeout(() => {+ try { child.kill('SIGTERM'); } catch { /* dead */ }+ finish({ stdout, stderr: stderr || `timed out after ${opts.timeoutMs}ms`, code: null });+ }, opts.timeoutMs);+ timer.unref?.();+ child.stdout?.on('data', (d: Buffer) => { stdout += d.toString(); });+ child.stderr?.on('data', (d: Buffer) => { stderr += d.toString(); });+ child.on('error', (e: Error) => finish({ stdout, stderr: e.message, code: null }));+ child.on('close', (code: number | null) => finish({ stdout, stderr, code }));+ });++/**+ * Build a real SSH-backed oracle runner. `exec` is injectable so tests assert+ * command construction without ever touching a network. Each plan command is+ * run via `sh -c <command-string>` so the fully-rendered ssh line executes as-is.+ */+export function createSshOracleRunner(exec: CommandExec = defaultCommandExec, timeoutMs = 15 * 60 * 1000): OracleRunner {+ const run = (command: string) => exec('sh', ['-c', command], { timeoutMs });+ return {+ async preflight(plan) {+ if (!plan.remote) return { ok: false, reason: 'no remote configured' };+ for (const c of plan.probeCommands) {+ const res = await run(c);+ if (res.code !== 0) {+ return { ok: false, reason: `probe failed (${c.slice(0, 60)}β¦): ${(res.stderr || '').slice(0, 120)}` };+ }+ }+ return { ok: true, reason: 'remote reachable; docker/darwin present' };+ },+ async runEval(plan) {+ let lastReason = 'no eval commands';+ for (const c of plan.evalCommands) {+ const res = await run(c);+ if (res.code !== 0) {+ return { resolved: false, reason: `eval failed (exit ${res.code}): ${(res.stderr || res.stdout || '').slice(0, 160)}` };+ }+ lastReason = interpretEvalStdout(res.stdout);+ if (lastReason.startsWith('NOT_RESOLVED')) {+ return { resolved: false, reason: lastReason };+ }+ }+ return { resolved: true, reason: `${plan.parseHint} β ${lastReason}` };+ },+ };+}++/** Interpret an eval command's JSON stdout for an explicit pass/fail signal. */+function interpretEvalStdout(stdout: string): string {+ const trimmed = (stdout ?? '').trim();+ const m = trimmed.match(/\{[\s\S]*\}/);+ if (m) {+ try {+ const o = JSON.parse(m[0]) as Record<string, unknown>;+ if (o.passed === false || o.resolved === false) return 'NOT_RESOLVED (json.passed=false)';+ if (o.passed === true || o.resolved === true) return 'json.passed=true';+ } catch { /* fall through to exit-code semantics */ }+ }+ return 'exit 0';+}++// ββ small helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++async function safeProbe(runner: OracleRunner, plan: OraclePlan): Promise<{ ok: boolean; reason: string }> {+ try {+ return await runner.preflight(plan);+ } catch (err) {+ return { ok: false, reason: `probe threw: ${err instanceof Error ? err.message : String(err)}` };+ }+}++async function safeRunEval(runner: OracleRunner, plan: OraclePlan, spec: TestSpec): Promise<OracleOutcome> {+ try {+ return await runner.runEval(plan, spec);+ } catch (err) {+ return { resolved: false, reason: `eval threw: ${err instanceof Error ? err.message : String(err)}` };+ }+}++function toJudgeItem(t: Trajectory): JudgeItem {+ return { id: t.id, task: t.task ?? '', output: t.output ?? '' };+}++function sanitize(s: string): string {+ return s.replace(/[^A-Za-z0-9._-]/g, '_');+}++/** Single-quote a token for safe interpolation into a shell command string. */+function shq(s: string): string {+ return `'${String(s).replace(/'/g, `'\\''`)}'`;+}++export default labelResolved;diff --git a/v3/@claude-flow/cli/src/services/fable-harness.ts b/v3/@claude-flow/cli/src/services/fable-harness.tsnew file mode 100644index 0000000000..6bd2c33e64--- /dev/null+++ b/v3/@claude-flow/cli/src/services/fable-harness.ts@@ -0,0 +1,417 @@+/**+ * fable-harness.ts β Cost-disciplined headless Fable LLM-as-judge harness.+ *+ * This is TIER 2 of the tiered `resolved` oracle (see distill-oracle.ts). When+ * a trajectory has NO mechanical test spec to execute, we judge whether its+ * completion actually resolved the task with a headless Fable model β a smarter+ * proxy than the structural verifier, but still a proxy (provenance tag+ * `judge:fable`, never presented as ground truth per ADR-169).+ *+ * ββ MEASURED COST DATA (load-bearing β this file is built around it) ββββββββ+ * `claude -p --model claude-fable-5 --output-format json` costs, per call:+ * β’ ~$1.56 when launched FROM THE PROJECT DIR β it auto-loads CLAUDE.md and+ * ~56k cache tokens of project context we do NOT want for judging.+ * β’ ~$0.34 from a CLEAN empty cwd with `--append-system-prompt` for the role.+ * β’ ~$0.02/item when we BATCH ~20 items into a single call (context amortizes+ * ~free across the batch).+ *+ * Therefore this harness MUST, and does:+ * 1. run `claude -p` from a FRESH EMPTY TEMP cwd β never the project dir, so+ * no CLAUDE.md / project context is loaded (the 5x cost driver);+ * 2. carry the judge/reflect role via `--append-system-prompt`, not a project+ * system prompt;+ * 3. BATCH N items per call (default 20) so per-item cost collapses to ~$0.02;+ * 4. pass `--max-budget-usd` as a hard per-call cap and stop launching batches+ * once the cumulative measured spend reaches the caller's budget;+ * 5. be OPT-IN and OFF BY DEFAULT β nothing here runs unless a caller+ * explicitly constructs the harness AND provides a budget cap.+ *+ * SAFETY: constructing this class spends nothing. Only `judgeBatch` /+ * `reflectFailures` spawn `claude`, and only when `maxBudgetUsd > 0`. The+ * `spawnClaude` implementation is injectable so tests never touch the real CLI.+ *+ * @module services/fable-harness+ */++import { spawn } from 'child_process';+import { mkdtemp, rm } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';++// ββ Cost model (measured β exported so callers/docs share one source) ββββββββ++export const FABLE_COST_MODEL = {+ /** Measured $/call when launched from the project dir (loads CLAUDE.md). Anti-pattern. */+ perCallProjectCwdUsd: 1.56,+ /** Measured $/call from a clean cwd with --append-system-prompt. */+ perCallCleanCwdUsd: 0.34,+ /** Measured amortized $/item when batching ~20 items per call. */+ perItemBatchedUsd: 0.02,+ /** Default items per `claude -p` call. */+ defaultBatchSize: 20,+ /** The judge model. */+ model: 'claude-fable-5',+} as const;++/**+ * Estimate the USD cost of judging `itemCount` items in batches of `batchSize`.+ * Uses the measured amortized per-item figure; callers use this to size a+ * budget cap before opting in.+ */+export function estimateFableCostUsd(itemCount: number, batchSize: number = FABLE_COST_MODEL.defaultBatchSize): number {+ if (itemCount <= 0) return 0;+ const batches = Math.ceil(itemCount / Math.max(1, batchSize));+ // Amortized per-item dominates; add a tiny floor per batch for the base call.+ const perItem = itemCount * FABLE_COST_MODEL.perItemBatchedUsd;+ const perBatchFloor = batches * 0.0; // per-item figure already includes base amortization+ return Number((perItem + perBatchFloor).toFixed(4));+}++// ββ Types ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++/** One item to judge: did `output` actually resolve `task`? */+export interface JudgeItem {+ id: string;+ task: string;+ output: string;+}++/** Verdict for a single judged item. */+export interface JudgeResult {+ id: string;+ resolved: boolean;+ /** 0..1 self-reported judge confidence. */+ confidence: number;+ reason: string;+}++/** One item for reflective failure analysis (GEPA/evolve mutation input). */+export interface ReflectItem {+ id: string;+ task: string;+ output: string;+ /** Optional signal that this trajectory is believed to have failed. */+ failureHint?: string;+}++/** Reflective diagnosis for a single item (the reflective-mutation SOTA trick). */+export interface ReflectResult {+ id: string;+ failureClass: string;+ diagnosis: string;+ mutationHint: string;+}++/** Result of a raw claude spawn. */+export interface ClaudeSpawnResult {+ stdout: string;+ stderr: string;+ code: number | null;+ /** Measured spend for this call, parsed from the JSON envelope when present. */+ costUsd?: number;+}++/**+ * Injectable spawner. Receives the argv (after `claude`), the prompt to pipe to+ * stdin, and the cwd (a fresh empty temp dir). Default implementation shells out+ * to the real `claude` CLI; tests inject a fake.+ */+export type ClaudeSpawnFn = (+ argv: string[],+ stdinPrompt: string,+ cwd: string,+ opts: { timeoutMs: number },+) => Promise<ClaudeSpawnResult>;++export interface FableHarnessOptions {+ /** Model id (default claude-fable-5). */+ model?: string;+ /** Items per `claude -p` call (default 20). */+ batchSize?: number;+ /**+ * Hard budget cap in USD across all calls this harness makes. REQUIRED to be+ * > 0 for any spend to happen β 0/undefined means the harness refuses to+ * spawn (safe default).+ */+ maxBudgetUsd?: number;+ /** Per-call timeout (default 5 min). */+ timeoutMs?: number;+ /** Injected spawner for tests; defaults to the real `claude` CLI. */+ spawnClaude?: ClaudeSpawnFn;+}++// ββ Prompt templates (carried via --append-system-prompt) ββββββββββββββββββββ++const JUDGE_SYSTEM_PROMPT = [+ 'You are a strict evaluator judging whether an agent trajectory RESOLVED its task.',+ 'You receive a JSON array of items: [{id, task, output}].',+ 'For each item decide if `output` genuinely and correctly resolves `task`.',+ 'Be conservative: plausible-but-unverified or partial completions are NOT resolved.',+ 'Reply with ONLY a JSON array, one object per input id, no prose:',+ '[{"id": "...", "resolved": true|false, "confidence": 0.0-1.0, "reason": "<one sentence>"}]',+].join('\n');++const REFLECT_SYSTEM_PROMPT = [+ 'You are a failure-analysis expert supporting reflective mutation (GEPA/evolve).',+ 'You receive a JSON array of items: [{id, task, output, failureHint?}].',+ 'For each item, classify the failure and propose a concrete mutation hint.',+ 'Reply with ONLY a JSON array, one object per input id, no prose:',+ '[{"id":"...","failureClass":"<short label>","diagnosis":"<one sentence>","mutationHint":"<actionable>"}]',+].join('\n');++// ββ Default spawner (real CLI) βββββββββββββββββββββββββββββββββββββββββββββββ++/**+ * Default `claude -p` spawner. Pipes the prompt via stdin (never as an argv+ * positional β mirrors the #1852 fix so shell metachars in prompts are never+ * re-tokenized), runs in the provided (temp) cwd, and returns stdout/stderr.+ * Parses `total_cost_usd` from the `--output-format json` envelope when present.+ */+export const defaultSpawnClaude: ClaudeSpawnFn = (argv, stdinPrompt, cwd, opts) =>+ new Promise<ClaudeSpawnResult>((resolve) => {+ let child;+ try {+ child = spawn('claude', argv, {+ cwd,+ env: { ...process.env, CLAUDE_ENTRYPOINT: 'fable-judge' },+ stdio: ['pipe', 'pipe', 'pipe'],+ windowsHide: true,+ });+ } catch (err) {+ resolve({ stdout: '', stderr: err instanceof Error ? err.message : String(err), code: null });+ return;+ }++ let stdout = '';+ let stderr = '';+ let done = false;+ const finish = (r: ClaudeSpawnResult) => {+ if (done) return;+ done = true;+ clearTimeout(timer);+ resolve(r);+ };++ const timer = setTimeout(() => {+ try { child.kill('SIGTERM'); } catch { /* already dead */ }+ finish({ stdout, stderr: stderr || `timed out after ${opts.timeoutMs}ms`, code: null });+ }, opts.timeoutMs);+ timer.unref?.();++ try { child.stdin?.end(stdinPrompt); } catch { /* surfaced via error */ }+ child.stdout?.on('data', (d: Buffer) => { stdout += d.toString(); });+ child.stderr?.on('data', (d: Buffer) => { stderr += d.toString(); });+ child.on('error', (e: Error) => finish({ stdout, stderr: e.message, code: null }));+ child.on('close', (code: number | null) => {+ finish({ stdout, stderr, code, costUsd: parseCostFromEnvelope(stdout) });+ });+ });++/** Pull `total_cost_usd`/`cost_usd` out of a claude `--output-format json` envelope. */+export function parseCostFromEnvelope(stdout: string): number | undefined {+ const env = tryParseJson(stdout);+ if (env && typeof env === 'object') {+ const o = env as Record<string, unknown>;+ for (const k of ['total_cost_usd', 'cost_usd', 'costUsd']) {+ if (typeof o[k] === 'number') return o[k] as number;+ }+ }+ return undefined;+}++// ββ Harness ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++export class FableHarness {+ private readonly model: string;+ private readonly batchSize: number;+ private readonly maxBudgetUsd: number;+ private readonly timeoutMs: number;+ private readonly spawnClaude: ClaudeSpawnFn;+ private spentUsd = 0;++ constructor(opts: FableHarnessOptions = {}) {+ this.model = opts.model ?? FABLE_COST_MODEL.model;+ this.batchSize = Math.max(1, opts.batchSize ?? FABLE_COST_MODEL.defaultBatchSize);+ this.maxBudgetUsd = opts.maxBudgetUsd ?? 0;+ this.timeoutMs = opts.timeoutMs ?? 5 * 60 * 1000;+ this.spawnClaude = opts.spawnClaude ?? defaultSpawnClaude;+ }++ /** Cumulative measured spend across all calls this harness has made. */+ getSpentUsd(): number {+ return Number(this.spentUsd.toFixed(4));+ }++ /** True when a positive budget cap is configured (a precondition for any spend). */+ isEnabled(): boolean {+ return this.maxBudgetUsd > 0;+ }++ /**+ * Judge a set of items in batches. Returns one JudgeResult per input id that+ * the model returned. Items that fall outside the budget, or that the model+ * omits, are simply absent from the result β the caller (distill-oracle) is+ * responsible for falling back to the structural proxy for those.+ *+ * Spends $0 and returns [] when no budget cap is configured.+ */+ async judgeBatch(items: JudgeItem[]): Promise<JudgeResult[]> {+ if (items.length === 0) return [];+ if (!this.isEnabled()) return [];+ const out: JudgeResult[] = [];+ for (const batch of chunk(items, this.batchSize)) {+ if (this.spentUsd >= this.maxBudgetUsd) break;+ const parsed = await this.runBatch(JUDGE_SYSTEM_PROMPT, batch);+ for (const raw of parsed) {+ const r = normalizeJudge(raw);+ if (r) out.push(r);+ }+ }+ return out;+ }++ /**+ * Reflective failure analysis over items β the second cost-disciplined entry+ * point, used by GEPA/evolve for mutation hints. Same batching + budget+ * discipline as judgeBatch. Returns [] when no budget cap is configured.+ */+ async reflectFailures(items: ReflectItem[]): Promise<ReflectResult[]> {+ if (items.length === 0) return [];+ if (!this.isEnabled()) return [];+ const out: ReflectResult[] = [];+ for (const batch of chunk(items, this.batchSize)) {+ if (this.spentUsd >= this.maxBudgetUsd) break;+ const parsed = await this.runBatch(REFLECT_SYSTEM_PROMPT, batch);+ for (const raw of parsed) {+ const r = normalizeReflect(raw);+ if (r) out.push(r);+ }+ }+ return out;+ }++ /** Build the argv for a `claude -p` call. Exposed shape for testability. */+ buildArgv(systemPrompt: string): string[] {+ const perCallCap = Math.max(0, this.maxBudgetUsd - this.spentUsd);+ return [+ '-p',+ '--model', this.model,+ '--output-format', 'json',+ '--append-system-prompt', systemPrompt,+ '--max-budget-usd', String(round(perCallCap)),+ ];+ }++ /**+ * Run one batch: create a FRESH EMPTY temp cwd (critical β no project+ * context), spawn `claude -p` there with the role via --append-system-prompt,+ * pipe the batch JSON to stdin, parse the verdict array out of the envelope,+ * and account the measured spend.+ */+ private async runBatch(systemPrompt: string, batch: readonly unknown[]): Promise<unknown[]> {+ const argv = this.buildArgv(systemPrompt);+ const stdinPrompt = JSON.stringify(batch);+ const cwd = await mkdtemp(join(tmpdir(), 'ruflo-fable-'));+ try {+ const res = await this.spawnClaude(argv, stdinPrompt, cwd, { timeoutMs: this.timeoutMs });+ // Account spend: prefer measured envelope cost, else the amortized estimate.+ this.spentUsd += typeof res.costUsd === 'number'+ ? res.costUsd+ : estimateFableCostUsd(batch.length, this.batchSize);+ if (res.code !== 0 && !res.stdout) return [];+ return extractVerdictArray(res.stdout);+ } finally {+ await rm(cwd, { recursive: true, force: true }).catch(() => { /* best-effort cleanup */ });+ }+ }+}++// ββ Parsing helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββ++/**+ * Extract the model's verdict array. `claude -p --output-format json` wraps the+ * assistant text in an envelope `{ result: "<text>", ... }`; the text is itself+ * the JSON array we asked for. Handle both the enveloped and bare forms, and+ * arrays fenced in ```json blocks.+ */+export function extractVerdictArray(stdout: string): unknown[] {+ const trimmed = (stdout ?? '').trim();+ if (!trimmed) return [];++ // 1. Enveloped: parse envelope, then its `result` field.+ const env = tryParseJson(trimmed);+ if (env && typeof env === 'object' && !Array.isArray(env)) {+ const result = (env as Record<string, unknown>).result;+ if (typeof result === 'string') {+ const inner = findJsonArray(result);+ if (inner) return inner;+ }+ // Some envelopes embed the array directly.+ const direct = (env as Record<string, unknown>).results;+ if (Array.isArray(direct)) return direct;+ }+ if (Array.isArray(env)) return env;++ // 2. Bare text: find a JSON array anywhere in stdout.+ const arr = findJsonArray(trimmed);+ return arr ?? [];+}++function findJsonArray(text: string): unknown[] | null {+ const fenced = text.match(/```(?:json)?\s*(\[[\s\S]*?\])\s*```/);+ if (fenced) {+ const v = tryParseJson(fenced[1]);+ if (Array.isArray(v)) return v;+ }+ const bare = text.match(/\[[\s\S]*\]/);+ if (bare) {+ const v = tryParseJson(bare[0]);+ if (Array.isArray(v)) return v;+ }+ return null;+}++function normalizeJudge(raw: unknown): JudgeResult | null {+ if (!raw || typeof raw !== 'object') return null;+ const o = raw as Record<string, unknown>;+ if (typeof o.id !== 'string') return null;+ return {+ id: o.id,+ resolved: o.resolved === true || o.resolved === 'true',+ confidence: clamp01(typeof o.confidence === 'number' ? o.confidence : Number(o.confidence)),+ reason: typeof o.reason === 'string' ? o.reason : '',+ };+}++function normalizeReflect(raw: unknown): ReflectResult | null {+ if (!raw || typeof raw !== 'object') return null;+ const o = raw as Record<string, unknown>;+ if (typeof o.id !== 'string') return null;+ return {+ id: o.id,+ failureClass: typeof o.failureClass === 'string' ? o.failureClass : 'unknown',+ diagnosis: typeof o.diagnosis === 'string' ? o.diagnosis : '',+ mutationHint: typeof o.mutationHint === 'string' ? o.mutationHint : '',+ };+}++function tryParseJson(s: string): unknown {+ try { return JSON.parse(s); } catch { return undefined; }+}++function chunk<T>(arr: T[], size: number): T[][] {+ const out: T[][] = [];+ for (let i = 0; i < arr.length; i += size) out.push(arr.slice(i, i + size));+ return out;+}++function clamp01(n: number): number {+ if (!Number.isFinite(n)) return 0;+ return Math.max(0, Math.min(1, n));+}++function round(n: number): number {+ return Math.round(n * 100) / 100;+}++export default FableHarness;diff --git a/v3/@claude-flow/cli/src/services/swarm-memory-branches.ts b/v3/@claude-flow/cli/src/services/swarm-memory-branches.tsnew file mode 100644index 0000000000..4f71b69822--- /dev/null+++ b/v3/@claude-flow/cli/src/services/swarm-memory-branches.ts@@ -0,0 +1,278 @@+/**+ * SwarmMemoryBranches β per-agent Copy-On-Write memory branching for swarms.+ *+ * ## Why this exists+ *+ * The v3.14.4 release uncovered a tarball-bloat regression: the Darwin+ * git-worktree-per-agent pattern accumulated 3.3 GB of disk because each+ * agent got a *full copy* of shared state. `agenticow` (a sibling RVF-based+ * COW vector store by the same author) forks a branch in a measured **162+ * bytes** regardless of base size β read-through semantics (parent βͺ edits,+ * child wins) instead of a linear-growth snapshot.+ *+ * This service is the swarm-facing consumer of that primitive. The pattern+ * mirrors `agenticow`'s own `examples/parallel-agents`:+ *+ * shared base .rvf+ * β each agent forks a 162-byte COW branch (nativeAnn:true) at spawn+ * β the agent reads/writes its branch in isolation+ * β on success: promote branch β base (merge its edits back)+ * β on failure: discard the branch file (throw the edits away)+ *+ * ## Honest scope (the seam)+ *+ * The current `agent_spawn` MCP path (src/mcp-tools/agent-tools.ts) stores an+ * agent as pure JSON metadata β it does **not** create, copy, or hold any+ * per-agent `.rvf` workspace today. So there is no full-copy for a COW branch+ * to "replace" inline. This service therefore wires in as an **opt-in**: a+ * swarm/agent that actually wants an isolated memory workspace passes a base+ * memory path, and only then does a branch get forked. Default behavior is+ * unchanged.+ *+ * ## Non-fatal + kill-switch (ADR-150)+ *+ * - `agenticow` is an optional dependency β every method degrades to+ * `{ degraded: true }` when it is absent (never throws MODULE_NOT_FOUND).+ * - The `CLAUDE_FLOW_NO_COW_MEMORY=1` env var hard-disables branching so an+ * operator can kill the feature without a redeploy.+ * - agenticow is loaded lazily (dynamic import inside `loadAgenticow`), so+ * importing this module does NOT pull agenticow onto the CLI startup path.+ *+ * @module @claude-flow/cli/services/swarm-memory-branches+ */++import { existsSync, mkdirSync, readFileSync, writeFileSync, rmSync } from 'node:fs';+import { dirname, join, basename } from 'node:path';+import { getProjectCwd } from '../mcp-tools/types.js';+import {+ loadAgenticow,+ resolveMemoryPath,+ manifestFor,+ validateLabel,+ openWithLineage,+} from '../mcp-tools/agenticow-loader.js';++/** Env var that hard-disables per-agent COW branching (operator kill switch). */+export const COW_KILL_SWITCH_ENV = 'CLAUDE_FLOW_NO_COW_MEMORY';++/** True unless the operator set the kill switch. */+export function cowMemoryEnabled(): boolean {+ const v = process.env[COW_KILL_SWITCH_ENV];+ return !(v === '1' || v === 'true' || v === 'yes');+}++/** Persisted mapping so promote/discard (a later, separate call) can find the branch. */+export interface BranchRecord {+ agentId: string;+ basePath: string;+ branchPath: string;+ label: string;+ createdAt: string;+}++interface BranchRegistry {+ version: string;+ branches: Record<string, BranchRecord>;+}++export interface BranchResult {+ success: boolean;+ agentId: string;+ basePath?: string;+ branchPath?: string;+ label?: string;+ /** Set when the operation was a no-op because COW is unavailable/disabled. */+ degraded?: true;+ reason?: string;+}++export interface PromoteResult {+ success: boolean;+ agentId: string;+ promoted: boolean;+ branchPath?: string;+ basePath?: string;+ degraded?: true;+ reason?: string;+}++export interface DiscardResult {+ success: boolean;+ agentId: string;+ discarded: boolean;+ branchPath?: string;+ reason?: string;+}++const REGISTRY_REL = join('.claude-flow', 'swarm', 'cow-branches.json');++/**+ * Manages the branchβbase COW lifecycle for a swarm's agents. One instance per+ * project cwd; state is persisted to `.claude-flow/swarm/cow-branches.json` so+ * a branch forked in `branchForAgent` survives to a later `promoteAgent` /+ * `discardAgent` call in a different process.+ */+export class SwarmMemoryBranches {+ private readonly registryPath: string;++ /**+ * @param registryPath Override the registry location (tests point this at a+ * temp dir). Defaults to `<cwd>/.claude-flow/swarm/cow-branches.json`.+ */+ constructor(registryPath?: string) {+ this.registryPath = registryPath ?? join(getProjectCwd(), REGISTRY_REL);+ }++ // ---- registry persistence -------------------------------------------------++ private loadRegistry(): BranchRegistry {+ try {+ if (existsSync(this.registryPath)) {+ const parsed = JSON.parse(readFileSync(this.registryPath, 'utf-8'));+ if (parsed && typeof parsed === 'object' && parsed.branches) return parsed as BranchRegistry;+ }+ } catch { /* fall through to empty */ }+ return { version: '1.0.0', branches: {} };+ }++ private saveRegistry(reg: BranchRegistry): void {+ mkdirSync(dirname(this.registryPath), { recursive: true });+ writeFileSync(this.registryPath, JSON.stringify(reg, null, 2), 'utf-8');+ }++ /** Look up the branch record for an agent, if one was forked. */+ getBranch(agentId: string): BranchRecord | undefined {+ return this.loadRegistry().branches[agentId];+ }++ /**+ * Deterministic per-agent branch path: `<baseDir>/.swarm-cow/<base>.<agentId>.rvf`.+ * Keeps branch files namespaced next to their base so cleanup is obvious.+ */+ private branchPathFor(basePath: string, agentId: string): string {+ const safeAgent = agentId.replace(/[^A-Za-z0-9_.\-]/g, '_');+ const baseName = basename(basePath).replace(/\.rvf$/i, '');+ return join(dirname(basePath), '.swarm-cow', `${baseName}.${safeAgent}.rvf`);+ }++ // ---- lifecycle ------------------------------------------------------------++ /**+ * Fork a 162-byte COW branch off `base` for `agentId`. The agent then owns+ * an isolated read/write view (parent βͺ its own edits). Idempotent: a second+ * call for the same agent returns the existing branch record.+ *+ * @param base Path to the shared base `.rvf` (absolute or cwd-relative).+ * @param agentId Agent that owns the branch (used as the COW label).+ * @param opts.dimension Required only when `base` does not yet exist.+ * @param opts.nativeAnn Fork with the native Rust ANN path (default true β+ * agent branches are meant to be queried).+ */+ async branchForAgent(+ base: string,+ agentId: string,+ opts: { dimension?: number; nativeAnn?: boolean } = {},+ ): Promise<BranchResult> {+ if (!cowMemoryEnabled()) {+ return { success: true, agentId, degraded: true, reason: 'cow-memory-disabled' };+ }+ const api = await loadAgenticow();+ if (!api) return { success: true, agentId, degraded: true, reason: 'agenticow-not-found' };++ const label = validateLabel(agentId);+ const basePath = resolveMemoryPath(base);++ // Idempotent β a retried spawn must not double-fork.+ const existing = this.getBranch(agentId);+ if (existing && existsSync(existing.branchPath)) {+ return {+ success: true, agentId,+ basePath: existing.basePath, branchPath: existing.branchPath, label: existing.label,+ };+ }++ const branchPath = this.branchPathFor(basePath, agentId);+ mkdirSync(dirname(branchPath), { recursive: true });+ const nativeAnn = opts.nativeAnn !== false;++ const baseMem = await openWithLineage(api, basePath, opts.dimension);+ try {+ const branch = await baseMem.fork(label, branchPath, { nativeAnn });+ // Persist lineage manifests so the branch + base reopen with the COW+ // chain intact β without this, the fork is in-memory only.+ await branch.save?.(manifestFor(branchPath));+ await baseMem.save?.(manifestFor(basePath));+ await branch.close?.();+ } finally {+ await baseMem.close?.();+ }++ const reg = this.loadRegistry();+ reg.branches[agentId] = {+ agentId, basePath, branchPath, label, createdAt: new Date().toISOString(),+ };+ this.saveRegistry(reg);++ return { success: true, agentId, basePath, branchPath, label };+ }++ /**+ * Promote an agent's branch back into its base (merge its edits + tombstones+ * atomically), then delete the branch file and drop it from the registry.+ * Call on agent success. No-op (`promoted:false`) when the agent has no+ * branch.+ */+ async promoteAgent(agentId: string): Promise<PromoteResult> {+ const rec = this.getBranch(agentId);+ if (!rec) return { success: true, agentId, promoted: false, reason: 'no-branch' };++ const api = await loadAgenticow();+ if (!api) return { success: true, agentId, promoted: false, degraded: true, reason: 'agenticow-not-found' };++ if (existsSync(manifestFor(rec.branchPath)) || existsSync(rec.branchPath)) {+ const branch = await openWithLineage(api, rec.branchPath);+ const baseMem = await openWithLineage(api, rec.basePath);+ try {+ await branch.promote(baseMem);+ await branch.save?.(manifestFor(rec.branchPath));+ await baseMem.save?.(manifestFor(rec.basePath));+ } finally {+ await branch.close?.();+ await baseMem.close?.();+ }+ }++ this.removeBranchFiles(rec.branchPath);+ this.forgetBranch(agentId);+ return { success: true, agentId, promoted: true, branchPath: rec.branchPath, basePath: rec.basePath };+ }++ /**+ * Discard an agent's branch β delete the branch file + lineage manifest and+ * drop the registry entry, WITHOUT merging anything into base. Call on agent+ * failure. No-op (`discarded:false`) when the agent has no branch. Never+ * touches agenticow (pure filesystem), so it works even in the degraded path.+ */+ async discardAgent(agentId: string): Promise<DiscardResult> {+ const rec = this.getBranch(agentId);+ if (!rec) return { success: true, agentId, discarded: false, reason: 'no-branch' };+ this.removeBranchFiles(rec.branchPath);+ this.forgetBranch(agentId);+ return { success: true, agentId, discarded: true, branchPath: rec.branchPath };+ }++ // ---- helpers --------------------------------------------------------------++ private removeBranchFiles(branchPath: string): void {+ try { rmSync(branchPath, { recursive: true, force: true }); } catch { /* best-effort */ }+ try { rmSync(manifestFor(branchPath), { force: true }); } catch { /* best-effort */ }+ }++ private forgetBranch(agentId: string): void {+ const reg = this.loadRegistry();+ if (reg.branches[agentId]) {+ delete reg.branches[agentId];+ this.saveRegistry(reg);+ }+ }+}diff --git a/v3/@claude-flow/cli/src/services/weight-eft.ts b/v3/@claude-flow/cli/src/services/weight-eft.tsnew file mode 100644index 0000000000..ad8e356829--- /dev/null+++ b/v3/@claude-flow/cli/src/services/weight-eft.ts@@ -0,0 +1,506 @@+/**+ * weight-eft.ts β Optional-dependency service wrapper around+ * `@metaharness/weight-eft` (agenticow / ADR-150 weight-eft slice).+ *+ * WHAT THIS SHIPS (and what it deliberately does NOT)+ * ---------------------------------------------------+ * This service turns ruflo's captured run transcripts into AUDITED TRAINING+ * DATA + a COST-PARETO measurement + a GPU TRAINING PLAN. It does NOT train a+ * model and it does NOT "reduce escalation":+ * - `runExport` β SFT (OpenAI chat) + DPO (TRL preference) JSONL + a guard+ * report (contamination / reward-hack / long-context). $0.+ * - `runPlan` β the GPU training plan + the exact `ruvllm microlora`+ * command a GPU host would run. $0 dry-run β never spawns.+ * - `runEval` β the cost-Pareto delta folded from two CascadeOutcome[]. $0.+ * - `runRemoteTrain` β an SSH-based remote-GPU invocation. DRY-RUN by default+ * (prints commands + read-only preflight); real compute only+ * behind explicit `execute && yes`. This is the ONLY path+ * that can spend, and it spends on the USER's host, not $0.+ *+ * HARD HONESTY RULE (do not overclaim): weight-eft's own `train` never spawns+ * (its README Β§Status), and no GPU tune has run here. `resolved` in the+ * captured archive is a PROXY (ruflo has no SWE-bench gold oracle) β the SFT+ * data-quality caveat stands. Nothing here claims ruflo "trains a model" as a+ * $0/local capability.+ *+ * ADR-150 GRACEFUL DEGRADATION+ * ----------------------------+ * `@metaharness/weight-eft` is an OPTIONAL dependency. Every entry point loads+ * it via a dynamic import through `loadWeightEft()` and returns a structured+ * `{ degraded: true }` result when it is absent β never a throw. There is NO+ * static `import β¦ from '@metaharness/weight-eft'` anywhere in this file; the+ * types below are LOCAL mirrors so tsc stays green with the package removed.+ *+ * @module services/weight-eft+ */++import { spawnSync } from 'node:child_process';++import type { RunTranscriptRecord } from '../ruvector/run-transcript-recorder.js';++// ============================================================================+// LOCAL type mirrors of @metaharness/weight-eft (no static import β ADR-150)+// ============================================================================++export interface WeftToolCall { id: string; type: 'function'; function: { name: string; arguments: string } }+export interface WeftChatMessage {+ role: 'system' | 'user' | 'assistant' | 'tool';+ content: string | null;+ tool_calls?: WeftToolCall[];+ tool_call_id?: string;+ name?: string;+}+export type WeftPolicyTier = 'cheap' | 'frontier';++/** Input contract for the exporter. Mirrors weight-eft's DarwinTrajectory. */+export interface DarwinTrajectory {+ instance_id: string;+ model: string;+ tier: WeftPolicyTier;+ resolved: boolean;+ messages: WeftChatMessage[];+ model_patch: string;+ sample?: number;+ source?: string;+}++export interface WeftExportReport {+ totalTrajectories: number;+ excludedByHoldout: number;+ droppedOverLength: number;+ truncatedOverLength: number;+ droppedRewardHacked: number;+ sftRows: number;+ dpoRows: number;+ sftInstanceIds: string[];+ dpoInstanceIds: string[];+ notes: string[];+}++export interface WeftCascadeOutcome {+ instance_id: string;+ cheapResolved: boolean;+ escalated: boolean;+ resolved: boolean;+ costUsd: number;+}++export interface WeftCostParetoDelta {+ base: unknown;+ adapter: unknown;+ cheapResolveLift: number;+ escalationRateReduction: number;+ costPerResolvedReduction: number;+ resolveRateDelta: number;+ verdict: string;+}++export interface WeftBaseModelSpec { id: string; paramsB: number }+export interface WeftTrainingPlan { config: unknown; command: string; summary: string }++/** The subset of the weight-eft module surface this service calls. */+interface WeightEftApi {+ exportTrainingData: (t: DarwinTrajectory[], o: {+ evalHoldout: string[]; maxTokens?: number; truncateOverLength?: boolean; dropRewardHacked?: boolean;+ }) => { sft: { messages: WeftChatMessage[] }[]; dpo: unknown[]; report: WeftExportReport };+ sftToJsonl: (rows: { messages: WeftChatMessage[] }[]) => string;+ dpoToJsonl: (rows: unknown[]) => string;+ costParetoDelta: (base: WeftCascadeOutcome[], adapter: WeftCascadeOutcome[]) => WeftCostParetoDelta;+ twoStagePlan: (base: WeftBaseModelSpec, sftPath: string, dpoPath: string, adapterPrefix: string) => {+ sft: WeftTrainingPlan; dpo: WeftTrainingPlan;+ };+}++/** Injectable importer so tests can force the degraded path deterministically. */+export type WeightEftImporter = () => Promise<unknown>;++const WEIGHT_EFT_PKG = '@metaharness/weight-eft';++/**+ * Load `@metaharness/weight-eft` (optional dep). Returns the module or `null`+ * when it is absent/broken. Never throws. The specifier is held in a variable+ * so tsc does not statically resolve the package (keeps the build green when+ * the optional dep is removed β ADR-150).+ */+export async function loadWeightEft(importer?: WeightEftImporter): Promise<WeightEftApi | null> {+ const load = importer ?? (() => import(/* @vite-ignore */ WEIGHT_EFT_PKG));+ try {+ const mod = (await load()) as Partial<WeightEftApi> & { default?: Partial<WeightEftApi> };+ const api = (mod && typeof mod.exportTrainingData === 'function' ? mod : mod?.default) as WeightEftApi | undefined;+ if (!api || typeof api.exportTrainingData !== 'function') return null;+ return api;+ } catch {+ return null; // MODULE_NOT_FOUND or any load error β degraded+ }+}++// ============================================================================+// Archive-builder: ruflo run records β DarwinTrajectory[] (unit-tested)+// ============================================================================++export interface ArchiveBuildStats {+ total: number;+ resolved: number;+ byTier: Record<WeftPolicyTier, number>;+ /** Honest breakdown: how many `resolved` booleans came from which proxy. */+ byResolvedSource: Record<string, number>;+ skipped: number;+}++export interface ArchiveBuildResult {+ trajectories: DarwinTrajectory[];+ stats: ArchiveBuildStats;+ /** Load-bearing honesty banner surfaced to CLI/report output. */+ proxyNote: string;+}++/**+ * Map captured ruflo run transcripts to the DarwinTrajectory[] contract the+ * weight-eft exporter codes against. PURE + synchronous β this is the seam the+ * archive-builder unit test exercises.+ *+ * A record is skipped (not thrown) when it lacks the minimum an exporter needs:+ * an instance_id and a non-empty messages array. `resolved` is copied verbatim+ * and its proxy provenance is tallied so the caller can print an honest note.+ */+export function buildArchiveFromRecords(records: RunTranscriptRecord[]): ArchiveBuildResult {+ const trajectories: DarwinTrajectory[] = [];+ const stats: ArchiveBuildStats = {+ total: 0, resolved: 0, byTier: { cheap: 0, frontier: 0 }, byResolvedSource: {}, skipped: 0,+ };+ let hasGold = false;++ for (const r of records) {+ if (!r || !r.instance_id || !Array.isArray(r.messages) || r.messages.length === 0) {+ stats.skipped++;+ continue;+ }+ const tier: WeftPolicyTier = r.tier === 'cheap' ? 'cheap' : 'frontier';+ trajectories.push({+ instance_id: r.instance_id,+ model: r.model,+ tier,+ resolved: !!r.resolved,+ messages: r.messages as WeftChatMessage[],+ model_patch: r.model_patch ?? '',+ sample: r.sample ?? 0,+ ...(r.source ? { source: r.source } : {}),+ });+ stats.total++;+ stats.byTier[tier]++;+ if (r.resolved) stats.resolved++;+ const src = r.resolved_source ?? 'external';+ stats.byResolvedSource[src] = (stats.byResolvedSource[src] ?? 0) + 1;+ if (src === 'gold-oracle') hasGold = true;+ }++ const proxyNote = hasGold+ ? 'resolved: some records carry gold-oracle status; others are proxies (see byResolvedSource).'+ : 'resolved is a PROXY β ruflo has no SWE-bench gold oracle. `output-verifier`/`api-success` ' ++ 'labels are explicitly-marked proxies, NOT conformant gold eval. SFT/DPO quality is bounded by this.';++ return { trajectories, stats, proxyNote };+}++// ============================================================================+// export | plan | eval ($0, offline, no creds)+// ============================================================================++export type ExportOutcome =+ | {+ degraded: false;+ report: WeftExportReport;+ sftJsonl: string;+ dpoJsonl: string;+ sftRows: number;+ dpoRows: number;+ }+ | { degraded: true; reason: string };++/** Run the weight-eft exporter over a DarwinTrajectory[] archive. $0. */+export async function runExport(opts: {+ archive: DarwinTrajectory[];+ evalHoldout?: string[];+ maxTokens?: number;+ truncateOverLength?: boolean;+ dropRewardHacked?: boolean;+ importer?: WeightEftImporter;+}): Promise<ExportOutcome> {+ const api = await loadWeightEft(opts.importer);+ if (!api) return { degraded: true, reason: 'weight-eft-not-available' };+ try {+ const res = api.exportTrainingData(opts.archive, {+ evalHoldout: opts.evalHoldout ?? [],+ ...(opts.maxTokens != null ? { maxTokens: opts.maxTokens } : {}),+ ...(opts.truncateOverLength != null ? { truncateOverLength: opts.truncateOverLength } : {}),+ // reward-hack filter defaults ON inside weight-eft; only forward an explicit override+ ...(opts.dropRewardHacked != null ? { dropRewardHacked: opts.dropRewardHacked } : {}),+ });+ return {+ degraded: false,+ report: res.report,+ sftJsonl: api.sftToJsonl(res.sft),+ dpoJsonl: api.dpoToJsonl(res.dpo),+ sftRows: res.sft.length,+ dpoRows: res.dpo.length,+ };+ } catch (e) {+ // exportTrainingData throws on contamination-guard violation β surface it.+ return { degraded: true, reason: `export-failed: ${(e as Error).message}` };+ }+}++export type PlanOutcome =+ | { degraded: false; base: WeftBaseModelSpec; sft: WeftTrainingPlan; dpo: WeftTrainingPlan }+ | { degraded: true; reason: string };++/** Emit the two-stage (SFT β on-policy DPO) GPU training plan. $0 dry-run. */+export async function runPlan(opts: {+ base?: WeftBaseModelSpec;+ sftPath: string;+ dpoPath: string;+ adapterPrefix?: string;+ importer?: WeightEftImporter;+}): Promise<PlanOutcome> {+ const api = await loadWeightEft(opts.importer);+ if (!api) return { degraded: true, reason: 'weight-eft-not-available' };+ const base = opts.base ?? DEFAULT_BASE_MODEL;+ try {+ const plan = api.twoStagePlan(base, opts.sftPath, opts.dpoPath, opts.adapterPrefix ?? 'ruflo-weft');+ return { degraded: false, base, sft: plan.sft, dpo: plan.dpo };+ } catch (e) {+ return { degraded: true, reason: `plan-failed: ${(e as Error).message}` };+ }+}++export type EvalOutcome =+ | { degraded: false; delta: WeftCostParetoDelta }+ | { degraded: true; reason: string };++/** Fold base + adapter CascadeOutcome[] into the cost-Pareto delta. $0. */+export async function runEval(opts: {+ baseOutcomes: WeftCascadeOutcome[];+ adapterOutcomes: WeftCascadeOutcome[];+ importer?: WeightEftImporter;+}): Promise<EvalOutcome> {+ const api = await loadWeightEft(opts.importer);+ if (!api) return { degraded: true, reason: 'weight-eft-not-available' };+ try {+ return { degraded: false, delta: api.costParetoDelta(opts.baseOutcomes, opts.adapterOutcomes) };+ } catch (e) {+ return { degraded: true, reason: `eval-failed: ${(e as Error).message}` };+ }+}++/** Default cheap-tier tune target β a 7B coder in the tunable [1,14]B band. */+export const DEFAULT_BASE_MODEL: WeftBaseModelSpec = { id: 'Qwen/Qwen2.5-Coder-7B-Instruct', paramsB: 7 };++// ============================================================================+// Remote-GPU train construction (PURE + testable) + spend-gated runner+// ============================================================================++export interface RemoteTrainArgs {+ /** SSH host or tailscale name (parameterized; never hard-coded). */+ host: string;+ /** Base model id to tune. Default DEFAULT_BASE_MODEL.id. */+ base?: string;+ /** Local path to the exported SFT jsonl. */+ sftPath: string;+ /** Local path to the exported DPO jsonl. */+ dpoPath: string;+ /** Local dir to fetch the trained LoRA adapter back into. Default .claude-flow/neural. */+ adapterDir?: string;+ /** Remote working dir. Default ~/.ruflo-weft/<runId>. */+ remoteWorkdir?: string;+ /** SSH user (default: current, i.e. no user@ prefix). */+ sshUser?: string;+ /** SSH port. Default 22. */+ sshPort?: number;+ /** Stable run id used in remote workdir + adapter names. Default derived. */+ runId?: string;+ /** Adapter name prefix. Default 'ruflo-weft'. */+ adapterPrefix?: string;+}++export interface RemoteStep { label: string; argv: string[] }++export interface RemoteTrainPlan {+ host: string;+ base: string;+ runId: string;+ remoteWorkdir: string;+ adapterDir: string;+ sftAdapter: string;+ dpoAdapter: string;+ /** Read-only reachability/capability probes (safe to run in dry-run). */+ preflight: RemoteStep[];+ /** The mutating steps: rsync data up, train, fetch adapter back. */+ steps: RemoteStep[];+ /** Rendered one-line commands for human display. */+ humanCommands: string[];+}++function sshTarget(args: { host: string; sshUser?: string }): string {+ return args.sshUser ? `${args.sshUser}@${args.host}` : args.host;+}++function sshBase(port: number): string[] {+ return ['-o', 'BatchMode=yes', '-o', 'ConnectTimeout=8', '-p', String(port)];+}++/** Render an argv as a copy-pasteable shell line (quoting args with spaces). */+function renderCmd(argv: string[]): string {+ return argv.map((a) => (/[\s"'$]/.test(a) ? `'${a.replace(/'/g, `'\\''`)}'` : a)).join(' ');+}++/**+ * Construct the exact ssh/rsync/ruvllm invocations a remote GPU tune would run.+ * PURE β no spawning, no filesystem, deterministic. This is the seam the+ * command-construction unit test exercises. The ruvllm commands mirror the+ * canonical `ruvllm microlora sft β¦ && ruvllm microlora dpo --init-from β¦`+ * plan weight-eft emits, wrapped for SSH execution on the remote host.+ */+export function buildRemoteTrainInvocation(args: RemoteTrainArgs): RemoteTrainPlan {+ const base = args.base ?? DEFAULT_BASE_MODEL.id;+ const port = args.sshPort ?? 22;+ const runId = args.runId ?? `weft-${Date.now().toString(36)}`;+ const prefix = args.adapterPrefix ?? 'ruflo-weft';+ const remoteWorkdir = args.remoteWorkdir ?? `~/.ruflo-weft/${runId}`;+ const adapterDir = args.adapterDir ?? '.claude-flow/neural';+ const target = sshTarget(args);+ const ssh = sshBase(port);+ const rsyncSsh = `ssh -p ${port}`;+ const sftAdapter = `${prefix}-${runId}-sft`;+ const dpoAdapter = `${prefix}-${runId}-dpo`;++ const preflight: RemoteStep[] = [+ { label: 'ssh reachability', argv: ['ssh', ...ssh, target, 'true'] },+ { label: 'ruvllm version', argv: ['ssh', ...ssh, target, 'ruvllm --version || echo RUVLLM_MISSING'] },+ { label: 'gpu probe', argv: ['ssh', ...ssh, target, 'nvidia-smi -L || echo NO_NVIDIA_SMI'] },+ ];++ const sftCmd =+ `cd ${remoteWorkdir} && ruvllm microlora sft --base ${base} --data sft.jsonl --output ${sftAdapter}`;+ const dpoCmd =+ `cd ${remoteWorkdir} && ruvllm microlora dpo --base ${base} --init-from ${sftAdapter} ` ++ `--data dpo.jsonl --output ${dpoAdapter}`;++ const steps: RemoteStep[] = [+ { label: 'remote mkdir', argv: ['ssh', ...ssh, target, `mkdir -p ${remoteWorkdir}`] },+ { label: 'rsync sft up', argv: ['rsync', '-az', '-e', rsyncSsh, args.sftPath, `${target}:${remoteWorkdir}/sft.jsonl`] },+ { label: 'rsync dpo up', argv: ['rsync', '-az', '-e', rsyncSsh, args.dpoPath, `${target}:${remoteWorkdir}/dpo.jsonl`] },+ { label: 'ruvllm sft (real GPU compute)', argv: ['ssh', ...ssh, target, sftCmd] },+ { label: 'ruvllm dpo (real GPU compute)', argv: ['ssh', ...ssh, target, dpoCmd] },+ { label: 'rsync adapter back', argv: ['rsync', '-az', '-e', rsyncSsh, `${target}:${remoteWorkdir}/${dpoAdapter}/`, `${adapterDir}/${dpoAdapter}/`] },+ ];++ return {+ host: args.host, base, runId, remoteWorkdir, adapterDir, sftAdapter, dpoAdapter,+ preflight, steps,+ humanCommands: [...preflight, ...steps].map((s) => renderCmd(s.argv)),+ };+}++/** Minimal spawn result shape (subset of child_process.SpawnSyncReturns). */+export interface SpawnLike { status: number | null; stdout?: string; stderr?: string; error?: Error }+export type SpawnFn = (cmd: string, argv: string[]) => SpawnLike;++export type RemoteTrainOutcome =+ | { degraded: true; reason: string }+ | {+ degraded: false;+ mode: 'dry-run' | 'refused' | 'preflight-failed' | 'executed';+ plan: RemoteTrainPlan;+ preflight?: { label: string; ok: boolean; detail: string }[];+ steps?: { label: string; ok: boolean; detail: string }[];+ reason?: string;+ };++/**+ * Run (or, by default, DRY-RUN) a remote-GPU tune. SAFETY MODEL:+ * - DEFAULT (no execute): builds the plan, runs read-only preflight probes,+ * and returns the commands that WOULD run. NO rsync of data, NO training.+ * - execute && !yes β 'refused' (real GPU spend needs an explicit second gate).+ * - execute && yes β runs preflight; if unreachable β 'preflight-failed'+ * WITHOUT training; else runs rsync + ssh ruvllm sft/dpo + fetch-back.+ * - No `ssh` binary / host unreachable / any spawn error β structured+ * degraded/preflight-failed. NEVER throws.+ *+ * `spawn` is injected for testing so CI never touches a live host.+ */+export async function runRemoteTrain(+ args: RemoteTrainArgs & { execute?: boolean; yes?: boolean; preflight?: boolean; spawn?: SpawnFn },+): Promise<RemoteTrainOutcome> {+ let plan: RemoteTrainPlan;+ try {+ plan = buildRemoteTrainInvocation(args);+ } catch (e) {+ return { degraded: true, reason: `plan-construction-failed: ${(e as Error).message}` };+ }++ const spawn: SpawnFn = args.spawn ?? defaultSpawn;++ // Preflight β read-only reachability/capability probes. These DO contact the+ // remote host (ssh ... true), so a bare dry-run must NOT run them: "no+ // implicit remote execution" (adversarial RC finding). Probes run only when+ // executing, or when the caller explicitly opts in with --preflight.+ const runProbe = (s: RemoteStep): { label: string; ok: boolean; detail: string } => {+ try {+ const r = spawn(s.argv[0], s.argv.slice(1));+ if (r.error) return { label: s.label, ok: false, detail: r.error.message };+ const out = `${r.stdout ?? ''}${r.stderr ?? ''}`.trim();+ const ok = (r.status ?? 1) === 0 && !/RUVLLM_MISSING|NO_NVIDIA_SMI/.test(out);+ return { label: s.label, ok, detail: out.slice(0, 200) || `exit ${r.status ?? 'null'}` };+ } catch (e) {+ return { label: s.label, ok: false, detail: (e as Error).message };+ }+ };+ const doProbe = args.execute === true || args.preflight === true;+ const preflight = doProbe ? plan.preflight.map(runProbe) : [];+ const reachable = preflight[0]?.ok === true;++ if (!args.execute) {+ // Bare dry-run is fully offline β plan + commands only, no host contact.+ return {+ degraded: false, mode: 'dry-run', plan, preflight,+ reason: doProbe ? undefined : 'offline dry-run β no host contacted. Add --preflight to probe reachability/GPU, or --execute --yes to train.',+ };+ }+ if (!args.yes) {+ return {+ degraded: false, mode: 'refused', plan, preflight,+ reason: '--execute runs REAL GPU compute on your host; re-run with --yes to confirm the spend.',+ };+ }+ if (!reachable) {+ return { degraded: false, mode: 'preflight-failed', plan, preflight, reason: 'ssh host not reachable β aborting before any data transfer or training.' };+ }++ // Execute the mutating steps sequentially, stopping at the first failure.+ const steps: { label: string; ok: boolean; detail: string }[] = [];+ for (const s of plan.steps) {+ let entry: { label: string; ok: boolean; detail: string };+ try {+ const r = spawn(s.argv[0], s.argv.slice(1));+ const out = `${r.stdout ?? ''}${r.stderr ?? ''}`.trim();+ entry = { label: s.label, ok: !r.error && (r.status ?? 1) === 0, detail: r.error ? r.error.message : (out.slice(0, 200) || `exit ${r.status ?? 'null'}`) };+ } catch (e) {+ entry = { label: s.label, ok: false, detail: (e as Error).message };+ }+ steps.push(entry);+ if (!entry.ok) break;+ }+ return { degraded: false, mode: 'executed', plan, preflight, steps };+}++/** Default spawn β synchronous child_process, imported lazily so this module+ * stays importable in any environment. Never throws (spawnSync surfaces+ * errors on the returned object). */+function defaultSpawn(cmd: string, argv: string[]): SpawnLike {+ try {+ const r = spawnSync(cmd, argv, { encoding: 'utf8', timeout: 30 * 60 * 1000 });+ return { status: r.status, stdout: r.stdout as string, stderr: r.stderr as string, error: r.error ?? undefined };+ } catch (e) {+ return { status: null, error: e as Error };+ }+}diff --git a/v3/docs/adr/ADR-170-agenticow-cow-memory-substrate.md b/v3/docs/adr/ADR-170-agenticow-cow-memory-substrate.mdnew file mode 100644index 0000000000..62f1298825--- /dev/null+++ b/v3/docs/adr/ADR-170-agenticow-cow-memory-substrate.md@@ -0,0 +1,62 @@+# ADR-170: agenticow Copy-On-Write Memory as an Agent-Scoped Workspace Substrate++**ID**: ADR-170+**Status**: Proposed β implemented on `feat/agenticow-integration` (ships in 3.21.0)+**Date**: 2026-07-04+**Authors**: rUv (drafted with Claude Code)+**Related ADRs**:+- ADR-150 (MetaHarness integration β the optional-dependency / graceful-degradation posture reused here)+- ADR-103 (Witness manifest β provenance discipline echoed by ADR-171)+- ADR-171 (Provenance-tiered evaluation oracle β gates promotion of the branches this ADR creates)++---++## 1. Context++`agenticow` (ruvnet, MIT, `@ruvector/rvf-node`-backed) is "Git for Agent Memory" β copy-on-write vector branching over `.rvf` files. A branch is a constant ~162 bytes regardless of base size, with read-through semantics (parent βͺ edits, child wins) and lifecycle verbs (checkpoint / rollback / promote).++ruflo already wrapped four lifecycle verbs (branch/checkpoint/rollback/promote) as MCP tools, but:+- The read/write verbs that make a branch *usable* β `ingest`, `query`, `diff`, `lineage`, `status` β were not wrapped. You could create a COW branch but not populate or read it.+- **Zero orchestration paths consumed any of it** β the tools sat in the registry, unreachable from swarm / autopilot / workflow.+- A load-bearing upstream bug: `save()` dropped per-node text payloads, so query hits lost their `text` after any manifest round-trip (fixed upstream in agenticow 0.2.4, ruvnet/agenticow#3).++The original motivation was the v3.14.4 **3.3 GB worktree-bloat regression** from Darwin's git-worktree-per-agent pattern (full-copy snapshot semantics).++## 2. Decision++Adopt agenticow as ruflo's **agent-scoped memory workspace substrate**, complete the verb surface, and wire it into orchestration behind opt-in flags. Five parts:++### 2.1 Complete verb surface (9 tools)+Add `agenticow_ingest / _query / _diff / _lineage / _status` alongside the existing four, plus a `nativeAnn` fast-path option on `agenticow_branch` (Rust dual-graph ANN, recall@10=1.0) and a targeted-`checkpointId` rollback. Floor bumped `~0.2.4` (the text-persistence fix).++### 2.2 Per-agent COW branches (opt-in)+`SwarmMemoryBranches` β `branchForAgent / promoteAgent / discardAgent` β wired into `agent_spawn` / `agent_terminate`. **Honest scope**: the swarm spawn path does not do a full `.rvf` copy today (agents are JSON metadata; the 3.3 GB bloat was the *external* Darwin worktree pattern). So this is delivered as an **opt-in agent workspace** (`memoryBase` input), not a replacement for a copy that doesn't exist β pretending otherwise would be benchmark theater.++### 2.3 Speculative branch-and-promote+`explore(base, candidates, score)` β fork a branch per candidate, run each in isolation, promote the winner, discard losers (delete 162-byte files). Exposed as `agenticow_speculate`. **Promotion is gated per ADR-171** β a winner is not eligible to graduate to base on scorer rank alone.++### 2.4 Checkpoint/rollback gate+`CheckpointGate.guard(memPath, label, fn)` β checkpoint before a risky tick, rollback on failure β wired opt-in into the autopilot loop's re-engage (checkpoint) and stall (rollback) seams. Cross-tick bracketing because the loop's memory mutation is out-of-process.++### 2.5 One shared optional-dep loader+A single `_agenticow.ts` module owns `loadAgenticow` / `resolveMemoryPath` / `manifestFor` / `validateLabel` / `openWithLineage`. Every consumer (MCP verbs, swarm branches, checkpoint gate, speculative, oracle) imports it β **first-class compatibility layer**, not per-consumer copies. (Three parallel implementations were consolidated at merge; divergent loaders are the highest merge-break risk in this integration.)++## 3. Constraints (all preserved)++- **ADR-150 optional-dependency posture**: `agenticow` in `optionalDependencies`; every path graceful-degrades to `{degraded:true, reason:'agenticow-not-found'}`; ruflo runs fully without it.+- **Startup**: agenticow is lazy-loaded β `ruflo --help` stays ~0.08s (verified).+- **Kill switches**: `CLAUDE_FLOW_NO_COW_MEMORY` / `CLAUDE_FLOW_AGENTICOW_DISABLE` per subsystem.+- **Security**: `resolveMemoryPath` rejects `..` traversal and NUL; labels constrained to `[A-Za-z0-9_.\-:/@]`.++## 4. Consequences++- Branches are real infrastructure: populable, queryable (COW read-through with provenance in the hit's `branch` field), diff-able before promote.+- The measured claims are honest: 162-byte branches confirmed; the "0.5ms / 83Γ" marketing is *not* reproduced (fixed ~10ms fork cost, wins full-copy only past ~30k-vector crossover β documented in `docs/agenticow/findings.md`).+- Everything is opt-in; default behavior is byte-identical. The value is *available*, not imposed.+- Enables the governed learning loop: branch β test β judge β promote β rollback (ADR-171).++## 5. Alternatives rejected++- **Re-track the git-worktree copy**: that was the bloat. Rejected.+- **Force branching on every spawn**: invents a workspace nothing consumes; inflates every run. Rejected in favor of opt-in.+- **Per-consumer loaders**: caused the merge-break risk; consolidated to one.diff --git a/v3/docs/adr/ADR-171-provenance-tiered-evaluation-oracle.md b/v3/docs/adr/ADR-171-provenance-tiered-evaluation-oracle.mdnew file mode 100644index 0000000000..addd6afbff--- /dev/null+++ b/v3/docs/adr/ADR-171-provenance-tiered-evaluation-oracle.md@@ -0,0 +1,62 @@+# ADR-171: Provenance-Tiered Evaluation Oracle for Distillation Gold-Labeling++**ID**: ADR-171+**Status**: Proposed β implemented on `feat/agenticow-integration` (ships in 3.21.0)+**Date**: 2026-07-04+**Authors**: rUv (drafted with Claude Code)+**Related ADRs**:+- ADR-169 (Benchmark reporting integrity β never present a proxy as ground truth; this ADR is that principle applied to training-data labels)+- ADR-170 (agenticow substrate β supplies the branches whose promotion this oracle gates)+- ADR-172 (Fable advisor harness β the Tier-2 judge mechanism)+- ADR-173 (Remote GPU distillation β consumes the labels this oracle produces)++---++## 1. Context++The weight-eft distillation slice (ADR-173) needs a gold `resolved: boolean` per trajectory to build SFT data. **ruflo has no SWE-bench oracle** β historically `resolved` was derived from `output-verifier` structural confidence: a *proxy*. A tune on proxy-labeled data distills plausible-but-wrong completions, and a single blended "resolved" number is exactly the benchmark theater ADR-169 forbids.++Two facts changed the calculus:+- A real GPU/compute host (`ruvultra`, tailscale) can execute actual task evaluations (FAIL_TO_PASS), giving true ground truth for trajectories that carry a test spec.+- A headless Fable judge (ADR-172) is cost-viable (~$0.02/item batched) as a smarter-than-structural labeler for the residue.++## 2. Decision++Label `resolved` through a **tiered trust hierarchy**, and **tag every label with its provenance**. Never blend tiers into one opaque score.++```+Tier 1 oracle:test-exec real evaluation (FAIL_TO_PASS via darwin bench/eval,+ executed on a remote GPU host over SSH) β GROUND TRUTH+Tier 2 judge:fable headless Fable LLM-as-judge (ADR-172) β smarter proxy+Tier 3 proxy:structural output-verifier structural confidence β WEAKEST, triage only+```++Interface:+```ts+labelResolved(trajectories, opts): Promise<Array<{+ ...trajectory,+ resolved: boolean,+ resolvedBy: 'oracle:test-exec' | 'judge:fable' | 'proxy:structural',+ resolvedConfidence?: number,+ resolvedReason?: string,+}>>+```+Tiers are tried in order per trajectory; the first that can decide wins, and its tag is recorded. **Default (no opts) = Tier-3 proxy + a Tier-1 dry-run preflight, ZERO spend, no SSH exec, no Fable call.** Tier 1 requires `--execute`; Tier 2 requires `--fable-judge` + a budget cap.++### 2.1 Promotion gate (the load-bearing rule)+A speculative branch (ADR-170 Β§2.3) is **promote-ineligible** unless its winning trajectory is cleared by `oracle:test-exec`, or by `judge:fable` **explicitly accepted** by the caller. `proxy:structural` **can never** clear a promote β it is triage-only. This is what keeps the flywheel from graduating plausible-but-wrong work into shared memory.++### 2.2 Causal failure receipts+On discard/rollback, emit a single receipt bundling `{checkpoint, diff, failing command, oracle provenance, promotion decision}`. A rollback that restores state but loses *why* is half-useful; the receipt is the forensic trail.++## 3. Consequences++- Training data and benchmark results stay auditable: every label says how it was earned. A reviewer can filter to `oracle:test-exec`-only before trusting an adapter.+- The honest residual is explicit: trajectories with no test spec and no accepted judge stay `proxy:structural` β usable for triage, never for gold claims. The set of un-ground-truthable tasks is *reported*, not hidden.+- $0 by default; every spend/exec path is an explicit opt-in with a cap.++## 4. Alternatives rejected++- **Single structural "resolved"**: the proxy-contamination failure mode. Rejected.+- **Fable-judge everything**: cost, and an LLM judge is still a proxy β must not outrank real execution. Rejected as the primary.+- **Blend tiers into a confidence scalar**: destroys provenance; ADR-169 violation. Rejected.diff --git a/v3/docs/adr/ADR-172-fable-advisor-harness.md b/v3/docs/adr/ADR-172-fable-advisor-harness.mdnew file mode 100644index 0000000000..b0938a2956--- /dev/null+++ b/v3/docs/adr/ADR-172-fable-advisor-harness.md@@ -0,0 +1,54 @@+# ADR-172: Fable Advisor Harness via `claude -p` (Cost-Disciplined Judge + Reflector)++**ID**: ADR-172+**Status**: Proposed β implemented on `feat/agenticow-integration` (ships in 3.21.0)+**Date**: 2026-07-04+**Authors**: rUv (drafted with Claude Code)+**Related ADRs**:+- ADR-171 (Provenance-tiered oracle β Tier-2 uses this harness as the judge)+- ADR-150 (MetaHarness β GEPA reflective-mutation is the optimization consumer)+- ADR-143 (Model routing / cost tiers β the cost discipline here is the same concern at a higher tier)++---++## 1. Context++Two SOTA loops want a frontier model *in the loop*, not just at the endpoints:+- **Distillation** (ADR-171 Tier 2): judge whether a cheap-model completion actually solved a task β a smarter labeler than structural confidence.+- **Optimization** (GEPA, ADR-150): GEPA's signature trick is natural-language failure diagnosis from execution traces feeding the *next* mutation β not a scalar fitness. metaharness_evolve mutates without it.++Both are the same primitive: a headless frontier-model advisor. Fable 5 (`claude-fable-5`) via `claude -p` provides it.++**The load-bearing constraint is cost.** Measured: a trivial `claude -p --model claude-fable-5` call from the project directory costs **$1.56** β it loads ruflo's CLAUDE.md context (56k cache-creation tokens). At a 100-trajectory corpus that is ~$150. Naive integration is unusable.++## 2. Decision++A single cost-disciplined `fable-harness.ts` service wrapping `claude -p`, with two entry points and three mandatory cost controls.++### 2.1 Cost controls (all required)+1. **Clean cwd** β spawn `claude -p` from a fresh empty temp directory so no project `CLAUDE.md` / settings load. Measured effect: $1.56 β **$0.34** (cache-creation 56k β 3.7k tokens).+2. **Batching** β N items per call (default 20). The per-call base amortizes to **~$0.02/item**.+3. **`--append-system-prompt` for the role + `--max-budget-usd` cap + `--output-format json`.** Opt-in, off by default.++Combined: $1.56/item naive β ~$0.02/item disciplined β the difference between a demo and a usable loop.++### 2.2 Entry points+- `judgeCompletions(items[]) β [{id, resolved, confidence, reason}]` β ADR-171 Tier 2. (Probe: correctly returned `resolved:true` for an applied patch, `false` for "I am not sure how to do this.")+- `reflectFailures(items[]) β [{failureClass, diagnosis, mutationHint}]` β GEPA reflective-mutation feed for evolve/optimization.++### 2.3 Safety+- No Fable call unless the caller explicitly opts in **and** passes a budget cap.+- ADR-150 graceful: no `claude` binary / budget exhausted / non-JSON reply β structured degraded result, never a throw.+- Tests **mock** `claude -p` (child_process) β CI never spends. One live smoke behind `RUFLO_FABLE_LIVE=1` for humans.++## 3. Consequences++- One harness serves both the distillation judge and the optimization reflector β the frontier-model-in-the-loop SOTA pattern, cost-bounded.+- Fable's judgment is Tier 2, never Tier 1 β an LLM judge is a smarter proxy, not ground truth, and cannot outrank real execution (ADR-171) or clear a promote unless explicitly accepted.+- Cost is measured and enforced, not hoped: the batch-mode default + spend cap are hard gates in the release checklist.++## 4. Alternatives rejected++- **Fable per item from the project dir**: $1.56/item β ~75Γ the disciplined cost. The whole ADR exists to reject this.+- **A cheaper model as judge**: the judge must be at least as capable as the tier it grades; using the cheap tier to grade itself is circular.+- **Skip the reflector, keep scalar-only evolution**: leaves GEPA's proven advantage on the table (SOTA-researcher-flagged gap).diff --git a/v3/docs/adr/ADR-173-remote-gpu-distillation-weight-eft.md b/v3/docs/adr/ADR-173-remote-gpu-distillation-weight-eft.mdnew file mode 100644index 0000000000..1981cf3691--- /dev/null+++ b/v3/docs/adr/ADR-173-remote-gpu-distillation-weight-eft.md@@ -0,0 +1,56 @@+# ADR-173: Remote GPU Distillation via weight-eft over SSH (Dry-Run-Default, Spend-Gated)++**ID**: ADR-173+**Status**: Proposed β implemented on `feat/agenticow-integration` (ships in 3.21.0)+**Date**: 2026-07-04+**Authors**: rUv (drafted with Claude Code)+**Related ADRs**:+- ADR-171 (Provenance-tiered oracle β supplies the gold labels this pipeline trains on)+- ADR-172 (Fable harness β the Tier-2 judge that may label data fed here)+- ADR-143 / ADR-026 (Model routing cost tiers β a distilled cheap-tier adapter is what reduces escalation)+- ADR-166 (MCP bridge RCE remediation β the "no implicit remote execution / secure-by-default" discipline reused here)++---++## 1. Context++`@metaharness/[email protected]` turns an agent's run archive into portable LoRA training data (SFT + DPO JSONL) with contamination / reward-hacking / long-context guards β all $0, offline. Its *value proposition* is closing the cost flywheel: fine-tune a cheap **open-weights** model (GLM/Qwen/DeepSeek) on successful runs so the cascade escalates to frontier models less often.++But the flywheel did not close, for reasons verified end-to-end:+- weight-eft's own `train` emits the `ruvllm microlora` command string and **deliberately never spawns it** (no GPU job, no paid call β by design).+- ruflo's native LoRA (ADR: 3.19.0 flywheel) is a *different* LoRA β 384-dim router-embedding pattern-alignment, not the 7-14B causal-LM attention-projection LoRA weight-eft targets. They do not plug into each other.+- It only makes sense with an open-weights cheap tier (you cannot LoRA Anthropic Haiku) β which ruflo's OpenRouter path provides.++The unlock: a real GPU host β `ruvultra` on tailscale (Linux, SSH open, no HTTP inference port). The tune can run there over SSH.++## 2. Decision++Ship `ruflo neural distill export | plan | eval | train`, where `train --remote <host>` constructs an SSH-based tune on a user-supplied GPU host β **but every spending / executing path is off by default and explicitly gated.**++### 2.1 The $0 spine (always available)+- `export` β captured run records β DarwinTrajectory[] β weight-eft SFT/DPO JSONL + guard report. $0, offline.+- `plan` β print the `ruvllm microlora` GPU training plan. $0 dry-run.+- `eval` β cost-Pareto delta between two cascade outcome sets. $0.++### 2.2 Remote train (opt-in, dry-run default)+`train --remote <host> [--base <model>]`:+1. rsync the JSONL to the host, run `ruvllm microlora sft && dpo` over SSH, fetch the adapter back.+2. **DRY-RUN by default**: print the exact ssh/rsync/ruvllm commands + a preflight probe (ssh reachable? `ruvllm --version` / nvidia-smi on remote, wrapped so failure is reported not fatal). No data leaves the machine, no compute runs.+3. Real execution requires **both** `--execute` **and** `--yes` (or an interactive confirm). Even then the command preview is shown first.+4. Host is **parameterized** (`--remote` / `RUFLO_DISTILL_REMOTE`) β never hard-coded. `ruvultra` / its IP appear in *no* source file; it is the user's infra, passed at runtime.++### 2.3 Honesty rule (hard)+No command, help text, or doc claims ruflo "trains a model" or "reduces escalation" as a $0/local capability. It is: export audited training data + measure the cost-Pareto + print the plan, and β as an explicit, user-triggered, remote-GPU, spend-gated step β run the tune. The residual gaps are stated plainly: (a) resolved-gold is Tier-graded (ADR-171), so SFT quality is only as good as its provenance; (b) a real adapter must clear a hand-verified holdout before it is trusted in routing.++## 3. Consequences++- The flywheel is *buildable and user-triggerable*, not falsely "done." The $0 spine ships as a real capability; the tune is one `--execute --yes` away once the user confirms the box has the GPU toolchain and accepts the spend.+- Attack surface (SSH, remote exec) is added **last** in the merge order and reviewed adversarially: no implicit remote execution, command preview mandatory, no env-secret logging (ADR-166 discipline).+- Distilled adapters target the OpenRouter open-weights cheap tier β the escalation-reduction path is real *if* a tune runs and eval confirms it on held-out data.++## 4. Alternatives rejected++- **Spawn weight-eft's train directly / claim the flywheel is done**: it never spawns; that would be a false capability claim. Rejected.+- **Reuse ruflo's 384-dim native LoRA**: wrong LoRA (router-embedding, not causal-LM). Rejected.+- **Auto-run the tune when a host is reachable**: silent spend + remote execution on user infra. Rejected β dry-run default, double-flag gate.+- **Hard-code ruvultra**: it is user infra; parameterized only. Rejected.diff --git a/v3/pnpm-lock.yaml b/v3/pnpm-lock.yamlindex e40726d0ad..970d276284 100644--- a/v3/pnpm-lock.yaml+++ b/v3/pnpm-lock.yaml@@ -163,6 +163,9 @@ importers:'@metaharness/router':specifier: ~0.3.2version: 0.3.2(@ruvector/[email protected])+ '@metaharness/weight-eft':+ specifier: ~0.1.1+ version: 0.1.1'@ruvector/attention':specifier: ^0.1.32version: 0.1.32@@ -200,8 +203,8 @@ importers:specifier: ^3.0.0-alpha.1version: 3.0.0-alpha.2agenticow:- specifier: ~0.2.3- version: 0.2.3+ specifier: ~0.2.4+ version: 0.2.4metaharness:specifier: ~0.2.8version: 0.2.8(@metaharness/[email protected])@@ -7402,8 +7405,8 @@ packages:- utf-8-validatedev: false- resolution: {integrity: sha512-vJ0hspUqCi6tWt3QR2CNoka9J+0q1ApL9pKfHCqy/KTRmHaEp+6dljRNIWjjJvPL9kX5VV3dPjatjwNMrye2BQ==}+ resolution: {integrity: sha512-x7CqbLhivrHNYCN0mLCi5+xDWI1ycJJuMSGGZchmlu2J4RDLLDkRokzA2VM+OaocbCe6sb1mBgrGgP7rsmoCjQ==}engines: {node: '>=18'}hasBin: truerequiresBuild: true