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,2 @@
1
+ if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.0");process.exit(0)}
2
+ import{b as A,d as M}from"./chunk-WGMPEW2T.js";import{a as S,b as D}from"./chunk-UFUVUO3J.js";import{M as Q,l as E}from"./chunk-2I7J3O6V.js";import{g as C}from"./chunk-4I2IOUS4.js";M();Q();var v=(1+Math.sqrt(5))/2,R=1/v;function k(t,e=0){if(t<0||!Number.isFinite(t))throw new Error(`Invalid dither sequence length: ${t}`);if(!Number.isFinite(e))throw new Error(`Invalid dither seed: ${e}`);let n=new Float32Array(t),r=(e*R%1+1)%1;for(let i=0;i<t;i++)n[i]=((r+(i+1)*v)%1+1)%1;return n}function I(t,e,n=0){if(!(t instanceof Float32Array))throw new Error("Input vector must be a Float32Array");if(t.length===0)return{quantized:new Int32Array(0),dequantized:new Float32Array(0),bitDepth:e,seed:n,stepSize:0,minValue:0,maxValue:0};if(e<1||e>32||!Number.isInteger(e))throw new Error(`Invalid bit depth: ${e}. Must be an integer in [1, 32].`);let r=t[0],i=t[0];for(let d=1;d<t.length;d++)t[d]<r&&(r=t[d]),t[d]>i&&(i=t[d]);let s=(1<<e)-1,a=i-r,o=a===0?1:a/s,m=k(t.length,n),l=new Int32Array(t.length),u=new Float32Array(t.length);for(let d=0;d<t.length;d++){if(a===0)l[d]=Math.round(s/2);else{let L=(t[d]-r)/o+(m[d]-.5);l[d]=Math.max(0,Math.min(s,Math.round(L)))}u[d]=l[d]*o+r}return{quantized:l,dequantized:u,bitDepth:e,seed:n,stepSize:o,minValue:r,maxValue:i}}var h=null,b=null,p=null,g=null,f=null,w=null,x=!1;try{let t=(D(),C(S));h=t.RuvectorLayer,b=t.TensorCompress,p=t.differentiableSearch,g=t.hierarchicalForward,f=t.getCompressionLevel,w=t.init,x=!0}catch{}function H(){return x}function c(){if(!x)throw new Error("@ruvector/gnn native module is not available on this platform. Install the appropriate optional dependency for your platform, or use a platform where pre-built binaries are available.")}var F=!1;function V(){if(!F){c();let t=w();return F=!0,t}return"@ruvector/gnn already initialized"}var y=class{indexes;config;nextId;gnnLayers;compressor;constructor(e={}){this.config={M:e.M||16,efConstruction:e.efConstruction||200,efSearch:e.efSearch||50,dimension:e.dimension||384,metric:e.metric||"cosine",quantization:e.quantization||"none"},this.indexes=new Map,this.nextId=new Map,this.gnnLayers=new Map,c(),this.compressor=new b,V()}initializeIndex(e){this.indexes.has(e)||(this.indexes.set(e,new Map),this.nextId.set(e,0))}addEmbedding(e,n){let r=e.namespace;this.indexes.has(r)||this.initializeIndex(r);let i=this.indexes.get(r),s=n??this.nextId.get(r);return n===void 0&&this.nextId.set(r,s+1),i.set(s,e),s}addEmbeddingsBatch(e){let n=[];for(let r of e){let i=this.addEmbedding(r.embedding,r.id);n.push(i)}return n}search(e,n={}){let r=n.namespace||e.namespace;if(!this.indexes.has(r))return[];let i=this.indexes.get(r),s=n.limit||10,a=[];for(let[u,d]of i.entries())a.push({id:u,vector:Array.from(d.vector)});if(a.length===0)return[];let o=new Float32Array(e.vector),m=a.map(u=>new Float32Array(u.vector)),l=p(o,m,Math.min(s,a.length),1);return l.indices.map((u,d)=>({id:a[u]?.id??u,distance:1-l.weights[d]}))}differentiableSearchWithWeights(e,n,r,i=1){let s=new Float32Array(e.vector),a=n.map(m=>new Float32Array(m.embedding.vector)),o=p(s,a,Math.min(r,n.length),i);return{indices:o.indices.map(m=>n[m]?.id??m),weights:o.weights}}hierarchicalForward(e,n,r){let i=r.map(l=>`${l.inputDim}-${l.hiddenDim}`).join(",");if(!this.gnnLayers.has(i)){let l=[];for(let u of r){let d=new h(u.inputDim,u.hiddenDim,u.heads,u.dropout);l.push(d)}this.gnnLayers.set(i,l[0])}let a=this.gnnLayers.get(i).toJson(),o=new Float32Array(e),m=n.map(l=>l.map(u=>new Float32Array(u)));return Array.from(g(o,m,[a]))}compressEmbedding(e,n){let r=f(n),s={none:"none",half:"half",pq8:"pq8",pq4:"pq4",binary:"binary"}[r]??"none",a=new Float32Array(e.vector),o=this.compressor.compress(a,n);return{dimension:Array.from(e.vector).length,level:s,data:o,accessFreq:n}}decompressEmbedding(e){let n=this.compressor.decompress(e.data),r={none:"none",half:"fp16",pq8:"int8",pq4:"int8",binary:"binary"};return{vector:n,dimension:e.dimension,namespace:"code",text:"",timestamp:Date.now(),quantization:r[e.level]??"none"}}getCompressionLevelForFrequency(e){return c(),f(e)}getIndexStats(e){return this.indexes.has(e)?{size:this.indexes.get(e).size,maxElements:1e4,dimension:this.config.dimension,metric:this.config.metric}:null}clearIndex(e){this.indexes.delete(e),this.nextId.delete(e)}clearAll(){this.indexes.clear(),this.nextId.clear()}resizeIndex(e){}setEfSearch(e){this.config.efSearch=e}getConfig(){return{...this.config}}isInitialized(e){return this.indexes.has(e)}getInitializedNamespaces(){return Array.from(this.indexes.keys())}getSize(e){return this.indexes.get(e)?.size??0}async saveIndex(e,n){let r=this.indexes.get(e);if(!r)throw new Error(`Namespace ${e} not initialized`);let i=Array.from(r.entries()).map(([a,o])=>({id:a,vector:Array.from(o.vector),metadata:o.metadata}));await(await import("fs/promises")).writeFile(n,JSON.stringify(i,null,2))}async loadIndex(e,n){let i=await(await import("fs/promises")).readFile(n,"utf-8"),s=A(i);this.initializeIndex(e);for(let a of s){let o={vector:a.vector,dimension:a.vector.length,namespace:e,text:"",timestamp:Date.now(),quantization:"none",metadata:a.metadata};this.addEmbedding(o,a.id)}}},q=class{static instances=new Map;static getInstance(e,n){return this.instances.has(e)||this.instances.set(e,new y(n)),this.instances.get(e)}static closeInstance(e){let n=this.instances.get(e);n&&(n.clearAll(),this.instances.delete(e))}static closeAll(){for(let e of this.instances.values())e.clearAll();this.instances.clear()}},z=class{static layers=new Map;static getLayer(e){let n=`${e.inputDim}-${e.hiddenDim}-${e.heads}-${e.dropout}`;if(!this.layers.has(n)){c();let r=new h(e.inputDim,e.hiddenDim,e.heads,e.dropout);this.layers.set(n,r)}return this.layers.get(n)}static layerFromJson(e){return c(),h.fromJson(e)}static clearCache(){this.layers.clear()}},N=class{static _compressor=null;static get compressor(){return this._compressor||(c(),this._compressor=new b),this._compressor}static compressWithLevel(e,n){let r={levelType:n,scale:1,subvectors:n==="pq8"?8:n==="pq4"?16:void 0,centroids:n==="pq8"?256:void 0,outlierThreshold:n==="pq4"?3:void 0,threshold:n==="binary"?0:void 0},i=e instanceof Float32Array?e:new Float32Array(e);return this.compressor.compressWithLevel(i,r)}static decompress(e){return this.compressor.decompress(e)}static getLevel(e){return c(),f(e)}static compressWithDither(e,n,r){let i=e instanceof Float32Array?e:new Float32Array(e),s;if(E()){let o={none:32,half:16,pq8:8,pq4:4,binary:1},m=r?.bitDepth??o[n]??8,l=r?.seed??0;s=I(i,m,l)}return{compressed:this.compressWithLevel(s?s.dequantized:e,n),ditherResult:s}}};function G(){return c(),h}function J(){return c(),b}function O(){return c(),p}function j(){return c(),g}function B(){return c(),f}function K(){return c(),w}function U(t){return t instanceof Float32Array?t:"vector"in t?t.vector instanceof Float32Array?t.vector:new Float32Array(t.vector):new Float32Array(t)}function X(t){return"vector"in t?Array.from(t.vector):Array.from(t)}function Y(t,e="code"){return{vector:t,dimension:t.length,namespace:e,text:"",timestamp:Date.now(),quantization:"none"}}function Z(t,e,n,r=1){let i=[],s=e.map(a=>a instanceof Float32Array?a:new Float32Array(a));for(let a of t){let o=a instanceof Float32Array?a:new Float32Array(a),m=p(o,s,n,r);i.push({indices:m.indices,weights:m.weights})}return i}export{H as a,V as b,y as c,q as d,z as e,N as f,G as g,J as h,O as i,j,B as k,K as l,U as m,X as n,Y as o,Z as p};
@@ -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 w,d as E,f as T}from"./chunk-4I2IOUS4.js";var d=E((b,u)=>{"use strict";var _=typeof Buffer<"u",a=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,l=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function p(r,t,e){e==null&&t!==null&&typeof t=="object"&&(e=t,t=void 0),_&&Buffer.isBuffer(r)&&(r=r.toString()),r&&r.charCodeAt(0)===65279&&(r=r.slice(1));let o=JSON.parse(r,t);if(o===null||typeof o!="object")return o;let n=e&&e.protoAction||"error",c=e&&e.constructorAction||"error";if(n==="ignore"&&c==="ignore")return o;if(n!=="ignore"&&c!=="ignore"){if(a.test(r)===!1&&l.test(r)===!1)return o}else if(n!=="ignore"&&c==="ignore"){if(a.test(r)===!1)return o}else if(l.test(r)===!1)return o;return y(o,{protoAction:n,constructorAction:c,safe:e&&e.safe})}function y(r,{protoAction:t="error",constructorAction:e="error",safe:o}={}){let n=[r];for(;n.length;){let c=n;n=[];for(let s of c){if(t!=="ignore"&&Object.prototype.hasOwnProperty.call(s,"__proto__")){if(o===!0)return null;if(t==="error")throw new SyntaxError("Object contains forbidden prototype property");delete s.__proto__}if(e!=="ignore"&&Object.prototype.hasOwnProperty.call(s,"constructor")&&s.constructor!==null&&typeof s.constructor=="object"&&Object.prototype.hasOwnProperty.call(s.constructor,"prototype")){if(o===!0)return null;if(e==="error")throw new SyntaxError("Object contains forbidden prototype property");delete s.constructor}for(let h in s){let f=s[h];f&&typeof f=="object"&&n.push(f)}}}return r}function i(r,t,e){let{stackTraceLimit:o}=Error;Error.stackTraceLimit=0;try{return p(r,t,e)}finally{Error.stackTraceLimit=o}}function m(r,t){let{stackTraceLimit:e}=Error;Error.stackTraceLimit=0;try{return p(r,t,{safe:!0})}catch{return}finally{Error.stackTraceLimit=e}}u.exports=i;u.exports.default=i;u.exports.parse=i;u.exports.safeParse=m;u.exports.scan=y});function F(r){return g.default.parse(r,void 0,{protoAction:"remove",constructorAction:"remove"})}function j(r,t){try{return F(r)}catch(e){throw new Error(`Invalid JSON in --${t}: ${e instanceof Error?e.message:"Parse error"}`)}}var g,O=w(()=>{"use strict";g=T(d(),1)});export{d as a,F as b,j as c,O 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 g}from"./chunk-5SKGFSKD.js";import{b as p,c}from"./chunk-3ZOONQG6.js";import{f as v}from"./chunk-SUSEVMZT.js";import{a as x,b as f,c as w}from"./chunk-JZSDOIXA.js";w();var l={ProtocolStarted:"coordination.ProtocolStarted",ProtocolCompleted:"coordination.ProtocolCompleted",ProtocolFailed:"coordination.ProtocolFailed",ProtocolCancelled:"coordination.ProtocolCancelled",ActionStarted:"coordination.ActionStarted",ActionCompleted:"coordination.ActionCompleted",ActionFailed:"coordination.ActionFailed"},E=class{constructor(e,t,o){this.eventBus=e;this.memory=t;this.getDomainAPI=o}protocols=new Map;executions=new Map;scheduledProtocols=new Map;schedulerRunning=!1;registerProtocol(e){this.protocols.set(e.id,e),e.schedule.type==="event"&&e.enabled&&this.setupEventTriggers(e),(e.schedule.type==="cron"||e.schedule.type==="interval")&&e.enabled&&this.scheduleProtocol(e)}unregisterProtocol(e){if(!this.protocols.get(e))return!1;let o=this.scheduledProtocols.get(e);return o?.intervalId&&clearInterval(o.intervalId),this.scheduledProtocols.delete(e),this.protocols.delete(e),!0}getProtocol(e){return this.protocols.get(e)}listProtocols(){return Array.from(this.protocols.values())}async execute(e,t){let o=this.protocols.get(e);return o?o.enabled?this.executeProtocol(o,t):c(new Error(`Protocol is disabled: ${e}`)):c(new Error(`Protocol not found: ${e}`))}async executeOnEvent(e,t){let o=this.protocols.get(e);return o?o.enabled?this.executeProtocol(o,void 0,t):c(new Error(`Protocol is disabled: ${e}`)):c(new Error(`Protocol not found: ${e}`))}getExecution(e){let t=this.executions.get(e);if(t)return this.toImmutableExecution(t.execution)}listActiveExecutions(){return Array.from(this.executions.values()).filter(e=>e.execution.status==="running"||e.execution.status==="paused").map(e=>this.toImmutableExecution(e.execution))}async cancelExecution(e){let t=this.executions.get(e);return t?t.execution.status!=="running"&&t.execution.status!=="paused"?c(new Error(`Cannot cancel execution in status: ${t.execution.status}`)):(t.cancelled=!0,t.execution.status="cancelled",t.execution.completedAt=new Date,await this.publishEvent(l.ProtocolCancelled,{executionId:e,protocolId:t.protocol.id}),p(void 0)):c(new Error(`Execution not found: ${e}`))}async pauseExecution(e){let t=this.executions.get(e);return t?t.execution.status!=="running"?c(new Error(`Cannot pause execution in status: ${t.execution.status}`)):(t.paused=!0,t.execution.status="paused",p(void 0)):c(new Error(`Execution not found: ${e}`))}async resumeExecution(e){let t=this.executions.get(e);return t?t.execution.status!=="paused"?c(new Error(`Cannot resume execution in status: ${t.execution.status}`)):(t.paused=!1,t.execution.status="running",p(void 0)):c(new Error(`Execution not found: ${e}`))}startScheduler(){if(!this.schedulerRunning){this.schedulerRunning=!0;for(let e of this.protocols.values())e.enabled&&(e.schedule.type==="interval"||e.schedule.type==="cron")&&this.scheduleProtocol(e)}}stopScheduler(){this.schedulerRunning=!1;for(let e of this.scheduledProtocols.values())e.intervalId&&(clearInterval(e.intervalId),e.intervalId=void 0)}async dispose(){this.stopScheduler(),this.protocols.clear(),this.executions.clear(),this.scheduledProtocols.clear()}async executeProtocol(e,t,o){let r=v(),a=o?.correlationId??r,n={executionId:r,protocolId:e.id,status:"running",participants:[...e.participants],results:new Map,startedAt:new Date,correlationId:a,triggeredBy:o},u={execution:n,protocol:e,params:t,actionResults:new Map,cancelled:!1,paused:!1};this.executions.set(r,u),await this.publishEvent(l.ProtocolStarted,{executionId:r,protocolId:e.id,participants:e.participants},a);try{await this.executeActions(u);let i=Array.from(u.actionResults.values()).some(s=>s.status==="failed");return u.cancelled?n.status="cancelled":i?(n.status="failed",await this.publishEvent(l.ProtocolFailed,{executionId:r,protocolId:e.id,failedActions:Array.from(u.actionResults.values()).filter(s=>s.status==="failed").map(s=>s.actionId)},a)):(n.status="completed",await this.publishEvent(l.ProtocolCompleted,{executionId:r,protocolId:e.id,duration:Date.now()-n.startedAt.getTime()},a)),n.completedAt=new Date,n.results=u.actionResults,await this.storeExecutionHistory(n),p(this.toImmutableExecution(n))}catch(i){return n.status="failed",n.completedAt=new Date,await this.publishEvent(l.ProtocolFailed,{executionId:r,protocolId:e.id,error:x(i)},a),c(f(i))}}async executeActions(e){let{protocol:t,actionResults:o}=e,r=new Set(t.actions.map(n=>n.id)),a=new Set;for(;r.size>0&&!e.cancelled;){for(;e.paused&&!e.cancelled;)await this.sleep(100);if(e.cancelled)break;let n=t.actions.filter(i=>r.has(i.id)&&this.dependenciesSatisfied(i,a));if(n.length===0&&r.size>0)throw new Error(`Deadlock detected: actions ${Array.from(r).join(", ")} cannot proceed`);let u=await Promise.allSettled(n.map(i=>this.executeAction(i,e)));for(let i=0;i<n.length;i++){let s=n[i],d=u[i],m;d.status==="fulfilled"?m=d.value:m={actionId:s.id,status:"failed",error:d.reason instanceof Error?d.reason.message:String(d.reason)},o.set(s.id,m),r.delete(s.id),m.status==="completed"&&a.add(s.id)}}for(let n of r)o.set(n,{actionId:n,status:e.cancelled?"cancelled":"skipped"})}async executeAction(e,t){let o=new Date;await this.publishEvent(l.ActionStarted,{executionId:t.execution.executionId,actionId:e.id,actionName:e.name,targetDomain:e.targetDomain},t.execution.correlationId);let r=0,a=e.retry?.maxAttempts??1,n;for(;r<a;){r++;try{let i=this.getDomainAPI(e.targetDomain);if(!i)throw new Error(`Domain API not available: ${e.targetDomain}`);let s=i[e.method];if(typeof s!="function")throw new Error(`Method ${e.method} not found on domain ${e.targetDomain}`);let d={...e.params,...t.params},m=await this.executeWithTimeout(s.bind(i)(d),e.timeout??3e4),h=new Date;return await this.publishEvent(l.ActionCompleted,{executionId:t.execution.executionId,actionId:e.id,duration:h.getTime()-o.getTime()},t.execution.correlationId),{actionId:e.id,status:"completed",startedAt:o,completedAt:h,duration:h.getTime()-o.getTime(),result:m,retryAttempts:r>1?r-1:void 0}}catch(i){if(n=f(i),r<a&&e.retry){let s=e.retry.backoffMs*Math.pow(e.retry.backoffMultiplier??2,r-1);await this.sleep(s)}}}let u=new Date;return await this.publishEvent(l.ActionFailed,{executionId:t.execution.executionId,actionId:e.id,error:n?.message??"Unknown error",attempts:r},t.execution.correlationId),{actionId:e.id,status:"failed",startedAt:o,completedAt:u,duration:u.getTime()-o.getTime(),error:n?.message??"Unknown error",retryAttempts:r>1?r-1:void 0}}dependenciesSatisfied(e,t){return!e.dependsOn||e.dependsOn.length===0?!0:e.dependsOn.every(o=>t.has(o))}async executeWithTimeout(e,t){return Promise.race([e,new Promise((o,r)=>setTimeout(()=>r(new Error("Action timeout")),t))])}setupEventTriggers(e){if(e.schedule.type==="event")for(let t of e.schedule.triggerEvents)this.eventBus.subscribe(t,async o=>{await this.executeOnEvent(e.id,o)})}scheduleProtocol(e){if(e.schedule.type==="interval"){let t={protocolId:e.id,schedule:e.schedule};t.intervalId=setInterval(async()=>{this.schedulerRunning&&await this.execute(e.id)},e.schedule.intervalMs),this.scheduledProtocols.set(e.id,t)}}async storeExecutionHistory(e){let t=`protocol-execution:${e.executionId}`;await this.memory.set(t,{...e,results:Object.fromEntries(e.results)},{namespace:"coordination",ttl:864e5})}toImmutableExecution(e){return{executionId:e.executionId,protocolId:e.protocolId,status:e.status,participants:[...e.participants],results:new Map(e.results),startedAt:e.startedAt,completedAt:e.completedAt,correlationId:e.correlationId,triggeredBy:e.triggeredBy}}async publishEvent(e,t,o){let r=g(e,"learning-optimization",t,o);await this.eventBus.publish(r)}sleep(e){return new Promise(t=>setTimeout(t,e))}};function S(P,e,t){return new E(P,e,t)}export{E as a,S as b};
@@ -0,0 +1,14 @@
1
+ if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.0");process.exit(0)}
2
+ import{c as _}from"./chunk-YVA65UZL.js";import{a as w}from"./chunk-BTREG4IW.js";import{k as M,o as U}from"./chunk-JJO7Y4H3.js";import{b as f,d as F}from"./chunk-WGMPEW2T.js";import{a as g,c as P}from"./chunk-JZSDOIXA.js";import{randomUUID as Q}from"crypto";U();F();P();var x={alpha:.1,minOutcomes:10,weightFloor:.2,weightCeiling:2},b=class{records=new Map;config;constructor(e){this.config={...x,...e}}recordOutcome(e,t,o){let{alpha:i,minOutcomes:r,weightFloor:s,weightCeiling:n}=this.config,u=this.records.get(e),d=t?1:0,a=Math.max(0,Math.min(1,o)),l,c;u?(l=i*d+(1-i)*u.emaAccuracy,c=i*a+(1-i)*u.emaQuality):(l=d,c=a);let h=(u?.totalOutcomes??0)+1,R;h>=r?R=Math.max(s,Math.min(n,l*2)):R=1;let k={agentId:e,emaAccuracy:l,emaQuality:c,calibratedWeight:R,totalOutcomes:h,lastUpdated:new Date};return this.records.set(e,k),k}getCalibration(e){return this.records.get(e)??null}getCalibratedWeight(e){let t=this.records.get(e);return!t||t.totalOutcomes<this.config.minOutcomes?1:t.calibratedWeight}getAllCalibrations(){return Array.from(this.records.values())}reset(e){e!==void 0?this.records.delete(e):this.records.clear()}serialize(){let e={};for(let[t,o]of this.records)e[t]={...o};return e}deserialize(e){this.records.clear();for(let[t,o]of Object.entries(e))this.records.set(t,{...o,lastUpdated:new Date(o.lastUpdated)})}};var D={escalateAfterFailures:2,deEscalateAfterSuccesses:5,maxTier:"opus",minTier:"haiku"},A=["booster","haiku","sonnet","opus"];function y(m){return A.indexOf(m)}var p=class{config;states=new Map;constructor(e){this.config={...D,...e}}recordOutcome(e,t,o){let i=this.states.get(e);i||(i={agentId:e,currentTier:o,baseTier:o,consecutiveFailures:0,consecutiveSuccesses:0,escalationCount:0,deEscalationCount:0,lastAction:"none",lastActionTimestamp:new Date},this.states.set(e,i));let r=i.currentTier;if(t){if(i.consecutiveSuccesses++,i.consecutiveFailures=0,i.consecutiveSuccesses>=this.config.deEscalateAfterSuccesses){let s=y(i.currentTier),n=y(this.config.minTier);if(s>n)return i.currentTier=A[s-1],i.deEscalationCount++,i.consecutiveSuccesses=0,i.lastAction="de-escalate",i.lastActionTimestamp=new Date,{action:"de-escalate",previousTier:r,newTier:i.currentTier}}}else if(i.consecutiveFailures++,i.consecutiveSuccesses=0,i.consecutiveFailures>=this.config.escalateAfterFailures){let s=y(i.currentTier),n=y(this.config.maxTier);if(s<n)return i.currentTier=A[s+1],i.escalationCount++,i.consecutiveFailures=0,i.lastAction="escalate",i.lastActionTimestamp=new Date,{action:"escalate",previousTier:r,newTier:i.currentTier}}return{action:"none",previousTier:r,newTier:i.currentTier}}getCurrentTier(e){return this.states.get(e)?.currentTier??null}getState(e){return this.states.get(e)??null}getAllStates(){return Array.from(this.states.values())}reset(e){e?this.states.delete(e):this.states.clear()}};var T={booster:{avgInputTokens:0,avgOutputTokens:0,costPerTask:0},haiku:{avgInputTokens:2e3,avgOutputTokens:1e3,costPerTask:.0035},sonnet:{avgInputTokens:2e3,avgOutputTokens:1e3,costPerTask:.021},opus:{avgInputTokens:2e3,avgOutputTokens:1e3,costPerTask:.105}},v=["booster","haiku","sonnet","opus"],E=T.opus.costPerTask,q={qualityWeight:.6,costWeight:.4,budgetPerHourUsd:0,budgetPerDayUsd:0,minQualityThreshold:.5,enabled:!0},I=.15,C=class{config;costTracker;tierQualityEstimates=new Map;tierOutcomeCounts=new Map;constructor(e,t){let o={...q,...t};o.qualityWeight=Math.max(0,Math.min(1,o.qualityWeight)),o.costWeight=Math.max(0,Math.min(1,o.costWeight)),o.minQualityThreshold=Math.max(0,Math.min(1,o.minQualityThreshold)),o.budgetPerHourUsd=Math.max(0,o.budgetPerHourUsd),o.budgetPerDayUsd=Math.max(0,o.budgetPerDayUsd);let i=o.qualityWeight+o.costWeight;i>0&&i!==1&&(o.qualityWeight/=i,o.costWeight/=i),this.config=o,this.costTracker=e,this.tierQualityEstimates.set("booster",.3),this.tierQualityEstimates.set("haiku",.55),this.tierQualityEstimates.set("sonnet",.75),this.tierQualityEstimates.set("opus",.9)}scoreTiers(e){let t=v.map(o=>{let i=this.getQualityEstimate(o,e),r=T[o].costPerTask,s=r>0?i/r:i>0?1/0:0,n=E>0?1-r/E:1,u=this.config.qualityWeight*i+this.config.costWeight*n;return{tier:o,qualityScore:i,estimatedCostUsd:r,qualityPerDollar:s,economicScore:u}});return t.sort((o,i)=>i.economicScore-o.economicScore),t}selectTier(e){let t=this.scoreTiers(e);for(let r of t)if(!(r.qualityScore<this.config.minQualityThreshold)&&!this.wouldExceedBudget(r.tier))return{tier:r.tier,reason:`Best economic score (${r.economicScore.toFixed(3)}): quality=${r.qualityScore.toFixed(2)}, cost=$${r.estimatedCostUsd.toFixed(4)}`,scores:t};let o=t.filter(r=>r.qualityScore>=this.config.minQualityThreshold);if(o.length>0){let r=[...o].sort((s,n)=>s.estimatedCostUsd-n.estimatedCostUsd)[0];return{tier:r.tier,reason:`Budget constrained fallback to ${r.tier}`,scores:t}}let i=[...t].sort((r,s)=>s.qualityScore-r.qualityScore)[0];return{tier:i.tier,reason:`No tier meets quality threshold ${this.config.minQualityThreshold}; using best quality: ${i.tier}`,scores:t}}wouldExceedBudget(e){let t=T[e].costPerTask;if(t===0)return!1;let o=this.costTracker.getCurrentCost("hour"),i=this.costTracker.getCurrentCost("day");return this.config.budgetPerHourUsd>0&&o+t>this.config.budgetPerHourUsd||this.config.budgetPerDayUsd>0&&i+t>this.config.budgetPerDayUsd}updateFromOutcome(e,t){let o=e.outcome.qualityScore,i=this.tierQualityEstimates.get(t)??.5,r=this.tierOutcomeCounts.get(t)??0,s=r<5?.4:I,n=i*(1-s)+o*s;this.tierQualityEstimates.set(t,n),this.tierOutcomeCounts.set(t,r+1)}getEconomicReport(){let e=this.scoreTiers(.5),t=this.costTracker.getCurrentCost("hour"),o=this.costTracker.getCurrentCost("day"),i={hourly:this.config.budgetPerHourUsd>0?Math.max(0,this.config.budgetPerHourUsd-t):null,daily:this.config.budgetPerDayUsd>0?Math.max(0,this.config.budgetPerDayUsd-o):null},r=null,s=[...e].sort((a,l)=>l.qualityPerDollar-a.qualityPerDollar),n=s.find(a=>a.estimatedCostUsd>0&&isFinite(a.qualityPerDollar)),u=[...s].reverse().find(a=>a.estimatedCostUsd>0&&isFinite(a.qualityPerDollar));if(n&&u&&n.tier!==u.tier){let a=u.estimatedCostUsd-n.estimatedCostUsd;a>0&&(r={usd:a,description:`Switch from ${u.tier} ($${u.estimatedCostUsd.toFixed(4)}/task) to ${n.tier} ($${n.estimatedCostUsd.toFixed(4)}/task) for comparable tasks to save ~$${a.toFixed(4)}/task`})}let d=this.generateRecommendation(e,i);return{tierEfficiency:e,currentHourlyCostUsd:t,currentDailyCostUsd:o,budgetRemaining:i,recommendation:d,savingsOpportunity:r}}computeCostAdjustedReward(e,t,o){let i=T[t].costPerTask;if(E===0)return e;let r=i/E,s=Math.max(0,o-this.config.minQualityThreshold),n=r*(1-s),u=e-n*this.config.costWeight;return Math.max(-1,Math.min(1,u))}serializeEstimates(){let e={};for(let t of v)e[t]={quality:this.tierQualityEstimates.get(t)??.5,count:this.tierOutcomeCounts.get(t)??0};return e}deserializeEstimates(e){for(let t of v)e[t]&&(this.tierQualityEstimates.set(t,e[t].quality),this.tierOutcomeCounts.set(t,e[t].count))}getConfig(){return{...this.config}}getQualityEstimate(e,t){let o=this.tierQualityEstimates.get(e)??.5,i=e==="booster"?t*.4:e==="haiku"?t*.2:0;return Math.max(0,Math.min(1,o-i))}generateRecommendation(e,t){if(t.hourly!==null&&t.hourly<.01)return"Hourly budget nearly exhausted. Consider increasing budget or routing to cheaper tiers.";if(t.daily!==null&&t.daily<.1)return"Daily budget nearly exhausted. Only critical tasks should use expensive tiers.";let o=e[0];return o?`Most cost-efficient tier: ${o.tier} (score=${o.economicScore.toFixed(3)}, quality=${o.qualityScore.toFixed(2)})`:"No economic data available yet."}};var S=class{outcomes=[];maxOutcomes;constructor(e=1e4){this.maxOutcomes=e}add(e){this.outcomes.push(e),this.outcomes.length>this.maxOutcomes&&(this.outcomes=this.outcomes.slice(-this.maxOutcomes))}getByAgent(e,t=100){return this.outcomes.filter(o=>o.usedAgent===e).slice(-t)}getAll(e=1e3){return this.outcomes.slice(-e)}getRecentOverrides(e=50){return this.outcomes.filter(t=>!t.followedRecommendation).slice(-e)}clear(){this.outcomes=[]}get size(){return this.outcomes.length}},O=class m{outcomeStore;router=null;db=null;calibrator=null;escalationTracker=null;economicModel=null;economicPersistCounter=0;static ECONOMIC_PERSIST_INTERVAL=10;persistCount=0;maxOutcomes;static RETENTION_CLEANUP_INTERVAL=100;constructor(e=1e4,t){this.maxOutcomes=e,this.outcomeStore=new S(e),t?.enableEMACalibration&&this.enableCalibration(),t?.enableAutoEscalation&&this.enableAutoEscalation()}async initialize(){try{this.db=M(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromDb(),this.loadCalibratorState()}catch(e){console.warn("[RoutingFeedbackCollector] DB init failed, using memory-only:",g(e)),this.db=null}}async loadFromDb(){if(!this.db)return;let t=this.db.getDatabase().prepare(`
3
+ SELECT * FROM routing_outcomes ORDER BY created_at DESC LIMIT ?
4
+ `).all(this.maxOutcomes);for(let o of t.reverse()){let i={id:o.id,task:f(o.task_json),decision:f(o.decision_json),usedAgent:o.used_agent,followedRecommendation:!!o.followed_recommendation,outcome:{success:!!o.success,qualityScore:o.quality_score,durationMs:o.duration_ms,error:o.error||void 0},timestamp:new Date(o.created_at)};this.outcomeStore.add(i)}t.length>0&&console.log(`[RoutingFeedbackCollector] Loaded ${t.length} outcomes from DB`)}persistOutcome(e){if(this.db)try{let t=this.db.getDatabase();try{t.prepare("ALTER TABLE routing_outcomes ADD COLUMN model_tier TEXT").run()}catch{}let o=this.inferTier(e.usedAgent);t.prepare(`
5
+ INSERT OR REPLACE INTO routing_outcomes (
6
+ id, task_json, decision_json, used_agent,
7
+ followed_recommendation, success, quality_score,
8
+ duration_ms, error, model_tier
9
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
10
+ `).run(e.id,JSON.stringify(e.task),JSON.stringify(e.decision),e.usedAgent,e.followedRecommendation?1:0,e.outcome.success?1:0,e.outcome.qualityScore,e.outcome.durationMs,e.outcome.error||null,o),this.persistCount++,this.persistCount%m.RETENTION_CLEANUP_INTERVAL===0&&this.enforceRetention(t)}catch(t){console.warn("[RoutingFeedbackCollector] Failed to persist outcome:",g(t))}}inferTier(e){let t=e.toLowerCase();return t.includes("booster")||t==="tier-0"?"booster":t==="tier-1"||t.includes("haiku")?"haiku":t==="tier-2"||t.includes("sonnet")?"sonnet":t.includes("opus")?"opus":"sonnet"}enforceRetention(e){try{let t=this.maxOutcomes*2;e.prepare(`
11
+ DELETE FROM routing_outcomes WHERE id NOT IN (
12
+ SELECT id FROM routing_outcomes ORDER BY created_at DESC LIMIT ?
13
+ )
14
+ `).run(t)}catch(t){console.warn("[RoutingFeedbackCollector] Retention cleanup failed:",g(t))}}loadCalibratorState(){if(!(!this.db||!this.calibrator))try{let t=this.db.getDatabase().prepare("SELECT value FROM kv_store WHERE key = 'routing:ema_calibrator_state'").get();if(t){let o=f(t.value);o&&typeof o=="object"&&(this.calibrator.deserialize(o),console.log("[RoutingFeedbackCollector] Loaded EMA calibrator state from DB"))}}catch(e){console.warn("[RoutingFeedbackCollector] Failed to load calibrator state:",g(e))}}persistCalibratorState(){if(!(!this.db||!this.calibrator))try{let e=this.db.getDatabase(),t=JSON.stringify(this.calibrator.serialize());e.prepare("INSERT OR REPLACE INTO kv_store (key, value, updated_at) VALUES (?, ?, datetime('now'))").run("routing:ema_calibrator_state",t)}catch(e){console.warn("[RoutingFeedbackCollector] Failed to persist calibrator state:",g(e))}}loadEconomicState(){if(!(!this.db||!this.economicModel))try{let t=this.db.getDatabase().prepare("SELECT value FROM kv_store WHERE key = 'routing:economic_quality_estimates'").get();if(t){let o=f(t.value);o&&typeof o=="object"&&(this.economicModel.deserializeEstimates(o),console.log("[RoutingFeedbackCollector] Loaded economic quality estimates from DB"))}}catch(e){console.warn("[RoutingFeedbackCollector] Failed to load economic state:",g(e))}}persistEconomicState(){if(!(!this.db||!this.economicModel))try{let e=this.db.getDatabase(),t=JSON.stringify(this.economicModel.serializeEstimates());e.prepare("INSERT OR REPLACE INTO kv_store (key, value, updated_at) VALUES (?, ?, datetime('now'))").run("routing:economic_quality_estimates",t)}catch(e){console.warn("[RoutingFeedbackCollector] Failed to persist economic state:",g(e))}}connectRouter(e){this.router=e}enableCalibration(e){this.calibrator=new b(e)}getCalibratedWeight(e){return this.calibrator?.getCalibratedWeight(e)??1}enableAutoEscalation(e){this.escalationTracker=new p(e)}getEscalationState(e){return this.escalationTracker?.getState(e)??null}enableEconomicRouting(e,t){let o=t??_();this.economicModel=new C(o,e),this.loadEconomicState()}getEconomicReport(){return this.economicModel?.getEconomicReport()??null}getEconomicScore(e){return this.economicModel?.scoreTiers(e)??null}recordOutcome(e,t,o,i){let r={id:`outcome-${Date.now()}-${Q().slice(0,8)}`,task:e,decision:t,usedAgent:o,followedRecommendation:o===t.recommended,outcome:i,timestamp:new Date};if(this.outcomeStore.add(r),this.persistOutcome(r),this.router&&this.router.updateAgentPerformance(o,i.success,i.qualityScore,i.durationMs),this.calibrator&&(this.calibrator.recordOutcome(o,i.success,i.qualityScore),this.persistCount%10===0&&this.persistCalibratorState()),this.escalationTracker){let s=t.recommended===o?"sonnet":"haiku",n=this.escalationTracker.recordOutcome(o,i.success,s);n.action!=="none"&&console.log(`[RoutingFeedbackCollector] Agent "${o}" ${n.action}d: ${n.previousTier} \u2192 ${n.newTier}`)}if(this.economicModel){let s=this.inferTier(o);this.economicModel.updateFromOutcome(r,s),this.economicPersistCounter++,this.economicPersistCounter%m.ECONOMIC_PERSIST_INTERVAL===0&&this.persistEconomicState()}return r}getAgentMetrics(e){let t=this.outcomeStore.getByAgent(e);if(t.length===0)return null;let o=t.filter(c=>c.outcome.success).length,i=t.reduce((c,h)=>c+h.outcome.durationMs,0),r=t.reduce((c,h)=>c+h.outcome.qualityScore,0),s=t.filter(c=>c.decision.recommended!==c.usedAgent&&c.decision.recommended===e).length,n=t.filter(c=>c.decision.recommended!==c.usedAgent&&c.usedAgent===e).length,u=t.slice(-10),d=u.filter(c=>c.outcome.success).length/u.length,a=o/t.length,l;return d>a+.1?l="improving":d<a-.1?l="declining":l="stable",{agentId:e,totalTasks:t.length,successfulTasks:o,successRate:o/t.length,avgQualityScore:r/t.length,avgDurationMs:i/t.length,overriddenCount:s,selectedOverOthersCount:n,trend:l,updatedAt:new Date}}getAllAgentMetrics(){let e=[];for(let t of w){let o=this.getAgentMetrics(t.id);o&&e.push(o)}return e.sort((t,o)=>o.successRate-t.successRate)}analyzeRoutingAccuracy(){let e=this.outcomeStore.getAll();if(e.length===0)return{totalOutcomes:0,followedRecommendations:0,overrideRate:0,recommendationSuccessRate:0,overrideSuccessRate:0,confidenceCorrelation:0};let t=e.filter(n=>n.followedRecommendation),o=e.filter(n=>!n.followedRecommendation),i=t.filter(n=>n.outcome.success).length,r=o.filter(n=>n.outcome.success).length,s=this.calculateConfidenceCorrelation(e);return{totalOutcomes:e.length,followedRecommendations:t.length,overrideRate:o.length/e.length,recommendationSuccessRate:t.length>0?i/t.length:0,overrideSuccessRate:o.length>0?r/o.length:0,confidenceCorrelation:s}}calculateConfidenceCorrelation(e){if(e.length<2)return 0;let t=e.map(a=>a.decision.confidence),o=e.map(a=>a.outcome.success?1:0),i=t.reduce((a,l)=>a+l,0)/t.length,r=o.reduce((a,l)=>a+l,0)/o.length,s=0,n=0,u=0;for(let a=0;a<e.length;a++){let l=t[a]-i,c=o[a]-r;s+=l*c,n+=l*l,u+=c*c}let d=Math.sqrt(n*u);return d===0?0:s/d}getImprovementRecommendations(){let e=[],t=this.analyzeRoutingAccuracy();if(t.totalOutcomes<50)return e.push("Collect more routing outcomes for reliable analysis (at least 50)"),e;t.overrideRate>.3&&t.overrideSuccessRate>t.recommendationSuccessRate&&e.push("Users are frequently overriding recommendations with better results. Consider adjusting routing weights or updating agent capabilities."),t.confidenceCorrelation<.3&&e.push("Low correlation between confidence and success. Consider improving semantic matching or adjusting weight distribution.");let o=this.getAllAgentMetrics(),i=o.filter(s=>s.successRate<.5&&s.totalTasks>=10);i.length>0&&e.push(`Agents with low success rates: ${i.map(s=>s.agentId).join(", ")}. Consider reviewing their capability mappings.`);let r=o.filter(s=>s.trend==="declining"&&s.totalTasks>=10);return r.length>0&&e.push(`Agents with declining performance: ${r.map(s=>s.agentId).join(", ")}. Monitor for potential issues.`),e.length===0&&e.push("Routing performance is healthy. Continue collecting feedback."),e}exportOutcomes(){return this.outcomeStore.getAll()}importOutcomes(e){for(let t of e)this.outcomeStore.add(t)}getStats(){let e=this.outcomeStore.getAll(),t=new Set(e.map(o=>o.usedAgent));return{totalOutcomes:this.outcomeStore.size,uniqueAgentsUsed:t.size,recentOverrides:this.outcomeStore.getRecentOverrides().length}}clear(){this.outcomeStore.clear()}};function ie(m=1e4,e){return new O(m,e)}export{O as a,ie as b};
@@ -0,0 +1,9 @@
1
+ if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.0");process.exit(0)}
2
+ function b(i,t){return{ingest(e){i.ingest(e)},search(e,r){return i.search(e,r).map(s=>({id:s.id,score:s.score}))},delete(e){i.delete(e)},status(){let e=i.status();return{totalVectors:e.totalVectors,dimensions:t,totalSegments:e.totalSegments,fileSizeBytes:e.fileSizeBytes,epoch:e.epoch,witnessValid:e.witnessValid,witnessEntries:e.witnessEntries}},close(){i.close()}}}function c(i,t){return(i.prepare("SELECT COUNT(*) as cnt FROM sqlite_master WHERE type='table' AND name=?").get(t)?.cnt??0)>0}var d=class{db;config;rvfStore=null;rvfAvailable=!1;constructor(t,e){this.db=t,this.config={...e,dimensions:e.dimensions??384}}async initialize(){if(this.config.mode==="sqlite-only"){this.rvfAvailable=!1;return}try{let t=await import("./rvf-native-adapter-LKFKTMUN.js");if(!t.isRvfNativeAvailable()){this.rvfAvailable=!1;return}let e;try{e=t.openRvfStore(this.config.rvfPath)}catch{e=t.createRvfStore(this.config.rvfPath,this.config.dimensions)}this.rvfStore=b(e,this.config.dimensions),this.rvfAvailable=!0}catch{this.rvfAvailable=!1}}setRvfStore(t){this.rvfStore=t,this.rvfAvailable=!0}writePattern(t,e){let r={sqliteSuccess:!1,rvfSuccess:!1};try{this.writeSqliteEmbedding(t,e),r.sqliteSuccess=!0}catch{r.sqliteSuccess=!1}if(this.shouldWriteRvf())try{this.rvfStore.ingest([{id:t,vector:e instanceof Float32Array?Array.from(e):e}]),r.rvfSuccess=!0}catch{r.rvfSuccess=!1,r.divergence="rvf-write-failed"}return r}deletePattern(t){let e={sqliteSuccess:!1,rvfSuccess:!1};try{this.deleteSqliteEmbedding(t),e.sqliteSuccess=!0}catch{e.sqliteSuccess=!1}if(this.shouldWriteRvf())try{this.rvfStore.delete([t]),e.rvfSuccess=!0}catch{e.rvfSuccess=!1,e.divergence="rvf-delete-failed"}return e}search(t,e){if(this.config.mode==="rvf-primary"&&this.rvfAvailable&&this.rvfStore)try{return this.rvfStore.search(t,e)}catch{}return this.searchSqlite(t,e)}getDivergenceReport(){let t={totalChecked:0,divergences:0,details:[]},e=this.getSqliteEmbeddingCount();if(t.totalChecked=e,!this.rvfAvailable||!this.rvfStore)return this.config.mode!=="sqlite-only"&&e>0&&(t.divergences=1,t.details.push({patternId:"*",issue:"count-mismatch"})),t;let s=this.rvfStore.status().totalVectors;return e!==s&&(t.divergences=1,t.details.push({patternId:"*",issue:"count-mismatch"})),t}isPromotionSafe(){return this.getDivergenceReport().divergences===0}status(){let t=this.getSqlitePatternCount(),e=this.getSqliteEmbeddingCount(),r=null;if(this.rvfAvailable&&this.rvfStore)try{r=this.rvfStore.status()}catch{r=null}return{sqlite:{patternCount:t,vectorCount:e},rvf:r,mode:this.config.mode}}close(){if(this.rvfStore){try{this.rvfStore.close()}catch{}this.rvfStore=null,this.rvfAvailable=!1}}shouldWriteRvf(){return(this.config.mode==="dual-write"||this.config.mode==="rvf-primary")&&this.rvfAvailable&&this.rvfStore!==null}writeSqliteEmbedding(t,e){let r=Buffer.from(e instanceof Float32Array?e.buffer:new Float32Array(e).buffer),s=e.length;c(this.db,"qe_pattern_embeddings")&&this.db.prepare(`
3
+ INSERT INTO qe_pattern_embeddings (pattern_id, embedding, dimension, model, created_at)
4
+ VALUES (?, ?, ?, 'all-MiniLM-L6-v2', datetime('now'))
5
+ ON CONFLICT(pattern_id) DO UPDATE SET
6
+ embedding = excluded.embedding,
7
+ dimension = excluded.dimension,
8
+ created_at = datetime('now')
9
+ `).run(t,r,s)}deleteSqliteEmbedding(t){c(this.db,"qe_pattern_embeddings")&&this.db.prepare("DELETE FROM qe_pattern_embeddings WHERE pattern_id = ?").run(t)}getSqliteEmbeddingCount(){return c(this.db,"qe_pattern_embeddings")?this.db.prepare("SELECT COUNT(*) as cnt FROM qe_pattern_embeddings").get()?.cnt??0:0}getSqlitePatternCount(){return c(this.db,"qe_patterns")?this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns").get()?.cnt??0:0}searchSqlite(t,e){if(!c(this.db,"qe_pattern_embeddings"))return[];let r=this.db.prepare("SELECT pattern_id, embedding, dimension FROM qe_pattern_embeddings").all(),s=t instanceof Float32Array?Array.from(t):t,v=Math.sqrt(s.reduce((n,o)=>n+o*o,0));if(v===0)return[];let f=[];for(let n of r){let o=new Float32Array(n.embedding.buffer,n.embedding.byteOffset,n.dimension),u=Array.from(o),m=0,l=0;for(let a=0;a<u.length&&a<s.length;a++)m+=u[a]*s[a],l+=u[a]*u[a];l=Math.sqrt(l);let h=l>0?m/(v*l):0;f.push({id:n.pattern_id,score:h})}return f.sort((n,o)=>o.score-n.score),f.slice(0,e)}};function g(i,t){return new d(i,t)}export{d as a,g 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 L,b as q,c as O}from"./chunk-MV6CMOJQ.js";import{d as Q,e as A,f as T,g as M}from"./chunk-4YS3IJ45.js";import{b as y,c as S}from"./chunk-3ZOONQG6.js";import{f as D}from"./chunk-SUSEVMZT.js";import{a as p,b as F,c as $}from"./chunk-JZSDOIXA.js";import{C,M as k,x,z as v}from"./chunk-2I7J3O6V.js";$();k();function U(o,e){let n=[o.pattern,o];for(let s of n){let i=e.split("."),r=s;for(let u of i){if(r==null)break;if(typeof r=="object")r=r[u];else{r=void 0;break}}if(r!==void 0)return r}}function W(o,e,t){switch(e){case"eq":return o===t;case"gt":return typeof o=="number"&&typeof t=="number"&&o>t;case"lt":return typeof o=="number"&&typeof t=="number"&&o<t;case"gte":return typeof o=="number"&&typeof t=="number"&&o>=t;case"lte":return typeof o=="number"&&typeof t=="number"&&o<=t;case"in":return Array.isArray(t)?t.includes(o):!1;case"contains":return Array.isArray(o)||typeof o=="string"&&typeof t=="string"?o.includes(t):!1;case"between":{if(typeof o!="number"||!Array.isArray(t)||t.length!==2){if(o instanceof Date&&Array.isArray(t)&&t.length===2){let i=o.getTime(),r=t[0]instanceof Date?t[0].getTime():Number(t[0]),u=t[1]instanceof Date?t[1].getTime():Number(t[1]);return i>=r&&i<=u}return!1}let[n,s]=t;return o>=n&&o<=s}default:return!1}}function w(o,e){switch(e.type){case"AND":return(e.children??[]).every(n=>w(o,n));case"OR":{let t=e.children??[];return t.length===0?!0:t.some(n=>w(o,n))}case"NOT":return e.child?!w(o,e.child):!0;case"FIELD":{if(!e.field||!e.operator)return!0;let t=U(o,e.field);return W(t,e.operator,e.value)}default:return!0}}function z(o,e){return e?o.filter(t=>w(t,e)):o}k();var R=null;function N(){return R||(R=L({dimensions:1e4})),R}var P=null,E=0;function H(o){return(!P||E!==o)&&(P=O({dimension:o,maxPatterns:1e4}),E=o),P}var j={namespace:"qe-patterns",embeddingDimension:384,hnsw:{M:16,efConstruction:200,efSearch:100,maxElements:5e4},promotionThreshold:A,minConfidence:.3,maxPatternsPerDomain:5e3,autoCleanup:!0,cleanupIntervalMs:36e5,tokenTracking:{enabled:!0,trackInputOutput:!0,estimateCosts:!0,costPerInputToken:3e-6,costPerOutputToken:15e-6},reuseOptimization:{enabled:!0,minSimilarityForReuse:.85,minSuccessRateForReuse:.9,maxAgeForReuse:7}},I=class{constructor(e,t={}){this.memory=e;this.config={...j,...t}}config;initialized=!1;cleanupTimer;sqliteStore=null;loadingPromise=null;patternCache=new Map;domainIndex=new Map;typeIndex=new Map;tierIndex=new Map;hnswIndex=null;hnswAvailable=!1;hnswInitPromise=null;hdcCache=new Map;deltaTracker=null;stats={searchOperations:0,searchLatencies:[]};setSqliteStore(e){if(this.sqliteStore=e,v()&&!this.deltaTracker)try{let t=e.getDb();this.deltaTracker=new q(t),this.deltaTracker.initialize(),console.log("[PatternStore] Delta event sourcing initialized")}catch(t){console.warn("[PatternStore] Delta tracker init failed:",t instanceof Error?t.message:t)}this.initialized&&(this.loadingPromise=this.loadPatterns().catch(t=>console.warn("[PatternStore] Failed to load patterns after setSqliteStore:",t)).finally(()=>{this.loadingPromise=null}))}async initialize(){this.initialized||(this.tierIndex.set("short-term",new Set),this.tierIndex.set("long-term",new Set),await this.loadPatterns(),this.config.autoCleanup&&(this.cleanupTimer=setInterval(()=>this.cleanup(),this.config.cleanupIntervalMs)),this.initialized=!0)}async ensureHNSW(){return this.hnswIndex!==null?this.hnswIndex:this.hnswAvailable===!1&&this.hnswInitPromise===null&&!(this.hnswIndex===null&&this.hnswAvailable===!1)?null:this.hnswInitPromise?(await this.hnswInitPromise,this.hnswIndex):(this.hnswInitPromise=this.initializeHNSWInternal(),await this.hnswInitPromise,this.hnswInitPromise=null,this.hnswIndex)}async initializeHNSWInternal(){try{let{HNSWIndex:e}=await import("./hnsw-index-YO7CT23I.js");this.hnswIndex=new e(this.memory,{dimensions:this.config.embeddingDimension,M:this.config.hnsw.M,efConstruction:this.config.hnsw.efConstruction,efSearch:this.config.hnsw.efSearch,maxElements:this.config.hnsw.maxElements,namespace:`${this.config.namespace}:hnsw`,metric:"cosine"});let t=5e3,n=this.hnswIndex.initialize(),s=new Promise((i,r)=>setTimeout(()=>r(new Error("HNSW init timeout")),t));if(await Promise.race([n,s]),this.hnswAvailable=this.hnswIndex.isNativeAvailable(),this.sqliteStore)try{let i=this.sqliteStore.getAllEmbeddings(),r=this.config.hnsw.maxElements,u=0;for(let{patternId:f,embedding:l}of i){if(u>=r)break;if(!l||l.length!==this.config.embeddingDimension)continue;let h=this.patternCache.get(f);if(h)try{await this.hnswIndex.insert(f,l,{filePath:h.patternType,lineCoverage:h.confidence*100,branchCoverage:h.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-h.confidence,lastUpdated:Date.now(),totalLines:0}),u++}catch{}}u>0&&console.log(`[PatternStore] Loaded ${u} embeddings from SQLite into HNSW`)}catch(i){console.warn("[PatternStore] Failed to load SQLite embeddings into HNSW:",p(i))}console.log(`[PatternStore] HNSW lazy-initialized (native: ${this.hnswAvailable})`)}catch(e){console.warn("[PatternStore] HNSW not available, using memory backend search:",p(e)),this.hnswIndex=null,this.hnswAvailable=!1}}async loadPatterns(){if(this.sqliteStore)try{let e=this.sqliteStore.getPatterns({limit:5e4});for(let t of e)this.indexPattern(t);e.length>0&&console.log(`[PatternStore] Loaded ${e.length} patterns from SQLite into memory cache`)}catch(e){console.warn("[PatternStore] Failed to load patterns from SQLite:",p(e))}}indexPattern(e){this.patternCache.set(e.id,e),this.domainIndex.has(e.qeDomain)||this.domainIndex.set(e.qeDomain,new Set),this.domainIndex.get(e.qeDomain).add(e.id),this.typeIndex.has(e.patternType)||this.typeIndex.set(e.patternType,new Set),this.typeIndex.get(e.patternType).add(e.id);let t=e.tier==="long-term"?"long-term":"short-term";e.tier!==t&&(e.tier=t),this.tierIndex.get(t).add(e.id)}unindexPattern(e){this.patternCache.delete(e.id),this.domainIndex.get(e.qeDomain)?.delete(e.id),this.typeIndex.get(e.patternType)?.delete(e.id),this.tierIndex.get(e.tier)?.delete(e.id),this.hdcCache.delete(e.id)}async store(e){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let t=M(e);if(!t.valid)return S(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return S(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));if((this.domainIndex.get(e.qeDomain)?.size||0)>=this.config.maxPatternsPerDomain&&await this.cleanupDomain(e.qeDomain),this.indexPattern(e),this.sqliteStore)try{this.sqliteStore.storePattern(e,e.embedding)}catch(s){console.warn(`[PatternStore] SQLite persist failed for ${e.id}:`,p(s))}if(e.embedding){let s=await this.ensureHNSW();if(s)try{await s.insert(e.id,e.embedding,{filePath:e.patternType,lineCoverage:e.confidence*100,branchCoverage:e.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-e.confidence,lastUpdated:Date.now(),totalLines:0})}catch(i){console.warn(`[PatternStore] Failed to index embedding for ${e.id}:`,i)}}if(x())try{let i=N().fingerprint({id:e.id,domain:e.qeDomain,type:e.patternType,content:e.description});this.hdcCache.set(e.id,i.vector)}catch(s){console.debug(`[PatternStore] HDC fingerprint failed for ${e.id}:`,p(s))}if(C()&&e.embedding)try{H(e.embedding.length).store(new Float32Array(e.embedding),{id:e.id,name:e.name,domain:e.qeDomain})}catch(s){console.debug(`[PatternStore] Hopfield store failed for ${e.id}:`,p(s))}if(v()&&this.deltaTracker)try{let s={id:e.id,name:e.name,confidence:e.confidence,qualityScore:e.qualityScore,usageCount:e.usageCount,successRate:e.successRate,tier:e.tier};this.deltaTracker.createGenesis(e.id,s)}catch(s){console.debug(`[PatternStore] Delta genesis for ${e.id}:`,p(s))}return y(e.id)}async create(e){let t=new Date,n=e.qeDomain||this.detectDomainFromType(e.patternType),s={id:D(),patternType:e.patternType,qeDomain:n,domain:n,name:e.name,description:e.description,confidence:e.confidence??.5,usageCount:0,successRate:0,qualityScore:.25,context:{...e.context,tags:e.context?.tags||[]},template:{...e.template,example:void 0},embedding:e.embedding,tier:"short-term",createdAt:t,lastUsedAt:t,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},i=await this.store(s);return i.success?y(s):S(i.error)}detectDomainFromType(e){return{"test-template":"test-generation","assertion-pattern":"test-generation","mock-pattern":"test-generation","coverage-strategy":"coverage-analysis","mutation-strategy":"test-generation","api-contract":"contract-testing","visual-baseline":"visual-accessibility","a11y-check":"visual-accessibility","perf-benchmark":"chaos-resilience","flaky-fix":"test-execution","refactor-safe":"code-intelligence","error-handling":"test-generation"}[e]||"test-generation"}async get(e){return this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise,this.patternCache.get(e)??null}async search(e,t={}){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let n=performance.now(),s=t.limit||10,i=[];try{if(Array.isArray(e)&&C())try{let a=H(e.length);if(a.getPatternCount()>0){let m=a.recall(new Float32Array(e));if(m&&m.similarity>.98){let d=m.metadata.id,c=await this.get(d);if(c&&this.matchesFilters(c,t)){let g=this.calculateReuseInfo(c,m.similarity);i.push({pattern:c,score:m.similarity,matchType:"vector",similarity:m.similarity,canReuse:g.canReuse,estimatedTokenSavings:g.estimatedTokenSavings,reuseConfidence:g.reuseConfidence})}}}}catch(a){console.debug("[PatternStore] Hopfield recall failed:",p(a))}if(Array.isArray(e)&&t.useVectorSearch!==!1){let a=await this.ensureHNSW();if(a){let m=await a.search(e,s*2);for(let d of m){let c=await this.get(d.key);if(c&&this.matchesFilters(c,t)){let g=this.calculateReuseInfo(c,d.score);i.push({pattern:c,score:d.score,matchType:"vector",similarity:d.score,canReuse:g.canReuse,estimatedTokenSavings:g.estimatedTokenSavings,reuseConfidence:g.reuseConfidence})}}}}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let a=this.sqliteStore.searchFTS(e,s*2);if(a.length>0){let m=new Map(a.map(c=>[c.id,c.ftsScore])),d=new Set(i.map(c=>c.pattern.id));for(let c of i){let g=m.get(c.pattern.id);g!==void 0&&(c.score=.75*c.score+.25*g)}for(let c of a){if(d.has(c.id))continue;let g=await this.get(c.id);if(g&&this.matchesFilters(g,t)){let b=this.calculateReuseInfo(g,c.ftsScore);i.push({pattern:g,score:.5*c.ftsScore,matchType:"exact",similarity:c.ftsScore,canReuse:b.canReuse,estimatedTokenSavings:b.estimatedTokenSavings,reuseConfidence:b.reuseConfidence})}}}}catch{}if(typeof e=="string"||i.length<s){let a=await this.searchByText(typeof e=="string"?e:"",t,s-i.length),m=new Set(i.map(d=>d.pattern.id));for(let d of a)m.has(d.pattern.id)||i.push(d)}let r=720*60*60*1e3,u=Date.now();for(let a of i){let m=a.pattern.lastUsedAt?.getTime()??a.pattern.createdAt.getTime(),d=u-m,c=Math.pow(.5,d/r),g=a.pattern.usageCount>0?c:.5;a.score=a.score*(.7+.3*g)}i.sort((a,m)=>m.score-a.score);let f=i;t.filter&&(f=z(i,t.filter));let l=f.slice(0,s),h=performance.now()-n;return this.recordSearchLatency(h),y(l)}catch(r){return S(F(r))}}async searchByText(e,t,n){let s=[],i=e.toLowerCase(),r;t.domain?r=this.domainIndex.get(t.domain)||new Set:t.patternType?r=this.typeIndex.get(t.patternType)||new Set:t.tier?r=this.tierIndex.get(t.tier)||new Set:r=new Set(this.patternCache.keys());let u=[...r];if(x()&&i&&this.hdcCache.size>0)try{let f=N(),l=f.fingerprint({id:"query",domain:t.domain??"unknown",type:t.patternType??"unknown",content:e}),h=u.filter(d=>this.hdcCache.has(d)).map(d=>({id:d,similarity:f.similarity(l.vector,this.hdcCache.get(d))}));h.sort((d,c)=>c.similarity-d.similarity);let a=h.map(d=>d.id),m=u.filter(d=>!this.hdcCache.has(d));u=[...a,...m]}catch{}for(let f of u){if(s.length>=n)break;let l=this.patternCache.get(f);if(!l||!this.matchesFilters(l,t))continue;let h=0;if(i){let a=l.name.toLowerCase(),m=l.description.toLowerCase();a.includes(i)&&(h+=.5),m.includes(i)&&(i.length/m.length>.3?h+=.5:h+=.3);for(let d of l.context.tags)if(d.toLowerCase().includes(i)){h+=.2;break}h=Math.min(h,1)}else h=l.qualityScore;if(h>0||!i){let a=this.calculateReuseInfo(l,h);s.push({pattern:l,score:h||l.qualityScore,matchType:i?"exact":"context",similarity:h||l.qualityScore,canReuse:a.canReuse,estimatedTokenSavings:a.estimatedTokenSavings,reuseConfidence:a.reuseConfidence})}}return s}calculateReuseInfo(e,t){let{reuseOptimization:n}=this.config,s=t>=n.minSimilarityForReuse,i=e.successRate>=n.minSuccessRateForReuse,r=e.lastUsedAt instanceof Date?e.lastUsedAt.getTime():new Date(e.lastUsedAt).getTime(),f=(Date.now()-r)/(1e3*60*60*24)<=n.maxAgeForReuse,l=n.enabled&&e.reusable&&s&&i&&f,h=l?e.averageTokenSavings>0?e.averageTokenSavings:e.tokensUsed||0:0,a=t,m=e.successRate,d=Math.min(e.reuseCount/10,1),c=l?a*.4+m*.4+d*.2:0;return{canReuse:l,estimatedTokenSavings:h,reuseConfidence:c}}matchesFilters(e,t){if(t.patternType&&e.patternType!==t.patternType||t.domain&&e.qeDomain!==t.domain||t.tier&&e.tier!==t.tier||t.minConfidence!==void 0&&e.confidence<t.minConfidence||t.minQualityScore!==void 0&&e.qualityScore<t.minQualityScore)return!1;if(t.context){let n=t.context;if(n.language&&e.context.language!==n.language||n.framework&&e.context.framework!==n.framework||n.testType&&e.context.testType!==n.testType)return!1}return!0}async recordUsage(e,t){let n=await this.get(e);if(!n)return S(new Error(`Pattern not found: ${e}`));let s=new Date,i=n.usageCount+1,r=n.successfulUses+(t?1:0),u=r/i,f=t?.02:-.01,l=Math.max(.1,Math.min(1,n.confidence+f)),h=Q({confidence:l,usageCount:i,successRate:u}),a={...n,usageCount:i,successfulUses:r,successRate:u,confidence:l,qualityScore:h,lastUsedAt:s};if(this.sqliteStore)try{this.sqliteStore.recordUsage(e,t)}catch(c){console.warn(`[PatternStore] SQLite recordUsage failed for ${e}:`,p(c))}if(v()&&this.deltaTracker)try{let c={id:n.id,name:n.name,confidence:n.confidence,qualityScore:n.qualityScore,usageCount:n.usageCount,successRate:n.successRate,tier:n.tier},g={id:a.id,name:a.name,confidence:a.confidence,qualityScore:a.qualityScore,usageCount:a.usageCount,successRate:a.successRate,tier:a.tier};this.deltaTracker.recordDelta(e,c,g,{success:t})}catch(c){console.debug(`[PatternStore] Delta recordDelta for ${e}:`,p(c))}let m=T(a);return m.meetsUsageCriteria&&m.meetsQualityCriteria&&m.meetsCoherenceCriteria&&a.tier==="short-term"?await this.promote(e):this.patternCache.set(e,a),y(void 0)}async promote(e){let t=await this.get(e);if(!t)return S(new Error(`Pattern not found: ${e}`));if(t.tier==="long-term")return y(void 0);let n={...t,tier:"long-term",confidence:Math.min(1,t.confidence+.1)};if(this.tierIndex.get("short-term")?.delete(e),this.tierIndex.get("long-term")?.add(e),this.patternCache.set(e,n),this.sqliteStore)try{this.sqliteStore.promotePattern(e)}catch(s){console.debug("[PatternStore] SQLite promotion error:",s instanceof Error?s.message:s)}return console.log(`[PatternStore] Promoted pattern ${e} (${t.name}) to long-term storage`),y(void 0)}async delete(e){let t=this.patternCache.get(e);if(!t)return S(new Error(`Pattern not found: ${e}`));if(this.unindexPattern(t),this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(n){console.debug("[PatternStore] SQLite deletion error:",n instanceof Error?n.message:n)}if(this.hnswIndex!==null)try{await this.hnswIndex.delete(e)}catch(n){console.debug("[PatternStore] HNSW deletion error:",n instanceof Error?n.message:n)}return y(void 0)}async getStats(){let e={},t={};for(let[f,l]of this.domainIndex)e[f]=l.size;for(let[f,l]of this.typeIndex)t[f]=l.size;let n=0,s=0,i=0,r=0;for(let f of this.patternCache.values())n+=f.confidence,s+=f.qualityScore,i+=f.successRate,r++;let u=this.hnswIndex!==null?await this.hnswIndex.getStats():{nativeHNSW:!1,vectorCount:0,indexSizeBytes:0,lazyLoaded:!0};return{totalPatterns:this.patternCache.size,byTier:{shortTerm:this.tierIndex.get("short-term")?.size||0,longTerm:this.tierIndex.get("long-term")?.size||0},byDomain:e,byType:t,avgConfidence:r>0?n/r:0,avgQualityScore:r>0?s/r:0,avgSuccessRate:r>0?i/r:0,searchOperations:this.stats.searchOperations,avgSearchLatencyMs:this.calculateAvgLatency(),hnswStats:{nativeAvailable:u.nativeHNSW,vectorCount:u.vectorCount,indexSizeBytes:u.indexSizeBytes}}}async cleanup(){let e=0,t=0,n=[],s=[];for(let i of this.patternCache.values()){let r=T(i);if(r.meetsUsageCriteria&&r.meetsQualityCriteria&&r.meetsCoherenceCriteria){s.push(i.id);continue}if(i.tier==="short-term"){let f=i.createdAt instanceof Date?i.createdAt.getTime():new Date(i.createdAt).getTime(),l=Date.now()-f,h=l>10080*60*1e3,a=i.qualityScore<.2,m=i.usageCount===0&&l>1440*60*1e3;(h&&a||m)&&n.push(i.id)}}for(let i of s)(await this.promote(i)).success&&t++;for(let i of n)(await this.delete(i)).success&&e++;return console.log(`[PatternStore] Cleanup: removed ${e}, promoted ${t}`),{removed:e,promoted:t}}async cleanupDomain(e){let t=this.domainIndex.get(e);if(!t||t.size<this.config.maxPatternsPerDomain)return;let n=[];for(let r of t){let u=this.patternCache.get(r);u&&n.push(u)}n.sort((r,u)=>r.qualityScore-u.qualityScore);let s=Math.ceil(n.length*.1),i=0;for(let r of n){if(i>=s)break;r.tier==="short-term"&&(await this.delete(r.id),i++)}}recordSearchLatency(e){this.stats.searchOperations++,this.stats.searchLatencies.push(e),this.stats.searchLatencies.length>1e3&&(this.stats.searchLatencies=this.stats.searchLatencies.slice(-1e3))}calculateAvgLatency(){return this.stats.searchLatencies.length===0?0:this.stats.searchLatencies.reduce((t,n)=>t+n,0)/this.stats.searchLatencies.length}async dispose(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0),this.patternCache.clear(),this.domainIndex.clear(),this.typeIndex.clear(),this.tierIndex.clear(),this.hdcCache.clear(),this.deltaTracker=null,P&&(P.clear(),P=null,E=0),this.initialized=!1}};function me(o,e){return new I(o,e)}export{me as a};
@@ -0,0 +1,146 @@
1
+ if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.0");process.exit(0)}
2
+ import{a as _}from"./chunk-3NZLZHJI.js";import{e as E}from"./chunk-4YS3IJ45.js";import{a as T}from"./chunk-3JPRUND5.js";import{c as h}from"./chunk-4VUPRTVX.js";import{b as p,d as b}from"./chunk-WGMPEW2T.js";import{M as S,j as g}from"./chunk-2I7J3O6V.js";b();T();S();var o=h.create("pattern-lifecycle"),A={promotionRewardThreshold:.7,promotionMinOccurrences:E,promotionMinSuccessRate:.7,deprecationFailureThreshold:3,staleDaysThreshold:30,confidenceDecayRate:.01,minActiveConfidence:.3,maxAgeForActivePatterns:90,promotionActivityWindowDays:30,asymmetricLearning:{}},f=class{constructor(e,t={}){this.db=e;this.config={...A,...t},this.asymmetricEngine=new _(this.config.asymmetricLearning),this.ensureSchema()}config;asymmetricEngine;_witnessChain=null;set witnessChain(e){this._witnessChain=e}_compressionService=null;set compressionService(e){this._compressionService=e}ensureSchema(){try{this.db.prepare(`
3
+ SELECT deprecated_at FROM qe_patterns LIMIT 1
4
+ `).get()}catch(e){o.debug("Adding missing deprecated_at column",{error:e instanceof Error?e.message:String(e)}),this.db.exec(`
5
+ ALTER TABLE qe_patterns ADD COLUMN deprecated_at TEXT DEFAULT NULL
6
+ `),console.log("[PatternLifecycle] Added deprecated_at column to qe_patterns")}try{this.db.prepare(`
7
+ SELECT consecutive_failures FROM qe_patterns LIMIT 1
8
+ `).get()}catch(e){o.debug("Adding missing consecutive_failures column",{error:e instanceof Error?e.message:String(e)}),this.db.exec(`
9
+ ALTER TABLE qe_patterns ADD COLUMN consecutive_failures INTEGER DEFAULT 0
10
+ `),console.log("[PatternLifecycle] Added consecutive_failures column to qe_patterns")}try{this.db.prepare(`
11
+ SELECT promotion_date FROM qe_patterns LIMIT 1
12
+ `).get()}catch(e){o.debug("Adding missing promotion_date column",{error:e instanceof Error?e.message:String(e)}),this.db.exec(`
13
+ ALTER TABLE qe_patterns ADD COLUMN promotion_date TEXT DEFAULT NULL
14
+ `),console.log("[PatternLifecycle] Added promotion_date column to qe_patterns")}}getRecentExperiences(e={}){let t=e.minReward??this.config.promotionRewardThreshold,n=e.limit??100,r=e.sinceDays??7;if(!this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='captured_experiences'").get())return o.debug("captured_experiences table not found"),[];let a=new Date(Date.now()-r*864e5).toISOString().replace("T"," ").slice(0,19);return this.db.prepare(`
15
+ SELECT
16
+ domain as task_type,
17
+ COUNT(*) as count,
18
+ AVG(quality) as avg_reward,
19
+ MAX(quality) as max_reward,
20
+ MIN(quality) as min_reward,
21
+ SUM(CASE WHEN quality >= ? THEN 1 ELSE 0 END) as success_count,
22
+ GROUP_CONCAT(DISTINCT agent) as actions,
23
+ MAX(started_at) as latest_at
24
+ FROM captured_experiences
25
+ WHERE started_at >= ?
26
+ AND quality >= ?
27
+ AND agent != 'cli-hook'
28
+ GROUP BY domain
29
+ HAVING COUNT(*) >= ?
30
+ ORDER BY avg_reward DESC
31
+ LIMIT ?
32
+ `).all(t,a,t*.5,this.config.promotionMinOccurrences,n).map(i=>({taskType:i.task_type,domain:this.taskTypeToQEDomain(i.task_type),count:i.count,avgReward:i.avg_reward,maxReward:i.max_reward,minReward:i.min_reward,actions:i.actions?i.actions.split(",").filter(Boolean):[],successCount:i.success_count,latestAt:new Date(i.latest_at)}))}taskTypeToQEDomain(e){let t={generate:"test-generation","test-generation":"test-generation",test:"test-generation",analyze:"coverage-analysis",coverage:"coverage-analysis","coverage-analysis":"coverage-analysis",run:"test-execution",execute:"test-execution","test-execution":"test-execution",report:"quality-assessment",quality:"quality-assessment",assessment:"quality-assessment",security:"security-compliance",sast:"security-compliance",audit:"security-compliance",defect:"defect-intelligence",predict:"defect-intelligence",bug:"defect-intelligence",requirements:"requirements-validation",validation:"requirements-validation",code:"code-intelligence",complexity:"code-intelligence",contract:"contract-testing",api:"contract-testing",visual:"visual-accessibility",a11y:"visual-accessibility",accessibility:"visual-accessibility",chaos:"chaos-resilience",resilience:"chaos-resilience",flaky:"chaos-resilience",learning:"learning-optimization",optimize:"learning-optimization"},n=e.toLowerCase();for(let[r,s]of Object.entries(t))if(n.includes(r))return s;return null}taskTypeToPatternType(e){let t={generate:"test-template",test:"test-template",coverage:"coverage-strategy",analyze:"coverage-strategy",mock:"mock-pattern",stub:"mock-pattern",assert:"assertion-pattern",expect:"assertion-pattern",security:"assertion-pattern",contract:"api-contract",api:"api-contract",visual:"visual-baseline",screenshot:"visual-baseline",a11y:"a11y-check",accessibility:"a11y-check",perf:"perf-benchmark",load:"perf-benchmark",stress:"perf-benchmark",flaky:"flaky-fix",retry:"flaky-fix",refactor:"refactor-safe",error:"error-handling",exception:"error-handling"},n=e.toLowerCase();for(let[r,s]of Object.entries(t))if(n.includes(r))return s;return"test-template"}findPatternCandidates(e){let t=[];for(let n of e){let r=n.avgReward>=this.config.promotionRewardThreshold,s=n.count>=this.config.promotionMinOccurrences,a=n.successCount/n.count,c=a>=this.config.promotionMinSuccessRate;if(r&&s&&c){let i=n.domain||"code-intelligence",d=this.taskTypeToPatternType(n.taskType);if(this.findExistingPattern(n.taskType,i))continue;t.push({name:`${n.taskType}-success-pattern`,domain:i,patternType:d,confidence:Math.min(.95,n.avgReward*.9),sourceExperiences:n.count,avgReward:n.avgReward,successRate:a,actions:n.actions.slice(0,5),templateContent:this.generateTemplateContent(n)})}}return t}findExistingPattern(e,t){let n=this.db.prepare(`
33
+ SELECT * FROM qe_patterns
34
+ WHERE name LIKE ? AND qe_domain = ? AND deprecated_at IS NULL
35
+ LIMIT 1
36
+ `).get(`%${e}%`,t);return n?this.rowToPattern(n):null}generateTemplateContent(e){let t=e.actions.map((n,r)=>`${r+1}. ${n}`).join(`
37
+ `);return`Task Type: ${e.taskType}
38
+ Domain: ${e.domain||"general"}
39
+ Average Reward: ${e.avgReward.toFixed(3)}
40
+ Success Rate: ${(e.successCount/e.count*100).toFixed(1)}%
41
+
42
+ Typical Actions:
43
+ ${t||"N/A"}
44
+
45
+ Pattern extracted from ${e.count} successful experiences.`}checkPromotion(e){let t=this.getPattern(e);if(!t)return{shouldPromote:!1,meetsRewardThreshold:!1,meetsOccurrenceThreshold:!1,meetsSuccessRateThreshold:!1,meetsActivityWindow:!1,currentReward:0,currentOccurrences:0,currentSuccessRate:0};let n=t.qualityScore,r=n>=this.config.promotionRewardThreshold,s=t.usageCount>=this.config.promotionMinOccurrences,a=t.successRate>=this.config.promotionMinSuccessRate,c=this.config.promotionActivityWindowDays*24*60*60*1e3,i=t.lastUsedAt?.getTime()??t.createdAt.getTime(),d=Date.now()-i<c;return{shouldPromote:t.tier==="short-term"&&r&&s&&a&&d,meetsRewardThreshold:r,meetsOccurrenceThreshold:s,meetsSuccessRateThreshold:a,meetsActivityWindow:d,currentReward:n,currentOccurrences:t.usageCount,currentSuccessRate:t.successRate}}promotePattern(e){return this.checkPromotion(e).shouldPromote?(this.db.prepare(`
46
+ UPDATE qe_patterns
47
+ SET tier = 'long-term',
48
+ promotion_date = datetime('now'),
49
+ confidence = MIN(1.0, confidence + 0.1),
50
+ updated_at = datetime('now')
51
+ WHERE id = ?
52
+ `).run(e),console.log(`[PatternLifecycle] Promoted pattern ${e} to long-term`),!0):!1}promoteEligiblePatterns(){let e=this.db.prepare(`
53
+ SELECT id FROM qe_patterns
54
+ WHERE tier = 'short-term' AND deprecated_at IS NULL
55
+ `).all(),t=0;for(let{id:n}of e)this.promotePattern(n)&&t++;return{promoted:t,checked:e.length}}runPromotionSweep(){return this.promoteEligiblePatterns()}checkDeprecation(e){let t=this.getPattern(e);if(!t)return{shouldDeprecate:!1,reason:null};if(t.deprecated_at)return{shouldDeprecate:!1,reason:null};let n=t.consecutive_failures||0;if(n>=this.config.deprecationFailureThreshold)return{shouldDeprecate:!0,reason:"failures",consecutiveFailures:n};let r=t.lastUsedAt instanceof Date?t.lastUsedAt.getTime():new Date(t.lastUsedAt).getTime(),s=(Date.now()-r)/(1e3*60*60*24);if(s>=this.config.staleDaysThreshold)return{shouldDeprecate:!0,reason:"stale",daysSinceLastUse:s};if(t.confidence<this.config.minActiveConfidence)return{shouldDeprecate:!0,reason:"low_confidence",currentConfidence:t.confidence};let a=t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime(),c=(Date.now()-a)/(1e3*60*60*24);return c>=this.config.maxAgeForActivePatterns&&t.usageCount<5?{shouldDeprecate:!0,reason:"age",ageInDays:c}:{shouldDeprecate:!1,reason:null}}deprecatePattern(e,t){let n=this.checkDeprecation(e);if(!n.shouldDeprecate&&!t)return!1;let r=t||n.reason||"manual";this.db.prepare(`
56
+ UPDATE qe_patterns
57
+ SET deprecated_at = datetime('now'),
58
+ updated_at = datetime('now')
59
+ WHERE id = ?
60
+ `).run(e);let s=this.getPattern(e);if(s){let a={deprecation_reason:r,deprecated_at:new Date().toISOString(),final_confidence:s.confidence,final_success_rate:s.successRate,total_usage:s.usageCount};this.db.prepare(`
61
+ UPDATE qe_patterns
62
+ SET context_json = json_patch(COALESCE(context_json, '{}'), ?)
63
+ WHERE id = ?
64
+ `).run(JSON.stringify({deprecation_metadata:a}),e)}return console.log(`[PatternLifecycle] Deprecated pattern ${e}: ${r}`),!0}deprecateStalePatterns(){let e=this.db.prepare(`
65
+ SELECT id FROM qe_patterns
66
+ WHERE deprecated_at IS NULL
67
+ `).all(),t=0;for(let{id:n}of e){let r=this.checkDeprecation(n);r.shouldDeprecate&&(this.deprecatePattern(n,r.reason||void 0),t++)}return{deprecated:t,checked:e.length}}applyConfidenceDecay(e=1){let t=1-this.config.confidenceDecayRate*e,n=Date.now()-e*24*60*60*1e3,r=this.db.prepare(`
68
+ UPDATE qe_patterns
69
+ SET confidence = MAX(?, confidence * ?),
70
+ updated_at = datetime('now')
71
+ WHERE deprecated_at IS NULL
72
+ AND (last_used_at IS NULL OR datetime(last_used_at) < datetime(?, 'unixepoch'))
73
+ `).run(this.config.minActiveConfidence,t,n/1e3);return{updated:r.changes,decayed:r.changes}}recordUsage(e,t){t?this.db.prepare(`
74
+ UPDATE qe_patterns
75
+ SET usage_count = usage_count + 1,
76
+ successful_uses = successful_uses + 1,
77
+ consecutive_failures = 0,
78
+ confidence = MIN(1.0, confidence + 0.02),
79
+ success_rate = CAST(successful_uses + 1 AS REAL) / CAST(usage_count + 1 AS REAL),
80
+ last_used_at = datetime('now'),
81
+ updated_at = datetime('now')
82
+ WHERE id = ?
83
+ `).run(e):this.db.prepare(`
84
+ UPDATE qe_patterns
85
+ SET usage_count = usage_count + 1,
86
+ consecutive_failures = consecutive_failures + 1,
87
+ confidence = MAX(0.1, confidence - 0.05),
88
+ success_rate = CAST(successful_uses AS REAL) / CAST(usage_count + 1 AS REAL),
89
+ last_used_at = datetime('now'),
90
+ updated_at = datetime('now')
91
+ WHERE id = ?
92
+ `).run(e),this.db.prepare(`
93
+ UPDATE qe_patterns
94
+ SET quality_score = confidence * 0.3 + (MIN(usage_count, 100) / 100.0) * 0.2 + success_rate * 0.5
95
+ WHERE id = ?
96
+ `).run(e)}recordAsymmetricOutcome(e,t,n){let r=this.getPattern(e);if(!r)return;let s=r.confidence,a=this.asymmetricEngine.computeConfidenceUpdate(s,t?"success":"failure",n);this.db.prepare(`
97
+ UPDATE qe_patterns
98
+ SET confidence = ?,
99
+ usage_count = usage_count + 1,
100
+ successful_uses = CASE WHEN ? THEN successful_uses + 1 ELSE successful_uses END,
101
+ consecutive_failures = CASE WHEN ? THEN 0 ELSE consecutive_failures + 1 END,
102
+ success_rate = CAST(CASE WHEN ? THEN successful_uses + 1 ELSE successful_uses END AS REAL) / CAST(usage_count + 1 AS REAL),
103
+ last_used_at = datetime('now'),
104
+ updated_at = datetime('now')
105
+ WHERE id = ?
106
+ `).run(a,t?1:0,t?1:0,t?1:0,e),this.asymmetricEngine.shouldQuarantine(a,n).shouldQuarantine&&this.quarantinePattern(e)}quarantinePattern(e){if(this.db.prepare(`
107
+ UPDATE qe_patterns
108
+ SET deprecated_at = datetime('now'),
109
+ updated_at = datetime('now')
110
+ WHERE id = ? AND deprecated_at IS NULL
111
+ `).run(e).changes>0){console.log(`[PatternLifecycle] Quarantined pattern ${e} (asymmetric confidence drop)`);try{this._witnessChain?.append("PATTERN_QUARANTINE",{patternId:e},"pattern-lifecycle")}catch{}return!0}return!1}checkRehabilitation(e,t){return this.asymmetricEngine.checkRehabilitation(t).canRehabilitate}rehabilitatePattern(e){return this.db.prepare(`
112
+ UPDATE qe_patterns
113
+ SET deprecated_at = NULL,
114
+ consecutive_failures = 0,
115
+ confidence = 0.5,
116
+ updated_at = datetime('now')
117
+ WHERE id = ?
118
+ `).run(e).changes>0?(console.log(`[PatternLifecycle] Rehabilitated pattern ${e} (10+ consecutive successes)`),!0):!1}getAsymmetricEngine(){return this.asymmetricEngine}compressPatternEmbedding(e){if(!g()||!this._compressionService)return null;let t=this.getPattern(e);if(!t||!t.embedding||t.embedding.length===0)return null;let n=t.lastUsedAt??t.createdAt,r=this._compressionService.classifyTier(n),s=new Float32Array(t.embedding),a=this._compressionService.compress(s,r);return o.debug("Compressed pattern embedding",{patternId:e,tier:r,ratio:(a.originalByteSize/a.compressedByteSize).toFixed(1)}),a}decompressPatternEmbedding(e){return this._compressionService?this._compressionService.decompress(e):null}compressAllPatternEmbeddings(){if(!g()||!this._compressionService)return 0;let e=this.db.prepare(`
119
+ SELECT id FROM qe_patterns
120
+ WHERE deprecated_at IS NULL
121
+ `).all(),t=0;for(let{id:n}of e)this.compressPatternEmbedding(n)&&t++;return o.info("Bulk pattern embedding compression complete",{total:e.length,compressed:t}),t}getStats(){let e=this.db.prepare(`
122
+ SELECT
123
+ COUNT(*) as total,
124
+ SUM(CASE WHEN deprecated_at IS NULL THEN 1 ELSE 0 END) as active,
125
+ SUM(CASE WHEN deprecated_at IS NOT NULL THEN 1 ELSE 0 END) as deprecated,
126
+ SUM(CASE WHEN tier = 'long-term' AND deprecated_at IS NULL THEN 1 ELSE 0 END) as promoted,
127
+ SUM(CASE WHEN tier = 'short-term' AND deprecated_at IS NULL THEN 1 ELSE 0 END) as short_term,
128
+ SUM(CASE WHEN tier = 'long-term' THEN 1 ELSE 0 END) as long_term,
129
+ AVG(CASE WHEN deprecated_at IS NULL THEN confidence ELSE NULL END) as avg_confidence,
130
+ AVG(CASE WHEN deprecated_at IS NULL THEN success_rate ELSE NULL END) as avg_success_rate
131
+ FROM qe_patterns
132
+ `).get(),t=this.db.prepare(`
133
+ SELECT COUNT(*) as count
134
+ FROM qe_patterns
135
+ WHERE deprecated_at IS NULL
136
+ AND (
137
+ consecutive_failures >= ?
138
+ OR confidence < ?
139
+ OR (julianday('now') - julianday(COALESCE(last_used_at, created_at))) >= ?
140
+ )
141
+ `).get(this.config.deprecationFailureThreshold-1,this.config.minActiveConfidence+.1,this.config.staleDaysThreshold-7);return{totalPatterns:e.total||0,activePatterns:e.active||0,deprecatedPatterns:e.deprecated||0,promotedPatterns:e.promoted||0,shortTermPatterns:e.short_term||0,longTermPatterns:e.long_term||0,avgConfidence:e.avg_confidence||0,avgSuccessRate:e.avg_success_rate||0,patternsNearDeprecation:t.count||0}}getPattern(e){let t=this.db.prepare(`
142
+ SELECT * FROM qe_patterns WHERE id = ?
143
+ `).get(e);return t?this.rowToPattern(t):null}rowToPattern(e){return{id:e.id,patternType:e.pattern_type,qeDomain:e.qe_domain,domain:e.domain,name:e.name,description:e.description||"",confidence:e.confidence,usageCount:e.usage_count,successRate:e.success_rate,qualityScore:e.quality_score,tier:e.tier,template:p(e.template_json||"{}"),context:p(e.context_json||"{}"),createdAt:new Date(e.created_at),lastUsedAt:e.last_used_at?new Date(e.last_used_at):new Date(e.created_at),successfulUses:e.successful_uses,reusable:e.reusable===1,reuseCount:e.reuse_count||0,averageTokenSavings:e.average_token_savings||0}}};function w(m,e){return new f(m,e)}import*as u from"fs";import*as l from"path";var D={"pattern-learned":"\u{1F9E0}","pattern-promoted":"\u2B06\uFE0F","pattern-quarantined":"\u{1F512}","experience-captured":"\u{1F4F8}","search-performed":"\u{1F50D}","reward-assigned":"\u{1F3AF}"},y=class{config;buffer=[];flushTimer=null;constructor(e){this.config={logDir:e?.logDir??l.join(process.cwd(),".agentic-qe","logs"),enabled:e?.enabled??!0,maxEntriesPerDay:e?.maxEntriesPerDay??500}}log(e){this.config.enabled&&(this.buffer.push(e),this.buffer.length>=10&&this.flush())}flush(){if(this.buffer.length===0)return;let e=new Date().toISOString().split("T")[0],t=l.join(this.config.logDir,`${e}.md`);try{u.mkdirSync(this.config.logDir,{recursive:!0});let n=this.buffer.splice(0,this.buffer.length),r=[];u.existsSync(t)||(r.push(`# AQE Daily Log \u2014 ${e}
144
+ `),r.push("| Time | Event | Summary |"),r.push("|------|-------|---------|"));for(let s of n){let a=s.timestamp.toISOString().split("T")[1]?.slice(0,8)??"00:00:00",c=D[s.type]??"\u{1F4DD}",i=s.summary.replace(/\\/g,"\\\\").replace(/\|/g,"\\|").replace(/\n/g," ");r.push(`| ${a} | ${c} ${s.type} | ${i} |`)}u.appendFileSync(t,r.join(`
145
+ `)+`
146
+ `)}catch(n){console.debug("[DailyLog] Write failed:",n)}}getTodayLogPath(){let e=new Date().toISOString().split("T")[0];return l.join(this.config.logDir,`${e}.md`)}dispose(){this.flush(),this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null)}};export{w as a,y 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{createRequire as t}from"module";var o=t(import.meta.url),e=o("hnswlib-node"),i=e,{RuvectorLayer:r,TensorCompress:a,differentiableSearch:c,hierarchicalForward:l,getCompressionLevel:s,init:p,FlashAttention:d,DotProductAttention:m,MultiHeadAttention:u,HyperbolicAttention:A,LinearAttention:h,MoEAttention:f,SonaEngine:_,pipeline:b}=e||{};export{i as a,r as b,a as c,c as d,l as e,s as f,p as g,d as h,m as i,u as j,A as k,h as l,f as m,_ as n,b as o};
@@ -0,0 +1,3 @@
1
+ if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.0");process.exit(0)}
2
+ import{b as r,d as f}from"./chunk-WGMPEW2T.js";import{a as d}from"./chunk-4I2IOUS4.js";f();import{existsSync as i,readFileSync as a}from"node:fs";import{join as s}from"node:path";import{execSync as p}from"node:child_process";var c=null,u=0,g=6e4;function F(){c=null,u=0}function x(e){if(c&&Date.now()-u<g)return c;let n=m(e);return c=n,u=Date.now(),n}function m(e){let n=w(e);if(n)return n;let o=h(e);if(o)return o;let t=v(e);return t||{available:!1}}function w(e){let n=s(e,".claude","mcp.json");if(i(n))try{let t=r(a(n,"utf-8"));if(t.mcpServers?.ruflo||t.mcpServers?.["claude-flow"])return{available:!0,method:"mcp-config"}}catch{}let o=s(e,".claude","settings.json");if(i(o))try{let t=r(a(o,"utf-8")),l=t.mcpServers||t.mcp?.servers||{};if(l.ruflo||l["claude-flow"]||l["@anthropic/claude-flow"])return{available:!0,method:"mcp-config"}}catch{}return null}function h(e){let n=s(e,"package.json");if(!i(n))return null;try{let o=r(a(n,"utf-8")),t={...o.dependencies,...o.devDependencies};if(t.ruflo||t["@claude-flow/cli"]||t["claude-flow"])return{available:!0,method:"npm-dependency"}}catch{}return null}function v(e){for(let n of["ruflo","@claude-flow/cli"])try{return{available:!0,method:"npx-cached",version:p(`npx --no-install ${n} --version`,{encoding:"utf-8",timeout:5e3,cwd:e,stdio:["pipe","pipe","pipe"]}).trim().match(/\d+\.\d+\.\d+[\w.-]*/)?.[0]}}catch{}return null}function b(){for(let e of["ruflo","@claude-flow/cli"])try{return d.resolve(`${e}/package.json`),e}catch{}return"ruflo"}function S(){return[" Claude Flow not found \u2014 running in standalone mode.",""," Claude Flow adds optional features:"," - SONA trajectory tracking (reinforcement learning)"," - 3-tier model routing (haiku / sonnet / opus)"," - Codebase pretrain analysis",""," To install later:"," npm install -g ruflo"," claude mcp add ruflo -- npx -y ruflo@3.5.18"," aqe init --auto --with-claude-flow"].join(`
3
+ `)}export{F as a,x as b,b as c,S as d};
@@ -0,0 +1,3 @@
1
+ if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.0");process.exit(0)}
2
+ import a from"chalk";import{existsSync as m,statSync as V}from"fs";import{join as p,relative as P}from"path";var l=class{static prompt(t,e){return new Promise(r=>{t.question(e,s=>{r(s)})})}static printStepHeader(t,e,r){console.log(""),console.log(a.cyan(`Step ${t}: ${e}`)),r&&console.log(a.gray(r)),console.log("")}static printWizardHeader(t,e){console.log(""),console.log(a.blue("========================================")),console.log(a.blue.bold(` ${t}`)),console.log(a.blue("========================================")),e&&console.log(a.gray(e)),console.log(a.gray("Press Ctrl+C to cancel at any time")),console.log("")}static printSummaryHeader(){console.log(""),console.log(a.blue("========================================")),console.log(a.blue.bold(" Configuration Summary")),console.log(a.blue("========================================")),console.log("")}static printSummaryField(t,e,r){let s=r?.indent??" ",i=r?.maxItems??5,c=r?.formatValue??(o=>a.cyan(o));if(Array.isArray(e))e.length===0?console.log(a.white(`${s}${t}: ${a.gray("(none)")}`)):e.length<=i?console.log(a.white(`${s}${t}: ${c(e.join(", "))}`)):(console.log(a.white(`${s}${t}:`)),e.slice(0,i).forEach(o=>{console.log(a.gray(`${s} - ${o}`))}),console.log(a.gray(`${s} ... and ${e.length-i} more`)));else{let o=t.padEnd(16);console.log(a.white(`${s}${o}${c(e)}`))}}static printDerivedSettings(t,e=" "){console.log(""),console.log(a.gray(`${e}Derived settings:`));for(let[r,s]of Object.entries(t))console.log(a.gray(`${e} ${r}: ${s}`));console.log("")}};var h=class u{static getSourceDirectories(t){let e=[],r=["src","lib","app","packages","api"];for(let s of r){let i=p(t,s);m(i)&&V(i).isDirectory()&&e.push(s)}return e}static getCoverageTargets(t){let e=u.getSourceDirectories(t),r=["coverage","coverage/lcov.info","coverage/coverage-final.json",".nyc_output"];for(let s of r){let i=p(t,s);m(i)&&e.push(s)}return e}static getSecurityTargets(t){let e=u.getSourceDirectories(t),r=["package.json","package-lock.json","yarn.lock","pnpm-lock.yaml",".env",".env.example","docker-compose.yml","Dockerfile"];for(let s of r){let i=p(t,s);m(i)&&e.push(s)}return e}static getTestSourceFiles(t){let e=[],r=["src","lib","app","packages"];for(let s of r){let i=p(t,s);m(i)&&V(i).isDirectory()&&(e.push(`${s}/**/*.ts`),e.push(s))}return m(p(t,"src"))&&(e.push("src/services/**/*.ts"),e.push("src/utils/**/*.ts"),e.push("src/components/**/*.tsx")),e}static checkPatternsExist(t){return[p(t,".agentic-qe","patterns"),p(t,".agentic-qe","memory.db"),p(t,".aqe","patterns"),p(t,"data","patterns")].some(r=>m(r))}},f=class{static relativePath(t,e){return P(e,t)||"."}static yesNo(t){return t?"Yes":"No"}static enabledDisabled(t){return t?"Enabled":"Disabled"}static percentage(t){return`${t}%`}static truncatedList(t,e=5){return t.length===0?"(none)":t.length<=e?t.join(", "):`${t.slice(0,e).join(", ")}... and ${t.length-e} more`}};import n from"chalk";import{existsSync as w}from"fs";import{resolve as I}from"path";var d=class{constructor(t){this.defaultValue=t}description;getDefaultValue(){return this.defaultValue}success(t){return{value:t,continue:!0}}cancelled(){return{value:this.defaultValue,continue:!1}}error(t){return{value:this.defaultValue,continue:!1,error:t}}};var y=class extends d{id;stepNumber;title;description;options;validValues;constructor(t){super(t.defaultValue),this.id=t.id,this.stepNumber=t.stepNumber,this.title=t.title,this.description=t.description,this.options=t.options,this.validValues=t.validValues}async execute(t){if(t.nonInteractive)return this.success(this.defaultValue);l.printStepHeader(this.stepNumber,this.title,this.description),this.options.forEach(i=>{let c=[];i.isRecommended?c.push(n.green(" (recommended)")):(i.isDefault||i.value===this.defaultValue)&&c.push(n.green(" (default)")),console.log(n.white(` ${i.key}. ${i.label||i.value}${c.join("")}`)),i.description&&console.log(n.gray(` ${i.description}`))}),console.log("");let r=(await l.prompt(t.rl,`Select ${this.title.toLowerCase()} [${n.gray(String(this.defaultValue))}]: `)).trim();if(!r)return this.success(this.defaultValue);let s=parseInt(r,10);return s>=1&&s<=this.options.length?this.success(this.options[s-1].value):this.validValues.includes(r)?this.success(r):(console.log(n.yellow(` Invalid input, using default: ${this.defaultValue}`)),this.success(this.defaultValue))}},b=class extends d{id;stepNumber;title;description;options;validValues;instructions;allowEmpty;constructor(t){super(t.defaultValue),this.id=t.id,this.stepNumber=t.stepNumber,this.title=t.title,this.description=t.description,this.options=t.options,this.validValues=t.validValues,this.instructions=t.instructions,this.allowEmpty=t.allowEmpty??!1}async execute(t){if(t.nonInteractive)return this.success(this.defaultValue);l.printStepHeader(this.stepNumber,this.title,this.description),this.instructions&&(console.log(n.gray(this.instructions)),console.log("")),this.options.forEach(o=>{let N=o.isDefaultSelected||this.defaultValue.includes(o.value)?n.green(" *"):"";console.log(n.white(` ${o.key}. ${o.label||o.value}${N}`)),o.description&&console.log(n.gray(` ${o.description}`))}),console.log(""),console.log(n.gray(" * = included in default selection")),console.log("");let e=this.defaultValue.join(","),s=(await l.prompt(t.rl,`Select options [${n.gray(e)}]: `)).trim();if(!s)return this.success(this.defaultValue);let i=s.split(",").map(o=>o.trim().toLowerCase()).filter(o=>o.length>0),c=[];for(let o of i){let g=parseInt(o,10);g>=1&&g<=this.options.length?c.push(this.options[g-1].value):this.validValues.includes(o)&&c.push(o)}return c.length===0?this.allowEmpty?this.success([]):(console.log(n.yellow(` Invalid input, using default: ${e}`)),this.success(this.defaultValue)):this.success([...new Set(c)])}},v=class extends d{id;stepNumber;title;description;additionalInfo;constructor(t){super(t.defaultValue),this.id=t.id,this.stepNumber=t.stepNumber,this.title=t.title,this.description=t.description,this.additionalInfo=t.additionalInfo}async execute(t){if(t.nonInteractive)return this.success(this.defaultValue);l.printStepHeader(this.stepNumber,this.title,this.description),this.additionalInfo&&(console.log(n.gray(this.additionalInfo)),console.log(""));let e=this.defaultValue?"Y/n":"y/N",s=(await l.prompt(t.rl,`${this.title}? [${n.gray(e)}]: `)).trim().toLowerCase();return s===""?this.success(this.defaultValue):s==="n"||s==="no"?this.success(!1):s==="y"||s==="yes"?this.success(!0):this.success(this.defaultValue)}},x=class extends d{id;stepNumber;title;description;presets;min;max;constructor(t){super(t.defaultValue),this.id=t.id,this.stepNumber=t.stepNumber,this.title=t.title,this.description=t.description,this.presets=t.presets,this.min=t.min,this.max=t.max}async execute(t){if(t.nonInteractive)return this.success(this.defaultValue);l.printStepHeader(this.stepNumber,this.title,this.description),this.presets&&this.presets.length>0&&(this.presets.forEach(i=>{let c=i.value===this.defaultValue?n.green(" (default)"):"";console.log(n.gray(` ${i.key}. ${i.label}${c}`))}),this.min!==void 0&&this.max!==void 0&&console.log(n.gray(` Or enter a custom number (${this.min}-${this.max})`)),console.log(""));let r=(await l.prompt(t.rl,`${this.title} [${n.gray(String(this.defaultValue))}]: `)).trim();if(!r)return this.success(this.defaultValue);let s=parseInt(r,10);if(this.presets){let i=s;if(i>=1&&i<=this.presets.length)return this.success(this.presets[i-1].value)}return isNaN(s)?(console.log(n.yellow(` Invalid input, using default: ${this.defaultValue}`)),this.success(this.defaultValue)):this.min!==void 0&&s<this.min?(console.log(n.yellow(` Value too low, using minimum: ${this.min}`)),this.success(this.min)):this.max!==void 0&&s>this.max?(console.log(n.yellow(` Value too high, using maximum: ${this.max}`)),this.success(this.max)):this.success(s)}},C=class extends d{id;stepNumber;title;description;examples;suggestionsProvider;validatePath;constructor(t){super(t.defaultValue),this.id=t.id,this.stepNumber=t.stepNumber,this.title=t.title,this.description=t.description,this.examples=t.examples,this.suggestionsProvider=t.suggestionsProvider,this.validatePath=t.validatePath??!0}async execute(t){if(t.nonInteractive){let i=I(t.cwd,this.defaultValue);return this.success(w(i)?i:t.cwd)}if(l.printStepHeader(this.stepNumber,this.title,this.description),this.examples&&(console.log(n.gray(`Examples: ${this.examples}`)),console.log("")),this.suggestionsProvider){let i=this.suggestionsProvider(t.cwd);i.length>0&&(console.log(n.yellow("Detected directories:")),i.slice(0,5).forEach((c,o)=>{console.log(n.gray(` ${o+1}. ${c}`))}),console.log(""))}let r=(await l.prompt(t.rl,`${this.title} [${n.gray(this.defaultValue)}]: `)).trim()||this.defaultValue,s=I(t.cwd,r);return this.validatePath&&!w(s)?(console.log(n.yellow(` Warning: '${r}' does not exist, using current directory.`)),this.success(t.cwd)):this.success(s)}};var T=class extends d{id;stepNumber;title;description;constructor(t){super({}),this.id=t.id,this.stepNumber=t.stepNumber,this.title=t.title,this.description=t.description}async execute(t){if(t.nonInteractive)return this.success({});l.printStepHeader(this.stepNumber,this.title,this.description);let e=await l.prompt(t.rl,`Include patterns [${n.gray("e.g., src/**/*.ts")}]: `),r=await l.prompt(t.rl,`Exclude patterns [${n.gray("e.g., **/*.test.ts,dist/**")}]: `),s={};return e.trim()&&(s.include=e.split(",").map(i=>i.trim()).filter(i=>i.length>0)),r.trim()&&(s.exclude=r.split(",").map(i=>i.trim()).filter(i=>i.length>0)),this.success(s)}};import{createInterface as R}from"readline";import $ from"chalk";var S=class{options;cwd;constructor(t){this.options=t,this.cwd=process.cwd()}async run(){if(this.isNonInteractive())return this.getDefaults();let t=R({input:process.stdin,output:process.stdout});try{this.printHeader();let e={},r=this.getCommands();for(let c of r){let o={rl:t,cwd:this.cwd,results:e,nonInteractive:!1},g=await c.execute(o);if(!g.continue)return this.getCancelled();e[c.id]=g.value}let s=this.buildResult(e);return this.printSummary(s),await this.promptConfirmation(t)?s:this.getCancelled()}finally{t.close()}}printHeader(){l.printWizardHeader(this.getTitle(),this.getSubtitle())}async promptConfirmation(t){console.log("");let r=(await l.prompt(t,`${$.green(this.getConfirmationPrompt())} [${$.gray("Y/n")}]: `)).trim().toLowerCase();return r==="n"||r==="no"?(console.log($.yellow(`
3
+ Wizard cancelled.`)),!1):!0}};export{l as a,h as b,f as c,y as d,b as e,v as f,x as g,C as h,T as i,S as j};
@@ -0,0 +1,2 @@
1
+ if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.0");process.exit(0)}
2
+ import{k as K,o as ot}from"./chunk-JJO7Y4H3.js";import{a as rt}from"./chunk-3JPRUND5.js";import{c as U}from"./chunk-4VUPRTVX.js";import{a as j,c as et}from"./chunk-JZSDOIXA.js";import{a as G,d as at}from"./chunk-DRT3WKQW.js";import{a as nt,b as it}from"./chunk-UFUVUO3J.js";import{c as H,e as V,g as w}from"./chunk-4I2IOUS4.js";var Z={};V(Z,{DotProductAttention:()=>yt,FlashAttention:()=>ft,HyperbolicAttention:()=>bt,LinearAttention:()=>vt,MoEAttention:()=>Et,MultiHeadAttention:()=>At,RuvectorLayer:()=>ut,SonaEngine:()=>P,TensorCompress:()=>mt,default:()=>ct,differentiableSearch:()=>ht,getCompressionLevel:()=>pt,hierarchicalForward:()=>dt,init:()=>gt,pipeline:()=>Ft});import{createRequire as st}from"module";var lt,$,ct,ut,mt,ht,dt,pt,gt,ft,yt,At,bt,vt,Et,P,Ft,k=H(()=>{lt=st(import.meta.url),$=lt("@ruvector/sona"),ct=$,{RuvectorLayer:ut,TensorCompress:mt,differentiableSearch:ht,hierarchicalForward:dt,getCompressionLevel:pt,init:gt,FlashAttention:ft,DotProductAttention:yt,MultiHeadAttention:At,HyperbolicAttention:bt,LinearAttention:vt,MoEAttention:Et,SonaEngine:P,pipeline:Ft}=$||{}});var N={};V(N,{DotProductAttention:()=>It,FlashAttention:()=>zt,HyperbolicAttention:()=>_t,LinearAttention:()=>Ht,MoEAttention:()=>Vt,MultiHeadAttention:()=>qt,RuvectorLayer:()=>Qt,SonaEngine:()=>jt,TensorCompress:()=>Nt,default:()=>xt,differentiableSearch:()=>Ot,getCompressionLevel:()=>Wt,hierarchicalForward:()=>Dt,init:()=>Bt,pipeline:()=>Ut});import{createRequire as kt}from"module";var Rt,X,xt,Qt,Nt,Ot,Dt,Wt,Bt,zt,It,qt,_t,Ht,Vt,jt,Ut,O=H(()=>{Rt=kt(import.meta.url),X=Rt("@ruvector/attention"),xt=X,{RuvectorLayer:Qt,TensorCompress:Nt,differentiableSearch:Ot,hierarchicalForward:Dt,getCompressionLevel:Wt,init:Bt,FlashAttention:zt,DotProductAttention:It,MultiHeadAttention:qt,HyperbolicAttention:_t,LinearAttention:Ht,MoEAttention:Vt,SonaEngine:jt,pipeline:Ut}=X||{}});k();at();import{randomUUID as Ct}from"crypto";rt();import{createRequire as wt}from"module";var f=U.create("sona-three-loop"),S=wt(import.meta.url),M=null,J=!1;function St(){if(J)return M;J=!0;try{let l=S("@ruvector/learning-wasm"),t=S("fs"),e=S("path"),r=e.join(e.dirname(S.resolve("@ruvector/learning-wasm")),"ruvector_learning_wasm_bg.wasm");l.initSync({module:t.readFileSync(r)}),M=l,f.info("WASM MicroLoRA loaded from @ruvector/learning-wasm (6.4x faster than TS)")}catch{M=null,f.debug("@ruvector/learning-wasm not available, using TypeScript MicroLoRA")}return M}var Mt={dimension:384,microLoraLr:.001,consolidationInterval:100,ewcLambda:1e3,taskBoundaryZScoreThreshold:2.5,fisherDecay:.9,fisherSampleSize:200,importanceThreshold:.01},R=class{adaptationVector;baseWeights;lr;adaptationCount=0;constructor(t,e=.001){this.adaptationVector=new Float32Array(t),this.baseWeights=new Float32Array(t),this.lr=e}adapt(t){let e=this.baseWeights.length,r=new Float32Array(e),a=Math.min(t.length,e);for(let n=0;n<e;n++){let o=n<a?t[n]:0;r[n]=this.baseWeights[n]+this.adaptationVector[n]+this.lr*o}for(let n=0;n<a;n++)this.adaptationVector[n]+=this.lr*t[n];return this.adaptationCount++,r}consolidate(){let t=this.adaptationCount,e=this.baseWeights.length;for(let r=0;r<e;r++)this.baseWeights[r]+=this.adaptationVector[r],this.adaptationVector[r]=0;return this.adaptationCount=0,t}getAdaptationCount(){return this.adaptationCount}getEffectiveWeights(){let t=this.baseWeights.length,e=new Float32Array(t);for(let r=0;r<t;r++)e[r]=this.baseWeights[r]+this.adaptationVector[r];return e}getAdaptationMagnitude(){let t=0;for(let e=0;e<this.adaptationVector.length;e++)t+=this.adaptationVector[e]*this.adaptationVector[e];return Math.sqrt(t)}resetAdaptation(){this.adaptationVector.fill(0),this.adaptationCount=0}},x=class{fisherMatrix;optimalParams;lambda;fisherDecay;zScoreThreshold;importanceThreshold;gradientHistory=[];gradientMean=0;gradientVariance=0;taskBoundaryCount=0;consolidationCount=0;constructor(t,e=1e3,r=.9,a=2.5,n=.01){this.fisherMatrix=new Float32Array(t),this.optimalParams=new Float32Array(t),this.lambda=e,this.fisherDecay=r,this.zScoreThreshold=a,this.importanceThreshold=n}detectTaskBoundary(t){let e=0;for(let i=0;i<t.length;i++)e+=t[i]*t[i];if(e=Math.sqrt(e),this.gradientHistory.length<5)return this.gradientHistory.push(e),this.updateGradientStats(),!1;let r=Math.sqrt(this.gradientVariance),a=0,n=Math.abs(e-this.gradientMean);return r>1e-10?a=n/r:n>1e-10&&this.gradientMean>1e-10&&(a=n/(this.gradientMean*.01+1e-10)),this.gradientHistory.push(e),this.gradientHistory.length>100&&this.gradientHistory.shift(),this.updateGradientStats(),a>this.zScoreThreshold?(this.taskBoundaryCount++,!0):!1}computeLoss(t){let e=0,r=Math.min(t.length,this.fisherMatrix.length,this.optimalParams.length);for(let a=0;a<r;a++){let n=t[a]-this.optimalParams[a];e+=this.fisherMatrix[a]*n*n}return this.lambda/2*e}updateFisher(t,e){if(t.length===0)return;let r=this.fisherMatrix.length,a=new Float32Array(r);for(let s of t){let u=Math.min(s.length,r);for(let c=0;c<u;c++)a[c]+=s[c]*s[c]}let n=t.length;for(let s=0;s<r;s++)a[s]/=n;let o=this.fisherDecay;for(let s=0;s<r;s++)this.fisherMatrix[s]=o*this.fisherMatrix[s]+(1-o)*a[s];let i=Math.min(e.length,r);for(let s=0;s<i;s++)this.optimalParams[s]=e[s];this.consolidationCount++}getMetrics(){let t=this.fisherMatrix.length,e=0,r=0,a=0;for(let n=0;n<t;n++)e+=this.fisherMatrix[n],this.fisherMatrix[n]>r&&(r=this.fisherMatrix[n]),this.fisherMatrix[n]>this.importanceThreshold&&a++;return{regularizationLoss:0,taskBoundariesDetected:this.taskBoundaryCount,fisherTrace:e,avgFisherImportance:t>0?e/t:0,maxFisherImportance:r,protectedParams:a,consolidationCycles:this.consolidationCount,lambda:this.lambda}}getTaskBoundaryCount(){return this.taskBoundaryCount}getFisherDiagonal(){return new Float32Array(this.fisherMatrix)}getOptimalParams(){return new Float32Array(this.optimalParams)}loadFisher(t,e){let r=this.fisherMatrix.length,a=Math.min(t.length,r),n=Math.min(e.length,r);for(let o=0;o<a;o++)this.fisherMatrix[o]=t[o];for(let o=0;o<n;o++)this.optimalParams[o]=e[o]}updateGradientStats(){let t=this.gradientHistory.length;if(t===0)return;let e=0;for(let a of this.gradientHistory)e+=a;e/=t;let r=0;for(let a of this.gradientHistory){let n=a-e;r+=n*n}r=t>1?r/(t-1):0,this.gradientMean=e,this.gradientVariance=r}},C=class{config;microLora;ewc;nativeEngine;wasmLora=null;requestCount=0;lastConsolidationRequest=0;peerStates=new Map;gradientBuffer=[];lastFeatures=null;constructor(t={},e){this.config={...Mt,...t},this.nativeEngine=e??null,this.microLora=new R(this.config.dimension,this.config.microLoraLr),this.ewc=new x(this.config.dimension,this.config.ewcLambda,this.config.fisherDecay,this.config.taskBoundaryZScoreThreshold,this.config.importanceThreshold);let r=St();if(r)try{this.wasmLora=new r.WasmMicroLoRA(this.config.dimension,1,this.config.microLoraLr),f.info("SONA Three-Loop using WASM MicroLoRA (0.07us/adapt)")}catch(a){f.debug("WASM MicroLoRA creation failed, falling back",{error:String(a)}),this.wasmLora=null}!this.wasmLora&&this.nativeEngine&&f.info("SONA Three-Loop using native @ruvector/sona engine for MicroLoRA delegation")}instantAdapt(t){let e=performance.now(),r;if(this.wasmLora)try{let o=new Float32Array(t),i=this.wasmLora.adapt(o);i&&i.length>0?(r=i,this.microLora.adapt(t)):r=this.microLora.adapt(t)}catch{r=this.microLora.adapt(t)}else if(this.nativeEngine)try{let o=this.nativeEngine.applyMicroLora(t);r=new Float32Array(o),this.microLora.adapt(t)}catch{r=this.microLora.adapt(t)}else r=this.microLora.adapt(t);let a=this.microLora.getAdaptationMagnitude();this.requestCount++,this.lastFeatures=[...t];let n=(performance.now()-e)*1e3;return{adaptedWeights:r,latencyUs:n,applied:!0,magnitude:a,requestIndex:this.requestCount}}recordOutcome(t,e){if(this.lastFeatures===null){f.warn("recordOutcome called without a preceding instantAdapt()");return}let r=this.lastFeatures.length,a=new Float32Array(r);for(let n=0;n<r;n++)a[n]=t*this.lastFeatures[n];this.gradientBuffer.push(a),this.gradientBuffer.length>this.config.fisherSampleSize&&this.gradientBuffer.shift(),this.lastFeatures=null}backgroundConsolidate(){let t=performance.now();if(this.nativeEngine)try{this.nativeEngine.forceLearn(),this.nativeEngine.tick()}catch(i){f.warn("Native SONA background learning failed, continuing with TypeScript",{error:String(i)})}let e=this.ewc.computeLoss(this.microLora.getEffectiveWeights()),r=!1;if(this.gradientBuffer.length>0){let i=this.gradientBuffer[this.gradientBuffer.length-1];r=this.ewc.detectTaskBoundary(i)}if(r&&this.gradientBuffer.length>0&&(this.ewc.updateFisher(this.gradientBuffer,this.microLora.getEffectiveWeights()),f.info("Task boundary detected, Fisher updated",{boundaries:this.ewc.getTaskBoundaryCount(),requestCount:this.requestCount})),this.gradientBuffer.length>1){let i=!1,s=this.gradientBuffer[0];for(let u=1;u<this.gradientBuffer.length&&!i;u++)for(let c=0;c<s.length;c++)if(Math.abs(this.gradientBuffer[u][c]-s[c])>1e-8){i=!0;break}i||f.warn("All gradient samples identical \u2014 Fisher estimate may be poor. Ensure recordOutcome() is called with diverse rewards.")}let a=this.microLora.consolidate();this.applyEWCRegularization();let n=this.ewc.computeLoss(this.microLora.getEffectiveWeights());this.lastConsolidationRequest=this.requestCount,this.gradientBuffer=[];let o=performance.now()-t;return{consolidated:a>0||r,adaptationsMerged:a,ewcLossBefore:e,ewcLossAfter:n,taskBoundaryDetected:r,durationMs:o}}shouldConsolidate(){return this.requestCount-this.lastConsolidationRequest>=this.config.consolidationInterval}syncWithPeers(t){if(t.length===0)return;for(let i of t)this.peerStates.set(i.peerId,i);let e=this.config.dimension,r=new Float32Array(e),a=new Float32Array(e),n=this.ewc.getFisherDiagonal(),o=this.microLora.adaptationVector;for(let i=0;i<e;i++){let s=n[i]+1e-10;r[i]+=s*o[i],a[i]+=s}for(let i of t){let s=Math.min(i.adaptationVector.length,e);for(let u=0;u<s;u++){let c=(u<i.fisherDiagonal.length?i.fisherDiagonal[u]:0)+1e-10;r[u]+=c*i.adaptationVector[u],a[u]+=c}}for(let i=0;i<e;i++)this.microLora.adaptationVector[i]=r[i]/a[i];f.debug("Synced with peers",{peerCount:t.length,peersStored:this.peerStates.size})}getLocalPeerState(t,e){return{peerId:t,domain:e,adaptationVector:new Float32Array(this.microLora.adaptationVector),fisherDiagonal:this.ewc.getFisherDiagonal(),requestCount:this.requestCount,lastUpdateMs:Date.now()}}getEWCMetrics(){let t=this.ewc.getMetrics();return t.regularizationLoss=this.ewc.computeLoss(this.microLora.getEffectiveWeights()),t}getFisherDiagonal(){return this.ewc.getFisherDiagonal()}getOptimalParams(){return this.ewc.getOptimalParams()}loadFisher(t,e){this.ewc.loadFisher(t,e)}getBaseWeights(){return new Float32Array(this.microLora.baseWeights)}setBaseWeights(t){let e=Math.min(t.length,this.microLora.baseWeights.length);for(let r=0;r<e;r++)this.microLora.baseWeights[r]=t[r]}getEffectiveWeights(){return this.microLora.getEffectiveWeights()}getRequestCount(){return this.requestCount}getConfig(){return{...this.config}}getPeerStates(){return new Map(this.peerStates)}getMicroLoRA(){return this.microLora}getEWC(){return this.ewc}applyEWCRegularization(){let t=this.config.dimension,e=this.ewc.fisherMatrix,r=this.ewc.optimalParams,a=this.microLora.baseWeights,n=.01;for(let o=0;o<t;o++)if(e[o]>this.config.importanceThreshold){let i=a[o]-r[o];a[o]-=n*e[o]*i}}persistFisher(t,e){let r=this.ewc.getMetrics();t(e,this.ewc.getFisherDiagonal(),this.ewc.getOptimalParams(),this.getBaseWeights(),{taskBoundaries:r.taskBoundariesDetected,consolidationCycles:r.consolidationCycles,requestCount:this.requestCount,ewcLambda:r.lambda}),f.info("Fisher matrix persisted to SQLite",{domain:e,requestCount:this.requestCount,taskBoundaries:r.taskBoundariesDetected})}restoreFisher(t){this.ewc.loadFisher(t.fisherDiagonal,t.optimalParams),t.baseWeights&&this.setBaseWeights(t.baseWeights),this.requestCount=t.requestCount,f.info("Fisher matrix restored from SQLite",{requestCount:t.requestCount,dimension:t.fisherDiagonal.length})}};var Lt={hiddenDim:256,embeddingDim:384,microLoraRank:1,baseLoraRank:8,microLoraLr:.001,baseLoraLr:1e-4,ewcLambda:1e3,patternClusters:50,trajectoryCapacity:1e4,backgroundIntervalMs:36e5,qualityThreshold:.5,enableSimd:!0,minConfidence:.5,maxPatterns:1e4},Q=class{patterns;trajectoryMap;maxPatterns;constructor(t=1e4){this.patterns=new Map,this.trajectoryMap=new Map,this.maxPatterns=t}register(t){if(this.patterns.size>=this.maxPatterns&&!this.patterns.has(t.id)){let e=Array.from(this.patterns.entries()).sort(([,r],[,a])=>(r.lastUsedAt?.getTime()??r.createdAt.getTime())-(a.lastUsedAt?.getTime()??a.createdAt.getTime()))[0];e&&this.patterns.delete(e[0])}this.patterns.set(t.id,t)}get(t){return this.patterns.get(t)}getByTrajectory(t){let e=this.trajectoryMap.get(t);return e?this.patterns.get(e):void 0}associateTrajectory(t,e){this.trajectoryMap.set(t,e)}update(t,e){let r=this.patterns.get(t);return r?(this.patterns.set(t,{...r,...e}),!0):!1}getAll(){return Array.from(this.patterns.values())}getByType(t){return Array.from(this.patterns.values()).filter(e=>e.type===t)}getByDomain(t){return Array.from(this.patterns.values()).filter(e=>e.domain===t)}clear(){this.patterns.clear(),this.trajectoryMap.clear()}size(){return this.patterns.size}},v=class{engine;registry;config;adaptationTimes=[];cacheHits=0;totalAdaptations=0;threeLoopEngine=null;fisherPersistFn=null;fisherDomain="default";constructor(t={}){this.config={...Lt,...t};let e={hiddenDim:this.config.hiddenDim,embeddingDim:this.config.embeddingDim,microLoraRank:this.config.microLoraRank,baseLoraRank:this.config.baseLoraRank,microLoraLr:this.config.microLoraLr,baseLoraLr:this.config.baseLoraLr,ewcLambda:this.config.ewcLambda,patternClusters:this.config.patternClusters,trajectoryCapacity:this.config.trajectoryCapacity,backgroundIntervalMs:this.config.backgroundIntervalMs,qualityThreshold:this.config.qualityThreshold,enableSimd:this.config.enableSimd};this.engine=P.withConfig(e),this.registry=new Q(this.config.maxPatterns??1e4)}async adaptPattern(t,e,r){let a=performance.now();try{let n=this.createStateEmbedding(t),o=this.engine.findPatterns(n,5),i=[];for(let m of o){let g=this.findByRawPattern(m);if(g||(g=this.createQEPatternFromRaw(m,e,r)),g.type===e&&g.domain===r&&g.confidence>=(this.config.minConfidence??.5)){let h=this.calculateSimilarity(n,m.centroid);i.push({pattern:g,similarity:h})}}if(i.length===0){let m=performance.now()-a;return this.recordAdaptation(m),{success:!1,pattern:null,adaptationTimeMs:m,similarity:0,reasoning:"No suitable pattern found"}}let s=i[0],u={...s.pattern,usageCount:s.pattern.usageCount+1,lastUsedAt:new Date};this.registry.update(u.id,u);let c=performance.now()-a;return this.recordAdaptation(c),{success:!0,pattern:u,adaptationTimeMs:c,similarity:s.similarity,reasoning:`Pattern adapted from @ruvector/sona with ${s.similarity.toFixed(3)} similarity`}}catch(n){let o=performance.now()-a;return this.recordAdaptation(o),{success:!1,pattern:null,adaptationTimeMs:o,similarity:0,reasoning:`Adaptation failed: ${n.message}`}}}recallPattern(t,e,r){let a=this.createStateEmbedding(t),n=this.engine.findPatterns(a,1);for(let o of n){let i=this.findByRawPattern(o);if(i&&i.type===e&&i.domain===r)return i}return null}storePattern(t){this.registry.register(t);let e=this.engine.beginTrajectory(t.stateEmbedding),r=this.createActionEmbedding(t.action),a=new Array(r.length).fill(1),n=t.outcome.success?t.outcome.quality:-t.outcome.quality;this.engine.addTrajectoryStep(e,r,a,n),this.engine.endTrajectory(e,t.outcome.quality),this.registry.associateTrajectory(e,t.id)}storePatternsBatch(t){for(let e of t)this.storePattern(e)}createPattern(t,e,r,a,n,o){let i={id:`qesona-${Date.now()}-${Ct().slice(0,7)}`,type:a,domain:n,stateEmbedding:this.createStateEmbedding(t),action:e,outcome:r,confidence:.5,usageCount:0,createdAt:new Date,metadata:o};return this.storePattern(i),i}updatePattern(t,e,r){let a=this.registry.get(t);if(!a)return!1;let n=e?r:-r,i=a.confidence+.1*(n-a.confidence),s={...a,confidence:Math.max(0,Math.min(1,i)),usageCount:a.usageCount+1,lastUsedAt:new Date};return this.registry.update(t,s)}applyMicroLora(t){return this.engine.applyMicroLora(t)}applyBaseLora(t,e){return this.engine.applyBaseLora(t,e)}forceLearn(){return this.engine.forceLearn()}tick(){return this.engine.tick()}getAllPatterns(){return this.registry.getAll()}getPatternsByType(t){return this.registry.getByType(t)}getPatternsByDomain(t){return this.registry.getByDomain(t)}getStats(){let t=this.registry.getAll(),e=this.engine.getStats(),r={"test-generation":0,"defect-prediction":0,"coverage-optimization":0,"quality-assessment":0,"resource-allocation":0};for(let a of t)r[a.type]++;return{totalPatterns:t.length,patternsByType:r,avgAdaptationTimeMs:this.avgAdaptationTime(),minAdaptationTimeMs:this.minAdaptationTime(),maxAdaptationTimeMs:this.maxAdaptationTime(),totalAdaptations:this.totalAdaptations,cacheHitRate:this.totalAdaptations>0?this.cacheHits/this.totalAdaptations:0,engineStats:e}}clear(){this.registry.clear(),this.adaptationTimes=[],this.cacheHits=0,this.totalAdaptations=0}exportPatterns(){return this.registry.getAll()}importPatterns(t){this.clear(),this.storePatternsBatch(t)}getConfig(){return{...this.config}}setEnabled(t){this.engine.setEnabled(t)}isEnabled(){return this.engine.isEnabled()}createStateEmbedding(t){let e=t.features;if(e.length===0)return new Array(this.config.embeddingDim??384).fill(0);let r=Math.max(...e.map(Math.abs));if(r===0)return[...e];let a=e.map(o=>o/r),n=this.config.embeddingDim??384;return a.length>=n?a.slice(0,n):[...a,...new Array(n-a.length).fill(0)]}createActionEmbedding(t){let e=[],r=this.hashCode(t.type);if(e.push(r%1e3/1e3),typeof t.value=="number")e.push(Math.min(1,Math.max(-1,t.value)));else if(typeof t.value=="string"){let n=this.hashCode(t.value);e.push(n%1e3/1e3)}else if(Array.isArray(t.value))for(let n of t.value.slice(0,10))typeof n=="number"&&e.push(Math.min(1,Math.max(-1,n)));let a=this.config.embeddingDim??384;for(;e.length<a;)e.push(0);return e.slice(0,a)}findByRawPattern(t){let e=this.registry.getAll();for(let r of e)if(r.rawPattern?.patternType===t.id)return r}createQEPatternFromRaw(t,e,r){let a={centroid:t.centroid,clusterSize:1,totalWeight:1,avgQuality:t.avgQuality,createdAt:new Date().toISOString(),lastAccessed:new Date().toISOString(),accessCount:0,patternType:t.patternType};return{id:`qesona-${t.id}`,type:e,domain:r,stateEmbedding:t.centroid,action:{type:"learned",value:t.patternType},outcome:{reward:t.avgQuality,success:t.avgQuality>.5,quality:t.avgQuality},confidence:t.avgQuality,usageCount:0,createdAt:new Date,rawPattern:a}}calculateSimilarity(t,e){let r=Math.min(t.length,e.length),a=0,n=0,o=0;for(let s=0;s<r;s++)a+=t[s]*e[s],n+=t[s]*t[s],o+=e[s]*e[s];return(a/(Math.sqrt(n)*Math.sqrt(o)+1e-10)+1)/2}hashCode(t){let e=0;for(let r=0;r<t.length;r++)e=(e<<5)-e+t.charCodeAt(r),e=e|0;return Math.abs(e)}recordAdaptation(t){this.adaptationTimes.push(t),this.totalAdaptations++,this.adaptationTimes.length>1e3&&this.adaptationTimes.shift()}avgAdaptationTime(){return this.adaptationTimes.length===0?0:this.adaptationTimes.reduce((e,r)=>e+r,0)/this.adaptationTimes.length}minAdaptationTime(){return this.adaptationTimes.length===0?0:Math.min(...this.adaptationTimes)}maxAdaptationTime(){return this.adaptationTimes.length===0?0:Math.max(...this.adaptationTimes)}initThreeLoopEngine(t){this.threeLoopEngine=new C({dimension:this.config.embeddingDim??384,microLoraLr:this.config.microLoraLr??.001,ewcLambda:this.config.ewcLambda??1e3,...t},this.engine)}getThreeLoopEngine(){return this.threeLoopEngine}instantAdapt(t){return this.threeLoopEngine?this.threeLoopEngine.instantAdapt(t):null}recordOutcome(t,e){this.threeLoopEngine&&this.threeLoopEngine.recordOutcome(t,e)}backgroundConsolidate(){if(!this.threeLoopEngine)return null;let t=this.threeLoopEngine.backgroundConsolidate();if(t&&(t.consolidated||t.taskBoundaryDetected)&&this.fisherPersistFn)try{this.threeLoopEngine.persistFisher(this.fisherPersistFn,this.fisherDomain)}catch(e){console.warn("[QESONA] Fisher persistence failed:",e instanceof Error?e.message:e)}return t}setFisherPersistence(t,e){this.fisherPersistFn=t,this.fisherDomain=e}syncWithPeers(t){this.threeLoopEngine&&this.threeLoopEngine.syncWithPeers(t)}getEWCMetrics(){return this.threeLoopEngine?this.threeLoopEngine.getEWCMetrics():null}shouldConsolidate(){return this.threeLoopEngine?this.threeLoopEngine.shouldConsolidate():!1}getLocalPeerState(t,e){return this.threeLoopEngine?this.threeLoopEngine.getLocalPeerState(t,e):null}isThreeLoopEnabled(){return this.threeLoopEngine!==null}async verifyPerformance(t=1e3){let e=[],r={id:"test-state",features:new Array(384).fill(0).map(()=>G())};for(let s=0;s<t;s++){let u=performance.now();await this.adaptPattern(r,"test-generation","test-generation");let c=performance.now();e.push({iteration:s,timeMs:c-u})}let a=e.map(s=>s.timeMs),n=a.reduce((s,u)=>s+u,0)/a.length,o=Math.min(...a),i=Math.max(...a);return{targetMet:n<.05,avgTimeMs:n,minTimeMs:o,maxTimeMs:i,details:e}}};function Tt(l){return new v(l)}function Pt(l,t){return new v({...t,maxPatterns:t?.maxPatterns||5e3})}ot();et();var F=null,D=null,W=null,B=null,z=null,I=null,q=!1;try{let l=(O(),w(N));F=l.FlashAttention,D=l.DotProductAttention,W=l.MultiHeadAttention,B=l.HyperbolicAttention,z=l.LinearAttention,I=l.MoEAttention,q=!0}catch{}function Gt(){return q}function A(){if(!q)throw new Error("@ruvector/attention native module is not available on this platform. Install the appropriate optional dependency for your platform, or use a platform where pre-built binaries are available.")}var T={"test-similarity":{dim:384,strategy:"flash",blockSize:64},"code-embedding":{dim:512,strategy:"flash",blockSize:128},"defect-matching":{dim:384,strategy:"flash",blockSize:64},"coverage-analysis":{dim:384,strategy:"flash",blockSize:256},"pattern-adaptation":{dim:256,strategy:"flash",blockSize:32}},Kt={"test-similarity":{enabled:!0,microLoRARank:4,targetAdaptationMs:.05,patternCacheSize:1e3},"code-embedding":{enabled:!0,microLoRARank:2,targetAdaptationMs:.03,patternCacheSize:5e3},"defect-matching":{enabled:!0,microLoRARank:8,targetAdaptationMs:.05,patternCacheSize:2e3},"coverage-analysis":{enabled:!1,microLoRARank:2,targetAdaptationMs:.01,patternCacheSize:100},"pattern-adaptation":{enabled:!0,microLoRARank:2,targetAdaptationMs:.05,patternCacheSize:1e4}},$t={"test-similarity":{latency:{before:50,after:15},memory:{before:200,after:80},throughput:{min:1e3}},"code-embedding":{latency:{before:50,after:15},memory:{before:200,after:80},throughput:{min:2e3}},"defect-matching":{latency:{before:20,after:5},memory:{before:150,after:50},throughput:{min:500}},"coverage-analysis":{latency:{before:100,after:1},memory:{before:100,after:30},throughput:{min:1e4}},"pattern-adaptation":{latency:{before:2,after:.05},memory:{before:50,after:20},throughput:{min:2e4}}};function Zt(l){return l<=128?{queryChunkSize:128,kvChunkSize:128}:l<=256?{queryChunkSize:256,kvChunkSize:256}:l<=512?{queryChunkSize:512,kvChunkSize:512}:l<=1024?{queryChunkSize:1024,kvChunkSize:1024}:{queryChunkSize:1024,kvChunkSize:2048}}var E=class{static create(t){switch(A(),t.strategy){case"flash":return new F(t.dim,t.blockSize);case"dot-product":return new D(t.dim);case"multi-head":return new W(t.dim,t.numHeads??8);case"hyperbolic":return new B(t.dim,t.curvature);case"linear":return new z(t.dim,t.features);case"moe":return I.simple(t.dim,t.moeConfig?.numExperts??8,t.moeConfig?.topK??2);default:return new F(t.dim,t.blockSize)}}},L=class l{attention;config;workload;metrics=[];db=null;persistCount=0;static KV_NAMESPACE="attention-metrics";static KV_TTL=3600;static PERSIST_INTERVAL=10;constructor(t,e){this.workload=t;let r=T[t];this.config={...r,...e},this.attention=E.create(this.config)}async initialize(){try{this.db=K(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(t){console.warn("[QEFlashAttention] DB init failed, using memory-only:",j(t)),this.db=null}}async computeFlashAttention(t,e,r,a,n){let o=performance.now(),i=process.memoryUsage().heapUsed/1024/1024,s=this.toFloat32Array(t,a,n),u=this.splitMatrix(e,a,n),c=this.splitMatrix(r,a,n),m,g=this.attention;typeof g.compute=="function"?m=g.compute(s,u,c):(A(),m=new F(this.config.dim).compute(s,u,c));let h=performance.now(),d=process.memoryUsage().heapUsed/1024/1024;return this.metrics.push({timeMs:h-o,memoryMB:d-i,speedup:1,throughput:a*a/((h-o)/1e3),peakMemoryMB:d}),this.maybePersistToKv(),m}async computeBaselineAttention(t,e,r,a,n){let o=performance.now(),i=process.memoryUsage().heapUsed/1024/1024,s=new Float32Array(a*a),u=1/Math.sqrt(n);for(let h=0;h<a;h++)for(let d=0;d<a;d++){let b=0;for(let p=0;p<n;p++)b+=t[h*n+p]*e[d*n+p];s[h*a+d]=b*u}for(let h=0;h<a;h++){let d=h*a,b=d+a,p=s.subarray(d,b),tt=Math.max(...p),_=0;for(let y=0;y<a;y++)p[y]=Math.exp(p[y]-tt),_+=p[y];for(let y=0;y<a;y++)p[y]/=_}let c=new Float32Array(a*n);for(let h=0;h<a;h++)for(let d=0;d<a;d++){let b=s[h*a+d];for(let p=0;p<n;p++)c[h*n+p]+=b*r[d*n+p]}let m=performance.now(),g=process.memoryUsage().heapUsed/1024/1024;return c}async computeTestSimilarity(t,e,r=5){let a=e.length,n=t.length,o=new Float32Array(a*n),i=new Float32Array(a*n);for(let m=0;m<a;m++)o.set(t,m*n),i.set(e[m],m*n);let s=new Float32Array(a*n),u=await this.computeFlashAttention(o,i,s,a,n),c=[];for(let m=0;m<a;m++)c.push({index:m,similarity:u[m*n]});return c.sort((m,g)=>g.similarity-m.similarity),c.slice(0,r)}async generateCodeEmbedding(t,e){let r=t.length/e.length,a=e.length;return await this.computeFlashAttention(t,e,t,r,a)}async matchDefectPattern(t,e){let r=e.length,a=t.length,n=new Float32Array(r*a),o=new Float32Array(r*a);for(let c=0;c<r;c++)n.set(t,c*a),o.set(e[c],c*a);let i=new Float32Array(r*a),s=await this.computeFlashAttention(n,o,i,r,a),u=[];for(let c=0;c<r;c++)u.push({pattern:c,score:s[c*a]});return u.sort((c,m)=>m.score-c.score),u}getMetrics(){return[...this.metrics]}getAverageSpeedup(){return this.metrics.length===0?1:this.metrics.reduce((t,e)=>t+e.speedup,0)/this.metrics.length}getConfig(){return{...this.config}}updateConfig(t){this.config={...this.config,...t},this.attention=E.create(this.config)}changeStrategy(t){this.config.strategy=t,this.attention=E.create(this.config)}resetMetrics(){this.metrics=[]}getWorkload(){return this.workload}dispose(){this.metrics=[]}async persistToKv(){if(!this.db)return;let t=`attention-metrics-${this.workload}`,e={workload:this.workload,metrics:this.metrics.slice(-50),savedAt:Date.now()};await this.db.kvSet(t,e,l.KV_NAMESPACE,l.KV_TTL)}async loadFromKv(){if(!this.db)return;let t=`attention-metrics-${this.workload}`,e=await this.db.kvGet(t,l.KV_NAMESPACE);e?.metrics?.length&&(this.metrics=e.metrics)}maybePersistToKv(){this.persistCount++,this.persistCount>=l.PERSIST_INTERVAL&&(this.persistCount=0,this.persistToKv().catch(()=>{}))}toFloat32Array(t,e,r){return t.slice(0,r)}splitMatrix(t,e,r){let a=[];for(let n=0;n<e;n++)a.push(t.slice(n*r,(n+1)*r));return a}};async function Y(l,t){let e=new L(l,t);return await e.initialize(),e}function Jt(l){return{...T[l]}}function Xt(){return Object.keys(T)}function Yt(){return A(),F}function te(){return A(),D}function ee(){return A(),W}function re(){return A(),B}function ae(){return A(),z}function ne(){return A(),I}function ie(l){return l instanceof Float32Array?l:new Float32Array(l)}function oe(l){return Array.from(l)}async function se(l,t,e,r){let a=await Y(l),n=[],o=t[0].length,i=e.length;for(let s of t){let u=new Float32Array(i*o),c=new Float32Array(i*o),m=new Float32Array(i*o);u.set(s,0);for(let h=0;h<i;h++)c.set(e[h],h*o),m.set(r[h],h*o);let g=await a.computeFlashAttention(u,c,m,i,o);n.push(g.slice(0,o))}return a.dispose(),n}function We(){return{"@ruvector/sona":"^0.1.5","@ruvector/attention":"^0.1.4","@ruvector/gnn":"^0.1.22"}}function Be(){let l={sona:!1,attention:!1,gnn:!1,all:!1};try{k(),l.sona=!0}catch{}try{O(),l.attention=!0}catch{}try{let t=(it(),w(nt));t.init();let e=new Float32Array([.1,.2,.3]),r=[new Float32Array([.1,.2,.3]),new Float32Array([.4,.5,.6])],a=t.differentiableSearch(e,r,1,1);a&&Array.isArray(a.indices)&&Array.isArray(a.weights)&&(l.gnn=!0)}catch{}return l.all=l.sona&&l.attention&&l.gnn,l}async function ze(){let{initGNN:l}=await import("./gnn-wrapper-OYC55N5E.js");return[l(),"SONA: Ready (no initialization required)","Attention: Ready (no initialization required)"]}export{v as a,Tt as b,Pt as c,Gt as d,T as e,Kt as f,$t as g,Zt as h,L as i,Y as j,Jt as k,Xt as l,Yt as m,te as n,ee as o,re as p,ae as q,ne as r,ie as s,oe as t,se as u,We as v,Be as w,ze as x};
@@ -0,0 +1,18 @@
1
+ if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.0");process.exit(0)}
2
+ import{a as x,c as N}from"./chunk-JZSDOIXA.js";import{b as w,c as P,d as O}from"./chunk-DRT3WKQW.js";N();O();import*as k from"fs";import*as T from"path";import*as L from"yaml";var D=5,F=4,U=3e4,W=".claude/skills",G=5e3,$=500,A=100,V=1e3,I=500,H=.8,Q=.2,K=.1,v=.1,q=.1,B=.1,z=.1,X=200,j=500,Y=300,J=1,Z=.9,M={maxWorkers:D,batchSize:F,retryFailedTests:!0,timeout:U,skillsDir:W,progressIntervalMs:G},R=class{async execute(e,s,t){let r=P(A,$+A);return await new Promise(i=>setTimeout(i,r)),{output:this.generateMockResponse(e),tokensUsed:w(I,V+I),durationMs:r}}generateMockResponse(e){let s=[];return e.includes("alt")&&s.push("alt","1.1.1","perceivable"),e.includes("contrast")&&s.push("contrast","1.4.3","4.5:1"),e.includes("keyboard")&&s.push("keyboard","2.1.1","operable","button"),e.includes("label")&&s.push("label","3.3.2","understandable"),e.includes("ARIA")&&s.push("ARIA","4.1.2","robust"),e.includes("focus")&&s.push("focus","2.4.7","outline"),e.includes("lang")&&s.push("lang","3.1.1","language"),e.includes("caption")&&s.push("caption","1.2.2","track"),e.includes("accessible")&&s.push("accessible","compliant"),s.length===0&&s.push("accessibility","WCAG","finding"),`Analysis complete. Found issues related to: ${s.join(", ")}.
3
+ Recommendations: Implement proper ${s[0]} attributes for better accessibility.
4
+ Severity: ${e.includes("critical")?"critical":"serious"}`}},y=class{constructor(e,s,t){this.executor=s;this.config=t;this.id=e}id;status="idle";tasksCompleted=0;tasksFailed=0;lastHeartbeat=Date.now();async executeBatch(e){this.status="running";let s=[];for(let t of e){this.lastHeartbeat=Date.now();try{let r=await this.executeTestCase(t);if(s.push(r),r.passed)this.tasksCompleted++;else if(this.tasksFailed++,this.config.retryFailedTests&&!r.passed){let a=await this.executeTestCase(t,!0);a.passed&&(s[s.length-1]=a,this.tasksCompleted++,this.tasksFailed--)}}catch(r){this.tasksFailed++,s.push({testId:t.testCaseId,passed:!1,expectedPatterns:t.testCase.expected_output.must_contain||[],actualPatterns:[],reasoningQuality:0,category:t.testCase.category,priority:t.testCase.priority,error:x(r)})}}return this.status="idle",s}async executeTestCase(e,s=!1){let t=Date.now(),r=this.buildPrompt(e),a=await this.executor.execute(r,e.model,{timeout:this.config.timeout}),i=this.validateResponse(a.output,e.testCase.expected_output,e.testCase.validation);return{testId:e.testCaseId,passed:i.passed,expectedPatterns:e.testCase.expected_output.must_contain||[],actualPatterns:i.foundPatterns,reasoningQuality:i.reasoningQuality,executionTimeMs:Date.now()-t,category:e.testCase.category,priority:e.testCase.priority,error:i.error}}buildPrompt(e){let{testCase:s}=e,t=s.input.context;return`Analyze the following ${t.language||"HTML"} code for accessibility issues.
5
+ Context: ${t.description||s.description}
6
+ WCAG Level: ${t.wcagLevel||"AA"}
7
+
8
+ Code:
9
+ \`\`\`${t.language||"html"}
10
+ ${s.input.code}
11
+ \`\`\`
12
+
13
+ Provide a detailed analysis including:
14
+ 1. All accessibility issues found
15
+ 2. WCAG success criteria violated
16
+ 3. Severity classification (critical/serious/moderate/minor)
17
+ 4. Remediation recommendations with code examples`}validateResponse(e,s,t){let r=[],a=[],i=s.must_contain||[],o=0;for(let u of i)new RegExp(u,"i").test(e)&&(r.push(u),o++);let n=s.must_not_contain||[];for(let u of n)new RegExp(u,"i").test(e)&&a.push(`Output should not contain: ${u}`);let d=s.must_match_regex||[];for(let u of d)new RegExp(u,"i").test(e)||a.push(`Output should match regex: ${u}`);let p=i.length>0?o/i.length:1,g=t?.keyword_match_threshold??H,h=p>=g,l=this.calculateReasoningQuality(e,t),m=t?.reasoning_quality_min??0,_=l>=m;return{passed:h&&_&&a.length===0,foundPatterns:r,reasoningQuality:l,error:a.length>0?a.join("; "):void 0}}calculateReasoningQuality(e,s){let t=0;if(e.length>X&&(t+=Q),e.length>j&&(t+=K),e.includes(`
18
+ `)&&(t+=v),(e.includes("1.")||e.includes("-"))&&(t+=v),e.includes("```")&&(t+=v),e.includes("WCAG")&&(t+=q),(e.includes("remediation")||e.includes("recommendation"))&&(t+=B),(e.includes("severity")||e.includes("critical"))&&(t+=z),s?.grading_rubric){let r=s.grading_rubric,a=0;r.completeness&&e.length>Y&&(a+=r.completeness),r.accuracy&&e.includes("WCAG")&&(a+=r.accuracy),r.actionability&&(e.includes("fix")||e.includes("change"))&&(a+=r.actionability),t=Math.max(t,a)}return Math.min(t,1)}getProgress(e){return{workerId:this.id,tasksCompleted:this.tasksCompleted,tasksTotal:e,elapsedMs:Date.now()-this.lastHeartbeat}}},S=class{constructor(e=M,s,t=new R){this.config=e;this.skillValidationLearner=s;this.executor=t;for(let r=0;r<e.maxWorkers;r++)this.workers.push(new y(r,t,e))}workers=[];progressCallback;onProgress(e){this.progressCallback=e}async runEvalParallel(e,s){let t=Date.now(),r=this.loadEvalSuite(e);if(!r)throw new Error(`Failed to load eval suite for skill: ${e}`);let a=this.createTasks(r,s),i=this.partitionTestCases(a,this.config.batchSize),o=a.length*(this.config.timeout/2),n=[],d=[];for(let c=0;c<i.length;c++){let b=this.workers[c%this.workers.length];d.push(b.executeBatch(i[c]))}let p=this.startProgressReporting(e,s,a.length,t);try{let c=await Promise.all(d);for(let b of c)n.push(...b)}finally{p&&clearInterval(p)}let g=Date.now()-t,h=n.filter(c=>c.passed).length,l=n.filter(c=>!c.passed).length,m=a.length-n.length,_=n.length>0?h/n.length:0,C=n.length>0?n.reduce((c,b)=>c+b.reasoningQuality,0)/n.length:0,u=g>0?o/g:1,f=_>=r.success_criteria.pass_rate&&C>=(r.success_criteria.avg_reasoning_quality??0);return await this.recordOutcome({skillName:e,trustTier:this.determineTrustTier(r),validationLevel:"eval",model:s,passed:f,score:_,testCaseResults:n,timestamp:new Date,runId:`${e}-${s}-${Date.now()}`,metadata:{duration:g,parallelSpeedup:u,workersUsed:this.config.maxWorkers,version:r.version}}),{skill:e,model:s,totalTests:a.length,passedTests:h,failedTests:l,skippedTests:m,passRate:_,testResults:n,totalDurationMs:g,parallelSpeedup:u,avgReasoningQuality:C,passed:f,workersUsed:this.config.maxWorkers,timestamp:new Date}}async runMultipleEvalsParallel(e,s){let t=new Map,r=[];for(let o of e){t.set(o,[]);for(let n of s)r.push({skill:o,model:n})}let a=r.map(async({skill:o,model:n})=>{let d=await this.runEvalParallel(o,n);return{skill:o,result:d}}),i=await Promise.all(a);for(let{skill:o,result:n}of i)t.get(o).push(n);return t}loadEvalSuite(e){let s=T.isAbsolute(this.config.skillsDir)?this.config.skillsDir:T.join(process.cwd(),this.config.skillsDir),t=T.join(s,e,"evals",`${e}.yaml`);if(!k.existsSync(t))return console.error(`Eval suite not found: ${t}`),null;try{let r=k.readFileSync(t,"utf-8");return L.parse(r)}catch(r){return console.error(`Failed to parse eval suite: ${r instanceof Error?r.message:r}`),null}}createTasks(e,s){return e.test_cases.map((t,r)=>({skillName:e.skill,testCaseId:t.id,testCase:t,model:s,batchId:Math.floor(r/this.config.batchSize),indexInBatch:r%this.config.batchSize}))}partitionTestCases(e,s){let t=[];for(let r=0;r<e.length;r+=s)t.push(e.slice(r,r+s));return t}determineTrustTier(e){let s=e.mcp_integration?.enabled??!1,t=e.learning?.cross_model_comparison??!1,r=e.success_criteria.critical_pass_rate??0;return s&&t&&r>=J?3:s||r>=Z?2:1}startProgressReporting(e,s,t,r){return this.progressCallback?setInterval(()=>{let a=Date.now()-r,i=this.workers.reduce((l,m)=>l+m.tasksCompleted,0),o=this.workers.reduce((l,m)=>l+m.tasksFailed,0),n=this.workers.filter(l=>l.status==="running").length,d=a>0?i/a:0,p=t-i,g=d>0?p/d:0,h={skill:e,model:s,totalTasks:t,completedTasks:i,failedTasks:o,activeWorkers:n,elapsedMs:a,estimatedRemainingMs:g,workerProgress:this.workers.map(l=>l.getProgress(t))};this.progressCallback(h)},this.config.progressIntervalMs):null}async recordOutcome(e){await this.skillValidationLearner.recordValidationOutcome(e)}getWorkerStatus(){return this.workers.map(e=>({id:e.id,status:e.status,tasksCompleted:e.tasksCompleted,tasksFailed:e.tasksFailed}))}resetWorkers(){for(let e of this.workers)e.tasksCompleted=0,e.tasksFailed=0,e.status="idle"}};function re(E,e={},s){let t={...M,...e};return new S(t,E,s)}export{M as a,re as b};