π 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
chore: sync repo dogfood helpers to 3.23.0 + gitignore auto-refresh runtime stamp
ruva5f86ad0ada8
diff --git a/.claude/helpers/auto-memory-hook.mjs b/.claude/helpers/auto-memory-hook.mjsold mode 100644new mode 100755index 7eabecbfe8..e0764c25cf--- a/.claude/helpers/auto-memory-hook.mjs+++ b/.claude/helpers/auto-memory-hook.mjs@@ -27,16 +27,29 @@ const CYAN = '\x1b[0;36m';const DIM = '\x1b[2m';const RESET = '\x1b[0m';+const YELLOW = '\x1b[0;33m';const log = (msg) => console.log(`${CYAN}[AutoMemory] ${msg}${RESET}`);const success = (msg) => console.log(`${GREEN}[AutoMemory] β ${msg}${RESET}`);const dim = (msg) => console.log(` ${DIM}${msg}${RESET}`);+// #2545: fail LOUD instead of a silent dim skip. When @claude-flow/memory cannot+// be resolved, self-learning imports are a no-op β the user must see this and be+// told exactly how to fix it (on both stdout, so it shows in the Claude Code hook+// transcript, and stderr, per the issue's requested channel).+function warnMemoryUnavailable() {+ const line1 = `[AutoMemory] @claude-flow/memory not resolvable from ${PROJECT_ROOT} β self-learning imports are DISABLED.`;+ const line2 = ' Fix: npm i -D @claude-flow/memory (or re-run: npx ruflo@latest init, then npx ruflo@latest doctor --fix)';+ console.log(`${YELLOW}${line1}${RESET}`);+ console.log(`${YELLOW}${line2}${RESET}`);+ process.stderr.write(`${line1}\n${line2}\n`);+}+const DEBUG = !!(process.env.RUFLO_DEBUG || process.env.DEBUG);// ββ Graceful shutdown (FIX 3) βββββββββββββββββββββββββββββββββββββββββββββββ-// Track the backend currently in use so a SIGTERM/SIGINT mid-run can still-// flush it (the JSON backend persists, a SQLite-backed one closes/flushes WAL)-// instead of leaving a half-written store or a stale lock behind.+// Track the backend in use so a SIGTERM/SIGINT mid-run can still flush it+// (the JSON backend persists; a SQLite-backed one closes/flushes WAL) instead+// of leaving a half-written store or a stale lock behind.let activeBackend = null;let shuttingDown = false;function trackBackend(b) { activeBackend = b; return b; }@@ -151,77 +164,31 @@ class JsonFileBackend {// Resolve memory package path (local dev or npm installed)// ============================================================================-/**- * Resolve a bundled package file (`<pkg>/<relativeFile>`) by trying, in order:- * 1. PROJECT_ROOT/v3/<pkg>/<relativeFile> (monorepo dev layout)- * 2. CWD/node_modules/<pkg>/<relativeFile> (user's project deps)- * 3. node_modules walk-up from PROJECT_ROOT- * 4. node_modules walk-up from CWD- * 5. Global npm prefix β checks the ruflo / claude-flow / @claude-flow/cli- * bundles, AND the package installed globally on its own- *- * Returns the resolved absolute path, or null. See issue #2285.- */-async function resolveBundledFile(pkg, relativeFile) {- const monorepo = join(PROJECT_ROOT, 'v3', pkg, relativeFile);- if (existsSync(monorepo)) return monorepo;-- const cwd = process.env.CLAUDE_FLOW_CWD || process.cwd();- const inCwd = join(cwd, 'node_modules', pkg, relativeFile);- if (existsSync(inCwd)) return inCwd;-- const walkUp = (start) => {- let dir = start;- while (dir && dir !== dirname(dir)) {- const candidate = join(dir, 'node_modules', pkg, relativeFile);- if (existsSync(candidate)) return candidate;- dir = dirname(dir);- }- return null;- };-- const fromProject = walkUp(PROJECT_ROOT);- if (fromProject) return fromProject;-- const fromCwd = walkUp(cwd);- if (fromCwd) return fromCwd;-- // Global npm prefix fallback β handles `npm i -g ruflo` and friends, where- // the marketplace clone (PROJECT_ROOT) has no access to the bundled deps.+async function loadMemoryPackage() {+ // Strategy 0 (#2545): sidecar recorded by `init` / `doctor --fix`. On the+ // documented `npx ruflo` path @claude-flow/memory (an optionalDependency of+ // the CLI) lands in the npx cache, which is NOT on the walk-up path from the+ // project β so init resolves it from the CLI's own context and records the+ // absolute path here. This is the only strategy that works on that install.try {- const { execSync } = await import('child_process');- const npmPrefix = execSync('npm prefix -g', {- encoding: 'utf-8',- stdio: ['ignore', 'pipe', 'ignore'],- }).trim();- if (npmPrefix) {- // Both Unix (<prefix>/lib/node_modules) and Windows (<prefix>/node_modules)- const roots = [join(npmPrefix, 'lib', 'node_modules'), join(npmPrefix, 'node_modules')];- const wrappers = ['ruflo', 'claude-flow', join('@claude-flow', 'cli')];- for (const root of roots) {- for (const wrapper of wrappers) {- const candidate = join(root, wrapper, 'node_modules', pkg, relativeFile);- if (existsSync(candidate)) return candidate;- }- const direct = join(root, pkg, relativeFile);- if (existsSync(direct)) return direct;+ const sidecar = join(PROJECT_ROOT, '.claude-flow', 'memory-package.json');+ if (existsSync(sidecar)) {+ const rec = JSON.parse(readFileSync(sidecar, 'utf-8'));+ if (rec?.distPath && existsSync(rec.distPath)) {+ return await import(`file://${rec.distPath}`);}}- } catch { /* npm not on PATH or no global install */ }-- return null;-}+ } catch { /* fall through */ }-async function loadMemoryPackage() {- // Strategy 1-5: locate dist/index.js across dev/installed/global layouts- const resolved = await resolveBundledFile('@claude-flow/memory', 'dist/index.js');- if (resolved) {+ // Strategy 1: Local dev (built dist)+ const localDist = join(PROJECT_ROOT, 'v3/@claude-flow/memory/dist/index.js');+ if (existsSync(localDist)) {try {- return await import(`file://${resolved}`);+ return await import(`file://${localDist}`);} catch { /* fall through */ }}- // Strategy 6: Use createRequire for CJS-style resolution (handles nested node_modules+ // Strategy 2: Use createRequire for CJS-style resolution (handles nested node_modules// when installed as a transitive dependency via npx ruflo / npx claude-flow)try {const { createRequire } = await import('module');@@ -229,11 +196,24 @@ async function loadMemoryPackage() {return require('@claude-flow/memory');} catch { /* fall through */ }- // Strategy 7: ESM import (works when @claude-flow/memory is a direct dependency)+ // Strategy 3: ESM import (works when @claude-flow/memory is a direct dependency)try {return await import('@claude-flow/memory');} catch { /* fall through */ }+ // Strategy 4: Walk up from PROJECT_ROOT looking for @claude-flow/memory in any node_modules+ let searchDir = PROJECT_ROOT;+ const { parse } = await import('path');+ while (searchDir !== parse(searchDir).root) {+ const candidate = join(searchDir, 'node_modules', '@claude-flow', 'memory', 'dist', 'index.js');+ if (existsSync(candidate)) {+ try {+ return await import(`file://${candidate}`);+ } catch { /* fall through */ }+ }+ searchDir = dirname(searchDir);+ }+return null;}@@ -283,7 +263,7 @@ async function doImport() {const memPkg = await loadMemoryPackage();if (!memPkg || !memPkg.AutoMemoryBridge) {- dim('Memory package not available β skipping auto memory import');+ warnMemoryUnavailable();return;}@@ -292,10 +272,7 @@ async function doImport() {await backend.initialize();const bridgeConfig = {- // Use Claude Code's invocation cwd (the user's project), not PROJECT_ROOT- // β PROJECT_ROOT resolves to the plugin clone when this hook runs from- // ~/.claude/plugins/marketplaces/ruflo/. See issue #2284.- workingDir: process.env.CLAUDE_FLOW_CWD || process.cwd(),+ workingDir: PROJECT_ROOT,syncMode: 'on-session-end',};@@ -327,36 +304,6 @@ async function doImport() {dim(`ββ Learning: ${config.learningBridge.enabled ? 'active' : 'disabled'}`);dim(`ββ Graph: ${config.memoryGraph.enabled ? 'active' : 'disabled'}`);dim(`ββ Agent scopes: ${config.agentScopes.enabled ? 'active' : 'disabled'}`);-- // Bridge to AgentDB: store entries with ONNX vector embeddings for semantic search- let vectorized = 0;- try {- const cliDistPath = await resolveBundledFile('@claude-flow/cli', 'dist/src/memory/memory-initializer.js');- if (cliDistPath) {- const memInit = await import(`file://${cliDistPath}`);- await memInit.initializeMemoryDatabase({ force: false, verbose: false });-- const entries = await backend.query({});- for (const entry of entries) {- if (!entry.content || entry.content.length < 10) continue;- try {- await memInit.storeEntry({- key: entry.key || entry.id,- value: entry.content,- namespace: entry.namespace || 'auto-memory',- generateEmbeddingFlag: true,- });- vectorized++;- } catch { /* skip entries that fail to embed */ }- }-- if (vectorized > 0) {- success(`Vectorized ${vectorized} entries into AgentDB (ONNX 384-dim)`);- }- }- } catch (vecErr) {- dim(`AgentDB vectorization skipped: ${vecErr.message?.slice(0, 60)}`);- }} catch (err) {dim(`Import failed (non-critical): ${err.message}`);}@@ -369,7 +316,7 @@ async function doSync() {const memPkg = await loadMemoryPackage();if (!memPkg || !memPkg.AutoMemoryBridge) {- dim('Memory package not available β skipping sync');+ warnMemoryUnavailable();return;}@@ -385,8 +332,7 @@ async function doSync() {}const bridgeConfig = {- // See doImport β must reflect the user's project, not PROJECT_ROOT (#2284)- workingDir: process.env.CLAUDE_FLOW_CWD || process.cwd(),+ workingDir: PROJECT_ROOT,syncMode: 'on-session-end',};@@ -416,21 +362,6 @@ async function doSync() {// Curate MEMORY.md index with graph-aware orderingawait bridge.curateIndex();success('Curated MEMORY.md index');-- // Flush intelligence patterns to disk (SONA + ReasoningBank)- try {- const intPath = await resolveBundledFile('@claude-flow/cli', 'dist/src/memory/intelligence.js');- if (intPath) {- const intelligence = await import(`file://${intPath}`);- if (intelligence.flushPatterns) {- intelligence.flushPatterns();- const stats = intelligence.getIntelligenceStats?.();- if (stats && stats.patternsLearned > 0) {- success(`Flushed ${stats.patternsLearned} learned patterns to disk`);- }- }- }- } catch { /* non-critical */ }} catch (err) {dim(`Sync failed (non-critical): ${err.message}`);}@@ -443,8 +374,12 @@ async function doStatus() {const memPkg = await loadMemoryPackage();const config = readConfig();+ const sidecar = join(PROJECT_ROOT, '.claude-flow', 'memory-package.json');+ const hasSidecar = existsSync(sidecar);+console.log('\n=== Auto Memory Bridge Status ===\n');- console.log(` Package: ${memPkg ? 'β Available' : 'β Not found'}`);+ console.log(` Package: ${memPkg ? 'β Available' : 'β Not found β self-learning DISABLED (fix: npm i -D @claude-flow/memory)'}`);+ console.log(` Resolver: ${hasSidecar ? 'β .claude-flow/memory-package.json' : 'βΈ no sidecar (run: npx ruflo@latest doctor --fix)'}`);console.log(` Store: ${existsSync(STORE_PATH) ? 'β ' + STORE_PATH : 'βΈ Not initialized'}`);console.log(` LearningBridge: ${config.learningBridge.enabled ? 'β Enabled' : 'βΈ Disabled'}`);console.log(` MemoryGraph: ${config.memoryGraph.enabled ? 'β Enabled' : 'βΈ Disabled'}`);@@ -457,158 +392,9 @@ async function doStatus() {} catch { /* ignore */ }}- // AgentDB vector status- try {- const dbPath = join(PROJECT_ROOT, '.claude-flow', 'memory', 'memory.db');- const swarmDbPath = join(PROJECT_ROOT, '.swarm', 'memory.db');- const hasDb = existsSync(dbPath) || existsSync(swarmDbPath);- console.log(` AgentDB: ${hasDb ? 'β sql.js database exists' : 'βΈ Not initialized'}`);-- const intPath = await resolveBundledFile('@claude-flow/cli', 'dist/src/memory/intelligence.js');- if (intPath) {- const intelligence = await import(`file://${intPath}`);- const stats = intelligence.getIntelligenceStats?.();- if (stats) {- console.log(` SONA: ${stats.sonaEnabled ? 'β Active' : 'βΈ Not initialized'}`);- console.log(` Patterns: ${stats.patternsLearned} learned`);- console.log(` Trajectories: ${stats.trajectoriesRecorded} recorded`);- }- }- } catch { /* ignore */ }-console.log('');}-// ============================================================================-// Import ALL Claude Code memories from all projects into AgentDB-// ============================================================================--async function doImportAll() {- log('Importing ALL Claude Code memories into AgentDB...');-- const { homedir } = await import('os');- const { readdirSync } = await import('fs');- const claudeProjectsDir = join(homedir(), '.claude', 'projects');-- if (!existsSync(claudeProjectsDir)) {- dim('No Claude Code projects found at ' + claudeProjectsDir);- return;- }-- // Find all memory files across all projects- const memoryFiles = [];- try {- const projects = readdirSync(claudeProjectsDir, { withFileTypes: true });- for (const project of projects) {- if (!project.isDirectory()) continue;- const memDir = join(claudeProjectsDir, project.name, 'memory');- if (!existsSync(memDir)) continue;- const files = readdirSync(memDir).filter(f => f.endsWith('.md'));- for (const file of files) {- memoryFiles.push({- path: join(memDir, file),- project: project.name,- file,- });- }- }- } catch (err) {- dim('Error scanning projects: ' + err.message);- return;- }-- if (memoryFiles.length === 0) {- dim('No memory files found');- return;- }-- log(`Found ${memoryFiles.length} memory files across ${new Set(memoryFiles.map(f => f.project)).size} projects`);-- // Load memory-initializer for vectorized storage- let memInit = null;- try {- const cliDistPath = await resolveBundledFile('@claude-flow/cli', 'dist/src/memory/memory-initializer.js');- if (cliDistPath) {- memInit = await import(`file://${cliDistPath}`);- await memInit.initializeMemoryDatabase({ force: false, verbose: false });- }- } catch (err) {- dim('Memory initializer not available: ' + err.message?.slice(0, 60));- }-- if (!memInit) {- dim('Cannot vectorize without memory-initializer. Run: cd v3/@claude-flow/cli && npm run build');- return;- }-- let imported = 0;- let skipped = 0;-- for (const memFile of memoryFiles) {- try {- const content = readFileSync(memFile.path, 'utf-8');-- // Parse YAML frontmatter + body- const frontmatterMatch = content.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);- let name = memFile.file.replace('.md', '');- let description = '';- let type = 'auto-memory';- let body = content;-- if (frontmatterMatch) {- const yaml = frontmatterMatch[1];- body = frontmatterMatch[2].trim();- const nameMatch = yaml.match(/^name:\s*(.+)$/m);- const descMatch = yaml.match(/^description:\s*(.+)$/m);- const typeMatch = yaml.match(/^type:\s*(.+)$/m);- if (nameMatch) name = nameMatch[1].trim();- if (descMatch) description = descMatch[1].trim();- if (typeMatch) type = typeMatch[1].trim();- }-- // Split body into sections (## headers) for granular entries- const sections = body.split(/^(?=## )/m).filter(s => s.trim().length > 20);-- if (sections.length === 0) {- // Store whole file as one entry- if (body.length > 10) {- await memInit.storeEntry({- key: `claude-memory:${memFile.project}:${name}`,- value: body.slice(0, 4096),- namespace: 'claude-memories',- generateEmbeddingFlag: true,- });- imported++;- }- } else {- // Store each section separately for better search granularity- for (const section of sections) {- const titleMatch = section.match(/^##\s+(.+)/);- const sectionTitle = titleMatch ? titleMatch[1].trim() : name;- const sectionBody = section.replace(/^##\s+.+\n/, '').trim();- if (sectionBody.length < 10) continue;-- await memInit.storeEntry({- key: `claude-memory:${memFile.project}:${name}:${sectionTitle.slice(0, 50)}`,- value: sectionBody.slice(0, 4096),- namespace: 'claude-memories',- generateEmbeddingFlag: true,- });- imported++;- }- }-- dim(` β ${memFile.project}/${memFile.file} (${sections.length || 1} entries)`);- } catch (err) {- dim(` β ${memFile.project}/${memFile.file}: ${err.message?.slice(0, 60)}`);- skipped++;- }- }-- success(`Imported ${imported} entries from ${memoryFiles.length} files (${skipped} skipped)`);- success('All Claude Code memories now searchable via AgentDB vector search');-}-// ============================================================================// Main// ============================================================================@@ -630,16 +416,15 @@ process.on('unhandledRejection', (reason) => {try {switch (command) {case 'import': await doImport(); break;- case 'import-all': await doImportAll(); break;case 'sync': await doSync(); break;case 'status': await doStatus(); break;default:console.log('Usage: auto-memory-hook.mjs <import|sync|status>');- process.exit(1);+ break;}} catch (err) {// Hooks must never crash Claude Code - fail silently- dim(`Error (non-critical): ${err.message}`);+ try { dim(`Error (non-critical): ${err.message}`); } catch (_) {}}-// Ensure clean exit for Claude Code hooks (exit 0 = success, no stderr = no error)+// Force clean exit β process.exitCode alone isn't enough if async errors override itprocess.exit(0);diff --git a/.claude/helpers/hook-handler.cjs b/.claude/helpers/hook-handler.cjsold mode 100644new mode 100755index 4a94838bc5..b2b91a8c75--- a/.claude/helpers/hook-handler.cjs+++ b/.claude/helpers/hook-handler.cjs@@ -2,6 +2,15 @@/*** Claude Flow Hook Handler (Cross-Platform)* Dispatches hook events to the appropriate helper modules.+ *+ * Usage: node hook-handler.cjs <command> [args...]+ *+ * Commands:+ * route - Route a task to optimal agent (reads PROMPT from env/stdin)+ * pre-bash - Validate command safety before execution+ * post-edit - Record edit outcome for learning+ * session-restore - Restore previous session state+ * session-end - End session and persist state*/const path = require('path');@@ -9,6 +18,9 @@ const fs = require('fs');const helpersDir = __dirname;+// Safe require with stdout suppression - the helper modules have CLI+// sections that run unconditionally on require(), so we mute console+// during the require to prevent noisy output.function safeRequire(modulePath) {try {if (fs.existsSync(modulePath)) {@@ -30,51 +42,43 @@ function safeRequire(modulePath) {return null;}-const router = safeRequire(path.join(helpersDir, 'router.cjs'));-const session = safeRequire(path.join(helpersDir, 'session.cjs'));-const memory = safeRequire(path.join(helpersDir, 'memory.cjs'));+const router = safeRequire(path.join(helpersDir, 'router.js'));+const session = safeRequire(path.join(helpersDir, 'session.js'));+const memory = safeRequire(path.join(helpersDir, 'memory.js'));const intelligence = safeRequire(path.join(helpersDir, 'intelligence.cjs'));// ββ Intelligence timeout protection (fixes #1530, #1531) βββββββββββββββββββ-var INTELLIGENCE_TIMEOUT_MS = 3000;-// Race the (possibly-async) work against a real timeout.+const INTELLIGENCE_TIMEOUT_MS = 3000;+// Race the (possibly-async) work against a real timeout. The previous version+// called fn() and clearTimeout(timer) immediately, so an async fn returned a+// pending promise that resolved THROUGH the race β the timeout protected+// nothing. This settles on whichever finishes first, then clears the timer.//-// The previous implementation called `fn()` and then `clearTimeout(timer)`-// immediately β but if `fn()` returns a *pending* promise (async work), the-// timer was cancelled before the work settled and the promise resolved with the-// still-pending promise, so the timeout protected nothing. This version only-// settles when the work resolves OR the timeout fires, whichever comes first,-// and clears the timer afterwards.-//-// LIMITATION (be honest): a *synchronous* CPU-bound `fn` (e.g. the current-// intelligence.init(), which does blocking fs reads) cannot be interrupted by-// any in-process timer β the event loop is blocked, so the timeout callback-// can't run until `fn` already returned. The real guard for that case lives in-// intelligence.cjs (MAX_DATA_FILE_SIZE / MAX_GRAPH_NODES caps). This util only-// bounds work that yields to the event loop (async I/O, dynamic import, etc.).+// LIMITATION: a synchronous blocking fn (the current intelligence.init() does+// blocking fs reads) cannot be interrupted by any in-process timer β the event+// loop is blocked. The real guard for that case is the readJSON file-size+// limit in intelligence.cjs. This util only bounds work that yields (async I/O).function runWithTimeout(fn, label) {- var timer;- var timeout = new Promise(function(resolve) {- timer = setTimeout(function() {+ let timer;+ const timeout = new Promise((resolve) => {+ timer = setTimeout(() => {process.stderr.write("[WARN] " + label + " timed out after " + INTELLIGENCE_TIMEOUT_MS + "ms, skipping\n");resolve(null);}, INTELLIGENCE_TIMEOUT_MS);});- // Promise.resolve().then(fn) turns a synchronous throw into a rejection so it- // is handled here rather than escaping the Promise constructor.- var work = Promise.resolve().then(fn).catch(function() { return null; });- return Promise.race([work, timeout]).then(function(result) {+ const work = Promise.resolve().then(fn).catch(() => null);+ return Promise.race([work, timeout]).then((result) => {clearTimeout(timer);return result;});}+// Get the command from argvconst [,, command, ...args] = process.argv;-// Read stdin β Claude Code sends hook data as JSON via stdin-// Uses a timeout to prevent hanging when stdin is in an ambiguous state-// (not TTY, not a proper pipe) which happens with Claude Code hook invocations.+// Read stdin with timeout β Claude Code sends hook data as JSON via stdin.+// Timeout prevents hanging when stdin is not properly closed (common on Windows).async function readStdin() {if (process.stdin.isTTY) return '';return new Promise((resolve) => {@@ -94,11 +98,11 @@ async function readStdin() {async function main() {// Global safety timeout: hooks must NEVER hang (#1530, #1531)- var safetyTimer = setTimeout(function() {+ const safetyTimer = setTimeout(() => {process.stderr.write("[WARN] Hook handler global timeout (5s), forcing exit\n");process.exit(0);}, 5000);- safetyTimer.unref();+ safetyTimer.unref(); // don't keep process alive just for this timerlet stdinData = '';try { stdinData = await readStdin(); } catch (e) { /* ignore stdin errors */ }@@ -108,21 +112,40 @@ async function main() {try { hookInput = JSON.parse(stdinData); } catch (e) { /* ignore parse errors */ }}- // Merge stdin data into prompt resolution: prefer stdin fields, then env vars.- // NEVER fall back to argv args β shell glob expansion of braces in bash output- // creates junk files (#1342). Use env vars or stdin only.// Normalize snake_case/camelCase: Claude Code sends tool_input/tool_name (snake_case)- var toolInput = hookInput.toolInput || hookInput.tool_input || {};- var toolName = hookInput.toolName || hookInput.tool_name || '';+ const toolInput = hookInput.toolInput || hookInput.tool_input || {};+ const toolName = hookInput.toolName || hookInput.tool_name || '';++ // Merge stdin data into prompt resolution: prefer stdin fields, then env, then argv.+ // `toolInput` is an object (e.g. {command:"ls"}) β it's truthy but not a string,+ // so falling back to it directly bound `prompt` to the object and tripped+ // `.toLowerCase()` / `.substring()` on every Bash hook (#1944). Use the+ // `.command` field instead, which is the actual string the hook needs.+ const prompt = hookInput.prompt || hookInput.command || toolInput.command+ || process.env.PROMPT || process.env.TOOL_INPUT_command || args.join(' ') || '';- // `toolInput` is an object (e.g. {command:"ls"}) β falling back to it- // directly bound `prompt` to the object and tripped `.toLowerCase()` /- // `.substring()` on every Bash hook (#1944). Use the `.command` field.- var prompt = hookInput.prompt || hookInput.command || toolInput.command- || process.env.PROMPT || process.env.TOOL_INPUT_command || '';+ // 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 routingif (intelligence && intelligence.getContext) {try {const ctx = intelligence.getContext(prompt);@@ -131,14 +154,16 @@ const handlers = {}if (router && router.routeTask) {const result = router.routeTask(prompt);- var output = [];- output.push('[INFO] Routing task: ' + (prompt.substring(0, 80) || '(no prompt)'));- output.push('');- output.push('+------------------- Primary Recommendation -------------------+');- output.push('| Agent: ' + result.agent.padEnd(53) + '|');- output.push('| Confidence: ' + (result.confidence * 100).toFixed(1) + '%' + ' '.repeat(44) + '|');- output.push('| Reason: ' + result.reason.substring(0, 53).padEnd(53) + '|');- output.push('+--------------------------------------------------------------+');+ // Format output for Claude Code hook consumption β real data only+ const output = [+ `[INFO] Routing task: ${prompt.substring(0, 80) || '(no prompt)'}`,+ '',+ '+------------------- Primary Recommendation -------------------+',+ `| Agent: ${result.agent.padEnd(53)}|`,+ `| Confidence: ${(result.confidence * 100).toFixed(1)}%${' '.repeat(44)}|`,+ `| Reason: ${(result.reason || '').substring(0, 53).padEnd(53)}|`,+ '+--------------------------------------------------------------+',+ ];console.log(output.join('\n'));} else {console.log('[INFO] Router not available, using default routing');@@ -146,14 +171,16 @@ const handlers = {},'pre-bash': () => {+ // Basic command safety check β prefer stdin command data from Claude Code.// String() wrap is belt-and-suspenders for #2017: even if a future regression// re-binds `prompt` or `hookInput.command` to a non-string, `.toLowerCase()`- // can no longer throw a TypeError that the global try/catch would swallow.- var cmd = String(hookInput.command || toolInput.command || prompt || '').toLowerCase();- var dangerous = ['rm -rf /', 'format c:', 'del /s /q c:\\', ':(){:|:&};:'];- for (var i = 0; i < dangerous.length; i++) {- if (cmd.includes(dangerous[i])) {- console.error('[BLOCKED] Dangerous command detected: ' + dangerous[i]);+ // can no longer throw a TypeError that the global try/catch would swallow+ // (silently exiting 0 and letting the dangerous command through).+ const cmd = String(hookInput.command || toolInput.command || prompt || '').toLowerCase();+ const dangerous = ['rm -rf /', 'format c:', 'del /s /q c:\\', ':(){:|:&};:'];+ for (const d of dangerous) {+ if (cmd.includes(d)) {+ console.error(`[BLOCKED] Dangerous command detected: ${d}`);process.exit(1);}}@@ -161,46 +188,60 @@ const handlers = {},'post-edit': () => {+ // Record edit for session metricsif (session && session.metric) {try { session.metric('edits'); } catch (e) { /* no active session */ }}+ // Record edit for intelligence consolidation β prefer stdin data from Claude Codeif (intelligence && intelligence.recordEdit) {try {- var file = hookInput.file_path || toolInput.file_path+ 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 () => {if (session) {- var existing = session.restore && session.restore();+ // Try restore first, fall back to start+ const existing = session.restore && session.restore();if (!existing) {session.start && session.start();}} else {- console.log('[OK] Session restored: session-' + Date.now());+ // Minimal session restore output+ const sessionId = `session-${Date.now()}`;+ console.log(`[INFO] Restoring session: %SESSION_ID%`);+ console.log('');+ console.log(`[OK] Session restored from %SESSION_ID%`);+ console.log(`New session ID: ${sessionId}`);+ console.log('');+ console.log('Restored State');+ console.log('+----------------+-------+');+ console.log('| Item | Count |');+ console.log('+----------------+-------+');+ console.log('| Tasks | 0 |');+ console.log('| Agents | 0 |');+ console.log('| Memory Entries | 0 |');+ console.log('+----------------+-------+');}- // Initialize intelligence (with timeout β #1530)+ // Initialize intelligence graph after session restore (with timeout β #1530)if (intelligence && intelligence.init) {- var initResult = await runWithTimeout(function() { return intelligence.init(); }, 'intelligence.init()');+ const initResult = await runWithTimeout(() => intelligence.init(), 'intelligence.init()');if (initResult && initResult.nodes > 0) {- console.log('[INTELLIGENCE] Loaded ' + initResult.nodes + ' patterns, ' + initResult.edges + ' edges');+ console.log(`[INTELLIGENCE] Loaded ${initResult.nodes} patterns, ${initResult.edges} edges`);}}},'session-end': async () => {- // Consolidate intelligence (with timeout β #1530)+ // Consolidate intelligence before ending session (with timeout β #1530)if (intelligence && intelligence.consolidate) {- var consResult = await runWithTimeout(function() { return intelligence.consolidate(); }, 'intelligence.consolidate()');+ const consResult = await runWithTimeout(() => intelligence.consolidate(), 'intelligence.consolidate()');if (consResult && consResult.entries > 0) {- var msg = '[INTELLIGENCE] Consolidated: ' + consResult.entries + ' entries, ' + consResult.edges + ' edges';- if (consResult.newEntries > 0) msg += ', ' + consResult.newEntries + ' new';- msg += ', PageRank recomputed';- console.log(msg);+ console.log(`[INTELLIGENCE] Consolidated: ${consResult.entries} entries, ${consResult.edges} edges${consResult.newEntries > 0 ? `, ${consResult.newEntries} new` : ''}, PageRank recomputed`);}}if (session && session.end) {@@ -214,44 +255,25 @@ const handlers = {if (session && session.metric) {try { session.metric('tasks'); } catch (e) { /* no active session */ }}+ // Route the task if router is availableif (router && router.routeTask && prompt) {- var result = router.routeTask(prompt);- console.log('[INFO] Task routed to: ' + result.agent + ' (confidence: ' + result.confidence + ')');+ const result = router.routeTask(prompt);+ console.log(`[INFO] Task routed to: ${result.agent} (confidence: ${result.confidence})`);} else {console.log('[OK] Task started');}},'post-task': () => {+ // 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');- },-- 'compact-manual': () => {- console.log('PreCompact Guidance:');- console.log('IMPORTANT: Review CLAUDE.md in project root for:');- console.log(' - Available agents and concurrent usage patterns');- console.log(' - Swarm coordination strategies (hierarchical, mesh, adaptive)');- console.log(' - Critical concurrent execution rules (1 MESSAGE = ALL OPERATIONS)');- console.log('Ready for compact operation');- },-- 'compact-auto': () => {- console.log('Auto-Compact Guidance (Context Window Full):');- console.log('CRITICAL: Before compacting, ensure you understand:');- console.log(' - All agents available in .claude/agents/ directory');- console.log(' - Concurrent execution patterns from CLAUDE.md');- console.log(' - Swarm coordination strategies for complex tasks');- console.log('Apply GOLDEN RULE: Always batch operations in single messages');- console.log('Auto-compact proceeding with full agent context');- },-- 'status': () => {- console.log('[OK] Status check');+ console.log(toolFailed ? '[LEARN] Task FAILURE recorded' : '[OK] Task completed');},'stats': () => {@@ -263,29 +285,27 @@ const handlers = {},};-if (command && handlers[command]) {+ // Execute the handler+ if (command && handlers[command]) {try {await Promise.resolve(handlers[command]());} catch (e) {- console.log('[WARN] Hook ' + command + ' encountered an error: ' + e.message);+ // Hooks should never crash Claude Code - fail silently+ console.log(`[WARN] Hook ${command} encountered an error: ${e.message}`);}} else if (command) {- console.log('[OK] Hook: ' + command);+ // Unknown command - pass through without error+ console.log(`[OK] Hook: ${command}`);} else {- console.log('Usage: hook-handler.cjs <route|pre-bash|post-edit|session-restore|session-end|pre-task|post-task|compact-manual|compact-auto|status|stats>');+ console.log('Usage: hook-handler.cjs <route|pre-bash|post-edit|session-restore|session-end|pre-task|post-task|stats>');}}-// Only dispatch hooks when run directly (node hook-handler.cjs ...). When-// require()'d by a test, just expose the internals so they can be unit-tested-// without triggering stdin reads / process.exit.-if (require.main === module) {- main().catch(function(e) {- console.log('[WARN] Hook handler error: ' + e.message);- }).finally(function() {- // Ensure clean exit for Claude Code hooks- process.exit(0);- });-}--module.exports = { runWithTimeout: runWithTimeout, INTELLIGENCE_TIMEOUT_MS: INTELLIGENCE_TIMEOUT_MS };+// Hooks must ALWAYS exit 0 β Claude Code treats non-zero as "hook error"+// and skips all subsequent hooks for the event.+process.exitCode = 0;+main().catch((e) => {+ try { console.log(`[WARN] Hook handler error: ${e.message}`); } catch (_) {}+}).finally(() => {+ process.exit(0);+});diff --git a/.claude/helpers/intelligence.cjs b/.claude/helpers/intelligence.cjsold mode 100644new mode 100755index d252ab953a..9fc094dd90--- a/.claude/helpers/intelligence.cjs+++ b/.claude/helpers/intelligence.cjs@@ -1,252 +1,1048 @@#!/usr/bin/env node/**- * Intelligence Layer Stub (ADR-050)- * Minimal fallback β full version is copied from package source.- * Provides: init, getContext, recordEdit, feedback, consolidate+ * Intelligence Layer (ADR-050)+ *+ * Closes the intelligence loop by wiring PageRank-ranked memory into+ * the hook system. Pure CJS β no ESM imports of @claude-flow/memory.+ *+ * Data files (all under .claude-flow/data/):+ * auto-memory-store.json β written by auto-memory-hook.mjs+ * graph-state.json β serialized graph (nodes + edges + pageRanks)+ * ranked-context.json β pre-computed ranked entries for fast lookup+ * pending-insights.jsonl β append-only edit/task log*/+'use strict';const fs = require('fs');const path = require('path');-const os = require('os');const DATA_DIR = path.join(process.cwd(), '.claude-flow', 'data');const STORE_PATH = path.join(DATA_DIR, 'auto-memory-store.json');+const GRAPH_PATH = path.join(DATA_DIR, 'graph-state.json');const RANKED_PATH = path.join(DATA_DIR, 'ranked-context.json');const PENDING_PATH = path.join(DATA_DIR, 'pending-insights.jsonl');const SESSION_DIR = path.join(process.cwd(), '.claude-flow', 'sessions');const SESSION_FILE = path.join(SESSION_DIR, 'current.json');// ββ Safety limits (fixes #1530, #1531) βββββββββββββββββββββββββββββββββββββ-var MAX_DATA_FILE_SIZE = 10 * 1024 * 1024; // 10 MB β skip files larger than this-var MAX_GRAPH_NODES = 5000; // skip PageRank if graph exceeds this+const MAX_DATA_FILE_SIZE = 10 * 1024 * 1024; // 10 MB β skip files larger than this+const MAX_GRAPH_NODES = 5000; // skip PageRank if graph exceeds this-function ensureDir(dir) {- if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });-}+// ββ Stop words for trigram matching ββββββββββββββββββββββββββββββββββββββββββ-function readJSON(p) {- // Safety: skip files exceeding MAX_DATA_FILE_SIZE (#1531)- try { var stat = fs.statSync(p); if (stat.size > MAX_DATA_FILE_SIZE) { process.stderr.write("[INTELLIGENCE] WARN: Skipping " + path.basename(p) + " (" + Math.round(stat.size / 1048576) + "MB exceeds 10MB limit)\n"); return null; } } catch(e) { /* file may not exist */ }- try { return fs.existsSync(p) ? JSON.parse(fs.readFileSync(p, "utf-8")) : null; }- catch { return null; }-}+const STOP_WORDS = new Set([+ 'the', 'a', 'an', 'is', 'are', 'was', 'were', 'be', 'been', 'being',+ 'have', 'has', 'had', 'do', 'does', 'did', 'will', 'would', 'could',+ 'should', 'may', 'might', 'shall', 'can', 'to', 'of', 'in', 'for',+ 'on', 'with', 'at', 'by', 'from', 'as', 'into', 'through', 'during',+ 'before', 'after', 'and', 'but', 'or', 'nor', 'not', 'so', 'yet',+ 'both', 'either', 'neither', 'each', 'every', 'all', 'any', 'few',+ 'more', 'most', 'other', 'some', 'such', 'no', 'only', 'own', 'same',+ 'than', 'too', 'very', 'just', 'because', 'if', 'when', 'which',+ 'who', 'whom', 'this', 'that', 'these', 'those', 'it', 'its',+]);-function writeJSON(p, data) {- ensureDir(path.dirname(p));- fs.writeFileSync(p, JSON.stringify(data, null, 2), "utf-8");+// ββ Helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++function ensureDataDir() {+ if (!fs.existsSync(DATA_DIR)) fs.mkdirSync(DATA_DIR, { recursive: true });}-function sessionGet(key) {- var session = readJSON(SESSION_FILE);- if (!session) return null;- return key ? (session.context || {})[key] : session.context;+function readJSON(filePath) {+ // Safety: skip files exceeding MAX_DATA_FILE_SIZE (#1531)+ try {+ const stat = fs.statSync(filePath);+ if (stat.size > MAX_DATA_FILE_SIZE) {+ process.stderr.write("[INTELLIGENCE] WARN: Skipping " + path.basename(filePath) + " (" + Math.round(stat.size / 1048576) + "MB exceeds 10MB limit)\n");+ return null;+ }+ } catch { /* file may not exist yet */ }+ try {+ if (fs.existsSync(filePath)) return JSON.parse(fs.readFileSync(filePath, 'utf-8'));+ } catch { /* corrupt file β start fresh */ }+ return null;}-function sessionSet(key, value) {- var session = readJSON(SESSION_FILE);- if (!session) return;- if (!session.context) session.context = {};- session.context[key] = value;- writeJSON(SESSION_FILE, session);+function writeJSON(filePath, data) {+ ensureDataDir();+ fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf-8');}function tokenize(text) {if (!text) return [];- return text.toLowerCase().replace(/[^a-z0-9\s]/g, " ").split(/\s+/).filter(function(w) { return w.length > 2; });+ return text.toLowerCase()+ .replace(/[^a-z0-9\s-]/g, ' ')+ .split(/\s+/)+ .filter(w => w.length > 2 && !STOP_WORDS.has(w));}-// ββ Truncation transparency (FIX 4) βββββββββββββββββββββββββββββββββββββββββ-// Silently severing stored values means later reasoning can be built on-// incomplete text. Warn (debug-gated) and mark the cut point with an ellipsis-// so it is visible that the value was clipped.-var DEBUG = !!(process.env.RUFLO_DEBUG || process.env.DEBUG);-function clip(text, max, label) {- text = text == null ? "" : String(text);- if (text.length <= max) return text;- if (DEBUG) {- process.stderr.write("[INTELLIGENCE] WARN: truncated " + (label || "value") +- " from " + text.length + " to " + max + " chars\n");+function trigrams(words) {+ const t = new Set();+ for (const w of words) {+ for (let i = 0; i <= w.length - 3; i++) t.add(w.slice(i, i + 3));}- return text.slice(0, max - 1) + "β¦";+ return t;+}++function jaccardSimilarity(setA, setB) {+ if (setA.size === 0 && setB.size === 0) return 0;+ let intersection = 0;+ for (const item of setA) { if (setB.has(item)) intersection++; }+ return intersection / (setA.size + setB.size - intersection);}// ββ Deduplication helper (fixes #1518) ββββββββββββββββββββββββββββββββββββββ+function deduplicateById(entries) {if (!entries || !Array.isArray(entries)) return entries;- var seen = new Map();- for (var i = 0; i < entries.length; i++) {- var id = entries[i].id || entries[i].key;+ const seen = new Map();+ for (const entry of entries) {+ const id = entry.id || entry.key;if (id) {- seen.set(id, entries[i]);+ seen.set(id, entry);} else {- seen.set('__no_id_' + seen.size, entries[i]);+ seen.set(`__no_id_${seen.size}`, entry);}}return Array.from(seen.values());}+// ADR-095 G6 β content-hash dedup. The April audit measured 5,706 entries+// in the auto-memory store with only ~20 unique by content; 5,686 dupes+// were the same MEMORY.md sections imported from sibling project dirs+// with different IDs. deduplicateById can't catch these (the IDs really+// are different); we need a content fingerprint.+//+// Fast non-cryptographic fingerprint β collisions on 64-bit FNV-1a are+// vanishingly rare for human prose at the scale of an auto-memory store.+// Whitespace-normalized so trivially-different formatting doesn't bypass dedup.+function fingerprintContent(text) {+ if (typeof text !== 'string' || text.length === 0) return '0';+ const norm = text.replace(/\s+/g, ' ').trim().toLowerCase();+ // FNV-1a 64-bit (split into 32-bit halves to stay within Number safe int)+ let h1 = 0x811c9dc5, h2 = 0xcbf29ce4;+ for (let i = 0; i < norm.length; i++) {+ const c = norm.charCodeAt(i);+ h1 ^= c; h1 = Math.imul(h1, 0x01000193) >>> 0;+ h2 ^= c; h2 = Math.imul(h2, 0x100000001b3 & 0xffffffff) >>> 0;+ }+ return `${h1.toString(16)}_${h2.toString(16)}_${norm.length}`;+}++function deduplicateByContent(entries) {+ if (!entries || !Array.isArray(entries)) return entries;+ const seen = new Map();+ for (const entry of entries) {+ const content = entry.content || entry.summary || entry.value || '';+ const fp = fingerprintContent(typeof content === 'string' ? content : JSON.stringify(content));+ if (!seen.has(fp)) {+ seen.set(fp, entry);+ } else {+ // Keep the entry with the higher accessCount or earlier createdAt+ const existing = seen.get(fp);+ const existingAccess = existing.accessCount || 0;+ const candidateAccess = entry.accessCount || 0;+ if (candidateAccess > existingAccess) seen.set(fp, entry);+ }+ }+ return Array.from(seen.values());+}++// ββ Session state helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββ++function sessionGet(key) {+ try {+ if (!fs.existsSync(SESSION_FILE)) return null;+ const session = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8'));+ return key ? (session.context || {})[key] : session.context;+ } catch { return null; }+}++function sessionSet(key, value) {+ try {+ if (!fs.existsSync(SESSION_DIR)) fs.mkdirSync(SESSION_DIR, { recursive: true });+ let session = {};+ if (fs.existsSync(SESSION_FILE)) {+ session = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8'));+ }+ if (!session.context) session.context = {};+ session.context[key] = value;+ session.updatedAt = new Date().toISOString();+ fs.writeFileSync(SESSION_FILE, JSON.stringify(session, null, 2), 'utf-8');+ } catch { /* best effort */ }+}++// ββ PageRank βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++function computePageRank(nodes, edges, damping, maxIter) {+ damping = damping || 0.85;+ maxIter = maxIter || 30;++ const ids = Object.keys(nodes);+ const n = ids.length;+ if (n === 0) return {};++ // Build adjacency: outgoing edges per node+ const outLinks = {};+ const inLinks = {};+ for (const id of ids) { outLinks[id] = []; inLinks[id] = []; }+ for (const edge of edges) {+ if (outLinks[edge.sourceId]) outLinks[edge.sourceId].push(edge.targetId);+ if (inLinks[edge.targetId]) inLinks[edge.targetId].push(edge.sourceId);+ }++ // Initialize ranks+ const ranks = {};+ for (const id of ids) ranks[id] = 1 / n;++ // Power iteration (with dangling node redistribution)+ for (let iter = 0; iter < maxIter; iter++) {+ const newRanks = {};+ let diff = 0;++ // Collect rank from dangling nodes (no outgoing edges)+ let danglingSum = 0;+ for (const id of ids) {+ if (outLinks[id].length === 0) danglingSum += ranks[id];+ }++ for (const id of ids) {+ let sum = 0;+ for (const src of inLinks[id]) {+ const outCount = outLinks[src].length;+ if (outCount > 0) sum += ranks[src] / outCount;+ }+ // Dangling rank distributed evenly + teleport+ newRanks[id] = (1 - damping) / n + damping * (sum + danglingSum / n);+ diff += Math.abs(newRanks[id] - ranks[id]);+ }++ for (const id of ids) ranks[id] = newRanks[id];+ if (diff < 1e-6) break; // converged+ }++ return ranks;+}++// ββ Edge building ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++function buildEdges(entries) {+ const edges = [];+ const byCategory = {};++ for (const entry of entries) {+ const cat = entry.category || entry.namespace || 'default';+ if (!byCategory[cat]) byCategory[cat] = [];+ byCategory[cat].push(entry);+ }++ // Temporal edges: entries from same sourceFile+ const byFile = {};+ for (const entry of entries) {+ const file = (entry.metadata && entry.metadata.sourceFile) || null;+ if (file) {+ if (!byFile[file]) byFile[file] = [];+ byFile[file].push(entry);+ }+ }+ for (const file of Object.keys(byFile)) {+ const group = byFile[file];+ for (let i = 0; i < group.length - 1; i++) {+ edges.push({+ sourceId: group[i].id,+ targetId: group[i + 1].id,+ type: 'temporal',+ weight: 0.5,+ });+ }+ }++ // Similarity edges within categories (Jaccard > 0.3).+ // ADR-095 G6 perf: hoist the trigram computation outside the inner+ // loop. Previously we re-tokenized + re-trigrammed group[j] for every+ // i β O(nΒ²) extra work for nothing. Now compute once per entry.+ for (const cat of Object.keys(byCategory)) {+ const group = byCategory[cat];+ if (group.length < 2) continue;++ // Cache trigram sets for every entry in the group.+ const triCache = new Array(group.length);+ for (let i = 0; i < group.length; i++) {+ triCache[i] = trigrams(tokenize(group[i].content || group[i].summary || ''));+ }++ for (let i = 0; i < group.length; i++) {+ const triA = triCache[i];+ for (let j = i + 1; j < group.length; j++) {+ const sim = jaccardSimilarity(triA, triCache[j]);+ if (sim > 0.3) {+ edges.push({+ sourceId: group[i].id,+ targetId: group[j].id,+ type: 'similar',+ weight: sim,+ });+ }+ }+ }+ }++ return edges;+}++// ββ Bootstrap from MEMORY.md files βββββββββββββββββββββββββββββββββββββββββββ++/**+ * If auto-memory-store.json is empty, bootstrap by parsing MEMORY.md and+ * topic files from the auto-memory directory. This removes the dependency+ * on @claude-flow/memory for the initial seed.+ */function bootstrapFromMemoryFiles() {- var entries = [];- // Scope to current project only (not all 51+ project dirs).- // Match Claude Code's project-dir slug convention: every non-alphanumeric char- // becomes '-' (e.g. "G:\\My Drive\\TJ_Vault" -> "G--My-Drive-TJ-Vault"). The old- // version only stripped a leading '/' and replaced '/', so on Windows the slug- // kept ':' and '\\' and never matched the real ~/.claude/projects/<slug> dir β- // memory bootstrap then silently found nothing (FIX 5). Runs are NOT collapsed:- // Claude emits "G--My" because ':' and '\\' each map to their own '-'.- var projectSlug = process.cwd().replace(/[^a-zA-Z0-9]/g, '-');- var candidates = [- path.join(os.homedir(), ".claude", "projects", projectSlug, "memory"),- path.join(process.cwd(), ".claude-flow", "memory"),- path.join(process.cwd(), ".claude", "memory"),+ const entries = [];+ const cwd = process.cwd();++ // Search for auto-memory directories+ const candidates = [+ // Claude Code auto-memory (project-scoped)+ path.join(require('os').homedir(), '.claude', 'projects'),+ // Local project memory+ path.join(cwd, '.claude-flow', 'memory'),+ path.join(cwd, '.claude', 'memory'),];- for (var i = 0; i < candidates.length; i++) {- try {- if (!fs.existsSync(candidates[i])) continue;- var files = [];++ // Find MEMORY.md in project-scoped dirs+ for (const base of candidates) {+ if (!fs.existsSync(base)) continue;++ // For the projects dir, scope to CURRENT project only (not all 51+ dirs)+ if (base.endsWith('projects')) {try {- var items = fs.readdirSync(candidates[i], { withFileTypes: true, recursive: true });- for (var j = 0; j < items.length; j++) {- if (items[j].name === "MEMORY.md") {- var parentDir = items[j].parentPath || items[j].path || candidates[i];- var fp = path.join(parentDir, items[j].name);- files.push(fp);- }+ // Match Claude Code's project-dir slug: every non-alphanumeric char -> '-'+ // (e.g. "G:\\My Drive\\TJ_Vault" -> "G--My-Drive-TJ-Vault"). The old version+ // only handled POSIX '/', so on Windows the slug kept ':' and '\\' and never+ // matched the real <projects>/<slug>/memory dir β bootstrap found nothing (FIX 5).+ const projectSlug = cwd.replace(/[^a-zA-Z0-9]/g, '-');+ const memDir = path.join(base, projectSlug, 'memory');+ if (fs.existsSync(memDir)) {+ parseMemoryDir(memDir, entries);}- } catch (e) { continue; }- for (var k = 0; k < files.length; k++) {- try {- var content = fs.readFileSync(files[k], "utf-8");- var sections = content.split(/^##\s+/m).filter(function(s) { return s.trim().length > 20; });- for (var s = 0; s < sections.length; s++) {- var lines = sections[s].split("\n");- var title = lines[0] ? lines[0].trim() : "section-" + s;- var clippedContent = clip(sections[s], 500, "memory content");- entries.push({- id: "mem-" + entries.length,- content: clippedContent,- summary: clip(title, 100, "memory summary"),- category: "memory",- confidence: 0.5,- sourceFile: files[k],- words: tokenize(clippedContent),- });- }- } catch (e) { /* skip */ }- }- } catch (e) { /* skip */ }+ } catch { /* skip */ }+ } else if (fs.existsSync(base)) {+ parseMemoryDir(base, entries);+ }}+return entries;}-function loadEntries() {- var store = readJSON(STORE_PATH);- // Support both formats: flat array or { entries: [...] }- var entries = null;- if (store) {- if (Array.isArray(store) && store.length > 0) {- entries = store;- } else if (store.entries && store.entries.length > 0) {- entries = store.entries;+// Truncation transparency (FIX 4): mark the cut with an ellipsis and warn under+// debug, so later reasoning isn't silently built on severed text.+const CLIP_DEBUG = !!(process.env.RUFLO_DEBUG || process.env.DEBUG);+function clip(text, max, label) {+ text = text == null ? '' : String(text);+ if (text.length <= max) return text;+ if (CLIP_DEBUG) process.stderr.write(`[INTELLIGENCE] WARN: truncated ${label || 'value'} from ${text.length} to ${max} chars\n`);+ return text.slice(0, max - 1) + 'β¦';+}++function parseMemoryDir(dir, entries) {+ try {+ const files = fs.readdirSync(dir).filter(f => f.endsWith('.md'));+ for (const file of files) {+ const filePath = path.join(dir, file);+ const content = fs.readFileSync(filePath, 'utf-8');+ if (!content.trim()) continue;++ // Parse markdown sections as separate entries+ const sections = content.split(/^##?\s+/m).filter(Boolean);+ for (let sIdx = 0; sIdx < sections.length; sIdx++) {+ const section = sections[sIdx];+ const lines = section.trim().split('\n');+ const title = lines[0].trim();+ const body = lines.slice(1).join('\n').trim();+ if (!body || body.length < 10) continue;++ const id = `mem-${file.replace('.md', '')}-${title.replace(/[^a-z0-9]/gi, '-').toLowerCase().slice(0, 30)}-${sIdx}`;+ entries.push({+ id,+ key: title.toLowerCase().replace(/[^a-z0-9]+/g, '-').slice(0, 50),+ content: clip(body, 500, 'memory content'),+ summary: title,+ namespace: file === 'MEMORY.md' ? 'core' : file.replace('.md', ''),+ type: 'semantic',+ metadata: { sourceFile: filePath, bootstrapped: true },+ createdAt: Date.now(),+ });+ }+ }+ } catch { /* skip unreadable dirs */ }+}++// ββ Exported functions βββββββββββββββββββββββββββββββββββββββββββββββββββββββ++/**+ * init() β Called from session-restore. Budget: <200ms.+ * Reads auto-memory-store.json, builds graph, computes PageRank, writes caches.+ * If store is empty, bootstraps from MEMORY.md files directly.+ */+function init() {+ ensureDataDir();++ // Check if graph-state.json is fresh (within 60s of store)+ const graphState = readJSON(GRAPH_PATH);+ let store = readJSON(STORE_PATH);++ // Bootstrap from MEMORY.md files if store is empty+ if (!store || !Array.isArray(store) || store.length === 0) {+ const bootstrapped = bootstrapFromMemoryFiles();+ if (bootstrapped.length > 0) {+ store = bootstrapped;+ writeJSON(STORE_PATH, store);+ } else {+ return { nodes: 0, edges: 0, message: 'No memory entries to index' };}}- if (entries) {- return entries.map(function(e, i) {++ // Deduplicate store entries by ID (fixes #1518 β 194MB β ~79KB)+ let deduped = deduplicateById(store);+ // ADR-095 G6: also dedupe by content fingerprint. The April audit+ // measured 5,706 entries with only ~20 unique by content because the+ // same MEMORY.md sections get imported from sibling project dirs with+ // different IDs. deduplicateById can't catch that; deduplicateByContent+ // can. Cuts the graph from O(nΒ²) over near-identical duplicates down+ // to O(uniqueΒ²), which is the difference between a 100MB graph-state+ // and a kilobytes-scale one for typical workloads.+ const beforeContentDedup = deduped.length;+ deduped = deduplicateByContent(deduped);+ if (deduped.length < store.length) {+ process.stderr.write(+ `[INTELLIGENCE] Deduped store: ${store.length} -> ${deduped.length} entries ` ++ `(by-id: ${store.length - beforeContentDedup} dropped, by-content: ${beforeContentDedup - deduped.length} dropped)\n`+ );+ writeJSON(STORE_PATH, deduped);+ }++ // Skip rebuild if graph is fresh and store hasn't changed+ if (graphState && graphState.nodeCount === deduped.length) {+ const age = Date.now() - (graphState.updatedAt || 0);+ if (age < 60000) {return {- id: e.id || ("entry-" + i),- content: e.content || e.value || "",- summary: e.summary || e.key || "",- category: e.category || e.namespace || "default",- confidence: e.confidence || 0.5,- sourceFile: e.sourceFile || (e.metadata && e.metadata.sourceFile) || "",- words: tokenize((e.content || e.value || "") + " " + (e.summary || e.key || "")),+ nodes: graphState.nodeCount || Object.keys(graphState.nodes || {}).length,+ edges: (graphState.edges || []).length,+ message: 'Graph cache hit',};- });- }- return bootstrapFromMemoryFiles();-}--function matchScore(promptWords, entryWords) {- if (!promptWords.length || !entryWords.length) return 0;- var entrySet = {};- for (var i = 0; i < entryWords.length; i++) entrySet[entryWords[i]] = true;- var overlap = 0;- for (var j = 0; j < promptWords.length; j++) {- if (entrySet[promptWords[j]]) overlap++;- }- var union = Object.keys(entrySet).length + promptWords.length - overlap;- return union > 0 ? overlap / union : 0;-}--var cachedEntries = null;--module.exports = {- init: function() {- cachedEntries = deduplicateById(loadEntries());- var ranked = cachedEntries.map(function(e) {- return { id: e.id, content: e.content, summary: e.summary, category: e.category, confidence: e.confidence, words: e.words };- });- writeJSON(RANKED_PATH, { version: 1, computedAt: Date.now(), entries: ranked });- return { nodes: cachedEntries.length, edges: 0 };- },-- getContext: function(prompt) {- if (!prompt) return null;- var ranked = readJSON(RANKED_PATH);- var entries = (ranked && ranked.entries) || (cachedEntries || []);- if (!entries.length) return null;- var promptWords = tokenize(prompt);- if (!promptWords.length) return null;- var scored = entries.map(function(e) {- return { entry: e, score: matchScore(promptWords, e.words || tokenize(e.content + " " + e.summary)) };- }).filter(function(s) { return s.score > 0.05; });- scored.sort(function(a, b) { return b.score - a.score; });- var top = scored.slice(0, 5);- if (!top.length) return null;- var prevMatched = sessionGet("lastMatchedPatterns");- var matchedIds = top.map(function(s) { return s.entry.id; });- sessionSet("lastMatchedPatterns", matchedIds);- var lines = ["[INTELLIGENCE] Relevant patterns for this task:"];- for (var j = 0; j < top.length; j++) {- var e = top[j];- var conf = e.entry.confidence || 0.5;- var summary = (e.entry.summary || e.entry.content || "").substring(0, 80);- lines.push(" * (" + conf.toFixed(2) + ") " + summary);- }- return lines.join("\n");- },-- recordEdit: function(file) {- if (!file) return;- ensureDir(DATA_DIR);- var line = JSON.stringify({ type: "edit", file: file, timestamp: Date.now() }) + "\n";- fs.appendFileSync(PENDING_PATH, line, "utf-8");- },-- feedback: function(success) {- // Stub: no-op in minimal version- },-- consolidate: function() {- var count = 0;- if (fs.existsSync(PENDING_PATH)) {+ }+ }++ // Build nodes from deduped entries+ const nodes = {};+ for (const entry of deduped) {+ const id = entry.id || entry.key || `entry-${Math.random().toString(36).slice(2, 8)}`;+ nodes[id] = {+ id,+ category: entry.namespace || entry.type || 'default',+ confidence: (entry.metadata && entry.metadata.confidence) || 0.5,+ accessCount: (entry.metadata && entry.metadata.accessCount) || 0,+ createdAt: entry.createdAt || Date.now(),+ };+ // Ensure entry has id for edge building+ entry.id = id;+ }++ // Build edges+ const edges = buildEdges(deduped);++ // Compute PageRank (skip if graph too large β #1531)+ const nodeCount = Object.keys(nodes).length;+ let pageRanks = {};+ if (nodeCount > MAX_GRAPH_NODES) {+ process.stderr.write("[INTELLIGENCE] WARN: Graph has " + nodeCount + " nodes (>" + MAX_GRAPH_NODES + "), skipping PageRank\n");+ for (const id of Object.keys(nodes)) pageRanks[id] = 1 / nodeCount;+ } else {+ pageRanks = computePageRank(nodes, edges, 0.85, 30);+ }++ // Write graph state+ const graph = {+ version: 1,+ updatedAt: Date.now(),+ nodeCount: Object.keys(nodes).length,+ nodes,+ edges,+ pageRanks,+ };+ writeJSON(GRAPH_PATH, graph);++ // Build ranked context for fast lookup+ const rankedEntries = deduped.map(entry => {+ const id = entry.id;+ const content = entry.content || entry.value || '';+ const summary = entry.summary || entry.key || '';+ const words = tokenize(content + ' ' + summary);+ return {+ id,+ content,+ summary,+ category: entry.namespace || entry.type || 'default',+ confidence: nodes[id] ? nodes[id].confidence : 0.5,+ pageRank: pageRanks[id] || 0,+ accessCount: nodes[id] ? nodes[id].accessCount : 0,+ words,+ };+ }).sort((a, b) => {+ const scoreA = 0.6 * a.pageRank + 0.4 * a.confidence;+ const scoreB = 0.6 * b.pageRank + 0.4 * b.confidence;+ return scoreB - scoreA;+ });++ const ranked = {+ version: 1,+ computedAt: Date.now(),+ entries: rankedEntries,+ };+ writeJSON(RANKED_PATH, ranked);++ return {+ nodes: Object.keys(nodes).length,+ edges: edges.length,+ message: 'Graph built and ranked',+ };+}++/**+ * getContext(prompt) β Called from route. Budget: <15ms.+ * Matches prompt to ranked entries, returns top-5 formatted context.+ */+function getContext(prompt) {+ if (!prompt) return null;++ const ranked = readJSON(RANKED_PATH);+ if (!ranked || !ranked.entries || ranked.entries.length === 0) return null;++ const promptWords = tokenize(prompt);+ if (promptWords.length === 0) return null;+ const promptTrigrams = trigrams(promptWords);++ const ALPHA = 0.6; // content match weight+ const MIN_THRESHOLD = 0.05;+ const TOP_K = 5;++ // Score each entry+ const scored = [];+ for (const entry of ranked.entries) {+ const entryTrigrams = trigrams(entry.words || []);+ const contentMatch = jaccardSimilarity(promptTrigrams, entryTrigrams);+ const score = ALPHA * contentMatch + (1 - ALPHA) * (entry.pageRank || 0);+ if (score >= MIN_THRESHOLD) {+ scored.push({ ...entry, score });+ }+ }++ if (scored.length === 0) return null;++ // Sort by score descending, take top-K+ scored.sort((a, b) => b.score - a.score);+ const topEntries = scored.slice(0, TOP_K);++ // Boost previously matched patterns (implicit success: user continued working)+ const prevMatched = sessionGet('lastMatchedPatterns');++ // Store NEW matched IDs in session state for feedback+ const matchedIds = topEntries.map(e => e.id);+ sessionSet('lastMatchedPatterns', matchedIds);++ // Only boost previous if they differ from current (avoid double-boosting)+ if (prevMatched && Array.isArray(prevMatched)) {+ const newSet = new Set(matchedIds);+ const toBoost = prevMatched.filter(id => !newSet.has(id));+ if (toBoost.length > 0) boostConfidence(toBoost, 0.03);+ }++ // Format output+ const lines = ['[INTELLIGENCE] Relevant patterns for this task:'];+ for (let i = 0; i < topEntries.length; i++) {+ const e = topEntries[i];+ const display = (e.summary || e.content || '').slice(0, 80);+ const accessed = e.accessCount || 0;+ lines.push(` * (${e.score.toFixed(2)}) ${display} [rank #${i + 1}, ${accessed}x accessed]`);+ }++ return lines.join('\n');+}++/**+ * recordEdit(file) β Called from post-edit. Budget: <2ms.+ * Appends to pending-insights.jsonl.+ */+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,+ });+ fs.appendFileSync(PENDING_PATH, entry + '\n', 'utf-8');+}++/**+ * feedback(success) β Called from post-task. Budget: <10ms.+ * Boosts or decays confidence for last-matched patterns.+ */+function feedback(success) {+ const matchedIds = sessionGet('lastMatchedPatterns');+ if (!matchedIds || !Array.isArray(matchedIds)) return;++ const amount = success ? 0.05 : -0.02;+ boostConfidence(matchedIds, amount);+}++function boostConfidence(ids, amount) {+ const ranked = readJSON(RANKED_PATH);+ if (!ranked || !ranked.entries) return;++ let changed = false;+ for (const entry of ranked.entries) {+ if (ids.includes(entry.id)) {+ entry.confidence = Math.max(0, Math.min(1, (entry.confidence || 0.5) + amount));+ entry.accessCount = (entry.accessCount || 0) + 1;+ changed = true;+ }+ }++ if (changed) writeJSON(RANKED_PATH, ranked);++ // Also update graph-state confidence+ const graph = readJSON(GRAPH_PATH);+ if (graph && graph.nodes) {+ for (const id of ids) {+ if (graph.nodes[id]) {+ graph.nodes[id].confidence = Math.max(0, Math.min(1, (graph.nodes[id].confidence || 0.5) + amount));+ graph.nodes[id].accessCount = (graph.nodes[id].accessCount || 0) + 1;+ }+ }+ writeJSON(GRAPH_PATH, graph);+ }+}++/**+ * consolidate() β Called from session-end. Budget: <500ms.+ * Processes pending insights, rebuilds edges, recomputes PageRank.+ */+function consolidate() {+ ensureDataDir();++ let store = readJSON(STORE_PATH);+ if (!store || !Array.isArray(store)) {+ return { entries: 0, edges: 0, newEntries: 0, message: 'No store to consolidate' };+ }++ // Deduplicate store entries by ID before processing (fixes #1518)+ const preDedupCount = store.length;+ store = deduplicateById(store);++ // 1. Process pending insights+ let newEntries = 0;+ if (fs.existsSync(PENDING_PATH)) {+ const lines = fs.readFileSync(PENDING_PATH, 'utf-8').trim().split('\n').filter(Boolean);+ const editCounts = {};+ for (const line of lines) {try {- var content = fs.readFileSync(PENDING_PATH, "utf-8").trim();- count = content ? content.split("\n").length : 0;- fs.writeFileSync(PENDING_PATH, "", "utf-8");- } catch (e) { /* skip */ }- }- return { entries: count, edges: 0, newEntries: 0 };- },-- stats: function(json) {- var ranked = readJSON(RANKED_PATH);- var count = ranked && ranked.entries ? ranked.entries.length : 0;- if (json) {- console.log(JSON.stringify({ entries: count, computedAt: ranked ? ranked.computedAt : null }));- } else {- console.log('[INTELLIGENCE] Stats: ' + count + ' entries loaded');+ const insight = JSON.parse(line);+ if (insight.file) {+ editCounts[insight.file] = (editCounts[insight.file] || 0) + 1;+ }+ } catch { /* skip malformed */ }+ }++ // Create entries for frequently-edited files (3+ edits)+ for (const [file, count] of Object.entries(editCounts)) {+ if (count >= 3) {+ const exists = store.some(e =>+ (e.metadata && e.metadata.sourceFile === file && e.metadata.autoGenerated)+ );+ if (!exists) {+ store.push({+ id: `insight-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,+ key: `frequent-edit-${path.basename(file)}`,+ content: `File ${file} was edited ${count} times this session β likely a hot path worth monitoring.`,+ summary: `Frequently edited: ${path.basename(file)} (${count}x)`,+ namespace: 'insights',+ type: 'procedural',+ metadata: { sourceFile: file, editCount: count, autoGenerated: true },+ createdAt: Date.now(),+ });+ newEntries++;+ }+ }+ }++ // Clear pending+ fs.writeFileSync(PENDING_PATH, '', 'utf-8');+ }++ // 2. Confidence decay for unaccessed entries+ const graph = readJSON(GRAPH_PATH);+ if (graph && graph.nodes) {+ const now = Date.now();+ for (const id of Object.keys(graph.nodes)) {+ const node = graph.nodes[id];+ const hoursSinceCreation = (now - (node.createdAt || now)) / (1000 * 60 * 60);+ if (node.accessCount === 0 && hoursSinceCreation > 24) {+ node.confidence = Math.max(0.05, (node.confidence || 0.5) - 0.005 * Math.floor(hoursSinceCreation / 24));+ }+ }+ }++ // 3. Rebuild edges with updated store+ for (const entry of store) {+ if (!entry.id) entry.id = `entry-${Math.random().toString(36).slice(2, 8)}`;+ }+ const edges = buildEdges(store);++ // 4. Build updated nodes+ const nodes = {};+ for (const entry of store) {+ nodes[entry.id] = {+ id: entry.id,+ category: entry.namespace || entry.type || 'default',+ confidence: (graph && graph.nodes && graph.nodes[entry.id])+ ? graph.nodes[entry.id].confidence+ : (entry.metadata && entry.metadata.confidence) || 0.5,+ accessCount: (graph && graph.nodes && graph.nodes[entry.id])+ ? graph.nodes[entry.id].accessCount+ : (entry.metadata && entry.metadata.accessCount) || 0,+ createdAt: entry.createdAt || Date.now(),+ };+ }++ // 5. Recompute PageRank (skip if graph too large β #1531)+ const nodeCount = Object.keys(nodes).length;+ let pageRanks = {};+ if (nodeCount > MAX_GRAPH_NODES) {+ process.stderr.write("[INTELLIGENCE] WARN: Graph has " + nodeCount + " nodes (>" + MAX_GRAPH_NODES + "), skipping PageRank in consolidate\n");+ for (const id of Object.keys(nodes)) pageRanks[id] = 1 / nodeCount;+ } else {+ pageRanks = computePageRank(nodes, edges, 0.85, 30);+ }++ // 6. Write updated graph+ writeJSON(GRAPH_PATH, {+ version: 1,+ updatedAt: Date.now(),+ nodeCount: Object.keys(nodes).length,+ nodes,+ edges,+ pageRanks,+ });++ // 7. Write updated ranked context+ const rankedEntries = store.map(entry => {+ const id = entry.id;+ const content = entry.content || entry.value || '';+ const summary = entry.summary || entry.key || '';+ const words = tokenize(content + ' ' + summary);+ return {+ id,+ content,+ summary,+ category: entry.namespace || entry.type || 'default',+ confidence: nodes[id] ? nodes[id].confidence : 0.5,+ pageRank: pageRanks[id] || 0,+ accessCount: nodes[id] ? nodes[id].accessCount : 0,+ words,+ };+ }).sort((a, b) => {+ const scoreA = 0.6 * a.pageRank + 0.4 * a.confidence;+ const scoreB = 0.6 * b.pageRank + 0.4 * b.confidence;+ return scoreB - scoreA;+ });++ writeJSON(RANKED_PATH, {+ version: 1,+ computedAt: Date.now(),+ entries: rankedEntries,+ });++ // 8. Persist updated store (deduped or with new insight entries)+ if (newEntries > 0 || store.length < preDedupCount) writeJSON(STORE_PATH, store);++ // 9. Save snapshot for delta tracking+ const updatedGraph = readJSON(GRAPH_PATH);+ const updatedRanked = readJSON(RANKED_PATH);+ saveSnapshot(updatedGraph, updatedRanked);++ return {+ entries: store.length,+ edges: edges.length,+ newEntries,+ message: 'Consolidated',+ };+}++// ββ Snapshot for delta tracking βββββββββββββββββββββββββββββββββββββββββββββ++const SNAPSHOT_PATH = path.join(DATA_DIR, 'intelligence-snapshot.json');++function saveSnapshot(graph, ranked) {+ const snap = {+ timestamp: Date.now(),+ nodes: graph ? Object.keys(graph.nodes || {}).length : 0,+ edges: graph ? (graph.edges || []).length : 0,+ pageRankSum: 0,+ confidences: [],+ accessCounts: [],+ topPatterns: [],+ };++ if (graph && graph.pageRanks) {+ for (const v of Object.values(graph.pageRanks)) snap.pageRankSum += v;+ }+ if (graph && graph.nodes) {+ for (const n of Object.values(graph.nodes)) {+ snap.confidences.push(n.confidence || 0.5);+ snap.accessCounts.push(n.accessCount || 0);+ }+ }+ if (ranked && ranked.entries) {+ snap.topPatterns = ranked.entries.slice(0, 10).map(e => ({+ id: e.id,+ summary: (e.summary || '').slice(0, 60),+ confidence: e.confidence || 0.5,+ pageRank: e.pageRank || 0,+ accessCount: e.accessCount || 0,+ }));+ }++ // Keep history: append to array, cap at 50+ let history = readJSON(SNAPSHOT_PATH);+ if (!Array.isArray(history)) history = [];+ history.push(snap);+ if (history.length > 50) history = history.slice(-50);+ writeJSON(SNAPSHOT_PATH, history);+}++/**+ * stats() β Diagnostic report showing intelligence health and improvement.+ * Can be called as: node intelligence.cjs stats [--json]+ */+function stats(outputJson) {+ const graph = readJSON(GRAPH_PATH);+ const ranked = readJSON(RANKED_PATH);+ const history = readJSON(SNAPSHOT_PATH) || [];+ const pending = fs.existsSync(PENDING_PATH)+ ? fs.readFileSync(PENDING_PATH, 'utf-8').trim().split('\n').filter(Boolean).length+ : 0;++ // Current state+ const nodes = graph ? Object.keys(graph.nodes || {}).length : 0;+ const edges = graph ? (graph.edges || []).length : 0;+ const density = nodes > 1 ? (2 * edges) / (nodes * (nodes - 1)) : 0;++ // Confidence distribution+ const confidences = [];+ const accessCounts = [];+ if (graph && graph.nodes) {+ for (const n of Object.values(graph.nodes)) {+ confidences.push(n.confidence || 0.5);+ accessCounts.push(n.accessCount || 0);+ }+ }+ confidences.sort((a, b) => a - b);+ const confMin = confidences.length ? confidences[0] : 0;+ const confMax = confidences.length ? confidences[confidences.length - 1] : 0;+ const confMean = confidences.length ? confidences.reduce((s, c) => s + c, 0) / confidences.length : 0;+ const confMedian = confidences.length ? confidences[Math.floor(confidences.length / 2)] : 0;++ // Access stats+ const totalAccess = accessCounts.reduce((s, c) => s + c, 0);+ const accessedCount = accessCounts.filter(c => c > 0).length;++ // PageRank stats+ let prSum = 0, prMax = 0, prMaxId = '';+ if (graph && graph.pageRanks) {+ for (const [id, pr] of Object.entries(graph.pageRanks)) {+ prSum += pr;+ if (pr > prMax) { prMax = pr; prMaxId = id; }+ }+ }++ // Top patterns by composite score+ const topPatterns = (ranked && ranked.entries || []).slice(0, 10).map((e, i) => ({+ rank: i + 1,+ summary: (e.summary || '').slice(0, 60),+ confidence: (e.confidence || 0.5).toFixed(3),+ pageRank: (e.pageRank || 0).toFixed(4),+ accessed: e.accessCount || 0,+ score: (0.6 * (e.pageRank || 0) + 0.4 * (e.confidence || 0.5)).toFixed(4),+ }));++ // Edge type breakdown+ const edgeTypes = {};+ if (graph && graph.edges) {+ for (const e of graph.edges) {+ edgeTypes[e.type || 'unknown'] = (edgeTypes[e.type || 'unknown'] || 0) + 1;+ }+ }++ // Delta from previous snapshot+ let delta = null;+ if (history.length >= 2) {+ const prev = history[history.length - 2];+ const curr = history[history.length - 1];+ const elapsed = (curr.timestamp - prev.timestamp) / 1000;+ const prevConfMean = prev.confidences.length+ ? prev.confidences.reduce((s, c) => s + c, 0) / prev.confidences.length : 0;+ const currConfMean = curr.confidences.length+ ? curr.confidences.reduce((s, c) => s + c, 0) / curr.confidences.length : 0;+ const prevAccess = prev.accessCounts.reduce((s, c) => s + c, 0);+ const currAccess = curr.accessCounts.reduce((s, c) => s + c, 0);++ delta = {+ elapsed: elapsed < 3600 ? `${Math.round(elapsed / 60)}m` : `${(elapsed / 3600).toFixed(1)}h`,+ nodes: curr.nodes - prev.nodes,+ edges: curr.edges - prev.edges,+ confidenceMean: currConfMean - prevConfMean,+ totalAccess: currAccess - prevAccess,+ };+ }++ // Trend over all history+ let trend = null;+ if (history.length >= 3) {+ const first = history[0];+ const last = history[history.length - 1];+ const sessions = history.length;+ const firstConfMean = first.confidences.length+ ? first.confidences.reduce((s, c) => s + c, 0) / first.confidences.length : 0;+ const lastConfMean = last.confidences.length+ ? last.confidences.reduce((s, c) => s + c, 0) / last.confidences.length : 0;+ trend = {+ sessions,+ nodeGrowth: last.nodes - first.nodes,+ edgeGrowth: last.edges - first.edges,+ confidenceDrift: lastConfMean - firstConfMean,+ direction: lastConfMean > firstConfMean ? 'improving' :+ lastConfMean < firstConfMean ? 'declining' : 'stable',+ };+ }++ const report = {+ graph: { nodes, edges, density: +density.toFixed(4) },+ confidence: {+ min: +confMin.toFixed(3), max: +confMax.toFixed(3),+ mean: +confMean.toFixed(3), median: +confMedian.toFixed(3),+ },+ access: { total: totalAccess, patternsAccessed: accessedCount, patternsNeverAccessed: nodes - accessedCount },+ pageRank: { sum: +prSum.toFixed(4), topNode: prMaxId, topNodeRank: +prMax.toFixed(4) },+ edgeTypes,+ pendingInsights: pending,+ snapshots: history.length,+ topPatterns,+ delta,+ trend,+ };++ if (outputJson) {+ console.log(JSON.stringify(report, null, 2));+ return report;+ }++ // Human-readable output+ const bar = '+' + '-'.repeat(62) + '+';+ console.log(bar);+ console.log('|' + ' Intelligence Diagnostics (ADR-050)'.padEnd(62) + '|');+ console.log(bar);+ console.log('');++ console.log(' Graph');+ console.log(` Nodes: ${nodes}`);+ console.log(` Edges: ${edges} (${Object.entries(edgeTypes).map(([t,c]) => `${c} ${t}`).join(', ') || 'none'})`);+ console.log(` Density: ${(density * 100).toFixed(1)}%`);+ console.log('');++ console.log(' Confidence');+ console.log(` Min: ${confMin.toFixed(3)}`);+ console.log(` Max: ${confMax.toFixed(3)}`);+ console.log(` Mean: ${confMean.toFixed(3)}`);+ console.log(` Median: ${confMedian.toFixed(3)}`);+ console.log('');++ console.log(' Access');+ console.log(` Total accesses: ${totalAccess}`);+ console.log(` Patterns used: ${accessedCount}/${nodes}`);+ console.log(` Never accessed: ${nodes - accessedCount}`);+ console.log(` Pending insights: ${pending}`);+ console.log('');++ console.log(' PageRank');+ console.log(` Sum: ${prSum.toFixed(4)} (should be ~1.0)`);+ console.log(` Top node: ${prMaxId || '(none)'} (${prMax.toFixed(4)})`);+ console.log('');++ if (topPatterns.length > 0) {+ console.log(' Top Patterns (by composite score)');+ console.log(' ' + '-'.repeat(60));+ for (const p of topPatterns) {+ console.log(` #${p.rank} ${p.summary}`);+ console.log(` conf=${p.confidence} pr=${p.pageRank} score=${p.score} accessed=${p.accessed}x`);}- },-};+ console.log('');+ }++ if (delta) {+ console.log(` Last Delta (${delta.elapsed} ago)`);+ const sign = v => v > 0 ? `+${v}` : `${v}`;+ console.log(` Nodes: ${sign(delta.nodes)}`);+ console.log(` Edges: ${sign(delta.edges)}`);+ console.log(` Confidence: ${delta.confidenceMean >= 0 ? '+' : ''}${delta.confidenceMean.toFixed(4)}`);+ console.log(` Accesses: ${sign(delta.totalAccess)}`);+ console.log('');+ }++ if (trend) {+ console.log(` Trend (${trend.sessions} snapshots)`);+ console.log(` Node growth: ${trend.nodeGrowth >= 0 ? '+' : ''}${trend.nodeGrowth}`);+ console.log(` Edge growth: ${trend.edgeGrowth >= 0 ? '+' : ''}${trend.edgeGrowth}`);+ console.log(` Confidence drift: ${trend.confidenceDrift >= 0 ? '+' : ''}${trend.confidenceDrift.toFixed(4)}`);+ console.log(` Direction: ${trend.direction.toUpperCase()}`);+ console.log('');+ }++ if (!delta && !trend) {+ console.log(' No history yet β run more sessions to see deltas and trends.');+ console.log('');+ }++ console.log(bar);+ return report;+}++module.exports = { init, getContext, recordEdit, feedback, consolidate, stats };++// ββ CLI entrypoint ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+if (require.main === module) {+ const cmd = process.argv[2];+ const jsonFlag = process.argv.includes('--json');++ const cmds = {+ init: () => { const r = init(); console.log(JSON.stringify(r)); },+ stats: () => { stats(jsonFlag); },+ consolidate: () => { const r = consolidate(); console.log(JSON.stringify(r)); },+ };++ if (cmd && cmds[cmd]) {+ cmds[cmd]();+ } else {+ console.log('Usage: intelligence.cjs <stats|init|consolidate> [--json]');+ console.log('');+ console.log(' stats Show intelligence diagnostics and trends');+ console.log(' stats --json Output as JSON for programmatic use');+ console.log(' init Build graph and rank entries');+ console.log(' consolidate Process pending insights and recompute');+ }+}diff --git a/.gitignore b/.gitignoreindex 39ce8bc185..29b0ec55e3 100644--- a/.gitignore+++ b/.gitignore@@ -171,3 +171,9 @@ hive-mind-prompt-*.txt# Publish-artifact mirror β regenerated by prepublishOnly (package.json:90); never edit or commitv3/@claude-flow/cli/plugins/++# Runtime artifacts of the version-stamped helper auto-refresh (ADR-174) β+# regenerated on demand, not source. The signed manifest source of truth lives+# in v3/@claude-flow/cli/.claude/helpers/helpers.manifest.json.+.claude/helpers/.helpers-version+.claude/helpers/helpers.manifest.json