agentdb 3.0.0-alpha.2 → 3.0.0-alpha.20

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 (519) hide show
  1. package/README.md +208 -2593
  2. package/dist/src/backends/GraphBackend.d.ts +8 -8
  3. package/dist/src/backends/GraphBackend.d.ts.map +1 -1
  4. package/dist/src/backends/GraphBackend.js +15 -16
  5. package/dist/src/backends/GraphBackend.js.map +1 -1
  6. package/dist/src/backends/LearningBackend.d.ts +2 -2
  7. package/dist/src/backends/LearningBackend.d.ts.map +1 -1
  8. package/dist/src/backends/LearningBackend.js +10 -11
  9. package/dist/src/backends/LearningBackend.js.map +1 -1
  10. package/dist/src/backends/VectorBackend.d.ts +10 -0
  11. package/dist/src/backends/VectorBackend.d.ts.map +1 -1
  12. package/dist/src/backends/detector.d.ts +3 -25
  13. package/dist/src/backends/detector.d.ts.map +1 -1
  14. package/dist/src/backends/detector.js +15 -119
  15. package/dist/src/backends/detector.js.map +1 -1
  16. package/dist/src/backends/graph/GraphDatabaseAdapter.d.ts +55 -1
  17. package/dist/src/backends/graph/GraphDatabaseAdapter.d.ts.map +1 -1
  18. package/dist/src/backends/graph/GraphDatabaseAdapter.js +133 -7
  19. package/dist/src/backends/graph/GraphDatabaseAdapter.js.map +1 -1
  20. package/dist/src/backends/hnswlib/HNSWLibBackend.d.ts +2 -2
  21. package/dist/src/backends/hnswlib/HNSWLibBackend.d.ts.map +1 -1
  22. package/dist/src/backends/hnswlib/HNSWLibBackend.js +12 -21
  23. package/dist/src/backends/hnswlib/HNSWLibBackend.js.map +1 -1
  24. package/dist/src/backends/index.d.ts +3 -25
  25. package/dist/src/backends/index.d.ts.map +1 -1
  26. package/dist/src/backends/index.js +1 -23
  27. package/dist/src/backends/index.js.map +1 -1
  28. package/dist/src/backends/ruvector/RuVectorBackend.d.ts +4 -4
  29. package/dist/src/backends/ruvector/RuVectorBackend.d.ts.map +1 -1
  30. package/dist/src/backends/ruvector/RuVectorBackend.js +2 -2
  31. package/dist/src/backends/ruvector/RuVectorBackend.js.map +1 -1
  32. package/dist/src/backends/ruvector/RuVectorLearning.d.ts.map +1 -1
  33. package/dist/src/backends/ruvector/RuVectorLearning.js +5 -10
  34. package/dist/src/backends/ruvector/RuVectorLearning.js.map +1 -1
  35. package/dist/src/backends/rvf/SelfLearningRvfBackend.d.ts.map +1 -1
  36. package/dist/src/backends/rvf/SelfLearningRvfBackend.js +45 -2
  37. package/dist/src/backends/rvf/SelfLearningRvfBackend.js.map +1 -1
  38. package/dist/src/backends/rvf/SqlJsRvfBackend.d.ts +26 -0
  39. package/dist/src/backends/rvf/SqlJsRvfBackend.d.ts.map +1 -1
  40. package/dist/src/backends/rvf/SqlJsRvfBackend.js +93 -31
  41. package/dist/src/backends/rvf/SqlJsRvfBackend.js.map +1 -1
  42. package/dist/src/benchmark/BenchmarkSuite.d.ts.map +1 -1
  43. package/dist/src/benchmark/BenchmarkSuite.js +0 -2
  44. package/dist/src/benchmark/BenchmarkSuite.js.map +1 -1
  45. package/dist/src/benchmarks/wasm-vector-benchmark.d.ts +10 -0
  46. package/dist/src/benchmarks/wasm-vector-benchmark.d.ts.map +1 -0
  47. package/dist/src/benchmarks/wasm-vector-benchmark.js +196 -0
  48. package/dist/src/benchmarks/wasm-vector-benchmark.js.map +1 -0
  49. package/dist/src/browser/AdvancedFeatures.d.ts.map +1 -1
  50. package/dist/src/browser/AdvancedFeatures.js +10 -3
  51. package/dist/src/browser/AdvancedFeatures.js.map +1 -1
  52. package/dist/src/browser/AttentionBrowser.d.ts.map +1 -1
  53. package/dist/src/browser/AttentionBrowser.js +13 -5
  54. package/dist/src/browser/AttentionBrowser.js.map +1 -1
  55. package/dist/src/browser/HNSWIndex.d.ts +1 -31
  56. package/dist/src/browser/HNSWIndex.d.ts.map +1 -1
  57. package/dist/src/browser/HNSWIndex.js +18 -136
  58. package/dist/src/browser/HNSWIndex.js.map +1 -1
  59. package/dist/src/browser/ProductQuantization.d.ts.map +1 -1
  60. package/dist/src/browser/ProductQuantization.js +1 -0
  61. package/dist/src/browser/ProductQuantization.js.map +1 -1
  62. package/dist/src/browser/index.d.ts +3 -3
  63. package/dist/src/browser/index.d.ts.map +1 -1
  64. package/dist/src/browser/index.js +1 -2
  65. package/dist/src/browser/index.js.map +1 -1
  66. package/dist/src/cli/agentdb-cli.d.ts +2 -3
  67. package/dist/src/cli/agentdb-cli.d.ts.map +1 -1
  68. package/dist/src/cli/agentdb-cli.js +142 -96
  69. package/dist/src/cli/agentdb-cli.js.map +1 -1
  70. package/dist/src/cli/commands/attention.js +15 -5
  71. package/dist/src/cli/commands/attention.js.map +1 -1
  72. package/dist/src/cli/commands/doctor.d.ts +0 -2
  73. package/dist/src/cli/commands/doctor.d.ts.map +1 -1
  74. package/dist/src/cli/commands/doctor.js +6 -111
  75. package/dist/src/cli/commands/doctor.js.map +1 -1
  76. package/dist/src/cli/commands/hyperbolic.d.ts.map +1 -1
  77. package/dist/src/cli/commands/hyperbolic.js +15 -3
  78. package/dist/src/cli/commands/hyperbolic.js.map +1 -1
  79. package/dist/src/cli/commands/init.d.ts +1 -2
  80. package/dist/src/cli/commands/init.d.ts.map +1 -1
  81. package/dist/src/cli/commands/init.js +7 -30
  82. package/dist/src/cli/commands/init.js.map +1 -1
  83. package/dist/src/cli/commands/install-embeddings.d.ts +1 -1
  84. package/dist/src/cli/commands/install-embeddings.d.ts.map +1 -1
  85. package/dist/src/cli/commands/install-embeddings.js +17 -11
  86. package/dist/src/cli/commands/install-embeddings.js.map +1 -1
  87. package/dist/src/cli/commands/learn.d.ts.map +1 -1
  88. package/dist/src/cli/commands/learn.js +12 -6
  89. package/dist/src/cli/commands/learn.js.map +1 -1
  90. package/dist/src/cli/commands/migrate.d.ts.map +1 -1
  91. package/dist/src/cli/commands/migrate.js +31 -10
  92. package/dist/src/cli/commands/migrate.js.map +1 -1
  93. package/dist/src/cli/commands/route.d.ts.map +1 -1
  94. package/dist/src/cli/commands/route.js +6 -1
  95. package/dist/src/cli/commands/route.js.map +1 -1
  96. package/dist/src/cli/commands/simulate-report.js +14 -2
  97. package/dist/src/cli/commands/simulate-report.js.map +1 -1
  98. package/dist/src/cli/commands/simulate-wizard.js.map +1 -1
  99. package/dist/src/cli/commands/simulate.d.ts +7 -0
  100. package/dist/src/cli/commands/simulate.d.ts.map +1 -0
  101. package/dist/src/cli/commands/simulate.js +100 -0
  102. package/dist/src/cli/commands/simulate.js.map +1 -0
  103. package/dist/src/cli/commands/status.js +1 -5
  104. package/dist/src/cli/commands/status.js.map +1 -1
  105. package/dist/src/cli/lib/attention-config.d.ts +2 -2
  106. package/dist/src/cli/lib/attention-config.d.ts.map +1 -1
  107. package/dist/src/cli/lib/attention-config.js +1 -2
  108. package/dist/src/cli/lib/attention-config.js.map +1 -1
  109. package/dist/src/cli/lib/config-manager.d.ts +110 -0
  110. package/dist/src/cli/lib/config-manager.d.ts.map +1 -0
  111. package/dist/src/cli/lib/config-manager.js +512 -0
  112. package/dist/src/cli/lib/config-manager.js.map +1 -0
  113. package/dist/src/cli/lib/config-validator.d.ts +1 -1
  114. package/dist/src/cli/lib/config-validator.d.ts.map +1 -1
  115. package/dist/src/cli/lib/health-monitor.d.ts +149 -0
  116. package/dist/src/cli/lib/health-monitor.d.ts.map +1 -0
  117. package/dist/src/cli/lib/health-monitor.js +380 -0
  118. package/dist/src/cli/lib/health-monitor.js.map +1 -0
  119. package/dist/src/cli/lib/history-tracker.d.ts +103 -0
  120. package/dist/src/cli/lib/history-tracker.d.ts.map +1 -0
  121. package/dist/src/cli/lib/history-tracker.js +352 -0
  122. package/dist/src/cli/lib/history-tracker.js.map +1 -0
  123. package/dist/src/cli/lib/report-store.d.ts.map +1 -1
  124. package/dist/src/cli/lib/report-store.js +3 -5
  125. package/dist/src/cli/lib/report-store.js.map +1 -1
  126. package/dist/src/cli/lib/simulation-registry.d.ts +1 -1
  127. package/dist/src/cli/lib/simulation-registry.d.ts.map +1 -1
  128. package/dist/src/cli/lib/simulation-registry.js +0 -1
  129. package/dist/src/cli/lib/simulation-registry.js.map +1 -1
  130. package/dist/src/cli/lib/simulation-runner.d.ts +1 -1
  131. package/dist/src/cli/lib/simulation-runner.d.ts.map +1 -1
  132. package/dist/src/cli/lib/simulation-runner.js +1 -4
  133. package/dist/src/cli/lib/simulation-runner.js.map +1 -1
  134. package/dist/src/compatibility/DeprecationWarnings.d.ts.map +1 -1
  135. package/dist/src/compatibility/V1toV2Adapter.d.ts +2 -2
  136. package/dist/src/compatibility/V1toV2Adapter.d.ts.map +1 -1
  137. package/dist/src/compatibility/V1toV2Adapter.js +1 -14
  138. package/dist/src/compatibility/V1toV2Adapter.js.map +1 -1
  139. package/dist/src/compatibility/VersionDetector.d.ts +1 -1
  140. package/dist/src/compatibility/VersionDetector.d.ts.map +1 -1
  141. package/dist/src/compatibility/VersionDetector.js +3 -3
  142. package/dist/src/compatibility/VersionDetector.js.map +1 -1
  143. package/dist/src/compatibility/index.d.ts +3 -0
  144. package/dist/src/compatibility/index.d.ts.map +1 -1
  145. package/dist/src/compatibility/index.js +11 -0
  146. package/dist/src/compatibility/index.js.map +1 -1
  147. package/dist/src/controllers/AttentionService.d.ts +98 -122
  148. package/dist/src/controllers/AttentionService.d.ts.map +1 -1
  149. package/dist/src/controllers/AttentionService.js +463 -238
  150. package/dist/src/controllers/AttentionService.js.map +1 -1
  151. package/dist/src/controllers/CausalMemoryGraph.d.ts +4 -4
  152. package/dist/src/controllers/CausalMemoryGraph.d.ts.map +1 -1
  153. package/dist/src/controllers/CausalMemoryGraph.js +7 -8
  154. package/dist/src/controllers/CausalMemoryGraph.js.map +1 -1
  155. package/dist/src/controllers/CausalRecall.d.ts +3 -2
  156. package/dist/src/controllers/CausalRecall.d.ts.map +1 -1
  157. package/dist/src/controllers/CausalRecall.js +21 -10
  158. package/dist/src/controllers/CausalRecall.js.map +1 -1
  159. package/dist/src/controllers/ContextSynthesizer.d.ts +1 -1
  160. package/dist/src/controllers/ContextSynthesizer.d.ts.map +1 -1
  161. package/dist/src/controllers/EmbeddingService.d.ts +29 -0
  162. package/dist/src/controllers/EmbeddingService.d.ts.map +1 -1
  163. package/dist/src/controllers/EmbeddingService.js +149 -34
  164. package/dist/src/controllers/EmbeddingService.js.map +1 -1
  165. package/dist/src/controllers/EnhancedEmbeddingService.d.ts.map +1 -1
  166. package/dist/src/controllers/EnhancedEmbeddingService.js +14 -7
  167. package/dist/src/controllers/EnhancedEmbeddingService.js.map +1 -1
  168. package/dist/src/controllers/ExplainableRecall.d.ts +5 -4
  169. package/dist/src/controllers/ExplainableRecall.d.ts.map +1 -1
  170. package/dist/src/controllers/ExplainableRecall.js +12 -20
  171. package/dist/src/controllers/ExplainableRecall.js.map +1 -1
  172. package/dist/src/controllers/HNSWIndex.d.ts +5 -4
  173. package/dist/src/controllers/HNSWIndex.d.ts.map +1 -1
  174. package/dist/src/controllers/HNSWIndex.js +6 -9
  175. package/dist/src/controllers/HNSWIndex.js.map +1 -1
  176. package/dist/src/controllers/LearningSystem.d.ts +10 -105
  177. package/dist/src/controllers/LearningSystem.d.ts.map +1 -1
  178. package/dist/src/controllers/LearningSystem.js +28 -39
  179. package/dist/src/controllers/LearningSystem.js.map +1 -1
  180. package/dist/src/controllers/MMRDiversityRanker.d.ts +1 -1
  181. package/dist/src/controllers/MMRDiversityRanker.d.ts.map +1 -1
  182. package/dist/src/controllers/MemoryController.d.ts +15 -2
  183. package/dist/src/controllers/MemoryController.d.ts.map +1 -1
  184. package/dist/src/controllers/MemoryController.js +33 -3
  185. package/dist/src/controllers/MemoryController.js.map +1 -1
  186. package/dist/src/controllers/MetadataFilter.d.ts +3 -3
  187. package/dist/src/controllers/MetadataFilter.d.ts.map +1 -1
  188. package/dist/src/controllers/MetadataFilter.js +6 -9
  189. package/dist/src/controllers/MetadataFilter.js.map +1 -1
  190. package/dist/src/controllers/MincutService.d.ts +92 -0
  191. package/dist/src/controllers/MincutService.d.ts.map +1 -0
  192. package/dist/src/controllers/MincutService.js +336 -0
  193. package/dist/src/controllers/MincutService.js.map +1 -0
  194. package/dist/src/controllers/NightlyLearner.d.ts +3 -4
  195. package/dist/src/controllers/NightlyLearner.d.ts.map +1 -1
  196. package/dist/src/controllers/NightlyLearner.js +17 -22
  197. package/dist/src/controllers/NightlyLearner.js.map +1 -1
  198. package/dist/src/controllers/QUICClient.d.ts +7 -10
  199. package/dist/src/controllers/QUICClient.d.ts.map +1 -1
  200. package/dist/src/controllers/QUICClient.js +3 -3
  201. package/dist/src/controllers/QUICClient.js.map +1 -1
  202. package/dist/src/controllers/QUICServer.d.ts +4 -4
  203. package/dist/src/controllers/QUICServer.d.ts.map +1 -1
  204. package/dist/src/controllers/QUICServer.js +14 -22
  205. package/dist/src/controllers/QUICServer.js.map +1 -1
  206. package/dist/src/controllers/ReasoningBank.d.ts +2 -9
  207. package/dist/src/controllers/ReasoningBank.d.ts.map +1 -1
  208. package/dist/src/controllers/ReasoningBank.js +39 -35
  209. package/dist/src/controllers/ReasoningBank.js.map +1 -1
  210. package/dist/src/controllers/ReflexionMemory.d.ts +51 -1
  211. package/dist/src/controllers/ReflexionMemory.d.ts.map +1 -1
  212. package/dist/src/controllers/ReflexionMemory.js +307 -33
  213. package/dist/src/controllers/ReflexionMemory.js.map +1 -1
  214. package/dist/src/controllers/SkillLibrary.d.ts +5 -11
  215. package/dist/src/controllers/SkillLibrary.d.ts.map +1 -1
  216. package/dist/src/controllers/SkillLibrary.js +39 -48
  217. package/dist/src/controllers/SkillLibrary.js.map +1 -1
  218. package/dist/src/controllers/SparsificationService.d.ts +151 -0
  219. package/dist/src/controllers/SparsificationService.d.ts.map +1 -0
  220. package/dist/src/controllers/SparsificationService.js +375 -0
  221. package/dist/src/controllers/SparsificationService.js.map +1 -0
  222. package/dist/src/controllers/SyncCoordinator.d.ts +3 -2
  223. package/dist/src/controllers/SyncCoordinator.d.ts.map +1 -1
  224. package/dist/src/controllers/SyncCoordinator.js +2 -2
  225. package/dist/src/controllers/SyncCoordinator.js.map +1 -1
  226. package/dist/src/controllers/WASMVectorSearch.d.ts +7 -6
  227. package/dist/src/controllers/WASMVectorSearch.d.ts.map +1 -1
  228. package/dist/src/controllers/WASMVectorSearch.js +2 -4
  229. package/dist/src/controllers/WASMVectorSearch.js.map +1 -1
  230. package/dist/src/controllers/attention/AttentionCache.d.ts +38 -0
  231. package/dist/src/controllers/attention/AttentionCache.d.ts.map +1 -0
  232. package/dist/src/controllers/attention/AttentionCache.js +80 -0
  233. package/dist/src/controllers/attention/AttentionCache.js.map +1 -0
  234. package/dist/src/controllers/attention/AttentionConfig.d.ts +127 -0
  235. package/dist/src/controllers/attention/AttentionConfig.d.ts.map +1 -0
  236. package/dist/src/controllers/attention/AttentionConfig.js +124 -0
  237. package/dist/src/controllers/attention/AttentionConfig.js.map +1 -0
  238. package/dist/src/controllers/attention/AttentionCore.d.ts +89 -0
  239. package/dist/src/controllers/attention/AttentionCore.d.ts.map +1 -0
  240. package/dist/src/controllers/attention/AttentionCore.js +289 -0
  241. package/dist/src/controllers/attention/AttentionCore.js.map +1 -0
  242. package/dist/src/controllers/attention/AttentionHelpers.d.ts +55 -0
  243. package/dist/src/controllers/attention/AttentionHelpers.d.ts.map +1 -0
  244. package/dist/src/controllers/attention/AttentionHelpers.js +148 -0
  245. package/dist/src/controllers/attention/AttentionHelpers.js.map +1 -0
  246. package/dist/src/controllers/attention/AttentionMetrics.d.ts +55 -0
  247. package/dist/src/controllers/attention/AttentionMetrics.d.ts.map +1 -0
  248. package/dist/src/controllers/attention/AttentionMetrics.js +72 -0
  249. package/dist/src/controllers/attention/AttentionMetrics.js.map +1 -0
  250. package/dist/src/controllers/attention/AttentionWASM.d.ts +98 -0
  251. package/dist/src/controllers/attention/AttentionWASM.d.ts.map +1 -0
  252. package/dist/src/controllers/attention/AttentionWASM.js +147 -0
  253. package/dist/src/controllers/attention/AttentionWASM.js.map +1 -0
  254. package/dist/src/controllers/attention/CrossAttentionController.d.ts +1 -1
  255. package/dist/src/controllers/attention/CrossAttentionController.d.ts.map +1 -1
  256. package/dist/src/controllers/attention/MultiHeadAttentionController.d.ts +1 -1
  257. package/dist/src/controllers/attention/MultiHeadAttentionController.d.ts.map +1 -1
  258. package/dist/src/controllers/attention/MultiHeadAttentionController.js +5 -8
  259. package/dist/src/controllers/attention/MultiHeadAttentionController.js.map +1 -1
  260. package/dist/src/controllers/attention/SelfAttentionController.d.ts +1 -1
  261. package/dist/src/controllers/attention/SelfAttentionController.d.ts.map +1 -1
  262. package/dist/src/controllers/attention/index.d.ts +9 -0
  263. package/dist/src/controllers/attention/index.d.ts.map +1 -1
  264. package/dist/src/controllers/attention/index.js +8 -0
  265. package/dist/src/controllers/attention/index.js.map +1 -1
  266. package/dist/src/controllers/frontier-index.d.ts +14 -0
  267. package/dist/src/controllers/frontier-index.d.ts.map +1 -0
  268. package/dist/src/controllers/frontier-index.js +10 -0
  269. package/dist/src/controllers/frontier-index.js.map +1 -0
  270. package/dist/src/controllers/index.d.ts +7 -1
  271. package/dist/src/controllers/index.d.ts.map +1 -1
  272. package/dist/src/controllers/index.js +5 -1
  273. package/dist/src/controllers/index.js.map +1 -1
  274. package/dist/src/controllers/prerequisites.d.ts +76 -0
  275. package/dist/src/controllers/prerequisites.d.ts.map +1 -0
  276. package/dist/src/controllers/prerequisites.js +235 -0
  277. package/dist/src/controllers/prerequisites.js.map +1 -0
  278. package/dist/src/core/AgentDB.d.ts +11 -36
  279. package/dist/src/core/AgentDB.d.ts.map +1 -1
  280. package/dist/src/core/AgentDB.js +31 -89
  281. package/dist/src/core/AgentDB.js.map +1 -1
  282. package/dist/src/core/QueryCache.d.ts +1 -1
  283. package/dist/src/core/QueryCache.d.ts.map +1 -1
  284. package/dist/src/core/QueryCache.js +2 -6
  285. package/dist/src/core/QueryCache.js.map +1 -1
  286. package/dist/src/db-fallback.d.ts +40 -3
  287. package/dist/src/db-fallback.d.ts.map +1 -1
  288. package/dist/src/db-fallback.js +308 -84
  289. package/dist/src/db-fallback.js.map +1 -1
  290. package/dist/src/db-test.d.ts +13 -0
  291. package/dist/src/db-test.d.ts.map +1 -0
  292. package/dist/src/db-test.js +55 -0
  293. package/dist/src/db-test.js.map +1 -0
  294. package/dist/src/db-unified.d.ts +76 -0
  295. package/dist/src/db-unified.d.ts.map +1 -0
  296. package/dist/src/db-unified.js +281 -0
  297. package/dist/src/db-unified.js.map +1 -0
  298. package/dist/src/embedding/EmbeddingSpaceIdentity.d.ts +58 -0
  299. package/dist/src/embedding/EmbeddingSpaceIdentity.d.ts.map +1 -0
  300. package/dist/src/embedding/EmbeddingSpaceIdentity.js +137 -0
  301. package/dist/src/embedding/EmbeddingSpaceIdentity.js.map +1 -0
  302. package/dist/src/embedding/index.d.ts +3 -0
  303. package/dist/src/embedding/index.d.ts.map +1 -0
  304. package/dist/src/embedding/index.js +2 -0
  305. package/dist/src/embedding/index.js.map +1 -0
  306. package/dist/src/examples/quic-sync-example.d.ts +9 -0
  307. package/dist/src/examples/quic-sync-example.d.ts.map +1 -0
  308. package/dist/src/examples/quic-sync-example.js +169 -0
  309. package/dist/src/examples/quic-sync-example.js.map +1 -0
  310. package/dist/src/examples/wasm-vector-usage.d.ts +12 -0
  311. package/dist/src/examples/wasm-vector-usage.d.ts.map +1 -0
  312. package/dist/src/examples/wasm-vector-usage.js +190 -0
  313. package/dist/src/examples/wasm-vector-usage.js.map +1 -0
  314. package/dist/src/governance/MetaHarnessGateway.d.ts +55 -0
  315. package/dist/src/governance/MetaHarnessGateway.d.ts.map +1 -0
  316. package/dist/src/governance/MetaHarnessGateway.js +65 -0
  317. package/dist/src/governance/MetaHarnessGateway.js.map +1 -0
  318. package/dist/src/governance/RvfExperimentBranch.d.ts +65 -0
  319. package/dist/src/governance/RvfExperimentBranch.d.ts.map +1 -0
  320. package/dist/src/governance/RvfExperimentBranch.js +115 -0
  321. package/dist/src/governance/RvfExperimentBranch.js.map +1 -0
  322. package/dist/src/index.d.ts +7 -25
  323. package/dist/src/index.d.ts.map +1 -1
  324. package/dist/src/index.js +9 -10
  325. package/dist/src/index.js.map +1 -1
  326. package/dist/src/mcp/agentdb-mcp-server.js +162 -159
  327. package/dist/src/mcp/agentdb-mcp-server.js.map +1 -1
  328. package/dist/src/mcp/learning-tools-handlers.d.ts +16 -0
  329. package/dist/src/mcp/learning-tools-handlers.d.ts.map +1 -0
  330. package/dist/src/mcp/learning-tools-handlers.js +105 -0
  331. package/dist/src/mcp/learning-tools-handlers.js.map +1 -0
  332. package/dist/src/model/ModelCacheLoader.d.ts +24 -0
  333. package/dist/src/model/ModelCacheLoader.d.ts.map +1 -0
  334. package/dist/src/model/ModelCacheLoader.js +123 -0
  335. package/dist/src/model/ModelCacheLoader.js.map +1 -0
  336. package/dist/src/observability/integration.d.ts +3 -3
  337. package/dist/src/observability/integration.d.ts.map +1 -1
  338. package/dist/src/observability/integration.js +2 -0
  339. package/dist/src/observability/integration.js.map +1 -1
  340. package/dist/src/observability/telemetry.d.ts +3 -3
  341. package/dist/src/observability/telemetry.d.ts.map +1 -1
  342. package/dist/src/observability/telemetry.js +3 -5
  343. package/dist/src/observability/telemetry.js.map +1 -1
  344. package/dist/src/optimizations/BatchOperations.d.ts +6 -6
  345. package/dist/src/optimizations/BatchOperations.d.ts.map +1 -1
  346. package/dist/src/optimizations/BatchOperations.js +6 -5
  347. package/dist/src/optimizations/BatchOperations.js.map +1 -1
  348. package/dist/src/optimizations/Quantization.d.ts +330 -0
  349. package/dist/src/optimizations/Quantization.d.ts.map +1 -0
  350. package/dist/src/optimizations/Quantization.js +793 -0
  351. package/dist/src/optimizations/Quantization.js.map +1 -0
  352. package/dist/src/optimizations/QueryOptimizer.d.ts +4 -4
  353. package/dist/src/optimizations/QueryOptimizer.d.ts.map +1 -1
  354. package/dist/src/optimizations/QueryOptimizer.js +1 -3
  355. package/dist/src/optimizations/QueryOptimizer.js.map +1 -1
  356. package/dist/src/optimizations/ToolCache.d.ts +4 -4
  357. package/dist/src/optimizations/ToolCache.d.ts.map +1 -1
  358. package/dist/src/optimizations/ToolCache.js.map +1 -1
  359. package/dist/src/quantization/vector-quantization.d.ts.map +1 -1
  360. package/dist/src/quantization/vector-quantization.js +1 -5
  361. package/dist/src/quantization/vector-quantization.js.map +1 -1
  362. package/dist/src/schemas/inline.d.ts +3 -0
  363. package/dist/src/schemas/inline.d.ts.map +1 -0
  364. package/dist/src/schemas/inline.js +10 -0
  365. package/dist/src/schemas/inline.js.map +1 -0
  366. package/dist/src/search/HybridSearch.d.ts +6 -6
  367. package/dist/src/search/HybridSearch.d.ts.map +1 -1
  368. package/dist/src/search/HybridSearch.js.map +1 -1
  369. package/dist/src/security/input-validation.d.ts +34 -12
  370. package/dist/src/security/input-validation.d.ts.map +1 -1
  371. package/dist/src/security/input-validation.js +46 -1
  372. package/dist/src/security/input-validation.js.map +1 -1
  373. package/dist/src/security/limits.d.ts +150 -0
  374. package/dist/src/security/limits.d.ts.map +1 -0
  375. package/dist/src/security/limits.js +288 -0
  376. package/dist/src/security/limits.js.map +1 -0
  377. package/dist/src/security/mcp-policy.d.ts +13 -0
  378. package/dist/src/security/mcp-policy.d.ts.map +1 -0
  379. package/dist/src/security/mcp-policy.js +66 -0
  380. package/dist/src/security/mcp-policy.js.map +1 -0
  381. package/dist/src/security/path-security.d.ts +100 -0
  382. package/dist/src/security/path-security.d.ts.map +1 -0
  383. package/dist/src/security/path-security.js +339 -0
  384. package/dist/src/security/path-security.js.map +1 -0
  385. package/dist/src/security/validation.d.ts +95 -0
  386. package/dist/src/security/validation.d.ts.map +1 -0
  387. package/dist/src/security/validation.js +315 -0
  388. package/dist/src/security/validation.js.map +1 -0
  389. package/dist/src/services/AttentionService.d.ts.map +1 -1
  390. package/dist/src/services/AttentionService.js +2 -4
  391. package/dist/src/services/AttentionService.js.map +1 -1
  392. package/dist/src/services/LLMRouter.d.ts +2 -2
  393. package/dist/src/services/LLMRouter.d.ts.map +1 -1
  394. package/dist/src/services/LLMRouter.js +3 -9
  395. package/dist/src/services/LLMRouter.js.map +1 -1
  396. package/dist/src/services/audit-logger.service.d.ts +168 -0
  397. package/dist/src/services/audit-logger.service.d.ts.map +1 -0
  398. package/dist/src/services/audit-logger.service.js +331 -0
  399. package/dist/src/services/audit-logger.service.js.map +1 -0
  400. package/dist/src/services/enhanced-embeddings.d.ts +271 -0
  401. package/dist/src/services/enhanced-embeddings.d.ts.map +1 -0
  402. package/dist/src/services/enhanced-embeddings.js +1035 -0
  403. package/dist/src/services/enhanced-embeddings.js.map +1 -0
  404. package/dist/src/services/federated-learning.d.ts +172 -0
  405. package/dist/src/services/federated-learning.d.ts.map +1 -0
  406. package/dist/src/services/federated-learning.js +342 -0
  407. package/dist/src/services/federated-learning.js.map +1 -0
  408. package/dist/src/simd/simd-vector-ops.d.ts.map +1 -1
  409. package/dist/src/simd/simd-vector-ops.js +0 -2
  410. package/dist/src/simd/simd-vector-ops.js.map +1 -1
  411. package/dist/src/types/attention.d.ts +249 -0
  412. package/dist/src/types/attention.d.ts.map +1 -0
  413. package/dist/src/types/attention.js +43 -0
  414. package/dist/src/types/attention.js.map +1 -0
  415. package/dist/src/types/database.types.d.ts +11 -11
  416. package/dist/src/types/database.types.d.ts.map +1 -1
  417. package/dist/src/types/database.types.js +2 -4
  418. package/dist/src/types/database.types.js.map +1 -1
  419. package/dist/src/types/graph.d.ts +29 -0
  420. package/dist/src/types/graph.d.ts.map +1 -0
  421. package/dist/src/types/graph.js +8 -0
  422. package/dist/src/types/graph.js.map +1 -0
  423. package/dist/src/types/quic.d.ts +518 -0
  424. package/dist/src/types/quic.d.ts.map +1 -0
  425. package/dist/src/types/quic.js +272 -0
  426. package/dist/src/types/quic.js.map +1 -0
  427. package/dist/src/utils/attention-metrics.d.ts +76 -0
  428. package/dist/src/utils/attention-metrics.d.ts.map +1 -0
  429. package/dist/src/utils/attention-metrics.js +178 -0
  430. package/dist/src/utils/attention-metrics.js.map +1 -0
  431. package/dist/src/wasm-loader.d.ts +0 -1
  432. package/dist/src/wasm-loader.d.ts.map +1 -1
  433. package/dist/src/wasm-loader.js +0 -2
  434. package/dist/src/wasm-loader.js.map +1 -1
  435. package/dist/src/wrappers/agentdb-fast.d.ts +5 -4
  436. package/dist/src/wrappers/agentdb-fast.d.ts.map +1 -1
  437. package/dist/src/wrappers/agentdb-fast.js +6 -13
  438. package/dist/src/wrappers/agentdb-fast.js.map +1 -1
  439. package/dist/src/wrappers/attention-fallbacks.d.ts +0 -8
  440. package/dist/src/wrappers/attention-fallbacks.d.ts.map +1 -1
  441. package/dist/src/wrappers/attention-fallbacks.js +3 -6
  442. package/dist/src/wrappers/attention-fallbacks.js.map +1 -1
  443. package/dist/src/wrappers/attention-native.d.ts +111 -0
  444. package/dist/src/wrappers/attention-native.d.ts.map +1 -0
  445. package/dist/src/wrappers/attention-native.js +273 -0
  446. package/dist/src/wrappers/attention-native.js.map +1 -0
  447. package/dist/src/wrappers/embedding-service.d.ts +4 -4
  448. package/dist/src/wrappers/embedding-service.d.ts.map +1 -1
  449. package/dist/src/wrappers/embedding-service.js +2 -8
  450. package/dist/src/wrappers/embedding-service.js.map +1 -1
  451. package/dist/src/wrappers/gnn-wrapper.d.ts.map +1 -1
  452. package/dist/src/wrappers/gnn-wrapper.js +3 -7
  453. package/dist/src/wrappers/gnn-wrapper.js.map +1 -1
  454. package/package.json +87 -18
  455. package/scripts/postinstall.cjs +13 -144
  456. package/dist/src/cli/tests/agentdb-cli.test.d.ts +0 -8
  457. package/dist/src/cli/tests/agentdb-cli.test.d.ts.map +0 -1
  458. package/dist/src/cli/tests/agentdb-cli.test.js +0 -50
  459. package/dist/src/cli/tests/agentdb-cli.test.js.map +0 -1
  460. package/dist/src/cli/tests/attention-cli.test.d.ts +0 -5
  461. package/dist/src/cli/tests/attention-cli.test.d.ts.map +0 -1
  462. package/dist/src/cli/tests/attention-cli.test.js +0 -257
  463. package/dist/src/cli/tests/attention-cli.test.js.map +0 -1
  464. package/dist/src/coordination/MultiDatabaseCoordinator.d.ts +0 -348
  465. package/dist/src/coordination/MultiDatabaseCoordinator.d.ts.map +0 -1
  466. package/dist/src/coordination/MultiDatabaseCoordinator.js +0 -803
  467. package/dist/src/coordination/MultiDatabaseCoordinator.js.map +0 -1
  468. package/dist/src/coordination/index.d.ts +0 -10
  469. package/dist/src/coordination/index.d.ts.map +0 -1
  470. package/dist/src/coordination/index.js +0 -10
  471. package/dist/src/coordination/index.js.map +0 -1
  472. package/dist/src/tests/attention-service.test.d.ts +0 -7
  473. package/dist/src/tests/attention-service.test.d.ts.map +0 -1
  474. package/dist/src/tests/attention-service.test.js +0 -401
  475. package/dist/src/tests/attention-service.test.js.map +0 -1
  476. package/dist/src/tests/integration/compatibility/backwards-compat.integration.test.d.ts +0 -7
  477. package/dist/src/tests/integration/compatibility/backwards-compat.integration.test.d.ts.map +0 -1
  478. package/dist/src/tests/integration/compatibility/backwards-compat.integration.test.js +0 -283
  479. package/dist/src/tests/integration/compatibility/backwards-compat.integration.test.js.map +0 -1
  480. package/dist/src/tests/query-cache.test.d.ts +0 -7
  481. package/dist/src/tests/query-cache.test.d.ts.map +0 -1
  482. package/dist/src/tests/query-cache.test.js +0 -343
  483. package/dist/src/tests/query-cache.test.js.map +0 -1
  484. package/dist/src/tests/ruvector-integration.test.d.ts +0 -14
  485. package/dist/src/tests/ruvector-integration.test.d.ts.map +0 -1
  486. package/dist/src/tests/ruvector-integration.test.js +0 -1156
  487. package/dist/src/tests/ruvector-integration.test.js.map +0 -1
  488. package/dist/src/tests/unit/auth/crypto.utils.test.d.ts +0 -6
  489. package/dist/src/tests/unit/auth/crypto.utils.test.d.ts.map +0 -1
  490. package/dist/src/tests/unit/auth/crypto.utils.test.js +0 -310
  491. package/dist/src/tests/unit/auth/crypto.utils.test.js.map +0 -1
  492. package/dist/src/tests/unit/compatibility/deprecation-warnings.test.d.ts +0 -5
  493. package/dist/src/tests/unit/compatibility/deprecation-warnings.test.d.ts.map +0 -1
  494. package/dist/src/tests/unit/compatibility/deprecation-warnings.test.js +0 -207
  495. package/dist/src/tests/unit/compatibility/deprecation-warnings.test.js.map +0 -1
  496. package/dist/src/tests/unit/compatibility/migration-utils.test.d.ts +0 -5
  497. package/dist/src/tests/unit/compatibility/migration-utils.test.d.ts.map +0 -1
  498. package/dist/src/tests/unit/compatibility/migration-utils.test.js +0 -264
  499. package/dist/src/tests/unit/compatibility/migration-utils.test.js.map +0 -1
  500. package/dist/src/tests/unit/compatibility/v1-adapter.test.d.ts +0 -7
  501. package/dist/src/tests/unit/compatibility/v1-adapter.test.d.ts.map +0 -1
  502. package/dist/src/tests/unit/compatibility/v1-adapter.test.js +0 -228
  503. package/dist/src/tests/unit/compatibility/v1-adapter.test.js.map +0 -1
  504. package/dist/src/tests/unit/compatibility/version-detector.test.d.ts +0 -10
  505. package/dist/src/tests/unit/compatibility/version-detector.test.d.ts.map +0 -1
  506. package/dist/src/tests/unit/compatibility/version-detector.test.js +0 -162
  507. package/dist/src/tests/unit/compatibility/version-detector.test.js.map +0 -1
  508. package/dist/src/tests/vector-quantization.test.d.ts +0 -5
  509. package/dist/src/tests/vector-quantization.test.d.ts.map +0 -1
  510. package/dist/src/tests/vector-quantization.test.js +0 -338
  511. package/dist/src/tests/vector-quantization.test.js.map +0 -1
  512. package/dist/src/tests/wasm-vector-search.test.d.ts +0 -7
  513. package/dist/src/tests/wasm-vector-search.test.d.ts.map +0 -1
  514. package/dist/src/tests/wasm-vector-search.test.js +0 -193
  515. package/dist/src/tests/wasm-vector-search.test.js.map +0 -1
  516. package/dist/src/utils/crypto.utils.d.ts +0 -122
  517. package/dist/src/utils/crypto.utils.d.ts.map +0 -1
  518. package/dist/src/utils/crypto.utils.js +0 -296
  519. package/dist/src/utils/crypto.utils.js.map +0 -1
@@ -15,122 +15,103 @@
15
15
  * - Performance monitoring hooks
16
16
  * - Type-safe interfaces
17
17
  */
18
+ import { AttentionConfigManager } from './attention/AttentionConfig.js';
19
+ import { AttentionMetricsTracker } from './attention/AttentionMetrics.js';
20
+ import { AttentionCacheManager } from './attention/AttentionCache.js';
21
+ import { AttentionWASMManager } from './attention/AttentionWASM.js';
22
+ import { AttentionCoreCompute } from './attention/AttentionCore.js';
23
+ import { SparsificationService } from './SparsificationService.js';
24
+ import { MincutService } from './MincutService.js';
18
25
  /**
19
- * Detect the current runtime environment
20
- */
21
- function detectRuntime() {
22
- // Check for Node.js
23
- if (typeof process !== 'undefined' && process.versions && process.versions.node) {
24
- return 'nodejs';
25
- }
26
- // Check for browser (with proper type guards)
27
- if (typeof globalThis !== 'undefined') {
28
- const global = globalThis;
29
- if (typeof global.window !== 'undefined' && typeof global.document !== 'undefined') {
30
- return 'browser';
31
- }
32
- }
33
- return 'unknown';
34
- }
35
- /**
36
- * AttentionService - Main controller for attention mechanisms
26
+ * AttentionService - Main orchestration layer for attention mechanisms
27
+ *
28
+ * Delegates to specialized classes:
29
+ * - AttentionConfigManager: Configuration and constants
30
+ * - AttentionMetricsTracker: Performance monitoring
31
+ * - AttentionCacheManager: Buffer pooling and mask caching
32
+ * - AttentionWASMManager: WASM/NAPI module loading
33
+ * - AttentionCoreCompute: Core computation algorithms
37
34
  */
38
35
  export class AttentionService {
39
- config;
40
- runtime;
41
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- optional native NAPI dependency
42
- napiModule = null;
43
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- optional WASM dependency
44
- wasmModule = null;
36
+ configManager;
37
+ metricsTracker;
38
+ cacheManager;
39
+ wasmManager;
40
+ coreCompute;
41
+ sparsificationService;
42
+ mincutService;
45
43
  initialized = false;
46
- // Performance tracking
47
- stats = {
48
- totalOps: 0,
49
- avgExecutionTimeMs: 0,
50
- peakMemoryBytes: 0,
51
- mechanismCounts: {},
52
- runtimeCounts: {}
53
- };
44
+ initPromise = null;
45
+ warmedUp = false;
54
46
  constructor(config) {
55
- this.config = {
56
- dropout: 0.1,
57
- bias: true,
58
- useFlash: true,
59
- useLinear: false,
60
- useHyperbolic: false,
61
- useMoE: false,
62
- numExperts: 8,
63
- topK: 2,
64
- ...config
65
- };
66
- this.runtime = detectRuntime();
47
+ this.configManager = new AttentionConfigManager(config);
48
+ this.metricsTracker = new AttentionMetricsTracker();
49
+ this.cacheManager = new AttentionCacheManager();
50
+ this.wasmManager = new AttentionWASMManager();
51
+ this.coreCompute = new AttentionCoreCompute(this.configManager, this.cacheManager);
52
+ // Initialize sparse attention services if configured
53
+ const cfg = this.configManager.getConfig();
54
+ if (cfg.sparsification?.enabled) {
55
+ this.sparsificationService = new SparsificationService({
56
+ method: cfg.sparsification.method,
57
+ topK: cfg.sparsification.topK
58
+ });
59
+ }
60
+ if (cfg.partitioning?.enabled) {
61
+ this.mincutService = new MincutService({
62
+ algorithm: cfg.partitioning.method,
63
+ maxPartitionSize: cfg.partitioning.maxPartitionSize
64
+ });
65
+ }
67
66
  }
68
67
  /**
69
68
  * Initialize the attention service
70
69
  * Automatically detects and loads the appropriate backend (NAPI or WASM)
70
+ * Thread-safe with promise guard to prevent concurrent initialization
71
71
  */
72
72
  async initialize() {
73
+ // Already initialized
73
74
  if (this.initialized) {
74
75
  return;
75
76
  }
77
+ // Initialization in progress - wait for it
78
+ if (this.initPromise) {
79
+ return this.initPromise;
80
+ }
81
+ // Start new initialization
82
+ this.initPromise = this._doInitialize();
83
+ await this.initPromise;
84
+ }
85
+ /**
86
+ * Internal initialization implementation
87
+ */
88
+ async _doInitialize() {
76
89
  performance.mark('attention-service-init-start');
77
90
  try {
78
- if (this.runtime === 'nodejs') {
79
- // Try to load NAPI module for Node.js
80
- await this.loadNAPIModule();
81
- }
82
- else if (this.runtime === 'browser') {
83
- // Load WASM module for browsers
84
- await this.loadWASMModule();
85
- }
86
- else {
87
- console.warn('⚠️ Unknown runtime environment, using fallback implementation');
88
- }
91
+ await this.wasmManager.initialize();
89
92
  this.initialized = true;
90
93
  performance.mark('attention-service-init-end');
91
94
  performance.measure('attention-service-init', 'attention-service-init-start', 'attention-service-init-end');
92
95
  const measure = performance.getEntriesByName('attention-service-init')[0];
93
- console.log(`✅ AttentionService initialized in ${measure.duration.toFixed(2)}ms (${this.runtime})`);
96
+ console.log(`✅ AttentionService initialized in ${measure.duration.toFixed(2)}ms (${this.wasmManager.getRuntime()})`);
97
+ // Clear performance entries to prevent memory leak
98
+ this.metricsTracker.clearPerformanceEntries('attention-service-init');
99
+ // Warm up JIT with small computation
100
+ if (!this.warmedUp) {
101
+ await this.warmUp();
102
+ this.warmedUp = true;
103
+ }
94
104
  }
95
105
  catch (error) {
96
106
  const errorMessage = error instanceof Error ? error.message : String(error);
97
107
  console.error(`❌ AttentionService initialization failed: ${errorMessage}`);
108
+ // Preserve original error stack trace
109
+ if (error instanceof Error) {
110
+ throw error;
111
+ }
98
112
  throw new Error(`Failed to initialize AttentionService: ${errorMessage}`);
99
113
  }
100
114
  }
101
- /**
102
- * Load NAPI module for Node.js runtime
103
- */
104
- async loadNAPIModule() {
105
- try {
106
- // Try to import @ruvector/attention (NAPI bindings)
107
- this.napiModule = await import('@ruvector/attention');
108
- console.log('✅ Loaded @ruvector/attention NAPI module');
109
- }
110
- catch (error) {
111
- const errorMessage = error instanceof Error ? error.message : String(error);
112
- console.warn(`⚠️ Failed to load @ruvector/attention: ${errorMessage}`);
113
- console.warn(' Falling back to JavaScript implementation');
114
- this.napiModule = null;
115
- }
116
- }
117
- /**
118
- * Load WASM module for browser runtime
119
- */
120
- async loadWASMModule() {
121
- try {
122
- // Try to import ruvector-attention-wasm
123
- this.wasmModule = await import('ruvector-attention-wasm');
124
- await this.wasmModule.default(); // Initialize WASM
125
- console.log('✅ Loaded ruvector-attention-wasm module');
126
- }
127
- catch (error) {
128
- const errorMessage = error instanceof Error ? error.message : String(error);
129
- console.warn(`⚠️ Failed to load ruvector-attention-wasm: ${errorMessage}`);
130
- console.warn(' Falling back to JavaScript implementation');
131
- this.wasmModule = null;
132
- }
133
- }
134
115
  /**
135
116
  * Compute multi-head attention
136
117
  *
@@ -149,23 +130,25 @@ export class AttentionService {
149
130
  let output;
150
131
  let weights;
151
132
  let runtime = 'fallback';
133
+ const napiModule = this.wasmManager.getNAPIModule();
134
+ const wasmModule = this.wasmManager.getWASMModule();
152
135
  // Try NAPI first (fastest for Node.js)
153
- if (this.napiModule && this.napiModule.multiHeadAttention) {
154
- const result = this.napiModule.multiHeadAttention(query, key, value, this.config.numHeads, this.config.headDim, mask);
136
+ if (napiModule && napiModule.multiHeadAttention) {
137
+ const result = napiModule.multiHeadAttention(query, key, value, this.configManager.getNumHeads(), this.configManager.getHeadDim(), mask);
155
138
  output = result.output;
156
139
  weights = result.weights;
157
140
  runtime = 'napi';
158
141
  }
159
142
  // Try WASM (for browsers)
160
- else if (this.wasmModule && this.wasmModule.multiHeadAttention) {
161
- const result = this.wasmModule.multiHeadAttention(query, key, value, this.config.numHeads, this.config.headDim, mask);
143
+ else if (wasmModule && wasmModule.multiHeadAttention) {
144
+ const result = wasmModule.multiHeadAttention(query, key, value, this.configManager.getNumHeads(), this.configManager.getHeadDim(), mask);
162
145
  output = result.output;
163
146
  weights = result.weights;
164
147
  runtime = 'wasm';
165
148
  }
166
149
  // Fallback to JavaScript implementation
167
150
  else {
168
- const result = this.multiHeadAttentionFallback(query, key, value, mask);
151
+ const result = this.coreCompute.multiHeadAttentionFallback(query, key, value, mask);
169
152
  output = result.output;
170
153
  weights = result.weights;
171
154
  runtime = 'fallback';
@@ -175,7 +158,7 @@ export class AttentionService {
175
158
  const measure = performance.getEntriesByName('mha')[0];
176
159
  const executionTimeMs = measure.duration;
177
160
  // Update statistics
178
- this.updateStats('multi-head', runtime, executionTimeMs, output.length * 4);
161
+ this.metricsTracker.updateStats('multi-head', runtime, executionTimeMs, output.length * 4);
179
162
  return {
180
163
  output,
181
164
  weights,
@@ -191,14 +174,6 @@ export class AttentionService {
191
174
  }
192
175
  /**
193
176
  * Compute Flash Attention (memory-efficient)
194
- *
195
- * Flash Attention reduces memory usage from O(n²) to O(n) for sequence length n
196
- *
197
- * @param query - Query vectors
198
- * @param key - Key vectors
199
- * @param value - Value vectors
200
- * @param mask - Optional attention mask
201
- * @returns Attention output and metadata
202
177
  */
203
178
  async flashAttention(query, key, value, mask) {
204
179
  if (!this.initialized) {
@@ -208,19 +183,21 @@ export class AttentionService {
208
183
  try {
209
184
  let output;
210
185
  let runtime = 'fallback';
186
+ const napiModule = this.wasmManager.getNAPIModule();
187
+ const wasmModule = this.wasmManager.getWASMModule();
211
188
  // Try NAPI first
212
- if (this.napiModule && this.napiModule.flashAttention) {
213
- output = this.napiModule.flashAttention(query, key, value, this.config.numHeads, this.config.headDim, mask);
189
+ if (napiModule && napiModule.flashAttention) {
190
+ output = napiModule.flashAttention(query, key, value, this.configManager.getNumHeads(), this.configManager.getHeadDim(), mask);
214
191
  runtime = 'napi';
215
192
  }
216
193
  // Try WASM
217
- else if (this.wasmModule && this.wasmModule.flashAttention) {
218
- output = this.wasmModule.flashAttention(query, key, value, this.config.numHeads, this.config.headDim, mask);
194
+ else if (wasmModule && wasmModule.flashAttention) {
195
+ output = wasmModule.flashAttention(query, key, value, this.configManager.getNumHeads(), this.configManager.getHeadDim(), mask);
219
196
  runtime = 'wasm';
220
197
  }
221
198
  // Fallback (same as multi-head for now)
222
199
  else {
223
- const result = this.multiHeadAttentionFallback(query, key, value, mask);
200
+ const result = this.coreCompute.multiHeadAttentionFallback(query, key, value, mask);
224
201
  output = result.output;
225
202
  runtime = 'fallback';
226
203
  }
@@ -229,7 +206,7 @@ export class AttentionService {
229
206
  const measure = performance.getEntriesByName('flash')[0];
230
207
  const executionTimeMs = measure.duration;
231
208
  // Update statistics
232
- this.updateStats('flash', runtime, executionTimeMs, output.length * 4);
209
+ this.metricsTracker.updateStats('flash', runtime, executionTimeMs, output.length * 4);
233
210
  return {
234
211
  output,
235
212
  executionTimeMs,
@@ -242,15 +219,100 @@ export class AttentionService {
242
219
  throw new Error(`Flash attention failed: ${errorMessage}`);
243
220
  }
244
221
  }
222
+ /**
223
+ * Compute Flash Attention v2 (optimized memory-efficient attention)
224
+ */
225
+ async flashAttentionV2(query, key, value, options) {
226
+ if (!this.initialized) {
227
+ await this.initialize();
228
+ }
229
+ performance.mark('flash-v2-start');
230
+ try {
231
+ let output;
232
+ let runtime = 'fallback';
233
+ let speedup;
234
+ let baselineTimeMs;
235
+ const napiModule = this.wasmManager.getNAPIModule();
236
+ const wasmModule = this.wasmManager.getWASMModule();
237
+ // Try NAPI first (fastest)
238
+ if (napiModule && napiModule.flashAttentionV2) {
239
+ const result = napiModule.flashAttentionV2(query, key, value, this.configManager.getNumHeads(), this.configManager.getHeadDim(), {
240
+ mask: options?.mask,
241
+ causal: options?.causal ?? false,
242
+ windowSize: options?.windowSize,
243
+ dropout: options?.dropout ?? this.configManager.getDropout(),
244
+ });
245
+ output = result.output;
246
+ speedup = result.speedup;
247
+ baselineTimeMs = result.baselineTimeMs;
248
+ runtime = 'napi';
249
+ }
250
+ // Try WASM (ADR-071 Phase 3 target)
251
+ else if (wasmModule && wasmModule.flashAttentionV2) {
252
+ const result = wasmModule.flashAttentionV2(query, key, value, this.configManager.getNumHeads(), this.configManager.getHeadDim(), {
253
+ mask: options?.mask,
254
+ causal: options?.causal ?? false,
255
+ windowSize: options?.windowSize,
256
+ dropout: options?.dropout ?? this.configManager.getDropout(),
257
+ });
258
+ output = result.output;
259
+ speedup = result.speedup;
260
+ baselineTimeMs = result.baselineTimeMs;
261
+ runtime = 'wasm';
262
+ }
263
+ // Fallback to Flash Attention v1 or standard attention
264
+ else {
265
+ console.warn('⚠️ Flash Attention v2 not available, falling back to v1');
266
+ // Benchmark baseline for comparison
267
+ const baselineStart = performance.now();
268
+ const fallbackResult = this.coreCompute.multiHeadAttentionFallback(query, key, value, options?.mask);
269
+ baselineTimeMs = performance.now() - baselineStart;
270
+ // Use v1 Flash Attention if available
271
+ if (wasmModule?.flashAttention || napiModule?.flashAttention) {
272
+ const flashStart = performance.now();
273
+ const flashResult = await this.flashAttention(query, key, value, options?.mask);
274
+ const flashTimeMs = performance.now() - flashStart;
275
+ output = flashResult.output;
276
+ speedup = baselineTimeMs / flashTimeMs;
277
+ runtime = flashResult.runtime;
278
+ }
279
+ else {
280
+ output = fallbackResult.output;
281
+ speedup = 1.0; // No speedup in pure fallback
282
+ runtime = 'fallback';
283
+ }
284
+ }
285
+ performance.mark('flash-v2-end');
286
+ performance.measure('flash-v2', 'flash-v2-start', 'flash-v2-end');
287
+ const measure = performance.getEntriesByName('flash-v2')[0];
288
+ const executionTimeMs = measure.duration;
289
+ // Update statistics
290
+ this.metricsTracker.updateStats('flash-v2', runtime, executionTimeMs, output.length * 4);
291
+ // Log performance metrics for ADR-071 verification
292
+ if (speedup && speedup >= AttentionConfigManager.FLASH_V2_MIN_SPEEDUP) {
293
+ console.log(`✅ Flash Attention v2 achieved ${speedup.toFixed(2)}x speedup ` +
294
+ `(target: ${AttentionConfigManager.FLASH_V2_MIN_SPEEDUP}x-${AttentionConfigManager.FLASH_V2_MAX_SPEEDUP}x)`);
295
+ }
296
+ else if (speedup) {
297
+ console.warn(`⚠️ Flash Attention v2 speedup ${speedup.toFixed(2)}x below target ` +
298
+ `(${AttentionConfigManager.FLASH_V2_MIN_SPEEDUP}x-${AttentionConfigManager.FLASH_V2_MAX_SPEEDUP}x)`);
299
+ }
300
+ return {
301
+ output,
302
+ executionTimeMs,
303
+ mechanism: 'flash',
304
+ runtime,
305
+ speedup,
306
+ baselineTimeMs,
307
+ };
308
+ }
309
+ catch (error) {
310
+ const errorMessage = error instanceof Error ? error.message : String(error);
311
+ throw new Error(`Flash Attention v2 failed: ${errorMessage}`);
312
+ }
313
+ }
245
314
  /**
246
315
  * Compute Linear Attention (O(n) complexity)
247
- *
248
- * Linear attention approximates standard attention with linear complexity
249
- *
250
- * @param query - Query vectors
251
- * @param key - Key vectors
252
- * @param value - Value vectors
253
- * @returns Attention output and metadata
254
316
  */
255
317
  async linearAttention(query, key, value) {
256
318
  if (!this.initialized) {
@@ -260,19 +322,21 @@ export class AttentionService {
260
322
  try {
261
323
  let output;
262
324
  let runtime = 'fallback';
325
+ const napiModule = this.wasmManager.getNAPIModule();
326
+ const wasmModule = this.wasmManager.getWASMModule();
263
327
  // Try NAPI first
264
- if (this.napiModule && this.napiModule.linearAttention) {
265
- output = this.napiModule.linearAttention(query, key, value, this.config.numHeads, this.config.headDim);
328
+ if (napiModule && napiModule.linearAttention) {
329
+ output = napiModule.linearAttention(query, key, value, this.configManager.getNumHeads(), this.configManager.getHeadDim());
266
330
  runtime = 'napi';
267
331
  }
268
332
  // Try WASM
269
- else if (this.wasmModule && this.wasmModule.linearAttention) {
270
- output = this.wasmModule.linearAttention(query, key, value, this.config.numHeads, this.config.headDim);
333
+ else if (wasmModule && wasmModule.linearAttention) {
334
+ output = wasmModule.linearAttention(query, key, value, this.configManager.getNumHeads(), this.configManager.getHeadDim());
271
335
  runtime = 'wasm';
272
336
  }
273
337
  // Fallback
274
338
  else {
275
- output = this.linearAttentionFallback(query, key, value);
339
+ output = this.coreCompute.linearAttentionFallback(query, key, value);
276
340
  runtime = 'fallback';
277
341
  }
278
342
  performance.mark('linear-end');
@@ -280,7 +344,7 @@ export class AttentionService {
280
344
  const measure = performance.getEntriesByName('linear')[0];
281
345
  const executionTimeMs = measure.duration;
282
346
  // Update statistics
283
- this.updateStats('linear', runtime, executionTimeMs, output.length * 4);
347
+ this.metricsTracker.updateStats('linear', runtime, executionTimeMs, output.length * 4);
284
348
  return {
285
349
  output,
286
350
  executionTimeMs,
@@ -295,14 +359,6 @@ export class AttentionService {
295
359
  }
296
360
  /**
297
361
  * Compute Hyperbolic Attention (for hierarchical data)
298
- *
299
- * Hyperbolic attention operates in hyperbolic space, suitable for tree-like structures
300
- *
301
- * @param query - Query vectors
302
- * @param key - Key vectors
303
- * @param value - Value vectors
304
- * @param curvature - Hyperbolic space curvature (default: -1.0)
305
- * @returns Attention output and metadata
306
362
  */
307
363
  async hyperbolicAttention(query, key, value, curvature = -1.0) {
308
364
  if (!this.initialized) {
@@ -312,19 +368,21 @@ export class AttentionService {
312
368
  try {
313
369
  let output;
314
370
  let runtime = 'fallback';
371
+ const napiModule = this.wasmManager.getNAPIModule();
372
+ const wasmModule = this.wasmManager.getWASMModule();
315
373
  // Try NAPI first
316
- if (this.napiModule && this.napiModule.hyperbolicAttention) {
317
- output = this.napiModule.hyperbolicAttention(query, key, value, this.config.numHeads, this.config.headDim, curvature);
374
+ if (napiModule && napiModule.hyperbolicAttention) {
375
+ output = napiModule.hyperbolicAttention(query, key, value, this.configManager.getNumHeads(), this.configManager.getHeadDim(), curvature);
318
376
  runtime = 'napi';
319
377
  }
320
378
  // Try WASM
321
- else if (this.wasmModule && this.wasmModule.hyperbolicAttention) {
322
- output = this.wasmModule.hyperbolicAttention(query, key, value, this.config.numHeads, this.config.headDim, curvature);
379
+ else if (wasmModule && wasmModule.hyperbolicAttention) {
380
+ output = wasmModule.hyperbolicAttention(query, key, value, this.configManager.getNumHeads(), this.configManager.getHeadDim(), curvature);
323
381
  runtime = 'wasm';
324
382
  }
325
383
  // Fallback (use standard attention)
326
384
  else {
327
- const result = this.multiHeadAttentionFallback(query, key, value);
385
+ const result = this.coreCompute.multiHeadAttentionFallback(query, key, value);
328
386
  output = result.output;
329
387
  runtime = 'fallback';
330
388
  }
@@ -333,7 +391,7 @@ export class AttentionService {
333
391
  const measure = performance.getEntriesByName('hyperbolic')[0];
334
392
  const executionTimeMs = measure.duration;
335
393
  // Update statistics
336
- this.updateStats('hyperbolic', runtime, executionTimeMs, output.length * 4);
394
+ this.metricsTracker.updateStats('hyperbolic', runtime, executionTimeMs, output.length * 4);
337
395
  return {
338
396
  output,
339
397
  executionTimeMs,
@@ -347,15 +405,25 @@ export class AttentionService {
347
405
  }
348
406
  }
349
407
  /**
350
- * Compute Mixture-of-Experts (MoE) Attention
408
+ * Compute Fused Attention (optimized single-pass attention)
351
409
  *
352
- * MoE routes inputs to different expert attention mechanisms
410
+ * Fused attention combines softmax and weighted sum in a single pass
411
+ * for 20-25% performance improvement through better cache locality.
353
412
  *
354
- * @param query - Query vectors
355
- * @param key - Key vectors
356
- * @param value - Value vectors
357
- * @param mask - Optional attention mask
358
- * @returns Attention output and metadata
413
+ * @param query - Query vectors [seqLen * embedDim]
414
+ * @param key - Key vectors [seqLen * embedDim]
415
+ * @param value - Value vectors [seqLen * embedDim]
416
+ * @param options - Fused attention options
417
+ * @returns Attention output and performance metrics
418
+ */
419
+ async fusedAttention(query, key, value, options) {
420
+ if (!this.initialized) {
421
+ await this.initialize();
422
+ }
423
+ return this.coreCompute.fusedAttention(query, key, value, options);
424
+ }
425
+ /**
426
+ * Compute Mixture-of-Experts (MoE) Attention
359
427
  */
360
428
  async moeAttention(query, key, value, mask) {
361
429
  if (!this.initialized) {
@@ -365,21 +433,23 @@ export class AttentionService {
365
433
  try {
366
434
  let output;
367
435
  let runtime = 'fallback';
368
- const numExperts = this.config.numExperts || 8;
369
- const topK = this.config.topK || 2;
436
+ const numExperts = this.configManager.getNumExperts();
437
+ const topK = this.configManager.getTopK();
438
+ const napiModule = this.wasmManager.getNAPIModule();
439
+ const wasmModule = this.wasmManager.getWASMModule();
370
440
  // Try NAPI first
371
- if (this.napiModule && this.napiModule.moeAttention) {
372
- output = this.napiModule.moeAttention(query, key, value, this.config.numHeads, this.config.headDim, numExperts, topK, mask);
441
+ if (napiModule && napiModule.moeAttention) {
442
+ output = napiModule.moeAttention(query, key, value, this.configManager.getNumHeads(), this.configManager.getHeadDim(), numExperts, topK, mask);
373
443
  runtime = 'napi';
374
444
  }
375
445
  // Try WASM
376
- else if (this.wasmModule && this.wasmModule.moeAttention) {
377
- output = this.wasmModule.moeAttention(query, key, value, this.config.numHeads, this.config.headDim, numExperts, topK, mask);
446
+ else if (wasmModule && wasmModule.moeAttention) {
447
+ output = wasmModule.moeAttention(query, key, value, this.configManager.getNumHeads(), this.configManager.getHeadDim(), numExperts, topK, mask);
378
448
  runtime = 'wasm';
379
449
  }
380
450
  // Fallback (use standard attention)
381
451
  else {
382
- const result = this.multiHeadAttentionFallback(query, key, value, mask);
452
+ const result = this.coreCompute.multiHeadAttentionFallback(query, key, value, mask);
383
453
  output = result.output;
384
454
  runtime = 'fallback';
385
455
  }
@@ -388,7 +458,7 @@ export class AttentionService {
388
458
  const measure = performance.getEntriesByName('moe')[0];
389
459
  const executionTimeMs = measure.duration;
390
460
  // Update statistics
391
- this.updateStats('moe', runtime, executionTimeMs, output.length * 4);
461
+ this.metricsTracker.updateStats('moe', runtime, executionTimeMs, output.length * 4);
392
462
  return {
393
463
  output,
394
464
  executionTimeMs,
@@ -402,103 +472,258 @@ export class AttentionService {
402
472
  }
403
473
  }
404
474
  /**
405
- * Fallback JavaScript implementation of multi-head attention
406
- * Used when native modules are not available
475
+ * Warm up JIT with small dummy computation
476
+ * Eliminates first-call JIT spikes (50-100ms 5-10ms)
407
477
  */
408
- multiHeadAttentionFallback(query, key, value, mask) {
409
- const { headDim, embedDim } = this.config;
410
- const seqLen = Math.floor(query.length / embedDim);
411
- // Simple scaled dot-product attention
412
- const scale = 1.0 / Math.sqrt(headDim);
413
- const output = new Float32Array(query.length);
414
- for (let i = 0; i < seqLen; i++) {
415
- for (let d = 0; d < embedDim; d++) {
416
- let sum = 0;
417
- let weightSum = 0;
418
- for (let j = 0; j < seqLen; j++) {
419
- // Compute attention score
420
- let score = 0;
421
- for (let k = 0; k < headDim; k++) {
422
- const qIdx = i * embedDim + k;
423
- const kIdx = j * embedDim + k;
424
- score += query[qIdx] * key[kIdx];
425
- }
426
- score *= scale;
427
- // Apply mask if provided
428
- if (mask && mask[i * seqLen + j] === 0) {
429
- score = -Infinity;
430
- }
431
- // Softmax (simplified)
432
- const weight = Math.exp(score);
433
- const vIdx = j * embedDim + d;
434
- sum += weight * value[vIdx];
435
- weightSum += weight;
436
- }
437
- output[i * embedDim + d] = weightSum > 0 ? sum / weightSum : 0;
438
- }
478
+ async warmUp() {
479
+ const dummySize = 16; // Small size for warm-up
480
+ const embedDim = this.configManager.getEmbedDim();
481
+ const dummyQ = new Float32Array(dummySize * embedDim);
482
+ const dummyK = new Float32Array(dummySize * embedDim);
483
+ const dummyV = new Float32Array(dummySize * embedDim);
484
+ // Fill with random values
485
+ for (let i = 0; i < dummyQ.length; i++) {
486
+ dummyQ[i] = Math.random();
487
+ dummyK[i] = Math.random();
488
+ dummyV[i] = Math.random();
439
489
  }
440
- return { output };
490
+ // Run once to warm up JIT (result discarded)
491
+ await this.multiHeadAttention(dummyQ, dummyK, dummyV);
441
492
  }
442
493
  /**
443
- * Fallback JavaScript implementation of linear attention
494
+ * Get performance statistics
444
495
  */
445
- linearAttentionFallback(query, key, value) {
446
- // Simplified linear attention using feature maps
447
- const { embedDim } = this.config;
448
- const seqLen = Math.floor(query.length / embedDim);
449
- const output = new Float32Array(query.length);
450
- // Apply feature map (elu + 1)
451
- const featureMap = (x) => x > 0 ? x + 1 : Math.exp(x);
452
- for (let i = 0; i < seqLen; i++) {
453
- for (let d = 0; d < embedDim; d++) {
454
- let numerator = 0;
455
- let denominator = 0;
456
- for (let j = 0; j < seqLen; j++) {
457
- const qVal = featureMap(query[i * embedDim + d]);
458
- const kVal = featureMap(key[j * embedDim + d]);
459
- const vVal = value[j * embedDim + d];
460
- numerator += qVal * kVal * vVal;
461
- denominator += qVal * kVal;
462
- }
463
- output[i * embedDim + d] = denominator > 0 ? numerator / denominator : 0;
464
- }
465
- }
466
- return output;
496
+ getStats() {
497
+ return this.metricsTracker.getStats();
467
498
  }
468
499
  /**
469
- * Update performance statistics
500
+ * Reset performance statistics
470
501
  */
471
- updateStats(mechanism, runtime, executionTimeMs, memoryBytes) {
472
- this.stats.totalOps++;
473
- // Update average execution time
474
- const prevTotal = this.stats.avgExecutionTimeMs * (this.stats.totalOps - 1);
475
- this.stats.avgExecutionTimeMs = (prevTotal + executionTimeMs) / this.stats.totalOps;
476
- // Update peak memory
477
- if (memoryBytes > this.stats.peakMemoryBytes) {
478
- this.stats.peakMemoryBytes = memoryBytes;
479
- }
480
- // Update mechanism counts
481
- this.stats.mechanismCounts[mechanism] = (this.stats.mechanismCounts[mechanism] || 0) + 1;
482
- // Update runtime counts
483
- this.stats.runtimeCounts[runtime] = (this.stats.runtimeCounts[runtime] || 0) + 1;
502
+ resetStats() {
503
+ this.metricsTracker.resetStats();
484
504
  }
485
505
  /**
486
- * Get performance statistics
506
+ * Dispose of resources and clean up
507
+ * Call this when AttentionService is no longer needed
487
508
  */
488
- getStats() {
489
- return { ...this.stats };
509
+ async dispose() {
510
+ // Clean up WASM modules
511
+ await this.wasmManager.dispose();
512
+ // Clear all performance entries
513
+ this.metricsTracker.clearAllPerformanceEntries();
514
+ // Clear caches
515
+ this.cacheManager.clear();
516
+ // Reset state
517
+ this.initialized = false;
518
+ this.warmedUp = false;
519
+ this.initPromise = null;
520
+ // Reset stats
521
+ this.metricsTracker.resetStats();
522
+ console.log('✅ AttentionService disposed');
490
523
  }
491
524
  /**
492
- * Reset performance statistics
525
+ * Compute Sparse Attention
526
+ *
527
+ * Uses graph sparsification to reduce the number of attention edges,
528
+ * achieving 10-100x speedup for large graphs (N > 10K nodes).
529
+ *
530
+ * @param query - Query vector for attention scoring
531
+ * @param graphEdges - Graph adjacency list (node -> neighbors)
532
+ * @param options - Sparse attention options
533
+ * @returns Attention result with sparsity metadata
493
534
  */
494
- resetStats() {
495
- this.stats = {
496
- totalOps: 0,
497
- avgExecutionTimeMs: 0,
498
- peakMemoryBytes: 0,
499
- mechanismCounts: {},
500
- runtimeCounts: {}
501
- };
535
+ async sparseAttention(query, graphEdges, options) {
536
+ if (!this.initialized) {
537
+ await this.initialize();
538
+ }
539
+ performance.mark('sparse-attention-start');
540
+ try {
541
+ const numNodes = graphEdges.length;
542
+ // For small graphs (N < 1000), fallback to dense attention
543
+ if (numNodes < 1000) {
544
+ console.warn(`⚠️ Graph size ${numNodes} < 1000, using dense attention`);
545
+ const dummyKey = new Float32Array(query.length);
546
+ const dummyValue = new Float32Array(query.length);
547
+ return this.multiHeadAttention(query, dummyKey, dummyValue);
548
+ }
549
+ // Initialize or reconfigure sparsification service
550
+ const cfg = this.configManager.getConfig();
551
+ const sparsificationMethod = options?.method || cfg.sparsification?.method || 'ppr';
552
+ const sparsificationTopK = options?.topK || cfg.sparsification?.topK || Math.floor(numNodes * 0.1);
553
+ if (!this.sparsificationService) {
554
+ this.sparsificationService = new SparsificationService({
555
+ method: sparsificationMethod,
556
+ topK: sparsificationTopK
557
+ });
558
+ await this.sparsificationService.initialize();
559
+ }
560
+ else {
561
+ // Update config if method or topK changed
562
+ this.sparsificationService.updateConfig({
563
+ method: sparsificationMethod,
564
+ topK: sparsificationTopK
565
+ });
566
+ }
567
+ // Determine source node (first non-zero element in query)
568
+ let sourceNode = 0;
569
+ for (let i = 0; i < query.length && i < numNodes; i++) {
570
+ if (query[i] !== 0) {
571
+ sourceNode = i;
572
+ break;
573
+ }
574
+ }
575
+ // Sparsify the graph
576
+ const sparsificationResult = await this.sparsificationService.sparsify(sourceNode, graphEdges);
577
+ // Build sparse graph with only top-K nodes
578
+ const sparseEdges = [];
579
+ const nodeMap = new Map(); // original -> sparse index
580
+ sparsificationResult.topKIndices.forEach((originalNode, sparseIdx) => {
581
+ nodeMap.set(originalNode, sparseIdx);
582
+ });
583
+ for (const originalNode of sparsificationResult.topKIndices) {
584
+ const neighbors = graphEdges[originalNode] || [];
585
+ const sparseNeighbors = [];
586
+ for (const neighbor of neighbors) {
587
+ const sparseNeighborIdx = nodeMap.get(neighbor);
588
+ if (sparseNeighborIdx !== undefined) {
589
+ sparseNeighbors.push(sparseNeighborIdx);
590
+ }
591
+ }
592
+ sparseEdges.push(sparseNeighbors);
593
+ }
594
+ // Build sparse query/key/value matrices
595
+ const topK = sparsificationResult.topKIndices.length;
596
+ const embedDim = this.configManager.getEmbedDim();
597
+ const sparseQuery = new Float32Array(topK * embedDim);
598
+ const sparseKey = new Float32Array(topK * embedDim);
599
+ const sparseValue = new Float32Array(topK * embedDim);
600
+ for (let i = 0; i < topK; i++) {
601
+ const originalNode = sparsificationResult.topKIndices[i];
602
+ const score = sparsificationResult.scores[originalNode];
603
+ // Use score as query embedding (weighted by importance)
604
+ for (let d = 0; d < embedDim; d++) {
605
+ sparseQuery[i * embedDim + d] = score;
606
+ sparseKey[i * embedDim + d] = score;
607
+ sparseValue[i * embedDim + d] = score;
608
+ }
609
+ }
610
+ // Run attention on sparse graph
611
+ const attentionResult = await this.multiHeadAttention(sparseQuery, sparseKey, sparseValue);
612
+ performance.mark('sparse-attention-end');
613
+ performance.measure('sparse-attention', 'sparse-attention-start', 'sparse-attention-end');
614
+ const measure = performance.getEntriesByName('sparse-attention')[0];
615
+ const executionTimeMs = measure.duration;
616
+ // Update statistics
617
+ this.metricsTracker.updateStats('sparse', attentionResult.runtime, executionTimeMs, attentionResult.output.length * 4);
618
+ return {
619
+ output: attentionResult.output,
620
+ weights: attentionResult.weights,
621
+ executionTimeMs,
622
+ mechanism: 'sparse',
623
+ runtime: attentionResult.runtime,
624
+ sparsityMetadata: {
625
+ method: sparsificationResult.method,
626
+ topKNodes: topK,
627
+ sparsityRatio: sparsificationResult.sparsityRatio
628
+ }
629
+ };
630
+ }
631
+ catch (error) {
632
+ const errorMessage = error instanceof Error ? error.message : String(error);
633
+ throw new Error(`Sparse attention failed: ${errorMessage}`);
634
+ }
635
+ }
636
+ /**
637
+ * Compute Partitioned Attention
638
+ *
639
+ * Uses graph mincut algorithms to partition the graph, then applies
640
+ * attention within each partition independently. Achieves 50-80% memory
641
+ * reduction through intelligent clustering.
642
+ *
643
+ * @param query - Query vector for attention scoring
644
+ * @param graphEdges - Graph adjacency list
645
+ * @param options - Partitioned attention options
646
+ * @returns Attention result with partitioning metadata
647
+ */
648
+ async partitionedAttention(query, graphEdges, options) {
649
+ if (!this.initialized) {
650
+ await this.initialize();
651
+ }
652
+ performance.mark('partitioned-attention-start');
653
+ try {
654
+ const numNodes = graphEdges.length;
655
+ // For small graphs, fallback to dense attention
656
+ if (numNodes < 1000) {
657
+ console.warn(`⚠️ Graph size ${numNodes} < 1000, using dense attention`);
658
+ const dummyKey = new Float32Array(query.length);
659
+ const dummyValue = new Float32Array(query.length);
660
+ return this.multiHeadAttention(query, dummyKey, dummyValue);
661
+ }
662
+ // Initialize mincut service if not already
663
+ if (!this.mincutService) {
664
+ const cfg = this.configManager.getConfig();
665
+ this.mincutService = new MincutService({
666
+ algorithm: options?.method || cfg.partitioning?.method || 'stoer-wagner',
667
+ maxPartitionSize: options?.maxPartitionSize || cfg.partitioning?.maxPartitionSize || 1000
668
+ });
669
+ await this.mincutService.initialize();
670
+ }
671
+ // Partition the graph
672
+ const partitionResult = await this.mincutService.partition(graphEdges);
673
+ // Get partition statistics
674
+ const stats = this.mincutService.getPartitionStats(partitionResult, graphEdges);
675
+ // Compute attention within each partition
676
+ const embedDim = this.configManager.getEmbedDim();
677
+ const partitionOutputs = [];
678
+ for (const partition of partitionResult.partitions) {
679
+ const partitionSize = partition.length;
680
+ const partitionQuery = new Float32Array(partitionSize * embedDim);
681
+ const partitionKey = new Float32Array(partitionSize * embedDim);
682
+ const partitionValue = new Float32Array(partitionSize * embedDim);
683
+ // Build partition matrices (simple: use node indices as embeddings)
684
+ for (let i = 0; i < partitionSize; i++) {
685
+ const nodeId = partition[i];
686
+ const value = nodeId < query.length ? query[nodeId] : 0;
687
+ for (let d = 0; d < embedDim; d++) {
688
+ partitionQuery[i * embedDim + d] = value;
689
+ partitionKey[i * embedDim + d] = value;
690
+ partitionValue[i * embedDim + d] = value;
691
+ }
692
+ }
693
+ // Run attention on this partition
694
+ const partitionResult = await this.multiHeadAttention(partitionQuery, partitionKey, partitionValue);
695
+ partitionOutputs.push(partitionResult.output);
696
+ }
697
+ // Merge partition outputs (simple concatenation)
698
+ const totalOutputSize = partitionOutputs.reduce((sum, output) => sum + output.length, 0);
699
+ const mergedOutput = new Float32Array(totalOutputSize);
700
+ let offset = 0;
701
+ for (const output of partitionOutputs) {
702
+ mergedOutput.set(output, offset);
703
+ offset += output.length;
704
+ }
705
+ performance.mark('partitioned-attention-end');
706
+ performance.measure('partitioned-attention', 'partitioned-attention-start', 'partitioned-attention-end');
707
+ const measure = performance.getEntriesByName('partitioned-attention')[0];
708
+ const executionTimeMs = measure.duration;
709
+ // Update statistics
710
+ this.metricsTracker.updateStats('partitioned', 'fallback', executionTimeMs, mergedOutput.length * 4);
711
+ return {
712
+ output: mergedOutput,
713
+ executionTimeMs,
714
+ mechanism: 'partitioned',
715
+ runtime: 'fallback',
716
+ partitioningMetadata: {
717
+ numPartitions: stats.numPartitions,
718
+ cutSize: partitionResult.cutSize,
719
+ avgPartitionSize: stats.avgPartitionSize
720
+ }
721
+ };
722
+ }
723
+ catch (error) {
724
+ const errorMessage = error instanceof Error ? error.message : String(error);
725
+ throw new Error(`Partitioned attention failed: ${errorMessage}`);
726
+ }
502
727
  }
503
728
  /**
504
729
  * Get service information
@@ -506,10 +731,10 @@ export class AttentionService {
506
731
  getInfo() {
507
732
  return {
508
733
  initialized: this.initialized,
509
- runtime: this.runtime,
510
- hasNAPI: this.napiModule !== null,
511
- hasWASM: this.wasmModule !== null,
512
- config: { ...this.config }
734
+ runtime: this.wasmManager.getRuntime(),
735
+ hasNAPI: this.wasmManager.hasNAPI(),
736
+ hasWASM: this.wasmManager.hasWASM(),
737
+ config: this.configManager.getConfig()
513
738
  };
514
739
  }
515
740
  }