🌊 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
fix(auto-memory): hooks deliver their subcommand, sync sees learnings, worktrees share the main memory dir, writes are atomic (#4058)
rceed62b1b410
diff --git a/.claude/helpers/auto-memory-hook.mjs b/.claude/helpers/auto-memory-hook.mjsindex 58ea812470..a16670d6cf 100755--- a/.claude/helpers/auto-memory-hook.mjs+++ b/.claude/helpers/auto-memory-hook.mjs@@ -11,8 +11,10 @@* node auto-memory-hook.mjs status # Show bridge status*/-import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';-import { join, dirname, resolve } from 'path';+import { existsSync, mkdirSync, readFileSync, writeFileSync, renameSync, unlinkSync, rmdirSync, rmSync, statSync } from 'fs';+import { execFileSync } from 'child_process';+import { homedir } from 'os';+import { join, dirname, resolve, sep } from 'path';import { fileURLToPath } from 'url';const __filename = fileURLToPath(import.meta.url);@@ -77,6 +79,66 @@ process.on('SIGINT', () => { gracefulExit('SIGINT'); });// Ensure data dirif (!existsSync(DATA_DIR)) mkdirSync(DATA_DIR, { recursive: true });+// ============================================================================+// Store write safety (#4058): intelligence.cjs read-modify-writes the same+// file from the session-end hook, so writes are atomic (temp + rename) and+// serialised by a short directory lock. The lock is advisory and fails open:+// a hook must never hang, so after ~2 s it proceeds without it.+// ============================================================================++const LOCK_WAIT_MS = 2000;+const LOCK_STALE_MS = 10000;+function sleepSync(ms) { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); }++function withStoreLock(storePath, fn) {+ const lock = storePath + '.lock';+ const deadline = Date.now() + LOCK_WAIT_MS;+ let held = false;+ for (;;) {+ try { mkdirSync(lock); held = true; break; } catch (e) {+ if (!e || e.code !== 'EEXIST') break;+ try {+ if (Date.now() - statSync(lock).mtimeMs > LOCK_STALE_MS) { rmSync(lock, { recursive: true, force: true }); continue; }+ } catch { /* lock vanished: retry */ }+ if (Date.now() > deadline) break;+ sleepSync(10);+ }+ }+ try { return fn(); } finally { if (held) { try { rmdirSync(lock); } catch { /* already gone */ } } }+}++function writeFileAtomic(filePath, text) {+ const tmp = filePath + '.' + process.pid + '.tmp';+ try {+ writeFileSync(tmp, text, 'utf-8');+ renameSync(tmp, filePath);+ } catch (e) {+ try { unlinkSync(tmp); } catch { /* nothing to clean */ }+ throw e;+ }+}++// Claude Code shares one auto-memory directory across every worktree of a+// repository, but findGitRoot() in the memory package stops at a worktree's+// `.git` FILE and keys the directory by the worktree path (#4058). Resolve the+// main checkout through git's common dir so both agree. No shell is involved.+function mainCheckoutRoot(dir) {+ try {+ if (!statSync(join(dir, '.git')).isFile()) return null;+ const common = execFileSync('git', ['rev-parse', '--git-common-dir'], { cwd: dir, encoding: 'utf8', timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'] }).trim();+ if (!common) return null;+ const abs = resolve(dir, common);+ return abs.endsWith('/.git') || abs.endsWith('\\.git') ? dirname(abs) : null;+ } catch { return null; }+}++function worktreeMemoryDir() {+ const main = mainCheckoutRoot(PROJECT_ROOT);+ if (!main) return undefined;+ const key = main.split(sep).join('/').replace(/[\/_:]/g, '-');+ return join(process.env.HOME || process.env.USERPROFILE || homedir(), '.claude', 'projects', key, 'memory');+}+// ============================================================================// Simple JSON File Backend (implements IMemoryBackend interface)// ============================================================================@@ -85,6 +147,8 @@ class JsonFileBackend {constructor(filePath) {this.filePath = filePath;this.entries = new Map();+ this.loadedIds = new Set();+ this.deletedIds = new Set();}async initialize() {@@ -92,7 +156,7 @@ class JsonFileBackend {try {const data = JSON.parse(readFileSync(this.filePath, 'utf-8'));if (Array.isArray(data)) {- for (const entry of data) this.entries.set(entry.id, entry);+ for (const entry of data) { this.entries.set(entry.id, entry); this.loadedIds.add(entry.id); }}} catch { /* start fresh */ }}@@ -117,17 +181,26 @@ class JsonFileBackend {this._persist();return e;}- async delete(id) { return this.entries.delete(id); }+ async delete(id) { this.deletedIds.add(id); return this.entries.delete(id); }async query(opts) {let results = [...this.entries.values()];if (opts?.namespace) results = results.filter(e => e.namespace === opts.namespace);- if (opts?.type) results = results.filter(e => e.type === opts.type);+ // MemoryQuery.type is the query mode (semantic|exact|prefix|tag|hybrid), not+ // the entry's memory type: the bridge asks for { type: 'hybrid' } and a strict+ // entry-type match returned nothing, so sync always reported 0 (#4058).+ const MODES = ['semantic', 'exact', 'prefix', 'tag', 'hybrid'];+ if (opts?.type && !MODES.includes(opts.type)) results = results.filter(e => e.type === opts.type);+ if (opts?.memoryType) results = results.filter(e => e.type === opts.memoryType);+ if (opts?.key) results = results.filter(e => e.key === opts.key);+ if (opts?.keyPrefix) results = results.filter(e => typeof e.key === 'string' && e.key.startsWith(opts.keyPrefix));+ if (Array.isArray(opts?.tags) && opts.tags.length) results = results.filter(e => opts.tags.every(t => (e.tags || []).includes(t)));+ if (opts?.updatedAfter) results = results.filter(e => (e.updatedAt || 0) > opts.updatedAfter);if (opts?.limit) results = results.slice(0, opts.limit);return results;}async search() { return []; } // No vector search in JSON backendasync bulkInsert(entries) { for (const e of entries) this.entries.set(e.id, e); this._persist(); }- async bulkDelete(ids) { let n = 0; for (const id of ids) { if (this.entries.delete(id)) n++; } this._persist(); return n; }+ async bulkDelete(ids) { let n = 0; for (const id of ids) { this.deletedIds.add(id); if (this.entries.delete(id)) n++; } this._persist(); return n; }async count() { return this.entries.size; }async listNamespaces() {const ns = new Set();@@ -137,7 +210,7 @@ class JsonFileBackend {async clearNamespace(ns) {let n = 0;for (const [id, e] of this.entries) {- if (e.namespace === ns) { this.entries.delete(id); n++; }+ if (e.namespace === ns) { this.deletedIds.add(id); this.entries.delete(id); n++; }}this._persist();return n;@@ -164,7 +237,22 @@ class JsonFileBackend {_persist() {try {- writeFileSync(this.filePath, JSON.stringify([...this.entries.values()], null, 2), 'utf-8');+ withStoreLock(this.filePath, () => {+ // Keep entries another writer (intelligence.cjs, a parallel hook) added+ // after we loaded; ours win on the same id, and our own deletes stay deleted.+ const merged = new Map(this.entries);+ try {+ const onDisk = JSON.parse(readFileSync(this.filePath, 'utf-8'));+ if (Array.isArray(onDisk)) {+ for (const e of onDisk) {+ if (e && !merged.has(e.id) && !this.loadedIds.has(e.id) && !this.deletedIds.has(e.id)) merged.set(e.id, e);+ }+ }+ } catch { /* missing or unreadable: write ours */ }+ writeFileAtomic(this.filePath, JSON.stringify([...merged.values()], null, 2));+ for (const id of merged.keys()) this.loadedIds.add(id);+ this.entries = merged;+ });} catch { /* best effort */ }}}@@ -284,6 +372,8 @@ async function doImport() {workingDir: PROJECT_ROOT,syncMode: 'on-session-end',};+ const wtDir = worktreeMemoryDir();+ if (wtDir) bridgeConfig.memoryDir = wtDir;// Wire learning if enabled and availableif (config.learningBridge.enabled && memPkg.LearningBridge) {@@ -344,6 +434,8 @@ async function doSync() {workingDir: PROJECT_ROOT,syncMode: 'on-session-end',};+ const wtDir = worktreeMemoryDir();+ if (wtDir) bridgeConfig.memoryDir = wtDir;if (config.learningBridge.enabled && memPkg.LearningBridge) {bridgeConfig.learning = {@@ -369,8 +461,11 @@ async function doSync() {dim(`└─ Backend entries: ${entryCount}`);// Curate MEMORY.md index with graph-aware ordering+ let indexSkipped = null;+ if (typeof bridge.on === 'function') bridge.on('index:skipped', (info) => { indexSkipped = info; });await bridge.curateIndex();- success('Curated MEMORY.md index');+ if (indexSkipped) dim(`MEMORY.md index unchanged (${indexSkipped.reason || 'nothing to curate'})`);+ else success('Curated MEMORY.md index');} catch (err) {dim(`Sync failed (non-critical): ${err.message}`);}@@ -408,7 +503,11 @@ async function doStatus() {// Main// ============================================================================-const command = process.argv[2] || 'status';+// Older settings.json files run `node -e "…import(file)" import`, where the+// subcommand lands in argv[1] and argv[2] is empty, so both hooks fell through+// to `status` and never imported or synced (#4058). Accept that shape too.+const COMMANDS = ['import', 'sync', 'status'];+const command = process.argv[2] || (COMMANDS.includes(process.argv[1]) ? process.argv[1] : 'status');// Dynamic import() failures can surface as unhandled rejections on a later// microtask even when the awaiting call site already caught them, which woulddiff --git a/.claude/helpers/intelligence.cjs b/.claude/helpers/intelligence.cjsindex 4c1e4d432b..4266dfa67a 100755--- a/.claude/helpers/intelligence.cjs+++ b/.claude/helpers/intelligence.cjs@@ -108,9 +108,54 @@ function readJSON(filePath) {return null;}+// Atomic (temp + rename): auto-memory-hook.mjs reads and writes the same store+// from the session hooks, and a reader must never see a half-written file (#4058).function writeJSON(filePath, data) {ensureDataDir();- fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf-8');+ const tmp = filePath + '.' + process.pid + '.tmp';+ try {+ fs.writeFileSync(tmp, JSON.stringify(data, null, 2), 'utf-8');+ fs.renameSync(tmp, filePath);+ } catch (e) {+ try { fs.unlinkSync(tmp); } catch { /* nothing to clean */ }+ throw e;+ }+}++// Short advisory directory lock shared with auto-memory-hook.mjs. It fails open+// after ~2 s so a stuck lock can never hang a hook.+function withStoreLock(filePath, fn) {+ const lock = filePath + '.lock';+ const deadline = Date.now() + 2000;+ let held = false;+ for (;;) {+ try { fs.mkdirSync(lock); held = true; break; } catch (e) {+ if (!e || e.code !== 'EEXIST') break;+ try {+ if (Date.now() - fs.statSync(lock).mtimeMs > 10000) { fs.rmSync(lock, { recursive: true, force: true }); continue; }+ } catch { /* lock vanished: retry */ }+ if (Date.now() > deadline) break;+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10);+ }+ }+ try { return fn(); } finally { if (held) { try { fs.rmdirSync(lock); } catch { /* already gone */ } } }+}++// Write the store, keeping entries another writer added after we read it.+function writeStoreMerged(filePath, next, loaded) {+ const loadedIds = new Set((Array.isArray(loaded) ? loaded : []).map((e) => e && e.id));+ withStoreLock(filePath, () => {+ let out = next;+ try {+ const current = JSON.parse(fs.readFileSync(filePath, 'utf-8'));+ if (Array.isArray(current)) {+ const have = new Set(next.map((e) => e && e.id));+ const added = current.filter((e) => e && !loadedIds.has(e.id) && !have.has(e.id));+ if (added.length) out = next.concat(added);+ }+ } catch { /* missing or unreadable: write ours */ }+ writeJSON(filePath, out);+ });}function tokenize(text) {@@ -481,7 +526,7 @@ function init() {const bootstrapped = bootstrapFromMemoryFiles();if (bootstrapped.length > 0) {store = bootstrapped;- writeJSON(STORE_PATH, store);+ writeStoreMerged(STORE_PATH, store, []);} else {return { nodes: 0, edges: 0, message: 'No memory entries to index' };}@@ -503,7 +548,7 @@ function init() {`[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);+ writeStoreMerged(STORE_PATH, deduped, store);}// Skip rebuild if graph is fresh and store hasn't changed. #2920: nodeCount@@ -834,6 +879,7 @@ function consolidate() {return { entries: 0, edges: 0, newEntries: 0, message: 'No store to consolidate' };}+ const loadedStore = store;// Deduplicate store entries by ID before processing (fixes #1518)const preDedupCount = store.length;store = deduplicateById(store);@@ -979,7 +1025,7 @@ function consolidate() {// RANKED_PATH are rewritten unconditionally just above; writing the// (already deduped, size-bounded per ADR-095 G6) store alongside them// costs nothing near the <500ms budget and removes the whole bug class.- writeJSON(STORE_PATH, store);+ writeStoreMerged(STORE_PATH, store, loadedStore);// 9. Save snapshot for delta trackingconst updatedGraph = readJSON(GRAPH_PATH);diff --git a/v3/@claude-flow/cli/.claude/helpers/auto-memory-hook.mjs b/v3/@claude-flow/cli/.claude/helpers/auto-memory-hook.mjsindex 85917f9167..132004a42a 100755--- a/v3/@claude-flow/cli/.claude/helpers/auto-memory-hook.mjs+++ b/v3/@claude-flow/cli/.claude/helpers/auto-memory-hook.mjs@@ -11,8 +11,10 @@* node auto-memory-hook.mjs status # Show bridge status*/-import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';-import { join, dirname, resolve } from 'path';+import { existsSync, mkdirSync, readFileSync, writeFileSync, renameSync, unlinkSync, rmdirSync, rmSync, statSync } from 'fs';+import { execFileSync } from 'child_process';+import { homedir } from 'os';+import { join, dirname, resolve, sep } from 'path';import { fileURLToPath } from 'url';const __filename = fileURLToPath(import.meta.url);@@ -77,6 +79,66 @@ process.on('SIGINT', () => { gracefulExit('SIGINT'); });// Ensure data dirif (!existsSync(DATA_DIR)) mkdirSync(DATA_DIR, { recursive: true });+// ============================================================================+// Store write safety (#4058): intelligence.cjs read-modify-writes the same+// file from the session-end hook, so writes are atomic (temp + rename) and+// serialised by a short directory lock. The lock is advisory and fails open:+// a hook must never hang, so after ~2 s it proceeds without it.+// ============================================================================++const LOCK_WAIT_MS = 2000;+const LOCK_STALE_MS = 10000;+function sleepSync(ms) { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); }++function withStoreLock(storePath, fn) {+ const lock = storePath + '.lock';+ const deadline = Date.now() + LOCK_WAIT_MS;+ let held = false;+ for (;;) {+ try { mkdirSync(lock); held = true; break; } catch (e) {+ if (!e || e.code !== 'EEXIST') break;+ try {+ if (Date.now() - statSync(lock).mtimeMs > LOCK_STALE_MS) { rmSync(lock, { recursive: true, force: true }); continue; }+ } catch { /* lock vanished: retry */ }+ if (Date.now() > deadline) break;+ sleepSync(10);+ }+ }+ try { return fn(); } finally { if (held) { try { rmdirSync(lock); } catch { /* already gone */ } } }+}++function writeFileAtomic(filePath, text) {+ const tmp = filePath + '.' + process.pid + '.tmp';+ try {+ writeFileSync(tmp, text, 'utf-8');+ renameSync(tmp, filePath);+ } catch (e) {+ try { unlinkSync(tmp); } catch { /* nothing to clean */ }+ throw e;+ }+}++// Claude Code shares one auto-memory directory across every worktree of a+// repository, but findGitRoot() in the memory package stops at a worktree's+// `.git` FILE and keys the directory by the worktree path (#4058). Resolve the+// main checkout through git's common dir so both agree. No shell is involved.+function mainCheckoutRoot(dir) {+ try {+ if (!statSync(join(dir, '.git')).isFile()) return null;+ const common = execFileSync('git', ['rev-parse', '--git-common-dir'], { cwd: dir, encoding: 'utf8', timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'] }).trim();+ if (!common) return null;+ const abs = resolve(dir, common);+ return abs.endsWith('/.git') || abs.endsWith('\\.git') ? dirname(abs) : null;+ } catch { return null; }+}++function worktreeMemoryDir() {+ const main = mainCheckoutRoot(PROJECT_ROOT);+ if (!main) return undefined;+ const key = main.split(sep).join('/').replace(/[\/_:]/g, '-');+ return join(process.env.HOME || process.env.USERPROFILE || homedir(), '.claude', 'projects', key, 'memory');+}+// ============================================================================// Simple JSON File Backend (implements IMemoryBackend interface)// ============================================================================@@ -85,6 +147,8 @@ class JsonFileBackend {constructor(filePath) {this.filePath = filePath;this.entries = new Map();+ this.loadedIds = new Set();+ this.deletedIds = new Set();}async initialize() {@@ -92,7 +156,7 @@ class JsonFileBackend {try {const data = JSON.parse(readFileSync(this.filePath, 'utf-8'));if (Array.isArray(data)) {- for (const entry of data) this.entries.set(entry.id, entry);+ for (const entry of data) { this.entries.set(entry.id, entry); this.loadedIds.add(entry.id); }}} catch { /* start fresh */ }}@@ -117,17 +181,26 @@ class JsonFileBackend {this._persist();return e;}- async delete(id) { return this.entries.delete(id); }+ async delete(id) { this.deletedIds.add(id); return this.entries.delete(id); }async query(opts) {let results = [...this.entries.values()];if (opts?.namespace) results = results.filter(e => e.namespace === opts.namespace);- if (opts?.type) results = results.filter(e => e.type === opts.type);+ // MemoryQuery.type is the query mode (semantic|exact|prefix|tag|hybrid), not+ // the entry's memory type: the bridge asks for { type: 'hybrid' } and a strict+ // entry-type match returned nothing, so sync always reported 0 (#4058).+ const MODES = ['semantic', 'exact', 'prefix', 'tag', 'hybrid'];+ if (opts?.type && !MODES.includes(opts.type)) results = results.filter(e => e.type === opts.type);+ if (opts?.memoryType) results = results.filter(e => e.type === opts.memoryType);+ if (opts?.key) results = results.filter(e => e.key === opts.key);+ if (opts?.keyPrefix) results = results.filter(e => typeof e.key === 'string' && e.key.startsWith(opts.keyPrefix));+ if (Array.isArray(opts?.tags) && opts.tags.length) results = results.filter(e => opts.tags.every(t => (e.tags || []).includes(t)));+ if (opts?.updatedAfter) results = results.filter(e => (e.updatedAt || 0) > opts.updatedAfter);if (opts?.limit) results = results.slice(0, opts.limit);return results;}async search() { return []; } // No vector search in JSON backendasync bulkInsert(entries) { for (const e of entries) this.entries.set(e.id, e); this._persist(); }- async bulkDelete(ids) { let n = 0; for (const id of ids) { if (this.entries.delete(id)) n++; } this._persist(); return n; }+ async bulkDelete(ids) { let n = 0; for (const id of ids) { this.deletedIds.add(id); if (this.entries.delete(id)) n++; } this._persist(); return n; }async count() { return this.entries.size; }async listNamespaces() {const ns = new Set();@@ -137,7 +210,7 @@ class JsonFileBackend {async clearNamespace(ns) {let n = 0;for (const [id, e] of this.entries) {- if (e.namespace === ns) { this.entries.delete(id); n++; }+ if (e.namespace === ns) { this.deletedIds.add(id); this.entries.delete(id); n++; }}this._persist();return n;@@ -164,7 +237,22 @@ class JsonFileBackend {_persist() {try {- writeFileSync(this.filePath, JSON.stringify([...this.entries.values()], null, 2), 'utf-8');+ withStoreLock(this.filePath, () => {+ // Keep entries another writer (intelligence.cjs, a parallel hook) added+ // after we loaded; ours win on the same id, and our own deletes stay deleted.+ const merged = new Map(this.entries);+ try {+ const onDisk = JSON.parse(readFileSync(this.filePath, 'utf-8'));+ if (Array.isArray(onDisk)) {+ for (const e of onDisk) {+ if (e && !merged.has(e.id) && !this.loadedIds.has(e.id) && !this.deletedIds.has(e.id)) merged.set(e.id, e);+ }+ }+ } catch { /* missing or unreadable: write ours */ }+ writeFileAtomic(this.filePath, JSON.stringify([...merged.values()], null, 2));+ for (const id of merged.keys()) this.loadedIds.add(id);+ this.entries = merged;+ });} catch { /* best effort */ }}}@@ -284,6 +372,8 @@ async function doImport() {workingDir: PROJECT_ROOT,syncMode: 'on-session-end',};+ const wtDir = worktreeMemoryDir();+ if (wtDir) bridgeConfig.memoryDir = wtDir;// Wire learning if enabled and availableif (config.learningBridge.enabled && memPkg.LearningBridge) {@@ -344,6 +434,8 @@ async function doSync() {workingDir: PROJECT_ROOT,syncMode: 'on-session-end',};+ const wtDir = worktreeMemoryDir();+ if (wtDir) bridgeConfig.memoryDir = wtDir;if (config.learningBridge.enabled && memPkg.LearningBridge) {bridgeConfig.learning = {@@ -369,8 +461,11 @@ async function doSync() {dim(`└─ Backend entries: ${entryCount}`);// Curate MEMORY.md index with graph-aware ordering+ let indexSkipped = null;+ if (typeof bridge.on === 'function') bridge.on('index:skipped', (info) => { indexSkipped = info; });await bridge.curateIndex();- success('Curated MEMORY.md index');+ if (indexSkipped) dim(`MEMORY.md index unchanged (${indexSkipped.reason || 'nothing to curate'})`);+ else success('Curated MEMORY.md index');} catch (err) {dim(`Sync failed (non-critical): ${err.message}`);}@@ -408,7 +503,11 @@ async function doStatus() {// Main// ============================================================================-const command = process.argv[2] || 'status';+// Older settings.json files run `node -e "…import(file)" import`, where the+// subcommand lands in argv[1] and argv[2] is empty, so both hooks fell through+// to `status` and never imported or synced (#4058). Accept that shape too.+const COMMANDS = ['import', 'sync', 'status'];+const command = process.argv[2] || (COMMANDS.includes(process.argv[1]) ? process.argv[1] : 'status');// Dynamic import() failures can surface as unhandled rejections on a later// microtask even when the awaiting call site already caught them, which woulddiff --git a/v3/@claude-flow/cli/.claude/helpers/helpers.manifest.json b/v3/@claude-flow/cli/.claude/helpers/helpers.manifest.jsonindex 794bd702d7..dede55f015 100644--- a/v3/@claude-flow/cli/.claude/helpers/helpers.manifest.json+++ b/v3/@claude-flow/cli/.claude/helpers/helpers.manifest.json@@ -1,14 +1,14 @@{"manifest": {- "version": "3.56.5",+ "version": "3.56.6","files": {- "auto-memory-hook.mjs": "381412515fb490def7d821ddfe1ebf8d9bee76e49a86e182806c0274f568bf15",+ "auto-memory-hook.mjs": "631fac9d518835e2852a406888316bbbddddb49e7ed8e406d2e971f46833df9a","hook-handler.cjs": "0f855c667b8d2d04cb4fe91b14b351d14c3dfb30516dcd9d7ae156acbe0a689d",- "intelligence.cjs": "ac5033a77bcea9796856629d5d319bde9ab6b7edf0dcd0d4af187ce30af90836",+ "intelligence.cjs": "f172483416381593d103130c96adc8dfd2eb1f4c85eee27a84c5ad1eba7d0ef2","statusline.cjs": "d72417ecb38634011a19f095a30e07b9929e6f97663520172ece9be7491b2eaa","router.cjs": "16648b3c0d73b6681ac2d8d13def6a68286c57f5a11004de5b19a0fa088c833d"}},- "signature": "8XUUrD8gMoKnYWmR6xkxOp5Z54ZeHtDWBb57RVfKLXpc3wj6LIqqvRPOcTgGJQzL98PCkbYffoBEtH5TeCTfBA==",+ "signature": "ExTq6zXk6QpG2EoNKRS8D8G46q0Uje/5K0JoByXiW6+veZYvJF0xa4ASwTyNSZE0F0eg5LgyIH6W6oAwUoQFBg==","algorithm": "ed25519"}diff --git a/v3/@claude-flow/cli/.claude/helpers/intelligence.cjs b/v3/@claude-flow/cli/.claude/helpers/intelligence.cjsindex 4c1e4d432b..4266dfa67a 100755--- a/v3/@claude-flow/cli/.claude/helpers/intelligence.cjs+++ b/v3/@claude-flow/cli/.claude/helpers/intelligence.cjs@@ -108,9 +108,54 @@ function readJSON(filePath) {return null;}+// Atomic (temp + rename): auto-memory-hook.mjs reads and writes the same store+// from the session hooks, and a reader must never see a half-written file (#4058).function writeJSON(filePath, data) {ensureDataDir();- fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf-8');+ const tmp = filePath + '.' + process.pid + '.tmp';+ try {+ fs.writeFileSync(tmp, JSON.stringify(data, null, 2), 'utf-8');+ fs.renameSync(tmp, filePath);+ } catch (e) {+ try { fs.unlinkSync(tmp); } catch { /* nothing to clean */ }+ throw e;+ }+}++// Short advisory directory lock shared with auto-memory-hook.mjs. It fails open+// after ~2 s so a stuck lock can never hang a hook.+function withStoreLock(filePath, fn) {+ const lock = filePath + '.lock';+ const deadline = Date.now() + 2000;+ let held = false;+ for (;;) {+ try { fs.mkdirSync(lock); held = true; break; } catch (e) {+ if (!e || e.code !== 'EEXIST') break;+ try {+ if (Date.now() - fs.statSync(lock).mtimeMs > 10000) { fs.rmSync(lock, { recursive: true, force: true }); continue; }+ } catch { /* lock vanished: retry */ }+ if (Date.now() > deadline) break;+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10);+ }+ }+ try { return fn(); } finally { if (held) { try { fs.rmdirSync(lock); } catch { /* already gone */ } } }+}++// Write the store, keeping entries another writer added after we read it.+function writeStoreMerged(filePath, next, loaded) {+ const loadedIds = new Set((Array.isArray(loaded) ? loaded : []).map((e) => e && e.id));+ withStoreLock(filePath, () => {+ let out = next;+ try {+ const current = JSON.parse(fs.readFileSync(filePath, 'utf-8'));+ if (Array.isArray(current)) {+ const have = new Set(next.map((e) => e && e.id));+ const added = current.filter((e) => e && !loadedIds.has(e.id) && !have.has(e.id));+ if (added.length) out = next.concat(added);+ }+ } catch { /* missing or unreadable: write ours */ }+ writeJSON(filePath, out);+ });}function tokenize(text) {@@ -481,7 +526,7 @@ function init() {const bootstrapped = bootstrapFromMemoryFiles();if (bootstrapped.length > 0) {store = bootstrapped;- writeJSON(STORE_PATH, store);+ writeStoreMerged(STORE_PATH, store, []);} else {return { nodes: 0, edges: 0, message: 'No memory entries to index' };}@@ -503,7 +548,7 @@ function init() {`[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);+ writeStoreMerged(STORE_PATH, deduped, store);}// Skip rebuild if graph is fresh and store hasn't changed. #2920: nodeCount@@ -834,6 +879,7 @@ function consolidate() {return { entries: 0, edges: 0, newEntries: 0, message: 'No store to consolidate' };}+ const loadedStore = store;// Deduplicate store entries by ID before processing (fixes #1518)const preDedupCount = store.length;store = deduplicateById(store);@@ -979,7 +1025,7 @@ function consolidate() {// RANKED_PATH are rewritten unconditionally just above; writing the// (already deduped, size-bounded per ADR-095 G6) store alongside them// costs nothing near the <500ms budget and removes the whole bug class.- writeJSON(STORE_PATH, store);+ writeStoreMerged(STORE_PATH, store, loadedStore);// 9. Save snapshot for delta trackingconst updatedGraph = readJSON(GRAPH_PATH);diff --git a/v3/@claude-flow/cli/__tests__/auto-memory-hooks-4058.test.ts b/v3/@claude-flow/cli/__tests__/auto-memory-hooks-4058.test.tsnew file mode 100644index 0000000000..f338abe348--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/auto-memory-hooks-4058.test.ts@@ -0,0 +1,210 @@+/**+ * Regression for #4058 (auto-memory hooks): the generated hooks must reach the+ * helper with their subcommand, sync must see the learnings the bridge asks+ * for, the index line must not claim work that was skipped, worktree sessions+ * must target the main repository's memory directory, and concurrent writers+ * must not lose each other's entries.+ */+import { afterEach, describe, expect, it } from 'vitest';+import { spawn, spawnSync, execFileSync } from 'node:child_process';+import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';++import { mergeSettingsForUpgrade } from '../src/init/executor.js';++const here = dirname(fileURLToPath(import.meta.url));+const packageHook = resolve(here, '../.claude/helpers/auto-memory-hook.mjs');+const dogfoodHook = resolve(here, '../../../../.claude/helpers/auto-memory-hook.mjs');+const packageIntel = resolve(here, '../.claude/helpers/intelligence.cjs');+const tempRoots: string[] = [];++afterEach(() => {+ for (const root of tempRoots.splice(0)) rmSync(root, { recursive: true, force: true });+});++function sandbox() {+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'ruflo-4058-')));+ tempRoots.push(root);+ const project = join(root, 'project');+ const home = join(root, 'home');+ mkdirSync(project, { recursive: true });+ mkdirSync(home, { recursive: true });+ return { root, project, home };+}++/** A memory package stub whose bridge calls the backend exactly like the real one. */+const MOCK_MEMORY = `+import { EventEmitter } from 'node:events';+import { appendFileSync, writeFileSync } from 'node:fs';+export class AutoMemoryBridge extends EventEmitter {+ constructor(backend, config) { super(); this.backend = backend; this.config = config; }+ async importFromAutoMemory() {+ appendFileSync(new URL('./config-seen.jsonl', import.meta.url), JSON.stringify(this.config) + '\\n');+ const id = 'imp-' + process.pid + '-' + Math.random().toString(16).slice(2);+ await this.backend.store({ id, key: id, namespace: 'auto-memory', content: 'x', type: 'semantic', tags: [], metadata: {}, createdAt: Date.now(), updatedAt: Date.now() });+ return { imported: 1, skipped: 0 };+ }+ async syncToAutoMemory() {+ // AutoMemoryBridge.queryRecentInsights, verbatim shape+ const found = await this.backend.query({ type: 'hybrid', namespace: 'learnings', tags: ['insight'], updatedAfter: 0, limit: 50 });+ writeFileSync(new URL('./sync-found.json', import.meta.url), JSON.stringify(found.map(e => e.id)));+ return { synced: found.length, categories: [] };+ }+ async curateIndex() { this.emit('index:skipped', { reason: 'no-matching-topic-files' }); }+}+`;++function installHook(source: string, home: string) {+ const hook = join(home, '.claude', 'helpers', 'auto-memory-hook.mjs');+ mkdirSync(dirname(hook), { recursive: true });+ copyFileSync(source, hook);+ const mock = join(home, 'mock-memory.mjs');+ writeFileSync(mock, MOCK_MEMORY);+ mkdirSync(join(home, '.claude-flow'), { recursive: true });+ writeFileSync(join(home, '.claude-flow', 'memory-package.json'), JSON.stringify({ distPath: mock }));+ return { hook, mock };+}++function run(hook: string, project: string, args: string[], env: NodeJS.ProcessEnv = {}) {+ const r = spawnSync(process.execPath, [hook, ...args], {+ cwd: project,+ env: { ...process.env, CLAUDE_PROJECT_DIR: project, ...env },+ encoding: 'utf8',+ timeout: 15_000,+ });+ expect(r.error).toBeUndefined();+ return r.stdout + r.stderr;+}++function upgradeCommands() {+ const { project } = sandbox();+ const { merged } = mergeSettingsForUpgrade({}, project);+ const hooks = merged.hooks as Record<string, Array<{ hooks: Array<{ command: string; timeout: number }> }>>;+ const pick = (event: string) => hooks[event].flatMap(g => g.hooks).find(h => h.command.includes('auto-memory-hook'))!;+ return { project, importHook: pick('SessionStart'), syncHook: pick('SessionEnd') };+}++describe('#4058 point 1: the generated command delivers the subcommand', () => {+ for (const sub of ['import', 'sync'] as const) {+ it(`upgrade-generated ${sub} command passes "${sub}" as the helper's first argument`, () => {+ const { project, importHook, syncHook } = upgradeCommands();+ const fake = join(project, '.claude', 'helpers', 'auto-memory-hook.mjs');+ mkdirSync(dirname(fake), { recursive: true });+ writeFileSync(fake, "import { writeFileSync } from 'node:fs';\nwriteFileSync(new URL('./argv.json', import.meta.url), JSON.stringify(process.argv.slice(2)));\n");+ const cmd = (sub === 'import' ? importHook : syncHook).command;+ const r = spawnSync(cmd, { shell: true, cwd: project, env: { ...process.env, CLAUDE_PROJECT_DIR: project }, encoding: 'utf8', timeout: 15_000 });+ expect(r.status).toBe(0);+ expect(JSON.parse(readFileSync(join(dirname(fake), 'argv.json'), 'utf8'))).toEqual([sub]);+ });+ }++ for (const [name, source] of [['package', packageHook], ['repository', dogfoodHook]] as const) {+ it(`${name} helper still imports when an older settings.json passes the subcommand as argv[1] (node -e form)`, () => {+ const { project, home } = sandbox();+ const { hook } = installHook(source, home);+ const legacy = `var u=require('url');import(u.pathToFileURL(${JSON.stringify(hook)}).href)`;+ const r = spawnSync(process.execPath, ['-e', legacy, 'import'], {+ cwd: project, env: { ...process.env, CLAUDE_PROJECT_DIR: project }, encoding: 'utf8', timeout: 15_000,+ });+ expect(r.stdout).toContain('Imported 1 entries');+ expect(r.stdout).not.toContain('Auto Memory Bridge Status');+ });+ }+});++describe('#4058 point 2: hook timeouts are in seconds', () => {+ it('auto-memory hooks written on upgrade use second-scale timeouts', () => {+ const { importHook, syncHook } = upgradeCommands();+ for (const h of [importHook, syncHook]) {+ expect(h.timeout).toBeGreaterThanOrEqual(5);+ expect(h.timeout).toBeLessThanOrEqual(120);+ }+ });+});++describe('#4058 point 4: sync sees learnings, and curate does not claim skipped work', () => {+ for (const [name, source] of [['package', packageHook], ['repository', dogfoodHook]] as const) {+ it(`${name} helper answers the bridge's learnings query and reports a skipped index honestly`, () => {+ const { project, home } = sandbox();+ const { hook } = installHook(source, home);+ const data = join(project, '.claude-flow', 'data');+ mkdirSync(data, { recursive: true });+ const entry = (id: string, namespace: string, tags: string[]) =>+ ({ id, key: id, namespace, content: id, type: 'semantic', tags, metadata: { confidence: 0.9 }, createdAt: 1, updatedAt: 2 });+ writeFileSync(join(data, 'auto-memory-store.json'), JSON.stringify([+ entry('insight-1', 'learnings', ['insight']),+ entry('insight-2', 'learnings', ['insight', 'extra']),+ entry('other-ns', 'auto-memory', ['insight']),+ entry('untagged', 'learnings', []),+ ]));+ const out = run(hook, project, ['sync']);+ expect(out).toContain('Synced 2 entries');+ expect(JSON.parse(readFileSync(join(home, 'sync-found.json'), 'utf8')).sort()).toEqual(['insight-1', 'insight-2']);+ expect(out).not.toContain('Curated MEMORY.md index');+ expect(out).toMatch(/index unchanged|skipped/i);+ });+ }+});++describe('#4058 point 5: a git worktree uses the main repository memory directory', () => {+ it('passes the main checkout key as memoryDir, never the worktree key', () => {+ const { root, home } = sandbox();+ const main = join(root, 'main_repo');+ const wt = join(root, 'wt-feature');+ mkdirSync(main, { recursive: true });+ const git = (cwd: string, ...args: string[]) =>+ execFileSync('git', ['-c', 'user.name=t', '-c', 'user.email=t@t', ...args], { cwd, encoding: 'utf8' });+ git(main, 'init', '-q', '-b', 'main');+ writeFileSync(join(main, 'f.txt'), 'x');+ git(main, 'add', '.');+ git(main, 'commit', '-q', '-m', 'init');+ git(main, 'worktree', 'add', '-q', wt, '-b', 'feature');+ expect(existsSync(join(wt, '.git'))).toBe(true);++ const { hook } = installHook(packageHook, home);+ run(hook, wt, ['import'], { HOME: home, USERPROFILE: home });+ const seen = readFileSync(join(home, 'config-seen.jsonl'), 'utf8').trim().split('\n').map(l => JSON.parse(l));+ const key = (p: string) => p.split('/').join('/').replace(/[\/_:]/g, '-');+ expect(seen[0].memoryDir).toBe(join(home, '.claude', 'projects', key(main), 'memory'));+ expect(seen[0].memoryDir).not.toContain(key(wt));+ });++ it('a plain checkout is unchanged (no memoryDir override needed)', () => {+ const { root, home } = sandbox();+ const repo = join(root, 'plain');+ mkdirSync(repo, { recursive: true });+ execFileSync('git', ['init', '-q'], { cwd: repo });+ const { hook } = installHook(packageHook, home);+ run(hook, repo, ['import'], { HOME: home, USERPROFILE: home });+ const seen = JSON.parse(readFileSync(join(home, 'config-seen.jsonl'), 'utf8').trim().split('\n')[0]);+ const key = repo.replace(/[\/_:]/g, '-');+ expect(seen.memoryDir ?? join(home, '.claude', 'projects', key, 'memory')).toBe(join(home, '.claude', 'projects', key, 'memory'));+ });+});++describe('#4058 point 6: concurrent writers do not lose entries', () => {+ it('eight overlapping imports all land in the store, with no temp files left', async () => {+ const { project, home } = sandbox();+ const { hook } = installHook(packageHook, home);+ mkdirSync(join(project, '.claude-flow', 'data'), { recursive: true });+ const runs = Array.from({ length: 8 }, () => new Promise<void>((done) => {+ const p = spawn(process.execPath, [hook, 'import'], { cwd: project, env: { ...process.env, CLAUDE_PROJECT_DIR: project }, stdio: 'ignore' });+ p.on('close', () => done());+ }));+ await Promise.all(runs);+ const dir = join(project, '.claude-flow', 'data');+ const store = JSON.parse(readFileSync(join(dir, 'auto-memory-store.json'), 'utf8'));+ expect(store.length).toBe(8);+ expect(readdirSync(dir).filter(f => f.includes('.tmp') || f.endsWith('.lock'))).toEqual([]);+ }, 60_000);++ it('intelligence.cjs writes JSON atomically (no truncated file under a concurrent reader)', () => {+ const source = readFileSync(packageIntel, 'utf8');+ expect(source).toMatch(/renameSync\(/);+ const writer = /function writeJSON\(filePath, data\) \{[\s\S]*?\n\}/.exec(source)![0];+ expect(writer).toContain('renameSync');+ expect(writer).not.toMatch(/writeFileSync\(filePath,/);+ });+});diff --git a/v3/@claude-flow/cli/src/init/executor.ts b/v3/@claude-flow/cli/src/init/executor.tsindex 319e36cd02..1776a52002 100644--- a/v3/@claude-flow/cli/src/init/executor.ts+++ b/v3/@claude-flow/cli/src/init/executor.ts@@ -33,7 +33,7 @@ import { generateClaudeMd } from './claudemd-generator.js';import { recordMemoryPackagePath } from './memory-package-resolver.js';import { ensureCommonJsCompanions } from './helper-companions.js';import { scanSettingsForRisk, formatRiskFindingsAsWarnings } from './settings-risk-scanner.js';-import { helperHookCommand, helperScopeFor, helperStatusLineCommand, pinToUserHelpers } from './helper-commands.js';+import { AUTO_MEMORY_HOOK_TIMEOUT_S, helperHookCommand, helperScopeFor, helperStatusLineCommand, pinToUserHelpers } from './helper-commands.js';/*** Skills to copy based on configuration@@ -375,18 +375,15 @@ export function mergeSettingsForUpgrade(const existingHooks = (existing.hooks as Record<string, unknown[]>) || {};merged.hooks = { ...existingHooks };- // Cross-platform auto-memory hook commands that resolve paths via git root.- // Uses node -e with git rev-parse so hooks work regardless of CWD (#1259, #1284).- const gitRootResolver = "var c=require('child_process'),p=require('path'),u=require('url'),r;"- + "try{r=c.execSync('git rev-parse --show-toplevel',{encoding:'utf8'}).trim()}"- + 'catch(e){r=process.cwd()}';+ // Auto-memory hook commands. They go through helperHookCommand like every other+ // helper hook (#4058): the previous `node -e "…import(file)" import` form left the+ // subcommand in process.argv[1], the helper read argv[2], and both hooks only+ // printed the status banner. Hooks run in the project directory with+ // CLAUDE_PROJECT_DIR set, so the shared probe resolves the helper without a+ // `git rev-parse` of its own.const autoMemoryScript = '.claude/helpers/auto-memory-hook.mjs';- const autoMemoryImportCmd = scope === 'user'- ? helperHookCommand(autoMemoryScript, 'import', 'user')- : `node -e "${gitRootResolver}var f=p.join(r,'${autoMemoryScript}');import(u.pathToFileURL(f).href)" import`;- const autoMemorySyncCmd = scope === 'user'- ? helperHookCommand(autoMemoryScript, 'sync', 'user')- : `node -e "${gitRootResolver}var f=p.join(r,'${autoMemoryScript}');import(u.pathToFileURL(f).href)" sync`;+ const autoMemoryImportCmd = helperHookCommand(autoMemoryScript, 'import', scope);+ const autoMemorySyncCmd = helperHookCommand(autoMemoryScript, 'sync', scope);// Add auto-memory import to SessionStart (if not already present)const sessionStartHooks = existingHooks.SessionStart as Array<{ hooks?: Array<{ command?: string }> }> | undefined;@@ -402,7 +399,7 @@ export function mergeSettingsForUpgrade(startGroup.hooks.push({type: 'command',command: autoMemoryImportCmd,- timeout: 6000,+ timeout: AUTO_MEMORY_HOOK_TIMEOUT_S,continueOnError: true,});}@@ -422,7 +419,7 @@ export function mergeSettingsForUpgrade(endGroup.hooks.unshift({type: 'command',command: autoMemorySyncCmd,- timeout: 8000,+ timeout: AUTO_MEMORY_HOOK_TIMEOUT_S,continueOnError: true,});}diff --git a/v3/@claude-flow/cli/src/init/helper-commands.ts b/v3/@claude-flow/cli/src/init/helper-commands.tsindex e99ae896f0..173090f79a 100644--- a/v3/@claude-flow/cli/src/init/helper-commands.ts+++ b/v3/@claude-flow/cli/src/init/helper-commands.ts@@ -17,6 +17,9 @@ import * as path from 'path';export type HelperScope = 'project' | 'user';+/** Claude Code reads a hook's `timeout` in SECONDS; the auto-memory hooks wrote 6000-10000, i.e. up to 100 minutes (#4058). */+export const AUTO_MEMORY_HOOK_TIMEOUT_S = 30;+const IS_WINDOWS = process.platform === 'win32';const STATUSLINE_SCRIPT = '.claude/helpers/statusline.cjs';diff --git a/v3/@claude-flow/cli/src/init/helpers-generator.ts b/v3/@claude-flow/cli/src/init/helpers-generator.tsindex 302f7ceca2..75dac47414 100644--- a/v3/@claude-flow/cli/src/init/helpers-generator.ts+++ b/v3/@claude-flow/cli/src/init/helpers-generator.ts@@ -1317,7 +1317,10 @@ function doStatus() {// Suppress unhandled rejection warnings from dynamic import() failuresprocess.on('unhandledRejection', () => {});-const command = process.argv[2] || 'status';+// Older settings.json files ran node -e with the helper imported, which puts the+// subcommand in argv[1] (#4058); accept that shape as well as script import.+const COMMANDS = ['import', 'sync', 'status'];+const command = process.argv[2] || (COMMANDS.includes(process.argv[1]) ? process.argv[1] : 'status');try {switch (command) {diff --git a/v3/@claude-flow/cli/src/init/settings-generator.ts b/v3/@claude-flow/cli/src/init/settings-generator.tsindex 1b49a6a48b..e52e9bafdd 100644--- a/v3/@claude-flow/cli/src/init/settings-generator.ts+++ b/v3/@claude-flow/cli/src/init/settings-generator.ts@@ -5,7 +5,7 @@import type { InitOptions, HooksConfig, PlatformInfo } from './types.js';import { detectPlatform } from './types.js';-import { helperHookCommand, helperScopeFor, helperStatusLineCommand, type HelperScope } from './helper-commands.js';+import { AUTO_MEMORY_HOOK_TIMEOUT_S, helperHookCommand, helperScopeFor, helperStatusLineCommand, type HelperScope } from './helper-commands.js';/*** Generate the complete settings.json content@@ -300,7 +300,7 @@ function generateHooksConfig(config: HooksConfig, scope: HelperScope): object {{type: 'command',command: autoMemoryCmd('import', scope),- timeout: 8000,+ timeout: AUTO_MEMORY_HOOK_TIMEOUT_S,},],},@@ -330,7 +330,7 @@ function generateHooksConfig(config: HooksConfig, scope: HelperScope): object {{type: 'command',command: autoMemoryCmd('sync', scope),- timeout: 10000,+ timeout: AUTO_MEMORY_HOOK_TIMEOUT_S,},],},