agentic-qe 3.9.19 → 3.9.21

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 (307) hide show
  1. package/.claude/skills/skills-manifest.json +1 -1
  2. package/CHANGELOG.md +52 -0
  3. package/README.md +39 -0
  4. package/assets/skills/skills-manifest.json +1 -1
  5. package/dist/adapters/claude-flow/trajectory-bridge.d.ts +12 -1
  6. package/dist/adapters/claude-flow/trajectory-bridge.js +33 -31
  7. package/dist/cli/bundle.js +5 -5
  8. package/dist/cli/chunks/adapter-WOEZOCHJ.js +2 -0
  9. package/dist/cli/chunks/{agent-booster-wasm-HVBKHNIS.js → agent-booster-wasm-55SQPP6T.js} +2 -2
  10. package/dist/cli/chunks/{agent-handler-XNBDYRSJ.js → agent-handler-Q2UXL73Y.js} +2 -2
  11. package/dist/cli/chunks/{agent-memory-branch-YCVTQEMJ.js → agent-memory-branch-56GIYNGH.js} +2 -2
  12. package/dist/cli/chunks/aqe-learning-engine-5AHKLABJ.js +2 -0
  13. package/dist/cli/chunks/{audit-6C2PE7OY.js → audit-2JQ3URVN.js} +2 -2
  14. package/dist/cli/chunks/base-RNCRGTZJ.js +2 -0
  15. package/dist/cli/chunks/{better-sqlite3-HZPCHUQU.js → better-sqlite3-XGA7Z5YL.js} +2 -2
  16. package/dist/cli/chunks/{brain-handler-OV75Q2NM.js → brain-handler-TOOZFEK5.js} +3 -3
  17. package/dist/cli/chunks/{branch-enumerator-QW6D42HJ.js → branch-enumerator-2BLPN73D.js} +2 -2
  18. package/dist/cli/chunks/{browser-5BA7Q7OR.js → browser-FSVNN36N.js} +2 -2
  19. package/dist/cli/chunks/browser-workflow-MXHA63OC.js +2 -0
  20. package/dist/cli/chunks/{chunk-K554X3T4.js → chunk-2AEWOQWU.js} +2 -2
  21. package/dist/cli/chunks/{chunk-GVDLCJC5.js → chunk-34BTSZ5D.js} +1 -1
  22. package/dist/cli/chunks/{chunk-CYLQTVIA.js → chunk-3Y7OZ2PC.js} +2 -2
  23. package/dist/cli/chunks/{chunk-HVNW3TZS.js → chunk-44BAZASI.js} +1 -1
  24. package/dist/cli/chunks/{chunk-O5ZP3CBF.js → chunk-4O7YJIOS.js} +2 -2
  25. package/dist/cli/chunks/{chunk-HJ7CRPZY.js → chunk-4XZPDEK5.js} +1 -1
  26. package/dist/cli/chunks/{chunk-FL2DMHOQ.js → chunk-4Z4C7BXV.js} +1 -1
  27. package/dist/cli/chunks/{chunk-WULMXLNN.js → chunk-4ZUXTOUG.js} +1 -1
  28. package/dist/cli/chunks/{chunk-JYHZK44T.js → chunk-56DGV2Q3.js} +1 -1
  29. package/dist/cli/chunks/{chunk-SKNHAGYP.js → chunk-5EYQP3V3.js} +2 -2
  30. package/dist/cli/chunks/{chunk-TXCOK5DC.js → chunk-5FNEOJSD.js} +2 -2
  31. package/dist/cli/chunks/{chunk-FT3MAIRW.js → chunk-5PZG4WUA.js} +3 -3
  32. package/dist/cli/chunks/{chunk-WZUQT2BE.js → chunk-63PHZGO2.js} +2 -2
  33. package/dist/cli/chunks/chunk-65U55JIH.js +12 -0
  34. package/dist/cli/chunks/{chunk-MTHO6A3V.js → chunk-6MGACOLN.js} +1 -1
  35. package/dist/cli/chunks/{chunk-AOASQYOO.js → chunk-6OYRNNP2.js} +1 -1
  36. package/dist/cli/chunks/{chunk-XP4T7CZY.js → chunk-7P4IZQVQ.js} +2 -2
  37. package/dist/cli/chunks/{chunk-PUUTYV32.js → chunk-ACOEV3YB.js} +2 -2
  38. package/dist/cli/chunks/{chunk-UIASVDYG.js → chunk-ADC73GLJ.js} +2 -2
  39. package/dist/cli/chunks/{chunk-NMYZSZHW.js → chunk-AEQNCDYD.js} +2 -2
  40. package/dist/cli/chunks/chunk-AMOCYHP3.js +2 -0
  41. package/dist/cli/chunks/{chunk-KTDGHN2J.js → chunk-AT25VXEO.js} +1 -1
  42. package/dist/cli/chunks/{chunk-MN4366PQ.js → chunk-C4CZXAOE.js} +2 -2
  43. package/dist/cli/chunks/{chunk-GYDE5TCN.js → chunk-CJKR47YY.js} +1 -1
  44. package/dist/cli/chunks/{chunk-VXUIIZNG.js → chunk-D24HN6BG.js} +1 -1
  45. package/dist/cli/chunks/{chunk-U2WMCNNR.js → chunk-DBW745QA.js} +2 -2
  46. package/dist/cli/chunks/{chunk-BOUCIIUI.js → chunk-DQI5ZR34.js} +1 -1
  47. package/dist/cli/chunks/{chunk-SKDDAPBV.js → chunk-E2XIPBJ7.js} +1 -1
  48. package/dist/cli/chunks/{chunk-2WJLEZKP.js → chunk-E55MYZGP.js} +2 -2
  49. package/dist/cli/chunks/{chunk-44SPMVML.js → chunk-E5TGH4V3.js} +2 -2
  50. package/dist/cli/chunks/{chunk-OEQCZBBM.js → chunk-E7J32PW2.js} +2 -2
  51. package/dist/cli/chunks/{chunk-VSI45JCP.js → chunk-ETEV7IZI.js} +1 -1
  52. package/dist/cli/chunks/{chunk-TCUIYIZ4.js → chunk-EVWNZEYV.js} +1 -1
  53. package/dist/cli/chunks/{chunk-AEET2WOI.js → chunk-F4VJ4PPI.js} +59 -47
  54. package/dist/cli/chunks/{chunk-GYESQBDU.js → chunk-FBCLQTXO.js} +2 -2
  55. package/dist/cli/chunks/{chunk-IG2RCBHJ.js → chunk-FZ2SYLSK.js} +1 -1
  56. package/dist/cli/chunks/{chunk-XXHJKAE6.js → chunk-G276EI3G.js} +2 -2
  57. package/dist/cli/chunks/{chunk-ALYUJEYA.js → chunk-G7ZYDJZ3.js} +2 -2
  58. package/dist/cli/chunks/{chunk-I3JRRFVT.js → chunk-GB6ATLR3.js} +2 -2
  59. package/dist/cli/chunks/{chunk-MIQAFOFO.js → chunk-GDZ6XQRI.js} +1 -1
  60. package/dist/cli/chunks/{chunk-QOK4TIE4.js → chunk-GJGFPXWG.js} +2 -2
  61. package/dist/cli/chunks/{chunk-H4QM37XS.js → chunk-GLQ6LLKC.js} +1 -1
  62. package/dist/cli/chunks/{chunk-BGTYOZRK.js → chunk-GR4RXQXV.js} +2 -2
  63. package/dist/cli/chunks/{chunk-C5YFCM2H.js → chunk-HC4VOQZJ.js} +2 -2
  64. package/dist/cli/chunks/{chunk-NBBIA3QA.js → chunk-HIEP3L7H.js} +2 -2
  65. package/dist/cli/chunks/{chunk-DZS7XQ2Z.js → chunk-HJCJWPN5.js} +2 -2
  66. package/dist/cli/chunks/{chunk-BFBR2ZZJ.js → chunk-HMMJ6ZI6.js} +2 -2
  67. package/dist/cli/chunks/{chunk-XKD6AFY5.js → chunk-HRHKLRBB.js} +1 -1
  68. package/dist/cli/chunks/{chunk-AG7J7DTM.js → chunk-I3HLZASP.js} +2 -2
  69. package/dist/cli/chunks/{chunk-3HQ4AZDH.js → chunk-ICPQR533.js} +2 -2
  70. package/dist/cli/chunks/{chunk-AZKVGH5I.js → chunk-IM7X6BDZ.js} +2 -2
  71. package/dist/cli/chunks/{chunk-XQZ63XSL.js → chunk-IS6IES7Q.js} +1 -1
  72. package/dist/cli/chunks/{chunk-Y3GX66VZ.js → chunk-ISNDQOXC.js} +2 -2
  73. package/dist/cli/chunks/{chunk-2SSDY6OE.js → chunk-J3GG3Q4X.js} +2 -2
  74. package/dist/cli/chunks/{chunk-2XATUQIG.js → chunk-KDOA7YHW.js} +2 -2
  75. package/dist/cli/chunks/{chunk-U257SS7D.js → chunk-KENZAFI2.js} +2 -2
  76. package/dist/cli/chunks/{chunk-5LXWEAEJ.js → chunk-KID7PTBZ.js} +2 -2
  77. package/dist/cli/chunks/{chunk-M6EP724N.js → chunk-KRXJ7LFP.js} +1 -1
  78. package/dist/cli/chunks/{chunk-IPLQPBJA.js → chunk-KWPPF7O4.js} +2 -2
  79. package/dist/cli/chunks/{chunk-XF32XZMY.js → chunk-KYPN6G7T.js} +2 -2
  80. package/dist/cli/chunks/{chunk-B65GTWF3.js → chunk-LHXIAPKR.js} +2 -2
  81. package/dist/cli/chunks/chunk-LP52AQE2.js +2 -0
  82. package/dist/cli/chunks/{chunk-5X2AUPK2.js → chunk-LYZUB3NP.js} +1 -1
  83. package/dist/cli/chunks/{chunk-3X3QQZ7Q.js → chunk-MJGMH7TW.js} +2 -2
  84. package/dist/cli/chunks/{chunk-5KGFDNYI.js → chunk-MYZ43VKA.js} +2 -2
  85. package/dist/cli/chunks/{chunk-7WMHLBNZ.js → chunk-ND2TFQF5.js} +1 -1
  86. package/dist/cli/chunks/{chunk-R5IL3XD5.js → chunk-NGT3VL66.js} +24 -16
  87. package/dist/cli/chunks/{chunk-YXLQJ226.js → chunk-NJICCYCB.js} +2 -2
  88. package/dist/cli/chunks/{chunk-DAPBSAVT.js → chunk-NKOGDRZE.js} +2 -2
  89. package/dist/cli/chunks/{chunk-PS72GF4R.js → chunk-NS2ZWXUK.js} +3 -3
  90. package/dist/cli/chunks/{chunk-W3IO4FQ5.js → chunk-NV6AUEIH.js} +2 -2
  91. package/dist/cli/chunks/{chunk-3546SG2L.js → chunk-OEB3V633.js} +2 -2
  92. package/dist/cli/chunks/chunk-OHR5ILR3.js +2 -0
  93. package/dist/cli/chunks/{chunk-N2PLNYEV.js → chunk-OK5JHHXK.js} +1 -1
  94. package/dist/cli/chunks/{chunk-VRGXYOIN.js → chunk-OXXCWRFU.js} +1 -1
  95. package/dist/cli/chunks/{chunk-GJ5FON37.js → chunk-P4Q5TMDH.js} +2 -2
  96. package/dist/cli/chunks/{chunk-7IV2RK5M.js → chunk-PAXSPZ3F.js} +2 -2
  97. package/dist/cli/chunks/{chunk-5R2DUR3A.js → chunk-PEOTZFNZ.js} +2 -2
  98. package/dist/cli/chunks/{chunk-VHG67L7O.js → chunk-PGHTRQK6.js} +2 -2
  99. package/dist/cli/chunks/{chunk-HQFREZRX.js → chunk-QERANESS.js} +2 -2
  100. package/dist/cli/chunks/{chunk-NPSWRGNT.js → chunk-QPSPIESU.js} +2 -2
  101. package/dist/cli/chunks/{chunk-V7ZPTEP7.js → chunk-QREO5LNR.js} +1 -1
  102. package/dist/cli/chunks/{chunk-J7F65KKG.js → chunk-QSLXOYPR.js} +6 -6
  103. package/dist/cli/chunks/{chunk-VWWLJBRA.js → chunk-QU3VFWZZ.js} +14 -14
  104. package/dist/cli/chunks/{chunk-KU7OXAFY.js → chunk-RDUIN7LO.js} +1 -1
  105. package/dist/cli/chunks/{chunk-O6UMETOH.js → chunk-RHAUASC6.js} +2 -2
  106. package/dist/cli/chunks/{chunk-P6EYD4V3.js → chunk-RIVX6YLS.js} +2 -2
  107. package/dist/cli/chunks/{chunk-FPVXXQVX.js → chunk-ROC2SSV3.js} +3 -3
  108. package/dist/cli/chunks/{chunk-B2EHSFUW.js → chunk-S3TU7B7D.js} +2 -2
  109. package/dist/cli/chunks/{chunk-LTE3CDOY.js → chunk-S5RNBBJ6.js} +2 -2
  110. package/dist/cli/chunks/{chunk-TMAIHTE3.js → chunk-S6FFUCVZ.js} +4 -4
  111. package/dist/cli/chunks/{chunk-GL742O2V.js → chunk-SIW4N4NE.js} +4 -4
  112. package/dist/cli/chunks/{chunk-37DTXQ6P.js → chunk-SMAC5IX4.js} +2 -2
  113. package/dist/cli/chunks/{chunk-5MGRZ4YD.js → chunk-SMBQERK7.js} +2 -2
  114. package/dist/cli/chunks/{chunk-G2V4GMPR.js → chunk-T5Z5LL5Y.js} +3 -3
  115. package/dist/cli/chunks/{chunk-NXO7CT5K.js → chunk-TCNJ5NGT.js} +2 -2
  116. package/dist/cli/chunks/{chunk-JCPJG2KU.js → chunk-TFAS5UND.js} +3 -3
  117. package/dist/cli/chunks/{chunk-SLDYG7LC.js → chunk-TMKJXKY2.js} +2 -2
  118. package/dist/cli/chunks/{chunk-D74RGYKI.js → chunk-TOE6DKE4.js} +1 -1
  119. package/dist/cli/chunks/{chunk-MMVSIESL.js → chunk-UOLIGPDW.js} +2 -2
  120. package/dist/cli/chunks/{chunk-SRKBR4DU.js → chunk-V5AVC4D4.js} +2 -2
  121. package/dist/cli/chunks/{chunk-RL5CBCBV.js → chunk-V6GJ3EMZ.js} +1 -1
  122. package/dist/cli/chunks/{chunk-2SIQ742L.js → chunk-VGAG5TG7.js} +1 -1
  123. package/dist/cli/chunks/{chunk-255CWHTF.js → chunk-VQLHHNOH.js} +2 -2
  124. package/dist/cli/chunks/{chunk-LDBHCOM3.js → chunk-VQXHHEPD.js} +2 -2
  125. package/dist/cli/chunks/{chunk-EZZJ5XD6.js → chunk-WI5HBS3C.js} +2 -2
  126. package/dist/cli/chunks/{chunk-HCSTXZYE.js → chunk-WL5IRCU4.js} +2 -2
  127. package/dist/cli/chunks/{chunk-FNVA7U7X.js → chunk-WY3H7VHF.js} +2 -2
  128. package/dist/cli/chunks/{chunk-FJJLNCSL.js → chunk-XEMVYJ2Z.js} +3 -3
  129. package/dist/cli/chunks/{chunk-EW5TQQBR.js → chunk-Y36AJ462.js} +2 -2
  130. package/dist/cli/chunks/{chunk-VLQYU7ZQ.js → chunk-YH7BAX7S.js} +1 -1
  131. package/dist/cli/chunks/{chunk-BB3KUX6C.js → chunk-YS5WV3CJ.js} +1 -1
  132. package/dist/cli/chunks/{chunk-6BRUQTC7.js → chunk-YVG4D6P3.js} +1 -1
  133. package/dist/cli/chunks/{chunk-JLX35EPX.js → chunk-YVPPR33H.js} +2 -2
  134. package/dist/cli/chunks/{chunk-IV74GAZN.js → chunk-ZUTYZIWQ.js} +2 -2
  135. package/dist/cli/chunks/{ci-FTZE4PD3.js → ci-GU2HBK5E.js} +2 -2
  136. package/dist/cli/chunks/{ci-output-C3ORCIHU.js → ci-output-FGZTTY3R.js} +2 -2
  137. package/dist/cli/chunks/{circuit-breaker-GS5OTOJZ.js → circuit-breaker-6UNLOLMW.js} +2 -2
  138. package/dist/cli/chunks/{claude-flow-setup-RWOFP5L2.js → claude-flow-setup-SCOCIDBC.js} +2 -2
  139. package/dist/cli/chunks/client-XU3ZUFMH.js +2 -0
  140. package/dist/cli/chunks/{cline-installer-D7RGRAUH.js → cline-installer-G6PQERGI.js} +2 -2
  141. package/dist/cli/chunks/{code-HBDMMYHY.js → code-RNKTYBI4.js} +2 -2
  142. package/dist/cli/chunks/{code-index-extractor-B2KUPAEH.js → code-index-extractor-A6KAUQOU.js} +2 -2
  143. package/dist/cli/chunks/{codex-installer-MPXV4AOD.js → codex-installer-ABWDMKEX.js} +2 -2
  144. package/dist/cli/chunks/{completions-QJS6QOZQ.js → completions-TB4E6O46.js} +2 -2
  145. package/dist/cli/chunks/{complexity-analyzer-YQQXWZIL.js → complexity-analyzer-XS37O7OR.js} +2 -2
  146. package/dist/cli/chunks/{continuedev-installer-Z6PBKYMB.js → continuedev-installer-WDY6O2SR.js} +2 -2
  147. package/dist/cli/chunks/{copilot-installer-RWVD44CV.js → copilot-installer-SDJ3GYLU.js} +2 -2
  148. package/dist/cli/chunks/{cost-tracker-DFPBFYWL.js → cost-tracker-MWEXRK7F.js} +2 -2
  149. package/dist/cli/chunks/{coverage-DYST26FK.js → coverage-Y3KDB56G.js} +3 -3
  150. package/dist/cli/chunks/cross-domain-router-KKYQWQE7.js +2 -0
  151. package/dist/cli/chunks/{cursor-installer-LL6UWKTZ.js → cursor-installer-4U7XENLX.js} +2 -2
  152. package/dist/cli/chunks/{daemon-6PIHFZNR.js → daemon-D6R3BPBJ.js} +3 -3
  153. package/dist/cli/chunks/{dag-attention-scheduler-WS3HJW4F.js → dag-attention-scheduler-EMVUX6ES.js} +2 -2
  154. package/dist/cli/chunks/{detect-J4OITSUD.js → detect-QIJPCTZO.js} +2 -2
  155. package/dist/cli/chunks/{dist-node-QSLD5K6K.js → dist-node-4ZYBZKOB.js} +2 -2
  156. package/dist/cli/chunks/{domain-handler-BD53QZ4Q.js → domain-handler-X6CTXJQF.js} +2 -2
  157. package/dist/cli/chunks/{domain-transfer-VZBWINQL.js → domain-transfer-HK4ER37F.js} +2 -2
  158. package/dist/cli/chunks/dream-FBYASIID.js +2 -0
  159. package/dist/cli/chunks/{embed-and-insert-pattern-5UAFXNDX.js → embed-and-insert-pattern-XKTD5DQ3.js} +2 -2
  160. package/dist/cli/chunks/{eval-GBKU6VTD.js → eval-WEEB3CHY.js} +2 -2
  161. package/dist/cli/chunks/{fast-paths-MYZ6GITZ.js → fast-paths-M2ENEKQX.js} +2 -2
  162. package/dist/cli/chunks/{feature-flags-6ALWBTHS.js → feature-flags-3WIZC67K.js} +2 -2
  163. package/dist/cli/chunks/{feature-flags-2WVV66AO.js → feature-flags-CZQXGFGX.js} +2 -2
  164. package/dist/cli/chunks/{file-discovery-FOYCPGD6.js → file-discovery-ERTPM3C4.js} +2 -2
  165. package/dist/cli/chunks/{fleet-JROEDHAT.js → fleet-WBEPTBQR.js} +3 -3
  166. package/dist/cli/chunks/{gnn-wrapper-KAXTFFEE.js → gnn-wrapper-GVRS33BK.js} +2 -2
  167. package/dist/cli/chunks/{heartbeat-handler-PG24CBMQ.js → heartbeat-handler-JQ6NSC6T.js} +4 -4
  168. package/dist/cli/chunks/{heartbeat-scheduler-LSS3RD6E.js → heartbeat-scheduler-7XHIE6IV.js} +2 -2
  169. package/dist/cli/chunks/hnsw-adapter-L7QOLNKP.js +2 -0
  170. package/dist/cli/chunks/hnsw-index-O2YO7WVU.js +2 -0
  171. package/dist/cli/chunks/{hnsw-legacy-bridge-HYH4AJAO.js → hnsw-legacy-bridge-TYO6GZ6Z.js} +2 -2
  172. package/dist/cli/chunks/hnswlib-node-UHEP6UZZ.js +2 -0
  173. package/dist/cli/chunks/{hooks-RDZSAFQG.js → hooks-2GU7LGNL.js} +58 -47
  174. package/dist/cli/chunks/{hybrid-router-HNPS6EFL.js → hybrid-router-Z5V4E5SJ.js} +2 -2
  175. package/dist/cli/chunks/{hypergraph-engine-JUFXRXCC.js → hypergraph-engine-F435AM7S.js} +2 -2
  176. package/dist/cli/chunks/{hypergraph-handler-YFRF53TF.js → hypergraph-handler-DQMYDUQY.js} +3 -3
  177. package/dist/cli/chunks/impact-analyzer-37TDXM6V.js +2 -0
  178. package/dist/cli/chunks/{init-handler-P4W5F57S.js → init-handler-Y4NPRT2W.js} +6 -6
  179. package/dist/cli/chunks/init-wizard-ONNAHU4H.js +2 -0
  180. package/dist/cli/chunks/kernel-3S7RJ7PT.js +2 -0
  181. package/dist/cli/chunks/{kilocode-installer-5VWY4DMH.js → kilocode-installer-EUTWNH4I.js} +2 -2
  182. package/dist/cli/chunks/{kiro-installer-PZC3BQII.js → kiro-installer-I3ECJ37F.js} +2 -2
  183. package/dist/cli/chunks/knowledge-graph-GNJMYFT2.js +2 -0
  184. package/dist/cli/chunks/{learning-4OH4ZG25.js → learning-5FW7N6DA.js} +3 -3
  185. package/dist/cli/chunks/{llm-router-LZBR6SZQ.js → llm-router-ZRYFNNPU.js} +4 -4
  186. package/dist/cli/chunks/{load-SPWP6VB3.js → load-7BF33NMJ.js} +2 -2
  187. package/dist/cli/chunks/load-test-ZHTSLJMB.js +2 -0
  188. package/dist/cli/chunks/{mcp-QYPQMM7L.js → mcp-7K6P7FMG.js} +2 -2
  189. package/dist/cli/chunks/{memory-54ILJMWQ.js → memory-O2DCN3GS.js} +5 -5
  190. package/dist/cli/chunks/memory-backend-LN6NWT4F.js +2 -0
  191. package/dist/cli/chunks/{memory-handlers-YK7H5UCX.js → memory-handlers-WA63DMQ4.js} +2 -2
  192. package/dist/cli/chunks/{multi-model-executor-XAOAVPPI.js → multi-model-executor-SJXBFOK5.js} +2 -2
  193. package/dist/cli/chunks/{opencode-installer-CNS4XMUF.js → opencode-installer-PE7ZV6SV.js} +2 -2
  194. package/dist/cli/chunks/{orchestrator-SSEMSKUI.js → orchestrator-N4GT5IGY.js} +5 -5
  195. package/dist/cli/chunks/{pipeline-DS3AENTB.js → pipeline-DUTGGNO6.js} +2 -2
  196. package/dist/cli/chunks/{platform-BL6LH5NF.js → platform-EGUD7X2R.js} +2 -2
  197. package/dist/cli/chunks/{plugin-FNXPEQ2C.js → plugin-6ZS3HK43.js} +2 -2
  198. package/dist/cli/chunks/{prime-radiant-advanced-wasm-E6S6BGNA.js → prime-radiant-advanced-wasm-B5S4RUJS.js} +2 -2
  199. package/dist/cli/chunks/protocol-executor-ED36SYE4.js +2 -0
  200. package/dist/cli/chunks/{protocol-handler-D4WIUU3W.js → protocol-handler-Z3QDY7O6.js} +2 -2
  201. package/dist/cli/chunks/{prove-OLB3PKW6.js → prove-TQHP2XVD.js} +2 -2
  202. package/dist/cli/chunks/{provider-manager-GKTQ75DT.js → provider-manager-2JFXKYMZ.js} +3 -3
  203. package/dist/cli/chunks/qe-reasoning-bank-AC5ZWDAZ.js +2 -0
  204. package/dist/cli/chunks/{quality-ZYJVYTUL.js → quality-NXDHVPAS.js} +2 -2
  205. package/dist/cli/chunks/queen-coordinator-IZ4RQGKV.js +2 -0
  206. package/dist/cli/chunks/{real-embeddings-SKJRHLCS.js → real-embeddings-P2LYDBVF.js} +2 -2
  207. package/dist/cli/chunks/{roocode-installer-WZGKOLWE.js → roocode-installer-YSRXO4W4.js} +2 -2
  208. package/dist/cli/chunks/router-DZVPCD7E.js +2 -0
  209. package/dist/cli/chunks/routing-feedback-3LUE56G4.js +2 -0
  210. package/dist/cli/chunks/{routing-handler-4GIMINCI.js → routing-handler-HVDQQF34.js} +2 -2
  211. package/dist/cli/chunks/{ruvector-commands-YZONXZ2W.js → ruvector-commands-5NJ5FQ3E.js} +2 -2
  212. package/dist/cli/chunks/{rvf-dual-writer-WSS5GF54.js → rvf-dual-writer-GZ2HIIKX.js} +2 -2
  213. package/dist/cli/chunks/{rvf-migration-adapter-WS4HHVEU.js → rvf-migration-adapter-QKEYGJFL.js} +2 -2
  214. package/dist/cli/chunks/{rvf-migration-coordinator-6BY5GI47.js → rvf-migration-coordinator-5RBME46Y.js} +2 -2
  215. package/dist/cli/chunks/rvf-native-adapter-UTX4WYSI.js +2 -0
  216. package/dist/cli/chunks/safe-db-PEJN42TX.js +2 -0
  217. package/dist/cli/chunks/schedule-UULIQP2J.js +2 -0
  218. package/dist/cli/chunks/scheduler-T57XAXKF.js +2 -0
  219. package/dist/cli/chunks/{security-HCNOL2K3.js → security-KB4TOOFJ.js} +3 -3
  220. package/dist/cli/chunks/shared-rvf-adapter-UZVFV2RJ.js +2 -0
  221. package/dist/cli/chunks/{shared-rvf-dual-writer-QRNLSDS7.js → shared-rvf-dual-writer-UMDFMGVS.js} +2 -2
  222. package/dist/cli/chunks/sqlite-persistence-W7E26KF3.js +2 -0
  223. package/dist/cli/chunks/{status-handler-QXZ442MY.js → status-handler-T53CO6SX.js} +2 -2
  224. package/dist/cli/chunks/{structural-health-OFYZ3Z4A.js → structural-health-AVS2GE7S.js} +2 -2
  225. package/dist/cli/chunks/{sync-J4BG65NF.js → sync-Q3UHMELK.js} +2 -2
  226. package/dist/cli/chunks/{task-handler-UBSFCKK3.js → task-handler-UAJWNRMS.js} +2 -2
  227. package/dist/cli/chunks/task-handlers-HYSHMTJN.js +9 -0
  228. package/dist/cli/chunks/{test-WTNAHJHH.js → test-GMXM664Y.js} +4 -4
  229. package/dist/cli/chunks/{test-scheduling-QREBYRGW.js → test-scheduling-PYU4NLDU.js} +3 -3
  230. package/dist/cli/chunks/{token-bootstrap-HE5H77OL.js → token-bootstrap-5SIETJI6.js} +2 -2
  231. package/dist/cli/chunks/{token-usage-V5B6K3JL.js → token-usage-3H4KEKTT.js} +2 -2
  232. package/dist/cli/chunks/{hnswlib-node-WTTST5LC.js → transformers-ZFPUASV4.js} +2 -2
  233. package/dist/cli/chunks/{tree-sitter-wasm-parser-WP2SF2M5.js → tree-sitter-wasm-parser-X72YXRIP.js} +2 -2
  234. package/dist/cli/chunks/{types-7ZBTAO5Z.js → types-CB2HAVZ6.js} +2 -2
  235. package/dist/cli/chunks/unified-memory-SAIRUPOI.js +2 -0
  236. package/dist/cli/chunks/unified-memory-hnsw-NQALAER6.js +2 -0
  237. package/dist/cli/chunks/unified-persistence-XNGQFWFS.js +2 -0
  238. package/dist/cli/chunks/{upgrade-WIFAJDBG.js → upgrade-BWAZTJKE.js} +2 -2
  239. package/dist/cli/chunks/{validate-W63V36GA.js → validate-3OVVTWN6.js} +2 -2
  240. package/dist/cli/chunks/{validate-swarm-CK5BM3YY.js → validate-swarm-WJVG4OUQ.js} +2 -2
  241. package/dist/cli/chunks/{vibium-MJCCO36E.js → vibium-IIU2F5HC.js} +2 -2
  242. package/dist/cli/chunks/visual-security-CE37LMFR.js +2 -0
  243. package/dist/cli/chunks/{web-tree-sitter-ESERXLPK.js → web-tree-sitter-RO4TKGTV.js} +2 -2
  244. package/dist/cli/chunks/{windsurf-installer-FDWQ5BWI.js → windsurf-installer-7N5CZTJS.js} +2 -2
  245. package/dist/cli/chunks/{witness-chain-L5KSYE2S.js → witness-chain-B4CHDDS5.js} +2 -2
  246. package/dist/cli/chunks/witness-chain-L2KM336B.js +2 -0
  247. package/dist/cli/chunks/{workflow-34GYJDFW.js → workflow-FKJKW36Z.js} +4 -4
  248. package/dist/cli/chunks/workflow-orchestrator-BE5PCEBO.js +2 -0
  249. package/dist/cli/chunks/{wrappers-VGKEBQLW.js → wrappers-HU3SB4FT.js} +2 -2
  250. package/dist/cli/commands/hooks-handlers/hooks-dream-learning.js +54 -0
  251. package/dist/cli/commands/init.js +3 -1
  252. package/dist/coordination/consensus/providers/claude-provider.js +1 -1
  253. package/dist/domains/code-intelligence/coordinator.js +20 -0
  254. package/dist/integrations/agentic-flow/reasoning-bank/experience-replay.js +82 -0
  255. package/dist/integrations/embeddings/index/HNSWIndex.js +16 -6
  256. package/dist/integrations/ruvector/hypergraph-engine.d.ts +45 -0
  257. package/dist/integrations/ruvector/hypergraph-engine.js +102 -0
  258. package/dist/integrations/ruvector/shared-rvf-adapter.js +110 -2
  259. package/dist/learning/dream/dream-engine.js +8 -0
  260. package/dist/learning/pattern-store.js +38 -1
  261. package/dist/mcp/bundle.js +361 -344
  262. package/dist/mcp/entry.js +15 -0
  263. package/dist/mcp/handlers/core-handlers.js +2 -2
  264. package/dist/mcp/handlers/task-handlers.js +45 -0
  265. package/dist/mcp/handlers/trajectory-judge.d.ts +13 -0
  266. package/dist/mcp/handlers/trajectory-judge.js +100 -0
  267. package/dist/shared/llm/providers/claude.js +1 -1
  268. package/package.json +2 -2
  269. package/scripts/preinstall.cjs +54 -0
  270. package/dist/cli/chunks/adapter-5NI3IO42.js +0 -2
  271. package/dist/cli/chunks/aqe-learning-engine-JOUK5HMO.js +0 -2
  272. package/dist/cli/chunks/base-DCAB7AHK.js +0 -2
  273. package/dist/cli/chunks/browser-workflow-A4UV73SZ.js +0 -2
  274. package/dist/cli/chunks/chunk-2WM4NYM5.js +0 -2
  275. package/dist/cli/chunks/chunk-D2EHD2KF.js +0 -2
  276. package/dist/cli/chunks/chunk-VPDZTMMB.js +0 -24
  277. package/dist/cli/chunks/chunk-Z2E5DTKX.js +0 -2
  278. package/dist/cli/chunks/client-UTNF2C5K.js +0 -2
  279. package/dist/cli/chunks/cross-domain-router-FCM34JOR.js +0 -2
  280. package/dist/cli/chunks/dream-6KCS7EWS.js +0 -2
  281. package/dist/cli/chunks/hnsw-adapter-PG6O67CQ.js +0 -2
  282. package/dist/cli/chunks/hnsw-index-AHYZHLNZ.js +0 -2
  283. package/dist/cli/chunks/impact-analyzer-USAJVJY5.js +0 -2
  284. package/dist/cli/chunks/init-wizard-GL7LAZID.js +0 -2
  285. package/dist/cli/chunks/kernel-2YAIESTR.js +0 -2
  286. package/dist/cli/chunks/knowledge-graph-QSIYZRAG.js +0 -2
  287. package/dist/cli/chunks/load-test-UEHSHLVN.js +0 -2
  288. package/dist/cli/chunks/memory-backend-4NE4ADPG.js +0 -2
  289. package/dist/cli/chunks/protocol-executor-YI4HNXND.js +0 -2
  290. package/dist/cli/chunks/qe-reasoning-bank-ANBAXQXC.js +0 -2
  291. package/dist/cli/chunks/queen-coordinator-MYYUSWVX.js +0 -2
  292. package/dist/cli/chunks/router-RYCLZ7A4.js +0 -2
  293. package/dist/cli/chunks/routing-feedback-5KSRG2UI.js +0 -2
  294. package/dist/cli/chunks/rvf-native-adapter-NEIOLJRF.js +0 -2
  295. package/dist/cli/chunks/safe-db-3JQP4EPU.js +0 -2
  296. package/dist/cli/chunks/schedule-2QKCL64E.js +0 -2
  297. package/dist/cli/chunks/scheduler-FMOP45FC.js +0 -2
  298. package/dist/cli/chunks/shared-rvf-adapter-BMFIVWMJ.js +0 -2
  299. package/dist/cli/chunks/sqlite-persistence-I5RYLFOE.js +0 -2
  300. package/dist/cli/chunks/task-handlers-JFUT2FQ7.js +0 -2
  301. package/dist/cli/chunks/transformers-HIVMQP4O.js +0 -2
  302. package/dist/cli/chunks/unified-memory-2ETCY22B.js +0 -2
  303. package/dist/cli/chunks/unified-memory-hnsw-OALJW537.js +0 -2
  304. package/dist/cli/chunks/unified-persistence-SQMP7A3O.js +0 -2
  305. package/dist/cli/chunks/visual-security-JUJPF2QO.js +0 -2
  306. package/dist/cli/chunks/witness-chain-QJVKAAZT.js +0 -2
  307. package/dist/cli/chunks/workflow-orchestrator-WXB2RVVW.js +0 -2
@@ -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.9.19");process.exit(0)}
2
- import{a as N,d as P}from"./chunk-SKNHAGYP.js";import{b,e as k}from"./chunk-WZUQT2BE.js";import{a as p,d as F}from"./chunk-IV74GAZN.js";import{a as T,c as E}from"./chunk-XF32XZMY.js";import{a as H,b as O}from"./chunk-YXLQJ226.js";import{c as z,g as S}from"./chunk-WULMXLNN.js";function x(l){let e=0;for(let t=0;t<l.length;t++)e+=l[t]*l[t];return Math.sqrt(e)}function C(l,e,t,s){let n=t*s;if(n===0)return 0;let o=0;for(let r=0;r<l.length;r++)o+=l[r]*e[r];return o/n}function U(l={}){let{name:e="default",...t}=l;return new M(e,t)}var f,w,v,I,A,M,D=z(()=>{F();P();k();E();f=null,w=null;try{let l=(O(),S(H));f=l.differentiableSearch,w=l.init}catch{}v=class{data=[];compareFn;constructor(e){this.compareFn=e}push(e){this.data.push(e),this.bubbleUp(this.data.length-1)}pop(){if(this.data.length===0)return;let e=this.data[0],t=this.data.pop();return this.data.length>0&&(this.data[0]=t,this.sinkDown(0)),e}peek(){return this.data[0]}size(){return this.data.length}bubbleUp(e){for(;e>0;){let t=e-1>>1;if(this.compareFn(this.data[e],this.data[t])<0)[this.data[e],this.data[t]]=[this.data[t],this.data[e]],e=t;else break}}sinkDown(e){let t=this.data.length;for(;;){let s=e,n=2*e+1,o=2*e+2;if(n<t&&this.compareFn(this.data[n],this.data[s])<0&&(s=n),o<t&&this.compareFn(this.data[o],this.data[s])<0&&(s=o),s!==e)[this.data[e],this.data[s]]=[this.data[s],this.data[e]],e=s;else break}}},I=class{nodes=new Map;M=b.M_CONNECTIONS;Mmax0=b.M_CONNECTIONS*2;efConstruction=b.EF_CONSTRUCTION;efSearch=b.EF_SEARCH;mL=1/Math.log(b.M_CONNECTIONS);maxLevel=16;entryPoint=null;currentMaxLevel=-1;randomLevel(){return Math.min(Math.floor(-Math.log(N())*this.mL),this.maxLevel)}similarity(e,t){let s=this.nodes.get(t);return s?p(e,s.embedding):-1}searchLayer(e,t,s){let n=t,o=this.similarity(e,n),r=!0;for(;r;){r=!1;let a=this.nodes.get(n);if(!a)break;let h=a.neighbors.get(s)??[];for(let d of h){if(!this.nodes.has(d))continue;let i=this.similarity(e,d);i>o&&(n=d,o=i,r=!0)}}return n}searchLayerBeam(e,t,s,n){let o=new Set(t),r=t.filter(i=>this.nodes.has(i)).map(i=>({id:i,score:this.similarity(e,i)})),a=new v((i,c)=>c.score-i.score),h=new v((i,c)=>i.score-c.score);for(let i of r)a.push(i),h.push(i);for(;a.size()>0;){let i=a.pop();if(h.size()>=n&&i.score<h.peek().score)break;let c=this.nodes.get(i.id);if(!c)continue;let u=c.neighbors.get(s)??[];for(let m of u){if(o.has(m)||(o.add(m),!this.nodes.has(m)))continue;let g=this.similarity(e,m),y=h.size()>=n?h.peek().score:-1/0;if(h.size()<n||g>y){let L={id:m,score:g};a.push(L),h.push(L),h.size()>n&&h.pop()}}}let d=[];for(;h.size()>0;)d.push(h.pop());return d.reverse(),d}selectNeighbors(e,t,s){return t.sort((n,o)=>o.score-n.score).slice(0,s).map(n=>n.id)}getMaxConnections(e){return e===0?this.Mmax0:this.M}add(e,t){this.nodes.has(e)&&this.remove(e);let s=this.randomLevel(),n={id:e,embedding:t,neighbors:new Map};for(let r=0;r<=s;r++)n.neighbors.set(r,[]);if(this.nodes.set(e,n),this.entryPoint===null){this.entryPoint=e,this.currentMaxLevel=s;return}let o=this.entryPoint;for(let r=this.currentMaxLevel;r>s;r--)o=this.searchLayer(t,o,r);for(let r=Math.min(s,this.currentMaxLevel);r>=0;r--){let a=this.getMaxConnections(r),h=this.searchLayerBeam(t,[o],r,this.efConstruction),d=this.selectNeighbors(t,h,a);n.neighbors.set(r,[...d]);for(let i of d){let c=this.nodes.get(i);if(!c)continue;let u=c.neighbors.get(r)??[];if(u.push(e),u.length>a){let m=u.filter(g=>this.nodes.has(g)).map(g=>({id:g,score:p(c.embedding,this.nodes.get(g).embedding)}));m.sort((g,y)=>y.score-g.score),c.neighbors.set(r,m.slice(0,a).map(g=>g.id))}else c.neighbors.set(r,u)}h.length>0&&(o=h[0].id)}s>this.currentMaxLevel&&(this.entryPoint=e,this.currentMaxLevel=s)}remove(e){let t=this.nodes.get(e);if(!t)return!1;for(let[s,n]of t.neighbors.entries())for(let o of n){let r=this.nodes.get(o);if(!r)continue;let a=r.neighbors.get(s);if(!a)continue;let h=a.indexOf(e);h!==-1&&a.splice(h,1);let d=this.getMaxConnections(s);if(a.length<d){for(let i of n)if(i!==o&&i!==e&&this.nodes.has(i)&&!a.includes(i)){a.push(i);let c=this.nodes.get(i);if(c){let u=c.neighbors.get(s)??[];!u.includes(o)&&u.length<d&&(u.push(o),c.neighbors.set(s,u))}if(a.length>=d)break}}r.neighbors.set(s,a)}if(this.nodes.delete(e),this.entryPoint===e)if(this.nodes.size===0)this.entryPoint=null,this.currentMaxLevel=-1;else{let s=null,n=-1;for(let[o,r]of this.nodes.entries()){let a=-1;for(let h of r.neighbors.keys())h>a&&(a=h);a>n&&(n=a,s=o)}this.entryPoint=s,this.currentMaxLevel=n}return!0}search(e,t){if(this.nodes.size===0||this.entryPoint===null)return[];if(this.nodes.size===1){let r=this.nodes.get(this.entryPoint);return[{id:r.id,score:p(e,r.embedding)}]}let s=this.entryPoint;for(let r=this.currentMaxLevel;r>0;r--)s=this.searchLayer(e,s,r);let n=Math.max(this.efSearch,t);return this.searchLayerBeam(e,[s],0,n).slice(0,t)}size(){return this.nodes.size}clear(){this.nodes.clear(),this.entryPoint=null,this.currentMaxLevel=-1}};A=class{ids=[];vectors=[];norms=[];idToIndex=new Map;initialized=!1;constructor(){if(w&&!this.initialized)try{w(),this.initialized=!0}catch{this.initialized=f!==null}}add(e,t){let s=new Float32Array(t),n=x(s);if(this.idToIndex.has(e)){let r=this.idToIndex.get(e);this.vectors[r]=s,this.norms[r]=n;return}let o=this.ids.length;this.ids.push(e),this.vectors.push(s),this.norms.push(n),this.idToIndex.set(e,o)}search(e,t){if(this.ids.length===0)return[];let s=Math.min(t,this.ids.length),n=this.vectors.length>0?this.vectors[0].length:0,o=e.length,r=n===o;if(f&&this.vectors.length>0&&r){let i=new Float32Array(e),c=x(i);return f(i,this.vectors,s,1).indices.map(m=>({id:this.ids[m],score:C(i,this.vectors[m],c,this.norms[m])}))}let a=new Float32Array(e),h=x(a),d=[];for(let i=0;i<this.ids.length;i++){let c=this.vectors[i];if(c.length!==a.length){i===0&&console.warn(`[RuvectorFlatIndex] Dimension mismatch: query=${a.length}, stored=${c.length}. Skipping ${this.ids.length} mismatched vectors. Re-index with correct dimensions.`);continue}else d.push({id:this.ids[i],score:C(a,c,h,this.norms[i])})}return d.sort((i,c)=>c.score-i.score),d.slice(0,s)}remove(e){let t=this.idToIndex.get(e);if(t===void 0)return!1;let s=this.ids.length-1;if(t!==s){let n=this.ids[s];this.ids[t]=n,this.vectors[t]=this.vectors[s],this.norms[t]=this.norms[s],this.idToIndex.set(n,t)}return this.ids.pop(),this.vectors.pop(),this.norms.pop(),this.idToIndex.delete(e),!0}clear(){this.ids=[],this.vectors=[],this.norms=[],this.idToIndex.clear()}size(){return this.ids.length}},M=class{adapter;constructor(e,t){this.adapter=T.create(e,t)}add(e,t){this.adapter.addByStringId(e,t)}search(e,t){return this.adapter.searchByArray(e,t)}remove(e){return this.adapter.removeByStringId(e)}clear(){this.adapter.clear()}size(){return this.adapter.size()}recall(){return this.adapter.recall()}getProvider(){return this.adapter}}});export{v as a,I as b,A as c,M as d,U as e,D as f};
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.9.21");process.exit(0)}
2
+ import{a as N,d as P}from"./chunk-5EYQP3V3.js";import{b,e as k}from"./chunk-63PHZGO2.js";import{a as p,d as F}from"./chunk-ZUTYZIWQ.js";import{a as T,c as E}from"./chunk-KYPN6G7T.js";import{a as H,b as O}from"./chunk-NJICCYCB.js";import{c as z,g as S}from"./chunk-4ZUXTOUG.js";function x(l){let e=0;for(let t=0;t<l.length;t++)e+=l[t]*l[t];return Math.sqrt(e)}function C(l,e,t,s){let n=t*s;if(n===0)return 0;let o=0;for(let r=0;r<l.length;r++)o+=l[r]*e[r];return o/n}function U(l={}){let{name:e="default",...t}=l;return new M(e,t)}var f,w,v,I,A,M,D=z(()=>{F();P();k();E();f=null,w=null;try{let l=(O(),S(H));f=l.differentiableSearch,w=l.init}catch{}v=class{data=[];compareFn;constructor(e){this.compareFn=e}push(e){this.data.push(e),this.bubbleUp(this.data.length-1)}pop(){if(this.data.length===0)return;let e=this.data[0],t=this.data.pop();return this.data.length>0&&(this.data[0]=t,this.sinkDown(0)),e}peek(){return this.data[0]}size(){return this.data.length}bubbleUp(e){for(;e>0;){let t=e-1>>1;if(this.compareFn(this.data[e],this.data[t])<0)[this.data[e],this.data[t]]=[this.data[t],this.data[e]],e=t;else break}}sinkDown(e){let t=this.data.length;for(;;){let s=e,n=2*e+1,o=2*e+2;if(n<t&&this.compareFn(this.data[n],this.data[s])<0&&(s=n),o<t&&this.compareFn(this.data[o],this.data[s])<0&&(s=o),s!==e)[this.data[e],this.data[s]]=[this.data[s],this.data[e]],e=s;else break}}},I=class{nodes=new Map;M=b.M_CONNECTIONS;Mmax0=b.M_CONNECTIONS*2;efConstruction=b.EF_CONSTRUCTION;efSearch=b.EF_SEARCH;mL=1/Math.log(b.M_CONNECTIONS);maxLevel=16;entryPoint=null;currentMaxLevel=-1;randomLevel(){return Math.min(Math.floor(-Math.log(N())*this.mL),this.maxLevel)}similarity(e,t){let s=this.nodes.get(t);return s?p(e,s.embedding):-1}searchLayer(e,t,s){let n=t,o=this.similarity(e,n),r=!0;for(;r;){r=!1;let a=this.nodes.get(n);if(!a)break;let h=a.neighbors.get(s)??[];for(let d of h){if(!this.nodes.has(d))continue;let i=this.similarity(e,d);i>o&&(n=d,o=i,r=!0)}}return n}searchLayerBeam(e,t,s,n){let o=new Set(t),r=t.filter(i=>this.nodes.has(i)).map(i=>({id:i,score:this.similarity(e,i)})),a=new v((i,c)=>c.score-i.score),h=new v((i,c)=>i.score-c.score);for(let i of r)a.push(i),h.push(i);for(;a.size()>0;){let i=a.pop();if(h.size()>=n&&i.score<h.peek().score)break;let c=this.nodes.get(i.id);if(!c)continue;let u=c.neighbors.get(s)??[];for(let m of u){if(o.has(m)||(o.add(m),!this.nodes.has(m)))continue;let g=this.similarity(e,m),y=h.size()>=n?h.peek().score:-1/0;if(h.size()<n||g>y){let L={id:m,score:g};a.push(L),h.push(L),h.size()>n&&h.pop()}}}let d=[];for(;h.size()>0;)d.push(h.pop());return d.reverse(),d}selectNeighbors(e,t,s){return t.sort((n,o)=>o.score-n.score).slice(0,s).map(n=>n.id)}getMaxConnections(e){return e===0?this.Mmax0:this.M}add(e,t){this.nodes.has(e)&&this.remove(e);let s=this.randomLevel(),n={id:e,embedding:t,neighbors:new Map};for(let r=0;r<=s;r++)n.neighbors.set(r,[]);if(this.nodes.set(e,n),this.entryPoint===null){this.entryPoint=e,this.currentMaxLevel=s;return}let o=this.entryPoint;for(let r=this.currentMaxLevel;r>s;r--)o=this.searchLayer(t,o,r);for(let r=Math.min(s,this.currentMaxLevel);r>=0;r--){let a=this.getMaxConnections(r),h=this.searchLayerBeam(t,[o],r,this.efConstruction),d=this.selectNeighbors(t,h,a);n.neighbors.set(r,[...d]);for(let i of d){let c=this.nodes.get(i);if(!c)continue;let u=c.neighbors.get(r)??[];if(u.push(e),u.length>a){let m=u.filter(g=>this.nodes.has(g)).map(g=>({id:g,score:p(c.embedding,this.nodes.get(g).embedding)}));m.sort((g,y)=>y.score-g.score),c.neighbors.set(r,m.slice(0,a).map(g=>g.id))}else c.neighbors.set(r,u)}h.length>0&&(o=h[0].id)}s>this.currentMaxLevel&&(this.entryPoint=e,this.currentMaxLevel=s)}remove(e){let t=this.nodes.get(e);if(!t)return!1;for(let[s,n]of t.neighbors.entries())for(let o of n){let r=this.nodes.get(o);if(!r)continue;let a=r.neighbors.get(s);if(!a)continue;let h=a.indexOf(e);h!==-1&&a.splice(h,1);let d=this.getMaxConnections(s);if(a.length<d){for(let i of n)if(i!==o&&i!==e&&this.nodes.has(i)&&!a.includes(i)){a.push(i);let c=this.nodes.get(i);if(c){let u=c.neighbors.get(s)??[];!u.includes(o)&&u.length<d&&(u.push(o),c.neighbors.set(s,u))}if(a.length>=d)break}}r.neighbors.set(s,a)}if(this.nodes.delete(e),this.entryPoint===e)if(this.nodes.size===0)this.entryPoint=null,this.currentMaxLevel=-1;else{let s=null,n=-1;for(let[o,r]of this.nodes.entries()){let a=-1;for(let h of r.neighbors.keys())h>a&&(a=h);a>n&&(n=a,s=o)}this.entryPoint=s,this.currentMaxLevel=n}return!0}search(e,t){if(this.nodes.size===0||this.entryPoint===null)return[];if(this.nodes.size===1){let r=this.nodes.get(this.entryPoint);return[{id:r.id,score:p(e,r.embedding)}]}let s=this.entryPoint;for(let r=this.currentMaxLevel;r>0;r--)s=this.searchLayer(e,s,r);let n=Math.max(this.efSearch,t);return this.searchLayerBeam(e,[s],0,n).slice(0,t)}size(){return this.nodes.size}clear(){this.nodes.clear(),this.entryPoint=null,this.currentMaxLevel=-1}};A=class{ids=[];vectors=[];norms=[];idToIndex=new Map;initialized=!1;constructor(){if(w&&!this.initialized)try{w(),this.initialized=!0}catch{this.initialized=f!==null}}add(e,t){let s=new Float32Array(t),n=x(s);if(this.idToIndex.has(e)){let r=this.idToIndex.get(e);this.vectors[r]=s,this.norms[r]=n;return}let o=this.ids.length;this.ids.push(e),this.vectors.push(s),this.norms.push(n),this.idToIndex.set(e,o)}search(e,t){if(this.ids.length===0)return[];let s=Math.min(t,this.ids.length),n=this.vectors.length>0?this.vectors[0].length:0,o=e.length,r=n===o;if(f&&this.vectors.length>0&&r){let i=new Float32Array(e),c=x(i);return f(i,this.vectors,s,1).indices.map(m=>({id:this.ids[m],score:C(i,this.vectors[m],c,this.norms[m])}))}let a=new Float32Array(e),h=x(a),d=[];for(let i=0;i<this.ids.length;i++){let c=this.vectors[i];if(c.length!==a.length){i===0&&console.warn(`[RuvectorFlatIndex] Dimension mismatch: query=${a.length}, stored=${c.length}. Skipping ${this.ids.length} mismatched vectors. Re-index with correct dimensions.`);continue}else d.push({id:this.ids[i],score:C(a,c,h,this.norms[i])})}return d.sort((i,c)=>c.score-i.score),d.slice(0,s)}remove(e){let t=this.idToIndex.get(e);if(t===void 0)return!1;let s=this.ids.length-1;if(t!==s){let n=this.ids[s];this.ids[t]=n,this.vectors[t]=this.vectors[s],this.norms[t]=this.norms[s],this.idToIndex.set(n,t)}return this.ids.pop(),this.vectors.pop(),this.norms.pop(),this.idToIndex.delete(e),!0}clear(){this.ids=[],this.vectors=[],this.norms=[],this.idToIndex.clear()}size(){return this.ids.length}},M=class{adapter;constructor(e,t){this.adapter=T.create(e,t)}add(e,t){this.adapter.addByStringId(e,t)}search(e,t){return this.adapter.searchByArray(e,t)}remove(e){return this.adapter.removeByStringId(e)}clear(){this.adapter.clear()}size(){return this.adapter.size()}recall(){return this.adapter.recall()}getProvider(){return this.adapter}}});export{v as a,I as b,A as c,M as d,U as e,D as f};
@@ -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.9.19");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.9.21");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.9.19");process.exit(0)}
2
- import{c as D}from"./chunk-D74RGYKI.js";import{a as _}from"./chunk-IPLQPBJA.js";import{k as w,o as U}from"./chunk-TXCOK5DC.js";import{b as f,d as q}from"./chunk-5R2DUR3A.js";import{a as g,c as P}from"./chunk-5MGRZ4YD.js";import{a as v}from"./chunk-WULMXLNN.js";import{randomUUID as L}from"crypto";U();q();P();var x={alpha:.1,minOutcomes:10,weightFloor:.2,weightCeiling:2},p=class{records=new Map;config;constructor(e){this.config={...x,...e}}recordOutcome(e,t,o){let{alpha:i,minOutcomes:r,weightFloor:s,weightCeiling:n}=this.config,c=this.records.get(e),d=t?1:0,a=Math.max(0,Math.min(1,o)),l,u;c?(l=i*d+(1-i)*c.emaAccuracy,u=i*a+(1-i)*c.emaQuality):(l=d,u=a);let h=(c?.totalOutcomes??0)+1,R;h>=r?R=Math.max(s,Math.min(n,l*2)):R=1;let k={agentId:e,emaAccuracy:l,emaQuality:u,calibratedWeight:R,totalOutcomes:h,lastUpdated:new Date};return this.records.set(e,k),k}getCalibration(e){return this.records.get(e)??null}getCalibratedWeight(e){let t=this.records.get(e);return!t||t.totalOutcomes<this.config.minOutcomes?1:t.calibratedWeight}getAllCalibrations(){return Array.from(this.records.values())}reset(e){e!==void 0?this.records.delete(e):this.records.clear()}serialize(){let e={};for(let[t,o]of this.records)e[t]={...o};return e}deserialize(e){this.records.clear();for(let[t,o]of Object.entries(e))this.records.set(t,{...o,lastUpdated:new Date(o.lastUpdated)})}};var F={escalateAfterFailures:2,deEscalateAfterSuccesses:5,maxTier:"opus",minTier:"haiku"},A=["booster","haiku","sonnet","opus"];function y(m){return A.indexOf(m)}var b=class{config;states=new Map;constructor(e){this.config={...F,...e}}recordOutcome(e,t,o){let i=this.states.get(e);i||(i={agentId:e,currentTier:o,baseTier:o,consecutiveFailures:0,consecutiveSuccesses:0,escalationCount:0,deEscalationCount:0,lastAction:"none",lastActionTimestamp:new Date},this.states.set(e,i));let r=i.currentTier;if(t){if(i.consecutiveSuccesses++,i.consecutiveFailures=0,i.consecutiveSuccesses>=this.config.deEscalateAfterSuccesses){let s=y(i.currentTier),n=y(this.config.minTier);if(s>n)return i.currentTier=A[s-1],i.deEscalationCount++,i.consecutiveSuccesses=0,i.lastAction="de-escalate",i.lastActionTimestamp=new Date,{action:"de-escalate",previousTier:r,newTier:i.currentTier}}}else if(i.consecutiveFailures++,i.consecutiveSuccesses=0,i.consecutiveFailures>=this.config.escalateAfterFailures){let s=y(i.currentTier),n=y(this.config.maxTier);if(s<n)return i.currentTier=A[s+1],i.escalationCount++,i.consecutiveFailures=0,i.lastAction="escalate",i.lastActionTimestamp=new Date,{action:"escalate",previousTier:r,newTier:i.currentTier}}return{action:"none",previousTier:r,newTier:i.currentTier}}getCurrentTier(e){return this.states.get(e)?.currentTier??null}getState(e){return this.states.get(e)??null}getAllStates(){return Array.from(this.states.values())}reset(e){e?this.states.delete(e):this.states.clear()}};var T={booster:{avgInputTokens:0,avgOutputTokens:0,costPerTask:0},haiku:{avgInputTokens:2e3,avgOutputTokens:1e3,costPerTask:.0035},sonnet:{avgInputTokens:2e3,avgOutputTokens:1e3,costPerTask:.021},opus:{avgInputTokens:2e3,avgOutputTokens:1e3,costPerTask:.105}},S=["booster","haiku","sonnet","opus"],E=T.opus.costPerTask,I={qualityWeight:.6,costWeight:.4,budgetPerHourUsd:0,budgetPerDayUsd:0,minQualityThreshold:.5,enabled:!0},N=.15,C=class{config;costTracker;tierQualityEstimates=new Map;tierOutcomeCounts=new Map;constructor(e,t){let o={...I,...t};o.qualityWeight=Math.max(0,Math.min(1,o.qualityWeight)),o.costWeight=Math.max(0,Math.min(1,o.costWeight)),o.minQualityThreshold=Math.max(0,Math.min(1,o.minQualityThreshold)),o.budgetPerHourUsd=Math.max(0,o.budgetPerHourUsd),o.budgetPerDayUsd=Math.max(0,o.budgetPerDayUsd);let i=o.qualityWeight+o.costWeight;i>0&&i!==1&&(o.qualityWeight/=i,o.costWeight/=i),this.config=o,this.costTracker=e,this.tierQualityEstimates.set("booster",.3),this.tierQualityEstimates.set("haiku",.55),this.tierQualityEstimates.set("sonnet",.75),this.tierQualityEstimates.set("opus",.9)}scoreTiers(e){let t=S.map(o=>{let i=this.getQualityEstimate(o,e),r=T[o].costPerTask,s=r>0?i/r:i>0?1/0:0,n=E>0?1-r/E:1,c=this.config.qualityWeight*i+this.config.costWeight*n;return{tier:o,qualityScore:i,estimatedCostUsd:r,qualityPerDollar:s,economicScore:c}});return t.sort((o,i)=>i.economicScore-o.economicScore),t}selectTier(e){let t=this.scoreTiers(e);for(let r of t)if(!(r.qualityScore<this.config.minQualityThreshold)&&!this.wouldExceedBudget(r.tier))return{tier:r.tier,reason:`Best economic score (${r.economicScore.toFixed(3)}): quality=${r.qualityScore.toFixed(2)}, cost=$${r.estimatedCostUsd.toFixed(4)}`,scores:t};let o=t.filter(r=>r.qualityScore>=this.config.minQualityThreshold);if(o.length>0){let r=[...o].sort((s,n)=>s.estimatedCostUsd-n.estimatedCostUsd)[0];return{tier:r.tier,reason:`Budget constrained fallback to ${r.tier}`,scores:t}}let i=[...t].sort((r,s)=>s.qualityScore-r.qualityScore)[0];return{tier:i.tier,reason:`No tier meets quality threshold ${this.config.minQualityThreshold}; using best quality: ${i.tier}`,scores:t}}wouldExceedBudget(e){let t=T[e].costPerTask;if(t===0)return!1;let o=this.costTracker.getCurrentCost("hour"),i=this.costTracker.getCurrentCost("day");return this.config.budgetPerHourUsd>0&&o+t>this.config.budgetPerHourUsd||this.config.budgetPerDayUsd>0&&i+t>this.config.budgetPerDayUsd}updateFromOutcome(e,t){let o=e.outcome.qualityScore,i=this.tierQualityEstimates.get(t)??.5,r=this.tierOutcomeCounts.get(t)??0,s=r<5?.4:N,n=i*(1-s)+o*s;this.tierQualityEstimates.set(t,n),this.tierOutcomeCounts.set(t,r+1)}getEconomicReport(){let e=this.scoreTiers(.5),t=this.costTracker.getCurrentCost("hour"),o=this.costTracker.getCurrentCost("day"),i={hourly:this.config.budgetPerHourUsd>0?Math.max(0,this.config.budgetPerHourUsd-t):null,daily:this.config.budgetPerDayUsd>0?Math.max(0,this.config.budgetPerDayUsd-o):null},r=null,s=[...e].sort((a,l)=>l.qualityPerDollar-a.qualityPerDollar),n=s.find(a=>a.estimatedCostUsd>0&&isFinite(a.qualityPerDollar)),c=[...s].reverse().find(a=>a.estimatedCostUsd>0&&isFinite(a.qualityPerDollar));if(n&&c&&n.tier!==c.tier){let a=c.estimatedCostUsd-n.estimatedCostUsd;a>0&&(r={usd:a,description:`Switch from ${c.tier} ($${c.estimatedCostUsd.toFixed(4)}/task) to ${n.tier} ($${n.estimatedCostUsd.toFixed(4)}/task) for comparable tasks to save ~$${a.toFixed(4)}/task`})}let d=this.generateRecommendation(e,i);return{tierEfficiency:e,currentHourlyCostUsd:t,currentDailyCostUsd:o,budgetRemaining:i,recommendation:d,savingsOpportunity:r}}computeCostAdjustedReward(e,t,o){let i=T[t].costPerTask;if(E===0)return e;let r=i/E,s=Math.max(0,o-this.config.minQualityThreshold),n=r*(1-s),c=e-n*this.config.costWeight;return Math.max(-1,Math.min(1,c))}serializeEstimates(){let e={};for(let t of S)e[t]={quality:this.tierQualityEstimates.get(t)??.5,count:this.tierOutcomeCounts.get(t)??0};return e}deserializeEstimates(e){for(let t of S)e[t]&&(this.tierQualityEstimates.set(t,e[t].quality),this.tierOutcomeCounts.set(t,e[t].count))}getConfig(){return{...this.config}}getQualityEstimate(e,t){let o=this.tierQualityEstimates.get(e)??.5,i=e==="booster"?t*.4:e==="haiku"?t*.2:0;return Math.max(0,Math.min(1,o-i))}generateRecommendation(e,t){if(t.hourly!==null&&t.hourly<.01)return"Hourly budget nearly exhausted. Consider increasing budget or routing to cheaper tiers.";if(t.daily!==null&&t.daily<.1)return"Daily budget nearly exhausted. Only critical tasks should use expensive tiers.";let o=e[0];return o?`Most cost-efficient tier: ${o.tier} (score=${o.economicScore.toFixed(3)}, quality=${o.qualityScore.toFixed(2)})`:"No economic data available yet."}};var O=class{outcomes=[];maxOutcomes;constructor(e=1e4){this.maxOutcomes=e}add(e){this.outcomes.push(e),this.outcomes.length>this.maxOutcomes&&(this.outcomes=this.outcomes.slice(-this.maxOutcomes))}getByAgent(e,t=100){return this.outcomes.filter(o=>o.usedAgent===e).slice(-t)}getAll(e=1e3){return this.outcomes.slice(-e)}getRecentOverrides(e=50){return this.outcomes.filter(t=>!t.followedRecommendation).slice(-e)}clear(){this.outcomes=[]}get size(){return this.outcomes.length}},M=class m{static schemaMigrated=!1;outcomeStore;router=null;db=null;calibrator=null;escalationTracker=null;economicModel=null;economicPersistCounter=0;static ECONOMIC_PERSIST_INTERVAL=10;persistCount=0;maxOutcomes;static RETENTION_CLEANUP_INTERVAL=100;constructor(e=1e4,t){this.maxOutcomes=e,this.outcomeStore=new O(e),t?.enableEMACalibration&&this.enableCalibration(),t?.enableAutoEscalation&&this.enableAutoEscalation()}async initialize(){try{this.db=w(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromDb(),this.loadCalibratorState()}catch(e){console.warn("[RoutingFeedbackCollector] DB init failed, using memory-only:",g(e)),this.db=null}}async loadFromDb(){if(!this.db)return;let t=this.db.getDatabase().prepare(`
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.9.21");process.exit(0)}
2
+ import{c as D}from"./chunk-TOE6DKE4.js";import{a as _}from"./chunk-KWPPF7O4.js";import{k as w,o as U}from"./chunk-5FNEOJSD.js";import{b as f,d as q}from"./chunk-PEOTZFNZ.js";import{a as g,c as P}from"./chunk-SMBQERK7.js";import{a as v}from"./chunk-4ZUXTOUG.js";import{randomUUID as L}from"crypto";U();q();P();var x={alpha:.1,minOutcomes:10,weightFloor:.2,weightCeiling:2},p=class{records=new Map;config;constructor(e){this.config={...x,...e}}recordOutcome(e,t,o){let{alpha:i,minOutcomes:r,weightFloor:s,weightCeiling:n}=this.config,c=this.records.get(e),d=t?1:0,a=Math.max(0,Math.min(1,o)),l,u;c?(l=i*d+(1-i)*c.emaAccuracy,u=i*a+(1-i)*c.emaQuality):(l=d,u=a);let h=(c?.totalOutcomes??0)+1,R;h>=r?R=Math.max(s,Math.min(n,l*2)):R=1;let k={agentId:e,emaAccuracy:l,emaQuality:u,calibratedWeight:R,totalOutcomes:h,lastUpdated:new Date};return this.records.set(e,k),k}getCalibration(e){return this.records.get(e)??null}getCalibratedWeight(e){let t=this.records.get(e);return!t||t.totalOutcomes<this.config.minOutcomes?1:t.calibratedWeight}getAllCalibrations(){return Array.from(this.records.values())}reset(e){e!==void 0?this.records.delete(e):this.records.clear()}serialize(){let e={};for(let[t,o]of this.records)e[t]={...o};return e}deserialize(e){this.records.clear();for(let[t,o]of Object.entries(e))this.records.set(t,{...o,lastUpdated:new Date(o.lastUpdated)})}};var F={escalateAfterFailures:2,deEscalateAfterSuccesses:5,maxTier:"opus",minTier:"haiku"},A=["booster","haiku","sonnet","opus"];function y(m){return A.indexOf(m)}var b=class{config;states=new Map;constructor(e){this.config={...F,...e}}recordOutcome(e,t,o){let i=this.states.get(e);i||(i={agentId:e,currentTier:o,baseTier:o,consecutiveFailures:0,consecutiveSuccesses:0,escalationCount:0,deEscalationCount:0,lastAction:"none",lastActionTimestamp:new Date},this.states.set(e,i));let r=i.currentTier;if(t){if(i.consecutiveSuccesses++,i.consecutiveFailures=0,i.consecutiveSuccesses>=this.config.deEscalateAfterSuccesses){let s=y(i.currentTier),n=y(this.config.minTier);if(s>n)return i.currentTier=A[s-1],i.deEscalationCount++,i.consecutiveSuccesses=0,i.lastAction="de-escalate",i.lastActionTimestamp=new Date,{action:"de-escalate",previousTier:r,newTier:i.currentTier}}}else if(i.consecutiveFailures++,i.consecutiveSuccesses=0,i.consecutiveFailures>=this.config.escalateAfterFailures){let s=y(i.currentTier),n=y(this.config.maxTier);if(s<n)return i.currentTier=A[s+1],i.escalationCount++,i.consecutiveFailures=0,i.lastAction="escalate",i.lastActionTimestamp=new Date,{action:"escalate",previousTier:r,newTier:i.currentTier}}return{action:"none",previousTier:r,newTier:i.currentTier}}getCurrentTier(e){return this.states.get(e)?.currentTier??null}getState(e){return this.states.get(e)??null}getAllStates(){return Array.from(this.states.values())}reset(e){e?this.states.delete(e):this.states.clear()}};var T={booster:{avgInputTokens:0,avgOutputTokens:0,costPerTask:0},haiku:{avgInputTokens:2e3,avgOutputTokens:1e3,costPerTask:.0035},sonnet:{avgInputTokens:2e3,avgOutputTokens:1e3,costPerTask:.021},opus:{avgInputTokens:2e3,avgOutputTokens:1e3,costPerTask:.105}},S=["booster","haiku","sonnet","opus"],E=T.opus.costPerTask,I={qualityWeight:.6,costWeight:.4,budgetPerHourUsd:0,budgetPerDayUsd:0,minQualityThreshold:.5,enabled:!0},N=.15,C=class{config;costTracker;tierQualityEstimates=new Map;tierOutcomeCounts=new Map;constructor(e,t){let o={...I,...t};o.qualityWeight=Math.max(0,Math.min(1,o.qualityWeight)),o.costWeight=Math.max(0,Math.min(1,o.costWeight)),o.minQualityThreshold=Math.max(0,Math.min(1,o.minQualityThreshold)),o.budgetPerHourUsd=Math.max(0,o.budgetPerHourUsd),o.budgetPerDayUsd=Math.max(0,o.budgetPerDayUsd);let i=o.qualityWeight+o.costWeight;i>0&&i!==1&&(o.qualityWeight/=i,o.costWeight/=i),this.config=o,this.costTracker=e,this.tierQualityEstimates.set("booster",.3),this.tierQualityEstimates.set("haiku",.55),this.tierQualityEstimates.set("sonnet",.75),this.tierQualityEstimates.set("opus",.9)}scoreTiers(e){let t=S.map(o=>{let i=this.getQualityEstimate(o,e),r=T[o].costPerTask,s=r>0?i/r:i>0?1/0:0,n=E>0?1-r/E:1,c=this.config.qualityWeight*i+this.config.costWeight*n;return{tier:o,qualityScore:i,estimatedCostUsd:r,qualityPerDollar:s,economicScore:c}});return t.sort((o,i)=>i.economicScore-o.economicScore),t}selectTier(e){let t=this.scoreTiers(e);for(let r of t)if(!(r.qualityScore<this.config.minQualityThreshold)&&!this.wouldExceedBudget(r.tier))return{tier:r.tier,reason:`Best economic score (${r.economicScore.toFixed(3)}): quality=${r.qualityScore.toFixed(2)}, cost=$${r.estimatedCostUsd.toFixed(4)}`,scores:t};let o=t.filter(r=>r.qualityScore>=this.config.minQualityThreshold);if(o.length>0){let r=[...o].sort((s,n)=>s.estimatedCostUsd-n.estimatedCostUsd)[0];return{tier:r.tier,reason:`Budget constrained fallback to ${r.tier}`,scores:t}}let i=[...t].sort((r,s)=>s.qualityScore-r.qualityScore)[0];return{tier:i.tier,reason:`No tier meets quality threshold ${this.config.minQualityThreshold}; using best quality: ${i.tier}`,scores:t}}wouldExceedBudget(e){let t=T[e].costPerTask;if(t===0)return!1;let o=this.costTracker.getCurrentCost("hour"),i=this.costTracker.getCurrentCost("day");return this.config.budgetPerHourUsd>0&&o+t>this.config.budgetPerHourUsd||this.config.budgetPerDayUsd>0&&i+t>this.config.budgetPerDayUsd}updateFromOutcome(e,t){let o=e.outcome.qualityScore,i=this.tierQualityEstimates.get(t)??.5,r=this.tierOutcomeCounts.get(t)??0,s=r<5?.4:N,n=i*(1-s)+o*s;this.tierQualityEstimates.set(t,n),this.tierOutcomeCounts.set(t,r+1)}getEconomicReport(){let e=this.scoreTiers(.5),t=this.costTracker.getCurrentCost("hour"),o=this.costTracker.getCurrentCost("day"),i={hourly:this.config.budgetPerHourUsd>0?Math.max(0,this.config.budgetPerHourUsd-t):null,daily:this.config.budgetPerDayUsd>0?Math.max(0,this.config.budgetPerDayUsd-o):null},r=null,s=[...e].sort((a,l)=>l.qualityPerDollar-a.qualityPerDollar),n=s.find(a=>a.estimatedCostUsd>0&&isFinite(a.qualityPerDollar)),c=[...s].reverse().find(a=>a.estimatedCostUsd>0&&isFinite(a.qualityPerDollar));if(n&&c&&n.tier!==c.tier){let a=c.estimatedCostUsd-n.estimatedCostUsd;a>0&&(r={usd:a,description:`Switch from ${c.tier} ($${c.estimatedCostUsd.toFixed(4)}/task) to ${n.tier} ($${n.estimatedCostUsd.toFixed(4)}/task) for comparable tasks to save ~$${a.toFixed(4)}/task`})}let d=this.generateRecommendation(e,i);return{tierEfficiency:e,currentHourlyCostUsd:t,currentDailyCostUsd:o,budgetRemaining:i,recommendation:d,savingsOpportunity:r}}computeCostAdjustedReward(e,t,o){let i=T[t].costPerTask;if(E===0)return e;let r=i/E,s=Math.max(0,o-this.config.minQualityThreshold),n=r*(1-s),c=e-n*this.config.costWeight;return Math.max(-1,Math.min(1,c))}serializeEstimates(){let e={};for(let t of S)e[t]={quality:this.tierQualityEstimates.get(t)??.5,count:this.tierOutcomeCounts.get(t)??0};return e}deserializeEstimates(e){for(let t of S)e[t]&&(this.tierQualityEstimates.set(t,e[t].quality),this.tierOutcomeCounts.set(t,e[t].count))}getConfig(){return{...this.config}}getQualityEstimate(e,t){let o=this.tierQualityEstimates.get(e)??.5,i=e==="booster"?t*.4:e==="haiku"?t*.2:0;return Math.max(0,Math.min(1,o-i))}generateRecommendation(e,t){if(t.hourly!==null&&t.hourly<.01)return"Hourly budget nearly exhausted. Consider increasing budget or routing to cheaper tiers.";if(t.daily!==null&&t.daily<.1)return"Daily budget nearly exhausted. Only critical tasks should use expensive tiers.";let o=e[0];return o?`Most cost-efficient tier: ${o.tier} (score=${o.economicScore.toFixed(3)}, quality=${o.qualityScore.toFixed(2)})`:"No economic data available yet."}};var O=class{outcomes=[];maxOutcomes;constructor(e=1e4){this.maxOutcomes=e}add(e){this.outcomes.push(e),this.outcomes.length>this.maxOutcomes&&(this.outcomes=this.outcomes.slice(-this.maxOutcomes))}getByAgent(e,t=100){return this.outcomes.filter(o=>o.usedAgent===e).slice(-t)}getAll(e=1e3){return this.outcomes.slice(-e)}getRecentOverrides(e=50){return this.outcomes.filter(t=>!t.followedRecommendation).slice(-e)}clear(){this.outcomes=[]}get size(){return this.outcomes.length}},M=class m{static schemaMigrated=!1;outcomeStore;router=null;db=null;calibrator=null;escalationTracker=null;economicModel=null;economicPersistCounter=0;static ECONOMIC_PERSIST_INTERVAL=10;persistCount=0;maxOutcomes;static RETENTION_CLEANUP_INTERVAL=100;constructor(e=1e4,t){this.maxOutcomes=e,this.outcomeStore=new O(e),t?.enableEMACalibration&&this.enableCalibration(),t?.enableAutoEscalation&&this.enableAutoEscalation()}async initialize(){try{this.db=w(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromDb(),this.loadCalibratorState()}catch(e){console.warn("[RoutingFeedbackCollector] DB init failed, using memory-only:",g(e)),this.db=null}}async loadFromDb(){if(!this.db)return;let t=this.db.getDatabase().prepare(`
3
3
  SELECT * FROM routing_outcomes ORDER BY created_at DESC LIMIT ?
4
4
  `).all(this.maxOutcomes);for(let o of t.reverse()){let i={id:o.id,task:f(o.task_json),decision:f(o.decision_json),usedAgent:o.used_agent,followedRecommendation:!!o.followed_recommendation,outcome:{success:!!o.success,qualityScore:o.quality_score,durationMs:o.duration_ms,error:o.error||void 0},timestamp:new Date(o.created_at),advisorConsultation:o.advisor_consultation_json?f(o.advisor_consultation_json):void 0};this.outcomeStore.add(i)}t.length>0&&console.log(`[RoutingFeedbackCollector] Loaded ${t.length} outcomes from DB`)}persistOutcome(e){if(this.db)try{let t=this.db.getDatabase();if(!m.schemaMigrated){for(let r of["ALTER TABLE routing_outcomes ADD COLUMN model_tier TEXT","ALTER TABLE routing_outcomes ADD COLUMN advisor_consultation_json TEXT"])try{t.prepare(r).run()}catch{}m.schemaMigrated=!0}let o=this.inferTier(e.usedAgent),i=e.advisorConsultation?JSON.stringify(e.advisorConsultation):null;t.prepare(`
5
5
  INSERT OR REPLACE INTO routing_outcomes (
@@ -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.9.19");process.exit(0)}
2
- import{b as c,d as p}from"./chunk-5R2DUR3A.js";import{a as f}from"./chunk-WULMXLNN.js";p();import{existsSync as l,readFileSync as i}from"node:fs";import{join as a}from"node:path";import{execSync as m}from"node:child_process";var s=null,d=0,g=6e4;function S(){s=null,d=0}function b(e){if(s&&Date.now()-d<g)return s;let n=w(e);return s=n,d=Date.now(),n}function w(e){let n=h(e);if(n)return n;let r=v(e);if(r)return r;let t=k(e);return t||{available:!1}}function h(e){let n=a(e,".mcp.json");if(l(n))try{let o=c(i(n,"utf-8"));if(o.mcpServers?.ruflo||o.mcpServers?.["claude-flow"])return{available:!0,method:"mcp-config"}}catch{}let r=a(e,".claude","mcp.json");if(l(r))try{let o=c(i(r,"utf-8"));if(o.mcpServers?.ruflo||o.mcpServers?.["claude-flow"])return{available:!0,method:"mcp-config"}}catch{}let t=a(e,".claude","settings.json");if(l(t))try{let o=c(i(t,"utf-8")),u=o.mcpServers||o.mcp?.servers||{};if(u.ruflo||u["claude-flow"]||u["@anthropic/claude-flow"])return{available:!0,method:"mcp-config"}}catch{}return null}function v(e){let n=a(e,"package.json");if(!l(n))return null;try{let r=c(i(n,"utf-8")),t={...r.dependencies,...r.devDependencies};if(t.ruflo||t["@claude-flow/cli"]||t["claude-flow"])return{available:!0,method:"npm-dependency"}}catch{}return null}function k(e){for(let n of["ruflo","@claude-flow/cli"])try{return{available:!0,method:"npx-cached",version:m(`npx --no-install ${n} --version`,{encoding:"utf-8",timeout:5e3,cwd:e,stdio:["pipe","pipe","pipe"]}).trim().match(/\d+\.\d+\.\d+[\w.-]*/)?.[0]}}catch{}return null}function x(){for(let e of["ruflo","@claude-flow/cli"])try{return f.resolve(`${e}/package.json`),e}catch{}return"ruflo"}function P(){return[" Claude Flow not found \u2014 running in standalone mode.",""," Claude Flow adds optional features:"," - SONA trajectory tracking (reinforcement learning)"," - 3-tier model routing (haiku / sonnet / opus)"," - Codebase pretrain analysis",""," To install later:"," npm install -g ruflo"," claude mcp add ruflo -- npx -y ruflo@3.5.18"," aqe init --auto --with-claude-flow"].join(`
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.9.21");process.exit(0)}
2
+ import{b as c,d as p}from"./chunk-PEOTZFNZ.js";import{a as f}from"./chunk-4ZUXTOUG.js";p();import{existsSync as l,readFileSync as i}from"node:fs";import{join as a}from"node:path";import{execSync as m}from"node:child_process";var s=null,d=0,g=6e4;function S(){s=null,d=0}function b(e){if(s&&Date.now()-d<g)return s;let n=w(e);return s=n,d=Date.now(),n}function w(e){let n=h(e);if(n)return n;let r=v(e);if(r)return r;let t=k(e);return t||{available:!1}}function h(e){let n=a(e,".mcp.json");if(l(n))try{let o=c(i(n,"utf-8"));if(o.mcpServers?.ruflo||o.mcpServers?.["claude-flow"])return{available:!0,method:"mcp-config"}}catch{}let r=a(e,".claude","mcp.json");if(l(r))try{let o=c(i(r,"utf-8"));if(o.mcpServers?.ruflo||o.mcpServers?.["claude-flow"])return{available:!0,method:"mcp-config"}}catch{}let t=a(e,".claude","settings.json");if(l(t))try{let o=c(i(t,"utf-8")),u=o.mcpServers||o.mcp?.servers||{};if(u.ruflo||u["claude-flow"]||u["@anthropic/claude-flow"])return{available:!0,method:"mcp-config"}}catch{}return null}function v(e){let n=a(e,"package.json");if(!l(n))return null;try{let r=c(i(n,"utf-8")),t={...r.dependencies,...r.devDependencies};if(t.ruflo||t["@claude-flow/cli"]||t["claude-flow"])return{available:!0,method:"npm-dependency"}}catch{}return null}function k(e){for(let n of["ruflo","@claude-flow/cli"])try{return{available:!0,method:"npx-cached",version:m(`npx --no-install ${n} --version`,{encoding:"utf-8",timeout:5e3,cwd:e,stdio:["pipe","pipe","pipe"]}).trim().match(/\d+\.\d+\.\d+[\w.-]*/)?.[0]}}catch{}return null}function x(){for(let e of["ruflo","@claude-flow/cli"])try{return f.resolve(`${e}/package.json`),e}catch{}return"ruflo"}function P(){return[" Claude Flow not found \u2014 running in standalone mode.",""," Claude Flow adds optional features:"," - SONA trajectory tracking (reinforcement learning)"," - 3-tier model routing (haiku / sonnet / opus)"," - Codebase pretrain analysis",""," To install later:"," npm install -g ruflo"," claude mcp add ruflo -- npx -y ruflo@3.5.18"," aqe init --auto --with-claude-flow"].join(`
3
3
  `)}export{S as a,b,x as c,P 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.9.19");process.exit(0)}
2
- import{a as f}from"./chunk-Z2E5DTKX.js";import{c as p}from"./chunk-5KGFDNYI.js";import{a as l,d as b}from"./chunk-SKNHAGYP.js";import{a as d,c as g}from"./chunk-XF32XZMY.js";f();g();b();var v={dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine",namespace:"coverage-hnsw",maxElements:1e5},S=p.create("coverage-analysis/hnsw-index"),u=class{constructor(e,t={}){this.memory=e;this.config={...v,...t},this.stats={vectorCount:0,searchOperations:0,insertOperations:0}}memory;config;stats;searchLatencies=[];backendType="ruvector-gnn";adapter=null;initialized=!1;metadataStore=new Map;async initialize(){if(this.initialized)return;let e=this.config.metric==="cosine"?"cosine":"euclidean",t=`coverage-${this.config.namespace}`;d.close(t),this.adapter=d.create(t,{dimensions:this.config.dimensions,M:this.config.M,efConstruction:this.config.efConstruction,efSearch:this.config.efSearch,metric:e}),S.info(`HnswAdapter initialized: dimension=${this.config.dimensions}, metric=${this.config.metric}, M=${this.config.M} (unified backend via ADR-071)`),this.initialized=!0}isNativeAvailable(){return this.initialized&&this.adapter!==null}getBackendType(){return this.backendType}isRuvectorAvailable(){return this.initialized&&this.adapter!==null&&this.adapter.isRuvectorAvailable()}async insert(e,t,a){this.initialized||await this.initialize(),t=this.validateVector(t),this.adapter.addByStringId(e,t),a&&this.metadataStore.set(e,a),this.stats.insertOperations++,this.stats.vectorCount=this.adapter.size()}async search(e,t){this.initialized||await this.initialize(),e=this.validateVector(e);let a=performance.now(),n=[];this.adapter.size()>0&&(n=this.adapter.searchByArray(e,t).map(({id:i,score:o})=>({key:i,score:o,distance:1-o,metadata:this.metadataStore.get(i)})));let s=performance.now()-a;return this.recordSearchLatency(s),this.stats.searchOperations++,n}async batchInsert(e){this.initialized||await this.initialize();let t=100;for(let a=0;a<e.length;a+=t){let n=e.slice(a,a+t);await Promise.all(n.map(r=>this.insert(r.key,r.vector,r.metadata)))}}async delete(e){if(!this.adapter)return!1;let t=this.adapter.removeByStringId(e);if(t){this.metadataStore.delete(e);let a=this.buildKey(e);await this.memory.delete(a),this.stats.vectorCount=this.adapter.size()}return t}async getStats(){return{nativeHNSW:this.initialized&&this.adapter!==null,backendType:this.backendType,vectorCount:this.stats.vectorCount,indexSizeBytes:this.stats.vectorCount*this.config.dimensions*4,avgSearchLatencyMs:this.calculateAvgLatency(),p95SearchLatencyMs:this.calculatePercentileLatency(95),p99SearchLatencyMs:this.calculatePercentileLatency(99),searchOperations:this.stats.searchOperations,insertOperations:this.stats.insertOperations}}async clear(){this.metadataStore.clear(),this.adapter&&this.adapter.clear(),this.stats.vectorCount=0,this.searchLatencies=[]}validateVector(e){if(e.length!==this.config.dimensions)return this.resizeVector(e,this.config.dimensions);for(let t=0;t<e.length;t++)if(!Number.isFinite(e[t]))throw new Error(`Invalid vector value at index ${t}: ${e[t]}`);return e}resizeVector(e,t){if(e.length===t)return e;if(e.length>t){let n=new Array(t).fill(0),r=e.length/t;for(let s=0;s<t;s++){let h=Math.floor(s*r),i=Math.floor((s+1)*r),o=0;for(let m=h;m<i;m++)o+=e[m];n[s]=o/(i-h)}return n}let a=new Array(t).fill(0);for(let n=0;n<e.length;n++)a[n]=e[n];return a}buildKey(e){return`${this.config.namespace}:${e}`}recordSearchLatency(e){this.searchLatencies.push(e);let t=1e3;this.searchLatencies.length>t&&(this.searchLatencies=this.searchLatencies.slice(-t))}calculateAvgLatency(){return this.searchLatencies.length===0?0:this.searchLatencies.reduce((t,a)=>t+a,0)/this.searchLatencies.length}calculatePercentileLatency(e){if(this.searchLatencies.length===0)return 0;let t=[...this.searchLatencies].sort((n,r)=>n-r),a=Math.ceil(e/100*t.length)-1;return t[Math.max(0,a)]}setEfSearch(e){this.config.efSearch=e}};function C(c,e){return new u(c,e)}async function H(c,e=1e4,t=1e3){let n=performance.now();for(let i=0;i<e;i++){let o=Array.from({length:384},()=>l());await c.insert(`bench-${i}`,o)}let r=performance.now()-n,s=performance.now();for(let i=0;i<t;i++){let o=Array.from({length:384},()=>l());await c.search(o,10)}let h=performance.now()-s;return{insertTimeMs:r,searchTimeMs:h,avgSearchLatencyMs:h/t,isNative:c.isNativeAvailable(),backendType:c.getBackendType()}}export{v as a,u as b,C as c,H as d};
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.9.21");process.exit(0)}
2
+ import{a as f}from"./chunk-OHR5ILR3.js";import{c as p}from"./chunk-MYZ43VKA.js";import{a as l,d as b}from"./chunk-5EYQP3V3.js";import{a as d,c as g}from"./chunk-KYPN6G7T.js";f();g();b();var v={dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine",namespace:"coverage-hnsw",maxElements:1e5},S=p.create("coverage-analysis/hnsw-index"),u=class{constructor(e,t={}){this.memory=e;this.config={...v,...t},this.stats={vectorCount:0,searchOperations:0,insertOperations:0}}memory;config;stats;searchLatencies=[];backendType="ruvector-gnn";adapter=null;initialized=!1;metadataStore=new Map;async initialize(){if(this.initialized)return;let e=this.config.metric==="cosine"?"cosine":"euclidean",t=`coverage-${this.config.namespace}`;d.close(t),this.adapter=d.create(t,{dimensions:this.config.dimensions,M:this.config.M,efConstruction:this.config.efConstruction,efSearch:this.config.efSearch,metric:e}),S.info(`HnswAdapter initialized: dimension=${this.config.dimensions}, metric=${this.config.metric}, M=${this.config.M} (unified backend via ADR-071)`),this.initialized=!0}isNativeAvailable(){return this.initialized&&this.adapter!==null}getBackendType(){return this.backendType}isRuvectorAvailable(){return this.initialized&&this.adapter!==null&&this.adapter.isRuvectorAvailable()}async insert(e,t,a){this.initialized||await this.initialize(),t=this.validateVector(t),this.adapter.addByStringId(e,t),a&&this.metadataStore.set(e,a),this.stats.insertOperations++,this.stats.vectorCount=this.adapter.size()}async search(e,t){this.initialized||await this.initialize(),e=this.validateVector(e);let a=performance.now(),n=[];this.adapter.size()>0&&(n=this.adapter.searchByArray(e,t).map(({id:i,score:o})=>({key:i,score:o,distance:1-o,metadata:this.metadataStore.get(i)})));let s=performance.now()-a;return this.recordSearchLatency(s),this.stats.searchOperations++,n}async batchInsert(e){this.initialized||await this.initialize();let t=100;for(let a=0;a<e.length;a+=t){let n=e.slice(a,a+t);await Promise.all(n.map(r=>this.insert(r.key,r.vector,r.metadata)))}}async delete(e){if(!this.adapter)return!1;let t=this.adapter.removeByStringId(e);if(t){this.metadataStore.delete(e);let a=this.buildKey(e);await this.memory.delete(a),this.stats.vectorCount=this.adapter.size()}return t}async getStats(){return{nativeHNSW:this.initialized&&this.adapter!==null,backendType:this.backendType,vectorCount:this.stats.vectorCount,indexSizeBytes:this.stats.vectorCount*this.config.dimensions*4,avgSearchLatencyMs:this.calculateAvgLatency(),p95SearchLatencyMs:this.calculatePercentileLatency(95),p99SearchLatencyMs:this.calculatePercentileLatency(99),searchOperations:this.stats.searchOperations,insertOperations:this.stats.insertOperations}}async clear(){this.metadataStore.clear(),this.adapter&&this.adapter.clear(),this.stats.vectorCount=0,this.searchLatencies=[]}validateVector(e){if(e.length!==this.config.dimensions)return this.resizeVector(e,this.config.dimensions);for(let t=0;t<e.length;t++)if(!Number.isFinite(e[t]))throw new Error(`Invalid vector value at index ${t}: ${e[t]}`);return e}resizeVector(e,t){if(e.length===t)return e;if(e.length>t){let n=new Array(t).fill(0),r=e.length/t;for(let s=0;s<t;s++){let h=Math.floor(s*r),i=Math.floor((s+1)*r),o=0;for(let m=h;m<i;m++)o+=e[m];n[s]=o/(i-h)}return n}let a=new Array(t).fill(0);for(let n=0;n<e.length;n++)a[n]=e[n];return a}buildKey(e){return`${this.config.namespace}:${e}`}recordSearchLatency(e){this.searchLatencies.push(e);let t=1e3;this.searchLatencies.length>t&&(this.searchLatencies=this.searchLatencies.slice(-t))}calculateAvgLatency(){return this.searchLatencies.length===0?0:this.searchLatencies.reduce((t,a)=>t+a,0)/this.searchLatencies.length}calculatePercentileLatency(e){if(this.searchLatencies.length===0)return 0;let t=[...this.searchLatencies].sort((n,r)=>n-r),a=Math.ceil(e/100*t.length)-1;return t[Math.max(0,a)]}setEfSearch(e){this.config.efSearch=e}};function C(c,e){return new u(c,e)}async function H(c,e=1e4,t=1e3){let n=performance.now();for(let i=0;i<e;i++){let o=Array.from({length:384},()=>l());await c.insert(`bench-${i}`,o)}let r=performance.now()-n,s=performance.now();for(let i=0;i<t;i++){let o=Array.from({length:384},()=>l());await c.search(o,10)}let h=performance.now()-s;return{insertTimeMs:r,searchTimeMs:h,avgSearchLatencyMs:h/t,isNative:c.isNativeAvailable(),backendType:c.getBackendType()}}export{v as a,u as b,C as c,H as d};
@@ -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.9.19");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.9.21");process.exit(0)}
2
2
  var N="ffffffff-ffff-ffff-ffff-ffffffffffff";var _="00000000-0000-0000-0000-000000000000";var y=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function k(r){return typeof r=="string"&&y.test(r)}var u=k;function q(r){if(!u(r))throw TypeError("Invalid UUID");let n;return Uint8Array.of((n=parseInt(r.slice(0,8),16))>>>24,n>>>16&255,n>>>8&255,n&255,(n=parseInt(r.slice(9,13),16))>>>8,n&255,(n=parseInt(r.slice(14,18),16))>>>8,n&255,(n=parseInt(r.slice(19,23),16))>>>8,n&255,(n=parseInt(r.slice(24,36),16))/1099511627776&255,n/4294967296&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255)}var c=q;var x=[];for(let r=0;r<256;++r)x.push((r+256).toString(16).slice(1));function l(r,n=0){return(x[r[n+0]]+x[r[n+1]]+x[r[n+2]]+x[r[n+3]]+"-"+x[r[n+4]]+x[r[n+5]]+"-"+x[r[n+6]]+x[r[n+7]]+"-"+x[r[n+8]]+x[r[n+9]]+"-"+x[r[n+10]]+x[r[n+11]]+x[r[n+12]]+x[r[n+13]]+x[r[n+14]]+x[r[n+15]]).toLowerCase()}function C(r,n=0){let f=l(r,n);if(!u(f))throw TypeError("Stringified UUID is invalid");return f}var H=C;var v=new Uint8Array(16);function m(){return crypto.getRandomValues(v)}var g={};function X(r,n,f){let e,o=r?._v6??!1;if(r){let t=Object.keys(r);t.length===1&&t[0]==="_v6"&&(r=void 0)}if(r)e=E(r.random??r.rng?.()??m(),r.msecs,r.nsecs,r.clockseq,r.node,n,f);else{let t=Date.now(),i=m();j(g,t,i),e=E(i,g.msecs,g.nsecs,o?void 0:g.clockseq,o?void 0:g.node,n,f)}return n??l(e)}function j(r,n,f){return r.msecs??=-1/0,r.nsecs??=0,n===r.msecs?(r.nsecs++,r.nsecs>=1e4&&(r.node=void 0,r.nsecs=0)):n>r.msecs?r.nsecs=0:n<r.msecs&&(r.node=void 0),r.node||(r.node=f.slice(10,16),r.node[0]|=1,r.clockseq=(f[8]<<8|f[9])&16383),r.msecs=n,r}function E(r,n,f,e,o,t,i=0){if(r.length<16)throw new Error("Random bytes length must be >= 16");if(!t)t=new Uint8Array(16),i=0;else if(i<0||i+16>t.length)throw new RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);n??=Date.now(),f??=0,e??=(r[8]<<8|r[9])&16383,o??=r.slice(10,16),n+=122192928e5;let d=((n&268435455)*1e4+f)%4294967296;t[i++]=d>>>24&255,t[i++]=d>>>16&255,t[i++]=d>>>8&255,t[i++]=d&255;let a=n/4294967296*1e4&268435455;t[i++]=a>>>8&255,t[i++]=a&255,t[i++]=a>>>24&15|16,t[i++]=a>>>16&255,t[i++]=e>>>8|128,t[i++]=e&255;for(let p=0;p<6;++p)t[i++]=o[p];return t}var D=X;function U(r){let n=typeof r=="string"?c(r):r,f=G(n);return typeof r=="string"?l(f):f}function G(r){return Uint8Array.of((r[6]&15)<<4|r[7]>>4&15,(r[7]&15)<<4|(r[4]&240)>>4,(r[4]&15)<<4|(r[5]&240)>>4,(r[5]&15)<<4|(r[0]&240)>>4,(r[0]&15)<<4|(r[1]&240)>>4,(r[1]&15)<<4|(r[2]&240)>>4,96|r[2]&15,r[3],r[8],r[9],r[10],r[11],r[12],r[13],r[14],r[15])}import{createHash as K}from"node:crypto";function M(r){return Array.isArray(r)?r=Buffer.from(r):typeof r=="string"&&(r=Buffer.from(r,"utf8")),K("md5").update(r).digest()}var T=M;function O(r){r=unescape(encodeURIComponent(r));let n=new Uint8Array(r.length);for(let f=0;f<r.length;++f)n[f]=r.charCodeAt(f);return n}var w="6ba7b810-9dad-11d1-80b4-00c04fd430c8",I="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function h(r,n,f,e,o,t){let i=typeof f=="string"?O(f):f,d=typeof e=="string"?c(e):e;if(typeof e=="string"&&(e=c(e)),e?.length!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let a=new Uint8Array(16+i.length);if(a.set(d),a.set(i,d.length),a=n(a),a[6]=a[6]&15|r,a[8]=a[8]&63|128,o){if(t??=0,t<0||t+16>o.length)throw new RangeError(`UUID byte range ${t}:${t+15} is out of buffer bounds`);for(let p=0;p<16;++p)o[t+p]=a[p];return o}return l(a)}function S(r,n,f,e){return h(48,T,r,n,f,e)}S.DNS=w;S.URL=I;var z=S;function F(r,n,f){return!n&&!r&&crypto.randomUUID?crypto.randomUUID():J(r,n,f)}function J(r,n,f){r=r||{};let e=r.random??r.rng?.()??m();if(e.length<16)throw new Error("Random bytes length must be >= 16");if(e[6]=e[6]&15|64,e[8]=e[8]&63|128,n){if(f=f||0,f<0||f+16>n.length)throw new RangeError(`UUID byte range ${f}:${f+15} is out of buffer bounds`);for(let o=0;o<16;++o)n[f+o]=e[o];return n}return l(e)}var P=F;import{createHash as Q}from"node:crypto";function W(r){return Array.isArray(r)?r=Buffer.from(r):typeof r=="string"&&(r=Buffer.from(r,"utf8")),Q("sha1").update(r).digest()}var V=W;function R(r,n,f,e){return h(80,V,r,n,f,e)}R.DNS=w;R.URL=I;var Y=R;function Z(r,n,f){r??={},f??=0;let e=D({...r,_v6:!0},new Uint8Array(16));if(e=U(e),n){if(f<0||f+16>n.length)throw new RangeError(`UUID byte range ${f}:${f+15} is out of buffer bounds`);for(let o=0;o<16;o++)n[f+o]=e[o];return n}return l(e)}var s=Z;function $(r){let n=typeof r=="string"?c(r):r,f=b(n);return typeof r=="string"?l(f):f}function b(r){return Uint8Array.of((r[3]&15)<<4|r[4]>>4&15,(r[4]&15)<<4|(r[5]&240)>>4,(r[5]&15)<<4|r[6]&15,r[7],(r[1]&15)<<4|(r[2]&240)>>4,(r[2]&15)<<4|(r[3]&240)>>4,16|(r[0]&240)>>4,(r[0]&15)<<4|(r[1]&240)>>4,r[8],r[9],r[10],r[11],r[12],r[13],r[14],r[15])}var A={};function B(r,n,f){let e;if(r)e=L(r.random??r.rng?.()??m(),r.msecs,r.seq,n,f);else{let o=Date.now(),t=m();r0(A,o,t),e=L(t,A.msecs,A.seq,n,f)}return n??l(e)}function r0(r,n,f){return r.msecs??=-1/0,r.seq??=0,n>r.msecs?(r.seq=f[6]<<23|f[7]<<16|f[8]<<8|f[9],r.msecs=n):(r.seq=r.seq+1|0,r.seq===0&&r.msecs++),r}function L(r,n,f,e,o=0){if(r.length<16)throw new Error("Random bytes length must be >= 16");if(!e)e=new Uint8Array(16),o=0;else if(o<0||o+16>e.length)throw new RangeError(`UUID byte range ${o}:${o+15} is out of buffer bounds`);return n??=Date.now(),f??=r[6]*127<<24|r[7]<<16|r[8]<<8|r[9],e[o++]=n/1099511627776&255,e[o++]=n/4294967296&255,e[o++]=n/16777216&255,e[o++]=n/65536&255,e[o++]=n/256&255,e[o++]=n&255,e[o++]=112|f>>>28&15,e[o++]=f>>>20&255,e[o++]=128|f>>>14&63,e[o++]=f>>>6&255,e[o++]=f<<2&255|r[10]&3,e[o++]=r[11],e[o++]=r[12],e[o++]=r[13],e[o++]=r[14],e[o++]=r[15],e}var n0=B;function f0(r){if(!u(r))throw TypeError("Invalid UUID");return parseInt(r.slice(14,15),16)}var e0=f0;export{N as a,_ as b,u as c,c as d,H as e,D as f,U as g,z as h,P as i,Y as j,s as k,$ as l,n0 as m,e0 as n};
@@ -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.9.19");process.exit(0)}
2
- import{a as T}from"./chunk-Z2E5DTKX.js";import{c as S}from"./chunk-5KGFDNYI.js";import{b as C,d as P}from"./chunk-5R2DUR3A.js";import{a as w,c as $}from"./chunk-5MGRZ4YD.js";import{a as b,d as M}from"./chunk-SKNHAGYP.js";$();M();import{randomUUID as D}from"crypto";var x={topology:"hierarchical",maxConcurrentSkills:10,maxConcurrentModels:3,timeout:3e5,continueOnFailure:!0,retry:{maxRetries:2,retryDelayMs:1e3}},R=class{config;learner;skillValidator=null;workers=new Map;taskQueue=[];isRunning=!1;constructor(e,t){this.config={...x,...e},this.learner=t}setSkillValidator(e){this.skillValidator=e}async validateSkillsParallel(e,t,i){let s=Date.now(),a=i?.trustTier??3,n=i?.validationLevel??"eval",c=this.determineTopology(e.length,t.length),r=this.createValidationTasks(e,t,a,n),o=await this.executeTasksParallel(r,c),l=new Map;for(let u of o){let p=l.get(u.skill)||[];p.push(u),l.set(u.skill,p)}return await this.recordOutcomesToLearner(o,a,n),l}async validateSkillCrossModel(e,t,i){return(await this.validateSkillsParallel([e],t,i)).get(e)||[]}getSummary(e){let t=[],i=new Map,s=new Map;for(let[c,r]of e){i.set(c,r);for(let o of r){t.push(o);let l=s.get(o.model)||[];l.push(o),s.set(o.model,l)}}let a=t.filter(c=>c.errors.length===0&&c.evalPassRate>=.9).length,n=t.reduce((c,r)=>c+r.durationMs,0);return{totalSkills:i.size,totalModels:s.size,successCount:a,failureCount:t.length-a,overallPassRate:t.length>0?a/t.length:0,totalDurationMs:n,avgDurationMs:t.length>0?n/t.length:0,topology:this.config.topology,bySkill:i,byModel:s,results:t}}determineTopology(e,t){if(this.config.topology){let i=e*t;return i>20&&this.config.topology==="mesh"&&console.warn(`[SwarmSkillValidator] Large workload (${i} tasks) may be more efficient with hierarchical topology`),this.config.topology}return e>5||e>t*2?"hierarchical":t>5&&e<=3?"mesh":"hierarchical"}createValidationTasks(e,t,i,s){let a=[];for(let n of e)for(let c of t)a.push({id:`${n}-${c}-${Date.now()}-${D().slice(0,8)}`,skill:n,model:c,trustTier:i,validationLevel:s,timeout:this.config.timeout,retryCount:0});return a}async executeTasksParallel(e,t){this.isRunning=!0,this.taskQueue=[...e];let i=[],s=t==="hierarchical"?this.config.maxConcurrentSkills:Math.min(this.config.maxConcurrentSkills*this.config.maxConcurrentModels,e.length),a=[];for(let n=0;n<Math.min(s,e.length);n++){let c=`worker-${n}`;this.workers.set(c,{id:c,task:null,status:"idle"}),a.push(this.runWorker(c,i))}return await Promise.all(a),this.isRunning=!1,this.workers.clear(),i}async runWorker(e,t){let i=this.workers.get(e);if(i){for(;this.taskQueue.length>0&&this.isRunning;){let s=this.taskQueue.shift();if(!s)break;i.task=s,i.status="running",i.startTime=Date.now();try{let a=await this.executeValidationTask(s);t.push(a),i.result=a,i.status="completed"}catch(a){let n=this.createErrorResult(s,a);this.config.retry&&s.retryCount<this.config.retry.maxRetries&&this.config.continueOnFailure?(s.retryCount++,this.taskQueue.push(s),await this.delay(this.config.retry.retryDelayMs)):(t.push(n),i.result=n,i.status="failed")}}i.task=null,i.status="idle"}}async executeValidationTask(e){let t=Date.now();if(!this.skillValidator)return this.createSimulatedResult(e,t);let i=new Promise((n,c)=>{setTimeout(()=>c(new Error(`Validation timeout after ${e.timeout}ms`)),e.timeout)}),s=await Promise.race([this.skillValidator(e.skill,e.model,{trustTier:e.trustTier,validationLevel:e.validationLevel,timeout:e.timeout}),i]),a=Date.now()-t;return this.outcomeToResult(s,e,a)}outcomeToResult(e,t,i){let s=e.testCaseResults.filter(c=>c.passed).length,a=e.testCaseResults.length,n=a>0?s/a:e.score;return{skill:t.skill,model:t.model,schemaValid:e.validationLevel!=="schema"||e.passed,validatorPassed:e.validationLevel!=="validator"||e.passed,evalPassRate:n,durationMs:i,errors:e.passed?[]:["Validation failed"],trustTier:t.trustTier,validationLevel:t.validationLevel,retryCount:t.retryCount,timestamp:new Date}}createSimulatedResult(e,t){let i=Date.now()-t+b()*100,s=.85+b()*.15;return{skill:e.skill,model:e.model,schemaValid:!0,validatorPassed:s>.8,evalPassRate:s,durationMs:i,errors:s>.8?[]:["Simulated validation failure"],trustTier:e.trustTier,validationLevel:e.validationLevel,retryCount:e.retryCount,timestamp:new Date}}createErrorResult(e,t){let i=w(t);return{skill:e.skill,model:e.model,schemaValid:!1,validatorPassed:!1,evalPassRate:0,durationMs:0,errors:[i],trustTier:e.trustTier,validationLevel:e.validationLevel,retryCount:e.retryCount,timestamp:new Date}}async recordOutcomesToLearner(e,t,i){for(let s of e){let a={skillName:s.skill,trustTier:s.trustTier||t,validationLevel:s.validationLevel||i,model:s.model,passed:s.errors.length===0&&s.evalPassRate>=.9,score:s.evalPassRate,testCaseResults:this.createTestCaseResults(s),timestamp:s.timestamp,runId:`swarm-${Date.now()}`,metadata:{duration:s.durationMs,retryCount:s.retryCount}};await this.learner.recordValidationOutcome(a)}}createTestCaseResults(e){return[{testId:`${e.skill}-${e.model}-aggregate`,passed:e.errors.length===0,expectedPatterns:["valid-output"],actualPatterns:e.errors.length===0?["valid-output"]:[],reasoningQuality:e.evalPassRate,executionTimeMs:e.durationMs,category:"swarm-validation",priority:"high",error:e.errors.length>0?e.errors.join("; "):void 0}]}delay(e){return new Promise(t=>setTimeout(t,e))}getConfig(){return{...this.config}}isValidationRunning(){return this.isRunning}getWorkerStatus(){return Array.from(this.workers.values())}cancel(){this.isRunning=!1,this.taskQueue=[]}};function A(y,e){return new R(y,e)}var F=["security-testing","accessibility-testing","api-testing","performance-testing","visual-regression-testing","mutation-testing","contract-testing","chaos-testing","compliance-testing","penetration-testing"],I=["claude-sonnet","claude-haiku","claude-opus"];P();import{readFileSync as L,writeFileSync as E,existsSync as N}from"fs";var O={varianceThreshold:.04,regressionThreshold:.1,minSamples:3,autoUpdateManifest:!1},k=class{constructor(e,t,i={}){this.learner=e;this.manifestPath=t;this.config={...O,...i}}learner;manifestPath;config;async aggregateResults(e){let t=`agg-${Date.now()}`,i=new Date,s=this.buildSkillResultsMap(e),a=this.calculateSummary(s,e),n=await this.detectCrossModelAnomalies(e),c=await this.detectRegressions(e,this.config.regressionThreshold),r=this.generateRecommendations(s,n,c),o={timestamp:i,runId:t,summary:a,skillResults:s,crossModelAnalysis:n,regressions:c,recommendations:r,metadata:{version:"1.0.0",environment:e[0]?.metadata?.environment,generatedBy:"ValidationResultAggregator",inputs:{runIds:e.map(l=>l.runId),models:[...new Set(e.map(l=>l.model))]}}};return this.config.autoUpdateManifest&&await this.updateManifest(o),o}buildSkillResultsMap(e){let t=new Map;for(let i of e)for(let s of i.outcomes){let a=s.skillName;t.has(a)||t.set(a,{skill:a,trustTier:s.trustTier,passRateByModel:new Map,avgPassRate:0,schemaValid:!0,validatorPassed:!0,evalPassed:!0,issues:[],executionTimeMs:0,testCount:0,passedTests:0,failedTests:0});let n=t.get(a),c=s.testCaseResults.filter(r=>r.passed).length/(s.testCaseResults.length||1);n.passRateByModel.set(i.model,c),n.testCount+=s.testCaseResults.length,n.passedTests+=s.testCaseResults.filter(r=>r.passed).length,n.failedTests+=s.testCaseResults.filter(r=>!r.passed).length,n.executionTimeMs+=s.metadata?.duration||0,s.validationLevel==="schema"&&!s.passed&&(n.schemaValid=!1),s.validationLevel==="validator"&&!s.passed&&(n.validatorPassed=!1),s.validationLevel==="eval"&&!s.passed&&(n.evalPassed=!1);for(let r of s.testCaseResults)!r.passed&&r.error&&n.issues.push({skill:a,model:i.model,severity:r.priority==="critical"?"critical":r.priority==="high"?"high":r.priority==="medium"?"medium":"low",type:this.categorizeIssueType(s.validationLevel,r.error),message:r.error,testId:r.testId})}for(let i of t.values()){let s=Array.from(i.passRateByModel.values());i.avgPassRate=s.length>0?s.reduce((a,n)=>a+n,0)/s.length:0}return t}categorizeIssueType(e,t){return t.toLowerCase().includes("timeout")?"timeout":e==="schema"?"schema_failure":e==="validator"?"validator_failure":e==="eval"?"eval_failure":"error"}calculateSummary(e,t){let i=Array.from(e.values()),s=i.filter(n=>n.avgPassRate>=.9).length,a=i.length>0?i.reduce((n,c)=>n+c.avgPassRate,0)/i.length:0;return{totalSkills:i.length,passedSkills:s,failedSkills:i.length-s,avgPassRate:a,totalDurationMs:t.reduce((n,c)=>n+c.durationMs,0),totalTests:i.reduce((n,c)=>n+c.testCount,0),passedTests:i.reduce((n,c)=>n+c.passedTests,0),failedTests:i.reduce((n,c)=>n+c.failedTests,0),modelsUsed:[...new Set(t.map(n=>n.model))]}}async detectCrossModelAnomalies(e){let t=new Map,i=new Map,s=new Map;for(let d of e){t.has(d.model)||(t.set(d.model,[]),i.set(d.model,{totalTests:0,passedTests:0,skillCount:0}));for(let g of d.outcomes){let h=g.testCaseResults.filter(m=>m.passed).length/(g.testCaseResults.length||1);t.get(d.model).push(h);let f=i.get(d.model);f.totalTests+=g.testCaseResults.length,f.passedTests+=g.testCaseResults.filter(m=>m.passed).length,f.skillCount++,s.has(g.skillName)||s.set(g.skillName,{passRates:[],models:[]}),s.get(g.skillName).passRates.push(h),s.get(g.skillName).models.push(d.model)}}let a=[];for(let d of t.values())a.push(...d);let n=a.length>0?a.reduce((d,g)=>d+g,0)/a.length:0,c=a.length>1?a.reduce((d,g)=>d+Math.pow(g-n,2),0)/a.length:0,r=Math.sqrt(c),o=[],l=new Map;for(let[d,g]of t.entries()){let h=g.reduce((v,V)=>v+V,0)/g.length,f=h-n,m=i.get(d);l.set(d,{avgPassRate:h,skillCount:m.skillCount,totalTests:m.totalTests}),Math.abs(f)>this.config.varianceThreshold*2&&o.push({model:d,type:f<0?"low_performance":"high_variance",description:`Model ${d} has ${(f*100).toFixed(1)}% difference from average`,passRate:h,avgPassRate:n,deviation:Math.abs(f)})}let u=[],p=[];for(let[d,g]of s.entries()){if(g.passRates.length<2)continue;let h=g.passRates.reduce((m,v)=>m+v,0)/g.passRates.length;g.passRates.reduce((m,v)=>m+Math.pow(v-h,2),0)/g.passRates.length<this.config.varianceThreshold?u.push(d):p.push(d)}return{variance:c,stdDeviation:r,anomalies:o,consistentSkills:u,inconsistentSkills:p,modelPerformance:l}}async detectRegressions(e,t){let i=[],s=new Set;for(let a of e)for(let n of a.outcomes){let c=`${n.skillName}-${a.model}`;if(s.has(c))continue;s.add(c);let r=await this.learner.getValidationTrends(n.skillName);if(!r)continue;let o=n.testCaseResults.filter(p=>p.passed).length/(n.testCaseResults.length||1),l=r.recentPassRate,u=l-o;u>=t&&i.push({skill:n.skillName,model:a.model,previousPassRate:l,currentPassRate:o,regressionAmount:u,trend:r.overall,possibleCauses:this.analyzePossibleCauses(n,u),severity:this.categorizeRegressionSeverity(u)})}return i.sort((a,n)=>{let c={critical:0,high:1,medium:2,low:3},r=c[a.severity]-c[n.severity];return r!==0?r:n.regressionAmount-a.regressionAmount})}analyzePossibleCauses(e,t){let i=[],s=e.testCaseResults.filter(c=>!c.passed);if(s.length>0){let c=[...new Set(s.map(r=>r.category).filter(Boolean))];c.length>0&&i.push(`Failures in categories: ${c.join(", ")}`)}let a=s.filter(c=>c.priority==="critical");a.length>0&&i.push(`${a.length} critical test(s) failing`);let n=e.testCaseResults.reduce((c,r)=>c+r.reasoningQuality,0)/(e.testCaseResults.length||1);return n<.7&&i.push(`Low reasoning quality score: ${(n*100).toFixed(1)}%`),t>.3&&i.push("Possible model behavior change or prompt drift"),i.length===0&&i.push("No specific cause identified - review test details"),i}categorizeRegressionSeverity(e){return e>=.5?"critical":e>=.3?"high":e>=.15?"medium":"low"}generateRecommendations(e,t,i){let s=[];if(t.inconsistentSkills.length>0&&s.push(`Review ${t.inconsistentSkills.length} skills with inconsistent cross-model behavior: `+t.inconsistentSkills.slice(0,3).join(", ")+(t.inconsistentSkills.length>3?` and ${t.inconsistentSkills.length-3} more`:"")),t.anomalies.some(r=>r.type==="low_performance")){let r=t.anomalies.filter(o=>o.type==="low_performance").map(o=>o.model);s.push(`Investigate low performance on model(s): ${r.join(", ")}`)}let a=i.filter(r=>r.severity==="critical");a.length>0&&s.push(`URGENT: ${a.length} critical regression(s) detected - immediate review required`);let n=Array.from(e.values()).filter(r=>r.avgPassRate<.9);if(n.length>0){let r=n.filter(l=>!l.schemaValid),o=n.filter(l=>!l.validatorPassed);r.length>0&&s.push(`Fix schema validation for: ${r.map(l=>l.skill).slice(0,3).join(", ")}`),o.length>0&&s.push(`Review validator scripts for: ${o.map(l=>l.skill).slice(0,3).join(", ")}`)}return Array.from(e.values()).reduce((r,o)=>r+o.avgPassRate,0)/e.size<.8&&s.push("Overall pass rate below 80% - consider reviewing skill definitions and test expectations"),s.length===0&&s.push("All validations passing - no immediate action required"),s}async updateManifest(e){if(!N(this.manifestPath))throw new Error(`Manifest file not found: ${this.manifestPath}`);let t=C(L(this.manifestPath,"utf-8"));for(let[s,a]of e.skillResults.entries())if(t.skills&&t.skills[s]){let n=t.skills[s];n.validation||(n.validation={}),n.validation.passRate=a.avgPassRate,n.validation.lastValidated=e.timestamp.toISOString(),n.validation.status=a.avgPassRate>=.9?"passing":"failing",n.validation.passRateByModel=Object.fromEntries(a.passRateByModel)}let i=Array.from(e.skillResults.values());t.validationStatus={passing:i.filter(s=>s.avgPassRate>=.9).length,failing:i.filter(s=>s.avgPassRate<.9).length,unknown:0,skipped:t.summary?.tier0||0},t.generatedAt=new Date().toISOString(),t.lastValidationRun={runId:e.runId,timestamp:e.timestamp.toISOString(),avgPassRate:e.summary.avgPassRate,modelsUsed:e.summary.modelsUsed},E(this.manifestPath,JSON.stringify(t,null,2))}generateMarkdownReport(e){let{summary:t,crossModelAnalysis:i,regressions:s,recommendations:a,skillResults:n}=e,c=(t.avgPassRate>=.9||t.avgPassRate>=.7,"`"),r=[];if(r.push(`# Validation Report
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.9.21");process.exit(0)}
2
+ import{a as T}from"./chunk-OHR5ILR3.js";import{c as S}from"./chunk-MYZ43VKA.js";import{b as C,d as P}from"./chunk-PEOTZFNZ.js";import{a as w,c as $}from"./chunk-SMBQERK7.js";import{a as b,d as M}from"./chunk-5EYQP3V3.js";$();M();import{randomUUID as D}from"crypto";var x={topology:"hierarchical",maxConcurrentSkills:10,maxConcurrentModels:3,timeout:3e5,continueOnFailure:!0,retry:{maxRetries:2,retryDelayMs:1e3}},R=class{config;learner;skillValidator=null;workers=new Map;taskQueue=[];isRunning=!1;constructor(e,t){this.config={...x,...e},this.learner=t}setSkillValidator(e){this.skillValidator=e}async validateSkillsParallel(e,t,i){let s=Date.now(),a=i?.trustTier??3,n=i?.validationLevel??"eval",c=this.determineTopology(e.length,t.length),r=this.createValidationTasks(e,t,a,n),o=await this.executeTasksParallel(r,c),l=new Map;for(let u of o){let p=l.get(u.skill)||[];p.push(u),l.set(u.skill,p)}return await this.recordOutcomesToLearner(o,a,n),l}async validateSkillCrossModel(e,t,i){return(await this.validateSkillsParallel([e],t,i)).get(e)||[]}getSummary(e){let t=[],i=new Map,s=new Map;for(let[c,r]of e){i.set(c,r);for(let o of r){t.push(o);let l=s.get(o.model)||[];l.push(o),s.set(o.model,l)}}let a=t.filter(c=>c.errors.length===0&&c.evalPassRate>=.9).length,n=t.reduce((c,r)=>c+r.durationMs,0);return{totalSkills:i.size,totalModels:s.size,successCount:a,failureCount:t.length-a,overallPassRate:t.length>0?a/t.length:0,totalDurationMs:n,avgDurationMs:t.length>0?n/t.length:0,topology:this.config.topology,bySkill:i,byModel:s,results:t}}determineTopology(e,t){if(this.config.topology){let i=e*t;return i>20&&this.config.topology==="mesh"&&console.warn(`[SwarmSkillValidator] Large workload (${i} tasks) may be more efficient with hierarchical topology`),this.config.topology}return e>5||e>t*2?"hierarchical":t>5&&e<=3?"mesh":"hierarchical"}createValidationTasks(e,t,i,s){let a=[];for(let n of e)for(let c of t)a.push({id:`${n}-${c}-${Date.now()}-${D().slice(0,8)}`,skill:n,model:c,trustTier:i,validationLevel:s,timeout:this.config.timeout,retryCount:0});return a}async executeTasksParallel(e,t){this.isRunning=!0,this.taskQueue=[...e];let i=[],s=t==="hierarchical"?this.config.maxConcurrentSkills:Math.min(this.config.maxConcurrentSkills*this.config.maxConcurrentModels,e.length),a=[];for(let n=0;n<Math.min(s,e.length);n++){let c=`worker-${n}`;this.workers.set(c,{id:c,task:null,status:"idle"}),a.push(this.runWorker(c,i))}return await Promise.all(a),this.isRunning=!1,this.workers.clear(),i}async runWorker(e,t){let i=this.workers.get(e);if(i){for(;this.taskQueue.length>0&&this.isRunning;){let s=this.taskQueue.shift();if(!s)break;i.task=s,i.status="running",i.startTime=Date.now();try{let a=await this.executeValidationTask(s);t.push(a),i.result=a,i.status="completed"}catch(a){let n=this.createErrorResult(s,a);this.config.retry&&s.retryCount<this.config.retry.maxRetries&&this.config.continueOnFailure?(s.retryCount++,this.taskQueue.push(s),await this.delay(this.config.retry.retryDelayMs)):(t.push(n),i.result=n,i.status="failed")}}i.task=null,i.status="idle"}}async executeValidationTask(e){let t=Date.now();if(!this.skillValidator)return this.createSimulatedResult(e,t);let i=new Promise((n,c)=>{setTimeout(()=>c(new Error(`Validation timeout after ${e.timeout}ms`)),e.timeout)}),s=await Promise.race([this.skillValidator(e.skill,e.model,{trustTier:e.trustTier,validationLevel:e.validationLevel,timeout:e.timeout}),i]),a=Date.now()-t;return this.outcomeToResult(s,e,a)}outcomeToResult(e,t,i){let s=e.testCaseResults.filter(c=>c.passed).length,a=e.testCaseResults.length,n=a>0?s/a:e.score;return{skill:t.skill,model:t.model,schemaValid:e.validationLevel!=="schema"||e.passed,validatorPassed:e.validationLevel!=="validator"||e.passed,evalPassRate:n,durationMs:i,errors:e.passed?[]:["Validation failed"],trustTier:t.trustTier,validationLevel:t.validationLevel,retryCount:t.retryCount,timestamp:new Date}}createSimulatedResult(e,t){let i=Date.now()-t+b()*100,s=.85+b()*.15;return{skill:e.skill,model:e.model,schemaValid:!0,validatorPassed:s>.8,evalPassRate:s,durationMs:i,errors:s>.8?[]:["Simulated validation failure"],trustTier:e.trustTier,validationLevel:e.validationLevel,retryCount:e.retryCount,timestamp:new Date}}createErrorResult(e,t){let i=w(t);return{skill:e.skill,model:e.model,schemaValid:!1,validatorPassed:!1,evalPassRate:0,durationMs:0,errors:[i],trustTier:e.trustTier,validationLevel:e.validationLevel,retryCount:e.retryCount,timestamp:new Date}}async recordOutcomesToLearner(e,t,i){for(let s of e){let a={skillName:s.skill,trustTier:s.trustTier||t,validationLevel:s.validationLevel||i,model:s.model,passed:s.errors.length===0&&s.evalPassRate>=.9,score:s.evalPassRate,testCaseResults:this.createTestCaseResults(s),timestamp:s.timestamp,runId:`swarm-${Date.now()}`,metadata:{duration:s.durationMs,retryCount:s.retryCount}};await this.learner.recordValidationOutcome(a)}}createTestCaseResults(e){return[{testId:`${e.skill}-${e.model}-aggregate`,passed:e.errors.length===0,expectedPatterns:["valid-output"],actualPatterns:e.errors.length===0?["valid-output"]:[],reasoningQuality:e.evalPassRate,executionTimeMs:e.durationMs,category:"swarm-validation",priority:"high",error:e.errors.length>0?e.errors.join("; "):void 0}]}delay(e){return new Promise(t=>setTimeout(t,e))}getConfig(){return{...this.config}}isValidationRunning(){return this.isRunning}getWorkerStatus(){return Array.from(this.workers.values())}cancel(){this.isRunning=!1,this.taskQueue=[]}};function A(y,e){return new R(y,e)}var F=["security-testing","accessibility-testing","api-testing","performance-testing","visual-regression-testing","mutation-testing","contract-testing","chaos-testing","compliance-testing","penetration-testing"],I=["claude-sonnet","claude-haiku","claude-opus"];P();import{readFileSync as L,writeFileSync as E,existsSync as N}from"fs";var O={varianceThreshold:.04,regressionThreshold:.1,minSamples:3,autoUpdateManifest:!1},k=class{constructor(e,t,i={}){this.learner=e;this.manifestPath=t;this.config={...O,...i}}learner;manifestPath;config;async aggregateResults(e){let t=`agg-${Date.now()}`,i=new Date,s=this.buildSkillResultsMap(e),a=this.calculateSummary(s,e),n=await this.detectCrossModelAnomalies(e),c=await this.detectRegressions(e,this.config.regressionThreshold),r=this.generateRecommendations(s,n,c),o={timestamp:i,runId:t,summary:a,skillResults:s,crossModelAnalysis:n,regressions:c,recommendations:r,metadata:{version:"1.0.0",environment:e[0]?.metadata?.environment,generatedBy:"ValidationResultAggregator",inputs:{runIds:e.map(l=>l.runId),models:[...new Set(e.map(l=>l.model))]}}};return this.config.autoUpdateManifest&&await this.updateManifest(o),o}buildSkillResultsMap(e){let t=new Map;for(let i of e)for(let s of i.outcomes){let a=s.skillName;t.has(a)||t.set(a,{skill:a,trustTier:s.trustTier,passRateByModel:new Map,avgPassRate:0,schemaValid:!0,validatorPassed:!0,evalPassed:!0,issues:[],executionTimeMs:0,testCount:0,passedTests:0,failedTests:0});let n=t.get(a),c=s.testCaseResults.filter(r=>r.passed).length/(s.testCaseResults.length||1);n.passRateByModel.set(i.model,c),n.testCount+=s.testCaseResults.length,n.passedTests+=s.testCaseResults.filter(r=>r.passed).length,n.failedTests+=s.testCaseResults.filter(r=>!r.passed).length,n.executionTimeMs+=s.metadata?.duration||0,s.validationLevel==="schema"&&!s.passed&&(n.schemaValid=!1),s.validationLevel==="validator"&&!s.passed&&(n.validatorPassed=!1),s.validationLevel==="eval"&&!s.passed&&(n.evalPassed=!1);for(let r of s.testCaseResults)!r.passed&&r.error&&n.issues.push({skill:a,model:i.model,severity:r.priority==="critical"?"critical":r.priority==="high"?"high":r.priority==="medium"?"medium":"low",type:this.categorizeIssueType(s.validationLevel,r.error),message:r.error,testId:r.testId})}for(let i of t.values()){let s=Array.from(i.passRateByModel.values());i.avgPassRate=s.length>0?s.reduce((a,n)=>a+n,0)/s.length:0}return t}categorizeIssueType(e,t){return t.toLowerCase().includes("timeout")?"timeout":e==="schema"?"schema_failure":e==="validator"?"validator_failure":e==="eval"?"eval_failure":"error"}calculateSummary(e,t){let i=Array.from(e.values()),s=i.filter(n=>n.avgPassRate>=.9).length,a=i.length>0?i.reduce((n,c)=>n+c.avgPassRate,0)/i.length:0;return{totalSkills:i.length,passedSkills:s,failedSkills:i.length-s,avgPassRate:a,totalDurationMs:t.reduce((n,c)=>n+c.durationMs,0),totalTests:i.reduce((n,c)=>n+c.testCount,0),passedTests:i.reduce((n,c)=>n+c.passedTests,0),failedTests:i.reduce((n,c)=>n+c.failedTests,0),modelsUsed:[...new Set(t.map(n=>n.model))]}}async detectCrossModelAnomalies(e){let t=new Map,i=new Map,s=new Map;for(let d of e){t.has(d.model)||(t.set(d.model,[]),i.set(d.model,{totalTests:0,passedTests:0,skillCount:0}));for(let g of d.outcomes){let h=g.testCaseResults.filter(m=>m.passed).length/(g.testCaseResults.length||1);t.get(d.model).push(h);let f=i.get(d.model);f.totalTests+=g.testCaseResults.length,f.passedTests+=g.testCaseResults.filter(m=>m.passed).length,f.skillCount++,s.has(g.skillName)||s.set(g.skillName,{passRates:[],models:[]}),s.get(g.skillName).passRates.push(h),s.get(g.skillName).models.push(d.model)}}let a=[];for(let d of t.values())a.push(...d);let n=a.length>0?a.reduce((d,g)=>d+g,0)/a.length:0,c=a.length>1?a.reduce((d,g)=>d+Math.pow(g-n,2),0)/a.length:0,r=Math.sqrt(c),o=[],l=new Map;for(let[d,g]of t.entries()){let h=g.reduce((v,V)=>v+V,0)/g.length,f=h-n,m=i.get(d);l.set(d,{avgPassRate:h,skillCount:m.skillCount,totalTests:m.totalTests}),Math.abs(f)>this.config.varianceThreshold*2&&o.push({model:d,type:f<0?"low_performance":"high_variance",description:`Model ${d} has ${(f*100).toFixed(1)}% difference from average`,passRate:h,avgPassRate:n,deviation:Math.abs(f)})}let u=[],p=[];for(let[d,g]of s.entries()){if(g.passRates.length<2)continue;let h=g.passRates.reduce((m,v)=>m+v,0)/g.passRates.length;g.passRates.reduce((m,v)=>m+Math.pow(v-h,2),0)/g.passRates.length<this.config.varianceThreshold?u.push(d):p.push(d)}return{variance:c,stdDeviation:r,anomalies:o,consistentSkills:u,inconsistentSkills:p,modelPerformance:l}}async detectRegressions(e,t){let i=[],s=new Set;for(let a of e)for(let n of a.outcomes){let c=`${n.skillName}-${a.model}`;if(s.has(c))continue;s.add(c);let r=await this.learner.getValidationTrends(n.skillName);if(!r)continue;let o=n.testCaseResults.filter(p=>p.passed).length/(n.testCaseResults.length||1),l=r.recentPassRate,u=l-o;u>=t&&i.push({skill:n.skillName,model:a.model,previousPassRate:l,currentPassRate:o,regressionAmount:u,trend:r.overall,possibleCauses:this.analyzePossibleCauses(n,u),severity:this.categorizeRegressionSeverity(u)})}return i.sort((a,n)=>{let c={critical:0,high:1,medium:2,low:3},r=c[a.severity]-c[n.severity];return r!==0?r:n.regressionAmount-a.regressionAmount})}analyzePossibleCauses(e,t){let i=[],s=e.testCaseResults.filter(c=>!c.passed);if(s.length>0){let c=[...new Set(s.map(r=>r.category).filter(Boolean))];c.length>0&&i.push(`Failures in categories: ${c.join(", ")}`)}let a=s.filter(c=>c.priority==="critical");a.length>0&&i.push(`${a.length} critical test(s) failing`);let n=e.testCaseResults.reduce((c,r)=>c+r.reasoningQuality,0)/(e.testCaseResults.length||1);return n<.7&&i.push(`Low reasoning quality score: ${(n*100).toFixed(1)}%`),t>.3&&i.push("Possible model behavior change or prompt drift"),i.length===0&&i.push("No specific cause identified - review test details"),i}categorizeRegressionSeverity(e){return e>=.5?"critical":e>=.3?"high":e>=.15?"medium":"low"}generateRecommendations(e,t,i){let s=[];if(t.inconsistentSkills.length>0&&s.push(`Review ${t.inconsistentSkills.length} skills with inconsistent cross-model behavior: `+t.inconsistentSkills.slice(0,3).join(", ")+(t.inconsistentSkills.length>3?` and ${t.inconsistentSkills.length-3} more`:"")),t.anomalies.some(r=>r.type==="low_performance")){let r=t.anomalies.filter(o=>o.type==="low_performance").map(o=>o.model);s.push(`Investigate low performance on model(s): ${r.join(", ")}`)}let a=i.filter(r=>r.severity==="critical");a.length>0&&s.push(`URGENT: ${a.length} critical regression(s) detected - immediate review required`);let n=Array.from(e.values()).filter(r=>r.avgPassRate<.9);if(n.length>0){let r=n.filter(l=>!l.schemaValid),o=n.filter(l=>!l.validatorPassed);r.length>0&&s.push(`Fix schema validation for: ${r.map(l=>l.skill).slice(0,3).join(", ")}`),o.length>0&&s.push(`Review validator scripts for: ${o.map(l=>l.skill).slice(0,3).join(", ")}`)}return Array.from(e.values()).reduce((r,o)=>r+o.avgPassRate,0)/e.size<.8&&s.push("Overall pass rate below 80% - consider reviewing skill definitions and test expectations"),s.length===0&&s.push("All validations passing - no immediate action required"),s}async updateManifest(e){if(!N(this.manifestPath))throw new Error(`Manifest file not found: ${this.manifestPath}`);let t=C(L(this.manifestPath,"utf-8"));for(let[s,a]of e.skillResults.entries())if(t.skills&&t.skills[s]){let n=t.skills[s];n.validation||(n.validation={}),n.validation.passRate=a.avgPassRate,n.validation.lastValidated=e.timestamp.toISOString(),n.validation.status=a.avgPassRate>=.9?"passing":"failing",n.validation.passRateByModel=Object.fromEntries(a.passRateByModel)}let i=Array.from(e.skillResults.values());t.validationStatus={passing:i.filter(s=>s.avgPassRate>=.9).length,failing:i.filter(s=>s.avgPassRate<.9).length,unknown:0,skipped:t.summary?.tier0||0},t.generatedAt=new Date().toISOString(),t.lastValidationRun={runId:e.runId,timestamp:e.timestamp.toISOString(),avgPassRate:e.summary.avgPassRate,modelsUsed:e.summary.modelsUsed},E(this.manifestPath,JSON.stringify(t,null,2))}generateMarkdownReport(e){let{summary:t,crossModelAnalysis:i,regressions:s,recommendations:a,skillResults:n}=e,c=(t.avgPassRate>=.9||t.avgPassRate>=.7,"`"),r=[];if(r.push(`# Validation Report
3
3
 
4
4
  > ${c} Generated: ${e.timestamp.toISOString()}
5
5
  > Run ID: ${e.runId}
@@ -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.9.19");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.9.21");process.exit(0)}
2
2
  import{existsSync as _,readdirSync as d,statSync as w}from"fs";import{join as i,extname as E}from"path";var T=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".pyw",".go",".rs",".java",".kt",".kts",".rb",".cs",".php",".swift",".c",".h",".cpp",".hpp",".cc",".scala"]),v=[".test.",".spec.","_test.","_spec."],b=new Set(["node_modules","dist","build","coverage",".git","__pycache__",".venv","venv",".tox",".mypy_cache","target",".gradle","vendor",".bundle",".next",".nuxt",".output"]);function O(s,p={}){let{maxDepth:f=6,includeTests:m=!1,testsOnly:x=!1,extraExtensions:S=[]}=p;if(!_(s))return[];let o=w(s);if(o.isFile())return[s];if(!o.isDirectory())return[];let y=new Set(S.map(t=>t.startsWith(".")?t:`.${t}`)),n=[];function r(t,c){if(c>f)return;let a;try{a=d(t,{withFileTypes:!0})}catch{return}for(let e of a)if(e.isDirectory()){if(b.has(e.name))continue;r(i(t,e.name),c+1)}else if(e.isFile()){let u=E(e.name).toLowerCase();if(!(T.has(u)||y.has(u))||e.name.endsWith(".d.ts"))continue;let l=v.some(h=>e.name.includes(h))||e.name.startsWith("test_");x?l&&n.push(i(t,e.name)):(m||!l)&&n.push(i(t,e.name))}}return r(s,0),n}export{T as a,O as b};
@@ -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.9.19");process.exit(0)}
2
- import{d as s}from"./chunk-5R2DUR3A.js";s();
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.9.21");process.exit(0)}
2
+ import{d as s}from"./chunk-PEOTZFNZ.js";s();
@@ -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.9.19");process.exit(0)}
2
- import{k as f,o as P}from"./chunk-TXCOK5DC.js";import{d as p,e as y}from"./chunk-5KGFDNYI.js";import{b as h,d as U}from"./chunk-5R2DUR3A.js";import{a as T,c as C}from"./chunk-5MGRZ4YD.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.9.21");process.exit(0)}
2
+ import{k as f,o as P}from"./chunk-5FNEOJSD.js";import{d as p,e as y}from"./chunk-MYZ43VKA.js";import{b as h,d as U}from"./chunk-PEOTZFNZ.js";import{a as T,c as C}from"./chunk-SMBQERK7.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.9.19");process.exit(0)}
2
- import{f as p}from"./chunk-O6UMETOH.js";import{a as f,c as R}from"./chunk-5MGRZ4YD.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-5BA7Q7OR.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.9.21");process.exit(0)}
2
+ import{f as p}from"./chunk-RHAUASC6.js";import{a as f,c as R}from"./chunk-SMBQERK7.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-FSVNN36N.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,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.9.19");process.exit(0)}
2
- import{a as L}from"./chunk-N2PLNYEV.js";import*as w from"fs";var R={"aqe test generate":{domain:"test-generation",action:"generateTests"},"aqe test execute":{domain:"test-execution",action:"execute"},"aqe coverage analyze":{domain:"coverage-analysis",action:"analyze"},"aqe coverage gaps":{domain:"coverage-analysis",action:"detectGaps"},"aqe quality gate":{domain:"quality-assessment",action:"evaluateGate"},"aqe quality assess":{domain:"quality-assessment",action:"analyzeQuality"},"aqe security scan":{domain:"security-compliance",action:"runSASTScan"},"aqe security audit":{domain:"security-compliance",action:"runAudit"},"aqe defect predict":{domain:"defect-intelligence",action:"predictDefects"},"aqe code index":{domain:"code-intelligence",action:"index"},"aqe code impact":{domain:"code-intelligence",action:"analyzeImpact"},"aqe contract validate":{domain:"contract-testing",action:"validateContract"},"aqe chaos test":{domain:"chaos-resilience",action:"runChaosTest"},"aqe requirements validate":{domain:"requirements-validation",action:"validateRequirements"},"aqe visual test":{domain:"visual-accessibility",action:"runVisualTest"},"aqe accessibility test":{domain:"visual-accessibility",action:"runAccessibilityTest"},"aqe learn optimize":{domain:"learning-optimization",action:"optimizeAllStrategies"}},D={daily:"0 0 * * *",weekly:"0 0 * * 0",hourly:"0 * * * *",minutely:"* * * * *"},S=1e4,x=20,M=1e4,W=["__proto__","constructor","prototype"];function v(t){return!W.includes(t)}function C(t){let n=t.split(`
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.9.21");process.exit(0)}
2
+ import{a as L}from"./chunk-OK5JHHXK.js";import*as w from"fs";var R={"aqe test generate":{domain:"test-generation",action:"generateTests"},"aqe test execute":{domain:"test-execution",action:"execute"},"aqe coverage analyze":{domain:"coverage-analysis",action:"analyze"},"aqe coverage gaps":{domain:"coverage-analysis",action:"detectGaps"},"aqe quality gate":{domain:"quality-assessment",action:"evaluateGate"},"aqe quality assess":{domain:"quality-assessment",action:"analyzeQuality"},"aqe security scan":{domain:"security-compliance",action:"runSASTScan"},"aqe security audit":{domain:"security-compliance",action:"runAudit"},"aqe defect predict":{domain:"defect-intelligence",action:"predictDefects"},"aqe code index":{domain:"code-intelligence",action:"index"},"aqe code impact":{domain:"code-intelligence",action:"analyzeImpact"},"aqe contract validate":{domain:"contract-testing",action:"validateContract"},"aqe chaos test":{domain:"chaos-resilience",action:"runChaosTest"},"aqe requirements validate":{domain:"requirements-validation",action:"validateRequirements"},"aqe visual test":{domain:"visual-accessibility",action:"runVisualTest"},"aqe accessibility test":{domain:"visual-accessibility",action:"runAccessibilityTest"},"aqe learn optimize":{domain:"learning-optimization",action:"optimizeAllStrategies"}},D={daily:"0 0 * * *",weekly:"0 0 * * 0",hourly:"0 * * * *",minutely:"* * * * *"},S=1e4,x=20,M=1e4,W=["__proto__","constructor","prototype"];function v(t){return!W.includes(t)}function C(t){let n=t.split(`
3
3
  `);if(n.length>S)throw new Error(`YAML content exceeds maximum allowed lines (${S}). File has ${n.length} lines.`);for(let i=0;i<n.length;i++)if(n[i].length>M)throw new Error(`YAML line ${i+1} exceeds maximum allowed length (${M} characters).`);let a={};for(let i=0;i<n.length;i++){let e=n[i];if(e.trim()===""||e.trim().startsWith("#")||e.search(/\S/)!==0)continue;let o=e.match(/^([\w_-]+):\s*(.+)$/);if(o){let[,c,u]=o;v(c)&&(a[c]=f(u))}}let r=["tags","stages","triggers"];for(let i of r){let e=new RegExp(`^${i}:\\s*$`),s=-1;for(let l=0;l<n.length;l++){let d=n[l];if(!(d.trim()===""||d.trim().startsWith("#"))&&e.test(d.trim())){s=l;break}}if(s===-1)continue;let o=[];a[i]=o;let c=n[s].search(/\S/),u=s+1;for(;u<n.length;){let l=n[u];if(l.trim()===""||l.trim().startsWith("#")){u++;continue}let d=l.search(/\S/),p=l.trim();if(d<=c&&!p.startsWith("-"))break;if(p.startsWith("- ")){let m=p.slice(2).trim();if(!m.includes(":")){o.push(f(m)),u++;continue}let g={},k=m.match(/^([\w_-]+):\s*(.*)$/);if(k){let[,h,y]=k;g[h]=f(y)}let T=d;for(u++;u<n.length;){let h=n[u];if(h.trim()===""||h.trim().startsWith("#")){u++;continue}let y=h.search(/\S/),q=h.trim();if(y<=T)break;let _=q.match(/^([\w_-]+):\s*(.*)$/);if(_){let[,A,$]=_;if($===""){let b=E(n,u+1,y,1);g[A]=b.value,u=b.nextLine;continue}else g[A]=f($)}u++}o.push(g)}else u++}}return a}function E(t,n,a,r=0){if(r>x)throw new Error(`YAML nesting exceeds maximum allowed depth (${x}).`);let i={},e=null,s=null,o=n;for(;o<t.length;){let u=t[o];if(u.trim()===""||u.trim().startsWith("#")){o++;continue}let l=u.search(/\S/),d=u.trim();if(l<=a)break;if(d.startsWith("- ")){let m=d.slice(2).trim();s&&!Array.isArray(i[s])&&(i[s]=[]),s?i[s].push(f(m)):(e||(e=[]),e.push(f(m))),o++;continue}let p=d.match(/^([\w_-]+):\s*(.*)$/);if(p){let[,m,g]=p;if(!v(m)){o++;continue}g===""?(s=m,i[m]=[]):(i[m]=f(g),s=null)}o++}if(e&&Object.keys(i).length===0)return{value:e,nextLine:o};let c=Object.keys(i);return c.length===1&&Array.isArray(i[c[0]])?{value:i[c[0]],nextLine:o}:{value:i,nextLine:o}}function f(t){if(t==="")return"";if(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))return t.slice(1,-1);if(t==="true")return!0;if(t==="false")return!1;if(t==="null"||t==="~")return null;let n=Number(t);return!isNaN(n)&&t!==""?n:t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1).split(",").map(r=>f(r.trim())):t}function K(t){let n=[];if(!w.existsSync(t))return{success:!1,errors:[`File not found: ${t}`]};let a;try{a=w.readFileSync(t,"utf-8")}catch(r){return{success:!1,errors:[`Failed to read file: ${r}`]}}return Y(a,t)}function Y(t,n){let a=[],r;try{r=C(t)}catch(s){return{success:!1,errors:[`Invalid YAML syntax: ${s}`]}}if((!r.name||typeof r.name!="string")&&a.push('Pipeline must have a "name" field'),(!r.stages||!Array.isArray(r.stages))&&a.push('Pipeline must have a "stages" array'),a.length>0)return{success:!1,errors:a};let i={name:r.name,description:r.description,version:r.version||"1.0.0",schedule:r.schedule,stages:r.stages.map((s,o)=>{let c=s;return{name:c.name||`stage-${o}`,command:c.command,params:c.params,depends_on:c.depends_on,condition:c.condition,timeout:c.timeout,retry:c.retry,continue_on_failure:c.continue_on_failure}}),triggers:r.triggers,tags:r.tags,timeout:r.timeout};for(let s=0;s<i.stages.length;s++){let o=i.stages[s];o.command||a.push(`Stage ${s+1} (${o.name}) must have a "command" field`)}if(a.length>0)return{success:!1,pipeline:i,errors:a};let e=O(i,n);return{success:!0,pipeline:i,workflow:e,errors:[]}}function O(t,n){let a=`pipeline-${t.name.replace(/\s+/g,"-").toLowerCase()}`,r=t.stages.map((e,s)=>{let o=P(e.command),c={};if(e.params)for(let[l,d]of Object.entries(e.params))v(l)&&(c[l]=`input.${l}`);let u={id:`stage-${e.name.replace(/\s+/g,"-").toLowerCase()}`,name:e.name,domain:o.domain,action:o.action,inputMapping:Object.keys(c).length>0?c:void 0,dependsOn:e.depends_on?.map(l=>`stage-${l.replace(/\s+/g,"-").toLowerCase()}`),timeout:e.timeout?e.timeout*1e3:void 0,continueOnFailure:e.continue_on_failure};return e.condition&&(u.condition={path:e.condition.path,operator:e.condition.operator,value:e.condition.value}),e.retry&&(u.retry={maxAttempts:e.retry.max_attempts||3,backoffMs:(e.retry.backoff_seconds||1)*1e3}),u}),i=t.triggers?.map(e=>{let s={eventType:I(e),sourceDomain:e.source_domain};return e.condition&&(s.condition={path:e.condition.path,operator:e.condition.operator,value:e.condition.value}),s});return{id:a,name:t.name,description:t.description||`Pipeline from ${n||"inline YAML"}`,version:t.version||"1.0.0",steps:r,triggers:i,tags:t.tags,timeout:t.timeout?t.timeout*1e3:void 0}}function P(t){let n=t.trim().replace(/\s+/g," ").toLowerCase();for(let[a,r]of Object.entries(R))if(n.startsWith(a.toLowerCase()))return r;return n.includes("test")&&n.includes("generate")?{domain:"test-generation",action:"generateTests"}:n.includes("test")&&(n.includes("execute")||n.includes("run"))?{domain:"test-execution",action:"execute"}:n.includes("coverage")?{domain:"coverage-analysis",action:"analyze"}:n.includes("quality")||n.includes("gate")?{domain:"quality-assessment",action:"evaluateGate"}:n.includes("security")||n.includes("scan")?{domain:"security-compliance",action:"runSASTScan"}:n.includes("defect")||n.includes("predict")?{domain:"defect-intelligence",action:"predictDefects"}:{domain:"learning-optimization",action:"runLearningCycle"}}function I(t){let n=t.event.toLowerCase();return n==="push"?"code-intelligence.CodePushed":n==="pull_request"||n==="pr"?"code-intelligence.PullRequestOpened":n==="schedule"?"workflow.ScheduleTrigger":n==="quality_gate"?"quality-assessment.QualityGateEvaluated":n==="test_complete"?"test-execution.TestRunCompleted":n}function F(t){let n=[],a=[];if(t.name||n.push({path:"name",message:"Pipeline name is required",severity:"error"}),!t.stages||t.stages.length===0)n.push({path:"stages",message:"Pipeline must have at least one stage",severity:"error"});else{let r=new Set;for(let e=0;e<t.stages.length;e++){let s=t.stages[e],o=`stages[${e}]`;if(r.has(s.name)&&n.push({path:`${o}.name`,message:`Duplicate stage name: ${s.name}`,severity:"error"}),r.add(s.name),s.command?P(s.command).domain==="learning-optimization"&&!s.command.toLowerCase().includes("learn")&&a.push({path:`${o}.command`,message:`Command "${s.command}" not recognized, will default to learning-optimization domain`,severity:"warning"}):n.push({path:`${o}.command`,message:"Stage must have a command",severity:"error"}),s.depends_on)for(let c of s.depends_on)t.stages.some(u=>u.name===c)||n.push({path:`${o}.depends_on`,message:`Unknown dependency: ${c}`,severity:"error"});s.timeout!==void 0&&s.timeout<=0&&n.push({path:`${o}.timeout`,message:"Timeout must be a positive number",severity:"error"}),s.retry&&s.retry.max_attempts!==void 0&&s.retry.max_attempts<1&&n.push({path:`${o}.retry.max_attempts`,message:"max_attempts must be at least 1",severity:"error"})}let i=N(t.stages);i&&n.push({path:"stages",message:`Circular dependency detected: ${i}`,severity:"error"})}if(t.schedule&&(z(t.schedule)||n.push({path:"schedule",message:`Invalid cron expression: ${t.schedule}`,severity:"error"})),t.triggers)for(let r=0;r<t.triggers.length;r++){let i=t.triggers[r],e=`triggers[${r}]`;i.event||n.push({path:`${e}.event`,message:"Trigger must have an event type",severity:"error"}),i.source_domain&&!L.includes(i.source_domain)&&a.push({path:`${e}.source_domain`,message:`Unknown domain: ${i.source_domain}`,severity:"warning"})}return{valid:n.length===0,errors:n,warnings:a}}function N(t){let n=new Set,a=new Set,r=(i,e)=>{if(a.has(i))return[...e,i].join(" -> ");if(n.has(i))return null;n.add(i),a.add(i);let s=t.find(o=>o.name===i);if(s?.depends_on)for(let o of s.depends_on){let c=r(o,[...e,i]);if(c)return c}return a.delete(i),null};for(let i of t){let e=r(i.name,[]);if(e)return e}return null}function z(t){if(Object.keys(D).includes(t))return!0;let n=t.trim().split(/\s+/);if(n.length!==5)return!1;let a=[/^(\*|[0-5]?\d)(-[0-5]?\d)?(\/\d+)?$/,/^(\*|1?\d|2[0-3])(-\d+)?(\/\d+)?$/,/^(\*|[1-9]|[12]\d|3[01])(-\d+)?(\/\d+)?$/,/^(\*|[1-9]|1[0-2])(-\d+)?(\/\d+)?$/,/^(\*|[0-7])(-[0-7])?(\/\d+)?$/];for(let r=0;r<5;r++){let i=n[r].split(",");for(let e of i)if(!a[r].test(e)&&e!=="*")return!1}return!0}function G(t){let n={"@daily":"Daily at midnight","@weekly":"Weekly on Sunday at midnight","@hourly":"Every hour","@minutely":"Every minute"};if(n[t])return n[t];if(Object.keys(D).includes(t))return{daily:"Daily at midnight",weekly:"Weekly on Sunday at midnight",hourly:"Every hour",minutely:"Every minute"}[t]||t;let a=t.trim().split(/\s+/);if(a.length!==5)return t;let[r,i,e,s,o]=a;return r==="0"&&i==="0"&&e==="*"&&s==="*"&&o==="*"?"Daily at midnight":r==="0"&&e==="*"&&s==="*"&&o==="*"?`Daily at ${i}:00`:r!=="*"&&i!=="*"&&e==="*"&&s==="*"?`Daily at ${i}:${r.padStart(2,"0")}`:i==="*"&&r==="0"?"Every hour":r!=="*"&&i==="*"?`Every hour at minute ${r}`:t}function H(t,n=new Date){let a=t.trim().split(/\s+/);if(a.length!==5)return new Date(n.getTime()+1440*60*1e3);let[r,i]=a,e=new Date(n);return i!=="*"&&r!=="*"?(e.setHours(parseInt(i,10),parseInt(r,10),0,0),e<=n&&e.setDate(e.getDate()+1)):i!=="*"?(e.setHours(parseInt(i,10),0,0,0),e<=n&&e.setDate(e.getDate()+1)):r!=="*"?(e.setMinutes(parseInt(r,10),0,0),e<=n&&e.setHours(e.getHours()+1)):(e.setSeconds(0,0),e.setMinutes(e.getMinutes()+1)),e}export{C as a,K as b,F as c,G as d,H as e};
@@ -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.9.19");process.exit(0)}
2
- import{d as m}from"./chunk-SKNHAGYP.js";import{d as T}from"./chunk-IV74GAZN.js";T();function p(t,r,o){let e=0,n=t.length;for(;e<n;){let i=e+n>>>1;o(t[i],r)<=0?e=i+1:n=i}return e}function a(t,r,o){let e=p(t,r,o);return t.splice(e,0,r),e}function s(){return(t,r)=>t.createdAt.getTime()-r.createdAt.getTime()}m();export{a,s as b};
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.9.21");process.exit(0)}
2
+ import{d as m}from"./chunk-5EYQP3V3.js";import{d as T}from"./chunk-ZUTYZIWQ.js";T();function p(t,r,o){let e=0,n=t.length;for(;e<n;){let i=e+n>>>1;o(t[i],r)<=0?e=i+1:n=i}return e}function a(t,r,o){let e=p(t,r,o);return t.splice(e,0,r),e}function s(){return(t,r)=>t.createdAt.getTime()-r.createdAt.getTime()}m();export{a,s as b};
@@ -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.9.19");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.9.21");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,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.9.19");process.exit(0)}
2
- import{c as t}from"./chunk-WULMXLNN.js";function o(e){try{return e.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.9.21");process.exit(0)}
2
+ import{c as t}from"./chunk-4ZUXTOUG.js";function o(e){try{return e.prepare(`
3
3
  SELECT COUNT(*) as count FROM sqlite_master
4
4
  WHERE type='table' AND name IN ('hypergraph_nodes', 'hypergraph_edges')
5
5
  `).get().count===2}catch{return!1}}var r,a,E,n,p=t(()=>{"use strict";r=`
@@ -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.9.19");process.exit(0)}
2
- import{b as d,d as c}from"./chunk-5R2DUR3A.js";import{a as l,c as g}from"./chunk-5MGRZ4YD.js";g();c();import{existsSync as y,readFileSync as p}from"node:fs";import{join as o,dirname as u}from"node:path";import{fileURLToPath as m}from"node:url";var i=class extends Error{constructor(t,n,r){super(t);this.code=n;this.cause=r;this.name="PatternLoaderError"}code;cause},s=class a{static instance=null;config;patterns;isLoading=!1;constructor(e={}){this.config={basePath:e.basePath??this.getDefaultBasePath(),throwOnMissing:e.throwOnMissing??!1,validatePatterns:e.validatePatterns??!0},this.patterns={index:null,booster:null,router:null,embedding:null,reasoning:null,loadedAt:null,errors:[]}}static getInstance(e){return a.instance||(a.instance=new a(e)),a.instance}static resetInstance(){a.instance=null}getDefaultBasePath(){try{let e=import.meta.url,t=m(e),n=u(t),r=o(n,"..","..","..");return o(r,"assets","patterns")}catch{return o(process.cwd(),"assets","patterns")}}async loadPatterns(){if(!this.isLoading){this.isLoading=!0,this.patterns.errors=[];try{this.patterns.index=this.loadJsonFile("index.json");let[e,t,n,r]=await Promise.all([Promise.resolve(this.loadJsonFile("adr-051-booster-patterns.json")),Promise.resolve(this.loadJsonFile("adr-051-router-patterns.json")),Promise.resolve(this.loadJsonFile("adr-051-embedding-patterns.json")),Promise.resolve(this.loadJsonFile("adr-051-reasoning-patterns.json"))]);this.patterns.booster=e,this.patterns.router=t,this.patterns.embedding=n,this.patterns.reasoning=r,this.patterns.loadedAt=new Date,this.config.validatePatterns&&this.validateLoadedPatterns()}finally{this.isLoading=!1}}}loadJsonFile(e){let t=o(this.config.basePath,e);try{if(!y(t)){let r=`Pattern file not found: ${t}`;if(this.patterns.errors.push(r),this.config.throwOnMissing)throw new i(r,"FILE_NOT_FOUND");return null}let n=p(t,"utf-8");return d(n)}catch(n){if(n instanceof i)throw n;let r=`Failed to load pattern file ${e}: ${l(n)}`;if(this.patterns.errors.push(r),this.config.throwOnMissing)throw new i(r,"PARSE_ERROR",n instanceof Error?n:void 0);return null}}validateLoadedPatterns(){this.patterns.booster&&(Array.isArray(this.patterns.booster.patterns)||this.patterns.errors.push("Booster patterns file missing patterns array")),this.patterns.router&&(Array.isArray(this.patterns.router.patterns)||this.patterns.errors.push("Router patterns file missing patterns array")),this.patterns.embedding&&(Array.isArray(this.patterns.embedding.patterns)||this.patterns.errors.push("Embedding patterns file missing patterns array")),this.patterns.reasoning&&(Array.isArray(this.patterns.reasoning.patterns)||this.patterns.errors.push("Reasoning patterns file missing patterns array"))}async ensureLoaded(){this.patterns.loadedAt||await this.loadPatterns()}async getIndex(){return await this.ensureLoaded(),this.patterns.index}async getBoosterPatterns(){return await this.ensureLoaded(),this.patterns.booster}async getRouterPatterns(){return await this.ensureLoaded(),this.patterns.router}async getEmbeddingPatterns(){return await this.ensureLoaded(),this.patterns.embedding}async getReasoningPatterns(){return await this.ensureLoaded(),this.patterns.reasoning}async getBoosterPatternByKey(e){let t=await this.getBoosterPatterns();return t?t.patterns.find(r=>r.key===e)??null:null}async getRouterPatternByKey(e){let t=await this.getRouterPatterns();return t?t.patterns.find(r=>r.key===e)??null:null}async getEmbeddingPatternByKey(e){let t=await this.getEmbeddingPatterns();return t?t.patterns.find(r=>r.key===e)??null:null}async getReasoningPatternByKey(e){let t=await this.getReasoningPatterns();return t?t.patterns.find(r=>r.key===e)??null:null}async getEligibleBoosterTransforms(){let e=await this.getBoosterPatternByKey("booster-transform-eligibility");return e?e.eligibility_criteria.simple_transforms:[]}async getTierHierarchy(){let e=await this.getRouterPatternByKey("router-5tier-complexity");return e?e.tier_hierarchy:null}async getQualityGateThresholds(){let e=await this.getReasoningPatternByKey("reasoning-pattern-quality-gates");return e?e.gate_thresholds:null}isLoaded(){return this.patterns.loadedAt!==null}getLoadedAt(){return this.patterns.loadedAt}getErrors(){return[...this.patterns.errors]}async getStatistics(){let e=await this.getIndex();return e?e.pattern_statistics:null}async reload(){this.patterns={index:null,booster:null,router:null,embedding:null,reasoning:null,loadedAt:null,errors:[]},await this.loadPatterns()}async getAllPatterns(){return await this.ensureLoaded(),{...this.patterns}}};function x(){return s.getInstance()}export{x 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.9.21");process.exit(0)}
2
+ import{b as d,d as c}from"./chunk-PEOTZFNZ.js";import{a as l,c as g}from"./chunk-SMBQERK7.js";g();c();import{existsSync as y,readFileSync as p}from"node:fs";import{join as o,dirname as u}from"node:path";import{fileURLToPath as m}from"node:url";var i=class extends Error{constructor(t,n,r){super(t);this.code=n;this.cause=r;this.name="PatternLoaderError"}code;cause},s=class a{static instance=null;config;patterns;isLoading=!1;constructor(e={}){this.config={basePath:e.basePath??this.getDefaultBasePath(),throwOnMissing:e.throwOnMissing??!1,validatePatterns:e.validatePatterns??!0},this.patterns={index:null,booster:null,router:null,embedding:null,reasoning:null,loadedAt:null,errors:[]}}static getInstance(e){return a.instance||(a.instance=new a(e)),a.instance}static resetInstance(){a.instance=null}getDefaultBasePath(){try{let e=import.meta.url,t=m(e),n=u(t),r=o(n,"..","..","..");return o(r,"assets","patterns")}catch{return o(process.cwd(),"assets","patterns")}}async loadPatterns(){if(!this.isLoading){this.isLoading=!0,this.patterns.errors=[];try{this.patterns.index=this.loadJsonFile("index.json");let[e,t,n,r]=await Promise.all([Promise.resolve(this.loadJsonFile("adr-051-booster-patterns.json")),Promise.resolve(this.loadJsonFile("adr-051-router-patterns.json")),Promise.resolve(this.loadJsonFile("adr-051-embedding-patterns.json")),Promise.resolve(this.loadJsonFile("adr-051-reasoning-patterns.json"))]);this.patterns.booster=e,this.patterns.router=t,this.patterns.embedding=n,this.patterns.reasoning=r,this.patterns.loadedAt=new Date,this.config.validatePatterns&&this.validateLoadedPatterns()}finally{this.isLoading=!1}}}loadJsonFile(e){let t=o(this.config.basePath,e);try{if(!y(t)){let r=`Pattern file not found: ${t}`;if(this.patterns.errors.push(r),this.config.throwOnMissing)throw new i(r,"FILE_NOT_FOUND");return null}let n=p(t,"utf-8");return d(n)}catch(n){if(n instanceof i)throw n;let r=`Failed to load pattern file ${e}: ${l(n)}`;if(this.patterns.errors.push(r),this.config.throwOnMissing)throw new i(r,"PARSE_ERROR",n instanceof Error?n:void 0);return null}}validateLoadedPatterns(){this.patterns.booster&&(Array.isArray(this.patterns.booster.patterns)||this.patterns.errors.push("Booster patterns file missing patterns array")),this.patterns.router&&(Array.isArray(this.patterns.router.patterns)||this.patterns.errors.push("Router patterns file missing patterns array")),this.patterns.embedding&&(Array.isArray(this.patterns.embedding.patterns)||this.patterns.errors.push("Embedding patterns file missing patterns array")),this.patterns.reasoning&&(Array.isArray(this.patterns.reasoning.patterns)||this.patterns.errors.push("Reasoning patterns file missing patterns array"))}async ensureLoaded(){this.patterns.loadedAt||await this.loadPatterns()}async getIndex(){return await this.ensureLoaded(),this.patterns.index}async getBoosterPatterns(){return await this.ensureLoaded(),this.patterns.booster}async getRouterPatterns(){return await this.ensureLoaded(),this.patterns.router}async getEmbeddingPatterns(){return await this.ensureLoaded(),this.patterns.embedding}async getReasoningPatterns(){return await this.ensureLoaded(),this.patterns.reasoning}async getBoosterPatternByKey(e){let t=await this.getBoosterPatterns();return t?t.patterns.find(r=>r.key===e)??null:null}async getRouterPatternByKey(e){let t=await this.getRouterPatterns();return t?t.patterns.find(r=>r.key===e)??null:null}async getEmbeddingPatternByKey(e){let t=await this.getEmbeddingPatterns();return t?t.patterns.find(r=>r.key===e)??null:null}async getReasoningPatternByKey(e){let t=await this.getReasoningPatterns();return t?t.patterns.find(r=>r.key===e)??null:null}async getEligibleBoosterTransforms(){let e=await this.getBoosterPatternByKey("booster-transform-eligibility");return e?e.eligibility_criteria.simple_transforms:[]}async getTierHierarchy(){let e=await this.getRouterPatternByKey("router-5tier-complexity");return e?e.tier_hierarchy:null}async getQualityGateThresholds(){let e=await this.getReasoningPatternByKey("reasoning-pattern-quality-gates");return e?e.gate_thresholds:null}isLoaded(){return this.patterns.loadedAt!==null}getLoadedAt(){return this.patterns.loadedAt}getErrors(){return[...this.patterns.errors]}async getStatistics(){let e=await this.getIndex();return e?e.pattern_statistics:null}async reload(){this.patterns={index:null,booster:null,router:null,embedding:null,reasoning:null,loadedAt:null,errors:[]},await this.loadPatterns()}async getAllPatterns(){return await this.ensureLoaded(),{...this.patterns}}};function x(){return s.getInstance()}export{x 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.9.19");process.exit(0)}
2
- import{a as F,c as D}from"./chunk-5MGRZ4YD.js";import{d as $}from"./chunk-IV74GAZN.js";$();D();var b=null,l=null,d=null,g=!1,f="",h={modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0,enableCache:!0,maxCacheSize:1e4},o=new Map,P=36e5;function I(t){let e=t.trim();return!!(e.startsWith("{")&&/["']metrics["']/.test(e)||e.startsWith("[")&&e.endsWith("]")&&e.length>50||(e.match(/[a-zA-Z]/g)||[]).length/Math.max(e.length,1)<.3&&e.length>20)}async function A(t={}){if(g)throw new Error(`Transformer initialization previously failed: ${f}`);if(d)return d;let e={...h,...t};return d=(async()=>{try{b=(await import("./transformers-HIVMQP4O.js")).pipeline,console.log(`[RealEmbeddings] Loading model: ${e.modelName}`);let a=performance.now();l=await b("feature-extraction",e.modelName,{quantized:e.quantized});let s=performance.now()-a;console.log(`[RealEmbeddings] Model loaded in ${s.toFixed(0)}ms`)}catch(r){throw g=!0,f=F(r),new Error(`Failed to initialize transformer model: ${f}`)}})(),d}async function q(t,e={}){let r={...h,...e};if(I(t))return new Array(N()).fill(0);if(r.enableCache){let i=o.get(t);if(i&&Date.now()-i.timestamp<P)return i.embedding}if(l||await A(e),!l)throw new Error("Embedding model failed to initialize");let a=performance.now(),s=await l(t,{pooling:"mean",normalize:!0}),m=Array.from(s.data),n=performance.now()-a;if(n>500&&console.warn(`[RealEmbeddings] Slow embedding computation: ${n.toFixed(1)}ms for "${t.slice(0,50)}..."`),r.enableCache){if(o.size>=r.maxCacheSize){let i=o.keys().next().value;i&&o.delete(i)}o.set(t,{embedding:m,timestamp:Date.now()})}return m}async function B(t,e={}){let r={...h,...e},a=[],s=[],m=new Array(t.length).fill(null);if(r.enableCache)for(let n=0;n<t.length;n++){let i=o.get(t[n]);i&&Date.now()-i.timestamp<P?m[n]=i.embedding:(a.push(t[n]),s.push(n))}else{a.push(...t);for(let n=0;n<t.length;n++)s.push(n)}if(a.length>0){if(l||await A(e),!l)throw new Error("Embedding model failed to initialize");let n=performance.now(),i=32;for(let c=0;c<a.length;c+=i){let M=Math.min(c+i,a.length),p=a.slice(c,M),E=await l(p,{pooling:"mean",normalize:!0}),w=E.dims||[p.length,384],R=w[0],C=w[1];for(let u=0;u<R;u++){let z=u*C,x=Array.from(E.data.slice(z,z+C)),y=c+u,v=s[y];if(m[v]=x,r.enableCache){if(o.size>=r.maxCacheSize){let T=o.keys().next().value;T&&o.delete(T)}o.set(a[y],{embedding:x,timestamp:Date.now()})}}}let S=performance.now()-n;console.log(`[RealEmbeddings] Batch computed ${a.length} embeddings in ${S.toFixed(0)}ms`)}return m.filter(n=>n!==null)}function O(){o.clear(),console.log("[RealEmbeddings] Cache cleared")}function W(){return{size:o.size,hitRate:0}}function k(){return!g&&l!==null}function N(){return 384}function G(){b=null,l=null,d=null,g=!1,f="",o.clear()}export{h as a,q as b,B as c,O as d,W as e,k as f,N as g,G as h};
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.9.21");process.exit(0)}
2
+ import{a as F,c as D}from"./chunk-SMBQERK7.js";import{d as $}from"./chunk-ZUTYZIWQ.js";$();D();var b=null,l=null,d=null,g=!1,f="",h={modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0,enableCache:!0,maxCacheSize:1e4},o=new Map,P=36e5;function I(t){let e=t.trim();return!!(e.startsWith("{")&&/["']metrics["']/.test(e)||e.startsWith("[")&&e.endsWith("]")&&e.length>50||(e.match(/[a-zA-Z]/g)||[]).length/Math.max(e.length,1)<.3&&e.length>20)}async function A(t={}){if(g)throw new Error(`Transformer initialization previously failed: ${f}`);if(d)return d;let e={...h,...t};return d=(async()=>{try{b=(await import("./transformers-ZFPUASV4.js")).pipeline,console.log(`[RealEmbeddings] Loading model: ${e.modelName}`);let a=performance.now();l=await b("feature-extraction",e.modelName,{quantized:e.quantized});let s=performance.now()-a;console.log(`[RealEmbeddings] Model loaded in ${s.toFixed(0)}ms`)}catch(r){throw g=!0,f=F(r),new Error(`Failed to initialize transformer model: ${f}`)}})(),d}async function q(t,e={}){let r={...h,...e};if(I(t))return new Array(N()).fill(0);if(r.enableCache){let i=o.get(t);if(i&&Date.now()-i.timestamp<P)return i.embedding}if(l||await A(e),!l)throw new Error("Embedding model failed to initialize");let a=performance.now(),s=await l(t,{pooling:"mean",normalize:!0}),m=Array.from(s.data),n=performance.now()-a;if(n>500&&console.warn(`[RealEmbeddings] Slow embedding computation: ${n.toFixed(1)}ms for "${t.slice(0,50)}..."`),r.enableCache){if(o.size>=r.maxCacheSize){let i=o.keys().next().value;i&&o.delete(i)}o.set(t,{embedding:m,timestamp:Date.now()})}return m}async function B(t,e={}){let r={...h,...e},a=[],s=[],m=new Array(t.length).fill(null);if(r.enableCache)for(let n=0;n<t.length;n++){let i=o.get(t[n]);i&&Date.now()-i.timestamp<P?m[n]=i.embedding:(a.push(t[n]),s.push(n))}else{a.push(...t);for(let n=0;n<t.length;n++)s.push(n)}if(a.length>0){if(l||await A(e),!l)throw new Error("Embedding model failed to initialize");let n=performance.now(),i=32;for(let c=0;c<a.length;c+=i){let M=Math.min(c+i,a.length),p=a.slice(c,M),E=await l(p,{pooling:"mean",normalize:!0}),w=E.dims||[p.length,384],R=w[0],C=w[1];for(let u=0;u<R;u++){let z=u*C,x=Array.from(E.data.slice(z,z+C)),y=c+u,v=s[y];if(m[v]=x,r.enableCache){if(o.size>=r.maxCacheSize){let T=o.keys().next().value;T&&o.delete(T)}o.set(a[y],{embedding:x,timestamp:Date.now()})}}}let S=performance.now()-n;console.log(`[RealEmbeddings] Batch computed ${a.length} embeddings in ${S.toFixed(0)}ms`)}return m.filter(n=>n!==null)}function O(){o.clear(),console.log("[RealEmbeddings] Cache cleared")}function W(){return{size:o.size,hitRate:0}}function k(){return!g&&l!==null}function N(){return 384}function G(){b=null,l=null,d=null,g=!1,f="",o.clear()}export{h as a,q as b,B as c,O as d,W as e,k as f,N as g,G as h};
@@ -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.9.19");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.9.21");process.exit(0)}
2
2
  var h=class{executionHistory=[];learnedDurations=new Map;runCount=0;lastPrunedCount=0;learningRate;maxHistorySize;constructor(t){this.learningRate=t?.learningRate??.3,this.maxHistorySize=t?.maxHistorySize??1e4}buildTestDAG(t){let e=new Map,n=new Map;for(let i of t){let s=this.applyLearnedDuration(i);e.set(s.id,s),n.set(s.id,[])}for(let i of t)for(let s of i.dependencies){if(!e.has(s))throw new Error(`Test '${i.id}' depends on '${s}' which does not exist in the test set`);n.get(s).push(i.id)}let o=this.computeCriticalPath(e,n),a=this.computeParallelGroups(e,n);return{nodes:e,edges:n,criticalPath:o,parallelGroups:a}}findCriticalPath(t){return t.criticalPath.map(e=>t.nodes.get(e)).filter(e=>e!==void 0)}findParallelBranches(t){return t.parallelGroups.map(e=>e.map(n=>t.nodes.get(n)).filter(n=>n!==void 0))}pruneByMinCut(t,e){let n=this.sumDurations(t.nodes);if(n<=e)return this.lastPrunedCount=0,t;let o=this.computeAttentionScores(t),a=Array.from(o.entries()).sort((r,l)=>r[1]-l[1]),i=new Set(t.criticalPath),s=new Set,c=n;for(let[r]of a){if(c<=e)break;if(i.has(r)||(t.edges.get(r)??[]).some(p=>!s.has(p)))continue;let d=t.nodes.get(r);d&&(s.add(r),c-=d.estimatedDuration)}this.lastPrunedCount=s.size;let u=Array.from(t.nodes.values()).filter(r=>!s.has(r.id));return this.buildTestDAG(u)}schedule(t){if(t.length===0)return{phases:[],totalEstimatedTime:0,criticalPathTime:0,parallelism:0};let e=this.buildTestDAG(t),o=this.findParallelBranches(e).map(u=>({tests:u,canRunInParallel:u.length>1})),a=this.computeCriticalPathDuration(e),i=this.sumDurations(e.nodes),s=o.reduce((u,r)=>r.canRunInParallel?u+Math.max(...r.tests.map(l=>l.estimatedDuration)):u+r.tests.reduce((l,d)=>l+d.estimatedDuration,0),0),c=s>0?i/s:1;return this.runCount++,{phases:o,totalEstimatedTime:s,criticalPathTime:a,parallelism:c}}getOptimizationStats(){return{totalTests:0,criticalPathLength:0,parallelGroupCount:0,prunedTests:this.lastPrunedCount,estimatedTimeSaved:0,historicalRuns:this.runCount,usingNativeBackend:!1}}recordExecution(t,e,n){this.executionHistory.push({testId:t,actualDuration:e,result:n,timestamp:Date.now()}),this.executionHistory.length>this.maxHistorySize&&(this.executionHistory=this.executionHistory.slice(-this.maxHistorySize));let o=this.learnedDurations.get(t);o!==void 0?this.learnedDurations.set(t,o*(1-this.learningRate)+e*this.learningRate):this.learnedDurations.set(t,e)}getLearnedDuration(t){return this.learnedDurations.get(t)}isNativeBackendAvailable(){return!1}computeCriticalPath(t,e){let n=this.topologicalSort(t,e);if(n.length===0)return[];let o=new Map,a=new Map;for(let r of n)o.set(r,t.get(r).estimatedDuration),a.set(r,null);for(let r of n){let l=o.get(r);for(let d of e.get(r)??[]){let p=t.get(d);if(!p)continue;let g=l+p.estimatedDuration;g>(o.get(d)??0)&&(o.set(d,g),a.set(d,r))}}let i=0,s=null;for(let[r,l]of o)l>i&&(i=l,s=r);if(!s)return[];let c=[],u=s;for(;u!==null;)c.unshift(u),u=a.get(u)??null;return c}computeCriticalPathDuration(t){return t.criticalPath.reduce((e,n)=>e+(t.nodes.get(n)?.estimatedDuration??0),0)}computeParallelGroups(t,e){let n=this.topologicalSort(t,e);if(n.length===0)return[];let o=new Map;for(let[u,r]of t)o.set(u,new Set(r.dependencies));let a=new Map;for(let u of n){let r=-1;for(let l of o.get(u)??new Set){let d=a.get(l);d!==void 0&&d>r&&(r=d)}a.set(u,r+1)}let i=new Map;for(let u of n){let r=a.get(u)??0;i.has(r)||i.set(r,[]),i.get(r).push(u)}let s=Math.max(...Array.from(i.keys()),-1),c=[];for(let u=0;u<=s;u++){let r=i.get(u);r&&r.length>0&&c.push(r)}return c}computeAttentionScores(t){let e=new Map,n=this.countTransitiveDependents(t);for(let[o,a]of t.nodes){let i=a.lastResult==="fail"?2:1,s=n.get(o)??0;e.set(o,a.priority*i*(1+s))}return e}countTransitiveDependents(t){let e=new Map,n=new Map,o=a=>{if(n.has(a))return n.get(a);let i=new Set;for(let s of t.edges.get(a)??[]){i.add(s);for(let c of o(s))i.add(c)}return n.set(a,i),i};for(let a of t.nodes.keys())e.set(a,o(a).size);return e}topologicalSort(t,e){let n=new Map;for(let i of t.keys())n.set(i,0);for(let i of e.values())for(let s of i)n.has(s)&&n.set(s,(n.get(s)??0)+1);let o=[];for(let[i,s]of n)s===0&&o.push(i);let a=[];for(;o.length>0;){let i=o.shift();a.push(i);for(let s of e.get(i)??[]){let c=(n.get(s)??0)-1;n.set(s,c),c===0&&o.push(s)}}if(a.length!==t.size)throw new Error(`Cycle detected in test DAG: sorted ${a.length} of ${t.size} nodes`);return a}applyLearnedDuration(t){let e=this.learnedDurations.get(t.id);return e!==void 0?{...t,estimatedDuration:Math.round(e)}:t}sumDurations(t){let e=0;for(let n of t.values())e+=n.estimatedDuration;return e}};function m(f){return new h(f)}export{h as a,m as b};
@@ -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.9.19");process.exit(0)}
2
- import{f as d}from"./chunk-O6UMETOH.js";import{a as u,c as g}from"./chunk-5MGRZ4YD.js";g();var m=[{type:"email",pattern:/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,mask:n=>n[0]+"***@"+n.split("@")[1]},{type:"ssn",pattern:/\b\d{3}-\d{2}-\d{4}\b/g,mask:()=>"***-**-****"},{type:"credit-card",pattern:/\b(?:\d[ -]*?){13,19}\b/g,mask:n=>"****-****-****-"+n.replace(/\D/g,"").slice(-4)},{type:"phone",pattern:/\b(?:\+?1[-.\s]?)?(?:\(?\d{3}\)?[-.\s]?)?\d{3}[-.\s]?\d{4}\b/g,mask:n=>n.slice(0,3)+"***"+n.slice(-2)},{type:"api-key",pattern:/(?:key|token|api_key|apikey|secret|password|passwd|auth)=([A-Za-z0-9_\-]{16,})/gi,mask:()=>"***REDACTED***"}],y=class extends d{config={name:"qe/security/url-validate",description:"Validate URL security: checks for XSS/injection patterns, unsafe protocols, and scans URL query parameters for PII exposure (emails, SSNs, credit cards, API keys).",domain:"security-compliance",schema:this.buildSchema()};buildSchema(){return{type:"object",properties:{url:{type:"string",description:"URL to validate for security threats and PII exposure"},enablePII:{type:"boolean",description:"Enable PII exposure scanning in URL and query parameters",default:!0}},required:["url"]}}async execute(s,r){try{let e=this.validateURLSecurity(s.url),t=s.enablePII!==!1?this.scanForPII(s.url):{scanned:!1,found:!1,types:[],details:[]},c=e.issues.length+(t.found?t.types.length:0)===0?`URL passed all checks (security: clean, PII: ${t.scanned?"none found":"not scanned"})`:`URL has ${e.issues.length} security issue(s)${t.found?` and ${t.types.length} PII type(s) exposed in URL`:""}`;return{success:!0,data:{url:s.url,urlSecurity:e,piiExposure:t,summary:c}}}catch(e){return{success:!1,error:u(e)}}}validateURLSecurity(s){let r=[],e="none";try{let t=new URL(s);["http:","https:"].includes(t.protocol)||(r.push({type:"unsafe-protocol",description:`Protocol ${t.protocol} is not allowed`,severity:"high"}),e="high");let o=[/<script/i,/javascript:/i,/on\w+=/i,/data:text\/html/i];for(let i of o)if(i.test(s)){r.push({type:"xss",description:"Potential XSS pattern detected in URL",severity:"critical"}),e="critical";break}let c=[/'.*or.*'/i,/union.*select/i,/drop.*table/i,/;\s*--/i];for(let i of c)if(i.test(s)){r.push({type:"sql-injection",description:"Potential SQL injection pattern detected in URL",severity:"critical"}),e="critical";break}/\.\.[/\\]/.test(s)&&(r.push({type:"path-traversal",description:"Potential path traversal pattern (../) detected",severity:"high"}),e!=="critical"&&(e="high"));let a=["redirect","url","next","return","returnUrl","goto"];for(let i of a){let l=t.searchParams.get(i);l&&/^https?:\/\//.test(l)&&(r.push({type:"open-redirect",description:`Query parameter "${i}" contains an external URL \u2014 potential open redirect`,severity:"medium"}),e==="none"&&(e="medium"))}}catch{r.push({type:"invalid-url",description:"URL could not be parsed",severity:"critical"}),e="critical"}return{valid:r.length===0,riskLevel:e,issues:r}}scanForPII(s){let r=[],e=new Set,t;try{t=decodeURIComponent(s)}catch{t=s}let o="",c="";try{let a=new URL(t);o=a.search,c=a.pathname}catch{o=t}for(let{type:a,pattern:i,mask:l}of m){i.lastIndex=0;let p;for(;(p=i.exec(t))!==null;){e.add(a);let h=o.includes(p[0])?"query-parameter":c.includes(p[0])?"path":"url";r.push({type:a,location:h,masked:l(p[0])})}}return{scanned:!0,found:e.size>0,types:Array.from(e),details:r}}};export{y 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.9.21");process.exit(0)}
2
+ import{f as d}from"./chunk-RHAUASC6.js";import{a as u,c as g}from"./chunk-SMBQERK7.js";g();var m=[{type:"email",pattern:/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,mask:n=>n[0]+"***@"+n.split("@")[1]},{type:"ssn",pattern:/\b\d{3}-\d{2}-\d{4}\b/g,mask:()=>"***-**-****"},{type:"credit-card",pattern:/\b(?:\d[ -]*?){13,19}\b/g,mask:n=>"****-****-****-"+n.replace(/\D/g,"").slice(-4)},{type:"phone",pattern:/\b(?:\+?1[-.\s]?)?(?:\(?\d{3}\)?[-.\s]?)?\d{3}[-.\s]?\d{4}\b/g,mask:n=>n.slice(0,3)+"***"+n.slice(-2)},{type:"api-key",pattern:/(?:key|token|api_key|apikey|secret|password|passwd|auth)=([A-Za-z0-9_\-]{16,})/gi,mask:()=>"***REDACTED***"}],y=class extends d{config={name:"qe/security/url-validate",description:"Validate URL security: checks for XSS/injection patterns, unsafe protocols, and scans URL query parameters for PII exposure (emails, SSNs, credit cards, API keys).",domain:"security-compliance",schema:this.buildSchema()};buildSchema(){return{type:"object",properties:{url:{type:"string",description:"URL to validate for security threats and PII exposure"},enablePII:{type:"boolean",description:"Enable PII exposure scanning in URL and query parameters",default:!0}},required:["url"]}}async execute(s,r){try{let e=this.validateURLSecurity(s.url),t=s.enablePII!==!1?this.scanForPII(s.url):{scanned:!1,found:!1,types:[],details:[]},c=e.issues.length+(t.found?t.types.length:0)===0?`URL passed all checks (security: clean, PII: ${t.scanned?"none found":"not scanned"})`:`URL has ${e.issues.length} security issue(s)${t.found?` and ${t.types.length} PII type(s) exposed in URL`:""}`;return{success:!0,data:{url:s.url,urlSecurity:e,piiExposure:t,summary:c}}}catch(e){return{success:!1,error:u(e)}}}validateURLSecurity(s){let r=[],e="none";try{let t=new URL(s);["http:","https:"].includes(t.protocol)||(r.push({type:"unsafe-protocol",description:`Protocol ${t.protocol} is not allowed`,severity:"high"}),e="high");let o=[/<script/i,/javascript:/i,/on\w+=/i,/data:text\/html/i];for(let i of o)if(i.test(s)){r.push({type:"xss",description:"Potential XSS pattern detected in URL",severity:"critical"}),e="critical";break}let c=[/'.*or.*'/i,/union.*select/i,/drop.*table/i,/;\s*--/i];for(let i of c)if(i.test(s)){r.push({type:"sql-injection",description:"Potential SQL injection pattern detected in URL",severity:"critical"}),e="critical";break}/\.\.[/\\]/.test(s)&&(r.push({type:"path-traversal",description:"Potential path traversal pattern (../) detected",severity:"high"}),e!=="critical"&&(e="high"));let a=["redirect","url","next","return","returnUrl","goto"];for(let i of a){let l=t.searchParams.get(i);l&&/^https?:\/\//.test(l)&&(r.push({type:"open-redirect",description:`Query parameter "${i}" contains an external URL \u2014 potential open redirect`,severity:"medium"}),e==="none"&&(e="medium"))}}catch{r.push({type:"invalid-url",description:"URL could not be parsed",severity:"critical"}),e="critical"}return{valid:r.length===0,riskLevel:e,issues:r}}scanForPII(s){let r=[],e=new Set,t;try{t=decodeURIComponent(s)}catch{t=s}let o="",c="";try{let a=new URL(t);o=a.search,c=a.pathname}catch{o=t}for(let{type:a,pattern:i,mask:l}of m){i.lastIndex=0;let p;for(;(p=i.exec(t))!==null;){e.add(a);let h=o.includes(p[0])?"query-parameter":c.includes(p[0])?"path":"url";r.push({type:a,location:h,masked:l(p[0])})}}return{scanned:!0,found:e.size>0,types:Array.from(e),details:r}}};export{y 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.9.19");process.exit(0)}
2
- import{a as h}from"./chunk-KTDGHN2J.js";import{a as C,f as x}from"./chunk-XKD6AFY5.js";var d={mechanical:["convert var to const","add types","remove console","convert to async","convert to esm","arrow function","rename variable","format code"],simple:["fix typo","update comment","fix simple bug","add documentation","format","rename","simple refactor","basic test"],moderate:["implement feature","implement","refactor","complex refactor","performance optimization","optimize","test generation","generate test","error handling","validation logic","api integration","code index","coverage analysis","quality assessment","defect prediction","predict defect","analyze coverage","analyze","assess","scan","detect"],complex:["multi-file refactor","orchestrate","coordinate","large codebase","migration","cross-domain","workflow","system design","analyze security","security scan","security analysis","vulnerability scan","chaos test","resilience test","contract validation"],critical:["architecture","security audit","critical bug","algorithm design","system-wide","vulnerability","cryptography","performance critical","hardcoded secret","cve","owasp","penetration test","exploit"]},f={architecture:/\b(architect|design|system design|overall structure|component design)\b/i,security:/\b(security|vulnerability|audit|xss|sql injection|csrf|encryption|auth|authentication|authorization)\b/i,multiStep:/\b(orchestrate|coordinate|workflow|pipeline|multi[- ]step)\b/i,crossDomain:/\b(cross[- ]domain|across (domains|modules)|integrate|coordination)\b/i},m=class{config;agentBoosterAdapter;constructor(e,t){this.config=e,this.agentBoosterAdapter=t}async collectSignals(e){let t=e.task.toLowerCase(),r=await this.checkAgentBoosterEligibility(e),o={simple:this.findKeywordMatches(t,d.simple),moderate:this.findKeywordMatches(t,d.moderate),complex:this.findKeywordMatches(t,d.complex),critical:this.findKeywordMatches(t,d.critical)},c=e.codeContext?e.codeContext.split(`
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.9.21");process.exit(0)}
2
+ import{a as h}from"./chunk-AT25VXEO.js";import{a as C,f as x}from"./chunk-HRHKLRBB.js";var d={mechanical:["convert var to const","add types","remove console","convert to async","convert to esm","arrow function","rename variable","format code"],simple:["fix typo","update comment","fix simple bug","add documentation","format","rename","simple refactor","basic test"],moderate:["implement feature","implement","refactor","complex refactor","performance optimization","optimize","test generation","generate test","error handling","validation logic","api integration","code index","coverage analysis","quality assessment","defect prediction","predict defect","analyze coverage","analyze","assess","scan","detect"],complex:["multi-file refactor","orchestrate","coordinate","large codebase","migration","cross-domain","workflow","system design","analyze security","security scan","security analysis","vulnerability scan","chaos test","resilience test","contract validation"],critical:["architecture","security audit","critical bug","algorithm design","system-wide","vulnerability","cryptography","performance critical","hardcoded secret","cve","owasp","penetration test","exploit"]},f={architecture:/\b(architect|design|system design|overall structure|component design)\b/i,security:/\b(security|vulnerability|audit|xss|sql injection|csrf|encryption|auth|authentication|authorization)\b/i,multiStep:/\b(orchestrate|coordinate|workflow|pipeline|multi[- ]step)\b/i,crossDomain:/\b(cross[- ]domain|across (domains|modules)|integrate|coordination)\b/i},m=class{config;agentBoosterAdapter;constructor(e,t){this.config=e,this.agentBoosterAdapter=t}async collectSignals(e){let t=e.task.toLowerCase(),r=await this.checkAgentBoosterEligibility(e),o={simple:this.findKeywordMatches(t,d.simple),moderate:this.findKeywordMatches(t,d.moderate),complex:this.findKeywordMatches(t,d.complex),critical:this.findKeywordMatches(t,d.critical)},c=e.codeContext?e.codeContext.split(`
3
3
  `).length:void 0,n=e.filePaths?e.filePaths.length:void 0,i=f.architecture.test(t),a=f.security.test(t),l=f.multiStep.test(t),g=f.crossDomain.test(t),b=this.detectCreativityRequirement(t),S=this.estimateLanguageComplexity(e.codeContext,e.filePaths),T=e.codeContext?this.estimateCyclomaticComplexity(e.codeContext):void 0;return{linesOfCode:c,fileCount:n,hasArchitectureScope:i,hasSecurityScope:a,requiresMultiStepReasoning:l,requiresCrossDomainCoordination:g,isMechanicalTransform:r.eligible,languageComplexity:S,cyclomaticComplexity:T,dependencyCount:this.countDependencies(e.codeContext),requiresCreativity:b,detectedTransformType:r.transformType,keywordMatches:o}}async checkAgentBoosterEligibility(e){if(!this.config.enableAgentBooster)return{eligible:!1,confidence:0,reason:"Agent Booster is disabled"};let t=e.task.toLowerCase(),r,o=0;for(let n of h){let i=this.getTransformKeywords(n),a=0;for(let l of i)t.includes(l.toLowerCase())&&(a=a===0?.5:a+.25);for(let l of d.mechanical)t.includes(l.toLowerCase())&&(a=Math.max(a,.6));a>o&&(o=a,r=n)}if(e.codeContext&&r&&this.agentBoosterAdapter)try{let i=(await this.agentBoosterAdapter.detectTransformOpportunities(e.codeContext)).opportunities.find(a=>a.type===r);if(i)return{eligible:i.confidence>=this.config.agentBoosterThreshold,transformType:r,confidence:i.confidence,reason:i.reason}}catch(n){console.debug("[SignalCollector] WASM analysis error:",n instanceof Error?n.message:n)}let c=o>=this.config.agentBoosterThreshold&&r!==void 0;return{eligible:c,transformType:r,confidence:Math.min(o,1),reason:c?`Detected ${r} transform pattern`:"No mechanical transform pattern detected"}}findKeywordMatches(e,t){let r=[];for(let o of t)e.includes(o.toLowerCase())&&r.push(o);return r}detectCreativityRequirement(e){return e.includes("design")||e.includes("creative")||e.includes("innovative")||e.includes("novel")}estimateLanguageComplexity(e,t){if(!e&&(!t||t.length===0))return;let r=[".ts",".tsx",".rs",".cpp",".c",".go"],o=[".js",".jsx",".py",".java"],c=[".json",".yaml",".md",".txt",".css",".html"];if(t){for(let n of t)if(r.some(i=>n.endsWith(i)))return"high";for(let n of t)if(o.some(i=>n.endsWith(i)))return"medium";for(let n of t)if(c.some(i=>n.endsWith(i)))return"low"}if(e){let n=/<[A-Z][^>]*>/.test(e),i=/\b(async|await)\b/.test(e),a=/\b(interface|type|class)\b/.test(e);return n&&a?"high":i||a?"medium":"low"}return"medium"}estimateCyclomaticComplexity(e){let t=[/\bif\b/g,/\bfor\b/g,/\bwhile\b/g,/\bcase\b/g,/\bcatch\b/g,/&&/g,/\|\|/g,/\?/g],r=1;for(let o of t){let c=e.match(o);c&&(r+=c.length)}return r}countDependencies(e){if(!e)return;let t=e.match(/\b(import|require|from)\b.*['"].*['"]/g);return t?t.length:0}getTransformKeywords(e){return{"var-to-const":["var to const","convert var","var declaration","var to let","convert var to const","change var to const"],"add-types":["add types","add type","typescript types","type annotations","type annotation","add type annotations"],"remove-console":["remove console","delete console","console.log","remove console.log","strip console"],"promise-to-async":["promise to async","async await",".then to async","convert to async","convert function to async"],"cjs-to-esm":["commonjs to esm","require to import","convert to esm","cjs to esm","module conversion"],"func-to-arrow":["arrow function","function to arrow","convert to arrow","convert function to arrow"]}[e]||[]}};function v(s,e){return new m(s,e)}var u=class{calculateCodeComplexity(e){let t=0;return t+=this.calculateLinesOfCodeContribution(e.linesOfCode),t+=this.calculateFileCountContribution(e.fileCount),t+=this.calculateCyclomaticContribution(e.cyclomaticComplexity),t+=this.calculateLanguageContribution(e.languageComplexity),Math.min(t,100)}calculateReasoningComplexity(e){let t=0;return t+=this.calculateKeywordScore(e.keywordMatches),e.requiresMultiStepReasoning&&(t+=20),e.requiresCreativity&&(t+=20),Math.min(t,100)}calculateScopeComplexity(e){let t=0;return e.hasArchitectureScope&&(t+=40),e.hasSecurityScope&&(t+=30),e.requiresCrossDomainCoordination&&(t+=20),t+=this.calculateDependencyContribution(e.dependencyCount),Math.min(t,100)}calculateOverallComplexity(e,t,r,o){if(o.isMechanicalTransform&&!o.hasSecurityScope&&!o.hasArchitectureScope&&!o.requiresMultiStepReasoning&&!o.requiresCrossDomainCoordination&&e===0&&t===0&&r===0)return 5;let c=e*.3+t*.4+r*.3,n=0;return o.hasSecurityScope&&(n=Math.max(n,50)),o.hasArchitectureScope&&(n=Math.max(n,55)),o.requiresCrossDomainCoordination&&(n=Math.max(n,35)),o.requiresMultiStepReasoning&&(n=Math.max(n,30)),o.keywordMatches.simple.length+o.keywordMatches.moderate.length+o.keywordMatches.complex.length+o.keywordMatches.critical.length===0&&!o.isMechanicalTransform&&c<15&&(n=Math.max(n,15)),Math.min(Math.max(Math.round(c),n),100)}calculateConfidence(e,t){let r=.5;return t.codeContext&&(r+=.2),t.filePaths&&t.filePaths.length>0&&(r+=.1),r+=this.calculateKeywordConfidenceBoost(e.keywordMatches),e.isMechanicalTransform&&(r+=.15),Math.min(r,1)}calculateLinesOfCodeContribution(e){return e===void 0||e<10?0:e<50?10:e<200?20:30}calculateFileCountContribution(e){return e===void 0||e===1?0:e<5?10:20}calculateCyclomaticContribution(e){return e===void 0||e<5?0:e<10?10:e<20?20:30}calculateLanguageContribution(e){return e==="low"?0:e==="medium"?10:e==="high"?20:0}calculateKeywordScore(e){let t=e.simple.length*5+e.moderate.length*15+e.complex.length*25+e.critical.length*35;return Math.min(t,60)}calculateDependencyContribution(e){return e===void 0||e<3?0:e<10?5:10}calculateKeywordConfidenceBoost(e){let t=e.simple.length+e.moderate.length+e.complex.length+e.critical.length;return t>=3?.1:t>=1?.05:0}};function M(){return new u}var p=class{getRecommendedTier(e){for(let t of[0,1,2,3,4]){let[r,o]=C[t].complexityRange;if(e>=r&&e<=o)return t}return 2}findAlternateTiers(e,t){let r=[];return t>0&&r.push(t-1),t<4&&r.push(t+1),t<3&&!r.includes(4)&&r.push(4),r}generateExplanation(e,t,r){let o=[];return o.push(`Complexity score: ${e}/100 (Tier ${t})`),r.isMechanicalTransform&&o.push(this.formatMechanicalTransformInfo(r.detectedTransformType)),o.push(...this.formatScopeExplanations(r)),o.push(...this.formatCodeMetricsExplanations(r)),o.join(". ")}formatMechanicalTransformInfo(e){return`Detected mechanical transform: ${e}`}formatScopeExplanations(e){let t=[];return e.hasArchitectureScope&&t.push("Architecture scope detected"),e.hasSecurityScope&&t.push("Security scope detected"),e.requiresMultiStepReasoning&&t.push("Multi-step reasoning required"),e.requiresCrossDomainCoordination&&t.push("Cross-domain coordination required"),t}formatCodeMetricsExplanations(e){let t=[];return e.linesOfCode!==void 0&&e.linesOfCode>100&&t.push(`Large code change: ${e.linesOfCode} lines`),e.fileCount!==void 0&&e.fileCount>3&&t.push(`Multi-file change: ${e.fileCount} files`),t}};function w(){return new p}var y=class{config;signalCollector;scoreCalculator;tierRecommender;constructor(e,t,r,o){this.config=e,this.signalCollector=t,this.scoreCalculator=r,this.tierRecommender=o}async analyze(e){try{let t=await this.signalCollector.collectSignals(e),r=this.scoreCalculator.calculateCodeComplexity(t),o=this.scoreCalculator.calculateReasoningComplexity(t),c=this.scoreCalculator.calculateScopeComplexity(t),n=this.scoreCalculator.calculateOverallComplexity(r,o,c,t),i=this.tierRecommender.getRecommendedTier(n),a=this.tierRecommender.findAlternateTiers(n,i),l=this.scoreCalculator.calculateConfidence(t,e),g=this.tierRecommender.generateExplanation(n,i,t);return{overall:n,codeComplexity:r,reasoningComplexity:o,scopeComplexity:c,confidence:l,signals:t,recommendedTier:i,alternateTiers:a,explanation:g}}catch(t){throw new x(`Failed to analyze task complexity: ${t instanceof Error?t.message:"Unknown error"}`,t instanceof Error?t:void 0)}}async checkAgentBoosterEligibility(e){return this.signalCollector.checkAgentBoosterEligibility(e)}getRecommendedTier(e){return this.tierRecommender.getRecommendedTier(e)}};function L(s,e){let t=new m(s,e),r=new u,o=new p;return new y(s,t,r,o)}function z(s,e,t,r){return new y(s,e,t,r)}export{m as a,v as b,u as c,M as d,p as e,w as f,y as g,L as h,z as i};