@aigentic/claude-flow 3.7.0-alpha.69

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 (807) hide show
  1. package/.claude/agents/MIGRATION_SUMMARY.md +222 -0
  2. package/.claude/agents/analysis/analyze-code-quality.md +58 -0
  3. package/.claude/agents/analysis/code-analyzer.md +189 -0
  4. package/.claude/agents/analysis/code-review/analyze-code-quality.md +58 -0
  5. package/.claude/agents/architecture/arch-system-design.md +157 -0
  6. package/.claude/agents/architecture/system-design/arch-system-design.md +36 -0
  7. package/.claude/agents/base-template-generator.md +41 -0
  8. package/.claude/agents/browser/browser-agent.yaml +182 -0
  9. package/.claude/agents/consensus/byzantine-coordinator.md +43 -0
  10. package/.claude/agents/consensus/crdt-synchronizer.md +977 -0
  11. package/.claude/agents/consensus/gossip-coordinator.md +43 -0
  12. package/.claude/agents/consensus/performance-benchmarker.md +831 -0
  13. package/.claude/agents/consensus/quorum-manager.md +803 -0
  14. package/.claude/agents/consensus/raft-manager.md +43 -0
  15. package/.claude/agents/consensus/security-manager.md +602 -0
  16. package/.claude/agents/core/coder.md +255 -0
  17. package/.claude/agents/core/planner.md +152 -0
  18. package/.claude/agents/core/researcher.md +174 -0
  19. package/.claude/agents/core/reviewer.md +309 -0
  20. package/.claude/agents/core/tester.md +300 -0
  21. package/.claude/agents/custom/test-long-runner.md +43 -0
  22. package/.claude/agents/data/data-ml-model.md +445 -0
  23. package/.claude/agents/data/ml/data-ml-model.md +76 -0
  24. package/.claude/agents/database-specialist.md +9 -0
  25. package/.claude/agents/development/backend/dev-backend-api.md +29 -0
  26. package/.claude/agents/development/dev-backend-api.md +178 -0
  27. package/.claude/agents/devops/ci-cd/ops-cicd-github.md +52 -0
  28. package/.claude/agents/devops/ops-cicd-github.md +165 -0
  29. package/.claude/agents/documentation/api-docs/docs-api-openapi.md +63 -0
  30. package/.claude/agents/documentation/docs-api-openapi.md +355 -0
  31. package/.claude/agents/dual-mode/codex-coordinator.md +206 -0
  32. package/.claude/agents/dual-mode/codex-worker.md +190 -0
  33. package/.claude/agents/dual-mode/dual-orchestrator.md +253 -0
  34. package/.claude/agents/flow-nexus/app-store.md +88 -0
  35. package/.claude/agents/flow-nexus/authentication.md +69 -0
  36. package/.claude/agents/flow-nexus/challenges.md +81 -0
  37. package/.claude/agents/flow-nexus/neural-network.md +88 -0
  38. package/.claude/agents/flow-nexus/payments.md +83 -0
  39. package/.claude/agents/flow-nexus/sandbox.md +76 -0
  40. package/.claude/agents/flow-nexus/swarm.md +76 -0
  41. package/.claude/agents/flow-nexus/user-tools.md +96 -0
  42. package/.claude/agents/flow-nexus/workflow.md +84 -0
  43. package/.claude/agents/github/code-review-swarm.md +521 -0
  44. package/.claude/agents/github/github-modes.md +154 -0
  45. package/.claude/agents/github/issue-tracker.md +299 -0
  46. package/.claude/agents/github/multi-repo-swarm.md +525 -0
  47. package/.claude/agents/github/pr-manager.md +163 -0
  48. package/.claude/agents/github/project-board-sync.md +478 -0
  49. package/.claude/agents/github/release-manager.md +336 -0
  50. package/.claude/agents/github/release-swarm.md +551 -0
  51. package/.claude/agents/github/repo-architect.md +365 -0
  52. package/.claude/agents/github/swarm-issue.md +548 -0
  53. package/.claude/agents/github/swarm-pr.md +399 -0
  54. package/.claude/agents/github/sync-coordinator.md +423 -0
  55. package/.claude/agents/github/workflow-automation.md +605 -0
  56. package/.claude/agents/goal/agent.md +817 -0
  57. package/.claude/agents/goal/code-goal-planner.md +445 -0
  58. package/.claude/agents/goal/goal-planner.md +168 -0
  59. package/.claude/agents/hive-mind/collective-intelligence-coordinator.md +129 -0
  60. package/.claude/agents/hive-mind/queen-coordinator.md +202 -0
  61. package/.claude/agents/hive-mind/scout-explorer.md +241 -0
  62. package/.claude/agents/hive-mind/swarm-memory-manager.md +192 -0
  63. package/.claude/agents/hive-mind/worker-specialist.md +216 -0
  64. package/.claude/agents/neural/safla-neural.md +74 -0
  65. package/.claude/agents/optimization/benchmark-suite.md +663 -0
  66. package/.claude/agents/optimization/load-balancer.md +429 -0
  67. package/.claude/agents/optimization/performance-monitor.md +670 -0
  68. package/.claude/agents/optimization/resource-allocator.md +672 -0
  69. package/.claude/agents/optimization/topology-optimizer.md +806 -0
  70. package/.claude/agents/payments/agentic-payments.md +126 -0
  71. package/.claude/agents/project-coordinator.md +8 -0
  72. package/.claude/agents/python-specialist.md +9 -0
  73. package/.claude/agents/reasoning/agent.md +817 -0
  74. package/.claude/agents/reasoning/goal-planner.md +73 -0
  75. package/.claude/agents/security-auditor.md +9 -0
  76. package/.claude/agents/sona/sona-learning-optimizer.md +65 -0
  77. package/.claude/agents/sparc/architecture.md +453 -0
  78. package/.claude/agents/sparc/pseudocode.md +299 -0
  79. package/.claude/agents/sparc/refinement.md +504 -0
  80. package/.claude/agents/sparc/specification.md +258 -0
  81. package/.claude/agents/specialized/mobile/spec-mobile-react-native.md +88 -0
  82. package/.claude/agents/specialized/spec-mobile-react-native.md +227 -0
  83. package/.claude/agents/sublinear/consensus-coordinator.md +338 -0
  84. package/.claude/agents/sublinear/matrix-optimizer.md +185 -0
  85. package/.claude/agents/sublinear/pagerank-analyzer.md +299 -0
  86. package/.claude/agents/sublinear/performance-optimizer.md +368 -0
  87. package/.claude/agents/sublinear/trading-predictor.md +246 -0
  88. package/.claude/agents/swarm/adaptive-coordinator.md +364 -0
  89. package/.claude/agents/swarm/hierarchical-coordinator.md +300 -0
  90. package/.claude/agents/swarm/mesh-coordinator.md +363 -0
  91. package/.claude/agents/templates/automation-smart-agent.md +185 -0
  92. package/.claude/agents/templates/base-template-generator.md +289 -0
  93. package/.claude/agents/templates/coordinator-swarm-init.md +83 -0
  94. package/.claude/agents/templates/github-pr-manager.md +155 -0
  95. package/.claude/agents/templates/implementer-sparc-coder.md +243 -0
  96. package/.claude/agents/templates/memory-coordinator.md +163 -0
  97. package/.claude/agents/templates/migration-plan.md +724 -0
  98. package/.claude/agents/templates/orchestrator-task.md +120 -0
  99. package/.claude/agents/templates/performance-analyzer.md +179 -0
  100. package/.claude/agents/templates/sparc-coordinator.md +163 -0
  101. package/.claude/agents/testing/production-validator.md +373 -0
  102. package/.claude/agents/testing/tdd-london-swarm.md +222 -0
  103. package/.claude/agents/testing/unit/tdd-london-swarm.md +222 -0
  104. package/.claude/agents/testing/validation/production-validator.md +373 -0
  105. package/.claude/agents/typescript-specialist.md +9 -0
  106. package/.claude/agents/v3/adr-architect.md +184 -0
  107. package/.claude/agents/v3/aidefence-guardian.md +282 -0
  108. package/.claude/agents/v3/claims-authorizer.md +208 -0
  109. package/.claude/agents/v3/collective-intelligence-coordinator.md +993 -0
  110. package/.claude/agents/v3/database-specialist.md +9 -0
  111. package/.claude/agents/v3/ddd-domain-expert.md +220 -0
  112. package/.claude/agents/v3/injection-analyst.md +236 -0
  113. package/.claude/agents/v3/memory-specialist.md +995 -0
  114. package/.claude/agents/v3/performance-engineer.md +1233 -0
  115. package/.claude/agents/v3/pii-detector.md +151 -0
  116. package/.claude/agents/v3/project-coordinator.md +8 -0
  117. package/.claude/agents/v3/python-specialist.md +9 -0
  118. package/.claude/agents/v3/reasoningbank-learner.md +213 -0
  119. package/.claude/agents/v3/security-architect-aidefence.md +410 -0
  120. package/.claude/agents/v3/security-architect.md +867 -0
  121. package/.claude/agents/v3/security-auditor.md +771 -0
  122. package/.claude/agents/v3/sparc-orchestrator.md +182 -0
  123. package/.claude/agents/v3/swarm-memory-manager.md +157 -0
  124. package/.claude/agents/v3/test-architect.md +9 -0
  125. package/.claude/agents/v3/typescript-specialist.md +9 -0
  126. package/.claude/agents/v3/v3-integration-architect.md +312 -0
  127. package/.claude/agents/v3/v3-memory-specialist.md +281 -0
  128. package/.claude/agents/v3/v3-performance-engineer.md +363 -0
  129. package/.claude/agents/v3/v3-queen-coordinator.md +63 -0
  130. package/.claude/agents/v3/v3-security-architect.md +140 -0
  131. package/.claude/checkpoints/1767754460.json +8 -0
  132. package/.claude/commands/agents/README.md +10 -0
  133. package/.claude/commands/agents/agent-capabilities.md +21 -0
  134. package/.claude/commands/agents/agent-coordination.md +28 -0
  135. package/.claude/commands/agents/agent-spawning.md +28 -0
  136. package/.claude/commands/agents/agent-types.md +26 -0
  137. package/.claude/commands/analysis/COMMAND_COMPLIANCE_REPORT.md +54 -0
  138. package/.claude/commands/analysis/README.md +9 -0
  139. package/.claude/commands/analysis/bottleneck-detect.md +162 -0
  140. package/.claude/commands/analysis/performance-bottlenecks.md +59 -0
  141. package/.claude/commands/analysis/performance-report.md +25 -0
  142. package/.claude/commands/analysis/token-efficiency.md +45 -0
  143. package/.claude/commands/analysis/token-usage.md +25 -0
  144. package/.claude/commands/automation/README.md +9 -0
  145. package/.claude/commands/automation/auto-agent.md +122 -0
  146. package/.claude/commands/automation/self-healing.md +106 -0
  147. package/.claude/commands/automation/session-memory.md +90 -0
  148. package/.claude/commands/automation/smart-agents.md +73 -0
  149. package/.claude/commands/automation/smart-spawn.md +25 -0
  150. package/.claude/commands/automation/workflow-select.md +25 -0
  151. package/.claude/commands/claude-flow-help.md +103 -0
  152. package/.claude/commands/claude-flow-memory.md +107 -0
  153. package/.claude/commands/claude-flow-swarm.md +205 -0
  154. package/.claude/commands/coordination/README.md +9 -0
  155. package/.claude/commands/coordination/agent-spawn.md +25 -0
  156. package/.claude/commands/coordination/init.md +44 -0
  157. package/.claude/commands/coordination/orchestrate.md +43 -0
  158. package/.claude/commands/coordination/spawn.md +45 -0
  159. package/.claude/commands/coordination/swarm-init.md +85 -0
  160. package/.claude/commands/coordination/task-orchestrate.md +25 -0
  161. package/.claude/commands/flow-nexus/app-store.md +124 -0
  162. package/.claude/commands/flow-nexus/challenges.md +120 -0
  163. package/.claude/commands/flow-nexus/login-registration.md +65 -0
  164. package/.claude/commands/flow-nexus/neural-network.md +134 -0
  165. package/.claude/commands/flow-nexus/payments.md +116 -0
  166. package/.claude/commands/flow-nexus/sandbox.md +83 -0
  167. package/.claude/commands/flow-nexus/swarm.md +87 -0
  168. package/.claude/commands/flow-nexus/user-tools.md +152 -0
  169. package/.claude/commands/flow-nexus/workflow.md +115 -0
  170. package/.claude/commands/github/README.md +11 -0
  171. package/.claude/commands/github/code-review-swarm.md +514 -0
  172. package/.claude/commands/github/code-review.md +25 -0
  173. package/.claude/commands/github/github-modes.md +147 -0
  174. package/.claude/commands/github/github-swarm.md +121 -0
  175. package/.claude/commands/github/issue-tracker.md +292 -0
  176. package/.claude/commands/github/issue-triage.md +25 -0
  177. package/.claude/commands/github/multi-repo-swarm.md +519 -0
  178. package/.claude/commands/github/pr-enhance.md +26 -0
  179. package/.claude/commands/github/pr-manager.md +170 -0
  180. package/.claude/commands/github/project-board-sync.md +471 -0
  181. package/.claude/commands/github/release-manager.md +338 -0
  182. package/.claude/commands/github/release-swarm.md +544 -0
  183. package/.claude/commands/github/repo-analyze.md +25 -0
  184. package/.claude/commands/github/repo-architect.md +367 -0
  185. package/.claude/commands/github/swarm-issue.md +482 -0
  186. package/.claude/commands/github/swarm-pr.md +285 -0
  187. package/.claude/commands/github/sync-coordinator.md +301 -0
  188. package/.claude/commands/github/workflow-automation.md +442 -0
  189. package/.claude/commands/hive-mind/README.md +17 -0
  190. package/.claude/commands/hive-mind/hive-mind-consensus.md +8 -0
  191. package/.claude/commands/hive-mind/hive-mind-init.md +18 -0
  192. package/.claude/commands/hive-mind/hive-mind-memory.md +8 -0
  193. package/.claude/commands/hive-mind/hive-mind-metrics.md +8 -0
  194. package/.claude/commands/hive-mind/hive-mind-resume.md +8 -0
  195. package/.claude/commands/hive-mind/hive-mind-sessions.md +8 -0
  196. package/.claude/commands/hive-mind/hive-mind-spawn.md +21 -0
  197. package/.claude/commands/hive-mind/hive-mind-status.md +8 -0
  198. package/.claude/commands/hive-mind/hive-mind-stop.md +8 -0
  199. package/.claude/commands/hive-mind/hive-mind-wizard.md +8 -0
  200. package/.claude/commands/hive-mind/hive-mind.md +27 -0
  201. package/.claude/commands/hooks/README.md +11 -0
  202. package/.claude/commands/hooks/overview.md +58 -0
  203. package/.claude/commands/hooks/post-edit.md +117 -0
  204. package/.claude/commands/hooks/post-task.md +112 -0
  205. package/.claude/commands/hooks/pre-edit.md +113 -0
  206. package/.claude/commands/hooks/pre-task.md +111 -0
  207. package/.claude/commands/hooks/session-end.md +118 -0
  208. package/.claude/commands/hooks/setup.md +103 -0
  209. package/.claude/commands/memory/README.md +9 -0
  210. package/.claude/commands/memory/memory-persist.md +25 -0
  211. package/.claude/commands/memory/memory-search.md +25 -0
  212. package/.claude/commands/memory/memory-usage.md +25 -0
  213. package/.claude/commands/memory/neural.md +47 -0
  214. package/.claude/commands/monitoring/README.md +9 -0
  215. package/.claude/commands/monitoring/agent-metrics.md +25 -0
  216. package/.claude/commands/monitoring/agents.md +44 -0
  217. package/.claude/commands/monitoring/real-time-view.md +25 -0
  218. package/.claude/commands/monitoring/status.md +46 -0
  219. package/.claude/commands/monitoring/swarm-monitor.md +25 -0
  220. package/.claude/commands/optimization/README.md +9 -0
  221. package/.claude/commands/optimization/auto-topology.md +62 -0
  222. package/.claude/commands/optimization/cache-manage.md +25 -0
  223. package/.claude/commands/optimization/parallel-execute.md +25 -0
  224. package/.claude/commands/optimization/parallel-execution.md +50 -0
  225. package/.claude/commands/optimization/topology-optimize.md +25 -0
  226. package/.claude/commands/pair/README.md +261 -0
  227. package/.claude/commands/pair/commands.md +546 -0
  228. package/.claude/commands/pair/config.md +510 -0
  229. package/.claude/commands/pair/examples.md +512 -0
  230. package/.claude/commands/pair/modes.md +348 -0
  231. package/.claude/commands/pair/session.md +407 -0
  232. package/.claude/commands/pair/start.md +209 -0
  233. package/.claude/commands/sparc/analyzer.md +52 -0
  234. package/.claude/commands/sparc/architect.md +53 -0
  235. package/.claude/commands/sparc/ask.md +97 -0
  236. package/.claude/commands/sparc/batch-executor.md +54 -0
  237. package/.claude/commands/sparc/code.md +89 -0
  238. package/.claude/commands/sparc/coder.md +54 -0
  239. package/.claude/commands/sparc/debug.md +83 -0
  240. package/.claude/commands/sparc/debugger.md +54 -0
  241. package/.claude/commands/sparc/designer.md +53 -0
  242. package/.claude/commands/sparc/devops.md +109 -0
  243. package/.claude/commands/sparc/docs-writer.md +80 -0
  244. package/.claude/commands/sparc/documenter.md +54 -0
  245. package/.claude/commands/sparc/innovator.md +54 -0
  246. package/.claude/commands/sparc/integration.md +83 -0
  247. package/.claude/commands/sparc/mcp.md +117 -0
  248. package/.claude/commands/sparc/memory-manager.md +54 -0
  249. package/.claude/commands/sparc/optimizer.md +54 -0
  250. package/.claude/commands/sparc/orchestrator.md +132 -0
  251. package/.claude/commands/sparc/post-deployment-monitoring-mode.md +83 -0
  252. package/.claude/commands/sparc/refinement-optimization-mode.md +83 -0
  253. package/.claude/commands/sparc/researcher.md +54 -0
  254. package/.claude/commands/sparc/reviewer.md +54 -0
  255. package/.claude/commands/sparc/security-review.md +80 -0
  256. package/.claude/commands/sparc/sparc-modes.md +174 -0
  257. package/.claude/commands/sparc/sparc.md +111 -0
  258. package/.claude/commands/sparc/spec-pseudocode.md +80 -0
  259. package/.claude/commands/sparc/supabase-admin.md +348 -0
  260. package/.claude/commands/sparc/swarm-coordinator.md +54 -0
  261. package/.claude/commands/sparc/tdd.md +54 -0
  262. package/.claude/commands/sparc/tester.md +54 -0
  263. package/.claude/commands/sparc/tutorial.md +79 -0
  264. package/.claude/commands/sparc/workflow-manager.md +54 -0
  265. package/.claude/commands/sparc.md +166 -0
  266. package/.claude/commands/stream-chain/pipeline.md +121 -0
  267. package/.claude/commands/stream-chain/run.md +70 -0
  268. package/.claude/commands/swarm/README.md +15 -0
  269. package/.claude/commands/swarm/analysis.md +95 -0
  270. package/.claude/commands/swarm/development.md +96 -0
  271. package/.claude/commands/swarm/examples.md +168 -0
  272. package/.claude/commands/swarm/maintenance.md +102 -0
  273. package/.claude/commands/swarm/optimization.md +117 -0
  274. package/.claude/commands/swarm/research.md +136 -0
  275. package/.claude/commands/swarm/swarm-analysis.md +8 -0
  276. package/.claude/commands/swarm/swarm-background.md +8 -0
  277. package/.claude/commands/swarm/swarm-init.md +19 -0
  278. package/.claude/commands/swarm/swarm-modes.md +8 -0
  279. package/.claude/commands/swarm/swarm-monitor.md +8 -0
  280. package/.claude/commands/swarm/swarm-spawn.md +19 -0
  281. package/.claude/commands/swarm/swarm-status.md +8 -0
  282. package/.claude/commands/swarm/swarm-strategies.md +8 -0
  283. package/.claude/commands/swarm/swarm.md +27 -0
  284. package/.claude/commands/swarm/testing.md +131 -0
  285. package/.claude/commands/training/README.md +9 -0
  286. package/.claude/commands/training/model-update.md +25 -0
  287. package/.claude/commands/training/neural-patterns.md +74 -0
  288. package/.claude/commands/training/neural-train.md +25 -0
  289. package/.claude/commands/training/pattern-learn.md +25 -0
  290. package/.claude/commands/training/specialization.md +63 -0
  291. package/.claude/commands/truth/start.md +143 -0
  292. package/.claude/commands/verify/check.md +50 -0
  293. package/.claude/commands/verify/start.md +128 -0
  294. package/.claude/commands/workflows/README.md +9 -0
  295. package/.claude/commands/workflows/development.md +78 -0
  296. package/.claude/commands/workflows/research.md +63 -0
  297. package/.claude/commands/workflows/workflow-create.md +25 -0
  298. package/.claude/commands/workflows/workflow-execute.md +25 -0
  299. package/.claude/commands/workflows/workflow-export.md +25 -0
  300. package/.claude/config/v3-dependency-optimization.json +266 -0
  301. package/.claude/config/v3-performance-targets.json +251 -0
  302. package/.claude/helpers/README.md +97 -0
  303. package/.claude/helpers/adr-compliance.sh +186 -0
  304. package/.claude/helpers/aggressive-microcompact.mjs +36 -0
  305. package/.claude/helpers/auto-commit.sh +178 -0
  306. package/.claude/helpers/auto-memory-hook.mjs +564 -0
  307. package/.claude/helpers/checkpoint-manager.sh +251 -0
  308. package/.claude/helpers/context-persistence-hook.mjs +1979 -0
  309. package/.claude/helpers/daemon-manager.sh +252 -0
  310. package/.claude/helpers/ddd-tracker.sh +144 -0
  311. package/.claude/helpers/github-safe.js +106 -0
  312. package/.claude/helpers/github-setup.sh +28 -0
  313. package/.claude/helpers/guidance-hook.sh +13 -0
  314. package/.claude/helpers/guidance-hooks.sh +102 -0
  315. package/.claude/helpers/health-monitor.sh +108 -0
  316. package/.claude/helpers/hook-handler.cjs +269 -0
  317. package/.claude/helpers/intelligence.cjs +230 -0
  318. package/.claude/helpers/learning-hooks.sh +329 -0
  319. package/.claude/helpers/learning-optimizer.sh +127 -0
  320. package/.claude/helpers/learning-service.mjs +1144 -0
  321. package/.claude/helpers/memory.cjs +84 -0
  322. package/.claude/helpers/memory.js +83 -0
  323. package/.claude/helpers/metrics-db.mjs +488 -0
  324. package/.claude/helpers/patch-aggressive-prune.mjs +184 -0
  325. package/.claude/helpers/pattern-consolidator.sh +86 -0
  326. package/.claude/helpers/perf-worker.sh +160 -0
  327. package/.claude/helpers/post-commit +16 -0
  328. package/.claude/helpers/pre-commit +26 -0
  329. package/.claude/helpers/quick-start.sh +19 -0
  330. package/.claude/helpers/router.cjs +62 -0
  331. package/.claude/helpers/router.js +66 -0
  332. package/.claude/helpers/security-scanner.sh +127 -0
  333. package/.claude/helpers/session.cjs +125 -0
  334. package/.claude/helpers/session.js +135 -0
  335. package/.claude/helpers/setup-mcp.sh +18 -0
  336. package/.claude/helpers/standard-checkpoint-hooks.sh +189 -0
  337. package/.claude/helpers/statusline-hook.sh +21 -0
  338. package/.claude/helpers/statusline.cjs +878 -0
  339. package/.claude/helpers/statusline.js +352 -0
  340. package/.claude/helpers/swarm-comms.sh +353 -0
  341. package/.claude/helpers/swarm-hooks.sh +761 -0
  342. package/.claude/helpers/swarm-monitor.sh +211 -0
  343. package/.claude/helpers/sync-v3-metrics.sh +245 -0
  344. package/.claude/helpers/update-v3-progress.sh +166 -0
  345. package/.claude/helpers/v3-quick-status.sh +58 -0
  346. package/.claude/helpers/v3.sh +111 -0
  347. package/.claude/helpers/validate-v3-config.sh +216 -0
  348. package/.claude/helpers/worker-manager.sh +170 -0
  349. package/.claude/mcp.json +13 -0
  350. package/.claude/scheduled_tasks.lock +1 -0
  351. package/.claude/settings.json +285 -0
  352. package/.claude/settings.json.bak +526 -0
  353. package/.claude/skills/agentdb-advanced/SKILL.md +550 -0
  354. package/.claude/skills/agentdb-learning/SKILL.md +545 -0
  355. package/.claude/skills/agentdb-memory-patterns/SKILL.md +339 -0
  356. package/.claude/skills/agentdb-optimization/SKILL.md +509 -0
  357. package/.claude/skills/agentdb-vector-search/SKILL.md +339 -0
  358. package/.claude/skills/agentic-jujutsu/SKILL.md +645 -0
  359. package/.claude/skills/browser/SKILL.md +204 -0
  360. package/.claude/skills/dual-mode/README.md +71 -0
  361. package/.claude/skills/dual-mode/dual-collect.md +103 -0
  362. package/.claude/skills/dual-mode/dual-coordinate.md +85 -0
  363. package/.claude/skills/dual-mode/dual-spawn.md +81 -0
  364. package/.claude/skills/flow-nexus-neural/SKILL.md +727 -0
  365. package/.claude/skills/flow-nexus-platform/SKILL.md +1154 -0
  366. package/.claude/skills/flow-nexus-swarm/SKILL.md +604 -0
  367. package/.claude/skills/github-code-review/SKILL.md +1125 -0
  368. package/.claude/skills/github-multi-repo/SKILL.md +862 -0
  369. package/.claude/skills/github-project-management/SKILL.md +1263 -0
  370. package/.claude/skills/github-release-management/SKILL.md +1064 -0
  371. package/.claude/skills/github-workflow-automation/SKILL.md +1047 -0
  372. package/.claude/skills/hive-mind-advanced/SKILL.md +709 -0
  373. package/.claude/skills/hooks-automation/SKILL.md +1201 -0
  374. package/.claude/skills/pair-programming/SKILL.md +1202 -0
  375. package/.claude/skills/performance-analysis/SKILL.md +560 -0
  376. package/.claude/skills/reasoningbank-agentdb/SKILL.md +446 -0
  377. package/.claude/skills/reasoningbank-intelligence/SKILL.md +201 -0
  378. package/.claude/skills/skill-builder/SKILL.md +910 -0
  379. package/.claude/skills/sparc-methodology/SKILL.md +1106 -0
  380. package/.claude/skills/stream-chain/SKILL.md +560 -0
  381. package/.claude/skills/swarm-advanced/SKILL.md +970 -0
  382. package/.claude/skills/swarm-orchestration/SKILL.md +179 -0
  383. package/.claude/skills/v3-cli-modernization/SKILL.md +872 -0
  384. package/.claude/skills/v3-core-implementation/SKILL.md +797 -0
  385. package/.claude/skills/v3-ddd-architecture/SKILL.md +442 -0
  386. package/.claude/skills/v3-integration-deep/SKILL.md +241 -0
  387. package/.claude/skills/v3-mcp-optimization/SKILL.md +777 -0
  388. package/.claude/skills/v3-memory-unification/SKILL.md +174 -0
  389. package/.claude/skills/v3-performance-optimization/SKILL.md +390 -0
  390. package/.claude/skills/v3-security-overhaul/SKILL.md +82 -0
  391. package/.claude/skills/v3-swarm-coordination/SKILL.md +340 -0
  392. package/.claude/skills/verification-quality/SKILL.md +691 -0
  393. package/.claude/skills/worker-benchmarks/SKILL.md +129 -0
  394. package/.claude/skills/worker-integration/SKILL.md +147 -0
  395. package/.claude/statusline-command.sh +176 -0
  396. package/.claude/statusline.mjs +109 -0
  397. package/.claude/statusline.sh +431 -0
  398. package/.claude-plugin/README.md +720 -0
  399. package/.claude-plugin/docs/INSTALLATION.md +261 -0
  400. package/.claude-plugin/docs/PLUGIN_SUMMARY.md +361 -0
  401. package/.claude-plugin/docs/QUICKSTART.md +361 -0
  402. package/.claude-plugin/docs/STRUCTURE.md +128 -0
  403. package/.claude-plugin/hooks/hooks.json +75 -0
  404. package/.claude-plugin/marketplace.json +170 -0
  405. package/.claude-plugin/plugin.json +71 -0
  406. package/.claude-plugin/scripts/install.sh +234 -0
  407. package/.claude-plugin/scripts/ruflo-hook.sh +33 -0
  408. package/.claude-plugin/scripts/uninstall.sh +36 -0
  409. package/.claude-plugin/scripts/verify.sh +108 -0
  410. package/LICENSE +21 -0
  411. package/README.md +410 -0
  412. package/bin/cli.js +11 -0
  413. package/bin/npx-repair.js +7 -0
  414. package/bin/npx-safe-launch.js +9 -0
  415. package/package.json +159 -0
  416. package/v3/@claude-flow/cli/README.md +410 -0
  417. package/v3/@claude-flow/cli/bin/cli.js +233 -0
  418. package/v3/@claude-flow/cli/bin/mcp-server.js +224 -0
  419. package/v3/@claude-flow/cli/bin/preinstall.cjs +2 -0
  420. package/v3/@claude-flow/cli/dist/src/appliance/gguf-engine.d.ts +91 -0
  421. package/v3/@claude-flow/cli/dist/src/appliance/gguf-engine.js +425 -0
  422. package/v3/@claude-flow/cli/dist/src/appliance/ruvllm-bridge.d.ts +102 -0
  423. package/v3/@claude-flow/cli/dist/src/appliance/ruvllm-bridge.js +292 -0
  424. package/v3/@claude-flow/cli/dist/src/appliance/rvfa-builder.d.ts +44 -0
  425. package/v3/@claude-flow/cli/dist/src/appliance/rvfa-builder.js +329 -0
  426. package/v3/@claude-flow/cli/dist/src/appliance/rvfa-distribution.d.ts +97 -0
  427. package/v3/@claude-flow/cli/dist/src/appliance/rvfa-distribution.js +370 -0
  428. package/v3/@claude-flow/cli/dist/src/appliance/rvfa-format.d.ts +111 -0
  429. package/v3/@claude-flow/cli/dist/src/appliance/rvfa-format.js +393 -0
  430. package/v3/@claude-flow/cli/dist/src/appliance/rvfa-runner.d.ts +69 -0
  431. package/v3/@claude-flow/cli/dist/src/appliance/rvfa-runner.js +237 -0
  432. package/v3/@claude-flow/cli/dist/src/appliance/rvfa-signing.d.ts +123 -0
  433. package/v3/@claude-flow/cli/dist/src/appliance/rvfa-signing.js +347 -0
  434. package/v3/@claude-flow/cli/dist/src/autopilot-state.d.ts +77 -0
  435. package/v3/@claude-flow/cli/dist/src/autopilot-state.js +271 -0
  436. package/v3/@claude-flow/cli/dist/src/benchmarks/pretrain/index.d.ts +58 -0
  437. package/v3/@claude-flow/cli/dist/src/benchmarks/pretrain/index.js +404 -0
  438. package/v3/@claude-flow/cli/dist/src/commands/agent-wasm.d.ts +14 -0
  439. package/v3/@claude-flow/cli/dist/src/commands/agent-wasm.js +333 -0
  440. package/v3/@claude-flow/cli/dist/src/commands/agent.d.ts +8 -0
  441. package/v3/@claude-flow/cli/dist/src/commands/agent.js +927 -0
  442. package/v3/@claude-flow/cli/dist/src/commands/analyze.d.ts +19 -0
  443. package/v3/@claude-flow/cli/dist/src/commands/analyze.js +2048 -0
  444. package/v3/@claude-flow/cli/dist/src/commands/appliance-advanced.d.ts +9 -0
  445. package/v3/@claude-flow/cli/dist/src/commands/appliance-advanced.js +215 -0
  446. package/v3/@claude-flow/cli/dist/src/commands/appliance.d.ts +8 -0
  447. package/v3/@claude-flow/cli/dist/src/commands/appliance.js +404 -0
  448. package/v3/@claude-flow/cli/dist/src/commands/autopilot.d.ts +15 -0
  449. package/v3/@claude-flow/cli/dist/src/commands/autopilot.js +362 -0
  450. package/v3/@claude-flow/cli/dist/src/commands/benchmark.d.ts +10 -0
  451. package/v3/@claude-flow/cli/dist/src/commands/benchmark.js +460 -0
  452. package/v3/@claude-flow/cli/dist/src/commands/claims.d.ts +10 -0
  453. package/v3/@claude-flow/cli/dist/src/commands/claims.js +620 -0
  454. package/v3/@claude-flow/cli/dist/src/commands/cleanup.d.ts +13 -0
  455. package/v3/@claude-flow/cli/dist/src/commands/cleanup.js +250 -0
  456. package/v3/@claude-flow/cli/dist/src/commands/completions.d.ts +10 -0
  457. package/v3/@claude-flow/cli/dist/src/commands/completions.js +539 -0
  458. package/v3/@claude-flow/cli/dist/src/commands/config.d.ts +8 -0
  459. package/v3/@claude-flow/cli/dist/src/commands/config.js +430 -0
  460. package/v3/@claude-flow/cli/dist/src/commands/daemon.d.ts +28 -0
  461. package/v3/@claude-flow/cli/dist/src/commands/daemon.js +1093 -0
  462. package/v3/@claude-flow/cli/dist/src/commands/deployment.d.ts +10 -0
  463. package/v3/@claude-flow/cli/dist/src/commands/deployment.js +672 -0
  464. package/v3/@claude-flow/cli/dist/src/commands/doctor.d.ts +10 -0
  465. package/v3/@claude-flow/cli/dist/src/commands/doctor.js +885 -0
  466. package/v3/@claude-flow/cli/dist/src/commands/embeddings.d.ts +18 -0
  467. package/v3/@claude-flow/cli/dist/src/commands/embeddings.js +1623 -0
  468. package/v3/@claude-flow/cli/dist/src/commands/guidance.d.ts +8 -0
  469. package/v3/@claude-flow/cli/dist/src/commands/guidance.js +556 -0
  470. package/v3/@claude-flow/cli/dist/src/commands/hive-mind.d.ts +11 -0
  471. package/v3/@claude-flow/cli/dist/src/commands/hive-mind.js +1297 -0
  472. package/v3/@claude-flow/cli/dist/src/commands/hooks.d.ts +8 -0
  473. package/v3/@claude-flow/cli/dist/src/commands/hooks.js +4499 -0
  474. package/v3/@claude-flow/cli/dist/src/commands/index.d.ts +118 -0
  475. package/v3/@claude-flow/cli/dist/src/commands/index.js +344 -0
  476. package/v3/@claude-flow/cli/dist/src/commands/init.d.ts +8 -0
  477. package/v3/@claude-flow/cli/dist/src/commands/init.js +997 -0
  478. package/v3/@claude-flow/cli/dist/src/commands/issues.d.ts +21 -0
  479. package/v3/@claude-flow/cli/dist/src/commands/issues.js +567 -0
  480. package/v3/@claude-flow/cli/dist/src/commands/mcp.d.ts +11 -0
  481. package/v3/@claude-flow/cli/dist/src/commands/mcp.js +718 -0
  482. package/v3/@claude-flow/cli/dist/src/commands/memory.d.ts +8 -0
  483. package/v3/@claude-flow/cli/dist/src/commands/memory.js +1456 -0
  484. package/v3/@claude-flow/cli/dist/src/commands/migrate.d.ts +8 -0
  485. package/v3/@claude-flow/cli/dist/src/commands/migrate.js +742 -0
  486. package/v3/@claude-flow/cli/dist/src/commands/neural.d.ts +10 -0
  487. package/v3/@claude-flow/cli/dist/src/commands/neural.js +1531 -0
  488. package/v3/@claude-flow/cli/dist/src/commands/performance.d.ts +10 -0
  489. package/v3/@claude-flow/cli/dist/src/commands/performance.js +583 -0
  490. package/v3/@claude-flow/cli/dist/src/commands/plugins.d.ts +11 -0
  491. package/v3/@claude-flow/cli/dist/src/commands/plugins.js +826 -0
  492. package/v3/@claude-flow/cli/dist/src/commands/process.d.ts +10 -0
  493. package/v3/@claude-flow/cli/dist/src/commands/process.js +694 -0
  494. package/v3/@claude-flow/cli/dist/src/commands/progress.d.ts +11 -0
  495. package/v3/@claude-flow/cli/dist/src/commands/progress.js +259 -0
  496. package/v3/@claude-flow/cli/dist/src/commands/providers.d.ts +10 -0
  497. package/v3/@claude-flow/cli/dist/src/commands/providers.js +502 -0
  498. package/v3/@claude-flow/cli/dist/src/commands/route.d.ts +16 -0
  499. package/v3/@claude-flow/cli/dist/src/commands/route.js +813 -0
  500. package/v3/@claude-flow/cli/dist/src/commands/ruvector/backup.d.ts +11 -0
  501. package/v3/@claude-flow/cli/dist/src/commands/ruvector/backup.js +747 -0
  502. package/v3/@claude-flow/cli/dist/src/commands/ruvector/benchmark.d.ts +11 -0
  503. package/v3/@claude-flow/cli/dist/src/commands/ruvector/benchmark.js +490 -0
  504. package/v3/@claude-flow/cli/dist/src/commands/ruvector/import.d.ts +18 -0
  505. package/v3/@claude-flow/cli/dist/src/commands/ruvector/import.js +373 -0
  506. package/v3/@claude-flow/cli/dist/src/commands/ruvector/index.d.ts +29 -0
  507. package/v3/@claude-flow/cli/dist/src/commands/ruvector/index.js +129 -0
  508. package/v3/@claude-flow/cli/dist/src/commands/ruvector/init.d.ts +11 -0
  509. package/v3/@claude-flow/cli/dist/src/commands/ruvector/init.js +467 -0
  510. package/v3/@claude-flow/cli/dist/src/commands/ruvector/migrate.d.ts +11 -0
  511. package/v3/@claude-flow/cli/dist/src/commands/ruvector/migrate.js +498 -0
  512. package/v3/@claude-flow/cli/dist/src/commands/ruvector/optimize.d.ts +11 -0
  513. package/v3/@claude-flow/cli/dist/src/commands/ruvector/optimize.js +505 -0
  514. package/v3/@claude-flow/cli/dist/src/commands/ruvector/pg-utils.d.ts +14 -0
  515. package/v3/@claude-flow/cli/dist/src/commands/ruvector/pg-utils.js +41 -0
  516. package/v3/@claude-flow/cli/dist/src/commands/ruvector/setup.d.ts +18 -0
  517. package/v3/@claude-flow/cli/dist/src/commands/ruvector/setup.js +765 -0
  518. package/v3/@claude-flow/cli/dist/src/commands/ruvector/status.d.ts +11 -0
  519. package/v3/@claude-flow/cli/dist/src/commands/ruvector/status.js +479 -0
  520. package/v3/@claude-flow/cli/dist/src/commands/security.d.ts +10 -0
  521. package/v3/@claude-flow/cli/dist/src/commands/security.js +920 -0
  522. package/v3/@claude-flow/cli/dist/src/commands/session.d.ts +8 -0
  523. package/v3/@claude-flow/cli/dist/src/commands/session.js +757 -0
  524. package/v3/@claude-flow/cli/dist/src/commands/start.d.ts +8 -0
  525. package/v3/@claude-flow/cli/dist/src/commands/start.js +418 -0
  526. package/v3/@claude-flow/cli/dist/src/commands/status.d.ts +8 -0
  527. package/v3/@claude-flow/cli/dist/src/commands/status.js +591 -0
  528. package/v3/@claude-flow/cli/dist/src/commands/swarm.d.ts +8 -0
  529. package/v3/@claude-flow/cli/dist/src/commands/swarm.js +887 -0
  530. package/v3/@claude-flow/cli/dist/src/commands/task.d.ts +8 -0
  531. package/v3/@claude-flow/cli/dist/src/commands/task.js +675 -0
  532. package/v3/@claude-flow/cli/dist/src/commands/transfer-store.d.ts +13 -0
  533. package/v3/@claude-flow/cli/dist/src/commands/transfer-store.js +428 -0
  534. package/v3/@claude-flow/cli/dist/src/commands/update.d.ts +8 -0
  535. package/v3/@claude-flow/cli/dist/src/commands/update.js +276 -0
  536. package/v3/@claude-flow/cli/dist/src/commands/verify.d.ts +19 -0
  537. package/v3/@claude-flow/cli/dist/src/commands/verify.js +261 -0
  538. package/v3/@claude-flow/cli/dist/src/commands/workflow.d.ts +8 -0
  539. package/v3/@claude-flow/cli/dist/src/commands/workflow.js +617 -0
  540. package/v3/@claude-flow/cli/dist/src/config-adapter.d.ts +15 -0
  541. package/v3/@claude-flow/cli/dist/src/config-adapter.js +186 -0
  542. package/v3/@claude-flow/cli/dist/src/encryption/vault.d.ts +94 -0
  543. package/v3/@claude-flow/cli/dist/src/encryption/vault.js +172 -0
  544. package/v3/@claude-flow/cli/dist/src/fs-secure.d.ts +67 -0
  545. package/v3/@claude-flow/cli/dist/src/fs-secure.js +74 -0
  546. package/v3/@claude-flow/cli/dist/src/index.d.ts +81 -0
  547. package/v3/@claude-flow/cli/dist/src/index.js +538 -0
  548. package/v3/@claude-flow/cli/dist/src/infrastructure/in-memory-repositories.d.ts +68 -0
  549. package/v3/@claude-flow/cli/dist/src/infrastructure/in-memory-repositories.js +264 -0
  550. package/v3/@claude-flow/cli/dist/src/init/claudemd-generator.d.ts +16 -0
  551. package/v3/@claude-flow/cli/dist/src/init/claudemd-generator.js +363 -0
  552. package/v3/@claude-flow/cli/dist/src/init/executor.d.ts +41 -0
  553. package/v3/@claude-flow/cli/dist/src/init/executor.js +1904 -0
  554. package/v3/@claude-flow/cli/dist/src/init/helpers-generator.d.ts +60 -0
  555. package/v3/@claude-flow/cli/dist/src/init/helpers-generator.js +1185 -0
  556. package/v3/@claude-flow/cli/dist/src/init/index.d.ts +13 -0
  557. package/v3/@claude-flow/cli/dist/src/init/index.js +15 -0
  558. package/v3/@claude-flow/cli/dist/src/init/mcp-generator.d.ts +26 -0
  559. package/v3/@claude-flow/cli/dist/src/init/mcp-generator.js +116 -0
  560. package/v3/@claude-flow/cli/dist/src/init/settings-generator.d.ts +14 -0
  561. package/v3/@claude-flow/cli/dist/src/init/settings-generator.js +456 -0
  562. package/v3/@claude-flow/cli/dist/src/init/statusline-generator.d.ts +28 -0
  563. package/v3/@claude-flow/cli/dist/src/init/statusline-generator.js +937 -0
  564. package/v3/@claude-flow/cli/dist/src/init/types.d.ts +308 -0
  565. package/v3/@claude-flow/cli/dist/src/init/types.js +263 -0
  566. package/v3/@claude-flow/cli/dist/src/log-filters.d.ts +22 -0
  567. package/v3/@claude-flow/cli/dist/src/log-filters.js +36 -0
  568. package/v3/@claude-flow/cli/dist/src/mcp-client.d.ts +92 -0
  569. package/v3/@claude-flow/cli/dist/src/mcp-client.js +287 -0
  570. package/v3/@claude-flow/cli/dist/src/mcp-server.d.ts +163 -0
  571. package/v3/@claude-flow/cli/dist/src/mcp-server.js +732 -0
  572. package/v3/@claude-flow/cli/dist/src/mcp-tools/agent-execute-core.d.ts +92 -0
  573. package/v3/@claude-flow/cli/dist/src/mcp-tools/agent-execute-core.js +328 -0
  574. package/v3/@claude-flow/cli/dist/src/mcp-tools/agent-tools.d.ts +9 -0
  575. package/v3/@claude-flow/cli/dist/src/mcp-tools/agent-tools.js +716 -0
  576. package/v3/@claude-flow/cli/dist/src/mcp-tools/agentdb-tools.d.ts +33 -0
  577. package/v3/@claude-flow/cli/dist/src/mcp-tools/agentdb-tools.js +867 -0
  578. package/v3/@claude-flow/cli/dist/src/mcp-tools/analyze-tools.d.ts +38 -0
  579. package/v3/@claude-flow/cli/dist/src/mcp-tools/analyze-tools.js +346 -0
  580. package/v3/@claude-flow/cli/dist/src/mcp-tools/auto-install.d.ts +83 -0
  581. package/v3/@claude-flow/cli/dist/src/mcp-tools/auto-install.js +131 -0
  582. package/v3/@claude-flow/cli/dist/src/mcp-tools/autopilot-tools.d.ts +12 -0
  583. package/v3/@claude-flow/cli/dist/src/mcp-tools/autopilot-tools.js +231 -0
  584. package/v3/@claude-flow/cli/dist/src/mcp-tools/browser-session-tools.d.ts +23 -0
  585. package/v3/@claude-flow/cli/dist/src/mcp-tools/browser-session-tools.js +324 -0
  586. package/v3/@claude-flow/cli/dist/src/mcp-tools/browser-tools.d.ts +13 -0
  587. package/v3/@claude-flow/cli/dist/src/mcp-tools/browser-tools.js +757 -0
  588. package/v3/@claude-flow/cli/dist/src/mcp-tools/claims-tools.d.ts +12 -0
  589. package/v3/@claude-flow/cli/dist/src/mcp-tools/claims-tools.js +863 -0
  590. package/v3/@claude-flow/cli/dist/src/mcp-tools/config-tools.d.ts +8 -0
  591. package/v3/@claude-flow/cli/dist/src/mcp-tools/config-tools.js +411 -0
  592. package/v3/@claude-flow/cli/dist/src/mcp-tools/coordination-tools.d.ts +13 -0
  593. package/v3/@claude-flow/cli/dist/src/mcp-tools/coordination-tools.js +729 -0
  594. package/v3/@claude-flow/cli/dist/src/mcp-tools/daa-tools.d.ts +13 -0
  595. package/v3/@claude-flow/cli/dist/src/mcp-tools/daa-tools.js +534 -0
  596. package/v3/@claude-flow/cli/dist/src/mcp-tools/embeddings-tools.d.ts +9 -0
  597. package/v3/@claude-flow/cli/dist/src/mcp-tools/embeddings-tools.js +904 -0
  598. package/v3/@claude-flow/cli/dist/src/mcp-tools/github-tools.d.ts +9 -0
  599. package/v3/@claude-flow/cli/dist/src/mcp-tools/github-tools.js +659 -0
  600. package/v3/@claude-flow/cli/dist/src/mcp-tools/guidance-tools.d.ts +15 -0
  601. package/v3/@claude-flow/cli/dist/src/mcp-tools/guidance-tools.js +639 -0
  602. package/v3/@claude-flow/cli/dist/src/mcp-tools/hive-mind-tools.d.ts +8 -0
  603. package/v3/@claude-flow/cli/dist/src/mcp-tools/hive-mind-tools.js +953 -0
  604. package/v3/@claude-flow/cli/dist/src/mcp-tools/hooks-tools.d.ts +46 -0
  605. package/v3/@claude-flow/cli/dist/src/mcp-tools/hooks-tools.js +3939 -0
  606. package/v3/@claude-flow/cli/dist/src/mcp-tools/index.d.ts +27 -0
  607. package/v3/@claude-flow/cli/dist/src/mcp-tools/index.js +26 -0
  608. package/v3/@claude-flow/cli/dist/src/mcp-tools/managed-agent-tools.d.ts +22 -0
  609. package/v3/@claude-flow/cli/dist/src/mcp-tools/managed-agent-tools.js +357 -0
  610. package/v3/@claude-flow/cli/dist/src/mcp-tools/memory-tools.d.ts +14 -0
  611. package/v3/@claude-flow/cli/dist/src/mcp-tools/memory-tools.js +1240 -0
  612. package/v3/@claude-flow/cli/dist/src/mcp-tools/neural-tools.d.ts +16 -0
  613. package/v3/@claude-flow/cli/dist/src/mcp-tools/neural-tools.js +793 -0
  614. package/v3/@claude-flow/cli/dist/src/mcp-tools/performance-tools.d.ts +16 -0
  615. package/v3/@claude-flow/cli/dist/src/mcp-tools/performance-tools.js +675 -0
  616. package/v3/@claude-flow/cli/dist/src/mcp-tools/progress-tools.d.ts +14 -0
  617. package/v3/@claude-flow/cli/dist/src/mcp-tools/progress-tools.js +348 -0
  618. package/v3/@claude-flow/cli/dist/src/mcp-tools/request-tracker.d.ts +17 -0
  619. package/v3/@claude-flow/cli/dist/src/mcp-tools/request-tracker.js +27 -0
  620. package/v3/@claude-flow/cli/dist/src/mcp-tools/ruvllm-tools.d.ts +9 -0
  621. package/v3/@claude-flow/cli/dist/src/mcp-tools/ruvllm-tools.js +339 -0
  622. package/v3/@claude-flow/cli/dist/src/mcp-tools/security-tools.d.ts +18 -0
  623. package/v3/@claude-flow/cli/dist/src/mcp-tools/security-tools.js +556 -0
  624. package/v3/@claude-flow/cli/dist/src/mcp-tools/session-tools.d.ts +8 -0
  625. package/v3/@claude-flow/cli/dist/src/mcp-tools/session-tools.js +517 -0
  626. package/v3/@claude-flow/cli/dist/src/mcp-tools/swarm-tools.d.ts +9 -0
  627. package/v3/@claude-flow/cli/dist/src/mcp-tools/swarm-tools.js +388 -0
  628. package/v3/@claude-flow/cli/dist/src/mcp-tools/system-tools.d.ts +13 -0
  629. package/v3/@claude-flow/cli/dist/src/mcp-tools/system-tools.js +674 -0
  630. package/v3/@claude-flow/cli/dist/src/mcp-tools/task-tools.d.ts +8 -0
  631. package/v3/@claude-flow/cli/dist/src/mcp-tools/task-tools.js +487 -0
  632. package/v3/@claude-flow/cli/dist/src/mcp-tools/terminal-tools.d.ts +8 -0
  633. package/v3/@claude-flow/cli/dist/src/mcp-tools/terminal-tools.js +306 -0
  634. package/v3/@claude-flow/cli/dist/src/mcp-tools/transfer-tools.d.ts +14 -0
  635. package/v3/@claude-flow/cli/dist/src/mcp-tools/transfer-tools.js +447 -0
  636. package/v3/@claude-flow/cli/dist/src/mcp-tools/types.d.ts +8 -0
  637. package/v3/@claude-flow/cli/dist/src/mcp-tools/types.js +8 -0
  638. package/v3/@claude-flow/cli/dist/src/mcp-tools/validate-input.d.ts +9 -0
  639. package/v3/@claude-flow/cli/dist/src/mcp-tools/validate-input.js +9 -0
  640. package/v3/@claude-flow/cli/dist/src/mcp-tools/wasm-agent-tools.d.ts +9 -0
  641. package/v3/@claude-flow/cli/dist/src/mcp-tools/wasm-agent-tools.js +291 -0
  642. package/v3/@claude-flow/cli/dist/src/mcp-tools/workflow-tools.d.ts +8 -0
  643. package/v3/@claude-flow/cli/dist/src/mcp-tools/workflow-tools.js +884 -0
  644. package/v3/@claude-flow/cli/dist/src/memory/ewc-consolidation.d.ts +295 -0
  645. package/v3/@claude-flow/cli/dist/src/memory/ewc-consolidation.js +601 -0
  646. package/v3/@claude-flow/cli/dist/src/memory/intelligence.d.ts +357 -0
  647. package/v3/@claude-flow/cli/dist/src/memory/intelligence.js +1200 -0
  648. package/v3/@claude-flow/cli/dist/src/memory/memory-bridge.d.ts +492 -0
  649. package/v3/@claude-flow/cli/dist/src/memory/memory-bridge.js +2101 -0
  650. package/v3/@claude-flow/cli/dist/src/memory/memory-initializer.d.ts +420 -0
  651. package/v3/@claude-flow/cli/dist/src/memory/memory-initializer.js +2376 -0
  652. package/v3/@claude-flow/cli/dist/src/memory/neural-package-bridge.d.ts +48 -0
  653. package/v3/@claude-flow/cli/dist/src/memory/neural-package-bridge.js +87 -0
  654. package/v3/@claude-flow/cli/dist/src/memory/rabitq-index.d.ts +60 -0
  655. package/v3/@claude-flow/cli/dist/src/memory/rabitq-index.js +242 -0
  656. package/v3/@claude-flow/cli/dist/src/memory/sona-optimizer.d.ts +267 -0
  657. package/v3/@claude-flow/cli/dist/src/memory/sona-optimizer.js +779 -0
  658. package/v3/@claude-flow/cli/dist/src/output.d.ts +9 -0
  659. package/v3/@claude-flow/cli/dist/src/output.js +9 -0
  660. package/v3/@claude-flow/cli/dist/src/parser.d.ts +69 -0
  661. package/v3/@claude-flow/cli/dist/src/parser.js +473 -0
  662. package/v3/@claude-flow/cli/dist/src/plugins/manager.d.ts +133 -0
  663. package/v3/@claude-flow/cli/dist/src/plugins/manager.js +402 -0
  664. package/v3/@claude-flow/cli/dist/src/plugins/store/discovery.d.ts +91 -0
  665. package/v3/@claude-flow/cli/dist/src/plugins/store/discovery.js +1202 -0
  666. package/v3/@claude-flow/cli/dist/src/plugins/store/index.d.ts +76 -0
  667. package/v3/@claude-flow/cli/dist/src/plugins/store/index.js +141 -0
  668. package/v3/@claude-flow/cli/dist/src/plugins/store/search.d.ts +46 -0
  669. package/v3/@claude-flow/cli/dist/src/plugins/store/search.js +230 -0
  670. package/v3/@claude-flow/cli/dist/src/plugins/store/types.d.ts +274 -0
  671. package/v3/@claude-flow/cli/dist/src/plugins/store/types.js +7 -0
  672. package/v3/@claude-flow/cli/dist/src/plugins/tests/demo-plugin-store.d.ts +7 -0
  673. package/v3/@claude-flow/cli/dist/src/plugins/tests/demo-plugin-store.js +126 -0
  674. package/v3/@claude-flow/cli/dist/src/plugins/tests/standalone-test.d.ts +12 -0
  675. package/v3/@claude-flow/cli/dist/src/plugins/tests/standalone-test.js +188 -0
  676. package/v3/@claude-flow/cli/dist/src/plugins/tests/test-plugin-store.d.ts +7 -0
  677. package/v3/@claude-flow/cli/dist/src/plugins/tests/test-plugin-store.js +206 -0
  678. package/v3/@claude-flow/cli/dist/src/production/circuit-breaker.d.ts +101 -0
  679. package/v3/@claude-flow/cli/dist/src/production/circuit-breaker.js +241 -0
  680. package/v3/@claude-flow/cli/dist/src/production/error-handler.d.ts +92 -0
  681. package/v3/@claude-flow/cli/dist/src/production/error-handler.js +299 -0
  682. package/v3/@claude-flow/cli/dist/src/production/index.d.ts +23 -0
  683. package/v3/@claude-flow/cli/dist/src/production/index.js +18 -0
  684. package/v3/@claude-flow/cli/dist/src/production/monitoring.d.ts +161 -0
  685. package/v3/@claude-flow/cli/dist/src/production/monitoring.js +356 -0
  686. package/v3/@claude-flow/cli/dist/src/production/rate-limiter.d.ts +80 -0
  687. package/v3/@claude-flow/cli/dist/src/production/rate-limiter.js +201 -0
  688. package/v3/@claude-flow/cli/dist/src/production/retry.d.ts +48 -0
  689. package/v3/@claude-flow/cli/dist/src/production/retry.js +179 -0
  690. package/v3/@claude-flow/cli/dist/src/prompt.d.ts +44 -0
  691. package/v3/@claude-flow/cli/dist/src/prompt.js +501 -0
  692. package/v3/@claude-flow/cli/dist/src/runtime/headless.d.ts +60 -0
  693. package/v3/@claude-flow/cli/dist/src/runtime/headless.js +284 -0
  694. package/v3/@claude-flow/cli/dist/src/ruvector/agent-wasm.d.ts +193 -0
  695. package/v3/@claude-flow/cli/dist/src/ruvector/agent-wasm.js +354 -0
  696. package/v3/@claude-flow/cli/dist/src/ruvector/ast-analyzer.d.ts +67 -0
  697. package/v3/@claude-flow/cli/dist/src/ruvector/ast-analyzer.js +277 -0
  698. package/v3/@claude-flow/cli/dist/src/ruvector/coverage-router.d.ts +160 -0
  699. package/v3/@claude-flow/cli/dist/src/ruvector/coverage-router.js +531 -0
  700. package/v3/@claude-flow/cli/dist/src/ruvector/coverage-tools.d.ts +33 -0
  701. package/v3/@claude-flow/cli/dist/src/ruvector/coverage-tools.js +157 -0
  702. package/v3/@claude-flow/cli/dist/src/ruvector/diff-classifier.d.ts +175 -0
  703. package/v3/@claude-flow/cli/dist/src/ruvector/diff-classifier.js +699 -0
  704. package/v3/@claude-flow/cli/dist/src/ruvector/diskann-backend.d.ts +78 -0
  705. package/v3/@claude-flow/cli/dist/src/ruvector/diskann-backend.js +310 -0
  706. package/v3/@claude-flow/cli/dist/src/ruvector/enhanced-model-router.d.ts +146 -0
  707. package/v3/@claude-flow/cli/dist/src/ruvector/enhanced-model-router.js +529 -0
  708. package/v3/@claude-flow/cli/dist/src/ruvector/graph-analyzer.d.ts +187 -0
  709. package/v3/@claude-flow/cli/dist/src/ruvector/graph-analyzer.js +929 -0
  710. package/v3/@claude-flow/cli/dist/src/ruvector/graph-backend.d.ts +79 -0
  711. package/v3/@claude-flow/cli/dist/src/ruvector/graph-backend.js +220 -0
  712. package/v3/@claude-flow/cli/dist/src/ruvector/index.d.ts +38 -0
  713. package/v3/@claude-flow/cli/dist/src/ruvector/index.js +82 -0
  714. package/v3/@claude-flow/cli/dist/src/ruvector/lora-adapter.d.ts +240 -0
  715. package/v3/@claude-flow/cli/dist/src/ruvector/lora-adapter.js +550 -0
  716. package/v3/@claude-flow/cli/dist/src/ruvector/model-router.d.ts +241 -0
  717. package/v3/@claude-flow/cli/dist/src/ruvector/model-router.js +608 -0
  718. package/v3/@claude-flow/cli/dist/src/ruvector/q-learning-router.d.ts +211 -0
  719. package/v3/@claude-flow/cli/dist/src/ruvector/q-learning-router.js +681 -0
  720. package/v3/@claude-flow/cli/dist/src/ruvector/ruvllm-wasm.d.ts +179 -0
  721. package/v3/@claude-flow/cli/dist/src/ruvector/ruvllm-wasm.js +367 -0
  722. package/v3/@claude-flow/cli/dist/src/ruvector/semantic-router.d.ts +77 -0
  723. package/v3/@claude-flow/cli/dist/src/ruvector/semantic-router.js +178 -0
  724. package/v3/@claude-flow/cli/dist/src/ruvector/vector-db.d.ts +73 -0
  725. package/v3/@claude-flow/cli/dist/src/ruvector/vector-db.js +264 -0
  726. package/v3/@claude-flow/cli/dist/src/services/agentic-flow-bridge.d.ts +50 -0
  727. package/v3/@claude-flow/cli/dist/src/services/agentic-flow-bridge.js +95 -0
  728. package/v3/@claude-flow/cli/dist/src/services/claim-service.d.ts +204 -0
  729. package/v3/@claude-flow/cli/dist/src/services/claim-service.js +818 -0
  730. package/v3/@claude-flow/cli/dist/src/services/config-file-manager.d.ts +37 -0
  731. package/v3/@claude-flow/cli/dist/src/services/config-file-manager.js +233 -0
  732. package/v3/@claude-flow/cli/dist/src/services/container-worker-pool.d.ts +197 -0
  733. package/v3/@claude-flow/cli/dist/src/services/container-worker-pool.js +583 -0
  734. package/v3/@claude-flow/cli/dist/src/services/headless-worker-executor.d.ts +310 -0
  735. package/v3/@claude-flow/cli/dist/src/services/headless-worker-executor.js +1058 -0
  736. package/v3/@claude-flow/cli/dist/src/services/index.d.ts +13 -0
  737. package/v3/@claude-flow/cli/dist/src/services/index.js +11 -0
  738. package/v3/@claude-flow/cli/dist/src/services/registry-api.d.ts +58 -0
  739. package/v3/@claude-flow/cli/dist/src/services/registry-api.js +146 -0
  740. package/v3/@claude-flow/cli/dist/src/services/ruvector-training.d.ts +222 -0
  741. package/v3/@claude-flow/cli/dist/src/services/ruvector-training.js +688 -0
  742. package/v3/@claude-flow/cli/dist/src/services/worker-daemon.d.ts +323 -0
  743. package/v3/@claude-flow/cli/dist/src/services/worker-daemon.js +1323 -0
  744. package/v3/@claude-flow/cli/dist/src/services/worker-queue.d.ts +194 -0
  745. package/v3/@claude-flow/cli/dist/src/services/worker-queue.js +513 -0
  746. package/v3/@claude-flow/cli/dist/src/suggest.d.ts +53 -0
  747. package/v3/@claude-flow/cli/dist/src/suggest.js +200 -0
  748. package/v3/@claude-flow/cli/dist/src/transfer/anonymization/index.d.ts +25 -0
  749. package/v3/@claude-flow/cli/dist/src/transfer/anonymization/index.js +175 -0
  750. package/v3/@claude-flow/cli/dist/src/transfer/deploy-seraphine.d.ts +13 -0
  751. package/v3/@claude-flow/cli/dist/src/transfer/deploy-seraphine.js +205 -0
  752. package/v3/@claude-flow/cli/dist/src/transfer/export.d.ts +25 -0
  753. package/v3/@claude-flow/cli/dist/src/transfer/export.js +113 -0
  754. package/v3/@claude-flow/cli/dist/src/transfer/index.d.ts +12 -0
  755. package/v3/@claude-flow/cli/dist/src/transfer/index.js +31 -0
  756. package/v3/@claude-flow/cli/dist/src/transfer/ipfs/client.d.ts +109 -0
  757. package/v3/@claude-flow/cli/dist/src/transfer/ipfs/client.js +307 -0
  758. package/v3/@claude-flow/cli/dist/src/transfer/ipfs/upload.d.ts +95 -0
  759. package/v3/@claude-flow/cli/dist/src/transfer/ipfs/upload.js +413 -0
  760. package/v3/@claude-flow/cli/dist/src/transfer/models/seraphine.d.ts +72 -0
  761. package/v3/@claude-flow/cli/dist/src/transfer/models/seraphine.js +373 -0
  762. package/v3/@claude-flow/cli/dist/src/transfer/serialization/cfp.d.ts +49 -0
  763. package/v3/@claude-flow/cli/dist/src/transfer/serialization/cfp.js +183 -0
  764. package/v3/@claude-flow/cli/dist/src/transfer/storage/gcs.d.ts +82 -0
  765. package/v3/@claude-flow/cli/dist/src/transfer/storage/gcs.js +272 -0
  766. package/v3/@claude-flow/cli/dist/src/transfer/storage/index.d.ts +6 -0
  767. package/v3/@claude-flow/cli/dist/src/transfer/storage/index.js +6 -0
  768. package/v3/@claude-flow/cli/dist/src/transfer/store/discovery.d.ts +84 -0
  769. package/v3/@claude-flow/cli/dist/src/transfer/store/discovery.js +382 -0
  770. package/v3/@claude-flow/cli/dist/src/transfer/store/download.d.ts +70 -0
  771. package/v3/@claude-flow/cli/dist/src/transfer/store/download.js +334 -0
  772. package/v3/@claude-flow/cli/dist/src/transfer/store/index.d.ts +84 -0
  773. package/v3/@claude-flow/cli/dist/src/transfer/store/index.js +153 -0
  774. package/v3/@claude-flow/cli/dist/src/transfer/store/publish.d.ts +76 -0
  775. package/v3/@claude-flow/cli/dist/src/transfer/store/publish.js +294 -0
  776. package/v3/@claude-flow/cli/dist/src/transfer/store/registry.d.ts +58 -0
  777. package/v3/@claude-flow/cli/dist/src/transfer/store/registry.js +285 -0
  778. package/v3/@claude-flow/cli/dist/src/transfer/store/search.d.ts +54 -0
  779. package/v3/@claude-flow/cli/dist/src/transfer/store/search.js +232 -0
  780. package/v3/@claude-flow/cli/dist/src/transfer/store/tests/standalone-test.d.ts +12 -0
  781. package/v3/@claude-flow/cli/dist/src/transfer/store/tests/standalone-test.js +190 -0
  782. package/v3/@claude-flow/cli/dist/src/transfer/store/types.d.ts +193 -0
  783. package/v3/@claude-flow/cli/dist/src/transfer/store/types.js +6 -0
  784. package/v3/@claude-flow/cli/dist/src/transfer/test-seraphine.d.ts +6 -0
  785. package/v3/@claude-flow/cli/dist/src/transfer/test-seraphine.js +105 -0
  786. package/v3/@claude-flow/cli/dist/src/transfer/tests/test-store.d.ts +7 -0
  787. package/v3/@claude-flow/cli/dist/src/transfer/tests/test-store.js +214 -0
  788. package/v3/@claude-flow/cli/dist/src/transfer/types.d.ts +245 -0
  789. package/v3/@claude-flow/cli/dist/src/transfer/types.js +6 -0
  790. package/v3/@claude-flow/cli/dist/src/types.d.ts +13 -0
  791. package/v3/@claude-flow/cli/dist/src/types.js +13 -0
  792. package/v3/@claude-flow/cli/dist/src/update/checker.d.ts +34 -0
  793. package/v3/@claude-flow/cli/dist/src/update/checker.js +191 -0
  794. package/v3/@claude-flow/cli/dist/src/update/executor.d.ts +33 -0
  795. package/v3/@claude-flow/cli/dist/src/update/executor.js +217 -0
  796. package/v3/@claude-flow/cli/dist/src/update/index.d.ts +33 -0
  797. package/v3/@claude-flow/cli/dist/src/update/index.js +64 -0
  798. package/v3/@claude-flow/cli/dist/src/update/rate-limiter.d.ts +20 -0
  799. package/v3/@claude-flow/cli/dist/src/update/rate-limiter.js +96 -0
  800. package/v3/@claude-flow/cli/dist/src/update/validator.d.ts +17 -0
  801. package/v3/@claude-flow/cli/dist/src/update/validator.js +123 -0
  802. package/v3/@claude-flow/cli/package.json +133 -0
  803. package/v3/@claude-flow/guidance/README.md +1195 -0
  804. package/v3/@claude-flow/guidance/package.json +198 -0
  805. package/v3/@claude-flow/shared/README.md +323 -0
  806. package/v3/@claude-flow/shared/package.json +43 -0
  807. package/v3/README.md +493 -0
@@ -0,0 +1,2376 @@
1
+ /**
2
+ * V3 Memory Initializer
3
+ * Properly initializes the memory database with sql.js (WASM SQLite)
4
+ * Includes pattern tables, vector embeddings, migration state tracking
5
+ *
6
+ * ADR-053: Routes through ControllerRegistry → AgentDB v3 when available,
7
+ * falls back to raw sql.js for backwards compatibility.
8
+ *
9
+ * @module v3/cli/memory-initializer
10
+ */
11
+ import * as fs from 'fs';
12
+ import * as path from 'path';
13
+ import { readFileMaybeEncrypted, writeFileRestricted } from '../fs-secure.js';
14
+ /**
15
+ * #1854: previously every site that needed the memory directory hardcoded
16
+ * `getMemoryRoot()`, so the documented config entry
17
+ * points (`memory.persistPath` config field, `memory configure --path`,
18
+ * `CLAUDE_FLOW_MEMORY_PATH` env var) all silently no-op'd. This helper
19
+ * is the single source of truth — every `.swarm/memory.db` resolution in
20
+ * this file flows through it.
21
+ *
22
+ * Precedence (highest → lowest):
23
+ * 1. CLAUDE_FLOW_MEMORY_PATH env var
24
+ * 2. memory.persistPath / memory.path in claude-flow.config.json (cwd or
25
+ * the directory the CLI was invoked from)
26
+ * 3. Default: cwd/.swarm
27
+ *
28
+ * Cached per-process so repeated lookups are cheap; reset only by spawning
29
+ * a fresh process (which is how config changes already propagate).
30
+ */
31
+ let _memoryRootCache;
32
+ export function getMemoryRoot() {
33
+ if (_memoryRootCache !== undefined)
34
+ return _memoryRootCache;
35
+ // 1. Env var
36
+ const envPath = process.env.CLAUDE_FLOW_MEMORY_PATH;
37
+ if (envPath && envPath.trim().length > 0) {
38
+ _memoryRootCache = path.resolve(envPath);
39
+ return _memoryRootCache;
40
+ }
41
+ // 2. Config file (claude-flow.config.json)
42
+ const configCandidates = [
43
+ path.resolve(process.cwd(), 'claude-flow.config.json'),
44
+ path.resolve(process.cwd(), '.claude-flow', 'config.json'),
45
+ ];
46
+ for (const configPath of configCandidates) {
47
+ if (!fs.existsSync(configPath))
48
+ continue;
49
+ try {
50
+ const raw = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
51
+ const fromConfig = raw?.memory?.persistPath ?? raw?.memory?.path;
52
+ if (typeof fromConfig === 'string' && fromConfig.trim().length > 0) {
53
+ _memoryRootCache = path.resolve(fromConfig);
54
+ return _memoryRootCache;
55
+ }
56
+ }
57
+ catch {
58
+ /* malformed config — fall through to default */
59
+ }
60
+ }
61
+ // 3. Default
62
+ _memoryRootCache = path.resolve(process.cwd(), '.swarm');
63
+ return _memoryRootCache;
64
+ }
65
+ /** For tests + the `memory configure` flow that mutates the config at runtime. */
66
+ export function _resetMemoryRootCache() {
67
+ _memoryRootCache = undefined;
68
+ }
69
+ // ADR-053: Lazy import of AgentDB v3 bridge
70
+ let _bridge;
71
+ async function getBridge() {
72
+ if (_bridge === null)
73
+ return null;
74
+ if (_bridge)
75
+ return _bridge;
76
+ try {
77
+ _bridge = await import('./memory-bridge.js');
78
+ return _bridge;
79
+ }
80
+ catch {
81
+ _bridge = null;
82
+ return null;
83
+ }
84
+ }
85
+ /**
86
+ * Enhanced schema with pattern confidence, temporal decay, versioning
87
+ * Vector embeddings enabled for semantic search
88
+ */
89
+ export const MEMORY_SCHEMA_V3 = `
90
+ -- RuFlo V3 Memory Database
91
+ -- Version: 3.0.0
92
+ -- Features: Pattern learning, vector embeddings, temporal decay, migration tracking
93
+
94
+ PRAGMA journal_mode = WAL;
95
+ PRAGMA synchronous = NORMAL;
96
+ PRAGMA foreign_keys = ON;
97
+
98
+ -- ============================================
99
+ -- CORE MEMORY TABLES
100
+ -- ============================================
101
+
102
+ -- Memory entries (main storage)
103
+ CREATE TABLE IF NOT EXISTS memory_entries (
104
+ id TEXT PRIMARY KEY,
105
+ key TEXT NOT NULL,
106
+ namespace TEXT DEFAULT 'default',
107
+ content TEXT NOT NULL,
108
+ type TEXT DEFAULT 'semantic' CHECK(type IN ('semantic', 'episodic', 'procedural', 'working', 'pattern')),
109
+
110
+ -- Vector embedding for semantic search (stored as JSON array)
111
+ embedding TEXT,
112
+ embedding_model TEXT DEFAULT 'local',
113
+ embedding_dimensions INTEGER,
114
+
115
+ -- Metadata
116
+ tags TEXT, -- JSON array
117
+ metadata TEXT, -- JSON object
118
+ owner_id TEXT,
119
+
120
+ -- Timestamps
121
+ created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now') * 1000),
122
+ updated_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now') * 1000),
123
+ expires_at INTEGER,
124
+ last_accessed_at INTEGER,
125
+
126
+ -- Access tracking for hot/cold detection
127
+ access_count INTEGER DEFAULT 0,
128
+
129
+ -- Status
130
+ status TEXT DEFAULT 'active' CHECK(status IN ('active', 'archived', 'deleted')),
131
+
132
+ UNIQUE(namespace, key)
133
+ );
134
+
135
+ -- Indexes for memory entries
136
+ CREATE INDEX IF NOT EXISTS idx_memory_namespace ON memory_entries(namespace);
137
+ CREATE INDEX IF NOT EXISTS idx_memory_key ON memory_entries(key);
138
+ CREATE INDEX IF NOT EXISTS idx_memory_type ON memory_entries(type);
139
+ CREATE INDEX IF NOT EXISTS idx_memory_status ON memory_entries(status);
140
+ CREATE INDEX IF NOT EXISTS idx_memory_created ON memory_entries(created_at);
141
+ CREATE INDEX IF NOT EXISTS idx_memory_accessed ON memory_entries(last_accessed_at);
142
+ CREATE INDEX IF NOT EXISTS idx_memory_owner ON memory_entries(owner_id);
143
+
144
+ -- ============================================
145
+ -- PATTERN LEARNING TABLES
146
+ -- ============================================
147
+
148
+ -- Learned patterns with confidence scoring and versioning
149
+ CREATE TABLE IF NOT EXISTS patterns (
150
+ id TEXT PRIMARY KEY,
151
+
152
+ -- Pattern identification
153
+ name TEXT NOT NULL,
154
+ pattern_type TEXT NOT NULL CHECK(pattern_type IN (
155
+ 'task-routing', 'error-recovery', 'optimization', 'learning',
156
+ 'coordination', 'prediction', 'code-pattern', 'workflow'
157
+ )),
158
+
159
+ -- Pattern definition
160
+ condition TEXT NOT NULL, -- Regex or semantic match
161
+ action TEXT NOT NULL, -- What to do when pattern matches
162
+ description TEXT,
163
+
164
+ -- Confidence scoring (0.0 - 1.0)
165
+ confidence REAL DEFAULT 0.5,
166
+ success_count INTEGER DEFAULT 0,
167
+ failure_count INTEGER DEFAULT 0,
168
+
169
+ -- Temporal decay
170
+ decay_rate REAL DEFAULT 0.01, -- How fast confidence decays
171
+ half_life_days INTEGER DEFAULT 30, -- Days until confidence halves without use
172
+
173
+ -- Vector embedding for semantic pattern matching
174
+ embedding TEXT,
175
+ embedding_dimensions INTEGER,
176
+
177
+ -- Versioning
178
+ version INTEGER DEFAULT 1,
179
+ parent_id TEXT REFERENCES patterns(id),
180
+
181
+ -- Metadata
182
+ tags TEXT, -- JSON array
183
+ metadata TEXT, -- JSON object
184
+ source TEXT, -- Where the pattern was learned from
185
+
186
+ -- Timestamps
187
+ created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now') * 1000),
188
+ updated_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now') * 1000),
189
+ last_matched_at INTEGER,
190
+ last_success_at INTEGER,
191
+ last_failure_at INTEGER,
192
+
193
+ -- Status
194
+ status TEXT DEFAULT 'active' CHECK(status IN ('active', 'archived', 'deprecated', 'experimental'))
195
+ );
196
+
197
+ -- Indexes for patterns
198
+ CREATE INDEX IF NOT EXISTS idx_patterns_type ON patterns(pattern_type);
199
+ CREATE INDEX IF NOT EXISTS idx_patterns_confidence ON patterns(confidence DESC);
200
+ CREATE INDEX IF NOT EXISTS idx_patterns_status ON patterns(status);
201
+ CREATE INDEX IF NOT EXISTS idx_patterns_last_matched ON patterns(last_matched_at);
202
+
203
+ -- Pattern evolution history (for versioning)
204
+ CREATE TABLE IF NOT EXISTS pattern_history (
205
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
206
+ pattern_id TEXT NOT NULL REFERENCES patterns(id),
207
+ version INTEGER NOT NULL,
208
+
209
+ -- Snapshot of pattern state
210
+ confidence REAL,
211
+ success_count INTEGER,
212
+ failure_count INTEGER,
213
+ condition TEXT,
214
+ action TEXT,
215
+
216
+ -- What changed
217
+ change_type TEXT CHECK(change_type IN ('created', 'updated', 'success', 'failure', 'decay', 'merged', 'split')),
218
+ change_reason TEXT,
219
+
220
+ created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now') * 1000)
221
+ );
222
+
223
+ CREATE INDEX IF NOT EXISTS idx_pattern_history_pattern ON pattern_history(pattern_id);
224
+
225
+ -- ============================================
226
+ -- LEARNING & TRAJECTORY TABLES
227
+ -- ============================================
228
+
229
+ -- Learning trajectories (SONA integration)
230
+ CREATE TABLE IF NOT EXISTS trajectories (
231
+ id TEXT PRIMARY KEY,
232
+ session_id TEXT,
233
+
234
+ -- Trajectory state
235
+ status TEXT DEFAULT 'active' CHECK(status IN ('active', 'completed', 'failed', 'abandoned')),
236
+ verdict TEXT CHECK(verdict IN ('success', 'failure', 'partial', NULL)),
237
+
238
+ -- Context
239
+ task TEXT,
240
+ context TEXT, -- JSON object
241
+
242
+ -- Metrics
243
+ total_steps INTEGER DEFAULT 0,
244
+ total_reward REAL DEFAULT 0,
245
+
246
+ -- Timestamps
247
+ started_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now') * 1000),
248
+ ended_at INTEGER,
249
+
250
+ -- Reference to extracted pattern (if any)
251
+ extracted_pattern_id TEXT REFERENCES patterns(id)
252
+ );
253
+
254
+ -- Trajectory steps
255
+ CREATE TABLE IF NOT EXISTS trajectory_steps (
256
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
257
+ trajectory_id TEXT NOT NULL REFERENCES trajectories(id),
258
+ step_number INTEGER NOT NULL,
259
+
260
+ -- Step data
261
+ action TEXT NOT NULL,
262
+ observation TEXT,
263
+ reward REAL DEFAULT 0,
264
+
265
+ -- Metadata
266
+ metadata TEXT, -- JSON object
267
+
268
+ created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now') * 1000)
269
+ );
270
+
271
+ CREATE INDEX IF NOT EXISTS idx_steps_trajectory ON trajectory_steps(trajectory_id);
272
+
273
+ -- ============================================
274
+ -- MIGRATION STATE TRACKING
275
+ -- ============================================
276
+
277
+ -- Migration state (for resume capability)
278
+ CREATE TABLE IF NOT EXISTS migration_state (
279
+ id TEXT PRIMARY KEY,
280
+ migration_type TEXT NOT NULL, -- 'v2-to-v3', 'pattern', 'memory', etc.
281
+
282
+ -- Progress tracking
283
+ status TEXT DEFAULT 'pending' CHECK(status IN ('pending', 'in_progress', 'completed', 'failed', 'rolled_back')),
284
+ total_items INTEGER DEFAULT 0,
285
+ processed_items INTEGER DEFAULT 0,
286
+ failed_items INTEGER DEFAULT 0,
287
+ skipped_items INTEGER DEFAULT 0,
288
+
289
+ -- Current position (for resume)
290
+ current_batch INTEGER DEFAULT 0,
291
+ last_processed_id TEXT,
292
+
293
+ -- Source/destination info
294
+ source_path TEXT,
295
+ source_type TEXT,
296
+ destination_path TEXT,
297
+
298
+ -- Backup info
299
+ backup_path TEXT,
300
+ backup_created_at INTEGER,
301
+
302
+ -- Error tracking
303
+ last_error TEXT,
304
+ errors TEXT, -- JSON array of errors
305
+
306
+ -- Timestamps
307
+ started_at INTEGER,
308
+ completed_at INTEGER,
309
+ created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now') * 1000),
310
+ updated_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now') * 1000)
311
+ );
312
+
313
+ -- ============================================
314
+ -- SESSION MANAGEMENT
315
+ -- ============================================
316
+
317
+ -- Sessions for context persistence
318
+ CREATE TABLE IF NOT EXISTS sessions (
319
+ id TEXT PRIMARY KEY,
320
+
321
+ -- Session state
322
+ state TEXT NOT NULL, -- JSON object with full session state
323
+ status TEXT DEFAULT 'active' CHECK(status IN ('active', 'paused', 'completed', 'expired')),
324
+
325
+ -- Context
326
+ project_path TEXT,
327
+ branch TEXT,
328
+
329
+ -- Metrics
330
+ tasks_completed INTEGER DEFAULT 0,
331
+ patterns_learned INTEGER DEFAULT 0,
332
+
333
+ -- Timestamps
334
+ created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now') * 1000),
335
+ updated_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now') * 1000),
336
+ expires_at INTEGER
337
+ );
338
+
339
+ -- ============================================
340
+ -- VECTOR INDEX METADATA (for HNSW)
341
+ -- ============================================
342
+
343
+ -- Track HNSW index state
344
+ CREATE TABLE IF NOT EXISTS vector_indexes (
345
+ id TEXT PRIMARY KEY,
346
+ name TEXT NOT NULL UNIQUE,
347
+
348
+ -- Index configuration
349
+ dimensions INTEGER NOT NULL,
350
+ metric TEXT DEFAULT 'cosine' CHECK(metric IN ('cosine', 'euclidean', 'dot')),
351
+
352
+ -- HNSW parameters
353
+ hnsw_m INTEGER DEFAULT 16,
354
+ hnsw_ef_construction INTEGER DEFAULT 200,
355
+ hnsw_ef_search INTEGER DEFAULT 100,
356
+
357
+ -- Quantization
358
+ quantization_type TEXT CHECK(quantization_type IN ('none', 'scalar', 'product')),
359
+ quantization_bits INTEGER DEFAULT 8,
360
+
361
+ -- Statistics
362
+ total_vectors INTEGER DEFAULT 0,
363
+ last_rebuild_at INTEGER,
364
+
365
+ created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now') * 1000),
366
+ updated_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now') * 1000)
367
+ );
368
+
369
+ -- ============================================
370
+ -- SYSTEM METADATA
371
+ -- ============================================
372
+
373
+ CREATE TABLE IF NOT EXISTS metadata (
374
+ key TEXT PRIMARY KEY,
375
+ value TEXT NOT NULL,
376
+ updated_at INTEGER DEFAULT (strftime('%s', 'now') * 1000)
377
+ );
378
+ `;
379
+ let hnswIndex = null;
380
+ let hnswInitializing = false;
381
+ /**
382
+ * Get or create the HNSW index singleton
383
+ * Lazily initializes from SQLite data on first use
384
+ */
385
+ export async function getHNSWIndex(options) {
386
+ const dimensions = options?.dimensions ?? 384;
387
+ // Return existing index if already initialized
388
+ if (hnswIndex?.initialized && !options?.forceRebuild) {
389
+ return hnswIndex;
390
+ }
391
+ // Prevent concurrent initialization
392
+ if (hnswInitializing) {
393
+ // Wait for initialization to complete
394
+ while (hnswInitializing) {
395
+ await new Promise(resolve => setTimeout(resolve, 10));
396
+ }
397
+ return hnswIndex;
398
+ }
399
+ hnswInitializing = true;
400
+ try {
401
+ // Import @ruvector/core dynamically
402
+ // Handle both ESM (default export) and CJS patterns
403
+ const ruvectorModule = await import('@ruvector/core').catch(() => null);
404
+ if (!ruvectorModule) {
405
+ hnswInitializing = false;
406
+ return null; // HNSW not available
407
+ }
408
+ // ESM returns { default: { VectorDb, ... } }, CJS returns { VectorDb, ... }
409
+ const ruvectorCore = ruvectorModule.default || ruvectorModule;
410
+ if (!ruvectorCore?.VectorDb) {
411
+ hnswInitializing = false;
412
+ return null; // VectorDb not found
413
+ }
414
+ const { VectorDb } = ruvectorCore;
415
+ // Persistent storage paths — resolve to absolute to survive CWD changes
416
+ const swarmDir = getMemoryRoot();
417
+ if (!fs.existsSync(swarmDir)) {
418
+ fs.mkdirSync(swarmDir, { recursive: true });
419
+ }
420
+ const hnswPath = path.join(swarmDir, 'hnsw.index');
421
+ const metadataPath = path.join(swarmDir, 'hnsw.metadata.json');
422
+ const dbPath = options?.dbPath ? path.resolve(options.dbPath) : path.join(swarmDir, 'memory.db');
423
+ // Create HNSW index with persistent storage
424
+ // @ruvector/core uses string enum for distanceMetric: 'Cosine', 'Euclidean', 'DotProduct', 'Manhattan'
425
+ const db = new VectorDb({
426
+ dimensions,
427
+ distanceMetric: 'Cosine',
428
+ storagePath: hnswPath // Persistent storage!
429
+ });
430
+ // Load metadata (entry info) if exists
431
+ const entries = new Map();
432
+ if (fs.existsSync(metadataPath)) {
433
+ try {
434
+ const metadataJson = fs.readFileSync(metadataPath, 'utf-8');
435
+ const metadata = JSON.parse(metadataJson);
436
+ for (const [key, value] of metadata) {
437
+ entries.set(key, value);
438
+ }
439
+ }
440
+ catch {
441
+ // Metadata load failed, will rebuild
442
+ }
443
+ }
444
+ hnswIndex = {
445
+ db,
446
+ entries,
447
+ dimensions,
448
+ initialized: false
449
+ };
450
+ // Check if index already has data (from persistent storage)
451
+ const existingLen = await db.len();
452
+ if (existingLen > 0 && entries.size > 0) {
453
+ // Index loaded from disk, skip SQLite sync
454
+ hnswIndex.initialized = true;
455
+ hnswInitializing = false;
456
+ return hnswIndex;
457
+ }
458
+ if (fs.existsSync(dbPath)) {
459
+ try {
460
+ const initSqlJs = (await import('sql.js')).default;
461
+ const SQL = await initSqlJs();
462
+ const fileBuffer = readFileMaybeEncrypted(dbPath, null);
463
+ const sqlDb = new SQL.Database(fileBuffer);
464
+ // Load all entries with embeddings
465
+ const result = sqlDb.exec(`
466
+ SELECT id, key, namespace, content, embedding
467
+ FROM memory_entries
468
+ WHERE status = 'active' AND embedding IS NOT NULL
469
+ LIMIT 10000
470
+ `);
471
+ if (result[0]?.values) {
472
+ for (const row of result[0].values) {
473
+ const [id, key, ns, content, embeddingJson] = row;
474
+ if (embeddingJson) {
475
+ try {
476
+ const embedding = JSON.parse(embeddingJson);
477
+ const vector = new Float32Array(embedding);
478
+ await db.insert({
479
+ id: String(id),
480
+ vector
481
+ });
482
+ hnswIndex.entries.set(String(id), {
483
+ id: String(id),
484
+ key: key || String(id),
485
+ namespace: ns || 'default',
486
+ content: content || ''
487
+ });
488
+ }
489
+ catch {
490
+ // Skip invalid embeddings
491
+ }
492
+ }
493
+ }
494
+ }
495
+ sqlDb.close();
496
+ }
497
+ catch {
498
+ // SQLite load failed, start with empty index
499
+ }
500
+ }
501
+ hnswIndex.initialized = true;
502
+ hnswInitializing = false;
503
+ return hnswIndex;
504
+ }
505
+ catch {
506
+ hnswInitializing = false;
507
+ return null;
508
+ }
509
+ }
510
+ /**
511
+ * Save HNSW metadata to disk for persistence
512
+ */
513
+ function saveHNSWMetadata() {
514
+ if (!hnswIndex?.entries)
515
+ return;
516
+ try {
517
+ const swarmDir = getMemoryRoot();
518
+ const metadataPath = path.join(swarmDir, 'hnsw.metadata.json');
519
+ const metadata = Array.from(hnswIndex.entries.entries());
520
+ fs.writeFileSync(metadataPath, JSON.stringify(metadata));
521
+ }
522
+ catch {
523
+ // Silently fail - metadata save is best-effort
524
+ }
525
+ }
526
+ /**
527
+ * Add entry to HNSW index (with automatic persistence)
528
+ */
529
+ export async function addToHNSWIndex(id, embedding, entry) {
530
+ // ADR-053: Try AgentDB v3 bridge first
531
+ const bridge = await getBridge();
532
+ if (bridge) {
533
+ const bridgeResult = await bridge.bridgeAddToHNSW(id, embedding, entry);
534
+ if (bridgeResult === true)
535
+ return true;
536
+ }
537
+ const index = await getHNSWIndex({ dimensions: embedding.length });
538
+ if (!index)
539
+ return false;
540
+ try {
541
+ const vector = new Float32Array(embedding);
542
+ await index.db.insert({
543
+ id,
544
+ vector
545
+ });
546
+ index.entries.set(id, entry);
547
+ // Save metadata for persistence (debounced would be better for high-volume)
548
+ saveHNSWMetadata();
549
+ return true;
550
+ }
551
+ catch {
552
+ return false;
553
+ }
554
+ }
555
+ /**
556
+ * Search HNSW index (150x faster than brute-force)
557
+ * Returns results sorted by similarity (highest first)
558
+ */
559
+ export async function searchHNSWIndex(queryEmbedding, options) {
560
+ // ADR-053: Try AgentDB v3 bridge first
561
+ const bridge = await getBridge();
562
+ if (bridge) {
563
+ const bridgeResult = await bridge.bridgeSearchHNSW(queryEmbedding, options);
564
+ if (bridgeResult)
565
+ return bridgeResult;
566
+ }
567
+ const index = await getHNSWIndex({ dimensions: queryEmbedding.length });
568
+ if (!index)
569
+ return null;
570
+ try {
571
+ const vector = new Float32Array(queryEmbedding);
572
+ const k = options?.k ?? 10;
573
+ // HNSW search returns results with cosine distance (lower = more similar)
574
+ const results = await index.db.search({ vector, k: k * 2 }); // Get extra for filtering
575
+ const filtered = [];
576
+ for (const result of results) {
577
+ const entry = index.entries.get(result.id);
578
+ if (!entry)
579
+ continue;
580
+ // Filter by namespace if specified
581
+ if (options?.namespace && options.namespace !== 'all' && entry.namespace !== options.namespace) {
582
+ continue;
583
+ }
584
+ // Convert cosine distance to similarity score (1 - distance)
585
+ // Cosine distance from @ruvector/core: 0 = identical, 2 = opposite
586
+ const score = 1 - (result.score / 2);
587
+ filtered.push({
588
+ id: entry.id.substring(0, 12),
589
+ key: entry.key || entry.id.substring(0, 15),
590
+ content: entry.content.substring(0, 60) + (entry.content.length > 60 ? '...' : ''),
591
+ score,
592
+ namespace: entry.namespace
593
+ });
594
+ if (filtered.length >= k)
595
+ break;
596
+ }
597
+ // Sort by score descending (highest similarity first)
598
+ filtered.sort((a, b) => b.score - a.score);
599
+ return filtered;
600
+ }
601
+ catch {
602
+ return null;
603
+ }
604
+ }
605
+ /**
606
+ * Get HNSW index status
607
+ */
608
+ export function getHNSWStatus() {
609
+ // ADR-053: If bridge was previously loaded, report availability
610
+ if (_bridge && _bridge !== null) {
611
+ // Bridge is loaded — HNSW-equivalent is available via AgentDB v3
612
+ return {
613
+ available: true,
614
+ initialized: true,
615
+ entryCount: hnswIndex?.entries.size ?? 0,
616
+ dimensions: hnswIndex?.dimensions ?? 384
617
+ };
618
+ }
619
+ return {
620
+ available: hnswIndex !== null,
621
+ initialized: hnswIndex?.initialized ?? false,
622
+ entryCount: hnswIndex?.entries.size ?? 0,
623
+ dimensions: hnswIndex?.dimensions ?? 384
624
+ };
625
+ }
626
+ /**
627
+ * Clear the HNSW index (for rebuilding)
628
+ */
629
+ export function clearHNSWIndex() {
630
+ hnswIndex = null;
631
+ }
632
+ /**
633
+ * Invalidate the in-memory HNSW cache so the next search rebuilds from DB.
634
+ * Call this after deleting entries that had embeddings to prevent ghost
635
+ * vectors from appearing in search results.
636
+ */
637
+ export function rebuildSearchIndex() {
638
+ hnswIndex = null;
639
+ hnswInitializing = false;
640
+ }
641
+ // ============================================================================
642
+ // INT8 VECTOR QUANTIZATION (4x memory reduction)
643
+ // ============================================================================
644
+ /**
645
+ * Quantize a Float32 embedding to Int8 (4x memory reduction)
646
+ * Uses symmetric quantization with scale factor stored per-vector
647
+ *
648
+ * @param embedding - Float32 embedding array
649
+ * @returns Quantized Int8 array with scale factor
650
+ */
651
+ export function quantizeInt8(embedding) {
652
+ const arr = embedding instanceof Float32Array ? embedding : new Float32Array(embedding);
653
+ // Find min/max for symmetric quantization
654
+ let min = Infinity, max = -Infinity;
655
+ for (let i = 0; i < arr.length; i++) {
656
+ if (arr[i] < min)
657
+ min = arr[i];
658
+ if (arr[i] > max)
659
+ max = arr[i];
660
+ }
661
+ // Symmetric quantization: scale = max(|min|, |max|) / 127
662
+ const absMax = Math.max(Math.abs(min), Math.abs(max));
663
+ const scale = absMax / 127 || 1e-10; // Avoid division by zero
664
+ const zeroPoint = 0; // Symmetric quantization
665
+ // Quantize
666
+ const quantized = new Int8Array(arr.length);
667
+ for (let i = 0; i < arr.length; i++) {
668
+ // Clamp to [-127, 127] to leave room for potential rounding
669
+ const q = Math.round(arr[i] / scale);
670
+ quantized[i] = Math.max(-127, Math.min(127, q));
671
+ }
672
+ return { quantized, scale, zeroPoint };
673
+ }
674
+ /**
675
+ * Dequantize Int8 back to Float32
676
+ *
677
+ * @param quantized - Int8 quantized array
678
+ * @param scale - Scale factor from quantization
679
+ * @param zeroPoint - Zero point (usually 0 for symmetric)
680
+ * @returns Float32Array
681
+ */
682
+ export function dequantizeInt8(quantized, scale, zeroPoint = 0) {
683
+ const result = new Float32Array(quantized.length);
684
+ for (let i = 0; i < quantized.length; i++) {
685
+ result[i] = (quantized[i] - zeroPoint) * scale;
686
+ }
687
+ return result;
688
+ }
689
+ /**
690
+ * Compute cosine similarity between quantized vectors
691
+ * Faster than dequantizing first
692
+ */
693
+ export function quantizedCosineSim(a, aScale, b, bScale) {
694
+ if (a.length !== b.length)
695
+ return 0;
696
+ let dot = 0, normA = 0, normB = 0;
697
+ for (let i = 0; i < a.length; i++) {
698
+ dot += a[i] * b[i];
699
+ normA += a[i] * a[i];
700
+ normB += b[i] * b[i];
701
+ }
702
+ // Scales cancel out in cosine similarity for normalized vectors
703
+ const mag = Math.sqrt(normA * normB);
704
+ return mag === 0 ? 0 : dot / mag;
705
+ }
706
+ /**
707
+ * Get quantization statistics for an embedding
708
+ */
709
+ export function getQuantizationStats(embedding) {
710
+ const len = embedding.length;
711
+ const originalBytes = len * 4; // Float32 = 4 bytes
712
+ const quantizedBytes = len + 8; // Int8 = 1 byte + 8 bytes for scale/zeroPoint
713
+ const compressionRatio = originalBytes / quantizedBytes;
714
+ return { originalBytes, quantizedBytes, compressionRatio };
715
+ }
716
+ // ============================================================================
717
+ // FLASH ATTENTION-STYLE BATCH OPERATIONS (V8-Optimized)
718
+ // ============================================================================
719
+ /**
720
+ * Batch cosine similarity - compute query against multiple vectors
721
+ * Optimized for V8 JIT with typed arrays
722
+ * ~50μs per 1000 vectors (384-dim)
723
+ */
724
+ export function batchCosineSim(query, vectors) {
725
+ const n = vectors.length;
726
+ const scores = new Float32Array(n);
727
+ if (n === 0 || query.length === 0)
728
+ return scores;
729
+ // Pre-compute query norm
730
+ let queryNorm = 0;
731
+ for (let i = 0; i < query.length; i++) {
732
+ queryNorm += query[i] * query[i];
733
+ }
734
+ queryNorm = Math.sqrt(queryNorm);
735
+ if (queryNorm === 0)
736
+ return scores;
737
+ // Compute similarities
738
+ for (let v = 0; v < n; v++) {
739
+ const vec = vectors[v];
740
+ const len = Math.min(query.length, vec.length);
741
+ let dot = 0, vecNorm = 0;
742
+ for (let i = 0; i < len; i++) {
743
+ dot += query[i] * vec[i];
744
+ vecNorm += vec[i] * vec[i];
745
+ }
746
+ vecNorm = Math.sqrt(vecNorm);
747
+ scores[v] = vecNorm === 0 ? 0 : dot / (queryNorm * vecNorm);
748
+ }
749
+ return scores;
750
+ }
751
+ /**
752
+ * Softmax normalization for attention scores
753
+ * Numerically stable implementation
754
+ */
755
+ export function softmaxAttention(scores, temperature = 1.0) {
756
+ const n = scores.length;
757
+ const result = new Float32Array(n);
758
+ if (n === 0)
759
+ return result;
760
+ // Find max for numerical stability
761
+ let max = scores[0];
762
+ for (let i = 1; i < n; i++) {
763
+ if (scores[i] > max)
764
+ max = scores[i];
765
+ }
766
+ // Compute exp and sum
767
+ let sum = 0;
768
+ for (let i = 0; i < n; i++) {
769
+ result[i] = Math.exp((scores[i] - max) / temperature);
770
+ sum += result[i];
771
+ }
772
+ // Normalize
773
+ if (sum > 0) {
774
+ for (let i = 0; i < n; i++) {
775
+ result[i] /= sum;
776
+ }
777
+ }
778
+ return result;
779
+ }
780
+ /**
781
+ * Top-K selection with partial sort (O(n + k log k))
782
+ * More efficient than full sort for small k
783
+ */
784
+ export function topKIndices(scores, k) {
785
+ const n = scores.length;
786
+ if (k >= n) {
787
+ // Return all indices sorted by score
788
+ return Array.from({ length: n }, (_, i) => i)
789
+ .sort((a, b) => scores[b] - scores[a]);
790
+ }
791
+ // Build min-heap of size k
792
+ const heap = [];
793
+ for (let i = 0; i < n; i++) {
794
+ if (heap.length < k) {
795
+ heap.push({ idx: i, score: scores[i] });
796
+ // Bubble up
797
+ let j = heap.length - 1;
798
+ while (j > 0) {
799
+ const parent = Math.floor((j - 1) / 2);
800
+ if (heap[j].score < heap[parent].score) {
801
+ [heap[j], heap[parent]] = [heap[parent], heap[j]];
802
+ j = parent;
803
+ }
804
+ else
805
+ break;
806
+ }
807
+ }
808
+ else if (scores[i] > heap[0].score) {
809
+ // Replace min and heapify down
810
+ heap[0] = { idx: i, score: scores[i] };
811
+ let j = 0;
812
+ while (true) {
813
+ const left = 2 * j + 1, right = 2 * j + 2;
814
+ let smallest = j;
815
+ if (left < k && heap[left].score < heap[smallest].score)
816
+ smallest = left;
817
+ if (right < k && heap[right].score < heap[smallest].score)
818
+ smallest = right;
819
+ if (smallest === j)
820
+ break;
821
+ [heap[j], heap[smallest]] = [heap[smallest], heap[j]];
822
+ j = smallest;
823
+ }
824
+ }
825
+ }
826
+ // Extract and sort descending
827
+ return heap.sort((a, b) => b.score - a.score).map(h => h.idx);
828
+ }
829
+ /**
830
+ * Flash Attention-style search
831
+ * Combines batch similarity, softmax, and top-k in one pass
832
+ * Returns indices and attention weights
833
+ */
834
+ export function flashAttentionSearch(query, vectors, options = {}) {
835
+ const { k = 10, temperature = 1.0, threshold = 0 } = options;
836
+ // Compute batch similarity
837
+ const scores = batchCosineSim(query, vectors);
838
+ // Get top-k indices
839
+ const indices = topKIndices(scores, k);
840
+ // Filter by threshold
841
+ const filtered = indices.filter(i => scores[i] >= threshold);
842
+ // Extract scores for filtered results
843
+ const topScores = new Float32Array(filtered.length);
844
+ for (let i = 0; i < filtered.length; i++) {
845
+ topScores[i] = scores[filtered[i]];
846
+ }
847
+ // Compute attention weights (softmax over top-k)
848
+ const weights = softmaxAttention(topScores, temperature);
849
+ return { indices: filtered, scores: topScores, weights };
850
+ }
851
+ // ============================================================================
852
+ // METADATA AND INITIALIZATION
853
+ // ============================================================================
854
+ /**
855
+ * Initial metadata to insert after schema creation
856
+ */
857
+ export function getInitialMetadata(backend) {
858
+ return `
859
+ INSERT OR REPLACE INTO metadata (key, value) VALUES
860
+ ('schema_version', '3.0.0'),
861
+ ('backend', '${backend}'),
862
+ ('created_at', '${new Date().toISOString()}'),
863
+ ('sql_js', 'true'),
864
+ ('vector_embeddings', 'enabled'),
865
+ ('pattern_learning', 'enabled'),
866
+ ('temporal_decay', 'enabled'),
867
+ ('hnsw_indexing', 'enabled');
868
+
869
+ -- Create default vector index configuration. Dimension matches the default
870
+ -- ONNX embedding model (Xenova/all-MiniLM-L6-v2, 384-dim); HNSW rejects
871
+ -- inserts whose dim does not match this row, so a 768 here breaks every
872
+ -- memory_store --vector and memory_search on a fresh install (#1947).
873
+ INSERT OR IGNORE INTO vector_indexes (id, name, dimensions) VALUES
874
+ ('default', 'default', 384),
875
+ ('patterns', 'patterns', 384);
876
+ `;
877
+ }
878
+ /**
879
+ * Ensure memory_entries table has all required columns
880
+ * Adds missing columns for older databases (e.g., 'content' column)
881
+ */
882
+ export async function ensureSchemaColumns(dbPath) {
883
+ const columnsAdded = [];
884
+ try {
885
+ if (!fs.existsSync(dbPath)) {
886
+ return { success: true, columnsAdded: [] };
887
+ }
888
+ const initSqlJs = (await import('sql.js')).default;
889
+ const SQL = await initSqlJs();
890
+ const fileBuffer = readFileMaybeEncrypted(dbPath, null);
891
+ const db = new SQL.Database(fileBuffer);
892
+ // Get current columns in memory_entries
893
+ const tableInfo = db.exec("PRAGMA table_info(memory_entries)");
894
+ const existingColumns = new Set(tableInfo[0]?.values?.map(row => row[1]) || []);
895
+ // Required columns that may be missing in older schemas
896
+ // Issue #977: 'type' column was missing from this list, causing store failures on older DBs
897
+ const requiredColumns = [
898
+ { name: 'content', definition: "content TEXT DEFAULT ''" },
899
+ { name: 'type', definition: "type TEXT DEFAULT 'semantic'" },
900
+ { name: 'embedding', definition: 'embedding TEXT' },
901
+ { name: 'embedding_model', definition: "embedding_model TEXT DEFAULT 'local'" },
902
+ { name: 'embedding_dimensions', definition: 'embedding_dimensions INTEGER' },
903
+ { name: 'tags', definition: 'tags TEXT' },
904
+ { name: 'metadata', definition: 'metadata TEXT' },
905
+ { name: 'owner_id', definition: 'owner_id TEXT' },
906
+ { name: 'expires_at', definition: 'expires_at INTEGER' },
907
+ { name: 'last_accessed_at', definition: 'last_accessed_at INTEGER' },
908
+ { name: 'access_count', definition: 'access_count INTEGER DEFAULT 0' },
909
+ { name: 'status', definition: "status TEXT DEFAULT 'active'" }
910
+ ];
911
+ let modified = false;
912
+ for (const col of requiredColumns) {
913
+ if (!existingColumns.has(col.name)) {
914
+ try {
915
+ db.run(`ALTER TABLE memory_entries ADD COLUMN ${col.definition}`);
916
+ columnsAdded.push(col.name);
917
+ modified = true;
918
+ }
919
+ catch (e) {
920
+ // Column might already exist or other error - continue
921
+ }
922
+ }
923
+ }
924
+ if (modified) {
925
+ // Save updated database
926
+ const data = db.export();
927
+ writeFileRestricted(dbPath, Buffer.from(data), { encrypt: true });
928
+ }
929
+ db.close();
930
+ return { success: true, columnsAdded };
931
+ }
932
+ catch (error) {
933
+ return {
934
+ success: false,
935
+ columnsAdded,
936
+ error: error instanceof Error ? error.message : String(error)
937
+ };
938
+ }
939
+ }
940
+ /**
941
+ * Check for legacy database installations and migrate if needed
942
+ */
943
+ export async function checkAndMigrateLegacy(options) {
944
+ const { dbPath, verbose = false } = options;
945
+ // Check for legacy locations
946
+ const legacyPaths = [
947
+ path.join(process.cwd(), 'memory.db'),
948
+ path.join(process.cwd(), '.claude/memory.db'),
949
+ path.join(process.cwd(), 'data/memory.db'),
950
+ path.join(process.cwd(), '.claude-flow/memory.db')
951
+ ];
952
+ for (const legacyPath of legacyPaths) {
953
+ if (fs.existsSync(legacyPath) && legacyPath !== dbPath) {
954
+ try {
955
+ const initSqlJs = (await import('sql.js')).default;
956
+ const SQL = await initSqlJs();
957
+ const legacyBuffer = fs.readFileSync(legacyPath);
958
+ const legacyDb = new SQL.Database(legacyBuffer);
959
+ // Check if it has data
960
+ const countResult = legacyDb.exec('SELECT COUNT(*) FROM memory_entries');
961
+ const count = countResult[0]?.values[0]?.[0] || 0;
962
+ // Get version if available
963
+ let version = 'unknown';
964
+ try {
965
+ const versionResult = legacyDb.exec("SELECT value FROM metadata WHERE key='schema_version'");
966
+ version = versionResult[0]?.values[0]?.[0] || 'unknown';
967
+ }
968
+ catch { /* no metadata table */ }
969
+ legacyDb.close();
970
+ if (count > 0) {
971
+ return {
972
+ needsMigration: true,
973
+ legacyVersion: version,
974
+ legacyEntries: count
975
+ };
976
+ }
977
+ }
978
+ catch {
979
+ // Not a valid SQLite database, skip
980
+ }
981
+ }
982
+ }
983
+ return { needsMigration: false };
984
+ }
985
+ /**
986
+ * ADR-053: Activate ControllerRegistry so AgentDB v3 controllers
987
+ * (ReasoningBank, SkillLibrary, ExplainableRecall, etc.) are instantiated.
988
+ *
989
+ * Uses the memory-bridge's getControllerRegistry() which lazily creates
990
+ * a singleton ControllerRegistry and initializes it with the given dbPath.
991
+ * After this call, all enabled controllers are ready for immediate use.
992
+ *
993
+ * Failures are isolated: if @claude-flow/memory or agentdb is not installed,
994
+ * this returns an empty result without throwing.
995
+ */
996
+ async function activateControllerRegistry(dbPath, verbose) {
997
+ const startTime = performance.now();
998
+ const activated = [];
999
+ const failed = [];
1000
+ try {
1001
+ const bridge = await getBridge();
1002
+ if (!bridge) {
1003
+ return { activated, failed, initTimeMs: performance.now() - startTime };
1004
+ }
1005
+ const registry = await bridge.getControllerRegistry(dbPath);
1006
+ if (!registry) {
1007
+ return { activated, failed, initTimeMs: performance.now() - startTime };
1008
+ }
1009
+ // Collect controller status from the registry
1010
+ if (typeof registry.listControllers === 'function') {
1011
+ const controllers = registry.listControllers();
1012
+ for (const ctrl of controllers) {
1013
+ if (ctrl.enabled) {
1014
+ activated.push(ctrl.name);
1015
+ }
1016
+ else {
1017
+ failed.push(ctrl.name);
1018
+ }
1019
+ }
1020
+ }
1021
+ if (verbose && activated.length > 0) {
1022
+ console.log(`ControllerRegistry: ${activated.length} controllers activated`);
1023
+ }
1024
+ }
1025
+ catch {
1026
+ // ControllerRegistry activation is best-effort
1027
+ }
1028
+ return { activated, failed, initTimeMs: performance.now() - startTime };
1029
+ }
1030
+ /**
1031
+ * Initialize the memory database properly using sql.js
1032
+ */
1033
+ export async function initializeMemoryDatabase(options) {
1034
+ const { backend = 'hybrid', dbPath: customPath, force = false, verbose = false, migrate = true } = options;
1035
+ const swarmDir = getMemoryRoot();
1036
+ const dbPath = customPath || path.join(swarmDir, 'memory.db');
1037
+ const dbDir = path.dirname(dbPath);
1038
+ try {
1039
+ // Create directory if needed
1040
+ if (!fs.existsSync(dbDir)) {
1041
+ fs.mkdirSync(dbDir, { recursive: true });
1042
+ }
1043
+ // Check for legacy installations
1044
+ if (migrate) {
1045
+ const legacyCheck = await checkAndMigrateLegacy({ dbPath, verbose });
1046
+ if (legacyCheck.needsMigration && verbose) {
1047
+ console.log(`Found legacy database (v${legacyCheck.legacyVersion}) with ${legacyCheck.legacyEntries} entries`);
1048
+ }
1049
+ }
1050
+ // Check existing database
1051
+ // #1791.6 — Idempotent re-init: if the database already exists and the
1052
+ // caller did not pass --force, treat it as a successful no-op instead of
1053
+ // an error. Callers (CLI, MCP tools, embeddings) can branch on
1054
+ // `alreadyExists` if they want a different message; previous behavior
1055
+ // surfaced an `[ERROR]` and a "Initialization failed" spinner even when
1056
+ // the existing DB was perfectly healthy.
1057
+ if (fs.existsSync(dbPath) && !force) {
1058
+ return {
1059
+ success: true,
1060
+ alreadyExists: true,
1061
+ backend,
1062
+ dbPath,
1063
+ schemaVersion: '3.0.0',
1064
+ tablesCreated: [],
1065
+ indexesCreated: [],
1066
+ features: {
1067
+ vectorEmbeddings: false,
1068
+ patternLearning: false,
1069
+ temporalDecay: false,
1070
+ hnswIndexing: false,
1071
+ migrationTracking: false
1072
+ }
1073
+ };
1074
+ }
1075
+ // Try to use sql.js (WASM SQLite)
1076
+ let db;
1077
+ let usedSqlJs = false;
1078
+ try {
1079
+ // Dynamic import of sql.js
1080
+ const initSqlJs = (await import('sql.js')).default;
1081
+ const SQL = await initSqlJs();
1082
+ // Load existing database or create new
1083
+ if (fs.existsSync(dbPath) && force) {
1084
+ fs.unlinkSync(dbPath);
1085
+ }
1086
+ db = new SQL.Database();
1087
+ usedSqlJs = true;
1088
+ }
1089
+ catch (e) {
1090
+ // sql.js not available, fall back to writing schema file
1091
+ if (verbose) {
1092
+ console.log('sql.js not available, writing schema file for later initialization');
1093
+ }
1094
+ }
1095
+ if (usedSqlJs && db) {
1096
+ // Execute schema
1097
+ db.run(MEMORY_SCHEMA_V3);
1098
+ // Insert initial metadata
1099
+ db.run(getInitialMetadata(backend));
1100
+ // Save to file
1101
+ const data = db.export();
1102
+ const buffer = Buffer.from(data);
1103
+ writeFileRestricted(dbPath, buffer, { encrypt: true });
1104
+ // Close database
1105
+ db.close();
1106
+ // Also create schema file for reference
1107
+ const schemaPath = path.join(dbDir, 'schema.sql');
1108
+ fs.writeFileSync(schemaPath, MEMORY_SCHEMA_V3 + '\n' + getInitialMetadata(backend));
1109
+ // ADR-053: Activate ControllerRegistry so controllers (ReasoningBank,
1110
+ // SkillLibrary, ExplainableRecall, etc.) are instantiated during init
1111
+ const controllerResult = await activateControllerRegistry(dbPath, verbose);
1112
+ return {
1113
+ success: true,
1114
+ backend,
1115
+ dbPath,
1116
+ schemaVersion: '3.0.0',
1117
+ tablesCreated: [
1118
+ 'memory_entries',
1119
+ 'patterns',
1120
+ 'pattern_history',
1121
+ 'trajectories',
1122
+ 'trajectory_steps',
1123
+ 'migration_state',
1124
+ 'sessions',
1125
+ 'vector_indexes',
1126
+ 'metadata'
1127
+ ],
1128
+ indexesCreated: [
1129
+ 'idx_memory_namespace',
1130
+ 'idx_memory_key',
1131
+ 'idx_memory_type',
1132
+ 'idx_memory_status',
1133
+ 'idx_memory_created',
1134
+ 'idx_memory_accessed',
1135
+ 'idx_memory_owner',
1136
+ 'idx_patterns_type',
1137
+ 'idx_patterns_confidence',
1138
+ 'idx_patterns_status',
1139
+ 'idx_patterns_last_matched',
1140
+ 'idx_pattern_history_pattern',
1141
+ 'idx_steps_trajectory'
1142
+ ],
1143
+ features: {
1144
+ vectorEmbeddings: true,
1145
+ patternLearning: true,
1146
+ temporalDecay: true,
1147
+ hnswIndexing: true,
1148
+ migrationTracking: true
1149
+ },
1150
+ controllers: controllerResult,
1151
+ };
1152
+ }
1153
+ else {
1154
+ // Fall back to schema file approach
1155
+ const schemaPath = path.join(dbDir, 'schema.sql');
1156
+ fs.writeFileSync(schemaPath, MEMORY_SCHEMA_V3 + '\n' + getInitialMetadata(backend));
1157
+ // Create minimal valid SQLite file
1158
+ const sqliteHeader = Buffer.alloc(4096, 0);
1159
+ // SQLite format 3 header
1160
+ Buffer.from('SQLite format 3\0').copy(sqliteHeader, 0);
1161
+ sqliteHeader[16] = 0x10; // page size high byte (4096)
1162
+ sqliteHeader[17] = 0x00; // page size low byte
1163
+ sqliteHeader[18] = 0x01; // file format write version
1164
+ sqliteHeader[19] = 0x01; // file format read version
1165
+ sqliteHeader[24] = 0x00; // max embedded payload
1166
+ sqliteHeader[25] = 0x40;
1167
+ sqliteHeader[26] = 0x20; // min embedded payload
1168
+ sqliteHeader[27] = 0x20; // leaf payload
1169
+ writeFileRestricted(dbPath, sqliteHeader, { encrypt: true });
1170
+ // ADR-053: Activate ControllerRegistry even on fallback path
1171
+ const controllerResult = await activateControllerRegistry(dbPath, verbose);
1172
+ return {
1173
+ success: true,
1174
+ backend,
1175
+ dbPath,
1176
+ schemaVersion: '3.0.0',
1177
+ tablesCreated: [
1178
+ 'memory_entries (pending)',
1179
+ 'patterns (pending)',
1180
+ 'pattern_history (pending)',
1181
+ 'trajectories (pending)',
1182
+ 'trajectory_steps (pending)',
1183
+ 'migration_state (pending)',
1184
+ 'sessions (pending)',
1185
+ 'vector_indexes (pending)',
1186
+ 'metadata (pending)'
1187
+ ],
1188
+ indexesCreated: [],
1189
+ features: {
1190
+ vectorEmbeddings: true,
1191
+ patternLearning: true,
1192
+ temporalDecay: true,
1193
+ hnswIndexing: true,
1194
+ migrationTracking: true
1195
+ },
1196
+ controllers: controllerResult,
1197
+ };
1198
+ }
1199
+ }
1200
+ catch (error) {
1201
+ return {
1202
+ success: false,
1203
+ backend,
1204
+ dbPath,
1205
+ schemaVersion: '3.0.0',
1206
+ tablesCreated: [],
1207
+ indexesCreated: [],
1208
+ features: {
1209
+ vectorEmbeddings: false,
1210
+ patternLearning: false,
1211
+ temporalDecay: false,
1212
+ hnswIndexing: false,
1213
+ migrationTracking: false
1214
+ },
1215
+ error: error instanceof Error ? error.message : String(error)
1216
+ };
1217
+ }
1218
+ }
1219
+ /**
1220
+ * Check if memory database is properly initialized
1221
+ */
1222
+ export async function checkMemoryInitialization(dbPath) {
1223
+ const swarmDir = getMemoryRoot();
1224
+ const path_ = dbPath || path.join(swarmDir, 'memory.db');
1225
+ if (!fs.existsSync(path_)) {
1226
+ return { initialized: false };
1227
+ }
1228
+ try {
1229
+ // Try to load with sql.js
1230
+ const initSqlJs = (await import('sql.js')).default;
1231
+ const SQL = await initSqlJs();
1232
+ const fileBuffer = fs.readFileSync(path_);
1233
+ const db = new SQL.Database(fileBuffer);
1234
+ // Check for metadata table
1235
+ const tables = db.exec("SELECT name FROM sqlite_master WHERE type='table'");
1236
+ const tableNames = tables[0]?.values?.map(v => v[0]) || [];
1237
+ // Get version
1238
+ let version = 'unknown';
1239
+ let backend = 'unknown';
1240
+ try {
1241
+ const versionResult = db.exec("SELECT value FROM metadata WHERE key='schema_version'");
1242
+ version = versionResult[0]?.values[0]?.[0] || 'unknown';
1243
+ const backendResult = db.exec("SELECT value FROM metadata WHERE key='backend'");
1244
+ backend = backendResult[0]?.values[0]?.[0] || 'unknown';
1245
+ }
1246
+ catch {
1247
+ // Metadata table might not exist
1248
+ }
1249
+ db.close();
1250
+ return {
1251
+ initialized: true,
1252
+ version,
1253
+ backend,
1254
+ features: {
1255
+ vectorEmbeddings: tableNames.includes('vector_indexes'),
1256
+ patternLearning: tableNames.includes('patterns'),
1257
+ temporalDecay: tableNames.includes('pattern_history')
1258
+ },
1259
+ tables: tableNames
1260
+ };
1261
+ }
1262
+ catch {
1263
+ // Could not read database
1264
+ return { initialized: false };
1265
+ }
1266
+ }
1267
+ /**
1268
+ * Apply temporal decay to patterns
1269
+ * Reduces confidence of patterns that haven't been used recently
1270
+ */
1271
+ export async function applyTemporalDecay(dbPath) {
1272
+ const swarmDir = getMemoryRoot();
1273
+ const path_ = dbPath || path.join(swarmDir, 'memory.db');
1274
+ try {
1275
+ const initSqlJs = (await import('sql.js')).default;
1276
+ const SQL = await initSqlJs();
1277
+ const fileBuffer = fs.readFileSync(path_);
1278
+ const db = new SQL.Database(fileBuffer);
1279
+ // Apply decay: confidence *= exp(-decay_rate * days_since_last_use)
1280
+ const now = Date.now();
1281
+ const decayQuery = `
1282
+ UPDATE patterns
1283
+ SET
1284
+ confidence = confidence * (1.0 - decay_rate * ((? - COALESCE(last_matched_at, created_at)) / 86400000.0)),
1285
+ updated_at = ?
1286
+ WHERE status = 'active'
1287
+ AND confidence > 0.1
1288
+ AND (? - COALESCE(last_matched_at, created_at)) > 86400000
1289
+ `;
1290
+ db.run(decayQuery, [now, now, now]);
1291
+ const changes = db.getRowsModified();
1292
+ // Save
1293
+ const data = db.export();
1294
+ fs.writeFileSync(path_, Buffer.from(data));
1295
+ db.close();
1296
+ return {
1297
+ success: true,
1298
+ patternsDecayed: changes
1299
+ };
1300
+ }
1301
+ catch (error) {
1302
+ return {
1303
+ success: false,
1304
+ patternsDecayed: 0,
1305
+ error: error instanceof Error ? error.message : String(error)
1306
+ };
1307
+ }
1308
+ }
1309
+ let embeddingModelState = null;
1310
+ /**
1311
+ * Lazy load ONNX embedding model
1312
+ * Only loads when first embedding is requested
1313
+ */
1314
+ export async function loadEmbeddingModel(options) {
1315
+ const { verbose = false } = options || {};
1316
+ const startTime = Date.now();
1317
+ // Already loaded
1318
+ if (embeddingModelState?.loaded) {
1319
+ return {
1320
+ success: true,
1321
+ dimensions: embeddingModelState.dimensions,
1322
+ modelName: 'cached',
1323
+ loadTime: 0
1324
+ };
1325
+ }
1326
+ // ADR-053: Try AgentDB v3 bridge first
1327
+ const bridge = await getBridge();
1328
+ if (bridge) {
1329
+ const bridgeResult = await bridge.bridgeLoadEmbeddingModel();
1330
+ if (bridgeResult && bridgeResult.success) {
1331
+ // Mark local state as loaded too so subsequent calls use cache
1332
+ embeddingModelState = {
1333
+ loaded: true,
1334
+ model: null, // Bridge handles embedding
1335
+ tokenizer: null,
1336
+ dimensions: bridgeResult.dimensions
1337
+ };
1338
+ return bridgeResult;
1339
+ }
1340
+ }
1341
+ try {
1342
+ // ADR-094: prefer @huggingface/transformers (clears protobufjs <7.5.5
1343
+ // critical RCE chain), fall back to legacy @xenova/transformers.
1344
+ // Inlined here rather than depending on @claude-flow/embeddings to
1345
+ // avoid a circular optional-dep at install time; the logic mirrors
1346
+ // @claude-flow/embeddings/src/transformers-loader.ts.
1347
+ let transformersSource = null;
1348
+ let pipelineFn = null;
1349
+ {
1350
+ const tryLoad = async (specifier) => {
1351
+ try {
1352
+ return (await import(specifier));
1353
+ }
1354
+ catch {
1355
+ return null;
1356
+ }
1357
+ };
1358
+ const hf = await tryLoad('@huggingface/transformers');
1359
+ if (hf && typeof hf.pipeline === 'function') {
1360
+ pipelineFn = hf.pipeline;
1361
+ transformersSource = '@huggingface/transformers';
1362
+ }
1363
+ else {
1364
+ const xen = await tryLoad('@xenova/transformers');
1365
+ if (xen && typeof xen.pipeline === 'function') {
1366
+ pipelineFn = xen.pipeline;
1367
+ transformersSource = '@xenova/transformers';
1368
+ }
1369
+ }
1370
+ }
1371
+ if (pipelineFn && transformersSource) {
1372
+ if (verbose) {
1373
+ console.log(`Loading ONNX embedding model via ${transformersSource} (all-MiniLM-L6-v2)...`);
1374
+ }
1375
+ const embedder = await pipelineFn('feature-extraction', 'Xenova/all-MiniLM-L6-v2');
1376
+ embeddingModelState = {
1377
+ loaded: true,
1378
+ model: embedder,
1379
+ tokenizer: null,
1380
+ dimensions: 384 // MiniLM-L6 produces 384-dim vectors
1381
+ };
1382
+ return {
1383
+ success: true,
1384
+ dimensions: 384,
1385
+ modelName: 'Xenova/all-MiniLM-L6-v2',
1386
+ loadTime: Date.now() - startTime
1387
+ };
1388
+ }
1389
+ // Fallback: Check for agentic-flow ReasoningBank embeddings (v3)
1390
+ const reasoningBank = await import('agentic-flow/reasoningbank').catch(() => null);
1391
+ if (reasoningBank?.computeEmbedding) {
1392
+ if (verbose) {
1393
+ console.log('Loading agentic-flow ReasoningBank embedding model...');
1394
+ }
1395
+ embeddingModelState = {
1396
+ loaded: true,
1397
+ model: { embed: reasoningBank.computeEmbedding },
1398
+ tokenizer: null,
1399
+ dimensions: 768
1400
+ };
1401
+ return {
1402
+ success: true,
1403
+ dimensions: 768,
1404
+ modelName: 'agentic-flow/reasoningbank',
1405
+ loadTime: Date.now() - startTime
1406
+ };
1407
+ }
1408
+ // Fallback: Check for ruvector ONNX embedder (bundled MiniLM-L6-v2 since v0.2.15)
1409
+ // v0.2.16: LoRA B=0 fix makes AdaptiveEmbedder safe (identity when untrained)
1410
+ // Note: isReady() returns false until first embed() call (lazy init), so we
1411
+ // skip the isReady() gate and verify with a probe embed instead.
1412
+ const ruvector = await import('ruvector').catch(() => null);
1413
+ if (ruvector?.initOnnxEmbedder) {
1414
+ try {
1415
+ await ruvector.initOnnxEmbedder();
1416
+ // Fallback: OptimizedOnnxEmbedder (raw ONNX, lazy-inits on first embed)
1417
+ const onnxEmb = ruvector.getOptimizedOnnxEmbedder?.();
1418
+ if (onnxEmb?.embed) {
1419
+ // Probe embed to trigger lazy ONNX init and verify it works
1420
+ const probe = await onnxEmb.embed('test');
1421
+ if (probe && probe.length > 0 && (Array.isArray(probe) ? probe.some((v) => v !== 0) : true)) {
1422
+ if (verbose) {
1423
+ console.log(`Loading ruvector ONNX embedder (all-MiniLM-L6-v2, ${probe.length}d)...`);
1424
+ }
1425
+ embeddingModelState = {
1426
+ loaded: true,
1427
+ model: (text) => onnxEmb.embed(text),
1428
+ tokenizer: null,
1429
+ dimensions: probe.length || 384
1430
+ };
1431
+ return {
1432
+ success: true,
1433
+ dimensions: probe.length || 384,
1434
+ modelName: 'ruvector/onnx',
1435
+ loadTime: Date.now() - startTime
1436
+ };
1437
+ }
1438
+ }
1439
+ }
1440
+ catch {
1441
+ // ruvector ONNX init failed, continue to next fallback
1442
+ }
1443
+ }
1444
+ // Legacy fallback: Check for agentic-flow core embeddings
1445
+ const agenticFlow = await import('agentic-flow').catch(() => null);
1446
+ if (agenticFlow && agenticFlow.embeddings) {
1447
+ if (verbose) {
1448
+ console.log('Loading agentic-flow embedding model...');
1449
+ }
1450
+ embeddingModelState = {
1451
+ loaded: true,
1452
+ model: agenticFlow.embeddings,
1453
+ tokenizer: null,
1454
+ dimensions: 768
1455
+ };
1456
+ return {
1457
+ success: true,
1458
+ dimensions: 768,
1459
+ modelName: 'agentic-flow',
1460
+ loadTime: Date.now() - startTime
1461
+ };
1462
+ }
1463
+ // No ONNX model available - use fallback
1464
+ embeddingModelState = {
1465
+ loaded: true,
1466
+ model: null, // Will use simple hash-based fallback
1467
+ tokenizer: null,
1468
+ dimensions: 128 // Smaller fallback dimensions
1469
+ };
1470
+ return {
1471
+ success: true,
1472
+ dimensions: 128,
1473
+ modelName: 'hash-fallback',
1474
+ loadTime: Date.now() - startTime
1475
+ };
1476
+ }
1477
+ catch (error) {
1478
+ return {
1479
+ success: false,
1480
+ dimensions: 0,
1481
+ modelName: 'none',
1482
+ error: error instanceof Error ? error.message : String(error)
1483
+ };
1484
+ }
1485
+ }
1486
+ /**
1487
+ * Generate real embedding for text
1488
+ * Uses ONNX model if available, falls back to deterministic hash
1489
+ */
1490
+ export async function generateEmbedding(text) {
1491
+ // ADR-053: Try AgentDB v3 bridge first
1492
+ const bridge = await getBridge();
1493
+ if (bridge) {
1494
+ const bridgeResult = await bridge.bridgeGenerateEmbedding(text);
1495
+ if (bridgeResult)
1496
+ return bridgeResult;
1497
+ }
1498
+ // Ensure model is loaded
1499
+ if (!embeddingModelState?.loaded) {
1500
+ await loadEmbeddingModel();
1501
+ }
1502
+ const state = embeddingModelState;
1503
+ // Use ONNX model if available
1504
+ if (state.model && typeof state.model === 'function') {
1505
+ try {
1506
+ const output = await state.model(text, { pooling: 'mean', normalize: true });
1507
+ // Handle both @xenova/transformers (output.data) and ruvector (plain array) formats
1508
+ const embedding = output?.data
1509
+ ? Array.from(output.data)
1510
+ : Array.isArray(output) ? output : null;
1511
+ if (embedding) {
1512
+ return {
1513
+ embedding,
1514
+ dimensions: embedding.length,
1515
+ model: 'onnx'
1516
+ };
1517
+ }
1518
+ }
1519
+ catch {
1520
+ // Fall through to fallback
1521
+ }
1522
+ }
1523
+ // Deterministic hash-based fallback (for testing/demo without ONNX)
1524
+ const embedding = generateHashEmbedding(text, state.dimensions);
1525
+ return {
1526
+ embedding,
1527
+ dimensions: state.dimensions,
1528
+ model: 'hash-fallback'
1529
+ };
1530
+ }
1531
+ /**
1532
+ * Generate embeddings for multiple texts
1533
+ * Uses parallel execution for API-based providers (2-4x faster)
1534
+ * Note: Local ONNX inference is CPU-bound, so parallelism has limited benefit
1535
+ *
1536
+ * @param texts - Array of texts to embed
1537
+ * @param options - Batch options
1538
+ * @returns Array of embedding results with timing info
1539
+ */
1540
+ export async function generateBatchEmbeddings(texts, options) {
1541
+ const { concurrency = texts.length, onProgress } = options || {};
1542
+ const startTime = Date.now();
1543
+ // Ensure model is loaded first (prevents cold start in parallel)
1544
+ if (!embeddingModelState?.loaded) {
1545
+ await loadEmbeddingModel();
1546
+ }
1547
+ // Process in parallel with optional concurrency limit
1548
+ if (concurrency >= texts.length) {
1549
+ // Full parallelism
1550
+ const embeddings = await Promise.all(texts.map(async (text, i) => {
1551
+ const result = await generateEmbedding(text);
1552
+ onProgress?.(i + 1, texts.length);
1553
+ return { text, ...result };
1554
+ }));
1555
+ const totalTime = Date.now() - startTime;
1556
+ return {
1557
+ results: embeddings,
1558
+ totalTime,
1559
+ avgTime: totalTime / texts.length
1560
+ };
1561
+ }
1562
+ // Limited concurrency using chunking
1563
+ const results = [];
1564
+ let completed = 0;
1565
+ for (let i = 0; i < texts.length; i += concurrency) {
1566
+ const chunk = texts.slice(i, i + concurrency);
1567
+ const chunkResults = await Promise.all(chunk.map(async (text) => {
1568
+ const result = await generateEmbedding(text);
1569
+ completed++;
1570
+ onProgress?.(completed, texts.length);
1571
+ return { text, ...result };
1572
+ }));
1573
+ results.push(...chunkResults);
1574
+ }
1575
+ const totalTime = Date.now() - startTime;
1576
+ return {
1577
+ results,
1578
+ totalTime,
1579
+ avgTime: totalTime / texts.length
1580
+ };
1581
+ }
1582
+ /**
1583
+ * Generate deterministic hash-based embedding
1584
+ * Not semantic, but deterministic and useful for testing
1585
+ */
1586
+ function generateHashEmbedding(text, dimensions) {
1587
+ const embedding = new Array(dimensions).fill(0);
1588
+ // Simple hash-based approach for reproducibility
1589
+ const words = text.toLowerCase().split(/\s+/);
1590
+ for (let i = 0; i < words.length; i++) {
1591
+ const word = words[i];
1592
+ for (let j = 0; j < word.length; j++) {
1593
+ const charCode = word.charCodeAt(j);
1594
+ const idx = (charCode * (i + 1) * (j + 1)) % dimensions;
1595
+ embedding[idx] += Math.sin(charCode * 0.1) * 0.1;
1596
+ }
1597
+ }
1598
+ // Normalize to unit vector
1599
+ const magnitude = Math.sqrt(embedding.reduce((sum, v) => sum + v * v, 0)) || 1;
1600
+ return embedding.map(v => v / magnitude);
1601
+ }
1602
+ /**
1603
+ * Verify memory initialization works correctly
1604
+ * Tests: write, read, search, patterns
1605
+ */
1606
+ export async function verifyMemoryInit(dbPath, options) {
1607
+ const { verbose = false } = options || {};
1608
+ const tests = [];
1609
+ try {
1610
+ const initSqlJs = (await import('sql.js')).default;
1611
+ const SQL = await initSqlJs();
1612
+ const fs = await import('fs');
1613
+ // Load database
1614
+ const fileBuffer = readFileMaybeEncrypted(dbPath, null);
1615
+ const db = new SQL.Database(fileBuffer);
1616
+ // Test 1: Schema verification
1617
+ const schemaStart = Date.now();
1618
+ const tables = db.exec("SELECT name FROM sqlite_master WHERE type='table'");
1619
+ const tableNames = tables[0]?.values?.map(v => v[0]) || [];
1620
+ const expectedTables = ['memory_entries', 'patterns', 'metadata', 'vector_indexes'];
1621
+ const missingTables = expectedTables.filter(t => !tableNames.includes(t));
1622
+ tests.push({
1623
+ name: 'Schema verification',
1624
+ passed: missingTables.length === 0,
1625
+ details: missingTables.length > 0 ? `Missing: ${missingTables.join(', ')}` : `${tableNames.length} tables found`,
1626
+ duration: Date.now() - schemaStart
1627
+ });
1628
+ // Test 2: Write entry
1629
+ const writeStart = Date.now();
1630
+ const testId = `test_${Date.now()}`;
1631
+ const testKey = 'verification_test';
1632
+ const testValue = 'This is a verification test entry for memory initialization';
1633
+ try {
1634
+ db.run(`
1635
+ INSERT INTO memory_entries (id, key, namespace, content, type, created_at, updated_at)
1636
+ VALUES (?, ?, 'test', ?, 'semantic', ?, ?)
1637
+ `, [testId, testKey, testValue, Date.now(), Date.now()]);
1638
+ tests.push({
1639
+ name: 'Write entry',
1640
+ passed: true,
1641
+ details: 'Entry written successfully',
1642
+ duration: Date.now() - writeStart
1643
+ });
1644
+ }
1645
+ catch (e) {
1646
+ tests.push({
1647
+ name: 'Write entry',
1648
+ passed: false,
1649
+ details: e instanceof Error ? e.message : 'Write failed',
1650
+ duration: Date.now() - writeStart
1651
+ });
1652
+ }
1653
+ // Test 3: Read entry
1654
+ const readStart = Date.now();
1655
+ try {
1656
+ const result = db.exec(`SELECT content FROM memory_entries WHERE id = ?`, [testId]);
1657
+ const content = result[0]?.values[0]?.[0];
1658
+ tests.push({
1659
+ name: 'Read entry',
1660
+ passed: content === testValue,
1661
+ details: content === testValue ? 'Content matches' : 'Content mismatch',
1662
+ duration: Date.now() - readStart
1663
+ });
1664
+ }
1665
+ catch (e) {
1666
+ tests.push({
1667
+ name: 'Read entry',
1668
+ passed: false,
1669
+ details: e instanceof Error ? e.message : 'Read failed',
1670
+ duration: Date.now() - readStart
1671
+ });
1672
+ }
1673
+ // Test 4: Write with embedding
1674
+ const embeddingStart = Date.now();
1675
+ try {
1676
+ const { embedding, dimensions, model } = await generateEmbedding(testValue);
1677
+ const embeddingJson = JSON.stringify(embedding);
1678
+ db.run(`
1679
+ UPDATE memory_entries
1680
+ SET embedding = ?, embedding_dimensions = ?, embedding_model = ?
1681
+ WHERE id = ?
1682
+ `, [embeddingJson, dimensions, model, testId]);
1683
+ tests.push({
1684
+ name: 'Generate embedding',
1685
+ passed: true,
1686
+ details: `${dimensions}-dim vector (${model})`,
1687
+ duration: Date.now() - embeddingStart
1688
+ });
1689
+ }
1690
+ catch (e) {
1691
+ tests.push({
1692
+ name: 'Generate embedding',
1693
+ passed: false,
1694
+ details: e instanceof Error ? e.message : 'Embedding failed',
1695
+ duration: Date.now() - embeddingStart
1696
+ });
1697
+ }
1698
+ // Test 5: Pattern storage
1699
+ const patternStart = Date.now();
1700
+ try {
1701
+ const patternId = `pattern_${Date.now()}`;
1702
+ db.run(`
1703
+ INSERT INTO patterns (id, name, pattern_type, condition, action, confidence, created_at, updated_at)
1704
+ VALUES (?, 'test-pattern', 'task-routing', 'test condition', 'test action', 0.5, ?, ?)
1705
+ `, [patternId, Date.now(), Date.now()]);
1706
+ tests.push({
1707
+ name: 'Pattern storage',
1708
+ passed: true,
1709
+ details: 'Pattern stored with confidence scoring',
1710
+ duration: Date.now() - patternStart
1711
+ });
1712
+ // Cleanup test pattern
1713
+ db.run(`DELETE FROM patterns WHERE id = ?`, [patternId]);
1714
+ }
1715
+ catch (e) {
1716
+ tests.push({
1717
+ name: 'Pattern storage',
1718
+ passed: false,
1719
+ details: e instanceof Error ? e.message : 'Pattern storage failed',
1720
+ duration: Date.now() - patternStart
1721
+ });
1722
+ }
1723
+ // Test 6: Vector index configuration
1724
+ const indexStart = Date.now();
1725
+ try {
1726
+ const indexResult = db.exec(`SELECT name, dimensions, hnsw_m, hnsw_ef_construction FROM vector_indexes`);
1727
+ const indexes = indexResult[0]?.values || [];
1728
+ tests.push({
1729
+ name: 'Vector index config',
1730
+ passed: indexes.length > 0,
1731
+ details: `${indexes.length} indexes configured (HNSW M=16, ef=200)`,
1732
+ duration: Date.now() - indexStart
1733
+ });
1734
+ }
1735
+ catch (e) {
1736
+ tests.push({
1737
+ name: 'Vector index config',
1738
+ passed: false,
1739
+ details: e instanceof Error ? e.message : 'Index check failed',
1740
+ duration: Date.now() - indexStart
1741
+ });
1742
+ }
1743
+ // Cleanup test entry
1744
+ db.run(`DELETE FROM memory_entries WHERE id = ?`, [testId]);
1745
+ // Save changes
1746
+ const data = db.export();
1747
+ writeFileRestricted(dbPath, Buffer.from(data), { encrypt: true });
1748
+ db.close();
1749
+ const passed = tests.filter(t => t.passed).length;
1750
+ const failed = tests.filter(t => !t.passed).length;
1751
+ return {
1752
+ success: failed === 0,
1753
+ tests,
1754
+ summary: {
1755
+ passed,
1756
+ failed,
1757
+ total: tests.length
1758
+ }
1759
+ };
1760
+ }
1761
+ catch (error) {
1762
+ return {
1763
+ success: false,
1764
+ tests: [{
1765
+ name: 'Database access',
1766
+ passed: false,
1767
+ details: error instanceof Error ? error.message : 'Unknown error'
1768
+ }],
1769
+ summary: { passed: 0, failed: 1, total: 1 }
1770
+ };
1771
+ }
1772
+ }
1773
+ /**
1774
+ * Store an entry directly using sql.js
1775
+ * This bypasses MCP and writes directly to the database
1776
+ */
1777
+ export async function storeEntry(options) {
1778
+ // ADR-053: Try AgentDB v3 bridge first
1779
+ const bridge = await getBridge();
1780
+ if (bridge) {
1781
+ const bridgeResult = await bridge.bridgeStoreEntry(options);
1782
+ if (bridgeResult) {
1783
+ // Keep HNSW index in sync with bridge-stored entries
1784
+ if (bridgeResult.rawEmbedding && bridgeResult.success) {
1785
+ const ns = options.namespace || 'default';
1786
+ await addToHNSWIndex(bridgeResult.id, bridgeResult.rawEmbedding, {
1787
+ id: bridgeResult.id,
1788
+ key: options.key,
1789
+ namespace: ns,
1790
+ content: options.value,
1791
+ }).catch(() => { });
1792
+ }
1793
+ return bridgeResult;
1794
+ }
1795
+ }
1796
+ // Fallback: raw sql.js
1797
+ const { key, value, namespace = 'default', generateEmbeddingFlag = true, tags = [], ttl, dbPath: customPath, upsert = false } = options;
1798
+ const swarmDir = getMemoryRoot();
1799
+ const dbPath = customPath ? path.resolve(customPath) : path.join(swarmDir, 'memory.db');
1800
+ try {
1801
+ if (!fs.existsSync(dbPath)) {
1802
+ return { success: false, id: '', error: 'Database not initialized. Run: claude-flow memory init' };
1803
+ }
1804
+ // Ensure schema has all required columns (migration for older DBs)
1805
+ await ensureSchemaColumns(dbPath);
1806
+ const initSqlJs = (await import('sql.js')).default;
1807
+ const SQL = await initSqlJs();
1808
+ const fileBuffer = readFileMaybeEncrypted(dbPath, null);
1809
+ const db = new SQL.Database(fileBuffer);
1810
+ const id = `entry_${Date.now()}_${Math.random().toString(36).substring(7)}`;
1811
+ const now = Date.now();
1812
+ // Generate embedding if requested
1813
+ let embeddingJson = null;
1814
+ let embeddingDimensions = null;
1815
+ let embeddingModel = null;
1816
+ if (generateEmbeddingFlag && value.length > 0) {
1817
+ const embResult = await generateEmbedding(value);
1818
+ embeddingJson = JSON.stringify(embResult.embedding);
1819
+ embeddingDimensions = embResult.dimensions;
1820
+ embeddingModel = embResult.model;
1821
+ }
1822
+ // #1941: provision a `vector_indexes` row for this namespace before the
1823
+ // entry insert. The HNSW lookup uses this table to find which namespaces
1824
+ // are indexed — without a row, `memory_search({namespace:"X"})` returns
1825
+ // 0 even when memory_entries holds matching rows. INSERT OR IGNORE
1826
+ // preserves the existing `default` / `patterns` rows.
1827
+ try {
1828
+ db.run(`INSERT OR IGNORE INTO vector_indexes (id, name, dimensions) VALUES (?, ?, ?)`, [namespace, namespace, embeddingDimensions ?? 384]);
1829
+ }
1830
+ catch { /* vector_indexes may not exist on legacy DBs — fall through */ }
1831
+ // Insert or update entry (upsert mode uses REPLACE)
1832
+ const insertSql = upsert
1833
+ ? `INSERT OR REPLACE INTO memory_entries (
1834
+ id, key, namespace, content, type,
1835
+ embedding, embedding_dimensions, embedding_model,
1836
+ tags, metadata, created_at, updated_at, expires_at, status
1837
+ ) VALUES (?, ?, ?, ?, 'semantic', ?, ?, ?, ?, ?, ?, ?, ?, 'active')`
1838
+ : `INSERT INTO memory_entries (
1839
+ id, key, namespace, content, type,
1840
+ embedding, embedding_dimensions, embedding_model,
1841
+ tags, metadata, created_at, updated_at, expires_at, status
1842
+ ) VALUES (?, ?, ?, ?, 'semantic', ?, ?, ?, ?, ?, ?, ?, ?, 'active')`;
1843
+ db.run(insertSql, [
1844
+ id,
1845
+ key,
1846
+ namespace,
1847
+ value,
1848
+ embeddingJson,
1849
+ embeddingDimensions,
1850
+ embeddingModel,
1851
+ tags.length > 0 ? JSON.stringify(tags) : null,
1852
+ '{}',
1853
+ now,
1854
+ now,
1855
+ ttl ? now + (ttl * 1000) : null
1856
+ ]);
1857
+ // Save
1858
+ const data = db.export();
1859
+ writeFileRestricted(dbPath, Buffer.from(data), { encrypt: true });
1860
+ db.close();
1861
+ // Add to HNSW index for faster future searches
1862
+ if (embeddingJson) {
1863
+ const embResult = JSON.parse(embeddingJson);
1864
+ await addToHNSWIndex(id, embResult, {
1865
+ id,
1866
+ key,
1867
+ namespace,
1868
+ content: value
1869
+ });
1870
+ }
1871
+ return {
1872
+ success: true,
1873
+ id,
1874
+ embedding: embeddingJson ? { dimensions: embeddingDimensions, model: embeddingModel } : undefined
1875
+ };
1876
+ }
1877
+ catch (error) {
1878
+ return {
1879
+ success: false,
1880
+ id: '',
1881
+ error: error instanceof Error ? error.message : String(error)
1882
+ };
1883
+ }
1884
+ }
1885
+ /**
1886
+ * Search entries using sql.js with vector similarity
1887
+ * Uses HNSW index for 150x faster search when available
1888
+ */
1889
+ export async function searchEntries(options) {
1890
+ // ADR-053: Try AgentDB v3 bridge first
1891
+ const bridge = await getBridge();
1892
+ if (bridge) {
1893
+ const bridgeResult = await bridge.bridgeSearchEntries(options);
1894
+ if (bridgeResult)
1895
+ return bridgeResult;
1896
+ }
1897
+ // Fallback: raw sql.js
1898
+ const { query, namespace, limit = 10, threshold = 0.3, dbPath: customPath } = options;
1899
+ const effectiveNamespace = namespace || 'all';
1900
+ const swarmDir = getMemoryRoot();
1901
+ const dbPath = customPath ? path.resolve(customPath) : path.join(swarmDir, 'memory.db');
1902
+ const startTime = Date.now();
1903
+ try {
1904
+ if (!fs.existsSync(dbPath)) {
1905
+ return { success: false, results: [], searchTime: 0, error: 'Database not found' };
1906
+ }
1907
+ // Ensure schema has all required columns (migration for older DBs)
1908
+ await ensureSchemaColumns(dbPath);
1909
+ // Generate query embedding
1910
+ const queryEmb = await generateEmbedding(query);
1911
+ const queryEmbedding = queryEmb.embedding;
1912
+ // Try RaBitQ pre-filter first (32× compressed Hamming scan)
1913
+ try {
1914
+ const { searchRabitq } = await import('./rabitq-index.js');
1915
+ const rabitqCandidates = await searchRabitq(queryEmbedding, { k: limit * 2, namespace: effectiveNamespace });
1916
+ if (rabitqCandidates && rabitqCandidates.length > 0) {
1917
+ // Rerank candidates with exact cosine similarity from SQLite
1918
+ const initSqlJs = (await import('sql.js')).default;
1919
+ const SQL = await initSqlJs();
1920
+ const fileBuffer = readFileMaybeEncrypted(dbPath, null);
1921
+ const db = new SQL.Database(fileBuffer);
1922
+ const reranked = [];
1923
+ for (const candidate of rabitqCandidates) {
1924
+ const stmt = db.prepare('SELECT content, embedding FROM memory_entries WHERE id = ? AND status = ?');
1925
+ stmt.bind([candidate.id, 'active']);
1926
+ if (stmt.step()) {
1927
+ const [content, embeddingJson] = stmt.get();
1928
+ let score = 0;
1929
+ if (embeddingJson) {
1930
+ try {
1931
+ const embedding = JSON.parse(embeddingJson);
1932
+ score = cosineSim(queryEmbedding, embedding);
1933
+ }
1934
+ catch { /* skip */ }
1935
+ }
1936
+ if (score >= threshold) {
1937
+ reranked.push({
1938
+ id: candidate.id.substring(0, 12),
1939
+ key: candidate.key || candidate.id.substring(0, 15),
1940
+ content: (content || '').substring(0, 60) + ((content || '').length > 60 ? '...' : ''),
1941
+ score,
1942
+ namespace: candidate.namespace,
1943
+ });
1944
+ }
1945
+ }
1946
+ stmt.free();
1947
+ }
1948
+ db.close();
1949
+ if (reranked.length > 0) {
1950
+ reranked.sort((a, b) => b.score - a.score);
1951
+ return { success: true, results: reranked.slice(0, limit), searchTime: Date.now() - startTime };
1952
+ }
1953
+ }
1954
+ }
1955
+ catch { /* RaBitQ unavailable, fall through */ }
1956
+ // Try HNSW search (150x faster than brute-force)
1957
+ const hnswResults = await searchHNSWIndex(queryEmbedding, { k: limit, namespace: effectiveNamespace });
1958
+ if (hnswResults && hnswResults.length > 0) {
1959
+ // Filter by threshold
1960
+ const filtered = hnswResults.filter(r => r.score >= threshold);
1961
+ return {
1962
+ success: true,
1963
+ results: filtered,
1964
+ searchTime: Date.now() - startTime
1965
+ };
1966
+ }
1967
+ // Fall back to brute-force SQLite search
1968
+ const initSqlJs = (await import('sql.js')).default;
1969
+ const SQL = await initSqlJs();
1970
+ const fileBuffer = readFileMaybeEncrypted(dbPath, null);
1971
+ const db = new SQL.Database(fileBuffer);
1972
+ // Get entries with embeddings
1973
+ const searchStmt = db.prepare(effectiveNamespace !== 'all'
1974
+ ? `SELECT id, key, namespace, content, embedding FROM memory_entries WHERE status = 'active' AND namespace = ? LIMIT 1000`
1975
+ : `SELECT id, key, namespace, content, embedding FROM memory_entries WHERE status = 'active' LIMIT 1000`);
1976
+ if (effectiveNamespace !== 'all') {
1977
+ searchStmt.bind([effectiveNamespace]);
1978
+ }
1979
+ const searchRows = [];
1980
+ while (searchStmt.step()) {
1981
+ searchRows.push(searchStmt.get());
1982
+ }
1983
+ searchStmt.free();
1984
+ const entries = searchRows.length > 0 ? [{ values: searchRows }] : [];
1985
+ const results = [];
1986
+ if (entries[0]?.values) {
1987
+ for (const row of entries[0].values) {
1988
+ const [id, key, ns, content, embeddingJson] = row;
1989
+ let score = 0;
1990
+ if (embeddingJson) {
1991
+ try {
1992
+ const embedding = JSON.parse(embeddingJson);
1993
+ score = cosineSim(queryEmbedding, embedding);
1994
+ }
1995
+ catch {
1996
+ // Invalid embedding, use keyword score
1997
+ }
1998
+ }
1999
+ // Fallback to keyword matching
2000
+ if (score < threshold) {
2001
+ const lowerContent = (content || '').toLowerCase();
2002
+ const lowerQuery = query.toLowerCase();
2003
+ const words = lowerQuery.split(/\s+/);
2004
+ const matchCount = words.filter(w => lowerContent.includes(w)).length;
2005
+ const keywordScore = matchCount / words.length * 0.5;
2006
+ score = Math.max(score, keywordScore);
2007
+ }
2008
+ if (score >= threshold) {
2009
+ results.push({
2010
+ id: id.substring(0, 12),
2011
+ key: key || id.substring(0, 15),
2012
+ content: (content || '').substring(0, 60) + ((content || '').length > 60 ? '...' : ''),
2013
+ score,
2014
+ namespace: ns || 'default'
2015
+ });
2016
+ }
2017
+ }
2018
+ }
2019
+ db.close();
2020
+ // Sort by score
2021
+ results.sort((a, b) => b.score - a.score);
2022
+ return {
2023
+ success: true,
2024
+ results: results.slice(0, limit),
2025
+ searchTime: Date.now() - startTime
2026
+ };
2027
+ }
2028
+ catch (error) {
2029
+ return {
2030
+ success: false,
2031
+ results: [],
2032
+ searchTime: Date.now() - startTime,
2033
+ error: error instanceof Error ? error.message : String(error)
2034
+ };
2035
+ }
2036
+ }
2037
+ /**
2038
+ * Optimized cosine similarity
2039
+ * V8 JIT-friendly - avoids manual unrolling which can hurt performance
2040
+ * ~0.5μs per 384-dim vector comparison
2041
+ */
2042
+ function cosineSim(a, b) {
2043
+ if (!a || !b || a.length === 0 || b.length === 0)
2044
+ return 0;
2045
+ const len = Math.min(a.length, b.length);
2046
+ let dot = 0, normA = 0, normB = 0;
2047
+ // Simple loop - V8 optimizes this well
2048
+ for (let i = 0; i < len; i++) {
2049
+ const ai = a[i], bi = b[i];
2050
+ dot += ai * bi;
2051
+ normA += ai * ai;
2052
+ normB += bi * bi;
2053
+ }
2054
+ // Combined sqrt for slightly better performance
2055
+ const mag = Math.sqrt(normA * normB);
2056
+ return mag === 0 ? 0 : dot / mag;
2057
+ }
2058
+ /**
2059
+ * List all entries from the memory database
2060
+ */
2061
+ export async function listEntries(options) {
2062
+ // ADR-053: Try AgentDB v3 bridge first
2063
+ const bridge = await getBridge();
2064
+ if (bridge) {
2065
+ const bridgeResult = await bridge.bridgeListEntries(options);
2066
+ if (bridgeResult)
2067
+ return bridgeResult;
2068
+ }
2069
+ // Fallback: raw sql.js
2070
+ const { namespace, limit = 20, offset = 0, dbPath: customPath } = options;
2071
+ const swarmDir = getMemoryRoot();
2072
+ const dbPath = customPath || path.join(swarmDir, 'memory.db');
2073
+ try {
2074
+ if (!fs.existsSync(dbPath)) {
2075
+ return { success: false, entries: [], total: 0, error: 'Database not found' };
2076
+ }
2077
+ // Ensure schema has all required columns (migration for older DBs)
2078
+ await ensureSchemaColumns(dbPath);
2079
+ const initSqlJs = (await import('sql.js')).default;
2080
+ const SQL = await initSqlJs();
2081
+ const fileBuffer = readFileMaybeEncrypted(dbPath, null);
2082
+ const db = new SQL.Database(fileBuffer);
2083
+ // Get total count
2084
+ const countStmt = namespace
2085
+ ? db.prepare(`SELECT COUNT(*) as cnt FROM memory_entries WHERE status = 'active' AND namespace = ?`)
2086
+ : db.prepare(`SELECT COUNT(*) as cnt FROM memory_entries WHERE status = 'active'`);
2087
+ if (namespace) {
2088
+ countStmt.bind([namespace]);
2089
+ }
2090
+ const countRows = [];
2091
+ while (countStmt.step()) {
2092
+ countRows.push(countStmt.get());
2093
+ }
2094
+ countStmt.free();
2095
+ const countResult = countRows.length > 0 ? [{ values: countRows }] : [];
2096
+ const total = countResult[0]?.values?.[0]?.[0] || 0;
2097
+ // Get entries
2098
+ const safeLimit = parseInt(String(limit), 10) || 100;
2099
+ const safeOffset = parseInt(String(offset), 10) || 0;
2100
+ const listStmt = namespace
2101
+ ? db.prepare(`SELECT id, key, namespace, content, embedding, access_count, created_at, updated_at FROM memory_entries WHERE status = 'active' AND namespace = ? ORDER BY updated_at DESC LIMIT ? OFFSET ?`)
2102
+ : db.prepare(`SELECT id, key, namespace, content, embedding, access_count, created_at, updated_at FROM memory_entries WHERE status = 'active' ORDER BY updated_at DESC LIMIT ? OFFSET ?`);
2103
+ if (namespace) {
2104
+ listStmt.bind([namespace, safeLimit, safeOffset]);
2105
+ }
2106
+ else {
2107
+ listStmt.bind([safeLimit, safeOffset]);
2108
+ }
2109
+ const listRows = [];
2110
+ while (listStmt.step()) {
2111
+ listRows.push(listStmt.get());
2112
+ }
2113
+ listStmt.free();
2114
+ const result = listRows.length > 0 ? [{ values: listRows }] : [];
2115
+ const entries = [];
2116
+ if (result[0]?.values) {
2117
+ for (const row of result[0].values) {
2118
+ const [id, key, ns, content, embedding, accessCount, createdAt, updatedAt] = row;
2119
+ entries.push({
2120
+ id: String(id).substring(0, 20),
2121
+ key: key || String(id).substring(0, 15),
2122
+ namespace: ns || 'default',
2123
+ size: (content || '').length,
2124
+ accessCount: accessCount || 0,
2125
+ createdAt: createdAt || new Date().toISOString(),
2126
+ updatedAt: updatedAt || new Date().toISOString(),
2127
+ hasEmbedding: !!embedding && embedding.length > 10
2128
+ });
2129
+ }
2130
+ }
2131
+ db.close();
2132
+ return { success: true, entries, total };
2133
+ }
2134
+ catch (error) {
2135
+ return {
2136
+ success: false,
2137
+ entries: [],
2138
+ total: 0,
2139
+ error: error instanceof Error ? error.message : String(error)
2140
+ };
2141
+ }
2142
+ }
2143
+ /**
2144
+ * Get a specific entry from the memory database
2145
+ */
2146
+ export async function getEntry(options) {
2147
+ // ADR-053: Try AgentDB v3 bridge first
2148
+ const bridge = await getBridge();
2149
+ if (bridge) {
2150
+ const bridgeResult = await bridge.bridgeGetEntry(options);
2151
+ if (bridgeResult)
2152
+ return bridgeResult;
2153
+ }
2154
+ // Fallback: raw sql.js
2155
+ const { key, namespace = 'default', dbPath: customPath } = options;
2156
+ const swarmDir = getMemoryRoot();
2157
+ const dbPath = customPath || path.join(swarmDir, 'memory.db');
2158
+ try {
2159
+ if (!fs.existsSync(dbPath)) {
2160
+ return { success: false, found: false, error: 'Database not found' };
2161
+ }
2162
+ // Ensure schema has all required columns (migration for older DBs)
2163
+ await ensureSchemaColumns(dbPath);
2164
+ const initSqlJs = (await import('sql.js')).default;
2165
+ const SQL = await initSqlJs();
2166
+ const fileBuffer = readFileMaybeEncrypted(dbPath, null);
2167
+ const db = new SQL.Database(fileBuffer);
2168
+ // Find entry by key
2169
+ const getStmt = db.prepare(`
2170
+ SELECT id, key, namespace, content, embedding, access_count, created_at, updated_at, tags
2171
+ FROM memory_entries
2172
+ WHERE status = 'active'
2173
+ AND key = ?
2174
+ AND namespace = ?
2175
+ LIMIT 1
2176
+ `);
2177
+ getStmt.bind([key, namespace]);
2178
+ const getRows = [];
2179
+ while (getStmt.step()) {
2180
+ getRows.push(getStmt.get());
2181
+ }
2182
+ getStmt.free();
2183
+ const result = getRows.length > 0 ? [{ values: getRows }] : [];
2184
+ if (!result[0]?.values?.[0]) {
2185
+ db.close();
2186
+ return { success: true, found: false };
2187
+ }
2188
+ const [id, entryKey, ns, content, embedding, accessCount, createdAt, updatedAt, tagsJson] = result[0].values[0];
2189
+ // Update access count
2190
+ db.run(`
2191
+ UPDATE memory_entries
2192
+ SET access_count = access_count + 1, last_accessed_at = strftime('%s', 'now') * 1000
2193
+ WHERE id = ?
2194
+ `, [String(id)]);
2195
+ // Save updated database
2196
+ const data = db.export();
2197
+ writeFileRestricted(dbPath, Buffer.from(data), { encrypt: true });
2198
+ db.close();
2199
+ let tags = [];
2200
+ if (tagsJson) {
2201
+ try {
2202
+ tags = JSON.parse(tagsJson);
2203
+ }
2204
+ catch {
2205
+ // Invalid JSON
2206
+ }
2207
+ }
2208
+ return {
2209
+ success: true,
2210
+ found: true,
2211
+ entry: {
2212
+ id: String(id),
2213
+ key: entryKey || String(id),
2214
+ namespace: ns || 'default',
2215
+ content: content || '',
2216
+ accessCount: (accessCount || 0) + 1,
2217
+ createdAt: createdAt || new Date().toISOString(),
2218
+ updatedAt: updatedAt || new Date().toISOString(),
2219
+ hasEmbedding: !!embedding && embedding.length > 10,
2220
+ tags
2221
+ }
2222
+ };
2223
+ }
2224
+ catch (error) {
2225
+ return {
2226
+ success: false,
2227
+ found: false,
2228
+ error: error instanceof Error ? error.message : String(error)
2229
+ };
2230
+ }
2231
+ }
2232
+ /**
2233
+ * Delete a memory entry by key and namespace
2234
+ * Issue #980: Properly supports namespaced entries
2235
+ */
2236
+ export async function deleteEntry(options) {
2237
+ // ADR-053: Try AgentDB v3 bridge first
2238
+ const bridge = await getBridge();
2239
+ if (bridge) {
2240
+ const bridgeResult = await bridge.bridgeDeleteEntry(options);
2241
+ if (bridgeResult) {
2242
+ // #1122: Bridge path must also invalidate the in-memory HNSW index.
2243
+ // Without this, deleted vectors remain as ghost entries in search results.
2244
+ if (bridgeResult.deleted && hnswIndex?.entries) {
2245
+ // Remove the entry from the HNSW entries map by key+namespace composite
2246
+ for (const [id, entry] of hnswIndex.entries) {
2247
+ if (entry?.key === options.key && (entry?.namespace ?? 'default') === (options.namespace ?? 'default')) {
2248
+ hnswIndex.entries.delete(id);
2249
+ break;
2250
+ }
2251
+ }
2252
+ saveHNSWMetadata();
2253
+ rebuildSearchIndex();
2254
+ }
2255
+ return bridgeResult;
2256
+ }
2257
+ }
2258
+ // Fallback: raw sql.js
2259
+ const { key, namespace = 'default', dbPath: customPath } = options;
2260
+ const swarmDir = getMemoryRoot();
2261
+ const dbPath = customPath || path.join(swarmDir, 'memory.db');
2262
+ try {
2263
+ if (!fs.existsSync(dbPath)) {
2264
+ return {
2265
+ success: false,
2266
+ deleted: false,
2267
+ key,
2268
+ namespace,
2269
+ remainingEntries: 0,
2270
+ error: 'Database not found'
2271
+ };
2272
+ }
2273
+ // Ensure schema has all required columns (migration for older DBs)
2274
+ await ensureSchemaColumns(dbPath);
2275
+ const initSqlJs = (await import('sql.js')).default;
2276
+ const SQL = await initSqlJs();
2277
+ const fileBuffer = readFileMaybeEncrypted(dbPath, null);
2278
+ const db = new SQL.Database(fileBuffer);
2279
+ // Check if entry exists first
2280
+ const checkStmt = db.prepare(`
2281
+ SELECT id FROM memory_entries
2282
+ WHERE status = 'active'
2283
+ AND key = ?
2284
+ AND namespace = ?
2285
+ LIMIT 1
2286
+ `);
2287
+ checkStmt.bind([key, namespace]);
2288
+ const checkRows = [];
2289
+ while (checkStmt.step()) {
2290
+ checkRows.push(checkStmt.get());
2291
+ }
2292
+ checkStmt.free();
2293
+ const checkResult = checkRows.length > 0 ? [{ values: checkRows }] : [];
2294
+ if (!checkResult[0]?.values?.[0]) {
2295
+ // Get remaining count before closing
2296
+ const countResult = db.exec(`SELECT COUNT(*) FROM memory_entries WHERE status = 'active'`);
2297
+ const remainingEntries = countResult[0]?.values?.[0]?.[0] || 0;
2298
+ db.close();
2299
+ return {
2300
+ success: true,
2301
+ deleted: false,
2302
+ key,
2303
+ namespace,
2304
+ remainingEntries,
2305
+ error: `Key '${key}' not found in namespace '${namespace}'`
2306
+ };
2307
+ }
2308
+ // Capture the entry ID for HNSW cleanup
2309
+ const entryId = String(checkResult[0].values[0][0]);
2310
+ // Delete the entry (soft delete by setting status to 'deleted')
2311
+ // Also null out the embedding to clean up vector data from SQLite
2312
+ db.run(`
2313
+ UPDATE memory_entries
2314
+ SET status = 'deleted',
2315
+ embedding = NULL,
2316
+ updated_at = strftime('%s', 'now') * 1000
2317
+ WHERE key = ?
2318
+ AND namespace = ?
2319
+ AND status = 'active'
2320
+ `, [key, namespace]);
2321
+ // Get remaining count
2322
+ const countResult = db.exec(`SELECT COUNT(*) FROM memory_entries WHERE status = 'active'`);
2323
+ const remainingEntries = countResult[0]?.values?.[0]?.[0] || 0;
2324
+ // Save updated database
2325
+ const data = db.export();
2326
+ writeFileRestricted(dbPath, Buffer.from(data), { encrypt: true });
2327
+ db.close();
2328
+ // Clean up in-memory HNSW index so ghost vectors don't appear in searches.
2329
+ // Remove the entry from the HNSW entries map and invalidate the index.
2330
+ // The next search will rebuild the HNSW index from the remaining DB rows.
2331
+ if (hnswIndex?.entries) {
2332
+ hnswIndex.entries.delete(entryId);
2333
+ saveHNSWMetadata();
2334
+ // Invalidate the HNSW index so it rebuilds from DB on next search.
2335
+ // We can't surgically remove a vector from the HNSW graph, so we
2336
+ // clear the entire index; it will be lazily rebuilt from SQLite.
2337
+ rebuildSearchIndex();
2338
+ }
2339
+ return {
2340
+ success: true,
2341
+ deleted: true,
2342
+ key,
2343
+ namespace,
2344
+ remainingEntries
2345
+ };
2346
+ }
2347
+ catch (error) {
2348
+ return {
2349
+ success: false,
2350
+ deleted: false,
2351
+ key,
2352
+ namespace,
2353
+ remainingEntries: 0,
2354
+ error: error instanceof Error ? error.message : String(error)
2355
+ };
2356
+ }
2357
+ }
2358
+ export default {
2359
+ initializeMemoryDatabase,
2360
+ checkMemoryInitialization,
2361
+ checkAndMigrateLegacy,
2362
+ ensureSchemaColumns,
2363
+ applyTemporalDecay,
2364
+ loadEmbeddingModel,
2365
+ generateEmbedding,
2366
+ verifyMemoryInit,
2367
+ storeEntry,
2368
+ searchEntries,
2369
+ listEntries,
2370
+ getEntry,
2371
+ deleteEntry,
2372
+ rebuildSearchIndex,
2373
+ MEMORY_SCHEMA_V3,
2374
+ getInitialMetadata
2375
+ };
2376
+ //# sourceMappingURL=memory-initializer.js.map