π 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: memory distillation self-learning loop (ADR-174) + page-agent browser intent (ADR-175) (#2570)
rUvcd8a9c09884d
diff --git a/plugins/ruflo-browser/skills/browser-intent/SKILL.md b/plugins/ruflo-browser/skills/browser-intent/SKILL.mdnew file mode 100644index 0000000000..f3e14c7626--- /dev/null+++ b/plugins/ruflo-browser/skills/browser-intent/SKILL.md@@ -0,0 +1,48 @@+---+name: browser-intent+description: Execute a natural-language browser intent via page-agent (browser_act) when the target is easier to describe than to select β degrades gracefully when page-agent or an OpenAI-compatible LLM provider isn't configured+argument-hint: "<task-description> [--url <url>] [--session <id>]"+allowed-tools: mcp__claude-flow__browser_act mcp__claude-flow__browser_open mcp__claude-flow__browser_snapshot mcp__claude-flow__browser_close mcp__claude-flow__aidefence_has_pii mcp__claude-flow__aidefence_is_safe Bash Read+---++# Browser Intent++Natural-language layer on top of the low-level `browser_*` selector tools. Where `browser-extract` and `browser-form-fill` compose selector-based primitives (`browser_click`, `browser_fill`, `browser_snapshot`), `browser-intent` lets the caller say what they want ("Click the login button", "Fill the search box with cats and submit") and delegates execution to [page-agent](https://github.com/alibaba/page-agent) β in-page injected JS that turns the DOM into text and drives an LLM tool-call loop against it.++## When to use++- The target element is easier to describe in words than to select reliably (dynamic class names, ambiguous structure, A/B-tested markup).+- A one-shot interaction where writing out a selector chain isn't worth it.+- Prefer `browser_click` / `browser_fill` / `browser_snapshot` directly when you already know the exact selector or ref (`@e1`) β `browser_act` adds LLM latency + cost that a direct selector call doesn't.++## Steps++1. **Call `browser_act`** with a `task` string, and optionally `url` (navigates first) and `session` (default `"default"`):+ ```+ mcp__claude-flow__browser_act({+ task: "Click the login button",+ url: "https://example.com/account",+ session: "my-session"+ })+ ```+2. **Read the response contract**:+ - `{ success: true, result, steps, history, contentFlagged, llmSource }` β the intent executed. `result` is the AIDefence-gated final text page-agent produced; `history` is the full step trace (reflection + action + tool result per step); `steps` is `history.length`.+ - `{ success: true, degraded: true, reason, hint }` β page-agent isn't installed, or no OpenAI-compatible LLM provider is configured. **Never treat `degraded: true` as an error to retry** β surface the `hint` and fall back to selector-based `browser_*` tools instead.+ - `{ success: false, error, ... }` β a real failure (browser open failed, injection failed, execution timed out, or page-agent's own `execute()` reported `success:false`).+3. **On `contentFlagged: true`**, the returned `result` has already been redacted by AIDefence (PII or a prompt-injection/threat pattern was detected in the page-agent output) β do not attempt to recover the original text.+4. **Prefer a recorded session** (`browser-record`) when the interaction matters enough to replay later; `browser_act` itself does not open an RVF container β it operates on whatever session id you pass (or `"default"`).++## Provider requirements (why this degrades so often)++`page-agent` calls its LLM directly from the browser page context via a plain OpenAI-compatible `POST {baseURL}/chat/completions`. That means:++- A bare `ANTHROPIC_API_KEY` is **not sufficient** β Anthropic's native API is a different shape (`/v1/messages`).+- Configure one of: `OPENROUTER_API_KEY` (OpenRouter, OpenAI-compatible), `OLLAMA_API_KEY` (Ollama Cloud, OpenAI-compatible), or `CLAUDE_FLOW_PAGE_AGENT_BASE_URL` + `CLAUDE_FLOW_PAGE_AGENT_API_KEY` for a custom OpenAI-compatible endpoint.+- The real provider key **never** enters the page: `browser_act` starts a short-lived loopback HTTP proxy that holds the key server-side and injects the real `Authorization` header itself. The page only ever sees a `127.0.0.1` URL and a placeholder key string.++## Caveats++- `page-agent` is an `optionalDependencies` entry (`npm i page-agent` if the doctor/degraded hint asks for it) β this plugin stays fully operational without it; you simply lose the natural-language layer and fall back to selector-based tools.+- The npm bundle's demo auto-init tail (which would otherwise construct a second `PageAgent` instance against Alibaba's public test endpoint) is stripped before injection β you should never see traffic to a `page-ag-testing-*` host from this tool.+- Every successful `browser_act` call best-effort records the intent + resulting trajectory into the `browser` memory namespace (ADR-174 distillation loop). This is fire-and-forget β a memory-store failure never fails the tool call.+- `timeoutMs` (default 120000) bounds how long `browser_act` polls for `execute()` to settle; a slow multi-step intent may need a higher value.diff --git a/v3/@claude-flow/cli/.claude/helpers/helpers.manifest.json b/v3/@claude-flow/cli/.claude/helpers/helpers.manifest.jsonnew file mode 100644index 0000000000..cd2939623d--- /dev/null+++ b/v3/@claude-flow/cli/.claude/helpers/helpers.manifest.json@@ -0,0 +1,12 @@+{+ "manifest": {+ "version": "3.21.1",+ "files": {+ "auto-memory-hook.mjs": "68be7e9a9eba7bf9c4e8a230db7bf61a243b965639f8504842799d6c6ca28762",+ "hook-handler.cjs": "bc4d2d26823d49b3ab1dded2946b66369f1f67bd76b4c30dca9f3b6df3cca8f0",+ "intelligence.cjs": "760cb82ed2000031abc1ac1fa90a014e7d91d93966e3aa4741b07ab7aff8d066"+ }+ },+ "signature": "kv+8Fp6as/ead/lLRxUZ1sizU1zQZRm1yAcfymzxJjpzwNLBPWgBo3zrHDrBT2zf40EhxpD9da/i1jmGLHGRDw==",+ "algorithm": "ed25519"+}diff --git a/v3/@claude-flow/cli/.claude/helpers/hook-handler.cjs b/v3/@claude-flow/cli/.claude/helpers/hook-handler.cjsindex 73cfee5f4b..b2b91a8c75 100644--- a/v3/@claude-flow/cli/.claude/helpers/hook-handler.cjs+++ b/v3/@claude-flow/cli/.claude/helpers/hook-handler.cjs@@ -124,6 +124,25 @@ async function main() {const prompt = hookInput.prompt || hookInput.command || toolInput.command|| process.env.PROMPT || process.env.TOOL_INPUT_command || args.join(' ') || '';+ // ADR-174: capture FAILURES so the learning substrate has negative examples.+ // Claude Code's PostToolUse payload carries the tool result; a failed+ // Write/Edit/Bash surfaces as tool_response.is_error / an error string /+ // a non-zero exit code. Conservative β only a positive error signal counts+ // as failure (mirrors isToolFailure() in helpers-generator.ts).+ const toolFailed = (function (hi) {+ if (!hi || typeof hi !== 'object') return false;+ const tr = hi.tool_response != null ? hi.tool_response : (hi.toolResponse != null ? hi.toolResponse : hi.result);+ if (tr == null) return false;+ if (typeof tr === 'string') return /\b(error|failed|failure|exception|not found|no such|permission denied|traceback)\b/i.test(tr);+ if (typeof tr === 'object') {+ if (tr.is_error === true || tr.isError === true || tr.success === false || tr.error != null) return true;+ const code = tr.exit_code != null ? tr.exit_code : (tr.exitCode != null ? tr.exitCode : tr.code);+ if (typeof code === 'number' && code !== 0) return true;+ if (Array.isArray(tr.content) && tr.is_error === true) return true;+ }+ return false;+ })(hookInput);+const handlers = {'route': () => {// Inject ranked intelligence context before routing@@ -178,10 +197,10 @@ const handlers = {try {const file = hookInput.file_path || toolInput.file_path|| process.env.TOOL_INPUT_file_path || args[0] || '';- intelligence.recordEdit(file);+ intelligence.recordEdit(file, !toolFailed);} catch (e) { /* non-fatal */ }}- console.log('[OK] Edit recorded');+ console.log(toolFailed ? '[LEARN] Edit FAILURE recorded' : '[OK] Edit recorded');},'session-restore': async () => {@@ -246,13 +265,15 @@ const handlers = {},'post-task': () => {- // Implicit success feedback for intelligence+ // ADR-174: feed the REAL outcome (feedback() boosts confidence on success,+ // decays it on failure) instead of a hardcoded true β no more all-positive+ // signal that the substrate can't learn from.if (intelligence && intelligence.feedback) {try {- intelligence.feedback(true);+ intelligence.feedback(!toolFailed);} catch (e) { /* non-fatal */ }}- console.log('[OK] Task completed');+ console.log(toolFailed ? '[LEARN] Task FAILURE recorded' : '[OK] Task completed');},'stats': () => {diff --git a/v3/@claude-flow/cli/.claude/helpers/intelligence.cjs b/v3/@claude-flow/cli/.claude/helpers/intelligence.cjsindex f77fb58d8b..9fc094dd90 100644--- a/v3/@claude-flow/cli/.claude/helpers/intelligence.cjs+++ b/v3/@claude-flow/cli/.claude/helpers/intelligence.cjs@@ -575,11 +575,14 @@ function getContext(prompt) {* recordEdit(file) β Called from post-edit. Budget: <2ms.* Appends to pending-insights.jsonl.*/-function recordEdit(file) {+function recordEdit(file, success) {ensureDataDir();const entry = JSON.stringify({type: 'edit',file: file || 'unknown',+ // ADR-174: record failures too, not just successes β the learning substrate+ // needs negative examples. Defaults true; an explicit false is a failed edit.+ success: success !== false,timestamp: Date.now(),sessionId: sessionGet('sessionId') || null,});diff --git a/v3/@claude-flow/cli/__tests__/browser-intent-tools.test.ts b/v3/@claude-flow/cli/__tests__/browser-intent-tools.test.tsnew file mode 100644index 0000000000..1da5ade11c--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/browser-intent-tools.test.ts@@ -0,0 +1,279 @@+/**+ * Tests for the `browser_act` MCP tool (ADR-175 page-agent integration).+ *+ * Four surfaces under test, per the integration brief:+ * (a) DEGRADED path β page-agent absent β {degraded:true}, no throw.+ * (b) Tool schema shape β input/handler present.+ * (c) LLM-config resolution β provider config maps to {baseURL,apiKey,model}+ * and NEVER emits a real key into a page-context string.+ * (d) Trajectory recording is attempted on success (mock the bridge).+ *+ * We cannot drive a real browser in CI, so `agent-browser` and `page-agent`+ * are both mocked/injected β these tests assert the wiring/contracts, not+ * live browser automation.+ *+ * NOTE on why page-agent is mocked differently from agenticow/metaharness:+ * `page-agent`'s npm package is ESM-only and touches DOM globals at module+ * scope, so `await import('page-agent')` throws `ReferenceError: window is+ * not defined` in Node EVEN WHEN INSTALLED (verified empirically β see the+ * deviation notes atop browser-intent-tools.ts). The tool therefore never+ * dynamically imports 'page-agent' β it only does `require.resolve('page-agent')`+ * (path resolution, no execution). We simulate absence either by injecting a+ * throwing resolver directly (clean DI, no module-mock gymnastics) or, for the+ * full-handler test, by mocking `node:module`'s `createRequire` β the closest+ * equivalent to the `vi.mock('agenticow', ...)` pattern given page-agent's+ * different (non-dynamic-import) availability check.+ */+import { describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('node:module', async (importOriginal) => {+ const actual = await importOriginal<typeof import('node:module')>();+ return {+ ...actual,+ createRequire: () => ({+ resolve: (id: string) => {+ const err = new Error(`Cannot find module '${id}'`) as NodeJS.ErrnoException;+ err.code = 'MODULE_NOT_FOUND';+ throw err;+ },+ }),+ };+});++vi.mock('../src/memory/memory-initializer.js', () => ({+ storeEntry: vi.fn(async () => ({ success: true, id: 'mock-id' })),+}));++import {+ browserIntentTools,+ locatePageAgentBundle,+ resolvePageAgentLLMConfig,+ buildPageAgentInjection,+ stripDemoAutoInit,+ findDemoLeak,+ DemoLeakError,+ recordBrowserTrajectory,+ PLACEHOLDER_API_KEY,+ BROWSER_ACT_RESULT_GLOBAL,+} from '../src/mcp-tools/browser-intent-tools.js';+import { storeEntry } from '../src/memory/memory-initializer.js';++function findTool(name: string) {+ const t = browserIntentTools.find((x) => x.name === name);+ if (!t) throw new Error(`tool not found: ${name}`);+ return t;+}++// ============================================================================+// (b) Tool schema shape+// ============================================================================++describe('browser_act β tool schema shape', () => {+ it('exposes exactly one tool: browser_act', () => {+ expect(browserIntentTools.map((t) => t.name)).toEqual(['browser_act']);+ });++ it('has a JSON-schema input with required "task" and a handler function', () => {+ const tool = findTool('browser_act');+ expect(tool.inputSchema.type).toBe('object');+ expect(tool.inputSchema.properties).toBeDefined();+ expect(tool.inputSchema.properties?.task).toBeDefined();+ expect(tool.inputSchema.required).toContain('task');+ expect(typeof tool.handler).toBe('function');+ });++ it('rejects a missing task with a structured error, not a throw', async () => {+ const tool = findTool('browser_act');+ const result = await tool.handler({});+ expect(result.isError).toBe(true);+ const parsed = JSON.parse(result.content[0].text as string);+ expect(parsed.success).toBe(false);+ });+});++// ============================================================================+// (a) DEGRADED path β page-agent not installed+// ============================================================================++describe('browser_act β degraded path (page-agent absent)', () => {+ it('locatePageAgentBundle returns null (never throws) when resolution fails with MODULE_NOT_FOUND', () => {+ const throwingResolver = (_id: string): string => {+ const err = new Error("Cannot find module 'page-agent'") as NodeJS.ErrnoException;+ err.code = 'MODULE_NOT_FOUND';+ throw err;+ };+ expect(() => locatePageAgentBundle(throwingResolver)).not.toThrow();+ expect(locatePageAgentBundle(throwingResolver)).toBeNull();+ });++ it('re-throws unexpected (non-not-found) resolver errors rather than silently swallowing them', () => {+ const throwingResolver = (_id: string): string => {+ throw new Error('disk on fire');+ };+ expect(() => locatePageAgentBundle(throwingResolver)).toThrow(/disk on fire/);+ });++ it('browser_act returns {success:true, degraded:true} with a hint, never throws, when page-agent is unresolvable', async () => {+ const tool = findTool('browser_act');+ const result = await tool.handler({ task: 'Click the login button' });+ expect(result.isError).toBeUndefined();+ const parsed = JSON.parse(result.content[0].text as string);+ expect(parsed.success).toBe(true);+ expect(parsed.degraded).toBe(true);+ expect(parsed.reason).toMatch(/page-agent not installed/i);+ expect(parsed.hint).toMatch(/npm i page-agent/);+ });+});++// ============================================================================+// (c) LLM-config resolution β provider config β {baseURL,apiKey,model},+// and key safety (never emitted into a page-context string)+// ============================================================================++describe('resolvePageAgentLLMConfig β provider resolution + key safety', () => {+ it('returns null when no supported provider env var is set', () => {+ expect(resolvePageAgentLLMConfig({})).toBeNull();+ });++ it('prefers an explicit CLAUDE_FLOW_PAGE_AGENT_* override', () => {+ const cfg = resolvePageAgentLLMConfig({+ CLAUDE_FLOW_PAGE_AGENT_BASE_URL: 'https://my-proxy.example/v1',+ CLAUDE_FLOW_PAGE_AGENT_API_KEY: 'sk-explicit-secret',+ CLAUDE_FLOW_PAGE_AGENT_MODEL: 'my-model',+ } as NodeJS.ProcessEnv);+ expect(cfg).toEqual({+ baseURL: 'https://my-proxy.example/v1',+ apiKey: 'sk-explicit-secret',+ model: 'my-model',+ source: 'explicit',+ });+ });++ it('falls back to OpenRouter (OpenAI-compatible) when only OPENROUTER_API_KEY is set', () => {+ const cfg = resolvePageAgentLLMConfig({ OPENROUTER_API_KEY: 'sk-or-secret' } as NodeJS.ProcessEnv);+ expect(cfg?.source).toBe('openrouter');+ expect(cfg?.apiKey).toBe('sk-or-secret');+ expect(cfg?.baseURL).toMatch(/\/v1$/);+ expect(cfg?.model.length).toBeGreaterThan(0);+ });++ it('falls back to Ollama Cloud (OpenAI-compatible) when only OLLAMA_API_KEY is set', () => {+ const cfg = resolvePageAgentLLMConfig({ OLLAMA_API_KEY: 'sk-ollama-secret' } as NodeJS.ProcessEnv);+ expect(cfg?.source).toBe('ollama');+ expect(cfg?.apiKey).toBe('sk-ollama-secret');+ expect(cfg?.baseURL).toMatch(/\/v1$/);+ });++ it('does NOT resolve a usable config from ANTHROPIC_API_KEY alone (native API is not OpenAI-compatible)', () => {+ const cfg = resolvePageAgentLLMConfig({ ANTHROPIC_API_KEY: 'sk-ant-secret' } as NodeJS.ProcessEnv);+ expect(cfg).toBeNull();+ });++ it('buildPageAgentInjection never embeds a real provider key into the page-context script', () => {+ const realSecret = 'sk-super-secret-should-never-leak';+ const script = buildPageAgentInjection(+ 'window.PageAgent = function(){};',+ { baseURL: 'http://127.0.0.1:54321', apiKey: PLACEHOLDER_API_KEY, model: 'anthropic/claude-sonnet-4-6' },+ 'Click the login button',+ );+ expect(script).not.toContain(realSecret);+ expect(script).toContain(PLACEHOLDER_API_KEY);+ expect(script).toContain('Click the login button');+ expect(script).toContain(BROWSER_ACT_RESULT_GLOBAL);+ });++ it('stripDemoAutoInit removes the always-on demo auto-init tail (which would otherwise leak page content to Alibaba\'s test endpoint)', () => {+ const fakeBundle = 'window.PageAgent = function(){};\nvar DEMO_MODEL="qwen3.5-plus", DEMO_API_KEY="NA"; setTimeout(()=>{ new PageAgent({apiKey:DEMO_API_KEY}); });';+ const stripped = stripDemoAutoInit(fakeBundle);+ expect(stripped).toContain('window.PageAgent');+ expect(stripped).not.toContain('DEMO_API_KEY');+ expect(stripped).not.toContain('DEMO_MODEL');+ });++ it('stripDemoAutoInit is a no-op (best-effort) when the marker is absent', () => {+ const noMarker = 'window.PageAgent = function(){};';+ expect(stripDemoAutoInit(noMarker)).toBe(noMarker);+ });++ // ββ Fail-closed demo-endpoint firewall ββββββββββββββββββββββββββββββββββββ+ it('findDemoLeak flags each real demo-endpoint signature', () => {+ expect(findDemoLeak('fetch("https://page-ag-testing-xyz.cn-shanghai.fcapp.run")')).toBeTruthy();+ expect(findDemoLeak('const h = "svc.us-west.fcapp.run"')).toBeTruthy();+ expect(findDemoLeak('var DEMO_MODEL = "qwen3.5-plus"')).toBeTruthy();+ });++ it('findDemoLeak returns null for a clean bundle', () => {+ expect(findDemoLeak('window.PageAgent = function(){}; export {};')).toBeNull();+ });++ it('buildPageAgentInjection REFUSES (throws DemoLeakError) when the strip marker moved but the endpoint survives β fail-closed', () => {+ // Simulate an upstream bundle change: the DEMO_MODEL marker is gone (so the+ // text strip is a no-op) but the auto-connect endpoint is still present.+ const movedMarkerBundle =+ 'window.PageAgent = function(){};\n' ++ 'setTimeout(function(){ fetch("https://page-ag-testing-newhash.cn-shanghai.fcapp.run", {method:"POST"}); });';+ let thrown: unknown;+ try {+ buildPageAgentInjection(+ movedMarkerBundle,+ { baseURL: 'http://127.0.0.1:1', apiKey: PLACEHOLDER_API_KEY, model: 'm' },+ 'do a thing',+ );+ } catch (e) { thrown = e; }+ expect(thrown).toBeInstanceOf(DemoLeakError);+ // And critically: it never produced an injectable string carrying the endpoint.+ expect((thrown as DemoLeakError).message).toMatch(/refusing to inject/i);+ });++ it('buildPageAgentInjection succeeds on a clean (endpoint-free) bundle', () => {+ const clean = 'window.PageAgent = function(){ this.execute = function(){ return Promise.resolve({success:true}); }; };';+ const script = buildPageAgentInjection(+ clean,+ { baseURL: 'http://127.0.0.1:1', apiKey: PLACEHOLDER_API_KEY, model: 'm' },+ 'do a thing',+ );+ expect(script).toContain('window.PageAgent');+ expect(findDemoLeak(script)).toBeNull();+ });+});++// ============================================================================+// (d) Trajectory recording is attempted on success (mock the bridge)+// ============================================================================++describe('recordBrowserTrajectory β ADR-174 distillation, best-effort', () => {+ beforeEach(() => {+ vi.mocked(storeEntry).mockClear();+ });++ it('calls storeEntry with the browser namespace on success', async () => {+ const ok = await recordBrowserTrajectory({+ task: 'Click the login button',+ url: 'https://example.com',+ success: true,+ dataPreview: 'logged in',+ steps: 3,+ source: 'openrouter',+ });+ expect(ok).toBe(true);+ expect(storeEntry).toHaveBeenCalledTimes(1);+ const call = vi.mocked(storeEntry).mock.calls[0][0];+ expect(call.namespace).toBe('browser');+ expect(call.key).toMatch(/^browser-act-/);+ const value = JSON.parse(call.value);+ expect(value.task).toBe('Click the login button');+ expect(value.success).toBe(true);+ });++ it('is best-effort β a storeEntry failure never throws', async () => {+ vi.mocked(storeEntry).mockRejectedValueOnce(new Error('db locked'));+ const ok = await recordBrowserTrajectory({+ task: 'Click the login button',+ success: false,+ dataPreview: '',+ steps: 0,+ source: 'ollama',+ });+ expect(ok).toBe(false);+ });+});diff --git a/v3/@claude-flow/cli/__tests__/distill-tuning.test.ts b/v3/@claude-flow/cli/__tests__/distill-tuning.test.tsnew file mode 100644index 0000000000..81d2eeb792--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/distill-tuning.test.ts@@ -0,0 +1,220 @@+/**+ * ADR-174 Milestone 4 β self-optimization harness ("ruflo tuning ruflo").+ *+ * Proves `tuneDistillation`:+ * - scores every grid point via runDistillation (M1, frozen) on isolated+ * temp copies, never the source DB;+ * - splits train/held-out by rowid with no overlap;+ * - picks a winner by train score and scores it once on the true held-out+ * set;+ * - never mutates the source DB (checksum unchanged);+ * - persists the winning config to a plain JSON-shaped object.+ */+import { describe, it, expect, beforeAll } from 'vitest';+import { mkdtempSync, readFileSync, existsSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import { createHash } from 'node:crypto';++import {+ tuneDistillation,+ computeTimeSplit,+ buildTunedConfigFile,+ writeTunedConfigFile,+ defaultTunedConfigPath,+ DEFAULT_GRID_BATCH_SIZE,+ DEFAULT_GRID_DEDUP_DISTANCE,+ DEFAULT_GRID_PROMOTE_THRESHOLD,+} from '../src/services/distill-tuning.js';++let Database: any;+let haveNative = false;+try {+ Database = (await import('better-sqlite3')).default;+ haveNative = true;+} catch {+ haveNative = false;+}++const TOPICS = [+ { label: 'auth', path: 'src/auth.ts', text: 'refactor the auth module in src/auth.ts to validate tokens' },+ { label: 'api', path: 'src/api/handler.ts', text: 'add validation to src/api/handler.ts for malformed input' },+ { label: 'db', path: 'src/db/store.ts', text: 'optimize the query in src/db/store.ts to cache results' },+ { label: 'memory', path: 'src/memory/bridge.ts', text: 'fix the memory leak in src/memory/bridge.ts on close' },+ { label: 'test', path: 'src/tests/runner.ts', text: 'debug the flaky test in src/tests/runner.ts and stub it' },+];++/** Deterministic per-topic vector cluster with a bit of jitter per row. */+function vec(topicIndex: number, jitterSeed: number): number[] {+ return Array.from({ length: 16 }, (_, i) => Math.sin(topicIndex * 10 + i) + 0.01 * Math.sin(jitterSeed + i));+}++/** Build a fixture DB with the source + agentdb target schemas (M1's shape). */+function seedDb(dbPath: string, rowCount: number): void {+ const db = new Database(dbPath);+ db.exec(`CREATE TABLE memory_entries (+ id TEXT PRIMARY KEY, key TEXT, namespace TEXT DEFAULT 'default',+ content TEXT, embedding TEXT, status TEXT DEFAULT 'active'+ )`);+ db.exec(`CREATE TABLE episodes (+ id INTEGER PRIMARY KEY AUTOINCREMENT, ts INTEGER DEFAULT 0, session_id TEXT NOT NULL,+ task TEXT NOT NULL, input TEXT, output TEXT, critique TEXT, reward REAL DEFAULT 0,+ success BOOLEAN DEFAULT 0, latency_ms INTEGER, tokens_used INTEGER, tags TEXT,+ metadata JSON, created_at INTEGER DEFAULT 0+ )`);+ db.exec(`CREATE TABLE reasoning_patterns (+ id INTEGER PRIMARY KEY AUTOINCREMENT, ts INTEGER DEFAULT 0, task_type TEXT NOT NULL,+ approach TEXT NOT NULL, success_rate REAL NOT NULL DEFAULT 0, uses INTEGER DEFAULT 0,+ avg_reward REAL DEFAULT 0, tags TEXT, metadata TEXT+ )`);+ db.exec(`CREATE TABLE pattern_embeddings (+ pattern_id INTEGER PRIMARY KEY, embedding BLOB NOT NULL+ )`);+ db.exec(`CREATE TABLE causal_edges (+ id INTEGER PRIMARY KEY AUTOINCREMENT, from_memory_id INTEGER NOT NULL, from_memory_type TEXT NOT NULL,+ to_memory_id INTEGER NOT NULL, to_memory_type TEXT NOT NULL, similarity REAL DEFAULT 0,+ confidence REAL DEFAULT 0.5, mechanism TEXT, metadata JSON, created_at INTEGER DEFAULT 0+ )`);++ const ins = db.prepare('INSERT INTO memory_entries (id, key, namespace, content, embedding) VALUES (?,?,?,?,?)');+ const commit = db.transaction(() => {+ for (let i = 0; i < rowCount; i++) {+ const topicIndex = i % TOPICS.length;+ const topic = TOPICS[topicIndex];+ const namespace = i % 3 === 0 ? 'feedback' : 'commands';+ const content =+ namespace === 'feedback'+ ? JSON.stringify({ taskId: `t${i}`, success: i % 2 === 0, note: topic.text })+ : `${topic.text} (row ${i})`;+ ins.run(`row-${i}`, `k${i}`, namespace, content, JSON.stringify(vec(topicIndex, i)));+ }+ });+ commit();+ db.close();+}++function sha256(p: string): string {+ return createHash('sha256').update(readFileSync(p)).digest('hex');+}++describe.skipIf(!haveNative)('tuneDistillation β Milestone 4 self-optimization harness', () => {+ let workdir: string;+ beforeAll(() => {+ workdir = mkdtempSync(join(tmpdir(), 'distill-tune-'));+ });++ it('exposes the ADR-174 default grid (batchSize x dedupDistance x promoteThreshold)', () => {+ expect(DEFAULT_GRID_BATCH_SIZE).toEqual([100, 200, 500]);+ expect(DEFAULT_GRID_DEDUP_DISTANCE).toEqual([0.05, 0.1, 0.15, 0.2, 0.3]);+ expect(DEFAULT_GRID_PROMOTE_THRESHOLD).toEqual(['execution-only', 'execution+corroborated']);+ });++ it(+ 'scores every grid point, picks a winner, and scores held-out exactly once',+ async () => {+ const dbPath = join(workdir, 'main.db');+ seedDb(dbPath, 90);+ const before = sha256(dbPath);++ const report = await tuneDistillation({+ dbPath,+ grid: {+ batchSize: [50, 200],+ dedupDistance: [0.1, 0.2],+ promoteThreshold: ['execution-only', 'execution+corroborated'],+ },+ tmpDir: join(workdir, 'tmp'),+ now: 1750000000000,+ });++ // All grid points scored.+ expect(report.candidates.length).toBe(2 * 2 * 2);+ for (const c of report.candidates) {+ expect(typeof c.trainScore).toBe('number');+ expect(c.trainScore).toBeGreaterThanOrEqual(0);+ }++ // Winner is a real candidate with the best train score among scored ones.+ const scored = report.candidates.filter((c) => !c.skipped);+ const maxScore = Math.max(...scored.map((c) => c.trainScore));+ expect(report.winner.trainScore).toBe(maxScore);+ expect(report.candidates).toContainEqual(report.winner);++ // Held-out scored once, with its own query count and a baseline comparison.+ expect(report.heldOut.queryCount).toBeGreaterThan(0);+ expect(typeof report.heldOut.mrrAt10).toBe('number');+ expect(typeof report.heldOut.baselineMrrAt10).toBe('number');+ expect(typeof report.overfit).toBe('boolean');++ // Provenance is stamped from the caller-supplied `now`, not Date.now().+ expect(report.provenance.tunedAt).toBe(1750000000000);+ expect(report.provenance.gridSize).toBe(8);+ expect(report.provenance.trainSize + report.provenance.heldOutSize).toBe(report.provenance.corpusSize);++ // Source DB byte-for-byte unchanged.+ const after = sha256(dbPath);+ expect(after).toBe(before);+ expect(report.provenance.sourceChecksumSha256).toBe(after);+ },+ 30000,+ );++ it('splits train/held-out by rowid with no overlap', () => {+ const dbPath = join(workdir, 'split.db');+ seedDb(dbPath, 40);+ const db = new Database(dbPath, { readonly: true });+ try {+ const split = computeTimeSplit(db, 0.8);+ expect(split.totalRows).toBe(40);+ expect(split.trainRowids.length + split.heldOutRowids.length).toBe(40);+ const trainSet = new Set(split.trainRowids);+ const overlap = split.heldOutRowids.filter((r) => trainSet.has(r));+ expect(overlap).toEqual([]);+ // Earliest ~80% is train: every train rowid precedes every held-out rowid.+ expect(Math.max(...split.trainRowids)).toBeLessThan(Math.min(...split.heldOutRowids));+ } finally {+ db.close();+ }+ });++ it('flags overfitting only when held-out is meaningfully worse than train', async () => {+ const dbPath = join(workdir, 'overfit.db');+ seedDb(dbPath, 60);+ const report = await tuneDistillation({+ dbPath,+ grid: { batchSize: [50], dedupDistance: [0.1], promoteThreshold: ['execution-only'] },+ tmpDir: join(workdir, 'tmp2'),+ now: 1750000000001,+ });+ // Deterministic check on the documented rule, not a specific outcome+ // (which depends on the synthetic corpus): overfit iff heldOut < 0.8*train.+ const expected = report.winner.trainScore > 0 && report.heldOut.mrrAt10 < report.winner.trainScore * 0.8;+ expect(report.overfit).toBe(expected);+ });++ it('builds a persistable config artifact carrying provenance', async () => {+ const dbPath = join(workdir, 'persist.db');+ seedDb(dbPath, 50);+ const report = await tuneDistillation({+ dbPath,+ grid: { batchSize: [100], dedupDistance: [0.15], promoteThreshold: ['execution-only'] },+ tmpDir: join(workdir, 'tmp3'),+ now: 1750000000002,+ });++ const artifact = buildTunedConfigFile(report);+ expect(artifact.batchSize).toBe(100);+ expect(artifact.dedupDistance).toBe(0.15);+ expect(artifact.promoteThreshold).toBe('execution-only');+ expect(artifact.provenance.tunedAt).toBe(1750000000002);+ expect(artifact.provenance.winnerTrainScore).toBe(report.winner.trainScore);++ const outPath = join(workdir, 'out', 'distill-tuned.json');+ writeTunedConfigFile(report, outPath);+ expect(existsSync(outPath)).toBe(true);+ const written = JSON.parse(readFileSync(outPath, 'utf8'));+ expect(written).toEqual(artifact);++ expect(defaultTunedConfigPath('/tmp/some-project')).toBe(join('/tmp/some-project', '.claude-flow', 'distill-tuned.json'));+ });+});diff --git a/v3/@claude-flow/cli/__tests__/helper-refresh.test.ts b/v3/@claude-flow/cli/__tests__/helper-refresh.test.tsnew file mode 100644index 0000000000..f8004f8a1d--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/helper-refresh.test.ts@@ -0,0 +1,77 @@+/**+ * Version-stamped critical-helper auto-refresh.+ *+ * The propagation gap: Claude Code hooks run the project-local+ * `.claude/helpers/*.cjs`, not the npm package, so hook fixes don't reach+ * existing users without a manual re-init. This test proves the stamp-and-+ * refresh path closes it: a stale-stamped project silently re-copies the+ * current helpers on the next CLI startup; a current one is a no-op; and a+ * non-ruflo directory is never touched.+ */+import { describe, it, expect, beforeEach } from 'vitest';+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';++import { autoRefreshHelpersIfStale, getInstalledCliVersion, HELPERS_STAMP_FILE } from '../src/init/helper-refresh.js';++function makeProject(): { cwd: string; helpersDir: string } {+ const cwd = mkdtempSync(join(tmpdir(), 'helper-refresh-'));+ const helpersDir = join(cwd, '.claude', 'helpers');+ mkdirSync(helpersDir, { recursive: true });+ return { cwd, helpersDir };+}++describe('autoRefreshHelpersIfStale', () => {+ let version: string;+ beforeEach(() => { version = getInstalledCliVersion(); });++ it('refreshes a project whose helpers are stamped with an older version', async () => {+ const { cwd, helpersDir } = makeProject();+ // Old, hardcoded-success hook-handler + a stale stamp.+ writeFileSync(join(helpersDir, 'hook-handler.cjs'), 'intelligence.feedback(true); // OLD, no failure capture\n');+ writeFileSync(join(helpersDir, HELPERS_STAMP_FILE), '0.0.1-old');++ const r = await autoRefreshHelpersIfStale(cwd);+ expect(r.refreshed).toBe(true);+ expect(r.from).toBe('0.0.1-old');+ expect(r.to).toBe(version);++ // The stamp now matches the installed version.+ expect(readFileSync(join(helpersDir, HELPERS_STAMP_FILE), 'utf-8').trim()).toBe(version);+ // And the copied hook-handler carries the NEW failure-capture logic.+ const refreshed = readFileSync(join(helpersDir, 'hook-handler.cjs'), 'utf-8');+ expect(refreshed).toMatch(/toolFailed/);+ expect(refreshed).not.toContain('// OLD, no failure capture');+ });++ it('is a no-op when the stamp already matches the installed version', async () => {+ const { cwd, helpersDir } = makeProject();+ const marker = 'CURRENT-HANDLER-DO-NOT-OVERWRITE';+ writeFileSync(join(helpersDir, 'hook-handler.cjs'), marker);+ writeFileSync(join(helpersDir, HELPERS_STAMP_FILE), version);++ const r = await autoRefreshHelpersIfStale(cwd);+ expect(r.refreshed).toBe(false);+ // Untouched β the fast path never copied over our marker file.+ expect(readFileSync(join(helpersDir, 'hook-handler.cjs'), 'utf-8')).toBe(marker);+ });++ it('refreshes an UNSTAMPED (pre-feature) project on first run', async () => {+ const { cwd, helpersDir } = makeProject();+ writeFileSync(join(helpersDir, 'hook-handler.cjs'), 'intelligence.feedback(true);\n');+ // no stamp file at all++ const r = await autoRefreshHelpersIfStale(cwd);+ expect(r.refreshed).toBe(true);+ expect(r.from).toBe('(unstamped)');+ expect(existsSync(join(helpersDir, HELPERS_STAMP_FILE))).toBe(true);+ });++ it('is a safe no-op outside a ruflo project (never creates files)', async () => {+ const cwd = mkdtempSync(join(tmpdir(), 'not-ruflo-'));+ const r = await autoRefreshHelpersIfStale(cwd);+ expect(r.refreshed).toBe(false);+ expect(existsSync(join(cwd, '.claude'))).toBe(false); // did not scaffold anything+ });+});diff --git a/v3/@claude-flow/cli/__tests__/helper-signing.test.ts b/v3/@claude-flow/cli/__tests__/helper-signing.test.tsnew file mode 100644index 0000000000..6e05ef9cd3--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/helper-signing.test.ts@@ -0,0 +1,82 @@+/**+ * Ed25519 provenance gate for the helper auto-refresh (ADR-174 security).+ *+ * The auto-refresh copies auto-executing hook code from the installed package.+ * These tests prove the fail-closed gate: a validly-signed manifest verifies,+ * ANY tampering (hash, signature, algorithm) is rejected, and the ACTUAL+ * shipped manifest is both signed by ruflo's key and matches the shipped+ * helper files byte-for-byte.+ */+import { describe, it, expect } from 'vitest';+import { generateKeyPairSync, sign as edSign } from 'node:crypto';+import { readFileSync, existsSync } from 'node:fs';+import { join, dirname } from 'node:path';+import { fileURLToPath } from 'node:url';++import {+ verifyHelpersManifest, canonicalManifestBytes, sha256Hex,+ RUFLO_HELPERS_PUBKEY, HELPERS_MANIFEST_FILE,+ type HelpersManifest,+} from '../src/init/helper-signing.js';++const PKG_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');+const HELPERS_DIR = join(PKG_ROOT, '.claude', 'helpers');++function makeSigned(manifest: HelpersManifest, privPem: string, algorithm = 'ed25519') {+ const sig = edSign(null, canonicalManifestBytes(manifest), privPem).toString('base64');+ return JSON.stringify({ manifest, signature: sig, algorithm });+}++describe('verifyHelpersManifest β fail-closed Ed25519 gate', () => {+ const { publicKey, privateKey } = generateKeyPairSync('ed25519', {+ publicKeyEncoding: { type: 'spki', format: 'pem' },+ privateKeyEncoding: { type: 'pkcs8', format: 'pem' },+ });+ const manifest: HelpersManifest = { version: '9.9.9', files: { 'hook-handler.cjs': 'a'.repeat(64), 'intelligence.cjs': 'b'.repeat(64) } };++ it('accepts a validly-signed manifest and returns the trusted map', () => {+ const out = verifyHelpersManifest(makeSigned(manifest, privateKey), publicKey);+ expect(out).not.toBeNull();+ expect(out!.files['hook-handler.cjs']).toBe('a'.repeat(64));+ });++ it('REJECTS a manifest whose hash was tampered after signing', () => {+ const signed = JSON.parse(makeSigned(manifest, privateKey));+ signed.manifest.files['hook-handler.cjs'] = 'c'.repeat(64); // flip a hash, keep old signature+ expect(verifyHelpersManifest(JSON.stringify(signed), publicKey)).toBeNull();+ });++ it('REJECTS a manifest signed by a DIFFERENT key (wrong provenance)', () => {+ const other = generateKeyPairSync('ed25519', { privateKeyEncoding: { type: 'pkcs8', format: 'pem' }, publicKeyEncoding: { type: 'spki', format: 'pem' } });+ expect(verifyHelpersManifest(makeSigned(manifest, other.privateKey), publicKey)).toBeNull();+ });++ it('REJECTS a non-ed25519 algorithm and malformed input', () => {+ expect(verifyHelpersManifest(makeSigned(manifest, privateKey, 'rsa'), publicKey)).toBeNull();+ expect(verifyHelpersManifest('not json', publicKey)).toBeNull();+ expect(verifyHelpersManifest('{}', publicKey)).toBeNull();+ expect(verifyHelpersManifest(JSON.stringify({ manifest, algorithm: 'ed25519' }), publicKey)).toBeNull(); // no signature+ });+});++describe('shipped helpers manifest β real signature + real content', () => {+ const manifestPath = join(HELPERS_DIR, HELPERS_MANIFEST_FILE);++ it('exists and verifies against the baked ruflo public key', () => {+ expect(existsSync(manifestPath)).toBe(true);+ const trusted = verifyHelpersManifest(readFileSync(manifestPath, 'utf-8'), RUFLO_HELPERS_PUBKEY);+ expect(trusted).not.toBeNull();+ });++ it('its hashes match the actual shipped helper files (a byte flip would break the gate)', () => {+ const trusted = verifyHelpersManifest(readFileSync(manifestPath, 'utf-8'), RUFLO_HELPERS_PUBKEY)!;+ for (const [name, expected] of Object.entries(trusted.files)) {+ const p = join(HELPERS_DIR, name);+ expect(existsSync(p), `${name} shipped`).toBe(true);+ expect(sha256Hex(readFileSync(p)), `${name} integrity`).toBe(expected);+ }+ // A tampered helper would NOT match β the refresh gate refuses.+ const anyName = Object.keys(trusted.files)[0];+ expect(sha256Hex(readFileSync(join(HELPERS_DIR, anyName)) + '// tampered')).not.toBe(trusted.files[anyName]);+ });+});diff --git a/v3/@claude-flow/cli/__tests__/memory-distill-cli.test.ts b/v3/@claude-flow/cli/__tests__/memory-distill-cli.test.tsnew file mode 100644index 0000000000..c1c4dff039--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/memory-distill-cli.test.ts@@ -0,0 +1,203 @@+/**+ * ADR-174 Milestone 2 β `memory distill` CLI surface.+ *+ * Exercises the CLI command family (run|status|config) built on top of the+ * frozen M1 service (`../src/services/memory-distillation.ts`). The service+ * itself is proven by `memory-distillation.test.ts`; this file proves the CLI+ * wiring: flag β DistillOptions mapping, the ADR-172 fail-fast budget gate,+ * the aggressive/conservative presets, and the read-only `status` report.+ */+import { describe, it, expect, beforeAll } from 'vitest';+import { mkdtempSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';++import type { Command, CommandContext } from '../src/types.js';+import { distillCommand, resolveDistillConfig } from '../src/commands/memory-distill.js';++let Database: any;+let haveNative = false;+try { Database = (await import('better-sqlite3')).default; haveNative = true; } catch { haveNative = false; }++/** Same fixture shape as __tests__/memory-distillation.test.ts. */+function seedDb(dbPath: string): void {+ const db = new Database(dbPath);+ db.exec(`CREATE TABLE memory_entries (+ id TEXT PRIMARY KEY, key TEXT, namespace TEXT DEFAULT 'default',+ content TEXT, embedding TEXT, status TEXT DEFAULT 'active'+ )`);+ db.exec(`CREATE TABLE episodes (+ id INTEGER PRIMARY KEY AUTOINCREMENT, ts INTEGER DEFAULT 0, session_id TEXT NOT NULL,+ task TEXT NOT NULL, input TEXT, output TEXT, critique TEXT, reward REAL DEFAULT 0,+ success BOOLEAN DEFAULT 0, latency_ms INTEGER, tokens_used INTEGER, tags TEXT,+ metadata JSON, created_at INTEGER DEFAULT 0+ )`);+ db.exec(`CREATE TABLE reasoning_patterns (+ id INTEGER PRIMARY KEY AUTOINCREMENT, ts INTEGER DEFAULT 0, task_type TEXT NOT NULL,+ approach TEXT NOT NULL, success_rate REAL NOT NULL DEFAULT 0, uses INTEGER DEFAULT 0,+ avg_reward REAL DEFAULT 0, tags TEXT, metadata TEXT+ )`);+ db.exec(`CREATE TABLE pattern_embeddings (+ pattern_id INTEGER PRIMARY KEY, embedding BLOB NOT NULL+ )`);+ db.exec(`CREATE TABLE causal_edges (+ id INTEGER PRIMARY KEY AUTOINCREMENT, from_memory_id INTEGER NOT NULL, from_memory_type TEXT NOT NULL,+ to_memory_id INTEGER NOT NULL, to_memory_type TEXT NOT NULL, similarity REAL DEFAULT 0,+ confidence REAL DEFAULT 0.5, mechanism TEXT, metadata JSON, created_at INTEGER DEFAULT 0+ )`);++ const ins = db.prepare('INSERT INTO memory_entries (id, key, namespace, content, embedding) VALUES (?,?,?,?,?)');+ const vec = (seed: number) => JSON.stringify(Array.from({ length: 8 }, (_, i) => Math.sin(seed + i)));+ ins.run('c1', 'k1', 'commands', 'refactor the auth module in src/auth.ts', vec(1));+ ins.run('c2', 'k2', 'commands', 'add validation to src/api/handler.ts', vec(2));+ ins.run('c3', 'k3', 'commands', 'optimize the query in src/db/store.ts', vec(3));+ ins.run('f1', 'k4', 'feedback', JSON.stringify({ taskId: 'edit-a', success: true }), vec(4));+ ins.run('f2', 'k5', 'feedback', JSON.stringify({ taskId: 'edit-b', success: false }), vec(5));+ db.close();+}++function countReasoningPatterns(dbPath: string): number {+ const db = new Database(dbPath, { readonly: true });+ const c = (db.prepare('SELECT COUNT(*) AS c FROM reasoning_patterns').get() as { c: number }).c;+ db.close();+ return c;+}++function makeCtx(flags: Record<string, unknown>, cwd: string): CommandContext {+ return { args: [], flags: { _: [], ...flags }, cwd, interactive: false } as CommandContext;+}++function sub(name: string): Command {+ const cmd = distillCommand.subcommands?.find((c) => c.name === name);+ if (!cmd?.action) throw new Error(`memory distill ${name} has no action`);+ return cmd;+}++describe.skipIf(!haveNative)('memory distill CLI (ADR-174 Milestone 2)', () => {+ let workdir: string;+ beforeAll(() => { workdir = mkdtempSync(join(tmpdir(), 'distill-cli-')); });++ it('registers run, status, and config as subcommands of `memory distill`', () => {+ const names = (distillCommand.subcommands ?? []).map((c) => c.name);+ expect(names).toEqual(expect.arrayContaining(['run', 'status', 'config']));+ });++ it('--dry-run makes no writes', async () => {+ const dbPath = join(workdir, 'dry.db');+ seedDb(dbPath);++ const result = await sub('run').action!(makeCtx({ dryRun: true, db: dbPath }, workdir));++ expect(result?.success).toBe(true);+ const data = result?.data as any;+ expect(data.report.patterns).toBeGreaterThan(0);+ expect(data.report.dryRun).toBe(true);+ expect(countReasoningPatterns(dbPath)).toBe(0); // no writes actually landed+ });++ it('--namespace scopes the run to the requested namespace(s)', async () => {+ const dbPath = join(workdir, 'ns.db');+ seedDb(dbPath);++ const result = await sub('run').action!(makeCtx({ namespace: 'feedback', db: dbPath }, workdir));++ expect(result?.success).toBe(true);+ const data = result?.data as any;+ expect(data.config.namespaces).toEqual(['feedback']);+ expect(data.report.processed).toBe(2); // only the 2 feedback rows+ expect(data.report.byProvenance['proxy:structural']).toBeUndefined();+ });++ it('--judge fable without --budget-usd fails fast (ADR-172 gate)', async () => {+ const dbPath = join(workdir, 'fable.db');+ seedDb(dbPath);++ const result = await sub('run').action!(makeCtx({ judge: 'fable', db: dbPath }, workdir));++ expect(result?.success).toBe(false);+ expect(result?.exitCode).toBe(1);+ expect(countReasoningPatterns(dbPath)).toBe(0); // refused before calling the service+ });++ it('--judge fable with --budget-usd > 0 passes the gate (service still reserves the tier)', async () => {+ const dbPath = join(workdir, 'fable-funded.db');+ seedDb(dbPath);++ const result = await sub('run').action!(makeCtx({ judge: 'fable', budgetUsd: 2, db: dbPath }, workdir));++ expect(result?.success).toBe(true);+ const data = result?.data as any;+ // The M1 service reserves judge:fable (ADR-172, not enabled here) β CLI must+ // surface that as a skip, not silently fall back to structural.+ expect(data.report.skipped).toContain('judge:fable');+ });++ it('--aggressive preset maps to dedup-distance 0.3 / batch-size 500', () => {+ const resolved = resolveDistillConfig(makeCtx({ aggressive: true }, workdir));+ expect(resolved.ok).toBe(true);+ if (resolved.ok) {+ expect(resolved.config.dedupDistance).toBe(0.3);+ expect(resolved.config.batchSize).toBe(500);+ }+ });++ it('--conservative preset maps to dedup-distance 0.1 / batch-size 100', () => {+ const resolved = resolveDistillConfig(makeCtx({ conservative: true }, workdir));+ expect(resolved.ok).toBe(true);+ if (resolved.ok) {+ expect(resolved.config.dedupDistance).toBe(0.1);+ expect(resolved.config.batchSize).toBe(100);+ }+ });++ it('rejects --aggressive and --conservative together', () => {+ const resolved = resolveDistillConfig(makeCtx({ aggressive: true, conservative: true }, workdir));+ expect(resolved.ok).toBe(false);+ });++ it('explicit --batch-size overrides the --aggressive preset', () => {+ const resolved = resolveDistillConfig(makeCtx({ aggressive: true, batchSize: 42 }, workdir));+ expect(resolved.ok).toBe(true);+ if (resolved.ok) {+ expect(resolved.config.batchSize).toBe(42);+ expect(resolved.config.dedupDistance).toBe(0.3); // untouched preset value+ }+ });++ it('`config` prints the effective merged config as JSON-serializable data', async () => {+ const result = await sub('config').action!(makeCtx({ aggressive: true, db: '/tmp/nonexistent.db' }, workdir));+ expect(result?.success).toBe(true);+ const data = result?.data as any;+ expect(data.dedupDistance).toBe(0.3);+ expect(data.batchSize).toBe(500);+ expect(data.dbPath).toBe('/tmp/nonexistent.db');+ });++ it('`status` reports table counts, cursor, and the promote-gate breakdown after a run', async () => {+ const dbPath = join(workdir, 'status.db');+ seedDb(dbPath);++ const runResult = await sub('run').action!(makeCtx({ db: dbPath }, workdir));+ expect(runResult?.success).toBe(true);++ const statusResult = await sub('status').action!(makeCtx({ db: dbPath }, workdir));+ expect(statusResult?.success).toBe(true);+ const data = statusResult?.data as any;++ expect(data.available).toBe(true);+ expect(data.counts.reasoning_patterns).toBeGreaterThan(0);+ expect(data.counts.episodes).toBeGreaterThan(0);+ expect(data.counts.pattern_embeddings).toBeGreaterThan(0);+ expect(data.promoted).toBeGreaterThan(0); // feedback rows promote (ADR-171)+ expect(data.proxy).toBeGreaterThan(0); // commands rows never promote+ expect(data.cursors.length).toBeGreaterThan(0);+ });++ it('`status` degrades gracefully when no DB exists at the path', async () => {+ const result = await sub('status').action!(makeCtx({ db: join(workdir, 'does-not-exist.db') }, workdir));+ expect(result?.success).toBe(true);+ const data = result?.data as any;+ expect(data.available).toBe(false);+ expect(data.reason).toBe('no-db');+ });+});diff --git a/v3/@claude-flow/cli/__tests__/memory-distillation.test.ts b/v3/@claude-flow/cli/__tests__/memory-distillation.test.tsnew file mode 100644index 0000000000..85e89789b8--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/memory-distillation.test.ts@@ -0,0 +1,193 @@+/**+ * ADR-174 memory distillation service.+ *+ * Proves the DISTILL/CONSOLIDATE pipeline turns raw `memory_entries` into the+ * structured intelligence tables (episodes / reasoning_patterns /+ * pattern_embeddings / causal_edges) that were empty because the daemon's+ * consolidate worker was a stub β while never mutating the source rows, staying+ * idempotent, and enforcing ADR-171 provenance discipline (proxy never promotes).+ */+import { describe, it, expect, beforeAll } from 'vitest';+import { mkdtempSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';++import { runDistillation } from '../src/services/memory-distillation.js';++let Database: any;+let haveNative = false;+try { Database = (await import('better-sqlite3')).default; haveNative = true; } catch { haveNative = false; }++/** Build a DB with the source + agentdb target schemas and some seeded memory. */+function seedDb(dbPath: string): void {+ const db = new Database(dbPath);+ db.exec(`CREATE TABLE memory_entries (+ id TEXT PRIMARY KEY, key TEXT, namespace TEXT DEFAULT 'default',+ content TEXT, embedding TEXT, status TEXT DEFAULT 'active'+ )`);+ db.exec(`CREATE TABLE episodes (+ id INTEGER PRIMARY KEY AUTOINCREMENT, ts INTEGER DEFAULT 0, session_id TEXT NOT NULL,+ task TEXT NOT NULL, input TEXT, output TEXT, critique TEXT, reward REAL DEFAULT 0,+ success BOOLEAN DEFAULT 0, latency_ms INTEGER, tokens_used INTEGER, tags TEXT,+ metadata JSON, created_at INTEGER DEFAULT 0+ )`);+ db.exec(`CREATE TABLE reasoning_patterns (+ id INTEGER PRIMARY KEY AUTOINCREMENT, ts INTEGER DEFAULT 0, task_type TEXT NOT NULL,+ approach TEXT NOT NULL, success_rate REAL NOT NULL DEFAULT 0, uses INTEGER DEFAULT 0,+ avg_reward REAL DEFAULT 0, tags TEXT, metadata TEXT+ )`);+ db.exec(`CREATE TABLE pattern_embeddings (+ pattern_id INTEGER PRIMARY KEY, embedding BLOB NOT NULL+ )`);+ db.exec(`CREATE TABLE causal_edges (+ id INTEGER PRIMARY KEY AUTOINCREMENT, from_memory_id INTEGER NOT NULL, from_memory_type TEXT NOT NULL,+ to_memory_id INTEGER NOT NULL, to_memory_type TEXT NOT NULL, similarity REAL DEFAULT 0,+ confidence REAL DEFAULT 0.5, mechanism TEXT, metadata JSON, created_at INTEGER DEFAULT 0+ )`);++ const ins = db.prepare('INSERT INTO memory_entries (id, key, namespace, content, embedding) VALUES (?,?,?,?,?)');+ // Distinct vectors so clustering keeps them separate.+ const vec = (seed: number) => JSON.stringify(Array.from({ length: 8 }, (_, i) => Math.sin(seed + i)));+ // 3 'commands' (proxy tier), 2 'feedback' (execution tier, one success one fail).+ ins.run('c1', 'k1', 'commands', 'refactor the auth module in src/auth.ts', vec(1));+ ins.run('c2', 'k2', 'commands', 'add validation to src/api/handler.ts', vec(2));+ ins.run('c3', 'k3', 'commands', 'optimize the query in src/db/store.ts', vec(3));+ ins.run('f1', 'k4', 'feedback', JSON.stringify({ taskId: 'edit-a', success: true }), vec(4));+ ins.run('f2', 'k5', 'feedback', JSON.stringify({ taskId: 'edit-b', success: false }), vec(5));+ db.close();+}++function counts(dbPath: string): Record<string, number> {+ const db = new Database(dbPath, { readonly: true });+ const q = (t: string) => (db.prepare(`SELECT COUNT(*) AS c FROM ${t}`).get() as { c: number }).c;+ const r = {+ memory_entries: q('memory_entries'), episodes: q('episodes'),+ reasoning_patterns: q('reasoning_patterns'), pattern_embeddings: q('pattern_embeddings'),+ causal_edges: q('causal_edges'),+ };+ db.close();+ return r;+}++describe.skipIf(!haveNative)('runDistillation β memory β structured intelligence', () => {+ let workdir: string;+ beforeAll(() => { workdir = mkdtempSync(join(tmpdir(), 'distill-')); });++ it('populates the empty target tables without mutating memory_entries', async () => {+ const dbPath = join(workdir, 'main.db');+ seedDb(dbPath);+ const before = counts(dbPath);+ expect(before.reasoning_patterns).toBe(0);++ const r = await runDistillation({ dbPath });+ expect(r.skipped).toBeUndefined();+ expect(r.processed).toBe(5);+ expect(r.patterns).toBeGreaterThan(0);+ expect(r.episodes).toBeGreaterThan(0);++ const after = counts(dbPath);+ expect(after.memory_entries).toBe(before.memory_entries); // source untouched+ expect(after.reasoning_patterns).toBeGreaterThan(0);+ expect(after.episodes).toBeGreaterThan(0);+ // Every pattern with a source embedding gets a pattern_embedding.+ expect(after.pattern_embeddings).toBe(after.reasoning_patterns);+ });++ it('enforces ADR-171 provenance: feedback promotes, proxy never does', async () => {+ const dbPath = join(workdir, 'prov.db');+ seedDb(dbPath);+ const r = await runDistillation({ dbPath });+ expect(r.byProvenance['proxy:structural']).toBeGreaterThan(0);+ expect(r.byProvenance['oracle:test-exec']).toBeGreaterThan(0);++ const db = new Database(dbPath, { readonly: true });+ const proxyPromoted = (db.prepare(+ "SELECT COUNT(*) AS c FROM reasoning_patterns WHERE json_extract(metadata,'$.provenance')='proxy:structural' AND json_extract(metadata,'$.promoted')=1",+ ).get() as { c: number }).c;+ expect(proxyPromoted).toBe(0); // proxy tier NEVER clears the promote gate+ db.close();+ });++ it('dry-run reports counts but writes nothing', async () => {+ const dbPath = join(workdir, 'dry.db');+ seedDb(dbPath);+ const r = await runDistillation({ dbPath, dryRun: true });+ expect(r.patterns).toBeGreaterThan(0);+ expect(counts(dbPath).reasoning_patterns).toBe(0); // no writes+ });++ it('is incremental/idempotent β a second run processes nothing new', async () => {+ const dbPath = join(workdir, 'idem.db');+ seedDb(dbPath);+ await runDistillation({ dbPath });+ const mid = counts(dbPath);+ const second = await runDistillation({ dbPath });+ expect(second.processed).toBe(0);+ expect(counts(dbPath).reasoning_patterns).toBe(mid.reasoning_patterns); // no duplicates+ });++ it('scopes to a namespace when asked', async () => {+ const dbPath = join(workdir, 'ns.db');+ seedDb(dbPath);+ const r = await runDistillation({ dbPath, namespaces: ['feedback'] });+ expect(r.processed).toBe(2); // only the 2 feedback rows+ expect(r.byProvenance['proxy:structural']).toBeUndefined();+ });++ it('skips (does not throw) when target tables are absent', async () => {+ const dbPath = join(workdir, 'bare.db');+ const db = new Database(dbPath);+ db.exec("CREATE TABLE memory_entries (id TEXT PRIMARY KEY, namespace TEXT, content TEXT, embedding TEXT)");+ db.close();+ const r = await runDistillation({ dbPath });+ expect(r.skipped).toBeTruthy();+ expect(r.patterns).toBe(0);+ });++ // ββ ADR-174 operational invariant: embedding coverage is EXACTLY 1:1 ββ+ it('every pattern has exactly one embedding, even when a source vector is malformed', async () => {+ const dbPath = join(workdir, 'embcov.db');+ seedDb(dbPath);+ // Add a row whose embedding column is non-null but unparseable β the old+ // code would create a pattern with no embedding (coverage gap).+ const db = new Database(dbPath);+ db.prepare('INSERT INTO memory_entries (id, key, namespace, content, embedding) VALUES (?,?,?,?,?)')+ .run('bad1', 'kb', 'commands', 'refactor thing in src/x.ts', 'NOT VALID JSON');+ db.close();++ const r = await runDistillation({ dbPath });+ expect(r.patterns).toBeGreaterThan(0);+ expect(r.patternEmbeddings).toBe(r.patterns); // report-level 1:1++ // SQL invariant: zero patterns without an embedding.+ const check = new Database(dbPath, { readonly: true });+ const gap = (check.prepare(+ 'SELECT COUNT(*) AS c FROM reasoning_patterns rp LEFT JOIN pattern_embeddings pe ON pe.pattern_id = rp.id WHERE pe.pattern_id IS NULL',+ ).get() as { c: number }).c;+ expect(gap).toBe(0);+ check.close();+ });++ // ββ ADR-174 edge contract: edges are WEAK co-occurrence, never causal proof ββ+ it('relational edges are typed cooccurrence / proxy-tier / non-promoted', async () => {+ const dbPath = join(workdir, 'edges.db');+ seedDb(dbPath);+ await runDistillation({ dbPath });++ const db = new Database(dbPath, { readonly: true });+ const edges = db.prepare('SELECT mechanism, confidence, metadata FROM causal_edges').all() as Array<{ mechanism: string; confidence: number; metadata: string }>;+ expect(edges.length).toBeGreaterThan(0);+ for (const e of edges) {+ expect(e.mechanism).toBe('co-occurrence');+ expect(e.confidence).toBeLessThan(0.5); // weak, never asserted as proof+ const m = JSON.parse(e.metadata);+ expect(m.edge_type).toBe('cooccurrence');+ expect(m.provenance_tier).toBe('proxy:structural');+ expect(m.promoted).toBe(false); // may rank retrieval, must NOT justify autonomous action+ }+ // No proxy edge is ever promoted.+ const promotedProxyEdges = edges.filter(e => JSON.parse(e.metadata).promoted === true).length;+ expect(promotedProxyEdges).toBe(0);+ db.close();+ });+});diff --git a/v3/@claude-flow/cli/__tests__/services/worker-daemon-consolidate.test.ts b/v3/@claude-flow/cli/__tests__/services/worker-daemon-consolidate.test.tsnew file mode 100644index 0000000000..4086260793--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/services/worker-daemon-consolidate.test.ts@@ -0,0 +1,190 @@+/**+ * ADR-174 Milestone 3 β daemon wiring for the consolidate worker.+ *+ * The daemon previously wrote a hardcoded { patternsConsolidated: 0 } stub+ * every 30 minutes and touched no database β the root cause of the+ * intelligence tables (reasoning_patterns, episodes, causal_edges) staying+ * empty. `runConsolidateWorker()` now calls the frozen M1 service+ * (memory-distillation.ts's runDistillation) against `.swarm/memory.db` and+ * persists the REAL report to .claude-flow/metrics/consolidation.json.+ *+ * These tests prove:+ * - the worker actually increases reasoning_patterns row count+ * - it writes non-zero, real metrics (not the old hardcoded zeros)+ * - running it twice is idempotent (distill_state cursor drains once)+ * - the RUFLO_DAEMON_NO_DISTILL opt-out skips distillation without crashing+ * - a corrupt/unusable DB is reported via metrics, never thrown+ */+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, mkdirSync, existsSync, readFileSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';++import { WorkerDaemon } from '../../src/services/worker-daemon.js';++let Database: any;+let haveNative = false;+try {+ Database = (await import('better-sqlite3')).default;+ haveNative = true;+} catch {+ haveNative = false;+}++/** Same schema/fixtures as __tests__/memory-distillation.test.ts. */+function seedDb(dbPath: string): void {+ const db = new Database(dbPath);+ db.exec(`CREATE TABLE memory_entries (+ id TEXT PRIMARY KEY, key TEXT, namespace TEXT DEFAULT 'default',+ content TEXT, embedding TEXT, status TEXT DEFAULT 'active'+ )`);+ db.exec(`CREATE TABLE episodes (+ id INTEGER PRIMARY KEY AUTOINCREMENT, ts INTEGER DEFAULT 0, session_id TEXT NOT NULL,+ task TEXT NOT NULL, input TEXT, output TEXT, critique TEXT, reward REAL DEFAULT 0,+ success BOOLEAN DEFAULT 0, latency_ms INTEGER, tokens_used INTEGER, tags TEXT,+ metadata JSON, created_at INTEGER DEFAULT 0+ )`);+ db.exec(`CREATE TABLE reasoning_patterns (+ id INTEGER PRIMARY KEY AUTOINCREMENT, ts INTEGER DEFAULT 0, task_type TEXT NOT NULL,+ approach TEXT NOT NULL, success_rate REAL NOT NULL DEFAULT 0, uses INTEGER DEFAULT 0,+ avg_reward REAL DEFAULT 0, tags TEXT, metadata TEXT+ )`);+ db.exec(`CREATE TABLE pattern_embeddings (+ pattern_id INTEGER PRIMARY KEY, embedding BLOB NOT NULL+ )`);+ db.exec(`CREATE TABLE causal_edges (+ id INTEGER PRIMARY KEY AUTOINCREMENT, from_memory_id INTEGER NOT NULL, from_memory_type TEXT NOT NULL,+ to_memory_id INTEGER NOT NULL, to_memory_type TEXT NOT NULL, similarity REAL DEFAULT 0,+ confidence REAL DEFAULT 0.5, mechanism TEXT, metadata JSON, created_at INTEGER DEFAULT 0+ )`);++ const ins = db.prepare('INSERT INTO memory_entries (id, key, namespace, content, embedding) VALUES (?,?,?,?,?)');+ const vec = (seed: number) => JSON.stringify(Array.from({ length: 8 }, (_, i) => Math.sin(seed + i)));+ ins.run('c1', 'k1', 'commands', 'refactor the auth module in src/auth.ts', vec(1));+ ins.run('c2', 'k2', 'commands', 'add validation to src/api/handler.ts', vec(2));+ ins.run('c3', 'k3', 'commands', 'optimize the query in src/db/store.ts', vec(3));+ ins.run('f1', 'k4', 'feedback', JSON.stringify({ taskId: 'edit-a', success: true }), vec(4));+ ins.run('f2', 'k5', 'feedback', JSON.stringify({ taskId: 'edit-b', success: false }), vec(5));+ db.close();+}++function reasoningPatternCount(dbPath: string): number {+ const db = new Database(dbPath, { readonly: true });+ const c = (db.prepare('SELECT COUNT(*) AS c FROM reasoning_patterns').get() as { c: number }).c;+ db.close();+ return c;+}++describe.skipIf(!haveNative)('WorkerDaemon consolidate worker β ADR-174 M3 wiring', () => {+ let tempDir: string;+ let dbPath: string;+ let metricsFile: string;++ beforeEach(() => {+ tempDir = mkdtempSync(join(tmpdir(), 'worker-daemon-consolidate-'));+ mkdirSync(join(tempDir, '.claude-flow', 'logs'), { recursive: true });+ mkdirSync(join(tempDir, '.swarm'), { recursive: true });+ dbPath = join(tempDir, '.swarm', 'memory.db');+ metricsFile = join(tempDir, '.claude-flow', 'metrics', 'consolidation.json');+ delete process.env.RUFLO_DAEMON_NO_DISTILL;+ });++ afterEach(() => {+ delete process.env.RUFLO_DAEMON_NO_DISTILL;+ rmSync(tempDir, { recursive: true, force: true });+ });++ it('distills memory_entries into reasoning_patterns and writes real (non-zero) metrics', async () => {+ seedDb(dbPath);+ expect(reasoningPatternCount(dbPath)).toBe(0);++ const daemon = new WorkerDaemon(tempDir);+ const result = await (daemon as any).runConsolidateWorker();++ // The worker must have actually written new rows, not a stub.+ expect(reasoningPatternCount(dbPath)).toBeGreaterThan(0);++ // Metrics file reflects the real report β not the old hardcoded zeros.+ expect(existsSync(metricsFile)).toBe(true);+ const metrics = JSON.parse(readFileSync(metricsFile, 'utf-8'));+ expect(metrics.distillationEnabled).toBe(true);+ expect(metrics.patternsConsolidated).toBeGreaterThan(0);+ expect(metrics.memoryCleaned).toBeGreaterThan(0);+ expect(metrics.episodes).toBeGreaterThan(0);++ // Same values surfaced on the returned worker result (used by+ // `daemon trigger -w consolidate` to print output.printJson(result.output)).+ expect((result as any).patternsConsolidated).toBe(metrics.patternsConsolidated);+ });++ it('is idempotent β a second tick processes nothing new (cursor-driven)', async () => {+ seedDb(dbPath);+ const daemon = new WorkerDaemon(tempDir);++ const first = await (daemon as any).runConsolidateWorker() as any;+ const patternsAfterFirst = reasoningPatternCount(dbPath);+ expect(patternsAfterFirst).toBeGreaterThan(0);++ const second = await (daemon as any).runConsolidateWorker() as any;++ // No new source rows since the first tick -> nothing new processed.+ expect(second.memoryCleaned).toBe(0);+ expect(reasoningPatternCount(dbPath)).toBe(patternsAfterFirst);+ });++ it('bounds each tick via maxEntries so a large backlog cannot be scanned in one call', async () => {+ seedDb(dbPath);+ const daemon = new WorkerDaemon(tempDir);+ // Sanity: the tick-bound constant used by the worker must be a small,+ // finite number β this is what keeps the worker well under+ // DEFAULT_WORKER_TIMEOUT_MS (16 min) regardless of backlog size.+ const result = await (daemon as any).runConsolidateWorker() as any;+ expect(result.memoryCleaned).toBeLessThanOrEqual(1000);+ });++ it('honors RUFLO_DAEMON_NO_DISTILL=1 and skips distillation entirely', async () => {+ seedDb(dbPath);+ process.env.RUFLO_DAEMON_NO_DISTILL = '1';++ const daemon = new WorkerDaemon(tempDir);+ const result = await (daemon as any).runConsolidateWorker() as any;++ expect(result.distillationEnabled).toBe(false);+ expect(reasoningPatternCount(dbPath)).toBe(0);++ const metrics = JSON.parse(readFileSync(metricsFile, 'utf-8'));+ expect(metrics.distillationEnabled).toBe(false);+ expect(metrics.patternsConsolidated).toBe(0);+ });++ it('never throws on a missing/absent memory DB β reports skipped in metrics', async () => {+ // No .swarm/memory.db written at all.+ const daemon = new WorkerDaemon(tempDir);+ await expect((daemon as any).runConsolidateWorker()).resolves.toBeDefined();++ const metrics = JSON.parse(readFileSync(metricsFile, 'utf-8'));+ expect(metrics.distillationEnabled).toBe(true);+ expect(metrics.skipped).toBeTruthy();+ expect(metrics.patternsConsolidated).toBe(0);+ });++ it('never throws on a corrupt memory DB β reports corrupt in metrics', async () => {+ // Write garbage bytes where a sqlite DB is expected.+ writeFileSync(dbPath, 'not a real sqlite file β corrupt on purpose');++ const daemon = new WorkerDaemon(tempDir);+ await expect((daemon as any).runConsolidateWorker()).resolves.toBeDefined();++ const metrics = JSON.parse(readFileSync(metricsFile, 'utf-8'));+ expect(metrics.distillationEnabled).toBe(true);+ expect(metrics.patternsConsolidated).toBe(0);+ });++ it('is dispatched via runWorkerLogic for the "consolidate" worker type (back-compat wiring)', async () => {+ seedDb(dbPath);+ const daemon = new WorkerDaemon(tempDir);+ const output = await (daemon as any).runWorkerLogic({ type: 'consolidate' } as any);+ expect((output as any).distillationEnabled).toBe(true);+ expect(reasoningPatternCount(dbPath)).toBeGreaterThan(0);+ });+});diff --git a/v3/@claude-flow/cli/__tests__/tool-failure-signal.test.ts b/v3/@claude-flow/cli/__tests__/tool-failure-signal.test.tsnew file mode 100644index 0000000000..39161e93d4--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/tool-failure-signal.test.ts@@ -0,0 +1,50 @@+/**+ * ADR-174 follow-up: capture FAILURES in the learning substrate.+ *+ * The DB analysis found 898 feedback records, 100% success, 0 failures β the+ * post-edit/post-task hooks recorded a hardcoded `success:true` and never+ * inspected the tool outcome, so the oracle tier had no negative examples.+ *+ * `isToolFailure()` is the detector the generated hook + the shipped+ * hook-handler.cjs both inline. It reads Claude Code's PostToolUse+ * `tool_response` and returns true only on a POSITIVE error signal.+ */+import { describe, it, expect } from 'vitest';+import { isToolFailure } from '../src/init/helpers-generator.js';++describe('isToolFailure β PostToolUse outcome detection', () => {+ it('treats missing/ambiguous payloads as success (conservative)', () => {+ expect(isToolFailure(undefined)).toBe(false);+ expect(isToolFailure(null)).toBe(false);+ expect(isToolFailure({})).toBe(false);+ expect(isToolFailure({ tool_response: null })).toBe(false);+ expect(isToolFailure({ tool_response: { content: 'edited ok' } })).toBe(false);+ expect(isToolFailure({ tool_response: 'File updated successfully' })).toBe(false);+ });++ it('detects the structured error markers Claude Code sets on tool failure', () => {+ expect(isToolFailure({ tool_response: { is_error: true, content: 'String to replace not found' } })).toBe(true);+ expect(isToolFailure({ toolResponse: { isError: true } })).toBe(true);+ expect(isToolFailure({ tool_response: { success: false } })).toBe(true);+ expect(isToolFailure({ tool_response: { error: 'ENOENT' } })).toBe(true);+ });++ it('detects a non-zero Bash exit code as failure', () => {+ expect(isToolFailure({ tool_response: { exit_code: 1 } })).toBe(true);+ expect(isToolFailure({ tool_response: { exitCode: 127 } })).toBe(true);+ expect(isToolFailure({ tool_response: { code: 2 } })).toBe(true);+ expect(isToolFailure({ tool_response: { exit_code: 0 } })).toBe(false); // success+ });++ it('detects error strings in a plain-string tool_response', () => {+ expect(isToolFailure({ tool_response: 'Error: string to replace not found in file' })).toBe(true);+ expect(isToolFailure({ result: 'bash: command not found' })).toBe(true);+ expect(isToolFailure({ tool_response: 'Traceback (most recent call last):' })).toBe(true);+ expect(isToolFailure({ tool_response: 'permission denied' })).toBe(true);+ });++ it('does not false-positive on benign content that merely mentions success', () => {+ expect(isToolFailure({ tool_response: 'Successfully wrote 42 lines' })).toBe(false);+ expect(isToolFailure({ tool_response: { content: [{ type: 'text', text: 'done' }] } })).toBe(false);+ });+});diff --git a/v3/@claude-flow/cli/package.json b/v3/@claude-flow/cli/package.jsonindex 584c7c116c..42a5041eda 100644--- a/v3/@claude-flow/cli/package.json+++ b/v3/@claude-flow/cli/package.json@@ -134,6 +134,7 @@"agentic-flow": "^3.0.0-alpha.1","agenticow": "~0.2.4","metaharness": "~0.2.8",+ "page-agent": "~1.11.0","ruvector": "^0.2.27"},"publishConfig": {diff --git a/v3/@claude-flow/cli/scripts/sign-helpers.mjs b/v3/@claude-flow/cli/scripts/sign-helpers.mjsnew file mode 100644index 0000000000..4b49326ec7--- /dev/null+++ b/v3/@claude-flow/cli/scripts/sign-helpers.mjs@@ -0,0 +1,78 @@+#!/usr/bin/env node+/**+ * Sign the critical helpers β .claude/helpers/helpers.manifest.json (ADR-174).+ *+ * Run at publish time WHENEVER a critical helper changes. NEVER commit the+ * private key. The public half is baked into src/init/helper-signing.ts+ * (RUFLO_HELPERS_PUBKEY).+ *+ * Private-key resolution (first that is set wins):+ * 1. GCP Secret Manager (PREFERRED for CI/publish):+ * RUFLO_HELPERS_SIGNING_SECRET=<secret-name> (e.g. ruflo-helpers-signing-key)+ * RUFLO_HELPERS_SIGNING_PROJECT=<gcp-project> (optional; defaults to the+ * active gcloud project)+ * Fetched via `gcloud secrets versions access latest`.+ * 2. RUFLO_HELPERS_SIGNING_KEY=<pem-file-path> (local / air-gapped)+ * 3. ~/.ruflo/helpers-signing.key (dev default)+ *+ * Usage: RUFLO_HELPERS_SIGNING_SECRET=ruflo-helpers-signing-key node scripts/sign-helpers.mjs+ */+import { readFileSync, writeFileSync, existsSync } from 'node:fs';+import { createHash, sign as edSign } from 'node:crypto';+import { execFileSync } from 'node:child_process';+import { join, dirname } from 'node:path';+import { fileURLToPath } from 'node:url';+import { homedir } from 'node:os';++const __dirname = dirname(fileURLToPath(import.meta.url));+const PKG_ROOT = join(__dirname, '..');+const HELPERS_DIR = join(PKG_ROOT, '.claude', 'helpers');+const CRITICAL = ['auto-memory-hook.mjs', 'hook-handler.cjs', 'intelligence.cjs'];++function loadPrivateKey() {+ const secret = process.env.RUFLO_HELPERS_SIGNING_SECRET;+ if (secret) {+ const args = ['secrets', 'versions', 'access', 'latest', '--secret', secret];+ const project = process.env.RUFLO_HELPERS_SIGNING_PROJECT;+ if (project) args.push('--project', project);+ try {+ // stdio: key on stdout (captured), stderr inherited for auth prompts/errors.+ return execFileSync('gcloud', args, { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'inherit'] });+ } catch (e) {+ console.error(`[sign-helpers] failed to read GCP secret '${secret}'. Is gcloud authed? (gcloud auth login)`);+ process.exit(1);+ }+ }+ const keyPath = process.env.RUFLO_HELPERS_SIGNING_KEY || join(homedir(), '.ruflo', 'helpers-signing.key');+ if (!existsSync(keyPath)) {+ console.error(+ `[sign-helpers] no signing key. Set RUFLO_HELPERS_SIGNING_SECRET (GCP) ` ++ `or RUFLO_HELPERS_SIGNING_KEY (PEM path); tried ${keyPath}.`,+ );+ process.exit(1);+ }+ return readFileSync(keyPath, 'utf-8');+}++const privateKeyPem = loadPrivateKey();++const version = JSON.parse(readFileSync(join(PKG_ROOT, 'package.json'), 'utf-8')).version;+const files = {};+for (const name of CRITICAL) {+ const p = join(HELPERS_DIR, name);+ if (!existsSync(p)) { console.error(`[sign-helpers] missing helper: ${p}`); process.exit(1); }+ files[name] = createHash('sha256').update(readFileSync(p)).digest('hex');+}++const manifest = { version, files };+// Canonical bytes: sorted file keys β MUST match helper-signing.ts.+const sortedFiles = {};+for (const k of Object.keys(manifest.files).sort()) sortedFiles[k] = manifest.files[k];+const canonical = Buffer.from(JSON.stringify({ version: manifest.version, files: sortedFiles }), 'utf-8');+const signature = edSign(null, canonical, privateKeyPem).toString('base64');++const signed = { manifest, signature, algorithm: 'ed25519' };+const outPath = join(HELPERS_DIR, 'helpers.manifest.json');+writeFileSync(outPath, JSON.stringify(signed, null, 2) + '\n', 'utf-8');+console.log(`[sign-helpers] signed ${CRITICAL.length} helpers β ${outPath}`);+for (const [n, h] of Object.entries(files)) console.log(` ${n}: ${h.slice(0, 16)}β¦`);diff --git a/v3/@claude-flow/cli/scripts/tune-distill.mjs b/v3/@claude-flow/cli/scripts/tune-distill.mjsnew file mode 100644index 0000000000..c09a2b0bd9--- /dev/null+++ b/v3/@claude-flow/cli/scripts/tune-distill.mjs@@ -0,0 +1,100 @@+#!/usr/bin/env node+// tune-distill.mjs β ADR-174 Milestone 4 self-optimization harness+// ("ruflo tuning ruflo"). Grid-searches the memory-distillation config+// (batchSize x dedupDistance x promoteThreshold) and prints the grid table ++// winner + held-out score.+//+// Safety: this script NEVER touches the live DB with a write connection. It+// copies the source DB into its own scratch temp file BEFORE tuneDistillation+// ever sees a path β defense-in-depth on top of tuneDistillation's own+// internal per-candidate isolation (which only ever opens further copies of+// whatever dbPath it's handed).+//+// Usage:+// node scripts/tune-distill.mjs # tune against a copy of .swarm/memory.db+// node scripts/tune-distill.mjs --db <path> # tune against a copy of a different source db+// node scripts/tune-distill.mjs --write-config # persist the winner to .claude-flow/distill-tuned.json+// node scripts/tune-distill.mjs --quick # smaller grid for a fast sanity run++import { mkdtempSync, copyFileSync, existsSync, rmSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { dirname, join, resolve } from 'node:path';+import { tmpdir } from 'node:os';++const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));+const CLI_ROOT = resolve(SCRIPT_DIR, '..');++const {+ tuneDistillation,+ buildTunedConfigFile,+ writeTunedConfigFile,+ defaultTunedConfigPath,+} = await import(join(CLI_ROOT, 'dist/src/services/distill-tuning.js'));+const { defaultMemoryDbPath } = await import(join(CLI_ROOT, 'dist/src/services/memory-distillation.js'));++function argValue(flag) {+ const i = process.argv.indexOf(flag);+ return i >= 0 && i + 1 < process.argv.length ? process.argv[i + 1] : undefined;+}++const sourceDb = argValue('--db') ?? defaultMemoryDbPath(process.cwd());+const writeConfig = process.argv.includes('--write-config');+const quick = process.argv.includes('--quick');++if (!existsSync(sourceDb)) {+ console.error(`tune-distill: no memory DB found at ${sourceDb}`);+ console.error('Pass --db <path> to point at a different source, or run inside a project with .swarm/memory.db');+ process.exit(1);+}++// Defense-in-depth: copy the live DB into a script-owned scratch temp file+// BEFORE tuneDistillation (or anything else in this process) ever sees the+// live path. Everything downstream only ever touches this copy β the live+// path is used exactly once, for fs.copyFileSync.+const workdir = mkdtempSync(join(tmpdir(), 'tune-distill-'));+const isolatedCopy = join(workdir, 'source-copy.db');+copyFileSync(sourceDb, isolatedCopy);+console.log(`tune-distill: tuning against an isolated copy of ${sourceDb}`);+console.log(` -> ${isolatedCopy}\n`);++try {+ const grid = quick+ ? { batchSize: [200], dedupDistance: [0.1, 0.2], promoteThreshold: ['execution-only', 'execution+corroborated'] }+ : undefined; // undefined => tuneDistillation's own ADR-174 default grid++ const t0 = Date.now();+ const report = await tuneDistillation({ dbPath: isolatedCopy, grid, now: Date.now(), verbose: true });+ const elapsedMs = Date.now() - t0;++ console.log('\n=== Grid results ===');+ console.log(+ 'batchSize | dedupDistance | promoteThreshold | trainMRR@10 | trainRecall@10 | patterns | promoted',+ );+ for (const c of report.candidates) {+ const cfg = c.config;+ const row =+ `${String(cfg.batchSize).padEnd(9)} | ${String(cfg.dedupDistance).padEnd(13)} | ${cfg.promoteThreshold.padEnd(25)} | ` ++ `${c.trainScore.toFixed(4).padEnd(11)} | ${c.trainRecallAt10.toFixed(4).padEnd(14)} | ${String(c.patternCount).padEnd(8)} | ${c.promotedCount}`;+ console.log(row + (c.skipped ? ` [skipped: ${c.skipped}]` : ''));+ }++ console.log('\n=== Winner (best train MRR@10) ===');+ console.log(JSON.stringify(report.winner, null, 2));++ console.log('\n=== Held-out (scored once, on the true held-out ~20%) ===');+ console.log(JSON.stringify(report.heldOut, null, 2));+ console.log(`\noverfit flag (held-out >20% worse than train): ${report.overfit}`);++ console.log('\n=== Provenance ===');+ console.log(JSON.stringify(report.provenance, null, 2));+ console.log(`\nwall time: ${elapsedMs}ms for ${report.candidates.length} grid points`);++ if (writeConfig) {+ const outPath = defaultTunedConfigPath(process.cwd());+ writeTunedConfigFile(report, outPath);+ console.log(`\nwrote winning config -> ${outPath}`);+ console.log(JSON.stringify(buildTunedConfigFile(report), null, 2));+ }+} finally {+ rmSync(workdir, { recursive: true, force: true });+}diff --git a/v3/@claude-flow/cli/src/commands/daemon.ts b/v3/@claude-flow/cli/src/commands/daemon.tsindex b3bd5f8989..ac674c0292 100644--- a/v3/@claude-flow/cli/src/commands/daemon.ts+++ b/v3/@claude-flow/cli/src/commands/daemon.ts@@ -17,6 +17,12 @@ const startCommand: Command = {description: 'Start the worker daemon with all enabled background workers',options: [{ name: 'workers', short: 'w', type: 'string', description: 'Comma-separated list of workers to enable (default: map,audit,optimize,consolidate,testgaps)' },+ // ADR-174 M3: consolidate now runs a real memory-distillation pass+ // (memory_entries -> episodes/reasoning_patterns/causal_edges) instead of+ // a no-op stub. This opt-out skips just that pass for the life of this+ // daemon process, without touching persisted worker-enabled state β for+ // permanently disabling the worker use `daemon enable -w consolidate --disable`.+ { name: 'no-distill', type: 'boolean', description: 'Disable the consolidate worker\'s memory-distillation pass (ADR-174)' },{ name: 'quiet', short: 'Q', type: 'boolean', description: 'Suppress output' },{ name: 'background', short: 'b', type: 'boolean', description: 'Run daemon in background (detached process)', default: true },{ name: 'foreground', short: 'f', type: 'boolean', description: 'Run daemon in foreground (blocks terminal)' },@@ -38,10 +44,19 @@ const startCommand: Command = {{ command: 'claude-flow daemon start --foreground', description: 'Start in foreground (blocks terminal)' },{ command: 'claude-flow daemon start -w map,audit,optimize', description: 'Start with specific workers' },{ command: 'claude-flow daemon start --headless --sandbox strict', description: 'Start with headless workers in strict sandbox' },+ { command: 'claude-flow daemon start --no-distill', description: 'Start with the consolidate worker\'s distillation pass disabled' },],action: async (ctx: CommandContext): Promise<CommandResult> => {const quiet = ctx.flags.quiet as boolean;const foreground = ctx.flags.foreground as boolean;+ const noDistill = ctx.flags['no-distill'] as boolean | undefined;+ // ADR-174 M3: honored by WorkerDaemon's consolidate worker directly via+ // process.env β set it now so the foreground path (which runs in this+ // same process) picks it up too; the background path forwards it to the+ // forked child's env explicitly (see startBackgroundDaemon below).+ if (noDistill) {+ process.env.RUFLO_DAEMON_NO_DISTILL = '1';+ }// #1914: a forked daemon child receives --workspace <root>; the launcher// and interactive invocations have no flag and fall back to cwd.const projectRoot = resolveWorkspaceFlag(ctx.flags.workspace) ?? process.cwd();@@ -193,6 +208,7 @@ const startCommand: Command = {headless: ctx.flags.headless as boolean | undefined,sandbox: ctx.flags.sandbox as string | undefined,ttl: rawTtl,+ noDistill,});} finally {// Release the lock NOW β startBackgroundDaemon has either written@@ -405,10 +421,12 @@ interface ForwardedDaemonFlags {headless?: boolean;sandbox?: string;ttl?: string;+ /** ADR-174 M3: disable the consolidate worker's memory-distillation pass. */+ noDistill?: boolean;}async function startBackgroundDaemon(projectRoot: string, quiet: boolean, forwarded: ForwardedDaemonFlags = {}): Promise<CommandResult> {- const { maxCpuLoad, minFreeMemory, workers, headless, sandbox, ttl } = forwarded;+ const { maxCpuLoad, minFreeMemory, workers, headless, sandbox, ttl, noDistill } = forwarded;// Validate and resolve project rootconst resolvedRoot = resolve(projectRoot);validatePath(resolvedRoot, 'Project root');@@ -504,6 +522,11 @@ async function startBackgroundDaemon(projectRoot: string, quiet: boolean, forwarif (typeof sandbox === 'string' && (sandbox === 'strict' || sandbox === 'permissive' || sandbox === 'disabled')) {forkArgs.push('--sandbox', sandbox);}+ // ADR-174 M3: forward the distillation opt-out to the forked foreground+ // child; its own `start` action sets RUFLO_DAEMON_NO_DISTILL from this flag.+ if (noDistill === true) {+ forkArgs.push('--no-distill');+ }// #1914: stamp the workspace into argv (kept LAST) so the foreground daemon// process is self-identifying and `killStaleDaemons` only reaps daemons// belonging to this workspace. resolvedRoot was validatePath()'d above.@@ -1403,7 +1426,7 @@ export const daemonCommand: Command = {`${output.highlight('map')} - Codebase mapping (5 min interval)`,`${output.highlight('audit')} - Security analysis (10 min interval)`,`${output.highlight('optimize')} - Performance optimization (15 min interval)`,- `${output.highlight('consolidate')} - Memory consolidation (30 min interval)`,+ `${output.highlight('consolidate')} - Memory distillation: memory_entries -> episodes/reasoning_patterns/causal_edges (30 min interval, ADR-174; --no-distill to disable)`,`${output.highlight('testgaps')} - Test coverage analysis (20 min interval)`,`${output.highlight('predict')} - Predictive preloading (2 min, disabled by default)`,`${output.highlight('document')} - Auto-documentation (60 min, disabled by default)`,diff --git a/v3/@claude-flow/cli/src/commands/memory-distill.ts b/v3/@claude-flow/cli/src/commands/memory-distill.tsnew file mode 100644index 0000000000..787a2d0315--- /dev/null+++ b/v3/@claude-flow/cli/src/commands/memory-distill.ts@@ -0,0 +1,433 @@+/**+ * V3 CLI `memory distill` Command Family (ADR-174 Milestone 2)+ *+ * CLI surface over the frozen M1 service (`../services/memory-distillation.js`+ * β `runDistillation` / `defaultMemoryDbPath`). This file does not implement+ * any distillation logic itself; it only resolves flags/config/presets into+ * `DistillOptions`, calls the service, and formats the report.+ *+ * memory distill run β run (or dry-run) a distillation pass+ * memory distill status β read-only report on the target tables + cursor+ * memory distill config β print the effective resolved config as JSON+ *+ * Design notes:+ * - `--judge fable` requires `--budget-usd > 0` (ADR-172 cost-bounded advisor+ * gate). This is enforced here, client-side, as a fail-fast β the service+ * itself also refuses (`skipped: 'judge:fable requires ...'`) but failing+ * fast in the CLI gives a clearer, non-zero-exit error.+ * - `--aggressive` / `--conservative` are preset bundles (ADR-174 param+ * table). Precedence, low to high: built-in defaults < `--config` file <+ * preset < explicit `--batch-size`/`--dedup-distance` flags.+ * - `status` opens the DB read-only via the same "variable-specifier"+ * optional-import pattern used by `../memory/graph-edge-writer.ts` so the+ * TypeScript compiler never statically requires `better-sqlite3` types,+ * and degrades gracefully (no throw) when the DB, tables, or the native+ * module are absent.+ */+import * as fs from 'fs';+import * as path from 'path';++import type { Command, CommandContext, CommandResult } from '../types.js';+import { output } from '../output.js';+import {+ runDistillation,+ defaultMemoryDbPath,+ type DistillOptions,+ type DistillReport,+} from '../services/memory-distillation.js';++// ============================================================================+// Shared config resolution (run + config subcommands)+// ============================================================================++export interface DistillCliConfig {+ dryRun: boolean;+ namespaces?: string[];+ batchSize: number;+ dedupDistance: number;+ maxEntries?: number;+ sinceRowid?: number;+ budgetUsd: number;+ judge: 'structural' | 'fable';+}++const DEFAULT_CONFIG: DistillCliConfig = {+ dryRun: false,+ batchSize: 200,+ dedupDistance: 0.2, // ADR-174 M4-tuned platform default (~37% fewer patterns, retrieval-neutral)+ budgetUsd: 0,+ judge: 'structural',+};++// ADR-174 preset bundles β distinct extremes around the 0.2 tuned default.+const AGGRESSIVE_PRESET = { dedupDistance: 0.3, batchSize: 500 }; // more clustering β fewer, coarser patterns+const CONSERVATIVE_PRESET = { dedupDistance: 0.1, batchSize: 100 }; // less clustering β more, granular patterns++const DB_OPTION = {+ name: 'db',+ description: 'Path to the memory DB (default: cwd/.swarm/memory.db)',+ type: 'string' as const,+};++type ResolveResult = { ok: true; config: DistillCliConfig } | { ok: false; error: string };++/**+ * Resolve the effective distill config from: built-in defaults, an optional+ * `--config <path>` JSON file, an `--aggressive`/`--conservative` preset, and+ * finally explicit CLI flags (highest precedence).+ */+export function resolveDistillConfig(ctx: CommandContext): ResolveResult {+ let cfg: DistillCliConfig = { ...DEFAULT_CONFIG };++ const configPath = ctx.flags.config as string | undefined;+ if (configPath) {+ try {+ const raw = fs.readFileSync(path.resolve(configPath), 'utf8');+ const parsed = JSON.parse(raw);+ if (parsed && typeof parsed === 'object') {+ cfg = { ...cfg, ...parsed };+ }+ } catch (error) {+ return { ok: false, error: `Failed to load --config ${configPath}: ${error instanceof Error ? error.message : String(error)}` };+ }+ }++ const aggressive = ctx.flags.aggressive === true;+ const conservative = ctx.flags.conservative === true;+ if (aggressive && conservative) {+ return { ok: false, error: '--aggressive and --conservative are mutually exclusive' };+ }+ if (aggressive) cfg = { ...cfg, ...AGGRESSIVE_PRESET };+ if (conservative) cfg = { ...cfg, ...CONSERVATIVE_PRESET };++ // Explicit CLI flags win over the config file and presets.+ if (ctx.flags.dryRun === true) cfg.dryRun = true;+ if (typeof ctx.flags.namespace === 'string' && ctx.flags.namespace.length > 0) {+ cfg.namespaces = ctx.flags.namespace.split(',').map((s) => s.trim()).filter(Boolean);+ }+ if (ctx.flags.batchSize !== undefined) cfg.batchSize = Number(ctx.flags.batchSize);+ if (ctx.flags.dedupDistance !== undefined) cfg.dedupDistance = Number(ctx.flags.dedupDistance);+ if (ctx.flags.maxEntries !== undefined) cfg.maxEntries = Number(ctx.flags.maxEntries);+ if (ctx.flags.since !== undefined) cfg.sinceRowid = Number(ctx.flags.since);+ if (ctx.flags.budgetUsd !== undefined) cfg.budgetUsd = Number(ctx.flags.budgetUsd);+ if (ctx.flags.judge !== undefined) {+ if (ctx.flags.judge !== 'structural' && ctx.flags.judge !== 'fable') {+ return { ok: false, error: `--judge must be 'structural' or 'fable' (got '${String(ctx.flags.judge)}')` };+ }+ cfg.judge = ctx.flags.judge;+ }++ return { ok: true, config: cfg };+}++function resolveDbPath(ctx: CommandContext): string {+ return (ctx.flags.db as string) || defaultMemoryDbPath(ctx.cwd || process.cwd());+}++// ============================================================================+// `memory distill run`+// ============================================================================++const runCommand: Command = {+ name: 'run',+ description: 'Distill memory_entries into episodes/reasoning_patterns/pattern_embeddings/causal_edges (ADR-174)',+ options: [+ { name: 'dry-run', description: 'Report counts, write nothing', type: 'boolean', default: false },+ { name: 'namespace', description: 'Comma-separated namespace scope (default: all embedded namespaces)', type: 'string' },+ { name: 'batch-size', description: 'Rows per transaction (default 200)', type: 'number', default: 200 },+ { name: 'dedup-distance', description: 'Cosine distance for pattern clustering (default 0.12)', type: 'number', default: 0.12 },+ { name: 'max-entries', description: 'Per-invocation work cap (default unbounded)', type: 'number' },+ { name: 'since', description: 'Override the incremental cursor and rescan from this rowid', type: 'number' },+ { name: 'budget-usd', description: '$0 by default; >0 required to unlock --judge fable (ADR-172)', type: 'number', default: 0 },+ { name: 'judge', description: "'structural' (default, $0) or 'fable' (requires --budget-usd > 0)", type: 'string', default: 'structural', choices: ['structural', 'fable'] },+ { name: 'aggressive', description: 'Preset: dedup-distance 0.2, batch-size 500', type: 'boolean' },+ { name: 'conservative', description: 'Preset: dedup-distance 0.08, batch-size 100', type: 'boolean' },+ { name: 'config', description: 'Load options from a JSON config file (see: memory distill config)', type: 'string' },+ { ...DB_OPTION },+ { name: 'verbose', short: 'v', description: 'Verbose service logging', type: 'boolean' },+ ],+ examples: [+ { command: 'claude-flow memory distill run --dry-run', description: 'Preview counts without writing anything' },+ { command: 'claude-flow memory distill run --namespace feedback,commands', description: 'Scope the run to specific namespaces' },+ { command: 'claude-flow memory distill run --aggressive', description: 'Larger batches, looser dedup clustering' },+ { command: 'claude-flow memory distill run --judge fable --budget-usd 2', description: 'Opt into the cost-bounded Fable judge (ADR-172)' },+ ],+ action: async (ctx: CommandContext): Promise<CommandResult> => {+ const resolved = resolveDistillConfig(ctx);+ if (!resolved.ok) {+ output.printError(resolved.error);+ return { success: false, exitCode: 1 };+ }+ const config = resolved.config;++ // Fail-fast ADR-172 gate: the Fable judge is cost-bounded and opt-in only.+ if (config.judge === 'fable' && !(config.budgetUsd > 0)) {+ output.printError(+ '--judge fable requires --budget-usd > 0 (ADR-172 cost-bounded advisor path). ' ++ 'Refusing to run the LLM judge against a $0 budget.',+ );+ return { success: false, exitCode: 1 };+ }++ const dbPath = resolveDbPath(ctx);++ output.writeln();+ output.writeln(output.bold('Memory Distillation (ADR-174)'));+ output.writeln(output.dim('β'.repeat(55)));+ if (config.dryRun) output.writeln(output.warning('DRY RUN β no writes will be made'));++ const spinner = output.createSpinner({ text: 'Distilling memory_entries...', spinner: 'dots' });+ spinner.start();++ const distillOptions: DistillOptions = {+ dbPath,+ namespaces: config.namespaces,+ batchSize: config.batchSize,+ maxEntries: config.maxEntries,+ dedupDistance: config.dedupDistance,+ dryRun: config.dryRun,+ judge: config.judge,+ sinceRowid: config.sinceRowid,+ verbose: ctx.flags.verbose === true,+ };++ let report: DistillReport;+ try {+ report = await runDistillation(distillOptions);+ } catch (error) {+ spinner.fail('Distillation failed');+ output.printError(error instanceof Error ? error.message : String(error));+ return { success: false, exitCode: 1 };+ }++ if (report.skipped) {+ spinner.succeed('Distillation skipped');+ output.writeln(output.warning(`skipped: ${report.skipped}`));+ return { success: true, data: { dbPath, config, report } };+ }++ spinner.succeed(config.dryRun ? 'Dry-run complete' : 'Distillation complete');+ output.writeln();++ output.printTable({+ columns: [+ { key: 'metric', header: 'Metric', width: 24 },+ { key: 'value', header: 'Value', width: 20 },+ ],+ data: [+ { metric: 'Processed', value: String(report.processed) },+ { metric: 'Episodes', value: String(report.episodes) },+ { metric: 'Patterns', value: String(report.patterns) },+ { metric: 'Pattern Embeddings', value: String(report.patternEmbeddings) },+ { metric: 'Causal Edges', value: String(report.causalEdges) },+ { metric: 'Promoted (ADR-171)', value: String(report.promoted) },+ { metric: 'Namespaces', value: report.namespaces.join(', ') || '(none)' },+ { metric: 'Spend', value: `$${report.spendUsd.toFixed(4)}` },+ { metric: 'Dry Run', value: report.dryRun ? 'yes' : 'no' },+ ],+ });++ const provenanceEntries = Object.entries(report.byProvenance);+ if (provenanceEntries.length > 0) {+ output.writeln();+ output.writeln(output.bold('By Provenance'));+ output.printList(provenanceEntries.map(([tier, count]) => `${output.highlight(tier)}: ${count}`));+ }++ return { success: true, data: { dbPath, config, report } };+ },+};++// ============================================================================+// `memory distill status`+// ============================================================================++const statusCommand: Command = {+ name: 'status',+ description: 'Read-only report: target table row counts, per-namespace distill_state cursor, promoted vs proxy breakdown',+ options: [{ ...DB_OPTION }],+ examples: [+ { command: 'claude-flow memory distill status', description: 'Show distillation state for the default DB' },+ { command: 'claude-flow memory distill status --db ./copy.db', description: 'Inspect a specific DB copy' },+ ],+ action: async (ctx: CommandContext): Promise<CommandResult> => {+ const dbPath = resolveDbPath(ctx);++ output.writeln();+ output.writeln(output.bold('Memory Distillation Status'));+ output.writeln(output.dim('β'.repeat(55)));++ if (!fs.existsSync(dbPath)) {+ output.writeln(output.warning(`No memory DB found at ${dbPath}`));+ return { success: true, data: { available: false, dbPath, reason: 'no-db' } };+ }++ // Optional native dep β hidden behind a variable specifier so the+ // compiler never statically requires `better-sqlite3` types (same+ // pattern as ../memory/graph-edge-writer.ts).+ let Database: any;+ try {+ const mod: string = 'better-sqlite3';+ Database = (await import(mod)).default;+ } catch {+ output.writeln(output.warning('better-sqlite3 native module unavailable β cannot read distillation state.'));+ return { success: true, data: { available: false, dbPath, reason: 'better-sqlite3 unavailable' } };+ }++ let db: any;+ try {+ db = new Database(dbPath, { readonly: true, fileMustExist: true });+ } catch (error) {+ output.printError(`Failed to open ${dbPath}: ${error instanceof Error ? error.message : String(error)}`);+ return { success: true, data: { available: false, dbPath, reason: 'open-failed' } };+ }++ try {+ const tableExists = (name: string): boolean =>+ (db.prepare("SELECT COUNT(*) AS c FROM sqlite_master WHERE type='table' AND name=?").get(name)?.c ?? 0) > 0;++ const targetTables = ['episodes', 'reasoning_patterns', 'pattern_embeddings', 'causal_edges'];+ const presence: Record<string, boolean> = {};+ for (const t of [...targetTables, 'distill_state']) presence[t] = tableExists(t);++ const counts: Record<string, number> = {};+ for (const t of targetTables) {+ counts[t] = presence[t] ? (db.prepare(`SELECT COUNT(*) AS c FROM ${t}`).get()?.c ?? 0) : 0;+ }++ let cursors: Array<{ namespace: string; lastRowid: number; lastRunAt: number | null }> = [];+ if (presence.distill_state) {+ cursors = db.prepare(+ 'SELECT namespace AS namespace, last_rowid AS lastRowid, last_run_at AS lastRunAt FROM distill_state ORDER BY namespace',+ ).all();+ }++ let promoted = 0;+ let proxy = 0;+ if (presence.reasoning_patterns) {+ promoted = db.prepare(+ "SELECT COUNT(*) AS c FROM reasoning_patterns WHERE json_extract(metadata,'$.promoted')=1",+ ).get()?.c ?? 0;+ proxy = db.prepare(+ "SELECT COUNT(*) AS c FROM reasoning_patterns WHERE json_extract(metadata,'$.provenance')='proxy:structural'",+ ).get()?.c ?? 0;+ }++ db.close();++ output.printTable({+ columns: [+ { key: 'table', header: 'Table', width: 22 },+ { key: 'rows', header: 'Rows', width: 10 },+ ],+ data: targetTables.map((t) => ({ table: t, rows: String(counts[t]) })),+ });++ output.writeln();+ output.writeln(output.bold('Promote gate (ADR-171)'));+ output.writeln(+ ` promoted: ${promoted} proxy (never promoted): ${proxy} total patterns: ${counts.reasoning_patterns}`,+ );++ if (cursors.length > 0) {+ output.writeln();+ output.writeln(output.bold('distill_state cursor'));+ output.printTable({+ columns: [+ { key: 'namespace', header: 'Namespace', width: 20 },+ { key: 'lastRowid', header: 'Last Rowid', width: 12 },+ { key: 'lastRunAt', header: 'Last Run', width: 26 },+ ],+ data: cursors.map((c) => ({+ namespace: c.namespace,+ lastRowid: String(c.lastRowid),+ lastRunAt: c.lastRunAt ? new Date(c.lastRunAt).toISOString() : 'never',+ })),+ });+ } else {+ output.writeln();+ output.writeln(output.dim('No distill_state cursor rows yet (run `memory distill run` first).'));+ }++ if (!presence.reasoning_patterns) {+ output.writeln();+ output.writeln(output.dim('Target tables not present β agentdb schema not initialised, or distillation never run.'));+ }++ return {+ success: true,+ data: { available: true, dbPath, counts, cursors, promoted, proxy, tablesPresent: presence },+ };+ } catch (error) {+ try { db?.close(); } catch { /* best-effort */ }+ output.printError(error instanceof Error ? error.message : String(error));+ return { success: true, data: { available: false, dbPath, reason: 'error' } };+ }+ },+};++// ============================================================================+// `memory distill config`+// ============================================================================++const configCommand: Command = {+ name: 'config',+ description: 'Print the effective distill config (defaults + --config file + preset + explicit flags) as JSON',+ options: [+ { name: 'config', description: 'Load options from a JSON config file', type: 'string' },+ { name: 'aggressive', description: 'Preset: dedup-distance 0.2, batch-size 500', type: 'boolean' },+ { name: 'conservative', description: 'Preset: dedup-distance 0.08, batch-size 100', type: 'boolean' },+ { name: 'namespace', description: 'Comma-separated namespace scope', type: 'string' },+ { name: 'batch-size', description: 'Rows per transaction', type: 'number' },+ { name: 'dedup-distance', description: 'Cosine distance for pattern clustering', type: 'number' },+ { name: 'max-entries', description: 'Per-invocation work cap', type: 'number' },+ { name: 'since', description: 'Override incremental cursor start (rowid)', type: 'number' },+ { name: 'budget-usd', description: '$0 by default', type: 'number' },+ { name: 'judge', description: "'structural' | 'fable'", type: 'string' },+ { ...DB_OPTION },+ ],+ examples: [+ { command: 'claude-flow memory distill config', description: 'Print the platform-default config' },+ { command: 'claude-flow memory distill config --aggressive', description: 'Print the effective config with the aggressive preset applied' },+ ],+ action: async (ctx: CommandContext): Promise<CommandResult> => {+ const resolved = resolveDistillConfig(ctx);+ if (!resolved.ok) {+ output.printError(resolved.error);+ return { success: false, exitCode: 1 };+ }+ const dbPath = resolveDbPath(ctx);+ const payload = { dbPath, ...resolved.config };+ output.writeln(JSON.stringify(payload, null, 2));+ return { success: true, data: payload };+ },+};++// ============================================================================+// `memory distill` (parent)+// ============================================================================++export const distillCommand: Command = {+ name: 'distill',+ description: 'Memory distillation (ADR-174): mine memory_entries into reasoning_patterns/episodes/causal_edges',+ subcommands: [runCommand, statusCommand, configCommand],+ examples: [+ { command: 'claude-flow memory distill run --dry-run', description: 'Preview a distillation pass' },+ { command: 'claude-flow memory distill status', description: 'Show distilled table counts + cursor' },+ { command: 'claude-flow memory distill config --conservative', description: 'Print the effective conservative-preset config' },+ ],+ action: async (): Promise<CommandResult> => {+ output.writeln();+ output.writeln(output.bold('Memory Distillation (ADR-174)'));+ output.writeln('Usage: claude-flow memory distill <run|status|config> [options]');+ output.writeln();+ output.printList([+ `${output.highlight('run')} - Distill memory_entries into the structured intelligence tables`,+ `${output.highlight('status')} - Report target table counts, cursor, and promote-gate breakdown`,+ `${output.highlight('config')} - Print the effective resolved config as JSON`,+ ]);+ return { success: true };+ },+};++export default distillCommand;diff --git a/v3/@claude-flow/cli/src/commands/memory.ts b/v3/@claude-flow/cli/src/commands/memory.tsindex 23d0acaabf..dbc48ae075 100644--- a/v3/@claude-flow/cli/src/commands/memory.ts+++ b/v3/@claude-flow/cli/src/commands/memory.ts@@ -7,6 +7,7 @@ import type { Command, CommandContext, CommandResult } from '../types.js';import { output } from '../output.js';import { select, confirm, input } from '../prompt.js';import { callMCPTool, MCPClientError } from '../mcp-client.js';+import { distillCommand } from './memory-distill.js';// Memory backendsconst BACKENDS = [@@ -1683,7 +1684,7 @@ const initMemoryCommand: Command = {export const memoryCommand: Command = {name: 'memory',description: 'Memory management commands',- subcommands: [initMemoryCommand, storeCommand, retrieveCommand, searchCommand, listCommand, deleteCommand, statsCommand, configureCommand, cleanupCommand, compressCommand, exportCommand, importCommand],+ subcommands: [initMemoryCommand, storeCommand, retrieveCommand, searchCommand, listCommand, deleteCommand, statsCommand, configureCommand, cleanupCommand, compressCommand, exportCommand, importCommand, distillCommand],options: [],examples: [{ command: 'claude-flow memory store -k "key" -v "value"', description: 'Store data' },@@ -1709,7 +1710,8 @@ export const memoryCommand: Command = {`${output.highlight('cleanup')} - Clean expired entries`,`${output.highlight('compress')} - Compress database`,`${output.highlight('export')} - Export memory to file`,- `${output.highlight('import')} - Import from file`+ `${output.highlight('import')} - Import from file`,+ `${output.highlight('distill')} - Distill memory_entries into structured intelligence (ADR-174)`]);return { success: true };diff --git a/v3/@claude-flow/cli/src/index.ts b/v3/@claude-flow/cli/src/index.tsindex a02aa92f48..3a49b04b21 100644--- a/v3/@claude-flow/cli/src/index.ts+++ b/v3/@claude-flow/cli/src/index.ts@@ -133,6 +133,26 @@ export class CLI {this.checkForUpdatesOnStartup().catch(() => {/* silent */});}+ // Version-stamped helper auto-refresh β propagate hook fixes to an already+ // initialized project without a manual re-init. Skip for init/upgrade+ // (they refresh explicitly). AWAITED (not fire-and-forget) so a fast+ // command can't exit before the copy lands; the fast path is a single+ // stamp read + string compare (sub-ms), and the copy runs at most once per+ // version bump. Best-effort + silent β never blocks or fails a command.+ if (commandPath[0] !== 'init' && commandPath[0] !== 'update') {+ try {+ const { autoRefreshHelpersIfStale } = await import('./init/helper-refresh.js');+ const r = await autoRefreshHelpersIfStale(process.cwd());+ if (r.blocked) {+ // Integrity failure = potential on-disk tampering of hook code. Warn+ // loudly (not silent) β the existing project helpers were left intact.+ this.output.printWarning(`Skipped helper auto-refresh β ${r.blocked}. Reinstall @claude-flow/cli from a trusted source.`);+ } else if (r.refreshed && this.output.isVerbose()) {+ this.output.printDebug(`Refreshed .claude/helpers (${r.from} β ${r.to})`);+ }+ } catch { /* silent */ }+ }+// Handle lazy-loaded commands that weren't recognized by the parser// If commandPath is empty but positional has a command name, check if it's lazy-loadableif (commandPath.length === 0 && positional.length > 0 && !positional[0].startsWith('-')) {diff --git a/v3/@claude-flow/cli/src/init/executor.ts b/v3/@claude-flow/cli/src/init/executor.tsindex 0c40abf54c..ec1de744ab 100644--- a/v3/@claude-flow/cli/src/init/executor.ts+++ b/v3/@claude-flow/cli/src/init/executor.ts@@ -28,6 +28,7 @@ import {generateAutoMemoryHook,generateRufloHookCjs,} from './helpers-generator.js';+import { getInstalledCliVersion, HELPERS_STAMP_FILE } from './helper-refresh.js';import { generateClaudeMd } from './claudemd-generator.js';import { recordMemoryPackagePath } from './memory-package-resolver.js';@@ -552,6 +553,15 @@ export async function executeUpgrade(targetDir: string, upgradeSettings = false)}}+ // Stamp the installed version so the startup auto-refresh treats these as+ // current (no redundant re-copy on the next command).+ try {+ fs.writeFileSync(+ path.join(targetDir, '.claude', 'helpers', HELPERS_STAMP_FILE),+ getInstalledCliVersion(), 'utf-8',+ );+ } catch { /* non-fatal */ }+// #2545: (re)record the resolved @claude-flow/memory path so the auto-memory// hook can find it on the npx install path. Best-effort β see executeInit.const memRecord = recordMemoryPackagePath(targetDir, 'upgrade');diff --git a/v3/@claude-flow/cli/src/init/helper-refresh.ts b/v3/@claude-flow/cli/src/init/helper-refresh.tsnew file mode 100644index 0000000000..abe4aab67b--- /dev/null+++ b/v3/@claude-flow/cli/src/init/helper-refresh.ts@@ -0,0 +1,157 @@+/**+ * Version-stamped critical-helper auto-refresh.+ *+ * The Claude Code hooks run the PROJECT-LOCAL `.claude/helpers/*.cjs` copies,+ * not the installed npm package β so `npx ruflo@latest` does NOT update them,+ * and users don't know to re-run `init`. This module stamps the helpers with+ * the installed CLI version and, on the next CLI command, silently re-copies+ * them when the stamp is stale. Hook fixes (e.g. the ADR-174 failure-capture+ * change) then propagate to every user on their next `ruflo` command with zero+ * action required.+ *+ * This file is intentionally LIGHTWEIGHT β it is imported on every CLI startup,+ * so it depends only on `fs`/`path`/`module` at load time and lazily imports the+ * heavy generators only on the rare fallback path (source dir unresolvable).+ */+import * as fs from 'fs';+import * as path from 'path';+import { fileURLToPath } from 'url';+import { createRequire } from 'module';+import {+ verifyHelpersManifest, sha256Hex, HELPERS_MANIFEST_FILE, type HelpersManifest,+} from './helper-signing.js';++const __dirname = path.dirname(fileURLToPath(import.meta.url));++export const HELPERS_STAMP_FILE = '.helpers-version';+/** ruflo-owned helpers that carry hook logic and must track the package version. */+export const CRITICAL_HELPERS = ['auto-memory-hook.mjs', 'hook-handler.cjs', 'intelligence.cjs'];++/** Installed @claude-flow/cli version β the value the helpers are stamped with. */+export function getInstalledCliVersion(): string {+ try {+ const esmRequire = createRequire(import.meta.url);+ const pkg = JSON.parse(fs.readFileSync(esmRequire.resolve('@claude-flow/cli/package.json'), 'utf-8'));+ return String(pkg.version || '0.0.0');+ } catch {+ // dist/src/init β package root+ try {+ const pkg = JSON.parse(fs.readFileSync(path.resolve(__dirname, '..', '..', '..', 'package.json'), 'utf-8'));+ return String(pkg.version || '0.0.0');+ } catch { return '0.0.0'; }+ }+}++/** Locate the in-package `.claude/helpers` dir (the copy source). Null if not found. */+function findPackageHelpersDir(): string | null {+ const candidates: string[] = [];+ try {+ const esmRequire = createRequire(import.meta.url);+ const pkgRoot = path.dirname(esmRequire.resolve('@claude-flow/cli/package.json'));+ candidates.push(path.join(pkgRoot, '.claude', 'helpers'));+ } catch { /* not resolvable */ }+ candidates.push(path.resolve(__dirname, '..', '..', '..', '.claude', 'helpers'));+ for (const c of candidates) {+ if (fs.existsSync(path.join(c, 'hook-handler.cjs'))) return c;+ }+ return null;+}++/**+ * Re-copy the critical helpers into `helpersDir` and stamp `version`.+ *+ * SECURITY (fail-closed): when copying from the installed package, every source+ * helper is verified against ruflo's Ed25519-signed manifest FIRST β nothing is+ * copied unless the manifest signature is valid AND each helper's SHA-256+ * matches. A tampered helper or manifest (e.g. a sibling package's postinstall+ * overwriting on-disk hook code) is REFUSED, not propagated. The generator+ * fallback needs no manifest β that content comes from the CLI's own compiled+ * code, which is already the trust root.+ */+async function writeCriticalHelpers(+ helpersDir: string,+ version: string,+): Promise<{ wrote: boolean; blocked?: string }> {+ const source = findPackageHelpersDir();+ if (source) {+ // 1. Verify the signed manifest against the baked public key.+ let trusted: HelpersManifest | null = null;+ try {+ trusted = verifyHelpersManifest(fs.readFileSync(path.join(source, HELPERS_MANIFEST_FILE), 'utf-8'));+ } catch { trusted = null; }+ if (!trusted) return { wrote: false, blocked: 'signed helpers manifest missing or signature invalid' };++ // 2. Verify EVERY source helper's hash before copying ANYTHING (atomic gate).+ const toCopy: string[] = [];+ for (const name of CRITICAL_HELPERS) {+ const sp = path.join(source, name);+ if (!fs.existsSync(sp)) continue;+ const expected = trusted.files[name];+ if (!expected || sha256Hex(fs.readFileSync(sp)) !== expected) {+ return { wrote: false, blocked: `integrity check failed for ${name} β refusing to install` };+ }+ toCopy.push(name);+ }++ // 3. All verified β copy, plus the signed manifest itself as an audit trail.+ let wrote = false;+ for (const name of toCopy) {+ const tp = path.join(helpersDir, name);+ fs.copyFileSync(path.join(source, name), tp);+ try { fs.chmodSync(tp, '755'); } catch { /* non-fatal */ }+ wrote = true;+ }+ try { fs.copyFileSync(path.join(source, HELPERS_MANIFEST_FILE), path.join(helpersDir, HELPERS_MANIFEST_FILE)); } catch { /* non-fatal */ }+ if (wrote) {+ try { fs.writeFileSync(path.join(helpersDir, HELPERS_STAMP_FILE), version, 'utf-8'); } catch { /* non-fatal */ }+ }+ return { wrote };+ }++ // Fallback: source unresolvable (broken npx paths) β regenerate from the CLI's+ // OWN compiled generators (the trust root; no external file to verify).+ const gen = await import('./helpers-generator.js');+ const files: Record<string, string> = {+ 'hook-handler.cjs': gen.generateHookHandler(),+ 'intelligence.cjs': gen.generateIntelligenceStub(),+ 'auto-memory-hook.mjs': gen.generateAutoMemoryHook(),+ };+ let wrote = false;+ for (const [name, content] of Object.entries(files)) {+ const tp = path.join(helpersDir, name);+ fs.writeFileSync(tp, content, 'utf-8');+ try { fs.chmodSync(tp, '755'); } catch { /* non-fatal */ }+ wrote = true;+ }+ if (wrote) {+ try { fs.writeFileSync(path.join(helpersDir, HELPERS_STAMP_FILE), version, 'utf-8'); } catch { /* non-fatal */ }+ }+ return { wrote };+}++/**+ * On CLI startup: if an initialized project's critical helpers are stamped older+ * than the installed CLI version, silently re-copy them. Fast path is a single+ * stamp read + string compare (sub-ms); the copy runs at most once per version+ * bump. Best-effort, never throws. No-op outside a ruflo project (requires an+ * existing hook-handler.cjs β never creates files in an unrelated directory).+ */+export async function autoRefreshHelpersIfStale(+ cwd: string,+): Promise<{ refreshed: boolean; from?: string; to?: string; blocked?: string }> {+ try {+ const helpersDir = path.join(cwd, '.claude', 'helpers');+ if (!fs.existsSync(path.join(helpersDir, 'hook-handler.cjs'))) return { refreshed: false };+ const version = getInstalledCliVersion();+ let stamped = '';+ try { stamped = fs.readFileSync(path.join(helpersDir, HELPERS_STAMP_FILE), 'utf-8').trim(); } catch { /* pre-feature: unstamped */ }+ if (stamped === version) return { refreshed: false }; // up to date β fast path+ const res = await writeCriticalHelpers(helpersDir, version);+ // A blocked refresh is a SECURITY signal (tampered source/manifest) β surface+ // it, don't advance the stamp, and leave the project's existing helpers intact.+ if (res.blocked) return { refreshed: false, blocked: res.blocked };+ return res.wrote ? { refreshed: true, from: stamped || '(unstamped)', to: version } : { refreshed: false };+ } catch {+ return { refreshed: false };+ }+}diff --git a/v3/@claude-flow/cli/src/init/helper-signing.ts b/v3/@claude-flow/cli/src/init/helper-signing.tsnew file mode 100644index 0000000000..347b9fa832--- /dev/null+++ b/v3/@claude-flow/cli/src/init/helper-signing.ts@@ -0,0 +1,73 @@+/**+ * Ed25519 provenance for the auto-refreshed critical helpers (ADR-174 security).+ *+ * The helper auto-refresh copies auto-EXECUTING hook code (`hook-handler.cjs`+ * etc.) from the installed package into a project. npm verifies the tarball at+ * INSTALL time, but not the files on disk afterward β a sibling package's+ * postinstall (or disk tampering) could overwrite them, and the refresh would+ * faithfully propagate the tampered code. This gate closes that: every helper+ * is verified against a ruflo-signed manifest before install, and a mismatch is+ * REFUSED (fail-closed). The public key is baked in below; the private key is+ * never in the repo (see scripts/sign-helpers.mjs).+ *+ * Native Node crypto (RFC 8032 Ed25519), zero external deps β same primitive as+ * src/appliance/rvfa-signing.ts.+ */+import { createHash, verify as edVerify } from 'crypto';++/**+ * Ruflo helper-signing PUBLIC key (safe to commit). The matching private key is+ * held out-of-repo and provided to scripts/sign-helpers.mjs at publish time via+ * $RUFLO_HELPERS_SIGNING_KEY. Rotating the key = replace this constant + re-sign.+ */+export const RUFLO_HELPERS_PUBKEY = `-----BEGIN PUBLIC KEY-----+MCowBQYDK2VwAyEAhnFv74/CRcGWd0hL8zjyZ+52bIJ9SfcSgOutuKgo0Vg=+-----END PUBLIC KEY-----`;++export const HELPERS_MANIFEST_FILE = 'helpers.manifest.json';++export interface HelpersManifest {+ version: string;+ files: Record<string, string>; // helper name -> sha256 hex+}+export interface SignedHelpersManifest {+ manifest: HelpersManifest;+ signature: string; // base64 Ed25519 signature over canonicalManifestBytes(manifest)+ algorithm: 'ed25519';+}++export function sha256Hex(content: string | Buffer): string {+ return createHash('sha256').update(content).digest('hex');+}++/**+ * Deterministic canonical bytes of a manifest β file keys sorted so the signer+ * and verifier agree byte-for-byte regardless of object insertion order.+ */+export function canonicalManifestBytes(m: HelpersManifest): Buffer {+ const files: Record<string, string> = {};+ for (const k of Object.keys(m.files).sort()) files[k] = m.files[k];+ return Buffer.from(JSON.stringify({ version: m.version, files }), 'utf-8');+}++/**+ * Verify a signed helpers manifest against ruflo's public key. Returns the+ * trusted file->sha256 manifest, or null on ANY failure (bad signature,+ * malformed JSON, wrong algorithm). Fail-closed β the caller MUST refuse to+ * install unverified helpers.+ */+export function verifyHelpersManifest(+ signedJson: string,+ pubkeyPem: string = RUFLO_HELPERS_PUBKEY,+): HelpersManifest | null {+ try {+ const signed = JSON.parse(signedJson) as SignedHelpersManifest;+ if (!signed || signed.algorithm !== 'ed25519' || !signed.signature || !signed.manifest) return null;+ if (!signed.manifest.files || typeof signed.manifest.files !== 'object') return null;+ const bytes = canonicalManifestBytes(signed.manifest);+ const ok = edVerify(null, bytes, pubkeyPem, Buffer.from(signed.signature, 'base64'));+ return ok ? signed.manifest : null;+ } catch {+ return null;+ }+}diff --git a/v3/@claude-flow/cli/src/init/helpers-generator.ts b/v3/@claude-flow/cli/src/init/helpers-generator.tsindex 12978b1ff9..4f46ec5520 100644--- a/v3/@claude-flow/cli/src/init/helpers-generator.ts+++ b/v3/@claude-flow/cli/src/init/helpers-generator.ts@@ -14,6 +14,56 @@ import { generateStatuslineScript, generateStatuslineHook } from './statusline-gexport const ATTRIBUTION_FOOTER ='π€ Generated with [RuFlo](https://github.com/ruvnet/ruflo)';+/**+ * Detect whether a Claude Code PostToolUse payload represents a FAILED tool run.+ *+ * Why this matters: the learning substrate had 898 feedback records, 100%+ * success, 0 failures β because the post-edit/post-task hooks recorded a+ * hardcoded `success:true` and never inspected the tool outcome. With no+ * negative examples, the oracle tier can't teach good-vs-bad (see the DB+ * analysis + ADR-174). Claude Code passes the tool result in the PostToolUse+ * hook payload (`tool_response`), which for a failed Write/Edit/Bash carries an+ * error marker. This predicate is the single source of truth the generated+ * hook inlines, and is unit-tested here so the detection stays honest.+ *+ * Conservative: returns true only on a POSITIVE error signal; ambiguous/missing+ * payloads default to success (matches prior behavior, avoids false failures).+ */+export function isToolFailure(hookInput: unknown): boolean {+ if (!hookInput || typeof hookInput !== 'object') return false;+ const h = hookInput as Record<string, unknown>;+ const tr = (h.tool_response ?? h.toolResponse ?? h.result) as unknown;+ if (tr == null) return false;+ if (typeof tr === 'string') {+ return /\b(error|failed|failure|exception|not found|no such|permission denied|traceback)\b/i.test(tr);+ }+ if (typeof tr === 'object') {+ const o = tr as Record<string, unknown>;+ if (o.is_error === true || o.isError === true || o.success === false || o.error != null) return true;+ // Bash tool: non-zero exit code is a failure.+ const code = (o.exit_code ?? o.exitCode ?? o.code) as unknown;+ if (typeof code === 'number' && code !== 0) return true;+ // Nested content array (Claude tool result shape): {content:[...], is_error:true}+ if (Array.isArray(o.content) && o.is_error === true) return true;+ }+ return false;+}++// The exact predicate the generated hook inlines β kept in sync with+// isToolFailure() above (mirrored, since the generated .cjs has no imports).+const TOOL_FAILURE_EXPR =+ '(function(hi){' ++ 'if(!hi||typeof hi!=="object")return false;' ++ 'var tr=hi.tool_response!=null?hi.tool_response:(hi.toolResponse!=null?hi.toolResponse:hi.result);' ++ 'if(tr==null)return false;' ++ 'if(typeof tr==="string")return /\\b(error|failed|failure|exception|not found|no such|permission denied|traceback)\\b/i.test(tr);' ++ 'if(typeof tr==="object"){' ++ 'if(tr.is_error===true||tr.isError===true||tr.success===false||tr.error!=null)return true;' ++ 'var code=tr.exit_code!=null?tr.exit_code:(tr.exitCode!=null?tr.exitCode:tr.code);' ++ 'if(typeof code==="number"&&code!==0)return true;' ++ 'if(Array.isArray(tr.content)&&tr.is_error===true)return true;' ++ '}return false;})(hookInput)';+/*** Generate pre-commit hook script*/@@ -469,6 +519,9 @@ export function generateHookHandler(): string {' // hook (#1944). Pull `.command` off whichever stdin shape Claude Code sent.',' var toolInputObj = hookInput.toolInput || hookInput.tool_input || {};'," var prompt = hookInput.prompt || hookInput.command || toolInputObj.command || process.env.PROMPT || process.env.TOOL_INPUT_command || args.join(' ') || '';",+ ' // Capture FAILURES, not just successes, so the learning substrate has',+ ' // negative examples (see ADR-174 / DB analysis). Mirrors isToolFailure().',+ ' var toolFailed = ' + TOOL_FAILURE_EXPR + ';','','const handlers = {'," 'route': () => {",@@ -513,10 +566,10 @@ export function generateHookHandler(): string {' if (intelligence && intelligence.recordEdit) {',' try {'," var file = process.env.TOOL_INPUT_file_path || args[0] || '';",- ' intelligence.recordEdit(file);',+ ' intelligence.recordEdit(file, !toolFailed);',' } catch (e) { /* non-fatal */ }',' }',- " console.log('[OK] Edit recorded');",+ " console.log(toolFailed ? '[LEARN] Edit FAILURE recorded' : '[OK] Edit recorded');",' },',''," 'session-restore': () => {",@@ -572,10 +625,10 @@ export function generateHookHandler(): string {" 'post-task': () => {",' if (intelligence && intelligence.feedback) {',' try {',- ' intelligence.feedback(true);',+ ' intelligence.feedback(!toolFailed);',' } catch (e) { /* non-fatal */ }',' }',- " console.log('[OK] Task completed');",+ " console.log(toolFailed ? '[LEARN] Task FAILURE recorded' : '[OK] Task completed');",' },',''," 'compact-manual': () => {",@@ -820,10 +873,12 @@ export function generateIntelligenceStub(): string {' return lines2.join("\\n");',' },','',- ' recordEdit: function(file) {',+ ' recordEdit: function(file, success) {',' if (!file) return;',' ensureDir(DATA_DIR);',- ' var line = JSON.stringify({ type: "edit", file: file, timestamp: Date.now() }) + "\\n";',+ ' // success defaults to true; an explicit false (failed edit) is recorded',+ ' // so consolidation/distillation gets a negative example (ADR-174).',+ ' var line = JSON.stringify({ type: "edit", file: file, success: success !== false, timestamp: Date.now() }) + "\\n";',' fs.appendFileSync(PENDING_PATH, line, "utf-8");',' },','',diff --git a/v3/@claude-flow/cli/src/mcp-client.ts b/v3/@claude-flow/cli/src/mcp-client.tsindex 0a9f4a9f02..b894771ece 100644--- a/v3/@claude-flow/cli/src/mcp-client.ts+++ b/v3/@claude-flow/cli/src/mcp-client.ts@@ -36,6 +36,10 @@ import { daaTools } from './mcp-tools/daa-tools.js';import { coordinationTools } from './mcp-tools/coordination-tools.js';import { browserTools } from './mcp-tools/browser-tools.js';import { browserSessionTools } from './mcp-tools/browser-session-tools.js';+// ADR-175 β page-agent natural-language intent layer (browser_act). Always+// registered; degrades to {degraded:true} at call time when page-agent or an+// OpenAI-compatible LLM provider isn't available.+import { browserIntentTools } from './mcp-tools/browser-intent-tools.js';import { execFileSync } from 'node:child_process';// Phase 6: AgentDB v3 controller toolsimport { agentdbTools } from './mcp-tools/agentdb-tools.js';@@ -94,6 +98,15 @@ function getBrowserSessionTools(): MCPTool[] {return browserSessionTools;}+/**+ * ADR-175 `browser_act` β always registered like browserSessionTools; the+ * handler itself resolves page-agent + LLM-provider availability at call+ * time and returns `{degraded: true}` rather than throwing.+ */+function getBrowserIntentTools(): MCPTool[] {+ return browserIntentTools;+}+/*** MCP Tool Registry* Maps tool names to their handler functions@@ -134,6 +147,7 @@ registerTools([...coordinationTools,...getBrowserTools(),...getBrowserSessionTools(),+ ...getBrowserIntentTools(),// Phase 6: AgentDB v3 controller tools...agentdbTools,// RuVector WASM toolsdiff --git a/v3/@claude-flow/cli/src/mcp-tools/browser-intent-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/browser-intent-tools.tsnew file mode 100644index 0000000000..c63d04bce2--- /dev/null+++ b/v3/@claude-flow/cli/src/mcp-tools/browser-intent-tools.ts@@ -0,0 +1,612 @@+/**+ * Browser Intent MCP Tools β ADR-175 page-agent integration.+ *+ * Adds a natural-language INTENT layer on top of the low-level selector-based+ * `browser_*` tools (browser-tools.ts, driven by the `agent-browser` CLI).+ * `browser_act({ task })` lets a caller say "Click the login button" instead+ * of chaining browser_snapshot + browser_click.+ *+ * Backing library: `page-agent` (npm, MIT, https://github.com/alibaba/page-agent)+ * β in-page injected JS that turns the DOM into text and lets an LLM execute+ * natural-language intents via `agent.execute('Click login')`.+ *+ * ============================================================================+ * VERIFIED API (recorded 2026-07-04 against [email protected] β `npm view+ * page-agent`, the published README, and the actual npm tarball contents).+ * Deviations from the original integration brief are called out inline.+ * ============================================================================+ *+ * - Package layout changed since the brief was written: `page-agent` is now a+ * thin composition of `@page-agent/core` + `@page-agent/llms` ++ * `@page-agent/page-controller` + `@page-agent/ui`. The npm package is+ * ESM-only (`"type":"module"`) and ships two builds:+ * - `dist/esm/page-agent.js` β the Node/bundler ESM entry.+ * - `dist/iife/page-agent.demo.js` β a self-contained browser IIFE that+ * sets `window.PageAgent = <class>` (this is what we inject).+ *+ * - DEVIATION #1 (load-bearing): `await import('page-agent')` is NOT a safe+ * availability probe in Node. Empirically, importing the ESM entry throws+ * `ReferenceError: window is not defined` β even when the package IS+ * correctly installed β because `@page-agent/core`'s module graph touches+ * DOM globals at import time (it's designed to run in a browser, not Node).+ * This differs from the agenticow-loader.ts pattern used elsewhere in this+ * repo (dynamic `import()` + catch `ERR_MODULE_NOT_FOUND`), which only+ * works for pure-Node optional deps. Instead we detect availability via+ * `require.resolve('page-agent')` β path resolution only, never executes+ * module code β the same technique `browser-session-tools.ts` already uses+ * to resolve the local `ruvector` CLI bin without invoking it.+ *+ * - DEVIATION #2: the IIFE bundle unconditionally (also) auto-constructs a+ * DEMO `PageAgent` instance via `setTimeout`, pointed at Alibaba's public+ * sandbox endpoint (`model: 'qwen3.5-plus'`, a `page-ag-testing-*.run`+ * baseURL, `apiKey: 'NA'`) UNLESS the bundle is loaded via a real+ * `<script src="...?autoInit=false">` tag β the guard reads+ * `document.currentScript.src`, which is `null` when the bundle runs via+ * `eval`/CDP (our only injection path through the `agent-browser`+ * primitive set). Left alone, every `browser_act` call would leak page+ * content to Alibaba's test endpoint using a placeholder key. We strip the+ * demo auto-init tail (`stripDemoAutoInit`) before injecting rather than+ * relying on the query-param guard.+ *+ * - Constructor: `new PageAgent({ model, baseURL, apiKey, language })` β+ * `apiKey` is OPTIONAL on the type (`LLMConfig.apiKey?: string`), confirmed+ * in `@page-agent/llms`' `LLMConfig` interface.+ *+ * - `execute(task: string): Promise<ExecutionResult>` where+ * `ExecutionResult = { success: boolean; data: string; history: HistoricalEvent[] }`+ * β DEVIATION #3: NOT `{ success, result, steps }` as sketched in the+ * original brief. We map `data` β `result` and `history.length` β `steps`+ * in the tool's own return shape, and also pass `history` through for+ * callers that want the full step trace.+ *+ * - LLM transport: confirmed via `@page-agent/llms`' `OpenAIClient` β a+ * single non-streaming `POST ${baseURL}/chat/completions` with+ * `Authorization: Bearer ${apiKey}` and OpenAI tool-calling JSON. This is+ * why a bare `ANTHROPIC_API_KEY` cannot be handed to page-agent directly:+ * Anthropic's native API is a different shape (`/v1/messages`, different+ * tool-call format). We require an OpenAI-*compatible* endpoint β reusing+ * this CLI's own Tier-3 fallback ladder from `agent-execute-core.ts`+ * (OpenRouter, then Ollama Cloud), or an explicit override.+ *+ * ARCHITECTURAL CONSTRAINT (mirrors metaharness-tools.ts / agenticow-tools.ts)+ * `page-agent` lives in `optionalDependencies`. Every code path degrades to+ * `{ degraded: true }` β never throws β when the package or an LLM provider+ * isn't available.+ *+ * KEY-SAFETY CONSTRAINT (load-bearing): page-agent's LLM calls happen FROM+ * the browser page context (it's client-side injected JS), so its `apiKey`+ * config field is necessarily visible to whatever we inject into the page.+ * To avoid ever placing a real provider key into a page-context string, we+ * start a short-lived local HTTP proxy (`startLocalLLMProxy`) bound to+ * 127.0.0.1 that holds the REAL key server-side and injects the real+ * `Authorization` header itself; the page only ever sees the proxy's+ * loopback URL plus a constant placeholder string (`PLACEHOLDER_API_KEY`).+ *+ * @module @claude-flow/cli/mcp-tools/browser-intent+ */++import { createRequire } from 'node:module';+import { createServer, type Server } from 'node:http';+import { readFileSync, existsSync } from 'node:fs';+import { dirname, join } from 'node:path';+import type { MCPTool, MCPToolResult } from './types.js';+import { validateText, validateIdentifier } from './validate-input.js';+import { execBrowserCommand } from './browser-tools.js';+import { storeEntry } from '../memory/memory-initializer.js';++// ============================================================================+// page-agent availability (Node-safe: never `import()`s the package β see+// DEVIATION #1 above)+// ============================================================================++export interface PageAgentBundle {+ /** Package root directory (contains package.json). */+ root: string;+ /** Absolute path to the browser-injectable IIFE bundle. */+ iifePath: string;+ version: string;+}++/**+ * Locate the installed `page-agent` package's browser bundle without ever+ * executing its module code. `resolvePkg` is injectable for tests (DI over+ * module mocking, since `vi.mock('page-agent', ...)` cannot simulate absence+ * for a package we deliberately never `import()`).+ */+export function locatePageAgentBundle(+ resolvePkg: (id: string) => string = (id) => createRequire(import.meta.url).resolve(id),+): PageAgentBundle | null {+ let entry: string;+ try {+ entry = resolvePkg('page-agent');+ } catch (err: unknown) {+ const e = err as NodeJS.ErrnoException;+ if (+ e?.code === 'MODULE_NOT_FOUND' ||+ e?.code === 'ERR_MODULE_NOT_FOUND' ||+ /Cannot find (module|package)/i.test(String(e?.message))+ ) {+ return null;+ }+ throw err;+ }++ // entry resolves to <root>/dist/esm/page-agent.js β walk up looking for the+ // package's own package.json (mirrors resolveLocalRuvectorCli's technique+ // in browser-session-tools.ts).+ let dir = dirname(entry);+ for (let i = 0; i < 6; i++) {+ try {+ const pkg = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf-8')) as {+ name?: string;+ version?: string;+ };+ if (pkg.name === 'page-agent') {+ const iifePath = join(dir, 'dist', 'iife', 'page-agent.demo.js');+ if (!existsSync(iifePath)) return null;+ return { root: dir, iifePath, version: pkg.version ?? 'unknown' };+ }+ } catch {+ // no package.json at this level β keep walking up+ }+ const parent = dirname(dir);+ if (parent === dir) break;+ dir = parent;+ }+ return null;+}++// ============================================================================+// LLM provider resolution β reuses this CLI's own Tier-3 fallback ladder+// (agent-execute-core.ts): OpenRouter, then Ollama Cloud β both already+// OpenAI-compatible. ANTHROPIC_API_KEY alone is intentionally NOT accepted+// here (see DEVIATION notes above β page-agent needs a /chat/completions+// shaped endpoint).+// ============================================================================++export interface ResolvedLLMConfig {+ baseURL: string;+ apiKey: string;+ model: string;+ source: 'explicit' | 'openrouter' | 'ollama';+}++export function resolvePageAgentLLMConfig(env: NodeJS.ProcessEnv = process.env): ResolvedLLMConfig | null {+ // 1. Explicit override β a caller-configured OpenAI-compatible endpoint+ // dedicated to page-agent (private proxy, Azure OpenAI, vLLM, etc).+ if (env.CLAUDE_FLOW_PAGE_AGENT_BASE_URL && env.CLAUDE_FLOW_PAGE_AGENT_API_KEY) {+ return {+ baseURL: env.CLAUDE_FLOW_PAGE_AGENT_BASE_URL,+ apiKey: env.CLAUDE_FLOW_PAGE_AGENT_API_KEY,+ model: env.CLAUDE_FLOW_PAGE_AGENT_MODEL || 'gpt-4o-mini',+ source: 'explicit',+ };+ }+ // 2. OpenRouter β this CLI's own Tier-3 OpenAI-compatible fallback.+ if (env.OPENROUTER_API_KEY) {+ const base = (env.OPENROUTER_BASE_URL || 'https://openrouter.ai/api').replace(/\/+$/, '');+ return {+ baseURL: base.endsWith('/v1') ? base : `${base}/v1`,+ apiKey: env.OPENROUTER_API_KEY,+ model: env.OPENROUTER_DEFAULT_MODEL || 'anthropic/claude-sonnet-4-6',+ source: 'openrouter',+ };+ }+ // 3. Ollama Cloud β OpenAI-compatible per #1725.+ if (env.OLLAMA_API_KEY) {+ const base = (env.OLLAMA_BASE_URL || 'https://ollama.com').replace(/\/+$/, '');+ return {+ baseURL: base.endsWith('/v1') ? base : `${base}/v1`,+ apiKey: env.OLLAMA_API_KEY,+ model: env.CLAUDE_FLOW_PAGE_AGENT_OLLAMA_MODEL || 'qwen2.5-coder:32b-cloud',+ source: 'ollama',+ };+ }+ return null;+}++// ============================================================================+// Local loopback LLM proxy β keeps the real provider key server-side. Only+// the proxy's 127.0.0.1 URL + a placeholder string ever reach page context.+// ============================================================================++export const PLACEHOLDER_API_KEY = 'ruflo-proxied-key';++export interface LLMProxyHandle {+ url: string;+ close: () => void;+}++export function startLocalLLMProxy(real: { baseURL: string; apiKey: string }): Promise<LLMProxyHandle> {+ return new Promise((resolve, reject) => {+ const server: Server = createServer((req, res) => {+ const target = `${real.baseURL.replace(/\/+$/, '')}${req.url ?? ''}`;+ const chunks: Buffer[] = [];+ req.on('data', (c: Buffer) => chunks.push(c));+ req.on('end', () => {+ const body = Buffer.concat(chunks);+ fetch(target, {+ method: req.method,+ headers: {+ 'content-type': 'application/json',+ // The real key is injected here, server-side, and nowhere else β+ // whatever Authorization header the page-context request carried+ // (the placeholder) is discarded.+ authorization: `Bearer ${real.apiKey}`,+ },+ body: body.length > 0 ? body : undefined,+ })+ .then(async (upstream) => {+ const text = await upstream.text();+ res.writeHead(upstream.status, {+ 'content-type': upstream.headers.get('content-type') || 'application/json',+ });+ res.end(text);+ })+ .catch((err: unknown) => {+ res.writeHead(502, { 'content-type': 'application/json' });+ res.end(JSON.stringify({ error: { message: String(err instanceof Error ? err.message : err) } }));+ });+ });+ });+ server.on('error', reject);+ server.listen(0, '127.0.0.1', () => {+ const addr = server.address();+ const port = typeof addr === 'object' && addr ? addr.port : 0;+ resolve({+ url: `http://127.0.0.1:${port}`,+ close: () => {+ try { server.close(); } catch { /* best-effort */ }+ },+ });+ });+ });+}++// ============================================================================+// Injection script assembly+// ============================================================================++/** Marker at which the demo bundle's always-on auto-init tail begins (see DEVIATION #2). */+const DEMO_TAIL_MARKER = 'var DEMO_MODEL=';++/**+ * Fail-CLOSED firewall signatures. page-agent's shipped IIFE (`page-agent.demo.js`)+ * auto-POSTs page content to Alibaba's public sandbox on inject+ * (`https://page-ag-testing-*.<region>.fcapp.run`, model `DEMO_MODEL`). We strip+ * that tail, but the strip is only best-effort text matching. These signatures+ * are the load-bearing guarantee: if ANY survive the strip, we REFUSE to inject.+ * Version-independent β an upstream bundle change that moves/renames the marker+ * can never silently re-enable the leak (the previous strip fell OPEN and+ * injected as-is when the marker moved; this cannot).+ */+const DEMO_LEAK_SIGNATURES: RegExp[] = [+ /page-ag-testing/i, // the demo endpoint subdomain prefix+ /\.fcapp\.run/i, // Alibaba Function Compute host (the demo backend)+ /\bDEMO_MODEL\b/, // the demo auto-init marker/model+];++/** Thrown when a bundle still contains a demo/sandbox endpoint after stripping. */+export class DemoLeakError extends Error {+ constructor(public readonly signature: string) {+ super(+ `page-agent bundle still contains a demo/sandbox endpoint (matched /${signature}/) ` ++ 'after stripping β refusing to inject to avoid leaking page content to Alibaba\'s sandbox',+ );+ this.name = 'DemoLeakError';+ }+}++/** Returns the first demo-leak signature found in `source`, or null if clean. */+export function findDemoLeak(source: string): string | null {+ for (const re of DEMO_LEAK_SIGNATURES) {+ if (re.test(source)) return re.source;+ }+ return null;+}++/**+ * Strip the demo bundle's auto-init tail so injecting it via eval doesn't spin+ * up a second `window.pageAgent` pointed at Alibaba's sandbox endpoint. This is+ * best-effort at the text level; the real guarantee is the fail-closed+ * `findDemoLeak` firewall enforced in `buildPageAgentInjection`, NOT this strip.+ */+export function stripDemoAutoInit(iifeSource: string): string {+ const idx = iifeSource.indexOf(DEMO_TAIL_MARKER);+ return idx === -1 ? iifeSource : iifeSource.slice(0, idx);+}++export const BROWSER_ACT_RESULT_GLOBAL = '__ruflo_browser_act_result__';++export interface PageAgentPageConfig {+ baseURL: string;+ apiKey: string;+ model: string;+ language?: string;+}++/**+ * Build the full script to hand to `browser_eval` / `agent-browser eval`:+ * the (demo-stripped) IIFE bundle, followed by our own controlled+ * construction + `execute()` call whose settled result lands on a window+ * global we can poll for.+ *+ * KEY-SAFETY: `pageConfig.apiKey` MUST be `PLACEHOLDER_API_KEY` (or another+ * non-secret placeholder) β callers are responsible for routing the real key+ * through `startLocalLLMProxy` first. This function only assembles strings;+ * it does not itself guarantee key safety, so callers MUST NOT pass a real+ * key here (see `browserIntentTools` handler for the enforced call site).+ */+export function buildPageAgentInjection(+ iifeSource: string,+ pageConfig: PageAgentPageConfig,+ task: string,+): string {+ const safeIife = stripDemoAutoInit(iifeSource);+ // Fail-closed: never inject a bundle that still carries the demo endpoint.+ const leak = findDemoLeak(safeIife);+ if (leak) throw new DemoLeakError(leak);+ const cfgJson = JSON.stringify(pageConfig);+ const taskJson = JSON.stringify(task);+ return `${safeIife}+;(function(){+ window.${BROWSER_ACT_RESULT_GLOBAL} = null;+ try {+ if (!window.PageAgent) {+ window.${BROWSER_ACT_RESULT_GLOBAL} = { success: false, error: 'PageAgent not defined after injection' };+ return;+ }+ var agent = new window.PageAgent(${cfgJson});+ window.__ruflo_pageAgent__ = agent;+ agent.execute(${taskJson}).then(function(r){+ window.${BROWSER_ACT_RESULT_GLOBAL} = { success: true, result: r };+ }).catch(function(e){+ window.${BROWSER_ACT_RESULT_GLOBAL} = { success: false, error: String((e && e.message) || e) };+ });+ } catch (e) {+ window.${BROWSER_ACT_RESULT_GLOBAL} = { success: false, error: String((e && e.message) || e) };+ }+})();+'ruflo-browser-act-injected'`;+}++// ============================================================================+// AIDefence content gate (best-effort β @claude-flow/aidefence is itself an+// optional dep; mirrors the lazy-load pattern in security-tools.ts)+// ============================================================================++async function gateWithAIDefence(text: string): Promise<{ text: string; flagged: boolean; gated: boolean }> {+ if (!text) return { text, flagged: false, gated: false };+ try {+ const mod = await import('@claude-flow/aidefence');+ const defender = mod.createAIDefence({ enableLearning: false });+ let flagged = false;+ try {+ const quick = defender.quickScan(text);+ flagged = !!quick?.threat;+ } catch { /* quickScan unavailable on this build */ }+ try {+ if (!flagged && defender.hasPII(text)) flagged = true;+ } catch { /* hasPII unavailable */ }+ if (flagged) {+ return { text: '[content redacted by AIDefence β threat or PII detected]', flagged: true, gated: true };+ }+ return { text, flagged: false, gated: true };+ } catch {+ // @claude-flow/aidefence is itself optional β pass through rather than+ // block the caller when it isn't installed.+ return { text, flagged: false, gated: false };+ }+}++// ============================================================================+// ADR-174 distillation β best-effort trajectory recording into the `browser`+// memory namespace. Never fatal.+// ============================================================================++export async function recordBrowserTrajectory(entry: {+ task: string;+ url?: string;+ success: boolean;+ dataPreview: string;+ steps: number;+ source: string;+}): Promise<boolean> {+ try {+ const slug = entry.task.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 40) || 'task';+ const key = `browser-act-${Date.now()}-${slug}`;+ const result = await storeEntry({+ key,+ namespace: 'browser',+ value: JSON.stringify(entry),+ generateEmbeddingFlag: true,+ });+ return !!result?.success;+ } catch {+ return false;+ }+}++// ============================================================================+// Result polling β `agent-browser eval` doesn't itself await in-page+// promises, so we kick off `execute()` in a fire-and-forget IIFE and poll a+// window global for the settled result.+// ============================================================================++async function pollForResult(session: string, timeoutMs: number): Promise<{ success: boolean; result?: unknown; error?: string } | null> {+ const start = Date.now();+ const pollScript = `JSON.stringify(window.${BROWSER_ACT_RESULT_GLOBAL} || null)`;+ while (Date.now() - start < timeoutMs) {+ const r = await execBrowserCommand(['eval', pollScript], session);+ const text = r.content[0]?.text;+ if (text) {+ let outer: unknown;+ try { outer = JSON.parse(text); } catch { outer = null; }+ const raw = outer && typeof outer === 'object' ? ((outer as Record<string, unknown>).result ?? (outer as Record<string, unknown>).data ?? outer) : outer;+ let parsed: unknown = null;+ if (typeof raw === 'string') {+ try { parsed = JSON.parse(raw); } catch { parsed = null; }+ } else {+ parsed = raw;+ }+ if (parsed && parsed !== 'null') return parsed as { success: boolean; result?: unknown; error?: string };+ }+ await new Promise((res) => setTimeout(res, 500));+ }+ return null;+}++function fail(error: string, extra: Record<string, unknown> = {}): MCPToolResult {+ return {+ content: [{ type: 'text', text: JSON.stringify({ success: false, error, ...extra }, null, 2) }],+ isError: true,+ };+}++function ok(payload: Record<string, unknown>): MCPToolResult {+ return { content: [{ type: 'text', text: JSON.stringify({ success: true, ...payload }, null, 2) }] };+}++function degraded(reason: string, hint: string): MCPToolResult {+ return { content: [{ type: 'text', text: JSON.stringify({ success: true, degraded: true, reason, hint }, null, 2) }] };+}++// ============================================================================+// Tool definition+// ============================================================================++export const browserIntentTools: MCPTool[] = [+ {+ name: 'browser_act',+ description:+ 'Use when a target element is easier to describe than to select, or when an intent spans several steps: executes a natural-language instruction on the current page via page-agent (e.g. "Click the login button", "Fill the search box with cats and submit"). ' ++ 'Prefer this over chaining browser_snapshot + browser_click/fill for such multi-step intents; pair with browser_open/browser_screenshot for navigation and visual verification (page-agent is text-DOM only, so it is blind to canvas/visual-only UIs β keep the selector + screenshot tools for those). ' ++ 'Falls back to {degraded:true} when page-agent is not installed or no OpenAI-compatible LLM provider is configured ' ++ '(set OPENROUTER_API_KEY or OLLAMA_API_KEY; a bare ANTHROPIC_API_KEY is not sufficient β page-agent requires a /chat/completions-shaped endpoint).',+ category: 'browser',+ tags: ['browser', 'intent', 'nl', 'page-agent'],+ inputSchema: {+ type: 'object',+ properties: {+ task: { type: 'string', description: 'Natural-language instruction, e.g. "Click the login button"' },+ session: { type: 'string', description: 'Session ID (default: "default")' },+ url: { type: 'string', description: 'Optional URL to navigate to before executing the intent' },+ timeoutMs: { type: 'number', description: 'Max time to wait for execute() to settle (default 120000)' },+ },+ required: ['task'],+ },+ handler: async (input): Promise<MCPToolResult> => {+ const vTask = validateText(input.task, 'task');+ if (!vTask.valid) return fail(vTask.error || 'invalid task');+ if (input.session) {+ const vS = validateIdentifier(input.session, 'session');+ if (!vS.valid) return fail(vS.error || 'invalid session');+ }+ if (input.url) {+ const vU = validateText(input.url, 'url');+ if (!vU.valid) return fail(vU.error || 'invalid url');+ }++ const task = input.task as string;+ const session = (input.session as string | undefined) || 'default';+ const url = input.url as string | undefined;+ const timeoutMs = typeof input.timeoutMs === 'number' && input.timeoutMs > 0 ? input.timeoutMs : 120_000;++ // 1. page-agent must be installed.+ const bundle = locatePageAgentBundle();+ if (!bundle) {+ return degraded('page-agent not installed', 'npm i page-agent');+ }++ // 2. An OpenAI-compatible LLM provider must be configured.+ const llmConfig = resolvePageAgentLLMConfig();+ if (!llmConfig) {+ return degraded(+ 'no OpenAI-compatible LLM provider configured',+ 'Set OPENROUTER_API_KEY or OLLAMA_API_KEY (both OpenAI-compatible), or CLAUDE_FLOW_PAGE_AGENT_BASE_URL + CLAUDE_FLOW_PAGE_AGENT_API_KEY for a custom endpoint. ANTHROPIC_API_KEY alone is not sufficient.',+ );+ }++ let iifeSource: string;+ try {+ iifeSource = readFileSync(bundle.iifePath, 'utf-8');+ } catch (err) {+ return degraded('page-agent bundle unreadable', String(err instanceof Error ? err.message : err));+ }++ // 3. Start the loopback proxy β the real key stays server-side.+ let proxy: LLMProxyHandle;+ try {+ proxy = await startLocalLLMProxy({ baseURL: llmConfig.baseURL, apiKey: llmConfig.apiKey });+ } catch (err) {+ return degraded('local LLM proxy failed to start', String(err instanceof Error ? err.message : err));+ }++ try {+ // 4. Navigate first, if requested.+ if (url) {+ const nav = await execBrowserCommand(['open', url], session);+ if (nav.isError) return fail('browser open failed', { detail: nav.content[0]?.text });+ }++ // 5. Inject the (demo-stripped) bundle + our controlled execute() call.+ // apiKey here is ALWAYS the placeholder β the real key lives only+ // in `llmConfig`, used above to start the proxy.+ const pageConfig: PageAgentPageConfig = {+ baseURL: proxy.url,+ apiKey: PLACEHOLDER_API_KEY,+ model: llmConfig.model,+ language: 'en-US',+ };+ let script: string;+ try {+ script = buildPageAgentInjection(iifeSource, pageConfig, task);+ } catch (err) {+ if (err instanceof DemoLeakError) {+ // Refuse to inject rather than leak page content to Alibaba's sandbox.+ return degraded('page-agent bundle contains a demo endpoint we could not neutralize', err.message);+ }+ throw err;+ }+ const inject = await execBrowserCommand(['eval', script], session);+ if (inject.isError) return fail('page-agent injection failed', { detail: inject.content[0]?.text });++ // 6. Poll for the settled execute() result.+ const settled = await pollForResult(session, timeoutMs);+ if (!settled) {+ return fail('timed out waiting for page-agent execution', { timeoutMs });+ }+ if (!settled.success) {+ return fail(settled.error || 'page-agent execution failed', { task, url });+ }++ const execResult = settled.result as { success: boolean; data: string; history: unknown[] } | undefined;+ const rawData = execResult?.data ?? '';+ const gate = await gateWithAIDefence(String(rawData));++ // 7. Best-effort ADR-174 trajectory recording.+ await recordBrowserTrajectory({+ task,+ url,+ success: !!execResult?.success,+ dataPreview: gate.text.slice(0, 500),+ steps: execResult?.history?.length ?? 0,+ source: llmConfig.source,+ });++ return ok({+ result: gate.text,+ steps: execResult?.history?.length ?? 0,+ history: execResult?.history ?? [],+ contentFlagged: gate.flagged,+ pageAgentVersion: bundle.version,+ llmSource: llmConfig.source,+ });+ } finally {+ proxy.close();+ }+ },+ },+];++export default browserIntentTools;diff --git a/v3/@claude-flow/cli/src/mcp-tools/browser-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/browser-tools.tsindex d1da13a5b3..f5ba6da665 100644--- a/v3/@claude-flow/cli/src/mcp-tools/browser-tools.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/browser-tools.ts@@ -19,8 +19,11 @@ const browserSessions = new Map<string, {/*** Execute agent-browser CLI command.* Tries global agent-browser first, falls back to npx if ENOENT.+ *+ * Exported so browser-intent-tools.ts (ADR-175 `browser_act`) can reuse the same+ * exec + fallback + session-plumbing instead of duplicating it.*/-async function execBrowserCommand(args: string[], session = 'default'): Promise<MCPToolResult> {+export async function execBrowserCommand(args: string[], session = 'default'): Promise<MCPToolResult> {const { execFileSync } = await import('child_process');const fullArgs = ['--session', session, '--json', ...args];diff --git a/v3/@claude-flow/cli/src/services/distill-tuning.ts b/v3/@claude-flow/cli/src/services/distill-tuning.tsnew file mode 100644index 0000000000..1d2b0c6f0f--- /dev/null+++ b/v3/@claude-flow/cli/src/services/distill-tuning.ts@@ -0,0 +1,695 @@+/**+ * distill-tuning.ts β Milestone 4 self-optimization harness (ADR-174+ * "Self-optimization (ruflo tuning ruflo)").+ *+ * Finds the memory-distillation config (batchSize, dedupDistance,+ * promoteThreshold) that maximises MEASURED retrieval quality β not a+ * marketing claim β via grid search over ISOLATED copies of a source DB,+ * scored on a held-out split. $0, offline, no LLM.+ *+ * ββ M1 is frozen ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+ * `runDistillation` (memory-distillation.ts) is Milestone 1 and DONE. This+ * module only imports and calls it; it never changes its behaviour.+ * `promoteThreshold` is NOT an M1 parameter, so the two grid values are+ * implemented here as a post-processing pass over the copy's+ * `reasoning_patterns.metadata` after M1 has run (see+ * `applyCorroboratedPromotion`) β 'execution-only' leaves M1's own promote+ * gate untouched (only `oracle:test-exec` promotes, per ADR-171);+ * 'execution+corroborated' additionally promotes `proxy:structural` patterns+ * that multiple near-duplicate entries corroborated (`uses >=+ * CORROBORATION_MIN_USES`), widening the promoted-recall pool.+ *+ * ββ Isolation (load-bearing) βββββββββββββββββββββββββββββββββββββββββββββ+ * The source DB at `options.dbPath` is NEVER opened with a database+ * connection anywhere in this module β only `fs.copyFileSync` (byte copy)+ * and a whole-file sha256 checksum (`fs.readFileSync`) ever touch it. Every+ * grid candidate, and the read-only split/query-set pass, runs against its+ * OWN temp copy. The checksum is asserted equal before and after the whole+ * run.+ *+ * ββ Held-out discipline (ADR-174 Β§Self-optimization) βββββββββββββββββββββ+ * Earliest ~80% of `memory_entries` (by rowid β a monotonic proxy for+ * insertion time) = TRAIN, most-recent ~20% = HELD-OUT. HELD-OUT is scored+ * exactly ONCE, for the winning config only, AFTER the winner has already+ * been chosen using an INNER 80/20 split of TRAIN itself (so grid search+ * never peeks at the true held-out set β tuning isn't circular).+ *+ * @module services/distill-tuning+ */+import * as fs from 'fs';+import * as path from 'path';+import * as os from 'os';+import * as crypto from 'crypto';++import { runDistillation, type DistillOptions } from './memory-distillation.js';+import { distillTrajectoryContent } from '../memory/structured-distill.js';+import { cosineSim } from '../memory/hybrid-retrieval.js';++// ββ Public types βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++export type PromoteThreshold = 'execution-only' | 'execution+corroborated';++export interface TuningConfig {+ batchSize: number;+ dedupDistance: number;+ promoteThreshold: PromoteThreshold;+}++export interface ParamGrid {+ batchSize?: number[];+ dedupDistance?: number[];+ promoteThreshold?: PromoteThreshold[];+}++export interface TuningCandidate {+ config: TuningConfig;+ /** MRR@10 on the inner train-query split (never the true held-out set). */+ trainScore: number;+ trainRecallAt10: number;+ trainQueryCount: number;+ patternCount: number;+ promotedCount: number;+ distillMs: number;+ /** Present iff M1 itself skipped this run (corrupt DB, missing tables, ...). */+ skipped?: string;+}++export interface HeldOutScore {+ mrrAt10: number;+ recallAt10: number;+ queryCount: number;+ /** Same held-out query set scored against raw (undistilled) train entries. */+ baselineMrrAt10: number;+ baselineRecallAt10: number;+}++export interface TuningProvenance {+ gridSize: number;+ corpusSize: number;+ trainSize: number;+ heldOutSize: number;+ metric: 'mrr@10';+ /** Stamped from `options.now` (or the orchestrator's own Date.now() at the+ * I/O boundary) β never read from inside pure scoring logic. */+ tunedAt: number;+ sourceDbPath: string;+ sourceChecksumSha256: string;+}++export interface TuningReport {+ candidates: TuningCandidate[];+ winner: TuningCandidate;+ heldOut: HeldOutScore;+ /** True when held-out MRR@10 is >20% worse (relative) than the winner's train score. */+ overfit: boolean;+ provenance: TuningProvenance;+}++export interface TuneDistillationOptions {+ /** Source DB β read (copied + hashed) only; NEVER opened with a DB connection. */+ dbPath: string;+ grid?: ParamGrid;+ /** Namespaces to distill / include in the raw baseline pool (default: all). */+ namespaces?: string[];+ /** Outer train/held-out split fraction (default 0.8). */+ trainFraction?: number;+ /** Namespaces the query set is drawn from (default: feedback + commands). */+ queryNamespaces?: string[];+ topK?: number;+ /** Timestamp stamped into `provenance.tunedAt`. Caller-supplied so the core+ * logic stays a pure function of its inputs; defaults to `Date.now()` at+ * this I/O boundary if omitted. */+ now?: number;+ tmpDir?: string;+ verbose?: boolean;+}++export interface TimeSplit {+ totalRows: number;+ trainBoundaryRowid: number;+ trainRowids: number[];+ heldOutRowids: number[];+}++export interface TunedConfigFile {+ batchSize: number;+ dedupDistance: number;+ promoteThreshold: PromoteThreshold;+ provenance: TuningProvenance & {+ winnerTrainScore: number;+ heldOutScore: number;+ baselineHeldOutScore: number;+ overfit: boolean;+ };+}++// ββ Grid defaults (requirement 1) βββββββββββββββββββββββββββββββββββββββ++export const DEFAULT_GRID_BATCH_SIZE = [100, 200, 500];+export const DEFAULT_GRID_DEDUP_DISTANCE = [0.05, 0.1, 0.15, 0.2, 0.3];+export const DEFAULT_GRID_PROMOTE_THRESHOLD: PromoteThreshold[] = [+ 'execution-only',+ 'execution+corroborated',+];+const DEFAULT_TOP_K = 10;+const DEFAULT_TRAIN_FRACTION = 0.8;+const DEFAULT_QUERY_NAMESPACES = ['feedback', 'commands'];+/** Minimum corroborating uses for a proxy:structural pattern to promote under+ * 'execution+corroborated' β multiple near-duplicate entries clustering into+ * one pattern is treated as weak corroboration (still not oracle ground+ * truth; ADR-171 discipline is preserved by keeping this a distinct,+ * visibly-named policy rather than silently loosening the default gate). */+const CORROBORATION_MIN_USES = 2;+/** Caps the raw-baseline candidate pool so scoring stays fast on large corpora. */+const MAX_BASELINE_INDEX_SIZE = 3000;++// ββ Internal shapes βββββββββββββββββββββββββββββββββββββββββββββββββββββ++interface QueryEntry {+ id: string;+ namespace: string;+ embedding: number[];+ labels: string[];+ paths: string[];+}++interface PatternIndexEntry {+ id: number;+ embedding: number[];+ labels: string[];+ paths: string[];+}++interface CandidateEvalResult {+ mrrAtK: number;+ recallAtK: number;+ queryCount: number;+ patternCount: number;+ promotedCount: number;+ distillMs: number;+ skipped?: string;+}++// ββ Public entry point βββββββββββββββββββββββββββββββββββββββββββββββββββ++/**+ * Grid-search the distillation config against isolated copies of `dbPath`,+ * scored on a held-out split. See module header for the full methodology.+ */+export async function tuneDistillation(options: TuneDistillationOptions): Promise<TuningReport> {+ const {+ dbPath,+ grid = {},+ namespaces,+ trainFraction = DEFAULT_TRAIN_FRACTION,+ queryNamespaces = DEFAULT_QUERY_NAMESPACES,+ topK = DEFAULT_TOP_K,+ now,+ tmpDir = os.tmpdir(),+ verbose = false,+ } = options;++ if (!dbPath || !fs.existsSync(dbPath)) {+ throw new Error(`tuneDistillation: source db not found at ${dbPath}`);+ }++ const Database = await loadBetterSqlite3();+ if (!Database) {+ throw new Error('tuneDistillation: better-sqlite3 unavailable β cannot run the tuning harness');+ }++ const sourceChecksumBefore = sha256File(dbPath);++ const batchSizes = grid.batchSize ?? DEFAULT_GRID_BATCH_SIZE;+ const dedupDistances = grid.dedupDistance ?? DEFAULT_GRID_DEDUP_DISTANCE;+ const promoteThresholds = grid.promoteThreshold ?? DEFAULT_GRID_PROMOTE_THRESHOLD;+ const configs: TuningConfig[] = [];+ for (const batchSize of batchSizes) {+ for (const dedupDistance of dedupDistances) {+ for (const promoteThreshold of promoteThresholds) {+ configs.push({ batchSize, dedupDistance, promoteThreshold });+ }+ }+ }+ if (configs.length === 0) {+ throw new Error('tuneDistillation: empty grid β supply at least one value per grid axis');+ }++ // ββ Splits + query sets: a dedicated read-only copy, never the source itself ββ+ const readCopy = copyToTemp(dbPath, tmpDir, 'split-read');+ let outerSplit: TimeSplit;+ let innerSplit: TimeSplit;+ let trainQuerySet: QueryEntry[];+ let heldOutQuerySet: QueryEntry[];+ let heldOutBaselineIndex: PatternIndexEntry[];+ try {+ const readDb = new Database(readCopy, { readonly: true });+ try {+ outerSplit = computeTimeSplit(readDb, trainFraction);+ assertDisjoint(outerSplit.trainRowids, outerSplit.heldOutRowids);++ innerSplit = computeTimeSplit(readDb, trainFraction, {+ extraWhere: `rowid <= ${outerSplit.trainBoundaryRowid}`,+ });+ assertDisjoint(innerSplit.trainRowids, innerSplit.heldOutRowids);++ trainQuerySet = buildQuerySet(readDb, {+ loRowid: innerSplit.trainBoundaryRowid,+ hiRowid: outerSplit.trainBoundaryRowid,+ namespaces: queryNamespaces,+ });+ heldOutQuerySet = buildQuerySet(readDb, {+ loRowid: outerSplit.trainBoundaryRowid,+ hiRowid: Infinity,+ namespaces: queryNamespaces,+ });+ heldOutBaselineIndex = buildRawIndex(readDb, {+ loRowid: 0,+ hiRowid: outerSplit.trainBoundaryRowid,+ namespaces,+ });+ } finally {+ readDb.close();+ }+ } finally {+ safeUnlink(readCopy);+ }++ // ββ Grid search: TRAIN-internal scoring only β never touches heldOutQuerySet ββ+ const candidates: TuningCandidate[] = [];+ for (const config of configs) {+ if (verbose) console.log(`tuneDistillation: evaluating ${JSON.stringify(config)}`);+ const result = await evaluateCandidate({+ Database,+ sourceDbPath: dbPath,+ tmpDir,+ config,+ fitBoundaryRowid: innerSplit.trainBoundaryRowid,+ namespaces,+ querySet: trainQuerySet,+ topK,+ });+ candidates.push({+ config,+ trainScore: result.mrrAtK,+ trainRecallAt10: result.recallAtK,+ trainQueryCount: result.queryCount,+ patternCount: result.patternCount,+ promotedCount: result.promotedCount,+ distillMs: result.distillMs,+ ...(result.skipped ? { skipped: result.skipped } : {}),+ });+ }++ const scored = candidates.filter((c) => !c.skipped);+ if (scored.length === 0) {+ throw new Error('tuneDistillation: every grid candidate was skipped β see candidates[].skipped');+ }+ const winner = scored.reduce((best, c) => (c.trainScore > best.trainScore ? c : best), scored[0]);++ // ββ Held-out: score the winner ONCE, refit on the FULL outer train partition ββ+ const winnerFull = await evaluateCandidate({+ Database,+ sourceDbPath: dbPath,+ tmpDir,+ config: winner.config,+ fitBoundaryRowid: outerSplit.trainBoundaryRowid,+ namespaces,+ querySet: heldOutQuerySet,+ topK,+ });+ const baseline = scoreQuerySet(heldOutBaselineIndex, heldOutQuerySet, topK);++ const heldOut: HeldOutScore = {+ mrrAt10: winnerFull.mrrAtK,+ recallAt10: winnerFull.recallAtK,+ queryCount: winnerFull.queryCount,+ baselineMrrAt10: baseline.mrrAtK,+ baselineRecallAt10: baseline.recallAtK,+ };+ // Overfit: held-out MRR is more than 20% (relative) worse than the winner's+ // own train score. Guard divide-by-zero β a zero train score can't overfit.+ const overfit = winner.trainScore > 0 && heldOut.mrrAt10 < winner.trainScore * 0.8;++ const sourceChecksumAfter = sha256File(dbPath);+ if (sourceChecksumAfter !== sourceChecksumBefore) {+ // This must be structurally impossible (dbPath is never opened with a DB+ // connection anywhere above) β a mismatch means an invariant was broken.+ throw new Error('tuneDistillation: source DB checksum changed during tuning β refusing to report a result');+ }++ return {+ candidates,+ winner,+ heldOut,+ overfit,+ provenance: {+ gridSize: configs.length,+ corpusSize: outerSplit.totalRows,+ trainSize: outerSplit.trainRowids.length,+ heldOutSize: outerSplit.heldOutRowids.length,+ metric: 'mrr@10',+ tunedAt: now ?? Date.now(),+ sourceDbPath: dbPath,+ sourceChecksumSha256: sourceChecksumAfter,+ },+ };+}++// ββ Persisted config artifact (requirement 6) ββββββββββββββββββββββββββββ++/** Shape the winning config + provenance for persistence. Pure β no I/O. */+export function buildTunedConfigFile(report: TuningReport): TunedConfigFile {+ return {+ batchSize: report.winner.config.batchSize,+ dedupDistance: report.winner.config.dedupDistance,+ promoteThreshold: report.winner.config.promoteThreshold,+ provenance: {+ ...report.provenance,+ winnerTrainScore: report.winner.trainScore,+ heldOutScore: report.heldOut.mrrAt10,+ baselineHeldOutScore: report.heldOut.baselineMrrAt10,+ overfit: report.overfit,+ },+ };+}++/** Write the winning config to disk. Caller decides whether/where to call this. */+export function writeTunedConfigFile(report: TuningReport, filePath: string): void {+ const dir = path.dirname(filePath);+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });+ fs.writeFileSync(filePath, JSON.stringify(buildTunedConfigFile(report), null, 2));+}++/** Where the tuned config lives by default, for daemon/CLI callers. */+export function defaultTunedConfigPath(cwd: string = process.cwd()): string {+ return path.join(cwd, '.claude-flow', 'distill-tuned.json');+}++// ββ Time-based split βββββββββββββββββββββββββββββββββββββββββββββββββββββ++/**+ * Split a table's rows by rowid (a monotonic proxy for insertion time) into+ * an earliest `trainFraction` chunk and a most-recent remainder. Pure given a+ * fixed db snapshot. `table`/`extraWhere` are only ever called with internal+ * literal strings (never external input) β not a SQL-injection surface.+ */+export function computeTimeSplit(+ db: unknown,+ trainFraction: number,+ opts: { table?: string; extraWhere?: string } = {},+): TimeSplit {+ const table = opts.table ?? 'memory_entries';+ const whereParts = ['embedding IS NOT NULL'];+ if (opts.extraWhere) whereParts.push(`(${opts.extraWhere})`);+ const where = `WHERE ${whereParts.join(' AND ')}`;+ const rows = (db as any)+ .prepare(`SELECT rowid AS rowid FROM ${table} ${where} ORDER BY rowid`)+ .all() as Array<{ rowid: number }>;+ const total = rows.length;+ if (total === 0) return { totalRows: 0, trainBoundaryRowid: 0, trainRowids: [], heldOutRowids: [] };++ const trainCount = Math.min(total, Math.max(1, Math.floor(total * trainFraction)));+ const trainBoundaryRowid = rows[trainCount - 1].rowid;+ const trainRowids: number[] = [];+ const heldOutRowids: number[] = [];+ for (const r of rows) {+ if (r.rowid <= trainBoundaryRowid) trainRowids.push(r.rowid);+ else heldOutRowids.push(r.rowid);+ }+ return { totalRows: total, trainBoundaryRowid, trainRowids, heldOutRowids };+}++function assertDisjoint(a: number[], b: number[]): void {+ const setA = new Set(a);+ for (const x of b) {+ if (setA.has(x)) {+ throw new Error(`tuneDistillation: train/held-out partitions are not disjoint (rowid ${x} in both)`);+ }+ }+}++// ββ Query set + baseline index construction βββββββββββββββββββββββββββββ++function buildQuerySet(+ db: any,+ opts: { loRowid: number; hiRowid: number; namespaces: string[] },+): QueryEntry[] {+ const { loRowid, hiRowid, namespaces } = opts;+ if (namespaces.length === 0) return [];+ const placeholders = namespaces.map(() => '?').join(',');+ const hiFinite = Number.isFinite(hiRowid);+ const sql = `SELECT rowid, id, namespace, content, embedding FROM memory_entries+ WHERE rowid > ? ${hiFinite ? 'AND rowid <= ?' : ''} AND embedding IS NOT NULL+ AND COALESCE(namespace,'default') IN (${placeholders})+ ORDER BY rowid`;+ const args = hiFinite ? [loRowid, hiRowid, ...namespaces] : [loRowid, ...namespaces];+ const rows = db.prepare(sql).all(...args) as Array<{+ rowid: number; id: string; namespace: string; content: string; embedding: string;+ }>;+ const out: QueryEntry[] = [];+ for (const r of rows) {+ const embedding = parseEmbeddingJson(r.embedding);+ if (!embedding) continue;+ const distilled = distillTrajectoryContent(String(r.content ?? ''));+ out.push({ id: r.id, namespace: r.namespace, embedding, labels: distilled.labels, paths: distilled.paths });+ }+ return out;+}++function buildRawIndex(+ db: any,+ opts: { loRowid: number; hiRowid: number; namespaces?: string[] },+): PatternIndexEntry[] {+ const { loRowid, hiRowid, namespaces } = opts;+ let sql = 'SELECT rowid, content, embedding FROM memory_entries WHERE rowid > ? AND rowid <= ? AND embedding IS NOT NULL';+ const args: unknown[] = [loRowid, hiRowid];+ if (namespaces && namespaces.length) {+ sql += ` AND COALESCE(namespace,'default') IN (${namespaces.map(() => '?').join(',')})`;+ args.push(...namespaces);+ }+ sql += ' ORDER BY rowid';+ const rows = db.prepare(sql).all(...args) as Array<{ rowid: number; content: string; embedding: string }>;+ const sampled = sampleCap(rows, MAX_BASELINE_INDEX_SIZE);+ const out: PatternIndexEntry[] = [];+ for (const r of sampled) {+ const embedding = parseEmbeddingJson(r.embedding);+ if (!embedding) continue;+ const distilled = distillTrajectoryContent(String(r.content ?? ''));+ out.push({ id: -1, embedding, labels: distilled.labels, paths: distilled.paths });+ }+ return out;+}++/** Evenly-spaced sample so large corpora stay fast without biasing toward one end. */+function sampleCap<T>(rows: T[], cap: number): T[] {+ if (rows.length <= cap) return rows;+ const stride = rows.length / cap;+ const out: T[] = [];+ for (let i = 0; i < cap; i++) out.push(rows[Math.floor(i * stride)]);+ return out;+}++function parseEmbeddingJson(raw: unknown): number[] | null {+ if (typeof raw !== 'string' || !raw) return null;+ try {+ const v = JSON.parse(raw);+ return Array.isArray(v) ? v : null;+ } catch {+ return null;+ }+}++// ββ Candidate evaluation (one isolated temp copy per call) ββββββββββββββ++async function evaluateCandidate(params: {+ Database: any;+ sourceDbPath: string;+ tmpDir: string;+ config: TuningConfig;+ /** Rows with rowid <= this are visible to distillation on the copy. */+ fitBoundaryRowid: number;+ namespaces?: string[];+ querySet: QueryEntry[];+ topK: number;+}): Promise<CandidateEvalResult> {+ const { Database, sourceDbPath, tmpDir, config, fitBoundaryRowid, namespaces, querySet, topK } = params;+ const label = `cand-${config.batchSize}-${config.dedupDistance}-${config.promoteThreshold.replace(/\W+/g, '_')}`;+ const tmpCopy = copyToTemp(sourceDbPath, tmpDir, label);+ try {+ // Reset any pre-existing distilled state on the COPY (the real+ // .swarm/memory.db already carries real reasoning_patterns/episodes/+ // distill_state from M1's own runs β without this reset every candidate's+ // cursor would already be at the tail and "process" zero rows, silently+ // scoring the CURRENT production config instead of the candidate's own).+ // Then trim to the fit partition. Both on the isolated copy only.+ const prep = new Database(tmpCopy);+ try {+ resetDistillationState(prep);+ prep.prepare('DELETE FROM memory_entries WHERE rowid > ?').run(fitBoundaryRowid);+ } finally {+ prep.close();+ }++ const t0 = Date.now();+ const distillOpts: DistillOptions = {+ dbPath: tmpCopy,+ namespaces,+ batchSize: config.batchSize,+ dedupDistance: config.dedupDistance,+ dryRun: false,+ judge: 'structural',+ };+ const report = await runDistillation(distillOpts);+ const distillMs = Date.now() - t0;+ if (report.skipped) {+ return { mrrAtK: 0, recallAtK: 0, queryCount: querySet.length, patternCount: 0, promotedCount: 0, distillMs, skipped: report.skipped };+ }++ const scoreDb = new Database(tmpCopy);+ let index: PatternIndexEntry[];+ let patternCount: number;+ try {+ if (config.promoteThreshold === 'execution+corroborated') {+ applyCorroboratedPromotion(scoreDb);+ }+ index = loadPromotedPatternIndex(scoreDb);+ patternCount = (scoreDb.prepare('SELECT COUNT(*) AS c FROM reasoning_patterns').get() as { c: number }).c;+ } finally {+ scoreDb.close();+ }++ const { mrrAtK, recallAtK } = scoreQuerySet(index, querySet, topK);+ return { mrrAtK, recallAtK, queryCount: querySet.length, patternCount, promotedCount: index.length, distillMs };+ } finally {+ safeUnlink(tmpCopy);+ }+}++function resetDistillationState(db: any): void {+ const tableExists = (name: string): boolean =>+ ((db.prepare("SELECT COUNT(*) AS c FROM sqlite_master WHERE type='table' AND name=?").get(name) as { c: number } | undefined)?.c ?? 0) > 0;+ for (const t of ['distill_state', 'causal_edges', 'pattern_embeddings', 'reasoning_patterns', 'episodes']) {+ if (tableExists(t)) db.exec(`DELETE FROM ${t}`);+ }+}++function applyCorroboratedPromotion(db: any): void {+ db.prepare(+ `UPDATE reasoning_patterns SET metadata = json_set(metadata, '$.promoted', 1)+ WHERE json_extract(metadata, '$.provenance') = 'proxy:structural' AND uses >= ?`,+ ).run(CORROBORATION_MIN_USES);+}++// ββ Scoring (MRR@K / recall@K, shared by candidate + baseline paths) ββββ++function scoreQuerySet(+ index: PatternIndexEntry[],+ queries: QueryEntry[],+ topK: number,+): { mrrAtK: number; recallAtK: number } {+ if (queries.length === 0 || index.length === 0) return { mrrAtK: 0, recallAtK: 0 };+ let mrrSum = 0;+ let recallHits = 0;+ for (const q of queries) {+ const ranked = index+ .map((p) => ({ p, sim: cosineSim(q.embedding, p.embedding) }))+ .sort((a, b) => b.sim - a.sim)+ .slice(0, topK);+ let firstCorrectRank = -1;+ for (let i = 0; i < ranked.length; i++) {+ if (isTopicallyCorrect(q, ranked[i].p)) {+ firstCorrectRank = i + 1;+ break;+ }+ }+ if (firstCorrectRank > 0) {+ mrrSum += 1 / firstCorrectRank;+ recallHits += 1;+ }+ }+ return { mrrAtK: mrrSum / queries.length, recallAtK: recallHits / queries.length };+}++/** Proxy for "topically correct": shares at least one label or path with the query. */+function isTopicallyCorrect(q: QueryEntry, p: { labels: string[]; paths: string[] }): boolean {+ if (p.labels.some((l) => q.labels.includes(l))) return true;+ if (p.paths.some((pp) => q.paths.includes(pp))) return true;+ return false;+}++// ββ pattern_embeddings BLOB β number[] βββββββββββββββββββββββββββββββββββ++function loadPromotedPatternIndex(db: any): PatternIndexEntry[] {+ const rows = db+ .prepare(+ `SELECT rp.id AS id, rp.tags AS tags, rp.metadata AS metadata, pe.embedding AS embedding+ FROM reasoning_patterns rp+ JOIN pattern_embeddings pe ON pe.pattern_id = rp.id+ WHERE json_extract(rp.metadata, '$.promoted') = 1`,+ )+ .all() as Array<{ id: number; tags: string; metadata: string; embedding: Buffer }>;+ return rows.map((r) => {+ let labels: string[] = [];+ try {+ const t = JSON.parse(r.tags ?? '[]');+ if (Array.isArray(t)) labels = t;+ } catch {+ /* not JSON β no labels */+ }+ let paths: string[] = [];+ try {+ const m = JSON.parse(r.metadata ?? '{}');+ if (Array.isArray(m.paths)) paths = m.paths;+ } catch {+ /* not JSON β no paths */+ }+ return { id: r.id, embedding: bufferToFloat32Array(r.embedding), labels, paths };+ });+}++/**+ * Copy a BLOB Buffer's bytes into a fresh, 4-byte-aligned ArrayBuffer before+ * viewing it as Float32Array β better-sqlite3 BLOB buffers aren't guaranteed+ * to start at a 4-byte-aligned offset within their backing ArrayBuffer, and+ * the Float32Array constructor throws on misaligned views.+ */+function bufferToFloat32Array(buf: Buffer): number[] {+ const floatCount = Math.floor(buf.byteLength / 4);+ const aligned = new ArrayBuffer(floatCount * 4);+ new Uint8Array(aligned).set(buf.subarray(0, floatCount * 4));+ return Array.from(new Float32Array(aligned));+}++// ββ fs / hashing / better-sqlite3 loading helpers ββββββββββββββββββββββββ++function sha256File(p: string): string {+ return crypto.createHash('sha256').update(fs.readFileSync(p)).digest('hex');+}++function copyToTemp(sourcePath: string, tmpDir: string, label: string): string {+ if (!fs.existsSync(tmpDir)) fs.mkdirSync(tmpDir, { recursive: true });+ const unique = crypto.randomBytes(6).toString('hex');+ const dest = path.join(tmpDir, `distill-tune-${label}-${unique}.db`);+ fs.copyFileSync(sourcePath, dest);+ return dest;+}++function safeUnlink(p: string): void {+ for (const suffix of ['', '-wal', '-shm', '-journal']) {+ try {+ fs.unlinkSync(p + suffix);+ } catch {+ /* already gone / never created */+ }+ }+}++async function loadBetterSqlite3(): Promise<any | null> {+ try {+ const mod: string = 'better-sqlite3';+ return (await import(mod)).default;+ } catch {+ return null;+ }+}diff --git a/v3/@claude-flow/cli/src/services/memory-distillation.ts b/v3/@claude-flow/cli/src/services/memory-distillation.tsnew file mode 100644index 0000000000..97a9a94c26--- /dev/null+++ b/v3/@claude-flow/cli/src/services/memory-distillation.ts@@ -0,0 +1,349 @@+/**+ * Memory Distillation Service (ADR-174)+ *+ * Turns raw `memory_entries` (what ruflo has been RECORDING for thousands of+ * commits) into the structured intelligence substrate it has never populated:+ * `episodes` β `reasoning_patterns` (+ `pattern_embeddings`) β `causal_edges`.+ * This is the DISTILL/CONSOLIDATE half of the RETRIEVEβJUDGEβDISTILLβCONSOLIDATE+ * pipeline; RETRIEVE (embeddings) was already populated, the rest was empty+ * because the daemon's `consolidate` worker was a stub (see ADR-174 root cause).+ *+ * Design invariants (load-bearing):+ * - $0 by default: reuses the deterministic structural extractor+ * (structured-distill.ts) and the embeddings ALREADY on each row β no LLM+ * call, no new embedding work, unless a caller explicitly opts into a judge.+ * - Incremental: a `distill_state` cursor (per namespace, by monotonic rowid)+ * means a run never rescans processed rows.+ * - Non-destructive: NEVER mutates or deletes `memory_entries`; only inserts+ * into the (previously empty) target tables. Writes are per-batch+ * transactions β a failure rolls back the batch and advances no cursor.+ * - Safe on a recovered DB: quick_check gate before any write; skips (not+ * throws) on corruption; better-sqlite3 optional (silent no-op if absent).+ * - Provenance discipline (ADR-171): `feedback` outcomes are execution-tier+ * ground truth; everything else is proxy. Proxy-tier patterns are written+ * but never `promoted` β visible for audit, excluded from promoted recall.+ */+import * as fs from 'fs';+import * as path from 'path';++import { distillTrajectoryContent, serialiseDistilled } from '../memory/structured-distill.js';++export type DistillProvenance = 'oracle:test-exec' | 'judge:fable' | 'proxy:structural';++export interface DistillOptions {+ dbPath: string;+ /** Restrict to these namespaces (default: all namespaces with embeddings). */+ namespaces?: string[];+ /** Rows per transaction (default 200). */+ batchSize?: number;+ /** Hard cap on rows processed this invocation (default: unbounded within a run). */+ maxEntries?: number;+ /** Cosine distance below which two entries collapse into one pattern (default 0.2, the ADR-174 M4-tuned platform default: ~37% fewer patterns, retrieval-neutral). */+ dedupDistance?: number;+ /** Report counts, write nothing (default false). */+ dryRun?: boolean;+ /** Judge tier. Only 'structural' ($0) is implemented here; 'fable' is reserved (ADR-172). */+ judge?: 'structural' | 'fable';+ /** Ignore the cursor and re-scan from this rowid (default: cursor-driven). */+ sinceRowid?: number;+ verbose?: boolean;+}++export interface DistillReport {+ processed: number;+ episodes: number;+ patterns: number;+ patternEmbeddings: number;+ causalEdges: number;+ promoted: number;+ byProvenance: Record<string, number>;+ namespaces: string[];+ dryRun: boolean;+ spendUsd: number;+ corrupt?: boolean;+ skipped?: string;+}++interface SourceRow {+ rowid: number;+ id: string;+ namespace: string;+ content: string;+ embedding: number[] | null;+}++interface Cluster {+ rep: SourceRow;+ members: SourceRow[];+ successCount: number;+ provenance: DistillProvenance;+}++function emptyReport(dryRun: boolean, extra: Partial<DistillReport> = {}): DistillReport {+ return {+ processed: 0, episodes: 0, patterns: 0, patternEmbeddings: 0, causalEdges: 0,+ promoted: 0, byProvenance: {}, namespaces: [], dryRun, spendUsd: 0, ...extra,+ };+}++function parseEmbedding(raw: unknown): number[] | null {+ if (typeof raw !== 'string' || !raw) return null;+ try { const v = JSON.parse(raw); return Array.isArray(v) ? v : null; } catch { return null; }+}++function cosine(a: number[], b: number[]): number {+ const len = Math.min(a.length, b.length);+ let dot = 0, na = 0, nb = 0;+ for (let i = 0; i < len; i++) { dot += a[i] * b[i]; na += a[i] * a[i]; nb += b[i] * b[i]; }+ const mag = Math.sqrt(na * nb);+ return mag === 0 ? 0 : dot / mag;+}++/**+ * Best-effort success/reward extraction for a `feedback` outcome record. These+ * are recorded post-edit outcomes β execution-observed ground truth (ADR-171+ * execution tier), not a proxy guess.+ */+function judgeFeedback(content: string): { success: boolean; reward: number } {+ try {+ const o = JSON.parse(content);+ if (typeof o.success === 'boolean') return { success: o.success, reward: o.success ? 1 : 0 };+ if (typeof o.outcome === 'string') { const ok = /success|pass|ok|true/i.test(o.outcome); return { success: ok, reward: ok ? 1 : 0 }; }+ if (typeof o.error === 'string' && o.error) return { success: false, reward: 0 };+ } catch { /* not JSON β treat as neutral */ }+ return { success: true, reward: 0.5 };+}++/**+ * Distill accumulated memory into the structured intelligence tables.+ * Incremental, $0, transactional, provenance-tagged.+ */+export async function runDistillation(options: DistillOptions): Promise<DistillReport> {+ const {+ dbPath, namespaces, batchSize = 200, maxEntries,+ dedupDistance = 0.2, dryRun = false, judge = 'structural',+ sinceRowid, verbose = false,+ } = options;++ if (judge === 'fable') {+ // ADR-172 cost gate: the LLM judge path is not enabled in this $0 service.+ return emptyReport(dryRun, { skipped: 'judge:fable requires the cost-bounded advisor path (ADR-172), not enabled here' });+ }+ if (!dbPath || !fs.existsSync(dbPath)) return emptyReport(dryRun, { skipped: 'no-db' });++ let Database: any;+ try {+ const mod: string = 'better-sqlite3';+ Database = (await import(mod)).default;+ } catch {+ return emptyReport(dryRun, { skipped: 'better-sqlite3 unavailable' });+ }++ const report = emptyReport(dryRun);+ let db: any;+ try {+ db = new Database(dbPath, { timeout: 3000 });++ const tableExists = (name: string): boolean =>+ (db.prepare("SELECT COUNT(*) AS c FROM sqlite_master WHERE type='table' AND name=?").get(name)?.c ?? 0) > 0;+ if (!tableExists('memory_entries')) { db.close(); return { ...report, skipped: 'no memory_entries' }; }+ for (const t of ['episodes', 'reasoning_patterns', 'pattern_embeddings', 'causal_edges']) {+ if (!tableExists(t)) { db.close(); return { ...report, skipped: `target table ${t} missing (agentdb schema not initialised)` }; }+ }++ // Safety gate: never distill into a structurally-corrupt DB.+ const qc = db.prepare('PRAGMA quick_check(1)').get() as Record<string, string> | undefined;+ if (qc && String(Object.values(qc)[0] ?? '').toLowerCase() !== 'ok') {+ db.close();+ return { ...report, corrupt: true, skipped: 'memory DB reports corruption β run recoverMemoryDatabase first' };+ }++ // M0: incremental cursor table (per namespace, by monotonic rowid).+ db.exec(`CREATE TABLE IF NOT EXISTS distill_state (+ namespace TEXT PRIMARY KEY,+ last_rowid INTEGER NOT NULL DEFAULT 0,+ last_run_at INTEGER+ )`);++ // Which namespaces to process.+ const nsAll = (db.prepare(+ "SELECT DISTINCT COALESCE(namespace,'default') AS ns FROM memory_entries WHERE embedding IS NOT NULL",+ ).all() as Array<{ ns: string }>).map(r => r.ns);+ const nsList = namespaces && namespaces.length ? nsAll.filter(n => namespaces.includes(n)) : nsAll;+ report.namespaces = nsList;++ const getCursor = db.prepare('SELECT last_rowid FROM distill_state WHERE namespace = ?');+ const setCursor = db.prepare(+ 'INSERT INTO distill_state (namespace, last_rowid, last_run_at) VALUES (?, ?, ?) ' ++ 'ON CONFLICT(namespace) DO UPDATE SET last_rowid = excluded.last_rowid, last_run_at = excluded.last_run_at',+ );++ const insEpisode = db.prepare(+ 'INSERT INTO episodes (session_id, task, input, output, reward, success, tags, metadata) VALUES (?,?,?,?,?,?,?,?)',+ );+ const insPattern = db.prepare(+ 'INSERT INTO reasoning_patterns (task_type, approach, success_rate, uses, avg_reward, tags, metadata) VALUES (?,?,?,?,?,?,?)',+ );+ const insPatEmb = db.prepare('INSERT OR REPLACE INTO pattern_embeddings (pattern_id, embedding) VALUES (?, ?)');+ const insEdge = db.prepare(+ 'INSERT INTO causal_edges (from_memory_id, from_memory_type, to_memory_id, to_memory_type, similarity, confidence, mechanism, metadata) VALUES (?,?,?,?,?,?,?,?)',+ );++ let remaining = typeof maxEntries === 'number' ? maxEntries : Infinity;++ for (const ns of nsList) {+ if (remaining <= 0) break;+ let cursor = typeof sinceRowid === 'number' ? sinceRowid : (getCursor.get(ns)?.last_rowid ?? 0);++ // Process this namespace in bounded batches until drained or cap hit.+ // eslint-disable-next-line no-constant-condition+ while (true) {+ if (remaining <= 0) break;+ const lim = Math.min(batchSize, remaining);+ const rows = db.prepare(+ "SELECT rowid AS rowid, id, COALESCE(namespace,'default') AS namespace, content, embedding " ++ 'FROM memory_entries WHERE embedding IS NOT NULL AND COALESCE(namespace,' + "'default'" + ') = ? AND rowid > ? ' ++ 'ORDER BY rowid LIMIT ?',+ ).all(ns, cursor, lim) as Array<{ rowid: number; id: string; namespace: string; content: string; embedding: string }>;+ if (rows.length === 0) break;++ const src: SourceRow[] = rows.map(r => ({+ rowid: r.rowid, id: r.id, namespace: r.namespace,+ content: String(r.content ?? ''), embedding: parseEmbedding(r.embedding),+ }));++ // Greedy cosine clustering within the batch (bounded n β O(nΒ²) is fine).+ const clusters: Cluster[] = [];+ for (const row of src) {+ let placed = false;+ if (row.embedding) {+ for (const cl of clusters) {+ if (cl.rep.embedding && cosine(row.embedding, cl.rep.embedding) >= 1 - dedupDistance) {+ cl.members.push(row);+ if (ns === 'feedback' && judgeFeedback(row.content).success) cl.successCount++;+ placed = true; break;+ }+ }+ }+ if (!placed) {+ const success = ns === 'feedback' ? judgeFeedback(row.content).success : false;+ clusters.push({+ rep: row, members: [row], successCount: success ? 1 : 0,+ provenance: ns === 'feedback' ? 'oracle:test-exec' : 'proxy:structural',+ });+ }+ }++ const maxRowid = Math.max(...src.map(r => r.rowid), cursor);++ // Embedding-coverage invariant: a cluster is only written if it has an+ // embeddable representative β reselect to any member with a valid+ // (parseable) vector; skip the cluster if none (unretrievable anyway).+ // Guarantees every reasoning_pattern has exactly one pattern_embedding.+ const embVecOf = (cl: Cluster): number[] | null =>+ cl.rep.embedding ?? cl.members.find(m => m.embedding)?.embedding ?? null;++ if (!dryRun) {+ const commit = db.transaction(() => {+ let prevEpId: number | null = null;+ for (const cl of clusters) {+ const embVec = embVecOf(cl);+ if (!embVec) continue; // no embeddable member β skip (keeps 1:1)++ const distilled = distillTrajectoryContent(cl.rep.content);+ const taskType = distilled.labels[0] ?? ns;+ const approach = distilled.summary || serialiseDistilled(distilled).slice(0, 200);+ const uses = cl.members.length;+ const successRate = cl.provenance === 'oracle:test-exec' ? cl.successCount / uses : 0;+ const avgReward = successRate; // structural: reward == success fraction+ const promoted = cl.provenance === 'oracle:test-exec'; // proxy NEVER promotes (ADR-171)+ const provMeta = {+ provenance: cl.provenance, provenance_tier: cl.provenance, promoted,+ sourceIds: cl.members.map(m => m.id).slice(0, 25),+ paths: distilled.paths.slice(0, 10), namespace: ns, distilledBy: 'structural',+ };++ const epInfo = insEpisode.run(+ `distill:${ns}`, approach, cl.rep.content.slice(0, 2000), '',+ avgReward, promoted && cl.successCount > 0 ? 1 : 0,+ JSON.stringify(distilled.labels), JSON.stringify(provMeta),+ );+ report.episodes++;++ const patInfo = insPattern.run(+ taskType, approach, successRate, uses, avgReward,+ JSON.stringify(distilled.labels), JSON.stringify(provMeta),+ );+ const patternId = Number(patInfo.lastInsertRowid);+ report.patterns++;+ report.byProvenance[cl.provenance] = (report.byProvenance[cl.provenance] ?? 0) + 1;+ if (promoted) report.promoted++;++ // pattern_embeddings: reuse the representative's existing 384-dim+ // vector as a Float32 BLOB β $0, no re-embedding. Guaranteed 1:1.+ insPatEmb.run(patternId, Buffer.from(Float32Array.from(embVec).buffer));+ report.patternEmbeddings++;++ // WEAK relational edge β NOT causal proof. Links to the actual+ // previous episode (not epId-1, which wrongly assumed consecutive+ // rowids). Explicitly typed co-occurrence / proxy-tier / non-+ // promoted: may rank retrieval, must NOT justify autonomous action+ // (ADR-174 edge contract).+ const epId = Number(epInfo.lastInsertRowid);+ if (prevEpId !== null) {+ insEdge.run(+ prevEpId, 'episode', epId, 'episode',+ 0, 0.3, 'co-occurrence',+ JSON.stringify({+ edge_type: 'cooccurrence',+ provenance_tier: 'proxy:structural',+ confidence: 0.3,+ promoted: false,+ namespace: ns,+ note: 'weak co-occurrence; may rank retrieval, must not justify autonomous action',+ }),+ );+ report.causalEdges++;+ }+ prevEpId = epId;+ }+ setCursor.run(ns, maxRowid, Date.now());+ });+ commit();+ } else {+ // dry-run accounting only β mirror the embeddable-cluster skip.+ for (const cl of clusters) {+ if (!embVecOf(cl)) continue;+ report.patterns++;+ report.episodes++;+ report.byProvenance[cl.provenance] = (report.byProvenance[cl.provenance] ?? 0) + 1;+ if (cl.provenance === 'oracle:test-exec') report.promoted++;+ }+ }++ report.processed += rows.length;+ remaining -= rows.length;+ cursor = maxRowid;+ if (rows.length < lim) break; // namespace drained+ }+ }++ db.close();+ if (verbose) {+ console.log(+ `distilled ${report.processed} entries β ${report.patterns} patterns ` ++ `(${report.promoted} promoted), ${report.episodes} episodes, ${report.causalEdges} edges` ++ (dryRun ? ' [dry-run]' : ''),+ );+ }+ } catch (e) {+ try { db?.close(); } catch { /* */ }+ return { ...report, skipped: `error: ${(e as Error)?.message ?? e}` };+ }+ return report;+}++/** Where the memory DB lives, for daemon/CLI callers. */+export function defaultMemoryDbPath(cwd: string = process.cwd()): string {+ return path.join(cwd, '.swarm', 'memory.db');+}diff --git a/v3/@claude-flow/cli/src/services/worker-daemon.ts b/v3/@claude-flow/cli/src/services/worker-daemon.tsindex b9f46d70be..bb4915810a 100644--- a/v3/@claude-flow/cli/src/services/worker-daemon.ts+++ b/v3/@claude-flow/cli/src/services/worker-daemon.ts@@ -6,7 +6,8 @@* - map: Codebase mapping (5 min interval)* - audit: Security analysis (10 min interval)* - optimize: Performance optimization (15 min interval)- * - consolidate: Memory consolidation (30 min interval)+ * - consolidate: Memory distillation β memory_entries -> episodes/reasoning_patterns/+ * causal_edges (30 min interval, ADR-174; RUFLO_DAEMON_NO_DISTILL=1 / --no-distill to skip)* - testgaps: Test coverage analysis (20 min interval)*/@@ -22,6 +23,12 @@ import {type HeadlessWorkerType,type HeadlessExecutionResult,} from './headless-worker-executor.js';+// ADR-174 M3: the consolidate worker below drives the real DISTILL/CONSOLIDATE+// pass instead of writing a hardcoded { patternsConsolidated: 0 } stub. The+// service itself is owned/frozen elsewhere (memory-distillation.ts) β it is+// incremental (rowid cursor), non-destructive, transactional, and+// quick_check-gated, so it's safe to call unconditionally on every tick.+import { runDistillation, defaultMemoryDbPath, type DistillReport } from './memory-distillation.js';// Worker types matching hooks-tools.tsexport type WorkerType =@@ -110,7 +117,7 @@ const DEFAULT_WORKERS: WorkerConfigInternal[] = [{ type: 'map', intervalMs: 15 * 60 * 1000, offsetMs: 0, priority: 'normal', description: 'Codebase mapping', enabled: true },{ type: 'audit', intervalMs: 10 * 60 * 1000, offsetMs: 2 * 60 * 1000, priority: 'critical', description: 'Security analysis', enabled: true },{ type: 'optimize', intervalMs: 15 * 60 * 1000, offsetMs: 4 * 60 * 1000, priority: 'high', description: 'Performance optimization', enabled: true },- { type: 'consolidate', intervalMs: 30 * 60 * 1000, offsetMs: 6 * 60 * 1000, priority: 'low', description: 'Memory consolidation', enabled: true },+ { type: 'consolidate', intervalMs: 30 * 60 * 1000, offsetMs: 6 * 60 * 1000, priority: 'low', description: 'Memory distillation (ADR-174)', enabled: true },{ type: 'testgaps', intervalMs: 20 * 60 * 1000, offsetMs: 8 * 60 * 1000, priority: 'normal', description: 'Test coverage analysis', enabled: true },{ type: 'predict', intervalMs: 10 * 60 * 1000, offsetMs: 0, priority: 'low', description: 'Predictive preloading', enabled: false },{ type: 'document', intervalMs: 60 * 60 * 1000, offsetMs: 0, priority: 'low', description: 'Auto-documentation', enabled: false },@@ -120,6 +127,29 @@ const DEFAULT_WORKERS: WorkerConfigInternal[] = [// Previously 5 min, which caused orphan processes when daemon timeout fired before executor timeout (#1117).const DEFAULT_WORKER_TIMEOUT_MS = 16 * 60 * 1000;+// ADR-174 M3: hard cap on rows the `consolidate` worker distills in a single+// tick. The distillation service is cursor-driven (per-namespace rowid) and+// batches in transactions of `batchSize`, so a capped `maxEntries` guarantees+// this worker returns well within DEFAULT_WORKER_TIMEOUT_MS even against a+// large backlog β the cursor just picks up where it left off next tick+// (every 30 min per DEFAULT_WORKERS), draining an arbitrarily large backlog+// over several ticks instead of blocking on one.+const CONSOLIDATE_MAX_ENTRIES_PER_TICK = 1000;+const CONSOLIDATE_BATCH_SIZE = 200;+// ADR-174 M5: platform-default distillation config, chosen by the M4 self-+// optimization grid-search (scripts/tune-distill.mjs) on the real ~7.9k-entry+// corpus. Winner: batchSize=200, dedupDistance=0.2 (held-out MRR@10 0.753 vs+// 0.749 baseline β measured on-par, not a large uplift; the payoff is the+// populated substrate + trainable model). Override per-run via `memory distill`.+const CONSOLIDATE_DEDUP_DISTANCE = 0.2;++// ADR-174 M3 opt-out: set to skip the real distillation pass entirely (e.g.+// constrained CI hosts, or a user who wants the daemon's other workers but+// not this one without touching persisted worker-enabled state). Mirrors the+// `--no-distill` flag on `daemon start` (see commands/daemon.ts), which sets+// this env var on the forked/foreground daemon process.+const NO_DISTILL_ENV = 'RUFLO_DAEMON_NO_DISTILL';+// #2356 β Self-terminating lifecycle defaults. A background daemon with no// upper bound on its lifetime runs until the box reboots; in the field this// leaked tens of thousands of headless `claude --print` sweeps over many days@@ -1440,8 +1470,27 @@ export class WorkerDaemon extends EventEmitter {return perf;}+ /**+ * ADR-174 M3: memory consolidation β runs the real DISTILL/CONSOLIDATE pass+ * (memory-distillation.ts) against `.swarm/memory.db`, turning raw+ * `memory_entries` into `episodes` / `reasoning_patterns` /+ * `pattern_embeddings` / `causal_edges`. Previously this wrote a hardcoded+ * `{ patternsConsolidated: 0 }` stub and touched no database β the root+ * cause of the intelligence tables staying empty.+ *+ * Kept as `runConsolidateWorker` / worker type `'consolidate'` for+ * back-compat with existing `-w consolidate` scripts and docs.+ *+ * Safety:+ * - Bounded via CONSOLIDATE_MAX_ENTRIES_PER_TICK so a large backlog can+ * never approach DEFAULT_WORKER_TIMEOUT_MS β the incremental cursor in+ * runDistillation() drains a bounded slice per tick and picks up where+ * it left off on the next scheduled run.+ * - runDistillation() never throws (it catches internally and returns+ * `{ skipped }` / `{ corrupt: true }`), but this worker still wraps the+ * call defensively β a background worker must never crash the daemon.+ */private async runConsolidateWorker(): Promise<unknown> {- // Memory consolidation - clean up old patternsconst consolidateFile = join(this.projectRoot, '.claude-flow', 'metrics', 'consolidation.json');const metricsDir = join(this.projectRoot, '.claude-flow', 'metrics');@@ -1449,11 +1498,76 @@ export class WorkerDaemon extends EventEmitter {mkdirSync(metricsDir, { recursive: true });}+ // Opt-out: RUFLO_DAEMON_NO_DISTILL=1 (or `daemon start --no-distill`)+ // skips the real distillation pass entirely without touching persisted+ // worker-enabled state (see also: `daemon enable -w consolidate --disable`,+ // which disables the worker's schedule altogether).+ if (process.env[NO_DISTILL_ENV] === '1') {+ const disabledResult = {+ timestamp: new Date().toISOString(),+ distillationEnabled: false,+ note: `Distillation disabled via ${NO_DISTILL_ENV}=1 / --no-distill`,+ patternsConsolidated: 0,+ memoryCleaned: 0,+ duplicatesRemoved: 0,+ };+ writeFileSync(consolidateFile, JSON.stringify(disabledResult, null, 2));+ return disabledResult;+ }++ let report: DistillReport;+ try {+ report = await runDistillation({+ dbPath: defaultMemoryDbPath(this.projectRoot),+ maxEntries: CONSOLIDATE_MAX_ENTRIES_PER_TICK,+ batchSize: CONSOLIDATE_BATCH_SIZE,+ dedupDistance: CONSOLIDATE_DEDUP_DISTANCE,+ });+ } catch (error) {+ // Defensive only β runDistillation() is internally try/catch'd and+ // should never reach here. A worker must never crash the daemon.+ const message = error instanceof Error ? error.message : String(error);+ this.log('warn', `Consolidate worker: distillation threw unexpectedly: ${message}`);+ const errorResult = {+ timestamp: new Date().toISOString(),+ distillationEnabled: true,+ error: message,+ patternsConsolidated: 0,+ memoryCleaned: 0,+ duplicatesRemoved: 0,+ };+ writeFileSync(consolidateFile, JSON.stringify(errorResult, null, 2));+ return errorResult;+ }++ if (report.corrupt) {+ this.log('warn', `Consolidate worker: memory DB reports corruption β ${report.skipped ?? 'skipped'}`);+ } else if (report.skipped) {+ this.log('info', `Consolidate worker: distillation skipped (${report.skipped})`);+ }+const result = {timestamp: new Date().toISOString(),- patternsConsolidated: 0,- memoryCleaned: 0,- duplicatesRemoved: 0,+ distillationEnabled: true,+ // Mapping onto the pre-existing metrics shape (ADR-174 M3):+ patternsConsolidated: report.patterns,+ // rows drained from the incremental cursor this tick β distillation is+ // non-destructive (never mutates/deletes memory_entries), so "cleaned"+ // here means "processed into the intelligence tables", not removed.+ memoryCleaned: report.processed,+ // clustering collapses near-duplicate entries into a single pattern+ // rather than deleting them; this is the count that got merged away+ // instead of becoming their own distinct pattern.+ duplicatesRemoved: Math.max(0, report.processed - report.patterns),+ episodes: report.episodes,+ patternEmbeddings: report.patternEmbeddings,+ causalEdges: report.causalEdges,+ promoted: report.promoted,+ byProvenance: report.byProvenance,+ namespaces: report.namespaces,+ dryRun: report.dryRun,+ corrupt: report.corrupt ?? false,+ skipped: report.skipped,};writeFileSync(consolidateFile, JSON.stringify(result, null, 2));diff --git a/v3/docs/adr/ADR-174-memory-distillation-self-optimization.md b/v3/docs/adr/ADR-174-memory-distillation-self-optimization.mdnew file mode 100644index 0000000000..31454bbca7--- /dev/null+++ b/v3/docs/adr/ADR-174-memory-distillation-self-optimization.md@@ -0,0 +1,193 @@+# ADR-174 β Memory Distillation & Self-Optimizing Learning Loop++- **Status:** Accepted β M0βM5 implemented + tested (pending merge of PR #2570)+- **Date:** 2026-07-04+- **Deciders:** ruflo core+- **Related:** [ADR-170](ADR-170-agenticow-substrate.md) (agenticow substrate), [ADR-171](ADR-171-provenance-tiered-oracle.md) (provenance-tiered oracle + promote-gate), [ADR-172](ADR-172-fable-advisor-harness.md) (Fable advisor, cost-bounded), [ADR-173](ADR-173-remote-gpu-distillation.md) (remote GPU weight distillation)++## Context++Ruflo has been **recording** to `.swarm/memory.db` `memory_entries` for thousands of commits β 7,900+ entries, 100% embedded (384-dim), across `commands` (6k), `feedback` (0.9k, post-edit outcome records), `session`, `cost-tracking`, `tasks`. But the structured intelligence substrate the RETRIEVEβJUDGEβDISTILLβCONSOLIDATE pipeline is supposed to build β `reasoning_patterns`, `pattern_embeddings`, `episodes`, `causal_edges`, `consolidated_memories` β was **completely empty (0 rows)**. Only RETRIEVE (the embeddings) was ever populated.++### Root cause (the load-bearing finding)++The daemon's `consolidate` background worker β scheduled every 30 minutes and `enabled: true` by default (`worker-daemon.ts` `DEFAULT_WORKERS`) β was a **stub**: `runConsolidateWorker()` (`worker-daemon.ts:1443`) wrote a hardcoded `{patternsConsolidated: 0, memoryCleaned: 0, duplicatesRemoved: 0}` to a metrics JSON file and touched no database. Meanwhile the on-demand bridge functions that DO reach the real controllers (`bridgeStorePattern`, `bridgeRecordCausalEdge`, `bridgeConsolidate`) were only ever invoked one entry at a time by MCP callers, never driven in bulk against the accumulated corpus. So 6,000+ commits of "self-learning" recorded everything and distilled nothing. The visible symptoms were `Vectors β0` (missing `vector_indexes`, fixed separately) and `π§ 0%` on the statusline (accurate β the intelligence substrate was empty).++There is also a structural gap: `reasoning_patterns`/`causal_edges` are populated by controllers that read from `episodes` (0 rows) β **not** from `memory_entries` directly. Nothing performed the `memory_entries β episodes` ETL.++## Decision++Build an incremental, **$0-default** memory distillation service that converts recorded `memory_entries` into auditable **episodes, patterns, embeddings, and explicitly weak relational edges**. The daemon runs it through the existing `consolidate` worker. Promotion is **provenance-gated**: only execution-observed feedback (or explicitly budgeted Fable judgments) can produce *promoted* patterns; structural patterns remain searchable but non-promoted. Configuration is tuned against a held-out split by ruflo's own search tooling, and the winner is promoted as the platform default **only if it satisfies the promotion rule below** (retrieval-neutral + measurable secondary gain).++Named `memory distill β¦` β deliberately **not** `neural distill β¦`, which already exists as the GPU/LoRA **weight** distillation pipeline (ADR-150/173, weight-eft). Two unrelated "distill" surfaces must not collide.++### How it works++- **RETRIEVE** β reuse the embeddings already on every row (no re-embedding, $0).+- **JUDGE** β `feedback` entries are recorded post-edit outcomes = execution-observed ground truth β `oracle:test-exec` tier. Everything else β `proxy:structural`. (`judge:fable` is reserved for the explicitly opt-in, cost-bounded LLM path per ADR-172 β not enabled in the $0 default.)+- **DISTILL** β reuse the deterministic sub-millisecond extractor `structured-distill.ts` (`distillTrajectoryContent` β `{summary, detail, labels, paths}`); greedily cluster near-duplicate entries by cosine distance so N near-identical logs collapse into one pattern with `uses` = cluster size.+- **CONSOLIDATE** β write `episodes`, `reasoning_patterns`, `pattern_embeddings` (reusing the representative's existing vector as a Float32 BLOB; guaranteed **1:1** β a cluster with no parseable vector is skipped, never producing an embedding-less pattern), and **weak relational edges** (see below).+- **Promote gate (ADR-171)** β a pattern is `promoted` only if its tier is `oracle:test-exec` (or `judge:fable`). `proxy:structural` patterns are written but **never** promoted β visible for audit, excluded from promoted recall. Enforced in code, not just prose.++### Relational edges are NOT causal proof (high-risk naming)++The `causal_edges` table name is a schema-compatibility artifact (agentdb owns it) and **overclaims** what this service writes. We emit **weak co-occurrence** edges, not established causation. To prevent downstream systems from treating them as causal proof, every edge carries an explicit contract in its metadata:++```+edge_type = cooccurrence (never temporal_precedes / intervention_observed here)+provenance_tier = proxy:structural+confidence = 0.3 (weak; never asserted as proof)+promoted = false+```++**Rule (enforced):** proxy co-occurrence edges **may rank retrieval** but **may not justify autonomous action**. Only an `intervention_observed`/oracle-backed edge (a future tier, produced by the doubly-robust `NightlyLearner` path, not by this structural service) could be `promoted`. This is the single biggest future failure mode β a memory system emitting plausible-but-false causal explanations β and the contract exists to foreclose it.++### Safety (the DB was just recovered from corruption)++- **Incremental** via a `distill_state` cursor (per namespace, by monotonic `rowid`) β never rescans processed rows.+- **Non-destructive** β never mutates or deletes `memory_entries`; only inserts into the previously-empty target tables.+- **Transactional** per batch β a failure rolls back the batch and advances no cursor.+- **quick_check gate** before any write β skips (does not throw) on a corrupt DB, deferring to `recoverMemoryDatabase`.+- **better-sqlite3 optional** β silent no-op if the native module is absent (WASM-only hosts).++## Parameter surface (alternative usage scenarios)++`memory distill run|status|config|tune` with:++| Flag | Default | Purpose |+|---|---|---|+| `--mode` | `dry-run` first / `continuous` in daemon | `dry-run \| one-shot \| continuous` |+| `--budget-usd` | `0` | `0` = offline structural ($0). `>0` unlocks the cost-capped Fable judge (ADR-172) |+| `--judge` | `structural` | `structural \| fable`; `fable` requires `--budget-usd > 0` |+| `--namespace` | all | comma-separated scope (e.g. `feedback,commands`) |+| `--batch-size` | 200 (tuned by M4) | rows per transaction |+| `--dedup-distance` | `0.2` | cosine distance for clustering; promoted after M4 tuning (see promotion rule) |+| `--consolidation-cadence` | 30m | daemon distill cadence |+| `--promote-threshold` | tier-based | min provenance tier that sets `promoted=true` |+| `--aggressive` / `--conservative` | conservative | preset bundles |+| `--since` | cursor-driven | override incremental start (re-backfill) |+| `--dry-run` | off in continuous | report counts, no writes |+| `--max-entries` | unbounded/run | per-invocation work cap |+| `--config <path>` | none | load the platform-default JSON config |++## Self-optimization (ruflo tuning ruflo β Milestone 4)++Objective metric (computed $0, offline): retrieval (MRR@10 / recall@10 of pattern search on a held-out query set derived from held-out `feedback`/`command` entries) vs. the raw-`memory_entries` baseline, plus secondary metrics (pattern-count compression, latency) and a proxy-promotion-violation guard. Time-based train/held-out split (earliest ~80% tune, most-recent ~20% scored once) so tuning isn't circular. Grid searched via `metaharness_evolve` (MAP-Elites) with a plain grid-search fallback β both $0, both real. Search runs only against **isolated copies**, never the live/daemon-attached DB.++### Promotion rule for a tuned default (honest framing)++A tuned config is promoted to the platform default **only if all hold**:++```+MRR@10 >= baseline β 0.002+recall@10 >= baseline β 0.002+pattern count reduced by >= 15% (the actual value it earns its keep on)+p95 distill latency < 250 ms / 200-row batch+proxy-promotion violations == 0+```++This is deliberate: the M4 retrieval delta is a **statistical tie** (MRR@10 0.753 vs 0.749 baseline = +0.53% relative β not a retrieval win), so `dedupDistance=0.2` is **not** justified as retrieval-improving. It is justified as **compression that is retrieval-neutral**: on the real corpus it produces **2,723 patterns vs 4,350 at 0.12 β a 37% reduction** β at **11.6 ms / 200-row batch** and **0 proxy-promotion violations**. Smaller substrate, same recall, lower daemon cost. That is the value claim; retrieval parity is the guardrail, not the selling point.++## Measured (on copies of the real ~7,900-entry DB)++- **Default `dedupDistance=0.2`:** 7,899 entries β **2,723 patterns** (2,723 embeddings β 1:1, 2,723 episodes, 2,722 edges); 99 promoted (oracle tier from `feedback`), rest proxy. 11.6 ms/200-row batch.+- **vs `dedupDistance=0.12`:** 4,350 patterns (37% more) at 14.5 ms/batch β same held-out recall.+- **Invariants (both):** `memory_entries` unchanged; dry-run wrote nothing; second run processed 0 (idempotent); **0 proxy rows promoted**; **0 patterns without an embedding**.++## Alternatives considered++- **New `distill` worker type** vs. reusing the existing `consolidate` worker β chose reuse for backward-compat with `-w consolidate` scripts, `doctor`, and docs.+- **LLM-judge by default** vs. structural-by-default β chose structural for $0 discipline; LLM judge is opt-in + cost-bounded (ADR-172).+- **Full rescan** vs. **incremental cursor** β chose incremental for safety on a recently-corrupted DB.+- **Reuse `bridgeStorePattern`** (controller path) vs. **direct table writes** β chose direct writes for the initial service so `pattern_embeddings` is guaranteed populated (the controller fallback silently skips it) and so it is testable without the full agentdb controller stack; controller-path integration + health surfacing is a follow-up.++## Operational invariants (the difference between a memory feature and a safe learning loop)++Enforced in code + tests; auditable in SQL at any time.++| Invariant | Required check |+|---|---|+| Source preservation | `memory_entries` row count + content unchanged after a run |+| Idempotence | a second run processes 0 rows at the same cursor |+| Promotion safety | `proxy:structural AND promoted=true` count == 0 |+| Embedding coverage | every pattern has exactly one `pattern_embedding` |++```sql+-- Promotion safety (must be 0)+SELECT COUNT(*) AS proxy_promoted FROM reasoning_patterns+WHERE json_extract(metadata,'$.provenance_tier') = 'proxy:structural'+ AND json_extract(metadata,'$.promoted') = 1;++-- Embedding coverage (must be 0)+SELECT COUNT(*) AS patterns_without_embeddings+FROM reasoning_patterns rp+LEFT JOIN pattern_embeddings pe ON pe.pattern_id = rp.id+WHERE pe.pattern_id IS NULL;++-- Incremental cursor position+SELECT namespace, last_rowid FROM distill_state ORDER BY namespace;++-- Provenance / promotion distribution+SELECT json_extract(metadata,'$.provenance_tier') AS tier,+ json_extract(metadata,'$.promoted') AS promoted, COUNT(*) AS n+FROM reasoning_patterns GROUP BY tier, promoted ORDER BY tier, promoted;+```++(Promotion/provenance live in the `metadata` JSON, not as columns, because the `reasoning_patterns` schema is owned by agentdb β the JSON-extract checks above are the canonical audit.)++## Business value++This turns ruflo memory from a passive audit log into a governed, usable learning substrate **without adding inference cost**. The enterprise story is not "4,260 patterns" β it is:++```+7,899 raw entries β 2,723 structured patterns (37% compressed, retrieval-neutral)+ 99 execution-backed promoted memories+ 0 proxy-promoted violations+ 0 source mutations+ 0 patterns without an embedding+ $0 default runtime (no model spend)+```++Governed memory consolidation with provenance, rollback, and no surprise model spend.++## Acceptance test++Run distill **twice** on a copy of a production DB and require: `memory_entries` unchanged (count + content hash); the second run processes **0** rows; `proxy_promoted == 0`; `patterns_without_embeddings == 0`; and held-out MRR@10 no worse than baseline by more than 0.002. (Covered by `__tests__/memory-distillation.test.ts` + `distill-tuning.test.ts`.)++## Security β signed provenance for the helper auto-refresh++Hook fixes (like the failure-capture change) propagate via a version-stamped+auto-refresh: on CLI startup, an initialized project's `.claude/helpers/*.cjs`+are silently re-copied from the installed package if their stamp is stale. Since+those helpers **auto-execute on every tool use**, the refresh is gated by+**Ed25519 signed provenance** (fail-closed):++- `scripts/sign-helpers.mjs` (publish-time) hashes the critical helpers, builds a+ manifest `{version, files:{nameβsha256}}`, signs it with ruflo's private key,+ and writes `.claude/helpers/helpers.manifest.json`. The private key lives in+ **GCP Secret Manager** (`RUFLO_HELPERS_SIGNING_SECRET=ruflo-helpers-signing-key`,+ fetched via `gcloud secrets versions access`), with a local-PEM fallback+ (`RUFLO_HELPERS_SIGNING_KEY`) for air-gapped signing. It is **never committed**.+- The public key is baked into `src/init/helper-signing.ts` (`RUFLO_HELPERS_PUBKEY`).+- Before the refresh installs any helper, it verifies the manifest signature+ against the baked key AND each source helper's SHA-256 against the manifest. A+ tampered helper or manifest β e.g. a sibling package's `postinstall` overwriting+ on-disk hook code β is **refused, not propagated**, and the CLI warns.+- Threat model: this closes post-install / on-disk tampering of the helper files.+ It does not defend against a wholesale-compromised CLI (which could replace the+ baked key too) β but at that point the attacker already owns the binary you run.+- **Publish requirement:** re-run `sign-helpers.mjs` whenever a critical helper+ changes. The `helper-signing.test.ts` "hashes match shipped files" test fails in+ CI if a helper is changed without re-signing, so a stale manifest cannot ship.++## Rollback++Disable via `-w` omission or `--no-distill`. All writes are additive to the previously-empty target tables and never touch `memory_entries`, so full revert = stop the worker and optionally `DELETE FROM reasoning_patterns/pattern_embeddings/episodes/causal_edges` β zero data loss on the source.++## Status of milestones++- **M0 safety harness / M1 distillation service** β implemented + tested.+- **M2 CLI surface** (`memory distill run|status|config`) β implemented + tested.+- **M3 daemon wiring** (replaced the stub `consolidate` worker) β implemented + tested; the loop is now self-sustaining.+- **M4 self-optimization** (`distill-tuning.ts` + `scripts/tune-distill.mjs`) β implemented + tested. Winner `batchSize=200, dedupDistance=0.2` promoted under the promotion rule above: retrieval-neutral (MRR@10 0.753 vs 0.749 β a tie) but **37% fewer patterns** at 11.6 ms/batch with 0 violations. Sold as safe compression, not retrieval lift.+- **M5 platform-default promotion** β the M4 winner is the default in both the service (`dedupDistance` default 0.2) and the daemon (`CONSOLIDATE_DEDUP_DISTANCE = 0.2`); `--aggressive`=0.3 / `--conservative`=0.1 bracket it; override per-run via `memory distill`.diff --git a/v3/docs/adr/ADR-175-page-agent-browser-intent-layer.md b/v3/docs/adr/ADR-175-page-agent-browser-intent-layer.mdnew file mode 100644index 0000000000..215ad0914c--- /dev/null+++ b/v3/docs/adr/ADR-175-page-agent-browser-intent-layer.md@@ -0,0 +1,60 @@+# ADR-175 β page-agent In-Page Natural-Language Browser Intent Layer++- **Status:** Proposed+- **Date:** 2026-07-04+- **Deciders:** ruflo core+- **Related:** [ADR-150](ADR-150-metaharness-integration-surfaces.md) (optional-dependency + graceful-degradation posture), [ADR-174](ADR-174-memory-distillation-self-optimization.md) (distillation / self-learning loop that browser trajectories feed), `plugins/ruflo-browser/docs/adrs/0001-browser-skills-architecture.md`+- **Upstream:** `github.com/alibaba/page-agent` (npm `page-agent`, MIT)++## Context++The `ruflo-browser` plugin drives a real browser through the `agent-browser` CLI (Playwright under the hood), exposing **23 low-level, selector-based** MCP tools (`browser_click`, `browser_fill`, `browser_type`, `browser_snapshot` with `@e1` refs, `browser_eval`, `browser_screenshot`, session record/replay β RVF containers + ruvector trajectories + AgentDB selector memory + AIDefence gating). Every action requires a CSS selector or element ref; the model must read a snapshot and orchestrate each step imperatively. **There is no natural-language "perform this task" action.**++`page-agent` is the inverse architecture: **injected in-page JavaScript** that serialises the DOM to text (no screenshots, no vision model, no headless process of its own) and lets an LLM execute a multi-step intent in-page β `agent.execute('fill out and submit the checkout form')`. It takes an OpenAI-compatible endpoint (`{ baseURL, apiKey, model }`), ships as an npm package and an injectable IIFE bundle, and is MIT-licensed.++The two are complementary, not competing: the Playwright harness owns navigation, session capture, screenshots, cookies, and gating; page-agent adds the missing intent layer *inside* the page it controls.++## Decision++Add an optional **natural-language intent layer** to the browser plugin: a `browser_act` MCP tool that injects page-agent into the `agent-browser`-controlled page, executes an NL task in-page, routes page-agent's LLM through ruflo's own model layer, captures the resulting action trajectory into memory (feeding ADR-174 distillation), and gates the result through AIDefence.++| Layer | Owner | Responsibility |+|---|---|---|+| Outer harness | `agent-browser` / Playwright (existing) | navigate, session β RVF, screenshots, cookies, AIDefence |+| **In-page intent** | **page-agent (new)** | one NL call reasons over DOM-as-text and performs the multi-step action |++### Design constraints (load-bearing)++1. **Optional dependency (ADR-150 posture).** `page-agent` goes in `optionalDependencies`. `browser_act` returns `{ degraded: true, reason, hint }` β never throws β when it is absent. The CLI is fully functional without it (the 23 selector tools are unaffected). Removability is part of the contract.+2. **Model routing, not hardcoded Qwen.** page-agent's `{ baseURL, apiKey, model }` are resolved from ruflo's existing provider/router configuration (the same OpenAI-compatible surface the rest of the CLI uses), so browser intents are cost-governed. Because page-agent is **text-DOM (no vision)**, it routes naturally to the cheap tier (Haiku/local) β most intents are near-$0.+3. **Key safety.** The API key is resolved node-side and never emitted into page context / injected script strings. If page-agent's in-page mode would require the key in the page, proxy the completion through a local node endpoint so the key never crosses into the DOM.+3b. **Demo-endpoint firewall (fail-closed).** page-agent's only shipped browser bundle (`dist/iife/page-agent.demo.js`) auto-POSTs page content to Alibaba's public sandbox on inject (`https://page-ag-testing-*.<region>.fcapp.run`, `DEMO_MODEL`). We strip that tail, but the strip is best-effort text matching. The load-bearing guarantee is a fail-**closed** content firewall (`findDemoLeak`): if any known demo-endpoint signature survives the strip, `browser_act` **refuses to inject** and degrades β so an upstream bundle change that moves the marker can never silently re-enable the leak. (No fork required: the library core ESM is clean; the leak lives only in the demo bundle. A fork would mean maintaining a parallel 3-package copy forever to delete a few demo lines β the firewall achieves the security goal at near-zero maintenance.)+4. **Trajectory β memory (ADR-174 tie-in).** Each successful `execute()` records the intent + action trajectory as a `browser`-namespace memory entry (best-effort, never fatal), so browser intents feed the distillation/self-learning loop β over time the SONA/MoE model learns which intentβaction sequences succeed. This closes the plugin's existing "AgentDB selector memory" into the same learning loop.+5. **AIDefence gating.** Returned page content/results pass through the existing AIDefence PII/injection gate before reaching the caller, matching the selector tools.+6. **Additive, never sole.** Text-DOM has blind spots (canvas, visual-only, heavy shadow-DOM). The screenshot + selector tools remain the fallback; `browser_act` is an added capability, not a replacement.++## Broader use cases (this tool is the foundation)++`browser_act` unlocks several follow-on integrations, sequenced by leverage:++1. **Natural-language acceptance gate** β power the browser-validation gate / `ruflo-testgen` / `production-validator` with `execute('log in, add an item, verify the total')` instead of manual selector orchestration. Cheapest real win.+2. **Learning web-task skill library** β page-agent trajectories β `browser` memory β distilled `reasoning_patterns` β auto-generated `browser-*` skills. The most strategic (compounds with ADR-174).+3. **DOMβtext distiller** β reuse page-agent's serialiser as an input adapter to the distillation/embeddings pipeline for arbitrary HTML.+4. **Red/blue web executor** β page-agent as the action executor for `@metaharness/redblue` live-web adversarial tests, scored + human-gated.+5. **GOAP web operators** β expose `execute()` as a planning operator so `ruflo-goals` objectives span code **and** web.+6. **Federated web capability** β page-agent's MCP-server mode exposed across installations via `ruflo-federation`, zero-trust-gated.++## Alternatives considered++- **Reimplement NL intent over Playwright directly** β rebuild page-agent's DOM-text reasoning ourselves. Rejected: page-agent is a proven MIT implementation; reimplementing is cost with no differentiation.+- **Vision/screenshot agent for NL intent** β more expensive (needs a multimodal model), and we already have screenshots for the visual cases. Kept as the fallback lane, not the primary.+- **page-agent's Chrome-extension mode** β requires a real browser profile / user session; breaks headless + CI. Rejected in favour of the injectable IIFE inside the agent-browser-controlled page.++## Rollback++Remove `page-agent` from `optionalDependencies`; `browser_act` degrades to `{ degraded: true }` and every other browser tool is unaffected. No schema, no persisted state, no change to the 23 selector tools. The trajectory-recording side effect is additive to the `browser` memory namespace and never mutates existing data.++## Status of implementation++- `browser_act` MCP tool + optional-dependency wiring + model routing + trajectory capture + AIDefence gating + `browser-intent` skill + degraded-path tests β implemented alongside this ADR.+- Use cases 1β6 above are follow-ons, not part of this change.diff --git a/v3/pnpm-lock.yaml b/v3/pnpm-lock.yamlindex 970d276284..787abbf587 100644--- a/v3/pnpm-lock.yaml+++ b/v3/pnpm-lock.yaml@@ -208,6 +208,9 @@ importers:metaharness:specifier: ~0.2.8version: 0.2.8(@metaharness/[email protected])+ page-agent:+ specifier: ~1.11.0+ version: 1.11.0([email protected])ruvector:specifier: ^0.2.27@@ -4852,6 +4855,44 @@ packages:dev: falseoptional: true+ /@page-agent/[email protected]([email protected]):+ resolution: {integrity: sha512-loeD+78vGfxBDj6tFnExhEIreb2NiyFfIxEkILYcfWyz8qUp9vZTpJm/hRNN0EkBsaPF328LfDydMcVKcZIEvw==}+ requiresBuild: true+ peerDependencies:+ zod: ^3.25.0 || ^4.0.0+ dependencies:+ '@page-agent/llms': 1.11.0([email protected])+ '@page-agent/page-controller': 1.11.0+ chalk: 5.6.2+ zod: 3.25.76+ dev: false+ optional: true++ /@page-agent/[email protected]([email protected]):+ resolution: {integrity: sha512-9coqfbv/jNa7XwwGlQUNrwb3pBgpjgRbAfzB2AYDekyoYtyKsWCFlh6O62ANq3qeqqAOgDWYuuB+Dh7npq2Q3g==}+ requiresBuild: true+ peerDependencies:+ zod: ^3.25.0 || ^4.0.0+ dependencies:+ chalk: 5.6.2+ zod: 3.25.76+ dev: false+ optional: true++ /@page-agent/[email protected]:+ resolution: {integrity: sha512-DOG386ur+0yeC/jKECdGP97ugN+HDuyxPbmdvoUjMWpQcfIFh7QD+wIhdygKPWOvOnwzQxsehzf6IdVdlMQgfg==}+ requiresBuild: true+ dependencies:+ ai-motion: 0.4.8+ dev: false+ optional: true++ /@page-agent/[email protected]:+ resolution: {integrity: sha512-XSJlaNzj3j+uSNfGkkkxw6hyKw+d8fuZd/N1/NrxvTJIiUhVMXQ1PE30JRu5yWzbvmezKSCmloz8wbq4sWsrFw==}+ requiresBuild: true+ dev: false+ optional: true+/@peculiar/[email protected]:resolution: {integrity: sha512-xNLYLBFTBKkCzEZIw842BxytQQATQv+lDTCEMZ8C196iJcJJMBUZxrhSTxLaohMyKK8QlzRNTRkUmanucnDSqg==}requiresBuild: true@@ -7441,6 +7482,12 @@ packages:clean-stack: 5.3.0indent-string: 5.0.0+ resolution: {integrity: sha512-9nQVjf8lrYQWSW0sZdb9bES4x8Ei1w9C0S62po2KvRbMjslmjm0WMeszyW771SEauDnu4YGWqurLZ/gCkCTosQ==}+ requiresBuild: true+ dev: false+ optional: true+resolution: {integrity: sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==}peerDependencies:@@ -11167,6 +11214,21 @@ packages:resolution: {integrity: sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==}+ resolution: {integrity: sha512-zoV2WAxRlIbt80CZzPtpw+DyBdLMRwarJJT7JJSYysUnw72SA/CaG54VpHv3bzbAXrPUZgHXqnn/9FPb3OKRIA==}+ requiresBuild: true+ peerDependencies:+ zod: ^3.25.0 || ^4.0.0+ dependencies:+ '@page-agent/core': 1.11.0([email protected])+ '@page-agent/llms': 1.11.0([email protected])+ '@page-agent/page-controller': 1.11.0+ '@page-agent/ui': 1.11.0+ chalk: 5.6.2+ zod: 3.25.76+ dev: false+ optional: true+resolution: {integrity: sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==}engines: {node: '>=6'}