agentic-qe 3.8.13 → 3.9.0

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 (359) hide show
  1. package/.claude/skills/skills-manifest.json +1 -1
  2. package/CHANGELOG.md +48 -0
  3. package/dist/adapters/a2ui/integration/agui-sync.js +2 -1
  4. package/dist/audit/witness-chain.js +15 -3
  5. package/dist/boot/fast-paths.d.ts +24 -0
  6. package/dist/boot/fast-paths.js +43 -0
  7. package/dist/boot/parallel-prefetch.d.ts +26 -0
  8. package/dist/boot/parallel-prefetch.js +36 -0
  9. package/dist/cli/bundle.js +12 -9431
  10. package/dist/cli/chunks/adapter-WBR5NXS3.js +2 -0
  11. package/dist/cli/chunks/agent-booster-wasm-PQYB7VRU.js +2 -0
  12. package/dist/cli/chunks/agent-handler-QDAB5NQS.js +33 -0
  13. package/dist/cli/chunks/aqe-learning-engine-TK4JQCGT.js +2 -0
  14. package/dist/cli/chunks/audit-S7JUYYVP.js +3 -0
  15. package/dist/cli/chunks/base-2WXOSMBQ.js +2 -0
  16. package/dist/cli/chunks/better-sqlite3-7KY2RDXO.js +2 -0
  17. package/dist/cli/chunks/brain-handler-PPEGDCN4.js +68 -0
  18. package/dist/cli/chunks/branch-enumerator-XK4V5W7L.js +7 -0
  19. package/dist/cli/chunks/browser-PALA5PL3.js +4 -0
  20. package/dist/cli/chunks/browser-workflow-42F7GK5T.js +2 -0
  21. package/dist/cli/chunks/chunk-24FKIJNC.js +15 -0
  22. package/dist/cli/chunks/chunk-263XS447.js +2 -0
  23. package/dist/cli/chunks/chunk-2BZFNEN2.js +4 -0
  24. package/dist/cli/chunks/chunk-2E5NQNSU.js +180 -0
  25. package/dist/cli/chunks/chunk-2I7J3O6V.js +2 -0
  26. package/dist/cli/chunks/chunk-3ADGXLTM.js +14 -0
  27. package/dist/cli/chunks/chunk-3IHG3WOY.js +12 -0
  28. package/dist/cli/chunks/chunk-3IUNFTIF.js +2 -0
  29. package/dist/cli/chunks/chunk-3JPRUND5.js +2 -0
  30. package/dist/cli/chunks/chunk-3NZLZHJI.js +2 -0
  31. package/dist/cli/chunks/chunk-3THRQEZ2.js +95 -0
  32. package/dist/cli/chunks/chunk-3ZOONQG6.js +2 -0
  33. package/dist/cli/chunks/chunk-4B6NCELM.js +2 -0
  34. package/dist/cli/chunks/chunk-4I2IOUS4.js +2 -0
  35. package/dist/cli/chunks/chunk-4VBTXZRM.js +2 -0
  36. package/dist/cli/chunks/chunk-4VUPRTVX.js +3 -0
  37. package/dist/cli/chunks/chunk-4YOMLWEK.js +70 -0
  38. package/dist/cli/chunks/chunk-4YS3IJ45.js +2 -0
  39. package/dist/cli/chunks/chunk-5SKGFSKD.js +2 -0
  40. package/dist/cli/chunks/chunk-5T2ZQWKF.js +27 -0
  41. package/dist/cli/chunks/chunk-62ADTHV7.js +2 -0
  42. package/dist/cli/chunks/chunk-6EOS7KX2.js +2 -0
  43. package/dist/cli/chunks/chunk-6SVX4DJC.js +6 -0
  44. package/dist/cli/chunks/chunk-72WOAVK6.js +2 -0
  45. package/dist/cli/chunks/chunk-7R6YMLVS.js +3 -0
  46. package/dist/cli/chunks/chunk-7VDBAVTY.js +2 -0
  47. package/dist/cli/chunks/chunk-AFLLQ5PP.js +15 -0
  48. package/dist/cli/chunks/chunk-AKE543X2.js +2 -0
  49. package/dist/cli/chunks/chunk-B36CDR4U.js +2 -0
  50. package/dist/cli/chunks/chunk-B6LLWYQ6.js +2 -0
  51. package/dist/cli/chunks/chunk-BDIEMZ22.js +91 -0
  52. package/dist/cli/chunks/chunk-BGXNSCXX.js +4 -0
  53. package/dist/cli/chunks/chunk-BLBRY5UD.js +2 -0
  54. package/dist/cli/chunks/chunk-BPWXXEH2.js +3029 -0
  55. package/dist/cli/chunks/chunk-BR26T7ZS.js +180 -0
  56. package/dist/cli/chunks/chunk-BTREG4IW.js +2 -0
  57. package/dist/cli/chunks/chunk-BULKFVYX.js +2 -0
  58. package/dist/cli/chunks/chunk-BXAXGEFC.js +24 -0
  59. package/dist/cli/chunks/chunk-CL6POIX4.js +2 -0
  60. package/dist/cli/chunks/chunk-CS2KS7LP.js +2 -0
  61. package/dist/cli/chunks/chunk-CWFB6BSA.js +316 -0
  62. package/dist/cli/chunks/chunk-DRT3WKQW.js +2 -0
  63. package/dist/cli/chunks/chunk-EHDQJQ6Y.js +27 -0
  64. package/dist/cli/chunks/chunk-ESVQ6MEB.js +2 -0
  65. package/dist/cli/chunks/chunk-FEKY7T6Q.js +2 -0
  66. package/dist/cli/chunks/chunk-FGA7VIFR.js +7 -0
  67. package/dist/cli/chunks/chunk-FIA6X7UL.js +2 -0
  68. package/dist/cli/chunks/chunk-GAOJV3OX.js +2 -0
  69. package/dist/cli/chunks/chunk-GKNNSCLC.js +5 -0
  70. package/dist/cli/chunks/chunk-GPQ57KA4.js +2 -0
  71. package/dist/cli/chunks/chunk-GRUUQAR6.js +2 -0
  72. package/dist/cli/chunks/chunk-HRO6OZQD.js +2 -0
  73. package/dist/cli/chunks/chunk-HY6PMO5W.js +66 -0
  74. package/dist/cli/chunks/chunk-IAV2JMIX.js +167 -0
  75. package/dist/cli/chunks/chunk-IFNIIK34.js +21 -0
  76. package/dist/cli/chunks/chunk-IGJPMN4I.js +3 -0
  77. package/dist/cli/chunks/chunk-J3KWWR6Z.js +1 -0
  78. package/dist/cli/chunks/chunk-JBANAPWG.js +2 -0
  79. package/dist/cli/chunks/chunk-JJO7Y4H3.js +604 -0
  80. package/dist/cli/chunks/chunk-JRYGQO2W.js +2 -0
  81. package/dist/cli/chunks/chunk-JXM26HEE.js +2 -0
  82. package/dist/cli/chunks/chunk-JZSDOIXA.js +2 -0
  83. package/dist/cli/chunks/chunk-KP5NUODU.js +3 -0
  84. package/dist/cli/chunks/chunk-LHJQD2VU.js +750 -0
  85. package/dist/cli/chunks/chunk-LNQIY6BP.js +2 -0
  86. package/dist/cli/chunks/chunk-MDUHYUHF.js +2 -0
  87. package/dist/cli/chunks/chunk-MV6CMOJQ.js +65 -0
  88. package/dist/cli/chunks/chunk-MZOFWJTM.js +2 -0
  89. package/dist/cli/chunks/chunk-N2NS2PHA.js +45 -0
  90. package/dist/cli/chunks/chunk-N4TL73TH.js +314 -0
  91. package/dist/cli/chunks/chunk-N5UXCLFI.js +2 -0
  92. package/dist/cli/chunks/chunk-NZ2VCPN4.js +2 -0
  93. package/dist/cli/chunks/chunk-OF4D7MYI.js +2 -0
  94. package/dist/cli/chunks/chunk-OI5NGQO2.js +2 -0
  95. package/dist/cli/chunks/chunk-OLHKGP35.js +2 -0
  96. package/dist/cli/chunks/chunk-QOVHWZEP.js +1 -0
  97. package/dist/cli/chunks/chunk-RFSN6IDA.js +79 -0
  98. package/dist/cli/chunks/chunk-RTGGL7D7.js +4 -0
  99. package/dist/cli/chunks/chunk-RU5WAHB7.js +3 -0
  100. package/dist/cli/chunks/chunk-SUSEVMZT.js +2 -0
  101. package/dist/cli/chunks/chunk-TLHP5EII.js +2 -0
  102. package/dist/cli/chunks/chunk-TWUWL5EJ.js +2 -0
  103. package/dist/cli/chunks/chunk-U5RN7YQW.js +2 -0
  104. package/dist/cli/chunks/chunk-UFUVUO3J.js +2 -0
  105. package/dist/cli/chunks/chunk-UQHYFOBX.js +16 -0
  106. package/dist/cli/chunks/chunk-VOS4NQSF.js +2 -0
  107. package/dist/cli/chunks/chunk-VSVXUTJN.js +256 -0
  108. package/dist/cli/chunks/chunk-WBQSXPBI.js +2 -0
  109. package/dist/cli/chunks/chunk-WGMPEW2T.js +2 -0
  110. package/dist/cli/chunks/chunk-WIEC7VKK.js +2 -0
  111. package/dist/cli/chunks/chunk-WJ3DLOXF.js +14 -0
  112. package/dist/cli/chunks/chunk-X3KI6JOY.js +9 -0
  113. package/dist/cli/chunks/chunk-X5IJGWYG.js +2 -0
  114. package/dist/cli/chunks/chunk-XIBDETCS.js +146 -0
  115. package/dist/cli/chunks/chunk-XLRQYLWW.js +2 -0
  116. package/dist/cli/chunks/chunk-XO6PVK2P.js +3 -0
  117. package/dist/cli/chunks/chunk-XRE2HCWG.js +3 -0
  118. package/dist/cli/chunks/chunk-XT2V2322.js +2 -0
  119. package/dist/cli/chunks/chunk-Y7BHKZFJ.js +18 -0
  120. package/dist/cli/chunks/chunk-YAGODYIG.js +59 -0
  121. package/dist/cli/chunks/chunk-YANUP2RO.js +2 -0
  122. package/dist/cli/chunks/chunk-YPFOCNOE.js +30 -0
  123. package/dist/cli/chunks/chunk-YR6ZZGH7.js +81 -0
  124. package/dist/cli/chunks/chunk-YVA65UZL.js +2 -0
  125. package/dist/cli/chunks/chunk-YW2THB5Q.js +2 -0
  126. package/dist/cli/chunks/chunk-ZAPS3UGQ.js +20 -0
  127. package/dist/cli/chunks/chunk-ZDATDCYN.js +2 -0
  128. package/dist/cli/chunks/ci-J374KDLI.js +81 -0
  129. package/dist/cli/chunks/ci-output-7JN7F6CI.js +2 -0
  130. package/dist/cli/chunks/claude-flow-setup-245JLJCN.js +2 -0
  131. package/dist/cli/chunks/client-MCSNSH2C.js +2 -0
  132. package/dist/cli/chunks/cline-installer-LBA2M5N3.js +4 -0
  133. package/dist/cli/chunks/code-U4N4WONM.js +38 -0
  134. package/dist/cli/chunks/code-index-extractor-A57Z6BO4.js +3 -0
  135. package/dist/cli/chunks/codex-installer-UXMK2N4T.js +8 -0
  136. package/dist/cli/chunks/completions-W66BSCOE.js +1364 -0
  137. package/dist/cli/chunks/complexity-analyzer-AB4OZARV.js +2 -0
  138. package/dist/cli/chunks/continuedev-installer-LRFZ2SJM.js +14 -0
  139. package/dist/cli/chunks/copilot-installer-CQ3JYBIB.js +3 -0
  140. package/dist/cli/chunks/cost-tracker-4F723RB6.js +2 -0
  141. package/dist/cli/chunks/coverage-4PUEQXAY.js +27 -0
  142. package/dist/cli/chunks/cross-domain-router-OWR5IJ5G.js +2 -0
  143. package/dist/cli/chunks/cursor-installer-JZEDEDHA.js +3 -0
  144. package/dist/cli/chunks/daemon-B7TWGHXQ.js +19 -0
  145. package/dist/cli/chunks/dag-attention-scheduler-JWO6XI6A.js +2 -0
  146. package/dist/cli/chunks/detect-L6ZZHUSX.js +2 -0
  147. package/dist/cli/chunks/domain-handler-FT5FLZWL.js +25 -0
  148. package/dist/cli/chunks/domain-transfer-5Y4FGJAJ.js +2 -0
  149. package/dist/cli/chunks/dream-4TDBIYED.js +2 -0
  150. package/dist/cli/chunks/esm-node-2PKHKOTS.js +2 -0
  151. package/dist/cli/chunks/eval-GHMPFGWV.js +15 -0
  152. package/dist/cli/chunks/fast-paths-B3R647KN.js +2 -0
  153. package/dist/cli/chunks/feature-flags-DWS7ARSX.js +2 -0
  154. package/dist/cli/chunks/feature-flags-IVQ3AL4Q.js +2 -0
  155. package/dist/cli/chunks/file-discovery-QFPA6GMV.js +2 -0
  156. package/dist/cli/chunks/fleet-EKOKMOMW.js +43 -0
  157. package/dist/cli/chunks/gnn-wrapper-OYC55N5E.js +2 -0
  158. package/dist/cli/chunks/heartbeat-handler-MBBS4IBU.js +48 -0
  159. package/dist/cli/chunks/heartbeat-scheduler-XDGMOT7X.js +2 -0
  160. package/dist/cli/chunks/hnsw-index-YO7CT23I.js +2 -0
  161. package/dist/cli/chunks/hnswlib-node-56YWVXFE.js +2 -0
  162. package/dist/cli/chunks/hooks-L5VLZGEK.js +101 -0
  163. package/dist/cli/chunks/hypergraph-engine-A4Y2ZRAG.js +2 -0
  164. package/dist/cli/chunks/hypergraph-handler-3HDGB5SZ.js +35 -0
  165. package/dist/cli/chunks/impact-analyzer-UEIGXSZ4.js +2 -0
  166. package/dist/cli/chunks/init-handler-JDET6WUN.js +68 -0
  167. package/dist/cli/chunks/init-wizard-JWZUGIPJ.js +2 -0
  168. package/dist/cli/chunks/kernel-YNDTVKIW.js +2 -0
  169. package/dist/cli/chunks/kilocode-installer-GZZG5AFW.js +4 -0
  170. package/dist/cli/chunks/kiro-installer-IWNY5TKH.js +74 -0
  171. package/dist/cli/chunks/knowledge-graph-NGJKFTSN.js +2 -0
  172. package/dist/cli/chunks/learning-722ZNSZ6.js +107 -0
  173. package/dist/cli/chunks/llm-router-DNAV746L.js +30 -0
  174. package/dist/cli/chunks/load-Y3GCUFM4.js +2 -0
  175. package/dist/cli/chunks/load-test-GZUBXFF3.js +2 -0
  176. package/dist/cli/chunks/mcp-LKPIBZ3W.js +2 -0
  177. package/dist/cli/chunks/memory-L57MLFOP.js +32 -0
  178. package/dist/cli/chunks/memory-backend-3NQIZUXE.js +2 -0
  179. package/dist/cli/chunks/memory-handlers-MDZQ7HVW.js +2 -0
  180. package/dist/cli/chunks/opencode-installer-4HUB36H5.js +3 -0
  181. package/dist/cli/chunks/orchestrator-QHSBB2UC.js +371 -0
  182. package/dist/cli/chunks/pipeline-D3QER35Z.js +19 -0
  183. package/dist/cli/chunks/platform-T4E7Q3RD.js +2 -0
  184. package/dist/cli/chunks/plugin-JHW2YPRC.js +27 -0
  185. package/dist/cli/chunks/prime-radiant-advanced-wasm-G7CFNNQV.js +2 -0
  186. package/dist/cli/chunks/protocol-executor-SPUVRDWT.js +2 -0
  187. package/dist/cli/chunks/protocol-handler-2BQQ4HDM.js +20 -0
  188. package/dist/cli/chunks/prove-UQ6JFT73.js +3 -0
  189. package/dist/cli/chunks/qe-reasoning-bank-3HBK2FVD.js +2 -0
  190. package/dist/cli/chunks/quality-JRZYMC77.js +7 -0
  191. package/dist/cli/chunks/queen-coordinator-RW3NKO5A.js +2 -0
  192. package/dist/cli/chunks/real-embeddings-GK63VF35.js +2 -0
  193. package/dist/cli/chunks/roocode-installer-F4E2LAYR.js +4 -0
  194. package/dist/cli/chunks/router-RJGHWDQ3.js +2 -0
  195. package/dist/cli/chunks/routing-feedback-ZXBXFKX6.js +2 -0
  196. package/dist/cli/chunks/routing-handler-VNKFUUGB.js +20 -0
  197. package/dist/cli/chunks/ruvector-commands-2TLNHC3A.js +8 -0
  198. package/dist/cli/chunks/rvf-dual-writer-MQW2SJLT.js +2 -0
  199. package/dist/cli/chunks/rvf-native-adapter-LKFKTMUN.js +2 -0
  200. package/dist/cli/chunks/safe-db-G22E5ROA.js +2 -0
  201. package/dist/cli/chunks/schedule-Y7VVCPYV.js +2 -0
  202. package/dist/cli/chunks/scheduler-AUQIFQB7.js +2 -0
  203. package/dist/cli/chunks/security-EBEG2OPU.js +14 -0
  204. package/dist/cli/chunks/shared-rvf-dual-writer-BVSCQAFS.js +2 -0
  205. package/dist/cli/chunks/sqlite-persistence-JAVHUGGL.js +2 -0
  206. package/dist/cli/chunks/status-handler-VZ32M4G4.js +45 -0
  207. package/dist/cli/chunks/structural-health-K6LRCKV6.js +2 -0
  208. package/dist/cli/chunks/sync-MHSHNLIM.js +23 -0
  209. package/dist/cli/chunks/task-handler-JNOIBZ2G.js +49 -0
  210. package/dist/cli/chunks/task-handlers-P5DSUKND.js +2 -0
  211. package/dist/cli/chunks/test-DO22BNIL.js +33 -0
  212. package/dist/cli/chunks/test-scheduling-VLRQZEFL.js +15 -0
  213. package/dist/cli/chunks/token-bootstrap-4VJKGVMK.js +2 -0
  214. package/dist/cli/chunks/token-usage-LG3PXRXH.js +25 -0
  215. package/dist/cli/chunks/transformers-GY7SIKEU.js +2 -0
  216. package/dist/cli/chunks/tree-sitter-wasm-parser-FT2KB66N.js +2 -0
  217. package/dist/cli/chunks/types-QJGNBKP2.js +2 -0
  218. package/dist/cli/chunks/unified-memory-XYGENQUT.js +2 -0
  219. package/dist/cli/chunks/unified-memory-hnsw-MVEGQBF3.js +2 -0
  220. package/dist/cli/chunks/unified-persistence-PFRCWEUG.js +2 -0
  221. package/dist/cli/chunks/validate-VQCRSVNQ.js +21 -0
  222. package/dist/cli/chunks/validate-swarm-A5DHAWTP.js +14 -0
  223. package/dist/cli/chunks/vibium-RZBSL4EB.js +2 -0
  224. package/dist/cli/chunks/visual-security-V47BLGJM.js +2 -0
  225. package/dist/cli/chunks/web-tree-sitter-7C4NXEOF.js +2 -0
  226. package/dist/cli/chunks/windsurf-installer-ES3KPQG3.js +7 -0
  227. package/dist/cli/chunks/witness-chain-BR63P4A7.js +2 -0
  228. package/dist/cli/chunks/workflow-JETHX4ML.js +51 -0
  229. package/dist/cli/chunks/workflow-orchestrator-7PZMX3JZ.js +2 -0
  230. package/dist/cli/chunks/wrappers-WP5RH745.js +2 -0
  231. package/dist/cli/commands/daemon.d.ts +13 -0
  232. package/dist/cli/commands/daemon.js +224 -0
  233. package/dist/cli/commands/hooks-handlers/hooks-shared.js +2 -1
  234. package/dist/cli/commands/plugin.d.ts +12 -0
  235. package/dist/cli/commands/plugin.js +135 -0
  236. package/dist/cli/commands/workflow.d.ts +10 -0
  237. package/dist/cli/commands/workflow.js +587 -0
  238. package/dist/cli/handlers/brain-handler.js +13 -8
  239. package/dist/cli/handlers/heartbeat-handler.d.ts +1 -0
  240. package/dist/cli/handlers/heartbeat-handler.js +20 -10
  241. package/dist/cli/handlers/hypergraph-handler.js +3 -3
  242. package/dist/cli/handlers/init-handler.js +10 -9
  243. package/dist/cli/handlers/interfaces.d.ts +4 -4
  244. package/dist/cli/index.js +159 -638
  245. package/dist/cli/lazy-registry.d.ts +27 -0
  246. package/dist/cli/lazy-registry.js +70 -0
  247. package/dist/context/compaction/context-budget.d.ts +71 -0
  248. package/dist/context/compaction/context-budget.js +120 -0
  249. package/dist/context/compaction/index.d.ts +96 -0
  250. package/dist/context/compaction/index.js +259 -0
  251. package/dist/context/compaction/llm-caller-adapter.d.ts +14 -0
  252. package/dist/context/compaction/llm-caller-adapter.js +47 -0
  253. package/dist/context/compaction/tier1-microcompact.d.ts +33 -0
  254. package/dist/context/compaction/tier1-microcompact.js +47 -0
  255. package/dist/context/compaction/tier2-session-summary.d.ts +72 -0
  256. package/dist/context/compaction/tier2-session-summary.js +172 -0
  257. package/dist/context/compaction/tier3-llm-compact.d.ts +65 -0
  258. package/dist/context/compaction/tier3-llm-compact.js +166 -0
  259. package/dist/context/compaction/tier4-reactive.d.ts +54 -0
  260. package/dist/context/compaction/tier4-reactive.js +129 -0
  261. package/dist/coordination/consensus/providers/claude-provider.d.ts +1 -0
  262. package/dist/coordination/consensus/providers/claude-provider.js +23 -3
  263. package/dist/domains/test-generation/generators/base-test-generator.d.ts +1 -1
  264. package/dist/domains/test-generation/generators/base-test-generator.js +11 -11
  265. package/dist/domains/test-generation/generators/go-test-generator.js +12 -12
  266. package/dist/domains/test-generation/generators/junit5-generator.js +9 -9
  267. package/dist/domains/test-generation/generators/kotlin-junit-generator.js +10 -10
  268. package/dist/domains/test-generation/generators/pytest-generator.js +8 -8
  269. package/dist/domains/test-generation/generators/swift-testing-generator.js +8 -8
  270. package/dist/domains/test-generation/generators/test-value-helpers.d.ts +20 -0
  271. package/dist/domains/test-generation/generators/test-value-helpers.js +48 -0
  272. package/dist/domains/test-generation/generators/xunit-generator.js +11 -11
  273. package/dist/hooks/cross-phase-hooks.d.ts +11 -0
  274. package/dist/hooks/cross-phase-hooks.js +73 -9
  275. package/dist/hooks/security/config-snapshot.d.ts +21 -0
  276. package/dist/hooks/security/config-snapshot.js +33 -0
  277. package/dist/hooks/security/exit-codes.d.ts +28 -0
  278. package/dist/hooks/security/exit-codes.js +33 -0
  279. package/dist/hooks/security/index.d.ts +15 -0
  280. package/dist/hooks/security/index.js +15 -0
  281. package/dist/hooks/security/ssrf-guard.d.ts +25 -0
  282. package/dist/hooks/security/ssrf-guard.js +69 -0
  283. package/dist/index.d.ts +1 -1
  284. package/dist/index.js +1 -2
  285. package/dist/init/init-wizard-hooks.js +15 -1
  286. package/dist/init/phases/07-hooks.js +2 -2
  287. package/dist/init/settings-merge.js +3 -7
  288. package/dist/kernel/kernel.js +35 -0
  289. package/dist/kernel/memory-backend.js +3 -1
  290. package/dist/mcp/bundle.js +416 -362
  291. package/dist/mcp/entry.js +132 -77
  292. package/dist/mcp/http-server.js +4 -1
  293. package/dist/mcp/index.d.ts +2 -2
  294. package/dist/mcp/index.js +5 -4
  295. package/dist/mcp/middleware/batch-executor.d.ts +46 -0
  296. package/dist/mcp/middleware/batch-executor.js +150 -0
  297. package/dist/mcp/middleware/microcompact.d.ts +97 -0
  298. package/dist/mcp/middleware/microcompact.js +179 -0
  299. package/dist/mcp/middleware/middleware-chain.d.ts +37 -0
  300. package/dist/mcp/middleware/middleware-chain.js +60 -0
  301. package/dist/mcp/protocol-server.d.ts +16 -0
  302. package/dist/mcp/protocol-server.js +140 -36
  303. package/dist/mcp/services/session-durability-middleware.d.ts +22 -0
  304. package/dist/mcp/services/session-durability-middleware.js +64 -0
  305. package/dist/mcp/services/session-resume.d.ts +29 -0
  306. package/dist/mcp/services/session-resume.js +221 -0
  307. package/dist/mcp/services/session-store.d.ts +84 -0
  308. package/dist/mcp/services/session-store.js +163 -0
  309. package/dist/mcp/tool-registry.d.ts +9 -0
  310. package/dist/mcp/tool-registry.js +30 -1
  311. package/dist/mcp/types.d.ts +1 -0
  312. package/dist/plugins/cache.d.ts +44 -0
  313. package/dist/plugins/cache.js +149 -0
  314. package/dist/plugins/index.d.ts +15 -0
  315. package/dist/plugins/index.js +15 -0
  316. package/dist/plugins/lifecycle.d.ts +67 -0
  317. package/dist/plugins/lifecycle.js +175 -0
  318. package/dist/plugins/manifest.d.ts +45 -0
  319. package/dist/plugins/manifest.js +173 -0
  320. package/dist/plugins/resolver.d.ts +37 -0
  321. package/dist/plugins/resolver.js +80 -0
  322. package/dist/plugins/security.d.ts +23 -0
  323. package/dist/plugins/security.js +125 -0
  324. package/dist/plugins/sources/github.d.ts +17 -0
  325. package/dist/plugins/sources/github.js +77 -0
  326. package/dist/plugins/sources/local.d.ts +20 -0
  327. package/dist/plugins/sources/local.js +32 -0
  328. package/dist/plugins/sources/npm.d.ts +18 -0
  329. package/dist/plugins/sources/npm.js +82 -0
  330. package/dist/shared/llm/retry.d.ts +5 -2
  331. package/dist/shared/llm/retry.js +7 -3
  332. package/dist/shared/prompt-cache-latch.d.ts +41 -0
  333. package/dist/shared/prompt-cache-latch.js +63 -0
  334. package/dist/shared/retry-engine.d.ts +77 -0
  335. package/dist/shared/retry-engine.js +194 -0
  336. package/dist/workers/daemon.d.ts +8 -0
  337. package/dist/workers/daemon.js +13 -0
  338. package/dist/workers/quality-daemon/ci-monitor.d.ts +55 -0
  339. package/dist/workers/quality-daemon/ci-monitor.js +147 -0
  340. package/dist/workers/quality-daemon/coverage-delta.d.ts +72 -0
  341. package/dist/workers/quality-daemon/coverage-delta.js +135 -0
  342. package/dist/workers/quality-daemon/git-watcher.d.ts +51 -0
  343. package/dist/workers/quality-daemon/git-watcher.js +209 -0
  344. package/dist/workers/quality-daemon/index.d.ts +119 -0
  345. package/dist/workers/quality-daemon/index.js +343 -0
  346. package/dist/workers/quality-daemon/nightly-consolidation.d.ts +74 -0
  347. package/dist/workers/quality-daemon/nightly-consolidation.js +136 -0
  348. package/dist/workers/quality-daemon/notification-service.d.ts +67 -0
  349. package/dist/workers/quality-daemon/notification-service.js +178 -0
  350. package/dist/workers/quality-daemon/persistent-memory.d.ts +31 -0
  351. package/dist/workers/quality-daemon/persistent-memory.js +30 -0
  352. package/dist/workers/quality-daemon/priority-queue.d.ts +97 -0
  353. package/dist/workers/quality-daemon/priority-queue.js +126 -0
  354. package/dist/workers/quality-daemon/test-suggester.d.ts +50 -0
  355. package/dist/workers/quality-daemon/test-suggester.js +121 -0
  356. package/dist/workers/worker-manager.js +2 -1
  357. package/package.json +1 -1
  358. package/dist/mcp/server.d.ts +0 -46
  359. package/dist/mcp/server.js +0 -802
@@ -0,0 +1,316 @@
1
+ if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.0");process.exit(0)}
2
+ import{b as P,c as x,d as R,f as O,g as j,h as D,i as $,j as L,k as N}from"./chunk-BR26T7ZS.js";import{b as _,d as T}from"./chunk-WGMPEW2T.js";import{a as k,c as q}from"./chunk-JZSDOIXA.js";import{a as v,b as ee}from"./chunk-263XS447.js";T();import{existsSync as w,mkdirSync as Q,writeFileSync as S,readFileSync as I,copyFileSync as te}from"fs";import{join as g,dirname as ne}from"path";async function M(t,e){if(!e.hooks.claudeCode)return!1;let n=g(t,".claude");w(n)||Q(n,{recursive:!0});let r=g(n,"settings.json"),s={};if(w(r))try{let u=I(r,"utf-8");s=_(u)}catch{s={}}let i={PreToolUse:[{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'npx agentic-qe hooks guard --file "$TOOL_INPUT_file_path" --json',timeout:3e3,continueOnError:!0}]},{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'npx agentic-qe hooks pre-edit --file "$TOOL_INPUT_file_path" --json',timeout:5e3,continueOnError:!0}]},{matcher:"^Bash$",hooks:[{type:"command",command:'npx agentic-qe hooks pre-command --command "$TOOL_INPUT_command" --json',timeout:3e3,continueOnError:!0}]},{matcher:"^Task$",hooks:[{type:"command",command:'npx agentic-qe hooks pre-task --description "$TOOL_INPUT_prompt" --json',timeout:5e3,continueOnError:!0}]}],PostToolUse:[{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'npx agentic-qe hooks post-edit --file "$TOOL_INPUT_file_path" --success --json',timeout:5e3,continueOnError:!0}]},{matcher:"^Bash$",hooks:[{type:"command",command:'npx agentic-qe hooks post-command --command "$TOOL_INPUT_command" --success --json',timeout:5e3,continueOnError:!0}]},{matcher:"^Task$",hooks:[{type:"command",command:'npx agentic-qe hooks post-task --task-id "$TOOL_RESULT_agent_id" --success --json',timeout:5e3,continueOnError:!0}]}],UserPromptSubmit:[{hooks:[{type:"command",command:'npx agentic-qe hooks route --task "$PROMPT" --json',timeout:5e3,continueOnError:!0}]}],SessionStart:[{hooks:[{type:"command",command:'npx agentic-qe hooks session-start --session-id "$SESSION_ID" --json',timeout:1e4,continueOnError:!0}]}],Stop:[{hooks:[{type:"command",command:"npx agentic-qe hooks session-end --save-state --json",timeout:5e3,continueOnError:!0}]}]},d=s.hooks||{};s.hooks=O(d,i);let c=s.env||{};s.env={...c,...j(e)};let m=D(e,t);for(let[u,h]of Object.entries(m))if(u==="_aqePermissions"){let p=s.permissions||{},l=p.allow||[],y=h,C=[...new Set([...l,...y])];s.permissions={...p,allow:C}}else s[u]=h;let a=s.enabledMcpjsonServers||[];return a=a.filter(u=>u!=="aqe"),a.includes("agentic-qe")||a.push("agentic-qe"),s.enabledMcpjsonServers=a,S(r,JSON.stringify(s,null,2),"utf-8"),await re(t),!0}async function re(t){let e=g(t,".claude","hooks");w(e)||Q(e,{recursive:!0});let n=g(e,"cross-phase-memory.yaml");if(w(n))return;let r=[g(ne(import.meta.url.replace("file://","")),"..","..","assets","hooks","cross-phase-memory.yaml"),g(process.cwd(),"assets","hooks","cross-phase-memory.yaml"),g(process.cwd(),"v3","assets","hooks","cross-phase-memory.yaml")];for(let i of r)try{if(w(i)){te(i,n),console.log(" \u2713 Cross-phase memory hooks installed");return}}catch{}S(n,`# Cross-Phase Memory Hooks Configuration
3
+ # Generated by aqe init
4
+ # See: https://github.com/anthropics/agentic-qe/docs/cross-phase-memory.md
5
+
6
+ version: "1.0"
7
+ enabled: true
8
+
9
+ hooks:
10
+ # Add custom QCSD feedback loop hooks here
11
+ # See .claude/hooks/cross-phase-memory.yaml in the agentic-qe repo for examples
12
+
13
+ routing:
14
+ authorized_receivers:
15
+ strategic:
16
+ - "qe-risk-assessor"
17
+ - "qe-quality-criteria-recommender"
18
+ tactical:
19
+ - "qe-product-factors-assessor"
20
+ operational:
21
+ - "qe-test-architect"
22
+ - "qe-tdd-specialist"
23
+ quality-criteria:
24
+ - "qe-requirements-validator"
25
+ - "qe-bdd-generator"
26
+ `,"utf-8"),console.log(" \u2713 Cross-phase memory hooks created (minimal config)")}async function z(t){let e=g(t,".mcp.json"),n={};if(w(e))try{let s=I(e,"utf-8");n=_(s)}catch{n={}}n.mcpServers||(n.mcpServers={});let r=n.mcpServers;return r["agentic-qe"]={command:"npx",args:["@anthropics/agentic-qe","mcp","start"],env:{AQE_LEARNING_ENABLED:"true",AQE_VERBOSE:"false"},autoStart:!1},S(e,JSON.stringify(n,null,2),"utf-8"),!0}async function U(t,e){let n=g(t,"CLAUDE.md"),r=se(e);if(w(n)){let s=I(n,"utf-8");if(s.includes("## Agentic QE v3"))return!0;let i=g(t,"CLAUDE.md.backup");S(i,s,"utf-8"),S(n,s+`
27
+
28
+ `+r,"utf-8")}else S(n,r,"utf-8");return!0}function se(t){let e=t.domains.enabled.slice(0,6).join(", "),n=Math.max(0,t.domains.enabled.length-6);return`## Agentic QE v3
29
+
30
+ This project uses **Agentic QE v3** - a Domain-Driven Quality Engineering platform with 12 bounded contexts, ReasoningBank learning, and HNSW vector search.
31
+
32
+ ---
33
+
34
+ ## \u{1F41D} AQE FLEET ORCHESTRATION
35
+
36
+ ### Fleet Initialization
37
+
38
+ **For QE-specific tasks, initialize the AQE fleet:**
39
+
40
+ \`\`\`javascript
41
+ // Initialize AQE Fleet with MCP tool
42
+ mcp__agentic-qe__fleet_init({
43
+ config: {
44
+ topology: "hierarchical", // Queen-led for QE coordination
45
+ maxAgents: 15,
46
+ testingFocus: ["unit", "integration", "e2e", "performance"],
47
+ frameworks: ["vitest", "jest", "playwright"],
48
+ environments: ["node", "browser"]
49
+ },
50
+ projectContext: {
51
+ language: "typescript",
52
+ buildSystem: "npm"
53
+ }
54
+ })
55
+ \`\`\`
56
+
57
+ ### 12 DDD Domains \u2192 Agent Mapping
58
+
59
+ | Domain | Primary Agents | Focus Area |
60
+ |--------|---------------|------------|
61
+ | \`test-generation\` | qe-test-architect, qe-tdd-specialist | AI-powered test creation |
62
+ | \`test-execution\` | qe-parallel-executor, qe-flaky-hunter, qe-retry-handler | Parallel execution, flaky detection |
63
+ | \`coverage-analysis\` | qe-coverage-specialist, qe-gap-detector | O(log n) sublinear coverage |
64
+ | \`quality-assessment\` | qe-quality-gate, qe-deployment-advisor | Quality gates, risk scoring |
65
+ | \`defect-intelligence\` | qe-defect-predictor, qe-root-cause-analyzer | ML-powered defect prediction |
66
+ | \`learning-optimization\` | qe-learning-coordinator, qe-pattern-learner | Cross-domain pattern learning |
67
+ | \`requirements-validation\` | qe-tdd-specialist, qe-property-tester | BDD scenarios, property tests |
68
+ | \`code-intelligence\` | qe-knowledge-manager, code-analyzer | Knowledge graphs, 80% token reduction |
69
+ | \`security-compliance\` | qe-security-scanner, qe-security-auditor | OWASP, CVE detection |
70
+ | \`contract-testing\` | qe-contract-validator, qe-api-tester | Pact, schema validation |
71
+ | \`visual-accessibility\` | qe-visual-tester, qe-a11y-validator | Visual regression, WCAG |
72
+ | \`chaos-resilience\` | qe-chaos-engineer, qe-performance-tester | Fault injection, load testing |
73
+
74
+ ### Fleet MCP Tools
75
+
76
+ \`\`\`javascript
77
+ // Spawn specialized QE agent
78
+ mcp__agentic-qe__agent_spawn({
79
+ spec: {
80
+ type: "test-generator",
81
+ capabilities: ["unit-tests", "integration-tests"],
82
+ name: "test-gen-1"
83
+ },
84
+ fleetId: "fleet-123"
85
+ })
86
+
87
+ // AI-enhanced test generation
88
+ mcp__agentic-qe__test_generate_enhanced({
89
+ sourceCode: "...",
90
+ language: "typescript",
91
+ testType: "unit",
92
+ coverageGoal: 90,
93
+ aiEnhancement: true,
94
+ detectAntiPatterns: true
95
+ })
96
+
97
+ // Parallel test execution with retry
98
+ mcp__agentic-qe__test_execute_parallel({
99
+ testFiles: ["tests/**/*.test.ts"],
100
+ parallelism: 4,
101
+ retryFailures: true,
102
+ maxRetries: 3,
103
+ collectCoverage: true
104
+ })
105
+
106
+ // Orchestrate QE task across fleet
107
+ mcp__agentic-qe__task_orchestrate({
108
+ task: {
109
+ type: "comprehensive-testing",
110
+ priority: "high",
111
+ strategy: "adaptive",
112
+ maxAgents: 5
113
+ },
114
+ context: {
115
+ project: "my-project",
116
+ environment: "test"
117
+ },
118
+ fleetId: "fleet-123"
119
+ })
120
+ \`\`\`
121
+
122
+ ### QE Memory Operations
123
+
124
+ \`\`\`javascript
125
+ // Store QE pattern with namespace
126
+ mcp__agentic-qe__memory_store({
127
+ key: "coverage-pattern-auth",
128
+ value: { pattern: "...", successRate: 0.95 },
129
+ namespace: "qe-patterns",
130
+ ttl: 86400,
131
+ persist: true
132
+ })
133
+
134
+ // Query memory with pattern matching
135
+ mcp__agentic-qe__memory_query({
136
+ pattern: "coverage-*",
137
+ namespace: "qe-patterns",
138
+ limit: 10
139
+ })
140
+ \`\`\`
141
+
142
+ ### QE Task Routing by Domain
143
+
144
+ | Task Type | MCP Tool | Agents Spawned |
145
+ |-----------|----------|----------------|
146
+ | Generate tests | \`test_generate_enhanced\` | qe-test-architect, qe-tdd-specialist |
147
+ | Run tests | \`test_execute_parallel\` | qe-parallel-executor, qe-retry-handler |
148
+ | Analyze coverage | \`task_orchestrate\` (coverage) | qe-coverage-specialist, qe-gap-detector |
149
+ | Quality gate | \`task_orchestrate\` (quality-gate) | qe-quality-gate, qe-deployment-advisor |
150
+ | Security scan | \`agent_spawn\` (security-scanner) | qe-security-scanner, qe-security-auditor |
151
+ | Chaos test | \`agent_spawn\` (chaos-engineer) | qe-chaos-engineer, qe-load-tester |
152
+
153
+ ---
154
+
155
+ ## Quick Reference
156
+
157
+ \`\`\`bash
158
+ # Run tests
159
+ npm test -- --run
160
+
161
+ # Check quality
162
+ aqe quality assess
163
+
164
+ # Generate tests
165
+ aqe test generate <file>
166
+
167
+ # Coverage analysis
168
+ aqe coverage <path>
169
+ \`\`\`
170
+
171
+ ### MCP Server
172
+
173
+ The AQE v3 MCP server is configured in \`.claude/mcp.json\`. Available tools:
174
+
175
+ | Tool | Description |
176
+ |------|-------------|
177
+ | \`fleet_init\` | Initialize QE fleet with topology |
178
+ | \`agent_spawn\` | Spawn specialized QE agent |
179
+ | \`test_generate_enhanced\` | AI-powered test generation |
180
+ | \`test_execute_parallel\` | Parallel test execution with retry |
181
+ | \`task_orchestrate\` | Orchestrate multi-agent QE tasks |
182
+ | \`coverage_analyze_sublinear\` | O(log n) coverage analysis |
183
+ | \`quality_assess\` | Quality gate evaluation |
184
+ | \`memory_store\` / \`memory_query\` | Pattern storage with namespacing |
185
+ | \`security_scan_comprehensive\` | SAST/DAST scanning |
186
+ | \`fleet_status\` | Get fleet and agent status |
187
+
188
+ ### Configuration
189
+
190
+ - **Enabled Domains**: ${e}${n>0?` (+${n} more)`:""}
191
+ - **Learning**: ${t.learning.enabled?"Enabled":"Disabled"} (${t.learning.embeddingModel} embeddings)
192
+ - **Max Concurrent Agents**: ${t.agents.maxConcurrent}
193
+ - **Background Workers**: ${t.workers.enabled.length>0?t.workers.enabled.join(", "):"None"}
194
+
195
+ ### V3 QE Agents
196
+
197
+ QE agents are installed in \`.claude/agents/v3/\`. Use with Claude Code's Task tool:
198
+
199
+ \`\`\`javascript
200
+ // Example: Generate tests
201
+ Task({ prompt: "Generate unit tests for auth module", subagent_type: "qe-test-architect", run_in_background: true })
202
+
203
+ // Example: Analyze coverage
204
+ Task({ prompt: "Find coverage gaps in src/", subagent_type: "qe-coverage-specialist", run_in_background: true })
205
+
206
+ // Example: Security scan
207
+ Task({ prompt: "Run security audit", subagent_type: "qe-security-scanner", run_in_background: true })
208
+ \`\`\`
209
+
210
+ ### Integration with Claude Flow
211
+
212
+ **AQE Fleet + Claude Flow work together:**
213
+
214
+ \`\`\`javascript
215
+ // STEP 1: Initialize Claude Flow swarm for coordination
216
+ Bash("npx ruflo swarm init --topology hierarchical --max-agents 15")
217
+
218
+ // STEP 2: Initialize AQE Fleet for QE-specific work
219
+ mcp__agentic-qe__fleet_init({
220
+ config: { topology: "hierarchical", maxAgents: 10, testingFocus: ["unit", "integration"] }
221
+ })
222
+
223
+ // STEP 3: Spawn agents via Claude Code Task tool (do the actual work)
224
+ Task({ prompt: "Generate tests for auth module", subagent_type: "qe-test-architect", run_in_background: true })
225
+ Task({ prompt: "Analyze coverage gaps", subagent_type: "qe-coverage-specialist", run_in_background: true })
226
+
227
+ // STEP 4: Store learnings in both systems
228
+ mcp__agentic-qe__memory_store({ key: "pattern-1", value: "...", namespace: "qe-patterns", persist: true })
229
+ Bash("npx ruflo memory store --key 'qe-pattern-1' --value '...' --namespace patterns")
230
+ \`\`\`
231
+
232
+ ### Data Storage
233
+
234
+ - **Memory Backend**: \`.agentic-qe/memory.db\` (SQLite)
235
+ - **Pattern Storage**: \`.agentic-qe/data/memory.db\` (ReasoningBank)
236
+ - **HNSW Index**: \`.agentic-qe/data/hnsw/index.bin\`
237
+ - **Configuration**: \`.agentic-qe/config.yaml\`
238
+
239
+ ### Best Practices
240
+
241
+ 1. **Test Execution**: Always use \`npm test -- --run\` (not \`npm test\` which runs in watch mode)
242
+ 2. **Coverage Targets**: Aim for 80%+ coverage on critical paths
243
+ 3. **Quality Gates**: Run \`quality_assess\` before merging PRs
244
+ 4. **Pattern Learning**: AQE learns from successful test patterns - consistent naming helps
245
+ 5. **Fleet Coordination**: Use \`fleet_init\` before spawning multiple QE agents
246
+ 6. **Memory Persistence**: Use \`persist: true\` for patterns you want to keep across sessions
247
+
248
+ ### Troubleshooting
249
+
250
+ If MCP tools aren't working:
251
+ \`\`\`bash
252
+ # Verify MCP server is configured
253
+ cat .claude/mcp.json
254
+
255
+ # Check fleet status
256
+ mcp__agentic-qe__fleet_status({ includeAgentDetails: true })
257
+
258
+ # Reinitialize if needed
259
+ aqe init --auto
260
+ \`\`\`
261
+
262
+ ---
263
+ *Generated by AQE v3 init - ${new Date().toISOString()}*
264
+ `}q();import{existsSync as f,mkdirSync as b,writeFileSync as E}from"fs";import{join as o,dirname as ae}from"path";q();ee();T();async function F(t,e){let n=o(t,".agentic-qe","memory.db");try{let r=ae(n);f(r)||b(r,{recursive:!0});let s=v(n);try{s.exec(`
265
+ CREATE TABLE IF NOT EXISTS kv_store (
266
+ key TEXT NOT NULL,
267
+ namespace TEXT NOT NULL,
268
+ value TEXT NOT NULL,
269
+ expires_at INTEGER,
270
+ created_at INTEGER DEFAULT (strftime('%s', 'now') * 1000),
271
+ PRIMARY KEY (namespace, key)
272
+ );
273
+ `);let i=Date.now();return s.prepare(`
274
+ INSERT OR REPLACE INTO kv_store (key, namespace, value, created_at)
275
+ VALUES (?, '_system', ?, ?)
276
+ `).run("aqe_version",JSON.stringify(e),i),s.prepare(`
277
+ INSERT OR REPLACE INTO kv_store (key, namespace, value, created_at)
278
+ VALUES (?, '_system', ?, ?)
279
+ `).run("init_timestamp",JSON.stringify(new Date().toISOString()),i),s.close(),console.log(` \u2713 Version ${e} written to memory.db`),!0}catch(i){return s.close(),console.warn(` \u26A0 Could not write version: ${k(i)}`),!1}}catch(r){return console.warn(` \u26A0 Could not open memory.db: ${k(r)}`),!1}}async function W(t){let e=null;try{e=(await import("./better-sqlite3-7KY2RDXO.js")).default}catch{throw new Error(`SQLite persistence REQUIRED but better-sqlite3 is not installed.
280
+ Install it with: npm install better-sqlite3
281
+ If you see native compilation errors, ensure build tools are installed:
282
+ - macOS: xcode-select --install
283
+ - Ubuntu/Debian: sudo apt-get install build-essential python3
284
+ - Alpine: apk add build-base python3`)}let n=o(t,".agentic-qe");f(n)||b(n,{recursive:!0});let r=o(n,"memory.db");try{let s=new e(r);if(s.pragma("journal_mode = WAL"),s.pragma("busy_timeout = 5000"),s.exec(`
285
+ CREATE TABLE IF NOT EXISTS kv_store (
286
+ key TEXT NOT NULL,
287
+ namespace TEXT NOT NULL,
288
+ value TEXT NOT NULL,
289
+ expires_at INTEGER,
290
+ created_at INTEGER DEFAULT (strftime('%s', 'now') * 1000),
291
+ PRIMARY KEY (namespace, key)
292
+ );
293
+ CREATE INDEX IF NOT EXISTS idx_kv_namespace ON kv_store(namespace);
294
+ CREATE INDEX IF NOT EXISTS idx_kv_expires ON kv_store(expires_at) WHERE expires_at IS NOT NULL;
295
+ `),!s.prepare(`
296
+ SELECT name FROM sqlite_master WHERE type='table' AND name='kv_store'
297
+ `).get())throw new Error("Failed to create kv_store table");return s.prepare(`
298
+ INSERT OR REPLACE INTO kv_store (key, namespace, value)
299
+ VALUES (?, ?, ?)
300
+ `).run("_init_test","_system",JSON.stringify({initialized:new Date().toISOString()})),s.close(),console.log(`\u2713 SQLite persistence initialized: ${r}`),!0}catch(s){throw new Error(`SQLite persistence initialization FAILED: ${s}
301
+ Database path: ${r}
302
+ Ensure the directory is writable and has sufficient disk space.`)}}async function G(t){let e=o(t,".agentic-qe","memory.db");if(!f(e))return!1;try{let n=v(e),r=n.prepare(`
303
+ SELECT COUNT(*) as count FROM kv_store
304
+ WHERE namespace = 'code-intelligence:kg'
305
+ `).get();return n.close(),r.count>0}catch{return!1}}async function V(t){try{let{KnowledgeGraphService:e}=await import("./knowledge-graph-NGJKFTSN.js"),{InMemoryBackend:n}=await import("./memory-backend-3NQIZUXE.js"),r=new n;await r.initialize();let s=new e(r,{namespace:"code-intelligence:kg",enableVectorEmbeddings:!0}),d=await(await import("fast-glob")).default(["**/*.ts","**/*.tsx","**/*.js","**/*.jsx","**/*.py"],{cwd:t,ignore:["node_modules/**","dist/**","coverage/**",".agentic-qe/**"]}),c=await s.index({paths:d.map(m=>o(t,m)),incremental:!1,includeTests:!0});return s.destroy(),c.success?{status:"indexed",entries:c.value.nodesCreated+c.value.edgesCreated}:{status:"error",entries:0}}catch(e){return console.warn("Code intelligence scan warning:",k(e)),{status:"skipped",entries:0}}}async function B(t){let e=o(t,".agentic-qe","memory.db");try{let n=v(e),r=n.prepare(`
306
+ SELECT COUNT(*) as count FROM kv_store
307
+ WHERE namespace LIKE 'code-intelligence:kg%'
308
+ `).get();return n.close(),r.count}catch{return 0}}async function H(t,e,n){if(!e.learning.enabled)return 0;let r=o(t,".agentic-qe","data");f(r)||b(r,{recursive:!0});let s=o(r,"hnsw");f(s)||b(s,{recursive:!0});let i=o(r,"learning-config.json"),d={embeddingModel:e.learning.embeddingModel,hnswConfig:e.learning.hnswConfig,qualityThreshold:e.learning.qualityThreshold,promotionThreshold:e.learning.promotionThreshold,databasePath:o(r,"memory.db"),hnswIndexPath:o(s,"index.bin"),initialized:new Date().toISOString()};E(i,JSON.stringify(d,null,2),"utf-8");let c=0;if(e.learning.pretrainedPatterns&&n){let m=n,a=new Map;for(let p of m.patterns){let l=p.domain||"general";a.has(l)||a.set(l,[]),a.get(l).push(p)}let u=o(r,"pretrained-index.json"),h={version:m.version,totalPatterns:m.statistics.totalPatterns,domains:Array.from(a.entries()).map(([p,l])=>({name:p,patternCount:l.length})),loadedAt:new Date().toISOString()};E(u,JSON.stringify(h,null,2),"utf-8");for(let[p,l]of a){let y=o(r,"patterns",p);f(y)||b(y,{recursive:!0});let C=o(y,"patterns.json");E(C,JSON.stringify(l,null,2),"utf-8"),c+=l.length}return c}return 0}async function J(t,e){if(!e.workers.daemonAutoStart||e.workers.enabled.length===0)return 0;let n=o(t,".agentic-qe","workers");f(n)||b(n,{recursive:!0});let r={},s={"pattern-consolidator":6e4,"coverage-gap-scanner":3e5,"flaky-test-detector":6e5,"routing-accuracy-monitor":12e4};for(let a of e.workers.enabled)r[a]={name:a,enabled:!0,interval:e.workers.intervals[a]||s[a]||6e4,lastRun:null,status:"pending"};let i=o(n,"registry.json"),d={version:e.version,maxConcurrent:e.workers.maxConcurrent,workers:r,createdAt:new Date().toISOString(),daemonPid:null};E(i,JSON.stringify(d,null,2),"utf-8");for(let a of e.workers.enabled){let u=o(n,`${a}.json`),h={name:a,enabled:!0,interval:e.workers.intervals[a]||s[a]||6e4,projectRoot:t,dataDir:o(t,".agentic-qe","data"),createdAt:new Date().toISOString()};E(u,JSON.stringify(h,null,2),"utf-8")}let c=o(n,"start-daemon.cjs");return E(c,`#!/usr/bin/env node
309
+ // AQE v3 Worker Daemon Startup Script (cross-platform)
310
+ // Generated by aqe init
311
+
312
+ console.log("AQE v3 hooks work via CLI commands (no daemon required)");
313
+ console.log("Use: npx aqe hooks session-start");
314
+ `),e.workers.enabled.length}async function X(t,e){if(!e.skills.install)return 0;let r=await $({projectRoot:t,installV2Skills:e.skills.installV2,installV3Skills:e.skills.installV3,overwrite:e.skills.overwrite}).install();return r.errors.length>0&&console.warn("Skills installation warnings:",r.errors),r.installed.length}async function K(t){let n=await L({projectRoot:t,installQEAgents:!0,installSubagents:!0,overwrite:!1}).install();return n.errors.length>0&&console.warn("Agents installation warnings:",n.errors),n.installed.length}async function Y(t,e,n){let s=await N({projectRoot:t,installAgents:!0,installSkills:!0,overwrite:!1,n8nApiConfig:n}).install();return s.errors.length>0&&console.warn("N8n installation warnings:",s.errors),e.platforms||(e.platforms={}),e.platforms.n8n={enabled:!0,installAgents:!0,installSkills:!0,installTypeScriptAgents:!1,n8nApiConfig:n},{agents:s.agentsInstalled.length,skills:s.skillsInstalled.length}}async function Z(t,e){if(!e)throw new Error("No configuration to save");let n=o(t,".agentic-qe");f(n)||b(n,{recursive:!0});let r=oe(e),s=o(n,"config.yaml");E(s,r,"utf-8")}function oe(t){let e=["# Agentic QE v3 Configuration","# Generated by aqe init",`# ${new Date().toISOString()}`,""];e.push(`version: "${t.version}"`),e.push(""),e.push("project:"),e.push(` name: "${t.project.name}"`),e.push(` root: "${t.project.root}"`),e.push(` type: "${t.project.type}"`),e.push(""),e.push("learning:"),e.push(` enabled: ${t.learning.enabled}`),e.push(` embeddingModel: "${t.learning.embeddingModel}"`),e.push(" hnswConfig:"),e.push(` M: ${t.learning.hnswConfig.M}`),e.push(` efConstruction: ${t.learning.hnswConfig.efConstruction}`),e.push(` efSearch: ${t.learning.hnswConfig.efSearch}`),e.push(` qualityThreshold: ${t.learning.qualityThreshold}`),e.push(` promotionThreshold: ${t.learning.promotionThreshold}`),e.push(` pretrainedPatterns: ${t.learning.pretrainedPatterns}`),e.push(""),e.push("routing:"),e.push(` mode: "${t.routing.mode}"`),e.push(` confidenceThreshold: ${t.routing.confidenceThreshold}`),e.push(` feedbackEnabled: ${t.routing.feedbackEnabled}`),e.push(""),e.push("workers:"),e.push(" enabled:");for(let n of t.workers.enabled)e.push(` - "${n}"`);e.push(" intervals:");for(let[n,r]of Object.entries(t.workers.intervals))e.push(` ${n}: ${r}`);e.push(` maxConcurrent: ${t.workers.maxConcurrent}`),e.push(` daemonAutoStart: ${t.workers.daemonAutoStart}`),e.push(""),e.push("hooks:"),e.push(` claudeCode: ${t.hooks.claudeCode}`),e.push(` preCommit: ${t.hooks.preCommit}`),e.push(` ciIntegration: ${t.hooks.ciIntegration}`),e.push(""),e.push("skills:"),e.push(` install: ${t.skills.install}`),e.push(` installV2: ${t.skills.installV2}`),e.push(` installV3: ${t.skills.installV3}`),e.push(` overwrite: ${t.skills.overwrite}`),e.push(""),e.push("autoTuning:"),e.push(` enabled: ${t.autoTuning.enabled}`),e.push(" parameters:");for(let n of t.autoTuning.parameters)e.push(` - "${n}"`);e.push(` evaluationPeriodMs: ${t.autoTuning.evaluationPeriodMs}`),e.push(""),e.push("domains:"),e.push(" enabled:");for(let n of t.domains.enabled)e.push(` - "${n}"`);e.push(" disabled:");for(let n of t.domains.disabled)e.push(` - "${n}"`);return e.push(""),e.push("agents:"),e.push(` maxConcurrent: ${t.agents.maxConcurrent}`),e.push(` defaultTimeout: ${t.agents.defaultTimeout}`),e.push(""),e.join(`
315
+ `)}var ie=[{id:"welcome",title:"Welcome to AQE v3",description:"This wizard will configure Agentic QE for your project.",type:"info"},{id:"project-type",title:"Project Type",description:"What type of project is this?",type:"choice",options:[{value:"auto",label:"Auto-detect",description:"Let AQE analyze your project",recommended:!0},{value:"single",label:"Single Package",description:"Standard single-package project"},{value:"monorepo",label:"Monorepo",description:"Multi-package workspace"},{value:"library",label:"Library",description:"Publishable package/library"}],default:"auto"},{id:"learning-mode",title:"Learning System",description:"How should AQE learn from your project?",type:"choice",options:[{value:"full",label:"Full Learning",description:"Transformer embeddings + SQLite persistence",recommended:!0},{value:"basic",label:"Basic Learning",description:"Hash-based embeddings, in-memory"},{value:"disabled",label:"Disabled",description:"No pattern learning"}],default:"full"},{id:"load-patterns",title:"Pre-trained Patterns",description:"Load pre-trained QE patterns for faster results?",type:"confirm",default:!0},{id:"hooks",title:"Claude Code Integration",description:"Enable Claude Code hooks for seamless integration?",type:"confirm",default:!0},{id:"workers",title:"Background Workers",description:"Start background workers for continuous monitoring?",type:"confirm",default:!0},{id:"skills",title:"Install Skills",description:"Install AQE skills (v2 methodology + v3 domain skills)?",type:"confirm",default:!0},{id:"agents",title:"Install Agents",description:"Install V3 QE agents for Claude Code Task tool?",type:"confirm",default:!0}],A=class{projectRoot;options;analyzer;configurator;steps=[];constructor(e){this.options=e,this.projectRoot=e.projectRoot,this.analyzer=x(e.projectRoot),this.configurator=R({minimal:e.minimal})}async initialize(){let e=Date.now();try{let n=await this.runStep("Project Analysis",async()=>await this.analyzer.analyze()),r=await this.runStep("Configuration Generation",async()=>this.options.autoMode?this.configurator.recommend(n):this.applyWizardAnswers(n));await this.runStep("Persistence Database Setup",async()=>await W(this.projectRoot));let s=await this.runStep("Code Intelligence Pre-Scan",async()=>{if(!await G(this.projectRoot))return console.log(" Building knowledge graph for code intelligence..."),await V(n.projectRoot);let y=await B(this.projectRoot);return console.log(` Using existing code intelligence index (${y} entries)`),{status:"existing",entries:y}}),i=await this.runStep("Learning System Setup",async()=>r.learning.enabled&&!this.options.skipPatterns?await H(this.projectRoot,r,this.options.pretrainedLibrary):0),d=await this.runStep("Hooks Configuration",async()=>r.hooks.claudeCode?await M(this.projectRoot,r):!1),c=await this.runStep("MCP Configuration",async()=>await z(this.projectRoot)),m=await this.runStep("CLAUDE.md Generation",async()=>await U(this.projectRoot,r)),a=await this.runStep("Background Workers",async()=>r.workers.daemonAutoStart?await J(this.projectRoot,r):0),u=await this.runStep("Skills Installation",async()=>r.skills.install?await X(this.projectRoot,r):0),h=await this.runStep("Agents Installation",async()=>await K(this.projectRoot)),p;if(this.options.withN8n){let l=await this.runStep("N8n Platform Installation",async()=>await Y(this.projectRoot,r,this.options.n8nApiConfig));l&&(p=l)}return await this.runStep("Save Configuration",async()=>await Z(this.projectRoot,r)),await this.runStep("Version Marker",async()=>await F(this.projectRoot,r.version)),{success:!0,config:r,steps:this.steps,summary:{projectAnalyzed:!0,configGenerated:!0,codeIntelligenceIndexed:s?.entries??0,patternsLoaded:i,skillsInstalled:u,agentsInstalled:h,hooksConfigured:d,mcpConfigured:c,claudeMdGenerated:m,workersStarted:a,n8nInstalled:p},totalDurationMs:Date.now()-e,timestamp:new Date}}catch(n){return this.steps.push({step:"Initialization Failed",status:"error",message:k(n),durationMs:0}),{success:!1,config:P("unknown",this.projectRoot),steps:this.steps,summary:{projectAnalyzed:!1,configGenerated:!1,codeIntelligenceIndexed:0,patternsLoaded:0,skillsInstalled:0,agentsInstalled:0,hooksConfigured:!1,mcpConfigured:!1,claudeMdGenerated:!1,workersStarted:0},totalDurationMs:Date.now()-e,timestamp:new Date}}}getWizardSteps(){return ie}async runStep(e,n){let r=Date.now();try{let s=await n();return this.steps.push({step:e,status:"success",message:`${e} completed successfully`,durationMs:Date.now()-r}),s}catch(s){throw this.steps.push({step:e,status:"error",message:k(s),durationMs:Date.now()-r}),s}}applyWizardAnswers(e){let n=this.options.wizardAnswers||{},r=this.configurator.recommend(e);switch(n["project-type"]&&n["project-type"]!=="auto"&&(r.project.type=n["project-type"]),n["learning-mode"]){case"full":r.learning.enabled=!0,r.learning.embeddingModel="transformer";break;case"basic":r.learning.enabled=!0,r.learning.embeddingModel="hash";break;case"disabled":r.learning.enabled=!1;break}return n["load-patterns"]===!1&&(r.learning.pretrainedPatterns=!1),n.hooks===!1&&(r.hooks.claudeCode=!1),n.workers===!1&&(r.workers.daemonAutoStart=!1),n.skills===!1&&(r.skills.install=!1),r}};function le(t){return new A(t)}async function xe(t){return await le({projectRoot:t,autoMode:!0}).initialize()}function Re(t){let e=[];e.push(""),e.push("+-------------------------------------------------------------+"),e.push("| AQE v3 Initialization |"),e.push("+-------------------------------------------------------------+");for(let r of t.steps){let s=r.status==="success"?"[OK]":r.status==="error"?"[!!]":"[ ]";e.push(`| ${s} ${r.step.padEnd(50)} ${String(r.durationMs).padStart(4)}ms |`)}e.push("+-------------------------------------------------------------+"),e.push(`| Project: ${t.config.project.name.padEnd(47)} |`),e.push(`| Type: ${t.config.project.type.padEnd(50)} |`),e.push(`| Code Intel Indexed: ${String(t.summary.codeIntelligenceIndexed).padEnd(36)} |`),e.push(`| Patterns Loaded: ${String(t.summary.patternsLoaded).padEnd(39)} |`),e.push(`| Skills Installed: ${String(t.summary.skillsInstalled).padEnd(38)} |`),e.push(`| Agents Installed: ${String(t.summary.agentsInstalled).padEnd(38)} |`),e.push(`| Workers Started: ${String(t.summary.workersStarted).padEnd(39)} |`),e.push(`| Hooks Configured: ${t.summary.hooksConfigured?"Yes":"No".padEnd(38)} |`),e.push(`| MCP Server: ${t.summary.mcpConfigured?"Yes":"No".padEnd(44)} |`),e.push(`| CLAUDE.md: ${t.summary.claudeMdGenerated?"Yes":"No".padEnd(45)} |`),e.push("+-------------------------------------------------------------+");let n=t.success?"[OK] AQE v3 initialized as self-learning platform":"[!!] Initialization failed";return e.push(`| ${n.padEnd(57)} |`),e.push("+-------------------------------------------------------------+"),e.push(""),e.join(`
316
+ `)}export{A as a,le as b,xe as c,Re as d};
@@ -0,0 +1,2 @@
1
+ if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.0");process.exit(0)}
2
+ import{c as t}from"./chunk-4I2IOUS4.js";import{randomInt as o}from"node:crypto";function a(){return Math.random()}function m(n,e){return o(n,e)}function c(n,e){return n+Math.random()*(e-n)}var r=t(()=>{"use strict"});export{a,m as b,c,r as d};
@@ -0,0 +1,27 @@
1
+ if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.0");process.exit(0)}
2
+ import{k as p,o as N}from"./chunk-JJO7Y4H3.js";N();import{createHash as y}from"crypto";var g="0".repeat(64);function m(s){return y("sha256").update(s,"utf-8").digest("hex")}function b(s){try{return y("shake256",{outputLength:32}).update(s,"utf-8").digest("hex")}catch{return m(s)}}function _(s,t){return s==="shake256"?b(t):m(t)}function f(s){return JSON.stringify({id:s.id,prev_hash:s.prev_hash,action_hash:s.action_hash,action_type:s.action_type,action_data:s.action_data,timestamp:s.timestamp,actor:s.actor})}var d=class{constructor(t,i){this.externalDb=t;this.keyManager=i??null}db=null;initialized=!1;keyManager=null;async initialize(){if(!this.initialized){if(this.externalDb)this.db=this.externalDb;else{let t=p();await t.initialize(),this.db=t.getDatabase()}this.ensureTable(),this.initialized=!0}}getDatabase(){return this.db}getKeyManager(){return this.keyManager}ensureTable(){if(!this.db)throw new Error("Database not initialized");this.db.exec(`
3
+ CREATE TABLE IF NOT EXISTS witness_chain (
4
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
5
+ prev_hash TEXT NOT NULL, action_hash TEXT NOT NULL, action_type TEXT NOT NULL,
6
+ action_data TEXT, timestamp TEXT NOT NULL, actor TEXT NOT NULL,
7
+ hash_algo TEXT DEFAULT 'sha256', signature TEXT, signer_key_id TEXT
8
+ );
9
+ CREATE INDEX IF NOT EXISTS idx_witness_action_type ON witness_chain(action_type);
10
+ CREATE INDEX IF NOT EXISTS idx_witness_timestamp ON witness_chain(timestamp);
11
+ CREATE INDEX IF NOT EXISTS idx_witness_actor ON witness_chain(actor);
12
+ `),this.addColumnIfMissing("hash_algo","TEXT DEFAULT 'sha256'"),this.addColumnIfMissing("signature","TEXT"),this.addColumnIfMissing("signer_key_id","TEXT"),this.db.exec(`
13
+ CREATE TABLE IF NOT EXISTS witness_chain_archive (
14
+ id INTEGER PRIMARY KEY,
15
+ prev_hash TEXT NOT NULL, action_hash TEXT NOT NULL, action_type TEXT NOT NULL,
16
+ action_data TEXT, timestamp TEXT NOT NULL, actor TEXT NOT NULL,
17
+ hash_algo TEXT DEFAULT 'sha256', signature TEXT, signer_key_id TEXT,
18
+ archived_at TEXT NOT NULL
19
+ );
20
+ `)}addColumnIfMissing(t,i){if(!this.db)return;this.db.prepare("SELECT name FROM pragma_table_info('witness_chain')").all().some(r=>r.name===t)||this.db.exec(`ALTER TABLE witness_chain ADD COLUMN ${t} ${i}`)}append(t,i,e){if(!this.db)throw new Error("WitnessChain not initialized");let r=new Date().toISOString(),o=JSON.stringify(i),a="shake256",n=b(o),h=this.db.prepare("SELECT * FROM witness_chain ORDER BY id DESC LIMIT 1").get(),c=h?_(a,f(h)):g,l=null,u=null;if(this.keyManager){let R=Buffer.from(c+n+t+r+e,"utf-8"),T=this.keyManager.sign(R);l=T.signature.toString("hex"),u=T.keyId}return{id:this.db.prepare(`INSERT INTO witness_chain
21
+ (prev_hash, action_hash, action_type, action_data, timestamp, actor, hash_algo, signature, signer_key_id)
22
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(c,n,t,o,r,e,a,l,u).lastInsertRowid,prev_hash:c,action_hash:n,action_type:t,action_data:o,timestamp:r,actor:e,hash_algo:a,signature:l,signer_key_id:u}}verify(t){if(!this.db)throw new Error("WitnessChain not initialized");let i=this.db.prepare("SELECT * FROM witness_chain ORDER BY id ASC").all();if(i.length===0)return{valid:!0,entriesChecked:0};let e=0,r=t?.checkSignatures===!0&&this.keyManager!==null;for(let a=0;a<i.length;a++){let n=i[a],h=n.hash_algo||"sha256";if(n.action_hash!==_(h,n.action_data))return{valid:!1,brokenAt:n.id,entriesChecked:a+1,signatureFailures:e};if(a===0){if(n.prev_hash!==g)return{valid:!1,brokenAt:n.id,entriesChecked:1,signatureFailures:e}}else{let c=_(h,f(i[a-1]));if(n.prev_hash!==c)return{valid:!1,brokenAt:n.id,entriesChecked:a+1,signatureFailures:e}}if(r&&n.signature&&n.signer_key_id){let c=Buffer.from(n.prev_hash+n.action_hash+n.action_type+n.timestamp+n.actor,"utf-8");this.keyManager.verify(Buffer.from(c),Buffer.from(n.signature,"hex"),n.signer_key_id)||e++}}return{valid:e===0,entriesChecked:i.length,signatureFailures:e,...e>0?{brokenAt:i[0].id}:{}}}getEntries(t){if(!this.db)throw new Error("WitnessChain not initialized");let i=[],e=[];t?.action_type&&(i.push("action_type = ?"),e.push(t.action_type)),t?.since&&(i.push("timestamp >= ?"),e.push(t.since)),t?.until&&(i.push("timestamp <= ?"),e.push(t.until)),t?.actor&&(i.push("actor = ?"),e.push(t.actor));let r=i.length>0?`WHERE ${i.join(" AND ")}`:"",o=t?.limit!=null,a=t?.offset!=null,n=o||a?"LIMIT ?":"",h=a?"OFFSET ?":"";return o?e.push(t.limit):a&&e.push(-1),a&&e.push(t.offset),this.db.prepare(`SELECT * FROM witness_chain ${r} ORDER BY id ASC ${n} ${h}`).all(...e)}getPatternLineage(t){if(!this.db)throw new Error("WitnessChain not initialized");return this.db.prepare(`SELECT * FROM witness_chain
23
+ WHERE json_extract(action_data, '$.patternId') = ? OR json_extract(action_data, '$.pattern_id') = ?
24
+ ORDER BY id ASC`).all(t,t)}getActorHistory(t,i){if(!this.db)throw new Error("WitnessChain not initialized");return i?this.db.prepare("SELECT * FROM witness_chain WHERE actor = ? AND timestamp >= ? ORDER BY id ASC").all(t,i):this.db.prepare("SELECT * FROM witness_chain WHERE actor = ? ORDER BY id ASC").all(t)}archiveEntries(t){if(!this.db)throw new Error("WitnessChain not initialized");let i=new Date().toISOString(),r=this.db.prepare(`INSERT INTO witness_chain_archive
25
+ (id, prev_hash, action_hash, action_type, action_data, timestamp, actor, hash_algo, signature, signer_key_id, archived_at)
26
+ SELECT id, prev_hash, action_hash, action_type, action_data, timestamp, actor, hash_algo, signature, signer_key_id, ?
27
+ FROM witness_chain WHERE timestamp < ? AND id > 1 AND id NOT IN (SELECT id FROM witness_chain_archive)`).run(i,t).changes;return r>0&&this.db.prepare("DELETE FROM witness_chain WHERE timestamp < ? AND id > 1").run(t),{archived:r}}crossVerifyWithRvf(t){let i=this.verify(),e=t.status(),r=e.witnessValid===!0,o=typeof e.witnessEntries=="number"?e.witnessEntries:0;return{sqliteValid:i.valid,rvfValid:r,rvfEntries:o,bothValid:i.valid&&r}}getChainLength(){if(!this.db)throw new Error("WitnessChain not initialized");return this.db.prepare("SELECT COUNT(*) as count FROM witness_chain").get().count}},E=null;async function C(){return E||(E=new d,await E.initialize()),E}function v(s,t){return new d(s,t)}export{C as a,v as b};
@@ -0,0 +1,2 @@
1
+ if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.0");process.exit(0)}
2
+ import{a as S}from"./chunk-3JPRUND5.js";import{c as g}from"./chunk-4VUPRTVX.js";import{M as T,b as l}from"./chunk-2I7J3O6V.js";S();T();import{createRequire as B}from"module";var G=B(import.meta.url),d=class{validateTransfer(e,t){return{approved:!0}}};function R(){if(l().useCoherenceGate)try{let{CoherenceGate:o}=G("./coherence-gate.js");return new o}catch{}return new d}S();var x=g.create("transfer-verification"),A={maxSourceRegression:.05,minTargetImprovement:0,maxSourceConfidenceRegression:.1},b=class{config;constructor(e={}){this.config={...A,...e}}verifyTransfer(e){let t=e.sourcePerformanceAfter.successRate-e.sourcePerformanceBefore.successRate,r=e.targetPerformanceAfter.successRate-e.targetPerformanceBefore.successRate,n=e.sourcePerformanceAfter.avgConfidence-e.sourcePerformanceBefore.avgConfidence,a=e.targetPerformanceAfter.avgConfidence-e.targetPerformanceBefore.avgConfidence,s=t>=-this.config.maxSourceRegression&&n>=-this.config.maxSourceConfidenceRegression,c=r>=this.config.minTargetImprovement,u=s&&c,m;if(!u){let i=[];s||i.push(`source domain regressed: successRate delta=${t.toFixed(4)}, confidence delta=${n.toFixed(4)}`),c||i.push(`target domain did not improve: successRate delta=${r.toFixed(4)}`),m=i.join("; ")}return u?x.debug("Transfer verification passed",{transferId:e.transferId,sourceDelta:t,targetDelta:r}):x.warn("Transfer verification failed",{transferId:e.transferId,sourceDomain:e.sourceDomain,targetDomain:e.targetDomain,sourceDelta:t,targetDelta:r,failureReason:m}),{passed:u,sourceStable:s,targetImproved:c,sourceDelta:t,targetDelta:r,sourceConfidenceDelta:n,targetConfidenceDelta:a,failureReason:m}}getConfig(){return{...this.config}}};function M(o){return new b(o)}T();var p=class{alphas=new Map;betas=new Map;sample(e){let t=this.alphas.get(e)??1,r=this.betas.get(e)??1;return this.sampleBeta(t,r)}update(e,t){t?this.alphas.set(e,(this.alphas.get(e)??1)+1):this.betas.set(e,(this.betas.get(e)??1)+1)}getMean(e){let t=this.alphas.get(e)??1,r=this.betas.get(e)??1;return t/(t+r)}getObservationCount(e){let t=this.alphas.get(e)??1,r=this.betas.get(e)??1;return t-1+(r-1)}getAlpha(e){return this.alphas.get(e)??1}getBeta(e){return this.betas.get(e)??1}sampleBeta(e,t){let r=this.sampleGamma(e),n=this.sampleGamma(t);return r+n===0?.5:r/(r+n)}sampleGamma(e){if(e<1){let n=Math.random();return this.sampleGamma(e+1)*Math.pow(n,1/e)}let t=e-1/3,r=1/Math.sqrt(9*t);for(;;){let n,a;do n=this.standardNormal(),a=1+r*n;while(a<=0);a=a*a*a;let s=Math.random();if(s<1-.0331*n*n*n*n||Math.log(s)<.5*n*n+t*(1-a+Math.log(a)))return t*a}}standardNormal(){let e=Math.random(),t=Math.random();return Math.sqrt(-2*Math.log(e||1e-10))*Math.cos(2*Math.PI*t)}};var I={threshold:5,slack:.5,resetOnAlarm:!0,warmupSamples:20},h=class{config;states=new Map;constructor(e={}){this.config={...I,...e}}update(e,t){let r=this.getOrCreateState(e);if(r.samplesSinceReset++,r.mu===null)return r.warmupSum+=t,r.warmupCount++,r.warmupCount>=this.config.warmupSamples&&(r.mu=r.warmupSum/r.warmupCount),{driftDetected:!1,cumulativeSum:0,direction:"none",samplesSinceReset:r.samplesSinceReset};r.sPlus=Math.max(0,r.sPlus+(t-r.mu-this.config.slack)),r.sMinus=Math.max(0,r.sMinus+(-t+r.mu-this.config.slack));let n=Math.max(r.sPlus,r.sMinus),a=!1,s="none";r.sPlus>this.config.threshold?(a=!0,s="positive"):r.sMinus>this.config.threshold&&(a=!0,s="negative");let c={driftDetected:a,cumulativeSum:n,direction:s,samplesSinceReset:r.samplesSinceReset};return a&&this.config.resetOnAlarm&&(r.sPlus=0,r.sMinus=0,r.samplesSinceReset=0),c}reset(e){e?this.states.delete(e):this.states.clear()}getState(e){let t=this.states.get(e);if(!t)return{driftDetected:!1,cumulativeSum:0,direction:"none",samplesSinceReset:0};let r=Math.max(t.sPlus,t.sMinus),n="none";return t.sPlus>this.config.threshold?n="positive":t.sMinus>this.config.threshold&&(n="negative"),{driftDetected:t.sPlus>this.config.threshold||t.sMinus>this.config.threshold,cumulativeSum:r,direction:n,samplesSinceReset:t.samplesSinceReset}}getOrCreateState(e){let t=this.states.get(e);return t||(t={sPlus:0,sMinus:0,samplesSinceReset:0,warmupSum:0,warmupCount:0,mu:null},this.states.set(e,t)),t}};var w=g.create("domain-transfer"),V={minTransferProbability:.3,explorationWarmup:5,verification:{},maxHistorySize:1e3,useMetaLearningEnhancements:!0},y=class{constructor(e=100){this.decayThreshold=e}getDecayMultiplier(e){return e<=0?1:Math.pow(.5,e/this.decayThreshold)}applyDecay(e,t,r){return t+(e-t)*this.getDecayMultiplier(r)}},v=class{cusum;outcomes=[];windowSize;constructor(e=20){this.windowSize=e,this.cusum=new h({threshold:3,slack:.1,resetOnAlarm:!1,warmupSamples:Math.min(10,Math.floor(e/2))})}record(e){this.outcomes.push(e),this.outcomes.length>this.windowSize*2&&this.outcomes.splice(0,this.outcomes.length-this.windowSize*2);let t=this.getCurrentRate();this.cusum.update("learn",t)}isPlateaued(){return this.outcomes.length<this.windowSize?!1:!this.cusum.getState("learn").driftDetected}getCurrentRate(){if(this.outcomes.length===0)return 0;let e=this.outcomes.slice(-this.windowSize);return e.filter(Boolean).length/e.length}getOutcomeCount(){return this.outcomes.length}getCusumState(){return this.cusum.getState("learn")}},D=class{front=[];dominates(e,t){let r=e.successRate>=t.successRate&&e.speed>=t.speed&&e.confidence>=t.confidence,n=e.successRate>t.successRate||e.speed>t.speed||e.confidence>t.confidence;return r&&n}add(e){for(let t=this.front.length-1;t>=0;t--)this.dominates(e,this.front[t])&&this.front.splice(t,1);this.front.some(t=>this.dominates(t,e))||this.front.push(e)}getFront(){return[...this.front]}isNonDominated(e){return!this.front.some(t=>this.dominates(t,e))}},C=class{constructor(e=.2){this.bonusScale=e}triedPairs=new Set;markTried(e){this.triedPairs.add(e)}isTried(e){return this.triedPairs.has(e)}getBonus(e){return this.triedPairs.has(e)?0:this.bonusScale}apply(e,t){return Math.min(1,e+this.getBonus(t))}getTriedCount(){return this.triedPairs.size}},P=class{config;sampler;verifier;coherenceGate;transferHistory=[];affinityScores=new Map;performanceProvider=null;transferExecutor=null;nativeModule=null;decayingBeta;plateauDetector;paretoFront;curiosityBonus;constructor(e={}){this.config={...V,...e},this.sampler=new p,this.verifier=M(this.config.verification),this.coherenceGate=R(),this.decayingBeta=new y,this.plateauDetector=new v,this.paretoFront=new D,this.curiosityBonus=new C,this.tryLoadNativeModule()}evaluateTransfer(e,t){if(!this.isEnabled())return this.createRejectedCandidate(e,t);let r=this.makePairKey(e,t),n=this.sampler.sample(r),s=this.sampler.getObservationCount(r)<this.config.explorationWarmup,c=this.getAffinityScore(e,t);if(this.isMetaLearningEnabled()){let u=this.sampler.getMean(r),m=this.sampler.getAlpha(r)-1;n=this.decayingBeta.applyDecay(n,u,m),n=this.curiosityBonus.apply(n,r)}return{sourceDomain:e,targetDomain:t,sampledProbability:n,affinityScore:c,isExploration:s,pairKey:r}}executeTransfer(e){let t=`transfer-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,r=this.coherenceGate.validateTransfer({domain:e.sourceDomain},e.targetDomain);if(!r.approved)return w.info("Transfer blocked by coherence gate",{transferId:t,source:e.sourceDomain,target:e.targetDomain,reason:r.rejectionReason}),this.createBlockedResult(t,e,r);let n=this.getPerformanceSnapshot(e.sourceDomain),a=this.getPerformanceSnapshot(e.targetDomain),s=this.computeSqrtDampening(e),c=this.doTransfer(e.sourceDomain,e.targetDomain,s),u=this.getPerformanceSnapshot(e.sourceDomain),m=this.getPerformanceSnapshot(e.targetDomain),i=this.verifier.verifyTransfer({transferId:t,sourceDomain:e.sourceDomain,targetDomain:e.targetDomain,sourcePerformanceBefore:n,sourcePerformanceAfter:u,targetPerformanceBefore:a,targetPerformanceAfter:m}),f=c&&i.passed;if(this.sampler.update(e.pairKey,f),this.updateAffinityScore(e.pairKey,f),this.isMetaLearningEnabled()){this.plateauDetector.record(f),this.curiosityBonus.markTried(e.pairKey);let F=this.sampler.getMean(e.pairKey);this.paretoFront.add({pairKey:e.pairKey,successRate:F,speed:1/(1+s),confidence:this.getAffinityScore(e.sourceDomain,e.targetDomain)})}return this.addToHistory({transferId:t,sourceDomain:e.sourceDomain,targetDomain:e.targetDomain,success:f,sampledProbability:e.sampledProbability,dampeningFactor:s,sourceDelta:i.sourceDelta,targetDelta:i.targetDelta,timestamp:Date.now()}),w.info("Transfer completed",{transferId:t,source:e.sourceDomain,target:e.targetDomain,success:f,dampeningFactor:s.toFixed(4),sourceDelta:i.sourceDelta.toFixed(4),targetDelta:i.targetDelta.toFixed(4)}),{transferId:t,candidate:e,success:f,dampeningFactor:s,verification:i,coherenceResult:r,sourcePerformanceBefore:n,sourcePerformanceAfter:u,targetPerformanceBefore:a,targetPerformanceAfter:m,timestamp:Date.now()}}getAffinityScore(e,t){return this.affinityScores.get(this.makePairKey(e,t))??.5}getTransferHistory(){return[...this.transferHistory]}getExpectedSuccessRate(e,t){return this.sampler.getMean(this.makePairKey(e,t))}getObservationCount(e,t){return this.sampler.getObservationCount(this.makePairKey(e,t))}setPerformanceProvider(e){this.performanceProvider=e}setTransferExecutor(e){this.transferExecutor=e}getSampler(){return this.sampler}getCoherenceGate(){return this.coherenceGate}getDecayingBeta(){return this.decayingBeta}getPlateauDetector(){return this.plateauDetector}getParetoFront(){return this.paretoFront}getCuriosityBonus(){return this.curiosityBonus}isLearningPlateaued(){return this.plateauDetector.isPlateaued()}isEnabled(){return l().useCrossDomainTransfer===!0}isMetaLearningEnabled(){return this.config.useMetaLearningEnhancements===!0&&l().useMetaLearningEnhancements!==!1}makePairKey(e,t){return`${e}->${t}`}computeSqrtDampening(e){let t=this.sampler.getObservationCount(e.pairKey);return Math.sqrt(t/(t+this.config.explorationWarmup))}doTransfer(e,t,r){return this.transferExecutor?this.transferExecutor(e,t,r):!0}getPerformanceSnapshot(e){return this.performanceProvider?this.performanceProvider(e):{domain:e,successRate:.5,avgConfidence:.5,patternCount:0,timestamp:Date.now()}}updateAffinityScore(e,t){let r=this.affinityScores.get(e)??.5;this.affinityScores.set(e,.2*(t?1:0)+.8*r)}addToHistory(e){for(this.transferHistory.push(e);this.transferHistory.length>this.config.maxHistorySize;)this.transferHistory.shift()}createBlockedResult(e,t,r){let n={domain:"",successRate:0,avgConfidence:0,patternCount:0,timestamp:Date.now()};return{transferId:e,candidate:t,success:!1,dampeningFactor:0,verification:{passed:!1,sourceStable:!1,targetImproved:!1,sourceDelta:0,targetDelta:0,sourceConfidenceDelta:0,targetConfidenceDelta:0,failureReason:`Coherence gate rejected: ${r.rejectionReason??"unknown"}`},coherenceResult:r,sourcePerformanceBefore:{...n,domain:t.sourceDomain},sourcePerformanceAfter:{...n,domain:t.sourceDomain},targetPerformanceBefore:{...n,domain:t.targetDomain},targetPerformanceAfter:{...n,domain:t.targetDomain},timestamp:Date.now()}}createRejectedCandidate(e,t){return{sourceDomain:e,targetDomain:t,sampledProbability:0,affinityScore:0,isExploration:!1,pairKey:this.makePairKey(e,t)}}tryLoadNativeModule(){this.nativeModule=null}};function J(o){return new P(o)}export{p as a,h as b,V as c,y as d,v as e,D as f,C as g,P as h,J as i};
@@ -0,0 +1,2 @@
1
+ if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.0");process.exit(0)}
2
+ import{a as f}from"./chunk-3JPRUND5.js";import{c as p}from"./chunk-4VUPRTVX.js";import{a as d,b as g}from"./chunk-62ADTHV7.js";import{a as l,d as b}from"./chunk-DRT3WKQW.js";f();g();b();var v={dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine",namespace:"coverage-hnsw",maxElements:1e5},S=p.create("coverage-analysis/hnsw-index"),u=class{constructor(e,t={}){this.memory=e;this.config={...v,...t},this.stats={vectorCount:0,searchOperations:0,insertOperations:0}}config;stats;searchLatencies=[];backendType="ruvector-gnn";adapter=null;initialized=!1;metadataStore=new Map;async initialize(){if(this.initialized)return;let e=this.config.metric==="cosine"?"cosine":"euclidean",t=`coverage-${this.config.namespace}`;d.close(t),this.adapter=d.create(t,{dimensions:this.config.dimensions,M:this.config.M,efConstruction:this.config.efConstruction,efSearch:this.config.efSearch,metric:e}),S.info(`HnswAdapter initialized: dimension=${this.config.dimensions}, metric=${this.config.metric}, M=${this.config.M} (unified backend via ADR-071)`),this.initialized=!0}isNativeAvailable(){return this.initialized&&this.adapter!==null}getBackendType(){return this.backendType}isRuvectorAvailable(){return this.initialized&&this.adapter!==null&&this.adapter.isRuvectorAvailable()}async insert(e,t,a){this.initialized||await this.initialize(),t=this.validateVector(t),this.adapter.addByStringId(e,t),a&&this.metadataStore.set(e,a),this.stats.insertOperations++,this.stats.vectorCount=this.adapter.size()}async search(e,t){this.initialized||await this.initialize(),e=this.validateVector(e);let a=performance.now(),n=[];this.adapter.size()>0&&(n=this.adapter.searchByArray(e,t).map(({id:i,score:o})=>({key:i,score:o,distance:1-o,metadata:this.metadataStore.get(i)})));let s=performance.now()-a;return this.recordSearchLatency(s),this.stats.searchOperations++,n}async batchInsert(e){this.initialized||await this.initialize();let t=100;for(let a=0;a<e.length;a+=t){let n=e.slice(a,a+t);await Promise.all(n.map(r=>this.insert(r.key,r.vector,r.metadata)))}}async delete(e){if(!this.adapter)return!1;let t=this.adapter.removeByStringId(e);if(t){this.metadataStore.delete(e);let a=this.buildKey(e);await this.memory.delete(a),this.stats.vectorCount=this.adapter.size()}return t}async getStats(){return{nativeHNSW:this.initialized&&this.adapter!==null,backendType:this.backendType,vectorCount:this.stats.vectorCount,indexSizeBytes:this.stats.vectorCount*this.config.dimensions*4,avgSearchLatencyMs:this.calculateAvgLatency(),p95SearchLatencyMs:this.calculatePercentileLatency(95),p99SearchLatencyMs:this.calculatePercentileLatency(99),searchOperations:this.stats.searchOperations,insertOperations:this.stats.insertOperations}}async clear(){this.metadataStore.clear(),this.adapter&&this.adapter.clear(),this.stats.vectorCount=0,this.searchLatencies=[]}validateVector(e){if(e.length!==this.config.dimensions)return this.resizeVector(e,this.config.dimensions);for(let t=0;t<e.length;t++)if(!Number.isFinite(e[t]))throw new Error(`Invalid vector value at index ${t}: ${e[t]}`);return e}resizeVector(e,t){if(e.length===t)return e;if(e.length>t){let n=new Array(t).fill(0),r=e.length/t;for(let s=0;s<t;s++){let h=Math.floor(s*r),i=Math.floor((s+1)*r),o=0;for(let m=h;m<i;m++)o+=e[m];n[s]=o/(i-h)}return n}let a=new Array(t).fill(0);for(let n=0;n<e.length;n++)a[n]=e[n];return a}buildKey(e){return`${this.config.namespace}:${e}`}recordSearchLatency(e){this.searchLatencies.push(e);let t=1e3;this.searchLatencies.length>t&&(this.searchLatencies=this.searchLatencies.slice(-t))}calculateAvgLatency(){return this.searchLatencies.length===0?0:this.searchLatencies.reduce((t,a)=>t+a,0)/this.searchLatencies.length}calculatePercentileLatency(e){if(this.searchLatencies.length===0)return 0;let t=[...this.searchLatencies].sort((n,r)=>n-r),a=Math.ceil(e/100*t.length)-1;return t[Math.max(0,a)]}setEfSearch(e){this.config.efSearch=e}};function C(c,e){return new u(c,e)}async function H(c,e=1e4,t=1e3){let n=performance.now();for(let i=0;i<e;i++){let o=Array.from({length:384},()=>l());await c.insert(`bench-${i}`,o)}let r=performance.now()-n,s=performance.now();for(let i=0;i<t;i++){let o=Array.from({length:384},()=>l());await c.search(o,10)}let h=performance.now()-s;return{insertTimeMs:r,searchTimeMs:h,avgSearchLatencyMs:h/t,isNative:c.isNativeAvailable(),backendType:c.getBackendType()}}export{v as a,u as b,C as c,H as d};
@@ -0,0 +1,7 @@
1
+ if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.0");process.exit(0)}
2
+ import{a as z}from"./chunk-X5IJGWYG.js";import{a as A}from"./chunk-4YS3IJ45.js";import{k as _,n as B,o as U}from"./chunk-JJO7Y4H3.js";import{d as P,e as K}from"./chunk-4VUPRTVX.js";import{b as w,d as Q}from"./chunk-WGMPEW2T.js";import{a as g,c as R}from"./chunk-JZSDOIXA.js";import{g as N}from"./chunk-4I2IOUS4.js";U();R();Q();K();import{randomUUID as D}from"crypto";var I=P("TokenTracker"),O={costPerInputToken:.003/1e3,costPerOutputToken:.015/1e3},j={filePath:".agentic-qe/token-metrics.json",autoSaveIntervalMs:6e4,maxMetricsInMemory:1e4},S=class c{taskMetrics=[];agentMetrics=new Map;domainMetrics=new Map;sessionId;sessionStartTime;costConfig;cacheHits=0;earlyExits=0;totalTokensSaved=0;totalPatternsReused=0;initialized=!1;persistenceConfig=j;autoSaveTimer=null;isDirty=!1;db=null;kvPersistCount=0;static KV_NAMESPACE="token-usage-metrics";static KV_KEY="token-tracker-snapshot";static KV_TTL=604800;static KV_PERSIST_INTERVAL=10;constructor(){this.sessionId=`session-${Date.now()}-${D().substring(0,8)}`,this.sessionStartTime=Date.now(),this.costConfig=O}initialize(e){this.initialized||(this.initialized=!0,e&&(this.costConfig={...O,...e}),this.initializeDb().catch(t=>{I.warn("DB initialization failed",{error:t instanceof Error?t.message:String(t)})}),this.startAutoSave())}setCostConfig(e){this.costConfig={...this.costConfig,...e}}recordTokenUsage(e,t,i,n,s,o){this.ensureInitialized();let l,u,r,a,m,d;typeof t=="object"?(l="default",u="unknown",r="unknown",a=t,m=!1,d=0):(l=t,u=i??"unknown",r=n??"unknown",a=s,m=o?.patternReused??!1,d=o?.tokensSaved??0),a.estimatedCostUsd===void 0&&(a.estimatedCostUsd=this.calculateCost(a));let h={taskId:e,agentId:l,domain:u,operation:r,timestamp:Date.now(),usage:a,patternReused:m,tokensSaved:d};this.taskMetrics.push(h),this.updateAgentMetrics(l,a,m,d),this.updateDomainMetrics(u,a),m&&this.totalPatternsReused++,d>0&&(this.totalTokensSaved+=d),this.isDirty=!0,this.maybePersistToKv()}recordPatternReuse(e,t){this.ensureInitialized(),this.totalPatternsReused++,this.totalTokensSaved+=t;let i={taskId:e,agentId:"pattern-cache",domain:"optimization",operation:"pattern-reuse",timestamp:Date.now(),usage:{inputTokens:0,outputTokens:0,totalTokens:0,estimatedCostUsd:0},patternReused:!0,tokensSaved:t};this.taskMetrics.push(i),this.isDirty=!0}recordCacheHit(e){this.cacheHits++,this.totalTokensSaved+=e,this.isDirty=!0}recordEarlyExit(e){this.earlyExits++,this.totalTokensSaved+=e,this.isDirty=!0}getSessionSummary(e){this.ensureInitialized();let t=this.filterByTimeframe(this.taskMetrics,e),i=this.aggregateTokenUsage(t),n=new Map;for(let r of t){let a=n.get(r.agentId);a?(a.totalInputTokens+=r.usage.inputTokens,a.totalOutputTokens+=r.usage.outputTokens,a.totalTokens+=r.usage.totalTokens,a.totalCost+=r.usage.estimatedCostUsd||0,a.tasksExecuted++,r.patternReused&&a.patternsReused++,a.estimatedTokensSaved+=r.tokensSaved||0):n.set(r.agentId,{agentId:r.agentId,totalInputTokens:r.usage.inputTokens,totalOutputTokens:r.usage.outputTokens,totalTokens:r.usage.totalTokens,totalCost:r.usage.estimatedCostUsd||0,tasksExecuted:1,patternsReused:r.patternReused?1:0,estimatedTokensSaved:r.tokensSaved||0})}let s=new Map;for(let r of t){let a=s.get(r.domain);a?(a.inputTokens+=r.usage.inputTokens,a.outputTokens+=r.usage.outputTokens,a.totalTokens+=r.usage.totalTokens,a.estimatedCostUsd=(a.estimatedCostUsd||0)+(r.usage.estimatedCostUsd||0)):s.set(r.domain,{...r.usage})}let o=i.totalTokens,l=this.totalTokensSaved,u=o+l>0?l/(o+l)*100:0;return{sessionId:this.sessionId,startTime:this.sessionStartTime,endTime:Date.now(),byAgent:n,byDomain:s,totalUsage:i,optimizationStats:{patternsReused:this.totalPatternsReused,cacheHits:this.cacheHits,earlyExits:this.earlyExits,tokensSaved:this.totalTokensSaved,savingsPercentage:Math.round(u*100)/100}}}getAgentMetrics(e,t){this.ensureInitialized();let i=this.filterByTimeframe(this.taskMetrics,t);if(e){let s=i.filter(o=>o.agentId===e);return this.aggregateAgentMetrics(e,s)}let n=new Map;for(let s of i){let o=n.get(s.agentId)||[];o.push(s),n.set(s.agentId,o)}return Array.from(n.entries()).map(([s,o])=>this.aggregateAgentMetrics(s,o))}getDomainMetrics(e,t){this.ensureInitialized();let i=this.filterByTimeframe(this.taskMetrics,t);if(e){let s=i.filter(o=>o.domain===e);return this.aggregateTokenUsage(s)}let n=new Map;for(let s of i){let o=n.get(s.domain);o?(o.inputTokens+=s.usage.inputTokens,o.outputTokens+=s.usage.outputTokens,o.totalTokens+=s.usage.totalTokens,o.estimatedCostUsd=(o.estimatedCostUsd||0)+(s.usage.estimatedCostUsd||0)):n.set(s.domain,{...s.usage})}return n}getTaskMetrics(e){return this.ensureInitialized(),this.filterByTimeframe(this.taskMetrics,e)}getEfficiencyReport(e){return this.getTokenEfficiency(e)}getTokenEfficiency(e){this.ensureInitialized();let t=this.filterByTimeframe(this.taskMetrics,e),n=this.aggregateTokenUsage(t).totalTokens,s=this.totalTokensSaved,o=n+s>0?s/(n+s)*100:0,l=t.length,u=l>0?t.filter(m=>m.patternReused).length/l:0,r=l>0?n/l:0,a=this.generateRecommendations(t);return{totalTokensUsed:n,totalTokensSaved:s,savingsPercentage:Math.round(o*100)/100,patternReuseRate:Math.round(u*100)/100,averageTokensPerTask:Math.round(r),recommendations:a}}reset(){this.stopAutoSave(),this.taskMetrics=[],this.agentMetrics.clear(),this.domainMetrics.clear(),this.sessionId=`session-${Date.now()}-${D().substring(0,8)}`,this.sessionStartTime=Date.now(),this.cacheHits=0,this.earlyExits=0,this.totalTokensSaved=0,this.totalPatternsReused=0,this.isDirty=!1}configurePersistence(e){this.persistenceConfig={...this.persistenceConfig,...e},e.autoSaveIntervalMs!==void 0&&(this.stopAutoSave(),e.autoSaveIntervalMs>0&&this.startAutoSave())}startAutoSave(){this.autoSaveTimer||this.persistenceConfig.autoSaveIntervalMs>0&&(this.autoSaveTimer=setInterval(()=>{this.isDirty&&this.save().catch(e=>{console.warn("[TokenMetricsCollector] Auto-save failed:",e)})},this.persistenceConfig.autoSaveIntervalMs))}stopAutoSave(){this.autoSaveTimer&&(clearInterval(this.autoSaveTimer),this.autoSaveTimer=null)}async save(){let e=await import("fs"),t=await import("path"),i={version:"1.0.0",sessionId:this.sessionId,sessionStartTime:this.sessionStartTime,taskMetrics:this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory),optimizationStats:{cacheHits:this.cacheHits,earlyExits:this.earlyExits,totalTokensSaved:this.totalTokensSaved,totalPatternsReused:this.totalPatternsReused},lastSavedAt:Date.now()},n=t.resolve(this.persistenceConfig.filePath),s=t.dirname(n);e.existsSync(s)||e.mkdirSync(s,{recursive:!0}),e.writeFileSync(n,JSON.stringify(i,null,2)),this.isDirty=!1}async load(){let e=await import("fs"),i=(await import("path")).resolve(this.persistenceConfig.filePath);if(!e.existsSync(i))return!1;try{let n=e.readFileSync(i,"utf-8"),s=w(n);if(!s.version||!s.version.startsWith("1."))return console.warn("[TokenMetricsCollector] Incompatible data version, skipping load"),!1;let o=s.taskMetrics||[];this.taskMetrics=[...o,...this.taskMetrics],this.cacheHits+=s.optimizationStats?.cacheHits||0,this.earlyExits+=s.optimizationStats?.earlyExits||0,this.totalTokensSaved+=s.optimizationStats?.totalTokensSaved||0,this.totalPatternsReused+=s.optimizationStats?.totalPatternsReused||0;for(let l of o)this.updateAgentMetrics(l.agentId,l.usage,l.patternReused,l.tokensSaved||0),this.updateDomainMetrics(l.domain,l.usage);return this.taskMetrics.length>this.persistenceConfig.maxMetricsInMemory&&(this.taskMetrics=this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory)),!0}catch(n){return console.warn("[TokenMetricsCollector] Failed to load persisted data:",n),!1}}getPersistenceFilePath(){return this.persistenceConfig.filePath}hasUnsavedChanges(){return this.isDirty}async initializeDb(){try{this.db=_(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(e){console.warn("[TokenMetricsCollector] DB init failed, using memory-only:",g(e)),this.db=null}}async persistToKv(){if(!this.db)return;let e={version:"1.0.0",sessionId:this.sessionId,sessionStartTime:this.sessionStartTime,taskMetrics:this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory),optimizationStats:{cacheHits:this.cacheHits,earlyExits:this.earlyExits,totalTokensSaved:this.totalTokensSaved,totalPatternsReused:this.totalPatternsReused},lastSavedAt:Date.now()};await this.db.kvSet(c.KV_KEY,e,c.KV_NAMESPACE,c.KV_TTL)}async loadFromKv(){if(!this.db)return!1;let e=await this.db.kvGet(c.KV_KEY,c.KV_NAMESPACE);if(!e)return!1;if(!e.version||!e.version.startsWith("1."))return console.warn("[TokenMetricsCollector] Incompatible kv_store data version, skipping load"),!1;let t=e.taskMetrics||[];this.taskMetrics=[...t,...this.taskMetrics],this.cacheHits+=e.optimizationStats?.cacheHits||0,this.earlyExits+=e.optimizationStats?.earlyExits||0,this.totalTokensSaved+=e.optimizationStats?.totalTokensSaved||0,this.totalPatternsReused+=e.optimizationStats?.totalPatternsReused||0;for(let i of t)this.updateAgentMetrics(i.agentId,i.usage,i.patternReused,i.tokensSaved||0),this.updateDomainMetrics(i.domain,i.usage);return this.taskMetrics.length>this.persistenceConfig.maxMetricsInMemory&&(this.taskMetrics=this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory)),!0}maybePersistToKv(){this.kvPersistCount++,this.kvPersistCount>=c.KV_PERSIST_INTERVAL&&(this.kvPersistCount=0,this.persistToKv().catch(e=>{I.warn("KV persist failed",{error:e instanceof Error?e.message:String(e)})}))}ensureInitialized(){this.initialized||this.initialize()}calculateCost(e){let t=e.inputTokens*this.costConfig.costPerInputToken,i=e.outputTokens*this.costConfig.costPerOutputToken;return Math.round((t+i)*1e5)/1e5}filterByTimeframe(e,t){if(!t)return e;let i=Date.now(),n;switch(t){case"1h":n=i-3600*1e3;break;case"24h":n=i-1440*60*1e3;break;case"7d":n=i-10080*60*1e3;break;case"30d":n=i-720*60*60*1e3;break;default:return e}return e.filter(s=>s.timestamp>=n)}aggregateTokenUsage(e){let t=0,i=0,n=0,s=0;for(let o of e)t+=o.usage.inputTokens,i+=o.usage.outputTokens,n+=o.usage.totalTokens,s+=o.usage.estimatedCostUsd||0;return{inputTokens:t,outputTokens:i,totalTokens:n,estimatedCostUsd:Math.round(s*1e5)/1e5}}aggregateAgentMetrics(e,t){let i=0,n=0,s=0,o=0,l=0,u=0;for(let r of t)i+=r.usage.inputTokens,n+=r.usage.outputTokens,s+=r.usage.totalTokens,o+=r.usage.estimatedCostUsd||0,r.patternReused&&l++,u+=r.tokensSaved||0;return{agentId:e,totalInputTokens:i,totalOutputTokens:n,totalTokens:s,totalCost:Math.round(o*1e5)/1e5,tasksExecuted:t.length,patternsReused:l,estimatedTokensSaved:u}}updateAgentMetrics(e,t,i,n){let s=this.agentMetrics.get(e);s?(s.totalInputTokens+=t.inputTokens,s.totalOutputTokens+=t.outputTokens,s.totalTokens+=t.totalTokens,s.totalCost+=t.estimatedCostUsd||0,s.tasksExecuted++,i&&s.patternsReused++,s.estimatedTokensSaved+=n):this.agentMetrics.set(e,{agentId:e,totalInputTokens:t.inputTokens,totalOutputTokens:t.outputTokens,totalTokens:t.totalTokens,totalCost:t.estimatedCostUsd||0,tasksExecuted:1,patternsReused:i?1:0,estimatedTokensSaved:n})}updateDomainMetrics(e,t){let i=this.domainMetrics.get(e);i?(i.inputTokens+=t.inputTokens,i.outputTokens+=t.outputTokens,i.totalTokens+=t.totalTokens,i.estimatedCostUsd=(i.estimatedCostUsd||0)+(t.estimatedCostUsd||0)):this.domainMetrics.set(e,{...t})}generateRecommendations(e){let t=[];if(e.length===0)return["No token usage data available yet. Start executing tasks to track consumption."];let i=e.filter(r=>r.patternReused).length/e.length;i<.2?t.push("Low pattern reuse rate detected. Consider enabling pattern caching for similar tasks."):i>.5&&t.push("Good pattern reuse rate. Continue leveraging cached patterns for token savings.");let n=new Map;for(let r of e){let a=n.get(r.domain)||0;n.set(r.domain,a+r.usage.totalTokens)}let s=Array.from(n.entries()).sort((r,a)=>a[1]-r[1]);if(s.length>0){let r=s[0];t.push(`Highest token consumer: ${r[0]} (${r[1].toLocaleString()} tokens). Consider optimizing prompts or increasing caching.`)}let o=e.reduce((r,a)=>r+a.usage.inputTokens,0);return e.reduce((r,a)=>r+a.usage.outputTokens,0)/(o||1)>2&&t.push("High output-to-input token ratio. Consider requesting more concise responses."),this.cacheHits===0&&e.length>10&&t.push("No cache hits detected. Enable response caching to reduce duplicate API calls."),this.earlyExits===0&&e.length>20&&t.push("Early exit optimization not utilized. Enable high-confidence pattern matching to skip unnecessary LLM calls."),t}};function F(c){return c.toLocaleString("en-US")}function $(c){if(process.env.AQE_TOKEN_DASHBOARD_ENABLED==="false")return"Token dashboard disabled (AQE_TOKEN_DASHBOARD_ENABLED=false)";if(!c){let u=p.getSessionSummary(),r=u.totalUsage.totalTokens,a=u.totalUsage.estimatedCostUsd??0,m=u.optimizationStats.tokensSaved,d=r>0?a/r:0,h=m*d;c={totalTokens:r,totalCostUsd:a,savedTokens:m,savedCostUsd:h}}let e=c.totalTokens??0,t=c.totalCostUsd??0,i=c.savedTokens??0,n=c.savedCostUsd??0,s=c.budgetLimitUsd;if(e===0&&i===0)return"Token Dashboard: No data available";let o=`Token Usage: ${F(e)} tokens ($${t.toFixed(2)})`;i>0&&(o+=` | Saved: ${F(i)} tokens ($${n.toFixed(2)}) via pattern reuse`);let l=[];if(s!==void 0&&s>0){let u=Math.round(t/s*100);l.push(`Budget: $${t.toFixed(2)} / $${s.toFixed(2)} (${u}%)`)}if(c.tierSplit&&Object.keys(c.tierSplit).length>0){let u=Object.entries(c.tierSplit).sort((r,a)=>a[1]-r[1]).map(([r,a])=>`${r} ${a}%`);l.push(`Tier split: ${u.join(" | ")}`)}return l.length===0?o:`${o}
3
+ ${l.join(" | ")}`}var p=new S;function te(c){return`$${c.toFixed(2)}`}import{createHash as V}from"crypto";var G={enabled:!0,maxEntries:500,ttlMs:3600*1e3,persistToDb:!0};function E(c){if(c==null||typeof c!="object")return JSON.stringify(c);if(Array.isArray(c))return"["+c.map(n=>E(n)).join(",")+"]";let e=c;return"{"+Object.keys(e).sort().map(n=>JSON.stringify(n)+":"+E(e[n])).join(",")+"}"}var b=class{cache=new Map;config;hits=0;misses=0;constructor(e){this.config={...G,...e}}computeFingerprint(e,t,i){let n=E({action:t,domain:e,input:i});return V("sha256").update(n).digest("hex").slice(0,16)}get(e){if(!this.config.enabled)return null;let t=this.cache.get(e);return t?Date.now()-t.cachedAt>this.config.ttlMs?(this.cache.delete(e),this.misses++,null):(t.hitCount++,t.lastHitAt=Date.now(),this.hits++,t):(this.misses++,null)}set(e,t,i,n,s){if(!this.config.enabled)return;this.cache.size>=this.config.maxEntries&&this.evictOldest();let o={fingerprint:e,domain:t,action:i,result:n,tokensSaved:s,cachedAt:Date.now(),hitCount:0,lastHitAt:0};this.cache.set(e,o),this.config.persistToDb&&this.persistEntry(o)}loadFromDb(){try{let e=H();if(!e)return;let t=Date.now()-this.config.ttlMs,i=e.prepare(`SELECT key, value FROM kv_store
4
+ WHERE namespace = 'session_cache'
5
+ AND created_at > ?
6
+ ORDER BY created_at DESC LIMIT ?`).all(t,this.config.maxEntries);for(let n of i)try{let s=JSON.parse(n.value);Date.now()-s.cachedAt<=this.config.ttlMs&&this.cache.set(s.fingerprint,s)}catch{}}catch{}}getStats(){let e=this.hits+this.misses,t=0;for(let i of this.cache.values())t+=i.tokensSaved*i.hitCount;return{size:this.cache.size,hits:this.hits,misses:this.misses,hitRate:e>0?this.hits/e:0,estimatedTokensSaved:t}}clear(){this.cache.clear(),this.hits=0,this.misses=0}evictOldest(){let e=null,t=1/0;for(let[i,n]of this.cache)n.cachedAt<t&&(t=n.cachedAt,e=i);e&&this.cache.delete(e)}persistEntry(e){try{let t=H();if(!t)return;t.prepare(`INSERT OR REPLACE INTO kv_store (key, namespace, value, created_at)
7
+ VALUES (?, 'session_cache', ?, ?)`).run(`session_cache:${e.fingerprint}`,JSON.stringify(e),Date.now())}catch{}}};function H(){try{let{getUnifiedMemory:c}=(U(),N(B)),e=c();return e.isInitialized()?e.getDatabase():null}catch{return null}}var f=null;function k(c){return f||(f=new b(c),f.loadFromDb()),f}import{randomUUID as q}from"crypto";R();var x={minConfidenceForExit:.85,minSuccessRate:.9,maxPatternAge:10080*60*1e3,minQualityScore:.7,minSuccessfulUses:2,maxSearchResults:5,similarityThreshold:.8,verbose:!1},ae={minConfidenceForExit:.75,minSuccessRate:.8,maxPatternAge:336*60*60*1e3,minQualityScore:.6,minSuccessfulUses:1,maxSearchResults:10,similarityThreshold:.7,verbose:!1},ce={minConfidenceForExit:.92,minSuccessRate:.95,maxPatternAge:4320*60*1e3,minQualityScore:.85,minSuccessfulUses:3,maxSearchResults:3,similarityThreshold:.9,verbose:!1},T=class{patternStore;config;reuseHistory=[];attemptHistory=[];constructor(e,t){this.patternStore=e,this.config={...x,...t}}async checkEarlyExit(e){let t=performance.now(),i=new Date;try{let n=e.domain??A(e.description)??void 0,s={limit:this.config.maxSearchResults*2,useVectorSearch:!!e.embedding};n&&(s.domain=n),e.context&&(s.context={language:e.context.language,framework:e.context.framework,testType:e.context.testType});let o=e.embedding??e.description,l=await this.patternStore.search(o,s),u=performance.now()-t;if(!l.success){let d="error"in l?l.error.message:"Unknown error",h=this.createResult(!1,"search_error",`Pattern search failed: ${d}`,u);return this.recordAttempt("search_error",n),h}let r=l.value;if(r.length===0){let d=this.createResult(!1,"no_matching_pattern","No matching patterns found in store",u);return this.recordAttempt("no_matching_pattern",n),d}let a=null;for(let{pattern:d,score:h}of r){let y=this.evaluatePatternEligibility(d,h,i);if(y.eligible){let v=this.estimateTokensSaved(d),L={canExit:!0,reusedPattern:d,estimatedTokensSaved:v,confidence:d.confidence,similarityScore:h,reason:"pattern_reused",explanation:`Reusing pattern "${d.name}" with ${(d.confidence*100).toFixed(1)}% confidence`,searchLatencyMs:u};return this.recordReuse(d.id,v,d.confidence,h,u,n),this.config.verbose&&console.log(`[EarlyExitTokenOptimizer] Pattern reuse: ${d.name} (confidence: ${d.confidence.toFixed(2)}, similarity: ${h.toFixed(2)}, tokens saved: ${v})`),L}a===null&&(a={reason:y.reason,explanation:y.explanation})}if(a){let d=this.createResult(!1,a.reason,a.explanation,u);return this.recordAttempt(a.reason,n),d}let m=this.createResult(!1,"no_matching_pattern",`Found ${r.length} patterns but none met eligibility criteria`,u);return this.recordAttempt("no_matching_pattern",n),m}catch(n){let s=performance.now()-t,o=this.createResult(!1,"search_error",`Error during pattern search: ${g(n)}`,s);return this.recordAttempt("search_error"),o}}evaluatePatternEligibility(e,t,i){if(t<this.config.similarityThreshold)return{eligible:!1,reason:"similarity_too_low",explanation:`Similarity ${(t*100).toFixed(1)}% < threshold ${(this.config.similarityThreshold*100).toFixed(1)}%`};if(e.confidence<this.config.minConfidenceForExit)return{eligible:!1,reason:"confidence_too_low",explanation:`Confidence ${(e.confidence*100).toFixed(1)}% < threshold ${(this.config.minConfidenceForExit*100).toFixed(1)}%`};if(e.successRate<this.config.minSuccessRate)return{eligible:!1,reason:"success_rate_too_low",explanation:`Success rate ${(e.successRate*100).toFixed(1)}% < threshold ${(this.config.minSuccessRate*100).toFixed(1)}%`};let n=i.getTime()-e.lastUsedAt.getTime();if(n>this.config.maxPatternAge){let s=Math.floor(n/864e5),o=Math.floor(this.config.maxPatternAge/(1440*60*1e3));return{eligible:!1,reason:"pattern_too_old",explanation:`Pattern age ${s} days > max ${o} days`}}return e.qualityScore<this.config.minQualityScore?{eligible:!1,reason:"quality_score_too_low",explanation:`Quality score ${(e.qualityScore*100).toFixed(1)}% < threshold ${(this.config.minQualityScore*100).toFixed(1)}%`}:e.successfulUses<this.config.minSuccessfulUses?{eligible:!1,reason:"insufficient_uses",explanation:`Successful uses ${e.successfulUses} < minimum ${this.config.minSuccessfulUses}`}:{eligible:!0,reason:"pattern_reused",explanation:"Pattern meets all eligibility criteria"}}estimateTokensSaved(e){let t=100,i=Math.ceil(e.template.content.length/4);t+=i,t+=50;let o={"test-template":1.5,"assertion-pattern":1,"mock-pattern":1.2,"coverage-strategy":1.3,"api-contract":1.4,"visual-baseline":1.1,"perf-benchmark":1.4,"flaky-fix":1.3,"error-handling":1.2}[e.patternType]??1;return Math.ceil(t*o)}createResult(e,t,i,n){return{canExit:e,reason:t,explanation:i,searchLatencyMs:n}}recordReuse(e,t,i,n,s,o){this.reuseHistory.push({patternId:e,tokensSaved:t,confidence:i,similarity:n,latencyMs:s,domain:o,timestamp:new Date}),this.attemptHistory.push({reason:"pattern_reused",domain:o,timestamp:new Date}),this.reuseHistory.length>1e4&&(this.reuseHistory=this.reuseHistory.slice(-1e4))}recordAttempt(e,t){this.attemptHistory.push({reason:e,domain:t,timestamp:new Date}),this.attemptHistory.length>1e4&&(this.attemptHistory=this.attemptHistory.slice(-1e4))}recordSuccessfulReuse(e){this.patternStore.recordUsage(e,!0).catch(t=>{console.warn(`[EarlyExitTokenOptimizer] Failed to record successful reuse for ${e}:`,t)})}recordFailedReuse(e){this.patternStore.recordUsage(e,!1).catch(t=>{console.warn(`[EarlyExitTokenOptimizer] Failed to record failed reuse for ${e}:`,t)})}getReuseStats(){let e=this.reuseHistory.length,t=this.attemptHistory.length,i=0,n=0,s=0,o=0;for(let r of this.reuseHistory)i+=r.tokensSaved,n+=r.confidence,s+=r.similarity,o+=r.latencyMs;let l={pattern_reused:0,no_matching_pattern:0,confidence_too_low:0,success_rate_too_low:0,pattern_too_old:0,quality_score_too_low:0,insufficient_uses:0,similarity_too_low:0,search_error:0};for(let r of this.attemptHistory)l[r.reason]++;let u={};for(let r of this.reuseHistory){let a=r.domain??"unknown";u[a]||(u[a]={reuses:0,tokens:0}),u[a].reuses++,u[a].tokens+=r.tokensSaved}return{totalReuses:e,tokensSaved:i,avgConfidence:e>0?n/e:0,avgSimilarity:e>0?s/e:0,avgSearchLatencyMs:e>0?o/e:0,totalAttempts:t,exitRate:t>0?e/t:0,reasonBreakdown:l,domainBreakdown:u}}resetStats(){this.reuseHistory=[],this.attemptHistory=[]}getConfig(){return{...this.config}}updateConfig(e){Object.assign(this.config,e)}};var C={enabled:!0,earlyExit:x,verbose:!1},M=class{optimizer=null;patternStore=null;config=C;initialized=!1;async initialize(e,t){if(!this.initialized){if(this.config={...C,...t},!this.config.enabled){this.config.verbose&&console.log("[TokenOptimizerService] Service disabled by configuration");return}try{this.patternStore=z(e),await this.patternStore.initialize(),this.optimizer=new T(this.patternStore,this.config.earlyExit),this.initialized=!0,this.config.verbose&&console.log("[TokenOptimizerService] Initialized with EarlyExitTokenOptimizer")}catch(i){console.warn("[TokenOptimizerService] Failed to initialize:",i)}}}async checkEarlyExit(e){if(!this.initialized||!this.optimizer)return{canExit:!1,reason:"no_matching_pattern",explanation:"Token optimizer service not initialized",searchLatencyMs:0};try{let i=k(),n=i.computeFingerprint(e.domain??"unknown",e.description,e.context??{}),s=i.get(n);if(s)return p.recordEarlyExit(s.tokensSaved),this.config.verbose&&console.log(`[TokenOptimizerService] Session cache hit: ${n.slice(0,8)}... (saved ${s.tokensSaved} tokens)`),{canExit:!0,estimatedTokensSaved:s.tokensSaved,confidence:1,similarityScore:1,reason:"pattern_reused",explanation:`Session cache exact match (fingerprint: ${n.slice(0,8)}...)`,searchLatencyMs:0}}catch{}let t=await this.optimizer.checkEarlyExit(e);return t.canExit&&t.estimatedTokensSaved&&(p.recordEarlyExit(t.estimatedTokensSaved),this.config.verbose&&console.log(`[TokenOptimizerService] Early exit: ${t.reusedPattern?.name} (saved ${t.estimatedTokensSaved} tokens)`)),t}async checkTaskEarlyExit(e,t){return this.checkEarlyExit({description:e,domain:t})}recordSuccessfulReuse(e){this.optimizer&&this.optimizer.recordSuccessfulReuse(e)}recordFailedReuse(e){this.optimizer&&this.optimizer.recordFailedReuse(e)}async storePattern(e){if(!this.patternStore)return null;try{let t=await this.patternStore.store({...e,id:`pattern-${Date.now()}-${q().slice(0,8)}`,createdAt:new Date,lastUsedAt:new Date});return t.success?t.value:null}catch(t){return console.warn("[TokenOptimizerService] Failed to store pattern:",t),null}}getReuseStats(){return this.optimizer?this.optimizer.getReuseStats():null}isEnabled(){return this.initialized&&this.config.enabled}getConfig(){return{...this.config}}getDashboardSummary(){return $()}cacheOperationResult(e,t,i,n,s){try{let o=k(),l=o.computeFingerprint(e,t,i);o.set(l,e,t,n,s)}catch{}}getSessionCacheStats(){try{return k().getStats()}catch{return{size:0,hits:0,misses:0,hitRate:0,estimatedTokensSaved:0}}}reset(){this.optimizer&&this.optimizer.resetStats(),this.optimizer=null,this.patternStore=null,this.initialized=!1,this.config=C}},J=new M;async function ve(c,e){await J.initialize(c,e)}export{$ as a,p as b,te as c,k as d,J as e,ve as f};
@@ -0,0 +1,2 @@
1
+ if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.0");process.exit(0)}
2
+ import{c as x,e as M,g as T}from"./chunk-4I2IOUS4.js";var v={};M(v,{DotProductAttention:()=>z,FlashAttention:()=>k,HyperbolicAttention:()=>W,LinearAttention:()=>j,MoEAttention:()=>K,MultiHeadAttention:()=>F,RuvectorLayer:()=>_,SonaEngine:()=>q,TensorCompress:()=>E,default:()=>O,differentiableSearch:()=>L,getCompressionLevel:()=>B,hierarchicalForward:()=>V,init:()=>D,pipeline:()=>J});import{createRequire as A}from"module";var I,b,O,_,E,L,V,B,D,k,z,F,W,j,K,q,J,g=x(()=>{I=A(import.meta.url),b=I("@ruvector/rvf-node"),O=b,{RuvectorLayer:_,TensorCompress:E,differentiableSearch:L,hierarchicalForward:V,getCompressionLevel:B,init:D,FlashAttention:k,DotProductAttention:z,MultiHeadAttention:F,HyperbolicAttention:W,LinearAttention:j,MoEAttention:K,SonaEngine:q,pipeline:J}=b||{}});import{readFileSync as C,writeFileSync as H,copyFileSync as $,existsSync as G}from"fs";var f=null,y=!1;function l(){if(y)return f;y=!0;try{let i=(g(),T(v));!i.RvfDatabase&&i.default&&i.default.RvfDatabase&&(i=i.default),f=i}catch{f=null}return f}function S(i){return`${i}.idmap.json`}function R(i){let e=S(i),t=new Map,n=new Map,s=1;if(G(e))try{let r=JSON.parse(C(e,"utf-8"));s=r.nextLabel;for(let[a,m]of r.entries)t.set(a,m),n.set(m,a)}catch{}return{strToNum:t,numToStr:n,nextLabel:s}}function h(i,e,t){let n={nextLabel:t,entries:Array.from(e.entries())};H(S(i),JSON.stringify(n),"utf-8")}var d=class i{db;_path;_dimension;strToNum;numToStr;nextLabel;_open;constructor(e,t,n,s,r,a){this.db=e,this._path=t,this._dimension=n,this.strToNum=s,this.numToStr=r,this.nextLabel=a,this._open=!0}ingest(e){if(this.ensureOpen(),e.length===0)return{accepted:0,rejected:0};let t=this._dimension,n=new Float32Array(e.length*t),s=[],r=[];for(let o=0;o<e.length;o++){let{id:u,vector:p,metadata:w}=e[o],c=this.strToNum.get(u);c===void 0&&(c=this.nextLabel++,this.strToNum.set(u,c),this.numToStr.set(c,u)),s.push(c),r.push(w);let N=p instanceof Float32Array?p:new Float32Array(p);n.set(N.subarray(0,t),o*t)}let a;if(r.some(o=>o!==void 0)&&typeof this.db.ingestBatchWithMetadata=="function"){let o=r.map(u=>u?JSON.stringify(u):"");a=this.db.ingestBatchWithMetadata(n,s,o)}else a=this.db.ingestBatch(n,s);return this.persistIdMap(),{accepted:a.accepted,rejected:a.rejected}}search(e,t){this.ensureOpen();let n=e instanceof Float32Array?e:new Float32Array(e);return this.db.query(n,t).map(r=>{let a=this.numToStr.get(r.id);return a===void 0?null:{id:a,distance:r.distance,score:1/(1+r.distance)}}).filter(r=>r!==null)}delete(e){this.ensureOpen();let t=[];for(let s of e){let r=this.strToNum.get(s);r!==void 0&&t.push(r)}if(t.length===0)return 0;let n=this.db.delete(t);for(let s of e){let r=this.strToNum.get(s);r!==void 0&&(this.strToNum.delete(s),this.numToStr.delete(r))}return this.persistIdMap(),n.deleted}fork(e){this.ensureOpen(),$(this._path,e);let t=new Map(this.strToNum),n=new Map(this.numToStr);h(e,t,this.nextLabel);let r=l().RvfDatabase.open(e);return new i(r,e,this._dimension,t,n,this.nextLabel)}status(){this.ensureOpen();let e=this.db.status(),n=this.db.segments().filter(s=>s.segType==="witness");return{totalVectors:e.totalVectors,totalSegments:e.totalSegments,fileSizeBytes:e.fileSize,epoch:e.currentEpoch,witnessValid:n.length>0,witnessEntries:n.length}}dimension(){return this._dimension}size(){return this.ensureOpen(),this.db.status().totalVectors}compact(){this.ensureOpen(),this.db.compact()}close(){this._open&&(this.db.close(),this._open=!1)}isOpen(){return this._open}path(){return this._path}embedKernel(e){return this.ensureOpen(),this.db.embedKernel(0,99,0,e,0,"")}extractKernel(){return this.ensureOpen(),this.db.extractKernel()}verifyWitness(){this.ensureOpen();let e=this.tryNative("verifyWitness");return e?{valid:e.valid??!0,totalEntries:e.totalEntries??0,errors:Array.isArray(e.errors)?e.errors:[]}:{valid:!0,totalEntries:0,errors:[]}}sign(e){this.ensureOpen();let t=this.tryNative("sign",e);return typeof t=="string"?t:null}fileId(){this.ensureOpen();let e=this.tryNative("fileId");return typeof e=="string"?e:null}parentId(){this.ensureOpen();let e=this.tryNative("parentId");return typeof e=="string"?e:null}lineageDepth(){this.ensureOpen();let e=this.tryNative("lineageDepth");return typeof e=="number"?e:0}indexStats(){let e=this.status();return{totalVectors:e.totalVectors,dimension:this._dimension,totalSegments:e.totalSegments,fileSizeBytes:e.fileSizeBytes,epoch:e.epoch,witnessValid:e.witnessValid,witnessEntries:e.witnessEntries,idMapSize:this.strToNum.size}}freeze(){this.ensureOpen();let e=this.tryNative("freeze");return typeof e=="number"?e:0}derive(e){this.ensureOpen();let t=l();if(typeof this.db.derive=="function")try{let n=this.db.derive(e),s=new Map(this.strToNum),r=new Map(this.numToStr);return h(e,s,this.nextLabel),new i(n,e,this._dimension,s,r,this.nextLabel)}catch{}return this.fork(e)}ensureOpen(){if(!this._open)throw new Error("RVF database is closed")}tryNative(e,...t){if(typeof this.db[e]!="function")return null;try{return this.db[e](...t)}catch{return null}}persistIdMap(){h(this._path,this.strToNum,this.nextLabel)}};function X(i,e){let t=l();if(!t)throw new Error("@ruvector/rvf-node is not available \u2014 install the package or check platform compatibility");let n=t.RvfDatabase.create(i,{dimension:e}),s=n.dimension();return new d(n,i,s,new Map,new Map,1)}function Y(i){let e=l();if(!e)throw new Error("@ruvector/rvf-node is not available \u2014 install the package or check platform compatibility");let t=e.RvfDatabase.open(i),n=t.dimension(),{strToNum:s,numToStr:r,nextLabel:a}=R(i);return new d(t,i,n,s,r,a)}function Z(i){let e=l();if(!e)throw new Error("@ruvector/rvf-node is not available \u2014 install the package or check platform compatibility");let t=e.RvfDatabase.openReadonly(i),n=t.dimension(),{strToNum:s,numToStr:r,nextLabel:a}=R(i);return new d(t,i,n,s,r,a)}function P(){return l()!==null}export{X as a,Y as b,Z as c,P as d};
@@ -0,0 +1,2 @@
1
+ if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.0");process.exit(0)}
2
+ import{a as T,b as E}from"./chunk-62ADTHV7.js";import{a as N,d as P}from"./chunk-DRT3WKQW.js";import{a as H,b as O}from"./chunk-UFUVUO3J.js";import{b,e as k}from"./chunk-7VDBAVTY.js";import{a as p,d as F}from"./chunk-B36CDR4U.js";import{c as z,g as S}from"./chunk-4I2IOUS4.js";function x(l){let e=0;for(let t=0;t<l.length;t++)e+=l[t]*l[t];return Math.sqrt(e)}function C(l,e,t,s){let n=t*s;if(n===0)return 0;let o=0;for(let r=0;r<l.length;r++)o+=l[r]*e[r];return o/n}function U(l={}){let{name:e="default",...t}=l;return new M(e,t)}var f,w,v,I,A,M,D=z(()=>{F();P();k();E();f=null,w=null;try{let l=(O(),S(H));f=l.differentiableSearch,w=l.init}catch{}v=class{data=[];compareFn;constructor(e){this.compareFn=e}push(e){this.data.push(e),this.bubbleUp(this.data.length-1)}pop(){if(this.data.length===0)return;let e=this.data[0],t=this.data.pop();return this.data.length>0&&(this.data[0]=t,this.sinkDown(0)),e}peek(){return this.data[0]}size(){return this.data.length}bubbleUp(e){for(;e>0;){let t=e-1>>1;if(this.compareFn(this.data[e],this.data[t])<0)[this.data[e],this.data[t]]=[this.data[t],this.data[e]],e=t;else break}}sinkDown(e){let t=this.data.length;for(;;){let s=e,n=2*e+1,o=2*e+2;if(n<t&&this.compareFn(this.data[n],this.data[s])<0&&(s=n),o<t&&this.compareFn(this.data[o],this.data[s])<0&&(s=o),s!==e)[this.data[e],this.data[s]]=[this.data[s],this.data[e]],e=s;else break}}},I=class{nodes=new Map;M=b.M_CONNECTIONS;Mmax0=b.M_CONNECTIONS*2;efConstruction=b.EF_CONSTRUCTION;efSearch=b.EF_SEARCH;mL=1/Math.log(b.M_CONNECTIONS);maxLevel=16;entryPoint=null;currentMaxLevel=-1;randomLevel(){return Math.min(Math.floor(-Math.log(N())*this.mL),this.maxLevel)}similarity(e,t){let s=this.nodes.get(t);return s?p(e,s.embedding):-1}searchLayer(e,t,s){let n=t,o=this.similarity(e,n),r=!0;for(;r;){r=!1;let a=this.nodes.get(n);if(!a)break;let h=a.neighbors.get(s)??[];for(let d of h){if(!this.nodes.has(d))continue;let i=this.similarity(e,d);i>o&&(n=d,o=i,r=!0)}}return n}searchLayerBeam(e,t,s,n){let o=new Set(t),r=t.filter(i=>this.nodes.has(i)).map(i=>({id:i,score:this.similarity(e,i)})),a=new v((i,c)=>c.score-i.score),h=new v((i,c)=>i.score-c.score);for(let i of r)a.push(i),h.push(i);for(;a.size()>0;){let i=a.pop();if(h.size()>=n&&i.score<h.peek().score)break;let c=this.nodes.get(i.id);if(!c)continue;let u=c.neighbors.get(s)??[];for(let m of u){if(o.has(m)||(o.add(m),!this.nodes.has(m)))continue;let g=this.similarity(e,m),y=h.size()>=n?h.peek().score:-1/0;if(h.size()<n||g>y){let L={id:m,score:g};a.push(L),h.push(L),h.size()>n&&h.pop()}}}let d=[];for(;h.size()>0;)d.push(h.pop());return d.reverse(),d}selectNeighbors(e,t,s){return t.sort((n,o)=>o.score-n.score).slice(0,s).map(n=>n.id)}getMaxConnections(e){return e===0?this.Mmax0:this.M}add(e,t){this.nodes.has(e)&&this.remove(e);let s=this.randomLevel(),n={id:e,embedding:t,neighbors:new Map};for(let r=0;r<=s;r++)n.neighbors.set(r,[]);if(this.nodes.set(e,n),this.entryPoint===null){this.entryPoint=e,this.currentMaxLevel=s;return}let o=this.entryPoint;for(let r=this.currentMaxLevel;r>s;r--)o=this.searchLayer(t,o,r);for(let r=Math.min(s,this.currentMaxLevel);r>=0;r--){let a=this.getMaxConnections(r),h=this.searchLayerBeam(t,[o],r,this.efConstruction),d=this.selectNeighbors(t,h,a);n.neighbors.set(r,[...d]);for(let i of d){let c=this.nodes.get(i);if(!c)continue;let u=c.neighbors.get(r)??[];if(u.push(e),u.length>a){let m=u.filter(g=>this.nodes.has(g)).map(g=>({id:g,score:p(c.embedding,this.nodes.get(g).embedding)}));m.sort((g,y)=>y.score-g.score),c.neighbors.set(r,m.slice(0,a).map(g=>g.id))}else c.neighbors.set(r,u)}h.length>0&&(o=h[0].id)}s>this.currentMaxLevel&&(this.entryPoint=e,this.currentMaxLevel=s)}remove(e){let t=this.nodes.get(e);if(!t)return!1;for(let[s,n]of t.neighbors.entries())for(let o of n){let r=this.nodes.get(o);if(!r)continue;let a=r.neighbors.get(s);if(!a)continue;let h=a.indexOf(e);h!==-1&&a.splice(h,1);let d=this.getMaxConnections(s);if(a.length<d){for(let i of n)if(i!==o&&i!==e&&this.nodes.has(i)&&!a.includes(i)){a.push(i);let c=this.nodes.get(i);if(c){let u=c.neighbors.get(s)??[];!u.includes(o)&&u.length<d&&(u.push(o),c.neighbors.set(s,u))}if(a.length>=d)break}}r.neighbors.set(s,a)}if(this.nodes.delete(e),this.entryPoint===e)if(this.nodes.size===0)this.entryPoint=null,this.currentMaxLevel=-1;else{let s=null,n=-1;for(let[o,r]of this.nodes.entries()){let a=-1;for(let h of r.neighbors.keys())h>a&&(a=h);a>n&&(n=a,s=o)}this.entryPoint=s,this.currentMaxLevel=n}return!0}search(e,t){if(this.nodes.size===0||this.entryPoint===null)return[];if(this.nodes.size===1){let r=this.nodes.get(this.entryPoint);return[{id:r.id,score:p(e,r.embedding)}]}let s=this.entryPoint;for(let r=this.currentMaxLevel;r>0;r--)s=this.searchLayer(e,s,r);let n=Math.max(this.efSearch,t);return this.searchLayerBeam(e,[s],0,n).slice(0,t)}size(){return this.nodes.size}clear(){this.nodes.clear(),this.entryPoint=null,this.currentMaxLevel=-1}};A=class{ids=[];vectors=[];norms=[];idToIndex=new Map;initialized=!1;constructor(){if(w&&!this.initialized)try{w(),this.initialized=!0}catch{this.initialized=f!==null}}add(e,t){let s=new Float32Array(t),n=x(s);if(this.idToIndex.has(e)){let r=this.idToIndex.get(e);this.vectors[r]=s,this.norms[r]=n;return}let o=this.ids.length;this.ids.push(e),this.vectors.push(s),this.norms.push(n),this.idToIndex.set(e,o)}search(e,t){if(this.ids.length===0)return[];let s=Math.min(t,this.ids.length),n=this.vectors.length>0?this.vectors[0].length:0,o=e.length,r=n===o;if(f&&this.vectors.length>0&&r){let i=new Float32Array(e),c=x(i);return f(i,this.vectors,s,1).indices.map(m=>({id:this.ids[m],score:C(i,this.vectors[m],c,this.norms[m])}))}let a=new Float32Array(e),h=x(a),d=[];for(let i=0;i<this.ids.length;i++){let c=this.vectors[i];if(c.length!==a.length){i===0&&console.warn(`[RuvectorFlatIndex] Dimension mismatch: query=${a.length}, stored=${c.length}. Skipping ${this.ids.length} mismatched vectors. Re-index with correct dimensions.`);continue}else d.push({id:this.ids[i],score:C(a,c,h,this.norms[i])})}return d.sort((i,c)=>c.score-i.score),d.slice(0,s)}remove(e){let t=this.idToIndex.get(e);if(t===void 0)return!1;let s=this.ids.length-1;if(t!==s){let n=this.ids[s];this.ids[t]=n,this.vectors[t]=this.vectors[s],this.norms[t]=this.norms[s],this.idToIndex.set(n,t)}return this.ids.pop(),this.vectors.pop(),this.norms.pop(),this.idToIndex.delete(e),!0}clear(){this.ids=[],this.vectors=[],this.norms=[],this.idToIndex.clear()}size(){return this.ids.length}},M=class{adapter;constructor(e,t){this.adapter=T.create(e,t)}add(e,t){this.adapter.addByStringId(e,t)}search(e,t){return this.adapter.searchByArray(e,t)}remove(e){return this.adapter.removeByStringId(e)}clear(){this.adapter.clear()}size(){return this.adapter.size()}recall(){return this.adapter.recall()}getProvider(){return this.adapter}}});export{v as a,I as b,A as c,M as d,U as e,D as f};