agentdb 3.0.0-alpha.1 → 3.0.0-alpha.10

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 (781) hide show
  1. package/README.md +222 -2576
  2. package/dist/agentdb.browser.js +1685 -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/backends/VectorBackend.d.ts +120 -0
  8. package/dist/backends/VectorBackend.js +14 -0
  9. package/dist/backends/VectorBackend.js.map +1 -0
  10. package/dist/optimizations/RVFOptimizer.d.ts +225 -0
  11. package/dist/optimizations/RVFOptimizer.js +541 -0
  12. package/dist/optimizations/RVFOptimizer.js.map +1 -0
  13. package/dist/schemas/frontier-schema.sql +0 -7
  14. package/dist/schemas/schema.sql +0 -7
  15. package/dist/simulation/cli.d.ts +9 -0
  16. package/dist/simulation/cli.d.ts.map +1 -0
  17. package/dist/simulation/cli.js +68 -0
  18. package/dist/simulation/cli.js.map +1 -0
  19. package/dist/simulation/runner.d.ts +21 -0
  20. package/dist/simulation/runner.d.ts.map +1 -0
  21. package/dist/simulation/runner.js +241 -0
  22. package/dist/simulation/runner.js.map +1 -0
  23. package/dist/simulation/scenarios/aidefence-integration.d.ts +24 -0
  24. package/dist/simulation/scenarios/aidefence-integration.d.ts.map +1 -0
  25. package/dist/simulation/scenarios/aidefence-integration.js +124 -0
  26. package/dist/simulation/scenarios/aidefence-integration.js.map +1 -0
  27. package/dist/simulation/scenarios/bmssp-integration.d.ts +23 -0
  28. package/dist/simulation/scenarios/bmssp-integration.d.ts.map +1 -0
  29. package/dist/simulation/scenarios/bmssp-integration.js +104 -0
  30. package/dist/simulation/scenarios/bmssp-integration.js.map +1 -0
  31. package/dist/simulation/scenarios/causal-reasoning.d.ts +16 -0
  32. package/dist/simulation/scenarios/causal-reasoning.d.ts.map +1 -0
  33. package/dist/simulation/scenarios/causal-reasoning.js +108 -0
  34. package/dist/simulation/scenarios/causal-reasoning.js.map +1 -0
  35. package/dist/simulation/scenarios/consciousness-explorer.d.ts +25 -0
  36. package/dist/simulation/scenarios/consciousness-explorer.d.ts.map +1 -0
  37. package/dist/simulation/scenarios/consciousness-explorer.js +108 -0
  38. package/dist/simulation/scenarios/consciousness-explorer.js.map +1 -0
  39. package/dist/simulation/scenarios/domain-examples/e-commerce-recommendations.d.ts +135 -0
  40. package/dist/simulation/scenarios/domain-examples/e-commerce-recommendations.d.ts.map +1 -0
  41. package/dist/simulation/scenarios/domain-examples/e-commerce-recommendations.js +158 -0
  42. package/dist/simulation/scenarios/domain-examples/e-commerce-recommendations.js.map +1 -0
  43. package/dist/simulation/scenarios/domain-examples/index.d.ts +14 -0
  44. package/dist/simulation/scenarios/domain-examples/index.d.ts.map +1 -0
  45. package/dist/simulation/scenarios/domain-examples/index.js +14 -0
  46. package/dist/simulation/scenarios/domain-examples/index.js.map +1 -0
  47. package/dist/simulation/scenarios/domain-examples/iot-sensor-networks.d.ts +178 -0
  48. package/dist/simulation/scenarios/domain-examples/iot-sensor-networks.d.ts.map +1 -0
  49. package/dist/simulation/scenarios/domain-examples/iot-sensor-networks.js +218 -0
  50. package/dist/simulation/scenarios/domain-examples/iot-sensor-networks.js.map +1 -0
  51. package/dist/simulation/scenarios/domain-examples/medical-imaging.d.ts +122 -0
  52. package/dist/simulation/scenarios/domain-examples/medical-imaging.d.ts.map +1 -0
  53. package/dist/simulation/scenarios/domain-examples/medical-imaging.js +129 -0
  54. package/dist/simulation/scenarios/domain-examples/medical-imaging.js.map +1 -0
  55. package/dist/simulation/scenarios/domain-examples/robotics-navigation.d.ts +166 -0
  56. package/dist/simulation/scenarios/domain-examples/robotics-navigation.d.ts.map +1 -0
  57. package/dist/simulation/scenarios/domain-examples/robotics-navigation.js +161 -0
  58. package/dist/simulation/scenarios/domain-examples/robotics-navigation.js.map +1 -0
  59. package/dist/simulation/scenarios/domain-examples/scientific-research.d.ts +151 -0
  60. package/dist/simulation/scenarios/domain-examples/scientific-research.d.ts.map +1 -0
  61. package/dist/simulation/scenarios/domain-examples/scientific-research.js +187 -0
  62. package/dist/simulation/scenarios/domain-examples/scientific-research.js.map +1 -0
  63. package/dist/simulation/scenarios/domain-examples/trading-systems.d.ts +102 -0
  64. package/dist/simulation/scenarios/domain-examples/trading-systems.d.ts.map +1 -0
  65. package/dist/simulation/scenarios/domain-examples/trading-systems.js +100 -0
  66. package/dist/simulation/scenarios/domain-examples/trading-systems.js.map +1 -0
  67. package/dist/simulation/scenarios/goalie-integration.d.ts +24 -0
  68. package/dist/simulation/scenarios/goalie-integration.d.ts.map +1 -0
  69. package/dist/simulation/scenarios/goalie-integration.js +121 -0
  70. package/dist/simulation/scenarios/goalie-integration.js.map +1 -0
  71. package/dist/simulation/scenarios/graph-traversal.d.ts +17 -0
  72. package/dist/simulation/scenarios/graph-traversal.d.ts.map +1 -0
  73. package/dist/simulation/scenarios/graph-traversal.js +101 -0
  74. package/dist/simulation/scenarios/graph-traversal.js.map +1 -0
  75. package/dist/simulation/scenarios/latent-space/attention-analysis.d.ts +45 -0
  76. package/dist/simulation/scenarios/latent-space/attention-analysis.d.ts.map +1 -0
  77. package/dist/simulation/scenarios/latent-space/attention-analysis.js +435 -0
  78. package/dist/simulation/scenarios/latent-space/attention-analysis.js.map +1 -0
  79. package/dist/simulation/scenarios/latent-space/clustering-analysis.d.ts +55 -0
  80. package/dist/simulation/scenarios/latent-space/clustering-analysis.d.ts.map +1 -0
  81. package/dist/simulation/scenarios/latent-space/clustering-analysis.js +606 -0
  82. package/dist/simulation/scenarios/latent-space/clustering-analysis.js.map +1 -0
  83. package/dist/simulation/scenarios/latent-space/hnsw-exploration.d.ts +74 -0
  84. package/dist/simulation/scenarios/latent-space/hnsw-exploration.d.ts.map +1 -0
  85. package/dist/simulation/scenarios/latent-space/hnsw-exploration.js +391 -0
  86. package/dist/simulation/scenarios/latent-space/hnsw-exploration.js.map +1 -0
  87. package/dist/simulation/scenarios/latent-space/hypergraph-exploration.d.ts +51 -0
  88. package/dist/simulation/scenarios/latent-space/hypergraph-exploration.d.ts.map +1 -0
  89. package/dist/simulation/scenarios/latent-space/hypergraph-exploration.js +536 -0
  90. package/dist/simulation/scenarios/latent-space/hypergraph-exploration.js.map +1 -0
  91. package/dist/simulation/scenarios/latent-space/index.d.ts +35 -0
  92. package/dist/simulation/scenarios/latent-space/index.d.ts.map +1 -0
  93. package/dist/simulation/scenarios/latent-space/index.js +35 -0
  94. package/dist/simulation/scenarios/latent-space/index.js.map +1 -0
  95. package/dist/simulation/scenarios/latent-space/neural-augmentation.d.ts +52 -0
  96. package/dist/simulation/scenarios/latent-space/neural-augmentation.d.ts.map +1 -0
  97. package/dist/simulation/scenarios/latent-space/neural-augmentation.js +472 -0
  98. package/dist/simulation/scenarios/latent-space/neural-augmentation.js.map +1 -0
  99. package/dist/simulation/scenarios/latent-space/quantum-hybrid.d.ts +53 -0
  100. package/dist/simulation/scenarios/latent-space/quantum-hybrid.d.ts.map +1 -0
  101. package/dist/simulation/scenarios/latent-space/quantum-hybrid.js +391 -0
  102. package/dist/simulation/scenarios/latent-space/quantum-hybrid.js.map +1 -0
  103. package/dist/simulation/scenarios/latent-space/self-organizing-hnsw.d.ts +52 -0
  104. package/dist/simulation/scenarios/latent-space/self-organizing-hnsw.d.ts.map +1 -0
  105. package/dist/simulation/scenarios/latent-space/self-organizing-hnsw.js +514 -0
  106. package/dist/simulation/scenarios/latent-space/self-organizing-hnsw.js.map +1 -0
  107. package/dist/simulation/scenarios/latent-space/traversal-optimization.d.ts +53 -0
  108. package/dist/simulation/scenarios/latent-space/traversal-optimization.d.ts.map +1 -0
  109. package/dist/simulation/scenarios/latent-space/traversal-optimization.js +595 -0
  110. package/dist/simulation/scenarios/latent-space/traversal-optimization.js.map +1 -0
  111. package/dist/simulation/scenarios/lean-agentic-swarm.d.ts +18 -0
  112. package/dist/simulation/scenarios/lean-agentic-swarm.d.ts.map +1 -0
  113. package/dist/simulation/scenarios/lean-agentic-swarm.js +132 -0
  114. package/dist/simulation/scenarios/lean-agentic-swarm.js.map +1 -0
  115. package/dist/simulation/scenarios/multi-agent-swarm.d.ts +17 -0
  116. package/dist/simulation/scenarios/multi-agent-swarm.d.ts.map +1 -0
  117. package/dist/simulation/scenarios/multi-agent-swarm.js +111 -0
  118. package/dist/simulation/scenarios/multi-agent-swarm.js.map +1 -0
  119. package/dist/simulation/scenarios/psycho-symbolic-reasoner.d.ts +23 -0
  120. package/dist/simulation/scenarios/psycho-symbolic-reasoner.d.ts.map +1 -0
  121. package/dist/simulation/scenarios/psycho-symbolic-reasoner.js +98 -0
  122. package/dist/simulation/scenarios/psycho-symbolic-reasoner.js.map +1 -0
  123. package/dist/simulation/scenarios/reflexion-learning.d.ts +16 -0
  124. package/dist/simulation/scenarios/reflexion-learning.d.ts.map +1 -0
  125. package/dist/simulation/scenarios/reflexion-learning.js +98 -0
  126. package/dist/simulation/scenarios/reflexion-learning.js.map +1 -0
  127. package/dist/simulation/scenarios/research-swarm.d.ts +24 -0
  128. package/dist/simulation/scenarios/research-swarm.d.ts.map +1 -0
  129. package/dist/simulation/scenarios/research-swarm.js +146 -0
  130. package/dist/simulation/scenarios/research-swarm.js.map +1 -0
  131. package/dist/simulation/scenarios/skill-evolution.d.ts +16 -0
  132. package/dist/simulation/scenarios/skill-evolution.d.ts.map +1 -0
  133. package/dist/simulation/scenarios/skill-evolution.js +109 -0
  134. package/dist/simulation/scenarios/skill-evolution.js.map +1 -0
  135. package/dist/simulation/scenarios/stock-market-emergence.d.ts +33 -0
  136. package/dist/simulation/scenarios/stock-market-emergence.d.ts.map +1 -0
  137. package/dist/simulation/scenarios/stock-market-emergence.js +246 -0
  138. package/dist/simulation/scenarios/stock-market-emergence.js.map +1 -0
  139. package/dist/simulation/scenarios/strange-loops.d.ts +18 -0
  140. package/dist/simulation/scenarios/strange-loops.d.ts.map +1 -0
  141. package/dist/simulation/scenarios/strange-loops.js +133 -0
  142. package/dist/simulation/scenarios/strange-loops.js.map +1 -0
  143. package/dist/simulation/scenarios/sublinear-solver.d.ts +22 -0
  144. package/dist/simulation/scenarios/sublinear-solver.d.ts.map +1 -0
  145. package/dist/simulation/scenarios/sublinear-solver.js +82 -0
  146. package/dist/simulation/scenarios/sublinear-solver.js.map +1 -0
  147. package/dist/simulation/scenarios/temporal-lead-solver.d.ts +23 -0
  148. package/dist/simulation/scenarios/temporal-lead-solver.d.ts.map +1 -0
  149. package/dist/simulation/scenarios/temporal-lead-solver.js +90 -0
  150. package/dist/simulation/scenarios/temporal-lead-solver.js.map +1 -0
  151. package/dist/simulation/scenarios/voting-system-consensus.d.ts +27 -0
  152. package/dist/simulation/scenarios/voting-system-consensus.d.ts.map +1 -0
  153. package/dist/simulation/scenarios/voting-system-consensus.js +175 -0
  154. package/dist/simulation/scenarios/voting-system-consensus.js.map +1 -0
  155. package/dist/simulation/types.d.ts +162 -0
  156. package/dist/simulation/types.d.ts.map +1 -0
  157. package/dist/simulation/types.js +5 -0
  158. package/dist/simulation/types.js.map +1 -0
  159. package/dist/simulation/utils/PerformanceOptimizer.d.ts +115 -0
  160. package/dist/simulation/utils/PerformanceOptimizer.d.ts.map +1 -0
  161. package/dist/simulation/utils/PerformanceOptimizer.js +223 -0
  162. package/dist/simulation/utils/PerformanceOptimizer.js.map +1 -0
  163. package/dist/src/backends/GraphBackend.d.ts +8 -8
  164. package/dist/src/backends/GraphBackend.d.ts.map +1 -1
  165. package/dist/src/backends/GraphBackend.js +15 -16
  166. package/dist/src/backends/GraphBackend.js.map +1 -1
  167. package/dist/src/backends/LearningBackend.d.ts +2 -2
  168. package/dist/src/backends/LearningBackend.d.ts.map +1 -1
  169. package/dist/src/backends/LearningBackend.js +10 -11
  170. package/dist/src/backends/LearningBackend.js.map +1 -1
  171. package/dist/src/backends/VectorBackend.d.ts +6 -31
  172. package/dist/src/backends/VectorBackend.d.ts.map +1 -1
  173. package/dist/src/backends/detector.d.ts +3 -25
  174. package/dist/src/backends/detector.d.ts.map +1 -1
  175. package/dist/src/backends/detector.js +15 -119
  176. package/dist/src/backends/detector.js.map +1 -1
  177. package/dist/src/backends/factory.d.ts +33 -16
  178. package/dist/src/backends/factory.d.ts.map +1 -1
  179. package/dist/src/backends/factory.js +108 -138
  180. package/dist/src/backends/factory.js.map +1 -1
  181. package/dist/src/backends/graph/GraphDatabaseAdapter.d.ts +1 -1
  182. package/dist/src/backends/graph/GraphDatabaseAdapter.d.ts.map +1 -1
  183. package/dist/src/backends/graph/GraphDatabaseAdapter.js +1 -5
  184. package/dist/src/backends/graph/GraphDatabaseAdapter.js.map +1 -1
  185. package/dist/src/backends/hnswlib/HNSWLibBackend.d.ts +2 -2
  186. package/dist/src/backends/hnswlib/HNSWLibBackend.d.ts.map +1 -1
  187. package/dist/src/backends/hnswlib/HNSWLibBackend.js +13 -49
  188. package/dist/src/backends/hnswlib/HNSWLibBackend.js.map +1 -1
  189. package/dist/src/backends/index.cjs +6 -0
  190. package/dist/src/backends/index.d.ts +3 -25
  191. package/dist/src/backends/index.d.ts.map +1 -1
  192. package/dist/src/backends/index.js +1 -23
  193. package/dist/src/backends/index.js.map +1 -1
  194. package/dist/src/backends/ruvector/GuardedVectorBackend.d.ts +93 -0
  195. package/dist/src/backends/ruvector/GuardedVectorBackend.d.ts.map +1 -0
  196. package/dist/src/backends/ruvector/GuardedVectorBackend.js +182 -0
  197. package/dist/src/backends/ruvector/GuardedVectorBackend.js.map +1 -0
  198. package/dist/src/backends/ruvector/RuVectorBackend.d.ts +47 -200
  199. package/dist/src/backends/ruvector/RuVectorBackend.d.ts.map +1 -1
  200. package/dist/src/backends/ruvector/RuVectorBackend.js +277 -612
  201. package/dist/src/backends/ruvector/RuVectorBackend.js.map +1 -1
  202. package/dist/src/backends/ruvector/RuVectorLearning.d.ts +4 -0
  203. package/dist/src/backends/ruvector/RuVectorLearning.d.ts.map +1 -1
  204. package/dist/src/backends/ruvector/RuVectorLearning.js +11 -10
  205. package/dist/src/backends/ruvector/RuVectorLearning.js.map +1 -1
  206. package/dist/src/benchmarks/wasm-vector-benchmark.d.ts +10 -0
  207. package/dist/src/benchmarks/wasm-vector-benchmark.d.ts.map +1 -0
  208. package/dist/src/benchmarks/wasm-vector-benchmark.js +196 -0
  209. package/dist/src/benchmarks/wasm-vector-benchmark.js.map +1 -0
  210. package/dist/src/browser/AdvancedFeatures.d.ts.map +1 -1
  211. package/dist/src/browser/AdvancedFeatures.js +10 -3
  212. package/dist/src/browser/AdvancedFeatures.js.map +1 -1
  213. package/dist/src/browser/AttentionBrowser.d.ts.map +1 -1
  214. package/dist/src/browser/AttentionBrowser.js +12 -5
  215. package/dist/src/browser/AttentionBrowser.js.map +1 -1
  216. package/dist/src/browser/HNSWIndex.d.ts +1 -31
  217. package/dist/src/browser/HNSWIndex.d.ts.map +1 -1
  218. package/dist/src/browser/HNSWIndex.js +18 -136
  219. package/dist/src/browser/HNSWIndex.js.map +1 -1
  220. package/dist/src/browser/ProductQuantization.d.ts.map +1 -1
  221. package/dist/src/browser/ProductQuantization.js +1 -0
  222. package/dist/src/browser/ProductQuantization.js.map +1 -1
  223. package/dist/src/browser/index.d.ts +3 -3
  224. package/dist/src/browser/index.d.ts.map +1 -1
  225. package/dist/src/browser/index.js +1 -2
  226. package/dist/src/browser/index.js.map +1 -1
  227. package/dist/src/cli/agentdb-cli.d.ts +2 -16
  228. package/dist/src/cli/agentdb-cli.d.ts.map +1 -1
  229. package/dist/src/cli/agentdb-cli.js +216 -853
  230. package/dist/src/cli/agentdb-cli.js.map +1 -1
  231. package/dist/src/cli/commands/attention.js +3 -3
  232. package/dist/src/cli/commands/attention.js.map +1 -1
  233. package/dist/src/cli/commands/doctor.d.ts +0 -2
  234. package/dist/src/cli/commands/doctor.d.ts.map +1 -1
  235. package/dist/src/cli/commands/doctor.js +1 -106
  236. package/dist/src/cli/commands/doctor.js.map +1 -1
  237. package/dist/src/cli/commands/init.d.ts +1 -2
  238. package/dist/src/cli/commands/init.d.ts.map +1 -1
  239. package/dist/src/cli/commands/init.js +7 -30
  240. package/dist/src/cli/commands/init.js.map +1 -1
  241. package/dist/src/cli/commands/install-embeddings.d.ts.map +1 -1
  242. package/dist/src/cli/commands/install-embeddings.js.map +1 -1
  243. package/dist/src/cli/commands/migrate.d.ts +0 -15
  244. package/dist/src/cli/commands/migrate.d.ts.map +1 -1
  245. package/dist/src/cli/commands/migrate.js +5 -164
  246. package/dist/src/cli/commands/migrate.js.map +1 -1
  247. package/dist/src/cli/commands/simulate-report.js.map +1 -1
  248. package/dist/src/cli/commands/simulate-wizard.js.map +1 -1
  249. package/dist/src/cli/commands/simulate.d.ts +7 -0
  250. package/dist/src/cli/commands/simulate.d.ts.map +1 -0
  251. package/dist/src/cli/commands/simulate.js +100 -0
  252. package/dist/src/cli/commands/simulate.js.map +1 -0
  253. package/dist/src/cli/commands/status.js +1 -5
  254. package/dist/src/cli/commands/status.js.map +1 -1
  255. package/dist/src/cli/lib/attention-config.d.ts +2 -2
  256. package/dist/src/cli/lib/attention-config.d.ts.map +1 -1
  257. package/dist/src/cli/lib/attention-config.js +1 -2
  258. package/dist/src/cli/lib/attention-config.js.map +1 -1
  259. package/dist/src/cli/lib/config-manager.d.ts +110 -0
  260. package/dist/src/cli/lib/config-manager.d.ts.map +1 -0
  261. package/dist/src/cli/lib/config-manager.js +512 -0
  262. package/dist/src/cli/lib/config-manager.js.map +1 -0
  263. package/dist/src/cli/lib/config-validator.d.ts +1 -1
  264. package/dist/src/cli/lib/config-validator.d.ts.map +1 -1
  265. package/dist/src/cli/lib/health-monitor.d.ts +149 -0
  266. package/dist/src/cli/lib/health-monitor.d.ts.map +1 -0
  267. package/dist/src/cli/lib/health-monitor.js +380 -0
  268. package/dist/src/cli/lib/health-monitor.js.map +1 -0
  269. package/dist/src/cli/lib/history-tracker.d.ts +103 -0
  270. package/dist/src/cli/lib/history-tracker.d.ts.map +1 -0
  271. package/dist/src/cli/lib/history-tracker.js +352 -0
  272. package/dist/src/cli/lib/history-tracker.js.map +1 -0
  273. package/dist/src/cli/lib/report-store.d.ts +1 -2
  274. package/dist/src/cli/lib/report-store.d.ts.map +1 -1
  275. package/dist/src/cli/lib/report-store.js +65 -87
  276. package/dist/src/cli/lib/report-store.js.map +1 -1
  277. package/dist/src/cli/lib/simulation-registry.d.ts +1 -1
  278. package/dist/src/cli/lib/simulation-registry.d.ts.map +1 -1
  279. package/dist/src/cli/lib/simulation-registry.js +0 -1
  280. package/dist/src/cli/lib/simulation-registry.js.map +1 -1
  281. package/dist/src/cli/lib/simulation-runner.d.ts +4 -41
  282. package/dist/src/cli/lib/simulation-runner.d.ts.map +1 -1
  283. package/dist/src/cli/lib/simulation-runner.js +6 -251
  284. package/dist/src/cli/lib/simulation-runner.js.map +1 -1
  285. package/dist/src/consensus/RaftConsensus.d.ts +220 -0
  286. package/dist/src/consensus/RaftConsensus.d.ts.map +1 -0
  287. package/dist/src/consensus/RaftConsensus.js +762 -0
  288. package/dist/src/consensus/RaftConsensus.js.map +1 -0
  289. package/dist/src/controllers/AttentionService.d.ts +80 -1
  290. package/dist/src/controllers/AttentionService.d.ts.map +1 -1
  291. package/dist/src/controllers/AttentionService.js +349 -16
  292. package/dist/src/controllers/AttentionService.js.map +1 -1
  293. package/dist/src/controllers/CausalMemoryGraph.d.ts +8 -33
  294. package/dist/src/controllers/CausalMemoryGraph.d.ts.map +1 -1
  295. package/dist/src/controllers/CausalMemoryGraph.js +16 -93
  296. package/dist/src/controllers/CausalMemoryGraph.js.map +1 -1
  297. package/dist/src/controllers/CausalRecall.d.ts +3 -6
  298. package/dist/src/controllers/CausalRecall.d.ts.map +1 -1
  299. package/dist/src/controllers/CausalRecall.js +8 -14
  300. package/dist/src/controllers/CausalRecall.js.map +1 -1
  301. package/dist/src/controllers/ContextSynthesizer.d.ts +1 -1
  302. package/dist/src/controllers/ContextSynthesizer.d.ts.map +1 -1
  303. package/dist/src/controllers/EmbeddingService.d.ts.map +1 -1
  304. package/dist/src/controllers/EmbeddingService.js +3 -10
  305. package/dist/src/controllers/EmbeddingService.js.map +1 -1
  306. package/dist/src/controllers/EnhancedEmbeddingService.d.ts +0 -4
  307. package/dist/src/controllers/EnhancedEmbeddingService.d.ts.map +1 -1
  308. package/dist/src/controllers/EnhancedEmbeddingService.js +3 -10
  309. package/dist/src/controllers/EnhancedEmbeddingService.js.map +1 -1
  310. package/dist/src/controllers/ExplainableRecall.d.ts +6 -5
  311. package/dist/src/controllers/ExplainableRecall.d.ts.map +1 -1
  312. package/dist/src/controllers/ExplainableRecall.js +13 -21
  313. package/dist/src/controllers/ExplainableRecall.js.map +1 -1
  314. package/dist/src/controllers/HNSWIndex.d.ts +7 -24
  315. package/dist/src/controllers/HNSWIndex.d.ts.map +1 -1
  316. package/dist/src/controllers/HNSWIndex.js +10 -89
  317. package/dist/src/controllers/HNSWIndex.js.map +1 -1
  318. package/dist/src/controllers/HierarchicalMemory.d.ts +197 -0
  319. package/dist/src/controllers/HierarchicalMemory.d.ts.map +1 -0
  320. package/dist/src/controllers/HierarchicalMemory.js +519 -0
  321. package/dist/src/controllers/HierarchicalMemory.js.map +1 -0
  322. package/dist/src/controllers/LearningSystem.d.ts +27 -106
  323. package/dist/src/controllers/LearningSystem.d.ts.map +1 -1
  324. package/dist/src/controllers/LearningSystem.js +145 -39
  325. package/dist/src/controllers/LearningSystem.js.map +1 -1
  326. package/dist/src/controllers/MMRDiversityRanker.d.ts +1 -1
  327. package/dist/src/controllers/MMRDiversityRanker.d.ts.map +1 -1
  328. package/dist/src/controllers/MemoryConsolidation.d.ts +142 -0
  329. package/dist/src/controllers/MemoryConsolidation.d.ts.map +1 -0
  330. package/dist/src/controllers/MemoryConsolidation.js +479 -0
  331. package/dist/src/controllers/MemoryConsolidation.js.map +1 -0
  332. package/dist/src/controllers/MetadataFilter.d.ts +3 -3
  333. package/dist/src/controllers/MetadataFilter.d.ts.map +1 -1
  334. package/dist/src/controllers/MetadataFilter.js +6 -9
  335. package/dist/src/controllers/MetadataFilter.js.map +1 -1
  336. package/dist/src/controllers/NightlyLearner.d.ts +4 -9
  337. package/dist/src/controllers/NightlyLearner.d.ts.map +1 -1
  338. package/dist/src/controllers/NightlyLearner.js +9 -28
  339. package/dist/src/controllers/NightlyLearner.js.map +1 -1
  340. package/dist/src/controllers/QUICClient.d.ts +2 -50
  341. package/dist/src/controllers/QUICClient.d.ts.map +1 -1
  342. package/dist/src/controllers/QUICClient.js +3 -193
  343. package/dist/src/controllers/QUICClient.js.map +1 -1
  344. package/dist/src/controllers/QUICConnection.d.ts +122 -0
  345. package/dist/src/controllers/QUICConnection.d.ts.map +1 -0
  346. package/dist/src/controllers/QUICConnection.js +329 -0
  347. package/dist/src/controllers/QUICConnection.js.map +1 -0
  348. package/dist/src/controllers/QUICConnectionPool.d.ts +83 -0
  349. package/dist/src/controllers/QUICConnectionPool.d.ts.map +1 -0
  350. package/dist/src/controllers/QUICConnectionPool.js +256 -0
  351. package/dist/src/controllers/QUICConnectionPool.js.map +1 -0
  352. package/dist/src/controllers/QUICServer.d.ts +4 -4
  353. package/dist/src/controllers/QUICServer.d.ts.map +1 -1
  354. package/dist/src/controllers/QUICServer.js +14 -22
  355. package/dist/src/controllers/QUICServer.js.map +1 -1
  356. package/dist/src/controllers/QUICStreamManager.d.ts +114 -0
  357. package/dist/src/controllers/QUICStreamManager.d.ts.map +1 -0
  358. package/dist/src/controllers/QUICStreamManager.js +267 -0
  359. package/dist/src/controllers/QUICStreamManager.js.map +1 -0
  360. package/dist/src/controllers/ReasoningBank.d.ts +4 -14
  361. package/dist/src/controllers/ReasoningBank.d.ts.map +1 -1
  362. package/dist/src/controllers/ReasoningBank.js +46 -59
  363. package/dist/src/controllers/ReasoningBank.js.map +1 -1
  364. package/dist/src/controllers/ReflexionMemory.d.ts +7 -80
  365. package/dist/src/controllers/ReflexionMemory.d.ts.map +1 -1
  366. package/dist/src/controllers/ReflexionMemory.js +214 -372
  367. package/dist/src/controllers/ReflexionMemory.js.map +1 -1
  368. package/dist/src/controllers/SkillLibrary.d.ts +7 -37
  369. package/dist/src/controllers/SkillLibrary.d.ts.map +1 -1
  370. package/dist/src/controllers/SkillLibrary.js +96 -212
  371. package/dist/src/controllers/SkillLibrary.js.map +1 -1
  372. package/dist/src/controllers/StreamingEmbeddingService.d.ts +82 -0
  373. package/dist/src/controllers/StreamingEmbeddingService.d.ts.map +1 -0
  374. package/dist/src/controllers/StreamingEmbeddingService.js +243 -0
  375. package/dist/src/controllers/StreamingEmbeddingService.js.map +1 -0
  376. package/dist/src/controllers/SyncCoordinator.d.ts +3 -2
  377. package/dist/src/controllers/SyncCoordinator.d.ts.map +1 -1
  378. package/dist/src/controllers/SyncCoordinator.js +5 -117
  379. package/dist/src/controllers/SyncCoordinator.js.map +1 -1
  380. package/dist/src/controllers/WASMVectorSearch.d.ts +37 -18
  381. package/dist/src/controllers/WASMVectorSearch.d.ts.map +1 -1
  382. package/dist/src/controllers/WASMVectorSearch.js +95 -150
  383. package/dist/src/controllers/WASMVectorSearch.js.map +1 -1
  384. package/dist/src/controllers/frontier-index.d.ts +14 -0
  385. package/dist/src/controllers/frontier-index.d.ts.map +1 -0
  386. package/dist/src/controllers/frontier-index.js +10 -0
  387. package/dist/src/controllers/frontier-index.js.map +1 -0
  388. package/dist/src/controllers/index.cjs +6 -0
  389. package/dist/src/controllers/index.d.ts +27 -8
  390. package/dist/src/controllers/index.d.ts.map +1 -1
  391. package/dist/src/controllers/index.js +18 -6
  392. package/dist/src/controllers/index.js.map +1 -1
  393. package/dist/src/core/AgentDB.d.ts +21 -60
  394. package/dist/src/core/AgentDB.d.ts.map +1 -1
  395. package/dist/src/core/AgentDB.js +123 -133
  396. package/dist/src/core/AgentDB.js.map +1 -1
  397. package/dist/src/db-fallback.d.ts +1 -10
  398. package/dist/src/db-fallback.d.ts.map +1 -1
  399. package/dist/src/db-fallback.js +4 -171
  400. package/dist/src/db-fallback.js.map +1 -1
  401. package/dist/src/db-test.d.ts +13 -0
  402. package/dist/src/db-test.d.ts.map +1 -0
  403. package/dist/src/db-test.js +55 -0
  404. package/dist/src/db-test.js.map +1 -0
  405. package/dist/src/db-unified.d.ts +76 -0
  406. package/dist/src/db-unified.d.ts.map +1 -0
  407. package/dist/src/db-unified.js +279 -0
  408. package/dist/src/db-unified.js.map +1 -0
  409. package/dist/src/examples/quic-sync-example.d.ts +9 -0
  410. package/dist/src/examples/quic-sync-example.d.ts.map +1 -0
  411. package/dist/src/examples/quic-sync-example.js +169 -0
  412. package/dist/src/examples/quic-sync-example.js.map +1 -0
  413. package/dist/src/examples/wasm-vector-usage.d.ts +12 -0
  414. package/dist/src/examples/wasm-vector-usage.d.ts.map +1 -0
  415. package/dist/src/examples/wasm-vector-usage.js +190 -0
  416. package/dist/src/examples/wasm-vector-usage.js.map +1 -0
  417. package/dist/src/index.cjs +6 -0
  418. package/dist/src/index.d.ts +16 -38
  419. package/dist/src/index.d.ts.map +1 -1
  420. package/dist/src/index.js +13 -46
  421. package/dist/src/index.js.map +1 -1
  422. package/dist/src/mcp/agentdb-mcp-server.js +63 -219
  423. package/dist/src/mcp/agentdb-mcp-server.js.map +1 -1
  424. package/dist/src/mcp/learning-tools-handlers.d.ts +16 -0
  425. package/dist/src/mcp/learning-tools-handlers.d.ts.map +1 -0
  426. package/dist/src/mcp/learning-tools-handlers.js +105 -0
  427. package/dist/src/mcp/learning-tools-handlers.js.map +1 -0
  428. package/dist/src/optimizations/BatchOperations.d.ts +5 -52
  429. package/dist/src/optimizations/BatchOperations.d.ts.map +1 -1
  430. package/dist/src/optimizations/BatchOperations.js +33 -186
  431. package/dist/src/optimizations/BatchOperations.js.map +1 -1
  432. package/dist/src/optimizations/QueryOptimizer.d.ts +4 -4
  433. package/dist/src/optimizations/QueryOptimizer.d.ts.map +1 -1
  434. package/dist/src/optimizations/QueryOptimizer.js +1 -3
  435. package/dist/src/optimizations/QueryOptimizer.js.map +1 -1
  436. package/dist/src/optimizations/RVFOptimizer.d.ts +226 -0
  437. package/dist/src/optimizations/RVFOptimizer.d.ts.map +1 -0
  438. package/dist/src/optimizations/RVFOptimizer.js +541 -0
  439. package/dist/src/optimizations/RVFOptimizer.js.map +1 -0
  440. package/dist/src/optimizations/ToolCache.d.ts +4 -4
  441. package/dist/src/optimizations/ToolCache.d.ts.map +1 -1
  442. package/dist/src/optimizations/ToolCache.js.map +1 -1
  443. package/dist/src/optimizations/index.d.ts +3 -1
  444. package/dist/src/optimizations/index.d.ts.map +1 -1
  445. package/dist/src/optimizations/index.js +1 -0
  446. package/dist/src/optimizations/index.js.map +1 -1
  447. package/dist/src/security/AttestationLog.d.ts +70 -0
  448. package/dist/src/security/AttestationLog.d.ts.map +1 -0
  449. package/dist/src/security/AttestationLog.js +174 -0
  450. package/dist/src/security/AttestationLog.js.map +1 -0
  451. package/dist/src/security/MutationGuard.d.ts +83 -0
  452. package/dist/src/security/MutationGuard.d.ts.map +1 -0
  453. package/dist/src/security/MutationGuard.js +364 -0
  454. package/dist/src/security/MutationGuard.js.map +1 -0
  455. package/dist/src/security/index.cjs +6 -0
  456. package/dist/src/security/index.d.ts +15 -0
  457. package/dist/src/security/index.d.ts.map +1 -0
  458. package/dist/src/security/index.js +18 -0
  459. package/dist/src/security/index.js.map +1 -0
  460. package/dist/src/security/input-validation.d.ts +12 -12
  461. package/dist/src/security/input-validation.d.ts.map +1 -1
  462. package/dist/src/security/input-validation.js +0 -1
  463. package/dist/src/security/input-validation.js.map +1 -1
  464. package/dist/src/security/limits.d.ts +150 -0
  465. package/dist/src/security/limits.d.ts.map +1 -0
  466. package/dist/src/security/limits.js +288 -0
  467. package/dist/src/security/limits.js.map +1 -0
  468. package/dist/src/security/path-security.d.ts +100 -0
  469. package/dist/src/security/path-security.d.ts.map +1 -0
  470. package/dist/src/security/path-security.js +337 -0
  471. package/dist/src/security/path-security.js.map +1 -0
  472. package/dist/src/security/validation.d.ts +95 -0
  473. package/dist/src/security/validation.d.ts.map +1 -0
  474. package/dist/src/security/validation.js +315 -0
  475. package/dist/src/security/validation.js.map +1 -0
  476. package/dist/src/services/GNNService.d.ts +173 -0
  477. package/dist/src/services/GNNService.d.ts.map +1 -0
  478. package/dist/src/services/GNNService.js +639 -0
  479. package/dist/src/services/GNNService.js.map +1 -0
  480. package/dist/src/services/GraphTransformerService.d.ts +80 -0
  481. package/dist/src/services/GraphTransformerService.d.ts.map +1 -0
  482. package/dist/src/services/GraphTransformerService.js +369 -0
  483. package/dist/src/services/GraphTransformerService.js.map +1 -0
  484. package/dist/src/services/LLMRouter.d.ts +7 -61
  485. package/dist/src/services/LLMRouter.d.ts.map +1 -1
  486. package/dist/src/services/LLMRouter.js +25 -295
  487. package/dist/src/services/LLMRouter.js.map +1 -1
  488. package/dist/src/services/SemanticRouter.d.ts +83 -0
  489. package/dist/src/services/SemanticRouter.d.ts.map +1 -0
  490. package/dist/src/services/SemanticRouter.js +160 -0
  491. package/dist/src/services/SemanticRouter.js.map +1 -0
  492. package/dist/src/services/SonaTrajectoryService.d.ts +224 -0
  493. package/dist/src/services/SonaTrajectoryService.d.ts.map +1 -0
  494. package/dist/src/services/SonaTrajectoryService.js +539 -0
  495. package/dist/src/services/SonaTrajectoryService.js.map +1 -0
  496. package/dist/src/types/attention.d.ts +249 -0
  497. package/dist/src/types/attention.d.ts.map +1 -0
  498. package/dist/src/types/attention.js +43 -0
  499. package/dist/src/types/attention.js.map +1 -0
  500. package/dist/src/types/quic.d.ts +518 -0
  501. package/dist/src/types/quic.d.ts.map +1 -0
  502. package/dist/src/types/quic.js +272 -0
  503. package/dist/src/types/quic.js.map +1 -0
  504. package/dist/src/utils/LegacyAttentionAdapter.d.ts +93 -0
  505. package/dist/src/utils/LegacyAttentionAdapter.d.ts.map +1 -0
  506. package/dist/src/utils/LegacyAttentionAdapter.js +241 -0
  507. package/dist/src/utils/LegacyAttentionAdapter.js.map +1 -0
  508. package/dist/src/utils/attention-metrics.d.ts +76 -0
  509. package/dist/src/utils/attention-metrics.d.ts.map +1 -0
  510. package/dist/src/utils/attention-metrics.js +178 -0
  511. package/dist/src/utils/attention-metrics.js.map +1 -0
  512. package/dist/src/utils/vector-math.d.ts +29 -0
  513. package/dist/src/utils/vector-math.d.ts.map +1 -0
  514. package/dist/src/utils/vector-math.js +66 -0
  515. package/dist/src/utils/vector-math.js.map +1 -0
  516. package/package.json +75 -61
  517. package/LICENSE +0 -21
  518. package/dist/src/backends/rvf/AdaptiveIndexTuner.d.ts +0 -175
  519. package/dist/src/backends/rvf/AdaptiveIndexTuner.d.ts.map +0 -1
  520. package/dist/src/backends/rvf/AdaptiveIndexTuner.js +0 -559
  521. package/dist/src/backends/rvf/AdaptiveIndexTuner.js.map +0 -1
  522. package/dist/src/backends/rvf/ContrastiveTrainer.d.ts +0 -148
  523. package/dist/src/backends/rvf/ContrastiveTrainer.d.ts.map +0 -1
  524. package/dist/src/backends/rvf/ContrastiveTrainer.js +0 -438
  525. package/dist/src/backends/rvf/ContrastiveTrainer.js.map +0 -1
  526. package/dist/src/backends/rvf/FederatedSessionManager.d.ts +0 -211
  527. package/dist/src/backends/rvf/FederatedSessionManager.d.ts.map +0 -1
  528. package/dist/src/backends/rvf/FederatedSessionManager.js +0 -389
  529. package/dist/src/backends/rvf/FederatedSessionManager.js.map +0 -1
  530. package/dist/src/backends/rvf/FilterBuilder.d.ts +0 -136
  531. package/dist/src/backends/rvf/FilterBuilder.d.ts.map +0 -1
  532. package/dist/src/backends/rvf/FilterBuilder.js +0 -157
  533. package/dist/src/backends/rvf/FilterBuilder.js.map +0 -1
  534. package/dist/src/backends/rvf/NativeAccelerator.d.ts +0 -140
  535. package/dist/src/backends/rvf/NativeAccelerator.d.ts.map +0 -1
  536. package/dist/src/backends/rvf/NativeAccelerator.js +0 -630
  537. package/dist/src/backends/rvf/NativeAccelerator.js.map +0 -1
  538. package/dist/src/backends/rvf/RvfBackend.d.ts +0 -194
  539. package/dist/src/backends/rvf/RvfBackend.d.ts.map +0 -1
  540. package/dist/src/backends/rvf/RvfBackend.js +0 -607
  541. package/dist/src/backends/rvf/RvfBackend.js.map +0 -1
  542. package/dist/src/backends/rvf/RvfSolver.d.ts +0 -175
  543. package/dist/src/backends/rvf/RvfSolver.d.ts.map +0 -1
  544. package/dist/src/backends/rvf/RvfSolver.js +0 -176
  545. package/dist/src/backends/rvf/RvfSolver.js.map +0 -1
  546. package/dist/src/backends/rvf/SelfLearningRvfBackend.d.ts +0 -143
  547. package/dist/src/backends/rvf/SelfLearningRvfBackend.d.ts.map +0 -1
  548. package/dist/src/backends/rvf/SelfLearningRvfBackend.js +0 -569
  549. package/dist/src/backends/rvf/SelfLearningRvfBackend.js.map +0 -1
  550. package/dist/src/backends/rvf/SemanticQueryRouter.d.ts +0 -128
  551. package/dist/src/backends/rvf/SemanticQueryRouter.d.ts.map +0 -1
  552. package/dist/src/backends/rvf/SemanticQueryRouter.js +0 -415
  553. package/dist/src/backends/rvf/SemanticQueryRouter.js.map +0 -1
  554. package/dist/src/backends/rvf/SimdFallbacks.d.ts +0 -25
  555. package/dist/src/backends/rvf/SimdFallbacks.d.ts.map +0 -1
  556. package/dist/src/backends/rvf/SimdFallbacks.js +0 -287
  557. package/dist/src/backends/rvf/SimdFallbacks.js.map +0 -1
  558. package/dist/src/backends/rvf/SolverBandit.d.ts +0 -100
  559. package/dist/src/backends/rvf/SolverBandit.d.ts.map +0 -1
  560. package/dist/src/backends/rvf/SolverBandit.js +0 -216
  561. package/dist/src/backends/rvf/SolverBandit.js.map +0 -1
  562. package/dist/src/backends/rvf/SonaLearningBackend.d.ts +0 -157
  563. package/dist/src/backends/rvf/SonaLearningBackend.d.ts.map +0 -1
  564. package/dist/src/backends/rvf/SonaLearningBackend.js +0 -283
  565. package/dist/src/backends/rvf/SonaLearningBackend.js.map +0 -1
  566. package/dist/src/backends/rvf/SqlJsRvfBackend.d.ts +0 -77
  567. package/dist/src/backends/rvf/SqlJsRvfBackend.d.ts.map +0 -1
  568. package/dist/src/backends/rvf/SqlJsRvfBackend.js +0 -382
  569. package/dist/src/backends/rvf/SqlJsRvfBackend.js.map +0 -1
  570. package/dist/src/backends/rvf/WasmStoreBridge.d.ts +0 -27
  571. package/dist/src/backends/rvf/WasmStoreBridge.d.ts.map +0 -1
  572. package/dist/src/backends/rvf/WasmStoreBridge.js +0 -87
  573. package/dist/src/backends/rvf/WasmStoreBridge.js.map +0 -1
  574. package/dist/src/backends/rvf/validation.d.ts +0 -20
  575. package/dist/src/backends/rvf/validation.d.ts.map +0 -1
  576. package/dist/src/backends/rvf/validation.js +0 -78
  577. package/dist/src/backends/rvf/validation.js.map +0 -1
  578. package/dist/src/benchmark/BenchmarkSuite.d.ts +0 -318
  579. package/dist/src/benchmark/BenchmarkSuite.d.ts.map +0 -1
  580. package/dist/src/benchmark/BenchmarkSuite.js +0 -986
  581. package/dist/src/benchmark/BenchmarkSuite.js.map +0 -1
  582. package/dist/src/benchmark/index.d.ts +0 -29
  583. package/dist/src/benchmark/index.d.ts.map +0 -1
  584. package/dist/src/benchmark/index.js +0 -39
  585. package/dist/src/benchmark/index.js.map +0 -1
  586. package/dist/src/cli/commands/hyperbolic.d.ts +0 -11
  587. package/dist/src/cli/commands/hyperbolic.d.ts.map +0 -1
  588. package/dist/src/cli/commands/hyperbolic.js +0 -428
  589. package/dist/src/cli/commands/hyperbolic.js.map +0 -1
  590. package/dist/src/cli/commands/learn.d.ts +0 -11
  591. package/dist/src/cli/commands/learn.d.ts.map +0 -1
  592. package/dist/src/cli/commands/learn.js +0 -404
  593. package/dist/src/cli/commands/learn.js.map +0 -1
  594. package/dist/src/cli/commands/route.d.ts +0 -11
  595. package/dist/src/cli/commands/route.d.ts.map +0 -1
  596. package/dist/src/cli/commands/route.js +0 -414
  597. package/dist/src/cli/commands/route.js.map +0 -1
  598. package/dist/src/cli/commands/rvf.d.ts +0 -21
  599. package/dist/src/cli/commands/rvf.d.ts.map +0 -1
  600. package/dist/src/cli/commands/rvf.js +0 -448
  601. package/dist/src/cli/commands/rvf.js.map +0 -1
  602. package/dist/src/cli/tests/agentdb-cli.test.d.ts +0 -8
  603. package/dist/src/cli/tests/agentdb-cli.test.d.ts.map +0 -1
  604. package/dist/src/cli/tests/agentdb-cli.test.js +0 -50
  605. package/dist/src/cli/tests/agentdb-cli.test.js.map +0 -1
  606. package/dist/src/cli/tests/attention-cli.test.d.ts +0 -5
  607. package/dist/src/cli/tests/attention-cli.test.d.ts.map +0 -1
  608. package/dist/src/cli/tests/attention-cli.test.js +0 -257
  609. package/dist/src/cli/tests/attention-cli.test.js.map +0 -1
  610. package/dist/src/compatibility/DeprecationWarnings.d.ts +0 -54
  611. package/dist/src/compatibility/DeprecationWarnings.d.ts.map +0 -1
  612. package/dist/src/compatibility/DeprecationWarnings.js +0 -131
  613. package/dist/src/compatibility/DeprecationWarnings.js.map +0 -1
  614. package/dist/src/compatibility/MigrationUtilities.d.ts +0 -30
  615. package/dist/src/compatibility/MigrationUtilities.d.ts.map +0 -1
  616. package/dist/src/compatibility/MigrationUtilities.js +0 -184
  617. package/dist/src/compatibility/MigrationUtilities.js.map +0 -1
  618. package/dist/src/compatibility/V1toV2Adapter.d.ts +0 -76
  619. package/dist/src/compatibility/V1toV2Adapter.d.ts.map +0 -1
  620. package/dist/src/compatibility/V1toV2Adapter.js +0 -198
  621. package/dist/src/compatibility/V1toV2Adapter.js.map +0 -1
  622. package/dist/src/compatibility/VersionDetector.d.ts +0 -32
  623. package/dist/src/compatibility/VersionDetector.d.ts.map +0 -1
  624. package/dist/src/compatibility/VersionDetector.js +0 -144
  625. package/dist/src/compatibility/VersionDetector.js.map +0 -1
  626. package/dist/src/compatibility/index.d.ts +0 -11
  627. package/dist/src/compatibility/index.d.ts.map +0 -1
  628. package/dist/src/compatibility/index.js +0 -10
  629. package/dist/src/compatibility/index.js.map +0 -1
  630. package/dist/src/compatibility/types.d.ts +0 -103
  631. package/dist/src/compatibility/types.d.ts.map +0 -1
  632. package/dist/src/compatibility/types.js +0 -5
  633. package/dist/src/compatibility/types.js.map +0 -1
  634. package/dist/src/controllers/MemoryController.d.ts +0 -161
  635. package/dist/src/controllers/MemoryController.d.ts.map +0 -1
  636. package/dist/src/controllers/MemoryController.js +0 -290
  637. package/dist/src/controllers/MemoryController.js.map +0 -1
  638. package/dist/src/controllers/attention/CrossAttentionController.d.ts +0 -141
  639. package/dist/src/controllers/attention/CrossAttentionController.d.ts.map +0 -1
  640. package/dist/src/controllers/attention/CrossAttentionController.js +0 -325
  641. package/dist/src/controllers/attention/CrossAttentionController.js.map +0 -1
  642. package/dist/src/controllers/attention/MultiHeadAttentionController.d.ts +0 -137
  643. package/dist/src/controllers/attention/MultiHeadAttentionController.d.ts.map +0 -1
  644. package/dist/src/controllers/attention/MultiHeadAttentionController.js +0 -339
  645. package/dist/src/controllers/attention/MultiHeadAttentionController.js.map +0 -1
  646. package/dist/src/controllers/attention/SelfAttentionController.d.ts +0 -117
  647. package/dist/src/controllers/attention/SelfAttentionController.d.ts.map +0 -1
  648. package/dist/src/controllers/attention/SelfAttentionController.js +0 -205
  649. package/dist/src/controllers/attention/SelfAttentionController.js.map +0 -1
  650. package/dist/src/controllers/attention/index.d.ts +0 -15
  651. package/dist/src/controllers/attention/index.d.ts.map +0 -1
  652. package/dist/src/controllers/attention/index.js +0 -12
  653. package/dist/src/controllers/attention/index.js.map +0 -1
  654. package/dist/src/core/QueryCache.d.ts +0 -138
  655. package/dist/src/core/QueryCache.d.ts.map +0 -1
  656. package/dist/src/core/QueryCache.js +0 -313
  657. package/dist/src/core/QueryCache.js.map +0 -1
  658. package/dist/src/observability/index.d.ts +0 -8
  659. package/dist/src/observability/index.d.ts.map +0 -1
  660. package/dist/src/observability/index.js +0 -8
  661. package/dist/src/observability/index.js.map +0 -1
  662. package/dist/src/observability/integration.d.ts +0 -32
  663. package/dist/src/observability/integration.d.ts.map +0 -1
  664. package/dist/src/observability/integration.js +0 -157
  665. package/dist/src/observability/integration.js.map +0 -1
  666. package/dist/src/observability/telemetry.d.ts +0 -137
  667. package/dist/src/observability/telemetry.d.ts.map +0 -1
  668. package/dist/src/observability/telemetry.js +0 -420
  669. package/dist/src/observability/telemetry.js.map +0 -1
  670. package/dist/src/quantization/index.d.ts +0 -7
  671. package/dist/src/quantization/index.d.ts.map +0 -1
  672. package/dist/src/quantization/index.js +0 -15
  673. package/dist/src/quantization/index.js.map +0 -1
  674. package/dist/src/quantization/vector-quantization.d.ts +0 -388
  675. package/dist/src/quantization/vector-quantization.d.ts.map +0 -1
  676. package/dist/src/quantization/vector-quantization.js +0 -1136
  677. package/dist/src/quantization/vector-quantization.js.map +0 -1
  678. package/dist/src/search/HybridSearch.d.ts +0 -311
  679. package/dist/src/search/HybridSearch.d.ts.map +0 -1
  680. package/dist/src/search/HybridSearch.js +0 -712
  681. package/dist/src/search/HybridSearch.js.map +0 -1
  682. package/dist/src/search/index.d.ts +0 -12
  683. package/dist/src/search/index.d.ts.map +0 -1
  684. package/dist/src/search/index.js +0 -16
  685. package/dist/src/search/index.js.map +0 -1
  686. package/dist/src/services/AttentionService.d.ts +0 -303
  687. package/dist/src/services/AttentionService.d.ts.map +0 -1
  688. package/dist/src/services/AttentionService.js +0 -1167
  689. package/dist/src/services/AttentionService.js.map +0 -1
  690. package/dist/src/simd/index.d.ts +0 -9
  691. package/dist/src/simd/index.d.ts.map +0 -1
  692. package/dist/src/simd/index.js +0 -27
  693. package/dist/src/simd/index.js.map +0 -1
  694. package/dist/src/simd/simd-vector-ops.d.ts +0 -332
  695. package/dist/src/simd/simd-vector-ops.d.ts.map +0 -1
  696. package/dist/src/simd/simd-vector-ops.js +0 -947
  697. package/dist/src/simd/simd-vector-ops.js.map +0 -1
  698. package/dist/src/tests/attention-service.test.d.ts +0 -7
  699. package/dist/src/tests/attention-service.test.d.ts.map +0 -1
  700. package/dist/src/tests/attention-service.test.js +0 -401
  701. package/dist/src/tests/attention-service.test.js.map +0 -1
  702. package/dist/src/tests/integration/compatibility/backwards-compat.integration.test.d.ts +0 -7
  703. package/dist/src/tests/integration/compatibility/backwards-compat.integration.test.d.ts.map +0 -1
  704. package/dist/src/tests/integration/compatibility/backwards-compat.integration.test.js +0 -283
  705. package/dist/src/tests/integration/compatibility/backwards-compat.integration.test.js.map +0 -1
  706. package/dist/src/tests/query-cache.test.d.ts +0 -7
  707. package/dist/src/tests/query-cache.test.d.ts.map +0 -1
  708. package/dist/src/tests/query-cache.test.js +0 -343
  709. package/dist/src/tests/query-cache.test.js.map +0 -1
  710. package/dist/src/tests/ruvector-integration.test.d.ts +0 -14
  711. package/dist/src/tests/ruvector-integration.test.d.ts.map +0 -1
  712. package/dist/src/tests/ruvector-integration.test.js +0 -1156
  713. package/dist/src/tests/ruvector-integration.test.js.map +0 -1
  714. package/dist/src/tests/unit/auth/crypto.utils.test.d.ts +0 -6
  715. package/dist/src/tests/unit/auth/crypto.utils.test.d.ts.map +0 -1
  716. package/dist/src/tests/unit/auth/crypto.utils.test.js +0 -310
  717. package/dist/src/tests/unit/auth/crypto.utils.test.js.map +0 -1
  718. package/dist/src/tests/unit/compatibility/deprecation-warnings.test.d.ts +0 -5
  719. package/dist/src/tests/unit/compatibility/deprecation-warnings.test.d.ts.map +0 -1
  720. package/dist/src/tests/unit/compatibility/deprecation-warnings.test.js +0 -207
  721. package/dist/src/tests/unit/compatibility/deprecation-warnings.test.js.map +0 -1
  722. package/dist/src/tests/unit/compatibility/migration-utils.test.d.ts +0 -5
  723. package/dist/src/tests/unit/compatibility/migration-utils.test.d.ts.map +0 -1
  724. package/dist/src/tests/unit/compatibility/migration-utils.test.js +0 -264
  725. package/dist/src/tests/unit/compatibility/migration-utils.test.js.map +0 -1
  726. package/dist/src/tests/unit/compatibility/v1-adapter.test.d.ts +0 -7
  727. package/dist/src/tests/unit/compatibility/v1-adapter.test.d.ts.map +0 -1
  728. package/dist/src/tests/unit/compatibility/v1-adapter.test.js +0 -228
  729. package/dist/src/tests/unit/compatibility/v1-adapter.test.js.map +0 -1
  730. package/dist/src/tests/unit/compatibility/version-detector.test.d.ts +0 -10
  731. package/dist/src/tests/unit/compatibility/version-detector.test.d.ts.map +0 -1
  732. package/dist/src/tests/unit/compatibility/version-detector.test.js +0 -162
  733. package/dist/src/tests/unit/compatibility/version-detector.test.js.map +0 -1
  734. package/dist/src/tests/vector-quantization.test.d.ts +0 -5
  735. package/dist/src/tests/vector-quantization.test.d.ts.map +0 -1
  736. package/dist/src/tests/vector-quantization.test.js +0 -338
  737. package/dist/src/tests/vector-quantization.test.js.map +0 -1
  738. package/dist/src/tests/wasm-vector-search.test.d.ts +0 -7
  739. package/dist/src/tests/wasm-vector-search.test.d.ts.map +0 -1
  740. package/dist/src/tests/wasm-vector-search.test.js +0 -193
  741. package/dist/src/tests/wasm-vector-search.test.js.map +0 -1
  742. package/dist/src/types/database.types.d.ts +0 -275
  743. package/dist/src/types/database.types.d.ts.map +0 -1
  744. package/dist/src/types/database.types.js +0 -57
  745. package/dist/src/types/database.types.js.map +0 -1
  746. package/dist/src/utils/chalk-fallback.d.ts +0 -3
  747. package/dist/src/utils/chalk-fallback.d.ts.map +0 -1
  748. package/dist/src/utils/chalk-fallback.js +0 -20
  749. package/dist/src/utils/chalk-fallback.js.map +0 -1
  750. package/dist/src/utils/crypto.utils.d.ts +0 -122
  751. package/dist/src/utils/crypto.utils.d.ts.map +0 -1
  752. package/dist/src/utils/crypto.utils.js +0 -296
  753. package/dist/src/utils/crypto.utils.js.map +0 -1
  754. package/dist/src/utils/similarity.d.ts +0 -11
  755. package/dist/src/utils/similarity.d.ts.map +0 -1
  756. package/dist/src/utils/similarity.js +0 -25
  757. package/dist/src/utils/similarity.js.map +0 -1
  758. package/dist/src/wasm-loader.d.ts +0 -67
  759. package/dist/src/wasm-loader.d.ts.map +0 -1
  760. package/dist/src/wasm-loader.js +0 -78
  761. package/dist/src/wasm-loader.js.map +0 -1
  762. package/dist/src/wrappers/agentdb-fast.d.ts +0 -139
  763. package/dist/src/wrappers/agentdb-fast.d.ts.map +0 -1
  764. package/dist/src/wrappers/agentdb-fast.js +0 -316
  765. package/dist/src/wrappers/agentdb-fast.js.map +0 -1
  766. package/dist/src/wrappers/attention-fallbacks.d.ts +0 -351
  767. package/dist/src/wrappers/attention-fallbacks.d.ts.map +0 -1
  768. package/dist/src/wrappers/attention-fallbacks.js +0 -1487
  769. package/dist/src/wrappers/attention-fallbacks.js.map +0 -1
  770. package/dist/src/wrappers/embedding-service.d.ts +0 -117
  771. package/dist/src/wrappers/embedding-service.d.ts.map +0 -1
  772. package/dist/src/wrappers/embedding-service.js +0 -376
  773. package/dist/src/wrappers/embedding-service.js.map +0 -1
  774. package/dist/src/wrappers/gnn-wrapper.d.ts +0 -71
  775. package/dist/src/wrappers/gnn-wrapper.d.ts.map +0 -1
  776. package/dist/src/wrappers/gnn-wrapper.js +0 -240
  777. package/dist/src/wrappers/gnn-wrapper.js.map +0 -1
  778. package/dist/src/wrappers/index.d.ts +0 -48
  779. package/dist/src/wrappers/index.d.ts.map +0 -1
  780. package/dist/src/wrappers/index.js +0 -83
  781. package/dist/src/wrappers/index.js.map +0 -1
package/README.md CHANGED
@@ -1,2698 +1,344 @@
1
1
  # AgentDB v3
2
2
 
3
- > Intelligent agentic vector database learns from experience, optimizes itself, runs anywhere
3
+ > **Proof-gated graph intelligence for AI agents every mutation requires cryptographic proof**
4
4
 
5
5
  [![npm version](https://img.shields.io/npm/v/agentdb.svg?style=flat-square)](https://www.npmjs.com/package/agentdb)
6
6
  [![npm downloads](https://img.shields.io/npm/dm/agentdb.svg?style=flat-square)](https://www.npmjs.com/package/agentdb)
7
7
  [![License](https://img.shields.io/badge/license-MIT%20OR%20Apache--2.0-green?style=flat-square)](LICENSE)
8
8
  [![TypeScript](https://img.shields.io/badge/TypeScript-5.x-blue?style=flat-square&logo=typescript)](https://www.typescriptlang.org/)
9
- [![MCP Compatible](https://img.shields.io/badge/MCP-41%20tools-blueviolet?style=flat-square)](docs/guides/)
10
9
 
11
- ---
12
-
13
- ## What is AgentDB?
14
-
15
- **AgentDB is a vector database that gets smarter every time you use it.**
16
-
17
- Most vector databases store and retrieve embeddings. AgentDB does that too — 150x faster — but it also watches which results your AI agent actually used, learns from that feedback, and returns better results next time. Search quality improves by up to **36% automatically**, with zero manual tuning.
18
-
19
- Everything lives in a **single Cognitive Container** (`.rvf` file) — vectors, indexes, learning state, and a cryptographic audit trail. No external services. No API keys. No monthly bills.
20
-
21
- > **3 lines to self-learning search:**
22
- > ```typescript
23
- > const backend = await SelfLearningRvfBackend.create({ learning: true, storagePath: './my.rvf' });
24
- > const results = await backend.searchAsync(query, 10); // search
25
- > backend.recordFeedback('q1', 0.9); // learn — next search is smarter
26
- > ```
27
-
28
- ### Who is it for?
29
-
30
- | If you're building... | AgentDB gives you... |
31
- | --- | --- |
32
- | **A RAG chatbot** | Search that learns which documents actually answer user questions |
33
- | **A code review agent** | Pattern memory that remembers what worked across 1000s of reviews |
34
- | **A research assistant** | Skill library that builds reusable tools from successful strategies |
35
- | **An RL-powered agent** | 9 algorithms from Q-Learning to PPO, with bandit-guided algorithm selection and transfer learning |
36
- | **A Claude Code / MCP tool** | 41 tools that plug in with one command |
37
- | **An offline or edge app** | Full vector DB in the browser via WASM — no server needed |
38
- | **An enterprise platform** | JWT auth, API key rotation, Argon2id hashing, SOC2/GDPR audit logs |
39
-
40
- ---
41
-
42
- ## Features
43
-
44
- ### Intelligence
45
-
46
- | | |
47
- | --- | --- |
48
- | **Self-Learning Search** | Gets 36% better over time — learns from feedback, no manual tuning |
49
- | **Cognitive Memory** | 6 human-inspired patterns: learn from mistakes, build reusable skills, discover what causes what |
50
- | **Decision Intelligence** | Thompson Sampling bandit auto-tunes skill selection, pattern ranking, compression tiers, and RL algorithm choice |
51
- | **9 RL Algorithms** | Q-Learning, SARSA, DQN, PPO, Actor-Critic, Policy Gradient, Decision Transformer, MCTS, Model-Based RL |
52
- | **Hybrid Search** | BM25 keyword + vector with Reciprocal Rank Fusion — exact matches + semantic understanding |
53
- | **Graph Intelligence** | Cypher queries, causal reasoning, GNN 8-head attention (+12.4% recall) |
54
-
55
- ### Performance
56
-
57
- | | |
58
- | --- | --- |
59
- | **150x Faster** | 61us search with Rust+SIMD — 800x faster than Pinecone, 160x faster than Chroma |
60
- | **4 Backends** | Auto-selects best available: RuVector (Rust) > RVF > HNSWLib (C++) > sql.js (WASM) |
61
- | **Runs Anywhere** | Node.js, browsers (WASM), edge functions, fully offline |
62
- | **AgentDBFast** | 50-200x faster programmatic API — skip CLI overhead for production workloads |
63
-
64
- ### Storage & Data
65
-
66
- | | |
67
- | --- | --- |
68
- | **Cognitive Container (RVF)** | Single `.rvf` file — vectors, index, learning state, SHAKE-256 witness chain |
69
- | **COW Branching** | Instant copy-on-write branches for experiments, with full lineage tracking |
70
- | **Compression** | 5-tier auto-tiering (hot/warm/cool/cold/archive), scalar 8-bit/4-bit, product quantization |
71
- | **Metadata Filtering** | 10 MongoDB-style operators ($eq, $gt, $in, $contains, $exists, etc.) |
72
-
73
- ### Integration & Tools
74
-
75
- | | |
76
- | --- | --- |
77
- | **41 MCP Tools** | One command to connect to Claude Code, Cursor, or any MCP-compatible assistant |
78
- | **Chat UI** | `@agentdb/chat` — deploy a self-learning RAG chatbot in one line |
79
- | **LLM Router** | Auto-selects best provider: RuvLLM (local), OpenRouter (200+ models), Gemini, Claude, ONNX |
80
- | **Real-Time Sync** | QUIC transport, multi-instance replication, 4 conflict resolution strategies |
81
-
82
- ### Enterprise & Security
83
-
84
- | | |
85
- | --- | --- |
86
- | **Auth & Audit** | JWT tokens, Argon2id hashing, API key rotation, SOC2/GDPR/HIPAA logging |
87
- | **Security** | Input validation, XSS/injection prevention, Cypher sanitization, witness chain verification |
88
- | **Observability** | OpenTelemetry traces, Prometheus metrics, structured logging |
89
- | **Benchmarking** | 5 built-in benchmarks, custom benchmark classes, Markdown/JSON reports |
90
-
91
- > **Zero config, zero cost.** `npm install agentdb` and go — fully local, no API keys, no cloud fees.
92
-
93
- ### Install
94
-
95
- ```bash
96
- npm install agentdb # Latest stable (v2)
97
- npm install agentdb@alpha # Latest alpha (v3 — unified .rvf, self-learning, SolverBandit)
98
- ```
99
-
100
- ---
101
-
102
- ## Comparison
103
-
104
- > **61 microseconds.** That's 800x faster than Pinecone, 160x faster than Chroma, and the only vector database that learns from your usage and gets better over time.
105
-
106
- ### vs. Other Vector Databases
107
-
108
- #### Intelligence
10
+ AgentDB v3 is the first memory system built specifically for autonomous AI agents with **proof-gated mutations** — every state-changing operation requires a cryptographic proof before execution. Powered by `@ruvector/graph-transformer` with 8 verified graph modules, native Rust performance via NAPI-RS, and 82-byte attestations.
109
11
 
110
- | Feature | AgentDB v3 | Pinecone | Chroma | Weaviate | pgvector |
111
- | --- | --- | --- | --- | --- | --- |
112
- | Self-learning pipeline | SONA + contrastive + federated + bandit | No | No | No | No |
113
- | Reinforcement learning | 9 algorithms (Q-Learning to MCTS) | No | No | No | No |
114
- | Cognitive memory | 6 patterns | No | No | No | No |
115
- | Hybrid search | BM25 + vector (RRF fusion) | No | No | BM25 only | No |
116
- | Graph queries | Cypher | No | No | GraphQL | No |
12
+ ## What's New in v3
117
13
 
118
- #### Performance & Deployment
119
-
120
- | Feature | AgentDB v3 | Pinecone | Chroma | Weaviate | pgvector |
121
- | --- | --- | --- | --- | --- | --- |
122
- | Search latency | **61us** | ~50ms | ~10ms | ~5ms | ~2ms |
123
- | Runs offline | Full | No | Yes | Yes | Yes |
124
- | Browser (WASM) | Yes | No | No | No | No |
125
-
126
- #### Storage
127
-
128
- | Feature | AgentDB v3 | Pinecone | Chroma | Weaviate | pgvector |
129
- | --- | --- | --- | --- | --- | --- |
130
- | Cognitive Container | Single `.rvf` file + COW branching | No | No | No | No |
131
- | Monthly cost | **$0** | $70+ | $0 | $0+ | $0+ |
132
-
133
- #### Integration & Security
134
-
135
- | Feature | AgentDB v3 | Pinecone | Chroma | Weaviate | pgvector |
136
- | --- | --- | --- | --- | --- | --- |
137
- | MCP integration | 41 tools | No | No | No | No |
138
- | Auth & audit | JWT + Argon2id + compliance logs | No | No | No | No |
139
- | Local-first | Yes | Cloud only | Yes | Self-host | Postgres |
140
-
141
- ### Backend Performance
142
-
143
- | Backend | Latency | Recall@10 | Native | Best For |
144
- | --- | --- | --- | --- | --- |
145
- | **RuVector** (Rust + SIMD) | 61us | 96.8% | Yes | Production, high throughput |
146
- | **Cognitive Container** (RVF) | ~100us | 96.8% | Yes | Portable, branching, lineage |
147
- | **HNSWLib** (C++) | ~500us | 95%+ | Yes | Compatibility |
148
- | **sql.js** (WASM) | ~5ms | 90%+ | No | Zero-dependency fallback |
149
-
150
- AgentDB auto-selects the best available: RuVector > Cognitive Container (RVF) > HNSWLib > sql.js
151
-
152
- ---
14
+ - **Proof-Gated Mutations** — MutationGuard validates every insert, search, remove, save, and load with structural hashes and attestation tokens
15
+ - **8 Graph-Transformer Modules** — Sublinear attention, verified training, causal attention, Granger extraction, Hamiltonian dynamics, spiking attention, game-theoretic equilibrium, product manifold distance
16
+ - **AttestationLog** Append-only audit trail with cryptographic proofs for compliance and debugging
17
+ - **GuardedVectorBackend** Drop-in wrapper that enforces proof gates on any vector backend
18
+ - **21 Active Controllers** All cognitive memory patterns are production-ready with proof validation
19
+ - **Zero-Native Regression** Package size reduced from 50.1MB to 1.4MB by removing unused binaries
20
+ - **Browser Support** Runs in Node.js, browsers, edge functions, and MCP tools via WASM fallback
153
21
 
154
22
  ## Quick Start
155
23
 
156
24
  ```bash
157
- npm install agentdb
158
- ```
25
+ # Install v3 Alpha
26
+ npm install agentdb@v3
159
27
 
160
- ### Unified AgentDB (recommended)
28
+ # Or use stable v2
29
+ npm install agentdb@latest
30
+ ```
161
31
 
162
- The `AgentDB` class is the simplest way to use AgentDB. Everything — vectors, relational data, learning state — lives in a single `.rvf` file:
32
+ ## Basic Usage
163
33
 
164
34
  ```typescript
165
35
  import { AgentDB } from 'agentdb';
166
36
 
167
- const db = new AgentDB({ dbPath: './knowledge.rvf' });
37
+ // Initialize with proof-gated vectorBackend
38
+ const db = new AgentDB({
39
+ dbPath: './agent-memory.db',
40
+ dimension: 384,
41
+ vectorBackend: 'ruvector',
42
+ enableProofGate: true // Default: true in v3
43
+ });
44
+
168
45
  await db.initialize();
169
46
 
170
- // All controllers are ready — reflexion memory, skill library, causal graph
47
+ // Access controllers
171
48
  const reflexion = db.getController('reflexion');
172
- const skills = db.getController('skills');
173
- const causal = db.getController('causal');
49
+ const reasoning = db.getController('reasoning');
50
+ const causalGraph = db.getController('causalGraph');
174
51
 
175
- // Store an episode
52
+ // Check proof engine status
53
+ const guard = db.getMutationGuard();
54
+ console.log(guard?.getStats());
55
+ // Output: { engineType: 'native', proofsGenerated: 42, denials: 0 }
56
+
57
+ // Store episode with automatic proof generation
176
58
  await reflexion.storeEpisode({
177
59
  sessionId: 'session-1',
178
- task: 'Fix auth bug',
60
+ task: 'Debug authentication bug',
179
61
  reward: 0.95,
180
62
  success: true,
181
- critique: 'OAuth2 PKCE was the right approach',
63
+ critique: 'OAuth2 PKCE flow was more secure than basic flow',
64
+ input: 'Users cannot log in',
65
+ output: 'Working OAuth2 implementation'
182
66
  });
183
67
 
184
- // Create a reusable skill
185
- await skills.createSkill({
186
- name: 'jwt_auth',
187
- description: 'JWT authentication with refresh tokens',
188
- code: 'implementation...',
189
- successRate: 0.92,
68
+ // Search patterns (proof-validated)
69
+ const patterns = await reasoning.searchPatterns({
70
+ task: 'authentication security',
71
+ k: 10,
72
+ threshold: 0.7
190
73
  });
191
-
192
- // Save everything to one file and close
193
- await db.save();
194
- await db.close();
195
- ```
196
-
197
- **Configuration options:**
198
-
199
- | Option | Default | Description |
200
- | --- | --- | --- |
201
- | `dbPath` | `':memory:'` | Path to `.rvf` file (or `.db` for legacy mode) |
202
- | `vectorBackend` | `'rvf'` | Backend: `'rvf'` (unified), `'auto'`, `'ruvector'`, `'hnswlib'` |
203
- | `vectorDimension` | `384` | Embedding dimension (384 for MiniLM, 768 for bge-base) |
204
- | `forceWasm` | `false` | Force sql.js WASM even if better-sqlite3 is available |
205
- | `enableAttention` | `false` | Enable GNN attention mechanisms |
206
-
207
- **Controllers:** `db.getController('reflexion')` (ReflexionMemory), `db.getController('skills')` (SkillLibrary), `db.getController('causal')` (CausalMemoryGraph)
208
-
209
- ### CLI — try it in 10 seconds
210
-
211
- ```bash
212
- npx agentdb init # Initialize a new database
213
- npx agentdb doctor # Check system health
214
- npx agentdb rvf status ./store.rvf # Inspect a Cognitive Container
215
- npx agentdb rvf derive ./prod.rvf ./experiment.rvf # Branch for experiments (instant, COW)
216
- npx agentdb mcp start # Start MCP server (41 tools)
217
- npx @agentdb/chat serve --rvf ./kb.rvf --port 3000 # Launch chat UI
218
- ```
219
-
220
- <details>
221
- <summary><strong>Complete CLI Reference</strong> — 60+ commands across 8 categories</summary>
222
-
223
- #### Core
224
-
225
- ```bash
226
- npx agentdb init # Initialize database
227
- npx agentdb status # System status and diagnostics
228
- npx agentdb doctor [--fix] [--verbose] # Health check with auto-fix
229
- ```
230
-
231
- #### Cognitive Container (RVF) Management
232
-
233
- ```bash
234
- npx agentdb rvf status ./store.rvf # Container statistics
235
- npx agentdb rvf compact ./store.rvf # Reclaim space
236
- npx agentdb rvf derive ./src.rvf ./dst.rvf # COW branch
237
- npx agentdb rvf segments ./store.rvf # Segment introspection
238
- npx agentdb rvf detect # SDK availability
239
- ```
240
-
241
- #### Learning & Training
242
-
243
- ```bash
244
- npx agentdb learn --session <id> --train # Train a learning session
245
- npx agentdb learn --status # Learning system status
246
- ```
247
-
248
- #### Routing
249
-
250
- ```bash
251
- npx agentdb route --query "search term" # Test semantic routing
252
- npx agentdb route --list # Show learned intents
253
- ```
254
-
255
- #### Attention & Hyperbolic
256
-
257
- ```bash
258
- npx agentdb attention --benchmark # Attention performance test
259
- npx agentdb hyperbolic --test # Hyperbolic embedding test
260
74
  ```
261
75
 
262
- #### Simulation
263
-
264
- ```bash
265
- npx agentdb simulate hnsw --iterations 3 # HNSW optimization
266
- npx agentdb simulate attention --iterations 3 # GNN attention
267
- npx agentdb simulate self-organizing --days 30 # Self-healing
268
- npx agentdb simulate --wizard # Interactive wizard
269
- npx agentdb simulate --custom ./my-scenario.json # Custom simulation
270
- npx agentdb simulate --report ./output.md # Generate report
271
- ```
76
+ ## Architecture
272
77
 
273
- #### Migration & Import
78
+ AgentDB v3 introduces a 3-layer architecture:
274
79
 
275
- ```bash
276
- npx agentdb migrate --source ./old.db --target ./new.db # Full v1→v2 migration
277
- npx agentdb migrate --source ./v2.db --to v3 --rvf-path ./unified.rvf # v2→v3 unified .rvf
278
- npx agentdb migrate --to rvf --rvf-path ./out.rvf # Export to Cognitive Container
279
- npx agentdb migrate --dry-run --verbose # Preview changes
280
80
  ```
281
-
282
- #### MCP Server
283
-
284
- ```bash
285
- npx agentdb mcp start # Start MCP server (41 tools)
286
- npx agentdb mcp start --port 8080 # Custom port
81
+ ┌─────────────────────────────────────────────────────┐
82
+ │ Application Layer │
83
+ │ (ReasoningBank, ReflexionMemory, SkillLibrary) │
84
+ └─────────────────────────────────────────────────────┘
85
+
86
+ ┌─────────────────────────────────────────────────────┐
87
+ │ Proof Validation Layer │
88
+ │ MutationGuard → AttestationLog → GuardedBackend │
89
+ └─────────────────────────────────────────────────────┘
90
+
91
+ ┌─────────────────────────────────────────────────────┐
92
+ │ Backend Layer │
93
+ │ RuVector (native) → WASM → JavaScript │
94
+ └─────────────────────────────────────────────────────┘
287
95
  ```
288
96
 
289
- </details>
290
-
291
- ### Self-Learning Vector Search (the differentiator)
292
-
293
- Most vector databases return the same results no matter how many times you query them. AgentDB closes the loop: after every search, you tell it which results were actually useful. A contrastive trainer (InfoNCE + hard-negative mining) adjusts a lightweight LoRA adapter in under 1 ms, and EWC++ consolidation keeps old knowledge intact. Over 500 feedback cycles, recall jumps from 54% to 90% — automatically.
294
-
295
- ```typescript
296
- import { SelfLearningRvfBackend } from 'agentdb/backends/rvf/SelfLearningRvfBackend';
297
-
298
- // Create a self-learning Cognitive Container
299
- const backend = await SelfLearningRvfBackend.create({
300
- dimension: 384,
301
- metric: 'cosine',
302
- storagePath: './knowledge.rvf',
303
- learning: true, // enable the learning pipeline
304
- });
305
-
306
- // Insert documents
307
- await backend.insertAsync('doc-1', embedding, { title: 'Auth Guide' });
308
- await backend.insertAsync('doc-2', embedding2, { title: 'API Reference' });
309
-
310
- // Search — automatically routed through the learning pipeline
311
- const results = await backend.searchAsync(queryEmbedding, 10);
97
+ Every mutation flows through the proof validation layer:
312
98
 
313
- // Tell AgentDB which results were useful — this drives learning
314
- backend.recordFeedback('query-1', 0.95); // great result
315
- backend.recordFeedback('query-2', 0.2); // poor result
99
+ 1. **Application** calls `storeEpisode()` or `searchPatterns()`
100
+ 2. **MutationGuard** generates a proof (structural hash + attestation token)
101
+ 3. **AttestationLog** records the proof attempt
102
+ 4. **GuardedBackend** validates proof before executing native operation
103
+ 5. **Result** returns to application with proof certificate
316
104
 
317
- // Run a learning tick — trains the model, updates adapters
318
- await backend.tick();
319
- // Next search will be smarter based on your feedback
320
- ```
105
+ ## Key Features
321
106
 
322
- ### Cognitive Memory (pattern learning)
107
+ ### 1. Proof-Gated Mutations (ADR-060)
323
108
 
324
- Store and retrieve reasoning patterns your agent remembers what worked:
109
+ Every state mutation requires a cryptographic proof:
325
110
 
326
111
  ```typescript
327
- import { createDatabase, ReasoningBank, EmbeddingService } from 'agentdb';
328
-
329
- const db = await createDatabase('./agent-memory.db');
330
- const embedder = new EmbeddingService({ model: 'Xenova/all-MiniLM-L6-v2' });
331
- await embedder.initialize();
112
+ import { MutationGuard } from 'agentdb/security';
332
113
 
333
- const reasoningBank = new ReasoningBank(db, embedder);
334
-
335
- // Store what your agent learned
336
- await reasoningBank.storePattern({
337
- taskType: 'code_review',
338
- approach: 'Security-first analysis',
339
- successRate: 0.95,
114
+ const guard = new MutationGuard({
115
+ strictMode: true,
116
+ enableNative: true // Prefer native proofs
340
117
  });
341
118
 
342
- // Find similar successful patterns
343
- const patterns = await reasoningBank.searchPatterns({
344
- task: 'security code review',
345
- k: 10,
119
+ // Insert requires proof
120
+ const proof = guard.generateProof({
121
+ operation: 'insert',
122
+ vectorId: 'vec-123',
123
+ embedding: [0.1, 0.2, ...],
124
+ metadata: { source: 'reflexion' }
346
125
  });
347
- ```
348
-
349
- ### Unified Mode — Everything in One File
350
-
351
- In v3, `AgentDB` stores vectors, relational data, learning state, and metadata in a single `.rvf` file:
352
-
353
- ```typescript
354
- import { AgentDB } from 'agentdb';
355
-
356
- // Single-file mode is the default — no configuration needed
357
- const db = new AgentDB({ dbPath: './agent.rvf' });
358
- await db.initialize();
359
-
360
- // Access the underlying database for advanced queries
361
- const raw = db.database;
362
- const stats = raw.prepare('SELECT COUNT(*) as c FROM episodes').get();
363
-
364
- // Check mode
365
- console.log(db.isUnifiedMode); // true — everything in one .rvf file
366
- console.log(db.vectorBackendName); // 'rvf'
367
-
368
- // Save and reopen — all data persists in agent.rvf
369
- await db.save();
370
- await db.close();
371
-
372
- const db2 = new AgentDB({ dbPath: './agent.rvf' });
373
- await db2.initialize(); // All episodes, skills, vectors restored
374
- ```
375
-
376
- ### Chat UI (one-line deployment)
377
-
378
- Deploy a self-learning RAG chatbot over any Cognitive Container:
379
-
380
- ```bash
381
- npx @agentdb/chat serve --rvf ./kb.rvf --port 3000
382
- ```
383
-
384
- ---
385
-
386
- ## How the Learning Loop Works
387
-
388
- Every search automatically triggers a learning cycle. No configuration needed — just call `recordFeedback()` after using results:
389
-
390
- ```mermaid
391
- graph LR
392
- A["Your Query"] --> B["Semantic Router<br/>classifies intent"]
393
- B --> C["Embedding Adapter<br/>adjusts in <1ms"]
394
- C --> D["HNSW Search<br/>61us, 96.8% recall"]
395
- D --> E["Results"]
396
- E --> F["Your Feedback<br/>0.0 - 1.0"]
397
- F --> G["Contrastive Trainer<br/>learns what's good"]
398
- G --> C
399
- style G fill:#2d6,stroke:#1a4,color:#fff
400
- style A fill:#36f,stroke:#24d,color:#fff
401
- ```
402
-
403
- > **Result:** Over 10 sessions with 50 episodes each, search quality improved from 54% to 90% — a 36% gain with zero manual tuning.
404
-
405
- ## Architecture
406
-
407
- ```mermaid
408
- graph TD
409
- A[Your Application] --> B[AgentDB Core]
410
- B --> C[Cognitive Memory<br/>6 patterns]
411
- B --> D[Self-Learning Pipeline<br/>SONA + Contrastive + Federated]
412
- B --> E[Backend Auto-Selection]
413
- E --> F[RuVector<br/>Rust+SIMD 61us]
414
- E --> G[Cognitive Container<br/>RVF single-file COW]
415
- E --> H[HNSWLib<br/>C++ HNSW]
416
- E --> I[sql.js<br/>WASM fallback]
417
- B --> J[NativeAccelerator<br/>15 capability groups]
418
- B --> K[MCP Server<br/>41 tools]
419
- B --> L[Graph Intelligence<br/>Cypher + GNN]
420
- ```
421
-
422
- ---
423
-
424
- ## MCP Integration
425
126
 
426
- > **One command** to give any AI assistant access to self-learning vector search, cognitive memory, and 37 specialized tools.
427
-
428
- Connect AgentDB to Claude Code, Cursor, or any MCP-compatible AI assistant:
429
-
430
- ```bash
431
- claude mcp add agentdb npx agentdb mcp start
432
- ```
127
+ // Proof includes:
128
+ // - structuralHash: SHA-256 of operation + data
129
+ // - attestationToken: 82-byte cryptographic token
130
+ // - timestamp: ISO8601 timestamp
131
+ // - nonce: Random 16-byte nonce
433
132
 
434
- Or add to `~/.config/claude/claude_desktop_config.json`:
435
-
436
- ```json
437
- {
438
- "mcpServers": {
439
- "agentdb": {
440
- "command": "npx",
441
- "args": ["agentdb", "mcp", "start"],
442
- "env": { "AGENTDB_PATH": "./agentdb.rvf" }
443
- }
444
- }
133
+ // Backend validates before execution
134
+ if (guard.validateProof(proof)) {
135
+ backend.insert(proof.vectorId, proof.embedding, proof.metadata);
445
136
  }
446
137
  ```
447
138
 
448
- ### MCP Tools Overview
139
+ ### 2. Eight Graph-Transformer Modules
449
140
 
450
- | Category | Tools | Examples |
451
- | --- | --- | --- |
452
- | **Core DB** | 6 | init, insert, batch insert, search, delete, stats |
453
- | **Patterns** | 4 | store, search, batch store, statistics |
454
- | **Memory** | 9 | reflexion store/retrieve/batch, skill create/search/batch, causal edges/queries, nightly learner |
455
- | **Learning** | 10 | RL sessions, predictions, feedback, training, transfer learning, explainability |
456
- | **Recall** | 2 | explainable recall with provenance certificates, cache management |
457
- | **Solver** | 4 | solver train, acceptance testing, policy inspection, witness chain audit |
458
- | **Admin** | 6 | diagnostics, migration, pruning, experience recording, reward signals, legacy stats |
459
-
460
- All 41 tools support parallel execution markers, batch operations, intelligent caching, and format parameters for token reduction.
461
-
462
- ---
463
-
464
- ## Chat Ecosystem
465
-
466
- The `@agentdb/chat` package provides a one-line chat UI with self-learning RAG built on top of AgentDB:
467
-
468
- ```bash
469
- # Serve a chat interface over your knowledge base
470
- npx @agentdb/chat serve --rvf ./kb.rvf --port 3000
471
- ```
141
+ Native Rust implementations via `@ruvector/graph-transformer`:
472
142
 
473
- Programmatic usage:
143
+ - **Sublinear Attention** — O(n log n) replacing O(n²) JavaScript fallback
144
+ - **Verified Training** — SGD with cryptographic proof of each gradient step
145
+ - **Causal Attention** — Temporal-decay weighted attention for CausalRecall
146
+ - **Granger Extract** — Time-series causal discovery for memory graphs
147
+ - **Hamiltonian Step** — Physics-informed trajectory modeling
148
+ - **Spiking Attention** — Biological integrate-and-fire for episodic memory
149
+ - **Game-Theoretic Attention** — Nash equilibrium for multi-agent routing
150
+ - **Product Manifold Distance** — Curved-space similarity for reasoning patterns
474
151
 
475
152
  ```typescript
476
- import { createChatServer } from '@agentdb/chat';
153
+ import { GraphTransformerService } from 'agentdb';
477
154
 
478
- const server = await createChatServer('./kb.rvf', {
479
- port: 3000,
480
- learning: true,
155
+ const transformer = new GraphTransformerService({
156
+ enableNative: true,
157
+ modules: ['sublinear', 'causal', 'verified']
481
158
  });
482
- ```
483
-
484
- The chat ecosystem includes:
485
- - **Chat Server** — streaming inference with any LLM provider
486
- - **Chat Persistence** — conversation history stored in Cognitive Containers
487
- - **MCP Bridge** — expose all 37 AgentDB tools through chat
488
- - **Chat UI** (`@agentdb/chat-ui`) — SvelteKit frontend with real-time tool invocation
489
-
490
- See the [@agentdb/chat README](../agentdb-chat/README.md) for full documentation.
491
-
492
- ---
493
-
494
- ## Deep Dives
495
-
496
- > Expand any section below for code examples, configuration, and architecture details.
497
-
498
- **Getting Started** | [Guides](#guides) | [Tutorials](#tutorials) | [Advanced Usage](#advanced-usage)
499
-
500
- **Intelligence & Learning** | [Self-Learning Pipeline](#self-learning-pipeline) | [Cognitive Memory](#cognitive-memory-patterns) | [Reinforcement Learning](#reinforcement-learning) | [Hybrid Search](#hybrid-search) | [Graph Intelligence](#graph-intelligence) | [Query Lifecycle](#query-lifecycle)
501
-
502
- **Performance & Architecture** | [SIMD Acceleration](#simd--native-acceleration) | [Browser & WASM](#browser--wasm-deployment) | [Benchmarks](#performance--benchmarks) | [AgentDBFast](#agentdbfast) | [Benchmark Suite](#benchmark-suite)
503
-
504
- **Storage & Data** | [Cognitive Container (RVF)](#cognitive-container-rvf-format) | [Quantization](#quantization--compression) | [Metadata Filtering](#metadata-filtering)
505
-
506
- **Integration & Tools** | [LLM Router](#llm-router) | [Model Import/Export](#model-importexport--embedding-models) | [Multi-Database Sync](#multi-database-coordination) | [Real-Time Sync](#real-time-sync-quic)
507
-
508
- **Enterprise & Security** | [Security](#security) | [Auth & Audit](#auth--audit) | [Observability](#observability)
509
-
510
- ---
511
-
512
- ### Getting Started
513
159
 
514
- Step-by-step guides, tutorials, and advanced configuration for every skill level.
160
+ await transformer.initialize();
515
161
 
516
- <details>
517
- <summary><strong>Guides</strong> backend selection, migration, health checks, federated learning</summary>
518
-
519
- #### Backend Selection
520
-
521
- ```bash
522
- # Auto-detect best backend (recommended)
523
- npx agentdb init --backend auto
524
-
525
- # Force RuVector (fastest, requires native bindings)
526
- npx agentdb init --backend ruvector
527
-
528
- # Force Cognitive Container (single-file, portable)
529
- npx agentdb init --backend rvf --rvf-path ./vectors.rvf
162
+ // Use sublinear attention (O(n log n))
163
+ const attended = await transformer.sublinearAttention(
164
+ queryVector,
165
+ keyMatrix,
166
+ valueMatrix
167
+ );
530
168
 
531
- # Force HNSWLib (C++ HNSW)
532
- npx agentdb init --backend hnswlib
169
+ // Verify training step
170
+ const trainingProof = await transformer.verifiedTraining(
171
+ weights,
172
+ gradients,
173
+ learningRate
174
+ );
533
175
  ```
534
176
 
535
- #### Migration
536
-
537
- ```bash
538
- # Migrate v1 → v2
539
- npx agentdb migrate --source ./old.db --target ./new.db
540
-
541
- # Migrate v2 → v3 unified .rvf (same schemas, data copy)
542
- npx agentdb migrate --source ./v2.db --to v3 --rvf-path ./unified.rvf
177
+ ### 3. Twenty-One Active Controllers
543
178
 
544
- # Export to Cognitive Container
545
- npx agentdb migrate --to rvf --rvf-path ./vectors.rvf
179
+ All cognitive memory patterns are production-ready:
546
180
 
547
- # Dry-run migration
548
- npx agentdb migrate --dry-run --verbose
549
- ```
181
+ - **ReflexionMemory** — Self-critique and episodic replay
182
+ - **SkillLibrary** Lifelong learning with skill consolidation
183
+ - **ReasoningBank** — Pattern learning and adaptive memory
184
+ - **CausalMemoryGraph** — Intervention-based causality tracking
185
+ - **CausalRecall** — Utility-based retrieval with uplift scoring
186
+ - **ExplainableRecall** — Provenance certificates with Merkle proofs
187
+ - **NightlyLearner** — Automated pattern discovery
188
+ - **LearningSystem** — 9 RL algorithms (Q-Learning, DQN, PPO, MCTS, etc.)
189
+ - **EmbeddingService** — Multi-provider embeddings (Transformers.js, OpenAI)
190
+ - **WASMVectorSearch** — Browser-compatible vector search
191
+ - **HNSWIndex** — HNSW graph indexing for approximate nearest neighbor
192
+ - **AttentionService** — 5 attention mechanisms (causal, spiking, game-theoretic)
193
+ - **And 9 more** — See [docs/CONTROLLERS.md](./docs/CONTROLLERS.md)
550
194
 
551
- #### Health Checks
195
+ ## Installation
552
196
 
553
197
  ```bash
554
- # Full diagnostic
555
- npx agentdb doctor --verbose
556
-
557
- # Check specific Cognitive Container
558
- npx agentdb doctor --rvf-path ./vectors.rvf
559
-
560
- # Auto-fix issues
561
- npx agentdb doctor --fix
562
- ```
563
-
564
- #### Federated Learning Setup
565
-
566
- Configure cross-session federated learning for continuous improvement:
198
+ # v3 Alpha (proof-gated mutations)
199
+ npm install agentdb@v3
567
200
 
568
- ```typescript
569
- import { FederatedLearningCoordinator, EphemeralLearningAgent } from 'agentdb/services/federated-learning';
570
-
571
- const coordinator = new FederatedLearningCoordinator({
572
- agentId: 'coordinator-1',
573
- minQuality: 0.7,
574
- maxAgents: 100,
575
- });
201
+ # Stable v2 (production-ready)
202
+ npm install agentdb@latest
576
203
 
577
- const agent = new EphemeralLearningAgent({
578
- agentId: 'session-agent-1',
579
- qualityFiltering: true,
580
- });
204
+ # With optional native addons for 150x performance
205
+ npm install agentdb@v3 ruvector@latest
581
206
 
582
- const state = agent.exportState();
583
- await coordinator.aggregate(state);
584
- const merged = await coordinator.consolidate();
207
+ # For browser environments (WASM only)
208
+ npm install agentdb@v3
209
+ # Native addons will be skipped automatically
585
210
  ```
586
211
 
587
- </details>
588
-
589
- ---
590
-
591
- <details>
592
- <summary><strong>Tutorials</strong> — 6 step-by-step walkthroughs from beginner to advanced</summary>
593
-
594
- #### Tutorial 1: Build a Learning Code Review Agent
595
-
596
- ```typescript
597
- import { createDatabase, ReasoningBank, ReflexionMemory, EmbeddingService } from 'agentdb';
598
-
599
- const db = await createDatabase('./code-reviewer.db');
600
- const embedder = new EmbeddingService({ model: 'Xenova/all-MiniLM-L6-v2' });
601
- await embedder.initialize();
602
-
603
- const reasoningBank = new ReasoningBank(db, embedder);
604
- const reflexion = new ReflexionMemory(db, embedder);
605
-
606
- await reasoningBank.storePattern({
607
- taskType: 'code_review',
608
- approach: 'Security scan > Type safety > Code quality > Performance',
609
- successRate: 0.94,
610
- });
611
-
612
- const result = await performCodeReview(code);
613
- await reflexion.storeEpisode({
614
- sessionId: 'review-1',
615
- task: 'Review authentication PR',
616
- reward: result.issuesFound > 0 ? 0.9 : 0.6,
617
- success: true,
618
- critique: 'Found SQL injection — security checks work!',
619
- input: code,
620
- output: result.findings,
621
- });
622
-
623
- const pastReviews = await reflexion.retrieveRelevant({
624
- task: 'authentication code review',
625
- k: 5,
626
- onlySuccesses: true,
627
- });
628
- ```
212
+ ## API Overview
629
213
 
630
- #### Tutorial 2: RAG with Self-Learning Skills
214
+ ### Core Class
631
215
 
632
216
  ```typescript
633
- import { createDatabase, SkillLibrary, EmbeddingService } from 'agentdb';
634
-
635
- const db = await createDatabase('./rag-system.db');
636
- const embedder = new EmbeddingService({ model: 'Xenova/all-MiniLM-L6-v2' });
637
- await embedder.initialize();
638
-
639
- const skills = new SkillLibrary(db, embedder);
217
+ import { AgentDB } from 'agentdb';
640
218
 
641
- await skills.createSkill({
642
- name: 'expand_query',
643
- description: 'Expand user query with domain-specific synonyms',
644
- signature: { inputs: { query: 'string' }, outputs: { expanded: 'string[]' } },
645
- code: `const map = { 'bug': ['issue', 'defect', 'error'] }; ...`,
646
- successRate: 0.92,
219
+ const db = new AgentDB({
220
+ dbPath: './memory.db',
221
+ dimension: 384,
222
+ vectorBackend: 'ruvector', // or 'hnswlib' | 'sqlite'
223
+ enableProofGate: true,
224
+ strictMode: true
647
225
  });
648
226
 
649
- const applicable = await skills.searchSkills({ task: 'find technical documentation', k: 10 });
650
- ```
651
-
652
- #### Tutorial 3: Run Latent Space Simulations
653
-
654
- ```bash
655
- npx agentdb simulate hnsw --iterations 3
656
- npx agentdb simulate attention --iterations 3
657
- npx agentdb simulate self-organizing --days 30
658
- npx agentdb simulate --wizard
227
+ await db.initialize();
659
228
  ```
660
229
 
661
- #### Tutorial 4: Cognitive Container Branching
230
+ ### Controller Access
662
231
 
663
232
  ```typescript
664
- import { RvfBackend } from 'agentdb/backends/rvf/RvfBackend';
665
-
666
- const main = new RvfBackend({ dimension: 384, metric: 'cosine', storagePath: './main.rvf' });
667
- await main.initialize();
668
- await main.insertAsync('doc-1', embedding1, { source: 'production' });
669
- await main.flush();
233
+ // Get controllers by name
234
+ const reflexion = db.getController('reflexion');
235
+ const reasoning = db.getController('reasoning');
236
+ const skills = db.getController('skills');
237
+ const causalGraph = db.getController('causalGraph');
670
238
 
671
- // Branch for experiment (copy-on-write, near-instant)
672
- const experiment = await main.derive('./experiment.rvf');
673
- await experiment.insertAsync('doc-exp-1', experimentEmbedding);
674
- console.log(`Lineage depth: ${await experiment.lineageDepth()}`);
239
+ // Access proof engine
240
+ const guard = db.getMutationGuard();
241
+ const stats = guard?.getStats();
675
242
  ```
676
243
 
677
- #### Tutorial 5: Self-Learning RAG Pipeline
244
+ ### Security Primitives
678
245
 
679
246
  ```typescript
680
- import { SelfLearningRvfBackend } from 'agentdb/backends/rvf/SelfLearningRvfBackend';
247
+ import { MutationGuard, AttestationLog } from 'agentdb/security';
681
248
 
682
- const backend = await SelfLearningRvfBackend.create({
683
- dimension: 384, metric: 'cosine', storagePath: './rag-vectors.rvf',
684
- learning: true, federated: true,
249
+ // Create guard
250
+ const guard = new MutationGuard({
251
+ strictMode: true,
252
+ enableNative: true,
253
+ logPath: './attestations.log'
685
254
  });
686
255
 
687
- for (const doc of documents) {
688
- await backend.insertAsync(doc.id, doc.embedding, { title: doc.title });
689
- }
690
-
691
- const results = await backend.searchAsync(queryEmbedding, 10);
692
- backend.recordFeedback('query-1', 0.95);
693
- await backend.tick();
694
- ```
695
-
696
- #### Tutorial 6: Chat UI with Custom Knowledge Base
697
-
698
- ```bash
699
- npx agentdb init --backend rvf --rvf-path ./docs.rvf
700
- npx agentdb import ./docs/ --rvf-path ./docs.rvf
701
- npx @agentdb/chat serve --rvf ./docs.rvf --port 3000
702
- ```
703
-
704
- </details>
705
-
706
- ---
707
-
708
- <details>
709
- <summary><strong>Advanced Usage</strong> — batch ops, caching, solver tuning, GNN training, context synthesis</summary>
710
-
711
- #### Batch Operations
712
-
713
- ```typescript
714
- import { BatchOperations } from 'agentdb/optimizations/BatchOperations';
715
-
716
- const batchOps = new BatchOperations(db, embedder, {
717
- batchSize: 100, parallelism: 4,
718
- progressCallback: (done, total) => console.log(`${done}/${total}`),
256
+ // Generate proof
257
+ const proof = guard.generateProof({
258
+ operation: 'insert',
259
+ vectorId: 'vec-123',
260
+ embedding: embedding,
261
+ metadata: { source: 'test' }
719
262
  });
720
263
 
721
- await batchOps.insertSkills([...skills]);
722
- await batchOps.insertEpisodes([...episodes]);
723
- await batchOps.insertPatterns([...patterns]);
264
+ // Access attestation log
265
+ const log = guard.getAttestationLog();
266
+ const recentProofs = await log.query({ limit: 10 });
724
267
  ```
725
268
 
726
- #### Custom Backend Selection
269
+ ### Backend Integration
727
270
 
728
271
  ```typescript
729
- import { createBackend, detectBackends } from 'agentdb/backends/factory';
272
+ import { GuardedVectorBackend } from 'agentdb/backends';
730
273
 
731
- const detection = await detectBackends();
732
- // { ruvector: { available, native, gnn }, rvf: { sdk, node, wasm }, hnswlib: { available } }
274
+ // Wrap any backend with proof validation
275
+ const guardedBackend = new GuardedVectorBackend(rawBackend, guard);
733
276
 
734
- const backend = await createBackend({ type: 'rvf', dimension: 384, metric: 'cosine', storagePath: './vectors.rvf' });
277
+ // All operations require proof
278
+ await guardedBackend.insert(proof);
279
+ await guardedBackend.search(query, k, proof);
735
280
  ```
736
281
 
737
- #### Adaptive Index Tuning
282
+ ## Performance
738
283
 
739
- ```typescript
740
- import { AgentDBSolver } from 'agentdb/backends/rvf/RvfSolver';
741
-
742
- const solver = await AgentDBSolver.create();
743
- const trainResult = solver.train({ count: 50, minDifficulty: 1, maxDifficulty: 10 });
744
- const policy = solver.policy();
745
- // 18 context buckets (3 range x 3 distractor x 2 noise)
746
- ```
747
-
748
- #### Federated Session Manager
749
-
750
- ```typescript
751
- import { FederatedLearningCoordinator, EphemeralLearningAgent } from 'agentdb/services/federated-learning';
752
-
753
- const coordinator = new FederatedLearningCoordinator({ agentId: 'coord-main', minQuality: 0.7, maxAgents: 100 });
754
- const sessionAgent = new EphemeralLearningAgent({ agentId: `session-${Date.now()}`, qualityFiltering: true });
755
-
756
- await sessionAgent.processTask(embedding, 0.9);
757
- const state = sessionAgent.exportState();
758
- await coordinator.aggregate(state);
759
- const merged = await coordinator.consolidate();
760
- ```
761
-
762
- #### Context Synthesizer
763
-
764
- ```typescript
765
- import { ContextSynthesizer } from 'agentdb/controllers/ContextSynthesizer';
766
-
767
- const synthesizer = new ContextSynthesizer();
768
- const context = await synthesizer.synthesize(memories);
769
- // { summary, patterns, successRate, averageReward, recommendations, keyInsights }
770
- ```
771
-
772
- #### GNN Learning Backend
773
-
774
- ```typescript
775
- import { LearningBackend } from 'agentdb/backends/LearningBackend';
284
+ **Proof Generation:**
285
+ - Native (NAPI-RS): ~50μs per proof
286
+ - WASM: ~200μs per proof
287
+ - JavaScript: ~500μs per proof
776
288
 
777
- const learner = new LearningBackend({ dimension: 384 });
778
- const enhanced = learner.enhance(queryEmbedding, neighborEmbeddings, weights);
779
- learner.addSample(embedding, 'positive', 1.0, { source: 'feedback' });
780
- const result = await learner.train(10);
781
- // { epochs: 10, finalLoss: 0.023, improvement: 15.2, durationMs: 340 }
782
- ```
289
+ **Vector Operations (with RuVector):**
290
+ - Insert: 150x faster than JavaScript
291
+ - Search: 61μs p50 latency (96.8% recall@10)
292
+ - Pattern search: 32.6M ops/sec with caching
783
293
 
784
- </details>
294
+ **Package Size:**
295
+ - v2: 50.1MB (with unused native binaries)
296
+ - v3: 1.4MB (zero-native regression fixed)
785
297
 
786
- ---
298
+ ## Documentation
787
299
 
788
- ### Intelligence & Learning
300
+ - **[ADR-060: Proof-Gated Mutations](./docs/adr/ADR-060-agentdb-v3-proof-gated-graph-intelligence.md)** — Architecture decision record
301
+ - **[Controllers Guide](./docs/CONTROLLERS.md)** — All 21 controllers documented
302
+ - **[MCP Tools Reference](./docs/MCP_TOOLS.md)** — 32 MCP tools for Claude Code
303
+ - **[Migration Guide](./MIGRATION_v3.0.0.md)** — Upgrade from v2 to v3
304
+ - **[Security Model](./docs/SECURITY.md)** — Proof validation and attestation
789
305
 
790
- How AgentDB learns, reasons, and improves over time — from self-learning search to reinforcement learning and causal graphs.
306
+ ## MCP Integration (Claude Code)
791
307
 
792
- <details>
793
- <summary><strong>Self-Learning Pipeline</strong> — how search improves 36% automatically</summary>
308
+ Zero-code integration with AI coding assistants:
794
309
 
795
- AgentDB's self-learning pipeline continuously improves search quality through a six-phase cycle:
310
+ ```bash
311
+ # One-command setup
312
+ claude mcp add agentdb npx agentdb@v3 mcp start
796
313
 
797
- ```mermaid
798
- flowchart LR
799
- Q[Query] --> R[Semantic Router]
800
- R --> S[SONA Enhancement]
801
- S --> T[HNSW Search]
802
- T --> U[Results]
803
- U --> V[Feedback]
804
- V --> W[Contrastive Trainer<br/>InfoNCE + Hard Negatives]
805
- W --> X[Micro-LoRA Update]
806
- X --> Y[EWC++ Consolidation]
807
- Y --> Z[Federated Aggregation]
314
+ # Now Claude Code can:
315
+ # - Store reasoning patterns with proof validation
316
+ # - Search 32.6M patterns/sec for relevant approaches
317
+ # - Learn from successful task completions
318
+ # - Build reusable skills with attestation logs
808
319
  ```
809
320
 
810
- ### 1. Semantic Query Routing
811
-
812
- The `SemanticQueryRouter` classifies query intent by comparing against learned intent centroids using efficient min-heap top-k selection (O(n log k)). It lazily loads `@ruvector/router` for sub-millisecond HNSW routing and falls back to brute-force cosine with pre-computed norms when native bindings aren't available.
813
-
814
- The router also selects the adaptive ef-search arm for the query. Four ef-search levels (50, 100, 200, 400) are chosen based on the solver's Thompson Sampling policy for the matching context bucket.
815
-
816
- ```typescript
817
- // Router learns intents from usage patterns
818
- router.addIntent('technical_search', embedding); // up to 100 exemplars per intent
819
- router.addIntent('conversational', embedding);
820
- const { intent, confidence } = await router.route(queryEmbedding, k);
821
-
822
- // Router state persists across restarts (debounced 5s save)
823
- // Max 1,000 intents, JSON fallback or native persistence
824
- ```
321
+ ## License
825
322
 
826
- ### 2. SONA Enhancement
323
+ MIT OR Apache-2.0
827
324
 
828
- Context enrichment from trajectory history. The SONA engine (`@ruvector/sona`) tracks query trajectories and enriches embeddings with session context before search. SONA also applies the base LoRA adapter to the query embedding, adjusting it in sub-millisecond time based on learned patterns.
325
+ See [LICENSE-MIT](LICENSE-MIT) and [LICENSE-APACHE](LICENSE-APACHE) for details.
829
326
 
830
- ### 3. Contrastive Training
327
+ ## Contributing
831
328
 
832
- InfoNCE contrastive loss with hard negative mining inspired by NV-Retriever's positive-aware filtering:
329
+ We welcome contributions! See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.
833
330
 
834
- - **Loss function:** `L = -log(exp(sim(anchor, positive) / τ) / Σ exp(sim(anchor, negative_i) / τ))`
835
- - **Hard negative filtering:** Rejects candidates where `sim(candidate, positive) > 0.85`, eliminating ~70% of false negatives
836
- - **3-stage curriculum:** Progressively increases difficulty — negatives per sample (4 → 8 → 16), hardness threshold (0.5 → 0.3 → 0.1), 100 batches per stage
837
- - **AdamW optimizer:** β1=0.9, β2=0.999, decoupled weight decay, full bias correction
838
- - **Temperature:** Bounded 0.01-1.0 (default: 0.07)
331
+ ## Acknowledgments
839
332
 
840
- ```typescript
841
- // ContrastiveTrainer handles hard negative mining automatically
842
- const result = trainer.trainBatch([
843
- { anchor: queryEmb, positive: goodResultEmb, negatives: [badResult1, badResult2] },
844
- ]);
845
- // result: { loss, gradients, batchSize }
846
- ```
333
+ AgentDB v3 builds on research from:
334
+ - **RuVector** Native Rust vector database (150x faster)
335
+ - **Reflexion** (Shinn et al., 2023) — Self-critique and episodic replay
336
+ - **Causal Inference** (Pearl, Judea) Intervention-based causality
337
+ - **HNSW** (Malkov & Yashunin, 2018) — Approximate nearest neighbor search
338
+ - **Graph Neural Networks** Attention mechanisms for memory navigation
847
339
 
848
- When native SIMD is available, cosine similarity and AdamW steps delegate to the NativeAccelerator for hardware-accelerated computation.
340
+ ---
849
341
 
850
- ### 4. Micro-LoRA Adaptation
851
-
852
- Sub-millisecond embedding adjustment per query. A lightweight projection matrix (W: d×d + bias: d) is applied to the query embedding before search, specializing for each user's query patterns without modifying the base model. LoRA adapters are updated after each contrastive training batch.
853
-
854
- ### 5. EWC++ Consolidation
855
-
856
- Elastic Weight Consolidation prevents catastrophic forgetting by penalizing changes to important parameters. The Fisher information matrix is updated incrementally via the NativeAccelerator's `ewcUpdateFisher()` and penalty is computed via `ewcPenalty()`, ensuring previously learned patterns survive new training.
857
-
858
- ### 6. Federated Session Aggregation
859
-
860
- Cross-session LoRA merging for continuous improvement. Lightweight `EphemeralLearningAgent` instances (~5MB each) export their state to a `FederatedLearningCoordinator` for quality-filtered aggregation (minimum quality threshold: 0.7, up to 100 agents).
861
-
862
- ### How `tick()` Works
863
-
864
- Each learning tick performs these steps in sequence:
865
-
866
- 1. **Flush SONA** — persist trajectory context
867
- 2. **Train contrastive batch** — 32 samples from recorded feedback
868
- 3. **Train solver** — 50 puzzles to update Thompson Sampling policy
869
- 4. **Decay access frequencies** — multiply by 0.99, prune entries below 0.001 (every 50 ticks)
870
- 5. **Update temporal compressor** — adjust compression tiers
871
- 6. **Assess health** — latency tracking via health monitor
872
- 7. **Consolidate federated state** — merge distributed agent states
873
- 8. **Acceptance check** — every 100 ticks, run A/B/C ablation (mode A: fixed heuristic, mode B: compiler-suggested, mode C: learned Thompson Sampling) to validate adaptive ef-search
874
-
875
- ### Full Example
876
-
877
- ```typescript
878
- import { SelfLearningRvfBackend } from 'agentdb/backends/rvf/SelfLearningRvfBackend';
879
-
880
- const backend = await SelfLearningRvfBackend.create({
881
- dimension: 384,
882
- metric: 'cosine',
883
- storagePath: './vectors.rvf',
884
- learning: true,
885
- federated: true,
886
- positiveThreshold: 0.7,
887
- negativeThreshold: 0.3,
888
- trainingBatchSize: 32,
889
- tickIntervalMs: 5000,
890
- });
891
-
892
- // Insert vectors
893
- await backend.insertAsync('doc-1', embedding, { source: 'docs' });
894
-
895
- // Search (automatically enhanced by SONA + router)
896
- const results = await backend.searchAsync(queryEmbedding, 10);
897
-
898
- // Record feedback to drive learning
899
- backend.recordFeedback('query-123', 0.9); // high quality result
900
-
901
- // Run a learning tick (contrastive training + LoRA update + EWC consolidation)
902
- await backend.tick();
903
-
904
- // Check learning progress
905
- const stats = backend.getLearningStats();
906
- console.log(`Trajectories: ${stats.trajectoryCount}, LoRA rank: ${stats.loraRank}`);
907
- ```
908
-
909
- </details>
910
-
911
- ---
912
-
913
- <details>
914
- <summary><strong>Cognitive Memory Patterns</strong> — 6 ways your agent learns like a human</summary>
915
-
916
- AgentDB implements six cognitive memory patterns inspired by how humans learn:
917
-
918
- ### 1. ReasoningBank — Pattern Learning
919
-
920
- Store successful reasoning patterns and retrieve them by semantic similarity. The system learns which approaches work best for different task types.
921
-
922
- ```typescript
923
- await reasoningBank.storePattern({
924
- taskType: 'bug_investigation',
925
- approach: 'Check logs > Reproduce > Binary search for root cause',
926
- successRate: 0.92,
927
- tags: ['debugging', 'systematic'],
928
- });
929
-
930
- const patterns = await reasoningBank.searchPatterns({
931
- task: 'debug memory leak',
932
- k: 10,
933
- threshold: 0.7,
934
- });
935
- ```
936
-
937
- ### 2. Reflexion Memory — Learn from Experience
938
-
939
- Store complete task episodes with self-generated critiques, then replay them to improve future performance. Based on Shinn et al., 2023.
940
-
941
- ```typescript
942
- await reflexion.storeEpisode({
943
- sessionId: 'session-1',
944
- task: 'Fix authentication bug',
945
- reward: 0.95,
946
- success: true,
947
- critique: 'OAuth2 PKCE flow was more secure than basic flow',
948
- input: 'Users cannot log in',
949
- output: 'Working OAuth2 implementation',
950
- latencyMs: 1200,
951
- tokensUsed: 500,
952
- });
953
-
954
- const similar = await reflexion.retrieveRelevant({
955
- task: 'authentication issues',
956
- k: 10,
957
- onlySuccesses: true,
958
- });
959
- ```
960
-
961
- ### 3. Skill Library — Lifelong Learning
962
-
963
- Transform successful patterns into reusable, composable skills that improve over time.
964
-
965
- ```typescript
966
- await skills.createSkill({
967
- name: 'jwt_authentication',
968
- description: 'Generate and validate JWT tokens',
969
- signature: { inputs: { userId: 'string' }, outputs: { token: 'string' } },
970
- code: 'implementation...',
971
- successRate: 0.92,
972
- });
973
-
974
- const applicable = await skills.searchSkills({
975
- task: 'user authentication',
976
- k: 5,
977
- minSuccessRate: 0.7,
978
- });
979
- ```
980
-
981
- ### 4. Causal Memory Graph — Intervention Causality
982
-
983
- Track `p(y|do(x))` using doubly robust estimation. Learn what interventions cause what outcomes.
984
-
985
- ```typescript
986
- import { CausalMemoryGraph } from 'agentdb';
987
-
988
- const causalGraph = new CausalMemoryGraph(db);
989
-
990
- const experimentId = causalGraph.createExperiment({
991
- name: 'test_error_handling',
992
- hypothesis: 'Try-catch reduces crash rate',
993
- treatmentId: 123,
994
- treatmentType: 'episode',
995
- controlId: 124,
996
- startTime: Date.now(),
997
- sampleSize: 0,
998
- status: 'running',
999
- });
1000
-
1001
- const { uplift, pValue } = causalGraph.calculateUplift(experimentId);
1002
- ```
1003
-
1004
- ### 5. Explainable Recall — Provenance Certificates
1005
-
1006
- Every retrieval comes with a cryptographic Merkle proof explaining why specific memories were selected.
1007
-
1008
- ```typescript
1009
- const result = await causalRecall.recall(
1010
- 'query-123',
1011
- 'How to optimize API response time',
1012
- 12,
1013
- ['performance'],
1014
- 'internal',
1015
- );
1016
-
1017
- console.log(`Certificate: ${result.certificate.id}`);
1018
- console.log(`Completeness: ${result.certificate.completenessScore}`);
1019
- ```
1020
-
1021
- ### 6. Nightly Learner — Automated Discovery
1022
-
1023
- Background process that discovers causal patterns, consolidates skills, and prunes low-quality data automatically.
1024
-
1025
- ```typescript
1026
- const learner = new NightlyLearner(db, embedder);
1027
- const discovered = await learner.discover({
1028
- minAttempts: 3,
1029
- minSuccessRate: 0.6,
1030
- minConfidence: 0.7,
1031
- dryRun: false,
1032
- });
1033
- ```
1034
-
1035
- </details>
1036
-
1037
- ---
1038
-
1039
- ### Storage & Data
1040
-
1041
- How AgentDB stores vectors, manages compression tiers, and provides MongoDB-style filtering — all in a single Cognitive Container.
1042
-
1043
- <details>
1044
- <summary><strong>Cognitive Container (RVF Format)</strong> — single-file storage with crash safety and branching</summary>
1045
-
1046
- The **Cognitive Container** is AgentDB's native storage format (`.rvf` — RuVector Format). It packs vectors, indexes, learning state, and a cryptographic witness chain into a single file with crash safety, progressive indexing, and full lineage tracking.
1047
-
1048
- ### Structure
1049
-
1050
- ```mermaid
1051
- graph TB
1052
- subgraph "store.rvf"
1053
- H[Header + Magic Bytes]
1054
- S1[Segment 1<br/>Vectors + Metadata]
1055
- S2[Segment 2]
1056
- IX[HNSW Index<br/>Progressive]
1057
- WC[Witness Chain<br/>SHAKE-256]
1058
- LN[Lineage Record<br/>Parent ID + Depth]
1059
- end
1060
- H --> S1
1061
- S1 --> S2
1062
- S2 --> IX
1063
- IX --> WC
1064
- WC --> LN
1065
- ```
1066
-
1067
- ### Key Capabilities
1068
-
1069
- | Feature | Description |
1070
- | --- | --- |
1071
- | **Single-file** | Everything in one Cognitive Container (`.rvf`) — vectors, index, metadata |
1072
- | **Crash-safe** | Append-only log with checksums, safe concurrent access |
1073
- | **COW Branching** | Create copy-on-write branches for experiments (near-instant) |
1074
- | **Lineage Tracking** | `fileId()`, `parentId()`, `lineageDepth()` for file-level provenance |
1075
- | **Progressive Indexing** | 3-layer HNSW quality tiers, index builds incrementally as data arrives |
1076
- | **Witness Chains** | SHAKE-256 cryptographic verification (73 bytes per entry) |
1077
- | **Filter Expressions** | 11 operators for metadata filtering, max 64 depth |
1078
- | **Auto-Compaction** | `compact()` reclaims space, reports segments compacted & bytes reclaimed |
1079
- | **Readonly Mode** | `openReadonly()` for concurrent readers without locks |
1080
- | **Segment Introspection** | `segments()` returns id, type, and payload length per segment |
1081
- | **Kernel Embedding** | Embed unikernel images directly into Cognitive Containers |
1082
- | **eBPF Embedding** | Embed and extract eBPF bytecode for programmable queries |
1083
-
1084
- ### Configuration
1085
-
1086
- ```typescript
1087
- const backend = new RvfBackend({
1088
- dimension: 384,
1089
- metric: 'cosine', // 'cosine' | 'l2' | 'dotproduct'
1090
- storagePath: './vectors.rvf',
1091
- rvfBackend: 'auto', // 'auto' | 'node' (N-API) | 'wasm' (browser)
1092
- batchThreshold: 100, // Auto-flush after N sync inserts (1-10,000)
1093
- compression: 'none', // 'none' (fp32) | 'scalar' (int8) | 'product' (PQ)
1094
- hardwareProfile: 0, // 0=Generic | 1=Core | 2=Hot | 3=Full
1095
- enableStats: true, // Track insert/search/flush/compaction timing
1096
- });
1097
- ```
1098
-
1099
- **Hardware profiles** tune internal parameters for your deployment:
1100
-
1101
- | Profile | Level | Best For |
1102
- | --- | --- | --- |
1103
- | Generic (0) | Conservative defaults | Unknown hardware |
1104
- | Core (1) | Balanced throughput/latency | Developer machines |
1105
- | Hot (2) | Aggressive caching | High-throughput servers |
1106
- | Full (3) | Maximum parallelism | Dedicated vector search |
1107
-
1108
- ### Witness Chains
1109
-
1110
- Every mutation is recorded in a tamper-evident SHAKE-256 witness chain (73 bytes per entry). This provides cryptographic proof that data has not been modified after the fact:
1111
-
1112
- ```typescript
1113
- const result = backend.verifyWitnessChain();
1114
- // { valid: true, entries: 1042, algorithm: 'SHAKE-256' }
1115
-
1116
- // Verification uses @ruvector/rvf-wasm: rvf_witness_verify(), rvf_witness_count()
1117
- ```
1118
-
1119
- ### Filter Expressions
1120
-
1121
- RVF supports 11 filter operators for metadata-filtered search. Filters are serialized to a compact field-ID format with a maximum depth of 64 expressions for security:
1122
-
1123
- ```typescript
1124
- import { FilterBuilder } from 'agentdb/backends/rvf/FilterBuilder';
1125
-
1126
- const filter = new FilterBuilder()
1127
- .eq('status', 'active')
1128
- .gt('score', 0.5)
1129
- .range('timestamp', startDate, endDate)
1130
- .in('category', ['research', 'engineering'])
1131
- .build();
1132
-
1133
- const results = await backend.searchAsync(queryVector, 10, { filter });
1134
-
1135
- // Also supports filter-based deletion
1136
- await backend.deleteByFilter(filter);
1137
- ```
1138
-
1139
- **Available operators:** `eq`, `ne`, `lt`, `le`, `gt`, `ge`, `in`, `range`, `and`, `or`, `not`
1140
-
1141
- ### Performance Stats
1142
-
1143
- The RVF backend tracks detailed performance counters:
1144
-
1145
- ```typescript
1146
- const stats = backend.getPerformanceStats();
1147
- // {
1148
- // insertCount: 10432, insertTotalMs: 521.6, avgInsertMs: 0.05,
1149
- // searchCount: 8891, searchTotalMs: 178.2, avgSearchMs: 0.02,
1150
- // flushCount: 104, compactionCount: 3
1151
- // }
1152
- ```
1153
-
1154
- ### Kernel & eBPF Embedding
1155
-
1156
- Cognitive Containers can embed unikernel images and eBPF bytecode directly, enabling self-contained deployable artifacts:
1157
-
1158
- ```typescript
1159
- // Embed a kernel image into the Cognitive Container
1160
- await backend.embedKernel({
1161
- arch: 'x86_64', // 'x86_64' | 'aarch64' | 'riscv64'
1162
- type: 'firecracker', // 'firecracker' | 'qemu' | 'cloud-hypervisor'
1163
- flags: 0,
1164
- image: kernelBuffer,
1165
- apiPort: 8080,
1166
- cmdline: 'console=ttyS0',
1167
- });
1168
-
1169
- // Extract it later
1170
- const kernel = await backend.extractKernel();
1171
- // { header: { arch, type, ... }, image: Uint8Array }
1172
-
1173
- // eBPF bytecode for programmable query filters
1174
- await backend.embedEbpf(ebpfBytecode);
1175
- const ebpf = await backend.extractEbpf();
1176
- ```
1177
-
1178
- ### CLI Commands
1179
-
1180
- ```bash
1181
- # Show store status
1182
- npx agentdb rvf status ./store.rvf
1183
-
1184
- # Compact to reclaim space
1185
- npx agentdb rvf compact ./store.rvf
1186
-
1187
- # Create a branch (copy-on-write)
1188
- npx agentdb rvf derive ./parent.rvf ./experiment.rvf
1189
-
1190
- # List segments
1191
- npx agentdb rvf segments ./store.rvf
1192
-
1193
- # Detect SDK availability
1194
- npx agentdb rvf detect
1195
- ```
1196
-
1197
- ### Programmatic Usage
1198
-
1199
- ```typescript
1200
- import { RvfBackend } from 'agentdb/backends/rvf/RvfBackend';
1201
-
1202
- const backend = new RvfBackend({
1203
- dimension: 384,
1204
- metric: 'cosine',
1205
- storagePath: './vectors.rvf',
1206
- rvfBackend: 'auto', // 'node' for N-API, 'wasm' for browser
1207
- });
1208
- await backend.initialize();
1209
-
1210
- // Async operations (native)
1211
- await backend.insertAsync('vec-1', embedding, { tag: 'example' });
1212
- const results = await backend.searchAsync(queryVector, 10);
1213
- await backend.flush();
1214
-
1215
- // COW branching
1216
- const branch = await backend.derive('./experiment.rvf');
1217
- const lineage = await backend.lineageDepth();
1218
- ```
1219
-
1220
- ### Backend Selection
1221
-
1222
- ```bash
1223
- # Initialize with RVF backend
1224
- npx agentdb init --backend rvf --rvf-path ./vectors.rvf
1225
-
1226
- # Migrate v2 database to v3 unified .rvf
1227
- npx agentdb migrate --source ./v2.db --to v3 --rvf-path ./unified.rvf
1228
-
1229
- # Migrate existing data to RVF
1230
- npx agentdb migrate --to rvf --rvf-path ./vectors.rvf
1231
-
1232
- # Check RVF in diagnostics
1233
- npx agentdb doctor --rvf-path ./vectors.rvf
1234
- ```
1235
-
1236
- </details>
1237
-
1238
- ---
1239
-
1240
- ### Performance & Architecture
1241
-
1242
- The engine behind AgentDB's speed — SIMD acceleration, graph intelligence, browser WASM, and benchmarking.
1243
-
1244
- <details>
1245
- <summary><strong>SIMD & Native Acceleration</strong> — 15 capability groups with automatic fallbacks</summary>
1246
-
1247
- The `NativeAccelerator` provides 15 capability groups bridging 11 `@ruvector` packages, with pure-JS fallbacks for every operation via `SimdFallbacks`.
1248
-
1249
- ### Capability Groups
1250
-
1251
- | Group | Operations | Package |
1252
- | --- | --- | --- |
1253
- | **Vector Distance & Math** | cosine, dot, L2, hamming, add, mul, scale, normalize | `ruvector` |
1254
- | **Activations** | softmax, relu, gelu, sigmoid, layerNorm | `@ruvector/ruvllm` |
1255
- | **Loss Functions** | InfoNCE (contrastive) | `@ruvector/sona` |
1256
- | **Optimizers** | AdamW step | `@ruvector/sona` |
1257
- | **Quantization** | scalar 8-bit/4-bit, product quantization | `@ruvector/rvf` |
1258
- | **WASM Store** | create, ingest, query, export, close | `@ruvector/rvf-wasm` |
1259
- | **Verification** | witness chain, segment header | `@ruvector/rvf-node` |
1260
- | **Graph Transactions** | begin, commit, rollback | `@ruvector/graph-node` |
1261
- | **Graph Batch Insert** | high-throughput node/edge ingestion | `@ruvector/graph-node` |
1262
- | **Graph Cypher** | pattern matching, path queries | `@ruvector/graph-node` |
1263
- | **Core Batch Insert** | native vector batch ingestion | `ruvector` |
1264
- | **EWC Memory** | penalty calculation, Fisher update | `@ruvector/sona` |
1265
- | **Router** | save/load state persistence | `@ruvector/router` |
1266
- | **SONA** | context addition, flush, base LoRA | `@ruvector/sona` |
1267
- | **Compression** | tensor compress/decompress | `@ruvector/rvf` |
1268
-
1269
- ### Auto-Detection
1270
-
1271
- Each capability group is lazily loaded — only the packages actually installed on the system are loaded, and each load is tried independently so a missing package never blocks others:
1272
-
1273
- ```typescript
1274
- import { NativeAccelerator } from 'agentdb/backends/rvf/NativeAccelerator';
1275
-
1276
- const accel = new NativeAccelerator();
1277
- const stats = await accel.initialize();
1278
-
1279
- console.log(stats);
1280
- // AcceleratorStats:
1281
- // {
1282
- // simdAvailable: true, // Vector distance + element-wise math
1283
- // simdActivationsAvailable: true, // softmax, relu, gelu, sigmoid, layerNorm
1284
- // wasmVerifyAvailable: true, // Witness chain & header verification
1285
- // wasmStoreAvailable: true, // In-browser HNSW store
1286
- // wasmQuantizationAvailable: true, // Scalar/product quantization ops
1287
- // nativeInfoNceAvailable: true, // Hardware-accelerated InfoNCE loss
1288
- // nativeAdamWAvailable: true, // Hardware-accelerated AdamW optimizer
1289
- // nativeTensorCompressAvailable: true, // SVD tensor compression
1290
- // routerPersistAvailable: true, // Semantic router state persistence
1291
- // sonaExtendedAvailable: true, // SONA trajectory context & base LoRA
1292
- // }
1293
- // Additional capabilities (probed separately):
1294
- // accel.graphTxAvailable // Graph transactions
1295
- // accel.graphBatchInsertAvailable // Graph batch insert
1296
- // accel.graphCypherAvailable // Cypher query engine
1297
- // accel.coreBatchInsertAvailable // Native vector batch insert
1298
- // accel.ewcManagerAvailable // EWC++ memory consolidation
1299
- ```
1300
-
1301
- ### Pure-JS Fallbacks
1302
-
1303
- Every SIMD operation has a pure-JS fallback with 4-wide loop unrolling for reasonable performance even without native bindings:
1304
-
1305
- ```typescript
1306
- import { SimdFallbacks } from 'agentdb/backends/rvf/SimdFallbacks';
1307
-
1308
- // Same API as native, ~10-50x slower but always available
1309
- const similarity = SimdFallbacks.jsCosineSimilarity(vecA, vecB);
1310
- const loss = SimdFallbacks.jsInfoNceLoss(anchor, positive, negatives, temperature);
1311
- const result = SimdFallbacks.jsAdamWStep(params, grads, m, v, lr, beta1, beta2, weightDecay, t);
1312
- ```
1313
-
1314
- ### Additional SIMD Operations
1315
-
1316
- The `SIMDVectorOps` class provides batch operations and platform-specific detection:
1317
-
1318
- ```typescript
1319
- import { SIMDVectorOps, detectSIMDSupport } from 'agentdb/simd';
1320
-
1321
- const simd = new SIMDVectorOps();
1322
- const support = detectSIMDSupport();
1323
- // { wasm: true, x64: false, avx2: false, neon: false }
1324
-
1325
- const similarities = simd.batchCosineSimilarity(query, [vec1, vec2, vec3]);
1326
- ```
1327
-
1328
- </details>
1329
-
1330
- ---
1331
-
1332
- <details>
1333
- <summary><strong>Graph Intelligence</strong> — Cypher queries, causal reasoning, GNN attention</summary>
1334
-
1335
- AgentDB integrates `@ruvector/graph-node` for a full graph database with Cypher query support, transactional batch inserts, and GNN-powered attention.
1336
-
1337
- ### Cypher Queries
1338
-
1339
- Full Neo4j-compatible Cypher syntax including MATCH, RETURN, WHERE, ORDER BY, LIMIT, relationship patterns, and graph traversal:
1340
-
1341
- ```typescript
1342
- import { GraphDatabaseAdapter } from 'agentdb/backends/graph/GraphDatabaseAdapter';
1343
-
1344
- const graph = new GraphDatabaseAdapter({
1345
- storagePath: './graph.db',
1346
- dimensions: 384,
1347
- distanceMetric: 'Cosine', // 'Cosine' | 'Euclidean' | 'DotProduct' | 'Manhattan'
1348
- });
1349
- await graph.initialize();
1350
-
1351
- // Create nodes and edges
1352
- await graph.storeEpisode(episode, embedding);
1353
- await graph.storeSkill(skill, embedding);
1354
- await graph.createCausalEdge(edge, embedding);
1355
-
1356
- // Cypher queries
1357
- const results = await graph.query(`
1358
- MATCH (e:Episode)-[:CAUSED]->(s:Skill)
1359
- WHERE e.reward > 0.8
1360
- RETURN e, s
1361
- ORDER BY e.reward DESC
1362
- LIMIT 10
1363
- `);
1364
- ```
1365
-
1366
- ### Graph Traversal
1367
-
1368
- Traverse relationships with direction control, depth limits, and label filtering:
1369
-
1370
- ```typescript
1371
- const paths = await graph.traverse({
1372
- startNodeId: 'episode-42',
1373
- pattern: '()-[:RELATES_TO]->(:Skill)',
1374
- direction: 'outgoing', // 'outgoing' | 'incoming' | 'both'
1375
- maxDepth: 3,
1376
- relationshipTypes: ['CAUSED', 'RELATES_TO'],
1377
- nodeLabels: ['Episode', 'Skill'],
1378
- });
1379
- ```
1380
-
1381
- ### Hybrid Vector + Graph Search
1382
-
1383
- Combine vector similarity with graph context filtering — find semantically similar nodes that are also connected in the knowledge graph:
1384
-
1385
- ```typescript
1386
- // Vector similarity within graph structure
1387
- const results = await graph.vectorSearch(queryEmbedding, 10);
1388
- // Returns nodes ranked by embedding similarity with graph context
1389
-
1390
- // Nodes support multi-label classification
1391
- await graph.createNode({
1392
- id: 'analysis-1',
1393
- label: ['Episode', 'Analyzed', 'Security'],
1394
- properties: { reward: 0.95, task: 'auth review' },
1395
- embedding: embeddingVector,
1396
- });
1397
- ```
1398
-
1399
- ### Transactional Batch Inserts
1400
-
1401
- ACID-guaranteed batch operations with rollback support:
1402
-
1403
- ```typescript
1404
- const txId = await graph.beginTransaction();
1405
- try {
1406
- await graph.batchInsert(
1407
- nodes.map(n => ({ id: n.id, label: n.type, properties: n.data })),
1408
- edges.map(e => ({ from: e.source, to: e.target, label: e.type, properties: e.data })),
1409
- );
1410
- await graph.commitTransaction(txId);
1411
- } catch (err) {
1412
- await graph.rollbackTransaction(txId);
1413
- }
1414
- ```
1415
-
1416
- ### GNN 8-Head Attention
1417
-
1418
- The GNN attention mechanism improves recall by +12.4% with a 3.8ms forward pass and 91% transfer learning retention. Three attention types are available:
1419
-
1420
- | Type | Algorithm | Best For |
1421
- | --- | --- | --- |
1422
- | `gat` | Graph Attention Network | Weighted neighbor aggregation |
1423
- | `gcn` | Graph Convolutional Network | Uniform message passing |
1424
- | `sage` | GraphSAGE | Inductive learning on unseen nodes |
1425
-
1426
- ```typescript
1427
- import { AttentionService } from 'agentdb/controllers/AttentionService';
1428
-
1429
- const attention = new AttentionService({
1430
- numHeads: 8,
1431
- dimension: 384,
1432
- attentionType: 'gat', // 'gat' | 'gcn' | 'sage'
1433
- });
1434
- const enhanced = await attention.forward(queryEmbedding, neighborEmbeddings);
1435
- ```
1436
-
1437
- ### Causal Memory Graph
1438
-
1439
- Track interventions with `p(y|do(x))` doubly robust estimation and optional Poincare embeddings for hierarchical relationships:
1440
-
1441
- ```typescript
1442
- import { CausalMemoryGraph } from 'agentdb';
1443
-
1444
- const causal = new CausalMemoryGraph(db, graph, embedder, {
1445
- ENABLE_HYPERBOLIC_ATTENTION: true, // Poincaré ball distance for hierarchies
1446
- });
1447
-
1448
- await causal.addCausalEdge({
1449
- fromMemoryId: 'episode-1',
1450
- toMemoryType: 'skill', // 'episode' | 'skill' | 'note' | 'fact'
1451
- uplift: 0.15, // E[y|do(x)] - E[y]
1452
- confidence: 0.92,
1453
- mechanism: 'error-handling improvement',
1454
- sampleSize: 50,
1455
- confounderScore: 0.03,
1456
- });
1457
- ```
1458
-
1459
- </details>
1460
-
1461
- ---
1462
-
1463
- <details>
1464
- <summary><strong>Browser & WASM Deployment</strong> — full vector DB in the browser, no server needed</summary>
1465
-
1466
- AgentDB runs fully in the browser with WASM-backed vector storage, GNN attention, product quantization, and pure-JS fallbacks.
1467
-
1468
- ### WasmStoreBridge
1469
-
1470
- The `WasmStoreBridge` provides a full HNSW vector database in the browser by wrapping `@ruvector/rvf-wasm`:
1471
-
1472
- ```typescript
1473
- import { WasmStoreBridge } from 'agentdb/backends/rvf/WasmStoreBridge';
1474
-
1475
- const bridge = new WasmStoreBridge();
1476
- await bridge.initialize();
1477
-
1478
- // Create an in-browser vector store
1479
- const handle = bridge.wasmStoreCreate(384, 0); // 384 dims, cosine metric
1480
-
1481
- // Ingest vectors
1482
- bridge.wasmStoreIngest(handle, vectors, ids, count);
1483
-
1484
- // Query
1485
- const results = bridge.wasmStoreQuery(handle, queryVector, 10, 0);
1486
- // [{ id: 42, distance: 0.12 }, ...]
1487
-
1488
- // Export to transferable binary (share between tabs/workers)
1489
- const bytes = bridge.wasmStoreExport(handle);
1490
-
1491
- bridge.wasmStoreClose(handle);
1492
- ```
1493
-
1494
- ### Browser Attention Mechanisms
1495
-
1496
- The `AttentionBrowser` provides three advanced attention types compiled to WASM:
1497
-
1498
- ```typescript
1499
- import { AttentionBrowser } from 'agentdb/browser/AttentionBrowser';
1500
-
1501
- const attention = new AttentionBrowser({ numHeads: 8 });
1502
- // Loading states: 'idle' → 'loading' → 'loaded' | 'error'
1503
-
1504
- // Standard multi-head attention
1505
- const enhanced = await attention.forward(query, neighbors);
1506
-
1507
- // Flash Attention — O(N) memory instead of O(N²)
1508
- const flash = await attention.flashAttention(query, keys, values);
1509
-
1510
- // Hyperbolic Attention — Poincaré ball distance for hierarchical data
1511
- const hyper = await attention.hyperbolicAttention(query, neighbors);
1512
-
1513
- // Memory Consolidation — agglomerative clustering to merge similar memories
1514
- const consolidated = await attention.consolidateMemories(memories, {
1515
- threshold: 0.85,
1516
- minClusterSize: 3,
1517
- });
1518
- ```
1519
-
1520
- ### Product Quantization (Browser)
1521
-
1522
- Memory-efficient vector storage with three PQ compression levels:
1523
-
1524
- | Variant | Compression | Subvectors | Centroids | Best For |
1525
- | --- | --- | --- | --- | --- |
1526
- | **PQ8** | 4x | 8 | 256 | Balanced quality/memory |
1527
- | **PQ16** | 8x | 16 | 256 | Medium datasets |
1528
- | **PQ32** | 16x | 32 | 256 | Maximum compression |
1529
-
1530
- ```typescript
1531
- import { createProductQuantizedStore, createScalar8BitStore } from 'agentdb/browser/ProductQuantization';
1532
-
1533
- // Product quantization with asymmetric distance computation (ADC)
1534
- const pq = createProductQuantizedStore(384, {
1535
- numSubvectors: 16,
1536
- bitsPerCode: 8,
1537
- // Uses K-means++ initialization for codebook training
1538
- });
1539
- pq.add('doc-1', embedding);
1540
- const results = pq.search(query, 10);
1541
- ```
1542
-
1543
- ### Browser Configuration Presets
1544
-
1545
- Pre-tuned configurations for common scenarios:
1546
-
1547
- | Preset | Features | Target |
1548
- | --- | --- | --- |
1549
- | `SMALL_DATASET` | GNN only | <1K vectors |
1550
- | `MEDIUM_DATASET` | HNSW + PQ8 | 1K-10K vectors |
1551
- | `LARGE_DATASET` | Aggressive compression + HNSW | 10K-100K vectors |
1552
- | `MEMORY_OPTIMIZED` | PQ32 + SVD (dim 64) | Memory-constrained |
1553
- | `SPEED_OPTIMIZED` | HNSW max quality | Latency-critical |
1554
- | `QUALITY_OPTIMIZED` | No compression, max attention heads | Accuracy-critical |
1555
-
1556
- ### Maximal Marginal Relevance (MMR)
1557
-
1558
- Diversify search results to avoid returning near-duplicate items:
1559
-
1560
- ```typescript
1561
- import { MMRDiversityRanker } from 'agentdb/controllers/MMRDiversityRanker';
1562
-
1563
- const ranker = new MMRDiversityRanker({
1564
- lambda: 0.7, // 0=max diversity, 1=max relevance
1565
- metric: 'cosine', // 'cosine' | 'euclidean' | 'dot'
1566
- });
1567
-
1568
- // Rerank results: MMR = λ × Sim(Di,Q) - (1-λ) × max Sim(Di,Dj)
1569
- const diverse = ranker.rerank(queryEmbedding, candidates, 10);
1570
- const score = ranker.diversityScore(diverse); // average pairwise distance
1571
- ```
1572
-
1573
- ### Browser Bundle
1574
-
1575
- ```typescript
1576
- import { AgentDB } from 'agentdb/browser';
1577
-
1578
- const db = new AgentDB({ dimension: 384 });
1579
- await db.initialize();
1580
-
1581
- await db.insert('doc-1', embedding, { title: 'Getting Started' });
1582
- const results = await db.search(queryEmbedding, 5);
1583
- ```
1584
-
1585
- ### sql.js & SIMD Fallbacks
1586
-
1587
- For zero-dependency environments, AgentDB falls back to `sql.js` (SQLite compiled to WASM) automatically. Non-WASM browsers get pure-JS implementations with 4-wide loop unrolling (~10-50x slower than native SIMD but fully functional):
1588
-
1589
- ```typescript
1590
- import { createDatabase } from 'agentdb';
1591
- import { detectSIMDSupport } from 'agentdb/simd';
1592
-
1593
- // In browsers, automatically uses sql.js WASM backend
1594
- const db = await createDatabase(':memory:');
1595
-
1596
- const support = detectSIMDSupport();
1597
- // { wasm: true, x64: false, avx2: false, neon: false }
1598
- ```
1599
-
1600
- </details>
1601
-
1602
- ---
1603
-
1604
- <details>
1605
- <summary><strong>Performance & Benchmarks</strong> — 61us latency, 96.8% recall, 32.6M ops/sec</summary>
1606
-
1607
- ### Core Operations
1608
-
1609
- | Operation | Throughput | Latency |
1610
- | --- | --- | --- |
1611
- | Pattern search | 32.6M ops/sec | <1ms |
1612
- | Pattern storage | 388K ops/sec | ~2.5us |
1613
- | Episode retrieval | 957 ops/sec | ~1ms |
1614
- | Skill search | 694 ops/sec | ~1.4ms |
1615
- | Batch insert | 5,556-7,692 ops/sec | 3-4x faster than sequential |
1616
-
1617
- ### Scaling Behavior
1618
-
1619
- ```
1620
- 500 patterns: 1,475/sec, 2MB memory
1621
- 2,000 patterns: 3,818/sec, 0MB delta
1622
- 5,000 patterns: 4,536/sec, 4MB memory (super-linear)
1623
- ```
1624
-
1625
- ### Self-Learning Improvement
1626
-
1627
- ```
1628
- Adaptive Learning (10 sessions, 50 episodes each)
1629
- Initial success rate: 54%
1630
- Final success rate: 90%
1631
- Improvement: +36%
1632
- ```
1633
-
1634
- ### Latent Space Validation (31 scenarios, 98.2% reproducibility)
1635
-
1636
- | Scenario | Result |
1637
- | --- | --- |
1638
- | HNSW Optimization | 61us p50, 96.8% recall@10, 8.2x vs hnswlib |
1639
- | GNN Attention | +12.4% recall, 3.8ms forward pass, 91% transfer |
1640
- | Self-Healing | 97.9% degradation prevention, <100ms repair |
1641
- | Neural Augmentation | +29.4% improvement, -32% memory, -52% hops |
1642
-
1643
- ### Adaptive Solver (Thompson Sampling)
1644
-
1645
- The solver uses 18 context-bucketed bandits (3 range x 3 distractor x 2 noise levels) to dynamically tune search parameters:
1646
-
1647
- ```typescript
1648
- const solver = await AgentDBSolver.create();
1649
-
1650
- // Train the solver with puzzles of varying difficulty
1651
- const result = solver.train({ count: 50, minDifficulty: 1, maxDifficulty: 10 });
1652
-
1653
- // Inspect the policy — shows Thompson Sampling alpha/beta per context bucket
1654
- const policy = solver.policy();
1655
- console.log(policy.contextStats);
1656
- // { '0_0_0': { alphaSafety: 12.5, betaSafety: 2.1, costEma: 0.03 }, ... }
1657
-
1658
- // A/B/C acceptance testing
1659
- const manifest = solver.acceptance({ holdoutSize: 100, cycles: 3 });
1660
- console.log(`Passed: ${manifest.passed}, Score: ${manifest.score}`);
1661
-
1662
- // SHAKE-256 witness chain for audit
1663
- const chain = solver.witnessChain();
1664
- ```
1665
-
1666
- Three-loop architecture:
1667
- 1. **Fast loop** — constraint propagation (~0.1ms)
1668
- 2. **Medium loop** — PolicyKernel with Thompson Sampling (~1ms)
1669
- 3. **Slow loop** — KnowledgeCompiler for long-term patterns (~10ms)
1670
-
1671
- ### SolverBandit — Decision Intelligence Across Controllers (ADR-010)
1672
-
1673
- The `SolverBandit` is a general-purpose Thompson Sampling bandit that provides explore/exploit decisions for any context-dependent selection problem. It powers adaptive decision-making in 5 AgentDB controllers:
1674
-
1675
- | Controller | What the Bandit Decides | Context Key |
1676
- | --- | --- | --- |
1677
- | **SkillLibrary** | Rerank retrieved skills by task type | `taskType` string |
1678
- | **ReasoningBank** | Rerank matching patterns by task type | query text |
1679
- | **NightlyLearner** | Prioritize experiment candidates | `'experiment'` |
1680
- | **LearningSystem** | Select best RL algorithm (9 options) | task description |
1681
- | **TemporalCompressor** | Choose compression tier (none/half/pq8/pq4/binary) | `hot`/`warm`/`cold` |
1682
-
1683
- Each controller uses the bandit optionally — when no bandit is provided, behavior is unchanged from v2. When present, the bandit reranks results using Thompson-sampled Beta distributions, and controllers feed outcomes back via `recordReward()`.
1684
-
1685
- ```typescript
1686
- import { SolverBandit } from 'agentdb/backends/rvf/SolverBandit';
1687
-
1688
- const bandit = new SolverBandit();
1689
-
1690
- // Select best arm for a context
1691
- const skill = bandit.selectArm('code_review', ['lint_first', 'test_first', 'security_scan']);
1692
-
1693
- // Record outcome
1694
- bandit.recordReward('code_review', skill, 0.85, /* latencyMs */ 120);
1695
-
1696
- // Rerank candidates by learned performance
1697
- const ranked = bandit.rerank('code_review', ['lint_first', 'test_first', 'security_scan']);
1698
-
1699
- // Serialize for cross-session persistence
1700
- const state = bandit.serialize(); // JSON-safe
1701
- const restored = SolverBandit.deserialize(state);
1702
- ```
1703
-
1704
- **Performance:** 100K `selectArm` calls in <200ms, 100K `recordReward` calls in <100ms.
1705
-
1706
- **Wire into AgentDB controllers:**
1707
-
1708
- ```typescript
1709
- import { SolverBandit, SkillLibrary, ReasoningBank, LearningSystem } from 'agentdb';
1710
-
1711
- const bandit = new SolverBandit({ costWeight: 0.01, explorationBonus: 0.1 });
1712
-
1713
- // Pass as optional last parameter to any controller
1714
- const skills = new SkillLibrary(db, embedder, undefined, bandit);
1715
- const patterns = new ReasoningBank(db, embedder, undefined, bandit);
1716
- const learning = new LearningSystem(db, undefined, bandit);
1717
-
1718
- // Controllers automatically rerank results and accept feedback
1719
- const algorithm = learning.recommendAlgorithm('navigation task');
1720
- learning.recordAlgorithmOutcome('navigation task', algorithm, 0.92, 340);
1721
- ```
1722
-
1723
- </details>
1724
-
1725
- ---
1726
-
1727
- ### Enterprise & Security
1728
-
1729
- Production-ready authentication, audit logging, and defense-in-depth security with cryptographic verification.
1730
-
1731
- <details>
1732
- <summary><strong>Security</strong> — defense-in-depth with cryptographic audit trails</summary>
1733
-
1734
- AgentDB provides defense-in-depth security with validation at every system boundary.
1735
-
1736
- ### Input Validation
1737
-
1738
- ```typescript
1739
- import {
1740
- validateVector,
1741
- validateVectorId,
1742
- validateSearchOptions,
1743
- validateHNSWParams,
1744
- sanitizeMetadata,
1745
- validateCypherParams,
1746
- validateLabel,
1747
- validateBatchSize,
1748
- } from 'agentdb/security/validation';
1749
-
1750
- // Vector validation — prevents NaN/Infinity injection
1751
- validateVector(embedding, 384, 'embedding');
1752
-
1753
- // ID validation — prevents path traversal (../, etc.)
1754
- validateVectorId('doc-123', 'id');
1755
-
1756
- // Search bounds — k, threshold, efSearch range checking
1757
- validateSearchOptions({ k: 10, threshold: 0.7 });
1758
-
1759
- // HNSW parameter validation — M, efConstruction, efSearch
1760
- validateHNSWParams({ M: 16, efConstruction: 200, efSearch: 100 });
1761
-
1762
- // Metadata sanitization — strips password, token, key, apiKey, auth fields
1763
- const safe = sanitizeMetadata(userInput);
1764
-
1765
- // Cypher injection prevention
1766
- validateCypherParams(params);
1767
- ```
1768
-
1769
- ### XSS & Injection Prevention
1770
-
1771
- ```typescript
1772
- import {
1773
- validateTaskString,
1774
- validateNumericRange,
1775
- validateEnum,
1776
- } from 'agentdb/security/input-validation';
1777
-
1778
- const task = validateTaskString(input, 'task'); // XSS pattern detection
1779
- const k = validateNumericRange(kVal, 'k', 1, 100);
1780
- const format = validateEnum(fmt, 'format', ['json', 'concise', 'detailed']);
1781
- ```
1782
-
1783
- ### Security Limits
1784
-
1785
- | Parameter | Limit |
1786
- | --- | --- |
1787
- | Max vectors | 10,000,000 |
1788
- | Max dimension | 4,096 |
1789
- | Max batch size | 10,000 |
1790
- | Max k | 10,000 |
1791
- | Max metadata size | 64 KB |
1792
- | Max ID length | 256 chars |
1793
- | Filter expression depth | 64 |
1794
- | ef-search range | 1 - 1,000 |
1795
- | ef-construction range | 4 - 500 |
1796
- | M range | 2 - 64 |
1797
-
1798
- ### Witness Chain Verification
1799
-
1800
- SHAKE-256 cryptographic witness chains provide tamper-evident audit trails:
1801
-
1802
- ```typescript
1803
- const result = backend.verifyWitnessChain();
1804
- if (!result.valid) {
1805
- console.error('Data integrity compromised!');
1806
- }
1807
- ```
1808
-
1809
- ### Provenance Certificates (Explainable Recall)
1810
-
1811
- Every search result can include a Merkle proof explaining why it was selected:
1812
-
1813
- ```typescript
1814
- const { results, certificate } = await causalRecall.recall(
1815
- 'query-id',
1816
- 'optimization strategies',
1817
- 10,
1818
- ['performance'],
1819
- 'internal',
1820
- );
1821
- console.log(`Certificate ID: ${certificate.id}`);
1822
- console.log(`Completeness: ${certificate.completenessScore}`);
1823
- ```
1824
-
1825
- </details>
1826
-
1827
- ---
1828
-
1829
- <details>
1830
- <summary><strong>Quantization & Compression</strong> — up to 32x memory reduction with 5-tier auto-tiering</summary>
1831
-
1832
- AgentDB supports multiple quantization strategies to reduce memory footprint while maintaining search quality.
1833
-
1834
- ### Scalar Quantization
1835
-
1836
- 8-bit and 4-bit scalar quantization for memory-efficient storage:
1837
-
1838
- ```typescript
1839
- import { createScalar8BitStore, createProductQuantizedStore } from 'agentdb/browser/ProductQuantization';
1840
-
1841
- // 8-bit quantization — 4x memory reduction
1842
- const store8 = createScalar8BitStore(384);
1843
- store8.add('doc-1', embedding);
1844
- const results = store8.search(query, 10);
1845
-
1846
- // Product quantization — up to 32x memory reduction
1847
- const storePQ = createProductQuantizedStore(384, { numSubvectors: 48, bitsPerCode: 8 });
1848
- storePQ.add('doc-1', embedding);
1849
- const results = storePQ.search(query, 10);
1850
- ```
1851
-
1852
- ### 5-Tier Temporal Compression
1853
-
1854
- Vectors are automatically compressed based on age and access frequency:
1855
-
1856
- | Tier | Compression | Memory | Quality | Trigger |
1857
- | --- | --- | --- | --- | --- |
1858
- | **Hot** | None | 100% | 100% | Recent / frequently accessed |
1859
- | **Warm** | Half-precision | 50% | ~99% | Moderate age |
1860
- | **Cool** | PQ-8 | ~12% | ~95% | Older data |
1861
- | **Cold** | PQ-4 | ~6% | ~90% | Rarely accessed |
1862
- | **Archive** | Binary | ~3% | ~80% | Archival storage |
1863
-
1864
- ### Matryoshka Dimension Truncation
1865
-
1866
- Reduce embedding dimensions while preserving the most important features:
1867
-
1868
- ```typescript
1869
- // Models trained with Matryoshka loss support dimension truncation
1870
- // 384d -> 128d with minimal quality loss
1871
- const truncated = embedding.slice(0, 128);
1872
- ```
1873
-
1874
- ### NativeAccelerator Quantization
1875
-
1876
- The NativeAccelerator provides hardware-accelerated quantization/dequantization:
1877
-
1878
- ```typescript
1879
- const accel = new NativeAccelerator();
1880
- await accel.initialize();
1881
-
1882
- // Load scalar quantization parameters
1883
- accel.loadSqParams(mins, scales);
1884
- const restored = accel.dequantI8(quantizedBytes);
1885
-
1886
- // Product quantization with codebook
1887
- accel.loadPqCodebook(codebook, numSubvectors, bitsPerCode);
1888
- const distances = accel.pqDistances(query, codes);
1889
- ```
1890
-
1891
- </details>
1892
-
1893
- ---
1894
-
1895
- ### Integration & Tools
1896
-
1897
- Connect AgentDB to LLM providers, embedding models, and distributed systems with real-time sync.
1898
-
1899
- <details>
1900
- <summary><strong>Model Import/Export & Embedding Models</strong> — 5 local models, no API keys</summary>
1901
-
1902
- ### Embedding Models
1903
-
1904
- AgentDB supports multiple embedding models. No API key required — all Xenova models run locally.
1905
-
1906
- | Model | Dimension | Quality | Speed | Best For |
1907
- | --- | --- | --- | --- | --- |
1908
- | **all-MiniLM-L6-v2** (default) | 384 | Good | Fastest | Prototyping |
1909
- | **bge-small-en-v1.5** | 384 | Excellent | Fast | Best 384d quality |
1910
- | **bge-base-en-v1.5** | 768 | Excellent | Moderate | Production |
1911
- | **all-mpnet-base-v2** | 768 | Excellent | Moderate | All-around |
1912
- | **e5-base-v2** | 768 | Excellent | Moderate | Multilingual |
1913
-
1914
- ```bash
1915
- # Default (384d, fast)
1916
- npx agentdb init
1917
-
1918
- # Production (768d, high quality)
1919
- npx agentdb init --dimension 768 --model "Xenova/bge-base-en-v1.5"
1920
- ```
1921
-
1922
- ### LLM Router for Multi-Provider Integration
1923
-
1924
- AgentDB can route queries through multiple LLM providers via `@ruvector/ruvllm`:
1925
-
1926
- ```typescript
1927
- import { isRuvLLMInstalled } from 'agentdb/wrappers';
1928
-
1929
- if (await isRuvLLMInstalled()) {
1930
- // LLM router available for enrichment and reranking
1931
- }
1932
- ```
1933
-
1934
- ### RVF Export/Import
1935
-
1936
- Export vector stores to the portable Cognitive Container format:
1937
-
1938
- ```bash
1939
- # Migrate v2 database to v3 unified .rvf (vectors + relational in one file)
1940
- npx agentdb migrate --source ./v2.db --to v3 --rvf-path ./unified.rvf
1941
-
1942
- # Export existing database to Cognitive Container
1943
- npx agentdb migrate --to rvf --rvf-path ./vectors.rvf
1944
-
1945
- # Import from Cognitive Container into a new backend
1946
- npx agentdb migrate --from rvf --rvf-path ./vectors.rvf --target ./new.db
1947
- ```
1948
-
1949
- ### WASM Export
1950
-
1951
- Export a WASM store to a transferable binary for sharing between browser tabs or workers:
1952
-
1953
- ```typescript
1954
- const bytes = bridge.wasmStoreExport(handle); // Uint8Array
1955
- // Transfer to another worker or save to IndexedDB
1956
- ```
1957
-
1958
- </details>
1959
-
1960
- ---
1961
-
1962
- <details>
1963
- <summary><strong>Query Lifecycle</strong> — what happens when you call searchAsync()</summary>
1964
-
1965
- The full lifecycle of a query through AgentDB's self-learning pipeline:
1966
-
1967
- ```mermaid
1968
- sequenceDiagram
1969
- participant App
1970
- participant Router as Semantic Router
1971
- participant SONA
1972
- participant HNSW as HNSW Index
1973
- participant Trainer as Contrastive Trainer
1974
-
1975
- App->>Router: query(embedding)
1976
- Router->>Router: classify intent
1977
- Router->>SONA: enhance(embedding, trajectories)
1978
- SONA->>SONA: apply micro-LoRA
1979
- SONA->>HNSW: searchAsync(enhanced, k, ef)
1980
- HNSW-->>App: results[]
1981
- App->>Trainer: recordFeedback(quality)
1982
- Trainer->>Trainer: InfoNCE + hard negatives
1983
- Trainer->>SONA: updateLoRA(gradients)
1984
- Note over SONA: EWC++ consolidation<br/>prevents forgetting
1985
- ```
1986
-
1987
- ### Phase Breakdown
1988
-
1989
- 1. **Routing** — `SemanticQueryRouter` classifies query intent via HNSW-indexed embeddings and selects the optimal search strategy
1990
- 2. **Enhancement** — SONA engine enriches the query embedding using trajectory history and context
1991
- 3. **LoRA Application** — Micro-LoRA adapter adjusts the embedding in sub-millisecond time
1992
- 4. **Search** — HNSW index returns top-k results with adaptive ef-search
1993
- 5. **Feedback** — Application records result quality (0.0-1.0)
1994
- 6. **Training** — Contrastive trainer runs InfoNCE loss with hard negative mining
1995
- 7. **Update** — LoRA gradients update the adapter weights
1996
- 8. **Consolidation** — EWC++ prevents catastrophic forgetting of previously learned patterns
1997
-
1998
- </details>
1999
-
2000
- ---
2001
-
2002
- ### Distributed Systems
2003
-
2004
- Multi-database coordination, real-time replication, and production observability.
2005
-
2006
- <details>
2007
- <summary><strong>Multi-Database Coordination</strong> — distributed sync with conflict resolution</summary>
2008
-
2009
- The `MultiDatabaseCoordinator` enables distributed sync between multiple AgentDB instances with configurable conflict resolution.
2010
-
2011
- ```typescript
2012
- import { MultiDatabaseCoordinator } from 'agentdb/coordination/MultiDatabaseCoordinator';
2013
-
2014
- const coordinator = new MultiDatabaseCoordinator({
2015
- replicationFactor: 3,
2016
- syncIntervalMs: 5000,
2017
- conflictResolution: 'merge', // 'last-write-wins' | 'merge' | 'manual'
2018
- autoFailover: true,
2019
- maxRetries: 3,
2020
- });
2021
-
2022
- // Register database instances
2023
- await coordinator.registerInstance({
2024
- id: 'primary',
2025
- url: 'file:///data/primary.rvf',
2026
- role: 'primary',
2027
- });
2028
- await coordinator.registerInstance({
2029
- id: 'replica-1',
2030
- url: 'file:///data/replica-1.rvf',
2031
- role: 'replica',
2032
- });
2033
-
2034
- // Sync a specific instance
2035
- const result = await coordinator.syncInstance('replica-1');
2036
- console.log(`Synced: ${result.recordsSynced}, Conflicts: ${result.conflicts}`);
2037
-
2038
- // Broadcast operations to all instances
2039
- await coordinator.broadcast('insertAsync', ['doc-1', embedding, { source: 'api' }]);
2040
-
2041
- // Monitor instance status
2042
- coordinator.onStatusChange((instanceId, status) => {
2043
- console.log(`${instanceId}: ${status.state}`); // 'healthy' | 'degraded' | 'offline'
2044
- });
2045
- ```
2046
-
2047
- ### Conflict Resolution Strategies
2048
-
2049
- | Strategy | Description | Best For |
2050
- | --- | --- | --- |
2051
- | **last-write-wins** | Most recent write wins (LWW) | Simple setups, eventual consistency |
2052
- | **merge** | Quality-based weighted average | Learning systems, federated aggregation |
2053
- | **manual** | Returns conflicts for user resolution | Critical data, compliance requirements |
2054
-
2055
- </details>
2056
-
2057
- ---
2058
-
2059
- <details>
2060
- <summary><strong>Real-Time Sync (QUIC)</strong> — bidirectional replication with 0-RTT resumption</summary>
2061
-
2062
- AgentDB supports real-time bidirectional sync between instances using QUIC transport and a high-level `SyncCoordinator`.
2063
-
2064
- ### QUIC Transport
2065
-
2066
- QUIC provides multiplexed streams over a single connection with zero head-of-line blocking, connection migration between networks, and 0-RTT session resumption:
2067
-
2068
- ```typescript
2069
- import { QUICServer } from 'agentdb/controllers/QUICServer';
2070
-
2071
- const server = new QUICServer({
2072
- port: 4433,
2073
- maxConnections: 100,
2074
- rateLimit: {
2075
- requestsPerMin: 1000,
2076
- bytesPerMin: 10_000_000,
2077
- },
2078
- authToken: 'secret', // optional token validation
2079
- });
2080
-
2081
- // Stale connections auto-cleaned after 5 minutes idle
2082
- // Sync types: 'episodes' | 'skills' | 'edges' | 'full'
2083
- // Incremental sync via `since` parameter and cursor-based pagination
2084
- ```
2085
-
2086
- ### Sync Coordinator
2087
-
2088
- High-level bidirectional sync with conflict resolution, progress tracking, and auto-sync:
2089
-
2090
- ```typescript
2091
- import { SyncCoordinator } from 'agentdb/controllers/SyncCoordinator';
2092
-
2093
- const sync = new SyncCoordinator({
2094
- conflictStrategy: 'latest-wins', // 'local-wins' | 'remote-wins' | 'latest-wins' | 'merge'
2095
- batchSize: 100,
2096
- autoSyncInterval: 60000, // Auto-sync every 60 seconds
2097
- });
2098
-
2099
- // Push local changes, pull remote changes, resolve conflicts
2100
- const report = await sync.sync();
2101
- console.log(report);
2102
- // {
2103
- // success: true,
2104
- // durationMs: 342,
2105
- // itemsPushed: 15,
2106
- // itemsPulled: 8,
2107
- // conflictsResolved: 2,
2108
- // bytesTransferred: 48200,
2109
- // errors: [],
2110
- // }
2111
-
2112
- // Progress tracking through 5 phases:
2113
- // detecting → pushing → pulling → resolving → applying
2114
-
2115
- // Sync state persists across restarts
2116
- await sync.saveSyncState();
2117
- // Tracks: lastSyncAt, lastEpisodeSync, lastSkillSync, lastEdgeSync,
2118
- // totalItemsSynced, totalBytesSynced, syncCount
2119
- ```
2120
-
2121
- ### Conflict Resolution
2122
-
2123
- | Strategy | Behavior |
2124
- | --- | --- |
2125
- | `local-wins` | Local version always kept |
2126
- | `remote-wins` | Remote version always accepted |
2127
- | `latest-wins` | Most recent timestamp wins |
2128
- | `merge` | Quality-weighted merge of both versions |
2129
-
2130
- </details>
2131
-
2132
- ---
2133
-
2134
- <details>
2135
- <summary><strong>Observability</strong> — OpenTelemetry traces and Prometheus metrics built in</summary>
2136
-
2137
- AgentDB integrates with OpenTelemetry for production monitoring.
2138
-
2139
- ### Traces
2140
-
2141
- Automatic span creation for search, insert, and sync operations:
2142
-
2143
- ```typescript
2144
- import { initTelemetry } from 'agentdb/observability';
2145
-
2146
- initTelemetry({
2147
- serviceName: 'my-agent',
2148
- exporterUrl: 'http://localhost:4318', // OTLP HTTP endpoint
2149
- });
2150
-
2151
- // All AgentDB operations automatically generate spans:
2152
- // - agentdb.search (with k, backend, latency attributes)
2153
- // - agentdb.insert (with batchSize, backend)
2154
- // - agentdb.sync (with itemsSynced, conflicts)
2155
- ```
2156
-
2157
- ### Metrics
2158
-
2159
- Prometheus-compatible metrics for latency, throughput, and error rates:
2160
-
2161
- - `agentdb_search_duration_ms` — search latency histogram
2162
- - `agentdb_insert_duration_ms` — insert latency histogram
2163
- - `agentdb_cache_hit_ratio` — MCP tool cache effectiveness
2164
- - `agentdb_learning_loss` — contrastive training loss
2165
- - `agentdb_vector_count` — total vectors stored
2166
-
2167
- </details>
2168
-
2169
- ---
2170
-
2171
- ### Additional Capabilities
2172
-
2173
- Reinforcement learning, hybrid search, LLM routing, authentication, and high-performance wrappers.
2174
-
2175
- <details>
2176
- <summary><strong>Reinforcement Learning</strong> — 9 algorithms from Q-Learning to Monte Carlo Tree Search</summary>
2177
-
2178
- AgentDB includes a complete reinforcement learning system with 9 algorithms for building agents that learn optimal strategies through interaction:
2179
-
2180
- ### Available Algorithms
2181
-
2182
- | Algorithm | Type | Best For |
2183
- | --- | --- | --- |
2184
- | **Q-Learning** | Value-based | Simple discrete action spaces |
2185
- | **SARSA** | Value-based | On-policy learning, safer exploration |
2186
- | **Deep Q-Network (DQN)** | Value-based | Complex state spaces with neural function approximation |
2187
- | **Policy Gradient** | Policy-based | Continuous action spaces |
2188
- | **Actor-Critic** | Hybrid | Balances value and policy learning |
2189
- | **PPO** | Policy-based | Stable training with clipped objectives |
2190
- | **Decision Transformer** | Sequence-based | Offline RL from logged trajectories |
2191
- | **Monte Carlo Tree Search** | Planning | Game-like decision trees, look-ahead planning |
2192
- | **Model-Based RL** | Model-based | Sample-efficient learning with world models |
2193
-
2194
- ### Usage
2195
-
2196
- ```typescript
2197
- import { LearningSystem } from 'agentdb';
2198
-
2199
- const learner = new LearningSystem(db, {
2200
- algorithm: 'ppo', // any of the 9 algorithms
2201
- learningRate: 0.001,
2202
- discountFactor: 0.99,
2203
- explorationRate: 0.1,
2204
- });
2205
-
2206
- // Start a learning session
2207
- const session = await learner.createSession({
2208
- task: 'optimize_api_responses',
2209
- maxEpisodes: 100,
2210
- });
2211
-
2212
- // Predict next action
2213
- const prediction = await learner.predict(session.id, currentState);
2214
- // { action, confidence, explorationUsed }
2215
-
2216
- // Record outcome
2217
- await learner.recordReward(session.id, prediction.action, reward);
2218
-
2219
- // Train on accumulated experience
2220
- await learner.train(session.id);
2221
-
2222
- // Transfer learning to new tasks
2223
- await learner.transfer(sourceSessionId, targetSessionId);
2224
- ```
2225
-
2226
- ### MCP Tools for RL
2227
-
2228
- All 9 algorithms are accessible through MCP tools:
2229
- - `agentdb_rl_create_session` — start a new learning session
2230
- - `agentdb_rl_predict` — get next action recommendation
2231
- - `agentdb_rl_record_reward` — record outcome feedback
2232
- - `agentdb_rl_train` — trigger training round
2233
- - `agentdb_rl_transfer` — transfer learned policy to new task
2234
- - `agentdb_rl_explain` — explain why a prediction was made
2235
-
2236
- </details>
2237
-
2238
- ---
2239
-
2240
- <details>
2241
- <summary><strong>Hybrid Search</strong> — BM25 keyword + vector fusion for best-of-both-worlds retrieval</summary>
2242
-
2243
- Combine traditional keyword search (BM25) with vector similarity for retrieval that handles both exact matches and semantic meaning:
2244
-
2245
- ```typescript
2246
- import { createHybridSearch, createKeywordIndex } from 'agentdb';
2247
-
2248
- // Create keyword index (BM25)
2249
- const keywordIndex = createKeywordIndex({
2250
- k1: 1.2, // term frequency saturation
2251
- b: 0.75, // document length normalization
2252
- avgDocLength: 100,
2253
- });
2254
-
2255
- // Index documents
2256
- keywordIndex.add('doc-1', 'JWT authentication with refresh token rotation');
2257
- keywordIndex.add('doc-2', 'OAuth2 PKCE flow for mobile applications');
2258
-
2259
- // Create hybrid search (keyword + vector)
2260
- const hybrid = createHybridSearch(keywordIndex, vectorBackend, {
2261
- fusion: 'rrf', // 'rrf' (Reciprocal Rank Fusion) | 'linear' | 'max'
2262
- keywordWeight: 0.3, // 30% keyword, 70% vector
2263
- vectorWeight: 0.7,
2264
- });
2265
-
2266
- // Search with both keyword and semantic matching
2267
- const results = await hybrid.search({
2268
- text: 'JWT refresh token', // keyword query
2269
- embedding: queryEmbedding, // vector query
2270
- k: 10,
2271
- });
2272
- // Results fused from both sources — exact term matches + semantic similarity
2273
- ```
2274
-
2275
- ### Fusion Strategies
2276
-
2277
- | Strategy | How it works | Best For |
2278
- | --- | --- | --- |
2279
- | **RRF** (default) | `1/(k + rank)` — rank-based fusion, no score calibration needed | General use |
2280
- | **Linear** | `α × keyword_score + β × vector_score` — weighted score combination | When you know the right balance |
2281
- | **Max** | `max(keyword_score, vector_score)` — takes highest signal | When either source is sufficient |
2282
-
2283
- > **When to use hybrid search:** When your data contains domain-specific terms (function names, error codes, product IDs) that vector embeddings might miss, but you also want semantic understanding for natural language queries.
2284
-
2285
- </details>
2286
-
2287
- ---
2288
-
2289
- <details>
2290
- <summary><strong>LLM Router</strong> — auto-select from 5 providers based on cost, quality, and privacy</summary>
2291
-
2292
- AgentDB can route LLM queries to the optimal provider based on your constraints:
2293
-
2294
- ```typescript
2295
- import { LLMRouter } from 'agentdb';
2296
-
2297
- const router = new LLMRouter({
2298
- providers: {
2299
- ruvllm: { enabled: true }, // Local, SIMD-optimized, free
2300
- openrouter: { apiKey: process.env.OPENROUTER_KEY }, // 200+ models, 99% cost savings
2301
- gemini: { apiKey: process.env.GEMINI_KEY }, // Free tier available
2302
- anthropic: { apiKey: process.env.ANTHROPIC_KEY }, // Claude models
2303
- onnx: { enabled: true }, // Local models via transformers.js
2304
- },
2305
- strategy: 'auto', // auto-selects based on constraints below
2306
- constraints: {
2307
- maxCostPerQuery: 0.001, // max $0.001 per query
2308
- minQuality: 0.8, // minimum quality score
2309
- preferLocal: true, // prefer local models when possible
2310
- requirePrivacy: false, // if true, only uses local providers
2311
- },
2312
- });
2313
-
2314
- const response = await router.generate('Summarize this document...', {
2315
- maxTokens: 500,
2316
- temperature: 0.7,
2317
- });
2318
- ```
2319
-
2320
- ### Provider Comparison
2321
-
2322
- | Provider | Latency | Cost | Privacy | Models |
2323
- | --- | --- | --- | --- | --- |
2324
- | **RuvLLM** | Fastest | Free | Full (local) | SIMD-optimized local models |
2325
- | **ONNX** | Fast | Free | Full (local) | transformers.js models |
2326
- | **OpenRouter** | ~500ms | $0.0001+ | Cloud | 200+ models (GPT-4, Claude, Llama, etc.) |
2327
- | **Gemini** | ~300ms | Free tier | Cloud | Gemini Pro, Flash |
2328
- | **Anthropic** | ~1s | $0.003+ | Cloud | Claude Opus, Sonnet, Haiku |
2329
-
2330
- ```typescript
2331
- // Check what's available locally
2332
- import { isRuvLLMInstalled } from 'agentdb';
2333
- if (await isRuvLLMInstalled()) {
2334
- // Local inference available — no API keys needed
2335
- }
2336
- ```
2337
-
2338
- </details>
2339
-
2340
- ---
2341
-
2342
- <details>
2343
- <summary><strong>Auth & Audit</strong> — JWT, API keys, Argon2id, and compliance-ready logging</summary>
2344
-
2345
- Enterprise-ready authentication and audit logging for production deployments.
2346
-
2347
- ### Authentication
2348
-
2349
- ```typescript
2350
- import { AuthService } from 'agentdb/services/auth';
2351
-
2352
- const auth = new AuthService(db, {
2353
- jwtSecret: process.env.JWT_SECRET,
2354
- accessTokenTTL: '15m',
2355
- refreshTokenTTL: '7d',
2356
- maxLoginAttempts: 5, // account lockout after 5 failures
2357
- lockoutDuration: '30m',
2358
- });
2359
-
2360
- // User registration (Argon2id password hashing)
2361
- const user = await auth.register({ email, password, role: 'user' });
2362
-
2363
- // Login — returns access + refresh token pair
2364
- const { accessToken, refreshToken } = await auth.login(email, password);
2365
-
2366
- // Token verification
2367
- const payload = await auth.verifyAccessToken(accessToken);
2368
-
2369
- // API key management
2370
- const apiKey = await auth.generateApiKey(userId, { name: 'prod-key', scopes: ['read', 'write'] });
2371
- await auth.rotateApiKey(apiKey.id); // automatic rotation
2372
- ```
2373
-
2374
- ### Audit Logging
2375
-
2376
- ```typescript
2377
- import { AuditLogger } from 'agentdb/services/audit-logger';
2378
-
2379
- const audit = new AuditLogger({
2380
- retention: '90d', // log retention period
2381
- compliance: ['SOC2', 'GDPR'], // compliance frameworks
2382
- autoRotate: true, // automatic log rotation
2383
- });
2384
-
2385
- // 13 audit event types tracked automatically:
2386
- // - jwt_auth, api_key_create, api_key_rotate, api_key_revoke
2387
- // - login_success, login_failure, registration
2388
- // - config_change, permission_change
2389
- // - rate_limit_exceeded, sensitive_data_access
2390
- // - data_export, data_deletion
2391
- ```
2392
-
2393
- ### Security Utilities
2394
-
2395
- ```typescript
2396
- import { hashPassword, verifyPassword, generateApiKey } from 'agentdb/utils/crypto';
2397
-
2398
- const hash = await hashPassword('user-password'); // Argon2id
2399
- const valid = await verifyPassword('user-password', hash);
2400
- const key = generateApiKey(); // cryptographically random
2401
- ```
2402
-
2403
- </details>
2404
-
2405
- ---
2406
-
2407
- <details>
2408
- <summary><strong>Metadata Filtering</strong> — 10 MongoDB-style query operators</summary>
2409
-
2410
- Filter search results and database queries using MongoDB-style operators:
2411
-
2412
- ```typescript
2413
- import { MetadataFilter } from 'agentdb';
2414
-
2415
- const filter = new MetadataFilter();
2416
-
2417
- // Episodes with reward > 0.8 and specific tags
2418
- const episodes = await filter.filterEpisodes(db, {
2419
- reward: { $gt: 0.8 },
2420
- tags: { $contains: 'security' },
2421
- status: { $in: ['success', 'partial'] },
2422
- archived: { $exists: false },
2423
- });
2424
-
2425
- // Patterns matching complex criteria
2426
- const patterns = await filter.filterPatterns(db, {
2427
- successRate: { $gte: 0.7, $lte: 1.0 },
2428
- taskType: { $ne: 'deprecated' },
2429
- createdAt: { $gt: lastWeekTimestamp },
2430
- });
2431
- ```
2432
-
2433
- ### Supported Operators
2434
-
2435
- | Operator | Description | Example |
2436
- | --- | --- | --- |
2437
- | `$eq` | Equal | `{ status: { $eq: 'active' } }` |
2438
- | `$ne` | Not equal | `{ role: { $ne: 'admin' } }` |
2439
- | `$gt` | Greater than | `{ reward: { $gt: 0.5 } }` |
2440
- | `$gte` | Greater than or equal | `{ score: { $gte: 0.8 } }` |
2441
- | `$lt` | Less than | `{ age: { $lt: 90 } }` |
2442
- | `$lte` | Less than or equal | `{ priority: { $lte: 3 } }` |
2443
- | `$in` | In array | `{ type: { $in: ['a', 'b'] } }` |
2444
- | `$nin` | Not in array | `{ status: { $nin: ['deleted'] } }` |
2445
- | `$contains` | Contains substring | `{ tags: { $contains: 'auth' } }` |
2446
- | `$exists` | Field exists | `{ metadata: { $exists: true } }` |
2447
-
2448
- </details>
2449
-
2450
- ---
2451
-
2452
- <details>
2453
- <summary><strong>AgentDBFast</strong> — 50-200x faster programmatic API (skip the CLI overhead)</summary>
2454
-
2455
- The `AgentDBFast` wrapper provides direct programmatic access that's 50-200x faster than going through the CLI:
2456
-
2457
- ```typescript
2458
- import { createFastAgentDB } from 'agentdb/wrappers/agentdb-fast';
2459
-
2460
- const db = await createFastAgentDB({
2461
- path: './agent-memory.db',
2462
- dimension: 384,
2463
- model: 'Xenova/all-MiniLM-L6-v2',
2464
- });
2465
-
2466
- // All operations bypass CLI parsing overhead
2467
- await db.insert('doc-1', embedding, metadata);
2468
- const results = await db.search(queryEmbedding, 10);
2469
- await db.batchInsert(documents);
2470
-
2471
- // Performance wrapper includes:
2472
- // - Direct function calls (no CLI arg parsing)
2473
- // - Pre-initialized connections (no startup cost per call)
2474
- // - Batched operations
2475
- // - Connection pooling
2476
- ```
2477
-
2478
- ### Wrapper Performance vs CLI
2479
-
2480
- | Operation | CLI | AgentDBFast | Speedup |
2481
- | --- | --- | --- | --- |
2482
- | Single insert | ~20ms | ~0.1ms | 200x |
2483
- | Search (k=10) | ~15ms | ~0.08ms | 187x |
2484
- | Batch insert (100) | ~500ms | ~10ms | 50x |
2485
-
2486
- ### Attention Wrappers
2487
-
2488
- Production-ready attention implementations with 11-22x speedup over naive:
2489
-
2490
- ```typescript
2491
- import {
2492
- MultiHeadAttention,
2493
- FlashAttention,
2494
- LinearAttention,
2495
- HyperbolicAttention,
2496
- MoEAttention,
2497
- } from 'agentdb/wrappers';
2498
-
2499
- // Flash Attention — O(N) memory instead of O(N^2)
2500
- const flash = new FlashAttention({ numHeads: 8 });
2501
- const result = await flash.forward(query, keys, values);
2502
-
2503
- // Mixture of Experts — routes to specialized attention heads
2504
- const moe = new MoEAttention({ numExperts: 4, topK: 2 });
2505
- const result = await moe.forward(query, keys, values);
2506
- ```
2507
-
2508
- ### Embedding Providers
2509
-
2510
- Multiple embedding backends with automatic fallback:
2511
-
2512
- ```typescript
2513
- import {
2514
- OpenAIEmbeddingService,
2515
- TransformersEmbeddingService,
2516
- MockEmbeddingService,
2517
- } from 'agentdb/wrappers';
2518
-
2519
- // OpenAI (cloud)
2520
- const openai = new OpenAIEmbeddingService({ apiKey: process.env.OPENAI_KEY });
2521
-
2522
- // Transformers.js (local, free)
2523
- const local = new TransformersEmbeddingService({ model: 'Xenova/all-MiniLM-L6-v2' });
2524
-
2525
- // Mock (testing)
2526
- const mock = new MockEmbeddingService({ dimension: 384 });
2527
- ```
2528
-
2529
- </details>
2530
-
2531
- ---
2532
-
2533
- <details>
2534
- <summary><strong>Benchmark Suite</strong> — 5 built-in benchmarks with custom benchmark support</summary>
2535
-
2536
- Run performance benchmarks to validate your deployment:
2537
-
2538
- ```typescript
2539
- import { BenchmarkSuite, runBenchmarks, formatReportAsMarkdown } from 'agentdb';
2540
-
2541
- // Run all built-in benchmarks
2542
- const report = await runBenchmarks({
2543
- dimension: 384,
2544
- iterations: 100,
2545
- warmup: 10,
2546
- });
2547
-
2548
- console.log(formatReportAsMarkdown(report));
2549
- ```
2550
-
2551
- ### Built-in Benchmarks
2552
-
2553
- | Benchmark | Measures | Key Metrics |
2554
- | --- | --- | --- |
2555
- | **VectorInsertBenchmark** | Insert throughput | ops/sec, p50/p99 latency |
2556
- | **VectorSearchBenchmark** | Search performance | ops/sec, recall@k, latency distribution |
2557
- | **MemoryUsageBenchmark** | RAM consumption | bytes per vector, total footprint |
2558
- | **ConcurrencyBenchmark** | Parallel performance | throughput under load, contention |
2559
- | **QuantizationBenchmark** | Compression tradeoffs | quality loss vs memory savings |
2560
-
2561
- ### Custom Benchmarks
2562
-
2563
- ```typescript
2564
- import { Benchmark, BenchmarkSuite } from 'agentdb';
2565
-
2566
- class MyBenchmark extends Benchmark {
2567
- name = 'my-custom-benchmark';
2568
-
2569
- async setup() { /* prepare data */ }
2570
- async run() { /* measure this */ }
2571
- async teardown() { /* cleanup */ }
2572
- }
2573
-
2574
- const suite = new BenchmarkSuite();
2575
- suite.add(new MyBenchmark());
2576
- const report = await suite.run({ iterations: 50 });
2577
-
2578
- // Compare reports across runs
2579
- import { formatComparisonAsMarkdown } from 'agentdb';
2580
- console.log(formatComparisonAsMarkdown(reportBefore, reportAfter));
2581
- ```
2582
-
2583
- ### CLI Benchmarks
2584
-
2585
- ```bash
2586
- npm run benchmark # Quick benchmark
2587
- npm run benchmark:full # Full suite
2588
- npm run benchmark:attention # Attention mechanism performance
2589
- npm run benchmark:backends # Compare all backends
2590
- npm run benchmark:ruvector # RuVector-specific benchmarks
2591
- npm run benchmark:all # Everything
2592
- ```
2593
-
2594
- </details>
2595
-
2596
- ---
2597
-
2598
- ## Testing
2599
-
2600
- <details>
2601
- <summary><strong>Test Suite</strong> — unit, integration, performance, security, and browser tests</summary>
2602
-
2603
- AgentDB ships with a comprehensive test suite covering every layer of the stack. All tests run via [Vitest](https://vitest.dev/) with parallel execution.
2604
-
2605
- ### Quick Commands
2606
-
2607
- ```bash
2608
- npm test # Run all tests (watch mode)
2609
- npm run test:unit # Unit tests only (single run)
2610
- npm run test:browser # Browser bundle + WASM tests
2611
- npm run test:ci # CI pipeline: browser tests + build + bundle verification
2612
- ```
2613
-
2614
- ### What's Tested
2615
-
2616
- | Suite | Coverage | What it validates |
2617
- | --- | --- | --- |
2618
- | **Unit tests** | Core controllers, memory patterns, embedding service, quantization | All 6 cognitive memory patterns, 9 RL algorithms, filter expressions, security validators |
2619
- | **Browser tests** | WASM store, attention mechanisms, product quantization, SIMD fallbacks | Full vector DB in browser, Flash/Hyperbolic/MoE attention, PQ8/PQ16/PQ32 compression |
2620
- | **Integration tests** | End-to-end flows, backend auto-selection, MCP tool execution | Self-learning pipeline, Cognitive Container operations, federated aggregation |
2621
- | **Performance tests** | Latency benchmarks, throughput, scaling behavior | 61us search target, 32.6M ops/sec pattern search, batch insert speedup |
2622
- | **Security tests** | Input validation, injection prevention, witness chain verification | XSS patterns, SQL injection, path traversal, Cypher sanitization, SHAKE-256 |
2623
-
2624
- ### Benchmarks
2625
-
2626
- ```bash
2627
- npm run benchmark # Quick benchmark (insert + search)
2628
- npm run benchmark:full # Full suite with all backends
2629
- npm run benchmark:attention # Attention mechanism performance
2630
- npm run benchmark:backends # Compare RuVector vs RVF vs HNSWLib vs sql.js
2631
- npm run benchmark:ruvector # RuVector-specific benchmarks
2632
- npm run benchmark:all # Run everything
2633
- ```
2634
-
2635
- ### CI Pipeline
2636
-
2637
- The CI pipeline runs `test:ci` which executes:
2638
- 1. **Browser bundle tests** — verifies WASM and JS fallbacks work
2639
- 2. **TypeScript build** — full `tsc` compilation
2640
- 3. **Bundle verification** — ensures all export paths resolve correctly
2641
-
2642
- ### Writing Custom Tests
2643
-
2644
- ```typescript
2645
- import { describe, it, expect } from 'vitest';
2646
- import { createDatabase, ReasoningBank, EmbeddingService } from 'agentdb';
2647
-
2648
- describe('My Agent Memory', () => {
2649
- it('stores and retrieves patterns', async () => {
2650
- const db = await createDatabase(':memory:');
2651
- const embedder = new EmbeddingService({ model: 'Xenova/all-MiniLM-L6-v2' });
2652
- await embedder.initialize();
2653
-
2654
- const bank = new ReasoningBank(db, embedder);
2655
- await bank.storePattern({ taskType: 'test', approach: 'TDD', successRate: 0.95 });
2656
-
2657
- const results = await bank.searchPatterns({ task: 'testing', k: 5 });
2658
- expect(results.length).toBeGreaterThan(0);
2659
- });
2660
- });
2661
- ```
2662
-
2663
- </details>
2664
-
2665
- ---
2666
-
2667
- ## Documentation
2668
-
2669
- | Document | Description |
2670
- | --- | --- |
2671
- | [MCP Tool Optimization Guide](docs/guides/) | Comprehensive MCP patterns |
2672
- | [Embedding Models Guide](docs/guides/) | Model selection and benchmarks |
2673
- | [Simulation System](simulation/README.md) | 31 scenarios, interactive wizard |
2674
- | [Security Hardening](docs/guides/) | Input validation and security patterns |
2675
- | [Chat Ecosystem](../agentdb-chat/README.md) | `@agentdb/chat` integration guide |
2676
- | [ADR-010: Solver Integration](docs/adrs/ADR-010-rvf-solver-v014-deep-integration.md) | SolverBandit + rvf-solver deep integration |
2677
-
2678
- ---
2679
-
2680
- ## Contributing
2681
-
2682
- See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines. Areas of interest: additional RL algorithms, performance optimizations, new backend integrations, documentation improvements.
2683
-
2684
- ---
2685
-
2686
- ## License
2687
-
2688
- MIT OR Apache-2.0 — See [LICENSE-MIT](LICENSE-MIT) and [LICENSE-APACHE](LICENSE-APACHE).
2689
-
2690
- ---
2691
-
2692
- **The only vector database that learns.** Start in 30 seconds:
2693
-
2694
- ```bash
2695
- npm install agentdb
2696
- ```
342
+ **Built with ❤️ for the agentic era**
2697
343
 
2698
- [Quick Start](#quick-start) | [Tutorials](#tutorials) | [MCP Integration](#mcp-integration) | [GitHub](https://github.com/ruvnet/agentic-flow/tree/main/packages/agentdb) | [npm](https://www.npmjs.com/package/agentdb)
344
+ [Documentation](./docs/) | [GitHub](https://github.com/ruvnet/agentic-flow/tree/main/packages/agentdb) | [npm](https://www.npmjs.com/package/agentdb)