@monoes/monomindcli 1.18.15 → 2.0.0

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 (511) hide show
  1. package/.claude/agents/core/researcher.md +29 -24
  2. package/.claude/agents/github/code-review-swarm.md +1 -1
  3. package/.claude/agents/github/github-modes.md +1 -1
  4. package/.claude/agents/github/issue-tracker.md +1 -3
  5. package/.claude/agents/github/multi-repo-swarm.md +1 -1
  6. package/.claude/agents/github/pr-manager.md +1 -3
  7. package/.claude/agents/github/project-board-sync.md +1 -1
  8. package/.claude/agents/github/release-manager.md +1 -1
  9. package/.claude/agents/github/repo-architect.md +4 -12
  10. package/.claude/agents/github/swarm-issue.md +1 -1
  11. package/.claude/agents/github/swarm-pr.md +1 -1
  12. package/.claude/agents/github/sync-coordinator.md +1 -1
  13. package/.claude/agents/github/workflow-automation.md +1 -1
  14. package/.claude/agents/goal/goal-planner.md +1 -2
  15. package/.claude/agents/specialized/specialized-workflow-architect.md +11 -14
  16. package/.claude/agents/testing/production-validator.md +8 -7
  17. package/.claude/agents/testing/testing-evidence-collector.md +3 -1
  18. package/.claude/commands/github/issue-tracker.md +0 -2
  19. package/.claude/commands/github/pr-manager.md +0 -2
  20. package/.claude/commands/github/repo-architect.md +3 -10
  21. package/.claude/commands/mastermind/code-review.md +4 -4
  22. package/.claude/commands/mastermind/help.md +5 -5
  23. package/.claude/commands/mastermind/okf-export.md +14 -0
  24. package/.claude/commands/mastermind/okf-import.md +15 -0
  25. package/.claude/commands/workflows/README.md +0 -1
  26. package/.claude/commands/workflows/workflow-create.md +0 -1
  27. package/.claude/commands/workflows/workflow-execute.md +1 -3
  28. package/.claude/commands/workflows/workflow-export.md +0 -2
  29. package/.claude/helpers/handlers/agent-start-handler.cjs +28 -36
  30. package/.claude/helpers/handlers/capture-handler.cjs +110 -0
  31. package/.claude/helpers/handlers/edit-handler.cjs +15 -0
  32. package/.claude/helpers/handlers/gates-handler.cjs +2 -8
  33. package/.claude/helpers/handlers/route-handler.cjs +314 -245
  34. package/.claude/helpers/handlers/session-handler.cjs +182 -163
  35. package/.claude/helpers/handlers/session-restore-handler.cjs +95 -53
  36. package/.claude/helpers/handlers/task-handler.cjs +17 -160
  37. package/.claude/helpers/hook-handler.cjs +153 -16
  38. package/.claude/helpers/intelligence.cjs +255 -15
  39. package/.claude/helpers/learning-service.mjs +1 -0
  40. package/.claude/helpers/mastermind-activate.cjs +33 -51
  41. package/.claude/helpers/monolean-activate.cjs +13 -3
  42. package/.claude/helpers/monolean-propagate.cjs +7 -3
  43. package/.claude/helpers/router.cjs +122 -11
  44. package/.claude/helpers/skill-registry.json +0 -189
  45. package/.claude/skills/github-toolkit/SKILL.md +60 -0
  46. package/.claude/skills/hive-mind-advanced/SKILL.md +0 -15
  47. package/.claude/skills/hooks-automation/SKILL.md +0 -1
  48. package/.claude/skills/mastermind-skills/_protocol.md +1 -1
  49. package/.claude/skills/mastermind-skills/architect.md +5 -6
  50. package/.claude/skills/mastermind-skills/autodev.md +8 -5
  51. package/.claude/skills/mastermind-skills/build.md +1 -2
  52. package/.claude/skills/mastermind-skills/review.md +8 -5
  53. package/.claude/skills/mastermind-skills/techport.md +37 -3
  54. package/.claude/skills/memory-toolkit/SKILL.md +75 -0
  55. package/.claude/skills/monodesign/document.md +9 -6
  56. package/.claude/skills/monodesign/extract.md +1 -1
  57. package/.claude/skills/monodesign/reference/document.md +1 -1
  58. package/.claude/skills/monodesign/reference/live.md +1 -1
  59. package/.claude/skills/monolean/SKILL.md +1 -1
  60. package/.claude/skills/specialagent/SKILL.md +2 -4
  61. package/.claude/skills/swarm-advanced/SKILL.md +0 -1
  62. package/README.md +2 -5
  63. package/bin/mcp-server.js +11 -1
  64. package/dist/src/autopilot-state.d.ts.map +1 -1
  65. package/dist/src/autopilot-state.js +4 -5
  66. package/dist/src/autopilot-state.js.map +1 -1
  67. package/dist/src/browser/dashboard/server.d.ts.map +1 -1
  68. package/dist/src/browser/dashboard/server.js +69 -1
  69. package/dist/src/browser/dashboard/server.js.map +1 -1
  70. package/dist/src/browser/dashboard/ui.html +214 -1764
  71. package/dist/src/capabilities/index.d.ts +0 -2
  72. package/dist/src/capabilities/index.d.ts.map +1 -1
  73. package/dist/src/capabilities/index.js +0 -1
  74. package/dist/src/capabilities/index.js.map +1 -1
  75. package/dist/src/commands/agent-lifecycle.d.ts.map +1 -1
  76. package/dist/src/commands/agent-lifecycle.js +2 -6
  77. package/dist/src/commands/agent-lifecycle.js.map +1 -1
  78. package/dist/src/commands/agent-ops.d.ts +1 -2
  79. package/dist/src/commands/agent-ops.d.ts.map +1 -1
  80. package/dist/src/commands/agent-ops.js +1 -59
  81. package/dist/src/commands/agent-ops.js.map +1 -1
  82. package/dist/src/commands/agent.d.ts.map +1 -1
  83. package/dist/src/commands/agent.js +2 -3
  84. package/dist/src/commands/agent.js.map +1 -1
  85. package/dist/src/commands/analyze-diff.js +1 -1
  86. package/dist/src/commands/analyze-diff.js.map +1 -1
  87. package/dist/src/commands/analyze.d.ts +0 -4
  88. package/dist/src/commands/analyze.d.ts.map +1 -1
  89. package/dist/src/commands/analyze.js +1 -29
  90. package/dist/src/commands/analyze.js.map +1 -1
  91. package/dist/src/commands/browse-action.d.ts.map +1 -1
  92. package/dist/src/commands/browse-action.js +94 -2
  93. package/dist/src/commands/browse-action.js.map +1 -1
  94. package/dist/src/commands/completions.d.ts.map +1 -1
  95. package/dist/src/commands/completions.js +12 -76
  96. package/dist/src/commands/completions.js.map +1 -1
  97. package/dist/src/commands/config.d.ts.map +1 -1
  98. package/dist/src/commands/config.js +0 -6
  99. package/dist/src/commands/config.js.map +1 -1
  100. package/dist/src/commands/doctor-project-checks.d.ts +13 -3
  101. package/dist/src/commands/doctor-project-checks.d.ts.map +1 -1
  102. package/dist/src/commands/doctor-project-checks.js +131 -23
  103. package/dist/src/commands/doctor-project-checks.js.map +1 -1
  104. package/dist/src/commands/doctor.d.ts.map +1 -1
  105. package/dist/src/commands/doctor.js +6 -5
  106. package/dist/src/commands/doctor.js.map +1 -1
  107. package/dist/src/commands/guidance.d.ts +5 -1
  108. package/dist/src/commands/guidance.d.ts.map +1 -1
  109. package/dist/src/commands/guidance.js +11 -556
  110. package/dist/src/commands/guidance.js.map +1 -1
  111. package/dist/src/commands/hive-mind-comms.d.ts.map +1 -1
  112. package/dist/src/commands/hive-mind-comms.js +11 -4
  113. package/dist/src/commands/hive-mind-comms.js.map +1 -1
  114. package/dist/src/commands/hive-mind-helpers.js +2 -2
  115. package/dist/src/commands/hive-mind-helpers.js.map +1 -1
  116. package/dist/src/commands/hive-mind-ops.d.ts +1 -3
  117. package/dist/src/commands/hive-mind-ops.d.ts.map +1 -1
  118. package/dist/src/commands/hive-mind-ops.js +2 -116
  119. package/dist/src/commands/hive-mind-ops.js.map +1 -1
  120. package/dist/src/commands/hive-mind.d.ts +4 -4
  121. package/dist/src/commands/hive-mind.d.ts.map +1 -1
  122. package/dist/src/commands/hive-mind.js +11 -11
  123. package/dist/src/commands/hive-mind.js.map +1 -1
  124. package/dist/src/commands/hooks-coverage-commands.d.ts.map +1 -1
  125. package/dist/src/commands/hooks-coverage-commands.js +8 -7
  126. package/dist/src/commands/hooks-coverage-commands.js.map +1 -1
  127. package/dist/src/commands/hooks-coverage-gaps.js +1 -1
  128. package/dist/src/commands/hooks-coverage-gaps.js.map +1 -1
  129. package/dist/src/commands/hooks-coverage-routing.js +2 -2
  130. package/dist/src/commands/hooks-coverage-routing.js.map +1 -1
  131. package/dist/src/commands/hooks-extended-commands.d.ts +0 -3
  132. package/dist/src/commands/hooks-extended-commands.d.ts.map +1 -1
  133. package/dist/src/commands/hooks-extended-commands.js +0 -307
  134. package/dist/src/commands/hooks-extended-commands.js.map +1 -1
  135. package/dist/src/commands/hooks-formatting.d.ts +1 -5
  136. package/dist/src/commands/hooks-formatting.d.ts.map +1 -1
  137. package/dist/src/commands/hooks-formatting.js +1 -18
  138. package/dist/src/commands/hooks-formatting.js.map +1 -1
  139. package/dist/src/commands/hooks-workers.d.ts +1 -1
  140. package/dist/src/commands/hooks-workers.d.ts.map +1 -1
  141. package/dist/src/commands/hooks-workers.js +82 -330
  142. package/dist/src/commands/hooks-workers.js.map +1 -1
  143. package/dist/src/commands/hooks.d.ts.map +1 -1
  144. package/dist/src/commands/hooks.js +1 -12
  145. package/dist/src/commands/hooks.js.map +1 -1
  146. package/dist/src/commands/index.d.ts +2 -55
  147. package/dist/src/commands/index.d.ts.map +1 -1
  148. package/dist/src/commands/index.js +23 -216
  149. package/dist/src/commands/index.js.map +1 -1
  150. package/dist/src/commands/init-wizard.d.ts.map +1 -1
  151. package/dist/src/commands/init-wizard.js +3 -5
  152. package/dist/src/commands/init-wizard.js.map +1 -1
  153. package/dist/src/commands/init.d.ts.map +1 -1
  154. package/dist/src/commands/init.js +4 -24
  155. package/dist/src/commands/init.js.map +1 -1
  156. package/dist/src/commands/mcp.d.ts.map +1 -1
  157. package/dist/src/commands/mcp.js +32 -4
  158. package/dist/src/commands/mcp.js.map +1 -1
  159. package/dist/src/commands/memory-admin.d.ts +1 -2
  160. package/dist/src/commands/memory-admin.d.ts.map +1 -1
  161. package/dist/src/commands/memory-admin.js +1 -118
  162. package/dist/src/commands/memory-admin.js.map +1 -1
  163. package/dist/src/commands/memory-transfer.d.ts +1 -2
  164. package/dist/src/commands/memory-transfer.d.ts.map +1 -1
  165. package/dist/src/commands/memory-transfer.js +5 -171
  166. package/dist/src/commands/memory-transfer.js.map +1 -1
  167. package/dist/src/commands/memory.d.ts.map +1 -1
  168. package/dist/src/commands/memory.js +3 -6
  169. package/dist/src/commands/memory.js.map +1 -1
  170. package/dist/src/commands/neural-core.d.ts +3 -1
  171. package/dist/src/commands/neural-core.d.ts.map +1 -1
  172. package/dist/src/commands/neural-core.js +154 -15
  173. package/dist/src/commands/neural-core.js.map +1 -1
  174. package/dist/src/commands/neural-optimize.d.ts.map +1 -1
  175. package/dist/src/commands/neural-optimize.js +13 -15
  176. package/dist/src/commands/neural-optimize.js.map +1 -1
  177. package/dist/src/commands/neural-registry.d.ts +1 -1
  178. package/dist/src/commands/neural-registry.js +14 -14
  179. package/dist/src/commands/neural-registry.js.map +1 -1
  180. package/dist/src/commands/neural.d.ts +1 -1
  181. package/dist/src/commands/neural.js +6 -6
  182. package/dist/src/commands/neural.js.map +1 -1
  183. package/dist/src/commands/performance.d.ts.map +1 -1
  184. package/dist/src/commands/performance.js +68 -58
  185. package/dist/src/commands/performance.js.map +1 -1
  186. package/dist/src/commands/providers.d.ts.map +1 -1
  187. package/dist/src/commands/providers.js +77 -117
  188. package/dist/src/commands/providers.js.map +1 -1
  189. package/dist/src/commands/search-universal.d.ts +7 -1
  190. package/dist/src/commands/search-universal.d.ts.map +1 -1
  191. package/dist/src/commands/search-universal.js +59 -5
  192. package/dist/src/commands/search-universal.js.map +1 -1
  193. package/dist/src/commands/security-cve.d.ts.map +1 -1
  194. package/dist/src/commands/security-cve.js +3 -5
  195. package/dist/src/commands/security-cve.js.map +1 -1
  196. package/dist/src/commands/security-misc.d.ts +0 -1
  197. package/dist/src/commands/security-misc.d.ts.map +1 -1
  198. package/dist/src/commands/security-misc.js +69 -45
  199. package/dist/src/commands/security-misc.js.map +1 -1
  200. package/dist/src/commands/security.d.ts.map +1 -1
  201. package/dist/src/commands/security.js +2 -4
  202. package/dist/src/commands/security.js.map +1 -1
  203. package/dist/src/commands/session.d.ts.map +1 -1
  204. package/dist/src/commands/session.js +137 -281
  205. package/dist/src/commands/session.js.map +1 -1
  206. package/dist/src/commands/start.d.ts.map +1 -1
  207. package/dist/src/commands/start.js +2 -59
  208. package/dist/src/commands/start.js.map +1 -1
  209. package/dist/src/commands/status.d.ts.map +1 -1
  210. package/dist/src/commands/status.js +18 -29
  211. package/dist/src/commands/status.js.map +1 -1
  212. package/dist/src/commands/swarm.d.ts.map +1 -1
  213. package/dist/src/commands/swarm.js +113 -66
  214. package/dist/src/commands/swarm.js.map +1 -1
  215. package/dist/src/commands/task.d.ts.map +1 -1
  216. package/dist/src/commands/task.js +2 -49
  217. package/dist/src/commands/task.js.map +1 -1
  218. package/dist/src/consensus/audit-writer.d.ts.map +1 -1
  219. package/dist/src/consensus/audit-writer.js +43 -1
  220. package/dist/src/consensus/audit-writer.js.map +1 -1
  221. package/dist/src/consensus/tally.d.ts +19 -0
  222. package/dist/src/consensus/tally.d.ts.map +1 -0
  223. package/dist/src/consensus/tally.js +34 -0
  224. package/dist/src/consensus/tally.js.map +1 -0
  225. package/dist/src/index.d.ts +3 -2
  226. package/dist/src/index.d.ts.map +1 -1
  227. package/dist/src/index.js +13 -9
  228. package/dist/src/index.js.map +1 -1
  229. package/dist/src/init/claudemd-generator.d.ts.map +1 -1
  230. package/dist/src/init/claudemd-generator.js +10 -14
  231. package/dist/src/init/claudemd-generator.js.map +1 -1
  232. package/dist/src/init/executor.d.ts.map +1 -1
  233. package/dist/src/init/executor.js +42 -100
  234. package/dist/src/init/executor.js.map +1 -1
  235. package/dist/src/init/helpers-generator.d.ts.map +1 -1
  236. package/dist/src/init/helpers-generator.js +2 -22
  237. package/dist/src/init/helpers-generator.js.map +1 -1
  238. package/dist/src/init/settings-generator.d.ts.map +1 -1
  239. package/dist/src/init/settings-generator.js +0 -13
  240. package/dist/src/init/settings-generator.js.map +1 -1
  241. package/dist/src/init/statusline-generator.d.ts.map +1 -1
  242. package/dist/src/init/statusline-generator.js +62 -0
  243. package/dist/src/init/statusline-generator.js.map +1 -1
  244. package/dist/src/init/types.d.ts +3 -9
  245. package/dist/src/init/types.d.ts.map +1 -1
  246. package/dist/src/init/types.js +0 -5
  247. package/dist/src/init/types.js.map +1 -1
  248. package/dist/src/knowledge/document-pipeline.d.ts.map +1 -1
  249. package/dist/src/knowledge/document-pipeline.js +18 -8
  250. package/dist/src/knowledge/document-pipeline.js.map +1 -1
  251. package/dist/src/mcp-client.d.ts.map +1 -1
  252. package/dist/src/mcp-client.js +0 -8
  253. package/dist/src/mcp-client.js.map +1 -1
  254. package/dist/src/mcp-server.d.ts.map +1 -1
  255. package/dist/src/mcp-server.js +14 -0
  256. package/dist/src/mcp-server.js.map +1 -1
  257. package/dist/src/mcp-tools/agent-tools.d.ts.map +1 -1
  258. package/dist/src/mcp-tools/agent-tools.js +0 -17
  259. package/dist/src/mcp-tools/agent-tools.js.map +1 -1
  260. package/dist/src/mcp-tools/coherence/causal-infer.d.ts +5 -5
  261. package/dist/src/mcp-tools/coherence/causal-infer.d.ts.map +1 -1
  262. package/dist/src/mcp-tools/coherence/causal-infer.js +32 -46
  263. package/dist/src/mcp-tools/coherence/causal-infer.js.map +1 -1
  264. package/dist/src/mcp-tools/coherence/coherence-check.d.ts.map +1 -1
  265. package/dist/src/mcp-tools/coherence/coherence-check.js +1 -19
  266. package/dist/src/mcp-tools/coherence/coherence-check.js.map +1 -1
  267. package/dist/src/mcp-tools/coherence/consensus-verify.d.ts +2 -3
  268. package/dist/src/mcp-tools/coherence/consensus-verify.d.ts.map +1 -1
  269. package/dist/src/mcp-tools/coherence/consensus-verify.js +22 -20
  270. package/dist/src/mcp-tools/coherence/consensus-verify.js.map +1 -1
  271. package/dist/src/mcp-tools/coherence/memory-gate.d.ts +3 -2
  272. package/dist/src/mcp-tools/coherence/memory-gate.d.ts.map +1 -1
  273. package/dist/src/mcp-tools/coherence/memory-gate.js +32 -19
  274. package/dist/src/mcp-tools/coherence/memory-gate.js.map +1 -1
  275. package/dist/src/mcp-tools/coherence/quantum-topology.d.ts +4 -4
  276. package/dist/src/mcp-tools/coherence/quantum-topology.d.ts.map +1 -1
  277. package/dist/src/mcp-tools/coherence/quantum-topology.js +11 -17
  278. package/dist/src/mcp-tools/coherence/quantum-topology.js.map +1 -1
  279. package/dist/src/mcp-tools/coherence/spectral-analyze.d.ts +2 -3
  280. package/dist/src/mcp-tools/coherence/spectral-analyze.d.ts.map +1 -1
  281. package/dist/src/mcp-tools/coherence/spectral-analyze.js +51 -32
  282. package/dist/src/mcp-tools/coherence/spectral-analyze.js.map +1 -1
  283. package/dist/src/mcp-tools/coherence/types.d.ts +8 -11
  284. package/dist/src/mcp-tools/coherence/types.d.ts.map +1 -1
  285. package/dist/src/mcp-tools/coherence/types.js +3 -18
  286. package/dist/src/mcp-tools/coherence/types.js.map +1 -1
  287. package/dist/src/mcp-tools/embeddings-tools.d.ts.map +1 -1
  288. package/dist/src/mcp-tools/embeddings-tools.js +1 -7
  289. package/dist/src/mcp-tools/embeddings-tools.js.map +1 -1
  290. package/dist/src/mcp-tools/graphify-tools.js +2 -2
  291. package/dist/src/mcp-tools/graphify-tools.js.map +1 -1
  292. package/dist/src/mcp-tools/guidance-tools.d.ts.map +1 -1
  293. package/dist/src/mcp-tools/guidance-tools.js +9 -19
  294. package/dist/src/mcp-tools/guidance-tools.js.map +1 -1
  295. package/dist/src/mcp-tools/hive-mind-tools.d.ts +8 -1
  296. package/dist/src/mcp-tools/hive-mind-tools.d.ts.map +1 -1
  297. package/dist/src/mcp-tools/hive-mind-tools.js +198 -40
  298. package/dist/src/mcp-tools/hive-mind-tools.js.map +1 -1
  299. package/dist/src/mcp-tools/hooks-advanced.d.ts +18 -0
  300. package/dist/src/mcp-tools/hooks-advanced.d.ts.map +1 -0
  301. package/dist/src/mcp-tools/hooks-advanced.js +25 -0
  302. package/dist/src/mcp-tools/hooks-advanced.js.map +1 -0
  303. package/dist/src/mcp-tools/hooks-intelligence.d.ts +4 -8
  304. package/dist/src/mcp-tools/hooks-intelligence.d.ts.map +1 -1
  305. package/dist/src/mcp-tools/hooks-intelligence.js +33 -482
  306. package/dist/src/mcp-tools/hooks-intelligence.js.map +1 -1
  307. package/dist/src/mcp-tools/hooks-routing.d.ts +1 -3
  308. package/dist/src/mcp-tools/hooks-routing.d.ts.map +1 -1
  309. package/dist/src/mcp-tools/hooks-routing.js +96 -202
  310. package/dist/src/mcp-tools/hooks-routing.js.map +1 -1
  311. package/dist/src/mcp-tools/hooks-synthesis.d.ts +31 -0
  312. package/dist/src/mcp-tools/hooks-synthesis.d.ts.map +1 -0
  313. package/dist/src/mcp-tools/hooks-synthesis.js +196 -0
  314. package/dist/src/mcp-tools/hooks-synthesis.js.map +1 -0
  315. package/dist/src/mcp-tools/hooks-tools.d.ts.map +1 -1
  316. package/dist/src/mcp-tools/hooks-tools.js +10 -11
  317. package/dist/src/mcp-tools/hooks-tools.js.map +1 -1
  318. package/dist/src/mcp-tools/index.d.ts +0 -3
  319. package/dist/src/mcp-tools/index.d.ts.map +1 -1
  320. package/dist/src/mcp-tools/index.js +0 -4
  321. package/dist/src/mcp-tools/index.js.map +1 -1
  322. package/dist/src/mcp-tools/memory-tools.d.ts.map +1 -1
  323. package/dist/src/mcp-tools/memory-tools.js +24 -9
  324. package/dist/src/mcp-tools/memory-tools.js.map +1 -1
  325. package/dist/src/mcp-tools/monograph-tools.d.ts +6 -0
  326. package/dist/src/mcp-tools/monograph-tools.d.ts.map +1 -1
  327. package/dist/src/mcp-tools/monograph-tools.js +370 -95
  328. package/dist/src/mcp-tools/monograph-tools.js.map +1 -1
  329. package/dist/src/mcp-tools/neural-tools.d.ts +8 -9
  330. package/dist/src/mcp-tools/neural-tools.d.ts.map +1 -1
  331. package/dist/src/mcp-tools/neural-tools.js +249 -539
  332. package/dist/src/mcp-tools/neural-tools.js.map +1 -1
  333. package/dist/src/mcp-tools/performance-tools.d.ts.map +1 -1
  334. package/dist/src/mcp-tools/performance-tools.js +5 -17
  335. package/dist/src/mcp-tools/performance-tools.js.map +1 -1
  336. package/dist/src/mcp-tools/quality/coverage-analysis/prioritize-gaps.js +2 -2
  337. package/dist/src/mcp-tools/quality/coverage-analysis/prioritize-gaps.js.map +1 -1
  338. package/dist/src/mcp-tools/quality/security-compliance/detect-secrets.d.ts +4 -4
  339. package/dist/src/mcp-tools/quality-tools.d.ts +7 -2
  340. package/dist/src/mcp-tools/quality-tools.d.ts.map +1 -1
  341. package/dist/src/mcp-tools/quality-tools.js +7 -257
  342. package/dist/src/mcp-tools/quality-tools.js.map +1 -1
  343. package/dist/src/mcp-tools/security-tools.d.ts.map +1 -1
  344. package/dist/src/mcp-tools/security-tools.js +103 -0
  345. package/dist/src/mcp-tools/security-tools.js.map +1 -1
  346. package/dist/src/memory/intelligence.d.ts +9 -9
  347. package/dist/src/memory/intelligence.d.ts.map +1 -1
  348. package/dist/src/memory/intelligence.js +71 -59
  349. package/dist/src/memory/intelligence.js.map +1 -1
  350. package/dist/src/memory/memory-bridge.d.ts +1 -0
  351. package/dist/src/memory/memory-bridge.d.ts.map +1 -1
  352. package/dist/src/memory/memory-bridge.js +47 -5
  353. package/dist/src/memory/memory-bridge.js.map +1 -1
  354. package/dist/src/memory/memory-read.d.ts.map +1 -1
  355. package/dist/src/memory/memory-read.js +1 -19
  356. package/dist/src/memory/memory-read.js.map +1 -1
  357. package/dist/src/suggest.d.ts.map +1 -1
  358. package/dist/src/suggest.js +1 -12
  359. package/dist/src/suggest.js.map +1 -1
  360. package/dist/src/transfer/store/discovery.d.ts +3 -2
  361. package/dist/src/transfer/store/discovery.d.ts.map +1 -1
  362. package/dist/src/transfer/store/discovery.js +22 -70
  363. package/dist/src/transfer/store/discovery.js.map +1 -1
  364. package/dist/src/update/checker.d.ts.map +1 -1
  365. package/dist/src/update/checker.js +0 -1
  366. package/dist/src/update/checker.js.map +1 -1
  367. package/dist/src/utils/cosine-similarity.d.ts +22 -0
  368. package/dist/src/utils/cosine-similarity.d.ts.map +1 -0
  369. package/dist/src/utils/cosine-similarity.js +38 -0
  370. package/dist/src/utils/cosine-similarity.js.map +1 -0
  371. package/dist/src/utils/input-guards.d.ts +51 -0
  372. package/dist/src/utils/input-guards.d.ts.map +1 -0
  373. package/dist/src/utils/input-guards.js +223 -0
  374. package/dist/src/utils/input-guards.js.map +1 -0
  375. package/dist/src/utils/json-file.d.ts +33 -0
  376. package/dist/src/utils/json-file.d.ts.map +1 -0
  377. package/dist/src/utils/json-file.js +57 -0
  378. package/dist/src/utils/json-file.js.map +1 -0
  379. package/dist/tsconfig.tsbuildinfo +1 -1
  380. package/package.json +9 -6
  381. package/scripts/sync-claude-assets.sh +16 -20
  382. package/.claude/agents/generated/case-analyst.md +0 -50
  383. package/.claude/agents/generated/channel-intelligence-director.md +0 -87
  384. package/.claude/agents/generated/chief-growth-officer.md +0 -88
  385. package/.claude/agents/generated/churn-analyst.md +0 -53
  386. package/.claude/agents/generated/code-reviewer.md +0 -55
  387. package/.claude/agents/generated/code-validator.md +0 -57
  388. package/.claude/agents/generated/complexity-scanner.md +0 -56
  389. package/.claude/agents/generated/content-seo-strategist.md +0 -90
  390. package/.claude/agents/generated/copy-editor.md +0 -45
  391. package/.claude/agents/generated/court-reporter.md +0 -50
  392. package/.claude/agents/generated/defender.md +0 -51
  393. package/.claude/agents/generated/devbot-orchestrator.md +0 -58
  394. package/.claude/agents/generated/devbot-planner.md +0 -63
  395. package/.claude/agents/generated/developer-community-strategist.md +0 -91
  396. package/.claude/agents/generated/editor-in-chief.md +0 -45
  397. package/.claude/agents/generated/fact-checker.md +0 -45
  398. package/.claude/agents/generated/impact-assessor.md +0 -54
  399. package/.claude/agents/generated/judge.md +0 -51
  400. package/.claude/agents/generated/outreach-partnership-strategist.md +0 -90
  401. package/.claude/agents/generated/prosecutor.md +0 -51
  402. package/.claude/agents/generated/reporter.md +0 -45
  403. package/.claude/agents/generated/social-media-strategist.md +0 -91
  404. package/.claude/agents/generated/video-visual-strategist.md +0 -90
  405. package/.claude/agents/reengineer-squad/boss.md +0 -113
  406. package/.claude/agents/reengineer-squad/critic-architect.md +0 -132
  407. package/.claude/agents/reengineer-squad/git-manager.md +0 -145
  408. package/.claude/agents/reengineer-squad/idea-generator.md +0 -95
  409. package/.claude/agents/reengineer-squad/implementer.md +0 -112
  410. package/.claude/agents/reengineer-squad/integration-planner.md +0 -112
  411. package/.claude/agents/reengineer-squad/source-analyst.md +0 -103
  412. package/.claude/agents/reengineer-squad/target-analyst.md +0 -118
  413. package/.claude/agents/reengineer-squad/tester.md +0 -105
  414. package/.claude/agents/sparc/architecture.md +0 -453
  415. package/.claude/agents/sparc/pseudocode.md +0 -299
  416. package/.claude/agents/sparc/refinement.md +0 -504
  417. package/.claude/agents/sparc/specification.md +0 -258
  418. package/.claude/agents/templates/implementer-sparc-coder.md +0 -231
  419. package/.claude/commands/sparc/analyzer.md +0 -35
  420. package/.claude/commands/sparc/architect.md +0 -36
  421. package/.claude/commands/sparc/ask.md +0 -56
  422. package/.claude/commands/sparc/batch-executor.md +0 -37
  423. package/.claude/commands/sparc/code.md +0 -48
  424. package/.claude/commands/sparc/coder.md +0 -37
  425. package/.claude/commands/sparc/debug.md +0 -42
  426. package/.claude/commands/sparc/debugger.md +0 -37
  427. package/.claude/commands/sparc/designer.md +0 -36
  428. package/.claude/commands/sparc/devops.md +0 -68
  429. package/.claude/commands/sparc/docs-writer.md +0 -39
  430. package/.claude/commands/sparc/documenter.md +0 -37
  431. package/.claude/commands/sparc/innovator.md +0 -37
  432. package/.claude/commands/sparc/integration.md +0 -42
  433. package/.claude/commands/sparc/mcp.md +0 -76
  434. package/.claude/commands/sparc/memory-manager.md +0 -57
  435. package/.claude/commands/sparc/optimizer.md +0 -37
  436. package/.claude/commands/sparc/orchestrator.md +0 -70
  437. package/.claude/commands/sparc/post-deployment-monitoring-mode.md +0 -42
  438. package/.claude/commands/sparc/refinement-optimization-mode.md +0 -42
  439. package/.claude/commands/sparc/researcher.md +0 -37
  440. package/.claude/commands/sparc/reviewer.md +0 -37
  441. package/.claude/commands/sparc/security-review.md +0 -39
  442. package/.claude/commands/sparc/sparc-modes.md +0 -120
  443. package/.claude/commands/sparc/sparc.md +0 -71
  444. package/.claude/commands/sparc/spec-pseudocode.md +0 -39
  445. package/.claude/commands/sparc/supabase-admin.md +0 -301
  446. package/.claude/commands/sparc/swarm-coordinator.md +0 -50
  447. package/.claude/commands/sparc/tdd.md +0 -37
  448. package/.claude/commands/sparc/tester.md +0 -37
  449. package/.claude/commands/sparc/tutorial.md +0 -38
  450. package/.claude/commands/sparc/workflow-manager.md +0 -37
  451. package/.claude/commands/sparc.md +0 -112
  452. package/.claude/helpers/auto-memory-hook.mjs +0 -503
  453. package/.claude/skills/sparc-methodology/SKILL.md +0 -950
  454. package/dist/src/capabilities/enrichment.d.ts +0 -44
  455. package/dist/src/capabilities/enrichment.d.ts.map +0 -1
  456. package/dist/src/capabilities/enrichment.js +0 -141
  457. package/dist/src/capabilities/enrichment.js.map +0 -1
  458. package/dist/src/commands/analyze-boundaries.d.ts +0 -14
  459. package/dist/src/commands/analyze-boundaries.d.ts.map +0 -1
  460. package/dist/src/commands/analyze-boundaries.js +0 -295
  461. package/dist/src/commands/analyze-boundaries.js.map +0 -1
  462. package/dist/src/commands/analyze-graph.d.ts +0 -14
  463. package/dist/src/commands/analyze-graph.d.ts.map +0 -1
  464. package/dist/src/commands/analyze-graph.js +0 -304
  465. package/dist/src/commands/analyze-graph.js.map +0 -1
  466. package/dist/src/commands/claims.d.ts +0 -10
  467. package/dist/src/commands/claims.d.ts.map +0 -1
  468. package/dist/src/commands/claims.js +0 -650
  469. package/dist/src/commands/claims.js.map +0 -1
  470. package/dist/src/commands/daemon.d.ts +0 -8
  471. package/dist/src/commands/daemon.d.ts.map +0 -1
  472. package/dist/src/commands/daemon.js +0 -681
  473. package/dist/src/commands/daemon.js.map +0 -1
  474. package/dist/src/commands/deployment.d.ts +0 -10
  475. package/dist/src/commands/deployment.d.ts.map +0 -1
  476. package/dist/src/commands/deployment.js +0 -706
  477. package/dist/src/commands/deployment.js.map +0 -1
  478. package/dist/src/commands/enrich.d.ts +0 -10
  479. package/dist/src/commands/enrich.d.ts.map +0 -1
  480. package/dist/src/commands/enrich.js +0 -58
  481. package/dist/src/commands/enrich.js.map +0 -1
  482. package/dist/src/commands/issues.d.ts +0 -21
  483. package/dist/src/commands/issues.d.ts.map +0 -1
  484. package/dist/src/commands/issues.js +0 -575
  485. package/dist/src/commands/issues.js.map +0 -1
  486. package/dist/src/commands/workflow.d.ts +0 -8
  487. package/dist/src/commands/workflow.d.ts.map +0 -1
  488. package/dist/src/commands/workflow.js +0 -677
  489. package/dist/src/commands/workflow.js.map +0 -1
  490. package/dist/src/mcp-tools/workflow-tools.d.ts +0 -8
  491. package/dist/src/mcp-tools/workflow-tools.d.ts.map +0 -1
  492. package/dist/src/mcp-tools/workflow-tools.js +0 -717
  493. package/dist/src/mcp-tools/workflow-tools.js.map +0 -1
  494. package/dist/src/services/claim-service.d.ts +0 -198
  495. package/dist/src/services/claim-service.d.ts.map +0 -1
  496. package/dist/src/services/claim-service.js +0 -890
  497. package/dist/src/services/claim-service.js.map +0 -1
  498. package/dist/src/services/headless-worker-executor.d.ts +0 -311
  499. package/dist/src/services/headless-worker-executor.d.ts.map +0 -1
  500. package/dist/src/services/headless-worker-executor.js +0 -1183
  501. package/dist/src/services/headless-worker-executor.js.map +0 -1
  502. package/dist/src/services/worker-daemon.d.ts +0 -248
  503. package/dist/src/services/worker-daemon.d.ts.map +0 -1
  504. package/dist/src/services/worker-daemon.js +0 -1417
  505. package/dist/src/services/worker-daemon.js.map +0 -1
  506. package/dist/src/ui/.monomind/capture/active-run.json +0 -1
  507. package/dist/src/ui/.monomind/orgs/system-trial-qa/runs/real-events-1782290897.convs.jsonl +0 -3
  508. package/dist/src/ui/.monomind/orgs/system-trial-qa/runs/real-events-1782290897.jsonl +0 -11
  509. package/dist/src/ui/.monomind/orgs/system-trial-qa/runs/rigid-qa-restart-1782288201.jsonl +0 -540
  510. package/dist/src/ui/.monomind/orgs/system-trial-qa-threads.jsonl +0 -3
  511. package/dist/src/ui/.monomind/orgs/test-event-fix/runs/rigid-qa-restart-1782288201.jsonl +0 -2
@@ -1,1417 +0,0 @@
1
- /**
2
- * Worker Daemon Service
3
- * Node.js-based background worker system that auto-runs like shell daemons
4
- *
5
- * Workers:
6
- * - map: Codebase mapping (5 min interval)
7
- * - audit: Security analysis (10 min interval)
8
- * - optimize: Performance optimization (15 min interval)
9
- * - consolidate: Memory consolidation (30 min interval)
10
- * - testgaps: Test coverage analysis (20 min interval)
11
- */
12
- import { EventEmitter } from 'events';
13
- import { existsSync, mkdirSync, writeFileSync, renameSync, readFileSync, appendFileSync, unlinkSync, statSync } from 'fs';
14
- import { cpus } from 'os';
15
- import { join, resolve } from 'path';
16
- import { HeadlessWorkerExecutor, isHeadlessWorker, } from './headless-worker-executor.js';
17
- // Default worker configurations with improved intervals (P0 fix: map 5min -> 15min)
18
- const DEFAULT_WORKERS = [
19
- { type: 'map', intervalMs: 15 * 60 * 1000, offsetMs: 0, priority: 'normal', description: 'Codebase mapping', enabled: true },
20
- { type: 'audit', intervalMs: 10 * 60 * 1000, offsetMs: 2 * 60 * 1000, priority: 'critical', description: 'Security analysis', enabled: true },
21
- { type: 'optimize', intervalMs: 15 * 60 * 1000, offsetMs: 4 * 60 * 1000, priority: 'high', description: 'Performance optimization', enabled: true },
22
- { type: 'consolidate', intervalMs: 30 * 60 * 1000, offsetMs: 6 * 60 * 1000, priority: 'low', description: 'Memory consolidation', enabled: true },
23
- { type: 'testgaps', intervalMs: 20 * 60 * 1000, offsetMs: 8 * 60 * 1000, priority: 'normal', description: 'Test coverage analysis', enabled: true },
24
- { type: 'predict', intervalMs: 10 * 60 * 1000, offsetMs: 0, priority: 'low', description: 'Predictive preloading', enabled: false },
25
- { type: 'document', intervalMs: 60 * 60 * 1000, offsetMs: 0, priority: 'low', description: 'Auto-documentation', enabled: false },
26
- ];
27
- // Worker timeout — must exceed the longest per-worker headless timeout (15 min for audit/refactor).
28
- // Previously 5 min, which caused orphan processes when daemon timeout fired before executor timeout (#1117).
29
- const DEFAULT_WORKER_TIMEOUT_MS = 16 * 60 * 1000;
30
- /**
31
- * Worker Daemon - Manages background workers with Node.js
32
- */
33
- export class WorkerDaemon extends EventEmitter {
34
- config;
35
- workers = new Map();
36
- timers = new Map();
37
- running = false;
38
- startedAt;
39
- projectRoot;
40
- runningWorkers = new Set(); // Track concurrent workers
41
- pendingWorkers = []; // Queue for deferred workers
42
- // Headless execution support
43
- headlessExecutor = null;
44
- headlessAvailable = false;
45
- // Preserve the original constructor config so we can detect explicit overrides
46
- // during state restoration (R1: constructor config takes priority over stale state)
47
- originalConfig;
48
- constructor(projectRoot, config) {
49
- super();
50
- // Resolve and validate projectRoot. Without this an attacker who can pass
51
- // a crafted projectRoot (env var, untrusted CLI flag, MCP tool argument)
52
- // gets arbitrary file write via the derived pidFile, logFile, stateFile,
53
- // and metrics paths.
54
- const resolved = resolve(projectRoot);
55
- this.projectRoot = resolved;
56
- this.originalConfig = config;
57
- const monomindDir = join(resolved, '.monomind');
58
- // Read daemon config from .monomind/config.json (Layer B)
59
- const fileConfig = this.readDaemonConfigFromFile(monomindDir);
60
- // CPU-proportional smart default instead of hardcoded 2.0
61
- const cpuCount = WorkerDaemon.getEffectiveCpuCount();
62
- const smartMaxCpuLoad = Math.max(cpuCount * 0.8, 2.0); // Floor of 2.0 for single-CPU machines
63
- // Platform-aware default: macOS os.freemem() excludes reclaimable file cache,
64
- // so reported "free" is much lower than actually available memory.
65
- // Linux reports available memory (including reclaimable cache) more accurately.
66
- const defaultMinFreeMemory = process.platform === 'darwin' ? 5 : 10;
67
- // Priority: constructor arg > config.json > smart default
68
- // For resourceThresholds, merge field-by-field so partial overrides
69
- // (e.g. only --max-cpu-load) still pick up defaults for other fields.
70
- this.config = {
71
- autoStart: config?.autoStart ?? fileConfig.autoStart ?? false,
72
- logDir: config?.logDir ?? join(monomindDir, 'logs'),
73
- stateFile: config?.stateFile ?? join(monomindDir, 'daemon-state.json'),
74
- maxConcurrent: config?.maxConcurrent ?? fileConfig.maxConcurrent ?? 2,
75
- workerTimeoutMs: config?.workerTimeoutMs ?? fileConfig.workerTimeoutMs ?? DEFAULT_WORKER_TIMEOUT_MS,
76
- resourceThresholds: {
77
- maxCpuLoad: config?.resourceThresholds?.maxCpuLoad ?? fileConfig.maxCpuLoad ?? smartMaxCpuLoad,
78
- minFreeMemoryPercent: config?.resourceThresholds?.minFreeMemoryPercent ?? fileConfig.minFreeMemoryPercent ?? defaultMinFreeMemory,
79
- },
80
- workers: config?.workers ?? DEFAULT_WORKERS,
81
- };
82
- // Setup graceful shutdown handlers
83
- this.setupShutdownHandlers();
84
- // Ensure directories exist
85
- if (!existsSync(monomindDir)) {
86
- mkdirSync(monomindDir, { recursive: true });
87
- }
88
- if (!existsSync(this.config.logDir)) {
89
- mkdirSync(this.config.logDir, { recursive: true });
90
- }
91
- // Initialize worker states
92
- this.initializeWorkerStates();
93
- // Initialize headless executor (async, non-blocking)
94
- this.initHeadlessExecutor().catch((err) => {
95
- this.log('warn', `Headless executor init failed: ${err}`);
96
- });
97
- }
98
- /**
99
- * Initialize headless executor if Claude Code is available
100
- */
101
- async initHeadlessExecutor() {
102
- try {
103
- this.headlessExecutor = new HeadlessWorkerExecutor(this.projectRoot, {
104
- maxConcurrent: this.config.maxConcurrent,
105
- });
106
- this.headlessAvailable = await this.headlessExecutor.isAvailable();
107
- if (this.headlessAvailable) {
108
- this.log('info', 'Claude Code headless mode available - AI workers enabled');
109
- // Forward headless executor events.
110
- // The executor emits 'start', 'complete', 'error' (not 'execution:*').
111
- this.headlessExecutor.on('start', (data) => {
112
- this.emit('headless:start', data);
113
- });
114
- this.headlessExecutor.on('complete', (data) => {
115
- this.emit('headless:complete', data);
116
- });
117
- this.headlessExecutor.on('error', (data) => {
118
- this.emit('headless:error', data);
119
- });
120
- this.headlessExecutor.on('output', (data) => {
121
- this.emit('headless:output', data);
122
- });
123
- }
124
- else {
125
- this.log('info', 'Claude Code not found - AI workers will run in local fallback mode');
126
- }
127
- }
128
- catch (error) {
129
- this.log('warn', `Failed to initialize headless executor: ${error}`);
130
- this.headlessAvailable = false;
131
- }
132
- }
133
- /**
134
- * Check if headless execution is available
135
- */
136
- isHeadlessAvailable() {
137
- return this.headlessAvailable;
138
- }
139
- /**
140
- * Get headless executor instance
141
- */
142
- getHeadlessExecutor() {
143
- return this.headlessExecutor;
144
- }
145
- /**
146
- * Detect effective CPU count for the current environment.
147
- *
148
- * Inside Docker / K8s containers, os.cpus().length reports the HOST cpu
149
- * count, not the container limit (Node.js #28762 — wontfix). We read
150
- * cgroup v2 / v1 quota files first so the maxCpuLoad threshold stays
151
- * meaningful under resource-limited containers.
152
- */
153
- static getEffectiveCpuCount() {
154
- // 1. Try cgroup v2: /sys/fs/cgroup/cpu.max
155
- try {
156
- const cpuMax = readFileSync('/sys/fs/cgroup/cpu.max', 'utf8').trim();
157
- const [quotaStr, periodStr] = cpuMax.split(' ');
158
- if (quotaStr !== 'max') {
159
- const quota = parseInt(quotaStr, 10);
160
- const period = parseInt(periodStr, 10);
161
- if (quota > 0 && period > 0)
162
- return Math.ceil(quota / period);
163
- }
164
- }
165
- catch { /* not in cgroup v2 */ }
166
- // 2. Try cgroup v1: /sys/fs/cgroup/cpu/cpu.cfs_quota_us
167
- try {
168
- const quota = parseInt(readFileSync('/sys/fs/cgroup/cpu/cpu.cfs_quota_us', 'utf8').trim(), 10);
169
- const period = parseInt(readFileSync('/sys/fs/cgroup/cpu/cpu.cfs_period_us', 'utf8').trim(), 10);
170
- if (quota > 0 && period > 0)
171
- return Math.ceil(quota / period);
172
- }
173
- catch { /* not in cgroup v1 */ }
174
- // 3. Fallback to os.cpus().length
175
- return cpus().length || 1;
176
- }
177
- /**
178
- * Read daemon-specific config from .monomind/config.json
179
- * Supports dot-notation keys like 'daemon.resourceThresholds.maxCpuLoad'
180
- */
181
- readDaemonConfigFromFile(monomindDir) {
182
- const configPath = join(monomindDir, 'config.json');
183
- if (!existsSync(configPath)) {
184
- // Warn if config.yaml exists but config.json does not (#1395 Bug 4)
185
- const yamlPath = join(monomindDir, 'config.yaml');
186
- const ymlPath = join(monomindDir, 'config.yml');
187
- if (existsSync(yamlPath) || existsSync(ymlPath)) {
188
- this.log('warn', `Found ${existsSync(yamlPath) ? 'config.yaml' : 'config.yml'} but daemon reads only config.json — YAML config is being ignored. Convert to JSON or create config.json.`);
189
- }
190
- return {};
191
- }
192
- try {
193
- // Guard against OOM from an oversized config file (tampered or corrupted).
194
- const configSize = statSync(configPath).size;
195
- if (configSize > 1_048_576 /* 1 MB */) {
196
- this.log('warn', `config.json is unusually large (${configSize} bytes) — ignoring daemon config`);
197
- return {};
198
- }
199
- const raw = JSON.parse(readFileSync(configPath, 'utf-8'));
200
- // Support both flat keys at root and nested under scopes.project
201
- const cfg = raw?.scopes?.project ?? raw;
202
- const rawCpuLoad = cfg['daemon.resourceThresholds.maxCpuLoad'] ?? raw['daemon.resourceThresholds.maxCpuLoad'];
203
- const rawMinMem = cfg['daemon.resourceThresholds.minFreeMemoryPercent'] ?? raw['daemon.resourceThresholds.minFreeMemoryPercent'];
204
- const rawMaxConcurrent = cfg['daemon.maxConcurrent'] ?? raw['daemon.maxConcurrent'];
205
- const rawTimeout = cfg['daemon.workerTimeoutMs'] ?? raw['daemon.workerTimeoutMs'];
206
- return {
207
- autoStart: typeof raw['daemon.autoStart'] === 'boolean' ? raw['daemon.autoStart'] : undefined,
208
- maxConcurrent: (typeof rawMaxConcurrent === 'number' && rawMaxConcurrent > 0) ? rawMaxConcurrent : undefined,
209
- workerTimeoutMs: (typeof rawTimeout === 'number' && rawTimeout > 0) ? rawTimeout : undefined,
210
- maxCpuLoad: (typeof rawCpuLoad === 'number' && rawCpuLoad > 0 && rawCpuLoad < 1000) ? rawCpuLoad : undefined,
211
- minFreeMemoryPercent: (typeof rawMinMem === 'number' && rawMinMem >= 0 && rawMinMem <= 100) ? rawMinMem : undefined,
212
- };
213
- }
214
- catch {
215
- return {};
216
- }
217
- }
218
- /**
219
- * Setup graceful shutdown handlers
220
- */
221
- setupShutdownHandlers() {
222
- const shutdown = async () => {
223
- this.log('info', 'Received shutdown signal, stopping daemon...');
224
- await this.stop();
225
- process.exit(0);
226
- };
227
- process.once('SIGTERM', shutdown);
228
- process.once('SIGINT', shutdown);
229
- process.once('SIGHUP', shutdown);
230
- }
231
- /**
232
- * Check if system resources allow worker execution
233
- */
234
- async canRunWorker() {
235
- const os = await import('os');
236
- const cpuLoad = os.loadavg()[0];
237
- const totalMem = os.totalmem();
238
- const freeMem = os.freemem();
239
- const freePercent = (freeMem / totalMem) * 100;
240
- if (cpuLoad > this.config.resourceThresholds.maxCpuLoad) {
241
- return { allowed: false, reason: `CPU load too high: ${cpuLoad.toFixed(2)}` };
242
- }
243
- if (freePercent < this.config.resourceThresholds.minFreeMemoryPercent) {
244
- return { allowed: false, reason: `Memory too low: ${freePercent.toFixed(1)}% free` };
245
- }
246
- return { allowed: true };
247
- }
248
- /**
249
- * Process pending workers queue
250
- *
251
- * When executeWorkerWithConcurrencyControl defers a worker (returns null),
252
- * we break immediately to avoid a busy-wait loop — the deferred worker is
253
- * already back on the pendingWorkers queue by that point. If no workers are
254
- * currently running when we break, we schedule a backoff retry so the queue
255
- * does not get permanently stuck.
256
- */
257
- async processPendingWorkers() {
258
- while (this.pendingWorkers.length > 0 && this.runningWorkers.size < this.config.maxConcurrent) {
259
- const workerType = this.pendingWorkers.shift();
260
- const workerConfig = this.config.workers.find(w => w.type === workerType);
261
- if (workerConfig) {
262
- const result = await this.executeWorkerWithConcurrencyControl(workerConfig);
263
- if (result === null) {
264
- // Worker was deferred (resource pressure or concurrency limit).
265
- // Break to avoid tight-looping — the next executeWorker() completion
266
- // will call processPendingWorkers() again via the finally block.
267
- if (this.runningWorkers.size === 0) {
268
- // No workers running means nobody will trigger the finally-block
269
- // callback, so schedule a backoff retry to avoid a stuck queue.
270
- setTimeout(() => this.processPendingWorkers(), 30_000).unref();
271
- }
272
- break;
273
- }
274
- }
275
- }
276
- }
277
- initializeWorkerStates() {
278
- // Try to restore state from file
279
- if (existsSync(this.config.stateFile)) {
280
- try {
281
- // Guard against OOM from an oversized state file (tampered or corrupted).
282
- const stateSize = statSync(this.config.stateFile).size;
283
- if (stateSize > 5_242_880 /* 5 MB */) {
284
- this.log('warn', `daemon-state.json is unusually large (${stateSize} bytes) — starting with fresh state`);
285
- return;
286
- }
287
- const saved = JSON.parse(readFileSync(this.config.stateFile, 'utf-8'));
288
- // CRITICAL: Restore worker config (including enabled flag) from saved state
289
- // This fixes #950: daemon enable command not persisting worker state
290
- if (saved.config?.workers && Array.isArray(saved.config.workers)) {
291
- for (const savedWorker of saved.config.workers) {
292
- const workerConfig = this.config.workers.find(w => w.type === savedWorker.type);
293
- if (workerConfig && typeof savedWorker.enabled === 'boolean') {
294
- workerConfig.enabled = savedWorker.enabled;
295
- }
296
- }
297
- }
298
- // Restore resourceThresholds, maxConcurrent, workerTimeoutMs from saved state
299
- // Only restore if valid numeric values within sane ranges
300
- if (saved.config?.resourceThresholds && !this.originalConfig?.resourceThresholds) {
301
- const rt = saved.config.resourceThresholds;
302
- if (typeof rt.maxCpuLoad === 'number' && rt.maxCpuLoad > 0 && rt.maxCpuLoad < 1000) {
303
- this.config.resourceThresholds.maxCpuLoad = rt.maxCpuLoad;
304
- }
305
- if (typeof rt.minFreeMemoryPercent === 'number' && rt.minFreeMemoryPercent >= 0 && rt.minFreeMemoryPercent <= 100) {
306
- this.config.resourceThresholds.minFreeMemoryPercent = rt.minFreeMemoryPercent;
307
- }
308
- }
309
- if (typeof saved.config?.maxConcurrent === 'number' && saved.config.maxConcurrent > 0) {
310
- this.config.maxConcurrent = saved.config.maxConcurrent;
311
- }
312
- if (typeof saved.config?.workerTimeoutMs === 'number' && saved.config.workerTimeoutMs > 0) {
313
- this.config.workerTimeoutMs = saved.config.workerTimeoutMs;
314
- }
315
- // Restore worker runtime states (runCount, successCount, etc.)
316
- // Validate keys against an allowlist to defeat prototype-pollution
317
- // attempts and reject unknown worker types injected into the file.
318
- if (saved.workers && typeof saved.workers === 'object') {
319
- const VALID_TYPES = new Set(this.config.workers.map(w => w.type));
320
- const FORBIDDEN = new Set(['__proto__', 'constructor', 'prototype']);
321
- const finiteNonNeg = (v) => {
322
- if (typeof v !== 'number' || !Number.isFinite(v) || v < 0)
323
- return 0;
324
- return Math.floor(v);
325
- };
326
- for (const [type, state] of Object.entries(saved.workers)) {
327
- if (FORBIDDEN.has(type) || !VALID_TYPES.has(type))
328
- continue;
329
- const savedState = state;
330
- const lastRunValue = savedState.lastRun;
331
- const lastRunDate = typeof lastRunValue === 'string' ? new Date(lastRunValue) : undefined;
332
- this.workers.set(type, {
333
- runCount: finiteNonNeg(savedState.runCount),
334
- successCount: finiteNonNeg(savedState.successCount),
335
- failureCount: finiteNonNeg(savedState.failureCount),
336
- averageDurationMs: finiteNonNeg(savedState.averageDurationMs),
337
- lastRun: lastRunDate && !isNaN(lastRunDate.getTime()) ? lastRunDate : undefined,
338
- nextRun: undefined,
339
- isRunning: false,
340
- });
341
- }
342
- }
343
- }
344
- catch {
345
- // Ignore parse errors, start fresh
346
- }
347
- }
348
- // Initialize any missing workers
349
- for (const workerConfig of this.config.workers) {
350
- if (!this.workers.has(workerConfig.type)) {
351
- this.workers.set(workerConfig.type, {
352
- runCount: 0,
353
- successCount: 0,
354
- failureCount: 0,
355
- averageDurationMs: 0,
356
- isRunning: false,
357
- });
358
- }
359
- }
360
- }
361
- /**
362
- * Get the PID file path for singleton enforcement (#1395 Bug 3).
363
- */
364
- get pidFile() {
365
- return join(this.projectRoot, '.monomind', 'daemon.pid');
366
- }
367
- /**
368
- * Check if another daemon instance is already running.
369
- * Returns the existing PID if alive, or null if no daemon is running.
370
- */
371
- checkExistingDaemon() {
372
- if (!existsSync(this.pidFile))
373
- return null;
374
- try {
375
- const pid = parseInt(readFileSync(this.pidFile, 'utf-8').trim(), 10);
376
- if (isNaN(pid))
377
- return null;
378
- // Check if process is alive (signal 0 = existence check)
379
- process.kill(pid, 0);
380
- return pid; // Process is alive
381
- }
382
- catch {
383
- // Process is dead — clean up stale PID file
384
- try {
385
- unlinkSync(this.pidFile);
386
- }
387
- catch { /* ignore */ }
388
- return null;
389
- }
390
- }
391
- /**
392
- * Write PID file with O_EXCL for atomic singleton enforcement (closes the
393
- * TOCTOU window between checkExistingDaemon and writePidFile that previously
394
- * allowed two concurrent `daemon start` calls to both succeed).
395
- * Returns true on success, false if another daemon raced us.
396
- */
397
- writePidFile() {
398
- const dir = join(this.projectRoot, '.monomind');
399
- if (!existsSync(dir))
400
- mkdirSync(dir, { recursive: true });
401
- try {
402
- // wx flag = O_CREAT | O_EXCL — atomic create-or-fail
403
- writeFileSync(this.pidFile, String(process.pid), { flag: 'wx' });
404
- return true;
405
- }
406
- catch (e) {
407
- const code = e.code;
408
- if (code === 'EEXIST') {
409
- // Recheck liveness — file may belong to a dead daemon we missed
410
- const racePid = this.checkExistingDaemon();
411
- if (racePid === null) {
412
- // Stale file was just removed by checkExistingDaemon, retry once
413
- try {
414
- writeFileSync(this.pidFile, String(process.pid), { flag: 'wx' });
415
- return true;
416
- }
417
- catch {
418
- return false;
419
- }
420
- }
421
- return false;
422
- }
423
- throw e;
424
- }
425
- }
426
- /**
427
- * Remove PID file on shutdown.
428
- */
429
- removePidFile() {
430
- try {
431
- unlinkSync(this.pidFile);
432
- }
433
- catch { /* ignore */ }
434
- }
435
- /**
436
- * Start the daemon and all enabled workers
437
- */
438
- async start() {
439
- if (this.running) {
440
- this.emit('warning', 'Daemon already running');
441
- return;
442
- }
443
- // PID singleton enforcement (#1395 Bug 3): prevent daemon accumulation
444
- const existingPid = this.checkExistingDaemon();
445
- if (existingPid !== null) {
446
- this.log('info', `Daemon already running (PID: ${existingPid}), skipping start`);
447
- this.emit('warning', `Daemon already running (PID: ${existingPid})`);
448
- return;
449
- }
450
- // Atomic PID file write — fails if another daemon raced us past
451
- // checkExistingDaemon. Without this two `daemon start` calls could both
452
- // pass the existence check then both clobber the PID file.
453
- if (!this.writePidFile()) {
454
- this.log('info', 'Another daemon won the PID race — aborting start');
455
- this.emit('warning', 'Another daemon instance is starting/running');
456
- return;
457
- }
458
- this.running = true;
459
- this.startedAt = new Date();
460
- this.emit('started', { pid: process.pid, startedAt: this.startedAt });
461
- // Schedule all enabled workers
462
- for (const workerConfig of this.config.workers) {
463
- if (workerConfig.enabled) {
464
- this.scheduleWorker(workerConfig);
465
- }
466
- }
467
- // Save state
468
- this.saveState();
469
- this.log('info', `Daemon started (PID: ${process.pid}, CPUs: ${cpus().length}, workers: ${this.config.workers.filter(w => w.enabled).length}, maxCpuLoad: ${this.config.resourceThresholds.maxCpuLoad}, minFreeMemoryPercent: ${this.config.resourceThresholds.minFreeMemoryPercent}%)`);
470
- }
471
- /**
472
- * Stop the daemon and all workers
473
- */
474
- async stop() {
475
- if (!this.running) {
476
- this.emit('warning', 'Daemon not running');
477
- return;
478
- }
479
- // Clear all timers (convert to array to avoid iterator issues)
480
- const timerEntries = Array.from(this.timers.entries());
481
- for (const [type, timer] of timerEntries) {
482
- clearTimeout(timer);
483
- this.log('info', `Stopped worker: ${type}`);
484
- }
485
- this.timers.clear();
486
- this.running = false;
487
- this.removePidFile();
488
- this.saveState();
489
- this.emit('stopped', { stoppedAt: new Date() });
490
- this.log('info', 'Daemon stopped');
491
- }
492
- /**
493
- * Get daemon status
494
- */
495
- getStatus() {
496
- return {
497
- running: this.running,
498
- pid: process.pid,
499
- startedAt: this.startedAt,
500
- workers: new Map(this.workers),
501
- config: this.config,
502
- };
503
- }
504
- /**
505
- * Schedule a worker to run at intervals with staggered start
506
- */
507
- scheduleWorker(workerConfig) {
508
- const state = this.workers.get(workerConfig.type);
509
- const internalConfig = workerConfig;
510
- const staggerOffset = internalConfig.offsetMs || 0;
511
- // Calculate initial delay with stagger offset
512
- let initialDelay = staggerOffset;
513
- if (state.lastRun) {
514
- const timeSinceLastRun = Date.now() - state.lastRun.getTime();
515
- initialDelay = Math.max(staggerOffset, workerConfig.intervalMs - timeSinceLastRun);
516
- }
517
- state.nextRun = new Date(Date.now() + initialDelay);
518
- const runAndReschedule = async () => {
519
- if (!this.running)
520
- return;
521
- // Use concurrency-controlled execution (P0 fix)
522
- await this.executeWorkerWithConcurrencyControl(workerConfig);
523
- // Reschedule
524
- if (this.running) {
525
- const timer = setTimeout(runAndReschedule, workerConfig.intervalMs);
526
- this.timers.set(workerConfig.type, timer);
527
- state.nextRun = new Date(Date.now() + workerConfig.intervalMs);
528
- }
529
- };
530
- // Schedule first run with stagger offset
531
- const timer = setTimeout(runAndReschedule, initialDelay);
532
- this.timers.set(workerConfig.type, timer);
533
- this.log('info', `Scheduled ${workerConfig.type} (interval: ${workerConfig.intervalMs / 1000}s, first run in ${initialDelay / 1000}s)`);
534
- }
535
- /**
536
- * Execute a worker with concurrency control (P0 fix)
537
- */
538
- async executeWorkerWithConcurrencyControl(workerConfig) {
539
- // Dedup: under sustained resource pressure each scheduler tick re-pushes
540
- // the same WorkerType. Without dedup, high-priority workers (audit) crowd
541
- // out low-priority ones (consolidate) — starvation. Skip the push if the
542
- // type is already pending.
543
- const pushPending = (type) => {
544
- if (!this.pendingWorkers.includes(type))
545
- this.pendingWorkers.push(type);
546
- };
547
- // Check concurrency limit
548
- if (this.runningWorkers.size >= this.config.maxConcurrent) {
549
- this.log('info', `Worker ${workerConfig.type} deferred: max concurrent (${this.config.maxConcurrent}) reached`);
550
- pushPending(workerConfig.type);
551
- this.emit('worker:deferred', { type: workerConfig.type, reason: 'max_concurrent' });
552
- return null;
553
- }
554
- // Check resource availability
555
- const resourceCheck = await this.canRunWorker();
556
- if (!resourceCheck.allowed) {
557
- this.log('info', `Worker ${workerConfig.type} deferred: ${resourceCheck.reason}`);
558
- pushPending(workerConfig.type);
559
- this.emit('worker:deferred', { type: workerConfig.type, reason: resourceCheck.reason });
560
- return null;
561
- }
562
- return this.executeWorker(workerConfig);
563
- }
564
- /**
565
- * Execute a worker with timeout protection
566
- */
567
- async executeWorker(workerConfig) {
568
- const state = this.workers.get(workerConfig.type);
569
- const workerId = `${workerConfig.type}_${Date.now()}`;
570
- const startTime = Date.now();
571
- // Track the headless executionId assigned by HeadlessWorkerExecutor so we
572
- // can cancel it precisely on timeout. The executor generates its own ID
573
- // (format: `${type}_${ts}_${random}`) which never matches workerId, so we
574
- // capture it from the 'start' event instead.
575
- let headlessExecutionId = null;
576
- const onHeadlessStart = (data) => {
577
- headlessExecutionId = data.executionId ?? null;
578
- };
579
- if (this.headlessExecutor) {
580
- this.headlessExecutor.on('start', onHeadlessStart);
581
- }
582
- // Track running worker
583
- this.runningWorkers.add(workerConfig.type);
584
- state.isRunning = true;
585
- this.emit('worker:start', { workerId, type: workerConfig.type });
586
- this.log('info', `Starting worker: ${workerConfig.type} (${this.runningWorkers.size}/${this.config.maxConcurrent} concurrent)`);
587
- try {
588
- // Execute worker logic with timeout (P1 fix)
589
- // Pass cleanup callback to kill only this worker's child process on timeout.
590
- // cancelAll() was too broad — it would kill concurrent healthy workers.
591
- const output = await this.runWithTimeout(() => this.runWorkerLogic(workerConfig), this.config.workerTimeoutMs, `Worker ${workerConfig.type} timed out after ${this.config.workerTimeoutMs / 1000}s`, () => {
592
- if (this.headlessExecutor) {
593
- // Use the exact executionId captured from the 'start' event.
594
- // Fall back to cancelByType only if we didn't capture an ID yet
595
- // (e.g. timeout fired before the executor emitted 'start').
596
- if (headlessExecutionId && this.headlessExecutor.cancel(headlessExecutionId)) {
597
- return;
598
- }
599
- this.headlessExecutor.cancelByType(workerConfig.type);
600
- }
601
- });
602
- const durationMs = Date.now() - startTime;
603
- // Update state
604
- state.runCount++;
605
- state.successCount++;
606
- state.lastRun = new Date();
607
- state.averageDurationMs = (state.averageDurationMs * (state.runCount - 1) + durationMs) / state.runCount;
608
- state.isRunning = false;
609
- const result = {
610
- workerId,
611
- type: workerConfig.type,
612
- success: true,
613
- durationMs,
614
- output,
615
- timestamp: new Date(),
616
- };
617
- this.emit('worker:complete', result);
618
- this.log('info', `Worker ${workerConfig.type} completed in ${durationMs}ms`);
619
- this.saveState();
620
- return result;
621
- }
622
- catch (error) {
623
- const durationMs = Date.now() - startTime;
624
- state.runCount++;
625
- state.failureCount++;
626
- state.lastRun = new Date();
627
- state.isRunning = false;
628
- const result = {
629
- workerId,
630
- type: workerConfig.type,
631
- success: false,
632
- durationMs,
633
- error: error instanceof Error ? error.message : String(error),
634
- timestamp: new Date(),
635
- };
636
- this.emit('worker:error', result);
637
- this.log('error', `Worker ${workerConfig.type} failed: ${result.error}`);
638
- this.saveState();
639
- return result;
640
- }
641
- finally {
642
- // Remove from running set and process queue
643
- this.runningWorkers.delete(workerConfig.type);
644
- // Unsubscribe the executionId capture listener regardless of outcome
645
- if (this.headlessExecutor) {
646
- this.headlessExecutor.off('start', onHeadlessStart);
647
- }
648
- this.processPendingWorkers();
649
- }
650
- }
651
- /**
652
- * Run a function with timeout (P1 fix)
653
- * @param fn - The async function to execute
654
- * @param timeoutMs - Timeout in milliseconds
655
- * @param timeoutMessage - Error message on timeout
656
- * @param onTimeout - Optional cleanup callback invoked when timeout fires (#1117: kills orphan processes)
657
- */
658
- async runWithTimeout(fn, timeoutMs, timeoutMessage, onTimeout) {
659
- return new Promise((resolve, reject) => {
660
- let settled = false;
661
- const timer = setTimeout(() => {
662
- if (settled)
663
- return;
664
- settled = true;
665
- // Kill orphan child processes before rejecting (#1117)
666
- if (onTimeout) {
667
- try {
668
- onTimeout();
669
- }
670
- catch {
671
- // Ignore cleanup errors
672
- }
673
- }
674
- reject(new Error(timeoutMessage));
675
- }, timeoutMs);
676
- fn()
677
- .then((result) => {
678
- if (settled)
679
- return;
680
- settled = true;
681
- clearTimeout(timer);
682
- resolve(result);
683
- })
684
- .catch((error) => {
685
- if (settled)
686
- return;
687
- settled = true;
688
- clearTimeout(timer);
689
- reject(error);
690
- });
691
- });
692
- }
693
- /**
694
- * Run the actual worker logic
695
- */
696
- async runWorkerLogic(workerConfig) {
697
- // Check if this is a headless worker type and headless execution is available
698
- if (isHeadlessWorker(workerConfig.type) && this.headlessAvailable && this.headlessExecutor) {
699
- try {
700
- this.log('info', `Running ${workerConfig.type} in headless mode (Claude Code AI)`);
701
- const result = await this.headlessExecutor.execute(workerConfig.type);
702
- return {
703
- mode: 'headless',
704
- ...result,
705
- };
706
- }
707
- catch (error) {
708
- this.log('warn', `Headless execution failed for ${workerConfig.type}, falling back to local mode`);
709
- this.emit('headless:fallback', {
710
- type: workerConfig.type,
711
- error: error instanceof Error ? error.message : String(error),
712
- });
713
- // Fall through to local execution
714
- }
715
- }
716
- // Local execution (fallback or for non-headless workers)
717
- switch (workerConfig.type) {
718
- case 'map':
719
- return this.runMapWorker();
720
- case 'audit':
721
- return this.runAuditWorkerLocal();
722
- case 'optimize':
723
- return this.runOptimizeWorkerLocal();
724
- case 'consolidate':
725
- return this.runConsolidateWorker();
726
- case 'testgaps':
727
- return this.runTestGapsWorkerLocal();
728
- case 'predict':
729
- return this.runPredictWorkerLocal();
730
- case 'document':
731
- return this.runDocumentWorkerLocal();
732
- case 'ultralearn':
733
- return this.runUltralearnWorkerLocal();
734
- case 'refactor':
735
- return this.runRefactorWorkerLocal();
736
- case 'deepdive':
737
- return this.runDeepdiveWorkerLocal();
738
- case 'benchmark':
739
- return this.runBenchmarkWorkerLocal();
740
- case 'preload':
741
- return this.runPreloadWorkerLocal();
742
- default:
743
- return { status: 'unknown worker type', mode: 'local' };
744
- }
745
- }
746
- // Worker implementations
747
- async runMapWorker() {
748
- // Scan project structure and update metrics
749
- const metricsFile = join(this.projectRoot, '.monomind', 'metrics', 'codebase-map.json');
750
- const metricsDir = join(this.projectRoot, '.monomind', 'metrics');
751
- if (!existsSync(metricsDir)) {
752
- mkdirSync(metricsDir, { recursive: true });
753
- }
754
- const map = {
755
- timestamp: new Date().toISOString(),
756
- structure: {
757
- hasPackageJson: existsSync(join(this.projectRoot, 'package.json')),
758
- hasTsConfig: existsSync(join(this.projectRoot, 'tsconfig.json')),
759
- hasClaudeConfig: existsSync(join(this.projectRoot, '.claude')),
760
- hasMonomind: existsSync(join(this.projectRoot, '.monomind')),
761
- },
762
- scannedAt: Date.now(),
763
- };
764
- // Enrich with monograph graph stats for LLM context injection.
765
- // Lazy-import to avoid hard dependency; silently skip on any error.
766
- try {
767
- const { openDb, closeDb, countNodes, countEdges } = await import('@monoes/monograph');
768
- const dbPath = join(this.projectRoot, '.monomind', 'monograph.db');
769
- if (existsSync(dbPath)) {
770
- const db = openDb(dbPath);
771
- try {
772
- // Node/edge counts
773
- map['graph'] = {
774
- nodes: countNodes(db),
775
- edges: countEdges(db),
776
- };
777
- // Top 3 god nodes (high degree internal files) — same SQL as monograph_god_nodes tool
778
- const excluded = ['File', 'Folder', 'Community', 'Concept'];
779
- const rows = db.prepare(`
780
- SELECT n.name, n.file_path, n.start_line,
781
- COUNT(DISTINCT e1.id) + COUNT(DISTINCT e2.id) AS degree
782
- FROM nodes n
783
- LEFT JOIN edges e1 ON e1.source_id = n.id
784
- LEFT JOIN edges e2 ON e2.target_id = n.id
785
- WHERE n.label NOT IN (${excluded.map(() => '?').join(',')})
786
- GROUP BY n.id HAVING degree > 0
787
- ORDER BY degree DESC LIMIT 3
788
- `).all(...excluded);
789
- if (rows.length > 0) {
790
- map['topFiles'] = rows.map(r => ({
791
- ref: r.file_path
792
- ? (r.start_line != null ? `${r.file_path}:${r.start_line}` : r.file_path)
793
- : r.name,
794
- degree: r.degree,
795
- }));
796
- }
797
- // Index staleness via git — same approach as monograph_health tool
798
- try {
799
- const { execSync } = await import('child_process');
800
- const lastHash = db.prepare("SELECT value FROM meta WHERE key = 'last_commit_hash' LIMIT 1").get()?.value;
801
- if (lastHash) {
802
- const countOut = execSync(`git -C ${JSON.stringify(this.projectRoot)} rev-list --count ${lastHash}..HEAD`, { timeout: 5000 }).toString().trim();
803
- const commitsBehind = parseInt(countOut, 10);
804
- if (!isNaN(commitsBehind)) {
805
- map['graphStaleness'] = { commitsBehind };
806
- }
807
- }
808
- }
809
- catch { /* git unavailable — skip staleness */ }
810
- }
811
- finally {
812
- closeDb(db);
813
- }
814
- }
815
- }
816
- catch { /* monograph unavailable — skip graph enrichment */ }
817
- const metricsFileTmp1 = metricsFile + '.tmp';
818
- writeFileSync(metricsFileTmp1, JSON.stringify(map, null, 2));
819
- renameSync(metricsFileTmp1, metricsFile);
820
- return map;
821
- }
822
- /**
823
- * Local audit worker (fallback when headless unavailable)
824
- */
825
- async runAuditWorkerLocal() {
826
- // Basic security checks
827
- const auditFile = join(this.projectRoot, '.monomind', 'metrics', 'security-audit.json');
828
- const metricsDir = join(this.projectRoot, '.monomind', 'metrics');
829
- if (!existsSync(metricsDir)) {
830
- mkdirSync(metricsDir, { recursive: true });
831
- }
832
- const audit = {
833
- timestamp: new Date().toISOString(),
834
- mode: 'local',
835
- checks: {
836
- envFilesProtected: !existsSync(join(this.projectRoot, '.env.local')),
837
- gitIgnoreExists: existsSync(join(this.projectRoot, '.gitignore')),
838
- noHardcodedSecrets: null, // Not checked in local mode — requires AI-powered scan
839
- },
840
- riskLevel: 'low',
841
- recommendations: [],
842
- note: 'Install Claude Code CLI for AI-powered security analysis',
843
- };
844
- // Enrich with monograph high-centrality files and surprising cross-community edges.
845
- // God-node files are high-value targets for security review: they are imported by
846
- // many consumers, so a vulnerability there has the largest blast radius.
847
- // Cross-community edges reveal unexpected coupling that may indicate hidden attack surfaces.
848
- try {
849
- const { openDb, closeDb } = await import('@monoes/monograph');
850
- const dbPath = join(this.projectRoot, '.monomind', 'monograph.db');
851
- if (existsSync(dbPath)) {
852
- const db = openDb(dbPath);
853
- try {
854
- const godFileRows = db.prepare(`
855
- SELECT n.file_path,
856
- COUNT(DISTINCT e1.id) + COUNT(DISTINCT e2.id) AS degree
857
- FROM nodes n
858
- LEFT JOIN edges e1 ON e1.source_id = n.id
859
- LEFT JOIN edges e2 ON e2.target_id = n.id
860
- WHERE n.label NOT IN ('File','Folder','Community','Concept')
861
- AND n.file_path IS NOT NULL
862
- AND n.file_path NOT LIKE '%node_modules%'
863
- AND n.file_path NOT LIKE '%/dist/%'
864
- AND n.file_path NOT LIKE '%.test.%'
865
- AND n.file_path NOT LIKE '%.spec.%'
866
- GROUP BY n.file_path
867
- ORDER BY degree DESC
868
- LIMIT 5
869
- `).all();
870
- const surpriseRows = db.prepare(`
871
- SELECT n1.name as src_name, n2.name as tgt_name, e.relation, e.confidence_score,
872
- n1.file_path as src_file, n2.file_path as tgt_file
873
- FROM edges e
874
- JOIN nodes n1 ON n1.id = e.source_id
875
- JOIN nodes n2 ON n2.id = e.target_id
876
- WHERE e.confidence != 'EXTRACTED'
877
- AND n1.community_id IS NOT NULL
878
- AND n2.community_id IS NOT NULL
879
- AND n1.community_id != n2.community_id
880
- ORDER BY e.confidence_score ASC
881
- LIMIT 5
882
- `).all();
883
- if (godFileRows.length > 0) {
884
- audit['priorityScanTargets'] = godFileRows.map(r => ({
885
- file: r.file_path.replace(this.projectRoot + '/', '').replace(this.projectRoot + '\\', ''),
886
- degree: r.degree,
887
- reason: 'high-centrality: vulnerability here affects the most consumers',
888
- }));
889
- }
890
- if (surpriseRows.length > 0) {
891
- audit['unexpectedCoupling'] = surpriseRows.map(r => ({
892
- edge: `${r.src_name} --${r.relation}--> ${r.tgt_name}`,
893
- srcFile: r.src_file ?? '(unknown)',
894
- tgtFile: r.tgt_file ?? '(unknown)',
895
- confidenceScore: r.confidence_score,
896
- reason: 'cross-community edge: may indicate hidden dependency or attack surface',
897
- }));
898
- }
899
- }
900
- finally {
901
- closeDb(db);
902
- }
903
- }
904
- }
905
- catch { /* monograph unavailable — skip graph enrichment */ }
906
- const auditFileTmp = auditFile + '.tmp';
907
- writeFileSync(auditFileTmp, JSON.stringify(audit, null, 2));
908
- renameSync(auditFileTmp, auditFile);
909
- return audit;
910
- }
911
- /**
912
- * Local optimize worker (fallback when headless unavailable)
913
- */
914
- async runOptimizeWorkerLocal() {
915
- // Update performance metrics
916
- const optimizeFile = join(this.projectRoot, '.monomind', 'metrics', 'performance.json');
917
- const metricsDir = join(this.projectRoot, '.monomind', 'metrics');
918
- if (!existsSync(metricsDir)) {
919
- mkdirSync(metricsDir, { recursive: true });
920
- }
921
- const perf = {
922
- timestamp: new Date().toISOString(),
923
- mode: 'local',
924
- memoryUsage: process.memoryUsage(),
925
- uptime: process.uptime(),
926
- optimizations: {
927
- cacheHitRate: null, // Not measured in local mode — requires AI-powered analysis
928
- avgResponseTime: null, // Not measured in local mode — requires AI-powered analysis
929
- },
930
- note: 'Install Claude Code CLI for AI-powered optimization suggestions',
931
- };
932
- const optimizeFileTmp = optimizeFile + '.tmp';
933
- writeFileSync(optimizeFileTmp, JSON.stringify(perf, null, 2));
934
- renameSync(optimizeFileTmp, optimizeFile);
935
- return perf;
936
- }
937
- async runConsolidateWorker() {
938
- // RAPTOR-style memory consolidation: cluster episodic entries by namespace,
939
- // generate a summary entry as 'contextual' type referencing source cluster.
940
- // Source: https://arxiv.org/abs/2401.18059 (RAPTOR — ICLR 2024)
941
- const consolidateFile = join(this.projectRoot, '.monomind', 'metrics', 'consolidation.json');
942
- const metricsDir = join(this.projectRoot, '.monomind', 'metrics');
943
- if (!existsSync(metricsDir)) {
944
- mkdirSync(metricsDir, { recursive: true });
945
- }
946
- let patternsConsolidated = 0;
947
- let clustersCreated = 0;
948
- try {
949
- // Lazy-import memory bridge to avoid hard dependency in worker
950
- const { bridgeSearchEntries, bridgeStoreEntry } = await import('../memory/memory-bridge.js');
951
- // Retrieve recent episodic entries (short-term tier) for RAPTOR clustering
952
- const episodic = await bridgeSearchEntries({
953
- query: 'task outcome agent pattern',
954
- namespace: 'patterns',
955
- limit: 50,
956
- threshold: 0.0,
957
- });
958
- if (episodic?.results && episodic.results.length >= 3) {
959
- // Group into clusters of ~5 by simple sequential chunking
960
- const CLUSTER_SIZE = 5;
961
- for (let i = 0; i < episodic.results.length; i += CLUSTER_SIZE) {
962
- const cluster = episodic.results.slice(i, i + CLUSTER_SIZE);
963
- if (cluster.length < 2)
964
- continue;
965
- // Build cluster summary (lightweight abstraction without LLM)
966
- const keys = cluster.map(r => r.key).join(', ');
967
- const summary = `RAPTOR cluster [${Math.floor(i / CLUSTER_SIZE)}]: ` +
968
- `${cluster.length} patterns consolidated. Topics: ${keys.slice(0, 120)}`;
969
- await bridgeStoreEntry({
970
- key: `raptor_cluster:${Date.now()}_${i}`,
971
- value: summary,
972
- namespace: 'contextual',
973
- tags: ['raptor', 'cluster_summary'],
974
- });
975
- patternsConsolidated += cluster.length;
976
- clustersCreated++;
977
- }
978
- }
979
- }
980
- catch { /* non-critical — bridge may be unavailable */ }
981
- const result = {
982
- timestamp: new Date().toISOString(),
983
- patternsConsolidated,
984
- clustersCreated,
985
- memoryCleaned: 0,
986
- duplicatesRemoved: 0,
987
- mode: 'raptor',
988
- };
989
- const consolidateFileTmp = consolidateFile + '.tmp';
990
- writeFileSync(consolidateFileTmp, JSON.stringify(result, null, 2));
991
- renameSync(consolidateFileTmp, consolidateFile);
992
- return result;
993
- }
994
- /**
995
- * Local testgaps worker (fallback when headless unavailable)
996
- */
997
- async runTestGapsWorkerLocal() {
998
- // Check for test coverage gaps
999
- const testGapsFile = join(this.projectRoot, '.monomind', 'metrics', 'test-gaps.json');
1000
- const metricsDir = join(this.projectRoot, '.monomind', 'metrics');
1001
- if (!existsSync(metricsDir)) {
1002
- mkdirSync(metricsDir, { recursive: true });
1003
- }
1004
- const result = {
1005
- timestamp: new Date().toISOString(),
1006
- mode: 'local',
1007
- hasTestDir: existsSync(join(this.projectRoot, 'tests')) || existsSync(join(this.projectRoot, '__tests__')),
1008
- estimatedCoverage: 'unknown',
1009
- gaps: [],
1010
- note: 'Install Claude Code CLI for AI-powered test gap analysis',
1011
- };
1012
- const testGapsFileTmp = testGapsFile + '.tmp';
1013
- writeFileSync(testGapsFileTmp, JSON.stringify(result, null, 2));
1014
- renameSync(testGapsFileTmp, testGapsFile);
1015
- return result;
1016
- }
1017
- /**
1018
- * Local predict worker (fallback when headless unavailable)
1019
- */
1020
- async runPredictWorkerLocal() {
1021
- return {
1022
- timestamp: new Date().toISOString(),
1023
- mode: 'local',
1024
- predictions: [],
1025
- preloaded: [],
1026
- note: 'Install Claude Code CLI for AI-powered predictions',
1027
- };
1028
- }
1029
- /**
1030
- * Local document worker (fallback when headless unavailable)
1031
- */
1032
- async runDocumentWorkerLocal() {
1033
- return {
1034
- timestamp: new Date().toISOString(),
1035
- mode: 'local',
1036
- filesDocumented: 0,
1037
- suggestedDocs: [],
1038
- note: 'Install Claude Code CLI for AI-powered documentation generation',
1039
- };
1040
- }
1041
- /**
1042
- * Local ultralearn worker (fallback when headless unavailable)
1043
- */
1044
- async runUltralearnWorkerLocal() {
1045
- const result = {
1046
- timestamp: new Date().toISOString(),
1047
- mode: 'local',
1048
- patternsLearned: 0,
1049
- insightsGained: [],
1050
- };
1051
- // Enrich with monograph community clusters and bridge-node patterns for LLM context injection.
1052
- // Bridge nodes (symbols that cross community boundaries) are architecturally significant —
1053
- // they represent coupling points an LLM should be aware of when reasoning about change impact.
1054
- try {
1055
- const { openDb, closeDb, countNodes, countEdges } = await import('@monoes/monograph');
1056
- const dbPath = join(this.projectRoot, '.monomind', 'monograph.db');
1057
- if (existsSync(dbPath)) {
1058
- const db = openDb(dbPath);
1059
- try {
1060
- const nodeCount = countNodes(db);
1061
- const edgeCount = countEdges(db);
1062
- const communityRows = db.prepare(`
1063
- SELECT community_id, COUNT(*) AS member_count
1064
- FROM nodes
1065
- WHERE community_id IS NOT NULL
1066
- AND label NOT IN ('File','Folder','Community','Concept')
1067
- GROUP BY community_id
1068
- ORDER BY member_count DESC
1069
- LIMIT 5
1070
- `).all();
1071
- const bridgeRows = db.prepare(`
1072
- SELECT n.name, n.label, n.file_path, n.start_line,
1073
- COUNT(DISTINCT e.id) AS cross_edges
1074
- FROM nodes n
1075
- JOIN edges e ON (e.source_id = n.id OR e.target_id = n.id)
1076
- JOIN nodes n2 ON (
1077
- CASE WHEN e.source_id = n.id THEN e.target_id ELSE e.source_id END = n2.id
1078
- )
1079
- WHERE n.community_id IS NOT NULL
1080
- AND n2.community_id IS NOT NULL
1081
- AND n.community_id != n2.community_id
1082
- AND n.label NOT IN ('File','Folder','Community','Concept')
1083
- AND (n.file_path IS NULL OR (
1084
- n.file_path NOT LIKE '%node_modules%'
1085
- AND n.file_path NOT LIKE '%/dist/%'
1086
- AND n.file_path NOT LIKE '%.test.%'
1087
- AND n.file_path NOT LIKE '%.spec.%'
1088
- ))
1089
- GROUP BY n.id
1090
- ORDER BY cross_edges DESC
1091
- LIMIT 5
1092
- `).all();
1093
- const insights = result['insightsGained'];
1094
- if (communityRows.length > 0) {
1095
- insights.push({
1096
- category: 'community_clusters',
1097
- description: `Top ${communityRows.length} community clusters by size`,
1098
- items: communityRows.map(r => ({
1099
- communityId: r.community_id,
1100
- memberCount: r.member_count,
1101
- })),
1102
- });
1103
- }
1104
- if (bridgeRows.length > 0) {
1105
- insights.push({
1106
- category: 'bridge_nodes',
1107
- description: `Top ${bridgeRows.length} bridge nodes crossing community boundaries (high coupling risk)`,
1108
- items: bridgeRows.map(r => {
1109
- const loc = r.file_path
1110
- ? (r.start_line != null ? `${r.file_path}:${r.start_line}` : r.file_path)
1111
- : '(unknown)';
1112
- return {
1113
- name: r.name,
1114
- label: r.label,
1115
- location: loc,
1116
- crossCommunityEdges: r.cross_edges,
1117
- };
1118
- }),
1119
- });
1120
- result['patternsLearned'] = bridgeRows.length + communityRows.length;
1121
- }
1122
- result['graph'] = { nodes: nodeCount, edges: edgeCount };
1123
- }
1124
- finally {
1125
- closeDb(db);
1126
- }
1127
- }
1128
- else {
1129
- result['note'] = 'Monograph index not built — run `monomind monograph build` for deep learning';
1130
- }
1131
- }
1132
- catch { /* monograph unavailable — return minimal result */ }
1133
- return result;
1134
- }
1135
- /**
1136
- * Local refactor worker (fallback when headless unavailable)
1137
- */
1138
- async runRefactorWorkerLocal() {
1139
- return {
1140
- timestamp: new Date().toISOString(),
1141
- mode: 'local',
1142
- suggestions: [],
1143
- duplicatesFound: 0,
1144
- note: 'Install Claude Code CLI for AI-powered refactoring suggestions',
1145
- };
1146
- }
1147
- /**
1148
- * Local deepdive worker (fallback when headless unavailable)
1149
- */
1150
- async runDeepdiveWorkerLocal() {
1151
- const deepdiveFile = join(this.projectRoot, '.monomind', 'metrics', 'deepdive.json');
1152
- const metricsDir = join(this.projectRoot, '.monomind', 'metrics');
1153
- if (!existsSync(metricsDir)) {
1154
- mkdirSync(metricsDir, { recursive: true });
1155
- }
1156
- const result = {
1157
- timestamp: new Date().toISOString(),
1158
- mode: 'local',
1159
- analysisDepth: 'graph',
1160
- findings: [],
1161
- };
1162
- // Enrich with monograph god nodes and high-degree file analysis for LLM context injection.
1163
- // Lazy-import to avoid hard dependency; silently skip on any error.
1164
- try {
1165
- const { openDb, closeDb, countNodes, countEdges } = await import('@monoes/monograph');
1166
- const dbPath = join(this.projectRoot, '.monomind', 'monograph.db');
1167
- if (existsSync(dbPath)) {
1168
- const db = openDb(dbPath);
1169
- try {
1170
- const nodeCount = countNodes(db);
1171
- const edgeCount = countEdges(db);
1172
- const godNodeRows = db.prepare(`
1173
- SELECT n.name, n.file_path, n.label,
1174
- COUNT(DISTINCT e1.id) + COUNT(DISTINCT e2.id) AS degree
1175
- FROM nodes n
1176
- LEFT JOIN edges e1 ON e1.source_id = n.id
1177
- LEFT JOIN edges e2 ON e2.target_id = n.id
1178
- WHERE n.label NOT IN ('File','Folder','Community','Concept')
1179
- AND (n.file_path IS NULL OR (
1180
- n.file_path NOT LIKE '%node_modules%'
1181
- AND n.file_path NOT LIKE '%/dist/%'
1182
- AND n.file_path NOT LIKE '%.test.%'
1183
- AND n.file_path NOT LIKE '%.spec.%'
1184
- ))
1185
- GROUP BY n.id
1186
- ORDER BY degree DESC
1187
- LIMIT 5
1188
- `).all();
1189
- const godNodes = godNodeRows.map(r => ({
1190
- name: r.name,
1191
- label: r.label,
1192
- file: r.file_path ?? '(unknown)',
1193
- degree: r.degree,
1194
- }));
1195
- const fileRows = db.prepare(`
1196
- SELECT n.file_path,
1197
- COUNT(DISTINCT e2.id) AS in_deg,
1198
- COUNT(DISTINCT e1.id) AS out_deg
1199
- FROM nodes n
1200
- LEFT JOIN edges e1 ON e1.source_id = n.id
1201
- LEFT JOIN edges e2 ON e2.target_id = n.id
1202
- WHERE n.label = 'File'
1203
- AND n.file_path NOT LIKE '%node_modules%'
1204
- AND n.file_path NOT LIKE '%/dist/%'
1205
- AND n.file_path NOT LIKE '%.test.%'
1206
- AND n.file_path NOT LIKE '%.spec.%'
1207
- GROUP BY n.id
1208
- ORDER BY (in_deg + out_deg) DESC
1209
- LIMIT 5
1210
- `).all();
1211
- const highDegFiles = fileRows.map(r => ({
1212
- file: r.file_path
1213
- .replace(this.projectRoot + '/', '')
1214
- .replace(this.projectRoot + '\\', ''),
1215
- inDegree: r.in_deg,
1216
- outDegree: r.out_deg,
1217
- totalDegree: r.in_deg + r.out_deg,
1218
- }));
1219
- const findings = [];
1220
- if (godNodes.length > 0) {
1221
- findings.push({
1222
- category: 'god_nodes',
1223
- description: `Top ${godNodes.length} high-centrality symbols (most imported/referenced)`,
1224
- items: godNodes,
1225
- });
1226
- }
1227
- if (highDegFiles.length > 0) {
1228
- findings.push({
1229
- category: 'high_degree_files',
1230
- description: `Top ${highDegFiles.length} files by total edge degree (import + export connections)`,
1231
- items: highDegFiles,
1232
- });
1233
- }
1234
- result['graph'] = { nodes: nodeCount, edges: edgeCount };
1235
- result['findings'] = findings;
1236
- result['analysisDepth'] = 'graph';
1237
- }
1238
- finally {
1239
- closeDb(db);
1240
- }
1241
- }
1242
- else {
1243
- result['note'] = 'Monograph index not built — run `monomind monograph build` for deep analysis';
1244
- }
1245
- }
1246
- catch { /* monograph unavailable — return minimal result */ }
1247
- const deepdiveFileTmp = deepdiveFile + '.tmp';
1248
- writeFileSync(deepdiveFileTmp, JSON.stringify(result, null, 2));
1249
- renameSync(deepdiveFileTmp, deepdiveFile);
1250
- return result;
1251
- }
1252
- /**
1253
- * Local benchmark worker
1254
- */
1255
- async runBenchmarkWorkerLocal() {
1256
- const benchmarkFile = join(this.projectRoot, '.monomind', 'metrics', 'benchmark.json');
1257
- const metricsDir = join(this.projectRoot, '.monomind', 'metrics');
1258
- if (!existsSync(metricsDir)) {
1259
- mkdirSync(metricsDir, { recursive: true });
1260
- }
1261
- const result = {
1262
- timestamp: new Date().toISOString(),
1263
- mode: 'local',
1264
- benchmarks: {
1265
- memoryUsage: process.memoryUsage(),
1266
- cpuUsage: process.cpuUsage(),
1267
- uptime: process.uptime(),
1268
- },
1269
- };
1270
- const benchmarkFileTmp = benchmarkFile + '.tmp';
1271
- writeFileSync(benchmarkFileTmp, JSON.stringify(result, null, 2));
1272
- renameSync(benchmarkFileTmp, benchmarkFile);
1273
- return result;
1274
- }
1275
- /**
1276
- * Local preload worker
1277
- */
1278
- async runPreloadWorkerLocal() {
1279
- return {
1280
- timestamp: new Date().toISOString(),
1281
- mode: 'local',
1282
- resourcesPreloaded: 0,
1283
- cacheStatus: 'active',
1284
- };
1285
- }
1286
- /**
1287
- * Manually trigger a worker
1288
- */
1289
- async triggerWorker(type) {
1290
- const workerConfig = this.config.workers.find(w => w.type === type);
1291
- if (!workerConfig) {
1292
- throw new Error(`Unknown worker type: ${type}`);
1293
- }
1294
- const result = await this.executeWorkerWithConcurrencyControl(workerConfig);
1295
- if (result !== null)
1296
- return result;
1297
- // Concurrency limit reached — execute directly for explicit manual trigger.
1298
- // Remove from pendingWorkers to avoid double execution when finally fires.
1299
- const pendingIdx = this.pendingWorkers.indexOf(workerConfig.type);
1300
- if (pendingIdx !== -1)
1301
- this.pendingWorkers.splice(pendingIdx, 1);
1302
- return this.executeWorker(workerConfig);
1303
- }
1304
- /**
1305
- * Enable/disable a worker
1306
- */
1307
- setWorkerEnabled(type, enabled) {
1308
- const workerConfig = this.config.workers.find(w => w.type === type);
1309
- if (workerConfig) {
1310
- workerConfig.enabled = enabled;
1311
- if (enabled && this.running) {
1312
- this.scheduleWorker(workerConfig);
1313
- }
1314
- else if (!enabled) {
1315
- const timer = this.timers.get(type);
1316
- if (timer) {
1317
- clearTimeout(timer);
1318
- this.timers.delete(type);
1319
- }
1320
- }
1321
- this.saveState();
1322
- }
1323
- }
1324
- /**
1325
- * Save daemon state to file
1326
- */
1327
- saveState() {
1328
- const state = {
1329
- running: this.running,
1330
- startedAt: this.startedAt?.toISOString(),
1331
- workers: Object.fromEntries(Array.from(this.workers.entries()).map(([type, state]) => [
1332
- type,
1333
- {
1334
- ...state,
1335
- lastRun: state.lastRun?.toISOString(),
1336
- nextRun: state.nextRun?.toISOString(),
1337
- }
1338
- ])),
1339
- config: {
1340
- ...this.config,
1341
- workers: this.config.workers.map(w => ({ ...w })),
1342
- },
1343
- savedAt: new Date().toISOString(),
1344
- };
1345
- try {
1346
- const tmp = this.config.stateFile + '.tmp';
1347
- writeFileSync(tmp, JSON.stringify(state, null, 2));
1348
- renameSync(tmp, this.config.stateFile);
1349
- }
1350
- catch (error) {
1351
- this.log('error', `Failed to save state: ${error}`);
1352
- }
1353
- }
1354
- /**
1355
- * Log message
1356
- */
1357
- log(level, message) {
1358
- const timestamp = new Date().toISOString();
1359
- const logMessage = `[${timestamp}] [${level.toUpperCase()}] ${message}`;
1360
- this.emit('log', { level, message, timestamp });
1361
- // Also write to log file
1362
- try {
1363
- const logFile = join(this.config.logDir, 'daemon.log');
1364
- appendFileSync(logFile, logMessage + '\n');
1365
- // Opportunistic rotation: keep the log under 10 MB. When exceeded,
1366
- // discard the oldest half so recent entries are always retained.
1367
- const MAX_LOG_BYTES = 10 * 1024 * 1024;
1368
- if (statSync(logFile).size > MAX_LOG_BYTES) {
1369
- const content = readFileSync(logFile, 'utf-8');
1370
- const lines = content.split('\n').filter(Boolean);
1371
- const trimmed = lines.slice(Math.floor(lines.length / 2)).join('\n') + '\n';
1372
- const tmp = `${logFile}.${process.pid}.${Date.now()}.tmp`;
1373
- writeFileSync(tmp, trimmed);
1374
- renameSync(tmp, logFile);
1375
- }
1376
- }
1377
- catch {
1378
- // Ignore log write errors
1379
- }
1380
- }
1381
- }
1382
- // Singleton instance for global access
1383
- let daemonInstance = null;
1384
- /**
1385
- * Get or create daemon instance
1386
- */
1387
- export function getDaemon(projectRoot, config) {
1388
- if (!daemonInstance && projectRoot) {
1389
- daemonInstance = new WorkerDaemon(projectRoot, config);
1390
- }
1391
- if (!daemonInstance) {
1392
- throw new Error('Daemon not initialized. Provide projectRoot on first call.');
1393
- }
1394
- return daemonInstance;
1395
- }
1396
- /**
1397
- * Start daemon (for use in session-start hook)
1398
- */
1399
- export async function startDaemon(projectRoot, config) {
1400
- // A2: the daemon is a long-lived host — keep the SONA write-path enabled so
1401
- // trajectories accumulate across worker runs and reach the consolidation
1402
- // threshold (see startMCPServer for the one-shot-CLI rationale).
1403
- process.env.MONOMIND_PERSISTENT_HOST = '1';
1404
- const daemon = getDaemon(projectRoot, config);
1405
- await daemon.start();
1406
- return daemon;
1407
- }
1408
- /**
1409
- * Stop daemon
1410
- */
1411
- export async function stopDaemon() {
1412
- if (daemonInstance) {
1413
- await daemonInstance.stop();
1414
- }
1415
- }
1416
- export default WorkerDaemon;
1417
- //# sourceMappingURL=worker-daemon.js.map