@monoes/monomindcli 1.19.0 → 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 (369) hide show
  1. package/.claude/agents/github/issue-tracker.md +0 -2
  2. package/.claude/agents/github/pr-manager.md +0 -2
  3. package/.claude/agents/github/repo-architect.md +3 -11
  4. package/.claude/agents/goal/goal-planner.md +0 -1
  5. package/.claude/commands/github/issue-tracker.md +0 -2
  6. package/.claude/commands/github/pr-manager.md +0 -2
  7. package/.claude/commands/github/repo-architect.md +3 -10
  8. package/.claude/commands/mastermind/help.md +3 -3
  9. package/.claude/commands/workflows/README.md +0 -1
  10. package/.claude/commands/workflows/workflow-create.md +0 -1
  11. package/.claude/commands/workflows/workflow-execute.md +1 -3
  12. package/.claude/commands/workflows/workflow-export.md +0 -2
  13. package/.claude/helpers/handlers/agent-start-handler.cjs +18 -1
  14. package/.claude/helpers/handlers/edit-handler.cjs +15 -0
  15. package/.claude/helpers/handlers/gates-handler.cjs +2 -8
  16. package/.claude/helpers/handlers/route-handler.cjs +149 -7
  17. package/.claude/helpers/handlers/session-handler.cjs +47 -25
  18. package/.claude/helpers/handlers/session-restore-handler.cjs +80 -43
  19. package/.claude/helpers/handlers/task-handler.cjs +8 -4
  20. package/.claude/helpers/hook-handler.cjs +69 -16
  21. package/.claude/helpers/intelligence.cjs +100 -9
  22. package/.claude/helpers/router.cjs +78 -5
  23. package/.claude/helpers/skill-registry.json +0 -189
  24. package/.claude/skills/github-toolkit/SKILL.md +60 -0
  25. package/.claude/skills/hive-mind-advanced/SKILL.md +0 -15
  26. package/.claude/skills/hooks-automation/SKILL.md +0 -1
  27. package/.claude/skills/mastermind-skills/_protocol.md +1 -1
  28. package/.claude/skills/mastermind-skills/build.md +1 -2
  29. package/.claude/skills/memory-toolkit/SKILL.md +75 -0
  30. package/.claude/skills/specialagent/SKILL.md +2 -4
  31. package/.claude/skills/swarm-advanced/SKILL.md +0 -1
  32. package/README.md +2 -5
  33. package/dist/src/autopilot-state.d.ts.map +1 -1
  34. package/dist/src/autopilot-state.js +4 -5
  35. package/dist/src/autopilot-state.js.map +1 -1
  36. package/dist/src/browser/dashboard/server.d.ts.map +1 -1
  37. package/dist/src/browser/dashboard/server.js +69 -1
  38. package/dist/src/browser/dashboard/server.js.map +1 -1
  39. package/dist/src/browser/dashboard/ui.html +214 -1764
  40. package/dist/src/capabilities/index.d.ts +0 -2
  41. package/dist/src/capabilities/index.d.ts.map +1 -1
  42. package/dist/src/capabilities/index.js +0 -1
  43. package/dist/src/capabilities/index.js.map +1 -1
  44. package/dist/src/commands/agent-lifecycle.d.ts.map +1 -1
  45. package/dist/src/commands/agent-lifecycle.js +2 -6
  46. package/dist/src/commands/agent-lifecycle.js.map +1 -1
  47. package/dist/src/commands/analyze.d.ts +0 -4
  48. package/dist/src/commands/analyze.d.ts.map +1 -1
  49. package/dist/src/commands/analyze.js +1 -29
  50. package/dist/src/commands/analyze.js.map +1 -1
  51. package/dist/src/commands/completions.d.ts.map +1 -1
  52. package/dist/src/commands/completions.js +3 -22
  53. package/dist/src/commands/completions.js.map +1 -1
  54. package/dist/src/commands/config.d.ts.map +1 -1
  55. package/dist/src/commands/config.js +0 -6
  56. package/dist/src/commands/config.js.map +1 -1
  57. package/dist/src/commands/doctor-project-checks.d.ts +12 -2
  58. package/dist/src/commands/doctor-project-checks.d.ts.map +1 -1
  59. package/dist/src/commands/doctor-project-checks.js +130 -22
  60. package/dist/src/commands/doctor-project-checks.js.map +1 -1
  61. package/dist/src/commands/doctor.d.ts.map +1 -1
  62. package/dist/src/commands/doctor.js +6 -5
  63. package/dist/src/commands/doctor.js.map +1 -1
  64. package/dist/src/commands/guidance.d.ts +5 -1
  65. package/dist/src/commands/guidance.d.ts.map +1 -1
  66. package/dist/src/commands/guidance.js +11 -556
  67. package/dist/src/commands/guidance.js.map +1 -1
  68. package/dist/src/commands/hive-mind-comms.d.ts.map +1 -1
  69. package/dist/src/commands/hive-mind-comms.js +11 -4
  70. package/dist/src/commands/hive-mind-comms.js.map +1 -1
  71. package/dist/src/commands/hive-mind.d.ts +4 -4
  72. package/dist/src/commands/hive-mind.d.ts.map +1 -1
  73. package/dist/src/commands/hive-mind.js +9 -6
  74. package/dist/src/commands/hive-mind.js.map +1 -1
  75. package/dist/src/commands/hooks-formatting.d.ts +1 -5
  76. package/dist/src/commands/hooks-formatting.d.ts.map +1 -1
  77. package/dist/src/commands/hooks-formatting.js +1 -18
  78. package/dist/src/commands/hooks-formatting.js.map +1 -1
  79. package/dist/src/commands/hooks-workers.d.ts +1 -1
  80. package/dist/src/commands/hooks-workers.d.ts.map +1 -1
  81. package/dist/src/commands/hooks-workers.js +82 -330
  82. package/dist/src/commands/hooks-workers.js.map +1 -1
  83. package/dist/src/commands/index.d.ts +0 -5
  84. package/dist/src/commands/index.d.ts.map +1 -1
  85. package/dist/src/commands/index.js +0 -45
  86. package/dist/src/commands/index.js.map +1 -1
  87. package/dist/src/commands/init-wizard.js +1 -1
  88. package/dist/src/commands/init-wizard.js.map +1 -1
  89. package/dist/src/commands/init.d.ts.map +1 -1
  90. package/dist/src/commands/init.js +4 -24
  91. package/dist/src/commands/init.js.map +1 -1
  92. package/dist/src/commands/neural-core.js +11 -11
  93. package/dist/src/commands/neural-core.js.map +1 -1
  94. package/dist/src/commands/neural-optimize.d.ts.map +1 -1
  95. package/dist/src/commands/neural-optimize.js +9 -11
  96. package/dist/src/commands/neural-optimize.js.map +1 -1
  97. package/dist/src/commands/neural-registry.js +10 -10
  98. package/dist/src/commands/neural-registry.js.map +1 -1
  99. package/dist/src/commands/providers.d.ts.map +1 -1
  100. package/dist/src/commands/providers.js +90 -1
  101. package/dist/src/commands/providers.js.map +1 -1
  102. package/dist/src/commands/search-universal.d.ts +7 -1
  103. package/dist/src/commands/search-universal.d.ts.map +1 -1
  104. package/dist/src/commands/search-universal.js +59 -5
  105. package/dist/src/commands/search-universal.js.map +1 -1
  106. package/dist/src/commands/security-cve.d.ts.map +1 -1
  107. package/dist/src/commands/security-cve.js +3 -5
  108. package/dist/src/commands/security-cve.js.map +1 -1
  109. package/dist/src/commands/session.d.ts.map +1 -1
  110. package/dist/src/commands/session.js +143 -3
  111. package/dist/src/commands/session.js.map +1 -1
  112. package/dist/src/commands/start.d.ts.map +1 -1
  113. package/dist/src/commands/start.js +0 -18
  114. package/dist/src/commands/start.js.map +1 -1
  115. package/dist/src/commands/swarm.d.ts.map +1 -1
  116. package/dist/src/commands/swarm.js +112 -65
  117. package/dist/src/commands/swarm.js.map +1 -1
  118. package/dist/src/consensus/audit-writer.d.ts.map +1 -1
  119. package/dist/src/consensus/audit-writer.js +43 -1
  120. package/dist/src/consensus/audit-writer.js.map +1 -1
  121. package/dist/src/consensus/tally.d.ts +19 -0
  122. package/dist/src/consensus/tally.d.ts.map +1 -0
  123. package/dist/src/consensus/tally.js +34 -0
  124. package/dist/src/consensus/tally.js.map +1 -0
  125. package/dist/src/index.d.ts +3 -2
  126. package/dist/src/index.d.ts.map +1 -1
  127. package/dist/src/index.js +9 -12
  128. package/dist/src/index.js.map +1 -1
  129. package/dist/src/init/claudemd-generator.d.ts.map +1 -1
  130. package/dist/src/init/claudemd-generator.js +10 -14
  131. package/dist/src/init/claudemd-generator.js.map +1 -1
  132. package/dist/src/init/executor.d.ts.map +1 -1
  133. package/dist/src/init/executor.js +39 -86
  134. package/dist/src/init/executor.js.map +1 -1
  135. package/dist/src/init/settings-generator.d.ts.map +1 -1
  136. package/dist/src/init/settings-generator.js +0 -12
  137. package/dist/src/init/settings-generator.js.map +1 -1
  138. package/dist/src/init/statusline-generator.d.ts.map +1 -1
  139. package/dist/src/init/statusline-generator.js +62 -0
  140. package/dist/src/init/statusline-generator.js.map +1 -1
  141. package/dist/src/init/types.d.ts +2 -6
  142. package/dist/src/init/types.d.ts.map +1 -1
  143. package/dist/src/init/types.js +0 -3
  144. package/dist/src/init/types.js.map +1 -1
  145. package/dist/src/knowledge/document-pipeline.d.ts.map +1 -1
  146. package/dist/src/knowledge/document-pipeline.js +18 -8
  147. package/dist/src/knowledge/document-pipeline.js.map +1 -1
  148. package/dist/src/mcp-client.d.ts.map +1 -1
  149. package/dist/src/mcp-client.js +0 -2
  150. package/dist/src/mcp-client.js.map +1 -1
  151. package/dist/src/mcp-server.d.ts.map +1 -1
  152. package/dist/src/mcp-server.js +12 -14
  153. package/dist/src/mcp-server.js.map +1 -1
  154. package/dist/src/mcp-tools/coherence/coherence-check.d.ts.map +1 -1
  155. package/dist/src/mcp-tools/coherence/coherence-check.js +1 -19
  156. package/dist/src/mcp-tools/coherence/coherence-check.js.map +1 -1
  157. package/dist/src/mcp-tools/coherence/types.d.ts +3 -2
  158. package/dist/src/mcp-tools/coherence/types.d.ts.map +1 -1
  159. package/dist/src/mcp-tools/coherence/types.js +3 -18
  160. package/dist/src/mcp-tools/coherence/types.js.map +1 -1
  161. package/dist/src/mcp-tools/embeddings-tools.d.ts.map +1 -1
  162. package/dist/src/mcp-tools/embeddings-tools.js +1 -7
  163. package/dist/src/mcp-tools/embeddings-tools.js.map +1 -1
  164. package/dist/src/mcp-tools/graphify-tools.js +2 -2
  165. package/dist/src/mcp-tools/graphify-tools.js.map +1 -1
  166. package/dist/src/mcp-tools/guidance-tools.d.ts.map +1 -1
  167. package/dist/src/mcp-tools/guidance-tools.js +7 -17
  168. package/dist/src/mcp-tools/guidance-tools.js.map +1 -1
  169. package/dist/src/mcp-tools/hive-mind-tools.d.ts +8 -1
  170. package/dist/src/mcp-tools/hive-mind-tools.d.ts.map +1 -1
  171. package/dist/src/mcp-tools/hive-mind-tools.js +174 -38
  172. package/dist/src/mcp-tools/hive-mind-tools.js.map +1 -1
  173. package/dist/src/mcp-tools/hooks-advanced.d.ts +18 -0
  174. package/dist/src/mcp-tools/hooks-advanced.d.ts.map +1 -0
  175. package/dist/src/mcp-tools/hooks-advanced.js +25 -0
  176. package/dist/src/mcp-tools/hooks-advanced.js.map +1 -0
  177. package/dist/src/mcp-tools/hooks-intelligence.d.ts +4 -8
  178. package/dist/src/mcp-tools/hooks-intelligence.d.ts.map +1 -1
  179. package/dist/src/mcp-tools/hooks-intelligence.js +33 -482
  180. package/dist/src/mcp-tools/hooks-intelligence.js.map +1 -1
  181. package/dist/src/mcp-tools/hooks-routing.d.ts +1 -0
  182. package/dist/src/mcp-tools/hooks-routing.d.ts.map +1 -1
  183. package/dist/src/mcp-tools/hooks-routing.js +51 -43
  184. package/dist/src/mcp-tools/hooks-routing.js.map +1 -1
  185. package/dist/src/mcp-tools/hooks-synthesis.d.ts +31 -0
  186. package/dist/src/mcp-tools/hooks-synthesis.d.ts.map +1 -0
  187. package/dist/src/mcp-tools/hooks-synthesis.js +196 -0
  188. package/dist/src/mcp-tools/hooks-synthesis.js.map +1 -0
  189. package/dist/src/mcp-tools/hooks-tools.d.ts.map +1 -1
  190. package/dist/src/mcp-tools/hooks-tools.js +10 -8
  191. package/dist/src/mcp-tools/hooks-tools.js.map +1 -1
  192. package/dist/src/mcp-tools/index.d.ts +0 -1
  193. package/dist/src/mcp-tools/index.d.ts.map +1 -1
  194. package/dist/src/mcp-tools/index.js +0 -1
  195. package/dist/src/mcp-tools/index.js.map +1 -1
  196. package/dist/src/mcp-tools/memory-tools.d.ts.map +1 -1
  197. package/dist/src/mcp-tools/memory-tools.js +20 -29
  198. package/dist/src/mcp-tools/memory-tools.js.map +1 -1
  199. package/dist/src/mcp-tools/monograph-tools.d.ts +6 -0
  200. package/dist/src/mcp-tools/monograph-tools.d.ts.map +1 -1
  201. package/dist/src/mcp-tools/monograph-tools.js +78 -220
  202. package/dist/src/mcp-tools/monograph-tools.js.map +1 -1
  203. package/dist/src/mcp-tools/neural-tools.d.ts +9 -4
  204. package/dist/src/mcp-tools/neural-tools.d.ts.map +1 -1
  205. package/dist/src/mcp-tools/neural-tools.js +242 -506
  206. package/dist/src/mcp-tools/neural-tools.js.map +1 -1
  207. package/dist/src/mcp-tools/security-tools.d.ts.map +1 -1
  208. package/dist/src/mcp-tools/security-tools.js +103 -0
  209. package/dist/src/mcp-tools/security-tools.js.map +1 -1
  210. package/dist/src/memory/intelligence.d.ts +2 -1
  211. package/dist/src/memory/intelligence.d.ts.map +1 -1
  212. package/dist/src/memory/intelligence.js +56 -43
  213. package/dist/src/memory/intelligence.js.map +1 -1
  214. package/dist/src/memory/memory-bridge.d.ts.map +1 -1
  215. package/dist/src/memory/memory-bridge.js +14 -9
  216. package/dist/src/memory/memory-bridge.js.map +1 -1
  217. package/dist/src/memory/memory-read.d.ts.map +1 -1
  218. package/dist/src/memory/memory-read.js +1 -19
  219. package/dist/src/memory/memory-read.js.map +1 -1
  220. package/dist/src/suggest.d.ts.map +1 -1
  221. package/dist/src/suggest.js +1 -7
  222. package/dist/src/suggest.js.map +1 -1
  223. package/dist/src/transfer/store/discovery.d.ts +3 -2
  224. package/dist/src/transfer/store/discovery.d.ts.map +1 -1
  225. package/dist/src/transfer/store/discovery.js +22 -70
  226. package/dist/src/transfer/store/discovery.js.map +1 -1
  227. package/dist/src/update/checker.d.ts.map +1 -1
  228. package/dist/src/update/checker.js +0 -1
  229. package/dist/src/update/checker.js.map +1 -1
  230. package/dist/src/utils/cosine-similarity.d.ts +22 -0
  231. package/dist/src/utils/cosine-similarity.d.ts.map +1 -0
  232. package/dist/src/utils/cosine-similarity.js +38 -0
  233. package/dist/src/utils/cosine-similarity.js.map +1 -0
  234. package/dist/src/utils/input-guards.d.ts +51 -0
  235. package/dist/src/utils/input-guards.d.ts.map +1 -0
  236. package/dist/src/utils/input-guards.js +223 -0
  237. package/dist/src/utils/input-guards.js.map +1 -0
  238. package/dist/src/utils/json-file.d.ts +33 -0
  239. package/dist/src/utils/json-file.d.ts.map +1 -0
  240. package/dist/src/utils/json-file.js +57 -0
  241. package/dist/src/utils/json-file.js.map +1 -0
  242. package/dist/tsconfig.tsbuildinfo +1 -1
  243. package/package.json +9 -6
  244. package/scripts/sync-claude-assets.sh +16 -20
  245. package/.claude/agents/generated/case-analyst.md +0 -50
  246. package/.claude/agents/generated/channel-intelligence-director.md +0 -87
  247. package/.claude/agents/generated/chief-growth-officer.md +0 -88
  248. package/.claude/agents/generated/churn-analyst.md +0 -53
  249. package/.claude/agents/generated/code-reviewer.md +0 -55
  250. package/.claude/agents/generated/code-validator.md +0 -57
  251. package/.claude/agents/generated/complexity-scanner.md +0 -56
  252. package/.claude/agents/generated/content-seo-strategist.md +0 -90
  253. package/.claude/agents/generated/copy-editor.md +0 -45
  254. package/.claude/agents/generated/court-reporter.md +0 -50
  255. package/.claude/agents/generated/defender.md +0 -51
  256. package/.claude/agents/generated/devbot-orchestrator.md +0 -58
  257. package/.claude/agents/generated/devbot-planner.md +0 -63
  258. package/.claude/agents/generated/developer-community-strategist.md +0 -91
  259. package/.claude/agents/generated/editor-in-chief.md +0 -45
  260. package/.claude/agents/generated/fact-checker.md +0 -45
  261. package/.claude/agents/generated/impact-assessor.md +0 -54
  262. package/.claude/agents/generated/judge.md +0 -51
  263. package/.claude/agents/generated/outreach-partnership-strategist.md +0 -90
  264. package/.claude/agents/generated/prosecutor.md +0 -51
  265. package/.claude/agents/generated/reporter.md +0 -45
  266. package/.claude/agents/generated/social-media-strategist.md +0 -91
  267. package/.claude/agents/generated/video-visual-strategist.md +0 -90
  268. package/.claude/agents/reengineer-squad/boss.md +0 -113
  269. package/.claude/agents/reengineer-squad/critic-architect.md +0 -132
  270. package/.claude/agents/reengineer-squad/git-manager.md +0 -145
  271. package/.claude/agents/reengineer-squad/idea-generator.md +0 -95
  272. package/.claude/agents/reengineer-squad/implementer.md +0 -112
  273. package/.claude/agents/reengineer-squad/integration-planner.md +0 -112
  274. package/.claude/agents/reengineer-squad/source-analyst.md +0 -103
  275. package/.claude/agents/reengineer-squad/target-analyst.md +0 -118
  276. package/.claude/agents/reengineer-squad/tester.md +0 -105
  277. package/.claude/agents/sparc/architecture.md +0 -453
  278. package/.claude/agents/sparc/pseudocode.md +0 -299
  279. package/.claude/agents/sparc/refinement.md +0 -504
  280. package/.claude/agents/sparc/specification.md +0 -258
  281. package/.claude/agents/templates/implementer-sparc-coder.md +0 -231
  282. package/.claude/commands/sparc/analyzer.md +0 -35
  283. package/.claude/commands/sparc/architect.md +0 -36
  284. package/.claude/commands/sparc/ask.md +0 -56
  285. package/.claude/commands/sparc/batch-executor.md +0 -37
  286. package/.claude/commands/sparc/code.md +0 -48
  287. package/.claude/commands/sparc/coder.md +0 -37
  288. package/.claude/commands/sparc/debug.md +0 -42
  289. package/.claude/commands/sparc/debugger.md +0 -37
  290. package/.claude/commands/sparc/designer.md +0 -36
  291. package/.claude/commands/sparc/devops.md +0 -68
  292. package/.claude/commands/sparc/docs-writer.md +0 -39
  293. package/.claude/commands/sparc/documenter.md +0 -37
  294. package/.claude/commands/sparc/innovator.md +0 -37
  295. package/.claude/commands/sparc/integration.md +0 -42
  296. package/.claude/commands/sparc/mcp.md +0 -76
  297. package/.claude/commands/sparc/memory-manager.md +0 -57
  298. package/.claude/commands/sparc/optimizer.md +0 -37
  299. package/.claude/commands/sparc/orchestrator.md +0 -70
  300. package/.claude/commands/sparc/post-deployment-monitoring-mode.md +0 -42
  301. package/.claude/commands/sparc/refinement-optimization-mode.md +0 -42
  302. package/.claude/commands/sparc/researcher.md +0 -37
  303. package/.claude/commands/sparc/reviewer.md +0 -37
  304. package/.claude/commands/sparc/security-review.md +0 -39
  305. package/.claude/commands/sparc/sparc-modes.md +0 -120
  306. package/.claude/commands/sparc/sparc.md +0 -71
  307. package/.claude/commands/sparc/spec-pseudocode.md +0 -39
  308. package/.claude/commands/sparc/supabase-admin.md +0 -301
  309. package/.claude/commands/sparc/swarm-coordinator.md +0 -50
  310. package/.claude/commands/sparc/tdd.md +0 -37
  311. package/.claude/commands/sparc/tester.md +0 -37
  312. package/.claude/commands/sparc/tutorial.md +0 -38
  313. package/.claude/commands/sparc/workflow-manager.md +0 -37
  314. package/.claude/commands/sparc.md +0 -112
  315. package/.claude/skills/sparc-methodology/SKILL.md +0 -950
  316. package/dist/src/capabilities/enrichment.d.ts +0 -44
  317. package/dist/src/capabilities/enrichment.d.ts.map +0 -1
  318. package/dist/src/capabilities/enrichment.js +0 -141
  319. package/dist/src/capabilities/enrichment.js.map +0 -1
  320. package/dist/src/commands/analyze-boundaries.d.ts +0 -14
  321. package/dist/src/commands/analyze-boundaries.d.ts.map +0 -1
  322. package/dist/src/commands/analyze-boundaries.js +0 -295
  323. package/dist/src/commands/analyze-boundaries.js.map +0 -1
  324. package/dist/src/commands/analyze-graph.d.ts +0 -14
  325. package/dist/src/commands/analyze-graph.d.ts.map +0 -1
  326. package/dist/src/commands/analyze-graph.js +0 -304
  327. package/dist/src/commands/analyze-graph.js.map +0 -1
  328. package/dist/src/commands/claims.d.ts +0 -10
  329. package/dist/src/commands/claims.d.ts.map +0 -1
  330. package/dist/src/commands/claims.js +0 -650
  331. package/dist/src/commands/claims.js.map +0 -1
  332. package/dist/src/commands/daemon.d.ts +0 -8
  333. package/dist/src/commands/daemon.d.ts.map +0 -1
  334. package/dist/src/commands/daemon.js +0 -681
  335. package/dist/src/commands/daemon.js.map +0 -1
  336. package/dist/src/commands/enrich.d.ts +0 -10
  337. package/dist/src/commands/enrich.d.ts.map +0 -1
  338. package/dist/src/commands/enrich.js +0 -58
  339. package/dist/src/commands/enrich.js.map +0 -1
  340. package/dist/src/commands/issues.d.ts +0 -21
  341. package/dist/src/commands/issues.d.ts.map +0 -1
  342. package/dist/src/commands/issues.js +0 -575
  343. package/dist/src/commands/issues.js.map +0 -1
  344. package/dist/src/commands/workflow.d.ts +0 -8
  345. package/dist/src/commands/workflow.d.ts.map +0 -1
  346. package/dist/src/commands/workflow.js +0 -575
  347. package/dist/src/commands/workflow.js.map +0 -1
  348. package/dist/src/mcp-tools/workflow-tools.d.ts +0 -8
  349. package/dist/src/mcp-tools/workflow-tools.d.ts.map +0 -1
  350. package/dist/src/mcp-tools/workflow-tools.js +0 -717
  351. package/dist/src/mcp-tools/workflow-tools.js.map +0 -1
  352. package/dist/src/services/claim-service.d.ts +0 -198
  353. package/dist/src/services/claim-service.d.ts.map +0 -1
  354. package/dist/src/services/claim-service.js +0 -890
  355. package/dist/src/services/claim-service.js.map +0 -1
  356. package/dist/src/services/headless-worker-executor.d.ts +0 -311
  357. package/dist/src/services/headless-worker-executor.d.ts.map +0 -1
  358. package/dist/src/services/headless-worker-executor.js +0 -1183
  359. package/dist/src/services/headless-worker-executor.js.map +0 -1
  360. package/dist/src/services/worker-daemon.d.ts +0 -230
  361. package/dist/src/services/worker-daemon.d.ts.map +0 -1
  362. package/dist/src/services/worker-daemon.js +0 -1350
  363. package/dist/src/services/worker-daemon.js.map +0 -1
  364. package/dist/src/ui/.monomind/capture/active-run.json +0 -1
  365. package/dist/src/ui/.monomind/orgs/system-trial-qa/runs/real-events-1782290897.convs.jsonl +0 -3
  366. package/dist/src/ui/.monomind/orgs/system-trial-qa/runs/real-events-1782290897.jsonl +0 -11
  367. package/dist/src/ui/.monomind/orgs/system-trial-qa/runs/rigid-qa-restart-1782288201.jsonl +0 -540
  368. package/dist/src/ui/.monomind/orgs/system-trial-qa-threads.jsonl +0 -3
  369. package/dist/src/ui/.monomind/orgs/test-event-fix/runs/rigid-qa-restart-1782288201.jsonl +0 -2
@@ -1,204 +1,112 @@
1
1
  /**
2
- * Pattern Store MCP Tools
2
+ * Pattern Store MCP Tools — "neural" namespace (legacy name, kept for API compat)
3
3
  *
4
- * Embed text as vectors, store patterns, search by cosine similarity.
5
- * Uses monovector ONNX embeddings when available, deterministic hash fallback otherwise.
6
- * Tools are registered under the "neural" namespace for backwards compatibility.
4
+ * These tools embed text as vectors and search by cosine similarity.
5
+ * No ML training, gradient descent, or neural network inference occurs.
6
+ * The "train" tool embeds and stores; the "predict" tool finds similar stored
7
+ * patterns. Embeddings come from the shared memory/embedding-operations.ts
8
+ * pipeline (LanceDB bridge -> ONNX -> deterministic hash fallback).
9
+ *
10
+ * All pattern storage is delegated to intelligence.ts's LocalReasoningBank
11
+ * (single source of truth for patterns.json). No separate models.json store.
7
12
  */
8
- import { getProjectCwd } from './types.js';
9
- import { existsSync, readFileSync, writeFileSync, renameSync, mkdirSync, statSync } from 'node:fs';
10
- import { join } from 'node:path';
11
- const MAX_NEURAL_STORE_BYTES = 50 * 1024 * 1024; // 50 MB
12
- const NEURAL_RESERVED_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
13
- // Embeddings via monovector ONNX when available; deterministic hash fallback otherwise.
14
- let realEmbeddings = null;
15
- let embeddingServiceName = 'none';
16
- try {
17
- const monovector = await import('monovector').catch(() => null);
18
- if (monovector?.getOptimizedOnnxEmbedder) {
19
- await monovector.initOnnxEmbedder?.();
20
- const onnxEmb = monovector.getOptimizedOnnxEmbedder();
21
- if (onnxEmb?.embed) {
22
- const probe = await onnxEmb.embed('test');
23
- const hasNonZero = ArrayBuffer.isView(probe) || Array.isArray(probe)
24
- ? [...probe].some((v) => v !== 0)
25
- : false;
26
- if (probe && probe.length > 0 && hasNonZero) {
27
- realEmbeddings = { embed: async (text) => Array.from(await onnxEmb.embed(text)) };
28
- embeddingServiceName = 'monovector/onnx';
29
- }
30
- }
31
- }
32
- }
33
- catch {
34
- // No ONNX embedding provider available, will use hash fallback
35
- }
36
- // Storage paths
37
- const STORAGE_DIR = '.monomind';
38
- const NEURAL_DIR = 'neural';
39
- const MODELS_FILE = 'models.json';
40
- const PATTERNS_FILE = 'patterns.json';
41
- function getNeuralDir() {
42
- return join(getProjectCwd(), STORAGE_DIR, NEURAL_DIR);
43
- }
44
- function getNeuralPath() {
45
- return join(getNeuralDir(), MODELS_FILE);
46
- }
47
- function ensureNeuralDir() {
48
- const dir = getNeuralDir();
49
- if (!existsSync(dir)) {
50
- mkdirSync(dir, { recursive: true });
51
- }
52
- }
53
- function loadNeuralStore() {
13
+ const RESERVED_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
14
+ const MAX_MODEL_ID_LEN = 256;
15
+ const MAX_PATTERNS = 10000;
16
+ const MAX_TRAINING_ENTRIES = 1000;
17
+ const MAX_TEXT_LENGTH = 64 * 1024;
18
+ const MAX_SEARCH_QUERY_LENGTH = 16 * 1024;
19
+ // Embeddings: delegate to the shared embedding pipeline (LanceDB bridge -> ONNX ->
20
+ // deterministic hash fallback) in memory/embedding-operations.ts.
21
+ let lastEmbeddingModel = 'unknown';
22
+ /**
23
+ * Generate embedding via the shared pipeline (LanceDB bridge -> ONNX -> deterministic
24
+ * hash), same one used by CLI `neural` commands and memory search. Falls back to a
25
+ * local deterministic hash only if the shared module fails to load entirely.
26
+ */
27
+ async function generateEmbedding(text, dims = 384) {
28
+ if (!text)
29
+ return new Array(dims).fill(0);
54
30
  try {
55
- const path = getNeuralPath();
56
- if (existsSync(path)) {
57
- if (statSync(path).size > MAX_NEURAL_STORE_BYTES) {
58
- return { models: {}, patterns: {}, version: '3.0.0' };
59
- }
60
- const raw = JSON.parse(readFileSync(path, 'utf-8'));
61
- // Strip proto-polluting keys from top-level containers
62
- const models = {};
63
- for (const [k, v] of Object.entries(raw.models ?? {})) {
64
- if (!NEURAL_RESERVED_KEYS.has(k))
65
- models[k] = v;
66
- }
67
- const patterns = {};
68
- for (const [k, v] of Object.entries(raw.patterns ?? {})) {
69
- if (!NEURAL_RESERVED_KEYS.has(k))
70
- patterns[k] = v;
71
- }
72
- return {
73
- models: models,
74
- patterns: patterns,
75
- version: typeof raw.version === 'string' ? raw.version : '3.0.0',
76
- };
77
- }
31
+ const { generateEmbedding: sharedGenerateEmbedding } = await import('../memory/embedding-operations.js');
32
+ const result = await sharedGenerateEmbedding(text);
33
+ lastEmbeddingModel = result.model;
34
+ return result.embedding;
78
35
  }
79
36
  catch {
80
- // Return empty store
81
- }
82
- return { models: {}, patterns: {}, version: '3.0.0' };
83
- }
84
- function saveNeuralStore(store) {
85
- ensureNeuralDir();
86
- const dest = getNeuralPath();
87
- const tmp = `${dest}.${process.pid}.${Date.now()}.tmp`;
88
- writeFileSync(tmp, JSON.stringify(store, null, 2), 'utf-8');
89
- renameSync(tmp, dest);
90
- }
91
- // Generate embedding - uses real ML embeddings if available, falls back to deterministic hash
92
- async function generateEmbedding(text, dims = 384) {
93
- // If real embeddings available and text provided, use them
94
- if (realEmbeddings && text) {
95
- try {
96
- return await realEmbeddings.embed(text);
97
- }
98
- catch {
99
- // Fall back to hash-based
100
- }
101
- }
102
- // Hash-based deterministic embedding (better than pure random for consistency)
103
- if (text) {
104
- const hash = text.split('').reduce((acc, char, i) => {
105
- return acc + char.charCodeAt(0) * (i + 1);
106
- }, 0);
107
- // Use hash to seed a deterministic embedding
37
+ // memory/embedding-operations.js unavailable — deterministic hash fallback
38
+ lastEmbeddingModel = 'hash-fallback';
39
+ const hash = text.split('').reduce((acc, char, i) => acc + char.charCodeAt(0) * (i + 1), 0);
108
40
  const embedding = [];
109
41
  let seed = hash;
110
42
  for (let i = 0; i < dims; i++) {
111
- // Simple LCG random with seed
112
43
  seed = (seed * 1103515245 + 12345) & 0x7fffffff;
113
44
  embedding.push((seed / 0x7fffffff) * 2 - 1);
114
45
  }
115
46
  return embedding;
116
47
  }
117
- // No text provided — return zero vector (callers should always provide text)
118
- return new Array(dims).fill(0);
119
48
  }
120
- // Cosine similarity for pattern search
121
- function cosineSimilarity(a, b) {
122
- if (a.length !== b.length) {
123
- throw new Error(`Embedding dimension mismatch: ${a.length} vs ${b.length}. Ensure all embeddings use the same provider and dims.`);
124
- }
125
- let dotProduct = 0;
126
- let normA = 0;
127
- let normB = 0;
128
- for (let i = 0; i < a.length; i++) {
129
- dotProduct += a[i] * b[i];
130
- normA += a[i] * a[i];
131
- normB += b[i] * b[i];
132
- }
133
- return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB) || 1);
49
+ /** Truncate and validate a modelId string */
50
+ function sanitizeModelId(raw) {
51
+ if (typeof raw !== 'string')
52
+ return null;
53
+ const id = raw.length > MAX_MODEL_ID_LEN ? raw.slice(0, MAX_MODEL_ID_LEN) : raw;
54
+ if (RESERVED_KEYS.has(id))
55
+ return null;
56
+ return id;
134
57
  }
135
58
  export const neuralTools = [
136
59
  {
137
60
  name: 'neural_train',
138
- description: 'Embed and store patterns for similarity search',
61
+ description: 'Embed text as vectors and store as named patterns for later similarity search (no ML training occurs)',
139
62
  category: 'neural',
140
63
  inputSchema: {
141
64
  type: 'object',
142
65
  properties: {
143
66
  modelId: { type: 'string', description: 'Store ID (groups related patterns)' },
144
67
  modelType: { type: 'string', enum: ['pattern', 'embedding'], description: 'Store type' },
145
- epochs: { type: 'number', description: 'Ignored (kept for backwards compatibility)' },
146
- learningRate: { type: 'number', description: 'Ignored (kept for backwards compatibility)' },
68
+ epochs: { type: 'number', description: 'Deprecated ignored. Patterns are embedded and stored, not trained.' },
69
+ learningRate: { type: 'number', description: 'Deprecated ignored. No gradient-based training occurs.' },
147
70
  data: { type: 'object', description: 'Data to embed and store (array of strings or {text/content/label} objects)' },
148
71
  },
149
72
  required: ['modelType'],
150
73
  },
151
74
  handler: async (input) => {
152
- const store = loadNeuralStore();
153
- // Cap modelId to prevent DoS via oversized object keys written to the neural store JSON.
154
- const MAX_MODEL_ID_LEN = 256;
155
75
  const rawModelId = input.modelId || `model-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
156
- const modelId = typeof rawModelId === 'string' && rawModelId.length > MAX_MODEL_ID_LEN
157
- ? rawModelId.slice(0, MAX_MODEL_ID_LEN)
158
- : rawModelId;
159
- const RESERVED_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
160
- if (RESERVED_KEYS.has(modelId)) {
76
+ const modelId = sanitizeModelId(rawModelId);
77
+ if (modelId === null) {
161
78
  return { success: false, error: 'Invalid modelId' };
162
79
  }
163
- const MAX_PATTERNS = 10000;
164
- if (Object.keys(store.patterns ?? {}).length >= MAX_PATTERNS) {
165
- return { success: false, error: `Pattern store full (max ${MAX_PATTERNS}). Run neural_compress first.` };
166
- }
167
- const MAX_MODELS = 100;
168
- if (Object.keys(store.models ?? {}).length >= MAX_MODELS) {
169
- return { success: false, error: `Model store full (max ${MAX_MODELS}). Delete old models first.` };
170
- }
171
80
  const VALID_MODEL_TYPES = new Set(['pattern', 'embedding']);
172
81
  const rawModelType = input.modelType;
173
82
  if (!rawModelType || !VALID_MODEL_TYPES.has(rawModelType)) {
174
83
  return { success: false, error: `Invalid modelType "${rawModelType}". Must be one of: pattern, embedding` };
175
84
  }
176
85
  const modelType = rawModelType;
177
- const epochs = 1;
178
- const model = {
179
- id: modelId,
180
- name: `${modelType}-store`,
181
- type: modelType,
182
- status: 'indexing',
183
- patternsStored: 0,
184
- epochs,
185
- config: {},
186
- };
187
- store.models[modelId] = model;
188
- saveNeuralStore(store);
189
- // Real training: embed training data and store as searchable patterns.
190
- // Cap input array length and re-check the pattern cap inside the loop
191
- // the pre-loop check at line 199 alone allowed an attacker to bypass
192
- // MAX_PATTERNS by passing a 100k-entry array.
193
- const MAX_TRAINING_ENTRIES = 1000;
194
- const MAX_TEXT_LENGTH = 64 * 1024;
86
+ // Initialize intelligence system (single source of truth)
87
+ const { initializeIntelligence, getReasoningBank, getAllPatterns, flushPatterns } = await import('../memory/intelligence.js');
88
+ const init = await initializeIntelligence();
89
+ if (!init.success) {
90
+ return { success: false, error: 'Failed to initialize intelligence system' };
91
+ }
92
+ const bank = getReasoningBank();
93
+ if (!bank) {
94
+ return { success: false, error: 'ReasoningBank not available' };
95
+ }
96
+ // Check pattern capacity
97
+ const existingPatterns = await getAllPatterns();
98
+ if (existingPatterns.length >= MAX_PATTERNS) {
99
+ return { success: false, error: `Pattern store full (max ${MAX_PATTERNS}). Run neural_compress first.` };
100
+ }
195
101
  const trainingData = input.data;
196
102
  let patternsStored = 0;
197
103
  if (trainingData) {
198
104
  const rawEntries = Array.isArray(trainingData) ? trainingData : [trainingData];
199
105
  const entries = rawEntries.slice(0, MAX_TRAINING_ENTRIES);
200
106
  for (let i = 0; i < entries.length; i++) {
201
- if (Object.keys(store.patterns ?? {}).length >= MAX_PATTERNS)
107
+ // Re-check capacity inside loop to prevent bypass via large arrays
108
+ const currentPatterns = await getAllPatterns();
109
+ if (currentPatterns.length >= MAX_PATTERNS)
202
110
  break;
203
111
  const entry = entries[i];
204
112
  let text = typeof entry === 'string' ? entry
@@ -212,74 +120,37 @@ export const neuralTools = [
212
120
  text = text.slice(0, MAX_TEXT_LENGTH);
213
121
  const embedding = await generateEmbedding(text, 384);
214
122
  const patternId = `${modelId}-train-${i}`;
215
- store.patterns[patternId] = {
123
+ bank.store({
216
124
  id: patternId,
217
- name: typeof entry === 'object' && entry !== null && 'label' in entry
218
- ? String(entry.label) : text.slice(0, 100),
219
125
  type: modelType,
220
126
  embedding,
221
- metadata: { modelId, epoch: epochs, index: i, raw: entry },
222
- createdAt: new Date().toISOString(),
223
- usageCount: 0,
224
- };
225
- patternsStored++;
226
- }
227
- }
228
- model.status = 'ready';
229
- model.patternsStored = patternsStored;
230
- model.trainedAt = new Date().toISOString();
231
- saveNeuralStore(store);
232
- // Mirror patterns to patterns.json so CLI commands (neural patterns list,
233
- // neural predict) can find patterns trained via MCP and vice versa.
234
- if (patternsStored > 0) {
235
- try {
236
- const patternsPath = join(getNeuralDir(), PATTERNS_FILE);
237
- let existing = [];
238
- if (existsSync(patternsPath) && statSync(patternsPath).size <= MAX_NEURAL_STORE_BYTES) {
239
- const raw = readFileSync(patternsPath, 'utf-8');
240
- const parsed = JSON.parse(raw);
241
- if (Array.isArray(parsed))
242
- existing = parsed;
243
- }
244
- const existingIds = new Set(existing.map(p => p['id']));
245
- const newEntries = Object.values(store.patterns)
246
- .filter(p => p.id.startsWith(modelId) && !existingIds.has(p.id))
247
- .map(p => ({
248
- id: p.id,
249
- type: p.type,
250
- content: p.name,
127
+ content: typeof entry === 'object' && entry !== null && 'label' in entry
128
+ ? String(entry.label) : text.slice(0, 100),
251
129
  confidence: 0.8,
252
- usageCount: 0,
253
- embedding: p.embedding,
254
- createdAt: p.createdAt,
255
- }));
256
- if (newEntries.length > 0) {
257
- const merged = [...existing, ...newEntries];
258
- const tmp = `${patternsPath}.${process.pid}.${Date.now()}.tmp`;
259
- writeFileSync(tmp, JSON.stringify(merged, null, 2), 'utf-8');
260
- renameSync(tmp, patternsPath);
261
- }
262
- }
263
- catch {
264
- // Mirror is best-effort; don't fail the train operation
130
+ metadata: { modelId, index: i, raw: entry },
131
+ });
132
+ patternsStored++;
265
133
  }
266
134
  }
135
+ // Flush immediately to persist
136
+ flushPatterns();
137
+ const totalPatterns = (await getAllPatterns()).length;
267
138
  return {
268
139
  success: true,
269
- _realEmbedding: !!realEmbeddings,
140
+ _realEmbedding: lastEmbeddingModel !== 'hash-fallback',
270
141
  modelId,
271
142
  type: modelType,
272
- status: model.status,
143
+ status: 'ready',
273
144
  patternsStored,
274
- totalPatterns: Object.keys(store.patterns).length,
275
- epochs,
276
- trainedAt: model.trainedAt,
145
+ totalPatterns,
146
+ epochs: 1,
147
+ trainedAt: new Date().toISOString(),
277
148
  };
278
149
  },
279
150
  },
280
151
  {
281
152
  name: 'neural_predict',
282
- description: 'Find similar patterns by cosine similarity',
153
+ description: 'Find stored patterns most similar to input text via cosine similarity (not ML prediction)',
283
154
  category: 'neural',
284
155
  inputSchema: {
285
156
  type: 'object',
@@ -291,86 +162,38 @@ export const neuralTools = [
291
162
  required: ['input'],
292
163
  },
293
164
  handler: async (input) => {
294
- const store = loadNeuralStore();
295
- // Cap modelId to prevent O(n) hash/compare cost on absurdly long keys.
296
- const MAX_MODEL_ID_LEN_PRED = 256;
297
165
  const rawModelIdPred = input.modelId;
298
- const modelId = typeof rawModelIdPred === 'string' && rawModelIdPred.length > MAX_MODEL_ID_LEN_PRED
299
- ? rawModelIdPred.slice(0, MAX_MODEL_ID_LEN_PRED)
300
- : rawModelIdPred;
301
- const inputText = typeof input.input === 'string' ? input.input.slice(0, 16 * 1024) : '';
302
- const topK = Math.max(1, Math.min(input.topK || 3, 50));
303
- const RESERVED_KEYS_PRED = new Set(['__proto__', 'constructor', 'prototype']);
304
- if (modelId && (RESERVED_KEYS_PRED.has(modelId) || typeof modelId !== 'string')) {
305
- return { success: false, error: 'Invalid modelId' };
306
- }
307
- // Find model or use default
308
- const model = modelId
309
- ? (Object.hasOwn(store.models, modelId) ? store.models[modelId] : undefined)
310
- : Object.values(store.models).find(m => m.status === 'ready');
311
- if (model && model.status !== 'ready') {
312
- return { success: false, error: 'Model not ready' };
166
+ if (rawModelIdPred) {
167
+ const modelId = sanitizeModelId(rawModelIdPred);
168
+ if (modelId === null) {
169
+ return { success: false, error: 'Invalid modelId' };
170
+ }
313
171
  }
314
- // Generate real embedding for the input
172
+ const inputText = typeof input.input === 'string' ? input.input.slice(0, MAX_SEARCH_QUERY_LENGTH) : '';
173
+ const topK = Math.max(1, Math.min(input.topK || 3, 50));
174
+ const { initializeIntelligence, findSimilarPatterns } = await import('../memory/intelligence.js');
175
+ await initializeIntelligence();
315
176
  const startTime = performance.now();
316
177
  const embedding = await generateEmbedding(inputText, 384);
178
+ // Use intelligence.ts findSimilarPatterns which handles embedding + search
179
+ const results = await findSimilarPatterns(inputText, {
180
+ k: topK,
181
+ threshold: 0.1,
182
+ });
317
183
  const latency = Math.round(performance.now() - startTime);
318
- // Search stored patterns via cosine similarity.
319
- // Merge MCP models.json patterns with CLI patterns.json.
320
- const MAX_SCAN = 10000;
321
- const EARLY_EXIT_THRESHOLD = 0.1;
322
- const mcpPatterns = Object.values(store.patterns);
323
- const cliPatternsRaw = [];
324
- try {
325
- const cliPath = join(getNeuralDir(), PATTERNS_FILE);
326
- if (existsSync(cliPath) && statSync(cliPath).size <= MAX_NEURAL_STORE_BYTES) {
327
- const raw = JSON.parse(readFileSync(cliPath, 'utf-8'));
328
- if (Array.isArray(raw)) {
329
- const mcpIds = new Set(mcpPatterns.map(p => p.id));
330
- for (const p of raw) {
331
- if (p?.id && !mcpIds.has(p.id) && Array.isArray(p.embedding)) {
332
- cliPatternsRaw.push(p);
333
- }
334
- }
335
- }
336
- }
337
- }
338
- catch { /* best-effort */ }
339
- const cliMapped = cliPatternsRaw.map(p => ({
340
- id: p.id ?? '',
341
- name: p.content ?? p.name ?? p.type ?? '',
342
- type: p.type ?? 'general',
343
- embedding: p.embedding ?? [],
344
- metadata: {},
345
- createdAt: new Date().toISOString(),
346
- usageCount: 0,
184
+ const predictions = results.map(r => ({
185
+ label: r.content || r.type || r.id,
186
+ confidence: r.similarity ?? r.confidence,
187
+ patternId: r.id,
347
188
  }));
348
- const storedPatterns = [...mcpPatterns, ...cliMapped].slice(0, MAX_SCAN);
349
- let predictions;
350
- if (storedPatterns.length > 0) {
351
- const scored = [];
352
- for (const p of storedPatterns) {
353
- if (!Array.isArray(p.embedding) || p.embedding.length !== embedding.length)
354
- continue;
355
- const conf = Math.max(0, cosineSimilarity(embedding, p.embedding));
356
- if (conf < EARLY_EXIT_THRESHOLD)
357
- continue;
358
- scored.push({ label: p.name || p.type || p.id, confidence: conf, patternId: p.id });
359
- }
360
- predictions = scored.sort((a, b) => b.confidence - a.confidence).slice(0, topK);
361
- }
362
- else {
363
- // No patterns stored — no predictions possible
364
- predictions = [];
365
- }
366
189
  return {
367
190
  success: true,
368
- _realEmbedding: !!realEmbeddings,
369
- _hasStoredPatterns: storedPatterns.length > 0,
370
- modelId: model?.id || 'default',
191
+ _realEmbedding: lastEmbeddingModel !== 'hash-fallback',
192
+ _hasStoredPatterns: results.length > 0,
193
+ modelId: rawModelIdPred || 'default',
371
194
  input: inputText,
372
195
  predictions,
373
- embedding: embedding.slice(0, 8), // Preview of embedding
196
+ embedding: embedding.slice(0, 8),
374
197
  embeddingDims: embedding.length,
375
198
  latency,
376
199
  };
@@ -392,116 +215,118 @@ export const neuralTools = [
392
215
  },
393
216
  },
394
217
  handler: async (input) => {
395
- const store = loadNeuralStore();
396
218
  const action = input.action || 'list';
219
+ const { initializeIntelligence, getAllPatterns, getPatternsByType, getReasoningBank, findSimilarPatterns, deletePattern, flushPatterns } = await import('../memory/intelligence.js');
220
+ await initializeIntelligence();
397
221
  if (action === 'list') {
398
- const patterns = Object.values(store.patterns);
399
222
  const typeFilter = input.type;
400
- const filtered = typeFilter ? patterns.filter(p => p.type === typeFilter) : patterns;
223
+ const patterns = typeFilter
224
+ ? await getPatternsByType(typeFilter)
225
+ : await getAllPatterns();
401
226
  return {
402
- patterns: filtered.map(p => ({
227
+ patterns: patterns.map(p => ({
403
228
  id: p.id,
404
- name: p.name,
229
+ name: p.content,
405
230
  type: p.type,
406
231
  usageCount: p.usageCount,
407
- createdAt: p.createdAt,
232
+ createdAt: typeof p.createdAt === 'number' ? new Date(p.createdAt).toISOString() : p.createdAt,
408
233
  })),
409
- total: filtered.length,
234
+ total: patterns.length,
410
235
  };
411
236
  }
412
237
  if (action === 'get') {
413
238
  const patternId = input.patternId;
414
- if (!patternId || NEURAL_RESERVED_KEYS.has(patternId)) {
239
+ if (!patternId || RESERVED_KEYS.has(patternId)) {
415
240
  return { success: false, error: 'Invalid patternId' };
416
241
  }
417
- const pattern = Object.hasOwn(store.patterns, patternId) ? store.patterns[patternId] : undefined;
242
+ const bank = getReasoningBank();
243
+ if (!bank) {
244
+ return { success: false, error: 'ReasoningBank not available' };
245
+ }
246
+ const pattern = bank.get(patternId);
418
247
  if (!pattern) {
419
248
  return { success: false, error: 'Pattern not found' };
420
249
  }
421
- return { success: true, pattern };
250
+ return {
251
+ success: true,
252
+ pattern: {
253
+ id: pattern.id,
254
+ name: pattern.content,
255
+ type: pattern.type,
256
+ embedding: pattern.embedding,
257
+ metadata: pattern.metadata ?? {},
258
+ createdAt: new Date(pattern.createdAt).toISOString(),
259
+ usageCount: pattern.usageCount,
260
+ },
261
+ };
422
262
  }
423
263
  if (action === 'store') {
424
- const MAX_PATTERNS = 10000;
425
- if (Object.keys(store.patterns ?? {}).length >= MAX_PATTERNS) {
264
+ const allPatterns = await getAllPatterns();
265
+ if (allPatterns.length >= MAX_PATTERNS) {
426
266
  return { success: false, error: `Pattern store full (max ${MAX_PATTERNS}). Run neural_compress first.` };
427
267
  }
428
- const patternId = `pattern-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
429
- // Cap name length to prevent DoS in generateEmbedding (hash path is O(n))
430
- const MAX_PATTERN_NAME_LENGTH = 16 * 1024; // 16 KB
268
+ const MAX_PATTERN_NAME_LENGTH = 16 * 1024;
431
269
  const rawPatternName = input.name || 'Unnamed pattern';
432
270
  const patternName = typeof rawPatternName === 'string' && rawPatternName.length > MAX_PATTERN_NAME_LENGTH
433
271
  ? rawPatternName.slice(0, MAX_PATTERN_NAME_LENGTH)
434
272
  : rawPatternName;
435
- // Generate embedding from pattern name/content
436
273
  const embedding = await generateEmbedding(patternName, 384);
437
- const pattern = {
274
+ const patternId = `pattern-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
275
+ const patternType = input.type || 'general';
276
+ const bank = getReasoningBank();
277
+ if (!bank) {
278
+ return { success: false, error: 'ReasoningBank not available' };
279
+ }
280
+ bank.store({
438
281
  id: patternId,
439
- name: patternName,
440
- type: input.type || 'general',
282
+ type: patternType,
441
283
  embedding,
284
+ content: patternName,
285
+ confidence: 0.8,
442
286
  metadata: input.data || {},
443
- createdAt: new Date().toISOString(),
444
- usageCount: 0,
445
- };
446
- store.patterns[patternId] = pattern;
447
- saveNeuralStore(store);
287
+ });
288
+ flushPatterns();
448
289
  return {
449
290
  success: true,
450
- _realEmbedding: !!realEmbeddings,
291
+ _realEmbedding: lastEmbeddingModel !== 'hash-fallback',
451
292
  patternId,
452
- name: pattern.name,
453
- type: pattern.type,
293
+ name: patternName,
294
+ type: patternType,
454
295
  embeddingDims: embedding.length,
455
- createdAt: pattern.createdAt,
296
+ createdAt: new Date().toISOString(),
456
297
  };
457
298
  }
458
299
  if (action === 'search') {
459
- // Cap query length to prevent DoS in generateEmbedding (hash path is O(n))
460
- const MAX_SEARCH_QUERY_LENGTH = 16 * 1024; // 16 KB — matches neural_predict cap
461
300
  const rawQuery = input.query;
462
301
  const query = typeof rawQuery === 'string' && rawQuery.length > MAX_SEARCH_QUERY_LENGTH
463
302
  ? rawQuery.slice(0, MAX_SEARCH_QUERY_LENGTH)
464
303
  : rawQuery;
465
- // Generate query embedding for real similarity search
466
- const queryEmbedding = await generateEmbedding(query, 384);
467
- // Calculate REAL cosine similarity against stored patterns
468
- const results = Object.values(store.patterns)
469
- .map(p => ({
470
- ...p,
471
- similarity: cosineSimilarity(queryEmbedding, p.embedding),
472
- }))
473
- .sort((a, b) => b.similarity - a.similarity)
474
- .slice(0, 10);
475
- // Increment usageCount so prune can track retrieval frequency
476
- for (const r of results) {
477
- if (Object.hasOwn(store.patterns, r.id)) {
478
- store.patterns[r.id].usageCount = (store.patterns[r.id].usageCount || 0) + 1;
479
- }
480
- }
481
- saveNeuralStore(store);
304
+ const results = await findSimilarPatterns(query || '', {
305
+ k: 10,
306
+ threshold: 0.1,
307
+ });
482
308
  return {
483
309
  _realSimilarity: true,
484
- _realEmbedding: !!realEmbeddings,
310
+ _realEmbedding: lastEmbeddingModel !== 'hash-fallback',
485
311
  query,
486
312
  results: results.map(r => ({
487
313
  id: r.id,
488
- name: r.name,
314
+ name: r.content,
489
315
  type: r.type,
490
- similarity: r.similarity,
316
+ similarity: r.similarity ?? r.confidence,
491
317
  })),
492
318
  total: results.length,
493
319
  };
494
320
  }
495
321
  if (action === 'delete') {
496
322
  const patternId = input.patternId;
497
- if (!patternId || NEURAL_RESERVED_KEYS.has(patternId)) {
323
+ if (!patternId || RESERVED_KEYS.has(patternId)) {
498
324
  return { success: false, error: 'Invalid patternId' };
499
325
  }
500
- if (!Object.hasOwn(store.patterns, patternId)) {
326
+ const deleted = await deletePattern(patternId);
327
+ if (!deleted) {
501
328
  return { success: false, error: 'Pattern not found' };
502
329
  }
503
- delete store.patterns[patternId];
504
- saveNeuralStore(store);
505
330
  return { success: true, deleted: patternId };
506
331
  }
507
332
  return { success: false, error: 'Unknown action' };
@@ -520,97 +345,39 @@ export const neuralTools = [
520
345
  },
521
346
  },
522
347
  handler: async (input) => {
523
- const store = loadNeuralStore();
524
348
  const method = input.method || 'quantize';
525
- const targetReduction = input.targetSize || 0.5;
526
- const patterns = Object.values(store.patterns);
349
+ const { initializeIntelligence, compactPatterns, getAllPatterns } = await import('../memory/intelligence.js');
350
+ await initializeIntelligence();
351
+ const patterns = await getAllPatterns();
527
352
  if (patterns.length === 0) {
528
353
  return { success: false, error: 'No patterns to compress. Train patterns first with neural_train.' };
529
354
  }
530
355
  const beforeCount = patterns.length;
531
- const beforeSize = patterns.reduce((s, p) => s + (p.embedding?.length || 0) * 4, 0); // Float32 = 4 bytes
532
- if (method === 'quantize') {
533
- try {
534
- const { quantizeInt8, getQuantizationStats } = await import('../memory/memory-initializer.js');
535
- let totalCompressed = 0;
536
- for (const pattern of patterns) {
537
- if (pattern.embedding && pattern.embedding.length > 0) {
538
- const stats = getQuantizationStats(pattern.embedding);
539
- const quantized = quantizeInt8(pattern.embedding);
540
- // Store quantized metadata (keep original embedding for search)
541
- pattern._quantized = {
542
- scale: quantized.scale,
543
- zeroPoint: quantized.zeroPoint,
544
- compressionRatio: stats.compressionRatio,
545
- };
546
- totalCompressed++;
547
- }
548
- }
549
- saveNeuralStore(store);
550
- return {
551
- success: true, _real: true, method,
552
- patternsCompressed: totalCompressed,
553
- note: 'Quantization metadata stored; original embeddings retained for search accuracy.',
554
- };
555
- }
556
- catch {
557
- return { success: false, error: 'Quantization requires memory-initializer. Run `memory init` first.' };
558
- }
559
- }
560
- if (method === 'prune') {
561
- // Prune the least-used fraction of patterns. targetReduction (0-1) is a percentile:
562
- // 0.5 removes the bottom 50% by usageCount, 0.8 removes the bottom 80%, etc.
563
- const counts = Object.values(store.patterns)
564
- .map(p => p.usageCount || 0)
565
- .sort((a, b) => a - b);
566
- const cutoffIdx = Math.floor(targetReduction * counts.length);
567
- const threshold = counts[cutoffIdx] ?? 0;
568
- const toRemove = [];
569
- for (const [id, pattern] of Object.entries(store.patterns)) {
570
- if ((pattern.usageCount || 0) < threshold)
571
- toRemove.push(id);
572
- }
573
- for (const id of toRemove)
574
- delete store.patterns[id];
575
- saveNeuralStore(store);
356
+ if (method === 'quantize' || method === 'distill') {
357
+ // Both quantize and distill map to compactPatterns (dedup by cosine similarity)
358
+ const threshold = method === 'quantize' ? 0.99 : 0.95;
359
+ const result = await compactPatterns(threshold);
576
360
  return {
577
361
  success: true, _real: true, method,
578
- threshold,
579
- patternsRemoved: toRemove.length,
580
- patternsBefore: beforeCount,
581
- patternsAfter: Object.keys(store.patterns).length,
362
+ patternsBefore: result.before,
363
+ patternsAfter: result.after,
364
+ patternsRemoved: result.removed,
365
+ note: method === 'quantize'
366
+ ? 'Near-duplicate patterns removed (cosine > 0.99).'
367
+ : `Similar patterns merged (cosine > ${threshold}).`,
582
368
  };
583
369
  }
584
- if (method === 'distill') {
585
- // Merge similar patterns by cosine similarity > 0.95
586
- const patternList = Object.entries(store.patterns);
587
- const merged = [];
588
- for (let i = 0; i < patternList.length; i++) {
589
- const [idA, a] = patternList[i];
590
- if (merged.includes(idA))
591
- continue;
592
- for (let j = i + 1; j < patternList.length; j++) {
593
- const [idB, b] = patternList[j];
594
- if (!a.embedding || !b.embedding || merged.includes(idB))
595
- continue;
596
- const sim = cosineSimilarity(a.embedding, b.embedding);
597
- if (sim > 0.95) {
598
- // Merge: average embeddings, keep higher usage count
599
- for (let k = 0; k < a.embedding.length; k++) {
600
- a.embedding[k] = (a.embedding[k] + (b.embedding[k] || 0)) / 2;
601
- }
602
- a.usageCount = Math.max(a.usageCount || 0, b.usageCount || 0);
603
- delete store.patterns[idB];
604
- merged.push(idB);
605
- }
606
- }
607
- }
608
- saveNeuralStore(store);
370
+ if (method === 'prune') {
371
+ // Prune maps to compactPatterns with a looser threshold
372
+ const targetReduction = input.targetSize || 0.5;
373
+ // Use a threshold proportional to target reduction (lower = more aggressive)
374
+ const threshold = 0.7 + (1 - targetReduction) * 0.25;
375
+ const result = await compactPatterns(threshold);
609
376
  return {
610
377
  success: true, _real: true, method,
611
- patternsMerged: merged.length,
612
- patternsBefore: beforeCount,
613
- patternsAfter: Object.keys(store.patterns).length,
378
+ patternsBefore: result.before,
379
+ patternsAfter: result.after,
380
+ patternsRemoved: result.removed,
614
381
  };
615
382
  }
616
383
  return { success: false, error: `Unknown method: ${method}. Use quantize, prune, or distill.` };
@@ -618,7 +385,7 @@ export const neuralTools = [
618
385
  },
619
386
  {
620
387
  name: 'neural_status',
621
- description: 'Get pattern store status',
388
+ description: 'Get pattern store status (pattern count, embedding dimensions, store health)',
622
389
  category: 'neural',
623
390
  inputSchema: {
624
391
  type: 'object',
@@ -628,38 +395,48 @@ export const neuralTools = [
628
395
  },
629
396
  },
630
397
  handler: async (input) => {
631
- const store = loadNeuralStore();
398
+ const { initializeIntelligence, getIntelligenceStats, getAllPatterns } = await import('../memory/intelligence.js');
399
+ await initializeIntelligence();
400
+ const stats = getIntelligenceStats();
401
+ const patterns = await getAllPatterns();
632
402
  if (input.modelId) {
633
- const MAX_MODEL_ID_LEN_STATUS = 256;
634
- const rawModelIdStatus = input.modelId;
635
- const modelId = typeof rawModelIdStatus === 'string' && rawModelIdStatus.length > MAX_MODEL_ID_LEN_STATUS
636
- ? rawModelIdStatus.slice(0, MAX_MODEL_ID_LEN_STATUS)
637
- : rawModelIdStatus;
638
- if (NEURAL_RESERVED_KEYS.has(modelId)) {
403
+ const modelId = sanitizeModelId(input.modelId);
404
+ if (modelId === null) {
639
405
  return { success: false, error: 'Invalid modelId' };
640
406
  }
641
- const model = Object.hasOwn(store.models, modelId) ? store.models[modelId] : undefined;
642
- if (!model) {
643
- return { success: false, error: 'Model not found' };
644
- }
645
- return { success: true, model };
407
+ // Filter patterns belonging to this model (by metadata or id prefix)
408
+ const modelPatterns = patterns.filter(p => p.id.startsWith(modelId) ||
409
+ (p.metadata?.modelId === modelId));
410
+ return {
411
+ success: true,
412
+ model: {
413
+ id: modelId,
414
+ patternsStored: modelPatterns.length,
415
+ status: modelPatterns.length > 0 ? 'ready' : 'empty',
416
+ },
417
+ };
418
+ }
419
+ const byType = {};
420
+ for (const p of patterns) {
421
+ byType[p.type] = (byType[p.type] || 0) + 1;
646
422
  }
647
- const models = Object.values(store.models);
648
- const patterns = Object.values(store.patterns);
649
423
  return {
650
- embeddingProvider: realEmbeddings ? embeddingServiceName : 'hash-based (deterministic)',
424
+ embeddingProvider: lastEmbeddingModel === 'unknown' ? 'not yet used' : lastEmbeddingModel,
425
+ sonaEnabled: stats.sonaEnabled,
651
426
  models: {
652
- total: models.length,
653
- ready: models.filter(m => m.status === 'ready').length,
654
- indexing: models.filter(m => m.status === 'indexing').length,
427
+ total: 0, // models concept removed; patterns are stored directly
428
+ ready: 0,
429
+ indexing: 0,
655
430
  },
656
431
  patterns: {
657
432
  total: patterns.length,
658
- byType: patterns.reduce((acc, p) => {
659
- acc[p.type] = (acc[p.type] || 0) + 1;
660
- return acc;
661
- }, {}),
662
- embeddingDims: patterns.length > 0 ? patterns[0].embedding.length : 384,
433
+ byType,
434
+ embeddingDims: patterns.length > 0 && patterns[0].embedding ? patterns[0].embedding.length : 384,
435
+ },
436
+ intelligence: {
437
+ reasoningBankSize: stats.reasoningBankSize,
438
+ patternsLearned: stats.patternsLearned,
439
+ trajectoriesRecorded: stats.trajectoriesRecorded,
663
440
  },
664
441
  };
665
442
  },
@@ -676,9 +453,10 @@ export const neuralTools = [
676
453
  },
677
454
  },
678
455
  handler: async (input) => {
679
- const store = loadNeuralStore();
680
456
  const target = input.target || 'balanced';
681
- const patterns = Object.values(store.patterns);
457
+ const { initializeIntelligence, compactPatterns, getAllPatterns } = await import('../memory/intelligence.js');
458
+ await initializeIntelligence();
459
+ const patterns = await getAllPatterns();
682
460
  if (patterns.length === 0) {
683
461
  return { success: false, error: 'No patterns to optimize. Train patterns first with neural_train.' };
684
462
  }
@@ -686,81 +464,39 @@ export const neuralTools = [
686
464
  const actions = [];
687
465
  const beforeCount = patterns.length;
688
466
  const dims = patterns[0]?.embedding?.length || 0;
689
- let patternsRemoved = 0;
690
- let patternsQuantized = 0;
691
- let duplicatesRemoved = 0;
692
- // speed / balanced: deduplicate identical or near-identical patterns
693
- if (target === 'speed' || target === 'balanced') {
694
- const seen = new Map(); // hash -> id
695
- for (const [id, p] of Object.entries(store.patterns)) {
696
- if (!p.embedding || p.embedding.length === 0)
697
- continue;
698
- // Quick hash: first 8 dims rounded
699
- const hash = p.embedding.slice(0, 8).map(v => v.toFixed(4)).join(',');
700
- if (seen.has(hash)) {
701
- // Verify with full cosine similarity
702
- const existingId = seen.get(hash);
703
- const existing = store.patterns[existingId];
704
- if (existing && cosineSimilarity(p.embedding, existing.embedding) > 0.99) {
705
- existing.usageCount = Math.max(existing.usageCount || 0, p.usageCount || 0);
706
- delete store.patterns[id];
707
- duplicatesRemoved++;
708
- }
709
- }
710
- else {
711
- seen.set(hash, id);
712
- }
713
- }
714
- if (duplicatesRemoved > 0)
715
- actions.push(`Removed ${duplicatesRemoved} near-duplicate patterns`);
467
+ // All optimization targets delegate to compactPatterns with varying thresholds
468
+ let threshold;
469
+ switch (target) {
470
+ case 'speed':
471
+ threshold = 0.99; // only near-exact duplicates
472
+ break;
473
+ case 'memory':
474
+ threshold = 0.90; // aggressive dedup
475
+ break;
476
+ case 'accuracy':
477
+ threshold = 0.98; // conservative
478
+ break;
479
+ case 'balanced':
480
+ default:
481
+ threshold = 0.95;
482
+ break;
716
483
  }
717
- // memory / balanced: quantize large embeddings
718
- if (target === 'memory' || target === 'balanced') {
719
- try {
720
- const { quantizeInt8, getQuantizationStats } = await import('../memory/memory-initializer.js');
721
- for (const p of Object.values(store.patterns)) {
722
- if (p.embedding && p.embedding.length > 0 && !p._quantized) {
723
- const stats = getQuantizationStats(p.embedding);
724
- const q = quantizeInt8(p.embedding);
725
- p._quantized = { scale: q.scale, zeroPoint: q.zeroPoint, compressionRatio: stats.compressionRatio };
726
- patternsQuantized++;
727
- }
728
- }
729
- if (patternsQuantized > 0)
730
- actions.push(`Quantized ${patternsQuantized} pattern embeddings (Int8, ~3.92x)`);
731
- }
732
- catch {
733
- actions.push('Quantization skipped (memory-initializer not available)');
734
- }
484
+ const result = await compactPatterns(threshold);
485
+ if (result.removed > 0) {
486
+ actions.push(`Removed ${result.removed} similar patterns (cosine > ${threshold})`);
735
487
  }
736
- // accuracy / balanced: prune low-usage, zero-embedding patterns
737
- if (target === 'accuracy' || target === 'balanced') {
738
- for (const [id, p] of Object.entries(store.patterns)) {
739
- if (!p.embedding || p.embedding.length === 0) {
740
- delete store.patterns[id];
741
- patternsRemoved++;
742
- continue;
743
- }
744
- // Remove patterns with all-zero embeddings (no useful signal)
745
- const norm = p.embedding.reduce((s, v) => s + v * v, 0);
746
- if (norm < 1e-10) {
747
- delete store.patterns[id];
748
- patternsRemoved++;
749
- }
750
- }
751
- if (patternsRemoved > 0)
752
- actions.push(`Pruned ${patternsRemoved} empty/zero-signal patterns`);
488
+ else {
489
+ actions.push('No duplicate patterns found');
753
490
  }
754
- saveNeuralStore(store);
755
491
  const elapsed = Math.round(performance.now() - startTime);
756
492
  return {
757
493
  success: true, _real: true, target,
758
494
  actions,
759
- patternsBefore: beforeCount,
760
- patternsAfter: Object.keys(store.patterns).length,
761
- duplicatesRemoved,
762
- patternsQuantized,
763
- patternsRemoved,
495
+ patternsBefore: result.before,
496
+ patternsAfter: result.after,
497
+ duplicatesRemoved: result.removed,
498
+ patternsQuantized: 0,
499
+ patternsRemoved: result.removed,
764
500
  embeddingDims: dims,
765
501
  elapsedMs: elapsed,
766
502
  };