agentic-qe 3.13.11 → 3.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (438) hide show
  1. package/.claude/helpers/.helpers-version +1 -1
  2. package/.claude/helpers/helpers.manifest.json +2 -2
  3. package/.claude/helpers/statusline.cjs +89 -40
  4. package/.claude/skills/qe-court/SKILL.md +4 -4
  5. package/.claude/skills/qe-court/config-schema.json +38 -0
  6. package/.claude/skills/qe-court/evals/qe-court.yaml +8 -8
  7. package/.claude/skills/skills-manifest.json +1 -1
  8. package/CHANGELOG.md +93 -0
  9. package/assets/skills/qe-court/SKILL.md +4 -4
  10. package/assets/skills/qe-court/config-schema.json +38 -0
  11. package/assets/skills/qe-court/evals/qe-court.yaml +8 -8
  12. package/assets/skills/skills-manifest.json +1 -1
  13. package/dist/cli/brain-commands.d.ts +1 -0
  14. package/dist/cli/brain-commands.js +1 -0
  15. package/dist/cli/bundle.js +5 -5
  16. package/dist/cli/chunks/adapter-3VBXL7DO.js +2 -0
  17. package/dist/cli/chunks/{agent-booster-wasm-5ARDZYNO.js → agent-booster-wasm-JZO6VUW4.js} +2 -2
  18. package/dist/cli/chunks/{agent-handler-SVKEPF7B.js → agent-handler-534KFGEJ.js} +2 -2
  19. package/dist/cli/chunks/{agent-memory-branch-QDL7OVHC.js → agent-memory-branch-B7KWLWY4.js} +2 -2
  20. package/dist/cli/chunks/aqe-learning-engine-NXRNKJNA.js +2 -0
  21. package/dist/cli/chunks/{arena-7OCKBN6O.js → arena-7CCD3S3I.js} +2 -2
  22. package/dist/cli/chunks/{arena-HQLSNQZ3.js → arena-OW5MELJX.js} +4 -4
  23. package/dist/cli/chunks/{audit-2EQJW5UE.js → audit-BHVKN4E2.js} +3 -3
  24. package/dist/cli/chunks/base-F6GMOKU2.js +2 -0
  25. package/dist/cli/chunks/{better-sqlite3-OBFNNE4T.js → better-sqlite3-P5FA6WFK.js} +2 -2
  26. package/dist/cli/chunks/brain-handler-WNW5LOV7.js +90 -0
  27. package/dist/cli/chunks/{branch-enumerator-6B4L5O3D.js → branch-enumerator-TVZ2ODKH.js} +2 -2
  28. package/dist/cli/chunks/{browser-VDMGBWNK.js → browser-TCEB2W2F.js} +2 -2
  29. package/dist/cli/chunks/browser-workflow-QRDC46LR.js +2 -0
  30. package/dist/cli/chunks/{chunk-M3MRFZKD.js → chunk-2D7UBX5S.js} +1 -1
  31. package/dist/cli/chunks/{chunk-IZF3VLNW.js → chunk-2HYVOX6N.js} +1 -1
  32. package/dist/cli/chunks/{chunk-U6G6RUFI.js → chunk-2NO4H35K.js} +1 -1
  33. package/dist/cli/chunks/{chunk-4TJJU5Y2.js → chunk-2O4DDPEA.js} +19 -19
  34. package/dist/cli/chunks/{chunk-24XW7KUX.js → chunk-3EM2MK3Z.js} +2 -2
  35. package/dist/cli/chunks/chunk-3GUO4ERR.js +24 -0
  36. package/dist/cli/chunks/{chunk-YRCNWQBO.js → chunk-3JIJBR4V.js} +2 -2
  37. package/dist/cli/chunks/{chunk-2E2QCIGR.js → chunk-3QT6S3A3.js} +3 -3
  38. package/dist/cli/chunks/{chunk-W2T36CS5.js → chunk-3RYTAYR6.js} +1 -1
  39. package/dist/cli/chunks/chunk-43GPSYAL.js +14 -0
  40. package/dist/cli/chunks/{chunk-YYAJEPRD.js → chunk-4FEJEVG7.js} +1 -1
  41. package/dist/cli/chunks/{chunk-4DTBGQWA.js → chunk-4MK2G6TK.js} +2 -2
  42. package/dist/cli/chunks/{chunk-CK7ZLMD2.js → chunk-4XTHRAUV.js} +1 -1
  43. package/dist/cli/chunks/{chunk-LM727BVL.js → chunk-4ZVGSVHV.js} +4 -4
  44. package/dist/cli/chunks/{chunk-DPZ4AU6W.js → chunk-52DFCV57.js} +2 -2
  45. package/dist/cli/chunks/{chunk-PADCR4LY.js → chunk-5LEAGKX5.js} +2 -2
  46. package/dist/cli/chunks/{chunk-P736OKQN.js → chunk-5MZF4N4Q.js} +1 -1
  47. package/dist/cli/chunks/{chunk-XZI4QXJJ.js → chunk-5VDVYTO5.js} +2 -2
  48. package/dist/cli/chunks/chunk-5XGVSQS2.js +11 -0
  49. package/dist/cli/chunks/{chunk-AAPJG3WI.js → chunk-6AOZU3UN.js} +2 -2
  50. package/dist/cli/chunks/{chunk-NC7HTDH5.js → chunk-6AYO3IR2.js} +2 -2
  51. package/dist/cli/chunks/{chunk-TJ67B7S7.js → chunk-6DPAMYLU.js} +2 -2
  52. package/dist/cli/chunks/{chunk-PZHAPI47.js → chunk-6IJMD2ZL.js} +3 -3
  53. package/dist/cli/chunks/{chunk-RGUKQXKL.js → chunk-6IZQSLYZ.js} +2 -2
  54. package/dist/cli/chunks/{chunk-2E3PRDEX.js → chunk-6W42XWLL.js} +2 -2
  55. package/dist/cli/chunks/{chunk-ATRUE6CT.js → chunk-7BOPFN3Y.js} +2 -2
  56. package/dist/cli/chunks/{chunk-LIGDJP6H.js → chunk-7OUMJCJT.js} +1 -1
  57. package/dist/cli/chunks/{chunk-2Y3PW5EJ.js → chunk-7RAB2BZY.js} +160 -26
  58. package/dist/cli/chunks/{chunk-XEUUWOSS.js → chunk-7RVAHJQZ.js} +3 -3
  59. package/dist/cli/chunks/{chunk-HHEWINDL.js → chunk-A2WZEMWT.js} +1 -1
  60. package/dist/cli/chunks/{chunk-36ONUM43.js → chunk-A7SKM6JL.js} +1 -1
  61. package/dist/cli/chunks/chunk-AFGT26NR.js +2 -0
  62. package/dist/cli/chunks/{chunk-23E37MDA.js → chunk-AR6SATU3.js} +2 -2
  63. package/dist/cli/chunks/{chunk-IYMV4CU5.js → chunk-AVLA5PBJ.js} +2 -2
  64. package/dist/cli/chunks/{chunk-OLPJGYO5.js → chunk-B3H4K7CY.js} +2 -2
  65. package/dist/cli/chunks/{chunk-JWT675RM.js → chunk-BQCTO7UB.js} +2 -2
  66. package/dist/cli/chunks/{chunk-JKP2BUF5.js → chunk-BZ4QVFP2.js} +2 -2
  67. package/dist/cli/chunks/{chunk-WINYWMQP.js → chunk-CIUOC5F3.js} +1 -1
  68. package/dist/cli/chunks/{chunk-SJJFU7KK.js → chunk-CIZ6LSNV.js} +2 -2
  69. package/dist/cli/chunks/{chunk-2D7SBOZ4.js → chunk-DDPJUAXQ.js} +2 -2
  70. package/dist/cli/chunks/{chunk-H7QWOJF2.js → chunk-DJITEQYS.js} +2 -2
  71. package/dist/cli/chunks/{chunk-DMHQ4ZUZ.js → chunk-DOWCOZDO.js} +2 -2
  72. package/dist/cli/chunks/{chunk-PBJ5I2NS.js → chunk-E4NU4BJA.js} +2 -2
  73. package/dist/cli/chunks/{chunk-E54QUKAD.js → chunk-E722WNWC.js} +2 -2
  74. package/dist/cli/chunks/chunk-ECTPFCON.js +2 -0
  75. package/dist/cli/chunks/{chunk-MUAW4AJ6.js → chunk-EJ6IP7DE.js} +5 -5
  76. package/dist/cli/chunks/{chunk-NHL37QAZ.js → chunk-ENGKLFLY.js} +2 -2
  77. package/dist/cli/chunks/{chunk-VU3ARH4S.js → chunk-FF43SRP6.js} +1 -1
  78. package/dist/cli/chunks/{chunk-PJNIDDER.js → chunk-FOHYBR3O.js} +1 -1
  79. package/dist/cli/chunks/{chunk-LREIHR2A.js → chunk-FRL3X2QA.js} +2 -2
  80. package/dist/cli/chunks/{chunk-WYQM7GXW.js → chunk-GKNDP5VK.js} +2 -2
  81. package/dist/cli/chunks/{chunk-JK6ENS3J.js → chunk-GVEJP5T7.js} +2 -2
  82. package/dist/cli/chunks/{chunk-H3BHOIT6.js → chunk-H3YDDKBW.js} +3 -3
  83. package/dist/cli/chunks/{chunk-3SPYI7TS.js → chunk-H6NFDOMK.js} +1 -1
  84. package/dist/cli/chunks/{chunk-AZVV7POX.js → chunk-H76TV4UU.js} +3 -3
  85. package/dist/cli/chunks/{chunk-2HT5HRAA.js → chunk-HJIAVR6P.js} +2 -2
  86. package/dist/cli/chunks/{chunk-UZ7OWJ75.js → chunk-HLNQDRHA.js} +1 -1
  87. package/dist/cli/chunks/{chunk-IGW5L7YM.js → chunk-HNKPLVYS.js} +1 -1
  88. package/dist/cli/chunks/{chunk-Y2S6SS7M.js → chunk-HQ7243G3.js} +2 -2
  89. package/dist/cli/chunks/{chunk-TZA45FI7.js → chunk-HQHLHSJO.js} +2 -2
  90. package/dist/cli/chunks/{chunk-YEPJS4AM.js → chunk-I3VHXA2W.js} +2 -2
  91. package/dist/cli/chunks/{chunk-W2NQDAJZ.js → chunk-IE5LC7MB.js} +2 -2
  92. package/dist/cli/chunks/{chunk-TU4BYSXR.js → chunk-IL4AEB3J.js} +27 -25
  93. package/dist/cli/chunks/{chunk-JTQSXU6V.js → chunk-IL6QRXRP.js} +6 -6
  94. package/dist/cli/chunks/{chunk-UX5SM2PW.js → chunk-IQ3JFHZN.js} +1 -1
  95. package/dist/cli/chunks/{chunk-RAV2NJNX.js → chunk-IQLRA4FV.js} +1 -1
  96. package/dist/cli/chunks/{chunk-S3FNAHNC.js → chunk-J3XSHJGK.js} +2 -2
  97. package/dist/cli/chunks/{chunk-AHG2O5HT.js → chunk-JAK5UUWH.js} +2 -2
  98. package/dist/cli/chunks/{chunk-XDK2TPI5.js → chunk-JGROLJ33.js} +1 -1
  99. package/dist/cli/chunks/{chunk-MWTFFGU3.js → chunk-JMKMDSXG.js} +2 -2
  100. package/dist/cli/chunks/{chunk-BVKFBJX6.js → chunk-JRKEBESE.js} +2 -2
  101. package/dist/cli/chunks/{chunk-76NSSNB3.js → chunk-JTWJR2KY.js} +2 -2
  102. package/dist/cli/chunks/{chunk-QYHRDBKI.js → chunk-JY4VZ6BN.js} +2 -2
  103. package/dist/cli/chunks/{chunk-DLL3AJH7.js → chunk-K6CGQR5R.js} +1 -1
  104. package/dist/cli/chunks/{chunk-7HTYM6XY.js → chunk-KDIZQHG5.js} +2 -2
  105. package/dist/cli/chunks/{chunk-B646CE3C.js → chunk-KTSCZ7AW.js} +2 -2
  106. package/dist/cli/chunks/{chunk-LLP3UW62.js → chunk-L4C42WYI.js} +2 -2
  107. package/dist/cli/chunks/{chunk-H3AKF2HS.js → chunk-LCSVROU7.js} +10 -10
  108. package/dist/cli/chunks/{chunk-HZR4G6I3.js → chunk-LKR7T3OZ.js} +1 -1
  109. package/dist/cli/chunks/{chunk-Z5ARI4XT.js → chunk-LZHTCUCO.js} +2 -2
  110. package/dist/cli/chunks/{chunk-YDEYB6Z2.js → chunk-M3HUZD2I.js} +1 -1
  111. package/dist/cli/chunks/{chunk-GWTGBQ6X.js → chunk-MO7EITJK.js} +2 -2
  112. package/dist/cli/chunks/{chunk-5364DBZG.js → chunk-N2YAUDAV.js} +2 -2
  113. package/dist/cli/chunks/{chunk-XVFSZLRS.js → chunk-NDPQ2WPU.js} +1 -1
  114. package/dist/cli/chunks/{chunk-CTS545BF.js → chunk-NKWO2X3T.js} +1 -1
  115. package/dist/cli/chunks/{chunk-GPJDZFFV.js → chunk-NOPVFBQM.js} +2 -2
  116. package/dist/cli/chunks/{chunk-VNVGCJCS.js → chunk-NYARYONH.js} +1 -1
  117. package/dist/cli/chunks/{chunk-WRZ5WZG3.js → chunk-O2MZZL54.js} +2 -2
  118. package/dist/cli/chunks/{chunk-EKFKQGIT.js → chunk-OIYUSWHX.js} +1 -1
  119. package/dist/cli/chunks/{chunk-ZNGFSR5M.js → chunk-OONCRNFA.js} +2 -2
  120. package/dist/cli/chunks/{chunk-LUAXQB57.js → chunk-PEW6FZ47.js} +1 -1
  121. package/dist/cli/chunks/{chunk-W7BB4XLP.js → chunk-Q73RRTLE.js} +2 -2
  122. package/dist/cli/chunks/{chunk-JKPMV5VB.js → chunk-QKQZ4IJF.js} +5 -5
  123. package/dist/cli/chunks/{chunk-EHZQIXH6.js → chunk-QMMDN4WX.js} +3 -3
  124. package/dist/cli/chunks/chunk-QQCENKCX.js +2 -0
  125. package/dist/cli/chunks/{chunk-7YL7P5XG.js → chunk-QSPRQPEL.js} +2 -2
  126. package/dist/cli/chunks/{chunk-DXQMVATY.js → chunk-QZPFUFZG.js} +2 -2
  127. package/dist/cli/chunks/chunk-R2B6EE45.js +2 -0
  128. package/dist/cli/chunks/{chunk-VLW63UA2.js → chunk-R6WJF4D5.js} +2 -2
  129. package/dist/cli/chunks/{chunk-EWH7PFV6.js → chunk-RGVD6ZUX.js} +1 -1
  130. package/dist/cli/chunks/{chunk-UGFHEVG4.js → chunk-RKUYVVGJ.js} +2 -2
  131. package/dist/cli/chunks/{chunk-V7QZMOG3.js → chunk-S5YVLPXU.js} +2 -2
  132. package/dist/cli/chunks/{chunk-UDFTDQ6C.js → chunk-SROZXIMT.js} +37 -37
  133. package/dist/cli/chunks/{chunk-AFXMTSO3.js → chunk-SSV6KSFT.js} +1 -1
  134. package/dist/cli/chunks/{chunk-HGPMS6JL.js → chunk-SUSMHSXT.js} +2 -2
  135. package/dist/cli/chunks/{chunk-BL5BHBXR.js → chunk-T3BZAFLP.js} +1 -1
  136. package/dist/cli/chunks/{chunk-K652SCBA.js → chunk-TGOGCA74.js} +2 -2
  137. package/dist/cli/chunks/{chunk-VHNAN7E2.js → chunk-TKYEP7OR.js} +1 -1
  138. package/dist/cli/chunks/{chunk-OJUI65TR.js → chunk-TQJE7DNL.js} +2 -2
  139. package/dist/cli/chunks/{chunk-MS5CAEPA.js → chunk-TRDEULS7.js} +2 -2
  140. package/dist/cli/chunks/{chunk-YRV45WDT.js → chunk-U4GZWPKM.js} +2 -2
  141. package/dist/cli/chunks/{chunk-2BDTZYQN.js → chunk-UI6WSPEK.js} +3 -3
  142. package/dist/cli/chunks/{chunk-TMY2Y7SC.js → chunk-UUJ5VQJM.js} +1 -1
  143. package/dist/cli/chunks/{chunk-4CTKRLRX.js → chunk-VESOYP6A.js} +2 -2
  144. package/dist/cli/chunks/{chunk-UPMQHCC2.js → chunk-VOSISOFD.js} +1 -1
  145. package/dist/cli/chunks/{chunk-IZOWGVTU.js → chunk-VPVZHJSU.js} +2 -2
  146. package/dist/cli/chunks/{chunk-TBO64O56.js → chunk-VRRG66XB.js} +1 -1
  147. package/dist/cli/chunks/{chunk-WJB6YYMJ.js → chunk-VXU53F7Z.js} +2 -2
  148. package/dist/cli/chunks/{chunk-4TUGQESL.js → chunk-VYENTZ45.js} +2 -2
  149. package/dist/cli/chunks/chunk-WJXHE52V.js +65 -0
  150. package/dist/cli/chunks/{chunk-EN36AFRJ.js → chunk-WKNWRDA5.js} +1 -1
  151. package/dist/cli/chunks/{chunk-4X4GTEQY.js → chunk-WTHAVFIC.js} +1 -1
  152. package/dist/cli/chunks/{chunk-LPDT27EC.js → chunk-WWWX76QB.js} +2 -2
  153. package/dist/cli/chunks/{chunk-TCVEXQLL.js → chunk-XITTURP2.js} +2 -2
  154. package/dist/cli/chunks/{chunk-HV6LJ57R.js → chunk-XXFKN7LB.js} +1 -1
  155. package/dist/cli/chunks/{chunk-UJ2NRIAS.js → chunk-YEAC3DC6.js} +2 -2
  156. package/dist/cli/chunks/{chunk-FBASWZ7G.js → chunk-YKWMKRYB.js} +1 -1
  157. package/dist/cli/chunks/chunk-YKZV7O65.js +2 -0
  158. package/dist/cli/chunks/{chunk-PT6U3IIK.js → chunk-YW4RNZWT.js} +2 -2
  159. package/dist/cli/chunks/{chunk-H5DS7S4B.js → chunk-ZAAYOENS.js} +2 -2
  160. package/dist/cli/chunks/chunk-ZBKGX72B.js +13 -0
  161. package/dist/cli/chunks/{chunk-WVNLNXXI.js → chunk-ZBOWR4XT.js} +2 -2
  162. package/dist/cli/chunks/{chunk-FPX4JSFH.js → chunk-ZCVJCCQQ.js} +2 -2
  163. package/dist/cli/chunks/{chunk-OQWG7GOD.js → chunk-ZI3UO7QR.js} +8 -7
  164. package/dist/cli/chunks/{chunk-BPPEN7SS.js → chunk-ZNSMVQCG.js} +2 -2
  165. package/dist/cli/chunks/{chunk-EI4KYBNI.js → chunk-ZQSXG7FA.js} +2 -2
  166. package/dist/cli/chunks/{ci-M6WYL2XY.js → ci-B432UH6N.js} +2 -2
  167. package/dist/cli/chunks/{ci-output-JFC3WOHX.js → ci-output-GTHH7WYG.js} +2 -2
  168. package/dist/cli/chunks/{circuit-breaker-IMVBU6WP.js → circuit-breaker-VW75DLME.js} +2 -2
  169. package/dist/cli/chunks/{claude-flow-setup-M5T5ZUXX.js → claude-flow-setup-RE3IVT7U.js} +2 -2
  170. package/dist/cli/chunks/client-HNBZUEVV.js +2 -0
  171. package/dist/cli/chunks/{cline-installer-LSFAUHXC.js → cline-installer-NUBZZ55N.js} +2 -2
  172. package/dist/cli/chunks/{code-N3SWJ3XL.js → code-K6JCWKNW.js} +2 -2
  173. package/dist/cli/chunks/{code-index-extractor-WPGRG36B.js → code-index-extractor-I4ILB5JN.js} +2 -2
  174. package/dist/cli/chunks/{codex-installer-LKRCSDU5.js → codex-installer-AKQ5BCHU.js} +2 -2
  175. package/dist/cli/chunks/{completions-E5TBZ5AB.js → completions-V3KJVJF4.js} +2 -2
  176. package/dist/cli/chunks/{complexity-analyzer-3FOSOELK.js → complexity-analyzer-HRG7OOY3.js} +2 -2
  177. package/dist/cli/chunks/{continuedev-installer-ZSVFWMQB.js → continuedev-installer-CNTDONWG.js} +2 -2
  178. package/dist/cli/chunks/{copilot-installer-POSKHPZM.js → copilot-installer-XPWWIWYA.js} +2 -2
  179. package/dist/cli/chunks/core-handlers-TB7NLYXL.js +2 -0
  180. package/dist/cli/chunks/{cost-tracker-3UWDCNGC.js → cost-tracker-MFNLQ56K.js} +2 -2
  181. package/dist/cli/chunks/{coverage-HPBO67JF.js → coverage-KOIK654V.js} +3 -3
  182. package/dist/cli/chunks/cross-domain-router-MDSI553U.js +2 -0
  183. package/dist/cli/chunks/{cursor-installer-DSW3L62X.js → cursor-installer-S5MKLRQQ.js} +2 -2
  184. package/dist/cli/chunks/{daemon-2622ZCMJ.js → daemon-DUS6JYW6.js} +3 -3
  185. package/dist/cli/chunks/{daemon-33KTKDUM.js → daemon-Z7VPGWHY.js} +4 -4
  186. package/dist/cli/chunks/{dag-attention-scheduler-YFT5JMM6.js → dag-attention-scheduler-7CQ3ARNI.js} +2 -2
  187. package/dist/cli/chunks/{detect-COR3Q6BE.js → detect-WORBCAYF.js} +2 -2
  188. package/dist/cli/chunks/{dist-node-5TRNTNWI.js → dist-node-KRNI6OYW.js} +2 -2
  189. package/dist/cli/chunks/{domain-handler-TZC4GCF6.js → domain-handler-KRUR2VQG.js} +2 -2
  190. package/dist/cli/chunks/{domain-transfer-D2TENM3Y.js → domain-transfer-VEOVLV54.js} +2 -2
  191. package/dist/cli/chunks/dream-X7ISHFEE.js +2 -0
  192. package/dist/cli/chunks/embed-and-insert-pattern-QU3NQVA5.js +3 -0
  193. package/dist/cli/chunks/{eval-5ID5D77H.js → eval-AYQ7BSUP.js} +2 -2
  194. package/dist/cli/chunks/{experience-capture-middleware-MT4Z74TD.js → experience-capture-middleware-AWQBL6LT.js} +3 -3
  195. package/dist/cli/chunks/{fast-paths-MACRZGSE.js → fast-paths-V5EL4BYJ.js} +2 -2
  196. package/dist/cli/chunks/{feature-flags-LFNL6BHS.js → feature-flags-BXX7BP22.js} +2 -2
  197. package/dist/cli/chunks/{feature-flags-JZX6ZBUX.js → feature-flags-P34BPRWU.js} +2 -2
  198. package/dist/cli/chunks/{file-discovery-DA5BEAO2.js → file-discovery-MS6BKQ2U.js} +2 -2
  199. package/dist/cli/chunks/{fleet-35I4F7D2.js → fleet-7WVVPA4W.js} +3 -3
  200. package/dist/cli/chunks/{gnn-wrapper-2W3HM3ZI.js → gnn-wrapper-7WQ3LEPG.js} +2 -2
  201. package/dist/cli/chunks/{heartbeat-handler-6O2D2FU2.js → heartbeat-handler-P7QD3BZH.js} +4 -4
  202. package/dist/cli/chunks/heartbeat-scheduler-2C5XGFQT.js +2 -0
  203. package/dist/cli/chunks/hnsw-adapter-KCVMXLUL.js +2 -0
  204. package/dist/cli/chunks/hnsw-index-OGWZS6MP.js +2 -0
  205. package/dist/cli/chunks/{hnsw-legacy-bridge-GWBXEMQR.js → hnsw-legacy-bridge-Y3GAR3UP.js} +2 -2
  206. package/dist/cli/chunks/{hnswlib-node-TZ4VLARU.js → hnswlib-node-5QUXZQWQ.js} +2 -2
  207. package/dist/cli/chunks/{hooks-723GPTQ4.js → hooks-2D64KPRY.js} +10 -10
  208. package/dist/cli/chunks/{hypergraph-engine-ILRYFJM5.js → hypergraph-engine-5INXEZDP.js} +2 -2
  209. package/dist/cli/chunks/{hypergraph-handler-523TSK4P.js → hypergraph-handler-YJJJ3ESZ.js} +3 -3
  210. package/dist/cli/chunks/impact-analyzer-IBJ43GQL.js +2 -0
  211. package/dist/cli/chunks/{init-handler-RBDYIXNV.js → init-handler-QSFYJN5Q.js} +6 -6
  212. package/dist/cli/chunks/init-wizard-6XMFD5LP.js +2 -0
  213. package/dist/cli/chunks/kernel-UDUMUPB3.js +2 -0
  214. package/dist/cli/chunks/{kilocode-installer-E2QSX7Z7.js → kilocode-installer-3N3QGTJU.js} +2 -2
  215. package/dist/cli/chunks/{kiro-installer-EZZLT2R5.js → kiro-installer-GIWVTFZQ.js} +2 -2
  216. package/dist/cli/chunks/knowledge-graph-JRYTUG3W.js +2 -0
  217. package/dist/cli/chunks/learning-SGO2DQ5Q.js +122 -0
  218. package/dist/cli/chunks/llm-router-HBBULO65.js +37 -0
  219. package/dist/cli/chunks/llm-router-service-KF5ZALUQ.js +2 -0
  220. package/dist/cli/chunks/{load-QFQ3YOBQ.js → load-B5OFYB4H.js} +2 -2
  221. package/dist/cli/chunks/load-test-LHMBCNCH.js +2 -0
  222. package/dist/cli/chunks/{mcp-FPBBJJFY.js → mcp-FG3LNQR4.js} +2 -2
  223. package/dist/cli/chunks/{memory-RKN6KV75.js → memory-SPS7ZWLC.js} +5 -5
  224. package/dist/cli/chunks/memory-backend-WZHKHBZK.js +2 -0
  225. package/dist/cli/chunks/memory-handlers-P7FTPWP3.js +2 -0
  226. package/dist/cli/chunks/{multi-model-executor-OUNW3JM5.js → multi-model-executor-PUB7E6KH.js} +2 -2
  227. package/dist/cli/chunks/{opencode-installer-FXETYGGY.js → opencode-installer-TGCSGVG2.js} +2 -2
  228. package/dist/cli/chunks/{orchestrator-35UTVXSP.js → orchestrator-S5FTJFGB.js} +10 -13
  229. package/dist/cli/chunks/pattern-null-store-UZSHCRL2.js +2 -0
  230. package/dist/cli/chunks/{pattern-usage-recorder-YEQDS7DN.js → pattern-usage-recorder-LCXXGRAB.js} +2 -2
  231. package/dist/cli/chunks/{pipeline-YDJMWCAR.js → pipeline-ENOSRHKW.js} +2 -2
  232. package/dist/cli/chunks/{platform-L3LPNVKT.js → platform-WCRBO3Z7.js} +2 -2
  233. package/dist/cli/chunks/{plugin-55EYFJH5.js → plugin-JZ5ODJSU.js} +2 -2
  234. package/dist/cli/chunks/{prime-radiant-advanced-wasm-SUZT6RTM.js → prime-radiant-advanced-wasm-DPJUPNCG.js} +2 -2
  235. package/dist/cli/chunks/protocol-executor-42NLVDTC.js +2 -0
  236. package/dist/cli/chunks/{protocol-handler-QNBFRJNY.js → protocol-handler-IP4NLVY3.js} +2 -2
  237. package/dist/cli/chunks/{prove-3X5NQP4L.js → prove-P6FM4RU7.js} +2 -2
  238. package/dist/cli/chunks/qe-reasoning-bank-W74RSMMU.js +2 -0
  239. package/dist/cli/chunks/{quality-5ZONTNA6.js → quality-UHP4XO26.js} +2 -2
  240. package/dist/cli/chunks/{quality-gate-JPNREEVR.js → quality-gate-63DDBSGM.js} +3 -3
  241. package/dist/cli/chunks/queen-coordinator-XELKSRMS.js +2 -0
  242. package/dist/cli/chunks/real-embeddings-6SO5MFRQ.js +2 -0
  243. package/dist/cli/chunks/{roocode-installer-ZK73O2GD.js → roocode-installer-WTWUOFCH.js} +2 -2
  244. package/dist/cli/chunks/router-GTW2EQZV.js +2 -0
  245. package/dist/cli/chunks/routing-feedback-NVOBWEMK.js +2 -0
  246. package/dist/cli/chunks/{routing-handler-2UN5GRHJ.js → routing-handler-IK7HYERQ.js} +2 -2
  247. package/dist/cli/chunks/{ruvector-commands-EQQUEVWN.js → ruvector-commands-THLB4NIM.js} +2 -2
  248. package/dist/cli/chunks/rvf-dual-writer-5OPVMXNL.js +2 -0
  249. package/dist/cli/chunks/rvf-migration-adapter-5S4YFTX4.js +2 -0
  250. package/dist/cli/chunks/rvf-migration-coordinator-BUKCSHBD.js +2 -0
  251. package/dist/cli/chunks/rvf-native-adapter-LYSJHEVX.js +2 -0
  252. package/dist/cli/chunks/{rvf-store-integrity-66FEC3MD.js → rvf-store-integrity-ECTADZIN.js} +2 -2
  253. package/dist/cli/chunks/safe-db-AEB3JMLD.js +2 -0
  254. package/dist/cli/chunks/schedule-4QNPCQNT.js +2 -0
  255. package/dist/cli/chunks/scheduler-S3DFHX6A.js +2 -0
  256. package/dist/cli/chunks/{security-H7PEUUCV.js → security-HN4UXFXX.js} +3 -3
  257. package/dist/cli/chunks/{shared-rvf-adapter-XETNK4ID.js → shared-rvf-adapter-XJCPX5SN.js} +2 -2
  258. package/dist/cli/chunks/{shared-rvf-dual-writer-PXD54BWJ.js → shared-rvf-dual-writer-23X5PNY5.js} +2 -2
  259. package/dist/cli/chunks/sqlite-persistence-L2KISU2H.js +2 -0
  260. package/dist/cli/chunks/status-handler-ZXANTHKT.js +47 -0
  261. package/dist/cli/chunks/{structural-health-EIFBDCRI.js → structural-health-LR6WI3AH.js} +2 -2
  262. package/dist/cli/chunks/{sync-PECWQ64K.js → sync-4OEI3BC2.js} +2 -2
  263. package/dist/cli/chunks/{sync-3SU4H6R3.js → sync-I5IUJF33.js} +2 -2
  264. package/dist/cli/chunks/{task-handler-ZTUAT6YF.js → task-handler-R3ATJKU5.js} +2 -2
  265. package/dist/cli/chunks/{task-handlers-4RIO7LJJ.js → task-handlers-4X357AEW.js} +3 -3
  266. package/dist/cli/chunks/{test-EV7BSUTI.js → test-PR2B5H2F.js} +4 -4
  267. package/dist/cli/chunks/{test-scheduling-4WVI5DLE.js → test-scheduling-ZNOSQVLD.js} +3 -3
  268. package/dist/cli/chunks/token-bootstrap-LYXOI72S.js +2 -0
  269. package/dist/cli/chunks/{token-usage-FR3JOWYB.js → token-usage-R6EQZBX2.js} +2 -2
  270. package/dist/cli/chunks/{transformers-FENO33LA.js → transformers-COQWK27J.js} +2 -2
  271. package/dist/cli/chunks/{tree-sitter-wasm-parser-YFGJLSMB.js → tree-sitter-wasm-parser-LLIW2X3M.js} +2 -2
  272. package/dist/cli/chunks/{types-N3Y565RZ.js → types-MEYTZITK.js} +2 -2
  273. package/dist/cli/chunks/unified-memory-5KQMA7FV.js +2 -0
  274. package/dist/cli/chunks/unified-memory-hnsw-PQRPTYOD.js +2 -0
  275. package/dist/cli/chunks/unified-persistence-YDONVPJB.js +2 -0
  276. package/dist/cli/chunks/{upgrade-33ZVVZFW.js → upgrade-DVIJ456A.js} +2 -2
  277. package/dist/cli/chunks/{validate-CS5PXGDF.js → validate-UYTSMJ5X.js} +2 -2
  278. package/dist/cli/chunks/{validate-swarm-GRZPWYNM.js → validate-swarm-P32WCJR6.js} +2 -2
  279. package/dist/cli/chunks/{vibium-IO7N4VEE.js → vibium-JGVOLM6X.js} +2 -2
  280. package/dist/cli/chunks/visual-security-RJ7RTNGJ.js +2 -0
  281. package/dist/cli/chunks/{web-tree-sitter-UQXR5HHR.js → web-tree-sitter-5ZGNCTPN.js} +2 -2
  282. package/dist/cli/chunks/{windsurf-installer-BCKLSLZT.js → windsurf-installer-IILSSQAE.js} +2 -2
  283. package/dist/cli/chunks/{witness-chain-R3V26QWL.js → witness-chain-JZMXCG3B.js} +2 -2
  284. package/dist/cli/chunks/witness-chain-YXXXNGAM.js +2 -0
  285. package/dist/cli/chunks/{witness-key-manager-Y36HMPEM.js → witness-key-manager-UUTLNUIH.js} +2 -2
  286. package/dist/cli/chunks/{workflow-4TCIUUFQ.js → workflow-NS7HXVHZ.js} +4 -4
  287. package/dist/cli/chunks/workflow-orchestrator-5KUAVSTH.js +2 -0
  288. package/dist/cli/chunks/{wrappers-MD4JRHJH.js → wrappers-XKEDSV5W.js} +2 -2
  289. package/dist/cli/commands/learning.js +44 -0
  290. package/dist/cli/commands/llm-router.js +62 -27
  291. package/dist/cli/handlers/brain-handler.js +2 -0
  292. package/dist/cli/handlers/status-handler.js +18 -2
  293. package/dist/context/compaction/index.d.ts +1 -0
  294. package/dist/context/compaction/index.js +3 -0
  295. package/dist/context/compaction/instruction-provenance.d.ts +20 -0
  296. package/dist/context/compaction/instruction-provenance.js +18 -0
  297. package/dist/context/compaction/tier2-session-summary.d.ts +8 -0
  298. package/dist/context/compaction/tier2-session-summary.js +20 -0
  299. package/dist/context/compaction/tier3-llm-compact.d.ts +4 -0
  300. package/dist/context/compaction/tier3-llm-compact.js +32 -4
  301. package/dist/init/phases/07-hooks.js +0 -3
  302. package/dist/integrations/embeddings/base/EmbeddingGenerator.js +4 -2
  303. package/dist/integrations/ruvector/brain-exporter.d.ts +1 -1
  304. package/dist/integrations/ruvector/brain-exporter.js +15 -3
  305. package/dist/integrations/ruvector/brain-rvf-exporter.d.ts +4 -0
  306. package/dist/integrations/ruvector/brain-rvf-exporter.js +118 -37
  307. package/dist/integrations/ruvector/brain-search.d.ts +1 -1
  308. package/dist/integrations/ruvector/brain-search.js +1 -1
  309. package/dist/integrations/ruvector/brain-shared.d.ts +4 -2
  310. package/dist/integrations/ruvector/brain-shared.js +11 -4
  311. package/dist/integrations/ruvector/brain-table-ddl.d.ts +2 -2
  312. package/dist/integrations/ruvector/brain-table-ddl.js +20 -8
  313. package/dist/integrations/ruvector/cognitive-container.js +1 -1
  314. package/dist/integrations/ruvector/rvf-dual-writer.d.ts +4 -0
  315. package/dist/integrations/ruvector/rvf-dual-writer.js +57 -9
  316. package/dist/integrations/ruvector/rvf-store-integrity.js +1 -1
  317. package/dist/kernel/unified-memory-schemas.d.ts +4 -3
  318. package/dist/kernel/unified-memory-schemas.js +19 -9
  319. package/dist/kernel/unified-memory.d.ts +2 -0
  320. package/dist/kernel/unified-memory.js +19 -0
  321. package/dist/learning/embed-and-insert-pattern.js +6 -3
  322. package/dist/learning/embedding-space.d.ts +50 -0
  323. package/dist/learning/embedding-space.js +128 -0
  324. package/dist/learning/evidence-admission-store.d.ts +15 -0
  325. package/dist/learning/evidence-admission-store.js +68 -0
  326. package/dist/learning/index.d.ts +4 -0
  327. package/dist/learning/index.js +2 -0
  328. package/dist/learning/learning-evidence-admission.d.ts +44 -0
  329. package/dist/learning/learning-evidence-admission.js +97 -0
  330. package/dist/learning/pattern-store.d.ts +5 -0
  331. package/dist/learning/pattern-store.js +36 -7
  332. package/dist/learning/qe-flywheel/coupled-anchor.d.ts +8 -0
  333. package/dist/learning/qe-flywheel/coupled-anchor.js +46 -3
  334. package/dist/learning/qe-reasoning-bank.js +4 -0
  335. package/dist/learning/real-embeddings.d.ts +3 -0
  336. package/dist/learning/real-embeddings.js +40 -3
  337. package/dist/learning/real-qe-reasoning-bank.js +7 -3
  338. package/dist/learning/rvf-pattern-migration.d.ts +2 -0
  339. package/dist/learning/rvf-pattern-migration.js +5 -3
  340. package/dist/learning/rvf-pattern-store.d.ts +3 -0
  341. package/dist/learning/rvf-pattern-store.js +21 -1
  342. package/dist/learning/sqlite-persistence.d.ts +7 -2
  343. package/dist/learning/sqlite-persistence.js +58 -21
  344. package/dist/mcp/bundle.js +607 -443
  345. package/dist/mcp/handlers/memory-handlers.js +6 -2
  346. package/dist/migrations/20260830_add_learning_evidence_tables.d.ts +7 -0
  347. package/dist/migrations/20260830_add_learning_evidence_tables.js +173 -0
  348. package/dist/persistence/rvf-migration-adapter.d.ts +2 -0
  349. package/dist/persistence/rvf-migration-adapter.js +56 -12
  350. package/dist/shared/llm/billing-modes.d.ts +5 -0
  351. package/dist/shared/llm/billing-modes.js +42 -3
  352. package/dist/shared/llm/index.d.ts +4 -1
  353. package/dist/shared/llm/index.js +5 -1
  354. package/dist/shared/llm/interfaces.d.ts +34 -3
  355. package/dist/shared/llm/interfaces.js +17 -0
  356. package/dist/shared/llm/llm-router-service.d.ts +8 -0
  357. package/dist/shared/llm/llm-router-service.js +21 -3
  358. package/dist/shared/llm/provider-manager.js +8 -1
  359. package/dist/shared/llm/provider-registry.d.ts +135 -0
  360. package/dist/shared/llm/provider-registry.js +227 -0
  361. package/dist/shared/llm/providers/external-cli.d.ts +129 -0
  362. package/dist/shared/llm/providers/external-cli.js +385 -0
  363. package/dist/shared/llm/router/config-store.d.ts +14 -0
  364. package/dist/shared/llm/router/config-store.js +102 -14
  365. package/dist/shared/llm/router/external-provider-config.d.ts +47 -0
  366. package/dist/shared/llm/router/external-provider-config.js +105 -0
  367. package/dist/shared/llm/router/types.d.ts +50 -4
  368. package/dist/shared/llm/router/types.js +10 -0
  369. package/dist/shared/llm/translation/message-formatter.js +7 -1
  370. package/dist/shared/sql-safety.js +4 -0
  371. package/dist/skills/qe-court/cli.d.ts +3 -0
  372. package/dist/skills/qe-court/cli.js +54 -0
  373. package/dist/verification/adversarial-verify/calibrate.d.ts +46 -2
  374. package/dist/verification/adversarial-verify/calibrate.js +104 -2
  375. package/dist/verification/adversarial-verify/index.d.ts +1 -1
  376. package/dist/verification/adversarial-verify/index.js +1 -1
  377. package/package.json +12 -3
  378. package/dist/cli/chunks/adapter-YBSKQFQ4.js +0 -2
  379. package/dist/cli/chunks/aqe-learning-engine-3H7DRDD4.js +0 -2
  380. package/dist/cli/chunks/base-ZTD6PFD7.js +0 -2
  381. package/dist/cli/chunks/brain-handler-FV2AJZ4A.js +0 -89
  382. package/dist/cli/chunks/browser-workflow-GKWDM25H.js +0 -2
  383. package/dist/cli/chunks/chunk-2CBEQV6R.js +0 -2
  384. package/dist/cli/chunks/chunk-4ZQOJ7Q2.js +0 -2
  385. package/dist/cli/chunks/chunk-CYQRZ645.js +0 -2
  386. package/dist/cli/chunks/chunk-FXKOHZBN.js +0 -2
  387. package/dist/cli/chunks/chunk-GJTGHVAX.js +0 -65
  388. package/dist/cli/chunks/chunk-GP5QBJVO.js +0 -3
  389. package/dist/cli/chunks/chunk-JGXP67BP.js +0 -2
  390. package/dist/cli/chunks/chunk-SW56PB22.js +0 -2
  391. package/dist/cli/chunks/chunk-T5M4TZRB.js +0 -12
  392. package/dist/cli/chunks/chunk-UDSNWQQI.js +0 -2
  393. package/dist/cli/chunks/chunk-VC77SDNH.js +0 -9
  394. package/dist/cli/chunks/chunk-WRMJWQUI.js +0 -12
  395. package/dist/cli/chunks/chunk-YXUFGDGS.js +0 -2
  396. package/dist/cli/chunks/client-4Q5JE7RY.js +0 -2
  397. package/dist/cli/chunks/core-handlers-4GKEYGPS.js +0 -2
  398. package/dist/cli/chunks/cross-domain-router-PBJ2ZGPJ.js +0 -2
  399. package/dist/cli/chunks/dream-4EXVFHUJ.js +0 -2
  400. package/dist/cli/chunks/embed-and-insert-pattern-COAZZGS6.js +0 -3
  401. package/dist/cli/chunks/heartbeat-scheduler-UNEYR3WR.js +0 -2
  402. package/dist/cli/chunks/hnsw-adapter-JQG66H4L.js +0 -2
  403. package/dist/cli/chunks/hnsw-index-2NOROILM.js +0 -2
  404. package/dist/cli/chunks/hybrid-router-FXTAJATE.js +0 -2
  405. package/dist/cli/chunks/impact-analyzer-VHZSBWMT.js +0 -2
  406. package/dist/cli/chunks/init-wizard-EML4OET2.js +0 -2
  407. package/dist/cli/chunks/kernel-TMRJOEO2.js +0 -2
  408. package/dist/cli/chunks/knowledge-graph-FMKVCMJQ.js +0 -2
  409. package/dist/cli/chunks/learning-II2U3EV2.js +0 -119
  410. package/dist/cli/chunks/llm-router-WC66OXZH.js +0 -36
  411. package/dist/cli/chunks/llm-router-service-GOSVGMKM.js +0 -2
  412. package/dist/cli/chunks/load-test-WIRGDZIA.js +0 -2
  413. package/dist/cli/chunks/memory-backend-XBBIXDZU.js +0 -2
  414. package/dist/cli/chunks/memory-handlers-SQHNK3DK.js +0 -2
  415. package/dist/cli/chunks/pattern-null-store-PFLKHRVU.js +0 -2
  416. package/dist/cli/chunks/protocol-executor-GAMNY2JB.js +0 -2
  417. package/dist/cli/chunks/provider-manager-VTIG5AKU.js +0 -2
  418. package/dist/cli/chunks/qe-reasoning-bank-KAX63PXV.js +0 -2
  419. package/dist/cli/chunks/queen-coordinator-UYW2MDKI.js +0 -2
  420. package/dist/cli/chunks/real-embeddings-HHR75AR5.js +0 -2
  421. package/dist/cli/chunks/router-NVDU7IIA.js +0 -2
  422. package/dist/cli/chunks/routing-feedback-KHR3J2J3.js +0 -2
  423. package/dist/cli/chunks/rvf-dual-writer-43L75WLF.js +0 -2
  424. package/dist/cli/chunks/rvf-migration-adapter-Y5OVCYTO.js +0 -2
  425. package/dist/cli/chunks/rvf-migration-coordinator-NEPDFB3N.js +0 -2
  426. package/dist/cli/chunks/rvf-native-adapter-PQ4IOTZU.js +0 -2
  427. package/dist/cli/chunks/safe-db-QHSFV63M.js +0 -2
  428. package/dist/cli/chunks/schedule-JGZFHJGM.js +0 -2
  429. package/dist/cli/chunks/scheduler-NGCDQIW5.js +0 -2
  430. package/dist/cli/chunks/sqlite-persistence-3JSNWL6I.js +0 -2
  431. package/dist/cli/chunks/status-handler-CTXOH3FX.js +0 -47
  432. package/dist/cli/chunks/token-bootstrap-3P22AYZ4.js +0 -2
  433. package/dist/cli/chunks/unified-memory-4VO5KSHP.js +0 -2
  434. package/dist/cli/chunks/unified-memory-hnsw-ZR2FZXOB.js +0 -2
  435. package/dist/cli/chunks/unified-persistence-VFPW5MFM.js +0 -2
  436. package/dist/cli/chunks/visual-security-SNADRUPR.js +0 -2
  437. package/dist/cli/chunks/witness-chain-2TXUTEJE.js +0 -2
  438. package/dist/cli/chunks/workflow-orchestrator-ON6UYRVE.js +0 -2
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.11");process.exit(0)}
2
- import{b as pe}from"./chunk-VHNAN7E2.js";import{a as dt}from"./chunk-HV6LJ57R.js";import{a as mt,b as gt}from"./chunk-PBJ5I2NS.js";import{j as I}from"./chunk-FPX4JSFH.js";import{a as lt,b as ut}from"./chunk-HGPMS6JL.js";import{a as nt}from"./chunk-WINYWMQP.js";import{a as at,b as ot,c as ct}from"./chunk-5364DBZG.js";import{b as st}from"./chunk-P736OKQN.js";import{a as ge}from"./chunk-36ONUM43.js";import{i as w,m as me}from"./chunk-2Y3PW5EJ.js";import{a as an}from"./chunk-CYQRZ645.js";import{c as it}from"./chunk-QYHRDBKI.js";import{b as M,d as rt}from"./chunk-TZA45FI7.js";import{a as v,b,c as y}from"./chunk-XDK2TPI5.js";import{a as h,b as tt,c as k}from"./chunk-TCVEXQLL.js";import{i as T}from"./chunk-PJNIDDER.js";import{R as on,S as cn}from"./chunk-NHL37QAZ.js";import{c as z,e as sn,g as et}from"./chunk-LUAXQB57.js";function ft(a){let e=[],t=0;if(a.fileCount!==void 0&&(a.fileCount>20?(t+=25,e.push({name:"very-high-file-count",weight:25,description:`Task involves ${a.fileCount} files (>20)`})):a.fileCount>10?(t+=20,e.push({name:"high-file-count",weight:20,description:`Task involves ${a.fileCount} files (>10)`})):a.fileCount>5&&(t+=10,e.push({name:"moderate-file-count",weight:10,description:`Task involves ${a.fileCount} files (>5)`}))),a.domain&&(dn.includes(a.domain)?(t+=30,e.push({name:"complex-domain",weight:30,description:`Domain '${a.domain}' requires complex reasoning`})):mn.includes(a.domain)&&(t+=15,e.push({name:"moderate-domain",weight:15,description:`Domain '${a.domain}' has moderate complexity`}))),a.crossComponent&&(t+=25,e.push({name:"cross-component",weight:25,description:"Task spans multiple components/modules"})),a.priority==="critical"?(t+=25,e.push({name:"critical-priority",weight:25,description:"Critical priority requires careful attention"})):a.priority==="high"&&(t+=15,e.push({name:"high-priority",weight:15,description:"High priority task"})),a.requiredCapabilities){let r=a.requiredCapabilities.filter(s=>gn.includes(s)).length;if(r>0){let s=Math.min(20,r*10);t+=s,e.push({name:"complex-capabilities",weight:s,description:`Requires ${r} complex capabilit${r===1?"y":"ies"}`})}}a.requiresExternalApis&&(t+=10,e.push({name:"external-apis",weight:10,description:"Requires external API integration"})),a.involvesDatabaseOps&&(t+=10,e.push({name:"database-ops",weight:10,description:"Involves database operations"})),a.timeSensitive&&(t+=5,e.push({name:"time-sensitive",weight:5,description:"Time-sensitive task"})),a.estimatedLinesAffected!==void 0&&(a.estimatedLinesAffected>500?(t+=15,e.push({name:"large-change",weight:15,description:`Estimated ${a.estimatedLinesAffected} lines affected (>500)`})):a.estimatedLinesAffected>200&&(t+=10,e.push({name:"medium-change",weight:10,description:`Estimated ${a.estimatedLinesAffected} lines affected (>200)`}))),(a.type==="security-scan"||a.type==="vulnerability-assessment")&&(t+=20,e.push({name:"security-task",weight:20,description:"Security-related task requires careful analysis"}));let n=t>=S.critical?"critical":t>=S.complex?"complex":t>=S.moderate?"moderate":"simple",i=pn[n];return{complexity:n,recommendedModel:i,factors:e,score:t,timestamp:new Date}}var dn,mn,gn,S,pn,yt=z(()=>{"use strict";dn=["security-compliance","chaos-resilience","defect-intelligence"],mn=["code-intelligence","contract-testing","quality-assessment","learning-optimization"],gn=["sast","dast","vulnerability","owasp","chaos-testing","resilience","fault-injection","mutation-testing"],S={critical:70,complex:45,moderate:20},pn={critical:"opus",complex:"sonnet",moderate:"sonnet",simple:"haiku"}});var R,Te=z(()=>{"use strict";R=class{weightsInputHidden;weightsHiddenOutput;biasHidden;biasOutput;learningRate;constructor(e=.01){this.learningRate=e,this.weightsInputHidden=this.xavierInit(4,32),this.weightsHiddenOutput=this.xavierInit(32,3),this.biasHidden=new Float32Array(32),this.biasOutput=new Float32Array(3)}xavierInit(e,t){let n=Math.sqrt(2/(e+t)),i=new Float32Array(e*t);for(let r=0;r<i.length;r++){let s=Math.random(),o=Math.random(),l=Math.sqrt(-2*Math.log(Math.max(s,1e-10)))*Math.cos(2*Math.PI*o);i[r]=l*n}return i}forward(e){if(e.length!==4)throw new Error(`Expected 4 features, got ${e.length}`);let t=new Float32Array(32);for(let i=0;i<32;i++){let r=this.biasHidden[i];for(let s=0;s<4;s++)r+=e[s]*this.weightsInputHidden[s*32+i];t[i]=Math.max(0,r)}let n=new Float32Array(3);for(let i=0;i<3;i++){let r=this.biasOutput[i];for(let s=0;s<32;s++)r+=t[s]*this.weightsHiddenOutput[s*3+i];n[i]=r}return this.softmax(n)}softmax(e){let t=Math.max(...e),n=new Float32Array(e.length),i=0;for(let s=0;s<e.length;s++)n[s]=Math.exp(e[s]-t),i+=n[s];let r=[];for(let s=0;s<e.length;s++)r.push(n[s]/i);return r}updateWeights(e,t,n){let i=new Float32Array(32);for(let c=0;c<32;c++){let u=this.biasHidden[c];for(let d=0;d<4;d++)u+=e[d]*this.weightsInputHidden[d*32+c];i[c]=Math.max(0,u)}let r=new Float32Array(3);for(let c=0;c<3;c++){let u=this.biasOutput[c];for(let d=0;d<32;d++)u+=i[d]*this.weightsHiddenOutput[d*3+c];r[c]=u}let s=this.softmax(r),o=new Float32Array(3);for(let c=0;c<3;c++)o[c]=(c===t?1:0)-s[c],o[c]*=n*this.learningRate;for(let c=0;c<32;c++)for(let u=0;u<3;u++)this.weightsHiddenOutput[c*3+u]+=i[c]*o[u];for(let c=0;c<3;c++)this.biasOutput[c]+=o[c];let l=new Float32Array(32);for(let c=0;c<32;c++){if(i[c]<=0)continue;let u=0;for(let d=0;d<3;d++)u+=o[d]*this.weightsHiddenOutput[c*3+d];l[c]=u}for(let c=0;c<4;c++)for(let u=0;u<32;u++)this.weightsInputHidden[c*32+u]+=e[c]*l[u];for(let c=0;c<32;c++)this.biasHidden[c]+=l[c]}serialize(){return{weightsInputHidden:Array.from(this.weightsInputHidden),weightsHiddenOutput:Array.from(this.weightsHiddenOutput),biasHidden:Array.from(this.biasHidden),biasOutput:Array.from(this.biasOutput)}}deserialize(e){e.weightsInputHidden.length===128&&(this.weightsInputHidden=new Float32Array(e.weightsInputHidden)),e.weightsHiddenOutput.length===96&&(this.weightsHiddenOutput=new Float32Array(e.weightsHiddenOutput)),e.biasHidden.length===32&&(this.biasHidden=new Float32Array(e.biasHidden)),e.biasOutput.length===3&&(this.biasOutput=new Float32Array(e.biasOutput))}}});var vt={};sn(vt,{NeuralTinyDancerRouter:()=>G,SimpleNeuralRouter:()=>R,createNeuralTinyDancerRouter:()=>Sn});import{performance as Tt}from"perf_hooks";function Sn(a){return new G(a)}var hn,fn,yn,Tn,vn,Cn,bn,kn,G,Ct=z(()=>{"use strict";ve();Te();Te();hn=1e3,fn=.1,yn=.2,Tn=50,vn=.01,Cn=["haiku","sonnet","opus"],bn={haiku:0,sonnet:1,opus:2},kn={"test-generation":.1,"test-execution":.15,"coverage-analysis":.2,"quality-assessment":.3,"requirements-validation":.35,"code-intelligence":.4,"contract-testing":.45,"visual-accessibility":.5,"learning-optimization":.55,"defect-intelligence":.7,"chaos-resilience":.8,"security-compliance":.9},G=class{ruleRouter;neuralNet;circuitBreakerThreshold;shadowModeDecisionLimit;shadowModeMaxDisagreement;shadowModeActive;shadowDecisions=[];shadowDisagreements=0;circuitBreakerTripped=!1;recentOutcomes=[];totalNeuralDecisions=0;totalWeightUpdates=0;neuralPrimary=!1;calibrationScores=[];maxCalibrationScores=500;domainSuccessRates=new Map;config;nativeRouterAvailable=!1;constructor(e={}){this.config=e,this.ruleRouter=new F(e),this.neuralNet=new R(e.learningRate??vn),this.circuitBreakerThreshold=e.circuitBreakerThreshold??yn,this.shadowModeDecisionLimit=e.shadowModeDecisions??hn,this.shadowModeMaxDisagreement=e.shadowModeMaxDisagreement??fn,e.forceShadowMode!==void 0?(this.shadowModeActive=e.forceShadowMode,this.neuralPrimary=!e.forceShadowMode):(this.shadowModeActive=!0,this.neuralPrimary=!1),this.tryLoadNativeRouter()}tryLoadNativeRouter(){this.nativeRouterAvailable=!1}async route(e){let t=Tt.now(),n=await this.ruleRouter.route(e);if(this.circuitBreakerTripped)return n;let i=this.extractFeatures(e,n.classification),r;try{r=this.neuralNet.forward(i)}catch{return this.tripCircuitBreaker(),n}let s=this.argmax(r),o=Cn[s],l=r[s];if(this.totalNeuralDecisions++,this.shadowModeActive){let m=n.model===o;return m||this.shadowDisagreements++,this.shadowDecisions.push({taskDescription:e.description.slice(0,100),ruleDecision:n.model,neuralDecision:o,agreed:m,neuralConfidence:l,timestamp:new Date}),this.evaluateShadowModeExit(),n}let c=Tt.now()-t,u=this.computeEmpiricalConfidenceBounds(r);return l<.3||u.calibrationScore>.8?n:{model:o,confidence:l,uncertainty:1-l,triggerMultiModel:n.triggerMultiModel,triggerHumanReview:n.triggerHumanReview,complexity:n.complexity,classification:n.classification,latencyMs:c,reasoning:this.buildNeuralReasoning(o,l,r,n,u)}}extractFeatures(e,t){let n=Math.min(1,t.score/100),i=e.description.length,r=e.context?.code?.length??0,s=(i+r)/4,o=Math.min(1,s/1e4),l=e.domain??"",c=kn[l]??.25,u=this.domainSuccessRates.get(l),d=u?u.success/Math.max(1,u.total):.7;return[n,o,c,d]}recordNeuralOutcome(e,t,n,i=n?1:0,r=t.model,s=0){this.ruleRouter.recordOutcome(e,t,n,i,r,s);let o=e.domain??"unknown",l=this.domainSuccessRates.get(o)??{success:0,total:0};l.total++,n&&l.success++,this.domainSuccessRates.set(o,l),this.recentOutcomes.push(n),this.recentOutcomes.length>Tn&&this.recentOutcomes.shift(),this.checkCircuitBreaker();let c=this.extractFeatures(e,t.classification),u=bn[r],d=(i-.5)*2;try{this.neuralNet.updateWeights(c,u,d),this.totalWeightUpdates++}catch{}let m=this.neuralNet.forward(c),p=this.argmax(m),f=1-m[u];this.calibrationScores.push(f),this.calibrationScores.length>this.maxCalibrationScores&&this.calibrationScores.shift()}computeEmpiricalConfidenceBounds(e){let n=Math.max(...e),i=1-n;if(this.calibrationScores.length<10)return{lower:0,upper:1,coverageLevel:.9,calibrationScore:i};let r=[...this.calibrationScores].sort((l,c)=>l-c),s=Math.ceil(.9*r.length)-1,o=r[Math.min(s,r.length-1)];return{lower:Math.max(0,n-o),upper:Math.min(1,n+o),coverageLevel:.9,calibrationScore:i}}computeConformalBounds(e){return this.computeEmpiricalConfidenceBounds(e)}evaluateShadowModeExit(){if(!this.shadowModeActive||this.config.forceShadowMode===!0)return;let e=this.shadowDecisions.length;if(e<this.shadowModeDecisionLimit)return;this.shadowDisagreements/e<=this.shadowModeMaxDisagreement&&(this.shadowModeActive=!1,this.neuralPrimary=!0)}checkCircuitBreaker(){if(this.recentOutcomes.length<10)return;let t=this.recentOutcomes.filter(n=>!n).length/this.recentOutcomes.length;t>this.circuitBreakerThreshold?this.tripCircuitBreaker():this.circuitBreakerTripped&&t<this.circuitBreakerThreshold*.5&&(this.circuitBreakerTripped=!1)}tripCircuitBreaker(){this.circuitBreakerTripped=!0,this.neuralPrimary=!1}buildNeuralReasoning(e,t,n,i,r){let s=[];return s.push(`[Neural] Routing to ${e.toUpperCase()}`),s.push(`with ${(t*100).toFixed(0)}% neural confidence.`),s.push(`Tier probabilities: haiku=${(n[0]*100).toFixed(0)}%,`),s.push(`sonnet=${(n[1]*100).toFixed(0)}%,`),s.push(`opus=${(n[2]*100).toFixed(0)}%.`),e!==i.model&&s.push(`Rule-based would choose ${i.model.toUpperCase()}.`),s.push(`Empirical bounds: [${r.lower.toFixed(2)}, ${r.upper.toFixed(2)}]`),s.push(`at ${(r.coverageLevel*100).toFixed(0)}% coverage.`),s.join(" ")}argmax(e){let t=0,n=e[0];for(let i=1;i<e.length;i++)e[i]>n&&(n=e[i],t=i);return t}getNeuralStats(){let e=this.shadowDecisions.length,t=e>0?this.shadowDisagreements/e:0,n=this.recentOutcomes.filter(r=>!r).length,i=this.recentOutcomes.length>0?n/this.recentOutcomes.length:0;return{shadowModeActive:this.shadowModeActive,shadowDecisions:e,disagreementRate:t,circuitBreakerTripped:this.circuitBreakerTripped,recentErrorRate:i,totalNeuralDecisions:this.totalNeuralDecisions,totalWeightUpdates:this.totalWeightUpdates,neuralPrimary:this.neuralPrimary}}getShadowDecisionLogs(){return this.shadowDecisions}getRuleRouter(){return this.ruleRouter}getNeuralNet(){return this.neuralNet}isNativeRouterAvailable(){return this.nativeRouterAvailable}isShadowModeActive(){return this.shadowModeActive}isNeuralPrimary(){return this.neuralPrimary}isCircuitBreakerTripped(){return this.circuitBreakerTripped}resetCircuitBreaker(){this.circuitBreakerTripped=!1,this.recentOutcomes=[]}getStats(){return this.ruleRouter.getStats()}getConfig(){return this.ruleRouter.getConfig()}reset(){this.ruleRouter.reset(),this.shadowDecisions=[],this.shadowDisagreements=0,this.circuitBreakerTripped=!1,this.recentOutcomes=[],this.totalNeuralDecisions=0,this.totalWeightUpdates=0,this.calibrationScores=[],this.domainSuccessRates.clear(),this.config.forceShadowMode!==void 0?(this.shadowModeActive=this.config.forceShadowMode,this.neuralPrimary=!this.config.forceShadowMode):(this.shadowModeActive=!0,this.neuralPrimary=!1)}}});import{performance as bt}from"perf_hooks";function kt(a){try{let{getRuVectorFeatureFlags:e}=(cn(),et(on));if(e().useNeuralRouting){let{NeuralTinyDancerRouter:n}=(Ct(),et(vt));return new n(a)}}catch(e){process.env.DEBUG&&console.debug("[Router] Neural router unavailable, using rule-based:",e instanceof Error?e.message:e)}return new F(a)}var F,ve=z(()=>{"use strict";yt();F=class{confidenceThreshold;uncertaintyThreshold;securityConfidenceThreshold;enableLearning;verbose;executor;totalRouted=0;routesByModel={haiku:0,sonnet:0,opus:0};routesByComplexity={simple:0,moderate:0,complex:0,critical:0};multiModelTriggers=0;humanReviewTriggers=0;advisorConsultations=0;totalConfidence=0;totalLatencyMs=0;outcomes=[];maxOutcomes=1e3;constructor(e={}){this.confidenceThreshold=e.confidenceThreshold??.8,this.uncertaintyThreshold=e.uncertaintyThreshold??.2,this.securityConfidenceThreshold=e.securityConfidenceThreshold??.85,this.enableLearning=e.enableLearning??!0,this.verbose=e.verbose??!1,this.executor=e.executor}hasExecutor(){return this.executor!==void 0}async routeWithAdvisor(e,t){let n=await this.route(e);if(!n.triggerMultiModel||!this.executor||!t)return{route:n};let i=await this.executor.consult(t,{agentName:e.agentId??e.id??"unknown",triggerReason:`tiny_dancer.confidence=${n.confidence.toFixed(2)}<${this.confidenceThreshold}`});return this.advisorConsultations++,{route:n,advisor:i}}async route(e){let t=bt.now(),n=ft(e),i=this.calculateConfidence(n),r=1-i,s=this.isSecurityTask(e),o=s&&i<this.securityConfidenceThreshold||i<this.confidenceThreshold&&n.complexity!=="simple",l=r>this.uncertaintyThreshold||s&&n.complexity==="critical",c=bt.now()-t,u=this.buildReasoning(n,i,s,o,l),d={model:n.recommendedModel,confidence:i,uncertainty:r,triggerMultiModel:o,triggerHumanReview:l,complexity:n.complexity,classification:n,latencyMs:c,reasoning:u};return this.updateStats(d),this.verbose&&console.log(`[TinyDancer] Route: ${n.recommendedModel} (complexity=${n.complexity}, confidence=${(i*100).toFixed(1)}%)`),d}calculateConfidence(e){let{score:t,complexity:n}=e;if(n==="simple"&&t<10)return .9;if(n==="critical"&&t>85)return .92;let i=[S.moderate,S.complex,S.critical],r=1/0;for(let d of i){let m=Math.abs(t-d);m<r&&(r=m)}let s=.55,o=.35,l=Math.min(r/25,1),c=s+l*o,u=n!=="simple"?Math.min(.05,e.factors.length*.01):0;return Math.min(.95,c+u)}isSecurityTask(e){let t=e;if(t.type==="security-scan"||t.type==="vulnerability-assessment"||e.domain==="security-compliance")return!0;let n=["sast","dast","vulnerability","owasp","security-scanning"];if(e.requiredCapabilities?.some(s=>n.includes(s)))return!0;let i=["security","vulnerability","cve","owasp","exploit","injection"],r=e.description.toLowerCase();return!!i.some(s=>r.includes(s))}buildReasoning(e,t,n,i,r){let s=[];if(s.push(`Routing to ${e.recommendedModel.toUpperCase()}`),s.push(`(complexity: ${e.complexity}, score: ${e.score})`),s.push(`with ${(t*100).toFixed(0)}% confidence.`),e.factors.length>0){let o=e.factors.slice(0,3).map(l=>l.name).join(", ");s.push(`Key factors: ${o}.`)}return n&&s.push("Security-sensitive task detected."),i&&s.push("Multi-model verification recommended due to uncertainty."),r&&s.push("Human review flagged due to high uncertainty or criticality."),s.join(" ")}updateStats(e){this.totalRouted++,this.routesByModel[e.model]++,this.routesByComplexity[e.complexity]++,this.totalConfidence+=e.confidence,this.totalLatencyMs+=e.latencyMs,e.triggerMultiModel&&this.multiModelTriggers++,e.triggerHumanReview&&this.humanReviewTriggers++}recordOutcome(e,t,n,i=n?1:0,r=t.model,s=0){if(!this.enableLearning)return;let o={task:e,routeResult:t,success:n,qualityScore:i,actualModelUsed:r,durationMs:s,timestamp:new Date};this.outcomes.push(o),this.outcomes.length>this.maxOutcomes&&this.outcomes.shift(),this.verbose&&console.log(`[TinyDancer] Recorded outcome: success=${n}, quality=${(i*100).toFixed(0)}%, model=${r}`)}getStats(){return{totalRouted:this.totalRouted,routesByModel:{...this.routesByModel},routesByComplexity:{...this.routesByComplexity},multiModelTriggers:this.multiModelTriggers,advisorConsultations:this.advisorConsultations,humanReviewTriggers:this.humanReviewTriggers,avgConfidence:this.totalRouted>0?this.totalConfidence/this.totalRouted:0,avgLatencyMs:this.totalRouted>0?this.totalLatencyMs/this.totalRouted:0,outcomesRecorded:this.outcomes.length}}getOutcomes(){return this.outcomes}getSuccessRateByModel(){let e={haiku:{success:0,total:0},sonnet:{success:0,total:0},opus:{success:0,total:0}};for(let t of this.outcomes){let n=t.actualModelUsed;e[n].total++,t.success&&e[n].success++}return{haiku:e.haiku.total>0?e.haiku.success/e.haiku.total:0,sonnet:e.sonnet.total>0?e.sonnet.success/e.sonnet.total:0,opus:e.opus.total>0?e.opus.success/e.opus.total:0}}reset(){this.totalRouted=0,this.routesByModel={haiku:0,sonnet:0,opus:0},this.routesByComplexity={simple:0,moderate:0,complex:0,critical:0},this.multiModelTriggers=0,this.advisorConsultations=0,this.humanReviewTriggers=0,this.totalConfidence=0,this.totalLatencyMs=0,this.outcomes=[]}getConfig(){return{confidenceThreshold:this.confidenceThreshold,uncertaintyThreshold:this.uncertaintyThreshold,securityConfidenceThreshold:this.securityConfidenceThreshold,enableLearning:this.enableLearning,verbose:this.verbose}}}});var ln={enableConsoleLog:!0,maxEntries:1e3,logPrefix:"[TASK]"},q=class{entries=[];config;constructor(e={}){this.config={...ln,...e}}log(e,t,n){let i={timestamp:new Date,operation:e,taskId:t,agentId:n?.agentId,domain:n?.domain,details:n?.details};if(this.entries.push(i),this.entries.length>this.config.maxEntries&&this.entries.splice(0,this.entries.length-this.config.maxEntries),this.config.enableConsoleLog){let r=n?.agentId?` by ${n.agentId}`:"",s=n?.domain?` (${n.domain})`:"";console.log(`${this.config.logPrefix} ${e.toUpperCase()} ${t}${r}${s}`)}}logSubmit(e,t){this.log("submit",e,{details:t})}logAssign(e,t,n){this.log("assign",e,{agentId:t,domain:n})}logReassign(e,t,n,i){this.log("reassign",e,{agentId:n,domain:i,details:{fromAgent:t}})}logComplete(e,t){this.log("complete",e,{agentId:t})}logFail(e,t,n){this.log("fail",e,{agentId:t,details:n?{error:n}:void 0})}logCancel(e){this.log("cancel",e)}logSteal(e,t,n){this.log("steal",e,{domain:n,details:{fromDomain:t}})}logQueue(e,t){this.log("queue",e,{details:{position:t}})}logDequeue(e){this.log("dequeue",e)}getEntries(e){let t=[...this.entries];e&&(e.operation&&(t=t.filter(i=>i.operation===e.operation)),e.taskId&&(t=t.filter(i=>i.taskId===e.taskId)),e.agentId&&(t=t.filter(i=>i.agentId===e.agentId)),e.domain&&(t=t.filter(i=>i.domain===e.domain)),e.fromTimestamp&&(t=t.filter(i=>i.timestamp>=e.fromTimestamp)),e.toTimestamp&&(t=t.filter(i=>i.timestamp<=e.toTimestamp)));let n=e?.limit??t.length;return t.slice(-n)}getStatistics(){let e={submit:0,assign:0,reassign:0,complete:0,fail:0,cancel:0,steal:0,queue:0,dequeue:0},t=new Set,n=new Set;for(let i of this.entries)e[i.operation]++,t.add(i.taskId),i.agentId&&n.add(i.agentId);return{totalEntries:this.entries.length,operationCounts:e,taskCount:t.size,agentCount:n.size}}clear(){this.entries.length=0}};function he(a){return new q(a)}me();rt();var fe=class{memory;initialized=!1;constructor(e){this.memory=e??w()}async initialize(){this.initialized||(this.memory.isInitialized()||await this.memory.initialize(),this.initialized=!0)}async saveSnapshot(e){this.ensureInitialized();let t=T();return this.memory.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.14.0");process.exit(0)}
2
+ import{b as pe}from"./chunk-TKYEP7OR.js";import{a as dt}from"./chunk-XXFKN7LB.js";import{a as mt,b as gt}from"./chunk-E4NU4BJA.js";import{j as I}from"./chunk-ZCVJCCQQ.js";import{a as lt,b as ut}from"./chunk-SUSMHSXT.js";import{a as nt}from"./chunk-CIUOC5F3.js";import{a as at,b as ot,c as ct}from"./chunk-N2YAUDAV.js";import{b as st}from"./chunk-5MZF4N4Q.js";import{a as ge}from"./chunk-A7SKM6JL.js";import{k as w,o as me}from"./chunk-7RAB2BZY.js";import{a as an}from"./chunk-R2B6EE45.js";import{c as it}from"./chunk-JY4VZ6BN.js";import{b as M,d as rt}from"./chunk-HQHLHSJO.js";import{a as v,b,c as y}from"./chunk-JGROLJ33.js";import{a as h,b as tt,c as k}from"./chunk-XITTURP2.js";import{i as T}from"./chunk-FOHYBR3O.js";import{R as on,S as cn}from"./chunk-ENGKLFLY.js";import{c as z,e as sn,g as et}from"./chunk-PEW6FZ47.js";function ft(a){let e=[],t=0;if(a.fileCount!==void 0&&(a.fileCount>20?(t+=25,e.push({name:"very-high-file-count",weight:25,description:`Task involves ${a.fileCount} files (>20)`})):a.fileCount>10?(t+=20,e.push({name:"high-file-count",weight:20,description:`Task involves ${a.fileCount} files (>10)`})):a.fileCount>5&&(t+=10,e.push({name:"moderate-file-count",weight:10,description:`Task involves ${a.fileCount} files (>5)`}))),a.domain&&(dn.includes(a.domain)?(t+=30,e.push({name:"complex-domain",weight:30,description:`Domain '${a.domain}' requires complex reasoning`})):mn.includes(a.domain)&&(t+=15,e.push({name:"moderate-domain",weight:15,description:`Domain '${a.domain}' has moderate complexity`}))),a.crossComponent&&(t+=25,e.push({name:"cross-component",weight:25,description:"Task spans multiple components/modules"})),a.priority==="critical"?(t+=25,e.push({name:"critical-priority",weight:25,description:"Critical priority requires careful attention"})):a.priority==="high"&&(t+=15,e.push({name:"high-priority",weight:15,description:"High priority task"})),a.requiredCapabilities){let r=a.requiredCapabilities.filter(s=>gn.includes(s)).length;if(r>0){let s=Math.min(20,r*10);t+=s,e.push({name:"complex-capabilities",weight:s,description:`Requires ${r} complex capabilit${r===1?"y":"ies"}`})}}a.requiresExternalApis&&(t+=10,e.push({name:"external-apis",weight:10,description:"Requires external API integration"})),a.involvesDatabaseOps&&(t+=10,e.push({name:"database-ops",weight:10,description:"Involves database operations"})),a.timeSensitive&&(t+=5,e.push({name:"time-sensitive",weight:5,description:"Time-sensitive task"})),a.estimatedLinesAffected!==void 0&&(a.estimatedLinesAffected>500?(t+=15,e.push({name:"large-change",weight:15,description:`Estimated ${a.estimatedLinesAffected} lines affected (>500)`})):a.estimatedLinesAffected>200&&(t+=10,e.push({name:"medium-change",weight:10,description:`Estimated ${a.estimatedLinesAffected} lines affected (>200)`}))),(a.type==="security-scan"||a.type==="vulnerability-assessment")&&(t+=20,e.push({name:"security-task",weight:20,description:"Security-related task requires careful analysis"}));let n=t>=S.critical?"critical":t>=S.complex?"complex":t>=S.moderate?"moderate":"simple",i=pn[n];return{complexity:n,recommendedModel:i,factors:e,score:t,timestamp:new Date}}var dn,mn,gn,S,pn,yt=z(()=>{"use strict";dn=["security-compliance","chaos-resilience","defect-intelligence"],mn=["code-intelligence","contract-testing","quality-assessment","learning-optimization"],gn=["sast","dast","vulnerability","owasp","chaos-testing","resilience","fault-injection","mutation-testing"],S={critical:70,complex:45,moderate:20},pn={critical:"opus",complex:"sonnet",moderate:"sonnet",simple:"haiku"}});var R,Te=z(()=>{"use strict";R=class{weightsInputHidden;weightsHiddenOutput;biasHidden;biasOutput;learningRate;constructor(e=.01){this.learningRate=e,this.weightsInputHidden=this.xavierInit(4,32),this.weightsHiddenOutput=this.xavierInit(32,3),this.biasHidden=new Float32Array(32),this.biasOutput=new Float32Array(3)}xavierInit(e,t){let n=Math.sqrt(2/(e+t)),i=new Float32Array(e*t);for(let r=0;r<i.length;r++){let s=Math.random(),o=Math.random(),l=Math.sqrt(-2*Math.log(Math.max(s,1e-10)))*Math.cos(2*Math.PI*o);i[r]=l*n}return i}forward(e){if(e.length!==4)throw new Error(`Expected 4 features, got ${e.length}`);let t=new Float32Array(32);for(let i=0;i<32;i++){let r=this.biasHidden[i];for(let s=0;s<4;s++)r+=e[s]*this.weightsInputHidden[s*32+i];t[i]=Math.max(0,r)}let n=new Float32Array(3);for(let i=0;i<3;i++){let r=this.biasOutput[i];for(let s=0;s<32;s++)r+=t[s]*this.weightsHiddenOutput[s*3+i];n[i]=r}return this.softmax(n)}softmax(e){let t=Math.max(...e),n=new Float32Array(e.length),i=0;for(let s=0;s<e.length;s++)n[s]=Math.exp(e[s]-t),i+=n[s];let r=[];for(let s=0;s<e.length;s++)r.push(n[s]/i);return r}updateWeights(e,t,n){let i=new Float32Array(32);for(let c=0;c<32;c++){let u=this.biasHidden[c];for(let d=0;d<4;d++)u+=e[d]*this.weightsInputHidden[d*32+c];i[c]=Math.max(0,u)}let r=new Float32Array(3);for(let c=0;c<3;c++){let u=this.biasOutput[c];for(let d=0;d<32;d++)u+=i[d]*this.weightsHiddenOutput[d*3+c];r[c]=u}let s=this.softmax(r),o=new Float32Array(3);for(let c=0;c<3;c++)o[c]=(c===t?1:0)-s[c],o[c]*=n*this.learningRate;for(let c=0;c<32;c++)for(let u=0;u<3;u++)this.weightsHiddenOutput[c*3+u]+=i[c]*o[u];for(let c=0;c<3;c++)this.biasOutput[c]+=o[c];let l=new Float32Array(32);for(let c=0;c<32;c++){if(i[c]<=0)continue;let u=0;for(let d=0;d<3;d++)u+=o[d]*this.weightsHiddenOutput[c*3+d];l[c]=u}for(let c=0;c<4;c++)for(let u=0;u<32;u++)this.weightsInputHidden[c*32+u]+=e[c]*l[u];for(let c=0;c<32;c++)this.biasHidden[c]+=l[c]}serialize(){return{weightsInputHidden:Array.from(this.weightsInputHidden),weightsHiddenOutput:Array.from(this.weightsHiddenOutput),biasHidden:Array.from(this.biasHidden),biasOutput:Array.from(this.biasOutput)}}deserialize(e){e.weightsInputHidden.length===128&&(this.weightsInputHidden=new Float32Array(e.weightsInputHidden)),e.weightsHiddenOutput.length===96&&(this.weightsHiddenOutput=new Float32Array(e.weightsHiddenOutput)),e.biasHidden.length===32&&(this.biasHidden=new Float32Array(e.biasHidden)),e.biasOutput.length===3&&(this.biasOutput=new Float32Array(e.biasOutput))}}});var vt={};sn(vt,{NeuralTinyDancerRouter:()=>G,SimpleNeuralRouter:()=>R,createNeuralTinyDancerRouter:()=>Sn});import{performance as Tt}from"perf_hooks";function Sn(a){return new G(a)}var hn,fn,yn,Tn,vn,Cn,bn,kn,G,Ct=z(()=>{"use strict";ve();Te();Te();hn=1e3,fn=.1,yn=.2,Tn=50,vn=.01,Cn=["haiku","sonnet","opus"],bn={haiku:0,sonnet:1,opus:2},kn={"test-generation":.1,"test-execution":.15,"coverage-analysis":.2,"quality-assessment":.3,"requirements-validation":.35,"code-intelligence":.4,"contract-testing":.45,"visual-accessibility":.5,"learning-optimization":.55,"defect-intelligence":.7,"chaos-resilience":.8,"security-compliance":.9},G=class{ruleRouter;neuralNet;circuitBreakerThreshold;shadowModeDecisionLimit;shadowModeMaxDisagreement;shadowModeActive;shadowDecisions=[];shadowDisagreements=0;circuitBreakerTripped=!1;recentOutcomes=[];totalNeuralDecisions=0;totalWeightUpdates=0;neuralPrimary=!1;calibrationScores=[];maxCalibrationScores=500;domainSuccessRates=new Map;config;nativeRouterAvailable=!1;constructor(e={}){this.config=e,this.ruleRouter=new F(e),this.neuralNet=new R(e.learningRate??vn),this.circuitBreakerThreshold=e.circuitBreakerThreshold??yn,this.shadowModeDecisionLimit=e.shadowModeDecisions??hn,this.shadowModeMaxDisagreement=e.shadowModeMaxDisagreement??fn,e.forceShadowMode!==void 0?(this.shadowModeActive=e.forceShadowMode,this.neuralPrimary=!e.forceShadowMode):(this.shadowModeActive=!0,this.neuralPrimary=!1),this.tryLoadNativeRouter()}tryLoadNativeRouter(){this.nativeRouterAvailable=!1}async route(e){let t=Tt.now(),n=await this.ruleRouter.route(e);if(this.circuitBreakerTripped)return n;let i=this.extractFeatures(e,n.classification),r;try{r=this.neuralNet.forward(i)}catch{return this.tripCircuitBreaker(),n}let s=this.argmax(r),o=Cn[s],l=r[s];if(this.totalNeuralDecisions++,this.shadowModeActive){let m=n.model===o;return m||this.shadowDisagreements++,this.shadowDecisions.push({taskDescription:e.description.slice(0,100),ruleDecision:n.model,neuralDecision:o,agreed:m,neuralConfidence:l,timestamp:new Date}),this.evaluateShadowModeExit(),n}let c=Tt.now()-t,u=this.computeEmpiricalConfidenceBounds(r);return l<.3||u.calibrationScore>.8?n:{model:o,confidence:l,uncertainty:1-l,triggerMultiModel:n.triggerMultiModel,triggerHumanReview:n.triggerHumanReview,complexity:n.complexity,classification:n.classification,latencyMs:c,reasoning:this.buildNeuralReasoning(o,l,r,n,u)}}extractFeatures(e,t){let n=Math.min(1,t.score/100),i=e.description.length,r=e.context?.code?.length??0,s=(i+r)/4,o=Math.min(1,s/1e4),l=e.domain??"",c=kn[l]??.25,u=this.domainSuccessRates.get(l),d=u?u.success/Math.max(1,u.total):.7;return[n,o,c,d]}recordNeuralOutcome(e,t,n,i=n?1:0,r=t.model,s=0){this.ruleRouter.recordOutcome(e,t,n,i,r,s);let o=e.domain??"unknown",l=this.domainSuccessRates.get(o)??{success:0,total:0};l.total++,n&&l.success++,this.domainSuccessRates.set(o,l),this.recentOutcomes.push(n),this.recentOutcomes.length>Tn&&this.recentOutcomes.shift(),this.checkCircuitBreaker();let c=this.extractFeatures(e,t.classification),u=bn[r],d=(i-.5)*2;try{this.neuralNet.updateWeights(c,u,d),this.totalWeightUpdates++}catch{}let m=this.neuralNet.forward(c),p=this.argmax(m),f=1-m[u];this.calibrationScores.push(f),this.calibrationScores.length>this.maxCalibrationScores&&this.calibrationScores.shift()}computeEmpiricalConfidenceBounds(e){let n=Math.max(...e),i=1-n;if(this.calibrationScores.length<10)return{lower:0,upper:1,coverageLevel:.9,calibrationScore:i};let r=[...this.calibrationScores].sort((l,c)=>l-c),s=Math.ceil(.9*r.length)-1,o=r[Math.min(s,r.length-1)];return{lower:Math.max(0,n-o),upper:Math.min(1,n+o),coverageLevel:.9,calibrationScore:i}}computeConformalBounds(e){return this.computeEmpiricalConfidenceBounds(e)}evaluateShadowModeExit(){if(!this.shadowModeActive||this.config.forceShadowMode===!0)return;let e=this.shadowDecisions.length;if(e<this.shadowModeDecisionLimit)return;this.shadowDisagreements/e<=this.shadowModeMaxDisagreement&&(this.shadowModeActive=!1,this.neuralPrimary=!0)}checkCircuitBreaker(){if(this.recentOutcomes.length<10)return;let t=this.recentOutcomes.filter(n=>!n).length/this.recentOutcomes.length;t>this.circuitBreakerThreshold?this.tripCircuitBreaker():this.circuitBreakerTripped&&t<this.circuitBreakerThreshold*.5&&(this.circuitBreakerTripped=!1)}tripCircuitBreaker(){this.circuitBreakerTripped=!0,this.neuralPrimary=!1}buildNeuralReasoning(e,t,n,i,r){let s=[];return s.push(`[Neural] Routing to ${e.toUpperCase()}`),s.push(`with ${(t*100).toFixed(0)}% neural confidence.`),s.push(`Tier probabilities: haiku=${(n[0]*100).toFixed(0)}%,`),s.push(`sonnet=${(n[1]*100).toFixed(0)}%,`),s.push(`opus=${(n[2]*100).toFixed(0)}%.`),e!==i.model&&s.push(`Rule-based would choose ${i.model.toUpperCase()}.`),s.push(`Empirical bounds: [${r.lower.toFixed(2)}, ${r.upper.toFixed(2)}]`),s.push(`at ${(r.coverageLevel*100).toFixed(0)}% coverage.`),s.join(" ")}argmax(e){let t=0,n=e[0];for(let i=1;i<e.length;i++)e[i]>n&&(n=e[i],t=i);return t}getNeuralStats(){let e=this.shadowDecisions.length,t=e>0?this.shadowDisagreements/e:0,n=this.recentOutcomes.filter(r=>!r).length,i=this.recentOutcomes.length>0?n/this.recentOutcomes.length:0;return{shadowModeActive:this.shadowModeActive,shadowDecisions:e,disagreementRate:t,circuitBreakerTripped:this.circuitBreakerTripped,recentErrorRate:i,totalNeuralDecisions:this.totalNeuralDecisions,totalWeightUpdates:this.totalWeightUpdates,neuralPrimary:this.neuralPrimary}}getShadowDecisionLogs(){return this.shadowDecisions}getRuleRouter(){return this.ruleRouter}getNeuralNet(){return this.neuralNet}isNativeRouterAvailable(){return this.nativeRouterAvailable}isShadowModeActive(){return this.shadowModeActive}isNeuralPrimary(){return this.neuralPrimary}isCircuitBreakerTripped(){return this.circuitBreakerTripped}resetCircuitBreaker(){this.circuitBreakerTripped=!1,this.recentOutcomes=[]}getStats(){return this.ruleRouter.getStats()}getConfig(){return this.ruleRouter.getConfig()}reset(){this.ruleRouter.reset(),this.shadowDecisions=[],this.shadowDisagreements=0,this.circuitBreakerTripped=!1,this.recentOutcomes=[],this.totalNeuralDecisions=0,this.totalWeightUpdates=0,this.calibrationScores=[],this.domainSuccessRates.clear(),this.config.forceShadowMode!==void 0?(this.shadowModeActive=this.config.forceShadowMode,this.neuralPrimary=!this.config.forceShadowMode):(this.shadowModeActive=!0,this.neuralPrimary=!1)}}});import{performance as bt}from"perf_hooks";function kt(a){try{let{getRuVectorFeatureFlags:e}=(cn(),et(on));if(e().useNeuralRouting){let{NeuralTinyDancerRouter:n}=(Ct(),et(vt));return new n(a)}}catch(e){process.env.DEBUG&&console.debug("[Router] Neural router unavailable, using rule-based:",e instanceof Error?e.message:e)}return new F(a)}var F,ve=z(()=>{"use strict";yt();F=class{confidenceThreshold;uncertaintyThreshold;securityConfidenceThreshold;enableLearning;verbose;executor;totalRouted=0;routesByModel={haiku:0,sonnet:0,opus:0};routesByComplexity={simple:0,moderate:0,complex:0,critical:0};multiModelTriggers=0;humanReviewTriggers=0;advisorConsultations=0;totalConfidence=0;totalLatencyMs=0;outcomes=[];maxOutcomes=1e3;constructor(e={}){this.confidenceThreshold=e.confidenceThreshold??.8,this.uncertaintyThreshold=e.uncertaintyThreshold??.2,this.securityConfidenceThreshold=e.securityConfidenceThreshold??.85,this.enableLearning=e.enableLearning??!0,this.verbose=e.verbose??!1,this.executor=e.executor}hasExecutor(){return this.executor!==void 0}async routeWithAdvisor(e,t){let n=await this.route(e);if(!n.triggerMultiModel||!this.executor||!t)return{route:n};let i=await this.executor.consult(t,{agentName:e.agentId??e.id??"unknown",triggerReason:`tiny_dancer.confidence=${n.confidence.toFixed(2)}<${this.confidenceThreshold}`});return this.advisorConsultations++,{route:n,advisor:i}}async route(e){let t=bt.now(),n=ft(e),i=this.calculateConfidence(n),r=1-i,s=this.isSecurityTask(e),o=s&&i<this.securityConfidenceThreshold||i<this.confidenceThreshold&&n.complexity!=="simple",l=r>this.uncertaintyThreshold||s&&n.complexity==="critical",c=bt.now()-t,u=this.buildReasoning(n,i,s,o,l),d={model:n.recommendedModel,confidence:i,uncertainty:r,triggerMultiModel:o,triggerHumanReview:l,complexity:n.complexity,classification:n,latencyMs:c,reasoning:u};return this.updateStats(d),this.verbose&&console.log(`[TinyDancer] Route: ${n.recommendedModel} (complexity=${n.complexity}, confidence=${(i*100).toFixed(1)}%)`),d}calculateConfidence(e){let{score:t,complexity:n}=e;if(n==="simple"&&t<10)return .9;if(n==="critical"&&t>85)return .92;let i=[S.moderate,S.complex,S.critical],r=1/0;for(let d of i){let m=Math.abs(t-d);m<r&&(r=m)}let s=.55,o=.35,l=Math.min(r/25,1),c=s+l*o,u=n!=="simple"?Math.min(.05,e.factors.length*.01):0;return Math.min(.95,c+u)}isSecurityTask(e){let t=e;if(t.type==="security-scan"||t.type==="vulnerability-assessment"||e.domain==="security-compliance")return!0;let n=["sast","dast","vulnerability","owasp","security-scanning"];if(e.requiredCapabilities?.some(s=>n.includes(s)))return!0;let i=["security","vulnerability","cve","owasp","exploit","injection"],r=e.description.toLowerCase();return!!i.some(s=>r.includes(s))}buildReasoning(e,t,n,i,r){let s=[];if(s.push(`Routing to ${e.recommendedModel.toUpperCase()}`),s.push(`(complexity: ${e.complexity}, score: ${e.score})`),s.push(`with ${(t*100).toFixed(0)}% confidence.`),e.factors.length>0){let o=e.factors.slice(0,3).map(l=>l.name).join(", ");s.push(`Key factors: ${o}.`)}return n&&s.push("Security-sensitive task detected."),i&&s.push("Multi-model verification recommended due to uncertainty."),r&&s.push("Human review flagged due to high uncertainty or criticality."),s.join(" ")}updateStats(e){this.totalRouted++,this.routesByModel[e.model]++,this.routesByComplexity[e.complexity]++,this.totalConfidence+=e.confidence,this.totalLatencyMs+=e.latencyMs,e.triggerMultiModel&&this.multiModelTriggers++,e.triggerHumanReview&&this.humanReviewTriggers++}recordOutcome(e,t,n,i=n?1:0,r=t.model,s=0){if(!this.enableLearning)return;let o={task:e,routeResult:t,success:n,qualityScore:i,actualModelUsed:r,durationMs:s,timestamp:new Date};this.outcomes.push(o),this.outcomes.length>this.maxOutcomes&&this.outcomes.shift(),this.verbose&&console.log(`[TinyDancer] Recorded outcome: success=${n}, quality=${(i*100).toFixed(0)}%, model=${r}`)}getStats(){return{totalRouted:this.totalRouted,routesByModel:{...this.routesByModel},routesByComplexity:{...this.routesByComplexity},multiModelTriggers:this.multiModelTriggers,advisorConsultations:this.advisorConsultations,humanReviewTriggers:this.humanReviewTriggers,avgConfidence:this.totalRouted>0?this.totalConfidence/this.totalRouted:0,avgLatencyMs:this.totalRouted>0?this.totalLatencyMs/this.totalRouted:0,outcomesRecorded:this.outcomes.length}}getOutcomes(){return this.outcomes}getSuccessRateByModel(){let e={haiku:{success:0,total:0},sonnet:{success:0,total:0},opus:{success:0,total:0}};for(let t of this.outcomes){let n=t.actualModelUsed;e[n].total++,t.success&&e[n].success++}return{haiku:e.haiku.total>0?e.haiku.success/e.haiku.total:0,sonnet:e.sonnet.total>0?e.sonnet.success/e.sonnet.total:0,opus:e.opus.total>0?e.opus.success/e.opus.total:0}}reset(){this.totalRouted=0,this.routesByModel={haiku:0,sonnet:0,opus:0},this.routesByComplexity={simple:0,moderate:0,complex:0,critical:0},this.multiModelTriggers=0,this.advisorConsultations=0,this.humanReviewTriggers=0,this.totalConfidence=0,this.totalLatencyMs=0,this.outcomes=[]}getConfig(){return{confidenceThreshold:this.confidenceThreshold,uncertaintyThreshold:this.uncertaintyThreshold,securityConfidenceThreshold:this.securityConfidenceThreshold,enableLearning:this.enableLearning,verbose:this.verbose}}}});var ln={enableConsoleLog:!0,maxEntries:1e3,logPrefix:"[TASK]"},q=class{entries=[];config;constructor(e={}){this.config={...ln,...e}}log(e,t,n){let i={timestamp:new Date,operation:e,taskId:t,agentId:n?.agentId,domain:n?.domain,details:n?.details};if(this.entries.push(i),this.entries.length>this.config.maxEntries&&this.entries.splice(0,this.entries.length-this.config.maxEntries),this.config.enableConsoleLog){let r=n?.agentId?` by ${n.agentId}`:"",s=n?.domain?` (${n.domain})`:"";console.log(`${this.config.logPrefix} ${e.toUpperCase()} ${t}${r}${s}`)}}logSubmit(e,t){this.log("submit",e,{details:t})}logAssign(e,t,n){this.log("assign",e,{agentId:t,domain:n})}logReassign(e,t,n,i){this.log("reassign",e,{agentId:n,domain:i,details:{fromAgent:t}})}logComplete(e,t){this.log("complete",e,{agentId:t})}logFail(e,t,n){this.log("fail",e,{agentId:t,details:n?{error:n}:void 0})}logCancel(e){this.log("cancel",e)}logSteal(e,t,n){this.log("steal",e,{domain:n,details:{fromDomain:t}})}logQueue(e,t){this.log("queue",e,{details:{position:t}})}logDequeue(e){this.log("dequeue",e)}getEntries(e){let t=[...this.entries];e&&(e.operation&&(t=t.filter(i=>i.operation===e.operation)),e.taskId&&(t=t.filter(i=>i.taskId===e.taskId)),e.agentId&&(t=t.filter(i=>i.agentId===e.agentId)),e.domain&&(t=t.filter(i=>i.domain===e.domain)),e.fromTimestamp&&(t=t.filter(i=>i.timestamp>=e.fromTimestamp)),e.toTimestamp&&(t=t.filter(i=>i.timestamp<=e.toTimestamp)));let n=e?.limit??t.length;return t.slice(-n)}getStatistics(){let e={submit:0,assign:0,reassign:0,complete:0,fail:0,cancel:0,steal:0,queue:0,dequeue:0},t=new Set,n=new Set;for(let i of this.entries)e[i.operation]++,t.add(i.taskId),i.agentId&&n.add(i.agentId);return{totalEntries:this.entries.length,operationCounts:e,taskCount:t.size,agentCount:n.size}}clear(){this.entries.length=0}};function he(a){return new q(a)}me();rt();var fe=class{memory;initialized=!1;constructor(e){this.memory=e??w()}async initialize(){this.initialized||(this.memory.isInitialized()||await this.memory.initialize(),this.initialized=!0)}async saveSnapshot(e){this.ensureInitialized();let t=T();return this.memory.getDatabase().prepare(`
3
3
  INSERT INTO mincut_snapshots (
4
4
  id, timestamp, vertex_count, edge_count, total_weight,
5
5
  is_connected, component_count, vertices_json, edges_json
@@ -177,4 +177,4 @@ import{b as pe}from"./chunk-VHNAN7E2.js";import{a as dt}from"./chunk-HV6LJ57R.js
177
177
  `;let i=this.getRecommendations(n);if(i.length>0){t+=`**Recommendations:**
178
178
  `;for(let r of i)t+=`- ${r}
179
179
  `;t+=`
180
- `}}return t}getRecommendations(e){switch(e.loopType){case"strategic":return[...e.recommendations.forRiskAssessor,...e.recommendations.forQualityCriteria];case"tactical":return e.recommendations.forProductFactorsAssessor;case"operational":return[...e.recommendations.forTestArchitect,...e.recommendations.antiPatterns];case"quality-criteria":return e.recommendations.forRequirementsValidator;default:return[]}}filterManagedHooks(e){if(process.env.AQE_HOOKS_MANAGED_ONLY!=="true")return e;let t=e.filter(([n])=>n.startsWith("managed:"));return t.length<e.length&&console.log(`[CrossPhaseHooks] AQE_HOOKS_MANAGED_ONLY: filtered ${e.length-t.length} non-managed hooks`),t}async isBlockedUrl(e){if(!e.includes("://"))return!1;let t=await pe(e);return t.safe?!1:(console.warn(`[CrossPhaseHooks] SSRF blocked: ${t.reason}`),!0)}checkConditions(e,t){return!e||e.length===0?!0:e.every(n=>this.evaluateCondition(n,t))}evaluateCondition(e,t){try{let n=e.split(/\s*(>|<|>=|<=|==|!=)\s*/);if(n.length!==3)return!1;let[i,r,s]=n,o=this.getValueFromPath(t,i),l=isNaN(Number(s))?s:Number(s),c=typeof o=="number"?o:Number(o),u=typeof l=="number"?l:Number(l);switch(r){case">":return c>u;case"<":return c<u;case">=":return c>=u;case"<=":return c<=u;case"==":return o==l;case"!=":return o!=l;default:return!1}}catch{return!1}}getValueFromPath(e,t){return t.split(".").reduce((n,i)=>{if(n&&typeof n=="object"&&i in n)return n[i]},e)}extractFromContext(e,t){let n={};for(let[i,r]of Object.entries(e))n[i]=this.getValueFromPath(t,r);return n}parseMaxAge(e){let t=e.match(/^(\d+)(d|h|m|s)$/);if(!t)return 0;let[,n,i]=t,r=parseInt(n,10);switch(i){case"d":return r*24*60*60*1e3;case"h":return r*60*60*1e3;case"m":return r*60*1e3;case"s":return r*1e3;default:return 0}}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t)}off(e,t){this.listeners.get(e)?.delete(t)}emit(e,t){this.listeners.get(e)?.forEach(n=>n(t))}async runCleanup(){if(!this.config?.cleanup.enabled)return;console.log("[CrossPhaseHooks] Running cleanup...");let e=await this.memory.cleanupExpired();console.log(`[CrossPhaseHooks] Cleanup complete: ${e.deleted} signals deleted`)}},qe=null;function Gt(a){return qe||(qe=new Ge(a)),qe}function jt(a,e){let t=[];for(let s of e){let o=a.router.subscribeToDoamin(s,async l=>{await ai(a,l)});t.push(o)}let n=a.router.subscribeToEventType("TaskCompleted",async s=>{await oi(a,s)});t.push(n);let i=a.router.subscribeToEventType("TaskFailed",async s=>{await ci(a,s)});t.push(i);let r=a.router.subscribeToEventType("AgentStatusChanged",async s=>{await li(a,s)});return t.push(r),t}async function ai(a,e){a.domainLastActivity.set(e.source,new Date),await a.processQueue()}async function oi(a,e){let{taskId:t,result:n}=e.payload,i=a.tasks.get(t);if(i){(i.status==="running"||i.status==="assigned")&&(a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1));let r=i.startedAt?Date.now()-i.startedAt.getTime():0;a.tasks.set(t,{...i,status:"completed",completedAt:new Date,result:n}),a.tasksCompleted++,a.taskDurations.push(r),a.auditLogger.logComplete(t,i.assignedAgents[0]);try{let s=Gt(),o=i.assignedAgents[0];o&&await s.onAgentComplete(o,{taskId:t,taskType:i.task.type,domain:i.assignedDomain,result:n,duration:r})}catch(s){console.warn("[QueenCoordinator] Cross-phase hook error:",s)}try{await I.afterTaskExecution({taskId:t,taskType:i.task.type,agentId:i.assignedAgents[0]||"unknown",domain:i.assignedDomain||"test-generation",priority:i.task.priority},!0,0,0)}catch(s){console.warn("[QueenCoordinator] Governance tracking error:",s)}if(a.domainBreakerRegistry&&i.assignedDomain&&a.domainBreakerRegistry.getBreaker(i.assignedDomain).recordSuccess(),a.traceCollector){let s=a.taskTraceContexts.get(t);s&&(a.traceCollector.completeSpan(s.spanId),a.taskTraceContexts.delete(t))}if(a.taskCompletedHook)try{let s=typeof n=="object"&&n!==null?n:null;if(s===null)console.error(`[QueenCoordinator] Pattern training skipped for task ${t}: result is not an object (got ${typeof n})`);else{let o=ui(s,t);if(o){let l={taskId:t,agentId:i.assignedAgents[0]||"unknown",domain:i.assignedDomain||"test-generation",type:i.task.type,status:"completed",output:s,metrics:o,duration:r,timestamp:Date.now()};a.taskCompletedHook.onTaskCompleted(l).catch(c=>{console.warn("[QueenCoordinator] Pattern training error:",c)})}}}catch(s){console.warn("[QueenCoordinator] Pattern training setup error:",s)}}await a.processQueue()}async function ci(a,e){let{taskId:t,error:n}=e.payload,i=a.tasks.get(t);if(i){if((i.status==="running"||i.status==="assigned")&&(a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1)),a.domainBreakerRegistry&&i.assignedDomain&&a.domainBreakerRegistry.getBreaker(i.assignedDomain).recordFailure(new Error(n||"Task failed")),a.traceCollector){let r=a.taskTraceContexts.get(t);r&&(a.traceCollector.failSpan(r.spanId,n||"Task failed"),a.taskTraceContexts.delete(t))}if(i.retryCount<a.config.taskRetryLimit){a.auditLogger.logFail(t,i.assignedAgents[0],n);let r={...i,status:"queued",retryCount:i.retryCount+1,error:n};a.tasks.set(t,r),a.enqueueTask(i.task)}else{a.tasks.set(t,{...i,status:"failed",completedAt:new Date,error:n}),a.tasksFailed++,a.auditLogger.logFail(t,i.assignedAgents[0],n);try{await I.afterTaskExecution({taskId:t,taskType:i.task.type,agentId:i.assignedAgents[0]||"unknown",domain:i.assignedDomain||"test-generation",priority:i.task.priority},!1,0,0)}catch(r){console.warn("[QueenCoordinator] Governance tracking error:",r)}if(a.hypothesisManager&&(i.task.priority==="p0"||i.task.priority==="p1"))try{let r=i.assignedDomain||"test-generation",s=a.hypothesisManager.createInvestigation(t,r,`Root cause analysis for ${i.task.type} failure: ${n}`);a.hypothesisManager.addHypothesis(s.id,`Infrastructure failure in domain '${r}' caused task ${t} to fail`,"log-analysis",`${r}-lead`),a.hypothesisManager.addHypothesis(s.id,`Logic/configuration error in task payload caused ${i.task.type} to fail: ${n}`,"code-analysis",i.assignedAgents[0]||"unknown"),console.log(`[QueenCoordinator] Competing hypotheses investigation created: ${s.id}`)}catch(r){console.warn("[QueenCoordinator] Hypothesis creation error:",r)}}}await a.processQueue()}async function li(a,e){let{agentId:t,status:n,domain:i}=e.payload;a.domainLastActivity.set(i,new Date),(n==="completed"||n==="failed")&&await a.processQueue()}function ui(a,e){if("metrics"in a&&typeof a.metrics=="object"&&a.metrics!==null){let t=a.metrics;return{testsPassed:typeof t.testsPassed=="number"?t.testsPassed:void 0,testsFailed:typeof t.testsFailed=="number"?t.testsFailed:void 0,coverageChange:typeof t.coverageChange=="number"?t.coverageChange:void 0,securityIssues:typeof t.securityIssues=="number"?t.securityIssues:void 0,performanceMs:typeof t.performanceMs=="number"?t.performanceMs:void 0,linesChanged:typeof t.linesChanged=="number"?t.linesChanged:void 0}}return"testsPassed"in a||"testsFailed"in a?{testsPassed:typeof a.testsPassed=="number"?a.testsPassed:void 0,testsFailed:typeof a.testsFailed=="number"?a.testsFailed:void 0,coverageChange:typeof a.coverageChange=="number"?a.coverageChange:void 0,securityIssues:typeof a.securityIssues=="number"?a.securityIssues:void 0,performanceMs:typeof a.performanceMs=="number"?a.performanceMs:void 0,linesChanged:typeof a.linesChanged=="number"?a.linesChanged:void 0}:(console.error(`[QueenCoordinator] Pattern training skipped for task ${e}: result object has no recognizable metrics shape (keys: ${Object.keys(a).join(", ")})`),null)}function Wt(a,e,t){let n=a.listAgents({domain:e}),i=n.filter(l=>l.status==="running").length,r=n.filter(l=>l.status==="idle").length,s=n.filter(l=>l.status==="failed").length,o;return s>0&&s>=n.length/2?o="unhealthy":s>0?o="degraded":i>0?o="healthy":o="idle",{status:o,agents:{total:n.length,active:i,idle:r,failed:s},lastActivity:t,errors:[]}}var di=ut();function Vt(a,e,t){let n=a.get(t.priority);n&&lt(n,t,di);for(let i of t.targetDomains){let r=e.get(i);r&&r.push(t)}}function de(a,e,t){let n=a.get(t.priority);if(n){let i=n.findIndex(r=>r.id===t.id);i!==-1&&n.splice(i,1)}for(let i of t.targetDomains){let r=e.get(i);if(r){let s=r.findIndex(o=>o.id===t.id);s!==-1&&r.splice(s,1)}}}function je(a,e){let t=0;for(let n of["p0","p1","p2","p3"]){let i=a.get(n);if(i){if(n===e.priority){t+=i.findIndex(r=>r.id===e.id);break}t+=i.length}}return t}async function We(a){if(!(a.runningTaskCounter>=a.config.maxConcurrentTasks))for(let e of["p0","p1","p2","p3"]){let t=a.taskQueue.get(e);if(!t||t.length===0)continue;let n=t.shift();if(n){de(a.taskQueue,a.domainQueues,n),a.runningTaskCounter++;try{await Ve(a,n)}catch(i){throw a.runningTaskCounter--,i}if(a.runningTaskCounter>=a.config.maxConcurrentTasks)return}}}function Kt(a,e){let t=Array.from(a.values());return e&&(e.status&&(t=t.filter(n=>n.status===e.status)),e.domain&&(t=t.filter(n=>n.assignedDomain===e.domain)),e.priority&&(t=t.filter(n=>n.task.priority===e.priority)),e.type&&(t=t.filter(n=>n.task.type===e.type)),e.fromDate&&(t=t.filter(n=>n.task.createdAt>=e.fromDate)),e.toDate&&(t=t.filter(n=>n.task.createdAt<=e.toDate))),t}async function Ve(a,e){let t=e.targetDomains.length>0?e.targetDomains:P[e.type]||[];if(t.length===0)return y(new Error(`No domains configured for task type: ${e.type}`));let n,i=1/0;for(let r of t){let s=a.getDomainLoad(r);a.getDomainHealth(r)?.status!=="unhealthy"&&s<i&&(i=s,n=r)}return n?Ke(a,e,n):y(new Error("No healthy domain available for task"))}async function Ke(a,e,t){let n;if(a.tinyDancerRouter){let c={p0:"critical",p1:"high",p2:"normal",p3:"low"},u={description:`${e.type}: ${JSON.stringify(e.payload).slice(0,200)}`,type:e.type,domain:t,priority:c[e.priority]};n=await a.tinyDancerRouter.route(u),a.config.enableMetrics&&console.log(`[Queen] TinyDancer routing: ${e.type} \u2192 tier=${n.tier}, model=${n.model}, cost=$${n.estimatedCost.toFixed(4)}`)}if(a.domainBreakerRegistry&&!a.domainBreakerRegistry.canExecuteInDomain(t))return y(new Error(`Domain '${t}' circuit breaker is open \u2014 too many recent failures`));if(a.domainTeamManager)try{if(!a.domainTeamManager.getDomainTeam(t)){let u=`${t}-lead`;a.domainTeamManager.createDomainTeam(t,u)}}catch(c){console.warn(`[Queen] Domain team setup for '${t}' failed (continuing):`,c)}let i=n?.tier||"task-worker",r=["task-execution",e.type,...n?[`model:${n.model}`]:[],...n?.triggerMultiModel?["advisor:triggerMultiModel"]:[]],s=await a.requestAgentSpawn(t,i,r),o=[];s.success&&o.push(s.value);let l={taskId:e.id,task:e,status:"running",assignedDomain:t,assignedAgents:o,startedAt:new Date,retryCount:0};a.tasks.set(e.id,l),a.domainLastActivity.set(t,new Date);for(let c of o)a.auditLogger.logAssign(e.id,c,t);if(await a.publishEvent("TaskAssigned",{taskId:e.id,domain:t,agentIds:o}),a.domainPlugins){let c=a.domainPlugins.get(t);if(c?.executeTask&&c.canHandleTask?.(e.type)){let u={taskId:e.id,taskType:e.type,payload:e.payload,priority:e.priority,timeout:e.timeout,correlationId:e.correlationId},d=await c.executeTask(u,m=>mi(a,m));return d.success?b(e.id):(a.tasks.set(e.id,{...l,status:"failed",error:d.error.message,completedAt:new Date}),a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1),a.tasksFailed++,a.auditLogger.logFail(e.id,o[0],d.error.message),y(d.error))}if(c)try{await c.handleEvent({id:T(),type:"TaskAssigned",timestamp:new Date,source:"queen-coordinator",correlationId:e.correlationId,payload:{task:e}}),console.warn(`[Queen] Domain ${t} has no executeTask handler, using event fallback`)}catch(u){console.warn(`[Queen] Failed to invoke domain ${t} event handler:`,u)}}return b(e.id)}async function mi(a,e){let t=a.tasks.get(e.taskId);if(!t){console.warn(`[Queen] Received completion for unknown task: ${e.taskId}`);return}let n={...t,status:e.success?"completed":"failed",completedAt:new Date,result:e.data,error:e.error};if(a.tasks.set(e.taskId,n),e.success?(a.tasksCompleted++,a.taskDurations.push(e.duration),a.auditLogger.logComplete(e.taskId,t.assignedAgents[0])):(a.tasksFailed++,a.auditLogger.logFail(e.taskId,t.assignedAgents[0],e.error||"Unknown error")),a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1),a.coExecutionRepo&&t.assignedAgents.length>=2)try{a.coExecutionRepo.recordSwarmCoExecution(t.assignedAgents,t.assignedDomain||"unknown",e.success,t.task.type)}catch{}for(let i of t.assignedAgents)await a.agentCoordinator.stop(i);await a.publishEvent(e.success?"TaskCompleted":"TaskFailed",{taskId:e.taskId,domain:t.assignedDomain,result:e.data,error:e.error,duration:e.duration}),await We(a)}function Yt(a,e){return(P[e.type]||[]).includes(a)}k();async function Zt(a){let e=0,t=a.getIdleDomains(),n=a.getBusyDomains();if(t.length===0||n.length===0)return 0;n.sort((i,r)=>a.getDomainLoad(r)-a.getDomainLoad(i));for(let i of n){if(t.length===0)break;let r=a.domainQueues.get(i)||[],s=Math.min(r.length,a.config.workStealing.stealBatchSize);for(let o=0;o<s&&t.length>0;o++){let l=r.find(c=>Yt(t[0],c));if(l){let c=t.shift();a.removeFromQueues(l),a.auditLogger.logSteal(l.id,i,c),await a.assignTaskToDomain(l,c),e++,a.tasksStolen++,await a.publishEvent("TaskStolen",{taskId:l.id,fromDomain:i,toDomain:c})}}}return e}function Ye(a,e){let t=0,n=10,i=setInterval(async()=>{try{await e(),t=0}catch(r){t++;let s=Math.min(1e3*Math.pow(2,t),3e4);if(console.warn(`[QueenCoordinator] Work-stealing failed (attempt ${t}), backing off ${s}ms`,h(r)),t>n){console.error(`[QueenCoordinator] Work-stealing exceeded ${n} consecutive failures, stopping interval`),clearInterval(i);return}await new Promise(o=>setTimeout(o,s))}},a.workStealing.checkInterval);return i}function Ze(a){return typeof a.setMinCutBridge=="function"}function Xt(a,e){for(let[t,n]of a)Ze(n)&&(n.setMinCutBridge(e),console.log(`[QueenCoordinator] MinCut bridge injected into ${t}`))}async function Jt(a,e,t){try{let n=await a.get("queen:state");if(n)for(let[i,r]of n.tasks)r.status==="queued"&&(e.set(i,r),t(r.task))}catch(n){console.debug("[QueenCoordinator] State loading failed:",n instanceof Error?n.message:n)}}async function en(a,e){let t=Array.from(e.entries()).filter(([,n])=>n.status==="queued");await a.set("queen:state",{tasks:t},{namespace:"queen-coordinator",persist:!0})}function tn(a){return setInterval(async()=>{let e=a.getMetrics();if(await a.publishEvent("MetricsCollected",{metrics:e}),await a.memory.set(`queen:metrics:${Date.now()}`,e,{ttl:86400,namespace:"queen-coordinator"}),a.dynamicScaler)try{let t=a.getAverageTaskDuration(),n={queueDepth:a.getQueuedTaskCount(),activeAgents:a.getActiveAgentCount(),idleAgents:a.getIdleAgentCount(),avgTaskDurationMs:t,errorRate:a.getTasksReceived()>0?a.getTasksFailed()/a.getTasksReceived():0,throughput:e.uptime>0?a.getTasksCompleted()/(e.uptime/1e3):0,timestamp:Date.now()};a.dynamicScaler.recordMetrics(n);let i=a.dynamicScaler.evaluate();i&&i.action!=="maintain"&&(console.log(`[QueenCoordinator] Dynamic scaler: ${i.action} to ${i.targetAgents} agents \u2014 ${i.reason}`),a.dynamicScaler.execute(i).catch(r=>{console.warn("[QueenCoordinator] Dynamic scaling execution error:",r)}))}catch(t){console.warn("[QueenCoordinator] Dynamic scaler metrics error:",t)}},a.config.metricsInterval)}function Xe(a,e,t=36e5){let n=Date.now(),i=0;for(let[s,o]of a)if(o.status==="completed"||o.status==="failed"||o.status==="cancelled"){let l=o.completedAt?.getTime()||o.startedAt?.getTime()||0;l>0&&n-l>t&&(a.delete(s),e.delete(s),i++)}let r=1e4;if(e.size>r){let s=e.size-r,o=e.keys();for(let l=0;l<s;l++){let c=o.next().value;c!==void 0&&e.delete(c)}console.log(`[QueenCoordinator] Evicted ${s} oldest trace contexts (max: ${r})`)}return i>0&&console.log(`[QueenCoordinator] Cleaned up ${i} old tasks (retention: ${t}ms)`),i}function nn(a,e){return a&&a.size>0?Array.from(a.keys()):[...e]}var g=it.create("QueenCoordinator");zt(v);var Je=class{constructor(e,t,n,i,r,s,o,l={}){this.eventBus=e;this.agentCoordinator=t;this.memory=n;this.router=i;this.protocolExecutor=r;this.workflowExecutor=s;this.domainPlugins=o;this.config={...Ut,...l},this.auditLogger=he({enableConsoleLog:this.config.enableMetrics,maxEntries:1e3,logPrefix:"[QUEEN]"}),["p0","p1","p2","p3"].forEach(c=>{this.taskQueue.set(c,[])}),this.config.enableRouting!==!1&&(this.tinyDancerRouter=new j(this.config.routing)),v.forEach(c=>{this.domainQueues.set(c,[]),this.domainLastActivity.set(c,new Date)})}eventBus;agentCoordinator;memory;router;protocolExecutor;workflowExecutor;domainPlugins;config;tasks=new Map;taskQueue=new Map;domainQueues=new Map;domainLastActivity=new Map;initialized=!1;workStealingTimer=null;metricsTimer=null;cleanupTimer=null;startTime=new Date;eventSubscriptionIds=[];runningTaskCounter=0;tasksReceived=0;tasksCompleted=0;tasksFailed=0;tasksStolen=0;taskDurations=new nt(1e3);protocolsExecuted=0;workflowsExecuted=0;auditLogger;minCutBridge=null;tinyDancerRouter=null;domainBreakerRegistry=null;domainTeamManager=null;agentTeamsAdapter=null;tierSelector=null;taskCompletedHook=null;traceCollector=null;taskTraceContexts=new Map;hypothesisManager=null;federationMailbox=null;dynamicScaler=null;coExecutionRepo=null;dependencyGraph=null;availableMcpServers=[];async initialize(){if(!this.initialized){this.startTime=new Date,await this.router.initialize(),this.subscribeToEvents(),this.config.workStealing.enabled&&(this.workStealingTimer=Ye(this.config,()=>this.triggerWorkStealing().then(()=>{}))),this.config.enableMetrics&&(this.metricsTimer=tn(this.createMetricsContext())),this.cleanupTimer=setInterval(()=>{Xe(this.tasks,this.taskTraceContexts,36e5)},3e5),this.cleanupTimer.unref(),await Jt(this.memory,this.tasks,e=>this.enqueueTaskInternal(e)),this.minCutBridge=ht(this.eventBus,this.agentCoordinator,{autoUpdateFromEvents:!0,persistData:!0,includeInQueenHealth:!0,sharedGraph:ct()}),await this.minCutBridge.initialize(),this.domainPlugins&&Xt(this.domainPlugins,this.minCutBridge);try{await I.initialize(),g.info("Governance adapter initialized")}catch(e){g.warn("Governance initialization failed (continuing)",{error:e})}this.initializeSubsystems();try{let{join:e}=await import("path"),t=e(process.cwd(),".claude","agents","v3");this.dependencyGraph=Rt(t),this.availableMcpServers=dt(process.cwd());let{getUnifiedMemory:n}=await import("./unified-memory-4VO5KSHP.js"),i=n();await i.initialize(),this.coExecutionRepo=wt(),this.coExecutionRepo.initialize(i.getDatabase()),this.dependencyGraph.warnings.length>0&&g.warn(`Dependency graph: ${this.dependencyGraph.warnings.length} warning(s)`,{warnings:this.dependencyGraph.warnings.slice(0,5)}),g.info("Dependency intelligence initialized",{agents:this.dependencyGraph.nodes.size,mcpServers:this.availableMcpServers.length})}catch(e){g.warn("Dependency intelligence initialization failed (continuing)",{error:e})}await this.publishEvent("QueenInitialized",{timestamp:new Date,config:this.config,domains:v}),this.initialized=!0}}async dispose(){this.workStealingTimer&&(clearInterval(this.workStealingTimer),this.workStealingTimer=null),this.metricsTimer&&(clearInterval(this.metricsTimer),this.metricsTimer=null),this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null),this.minCutBridge&&(await this.minCutBridge.dispose(),this.minCutBridge=null),this.domainTeamManager&&(this.domainTeamManager.dispose(),this.domainTeamManager=null),this.agentTeamsAdapter&&(this.agentTeamsAdapter.shutdown(),this.agentTeamsAdapter=null),this.domainBreakerRegistry=null,this.tierSelector=null,this.traceCollector&&(this.traceCollector.dispose(),this.traceCollector=null),this.hypothesisManager&&(this.hypothesisManager.dispose(),this.hypothesisManager=null),this.federationMailbox&&(this.federationMailbox.dispose(),this.federationMailbox=null),this.dynamicScaler&&(this.dynamicScaler.dispose(),this.dynamicScaler=null),await en(this.memory,this.tasks);for(let[e,t]of this.tasks)(t.status==="queued"||t.status==="running")&&await this.cancelTask(e);await this.publishEvent("QueenShutdown",{timestamp:new Date,metrics:this.getMetrics()});for(let e of this.eventSubscriptionIds)this.router.unsubscribe(e);this.eventSubscriptionIds=[],await this.router.dispose(),this.initialized=!1}async submitTask(e){if(!this.initialized)return y(new Error("Queen Coordinator not initialized"));let t=`task_${T()}`,n={...e,id:t,createdAt:new Date,timeout:e.timeout||this.config.defaultTaskTimeout},i={taskId:n.id,taskType:n.type,agentId:n.requester||`queen-task:${n.id}`,domain:n.targetDomains[0]||"test-generation",priority:n.priority,payload:n.payload};try{let r=await I.beforeTaskExecution(i);if(!r.allowed)return this.auditLogger.logFail(t,"governance",r.reason||"Governance check failed"),await this.publishEvent("TaskRejected",{taskId:t,reason:r.reason,escalate:r.escalate}),y(new Error(`Task blocked by governance: ${r.reason}`))}catch(r){g.warn("Governance check error (continuing)",{error:r})}this.runningTaskCounter++;try{if(this.runningTaskCounter>this.config.maxConcurrentTasks)return this.runningTaskCounter--,this.queueTask(n);this.auditLogger.logSubmit(t,{type:n.type,priority:n.priority}),this.selectFleetTier(n),this.startTaskTrace(n,t);let r=await Ve(this.createTaskContext(),n);return r.success?(this.tasksReceived++,await this.publishEvent("TaskSubmitted",{taskId:t,task:n}),b(t)):(this.runningTaskCounter--,r)}catch(r){throw this.runningTaskCounter--,r}}async cancelTask(e){let t=this.tasks.get(e);if(!t)return y(new Error(`Task not found: ${e}`));if(t.status==="completed"||t.status==="failed")return y(new Error(`Task already finished: ${e}`));(t.status==="running"||t.status==="assigned")&&(this.runningTaskCounter=Math.max(0,this.runningTaskCounter-1)),this.tasks.set(e,{...t,status:"cancelled",completedAt:new Date}),de(this.taskQueue,this.domainQueues,t.task);for(let n of t.assignedAgents)await this.agentCoordinator.stop(n);return this.auditLogger.logCancel(e),await this.publishEvent("TaskCancelled",{taskId:e}),b(void 0)}getTaskStatus(e){return this.tasks.get(e)}listTasks(e){return Kt(this.tasks,e)}getDomainHealth(e){if(this.domainPlugins){let t=this.domainPlugins.get(e);if(t)return t.getHealth()}return Wt(this.agentCoordinator,e,this.domainLastActivity.get(e))}getDomainLoad(e){let t=this.domainQueues.get(e)||[],n=Array.from(this.tasks.values()).filter(i=>i.assignedDomain===e&&i.status==="running");return t.length+n.length}getIdleDomains(){let e=Date.now(),t=this.config.workStealing.idleThreshold;return v.filter(n=>{let i=this.domainLastActivity.get(n);return this.getDomainLoad(n)===0&&i&&e-i.getTime()>t})}getBusyDomains(){return v.filter(e=>this.getDomainLoad(e)>this.config.workStealing.loadThreshold)}getSpawnPlan(e){return this.dependencyGraph?_t(e,this.dependencyGraph):{phases:[e],warnings:[],unsatisfiedHardDeps:[]}}getDependencyGraph(){return this.dependencyGraph}enableWorkStealing(){this.workStealingTimer||(this.workStealingTimer=Ye(this.config,()=>this.triggerWorkStealing().then(()=>{})))}disableWorkStealing(){this.workStealingTimer&&(clearInterval(this.workStealingTimer),this.workStealingTimer=null)}async triggerWorkStealing(){return Zt(this.createWorkStealingContext())}listAllAgents(){return this.agentCoordinator.listAgents()}getAgentsByDomain(e){return this.agentCoordinator.listAgents({domain:e})}async requestAgentSpawn(e,t,n){if(!this.agentCoordinator.canSpawn())return y(new Error("Maximum concurrent agents reached (15)"));if(this.dependencyGraph&&this.availableMcpServers.length>0)try{for(let[,r]of this.dependencyGraph.nodes){let s=r.dependencies.mcpServers;if(!s||s.length===0)continue;let o=s.filter(l=>l.required&&!this.availableMcpServers.includes(l.name));if(o.length>0){g.warn(`Pre-spawn MCP advisory: ${r.agentName} needs ${o.map(l=>l.name).join(", ")}`,{agent:r.agentName,domain:e,missing:o.map(l=>l.name)});break}}}catch{}let i=await this.agentCoordinator.spawn({name:`${e}-${t}-${Date.now()}`,domain:e,type:t,capabilities:n});if(i.success){if(this.domainLastActivity.set(e,new Date),this.domainTeamManager&&typeof this.domainTeamManager.getDomainTeam=="function")try{if(this.domainTeamManager.getDomainTeam(e))this.domainTeamManager.addTeammate(e,i.value)||g.warn(`Agent ${i.value} could not join ${e} team (full)`);else try{this.domainTeamManager.createDomainTeam(e,i.value)}catch{this.domainTeamManager.addTeammate(e,i.value)||g.warn(`Agent ${i.value} could not join ${e} team (full or max teams reached)`)}}catch(r){g.warn(`Auto-team-wiring failed for ${i.value}`,{error:r})}await this.publishEvent("AgentSpawned",{agentId:i.value,domain:e,type:t,capabilities:n})}return i}getHealth(){let e=new Map,t=[],n=0,i=0,r=nn(this.domainPlugins,v);for(let u of r){let d=this.getDomainHealth(u);d&&(e.set(u,d),d.status==="unhealthy"?(n++,t.push({domain:u,severity:"high",message:`Domain ${u} is unhealthy`,timestamp:new Date})):d.status==="degraded"&&(i++,t.push({domain:u,severity:"medium",message:`Domain ${u} is degraded`,timestamp:new Date})))}let s=this.agentCoordinator.listAgents(),o=s.filter(u=>u.status==="running").length,l="healthy";n>0?l="unhealthy":i>r.length/2&&(l="degraded");let c={status:l,domainHealth:e,totalAgents:s.length,activeAgents:o,pendingTasks:this.getQueuedTaskCount(),runningTasks:this.getRunningTaskCount(),workStealingActive:this.workStealingTimer!==null,lastHealthCheck:new Date,issues:t};return this.minCutBridge?this.minCutBridge.extendQueenHealth(c):c}getMetrics(){let e=new Map;for(let o of v){let l=this.getDomainLoad(o);e.set(o,l)}let t=this.agentCoordinator.listAgents(),n=t.filter(o=>o.status==="running").length,i=t.length>0?n/t.length:0,r=this.taskDurations.average(),s={tasksReceived:this.tasksReceived,tasksCompleted:this.tasksCompleted,tasksFailed:this.tasksFailed,tasksStolen:this.tasksStolen,averageTaskDuration:r,domainUtilization:e,agentUtilization:i,protocolsExecuted:this.protocolsExecuted,workflowsExecuted:this.workflowsExecuted,uptime:Date.now()-this.startTime.getTime()};return this.minCutBridge?this.minCutBridge.extendQueenMetrics(s):s}getMinCutBridge(){return this.minCutBridge}injectMinCutBridgeIntoDomain(e){if(!this.minCutBridge)return g.warn("Cannot inject MinCut bridge: bridge not initialized"),!1;if(!this.domainPlugins)return g.warn("Cannot inject MinCut bridge: no domain plugins registered"),!1;let t=this.domainPlugins.get(e);return t?Ze(t)?(t.setMinCutBridge(this.minCutBridge),g.info(`MinCut bridge injected into ${e} (late binding)`),!0):(g.warn(`Domain ${e} does not support MinCut integration`),!1):(g.warn(`Cannot inject MinCut bridge: domain ${e} not found`),!1)}getTinyDancerRouter(){return this.tinyDancerRouter}getDomainBreakerRegistry(){return this.domainBreakerRegistry}getDomainTeamManager(){return this.domainTeamManager}getAgentTeamsAdapter(){return this.agentTeamsAdapter}getTierSelector(){return this.tierSelector}getTraceCollector(){return this.traceCollector}getHypothesisManager(){return this.hypothesisManager}getFederationMailbox(){return this.federationMailbox}getDynamicScaler(){return this.dynamicScaler}connectReasoningBank(e){let t=new ae(e);this.taskCompletedHook=new se({},t),g.info("ReasoningBank connected for pattern training")}async executeProtocol(e,t){if(!this.protocolExecutor)return y(new Error("Protocol executor not configured"));let n=await this.protocolExecutor.execute(e,t);return n.success?(this.protocolsExecuted++,await this.publishEvent("ProtocolExecuted",{protocolId:e,executionId:n.value.executionId}),b(n.value.executionId)):n}async executeWorkflow(e,t){if(!this.workflowExecutor)return y(new Error("Workflow executor not configured"));let n=await this.workflowExecutor.execute(e,t);return n.success?(this.workflowsExecuted++,await this.publishEvent("WorkflowExecuted",{workflowId:e,executionId:n.value.executionId}),b(n.value.executionId)):n}cleanupCompletedTasks(e=36e5){return Xe(this.tasks,this.taskTraceContexts,e)}subscribeToEvents(){this.eventSubscriptionIds=jt(this.createEventHandlerContext(),v)}enqueueTaskInternal(e){Vt(this.taskQueue,this.domainQueues,e)}async publishEvent(e,t){await this.eventBus.publish({id:T(),type:`Queen${e}`,timestamp:new Date,source:"queen-coordinator",payload:t})}queueTask(e){this.enqueueTaskInternal(e);let t={taskId:e.id,task:e,status:"queued",assignedAgents:[],retryCount:0};return this.tasks.set(e.id,t),this.tasksReceived++,this.auditLogger.logSubmit(e.id,{type:e.type,priority:e.priority}),this.auditLogger.logQueue(e.id,je(this.taskQueue,e)),this.publishEvent("TaskQueued",{taskId:e.id,task:e,position:je(this.taskQueue,e)}),b(e.id)}selectFleetTier(e){if(this.tierSelector)try{let t={trigger:e.payload?.trigger??"manual",changedFiles:e.payload?.changedFiles,affectedDomains:e.targetDomains,severity:e.priority==="p0"?"critical":e.priority==="p1"?"high":void 0,isHotfix:e.payload?.isHotfix},n=this.tierSelector.selectTier(t);return g.info(`Fleet tier: ${n.selectedTier} (${n.reason})`),n.selectedTier}catch(t){g.warn("Tier selection error (continuing)",{error:t});return}}startTaskTrace(e,t){if(this.traceCollector)try{let{context:n}=this.traceCollector.startTrace({operationName:e.type,agentId:e.requester||"queen",domain:e.targetDomains[0]||"test-generation",tags:{taskId:t,priority:e.priority}});if(this.taskTraceContexts.size>=1e4){let r=this.taskTraceContexts.keys().next().value;r!==void 0&&this.taskTraceContexts.delete(r)}this.taskTraceContexts.set(t,n)}catch(n){g.warn("Trace start error (continuing)",{error:n})}}getRunningTaskCount(){return Array.from(this.tasks.values()).filter(e=>e.status==="running"||e.status==="assigned").length}getQueuedTaskCount(){return Array.from(this.tasks.values()).filter(e=>e.status==="queued").length}initializeSubsystems(){if(this.config.enableCircuitBreakers!==!1)try{this.domainBreakerRegistry=Ot(),g.info("Domain circuit breaker registry initialized")}catch(e){g.warn("Circuit breaker initialization failed (continuing)",{error:e})}if(this.config.enableDomainTeams!==!1)try{this.agentTeamsAdapter=Ae(),this.agentTeamsAdapter.initialize(),this.domainTeamManager=Ee(this.agentTeamsAdapter),g.info("Domain team manager initialized")}catch(e){g.warn("Domain team manager initialization failed (continuing)",{error:e})}if(this.config.enableFleetTiers!==!1)try{this.tierSelector=Re(),g.info("Fleet tier selector initialized")}catch(e){g.warn("Tier selector initialization failed (continuing)",{error:e})}try{this.traceCollector=xe(),g.info("Trace collector initialized")}catch(e){g.warn("Trace collector initialization failed (continuing)",{error:e})}try{this.hypothesisManager=Fe(),this.federationMailbox=Oe(),this.dynamicScaler=Le(),g.info("Phase 4 modules initialized (hypotheses, federation, scaling)")}catch(e){g.warn("Phase 4 initialization failed (continuing)",{error:e})}}createEventHandlerContext(){let e=this;return{config:e.config,tasks:e.tasks,domainLastActivity:e.domainLastActivity,auditLogger:e.auditLogger,router:e.router,agentCoordinator:e.agentCoordinator,get runningTaskCounter(){return e.runningTaskCounter},set runningTaskCounter(t){e.runningTaskCounter=t},get tasksCompleted(){return e.tasksCompleted},set tasksCompleted(t){e.tasksCompleted=t},get tasksFailed(){return e.tasksFailed},set tasksFailed(t){e.tasksFailed=t},taskDurations:e.taskDurations,get domainBreakerRegistry(){return e.domainBreakerRegistry},get traceCollector(){return e.traceCollector},taskTraceContexts:e.taskTraceContexts,get taskCompletedHook(){return e.taskCompletedHook},get hypothesisManager(){return e.hypothesisManager},processQueue:()=>We(e.createTaskContext()),enqueueTask:t=>e.enqueueTaskInternal(t)}}createTaskContext(){let e=this;return{config:e.config,tasks:e.tasks,taskQueue:e.taskQueue,domainQueues:e.domainQueues,domainLastActivity:e.domainLastActivity,auditLogger:e.auditLogger,agentCoordinator:e.agentCoordinator,domainPlugins:e.domainPlugins,get runningTaskCounter(){return e.runningTaskCounter},set runningTaskCounter(t){e.runningTaskCounter=t},get tasksReceived(){return e.tasksReceived},set tasksReceived(t){e.tasksReceived=t},get tasksCompleted(){return e.tasksCompleted},set tasksCompleted(t){e.tasksCompleted=t},get tasksFailed(){return e.tasksFailed},set tasksFailed(t){e.tasksFailed=t},taskDurations:e.taskDurations,get tinyDancerRouter(){return e.tinyDancerRouter},get domainBreakerRegistry(){return e.domainBreakerRegistry},get domainTeamManager(){return e.domainTeamManager},get tierSelector(){return e.tierSelector},get traceCollector(){return e.traceCollector},taskTraceContexts:e.taskTraceContexts,get coExecutionRepo(){return e.coExecutionRepo},requestAgentSpawn:(t,n,i)=>e.requestAgentSpawn(t,n,i),publishEvent:(t,n)=>e.publishEvent(t,n),getDomainLoad:t=>e.getDomainLoad(t),getDomainHealth:t=>e.getDomainHealth(t)}}createWorkStealingContext(){let e=this;return{config:e.config,domainQueues:e.domainQueues,auditLogger:e.auditLogger,get tasksStolen(){return e.tasksStolen},set tasksStolen(t){e.tasksStolen=t},getIdleDomains:()=>e.getIdleDomains(),getBusyDomains:()=>e.getBusyDomains(),getDomainLoad:t=>e.getDomainLoad(t),removeFromQueues:t=>de(e.taskQueue,e.domainQueues,t),assignTaskToDomain:(t,n)=>Ke(e.createTaskContext(),t,n).then(()=>{}),publishEvent:(t,n)=>e.publishEvent(t,n)}}createMetricsContext(){let e=this;return{config:e.config,memory:e.memory,get dynamicScaler(){return e.dynamicScaler},getMetrics:()=>e.getMetrics(),publishEvent:(t,n)=>e.publishEvent(t,n),getQueuedTaskCount:()=>e.getQueuedTaskCount(),getActiveAgentCount:()=>e.agentCoordinator.listAgents().filter(t=>t.status==="running").length,getIdleAgentCount:()=>e.agentCoordinator.listAgents().filter(t=>t.status==="idle").length,getAverageTaskDuration:()=>e.taskDurations.average(),getTasksReceived:()=>e.tasksReceived,getTasksFailed:()=>e.tasksFailed,getTasksCompleted:()=>e.tasksCompleted}}};function uo(a,e,t,n,i,r){return new Je(a.eventBus,a.coordinator,a.memory,e,t,n,i,r)}export{ei as a,P as b,Je as c,uo as d};
180
+ `}}return t}getRecommendations(e){switch(e.loopType){case"strategic":return[...e.recommendations.forRiskAssessor,...e.recommendations.forQualityCriteria];case"tactical":return e.recommendations.forProductFactorsAssessor;case"operational":return[...e.recommendations.forTestArchitect,...e.recommendations.antiPatterns];case"quality-criteria":return e.recommendations.forRequirementsValidator;default:return[]}}filterManagedHooks(e){if(process.env.AQE_HOOKS_MANAGED_ONLY!=="true")return e;let t=e.filter(([n])=>n.startsWith("managed:"));return t.length<e.length&&console.log(`[CrossPhaseHooks] AQE_HOOKS_MANAGED_ONLY: filtered ${e.length-t.length} non-managed hooks`),t}async isBlockedUrl(e){if(!e.includes("://"))return!1;let t=await pe(e);return t.safe?!1:(console.warn(`[CrossPhaseHooks] SSRF blocked: ${t.reason}`),!0)}checkConditions(e,t){return!e||e.length===0?!0:e.every(n=>this.evaluateCondition(n,t))}evaluateCondition(e,t){try{let n=e.split(/\s*(>|<|>=|<=|==|!=)\s*/);if(n.length!==3)return!1;let[i,r,s]=n,o=this.getValueFromPath(t,i),l=isNaN(Number(s))?s:Number(s),c=typeof o=="number"?o:Number(o),u=typeof l=="number"?l:Number(l);switch(r){case">":return c>u;case"<":return c<u;case">=":return c>=u;case"<=":return c<=u;case"==":return o==l;case"!=":return o!=l;default:return!1}}catch{return!1}}getValueFromPath(e,t){return t.split(".").reduce((n,i)=>{if(n&&typeof n=="object"&&i in n)return n[i]},e)}extractFromContext(e,t){let n={};for(let[i,r]of Object.entries(e))n[i]=this.getValueFromPath(t,r);return n}parseMaxAge(e){let t=e.match(/^(\d+)(d|h|m|s)$/);if(!t)return 0;let[,n,i]=t,r=parseInt(n,10);switch(i){case"d":return r*24*60*60*1e3;case"h":return r*60*60*1e3;case"m":return r*60*1e3;case"s":return r*1e3;default:return 0}}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t)}off(e,t){this.listeners.get(e)?.delete(t)}emit(e,t){this.listeners.get(e)?.forEach(n=>n(t))}async runCleanup(){if(!this.config?.cleanup.enabled)return;console.log("[CrossPhaseHooks] Running cleanup...");let e=await this.memory.cleanupExpired();console.log(`[CrossPhaseHooks] Cleanup complete: ${e.deleted} signals deleted`)}},qe=null;function Gt(a){return qe||(qe=new Ge(a)),qe}function jt(a,e){let t=[];for(let s of e){let o=a.router.subscribeToDoamin(s,async l=>{await ai(a,l)});t.push(o)}let n=a.router.subscribeToEventType("TaskCompleted",async s=>{await oi(a,s)});t.push(n);let i=a.router.subscribeToEventType("TaskFailed",async s=>{await ci(a,s)});t.push(i);let r=a.router.subscribeToEventType("AgentStatusChanged",async s=>{await li(a,s)});return t.push(r),t}async function ai(a,e){a.domainLastActivity.set(e.source,new Date),await a.processQueue()}async function oi(a,e){let{taskId:t,result:n}=e.payload,i=a.tasks.get(t);if(i){(i.status==="running"||i.status==="assigned")&&(a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1));let r=i.startedAt?Date.now()-i.startedAt.getTime():0;a.tasks.set(t,{...i,status:"completed",completedAt:new Date,result:n}),a.tasksCompleted++,a.taskDurations.push(r),a.auditLogger.logComplete(t,i.assignedAgents[0]);try{let s=Gt(),o=i.assignedAgents[0];o&&await s.onAgentComplete(o,{taskId:t,taskType:i.task.type,domain:i.assignedDomain,result:n,duration:r})}catch(s){console.warn("[QueenCoordinator] Cross-phase hook error:",s)}try{await I.afterTaskExecution({taskId:t,taskType:i.task.type,agentId:i.assignedAgents[0]||"unknown",domain:i.assignedDomain||"test-generation",priority:i.task.priority},!0,0,0)}catch(s){console.warn("[QueenCoordinator] Governance tracking error:",s)}if(a.domainBreakerRegistry&&i.assignedDomain&&a.domainBreakerRegistry.getBreaker(i.assignedDomain).recordSuccess(),a.traceCollector){let s=a.taskTraceContexts.get(t);s&&(a.traceCollector.completeSpan(s.spanId),a.taskTraceContexts.delete(t))}if(a.taskCompletedHook)try{let s=typeof n=="object"&&n!==null?n:null;if(s===null)console.error(`[QueenCoordinator] Pattern training skipped for task ${t}: result is not an object (got ${typeof n})`);else{let o=ui(s,t);if(o){let l={taskId:t,agentId:i.assignedAgents[0]||"unknown",domain:i.assignedDomain||"test-generation",type:i.task.type,status:"completed",output:s,metrics:o,duration:r,timestamp:Date.now()};a.taskCompletedHook.onTaskCompleted(l).catch(c=>{console.warn("[QueenCoordinator] Pattern training error:",c)})}}}catch(s){console.warn("[QueenCoordinator] Pattern training setup error:",s)}}await a.processQueue()}async function ci(a,e){let{taskId:t,error:n}=e.payload,i=a.tasks.get(t);if(i){if((i.status==="running"||i.status==="assigned")&&(a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1)),a.domainBreakerRegistry&&i.assignedDomain&&a.domainBreakerRegistry.getBreaker(i.assignedDomain).recordFailure(new Error(n||"Task failed")),a.traceCollector){let r=a.taskTraceContexts.get(t);r&&(a.traceCollector.failSpan(r.spanId,n||"Task failed"),a.taskTraceContexts.delete(t))}if(i.retryCount<a.config.taskRetryLimit){a.auditLogger.logFail(t,i.assignedAgents[0],n);let r={...i,status:"queued",retryCount:i.retryCount+1,error:n};a.tasks.set(t,r),a.enqueueTask(i.task)}else{a.tasks.set(t,{...i,status:"failed",completedAt:new Date,error:n}),a.tasksFailed++,a.auditLogger.logFail(t,i.assignedAgents[0],n);try{await I.afterTaskExecution({taskId:t,taskType:i.task.type,agentId:i.assignedAgents[0]||"unknown",domain:i.assignedDomain||"test-generation",priority:i.task.priority},!1,0,0)}catch(r){console.warn("[QueenCoordinator] Governance tracking error:",r)}if(a.hypothesisManager&&(i.task.priority==="p0"||i.task.priority==="p1"))try{let r=i.assignedDomain||"test-generation",s=a.hypothesisManager.createInvestigation(t,r,`Root cause analysis for ${i.task.type} failure: ${n}`);a.hypothesisManager.addHypothesis(s.id,`Infrastructure failure in domain '${r}' caused task ${t} to fail`,"log-analysis",`${r}-lead`),a.hypothesisManager.addHypothesis(s.id,`Logic/configuration error in task payload caused ${i.task.type} to fail: ${n}`,"code-analysis",i.assignedAgents[0]||"unknown"),console.log(`[QueenCoordinator] Competing hypotheses investigation created: ${s.id}`)}catch(r){console.warn("[QueenCoordinator] Hypothesis creation error:",r)}}}await a.processQueue()}async function li(a,e){let{agentId:t,status:n,domain:i}=e.payload;a.domainLastActivity.set(i,new Date),(n==="completed"||n==="failed")&&await a.processQueue()}function ui(a,e){if("metrics"in a&&typeof a.metrics=="object"&&a.metrics!==null){let t=a.metrics;return{testsPassed:typeof t.testsPassed=="number"?t.testsPassed:void 0,testsFailed:typeof t.testsFailed=="number"?t.testsFailed:void 0,coverageChange:typeof t.coverageChange=="number"?t.coverageChange:void 0,securityIssues:typeof t.securityIssues=="number"?t.securityIssues:void 0,performanceMs:typeof t.performanceMs=="number"?t.performanceMs:void 0,linesChanged:typeof t.linesChanged=="number"?t.linesChanged:void 0}}return"testsPassed"in a||"testsFailed"in a?{testsPassed:typeof a.testsPassed=="number"?a.testsPassed:void 0,testsFailed:typeof a.testsFailed=="number"?a.testsFailed:void 0,coverageChange:typeof a.coverageChange=="number"?a.coverageChange:void 0,securityIssues:typeof a.securityIssues=="number"?a.securityIssues:void 0,performanceMs:typeof a.performanceMs=="number"?a.performanceMs:void 0,linesChanged:typeof a.linesChanged=="number"?a.linesChanged:void 0}:(console.error(`[QueenCoordinator] Pattern training skipped for task ${e}: result object has no recognizable metrics shape (keys: ${Object.keys(a).join(", ")})`),null)}function Wt(a,e,t){let n=a.listAgents({domain:e}),i=n.filter(l=>l.status==="running").length,r=n.filter(l=>l.status==="idle").length,s=n.filter(l=>l.status==="failed").length,o;return s>0&&s>=n.length/2?o="unhealthy":s>0?o="degraded":i>0?o="healthy":o="idle",{status:o,agents:{total:n.length,active:i,idle:r,failed:s},lastActivity:t,errors:[]}}var di=ut();function Vt(a,e,t){let n=a.get(t.priority);n&&lt(n,t,di);for(let i of t.targetDomains){let r=e.get(i);r&&r.push(t)}}function de(a,e,t){let n=a.get(t.priority);if(n){let i=n.findIndex(r=>r.id===t.id);i!==-1&&n.splice(i,1)}for(let i of t.targetDomains){let r=e.get(i);if(r){let s=r.findIndex(o=>o.id===t.id);s!==-1&&r.splice(s,1)}}}function je(a,e){let t=0;for(let n of["p0","p1","p2","p3"]){let i=a.get(n);if(i){if(n===e.priority){t+=i.findIndex(r=>r.id===e.id);break}t+=i.length}}return t}async function We(a){if(!(a.runningTaskCounter>=a.config.maxConcurrentTasks))for(let e of["p0","p1","p2","p3"]){let t=a.taskQueue.get(e);if(!t||t.length===0)continue;let n=t.shift();if(n){de(a.taskQueue,a.domainQueues,n),a.runningTaskCounter++;try{await Ve(a,n)}catch(i){throw a.runningTaskCounter--,i}if(a.runningTaskCounter>=a.config.maxConcurrentTasks)return}}}function Kt(a,e){let t=Array.from(a.values());return e&&(e.status&&(t=t.filter(n=>n.status===e.status)),e.domain&&(t=t.filter(n=>n.assignedDomain===e.domain)),e.priority&&(t=t.filter(n=>n.task.priority===e.priority)),e.type&&(t=t.filter(n=>n.task.type===e.type)),e.fromDate&&(t=t.filter(n=>n.task.createdAt>=e.fromDate)),e.toDate&&(t=t.filter(n=>n.task.createdAt<=e.toDate))),t}async function Ve(a,e){let t=e.targetDomains.length>0?e.targetDomains:P[e.type]||[];if(t.length===0)return y(new Error(`No domains configured for task type: ${e.type}`));let n,i=1/0;for(let r of t){let s=a.getDomainLoad(r);a.getDomainHealth(r)?.status!=="unhealthy"&&s<i&&(i=s,n=r)}return n?Ke(a,e,n):y(new Error("No healthy domain available for task"))}async function Ke(a,e,t){let n;if(a.tinyDancerRouter){let c={p0:"critical",p1:"high",p2:"normal",p3:"low"},u={description:`${e.type}: ${JSON.stringify(e.payload).slice(0,200)}`,type:e.type,domain:t,priority:c[e.priority]};n=await a.tinyDancerRouter.route(u),a.config.enableMetrics&&console.log(`[Queen] TinyDancer routing: ${e.type} \u2192 tier=${n.tier}, model=${n.model}, cost=$${n.estimatedCost.toFixed(4)}`)}if(a.domainBreakerRegistry&&!a.domainBreakerRegistry.canExecuteInDomain(t))return y(new Error(`Domain '${t}' circuit breaker is open \u2014 too many recent failures`));if(a.domainTeamManager)try{if(!a.domainTeamManager.getDomainTeam(t)){let u=`${t}-lead`;a.domainTeamManager.createDomainTeam(t,u)}}catch(c){console.warn(`[Queen] Domain team setup for '${t}' failed (continuing):`,c)}let i=n?.tier||"task-worker",r=["task-execution",e.type,...n?[`model:${n.model}`]:[],...n?.triggerMultiModel?["advisor:triggerMultiModel"]:[]],s=await a.requestAgentSpawn(t,i,r),o=[];s.success&&o.push(s.value);let l={taskId:e.id,task:e,status:"running",assignedDomain:t,assignedAgents:o,startedAt:new Date,retryCount:0};a.tasks.set(e.id,l),a.domainLastActivity.set(t,new Date);for(let c of o)a.auditLogger.logAssign(e.id,c,t);if(await a.publishEvent("TaskAssigned",{taskId:e.id,domain:t,agentIds:o}),a.domainPlugins){let c=a.domainPlugins.get(t);if(c?.executeTask&&c.canHandleTask?.(e.type)){let u={taskId:e.id,taskType:e.type,payload:e.payload,priority:e.priority,timeout:e.timeout,correlationId:e.correlationId},d=await c.executeTask(u,m=>mi(a,m));return d.success?b(e.id):(a.tasks.set(e.id,{...l,status:"failed",error:d.error.message,completedAt:new Date}),a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1),a.tasksFailed++,a.auditLogger.logFail(e.id,o[0],d.error.message),y(d.error))}if(c)try{await c.handleEvent({id:T(),type:"TaskAssigned",timestamp:new Date,source:"queen-coordinator",correlationId:e.correlationId,payload:{task:e}}),console.warn(`[Queen] Domain ${t} has no executeTask handler, using event fallback`)}catch(u){console.warn(`[Queen] Failed to invoke domain ${t} event handler:`,u)}}return b(e.id)}async function mi(a,e){let t=a.tasks.get(e.taskId);if(!t){console.warn(`[Queen] Received completion for unknown task: ${e.taskId}`);return}let n={...t,status:e.success?"completed":"failed",completedAt:new Date,result:e.data,error:e.error};if(a.tasks.set(e.taskId,n),e.success?(a.tasksCompleted++,a.taskDurations.push(e.duration),a.auditLogger.logComplete(e.taskId,t.assignedAgents[0])):(a.tasksFailed++,a.auditLogger.logFail(e.taskId,t.assignedAgents[0],e.error||"Unknown error")),a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1),a.coExecutionRepo&&t.assignedAgents.length>=2)try{a.coExecutionRepo.recordSwarmCoExecution(t.assignedAgents,t.assignedDomain||"unknown",e.success,t.task.type)}catch{}for(let i of t.assignedAgents)await a.agentCoordinator.stop(i);await a.publishEvent(e.success?"TaskCompleted":"TaskFailed",{taskId:e.taskId,domain:t.assignedDomain,result:e.data,error:e.error,duration:e.duration}),await We(a)}function Yt(a,e){return(P[e.type]||[]).includes(a)}k();async function Zt(a){let e=0,t=a.getIdleDomains(),n=a.getBusyDomains();if(t.length===0||n.length===0)return 0;n.sort((i,r)=>a.getDomainLoad(r)-a.getDomainLoad(i));for(let i of n){if(t.length===0)break;let r=a.domainQueues.get(i)||[],s=Math.min(r.length,a.config.workStealing.stealBatchSize);for(let o=0;o<s&&t.length>0;o++){let l=r.find(c=>Yt(t[0],c));if(l){let c=t.shift();a.removeFromQueues(l),a.auditLogger.logSteal(l.id,i,c),await a.assignTaskToDomain(l,c),e++,a.tasksStolen++,await a.publishEvent("TaskStolen",{taskId:l.id,fromDomain:i,toDomain:c})}}}return e}function Ye(a,e){let t=0,n=10,i=setInterval(async()=>{try{await e(),t=0}catch(r){t++;let s=Math.min(1e3*Math.pow(2,t),3e4);if(console.warn(`[QueenCoordinator] Work-stealing failed (attempt ${t}), backing off ${s}ms`,h(r)),t>n){console.error(`[QueenCoordinator] Work-stealing exceeded ${n} consecutive failures, stopping interval`),clearInterval(i);return}await new Promise(o=>setTimeout(o,s))}},a.workStealing.checkInterval);return i}function Ze(a){return typeof a.setMinCutBridge=="function"}function Xt(a,e){for(let[t,n]of a)Ze(n)&&(n.setMinCutBridge(e),console.log(`[QueenCoordinator] MinCut bridge injected into ${t}`))}async function Jt(a,e,t){try{let n=await a.get("queen:state");if(n)for(let[i,r]of n.tasks)r.status==="queued"&&(e.set(i,r),t(r.task))}catch(n){console.debug("[QueenCoordinator] State loading failed:",n instanceof Error?n.message:n)}}async function en(a,e){let t=Array.from(e.entries()).filter(([,n])=>n.status==="queued");await a.set("queen:state",{tasks:t},{namespace:"queen-coordinator",persist:!0})}function tn(a){return setInterval(async()=>{let e=a.getMetrics();if(await a.publishEvent("MetricsCollected",{metrics:e}),await a.memory.set(`queen:metrics:${Date.now()}`,e,{ttl:86400,namespace:"queen-coordinator"}),a.dynamicScaler)try{let t=a.getAverageTaskDuration(),n={queueDepth:a.getQueuedTaskCount(),activeAgents:a.getActiveAgentCount(),idleAgents:a.getIdleAgentCount(),avgTaskDurationMs:t,errorRate:a.getTasksReceived()>0?a.getTasksFailed()/a.getTasksReceived():0,throughput:e.uptime>0?a.getTasksCompleted()/(e.uptime/1e3):0,timestamp:Date.now()};a.dynamicScaler.recordMetrics(n);let i=a.dynamicScaler.evaluate();i&&i.action!=="maintain"&&(console.log(`[QueenCoordinator] Dynamic scaler: ${i.action} to ${i.targetAgents} agents \u2014 ${i.reason}`),a.dynamicScaler.execute(i).catch(r=>{console.warn("[QueenCoordinator] Dynamic scaling execution error:",r)}))}catch(t){console.warn("[QueenCoordinator] Dynamic scaler metrics error:",t)}},a.config.metricsInterval)}function Xe(a,e,t=36e5){let n=Date.now(),i=0;for(let[s,o]of a)if(o.status==="completed"||o.status==="failed"||o.status==="cancelled"){let l=o.completedAt?.getTime()||o.startedAt?.getTime()||0;l>0&&n-l>t&&(a.delete(s),e.delete(s),i++)}let r=1e4;if(e.size>r){let s=e.size-r,o=e.keys();for(let l=0;l<s;l++){let c=o.next().value;c!==void 0&&e.delete(c)}console.log(`[QueenCoordinator] Evicted ${s} oldest trace contexts (max: ${r})`)}return i>0&&console.log(`[QueenCoordinator] Cleaned up ${i} old tasks (retention: ${t}ms)`),i}function nn(a,e){return a&&a.size>0?Array.from(a.keys()):[...e]}var g=it.create("QueenCoordinator");zt(v);var Je=class{constructor(e,t,n,i,r,s,o,l={}){this.eventBus=e;this.agentCoordinator=t;this.memory=n;this.router=i;this.protocolExecutor=r;this.workflowExecutor=s;this.domainPlugins=o;this.config={...Ut,...l},this.auditLogger=he({enableConsoleLog:this.config.enableMetrics,maxEntries:1e3,logPrefix:"[QUEEN]"}),["p0","p1","p2","p3"].forEach(c=>{this.taskQueue.set(c,[])}),this.config.enableRouting!==!1&&(this.tinyDancerRouter=new j(this.config.routing)),v.forEach(c=>{this.domainQueues.set(c,[]),this.domainLastActivity.set(c,new Date)})}eventBus;agentCoordinator;memory;router;protocolExecutor;workflowExecutor;domainPlugins;config;tasks=new Map;taskQueue=new Map;domainQueues=new Map;domainLastActivity=new Map;initialized=!1;workStealingTimer=null;metricsTimer=null;cleanupTimer=null;startTime=new Date;eventSubscriptionIds=[];runningTaskCounter=0;tasksReceived=0;tasksCompleted=0;tasksFailed=0;tasksStolen=0;taskDurations=new nt(1e3);protocolsExecuted=0;workflowsExecuted=0;auditLogger;minCutBridge=null;tinyDancerRouter=null;domainBreakerRegistry=null;domainTeamManager=null;agentTeamsAdapter=null;tierSelector=null;taskCompletedHook=null;traceCollector=null;taskTraceContexts=new Map;hypothesisManager=null;federationMailbox=null;dynamicScaler=null;coExecutionRepo=null;dependencyGraph=null;availableMcpServers=[];async initialize(){if(!this.initialized){this.startTime=new Date,await this.router.initialize(),this.subscribeToEvents(),this.config.workStealing.enabled&&(this.workStealingTimer=Ye(this.config,()=>this.triggerWorkStealing().then(()=>{}))),this.config.enableMetrics&&(this.metricsTimer=tn(this.createMetricsContext())),this.cleanupTimer=setInterval(()=>{Xe(this.tasks,this.taskTraceContexts,36e5)},3e5),this.cleanupTimer.unref(),await Jt(this.memory,this.tasks,e=>this.enqueueTaskInternal(e)),this.minCutBridge=ht(this.eventBus,this.agentCoordinator,{autoUpdateFromEvents:!0,persistData:!0,includeInQueenHealth:!0,sharedGraph:ct()}),await this.minCutBridge.initialize(),this.domainPlugins&&Xt(this.domainPlugins,this.minCutBridge);try{await I.initialize(),g.info("Governance adapter initialized")}catch(e){g.warn("Governance initialization failed (continuing)",{error:e})}this.initializeSubsystems();try{let{join:e}=await import("path"),t=e(process.cwd(),".claude","agents","v3");this.dependencyGraph=Rt(t),this.availableMcpServers=dt(process.cwd());let{getUnifiedMemory:n}=await import("./unified-memory-5KQMA7FV.js"),i=n();await i.initialize(),this.coExecutionRepo=wt(),this.coExecutionRepo.initialize(i.getDatabase()),this.dependencyGraph.warnings.length>0&&g.warn(`Dependency graph: ${this.dependencyGraph.warnings.length} warning(s)`,{warnings:this.dependencyGraph.warnings.slice(0,5)}),g.info("Dependency intelligence initialized",{agents:this.dependencyGraph.nodes.size,mcpServers:this.availableMcpServers.length})}catch(e){g.warn("Dependency intelligence initialization failed (continuing)",{error:e})}await this.publishEvent("QueenInitialized",{timestamp:new Date,config:this.config,domains:v}),this.initialized=!0}}async dispose(){this.workStealingTimer&&(clearInterval(this.workStealingTimer),this.workStealingTimer=null),this.metricsTimer&&(clearInterval(this.metricsTimer),this.metricsTimer=null),this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null),this.minCutBridge&&(await this.minCutBridge.dispose(),this.minCutBridge=null),this.domainTeamManager&&(this.domainTeamManager.dispose(),this.domainTeamManager=null),this.agentTeamsAdapter&&(this.agentTeamsAdapter.shutdown(),this.agentTeamsAdapter=null),this.domainBreakerRegistry=null,this.tierSelector=null,this.traceCollector&&(this.traceCollector.dispose(),this.traceCollector=null),this.hypothesisManager&&(this.hypothesisManager.dispose(),this.hypothesisManager=null),this.federationMailbox&&(this.federationMailbox.dispose(),this.federationMailbox=null),this.dynamicScaler&&(this.dynamicScaler.dispose(),this.dynamicScaler=null),await en(this.memory,this.tasks);for(let[e,t]of this.tasks)(t.status==="queued"||t.status==="running")&&await this.cancelTask(e);await this.publishEvent("QueenShutdown",{timestamp:new Date,metrics:this.getMetrics()});for(let e of this.eventSubscriptionIds)this.router.unsubscribe(e);this.eventSubscriptionIds=[],await this.router.dispose(),this.initialized=!1}async submitTask(e){if(!this.initialized)return y(new Error("Queen Coordinator not initialized"));let t=`task_${T()}`,n={...e,id:t,createdAt:new Date,timeout:e.timeout||this.config.defaultTaskTimeout},i={taskId:n.id,taskType:n.type,agentId:n.requester||`queen-task:${n.id}`,domain:n.targetDomains[0]||"test-generation",priority:n.priority,payload:n.payload};try{let r=await I.beforeTaskExecution(i);if(!r.allowed)return this.auditLogger.logFail(t,"governance",r.reason||"Governance check failed"),await this.publishEvent("TaskRejected",{taskId:t,reason:r.reason,escalate:r.escalate}),y(new Error(`Task blocked by governance: ${r.reason}`))}catch(r){g.warn("Governance check error (continuing)",{error:r})}this.runningTaskCounter++;try{if(this.runningTaskCounter>this.config.maxConcurrentTasks)return this.runningTaskCounter--,this.queueTask(n);this.auditLogger.logSubmit(t,{type:n.type,priority:n.priority}),this.selectFleetTier(n),this.startTaskTrace(n,t);let r=await Ve(this.createTaskContext(),n);return r.success?(this.tasksReceived++,await this.publishEvent("TaskSubmitted",{taskId:t,task:n}),b(t)):(this.runningTaskCounter--,r)}catch(r){throw this.runningTaskCounter--,r}}async cancelTask(e){let t=this.tasks.get(e);if(!t)return y(new Error(`Task not found: ${e}`));if(t.status==="completed"||t.status==="failed")return y(new Error(`Task already finished: ${e}`));(t.status==="running"||t.status==="assigned")&&(this.runningTaskCounter=Math.max(0,this.runningTaskCounter-1)),this.tasks.set(e,{...t,status:"cancelled",completedAt:new Date}),de(this.taskQueue,this.domainQueues,t.task);for(let n of t.assignedAgents)await this.agentCoordinator.stop(n);return this.auditLogger.logCancel(e),await this.publishEvent("TaskCancelled",{taskId:e}),b(void 0)}getTaskStatus(e){return this.tasks.get(e)}listTasks(e){return Kt(this.tasks,e)}getDomainHealth(e){if(this.domainPlugins){let t=this.domainPlugins.get(e);if(t)return t.getHealth()}return Wt(this.agentCoordinator,e,this.domainLastActivity.get(e))}getDomainLoad(e){let t=this.domainQueues.get(e)||[],n=Array.from(this.tasks.values()).filter(i=>i.assignedDomain===e&&i.status==="running");return t.length+n.length}getIdleDomains(){let e=Date.now(),t=this.config.workStealing.idleThreshold;return v.filter(n=>{let i=this.domainLastActivity.get(n);return this.getDomainLoad(n)===0&&i&&e-i.getTime()>t})}getBusyDomains(){return v.filter(e=>this.getDomainLoad(e)>this.config.workStealing.loadThreshold)}getSpawnPlan(e){return this.dependencyGraph?_t(e,this.dependencyGraph):{phases:[e],warnings:[],unsatisfiedHardDeps:[]}}getDependencyGraph(){return this.dependencyGraph}enableWorkStealing(){this.workStealingTimer||(this.workStealingTimer=Ye(this.config,()=>this.triggerWorkStealing().then(()=>{})))}disableWorkStealing(){this.workStealingTimer&&(clearInterval(this.workStealingTimer),this.workStealingTimer=null)}async triggerWorkStealing(){return Zt(this.createWorkStealingContext())}listAllAgents(){return this.agentCoordinator.listAgents()}getAgentsByDomain(e){return this.agentCoordinator.listAgents({domain:e})}async requestAgentSpawn(e,t,n){if(!this.agentCoordinator.canSpawn())return y(new Error("Maximum concurrent agents reached (15)"));if(this.dependencyGraph&&this.availableMcpServers.length>0)try{for(let[,r]of this.dependencyGraph.nodes){let s=r.dependencies.mcpServers;if(!s||s.length===0)continue;let o=s.filter(l=>l.required&&!this.availableMcpServers.includes(l.name));if(o.length>0){g.warn(`Pre-spawn MCP advisory: ${r.agentName} needs ${o.map(l=>l.name).join(", ")}`,{agent:r.agentName,domain:e,missing:o.map(l=>l.name)});break}}}catch{}let i=await this.agentCoordinator.spawn({name:`${e}-${t}-${Date.now()}`,domain:e,type:t,capabilities:n});if(i.success){if(this.domainLastActivity.set(e,new Date),this.domainTeamManager&&typeof this.domainTeamManager.getDomainTeam=="function")try{if(this.domainTeamManager.getDomainTeam(e))this.domainTeamManager.addTeammate(e,i.value)||g.warn(`Agent ${i.value} could not join ${e} team (full)`);else try{this.domainTeamManager.createDomainTeam(e,i.value)}catch{this.domainTeamManager.addTeammate(e,i.value)||g.warn(`Agent ${i.value} could not join ${e} team (full or max teams reached)`)}}catch(r){g.warn(`Auto-team-wiring failed for ${i.value}`,{error:r})}await this.publishEvent("AgentSpawned",{agentId:i.value,domain:e,type:t,capabilities:n})}return i}getHealth(){let e=new Map,t=[],n=0,i=0,r=nn(this.domainPlugins,v);for(let u of r){let d=this.getDomainHealth(u);d&&(e.set(u,d),d.status==="unhealthy"?(n++,t.push({domain:u,severity:"high",message:`Domain ${u} is unhealthy`,timestamp:new Date})):d.status==="degraded"&&(i++,t.push({domain:u,severity:"medium",message:`Domain ${u} is degraded`,timestamp:new Date})))}let s=this.agentCoordinator.listAgents(),o=s.filter(u=>u.status==="running").length,l="healthy";n>0?l="unhealthy":i>r.length/2&&(l="degraded");let c={status:l,domainHealth:e,totalAgents:s.length,activeAgents:o,pendingTasks:this.getQueuedTaskCount(),runningTasks:this.getRunningTaskCount(),workStealingActive:this.workStealingTimer!==null,lastHealthCheck:new Date,issues:t};return this.minCutBridge?this.minCutBridge.extendQueenHealth(c):c}getMetrics(){let e=new Map;for(let o of v){let l=this.getDomainLoad(o);e.set(o,l)}let t=this.agentCoordinator.listAgents(),n=t.filter(o=>o.status==="running").length,i=t.length>0?n/t.length:0,r=this.taskDurations.average(),s={tasksReceived:this.tasksReceived,tasksCompleted:this.tasksCompleted,tasksFailed:this.tasksFailed,tasksStolen:this.tasksStolen,averageTaskDuration:r,domainUtilization:e,agentUtilization:i,protocolsExecuted:this.protocolsExecuted,workflowsExecuted:this.workflowsExecuted,uptime:Date.now()-this.startTime.getTime()};return this.minCutBridge?this.minCutBridge.extendQueenMetrics(s):s}getMinCutBridge(){return this.minCutBridge}injectMinCutBridgeIntoDomain(e){if(!this.minCutBridge)return g.warn("Cannot inject MinCut bridge: bridge not initialized"),!1;if(!this.domainPlugins)return g.warn("Cannot inject MinCut bridge: no domain plugins registered"),!1;let t=this.domainPlugins.get(e);return t?Ze(t)?(t.setMinCutBridge(this.minCutBridge),g.info(`MinCut bridge injected into ${e} (late binding)`),!0):(g.warn(`Domain ${e} does not support MinCut integration`),!1):(g.warn(`Cannot inject MinCut bridge: domain ${e} not found`),!1)}getTinyDancerRouter(){return this.tinyDancerRouter}getDomainBreakerRegistry(){return this.domainBreakerRegistry}getDomainTeamManager(){return this.domainTeamManager}getAgentTeamsAdapter(){return this.agentTeamsAdapter}getTierSelector(){return this.tierSelector}getTraceCollector(){return this.traceCollector}getHypothesisManager(){return this.hypothesisManager}getFederationMailbox(){return this.federationMailbox}getDynamicScaler(){return this.dynamicScaler}connectReasoningBank(e){let t=new ae(e);this.taskCompletedHook=new se({},t),g.info("ReasoningBank connected for pattern training")}async executeProtocol(e,t){if(!this.protocolExecutor)return y(new Error("Protocol executor not configured"));let n=await this.protocolExecutor.execute(e,t);return n.success?(this.protocolsExecuted++,await this.publishEvent("ProtocolExecuted",{protocolId:e,executionId:n.value.executionId}),b(n.value.executionId)):n}async executeWorkflow(e,t){if(!this.workflowExecutor)return y(new Error("Workflow executor not configured"));let n=await this.workflowExecutor.execute(e,t);return n.success?(this.workflowsExecuted++,await this.publishEvent("WorkflowExecuted",{workflowId:e,executionId:n.value.executionId}),b(n.value.executionId)):n}cleanupCompletedTasks(e=36e5){return Xe(this.tasks,this.taskTraceContexts,e)}subscribeToEvents(){this.eventSubscriptionIds=jt(this.createEventHandlerContext(),v)}enqueueTaskInternal(e){Vt(this.taskQueue,this.domainQueues,e)}async publishEvent(e,t){await this.eventBus.publish({id:T(),type:`Queen${e}`,timestamp:new Date,source:"queen-coordinator",payload:t})}queueTask(e){this.enqueueTaskInternal(e);let t={taskId:e.id,task:e,status:"queued",assignedAgents:[],retryCount:0};return this.tasks.set(e.id,t),this.tasksReceived++,this.auditLogger.logSubmit(e.id,{type:e.type,priority:e.priority}),this.auditLogger.logQueue(e.id,je(this.taskQueue,e)),this.publishEvent("TaskQueued",{taskId:e.id,task:e,position:je(this.taskQueue,e)}),b(e.id)}selectFleetTier(e){if(this.tierSelector)try{let t={trigger:e.payload?.trigger??"manual",changedFiles:e.payload?.changedFiles,affectedDomains:e.targetDomains,severity:e.priority==="p0"?"critical":e.priority==="p1"?"high":void 0,isHotfix:e.payload?.isHotfix},n=this.tierSelector.selectTier(t);return g.info(`Fleet tier: ${n.selectedTier} (${n.reason})`),n.selectedTier}catch(t){g.warn("Tier selection error (continuing)",{error:t});return}}startTaskTrace(e,t){if(this.traceCollector)try{let{context:n}=this.traceCollector.startTrace({operationName:e.type,agentId:e.requester||"queen",domain:e.targetDomains[0]||"test-generation",tags:{taskId:t,priority:e.priority}});if(this.taskTraceContexts.size>=1e4){let r=this.taskTraceContexts.keys().next().value;r!==void 0&&this.taskTraceContexts.delete(r)}this.taskTraceContexts.set(t,n)}catch(n){g.warn("Trace start error (continuing)",{error:n})}}getRunningTaskCount(){return Array.from(this.tasks.values()).filter(e=>e.status==="running"||e.status==="assigned").length}getQueuedTaskCount(){return Array.from(this.tasks.values()).filter(e=>e.status==="queued").length}initializeSubsystems(){if(this.config.enableCircuitBreakers!==!1)try{this.domainBreakerRegistry=Ot(),g.info("Domain circuit breaker registry initialized")}catch(e){g.warn("Circuit breaker initialization failed (continuing)",{error:e})}if(this.config.enableDomainTeams!==!1)try{this.agentTeamsAdapter=Ae(),this.agentTeamsAdapter.initialize(),this.domainTeamManager=Ee(this.agentTeamsAdapter),g.info("Domain team manager initialized")}catch(e){g.warn("Domain team manager initialization failed (continuing)",{error:e})}if(this.config.enableFleetTiers!==!1)try{this.tierSelector=Re(),g.info("Fleet tier selector initialized")}catch(e){g.warn("Tier selector initialization failed (continuing)",{error:e})}try{this.traceCollector=xe(),g.info("Trace collector initialized")}catch(e){g.warn("Trace collector initialization failed (continuing)",{error:e})}try{this.hypothesisManager=Fe(),this.federationMailbox=Oe(),this.dynamicScaler=Le(),g.info("Phase 4 modules initialized (hypotheses, federation, scaling)")}catch(e){g.warn("Phase 4 initialization failed (continuing)",{error:e})}}createEventHandlerContext(){let e=this;return{config:e.config,tasks:e.tasks,domainLastActivity:e.domainLastActivity,auditLogger:e.auditLogger,router:e.router,agentCoordinator:e.agentCoordinator,get runningTaskCounter(){return e.runningTaskCounter},set runningTaskCounter(t){e.runningTaskCounter=t},get tasksCompleted(){return e.tasksCompleted},set tasksCompleted(t){e.tasksCompleted=t},get tasksFailed(){return e.tasksFailed},set tasksFailed(t){e.tasksFailed=t},taskDurations:e.taskDurations,get domainBreakerRegistry(){return e.domainBreakerRegistry},get traceCollector(){return e.traceCollector},taskTraceContexts:e.taskTraceContexts,get taskCompletedHook(){return e.taskCompletedHook},get hypothesisManager(){return e.hypothesisManager},processQueue:()=>We(e.createTaskContext()),enqueueTask:t=>e.enqueueTaskInternal(t)}}createTaskContext(){let e=this;return{config:e.config,tasks:e.tasks,taskQueue:e.taskQueue,domainQueues:e.domainQueues,domainLastActivity:e.domainLastActivity,auditLogger:e.auditLogger,agentCoordinator:e.agentCoordinator,domainPlugins:e.domainPlugins,get runningTaskCounter(){return e.runningTaskCounter},set runningTaskCounter(t){e.runningTaskCounter=t},get tasksReceived(){return e.tasksReceived},set tasksReceived(t){e.tasksReceived=t},get tasksCompleted(){return e.tasksCompleted},set tasksCompleted(t){e.tasksCompleted=t},get tasksFailed(){return e.tasksFailed},set tasksFailed(t){e.tasksFailed=t},taskDurations:e.taskDurations,get tinyDancerRouter(){return e.tinyDancerRouter},get domainBreakerRegistry(){return e.domainBreakerRegistry},get domainTeamManager(){return e.domainTeamManager},get tierSelector(){return e.tierSelector},get traceCollector(){return e.traceCollector},taskTraceContexts:e.taskTraceContexts,get coExecutionRepo(){return e.coExecutionRepo},requestAgentSpawn:(t,n,i)=>e.requestAgentSpawn(t,n,i),publishEvent:(t,n)=>e.publishEvent(t,n),getDomainLoad:t=>e.getDomainLoad(t),getDomainHealth:t=>e.getDomainHealth(t)}}createWorkStealingContext(){let e=this;return{config:e.config,domainQueues:e.domainQueues,auditLogger:e.auditLogger,get tasksStolen(){return e.tasksStolen},set tasksStolen(t){e.tasksStolen=t},getIdleDomains:()=>e.getIdleDomains(),getBusyDomains:()=>e.getBusyDomains(),getDomainLoad:t=>e.getDomainLoad(t),removeFromQueues:t=>de(e.taskQueue,e.domainQueues,t),assignTaskToDomain:(t,n)=>Ke(e.createTaskContext(),t,n).then(()=>{}),publishEvent:(t,n)=>e.publishEvent(t,n)}}createMetricsContext(){let e=this;return{config:e.config,memory:e.memory,get dynamicScaler(){return e.dynamicScaler},getMetrics:()=>e.getMetrics(),publishEvent:(t,n)=>e.publishEvent(t,n),getQueuedTaskCount:()=>e.getQueuedTaskCount(),getActiveAgentCount:()=>e.agentCoordinator.listAgents().filter(t=>t.status==="running").length,getIdleAgentCount:()=>e.agentCoordinator.listAgents().filter(t=>t.status==="idle").length,getAverageTaskDuration:()=>e.taskDurations.average(),getTasksReceived:()=>e.tasksReceived,getTasksFailed:()=>e.tasksFailed,getTasksCompleted:()=>e.tasksCompleted}}};function uo(a,e,t,n,i,r){return new Je(a.eventBus,a.coordinator,a.memory,e,t,n,i,r)}export{ei as a,P as b,Je as c,uo as d};
@@ -1,4 +1,4 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.11");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.0");process.exit(0)}
2
2
  var P="quality-daemon",x=class{constructor(e){this.backend=e}backend;async get(e){return this.backend.kvGet(e,P)}async set(e,t){await this.backend.kvSet(e,t,P)}async search(e){return this.backend.kvSearch(e,P)}};import{cpus as Z,freemem as ee,totalmem as te,loadavg as ie}from"os";var g=class{queues={now:[],next:[],later:[]};_maxSize;constructor(e=1e3){this._maxSize=e}enqueue(e){return this.size>=this._maxSize?!1:(this.queues[e.priority].push(e),!0)}dequeue(){let e=Date.now();for(let t of["now","next","later"]){let i=this.queues[t];for(;i.length>0;){let o=i.shift();if(!(o.ttlMs&&e-o.createdAt>o.ttlMs))return o}}}peek(){let e=Date.now();for(let t of["now","next","later"]){let i=this.queues[t];for(let o of i)if(!o.ttlMs||e-o.createdAt<=o.ttlMs)return o}}drainPriority(e){let t=this.queues[e].splice(0),i=Date.now();return t.filter(o=>!o.ttlMs||i-o.createdAt<=o.ttlMs)}pruneExpired(){let e=0,t=Date.now();for(let i of["now","next","later"]){let o=this.queues[i].length;this.queues[i]=this.queues[i].filter(r=>!r.ttlMs||t-r.createdAt<=r.ttlMs),e+=o-this.queues[i].length}return e}get size(){return this.queues.now.length+this.queues.next.length+this.queues.later.length}get depths(){return{now:this.queues.now.length,next:this.queues.next.length,later:this.queues.later.length}}get isEmpty(){return this.size===0}clear(){this.queues.now=[],this.queues.next=[],this.queues.later=[]}};import{watch as G}from"fs";import{execFile as Q}from"child_process";import{promisify as $}from"util";import{resolve as q,join as H}from"path";import{existsSync as L,readFileSync as U}from"fs";var _=$(Q),z={repoRoot:process.cwd(),debounceMs:500,maxChangedFiles:200,pollIntervalMs:5e3},p=class{constructor(e,t){this.queue=e;this.options={...z,...t}}queue;watcher;pollTimer;options;lastKnownHeads=new Map;debounceTimer;_running=!1;_polling=!1;get running(){return this._running}async start(){if(this._running)return;let e=q(this.options.repoRoot,".git","refs","heads");if(!L(e))throw new Error(`Git refs directory not found: ${e}`);await this.snapshotHeads(),process.platform==="darwin"||process.platform==="win32"?this.watcher=G(e,{recursive:!0},(i,o)=>{o&&this.handleRefChange(o)}):(this.pollTimer=setInterval(()=>{this.poll().catch(i=>{console.debug("[GitWatcher] Poll error:",i)})},this.options.pollIntervalMs),this.pollTimer.unref?.()),this._running=!0}stop(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=void 0),this.watcher&&(this.watcher.close(),this.watcher=void 0),this._running=!1}async poll(){if(this._polling)return[];this._polling=!0;let e=[];try{let{stdout:t}=await _("git",["for-each-ref","--format=%(refname:short) %(objectname:short)","refs/heads/"],{cwd:this.options.repoRoot});for(let i of t.trim().split(`
3
3
  `)){if(!i)continue;let[o,r]=i.split(" "),n=this.lastKnownHeads.get(o);n&&n!==r&&(e.push(o),await this.enqueueCommitAnalysis(o,r)),this.lastKnownHeads.set(o,r)}}catch{}finally{this._polling=!1}return e}handleRefChange(e){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.processRefChange(e).catch(t=>{console.debug("[GitWatcher] Error processing ref change:",t)})},this.options.debounceMs)}async processRefChange(e){let t=e.replace(/\\/g,"/"),i=q(this.options.repoRoot,".git","refs","heads"),o=H(i,e),r;try{r=U(o,"utf-8").trim()}catch{return}this.lastKnownHeads.get(t)!==r&&(this.lastKnownHeads.set(t,r),await this.enqueueCommitAnalysis(t,r))}async enqueueCommitAnalysis(e,t){let i=[];try{let{stdout:n}=await _("git",["diff-tree","--no-commit-id","--name-only","-r",t],{cwd:this.options.repoRoot});i=n.trim().split(`
4
4
  `).filter(Boolean).slice(0,this.options.maxChangedFiles)}catch{}let o={type:"git_commit",branch:e,commitHash:t,changedFiles:i},r={id:`git-${t}-${Date.now()}`,priority:"next",payload:o,createdAt:Date.now(),source:"git-watcher",ttlMs:300*1e3};this.queue.enqueue(r)}async snapshotHeads(){try{let{stdout:e}=await _("git",["for-each-ref","--format=%(refname:short) %(objectname:short)","refs/heads/"],{cwd:this.options.repoRoot});for(let t of e.trim().split(`
@@ -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.13.11");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.0");process.exit(0)}
2
2
  var s={"test-generation":/test|spec|describe|it\(|expect|assert|mock|stub|fixture|tdd|bdd/i,"test-execution":/run|execute|parallel|retry|flaky|timeout|worker|orchestrat/i,"coverage-analysis":/coverage|branch|line|uncovered|gap|untested|percentage|sublinear/i,"quality-assessment":/quality|gate|deploy|readiness|metric|threshold|sla|score/i,"defect-intelligence":/defect|bug|predict|root.?cause|regression|failure|incident/i,"requirements-validation":/requirement|bdd|gherkin|testabil|accept|criteri|scenario/i,"code-intelligence":/semantic|knowledge|graph|ast|symbol|reference|impact|depend/i,"security-compliance":/vuln|cve|owasp|xss|sqli|injection|csrf|auth|secret|compliance|sast|dast/i,"contract-testing":/contract|pact|openapi|swagger|graphql|schema|endpoint|api/i,"visual-accessibility":/screenshot|visual|snapshot|pixel|percy|a11y|aria|wcag|screen.?reader|accessible|contrast/i,"chaos-resilience":/chaos|resilience|fault|inject|blast|recover|latency|failure|stress|load/i,"learning-optimization":/learn|pattern|optim|neural|embedding|vector|memory|adapt|train/i};function l(e){for(let[t,a]of Object.entries(s))if(a.test(e))return t;return null}function m(e){let t=[];for(let[a,n]of Object.entries(s))n.test(e)&&t.push(a);return t}function u(e){return e}function d(e){let t=Math.min(e.usageCount/100,1);return e.confidence*.3+t*.2+e.successRate*.5}var c=3;function p(e,t,a=.4){let n=e.tier==="short-term"&&e.successfulUses>=c,r=e.successRate>=.7&&e.confidence>=.6,i=t===void 0||t<a,o;return n?r?i||(o="coherence_violation"):o="low_quality":o="insufficient_usage",{meetsUsageCriteria:n,meetsQualityCriteria:r,meetsCoherenceCriteria:i,blockReason:o}}function y(e){let t=[];if(e.id||t.push("Pattern ID is required"),e.patternType||t.push("Pattern type is required"),e.qeDomain||t.push("QE domain is required"),e.name||t.push("Pattern name is required"),e.template?.content||t.push("Template content is required"),e.confidence!==void 0&&(e.confidence<0||e.confidence>1)&&t.push("Confidence must be between 0 and 1"),e.successRate!==void 0&&(e.successRate<0||e.successRate>1)&&t.push("Success rate must be between 0 and 1"),e.template?.variables){let a=new Set;for(let n of e.template.variables)a.has(n.name)&&t.push(`Duplicate variable name: ${n.name}`),a.add(n.name),e.template.content.includes(`{{${n.name}}}`)||t.push(`Variable ${n.name} not referenced in template`)}return{valid:t.length===0,errors:t}}function f(e,t){let a=e.content;for(let n of e.variables){let r=t[n.name]??n.defaultValue;if(n.required&&r===void 0)throw new Error(`Required variable ${n.name} not provided`);if(r!==void 0){let i=`{{${n.name}}}`,o=typeof r=="object"?JSON.stringify(r):String(r);a=a.split(i).join(o)}}return a}var g=Object.keys(s);export{l as a,m as b,u as c,d,c as e,p as f,y as g,f as h,g as i};
@@ -0,0 +1,2 @@
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.0");process.exit(0)}
2
+ import{a as r,h as n}from"./chunk-5XGVSQS2.js";var a={claude:"metered-api","claude-code":"subscription",codex:"subscription",openai:"metered-api",openrouter:"metered-api",gemini:"metered-api","azure-openai":"metered-api",bedrock:"metered-api",cognitum:"metered-capped",ollama:"local"};function o(e){return r(e)?a[e]:void 0}function p(e){return e.billingMode??o(e.type)??"metered-api"}function c(e){return o(e)??"metered-api"}function g(e,t){switch(t){case"metered-api":return`\u26A0\uFE0F LLM provider "${e}" bills a pay-per-token API key (not your Claude subscription) and has no server-side spend cap. Set a budget with --max-budget-usd / AQE_MAX_BUDGET_USD, or use AQE_LLM_PROVIDER=claude-code to run on your Claude Code subscription instead.`;case"metered-capped":return`\u2139\uFE0F LLM provider "${e}" bills per-token but enforces a server-side hard spend cap; it will pause at the cap rather than overspend.`;case"subscription":{let i=n(e);if(i){let d=i.detail?`declared by ${i.detail}`:`declared by ${i.source==="config"?"config":"the registering caller"}`;return`\u2139\uFE0F LLM provider "${e}" is an external provider that reports subscription billing (${d}) \u2014 AQE does not verify this. It draws on that host's own plan, not on your Claude Code or ChatGPT subscription.`}return`\u2139\uFE0F LLM provider "${e}" runs on your ${e==="codex"?"ChatGPT":"Claude Code"} subscription (shared plan usage). Worst case is hitting your plan's rate limit and pausing \u2014 no per-token API charges.`}case"local":return}}export{p as a,c as b,g 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.13.11");process.exit(0)}
2
- import{c as h}from"./chunk-LUAXQB57.js";function i(t,r){if(t.length!==r.length)throw new Error(`Vector length mismatch: ${t.length} vs ${r.length}`);let e=0,o=0,l=0;for(let n=0;n<t.length;n++)e+=t[n]*r[n],o+=t[n]*t[n],l+=r[n]*r[n];let u=Math.sqrt(o)*Math.sqrt(l);return u===0?0:e/u}function c(t){let r=Math.sqrt(t.reduce((e,o)=>e+o*o,0));return r===0?t.slice():t.map(e=>e/r)}function g(t){let r=0;for(let e=0;e<t.length;e++)r+=t[e]*t[e];return Math.sqrt(r)}var m=h(()=>{"use strict"});export{i as a,c as b,g as c,m 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.14.0");process.exit(0)}
2
+ import{c as h}from"./chunk-PEW6FZ47.js";function i(t,r){if(t.length!==r.length)throw new Error(`Vector length mismatch: ${t.length} vs ${r.length}`);let e=0,o=0,l=0;for(let n=0;n<t.length;n++)e+=t[n]*r[n],o+=t[n]*t[n],l+=r[n]*r[n];let u=Math.sqrt(o)*Math.sqrt(l);return u===0?0:e/u}function c(t){let r=Math.sqrt(t.reduce((e,o)=>e+o*o,0));return r===0?t.slice():t.map(e=>e/r)}function g(t){let r=0;for(let e=0;e<t.length;e++)r+=t[e]*t[e];return Math.sqrt(r)}var m=h(()=>{"use strict"});export{i as a,c as b,g as c,m as d};
@@ -1,4 +1,4 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.11");process.exit(0)}
2
- import{b as f,d as v}from"./chunk-TZA45FI7.js";import q,{MultiBar as F,Presets as k}from"cli-progress";import O from"ora";import o from"chalk";v();import{existsSync as w,readFileSync as y,writeFileSync as j,mkdirSync as W,unlinkSync as V}from"fs";import{join as p}from"path";import{homedir as C}from"os";var u={wizards:{enabled:!0,themes:["default","minimal","detailed"],defaultTheme:"default"},progress:{style:"multi-bar",updateIntervalMs:100,showETA:!0,colors:!0},completion:{maxSuggestions:10,historyWeight:.3,contextWeight:.7,fuzzyMatch:!0},streaming:{enabled:!0,bufferSize:100,updateIntervalMs:50}};function x(){return p(C(),".aqe")}function E(){return p(x(),"cli-config.json")}var g=null,d=0,T=5e3;function S(){return g?Date.now()-d<T:!1}function A(s){let e=[],t=s;if(typeof t.enabled!="boolean"&&t.enabled!==void 0&&e.push({path:"wizards.enabled",message:"must be a boolean"}),t.themes!==void 0)if(!Array.isArray(t.themes))e.push({path:"wizards.themes",message:"must be an array"});else{let r=["default","minimal","detailed"];for(let n of t.themes)r.includes(n)||e.push({path:"wizards.themes",message:`invalid theme: ${n}`})}return t.defaultTheme!==void 0&&(["default","minimal","detailed"].includes(t.defaultTheme)||e.push({path:"wizards.defaultTheme",message:`invalid theme: ${t.defaultTheme}`})),e}function P(s){let e=[],t=s;return t.style!==void 0&&(["multi-bar","single-bar","spinner"].includes(t.style)||e.push({path:"progress.style",message:`invalid style: ${t.style}`})),t.updateIntervalMs!==void 0&&(typeof t.updateIntervalMs!="number"||t.updateIntervalMs<10)&&e.push({path:"progress.updateIntervalMs",message:"must be a number >= 10"}),typeof t.showETA!="boolean"&&t.showETA!==void 0&&e.push({path:"progress.showETA",message:"must be a boolean"}),typeof t.colors!="boolean"&&t.colors!==void 0&&e.push({path:"progress.colors",message:"must be a boolean"}),e}function $(s){let e=[],t=s;return t.maxSuggestions!==void 0&&(typeof t.maxSuggestions!="number"||t.maxSuggestions<1)&&e.push({path:"completion.maxSuggestions",message:"must be a number >= 1"}),t.historyWeight!==void 0&&(typeof t.historyWeight!="number"||t.historyWeight<0||t.historyWeight>1)&&e.push({path:"completion.historyWeight",message:"must be a number between 0 and 1"}),t.contextWeight!==void 0&&(typeof t.contextWeight!="number"||t.contextWeight<0||t.contextWeight>1)&&e.push({path:"completion.contextWeight",message:"must be a number between 0 and 1"}),typeof t.fuzzyMatch!="boolean"&&t.fuzzyMatch!==void 0&&e.push({path:"completion.fuzzyMatch",message:"must be a boolean"}),e}function I(s){let e=[],t=s;return typeof t.enabled!="boolean"&&t.enabled!==void 0&&e.push({path:"streaming.enabled",message:"must be a boolean"}),t.bufferSize!==void 0&&(typeof t.bufferSize!="number"||t.bufferSize<1)&&e.push({path:"streaming.bufferSize",message:"must be a number >= 1"}),t.updateIntervalMs!==void 0&&(typeof t.updateIntervalMs!="number"||t.updateIntervalMs<10)&&e.push({path:"streaming.updateIntervalMs",message:"must be a number >= 10"}),e}function M(s){let e=[];if(typeof s!="object"||s===null)return{valid:!1,errors:[{path:"",message:"config must be an object"}]};let t=s;return t.wizards!==void 0&&(typeof t.wizards!="object"||t.wizards===null?e.push({path:"wizards",message:"must be an object"}):e.push(...A(t.wizards))),t.progress!==void 0&&(typeof t.progress!="object"||t.progress===null?e.push({path:"progress",message:"must be an object"}):e.push(...P(t.progress))),t.completion!==void 0&&(typeof t.completion!="object"||t.completion===null?e.push({path:"completion",message:"must be an object"}):e.push(...$(t.completion))),t.streaming!==void 0&&(typeof t.streaming!="object"||t.streaming===null?e.push({path:"streaming",message:"must be an object"}):e.push(...I(t.streaming))),{valid:e.length===0,errors:e}}var z=["__proto__","constructor","prototype"];function m(s,e){let t={...s};for(let r of Object.keys(e)){if(z.includes(r)){console.warn(`Security: Skipping forbidden key '${String(r)}' in configuration merge`);continue}let n=e[r],i=s[r];n!==void 0&&typeof n=="object"&&!Array.isArray(n)&&typeof i=="object"&&!Array.isArray(i)?t[r]=m(i,n):n!==void 0&&(t[r]=n)}return t}function D(){let s=E();if(!w(s))return{...u};try{let e=y(s,"utf-8"),t=f(e),r=M(t);return r.valid?m(u,t):(console.warn(`CLI config validation errors: ${r.errors.map(n=>`${n.path}: ${n.message}`).join(", ")}`),console.warn("Using default configuration"),{...u})}catch(e){return console.warn(`Failed to load CLI config: ${e instanceof Error?e.message:"Unknown error"}`),{...u}}}function c(){return S()||(g=D(),d=Date.now()),g}function B(){return process.stdout.isTTY===!0}function h(){let s=c();return process.env.NO_COLOR!==void 0?!1:process.env.FORCE_COLOR!==void 0?!0:s.progress.colors&&B()}var b=class{multiBar;agentBars=new Map;agentStates=new Map;fleetBar=null;startTime=Date.now();options;isActive=!1;constructor(e={}){let t=c(),r=h();this.options={title:"Fleet Progress",showEta:t.progress.showETA,showPercentage:!0,...e};let n=r?o.cyan("{bar}"):"{bar}",i=this.options.format||`{name} ${n} {percentage}% | {status} {eta}`;this.multiBar=new F({clearOnComplete:!1,hideCursor:!0,format:i,barCompleteChar:"\u2588",barIncompleteChar:"\u2591",forceRedraw:!0,fps:Math.round(1e3/t.progress.updateIntervalMs)},k.shades_classic)}start(e){this.isActive=!0,this.startTime=Date.now(),console.log(o.blue(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.0");process.exit(0)}
2
+ import{b as f,d as v}from"./chunk-HQHLHSJO.js";import q,{MultiBar as F,Presets as k}from"cli-progress";import O from"ora";import o from"chalk";v();import{existsSync as w,readFileSync as y,writeFileSync as j,mkdirSync as W,unlinkSync as V}from"fs";import{join as p}from"path";import{homedir as C}from"os";var u={wizards:{enabled:!0,themes:["default","minimal","detailed"],defaultTheme:"default"},progress:{style:"multi-bar",updateIntervalMs:100,showETA:!0,colors:!0},completion:{maxSuggestions:10,historyWeight:.3,contextWeight:.7,fuzzyMatch:!0},streaming:{enabled:!0,bufferSize:100,updateIntervalMs:50}};function x(){return p(C(),".aqe")}function E(){return p(x(),"cli-config.json")}var g=null,d=0,T=5e3;function S(){return g?Date.now()-d<T:!1}function A(s){let e=[],t=s;if(typeof t.enabled!="boolean"&&t.enabled!==void 0&&e.push({path:"wizards.enabled",message:"must be a boolean"}),t.themes!==void 0)if(!Array.isArray(t.themes))e.push({path:"wizards.themes",message:"must be an array"});else{let r=["default","minimal","detailed"];for(let n of t.themes)r.includes(n)||e.push({path:"wizards.themes",message:`invalid theme: ${n}`})}return t.defaultTheme!==void 0&&(["default","minimal","detailed"].includes(t.defaultTheme)||e.push({path:"wizards.defaultTheme",message:`invalid theme: ${t.defaultTheme}`})),e}function P(s){let e=[],t=s;return t.style!==void 0&&(["multi-bar","single-bar","spinner"].includes(t.style)||e.push({path:"progress.style",message:`invalid style: ${t.style}`})),t.updateIntervalMs!==void 0&&(typeof t.updateIntervalMs!="number"||t.updateIntervalMs<10)&&e.push({path:"progress.updateIntervalMs",message:"must be a number >= 10"}),typeof t.showETA!="boolean"&&t.showETA!==void 0&&e.push({path:"progress.showETA",message:"must be a boolean"}),typeof t.colors!="boolean"&&t.colors!==void 0&&e.push({path:"progress.colors",message:"must be a boolean"}),e}function $(s){let e=[],t=s;return t.maxSuggestions!==void 0&&(typeof t.maxSuggestions!="number"||t.maxSuggestions<1)&&e.push({path:"completion.maxSuggestions",message:"must be a number >= 1"}),t.historyWeight!==void 0&&(typeof t.historyWeight!="number"||t.historyWeight<0||t.historyWeight>1)&&e.push({path:"completion.historyWeight",message:"must be a number between 0 and 1"}),t.contextWeight!==void 0&&(typeof t.contextWeight!="number"||t.contextWeight<0||t.contextWeight>1)&&e.push({path:"completion.contextWeight",message:"must be a number between 0 and 1"}),typeof t.fuzzyMatch!="boolean"&&t.fuzzyMatch!==void 0&&e.push({path:"completion.fuzzyMatch",message:"must be a boolean"}),e}function I(s){let e=[],t=s;return typeof t.enabled!="boolean"&&t.enabled!==void 0&&e.push({path:"streaming.enabled",message:"must be a boolean"}),t.bufferSize!==void 0&&(typeof t.bufferSize!="number"||t.bufferSize<1)&&e.push({path:"streaming.bufferSize",message:"must be a number >= 1"}),t.updateIntervalMs!==void 0&&(typeof t.updateIntervalMs!="number"||t.updateIntervalMs<10)&&e.push({path:"streaming.updateIntervalMs",message:"must be a number >= 10"}),e}function M(s){let e=[];if(typeof s!="object"||s===null)return{valid:!1,errors:[{path:"",message:"config must be an object"}]};let t=s;return t.wizards!==void 0&&(typeof t.wizards!="object"||t.wizards===null?e.push({path:"wizards",message:"must be an object"}):e.push(...A(t.wizards))),t.progress!==void 0&&(typeof t.progress!="object"||t.progress===null?e.push({path:"progress",message:"must be an object"}):e.push(...P(t.progress))),t.completion!==void 0&&(typeof t.completion!="object"||t.completion===null?e.push({path:"completion",message:"must be an object"}):e.push(...$(t.completion))),t.streaming!==void 0&&(typeof t.streaming!="object"||t.streaming===null?e.push({path:"streaming",message:"must be an object"}):e.push(...I(t.streaming))),{valid:e.length===0,errors:e}}var z=["__proto__","constructor","prototype"];function m(s,e){let t={...s};for(let r of Object.keys(e)){if(z.includes(r)){console.warn(`Security: Skipping forbidden key '${String(r)}' in configuration merge`);continue}let n=e[r],i=s[r];n!==void 0&&typeof n=="object"&&!Array.isArray(n)&&typeof i=="object"&&!Array.isArray(i)?t[r]=m(i,n):n!==void 0&&(t[r]=n)}return t}function D(){let s=E();if(!w(s))return{...u};try{let e=y(s,"utf-8"),t=f(e),r=M(t);return r.valid?m(u,t):(console.warn(`CLI config validation errors: ${r.errors.map(n=>`${n.path}: ${n.message}`).join(", ")}`),console.warn("Using default configuration"),{...u})}catch(e){return console.warn(`Failed to load CLI config: ${e instanceof Error?e.message:"Unknown error"}`),{...u}}}function c(){return S()||(g=D(),d=Date.now()),g}function B(){return process.stdout.isTTY===!0}function h(){let s=c();return process.env.NO_COLOR!==void 0?!1:process.env.FORCE_COLOR!==void 0?!0:s.progress.colors&&B()}var b=class{multiBar;agentBars=new Map;agentStates=new Map;fleetBar=null;startTime=Date.now();options;isActive=!1;constructor(e={}){let t=c(),r=h();this.options={title:"Fleet Progress",showEta:t.progress.showETA,showPercentage:!0,...e};let n=r?o.cyan("{bar}"):"{bar}",i=this.options.format||`{name} ${n} {percentage}% | {status} {eta}`;this.multiBar=new F({clearOnComplete:!1,hideCursor:!0,format:i,barCompleteChar:"\u2588",barIncompleteChar:"\u2591",forceRedraw:!0,fps:Math.round(1e3/t.progress.updateIntervalMs)},k.shades_classic)}start(e){this.isActive=!0,this.startTime=Date.now(),console.log(o.blue(`
3
3
  ${this.options.title}
4
4
  `)),this.fleetBar=this.multiBar.create(100,0,{name:o.white("Fleet Progress".padEnd(30)),status:"",eta:""})}addAgent(e){if(!this.isActive)return;this.agentStates.set(e.id,e);let t=this.multiBar.create(100,e.progress,{name:o.gray(this.truncateName(e.name,30).padEnd(30)),status:this.getStatusIcon(e.status),eta:e.eta?this.formatEta(e.eta):""});this.agentBars.set(e.id,t),this.updateFleetProgress()}updateAgent(e,t,r){if(!this.isActive)return;let n=this.agentStates.get(e),i=this.agentBars.get(e);!n||!i||(n.progress=Math.min(100,Math.max(0,t)),r?.status&&(n.status=r.status),r?.message&&(n.message=r.message),r?.eta!==void 0&&(n.eta=r.eta),i.update(n.progress,{name:this.getAgentNameDisplay(n),status:this.getStatusIcon(n.status),eta:n.eta?this.formatEta(n.eta):""}),this.updateFleetProgress())}completeAgent(e,t=!0){if(!this.isActive)return;let r=this.agentStates.get(e),n=this.agentBars.get(e);!r||!n||(r.status=t?"completed":"failed",r.progress=t?100:r.progress,n.update(r.progress,{name:this.getAgentNameDisplay(r),status:this.getStatusIcon(r.status),eta:""}),this.updateFleetProgress())}stop(){if(!this.isActive)return;this.isActive=!1,this.multiBar.stop();let e=Array.from(this.agentStates.values()).filter(i=>i.status==="completed").length,t=Array.from(this.agentStates.values()).filter(i=>i.status==="failed").length,r=this.agentStates.size,n=Date.now()-this.startTime;console.log(""),console.log(t===0?o.green(`All ${e}/${r} agents completed successfully (${this.formatDuration(n)})`):o.yellow(`${e}/${r} agents completed, ${t} failed (${this.formatDuration(n)})`)),console.log("")}updateFleetProgress(){if(!this.fleetBar)return;let e=Array.from(this.agentStates.values()),t=e.reduce((a,l)=>a+l.progress,0),r=e.length>0?Math.round(t/e.length):0,n=e.filter(a=>a.status==="completed").length,i=e.filter(a=>a.status==="running").length;this.fleetBar.update(r,{status:o.gray(`${n}/${e.length} complete, ${i} running`),eta:this.options.showEta?this.estimateFleetEta(e):""})}getAgentNameDisplay(e){let t=this.truncateName(e.name,26);switch(e.status){case"completed":return o.green(t.padEnd(30));case"failed":return o.red(t.padEnd(30));case"running":return o.yellow(t.padEnd(30));default:return o.gray(t.padEnd(30))}}getStatusIcon(e){switch(e){case"completed":return o.green("\u2713");case"failed":return o.red("\u2717");case"running":return o.yellow("\u25B6");default:return o.gray("\u25CB")}}truncateName(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}formatEta(e){return e<=0?"":e<1e3?`${e}ms`:e<6e4?`${Math.round(e/1e3)}s`:e<36e5?`${Math.round(e/6e4)}m`:`${Math.round(e/36e5)}h`}formatDuration(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:e<36e5?`${(e/6e4).toFixed(1)}m`:`${(e/36e5).toFixed(1)}h`}estimateFleetEta(e){let t=e.filter(a=>a.status==="running"||a.status==="pending");if(t.length===0)return"";let r=t.map(a=>a.eta||0).filter(a=>a>0);if(r.length>0){let a=Math.max(...r);return o.gray(`ETA: ${this.formatEta(a)}`)}let n=Date.now()-this.startTime,i=t.reduce((a,l)=>a+l.progress,0)/t.length;if(i>0){let a=n/(i/100),l=Math.max(0,a-n);return o.gray(`ETA: ${this.formatEta(l)}`)}return""}};function X(s){let e=Date.now(),t=O({text:s,color:"cyan"}).start(),r=setInterval(()=>{let i=((Date.now()-e)/1e3).toFixed(1);t.text=`${s} (${i}s)`},100);r.unref?.();let n=()=>{clearInterval(r)};return{spinner:t,stop:()=>{n(),t.stop()},succeed:i=>{n();let a=((Date.now()-e)/1e3).toFixed(1);t.succeed(i||`${s} (${a}s)`)},fail:i=>{n();let a=((Date.now()-e)/1e3).toFixed(1);t.fail(i||`${s} failed (${a}s)`)}}}export{b as a,X as b};
@@ -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.13.11");process.exit(0)}
2
- import{a as h}from"./chunk-UX5SM2PW.js";import{a as C,f as x}from"./chunk-EWH7PFV6.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.14.0");process.exit(0)}
2
+ import{a as h}from"./chunk-IQ3JFHZN.js";import{a as C,f as x}from"./chunk-RGVD6ZUX.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};
@@ -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.13.11");process.exit(0)}
2
- import{b as f}from"./chunk-E54QUKAD.js";import{i as g,m as A}from"./chunk-2Y3PW5EJ.js";A();import{createHash as m}from"crypto";var y="0".repeat(64);function R(a){return m("sha256").update(a,"utf-8").digest("hex")}function b(a){try{return m("shake256",{outputLength:32}).update(a,"utf-8").digest("hex")}catch{return R(a)}}function l(a,t){return a==="shake256"?b(t):R(t)}function T(a){return JSON.stringify({id:a.id,prev_hash:a.prev_hash,action_hash:a.action_hash,action_type:a.action_type,action_data:a.action_data,timestamp:a.timestamp,actor:a.actor})}var _=class{constructor(t,i){this.externalDb=t;this.keyManager=i??null}externalDb;db=null;initialized=!1;keyManager=null;async initialize(){if(!this.initialized){if(this.externalDb)this.db=this.externalDb;else{let t=g();await t.initialize(),this.db=t.getDatabase()}this.ensureTable(),this.initialized=!0}}getDatabase(){return this.db}getKeyManager(){return this.keyManager}ensureTable(){if(!this.db)throw new Error("Database not initialized");this.db.exec(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.0");process.exit(0)}
2
+ import{b as f}from"./chunk-E722WNWC.js";import{k as g,o as A}from"./chunk-7RAB2BZY.js";A();import{createHash as m}from"crypto";var y="0".repeat(64);function R(a){return m("sha256").update(a,"utf-8").digest("hex")}function b(a){try{return m("shake256",{outputLength:32}).update(a,"utf-8").digest("hex")}catch{return R(a)}}function l(a,t){return a==="shake256"?b(t):R(t)}function T(a){return JSON.stringify({id:a.id,prev_hash:a.prev_hash,action_hash:a.action_hash,action_type:a.action_type,action_data:a.action_data,timestamp:a.timestamp,actor:a.actor})}var _=class{constructor(t,i){this.externalDb=t;this.keyManager=i??null}externalDb;db=null;initialized=!1;keyManager=null;async initialize(){if(!this.initialized){if(this.externalDb)this.db=this.externalDb;else{let t=g();await t.initialize(),this.db=t.getDatabase()}this.ensureTable(),this.initialized=!0}}getDatabase(){return this.db}getKeyManager(){return this.keyManager}ensureTable(){if(!this.db)throw new Error("Database not initialized");this.db.exec(`
3
3
  CREATE TABLE IF NOT EXISTS witness_chain (
4
4
  id INTEGER PRIMARY KEY AUTOINCREMENT,
5
5
  prev_hash TEXT NOT NULL, action_hash TEXT NOT NULL, action_type TEXT NOT NULL,
@@ -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.13.11");process.exit(0)}
2
- import{a as v}from"./chunk-76NSSNB3.js";import{h as U}from"./chunk-OLPJGYO5.js";import{c as D,d as R,e as h,g as x}from"./chunk-EWH7PFV6.js";var f=class{config;trackers;globalCostTodayUsd=0;lastGlobalReset=new Date;constructor(e){this.config=e,this.trackers=new Map;for(let t of[0,1,2,3,4])this.trackers.set(t,{tier:t,costSpentTodayUsd:0,requestsThisHour:0,requestsToday:0,lastHourlyReset:new Date,lastDailyReset:new Date,requestHistory:[]})}async checkBudget(e,t){if(!this.config.enabled)return this.createAllowedDecision(e,e,t,!1,[]);this.autoReset();let r=this.config.tierBudgets[e];if(!r||!r.enabled)return this.createAllowedDecision(e,e,t,!1,["Tier budget not configured or disabled"]);let s=this.getUsage(e),i=[],c=this.config.maxDailyCostUsd-this.globalCostTodayUsd;if(this.globalCostTodayUsd+t>this.config.maxDailyCostUsd)return this.handleBudgetExceeded(e,t,s,"Global daily budget would be exceeded");if(this.globalCostTodayUsd+t>=this.config.maxDailyCostUsd*this.config.warningThreshold&&(i.push(`Approaching global daily budget limit: $${this.globalCostTodayUsd.toFixed(2)}/$${this.config.maxDailyCostUsd.toFixed(2)}`),this.config.onBudgetWarning==="downgrade"))return this.downgradeTier(e,t,s,i);let a=[{exceeded:s.costSpentTodayUsd+t>r.maxDailyCostUsd,message:`Tier ${e} daily cost limit would be exceeded: $${s.costSpentTodayUsd.toFixed(2)}/$${r.maxDailyCostUsd.toFixed(2)}`},{exceeded:s.requestsThisHour>=r.maxRequestsPerHour,message:`Tier ${e} hourly request limit reached: ${s.requestsThisHour}/${r.maxRequestsPerHour}`},{exceeded:s.requestsToday>=r.maxRequestsPerDay,message:`Tier ${e} daily request limit reached: ${s.requestsToday}/${r.maxRequestsPerDay}`},{exceeded:t>r.maxCostPerRequest,message:`Tier ${e} per-request cost limit would be exceeded: $${t.toFixed(4)}/$${r.maxCostPerRequest.toFixed(4)}`}];for(let n of a)if(n.exceeded)return this.handleBudgetExceeded(e,t,s,n.message);return s.budgetUtilization>=this.config.warningThreshold&&(i.push(`Tier ${e} at ${(s.budgetUtilization*100).toFixed(1)}% of daily budget`),this.config.onBudgetWarning==="downgrade")?this.downgradeTier(e,t,s,i):this.createAllowedDecision(e,e,t,!1,i)}async recordCost(e,t){if(!this.config.enabled)return;let r=this.trackers.get(e);r&&(this.autoReset(),r.costSpentTodayUsd+=t,r.requestsThisHour++,r.requestsToday++,this.globalCostTodayUsd+=t,r.requestHistory.push({timestamp:new Date,costUsd:t}),r.requestHistory.length>1e3&&(r.requestHistory=r.requestHistory.slice(-1e3)))}getUsage(e){this.autoReset();let t=this.trackers.get(e);if(!t)return this.createEmptyUsage(e);let r=this.config.tierBudgets[e];if(!r)return this.createEmptyUsage(e);let s=r.maxDailyCostUsd>0?t.costSpentTodayUsd/r.maxDailyCostUsd:0,i=t.costSpentTodayUsd>=r.maxDailyCostUsd||t.requestsThisHour>=r.maxRequestsPerHour||t.requestsToday>=r.maxRequestsPerDay,c=s>=this.config.warningThreshold,a=new Date,n=new Date(a);return n.setUTCHours(24,0,0,0),{tier:e,costSpentTodayUsd:t.costSpentTodayUsd,requestsThisHour:t.requestsThisHour,requestsToday:t.requestsToday,budgetUtilization:s,isExceeded:i,isNearLimit:c,resetTime:n,remainingBudgetUsd:Math.max(0,r.maxDailyCostUsd-t.costSpentTodayUsd),remainingRequestsThisHour:Math.max(0,r.maxRequestsPerHour-t.requestsThisHour),remainingRequestsToday:Math.max(0,r.maxRequestsPerDay-t.requestsToday)}}getAllUsage(){let e={};for(let t of[0,1,2,3,4])e[t]=this.getUsage(t);return e}reset(){let e=new Date;for(let t of this.trackers.values())t.costSpentTodayUsd=0,t.requestsThisHour=0,t.requestsToday=0,t.lastHourlyReset=e,t.lastDailyReset=e,t.requestHistory=[];this.globalCostTodayUsd=0,this.lastGlobalReset=e}handleBudgetExceeded(e,t,r,s){switch(this.config.onBudgetExceeded){case"error":throw new h(`Budget exceeded: ${s}`,e,r);case"downgrade":return this.downgradeTier(e,t,r,[s]);case"queue":throw new h(`Budget exceeded (queueing not yet implemented): ${s}`,e,r);default:throw new h(`Budget exceeded: ${s}`,e,r)}}downgradeTier(e,t,r,s){for(let i=e-1;i>=0;i--){let c=this.config.tierBudgets[i];if(!c||!c.enabled)continue;let a=this.getUsage(i);if(!a.isExceeded){let n=t*.5;if(a.costSpentTodayUsd+n<=c.maxDailyCostUsd)return this.createAllowedDecision(e,i,n,!0,[...s,`Downgraded from Tier ${e} to Tier ${i} due to budget constraints`])}}throw new h(`Budget exceeded and no lower tier available: ${s.join("; ")}`,e,r)}createAllowedDecision(e,t,r,s,i){let c=this.getUsage(t);return{allowed:!0,reason:s?`Budget enforced: downgraded to Tier ${t}`:"Budget check passed",requestedTier:e,approvedTier:t,wasDowngraded:s,estimatedCostUsd:r,currentUsage:c,warnings:i}}createEmptyUsage(e){let t=new Date,r=new Date(t);return r.setUTCHours(24,0,0,0),{tier:e,costSpentTodayUsd:0,requestsThisHour:0,requestsToday:0,budgetUtilization:0,isExceeded:!1,isNearLimit:!1,resetTime:r,remainingBudgetUsd:0,remainingRequestsThisHour:0,remainingRequestsToday:0}}autoReset(){let e=new Date;this.shouldResetDaily(this.lastGlobalReset,e)&&(this.globalCostTodayUsd=0,this.lastGlobalReset=e);for(let t of this.trackers.values())this.shouldResetHourly(t.lastHourlyReset,e)&&(t.requestsThisHour=0,t.lastHourlyReset=e),this.shouldResetDaily(t.lastDailyReset,e)&&(t.costSpentTodayUsd=0,t.requestsToday=0,t.requestHistory=[],t.lastDailyReset=e)}shouldResetHourly(e,t){return(t.getTime()-e.getTime())/36e5>=1}shouldResetDaily(e,t){return t.getUTCDate()!==e.getUTCDate()||t.getUTCMonth()!==e.getUTCMonth()||t.getUTCFullYear()!==e.getUTCFullYear()}getSessionCostSummary(){this.autoReset();let e=this.config.maxDailyCostUsd,t=0,r={},s={0:"AgentBooster",1:"Haiku",2:"Sonnet",3:"SonnetExtended",4:"Opus"};for(let[c,a]of this.trackers.entries()){let n=this.config.tierBudgets[c],o=s[c]??`Tier${c}`;t+=a.costSpentTodayUsd,r[o]={spent:a.costSpentTodayUsd,limit:n?.maxDailyCostUsd??0,requests:a.requestsToday}}let i=e>0?Math.round(t/e*100):0;return{totalSpentUsd:t,dailyLimitUsd:e,utilizationPercent:i,byTier:r}}};var w=class{cache=new Map;maxSize;ttlMs;enabled;constructor(e,t,r){this.enabled=e,this.maxSize=t,this.ttlMs=r}generateKey(e){return`${e.agentType||"unknown"}:${e.domain||"unknown"}:${e.task.slice(0,100)}`}get(e){if(!this.enabled)return null;let t=this.generateKey(e),r=this.cache.get(t);return r?Date.now()>r.expiresAt?(this.cache.delete(t),null):{...r.decision,metadata:{...r.decision.metadata,fromCache:!0,decisionTimeMs:0}}:null}set(e,t){if(!this.enabled)return;let r=this.generateKey(e);if(this.cache.size>=this.maxSize){let s=this.cache.keys().next().value;s&&this.cache.delete(s)}this.cache.set(r,{decision:t,expiresAt:Date.now()+this.ttlMs})}clear(){this.cache.clear()}getStats(){return{size:this.cache.size,hitRate:0}}},M=class{events=[];enabled;maxEvents=1e4;constructor(e){this.enabled=e}record(e){this.enabled&&(this.events.push(e),this.events.length>this.maxEvents&&(this.events=this.events.slice(-this.maxEvents)))}getMetrics(){if(this.events.length===0)return this.createEmptyMetrics();let e=new Date,t={};for(let o of[0,1,2,3,4]){let d=this.events.filter(l=>l.tier===o);if(d.length===0)continue;let T=d.filter(l=>l.success),m=d.filter(l=>!l.wasManualOverride),b=d.filter(l=>l.wasDowngraded),y=d.map(l=>l.latencyMs).sort((l,g)=>l-g),B=Math.floor(y.length*.95);t[o]={tier:o,selectionCount:d.length,autoRouteCount:m.length,manualOverrideCount:d.length-m.length,budgetDowngradeCount:b.length,successRate:T.length/d.length,avgComplexity:d.reduce((l,g)=>l+g.complexity,0)/d.length,totalCostUsd:d.reduce((l,g)=>l+g.costUsd,0),avgLatencyMs:d.reduce((l,g)=>l+g.latencyMs,0)/d.length,p95LatencyMs:y[B]||0,budgetUtilization:0}}let r=this.events.map(o=>o.latencyMs).sort((o,d)=>o-d),s=Math.floor(r.length*.95),i=Math.floor(r.length*.99),c=this.events.filter(o=>o.agentBoosterEligible).length,a=this.events.filter(o=>o.tier===0).length,n=this.events.filter(o=>o.tier===0&&o.success).length;return{byTier:t,totalDecisions:this.events.length,avgDecisionTimeMs:this.events.reduce((o,d)=>o+d.latencyMs,0)/this.events.length,p95DecisionTimeMs:r[s]||0,p99DecisionTimeMs:r[i]||0,fallbackRate:this.events.filter(o=>o.wasDowngraded).length/this.events.length,ruleMatchRate:this.events.filter(o=>!o.wasManualOverride).length/this.events.length,estimatedCostSavings:0,agentBoosterStats:{eligible:c,used:a,fallbackToLLM:Math.max(0,c-a),successRate:a>0?n/a:0},budgetStats:{totalSpentUsd:this.events.reduce((o,d)=>o+d.costUsd,0),budgetUtilization:0,downgradeCount:this.events.filter(o=>o.wasDowngraded).length,overrideCount:this.events.filter(o=>o.wasManualOverride).length},period:{start:this.events[0]?.timestamp||e,end:this.events[this.events.length-1]?.timestamp||e}}}reset(){this.events=[]}createEmptyMetrics(){let e=new Date;return{byTier:{},totalDecisions:0,avgDecisionTimeMs:0,p95DecisionTimeMs:0,p99DecisionTimeMs:0,fallbackRate:0,ruleMatchRate:0,estimatedCostSavings:0,agentBoosterStats:{eligible:0,used:0,fallbackToLLM:0,successRate:0},budgetStats:{totalSpentUsd:0,budgetUtilization:0,downgradeCount:0,overrideCount:0},period:{start:e,end:e}}}},p=class{config;complexityAnalyzer;budgetEnforcer;agentBoosterAdapter;cache;metrics;persistentMetricsTracker;patternsLoaded=!1;tierHierarchyFromPatterns=null;constructor(e={},t,r){this.config={...D,...e},this.agentBoosterAdapter=t,this.persistentMetricsTracker=r,this.complexityAnalyzer=U(this.config,t),this.budgetEnforcer=new f(this.config.budgetConfig),this.cache=new w(this.config.enableDecisionCache,1e3,this.config.decisionCacheTtlMs),this.metrics=new M(this.config.enableMetrics)}setPersistentMetricsTracker(e){this.persistentMetricsTracker=e}async loadPatternsFromLoader(){try{let t=await v().getTierHierarchy();if(t){this.tierHierarchyFromPatterns=t,this.patternsLoaded=!0,console.info("[ModelRouter] Loaded tier hierarchy from PatternLoader",{tiers:Object.keys(t)});return}console.debug("[ModelRouter] PatternLoader returned no tier hierarchy, using defaults")}catch(e){console.warn("[ModelRouter] Failed to load patterns from PatternLoader, using defaults",{error:e instanceof Error?e.message:"Unknown error"})}this.patternsLoaded=!1}getPatternsLoaded(){return this.patternsLoaded}getTierHierarchyFromPatterns(){return this.tierHierarchyFromPatterns}async route(e){let t=Date.now(),r=e.metadata?.correlationId;try{let s=this.cache.get(e);if(s)return s;let i=await Promise.race([this.routeInternal(e,t,r),new Promise((c,a)=>setTimeout(()=>a(new x("Routing decision timed out",this.config.maxDecisionTimeMs)),this.config.maxDecisionTimeMs))]);return this.cache.set(e,i),this.recordMetrics(i,!0),i}catch(s){let i=await this.createFallbackDecision(e,t,r,s instanceof Error?s:new Error("Unknown error"));return this.recordMetrics(i,!1),i}}getMetrics(){return this.metrics.getMetrics()}async getAgentBoosterHealth(){if(!this.agentBoosterAdapter)throw new R("Agent Booster adapter not available","AGENT_BOOSTER_UNAVAILABLE");return this.agentBoosterAdapter.getHealth()}resetMetrics(){this.metrics.reset()}async dispose(){this.cache.clear(),this.metrics.reset(),this.agentBoosterAdapter&&await this.agentBoosterAdapter.dispose()}async routeInternal(e,t,r){let s=[];if(e.manualTier!==void 0&&this.config.allowManualOverrides)return this.handleManualOverride(e,e.manualTier,t,r);let i=await this.complexityAnalyzer.analyze(e),c=i.recommendedTier,a=this.estimateCost(c,e.task.length),n=await this.budgetEnforcer.checkBudget(c,a),o=n.approvedTier;s.push(...n.warnings);let d=o===0&&i.signals.isMechanicalTransform,T=this.getModelIdForTier(o),m=this.buildRationale(i,n,o),b=this.buildAlternatives(i,o),y=Date.now()-t;return{tier:o,modelId:T,complexityAnalysis:i,budgetDecision:n,confidence:i.confidence,rationale:m,agentBoosterEligible:d,agentBoosterTransform:d?i.signals.detectedTransformType:void 0,alternativeTiers:b,metadata:{timestamp:new Date,decisionTimeMs:y,fromCache:!1,correlationId:r},warnings:s}}async handleManualOverride(e,t,r,s){let i=await this.complexityAnalyzer.analyze(e),c=this.estimateCost(t,e.task.length),a=await this.budgetEnforcer.checkBudget(t,c);!a.allowed&&e.isCritical&&this.config.budgetConfig.allowCriticalOverrides&&(a={...a,allowed:!0,reason:"Critical task override",warnings:[...a.warnings,"Budget exceeded but allowed due to critical task override"]});let n=a.approvedTier,o=this.getModelIdForTier(n),d=Date.now()-r;return{tier:n,modelId:o,complexityAnalysis:i,budgetDecision:a,confidence:1,rationale:`Manual override to Tier ${n}${a.wasDowngraded?" (downgraded due to budget)":""}`,agentBoosterEligible:n===0,alternativeTiers:[],metadata:{timestamp:new Date,decisionTimeMs:d,fromCache:!1,correlationId:s},warnings:a.warnings}}async createFallbackDecision(e,t,r,s){let i=this.config.fallbackTier,c=this.getModelIdForTier(i),a={overall:50,codeComplexity:50,reasoningComplexity:50,scopeComplexity:50,confidence:.3,signals:{hasArchitectureScope:!1,hasSecurityScope:!1,requiresMultiStepReasoning:!1,requiresCrossDomainCoordination:!1,isMechanicalTransform:!1,requiresCreativity:!1,keywordMatches:{simple:[],moderate:[],complex:[],critical:[]}},recommendedTier:i,alternateTiers:[],explanation:`Fallback to Tier ${i} due to routing error`},n={allowed:!0,reason:"Fallback routing",requestedTier:i,approvedTier:i,wasDowngraded:!1,estimatedCostUsd:0,currentUsage:this.budgetEnforcer.getUsage(i),warnings:[]},o=Date.now()-t;return{tier:i,modelId:c,complexityAnalysis:a,budgetDecision:n,confidence:.3,rationale:`Fallback to Tier ${i} due to error: ${s.message}`,agentBoosterEligible:!1,alternativeTiers:[],metadata:{timestamp:new Date,decisionTimeMs:o,fromCache:!1,correlationId:r},warnings:[`Routing error: ${s.message}`,"Using fallback tier"]}}estimateCost(e,t){let r=[0,.001,.01,.05,.2],s=Math.max(1,t/1e3);return r[e]*s}getModelIdForTier(e){return this.config.tierModels[e]||`tier-${e}-default`}buildRationale(e,t,r){let s=[];return s.push(`Complexity: ${e.overall}/100`),s.push(`Tier ${r} selected`),t.wasDowngraded&&s.push(`Downgraded due to budget: ${t.reason}`),s.push(e.explanation),s.join(". ")}buildAlternatives(e,t){return e.alternateTiers.filter(r=>r!==t).map(r=>({tier:r,modelId:this.getModelIdForTier(r),reason:`Alternative tier ${r}`}))}recordMetrics(e,t){this.metrics.record({timestamp:e.metadata.timestamp,tier:e.tier,complexity:e.complexityAnalysis.overall,costUsd:e.budgetDecision.estimatedCostUsd,latencyMs:e.metadata.decisionTimeMs,wasDowngraded:e.budgetDecision.wasDowngraded,wasManualOverride:!1,agentBoosterEligible:e.agentBoosterEligible,success:t}),this.recordPersistentMetrics(e,t).catch(console.error)}async recordPersistentMetrics(e,t){if(this.persistentMetricsTracker)try{let r=`router-tier${e.tier}-${Date.now()}`;await this.persistentMetricsTracker.recordOutcome("router",r,t,e.metadata.decisionTimeMs,{subType:`tier-${e.tier}`,confidence:e.confidence,usedFallback:e.budgetDecision.wasDowngraded})}catch(r){console.warn("[ModelRouter] Failed to record persistent metrics:",r)}}};function H(u={},e,t){return new p(u,e,t)}async function $(u={},e){let{createAgentBoosterAdapter:t}=await import("./adapter-YBSKQFQ4.js"),r=await t({enabled:!0}),s=new p(u,r,e);return await s.loadPatternsFromLoader(),s}export{p as a,H as b,$ as c};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.0");process.exit(0)}
2
+ import{a as v}from"./chunk-JTWJR2KY.js";import{h as U}from"./chunk-B3H4K7CY.js";import{c as D,d as R,e as h,g as x}from"./chunk-RGVD6ZUX.js";var f=class{config;trackers;globalCostTodayUsd=0;lastGlobalReset=new Date;constructor(e){this.config=e,this.trackers=new Map;for(let t of[0,1,2,3,4])this.trackers.set(t,{tier:t,costSpentTodayUsd:0,requestsThisHour:0,requestsToday:0,lastHourlyReset:new Date,lastDailyReset:new Date,requestHistory:[]})}async checkBudget(e,t){if(!this.config.enabled)return this.createAllowedDecision(e,e,t,!1,[]);this.autoReset();let r=this.config.tierBudgets[e];if(!r||!r.enabled)return this.createAllowedDecision(e,e,t,!1,["Tier budget not configured or disabled"]);let s=this.getUsage(e),i=[],c=this.config.maxDailyCostUsd-this.globalCostTodayUsd;if(this.globalCostTodayUsd+t>this.config.maxDailyCostUsd)return this.handleBudgetExceeded(e,t,s,"Global daily budget would be exceeded");if(this.globalCostTodayUsd+t>=this.config.maxDailyCostUsd*this.config.warningThreshold&&(i.push(`Approaching global daily budget limit: $${this.globalCostTodayUsd.toFixed(2)}/$${this.config.maxDailyCostUsd.toFixed(2)}`),this.config.onBudgetWarning==="downgrade"))return this.downgradeTier(e,t,s,i);let a=[{exceeded:s.costSpentTodayUsd+t>r.maxDailyCostUsd,message:`Tier ${e} daily cost limit would be exceeded: $${s.costSpentTodayUsd.toFixed(2)}/$${r.maxDailyCostUsd.toFixed(2)}`},{exceeded:s.requestsThisHour>=r.maxRequestsPerHour,message:`Tier ${e} hourly request limit reached: ${s.requestsThisHour}/${r.maxRequestsPerHour}`},{exceeded:s.requestsToday>=r.maxRequestsPerDay,message:`Tier ${e} daily request limit reached: ${s.requestsToday}/${r.maxRequestsPerDay}`},{exceeded:t>r.maxCostPerRequest,message:`Tier ${e} per-request cost limit would be exceeded: $${t.toFixed(4)}/$${r.maxCostPerRequest.toFixed(4)}`}];for(let n of a)if(n.exceeded)return this.handleBudgetExceeded(e,t,s,n.message);return s.budgetUtilization>=this.config.warningThreshold&&(i.push(`Tier ${e} at ${(s.budgetUtilization*100).toFixed(1)}% of daily budget`),this.config.onBudgetWarning==="downgrade")?this.downgradeTier(e,t,s,i):this.createAllowedDecision(e,e,t,!1,i)}async recordCost(e,t){if(!this.config.enabled)return;let r=this.trackers.get(e);r&&(this.autoReset(),r.costSpentTodayUsd+=t,r.requestsThisHour++,r.requestsToday++,this.globalCostTodayUsd+=t,r.requestHistory.push({timestamp:new Date,costUsd:t}),r.requestHistory.length>1e3&&(r.requestHistory=r.requestHistory.slice(-1e3)))}getUsage(e){this.autoReset();let t=this.trackers.get(e);if(!t)return this.createEmptyUsage(e);let r=this.config.tierBudgets[e];if(!r)return this.createEmptyUsage(e);let s=r.maxDailyCostUsd>0?t.costSpentTodayUsd/r.maxDailyCostUsd:0,i=t.costSpentTodayUsd>=r.maxDailyCostUsd||t.requestsThisHour>=r.maxRequestsPerHour||t.requestsToday>=r.maxRequestsPerDay,c=s>=this.config.warningThreshold,a=new Date,n=new Date(a);return n.setUTCHours(24,0,0,0),{tier:e,costSpentTodayUsd:t.costSpentTodayUsd,requestsThisHour:t.requestsThisHour,requestsToday:t.requestsToday,budgetUtilization:s,isExceeded:i,isNearLimit:c,resetTime:n,remainingBudgetUsd:Math.max(0,r.maxDailyCostUsd-t.costSpentTodayUsd),remainingRequestsThisHour:Math.max(0,r.maxRequestsPerHour-t.requestsThisHour),remainingRequestsToday:Math.max(0,r.maxRequestsPerDay-t.requestsToday)}}getAllUsage(){let e={};for(let t of[0,1,2,3,4])e[t]=this.getUsage(t);return e}reset(){let e=new Date;for(let t of this.trackers.values())t.costSpentTodayUsd=0,t.requestsThisHour=0,t.requestsToday=0,t.lastHourlyReset=e,t.lastDailyReset=e,t.requestHistory=[];this.globalCostTodayUsd=0,this.lastGlobalReset=e}handleBudgetExceeded(e,t,r,s){switch(this.config.onBudgetExceeded){case"error":throw new h(`Budget exceeded: ${s}`,e,r);case"downgrade":return this.downgradeTier(e,t,r,[s]);case"queue":throw new h(`Budget exceeded (queueing not yet implemented): ${s}`,e,r);default:throw new h(`Budget exceeded: ${s}`,e,r)}}downgradeTier(e,t,r,s){for(let i=e-1;i>=0;i--){let c=this.config.tierBudgets[i];if(!c||!c.enabled)continue;let a=this.getUsage(i);if(!a.isExceeded){let n=t*.5;if(a.costSpentTodayUsd+n<=c.maxDailyCostUsd)return this.createAllowedDecision(e,i,n,!0,[...s,`Downgraded from Tier ${e} to Tier ${i} due to budget constraints`])}}throw new h(`Budget exceeded and no lower tier available: ${s.join("; ")}`,e,r)}createAllowedDecision(e,t,r,s,i){let c=this.getUsage(t);return{allowed:!0,reason:s?`Budget enforced: downgraded to Tier ${t}`:"Budget check passed",requestedTier:e,approvedTier:t,wasDowngraded:s,estimatedCostUsd:r,currentUsage:c,warnings:i}}createEmptyUsage(e){let t=new Date,r=new Date(t);return r.setUTCHours(24,0,0,0),{tier:e,costSpentTodayUsd:0,requestsThisHour:0,requestsToday:0,budgetUtilization:0,isExceeded:!1,isNearLimit:!1,resetTime:r,remainingBudgetUsd:0,remainingRequestsThisHour:0,remainingRequestsToday:0}}autoReset(){let e=new Date;this.shouldResetDaily(this.lastGlobalReset,e)&&(this.globalCostTodayUsd=0,this.lastGlobalReset=e);for(let t of this.trackers.values())this.shouldResetHourly(t.lastHourlyReset,e)&&(t.requestsThisHour=0,t.lastHourlyReset=e),this.shouldResetDaily(t.lastDailyReset,e)&&(t.costSpentTodayUsd=0,t.requestsToday=0,t.requestHistory=[],t.lastDailyReset=e)}shouldResetHourly(e,t){return(t.getTime()-e.getTime())/36e5>=1}shouldResetDaily(e,t){return t.getUTCDate()!==e.getUTCDate()||t.getUTCMonth()!==e.getUTCMonth()||t.getUTCFullYear()!==e.getUTCFullYear()}getSessionCostSummary(){this.autoReset();let e=this.config.maxDailyCostUsd,t=0,r={},s={0:"AgentBooster",1:"Haiku",2:"Sonnet",3:"SonnetExtended",4:"Opus"};for(let[c,a]of this.trackers.entries()){let n=this.config.tierBudgets[c],o=s[c]??`Tier${c}`;t+=a.costSpentTodayUsd,r[o]={spent:a.costSpentTodayUsd,limit:n?.maxDailyCostUsd??0,requests:a.requestsToday}}let i=e>0?Math.round(t/e*100):0;return{totalSpentUsd:t,dailyLimitUsd:e,utilizationPercent:i,byTier:r}}};var w=class{cache=new Map;maxSize;ttlMs;enabled;constructor(e,t,r){this.enabled=e,this.maxSize=t,this.ttlMs=r}generateKey(e){return`${e.agentType||"unknown"}:${e.domain||"unknown"}:${e.task.slice(0,100)}`}get(e){if(!this.enabled)return null;let t=this.generateKey(e),r=this.cache.get(t);return r?Date.now()>r.expiresAt?(this.cache.delete(t),null):{...r.decision,metadata:{...r.decision.metadata,fromCache:!0,decisionTimeMs:0}}:null}set(e,t){if(!this.enabled)return;let r=this.generateKey(e);if(this.cache.size>=this.maxSize){let s=this.cache.keys().next().value;s&&this.cache.delete(s)}this.cache.set(r,{decision:t,expiresAt:Date.now()+this.ttlMs})}clear(){this.cache.clear()}getStats(){return{size:this.cache.size,hitRate:0}}},M=class{events=[];enabled;maxEvents=1e4;constructor(e){this.enabled=e}record(e){this.enabled&&(this.events.push(e),this.events.length>this.maxEvents&&(this.events=this.events.slice(-this.maxEvents)))}getMetrics(){if(this.events.length===0)return this.createEmptyMetrics();let e=new Date,t={};for(let o of[0,1,2,3,4]){let d=this.events.filter(l=>l.tier===o);if(d.length===0)continue;let T=d.filter(l=>l.success),m=d.filter(l=>!l.wasManualOverride),b=d.filter(l=>l.wasDowngraded),y=d.map(l=>l.latencyMs).sort((l,g)=>l-g),B=Math.floor(y.length*.95);t[o]={tier:o,selectionCount:d.length,autoRouteCount:m.length,manualOverrideCount:d.length-m.length,budgetDowngradeCount:b.length,successRate:T.length/d.length,avgComplexity:d.reduce((l,g)=>l+g.complexity,0)/d.length,totalCostUsd:d.reduce((l,g)=>l+g.costUsd,0),avgLatencyMs:d.reduce((l,g)=>l+g.latencyMs,0)/d.length,p95LatencyMs:y[B]||0,budgetUtilization:0}}let r=this.events.map(o=>o.latencyMs).sort((o,d)=>o-d),s=Math.floor(r.length*.95),i=Math.floor(r.length*.99),c=this.events.filter(o=>o.agentBoosterEligible).length,a=this.events.filter(o=>o.tier===0).length,n=this.events.filter(o=>o.tier===0&&o.success).length;return{byTier:t,totalDecisions:this.events.length,avgDecisionTimeMs:this.events.reduce((o,d)=>o+d.latencyMs,0)/this.events.length,p95DecisionTimeMs:r[s]||0,p99DecisionTimeMs:r[i]||0,fallbackRate:this.events.filter(o=>o.wasDowngraded).length/this.events.length,ruleMatchRate:this.events.filter(o=>!o.wasManualOverride).length/this.events.length,estimatedCostSavings:0,agentBoosterStats:{eligible:c,used:a,fallbackToLLM:Math.max(0,c-a),successRate:a>0?n/a:0},budgetStats:{totalSpentUsd:this.events.reduce((o,d)=>o+d.costUsd,0),budgetUtilization:0,downgradeCount:this.events.filter(o=>o.wasDowngraded).length,overrideCount:this.events.filter(o=>o.wasManualOverride).length},period:{start:this.events[0]?.timestamp||e,end:this.events[this.events.length-1]?.timestamp||e}}}reset(){this.events=[]}createEmptyMetrics(){let e=new Date;return{byTier:{},totalDecisions:0,avgDecisionTimeMs:0,p95DecisionTimeMs:0,p99DecisionTimeMs:0,fallbackRate:0,ruleMatchRate:0,estimatedCostSavings:0,agentBoosterStats:{eligible:0,used:0,fallbackToLLM:0,successRate:0},budgetStats:{totalSpentUsd:0,budgetUtilization:0,downgradeCount:0,overrideCount:0},period:{start:e,end:e}}}},p=class{config;complexityAnalyzer;budgetEnforcer;agentBoosterAdapter;cache;metrics;persistentMetricsTracker;patternsLoaded=!1;tierHierarchyFromPatterns=null;constructor(e={},t,r){this.config={...D,...e},this.agentBoosterAdapter=t,this.persistentMetricsTracker=r,this.complexityAnalyzer=U(this.config,t),this.budgetEnforcer=new f(this.config.budgetConfig),this.cache=new w(this.config.enableDecisionCache,1e3,this.config.decisionCacheTtlMs),this.metrics=new M(this.config.enableMetrics)}setPersistentMetricsTracker(e){this.persistentMetricsTracker=e}async loadPatternsFromLoader(){try{let t=await v().getTierHierarchy();if(t){this.tierHierarchyFromPatterns=t,this.patternsLoaded=!0,console.info("[ModelRouter] Loaded tier hierarchy from PatternLoader",{tiers:Object.keys(t)});return}console.debug("[ModelRouter] PatternLoader returned no tier hierarchy, using defaults")}catch(e){console.warn("[ModelRouter] Failed to load patterns from PatternLoader, using defaults",{error:e instanceof Error?e.message:"Unknown error"})}this.patternsLoaded=!1}getPatternsLoaded(){return this.patternsLoaded}getTierHierarchyFromPatterns(){return this.tierHierarchyFromPatterns}async route(e){let t=Date.now(),r=e.metadata?.correlationId;try{let s=this.cache.get(e);if(s)return s;let i=await Promise.race([this.routeInternal(e,t,r),new Promise((c,a)=>setTimeout(()=>a(new x("Routing decision timed out",this.config.maxDecisionTimeMs)),this.config.maxDecisionTimeMs))]);return this.cache.set(e,i),this.recordMetrics(i,!0),i}catch(s){let i=await this.createFallbackDecision(e,t,r,s instanceof Error?s:new Error("Unknown error"));return this.recordMetrics(i,!1),i}}getMetrics(){return this.metrics.getMetrics()}async getAgentBoosterHealth(){if(!this.agentBoosterAdapter)throw new R("Agent Booster adapter not available","AGENT_BOOSTER_UNAVAILABLE");return this.agentBoosterAdapter.getHealth()}resetMetrics(){this.metrics.reset()}async dispose(){this.cache.clear(),this.metrics.reset(),this.agentBoosterAdapter&&await this.agentBoosterAdapter.dispose()}async routeInternal(e,t,r){let s=[];if(e.manualTier!==void 0&&this.config.allowManualOverrides)return this.handleManualOverride(e,e.manualTier,t,r);let i=await this.complexityAnalyzer.analyze(e),c=i.recommendedTier,a=this.estimateCost(c,e.task.length),n=await this.budgetEnforcer.checkBudget(c,a),o=n.approvedTier;s.push(...n.warnings);let d=o===0&&i.signals.isMechanicalTransform,T=this.getModelIdForTier(o),m=this.buildRationale(i,n,o),b=this.buildAlternatives(i,o),y=Date.now()-t;return{tier:o,modelId:T,complexityAnalysis:i,budgetDecision:n,confidence:i.confidence,rationale:m,agentBoosterEligible:d,agentBoosterTransform:d?i.signals.detectedTransformType:void 0,alternativeTiers:b,metadata:{timestamp:new Date,decisionTimeMs:y,fromCache:!1,correlationId:r},warnings:s}}async handleManualOverride(e,t,r,s){let i=await this.complexityAnalyzer.analyze(e),c=this.estimateCost(t,e.task.length),a=await this.budgetEnforcer.checkBudget(t,c);!a.allowed&&e.isCritical&&this.config.budgetConfig.allowCriticalOverrides&&(a={...a,allowed:!0,reason:"Critical task override",warnings:[...a.warnings,"Budget exceeded but allowed due to critical task override"]});let n=a.approvedTier,o=this.getModelIdForTier(n),d=Date.now()-r;return{tier:n,modelId:o,complexityAnalysis:i,budgetDecision:a,confidence:1,rationale:`Manual override to Tier ${n}${a.wasDowngraded?" (downgraded due to budget)":""}`,agentBoosterEligible:n===0,alternativeTiers:[],metadata:{timestamp:new Date,decisionTimeMs:d,fromCache:!1,correlationId:s},warnings:a.warnings}}async createFallbackDecision(e,t,r,s){let i=this.config.fallbackTier,c=this.getModelIdForTier(i),a={overall:50,codeComplexity:50,reasoningComplexity:50,scopeComplexity:50,confidence:.3,signals:{hasArchitectureScope:!1,hasSecurityScope:!1,requiresMultiStepReasoning:!1,requiresCrossDomainCoordination:!1,isMechanicalTransform:!1,requiresCreativity:!1,keywordMatches:{simple:[],moderate:[],complex:[],critical:[]}},recommendedTier:i,alternateTiers:[],explanation:`Fallback to Tier ${i} due to routing error`},n={allowed:!0,reason:"Fallback routing",requestedTier:i,approvedTier:i,wasDowngraded:!1,estimatedCostUsd:0,currentUsage:this.budgetEnforcer.getUsage(i),warnings:[]},o=Date.now()-t;return{tier:i,modelId:c,complexityAnalysis:a,budgetDecision:n,confidence:.3,rationale:`Fallback to Tier ${i} due to error: ${s.message}`,agentBoosterEligible:!1,alternativeTiers:[],metadata:{timestamp:new Date,decisionTimeMs:o,fromCache:!1,correlationId:r},warnings:[`Routing error: ${s.message}`,"Using fallback tier"]}}estimateCost(e,t){let r=[0,.001,.01,.05,.2],s=Math.max(1,t/1e3);return r[e]*s}getModelIdForTier(e){return this.config.tierModels[e]||`tier-${e}-default`}buildRationale(e,t,r){let s=[];return s.push(`Complexity: ${e.overall}/100`),s.push(`Tier ${r} selected`),t.wasDowngraded&&s.push(`Downgraded due to budget: ${t.reason}`),s.push(e.explanation),s.join(". ")}buildAlternatives(e,t){return e.alternateTiers.filter(r=>r!==t).map(r=>({tier:r,modelId:this.getModelIdForTier(r),reason:`Alternative tier ${r}`}))}recordMetrics(e,t){this.metrics.record({timestamp:e.metadata.timestamp,tier:e.tier,complexity:e.complexityAnalysis.overall,costUsd:e.budgetDecision.estimatedCostUsd,latencyMs:e.metadata.decisionTimeMs,wasDowngraded:e.budgetDecision.wasDowngraded,wasManualOverride:!1,agentBoosterEligible:e.agentBoosterEligible,success:t}),this.recordPersistentMetrics(e,t).catch(console.error)}async recordPersistentMetrics(e,t){if(this.persistentMetricsTracker)try{let r=`router-tier${e.tier}-${Date.now()}`;await this.persistentMetricsTracker.recordOutcome("router",r,t,e.metadata.decisionTimeMs,{subType:`tier-${e.tier}`,confidence:e.confidence,usedFallback:e.budgetDecision.wasDowngraded})}catch(r){console.warn("[ModelRouter] Failed to record persistent metrics:",r)}}};function H(u={},e,t){return new p(u,e,t)}async function $(u={},e){let{createAgentBoosterAdapter:t}=await import("./adapter-3VBXL7DO.js"),r=await t({enabled:!0}),s=new p(u,r,e);return await s.loadPatternsFromLoader(),s}export{p as a,H 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.13.11");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.0");process.exit(0)}
2
2
  var n=class{constructor(t){this.capacity=t;this.buffer=new Array(t)}capacity;buffer;head=0;tail=0;count=0;push(t){this.buffer[this.tail]=t,this.tail=(this.tail+1)%this.capacity,this.count<this.capacity?this.count++:this.head=(this.head+1)%this.capacity}toArray(){let t=[];for(let e=0;e<this.count;e++){let i=(this.head+e)%this.capacity;t.push(this.buffer[i])}return t}get length(){return this.count}get size(){return this.count}clear(){this.buffer=new Array(this.capacity),this.head=0,this.tail=0,this.count=0}last(t){let e=[],i=Math.max(0,this.count-t);for(let s=i;s<this.count;s++){let r=(this.head+s)%this.capacity;e.push(this.buffer[r])}return e}percentile(t){if(this.count===0)return;let e=this.toArray().sort((s,r)=>Number(s)-Number(r)),i=Math.floor(t/100*(e.length-1));return e[i]}reduce(t,e){let i=e;for(let s=0;s<this.count;s++){let r=(this.head+s)%this.capacity;i=t(i,this.buffer[r])}return i}average(){return this.count===0?0:this.reduce((e,i)=>e+i,0)/this.count}};export{n 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.13.11");process.exit(0)}
2
- import{c as t}from"./chunk-LUAXQB57.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.14.0");process.exit(0)}
2
+ import{c as t}from"./chunk-PEW6FZ47.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.13.11");process.exit(0)}
2
- import{c as h,e as v,g as T}from"./chunk-LUAXQB57.js";var y={};v(y,{DotProductAttention:()=>z,FlashAttention:()=>k,HyperbolicAttention:()=>C,LinearAttention:()=>j,MoEAttention:()=>W,MultiHeadAttention:()=>F,RuvectorLayer:()=>O,SonaEngine:()=>K,TensorCompress:()=>E,default:()=>I,differentiableSearch:()=>L,getCompressionLevel:()=>B,hierarchicalForward:()=>V,init:()=>D,pipeline:()=>q});import{createRequire as A}from"module";var _,g,I,O,E,L,V,B,D,k,z,F,C,j,W,K,q,R=h(()=>{_=A(import.meta.url),g=_("@ruvector/rvf-node"),I=g,{RuvectorLayer:O,TensorCompress:E,differentiableSearch:L,hierarchicalForward:V,getCompressionLevel:B,init:D,FlashAttention:k,DotProductAttention:z,MultiHeadAttention:F,HyperbolicAttention:C,LinearAttention:j,MoEAttention:W,SonaEngine:K,pipeline:q}=g||{}});var Z={};v(Z,{createRvfStore:()=>$,isRvfNativeAvailable:()=>X,openRvfStore:()=>G,openRvfStoreReadonly:()=>U});import{readFileSync as J,writeFileSync as H,copyFileSync as Q,existsSync as Y}from"fs";function c(){if(S)return m;S=!0;try{let s=(R(),T(y));!s.RvfDatabase&&s.default&&s.default.RvfDatabase&&(s=s.default),m=s}catch{m=null}return m}function w(s){return`${s}.idmap.json`}function N(s){let e=w(s),t=new Map,n=new Map,i=1;if(Y(e))try{let r=JSON.parse(J(e,"utf-8"));i=r.nextLabel;for(let[a,p]of r.entries)t.set(a,p),n.set(p,a)}catch{}return{strToNum:t,numToStr:n,nextLabel:i}}function b(s,e,t){let n={nextLabel:t,entries:Array.from(e.entries())};H(w(s),JSON.stringify(n),"utf-8")}function $(s,e){let t=c();if(!t)throw new Error("@ruvector/rvf-node is not available \u2014 install the package or check platform compatibility");let n=t.RvfDatabase.create(s,{dimension:e}),i=n.dimension();return new d(n,s,i,new Map,new Map,1)}function G(s){let e=c();if(!e)throw new Error("@ruvector/rvf-node is not available \u2014 install the package or check platform compatibility");let t=e.RvfDatabase.open(s),n=t.dimension(),{strToNum:i,numToStr:r,nextLabel:a}=N(s);return new d(t,s,n,i,r,a)}function U(s){let e=c();if(!e)throw new Error("@ruvector/rvf-node is not available \u2014 install the package or check platform compatibility");let t=e.RvfDatabase.openReadonly(s),n=t.dimension(),{strToNum:i,numToStr:r,nextLabel:a}=N(s);return new d(t,s,n,i,r,a)}function X(){return process.env.AQE_MEMORY_BACKEND==="memory"?!1:c()!==null}var m,S,d,P=h(()=>{m=null,S=!1;d=class s{db;_path;_dimension;strToNum;numToStr;nextLabel;_open;constructor(e,t,n,i,r,a){this.db=e,this._path=t,this._dimension=n,this.strToNum=i,this.numToStr=r,this.nextLabel=a,this._open=!0}ingest(e){if(this.ensureOpen(),e.length===0)return{accepted:0,rejected:0};let t=this._dimension,n=new Float32Array(e.length*t),i=[],r=[];for(let o=0;o<e.length;o++){let{id:u,vector:f,metadata:x}=e[o],l=this.strToNum.get(u);l===void 0&&(l=this.nextLabel++,this.strToNum.set(u,l),this.numToStr.set(l,u)),i.push(l),r.push(x);let M=f instanceof Float32Array?f:new Float32Array(f);n.set(M.subarray(0,t),o*t)}let a;if(r.some(o=>o!==void 0)&&typeof this.db.ingestBatchWithMetadata=="function"){let o=r.map(u=>u?JSON.stringify(u):"");a=this.db.ingestBatchWithMetadata(n,i,o)}else a=this.db.ingestBatch(n,i);return this.persistIdMap(),{accepted:a.accepted,rejected:a.rejected}}search(e,t){this.ensureOpen();let n=e instanceof Float32Array?e:new Float32Array(e);return this.db.query(n,t).map(r=>{let a=this.numToStr.get(r.id);return a===void 0?null:{id:a,distance:r.distance,score:1/(1+r.distance)}}).filter(r=>r!==null)}delete(e){this.ensureOpen();let t=[];for(let i of e){let r=this.strToNum.get(i);r!==void 0&&t.push(r)}if(t.length===0)return 0;let n=this.db.delete(t);for(let i of e){let r=this.strToNum.get(i);r!==void 0&&(this.strToNum.delete(i),this.numToStr.delete(r))}return this.persistIdMap(),n.deleted}fork(e){this.ensureOpen(),Q(this._path,e);let t=new Map(this.strToNum),n=new Map(this.numToStr);b(e,t,this.nextLabel);let r=c().RvfDatabase.open(e);return new s(r,e,this._dimension,t,n,this.nextLabel)}status(){this.ensureOpen();let e=this.db.status(),n=this.db.segments().filter(i=>i.segType==="witness");return{totalVectors:e.totalVectors,totalSegments:e.totalSegments,fileSizeBytes:e.fileSize,epoch:e.currentEpoch,witnessValid:n.length>0,witnessEntries:n.length,deadSpaceRatio:typeof e.deadSpaceRatio=="number"?e.deadSpaceRatio:0}}dimension(){return this._dimension}size(){return this.ensureOpen(),this.db.status().totalVectors}compact(){this.ensureOpen();try{let e=this.db.compact();return e&&typeof e=="object"?{segmentsCompacted:typeof e.segmentsCompacted=="number"?e.segmentsCompacted:0,bytesReclaimed:typeof e.bytesReclaimed=="number"?e.bytesReclaimed:0,epoch:typeof e.epoch=="number"?e.epoch:0}:{segmentsCompacted:0,bytesReclaimed:0,epoch:0}}catch{return null}}close(){this._open&&(this.db.close(),this._open=!1)}isOpen(){return this._open}path(){return this._path}embedKernel(e){return this.ensureOpen(),this.db.embedKernel(0,99,0,e,0,"")}extractKernel(){return this.ensureOpen(),this.db.extractKernel()}verifyWitness(){this.ensureOpen();let e=this.tryNative("verifyWitness");return e?{valid:e.valid??!0,totalEntries:e.totalEntries??0,errors:Array.isArray(e.errors)?e.errors:[]}:{valid:!0,totalEntries:0,errors:[]}}sign(e){this.ensureOpen();let t=this.tryNative("sign",e);return typeof t=="string"?t:null}fileId(){this.ensureOpen();let e=this.tryNative("fileId");return typeof e=="string"?e:null}parentId(){this.ensureOpen();let e=this.tryNative("parentId");return typeof e=="string"?e:null}lineageDepth(){this.ensureOpen();let e=this.tryNative("lineageDepth");return typeof e=="number"?e:0}indexStats(){let e=this.status();return{totalVectors:e.totalVectors,dimension:this._dimension,totalSegments:e.totalSegments,fileSizeBytes:e.fileSizeBytes,epoch:e.epoch,witnessValid:e.witnessValid,witnessEntries:e.witnessEntries,idMapSize:this.strToNum.size}}freeze(){this.ensureOpen();let e=this.tryNative("freeze");return typeof e=="number"?e:0}derive(e){this.ensureOpen();let t=c();if(typeof this.db.derive=="function")try{let n=this.db.derive(e),i=new Map(this.strToNum),r=new Map(this.numToStr);return b(e,i,this.nextLabel),new s(n,e,this._dimension,i,r,this.nextLabel)}catch{}return this.fork(e)}ensureOpen(){if(!this._open)throw new Error("RVF database is closed")}tryNative(e,...t){if(typeof this.db[e]!="function")return null;try{return this.db[e](...t)}catch{return null}}persistIdMap(){b(this._path,this.strToNum,this.nextLabel)}}});export{$ as a,G as b,U as c,X as d,Z as e,P 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.14.0");process.exit(0)}
2
+ import{c as h,e as v,g as T}from"./chunk-PEW6FZ47.js";var y={};v(y,{DotProductAttention:()=>z,FlashAttention:()=>k,HyperbolicAttention:()=>C,LinearAttention:()=>j,MoEAttention:()=>W,MultiHeadAttention:()=>F,RuvectorLayer:()=>O,SonaEngine:()=>K,TensorCompress:()=>E,default:()=>I,differentiableSearch:()=>L,getCompressionLevel:()=>B,hierarchicalForward:()=>V,init:()=>D,pipeline:()=>q});import{createRequire as A}from"module";var _,g,I,O,E,L,V,B,D,k,z,F,C,j,W,K,q,R=h(()=>{_=A(import.meta.url),g=_("@ruvector/rvf-node"),I=g,{RuvectorLayer:O,TensorCompress:E,differentiableSearch:L,hierarchicalForward:V,getCompressionLevel:B,init:D,FlashAttention:k,DotProductAttention:z,MultiHeadAttention:F,HyperbolicAttention:C,LinearAttention:j,MoEAttention:W,SonaEngine:K,pipeline:q}=g||{}});var Z={};v(Z,{createRvfStore:()=>$,isRvfNativeAvailable:()=>X,openRvfStore:()=>G,openRvfStoreReadonly:()=>U});import{readFileSync as J,writeFileSync as H,copyFileSync as Q,existsSync as Y}from"fs";function c(){if(S)return m;S=!0;try{let s=(R(),T(y));!s.RvfDatabase&&s.default&&s.default.RvfDatabase&&(s=s.default),m=s}catch{m=null}return m}function w(s){return`${s}.idmap.json`}function N(s){let e=w(s),t=new Map,n=new Map,i=1;if(Y(e))try{let r=JSON.parse(J(e,"utf-8"));i=r.nextLabel;for(let[a,p]of r.entries)t.set(a,p),n.set(p,a)}catch{}return{strToNum:t,numToStr:n,nextLabel:i}}function b(s,e,t){let n={nextLabel:t,entries:Array.from(e.entries())};H(w(s),JSON.stringify(n),"utf-8")}function $(s,e){let t=c();if(!t)throw new Error("@ruvector/rvf-node is not available \u2014 install the package or check platform compatibility");let n=t.RvfDatabase.create(s,{dimension:e}),i=n.dimension();return new d(n,s,i,new Map,new Map,1)}function G(s){let e=c();if(!e)throw new Error("@ruvector/rvf-node is not available \u2014 install the package or check platform compatibility");let t=e.RvfDatabase.open(s),n=t.dimension(),{strToNum:i,numToStr:r,nextLabel:a}=N(s);return new d(t,s,n,i,r,a)}function U(s){let e=c();if(!e)throw new Error("@ruvector/rvf-node is not available \u2014 install the package or check platform compatibility");let t=e.RvfDatabase.openReadonly(s),n=t.dimension(),{strToNum:i,numToStr:r,nextLabel:a}=N(s);return new d(t,s,n,i,r,a)}function X(){return process.env.AQE_MEMORY_BACKEND==="memory"?!1:c()!==null}var m,S,d,P=h(()=>{m=null,S=!1;d=class s{db;_path;_dimension;strToNum;numToStr;nextLabel;_open;constructor(e,t,n,i,r,a){this.db=e,this._path=t,this._dimension=n,this.strToNum=i,this.numToStr=r,this.nextLabel=a,this._open=!0}ingest(e){if(this.ensureOpen(),e.length===0)return{accepted:0,rejected:0};let t=this._dimension,n=new Float32Array(e.length*t),i=[],r=[];for(let o=0;o<e.length;o++){let{id:u,vector:f,metadata:x}=e[o],l=this.strToNum.get(u);l===void 0&&(l=this.nextLabel++,this.strToNum.set(u,l),this.numToStr.set(l,u)),i.push(l),r.push(x);let M=f instanceof Float32Array?f:new Float32Array(f);n.set(M.subarray(0,t),o*t)}let a;if(r.some(o=>o!==void 0)&&typeof this.db.ingestBatchWithMetadata=="function"){let o=r.map(u=>u?JSON.stringify(u):"");a=this.db.ingestBatchWithMetadata(n,i,o)}else a=this.db.ingestBatch(n,i);return this.persistIdMap(),{accepted:a.accepted,rejected:a.rejected}}search(e,t){this.ensureOpen();let n=e instanceof Float32Array?e:new Float32Array(e);return this.db.query(n,t).map(r=>{let a=this.numToStr.get(r.id);return a===void 0?null:{id:a,distance:r.distance,score:1/(1+r.distance)}}).filter(r=>r!==null)}delete(e){this.ensureOpen();let t=[];for(let i of e){let r=this.strToNum.get(i);r!==void 0&&t.push(r)}if(t.length===0)return 0;let n=this.db.delete(t);for(let i of e){let r=this.strToNum.get(i);r!==void 0&&(this.strToNum.delete(i),this.numToStr.delete(r))}return this.persistIdMap(),n.deleted}fork(e){this.ensureOpen(),Q(this._path,e);let t=new Map(this.strToNum),n=new Map(this.numToStr);b(e,t,this.nextLabel);let r=c().RvfDatabase.open(e);return new s(r,e,this._dimension,t,n,this.nextLabel)}status(){this.ensureOpen();let e=this.db.status(),n=this.db.segments().filter(i=>i.segType==="witness");return{totalVectors:e.totalVectors,totalSegments:e.totalSegments,fileSizeBytes:e.fileSize,epoch:e.currentEpoch,witnessValid:n.length>0,witnessEntries:n.length,deadSpaceRatio:typeof e.deadSpaceRatio=="number"?e.deadSpaceRatio:0}}dimension(){return this._dimension}size(){return this.ensureOpen(),this.db.status().totalVectors}compact(){this.ensureOpen();try{let e=this.db.compact();return e&&typeof e=="object"?{segmentsCompacted:typeof e.segmentsCompacted=="number"?e.segmentsCompacted:0,bytesReclaimed:typeof e.bytesReclaimed=="number"?e.bytesReclaimed:0,epoch:typeof e.epoch=="number"?e.epoch:0}:{segmentsCompacted:0,bytesReclaimed:0,epoch:0}}catch{return null}}close(){this._open&&(this.db.close(),this._open=!1)}isOpen(){return this._open}path(){return this._path}embedKernel(e){return this.ensureOpen(),this.db.embedKernel(0,99,0,e,0,"")}extractKernel(){return this.ensureOpen(),this.db.extractKernel()}verifyWitness(){this.ensureOpen();let e=this.tryNative("verifyWitness");return e?{valid:e.valid??!0,totalEntries:e.totalEntries??0,errors:Array.isArray(e.errors)?e.errors:[]}:{valid:!0,totalEntries:0,errors:[]}}sign(e){this.ensureOpen();let t=this.tryNative("sign",e);return typeof t=="string"?t:null}fileId(){this.ensureOpen();let e=this.tryNative("fileId");return typeof e=="string"?e:null}parentId(){this.ensureOpen();let e=this.tryNative("parentId");return typeof e=="string"?e:null}lineageDepth(){this.ensureOpen();let e=this.tryNative("lineageDepth");return typeof e=="number"?e:0}indexStats(){let e=this.status();return{totalVectors:e.totalVectors,dimension:this._dimension,totalSegments:e.totalSegments,fileSizeBytes:e.fileSizeBytes,epoch:e.epoch,witnessValid:e.witnessValid,witnessEntries:e.witnessEntries,idMapSize:this.strToNum.size}}freeze(){this.ensureOpen();let e=this.tryNative("freeze");return typeof e=="number"?e:0}derive(e){this.ensureOpen();let t=c();if(typeof this.db.derive=="function")try{let n=this.db.derive(e),i=new Map(this.strToNum),r=new Map(this.numToStr);return b(e,i,this.nextLabel),new s(n,e,this._dimension,i,r,this.nextLabel)}catch{}return this.fork(e)}ensureOpen(){if(!this._open)throw new Error("RVF database is closed")}tryNative(e,...t){if(typeof this.db[e]!="function")return null;try{return this.db[e](...t)}catch{return null}}persistIdMap(){b(this._path,this.strToNum,this.nextLabel)}}});export{$ as a,G as b,U as c,X as d,Z as e,P as f};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.11");process.exit(0)}
2
- import{e as l,l as i}from"./chunk-YRCNWQBO.js";import{a as r,c as g}from"./chunk-TCVEXQLL.js";g();var c=class extends i{config={name:"qe/tests/schedule",description:"Schedule and execute tests using phase-based pipeline with git-aware selection and flaky tracking. Runs tests in phases (unit, integration, e2e), selects affected tests from git changes, and tracks flaky tests.",domain:"test-execution",schema:this.buildSchema()};buildSchema(){return{type:"object",properties:{cwd:{type:"string",description:"Working directory for test execution (defaults to project root)"},gitRef:{type:"string",description:'Git ref to compare for affected test selection (e.g., "main", "HEAD~3")'},useGitAware:{type:"boolean",description:"Enable git-aware test selection to only run affected tests",default:!0},trackFlaky:{type:"boolean",description:"Enable flaky test tracking and quarantine",default:!0}}}}async execute(s,o){try{let{runTestPipeline:n}=await import("./test-scheduling-4WVI5DLE.js"),d=await l(o),t=await n({cwd:s.cwd||process.cwd(),memory:d,baseRef:s.gitRef,flakyHistoryPath:s.trackFlaky!==!1?".agentic-qe/flaky-history.json":void 0,runAllTests:s.useGitAware===!1}),u=t.phaseResults.reduce((e,a)=>e+a.totalTests,0),f=t.phaseResults.reduce((e,a)=>e+a.passed,0),p=t.phaseResults.reduce((e,a)=>e+a.failed,0);return{success:!0,data:{pipelineId:o.requestId,phases:t.phaseResults.map(e=>({phaseId:e.phaseId,phaseName:e.phaseName,totalTests:e.totalTests,passed:e.passed,failed:e.failed,passRate:e.passRate,durationMs:e.durationMs})),gitAware:{enabled:!t.ranAllTests,selectedTests:t.selectedTests.length,gitRef:s.gitRef},flakyTracking:{enabled:s.trackFlaky!==!1},totalDuration:t.totalDurationMs,ranAllTests:t.ranAllTests,summary:`Executed ${t.phaseResults.length} phases, ${u} tests (${f} passed, ${p} failed) in ${t.totalDurationMs}ms`}}}catch(n){return{success:!1,error:r(n)}}}};export{c as a};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.0");process.exit(0)}
2
+ import{e as l,l as i}from"./chunk-3JIJBR4V.js";import{a as r,c as g}from"./chunk-XITTURP2.js";g();var c=class extends i{config={name:"qe/tests/schedule",description:"Schedule and execute tests using phase-based pipeline with git-aware selection and flaky tracking. Runs tests in phases (unit, integration, e2e), selects affected tests from git changes, and tracks flaky tests.",domain:"test-execution",schema:this.buildSchema()};buildSchema(){return{type:"object",properties:{cwd:{type:"string",description:"Working directory for test execution (defaults to project root)"},gitRef:{type:"string",description:'Git ref to compare for affected test selection (e.g., "main", "HEAD~3")'},useGitAware:{type:"boolean",description:"Enable git-aware test selection to only run affected tests",default:!0},trackFlaky:{type:"boolean",description:"Enable flaky test tracking and quarantine",default:!0}}}}async execute(s,o){try{let{runTestPipeline:n}=await import("./test-scheduling-ZNOSQVLD.js"),d=await l(o),t=await n({cwd:s.cwd||process.cwd(),memory:d,baseRef:s.gitRef,flakyHistoryPath:s.trackFlaky!==!1?".agentic-qe/flaky-history.json":void 0,runAllTests:s.useGitAware===!1}),u=t.phaseResults.reduce((e,a)=>e+a.totalTests,0),f=t.phaseResults.reduce((e,a)=>e+a.passed,0),p=t.phaseResults.reduce((e,a)=>e+a.failed,0);return{success:!0,data:{pipelineId:o.requestId,phases:t.phaseResults.map(e=>({phaseId:e.phaseId,phaseName:e.phaseName,totalTests:e.totalTests,passed:e.passed,failed:e.failed,passRate:e.passRate,durationMs:e.durationMs})),gitAware:{enabled:!t.ranAllTests,selectedTests:t.selectedTests.length,gitRef:s.gitRef},flakyTracking:{enabled:s.trackFlaky!==!1},totalDuration:t.totalDurationMs,ranAllTests:t.ranAllTests,summary:`Executed ${t.phaseResults.length} phases, ${u} tests (${f} passed, ${p} failed) in ${t.totalDurationMs}ms`}}}catch(n){return{success:!1,error:r(n)}}}};export{c as a};