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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (1038) hide show
  1. package/README.md +978 -2342
  2. package/dist/agentdb.browser.js +1492 -0
  3. package/dist/agentdb.browser.js.map +7 -0
  4. package/dist/agentdb.browser.min.js +3 -0
  5. package/dist/agentdb.browser.min.js.map +7 -0
  6. package/dist/agentdb.wasm-loader.js +207 -0
  7. package/dist/schemas/frontier-schema.sql +0 -7
  8. package/dist/schemas/schema.sql +0 -7
  9. package/dist/simulation/cli.d.ts +9 -0
  10. package/dist/simulation/cli.d.ts.map +1 -0
  11. package/dist/simulation/cli.js +68 -0
  12. package/dist/simulation/cli.js.map +1 -0
  13. package/dist/simulation/runner.d.ts +21 -0
  14. package/dist/simulation/runner.d.ts.map +1 -0
  15. package/dist/simulation/runner.js +241 -0
  16. package/dist/simulation/runner.js.map +1 -0
  17. package/dist/simulation/scenarios/aidefence-integration.d.ts +24 -0
  18. package/dist/simulation/scenarios/aidefence-integration.d.ts.map +1 -0
  19. package/dist/simulation/scenarios/aidefence-integration.js +124 -0
  20. package/dist/simulation/scenarios/aidefence-integration.js.map +1 -0
  21. package/dist/simulation/scenarios/bmssp-integration.d.ts +23 -0
  22. package/dist/simulation/scenarios/bmssp-integration.d.ts.map +1 -0
  23. package/dist/simulation/scenarios/bmssp-integration.js +104 -0
  24. package/dist/simulation/scenarios/bmssp-integration.js.map +1 -0
  25. package/dist/simulation/scenarios/causal-reasoning.d.ts +16 -0
  26. package/dist/simulation/scenarios/causal-reasoning.d.ts.map +1 -0
  27. package/dist/simulation/scenarios/causal-reasoning.js +108 -0
  28. package/dist/simulation/scenarios/causal-reasoning.js.map +1 -0
  29. package/dist/simulation/scenarios/consciousness-explorer.d.ts +25 -0
  30. package/dist/simulation/scenarios/consciousness-explorer.d.ts.map +1 -0
  31. package/dist/simulation/scenarios/consciousness-explorer.js +108 -0
  32. package/dist/simulation/scenarios/consciousness-explorer.js.map +1 -0
  33. package/dist/simulation/scenarios/domain-examples/e-commerce-recommendations.d.ts +135 -0
  34. package/dist/simulation/scenarios/domain-examples/e-commerce-recommendations.d.ts.map +1 -0
  35. package/dist/simulation/scenarios/domain-examples/e-commerce-recommendations.js +158 -0
  36. package/dist/simulation/scenarios/domain-examples/e-commerce-recommendations.js.map +1 -0
  37. package/dist/simulation/scenarios/domain-examples/index.d.ts +14 -0
  38. package/dist/simulation/scenarios/domain-examples/index.d.ts.map +1 -0
  39. package/dist/simulation/scenarios/domain-examples/index.js +14 -0
  40. package/dist/simulation/scenarios/domain-examples/index.js.map +1 -0
  41. package/dist/simulation/scenarios/domain-examples/iot-sensor-networks.d.ts +178 -0
  42. package/dist/simulation/scenarios/domain-examples/iot-sensor-networks.d.ts.map +1 -0
  43. package/dist/simulation/scenarios/domain-examples/iot-sensor-networks.js +218 -0
  44. package/dist/simulation/scenarios/domain-examples/iot-sensor-networks.js.map +1 -0
  45. package/dist/simulation/scenarios/domain-examples/medical-imaging.d.ts +122 -0
  46. package/dist/simulation/scenarios/domain-examples/medical-imaging.d.ts.map +1 -0
  47. package/dist/simulation/scenarios/domain-examples/medical-imaging.js +129 -0
  48. package/dist/simulation/scenarios/domain-examples/medical-imaging.js.map +1 -0
  49. package/dist/simulation/scenarios/domain-examples/robotics-navigation.d.ts +166 -0
  50. package/dist/simulation/scenarios/domain-examples/robotics-navigation.d.ts.map +1 -0
  51. package/dist/simulation/scenarios/domain-examples/robotics-navigation.js +161 -0
  52. package/dist/simulation/scenarios/domain-examples/robotics-navigation.js.map +1 -0
  53. package/dist/simulation/scenarios/domain-examples/scientific-research.d.ts +151 -0
  54. package/dist/simulation/scenarios/domain-examples/scientific-research.d.ts.map +1 -0
  55. package/dist/simulation/scenarios/domain-examples/scientific-research.js +187 -0
  56. package/dist/simulation/scenarios/domain-examples/scientific-research.js.map +1 -0
  57. package/dist/simulation/scenarios/domain-examples/trading-systems.d.ts +102 -0
  58. package/dist/simulation/scenarios/domain-examples/trading-systems.d.ts.map +1 -0
  59. package/dist/simulation/scenarios/domain-examples/trading-systems.js +100 -0
  60. package/dist/simulation/scenarios/domain-examples/trading-systems.js.map +1 -0
  61. package/dist/simulation/scenarios/goalie-integration.d.ts +24 -0
  62. package/dist/simulation/scenarios/goalie-integration.d.ts.map +1 -0
  63. package/dist/simulation/scenarios/goalie-integration.js +121 -0
  64. package/dist/simulation/scenarios/goalie-integration.js.map +1 -0
  65. package/dist/simulation/scenarios/graph-traversal.d.ts +17 -0
  66. package/dist/simulation/scenarios/graph-traversal.d.ts.map +1 -0
  67. package/dist/simulation/scenarios/graph-traversal.js +101 -0
  68. package/dist/simulation/scenarios/graph-traversal.js.map +1 -0
  69. package/dist/simulation/scenarios/latent-space/attention-analysis.d.ts +45 -0
  70. package/dist/simulation/scenarios/latent-space/attention-analysis.d.ts.map +1 -0
  71. package/dist/simulation/scenarios/latent-space/attention-analysis.js +435 -0
  72. package/dist/simulation/scenarios/latent-space/attention-analysis.js.map +1 -0
  73. package/dist/simulation/scenarios/latent-space/clustering-analysis.d.ts +55 -0
  74. package/dist/simulation/scenarios/latent-space/clustering-analysis.d.ts.map +1 -0
  75. package/dist/simulation/scenarios/latent-space/clustering-analysis.js +606 -0
  76. package/dist/simulation/scenarios/latent-space/clustering-analysis.js.map +1 -0
  77. package/dist/simulation/scenarios/latent-space/hnsw-exploration.d.ts +74 -0
  78. package/dist/simulation/scenarios/latent-space/hnsw-exploration.d.ts.map +1 -0
  79. package/dist/simulation/scenarios/latent-space/hnsw-exploration.js +391 -0
  80. package/dist/simulation/scenarios/latent-space/hnsw-exploration.js.map +1 -0
  81. package/dist/simulation/scenarios/latent-space/hypergraph-exploration.d.ts +51 -0
  82. package/dist/simulation/scenarios/latent-space/hypergraph-exploration.d.ts.map +1 -0
  83. package/dist/simulation/scenarios/latent-space/hypergraph-exploration.js +536 -0
  84. package/dist/simulation/scenarios/latent-space/hypergraph-exploration.js.map +1 -0
  85. package/dist/simulation/scenarios/latent-space/index.d.ts +35 -0
  86. package/dist/simulation/scenarios/latent-space/index.d.ts.map +1 -0
  87. package/dist/simulation/scenarios/latent-space/index.js +35 -0
  88. package/dist/simulation/scenarios/latent-space/index.js.map +1 -0
  89. package/dist/simulation/scenarios/latent-space/neural-augmentation.d.ts +52 -0
  90. package/dist/simulation/scenarios/latent-space/neural-augmentation.d.ts.map +1 -0
  91. package/dist/simulation/scenarios/latent-space/neural-augmentation.js +472 -0
  92. package/dist/simulation/scenarios/latent-space/neural-augmentation.js.map +1 -0
  93. package/dist/simulation/scenarios/latent-space/quantum-hybrid.d.ts +53 -0
  94. package/dist/simulation/scenarios/latent-space/quantum-hybrid.d.ts.map +1 -0
  95. package/dist/simulation/scenarios/latent-space/quantum-hybrid.js +391 -0
  96. package/dist/simulation/scenarios/latent-space/quantum-hybrid.js.map +1 -0
  97. package/dist/simulation/scenarios/latent-space/self-organizing-hnsw.d.ts +52 -0
  98. package/dist/simulation/scenarios/latent-space/self-organizing-hnsw.d.ts.map +1 -0
  99. package/dist/simulation/scenarios/latent-space/self-organizing-hnsw.js +514 -0
  100. package/dist/simulation/scenarios/latent-space/self-organizing-hnsw.js.map +1 -0
  101. package/dist/simulation/scenarios/latent-space/traversal-optimization.d.ts +53 -0
  102. package/dist/simulation/scenarios/latent-space/traversal-optimization.d.ts.map +1 -0
  103. package/dist/simulation/scenarios/latent-space/traversal-optimization.js +595 -0
  104. package/dist/simulation/scenarios/latent-space/traversal-optimization.js.map +1 -0
  105. package/dist/simulation/scenarios/lean-agentic-swarm.d.ts +18 -0
  106. package/dist/simulation/scenarios/lean-agentic-swarm.d.ts.map +1 -0
  107. package/dist/simulation/scenarios/lean-agentic-swarm.js +132 -0
  108. package/dist/simulation/scenarios/lean-agentic-swarm.js.map +1 -0
  109. package/dist/simulation/scenarios/multi-agent-swarm.d.ts +17 -0
  110. package/dist/simulation/scenarios/multi-agent-swarm.d.ts.map +1 -0
  111. package/dist/simulation/scenarios/multi-agent-swarm.js +111 -0
  112. package/dist/simulation/scenarios/multi-agent-swarm.js.map +1 -0
  113. package/dist/simulation/scenarios/psycho-symbolic-reasoner.d.ts +23 -0
  114. package/dist/simulation/scenarios/psycho-symbolic-reasoner.d.ts.map +1 -0
  115. package/dist/simulation/scenarios/psycho-symbolic-reasoner.js +98 -0
  116. package/dist/simulation/scenarios/psycho-symbolic-reasoner.js.map +1 -0
  117. package/dist/simulation/scenarios/reflexion-learning.d.ts +16 -0
  118. package/dist/simulation/scenarios/reflexion-learning.d.ts.map +1 -0
  119. package/dist/simulation/scenarios/reflexion-learning.js +98 -0
  120. package/dist/simulation/scenarios/reflexion-learning.js.map +1 -0
  121. package/dist/simulation/scenarios/research-swarm.d.ts +24 -0
  122. package/dist/simulation/scenarios/research-swarm.d.ts.map +1 -0
  123. package/dist/simulation/scenarios/research-swarm.js +146 -0
  124. package/dist/simulation/scenarios/research-swarm.js.map +1 -0
  125. package/dist/simulation/scenarios/skill-evolution.d.ts +16 -0
  126. package/dist/simulation/scenarios/skill-evolution.d.ts.map +1 -0
  127. package/dist/simulation/scenarios/skill-evolution.js +109 -0
  128. package/dist/simulation/scenarios/skill-evolution.js.map +1 -0
  129. package/dist/simulation/scenarios/stock-market-emergence.d.ts +33 -0
  130. package/dist/simulation/scenarios/stock-market-emergence.d.ts.map +1 -0
  131. package/dist/simulation/scenarios/stock-market-emergence.js +246 -0
  132. package/dist/simulation/scenarios/stock-market-emergence.js.map +1 -0
  133. package/dist/simulation/scenarios/strange-loops.d.ts +18 -0
  134. package/dist/simulation/scenarios/strange-loops.d.ts.map +1 -0
  135. package/dist/simulation/scenarios/strange-loops.js +133 -0
  136. package/dist/simulation/scenarios/strange-loops.js.map +1 -0
  137. package/dist/simulation/scenarios/sublinear-solver.d.ts +22 -0
  138. package/dist/simulation/scenarios/sublinear-solver.d.ts.map +1 -0
  139. package/dist/simulation/scenarios/sublinear-solver.js +82 -0
  140. package/dist/simulation/scenarios/sublinear-solver.js.map +1 -0
  141. package/dist/simulation/scenarios/temporal-lead-solver.d.ts +23 -0
  142. package/dist/simulation/scenarios/temporal-lead-solver.d.ts.map +1 -0
  143. package/dist/simulation/scenarios/temporal-lead-solver.js +90 -0
  144. package/dist/simulation/scenarios/temporal-lead-solver.js.map +1 -0
  145. package/dist/simulation/scenarios/voting-system-consensus.d.ts +27 -0
  146. package/dist/simulation/scenarios/voting-system-consensus.d.ts.map +1 -0
  147. package/dist/simulation/scenarios/voting-system-consensus.js +175 -0
  148. package/dist/simulation/scenarios/voting-system-consensus.js.map +1 -0
  149. package/dist/simulation/types.d.ts +162 -0
  150. package/dist/simulation/types.d.ts.map +1 -0
  151. package/dist/simulation/types.js +5 -0
  152. package/dist/simulation/types.js.map +1 -0
  153. package/dist/simulation/utils/PerformanceOptimizer.d.ts +115 -0
  154. package/dist/simulation/utils/PerformanceOptimizer.d.ts.map +1 -0
  155. package/dist/simulation/utils/PerformanceOptimizer.js +223 -0
  156. package/dist/simulation/utils/PerformanceOptimizer.js.map +1 -0
  157. package/dist/src/backends/GraphBackend.d.ts +8 -8
  158. package/dist/src/backends/GraphBackend.d.ts.map +1 -1
  159. package/dist/src/backends/GraphBackend.js +15 -16
  160. package/dist/src/backends/GraphBackend.js.map +1 -1
  161. package/dist/src/backends/LearningBackend.d.ts +2 -2
  162. package/dist/src/backends/LearningBackend.d.ts.map +1 -1
  163. package/dist/src/backends/LearningBackend.js +10 -11
  164. package/dist/src/backends/LearningBackend.js.map +1 -1
  165. package/dist/src/backends/VectorBackend.d.ts +6 -31
  166. package/dist/src/backends/VectorBackend.d.ts.map +1 -1
  167. package/dist/src/backends/detector.d.ts +3 -25
  168. package/dist/src/backends/detector.d.ts.map +1 -1
  169. package/dist/src/backends/detector.js +15 -119
  170. package/dist/src/backends/detector.js.map +1 -1
  171. package/dist/src/backends/factory.d.ts +32 -16
  172. package/dist/src/backends/factory.d.ts.map +1 -1
  173. package/dist/src/backends/factory.js +70 -133
  174. package/dist/src/backends/factory.js.map +1 -1
  175. package/dist/src/backends/graph/GraphDatabaseAdapter.d.ts +1 -1
  176. package/dist/src/backends/graph/GraphDatabaseAdapter.d.ts.map +1 -1
  177. package/dist/src/backends/graph/GraphDatabaseAdapter.js +1 -5
  178. package/dist/src/backends/graph/GraphDatabaseAdapter.js.map +1 -1
  179. package/dist/src/backends/hnswlib/HNSWLibBackend.d.ts +2 -2
  180. package/dist/src/backends/hnswlib/HNSWLibBackend.d.ts.map +1 -1
  181. package/dist/src/backends/hnswlib/HNSWLibBackend.js +13 -49
  182. package/dist/src/backends/hnswlib/HNSWLibBackend.js.map +1 -1
  183. package/dist/src/backends/index.d.ts +3 -25
  184. package/dist/src/backends/index.d.ts.map +1 -1
  185. package/dist/src/backends/index.js +1 -23
  186. package/dist/src/backends/index.js.map +1 -1
  187. package/dist/src/backends/ruvector/GuardedVectorBackend.d.ts +93 -0
  188. package/dist/src/backends/ruvector/GuardedVectorBackend.d.ts.map +1 -0
  189. package/dist/src/backends/ruvector/GuardedVectorBackend.js +182 -0
  190. package/dist/src/backends/ruvector/GuardedVectorBackend.js.map +1 -0
  191. package/dist/src/backends/ruvector/RuVectorBackend.d.ts +16 -187
  192. package/dist/src/backends/ruvector/RuVectorBackend.d.ts.map +1 -1
  193. package/dist/src/backends/ruvector/RuVectorBackend.js +94 -576
  194. package/dist/src/backends/ruvector/RuVectorBackend.js.map +1 -1
  195. package/dist/src/backends/ruvector/RuVectorLearning.d.ts +4 -0
  196. package/dist/src/backends/ruvector/RuVectorLearning.d.ts.map +1 -1
  197. package/dist/src/backends/ruvector/RuVectorLearning.js +11 -10
  198. package/dist/src/backends/ruvector/RuVectorLearning.js.map +1 -1
  199. package/dist/src/benchmarks/wasm-vector-benchmark.d.ts +10 -0
  200. package/dist/src/benchmarks/wasm-vector-benchmark.d.ts.map +1 -0
  201. package/dist/src/benchmarks/wasm-vector-benchmark.js +196 -0
  202. package/dist/src/benchmarks/wasm-vector-benchmark.js.map +1 -0
  203. package/dist/src/browser/AdvancedFeatures.d.ts.map +1 -1
  204. package/dist/src/browser/AdvancedFeatures.js +10 -3
  205. package/dist/src/browser/AdvancedFeatures.js.map +1 -1
  206. package/dist/src/browser/AttentionBrowser.d.ts.map +1 -1
  207. package/dist/src/browser/AttentionBrowser.js +12 -5
  208. package/dist/src/browser/AttentionBrowser.js.map +1 -1
  209. package/dist/src/browser/HNSWIndex.d.ts +1 -31
  210. package/dist/src/browser/HNSWIndex.d.ts.map +1 -1
  211. package/dist/src/browser/HNSWIndex.js +18 -136
  212. package/dist/src/browser/HNSWIndex.js.map +1 -1
  213. package/dist/src/browser/ProductQuantization.d.ts.map +1 -1
  214. package/dist/src/browser/ProductQuantization.js +1 -0
  215. package/dist/src/browser/ProductQuantization.js.map +1 -1
  216. package/dist/src/browser/index.d.ts +3 -3
  217. package/dist/src/browser/index.d.ts.map +1 -1
  218. package/dist/src/browser/index.js +1 -2
  219. package/dist/src/browser/index.js.map +1 -1
  220. package/dist/src/cli/agentdb-cli.d.ts +2 -16
  221. package/dist/src/cli/agentdb-cli.d.ts.map +1 -1
  222. package/dist/src/cli/agentdb-cli.js +216 -853
  223. package/dist/src/cli/agentdb-cli.js.map +1 -1
  224. package/dist/src/cli/commands/attention.js +3 -3
  225. package/dist/src/cli/commands/attention.js.map +1 -1
  226. package/dist/src/cli/commands/doctor.d.ts +0 -2
  227. package/dist/src/cli/commands/doctor.d.ts.map +1 -1
  228. package/dist/src/cli/commands/doctor.js +1 -106
  229. package/dist/src/cli/commands/doctor.js.map +1 -1
  230. package/dist/src/cli/commands/init.d.ts +1 -2
  231. package/dist/src/cli/commands/init.d.ts.map +1 -1
  232. package/dist/src/cli/commands/init.js +7 -30
  233. package/dist/src/cli/commands/init.js.map +1 -1
  234. package/dist/src/cli/commands/install-embeddings.d.ts.map +1 -1
  235. package/dist/src/cli/commands/install-embeddings.js.map +1 -1
  236. package/dist/src/cli/commands/migrate.d.ts +0 -15
  237. package/dist/src/cli/commands/migrate.d.ts.map +1 -1
  238. package/dist/src/cli/commands/migrate.js +5 -164
  239. package/dist/src/cli/commands/migrate.js.map +1 -1
  240. package/dist/src/cli/commands/simulate-report.js.map +1 -1
  241. package/dist/src/cli/commands/simulate-wizard.js.map +1 -1
  242. package/dist/src/cli/commands/simulate.d.ts +7 -0
  243. package/dist/src/cli/commands/simulate.d.ts.map +1 -0
  244. package/dist/src/cli/commands/simulate.js +100 -0
  245. package/dist/src/cli/commands/simulate.js.map +1 -0
  246. package/dist/src/cli/commands/status.js +1 -5
  247. package/dist/src/cli/commands/status.js.map +1 -1
  248. package/dist/src/cli/lib/attention-config.d.ts +2 -2
  249. package/dist/src/cli/lib/attention-config.d.ts.map +1 -1
  250. package/dist/src/cli/lib/attention-config.js +1 -2
  251. package/dist/src/cli/lib/attention-config.js.map +1 -1
  252. package/dist/src/cli/lib/config-manager.d.ts +110 -0
  253. package/dist/src/cli/lib/config-manager.d.ts.map +1 -0
  254. package/dist/src/cli/lib/config-manager.js +512 -0
  255. package/dist/src/cli/lib/config-manager.js.map +1 -0
  256. package/dist/src/cli/lib/config-validator.d.ts +1 -1
  257. package/dist/src/cli/lib/config-validator.d.ts.map +1 -1
  258. package/dist/src/cli/lib/health-monitor.d.ts +149 -0
  259. package/dist/src/cli/lib/health-monitor.d.ts.map +1 -0
  260. package/dist/src/cli/lib/health-monitor.js +380 -0
  261. package/dist/src/cli/lib/health-monitor.js.map +1 -0
  262. package/dist/src/cli/lib/history-tracker.d.ts +103 -0
  263. package/dist/src/cli/lib/history-tracker.d.ts.map +1 -0
  264. package/dist/src/cli/lib/history-tracker.js +352 -0
  265. package/dist/src/cli/lib/history-tracker.js.map +1 -0
  266. package/dist/src/cli/lib/report-store.d.ts +1 -2
  267. package/dist/src/cli/lib/report-store.d.ts.map +1 -1
  268. package/dist/src/cli/lib/report-store.js +65 -87
  269. package/dist/src/cli/lib/report-store.js.map +1 -1
  270. package/dist/src/cli/lib/simulation-registry.d.ts +1 -1
  271. package/dist/src/cli/lib/simulation-registry.d.ts.map +1 -1
  272. package/dist/src/cli/lib/simulation-registry.js +0 -1
  273. package/dist/src/cli/lib/simulation-registry.js.map +1 -1
  274. package/dist/src/cli/lib/simulation-runner.d.ts +4 -41
  275. package/dist/src/cli/lib/simulation-runner.d.ts.map +1 -1
  276. package/dist/src/cli/lib/simulation-runner.js +6 -251
  277. package/dist/src/cli/lib/simulation-runner.js.map +1 -1
  278. package/dist/src/controllers/AttentionService.d.ts.map +1 -1
  279. package/dist/src/controllers/AttentionService.js +5 -3
  280. package/dist/src/controllers/AttentionService.js.map +1 -1
  281. package/dist/src/controllers/CausalMemoryGraph.d.ts +8 -33
  282. package/dist/src/controllers/CausalMemoryGraph.d.ts.map +1 -1
  283. package/dist/src/controllers/CausalMemoryGraph.js +16 -93
  284. package/dist/src/controllers/CausalMemoryGraph.js.map +1 -1
  285. package/dist/src/controllers/CausalRecall.d.ts +3 -6
  286. package/dist/src/controllers/CausalRecall.d.ts.map +1 -1
  287. package/dist/src/controllers/CausalRecall.js +8 -14
  288. package/dist/src/controllers/CausalRecall.js.map +1 -1
  289. package/dist/src/controllers/ContextSynthesizer.d.ts +1 -1
  290. package/dist/src/controllers/ContextSynthesizer.d.ts.map +1 -1
  291. package/dist/src/controllers/EmbeddingService.d.ts.map +1 -1
  292. package/dist/src/controllers/EmbeddingService.js +3 -10
  293. package/dist/src/controllers/EmbeddingService.js.map +1 -1
  294. package/dist/src/controllers/EnhancedEmbeddingService.d.ts +0 -4
  295. package/dist/src/controllers/EnhancedEmbeddingService.d.ts.map +1 -1
  296. package/dist/src/controllers/EnhancedEmbeddingService.js +3 -10
  297. package/dist/src/controllers/EnhancedEmbeddingService.js.map +1 -1
  298. package/dist/src/controllers/ExplainableRecall.d.ts +6 -5
  299. package/dist/src/controllers/ExplainableRecall.d.ts.map +1 -1
  300. package/dist/src/controllers/ExplainableRecall.js +13 -21
  301. package/dist/src/controllers/ExplainableRecall.js.map +1 -1
  302. package/dist/src/controllers/HNSWIndex.d.ts +7 -24
  303. package/dist/src/controllers/HNSWIndex.d.ts.map +1 -1
  304. package/dist/src/controllers/HNSWIndex.js +10 -89
  305. package/dist/src/controllers/HNSWIndex.js.map +1 -1
  306. package/dist/src/controllers/LearningSystem.d.ts +10 -106
  307. package/dist/src/controllers/LearningSystem.d.ts.map +1 -1
  308. package/dist/src/controllers/LearningSystem.js +14 -39
  309. package/dist/src/controllers/LearningSystem.js.map +1 -1
  310. package/dist/src/controllers/MMRDiversityRanker.d.ts +1 -1
  311. package/dist/src/controllers/MMRDiversityRanker.d.ts.map +1 -1
  312. package/dist/src/controllers/MetadataFilter.d.ts +3 -3
  313. package/dist/src/controllers/MetadataFilter.d.ts.map +1 -1
  314. package/dist/src/controllers/MetadataFilter.js +6 -9
  315. package/dist/src/controllers/MetadataFilter.js.map +1 -1
  316. package/dist/src/controllers/NightlyLearner.d.ts +4 -9
  317. package/dist/src/controllers/NightlyLearner.d.ts.map +1 -1
  318. package/dist/src/controllers/NightlyLearner.js +9 -28
  319. package/dist/src/controllers/NightlyLearner.js.map +1 -1
  320. package/dist/src/controllers/QUICClient.d.ts +2 -50
  321. package/dist/src/controllers/QUICClient.d.ts.map +1 -1
  322. package/dist/src/controllers/QUICClient.js +3 -193
  323. package/dist/src/controllers/QUICClient.js.map +1 -1
  324. package/dist/src/controllers/QUICServer.d.ts +4 -4
  325. package/dist/src/controllers/QUICServer.d.ts.map +1 -1
  326. package/dist/src/controllers/QUICServer.js +14 -22
  327. package/dist/src/controllers/QUICServer.js.map +1 -1
  328. package/dist/src/controllers/ReasoningBank.d.ts +4 -14
  329. package/dist/src/controllers/ReasoningBank.d.ts.map +1 -1
  330. package/dist/src/controllers/ReasoningBank.js +46 -59
  331. package/dist/src/controllers/ReasoningBank.js.map +1 -1
  332. package/dist/src/controllers/ReflexionMemory.d.ts +7 -80
  333. package/dist/src/controllers/ReflexionMemory.d.ts.map +1 -1
  334. package/dist/src/controllers/ReflexionMemory.js +214 -372
  335. package/dist/src/controllers/ReflexionMemory.js.map +1 -1
  336. package/dist/src/controllers/SkillLibrary.d.ts +7 -37
  337. package/dist/src/controllers/SkillLibrary.d.ts.map +1 -1
  338. package/dist/src/controllers/SkillLibrary.js +96 -212
  339. package/dist/src/controllers/SkillLibrary.js.map +1 -1
  340. package/dist/src/controllers/SyncCoordinator.d.ts +3 -2
  341. package/dist/src/controllers/SyncCoordinator.d.ts.map +1 -1
  342. package/dist/src/controllers/SyncCoordinator.js +5 -117
  343. package/dist/src/controllers/SyncCoordinator.js.map +1 -1
  344. package/dist/src/controllers/WASMVectorSearch.d.ts +9 -20
  345. package/dist/src/controllers/WASMVectorSearch.d.ts.map +1 -1
  346. package/dist/src/controllers/WASMVectorSearch.js +29 -154
  347. package/dist/src/controllers/WASMVectorSearch.js.map +1 -1
  348. package/dist/src/controllers/frontier-index.d.ts +14 -0
  349. package/dist/src/controllers/frontier-index.d.ts.map +1 -0
  350. package/dist/src/controllers/frontier-index.js +10 -0
  351. package/dist/src/controllers/frontier-index.js.map +1 -0
  352. package/dist/src/controllers/index.d.ts +17 -8
  353. package/dist/src/controllers/index.d.ts.map +1 -1
  354. package/dist/src/controllers/index.js +12 -6
  355. package/dist/src/controllers/index.js.map +1 -1
  356. package/dist/src/core/AgentDB.d.ts +25 -57
  357. package/dist/src/core/AgentDB.d.ts.map +1 -1
  358. package/dist/src/core/AgentDB.js +115 -137
  359. package/dist/src/core/AgentDB.js.map +1 -1
  360. package/dist/src/db-fallback.d.ts +1 -10
  361. package/dist/src/db-fallback.d.ts.map +1 -1
  362. package/dist/src/db-fallback.js +4 -171
  363. package/dist/src/db-fallback.js.map +1 -1
  364. package/dist/src/db-test.d.ts +13 -0
  365. package/dist/src/db-test.d.ts.map +1 -0
  366. package/dist/src/db-test.js +55 -0
  367. package/dist/src/db-test.js.map +1 -0
  368. package/dist/src/db-unified.d.ts +76 -0
  369. package/dist/src/db-unified.d.ts.map +1 -0
  370. package/dist/src/db-unified.js +279 -0
  371. package/dist/src/db-unified.js.map +1 -0
  372. package/dist/src/examples/quic-sync-example.d.ts +9 -0
  373. package/dist/src/examples/quic-sync-example.d.ts.map +1 -0
  374. package/dist/src/examples/quic-sync-example.js +169 -0
  375. package/dist/src/examples/quic-sync-example.js.map +1 -0
  376. package/dist/src/examples/wasm-vector-usage.d.ts +12 -0
  377. package/dist/src/examples/wasm-vector-usage.d.ts.map +1 -0
  378. package/dist/src/examples/wasm-vector-usage.js +190 -0
  379. package/dist/src/examples/wasm-vector-usage.js.map +1 -0
  380. package/dist/src/index.d.ts +12 -38
  381. package/dist/src/index.d.ts.map +1 -1
  382. package/dist/src/index.js +11 -46
  383. package/dist/src/index.js.map +1 -1
  384. package/dist/src/mcp/agentdb-mcp-server.js +63 -219
  385. package/dist/src/mcp/agentdb-mcp-server.js.map +1 -1
  386. package/dist/src/mcp/learning-tools-handlers.d.ts +16 -0
  387. package/dist/src/mcp/learning-tools-handlers.d.ts.map +1 -0
  388. package/dist/src/mcp/learning-tools-handlers.js +105 -0
  389. package/dist/src/mcp/learning-tools-handlers.js.map +1 -0
  390. package/dist/src/optimizations/BatchOperations.d.ts +5 -52
  391. package/dist/src/optimizations/BatchOperations.d.ts.map +1 -1
  392. package/dist/src/optimizations/BatchOperations.js +33 -186
  393. package/dist/src/optimizations/BatchOperations.js.map +1 -1
  394. package/dist/src/optimizations/QueryOptimizer.d.ts +4 -4
  395. package/dist/src/optimizations/QueryOptimizer.d.ts.map +1 -1
  396. package/dist/src/optimizations/QueryOptimizer.js +1 -3
  397. package/dist/src/optimizations/QueryOptimizer.js.map +1 -1
  398. package/dist/src/optimizations/ToolCache.d.ts +4 -4
  399. package/dist/src/optimizations/ToolCache.d.ts.map +1 -1
  400. package/dist/src/optimizations/ToolCache.js.map +1 -1
  401. package/dist/src/optimizations/index.d.ts +1 -1
  402. package/dist/src/optimizations/index.d.ts.map +1 -1
  403. package/dist/src/security/AttestationLog.d.ts +70 -0
  404. package/dist/src/security/AttestationLog.d.ts.map +1 -0
  405. package/dist/src/security/AttestationLog.js +174 -0
  406. package/dist/src/security/AttestationLog.js.map +1 -0
  407. package/dist/src/security/MutationGuard.d.ts +83 -0
  408. package/dist/src/security/MutationGuard.d.ts.map +1 -0
  409. package/dist/src/security/MutationGuard.js +379 -0
  410. package/dist/src/security/MutationGuard.js.map +1 -0
  411. package/dist/src/security/index.d.ts +15 -0
  412. package/dist/src/security/index.d.ts.map +1 -0
  413. package/dist/src/security/index.js +18 -0
  414. package/dist/src/security/index.js.map +1 -0
  415. package/dist/src/security/input-validation.d.ts +12 -12
  416. package/dist/src/security/input-validation.d.ts.map +1 -1
  417. package/dist/src/security/input-validation.js +0 -1
  418. package/dist/src/security/input-validation.js.map +1 -1
  419. package/dist/src/security/limits.d.ts +150 -0
  420. package/dist/src/security/limits.d.ts.map +1 -0
  421. package/dist/src/security/limits.js +288 -0
  422. package/dist/src/security/limits.js.map +1 -0
  423. package/dist/src/security/path-security.d.ts +100 -0
  424. package/dist/src/security/path-security.d.ts.map +1 -0
  425. package/dist/src/security/path-security.js +337 -0
  426. package/dist/src/security/path-security.js.map +1 -0
  427. package/dist/src/security/validation.d.ts +95 -0
  428. package/dist/src/security/validation.d.ts.map +1 -0
  429. package/dist/src/security/validation.js +315 -0
  430. package/dist/src/security/validation.js.map +1 -0
  431. package/dist/src/services/GraphTransformerService.d.ts +79 -0
  432. package/dist/src/services/GraphTransformerService.d.ts.map +1 -0
  433. package/dist/src/services/GraphTransformerService.js +331 -0
  434. package/dist/src/services/GraphTransformerService.js.map +1 -0
  435. package/dist/src/services/LLMRouter.d.ts +7 -61
  436. package/dist/src/services/LLMRouter.d.ts.map +1 -1
  437. package/dist/src/services/LLMRouter.js +25 -295
  438. package/dist/src/services/LLMRouter.js.map +1 -1
  439. package/dist/src/services/SemanticRouter.d.ts +78 -0
  440. package/dist/src/services/SemanticRouter.d.ts.map +1 -0
  441. package/dist/src/services/SemanticRouter.js +149 -0
  442. package/dist/src/services/SemanticRouter.js.map +1 -0
  443. package/dist/src/services/SonaTrajectoryService.d.ts +100 -0
  444. package/dist/src/services/SonaTrajectoryService.d.ts.map +1 -0
  445. package/dist/src/services/SonaTrajectoryService.js +231 -0
  446. package/dist/src/services/SonaTrajectoryService.js.map +1 -0
  447. package/dist/src/types/attention.d.ts +249 -0
  448. package/dist/src/types/attention.d.ts.map +1 -0
  449. package/dist/src/types/attention.js +43 -0
  450. package/dist/src/types/attention.js.map +1 -0
  451. package/dist/src/types/quic.d.ts +518 -0
  452. package/dist/src/types/quic.d.ts.map +1 -0
  453. package/dist/src/types/quic.js +272 -0
  454. package/dist/src/types/quic.js.map +1 -0
  455. package/dist/src/utils/LegacyAttentionAdapter.d.ts +93 -0
  456. package/dist/src/utils/LegacyAttentionAdapter.d.ts.map +1 -0
  457. package/dist/src/utils/LegacyAttentionAdapter.js +241 -0
  458. package/dist/src/utils/LegacyAttentionAdapter.js.map +1 -0
  459. package/dist/src/utils/attention-metrics.d.ts +76 -0
  460. package/dist/src/utils/attention-metrics.d.ts.map +1 -0
  461. package/dist/src/utils/attention-metrics.js +178 -0
  462. package/dist/src/utils/attention-metrics.js.map +1 -0
  463. package/dist/src/utils/vector-math.d.ts +29 -0
  464. package/dist/src/utils/vector-math.d.ts.map +1 -0
  465. package/dist/src/utils/vector-math.js +66 -0
  466. package/dist/src/utils/vector-math.js.map +1 -0
  467. package/examples/README.md +105 -0
  468. package/examples/browser/attention-demo.html +499 -0
  469. package/examples/browser/flash-consolidation.html +598 -0
  470. package/examples/browser/hyperbolic-hierarchy.html +497 -0
  471. package/examples/quickstart.js +43 -0
  472. package/package.json +53 -56
  473. package/simulation/.claude-flow/metrics/agent-metrics.json +1 -0
  474. package/simulation/.claude-flow/metrics/performance.json +87 -0
  475. package/simulation/.claude-flow/metrics/task-metrics.json +10 -0
  476. package/simulation/COMPLETION-STATUS.md +139 -0
  477. package/simulation/FINAL-RESULTS.md +414 -0
  478. package/simulation/FINAL-STATUS.md +281 -0
  479. package/simulation/INTEGRATION-COMPLETE.md +452 -0
  480. package/simulation/MIGRATION-STATUS.md +231 -0
  481. package/simulation/OPTIMIZATION-RESULTS.md +397 -0
  482. package/simulation/PHASE1-COMPLETE.md +163 -0
  483. package/simulation/README.md +848 -0
  484. package/simulation/SIMULATION-RESULTS.md +239 -0
  485. package/simulation/cli.ts +78 -0
  486. package/simulation/configs/default.json +37 -0
  487. package/simulation/data/advanced/aidefence.graph +0 -0
  488. package/simulation/data/advanced/bmssp.graph +0 -0
  489. package/simulation/data/advanced/consciousness.graph +0 -0
  490. package/simulation/data/advanced/goalie.graph +0 -0
  491. package/simulation/data/advanced/psycho-symbolic.graph +0 -0
  492. package/simulation/data/advanced/research-swarm.graph +0 -0
  493. package/simulation/data/advanced/sublinear.graph +0 -0
  494. package/simulation/data/advanced/temporal.graph +0 -0
  495. package/simulation/data/causal.graph +0 -0
  496. package/simulation/data/graph-traversal.graph +0 -0
  497. package/simulation/data/lean-agentic.graph +0 -0
  498. package/simulation/data/reflexion.graph +0 -0
  499. package/simulation/data/skills.graph +0 -0
  500. package/simulation/data/stock-market.graph +0 -0
  501. package/simulation/data/strange-loops.graph +0 -0
  502. package/simulation/data/swarm.graph +0 -0
  503. package/simulation/data/voting-consensus.graph +0 -0
  504. package/simulation/docs/CLI-INTEGRATION-PLAN.md +1038 -0
  505. package/simulation/docs/COMPREHENSIVE-LATENT-SPACE-COMPLETION.md +354 -0
  506. package/simulation/docs/DOCUMENTATION-INDEX.md +226 -0
  507. package/simulation/docs/IMPLEMENTATION-COMPLETE.md +521 -0
  508. package/simulation/docs/OPTIMIZATION-SUMMARY.md +279 -0
  509. package/simulation/docs/README.md +229 -0
  510. package/simulation/docs/SWARM-5-INTEGRATION-SUMMARY.md +528 -0
  511. package/simulation/docs/TESTING-SUMMARY.md +304 -0
  512. package/simulation/docs/architecture/EXTENSION-API.md +868 -0
  513. package/simulation/docs/architecture/INTEGRATION-ARCHITECTURE.md +1138 -0
  514. package/simulation/docs/architecture/OPTIMIZATION-STRATEGY.md +778 -0
  515. package/simulation/docs/architecture/SIMULATION-ARCHITECTURE.md +892 -0
  516. package/simulation/docs/guides/CLI-REFERENCE.md +896 -0
  517. package/simulation/docs/guides/CUSTOM-SIMULATIONS.md +931 -0
  518. package/simulation/docs/guides/DEPLOYMENT.md +832 -0
  519. package/simulation/docs/guides/IMPLEMENTATION-SUMMARY.md +544 -0
  520. package/simulation/docs/guides/MIGRATION-GUIDE.md +591 -0
  521. package/simulation/docs/guides/QUICK-START.md +361 -0
  522. package/simulation/docs/guides/README.md +736 -0
  523. package/simulation/docs/guides/TROUBLESHOOTING.md +817 -0
  524. package/simulation/docs/guides/WIZARD-GUIDE.md +869 -0
  525. package/simulation/docs/reports/latent-space/MASTER-SYNTHESIS.md +345 -0
  526. package/simulation/docs/reports/latent-space/README.md +132 -0
  527. package/simulation/docs/reports/latent-space/attention-analysis-RESULTS.md +238 -0
  528. package/simulation/docs/reports/latent-space/clustering-analysis-RESULTS.md +210 -0
  529. package/simulation/docs/reports/latent-space/hnsw-exploration-RESULTS.md +332 -0
  530. package/simulation/docs/reports/latent-space/hypergraph-exploration-RESULTS.md +37 -0
  531. package/simulation/docs/reports/latent-space/neural-augmentation-RESULTS.md +69 -0
  532. package/simulation/docs/reports/latent-space/quantum-hybrid-RESULTS.md +91 -0
  533. package/simulation/docs/reports/latent-space/self-organizing-hnsw-RESULTS.md +51 -0
  534. package/simulation/docs/reports/latent-space/traversal-optimization-RESULTS.md +238 -0
  535. package/simulation/reports/README.md +397 -0
  536. package/simulation/reports/advanced-simulations-performance.md +1241 -0
  537. package/simulation/reports/aidefence-integration-2025-11-30T01-36-53-486Z.json +30 -0
  538. package/simulation/reports/architecture-analysis.md +1396 -0
  539. package/simulation/reports/basic-scenarios-performance.md +1840 -0
  540. package/simulation/reports/bmssp-integration-2025-11-30T01-36-27-193Z.json +30 -0
  541. package/simulation/reports/bmssp-integration-2025-11-30T03-38-12-887Z.json +30 -0
  542. package/simulation/reports/causal-reasoning-2025-11-29T23-35-21-795Z.json +36 -0
  543. package/simulation/reports/causal-reasoning-2025-11-30T00-58-42-862Z.json +30 -0
  544. package/simulation/reports/causal-reasoning-2025-11-30T00-59-12-546Z.json +40 -0
  545. package/simulation/reports/consciousness-explorer-2025-11-30T01-36-51-269Z.json +31 -0
  546. package/simulation/reports/core-benchmarks.md +727 -0
  547. package/simulation/reports/goalie-integration-2025-11-30T01-36-52-377Z.json +30 -0
  548. package/simulation/reports/graph-traversal-2025-11-29T23-35-35-279Z.json +78 -0
  549. package/simulation/reports/graph-traversal-2025-11-29T23-37-36-697Z.json +30 -0
  550. package/simulation/reports/graph-traversal-2025-11-30T01-03-59-716Z.json +30 -0
  551. package/simulation/reports/graph-traversal-2025-11-30T01-05-10-984Z.json +30 -0
  552. package/simulation/reports/graph-traversal-2025-11-30T01-06-16-334Z.json +30 -0
  553. package/simulation/reports/graph-traversal-2025-11-30T01-06-53-312Z.json +30 -0
  554. package/simulation/reports/graph-traversal-2025-11-30T01-07-51-075Z.json +24 -0
  555. package/simulation/reports/graph-traversal-2025-11-30T01-08-22-179Z.json +42 -0
  556. package/simulation/reports/lean-agentic-swarm-2025-11-29T23-37-23-804Z.json +148 -0
  557. package/simulation/reports/lean-agentic-swarm-2025-11-30T01-31-24-401Z.json +31 -0
  558. package/simulation/reports/lean-agentic-swarm-2025-11-30T03-38-01-470Z.json +31 -0
  559. package/simulation/reports/multi-agent-swarm-2025-11-29T23-35-28-093Z.json +78 -0
  560. package/simulation/reports/multi-agent-swarm-2025-11-30T01-03-54-062Z.json +42 -0
  561. package/simulation/reports/multi-agent-swarm-2025-11-30T01-05-06-092Z.json +42 -0
  562. package/simulation/reports/psycho-symbolic-reasoner-2025-11-30T01-36-50-180Z.json +30 -0
  563. package/simulation/reports/quality-metrics.md +727 -0
  564. package/simulation/reports/reflexion-learning-2025-11-29T23-35-09-774Z.json +48 -0
  565. package/simulation/reports/reflexion-learning-2025-11-29T23-37-16-934Z.json +36 -0
  566. package/simulation/reports/reflexion-learning-2025-11-30T00-07-49-259Z.json +30 -0
  567. package/simulation/reports/reflexion-learning-2025-11-30T00-09-29-319Z.json +51 -0
  568. package/simulation/reports/reflexion-learning-2025-11-30T00-28-37-659Z.json +51 -0
  569. package/simulation/reports/reflexion-learning-2025-11-30T01-31-30-690Z.json +29 -0
  570. package/simulation/reports/reflexion-learning-2025-11-30T03-38-06-937Z.json +29 -0
  571. package/simulation/reports/research-foundations.md +2004 -0
  572. package/simulation/reports/research-swarm-2025-11-30T01-36-54-647Z.json +30 -0
  573. package/simulation/reports/scalability-deployment.md +2404 -0
  574. package/simulation/reports/skill-evolution-2025-11-29T23-35-15-945Z.json +36 -0
  575. package/simulation/reports/skill-evolution-2025-11-30T01-03-17-995Z.json +30 -0
  576. package/simulation/reports/skill-evolution-2025-11-30T01-03-48-441Z.json +30 -0
  577. package/simulation/reports/skill-evolution-2025-11-30T01-05-00-554Z.json +30 -0
  578. package/simulation/reports/skill-evolution-2025-11-30T01-06-11-436Z.json +30 -0
  579. package/simulation/reports/skill-evolution-2025-11-30T01-06-51-979Z.json +30 -0
  580. package/simulation/reports/skill-evolution-2025-11-30T01-07-32-695Z.json +40 -0
  581. package/simulation/reports/stock-market-emergence-2025-11-30T00-11-43-865Z.json +56 -0
  582. package/simulation/reports/stock-market-emergence-2025-11-30T00-28-57-495Z.json +56 -0
  583. package/simulation/reports/strange-loops-2025-11-29T23-37-30-621Z.json +78 -0
  584. package/simulation/reports/strange-loops-2025-11-30T00-07-55-415Z.json +30 -0
  585. package/simulation/reports/strange-loops-2025-11-30T00-09-35-133Z.json +30 -0
  586. package/simulation/reports/strange-loops-2025-11-30T00-48-50-744Z.json +24 -0
  587. package/simulation/reports/strange-loops-2025-11-30T00-54-48-044Z.json +24 -0
  588. package/simulation/reports/strange-loops-2025-11-30T00-57-27-633Z.json +24 -0
  589. package/simulation/reports/strange-loops-2025-11-30T00-57-59-135Z.json +42 -0
  590. package/simulation/reports/sublinear-solver-2025-11-30T01-36-33-134Z.json +30 -0
  591. package/simulation/reports/temporal-lead-solver-2025-11-30T01-36-38-628Z.json +30 -0
  592. package/simulation/reports/use-cases-applications.md +2212 -0
  593. package/simulation/reports/voting-system-consensus-2025-11-30T00-11-37-199Z.json +58 -0
  594. package/simulation/reports/voting-system-consensus-2025-11-30T00-28-47-735Z.json +58 -0
  595. package/simulation/runner.ts +300 -0
  596. package/simulation/scenarios/README-advanced/aidefence-integration.md +63 -0
  597. package/simulation/scenarios/README-advanced/bmssp-integration.md +58 -0
  598. package/simulation/scenarios/README-advanced/consciousness-explorer.md +53 -0
  599. package/simulation/scenarios/README-advanced/goalie-integration.md +61 -0
  600. package/simulation/scenarios/README-advanced/psycho-symbolic-reasoner.md +55 -0
  601. package/simulation/scenarios/README-advanced/research-swarm.md +63 -0
  602. package/simulation/scenarios/README-advanced/sublinear-solver.md +58 -0
  603. package/simulation/scenarios/README-advanced/temporal-lead-solver.md +55 -0
  604. package/simulation/scenarios/README-basic/causal-reasoning.md +39 -0
  605. package/simulation/scenarios/README-basic/graph-traversal.md +41 -0
  606. package/simulation/scenarios/README-basic/lean-agentic-swarm.md +122 -0
  607. package/simulation/scenarios/README-basic/multi-agent-swarm.md +34 -0
  608. package/simulation/scenarios/README-basic/reflexion-learning.md +41 -0
  609. package/simulation/scenarios/README-basic/skill-evolution.md +38 -0
  610. package/simulation/scenarios/README-basic/stock-market-emergence.md +28 -0
  611. package/simulation/scenarios/README-basic/strange-loops.md +36 -0
  612. package/simulation/scenarios/README-basic/voting-system-consensus.md +28 -0
  613. package/simulation/scenarios/README.md +438 -0
  614. package/simulation/scenarios/aidefence-integration.ts +165 -0
  615. package/simulation/scenarios/bmssp-integration.ts +137 -0
  616. package/simulation/scenarios/causal-reasoning.ts +143 -0
  617. package/simulation/scenarios/consciousness-explorer.ts +139 -0
  618. package/simulation/scenarios/domain-examples/.claude-flow/metrics/agent-metrics.json +1 -0
  619. package/simulation/scenarios/domain-examples/.claude-flow/metrics/performance.json +87 -0
  620. package/simulation/scenarios/domain-examples/.claude-flow/metrics/task-metrics.json +10 -0
  621. package/simulation/scenarios/domain-examples/README.md +525 -0
  622. package/simulation/scenarios/domain-examples/e-commerce-recommendations.ts +220 -0
  623. package/simulation/scenarios/domain-examples/index.ts +81 -0
  624. package/simulation/scenarios/domain-examples/iot-sensor-networks.ts +290 -0
  625. package/simulation/scenarios/domain-examples/medical-imaging.ts +181 -0
  626. package/simulation/scenarios/domain-examples/robotics-navigation.ts +214 -0
  627. package/simulation/scenarios/domain-examples/scientific-research.ts +250 -0
  628. package/simulation/scenarios/domain-examples/trading-systems.ts +138 -0
  629. package/simulation/scenarios/goalie-integration.ts +161 -0
  630. package/simulation/scenarios/graph-traversal.ts +129 -0
  631. package/simulation/scenarios/latent-space/OPTIMIZATION-COMPLETE.md +287 -0
  632. package/simulation/scenarios/latent-space/README-attention-analysis.md +170 -0
  633. package/simulation/scenarios/latent-space/README-clustering-analysis.md +239 -0
  634. package/simulation/scenarios/latent-space/README-hnsw-exploration.md +199 -0
  635. package/simulation/scenarios/latent-space/README-hypergraph-exploration.md +279 -0
  636. package/simulation/scenarios/latent-space/README-neural-augmentation.md +267 -0
  637. package/simulation/scenarios/latent-space/README-quantum-hybrid.md +276 -0
  638. package/simulation/scenarios/latent-space/README-self-organizing-hnsw.md +244 -0
  639. package/simulation/scenarios/latent-space/README-traversal-optimization.md +212 -0
  640. package/simulation/scenarios/latent-space/attention-analysis.ts +598 -0
  641. package/simulation/scenarios/latent-space/clustering-analysis.ts +796 -0
  642. package/simulation/scenarios/latent-space/hnsw-exploration.ts +526 -0
  643. package/simulation/scenarios/latent-space/hypergraph-exploration.ts +706 -0
  644. package/simulation/scenarios/latent-space/index.ts +47 -0
  645. package/simulation/scenarios/latent-space/neural-augmentation.ts +604 -0
  646. package/simulation/scenarios/latent-space/quantum-hybrid.ts +508 -0
  647. package/simulation/scenarios/latent-space/self-organizing-hnsw.ts +680 -0
  648. package/simulation/scenarios/latent-space/traversal-optimization.ts +782 -0
  649. package/simulation/scenarios/lean-agentic-swarm.ts +182 -0
  650. package/simulation/scenarios/multi-agent-swarm.ts +146 -0
  651. package/simulation/scenarios/psycho-symbolic-reasoner.ts +136 -0
  652. package/simulation/scenarios/reflexion-learning.ts +132 -0
  653. package/simulation/scenarios/research-swarm.ts +187 -0
  654. package/simulation/scenarios/skill-evolution.ts +135 -0
  655. package/simulation/scenarios/stock-market-emergence.ts +323 -0
  656. package/simulation/scenarios/strange-loops.ts +175 -0
  657. package/simulation/scenarios/sublinear-solver.ts +108 -0
  658. package/simulation/scenarios/temporal-lead-solver.ts +121 -0
  659. package/simulation/scenarios/voting-system-consensus.ts +251 -0
  660. package/simulation/tests/latent-space/attention-analysis.test.ts +204 -0
  661. package/simulation/tests/latent-space/clustering-analysis.test.ts +281 -0
  662. package/simulation/tests/latent-space/hnsw-exploration.test.ts +253 -0
  663. package/simulation/tests/latent-space/hypergraph-exploration.test.ts +295 -0
  664. package/simulation/tests/latent-space/neural-augmentation.test.ts +326 -0
  665. package/simulation/tests/latent-space/quantum-hybrid.test.ts +307 -0
  666. package/simulation/tests/latent-space/self-organizing-hnsw.test.ts +291 -0
  667. package/simulation/tests/latent-space/traversal-optimization.test.ts +261 -0
  668. package/simulation/types.ts +177 -0
  669. package/simulation/utils/PerformanceOptimizer.ts +269 -0
  670. package/src/backends/GraphBackend.ts +290 -0
  671. package/src/backends/LearningBackend.ts +210 -0
  672. package/src/backends/README.md +389 -0
  673. package/src/backends/VectorBackend.ts +147 -0
  674. package/src/backends/detector.ts +283 -0
  675. package/src/backends/factory.ts +279 -0
  676. package/src/backends/graph/GraphDatabaseAdapter.ts +334 -0
  677. package/src/backends/hnswlib/HNSWLibBackend.ts +419 -0
  678. package/src/backends/hnswlib/index.ts +7 -0
  679. package/src/backends/index.ts +32 -0
  680. package/src/backends/ruvector/GuardedVectorBackend.ts +219 -0
  681. package/src/backends/ruvector/RuVectorBackend.ts +343 -0
  682. package/src/backends/ruvector/RuVectorLearning.ts +254 -0
  683. package/src/backends/ruvector/index.ts +9 -0
  684. package/src/benchmarks/wasm-vector-benchmark.ts +250 -0
  685. package/src/browser/AdvancedFeatures.ts +565 -0
  686. package/src/browser/AttentionBrowser.ts +387 -0
  687. package/src/browser/HNSWIndex.ts +494 -0
  688. package/src/browser/ProductQuantization.ts +419 -0
  689. package/src/browser/index.ts +317 -0
  690. package/src/cli/agentdb-cli.ts +2712 -0
  691. package/src/cli/attention-cli-integration.ts +91 -0
  692. package/src/cli/commands/attention.ts +656 -0
  693. package/src/cli/commands/doctor.ts +322 -0
  694. package/src/cli/commands/init.ts +176 -0
  695. package/src/cli/commands/install-embeddings.ts +81 -0
  696. package/src/cli/commands/migrate.ts +545 -0
  697. package/src/cli/commands/simulate-custom.ts +232 -0
  698. package/src/cli/commands/simulate-report.ts +171 -0
  699. package/src/cli/commands/simulate-wizard.ts +379 -0
  700. package/src/cli/commands/simulate.ts +115 -0
  701. package/src/cli/commands/status.ts +156 -0
  702. package/src/cli/examples.sh +83 -0
  703. package/src/cli/lib/attention-config.ts +326 -0
  704. package/src/cli/lib/config-manager.ts +627 -0
  705. package/src/cli/lib/config-validator.ts +261 -0
  706. package/src/cli/lib/health-monitor.ts +513 -0
  707. package/src/cli/lib/help-formatter.ts +406 -0
  708. package/src/cli/lib/history-tracker.ts +503 -0
  709. package/src/cli/lib/report-generator.ts +455 -0
  710. package/src/cli/lib/report-store.ts +582 -0
  711. package/src/cli/lib/simulation-registry.ts +503 -0
  712. package/src/cli/lib/simulation-runner.ts +291 -0
  713. package/src/cli/tests/agentdb-cli.test.ts +58 -0
  714. package/src/cli/tests/attention-cli.test.ts +335 -0
  715. package/src/controllers/AttentionService.ts +770 -0
  716. package/src/controllers/CausalMemoryGraph.ts +773 -0
  717. package/src/controllers/CausalRecall.ts +484 -0
  718. package/src/controllers/ContextSynthesizer.ts +285 -0
  719. package/src/controllers/EmbeddingService.ts +161 -0
  720. package/src/controllers/EnhancedEmbeddingService.ts +143 -0
  721. package/src/controllers/ExplainableRecall.ts +746 -0
  722. package/src/controllers/HNSWIndex.ts +495 -0
  723. package/src/controllers/LearningSystem.ts +1270 -0
  724. package/src/controllers/MMRDiversityRanker.ts +187 -0
  725. package/src/controllers/MetadataFilter.ts +280 -0
  726. package/src/controllers/NightlyLearner.ts +647 -0
  727. package/src/controllers/QUICClient.ts +413 -0
  728. package/src/controllers/QUICServer.ts +498 -0
  729. package/src/controllers/ReasoningBank.ts +665 -0
  730. package/src/controllers/ReflexionMemory.ts +872 -0
  731. package/src/controllers/SkillLibrary.ts +795 -0
  732. package/src/controllers/SyncCoordinator.ts +597 -0
  733. package/src/controllers/WASMVectorSearch.ts +292 -0
  734. package/src/controllers/frontier-index.ts +35 -0
  735. package/src/controllers/index.ts +57 -0
  736. package/src/coordination/MultiDatabaseCoordinator.ts +1107 -0
  737. package/src/coordination/index.ts +24 -0
  738. package/src/core/AgentDB.ts +211 -0
  739. package/src/db-fallback.ts +296 -0
  740. package/src/db-test.ts +59 -0
  741. package/src/db-unified.ts +327 -0
  742. package/src/examples/quic-sync-example.ts +198 -0
  743. package/src/examples/wasm-vector-usage.ts +245 -0
  744. package/src/index.ts +69 -0
  745. package/src/mcp/agentdb-mcp-server.ts +2318 -0
  746. package/src/mcp/attention-mcp-integration.ts +145 -0
  747. package/src/mcp/attention-tools-handlers.ts +586 -0
  748. package/src/mcp/learning-tools-handlers.ts +106 -0
  749. package/src/optimizations/BatchOperations.ts +594 -0
  750. package/src/optimizations/QueryOptimizer.ts +297 -0
  751. package/src/optimizations/ToolCache.ts +355 -0
  752. package/src/optimizations/index.ts +11 -0
  753. package/src/schemas/frontier-schema.sql +378 -0
  754. package/src/schemas/schema.sql +382 -0
  755. package/src/security/AttestationLog.ts +252 -0
  756. package/src/security/MutationGuard.ts +420 -0
  757. package/src/security/index.ts +52 -0
  758. package/src/security/input-validation.ts +543 -0
  759. package/src/security/limits.ts +375 -0
  760. package/src/security/path-security.ts +436 -0
  761. package/src/security/validation.ts +556 -0
  762. package/src/services/GraphTransformerService.ts +389 -0
  763. package/src/services/LLMRouter.ts +380 -0
  764. package/src/services/SemanticRouter.ts +169 -0
  765. package/src/services/SonaTrajectoryService.ts +264 -0
  766. package/src/tests/attention-service.test.ts +492 -0
  767. package/src/tests/wasm-vector-search.test.ts +240 -0
  768. package/src/types/attention.ts +392 -0
  769. package/src/types/quic.ts +772 -0
  770. package/src/utils/LegacyAttentionAdapter.ts +393 -0
  771. package/src/utils/NodeIdMapper.ts +64 -0
  772. package/src/utils/attention-metrics.ts +253 -0
  773. package/src/utils/vector-math.ts +71 -0
  774. package/LICENSE +0 -21
  775. package/dist/src/backends/rvf/AdaptiveIndexTuner.d.ts +0 -175
  776. package/dist/src/backends/rvf/AdaptiveIndexTuner.d.ts.map +0 -1
  777. package/dist/src/backends/rvf/AdaptiveIndexTuner.js +0 -559
  778. package/dist/src/backends/rvf/AdaptiveIndexTuner.js.map +0 -1
  779. package/dist/src/backends/rvf/ContrastiveTrainer.d.ts +0 -148
  780. package/dist/src/backends/rvf/ContrastiveTrainer.d.ts.map +0 -1
  781. package/dist/src/backends/rvf/ContrastiveTrainer.js +0 -438
  782. package/dist/src/backends/rvf/ContrastiveTrainer.js.map +0 -1
  783. package/dist/src/backends/rvf/FederatedSessionManager.d.ts +0 -211
  784. package/dist/src/backends/rvf/FederatedSessionManager.d.ts.map +0 -1
  785. package/dist/src/backends/rvf/FederatedSessionManager.js +0 -389
  786. package/dist/src/backends/rvf/FederatedSessionManager.js.map +0 -1
  787. package/dist/src/backends/rvf/FilterBuilder.d.ts +0 -136
  788. package/dist/src/backends/rvf/FilterBuilder.d.ts.map +0 -1
  789. package/dist/src/backends/rvf/FilterBuilder.js +0 -157
  790. package/dist/src/backends/rvf/FilterBuilder.js.map +0 -1
  791. package/dist/src/backends/rvf/NativeAccelerator.d.ts +0 -140
  792. package/dist/src/backends/rvf/NativeAccelerator.d.ts.map +0 -1
  793. package/dist/src/backends/rvf/NativeAccelerator.js +0 -630
  794. package/dist/src/backends/rvf/NativeAccelerator.js.map +0 -1
  795. package/dist/src/backends/rvf/RvfBackend.d.ts +0 -194
  796. package/dist/src/backends/rvf/RvfBackend.d.ts.map +0 -1
  797. package/dist/src/backends/rvf/RvfBackend.js +0 -607
  798. package/dist/src/backends/rvf/RvfBackend.js.map +0 -1
  799. package/dist/src/backends/rvf/RvfSolver.d.ts +0 -175
  800. package/dist/src/backends/rvf/RvfSolver.d.ts.map +0 -1
  801. package/dist/src/backends/rvf/RvfSolver.js +0 -176
  802. package/dist/src/backends/rvf/RvfSolver.js.map +0 -1
  803. package/dist/src/backends/rvf/SelfLearningRvfBackend.d.ts +0 -143
  804. package/dist/src/backends/rvf/SelfLearningRvfBackend.d.ts.map +0 -1
  805. package/dist/src/backends/rvf/SelfLearningRvfBackend.js +0 -569
  806. package/dist/src/backends/rvf/SelfLearningRvfBackend.js.map +0 -1
  807. package/dist/src/backends/rvf/SemanticQueryRouter.d.ts +0 -128
  808. package/dist/src/backends/rvf/SemanticQueryRouter.d.ts.map +0 -1
  809. package/dist/src/backends/rvf/SemanticQueryRouter.js +0 -415
  810. package/dist/src/backends/rvf/SemanticQueryRouter.js.map +0 -1
  811. package/dist/src/backends/rvf/SimdFallbacks.d.ts +0 -25
  812. package/dist/src/backends/rvf/SimdFallbacks.d.ts.map +0 -1
  813. package/dist/src/backends/rvf/SimdFallbacks.js +0 -287
  814. package/dist/src/backends/rvf/SimdFallbacks.js.map +0 -1
  815. package/dist/src/backends/rvf/SolverBandit.d.ts +0 -100
  816. package/dist/src/backends/rvf/SolverBandit.d.ts.map +0 -1
  817. package/dist/src/backends/rvf/SolverBandit.js +0 -216
  818. package/dist/src/backends/rvf/SolverBandit.js.map +0 -1
  819. package/dist/src/backends/rvf/SonaLearningBackend.d.ts +0 -157
  820. package/dist/src/backends/rvf/SonaLearningBackend.d.ts.map +0 -1
  821. package/dist/src/backends/rvf/SonaLearningBackend.js +0 -283
  822. package/dist/src/backends/rvf/SonaLearningBackend.js.map +0 -1
  823. package/dist/src/backends/rvf/SqlJsRvfBackend.d.ts +0 -77
  824. package/dist/src/backends/rvf/SqlJsRvfBackend.d.ts.map +0 -1
  825. package/dist/src/backends/rvf/SqlJsRvfBackend.js +0 -382
  826. package/dist/src/backends/rvf/SqlJsRvfBackend.js.map +0 -1
  827. package/dist/src/backends/rvf/WasmStoreBridge.d.ts +0 -27
  828. package/dist/src/backends/rvf/WasmStoreBridge.d.ts.map +0 -1
  829. package/dist/src/backends/rvf/WasmStoreBridge.js +0 -87
  830. package/dist/src/backends/rvf/WasmStoreBridge.js.map +0 -1
  831. package/dist/src/backends/rvf/validation.d.ts +0 -20
  832. package/dist/src/backends/rvf/validation.d.ts.map +0 -1
  833. package/dist/src/backends/rvf/validation.js +0 -78
  834. package/dist/src/backends/rvf/validation.js.map +0 -1
  835. package/dist/src/benchmark/BenchmarkSuite.d.ts +0 -318
  836. package/dist/src/benchmark/BenchmarkSuite.d.ts.map +0 -1
  837. package/dist/src/benchmark/BenchmarkSuite.js +0 -986
  838. package/dist/src/benchmark/BenchmarkSuite.js.map +0 -1
  839. package/dist/src/benchmark/index.d.ts +0 -29
  840. package/dist/src/benchmark/index.d.ts.map +0 -1
  841. package/dist/src/benchmark/index.js +0 -39
  842. package/dist/src/benchmark/index.js.map +0 -1
  843. package/dist/src/cli/commands/hyperbolic.d.ts +0 -11
  844. package/dist/src/cli/commands/hyperbolic.d.ts.map +0 -1
  845. package/dist/src/cli/commands/hyperbolic.js +0 -428
  846. package/dist/src/cli/commands/hyperbolic.js.map +0 -1
  847. package/dist/src/cli/commands/learn.d.ts +0 -11
  848. package/dist/src/cli/commands/learn.d.ts.map +0 -1
  849. package/dist/src/cli/commands/learn.js +0 -404
  850. package/dist/src/cli/commands/learn.js.map +0 -1
  851. package/dist/src/cli/commands/route.d.ts +0 -11
  852. package/dist/src/cli/commands/route.d.ts.map +0 -1
  853. package/dist/src/cli/commands/route.js +0 -414
  854. package/dist/src/cli/commands/route.js.map +0 -1
  855. package/dist/src/cli/commands/rvf.d.ts +0 -21
  856. package/dist/src/cli/commands/rvf.d.ts.map +0 -1
  857. package/dist/src/cli/commands/rvf.js +0 -448
  858. package/dist/src/cli/commands/rvf.js.map +0 -1
  859. package/dist/src/cli/tests/agentdb-cli.test.d.ts +0 -8
  860. package/dist/src/cli/tests/agentdb-cli.test.d.ts.map +0 -1
  861. package/dist/src/cli/tests/agentdb-cli.test.js +0 -50
  862. package/dist/src/cli/tests/agentdb-cli.test.js.map +0 -1
  863. package/dist/src/cli/tests/attention-cli.test.d.ts +0 -5
  864. package/dist/src/cli/tests/attention-cli.test.d.ts.map +0 -1
  865. package/dist/src/cli/tests/attention-cli.test.js +0 -257
  866. package/dist/src/cli/tests/attention-cli.test.js.map +0 -1
  867. package/dist/src/compatibility/DeprecationWarnings.d.ts +0 -54
  868. package/dist/src/compatibility/DeprecationWarnings.d.ts.map +0 -1
  869. package/dist/src/compatibility/DeprecationWarnings.js +0 -131
  870. package/dist/src/compatibility/DeprecationWarnings.js.map +0 -1
  871. package/dist/src/compatibility/MigrationUtilities.d.ts +0 -30
  872. package/dist/src/compatibility/MigrationUtilities.d.ts.map +0 -1
  873. package/dist/src/compatibility/MigrationUtilities.js +0 -184
  874. package/dist/src/compatibility/MigrationUtilities.js.map +0 -1
  875. package/dist/src/compatibility/V1toV2Adapter.d.ts +0 -76
  876. package/dist/src/compatibility/V1toV2Adapter.d.ts.map +0 -1
  877. package/dist/src/compatibility/V1toV2Adapter.js +0 -198
  878. package/dist/src/compatibility/V1toV2Adapter.js.map +0 -1
  879. package/dist/src/compatibility/VersionDetector.d.ts +0 -32
  880. package/dist/src/compatibility/VersionDetector.d.ts.map +0 -1
  881. package/dist/src/compatibility/VersionDetector.js +0 -144
  882. package/dist/src/compatibility/VersionDetector.js.map +0 -1
  883. package/dist/src/compatibility/index.d.ts +0 -11
  884. package/dist/src/compatibility/index.d.ts.map +0 -1
  885. package/dist/src/compatibility/index.js +0 -10
  886. package/dist/src/compatibility/index.js.map +0 -1
  887. package/dist/src/compatibility/types.d.ts +0 -103
  888. package/dist/src/compatibility/types.d.ts.map +0 -1
  889. package/dist/src/compatibility/types.js +0 -5
  890. package/dist/src/compatibility/types.js.map +0 -1
  891. package/dist/src/controllers/MemoryController.d.ts +0 -161
  892. package/dist/src/controllers/MemoryController.d.ts.map +0 -1
  893. package/dist/src/controllers/MemoryController.js +0 -290
  894. package/dist/src/controllers/MemoryController.js.map +0 -1
  895. package/dist/src/controllers/attention/CrossAttentionController.d.ts +0 -141
  896. package/dist/src/controllers/attention/CrossAttentionController.d.ts.map +0 -1
  897. package/dist/src/controllers/attention/CrossAttentionController.js +0 -325
  898. package/dist/src/controllers/attention/CrossAttentionController.js.map +0 -1
  899. package/dist/src/controllers/attention/MultiHeadAttentionController.d.ts +0 -137
  900. package/dist/src/controllers/attention/MultiHeadAttentionController.d.ts.map +0 -1
  901. package/dist/src/controllers/attention/MultiHeadAttentionController.js +0 -339
  902. package/dist/src/controllers/attention/MultiHeadAttentionController.js.map +0 -1
  903. package/dist/src/controllers/attention/SelfAttentionController.d.ts +0 -117
  904. package/dist/src/controllers/attention/SelfAttentionController.d.ts.map +0 -1
  905. package/dist/src/controllers/attention/SelfAttentionController.js +0 -205
  906. package/dist/src/controllers/attention/SelfAttentionController.js.map +0 -1
  907. package/dist/src/controllers/attention/index.d.ts +0 -15
  908. package/dist/src/controllers/attention/index.d.ts.map +0 -1
  909. package/dist/src/controllers/attention/index.js +0 -12
  910. package/dist/src/controllers/attention/index.js.map +0 -1
  911. package/dist/src/core/QueryCache.d.ts +0 -138
  912. package/dist/src/core/QueryCache.d.ts.map +0 -1
  913. package/dist/src/core/QueryCache.js +0 -313
  914. package/dist/src/core/QueryCache.js.map +0 -1
  915. package/dist/src/observability/index.d.ts +0 -8
  916. package/dist/src/observability/index.d.ts.map +0 -1
  917. package/dist/src/observability/index.js +0 -8
  918. package/dist/src/observability/index.js.map +0 -1
  919. package/dist/src/observability/integration.d.ts +0 -32
  920. package/dist/src/observability/integration.d.ts.map +0 -1
  921. package/dist/src/observability/integration.js +0 -157
  922. package/dist/src/observability/integration.js.map +0 -1
  923. package/dist/src/observability/telemetry.d.ts +0 -137
  924. package/dist/src/observability/telemetry.d.ts.map +0 -1
  925. package/dist/src/observability/telemetry.js +0 -420
  926. package/dist/src/observability/telemetry.js.map +0 -1
  927. package/dist/src/quantization/index.d.ts +0 -7
  928. package/dist/src/quantization/index.d.ts.map +0 -1
  929. package/dist/src/quantization/index.js +0 -15
  930. package/dist/src/quantization/index.js.map +0 -1
  931. package/dist/src/quantization/vector-quantization.d.ts +0 -388
  932. package/dist/src/quantization/vector-quantization.d.ts.map +0 -1
  933. package/dist/src/quantization/vector-quantization.js +0 -1136
  934. package/dist/src/quantization/vector-quantization.js.map +0 -1
  935. package/dist/src/search/HybridSearch.d.ts +0 -311
  936. package/dist/src/search/HybridSearch.d.ts.map +0 -1
  937. package/dist/src/search/HybridSearch.js +0 -712
  938. package/dist/src/search/HybridSearch.js.map +0 -1
  939. package/dist/src/search/index.d.ts +0 -12
  940. package/dist/src/search/index.d.ts.map +0 -1
  941. package/dist/src/search/index.js +0 -16
  942. package/dist/src/search/index.js.map +0 -1
  943. package/dist/src/services/AttentionService.d.ts +0 -303
  944. package/dist/src/services/AttentionService.d.ts.map +0 -1
  945. package/dist/src/services/AttentionService.js +0 -1167
  946. package/dist/src/services/AttentionService.js.map +0 -1
  947. package/dist/src/simd/index.d.ts +0 -9
  948. package/dist/src/simd/index.d.ts.map +0 -1
  949. package/dist/src/simd/index.js +0 -27
  950. package/dist/src/simd/index.js.map +0 -1
  951. package/dist/src/simd/simd-vector-ops.d.ts +0 -332
  952. package/dist/src/simd/simd-vector-ops.d.ts.map +0 -1
  953. package/dist/src/simd/simd-vector-ops.js +0 -947
  954. package/dist/src/simd/simd-vector-ops.js.map +0 -1
  955. package/dist/src/tests/attention-service.test.d.ts +0 -7
  956. package/dist/src/tests/attention-service.test.d.ts.map +0 -1
  957. package/dist/src/tests/attention-service.test.js +0 -401
  958. package/dist/src/tests/attention-service.test.js.map +0 -1
  959. package/dist/src/tests/integration/compatibility/backwards-compat.integration.test.d.ts +0 -7
  960. package/dist/src/tests/integration/compatibility/backwards-compat.integration.test.d.ts.map +0 -1
  961. package/dist/src/tests/integration/compatibility/backwards-compat.integration.test.js +0 -283
  962. package/dist/src/tests/integration/compatibility/backwards-compat.integration.test.js.map +0 -1
  963. package/dist/src/tests/query-cache.test.d.ts +0 -7
  964. package/dist/src/tests/query-cache.test.d.ts.map +0 -1
  965. package/dist/src/tests/query-cache.test.js +0 -343
  966. package/dist/src/tests/query-cache.test.js.map +0 -1
  967. package/dist/src/tests/ruvector-integration.test.d.ts +0 -14
  968. package/dist/src/tests/ruvector-integration.test.d.ts.map +0 -1
  969. package/dist/src/tests/ruvector-integration.test.js +0 -1156
  970. package/dist/src/tests/ruvector-integration.test.js.map +0 -1
  971. package/dist/src/tests/unit/auth/crypto.utils.test.d.ts +0 -6
  972. package/dist/src/tests/unit/auth/crypto.utils.test.d.ts.map +0 -1
  973. package/dist/src/tests/unit/auth/crypto.utils.test.js +0 -310
  974. package/dist/src/tests/unit/auth/crypto.utils.test.js.map +0 -1
  975. package/dist/src/tests/unit/compatibility/deprecation-warnings.test.d.ts +0 -5
  976. package/dist/src/tests/unit/compatibility/deprecation-warnings.test.d.ts.map +0 -1
  977. package/dist/src/tests/unit/compatibility/deprecation-warnings.test.js +0 -207
  978. package/dist/src/tests/unit/compatibility/deprecation-warnings.test.js.map +0 -1
  979. package/dist/src/tests/unit/compatibility/migration-utils.test.d.ts +0 -5
  980. package/dist/src/tests/unit/compatibility/migration-utils.test.d.ts.map +0 -1
  981. package/dist/src/tests/unit/compatibility/migration-utils.test.js +0 -264
  982. package/dist/src/tests/unit/compatibility/migration-utils.test.js.map +0 -1
  983. package/dist/src/tests/unit/compatibility/v1-adapter.test.d.ts +0 -7
  984. package/dist/src/tests/unit/compatibility/v1-adapter.test.d.ts.map +0 -1
  985. package/dist/src/tests/unit/compatibility/v1-adapter.test.js +0 -228
  986. package/dist/src/tests/unit/compatibility/v1-adapter.test.js.map +0 -1
  987. package/dist/src/tests/unit/compatibility/version-detector.test.d.ts +0 -10
  988. package/dist/src/tests/unit/compatibility/version-detector.test.d.ts.map +0 -1
  989. package/dist/src/tests/unit/compatibility/version-detector.test.js +0 -162
  990. package/dist/src/tests/unit/compatibility/version-detector.test.js.map +0 -1
  991. package/dist/src/tests/vector-quantization.test.d.ts +0 -5
  992. package/dist/src/tests/vector-quantization.test.d.ts.map +0 -1
  993. package/dist/src/tests/vector-quantization.test.js +0 -338
  994. package/dist/src/tests/vector-quantization.test.js.map +0 -1
  995. package/dist/src/tests/wasm-vector-search.test.d.ts +0 -7
  996. package/dist/src/tests/wasm-vector-search.test.d.ts.map +0 -1
  997. package/dist/src/tests/wasm-vector-search.test.js +0 -193
  998. package/dist/src/tests/wasm-vector-search.test.js.map +0 -1
  999. package/dist/src/types/database.types.d.ts +0 -275
  1000. package/dist/src/types/database.types.d.ts.map +0 -1
  1001. package/dist/src/types/database.types.js +0 -57
  1002. package/dist/src/types/database.types.js.map +0 -1
  1003. package/dist/src/utils/chalk-fallback.d.ts +0 -3
  1004. package/dist/src/utils/chalk-fallback.d.ts.map +0 -1
  1005. package/dist/src/utils/chalk-fallback.js +0 -20
  1006. package/dist/src/utils/chalk-fallback.js.map +0 -1
  1007. package/dist/src/utils/crypto.utils.d.ts +0 -122
  1008. package/dist/src/utils/crypto.utils.d.ts.map +0 -1
  1009. package/dist/src/utils/crypto.utils.js +0 -296
  1010. package/dist/src/utils/crypto.utils.js.map +0 -1
  1011. package/dist/src/utils/similarity.d.ts +0 -11
  1012. package/dist/src/utils/similarity.d.ts.map +0 -1
  1013. package/dist/src/utils/similarity.js +0 -25
  1014. package/dist/src/utils/similarity.js.map +0 -1
  1015. package/dist/src/wasm-loader.d.ts +0 -67
  1016. package/dist/src/wasm-loader.d.ts.map +0 -1
  1017. package/dist/src/wasm-loader.js +0 -78
  1018. package/dist/src/wasm-loader.js.map +0 -1
  1019. package/dist/src/wrappers/agentdb-fast.d.ts +0 -139
  1020. package/dist/src/wrappers/agentdb-fast.d.ts.map +0 -1
  1021. package/dist/src/wrappers/agentdb-fast.js +0 -316
  1022. package/dist/src/wrappers/agentdb-fast.js.map +0 -1
  1023. package/dist/src/wrappers/attention-fallbacks.d.ts +0 -351
  1024. package/dist/src/wrappers/attention-fallbacks.d.ts.map +0 -1
  1025. package/dist/src/wrappers/attention-fallbacks.js +0 -1487
  1026. package/dist/src/wrappers/attention-fallbacks.js.map +0 -1
  1027. package/dist/src/wrappers/embedding-service.d.ts +0 -117
  1028. package/dist/src/wrappers/embedding-service.d.ts.map +0 -1
  1029. package/dist/src/wrappers/embedding-service.js +0 -376
  1030. package/dist/src/wrappers/embedding-service.js.map +0 -1
  1031. package/dist/src/wrappers/gnn-wrapper.d.ts +0 -71
  1032. package/dist/src/wrappers/gnn-wrapper.d.ts.map +0 -1
  1033. package/dist/src/wrappers/gnn-wrapper.js +0 -240
  1034. package/dist/src/wrappers/gnn-wrapper.js.map +0 -1
  1035. package/dist/src/wrappers/index.d.ts +0 -48
  1036. package/dist/src/wrappers/index.d.ts.map +0 -1
  1037. package/dist/src/wrappers/index.js +0 -83
  1038. package/dist/src/wrappers/index.js.map +0 -1
@@ -0,0 +1,2318 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * AgentDB MCP Server
4
+ * Production-ready MCP server for Claude Desktop integration
5
+ * Exposes AgentDB frontier memory features + core vector DB operations via MCP protocol
6
+ */
7
+
8
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
9
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
10
+ import {
11
+ CallToolRequestSchema,
12
+ ListToolsRequestSchema,
13
+ } from '@modelcontextprotocol/sdk/types.js';
14
+ // Database type from db-fallback
15
+ type Database = any;
16
+ import { createDatabase } from '../db-fallback.js';
17
+ import { CausalMemoryGraph } from '../controllers/CausalMemoryGraph.js';
18
+ import { CausalRecall } from '../controllers/CausalRecall.js';
19
+ import { ReflexionMemory } from '../controllers/ReflexionMemory.js';
20
+ import { SkillLibrary } from '../controllers/SkillLibrary.js';
21
+ import { NightlyLearner } from '../controllers/NightlyLearner.js';
22
+ import { LearningSystem } from '../controllers/LearningSystem.js';
23
+ import { EmbeddingService } from '../controllers/EmbeddingService.js';
24
+ import { BatchOperations } from '../optimizations/BatchOperations.js';
25
+ import { ReasoningBank } from '../controllers/ReasoningBank.js';
26
+ import { MCPToolCaches } from '../optimizations/ToolCache.js';
27
+ import {
28
+ validateId,
29
+ validateTimestamp,
30
+ validateSessionId,
31
+ validateTaskString,
32
+ validateNumericRange,
33
+ validateArrayLength,
34
+ validateObject,
35
+ validateBoolean,
36
+ validateEnum,
37
+ ValidationError,
38
+ handleSecurityError,
39
+ } from '../security/input-validation.js';
40
+ import * as path from 'path';
41
+ import * as fs from 'fs';
42
+ import { fileURLToPath } from 'url';
43
+ import { dirname } from 'path';
44
+
45
+ // ES module equivalent of __dirname
46
+ const __filename = fileURLToPath(import.meta.url);
47
+ const __dirname = dirname(__filename);
48
+
49
+ // ============================================================================
50
+ // Helper Functions for Core Vector DB Operations
51
+ // ============================================================================
52
+
53
+ /**
54
+ * Initialize database schema
55
+ */
56
+ function initializeSchema(database: any): void {
57
+ const db = database;
58
+ // Episodes table (vector store)
59
+ db.exec(`
60
+ CREATE TABLE IF NOT EXISTS episodes (
61
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
62
+ ts INTEGER DEFAULT (strftime('%s', 'now')),
63
+ session_id TEXT NOT NULL,
64
+ task TEXT NOT NULL,
65
+ input TEXT,
66
+ output TEXT,
67
+ critique TEXT,
68
+ reward REAL NOT NULL,
69
+ success INTEGER NOT NULL,
70
+ latency_ms INTEGER,
71
+ tokens_used INTEGER,
72
+ tags TEXT,
73
+ metadata TEXT
74
+ );
75
+
76
+ CREATE INDEX IF NOT EXISTS idx_episodes_session ON episodes(session_id);
77
+ CREATE INDEX IF NOT EXISTS idx_episodes_task ON episodes(task);
78
+ CREATE INDEX IF NOT EXISTS idx_episodes_reward ON episodes(reward);
79
+ CREATE INDEX IF NOT EXISTS idx_episodes_success ON episodes(success);
80
+ `);
81
+
82
+ // Episode embeddings (vector storage)
83
+ db.exec(`
84
+ CREATE TABLE IF NOT EXISTS episode_embeddings (
85
+ episode_id INTEGER PRIMARY KEY,
86
+ embedding BLOB NOT NULL,
87
+ FOREIGN KEY (episode_id) REFERENCES episodes(id) ON DELETE CASCADE
88
+ );
89
+ `);
90
+
91
+ // Skills table
92
+ db.exec(`
93
+ CREATE TABLE IF NOT EXISTS skills (
94
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
95
+ ts INTEGER DEFAULT (strftime('%s', 'now')),
96
+ name TEXT UNIQUE NOT NULL,
97
+ description TEXT NOT NULL,
98
+ signature TEXT,
99
+ code TEXT,
100
+ success_rate REAL DEFAULT 0.0,
101
+ uses INTEGER DEFAULT 0,
102
+ avg_reward REAL DEFAULT 0.0,
103
+ avg_latency_ms REAL DEFAULT 0.0,
104
+ tags TEXT,
105
+ metadata TEXT
106
+ );
107
+
108
+ CREATE INDEX IF NOT EXISTS idx_skills_success_rate ON skills(success_rate);
109
+ `);
110
+
111
+ // Skill embeddings
112
+ db.exec(`
113
+ CREATE TABLE IF NOT EXISTS skill_embeddings (
114
+ skill_id INTEGER PRIMARY KEY,
115
+ embedding BLOB NOT NULL,
116
+ FOREIGN KEY (skill_id) REFERENCES skills(id) ON DELETE CASCADE
117
+ );
118
+ `);
119
+
120
+ // Causal edges table
121
+ db.exec(`
122
+ CREATE TABLE IF NOT EXISTS causal_edges (
123
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
124
+ ts INTEGER DEFAULT (strftime('%s', 'now')),
125
+ from_memory_id INTEGER NOT NULL,
126
+ from_memory_type TEXT NOT NULL,
127
+ to_memory_id INTEGER NOT NULL,
128
+ to_memory_type TEXT NOT NULL,
129
+ similarity REAL DEFAULT 0.0,
130
+ uplift REAL NOT NULL,
131
+ confidence REAL DEFAULT 0.95,
132
+ sample_size INTEGER DEFAULT 0,
133
+ evidence_ids TEXT,
134
+ experiment_ids TEXT,
135
+ confounder_score REAL DEFAULT 0.0,
136
+ mechanism TEXT,
137
+ metadata TEXT
138
+ );
139
+
140
+ CREATE INDEX IF NOT EXISTS idx_causal_from ON causal_edges(from_memory_id, from_memory_type);
141
+ CREATE INDEX IF NOT EXISTS idx_causal_to ON causal_edges(to_memory_id, to_memory_type);
142
+ CREATE INDEX IF NOT EXISTS idx_causal_uplift ON causal_edges(uplift);
143
+ `);
144
+
145
+ // Causal experiments
146
+ db.exec(`
147
+ CREATE TABLE IF NOT EXISTS causal_experiments (
148
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
149
+ ts INTEGER DEFAULT (strftime('%s', 'now')),
150
+ intervention_id INTEGER NOT NULL,
151
+ control_outcome REAL NOT NULL,
152
+ treatment_outcome REAL NOT NULL,
153
+ uplift REAL NOT NULL,
154
+ sample_size INTEGER DEFAULT 1,
155
+ metadata TEXT
156
+ );
157
+ `);
158
+
159
+ // Causal observations
160
+ db.exec(`
161
+ CREATE TABLE IF NOT EXISTS causal_observations (
162
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
163
+ ts INTEGER DEFAULT (strftime('%s', 'now')),
164
+ action TEXT NOT NULL,
165
+ outcome TEXT NOT NULL,
166
+ reward REAL NOT NULL,
167
+ session_id TEXT,
168
+ metadata TEXT
169
+ );
170
+ `);
171
+
172
+ // Provenance certificates
173
+ db.exec(`
174
+ CREATE TABLE IF NOT EXISTS provenance_certificates (
175
+ id TEXT PRIMARY KEY,
176
+ ts INTEGER DEFAULT (strftime('%s', 'now')),
177
+ query_id TEXT NOT NULL,
178
+ agent_id TEXT NOT NULL,
179
+ query_text TEXT NOT NULL,
180
+ retrieval_method TEXT NOT NULL,
181
+ source_ids TEXT NOT NULL,
182
+ certificate_hash TEXT NOT NULL,
183
+ metadata TEXT
184
+ );
185
+ `);
186
+ }
187
+
188
+ /**
189
+ * Serialize embedding to BLOB
190
+ */
191
+ function serializeEmbedding(embedding: Float32Array): Buffer {
192
+ return Buffer.from(embedding.buffer);
193
+ }
194
+
195
+ /**
196
+ * Deserialize embedding from BLOB
197
+ */
198
+ function deserializeEmbedding(blob: Buffer): Float32Array {
199
+ return new Float32Array(blob.buffer, blob.byteOffset, blob.byteLength / 4);
200
+ }
201
+
202
+ /**
203
+ * Calculate cosine similarity between two vectors
204
+ */
205
+ function cosineSimilarity(a: Float32Array, b: Float32Array): number {
206
+ if (a.length !== b.length) {
207
+ throw new Error('Vectors must have same length');
208
+ }
209
+
210
+ let dotProduct = 0;
211
+ let normA = 0;
212
+ let normB = 0;
213
+
214
+ for (let i = 0; i < a.length; i++) {
215
+ dotProduct += a[i] * b[i];
216
+ normA += a[i] * a[i];
217
+ normB += b[i] * b[i];
218
+ }
219
+
220
+ return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
221
+ }
222
+
223
+ // ============================================================================
224
+ // Initialize Database and Controllers
225
+ // ============================================================================
226
+ const dbPath = process.env.AGENTDB_PATH || './agentdb.db';
227
+ const db = await createDatabase(dbPath);
228
+
229
+ // Configure for performance
230
+ db.pragma('journal_mode = WAL');
231
+ db.pragma('synchronous = NORMAL');
232
+ db.pragma('cache_size = -64000');
233
+
234
+ // Initialize schema automatically on server start using SQL files
235
+ const schemaPath = path.join(__dirname, '../schemas/schema.sql');
236
+ const frontierSchemaPath = path.join(__dirname, '../schemas/frontier-schema.sql');
237
+
238
+ try {
239
+ if (fs.existsSync(schemaPath)) {
240
+ const schemaSQL = fs.readFileSync(schemaPath, 'utf-8');
241
+ db.exec(schemaSQL);
242
+ console.error('āœ… Main schema loaded');
243
+ }
244
+
245
+ if (fs.existsSync(frontierSchemaPath)) {
246
+ const frontierSQL = fs.readFileSync(frontierSchemaPath, 'utf-8');
247
+ db.exec(frontierSQL);
248
+ console.error('āœ… Frontier schema loaded');
249
+ }
250
+
251
+ console.error('āœ… Database schema initialized');
252
+ } catch (error) {
253
+ console.error('āš ļø Schema initialization failed, using fallback:', (error as Error).message);
254
+ // Fallback to initializeSchema function if SQL files not found
255
+ initializeSchema(db);
256
+ }
257
+
258
+ // Initialize embedding service
259
+ const embeddingService = new EmbeddingService({
260
+ model: 'Xenova/all-MiniLM-L6-v2',
261
+ dimension: 384,
262
+ provider: 'transformers'
263
+ });
264
+ await embeddingService.initialize();
265
+
266
+ // Initialize all controllers
267
+ const causalGraph = new CausalMemoryGraph(db);
268
+ const reflexion = new ReflexionMemory(db, embeddingService);
269
+ const skills = new SkillLibrary(db, embeddingService);
270
+ const causalRecall = new CausalRecall(db, embeddingService);
271
+ const learner = new NightlyLearner(db, embeddingService);
272
+ const learningSystem = new LearningSystem(db, embeddingService);
273
+ const batchOps = new BatchOperations(db, embeddingService);
274
+ const reasoningBank = new ReasoningBank(db, embeddingService);
275
+ const caches = new MCPToolCaches();
276
+
277
+ // ============================================================================
278
+ // MCP Server Setup
279
+ // ============================================================================
280
+ const server = new Server(
281
+ {
282
+ name: 'agentdb',
283
+ version: '1.3.0',
284
+ },
285
+ {
286
+ capabilities: {
287
+ tools: {},
288
+ },
289
+ }
290
+ );
291
+
292
+ // ============================================================================
293
+ // Tool Definitions
294
+ // ============================================================================
295
+ const tools = [
296
+ // ==========================================================================
297
+ // CORE VECTOR DB OPERATIONS (NEW)
298
+ // ==========================================================================
299
+ {
300
+ name: 'agentdb_init',
301
+ description: 'Initialize AgentDB database with schema and optimizations. Creates all required tables for vector storage, causal memory, skills, and provenance tracking.',
302
+ inputSchema: {
303
+ type: 'object',
304
+ properties: {
305
+ db_path: { type: 'string', description: 'Database file path (optional, defaults to ./agentdb.db)', default: './agentdb.db' },
306
+ reset: { type: 'boolean', description: 'Reset database (delete existing)', default: false },
307
+ },
308
+ },
309
+ },
310
+ {
311
+ name: 'agentdb_insert',
312
+ description: 'Insert a single vector with metadata into AgentDB. Automatically generates embeddings for the provided text.',
313
+ inputSchema: {
314
+ type: 'object',
315
+ properties: {
316
+ text: { type: 'string', description: 'Text content to embed and store' },
317
+ metadata: { type: 'object', description: 'Additional metadata (JSON object)' },
318
+ session_id: { type: 'string', description: 'Session identifier', default: 'default' },
319
+ tags: { type: 'array', items: { type: 'string' }, description: 'Tags for categorization' },
320
+ },
321
+ required: ['text'],
322
+ },
323
+ },
324
+ {
325
+ name: 'agentdb_insert_batch',
326
+ description: 'Batch insert multiple vectors efficiently using transactions and parallel embedding generation. Optimized for large datasets.',
327
+ inputSchema: {
328
+ type: 'object',
329
+ properties: {
330
+ items: {
331
+ type: 'array',
332
+ items: {
333
+ type: 'object',
334
+ properties: {
335
+ text: { type: 'string', description: 'Text content to embed' },
336
+ metadata: { type: 'object', description: 'Metadata (JSON)' },
337
+ session_id: { type: 'string', description: 'Session ID' },
338
+ tags: { type: 'array', items: { type: 'string' } },
339
+ },
340
+ required: ['text'],
341
+ },
342
+ description: 'Array of items to insert',
343
+ },
344
+ batch_size: { type: 'number', description: 'Batch size for processing', default: 100 },
345
+ },
346
+ required: ['items'],
347
+ },
348
+ },
349
+ {
350
+ name: 'agentdb_search',
351
+ description: 'Semantic k-NN vector search using cosine similarity. Returns the most relevant results ranked by similarity score.',
352
+ inputSchema: {
353
+ type: 'object',
354
+ properties: {
355
+ query: { type: 'string', description: 'Search query text' },
356
+ k: { type: 'number', description: 'Number of results to return', default: 10 },
357
+ min_similarity: { type: 'number', description: 'Minimum similarity threshold (0-1)', default: 0.0 },
358
+ filters: {
359
+ type: 'object',
360
+ properties: {
361
+ session_id: { type: 'string', description: 'Filter by session ID' },
362
+ tags: { type: 'array', items: { type: 'string' }, description: 'Filter by tags' },
363
+ min_reward: { type: 'number', description: 'Minimum reward threshold' },
364
+ },
365
+ description: 'Optional filters',
366
+ },
367
+ },
368
+ required: ['query'],
369
+ },
370
+ },
371
+ {
372
+ name: 'agentdb_delete',
373
+ description: 'Delete vector(s) from AgentDB by ID or filters. Supports single ID deletion or bulk deletion with conditions.',
374
+ inputSchema: {
375
+ type: 'object',
376
+ properties: {
377
+ id: { type: 'number', description: 'Specific vector ID to delete' },
378
+ filters: {
379
+ type: 'object',
380
+ properties: {
381
+ session_id: { type: 'string', description: 'Delete all vectors with this session ID' },
382
+ before_timestamp: { type: 'number', description: 'Delete vectors before this Unix timestamp' },
383
+ },
384
+ description: 'Bulk deletion filters (used if id not provided)',
385
+ },
386
+ },
387
+ },
388
+ },
389
+
390
+ // ==========================================================================
391
+ // FRONTIER MEMORY FEATURES (EXISTING)
392
+ // ==========================================================================
393
+ {
394
+ name: 'reflexion_store',
395
+ description: 'Store an episode with self-critique for reflexion-based learning',
396
+ inputSchema: {
397
+ type: 'object',
398
+ properties: {
399
+ session_id: { type: 'string', description: 'Session identifier' },
400
+ task: { type: 'string', description: 'Task description' },
401
+ reward: { type: 'number', description: 'Task reward (0-1)' },
402
+ success: { type: 'boolean', description: 'Whether task succeeded' },
403
+ critique: { type: 'string', description: 'Self-critique reflection' },
404
+ input: { type: 'string', description: 'Task input' },
405
+ output: { type: 'string', description: 'Task output' },
406
+ latency_ms: { type: 'number', description: 'Execution latency' },
407
+ tokens: { type: 'number', description: 'Tokens used' },
408
+ },
409
+ required: ['session_id', 'task', 'reward', 'success'],
410
+ },
411
+ },
412
+ {
413
+ name: 'reflexion_retrieve',
414
+ description: 'Retrieve relevant past episodes for learning from experience',
415
+ inputSchema: {
416
+ type: 'object',
417
+ properties: {
418
+ task: { type: 'string', description: 'Task to find similar episodes for' },
419
+ k: { type: 'number', description: 'Number of episodes to retrieve', default: 5 },
420
+ only_failures: { type: 'boolean', description: 'Only retrieve failures' },
421
+ only_successes: { type: 'boolean', description: 'Only retrieve successes' },
422
+ min_reward: { type: 'number', description: 'Minimum reward threshold' },
423
+ },
424
+ required: ['task'],
425
+ },
426
+ },
427
+ {
428
+ name: 'skill_create',
429
+ description: 'Create a reusable skill in the skill library',
430
+ inputSchema: {
431
+ type: 'object',
432
+ properties: {
433
+ name: { type: 'string', description: 'Skill name' },
434
+ description: { type: 'string', description: 'What the skill does' },
435
+ code: { type: 'string', description: 'Skill implementation code' },
436
+ success_rate: { type: 'number', description: 'Initial success rate' },
437
+ },
438
+ required: ['name', 'description'],
439
+ },
440
+ },
441
+ {
442
+ name: 'skill_search',
443
+ description: 'Search for applicable skills by semantic similarity',
444
+ inputSchema: {
445
+ type: 'object',
446
+ properties: {
447
+ task: { type: 'string', description: 'Task to find skills for' },
448
+ k: { type: 'number', description: 'Number of skills to return', default: 10 },
449
+ min_success_rate: { type: 'number', description: 'Minimum success rate filter' },
450
+ },
451
+ required: ['task'],
452
+ },
453
+ },
454
+ {
455
+ name: 'causal_add_edge',
456
+ description: 'Add a causal relationship between actions and outcomes',
457
+ inputSchema: {
458
+ type: 'object',
459
+ properties: {
460
+ cause: { type: 'string', description: 'Causal action/intervention' },
461
+ effect: { type: 'string', description: 'Observed effect/outcome' },
462
+ uplift: { type: 'number', description: 'Causal uplift magnitude' },
463
+ confidence: { type: 'number', description: 'Confidence in causal claim (0-1)', default: 0.95 },
464
+ sample_size: { type: 'number', description: 'Number of observations', default: 0 },
465
+ },
466
+ required: ['cause', 'effect', 'uplift'],
467
+ },
468
+ },
469
+ {
470
+ name: 'causal_query',
471
+ description: 'Query causal effects to understand what actions cause what outcomes',
472
+ inputSchema: {
473
+ type: 'object',
474
+ properties: {
475
+ cause: { type: 'string', description: 'Filter by cause (optional)' },
476
+ effect: { type: 'string', description: 'Filter by effect (optional)' },
477
+ min_confidence: { type: 'number', description: 'Minimum confidence', default: 0.5 },
478
+ min_uplift: { type: 'number', description: 'Minimum uplift', default: 0.0 },
479
+ limit: { type: 'number', description: 'Maximum results', default: 10 },
480
+ },
481
+ },
482
+ },
483
+ {
484
+ name: 'recall_with_certificate',
485
+ description: 'Retrieve memories with causal utility scoring and provenance certificate',
486
+ inputSchema: {
487
+ type: 'object',
488
+ properties: {
489
+ query: { type: 'string', description: 'Query for memory retrieval' },
490
+ k: { type: 'number', description: 'Number of results', default: 12 },
491
+ alpha: { type: 'number', description: 'Similarity weight', default: 0.7 },
492
+ beta: { type: 'number', description: 'Causal uplift weight', default: 0.2 },
493
+ gamma: { type: 'number', description: 'Recency weight', default: 0.1 },
494
+ },
495
+ required: ['query'],
496
+ },
497
+ },
498
+ {
499
+ name: 'learner_discover',
500
+ description: 'Automatically discover causal patterns from episode history',
501
+ inputSchema: {
502
+ type: 'object',
503
+ properties: {
504
+ min_attempts: { type: 'number', description: 'Minimum attempts required', default: 3 },
505
+ min_success_rate: { type: 'number', description: 'Minimum success rate', default: 0.6 },
506
+ min_confidence: { type: 'number', description: 'Minimum statistical confidence', default: 0.7 },
507
+ dry_run: { type: 'boolean', description: 'Preview without storing', default: false },
508
+ },
509
+ },
510
+ },
511
+ {
512
+ name: 'db_stats',
513
+ description: 'Get database statistics showing record counts',
514
+ inputSchema: {
515
+ type: 'object',
516
+ properties: {},
517
+ },
518
+ },
519
+
520
+ // ==========================================================================
521
+ // LEARNING SYSTEM TOOLS (v1.3.0 - Tools 1-5)
522
+ // ==========================================================================
523
+ {
524
+ name: 'learning_start_session',
525
+ description: 'Start a new reinforcement learning session with specified algorithm and configuration. Supports 9 RL algorithms: q-learning, sarsa, dqn, policy-gradient, actor-critic, ppo, decision-transformer, mcts, model-based.',
526
+ inputSchema: {
527
+ type: 'object',
528
+ properties: {
529
+ user_id: { type: 'string', description: 'User identifier for the learning session' },
530
+ session_type: {
531
+ type: 'string',
532
+ description: 'RL algorithm type',
533
+ enum: ['q-learning', 'sarsa', 'dqn', 'policy-gradient', 'actor-critic', 'ppo', 'decision-transformer', 'mcts', 'model-based'],
534
+ },
535
+ config: {
536
+ type: 'object',
537
+ description: 'Learning configuration parameters',
538
+ properties: {
539
+ learning_rate: { type: 'number', description: 'Learning rate (0-1)', default: 0.01 },
540
+ discount_factor: { type: 'number', description: 'Discount factor gamma (0-1)', default: 0.99 },
541
+ exploration_rate: { type: 'number', description: 'Epsilon for epsilon-greedy exploration (0-1)', default: 0.1 },
542
+ batch_size: { type: 'number', description: 'Batch size for training', default: 32 },
543
+ target_update_frequency: { type: 'number', description: 'Update frequency for target network', default: 100 },
544
+ },
545
+ required: ['learning_rate', 'discount_factor'],
546
+ },
547
+ },
548
+ required: ['user_id', 'session_type', 'config'],
549
+ },
550
+ },
551
+ {
552
+ name: 'learning_end_session',
553
+ description: 'End an active learning session and save the final trained policy to the database.',
554
+ inputSchema: {
555
+ type: 'object',
556
+ properties: {
557
+ session_id: { type: 'string', description: 'Session ID to end' },
558
+ },
559
+ required: ['session_id'],
560
+ },
561
+ },
562
+ {
563
+ name: 'learning_predict',
564
+ description: 'Get AI-recommended action for a given state with confidence scores and alternative actions.',
565
+ inputSchema: {
566
+ type: 'object',
567
+ properties: {
568
+ session_id: { type: 'string', description: 'Learning session ID' },
569
+ state: { type: 'string', description: 'Current state description' },
570
+ },
571
+ required: ['session_id', 'state'],
572
+ },
573
+ },
574
+ {
575
+ name: 'learning_feedback',
576
+ description: 'Submit feedback on action quality to train the RL policy. Feedback includes reward signal and outcome state.',
577
+ inputSchema: {
578
+ type: 'object',
579
+ properties: {
580
+ session_id: { type: 'string', description: 'Learning session ID' },
581
+ state: { type: 'string', description: 'State where action was taken' },
582
+ action: { type: 'string', description: 'Action that was executed' },
583
+ reward: { type: 'number', description: 'Reward received (higher is better)' },
584
+ next_state: { type: 'string', description: 'Resulting state after action (optional)' },
585
+ success: { type: 'boolean', description: 'Whether the action was successful' },
586
+ },
587
+ required: ['session_id', 'state', 'action', 'reward', 'success'],
588
+ },
589
+ },
590
+ {
591
+ name: 'learning_train',
592
+ description: 'Train the RL policy using batch learning with collected experiences. Returns training metrics including loss, average reward, and convergence rate.',
593
+ inputSchema: {
594
+ type: 'object',
595
+ properties: {
596
+ session_id: { type: 'string', description: 'Learning session ID to train' },
597
+ epochs: { type: 'number', description: 'Number of training epochs', default: 50 },
598
+ batch_size: { type: 'number', description: 'Batch size for training', default: 32 },
599
+ learning_rate: { type: 'number', description: 'Learning rate for this training run', default: 0.01 },
600
+ },
601
+ required: ['session_id'],
602
+ },
603
+ },
604
+
605
+ // ==========================================================================
606
+ // LEARNING SYSTEM TOOLS (v1.4.0 - Tools 6-10)
607
+ // ==========================================================================
608
+ {
609
+ name: 'learning_metrics',
610
+ description: 'Get learning performance metrics including success rates, rewards, and policy improvement',
611
+ inputSchema: {
612
+ type: 'object',
613
+ properties: {
614
+ session_id: { type: 'string', description: 'Optional session ID to filter metrics' },
615
+ time_window_days: { type: 'number', description: 'Time window in days for metrics (default: 7)', default: 7 },
616
+ include_trends: { type: 'boolean', description: 'Include trend analysis over time', default: true },
617
+ group_by: { type: 'string', description: 'Group metrics by task/session/skill', enum: ['task', 'session', 'skill'], default: 'task' },
618
+ },
619
+ },
620
+ },
621
+ {
622
+ name: 'learning_transfer',
623
+ description: 'Transfer learning between sessions or tasks, enabling knowledge reuse across different contexts',
624
+ inputSchema: {
625
+ type: 'object',
626
+ properties: {
627
+ source_session: { type: 'string', description: 'Source session ID to transfer from' },
628
+ target_session: { type: 'string', description: 'Target session ID to transfer to' },
629
+ source_task: { type: 'string', description: 'Source task pattern to transfer from' },
630
+ target_task: { type: 'string', description: 'Target task pattern to transfer to' },
631
+ min_similarity: { type: 'number', description: 'Minimum similarity threshold (0-1)', default: 0.7, minimum: 0, maximum: 1 },
632
+ transfer_type: { type: 'string', description: 'Type of transfer', enum: ['episodes', 'skills', 'causal_edges', 'all'], default: 'all' },
633
+ max_transfers: { type: 'number', description: 'Maximum number of items to transfer', default: 10 },
634
+ },
635
+ },
636
+ },
637
+ {
638
+ name: 'learning_explain',
639
+ description: 'Explain action recommendations with confidence scores and supporting evidence from past experiences',
640
+ inputSchema: {
641
+ type: 'object',
642
+ properties: {
643
+ query: { type: 'string', description: 'Query or task description to get recommendations for' },
644
+ k: { type: 'number', description: 'Number of recommendations to return', default: 5 },
645
+ explain_depth: { type: 'string', description: 'Explanation detail level', enum: ['summary', 'detailed', 'full'], default: 'detailed' },
646
+ include_confidence: { type: 'boolean', description: 'Include confidence scores', default: true },
647
+ include_evidence: { type: 'boolean', description: 'Include supporting evidence from past episodes', default: true },
648
+ include_causal: { type: 'boolean', description: 'Include causal reasoning chains', default: true },
649
+ },
650
+ required: ['query'],
651
+ },
652
+ },
653
+ {
654
+ name: 'experience_record',
655
+ description: 'Record tool execution as experience for reinforcement learning and experience replay',
656
+ inputSchema: {
657
+ type: 'object',
658
+ properties: {
659
+ session_id: { type: 'string', description: 'Session identifier' },
660
+ tool_name: { type: 'string', description: 'Name of the tool executed' },
661
+ action: { type: 'string', description: 'Action taken or tool parameters' },
662
+ state_before: { type: 'object', description: 'System state before action (JSON)' },
663
+ state_after: { type: 'object', description: 'System state after action (JSON)' },
664
+ outcome: { type: 'string', description: 'Outcome description' },
665
+ reward: { type: 'number', description: 'Reward signal (0-1)', minimum: 0, maximum: 1 },
666
+ success: { type: 'boolean', description: 'Whether the action succeeded' },
667
+ latency_ms: { type: 'number', description: 'Execution latency in milliseconds' },
668
+ metadata: { type: 'object', description: 'Additional metadata (JSON)' },
669
+ },
670
+ required: ['session_id', 'tool_name', 'action', 'outcome', 'reward', 'success'],
671
+ },
672
+ },
673
+ {
674
+ name: 'reward_signal',
675
+ description: 'Calculate reward signal for outcomes based on success, efficiency, and causal impact',
676
+ inputSchema: {
677
+ type: 'object',
678
+ properties: {
679
+ episode_id: { type: 'number', description: 'Episode ID to calculate reward for' },
680
+ success: { type: 'boolean', description: 'Whether the outcome was successful' },
681
+ target_achieved: { type: 'boolean', description: 'Whether the target was achieved', default: true },
682
+ efficiency_score: { type: 'number', description: 'Efficiency score (0-1)', default: 0.5, minimum: 0, maximum: 1 },
683
+ quality_score: { type: 'number', description: 'Quality score (0-1)', default: 0.5, minimum: 0, maximum: 1 },
684
+ time_taken_ms: { type: 'number', description: 'Time taken in milliseconds' },
685
+ expected_time_ms: { type: 'number', description: 'Expected time in milliseconds' },
686
+ include_causal: { type: 'boolean', description: 'Include causal impact in reward', default: true },
687
+ reward_function: { type: 'string', description: 'Reward function to use', enum: ['standard', 'sparse', 'dense', 'shaped'], default: 'standard' },
688
+ },
689
+ required: ['success'],
690
+ },
691
+ },
692
+
693
+ // ==========================================================================
694
+ // CORE AGENTDB TOOLS (6-10) - v1.3.0
695
+ // ==========================================================================
696
+ {
697
+ name: 'agentdb_stats',
698
+ description: 'Get comprehensive database statistics including table counts, storage usage, and performance metrics',
699
+ inputSchema: {
700
+ type: 'object',
701
+ properties: {
702
+ detailed: { type: 'boolean', description: 'Include detailed statistics', default: false },
703
+ },
704
+ },
705
+ },
706
+ {
707
+ name: 'agentdb_pattern_store',
708
+ description: 'Store reasoning pattern with embedding, taskType, approach, and successRate',
709
+ inputSchema: {
710
+ type: 'object',
711
+ properties: {
712
+ taskType: { type: 'string', description: 'Type of task (e.g., "code_review", "data_analysis")' },
713
+ approach: { type: 'string', description: 'Description of the reasoning approach' },
714
+ successRate: { type: 'number', description: 'Success rate (0-1)', default: 0.0 },
715
+ tags: { type: 'array', items: { type: 'string' }, description: 'Optional tags' },
716
+ metadata: { type: 'object', description: 'Additional metadata' },
717
+ },
718
+ required: ['taskType', 'approach', 'successRate'],
719
+ },
720
+ },
721
+ {
722
+ name: 'agentdb_pattern_search',
723
+ description: 'Search patterns with taskEmbedding, k, threshold, and filters',
724
+ inputSchema: {
725
+ type: 'object',
726
+ properties: {
727
+ task: { type: 'string', description: 'Task description to search for' },
728
+ k: { type: 'number', description: 'Number of results to return', default: 10 },
729
+ threshold: { type: 'number', description: 'Minimum similarity threshold (0-1)', default: 0.0 },
730
+ filters: {
731
+ type: 'object',
732
+ properties: {
733
+ taskType: { type: 'string', description: 'Filter by task type' },
734
+ minSuccessRate: { type: 'number', description: 'Minimum success rate' },
735
+ tags: { type: 'array', items: { type: 'string' }, description: 'Filter by tags' },
736
+ },
737
+ description: 'Optional filters',
738
+ },
739
+ },
740
+ required: ['task'],
741
+ },
742
+ },
743
+ {
744
+ name: 'agentdb_pattern_stats',
745
+ description: 'Get pattern statistics including total patterns, success rates, and top task types',
746
+ inputSchema: {
747
+ type: 'object',
748
+ properties: {},
749
+ },
750
+ },
751
+ {
752
+ name: 'agentdb_clear_cache',
753
+ description: 'Clear query cache to refresh statistics and search results',
754
+ inputSchema: {
755
+ type: 'object',
756
+ properties: {
757
+ cache_type: {
758
+ type: 'string',
759
+ description: 'Type of cache to clear (all, patterns, stats)',
760
+ enum: ['all', 'patterns', 'stats'],
761
+ default: 'all'
762
+ },
763
+ },
764
+ },
765
+ },
766
+
767
+ // ==========================================================================
768
+ // BATCH OPERATION TOOLS (v2.0 MCP Optimization - Phase 2)
769
+ // ==========================================================================
770
+ {
771
+ name: 'skill_create_batch',
772
+ description: 'Batch create multiple skills efficiently using transactions and parallel embedding generation. 3x faster than sequential skill_create calls (304 → 900 ops/sec). šŸ”„ PARALLEL-SAFE: Can be used alongside other batch operations.',
773
+ inputSchema: {
774
+ type: 'object',
775
+ properties: {
776
+ skills: {
777
+ type: 'array',
778
+ items: {
779
+ type: 'object',
780
+ properties: {
781
+ name: { type: 'string', description: 'Skill name (unique)' },
782
+ description: { type: 'string', description: 'What the skill does' },
783
+ signature: { type: 'object', description: 'Optional function signature' },
784
+ code: { type: 'string', description: 'Skill implementation code' },
785
+ success_rate: { type: 'number', description: 'Initial success rate (0-1)', default: 0.0 },
786
+ uses: { type: 'number', description: 'Initial use count', default: 0 },
787
+ avg_reward: { type: 'number', description: 'Average reward', default: 0.0 },
788
+ avg_latency_ms: { type: 'number', description: 'Average latency', default: 0.0 },
789
+ tags: { type: 'array', items: { type: 'string' }, description: 'Tags for categorization' },
790
+ metadata: { type: 'object', description: 'Additional metadata (JSON)' },
791
+ },
792
+ required: ['name', 'description'],
793
+ },
794
+ description: 'Array of skills to create',
795
+ minItems: 1,
796
+ maxItems: 100,
797
+ },
798
+ batch_size: { type: 'number', description: 'Batch size for processing (default: 32)', default: 32 },
799
+ format: {
800
+ type: 'string',
801
+ enum: ['concise', 'detailed', 'json'],
802
+ description: 'Response format (default: concise)',
803
+ default: 'concise',
804
+ },
805
+ },
806
+ required: ['skills'],
807
+ },
808
+ },
809
+ {
810
+ name: 'reflexion_store_batch',
811
+ description: 'Batch store multiple episodes efficiently using transactions and parallel embedding generation. 3.3x faster than sequential reflexion_store calls (152 → 500 ops/sec). šŸ”„ PARALLEL-SAFE: Can be used alongside other batch operations.',
812
+ inputSchema: {
813
+ type: 'object',
814
+ properties: {
815
+ episodes: {
816
+ type: 'array',
817
+ items: {
818
+ type: 'object',
819
+ properties: {
820
+ session_id: { type: 'string', description: 'Session identifier' },
821
+ task: { type: 'string', description: 'Task description' },
822
+ reward: { type: 'number', description: 'Task reward (0-1)' },
823
+ success: { type: 'boolean', description: 'Whether task succeeded' },
824
+ critique: { type: 'string', description: 'Self-critique reflection' },
825
+ input: { type: 'string', description: 'Task input' },
826
+ output: { type: 'string', description: 'Task output' },
827
+ latency_ms: { type: 'number', description: 'Execution latency' },
828
+ tokens: { type: 'number', description: 'Tokens used' },
829
+ tags: { type: 'array', items: { type: 'string' }, description: 'Tags' },
830
+ metadata: { type: 'object', description: 'Additional metadata' },
831
+ },
832
+ required: ['session_id', 'task', 'reward', 'success'],
833
+ },
834
+ description: 'Array of episodes to store',
835
+ minItems: 1,
836
+ maxItems: 1000,
837
+ },
838
+ batch_size: { type: 'number', description: 'Batch size for processing (default: 100)', default: 100 },
839
+ format: {
840
+ type: 'string',
841
+ enum: ['concise', 'detailed', 'json'],
842
+ description: 'Response format (default: concise)',
843
+ default: 'concise',
844
+ },
845
+ },
846
+ required: ['episodes'],
847
+ },
848
+ },
849
+ {
850
+ name: 'agentdb_pattern_store_batch',
851
+ description: 'Batch store multiple reasoning patterns efficiently using transactions and parallel embedding generation. 4x faster than sequential agentdb_pattern_store calls. šŸ”„ PARALLEL-SAFE: Can be used alongside other batch operations.',
852
+ inputSchema: {
853
+ type: 'object',
854
+ properties: {
855
+ patterns: {
856
+ type: 'array',
857
+ items: {
858
+ type: 'object',
859
+ properties: {
860
+ taskType: { type: 'string', description: 'Type of task (e.g., "code_review", "data_analysis")' },
861
+ approach: { type: 'string', description: 'Description of the reasoning approach' },
862
+ successRate: { type: 'number', description: 'Success rate (0-1)' },
863
+ tags: { type: 'array', items: { type: 'string' }, description: 'Optional tags' },
864
+ metadata: { type: 'object', description: 'Additional metadata' },
865
+ },
866
+ required: ['taskType', 'approach', 'successRate'],
867
+ },
868
+ description: 'Array of reasoning patterns to store',
869
+ minItems: 1,
870
+ maxItems: 500,
871
+ },
872
+ batch_size: { type: 'number', description: 'Batch size for processing (default: 50)', default: 50 },
873
+ format: {
874
+ type: 'string',
875
+ enum: ['concise', 'detailed', 'json'],
876
+ description: 'Response format (default: concise)',
877
+ default: 'concise',
878
+ },
879
+ },
880
+ required: ['patterns'],
881
+ },
882
+ },
883
+ ];
884
+
885
+ // ============================================================================
886
+ // Tool Handlers
887
+ // ============================================================================
888
+ server.setRequestHandler(ListToolsRequestSchema, async () => {
889
+ return { tools };
890
+ });
891
+
892
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
893
+ const { name, arguments: args } = request.params;
894
+
895
+ try {
896
+ switch (name) {
897
+ // ======================================================================
898
+ // CORE VECTOR DB OPERATIONS
899
+ // ======================================================================
900
+ case 'agentdb_init': {
901
+ const targetDbPath = (args?.db_path as string) || dbPath;
902
+
903
+ if (args?.reset && fs.existsSync(targetDbPath)) {
904
+ fs.unlinkSync(targetDbPath);
905
+ }
906
+
907
+ // Initialize schema
908
+ initializeSchema(db);
909
+
910
+ const stats = db.prepare('SELECT COUNT(*) as count FROM sqlite_master WHERE type="table"').get() as any;
911
+
912
+ return {
913
+ content: [
914
+ {
915
+ type: 'text',
916
+ text: `āœ… AgentDB initialized successfully!\n` +
917
+ `šŸ“ Database: ${targetDbPath}\n` +
918
+ `šŸ“Š Tables created: ${stats.count}\n` +
919
+ `āš™ļø Optimizations: WAL mode, cache_size=64MB\n` +
920
+ `🧠 Embedding service: ${embeddingService.constructor.name} ready`,
921
+ },
922
+ ],
923
+ };
924
+ }
925
+
926
+ case 'agentdb_insert': {
927
+ const text = args?.text as string;
928
+ const sessionId = (args?.session_id as string) || 'default';
929
+ const tags = (args?.tags as string[]) || [];
930
+ const metadata = (args?.metadata as Record<string, any>) || {};
931
+
932
+ const episodeId = await reflexion.storeEpisode({
933
+ sessionId,
934
+ task: text,
935
+ reward: 1.0,
936
+ success: true,
937
+ input: text,
938
+ output: '',
939
+ critique: '',
940
+ latencyMs: 0,
941
+ tokensUsed: 0,
942
+ tags,
943
+ metadata,
944
+ });
945
+
946
+ return {
947
+ content: [
948
+ {
949
+ type: 'text',
950
+ text: `āœ… Vector inserted successfully!\n` +
951
+ `šŸ†” ID: ${episodeId}\n` +
952
+ `šŸ“ Text: ${text.substring(0, 100)}${text.length > 100 ? '...' : ''}\n` +
953
+ `šŸ·ļø Tags: ${tags.join(', ') || 'none'}\n` +
954
+ `🧠 Embedding: ${embeddingService.constructor.name}`,
955
+ },
956
+ ],
957
+ };
958
+ }
959
+
960
+ case 'agentdb_insert_batch': {
961
+ const items = (args?.items as any[]) || [];
962
+ const batchSize = (args?.batch_size as number) || 100;
963
+
964
+ const episodes = items.map((item: any) => ({
965
+ sessionId: item.session_id || 'default',
966
+ task: item.text,
967
+ reward: 1.0,
968
+ success: true,
969
+ input: item.text,
970
+ output: '',
971
+ critique: '',
972
+ latencyMs: 0,
973
+ tokensUsed: 0,
974
+ tags: item.tags || [],
975
+ metadata: item.metadata || {},
976
+ }));
977
+
978
+ const batchOpsConfig = new BatchOperations(db, embeddingService, {
979
+ batchSize,
980
+ parallelism: 4,
981
+ });
982
+
983
+ const inserted = await batchOpsConfig.insertEpisodes(episodes);
984
+
985
+ return {
986
+ content: [
987
+ {
988
+ type: 'text',
989
+ text: `āœ… Batch insert completed!\n` +
990
+ `šŸ“Š Inserted: ${inserted} vectors\n` +
991
+ `⚔ Batch size: ${batchSize}\n` +
992
+ `🧠 Embeddings generated in parallel\n` +
993
+ `šŸ’¾ Transaction committed`,
994
+ },
995
+ ],
996
+ };
997
+ }
998
+
999
+ case 'agentdb_search': {
1000
+ const queryText = args?.query as string;
1001
+ const k = (args?.k as number) || 10;
1002
+ const minSimilarity = (args?.min_similarity as number) || 0.0;
1003
+ const filters = args?.filters as any;
1004
+
1005
+ const query: any = {
1006
+ task: queryText,
1007
+ k,
1008
+ };
1009
+
1010
+ if (filters) {
1011
+ if (filters.min_reward !== undefined) {
1012
+ query.minReward = filters.min_reward;
1013
+ }
1014
+ // Session ID filter would require custom query
1015
+ }
1016
+
1017
+ const results = await reflexion.retrieveRelevant(query);
1018
+
1019
+ // Filter by minimum similarity if specified
1020
+ let filteredResults = results;
1021
+ if (minSimilarity > 0) {
1022
+ filteredResults = results.filter(r => (r.similarity || 0) >= minSimilarity);
1023
+ }
1024
+
1025
+ return {
1026
+ content: [
1027
+ {
1028
+ type: 'text',
1029
+ text: `šŸ” Search completed!\n` +
1030
+ `šŸ“Š Found: ${filteredResults.length} results\n` +
1031
+ `šŸŽÆ Query: ${queryText}\n\n` +
1032
+ `Top Results:\n` +
1033
+ filteredResults.slice(0, 5).map((r, i) =>
1034
+ `${i + 1}. [ID: ${r.id}] Similarity: ${(r.similarity || 0).toFixed(3)}\n` +
1035
+ ` Task: ${r.task.substring(0, 80)}${r.task.length > 80 ? '...' : ''}\n` +
1036
+ ` Reward: ${r.reward.toFixed(2)}`
1037
+ ).join('\n\n') +
1038
+ (filteredResults.length > 5 ? `\n\n... and ${filteredResults.length - 5} more results` : ''),
1039
+ },
1040
+ ],
1041
+ };
1042
+ }
1043
+
1044
+ case 'agentdb_delete': {
1045
+ let deleted = 0;
1046
+ const id = args?.id as number | undefined;
1047
+ const filters = args?.filters as any;
1048
+
1049
+ try {
1050
+ if (id !== undefined) {
1051
+ // Validate ID
1052
+ const validatedId = validateId(id, 'id');
1053
+
1054
+ // Delete single vector using parameterized query
1055
+ const stmt = db.prepare('DELETE FROM episodes WHERE id = ?');
1056
+ const result = stmt.run(validatedId);
1057
+ deleted = result.changes;
1058
+ } else if (filters) {
1059
+ // Bulk delete with validated filters
1060
+ if (filters.session_id) {
1061
+ // Validate session_id
1062
+ const validatedSessionId = validateSessionId(filters.session_id);
1063
+
1064
+ // Use parameterized query
1065
+ const stmt = db.prepare('DELETE FROM episodes WHERE session_id = ?');
1066
+ const result = stmt.run(validatedSessionId);
1067
+ deleted = result.changes;
1068
+ } else if (filters.before_timestamp) {
1069
+ // Validate timestamp
1070
+ const validatedTimestamp = validateTimestamp(filters.before_timestamp, 'before_timestamp');
1071
+
1072
+ // Use parameterized query
1073
+ const stmt = db.prepare('DELETE FROM episodes WHERE ts < ?');
1074
+ const result = stmt.run(validatedTimestamp);
1075
+ deleted = result.changes;
1076
+ } else {
1077
+ throw new ValidationError('Invalid or missing filter criteria', 'INVALID_FILTER');
1078
+ }
1079
+ } else {
1080
+ throw new ValidationError('Either id or filters must be provided', 'MISSING_PARAMETER');
1081
+ }
1082
+
1083
+ return {
1084
+ content: [
1085
+ {
1086
+ type: 'text',
1087
+ text: `āœ… Delete operation completed!\n` +
1088
+ `šŸ“Š Deleted: ${deleted} vector(s)\n` +
1089
+ `šŸ—‘ļø ${id !== undefined ? `ID: ${id}` : 'Bulk deletion with filters'}`,
1090
+ },
1091
+ ],
1092
+ };
1093
+ } catch (error: any) {
1094
+ const safeMessage = handleSecurityError(error);
1095
+ return {
1096
+ content: [
1097
+ {
1098
+ type: 'text',
1099
+ text: `āŒ Delete operation failed: ${safeMessage}`,
1100
+ },
1101
+ ],
1102
+ isError: true,
1103
+ };
1104
+ }
1105
+ }
1106
+
1107
+ // ======================================================================
1108
+ // FRONTIER MEMORY FEATURES (EXISTING)
1109
+ // ======================================================================
1110
+ case 'reflexion_store': {
1111
+ const episodeId = await reflexion.storeEpisode({
1112
+ sessionId: args?.session_id as string,
1113
+ task: args?.task as string,
1114
+ reward: args?.reward as number,
1115
+ success: args?.success as boolean,
1116
+ critique: (args?.critique as string) || '',
1117
+ input: (args?.input as string) || '',
1118
+ output: (args?.output as string) || '',
1119
+ latencyMs: (args?.latency_ms as number) || 0,
1120
+ tokensUsed: (args?.tokens as number) || 0,
1121
+ });
1122
+ return {
1123
+ content: [
1124
+ {
1125
+ type: 'text',
1126
+ text: `āœ… Stored episode #${episodeId}\nTask: ${args?.task}\nReward: ${args?.reward}\nSuccess: ${args?.success}`,
1127
+ },
1128
+ ],
1129
+ };
1130
+ }
1131
+
1132
+ case 'reflexion_retrieve': {
1133
+ const episodes = await reflexion.retrieveRelevant({
1134
+ task: args?.task as string,
1135
+ k: (args?.k as number) || 5,
1136
+ onlyFailures: args?.only_failures as boolean | undefined,
1137
+ onlySuccesses: args?.only_successes as boolean | undefined,
1138
+ minReward: args?.min_reward as number | undefined,
1139
+ });
1140
+ return {
1141
+ content: [
1142
+ {
1143
+ type: 'text',
1144
+ text: `šŸ” Retrieved ${episodes.length} episodes:\n\n` +
1145
+ episodes.map((ep, i) =>
1146
+ `${i + 1}. Episode ${ep.id}\n Task: ${ep.task}\n Reward: ${ep.reward.toFixed(2)}\n Similarity: ${ep.similarity?.toFixed(3) || 'N/A'}`
1147
+ ).join('\n\n'),
1148
+ },
1149
+ ],
1150
+ };
1151
+ }
1152
+
1153
+ case 'skill_create': {
1154
+ const skillId = await skills.createSkill({
1155
+ name: args?.name as string,
1156
+ description: args?.description as string,
1157
+ signature: { inputs: {}, outputs: {} },
1158
+ code: (args?.code as string) || '',
1159
+ successRate: (args?.success_rate as number) || 0.0,
1160
+ uses: 0,
1161
+ avgReward: 0.0,
1162
+ avgLatencyMs: 0.0,
1163
+ });
1164
+ return {
1165
+ content: [
1166
+ {
1167
+ type: 'text',
1168
+ text: `āœ… Created skill #${skillId}: ${args?.name}`,
1169
+ },
1170
+ ],
1171
+ };
1172
+ }
1173
+
1174
+ case 'skill_search': {
1175
+ const foundSkills = await skills.searchSkills({
1176
+ task: args?.task as string,
1177
+ k: (args?.k as number) || 10,
1178
+ minSuccessRate: (args?.min_success_rate as number) || 0.0,
1179
+ });
1180
+ return {
1181
+ content: [
1182
+ {
1183
+ type: 'text',
1184
+ text: `šŸ” Found ${foundSkills.length} skills:\n\n` +
1185
+ foundSkills.map((skill, i) =>
1186
+ `${i + 1}. ${skill.name}\n ${skill.description}\n Success: ${(skill.successRate * 100).toFixed(1)}%`
1187
+ ).join('\n\n'),
1188
+ },
1189
+ ],
1190
+ };
1191
+ }
1192
+
1193
+ case 'causal_add_edge': {
1194
+ const cause = args?.cause as string;
1195
+ const effect = args?.effect as string;
1196
+ const uplift = args?.uplift as number;
1197
+ const confidence = (args?.confidence as number) || 0.95;
1198
+ const sampleSize = (args?.sample_size as number) || 0;
1199
+
1200
+ const edgeId = causalGraph.addCausalEdge({
1201
+ fromMemoryId: 0,
1202
+ fromMemoryType: cause as 'episode' | 'skill' | 'note' | 'fact',
1203
+ toMemoryId: 0,
1204
+ toMemoryType: effect as 'episode' | 'skill' | 'note' | 'fact',
1205
+ similarity: 0,
1206
+ uplift,
1207
+ confidence,
1208
+ sampleSize,
1209
+ evidenceIds: [],
1210
+ });
1211
+ return {
1212
+ content: [
1213
+ {
1214
+ type: 'text',
1215
+ text: `āœ… Added causal edge #${edgeId}\n${cause} → ${effect}\nUplift: ${uplift}`,
1216
+ },
1217
+ ],
1218
+ };
1219
+ }
1220
+
1221
+ case 'causal_query': {
1222
+ const cause = args?.cause as string | undefined;
1223
+ const effect = args?.effect as string | undefined;
1224
+ const minConfidence = (args?.min_confidence as number) || 0.5;
1225
+ const minUplift = (args?.min_uplift as number) || 0.0;
1226
+ const limit = (args?.limit as number) || 10;
1227
+
1228
+ const edges = causalGraph.queryCausalEffects({
1229
+ interventionMemoryId: 0,
1230
+ interventionMemoryType: cause || '',
1231
+ outcomeMemoryId: effect ? 0 : undefined,
1232
+ minConfidence,
1233
+ minUplift,
1234
+ });
1235
+ const limited = edges.slice(0, limit);
1236
+ return {
1237
+ content: [
1238
+ {
1239
+ type: 'text',
1240
+ text: `šŸ” Found ${edges.length} causal edges:\n\n` +
1241
+ limited.map((edge, i) =>
1242
+ `${i + 1}. ${edge.fromMemoryType} → ${edge.toMemoryType}\n Uplift: ${(edge.uplift || 0).toFixed(3)} (confidence: ${edge.confidence.toFixed(2)})`
1243
+ ).join('\n\n'),
1244
+ },
1245
+ ],
1246
+ };
1247
+ }
1248
+
1249
+ case 'recall_with_certificate': {
1250
+ const query = args?.query as string;
1251
+ const k = (args?.k as number) || 12;
1252
+
1253
+ const result = await causalRecall.recall(
1254
+ 'mcp-' + Date.now(),
1255
+ query,
1256
+ k,
1257
+ undefined,
1258
+ 'internal'
1259
+ );
1260
+ return {
1261
+ content: [
1262
+ {
1263
+ type: 'text',
1264
+ text: `šŸ” Retrieved ${result.candidates.length} results:\n\n` +
1265
+ result.candidates.slice(0, 5).map((r, i) =>
1266
+ `${i + 1}. ${r.type} ${r.id}\n Similarity: ${r.similarity.toFixed(3)}\n Uplift: ${r.uplift?.toFixed(3) || '0.000'}`
1267
+ ).join('\n\n') +
1268
+ `\n\nšŸ“œ Certificate ID: ${result.certificate.id}`,
1269
+ },
1270
+ ],
1271
+ };
1272
+ }
1273
+
1274
+ case 'learner_discover': {
1275
+ const minAttempts = (args?.min_attempts as number) || 3;
1276
+ const minSuccessRate = (args?.min_success_rate as number) || 0.6;
1277
+ const minConfidence = (args?.min_confidence as number) || 0.7;
1278
+ const dryRun = (args?.dry_run as boolean) || false;
1279
+
1280
+ const discovered = await learner.discover({
1281
+ minAttempts,
1282
+ minSuccessRate,
1283
+ minConfidence,
1284
+ dryRun,
1285
+ });
1286
+ return {
1287
+ content: [
1288
+ {
1289
+ type: 'text',
1290
+ text: `šŸŒ™ Discovered ${discovered.length} causal patterns:\n\n` +
1291
+ discovered.slice(0, 10).map((edge, i) =>
1292
+ `${i + 1}. ${edge.fromMemoryType} → ${edge.toMemoryType}\n Uplift: ${(edge.uplift || 0).toFixed(3)} (n=${edge.sampleSize || 0})`
1293
+ ).join('\n\n'),
1294
+ },
1295
+ ],
1296
+ };
1297
+ }
1298
+
1299
+ case 'db_stats': {
1300
+ const stats: Record<string, number> = {
1301
+ causal_edges: (db.prepare('SELECT COUNT(*) as count FROM causal_edges').get() as any)?.count || 0,
1302
+ causal_experiments: (db.prepare('SELECT COUNT(*) as count FROM causal_experiments').get() as any)?.count || 0,
1303
+ causal_observations: (db.prepare('SELECT COUNT(*) as count FROM causal_observations').get() as any)?.count || 0,
1304
+ episodes: (db.prepare('SELECT COUNT(*) as count FROM episodes').get() as any)?.count || 0,
1305
+ episode_embeddings: (db.prepare('SELECT COUNT(*) as count FROM episode_embeddings').get() as any)?.count || 0,
1306
+ skills: (db.prepare('SELECT COUNT(*) as count FROM skills').get() as any)?.count || 0,
1307
+ };
1308
+ return {
1309
+ content: [
1310
+ {
1311
+ type: 'text',
1312
+ text: `šŸ“Š Database Statistics:\n\n` +
1313
+ `Causal Edges: ${stats.causal_edges}\n` +
1314
+ `Experiments: ${stats.causal_experiments}\n` +
1315
+ `Observations: ${stats.causal_observations}\n` +
1316
+ `Episodes (Vectors): ${stats.episodes}\n` +
1317
+ `Episode Embeddings: ${stats.episode_embeddings}\n` +
1318
+ `Skills: ${stats.skills}`,
1319
+ },
1320
+ ],
1321
+ };
1322
+ }
1323
+
1324
+ // ======================================================================
1325
+ // CORE AGENTDB TOOLS (6-10)
1326
+ // ======================================================================
1327
+ case 'agentdb_stats': {
1328
+ const detailed = (args?.detailed as boolean) || false;
1329
+
1330
+ // Check cache first (60s TTL)
1331
+ const cacheKey = `stats:${detailed ? 'detailed' : 'summary'}`;
1332
+ const cached = caches.stats.get(cacheKey);
1333
+ if (cached) {
1334
+ return {
1335
+ content: [
1336
+ {
1337
+ type: 'text',
1338
+ text: `${cached}\n\n⚔ (cached)`,
1339
+ },
1340
+ ],
1341
+ };
1342
+ }
1343
+
1344
+ // Helper to safely query table count
1345
+ const safeCount = (tableName: string): number => {
1346
+ try {
1347
+ return (db.prepare(`SELECT COUNT(*) as count FROM ${tableName}`).get() as any)?.count || 0;
1348
+ } catch {
1349
+ return 0; // Table doesn't exist
1350
+ }
1351
+ };
1352
+
1353
+ const stats: Record<string, number> = {
1354
+ causal_edges: safeCount('causal_edges'),
1355
+ causal_experiments: safeCount('causal_experiments'),
1356
+ causal_observations: safeCount('causal_observations'),
1357
+ episodes: safeCount('episodes'),
1358
+ episode_embeddings: safeCount('episode_embeddings'),
1359
+ skills: safeCount('skills'),
1360
+ skill_embeddings: safeCount('skill_embeddings'),
1361
+ reasoning_patterns: safeCount('reasoning_patterns'),
1362
+ pattern_embeddings: safeCount('pattern_embeddings'),
1363
+ learning_sessions: safeCount('rl_sessions'),
1364
+ };
1365
+
1366
+ let output = `šŸ“Š AgentDB Comprehensive Statistics\n\n` +
1367
+ `🧠 Memory & Learning:\n` +
1368
+ ` Episodes (Vectors): ${stats.episodes}\n` +
1369
+ ` Episode Embeddings: ${stats.episode_embeddings}\n` +
1370
+ ` Skills: ${stats.skills}\n` +
1371
+ ` Skill Embeddings: ${stats.skill_embeddings}\n` +
1372
+ ` Reasoning Patterns: ${stats.reasoning_patterns}\n` +
1373
+ ` Pattern Embeddings: ${stats.pattern_embeddings}\n` +
1374
+ ` Learning Sessions: ${stats.learning_sessions}\n\n` +
1375
+ `šŸ”— Causal Intelligence:\n` +
1376
+ ` Causal Edges: ${stats.causal_edges}\n` +
1377
+ ` Experiments: ${stats.causal_experiments}\n` +
1378
+ ` Observations: ${stats.causal_observations}\n`;
1379
+
1380
+ if (detailed) {
1381
+ // Add storage statistics
1382
+ const dbStats = db.prepare(`
1383
+ SELECT page_count * page_size as total_bytes
1384
+ FROM pragma_page_count(), pragma_page_size()
1385
+ `).get() as any;
1386
+
1387
+ const totalMB = (dbStats.total_bytes / (1024 * 1024)).toFixed(2);
1388
+
1389
+ // Add recent activity stats
1390
+ const recentActivity = db.prepare(`
1391
+ SELECT COUNT(*) as count
1392
+ FROM episodes
1393
+ WHERE ts >= strftime('%s', 'now', '-7 days')
1394
+ `).get() as any;
1395
+
1396
+ output += `\nšŸ“¦ Storage:\n` +
1397
+ ` Database Size: ${totalMB} MB\n` +
1398
+ ` Recent Activity (7d): ${recentActivity.count} episodes\n`;
1399
+ }
1400
+
1401
+ // Cache the result (60s TTL)
1402
+ caches.stats.set(cacheKey, output);
1403
+
1404
+ return {
1405
+ content: [
1406
+ {
1407
+ type: 'text',
1408
+ text: output,
1409
+ },
1410
+ ],
1411
+ };
1412
+ }
1413
+
1414
+ case 'agentdb_pattern_store': {
1415
+ const taskType = args?.taskType as string;
1416
+ const approach = args?.approach as string;
1417
+ const successRate = args?.successRate as number;
1418
+ const tags = (args?.tags as string[]) || [];
1419
+ const metadata = (args?.metadata as Record<string, any>) || {};
1420
+
1421
+ const patternId = await reasoningBank.storePattern({
1422
+ taskType,
1423
+ approach,
1424
+ successRate,
1425
+ tags,
1426
+ metadata,
1427
+ });
1428
+
1429
+ return {
1430
+ content: [
1431
+ {
1432
+ type: 'text',
1433
+ text: `āœ… Reasoning pattern stored successfully!\n\n` +
1434
+ `šŸ†” Pattern ID: ${patternId}\n` +
1435
+ `šŸ“‹ Task Type: ${taskType}\n` +
1436
+ `šŸ’” Approach: ${approach.substring(0, 100)}${approach.length > 100 ? '...' : ''}\n` +
1437
+ `šŸ“Š Success Rate: ${(successRate * 100).toFixed(1)}%\n` +
1438
+ `šŸ·ļø Tags: ${tags.join(', ') || 'none'}\n` +
1439
+ `🧠 Embedding generated and stored`,
1440
+ },
1441
+ ],
1442
+ };
1443
+ }
1444
+
1445
+ case 'agentdb_pattern_search': {
1446
+ const task = args?.task as string;
1447
+ const k = (args?.k as number) || 10;
1448
+ const threshold = (args?.threshold as number) || 0.0;
1449
+ const filters = args?.filters as any;
1450
+
1451
+ // Generate embedding for the task
1452
+ const taskEmbedding = await embeddingService.embed(task);
1453
+
1454
+ const patterns = await reasoningBank.searchPatterns({
1455
+ taskEmbedding,
1456
+ k,
1457
+ threshold,
1458
+ filters: filters ? {
1459
+ taskType: filters.taskType,
1460
+ minSuccessRate: filters.minSuccessRate,
1461
+ tags: filters.tags,
1462
+ } : undefined,
1463
+ });
1464
+
1465
+ return {
1466
+ content: [
1467
+ {
1468
+ type: 'text',
1469
+ text: `šŸ” Pattern search completed!\n\n` +
1470
+ `šŸ“Š Found: ${patterns.length} matching patterns\n` +
1471
+ `šŸŽÆ Query: ${task}\n` +
1472
+ `šŸŽšļø Threshold: ${threshold.toFixed(2)}\n\n` +
1473
+ `Top Results:\n` +
1474
+ patterns.slice(0, 5).map((p, i) =>
1475
+ `${i + 1}. [ID: ${p.id}] ${p.taskType}\n` +
1476
+ ` Similarity: ${(p.similarity || 0).toFixed(3)}\n` +
1477
+ ` Success Rate: ${(p.successRate * 100).toFixed(1)}%\n` +
1478
+ ` Approach: ${p.approach.substring(0, 80)}${p.approach.length > 80 ? '...' : ''}\n` +
1479
+ ` Uses: ${p.uses || 0}`
1480
+ ).join('\n\n') +
1481
+ (patterns.length > 5 ? `\n\n... and ${patterns.length - 5} more patterns` : ''),
1482
+ },
1483
+ ],
1484
+ };
1485
+ }
1486
+
1487
+ case 'agentdb_pattern_stats': {
1488
+ // Check cache first (60s TTL)
1489
+ const cacheKey = 'pattern_stats';
1490
+ const cached = caches.stats.get(cacheKey);
1491
+ if (cached) {
1492
+ return {
1493
+ content: [
1494
+ {
1495
+ type: 'text',
1496
+ text: `${cached}\n\n⚔ (cached)`,
1497
+ },
1498
+ ],
1499
+ };
1500
+ }
1501
+
1502
+ const stats = reasoningBank.getPatternStats();
1503
+
1504
+ const output = `šŸ“Š Reasoning Pattern Statistics\n\n` +
1505
+ `šŸ“ˆ Overview:\n` +
1506
+ ` Total Patterns: ${stats.totalPatterns}\n` +
1507
+ ` Avg Success Rate: ${(stats.avgSuccessRate * 100).toFixed(1)}%\n` +
1508
+ ` Avg Uses per Pattern: ${stats.avgUses.toFixed(1)}\n` +
1509
+ ` High Performing (≄80%): ${stats.highPerformingPatterns}\n` +
1510
+ ` Recent (7 days): ${stats.recentPatterns}\n\n` +
1511
+ `šŸ† Top Task Types:\n` +
1512
+ stats.topTaskTypes.slice(0, 10).map((tt, i) =>
1513
+ ` ${i + 1}. ${tt.taskType}: ${tt.count} patterns`
1514
+ ).join('\n') +
1515
+ (stats.topTaskTypes.length === 0 ? ' No patterns stored yet' : '');
1516
+
1517
+ // Cache the result (60s TTL)
1518
+ caches.stats.set(cacheKey, output);
1519
+
1520
+ return {
1521
+ content: [
1522
+ {
1523
+ type: 'text',
1524
+ text: output,
1525
+ },
1526
+ ],
1527
+ };
1528
+ }
1529
+
1530
+ case 'agentdb_clear_cache': {
1531
+ const cacheType = (args?.cache_type as string) || 'all';
1532
+
1533
+ let cleared = 0;
1534
+
1535
+ switch (cacheType) {
1536
+ case 'patterns':
1537
+ cleared += caches.patterns.clear();
1538
+ reasoningBank.clearCache();
1539
+ break;
1540
+ case 'stats':
1541
+ cleared += caches.stats.clear();
1542
+ cleared += caches.metrics.clear();
1543
+ break;
1544
+ case 'all':
1545
+ caches.clearAll();
1546
+ reasoningBank.clearCache();
1547
+ cleared = -1; // All cleared
1548
+ break;
1549
+ }
1550
+
1551
+ return {
1552
+ content: [
1553
+ {
1554
+ type: 'text',
1555
+ text: `āœ… Cache cleared successfully!\n\n` +
1556
+ `🧹 Cache Type: ${cacheType}\n` +
1557
+ `ā™»ļø ${cleared === -1 ? 'All caches' : `${cleared} cache entries`} cleared\n` +
1558
+ `šŸ“Š Statistics and search results will be refreshed on next query`,
1559
+ },
1560
+ ],
1561
+ };
1562
+ }
1563
+
1564
+ // ======================================================================
1565
+ // BATCH OPERATION TOOLS (v2.0 MCP Optimization - Phase 2)
1566
+ // ======================================================================
1567
+ case 'skill_create_batch': {
1568
+ try {
1569
+ // Validate inputs
1570
+ const skillsArray = validateArrayLength(args?.skills, 'skills', 1, 100);
1571
+ const batchSize = args?.batch_size ? validateNumericRange(args.batch_size, 'batch_size', 1, 100) : 32;
1572
+ const format = args?.format ? validateEnum(args.format, 'format', ['concise', 'detailed', 'json'] as const) : 'concise';
1573
+
1574
+ // Validate each skill
1575
+ const validatedSkills = skillsArray.map((skill: any, index: number) => {
1576
+ const name = validateTaskString(skill.name, `skills[${index}].name`);
1577
+ const description = validateTaskString(skill.description, `skills[${index}].description`);
1578
+ const successRate = skill.success_rate !== undefined
1579
+ ? validateNumericRange(skill.success_rate, `skills[${index}].success_rate`, 0, 1)
1580
+ : 0.0;
1581
+
1582
+ return {
1583
+ name,
1584
+ description,
1585
+ signature: skill.signature || { inputs: {}, outputs: {} },
1586
+ code: skill.code || '',
1587
+ successRate,
1588
+ uses: skill.uses || 0,
1589
+ avgReward: skill.avg_reward || 0.0,
1590
+ avgLatencyMs: skill.avg_latency_ms || 0.0,
1591
+ tags: skill.tags || [],
1592
+ metadata: skill.metadata || {},
1593
+ };
1594
+ });
1595
+
1596
+ // Use BatchOperations for efficient insertion
1597
+ const startTime = Date.now();
1598
+ const batchOpsConfig = new BatchOperations(db, embeddingService, {
1599
+ batchSize,
1600
+ parallelism: 4,
1601
+ });
1602
+
1603
+ const skillIds = await batchOpsConfig.insertSkills(validatedSkills);
1604
+ const duration = Date.now() - startTime;
1605
+
1606
+ // Format response
1607
+ if (format === 'json') {
1608
+ return {
1609
+ content: [
1610
+ {
1611
+ type: 'text',
1612
+ text: JSON.stringify({
1613
+ success: true,
1614
+ inserted: skillIds.length,
1615
+ skill_ids: skillIds,
1616
+ duration_ms: duration,
1617
+ batch_size: batchSize,
1618
+ }, null, 2),
1619
+ },
1620
+ ],
1621
+ };
1622
+ } else if (format === 'detailed') {
1623
+ return {
1624
+ content: [
1625
+ {
1626
+ type: 'text',
1627
+ text: `āœ… Batch skill creation completed!\n\n` +
1628
+ `šŸ“Š Performance:\n` +
1629
+ ` • Skills Created: ${skillIds.length}\n` +
1630
+ ` • Duration: ${duration}ms\n` +
1631
+ ` • Throughput: ${(skillIds.length / (duration / 1000)).toFixed(1)} skills/sec\n` +
1632
+ ` • Batch Size: ${batchSize}\n` +
1633
+ ` • Parallelism: 4 workers\n\n` +
1634
+ `šŸ†” Created Skill IDs:\n` +
1635
+ skillIds.slice(0, 10).map((id, i) =>
1636
+ ` ${i + 1}. Skill #${id}: ${validatedSkills[i].name}`
1637
+ ).join('\n') +
1638
+ (skillIds.length > 10 ? `\n ... and ${skillIds.length - 10} more skills` : '') +
1639
+ `\n\n🧠 All embeddings generated in parallel\n` +
1640
+ `šŸ’¾ Transaction committed successfully`,
1641
+ },
1642
+ ],
1643
+ };
1644
+ } else {
1645
+ // Concise format (default)
1646
+ return {
1647
+ content: [
1648
+ {
1649
+ type: 'text',
1650
+ text: `āœ… Created ${skillIds.length} skills in ${duration}ms (${(skillIds.length / (duration / 1000)).toFixed(1)} skills/sec)`,
1651
+ },
1652
+ ],
1653
+ };
1654
+ }
1655
+ } catch (error: any) {
1656
+ const safeMessage = handleSecurityError(error);
1657
+ return {
1658
+ content: [
1659
+ {
1660
+ type: 'text',
1661
+ text: `āŒ Batch skill creation failed: ${safeMessage}\n\n` +
1662
+ `šŸ’” Troubleshooting:\n` +
1663
+ ` • Ensure all skills have unique names\n` +
1664
+ ` • Verify success_rate is between 0 and 1\n` +
1665
+ ` • Check that skills array has 1-100 items\n` +
1666
+ ` • Ensure descriptions are not empty`,
1667
+ },
1668
+ ],
1669
+ isError: true,
1670
+ };
1671
+ }
1672
+ }
1673
+
1674
+ case 'reflexion_store_batch': {
1675
+ try {
1676
+ // Validate inputs
1677
+ const episodesArray = validateArrayLength(args?.episodes, 'episodes', 1, 1000);
1678
+ const batchSize = args?.batch_size ? validateNumericRange(args.batch_size, 'batch_size', 1, 1000) : 100;
1679
+ const format = args?.format ? validateEnum(args.format, 'format', ['concise', 'detailed', 'json'] as const) : 'concise';
1680
+
1681
+ // Validate each episode
1682
+ const validatedEpisodes = episodesArray.map((ep: any, index: number) => {
1683
+ const sessionId = validateSessionId(ep.session_id);
1684
+ const task = validateTaskString(ep.task, `episodes[${index}].task`);
1685
+ const reward = validateNumericRange(ep.reward, `episodes[${index}].reward`, 0, 1);
1686
+ const success = validateBoolean(ep.success, `episodes[${index}].success`);
1687
+
1688
+ return {
1689
+ sessionId,
1690
+ task,
1691
+ reward,
1692
+ success,
1693
+ critique: ep.critique || '',
1694
+ input: ep.input || '',
1695
+ output: ep.output || '',
1696
+ latencyMs: ep.latency_ms || 0,
1697
+ tokensUsed: ep.tokens || 0,
1698
+ tags: ep.tags || [],
1699
+ metadata: ep.metadata || {},
1700
+ };
1701
+ });
1702
+
1703
+ // Use BatchOperations for efficient insertion
1704
+ const startTime = Date.now();
1705
+ const batchOpsConfig = new BatchOperations(db, embeddingService, {
1706
+ batchSize,
1707
+ parallelism: 4,
1708
+ });
1709
+
1710
+ const insertedCount = await batchOpsConfig.insertEpisodes(validatedEpisodes);
1711
+ const duration = Date.now() - startTime;
1712
+
1713
+ // Format response
1714
+ if (format === 'json') {
1715
+ return {
1716
+ content: [
1717
+ {
1718
+ type: 'text',
1719
+ text: JSON.stringify({
1720
+ success: true,
1721
+ inserted: insertedCount,
1722
+ duration_ms: duration,
1723
+ batch_size: batchSize,
1724
+ }, null, 2),
1725
+ },
1726
+ ],
1727
+ };
1728
+ } else if (format === 'detailed') {
1729
+ return {
1730
+ content: [
1731
+ {
1732
+ type: 'text',
1733
+ text: `āœ… Batch episode storage completed!\n\n` +
1734
+ `šŸ“Š Performance:\n` +
1735
+ ` • Episodes Stored: ${insertedCount}\n` +
1736
+ ` • Duration: ${duration}ms\n` +
1737
+ ` • Throughput: ${(insertedCount / (duration / 1000)).toFixed(1)} episodes/sec\n` +
1738
+ ` • Batch Size: ${batchSize}\n` +
1739
+ ` • Parallelism: 4 workers\n\n` +
1740
+ `šŸ“ˆ Statistics:\n` +
1741
+ ` • Sessions: ${new Set(validatedEpisodes.map(e => e.sessionId)).size}\n` +
1742
+ ` • Success Rate: ${(validatedEpisodes.filter(e => e.success).length / validatedEpisodes.length * 100).toFixed(1)}%\n` +
1743
+ ` • Avg Reward: ${(validatedEpisodes.reduce((sum, e) => sum + e.reward, 0) / validatedEpisodes.length).toFixed(3)}\n\n` +
1744
+ `🧠 All embeddings generated in parallel\n` +
1745
+ `šŸ’¾ Transaction committed successfully`,
1746
+ },
1747
+ ],
1748
+ };
1749
+ } else {
1750
+ // Concise format (default)
1751
+ return {
1752
+ content: [
1753
+ {
1754
+ type: 'text',
1755
+ text: `āœ… Stored ${insertedCount} episodes in ${duration}ms (${(insertedCount / (duration / 1000)).toFixed(1)} episodes/sec)`,
1756
+ },
1757
+ ],
1758
+ };
1759
+ }
1760
+ } catch (error: any) {
1761
+ const safeMessage = handleSecurityError(error);
1762
+ return {
1763
+ content: [
1764
+ {
1765
+ type: 'text',
1766
+ text: `āŒ Batch episode storage failed: ${safeMessage}\n\n` +
1767
+ `šŸ’” Troubleshooting:\n` +
1768
+ ` • Ensure all session_ids are valid (alphanumeric, hyphens, underscores)\n` +
1769
+ ` • Verify rewards are between 0 and 1\n` +
1770
+ ` • Check that episodes array has 1-1000 items\n` +
1771
+ ` • Ensure tasks are not empty or excessively long`,
1772
+ },
1773
+ ],
1774
+ isError: true,
1775
+ };
1776
+ }
1777
+ }
1778
+
1779
+ case 'agentdb_pattern_store_batch': {
1780
+ try {
1781
+ // Validate inputs
1782
+ const patternsArray = validateArrayLength(args?.patterns, 'patterns', 1, 500);
1783
+ const batchSize = args?.batch_size ? validateNumericRange(args.batch_size, 'batch_size', 1, 500) : 50;
1784
+ const format = args?.format ? validateEnum(args.format, 'format', ['concise', 'detailed', 'json'] as const) : 'concise';
1785
+
1786
+ // Validate each pattern
1787
+ const validatedPatterns = patternsArray.map((pattern: any, index: number) => {
1788
+ const taskType = validateTaskString(pattern.taskType, `patterns[${index}].taskType`);
1789
+ const approach = validateTaskString(pattern.approach, `patterns[${index}].approach`);
1790
+ const successRate = validateNumericRange(pattern.successRate, `patterns[${index}].successRate`, 0, 1);
1791
+
1792
+ return {
1793
+ taskType,
1794
+ approach,
1795
+ successRate,
1796
+ tags: pattern.tags || [],
1797
+ metadata: pattern.metadata || {},
1798
+ };
1799
+ });
1800
+
1801
+ // Use BatchOperations for efficient insertion
1802
+ const startTime = Date.now();
1803
+ const batchOpsConfig = new BatchOperations(db, embeddingService, {
1804
+ batchSize,
1805
+ parallelism: 4,
1806
+ });
1807
+
1808
+ const patternIds = await batchOpsConfig.insertPatterns(validatedPatterns);
1809
+ const duration = Date.now() - startTime;
1810
+
1811
+ // Format response
1812
+ if (format === 'json') {
1813
+ return {
1814
+ content: [
1815
+ {
1816
+ type: 'text',
1817
+ text: JSON.stringify({
1818
+ success: true,
1819
+ inserted: patternIds.length,
1820
+ pattern_ids: patternIds,
1821
+ duration_ms: duration,
1822
+ batch_size: batchSize,
1823
+ }, null, 2),
1824
+ },
1825
+ ],
1826
+ };
1827
+ } else if (format === 'detailed') {
1828
+ return {
1829
+ content: [
1830
+ {
1831
+ type: 'text',
1832
+ text: `āœ… Batch pattern storage completed!\n\n` +
1833
+ `šŸ“Š Performance:\n` +
1834
+ ` • Patterns Stored: ${patternIds.length}\n` +
1835
+ ` • Duration: ${duration}ms\n` +
1836
+ ` • Throughput: ${(patternIds.length / (duration / 1000)).toFixed(1)} patterns/sec\n` +
1837
+ ` • Batch Size: ${batchSize}\n` +
1838
+ ` • Parallelism: 4 workers\n\n` +
1839
+ `šŸ“ˆ Statistics:\n` +
1840
+ ` • Task Types: ${new Set(validatedPatterns.map(p => p.taskType)).size}\n` +
1841
+ ` • Avg Success Rate: ${(validatedPatterns.reduce((sum, p) => sum + p.successRate, 0) / validatedPatterns.length * 100).toFixed(1)}%\n` +
1842
+ ` • High Performing (≄80%): ${validatedPatterns.filter(p => p.successRate >= 0.8).length}\n\n` +
1843
+ `šŸ†” Sample Pattern IDs: ${patternIds.slice(0, 5).join(', ')}${patternIds.length > 5 ? '...' : ''}\n` +
1844
+ `🧠 All embeddings generated in parallel\n` +
1845
+ `šŸ’¾ Transaction committed successfully`,
1846
+ },
1847
+ ],
1848
+ };
1849
+ } else {
1850
+ // Concise format (default)
1851
+ return {
1852
+ content: [
1853
+ {
1854
+ type: 'text',
1855
+ text: `āœ… Stored ${patternIds.length} patterns in ${duration}ms (${(patternIds.length / (duration / 1000)).toFixed(1)} patterns/sec)`,
1856
+ },
1857
+ ],
1858
+ };
1859
+ }
1860
+ } catch (error: any) {
1861
+ const safeMessage = handleSecurityError(error);
1862
+ return {
1863
+ content: [
1864
+ {
1865
+ type: 'text',
1866
+ text: `āŒ Batch pattern storage failed: ${safeMessage}\n\n` +
1867
+ `šŸ’” Troubleshooting:\n` +
1868
+ ` • Ensure taskType and approach are not empty\n` +
1869
+ ` • Verify successRate is between 0 and 1\n` +
1870
+ ` • Check that patterns array has 1-500 items\n` +
1871
+ ` • Avoid excessively long task types or approaches`,
1872
+ },
1873
+ ],
1874
+ isError: true,
1875
+ };
1876
+ }
1877
+ }
1878
+
1879
+ // ======================================================================
1880
+ // LEARNING SYSTEM TOOLS (Tools 1-5)
1881
+ // ======================================================================
1882
+ case 'learning_start_session': {
1883
+ const userId = args?.user_id as string;
1884
+ const sessionType = args?.session_type as any;
1885
+ const config = args?.config as any;
1886
+
1887
+ const sessionId = await learningSystem.startSession(
1888
+ userId,
1889
+ sessionType,
1890
+ {
1891
+ learningRate: config.learning_rate,
1892
+ discountFactor: config.discount_factor,
1893
+ explorationRate: config.exploration_rate,
1894
+ batchSize: config.batch_size,
1895
+ targetUpdateFrequency: config.target_update_frequency,
1896
+ }
1897
+ );
1898
+
1899
+ return {
1900
+ content: [
1901
+ {
1902
+ type: 'text',
1903
+ text: `āœ… Learning session started!\n\n` +
1904
+ `šŸ†” Session ID: ${sessionId}\n` +
1905
+ `šŸ‘¤ User: ${userId}\n` +
1906
+ `🧠 Algorithm: ${sessionType}\n` +
1907
+ `āš™ļø Config:\n` +
1908
+ ` • Learning Rate: ${config.learning_rate}\n` +
1909
+ ` • Discount Factor: ${config.discount_factor}\n` +
1910
+ ` • Exploration Rate: ${config.exploration_rate || 0.1}\n` +
1911
+ ` • Batch Size: ${config.batch_size || 32}\n\n` +
1912
+ `šŸ“ Use this session ID for predictions and feedback.`,
1913
+ },
1914
+ ],
1915
+ };
1916
+ }
1917
+
1918
+ case 'learning_end_session': {
1919
+ const sessionId = args?.session_id as string;
1920
+ await learningSystem.endSession(sessionId);
1921
+
1922
+ return {
1923
+ content: [
1924
+ {
1925
+ type: 'text',
1926
+ text: `āœ… Learning session ended!\n\n` +
1927
+ `šŸ†” Session ID: ${sessionId}\n` +
1928
+ `šŸ’¾ Final policy saved to database\n` +
1929
+ `šŸ“Š Session marked as completed`,
1930
+ },
1931
+ ],
1932
+ };
1933
+ }
1934
+
1935
+ case 'learning_predict': {
1936
+ const sessionId = args?.session_id as string;
1937
+ const state = args?.state as string;
1938
+
1939
+ const prediction = await learningSystem.predict(sessionId, state);
1940
+
1941
+ return {
1942
+ content: [
1943
+ {
1944
+ type: 'text',
1945
+ text: `šŸŽÆ AI Recommendation:\n\n` +
1946
+ `šŸ“ State: ${state}\n` +
1947
+ `✨ Recommended Action: ${prediction.action}\n` +
1948
+ `šŸ’Æ Confidence: ${(prediction.confidence * 100).toFixed(1)}%\n` +
1949
+ `šŸ“Š Q-Value: ${prediction.qValue?.toFixed(3) || 'N/A'}\n\n` +
1950
+ `šŸ”„ Alternative Actions:\n` +
1951
+ prediction.alternatives.map((alt, i) =>
1952
+ ` ${i + 1}. ${alt.action} (${(alt.confidence * 100).toFixed(1)}% confidence)`
1953
+ ).join('\n'),
1954
+ },
1955
+ ],
1956
+ };
1957
+ }
1958
+
1959
+ case 'learning_feedback': {
1960
+ const sessionId = args?.session_id as string;
1961
+ const state = args?.state as string;
1962
+ const action = args?.action as string;
1963
+ const reward = args?.reward as number;
1964
+ const nextState = args?.next_state as string | undefined;
1965
+ const success = args?.success as boolean;
1966
+
1967
+ await learningSystem.submitFeedback({
1968
+ sessionId,
1969
+ state,
1970
+ action,
1971
+ reward,
1972
+ nextState,
1973
+ success,
1974
+ timestamp: Date.now(),
1975
+ });
1976
+
1977
+ return {
1978
+ content: [
1979
+ {
1980
+ type: 'text',
1981
+ text: `āœ… Feedback recorded!\n\n` +
1982
+ `šŸ†” Session: ${sessionId}\n` +
1983
+ `šŸ“ State: ${state}\n` +
1984
+ `šŸŽ¬ Action: ${action}\n` +
1985
+ `šŸ† Reward: ${reward.toFixed(2)}\n` +
1986
+ `${success ? 'āœ…' : 'āŒ'} Success: ${success}\n` +
1987
+ `${nextState ? `āž”ļø Next State: ${nextState}\n` : ''}` +
1988
+ `🧠 Policy updated incrementally`,
1989
+ },
1990
+ ],
1991
+ };
1992
+ }
1993
+
1994
+ case 'learning_train': {
1995
+ const sessionId = args?.session_id as string;
1996
+ const epochs = (args?.epochs as number) || 50;
1997
+ const batchSize = (args?.batch_size as number) || 32;
1998
+ const learningRate = (args?.learning_rate as number) || 0.01;
1999
+
2000
+ console.log(`šŸŽ“ Training session ${sessionId}...`);
2001
+ const result = await learningSystem.train(sessionId, epochs, batchSize, learningRate);
2002
+
2003
+ return {
2004
+ content: [
2005
+ {
2006
+ type: 'text',
2007
+ text: `šŸŽ“ Training completed!\n\n` +
2008
+ `šŸ“Š Training Results:\n` +
2009
+ ` • Epochs: ${result.epochsCompleted}\n` +
2010
+ ` • Final Loss: ${result.finalLoss.toFixed(4)}\n` +
2011
+ ` • Avg Reward: ${result.avgReward.toFixed(3)}\n` +
2012
+ ` • Convergence Rate: ${(result.convergenceRate * 100).toFixed(1)}%\n` +
2013
+ ` • Training Time: ${result.trainingTimeMs}ms\n\n` +
2014
+ `šŸ’¾ Trained policy saved to database\n` +
2015
+ `✨ Ready for improved predictions!`,
2016
+ },
2017
+ ],
2018
+ };
2019
+ }
2020
+
2021
+ // ======================================================================
2022
+ // LEARNING SYSTEM TOOLS (v1.4.0 - Tools 6-10) - IMPLEMENTATIONS
2023
+ // ======================================================================
2024
+ case 'learning_metrics': {
2025
+ const sessionId = args?.session_id as string | undefined;
2026
+ const timeWindowDays = (args?.time_window_days as number) || 7;
2027
+ const includeTrends = (args?.include_trends as boolean) !== false;
2028
+ const groupBy = (args?.group_by as 'task' | 'session' | 'skill') || 'task';
2029
+
2030
+ // Check cache first (120s TTL for expensive computations)
2031
+ const cacheKey = `metrics:${sessionId || 'all'}:${timeWindowDays}:${groupBy}:${includeTrends}`;
2032
+ const cached = caches.metrics.get(cacheKey);
2033
+ if (cached) {
2034
+ return {
2035
+ content: [
2036
+ {
2037
+ type: 'text',
2038
+ text: `${cached}\n\n⚔ (cached)`,
2039
+ },
2040
+ ],
2041
+ };
2042
+ }
2043
+
2044
+ const metrics = await learningSystem.getMetrics({
2045
+ sessionId,
2046
+ timeWindowDays,
2047
+ includeTrends,
2048
+ groupBy,
2049
+ });
2050
+
2051
+ const output = `šŸ“Š Learning Performance Metrics\n\n` +
2052
+ `ā±ļø Time Window: ${timeWindowDays} days\n\n` +
2053
+ `šŸ“ˆ Overall Performance:\n` +
2054
+ ` • Total Episodes: ${metrics.overall.totalEpisodes}\n` +
2055
+ ` • Success Rate: ${(metrics.overall.successRate * 100).toFixed(1)}%\n` +
2056
+ ` • Avg Reward: ${metrics.overall.avgReward.toFixed(3)}\n` +
2057
+ ` • Reward Range: [${metrics.overall.minReward.toFixed(2)}, ${metrics.overall.maxReward.toFixed(2)}]\n` +
2058
+ ` • Avg Latency: ${metrics.overall.avgLatencyMs.toFixed(0)}ms\n\n` +
2059
+ `šŸŽÆ Top ${groupBy.charAt(0).toUpperCase() + groupBy.slice(1)}s:\n` +
2060
+ metrics.groupedMetrics.slice(0, 5).map((g, i) =>
2061
+ ` ${i + 1}. ${g.key.substring(0, 40)}${g.key.length > 40 ? '...' : ''}\n` +
2062
+ ` Count: ${g.count}, Success: ${(g.successRate * 100).toFixed(1)}%, Reward: ${g.avgReward.toFixed(2)}`
2063
+ ).join('\n') +
2064
+ (metrics.groupedMetrics.length === 0 ? ' No data available' : '') +
2065
+ (includeTrends && metrics.trends.length > 0 ? `\n\nšŸ“‰ Recent Trends (last ${Math.min(7, metrics.trends.length)} days):\n` +
2066
+ metrics.trends.slice(-7).map((t) =>
2067
+ ` ${t.date}: ${t.count} episodes, ${(t.successRate * 100).toFixed(1)}% success`
2068
+ ).join('\n') : '') +
2069
+ (metrics.policyImprovement.versions > 0 ? `\n\n🧠 Policy Improvement:\n` +
2070
+ ` • Versions: ${metrics.policyImprovement.versions}\n` +
2071
+ ` • Q-Value Improvement: ${metrics.policyImprovement.qValueImprovement >= 0 ? '+' : ''}${metrics.policyImprovement.qValueImprovement.toFixed(3)}` : '');
2072
+
2073
+ // Cache the result (120s TTL)
2074
+ caches.metrics.set(cacheKey, output);
2075
+
2076
+ return {
2077
+ content: [
2078
+ {
2079
+ type: 'text',
2080
+ text: output,
2081
+ },
2082
+ ],
2083
+ };
2084
+ }
2085
+
2086
+ case 'learning_transfer': {
2087
+ const sourceSession = args?.source_session as string | undefined;
2088
+ const targetSession = args?.target_session as string | undefined;
2089
+ const sourceTask = args?.source_task as string | undefined;
2090
+ const targetTask = args?.target_task as string | undefined;
2091
+ const minSimilarity = (args?.min_similarity as number) || 0.7;
2092
+ const transferType = (args?.transfer_type as any) || 'all';
2093
+ const maxTransfers = (args?.max_transfers as number) || 10;
2094
+
2095
+ const result = await learningSystem.transferLearning({
2096
+ sourceSession,
2097
+ targetSession,
2098
+ sourceTask,
2099
+ targetTask,
2100
+ minSimilarity,
2101
+ transferType,
2102
+ maxTransfers,
2103
+ });
2104
+
2105
+ return {
2106
+ content: [
2107
+ {
2108
+ type: 'text',
2109
+ text: `šŸ”„ Learning Transfer Completed!\n\n` +
2110
+ `šŸ“¤ Source: ${sourceSession ? `Session ${sourceSession}` : `Task "${sourceTask}"`}\n` +
2111
+ `šŸ“„ Target: ${targetSession ? `Session ${targetSession}` : `Task "${targetTask}"`}\n` +
2112
+ `šŸŽÆ Transfer Type: ${transferType}\n` +
2113
+ `šŸ“Š Min Similarity: ${(minSimilarity * 100).toFixed(0)}%\n\n` +
2114
+ `āœ… Transferred:\n` +
2115
+ ` • Episodes: ${result.transferred.episodes}\n` +
2116
+ ` • Skills/Q-Values: ${result.transferred.skills}\n` +
2117
+ ` • Causal Edges: ${result.transferred.causalEdges}\n` +
2118
+ (result.transferred.details.length > 0 ? `\nšŸ“ Transfer Details:\n` +
2119
+ result.transferred.details.slice(0, 5).map((d: any, i: number) =>
2120
+ ` ${i + 1}. ${d.type} #${d.id} (similarity: ${(d.similarity * 100).toFixed(1)}%)`
2121
+ ).join('\n') : '') +
2122
+ `\n\nšŸ’” Knowledge successfully transferred for reuse!`,
2123
+ },
2124
+ ],
2125
+ };
2126
+ }
2127
+
2128
+ case 'learning_explain': {
2129
+ const query = args?.query as string;
2130
+ const k = (args?.k as number) || 5;
2131
+ const explainDepth = (args?.explain_depth as any) || 'detailed';
2132
+ const includeConfidence = (args?.include_confidence as boolean) !== false;
2133
+ const includeEvidence = (args?.include_evidence as boolean) !== false;
2134
+ const includeCausal = (args?.include_causal as boolean) !== false;
2135
+
2136
+ const explanation = await learningSystem.explainAction({
2137
+ query,
2138
+ k,
2139
+ explainDepth,
2140
+ includeConfidence,
2141
+ includeEvidence,
2142
+ includeCausal,
2143
+ });
2144
+
2145
+ return {
2146
+ content: [
2147
+ {
2148
+ type: 'text',
2149
+ text: `šŸ” AI Action Recommendations (Explainable)\n\n` +
2150
+ `šŸŽÆ Query: ${query}\n\n` +
2151
+ `šŸ’” Recommended Actions:\n` +
2152
+ explanation.recommendations.map((rec: any, i: number) =>
2153
+ `${i + 1}. ${rec.action}\n` +
2154
+ ` • Confidence: ${(rec.confidence * 100).toFixed(1)}%\n` +
2155
+ ` • Success Rate: ${(rec.successRate * 100).toFixed(1)}%\n` +
2156
+ ` • Avg Reward: ${rec.avgReward.toFixed(3)}\n` +
2157
+ ` • Supporting Examples: ${rec.supportingExamples}\n` +
2158
+ (includeEvidence && rec.evidence ? ` • Evidence:\n` +
2159
+ rec.evidence.map((e: any) =>
2160
+ ` - Episode ${e.episodeId}: reward=${e.reward.toFixed(2)}, similarity=${(e.similarity * 100).toFixed(1)}%`
2161
+ ).join('\n') : '')
2162
+ ).join('\n\n') +
2163
+ (explainDepth !== 'summary' && explanation.reasoning ? `\n\n🧠 Reasoning:\n` +
2164
+ ` • Similar Experiences Found: ${explanation.reasoning.similarExperiencesFound}\n` +
2165
+ ` • Avg Similarity: ${(explanation.reasoning.avgSimilarity * 100).toFixed(1)}%\n` +
2166
+ ` • Unique Actions Considered: ${explanation.reasoning.uniqueActions}` : '') +
2167
+ (includeCausal && explanation.causalChains && explanation.causalChains.length > 0 ? `\n\nšŸ”— Causal Reasoning Chains:\n` +
2168
+ explanation.causalChains.slice(0, 3).map((chain: any, i: number) =>
2169
+ ` ${i + 1}. ${chain.fromMemoryType} → ${chain.toMemoryType} (uplift: ${(chain.uplift || 0).toFixed(3)})`
2170
+ ).join('\n') : ''),
2171
+ },
2172
+ ],
2173
+ };
2174
+ }
2175
+
2176
+ case 'experience_record': {
2177
+ const sessionId = args?.session_id as string;
2178
+ const toolName = args?.tool_name as string;
2179
+ const action = args?.action as string;
2180
+ const stateBefore = args?.state_before as any;
2181
+ const stateAfter = args?.state_after as any;
2182
+ const outcome = args?.outcome as string;
2183
+ const reward = args?.reward as number;
2184
+ const success = args?.success as boolean;
2185
+ const latencyMs = args?.latency_ms as number | undefined;
2186
+ const metadata = args?.metadata as any;
2187
+
2188
+ const experienceId = await learningSystem.recordExperience({
2189
+ sessionId,
2190
+ toolName,
2191
+ action,
2192
+ stateBefore,
2193
+ stateAfter,
2194
+ outcome,
2195
+ reward,
2196
+ success,
2197
+ latencyMs,
2198
+ metadata,
2199
+ });
2200
+
2201
+ return {
2202
+ content: [
2203
+ {
2204
+ type: 'text',
2205
+ text: `āœ… Experience recorded successfully!\n\n` +
2206
+ `šŸ†” Experience ID: ${experienceId}\n` +
2207
+ `šŸ“‹ Session: ${sessionId}\n` +
2208
+ `šŸ”§ Tool: ${toolName}\n` +
2209
+ `šŸŽ¬ Action: ${action}\n` +
2210
+ `šŸ“Š Outcome: ${outcome}\n` +
2211
+ `šŸ† Reward: ${reward.toFixed(3)}\n` +
2212
+ `${success ? 'āœ…' : 'āŒ'} Success: ${success}\n` +
2213
+ (latencyMs ? `ā±ļø Latency: ${latencyMs}ms\n` : '') +
2214
+ `\nšŸ’¾ Experience stored for offline learning and future recommendations`,
2215
+ },
2216
+ ],
2217
+ };
2218
+ }
2219
+
2220
+ case 'reward_signal': {
2221
+ const episodeId = args?.episode_id as number | undefined;
2222
+ const success = args?.success as boolean;
2223
+ const targetAchieved = (args?.target_achieved as boolean) !== false;
2224
+ const efficiencyScore = (args?.efficiency_score as number) || 0.5;
2225
+ const qualityScore = (args?.quality_score as number) || 0.5;
2226
+ const timeTakenMs = args?.time_taken_ms as number | undefined;
2227
+ const expectedTimeMs = args?.expected_time_ms as number | undefined;
2228
+ const includeCausal = (args?.include_causal as boolean) !== false;
2229
+ const rewardFunction = (args?.reward_function as any) || 'standard';
2230
+
2231
+ const reward = learningSystem.calculateReward({
2232
+ episodeId,
2233
+ success,
2234
+ targetAchieved,
2235
+ efficiencyScore,
2236
+ qualityScore,
2237
+ timeTakenMs,
2238
+ expectedTimeMs,
2239
+ includeCausal,
2240
+ rewardFunction,
2241
+ });
2242
+
2243
+ return {
2244
+ content: [
2245
+ {
2246
+ type: 'text',
2247
+ text: `šŸŽÆ Reward Signal Calculated\n\n` +
2248
+ `šŸ“Š Final Reward: ${reward.toFixed(3)}\n` +
2249
+ `šŸ”§ Reward Function: ${rewardFunction}\n\n` +
2250
+ `šŸ“ˆ Input Factors:\n` +
2251
+ ` • Success: ${success ? 'āœ…' : 'āŒ'}\n` +
2252
+ ` • Target Achieved: ${targetAchieved ? 'āœ…' : 'āŒ'}\n` +
2253
+ ` • Efficiency Score: ${(efficiencyScore * 100).toFixed(1)}%\n` +
2254
+ ` • Quality Score: ${(qualityScore * 100).toFixed(1)}%\n` +
2255
+ (timeTakenMs && expectedTimeMs ? ` • Time Efficiency: ${((expectedTimeMs / timeTakenMs) * 100).toFixed(1)}%\n` : '') +
2256
+ (includeCausal ? ` • Causal Impact: Included\n` : '') +
2257
+ `\nšŸ’” Use this reward signal for learning feedback`,
2258
+ },
2259
+ ],
2260
+ };
2261
+ }
2262
+
2263
+ default:
2264
+ throw new Error(`Unknown tool: ${name}`);
2265
+ }
2266
+ } catch (error: any) {
2267
+ return {
2268
+ content: [
2269
+ {
2270
+ type: 'text',
2271
+ text: `āŒ Error: ${error.message}\n${error.stack || ''}`,
2272
+ },
2273
+ ],
2274
+ isError: true,
2275
+ };
2276
+ }
2277
+ });
2278
+
2279
+ // ============================================================================
2280
+ // Start Server
2281
+ // ============================================================================
2282
+ async function main() {
2283
+ const transport = new StdioServerTransport();
2284
+ await server.connect(transport);
2285
+
2286
+ console.error('šŸš€ AgentDB MCP Server v2.0.0 running on stdio');
2287
+ console.error('šŸ“¦ 32 tools available (5 core + 9 frontier + 10 learning + 5 AgentDB + 3 batch ops)');
2288
+ console.error('🧠 Embedding service initialized');
2289
+ console.error('šŸŽ“ Learning system ready (9 RL algorithms)');
2290
+ console.error('⚔ NEW v2.0: Batch operations (3-4x faster), format parameters, enhanced validation');
2291
+ console.error('šŸ”¬ Features: transfer learning, XAI explanations, reward shaping, intelligent caching');
2292
+
2293
+ // Keep the process alive - the StdioServerTransport handles stdin/stdout
2294
+ // but we need to ensure Node.js doesn't exit when main() completes
2295
+
2296
+ // Use setInterval to keep event loop alive (like many MCP servers do)
2297
+ // This ensures the process doesn't exit even if stdin closes
2298
+ const keepAlive = setInterval(() => {
2299
+ // Empty interval just to keep event loop alive
2300
+ }, 1000 * 60 * 60); // Every hour (basically forever)
2301
+
2302
+ // Handle graceful shutdown
2303
+ const shutdown = () => {
2304
+ clearInterval(keepAlive);
2305
+ process.exit(0);
2306
+ };
2307
+
2308
+ process.on('SIGINT', shutdown);
2309
+ process.on('SIGTERM', shutdown);
2310
+
2311
+ // Return a never-resolving promise
2312
+ return new Promise(() => {
2313
+ // The setInterval above keeps the event loop alive
2314
+ // StdioServerTransport handles all MCP communication
2315
+ });
2316
+ }
2317
+
2318
+ main().catch(console.error);