agentdb 3.0.0-alpha.2 → 3.0.0-alpha.4

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 (1038) hide show
  1. package/README.md +978 -2342
  2. package/dist/agentdb.browser.js +1492 -0
  3. package/dist/agentdb.browser.js.map +7 -0
  4. package/dist/agentdb.browser.min.js +3 -0
  5. package/dist/agentdb.browser.min.js.map +7 -0
  6. package/dist/agentdb.wasm-loader.js +207 -0
  7. package/dist/schemas/frontier-schema.sql +0 -7
  8. package/dist/schemas/schema.sql +0 -7
  9. package/dist/simulation/cli.d.ts +9 -0
  10. package/dist/simulation/cli.d.ts.map +1 -0
  11. package/dist/simulation/cli.js +68 -0
  12. package/dist/simulation/cli.js.map +1 -0
  13. package/dist/simulation/runner.d.ts +21 -0
  14. package/dist/simulation/runner.d.ts.map +1 -0
  15. package/dist/simulation/runner.js +241 -0
  16. package/dist/simulation/runner.js.map +1 -0
  17. package/dist/simulation/scenarios/aidefence-integration.d.ts +24 -0
  18. package/dist/simulation/scenarios/aidefence-integration.d.ts.map +1 -0
  19. package/dist/simulation/scenarios/aidefence-integration.js +124 -0
  20. package/dist/simulation/scenarios/aidefence-integration.js.map +1 -0
  21. package/dist/simulation/scenarios/bmssp-integration.d.ts +23 -0
  22. package/dist/simulation/scenarios/bmssp-integration.d.ts.map +1 -0
  23. package/dist/simulation/scenarios/bmssp-integration.js +104 -0
  24. package/dist/simulation/scenarios/bmssp-integration.js.map +1 -0
  25. package/dist/simulation/scenarios/causal-reasoning.d.ts +16 -0
  26. package/dist/simulation/scenarios/causal-reasoning.d.ts.map +1 -0
  27. package/dist/simulation/scenarios/causal-reasoning.js +108 -0
  28. package/dist/simulation/scenarios/causal-reasoning.js.map +1 -0
  29. package/dist/simulation/scenarios/consciousness-explorer.d.ts +25 -0
  30. package/dist/simulation/scenarios/consciousness-explorer.d.ts.map +1 -0
  31. package/dist/simulation/scenarios/consciousness-explorer.js +108 -0
  32. package/dist/simulation/scenarios/consciousness-explorer.js.map +1 -0
  33. package/dist/simulation/scenarios/domain-examples/e-commerce-recommendations.d.ts +135 -0
  34. package/dist/simulation/scenarios/domain-examples/e-commerce-recommendations.d.ts.map +1 -0
  35. package/dist/simulation/scenarios/domain-examples/e-commerce-recommendations.js +158 -0
  36. package/dist/simulation/scenarios/domain-examples/e-commerce-recommendations.js.map +1 -0
  37. package/dist/simulation/scenarios/domain-examples/index.d.ts +14 -0
  38. package/dist/simulation/scenarios/domain-examples/index.d.ts.map +1 -0
  39. package/dist/simulation/scenarios/domain-examples/index.js +14 -0
  40. package/dist/simulation/scenarios/domain-examples/index.js.map +1 -0
  41. package/dist/simulation/scenarios/domain-examples/iot-sensor-networks.d.ts +178 -0
  42. package/dist/simulation/scenarios/domain-examples/iot-sensor-networks.d.ts.map +1 -0
  43. package/dist/simulation/scenarios/domain-examples/iot-sensor-networks.js +218 -0
  44. package/dist/simulation/scenarios/domain-examples/iot-sensor-networks.js.map +1 -0
  45. package/dist/simulation/scenarios/domain-examples/medical-imaging.d.ts +122 -0
  46. package/dist/simulation/scenarios/domain-examples/medical-imaging.d.ts.map +1 -0
  47. package/dist/simulation/scenarios/domain-examples/medical-imaging.js +129 -0
  48. package/dist/simulation/scenarios/domain-examples/medical-imaging.js.map +1 -0
  49. package/dist/simulation/scenarios/domain-examples/robotics-navigation.d.ts +166 -0
  50. package/dist/simulation/scenarios/domain-examples/robotics-navigation.d.ts.map +1 -0
  51. package/dist/simulation/scenarios/domain-examples/robotics-navigation.js +161 -0
  52. package/dist/simulation/scenarios/domain-examples/robotics-navigation.js.map +1 -0
  53. package/dist/simulation/scenarios/domain-examples/scientific-research.d.ts +151 -0
  54. package/dist/simulation/scenarios/domain-examples/scientific-research.d.ts.map +1 -0
  55. package/dist/simulation/scenarios/domain-examples/scientific-research.js +187 -0
  56. package/dist/simulation/scenarios/domain-examples/scientific-research.js.map +1 -0
  57. package/dist/simulation/scenarios/domain-examples/trading-systems.d.ts +102 -0
  58. package/dist/simulation/scenarios/domain-examples/trading-systems.d.ts.map +1 -0
  59. package/dist/simulation/scenarios/domain-examples/trading-systems.js +100 -0
  60. package/dist/simulation/scenarios/domain-examples/trading-systems.js.map +1 -0
  61. package/dist/simulation/scenarios/goalie-integration.d.ts +24 -0
  62. package/dist/simulation/scenarios/goalie-integration.d.ts.map +1 -0
  63. package/dist/simulation/scenarios/goalie-integration.js +121 -0
  64. package/dist/simulation/scenarios/goalie-integration.js.map +1 -0
  65. package/dist/simulation/scenarios/graph-traversal.d.ts +17 -0
  66. package/dist/simulation/scenarios/graph-traversal.d.ts.map +1 -0
  67. package/dist/simulation/scenarios/graph-traversal.js +101 -0
  68. package/dist/simulation/scenarios/graph-traversal.js.map +1 -0
  69. package/dist/simulation/scenarios/latent-space/attention-analysis.d.ts +45 -0
  70. package/dist/simulation/scenarios/latent-space/attention-analysis.d.ts.map +1 -0
  71. package/dist/simulation/scenarios/latent-space/attention-analysis.js +435 -0
  72. package/dist/simulation/scenarios/latent-space/attention-analysis.js.map +1 -0
  73. package/dist/simulation/scenarios/latent-space/clustering-analysis.d.ts +55 -0
  74. package/dist/simulation/scenarios/latent-space/clustering-analysis.d.ts.map +1 -0
  75. package/dist/simulation/scenarios/latent-space/clustering-analysis.js +606 -0
  76. package/dist/simulation/scenarios/latent-space/clustering-analysis.js.map +1 -0
  77. package/dist/simulation/scenarios/latent-space/hnsw-exploration.d.ts +74 -0
  78. package/dist/simulation/scenarios/latent-space/hnsw-exploration.d.ts.map +1 -0
  79. package/dist/simulation/scenarios/latent-space/hnsw-exploration.js +391 -0
  80. package/dist/simulation/scenarios/latent-space/hnsw-exploration.js.map +1 -0
  81. package/dist/simulation/scenarios/latent-space/hypergraph-exploration.d.ts +51 -0
  82. package/dist/simulation/scenarios/latent-space/hypergraph-exploration.d.ts.map +1 -0
  83. package/dist/simulation/scenarios/latent-space/hypergraph-exploration.js +536 -0
  84. package/dist/simulation/scenarios/latent-space/hypergraph-exploration.js.map +1 -0
  85. package/dist/simulation/scenarios/latent-space/index.d.ts +35 -0
  86. package/dist/simulation/scenarios/latent-space/index.d.ts.map +1 -0
  87. package/dist/simulation/scenarios/latent-space/index.js +35 -0
  88. package/dist/simulation/scenarios/latent-space/index.js.map +1 -0
  89. package/dist/simulation/scenarios/latent-space/neural-augmentation.d.ts +52 -0
  90. package/dist/simulation/scenarios/latent-space/neural-augmentation.d.ts.map +1 -0
  91. package/dist/simulation/scenarios/latent-space/neural-augmentation.js +472 -0
  92. package/dist/simulation/scenarios/latent-space/neural-augmentation.js.map +1 -0
  93. package/dist/simulation/scenarios/latent-space/quantum-hybrid.d.ts +53 -0
  94. package/dist/simulation/scenarios/latent-space/quantum-hybrid.d.ts.map +1 -0
  95. package/dist/simulation/scenarios/latent-space/quantum-hybrid.js +391 -0
  96. package/dist/simulation/scenarios/latent-space/quantum-hybrid.js.map +1 -0
  97. package/dist/simulation/scenarios/latent-space/self-organizing-hnsw.d.ts +52 -0
  98. package/dist/simulation/scenarios/latent-space/self-organizing-hnsw.d.ts.map +1 -0
  99. package/dist/simulation/scenarios/latent-space/self-organizing-hnsw.js +514 -0
  100. package/dist/simulation/scenarios/latent-space/self-organizing-hnsw.js.map +1 -0
  101. package/dist/simulation/scenarios/latent-space/traversal-optimization.d.ts +53 -0
  102. package/dist/simulation/scenarios/latent-space/traversal-optimization.d.ts.map +1 -0
  103. package/dist/simulation/scenarios/latent-space/traversal-optimization.js +595 -0
  104. package/dist/simulation/scenarios/latent-space/traversal-optimization.js.map +1 -0
  105. package/dist/simulation/scenarios/lean-agentic-swarm.d.ts +18 -0
  106. package/dist/simulation/scenarios/lean-agentic-swarm.d.ts.map +1 -0
  107. package/dist/simulation/scenarios/lean-agentic-swarm.js +132 -0
  108. package/dist/simulation/scenarios/lean-agentic-swarm.js.map +1 -0
  109. package/dist/simulation/scenarios/multi-agent-swarm.d.ts +17 -0
  110. package/dist/simulation/scenarios/multi-agent-swarm.d.ts.map +1 -0
  111. package/dist/simulation/scenarios/multi-agent-swarm.js +111 -0
  112. package/dist/simulation/scenarios/multi-agent-swarm.js.map +1 -0
  113. package/dist/simulation/scenarios/psycho-symbolic-reasoner.d.ts +23 -0
  114. package/dist/simulation/scenarios/psycho-symbolic-reasoner.d.ts.map +1 -0
  115. package/dist/simulation/scenarios/psycho-symbolic-reasoner.js +98 -0
  116. package/dist/simulation/scenarios/psycho-symbolic-reasoner.js.map +1 -0
  117. package/dist/simulation/scenarios/reflexion-learning.d.ts +16 -0
  118. package/dist/simulation/scenarios/reflexion-learning.d.ts.map +1 -0
  119. package/dist/simulation/scenarios/reflexion-learning.js +98 -0
  120. package/dist/simulation/scenarios/reflexion-learning.js.map +1 -0
  121. package/dist/simulation/scenarios/research-swarm.d.ts +24 -0
  122. package/dist/simulation/scenarios/research-swarm.d.ts.map +1 -0
  123. package/dist/simulation/scenarios/research-swarm.js +146 -0
  124. package/dist/simulation/scenarios/research-swarm.js.map +1 -0
  125. package/dist/simulation/scenarios/skill-evolution.d.ts +16 -0
  126. package/dist/simulation/scenarios/skill-evolution.d.ts.map +1 -0
  127. package/dist/simulation/scenarios/skill-evolution.js +109 -0
  128. package/dist/simulation/scenarios/skill-evolution.js.map +1 -0
  129. package/dist/simulation/scenarios/stock-market-emergence.d.ts +33 -0
  130. package/dist/simulation/scenarios/stock-market-emergence.d.ts.map +1 -0
  131. package/dist/simulation/scenarios/stock-market-emergence.js +246 -0
  132. package/dist/simulation/scenarios/stock-market-emergence.js.map +1 -0
  133. package/dist/simulation/scenarios/strange-loops.d.ts +18 -0
  134. package/dist/simulation/scenarios/strange-loops.d.ts.map +1 -0
  135. package/dist/simulation/scenarios/strange-loops.js +133 -0
  136. package/dist/simulation/scenarios/strange-loops.js.map +1 -0
  137. package/dist/simulation/scenarios/sublinear-solver.d.ts +22 -0
  138. package/dist/simulation/scenarios/sublinear-solver.d.ts.map +1 -0
  139. package/dist/simulation/scenarios/sublinear-solver.js +82 -0
  140. package/dist/simulation/scenarios/sublinear-solver.js.map +1 -0
  141. package/dist/simulation/scenarios/temporal-lead-solver.d.ts +23 -0
  142. package/dist/simulation/scenarios/temporal-lead-solver.d.ts.map +1 -0
  143. package/dist/simulation/scenarios/temporal-lead-solver.js +90 -0
  144. package/dist/simulation/scenarios/temporal-lead-solver.js.map +1 -0
  145. package/dist/simulation/scenarios/voting-system-consensus.d.ts +27 -0
  146. package/dist/simulation/scenarios/voting-system-consensus.d.ts.map +1 -0
  147. package/dist/simulation/scenarios/voting-system-consensus.js +175 -0
  148. package/dist/simulation/scenarios/voting-system-consensus.js.map +1 -0
  149. package/dist/simulation/types.d.ts +162 -0
  150. package/dist/simulation/types.d.ts.map +1 -0
  151. package/dist/simulation/types.js +5 -0
  152. package/dist/simulation/types.js.map +1 -0
  153. package/dist/simulation/utils/PerformanceOptimizer.d.ts +115 -0
  154. package/dist/simulation/utils/PerformanceOptimizer.d.ts.map +1 -0
  155. package/dist/simulation/utils/PerformanceOptimizer.js +223 -0
  156. package/dist/simulation/utils/PerformanceOptimizer.js.map +1 -0
  157. package/dist/src/backends/GraphBackend.d.ts +8 -8
  158. package/dist/src/backends/GraphBackend.d.ts.map +1 -1
  159. package/dist/src/backends/GraphBackend.js +15 -16
  160. package/dist/src/backends/GraphBackend.js.map +1 -1
  161. package/dist/src/backends/LearningBackend.d.ts +2 -2
  162. package/dist/src/backends/LearningBackend.d.ts.map +1 -1
  163. package/dist/src/backends/LearningBackend.js +10 -11
  164. package/dist/src/backends/LearningBackend.js.map +1 -1
  165. package/dist/src/backends/VectorBackend.d.ts +6 -31
  166. package/dist/src/backends/VectorBackend.d.ts.map +1 -1
  167. package/dist/src/backends/detector.d.ts +3 -25
  168. package/dist/src/backends/detector.d.ts.map +1 -1
  169. package/dist/src/backends/detector.js +15 -119
  170. package/dist/src/backends/detector.js.map +1 -1
  171. package/dist/src/backends/factory.d.ts +32 -16
  172. package/dist/src/backends/factory.d.ts.map +1 -1
  173. package/dist/src/backends/factory.js +70 -133
  174. package/dist/src/backends/factory.js.map +1 -1
  175. package/dist/src/backends/graph/GraphDatabaseAdapter.d.ts +1 -1
  176. package/dist/src/backends/graph/GraphDatabaseAdapter.d.ts.map +1 -1
  177. package/dist/src/backends/graph/GraphDatabaseAdapter.js +1 -5
  178. package/dist/src/backends/graph/GraphDatabaseAdapter.js.map +1 -1
  179. package/dist/src/backends/hnswlib/HNSWLibBackend.d.ts +2 -2
  180. package/dist/src/backends/hnswlib/HNSWLibBackend.d.ts.map +1 -1
  181. package/dist/src/backends/hnswlib/HNSWLibBackend.js +13 -49
  182. package/dist/src/backends/hnswlib/HNSWLibBackend.js.map +1 -1
  183. package/dist/src/backends/index.d.ts +3 -25
  184. package/dist/src/backends/index.d.ts.map +1 -1
  185. package/dist/src/backends/index.js +1 -23
  186. package/dist/src/backends/index.js.map +1 -1
  187. package/dist/src/backends/ruvector/GuardedVectorBackend.d.ts +93 -0
  188. package/dist/src/backends/ruvector/GuardedVectorBackend.d.ts.map +1 -0
  189. package/dist/src/backends/ruvector/GuardedVectorBackend.js +182 -0
  190. package/dist/src/backends/ruvector/GuardedVectorBackend.js.map +1 -0
  191. package/dist/src/backends/ruvector/RuVectorBackend.d.ts +16 -187
  192. package/dist/src/backends/ruvector/RuVectorBackend.d.ts.map +1 -1
  193. package/dist/src/backends/ruvector/RuVectorBackend.js +94 -576
  194. package/dist/src/backends/ruvector/RuVectorBackend.js.map +1 -1
  195. package/dist/src/backends/ruvector/RuVectorLearning.d.ts +4 -0
  196. package/dist/src/backends/ruvector/RuVectorLearning.d.ts.map +1 -1
  197. package/dist/src/backends/ruvector/RuVectorLearning.js +11 -10
  198. package/dist/src/backends/ruvector/RuVectorLearning.js.map +1 -1
  199. package/dist/src/benchmarks/wasm-vector-benchmark.d.ts +10 -0
  200. package/dist/src/benchmarks/wasm-vector-benchmark.d.ts.map +1 -0
  201. package/dist/src/benchmarks/wasm-vector-benchmark.js +196 -0
  202. package/dist/src/benchmarks/wasm-vector-benchmark.js.map +1 -0
  203. package/dist/src/browser/AdvancedFeatures.d.ts.map +1 -1
  204. package/dist/src/browser/AdvancedFeatures.js +10 -3
  205. package/dist/src/browser/AdvancedFeatures.js.map +1 -1
  206. package/dist/src/browser/AttentionBrowser.d.ts.map +1 -1
  207. package/dist/src/browser/AttentionBrowser.js +12 -5
  208. package/dist/src/browser/AttentionBrowser.js.map +1 -1
  209. package/dist/src/browser/HNSWIndex.d.ts +1 -31
  210. package/dist/src/browser/HNSWIndex.d.ts.map +1 -1
  211. package/dist/src/browser/HNSWIndex.js +18 -136
  212. package/dist/src/browser/HNSWIndex.js.map +1 -1
  213. package/dist/src/browser/ProductQuantization.d.ts.map +1 -1
  214. package/dist/src/browser/ProductQuantization.js +1 -0
  215. package/dist/src/browser/ProductQuantization.js.map +1 -1
  216. package/dist/src/browser/index.d.ts +3 -3
  217. package/dist/src/browser/index.d.ts.map +1 -1
  218. package/dist/src/browser/index.js +1 -2
  219. package/dist/src/browser/index.js.map +1 -1
  220. package/dist/src/cli/agentdb-cli.d.ts +2 -16
  221. package/dist/src/cli/agentdb-cli.d.ts.map +1 -1
  222. package/dist/src/cli/agentdb-cli.js +216 -853
  223. package/dist/src/cli/agentdb-cli.js.map +1 -1
  224. package/dist/src/cli/commands/attention.js +3 -3
  225. package/dist/src/cli/commands/attention.js.map +1 -1
  226. package/dist/src/cli/commands/doctor.d.ts +0 -2
  227. package/dist/src/cli/commands/doctor.d.ts.map +1 -1
  228. package/dist/src/cli/commands/doctor.js +1 -106
  229. package/dist/src/cli/commands/doctor.js.map +1 -1
  230. package/dist/src/cli/commands/init.d.ts +1 -2
  231. package/dist/src/cli/commands/init.d.ts.map +1 -1
  232. package/dist/src/cli/commands/init.js +7 -30
  233. package/dist/src/cli/commands/init.js.map +1 -1
  234. package/dist/src/cli/commands/install-embeddings.d.ts.map +1 -1
  235. package/dist/src/cli/commands/install-embeddings.js.map +1 -1
  236. package/dist/src/cli/commands/migrate.d.ts +0 -15
  237. package/dist/src/cli/commands/migrate.d.ts.map +1 -1
  238. package/dist/src/cli/commands/migrate.js +5 -164
  239. package/dist/src/cli/commands/migrate.js.map +1 -1
  240. package/dist/src/cli/commands/simulate-report.js.map +1 -1
  241. package/dist/src/cli/commands/simulate-wizard.js.map +1 -1
  242. package/dist/src/cli/commands/simulate.d.ts +7 -0
  243. package/dist/src/cli/commands/simulate.d.ts.map +1 -0
  244. package/dist/src/cli/commands/simulate.js +100 -0
  245. package/dist/src/cli/commands/simulate.js.map +1 -0
  246. package/dist/src/cli/commands/status.js +1 -5
  247. package/dist/src/cli/commands/status.js.map +1 -1
  248. package/dist/src/cli/lib/attention-config.d.ts +2 -2
  249. package/dist/src/cli/lib/attention-config.d.ts.map +1 -1
  250. package/dist/src/cli/lib/attention-config.js +1 -2
  251. package/dist/src/cli/lib/attention-config.js.map +1 -1
  252. package/dist/src/cli/lib/config-manager.d.ts +110 -0
  253. package/dist/src/cli/lib/config-manager.d.ts.map +1 -0
  254. package/dist/src/cli/lib/config-manager.js +512 -0
  255. package/dist/src/cli/lib/config-manager.js.map +1 -0
  256. package/dist/src/cli/lib/config-validator.d.ts +1 -1
  257. package/dist/src/cli/lib/config-validator.d.ts.map +1 -1
  258. package/dist/src/cli/lib/health-monitor.d.ts +149 -0
  259. package/dist/src/cli/lib/health-monitor.d.ts.map +1 -0
  260. package/dist/src/cli/lib/health-monitor.js +380 -0
  261. package/dist/src/cli/lib/health-monitor.js.map +1 -0
  262. package/dist/src/cli/lib/history-tracker.d.ts +103 -0
  263. package/dist/src/cli/lib/history-tracker.d.ts.map +1 -0
  264. package/dist/src/cli/lib/history-tracker.js +352 -0
  265. package/dist/src/cli/lib/history-tracker.js.map +1 -0
  266. package/dist/src/cli/lib/report-store.d.ts +1 -2
  267. package/dist/src/cli/lib/report-store.d.ts.map +1 -1
  268. package/dist/src/cli/lib/report-store.js +65 -87
  269. package/dist/src/cli/lib/report-store.js.map +1 -1
  270. package/dist/src/cli/lib/simulation-registry.d.ts +1 -1
  271. package/dist/src/cli/lib/simulation-registry.d.ts.map +1 -1
  272. package/dist/src/cli/lib/simulation-registry.js +0 -1
  273. package/dist/src/cli/lib/simulation-registry.js.map +1 -1
  274. package/dist/src/cli/lib/simulation-runner.d.ts +4 -41
  275. package/dist/src/cli/lib/simulation-runner.d.ts.map +1 -1
  276. package/dist/src/cli/lib/simulation-runner.js +6 -251
  277. package/dist/src/cli/lib/simulation-runner.js.map +1 -1
  278. package/dist/src/controllers/AttentionService.d.ts.map +1 -1
  279. package/dist/src/controllers/AttentionService.js +5 -3
  280. package/dist/src/controllers/AttentionService.js.map +1 -1
  281. package/dist/src/controllers/CausalMemoryGraph.d.ts +8 -33
  282. package/dist/src/controllers/CausalMemoryGraph.d.ts.map +1 -1
  283. package/dist/src/controllers/CausalMemoryGraph.js +16 -93
  284. package/dist/src/controllers/CausalMemoryGraph.js.map +1 -1
  285. package/dist/src/controllers/CausalRecall.d.ts +3 -6
  286. package/dist/src/controllers/CausalRecall.d.ts.map +1 -1
  287. package/dist/src/controllers/CausalRecall.js +8 -14
  288. package/dist/src/controllers/CausalRecall.js.map +1 -1
  289. package/dist/src/controllers/ContextSynthesizer.d.ts +1 -1
  290. package/dist/src/controllers/ContextSynthesizer.d.ts.map +1 -1
  291. package/dist/src/controllers/EmbeddingService.d.ts.map +1 -1
  292. package/dist/src/controllers/EmbeddingService.js +3 -10
  293. package/dist/src/controllers/EmbeddingService.js.map +1 -1
  294. package/dist/src/controllers/EnhancedEmbeddingService.d.ts +0 -4
  295. package/dist/src/controllers/EnhancedEmbeddingService.d.ts.map +1 -1
  296. package/dist/src/controllers/EnhancedEmbeddingService.js +3 -10
  297. package/dist/src/controllers/EnhancedEmbeddingService.js.map +1 -1
  298. package/dist/src/controllers/ExplainableRecall.d.ts +6 -5
  299. package/dist/src/controllers/ExplainableRecall.d.ts.map +1 -1
  300. package/dist/src/controllers/ExplainableRecall.js +13 -21
  301. package/dist/src/controllers/ExplainableRecall.js.map +1 -1
  302. package/dist/src/controllers/HNSWIndex.d.ts +7 -24
  303. package/dist/src/controllers/HNSWIndex.d.ts.map +1 -1
  304. package/dist/src/controllers/HNSWIndex.js +10 -89
  305. package/dist/src/controllers/HNSWIndex.js.map +1 -1
  306. package/dist/src/controllers/LearningSystem.d.ts +10 -106
  307. package/dist/src/controllers/LearningSystem.d.ts.map +1 -1
  308. package/dist/src/controllers/LearningSystem.js +14 -39
  309. package/dist/src/controllers/LearningSystem.js.map +1 -1
  310. package/dist/src/controllers/MMRDiversityRanker.d.ts +1 -1
  311. package/dist/src/controllers/MMRDiversityRanker.d.ts.map +1 -1
  312. package/dist/src/controllers/MetadataFilter.d.ts +3 -3
  313. package/dist/src/controllers/MetadataFilter.d.ts.map +1 -1
  314. package/dist/src/controllers/MetadataFilter.js +6 -9
  315. package/dist/src/controllers/MetadataFilter.js.map +1 -1
  316. package/dist/src/controllers/NightlyLearner.d.ts +4 -9
  317. package/dist/src/controllers/NightlyLearner.d.ts.map +1 -1
  318. package/dist/src/controllers/NightlyLearner.js +9 -28
  319. package/dist/src/controllers/NightlyLearner.js.map +1 -1
  320. package/dist/src/controllers/QUICClient.d.ts +2 -50
  321. package/dist/src/controllers/QUICClient.d.ts.map +1 -1
  322. package/dist/src/controllers/QUICClient.js +3 -193
  323. package/dist/src/controllers/QUICClient.js.map +1 -1
  324. package/dist/src/controllers/QUICServer.d.ts +4 -4
  325. package/dist/src/controllers/QUICServer.d.ts.map +1 -1
  326. package/dist/src/controllers/QUICServer.js +14 -22
  327. package/dist/src/controllers/QUICServer.js.map +1 -1
  328. package/dist/src/controllers/ReasoningBank.d.ts +4 -14
  329. package/dist/src/controllers/ReasoningBank.d.ts.map +1 -1
  330. package/dist/src/controllers/ReasoningBank.js +46 -59
  331. package/dist/src/controllers/ReasoningBank.js.map +1 -1
  332. package/dist/src/controllers/ReflexionMemory.d.ts +7 -80
  333. package/dist/src/controllers/ReflexionMemory.d.ts.map +1 -1
  334. package/dist/src/controllers/ReflexionMemory.js +214 -372
  335. package/dist/src/controllers/ReflexionMemory.js.map +1 -1
  336. package/dist/src/controllers/SkillLibrary.d.ts +7 -37
  337. package/dist/src/controllers/SkillLibrary.d.ts.map +1 -1
  338. package/dist/src/controllers/SkillLibrary.js +96 -212
  339. package/dist/src/controllers/SkillLibrary.js.map +1 -1
  340. package/dist/src/controllers/SyncCoordinator.d.ts +3 -2
  341. package/dist/src/controllers/SyncCoordinator.d.ts.map +1 -1
  342. package/dist/src/controllers/SyncCoordinator.js +5 -117
  343. package/dist/src/controllers/SyncCoordinator.js.map +1 -1
  344. package/dist/src/controllers/WASMVectorSearch.d.ts +9 -20
  345. package/dist/src/controllers/WASMVectorSearch.d.ts.map +1 -1
  346. package/dist/src/controllers/WASMVectorSearch.js +29 -154
  347. package/dist/src/controllers/WASMVectorSearch.js.map +1 -1
  348. package/dist/src/controllers/frontier-index.d.ts +14 -0
  349. package/dist/src/controllers/frontier-index.d.ts.map +1 -0
  350. package/dist/src/controllers/frontier-index.js +10 -0
  351. package/dist/src/controllers/frontier-index.js.map +1 -0
  352. package/dist/src/controllers/index.d.ts +17 -8
  353. package/dist/src/controllers/index.d.ts.map +1 -1
  354. package/dist/src/controllers/index.js +12 -6
  355. package/dist/src/controllers/index.js.map +1 -1
  356. package/dist/src/core/AgentDB.d.ts +25 -57
  357. package/dist/src/core/AgentDB.d.ts.map +1 -1
  358. package/dist/src/core/AgentDB.js +115 -137
  359. package/dist/src/core/AgentDB.js.map +1 -1
  360. package/dist/src/db-fallback.d.ts +1 -10
  361. package/dist/src/db-fallback.d.ts.map +1 -1
  362. package/dist/src/db-fallback.js +4 -171
  363. package/dist/src/db-fallback.js.map +1 -1
  364. package/dist/src/db-test.d.ts +13 -0
  365. package/dist/src/db-test.d.ts.map +1 -0
  366. package/dist/src/db-test.js +55 -0
  367. package/dist/src/db-test.js.map +1 -0
  368. package/dist/src/db-unified.d.ts +76 -0
  369. package/dist/src/db-unified.d.ts.map +1 -0
  370. package/dist/src/db-unified.js +279 -0
  371. package/dist/src/db-unified.js.map +1 -0
  372. package/dist/src/examples/quic-sync-example.d.ts +9 -0
  373. package/dist/src/examples/quic-sync-example.d.ts.map +1 -0
  374. package/dist/src/examples/quic-sync-example.js +169 -0
  375. package/dist/src/examples/quic-sync-example.js.map +1 -0
  376. package/dist/src/examples/wasm-vector-usage.d.ts +12 -0
  377. package/dist/src/examples/wasm-vector-usage.d.ts.map +1 -0
  378. package/dist/src/examples/wasm-vector-usage.js +190 -0
  379. package/dist/src/examples/wasm-vector-usage.js.map +1 -0
  380. package/dist/src/index.d.ts +12 -38
  381. package/dist/src/index.d.ts.map +1 -1
  382. package/dist/src/index.js +11 -46
  383. package/dist/src/index.js.map +1 -1
  384. package/dist/src/mcp/agentdb-mcp-server.js +63 -219
  385. package/dist/src/mcp/agentdb-mcp-server.js.map +1 -1
  386. package/dist/src/mcp/learning-tools-handlers.d.ts +16 -0
  387. package/dist/src/mcp/learning-tools-handlers.d.ts.map +1 -0
  388. package/dist/src/mcp/learning-tools-handlers.js +105 -0
  389. package/dist/src/mcp/learning-tools-handlers.js.map +1 -0
  390. package/dist/src/optimizations/BatchOperations.d.ts +5 -52
  391. package/dist/src/optimizations/BatchOperations.d.ts.map +1 -1
  392. package/dist/src/optimizations/BatchOperations.js +33 -186
  393. package/dist/src/optimizations/BatchOperations.js.map +1 -1
  394. package/dist/src/optimizations/QueryOptimizer.d.ts +4 -4
  395. package/dist/src/optimizations/QueryOptimizer.d.ts.map +1 -1
  396. package/dist/src/optimizations/QueryOptimizer.js +1 -3
  397. package/dist/src/optimizations/QueryOptimizer.js.map +1 -1
  398. package/dist/src/optimizations/ToolCache.d.ts +4 -4
  399. package/dist/src/optimizations/ToolCache.d.ts.map +1 -1
  400. package/dist/src/optimizations/ToolCache.js.map +1 -1
  401. package/dist/src/optimizations/index.d.ts +1 -1
  402. package/dist/src/optimizations/index.d.ts.map +1 -1
  403. package/dist/src/security/AttestationLog.d.ts +70 -0
  404. package/dist/src/security/AttestationLog.d.ts.map +1 -0
  405. package/dist/src/security/AttestationLog.js +174 -0
  406. package/dist/src/security/AttestationLog.js.map +1 -0
  407. package/dist/src/security/MutationGuard.d.ts +83 -0
  408. package/dist/src/security/MutationGuard.d.ts.map +1 -0
  409. package/dist/src/security/MutationGuard.js +379 -0
  410. package/dist/src/security/MutationGuard.js.map +1 -0
  411. package/dist/src/security/index.d.ts +15 -0
  412. package/dist/src/security/index.d.ts.map +1 -0
  413. package/dist/src/security/index.js +18 -0
  414. package/dist/src/security/index.js.map +1 -0
  415. package/dist/src/security/input-validation.d.ts +12 -12
  416. package/dist/src/security/input-validation.d.ts.map +1 -1
  417. package/dist/src/security/input-validation.js +0 -1
  418. package/dist/src/security/input-validation.js.map +1 -1
  419. package/dist/src/security/limits.d.ts +150 -0
  420. package/dist/src/security/limits.d.ts.map +1 -0
  421. package/dist/src/security/limits.js +288 -0
  422. package/dist/src/security/limits.js.map +1 -0
  423. package/dist/src/security/path-security.d.ts +100 -0
  424. package/dist/src/security/path-security.d.ts.map +1 -0
  425. package/dist/src/security/path-security.js +337 -0
  426. package/dist/src/security/path-security.js.map +1 -0
  427. package/dist/src/security/validation.d.ts +95 -0
  428. package/dist/src/security/validation.d.ts.map +1 -0
  429. package/dist/src/security/validation.js +315 -0
  430. package/dist/src/security/validation.js.map +1 -0
  431. package/dist/src/services/GraphTransformerService.d.ts +79 -0
  432. package/dist/src/services/GraphTransformerService.d.ts.map +1 -0
  433. package/dist/src/services/GraphTransformerService.js +331 -0
  434. package/dist/src/services/GraphTransformerService.js.map +1 -0
  435. package/dist/src/services/LLMRouter.d.ts +7 -61
  436. package/dist/src/services/LLMRouter.d.ts.map +1 -1
  437. package/dist/src/services/LLMRouter.js +25 -295
  438. package/dist/src/services/LLMRouter.js.map +1 -1
  439. package/dist/src/services/SemanticRouter.d.ts +78 -0
  440. package/dist/src/services/SemanticRouter.d.ts.map +1 -0
  441. package/dist/src/services/SemanticRouter.js +149 -0
  442. package/dist/src/services/SemanticRouter.js.map +1 -0
  443. package/dist/src/services/SonaTrajectoryService.d.ts +100 -0
  444. package/dist/src/services/SonaTrajectoryService.d.ts.map +1 -0
  445. package/dist/src/services/SonaTrajectoryService.js +231 -0
  446. package/dist/src/services/SonaTrajectoryService.js.map +1 -0
  447. package/dist/src/types/attention.d.ts +249 -0
  448. package/dist/src/types/attention.d.ts.map +1 -0
  449. package/dist/src/types/attention.js +43 -0
  450. package/dist/src/types/attention.js.map +1 -0
  451. package/dist/src/types/quic.d.ts +518 -0
  452. package/dist/src/types/quic.d.ts.map +1 -0
  453. package/dist/src/types/quic.js +272 -0
  454. package/dist/src/types/quic.js.map +1 -0
  455. package/dist/src/utils/LegacyAttentionAdapter.d.ts +93 -0
  456. package/dist/src/utils/LegacyAttentionAdapter.d.ts.map +1 -0
  457. package/dist/src/utils/LegacyAttentionAdapter.js +241 -0
  458. package/dist/src/utils/LegacyAttentionAdapter.js.map +1 -0
  459. package/dist/src/utils/attention-metrics.d.ts +76 -0
  460. package/dist/src/utils/attention-metrics.d.ts.map +1 -0
  461. package/dist/src/utils/attention-metrics.js +178 -0
  462. package/dist/src/utils/attention-metrics.js.map +1 -0
  463. package/dist/src/utils/vector-math.d.ts +29 -0
  464. package/dist/src/utils/vector-math.d.ts.map +1 -0
  465. package/dist/src/utils/vector-math.js +66 -0
  466. package/dist/src/utils/vector-math.js.map +1 -0
  467. package/examples/README.md +105 -0
  468. package/examples/browser/attention-demo.html +499 -0
  469. package/examples/browser/flash-consolidation.html +598 -0
  470. package/examples/browser/hyperbolic-hierarchy.html +497 -0
  471. package/examples/quickstart.js +43 -0
  472. package/package.json +53 -56
  473. package/simulation/.claude-flow/metrics/agent-metrics.json +1 -0
  474. package/simulation/.claude-flow/metrics/performance.json +87 -0
  475. package/simulation/.claude-flow/metrics/task-metrics.json +10 -0
  476. package/simulation/COMPLETION-STATUS.md +139 -0
  477. package/simulation/FINAL-RESULTS.md +414 -0
  478. package/simulation/FINAL-STATUS.md +281 -0
  479. package/simulation/INTEGRATION-COMPLETE.md +452 -0
  480. package/simulation/MIGRATION-STATUS.md +231 -0
  481. package/simulation/OPTIMIZATION-RESULTS.md +397 -0
  482. package/simulation/PHASE1-COMPLETE.md +163 -0
  483. package/simulation/README.md +848 -0
  484. package/simulation/SIMULATION-RESULTS.md +239 -0
  485. package/simulation/cli.ts +78 -0
  486. package/simulation/configs/default.json +37 -0
  487. package/simulation/data/advanced/aidefence.graph +0 -0
  488. package/simulation/data/advanced/bmssp.graph +0 -0
  489. package/simulation/data/advanced/consciousness.graph +0 -0
  490. package/simulation/data/advanced/goalie.graph +0 -0
  491. package/simulation/data/advanced/psycho-symbolic.graph +0 -0
  492. package/simulation/data/advanced/research-swarm.graph +0 -0
  493. package/simulation/data/advanced/sublinear.graph +0 -0
  494. package/simulation/data/advanced/temporal.graph +0 -0
  495. package/simulation/data/causal.graph +0 -0
  496. package/simulation/data/graph-traversal.graph +0 -0
  497. package/simulation/data/lean-agentic.graph +0 -0
  498. package/simulation/data/reflexion.graph +0 -0
  499. package/simulation/data/skills.graph +0 -0
  500. package/simulation/data/stock-market.graph +0 -0
  501. package/simulation/data/strange-loops.graph +0 -0
  502. package/simulation/data/swarm.graph +0 -0
  503. package/simulation/data/voting-consensus.graph +0 -0
  504. package/simulation/docs/CLI-INTEGRATION-PLAN.md +1038 -0
  505. package/simulation/docs/COMPREHENSIVE-LATENT-SPACE-COMPLETION.md +354 -0
  506. package/simulation/docs/DOCUMENTATION-INDEX.md +226 -0
  507. package/simulation/docs/IMPLEMENTATION-COMPLETE.md +521 -0
  508. package/simulation/docs/OPTIMIZATION-SUMMARY.md +279 -0
  509. package/simulation/docs/README.md +229 -0
  510. package/simulation/docs/SWARM-5-INTEGRATION-SUMMARY.md +528 -0
  511. package/simulation/docs/TESTING-SUMMARY.md +304 -0
  512. package/simulation/docs/architecture/EXTENSION-API.md +868 -0
  513. package/simulation/docs/architecture/INTEGRATION-ARCHITECTURE.md +1138 -0
  514. package/simulation/docs/architecture/OPTIMIZATION-STRATEGY.md +778 -0
  515. package/simulation/docs/architecture/SIMULATION-ARCHITECTURE.md +892 -0
  516. package/simulation/docs/guides/CLI-REFERENCE.md +896 -0
  517. package/simulation/docs/guides/CUSTOM-SIMULATIONS.md +931 -0
  518. package/simulation/docs/guides/DEPLOYMENT.md +832 -0
  519. package/simulation/docs/guides/IMPLEMENTATION-SUMMARY.md +544 -0
  520. package/simulation/docs/guides/MIGRATION-GUIDE.md +591 -0
  521. package/simulation/docs/guides/QUICK-START.md +361 -0
  522. package/simulation/docs/guides/README.md +736 -0
  523. package/simulation/docs/guides/TROUBLESHOOTING.md +817 -0
  524. package/simulation/docs/guides/WIZARD-GUIDE.md +869 -0
  525. package/simulation/docs/reports/latent-space/MASTER-SYNTHESIS.md +345 -0
  526. package/simulation/docs/reports/latent-space/README.md +132 -0
  527. package/simulation/docs/reports/latent-space/attention-analysis-RESULTS.md +238 -0
  528. package/simulation/docs/reports/latent-space/clustering-analysis-RESULTS.md +210 -0
  529. package/simulation/docs/reports/latent-space/hnsw-exploration-RESULTS.md +332 -0
  530. package/simulation/docs/reports/latent-space/hypergraph-exploration-RESULTS.md +37 -0
  531. package/simulation/docs/reports/latent-space/neural-augmentation-RESULTS.md +69 -0
  532. package/simulation/docs/reports/latent-space/quantum-hybrid-RESULTS.md +91 -0
  533. package/simulation/docs/reports/latent-space/self-organizing-hnsw-RESULTS.md +51 -0
  534. package/simulation/docs/reports/latent-space/traversal-optimization-RESULTS.md +238 -0
  535. package/simulation/reports/README.md +397 -0
  536. package/simulation/reports/advanced-simulations-performance.md +1241 -0
  537. package/simulation/reports/aidefence-integration-2025-11-30T01-36-53-486Z.json +30 -0
  538. package/simulation/reports/architecture-analysis.md +1396 -0
  539. package/simulation/reports/basic-scenarios-performance.md +1840 -0
  540. package/simulation/reports/bmssp-integration-2025-11-30T01-36-27-193Z.json +30 -0
  541. package/simulation/reports/bmssp-integration-2025-11-30T03-38-12-887Z.json +30 -0
  542. package/simulation/reports/causal-reasoning-2025-11-29T23-35-21-795Z.json +36 -0
  543. package/simulation/reports/causal-reasoning-2025-11-30T00-58-42-862Z.json +30 -0
  544. package/simulation/reports/causal-reasoning-2025-11-30T00-59-12-546Z.json +40 -0
  545. package/simulation/reports/consciousness-explorer-2025-11-30T01-36-51-269Z.json +31 -0
  546. package/simulation/reports/core-benchmarks.md +727 -0
  547. package/simulation/reports/goalie-integration-2025-11-30T01-36-52-377Z.json +30 -0
  548. package/simulation/reports/graph-traversal-2025-11-29T23-35-35-279Z.json +78 -0
  549. package/simulation/reports/graph-traversal-2025-11-29T23-37-36-697Z.json +30 -0
  550. package/simulation/reports/graph-traversal-2025-11-30T01-03-59-716Z.json +30 -0
  551. package/simulation/reports/graph-traversal-2025-11-30T01-05-10-984Z.json +30 -0
  552. package/simulation/reports/graph-traversal-2025-11-30T01-06-16-334Z.json +30 -0
  553. package/simulation/reports/graph-traversal-2025-11-30T01-06-53-312Z.json +30 -0
  554. package/simulation/reports/graph-traversal-2025-11-30T01-07-51-075Z.json +24 -0
  555. package/simulation/reports/graph-traversal-2025-11-30T01-08-22-179Z.json +42 -0
  556. package/simulation/reports/lean-agentic-swarm-2025-11-29T23-37-23-804Z.json +148 -0
  557. package/simulation/reports/lean-agentic-swarm-2025-11-30T01-31-24-401Z.json +31 -0
  558. package/simulation/reports/lean-agentic-swarm-2025-11-30T03-38-01-470Z.json +31 -0
  559. package/simulation/reports/multi-agent-swarm-2025-11-29T23-35-28-093Z.json +78 -0
  560. package/simulation/reports/multi-agent-swarm-2025-11-30T01-03-54-062Z.json +42 -0
  561. package/simulation/reports/multi-agent-swarm-2025-11-30T01-05-06-092Z.json +42 -0
  562. package/simulation/reports/psycho-symbolic-reasoner-2025-11-30T01-36-50-180Z.json +30 -0
  563. package/simulation/reports/quality-metrics.md +727 -0
  564. package/simulation/reports/reflexion-learning-2025-11-29T23-35-09-774Z.json +48 -0
  565. package/simulation/reports/reflexion-learning-2025-11-29T23-37-16-934Z.json +36 -0
  566. package/simulation/reports/reflexion-learning-2025-11-30T00-07-49-259Z.json +30 -0
  567. package/simulation/reports/reflexion-learning-2025-11-30T00-09-29-319Z.json +51 -0
  568. package/simulation/reports/reflexion-learning-2025-11-30T00-28-37-659Z.json +51 -0
  569. package/simulation/reports/reflexion-learning-2025-11-30T01-31-30-690Z.json +29 -0
  570. package/simulation/reports/reflexion-learning-2025-11-30T03-38-06-937Z.json +29 -0
  571. package/simulation/reports/research-foundations.md +2004 -0
  572. package/simulation/reports/research-swarm-2025-11-30T01-36-54-647Z.json +30 -0
  573. package/simulation/reports/scalability-deployment.md +2404 -0
  574. package/simulation/reports/skill-evolution-2025-11-29T23-35-15-945Z.json +36 -0
  575. package/simulation/reports/skill-evolution-2025-11-30T01-03-17-995Z.json +30 -0
  576. package/simulation/reports/skill-evolution-2025-11-30T01-03-48-441Z.json +30 -0
  577. package/simulation/reports/skill-evolution-2025-11-30T01-05-00-554Z.json +30 -0
  578. package/simulation/reports/skill-evolution-2025-11-30T01-06-11-436Z.json +30 -0
  579. package/simulation/reports/skill-evolution-2025-11-30T01-06-51-979Z.json +30 -0
  580. package/simulation/reports/skill-evolution-2025-11-30T01-07-32-695Z.json +40 -0
  581. package/simulation/reports/stock-market-emergence-2025-11-30T00-11-43-865Z.json +56 -0
  582. package/simulation/reports/stock-market-emergence-2025-11-30T00-28-57-495Z.json +56 -0
  583. package/simulation/reports/strange-loops-2025-11-29T23-37-30-621Z.json +78 -0
  584. package/simulation/reports/strange-loops-2025-11-30T00-07-55-415Z.json +30 -0
  585. package/simulation/reports/strange-loops-2025-11-30T00-09-35-133Z.json +30 -0
  586. package/simulation/reports/strange-loops-2025-11-30T00-48-50-744Z.json +24 -0
  587. package/simulation/reports/strange-loops-2025-11-30T00-54-48-044Z.json +24 -0
  588. package/simulation/reports/strange-loops-2025-11-30T00-57-27-633Z.json +24 -0
  589. package/simulation/reports/strange-loops-2025-11-30T00-57-59-135Z.json +42 -0
  590. package/simulation/reports/sublinear-solver-2025-11-30T01-36-33-134Z.json +30 -0
  591. package/simulation/reports/temporal-lead-solver-2025-11-30T01-36-38-628Z.json +30 -0
  592. package/simulation/reports/use-cases-applications.md +2212 -0
  593. package/simulation/reports/voting-system-consensus-2025-11-30T00-11-37-199Z.json +58 -0
  594. package/simulation/reports/voting-system-consensus-2025-11-30T00-28-47-735Z.json +58 -0
  595. package/simulation/runner.ts +300 -0
  596. package/simulation/scenarios/README-advanced/aidefence-integration.md +63 -0
  597. package/simulation/scenarios/README-advanced/bmssp-integration.md +58 -0
  598. package/simulation/scenarios/README-advanced/consciousness-explorer.md +53 -0
  599. package/simulation/scenarios/README-advanced/goalie-integration.md +61 -0
  600. package/simulation/scenarios/README-advanced/psycho-symbolic-reasoner.md +55 -0
  601. package/simulation/scenarios/README-advanced/research-swarm.md +63 -0
  602. package/simulation/scenarios/README-advanced/sublinear-solver.md +58 -0
  603. package/simulation/scenarios/README-advanced/temporal-lead-solver.md +55 -0
  604. package/simulation/scenarios/README-basic/causal-reasoning.md +39 -0
  605. package/simulation/scenarios/README-basic/graph-traversal.md +41 -0
  606. package/simulation/scenarios/README-basic/lean-agentic-swarm.md +122 -0
  607. package/simulation/scenarios/README-basic/multi-agent-swarm.md +34 -0
  608. package/simulation/scenarios/README-basic/reflexion-learning.md +41 -0
  609. package/simulation/scenarios/README-basic/skill-evolution.md +38 -0
  610. package/simulation/scenarios/README-basic/stock-market-emergence.md +28 -0
  611. package/simulation/scenarios/README-basic/strange-loops.md +36 -0
  612. package/simulation/scenarios/README-basic/voting-system-consensus.md +28 -0
  613. package/simulation/scenarios/README.md +438 -0
  614. package/simulation/scenarios/aidefence-integration.ts +165 -0
  615. package/simulation/scenarios/bmssp-integration.ts +137 -0
  616. package/simulation/scenarios/causal-reasoning.ts +143 -0
  617. package/simulation/scenarios/consciousness-explorer.ts +139 -0
  618. package/simulation/scenarios/domain-examples/.claude-flow/metrics/agent-metrics.json +1 -0
  619. package/simulation/scenarios/domain-examples/.claude-flow/metrics/performance.json +87 -0
  620. package/simulation/scenarios/domain-examples/.claude-flow/metrics/task-metrics.json +10 -0
  621. package/simulation/scenarios/domain-examples/README.md +525 -0
  622. package/simulation/scenarios/domain-examples/e-commerce-recommendations.ts +220 -0
  623. package/simulation/scenarios/domain-examples/index.ts +81 -0
  624. package/simulation/scenarios/domain-examples/iot-sensor-networks.ts +290 -0
  625. package/simulation/scenarios/domain-examples/medical-imaging.ts +181 -0
  626. package/simulation/scenarios/domain-examples/robotics-navigation.ts +214 -0
  627. package/simulation/scenarios/domain-examples/scientific-research.ts +250 -0
  628. package/simulation/scenarios/domain-examples/trading-systems.ts +138 -0
  629. package/simulation/scenarios/goalie-integration.ts +161 -0
  630. package/simulation/scenarios/graph-traversal.ts +129 -0
  631. package/simulation/scenarios/latent-space/OPTIMIZATION-COMPLETE.md +287 -0
  632. package/simulation/scenarios/latent-space/README-attention-analysis.md +170 -0
  633. package/simulation/scenarios/latent-space/README-clustering-analysis.md +239 -0
  634. package/simulation/scenarios/latent-space/README-hnsw-exploration.md +199 -0
  635. package/simulation/scenarios/latent-space/README-hypergraph-exploration.md +279 -0
  636. package/simulation/scenarios/latent-space/README-neural-augmentation.md +267 -0
  637. package/simulation/scenarios/latent-space/README-quantum-hybrid.md +276 -0
  638. package/simulation/scenarios/latent-space/README-self-organizing-hnsw.md +244 -0
  639. package/simulation/scenarios/latent-space/README-traversal-optimization.md +212 -0
  640. package/simulation/scenarios/latent-space/attention-analysis.ts +598 -0
  641. package/simulation/scenarios/latent-space/clustering-analysis.ts +796 -0
  642. package/simulation/scenarios/latent-space/hnsw-exploration.ts +526 -0
  643. package/simulation/scenarios/latent-space/hypergraph-exploration.ts +706 -0
  644. package/simulation/scenarios/latent-space/index.ts +47 -0
  645. package/simulation/scenarios/latent-space/neural-augmentation.ts +604 -0
  646. package/simulation/scenarios/latent-space/quantum-hybrid.ts +508 -0
  647. package/simulation/scenarios/latent-space/self-organizing-hnsw.ts +680 -0
  648. package/simulation/scenarios/latent-space/traversal-optimization.ts +782 -0
  649. package/simulation/scenarios/lean-agentic-swarm.ts +182 -0
  650. package/simulation/scenarios/multi-agent-swarm.ts +146 -0
  651. package/simulation/scenarios/psycho-symbolic-reasoner.ts +136 -0
  652. package/simulation/scenarios/reflexion-learning.ts +132 -0
  653. package/simulation/scenarios/research-swarm.ts +187 -0
  654. package/simulation/scenarios/skill-evolution.ts +135 -0
  655. package/simulation/scenarios/stock-market-emergence.ts +323 -0
  656. package/simulation/scenarios/strange-loops.ts +175 -0
  657. package/simulation/scenarios/sublinear-solver.ts +108 -0
  658. package/simulation/scenarios/temporal-lead-solver.ts +121 -0
  659. package/simulation/scenarios/voting-system-consensus.ts +251 -0
  660. package/simulation/tests/latent-space/attention-analysis.test.ts +204 -0
  661. package/simulation/tests/latent-space/clustering-analysis.test.ts +281 -0
  662. package/simulation/tests/latent-space/hnsw-exploration.test.ts +253 -0
  663. package/simulation/tests/latent-space/hypergraph-exploration.test.ts +295 -0
  664. package/simulation/tests/latent-space/neural-augmentation.test.ts +326 -0
  665. package/simulation/tests/latent-space/quantum-hybrid.test.ts +307 -0
  666. package/simulation/tests/latent-space/self-organizing-hnsw.test.ts +291 -0
  667. package/simulation/tests/latent-space/traversal-optimization.test.ts +261 -0
  668. package/simulation/types.ts +177 -0
  669. package/simulation/utils/PerformanceOptimizer.ts +269 -0
  670. package/src/backends/GraphBackend.ts +290 -0
  671. package/src/backends/LearningBackend.ts +210 -0
  672. package/src/backends/README.md +389 -0
  673. package/src/backends/VectorBackend.ts +147 -0
  674. package/src/backends/detector.ts +283 -0
  675. package/src/backends/factory.ts +279 -0
  676. package/src/backends/graph/GraphDatabaseAdapter.ts +334 -0
  677. package/src/backends/hnswlib/HNSWLibBackend.ts +419 -0
  678. package/src/backends/hnswlib/index.ts +7 -0
  679. package/src/backends/index.ts +32 -0
  680. package/src/backends/ruvector/GuardedVectorBackend.ts +219 -0
  681. package/src/backends/ruvector/RuVectorBackend.ts +343 -0
  682. package/src/backends/ruvector/RuVectorLearning.ts +254 -0
  683. package/src/backends/ruvector/index.ts +9 -0
  684. package/src/benchmarks/wasm-vector-benchmark.ts +250 -0
  685. package/src/browser/AdvancedFeatures.ts +565 -0
  686. package/src/browser/AttentionBrowser.ts +387 -0
  687. package/src/browser/HNSWIndex.ts +494 -0
  688. package/src/browser/ProductQuantization.ts +419 -0
  689. package/src/browser/index.ts +317 -0
  690. package/src/cli/agentdb-cli.ts +2712 -0
  691. package/src/cli/attention-cli-integration.ts +91 -0
  692. package/src/cli/commands/attention.ts +656 -0
  693. package/src/cli/commands/doctor.ts +322 -0
  694. package/src/cli/commands/init.ts +176 -0
  695. package/src/cli/commands/install-embeddings.ts +81 -0
  696. package/src/cli/commands/migrate.ts +545 -0
  697. package/src/cli/commands/simulate-custom.ts +232 -0
  698. package/src/cli/commands/simulate-report.ts +171 -0
  699. package/src/cli/commands/simulate-wizard.ts +379 -0
  700. package/src/cli/commands/simulate.ts +115 -0
  701. package/src/cli/commands/status.ts +156 -0
  702. package/src/cli/examples.sh +83 -0
  703. package/src/cli/lib/attention-config.ts +326 -0
  704. package/src/cli/lib/config-manager.ts +627 -0
  705. package/src/cli/lib/config-validator.ts +261 -0
  706. package/src/cli/lib/health-monitor.ts +513 -0
  707. package/src/cli/lib/help-formatter.ts +406 -0
  708. package/src/cli/lib/history-tracker.ts +503 -0
  709. package/src/cli/lib/report-generator.ts +455 -0
  710. package/src/cli/lib/report-store.ts +582 -0
  711. package/src/cli/lib/simulation-registry.ts +503 -0
  712. package/src/cli/lib/simulation-runner.ts +291 -0
  713. package/src/cli/tests/agentdb-cli.test.ts +58 -0
  714. package/src/cli/tests/attention-cli.test.ts +335 -0
  715. package/src/controllers/AttentionService.ts +770 -0
  716. package/src/controllers/CausalMemoryGraph.ts +773 -0
  717. package/src/controllers/CausalRecall.ts +484 -0
  718. package/src/controllers/ContextSynthesizer.ts +285 -0
  719. package/src/controllers/EmbeddingService.ts +161 -0
  720. package/src/controllers/EnhancedEmbeddingService.ts +143 -0
  721. package/src/controllers/ExplainableRecall.ts +746 -0
  722. package/src/controllers/HNSWIndex.ts +495 -0
  723. package/src/controllers/LearningSystem.ts +1270 -0
  724. package/src/controllers/MMRDiversityRanker.ts +187 -0
  725. package/src/controllers/MetadataFilter.ts +280 -0
  726. package/src/controllers/NightlyLearner.ts +647 -0
  727. package/src/controllers/QUICClient.ts +413 -0
  728. package/src/controllers/QUICServer.ts +498 -0
  729. package/src/controllers/ReasoningBank.ts +665 -0
  730. package/src/controllers/ReflexionMemory.ts +872 -0
  731. package/src/controllers/SkillLibrary.ts +795 -0
  732. package/src/controllers/SyncCoordinator.ts +597 -0
  733. package/src/controllers/WASMVectorSearch.ts +292 -0
  734. package/src/controllers/frontier-index.ts +35 -0
  735. package/src/controllers/index.ts +57 -0
  736. package/src/coordination/MultiDatabaseCoordinator.ts +1107 -0
  737. package/src/coordination/index.ts +24 -0
  738. package/src/core/AgentDB.ts +211 -0
  739. package/src/db-fallback.ts +296 -0
  740. package/src/db-test.ts +59 -0
  741. package/src/db-unified.ts +327 -0
  742. package/src/examples/quic-sync-example.ts +198 -0
  743. package/src/examples/wasm-vector-usage.ts +245 -0
  744. package/src/index.ts +69 -0
  745. package/src/mcp/agentdb-mcp-server.ts +2318 -0
  746. package/src/mcp/attention-mcp-integration.ts +145 -0
  747. package/src/mcp/attention-tools-handlers.ts +586 -0
  748. package/src/mcp/learning-tools-handlers.ts +106 -0
  749. package/src/optimizations/BatchOperations.ts +594 -0
  750. package/src/optimizations/QueryOptimizer.ts +297 -0
  751. package/src/optimizations/ToolCache.ts +355 -0
  752. package/src/optimizations/index.ts +11 -0
  753. package/src/schemas/frontier-schema.sql +378 -0
  754. package/src/schemas/schema.sql +382 -0
  755. package/src/security/AttestationLog.ts +252 -0
  756. package/src/security/MutationGuard.ts +420 -0
  757. package/src/security/index.ts +52 -0
  758. package/src/security/input-validation.ts +543 -0
  759. package/src/security/limits.ts +375 -0
  760. package/src/security/path-security.ts +436 -0
  761. package/src/security/validation.ts +556 -0
  762. package/src/services/GraphTransformerService.ts +389 -0
  763. package/src/services/LLMRouter.ts +380 -0
  764. package/src/services/SemanticRouter.ts +169 -0
  765. package/src/services/SonaTrajectoryService.ts +264 -0
  766. package/src/tests/attention-service.test.ts +492 -0
  767. package/src/tests/wasm-vector-search.test.ts +240 -0
  768. package/src/types/attention.ts +392 -0
  769. package/src/types/quic.ts +772 -0
  770. package/src/utils/LegacyAttentionAdapter.ts +393 -0
  771. package/src/utils/NodeIdMapper.ts +64 -0
  772. package/src/utils/attention-metrics.ts +253 -0
  773. package/src/utils/vector-math.ts +71 -0
  774. package/LICENSE +0 -21
  775. package/dist/src/backends/rvf/AdaptiveIndexTuner.d.ts +0 -175
  776. package/dist/src/backends/rvf/AdaptiveIndexTuner.d.ts.map +0 -1
  777. package/dist/src/backends/rvf/AdaptiveIndexTuner.js +0 -559
  778. package/dist/src/backends/rvf/AdaptiveIndexTuner.js.map +0 -1
  779. package/dist/src/backends/rvf/ContrastiveTrainer.d.ts +0 -148
  780. package/dist/src/backends/rvf/ContrastiveTrainer.d.ts.map +0 -1
  781. package/dist/src/backends/rvf/ContrastiveTrainer.js +0 -438
  782. package/dist/src/backends/rvf/ContrastiveTrainer.js.map +0 -1
  783. package/dist/src/backends/rvf/FederatedSessionManager.d.ts +0 -211
  784. package/dist/src/backends/rvf/FederatedSessionManager.d.ts.map +0 -1
  785. package/dist/src/backends/rvf/FederatedSessionManager.js +0 -389
  786. package/dist/src/backends/rvf/FederatedSessionManager.js.map +0 -1
  787. package/dist/src/backends/rvf/FilterBuilder.d.ts +0 -136
  788. package/dist/src/backends/rvf/FilterBuilder.d.ts.map +0 -1
  789. package/dist/src/backends/rvf/FilterBuilder.js +0 -157
  790. package/dist/src/backends/rvf/FilterBuilder.js.map +0 -1
  791. package/dist/src/backends/rvf/NativeAccelerator.d.ts +0 -140
  792. package/dist/src/backends/rvf/NativeAccelerator.d.ts.map +0 -1
  793. package/dist/src/backends/rvf/NativeAccelerator.js +0 -630
  794. package/dist/src/backends/rvf/NativeAccelerator.js.map +0 -1
  795. package/dist/src/backends/rvf/RvfBackend.d.ts +0 -194
  796. package/dist/src/backends/rvf/RvfBackend.d.ts.map +0 -1
  797. package/dist/src/backends/rvf/RvfBackend.js +0 -607
  798. package/dist/src/backends/rvf/RvfBackend.js.map +0 -1
  799. package/dist/src/backends/rvf/RvfSolver.d.ts +0 -175
  800. package/dist/src/backends/rvf/RvfSolver.d.ts.map +0 -1
  801. package/dist/src/backends/rvf/RvfSolver.js +0 -176
  802. package/dist/src/backends/rvf/RvfSolver.js.map +0 -1
  803. package/dist/src/backends/rvf/SelfLearningRvfBackend.d.ts +0 -143
  804. package/dist/src/backends/rvf/SelfLearningRvfBackend.d.ts.map +0 -1
  805. package/dist/src/backends/rvf/SelfLearningRvfBackend.js +0 -569
  806. package/dist/src/backends/rvf/SelfLearningRvfBackend.js.map +0 -1
  807. package/dist/src/backends/rvf/SemanticQueryRouter.d.ts +0 -128
  808. package/dist/src/backends/rvf/SemanticQueryRouter.d.ts.map +0 -1
  809. package/dist/src/backends/rvf/SemanticQueryRouter.js +0 -415
  810. package/dist/src/backends/rvf/SemanticQueryRouter.js.map +0 -1
  811. package/dist/src/backends/rvf/SimdFallbacks.d.ts +0 -25
  812. package/dist/src/backends/rvf/SimdFallbacks.d.ts.map +0 -1
  813. package/dist/src/backends/rvf/SimdFallbacks.js +0 -287
  814. package/dist/src/backends/rvf/SimdFallbacks.js.map +0 -1
  815. package/dist/src/backends/rvf/SolverBandit.d.ts +0 -100
  816. package/dist/src/backends/rvf/SolverBandit.d.ts.map +0 -1
  817. package/dist/src/backends/rvf/SolverBandit.js +0 -216
  818. package/dist/src/backends/rvf/SolverBandit.js.map +0 -1
  819. package/dist/src/backends/rvf/SonaLearningBackend.d.ts +0 -157
  820. package/dist/src/backends/rvf/SonaLearningBackend.d.ts.map +0 -1
  821. package/dist/src/backends/rvf/SonaLearningBackend.js +0 -283
  822. package/dist/src/backends/rvf/SonaLearningBackend.js.map +0 -1
  823. package/dist/src/backends/rvf/SqlJsRvfBackend.d.ts +0 -77
  824. package/dist/src/backends/rvf/SqlJsRvfBackend.d.ts.map +0 -1
  825. package/dist/src/backends/rvf/SqlJsRvfBackend.js +0 -382
  826. package/dist/src/backends/rvf/SqlJsRvfBackend.js.map +0 -1
  827. package/dist/src/backends/rvf/WasmStoreBridge.d.ts +0 -27
  828. package/dist/src/backends/rvf/WasmStoreBridge.d.ts.map +0 -1
  829. package/dist/src/backends/rvf/WasmStoreBridge.js +0 -87
  830. package/dist/src/backends/rvf/WasmStoreBridge.js.map +0 -1
  831. package/dist/src/backends/rvf/validation.d.ts +0 -20
  832. package/dist/src/backends/rvf/validation.d.ts.map +0 -1
  833. package/dist/src/backends/rvf/validation.js +0 -78
  834. package/dist/src/backends/rvf/validation.js.map +0 -1
  835. package/dist/src/benchmark/BenchmarkSuite.d.ts +0 -318
  836. package/dist/src/benchmark/BenchmarkSuite.d.ts.map +0 -1
  837. package/dist/src/benchmark/BenchmarkSuite.js +0 -986
  838. package/dist/src/benchmark/BenchmarkSuite.js.map +0 -1
  839. package/dist/src/benchmark/index.d.ts +0 -29
  840. package/dist/src/benchmark/index.d.ts.map +0 -1
  841. package/dist/src/benchmark/index.js +0 -39
  842. package/dist/src/benchmark/index.js.map +0 -1
  843. package/dist/src/cli/commands/hyperbolic.d.ts +0 -11
  844. package/dist/src/cli/commands/hyperbolic.d.ts.map +0 -1
  845. package/dist/src/cli/commands/hyperbolic.js +0 -428
  846. package/dist/src/cli/commands/hyperbolic.js.map +0 -1
  847. package/dist/src/cli/commands/learn.d.ts +0 -11
  848. package/dist/src/cli/commands/learn.d.ts.map +0 -1
  849. package/dist/src/cli/commands/learn.js +0 -404
  850. package/dist/src/cli/commands/learn.js.map +0 -1
  851. package/dist/src/cli/commands/route.d.ts +0 -11
  852. package/dist/src/cli/commands/route.d.ts.map +0 -1
  853. package/dist/src/cli/commands/route.js +0 -414
  854. package/dist/src/cli/commands/route.js.map +0 -1
  855. package/dist/src/cli/commands/rvf.d.ts +0 -21
  856. package/dist/src/cli/commands/rvf.d.ts.map +0 -1
  857. package/dist/src/cli/commands/rvf.js +0 -448
  858. package/dist/src/cli/commands/rvf.js.map +0 -1
  859. package/dist/src/cli/tests/agentdb-cli.test.d.ts +0 -8
  860. package/dist/src/cli/tests/agentdb-cli.test.d.ts.map +0 -1
  861. package/dist/src/cli/tests/agentdb-cli.test.js +0 -50
  862. package/dist/src/cli/tests/agentdb-cli.test.js.map +0 -1
  863. package/dist/src/cli/tests/attention-cli.test.d.ts +0 -5
  864. package/dist/src/cli/tests/attention-cli.test.d.ts.map +0 -1
  865. package/dist/src/cli/tests/attention-cli.test.js +0 -257
  866. package/dist/src/cli/tests/attention-cli.test.js.map +0 -1
  867. package/dist/src/compatibility/DeprecationWarnings.d.ts +0 -54
  868. package/dist/src/compatibility/DeprecationWarnings.d.ts.map +0 -1
  869. package/dist/src/compatibility/DeprecationWarnings.js +0 -131
  870. package/dist/src/compatibility/DeprecationWarnings.js.map +0 -1
  871. package/dist/src/compatibility/MigrationUtilities.d.ts +0 -30
  872. package/dist/src/compatibility/MigrationUtilities.d.ts.map +0 -1
  873. package/dist/src/compatibility/MigrationUtilities.js +0 -184
  874. package/dist/src/compatibility/MigrationUtilities.js.map +0 -1
  875. package/dist/src/compatibility/V1toV2Adapter.d.ts +0 -76
  876. package/dist/src/compatibility/V1toV2Adapter.d.ts.map +0 -1
  877. package/dist/src/compatibility/V1toV2Adapter.js +0 -198
  878. package/dist/src/compatibility/V1toV2Adapter.js.map +0 -1
  879. package/dist/src/compatibility/VersionDetector.d.ts +0 -32
  880. package/dist/src/compatibility/VersionDetector.d.ts.map +0 -1
  881. package/dist/src/compatibility/VersionDetector.js +0 -144
  882. package/dist/src/compatibility/VersionDetector.js.map +0 -1
  883. package/dist/src/compatibility/index.d.ts +0 -11
  884. package/dist/src/compatibility/index.d.ts.map +0 -1
  885. package/dist/src/compatibility/index.js +0 -10
  886. package/dist/src/compatibility/index.js.map +0 -1
  887. package/dist/src/compatibility/types.d.ts +0 -103
  888. package/dist/src/compatibility/types.d.ts.map +0 -1
  889. package/dist/src/compatibility/types.js +0 -5
  890. package/dist/src/compatibility/types.js.map +0 -1
  891. package/dist/src/controllers/MemoryController.d.ts +0 -161
  892. package/dist/src/controllers/MemoryController.d.ts.map +0 -1
  893. package/dist/src/controllers/MemoryController.js +0 -290
  894. package/dist/src/controllers/MemoryController.js.map +0 -1
  895. package/dist/src/controllers/attention/CrossAttentionController.d.ts +0 -141
  896. package/dist/src/controllers/attention/CrossAttentionController.d.ts.map +0 -1
  897. package/dist/src/controllers/attention/CrossAttentionController.js +0 -325
  898. package/dist/src/controllers/attention/CrossAttentionController.js.map +0 -1
  899. package/dist/src/controllers/attention/MultiHeadAttentionController.d.ts +0 -137
  900. package/dist/src/controllers/attention/MultiHeadAttentionController.d.ts.map +0 -1
  901. package/dist/src/controllers/attention/MultiHeadAttentionController.js +0 -339
  902. package/dist/src/controllers/attention/MultiHeadAttentionController.js.map +0 -1
  903. package/dist/src/controllers/attention/SelfAttentionController.d.ts +0 -117
  904. package/dist/src/controllers/attention/SelfAttentionController.d.ts.map +0 -1
  905. package/dist/src/controllers/attention/SelfAttentionController.js +0 -205
  906. package/dist/src/controllers/attention/SelfAttentionController.js.map +0 -1
  907. package/dist/src/controllers/attention/index.d.ts +0 -15
  908. package/dist/src/controllers/attention/index.d.ts.map +0 -1
  909. package/dist/src/controllers/attention/index.js +0 -12
  910. package/dist/src/controllers/attention/index.js.map +0 -1
  911. package/dist/src/core/QueryCache.d.ts +0 -138
  912. package/dist/src/core/QueryCache.d.ts.map +0 -1
  913. package/dist/src/core/QueryCache.js +0 -313
  914. package/dist/src/core/QueryCache.js.map +0 -1
  915. package/dist/src/observability/index.d.ts +0 -8
  916. package/dist/src/observability/index.d.ts.map +0 -1
  917. package/dist/src/observability/index.js +0 -8
  918. package/dist/src/observability/index.js.map +0 -1
  919. package/dist/src/observability/integration.d.ts +0 -32
  920. package/dist/src/observability/integration.d.ts.map +0 -1
  921. package/dist/src/observability/integration.js +0 -157
  922. package/dist/src/observability/integration.js.map +0 -1
  923. package/dist/src/observability/telemetry.d.ts +0 -137
  924. package/dist/src/observability/telemetry.d.ts.map +0 -1
  925. package/dist/src/observability/telemetry.js +0 -420
  926. package/dist/src/observability/telemetry.js.map +0 -1
  927. package/dist/src/quantization/index.d.ts +0 -7
  928. package/dist/src/quantization/index.d.ts.map +0 -1
  929. package/dist/src/quantization/index.js +0 -15
  930. package/dist/src/quantization/index.js.map +0 -1
  931. package/dist/src/quantization/vector-quantization.d.ts +0 -388
  932. package/dist/src/quantization/vector-quantization.d.ts.map +0 -1
  933. package/dist/src/quantization/vector-quantization.js +0 -1136
  934. package/dist/src/quantization/vector-quantization.js.map +0 -1
  935. package/dist/src/search/HybridSearch.d.ts +0 -311
  936. package/dist/src/search/HybridSearch.d.ts.map +0 -1
  937. package/dist/src/search/HybridSearch.js +0 -712
  938. package/dist/src/search/HybridSearch.js.map +0 -1
  939. package/dist/src/search/index.d.ts +0 -12
  940. package/dist/src/search/index.d.ts.map +0 -1
  941. package/dist/src/search/index.js +0 -16
  942. package/dist/src/search/index.js.map +0 -1
  943. package/dist/src/services/AttentionService.d.ts +0 -303
  944. package/dist/src/services/AttentionService.d.ts.map +0 -1
  945. package/dist/src/services/AttentionService.js +0 -1167
  946. package/dist/src/services/AttentionService.js.map +0 -1
  947. package/dist/src/simd/index.d.ts +0 -9
  948. package/dist/src/simd/index.d.ts.map +0 -1
  949. package/dist/src/simd/index.js +0 -27
  950. package/dist/src/simd/index.js.map +0 -1
  951. package/dist/src/simd/simd-vector-ops.d.ts +0 -332
  952. package/dist/src/simd/simd-vector-ops.d.ts.map +0 -1
  953. package/dist/src/simd/simd-vector-ops.js +0 -947
  954. package/dist/src/simd/simd-vector-ops.js.map +0 -1
  955. package/dist/src/tests/attention-service.test.d.ts +0 -7
  956. package/dist/src/tests/attention-service.test.d.ts.map +0 -1
  957. package/dist/src/tests/attention-service.test.js +0 -401
  958. package/dist/src/tests/attention-service.test.js.map +0 -1
  959. package/dist/src/tests/integration/compatibility/backwards-compat.integration.test.d.ts +0 -7
  960. package/dist/src/tests/integration/compatibility/backwards-compat.integration.test.d.ts.map +0 -1
  961. package/dist/src/tests/integration/compatibility/backwards-compat.integration.test.js +0 -283
  962. package/dist/src/tests/integration/compatibility/backwards-compat.integration.test.js.map +0 -1
  963. package/dist/src/tests/query-cache.test.d.ts +0 -7
  964. package/dist/src/tests/query-cache.test.d.ts.map +0 -1
  965. package/dist/src/tests/query-cache.test.js +0 -343
  966. package/dist/src/tests/query-cache.test.js.map +0 -1
  967. package/dist/src/tests/ruvector-integration.test.d.ts +0 -14
  968. package/dist/src/tests/ruvector-integration.test.d.ts.map +0 -1
  969. package/dist/src/tests/ruvector-integration.test.js +0 -1156
  970. package/dist/src/tests/ruvector-integration.test.js.map +0 -1
  971. package/dist/src/tests/unit/auth/crypto.utils.test.d.ts +0 -6
  972. package/dist/src/tests/unit/auth/crypto.utils.test.d.ts.map +0 -1
  973. package/dist/src/tests/unit/auth/crypto.utils.test.js +0 -310
  974. package/dist/src/tests/unit/auth/crypto.utils.test.js.map +0 -1
  975. package/dist/src/tests/unit/compatibility/deprecation-warnings.test.d.ts +0 -5
  976. package/dist/src/tests/unit/compatibility/deprecation-warnings.test.d.ts.map +0 -1
  977. package/dist/src/tests/unit/compatibility/deprecation-warnings.test.js +0 -207
  978. package/dist/src/tests/unit/compatibility/deprecation-warnings.test.js.map +0 -1
  979. package/dist/src/tests/unit/compatibility/migration-utils.test.d.ts +0 -5
  980. package/dist/src/tests/unit/compatibility/migration-utils.test.d.ts.map +0 -1
  981. package/dist/src/tests/unit/compatibility/migration-utils.test.js +0 -264
  982. package/dist/src/tests/unit/compatibility/migration-utils.test.js.map +0 -1
  983. package/dist/src/tests/unit/compatibility/v1-adapter.test.d.ts +0 -7
  984. package/dist/src/tests/unit/compatibility/v1-adapter.test.d.ts.map +0 -1
  985. package/dist/src/tests/unit/compatibility/v1-adapter.test.js +0 -228
  986. package/dist/src/tests/unit/compatibility/v1-adapter.test.js.map +0 -1
  987. package/dist/src/tests/unit/compatibility/version-detector.test.d.ts +0 -10
  988. package/dist/src/tests/unit/compatibility/version-detector.test.d.ts.map +0 -1
  989. package/dist/src/tests/unit/compatibility/version-detector.test.js +0 -162
  990. package/dist/src/tests/unit/compatibility/version-detector.test.js.map +0 -1
  991. package/dist/src/tests/vector-quantization.test.d.ts +0 -5
  992. package/dist/src/tests/vector-quantization.test.d.ts.map +0 -1
  993. package/dist/src/tests/vector-quantization.test.js +0 -338
  994. package/dist/src/tests/vector-quantization.test.js.map +0 -1
  995. package/dist/src/tests/wasm-vector-search.test.d.ts +0 -7
  996. package/dist/src/tests/wasm-vector-search.test.d.ts.map +0 -1
  997. package/dist/src/tests/wasm-vector-search.test.js +0 -193
  998. package/dist/src/tests/wasm-vector-search.test.js.map +0 -1
  999. package/dist/src/types/database.types.d.ts +0 -275
  1000. package/dist/src/types/database.types.d.ts.map +0 -1
  1001. package/dist/src/types/database.types.js +0 -57
  1002. package/dist/src/types/database.types.js.map +0 -1
  1003. package/dist/src/utils/chalk-fallback.d.ts +0 -3
  1004. package/dist/src/utils/chalk-fallback.d.ts.map +0 -1
  1005. package/dist/src/utils/chalk-fallback.js +0 -20
  1006. package/dist/src/utils/chalk-fallback.js.map +0 -1
  1007. package/dist/src/utils/crypto.utils.d.ts +0 -122
  1008. package/dist/src/utils/crypto.utils.d.ts.map +0 -1
  1009. package/dist/src/utils/crypto.utils.js +0 -296
  1010. package/dist/src/utils/crypto.utils.js.map +0 -1
  1011. package/dist/src/utils/similarity.d.ts +0 -11
  1012. package/dist/src/utils/similarity.d.ts.map +0 -1
  1013. package/dist/src/utils/similarity.js +0 -25
  1014. package/dist/src/utils/similarity.js.map +0 -1
  1015. package/dist/src/wasm-loader.d.ts +0 -67
  1016. package/dist/src/wasm-loader.d.ts.map +0 -1
  1017. package/dist/src/wasm-loader.js +0 -78
  1018. package/dist/src/wasm-loader.js.map +0 -1
  1019. package/dist/src/wrappers/agentdb-fast.d.ts +0 -139
  1020. package/dist/src/wrappers/agentdb-fast.d.ts.map +0 -1
  1021. package/dist/src/wrappers/agentdb-fast.js +0 -316
  1022. package/dist/src/wrappers/agentdb-fast.js.map +0 -1
  1023. package/dist/src/wrappers/attention-fallbacks.d.ts +0 -351
  1024. package/dist/src/wrappers/attention-fallbacks.d.ts.map +0 -1
  1025. package/dist/src/wrappers/attention-fallbacks.js +0 -1487
  1026. package/dist/src/wrappers/attention-fallbacks.js.map +0 -1
  1027. package/dist/src/wrappers/embedding-service.d.ts +0 -117
  1028. package/dist/src/wrappers/embedding-service.d.ts.map +0 -1
  1029. package/dist/src/wrappers/embedding-service.js +0 -376
  1030. package/dist/src/wrappers/embedding-service.js.map +0 -1
  1031. package/dist/src/wrappers/gnn-wrapper.d.ts +0 -71
  1032. package/dist/src/wrappers/gnn-wrapper.d.ts.map +0 -1
  1033. package/dist/src/wrappers/gnn-wrapper.js +0 -240
  1034. package/dist/src/wrappers/gnn-wrapper.js.map +0 -1
  1035. package/dist/src/wrappers/index.d.ts +0 -48
  1036. package/dist/src/wrappers/index.d.ts.map +0 -1
  1037. package/dist/src/wrappers/index.js +0 -83
  1038. package/dist/src/wrappers/index.js.map +0 -1
@@ -0,0 +1,2712 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * AgentDB CLI - Command-line interface for frontier memory features
4
+ *
5
+ * Provides commands for:
6
+ * - Causal memory graph operations
7
+ * - Explainable recall with certificates
8
+ * - Nightly learner automation
9
+ * - Database management
10
+ */
11
+
12
+ import { createDatabase } from '../db-fallback.js';
13
+ import { CausalMemoryGraph } from '../controllers/CausalMemoryGraph.js';
14
+ import { CausalRecall } from '../controllers/CausalRecall.js';
15
+ import { ExplainableRecall } from '../controllers/ExplainableRecall.js';
16
+ import { NightlyLearner } from '../controllers/NightlyLearner.js';
17
+ import { ReflexionMemory, Episode, ReflexionQuery } from '../controllers/ReflexionMemory.js';
18
+ import { SkillLibrary, Skill, SkillQuery } from '../controllers/SkillLibrary.js';
19
+ import { EmbeddingService } from '../controllers/EmbeddingService.js';
20
+ import { MMRDiversityRanker } from '../controllers/MMRDiversityRanker.js';
21
+ import { ContextSynthesizer } from '../controllers/ContextSynthesizer.js';
22
+ import { MetadataFilter } from '../controllers/MetadataFilter.js';
23
+ import { initCommand } from './commands/init.js';
24
+ import { statusCommand } from './commands/status.js';
25
+ import { installEmbeddingsCommand } from './commands/install-embeddings.js';
26
+ import { migrateCommand } from './commands/migrate.js';
27
+ import { doctorCommand } from './commands/doctor.js';
28
+ import * as fs from 'fs';
29
+ import * as path from 'path';
30
+ import * as zlib from 'zlib';
31
+ import { fileURLToPath } from 'url';
32
+ import { dirname } from 'path';
33
+
34
+ const __filename = fileURLToPath(import.meta.url);
35
+ const __dirname = dirname(__filename);
36
+
37
+ // Color codes for terminal output
38
+ const colors = {
39
+ reset: '\x1b[0m',
40
+ bright: '\x1b[1m',
41
+ green: '\x1b[32m',
42
+ yellow: '\x1b[33m',
43
+ blue: '\x1b[34m',
44
+ red: '\x1b[31m',
45
+ cyan: '\x1b[36m'
46
+ };
47
+
48
+ const log = {
49
+ success: (msg: string) => console.log(`${colors.green}✅ ${msg}${colors.reset}`),
50
+ error: (msg: string) => console.error(`${colors.red}❌ ${msg}${colors.reset}`),
51
+ info: (msg: string) => console.log(`${colors.blue}ℹ ${msg}${colors.reset}`),
52
+ warning: (msg: string) => console.log(`${colors.yellow}⚠ ${msg}${colors.reset}`),
53
+ header: (msg: string) => console.log(`${colors.bright}${colors.cyan}${msg}${colors.reset}`)
54
+ };
55
+
56
+ class AgentDBCLI {
57
+ public db?: any; // Database instance from createDatabase (public for init command)
58
+ private causalGraph?: CausalMemoryGraph;
59
+ private causalRecall?: CausalRecall;
60
+ private explainableRecall?: ExplainableRecall;
61
+ private nightlyLearner?: NightlyLearner;
62
+ private reflexion?: ReflexionMemory;
63
+ private skills?: SkillLibrary;
64
+ private embedder?: EmbeddingService;
65
+
66
+ async initialize(dbPath: string = './agentdb.db'): Promise<void> {
67
+ // Initialize database
68
+ this.db = await createDatabase(dbPath);
69
+
70
+ // Configure for performance
71
+ this.db.pragma('journal_mode = WAL');
72
+ this.db.pragma('synchronous = NORMAL');
73
+ this.db.pragma('cache_size = -64000');
74
+
75
+ // Load both schemas: main schema (episodes, skills) + frontier schema (causal)
76
+ const schemaFiles = ['schema.sql', 'frontier-schema.sql'];
77
+ const basePaths = [
78
+ path.join(__dirname, '../schemas'), // dist/cli/../schemas (local dev)
79
+ path.join(__dirname, '../../schemas'), // dist/schemas (published package)
80
+ path.join(__dirname, '../../src/schemas'), // dist/cli/../../src/schemas
81
+ path.join(process.cwd(), 'dist/schemas'), // current/dist/schemas
82
+ path.join(process.cwd(), 'src/schemas'), // current/src/schemas
83
+ path.join(process.cwd(), 'node_modules/agentdb/dist/schemas') // installed package
84
+ ];
85
+
86
+ let schemasLoaded = 0;
87
+ for (const basePath of basePaths) {
88
+ if (fs.existsSync(basePath)) {
89
+ for (const schemaFile of schemaFiles) {
90
+ const schemaPath = path.join(basePath, schemaFile);
91
+ if (fs.existsSync(schemaPath)) {
92
+ try {
93
+ const schema = fs.readFileSync(schemaPath, 'utf-8');
94
+ this.db.exec(schema);
95
+ schemasLoaded++;
96
+ } catch (error) {
97
+ log.error(`Failed to load schema from ${schemaPath}: ${(error as Error).message}`);
98
+ }
99
+ }
100
+ }
101
+ // If we found at least one schema in this path, we're done
102
+ if (schemasLoaded > 0) break;
103
+ }
104
+ }
105
+
106
+ if (schemasLoaded === 0) {
107
+ log.warning('Schema files not found, database may not be initialized properly');
108
+ log.info('__dirname: ' + __dirname);
109
+ log.info('process.cwd(): ' + process.cwd());
110
+ log.info('Tried base paths:');
111
+ basePaths.forEach(p => {
112
+ log.info(` - ${p} (exists: ${fs.existsSync(p)})`);
113
+ });
114
+ }
115
+
116
+ // Initialize embedding service
117
+ this.embedder = new EmbeddingService({
118
+ model: 'Xenova/all-MiniLM-L6-v2',
119
+ dimension: 384,
120
+ provider: 'transformers'
121
+ });
122
+ await this.embedder.initialize();
123
+
124
+ // Initialize controllers
125
+ this.causalGraph = new CausalMemoryGraph(this.db);
126
+ this.explainableRecall = new ExplainableRecall(this.db);
127
+ this.causalRecall = new CausalRecall(this.db, this.embedder, undefined, {
128
+ alpha: 0.7,
129
+ beta: 0.2,
130
+ gamma: 0.1,
131
+ minConfidence: 0.6
132
+ });
133
+ this.nightlyLearner = new NightlyLearner(this.db, this.embedder);
134
+
135
+ // ReflexionMemory and SkillLibrary support optional GNN/Graph backends
136
+ // These will be undefined if @ruvector/gnn or @ruvector/graph-node are not installed
137
+ this.reflexion = new ReflexionMemory(
138
+ this.db,
139
+ this.embedder,
140
+ undefined, // vectorBackend - would be created with detectBackends()
141
+ undefined, // learningBackend - requires @ruvector/gnn
142
+ undefined // graphBackend - requires @ruvector/graph-node
143
+ );
144
+ this.skills = new SkillLibrary(this.db, this.embedder);
145
+ }
146
+
147
+ // ============================================================================
148
+ // Causal Commands
149
+ // ============================================================================
150
+
151
+ async causalAddEdge(params: {
152
+ cause: string;
153
+ effect: string;
154
+ uplift: number;
155
+ confidence?: number;
156
+ sampleSize?: number;
157
+ }): Promise<void> {
158
+ if (!this.causalGraph) throw new Error('Not initialized');
159
+
160
+ log.header('\n📊 Adding Causal Edge');
161
+ log.info(`Cause: ${params.cause}`);
162
+ log.info(`Effect: ${params.effect}`);
163
+ log.info(`Uplift: ${params.uplift}`);
164
+
165
+ const edgeId = this.causalGraph.addCausalEdge({
166
+ fromMemoryId: 1,
167
+ fromMemoryType: 'episode',
168
+ toMemoryId: 2,
169
+ toMemoryType: 'episode',
170
+ similarity: 0.9,
171
+ uplift: params.uplift,
172
+ confidence: params.confidence || 0.95,
173
+ sampleSize: params.sampleSize || 0,
174
+ mechanism: `${params.cause} → ${params.effect}`,
175
+ evidenceIds: []
176
+ });
177
+
178
+ log.success(`Added causal edge #${edgeId}`);
179
+ }
180
+
181
+ async causalExperimentCreate(params: {
182
+ name: string;
183
+ cause: string;
184
+ effect: string;
185
+ }): Promise<void> {
186
+ if (!this.causalGraph) throw new Error('Not initialized');
187
+
188
+ log.header('\n🧪 Creating A/B Experiment');
189
+ log.info(`Name: ${params.name}`);
190
+ log.info(`Cause: ${params.cause}`);
191
+ log.info(`Effect: ${params.effect}`);
192
+
193
+ // Create a dummy episode for treatment reference
194
+ const dummyEpisode = this.db!.prepare(
195
+ 'INSERT INTO episodes (session_id, task, reward, success, created_at) VALUES (?, ?, ?, ?, ?)'
196
+ ).run('experiment-placeholder', params.name, 0.0, 0, Math.floor(Date.now() / 1000));
197
+
198
+ const treatmentId = Number(dummyEpisode.lastInsertRowid);
199
+
200
+ const expId = this.causalGraph.createExperiment({
201
+ name: params.name,
202
+ hypothesis: `Does ${params.cause} causally affect ${params.effect}?`,
203
+ treatmentId: treatmentId,
204
+ treatmentType: params.cause,
205
+ controlId: undefined,
206
+ startTime: Math.floor(Date.now() / 1000),
207
+ sampleSize: 0,
208
+ status: 'running',
209
+ metadata: { effect: params.effect }
210
+ });
211
+
212
+ log.success(`Created experiment #${expId}`);
213
+ log.info('Use `agentdb causal experiment add-observation` to record data');
214
+
215
+ // Save database to persist experiment
216
+ this.db.save();
217
+ }
218
+
219
+ async causalExperimentAddObservation(params: {
220
+ experimentId: number;
221
+ isTreatment: boolean;
222
+ outcome: number;
223
+ context?: string;
224
+ }): Promise<void> {
225
+ if (!this.causalGraph) throw new Error('Not initialized');
226
+
227
+ // Create a dummy episode to get an episode ID
228
+ const insertResult = this.db!.prepare('INSERT INTO episodes (session_id, task, reward, success, created_at) VALUES (?, ?, ?, ?, ?)').run('cli-session', 'experiment', params.outcome, 1, Math.floor(Date.now() / 1000));
229
+ if (!insertResult || !insertResult.lastInsertRowid) {
230
+ throw new Error('Failed to create episode');
231
+ }
232
+ const episodeId = Number(insertResult.lastInsertRowid);
233
+
234
+ this.causalGraph.recordObservation({
235
+ experimentId: params.experimentId,
236
+ episodeId: episodeId,
237
+ isTreatment: params.isTreatment,
238
+ outcomeValue: params.outcome,
239
+ outcomeType: 'reward',
240
+ context: params.context && params.context.trim() ? JSON.parse(params.context) : undefined
241
+ });
242
+
243
+ // Save database to persist changes
244
+ this.db.save();
245
+
246
+ log.success(`Recorded ${params.isTreatment ? 'treatment' : 'control'} observation: ${params.outcome}`);
247
+ }
248
+
249
+ async causalExperimentCalculate(experimentId: number): Promise<void> {
250
+ if (!this.causalGraph) throw new Error('Not initialized');
251
+
252
+ log.header('\n📈 Calculating Uplift');
253
+
254
+ const result = this.causalGraph.calculateUplift(experimentId);
255
+
256
+ // Fetch experiment details (now includes calculated means)
257
+ const experiment = this.db!.prepare('SELECT * FROM causal_experiments WHERE id = ?').get(experimentId) as any;
258
+ if (!experiment) {
259
+ throw new Error(`Experiment ${experimentId} not found`);
260
+ }
261
+
262
+ log.info(`Experiment: ${experiment.hypothesis || 'Unknown'}`);
263
+ log.info(`Treatment Mean: ${experiment.treatment_mean?.toFixed(3) || 'N/A'}`);
264
+ log.info(`Control Mean: ${experiment.control_mean?.toFixed(3) || 'N/A'}`);
265
+ log.success(`Uplift: ${result?.uplift?.toFixed(3) || 'N/A'}`);
266
+ if (result?.confidenceInterval && result.confidenceInterval.length === 2) {
267
+ log.info(`95% CI: [${result.confidenceInterval[0]?.toFixed(3) || 'N/A'}, ${result.confidenceInterval[1]?.toFixed(3) || 'N/A'}]`);
268
+ }
269
+ if (result?.pValue !== undefined) {
270
+ log.info(`p-value: ${result.pValue.toFixed(4)}`);
271
+ }
272
+
273
+ // Get sample sizes from observations
274
+ const counts = this.db!.prepare('SELECT COUNT(*) as total, SUM(is_treatment) as treatment FROM causal_observations WHERE experiment_id = ?').get(experimentId) as any;
275
+ if (!counts) {
276
+ throw new Error(`Failed to get observation counts for experiment ${experimentId}`);
277
+ }
278
+ log.info(`Sample Sizes: ${counts.treatment || 0} treatment, ${(counts.total || 0) - (counts.treatment || 0)} control`);
279
+
280
+ if (result && result.pValue !== undefined && result.pValue < 0.05) {
281
+ log.success('Result is statistically significant (p < 0.05)');
282
+ } else {
283
+ log.warning('Result is not statistically significant');
284
+ }
285
+ }
286
+
287
+ async causalQuery(params: {
288
+ cause?: string;
289
+ effect?: string;
290
+ minConfidence?: number;
291
+ minUplift?: number;
292
+ limit?: number;
293
+ }): Promise<void> {
294
+ if (!this.causalGraph) throw new Error('Not initialized');
295
+
296
+ log.header('\n🔍 Querying Causal Edges');
297
+
298
+ const edges = this.causalGraph.queryCausalEffects({
299
+ interventionMemoryId: 0,
300
+ interventionMemoryType: params.cause || '',
301
+ outcomeMemoryId: params.effect ? 0 : undefined,
302
+ minConfidence: params.minConfidence || 0.7,
303
+ minUplift: params.minUplift || 0.1
304
+ });
305
+
306
+ if (edges.length === 0) {
307
+ log.warning('No causal edges found');
308
+ return;
309
+ }
310
+
311
+ console.log('\n' + '═'.repeat(80));
312
+ edges.slice(0, params.limit || 10).forEach((edge, i) => {
313
+ console.log(`${colors.bright}#${i + 1}: ${edge.fromMemoryType} → ${edge.toMemoryType}${colors.reset}`);
314
+ console.log(` Uplift: ${colors.green}${(edge.uplift || 0).toFixed(3)}${colors.reset}`);
315
+ console.log(` Confidence: ${edge.confidence.toFixed(2)} (n=${edge.sampleSize})`);
316
+ console.log('─'.repeat(80));
317
+ });
318
+
319
+ log.success(`Found ${edges.length} causal edges`);
320
+ }
321
+
322
+ // ============================================================================
323
+ // Recall Commands
324
+ // ============================================================================
325
+
326
+ async recallWithCertificate(params: {
327
+ query: string;
328
+ k?: number;
329
+ alpha?: number;
330
+ beta?: number;
331
+ gamma?: number;
332
+ }): Promise<void> {
333
+ if (!this.causalRecall) throw new Error('Not initialized');
334
+
335
+ log.header('\n🔍 Causal Recall with Certificate');
336
+ log.info(`Query: "${params.query}"`);
337
+ log.info(`k: ${params.k || 12}`);
338
+
339
+ const startTime = Date.now();
340
+
341
+ const result = await this.causalRecall.recall(
342
+ 'cli-' + Date.now(),
343
+ params.query,
344
+ params.k || 12,
345
+ undefined,
346
+ 'internal'
347
+ );
348
+
349
+ const duration = Date.now() - startTime;
350
+
351
+ console.log('\n' + '═'.repeat(80));
352
+ console.log(`${colors.bright}Results (${result.candidates.length})${colors.reset}`);
353
+ console.log('═'.repeat(80));
354
+
355
+ result.candidates.slice(0, 5).forEach((r, i) => {
356
+ console.log(`\n${colors.bright}#${i + 1}: ${r.type} ${r.id}${colors.reset}`);
357
+ console.log(` Content: ${r.content.substring(0, 50)}...`);
358
+ console.log(` Similarity: ${colors.cyan}${r.similarity.toFixed(3)}${colors.reset}`);
359
+ console.log(` Uplift: ${colors.green}${r.uplift?.toFixed(3) || 'N/A'}${colors.reset}`);
360
+ console.log(` Utility: ${colors.yellow}${r.utilityScore.toFixed(3)}${colors.reset}`);
361
+ });
362
+
363
+ console.log('\n' + '═'.repeat(80));
364
+ log.info(`Certificate ID: ${result.certificate.id}`);
365
+ log.info(`Query: ${result.certificate.queryText}`);
366
+ log.info(`Completeness: ${result.certificate.completenessScore.toFixed(2)}`);
367
+ log.success(`Completed in ${duration}ms`);
368
+ }
369
+
370
+ // ============================================================================
371
+ // Learner Commands
372
+ // ============================================================================
373
+
374
+ async learnerRun(params: {
375
+ minAttempts?: number;
376
+ minSuccessRate?: number;
377
+ minConfidence?: number;
378
+ dryRun?: boolean;
379
+ }): Promise<void> {
380
+ if (!this.nightlyLearner) throw new Error('Not initialized');
381
+
382
+ log.header('\n🌙 Running Nightly Learner');
383
+ log.info(`Min Attempts: ${params.minAttempts || 3}`);
384
+ log.info(`Min Success Rate: ${params.minSuccessRate || 0.6}`);
385
+ log.info(`Min Confidence: ${params.minConfidence || 0.7}`);
386
+
387
+ const startTime = Date.now();
388
+
389
+ const discovered = await this.nightlyLearner.discover({
390
+ minAttempts: params.minAttempts || 3,
391
+ minSuccessRate: params.minSuccessRate || 0.6,
392
+ minConfidence: params.minConfidence || 0.7,
393
+ dryRun: params.dryRun || false
394
+ });
395
+
396
+ const duration = Date.now() - startTime;
397
+
398
+ log.success(`Discovered ${discovered.length} causal edges in ${(duration / 1000).toFixed(1)}s`);
399
+
400
+ if (discovered.length > 0) {
401
+ console.log('\n' + '═'.repeat(80));
402
+ discovered.slice(0, 10).forEach((edge: any, i: number) => {
403
+ console.log(`${colors.bright}#${i + 1}: ${edge.cause} → ${edge.effect}${colors.reset}`);
404
+ console.log(` Uplift: ${colors.green}${edge.uplift.toFixed(3)}${colors.reset} (CI: ${edge.confidence.toFixed(2)})`);
405
+ console.log(` Sample size: ${edge.sampleSize}`);
406
+ console.log('─'.repeat(80));
407
+ });
408
+ }
409
+ }
410
+
411
+ async learnerPrune(params: {
412
+ minConfidence?: number;
413
+ minUplift?: number;
414
+ maxAgeDays?: number;
415
+ }): Promise<void> {
416
+ if (!this.nightlyLearner) throw new Error('Not initialized');
417
+
418
+ log.header('\n🧹 Pruning Low-Quality Edges');
419
+
420
+ // Update config and run pruning
421
+ this.nightlyLearner.updateConfig({
422
+ confidenceThreshold: params.minConfidence || 0.6,
423
+ upliftThreshold: params.minUplift || 0.05,
424
+ edgeMaxAgeDays: params.maxAgeDays || 90
425
+ });
426
+
427
+ const report = await this.nightlyLearner.run();
428
+
429
+ log.success(`Pruned ${report.edgesPruned} edges`);
430
+ }
431
+
432
+ // ============================================================================
433
+ // Reflexion Commands
434
+ // ============================================================================
435
+
436
+ async reflexionStoreEpisode(params: {
437
+ sessionId: string;
438
+ task: string;
439
+ input?: string;
440
+ output?: string;
441
+ critique?: string;
442
+ reward: number;
443
+ success: boolean;
444
+ latencyMs?: number;
445
+ tokensUsed?: number;
446
+ }): Promise<void> {
447
+ if (!this.reflexion) throw new Error('Not initialized');
448
+
449
+ log.header('\n💭 Storing Episode');
450
+ log.info(`Task: ${params.task}`);
451
+ log.info(`Success: ${params.success ? 'Yes' : 'No'}`);
452
+ log.info(`Reward: ${params.reward.toFixed(2)}`);
453
+
454
+ const episodeId = await this.reflexion.storeEpisode(params as Episode);
455
+
456
+ // Save database to persist changes
457
+ this.db.save();
458
+
459
+ log.success(`Stored episode #${episodeId}`);
460
+ if (params.critique) {
461
+ log.info(`Critique: "${params.critique}"`);
462
+ }
463
+ }
464
+
465
+ async reflexionRetrieve(params: {
466
+ task: string;
467
+ k?: number;
468
+ onlyFailures?: boolean;
469
+ onlySuccesses?: boolean;
470
+ minReward?: number;
471
+ synthesizeContext?: boolean;
472
+ filters?: any;
473
+ }): Promise<void> {
474
+ if (!this.reflexion) throw new Error('Not initialized');
475
+
476
+ log.header('\n🔍 Retrieving Past Episodes');
477
+ log.info(`Task: "${params.task}"`);
478
+ log.info(`k: ${params.k || 5}`);
479
+ if (params.onlyFailures) log.info('Filter: Failures only');
480
+ if (params.onlySuccesses) log.info('Filter: Successes only');
481
+ if (params.synthesizeContext) log.info('Context synthesis: enabled');
482
+
483
+ let episodes = await this.reflexion.retrieveRelevant({
484
+ task: params.task,
485
+ k: params.k || 5,
486
+ onlyFailures: params.onlyFailures,
487
+ onlySuccesses: params.onlySuccesses,
488
+ minReward: params.minReward
489
+ });
490
+
491
+ // Apply metadata filters if provided
492
+ if (params.filters && Object.keys(params.filters).length > 0) {
493
+ episodes = MetadataFilter.apply(episodes, params.filters);
494
+ log.info(`Filtered to ${episodes.length} results matching metadata criteria`);
495
+ }
496
+
497
+ if (episodes.length === 0) {
498
+ log.warning('No episodes found');
499
+ return;
500
+ }
501
+
502
+ console.log('\n' + '═'.repeat(80));
503
+ episodes.forEach((ep, i) => {
504
+ console.log(`${colors.bright}#${i + 1}: Episode ${ep.id}${colors.reset}`);
505
+ console.log(` Task: ${ep.task}`);
506
+ console.log(` Reward: ${colors.green}${ep.reward.toFixed(2)}${colors.reset}`);
507
+ console.log(` Success: ${ep.success ? colors.green + 'Yes' : colors.red + 'No'}${colors.reset}`);
508
+ console.log(` Similarity: ${colors.cyan}${ep.similarity?.toFixed(3) || 'N/A'}${colors.reset}`);
509
+ if (ep.critique) {
510
+ console.log(` Critique: "${ep.critique}"`);
511
+ }
512
+ console.log('─'.repeat(80));
513
+ });
514
+
515
+ log.success(`Retrieved ${episodes.length} relevant episodes`);
516
+
517
+ // Synthesize context if requested
518
+ if (params.synthesizeContext && episodes.length > 0) {
519
+ const context = ContextSynthesizer.synthesize(episodes.map(ep => ({
520
+ task: ep.task,
521
+ reward: ep.reward,
522
+ success: ep.success,
523
+ critique: ep.critique,
524
+ input: ep.input,
525
+ output: ep.output,
526
+ similarity: ep.similarity
527
+ })));
528
+
529
+ console.log('\n' + '═'.repeat(80));
530
+ console.log(`${colors.bright}${colors.cyan}SYNTHESIZED CONTEXT${colors.reset}`);
531
+ console.log('═'.repeat(80));
532
+ console.log(`\n${context.summary}\n`);
533
+
534
+ if (context.patterns.length > 0) {
535
+ console.log(`${colors.yellow}Common Patterns:${colors.reset}`);
536
+ context.patterns.forEach(p => console.log(` • ${p}`));
537
+ console.log('');
538
+ }
539
+
540
+ if (context.keyInsights.length > 0) {
541
+ console.log(`${colors.cyan}Key Insights:${colors.reset}`);
542
+ context.keyInsights.forEach(i => console.log(` • ${i}`));
543
+ console.log('');
544
+ }
545
+
546
+ if (context.recommendations.length > 0) {
547
+ console.log(`${colors.green}Recommendations:${colors.reset}`);
548
+ context.recommendations.forEach((r, i) => console.log(` ${i + 1}. ${r}`));
549
+ console.log('');
550
+ }
551
+
552
+ console.log('═'.repeat(80));
553
+ }
554
+ }
555
+
556
+ async reflexionRetrieveJson(params: {
557
+ task: string;
558
+ k?: number;
559
+ onlyFailures?: boolean;
560
+ onlySuccesses?: boolean;
561
+ minReward?: number;
562
+ }): Promise<any[]> {
563
+ if (!this.reflexion) throw new Error('Not initialized');
564
+
565
+ const episodes = await this.reflexion.retrieveRelevant({
566
+ task: params.task,
567
+ k: params.k || 5,
568
+ onlyFailures: params.onlyFailures,
569
+ onlySuccesses: params.onlySuccesses,
570
+ minReward: params.minReward
571
+ });
572
+
573
+ return episodes;
574
+ }
575
+
576
+ async reflexionGetCritiqueSummary(params: {
577
+ task: string;
578
+ k?: number;
579
+ }): Promise<void> {
580
+ if (!this.reflexion) throw new Error('Not initialized');
581
+
582
+ log.header('\n📋 Critique Summary');
583
+ log.info(`Task: "${params.task}"`);
584
+
585
+ const summary = await this.reflexion.getCritiqueSummary({
586
+ task: params.task,
587
+ k: params.k
588
+ });
589
+
590
+ console.log('\n' + '═'.repeat(80));
591
+ console.log(colors.bright + 'Past Lessons:' + colors.reset);
592
+ console.log(summary);
593
+ console.log('═'.repeat(80));
594
+ }
595
+
596
+ async reflexionPrune(params: {
597
+ minReward?: number;
598
+ maxAgeDays?: number;
599
+ keepMinPerTask?: number;
600
+ }): Promise<void> {
601
+ if (!this.reflexion) throw new Error('Not initialized');
602
+
603
+ log.header('\n🧹 Pruning Episodes');
604
+
605
+ const pruned = this.reflexion.pruneEpisodes({
606
+ minReward: params.minReward || 0.3,
607
+ maxAgeDays: params.maxAgeDays || 30,
608
+ keepMinPerTask: params.keepMinPerTask || 5
609
+ });
610
+
611
+ log.success(`Pruned ${pruned} low-quality episodes`);
612
+ }
613
+
614
+ // ============================================================================
615
+ // Skill Library Commands
616
+ // ============================================================================
617
+
618
+ async skillCreate(params: {
619
+ name: string;
620
+ description: string;
621
+ code?: string;
622
+ successRate?: number;
623
+ episodeId?: number;
624
+ }): Promise<void> {
625
+ if (!this.skills) throw new Error('Not initialized');
626
+
627
+ log.header('\n🎯 Creating Skill');
628
+ log.info(`Name: ${params.name}`);
629
+ log.info(`Description: ${params.description}`);
630
+
631
+ const skillId = await this.skills.createSkill({
632
+ name: params.name,
633
+ description: params.description,
634
+ signature: { inputs: {}, outputs: {} },
635
+ code: params.code,
636
+ successRate: params.successRate || 0.0,
637
+ uses: 0,
638
+ avgReward: 0.0,
639
+ avgLatencyMs: 0.0,
640
+ createdFromEpisode: params.episodeId
641
+ });
642
+
643
+ // Save database to persist changes
644
+ this.db.save();
645
+
646
+ log.success(`Created skill #${skillId}`);
647
+ }
648
+
649
+ async skillSearch(params: {
650
+ task: string;
651
+ k?: number;
652
+ minSuccessRate?: number;
653
+ }): Promise<void> {
654
+ if (!this.skills) throw new Error('Not initialized');
655
+
656
+ log.header('\n🔍 Searching Skills');
657
+ log.info(`Task: "${params.task}"`);
658
+ log.info(`Min Success Rate: ${params.minSuccessRate || 0.0}`);
659
+
660
+ const skills = await this.skills.searchSkills({
661
+ task: params.task,
662
+ k: params.k || 10,
663
+ minSuccessRate: params.minSuccessRate || 0.0
664
+ });
665
+
666
+ if (skills.length === 0) {
667
+ log.warning('No skills found');
668
+ return;
669
+ }
670
+
671
+ console.log('\n' + '═'.repeat(80));
672
+ skills.forEach((skill: any, i: number) => {
673
+ console.log(`${colors.bright}#${i + 1}: ${skill.name}${colors.reset}`);
674
+ console.log(` Description: ${skill.description}`);
675
+ console.log(` Success Rate: ${colors.green}${(skill.successRate * 100).toFixed(1)}%${colors.reset}`);
676
+ console.log(` Uses: ${skill.uses}`);
677
+ console.log(` Avg Reward: ${skill.avgReward.toFixed(2)}`);
678
+ console.log(` Avg Latency: ${skill.avgLatencyMs.toFixed(0)}ms`);
679
+ console.log('─'.repeat(80));
680
+ });
681
+
682
+ log.success(`Found ${skills.length} matching skills`);
683
+ }
684
+
685
+ async skillConsolidate(params: {
686
+ minAttempts?: number;
687
+ minReward?: number;
688
+ timeWindowDays?: number;
689
+ extractPatterns?: boolean;
690
+ }): Promise<void> {
691
+ if (!this.skills) throw new Error('Not initialized');
692
+
693
+ log.header('\n🔄 Consolidating Episodes into Skills with Pattern Extraction');
694
+ log.info(`Min Attempts: ${params.minAttempts || 3}`);
695
+ log.info(`Min Reward: ${params.minReward || 0.7}`);
696
+ log.info(`Time Window: ${params.timeWindowDays || 7} days`);
697
+ log.info(`Pattern Extraction: ${params.extractPatterns !== false ? 'Enabled' : 'Disabled'}`);
698
+
699
+ const startTime = Date.now();
700
+
701
+ const result = await this.skills.consolidateEpisodesIntoSkills({
702
+ minAttempts: params.minAttempts || 3,
703
+ minReward: params.minReward || 0.7,
704
+ timeWindowDays: params.timeWindowDays || 7,
705
+ extractPatterns: params.extractPatterns !== false
706
+ });
707
+
708
+ // Save database to persist changes
709
+ this.db.save();
710
+
711
+ const duration = Date.now() - startTime;
712
+
713
+ log.success(`Created ${result.created} new skills, updated ${result.updated} existing skills in ${duration}ms`);
714
+
715
+ // Display extracted patterns if available
716
+ if (result.patterns.length > 0) {
717
+ console.log('\n' + '═'.repeat(80));
718
+ console.log(`${colors.bright}${colors.cyan}Extracted Patterns:${colors.reset}`);
719
+ console.log('═'.repeat(80));
720
+
721
+ result.patterns.forEach((pattern, i) => {
722
+ console.log(`\n${colors.bright}#${i + 1}: ${pattern.task}${colors.reset}`);
723
+ console.log(` Avg Reward: ${colors.green}${pattern.avgReward.toFixed(2)}${colors.reset}`);
724
+
725
+ if (pattern.commonPatterns.length > 0) {
726
+ console.log(` ${colors.cyan}Common Patterns:${colors.reset}`);
727
+ pattern.commonPatterns.forEach(p => console.log(` • ${p}`));
728
+ }
729
+
730
+ if (pattern.successIndicators.length > 0) {
731
+ console.log(` ${colors.yellow}Success Indicators:${colors.reset}`);
732
+ pattern.successIndicators.forEach(s => console.log(` • ${s}`));
733
+ }
734
+
735
+ console.log('─'.repeat(80));
736
+ });
737
+ }
738
+
739
+ if (result.created === 0 && result.updated === 0) {
740
+ log.warning('No episodes met the criteria for skill consolidation');
741
+ log.info('Try lowering minReward or increasing timeWindowDays');
742
+ }
743
+ }
744
+
745
+ async skillPrune(params: {
746
+ minUses?: number;
747
+ minSuccessRate?: number;
748
+ maxAgeDays?: number;
749
+ }): Promise<void> {
750
+ if (!this.skills) throw new Error('Not initialized');
751
+
752
+ log.header('\n🧹 Pruning Skills');
753
+
754
+ const pruned = this.skills.pruneSkills({
755
+ minUses: params.minUses || 3,
756
+ minSuccessRate: params.minSuccessRate || 0.4,
757
+ maxAgeDays: params.maxAgeDays || 60
758
+ });
759
+
760
+ log.success(`Pruned ${pruned} underperforming skills`);
761
+ }
762
+
763
+ // ============================================================================
764
+ // QUIC Synchronization Commands
765
+ // ============================================================================
766
+
767
+ async quicStartServer(params: {
768
+ port?: number;
769
+ cert?: string;
770
+ key?: string;
771
+ authToken?: string;
772
+ }): Promise<void> {
773
+ log.header('\n🚀 Starting QUIC Sync Server');
774
+
775
+ const port = params.port || 4433;
776
+ const authToken = params.authToken || this.generateAuthToken();
777
+
778
+ log.info(`Port: ${port}`);
779
+ log.info(`Auth Token: ${authToken}`);
780
+
781
+ if (params.cert && params.key) {
782
+ log.info(`TLS Certificate: ${params.cert}`);
783
+ log.info(`TLS Key: ${params.key}`);
784
+ } else {
785
+ log.warning('No TLS certificate provided - using self-signed certificate');
786
+ }
787
+
788
+ // TODO: Implement QUIC server using existing QUICSync controller
789
+ log.info('\nServer started. Waiting for connections...');
790
+ log.info('Press Ctrl+C to stop');
791
+
792
+ // Keep process alive
793
+ await new Promise(() => {});
794
+ }
795
+
796
+ async quicConnect(params: {
797
+ host: string;
798
+ port: number;
799
+ authToken?: string;
800
+ cert?: string;
801
+ }): Promise<void> {
802
+ log.header('\n🔌 Connecting to QUIC Sync Server');
803
+
804
+ log.info(`Host: ${params.host}`);
805
+ log.info(`Port: ${params.port}`);
806
+
807
+ if (params.authToken) {
808
+ log.info('Authentication: Enabled');
809
+ }
810
+
811
+ if (params.cert) {
812
+ log.info(`TLS Certificate: ${params.cert}`);
813
+ } else {
814
+ log.warning('No TLS certificate provided - using insecure connection');
815
+ }
816
+
817
+ // TODO: Implement QUIC client connection
818
+ log.success('Connected to remote server');
819
+ log.info('Server info: AgentDB QUIC Sync v1.0');
820
+ }
821
+
822
+ async quicPush(params: {
823
+ server: string;
824
+ incremental?: boolean;
825
+ filter?: string;
826
+ }): Promise<void> {
827
+ if (!this.db) throw new Error('Not initialized');
828
+
829
+ log.header('\n⬆️ Pushing Changes to Remote');
830
+
831
+ log.info(`Server: ${params.server}`);
832
+ log.info(`Mode: ${params.incremental ? 'Incremental' : 'Full'}`);
833
+
834
+ if (params.filter) {
835
+ log.info(`Filter: ${params.filter}`);
836
+ }
837
+
838
+ // Get pending changes
839
+ const changes = this.getPendingChanges(params.incremental, params.filter);
840
+
841
+ console.log('\n' + '═'.repeat(80));
842
+ console.log(`${colors.bright}Pending Changes${colors.reset}`);
843
+ console.log('═'.repeat(80));
844
+ console.log(` Episodes: ${changes.episodes}`);
845
+ console.log(` Skills: ${changes.skills}`);
846
+ console.log(` Causal Edges: ${changes.causalEdges}`);
847
+ console.log(` Total Size: ${(changes.totalSize / 1024).toFixed(2)} KB`);
848
+ console.log('═'.repeat(80));
849
+
850
+ // TODO: Implement QUIC push
851
+ log.success('Changes pushed successfully');
852
+ log.info(`Transferred: ${(changes.totalSize / 1024).toFixed(2)} KB`);
853
+ }
854
+
855
+ async quicPull(params: {
856
+ server: string;
857
+ incremental?: boolean;
858
+ filter?: string;
859
+ }): Promise<void> {
860
+ if (!this.db) throw new Error('Not initialized');
861
+
862
+ log.header('\n⬇️ Pulling Changes from Remote');
863
+
864
+ log.info(`Server: ${params.server}`);
865
+ log.info(`Mode: ${params.incremental ? 'Incremental' : 'Full'}`);
866
+
867
+ if (params.filter) {
868
+ log.info(`Filter: ${params.filter}`);
869
+ }
870
+
871
+ // TODO: Implement QUIC pull
872
+ const changes = {
873
+ episodes: 5,
874
+ skills: 2,
875
+ causalEdges: 3,
876
+ totalSize: 12800
877
+ };
878
+
879
+ console.log('\n' + '═'.repeat(80));
880
+ console.log(`${colors.bright}Received Changes${colors.reset}`);
881
+ console.log('═'.repeat(80));
882
+ console.log(` Episodes: ${changes.episodes}`);
883
+ console.log(` Skills: ${changes.skills}`);
884
+ console.log(` Causal Edges: ${changes.causalEdges}`);
885
+ console.log(` Total Size: ${(changes.totalSize / 1024).toFixed(2)} KB`);
886
+ console.log('═'.repeat(80));
887
+
888
+ log.success('Changes pulled and merged successfully');
889
+ log.info(`Downloaded: ${(changes.totalSize / 1024).toFixed(2)} KB`);
890
+ }
891
+
892
+ async quicStatus(): Promise<void> {
893
+ if (!this.db) throw new Error('Not initialized');
894
+
895
+ log.header('\n📊 QUIC Sync Status');
896
+
897
+ // Get sync metadata
898
+ const syncMeta = this.getSyncMetadata();
899
+
900
+ console.log('\n' + '═'.repeat(80));
901
+ console.log(`${colors.bright}Sync Status${colors.reset}`);
902
+ console.log('═'.repeat(80));
903
+
904
+ if (syncMeta.lastSyncTime) {
905
+ const lastSync = new Date(syncMeta.lastSyncTime * 1000);
906
+ console.log(` Last Sync: ${colors.cyan}${lastSync.toLocaleString()}${colors.reset}`);
907
+ console.log(` Time Ago: ${this.timeAgo(syncMeta.lastSyncTime)}`);
908
+ } else {
909
+ console.log(` Last Sync: ${colors.yellow}Never${colors.reset}`);
910
+ }
911
+
912
+ console.log('\n' + '─'.repeat(80));
913
+ console.log(`${colors.bright}Pending Changes${colors.reset}`);
914
+ console.log('─'.repeat(80));
915
+ console.log(` Episodes: ${colors.green}${syncMeta.pendingEpisodes}${colors.reset}`);
916
+ console.log(` Skills: ${colors.green}${syncMeta.pendingSkills}${colors.reset}`);
917
+ console.log(` Causal Edges: ${colors.green}${syncMeta.pendingCausalEdges}${colors.reset}`);
918
+
919
+ console.log('\n' + '─'.repeat(80));
920
+ console.log(`${colors.bright}Connected Servers${colors.reset}`);
921
+ console.log('─'.repeat(80));
922
+
923
+ if (syncMeta.servers.length === 0) {
924
+ console.log(` ${colors.yellow}No servers connected${colors.reset}`);
925
+ } else {
926
+ syncMeta.servers.forEach((server: any) => {
927
+ console.log(` ${colors.cyan}${server.host}:${server.port}${colors.reset}`);
928
+ console.log(` Status: ${server.connected ? colors.green + 'Connected' : colors.red + 'Disconnected'}${colors.reset}`);
929
+ console.log(` Last Seen: ${new Date(server.lastSeen * 1000).toLocaleString()}`);
930
+ });
931
+ }
932
+
933
+ console.log('═'.repeat(80));
934
+ }
935
+
936
+ private generateAuthToken(): string {
937
+ // Generate a random 32-character token
938
+ return Array.from({ length: 32 }, () =>
939
+ Math.floor(Math.random() * 16).toString(16)
940
+ ).join('');
941
+ }
942
+
943
+ private getPendingChanges(incremental?: boolean, filter?: string): {
944
+ episodes: number;
945
+ skills: number;
946
+ causalEdges: number;
947
+ totalSize: number;
948
+ } {
949
+ // Mock implementation - would query sync metadata table
950
+ return {
951
+ episodes: 10,
952
+ skills: 3,
953
+ causalEdges: 5,
954
+ totalSize: 25600
955
+ };
956
+ }
957
+
958
+ private getSyncMetadata(): {
959
+ lastSyncTime: number | null;
960
+ pendingEpisodes: number;
961
+ pendingSkills: number;
962
+ pendingCausalEdges: number;
963
+ servers: Array<{
964
+ host: string;
965
+ port: number;
966
+ connected: boolean;
967
+ lastSeen: number;
968
+ }>;
969
+ } {
970
+ // Mock implementation - would query sync metadata table
971
+ return {
972
+ lastSyncTime: null,
973
+ pendingEpisodes: 10,
974
+ pendingSkills: 3,
975
+ pendingCausalEdges: 5,
976
+ servers: []
977
+ };
978
+ }
979
+
980
+ private timeAgo(timestamp: number): string {
981
+ const now = Math.floor(Date.now() / 1000);
982
+ const diff = now - timestamp;
983
+
984
+ if (diff < 60) return `${diff} seconds ago`;
985
+ if (diff < 3600) return `${Math.floor(diff / 60)} minutes ago`;
986
+ if (diff < 86400) return `${Math.floor(diff / 3600)} hours ago`;
987
+ return `${Math.floor(diff / 86400)} days ago`;
988
+ }
989
+
990
+ // ============================================================================
991
+ // Database Commands
992
+ // ============================================================================
993
+
994
+ async dbStats(): Promise<void> {
995
+ if (!this.db) throw new Error('Not initialized');
996
+
997
+ log.header('\n📊 Database Statistics');
998
+
999
+ const tables = ['causal_edges', 'causal_experiments', 'causal_observations',
1000
+ 'certificates', 'provenance_lineage', 'episodes'];
1001
+
1002
+ console.log('\n' + '═'.repeat(80));
1003
+ tables.forEach(table => {
1004
+ try {
1005
+ const count = this.db!.prepare(`SELECT COUNT(*) as count FROM ${table}`).get() as { count: number };
1006
+ console.log(`${colors.bright}${table}:${colors.reset} ${colors.cyan}${count.count}${colors.reset} records`);
1007
+ } catch (e) {
1008
+ console.log(`${colors.bright}${table}:${colors.reset} ${colors.yellow}N/A${colors.reset}`);
1009
+ }
1010
+ });
1011
+ console.log('═'.repeat(80));
1012
+ }
1013
+ }
1014
+
1015
+ // ============================================================================
1016
+ // CLI Entry Point
1017
+ // ============================================================================
1018
+
1019
+ async function main() {
1020
+ const args = process.argv.slice(2);
1021
+
1022
+ // Handle version flag
1023
+ if (args[0] === '--version' || args[0] === '-v' || args[0] === 'version') {
1024
+ // Try multiple paths to find package.json (handles different execution contexts)
1025
+ const possiblePaths = [
1026
+ path.join(__dirname, '../../package.json'), // dist/src/cli/../../package.json (local dev)
1027
+ path.join(__dirname, '../../../package.json'), // dist/package.json (published package)
1028
+ path.join(process.cwd(), 'package.json'),
1029
+ path.join(process.cwd(), 'node_modules/agentdb/package.json')
1030
+ ];
1031
+
1032
+ let version = '2.0.0-alpha.2.6'; // Fallback version
1033
+ for (const pkgPath of possiblePaths) {
1034
+ try {
1035
+ if (fs.existsSync(pkgPath)) {
1036
+ const packageJson = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
1037
+ if (packageJson.name === 'agentdb' && packageJson.version) {
1038
+ version = packageJson.version;
1039
+ break;
1040
+ }
1041
+ }
1042
+ } catch {
1043
+ continue;
1044
+ }
1045
+ }
1046
+ console.log(`agentdb v${version}`);
1047
+ process.exit(0);
1048
+ }
1049
+
1050
+ // Handle help - show help if no args or help flag
1051
+ if (args.length === 0 || args[0] === 'help' || args[0] === '--help' || args[0] === '-h') {
1052
+ printHelp();
1053
+ process.exit(0);
1054
+ }
1055
+
1056
+ const command = args[0];
1057
+
1058
+ // Handle MCP server command separately (doesn't need CLI initialization)
1059
+ if (command === 'mcp') {
1060
+ await handleMcpCommand(args.slice(1));
1061
+ return;
1062
+ }
1063
+
1064
+ // Handle init command with new v2 implementation
1065
+ if (command === 'init') {
1066
+ const options: any = { dbPath: './agentdb.db', dimension: 384 };
1067
+ for (let i = 1; i < args.length; i++) {
1068
+ const arg = args[i];
1069
+ if (arg === '--backend' && i + 1 < args.length) {
1070
+ options.backend = args[++i];
1071
+ } else if (arg === '--dimension' && i + 1 < args.length) {
1072
+ options.dimension = parseInt(args[++i]);
1073
+ } else if (arg === '--model' && i + 1 < args.length) {
1074
+ options.model = args[++i];
1075
+ } else if (arg === '--preset' && i + 1 < args.length) {
1076
+ options.preset = args[++i];
1077
+ } else if (arg === '--in-memory') {
1078
+ options.inMemory = true;
1079
+ } else if (arg === '--dry-run') {
1080
+ options.dryRun = true;
1081
+ } else if (arg === '--db' && i + 1 < args.length) {
1082
+ options.dbPath = args[++i];
1083
+ } else if (!arg.startsWith('--')) {
1084
+ options.dbPath = arg;
1085
+ }
1086
+ }
1087
+ await initCommand(options);
1088
+ return;
1089
+ }
1090
+
1091
+ // Handle status command
1092
+ if (command === 'status') {
1093
+ const options: any = { dbPath: './agentdb.db', verbose: false };
1094
+ for (let i = 1; i < args.length; i++) {
1095
+ const arg = args[i];
1096
+ if (arg === '--db' && i + 1 < args.length) {
1097
+ options.dbPath = args[++i];
1098
+ } else if (arg === '--verbose' || arg === '-v') {
1099
+ options.verbose = true;
1100
+ } else if (!arg.startsWith('--')) {
1101
+ options.dbPath = arg;
1102
+ }
1103
+ }
1104
+ await statusCommand(options);
1105
+ return;
1106
+ }
1107
+
1108
+ // Handle install-embeddings command
1109
+ if (command === 'install-embeddings') {
1110
+ const options: any = { global: false };
1111
+ for (let i = 1; i < args.length; i++) {
1112
+ const arg = args[i];
1113
+ if (arg === '--global' || arg === '-g') {
1114
+ options.global = true;
1115
+ }
1116
+ }
1117
+ await installEmbeddingsCommand(options);
1118
+ return;
1119
+ }
1120
+
1121
+ // Handle migrate command
1122
+ if (command === 'migrate') {
1123
+ const options: any = { optimize: true, dryRun: false, verbose: false };
1124
+ for (let i = 1; i < args.length; i++) {
1125
+ const arg = args[i];
1126
+ if (arg === '--source' && i + 1 < args.length) {
1127
+ options.sourceDb = args[++i];
1128
+ } else if (arg === '--target' && i + 1 < args.length) {
1129
+ options.targetDb = args[++i];
1130
+ } else if (arg === '--no-optimize') {
1131
+ options.optimize = false;
1132
+ } else if (arg === '--dry-run') {
1133
+ options.dryRun = true;
1134
+ } else if (arg === '--verbose' || arg === '-v') {
1135
+ options.verbose = true;
1136
+ } else if (!arg.startsWith('--') && !options.sourceDb) {
1137
+ options.sourceDb = arg;
1138
+ }
1139
+ }
1140
+ if (!options.sourceDb) {
1141
+ log.error('Source database path required');
1142
+ console.log('Usage: agentdb migrate <source-db> [--target <target-db>] [--no-optimize] [--dry-run] [--verbose]');
1143
+ process.exit(1);
1144
+ }
1145
+ await migrateCommand(options);
1146
+ return;
1147
+ }
1148
+
1149
+ // Handle doctor command
1150
+ if (command === 'doctor') {
1151
+ const options: any = { verbose: false };
1152
+ for (let i = 1; i < args.length; i++) {
1153
+ const arg = args[i];
1154
+ if (arg === '--db' && i + 1 < args.length) {
1155
+ options.dbPath = args[++i];
1156
+ } else if (arg === '--verbose' || arg === '-v') {
1157
+ options.verbose = true;
1158
+ } else if (!arg.startsWith('--')) {
1159
+ options.dbPath = arg;
1160
+ }
1161
+ }
1162
+ await doctorCommand(options);
1163
+ return;
1164
+ }
1165
+
1166
+ // Handle vector search commands (no CLI initialization needed)
1167
+ if (command === 'vector-search') {
1168
+ await handleVectorSearchCommand(args.slice(1));
1169
+ return;
1170
+ }
1171
+
1172
+ if (command === 'export') {
1173
+ await handleExportCommand(args.slice(1));
1174
+ return;
1175
+ }
1176
+
1177
+ if (command === 'import') {
1178
+ await handleImportCommand(args.slice(1));
1179
+ return;
1180
+ }
1181
+
1182
+ if (command === 'stats') {
1183
+ await handleStatsCommand(args.slice(1));
1184
+ return;
1185
+ }
1186
+
1187
+ // Handle simulate command - run simulation CLI
1188
+ if (command === 'simulate') {
1189
+ // Use pathToFileURL for proper ESM module resolution
1190
+ const { pathToFileURL } = await import('url');
1191
+
1192
+ // Get current directory using import.meta.url
1193
+ const currentUrl = import.meta.url;
1194
+ const currentPath = currentUrl.replace(/^file:\/\//, '');
1195
+ const __dirname = path.dirname(currentPath);
1196
+
1197
+ // Dynamic import with proper file URL for ESM compatibility
1198
+ // Note: simulation files are in dist/simulation, not dist/src/simulation
1199
+ const runnerPath = path.resolve(__dirname, '../../simulation/runner.js');
1200
+ const runnerUrl = pathToFileURL(runnerPath).href;
1201
+
1202
+ try {
1203
+ const { runSimulation, listScenarios, initScenario } = await import(runnerUrl);
1204
+ const subcommand = args[1];
1205
+
1206
+ if (!subcommand || subcommand === 'list') {
1207
+ await listScenarios();
1208
+ return;
1209
+ }
1210
+
1211
+ if (subcommand === 'init') {
1212
+ const scenario = args[2];
1213
+ const options: any = { template: 'basic' };
1214
+ for (let i = 3; i < args.length; i++) {
1215
+ if (args[i] === '-t' || args[i] === '--template') {
1216
+ options.template = args[++i];
1217
+ }
1218
+ }
1219
+ await initScenario(scenario, options);
1220
+ return;
1221
+ }
1222
+
1223
+ if (subcommand === 'run') {
1224
+ const scenario = args[2];
1225
+ const options: any = {
1226
+ config: 'simulation/configs/default.json',
1227
+ verbosity: '2',
1228
+ iterations: '10',
1229
+ swarmSize: '5',
1230
+ model: 'anthropic/claude-3.5-sonnet',
1231
+ parallel: false,
1232
+ output: 'simulation/reports',
1233
+ stream: false,
1234
+ optimize: false
1235
+ };
1236
+
1237
+ for (let i = 3; i < args.length; i++) {
1238
+ const arg = args[i];
1239
+ if (arg === '-c' || arg === '--config') options.config = args[++i];
1240
+ else if (arg === '-v' || arg === '--verbosity') options.verbosity = args[++i];
1241
+ else if (arg === '-i' || arg === '--iterations') options.iterations = args[++i];
1242
+ else if (arg === '-s' || arg === '--swarm-size') options.swarmSize = args[++i];
1243
+ else if (arg === '-m' || arg === '--model') options.model = args[++i];
1244
+ else if (arg === '-p' || arg === '--parallel') options.parallel = true;
1245
+ else if (arg === '-o' || arg === '--output') options.output = args[++i];
1246
+ else if (arg === '--stream') options.stream = true;
1247
+ else if (arg === '--optimize') options.optimize = true;
1248
+ }
1249
+
1250
+ await runSimulation(scenario, options);
1251
+ return;
1252
+ }
1253
+
1254
+ log.error(`Unknown simulate subcommand: ${subcommand}`);
1255
+ log.info('Available: simulate list, simulate run <scenario>, simulate init <scenario>');
1256
+ return;
1257
+ } catch (error) {
1258
+ log.error(`Failed to load simulation module: ${(error as Error).message}`);
1259
+ log.info('Falling back to agentdb-simulate binary...');
1260
+ log.info('Usage: npx agentdb-simulate <command>');
1261
+ return;
1262
+ }
1263
+ }
1264
+
1265
+ const cli = new AgentDBCLI();
1266
+ const dbPath = process.env.AGENTDB_PATH || './agentdb.db';
1267
+
1268
+ try {
1269
+ await cli.initialize(dbPath);
1270
+
1271
+ const subcommand = args[1];
1272
+
1273
+ if (command === 'causal') {
1274
+ await handleCausalCommands(cli, subcommand, args.slice(2));
1275
+ } else if (command === 'recall') {
1276
+ await handleRecallCommands(cli, subcommand, args.slice(2));
1277
+ } else if (command === 'learner') {
1278
+ await handleLearnerCommands(cli, subcommand, args.slice(2));
1279
+ } else if (command === 'reflexion') {
1280
+ await handleReflexionCommands(cli, subcommand, args.slice(2));
1281
+ } else if (command === 'skill') {
1282
+ await handleSkillCommands(cli, subcommand, args.slice(2));
1283
+ } else if (command === 'db') {
1284
+ await handleDbCommands(cli, subcommand, args.slice(2));
1285
+ } else if (command === 'sync') {
1286
+ await handleSyncCommands(cli, subcommand, args.slice(2));
1287
+ } else if (command === 'query') {
1288
+ await handleQueryCommand(cli, args.slice(1));
1289
+ } else if (command === 'store-pattern') {
1290
+ await handleStorePatternCommand(cli, args.slice(1));
1291
+ } else if (command === 'train') {
1292
+ await handleTrainCommand(cli, args.slice(1));
1293
+ } else if (command === 'optimize-memory') {
1294
+ await handleOptimizeMemoryCommand(cli, args.slice(1));
1295
+ } else {
1296
+ log.error(`Unknown command: ${command}`);
1297
+ printHelp();
1298
+ process.exit(1);
1299
+ }
1300
+ } catch (error) {
1301
+ log.error((error as Error).message);
1302
+ process.exit(1);
1303
+ }
1304
+ }
1305
+
1306
+ // Command handlers
1307
+
1308
+ // Init command handler
1309
+ async function handleInitCommand(args: string[]) {
1310
+ // Parse arguments
1311
+ let dbPath = './agentdb.db';
1312
+ let dimension = 1536; // Default OpenAI ada-002
1313
+ let preset: 'small' | 'medium' | 'large' | null = null;
1314
+ let inMemory = false;
1315
+
1316
+ for (let i = 0; i < args.length; i++) {
1317
+ const arg = args[i];
1318
+ if (arg === '--dimension' && i + 1 < args.length) {
1319
+ dimension = parseInt(args[++i]);
1320
+ } else if (arg === '--preset' && i + 1 < args.length) {
1321
+ preset = args[++i] as 'small' | 'medium' | 'large';
1322
+ } else if (arg === '--in-memory') {
1323
+ inMemory = true;
1324
+ dbPath = ':memory:';
1325
+ } else if (!arg.startsWith('--')) {
1326
+ dbPath = arg;
1327
+ }
1328
+ }
1329
+
1330
+ // Apply preset configurations
1331
+ if (preset) {
1332
+ if (preset === 'small') {
1333
+ log.info('Using SMALL preset (<10K vectors)');
1334
+ } else if (preset === 'medium') {
1335
+ log.info('Using MEDIUM preset (10K-100K vectors)');
1336
+ } else if (preset === 'large') {
1337
+ log.info('Using LARGE preset (>100K vectors)');
1338
+ }
1339
+ }
1340
+
1341
+ log.info(`Initializing AgentDB at: ${dbPath}`);
1342
+ log.info(`Embedding dimension: ${dimension}`);
1343
+ if (inMemory) {
1344
+ log.info('Using in-memory database (data will not persist)');
1345
+ }
1346
+
1347
+ // Check if database already exists
1348
+ if (!inMemory && fs.existsSync(dbPath)) {
1349
+ log.warning(`Database already exists at ${dbPath}`);
1350
+ log.info('Use a different path or remove the existing file to reinitialize');
1351
+ return;
1352
+ }
1353
+
1354
+ // Create parent directories if needed
1355
+ if (!inMemory) {
1356
+ const parentDir = path.dirname(dbPath);
1357
+ if (parentDir !== '.' && !fs.existsSync(parentDir)) {
1358
+ log.info(`Creating directory: ${parentDir}`);
1359
+ fs.mkdirSync(parentDir, { recursive: true });
1360
+ }
1361
+ }
1362
+
1363
+ // Create new database with schemas
1364
+ const cli = new AgentDBCLI();
1365
+ await cli.initialize(dbPath);
1366
+
1367
+ // CRITICAL: Save the database to disk (unless in-memory)
1368
+ // sql.js keeps everything in memory until explicitly saved
1369
+ if (!inMemory) {
1370
+ if (cli.db && typeof cli.db.save === 'function') {
1371
+ cli.db.save();
1372
+ } else if (cli.db && typeof cli.db.close === 'function') {
1373
+ // close() calls save() internally
1374
+ cli.db.close();
1375
+ }
1376
+
1377
+ // Verify database file was created
1378
+ if (!fs.existsSync(dbPath)) {
1379
+ log.error(`Failed to create database file at ${dbPath}`);
1380
+ log.error('The database may be in memory only');
1381
+ process.exit(1);
1382
+ }
1383
+ }
1384
+
1385
+ // Verify database has tables
1386
+ try {
1387
+ const db = await createDatabase(dbPath);
1388
+ const tables = db.prepare("SELECT name FROM sqlite_master WHERE type='table'").all();
1389
+ db.close();
1390
+
1391
+ if (tables.length === 0) {
1392
+ log.warning('Database file created but no tables found');
1393
+ log.warning('Schemas may not have been loaded correctly');
1394
+ } else {
1395
+ log.success(`Database created with ${tables.length} tables`);
1396
+ }
1397
+ } catch (error) {
1398
+ log.warning(`Could not verify database tables: ${(error as Error).message}`);
1399
+ }
1400
+
1401
+ log.success(`✅ AgentDB initialized successfully at ${dbPath}`);
1402
+ log.info('Database includes:');
1403
+ log.info(' - Core vector tables (episodes, embeddings)');
1404
+ log.info(' - Causal memory graph');
1405
+ log.info(' - Reflexion memory');
1406
+ log.info(' - Skill library');
1407
+ log.info(' - Learning system');
1408
+ log.info('');
1409
+ log.info('Next steps:');
1410
+ log.info(' - Use "agentdb mcp start" to start MCP server');
1411
+ log.info(' - Use "agentdb causal add" to add causal edges');
1412
+ log.info(' - Use "agentdb reflexion add" to store episodes');
1413
+ log.info(' - See "agentdb help" for all commands');
1414
+ }
1415
+
1416
+ async function handleMcpCommand(args: string[]) {
1417
+ const subcommand = args[0];
1418
+
1419
+ if (subcommand === 'start' || !subcommand) {
1420
+ log.info('Starting AgentDB MCP Server...');
1421
+
1422
+ // Spawn the MCP server as a child process (like agentic-flow does)
1423
+ // This ensures the server stays running with proper stdio inheritance
1424
+ const mcpServerPath = path.join(__dirname, '../mcp/agentdb-mcp-server.js');
1425
+
1426
+ if (!fs.existsSync(mcpServerPath)) {
1427
+ log.error('MCP server not found. Please rebuild the package: npm run build');
1428
+ process.exit(1);
1429
+ }
1430
+
1431
+ // Spawn server process with stdio inheritance
1432
+ const { spawn } = await import('child_process');
1433
+ const serverProcess = spawn('node', [mcpServerPath], {
1434
+ stdio: 'inherit',
1435
+ env: process.env
1436
+ });
1437
+
1438
+ // Handle server exit
1439
+ serverProcess.on('exit', (code) => {
1440
+ process.exit(code || 0);
1441
+ });
1442
+
1443
+ // Forward termination signals
1444
+ process.on('SIGINT', () => {
1445
+ serverProcess.kill('SIGINT');
1446
+ });
1447
+
1448
+ process.on('SIGTERM', () => {
1449
+ serverProcess.kill('SIGTERM');
1450
+ });
1451
+
1452
+ // Keep this process alive until server exits
1453
+ return new Promise(() => {
1454
+ // Never resolve - wait for server process
1455
+ });
1456
+ } else {
1457
+ log.error(`Unknown mcp subcommand: ${subcommand}`);
1458
+ log.info('Usage: agentdb mcp start');
1459
+ process.exit(1);
1460
+ }
1461
+ }
1462
+
1463
+ async function handleCausalCommands(cli: AgentDBCLI, subcommand: string, args: string[]) {
1464
+ if (subcommand === 'add-edge') {
1465
+ await cli.causalAddEdge({
1466
+ cause: args[0],
1467
+ effect: args[1],
1468
+ uplift: parseFloat(args[2]),
1469
+ confidence: args[3] ? parseFloat(args[3]) : undefined,
1470
+ sampleSize: args[4] ? parseInt(args[4]) : undefined
1471
+ });
1472
+ } else if (subcommand === 'experiment' && args[0] === 'create') {
1473
+ await cli.causalExperimentCreate({
1474
+ name: args[1],
1475
+ cause: args[2],
1476
+ effect: args[3]
1477
+ });
1478
+ } else if (subcommand === 'experiment' && args[0] === 'add-observation') {
1479
+ await cli.causalExperimentAddObservation({
1480
+ experimentId: parseInt(args[1]),
1481
+ isTreatment: args[2] === 'true',
1482
+ outcome: parseFloat(args[3]),
1483
+ context: args[4]
1484
+ });
1485
+ } else if (subcommand === 'experiment' && args[0] === 'calculate') {
1486
+ await cli.causalExperimentCalculate(parseInt(args[1]));
1487
+ } else if (subcommand === 'query') {
1488
+ await cli.causalQuery({
1489
+ cause: args[0],
1490
+ effect: args[1],
1491
+ minConfidence: args[2] ? parseFloat(args[2]) : undefined,
1492
+ minUplift: args[3] ? parseFloat(args[3]) : undefined,
1493
+ limit: args[4] ? parseInt(args[4]) : undefined
1494
+ });
1495
+ } else {
1496
+ log.error(`Unknown causal subcommand: ${subcommand}`);
1497
+ printHelp();
1498
+ }
1499
+ }
1500
+
1501
+ async function handleRecallCommands(cli: AgentDBCLI, subcommand: string, args: string[]) {
1502
+ if (subcommand === 'with-certificate') {
1503
+ await cli.recallWithCertificate({
1504
+ query: args[0],
1505
+ k: args[1] ? parseInt(args[1]) : undefined,
1506
+ alpha: args[2] ? parseFloat(args[2]) : undefined,
1507
+ beta: args[3] ? parseFloat(args[3]) : undefined,
1508
+ gamma: args[4] ? parseFloat(args[4]) : undefined
1509
+ });
1510
+ } else {
1511
+ log.error(`Unknown recall subcommand: ${subcommand}`);
1512
+ printHelp();
1513
+ }
1514
+ }
1515
+
1516
+ async function handleLearnerCommands(cli: AgentDBCLI, subcommand: string, args: string[]) {
1517
+ if (subcommand === 'run') {
1518
+ await cli.learnerRun({
1519
+ minAttempts: args[0] ? parseInt(args[0]) : undefined,
1520
+ minSuccessRate: args[1] ? parseFloat(args[1]) : undefined,
1521
+ minConfidence: args[2] ? parseFloat(args[2]) : undefined,
1522
+ dryRun: args[3] === 'true'
1523
+ });
1524
+ } else if (subcommand === 'prune') {
1525
+ await cli.learnerPrune({
1526
+ minConfidence: args[0] ? parseFloat(args[0]) : undefined,
1527
+ minUplift: args[1] ? parseFloat(args[1]) : undefined,
1528
+ maxAgeDays: args[2] ? parseInt(args[2]) : undefined
1529
+ });
1530
+ } else {
1531
+ log.error(`Unknown learner subcommand: ${subcommand}`);
1532
+ printHelp();
1533
+ }
1534
+ }
1535
+
1536
+ async function handleReflexionCommands(cli: AgentDBCLI, subcommand: string, args: string[]) {
1537
+ if (subcommand === 'store') {
1538
+ await cli.reflexionStoreEpisode({
1539
+ sessionId: args[0],
1540
+ task: args[1],
1541
+ reward: parseFloat(args[2]),
1542
+ success: args[3] === 'true',
1543
+ critique: args[4],
1544
+ input: args[5],
1545
+ output: args[6],
1546
+ latencyMs: args[7] ? parseInt(args[7]) : undefined,
1547
+ tokensUsed: args[8] ? parseInt(args[8]) : undefined
1548
+ });
1549
+ } else if (subcommand === 'retrieve') {
1550
+ // Parse retrieve command with new flags
1551
+ let task = args[0];
1552
+ let k: number | undefined = undefined;
1553
+ let minReward: number | undefined = undefined;
1554
+ let onlyFailures: boolean | undefined = undefined;
1555
+ let onlySuccesses: boolean | undefined = undefined;
1556
+ let synthesizeContext = false;
1557
+ let filters: any = {};
1558
+
1559
+ for (let i = 1; i < args.length; i++) {
1560
+ const arg = args[i];
1561
+ if (arg === '--k' && i + 1 < args.length) {
1562
+ k = parseInt(args[++i]);
1563
+ } else if (arg === '--min-reward' && i + 1 < args.length) {
1564
+ minReward = parseFloat(args[++i]);
1565
+ } else if (arg === '--only-failures') {
1566
+ onlyFailures = true;
1567
+ } else if (arg === '--only-successes') {
1568
+ onlySuccesses = true;
1569
+ } else if (arg === '--synthesize-context') {
1570
+ synthesizeContext = true;
1571
+ } else if (arg === '--filters' && i + 1 < args.length) {
1572
+ try {
1573
+ filters = JSON.parse(args[++i]);
1574
+ } catch (error) {
1575
+ log.error(`Invalid JSON in --filters parameter: ${(error as Error).message}`);
1576
+ process.exit(1);
1577
+ }
1578
+ } else if (!arg.startsWith('--') && k === undefined) {
1579
+ // Legacy positional argument parsing
1580
+ k = parseInt(arg);
1581
+ if (i + 1 < args.length && !args[i + 1].startsWith('--')) {
1582
+ minReward = parseFloat(args[++i]);
1583
+ }
1584
+ if (i + 1 < args.length && args[i + 1] === 'true') {
1585
+ onlyFailures = true;
1586
+ i++;
1587
+ }
1588
+ if (i + 1 < args.length && args[i + 1] === 'true') {
1589
+ onlySuccesses = true;
1590
+ i++;
1591
+ }
1592
+ }
1593
+ }
1594
+
1595
+ await cli.reflexionRetrieve({
1596
+ task,
1597
+ k,
1598
+ minReward,
1599
+ onlyFailures,
1600
+ onlySuccesses,
1601
+ synthesizeContext,
1602
+ filters: Object.keys(filters).length > 0 ? filters : undefined
1603
+ });
1604
+ } else if (subcommand === 'critique-summary') {
1605
+ await cli.reflexionGetCritiqueSummary({
1606
+ task: args[0],
1607
+ k: args[1] ? parseInt(args[1]) : undefined
1608
+ });
1609
+ } else if (subcommand === 'prune') {
1610
+ await cli.reflexionPrune({
1611
+ maxAgeDays: args[0] ? parseInt(args[0]) : undefined,
1612
+ minReward: args[1] ? parseFloat(args[1]) : undefined
1613
+ });
1614
+ } else {
1615
+ log.error(`Unknown reflexion subcommand: ${subcommand}`);
1616
+ printHelp();
1617
+ }
1618
+ }
1619
+
1620
+ async function handleSkillCommands(cli: AgentDBCLI, subcommand: string, args: string[]) {
1621
+ if (subcommand === 'create') {
1622
+ await cli.skillCreate({
1623
+ name: args[0],
1624
+ description: args[1],
1625
+ code: args[2]
1626
+ });
1627
+ } else if (subcommand === 'search') {
1628
+ await cli.skillSearch({
1629
+ task: args[0],
1630
+ k: args[1] ? parseInt(args[1]) : undefined
1631
+ });
1632
+ } else if (subcommand === 'consolidate') {
1633
+ await cli.skillConsolidate({
1634
+ minAttempts: args[0] ? parseInt(args[0]) : undefined,
1635
+ minReward: args[1] ? parseFloat(args[1]) : undefined,
1636
+ timeWindowDays: args[2] ? parseInt(args[2]) : undefined,
1637
+ extractPatterns: args[3] !== 'false' // Default true, set to false if explicitly passed
1638
+ });
1639
+ } else if (subcommand === 'prune') {
1640
+ await cli.skillPrune({
1641
+ minUses: args[0] ? parseInt(args[0]) : undefined,
1642
+ minSuccessRate: args[1] ? parseFloat(args[1]) : undefined,
1643
+ maxAgeDays: args[2] ? parseInt(args[2]) : undefined
1644
+ });
1645
+ } else {
1646
+ log.error(`Unknown skill subcommand: ${subcommand}`);
1647
+ printHelp();
1648
+ }
1649
+ }
1650
+
1651
+ async function handleDbCommands(cli: AgentDBCLI, subcommand: string, args: string[]) {
1652
+ if (subcommand === 'stats') {
1653
+ await cli.dbStats();
1654
+ } else {
1655
+ log.error(`Unknown db subcommand: ${subcommand}`);
1656
+ printHelp();
1657
+ }
1658
+ }
1659
+
1660
+ async function handleSyncCommands(cli: AgentDBCLI, subcommand: string, args: string[]) {
1661
+ if (subcommand === 'start-server') {
1662
+ // Parse options
1663
+ let port: number | undefined;
1664
+ let cert: string | undefined;
1665
+ let key: string | undefined;
1666
+ let authToken: string | undefined;
1667
+
1668
+ for (let i = 0; i < args.length; i++) {
1669
+ if (args[i] === '--port' && i + 1 < args.length) {
1670
+ port = parseInt(args[++i]);
1671
+ } else if (args[i] === '--cert' && i + 1 < args.length) {
1672
+ cert = args[++i];
1673
+ } else if (args[i] === '--key' && i + 1 < args.length) {
1674
+ key = args[++i];
1675
+ } else if (args[i] === '--auth-token' && i + 1 < args.length) {
1676
+ authToken = args[++i];
1677
+ }
1678
+ }
1679
+
1680
+ await cli.quicStartServer({ port, cert, key, authToken });
1681
+ } else if (subcommand === 'connect') {
1682
+ // Parse host and port
1683
+ const host = args[0];
1684
+ const port = parseInt(args[1]);
1685
+
1686
+ if (!host || !port) {
1687
+ log.error('Missing required arguments: host and port');
1688
+ log.info('Usage: agentdb sync connect <host> <port> [--auth-token <token>] [--cert <path>]');
1689
+ process.exit(1);
1690
+ }
1691
+
1692
+ let authToken: string | undefined;
1693
+ let cert: string | undefined;
1694
+
1695
+ for (let i = 2; i < args.length; i++) {
1696
+ if (args[i] === '--auth-token' && i + 1 < args.length) {
1697
+ authToken = args[++i];
1698
+ } else if (args[i] === '--cert' && i + 1 < args.length) {
1699
+ cert = args[++i];
1700
+ }
1701
+ }
1702
+
1703
+ await cli.quicConnect({ host, port, authToken, cert });
1704
+ } else if (subcommand === 'push') {
1705
+ // Parse options
1706
+ let server: string | undefined;
1707
+ let incremental = false;
1708
+ let filter: string | undefined;
1709
+
1710
+ for (let i = 0; i < args.length; i++) {
1711
+ if (args[i] === '--server' && i + 1 < args.length) {
1712
+ server = args[++i];
1713
+ } else if (args[i] === '--incremental') {
1714
+ incremental = true;
1715
+ } else if (args[i] === '--filter' && i + 1 < args.length) {
1716
+ filter = args[++i];
1717
+ } else if (!args[i].startsWith('--') && !server) {
1718
+ server = args[i];
1719
+ }
1720
+ }
1721
+
1722
+ if (!server) {
1723
+ log.error('Missing required --server parameter');
1724
+ log.info('Usage: agentdb sync push --server <host:port> [--incremental] [--filter <pattern>]');
1725
+ process.exit(1);
1726
+ }
1727
+
1728
+ await cli.quicPush({ server, incremental, filter });
1729
+ } else if (subcommand === 'pull') {
1730
+ // Parse options
1731
+ let server: string | undefined;
1732
+ let incremental = false;
1733
+ let filter: string | undefined;
1734
+
1735
+ for (let i = 0; i < args.length; i++) {
1736
+ if (args[i] === '--server' && i + 1 < args.length) {
1737
+ server = args[++i];
1738
+ } else if (args[i] === '--incremental') {
1739
+ incremental = true;
1740
+ } else if (args[i] === '--filter' && i + 1 < args.length) {
1741
+ filter = args[++i];
1742
+ } else if (!args[i].startsWith('--') && !server) {
1743
+ server = args[i];
1744
+ }
1745
+ }
1746
+
1747
+ if (!server) {
1748
+ log.error('Missing required --server parameter');
1749
+ log.info('Usage: agentdb sync pull --server <host:port> [--incremental] [--filter <pattern>]');
1750
+ process.exit(1);
1751
+ }
1752
+
1753
+ await cli.quicPull({ server, incremental, filter });
1754
+ } else if (subcommand === 'status') {
1755
+ await cli.quicStatus();
1756
+ } else {
1757
+ log.error(`Unknown sync subcommand: ${subcommand}`);
1758
+ log.info('Available subcommands: start-server, connect, push, pull, status');
1759
+ printHelp();
1760
+ }
1761
+ }
1762
+
1763
+ // Query command - semantic search across reflexion episodes with context synthesis
1764
+ async function handleQueryCommand(cli: AgentDBCLI, args: string[]) {
1765
+ // Parse command-line arguments
1766
+ let domain = '';
1767
+ let query = '';
1768
+ let k = 5;
1769
+ let minConfidence = 0.0;
1770
+ let format = 'json';
1771
+ let synthesizeContext = false;
1772
+ let filters: any = {};
1773
+
1774
+ for (let i = 0; i < args.length; i++) {
1775
+ if (args[i] === '--domain' && i + 1 < args.length) {
1776
+ domain = args[++i];
1777
+ } else if (args[i] === '--query' && i + 1 < args.length) {
1778
+ query = args[++i];
1779
+ } else if (args[i] === '--k' && i + 1 < args.length) {
1780
+ k = parseInt(args[++i]);
1781
+ } else if (args[i] === '--min-confidence' && i + 1 < args.length) {
1782
+ minConfidence = parseFloat(args[++i]);
1783
+ } else if (args[i] === '--format' && i + 1 < args.length) {
1784
+ format = args[++i];
1785
+ } else if (args[i] === '--synthesize-context') {
1786
+ synthesizeContext = true;
1787
+ } else if (args[i] === '--filters' && i + 1 < args.length) {
1788
+ try {
1789
+ filters = JSON.parse(args[++i]);
1790
+ } catch (error) {
1791
+ log.error(`Invalid JSON in --filters parameter: ${(error as Error).message}`);
1792
+ process.exit(1);
1793
+ }
1794
+ }
1795
+ }
1796
+
1797
+ if (!query) {
1798
+ log.error('Missing required --query parameter');
1799
+ process.exit(1);
1800
+ }
1801
+
1802
+ // Validate filters if provided
1803
+ if (Object.keys(filters).length > 0) {
1804
+ const validation = MetadataFilter.validate(filters);
1805
+ if (!validation.valid) {
1806
+ log.error('Invalid filters:');
1807
+ validation.errors.forEach(err => log.error(` - ${err}`));
1808
+ process.exit(1);
1809
+ }
1810
+ }
1811
+
1812
+ // Use reflexionRetrieveJson method for JSON output
1813
+ let results = await cli.reflexionRetrieveJson({
1814
+ task: query,
1815
+ k,
1816
+ minReward: minConfidence,
1817
+ onlySuccesses: domain === 'successful-edits'
1818
+ });
1819
+
1820
+ // Apply metadata filters if provided
1821
+ if (Object.keys(filters).length > 0) {
1822
+ results = MetadataFilter.apply(results, filters);
1823
+ log.info(`Filtered to ${results.length} results matching metadata criteria`);
1824
+ }
1825
+
1826
+ // Synthesize context if requested
1827
+ if (synthesizeContext && results.length > 0) {
1828
+ const context = ContextSynthesizer.synthesize(results.map((r: any) => ({
1829
+ task: r.task,
1830
+ reward: r.reward,
1831
+ success: r.success,
1832
+ critique: r.critique,
1833
+ input: r.input,
1834
+ output: r.output,
1835
+ similarity: r.similarity
1836
+ })));
1837
+
1838
+ if (format === 'json') {
1839
+ console.log(JSON.stringify({ results, synthesizedContext: context }, null, 2));
1840
+ } else {
1841
+ console.log('\n' + '═'.repeat(80));
1842
+ console.log('SYNTHESIZED CONTEXT');
1843
+ console.log('═'.repeat(80));
1844
+ console.log(`\n${context.summary}\n`);
1845
+
1846
+ if (context.patterns.length > 0) {
1847
+ console.log('Common Patterns:');
1848
+ context.patterns.forEach(p => console.log(` • ${p}`));
1849
+ console.log('');
1850
+ }
1851
+
1852
+ if (context.keyInsights.length > 0) {
1853
+ console.log('Key Insights:');
1854
+ context.keyInsights.forEach(i => console.log(` • ${i}`));
1855
+ console.log('');
1856
+ }
1857
+
1858
+ if (context.recommendations.length > 0) {
1859
+ console.log('Recommendations:');
1860
+ context.recommendations.forEach((r, i) => console.log(` ${i + 1}. ${r}`));
1861
+ console.log('');
1862
+ }
1863
+
1864
+ console.log('═'.repeat(80));
1865
+ console.log(`\nMatched ${results.length} memories\n`);
1866
+ }
1867
+ } else {
1868
+ if (format === 'json') {
1869
+ console.log(JSON.stringify(results, null, 2));
1870
+ } else {
1871
+ console.log(results);
1872
+ }
1873
+ }
1874
+ }
1875
+
1876
+ // Store-pattern command - store learned patterns
1877
+ async function handleStorePatternCommand(cli: AgentDBCLI, args: string[]) {
1878
+ let type = '';
1879
+ let domain = '';
1880
+ let pattern = '';
1881
+ let confidence = 0.5;
1882
+
1883
+ for (let i = 0; i < args.length; i++) {
1884
+ if (args[i] === '--type' && i + 1 < args.length) {
1885
+ type = args[++i];
1886
+ } else if (args[i] === '--domain' && i + 1 < args.length) {
1887
+ domain = args[++i];
1888
+ } else if (args[i] === '--pattern' && i + 1 < args.length) {
1889
+ pattern = args[++i];
1890
+ } else if (args[i] === '--confidence' && i + 1 < args.length) {
1891
+ confidence = parseFloat(args[++i]);
1892
+ }
1893
+ }
1894
+
1895
+ if (!pattern) {
1896
+ log.error('Missing required --pattern parameter');
1897
+ process.exit(1);
1898
+ }
1899
+
1900
+ // Parse pattern JSON
1901
+ let patternData;
1902
+ try {
1903
+ patternData = JSON.parse(pattern);
1904
+ } catch (error) {
1905
+ log.error('Invalid JSON in --pattern parameter');
1906
+ process.exit(1);
1907
+ }
1908
+
1909
+ // Store as reflexion episode with pattern metadata
1910
+ const sessionId = `pattern-${Date.now()}-${Math.random().toString(36).substring(7)}`;
1911
+ await cli.reflexionStoreEpisode({
1912
+ sessionId,
1913
+ task: `${type}:${domain}`,
1914
+ reward: confidence,
1915
+ success: true,
1916
+ critique: JSON.stringify({
1917
+ type,
1918
+ domain,
1919
+ pattern: patternData,
1920
+ storedAt: Date.now()
1921
+ })
1922
+ });
1923
+
1924
+ console.log(JSON.stringify({ success: true, sessionId }, null, 2));
1925
+ }
1926
+
1927
+ // Train command - trigger pattern learning
1928
+ async function handleTrainCommand(cli: AgentDBCLI, args: string[]) {
1929
+ let domain = '';
1930
+ let epochs = 10;
1931
+ let batchSize = 32;
1932
+
1933
+ for (let i = 0; i < args.length; i++) {
1934
+ if (args[i] === '--domain' && i + 1 < args.length) {
1935
+ domain = args[++i];
1936
+ } else if (args[i] === '--epochs' && i + 1 < args.length) {
1937
+ epochs = parseInt(args[++i]);
1938
+ } else if (args[i] === '--batch-size' && i + 1 < args.length) {
1939
+ batchSize = parseInt(args[++i]);
1940
+ }
1941
+ }
1942
+
1943
+ // Run learner to discover causal patterns
1944
+ log.info(`Training on domain: ${domain || 'all'} (${epochs} epochs, batch size: ${batchSize})`);
1945
+
1946
+ await cli.learnerRun({
1947
+ minAttempts: 3,
1948
+ minSuccessRate: 0.6,
1949
+ minConfidence: 0.7,
1950
+ dryRun: false
1951
+ });
1952
+
1953
+ // Also consolidate skills from successful episodes
1954
+ await cli.skillConsolidate({
1955
+ minAttempts: 3,
1956
+ minReward: 0.7,
1957
+ timeWindowDays: 7,
1958
+ extractPatterns: true
1959
+ });
1960
+
1961
+ console.log(JSON.stringify({ success: true, message: 'Training completed' }, null, 2));
1962
+ }
1963
+
1964
+ // Optimize-memory command - memory consolidation and compression
1965
+ async function handleOptimizeMemoryCommand(cli: AgentDBCLI, args: string[]) {
1966
+ let compress = true;
1967
+ let consolidatePatterns = true;
1968
+
1969
+ for (let i = 0; i < args.length; i++) {
1970
+ if (args[i] === '--compress' && i + 1 < args.length) {
1971
+ compress = args[++i] === 'true';
1972
+ } else if (args[i] === '--consolidate-patterns' && i + 1 < args.length) {
1973
+ consolidatePatterns = args[++i] === 'true';
1974
+ }
1975
+ }
1976
+
1977
+ log.info('Optimizing memory...');
1978
+
1979
+ // Prune old/low-quality episodes
1980
+ if (compress) {
1981
+ await cli.reflexionPrune({
1982
+ maxAgeDays: 90,
1983
+ minReward: 0.3
1984
+ });
1985
+ }
1986
+
1987
+ // Consolidate patterns into skills
1988
+ if (consolidatePatterns) {
1989
+ await cli.skillConsolidate({
1990
+ minAttempts: 3,
1991
+ minReward: 0.7,
1992
+ timeWindowDays: 7,
1993
+ extractPatterns: true
1994
+ });
1995
+ }
1996
+
1997
+ // Prune underperforming skills
1998
+ await cli.skillPrune({
1999
+ minUses: 3,
2000
+ minSuccessRate: 0.4,
2001
+ maxAgeDays: 60
2002
+ });
2003
+
2004
+ // Prune low-confidence causal edges
2005
+ await cli.learnerPrune({
2006
+ minConfidence: 0.5,
2007
+ minUplift: 0.05,
2008
+ maxAgeDays: 90
2009
+ });
2010
+
2011
+ console.log(JSON.stringify({ success: true, message: 'Memory optimization completed' }, null, 2));
2012
+ }
2013
+
2014
+ // Vector-search command - direct vector similarity search with MMR diversity ranking
2015
+ async function handleVectorSearchCommand(args: string[]) {
2016
+ // Parse arguments
2017
+ let dbPath = './agentdb.db';
2018
+ let vector: number[] = [];
2019
+ let k = 10;
2020
+ let threshold = 0.0;
2021
+ let metric = 'cosine';
2022
+ let format = 'json';
2023
+ let verbose = false;
2024
+ let useMmr = false;
2025
+ let mmrLambda = 0.5;
2026
+
2027
+ for (let i = 0; i < args.length; i++) {
2028
+ const arg = args[i];
2029
+ if (arg === '-k' && i + 1 < args.length) {
2030
+ k = parseInt(args[++i]);
2031
+ } else if (arg === '-t' && i + 1 < args.length) {
2032
+ threshold = parseFloat(args[++i]);
2033
+ } else if (arg === '-m' && i + 1 < args.length) {
2034
+ metric = args[++i];
2035
+ } else if (arg === '-f' && i + 1 < args.length) {
2036
+ format = args[++i];
2037
+ } else if (arg === '-v' || arg === '--verbose') {
2038
+ verbose = true;
2039
+ } else if (arg === '--mmr') {
2040
+ useMmr = true;
2041
+ if (i + 1 < args.length && !args[i + 1].startsWith('-')) {
2042
+ mmrLambda = parseFloat(args[++i]);
2043
+ }
2044
+ } else if (!dbPath.endsWith('.db') && !arg.startsWith('[')) {
2045
+ dbPath = arg;
2046
+ } else if (arg.startsWith('[') || (!isNaN(parseFloat(arg)))) {
2047
+ // Parse vector - either JSON array or space-separated numbers
2048
+ try {
2049
+ if (arg.startsWith('[')) {
2050
+ vector = JSON.parse(arg);
2051
+ } else {
2052
+ // Collect space-separated numbers
2053
+ while (i < args.length && !isNaN(parseFloat(args[i]))) {
2054
+ vector.push(parseFloat(args[i++]));
2055
+ }
2056
+ i--; // Back up one since loop will increment
2057
+ }
2058
+ } catch (e) {
2059
+ log.error('Invalid vector format. Use JSON array: "[0.1,0.2,0.3]" or space-separated: "0.1 0.2 0.3"');
2060
+ process.exit(1);
2061
+ }
2062
+ }
2063
+ }
2064
+
2065
+ if (vector.length === 0) {
2066
+ log.error('Missing required vector parameter');
2067
+ log.info('Usage: agentdb vector-search <db-path> <vector> [-k 10] [-t 0.75] [-m cosine] [-f json] [-v] [--mmr [lambda]]');
2068
+ process.exit(1);
2069
+ }
2070
+
2071
+ if (useMmr) {
2072
+ log.info(`Using MMR diversity ranking (λ=${mmrLambda})`);
2073
+ }
2074
+
2075
+ // Initialize database
2076
+ const cli = new AgentDBCLI();
2077
+ await cli.initialize(dbPath);
2078
+
2079
+ // Perform vector search using reflexion's retrieveRelevant (which uses embeddings)
2080
+ // We'll need to search episode_embeddings table directly
2081
+ const query = `
2082
+ SELECT
2083
+ e.id,
2084
+ e.session_id,
2085
+ e.task,
2086
+ e.reward,
2087
+ e.success,
2088
+ ee.embedding
2089
+ FROM episodes e
2090
+ JOIN episode_embeddings ee ON e.id = ee.episode_id
2091
+ LIMIT ?
2092
+ `;
2093
+
2094
+ const results = cli.db.prepare(query).all(k * 10); // Get more for filtering
2095
+
2096
+ // Calculate similarities
2097
+ let scored = results.map((row: any) => {
2098
+ const embedding = new Float32Array(row.embedding);
2099
+ const similarity = calculateSimilarity(vector, Array.from(embedding), metric);
2100
+ return {
2101
+ id: row.id,
2102
+ session_id: row.session_id,
2103
+ task: row.task,
2104
+ reward: row.reward,
2105
+ success: row.success,
2106
+ similarity,
2107
+ embedding: Array.from(embedding)
2108
+ };
2109
+ }).filter(r => r.similarity >= threshold)
2110
+ .sort((a, b) => b.similarity - a.similarity);
2111
+
2112
+ // Apply MMR diversity ranking if requested
2113
+ if (useMmr && scored.length > k) {
2114
+ scored = MMRDiversityRanker.selectDiverse(scored, vector, {
2115
+ lambda: mmrLambda,
2116
+ k,
2117
+ metric: metric as 'cosine' | 'euclidean' | 'dot'
2118
+ });
2119
+ } else {
2120
+ scored = scored.slice(0, k);
2121
+ }
2122
+
2123
+ // Remove embedding from output
2124
+ const output = scored.map(({ embedding, ...rest }) => rest);
2125
+
2126
+ if (format === 'json') {
2127
+ console.log(JSON.stringify(output, null, 2));
2128
+ } else {
2129
+ console.log(`Found ${output.length} results:`);
2130
+ output.forEach((r, i) => {
2131
+ console.log(`${i + 1}. [${r.id}] ${r.task} (similarity: ${r.similarity.toFixed(4)})`);
2132
+ if (verbose) {
2133
+ console.log(` Session: ${r.session_id}, Reward: ${r.reward}, Success: ${r.success}`);
2134
+ }
2135
+ });
2136
+ }
2137
+ }
2138
+
2139
+ // Helper function to calculate similarity
2140
+ function calculateSimilarity(v1: number[], v2: number[], metric: string): number {
2141
+ if (v1.length !== v2.length) {
2142
+ throw new Error(`Vector dimension mismatch: ${v1.length} vs ${v2.length}`);
2143
+ }
2144
+
2145
+ if (metric === 'cosine') {
2146
+ let dot = 0, mag1 = 0, mag2 = 0;
2147
+ for (let i = 0; i < v1.length; i++) {
2148
+ dot += v1[i] * v2[i];
2149
+ mag1 += v1[i] * v1[i];
2150
+ mag2 += v2[i] * v2[i];
2151
+ }
2152
+ return dot / (Math.sqrt(mag1) * Math.sqrt(mag2));
2153
+ } else if (metric === 'euclidean') {
2154
+ let sum = 0;
2155
+ for (let i = 0; i < v1.length; i++) {
2156
+ const diff = v1[i] - v2[i];
2157
+ sum += diff * diff;
2158
+ }
2159
+ return 1 / (1 + Math.sqrt(sum)); // Normalize to 0-1 range
2160
+ } else if (metric === 'dot') {
2161
+ let dot = 0;
2162
+ for (let i = 0; i < v1.length; i++) {
2163
+ dot += v1[i] * v2[i];
2164
+ }
2165
+ return dot;
2166
+ }
2167
+
2168
+ return 0;
2169
+ }
2170
+
2171
+ // Export command - export vectors to JSON with optional compression
2172
+ async function handleExportCommand(args: string[]) {
2173
+ let dbPath = './agentdb.db';
2174
+ let outputPath = './agentdb-export.json';
2175
+ let compress = false;
2176
+
2177
+ // Parse arguments
2178
+ for (let i = 0; i < args.length; i++) {
2179
+ const arg = args[i];
2180
+ if (arg === '--compress') {
2181
+ compress = true;
2182
+ } else if (arg === '--output' && i + 1 < args.length) {
2183
+ outputPath = args[++i];
2184
+ } else if (!arg.startsWith('--')) {
2185
+ if (dbPath === './agentdb.db') {
2186
+ dbPath = arg;
2187
+ } else if (outputPath === './agentdb-export.json') {
2188
+ outputPath = arg;
2189
+ }
2190
+ }
2191
+ }
2192
+
2193
+ // Add .gz extension if compressing and not already present
2194
+ if (compress && !outputPath.endsWith('.gz')) {
2195
+ outputPath += '.gz';
2196
+ }
2197
+
2198
+ log.info(`Exporting vectors from: ${dbPath}`);
2199
+ if (compress) {
2200
+ log.info('Compression: enabled');
2201
+ }
2202
+
2203
+ const cli = new AgentDBCLI();
2204
+ await cli.initialize(dbPath);
2205
+
2206
+ // Export all episodes with embeddings
2207
+ const query = `
2208
+ SELECT
2209
+ e.*,
2210
+ ee.embedding
2211
+ FROM episodes e
2212
+ LEFT JOIN episode_embeddings ee ON e.id = ee.episode_id
2213
+ `;
2214
+
2215
+ const results = cli.db.prepare(query).all();
2216
+
2217
+ const jsonData = JSON.stringify(results, null, 2);
2218
+
2219
+ try {
2220
+ if (compress) {
2221
+ // Compress with gzip
2222
+ const compressed = zlib.gzipSync(jsonData);
2223
+ fs.writeFileSync(outputPath, compressed);
2224
+ const originalSize = Buffer.byteLength(jsonData);
2225
+ const compressedSize = compressed.length;
2226
+ const ratio = ((1 - compressedSize / originalSize) * 100).toFixed(1);
2227
+ log.success(`Exported ${results.length} episodes to ${outputPath}`);
2228
+ log.info(`Original size: ${(originalSize / 1024).toFixed(2)} KB`);
2229
+ log.info(`Compressed size: ${(compressedSize / 1024).toFixed(2)} KB (${ratio}% reduction)`);
2230
+ } else {
2231
+ fs.writeFileSync(outputPath, jsonData);
2232
+ log.success(`Exported ${results.length} episodes to ${outputPath}`);
2233
+ }
2234
+ } catch (error) {
2235
+ log.error(`Failed to export: ${(error as Error).message}`);
2236
+ process.exit(1);
2237
+ }
2238
+ }
2239
+
2240
+ // Import command - import vectors from JSON with optional decompression
2241
+ async function handleImportCommand(args: string[]) {
2242
+ let inputPath = '';
2243
+ let dbPath = './agentdb.db';
2244
+ let decompress = false;
2245
+
2246
+ // Parse arguments
2247
+ for (let i = 0; i < args.length; i++) {
2248
+ const arg = args[i];
2249
+ if (arg === '--decompress') {
2250
+ decompress = true;
2251
+ } else if (arg === '--db' && i + 1 < args.length) {
2252
+ dbPath = args[++i];
2253
+ } else if (!arg.startsWith('--')) {
2254
+ if (!inputPath) {
2255
+ inputPath = arg;
2256
+ } else if (dbPath === './agentdb.db') {
2257
+ dbPath = arg;
2258
+ }
2259
+ }
2260
+ }
2261
+
2262
+ // Auto-detect compression from .gz extension
2263
+ if (inputPath.endsWith('.gz')) {
2264
+ decompress = true;
2265
+ }
2266
+
2267
+ if (!inputPath) {
2268
+ log.error('Missing required input file');
2269
+ log.info('Usage: agentdb import <input-file.json> [db-path] [--decompress]');
2270
+ process.exit(1);
2271
+ }
2272
+
2273
+ log.info(`Importing vectors from: ${inputPath}`);
2274
+ if (decompress) {
2275
+ log.info('Decompression: enabled');
2276
+ }
2277
+
2278
+ let data: any[];
2279
+
2280
+ try {
2281
+ if (decompress) {
2282
+ // Decompress with gunzip
2283
+ const compressed = fs.readFileSync(inputPath);
2284
+ const decompressed = zlib.gunzipSync(compressed);
2285
+ data = JSON.parse(decompressed.toString('utf-8'));
2286
+ log.info(`Decompressed ${(compressed.length / 1024).toFixed(2)} KB to ${(decompressed.length / 1024).toFixed(2)} KB`);
2287
+ } else {
2288
+ data = JSON.parse(fs.readFileSync(inputPath, 'utf-8'));
2289
+ }
2290
+ } catch (error) {
2291
+ log.error(`Failed to read/parse input file: ${(error as Error).message}`);
2292
+ process.exit(1);
2293
+ }
2294
+
2295
+ const cli = new AgentDBCLI();
2296
+ await cli.initialize(dbPath);
2297
+
2298
+ let imported = 0;
2299
+ for (const item of data) {
2300
+ try {
2301
+ // Import episode
2302
+ const episodeQuery = `
2303
+ INSERT INTO episodes (session_id, task, input, output, critique, reward, success, latency_ms, tokens_used, tags, metadata)
2304
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2305
+ `;
2306
+
2307
+ const result = cli.db.prepare(episodeQuery).run(
2308
+ item.session_id,
2309
+ item.task,
2310
+ item.input,
2311
+ item.output,
2312
+ item.critique,
2313
+ item.reward,
2314
+ item.success,
2315
+ item.latency_ms,
2316
+ item.tokens_used,
2317
+ item.tags,
2318
+ item.metadata
2319
+ );
2320
+
2321
+ // Import embedding if exists
2322
+ if (item.embedding) {
2323
+ const embeddingQuery = `INSERT INTO episode_embeddings (episode_id, embedding) VALUES (?, ?)`;
2324
+ cli.db.prepare(embeddingQuery).run(result.lastInsertRowid, item.embedding);
2325
+ }
2326
+
2327
+ imported++;
2328
+ } catch (error) {
2329
+ log.warning(`Failed to import item ${imported + 1}: ${(error as Error).message}`);
2330
+ }
2331
+ }
2332
+
2333
+ // Save database
2334
+ if (cli.db && typeof cli.db.save === 'function') {
2335
+ cli.db.save();
2336
+ }
2337
+
2338
+ log.success(`Imported ${imported} episodes`);
2339
+ }
2340
+
2341
+ // Stats command - show database statistics
2342
+ async function handleStatsCommand(args: string[]) {
2343
+ const dbPath = args[0] || './agentdb.db';
2344
+
2345
+ log.info(`Getting statistics for: ${dbPath}`);
2346
+
2347
+ const cli = new AgentDBCLI();
2348
+ await cli.initialize(dbPath);
2349
+
2350
+ // Get counts (with fallback for missing tables)
2351
+ const episodeCount = cli.db.prepare('SELECT COUNT(*) as count FROM episodes').get()?.count || 0;
2352
+ const embeddingCount = cli.db.prepare('SELECT COUNT(*) as count FROM episode_embeddings').get()?.count || 0;
2353
+
2354
+ let skillCount = 0;
2355
+ try {
2356
+ skillCount = cli.db.prepare('SELECT COUNT(*) as count FROM skill_library').get()?.count || 0;
2357
+ } catch (e) {
2358
+ // skill_library table may not exist in older databases
2359
+ }
2360
+
2361
+ let causalEdges = 0;
2362
+ try {
2363
+ causalEdges = cli.db.prepare('SELECT COUNT(*) as count FROM causal_edges').get()?.count || 0;
2364
+ } catch (e) {
2365
+ // causal_edges table may not exist in older databases
2366
+ }
2367
+
2368
+ // Get database file size
2369
+ let dbSize = 0;
2370
+ if (dbPath !== ':memory:' && fs.existsSync(dbPath)) {
2371
+ dbSize = fs.statSync(dbPath).size;
2372
+ }
2373
+
2374
+ // Get average confidence
2375
+ const avgConfidence = cli.db.prepare('SELECT AVG(reward) as avg FROM episodes').get().avg || 0;
2376
+
2377
+ // Get domains
2378
+ const domains = cli.db.prepare(`
2379
+ SELECT task, COUNT(*) as count
2380
+ FROM episodes
2381
+ GROUP BY task
2382
+ ORDER BY count DESC
2383
+ LIMIT 5
2384
+ `).all();
2385
+
2386
+ console.log(`
2387
+ 📊 AgentDB Statistics
2388
+
2389
+ Database: ${dbPath}
2390
+ Size: ${(dbSize / 1024).toFixed(2)} KB
2391
+
2392
+ 📈 Counts:
2393
+ Episodes: ${episodeCount}
2394
+ Embeddings: ${embeddingCount}
2395
+ Skills: ${skillCount}
2396
+ Causal Edges: ${causalEdges}
2397
+
2398
+ 📊 Metrics:
2399
+ Average Reward: ${avgConfidence.toFixed(3)}
2400
+ Embedding Coverage: ${episodeCount > 0 ? ((embeddingCount / episodeCount) * 100).toFixed(1) : 0}%
2401
+
2402
+ 🏷️ Top Domains:
2403
+ ${domains.map(d => ` • ${d.task}: ${d.count}`).join('\n')}
2404
+ `);
2405
+ }
2406
+
2407
+ function printHelp() {
2408
+ console.log(`
2409
+ ${colors.bright}${colors.cyan}█▀█ █▀▀ █▀▀ █▄░█ ▀█▀ █▀▄ █▄▄
2410
+ █▀█ █▄█ ██▄ █░▀█ ░█░ █▄▀ █▄█${colors.reset}
2411
+
2412
+ ${colors.bright}${colors.cyan}AgentDB v2 CLI - Vector Intelligence with Auto Backend Detection${colors.reset}
2413
+
2414
+ ${colors.bright}CORE COMMANDS:${colors.reset}
2415
+ ${colors.cyan}init${colors.reset} [options] Initialize database with backend detection
2416
+ --backend <type> Backend: auto (default), ruvector, hnswlib
2417
+ --dimension <n> Vector dimension (default: 384)
2418
+ --model <name> Embedding model (default: Xenova/all-MiniLM-L6-v2)
2419
+ Popular: Xenova/bge-base-en-v1.5 (768d production)
2420
+ Xenova/bge-small-en-v1.5 (384d best quality)
2421
+ --dry-run Show detection info without initializing
2422
+ --db <path> Database path (default: ./agentdb.db)
2423
+
2424
+ ${colors.cyan}status${colors.reset} [options] Show database and backend status
2425
+ --db <path> Database path (default: ./agentdb.db)
2426
+ --verbose, -v Show detailed statistics
2427
+
2428
+ ${colors.cyan}doctor${colors.reset} [options] System diagnostics and health check
2429
+ --db <path> Database path to check (optional)
2430
+ --verbose, -v Show detailed system information
2431
+
2432
+ ${colors.bright}USAGE:${colors.reset}
2433
+ agentdb <command> <subcommand> [options]
2434
+
2435
+ ${colors.bright}SETUP COMMANDS:${colors.reset}
2436
+ agentdb init [db-path] [--dimension 384] [--model <name>] [--preset small|medium|large] [--in-memory]
2437
+ Initialize a new AgentDB database (default: ./agentdb.db)
2438
+ Options:
2439
+ --dimension <n> Vector dimension (default: 384 for all-MiniLM, 768 for bge-base)
2440
+ --model <name> Embedding model (default: Xenova/all-MiniLM-L6-v2)
2441
+ Examples:
2442
+ Xenova/bge-small-en-v1.5 (384d) - Best quality at 384-dim
2443
+ Xenova/bge-base-en-v1.5 (768d) - Production quality
2444
+ Xenova/all-mpnet-base-v2 (768d) - All-around excellence
2445
+ See: docs/EMBEDDING-MODELS-GUIDE.md for full list
2446
+ --preset <size> small (<10K), medium (10K-100K), large (>100K vectors)
2447
+ --in-memory Use temporary in-memory database (:memory:)
2448
+
2449
+ agentdb install-embeddings [--global]
2450
+ Install optional embedding dependencies (@xenova/transformers)
2451
+ By default uses mock embeddings - run this for real ML-powered embeddings
2452
+ Options:
2453
+ --global, -g Install globally instead of locally
2454
+ Note: Requires build tools (python3, make, g++)
2455
+
2456
+ agentdb migrate <source-db> [--target <target-db>] [--no-optimize] [--dry-run] [-v]
2457
+ Migrate legacy AgentDB v1 or claude-flow memory databases to v2 format
2458
+ Automatically detects source type and optimizes for RuVector GNN
2459
+ Options:
2460
+ --target <path> Target database path (default: source-v2.db)
2461
+ --no-optimize Skip GNN optimization analysis
2462
+ --dry-run Analyze migration without making changes
2463
+ --verbose, -v Show detailed migration progress
2464
+
2465
+ ${colors.bright}VECTOR SEARCH COMMANDS:${colors.reset}
2466
+ agentdb vector-search <db-path> <vector> [-k 10] [-t 0.75] [-m cosine] [-f json] [-v] [--mmr [lambda]]
2467
+ Direct vector similarity search without text embeddings
2468
+ Arguments:
2469
+ <db-path> Database file path (or :memory:)
2470
+ <vector> Vector as JSON array [0.1,0.2,...] or space-separated numbers
2471
+ Options:
2472
+ -k <n> Number of results (default: 10)
2473
+ -t <threshold> Minimum similarity threshold (default: 0.0)
2474
+ -m <metric> Similarity metric: cosine|euclidean|dot (default: cosine)
2475
+ -f <format> Output format: json|table (default: json)
2476
+ -v Verbose mode with similarity scores
2477
+ --mmr [lambda] Enable MMR diversity ranking (lambda: 0-1, default: 0.5)
2478
+ 0 = max diversity, 1 = max relevance
2479
+ Example: agentdb vector-search ./vectors.db "[0.1,0.2,0.3]" -k 10 -m cosine
2480
+ Example: agentdb vector-search ./vectors.db "[0.1,0.2,0.3]" --mmr 0.7
2481
+
2482
+ agentdb export <db-path> [output-file] [--compress]
2483
+ Export all vectors and episodes to JSON file
2484
+ Options:
2485
+ --compress Compress output with gzip (adds .gz extension)
2486
+ --output <file> Output file path
2487
+ Example: agentdb export ./agentdb.db ./backup.json
2488
+ Example: agentdb export ./agentdb.db --compress --output backup.json.gz
2489
+
2490
+ agentdb import <input-file> [db-path] [--decompress]
2491
+ Import vectors and episodes from JSON file
2492
+ Options:
2493
+ --decompress Decompress gzip input (auto-detected for .gz files)
2494
+ --db <path> Database file path
2495
+ Example: agentdb import ./backup.json ./new-db.db
2496
+ Example: agentdb import ./backup.json.gz --decompress
2497
+
2498
+ agentdb stats [db-path]
2499
+ Show detailed database statistics and metrics
2500
+ Example: agentdb stats ./agentdb.db
2501
+
2502
+ ${colors.bright}MCP COMMANDS:${colors.reset}
2503
+ agentdb mcp start
2504
+ Start the MCP server for Claude Desktop integration
2505
+
2506
+ ${colors.bright}QUIC SYNC COMMANDS:${colors.reset}
2507
+ agentdb sync start-server [--port 4433] [--cert <path>] [--key <path>] [--auth-token <token>]
2508
+ Start a QUIC synchronization server for multi-agent coordination
2509
+ Options:
2510
+ --port <n> Server port (default: 4433)
2511
+ --cert <path> TLS certificate file path
2512
+ --key <path> TLS key file path
2513
+ --auth-token <token> Authentication token (auto-generated if not provided)
2514
+ Example: agentdb sync start-server --port 4433 --cert ./cert.pem --key ./key.pem
2515
+
2516
+ agentdb sync connect <host> <port> [--auth-token <token>] [--cert <path>]
2517
+ Connect to a remote QUIC sync server
2518
+ Arguments:
2519
+ <host> Remote server hostname or IP
2520
+ <port> Remote server port
2521
+ Options:
2522
+ --auth-token <token> Authentication token
2523
+ --cert <path> TLS certificate for verification
2524
+ Example: agentdb sync connect 192.168.1.100 4433 --auth-token abc123
2525
+
2526
+ agentdb sync push --server <host:port> [--incremental] [--filter <pattern>]
2527
+ Push local changes to remote server
2528
+ Options:
2529
+ --server <host:port> Remote server address (e.g., 192.168.1.100:4433)
2530
+ --incremental Only push changes since last sync
2531
+ --filter <pattern> Filter changes by pattern (e.g., "episodes", "skills")
2532
+ Example: agentdb sync push --server 192.168.1.100:4433 --incremental
2533
+ Example: agentdb sync push --server localhost:4433 --filter "episodes"
2534
+
2535
+ agentdb sync pull --server <host:port> [--incremental] [--filter <pattern>]
2536
+ Pull remote changes from server
2537
+ Options:
2538
+ --server <host:port> Remote server address (e.g., 192.168.1.100:4433)
2539
+ --incremental Only pull changes since last sync
2540
+ --filter <pattern> Filter changes by pattern (e.g., "skills", "causal_edges")
2541
+ Example: agentdb sync pull --server 192.168.1.100:4433 --incremental
2542
+ Example: agentdb sync pull --server localhost:4433 --filter "skills"
2543
+
2544
+ agentdb sync status
2545
+ Show synchronization status, pending changes, and connected servers
2546
+ Example: agentdb sync status
2547
+
2548
+ ${colors.bright}CAUSAL COMMANDS:${colors.reset}
2549
+ agentdb causal add-edge <cause> <effect> <uplift> [confidence] [sample-size]
2550
+ Add a causal edge manually
2551
+
2552
+ agentdb causal experiment create <name> <cause> <effect>
2553
+ Create a new A/B experiment
2554
+
2555
+ agentdb causal experiment add-observation <experiment-id> <is-treatment> <outcome> [context]
2556
+ Record an observation (is-treatment: true/false)
2557
+
2558
+ agentdb causal experiment calculate <experiment-id>
2559
+ Calculate uplift and statistical significance
2560
+
2561
+ agentdb causal query [cause] [effect] [min-confidence] [min-uplift] [limit]
2562
+ Query causal edges with filters
2563
+
2564
+ ${colors.bright}RECALL COMMANDS:${colors.reset}
2565
+ agentdb recall with-certificate <query> [k] [alpha] [beta] [gamma]
2566
+ Retrieve episodes with causal utility and provenance certificate
2567
+ Defaults: k=12, alpha=0.7, beta=0.2, gamma=0.1
2568
+
2569
+ ${colors.bright}LEARNER COMMANDS:${colors.reset}
2570
+ agentdb learner run [min-attempts] [min-success-rate] [min-confidence] [dry-run]
2571
+ Discover causal edges from episode patterns
2572
+ Defaults: min-attempts=3, min-success-rate=0.6, min-confidence=0.7
2573
+
2574
+ agentdb learner prune [min-confidence] [min-uplift] [max-age-days]
2575
+ Remove low-quality or old causal edges
2576
+ Defaults: min-confidence=0.5, min-uplift=0.05, max-age-days=90
2577
+
2578
+ ${colors.bright}REFLEXION COMMANDS:${colors.reset}
2579
+ agentdb reflexion store <session-id> <task> <reward> <success> [critique] [input] [output] [latency-ms] [tokens]
2580
+ Store episode with self-critique
2581
+
2582
+ agentdb reflexion retrieve <task> [--k <n>] [--min-reward <r>] [--only-failures] [--only-successes] [--synthesize-context] [--filters <json>]
2583
+ Retrieve relevant past episodes
2584
+ Options:
2585
+ --k <n> Number of results (default: 5)
2586
+ --min-reward <r> Minimum reward threshold
2587
+ --only-failures Return only failed episodes
2588
+ --only-successes Return only successful episodes
2589
+ --synthesize-context Generate coherent summary with patterns and insights
2590
+ --filters <json> MongoDB-style metadata filters (e.g., '{"metadata.year":{"$gte":2024}}')
2591
+ Example: agentdb reflexion retrieve "authentication" --k 10 --synthesize-context
2592
+ Example: agentdb reflexion retrieve "bug-fix" --filters '{"success":true,"reward":{"$gte":0.8}}'
2593
+
2594
+ agentdb reflexion critique-summary <task> [only-failures]
2595
+ Get aggregated critique lessons
2596
+
2597
+ agentdb reflexion prune [max-age-days] [max-reward]
2598
+ Clean up old or low-value episodes
2599
+
2600
+ ${colors.bright}SKILL COMMANDS:${colors.reset}
2601
+ agentdb skill create <name> <description> [code]
2602
+ Create a reusable skill
2603
+
2604
+ agentdb skill search <query> [k]
2605
+ Find applicable skills by similarity
2606
+
2607
+ agentdb skill consolidate [min-attempts] [min-reward] [time-window-days] [extract-patterns]
2608
+ Auto-create skills from successful episodes with ML pattern extraction
2609
+ Defaults: min-attempts=3, min-reward=0.7, time-window-days=7, extract-patterns=true
2610
+ Analyzes: keyword frequency, critique patterns, reward distribution, metadata, learning curves
2611
+
2612
+ agentdb skill prune [min-uses] [min-success-rate] [max-age-days]
2613
+ Remove underperforming skills (defaults: 3, 0.4, 60)
2614
+
2615
+ ${colors.bright}DATABASE COMMANDS:${colors.reset}
2616
+ agentdb db stats
2617
+ Show database statistics
2618
+
2619
+ ${colors.bright}HOOKS INTEGRATION COMMANDS:${colors.reset}
2620
+ agentdb query --query <query> [--domain <domain>] [--k <k>] [--min-confidence <conf>] [--format json] [--synthesize-context] [--filters <json>]
2621
+ Semantic search across stored episodes and patterns
2622
+ Options:
2623
+ --query <q> Query string (required)
2624
+ --domain <d> Domain filter (e.g., "successful-edits")
2625
+ --k <n> Number of results (default: 5)
2626
+ --min-confidence <c> Minimum confidence threshold (default: 0.0)
2627
+ --format <f> Output format: json|text (default: json)
2628
+ --synthesize-context Generate coherent summary with patterns and insights
2629
+ --filters <json> MongoDB-style metadata filters
2630
+ Example: agentdb query --query "authentication" --k 5 --min-confidence 0.8 --synthesize-context
2631
+ Example: agentdb query --query "bug-fix" --filters '{"metadata.priority":"high"}' --synthesize-context
2632
+
2633
+ agentdb store-pattern --type <type> --domain <domain> --pattern <json> --confidence <conf>
2634
+ Store a learned pattern for future retrieval
2635
+ Example: agentdb store-pattern --type "experience" --domain "code-edits" --pattern '{"success":true}' --confidence 0.9
2636
+
2637
+ agentdb train --domain <domain> --epochs <n> --batch-size <n>
2638
+ Trigger pattern learning and skill consolidation
2639
+ Example: agentdb train --domain "code-edits" --epochs 10 --batch-size 32
2640
+
2641
+ agentdb optimize-memory --compress <bool> --consolidate-patterns <bool>
2642
+ Memory consolidation, compression, and cleanup
2643
+ Example: agentdb optimize-memory --compress true --consolidate-patterns true
2644
+
2645
+ ${colors.bright}ENVIRONMENT:${colors.reset}
2646
+ AGENTDB_PATH Database file path (default: ./agentdb.db)
2647
+
2648
+ ${colors.bright}EXAMPLES:${colors.reset}
2649
+ # QUIC Sync: Multi-agent coordination
2650
+ # On server machine:
2651
+ agentdb sync start-server --port 4433 --auth-token secret123
2652
+
2653
+ # On client machines:
2654
+ agentdb sync connect 192.168.1.100 4433 --auth-token secret123
2655
+ agentdb sync push --server 192.168.1.100:4433 --incremental
2656
+ agentdb sync pull --server 192.168.1.100:4433 --incremental
2657
+ agentdb sync status
2658
+
2659
+ # Vector Search: Direct similarity queries
2660
+ agentdb init ./vectors.db --dimension 768 --preset medium
2661
+ agentdb vector-search ./vectors.db "[0.1,0.2,0.3]" -k 10 -m cosine -f json
2662
+ agentdb export ./vectors.db ./backup.json
2663
+ agentdb import ./backup.json ./new-vectors.db
2664
+ agentdb stats ./vectors.db
2665
+
2666
+ # Reflexion: Store and retrieve episodes
2667
+ agentdb reflexion store "session-1" "implement_auth" 0.95 true "Used OAuth2"
2668
+ agentdb reflexion retrieve "authentication" 10 0.8
2669
+ agentdb reflexion critique-summary "bug_fix" true
2670
+
2671
+ # Skills: Create and search
2672
+ agentdb skill create "jwt_auth" "Generate JWT tokens" "code here..."
2673
+ agentdb skill search "authentication" 5
2674
+ agentdb skill consolidate 3 0.7 7 true # With pattern extraction
2675
+ agentdb skill consolidate 5 0.8 14 # Higher thresholds, longer window
2676
+
2677
+ # Causal: Add edges and run experiments
2678
+ agentdb causal add-edge "add_tests" "code_quality" 0.25 0.95 100
2679
+ agentdb causal experiment create "test-coverage-quality" "test_coverage" "bug_rate"
2680
+ agentdb causal experiment add-observation 1 true 0.15
2681
+ agentdb causal experiment calculate 1
2682
+
2683
+ # Retrieve with causal utility
2684
+ agentdb recall with-certificate "implement authentication" 10
2685
+
2686
+ # Discover patterns automatically
2687
+ agentdb learner run 3 0.6 0.7
2688
+
2689
+ # Get database stats
2690
+ agentdb db stats
2691
+ `);
2692
+ }
2693
+
2694
+ // ESM entry point check - run if this is the main module
2695
+ // Handle both direct execution and npx/symlink scenarios
2696
+ const isMainModule = import.meta.url === `file://${process.argv[1]}` ||
2697
+ import.meta.url.endsWith('/agentdb-cli.js');
2698
+
2699
+ // Run main() when executed as main module (removed argv length check to allow no-args help)
2700
+ if (isMainModule) {
2701
+ main()
2702
+ .then(() => {
2703
+ // Force immediate exit to avoid onnxruntime cleanup crash
2704
+ process.exit(0);
2705
+ })
2706
+ .catch((error) => {
2707
+ console.error('AgentDB CLI Error:', error);
2708
+ process.exit(1);
2709
+ });
2710
+ }
2711
+
2712
+ export { AgentDBCLI };