agentdb 1.6.1 → 2.0.0-alpha.2

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