monomind 2.0.3 → 2.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/README.md +74 -92
  2. package/package.json +11 -7
  3. package/packages/@monomind/cli/.claude/helpers/control-start.cjs +13 -20
  4. package/packages/@monomind/cli/.claude/helpers/event-logger.cjs +109 -6
  5. package/packages/@monomind/cli/.claude/helpers/graphify-freshen.cjs +19 -17
  6. package/packages/@monomind/cli/.claude/helpers/handlers/agent-start-handler.cjs +60 -28
  7. package/packages/@monomind/cli/.claude/helpers/handlers/capture-handler.cjs +99 -28
  8. package/packages/@monomind/cli/.claude/helpers/handlers/edit-handler.cjs +27 -9
  9. package/packages/@monomind/cli/.claude/helpers/handlers/gates-handler.cjs +18 -9
  10. package/packages/@monomind/cli/.claude/helpers/handlers/loops-status-handler.cjs +1 -1
  11. package/packages/@monomind/cli/.claude/helpers/handlers/route-handler.cjs +33 -4
  12. package/packages/@monomind/cli/.claude/helpers/handlers/session-handler.cjs +75 -45
  13. package/packages/@monomind/cli/.claude/helpers/handlers/session-restore-handler.cjs +0 -12
  14. package/packages/@monomind/cli/.claude/helpers/handlers/task-handler.cjs +53 -22
  15. package/packages/@monomind/cli/.claude/helpers/hook-handler.cjs +75 -4
  16. package/packages/@monomind/cli/.claude/helpers/intelligence.cjs +94 -15
  17. package/packages/@monomind/cli/.claude/helpers/session.cjs +6 -1
  18. package/packages/@monomind/cli/.claude/helpers/statusline.cjs +10 -10
  19. package/packages/@monomind/cli/.claude/helpers/token-tracker.cjs +3 -3
  20. package/packages/@monomind/cli/.claude/helpers/utils/agent-registrations.cjs +41 -0
  21. package/packages/@monomind/cli/.claude/helpers/utils/fs-helpers.cjs +183 -0
  22. package/packages/@monomind/cli/.claude/helpers/utils/micro-agents.cjs +10 -6
  23. package/packages/@monomind/cli/.claude/helpers/utils/monograph.cjs +73 -2
  24. package/packages/@monomind/cli/.claude/helpers/utils/telemetry.cjs +35 -19
  25. package/packages/@monomind/cli/README.md +74 -92
  26. package/packages/@monomind/cli/bin/cli.js +10 -1
  27. package/packages/@monomind/cli/dist/src/browser/workflow/store.d.ts +2 -2
  28. package/packages/@monomind/cli/dist/src/commands/agent-ops.js +9 -15
  29. package/packages/@monomind/cli/dist/src/commands/browse.d.ts +1 -1
  30. package/packages/@monomind/cli/dist/src/commands/cleanup.js +20 -4
  31. package/packages/@monomind/cli/dist/src/commands/completions.js +66 -261
  32. package/packages/@monomind/cli/dist/src/commands/doctor-env-checks.js +5 -0
  33. package/packages/@monomind/cli/dist/src/commands/doctor.js +7 -2
  34. package/packages/@monomind/cli/dist/src/commands/hooks-workers.js +7 -0
  35. package/packages/@monomind/cli/dist/src/commands/index.js +3 -0
  36. package/packages/@monomind/cli/dist/src/commands/mcp.js +11 -6
  37. package/packages/@monomind/cli/dist/src/commands/memory-admin.js +12 -6
  38. package/packages/@monomind/cli/dist/src/commands/memory-transfer.js +6 -13
  39. package/packages/@monomind/cli/dist/src/commands/monograph.js +3 -3
  40. package/packages/@monomind/cli/dist/src/commands/org.d.ts +3 -1
  41. package/packages/@monomind/cli/dist/src/commands/org.js +321 -127
  42. package/packages/@monomind/cli/dist/src/commands/platforms.d.ts +1 -1
  43. package/packages/@monomind/cli/dist/src/commands/start.js +142 -37
  44. package/packages/@monomind/cli/dist/src/commands/tokens.js +21 -3
  45. package/packages/@monomind/cli/dist/src/config-adapter.js +37 -17
  46. package/packages/@monomind/cli/dist/src/index.js +64 -28
  47. package/packages/@monomind/cli/dist/src/init/claudemd-generator.js +44 -11
  48. package/packages/@monomind/cli/dist/src/init/executor.js +93 -55
  49. package/packages/@monomind/cli/dist/src/mcp-client.d.ts +8 -3
  50. package/packages/@monomind/cli/dist/src/mcp-client.js +37 -3
  51. package/packages/@monomind/cli/dist/src/mcp-server.js +8 -2
  52. package/packages/@monomind/cli/dist/src/mcp-tools/agent-tools.d.ts +20 -0
  53. package/packages/@monomind/cli/dist/src/mcp-tools/agent-tools.js +10 -5
  54. package/packages/@monomind/cli/dist/src/mcp-tools/auto-install.d.ts +8 -8
  55. package/packages/@monomind/cli/dist/src/mcp-tools/coherence/types.d.ts +31 -31
  56. package/packages/@monomind/cli/dist/src/mcp-tools/github-tools.js +30 -8
  57. package/packages/@monomind/cli/dist/src/mcp-tools/graphify-tools.js +11 -2
  58. package/packages/@monomind/cli/dist/src/mcp-tools/hive-mind-tools.js +56 -35
  59. package/packages/@monomind/cli/dist/src/mcp-tools/knowledge-tools.js +9 -1
  60. package/packages/@monomind/cli/dist/src/mcp-tools/monograph-compat.js +56 -14
  61. package/packages/@monomind/cli/dist/src/mcp-tools/monograph-tools.js +88 -41
  62. package/packages/@monomind/cli/dist/src/mcp-tools/quality/coverage-analysis/prioritize-gaps.d.ts +36 -36
  63. package/packages/@monomind/cli/dist/src/mcp-tools/quality/security-compliance/detect-secrets.d.ts +4 -4
  64. package/packages/@monomind/cli/dist/src/mcp-tools/swarm-tools.js +6 -4
  65. package/packages/@monomind/cli/dist/src/mcp-tools/system-tools.js +4 -4
  66. package/packages/@monomind/cli/dist/src/mcp-tools/types.d.ts +20 -0
  67. package/packages/@monomind/cli/dist/src/mcp-tools/types.js +36 -1
  68. package/packages/@monomind/cli/dist/src/memory/ewc-consolidation.d.ts +12 -0
  69. package/packages/@monomind/cli/dist/src/memory/hnsw-operations.d.ts +13 -1
  70. package/packages/@monomind/cli/dist/src/memory/hnsw-operations.js +66 -14
  71. package/packages/@monomind/cli/dist/src/memory/intelligence.js +99 -3
  72. package/packages/@monomind/cli/dist/src/memory/memory-bridge.d.ts +7 -0
  73. package/packages/@monomind/cli/dist/src/memory/memory-bridge.js +20 -0
  74. package/packages/@monomind/cli/dist/src/memory/sona-optimizer.d.ts +12 -0
  75. package/packages/@monomind/cli/dist/src/orgrt/broker.d.ts +26 -0
  76. package/packages/@monomind/cli/dist/src/orgrt/broker.js +73 -0
  77. package/packages/@monomind/cli/dist/src/orgrt/bus.d.ts +5 -1
  78. package/packages/@monomind/cli/dist/src/orgrt/bus.js +5 -1
  79. package/packages/@monomind/cli/dist/src/orgrt/daemon.d.ts +46 -0
  80. package/packages/@monomind/cli/dist/src/orgrt/daemon.js +201 -18
  81. package/packages/@monomind/cli/dist/src/orgrt/forwarder.d.ts +10 -5
  82. package/packages/@monomind/cli/dist/src/orgrt/forwarder.js +138 -8
  83. package/packages/@monomind/cli/dist/src/orgrt/inbox.d.ts +11 -0
  84. package/packages/@monomind/cli/dist/src/orgrt/inbox.js +56 -0
  85. package/packages/@monomind/cli/dist/src/orgrt/policy.d.ts +5 -1
  86. package/packages/@monomind/cli/dist/src/orgrt/policy.js +58 -5
  87. package/packages/@monomind/cli/dist/src/orgrt/provider.js +1 -0
  88. package/packages/@monomind/cli/dist/src/orgrt/scheduler.d.ts +13 -0
  89. package/packages/@monomind/cli/dist/src/orgrt/scheduler.js +48 -0
  90. package/packages/@monomind/cli/dist/src/orgrt/server.d.ts +9 -0
  91. package/packages/@monomind/cli/dist/src/orgrt/server.js +39 -0
  92. package/packages/@monomind/cli/dist/src/orgrt/session.d.ts +10 -1
  93. package/packages/@monomind/cli/dist/src/orgrt/session.js +24 -1
  94. package/packages/@monomind/cli/dist/src/orgrt/test-loop.d.ts +12 -0
  95. package/packages/@monomind/cli/dist/src/orgrt/test-loop.js +108 -0
  96. package/packages/@monomind/cli/dist/src/orgrt/types.d.ts +52 -52
  97. package/packages/@monomind/cli/dist/src/output.d.ts +29 -29
  98. package/packages/@monomind/cli/dist/src/output.js +22 -7
  99. package/packages/@monomind/cli/dist/src/parser.d.ts +32 -0
  100. package/packages/@monomind/cli/dist/src/parser.js +130 -5
  101. package/packages/@monomind/cli/dist/src/routing/embed-worker.js +13 -1
  102. package/packages/@monomind/cli/dist/src/routing/route-layer-factory.js +31 -0
  103. package/packages/@monomind/cli/dist/src/services/config-file-manager.d.ts +21 -0
  104. package/packages/@monomind/cli/dist/src/services/config-file-manager.js +60 -7
  105. package/packages/@monomind/cli/dist/src/services/crash-reporter.js +2 -1
  106. package/packages/@monomind/cli/dist/src/types.d.ts +2 -2
  107. package/packages/@monomind/cli/dist/src/ui/dashboard.html +243 -49
  108. package/packages/@monomind/cli/dist/src/ui/orgs-files.js +192 -0
  109. package/packages/@monomind/cli/dist/src/ui/orgs.html +79 -11
  110. package/packages/@monomind/cli/dist/src/ui/server.mjs +346 -139
  111. package/packages/@monomind/cli/dist/src/utils/input-guards.d.ts +9 -0
  112. package/packages/@monomind/cli/dist/src/utils/input-guards.js +39 -5
  113. package/packages/@monomind/cli/package.json +15 -15
@@ -41,34 +41,46 @@ module.exports = {
41
41
  if (fs.existsSync(lastRoutePath) && (function() { try { return fs.statSync(lastRoutePath).size <= MAX_ROUTE; } catch(_) { return false; } }())) {
42
42
  var lastRoute = JSON.parse(fs.readFileSync(lastRoutePath, 'utf-8'));
43
43
 
44
- // Derive sessionSuccess from git commits (strongest signal: user committed = success)
44
+ // Derive sessionSuccess. A commit alone is not proof of success — a
45
+ // session can commit a partial fix and then hit repeated failures —
46
+ // so recent intelligence-outcomes are checked FIRST and can veto a
47
+ // commit-based "true" when they show a majority of failures.
45
48
  try {
46
49
  var execSync = require('child_process').execSync;
47
- var recentCommits = execSync('git log --oneline --since="30 minutes ago" 2>/dev/null || true', { cwd: CWD, timeout: 3000, encoding: 'utf-8' }).trim();
48
- if (recentCommits.length > 0) {
49
- sessionSuccess = true;
50
+
51
+ var outcomesSignal = null; // majority success/failure from intelligence-outcomes, if any
52
+ var outcomesPath = path.join(CWD, '.monomind', 'data', 'intelligence-outcomes.jsonl');
53
+ var MAX_OUTCOMES = 512 * 1024;
54
+ if (fs.existsSync(outcomesPath) && (function() { try { return fs.statSync(outcomesPath).size <= MAX_OUTCOMES; } catch(_) { return false; } }())) {
55
+ var windowMs = 30 * 60 * 1000;
56
+ var cutoff = Date.now() - windowMs;
57
+ var outcomeLines = fs.readFileSync(outcomesPath, 'utf-8').trim().split('\n').filter(Boolean);
58
+ var recent = outcomeLines.map(function(l) {
59
+ try { return JSON.parse(l); } catch { return null; }
60
+ }).filter(function(e) { return e && e.ts && e.ts >= cutoff; });
61
+ if (recent.length > 0) {
62
+ var failures = recent.filter(function(e) { return e.success === false; }).length;
63
+ outcomesSignal = failures / recent.length < 0.5;
64
+ }
65
+ }
66
+
67
+ if (outcomesSignal === false) {
68
+ // Recent tool/command outcomes were majority failures — this
69
+ // overrides a commit, since committing doesn't undo those failures.
70
+ sessionSuccess = false;
50
71
  } else {
51
- // No commits check if files were modified (work in progress, not failure)
52
- var gitStatus = execSync('git diff --name-only 2>/dev/null || true', { cwd: CWD, timeout: 3000, encoding: 'utf-8' }).trim();
53
- // Modified files = probably still working; no changes at all = exploration or failure
54
- if (gitStatus.length === 0) {
55
- // Fall back to intelligence-outcomes as a weak signal
56
- var outcomesPath = path.join(CWD, '.monomind', 'data', 'intelligence-outcomes.jsonl');
57
- var MAX_OUTCOMES = 512 * 1024;
58
- if (fs.existsSync(outcomesPath) && (function() { try { return fs.statSync(outcomesPath).size <= MAX_OUTCOMES; } catch(_) { return false; } }())) {
59
- var windowMs = 30 * 60 * 1000;
60
- var cutoff = Date.now() - windowMs;
61
- var outcomeLines = fs.readFileSync(outcomesPath, 'utf-8').trim().split('\n').filter(Boolean);
62
- var recent = outcomeLines.map(function(l) {
63
- try { return JSON.parse(l); } catch { return null; }
64
- }).filter(function(e) { return e && e.ts && e.ts >= cutoff; });
65
- if (recent.length > 0) {
66
- var failures = recent.filter(function(e) { return e.success === false; }).length;
67
- sessionSuccess = failures / recent.length < 0.5;
68
- }
72
+ var recentCommits = execSync('git log --oneline --since="30 minutes ago" 2>/dev/null || true', { cwd: CWD, timeout: 3000, encoding: 'utf-8' }).trim();
73
+ if (recentCommits.length > 0) {
74
+ sessionSuccess = true;
75
+ } else {
76
+ // No commits check if files were modified (work in progress, not failure)
77
+ var gitStatus = execSync('git diff --name-only 2>/dev/null || true', { cwd: CWD, timeout: 3000, encoding: 'utf-8' }).trim();
78
+ // Modified files = probably still working; no changes at all = exploration or failure
79
+ if (gitStatus.length === 0 && outcomesSignal !== null) {
80
+ sessionSuccess = outcomesSignal;
69
81
  }
82
+ // else: modified files exist, or no evidence either way (leave null)
70
83
  }
71
- // else: modified files exist — work in progress, not evidence either way (leave null)
72
84
  }
73
85
  } catch (e) { /* non-critical — leave null (no evidence) */ }
74
86
 
@@ -89,17 +101,48 @@ module.exports = {
89
101
  // Only write the success flag when derived from actual evidence (commits, outcomes)
90
102
  if (typeof sessionSuccess === 'boolean') feedbackEntry.intelligenceFeedback = sessionSuccess;
91
103
  fs.appendFileSync(feedbackPath, JSON.stringify(feedbackEntry) + '\n', 'utf-8');
92
- // Rotate: keep last 1000 lines to prevent unbounded growth
104
+ // Rotate: keep last 1000 lines to prevent unbounded growth.
93
105
  try {
94
106
  var MAX_FEEDBACK = 512 * 1024; // 512 KiB
95
- if (fs.existsSync(feedbackPath) && fs.statSync(feedbackPath).size > MAX_FEEDBACK) {
96
- // File too large emergency trim without full read
97
- throw new Error('skip-rotation');
98
- }
99
- var raw = fs.readFileSync(feedbackPath, 'utf-8');
100
- var lines = raw.split('\n').filter(Boolean);
101
- if (lines.length > 1000) {
102
- fs.writeFileSync(feedbackPath, lines.slice(-1000).join('\n') + '\n', 'utf-8');
107
+ var feedbackStat = fs.existsSync(feedbackPath) ? fs.statSync(feedbackPath) : null;
108
+ if (feedbackStat && feedbackStat.size > MAX_FEEDBACK) {
109
+ // Emergency tail-trim: the file is too large to comfortably read+split
110
+ // in full, so seek to a byte offset near the end, read only that tail,
111
+ // drop the first (possibly partial) line, and keep the rest — instead
112
+ // of the previous behavior which threw here and skipped trimming
113
+ // entirely, leaving the file to grow forever and permanently disabling
114
+ // consumers (router.cjs, route-handler.cjs) that bail out on oversized
115
+ // files.
116
+ var TAIL_BYTES = 256 * 1024; // ~256 KiB of tail content
117
+ var fd = fs.openSync(feedbackPath, 'r');
118
+ try {
119
+ var readSize = Math.min(TAIL_BYTES, feedbackStat.size);
120
+ var startOffset = feedbackStat.size - readSize;
121
+ var buf = Buffer.alloc(readSize);
122
+ fs.readSync(fd, buf, 0, readSize, startOffset);
123
+ var tailRaw = buf.toString('utf-8');
124
+ var tailLines = tailRaw.split('\n');
125
+ // Drop the first line if we didn't start at byte 0 — it's likely partial.
126
+ if (startOffset > 0) tailLines.shift();
127
+ var validTailLines = tailLines.filter(function(l) {
128
+ if (!l) return false;
129
+ try { JSON.parse(l); return true; } catch (eParse) { return false; }
130
+ });
131
+ var trimmedTail = validTailLines.slice(-1000);
132
+ var tmpFeedbackPath = feedbackPath + '.' + process.pid + '.tmp';
133
+ fs.writeFileSync(tmpFeedbackPath, trimmedTail.join('\n') + (trimmedTail.length > 0 ? '\n' : ''), 'utf-8');
134
+ fs.renameSync(tmpFeedbackPath, feedbackPath);
135
+ } finally {
136
+ fs.closeSync(fd);
137
+ }
138
+ } else {
139
+ var raw = fs.readFileSync(feedbackPath, 'utf-8');
140
+ var lines = raw.split('\n').filter(Boolean);
141
+ if (lines.length > 1000) {
142
+ var tmpFeedbackPath2 = feedbackPath + '.' + process.pid + '.tmp';
143
+ fs.writeFileSync(tmpFeedbackPath2, lines.slice(-1000).join('\n') + '\n', 'utf-8');
144
+ fs.renameSync(tmpFeedbackPath2, feedbackPath);
145
+ }
103
146
  }
104
147
  } catch (e2) { /* rotation is best-effort */ }
105
148
  }
@@ -141,19 +184,6 @@ module.exports = {
141
184
 
142
185
  // Memory Palace tombstone writes removed — redundant with raw session JSONL
143
186
 
144
- // ── Context Persistence Auto-Archive ─────────────────────────────────
145
- // Archive conversation context so it survives compaction and new sessions
146
- try {
147
- var cpHook = await import('file://' + path.join(__dirname, '..', 'context-persistence-hook.mjs'));
148
- if (cpHook && cpHook.archive) {
149
- await hCtx.runWithTimeout(function() { return cpHook.archive(); }, 'context-persistence.archive()');
150
- console.log('[CONTEXT_PERSIST] Session transcript archived');
151
- } else if (cpHook && cpHook.default && cpHook.default.archive) {
152
- await hCtx.runWithTimeout(function() { return cpHook.default.archive(); }, 'context-persistence.archive()');
153
- console.log('[CONTEXT_PERSIST] Session transcript archived');
154
- }
155
- } catch (e) { /* non-fatal — context-persistence may not export archive() */ }
156
-
157
187
  // ── Auto-populate: write session episode for every session ─────
158
188
  // Even solo sessions (no subagents) produce an episode so the
159
189
  // route handler can surface relevant past sessions.
@@ -206,18 +206,6 @@ module.exports = {
206
206
  }
207
207
  } catch (e) { /* non-fatal — hooks workers unavailable */ }
208
208
 
209
- // Context Persistence Auto-Restore
210
- try {
211
- var cpHook = await import('file://' + path.join(helpersDir, 'context-persistence-hook.mjs'));
212
- var restoreFn = (cpHook && cpHook.restore) || (cpHook && cpHook.default && cpHook.default.restore);
213
- if (restoreFn) {
214
- var restored = await runWithTimeout(function() { return restoreFn(); }, 'context-persistence.restore()');
215
- if (restored && restored.turns > 0) {
216
- console.log('[CONTEXT_RESTORED] ' + restored.turns + ' turns from previous session');
217
- }
218
- }
219
- } catch (e) { /* non-fatal */ }
220
-
221
209
  // AgentKnowledgeBase — preload shared knowledge context on session restore.
222
210
  try {
223
211
  var knowledgeDir = path.join(CWD, '.monomind', 'knowledge');
@@ -5,6 +5,8 @@
5
5
 
6
6
  const path = require('path');
7
7
  const fs = require('fs');
8
+ const { purgeStaleRegistrations } = require('../utils/agent-registrations.cjs');
9
+ const { atomicWriteFileSync, withLock } = require('../utils/fs-helpers.cjs');
8
10
 
9
11
  module.exports = {
10
12
  handlePreTask: async function(hCtx) {
@@ -50,36 +52,65 @@ module.exports = {
50
52
  intelligence.feedback(taskSuccess);
51
53
  } catch (e) { /* non-fatal */ }
52
54
  }
53
- // Each TeammateIdle/TaskCompleted = one agent done → remove oldest registration (FIFO)
55
+ // Each TeammateIdle/TaskCompleted = one agent done → remove its registration.
54
56
  const regDir = path.join(CWD, '.monomind', 'agents', 'registrations');
55
57
  try {
56
58
  if (fs.existsSync(regDir)) {
57
59
  const files = fs.readdirSync(regDir).filter(f => f.endsWith('.json'));
58
- if (files.length > 0) {
59
- // Sort by mtime ascending (oldest first) and remove the oldest one
60
+ // P3-15: post-task (TeammateIdle/TaskCompleted) also fires for the MAIN
61
+ // session's own tasks e.g. the team lead completing a self-assigned
62
+ // TaskList item — which never wrote an agent-start registration in the
63
+ // first place. Blindly popping the oldest registration on EVERY
64
+ // post-task event therefore deregistered an unrelated, still-running
65
+ // agent whenever the lead (not a subagent) finished a task, silently
66
+ // drifting the count negative-equivalent (undercounting active agents).
67
+ //
68
+ // Registrations now carry an `agentType` (agent-start-handler.cjs), and
69
+ // this hook's payload may carry the same identifying field under one of
70
+ // several possible names — mirroring the precedence agent-start-handler
71
+ // already uses to derive it. If this event carries NO such field at
72
+ // all, there's no evidence it corresponds to a real agent completion
73
+ // (as opposed to the main session's own task), so we skip touching
74
+ // registrations entirely rather than guessing via FIFO. When the field
75
+ // IS present, prefer removing the registration recorded with the SAME
76
+ // type; fall back to oldest-of-all only if no type match is found
77
+ // (e.g. a legacy registration written before this fix, with no
78
+ // agentType stored).
79
+ const completingType = hookInput.subagent_type || hookInput.agentType || hookInput.agent_type
80
+ || hookInput.agentSlug || hookInput.agent_slug || '';
81
+ if (files.length > 0 && completingType) {
60
82
  const sorted = files
61
- .map(f => ({ f, mtime: (() => { try { return fs.statSync(path.join(regDir, f)).mtimeMs; } catch { return 0; } })() }))
83
+ .map(f => {
84
+ let mtime = 0, agentType = null;
85
+ try { mtime = fs.statSync(path.join(regDir, f)).mtimeMs; } catch { /* ignore */ }
86
+ try { agentType = JSON.parse(fs.readFileSync(path.join(regDir, f), 'utf-8')).agentType || null; } catch { /* ignore */ }
87
+ return { f, mtime, agentType };
88
+ })
62
89
  .sort((a, b) => a.mtime - b.mtime);
63
- try { fs.unlinkSync(path.join(regDir, sorted[0].f)); } catch { /* ignore */ }
90
+ const typeMatch = sorted.find(r => r.agentType === completingType);
91
+ const toRemove = typeMatch || sorted[0];
92
+ try { fs.unlinkSync(path.join(regDir, toRemove.f)); } catch { /* ignore */ }
64
93
  }
65
- // Also purge any stragglers older than 30 min
66
- const now = Date.now();
67
- for (const f of fs.readdirSync(regDir).filter(f => f.endsWith('.json'))) {
68
- try { if (now - fs.statSync(path.join(regDir, f)).mtimeMs > 30 * 60 * 1000) fs.unlinkSync(path.join(regDir, f)); } catch { /* ignore */ }
69
- }
70
- const remaining = fs.readdirSync(regDir).filter(f => f.endsWith('.json')).length;
94
+ // Also purge any stragglers older than 30 min (shared with agent-start-handler.cjs)
95
+ const remaining = purgeStaleRegistrations(regDir) || 0;
96
+ // P2-21: shares a lock with agent-start-handler.cjs's swarm-activity.json
97
+ // writer (same path + '.lock') so the read-prevLastActive-then-write
98
+ // cycle can't race with that handler's concurrent write and silently
99
+ // drop whichever one wrote last — see that file for full rationale.
71
100
  const _actPath = path.join(CWD, '.monomind', 'metrics', 'swarm-activity.json');
72
- let _prevLastActive = 0;
73
- try { var _actSt = fs.statSync(_actPath); if (_actSt.size < 65536) { _prevLastActive = (JSON.parse(fs.readFileSync(_actPath, 'utf-8'))?.swarm?.lastActive) || 0; } } catch { /* ignore */ }
74
- fs.writeFileSync(_actPath, JSON.stringify({
75
- timestamp: new Date().toISOString(),
76
- swarm: {
77
- active: remaining > 0,
78
- agent_count: remaining,
79
- coordination_active: remaining > 0,
80
- lastActive: Math.max(remaining, _prevLastActive), // preserve peak across completion
81
- },
82
- }));
101
+ withLock(_actPath + '.lock', function() {
102
+ let _prevLastActive = 0;
103
+ try { var _actSt = fs.statSync(_actPath); if (_actSt.size < 65536) { _prevLastActive = (JSON.parse(fs.readFileSync(_actPath, 'utf-8'))?.swarm?.lastActive) || 0; } } catch { /* ignore */ }
104
+ atomicWriteFileSync(_actPath, JSON.stringify({
105
+ timestamp: new Date().toISOString(),
106
+ swarm: {
107
+ active: remaining > 0,
108
+ agent_count: remaining,
109
+ coordination_active: remaining > 0,
110
+ lastActive: Math.max(remaining, _prevLastActive), // preserve peak across completion
111
+ },
112
+ }));
113
+ }, 5000);
83
114
  }
84
115
  } catch (e) { /* non-fatal */ }
85
116
 
@@ -55,6 +55,7 @@ const {
55
55
  getMonographSuggestions, getMonographNeighbors,
56
56
  _recordGraphTelemetry, _injectCompactGraphMap,
57
57
  _findAffectedTests, _maybeRebuildMonograph,
58
+ _graphGateShouldBlock, _graphGateMarkQueried,
58
59
  } = monograph;
59
60
 
60
61
  const {
@@ -136,9 +137,49 @@ async function _ensureHooksModule() {
136
137
  _hooksModule = null; // not built — bridge stays a fail-soft no-op
137
138
  }
138
139
  }
140
+ if (!_hooksModule) _warnHooksBridgeUnavailable();
139
141
  return _hooksModule;
140
142
  }
141
143
 
144
+ // ── Visible one-time warning when the @monomind/hooks bridge fully fails ───
145
+ // Both load paths above (bare specifier + dev-repo file:// fallback) failed:
146
+ // the 15 background workers (metrics, security scan, DDD tracking, etc.) are
147
+ // unavailable for the rest of this session. This is almost always because
148
+ // @monomind/hooks was never resolvable from npm (it ships with
149
+ // optionalDependencies:"*", which npm silently skips) — NOT a problem with
150
+ // the user's own project setup. Historically this failed completely
151
+ // silently (see docs/AUDIT-BACKLOG.md P1-1), burning debugging time on the
152
+ // wrong target. Warned once per session (file-marker keyed by session id,
153
+ // same pattern as the once-per-day update check below) since every hook
154
+ // event is its own fresh `node` process and would otherwise spam this on
155
+ // every single tool call.
156
+ function _warnHooksBridgeUnavailable() {
157
+ try {
158
+ var sessId = String((hookInput && (hookInput.sessionId || hookInput.session_id)) || '');
159
+ var flagFile = path.join(CWD, '.monomind', 'hooks-bridge-warned.json');
160
+ var alreadyWarned = false;
161
+ if (sessId && fs.existsSync(flagFile)) {
162
+ try {
163
+ var flagData = JSON.parse(fs.readFileSync(flagFile, 'utf-8'));
164
+ if (flagData && flagData.sessionId === sessId) alreadyWarned = true;
165
+ } catch (e) { /* corrupt/unreadable flag file — warn again to be safe */ }
166
+ }
167
+ if (alreadyWarned) return;
168
+ process.stderr.write(
169
+ '[WARN] @monomind/hooks could not be loaded (bare specifier and dev-repo fallback both failed) — ' +
170
+ 'background workers (metrics, security scan, DDD tracking, etc.) are unavailable this session. ' +
171
+ 'This is not a problem with your project configuration — the package is not resolvable via npm ' +
172
+ 'from this install. See docs/AUDIT-BACKLOG.md P1-1 or https://github.com/monoes/monomind/issues.\n'
173
+ );
174
+ if (sessId) {
175
+ try {
176
+ fs.mkdirSync(path.join(CWD, '.monomind'), { recursive: true });
177
+ fs.writeFileSync(flagFile, JSON.stringify({ sessionId: sessId, warnedAt: new Date().toISOString() }), 'utf-8');
178
+ } catch (e) { /* non-fatal — worst case we warn again next event */ }
179
+ }
180
+ } catch (e) { /* never let the warning itself break a hook event */ }
181
+ }
182
+
142
183
  // ── Intelligence timeout protection (fixes #1530, #1531) ───────────────────
143
184
  var INTELLIGENCE_TIMEOUT_MS = 1500;
144
185
  function runWithTimeout(fn, label) {
@@ -351,11 +392,33 @@ const handlers = {
351
392
  h.handle(hCtx);
352
393
  },
353
394
 
354
- 'pre-bash': () => {
395
+ 'pre-bash': async () => {
396
+ // SECURITY GATE FIRST — destructive-ops enforcement must never be
397
+ // starved by the slower enrichment work below (monograph hint lookups).
398
+ // Previously this ran LAST, after up to 10 monograph SQLite strategies,
399
+ // AND was fired without awaiting its promise — meaning the block
400
+ // decision (process.exitCode) could still be unset when the process
401
+ // exited under the global 5s safety timer (see main()'s
402
+ // `process.exit(0)`), i.e. the gate could fail OPEN under time
403
+ // pressure. Awaiting it first guarantees the block/allow decision is
404
+ // computed and set before any enrichment work even starts.
405
+ var gates = require('./handlers/gates-handler.cjs');
406
+ await gates.handlePreBash(hCtx);
407
+ if (process.exitCode === 2) return; // blocked — skip enrichment entirely
408
+
355
409
  var cmd = (hCtx.toolInput && (hCtx.toolInput.command || hCtx.toolInput.cmd)) || '';
356
410
  var isGrep = /\b(?:grep|rg|ag)\b/.test(cmd);
357
411
  var isFind = /\b(?:find|fd)\b/.test(cmd) && !isGrep;
358
412
  if (isGrep || isFind) {
413
+ var sessIdGate = String((hCtx.hookInput && (hCtx.hookInput.sessionId || hCtx.hookInput.session_id)) || '');
414
+ if (_graphGateShouldBlock(sessIdGate)) {
415
+ process.stderr.write(JSON.stringify({
416
+ decision: 'block',
417
+ reason: '[graph-gate] Call mcp__monomind__monograph_query or monograph_suggest before grep/rg/find for code exploration (CLAUDE.md). This blocks once per session — after your first monograph call (or this one warning), Bash grep/find work normally for the rest of the session.',
418
+ }) + '\n');
419
+ process.exitCode = 2;
420
+ return;
421
+ }
359
422
  var graphAssisted = false;
360
423
  if (_isGraphFresh()) {
361
424
  try {
@@ -596,9 +659,6 @@ const handlers = {
596
659
  else if (isGrep) _recordGraphTelemetry('bash_grep_call');
597
660
  else _recordGraphTelemetry('bash_find_call');
598
661
  }
599
- // Enforcement gate: destructive operations
600
- var gates = require('./handlers/gates-handler.cjs');
601
- gates.handlePreBash(hCtx);
602
662
  },
603
663
 
604
664
  'pre-write': () => {
@@ -609,6 +669,15 @@ const handlers = {
609
669
 
610
670
  'pre-search': () => {
611
671
  var tool = hCtx.toolName || '';
672
+ var sessIdGate = String((hCtx.hookInput && (hCtx.hookInput.sessionId || hCtx.hookInput.session_id)) || '');
673
+ if (_graphGateShouldBlock(sessIdGate)) {
674
+ process.stderr.write(JSON.stringify({
675
+ decision: 'block',
676
+ reason: '[graph-gate] Call mcp__monomind__monograph_query or monograph_suggest before ' + (tool || 'Grep/Glob') + ' for code exploration (CLAUDE.md). This blocks once per session — after your first monograph call (or this one warning), search tools work normally for the rest of the session.',
677
+ }) + '\n');
678
+ process.exitCode = 2;
679
+ return;
680
+ }
612
681
  var graphResolved = false;
613
682
  try {
614
683
  var grepPattern = (typeof toolInput === 'object' && toolInput !== null)
@@ -767,6 +836,8 @@ const handlers = {
767
836
  'post-graph-tool': () => {
768
837
  // Record monograph MCP tool calls as graph wins
769
838
  _recordGraphTelemetry('monograph_call');
839
+ var sessIdGate = String((hCtx.hookInput && (hCtx.hookInput.sessionId || hCtx.hookInput.session_id)) || '');
840
+ _graphGateMarkQueried(sessIdGate);
770
841
  },
771
842
 
772
843
  'graph-status': () => {
@@ -13,6 +13,7 @@
13
13
 
14
14
  const path = require('path');
15
15
  const fs = require('fs');
16
+ const { claimLock, releaseLock } = require('./utils/fs-helpers.cjs');
16
17
 
17
18
  // Resolve base dir at require-time so tests can inject CLAUDE_PROJECT_DIR
18
19
  // per fresh require() call.
@@ -35,6 +36,76 @@ function ensureDataDir() {
35
36
  try { fs.mkdirSync(DATA_DIR, { recursive: true }); } catch (_) {}
36
37
  }
37
38
 
39
+ // ── multi-process-safe store flush (P1-14) ──────────────────────────────────
40
+ // STORE_FILE (auto-memory-store.json) is read once into `_entries` at init()
41
+ // and can be written by more than one code path — consolidate() and
42
+ // bootstrapFromDb() — each of which may be running in a *different* process
43
+ // (e.g. the long-lived MCP server process and a short-lived CJS hook
44
+ // subprocess launched concurrently). Without a lock + re-read-before-write,
45
+ // whichever process flushes last silently erases whatever the other process
46
+ // added since its own load. mergeAndWriteStore() re-reads the current
47
+ // on-disk file immediately before writing, merges the caller's updates in by
48
+ // `id` (keeping whichever record has the newer `ts`), and writes atomically
49
+ // via tmp+rename, guarded by a short advisory lock.
50
+
51
+ const STORE_LOCK_FILE = STORE_FILE + '.lock';
52
+ const STORE_LOCK_STALE_MS = 10 * 1000; // single JSON write — 10s is generous
53
+
54
+ // Uses fs-helpers.cjs's claimLock/releaseLock: unlike an unlink-then-recreate
55
+ // stale-break, it reclaims via an atomic rename, so two processes that both
56
+ // decide the lock is stale can't both end up believing they hold it (a real
57
+ // TOCTOU race a previous unlink-then-create version of this had — best-effort
58
+ // either way, since a missed lock still merges via mergeAndWriteStore's
59
+ // re-read, this just narrows the window further).
60
+ function claimStoreLock() {
61
+ return claimLock(STORE_LOCK_FILE, STORE_LOCK_STALE_MS);
62
+ }
63
+
64
+ function releaseStoreLock() {
65
+ releaseLock(STORE_LOCK_FILE);
66
+ }
67
+
68
+ /**
69
+ * Merge `updates` (new or changed entries) into the on-disk store and write
70
+ * the result atomically. Re-reads STORE_FILE immediately before writing so a
71
+ * concurrent flush from another process is merged, not clobbered. When both
72
+ * sides have an entry with the same `id`, the one with the newer `ts` wins.
73
+ */
74
+ function mergeAndWriteStore(updates, capTo) {
75
+ var acquired = claimStoreLock();
76
+ if (!acquired) acquired = claimStoreLock(); // one retry — lock is short-lived
77
+
78
+ try {
79
+ var diskRaw = safeReadJson(STORE_FILE);
80
+ var diskEntries = Array.isArray(diskRaw) ? diskRaw : [];
81
+ var merged = new Map();
82
+ for (var i = 0; i < diskEntries.length; i++) {
83
+ var d = diskEntries[i];
84
+ if (d && d.id) merged.set(String(d.id), d);
85
+ }
86
+ for (var j = 0; j < (updates || []).length; j++) {
87
+ var u = updates[j];
88
+ if (!u || !u.id) continue;
89
+ var key = String(u.id);
90
+ var existing = merged.get(key);
91
+ if (!existing || (u.ts || 0) >= (existing.ts || 0)) {
92
+ merged.set(key, u);
93
+ }
94
+ }
95
+ var result = Array.from(merged.values());
96
+ if (capTo && result.length > capTo) {
97
+ result.sort(function(a, b) { return (b.ts || 0) - (a.ts || 0); });
98
+ result = result.slice(0, capTo);
99
+ }
100
+ var tmpPath = STORE_FILE + '.' + process.pid + '.tmp';
101
+ fs.writeFileSync(tmpPath, JSON.stringify(result, null, 2), 'utf-8');
102
+ fs.renameSync(tmpPath, STORE_FILE);
103
+ return result;
104
+ } finally {
105
+ if (acquired) releaseStoreLock();
106
+ }
107
+ }
108
+
38
109
  function safeReadJson(filePath) {
39
110
  try {
40
111
  if (!fs.existsSync(filePath)) return null;
@@ -274,7 +345,11 @@ function consolidate() {
274
345
  }
275
346
 
276
347
  if (newStoreEntries.length > 0) {
277
- // Merge with existing store entries
348
+ // Decide which of newStoreEntries are worth adding, based on a read of
349
+ // the store as of "now". The actual write below re-reads immediately
350
+ // before flushing (mergeAndWriteStore), so a concurrent process's writes
351
+ // in between are merged rather than clobbered — this initial read is
352
+ // only used for the near-duplicate decision, not as the write's base.
278
353
  var existing = safeReadJson(STORE_FILE);
279
354
  var store = Array.isArray(existing) ? existing : [];
280
355
  var existingIds = new Set(store.map(function(e) { return e && e.id; }));
@@ -283,25 +358,23 @@ function consolidate() {
283
358
  var fileSetKey = function(e) { return (e.files || []).slice().sort().join('|'); };
284
359
  var seenSummaries = new Set(store.map(function(e) { return e && e.summary; }));
285
360
  var seenFileSets = new Set(store.filter(function(e) { return e && Array.isArray(e.files) && e.files.length > 0; }).map(fileSetKey));
361
+ var toAdd = [];
286
362
  var addedCount = 0;
287
363
  for (var j = 0; j < newStoreEntries.length; j++) {
288
364
  var ne = newStoreEntries[j];
289
365
  if (existingIds.has(ne.id)) continue;
290
366
  if (seenSummaries.has(ne.summary)) continue;
291
367
  if (ne.files && ne.files.length > 0 && seenFileSets.has(fileSetKey(ne))) continue;
292
- store.push(ne);
368
+ toAdd.push(ne);
293
369
  seenSummaries.add(ne.summary);
294
370
  if (ne.files && ne.files.length > 0) seenFileSets.add(fileSetKey(ne));
295
371
  addedCount++;
296
372
  }
297
- // Cap store at 200 entries to prevent unbounded growth
298
- if (store.length > 200) {
299
- store.sort(function(a, b) { return (b.ts || 0) - (a.ts || 0); });
300
- store = store.slice(0, 200);
373
+ if (toAdd.length > 0) {
374
+ try {
375
+ mergeAndWriteStore(toAdd, 200);
376
+ } catch (_) {}
301
377
  }
302
- try {
303
- fs.writeFileSync(STORE_FILE, JSON.stringify(store, null, 2), 'utf-8');
304
- } catch (_) {}
305
378
  count += addedCount;
306
379
  }
307
380
 
@@ -395,19 +468,20 @@ function bootstrapFromDb(db) {
395
468
  if (!db || _entries.length >= 5) return 0;
396
469
  try {
397
470
  var hubs = db.prepare(
398
- "SELECT n.name, n.label, n.file, COUNT(e.id) AS deg " +
399
- "FROM nodes n JOIN edges e ON (e.source = n.id OR e.target = n.id) " +
400
- "WHERE n.label IN ('File','Function','Class') AND n.file NOT LIKE '%node_modules%' AND n.file NOT LIKE '%dist/%' " +
471
+ "SELECT n.name, n.label, n.file_path AS file, COUNT(e.id) AS deg " +
472
+ "FROM nodes n JOIN edges e ON (e.source_id = n.id OR e.target_id = n.id) " +
473
+ "WHERE n.label IN ('File','Function','Class') AND n.file_path NOT LIKE '%node_modules%' AND n.file_path NOT LIKE '%dist/%' " +
401
474
  "GROUP BY n.id ORDER BY deg DESC LIMIT 10"
402
475
  ).all();
403
476
  if (hubs.length === 0) return 0;
404
477
  var existingIds = new Set(_entries.map(function(e) { return e.id; }));
478
+ var newHubEntries = [];
405
479
  var added = 0;
406
480
  for (var hi = 0; hi < hubs.length; hi++) {
407
481
  var h = hubs[hi];
408
482
  var bId = 'bootstrap-hub-' + hi;
409
483
  if (existingIds.has(bId)) continue;
410
- _entries.push({
484
+ var hubEntry = {
411
485
  id: bId,
412
486
  type: 'hub',
413
487
  content: h.name + ' (' + h.label + ') — ' + (h.file || '').replace(CWD + '/', '') + ' (' + h.deg + ' connections)',
@@ -415,12 +489,17 @@ function bootstrapFromDb(db) {
415
489
  confidence: 0.4,
416
490
  files: h.file ? [h.file] : [],
417
491
  ts: Date.now(),
418
- });
492
+ };
493
+ _entries.push(hubEntry);
494
+ newHubEntries.push(hubEntry);
419
495
  added++;
420
496
  }
421
497
  if (added > 0) {
422
498
  ensureDataDir();
423
- try { fs.writeFileSync(STORE_FILE, JSON.stringify(_entries, null, 2), 'utf-8'); } catch (_) {}
499
+ // mergeAndWriteStore re-reads STORE_FILE immediately before writing, so
500
+ // this only ever adds these hub entries into whatever is currently on
501
+ // disk — it never overwrites entries a concurrent process added.
502
+ try { mergeAndWriteStore(newHubEntries, 200); } catch (_) {}
424
503
  }
425
504
  return added;
426
505
  } catch (_) { return 0; }
@@ -9,6 +9,7 @@
9
9
 
10
10
  const path = require('path');
11
11
  const fs = require('fs');
12
+ const { atomicWriteFileSync } = require('./utils/fs-helpers.cjs');
12
13
 
13
14
  const CWD = process.env.CLAUDE_PROJECT_DIR || process.cwd();
14
15
 
@@ -54,7 +55,11 @@ function readCurrent() {
54
55
  function writeCurrent(data) {
55
56
  ensureDir();
56
57
  try {
57
- fs.writeFileSync(CURRENT_FILE, JSON.stringify(data, null, 2), 'utf-8');
58
+ // P2-21: tmp+rename — current.json is read+written by metric()/update()
59
+ // from multiple concurrent hook processes (pre-task, post-edit, etc. can
60
+ // all fire in one batched tool-call message); a plain writeFileSync lets
61
+ // a concurrent reader observe a partially-written file.
62
+ atomicWriteFileSync(CURRENT_FILE, JSON.stringify(data, null, 2), 'utf-8');
58
63
  } catch (_) {}
59
64
  }
60
65