agentic-qe 3.14.0 → 3.14.2

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 (430) hide show
  1. package/.claude/helpers/brain-checkpoint.cjs +2 -1
  2. package/.claude/helpers/validate-v3-config.sh +6 -5
  3. package/.claude/hooks/aqe-hook.cjs +14 -14
  4. package/.claude/skills/qe-browser/evals/qe-browser.yaml +30 -41
  5. package/.claude/skills/qe-browser/fixtures/serve-skills.js +37 -0
  6. package/.claude/skills/qe-browser/scripts/lib/vibium.js +1 -1
  7. package/.claude/skills/qe-browser/scripts/smoke-test.sh +56 -25
  8. package/.claude/skills/qe-browser/scripts/visual-diff.js +24 -15
  9. package/.claude/skills/skills-manifest.json +1 -1
  10. package/CHANGELOG.md +114 -0
  11. package/assets/skills/qe-browser/evals/qe-browser.yaml +30 -41
  12. package/assets/skills/qe-browser/fixtures/serve-skills.js +37 -0
  13. package/assets/skills/qe-browser/scripts/lib/vibium.js +1 -1
  14. package/assets/skills/qe-browser/scripts/smoke-test.sh +56 -25
  15. package/assets/skills/qe-browser/scripts/visual-diff.js +24 -15
  16. package/assets/skills/skills-manifest.json +1 -1
  17. package/dist/cli/bundle.js +7 -7
  18. package/dist/cli/chunks/adapter-OJF6LAJV.js +2 -0
  19. package/dist/cli/chunks/{agent-booster-wasm-JZO6VUW4.js → agent-booster-wasm-SD5N32MX.js} +2 -2
  20. package/dist/cli/chunks/{agent-handler-534KFGEJ.js → agent-handler-OZRSJM7F.js} +2 -2
  21. package/dist/cli/chunks/{agent-memory-branch-B7KWLWY4.js → agent-memory-branch-NYTRANRN.js} +2 -2
  22. package/dist/cli/chunks/aqe-learning-engine-FGT474XB.js +2 -0
  23. package/dist/cli/chunks/{arena-OW5MELJX.js → arena-EX3SC2DP.js} +4 -4
  24. package/dist/cli/chunks/{arena-7CCD3S3I.js → arena-FOTVSRK4.js} +2 -2
  25. package/dist/cli/chunks/{audit-BHVKN4E2.js → audit-Q5GHSUQY.js} +3 -3
  26. package/dist/cli/chunks/base-HH765JFV.js +2 -0
  27. package/dist/cli/chunks/{better-sqlite3-P5FA6WFK.js → better-sqlite3-S7M5R2HS.js} +2 -2
  28. package/dist/cli/chunks/{brain-handler-WNW5LOV7.js → brain-handler-5FSA46R5.js} +3 -3
  29. package/dist/cli/chunks/{branch-enumerator-TVZ2ODKH.js → branch-enumerator-RWAXTGEU.js} +2 -2
  30. package/dist/cli/chunks/{browser-TCEB2W2F.js → browser-IGDESJGF.js} +2 -2
  31. package/dist/cli/chunks/browser-workflow-NPM4FUPI.js +2 -0
  32. package/dist/cli/chunks/{chunk-Q73RRTLE.js → chunk-2EHFEMRU.js} +2 -2
  33. package/dist/cli/chunks/{chunk-ZBOWR4XT.js → chunk-2H5YJ5ZK.js} +2 -2
  34. package/dist/cli/chunks/chunk-2LKAMMMI.js +2 -0
  35. package/dist/cli/chunks/{chunk-A2WZEMWT.js → chunk-2TG24LYQ.js} +1 -1
  36. package/dist/cli/chunks/{chunk-3QT6S3A3.js → chunk-3C2K4YMS.js} +3 -3
  37. package/dist/cli/chunks/{chunk-VESOYP6A.js → chunk-3DFFFXXO.js} +2 -2
  38. package/dist/cli/chunks/{chunk-K6CGQR5R.js → chunk-3WV4H33V.js} +1 -1
  39. package/dist/cli/chunks/{chunk-IL4AEB3J.js → chunk-42WUDDUU.js} +2 -2
  40. package/dist/cli/chunks/chunk-4AKGBUYD.js +4 -0
  41. package/dist/cli/chunks/{chunk-4FEJEVG7.js → chunk-4K27ESCA.js} +1 -1
  42. package/dist/cli/chunks/{chunk-TGOGCA74.js → chunk-4M6A3PVJ.js} +2 -2
  43. package/dist/cli/chunks/{chunk-RGVD6ZUX.js → chunk-4MH22236.js} +1 -1
  44. package/dist/cli/chunks/{chunk-6DPAMYLU.js → chunk-4N44UJGI.js} +2 -2
  45. package/dist/cli/chunks/{chunk-DJITEQYS.js → chunk-4PH7O5ZH.js} +2 -2
  46. package/dist/cli/chunks/{chunk-M3HUZD2I.js → chunk-4RT7I7PI.js} +1 -1
  47. package/dist/cli/chunks/chunk-4UCMTYFQ.js +65 -0
  48. package/dist/cli/chunks/{chunk-ZI3UO7QR.js → chunk-4ZUZDFAA.js} +2 -2
  49. package/dist/cli/chunks/{chunk-QSPRQPEL.js → chunk-57TNBR2P.js} +2 -2
  50. package/dist/cli/chunks/{chunk-ZCVJCCQQ.js → chunk-5EHLGOWW.js} +2 -2
  51. package/dist/cli/chunks/{chunk-ZAAYOENS.js → chunk-5WJUNRTY.js} +2 -2
  52. package/dist/cli/chunks/{chunk-QZPFUFZG.js → chunk-67A6PEZM.js} +2 -2
  53. package/dist/cli/chunks/{chunk-7BOPFN3Y.js → chunk-6EHN7Q2Q.js} +2 -2
  54. package/dist/cli/chunks/{chunk-2HYVOX6N.js → chunk-6F4WHN7D.js} +1 -1
  55. package/dist/cli/chunks/{chunk-GVEJP5T7.js → chunk-6LMLN5R2.js} +2 -2
  56. package/dist/cli/chunks/{chunk-QKQZ4IJF.js → chunk-6SZKLWZT.js} +5 -5
  57. package/dist/cli/chunks/{chunk-PEW6FZ47.js → chunk-6VKJAMZY.js} +1 -1
  58. package/dist/cli/chunks/{chunk-VYENTZ45.js → chunk-7AFBNU6K.js} +2 -2
  59. package/dist/cli/chunks/{chunk-6IJMD2ZL.js → chunk-7FWP7CZY.js} +3 -3
  60. package/dist/cli/chunks/{chunk-IE5LC7MB.js → chunk-7SK6IMGZ.js} +2 -2
  61. package/dist/cli/chunks/{chunk-3EM2MK3Z.js → chunk-A7N3YUDJ.js} +2 -2
  62. package/dist/cli/chunks/{chunk-J3XSHJGK.js → chunk-ADK7DF3G.js} +2 -2
  63. package/dist/cli/chunks/{chunk-EJ6IP7DE.js → chunk-ARMZYHYL.js} +2 -2
  64. package/dist/cli/chunks/{chunk-BZ4QVFP2.js → chunk-BWRHOIYC.js} +2 -2
  65. package/dist/cli/chunks/{chunk-A7SKM6JL.js → chunk-C7AXRI7E.js} +1 -1
  66. package/dist/cli/chunks/{chunk-4XTHRAUV.js → chunk-CG2MUD7U.js} +1 -1
  67. package/dist/cli/chunks/{chunk-HLNQDRHA.js → chunk-CH2TQCV5.js} +1 -1
  68. package/dist/cli/chunks/{chunk-JGROLJ33.js → chunk-CIESXO73.js} +1 -1
  69. package/dist/cli/chunks/{chunk-AR6SATU3.js → chunk-CJCT452S.js} +2 -2
  70. package/dist/cli/chunks/{chunk-UUJ5VQJM.js → chunk-CJHVOBJY.js} +1 -1
  71. package/dist/cli/chunks/{chunk-VOSISOFD.js → chunk-CTCQOYBS.js} +1 -1
  72. package/dist/cli/chunks/{chunk-XITTURP2.js → chunk-D4RCV4LY.js} +2 -2
  73. package/dist/cli/chunks/{chunk-5XGVSQS2.js → chunk-DRO5NJZA.js} +2 -2
  74. package/dist/cli/chunks/{chunk-QMMDN4WX.js → chunk-DVHWLAEO.js} +3 -3
  75. package/dist/cli/chunks/{chunk-5LEAGKX5.js → chunk-DW6ZMNMR.js} +2 -2
  76. package/dist/cli/chunks/{chunk-ZBKGX72B.js → chunk-E3Q7WNJD.js} +3 -3
  77. package/dist/cli/chunks/{chunk-5MZF4N4Q.js → chunk-EAJK25IS.js} +1 -1
  78. package/dist/cli/chunks/{chunk-3RYTAYR6.js → chunk-EH5OCHAJ.js} +1 -1
  79. package/dist/cli/chunks/{chunk-UI6WSPEK.js → chunk-F2KRT2II.js} +3 -3
  80. package/dist/cli/chunks/{chunk-NDPQ2WPU.js → chunk-FPHPP5TQ.js} +1 -1
  81. package/dist/cli/chunks/{chunk-WWWX76QB.js → chunk-FREF6Y4L.js} +2 -2
  82. package/dist/cli/chunks/{chunk-SROZXIMT.js → chunk-FVGTINVR.js} +54 -54
  83. package/dist/cli/chunks/{chunk-H3YDDKBW.js → chunk-G2CLZVYI.js} +3 -3
  84. package/dist/cli/chunks/{chunk-2O4DDPEA.js → chunk-G6AV2HGY.js} +3 -3
  85. package/dist/cli/chunks/{chunk-ENGKLFLY.js → chunk-GHQ5PUOV.js} +2 -2
  86. package/dist/cli/chunks/{chunk-NKWO2X3T.js → chunk-GHUPID5E.js} +1 -1
  87. package/dist/cli/chunks/{chunk-S5YVLPXU.js → chunk-GJAWEUIN.js} +2 -2
  88. package/dist/cli/chunks/{chunk-6IZQSLYZ.js → chunk-HBTC4L53.js} +2 -2
  89. package/dist/cli/chunks/{chunk-DDPJUAXQ.js → chunk-HSJ5FQCF.js} +2 -2
  90. package/dist/cli/chunks/{chunk-OONCRNFA.js → chunk-HZ6NEJMO.js} +2 -2
  91. package/dist/cli/chunks/{chunk-LCSVROU7.js → chunk-HZMLNM2T.js} +10 -10
  92. package/dist/cli/chunks/{chunk-JY4VZ6BN.js → chunk-ICKLBATY.js} +2 -2
  93. package/dist/cli/chunks/{chunk-JMKMDSXG.js → chunk-IUNMW454.js} +2 -2
  94. package/dist/cli/chunks/{chunk-XXFKN7LB.js → chunk-IVGVOGIZ.js} +1 -1
  95. package/dist/cli/chunks/{chunk-3GUO4ERR.js → chunk-IWFL6EFI.js} +2 -2
  96. package/dist/cli/chunks/{chunk-FRL3X2QA.js → chunk-JDXLCNKV.js} +2 -2
  97. package/dist/cli/chunks/{chunk-YW4RNZWT.js → chunk-JIUF6NV6.js} +2 -2
  98. package/dist/cli/chunks/{chunk-JAK5UUWH.js → chunk-JQ2ZD3WO.js} +2 -2
  99. package/dist/cli/chunks/{chunk-YEAC3DC6.js → chunk-K574FLVB.js} +2 -2
  100. package/dist/cli/chunks/{chunk-LZHTCUCO.js → chunk-KEEBUVGV.js} +2 -2
  101. package/dist/cli/chunks/{chunk-LKR7T3OZ.js → chunk-KFXZDQ5J.js} +1 -1
  102. package/dist/cli/chunks/{chunk-7OUMJCJT.js → chunk-KPFG4OIM.js} +1 -1
  103. package/dist/cli/chunks/{chunk-HQ7243G3.js → chunk-KZOBLLXW.js} +2 -2
  104. package/dist/cli/chunks/{chunk-R6WJF4D5.js → chunk-L2F7FVIU.js} +2 -2
  105. package/dist/cli/chunks/{chunk-VRRG66XB.js → chunk-LML5VTFK.js} +1 -1
  106. package/dist/cli/chunks/{chunk-JTWJR2KY.js → chunk-LWUJQGCS.js} +2 -2
  107. package/dist/cli/chunks/{chunk-BQCTO7UB.js → chunk-MH73D5TN.js} +2 -2
  108. package/dist/cli/chunks/{chunk-U4GZWPKM.js → chunk-MWQTACNA.js} +2 -2
  109. package/dist/cli/chunks/{chunk-CIZ6LSNV.js → chunk-N3RN4QTC.js} +2 -2
  110. package/dist/cli/chunks/{chunk-ZQSXG7FA.js → chunk-N5ZRUOMR.js} +2 -2
  111. package/dist/cli/chunks/{chunk-AFGT26NR.js → chunk-NAZVPZJS.js} +2 -2
  112. package/dist/cli/chunks/{chunk-FOHYBR3O.js → chunk-NG2UVPTW.js} +1 -1
  113. package/dist/cli/chunks/{chunk-2D7UBX5S.js → chunk-NHHWLJQF.js} +1 -1
  114. package/dist/cli/chunks/{chunk-JRKEBESE.js → chunk-NNOMDM4N.js} +2 -2
  115. package/dist/cli/chunks/{chunk-YKWMKRYB.js → chunk-NRR23SJV.js} +1 -1
  116. package/dist/cli/chunks/{chunk-WKNWRDA5.js → chunk-NWFIJNEB.js} +1 -1
  117. package/dist/cli/chunks/{chunk-4MK2G6TK.js → chunk-OBCKP3G4.js} +2 -2
  118. package/dist/cli/chunks/{chunk-YKZV7O65.js → chunk-OC2CKU7I.js} +2 -2
  119. package/dist/cli/chunks/{chunk-7RVAHJQZ.js → chunk-OX6T26CD.js} +3 -3
  120. package/dist/cli/chunks/chunk-P64DMQ2C.js +2 -0
  121. package/dist/cli/chunks/{chunk-RKUYVVGJ.js → chunk-PFXX5Q32.js} +2 -2
  122. package/dist/cli/chunks/chunk-PHHXHG2W.js +2 -0
  123. package/dist/cli/chunks/{chunk-N2YAUDAV.js → chunk-PMUBG2RU.js} +2 -2
  124. package/dist/cli/chunks/{chunk-WTHAVFIC.js → chunk-PVHO6KLB.js} +1 -1
  125. package/dist/cli/chunks/{chunk-MO7EITJK.js → chunk-PWEIDHT7.js} +2 -2
  126. package/dist/cli/chunks/{chunk-52DFCV57.js → chunk-PZKZY6PB.js} +2 -2
  127. package/dist/cli/chunks/{chunk-I3VHXA2W.js → chunk-Q335R4MR.js} +2 -2
  128. package/dist/cli/chunks/{chunk-ECTPFCON.js → chunk-Q3JHS3UD.js} +2 -2
  129. package/dist/cli/chunks/{chunk-HJIAVR6P.js → chunk-QFUX7ELG.js} +2 -2
  130. package/dist/cli/chunks/{chunk-L4C42WYI.js → chunk-QW4LN5NK.js} +2 -2
  131. package/dist/cli/chunks/{chunk-HQHLHSJO.js → chunk-QXTW7XCS.js} +2 -2
  132. package/dist/cli/chunks/{chunk-SSV6KSFT.js → chunk-R5RNOLHI.js} +1 -1
  133. package/dist/cli/chunks/{chunk-AVLA5PBJ.js → chunk-RCI64RIJ.js} +2 -2
  134. package/dist/cli/chunks/{chunk-T3BZAFLP.js → chunk-RFNEHNJV.js} +1 -1
  135. package/dist/cli/chunks/{chunk-IL6QRXRP.js → chunk-RGH3WGWD.js} +10 -10
  136. package/dist/cli/chunks/{chunk-E4NU4BJA.js → chunk-RHJVDCLV.js} +2 -2
  137. package/dist/cli/chunks/{chunk-KTSCZ7AW.js → chunk-RVCWSAXI.js} +2 -2
  138. package/dist/cli/chunks/{chunk-TQJE7DNL.js → chunk-RYJHREYS.js} +2 -2
  139. package/dist/cli/chunks/{chunk-HNKPLVYS.js → chunk-S4MR6RTE.js} +1 -1
  140. package/dist/cli/chunks/{chunk-6AYO3IR2.js → chunk-S7N4BKI3.js} +2 -2
  141. package/dist/cli/chunks/{chunk-2NO4H35K.js → chunk-SEHCX4NH.js} +1 -1
  142. package/dist/cli/chunks/{chunk-GKNDP5VK.js → chunk-T46LOLW3.js} +2 -2
  143. package/dist/cli/chunks/{chunk-VXU53F7Z.js → chunk-T4C56HBW.js} +2 -2
  144. package/dist/cli/chunks/{chunk-43GPSYAL.js → chunk-TENYL5TI.js} +2 -2
  145. package/dist/cli/chunks/{chunk-6AOZU3UN.js → chunk-TLPL3EQY.js} +2 -2
  146. package/dist/cli/chunks/{chunk-4ZVGSVHV.js → chunk-TYVQNYXX.js} +4 -4
  147. package/dist/cli/chunks/{chunk-NOPVFBQM.js → chunk-U2AY57XZ.js} +2 -2
  148. package/dist/cli/chunks/{chunk-IQLRA4FV.js → chunk-U54OOA24.js} +1 -1
  149. package/dist/cli/chunks/{chunk-IQ3JFHZN.js → chunk-UHTAI4ZB.js} +1 -1
  150. package/dist/cli/chunks/{chunk-KDIZQHG5.js → chunk-UIGEUEBT.js} +2 -2
  151. package/dist/cli/chunks/{chunk-5VDVYTO5.js → chunk-UYTWDS2R.js} +2 -2
  152. package/dist/cli/chunks/{chunk-ZNSMVQCG.js → chunk-VNAKBHJI.js} +2 -2
  153. package/dist/cli/chunks/{chunk-SUSMHSXT.js → chunk-VOYJJ3KA.js} +2 -2
  154. package/dist/cli/chunks/{chunk-QQCENKCX.js → chunk-VSYBMNIR.js} +1 -1
  155. package/dist/cli/chunks/{chunk-7RAB2BZY.js → chunk-W2FLULF4.js} +2 -2
  156. package/dist/cli/chunks/{chunk-NYARYONH.js → chunk-W4OQYLYO.js} +1 -1
  157. package/dist/cli/chunks/{chunk-DOWCOZDO.js → chunk-WBH4C4BG.js} +2 -2
  158. package/dist/cli/chunks/{chunk-OIYUSWHX.js → chunk-WBMRADQP.js} +1 -1
  159. package/dist/cli/chunks/{chunk-B3H4K7CY.js → chunk-WMW47QMR.js} +2 -2
  160. package/dist/cli/chunks/{chunk-VPVZHJSU.js → chunk-WVY22NHZ.js} +2 -2
  161. package/dist/cli/chunks/{chunk-6W42XWLL.js → chunk-WXMSRBQF.js} +2 -2
  162. package/dist/cli/chunks/{chunk-CIUOC5F3.js → chunk-XPLSLHRB.js} +1 -1
  163. package/dist/cli/chunks/{chunk-E722WNWC.js → chunk-YF5OP6CR.js} +2 -2
  164. package/dist/cli/chunks/{chunk-H76TV4UU.js → chunk-YN6W2XIT.js} +3 -3
  165. package/dist/cli/chunks/{chunk-FF43SRP6.js → chunk-ZCDXJ27H.js} +1 -1
  166. package/dist/cli/chunks/{chunk-TKYEP7OR.js → chunk-ZFGND4QK.js} +1 -1
  167. package/dist/cli/chunks/{chunk-O2MZZL54.js → chunk-ZWRQ5VAU.js} +2 -2
  168. package/dist/cli/chunks/{chunk-H6NFDOMK.js → chunk-ZYLSOBOR.js} +1 -1
  169. package/dist/cli/chunks/{ci-B432UH6N.js → ci-NTRH7PAW.js} +2 -2
  170. package/dist/cli/chunks/{ci-output-GTHH7WYG.js → ci-output-F57RSD35.js} +2 -2
  171. package/dist/cli/chunks/{circuit-breaker-VW75DLME.js → circuit-breaker-4WST3QSA.js} +2 -2
  172. package/dist/cli/chunks/{claude-flow-setup-RE3IVT7U.js → claude-flow-setup-KB4TKMYI.js} +2 -2
  173. package/dist/cli/chunks/client-GPZEC54E.js +2 -0
  174. package/dist/cli/chunks/{cline-installer-NUBZZ55N.js → cline-installer-W2ZHQ6WM.js} +2 -2
  175. package/dist/cli/chunks/{code-K6JCWKNW.js → code-TF2AVR5D.js} +2 -2
  176. package/dist/cli/chunks/{code-index-extractor-I4ILB5JN.js → code-index-extractor-RMDRUVQJ.js} +2 -2
  177. package/dist/cli/chunks/codex-installer-VSTRHJHV.js +14 -0
  178. package/dist/cli/chunks/{completions-V3KJVJF4.js → completions-3Q37QVFR.js} +2 -2
  179. package/dist/cli/chunks/{complexity-analyzer-HRG7OOY3.js → complexity-analyzer-3FNFLACD.js} +2 -2
  180. package/dist/cli/chunks/{continuedev-installer-CNTDONWG.js → continuedev-installer-VTEXM455.js} +2 -2
  181. package/dist/cli/chunks/{copilot-installer-XPWWIWYA.js → copilot-installer-AGY7DQUS.js} +2 -2
  182. package/dist/cli/chunks/core-handlers-YMGHYIBR.js +2 -0
  183. package/dist/cli/chunks/{cost-tracker-MFNLQ56K.js → cost-tracker-LTZAQBX7.js} +2 -2
  184. package/dist/cli/chunks/{coverage-KOIK654V.js → coverage-TT64IOS4.js} +3 -3
  185. package/dist/cli/chunks/cross-domain-router-ECBNTGYJ.js +2 -0
  186. package/dist/cli/chunks/{cursor-installer-S5MKLRQQ.js → cursor-installer-OVOJIOHN.js} +2 -2
  187. package/dist/cli/chunks/{daemon-DUS6JYW6.js → daemon-DMFZMXKA.js} +8 -8
  188. package/dist/cli/chunks/{daemon-Z7VPGWHY.js → daemon-XCULEHWY.js} +4 -4
  189. package/dist/cli/chunks/{dag-attention-scheduler-7CQ3ARNI.js → dag-attention-scheduler-WW2RX4B5.js} +2 -2
  190. package/dist/cli/chunks/{detect-WORBCAYF.js → detect-QNWIM232.js} +2 -2
  191. package/dist/cli/chunks/{dist-node-KRNI6OYW.js → dist-node-6GQIY3CG.js} +2 -2
  192. package/dist/cli/chunks/{domain-handler-KRUR2VQG.js → domain-handler-6RJPDELX.js} +2 -2
  193. package/dist/cli/chunks/{domain-transfer-VEOVLV54.js → domain-transfer-WK524LBS.js} +2 -2
  194. package/dist/cli/chunks/dream-EHGKCFWH.js +2 -0
  195. package/dist/cli/chunks/{embed-and-insert-pattern-QU3NQVA5.js → embed-and-insert-pattern-SO6GWJW7.js} +2 -2
  196. package/dist/cli/chunks/{eval-AYQ7BSUP.js → eval-GL544IPO.js} +2 -2
  197. package/dist/cli/chunks/{experience-capture-middleware-AWQBL6LT.js → experience-capture-middleware-BCCJ35OX.js} +3 -3
  198. package/dist/cli/chunks/{fast-paths-V5EL4BYJ.js → fast-paths-CATDDBEU.js} +2 -2
  199. package/dist/cli/chunks/{feature-flags-P34BPRWU.js → feature-flags-BUXNAORY.js} +2 -2
  200. package/dist/cli/chunks/{feature-flags-BXX7BP22.js → feature-flags-KNNWWP5G.js} +2 -2
  201. package/dist/cli/chunks/{file-discovery-MS6BKQ2U.js → file-discovery-S4HF3O7D.js} +2 -2
  202. package/dist/cli/chunks/{fleet-7WVVPA4W.js → fleet-DQVQQONW.js} +3 -3
  203. package/dist/cli/chunks/{gnn-wrapper-7WQ3LEPG.js → gnn-wrapper-G7ABZUG7.js} +2 -2
  204. package/dist/cli/chunks/{heartbeat-handler-P7QD3BZH.js → heartbeat-handler-UFMELIWT.js} +4 -4
  205. package/dist/cli/chunks/heartbeat-scheduler-UFEL2CBW.js +2 -0
  206. package/dist/cli/chunks/hnsw-adapter-BLSD45CX.js +2 -0
  207. package/dist/cli/chunks/hnsw-index-A3RZODEN.js +2 -0
  208. package/dist/cli/chunks/{hnsw-legacy-bridge-Y3GAR3UP.js → hnsw-legacy-bridge-YIILSRXI.js} +2 -2
  209. package/dist/cli/chunks/{hnswlib-node-5QUXZQWQ.js → hnswlib-node-TSVRMXDH.js} +2 -2
  210. package/dist/cli/chunks/{hooks-2D64KPRY.js → hooks-OHQPNK74.js} +10 -10
  211. package/dist/cli/chunks/{hypergraph-engine-5INXEZDP.js → hypergraph-engine-LY7PJDSL.js} +2 -2
  212. package/dist/cli/chunks/{hypergraph-handler-YJJJ3ESZ.js → hypergraph-handler-YGDYZO6H.js} +3 -3
  213. package/dist/cli/chunks/impact-analyzer-OXHD3FOH.js +2 -0
  214. package/dist/cli/chunks/{init-handler-QSFYJN5Q.js → init-handler-MTK65LI3.js} +9 -8
  215. package/dist/cli/chunks/init-wizard-PKZL7QBU.js +2 -0
  216. package/dist/cli/chunks/kernel-XWPM72UJ.js +2 -0
  217. package/dist/cli/chunks/{kilocode-installer-3N3QGTJU.js → kilocode-installer-3IICU4RS.js} +2 -2
  218. package/dist/cli/chunks/{kiro-installer-GIWVTFZQ.js → kiro-installer-MXOVQYQA.js} +2 -2
  219. package/dist/cli/chunks/knowledge-graph-FRKR5XWI.js +2 -0
  220. package/dist/cli/chunks/{learning-SGO2DQ5Q.js → learning-EV5LSOOM.js} +3 -3
  221. package/dist/cli/chunks/{llm-router-HBBULO65.js → llm-router-7LYDJUOT.js} +4 -4
  222. package/dist/cli/chunks/llm-router-service-R7A5HHDM.js +2 -0
  223. package/dist/cli/chunks/{load-B5OFYB4H.js → load-F4PVAMXQ.js} +2 -2
  224. package/dist/cli/chunks/load-test-5IKDWSYL.js +2 -0
  225. package/dist/cli/chunks/{mcp-FG3LNQR4.js → mcp-DUYJUEME.js} +2 -2
  226. package/dist/cli/chunks/{memory-SPS7ZWLC.js → memory-XTTYORAS.js} +5 -5
  227. package/dist/cli/chunks/memory-backend-7VW5QCMO.js +2 -0
  228. package/dist/cli/chunks/{memory-handlers-P7FTPWP3.js → memory-handlers-VZH3R2TQ.js} +2 -2
  229. package/dist/cli/chunks/{multi-model-executor-PUB7E6KH.js → multi-model-executor-R6XCTMCF.js} +2 -2
  230. package/dist/cli/chunks/{opencode-installer-TGCSGVG2.js → opencode-installer-33ULBU2F.js} +2 -2
  231. package/dist/cli/chunks/{orchestrator-S5FTJFGB.js → orchestrator-34ZJEKTJ.js} +22 -21
  232. package/dist/cli/chunks/pattern-null-store-BU6LCB2W.js +2 -0
  233. package/dist/cli/chunks/{pattern-usage-recorder-LCXXGRAB.js → pattern-usage-recorder-GZ2M3F2E.js} +2 -2
  234. package/dist/cli/chunks/{pipeline-ENOSRHKW.js → pipeline-SR5OTY45.js} +2 -2
  235. package/dist/cli/chunks/platform-VKJFJIAW.js +2 -0
  236. package/dist/cli/chunks/{plugin-JZ5ODJSU.js → plugin-5C5UBQUQ.js} +2 -2
  237. package/dist/cli/chunks/{prime-radiant-advanced-wasm-DPJUPNCG.js → prime-radiant-advanced-wasm-KO2PQI3D.js} +2 -2
  238. package/dist/cli/chunks/protocol-executor-BSP5LWJN.js +2 -0
  239. package/dist/cli/chunks/{protocol-handler-IP4NLVY3.js → protocol-handler-ZF74NIKA.js} +2 -2
  240. package/dist/cli/chunks/{prove-P6FM4RU7.js → prove-MO5TQQU4.js} +2 -2
  241. package/dist/cli/chunks/qe-reasoning-bank-J2RC7P25.js +2 -0
  242. package/dist/cli/chunks/{quality-UHP4XO26.js → quality-EYIN6AER.js} +2 -2
  243. package/dist/cli/chunks/quality-gate-V6OQM57O.js +7 -0
  244. package/dist/cli/chunks/queen-coordinator-XI5AJV2V.js +2 -0
  245. package/dist/cli/chunks/{real-embeddings-6SO5MFRQ.js → real-embeddings-AR7TZX7U.js} +2 -2
  246. package/dist/cli/chunks/{roocode-installer-WTWUOFCH.js → roocode-installer-46E626VZ.js} +2 -2
  247. package/dist/cli/chunks/router-VXQYYA3D.js +2 -0
  248. package/dist/cli/chunks/routing-feedback-HZQTASFF.js +2 -0
  249. package/dist/cli/chunks/{routing-handler-IK7HYERQ.js → routing-handler-ZNRVW6QW.js} +2 -2
  250. package/dist/cli/chunks/{ruvector-commands-THLB4NIM.js → ruvector-commands-4L2CQMWS.js} +2 -2
  251. package/dist/cli/chunks/rvf-dual-writer-BDTLLJER.js +2 -0
  252. package/dist/cli/chunks/rvf-migration-adapter-IB343MDN.js +2 -0
  253. package/dist/cli/chunks/{rvf-migration-coordinator-BUKCSHBD.js → rvf-migration-coordinator-H4RVGBIA.js} +2 -2
  254. package/dist/cli/chunks/rvf-native-adapter-Y7SN7LHU.js +2 -0
  255. package/dist/cli/chunks/{rvf-store-integrity-ECTADZIN.js → rvf-store-integrity-OJGWWPLL.js} +2 -2
  256. package/dist/cli/chunks/safe-db-2VTKKBJU.js +2 -0
  257. package/dist/cli/chunks/schedule-QJ4CFGJY.js +2 -0
  258. package/dist/cli/chunks/scheduler-2NHDQPC3.js +2 -0
  259. package/dist/cli/chunks/{security-HN4UXFXX.js → security-JF3BVNRO.js} +3 -3
  260. package/dist/cli/chunks/{shared-rvf-adapter-XJCPX5SN.js → shared-rvf-adapter-M6NNIZ5W.js} +2 -2
  261. package/dist/cli/chunks/{shared-rvf-dual-writer-23X5PNY5.js → shared-rvf-dual-writer-LHMFCYVE.js} +2 -2
  262. package/dist/cli/chunks/sqlite-persistence-NVVAPZN3.js +2 -0
  263. package/dist/cli/chunks/{status-handler-ZXANTHKT.js → status-handler-GMIOXQIE.js} +2 -2
  264. package/dist/cli/chunks/{structural-health-LR6WI3AH.js → structural-health-YZXHVHM6.js} +2 -2
  265. package/dist/cli/chunks/{sync-I5IUJF33.js → sync-GMPCPV5L.js} +2 -2
  266. package/dist/cli/chunks/{sync-4OEI3BC2.js → sync-N56UQGCS.js} +2 -2
  267. package/dist/cli/chunks/{task-handler-R3ATJKU5.js → task-handler-VTNRGAXP.js} +2 -2
  268. package/dist/cli/chunks/{task-handlers-4X357AEW.js → task-handlers-FYSDH55N.js} +3 -3
  269. package/dist/cli/chunks/{test-PR2B5H2F.js → test-GQNCKRSP.js} +4 -4
  270. package/dist/cli/chunks/{test-scheduling-ZNOSQVLD.js → test-scheduling-GPRXSIRP.js} +3 -3
  271. package/dist/cli/chunks/{token-bootstrap-LYXOI72S.js → token-bootstrap-76SRNXGG.js} +2 -2
  272. package/dist/cli/chunks/{token-usage-R6EQZBX2.js → token-usage-O7CZDP5Q.js} +2 -2
  273. package/dist/cli/chunks/{transformers-COQWK27J.js → transformers-LTU4LSSC.js} +2 -2
  274. package/dist/cli/chunks/{tree-sitter-wasm-parser-LLIW2X3M.js → tree-sitter-wasm-parser-NQSQCMBM.js} +2 -2
  275. package/dist/cli/chunks/{types-MEYTZITK.js → types-OP6IWE6N.js} +2 -2
  276. package/dist/cli/chunks/unified-memory-DSTIEDSH.js +2 -0
  277. package/dist/cli/chunks/unified-memory-hnsw-KBV3P4OS.js +2 -0
  278. package/dist/cli/chunks/unified-persistence-XKCOUBKY.js +2 -0
  279. package/dist/cli/chunks/{upgrade-DVIJ456A.js → upgrade-OQWRBZ3R.js} +2 -2
  280. package/dist/cli/chunks/{validate-UYTSMJ5X.js → validate-TH5SRP3E.js} +2 -2
  281. package/dist/cli/chunks/{validate-swarm-P32WCJR6.js → validate-swarm-UITL2JUS.js} +2 -2
  282. package/dist/cli/chunks/{vibium-JGVOLM6X.js → vibium-O6PRAG4J.js} +2 -2
  283. package/dist/cli/chunks/visual-security-TTWSPZTZ.js +2 -0
  284. package/dist/cli/chunks/{web-tree-sitter-5ZGNCTPN.js → web-tree-sitter-XBFBY4OF.js} +2 -2
  285. package/dist/cli/chunks/{windsurf-installer-IILSSQAE.js → windsurf-installer-DVT5NRNY.js} +2 -2
  286. package/dist/cli/chunks/witness-chain-2KY73HPN.js +2 -0
  287. package/dist/cli/chunks/{witness-chain-JZMXCG3B.js → witness-chain-VRSH2F36.js} +2 -2
  288. package/dist/cli/chunks/{witness-key-manager-UUTLNUIH.js → witness-key-manager-GFHRDKQ4.js} +2 -2
  289. package/dist/cli/chunks/{workflow-NS7HXVHZ.js → workflow-HAZ6YKOG.js} +4 -4
  290. package/dist/cli/chunks/workflow-orchestrator-UK56AVOT.js +2 -0
  291. package/dist/cli/chunks/{wrappers-XKEDSV5W.js → wrappers-5LLLT7GM.js} +2 -2
  292. package/dist/cli/commands/daemon.js +3 -0
  293. package/dist/cli/commands/platform.d.ts +1 -0
  294. package/dist/cli/commands/platform.js +28 -6
  295. package/dist/cli/commands/quality-gate.js +25 -3
  296. package/dist/cli/foreground-command.d.ts +3 -0
  297. package/dist/cli/foreground-command.js +22 -0
  298. package/dist/cli/handlers/init-handler.d.ts +5 -0
  299. package/dist/cli/handlers/init-handler.js +6 -0
  300. package/dist/cli/index.js +8 -1
  301. package/dist/contracts/verdicts.d.ts +625 -0
  302. package/dist/contracts/verdicts.js +202 -14
  303. package/dist/coordination/handlers/coverage-handlers.js +8 -1
  304. package/dist/domains/chaos-resilience/diagnosis/corpus.d.ts +5 -0
  305. package/dist/domains/chaos-resilience/diagnosis/corpus.js +141 -0
  306. package/dist/domains/chaos-resilience/diagnosis/detectors.d.ts +11 -0
  307. package/dist/domains/chaos-resilience/diagnosis/detectors.js +109 -0
  308. package/dist/domains/chaos-resilience/diagnosis/index.d.ts +5 -0
  309. package/dist/domains/chaos-resilience/diagnosis/index.js +5 -0
  310. package/dist/domains/chaos-resilience/diagnosis/scorer.d.ts +8 -0
  311. package/dist/domains/chaos-resilience/diagnosis/scorer.js +128 -0
  312. package/dist/domains/chaos-resilience/diagnosis/types.d.ts +171 -0
  313. package/dist/domains/chaos-resilience/diagnosis/types.js +3 -0
  314. package/dist/domains/chaos-resilience/index.d.ts +1 -0
  315. package/dist/domains/chaos-resilience/index.js +1 -0
  316. package/dist/domains/index.d.ts +1 -0
  317. package/dist/domains/index.js +1 -0
  318. package/dist/early-exit/early-exit-controller.d.ts +4 -2
  319. package/dist/early-exit/early-exit-controller.js +95 -7
  320. package/dist/early-exit/index.d.ts +1 -1
  321. package/dist/early-exit/speculative-executor.js +3 -0
  322. package/dist/early-exit/types.d.ts +51 -0
  323. package/dist/early-exit/types.js +3 -0
  324. package/dist/index.d.ts +4 -2
  325. package/dist/index.js +2 -1
  326. package/dist/init/browser-engine-installer.d.ts +11 -0
  327. package/dist/init/browser-engine-installer.js +35 -5
  328. package/dist/init/codex-installer.d.ts +11 -1
  329. package/dist/init/codex-installer.js +90 -24
  330. package/dist/init/init-wizard-hooks.js +11 -11
  331. package/dist/init/orchestrator.js +2 -0
  332. package/dist/init/phases/07-hooks.d.ts +3 -3
  333. package/dist/init/phases/07-hooks.js +19 -18
  334. package/dist/init/phases/09-assets.d.ts +4 -0
  335. package/dist/init/phases/09-assets.js +13 -10
  336. package/dist/init/phases/phase-interface.d.ts +2 -0
  337. package/dist/init/types.d.ts +4 -0
  338. package/dist/learning/index.d.ts +3 -0
  339. package/dist/learning/index.js +2 -0
  340. package/dist/learning/pattern-mutation-error.d.ts +9 -0
  341. package/dist/learning/pattern-mutation-error.js +14 -0
  342. package/dist/learning/pattern-store.js +24 -2
  343. package/dist/learning/qe-reasoning-bank.js +24 -5
  344. package/dist/learning/rvf-pattern-store.js +23 -5
  345. package/dist/learning/structural-retrieval/corpus.d.ts +5 -0
  346. package/dist/learning/structural-retrieval/corpus.js +97 -0
  347. package/dist/learning/structural-retrieval/evaluate.d.ts +7 -0
  348. package/dist/learning/structural-retrieval/evaluate.js +124 -0
  349. package/dist/learning/structural-retrieval/index.d.ts +6 -0
  350. package/dist/learning/structural-retrieval/index.js +4 -0
  351. package/dist/learning/structural-retrieval/receipt.d.ts +14 -0
  352. package/dist/learning/structural-retrieval/receipt.js +36 -0
  353. package/dist/learning/structural-retrieval/types.d.ts +83 -0
  354. package/dist/learning/structural-retrieval/types.js +2 -0
  355. package/dist/mcp/bundle.js +423 -423
  356. package/dist/mcp/index.d.ts +1 -0
  357. package/dist/mcp/index.js +1 -0
  358. package/dist/mcp/protocol-server.js +11 -2
  359. package/dist/mcp/qe-tool-bridge.js +1 -0
  360. package/dist/mcp/services/session-resume.d.ts +15 -19
  361. package/dist/mcp/services/session-resume.js +204 -194
  362. package/dist/mcp/tool-annotations.d.ts +25 -0
  363. package/dist/mcp/tool-annotations.js +75 -0
  364. package/dist/mcp/tool-registry.js +17 -12
  365. package/dist/mcp/tools/base.d.ts +7 -1
  366. package/dist/mcp/tools/base.js +8 -0
  367. package/dist/mcp/tools/quality-assessment/gate.d.ts +8 -5
  368. package/dist/mcp/tools/quality-assessment/gate.js +9 -4
  369. package/dist/mcp/tools/registry.d.ts +3 -0
  370. package/dist/mcp/tools/registry.js +1 -0
  371. package/dist/mcp/types.d.ts +15 -0
  372. package/dist/skills/qe-court/cli.js +0 -0
  373. package/dist/validation/quality-gate-runner.d.ts +27 -4
  374. package/dist/validation/quality-gate-runner.js +33 -4
  375. package/dist/validation/verification-reach.d.ts +90 -0
  376. package/dist/validation/verification-reach.js +187 -0
  377. package/dist/verification/adversarial-verify/index.d.ts +1 -1
  378. package/dist/verification/adversarial-verify/measurement-receipt.d.ts +13 -0
  379. package/dist/verification/adversarial-verify/measurement-receipt.js +136 -0
  380. package/dist/verification/adversarial-verify/synthesize.js +7 -10
  381. package/dist/verification/adversarial-verify/types.d.ts +35 -0
  382. package/dist/verification/adversarial-verify/verify.js +6 -1
  383. package/package.json +9 -5
  384. package/schemas/coverage-gap.schema.json +41 -0
  385. package/schemas/finding-verdict.schema.json +470 -0
  386. package/schemas/risk-decision.schema.json +41 -0
  387. package/dist/cli/chunks/adapter-3VBXL7DO.js +0 -2
  388. package/dist/cli/chunks/aqe-learning-engine-NXRNKJNA.js +0 -2
  389. package/dist/cli/chunks/base-F6GMOKU2.js +0 -2
  390. package/dist/cli/chunks/browser-workflow-QRDC46LR.js +0 -2
  391. package/dist/cli/chunks/chunk-3JIJBR4V.js +0 -2
  392. package/dist/cli/chunks/chunk-R2B6EE45.js +0 -2
  393. package/dist/cli/chunks/chunk-TRDEULS7.js +0 -4
  394. package/dist/cli/chunks/chunk-WJXHE52V.js +0 -65
  395. package/dist/cli/chunks/client-HNBZUEVV.js +0 -2
  396. package/dist/cli/chunks/codex-installer-AKQ5BCHU.js +0 -15
  397. package/dist/cli/chunks/core-handlers-TB7NLYXL.js +0 -2
  398. package/dist/cli/chunks/cross-domain-router-MDSI553U.js +0 -2
  399. package/dist/cli/chunks/dream-X7ISHFEE.js +0 -2
  400. package/dist/cli/chunks/heartbeat-scheduler-2C5XGFQT.js +0 -2
  401. package/dist/cli/chunks/hnsw-adapter-KCVMXLUL.js +0 -2
  402. package/dist/cli/chunks/hnsw-index-OGWZS6MP.js +0 -2
  403. package/dist/cli/chunks/impact-analyzer-IBJ43GQL.js +0 -2
  404. package/dist/cli/chunks/init-wizard-6XMFD5LP.js +0 -2
  405. package/dist/cli/chunks/kernel-UDUMUPB3.js +0 -2
  406. package/dist/cli/chunks/knowledge-graph-JRYTUG3W.js +0 -2
  407. package/dist/cli/chunks/llm-router-service-KF5ZALUQ.js +0 -2
  408. package/dist/cli/chunks/load-test-LHMBCNCH.js +0 -2
  409. package/dist/cli/chunks/memory-backend-WZHKHBZK.js +0 -2
  410. package/dist/cli/chunks/pattern-null-store-UZSHCRL2.js +0 -2
  411. package/dist/cli/chunks/platform-WCRBO3Z7.js +0 -2
  412. package/dist/cli/chunks/protocol-executor-42NLVDTC.js +0 -2
  413. package/dist/cli/chunks/qe-reasoning-bank-W74RSMMU.js +0 -2
  414. package/dist/cli/chunks/quality-gate-63DDBSGM.js +0 -7
  415. package/dist/cli/chunks/queen-coordinator-XELKSRMS.js +0 -2
  416. package/dist/cli/chunks/router-GTW2EQZV.js +0 -2
  417. package/dist/cli/chunks/routing-feedback-NVOBWEMK.js +0 -2
  418. package/dist/cli/chunks/rvf-dual-writer-5OPVMXNL.js +0 -2
  419. package/dist/cli/chunks/rvf-migration-adapter-5S4YFTX4.js +0 -2
  420. package/dist/cli/chunks/rvf-native-adapter-LYSJHEVX.js +0 -2
  421. package/dist/cli/chunks/safe-db-AEB3JMLD.js +0 -2
  422. package/dist/cli/chunks/schedule-4QNPCQNT.js +0 -2
  423. package/dist/cli/chunks/scheduler-S3DFHX6A.js +0 -2
  424. package/dist/cli/chunks/sqlite-persistence-L2KISU2H.js +0 -2
  425. package/dist/cli/chunks/unified-memory-5KQMA7FV.js +0 -2
  426. package/dist/cli/chunks/unified-memory-hnsw-PQRPTYOD.js +0 -2
  427. package/dist/cli/chunks/unified-persistence-YDONVPJB.js +0 -2
  428. package/dist/cli/chunks/visual-security-RJ7RTNGJ.js +0 -2
  429. package/dist/cli/chunks/witness-chain-YXXXNGAM.js +0 -2
  430. package/dist/cli/chunks/workflow-orchestrator-5KUAVSTH.js +0 -2
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.0");process.exit(0)}
2
- import{a as G,b as H}from"./chunk-NOPVFBQM.js";import{h as U}from"./chunk-IL6QRXRP.js";import{e as N}from"./chunk-UUJ5VQJM.js";import{a as W}from"./chunk-WJXHE52V.js";import{e as F}from"./chunk-A7SKM6JL.js";import{b as v,c as x}from"./chunk-RKUYVVGJ.js";import{a as ae}from"./chunk-R2B6EE45.js";import{c as O}from"./chunk-JY4VZ6BN.js";import{b as k,d as q}from"./chunk-HQHLHSJO.js";import{b,c as E}from"./chunk-JGROLJ33.js";import{a as y,c as I}from"./chunk-XITTURP2.js";import{i as z}from"./chunk-FOHYBR3O.js";import{S as se,b as _}from"./chunk-ENGKLFLY.js";import{randomUUID as ee}from"crypto";I();q();import{randomUUID as oe}from"node:crypto";var B=x(),P=class{constructor(e){this.options=e}options;claudeFlowAvailable=!1;localTrajectories=new Map;async initialize(){this.claudeFlowAvailable=await this.checkClaudeFlow()}async checkClaudeFlow(){return v(this.options.projectRoot).available}async startTrajectory(e,t){let i=`trajectory-${oe()}`;if(this.claudeFlowAvailable)try{let{execFileSync:r}=await import("child_process"),n=["--no-install",B,"hooks","intelligence","trajectory-start","--task",e];t&&n.push("--agent",t);let s=r("npx",n,{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot}).match(/trajectoryId[:\s]+["']?([^"'\s,}]+)/i);if(s?.[1])return s[1]}catch(r){console.debug("[TrajectoryBridge] Claude Flow trajectory start failed:",r instanceof Error?r.message:r)}return this.localTrajectories.set(i,{id:i,task:e,agent:t,steps:[],startedAt:Date.now()}),i}async recordStep(e,t,i,r){if(this.claudeFlowAvailable)try{let{execFileSync:a}=await import("child_process"),s=["--no-install",B,"hooks","intelligence","trajectory-step","--trajectory-id",e,"--action",t];i&&s.push("--result",i),r!==void 0&&s.push("--quality",String(r)),a("npx",s,{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot});return}catch(a){console.debug("[TrajectoryBridge] Claude Flow trajectory step failed:",a instanceof Error?a.message:a)}let n=this.localTrajectories.get(e);n&&n.steps.push({id:`step-${n.steps.length+1}`,action:t,result:i,quality:r,timestamp:Date.now()})}async endTrajectory(e,t,i){if(this.claudeFlowAvailable)try{let{execFileSync:n}=await import("child_process"),a=["--no-install",B,"hooks","intelligence","trajectory-end","--trajectory-id",e,"--success",String(t)];i&&a.push("--feedback",i),n("npx",a,{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot})}catch{}let r=this.localTrajectories.get(e);if(r)return r.success=t,r.feedback=i,r.completedAt=Date.now(),await this.persistTrajectory(r),r}getTrajectory(e){return this.localTrajectories.get(e)}isClaudeFlowAvailable(){return this.claudeFlowAvailable}async persistTrajectory(e){try{let{getUnifiedMemory:t}=await import("./unified-memory-5KQMA7FV.js"),i=t();i.isInitialized()||await i.initialize();let r=i.getDatabase();try{r.prepare("PRAGMA table_info(qe_trajectories)").all().some(o=>o.name==="feedback")||r.exec("ALTER TABLE qe_trajectories ADD COLUMN feedback TEXT")}catch{}let n=new Date(e.startedAt).toISOString(),a=e.completedAt?new Date(e.completedAt).toISOString():null;r.prepare(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.2");process.exit(0)}
2
+ import{a as G,b as H}from"./chunk-U2AY57XZ.js";import{h as U}from"./chunk-RGH3WGWD.js";import{e as N}from"./chunk-CJHVOBJY.js";import{b as W}from"./chunk-4UCMTYFQ.js";import{e as F}from"./chunk-C7AXRI7E.js";import{b as v,c as x}from"./chunk-PFXX5Q32.js";import{a as ae}from"./chunk-PHHXHG2W.js";import{c as O}from"./chunk-ICKLBATY.js";import{b as k,d as q}from"./chunk-QXTW7XCS.js";import{b,c as E}from"./chunk-CIESXO73.js";import{a as y,c as I}from"./chunk-D4RCV4LY.js";import{i as z}from"./chunk-NG2UVPTW.js";import{S as se,b as _}from"./chunk-GHQ5PUOV.js";import{randomUUID as ee}from"crypto";I();q();import{randomUUID as oe}from"node:crypto";var B=x(),P=class{constructor(e){this.options=e}options;claudeFlowAvailable=!1;localTrajectories=new Map;async initialize(){this.claudeFlowAvailable=await this.checkClaudeFlow()}async checkClaudeFlow(){return v(this.options.projectRoot).available}async startTrajectory(e,t){let i=`trajectory-${oe()}`;if(this.claudeFlowAvailable)try{let{execFileSync:r}=await import("child_process"),n=["--no-install",B,"hooks","intelligence","trajectory-start","--task",e];t&&n.push("--agent",t);let s=r("npx",n,{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot}).match(/trajectoryId[:\s]+["']?([^"'\s,}]+)/i);if(s?.[1])return s[1]}catch(r){console.debug("[TrajectoryBridge] Claude Flow trajectory start failed:",r instanceof Error?r.message:r)}return this.localTrajectories.set(i,{id:i,task:e,agent:t,steps:[],startedAt:Date.now()}),i}async recordStep(e,t,i,r){if(this.claudeFlowAvailable)try{let{execFileSync:a}=await import("child_process"),s=["--no-install",B,"hooks","intelligence","trajectory-step","--trajectory-id",e,"--action",t];i&&s.push("--result",i),r!==void 0&&s.push("--quality",String(r)),a("npx",s,{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot});return}catch(a){console.debug("[TrajectoryBridge] Claude Flow trajectory step failed:",a instanceof Error?a.message:a)}let n=this.localTrajectories.get(e);n&&n.steps.push({id:`step-${n.steps.length+1}`,action:t,result:i,quality:r,timestamp:Date.now()})}async endTrajectory(e,t,i){if(this.claudeFlowAvailable)try{let{execFileSync:n}=await import("child_process"),a=["--no-install",B,"hooks","intelligence","trajectory-end","--trajectory-id",e,"--success",String(t)];i&&a.push("--feedback",i),n("npx",a,{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot})}catch{}let r=this.localTrajectories.get(e);if(r)return r.success=t,r.feedback=i,r.completedAt=Date.now(),await this.persistTrajectory(r),r}getTrajectory(e){return this.localTrajectories.get(e)}isClaudeFlowAvailable(){return this.claudeFlowAvailable}async persistTrajectory(e){try{let{getUnifiedMemory:t}=await import("./unified-memory-DSTIEDSH.js"),i=t();i.isInitialized()||await i.initialize();let r=i.getDatabase();try{r.prepare("PRAGMA table_info(qe_trajectories)").all().some(o=>o.name==="feedback")||r.exec("ALTER TABLE qe_trajectories ADD COLUMN feedback TEXT")}catch{}let n=new Date(e.startedAt).toISOString(),a=e.completedAt?new Date(e.completedAt).toISOString():null;r.prepare(`
3
3
  INSERT OR REPLACE INTO qe_trajectories
4
4
  (id, task, agent, domain, started_at, ended_at, success, steps_json, feedback)
5
5
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
@@ -9,4 +9,4 @@ Steps:
9
9
  ${e.steps.map((n,a)=>`${a+1}. ${n.action}${n.result?` \u2192 ${n.result}`:""}`).join(`
10
10
  `)}
11
11
 
12
- Duration: ${e.durationMs}ms`;return{patternType:t,name:this.generatePatternName(e),description:`Pattern extracted from: ${e.task}`,context:{tags:this.extractTags(e),testType:this.detectTestType(e.task)},template:{type:"workflow",content:r,variables:[{name:"task",type:"string",description:"The task to execute",required:!0}]}}}detectPatternType(e){let t=e.toLowerCase();return t.includes("test")||t.includes("spec")?(t.includes("unit")||t.includes("integration")||t.includes("e2e"),"test-template"):t.includes("mock")||t.includes("stub")?"mock-pattern":t.includes("assert")||t.includes("expect")?"assertion-pattern":t.includes("coverage")?"coverage-strategy":t.includes("api")||t.includes("contract")?"api-contract":t.includes("visual")||t.includes("screenshot")?"visual-baseline":t.includes("accessibility")||t.includes("a11y")?"a11y-check":t.includes("performance")||t.includes("perf")?"perf-benchmark":t.includes("flaky")?"flaky-fix":t.includes("refactor")?"refactor-safe":t.includes("error")||t.includes("exception")?"error-handling":"test-template"}generatePatternName(e){let t=e.task.replace(/[^a-zA-Z0-9\s-]/g,"").slice(0,50).trim();return`${e.domain?`[${e.domain}] `:""}${t}`}extractTags(e){let t=[];e.domain&&t.push(e.domain),e.agent&&t.push(e.agent),e.model&&t.push(`model:${e.model}`);let i=e.task.toLowerCase().split(/\s+/),r=["unit","integration","e2e","api","mock","coverage","security"];for(let n of r)i.some(a=>a.includes(n))&&t.push(n);return t}detectTestType(e){let t=e.toLowerCase();if(t.includes("unit"))return"unit";if(t.includes("integration"))return"integration";if(t.includes("e2e")||t.includes("end-to-end"))return"e2e";if(t.includes("contract")||t.includes("api"))return"contract";if(t.includes("smoke"))return"smoke"}getRelatedDomains(e){return{"test-generation":["test-execution","coverage-analysis"],"test-execution":["test-generation","coverage-analysis","quality-assessment"],"coverage-analysis":["test-generation","test-execution"],"quality-assessment":["test-execution","defect-intelligence"],"defect-intelligence":["quality-assessment","code-intelligence"],"requirements-validation":["test-generation","quality-assessment"],"code-intelligence":["defect-intelligence","security-compliance"],"security-compliance":["code-intelligence","quality-assessment"],"contract-testing":["test-generation","test-execution"],"visual-accessibility":["quality-assessment","test-execution"],"chaos-resilience":["test-execution","quality-assessment"],"learning-optimization":[]}[e]||[]}emitExperienceCaptured(e){this.eventBus&&this.eventBus.publish({id:`exp-captured-${e.id}`,type:"learning.ExperienceCaptured",source:"learning-optimization",timestamp:new Date,payload:{experience:e,reward:e.reward,testOutcome:e.testOutcome}})}async loadStats(){try{let e=await this.memory.get(`${this.config.namespace}:stats`);e&&(this.stats.totalCaptured=e.totalCaptured,this.stats.successfulCaptures=e.successfulCaptures,this.stats.patternsExtracted=e.patternsExtracted,this.stats.patternsPromoted=e.patternsPromoted,this.stats.byDomain=new Map(e.byDomain))}catch(e){T.debug("Stats restoration failed, starting fresh",{error:e instanceof Error?e.message:String(e)})}}async saveStats(){try{await this.memory.set(`${this.config.namespace}:stats`,{totalCaptured:this.stats.totalCaptured,successfulCaptures:this.stats.successfulCaptures,patternsExtracted:this.stats.patternsExtracted,patternsPromoted:this.stats.patternsPromoted,byDomain:Array.from(this.stats.byDomain.entries())},{persist:!0})}catch(e){console.error("[ExperienceCapture] Failed to save stats:",e)}}};function Y(l,e,t,i){return new Q(l,e,t,i)}var de={enableClaudeFlow:!0,enableExperienceCapture:!0,enablePatternPromotion:!0,promotionThreshold:F},L=class{constructor(e,t,i){this.memory=e;this.eventBus=i;this.config={...de,...t}}memory;eventBus;config;reasoningBank;claudeFlowBridge;experienceCapture;patternStore;coherenceService;initialized=!1;_domainTransferEngine=null;_domainTransferInterval=null;activeTasks=new Map;completedTasks=0;claudeFlowErrors=0;async initialize(){if(!this.initialized){try{this.coherenceService=await G(H),this.coherenceService.isInitialized()&&console.log("[AQELearningEngine] CoherenceService initialized with WASM engines")}catch(e){console.log("[AQELearningEngine] CoherenceService WASM unavailable, using fallback:",y(e))}this.patternStore=W(this.memory,{promotionThreshold:this.config.promotionThreshold}),await this.patternStore.initialize(),this.reasoningBank=U(this.memory,this.eventBus,this.config.reasoningBank,this.coherenceService),await this.reasoningBank.initialize();try{let{getSharedRvfDualWriter:e}=await import("./shared-rvf-dual-writer-23X5PNY5.js"),t=await e();t&&this.reasoningBank.setRvfDualWriter(t)}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] RVF wiring skipped:",e instanceof Error?e.message:e)}if(this.config.enableExperienceCapture){this.experienceCapture=Y(this.memory,this.patternStore,this.eventBus,{promotionThreshold:this.config.promotionThreshold}),await this.experienceCapture.initialize();try{let{isWitnessChainFeatureEnabled:e}=await import("./witness-chain-JZMXCG3B.js");if(e()){let{createPersistentWitnessChain:t,createWitnessChainSQLitePersistence:i}=await import("./witness-chain-JZMXCG3B.js"),{getUnifiedPersistence:r}=await import("./unified-persistence-YDONVPJB.js"),n=r();if(n.isInitialized()){let a=n.getDatabase(),s=i(a),o=t(s);this.experienceCapture.setWitnessChain(o)}}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Witness chain wiring skipped:",e instanceof Error?e.message:e)}try{let{getUnifiedPersistence:e}=await import("./unified-persistence-YDONVPJB.js"),t=e();if(t.isInitialized()){let{PatternNullStore:i}=await import("./pattern-null-store-UZSHCRL2.js"),r=new i(t.getDatabase());this.experienceCapture.setNullRecorder(n=>r.recordNull(n))}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Null recorder wiring skipped:",e instanceof Error?e.message:e)}}try{let{isCrossDomainTransferEnabled:e}=await import("./feature-flags-P34BPRWU.js");if(e()&&this.patternStore){let{createDomainTransferEngine:t}=await import("./domain-transfer-VEOVLV54.js"),i=t(),r=this.patternStore,n=await r.getStats();this._domainTransferInterval=setInterval(async()=>{try{n=await r.getStats()}catch(a){process.env.DEBUG&&console.debug("[AQELearningEngine] Stats refresh failed:",a instanceof Error?a.message:a)}},6e4),this._domainTransferInterval.unref?.(),i.setPerformanceProvider(a=>{let s=n.byDomain?.[a]??0,o=n.totalPatterns??0;return{domain:a,successRate:o>0?s/o:.5,avgConfidence:n.avgConfidence??.5,patternCount:s,timestamp:Date.now()}}),this._domainTransferEngine=i}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Domain transfer wiring skipped:",e instanceof Error?e.message:e)}if(this.config.enableClaudeFlow)try{this.claudeFlowBridge=X({projectRoot:this.config.projectRoot}),await this.claudeFlowBridge.initialize(),this.claudeFlowBridge.isAvailable()&&console.log("[AQELearningEngine] Claude Flow integration enabled")}catch(e){process.env.DEBUG&&console.log("[AQELearningEngine] Claude Flow not available, using standalone mode:",y(e))}this.initialized=!0,console.log("[AQELearningEngine] Initialized")}}getStatus(){let e=this.claudeFlowBridge?.getStatus();return{initialized:this.initialized,claudeFlowAvailable:e?.available??!1,features:{patternLearning:!0,vectorSearch:!0,taskRouting:!0,trajectories:e?.features.trajectories??!1,modelRouting:e?.features.modelRouting??!1,pretrain:e?.features.pretrain??!1}}}async getStats(){if(!this.initialized||!this.reasoningBank)throw new Error("Engine not initialized");let e=await this.reasoningBank.getStats(),t=this.experienceCapture?await this.experienceCapture.getStats():{totalExperiences:0,byDomain:{},successRate:0,avgQuality:0,patternsExtracted:0,patternsPromoted:0};return{...e,activeTasks:this.activeTasks.size,completedTasks:this.completedTasks,claudeFlowStatus:this.claudeFlowBridge?.getStatus()??{available:!1,features:{trajectories:!1,modelRouting:!1,pretrain:!1,patternSearch:!1}},claudeFlowErrors:this.claudeFlowErrors,experienceCapture:t}}async storePattern(e){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.storePattern(e)}async searchPatterns(e,t){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.searchPatterns(e,t)}async getPattern(e){return!this.initialized||!this.reasoningBank?null:this.reasoningBank.getPattern(e)}async recordOutcome(e){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.recordOutcome(e)}async routeTask(e){if(!this.initialized||!this.reasoningBank)return E(new Error("Engine not initialized"));let t=await this.searchPatternsForTask(e.task,{limit:5,minConfidence:.4,domain:e.domain,contextFingerprint:e.domain?`${e.domain}:router`:void 0});t.success&&t.value.length>0&&await this.trackPatternSearch(e.task,t.value);let i=await this.reasoningBank.routeTask(e);if(i.success&&this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable(),i.success&&t.success){let r=N(i.value,t.value);return b(r)}return i}async route(e,t){let i=await this.routeTask({task:e,context:t});return i.success?i.value:null}async searchPatternsForTask(e,t={}){if(!this.reasoningBank)return b([]);try{return await this.reasoningBank.searchPatterns(e,{limit:t.limit||5,minConfidence:t.minConfidence||.4,domain:t.domain,contextFingerprint:t.contextFingerprint,useVectorSearch:!0})}catch(i){return console.warn("[AQELearningEngine] Pattern search failed:",y(i)),b([])}}async trackPatternSearch(e,t){let i={timestamp:Date.now(),task:e.slice(0,500),patternsFound:t.length,patternIds:t.map(r=>r.pattern.id),avgSimilarity:t.length>0?t.reduce((r,n)=>r+n.similarity,0)/t.length:0};try{let r=`pattern-usage:search:${Date.now()}-${ee().slice(0,8)}`;await this.memory.set(r,i,{persist:!0,ttl:10080*60})}catch(r){console.debug("[AQELearningEngine] Failed to track pattern search:",y(r))}}async recommendModel(e){if(this.claudeFlowBridge?.modelRouter.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.modelRouter.routeTask(e)}catch(t){console.debug("[AQELearningEngine] Claude Flow model routing failed:",t instanceof Error?t.message:t)}return this.localModelRoute(e)}async recordModelOutcome(e,t,i){this.claudeFlowBridge?.modelRouter.isClaudeFlowAvailable()&&await this.claudeFlowBridge.modelRouter.recordOutcome({task:e,model:t,outcome:i})}localModelRoute(e){let t=e.toLowerCase(),i=[/simple/i,/basic/i,/fix typo/i,/rename/i,/format/i,/add comment/i,/lint/i,/minor/i,/quick/i,/small/i];for(let n of i)if(n.test(t))return{model:"haiku",confidence:.75,reasoning:"Low complexity task - using haiku for speed"};let r=[/architect/i,/design/i,/complex/i,/security/i,/performance/i,/refactor.*large/i,/critical/i,/analysis/i,/multi.*file/i,/distributed/i,/concurrent/i,/migration/i];for(let n of r)if(n.test(t))return{model:"opus",confidence:.8,reasoning:"High complexity task - using opus for capability"};return e.length>500?{model:"opus",confidence:.65,reasoning:"Long task description - using opus for complex reasoning"}:e.length<50?{model:"haiku",confidence:.6,reasoning:"Short task - using haiku for efficiency"}:{model:"sonnet",confidence:.7,reasoning:"Medium complexity - using sonnet for balance"}}async startTask(e,t,i){let r=`task-${Date.now()}-${ee().slice(0,8)}`,n=r;if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{n=await this.claudeFlowBridge.trajectory.startTrajectory(e,t)}catch(u){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow startTrajectory failed (${this.claudeFlowErrors} total errors):`,y(u))}let a=`${i??"unknown"}:${t??"unknown"}`,s;try{let u=await this.searchPatternsForTask(e,{domain:i,contextFingerprint:a});u.success&&u.value.length>0&&(s=u.value.map(g=>g.pattern.id))}catch{}let o;this.experienceCapture&&(o=this.experienceCapture.startCapture(e,{agent:t,domain:i,trajectoryId:n!==r?n:void 0,appliedPatterns:s}));let p={id:o||n,task:e,agent:t,startedAt:Date.now(),steps:[]};return this.activeTasks.set(p.id,p),p.id}async recordStep(e,t,i,r){if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{await this.claudeFlowBridge.trajectory.recordStep(e,t,i,r)}catch(a){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow recordStep failed (${this.claudeFlowErrors} total errors):`,y(a))}this.experienceCapture&&this.experienceCapture.recordStep(e,{action:t,result:i,quality:r});let n=this.activeTasks.get(e);n&&n.steps.push({action:t,result:i,quality:r,timestamp:Date.now()})}async endTask(e,t,i){if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{await this.claudeFlowBridge.trajectory.endTrajectory(e,t,i)}catch(n){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow endTrajectory failed (${this.claudeFlowErrors} total errors):`,y(n))}let r=this.activeTasks.get(e);if(r)return this.activeTasks.delete(e),this.completedTasks++,this.config.enableExperienceCapture&&t&&await this.captureExperience(r),r}getTask(e){return this.activeTasks.get(e)}async analyzeCodebase(e,t="medium"){let i=e||this.config.projectRoot;if(this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.pretrain.analyze(i,t)}catch(r){console.debug("[AQELearningEngine] Claude Flow pretrain analyze failed:",r instanceof Error?r.message:r)}return this.localAnalyze(i,t)}async generateAgentConfigs(e="yaml"){if(this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.pretrain.generateAgentConfigs(e)}catch(t){console.debug("[AQELearningEngine] Claude Flow agent config failed:",t instanceof Error?t.message:t)}return[{name:"qe-test-architect",type:"worker",capabilities:["test-generation","test-design"],model:"sonnet"},{name:"qe-coverage-specialist",type:"worker",capabilities:["coverage-analysis","gap-detection"],model:"haiku"},{name:"qe-security-scanner",type:"worker",capabilities:["security-scanning","vulnerability-detection"],model:"opus"}]}async captureExperience(e){if(!this.experienceCapture||!this.config.enableExperienceCapture)return;let t=e.steps.length>0?e.steps.reduce((r,n)=>r+(n.quality??.5),0)/e.steps.length:.5;await this.experienceCapture.completeCapture(e.id,{success:!0,quality:t});let i=await this.experienceCapture.getExperience(e.id);i&&i.quality>=.7&&await this.experienceCapture.shareAcrossDomains(i)}startExperienceCapture(e,t){if(this.experienceCapture)return this.experienceCapture.startCapture(e,t)}getExperienceCaptureService(){return this.experienceCapture}async localAnalyze(e,t){try{let i=await import("fast-glob"),{existsSync:r,readFileSync:n}=await import("fs"),{join:a}=await import("path"),s=t==="shallow"?["*.ts","*.js","*.json"]:t==="medium"?["**/*.ts","**/*.js","**/*.json","**/*.py"]:["**/*"],o=["node_modules/**","dist/**","coverage/**",".git/**"],p=await i.default(s,{cwd:e,ignore:o,onlyFiles:!0}),u=new Set,g=new Set;for(let m of p.slice(0,100))(m.endsWith(".ts")||m.endsWith(".tsx"))&&u.add("typescript"),(m.endsWith(".js")||m.endsWith(".jsx"))&&u.add("javascript"),m.endsWith(".py")&&u.add("python"),m.endsWith(".go")&&u.add("go"),m.endsWith(".rs")&&u.add("rust");let w=a(e,"package.json");if(r(w))try{let m=k(n(w,"utf-8")),d={...m.dependencies,...m.devDependencies};d.react&&g.add("react"),d.vue&&g.add("vue"),d.vitest&&g.add("vitest"),d.jest&&g.add("jest"),d.playwright&&g.add("playwright")}catch(m){console.debug("[AQELearningEngine] package.json parse failed:",m instanceof Error?m.message:m)}return{success:!0,repositoryPath:e,depth:t,analysis:{languages:Array.from(u),frameworks:Array.from(g),patterns:[],complexity:p.length>500?3:p.length>100?2:1}}}catch(i){return{success:!1,repositoryPath:e,depth:t,error:y(i)}}}getGuidance(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.getGuidance(e,t)}generateContext(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.generateContext(e,t)}checkAntiPatterns(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.checkAntiPatterns(e,t)}async dispose(){this._domainTransferInterval&&(clearInterval(this._domainTransferInterval),this._domainTransferInterval=null),this._domainTransferEngine=null,this.experienceCapture&&await this.experienceCapture.dispose(),this.patternStore&&await this.patternStore.dispose(),this.reasoningBank&&await this.reasoningBank.dispose(),this.activeTasks.clear(),this.initialized=!1}},pe={enabled:!1,snapshotIntervalMs:3e5,minSnapshotsForAnalysis:5,autoApplyThreshold:.8},te=class{config;constructor(e){this.config={...pe,...e}}runMetaLearningCycle(e){if(process.env.AQE_META_LEARNING_ENABLED!=="true")return[];if(!this.config.enabled)return[];if(e.length<this.config.minSnapshotsForAnalysis)return[];let t=Math.floor(e.length/2),i=e.slice(0,t),r=e.slice(t),n=[],a=Date.now(),s=h(i.map(c=>c.tokenMetrics.costUsd)),o=h(r.map(c=>c.tokenMetrics.costUsd)),p=h(i.map(c=>c.tokenMetrics.savingsUsd)),u=h(r.map(c=>c.tokenMetrics.savingsUsd));if(o>s*1.1&&u<=p*1.05){let c=Math.min(1,(o-s)/(s||1));n.push({id:`meta-tw-${a}`,type:"token-waste",description:`Token cost increased by ${((o/(s||1)-1)*100).toFixed(1)}% while savings remained flat`,confidence:A(c),suggestedAction:"Review cache configuration and increase pattern reuse thresholds",detectedAt:a})}let g=h(i.map(c=>c.qualityMetrics.gatePassRate)),w=h(r.map(c=>c.qualityMetrics.gatePassRate));Math.abs(w-g)<.02&&e.length>=this.config.minSnapshotsForAnalysis&&n.push({id:`meta-qp-${a}`,type:"quality-plateau",description:`Gate pass rate has been flat at ${(w*100).toFixed(1)}% across ${e.length} snapshots`,confidence:A(.6+(e.length-this.config.minSnapshotsForAnalysis)*.05),suggestedAction:"Consider reviewing quality thresholds or adding new test coverage domains",detectedAt:a});let d=h(i.map(c=>c.learningMetrics.patternCount)),f=h(r.map(c=>c.learningMetrics.patternCount)),ie=h(i.map(c=>c.learningMetrics.averageConfidence)),$=h(r.map(c=>c.learningMetrics.averageConfidence)),re=Math.abs(f-d),ne=Math.abs($-ie);re<1&&ne<.02&&n.push({id:`meta-ls-${a}`,type:"learning-stall",description:`Pattern count (~${Math.round(f)}) and confidence (~${$.toFixed(2)}) have stagnated`,confidence:A(.65+(e.length-this.config.minSnapshotsForAnalysis)*.04),suggestedAction:"Expand to new QE domains or lower pattern creation thresholds to encourage exploration",detectedAt:a});let C=h(i.map(c=>c.performanceMetrics.p95LatencyMs)),j=h(r.map(c=>c.performanceMetrics.p95LatencyMs));if(j>C*1.2&&C>0){let c=Math.min(1,(j-C)/(C||1));n.push({id:`meta-pr-${a}`,type:"performance-regression",description:`P95 latency increased from ${C.toFixed(0)}ms to ${j.toFixed(0)}ms`,confidence:A(c),suggestedAction:"Profile hot paths and consider HNSW index tuning or batch size reduction",detectedAt:a})}return n}shouldAutoApply(e,t){let i=(t??this.config).autoApplyThreshold;return e.confidence>=i}};function h(l){return l.length===0?0:l.reduce((e,t)=>e+t,0)/l.length}function A(l){return Math.max(0,Math.min(1,l))}function ge(l,e,t){return new L(l,e,t)}function it(l,e,t){return ge(l,{projectRoot:e},t)}export{de as a,L as b,pe as c,te as d,ge as e,it as f};
12
+ Duration: ${e.durationMs}ms`;return{patternType:t,name:this.generatePatternName(e),description:`Pattern extracted from: ${e.task}`,context:{tags:this.extractTags(e),testType:this.detectTestType(e.task)},template:{type:"workflow",content:r,variables:[{name:"task",type:"string",description:"The task to execute",required:!0}]}}}detectPatternType(e){let t=e.toLowerCase();return t.includes("test")||t.includes("spec")?(t.includes("unit")||t.includes("integration")||t.includes("e2e"),"test-template"):t.includes("mock")||t.includes("stub")?"mock-pattern":t.includes("assert")||t.includes("expect")?"assertion-pattern":t.includes("coverage")?"coverage-strategy":t.includes("api")||t.includes("contract")?"api-contract":t.includes("visual")||t.includes("screenshot")?"visual-baseline":t.includes("accessibility")||t.includes("a11y")?"a11y-check":t.includes("performance")||t.includes("perf")?"perf-benchmark":t.includes("flaky")?"flaky-fix":t.includes("refactor")?"refactor-safe":t.includes("error")||t.includes("exception")?"error-handling":"test-template"}generatePatternName(e){let t=e.task.replace(/[^a-zA-Z0-9\s-]/g,"").slice(0,50).trim();return`${e.domain?`[${e.domain}] `:""}${t}`}extractTags(e){let t=[];e.domain&&t.push(e.domain),e.agent&&t.push(e.agent),e.model&&t.push(`model:${e.model}`);let i=e.task.toLowerCase().split(/\s+/),r=["unit","integration","e2e","api","mock","coverage","security"];for(let n of r)i.some(a=>a.includes(n))&&t.push(n);return t}detectTestType(e){let t=e.toLowerCase();if(t.includes("unit"))return"unit";if(t.includes("integration"))return"integration";if(t.includes("e2e")||t.includes("end-to-end"))return"e2e";if(t.includes("contract")||t.includes("api"))return"contract";if(t.includes("smoke"))return"smoke"}getRelatedDomains(e){return{"test-generation":["test-execution","coverage-analysis"],"test-execution":["test-generation","coverage-analysis","quality-assessment"],"coverage-analysis":["test-generation","test-execution"],"quality-assessment":["test-execution","defect-intelligence"],"defect-intelligence":["quality-assessment","code-intelligence"],"requirements-validation":["test-generation","quality-assessment"],"code-intelligence":["defect-intelligence","security-compliance"],"security-compliance":["code-intelligence","quality-assessment"],"contract-testing":["test-generation","test-execution"],"visual-accessibility":["quality-assessment","test-execution"],"chaos-resilience":["test-execution","quality-assessment"],"learning-optimization":[]}[e]||[]}emitExperienceCaptured(e){this.eventBus&&this.eventBus.publish({id:`exp-captured-${e.id}`,type:"learning.ExperienceCaptured",source:"learning-optimization",timestamp:new Date,payload:{experience:e,reward:e.reward,testOutcome:e.testOutcome}})}async loadStats(){try{let e=await this.memory.get(`${this.config.namespace}:stats`);e&&(this.stats.totalCaptured=e.totalCaptured,this.stats.successfulCaptures=e.successfulCaptures,this.stats.patternsExtracted=e.patternsExtracted,this.stats.patternsPromoted=e.patternsPromoted,this.stats.byDomain=new Map(e.byDomain))}catch(e){T.debug("Stats restoration failed, starting fresh",{error:e instanceof Error?e.message:String(e)})}}async saveStats(){try{await this.memory.set(`${this.config.namespace}:stats`,{totalCaptured:this.stats.totalCaptured,successfulCaptures:this.stats.successfulCaptures,patternsExtracted:this.stats.patternsExtracted,patternsPromoted:this.stats.patternsPromoted,byDomain:Array.from(this.stats.byDomain.entries())},{persist:!0})}catch(e){console.error("[ExperienceCapture] Failed to save stats:",e)}}};function Y(l,e,t,i){return new Q(l,e,t,i)}var de={enableClaudeFlow:!0,enableExperienceCapture:!0,enablePatternPromotion:!0,promotionThreshold:F},L=class{constructor(e,t,i){this.memory=e;this.eventBus=i;this.config={...de,...t}}memory;eventBus;config;reasoningBank;claudeFlowBridge;experienceCapture;patternStore;coherenceService;initialized=!1;_domainTransferEngine=null;_domainTransferInterval=null;activeTasks=new Map;completedTasks=0;claudeFlowErrors=0;async initialize(){if(!this.initialized){try{this.coherenceService=await G(H),this.coherenceService.isInitialized()&&console.log("[AQELearningEngine] CoherenceService initialized with WASM engines")}catch(e){console.log("[AQELearningEngine] CoherenceService WASM unavailable, using fallback:",y(e))}this.patternStore=W(this.memory,{promotionThreshold:this.config.promotionThreshold}),await this.patternStore.initialize(),this.reasoningBank=U(this.memory,this.eventBus,this.config.reasoningBank,this.coherenceService),await this.reasoningBank.initialize();try{let{getSharedRvfDualWriter:e}=await import("./shared-rvf-dual-writer-LHMFCYVE.js"),t=await e();t&&this.reasoningBank.setRvfDualWriter(t)}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] RVF wiring skipped:",e instanceof Error?e.message:e)}if(this.config.enableExperienceCapture){this.experienceCapture=Y(this.memory,this.patternStore,this.eventBus,{promotionThreshold:this.config.promotionThreshold}),await this.experienceCapture.initialize();try{let{isWitnessChainFeatureEnabled:e}=await import("./witness-chain-VRSH2F36.js");if(e()){let{createPersistentWitnessChain:t,createWitnessChainSQLitePersistence:i}=await import("./witness-chain-VRSH2F36.js"),{getUnifiedPersistence:r}=await import("./unified-persistence-XKCOUBKY.js"),n=r();if(n.isInitialized()){let a=n.getDatabase(),s=i(a),o=t(s);this.experienceCapture.setWitnessChain(o)}}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Witness chain wiring skipped:",e instanceof Error?e.message:e)}try{let{getUnifiedPersistence:e}=await import("./unified-persistence-XKCOUBKY.js"),t=e();if(t.isInitialized()){let{PatternNullStore:i}=await import("./pattern-null-store-BU6LCB2W.js"),r=new i(t.getDatabase());this.experienceCapture.setNullRecorder(n=>r.recordNull(n))}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Null recorder wiring skipped:",e instanceof Error?e.message:e)}}try{let{isCrossDomainTransferEnabled:e}=await import("./feature-flags-BUXNAORY.js");if(e()&&this.patternStore){let{createDomainTransferEngine:t}=await import("./domain-transfer-WK524LBS.js"),i=t(),r=this.patternStore,n=await r.getStats();this._domainTransferInterval=setInterval(async()=>{try{n=await r.getStats()}catch(a){process.env.DEBUG&&console.debug("[AQELearningEngine] Stats refresh failed:",a instanceof Error?a.message:a)}},6e4),this._domainTransferInterval.unref?.(),i.setPerformanceProvider(a=>{let s=n.byDomain?.[a]??0,o=n.totalPatterns??0;return{domain:a,successRate:o>0?s/o:.5,avgConfidence:n.avgConfidence??.5,patternCount:s,timestamp:Date.now()}}),this._domainTransferEngine=i}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Domain transfer wiring skipped:",e instanceof Error?e.message:e)}if(this.config.enableClaudeFlow)try{this.claudeFlowBridge=X({projectRoot:this.config.projectRoot}),await this.claudeFlowBridge.initialize(),this.claudeFlowBridge.isAvailable()&&console.log("[AQELearningEngine] Claude Flow integration enabled")}catch(e){process.env.DEBUG&&console.log("[AQELearningEngine] Claude Flow not available, using standalone mode:",y(e))}this.initialized=!0,console.log("[AQELearningEngine] Initialized")}}getStatus(){let e=this.claudeFlowBridge?.getStatus();return{initialized:this.initialized,claudeFlowAvailable:e?.available??!1,features:{patternLearning:!0,vectorSearch:!0,taskRouting:!0,trajectories:e?.features.trajectories??!1,modelRouting:e?.features.modelRouting??!1,pretrain:e?.features.pretrain??!1}}}async getStats(){if(!this.initialized||!this.reasoningBank)throw new Error("Engine not initialized");let e=await this.reasoningBank.getStats(),t=this.experienceCapture?await this.experienceCapture.getStats():{totalExperiences:0,byDomain:{},successRate:0,avgQuality:0,patternsExtracted:0,patternsPromoted:0};return{...e,activeTasks:this.activeTasks.size,completedTasks:this.completedTasks,claudeFlowStatus:this.claudeFlowBridge?.getStatus()??{available:!1,features:{trajectories:!1,modelRouting:!1,pretrain:!1,patternSearch:!1}},claudeFlowErrors:this.claudeFlowErrors,experienceCapture:t}}async storePattern(e){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.storePattern(e)}async searchPatterns(e,t){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.searchPatterns(e,t)}async getPattern(e){return!this.initialized||!this.reasoningBank?null:this.reasoningBank.getPattern(e)}async recordOutcome(e){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.recordOutcome(e)}async routeTask(e){if(!this.initialized||!this.reasoningBank)return E(new Error("Engine not initialized"));let t=await this.searchPatternsForTask(e.task,{limit:5,minConfidence:.4,domain:e.domain,contextFingerprint:e.domain?`${e.domain}:router`:void 0});t.success&&t.value.length>0&&await this.trackPatternSearch(e.task,t.value);let i=await this.reasoningBank.routeTask(e);if(i.success&&this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable(),i.success&&t.success){let r=N(i.value,t.value);return b(r)}return i}async route(e,t){let i=await this.routeTask({task:e,context:t});return i.success?i.value:null}async searchPatternsForTask(e,t={}){if(!this.reasoningBank)return b([]);try{return await this.reasoningBank.searchPatterns(e,{limit:t.limit||5,minConfidence:t.minConfidence||.4,domain:t.domain,contextFingerprint:t.contextFingerprint,useVectorSearch:!0})}catch(i){return console.warn("[AQELearningEngine] Pattern search failed:",y(i)),b([])}}async trackPatternSearch(e,t){let i={timestamp:Date.now(),task:e.slice(0,500),patternsFound:t.length,patternIds:t.map(r=>r.pattern.id),avgSimilarity:t.length>0?t.reduce((r,n)=>r+n.similarity,0)/t.length:0};try{let r=`pattern-usage:search:${Date.now()}-${ee().slice(0,8)}`;await this.memory.set(r,i,{persist:!0,ttl:10080*60})}catch(r){console.debug("[AQELearningEngine] Failed to track pattern search:",y(r))}}async recommendModel(e){if(this.claudeFlowBridge?.modelRouter.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.modelRouter.routeTask(e)}catch(t){console.debug("[AQELearningEngine] Claude Flow model routing failed:",t instanceof Error?t.message:t)}return this.localModelRoute(e)}async recordModelOutcome(e,t,i){this.claudeFlowBridge?.modelRouter.isClaudeFlowAvailable()&&await this.claudeFlowBridge.modelRouter.recordOutcome({task:e,model:t,outcome:i})}localModelRoute(e){let t=e.toLowerCase(),i=[/simple/i,/basic/i,/fix typo/i,/rename/i,/format/i,/add comment/i,/lint/i,/minor/i,/quick/i,/small/i];for(let n of i)if(n.test(t))return{model:"haiku",confidence:.75,reasoning:"Low complexity task - using haiku for speed"};let r=[/architect/i,/design/i,/complex/i,/security/i,/performance/i,/refactor.*large/i,/critical/i,/analysis/i,/multi.*file/i,/distributed/i,/concurrent/i,/migration/i];for(let n of r)if(n.test(t))return{model:"opus",confidence:.8,reasoning:"High complexity task - using opus for capability"};return e.length>500?{model:"opus",confidence:.65,reasoning:"Long task description - using opus for complex reasoning"}:e.length<50?{model:"haiku",confidence:.6,reasoning:"Short task - using haiku for efficiency"}:{model:"sonnet",confidence:.7,reasoning:"Medium complexity - using sonnet for balance"}}async startTask(e,t,i){let r=`task-${Date.now()}-${ee().slice(0,8)}`,n=r;if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{n=await this.claudeFlowBridge.trajectory.startTrajectory(e,t)}catch(u){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow startTrajectory failed (${this.claudeFlowErrors} total errors):`,y(u))}let a=`${i??"unknown"}:${t??"unknown"}`,s;try{let u=await this.searchPatternsForTask(e,{domain:i,contextFingerprint:a});u.success&&u.value.length>0&&(s=u.value.map(g=>g.pattern.id))}catch{}let o;this.experienceCapture&&(o=this.experienceCapture.startCapture(e,{agent:t,domain:i,trajectoryId:n!==r?n:void 0,appliedPatterns:s}));let p={id:o||n,task:e,agent:t,startedAt:Date.now(),steps:[]};return this.activeTasks.set(p.id,p),p.id}async recordStep(e,t,i,r){if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{await this.claudeFlowBridge.trajectory.recordStep(e,t,i,r)}catch(a){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow recordStep failed (${this.claudeFlowErrors} total errors):`,y(a))}this.experienceCapture&&this.experienceCapture.recordStep(e,{action:t,result:i,quality:r});let n=this.activeTasks.get(e);n&&n.steps.push({action:t,result:i,quality:r,timestamp:Date.now()})}async endTask(e,t,i){if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{await this.claudeFlowBridge.trajectory.endTrajectory(e,t,i)}catch(n){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow endTrajectory failed (${this.claudeFlowErrors} total errors):`,y(n))}let r=this.activeTasks.get(e);if(r)return this.activeTasks.delete(e),this.completedTasks++,this.config.enableExperienceCapture&&t&&await this.captureExperience(r),r}getTask(e){return this.activeTasks.get(e)}async analyzeCodebase(e,t="medium"){let i=e||this.config.projectRoot;if(this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.pretrain.analyze(i,t)}catch(r){console.debug("[AQELearningEngine] Claude Flow pretrain analyze failed:",r instanceof Error?r.message:r)}return this.localAnalyze(i,t)}async generateAgentConfigs(e="yaml"){if(this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.pretrain.generateAgentConfigs(e)}catch(t){console.debug("[AQELearningEngine] Claude Flow agent config failed:",t instanceof Error?t.message:t)}return[{name:"qe-test-architect",type:"worker",capabilities:["test-generation","test-design"],model:"sonnet"},{name:"qe-coverage-specialist",type:"worker",capabilities:["coverage-analysis","gap-detection"],model:"haiku"},{name:"qe-security-scanner",type:"worker",capabilities:["security-scanning","vulnerability-detection"],model:"opus"}]}async captureExperience(e){if(!this.experienceCapture||!this.config.enableExperienceCapture)return;let t=e.steps.length>0?e.steps.reduce((r,n)=>r+(n.quality??.5),0)/e.steps.length:.5;await this.experienceCapture.completeCapture(e.id,{success:!0,quality:t});let i=await this.experienceCapture.getExperience(e.id);i&&i.quality>=.7&&await this.experienceCapture.shareAcrossDomains(i)}startExperienceCapture(e,t){if(this.experienceCapture)return this.experienceCapture.startCapture(e,t)}getExperienceCaptureService(){return this.experienceCapture}async localAnalyze(e,t){try{let i=await import("fast-glob"),{existsSync:r,readFileSync:n}=await import("fs"),{join:a}=await import("path"),s=t==="shallow"?["*.ts","*.js","*.json"]:t==="medium"?["**/*.ts","**/*.js","**/*.json","**/*.py"]:["**/*"],o=["node_modules/**","dist/**","coverage/**",".git/**"],p=await i.default(s,{cwd:e,ignore:o,onlyFiles:!0}),u=new Set,g=new Set;for(let m of p.slice(0,100))(m.endsWith(".ts")||m.endsWith(".tsx"))&&u.add("typescript"),(m.endsWith(".js")||m.endsWith(".jsx"))&&u.add("javascript"),m.endsWith(".py")&&u.add("python"),m.endsWith(".go")&&u.add("go"),m.endsWith(".rs")&&u.add("rust");let w=a(e,"package.json");if(r(w))try{let m=k(n(w,"utf-8")),d={...m.dependencies,...m.devDependencies};d.react&&g.add("react"),d.vue&&g.add("vue"),d.vitest&&g.add("vitest"),d.jest&&g.add("jest"),d.playwright&&g.add("playwright")}catch(m){console.debug("[AQELearningEngine] package.json parse failed:",m instanceof Error?m.message:m)}return{success:!0,repositoryPath:e,depth:t,analysis:{languages:Array.from(u),frameworks:Array.from(g),patterns:[],complexity:p.length>500?3:p.length>100?2:1}}}catch(i){return{success:!1,repositoryPath:e,depth:t,error:y(i)}}}getGuidance(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.getGuidance(e,t)}generateContext(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.generateContext(e,t)}checkAntiPatterns(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.checkAntiPatterns(e,t)}async dispose(){this._domainTransferInterval&&(clearInterval(this._domainTransferInterval),this._domainTransferInterval=null),this._domainTransferEngine=null,this.experienceCapture&&await this.experienceCapture.dispose(),this.patternStore&&await this.patternStore.dispose(),this.reasoningBank&&await this.reasoningBank.dispose(),this.activeTasks.clear(),this.initialized=!1}},pe={enabled:!1,snapshotIntervalMs:3e5,minSnapshotsForAnalysis:5,autoApplyThreshold:.8},te=class{config;constructor(e){this.config={...pe,...e}}runMetaLearningCycle(e){if(process.env.AQE_META_LEARNING_ENABLED!=="true")return[];if(!this.config.enabled)return[];if(e.length<this.config.minSnapshotsForAnalysis)return[];let t=Math.floor(e.length/2),i=e.slice(0,t),r=e.slice(t),n=[],a=Date.now(),s=h(i.map(c=>c.tokenMetrics.costUsd)),o=h(r.map(c=>c.tokenMetrics.costUsd)),p=h(i.map(c=>c.tokenMetrics.savingsUsd)),u=h(r.map(c=>c.tokenMetrics.savingsUsd));if(o>s*1.1&&u<=p*1.05){let c=Math.min(1,(o-s)/(s||1));n.push({id:`meta-tw-${a}`,type:"token-waste",description:`Token cost increased by ${((o/(s||1)-1)*100).toFixed(1)}% while savings remained flat`,confidence:A(c),suggestedAction:"Review cache configuration and increase pattern reuse thresholds",detectedAt:a})}let g=h(i.map(c=>c.qualityMetrics.gatePassRate)),w=h(r.map(c=>c.qualityMetrics.gatePassRate));Math.abs(w-g)<.02&&e.length>=this.config.minSnapshotsForAnalysis&&n.push({id:`meta-qp-${a}`,type:"quality-plateau",description:`Gate pass rate has been flat at ${(w*100).toFixed(1)}% across ${e.length} snapshots`,confidence:A(.6+(e.length-this.config.minSnapshotsForAnalysis)*.05),suggestedAction:"Consider reviewing quality thresholds or adding new test coverage domains",detectedAt:a});let d=h(i.map(c=>c.learningMetrics.patternCount)),f=h(r.map(c=>c.learningMetrics.patternCount)),ie=h(i.map(c=>c.learningMetrics.averageConfidence)),$=h(r.map(c=>c.learningMetrics.averageConfidence)),re=Math.abs(f-d),ne=Math.abs($-ie);re<1&&ne<.02&&n.push({id:`meta-ls-${a}`,type:"learning-stall",description:`Pattern count (~${Math.round(f)}) and confidence (~${$.toFixed(2)}) have stagnated`,confidence:A(.65+(e.length-this.config.minSnapshotsForAnalysis)*.04),suggestedAction:"Expand to new QE domains or lower pattern creation thresholds to encourage exploration",detectedAt:a});let C=h(i.map(c=>c.performanceMetrics.p95LatencyMs)),j=h(r.map(c=>c.performanceMetrics.p95LatencyMs));if(j>C*1.2&&C>0){let c=Math.min(1,(j-C)/(C||1));n.push({id:`meta-pr-${a}`,type:"performance-regression",description:`P95 latency increased from ${C.toFixed(0)}ms to ${j.toFixed(0)}ms`,confidence:A(c),suggestedAction:"Profile hot paths and consider HNSW index tuning or batch size reduction",detectedAt:a})}return n}shouldAutoApply(e,t){let i=(t??this.config).autoApplyThreshold;return e.confidence>=i}};function h(l){return l.length===0?0:l.reduce((e,t)=>e+t,0)/l.length}function A(l){return Math.max(0,Math.min(1,l))}function ge(l,e,t){return new L(l,e,t)}function it(l,e,t){return ge(l,{projectRoot:e},t)}export{de as a,L as b,pe as c,te as d,ge as e,it as f};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.0");process.exit(0)}
2
- import{a as h}from"./chunk-R2B6EE45.js";import{c as m}from"./chunk-JY4VZ6BN.js";h();var g=m.create("regret-tracker"),l=50,R=.9,d=1.1;function f(o,t){let e=o.length;if(e<2)return 0;let n=0,r=0,i=0,a=0;for(let s=0;s<e;s++)n+=o[s],r+=t[s],i+=o[s]*t[s],a+=o[s]*o[s];let u=e*a-n*n;return Math.abs(u)<1e-10?0:(e*i-n*r)/u}var c=class{domains=new Map;alertCallbacks=[];alerts=[];maxAlerts;recentWindow;constructor(t){this.maxAlerts=t?.maxAlerts??100,this.recentWindow=t?.recentWindow??20}recordDecision(t,e,n){let r=this.getOrCreateDomainState(t),i=Math.max(0,n-e);if(r.cumulativeRegret+=i,r.decisionCount++,r.points.push({decisionCount:r.decisionCount,cumulativeRegret:r.cumulativeRegret,timestamp:Date.now()}),r.decisionCount>=l){let a=this.classifyGrowthRate(r.points);r.lastGrowthRate!=="insufficient_data"&&a!==r.lastGrowthRate&&this.emitAlert(t,r.lastGrowthRate,a),r.lastGrowthRate=a}}getCumulativeRegret(t){return this.domains.get(t)?.cumulativeRegret??0}getRegretCurve(t){let e=this.domains.get(t);return e?[...e.points]:[]}getRegretGrowthRate(t){let e=this.domains.get(t);return e?this.classifyGrowthRate(e.points):"insufficient_data"}detectStagnation(t){let e=this.getRegretGrowthRate(t);return e==="linear"||e==="superlinear"}getHealthSummary(){let t=[];for(let[e,n]of this.domains){let r=this.classifyGrowthRate(n.points),i=this.computeLogLogSlope(n.points),a=this.computeRecentAvgRegret(n);t.push({domain:e,totalDecisions:n.decisionCount,cumulativeRegret:n.cumulativeRegret,growthRate:r,stagnating:r==="linear"||r==="superlinear",slope:i,recentAvgRegret:a})}return t.sort((e,n)=>e.domain.localeCompare(n.domain)),t}onAlert(t){this.alertCallbacks.push(t)}getAlerts(){return[...this.alerts]}getTrackedDomains(){return[...this.domains.keys()].sort()}getTotalDecisions(){let t=0;for(let e of this.domains.values())t+=e.decisionCount;return t}reset(t){t?this.domains.delete(t):(this.domains.clear(),this.alerts=[])}getOrCreateDomainState(t){let e=this.domains.get(t);return e||(e={points:[],cumulativeRegret:0,decisionCount:0,lastGrowthRate:"insufficient_data"},this.domains.set(t,e)),e}classifyGrowthRate(t){if(t.length<l)return"insufficient_data";let e=this.computeLogLogSlope(t);return e===void 0?"insufficient_data":e<R?"sublinear":e<=d?"linear":"superlinear"}computeLogLogSlope(t){if(t.length<l)return;let e=t.filter(i=>i.cumulativeRegret>0&&i.decisionCount>0);if(e.length<2)return;let n=e.map(i=>Math.log(i.decisionCount)),r=e.map(i=>Math.log(i.cumulativeRegret));return f(n,r)}computeRecentAvgRegret(t){if(t.points.length<2)return 0;let e=Math.min(this.recentWindow,t.points.length),n=t.points.slice(-e),r=n[0],i=n[n.length-1],a=i.cumulativeRegret-r.cumulativeRegret,u=i.decisionCount-r.decisionCount;return u<=0?0:a/u}emitAlert(t,e,n){let r={domain:t,previousRate:e,newRate:n,timestamp:Date.now(),message:`Domain "${t}" regret growth changed from ${e} to ${n}`};this.alerts.push(r),this.alerts.length>this.maxAlerts&&this.alerts.shift(),g.info("Regret growth rate transition",{domain:t,previousRate:e,newRate:n});for(let i of this.alertCallbacks)try{i(r)}catch(a){g.error("Alert callback error",a instanceof Error?a:void 0)}}};function b(o){return new c(o)}export{b as a};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.2");process.exit(0)}
2
+ import{a as h}from"./chunk-PHHXHG2W.js";import{c as m}from"./chunk-ICKLBATY.js";h();var g=m.create("regret-tracker"),l=50,R=.9,d=1.1;function f(o,t){let e=o.length;if(e<2)return 0;let n=0,r=0,i=0,a=0;for(let s=0;s<e;s++)n+=o[s],r+=t[s],i+=o[s]*t[s],a+=o[s]*o[s];let u=e*a-n*n;return Math.abs(u)<1e-10?0:(e*i-n*r)/u}var c=class{domains=new Map;alertCallbacks=[];alerts=[];maxAlerts;recentWindow;constructor(t){this.maxAlerts=t?.maxAlerts??100,this.recentWindow=t?.recentWindow??20}recordDecision(t,e,n){let r=this.getOrCreateDomainState(t),i=Math.max(0,n-e);if(r.cumulativeRegret+=i,r.decisionCount++,r.points.push({decisionCount:r.decisionCount,cumulativeRegret:r.cumulativeRegret,timestamp:Date.now()}),r.decisionCount>=l){let a=this.classifyGrowthRate(r.points);r.lastGrowthRate!=="insufficient_data"&&a!==r.lastGrowthRate&&this.emitAlert(t,r.lastGrowthRate,a),r.lastGrowthRate=a}}getCumulativeRegret(t){return this.domains.get(t)?.cumulativeRegret??0}getRegretCurve(t){let e=this.domains.get(t);return e?[...e.points]:[]}getRegretGrowthRate(t){let e=this.domains.get(t);return e?this.classifyGrowthRate(e.points):"insufficient_data"}detectStagnation(t){let e=this.getRegretGrowthRate(t);return e==="linear"||e==="superlinear"}getHealthSummary(){let t=[];for(let[e,n]of this.domains){let r=this.classifyGrowthRate(n.points),i=this.computeLogLogSlope(n.points),a=this.computeRecentAvgRegret(n);t.push({domain:e,totalDecisions:n.decisionCount,cumulativeRegret:n.cumulativeRegret,growthRate:r,stagnating:r==="linear"||r==="superlinear",slope:i,recentAvgRegret:a})}return t.sort((e,n)=>e.domain.localeCompare(n.domain)),t}onAlert(t){this.alertCallbacks.push(t)}getAlerts(){return[...this.alerts]}getTrackedDomains(){return[...this.domains.keys()].sort()}getTotalDecisions(){let t=0;for(let e of this.domains.values())t+=e.decisionCount;return t}reset(t){t?this.domains.delete(t):(this.domains.clear(),this.alerts=[])}getOrCreateDomainState(t){let e=this.domains.get(t);return e||(e={points:[],cumulativeRegret:0,decisionCount:0,lastGrowthRate:"insufficient_data"},this.domains.set(t,e)),e}classifyGrowthRate(t){if(t.length<l)return"insufficient_data";let e=this.computeLogLogSlope(t);return e===void 0?"insufficient_data":e<R?"sublinear":e<=d?"linear":"superlinear"}computeLogLogSlope(t){if(t.length<l)return;let e=t.filter(i=>i.cumulativeRegret>0&&i.decisionCount>0);if(e.length<2)return;let n=e.map(i=>Math.log(i.decisionCount)),r=e.map(i=>Math.log(i.cumulativeRegret));return f(n,r)}computeRecentAvgRegret(t){if(t.points.length<2)return 0;let e=Math.min(this.recentWindow,t.points.length),n=t.points.slice(-e),r=n[0],i=n[n.length-1],a=i.cumulativeRegret-r.cumulativeRegret,u=i.decisionCount-r.decisionCount;return u<=0?0:a/u}emitAlert(t,e,n){let r={domain:t,previousRate:e,newRate:n,timestamp:Date.now(),message:`Domain "${t}" regret growth changed from ${e} to ${n}`};this.alerts.push(r),this.alerts.length>this.maxAlerts&&this.alerts.shift(),g.info("Regret growth rate transition",{domain:t,previousRate:e,newRate:n});for(let i of this.alertCallbacks)try{i(r)}catch(a){g.error("Alert callback error",a instanceof Error?a:void 0)}}};function b(o){return new c(o)}export{b as a};
@@ -1,3 +1,3 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.0");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.2");process.exit(0)}
2
2
  var p={"||":1,"&&":2,"===":3,"!==":3,"==":3,"!=":3,"<":4,">":4,"<=":4,">=":4,"+":5,"-":5,"*":6,"/":6,"%":6},l=new Set(Object.keys(p)),w=new Set(["!","-","+"]);function h(r){let n=[],e=0;for(;e<r.length;){let t=r[e];if(/\s/.test(t)){e++;continue}if(/\d/.test(t)||t==="."&&/\d/.test(r[e+1])){let s="";for(;e<r.length&&/[\d.]/.test(r[e]);)s+=r[e++];n.push({type:"NUMBER",value:parseFloat(s),raw:s});continue}if(t==='"'||t==="'"){let s=t,u="";for(e++;e<r.length&&r[e]!==s;){if(r[e]==="\\"&&e+1<r.length){e++;let c=r[e];switch(c){case"n":u+=`
3
3
  `;break;case"t":u+=" ";break;case"r":u+="\r";break;default:u+=c}}else u+=r[e];e++}e++,n.push({type:"STRING",value:u,raw:`${s}${u}${s}`});continue}if(/[a-zA-Z_$]/.test(t)){let s="";for(;e<r.length&&/[a-zA-Z0-9_$]/.test(r[e]);)s+=r[e++];s==="true"?n.push({type:"BOOLEAN",value:!0,raw:s}):s==="false"?n.push({type:"BOOLEAN",value:!1,raw:s}):s==="null"?n.push({type:"NULL",value:null,raw:s}):s==="undefined"?n.push({type:"UNDEFINED",value:void 0,raw:s}):n.push({type:"IDENTIFIER",value:s,raw:s});continue}let a=r.slice(e,e+2),o=r.slice(e,e+3);if(o==="==="||o==="!=="){n.push({type:"OPERATOR",value:o,raw:o}),e+=3;continue}if(a==="=="||a==="!="||a==="<="||a===">="||a==="&&"||a==="||"){n.push({type:"OPERATOR",value:a,raw:a}),e+=2;continue}if(t==="("){n.push({type:"LPAREN",value:"(",raw:"("}),e++;continue}if(t===")"){n.push({type:"RPAREN",value:")",raw:")"}),e++;continue}if(t==="."){n.push({type:"DOT",value:".",raw:"."}),e++;continue}if("+-*/%<>!".includes(t)){n.push({type:"OPERATOR",value:t,raw:t}),e++;continue}throw new Error(`Unexpected character at position ${e}: ${t}`)}return n.push({type:"EOF",value:"",raw:""}),n}var i=class{tokens;pos=0;context;constructor(n,e){this.tokens=n,this.context=e}current(){return this.tokens[this.pos]}advance(){return this.tokens[this.pos++]}expect(n){let e=this.current();if(e.type!==n)throw new Error(`Expected ${n}, got ${e.type}`);return this.advance()}parse(){let n=this.parseExpression(0);if(this.current().type!=="EOF")throw new Error(`Unexpected token: ${this.current().raw}`);return n}parseExpression(n){let e=this.parseUnary();for(;;){let t=this.current();if(t.type!=="OPERATOR"||!l.has(t.value))break;let a=p[t.value];if(a<n)break;let o=this.advance().value,s=this.parseExpression(a+1);e=this.applyBinaryOperator(o,e,s)}return e}parseUnary(){let n=this.current();if(n.type==="OPERATOR"&&w.has(n.value)){let e=this.advance().value,t=this.parseUnary();return this.applyUnaryOperator(e,t)}return this.parsePrimary()}parsePrimary(){let n=this.current();switch(n.type){case"NUMBER":case"STRING":case"BOOLEAN":case"NULL":case"UNDEFINED":return this.advance(),n.value;case"IDENTIFIER":return this.parseIdentifier();case"LPAREN":{this.advance();let e=this.parseExpression(0);return this.expect("RPAREN"),e}default:throw new Error(`Unexpected token: ${n.raw}`)}}parseIdentifier(){let n=this.context,e=this.advance().value;for(typeof n=="object"&&n!==null&&(e in n)?n=n[e]:n=void 0;this.current().type==="DOT";){this.advance();let t=this.expect("IDENTIFIER").value;n!=null&&typeof n=="object"?n=n[t]:n=void 0}return n}applyBinaryOperator(n,e,t){switch(n){case"===":return e===t;case"!==":return e!==t;case"==":return e==t;case"!=":return e!=t;case"<":return e<t;case">":return e>t;case"<=":return e<=t;case">=":return e>=t;case"&&":return e&&t;case"||":return e||t;case"+":return e+t;case"-":return e-t;case"*":return e*t;case"/":return e/t;case"%":return e%t;default:throw new Error(`Unknown operator: ${n}`)}}applyUnaryOperator(n,e){switch(n){case"!":return!e;case"-":return-e;case"+":return+e;default:throw new Error(`Unknown unary operator: ${n}`)}}};function E(r,n={}){if(!r||typeof r!="string")throw new Error("Expression must be a non-empty string");let e=[/\beval\b/i,/\bFunction\b/,/\bconstructor\b/,/\b__proto__\b/,/\bprototype\b/,/\bimport\b/,/\brequire\b/,/\bprocess\b/,/\bglobal\b/,/\bwindow\b/,/\bdocument\b/,/\[\s*['"`]/,/\[.*\]/];for(let o of e)if(o.test(r))throw new Error(`Expression contains potentially dangerous pattern: ${r}`);let t=h(r.trim());return new i(t,n).parse()}function b(r,n={},e=!1){try{return!!E(r,n)}catch(t){return console.warn(`[SafeEvaluator] Failed to evaluate expression: ${r}`,t),e}}export{b as a};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.0");process.exit(0)}
2
- import{a as L,b as I,f,j as A,l as y,n as l}from"./chunk-ZBKGX72B.js";import{k as O,o as M}from"./chunk-7RAB2BZY.js";import{b,d as U}from"./chunk-HQHLHSJO.js";import{a as C}from"./chunk-VOSISOFD.js";import{a as p,c as P}from"./chunk-XITTURP2.js";import{i as R}from"./chunk-FOHYBR3O.js";import{a as N,b as F}from"./chunk-ZQSXG7FA.js";F();U();P();M();var v={dbPath:".agentic-qe/memory.db",walMode:!0,mmapSize:256*1024*1024,cacheSize:-64e3,foreignKeys:!0,useUnified:!0};function W(T,e=384){let t=new Array(e).fill(0),n=T.toLowerCase().trim();for(let a=0;a<3;a++)for(let s=0;s<n.length;s++){let i=n.charCodeAt(s),o=i*(s+1)*(a+1)%e;t[o]+=Math.sin(i*(a+1))/(s+1)}let r=Math.sqrt(t.reduce((a,s)=>a+s*s,0));if(r>0)for(let a=0;a<e;a++)t[a]/=r;return t}var h=class{db=null;config;prepared=new Map;initialized=!1;unifiedMemory=null;constructor(e={}){this.config={...v,...e}}getDatabase(){return this.db}async initialize(){if(!this.initialized)try{if(this.config.useUnified)this.unifiedMemory=O(),await this.unifiedMemory.initialize(),this.db=this.unifiedMemory.getDatabase(),console.log(`[SQLitePatternStore] Using unified storage: ${this.unifiedMemory.getDbPath()}`);else{let e=await import("path"),t=await import("fs"),n=e.dirname(this.config.dbPath);t.existsSync(n)||t.mkdirSync(n,{recursive:!0}),this.db=N(this.config.dbPath),this.db.pragma(`mmap_size = ${this.config.mmapSize}`),this.db.pragma(`cache_size = ${this.config.cacheSize}`),this.config.foreignKeys&&this.db.pragma("foreign_keys = ON"),this.createSchema(),console.log(`[SQLitePatternStore] Initialized (legacy): ${this.config.dbPath}`)}this.deduplicatePatterns(),this.ensureEmbeddingSpaceSchema(),this.prepareStatements(),this.initialized=!0}catch(e){throw new Error(`Failed to initialize SQLite: ${p(e)}`)}}createSchema(){if(!this.db)throw new Error("Database not initialized");this.db.exec(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.2");process.exit(0)}
2
+ import{a as L,b as I,f,j as A,l as y,n as l}from"./chunk-E3Q7WNJD.js";import{k as O,o as M}from"./chunk-W2FLULF4.js";import{b,d as U}from"./chunk-QXTW7XCS.js";import{a as C}from"./chunk-CTCQOYBS.js";import{a as p,c as P}from"./chunk-D4RCV4LY.js";import{i as R}from"./chunk-NG2UVPTW.js";import{a as N,b as F}from"./chunk-N5ZRUOMR.js";F();U();P();M();var v={dbPath:".agentic-qe/memory.db",walMode:!0,mmapSize:256*1024*1024,cacheSize:-64e3,foreignKeys:!0,useUnified:!0};function W(T,e=384){let t=new Array(e).fill(0),n=T.toLowerCase().trim();for(let a=0;a<3;a++)for(let s=0;s<n.length;s++){let i=n.charCodeAt(s),o=i*(s+1)*(a+1)%e;t[o]+=Math.sin(i*(a+1))/(s+1)}let r=Math.sqrt(t.reduce((a,s)=>a+s*s,0));if(r>0)for(let a=0;a<e;a++)t[a]/=r;return t}var h=class{db=null;config;prepared=new Map;initialized=!1;unifiedMemory=null;constructor(e={}){this.config={...v,...e}}getDatabase(){return this.db}async initialize(){if(!this.initialized)try{if(this.config.useUnified)this.unifiedMemory=O(),await this.unifiedMemory.initialize(),this.db=this.unifiedMemory.getDatabase(),console.log(`[SQLitePatternStore] Using unified storage: ${this.unifiedMemory.getDbPath()}`);else{let e=await import("path"),t=await import("fs"),n=e.dirname(this.config.dbPath);t.existsSync(n)||t.mkdirSync(n,{recursive:!0}),this.db=N(this.config.dbPath),this.db.pragma(`mmap_size = ${this.config.mmapSize}`),this.db.pragma(`cache_size = ${this.config.cacheSize}`),this.config.foreignKeys&&this.db.pragma("foreign_keys = ON"),this.createSchema(),console.log(`[SQLitePatternStore] Initialized (legacy): ${this.config.dbPath}`)}this.deduplicatePatterns(),this.ensureEmbeddingSpaceSchema(),this.prepareStatements(),this.initialized=!0}catch(e){throw new Error(`Failed to initialize SQLite: ${p(e)}`)}}createSchema(){if(!this.db)throw new Error("Database not initialized");this.db.exec(`
3
3
  -- QE Patterns table
4
4
  CREATE TABLE IF NOT EXISTS qe_patterns (
5
5
  id TEXT PRIMARY KEY,
@@ -0,0 +1,4 @@
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.2");process.exit(0)}
2
+ import{a as p}from"./chunk-KFXZDQ5J.js";import{f as m}from"./chunk-FPHPP5TQ.js";import{o as T}from"./chunk-W2FLULF4.js";import{b as V}from"./chunk-JDXLCNKV.js";import k from"node:path";async function y(e){if(e.checklist.requirements.length===0)throw new Error("RequirementChecklist must have a non-empty, constant denominator (ADR-117).");if(!(e.oracle!=null&&e.oracle.baselinePassed&&e.oracle.passed)){let c=e.oracle==null?"oracle did not run":e.oracle.baselinePassed?"mutation score below threshold":"tests did not execute against the reference implementation";return{verdict:"fail",mechanical:"fail",specCoverage:null,unmet:[],attempts:0,reason:`mechanical gate failed: ${c}`}}if(!await e.judge.preflight())return{verdict:"inconclusive",mechanical:"pass",specCoverage:null,unmet:[],attempts:0,reason:"judge preflight failed: judge tooling did not run \u2014 refusing to report success"};let r=[],n=null,a=[],o=0;for(let c=0;c<2;c++){o++;let u=await e.judge.grade(e.artifact,e.checklist);if(u.ran&&(r.push(u),(n==null||u.coverage>n)&&(n=u.coverage,a=u.unmet),u.coverage>=1))return{verdict:"pass",mechanical:"pass",specCoverage:u.coverage,unmet:[],attempts:o,reason:`spec gate passed at coverage ${u.coverage.toFixed(3)} on attempt ${o}`}}return r.length>=2?{verdict:"fail",mechanical:"pass",specCoverage:n,unmet:a,attempts:o,reason:`spec gate failed: ${r.length} real opinions, best coverage ${(n??0).toFixed(3)} < 1 (${a.length} unmet)`}:{verdict:"inconclusive",mechanical:"pass",specCoverage:n,unmet:a,attempts:o,reason:`spec gate inconclusive: only ${r.length} real opinion(s) obtainable (need 2 to fail) \u2014 retry later, record neither pass nor fail`}}T();import{createHash as R}from"node:crypto";function E(e){let{manifestHash:t,...i}=e;return`sha256:${R("sha256").update(h(i)).digest("hex")}`}function b(e){return`sha256:${R("sha256").update(e).digest("hex")}`}function x(e,t={}){j(e);let i=E(e);if(e.manifestHash!==i)throw new Error(`Verification reach manifestHash mismatch: expected ${i}`);let r=t.now??new Date,n=r.toISOString(),a=e.expiresAt!=null&&r.getTime()>l(e.expiresAt,"expiresAt"),o=e.risks.map(c=>I(c,e,a,r.getTime()));return{manifestId:e.id,manifestHash:e.manifestHash,systemUnderTest:e.systemUnderTest,artifact:structuredClone(e.artifact),coverageVerdict:$(o.map(c=>c.verdict)),risks:o,evaluatedAt:n}}function I(e,t,i,r){let n=new Set,a=new Set,o=new Set,c=new Set,u=new Set;for(let s of e.checks){for(let v of s.limitations)u.add(v);if(O(s,t,i,r)){if(s.reach==="partial"){a.add(s.checkId);continue}if(s.reach==="direct"&&e.requiredObservations.includes(s.channel)&&s.oracleRef===e.requiredOracle){if(s.executionStatus==="failed"){o.add(s.checkId);continue}s.executionStatus==="passed"&&(n.add(s.checkId),c.add(s.channel))}}}let d=e.requiredObservations.filter(s=>!c.has(s)),f=o.size>0?"fail":d.length===0?"pass":e.dispositionWhenUncovered;return{riskId:e.riskId,failureMode:e.failureMode,severity:e.severity,verdict:f,directCheckIds:[...n],partialCheckIds:[...a],failedCheckIds:[...o],uncoveredObservations:d,limitations:[...u],reason:P(f,o,d,i)}}function O(e,t,i,r){if(i||!S(e.target,t.artifact)||e.evidenceClass!=="EXECUTED"||e.executionStatus==="not-run"||e.executionStatus==="unavailable"||!e.observedAt)return!1;let n=l(e.observedAt,`check ${e.checkId} observedAt`),a=l(t.generatedAt,"generatedAt");return!(n<a||n>r||t.expiresAt&&n>l(t.expiresAt,"expiresAt"))}function S(e,t){return e.revision===t.revision&&e.digest===t.digest&&e.environment===t.environment}function $(e){return e.some(t=>t==="fail")?"fail":e.some(t=>t==="human-review")?"human-review":e.some(t=>t==="inconclusive")?"inconclusive":"pass"}function P(e,t,i,r){return r?`verification manifest expired; uncovered: ${i.join(", ")}`:t.size>0?`direct check failed: ${[...t].join(", ")}`:e==="pass"?"all required observation channels have direct executed reach":`required reach is uncovered (${i.join(", ")}); disposition: ${e}`}function j(e){if(!e.id||!e.systemUnderTest)throw new Error("Verification reach manifest requires id and systemUnderTest");if(!e.artifact.revision||!e.artifact.digest||!e.artifact.environment)throw new Error("Verification reach manifest artifact requires revision, digest, and environment");if(l(e.generatedAt,"generatedAt"),e.expiresAt&&l(e.expiresAt,"expiresAt"),e.risks.length===0)throw new Error("Verification reach manifest requires at least one failure mode");let t=new Set;for(let i of e.risks){if(t.has(i.riskId))throw new Error(`Duplicate riskId: ${i.riskId}`);if(t.add(i.riskId),!i.riskId||!i.failureMode||!i.requiredOracle)throw new Error("Each failure mode requires riskId, failureMode, and requiredOracle");if(i.requiredObservations.length===0)throw new Error(`Failure mode ${i.riskId} requires at least one observation channel`)}}function l(e,t){let i=Date.parse(e);if(!Number.isFinite(i))throw new Error(`Invalid ${t} timestamp: ${e}`);return i}function h(e){return Array.isArray(e)?`[${e.map(h).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).filter(([,i])=>i!==void 0).sort(([i],[r])=>i<r?-1:i>r?1:0).map(([i,r])=>`${JSON.stringify(i)}:${h(r)}`).join(",")}}`:JSON.stringify(e)}var q="verification/anchors/qe-anchor-v1.json";async function ee(e){let t=F(e.checklistId,e.anchorPath);if(e.verificationManifest&&e.verificationManifest.artifact.digest!==b(e.artifact))throw new Error("Verification reach manifest artifact digest does not match the judged artifact");let i=e.verificationManifest?{kind:"verified",...x(e.verificationManifest)}:{kind:"legacy-unknown",coverageVerdict:"inconclusive",reason:"legacy quality-gate request has no verification reach manifest"},r=i.coverageVerdict,n=await y({oracle:e.oracleResult,artifact:e.artifact,checklist:t,judge:e.judge});return{...n,qualityVerdict:n.verdict,coverageVerdict:r,verdict:U(n.verdict,r),verification:i}}function U(e,t){return e==="fail"||t==="fail"?"fail":e==="pass"&&t==="pass"?"pass":"inconclusive"}function F(e,t){let i=C(t),r=p(i),n=r.items.find(a=>a.id===e);if(!n){let a=r.items.map(o=>o.id).join(", ");throw new Error(`Unknown checklist id "${e}" in anchor ${i}. Available: ${a}`)}return{id:n.id,requirements:n.requirements}}function te(e){return p(C(e)).items.map(i=>i.id)}function C(e){if(e&&k.isAbsolute(e))return e;let t=V();return k.resolve(t,e??q)}var J=6e4,D=15e3;function Q(e){let t=e.timeoutMs??J,i=e.logger??(()=>{}),r=e.model??"frontier",n=e.ping??(async()=>{let a=await w(e.complete("Reply with exactly: OK"),Math.min(D,t),"judge preflight ping");return typeof a=="string"&&a.trim().length>0});return{async preflight(){try{let a=await n();return a||i(`frontier-judge preflight: provider (${r}) returned empty \u2014 not ready`),a}catch(a){return i(`frontier-judge preflight failed (${r}): ${A(a)}`),!1}},async grade(a,o){let c=o.requirements.length;try{let u=_(a,o),d=await w(e.complete(u),t,"judge grade"),f=H(d,c);if(f==null)return i(`frontier-judge grade: could not parse response for ${o.id}`),{ran:!1,coverage:0,unmet:[]};let s=[...f].sort((g,M)=>g-M).map(g=>o.requirements[g]);return{ran:!0,coverage:(c-s.length)/c,unmet:s}}catch(u){return i(`frontier-judge grade failed for ${o.id} (${r}): ${A(u)}`),{ran:!1,coverage:0,unmet:[]}}}}}function N(e,t={}){let i=t.model??m;return async r=>(await e.chat({messages:[{role:"user",content:r}],model:i,preferredProvider:t.preferredProvider,temperature:t.temperature??0,maxTokens:t.maxTokens??1024,timeoutMs:t.timeoutMs,skipCache:!0})).content??""}function ne(e,t={}){let i=t.model??m;return Q({complete:N(e,{...t,model:i}),model:i,timeoutMs:t.timeoutMs,logger:t.logger})}function ae(e){return{preflight:()=>!1,grade:()=>({ran:!1,coverage:0,unmet:[]})}}function _(e,t){let i=t.requirements.map((r,n)=>`${n+1}. ${r}`).join(`
3
+ `);return["You are a rigorous, frontier-tier quality oracle grading a software artifact","against a FIXED requirement checklist. Judge only what the artifact actually","verifies \u2014 do not give credit for requirements it merely mentions or leaves",'implicit. A requirement is "met" only if the artifact demonstrably covers it.',"",`Checklist id: ${t.id}`,"Requirements (the denominator is fixed \u2014 grade ALL of them):",i,"","--- ARTIFACT UNDER JUDGEMENT ---",e,"--- END ARTIFACT ---","","Return ONLY a single JSON object, no prose, no markdown fences, of the form:",'{"unmet": [<numbers of requirements NOT met>]}','Use the requirement numbers above. If every requirement is met, return {"unmet": []}.'].join(`
4
+ `)}function H(e,t){let i=G(e);if(i==null||!Array.isArray(i.unmet))return null;let r=new Set;for(let n of i.unmet){let a=typeof n=="number"?n:typeof n=="string"?Number(n.trim()):NaN;if(!Number.isInteger(a))continue;let o=a-1;o>=0&&o<t&&r.add(o)}return r}function G(e){if(typeof e!="string")return null;let t=e.indexOf("{");if(t===-1)return null;let i=0,r=!1,n=!1;for(let a=t;a<e.length;a++){let o=e[a];if(r){n?n=!1:o==="\\"?n=!0:o==='"'&&(r=!1);continue}if(o==='"')r=!0;else if(o==="{")i++;else if(o==="}"&&(i--,i===0))try{return JSON.parse(e.slice(t,a+1))}catch{return null}}return null}function w(e,t,i){return new Promise((r,n)=>{let a=setTimeout(()=>n(new Error(`${i} timed out after ${t}ms`)),t);e.then(o=>{clearTimeout(a),r(o)},o=>{clearTimeout(a),n(o)})})}function A(e){return e instanceof Error?e.message:String(e)}export{ee as a,te as b,ne as c,ae as d};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.0");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.2");process.exit(0)}
2
2
  var u="quality-assessment";var o=["coverage","testsPassing","criticalBugs","codeSmells","securityVulnerabilities","technicalDebt","duplications"],d={coverage:{direction:"min",value:80,severity:"high"},testsPassing:{direction:"min",value:95,severity:"critical"},criticalBugs:{direction:"max",value:0,severity:"critical"},codeSmells:{direction:"max",value:20,severity:"medium"},securityVulnerabilities:{direction:"max",value:0,severity:"critical"},technicalDebt:{direction:"max",value:5,severity:"medium"},duplications:{direction:"max",value:5,severity:"low"}};function c(a){return`quality-evidence:${a}:latest`}function l(a,t,e){if(typeof a!="string")throw new Error("Measured quality evidence is malformed: measuredAt is required.");let r=Date.parse(a);if(!Number.isFinite(r))throw new Error("Measured quality evidence is malformed: measuredAt is invalid.");if(r>t+6e4)throw new Error("Measured quality evidence is malformed: measuredAt is in the future.");if(t-r>e)throw new Error("Measured quality evidence is stale. Run the relevant quality analyzers again.");return r}function m(a,t,e,r){if(!a||typeof a!="object")throw new Error(`No measured quality evidence found for ${t}.`);let i=a;if(i.schemaVersion!==1||i.metric!==t||!Number.isFinite(i.value)||i.value<0||typeof i.source!="string"||i.source.trim().length===0)throw new Error(`Measured quality evidence for ${t} is malformed or incomplete.`);l(i.measuredAt,e,r)}async function v(a,t,e){let r=Date.now();if(l(e.measuredAt,r,Number.POSITIVE_INFINITY),e.source.trim().length===0)throw new Error("Quality evidence source is required.");for(let i of o){let n=t[i];if(n===void 0)continue;if(!Number.isFinite(n)||n<0)throw new Error(`Quality evidence value for ${i} must be a non-negative finite number.`);let s={schemaVersion:1,metric:i,value:n,measuredAt:e.measuredAt,source:e.source};await a.set(c(i),s,{namespace:u,persist:!0})}}async function y(a,t={}){let e=t.now??Date.now(),r=t.maxAgeMs??864e5,i={};for(let n of o){let s=await a.get(c(n),{namespace:u});m(s,n,e,r),i[n]=s.value}return i}function E(a){let t=o.map(e=>{let r=d[e],i=a[e];return{name:e,value:i,threshold:r.value,direction:r.direction,severity:r.severity,passed:r.direction==="min"?i>=r.value:i<=r.value}});return{passed:t.every(e=>e.passed),checks:t,recommendations:t.filter(e=>!e.passed).map(e=>`${e.name} failed its measured ${e.direction} threshold.`)}}export{d as a,v as b,y as c,E as d};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.0");process.exit(0)}
2
- import{l as p}from"./chunk-3JIJBR4V.js";import{a as f,c as R}from"./chunk-XITTURP2.js";R();var u=class extends p{config={name:"qe/workflows/browser-load",description:"Load, validate, and prepare browser automation workflows from inline YAML or built-in templates. Returns the resolved workflow with steps and variable bindings, ready for browser execution. Templates: login-flow, form-validation, visual-regression, oauth-flow, etc.",domain:"test-execution",schema:this.buildSchema()};buildSchema(){return{type:"object",properties:{workflowYaml:{type:"string",description:"Inline YAML workflow definition. Mutually exclusive with templateName."},templateName:{type:"string",description:"Built-in template name to load.",enum:["login-flow","oauth-flow","scraping-workflow","visual-regression","form-validation","navigation-flow","api-integration","performance-audit","accessibility-audit"]},variables:{type:"object",description:'Runtime variable overrides (e.g., { "baseUrl": "https://example.com" })'}}}}async execute(r,C){try{let{WorkflowLoader:n,WORKFLOW_TEMPLATES:g,WORKFLOW_DESCRIPTIONS:v,interpolateVariables:b}=await import("./browser-TCEB2W2F.js"),{parse:k}=await import("yaml"),d=new n,l=[...g],y=v;if(!r.workflowYaml&&!r.templateName)return{success:!0,data:{workflowName:"none",description:"No workflow specified. Use templateName or workflowYaml.",source:"none",templateUsed:null,steps:[],variables:{defined:[],provided:{}},validation:{valid:!0,errors:[],warnings:[]},availableTemplates:l,summary:`Available templates: ${l.join(", ")}`}};let e,i,t=null;r.workflowYaml?(i="inline-yaml",e=k(r.workflowYaml)):(i="template",t=r.templateName,e=await d.load(r.templateName));let a=await d.validate(e),w=(e.steps??[]).map(o=>{let s=o.config;if(r.variables){let c={};for(let[h,m]of Object.entries(s))c[h]=typeof m=="string"?b(m,r.variables):m;s=c}return{name:o.name,action:o.action,config:s,optional:o.optional??!1,assertionCount:o.assertions?.length??0}});return{success:!0,data:{workflowName:e.name||t||"custom",description:e.description||t&&y[t]||"",source:i,templateUsed:t,steps:w,variables:{defined:(e.variables??[]).map(o=>({name:o.name,type:o.type,required:o.required,hasDefault:o.default!==void 0})),provided:r.variables||{}},validation:{valid:a.valid,errors:a.errors,warnings:a.warnings},availableTemplates:l,summary:a.valid?`Workflow "${e.name}" loaded (${i}): ${w.length} steps, ${(e.variables??[]).length} variables`:`Workflow "${e.name}" has validation errors: ${a.errors.join("; ")}`}}}catch(n){return{success:!1,error:f(n)}}}};export{u as a};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.2");process.exit(0)}
2
+ import{l as p}from"./chunk-2LKAMMMI.js";import{a as f,c as R}from"./chunk-D4RCV4LY.js";R();var u=class extends p{config={name:"qe/workflows/browser-load",description:"Load, validate, and prepare browser automation workflows from inline YAML or built-in templates. Returns the resolved workflow with steps and variable bindings, ready for browser execution. Templates: login-flow, form-validation, visual-regression, oauth-flow, etc.",domain:"test-execution",schema:this.buildSchema()};buildSchema(){return{type:"object",properties:{workflowYaml:{type:"string",description:"Inline YAML workflow definition. Mutually exclusive with templateName."},templateName:{type:"string",description:"Built-in template name to load.",enum:["login-flow","oauth-flow","scraping-workflow","visual-regression","form-validation","navigation-flow","api-integration","performance-audit","accessibility-audit"]},variables:{type:"object",description:'Runtime variable overrides (e.g., { "baseUrl": "https://example.com" })'}}}}async execute(r,C){try{let{WorkflowLoader:n,WORKFLOW_TEMPLATES:g,WORKFLOW_DESCRIPTIONS:v,interpolateVariables:b}=await import("./browser-IGDESJGF.js"),{parse:k}=await import("yaml"),d=new n,l=[...g],y=v;if(!r.workflowYaml&&!r.templateName)return{success:!0,data:{workflowName:"none",description:"No workflow specified. Use templateName or workflowYaml.",source:"none",templateUsed:null,steps:[],variables:{defined:[],provided:{}},validation:{valid:!0,errors:[],warnings:[]},availableTemplates:l,summary:`Available templates: ${l.join(", ")}`}};let e,i,t=null;r.workflowYaml?(i="inline-yaml",e=k(r.workflowYaml)):(i="template",t=r.templateName,e=await d.load(r.templateName));let a=await d.validate(e),w=(e.steps??[]).map(o=>{let s=o.config;if(r.variables){let c={};for(let[h,m]of Object.entries(s))c[h]=typeof m=="string"?b(m,r.variables):m;s=c}return{name:o.name,action:o.action,config:s,optional:o.optional??!1,assertionCount:o.assertions?.length??0}});return{success:!0,data:{workflowName:e.name||t||"custom",description:e.description||t&&y[t]||"",source:i,templateUsed:t,steps:w,variables:{defined:(e.variables??[]).map(o=>({name:o.name,type:o.type,required:o.required,hasDefault:o.default!==void 0})),provided:r.variables||{}},validation:{valid:a.valid,errors:a.errors,warnings:a.warnings},availableTemplates:l,summary:a.valid?`Workflow "${e.name}" loaded (${i}): ${w.length} steps, ${(e.variables??[]).length} variables`:`Workflow "${e.name}" has validation errors: ${a.errors.join("; ")}`}}}catch(n){return{success:!1,error:f(n)}}}};export{u as a};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.0");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.2");process.exit(0)}
2
2
  var u={0:{tier:0,name:"Agent Booster",description:"Mechanical code transforms via Rust/WASM",useCases:["var-to-const conversion","add-types","remove-console statements","promise-to-async","cjs-to-esm","func-to-arrow"],typicalLatencyMs:1,relativeCost:0,exampleModels:["agent-booster-wasm","agent-booster-typescript"],requiresNetwork:!1,complexityRange:[0,10]},1:{tier:1,name:"Haiku",description:"Fast, cost-effective for simple tasks",useCases:["Simple bug fixes","Code formatting","Documentation updates","Basic refactoring","Test generation (simple)"],typicalLatencyMs:500,relativeCost:1,exampleModels:["claude-haiku-4-5-20251001","gpt-4o-mini","gemini-flash"],requiresNetwork:!0,complexityRange:[10,35]},2:{tier:2,name:"Sonnet",description:"Balanced capability for complex reasoning",useCases:["Feature implementation","Complex refactoring","Security analysis","Performance optimization","Test generation (complex)"],typicalLatencyMs:3e3,relativeCost:2,exampleModels:["claude-sonnet-4-6","gpt-4o","gemini-pro"],requiresNetwork:!0,complexityRange:[35,70]},3:{tier:3,name:"Sonnet Extended",description:"Extended context for multi-step workflows",useCases:["Multi-file refactoring","Workflow orchestration","Cross-domain coordination","Large codebase analysis"],typicalLatencyMs:7e3,relativeCost:3,exampleModels:["claude-sonnet-4-6"],requiresNetwork:!0,complexityRange:[60,85]},4:{tier:4,name:"Opus",description:"Maximum capability for critical decisions",useCases:["Architecture design","Security audits","Complex algorithm design","Critical bug analysis","System-wide refactoring"],typicalLatencyMs:5e3,relativeCost:4,exampleModels:["claude-opus-4-7","gpt-4-turbo"],requiresNetwork:!0,complexityRange:[75,100]}},d={enabled:!0,tierBudgets:{0:{tier:0,maxCostPerRequest:0,maxRequestsPerHour:1e4,maxRequestsPerDay:1e5,maxDailyCostUsd:0,enabled:!0},1:{tier:1,maxCostPerRequest:.01,maxRequestsPerHour:100,maxRequestsPerDay:1e3,maxDailyCostUsd:5,enabled:!0},2:{tier:2,maxCostPerRequest:.1,maxRequestsPerHour:50,maxRequestsPerDay:500,maxDailyCostUsd:20,enabled:!0},3:{tier:3,maxCostPerRequest:.5,maxRequestsPerHour:20,maxRequestsPerDay:100,maxDailyCostUsd:30,enabled:!0},4:{tier:4,maxCostPerRequest:2,maxRequestsPerHour:10,maxRequestsPerDay:50,maxDailyCostUsd:50,enabled:!0}},maxDailyCostUsd:100,warningThreshold:.8,onBudgetExceeded:"downgrade",onBudgetWarning:"warn",allowCriticalOverrides:!0},y={budgetConfig:d,enableAgentBooster:!0,agentBoosterThreshold:.7,enableAutoRouting:!0,complexityThresholds:{0:10,1:35,2:70,3:85,4:100},allowManualOverrides:!0,enableDecisionCache:!0,decisionCacheTtlMs:300*1e3,enableMetrics:!0,maxDecisionTimeMs:10,fallbackTier:2,tierModels:{0:"agent-booster",1:"claude-haiku-4-5-20251001",2:"claude-sonnet-4-6",3:"claude-sonnet-4-6",4:"claude-opus-4-7"}},r=class extends Error{constructor(e,t,l){super(e);this.code=t;this.cause=l;this.name="ModelRouterError"}code;cause},a=class extends r{constructor(e,t,l){super(e,"BUDGET_EXCEEDED");this.tier=t;this.usage=l;this.name="BudgetExceededError"}tier;usage},i=class extends r{constructor(o,e){super(o,"COMPLEXITY_ANALYSIS_ERROR",e),this.name="ComplexityAnalysisError"}},s=class extends r{constructor(e,t){super(e,"ROUTING_TIMEOUT");this.timeoutMs=t;this.name="RoutingTimeoutError"}timeoutMs};export{u as a,d as b,y as c,r as d,a as e,i as f,s as g};
@@ -1,3 +1,3 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.0");process.exit(0)}
2
- import{k as f,o as P}from"./chunk-7RAB2BZY.js";import{d as p,e as y}from"./chunk-JY4VZ6BN.js";import{b as h,d as U}from"./chunk-HQHLHSJO.js";import{a as T,c as C}from"./chunk-XITTURP2.js";P();C();U();y();import{randomUUID as v}from"crypto";var M=p("TokenTracker"),S={costPerInputToken:.003/1e3,costPerOutputToken:.015/1e3},I={filePath:".agentic-qe/token-metrics.json",autoSaveIntervalMs:6e4,maxMetricsInMemory:1e4},m=class u{taskMetrics=[];agentMetrics=new Map;domainMetrics=new Map;sessionId;sessionStartTime;costConfig;cacheHits=0;earlyExits=0;totalTokensSaved=0;totalPatternsReused=0;initialized=!1;persistenceConfig=I;autoSaveTimer=null;isDirty=!1;db=null;kvPersistCount=0;static KV_NAMESPACE="token-usage-metrics";static KV_KEY="token-tracker-snapshot";static KV_TTL=604800;static KV_PERSIST_INTERVAL=10;constructor(){this.sessionId=`session-${Date.now()}-${v().substring(0,8)}`,this.sessionStartTime=Date.now(),this.costConfig=S}initialize(t){this.initialized||(this.initialized=!0,t&&(this.costConfig={...S,...t}),this.initializeDb().catch(e=>{M.warn("DB initialization failed",{error:e instanceof Error?e.message:String(e)})}),this.startAutoSave())}setCostConfig(t){this.costConfig={...this.costConfig,...t}}recordTokenUsage(t,e,n,a,s,r){this.ensureInitialized();let c,d,i,o,l,k;typeof e=="object"?(c="default",d="unknown",i="unknown",o=e,l=!1,k=0):(c=e,d=n??"unknown",i=a??"unknown",o=s,l=r?.patternReused??!1,k=r?.tokensSaved??0),o.estimatedCostUsd===void 0&&(o.estimatedCostUsd=this.calculateCost(o));let g={taskId:t,agentId:c,domain:d,operation:i,timestamp:Date.now(),usage:o,patternReused:l,tokensSaved:k};this.taskMetrics.push(g),this.updateAgentMetrics(c,o,l,k),this.updateDomainMetrics(d,o),l&&this.totalPatternsReused++,k>0&&(this.totalTokensSaved+=k),this.isDirty=!0,this.maybePersistToKv()}recordPatternReuse(t,e){this.ensureInitialized(),this.totalPatternsReused++,this.totalTokensSaved+=e;let n={taskId:t,agentId:"pattern-cache",domain:"optimization",operation:"pattern-reuse",timestamp:Date.now(),usage:{inputTokens:0,outputTokens:0,totalTokens:0,estimatedCostUsd:0},patternReused:!0,tokensSaved:e};this.taskMetrics.push(n),this.isDirty=!0}recordCacheHit(t){this.cacheHits++,this.totalTokensSaved+=t,this.isDirty=!0}recordEarlyExit(t){this.earlyExits++,this.totalTokensSaved+=t,this.isDirty=!0}getSessionSummary(t){this.ensureInitialized();let e=this.filterByTimeframe(this.taskMetrics,t),n=this.aggregateTokenUsage(e),a=new Map;for(let i of e){let o=a.get(i.agentId);o?(o.totalInputTokens+=i.usage.inputTokens,o.totalOutputTokens+=i.usage.outputTokens,o.totalTokens+=i.usage.totalTokens,o.totalCost+=i.usage.estimatedCostUsd||0,o.tasksExecuted++,i.patternReused&&o.patternsReused++,o.estimatedTokensSaved+=i.tokensSaved||0):a.set(i.agentId,{agentId:i.agentId,totalInputTokens:i.usage.inputTokens,totalOutputTokens:i.usage.outputTokens,totalTokens:i.usage.totalTokens,totalCost:i.usage.estimatedCostUsd||0,tasksExecuted:1,patternsReused:i.patternReused?1:0,estimatedTokensSaved:i.tokensSaved||0})}let s=new Map;for(let i of e){let o=s.get(i.domain);o?(o.inputTokens+=i.usage.inputTokens,o.outputTokens+=i.usage.outputTokens,o.totalTokens+=i.usage.totalTokens,o.estimatedCostUsd=(o.estimatedCostUsd||0)+(i.usage.estimatedCostUsd||0)):s.set(i.domain,{...i.usage})}let r=n.totalTokens,c=this.totalTokensSaved,d=r+c>0?c/(r+c)*100:0;return{sessionId:this.sessionId,startTime:this.sessionStartTime,endTime:Date.now(),byAgent:a,byDomain:s,totalUsage:n,optimizationStats:{patternsReused:this.totalPatternsReused,cacheHits:this.cacheHits,earlyExits:this.earlyExits,tokensSaved:this.totalTokensSaved,savingsPercentage:Math.round(d*100)/100}}}getAgentMetrics(t,e){this.ensureInitialized();let n=this.filterByTimeframe(this.taskMetrics,e);if(t){let s=n.filter(r=>r.agentId===t);return this.aggregateAgentMetrics(t,s)}let a=new Map;for(let s of n){let r=a.get(s.agentId)||[];r.push(s),a.set(s.agentId,r)}return Array.from(a.entries()).map(([s,r])=>this.aggregateAgentMetrics(s,r))}getDomainMetrics(t,e){this.ensureInitialized();let n=this.filterByTimeframe(this.taskMetrics,e);if(t){let s=n.filter(r=>r.domain===t);return this.aggregateTokenUsage(s)}let a=new Map;for(let s of n){let r=a.get(s.domain);r?(r.inputTokens+=s.usage.inputTokens,r.outputTokens+=s.usage.outputTokens,r.totalTokens+=s.usage.totalTokens,r.estimatedCostUsd=(r.estimatedCostUsd||0)+(s.usage.estimatedCostUsd||0)):a.set(s.domain,{...s.usage})}return a}getTaskMetrics(t){return this.ensureInitialized(),this.filterByTimeframe(this.taskMetrics,t)}getEfficiencyReport(t){return this.getTokenEfficiency(t)}getTokenEfficiency(t){this.ensureInitialized();let e=this.filterByTimeframe(this.taskMetrics,t),a=this.aggregateTokenUsage(e).totalTokens,s=this.totalTokensSaved,r=a+s>0?s/(a+s)*100:0,c=e.length,d=c>0?e.filter(l=>l.patternReused).length/c:0,i=c>0?a/c:0,o=this.generateRecommendations(e);return{totalTokensUsed:a,totalTokensSaved:s,savingsPercentage:Math.round(r*100)/100,patternReuseRate:Math.round(d*100)/100,averageTokensPerTask:Math.round(i),recommendations:o}}reset(){this.stopAutoSave(),this.taskMetrics=[],this.agentMetrics.clear(),this.domainMetrics.clear(),this.sessionId=`session-${Date.now()}-${v().substring(0,8)}`,this.sessionStartTime=Date.now(),this.cacheHits=0,this.earlyExits=0,this.totalTokensSaved=0,this.totalPatternsReused=0,this.isDirty=!1}configurePersistence(t){this.persistenceConfig={...this.persistenceConfig,...t},t.autoSaveIntervalMs!==void 0&&(this.stopAutoSave(),t.autoSaveIntervalMs>0&&this.startAutoSave())}startAutoSave(){this.autoSaveTimer||this.persistenceConfig.autoSaveIntervalMs>0&&(this.autoSaveTimer=setInterval(()=>{this.isDirty&&this.save().catch(t=>{console.warn("[TokenMetricsCollector] Auto-save failed:",t)})},this.persistenceConfig.autoSaveIntervalMs))}stopAutoSave(){this.autoSaveTimer&&(clearInterval(this.autoSaveTimer),this.autoSaveTimer=null)}async save(){let t=await import("fs"),e=await import("path"),n={version:"1.0.0",sessionId:this.sessionId,sessionStartTime:this.sessionStartTime,taskMetrics:this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory),optimizationStats:{cacheHits:this.cacheHits,earlyExits:this.earlyExits,totalTokensSaved:this.totalTokensSaved,totalPatternsReused:this.totalPatternsReused},lastSavedAt:Date.now()},a=e.resolve(this.persistenceConfig.filePath),s=e.dirname(a);t.existsSync(s)||t.mkdirSync(s,{recursive:!0}),t.writeFileSync(a,JSON.stringify(n,null,2)),this.isDirty=!1}async load(){let t=await import("fs"),n=(await import("path")).resolve(this.persistenceConfig.filePath);if(!t.existsSync(n))return!1;try{let a=t.readFileSync(n,"utf-8"),s=h(a);if(!s.version||!s.version.startsWith("1."))return console.warn("[TokenMetricsCollector] Incompatible data version, skipping load"),!1;let r=s.taskMetrics||[];this.taskMetrics=[...r,...this.taskMetrics],this.cacheHits+=s.optimizationStats?.cacheHits||0,this.earlyExits+=s.optimizationStats?.earlyExits||0,this.totalTokensSaved+=s.optimizationStats?.totalTokensSaved||0,this.totalPatternsReused+=s.optimizationStats?.totalPatternsReused||0;for(let c of r)this.updateAgentMetrics(c.agentId,c.usage,c.patternReused,c.tokensSaved||0),this.updateDomainMetrics(c.domain,c.usage);return this.taskMetrics.length>this.persistenceConfig.maxMetricsInMemory&&(this.taskMetrics=this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory)),!0}catch(a){return console.warn("[TokenMetricsCollector] Failed to load persisted data:",a),!1}}getPersistenceFilePath(){return this.persistenceConfig.filePath}hasUnsavedChanges(){return this.isDirty}async initializeDb(){try{this.db=f(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(t){console.warn("[TokenMetricsCollector] DB init failed, using memory-only:",T(t)),this.db=null}}async persistToKv(){if(!this.db)return;let t={version:"1.0.0",sessionId:this.sessionId,sessionStartTime:this.sessionStartTime,taskMetrics:this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory),optimizationStats:{cacheHits:this.cacheHits,earlyExits:this.earlyExits,totalTokensSaved:this.totalTokensSaved,totalPatternsReused:this.totalPatternsReused},lastSavedAt:Date.now()};await this.db.kvSet(u.KV_KEY,t,u.KV_NAMESPACE,u.KV_TTL)}async loadFromKv(){if(!this.db)return!1;let t=await this.db.kvGet(u.KV_KEY,u.KV_NAMESPACE);if(!t)return!1;if(!t.version||!t.version.startsWith("1."))return console.warn("[TokenMetricsCollector] Incompatible kv_store data version, skipping load"),!1;let e=t.taskMetrics||[];this.taskMetrics=[...e,...this.taskMetrics],this.cacheHits+=t.optimizationStats?.cacheHits||0,this.earlyExits+=t.optimizationStats?.earlyExits||0,this.totalTokensSaved+=t.optimizationStats?.totalTokensSaved||0,this.totalPatternsReused+=t.optimizationStats?.totalPatternsReused||0;for(let n of e)this.updateAgentMetrics(n.agentId,n.usage,n.patternReused,n.tokensSaved||0),this.updateDomainMetrics(n.domain,n.usage);return this.taskMetrics.length>this.persistenceConfig.maxMetricsInMemory&&(this.taskMetrics=this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory)),!0}maybePersistToKv(){this.kvPersistCount++,this.kvPersistCount>=u.KV_PERSIST_INTERVAL&&(this.kvPersistCount=0,this.persistToKv().catch(t=>{M.warn("KV persist failed",{error:t instanceof Error?t.message:String(t)})}))}ensureInitialized(){this.initialized||this.initialize()}calculateCost(t){let e=t.inputTokens*this.costConfig.costPerInputToken,n=t.outputTokens*this.costConfig.costPerOutputToken;return Math.round((e+n)*1e5)/1e5}filterByTimeframe(t,e){if(!e)return t;let n=Date.now(),a;switch(e){case"1h":a=n-3600*1e3;break;case"24h":a=n-1440*60*1e3;break;case"7d":a=n-10080*60*1e3;break;case"30d":a=n-720*60*60*1e3;break;default:return t}return t.filter(s=>s.timestamp>=a)}aggregateTokenUsage(t){let e=0,n=0,a=0,s=0;for(let r of t)e+=r.usage.inputTokens,n+=r.usage.outputTokens,a+=r.usage.totalTokens,s+=r.usage.estimatedCostUsd||0;return{inputTokens:e,outputTokens:n,totalTokens:a,estimatedCostUsd:Math.round(s*1e5)/1e5}}aggregateAgentMetrics(t,e){let n=0,a=0,s=0,r=0,c=0,d=0;for(let i of e)n+=i.usage.inputTokens,a+=i.usage.outputTokens,s+=i.usage.totalTokens,r+=i.usage.estimatedCostUsd||0,i.patternReused&&c++,d+=i.tokensSaved||0;return{agentId:t,totalInputTokens:n,totalOutputTokens:a,totalTokens:s,totalCost:Math.round(r*1e5)/1e5,tasksExecuted:e.length,patternsReused:c,estimatedTokensSaved:d}}updateAgentMetrics(t,e,n,a){let s=this.agentMetrics.get(t);s?(s.totalInputTokens+=e.inputTokens,s.totalOutputTokens+=e.outputTokens,s.totalTokens+=e.totalTokens,s.totalCost+=e.estimatedCostUsd||0,s.tasksExecuted++,n&&s.patternsReused++,s.estimatedTokensSaved+=a):this.agentMetrics.set(t,{agentId:t,totalInputTokens:e.inputTokens,totalOutputTokens:e.outputTokens,totalTokens:e.totalTokens,totalCost:e.estimatedCostUsd||0,tasksExecuted:1,patternsReused:n?1:0,estimatedTokensSaved:a})}updateDomainMetrics(t,e){let n=this.domainMetrics.get(t);n?(n.inputTokens+=e.inputTokens,n.outputTokens+=e.outputTokens,n.totalTokens+=e.totalTokens,n.estimatedCostUsd=(n.estimatedCostUsd||0)+(e.estimatedCostUsd||0)):this.domainMetrics.set(t,{...e})}generateRecommendations(t){let e=[];if(t.length===0)return["No token usage data available yet. Start executing tasks to track consumption."];let n=t.filter(i=>i.patternReused).length/t.length;n<.2?e.push("Low pattern reuse rate detected. Consider enabling pattern caching for similar tasks."):n>.5&&e.push("Good pattern reuse rate. Continue leveraging cached patterns for token savings.");let a=new Map;for(let i of t){let o=a.get(i.domain)||0;a.set(i.domain,o+i.usage.totalTokens)}let s=Array.from(a.entries()).sort((i,o)=>o[1]-i[1]);if(s.length>0){let i=s[0];e.push(`Highest token consumer: ${i[0]} (${i[1].toLocaleString()} tokens). Consider optimizing prompts or increasing caching.`)}let r=t.reduce((i,o)=>i+o.usage.inputTokens,0);return t.reduce((i,o)=>i+o.usage.outputTokens,0)/(r||1)>2&&e.push("High output-to-input token ratio. Consider requesting more concise responses."),this.cacheHits===0&&t.length>10&&e.push("No cache hits detected. Enable response caching to reduce duplicate API calls."),this.earlyExits===0&&t.length>20&&e.push("Early exit optimization not utilized. Enable high-confidence pattern matching to skip unnecessary LLM calls."),e}};function b(u){return u.toLocaleString("en-US")}function z(u){if(process.env.AQE_TOKEN_DASHBOARD_ENABLED==="false")return"Token dashboard disabled (AQE_TOKEN_DASHBOARD_ENABLED=false)";if(!u){let d=E.getSessionSummary(),i=d.totalUsage.totalTokens,o=d.totalUsage.estimatedCostUsd??0,l=d.optimizationStats.tokensSaved,k=i>0?o/i:0,g=l*k;u={totalTokens:i,totalCostUsd:o,savedTokens:l,savedCostUsd:g}}let t=u.totalTokens??0,e=u.totalCostUsd??0,n=u.savedTokens??0,a=u.savedCostUsd??0,s=u.budgetLimitUsd;if(t===0&&n===0)return"Token Dashboard: No data available";let r=`Token Usage: ${b(t)} tokens ($${e.toFixed(2)})`;n>0&&(r+=` | Saved: ${b(n)} tokens ($${a.toFixed(2)}) via pattern reuse`);let c=[];if(s!==void 0&&s>0){let d=Math.round(e/s*100);c.push(`Budget: $${e.toFixed(2)} / $${s.toFixed(2)} (${d}%)`)}if(u.tierSplit&&Object.keys(u.tierSplit).length>0){let d=Object.entries(u.tierSplit).sort((i,o)=>o[1]-i[1]).map(([i,o])=>`${i} ${o}%`);c.push(`Tier split: ${d.join(" | ")}`)}return c.length===0?r:`${r}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.2");process.exit(0)}
2
+ import{k as f,o as P}from"./chunk-W2FLULF4.js";import{d as p,e as y}from"./chunk-ICKLBATY.js";import{b as h,d as U}from"./chunk-QXTW7XCS.js";import{a as T,c as C}from"./chunk-D4RCV4LY.js";P();C();U();y();import{randomUUID as v}from"crypto";var M=p("TokenTracker"),S={costPerInputToken:.003/1e3,costPerOutputToken:.015/1e3},I={filePath:".agentic-qe/token-metrics.json",autoSaveIntervalMs:6e4,maxMetricsInMemory:1e4},m=class u{taskMetrics=[];agentMetrics=new Map;domainMetrics=new Map;sessionId;sessionStartTime;costConfig;cacheHits=0;earlyExits=0;totalTokensSaved=0;totalPatternsReused=0;initialized=!1;persistenceConfig=I;autoSaveTimer=null;isDirty=!1;db=null;kvPersistCount=0;static KV_NAMESPACE="token-usage-metrics";static KV_KEY="token-tracker-snapshot";static KV_TTL=604800;static KV_PERSIST_INTERVAL=10;constructor(){this.sessionId=`session-${Date.now()}-${v().substring(0,8)}`,this.sessionStartTime=Date.now(),this.costConfig=S}initialize(t){this.initialized||(this.initialized=!0,t&&(this.costConfig={...S,...t}),this.initializeDb().catch(e=>{M.warn("DB initialization failed",{error:e instanceof Error?e.message:String(e)})}),this.startAutoSave())}setCostConfig(t){this.costConfig={...this.costConfig,...t}}recordTokenUsage(t,e,n,a,s,r){this.ensureInitialized();let c,d,i,o,l,k;typeof e=="object"?(c="default",d="unknown",i="unknown",o=e,l=!1,k=0):(c=e,d=n??"unknown",i=a??"unknown",o=s,l=r?.patternReused??!1,k=r?.tokensSaved??0),o.estimatedCostUsd===void 0&&(o.estimatedCostUsd=this.calculateCost(o));let g={taskId:t,agentId:c,domain:d,operation:i,timestamp:Date.now(),usage:o,patternReused:l,tokensSaved:k};this.taskMetrics.push(g),this.updateAgentMetrics(c,o,l,k),this.updateDomainMetrics(d,o),l&&this.totalPatternsReused++,k>0&&(this.totalTokensSaved+=k),this.isDirty=!0,this.maybePersistToKv()}recordPatternReuse(t,e){this.ensureInitialized(),this.totalPatternsReused++,this.totalTokensSaved+=e;let n={taskId:t,agentId:"pattern-cache",domain:"optimization",operation:"pattern-reuse",timestamp:Date.now(),usage:{inputTokens:0,outputTokens:0,totalTokens:0,estimatedCostUsd:0},patternReused:!0,tokensSaved:e};this.taskMetrics.push(n),this.isDirty=!0}recordCacheHit(t){this.cacheHits++,this.totalTokensSaved+=t,this.isDirty=!0}recordEarlyExit(t){this.earlyExits++,this.totalTokensSaved+=t,this.isDirty=!0}getSessionSummary(t){this.ensureInitialized();let e=this.filterByTimeframe(this.taskMetrics,t),n=this.aggregateTokenUsage(e),a=new Map;for(let i of e){let o=a.get(i.agentId);o?(o.totalInputTokens+=i.usage.inputTokens,o.totalOutputTokens+=i.usage.outputTokens,o.totalTokens+=i.usage.totalTokens,o.totalCost+=i.usage.estimatedCostUsd||0,o.tasksExecuted++,i.patternReused&&o.patternsReused++,o.estimatedTokensSaved+=i.tokensSaved||0):a.set(i.agentId,{agentId:i.agentId,totalInputTokens:i.usage.inputTokens,totalOutputTokens:i.usage.outputTokens,totalTokens:i.usage.totalTokens,totalCost:i.usage.estimatedCostUsd||0,tasksExecuted:1,patternsReused:i.patternReused?1:0,estimatedTokensSaved:i.tokensSaved||0})}let s=new Map;for(let i of e){let o=s.get(i.domain);o?(o.inputTokens+=i.usage.inputTokens,o.outputTokens+=i.usage.outputTokens,o.totalTokens+=i.usage.totalTokens,o.estimatedCostUsd=(o.estimatedCostUsd||0)+(i.usage.estimatedCostUsd||0)):s.set(i.domain,{...i.usage})}let r=n.totalTokens,c=this.totalTokensSaved,d=r+c>0?c/(r+c)*100:0;return{sessionId:this.sessionId,startTime:this.sessionStartTime,endTime:Date.now(),byAgent:a,byDomain:s,totalUsage:n,optimizationStats:{patternsReused:this.totalPatternsReused,cacheHits:this.cacheHits,earlyExits:this.earlyExits,tokensSaved:this.totalTokensSaved,savingsPercentage:Math.round(d*100)/100}}}getAgentMetrics(t,e){this.ensureInitialized();let n=this.filterByTimeframe(this.taskMetrics,e);if(t){let s=n.filter(r=>r.agentId===t);return this.aggregateAgentMetrics(t,s)}let a=new Map;for(let s of n){let r=a.get(s.agentId)||[];r.push(s),a.set(s.agentId,r)}return Array.from(a.entries()).map(([s,r])=>this.aggregateAgentMetrics(s,r))}getDomainMetrics(t,e){this.ensureInitialized();let n=this.filterByTimeframe(this.taskMetrics,e);if(t){let s=n.filter(r=>r.domain===t);return this.aggregateTokenUsage(s)}let a=new Map;for(let s of n){let r=a.get(s.domain);r?(r.inputTokens+=s.usage.inputTokens,r.outputTokens+=s.usage.outputTokens,r.totalTokens+=s.usage.totalTokens,r.estimatedCostUsd=(r.estimatedCostUsd||0)+(s.usage.estimatedCostUsd||0)):a.set(s.domain,{...s.usage})}return a}getTaskMetrics(t){return this.ensureInitialized(),this.filterByTimeframe(this.taskMetrics,t)}getEfficiencyReport(t){return this.getTokenEfficiency(t)}getTokenEfficiency(t){this.ensureInitialized();let e=this.filterByTimeframe(this.taskMetrics,t),a=this.aggregateTokenUsage(e).totalTokens,s=this.totalTokensSaved,r=a+s>0?s/(a+s)*100:0,c=e.length,d=c>0?e.filter(l=>l.patternReused).length/c:0,i=c>0?a/c:0,o=this.generateRecommendations(e);return{totalTokensUsed:a,totalTokensSaved:s,savingsPercentage:Math.round(r*100)/100,patternReuseRate:Math.round(d*100)/100,averageTokensPerTask:Math.round(i),recommendations:o}}reset(){this.stopAutoSave(),this.taskMetrics=[],this.agentMetrics.clear(),this.domainMetrics.clear(),this.sessionId=`session-${Date.now()}-${v().substring(0,8)}`,this.sessionStartTime=Date.now(),this.cacheHits=0,this.earlyExits=0,this.totalTokensSaved=0,this.totalPatternsReused=0,this.isDirty=!1}configurePersistence(t){this.persistenceConfig={...this.persistenceConfig,...t},t.autoSaveIntervalMs!==void 0&&(this.stopAutoSave(),t.autoSaveIntervalMs>0&&this.startAutoSave())}startAutoSave(){this.autoSaveTimer||this.persistenceConfig.autoSaveIntervalMs>0&&(this.autoSaveTimer=setInterval(()=>{this.isDirty&&this.save().catch(t=>{console.warn("[TokenMetricsCollector] Auto-save failed:",t)})},this.persistenceConfig.autoSaveIntervalMs))}stopAutoSave(){this.autoSaveTimer&&(clearInterval(this.autoSaveTimer),this.autoSaveTimer=null)}async save(){let t=await import("fs"),e=await import("path"),n={version:"1.0.0",sessionId:this.sessionId,sessionStartTime:this.sessionStartTime,taskMetrics:this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory),optimizationStats:{cacheHits:this.cacheHits,earlyExits:this.earlyExits,totalTokensSaved:this.totalTokensSaved,totalPatternsReused:this.totalPatternsReused},lastSavedAt:Date.now()},a=e.resolve(this.persistenceConfig.filePath),s=e.dirname(a);t.existsSync(s)||t.mkdirSync(s,{recursive:!0}),t.writeFileSync(a,JSON.stringify(n,null,2)),this.isDirty=!1}async load(){let t=await import("fs"),n=(await import("path")).resolve(this.persistenceConfig.filePath);if(!t.existsSync(n))return!1;try{let a=t.readFileSync(n,"utf-8"),s=h(a);if(!s.version||!s.version.startsWith("1."))return console.warn("[TokenMetricsCollector] Incompatible data version, skipping load"),!1;let r=s.taskMetrics||[];this.taskMetrics=[...r,...this.taskMetrics],this.cacheHits+=s.optimizationStats?.cacheHits||0,this.earlyExits+=s.optimizationStats?.earlyExits||0,this.totalTokensSaved+=s.optimizationStats?.totalTokensSaved||0,this.totalPatternsReused+=s.optimizationStats?.totalPatternsReused||0;for(let c of r)this.updateAgentMetrics(c.agentId,c.usage,c.patternReused,c.tokensSaved||0),this.updateDomainMetrics(c.domain,c.usage);return this.taskMetrics.length>this.persistenceConfig.maxMetricsInMemory&&(this.taskMetrics=this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory)),!0}catch(a){return console.warn("[TokenMetricsCollector] Failed to load persisted data:",a),!1}}getPersistenceFilePath(){return this.persistenceConfig.filePath}hasUnsavedChanges(){return this.isDirty}async initializeDb(){try{this.db=f(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(t){console.warn("[TokenMetricsCollector] DB init failed, using memory-only:",T(t)),this.db=null}}async persistToKv(){if(!this.db)return;let t={version:"1.0.0",sessionId:this.sessionId,sessionStartTime:this.sessionStartTime,taskMetrics:this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory),optimizationStats:{cacheHits:this.cacheHits,earlyExits:this.earlyExits,totalTokensSaved:this.totalTokensSaved,totalPatternsReused:this.totalPatternsReused},lastSavedAt:Date.now()};await this.db.kvSet(u.KV_KEY,t,u.KV_NAMESPACE,u.KV_TTL)}async loadFromKv(){if(!this.db)return!1;let t=await this.db.kvGet(u.KV_KEY,u.KV_NAMESPACE);if(!t)return!1;if(!t.version||!t.version.startsWith("1."))return console.warn("[TokenMetricsCollector] Incompatible kv_store data version, skipping load"),!1;let e=t.taskMetrics||[];this.taskMetrics=[...e,...this.taskMetrics],this.cacheHits+=t.optimizationStats?.cacheHits||0,this.earlyExits+=t.optimizationStats?.earlyExits||0,this.totalTokensSaved+=t.optimizationStats?.totalTokensSaved||0,this.totalPatternsReused+=t.optimizationStats?.totalPatternsReused||0;for(let n of e)this.updateAgentMetrics(n.agentId,n.usage,n.patternReused,n.tokensSaved||0),this.updateDomainMetrics(n.domain,n.usage);return this.taskMetrics.length>this.persistenceConfig.maxMetricsInMemory&&(this.taskMetrics=this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory)),!0}maybePersistToKv(){this.kvPersistCount++,this.kvPersistCount>=u.KV_PERSIST_INTERVAL&&(this.kvPersistCount=0,this.persistToKv().catch(t=>{M.warn("KV persist failed",{error:t instanceof Error?t.message:String(t)})}))}ensureInitialized(){this.initialized||this.initialize()}calculateCost(t){let e=t.inputTokens*this.costConfig.costPerInputToken,n=t.outputTokens*this.costConfig.costPerOutputToken;return Math.round((e+n)*1e5)/1e5}filterByTimeframe(t,e){if(!e)return t;let n=Date.now(),a;switch(e){case"1h":a=n-3600*1e3;break;case"24h":a=n-1440*60*1e3;break;case"7d":a=n-10080*60*1e3;break;case"30d":a=n-720*60*60*1e3;break;default:return t}return t.filter(s=>s.timestamp>=a)}aggregateTokenUsage(t){let e=0,n=0,a=0,s=0;for(let r of t)e+=r.usage.inputTokens,n+=r.usage.outputTokens,a+=r.usage.totalTokens,s+=r.usage.estimatedCostUsd||0;return{inputTokens:e,outputTokens:n,totalTokens:a,estimatedCostUsd:Math.round(s*1e5)/1e5}}aggregateAgentMetrics(t,e){let n=0,a=0,s=0,r=0,c=0,d=0;for(let i of e)n+=i.usage.inputTokens,a+=i.usage.outputTokens,s+=i.usage.totalTokens,r+=i.usage.estimatedCostUsd||0,i.patternReused&&c++,d+=i.tokensSaved||0;return{agentId:t,totalInputTokens:n,totalOutputTokens:a,totalTokens:s,totalCost:Math.round(r*1e5)/1e5,tasksExecuted:e.length,patternsReused:c,estimatedTokensSaved:d}}updateAgentMetrics(t,e,n,a){let s=this.agentMetrics.get(t);s?(s.totalInputTokens+=e.inputTokens,s.totalOutputTokens+=e.outputTokens,s.totalTokens+=e.totalTokens,s.totalCost+=e.estimatedCostUsd||0,s.tasksExecuted++,n&&s.patternsReused++,s.estimatedTokensSaved+=a):this.agentMetrics.set(t,{agentId:t,totalInputTokens:e.inputTokens,totalOutputTokens:e.outputTokens,totalTokens:e.totalTokens,totalCost:e.estimatedCostUsd||0,tasksExecuted:1,patternsReused:n?1:0,estimatedTokensSaved:a})}updateDomainMetrics(t,e){let n=this.domainMetrics.get(t);n?(n.inputTokens+=e.inputTokens,n.outputTokens+=e.outputTokens,n.totalTokens+=e.totalTokens,n.estimatedCostUsd=(n.estimatedCostUsd||0)+(e.estimatedCostUsd||0)):this.domainMetrics.set(t,{...e})}generateRecommendations(t){let e=[];if(t.length===0)return["No token usage data available yet. Start executing tasks to track consumption."];let n=t.filter(i=>i.patternReused).length/t.length;n<.2?e.push("Low pattern reuse rate detected. Consider enabling pattern caching for similar tasks."):n>.5&&e.push("Good pattern reuse rate. Continue leveraging cached patterns for token savings.");let a=new Map;for(let i of t){let o=a.get(i.domain)||0;a.set(i.domain,o+i.usage.totalTokens)}let s=Array.from(a.entries()).sort((i,o)=>o[1]-i[1]);if(s.length>0){let i=s[0];e.push(`Highest token consumer: ${i[0]} (${i[1].toLocaleString()} tokens). Consider optimizing prompts or increasing caching.`)}let r=t.reduce((i,o)=>i+o.usage.inputTokens,0);return t.reduce((i,o)=>i+o.usage.outputTokens,0)/(r||1)>2&&e.push("High output-to-input token ratio. Consider requesting more concise responses."),this.cacheHits===0&&t.length>10&&e.push("No cache hits detected. Enable response caching to reduce duplicate API calls."),this.earlyExits===0&&t.length>20&&e.push("Early exit optimization not utilized. Enable high-confidence pattern matching to skip unnecessary LLM calls."),e}};function b(u){return u.toLocaleString("en-US")}function z(u){if(process.env.AQE_TOKEN_DASHBOARD_ENABLED==="false")return"Token dashboard disabled (AQE_TOKEN_DASHBOARD_ENABLED=false)";if(!u){let d=E.getSessionSummary(),i=d.totalUsage.totalTokens,o=d.totalUsage.estimatedCostUsd??0,l=d.optimizationStats.tokensSaved,k=i>0?o/i:0,g=l*k;u={totalTokens:i,totalCostUsd:o,savedTokens:l,savedCostUsd:g}}let t=u.totalTokens??0,e=u.totalCostUsd??0,n=u.savedTokens??0,a=u.savedCostUsd??0,s=u.budgetLimitUsd;if(t===0&&n===0)return"Token Dashboard: No data available";let r=`Token Usage: ${b(t)} tokens ($${e.toFixed(2)})`;n>0&&(r+=` | Saved: ${b(n)} tokens ($${a.toFixed(2)}) via pattern reuse`);let c=[];if(s!==void 0&&s>0){let d=Math.round(e/s*100);c.push(`Budget: $${e.toFixed(2)} / $${s.toFixed(2)} (${d}%)`)}if(u.tierSplit&&Object.keys(u.tierSplit).length>0){let d=Object.entries(u.tierSplit).sort((i,o)=>o[1]-i[1]).map(([i,o])=>`${i} ${o}%`);c.push(`Tier split: ${d.join(" | ")}`)}return c.length===0?r:`${r}
3
3
  ${c.join(" | ")}`}var E=new m;function $(u){return`$${u.toFixed(2)}`}export{z as a,E as b,$ as c};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.0");process.exit(0)}
2
- import{e as l,l as i}from"./chunk-3JIJBR4V.js";import{a as r,c as g}from"./chunk-XITTURP2.js";g();var c=class extends i{config={name:"qe/tests/schedule",description:"Schedule and execute tests using phase-based pipeline with git-aware selection and flaky tracking. Runs tests in phases (unit, integration, e2e), selects affected tests from git changes, and tracks flaky tests.",domain:"test-execution",schema:this.buildSchema()};buildSchema(){return{type:"object",properties:{cwd:{type:"string",description:"Working directory for test execution (defaults to project root)"},gitRef:{type:"string",description:'Git ref to compare for affected test selection (e.g., "main", "HEAD~3")'},useGitAware:{type:"boolean",description:"Enable git-aware test selection to only run affected tests",default:!0},trackFlaky:{type:"boolean",description:"Enable flaky test tracking and quarantine",default:!0}}}}async execute(s,o){try{let{runTestPipeline:n}=await import("./test-scheduling-ZNOSQVLD.js"),d=await l(o),t=await n({cwd:s.cwd||process.cwd(),memory:d,baseRef:s.gitRef,flakyHistoryPath:s.trackFlaky!==!1?".agentic-qe/flaky-history.json":void 0,runAllTests:s.useGitAware===!1}),u=t.phaseResults.reduce((e,a)=>e+a.totalTests,0),f=t.phaseResults.reduce((e,a)=>e+a.passed,0),p=t.phaseResults.reduce((e,a)=>e+a.failed,0);return{success:!0,data:{pipelineId:o.requestId,phases:t.phaseResults.map(e=>({phaseId:e.phaseId,phaseName:e.phaseName,totalTests:e.totalTests,passed:e.passed,failed:e.failed,passRate:e.passRate,durationMs:e.durationMs})),gitAware:{enabled:!t.ranAllTests,selectedTests:t.selectedTests.length,gitRef:s.gitRef},flakyTracking:{enabled:s.trackFlaky!==!1},totalDuration:t.totalDurationMs,ranAllTests:t.ranAllTests,summary:`Executed ${t.phaseResults.length} phases, ${u} tests (${f} passed, ${p} failed) in ${t.totalDurationMs}ms`}}}catch(n){return{success:!1,error:r(n)}}}};export{c as a};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.2");process.exit(0)}
2
+ import{e as l,l as i}from"./chunk-2LKAMMMI.js";import{a as r,c as g}from"./chunk-D4RCV4LY.js";g();var c=class extends i{config={name:"qe/tests/schedule",description:"Schedule and execute tests using phase-based pipeline with git-aware selection and flaky tracking. Runs tests in phases (unit, integration, e2e), selects affected tests from git changes, and tracks flaky tests.",domain:"test-execution",schema:this.buildSchema()};buildSchema(){return{type:"object",properties:{cwd:{type:"string",description:"Working directory for test execution (defaults to project root)"},gitRef:{type:"string",description:'Git ref to compare for affected test selection (e.g., "main", "HEAD~3")'},useGitAware:{type:"boolean",description:"Enable git-aware test selection to only run affected tests",default:!0},trackFlaky:{type:"boolean",description:"Enable flaky test tracking and quarantine",default:!0}}}}async execute(s,o){try{let{runTestPipeline:n}=await import("./test-scheduling-GPRXSIRP.js"),d=await l(o),t=await n({cwd:s.cwd||process.cwd(),memory:d,baseRef:s.gitRef,flakyHistoryPath:s.trackFlaky!==!1?".agentic-qe/flaky-history.json":void 0,runAllTests:s.useGitAware===!1}),u=t.phaseResults.reduce((e,a)=>e+a.totalTests,0),f=t.phaseResults.reduce((e,a)=>e+a.passed,0),p=t.phaseResults.reduce((e,a)=>e+a.failed,0);return{success:!0,data:{pipelineId:o.requestId,phases:t.phaseResults.map(e=>({phaseId:e.phaseId,phaseName:e.phaseName,totalTests:e.totalTests,passed:e.passed,failed:e.failed,passRate:e.passRate,durationMs:e.durationMs})),gitAware:{enabled:!t.ranAllTests,selectedTests:t.selectedTests.length,gitRef:s.gitRef},flakyTracking:{enabled:s.trackFlaky!==!1},totalDuration:t.totalDurationMs,ranAllTests:t.ranAllTests,summary:`Executed ${t.phaseResults.length} phases, ${u} tests (${f} passed, ${p} failed) in ${t.totalDurationMs}ms`}}}catch(n){return{success:!1,error:r(n)}}}};export{c as a};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.0");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.2");process.exit(0)}
2
2
  import r from"chalk";function s(e){switch(e){case"healthy":case"completed":return r.green(e);case"idle":return r.cyan(e);case"degraded":case"running":return r.yellow(e);case"unhealthy":case"failed":return r.red(e);default:return r.gray(e)}}function a(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:e<36e5?`${(e/6e4).toFixed(1)}m`:`${(e/36e5).toFixed(1)}h`}function l(e){let t=Math.floor(e/36e5),n=Math.floor(e%36e5/6e4),o=Math.floor(e%6e4/1e3);return`${t}h ${n}m ${o}s`}export{s as a,a as b,l as c};
@@ -0,0 +1,65 @@
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.2");process.exit(0)}
2
+ import{d as j,e as W,f as ne,g as V}from"./chunk-C7AXRI7E.js";import{a as se}from"./chunk-R5RNOLHI.js";import{b as Me}from"./chunk-IUNMW454.js";import{a as ae}from"./chunk-Q335R4MR.js";import{c as Fe,n as T}from"./chunk-E3Q7WNJD.js";import{b as De,c as at}from"./chunk-JDXLCNKV.js";import{a as ie,b as Oe,d as _e,f as ot}from"./chunk-HSJ5FQCF.js";import{c as Ne}from"./chunk-VSYBMNIR.js";import{b as P,c as v}from"./chunk-CIESXO73.js";import{a as S,b as xe,c as Ie}from"./chunk-D4RCV4LY.js";import{i as D}from"./chunk-NG2UVPTW.js";import{B as $,D as L,G as re,P as k,S as O,b as F}from"./chunk-GHQ5PUOV.js";import{d as B,f as st}from"./chunk-6VKJAMZY.js";var Y=B(E=>{var gt=E&&E.__extends||(function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var s in i)i.hasOwnProperty(s)&&(r[s]=i[s])},n(e,t)};return function(e,t){n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}})();Object.defineProperty(E,"__esModule",{value:!0});var yt=Object.prototype.hasOwnProperty;function he(n,e){return yt.call(n,e)}E.hasOwnProperty=he;function Je(n){if(Array.isArray(n)){for(var e=new Array(n.length),t=0;t<e.length;t++)e[t]=""+t;return e}if(Object.keys)return Object.keys(n);var r=[];for(var i in n)he(n,i)&&r.push(i);return r}E._objectKeys=Je;function vt(n){switch(typeof n){case"object":return JSON.parse(JSON.stringify(n));case"undefined":return null;default:return n}}E._deepClone=vt;function St(n){for(var e=0,t=n.length,r;e<t;){if(r=n.charCodeAt(e),r>=48&&r<=57){e++;continue}return!1}return!0}E.isInteger=St;function de(n){return n.indexOf("/")===-1&&n.indexOf("~")===-1?n:n.replace(/~/g,"~0").replace(/\//g,"~1")}E.escapePathComponent=de;function wt(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}E.unescapePathComponent=wt;function fe(n,e){var t;for(var r in n)if(he(n,r)){if(n[r]===e)return de(r)+"/";if(typeof n[r]=="object"&&(t=fe(n[r],e),t!=""))return de(r)+"/"+t}return""}E._getPathRecursive=fe;function Pt(n,e){if(n===e)return"/";var t=fe(n,e);if(t==="")throw new Error("Object not found in root");return"/"+t}E.getPath=Pt;function ue(n){if(n===void 0)return!0;if(n){if(Array.isArray(n)){for(var e=0,t=n.length;e<t;e++)if(ue(n[e]))return!0}else if(typeof n=="object"){for(var r=Je(n),i=r.length,s=0;s<i;s++)if(ue(n[r[s]]))return!0}}return!1}E.hasUndefined=ue;function ze(n,e){var t=[n];for(var r in e){var i=typeof e[r]=="object"?JSON.stringify(e[r],null,2):e[r];typeof i<"u"&&t.push(r+": "+i)}return t.join(`
3
+ `)}var bt=(function(n){gt(e,n);function e(t,r,i,s,a){var c=this.constructor,d=n.call(this,ze(t,{name:r,index:i,operation:s,tree:a}))||this;return d.name=r,d.index=i,d.operation=s,d.tree=a,Object.setPrototypeOf(d,c.prototype),d.message=ze(t,{name:r,index:i,operation:s,tree:a}),d}return e})(Error);E.PatchError=bt});var me=B(g=>{Object.defineProperty(g,"__esModule",{value:!0});var R=Y();g.JsonPatchError=R.PatchError;g.deepClone=R._deepClone;var U={add:function(n,e,t){return n[e]=this.value,{newDocument:t}},remove:function(n,e,t){var r=n[e];return delete n[e],{newDocument:t,removed:r}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:function(n,e,t){var r=K(t,this.path);r&&(r=R._deepClone(r));var i=_(t,{op:"remove",path:this.from}).removed;return _(t,{op:"add",path:this.path,value:i}),{newDocument:t,removed:r}},copy:function(n,e,t){var r=K(t,this.from);return _(t,{op:"add",path:this.path,value:R._deepClone(r)}),{newDocument:t}},test:function(n,e,t){return{newDocument:t,test:J(n[e],this.value)}},_get:function(n,e,t){return this.value=n[e],{newDocument:t}}},Et={add:function(n,e,t){return R.isInteger(e)?n.splice(e,0,this.value):n[e]=this.value,{newDocument:t,index:e}},remove:function(n,e,t){var r=n.splice(e,1);return{newDocument:t,removed:r[0]}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:U.move,copy:U.copy,test:U.test,_get:U._get};function K(n,e){if(e=="")return n;var t={op:"_get",path:e};return _(n,t),t.value}g.getValueByPointer=K;function _(n,e,t,r,i,s){if(t===void 0&&(t=!1),r===void 0&&(r=!0),i===void 0&&(i=!0),s===void 0&&(s=0),t&&(typeof t=="function"?t(e,0,n,e.path):Z(e,0)),e.path===""){var a={newDocument:n};if(e.op==="add")return a.newDocument=e.value,a;if(e.op==="replace")return a.newDocument=e.value,a.removed=n,a;if(e.op==="move"||e.op==="copy")return a.newDocument=K(n,e.from),e.op==="move"&&(a.removed=n),a;if(e.op==="test"){if(a.test=J(n,e.value),a.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a.newDocument=n,a}else{if(e.op==="remove")return a.removed=n,a.newDocument=null,a;if(e.op==="_get")return e.value=n,a;if(t)throw new g.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,e,n);return a}}else{r||(n=R._deepClone(n));var c=e.path||"",d=c.split("/"),o=n,l=1,f=d.length,h=void 0,u=void 0,m=void 0;for(typeof t=="function"?m=t:m=Z;;){if(u=d[l],u&&u.indexOf("~")!=-1&&(u=R.unescapePathComponent(u)),i&&(u=="__proto__"||u=="prototype"&&l>0&&d[l-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(t&&h===void 0&&(o[u]===void 0?h=d.slice(0,l).join("/"):l==f-1&&(h=e.path),h!==void 0&&m(e,0,n,h)),l++,Array.isArray(o)){if(u==="-")u=o.length;else{if(t&&!R.isInteger(u))throw new g.JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",s,e,n);R.isInteger(u)&&(u=~~u)}if(l>=f){if(t&&e.op==="add"&&u>o.length)throw new g.JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,e,n);var a=Et[e.op].call(e,o,u,n);if(a.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}}else if(l>=f){var a=U[e.op].call(e,o,u,n);if(a.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}if(o=o[u],t&&l<f&&(!o||typeof o!="object"))throw new g.JsonPatchError("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,e,n)}}}g.applyOperation=_;function Be(n,e,t,r,i){if(r===void 0&&(r=!0),i===void 0&&(i=!0),t&&!Array.isArray(e))throw new g.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(n=R._deepClone(n));for(var s=new Array(e.length),a=0,c=e.length;a<c;a++)s[a]=_(n,e[a],t,!0,i,a),n=s[a].newDocument;return s.newDocument=n,s}g.applyPatch=Be;function At(n,e,t){var r=_(n,e);if(r.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",t,e,n);return r.newDocument}g.applyReducer=At;function Z(n,e,t,r){if(typeof n!="object"||n===null||Array.isArray(n))throw new g.JsonPatchError("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,n,t);if(U[n.op]){if(typeof n.path!="string")throw new g.JsonPatchError("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,n,t);if(n.path.indexOf("/")!==0&&n.path.length>0)throw new g.JsonPatchError('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,n,t);if((n.op==="move"||n.op==="copy")&&typeof n.from!="string")throw new g.JsonPatchError("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&n.value===void 0)throw new g.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&R.hasUndefined(n.value))throw new g.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,n,t);if(t){if(n.op=="add"){var i=n.path.split("/").length,s=r.split("/").length;if(i!==s+1&&i!==s)throw new g.JsonPatchError("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,n,t)}else if(n.op==="replace"||n.op==="remove"||n.op==="_get"){if(n.path!==r)throw new g.JsonPatchError("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,n,t)}else if(n.op==="move"||n.op==="copy"){var a={op:"_get",path:n.from,value:void 0},c=je([a],t);if(c&&c.name==="OPERATION_PATH_UNRESOLVABLE")throw new g.JsonPatchError("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,n,t)}}}else throw new g.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,n,t)}g.validator=Z;function je(n,e,t){try{if(!Array.isArray(n))throw new g.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Be(R._deepClone(e),R._deepClone(n),t||!0);else{t=t||Z;for(var r=0;r<n.length;r++)t(n[r],r,e,void 0)}}catch(i){if(i instanceof g.JsonPatchError)return i;throw i}}g.validate=je;function J(n,e){if(n===e)return!0;if(n&&e&&typeof n=="object"&&typeof e=="object"){var t=Array.isArray(n),r=Array.isArray(e),i,s,a;if(t&&r){if(s=n.length,s!=e.length)return!1;for(i=s;i--!==0;)if(!J(n[i],e[i]))return!1;return!0}if(t!=r)return!1;var c=Object.keys(n);if(s=c.length,s!==Object.keys(e).length)return!1;for(i=s;i--!==0;)if(!e.hasOwnProperty(c[i]))return!1;for(i=s;i--!==0;)if(a=c[i],!J(n[a],e[a]))return!1;return!0}return n!==n&&e!==e}g._areEquals=J});var We=B(q=>{Object.defineProperty(q,"__esModule",{value:!0});var b=Y(),Rt=me(),ge=new WeakMap,Tt=(function(){function n(e){this.observers=new Map,this.obj=e}return n})(),Ct=(function(){function n(e,t){this.callback=e,this.observer=t}return n})();function xt(n){return ge.get(n)}function It(n,e){return n.observers.get(e)}function Dt(n,e){n.observers.delete(e.callback)}function Ft(n,e){e.unobserve()}q.unobserve=Ft;function Ot(n,e){var t=[],r,i=xt(n);if(!i)i=new Tt(n),ge.set(n,i);else{var s=It(i,e);r=s&&s.observer}if(r)return r;if(r={},i.value=b._deepClone(n),e){r.callback=e,r.next=null;var a=function(){pe(r)},c=function(){clearTimeout(r.next),r.next=setTimeout(a)};typeof window<"u"&&(window.addEventListener("mouseup",c),window.addEventListener("keyup",c),window.addEventListener("mousedown",c),window.addEventListener("keydown",c),window.addEventListener("change",c))}return r.patches=t,r.object=n,r.unobserve=function(){pe(r),clearTimeout(r.next),Dt(i,r),typeof window<"u"&&(window.removeEventListener("mouseup",c),window.removeEventListener("keyup",c),window.removeEventListener("mousedown",c),window.removeEventListener("keydown",c),window.removeEventListener("change",c))},i.observers.set(e,new Ct(e,r)),r}q.observe=Ot;function pe(n,e){e===void 0&&(e=!1);var t=ge.get(n.object);ye(t.value,n.object,n.patches,"",e),n.patches.length&&Rt.applyPatch(t.value,n.patches);var r=n.patches;return r.length>0&&(n.patches=[],n.callback&&n.callback(r)),r}q.generate=pe;function ye(n,e,t,r,i){if(e!==n){typeof e.toJSON=="function"&&(e=e.toJSON());for(var s=b._objectKeys(e),a=b._objectKeys(n),c=!1,d=!1,o=a.length-1;o>=0;o--){var l=a[o],f=n[l];if(b.hasOwnProperty(e,l)&&!(e[l]===void 0&&f!==void 0&&Array.isArray(e)===!1)){var h=e[l];typeof f=="object"&&f!=null&&typeof h=="object"&&h!=null&&Array.isArray(f)===Array.isArray(h)?ye(f,h,t,r+"/"+b.escapePathComponent(l),i):f!==h&&(c=!0,i&&t.push({op:"test",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(f)}),t.push({op:"replace",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(h)}))}else Array.isArray(n)===Array.isArray(e)?(i&&t.push({op:"test",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(f)}),t.push({op:"remove",path:r+"/"+b.escapePathComponent(l)}),d=!0):(i&&t.push({op:"test",path:r,value:n}),t.push({op:"replace",path:r,value:e}),c=!0)}if(!(!d&&s.length==a.length))for(var o=0;o<s.length;o++){var l=s[o];!b.hasOwnProperty(n,l)&&e[l]!==void 0&&t.push({op:"add",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(e[l])})}}}function _t(n,e,t){t===void 0&&(t=!1);var r=[];return ye(n,e,r,"",t),r}q.compare=_t});var Ve=B(N=>{var Nt=me();Object.assign(N,Nt);var Mt=We();Object.assign(N,Mt);var ee=Y();N.JsonPatchError=ee.PatchError;N.deepClone=ee._deepClone;N.escapePathComponent=ee.escapePathComponent;N.unescapePathComponent=ee.unescapePathComponent});var A=class extends Error{patternId;disposition;cause;constructor(e,t,r){super(`${t}: pattern ${e}: ${r instanceof Error?r.message:String(r)}`),this.name="PatternMutationError",this.patternId=e,this.disposition=t,this.cause=r}};at();import{existsSync as jt}from"node:fs";import{join as rt}from"node:path";Ie();var z=class{constructor(e,t){this.createAdapter=e;this.config=t?.base??X,this.rvfPath=t?.rvfPath??".agentic-qe/patterns.rvf",this.skipCloseOnDispose=t?.skipCloseOnDispose??!1,this.embeddingSpaceId=t?.embeddingSpaceId}createAdapter;config;rvfPath;skipCloseOnDispose;embeddingSpaceId;adapter=null;sqliteStore=null;initialized=!1;rvfInitError=null;searchOps=0;totalSearchMs=0;setSqliteStore(e){this.sqliteStore=e}getAdapter(){return this.adapter}async initialize(){if(!this.initialized){if(this.rvfInitError=null,process.env.AQE_MEMORY_BACKEND==="memory"){this.adapter=null,this.initialized=!0;return}try{this.adapter=this.createAdapter(this.rvfPath,this.config.embeddingDimension);let e=T()?.spaceId??this.embeddingSpaceId??null;Fe(this.rvfPath,e,this.adapter.status()?.totalVectors??0),this.initialized=!0,console.log(`[RvfPatternStore] Initialized: ${this.rvfPath} (dim=${this.config.embeddingDimension})`)}catch(e){this.rvfInitError=S(e);try{this.adapter?.close()}catch{}console.error(`[RvfPatternStore] ERROR: RVF native init failed \u2014 vector search is DISABLED. Cause: ${this.rvfInitError}. Fix: install @ruvector/rvf-node native bindings, or set useRVFPatternStore=false to use SQLite HNSW.`),this.adapter=null,this.initialized=!0}if(!this.sqliteStore)try{let{createSQLitePatternStore:e}=await import("./sqlite-persistence-NVVAPZN3.js"),t=e();await t.initialize(),this.sqliteStore=t}catch{}await this.purgeOrphanedVectors()}}async purgeOrphanedVectors(){if(!(!this.adapter||!this.sqliteStore))try{let e=this.adapter.status()?.totalVectors??0,t=this.sqliteStore.getStats()?.totalPatterns??0;if(e<=t)return;let{readFileSync:r,existsSync:i}=await import("node:fs"),s=`${this.rvfPath}.idmap.json`;if(!i(s))return;let a=JSON.parse(r(s,"utf-8")),c=new Set((a.entries??[]).map(l=>Array.isArray(l)?l[0]:void 0).filter(l=>typeof l=="string")),d=new Set(this.sqliteStore.getPatterns({limit:1e4}).map(l=>l.id)),o=[...c].filter(l=>!d.has(l));if(o.length===0)return;this.adapter.delete(o),console.log(`[RvfPatternStore] Removed ${o.length} ghost vectors (index ${e} > DB ${t})`)}catch(e){console.warn(`[RvfPatternStore] orphan purge skipped: ${S(e)}`)}}async dispose(){if(this.adapter&&!this.skipCloseOnDispose)try{this.adapter.close()}catch{}this.adapter=null,this.initialized=!1}async store(e){await this.ensureInitialized();let t=V(e);if(!t.valid)return v(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return v(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));if(!this.sqliteStore)return v(new A(e.id,"FAILED",new Error("authoritative SQLite pattern store is unavailable")));let r=T()?.spaceId??this.embeddingSpaceId;if(e.embedding&&!r)return v(new Error("VECTOR_SPACE_UNVERIFIED: refusing to persist or index an embedding without runtime provenance"));let i=!1;if(this.sqliteStore)try{let s=this.sqliteStore.storePattern(e,e.embedding,r);s&&s!==e.id&&(e.id=s),i=!0}catch(s){return v(new A(e.id,"FAILED",s))}if(e.embedding&&!this.adapter&&this.rvfInitError)return v(new A(e.id,i?"COMMITTED_PENDING_INDEX":"FAILED",new Error(`RVF unavailable ${i?"after":"before"} authoritative pattern commit: ${this.rvfInitError}`)));if(e.embedding&&this.adapter)try{let s=e.embedding instanceof Float32Array?e.embedding:new Float32Array(e.embedding),a=this.adapter.ingest([{id:e.id,vector:s}]);if(a.accepted!==1||a.rejected!==0)throw new Error(`RVF rejected pattern vector (accepted=${a.accepted}, rejected=${a.rejected})`)}catch(s){return v(new A(e.id,i?"COMMITTED_PENDING_INDEX":"FAILED",s))}return P(e.id)}async create(e){let t=e.confidence??.5,r=e.qeDomain??"test-generation",i={id:D(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:t,usageCount:0,successRate:0,qualityScore:j({confidence:t,usageCount:0,successRate:0}),context:{tags:[],...e.context},template:{example:"",...e.template},embedding:e.embedding,tier:"short-term",createdAt:new Date,lastUsedAt:new Date,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},s=await this.store(i);return s.success?P(i):v(s.error)}async get(e){if(this.sqliteStore)try{return this.sqliteStore.getPattern(e)??null}catch{return null}return null}async search(e,t={}){await this.ensureInitialized();let r=performance.now(),i=t.limit??10,s=[];if(Array.isArray(e)){let c=T()?.spaceId??this.embeddingSpaceId;if(!c||t.embeddingSpaceId!==c)return v(new Error("VECTOR_SPACE_UNVERIFIED: pre-computed query vectors require the active embeddingSpaceId"))}if(Array.isArray(e)&&this.adapter)try{let c=e instanceof Float32Array?e:new Float32Array(e),d=this.adapter.search(c,i*2);for(let o of d){let l=await this.get(o.id);if(l&&this.matchesFilters(l,t)){let f=this.calculateReuseInfo(l,o.score);s.push({pattern:l,score:o.score,matchType:"vector",similarity:o.score,canReuse:f.canReuse,estimatedTokenSavings:f.estimatedTokenSavings,reuseConfidence:f.reuseConfidence})}}}catch(c){console.warn("[RvfPatternStore] RVF search failed:",S(c))}if(Array.isArray(e)&&!this.adapter&&this.sqliteStore&&s.length===0)try{let c=this.sqliteStore.getPatterns({limit:i*4}),d=e,o=Math.sqrt(d.reduce((l,f)=>l+f*f,0));if(o>0)for(let l of c){if(!this.matchesFilters(l,t))continue;let f=this.sqliteStore.getPattern(l.id),h=f?.embedding;if(!h||h.length!==d.length)continue;let u=0,m=0;for(let w=0;w<d.length;w++)u+=d[w]*h[w],m+=h[w]*h[w];if(m=Math.sqrt(m),m===0)continue;let p=u/(o*m),y=this.calculateReuseInfo(f,p);s.push({pattern:f,score:p,matchType:"vector",similarity:p,canReuse:y.canReuse,estimatedTokenSavings:y.estimatedTokenSavings,reuseConfidence:y.reuseConfidence})}}catch{}if(typeof e=="string"&&!e.trim()&&this.sqliteStore)try{let c=this.sqliteStore.getPatterns({limit:i*2}),d=new Set(s.map(o=>o.pattern.id));for(let o of c){if(d.has(o.id)||!this.matchesFilters(o,t))continue;let l=this.calculateReuseInfo(o,o.confidence);s.push({pattern:o,score:o.confidence,matchType:"exact",similarity:o.confidence,canReuse:l.canReuse,estimatedTokenSavings:l.estimatedTokenSavings,reuseConfidence:l.reuseConfidence})}}catch{}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let c=this.sqliteStore.searchFTS(e,i*2),d=new Set(s.map(o=>o.pattern.id));for(let o of c){if(d.has(o.id))continue;let l=await this.get(o.id);if(l&&this.matchesFilters(l,t)){let f=this.calculateReuseInfo(l,o.ftsScore);s.push({pattern:l,score:.5*o.ftsScore,matchType:"exact",similarity:o.ftsScore,canReuse:f.canReuse,estimatedTokenSavings:f.estimatedTokenSavings,reuseConfidence:f.reuseConfidence})}}}catch{}s.sort((c,d)=>d.score-c.score);let a=performance.now()-r;return this.searchOps++,this.totalSearchMs+=a,P(s.slice(0,i))}async recordUsage(e,t,r,i){if(!this.sqliteStore)return v(new Error("No SQLite store attached"));try{return this.sqliteStore.recordUsage(e,t,r,i),P(void 0)}catch(s){return v(new Error(`recordUsage failed: ${S(s)}`))}}async promote(e){if(!this.sqliteStore)return v(new Error("No SQLite store attached"));try{return this.sqliteStore.promotePattern(e),P(void 0)}catch(t){return v(new Error(`promote failed: ${S(t)}`))}}async delete(e){if(this.adapter)try{this.adapter.delete([e])}catch(t){console.warn(`[RvfPatternStore] RVF delete failed for ${e}:`,S(t))}if(this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(t){return v(new Error(`SQLite delete failed: ${S(t)}`))}return P(void 0)}async getStats(){let e=this.adapter?.status(),t=0,r={},i={shortTerm:0,longTerm:0};if(this.sqliteStore)try{let s=this.sqliteStore.getStats();t=s.totalPatterns,r=s.byDomain,i={shortTerm:s.byTier["short-term"]??0,longTerm:s.byTier["long-term"]??0}}catch{}return{totalPatterns:t,byTier:i,byDomain:r,byType:{},avgConfidence:0,avgQualityScore:0,avgSuccessRate:0,searchOperations:this.searchOps,avgSearchLatencyMs:this.searchOps>0?this.totalSearchMs/this.searchOps:0,hnswStats:{nativeAvailable:this.adapter!==null,vectorCount:e?.totalVectors??0,indexSizeBytes:e?.fileSizeBytes??0,...this.rvfInitError?{rvfInitError:this.rvfInitError}:{}}}}async cleanup(){if(!this.sqliteStore)return{removed:0,promoted:0};let e=0,t=0;try{let r=this.sqliteStore.getPatterns({limit:1e4});for(let i of r)i.confidence<this.config.minConfidence&&i.usageCount>3?(await this.delete(i.id),e++):i.tier==="short-term"&&i.successfulUses>=W&&(await this.promote(i.id),t++)}catch(r){console.warn("[RvfPatternStore] Cleanup error:",S(r))}return{removed:e,promoted:t}}async ensureInitialized(){this.initialized||await this.initialize()}matchesFilters(e,t){return!(t.patternType&&e.patternType!==t.patternType||t.domain&&e.qeDomain!==t.domain||t.tier&&e.tier!==t.tier||t.minConfidence&&e.confidence<t.minConfidence||t.minQualityScore&&e.qualityScore<t.minQualityScore)}calculateReuseInfo(e,t){let r=this.config.reuseOptimization,i=r.enabled&&t>=r.minSimilarityForReuse&&e.successRate>=r.minSuccessRateForReuse;return{canReuse:i,estimatedTokenSavings:i?500:0,reuseConfidence:i?t*e.successRate:0}}};ot();Ie();O();function lt(n,e){let r=[n.pattern,n];for(let i of r){let s=e.split("."),a=i;for(let c of s){if(a==null)break;if(typeof a=="object")a=a[c];else{a=void 0;break}}if(a!==void 0)return a}}function dt(n,e,t){switch(e){case"eq":return n===t;case"gt":return typeof n=="number"&&typeof t=="number"&&n>t;case"lt":return typeof n=="number"&&typeof t=="number"&&n<t;case"gte":return typeof n=="number"&&typeof t=="number"&&n>=t;case"lte":return typeof n=="number"&&typeof t=="number"&&n<=t;case"in":return Array.isArray(t)?t.includes(n):!1;case"contains":return Array.isArray(n)||typeof n=="string"&&typeof t=="string"?n.includes(t):!1;case"between":{if(typeof n!="number"||!Array.isArray(t)||t.length!==2){if(n instanceof Date&&Array.isArray(t)&&t.length===2){let s=n.getTime(),a=t[0]instanceof Date?t[0].getTime():Number(t[0]),c=t[1]instanceof Date?t[1].getTime():Number(t[1]);return s>=a&&s<=c}return!1}let[r,i]=t;return n>=r&&n<=i}default:return!1}}function G(n,e){switch(e.type){case"AND":return(e.children??[]).every(r=>G(n,r));case"OR":{let t=e.children??[];return t.length===0?!0:t.some(r=>G(n,r))}case"NOT":return e.child?!G(n,e.child):!0;case"FIELD":{if(!e.field||!e.operator)return!0;let t=lt(n,e.field);return dt(t,e.operator,e.value)}default:return!0}}function He(n,e){return e?n.filter(t=>G(t,e)):n}O();O();var ke=1e4,Ue=2166136261;function qe(n){let e=2166136261;for(let t=0;t<n.length;t++)e^=n.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}var le=new Uint8Array(256);for(let n=0;n<256;n++){let e=0,t=n;for(;t;)e++,t&=t-1;le[n]=e}var Le="0123456789abcdef";function ut(n){let e=Math.min(n.length,16),t="";for(let r=0;r<e;r++){let i=n[r];t+=Le[i>>4]+Le[i&15]}return t}function ht(n,e){if(n.length!==e.length)throw new Error(`Cannot bind vectors of different lengths: ${n.length} vs ${e.length}`);let t=new Uint8Array(n.length);for(let r=0;r<n.length;r++)t[r]=n[r]^e[r];return t}function ft(n){if(n.length===0)throw new Error("Cannot bundle zero vectors");let e=n[0].length;for(let i=1;i<n.length;i++)if(n[i].length!==e)throw new Error(`Vector length mismatch at index ${i}: expected ${e}, got ${n[i].length}`);let t=new Uint8Array(e),r=n.length/2;for(let i=0;i<e;i++){let s=0;for(let a=0;a<8;a++){let c=0,d=1<<a;for(let o=0;o<n.length;o++)n[o][i]&d&&c++;c>=r&&(s|=d)}t[i]=s}return t}function mt(n,e,t){if(n.length!==e.length)throw new Error(`Cannot compute Hamming distance for vectors of different lengths: ${n.length} vs ${e.length}`);let r=0;for(let s=0;s<n.length;s++)r+=le[n[s]^e[s]];let i=t??n.length*8;return i>0?r/i:0}function pt(n,e,t){return 1-mt(n,e,t)}var oe=class{dimensions;baseSeed;byteLen;tokenCache=new Map;constructor(e){if(this.dimensions=e?.dimensions??ke,this.baseSeed=e?.seed??Ue,this.byteLen=Math.ceil(this.dimensions/8),this.dimensions<=0)throw new Error(`HDC dimensions must be positive, got ${this.dimensions}`)}tokenToHypervector(e){let t=this.tokenCache.get(e);if(t)return new Uint8Array(t);let r=qe(e)^this.baseSeed,i=this.generateSeededVector(r);return this.tokenCache.set(e,i),new Uint8Array(i)}fingerprintPattern(e){if(e.length===0)return new Uint8Array(this.byteLen);let t=this.tokenToHypervector(e[0]);for(let r=1;r<e.length;r++)t=ht(t,this.tokenToHypervector(e[r]));return t}fingerprintWithContext(e,t){let r=this.fingerprintPattern(e);if(t.length===0)return r;let i=this.fingerprintPattern(t);return ft([r,i])}similarity(e,t){return pt(e,t,this.dimensions)}generateSeededVector(e){let t=new Uint8Array(this.byteLen),r=new se(e),i=0;for(;i<this.byteLen;){let a=r.next(),c=Math.min(4,this.byteLen-i);for(let d=0;d<c;d++)t[i++]=a>>>d*8&255}let s=this.dimensions%8;return s>0&&(t[this.byteLen-1]&=(1<<s)-1),t}},ce=class{dimensions;baseSeed;constructor(e){if(this.dimensions=e?.dimensions??ke,this.baseSeed=e?.seed??Ue,this.dimensions<=0)throw new Error(`HDC dimensions must be positive, got ${this.dimensions}`)}fingerprint(e){let t=`${e.id}|${e.domain}|${e.type}|${e.content??""}`,r=qe(t)^this.baseSeed,i=this.generateVector(r);return{vector:i,dimensions:this.dimensions,hash:ut(i)}}compositionalBind(e,t){if(e.length!==t.length)throw new Error(`Cannot bind vectors of different lengths: ${e.length} vs ${t.length}`);let r=new Uint8Array(e.length);for(let i=0;i<e.length;i++)r[i]=e[i]^t[i];return r}hammingDistance(e,t){if(e.length!==t.length)throw new Error(`Cannot compute Hamming distance for vectors of different lengths: ${e.length} vs ${t.length}`);let r=0;for(let i=0;i<e.length;i++)r+=le[e[i]^t[i]];return r}similarity(e,t){return 1-this.hammingDistance(e,t)/this.dimensions}batchFingerprint(e){return e.map(t=>this.fingerprint(t))}generateVector(e){let t=Math.ceil(this.dimensions/8),r=new Uint8Array(t),i=new se(e),s=0;for(;s<t;){let c=i.next(),d=t-s,o=d<4?d:4;for(let l=0;l<o;l++)r[s++]=c>>>l*8&255}let a=this.dimensions%8;return a>0&&(r[t-1]&=(1<<a)-1),r}};function Qe(n){return new ce(n)}function $e(n){return $()?new oe(n):null}var Se=st(Ve(),1),ve=Se.default??Se,Ht=`
4
+ CREATE TABLE IF NOT EXISTS pattern_deltas (
5
+ id TEXT PRIMARY KEY,
6
+ pattern_id TEXT NOT NULL,
7
+ version INTEGER NOT NULL,
8
+ timestamp INTEGER NOT NULL,
9
+ type TEXT NOT NULL CHECK (type IN ('genesis', 'update', 'rollback')),
10
+ patch TEXT NOT NULL DEFAULT '[]',
11
+ reverse_patch TEXT NOT NULL DEFAULT '[]',
12
+ metadata TEXT
13
+ );
14
+ CREATE INDEX IF NOT EXISTS idx_pattern_deltas_pid_version
15
+ ON pattern_deltas (pattern_id, version);
16
+ CREATE INDEX IF NOT EXISTS idx_pattern_deltas_timestamp
17
+ ON pattern_deltas (timestamp);
18
+ `;function Xe(n,e){let t=ve.compare(n,e),r=ve.compare(e,n);return{forward:t,reverse:r}}function Lt(n,e){let t=JSON.parse(JSON.stringify(n));return ve.applyPatch(t,e).newDocument}function Ge(n){return{id:n.id,patternId:n.pattern_id,version:n.version,timestamp:n.timestamp,type:n.type,patch:JSON.parse(n.patch),reversePatch:JSON.parse(n.reverse_patch),metadata:n.metadata?JSON.parse(n.metadata):void 0}}var te=class{db;config;prepared=new Map;initialized=!1;constructor(e,t){this.db=e,this.config={maxVersionsPerPattern:t?.maxVersionsPerPattern??100,compressDeltas:t?.compressDeltas??!1}}initialize(){this.initialized||(this.db.exec(Ht),this.prepareStatements(),this.initialized=!0)}prepareStatements(){this.prepared.set("insert",this.db.prepare(`
19
+ INSERT INTO pattern_deltas (id, pattern_id, version, timestamp, type, patch, reverse_patch, metadata)
20
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
21
+ `)),this.prepared.set("getHistory",this.db.prepare(`
22
+ SELECT * FROM pattern_deltas
23
+ WHERE pattern_id = ?
24
+ ORDER BY version ASC
25
+ `)),this.prepared.set("currentVersion",this.db.prepare(`
26
+ SELECT MAX(version) as max_version FROM pattern_deltas
27
+ WHERE pattern_id = ?
28
+ `)),this.prepared.set("incrementalSync",this.db.prepare(`
29
+ SELECT * FROM pattern_deltas
30
+ WHERE timestamp > ?
31
+ ORDER BY timestamp ASC
32
+ `)),this.prepared.set("countForPattern",this.db.prepare(`
33
+ SELECT COUNT(*) as cnt FROM pattern_deltas
34
+ WHERE pattern_id = ?
35
+ `)),this.prepared.set("deleteOldest",this.db.prepare(`
36
+ DELETE FROM pattern_deltas
37
+ WHERE pattern_id = ? AND version IN (
38
+ SELECT version FROM pattern_deltas
39
+ WHERE pattern_id = ?
40
+ ORDER BY version ASC
41
+ LIMIT ?
42
+ )
43
+ `))}ensureInitialized(){if(!this.initialized)throw new Error("DeltaTracker not initialized. Call initialize() first.")}createGenesis(e,t,r){this.ensureInitialized();let i=this.getCurrentVersion(e);if(i>=0)throw new Error(`Genesis already exists for pattern ${e} (current version: ${i})`);let s={id:D(),patternId:e,version:0,timestamp:Date.now(),type:"genesis",patch:[],reversePatch:[],metadata:{...r,snapshot:t}};return this.insertEvent(s),s}recordDelta(e,t,r,i){this.ensureInitialized();let s=this.getCurrentVersion(e);if(s<0)throw new Error(`No genesis found for pattern ${e}. Call createGenesis() first.`);let{forward:a,reverse:c}=Xe(t,r),d={id:D(),patternId:e,version:s+1,timestamp:Date.now(),type:"update",patch:a,reversePatch:c,metadata:i};return this.insertEvent(d),this.enforceRetention(e),d}rollback(e,t){this.ensureInitialized();let r=this.getHistory(e);if(r.length===0)throw new Error(`No history found for pattern ${e}`);let i=r[r.length-1].version;if(t<0||t>i)throw new Error(`Invalid rollback version ${t}. Valid range: 0-${i}`);if(t===i)return this.reconstructState(r,i);let s=this.reconstructState(r,t),a=this.reconstructState(r,i),{forward:c,reverse:d}=Xe(a,s),o={id:D(),patternId:e,version:i+1,timestamp:Date.now(),type:"rollback",patch:c,reversePatch:d,metadata:{rolledBackTo:t}};return this.insertEvent(o),this.enforceRetention(e),s}getHistory(e){return this.ensureInitialized(),this.prepared.get("getHistory").all(e).map(Ge)}incrementalSync(e){return this.ensureInitialized(),this.prepared.get("incrementalSync").all(e).map(Ge)}getCurrentVersion(e){return this.ensureInitialized(),this.prepared.get("currentVersion").get(e).max_version??-1}insertEvent(e){this.prepared.get("insert").run(e.id,e.patternId,e.version,e.timestamp,e.type,JSON.stringify(e.patch),JSON.stringify(e.reversePatch),e.metadata?JSON.stringify(e.metadata):null)}reconstructState(e,t){let r=e.find(s=>s.type==="genesis");if(!r||!r.metadata?.snapshot)throw new Error("Cannot reconstruct state: no genesis snapshot found");let i=JSON.parse(JSON.stringify(r.metadata.snapshot));for(let s of e)if(s.version!==0){if(s.version>t)break;i=Lt(i,s.patch)}return i}enforceRetention(e){let{maxVersionsPerPattern:t}=this.config,i=this.prepared.get("countForPattern").get(e).cnt;if(i>t){let s=i-t;this.db.prepare(`DELETE FROM pattern_deltas
44
+ WHERE pattern_id = ? AND version != 0 AND id IN (
45
+ SELECT id FROM pattern_deltas
46
+ WHERE pattern_id = ? AND version != 0
47
+ ORDER BY version ASC
48
+ LIMIT ?
49
+ )`).run(e,e,s)}}};O();var kt={maxHistoryPerPattern:50,snapshotInterval:10,batchSize:20,epsilon:1e-7},we=class{config;history=new Map;snapshots=new Map;versions=new Map;buffer=[];constructor(e){this.config={...kt,...e}}recordGenesis(e,t,r){if(this.versions.has(e))throw new Error(`Genesis already exists for pattern ${e} (version ${this.versions.get(e)})`);let i=this.computeSparseChanges(new Array(t.length).fill(0),t),s={patternId:e,version:0,timestamp:Date.now(),deltaType:"genesis",sparseChanges:i,metadata:r,compressedSize:i.length},a={patternId:e,version:0,fullVector:[...t],timestamp:s.timestamp};return this.versions.set(e,0),this.getOrCreate(this.history,e).push(s),this.getOrCreate(this.snapshots,e).push(a),this.buffer.push(s),s}recordDelta(e,t,r,i){let s=this.versions.get(e);if(s===void 0)throw new Error(`No genesis found for pattern ${e}. Call recordGenesis() first.`);let a=s+1,c=this.computeSparseChanges(t,r),d={patternId:e,version:a,timestamp:Date.now(),deltaType:"update",sparseChanges:c,metadata:i,compressedSize:c.length};return this.versions.set(e,a),this.getOrCreate(this.history,e).push(d),this.buffer.push(d),a%this.config.snapshotInterval===0&&this.getOrCreate(this.snapshots,e).push({patternId:e,version:a,fullVector:[...r],timestamp:d.timestamp}),this.enforceRetention(e),d}getHistory(e,t){let r=this.history.get(e);if(!r||r.length===0)return[];let i=[...r].reverse();return t!==void 0&&t>0?i.slice(0,t):i}rollback(e,t){let r=this.reconstructAtVersion(e,t);return r===null?null:{patternId:e,version:t,fullVector:r,timestamp:Date.now()}}getVersion(e){return this.versions.get(e)??-1}reconstructAtVersion(e,t){let r=this.history.get(e);if(!r||r.length===0)return null;let i=this.versions.get(e);if(t<0||t>i)return null;let s=this.snapshots.get(e)||[],a=null;for(let o=s.length-1;o>=0;o--)if(s[o].version<=t){a=s[o];break}if(!a)return null;let c=[...a.fullVector],d=a.version+1;for(let o of r)if(!(o.version<d)){if(o.version>t)break;this.applySparseForward(c,o.sparseChanges)}return c}pruneHistory(e,t){let r=t??this.config.maxHistoryPerPattern,i=this.history.get(e);if(!i||i.length<=r)return 0;let s=i.length-r,a=i.slice(0,s),c=i.slice(s),d=a.findIndex(f=>f.deltaType==="genesis");d>=0&&(c.unshift(a[d]),a.splice(d,1)),this.history.set(e,c);let o=c[0]?.version??0,l=this.snapshots.get(e);return l&&this.snapshots.set(e,l.filter(f=>f.version===0||f.version>=o)),a.length}getStats(){let e=0;for(let r of this.history.values())e+=r.length;let t=this.history.size;return{totalPatterns:t,totalDeltas:e,avgDeltasPerPattern:t>0?e/t:0}}flush(){let e=[...this.buffer];return this.buffer.length=0,e}getBufferSize(){return this.buffer.length}clear(){this.history.clear(),this.snapshots.clear(),this.versions.clear(),this.buffer.length=0}computeSparseChanges(e,t){let r=[],i=Math.max(e.length,t.length);for(let s=0;s<i;s++){let a=s<e.length?e[s]:0,c=s<t.length?t[s]:0;Math.abs(a-c)>this.config.epsilon&&r.push({index:s,oldValue:a,newValue:c})}return r}applySparseForward(e,t){for(let r of t){for(;e.length<=r.index;)e.push(0);e[r.index]=r.newValue}}enforceRetention(e){this.pruneHistory(e,this.config.maxHistoryPerPattern)}getOrCreate(e,t){let r=e.get(t);return r||(r=[],e.set(t,r)),r}};function Ye(n){return L()?new we(n):null}O();var Ut=128,qt=8,Qt=1e4,Pe=class{dimension;beta;maxPatterns;patterns;constructor(e){if(this.dimension=e?.dimension??Ut,this.beta=e?.beta??qt,this.maxPatterns=e?.maxPatterns??Qt,this.patterns=[],this.dimension<=0)throw new Error(`Hopfield dimension must be positive, got ${this.dimension}`);if(this.beta<=0)throw new Error(`Hopfield beta must be positive, got ${this.beta}`);if(this.maxPatterns<=0)throw new Error(`Hopfield maxPatterns must be positive, got ${this.maxPatterns}`)}store(e,t){if(this.assertEnabled(),e.length!==this.dimension)throw new Error(`Pattern dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(this.dotProduct(e,e)===0)throw new Error("Cannot store zero-magnitude pattern in Hopfield memory");let i=this.normalize(e);this.patterns.length>=this.maxPatterns&&this.patterns.shift(),this.patterns.push({pattern:i,metadata:t??{},storedAt:Date.now()})}recall(e){if(this.assertEnabled(),e.length!==this.dimension)throw new Error(`Query dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(this.patterns.length===0)return null;let t=this.normalize(e),r=new Float32Array(this.patterns.length);for(let l=0;l<this.patterns.length;l++)r[l]=this.beta*this.dotProduct(this.patterns[l].pattern,t);let i=this.softmax(r),s=0,a=i[0];for(let l=1;l<i.length;l++)i[l]>a&&(a=i[l],s=l);let c=this.patterns[s],d=this.getEnergy(t),o=this.cosineSimilarity(t,c.pattern);return{pattern:new Float32Array(c.pattern),metadata:{...c.metadata},energy:d,similarity:o}}batchRecall(e){return this.assertEnabled(),e.map(t=>this.recall(t))}getPatternCount(){return this.patterns.length}clear(){this.patterns.length=0}getEnergy(e){if(e.length!==this.dimension)throw new Error(`State dimension mismatch: expected ${this.dimension}, got ${e.length}`);let t=this.normalize(e);if(this.patterns.length===0)return .5*this.dotProduct(t,t);let r=new Float32Array(this.patterns.length);for(let o=0;o<this.patterns.length;o++)r[o]=this.dotProduct(this.patterns[o].pattern,t);let i=new Float32Array(this.patterns.length),s=-1/0;for(let o=0;o<this.patterns.length;o++)i[o]=this.beta*r[o],i[o]>s&&(s=i[o]);let a=0;for(let o=0;o<this.patterns.length;o++)a+=Math.exp(i[o]-s);let c=1/this.beta*(s+Math.log(a)),d=this.dotProduct(t,t);return-c+.5*d}softmax(e){let t=new Float32Array(e.length),r=-1/0;for(let s=0;s<e.length;s++)e[s]>r&&(r=e[s]);let i=0;for(let s=0;s<e.length;s++)t[s]=Math.exp(e[s]-r),i+=t[s];if(i>0)for(let s=0;s<t.length;s++)t[s]/=i;return t}dotProduct(e,t){let r=0;for(let i=0;i<e.length;i++)r+=e[i]*t[i];return r}cosineSimilarity(e,t){let r=this.dotProduct(e,t),i=Math.sqrt(this.dotProduct(e,e)),s=Math.sqrt(this.dotProduct(t,t));return i===0||s===0?0:r/(i*s)}normalize(e){let t=Math.sqrt(this.dotProduct(e,e)),r=new Float32Array(e.length);if(t>0)for(let i=0;i<e.length;i++)r[i]=e[i]/t;return r}assertEnabled(){if(!F().useHopfieldMemory)throw new Error("Hopfield memory is disabled (useHopfieldMemory feature flag is false)")}};function Ke(n){return new Pe(n)}O();var $t={dimensions:32,curvature:-1,maxElements:1e4,efConstruction:200,M:16},M=1e-5,Ze=1-M;function zt(n,e){let t=0;for(let r=0;r<n.length;r++)t+=n[r]*e[r];return t}function C(n){let e=0;for(let t=0;t<n.length;t++)e+=n[t]*n[t];return e}function Jt(n,e){let t=new Float32Array(n.length);for(let r=0;r<n.length;r++)t[r]=n[r]-e[r];return t}var x=class n{static poincareDistance(e,t){let r=C(Jt(e,t)),i=Math.max(M,1-C(e)),s=Math.max(M,1-C(t));return Math.acosh(Math.max(1,1+2*r/(i*s)))}static mobiusAdd(e,t){let r=zt(e,t),i=C(e),s=C(t),a=Math.max(M,1+2*r+i*s),c=1+2*r+s,d=1-i,o=new Float32Array(e.length);for(let l=0;l<e.length;l++)o[l]=(c*e[l]+d*t[l])/a;return n.project(o)}static expMap(e,t){let r=2/Math.max(M,1-C(e)),i=Math.sqrt(C(t));if(i<M)return new Float32Array(e);let s=Math.tanh(r*i/2),a=new Float32Array(t.length);for(let c=0;c<t.length;c++)a[c]=s/i*t[c];return n.mobiusAdd(e,a)}static project(e){let t=Math.sqrt(C(e));if(t<=Ze)return new Float32Array(e);let r=Ze/t,i=new Float32Array(e.length);for(let s=0;s<e.length;s++)i[s]=e[s]*r;return i}static euclideanToHyperbolic(e){let t=Math.sqrt(C(e));if(t<M)return new Float32Array(e.length);let r=Math.tanh(t)/t,i=new Float32Array(e.length);for(let s=0;s<e.length;s++)i[s]=e[s]*r;return n.project(i)}},be=class{config;points=new Map;constructor(e){if(this.config={...$t,...e},this.config.dimensions<=0)throw new Error(`dimensions must be positive, got ${this.config.dimensions}`);if(this.config.curvature>=0)throw new Error(`curvature must be negative for hyperbolic space, got ${this.config.curvature}`);if(this.config.maxElements<=0)throw new Error(`maxElements must be positive, got ${this.config.maxElements}`)}insert(e,t,r){if(t.length!==this.config.dimensions)throw new Error(`Dimension mismatch: expected ${this.config.dimensions}, got ${t.length}`);if(this.points.size>=this.config.maxElements)throw new Error(`Maximum elements (${this.config.maxElements}) reached`);this.points.set(e,{id:e,coordinates:x.project(t),metadata:r?{...r}:void 0})}search(e,t){if(e.length!==this.config.dimensions)throw new Error(`Query dimension mismatch: expected ${this.config.dimensions}, got ${e.length}`);let r=x.project(e),i=[];for(let s of this.points.values())i.push({id:s.id,distance:x.poincareDistance(r,s.coordinates),point:s});return i.sort((s,a)=>s.distance-a.distance),i.slice(0,Math.max(0,t))}embedHierarchy(e){let t=new Map;if(e.length===0)return t;let r=this.config.dimensions,i=new Map,s=new Map,a=[];for(let d of e)if(s.set(d.id,d),!d.parentId)a.push(d.id);else{let o=i.get(d.parentId);o||(o=[],i.set(d.parentId,o)),o.push(d.id)}let c=a.map((d,o)=>({id:d,depth:0,angOff:2*Math.PI*o/Math.max(1,a.length),angSpan:2*Math.PI/Math.max(1,a.length)}));for(;c.length>0;){let{id:d,depth:o,angOff:l,angSpan:f}=c.shift(),h=Math.tanh(.3*(o+.1)),u=l+f/2,m=new Float32Array(r);m[0]=h*Math.cos(u),m[1]=h*Math.sin(u);let p=s.get(d);if(p&&p.features.length>0){let H=h*.1;for(let I=2;I<r&&I-2<p.features.length;I++)m[I]=p.features[I-2]*H}let y=x.project(m);t.set(d,y),this.points.set(d,{id:d,coordinates:y,metadata:{depth:o,parentId:p?.parentId}});let w=i.get(d)??[];for(let H=0;H<w.length;H++){let I=f/Math.max(1,w.length);c.push({id:w[H],depth:o+1,angOff:l+H*I,angSpan:I})}}return t}getStats(){return{elementCount:this.points.size,dimensions:this.config.dimensions,curvature:this.config.curvature}}};function et(n){return Bt()?new be(n):null}function Bt(){return F().useHyperbolicHnsw}O();var Ee=class{index=null;initialized=!1;config;constructor(e){this.config=e??{}}ensureInitialized(){if(this.initialized)return this.index!==null;if(this.initialized=!0,!k())return!1;try{return this.index=et(this.config),this.index!==null}catch(e){return console.warn("[HyperbolicPatternIndex] Failed to create HyperbolicHNSW:",e instanceof Error?e.message:e),this.index=null,!1}}get isAvailable(){return this.index!==null}indexPattern(e,t,r){if(!(!this.ensureInitialized()||!this.index))try{let i=t instanceof Float32Array?t:new Float32Array(t),s=x.euclideanToHyperbolic(i);this.index.insert(e,s,r)}catch(i){console.debug(`[HyperbolicPatternIndex] Failed to index pattern ${e}:`,i instanceof Error?i.message:i)}}search(e,t){if(!this.ensureInitialized()||!this.index)return[];try{let r=e instanceof Float32Array?e:new Float32Array(e),i=x.euclideanToHyperbolic(r);return this.index.search(i,t).map(a=>({patternId:a.id,distance:a.distance,metadata:a.point.metadata}))}catch(r){return console.warn("[HyperbolicPatternIndex] Search failed:",r instanceof Error?r.message:r),[]}}getStats(){return this.index?this.index.getStats():null}reset(){this.index=null,this.initialized=!1}};function tt(n){return new Ee(n)}var Ae=null;function nt(){return Ae||(Ae=Qe({dimensions:1e4})),Ae}var Re;function Wt(){return Re===void 0&&(Re=$e()),Re}var Q=null,Te=0;function it(n){return(!Q||Te!==n)&&(Q=Ke({dimension:n,maxPatterns:1e4}),Te=n),Q}var X={namespace:"qe-patterns",embeddingDimension:384,hnsw:{M:16,efConstruction:200,efSearch:100,maxElements:5e4},promotionThreshold:W,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}},Ce=class{constructor(e,t={}){this.memory=e;this.config={...X,...t}}memory;config;initialized=!1;cleanupTimer;sqliteStore=null;nullStore=null;loadingPromise=null;patternCache=new Map;domainIndex=new Map;typeIndex=new Map;tierIndex=new Map;hnswIndex=null;hnswSpaceId=null;hnswAvailable=!1;hnswInitPromise=null;hdcCache=new Map;hdcTokenCache=new Map;deltaTracker=null;vectorDeltaTracker=void 0;hyperbolicIndex=null;stats={searchOperations:0,searchLatencies:[]};setSqliteStore(e){if(this.sqliteStore=e,L()&&!this.deltaTracker)try{let t=e.getDb();this.deltaTracker=new te(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(){if(this.hnswIndex!==null){let e=T()?.spaceId??this.config.embeddingSpaceId??null;return this.hnswSpaceId!==e?(console.warn("[PatternStore] VECTOR_SPACE_MISMATCH: active embedder changed; semantic index disabled"),null):this.hnswIndex}return 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{if(this.hnswSpaceId=T()?.spaceId??this.config.embeddingSpaceId??null,!this.hnswSpaceId)throw new Error("VECTOR_SPACE_UNVERIFIED: cannot initialize HNSW without runtime provenance");if(F().useUnifiedHnsw)try{let{HnswLegacyBridge:a}=await import("./hnsw-legacy-bridge-YIILSRXI.js"),{HnswAdapter:c}=await import("./hnsw-adapter-BLSD45CX.js"),d=new c("patterns",{dimensions:this.config.embeddingDimension,M:this.config.hnsw.M,efConstruction:this.config.hnsw.efConstruction,efSearch:this.config.hnsw.efSearch,metric:"cosine"});this.hnswIndex=new a(d),this.hnswAvailable=!0,console.log("[PatternStore] Using unified HNSW via HnswLegacyBridge (ADR-071)"),await this.loadEmbeddingsIntoHNSW();return}catch(a){console.warn("[PatternStore] Unified HNSW bridge failed, falling back:",a)}let{HNSWIndex:t}=await import("./hnsw-index-A3RZODEN.js");this.hnswIndex=new t(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 r=5e3,i=this.hnswIndex.initialize(),s=new Promise((a,c)=>setTimeout(()=>c(new Error("HNSW init timeout")),r));await Promise.race([i,s]),this.hnswAvailable=this.hnswIndex.isNativeAvailable(),await this.loadEmbeddingsIntoHNSW(),console.log(`[PatternStore] HNSW lazy-initialized (native: ${this.hnswAvailable})`)}catch(e){console.warn("[PatternStore] HNSW not available, using memory backend search:",S(e)),this.hnswIndex=null,this.hnswAvailable=!1}}async loadEmbeddingsIntoHNSW(){if(!(!this.hnswIndex||!this.sqliteStore))try{let e=this.sqliteStore.getAllEmbeddings(),t=this.config.hnsw.maxElements,r=0,i=0,s=T()?.spaceId??this.config.embeddingSpaceId;for(let{patternId:a,embedding:c,spaceId:d}of e){if(r>=t)break;if(!s||d!==s||!c||c.length!==this.config.embeddingDimension){i++;continue}let o=this.patternCache.get(a);if(!o){i++;continue}try{await this.hnswIndex.insert(a,c,{filePath:o.patternType,lineCoverage:o.confidence*100,branchCoverage:o.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-o.confidence,lastUpdated:Date.now(),totalLines:0}),r++}catch{i++}}r>0&&console.log(`[PatternStore] Loaded ${r} embeddings into HNSW (skipped ${i})`)}catch(e){console.warn("[PatternStore] Failed to load SQLite embeddings into HNSW:",S(e))}}getVectorDeltaTracker(){return this.vectorDeltaTracker===void 0&&(this.vectorDeltaTracker=Ye()),this.vectorDeltaTracker}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:",S(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),this.hdcTokenCache.delete(e.id)}async store(e){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let t=V(e);if(!t.valid)return v(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return v(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));let r=(process.env.AQE_MEMORY_BACKEND??"memory")!=="memory";if(r&&!this.sqliteStore)return v(new A(e.id,"FAILED",new Error("authoritative SQLite pattern store is unavailable")));let i=T()?.spaceId??this.config.embeddingSpaceId;if(e.embedding&&!i)return v(new Error("VECTOR_SPACE_UNVERIFIED: refusing to persist or index an embedding without runtime provenance"));(this.domainIndex.get(e.qeDomain)?.size||0)>=this.config.maxPatternsPerDomain&&await this.cleanupDomain(e.qeDomain);let a=this.patternCache.get(e.id)??null,c=!1,d=()=>{this.unindexPattern(e),a&&this.indexPattern(a)};if(this.indexPattern(e),this.sqliteStore)try{let o=this.sqliteStore.storePattern(e,e.embedding,i);o&&o!==e.id&&(this.unindexPattern(e),e.id=o,this.indexPattern(e)),c=!0}catch(o){return d(),v(new A(e.id,"FAILED",o))}if(e.embedding){let o=await this.ensureHNSW();if(!o&&c)return v(new A(e.id,"COMMITTED_PENDING_INDEX",new Error("HNSW unavailable after authoritative pattern commit")));if(!o&&r)return d(),v(new A(e.id,"FAILED",new Error("HNSW unavailable before an authoritative pattern commit")));if(o)try{await o.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(l){return c||d(),v(new A(e.id,c?"COMMITTED_PENDING_INDEX":"FAILED",l))}}if($())try{let l=nt().fingerprint({id:e.id,domain:e.qeDomain,type:e.patternType,content:e.description});this.hdcCache.set(e.id,l.vector)}catch(o){console.debug(`[PatternStore] HDC fingerprint failed for ${e.id}:`,S(o))}try{let o=Wt();if(o){let l=[e.patternType,e.qeDomain];e.context?.tags&&l.push(...e.context.tags),e.name&&l.push(e.name);let f=o.fingerprintPattern(l);this.hdcTokenCache.set(e.id,f)}}catch(o){console.debug(`[PatternStore] HDC token fingerprint failed for ${e.id}:`,S(o))}if(re()&&e.embedding)try{it(e.embedding.length).store(new Float32Array(e.embedding),{id:e.id,name:e.name,domain:e.qeDomain})}catch(o){console.debug(`[PatternStore] Hopfield store failed for ${e.id}:`,S(o))}if(L()&&this.deltaTracker)try{let o={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,o)}catch(o){console.debug(`[PatternStore] Delta genesis for ${e.id}:`,S(o))}if(e.embedding)try{let o=this.getVectorDeltaTracker();o&&(a?.embedding?o.recordDelta(e.id,a.embedding,e.embedding):o.getVersion(e.id)<0&&o.recordGenesis(e.id,e.embedding))}catch(o){console.debug(`[PatternStore] VectorDeltaTracker for ${e.id}:`,S(o))}try{k()&&e.embedding&&this.indexHyperbolic(e.id,e.embedding,{domain:e.qeDomain,type:e.patternType,name:e.name})}catch{}return P(e.id)}async create(e){let t=new Date,r=e.qeDomain||this.detectDomainFromType(e.patternType),i={id:D(),patternType:e.patternType,qeDomain:r,domain:r,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},s=await this.store(i);return s.success?P(i):v(s.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","meta-optimization":"learning-optimization"}[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 r=performance.now(),i=t.limit||10,s=[];try{if(Array.isArray(e)&&re())try{let h=it(e.length);if(h.getPatternCount()>0){let u=h.recall(new Float32Array(e));if(u&&u.similarity>.98){let m=u.metadata.id,p=await this.get(m);if(p&&this.matchesFilters(p,t)){let y=this.calculateReuseInfo(p,u.similarity);s.push({pattern:p,score:u.similarity,matchType:"vector",similarity:u.similarity,canReuse:y.canReuse,estimatedTokenSavings:y.estimatedTokenSavings,reuseConfidence:y.reuseConfidence})}}}}catch(h){console.debug("[PatternStore] Hopfield recall failed:",S(h))}if(Array.isArray(e)&&t.useVectorSearch!==!1){let h=T()?.spaceId??this.config.embeddingSpaceId;if(!h||t.embeddingSpaceId!==h)throw new Error("VECTOR_SPACE_UNVERIFIED: pre-computed query vectors require the active embeddingSpaceId");let u=await this.ensureHNSW();if(u){let m=await u.search(e,i*2);for(let p of m){let y=await this.get(p.key);if(y&&this.matchesFilters(y,t)){let w=this.calculateReuseInfo(y,p.score);s.push({pattern:y,score:p.score,matchType:"vector",similarity:p.score,canReuse:w.canReuse,estimatedTokenSavings:w.estimatedTokenSavings,reuseConfidence:w.reuseConfidence})}}}}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let h=this.sqliteStore.searchFTS(e,i*2);if(h.length>0){let u=new Map(h.map(p=>[p.id,p.ftsScore])),m=new Set(s.map(p=>p.pattern.id));for(let p of s){let y=u.get(p.pattern.id);y!==void 0&&(p.score=.75*p.score+.25*y)}for(let p of h){if(m.has(p.id))continue;let y=await this.get(p.id);if(y&&this.matchesFilters(y,t)){let w=this.calculateReuseInfo(y,p.ftsScore);s.push({pattern:y,score:.5*p.ftsScore,matchType:"exact",similarity:p.ftsScore,canReuse:w.canReuse,estimatedTokenSavings:w.estimatedTokenSavings,reuseConfidence:w.reuseConfidence})}}}}catch{}if(typeof e=="string"||s.length<i){let h=await this.searchByText(typeof e=="string"?e:"",t,i-s.length),u=new Set(s.map(m=>m.pattern.id));for(let m of h)u.has(m.pattern.id)||s.push(m)}let a=720*60*60*1e3,c=Date.now();for(let h of s){let u=h.pattern.lastUsedAt?.getTime()??h.pattern.createdAt.getTime(),m=c-u,p=Math.pow(.5,m/a),y=h.pattern.usageCount>0?p:.5;h.score=h.score*(.7+.3*y)}let d=this.sqliteStore?.getDatabase();if(d&&s.length>0)try{this.nullStore||(this.nullStore=new ae(d));let h=this.nullStore.getNullSummaries(s.map(u=>u.pattern.id));for(let u of s){let m=h.get(u.pattern.id);m&&(u.nullSummary=m,u.score=ae.applyNullDiscount(u.score,m,t.contextFingerprint))}}catch(h){console.debug("[PatternStore] null discount skipped:",S(h))}s.sort((h,u)=>u.score-h.score);let o=s;t.filter&&(o=He(s,t.filter));let l=o.slice(0,i),f=performance.now()-r;return this.recordSearchLatency(f),P(l)}catch(a){return v(xe(a))}}async searchByText(e,t,r){let i=[],s=e.toLowerCase(),a;t.domain?a=this.domainIndex.get(t.domain)||new Set:t.patternType?a=this.typeIndex.get(t.patternType)||new Set:t.tier?a=this.tierIndex.get(t.tier)||new Set:a=new Set(this.patternCache.keys());let c=[...a];if($()&&s&&this.hdcCache.size>0)try{let d=nt(),o=d.fingerprint({id:"query",domain:t.domain??"unknown",type:t.patternType??"unknown",content:e}),l=c.filter(u=>this.hdcCache.has(u)).map(u=>({id:u,similarity:d.similarity(o.vector,this.hdcCache.get(u))}));l.sort((u,m)=>m.similarity-u.similarity);let f=l.map(u=>u.id),h=c.filter(u=>!this.hdcCache.has(u));c=[...f,...h]}catch{}for(let d of c){if(i.length>=r)break;let o=this.patternCache.get(d);if(!o||!this.matchesFilters(o,t))continue;let l=0;if(s){let f=o.name.toLowerCase(),h=o.description.toLowerCase();f.includes(s)&&(l+=.5),h.includes(s)&&(s.length/h.length>.3?l+=.5:l+=.3);for(let u of o.context.tags)if(u.toLowerCase().includes(s)){l+=.2;break}l=Math.min(l,1)}else l=o.qualityScore;if(l>0||!s){let f=this.calculateReuseInfo(o,l);i.push({pattern:o,score:l||o.qualityScore,matchType:s?"exact":"context",similarity:l||o.qualityScore,canReuse:f.canReuse,estimatedTokenSavings:f.estimatedTokenSavings,reuseConfidence:f.reuseConfidence})}}return i}calculateReuseInfo(e,t){let{reuseOptimization:r}=this.config,i=t>=r.minSimilarityForReuse,s=e.successRate>=r.minSuccessRateForReuse,a=e.lastUsedAt instanceof Date?e.lastUsedAt.getTime():new Date(e.lastUsedAt).getTime(),d=(Date.now()-a)/(1e3*60*60*24)<=r.maxAgeForReuse,o=r.enabled&&e.reusable&&i&&s&&d,l=o?e.averageTokenSavings>0?e.averageTokenSavings:e.tokensUsed||0:0,f=t,h=e.successRate,u=Math.min(e.reuseCount/10,1),m=o?f*.4+h*.4+u*.2:0;return{canReuse:o,estimatedTokenSavings:l,reuseConfidence:m}}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 r=t.context;if(r.language&&e.context.language!==r.language||r.framework&&e.context.framework!==r.framework||r.testType&&e.context.testType!==r.testType)return!1}return!0}async recordUsage(e,t,r,i){let s=await this.get(e);if(!s)return v(new Error(`Pattern not found: ${e}`));let a=new Date,c=s.usageCount+1,d=s.successfulUses+(t?1:0),o=d/c,l=t?.02:-.01,f=Math.max(.1,Math.min(1,s.confidence+l)),h=j({confidence:f,usageCount:c,successRate:o}),u={...s,usageCount:c,successfulUses:d,successRate:o,confidence:f,qualityScore:h,lastUsedAt:a};if(this.sqliteStore)try{this.sqliteStore.recordUsage(e,t,r,i)}catch(y){console.warn(`[PatternStore] SQLite recordUsage failed for ${e}:`,S(y))}if(L()&&this.deltaTracker)try{let y={id:s.id,name:s.name,confidence:s.confidence,qualityScore:s.qualityScore,usageCount:s.usageCount,successRate:s.successRate,tier:s.tier},w={id:u.id,name:u.name,confidence:u.confidence,qualityScore:u.qualityScore,usageCount:u.usageCount,successRate:u.successRate,tier:u.tier};this.deltaTracker.recordDelta(e,y,w,{success:t})}catch(y){console.debug(`[PatternStore] Delta recordDelta for ${e}:`,S(y))}let m=ne(u);return m.meetsUsageCriteria&&m.meetsQualityCriteria&&m.meetsCoherenceCriteria&&u.tier==="short-term"?await this.promote(e):this.patternCache.set(e,u),P(void 0)}async promote(e){let t=await this.get(e);if(!t)return v(new Error(`Pattern not found: ${e}`));if(t.tier==="long-term")return P(void 0);let r={...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,r),this.sqliteStore)try{this.sqliteStore.promotePattern(e)}catch(i){console.debug("[PatternStore] SQLite promotion error:",i instanceof Error?i.message:i)}return console.log(`[PatternStore] Promoted pattern ${e} (${t.name}) to long-term storage`),P(void 0)}async delete(e){let t=this.patternCache.get(e);if(!t)return v(new Error(`Pattern not found: ${e}`));if(this.unindexPattern(t),this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(r){console.debug("[PatternStore] SQLite deletion error:",r instanceof Error?r.message:r)}if(this.hnswIndex!==null)try{await this.hnswIndex.delete(e)}catch(r){console.debug("[PatternStore] HNSW deletion error:",r instanceof Error?r.message:r)}return P(void 0)}async getStats(){let e={},t={};for(let[o,l]of this.domainIndex)e[o]=l.size;for(let[o,l]of this.typeIndex)t[o]=l.size;let r=0,i=0,s=0,a=0;for(let o of this.patternCache.values())r+=o.confidence,i+=o.qualityScore,s+=o.successRate,a++;let c=await this.ensureHNSW(),d=c!==null?await c.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:a>0?r/a:0,avgQualityScore:a>0?i/a:0,avgSuccessRate:a>0?s/a:0,searchOperations:this.stats.searchOperations,avgSearchLatencyMs:this.calculateAvgLatency(),hnswStats:{nativeAvailable:d.nativeHNSW,vectorCount:d.vectorCount,indexSizeBytes:d.indexSizeBytes}}}async cleanup(){let e=0,t=0,r=[],i=[];for(let s of this.patternCache.values()){let a=ne(s);if(a.meetsUsageCriteria&&a.meetsQualityCriteria&&a.meetsCoherenceCriteria){i.push(s.id);continue}if(s.tier==="short-term"){let d=s.createdAt instanceof Date?s.createdAt.getTime():new Date(s.createdAt).getTime(),o=Date.now()-d,l=o>10080*60*1e3,f=s.qualityScore<.2,h=s.usageCount===0&&o>1440*60*1e3;(l&&f||h)&&r.push(s.id)}}for(let s of i)(await this.promote(s)).success&&t++;for(let s of r)(await this.delete(s)).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 r=[];for(let a of t){let c=this.patternCache.get(a);c&&r.push(c)}r.sort((a,c)=>a.qualityScore-c.qualityScore);let i=Math.ceil(r.length*.1),s=0;for(let a of r){if(s>=i)break;a.tier==="short-term"&&(await this.delete(a.id),s++)}}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,r)=>t+r,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,this.hyperbolicIndex&&(this.hyperbolicIndex.reset(),this.hyperbolicIndex=null),Q&&(Q.clear(),Q=null,Te=0),this.initialized=!1}indexHyperbolic(e,t,r){if(k())try{this.hyperbolicIndex||(this.hyperbolicIndex=tt({dimensions:this.config.embeddingDimension,maxElements:this.config.hnsw.maxElements})),this.hyperbolicIndex.indexPattern(e,t,r)}catch(i){console.debug(`[PatternStore] Hyperbolic indexing failed for ${e}:`,i instanceof Error?i.message:i)}}async searchHyperbolic(e,t=10){if(!k()||!this.hyperbolicIndex)return P([]);try{let r=this.hyperbolicIndex.search(e,t),i=[];for(let s of r){let a=await this.get(s.patternId);if(!a)continue;let c=Math.exp(-s.distance),d=this.calculateReuseInfo(a,c);i.push({pattern:a,score:c,matchType:"vector",similarity:c,canReuse:d.canReuse,estimatedTokenSavings:d.estimatedTokenSavings,reuseConfidence:d.reuseConfidence})}return P(i)}catch(r){return console.warn("[PatternStore] Hyperbolic search failed, returning empty results:",r instanceof Error?r.message:r),P([])}}};function rn(n,e){try{if(F().useRVFPatternStore&&_e()){let r=process.env.AQE_PROJECT_ROOT??De(),i=rt(r,".agentic-qe"),s=rt(i,"patterns.rvf");if(jt(i)){let a={...X,...e},c=!1;try{let d=Me(i,a.embeddingDimension);if(d){c=!0;let o=new z(()=>d,{rvfPath:s,base:a,skipCloseOnDispose:!0,embeddingSpaceId:a.embeddingSpaceId});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),o}}catch{}if(!c){let d=new z((o,l)=>{let f=()=>{try{return Oe(o)}catch{return null}},h=f();if(h){if(h.dimension()!==l){try{h.close()}catch{}throw new Error(`RVF dimension mismatch (file=${h.dimension()}, requested=${l})`)}return h}try{return ie(o,l)}catch(u){if(h=f(),h&&h.dimension()===l)return h;if(Ne(o,u instanceof Error?u.message:String(u)))return ie(o,l);throw u}},{rvfPath:s,base:a,embeddingSpaceId:a.embeddingSpaceId});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),d}}}}catch(t){console.warn("[PatternStore] RVF store unavailable, using in-memory HNSW:",t instanceof Error?t.message:t)}return new Ce(n,e)}export{A as a,rn as b};
50
+ /*! Bundled license information:
51
+
52
+ fast-json-patch/commonjs/helpers.js:
53
+ (*!
54
+ * https://github.com/Starcounter-Jack/JSON-Patch
55
+ * (c) 2017-2022 Joachim Wester
56
+ * MIT licensed
57
+ *)
58
+
59
+ fast-json-patch/commonjs/duplex.js:
60
+ (*!
61
+ * https://github.com/Starcounter-Jack/JSON-Patch
62
+ * (c) 2017-2021 Joachim Wester
63
+ * MIT license
64
+ *)
65
+ */
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.0");process.exit(0)}
2
- import{b as E,d as p,e as u,f as L}from"./chunk-7RAB2BZY.js";import{createHash as R}from"crypto";import{existsSync as A,readFileSync as X,writeFileSync as U,openSync as f,writeSync as I,closeSync as b}from"fs";L();var g=[`CREATE TABLE IF NOT EXISTS qe_patterns (
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.2");process.exit(0)}
2
+ import{b as E,d as p,e as u,f as L}from"./chunk-W2FLULF4.js";import{createHash as R}from"crypto";import{existsSync as A,readFileSync as X,writeFileSync as U,openSync as f,writeSync as I,closeSync as b}from"fs";L();var g=[`CREATE TABLE IF NOT EXISTS qe_patterns (
3
3
  id TEXT PRIMARY KEY, pattern_type TEXT NOT NULL, qe_domain TEXT NOT NULL,
4
4
  domain TEXT NOT NULL, name TEXT NOT NULL, description TEXT,
5
5
  confidence REAL DEFAULT 0.5, usage_count INTEGER DEFAULT 0,