agentic-qe 3.14.6 → 3.14.7

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 (416) hide show
  1. package/.claude/skills/skills-manifest.json +1 -1
  2. package/CHANGELOG.md +74 -0
  3. package/assets/skills/skills-manifest.json +1 -1
  4. package/dist/cli/bundle.js +8 -8
  5. package/dist/cli/chunks/adapter-TVQKH65T.js +2 -0
  6. package/dist/cli/chunks/{agent-booster-wasm-2YGML6OU.js → agent-booster-wasm-AK2W76RG.js} +2 -2
  7. package/dist/cli/chunks/{agent-handler-D5SSQYNU.js → agent-handler-MGZCWHIY.js} +2 -2
  8. package/dist/cli/chunks/{agent-memory-branch-YHPLTITV.js → agent-memory-branch-JZ54MCSP.js} +2 -2
  9. package/dist/cli/chunks/aqe-learning-engine-ULGTVVWE.js +2 -0
  10. package/dist/cli/chunks/{arena-7BGOXGXO.js → arena-CUVH3V7H.js} +2 -2
  11. package/dist/cli/chunks/{arena-MCE6EU7K.js → arena-YSWTKBCL.js} +4 -4
  12. package/dist/cli/chunks/{audit-BMWTQECB.js → audit-LVU76QGA.js} +3 -3
  13. package/dist/cli/chunks/base-W42BURDL.js +2 -0
  14. package/dist/cli/chunks/{better-sqlite3-PMUNGASU.js → better-sqlite3-DB3LOJQU.js} +2 -2
  15. package/dist/cli/chunks/{brain-handler-QPUFYX7F.js → brain-handler-SD63KOQ6.js} +3 -3
  16. package/dist/cli/chunks/{branch-enumerator-WKFDGRN4.js → branch-enumerator-4MNOPUC7.js} +2 -2
  17. package/dist/cli/chunks/{browser-VY5HKH5X.js → browser-OLPNTWQE.js} +2 -2
  18. package/dist/cli/chunks/browser-workflow-HKGHFFFT.js +2 -0
  19. package/dist/cli/chunks/{chunk-62N4NUJH.js → chunk-23CX7JNL.js} +2 -2
  20. package/dist/cli/chunks/{chunk-MW2GGZZ5.js → chunk-25P6JA6V.js} +1 -1
  21. package/dist/cli/chunks/{chunk-RSXXCL4A.js → chunk-2G63VIJE.js} +1 -1
  22. package/dist/cli/chunks/{chunk-3NIG7S5W.js → chunk-2IMSJ7IO.js} +1 -1
  23. package/dist/cli/chunks/{chunk-I33ERSGB.js → chunk-36VKMAMN.js} +2 -2
  24. package/dist/cli/chunks/{chunk-2TMWAQQ3.js → chunk-3M7J4U74.js} +3 -3
  25. package/dist/cli/chunks/{chunk-CM7U6TAX.js → chunk-3QJU4Q4R.js} +2 -2
  26. package/dist/cli/chunks/{chunk-H5BS5VH7.js → chunk-4EKV7PHB.js} +2 -2
  27. package/dist/cli/chunks/{chunk-IG5GNEC6.js → chunk-4INST4ZL.js} +1 -1
  28. package/dist/cli/chunks/{chunk-YHKEDEAA.js → chunk-53BXTTRO.js} +3 -3
  29. package/dist/cli/chunks/{chunk-ENGZ4D5V.js → chunk-5D7ZFWDS.js} +2 -2
  30. package/dist/cli/chunks/{chunk-DZ3AUAAB.js → chunk-5FSLMYAC.js} +2 -2
  31. package/dist/cli/chunks/{chunk-FBMN7B46.js → chunk-5GFKTJ65.js} +2 -2
  32. package/dist/cli/chunks/{chunk-NMAIY4PX.js → chunk-5U6N4V5M.js} +11 -11
  33. package/dist/cli/chunks/{chunk-B6D2CHEH.js → chunk-6EGS77BB.js} +1 -1
  34. package/dist/cli/chunks/{chunk-NQZ5AR3D.js → chunk-6PJPQGF4.js} +2 -2
  35. package/dist/cli/chunks/{chunk-ICTXTNQZ.js → chunk-6RD44SCE.js} +1 -1
  36. package/dist/cli/chunks/{chunk-2NPKIBAZ.js → chunk-74IOEOMH.js} +2 -2
  37. package/dist/cli/chunks/{chunk-RTFO5UQH.js → chunk-77QZHIVX.js} +2 -2
  38. package/dist/cli/chunks/{chunk-D45SG6CP.js → chunk-7EZ2Z2CK.js} +1 -1
  39. package/dist/cli/chunks/{chunk-UNFFDHER.js → chunk-7MIOK72I.js} +10 -32
  40. package/dist/cli/chunks/{chunk-HNFVJP4I.js → chunk-7QYOTUOX.js} +2 -2
  41. package/dist/cli/chunks/{chunk-Q7EAGKAE.js → chunk-A2VUCUTT.js} +2 -2
  42. package/dist/cli/chunks/{chunk-TVYY3OCX.js → chunk-A3DK3XNZ.js} +1 -1
  43. package/dist/cli/chunks/{chunk-RETBYIAC.js → chunk-A5MA7A23.js} +4 -4
  44. package/dist/cli/chunks/{chunk-DUYOVM5I.js → chunk-AEUEMVJK.js} +2 -2
  45. package/dist/cli/chunks/{chunk-6U7LNMWZ.js → chunk-AJUBT4NP.js} +2 -2
  46. package/dist/cli/chunks/{chunk-7CUQCCMD.js → chunk-B2YGVSOP.js} +2 -2
  47. package/dist/cli/chunks/{chunk-SNOBH4AZ.js → chunk-B4I43GE2.js} +2 -2
  48. package/dist/cli/chunks/{chunk-VMNWDJIZ.js → chunk-BD7FEUN3.js} +2 -2
  49. package/dist/cli/chunks/{chunk-HM6ZSCPI.js → chunk-BE4KALTE.js} +1 -1
  50. package/dist/cli/chunks/{chunk-WGM35YWL.js → chunk-BEFTQVEW.js} +2 -2
  51. package/dist/cli/chunks/{chunk-SMDN3BQZ.js → chunk-BLG7SH4A.js} +1 -1
  52. package/dist/cli/chunks/{chunk-AJRUJAAK.js → chunk-C3FXFU2T.js} +1 -1
  53. package/dist/cli/chunks/{chunk-IQO7UCFR.js → chunk-CBONQM5D.js} +2 -2
  54. package/dist/cli/chunks/{chunk-L4RUBPLR.js → chunk-CQNMGK6Y.js} +2 -2
  55. package/dist/cli/chunks/{chunk-NHWGMJAP.js → chunk-CVOQ6ESD.js} +2 -2
  56. package/dist/cli/chunks/{chunk-P6OYS755.js → chunk-DOBKEXMJ.js} +1 -1
  57. package/dist/cli/chunks/{chunk-QZANMBIT.js → chunk-DYTQHRUS.js} +1 -1
  58. package/dist/cli/chunks/{chunk-FZOBD67M.js → chunk-EADSQN5T.js} +1 -1
  59. package/dist/cli/chunks/{chunk-DHVX5UB2.js → chunk-EGOIIUBD.js} +2 -2
  60. package/dist/cli/chunks/{chunk-6OS76PHI.js → chunk-EIGRV3J6.js} +2 -2
  61. package/dist/cli/chunks/{chunk-CD542DNJ.js → chunk-EJ6MMYLK.js} +1 -1
  62. package/dist/cli/chunks/{chunk-ELLBS5RP.js → chunk-ENK44A6Q.js} +2 -2
  63. package/dist/cli/chunks/{chunk-VGFFFKGK.js → chunk-EYXE2XKP.js} +2 -2
  64. package/dist/cli/chunks/{chunk-72KXSMWI.js → chunk-F2OPFVQH.js} +1 -1
  65. package/dist/cli/chunks/{chunk-DK4XN4CU.js → chunk-FBZC4IGB.js} +2 -2
  66. package/dist/cli/chunks/{chunk-MUOG6QXR.js → chunk-FSSR6WBE.js} +2 -2
  67. package/dist/cli/chunks/{chunk-DPYSUDAO.js → chunk-FW4DJ4FJ.js} +1 -1
  68. package/dist/cli/chunks/{chunk-ZVWVV4EX.js → chunk-FYPX5WBJ.js} +1 -1
  69. package/dist/cli/chunks/{chunk-7J6QC567.js → chunk-G367W7XR.js} +3 -3
  70. package/dist/cli/chunks/{chunk-IAF6T27S.js → chunk-GLGKQX2V.js} +2 -2
  71. package/dist/cli/chunks/{chunk-JXGFRBUO.js → chunk-GV4DYPJP.js} +2 -2
  72. package/dist/cli/chunks/{chunk-BPEDWS6O.js → chunk-GVVFTFMB.js} +2 -2
  73. package/dist/cli/chunks/{chunk-CF2ISEOJ.js → chunk-H5RQPO3X.js} +2 -2
  74. package/dist/cli/chunks/{chunk-GSF6MB64.js → chunk-HPWWYT67.js} +2 -2
  75. package/dist/cli/chunks/{chunk-RG52OKAM.js → chunk-HXXHMLJ5.js} +1 -1
  76. package/dist/cli/chunks/{chunk-SESK3ARK.js → chunk-HYFQUWNB.js} +2 -2
  77. package/dist/cli/chunks/{chunk-7D3V65N5.js → chunk-HYOPJHHW.js} +1 -1
  78. package/dist/cli/chunks/{chunk-7LPR6HJG.js → chunk-HZY42OVU.js} +2 -2
  79. package/dist/cli/chunks/{chunk-SDRHUMJB.js → chunk-IAENZ2DR.js} +2 -2
  80. package/dist/cli/chunks/{chunk-B6MOJC3X.js → chunk-IEJ7ZV3M.js} +1 -1
  81. package/dist/cli/chunks/{chunk-UCFQALXO.js → chunk-IWFFO6VT.js} +2 -2
  82. package/dist/cli/chunks/chunk-J7AQZLIH.js +21 -0
  83. package/dist/cli/chunks/{chunk-H52HZ67P.js → chunk-JHJUSSAU.js} +2 -2
  84. package/dist/cli/chunks/{chunk-2YXGBZWV.js → chunk-JOZ47MV6.js} +1 -1
  85. package/dist/cli/chunks/{chunk-EAY2JMZG.js → chunk-JZT7BU44.js} +2 -2
  86. package/dist/cli/chunks/{chunk-BVR7RMC5.js → chunk-KD2BLA5Y.js} +1 -1
  87. package/dist/cli/chunks/{chunk-BAMN2CHI.js → chunk-KUHLTVWC.js} +1 -1
  88. package/dist/cli/chunks/{chunk-5QQSIGUA.js → chunk-LU2EDWQK.js} +2 -2
  89. package/dist/cli/chunks/{chunk-D6CJIGRU.js → chunk-LXZMP3VX.js} +54 -54
  90. package/dist/cli/chunks/{chunk-GPYVDFB3.js → chunk-LY7MFGBD.js} +196 -187
  91. package/dist/cli/chunks/{chunk-W6HXLH5G.js → chunk-MM56VPNE.js} +2 -2
  92. package/dist/cli/chunks/{chunk-E6G2RD5H.js → chunk-MNQN7UZX.js} +2 -2
  93. package/dist/cli/chunks/{chunk-ZCRTRYXK.js → chunk-MQZ53OR3.js} +2 -2
  94. package/dist/cli/chunks/{chunk-3HZS4M3O.js → chunk-MT7UNBZ7.js} +2 -2
  95. package/dist/cli/chunks/{chunk-XAS3XRYM.js → chunk-MZB2UV2O.js} +1 -1
  96. package/dist/cli/chunks/{chunk-GDSXITFH.js → chunk-MZMG6CUJ.js} +2 -2
  97. package/dist/cli/chunks/{chunk-6SQM2MUX.js → chunk-N5XOXPHZ.js} +2 -2
  98. package/dist/cli/chunks/{chunk-5OOMJGFN.js → chunk-NBLDBVAW.js} +1 -1
  99. package/dist/cli/chunks/{chunk-PI7TJS62.js → chunk-ND4QTZOL.js} +2 -2
  100. package/dist/cli/chunks/{chunk-H6ZM3PUT.js → chunk-NHUGHAY6.js} +1 -1
  101. package/dist/cli/chunks/{chunk-5VFPCSK7.js → chunk-NOHWJOBS.js} +1 -1
  102. package/dist/cli/chunks/{chunk-DBDPRORT.js → chunk-O5V7RHVG.js} +2 -2
  103. package/dist/cli/chunks/{chunk-UQ32JHES.js → chunk-O6MO5KMR.js} +2 -2
  104. package/dist/cli/chunks/{chunk-WO4QMXIG.js → chunk-OAZX6WFU.js} +2 -2
  105. package/dist/cli/chunks/{chunk-GGRHV6D7.js → chunk-OEPNNLR4.js} +1 -1
  106. package/dist/cli/chunks/{chunk-AIRGNL55.js → chunk-OIDWDGLG.js} +2 -2
  107. package/dist/cli/chunks/{chunk-V4DM6ELU.js → chunk-ON2UTP2U.js} +2 -2
  108. package/dist/cli/chunks/{chunk-MBRHSU6W.js → chunk-ONR2NXXD.js} +10 -10
  109. package/dist/cli/chunks/{chunk-WCJBU2KI.js → chunk-OXHF3L2T.js} +2 -2
  110. package/dist/cli/chunks/{chunk-AVBJYI5I.js → chunk-OZGIOKEA.js} +1 -1
  111. package/dist/cli/chunks/{chunk-YFBSPLJG.js → chunk-P2UPYSDJ.js} +1 -1
  112. package/dist/cli/chunks/{chunk-C6KWXUFJ.js → chunk-P7XSPP5D.js} +2 -2
  113. package/dist/cli/chunks/{chunk-QDFTT3RF.js → chunk-PCJQCEBA.js} +2 -2
  114. package/dist/cli/chunks/chunk-PELENDDQ.js +2 -0
  115. package/dist/cli/chunks/{chunk-257E2A5M.js → chunk-PYKY22GC.js} +5 -5
  116. package/dist/cli/chunks/{chunk-LL3IGZBI.js → chunk-Q3NSU24F.js} +2 -2
  117. package/dist/cli/chunks/{chunk-Y3LZ35OG.js → chunk-Q6NTEICT.js} +2 -2
  118. package/dist/cli/chunks/chunk-QFETNCNN.js +12 -0
  119. package/dist/cli/chunks/{chunk-SE4WIB26.js → chunk-QGOWNVVG.js} +1 -1
  120. package/dist/cli/chunks/{chunk-6RE3X4V5.js → chunk-QPLSYEWJ.js} +2 -2
  121. package/dist/cli/chunks/{chunk-FWASDOT2.js → chunk-QQFQDEUE.js} +2 -2
  122. package/dist/cli/chunks/{chunk-2JVWITNK.js → chunk-QUORH2MG.js} +55 -79
  123. package/dist/cli/chunks/{chunk-5J6W7SIA.js → chunk-QVH5Y7AP.js} +1 -1
  124. package/dist/cli/chunks/{chunk-YSLL6VSL.js → chunk-RC2A4JZ5.js} +2 -2
  125. package/dist/cli/chunks/{chunk-IB27QACC.js → chunk-RDGPXENG.js} +2 -2
  126. package/dist/cli/chunks/{chunk-PX5YDCRH.js → chunk-RKI3IQKQ.js} +2 -2
  127. package/dist/cli/chunks/{chunk-BMAPORJ7.js → chunk-RKUAWQOF.js} +2 -2
  128. package/dist/cli/chunks/chunk-RLW25X66.js +2 -0
  129. package/dist/cli/chunks/{chunk-RFNPJK6N.js → chunk-ROVZSZCS.js} +3 -3
  130. package/dist/cli/chunks/{chunk-MQROI74N.js → chunk-RT6O2HW2.js} +2 -2
  131. package/dist/cli/chunks/{chunk-Y3UOUNHM.js → chunk-SM2YJ2AL.js} +2 -2
  132. package/dist/cli/chunks/{chunk-BBT64TII.js → chunk-SRPLERER.js} +3 -3
  133. package/dist/cli/chunks/{chunk-YS4FCTWF.js → chunk-T77GZF4B.js} +1 -1
  134. package/dist/cli/chunks/{chunk-IV5UZOHH.js → chunk-TFK2AYIN.js} +2 -2
  135. package/dist/cli/chunks/chunk-TW3SR4TS.js +2 -0
  136. package/dist/cli/chunks/{chunk-7Z5LHRC3.js → chunk-TXSPBLBT.js} +2 -2
  137. package/dist/cli/chunks/chunk-UA7TDVL7.js +12 -0
  138. package/dist/cli/chunks/{chunk-3EZOZN25.js → chunk-UBJG3IHT.js} +2 -2
  139. package/dist/cli/chunks/{chunk-QW6VMTBR.js → chunk-UFSVUBTR.js} +2 -2
  140. package/dist/cli/chunks/{chunk-ZEV3YTO7.js → chunk-UOI6ULCH.js} +2 -2
  141. package/dist/cli/chunks/{chunk-JZOS5FCX.js → chunk-UYUJT6QO.js} +2 -2
  142. package/dist/cli/chunks/{chunk-3EA536JF.js → chunk-V5AK56DA.js} +2 -2
  143. package/dist/cli/chunks/{chunk-UKA2KOXE.js → chunk-V6RE4YRQ.js} +2 -2
  144. package/dist/cli/chunks/{chunk-RZZCUIAI.js → chunk-VW6FRMLW.js} +2 -2
  145. package/dist/cli/chunks/chunk-VXKWNRGA.js +2 -0
  146. package/dist/cli/chunks/{chunk-6SH5VZUD.js → chunk-VYDVI6FZ.js} +2 -2
  147. package/dist/cli/chunks/{chunk-BJTJLJRZ.js → chunk-WF6UISKW.js} +3 -3
  148. package/dist/cli/chunks/{chunk-ZL6SYKUK.js → chunk-WIH522AP.js} +1 -1
  149. package/dist/cli/chunks/{chunk-JIXUMYKZ.js → chunk-WOV6XI3A.js} +1 -1
  150. package/dist/cli/chunks/{chunk-JBTPOIAC.js → chunk-X7ADKL7T.js} +2 -2
  151. package/dist/cli/chunks/{chunk-JVNTSNWU.js → chunk-XBYQ2BS4.js} +2 -2
  152. package/dist/cli/chunks/{chunk-Z7WODOTH.js → chunk-XL5KIYE3.js} +2 -2
  153. package/dist/cli/chunks/{chunk-JMONHE4B.js → chunk-XWYELBZS.js} +1 -1
  154. package/dist/cli/chunks/{chunk-SJUXE4IC.js → chunk-XYLQZWF6.js} +2 -2
  155. package/dist/cli/chunks/{chunk-KNNISEDY.js → chunk-Y6AKKQIQ.js} +1 -1
  156. package/dist/cli/chunks/{chunk-CCK4BF76.js → chunk-YMW57PEL.js} +1 -1
  157. package/dist/cli/chunks/{chunk-64VGZQLB.js → chunk-YO4ESCB4.js} +1 -1
  158. package/dist/cli/chunks/{chunk-ZSPU4MOS.js → chunk-YRHTQZU4.js} +2 -2
  159. package/dist/cli/chunks/chunk-Z4Q5PCRZ.js +65 -0
  160. package/dist/cli/chunks/{chunk-Q5XTSMWR.js → chunk-ZELWDJXT.js} +2 -2
  161. package/dist/cli/chunks/{chunk-SPV2VKC5.js → chunk-ZQZD55MN.js} +2 -2
  162. package/dist/cli/chunks/{chunk-66VWCR67.js → chunk-ZS4XVJGV.js} +2 -2
  163. package/dist/cli/chunks/{chunk-6LIHFV7O.js → chunk-ZUB5YOCM.js} +2 -2
  164. package/dist/cli/chunks/chunk-ZUOVNFXK.js +2 -0
  165. package/dist/cli/chunks/{chunk-7NITCZWD.js → chunk-ZWEKAEEV.js} +1 -1
  166. package/dist/cli/chunks/{ci-W6K6G2KZ.js → ci-J3TDK5RA.js} +8 -8
  167. package/dist/cli/chunks/{ci-output-LDT24TS3.js → ci-output-RLS32FUY.js} +2 -2
  168. package/dist/cli/chunks/{circuit-breaker-F5V4KITU.js → circuit-breaker-MRCC7WCM.js} +2 -2
  169. package/dist/cli/chunks/{claude-flow-setup-DT6WQQVD.js → claude-flow-setup-LIZCEKDF.js} +2 -2
  170. package/dist/cli/chunks/client-3BD2DI4N.js +2 -0
  171. package/dist/cli/chunks/{cline-installer-G7TJOAEX.js → cline-installer-T7H6R2RC.js} +2 -2
  172. package/dist/cli/chunks/{code-PGE6A42V.js → code-XMBLI7OF.js} +3 -3
  173. package/dist/cli/chunks/{code-index-extractor-RNITH372.js → code-index-extractor-QS7BYLEX.js} +2 -2
  174. package/dist/cli/chunks/{codex-installer-LBX77AI3.js → codex-installer-6PGT5FM6.js} +2 -2
  175. package/dist/cli/chunks/{completions-4AWLAARX.js → completions-2A3WRXY2.js} +2 -2
  176. package/dist/cli/chunks/{complexity-analyzer-ZPNSS476.js → complexity-analyzer-23HOOGJ7.js} +2 -2
  177. package/dist/cli/chunks/{continuedev-installer-UAPWX6OA.js → continuedev-installer-4FSF7B3N.js} +2 -2
  178. package/dist/cli/chunks/{copilot-installer-BJN2YJGI.js → copilot-installer-A5GRQQUU.js} +2 -2
  179. package/dist/cli/chunks/core-handlers-C3H2ZCS2.js +2 -0
  180. package/dist/cli/chunks/{cost-tracker-MHP2VJ63.js → cost-tracker-Z4STQ5VB.js} +2 -2
  181. package/dist/cli/chunks/{coverage-PQB4IEFG.js → coverage-NUPP6KZZ.js} +3 -3
  182. package/dist/cli/chunks/cross-domain-router-JCQ7SWDP.js +2 -0
  183. package/dist/cli/chunks/{cursor-installer-ZXBWYAS3.js → cursor-installer-FVJ7ROPJ.js} +2 -2
  184. package/dist/cli/chunks/{daemon-N2BEGEFY.js → daemon-7ZZA2MMN.js} +4 -4
  185. package/dist/cli/chunks/{daemon-64C7R6OJ.js → daemon-D662EX5N.js} +3 -3
  186. package/dist/cli/chunks/{dag-attention-scheduler-SPZDAPNL.js → dag-attention-scheduler-IB4TQ2KA.js} +2 -2
  187. package/dist/cli/chunks/{detect-LXJBSSZW.js → detect-LGLBZN4I.js} +2 -2
  188. package/dist/cli/chunks/{dist-node-U3TKZ2IZ.js → dist-node-Z3OL42YE.js} +2 -2
  189. package/dist/cli/chunks/{domain-handler-3DDWUVSR.js → domain-handler-L3CLNL7U.js} +2 -2
  190. package/dist/cli/chunks/{domain-plugins-JJVWI4OQ.js → domain-plugins-GQ3V5X6L.js} +2 -2
  191. package/dist/cli/chunks/{domain-transfer-M36KUJ2U.js → domain-transfer-MFCI76IY.js} +2 -2
  192. package/dist/cli/chunks/dream-FTP33IJB.js +2 -0
  193. package/dist/cli/chunks/{embed-and-insert-pattern-JPAR7TXX.js → embed-and-insert-pattern-UGD6USYH.js} +2 -2
  194. package/dist/cli/chunks/{eval-SOLG23EA.js → eval-3B7UIYGY.js} +2 -2
  195. package/dist/cli/chunks/{experience-capture-middleware-T7G2VOOD.js → experience-capture-middleware-3RQ4NYY3.js} +3 -3
  196. package/dist/cli/chunks/{fast-paths-32N3ELI4.js → fast-paths-QOSAEPYD.js} +2 -2
  197. package/dist/cli/chunks/{feature-flags-NAHKLDRN.js → feature-flags-3S5TH6P4.js} +2 -2
  198. package/dist/cli/chunks/{feature-flags-APJDQ4N7.js → feature-flags-TLF4NKOH.js} +2 -2
  199. package/dist/cli/chunks/{file-discovery-YKVM3MDB.js → file-discovery-AEVMJRNB.js} +2 -2
  200. package/dist/cli/chunks/{fleet-55M5CJS4.js → fleet-E6WTXWFL.js} +3 -3
  201. package/dist/cli/chunks/{gnn-wrapper-UD6E6S6Z.js → gnn-wrapper-MCKH3AUU.js} +2 -2
  202. package/dist/cli/chunks/{heartbeat-handler-OYVW3VSC.js → heartbeat-handler-U7XENHRR.js} +4 -4
  203. package/dist/cli/chunks/heartbeat-scheduler-HXBJVJL2.js +2 -0
  204. package/dist/cli/chunks/hnsw-adapter-TU6WG2ME.js +2 -0
  205. package/dist/cli/chunks/hnsw-index-MS5KODD7.js +2 -0
  206. package/dist/cli/chunks/{hnsw-legacy-bridge-HBYIS3ZW.js → hnsw-legacy-bridge-5GW4SAEI.js} +2 -2
  207. package/dist/cli/chunks/{hnswlib-node-EQPM42OU.js → hnswlib-node-7BLZBK5T.js} +2 -2
  208. package/dist/cli/chunks/{hooks-5ZSSJWO6.js → hooks-F3O2SB6H.js} +10 -10
  209. package/dist/cli/chunks/hybrid-backend-HT45LBHC.js +2 -0
  210. package/dist/cli/chunks/{hypergraph-engine-XBGVQ4PD.js → hypergraph-engine-PV4EKXHB.js} +2 -2
  211. package/dist/cli/chunks/{hypergraph-handler-CAWAQ673.js → hypergraph-handler-VOWO5ZTW.js} +3 -3
  212. package/dist/cli/chunks/impact-analyzer-AP4AGTG5.js +2 -0
  213. package/dist/cli/chunks/{init-handler-PRHXSARK.js → init-handler-ENJ5ONJX.js} +16 -14
  214. package/dist/cli/chunks/init-wizard-I5DFZUQL.js +2 -0
  215. package/dist/cli/chunks/kernel-MISPSPPA.js +2 -0
  216. package/dist/cli/chunks/{kilocode-installer-F7LXBM7I.js → kilocode-installer-HNNJOOPE.js} +2 -2
  217. package/dist/cli/chunks/{kiro-installer-NM723ZRG.js → kiro-installer-UZBIQ3IC.js} +2 -2
  218. package/dist/cli/chunks/knowledge-graph-L26JESGE.js +2 -0
  219. package/dist/cli/chunks/{learning-5QYIDHH3.js → learning-YMLCVFUT.js} +3 -3
  220. package/dist/cli/chunks/{llm-router-43HKWPSX.js → llm-router-YWTARCCT.js} +4 -4
  221. package/dist/cli/chunks/llm-router-service-MWGC43ZA.js +2 -0
  222. package/dist/cli/chunks/{load-5YDBWSCS.js → load-DKE3F3IP.js} +2 -2
  223. package/dist/cli/chunks/load-test-H5ISNNM5.js +2 -0
  224. package/dist/cli/chunks/{mcp-UMAPMNMY.js → mcp-5PSGIUCW.js} +2 -2
  225. package/dist/cli/chunks/{memory-FWCPCQFP.js → memory-3L3O6JMM.js} +5 -5
  226. package/dist/cli/chunks/memory-backend-HWDNOBKW.js +2 -0
  227. package/dist/cli/chunks/memory-handlers-ZFDVQZM5.js +2 -0
  228. package/dist/cli/chunks/{multi-model-executor-2XTBGLE4.js → multi-model-executor-AEEO7IA4.js} +2 -2
  229. package/dist/cli/chunks/{opencode-installer-GIXOJ6NS.js → opencode-installer-ABBO355U.js} +2 -2
  230. package/dist/cli/chunks/{orchestrator-VW6BKHLI.js → orchestrator-E36Q7MKE.js} +17 -17
  231. package/dist/cli/chunks/pattern-null-store-GQP6ICWK.js +2 -0
  232. package/dist/cli/chunks/{pattern-usage-recorder-7CEUC3J7.js → pattern-usage-recorder-H4XKSID4.js} +2 -2
  233. package/dist/cli/chunks/{pipeline-IGUQPPPO.js → pipeline-BGFEHXIN.js} +2 -2
  234. package/dist/cli/chunks/{platform-2P636I7B.js → platform-GK7ZVDJI.js} +2 -2
  235. package/dist/cli/chunks/{plugin-NY6SWDPE.js → plugin-CAH2CKI6.js} +2 -2
  236. package/dist/cli/chunks/{prime-radiant-advanced-wasm-2UUDTIO2.js → prime-radiant-advanced-wasm-M5EYRONA.js} +2 -2
  237. package/dist/cli/chunks/{project-root-IOISG5KX.js → project-root-BSNZC243.js} +2 -2
  238. package/dist/cli/chunks/protocol-executor-AD5A4DAI.js +2 -0
  239. package/dist/cli/chunks/{protocol-handler-ZTPCRQ5W.js → protocol-handler-JDSSC2SF.js} +2 -2
  240. package/dist/cli/chunks/{prove-SQX5A3IG.js → prove-ANPTOZJE.js} +2 -2
  241. package/dist/cli/chunks/qe-reasoning-bank-W3Z2PKTR.js +2 -0
  242. package/dist/cli/chunks/{quality-DROILKRY.js → quality-SXWGYRQR.js} +2 -2
  243. package/dist/cli/chunks/{quality-gate-PWKWDJY2.js → quality-gate-GYNCA4ZY.js} +3 -3
  244. package/dist/cli/chunks/queen-coordinator-HQRHLIJX.js +2 -0
  245. package/dist/cli/chunks/{real-embeddings-P5U3MGYC.js → real-embeddings-WSRYAOZM.js} +2 -2
  246. package/dist/cli/chunks/{ref-validation-KY73NQXD.js → ref-validation-AZ3LRWEK.js} +2 -2
  247. package/dist/cli/chunks/{roocode-installer-6JPPRB3W.js → roocode-installer-2QKGFIEU.js} +2 -2
  248. package/dist/cli/chunks/router-MTP5LH4H.js +2 -0
  249. package/dist/cli/chunks/routing-feedback-GWETVB4L.js +2 -0
  250. package/dist/cli/chunks/{routing-handler-VTJIVFUO.js → routing-handler-UYDC5MMD.js} +2 -2
  251. package/dist/cli/chunks/{ruvector-commands-C6RPSJJO.js → ruvector-commands-QXADPVEY.js} +2 -2
  252. package/dist/cli/chunks/rvf-dual-writer-4UE5S7WP.js +2 -0
  253. package/dist/cli/chunks/rvf-migration-adapter-PHH3HF4Q.js +2 -0
  254. package/dist/cli/chunks/{rvf-migration-coordinator-R53URRIO.js → rvf-migration-coordinator-GD4NBFKT.js} +2 -2
  255. package/dist/cli/chunks/rvf-native-adapter-KTLZBUWV.js +2 -0
  256. package/dist/cli/chunks/{rvf-store-integrity-MMXN5TEJ.js → rvf-store-integrity-7SXG66IL.js} +2 -2
  257. package/dist/cli/chunks/safe-db-FWWGAPVE.js +2 -0
  258. package/dist/cli/chunks/schedule-TPA4V4D5.js +2 -0
  259. package/dist/cli/chunks/scheduler-5ZTEPNDD.js +2 -0
  260. package/dist/cli/chunks/{security-3B3R2NL4.js → security-YKB622PK.js} +3 -3
  261. package/dist/cli/chunks/{shared-rvf-adapter-VIJB7JUS.js → shared-rvf-adapter-KMLAV7JK.js} +2 -2
  262. package/dist/cli/chunks/{shared-rvf-dual-writer-UVWGDUWC.js → shared-rvf-dual-writer-OYY27DFV.js} +2 -2
  263. package/dist/cli/chunks/sqlite-persistence-HPTT624C.js +2 -0
  264. package/dist/cli/chunks/{standalone-memory-M4LWAAYZ.js → standalone-memory-2DOABVLC.js} +2 -2
  265. package/dist/cli/chunks/{status-handler-YYFV6OZL.js → status-handler-EXRKETV7.js} +2 -2
  266. package/dist/cli/chunks/{structural-health-27E6LLKB.js → structural-health-2SKK6DU6.js} +2 -2
  267. package/dist/cli/chunks/sync-DQ2YUNI6.js +2 -0
  268. package/dist/cli/chunks/{sync-J3LJ56WN.js → sync-UW7SX7GO.js} +2 -2
  269. package/dist/cli/chunks/{task-handler-4MCEBQZL.js → task-handler-LYQ6WYUY.js} +2 -2
  270. package/dist/cli/chunks/task-handlers-DIJO232S.js +9 -0
  271. package/dist/cli/chunks/test-WRHZMUCW.js +33 -0
  272. package/dist/cli/chunks/{test-scheduling-ZJBFRZ3J.js → test-scheduling-HI23RXFK.js} +3 -3
  273. package/dist/cli/chunks/token-bootstrap-23SA6SWZ.js +2 -0
  274. package/dist/cli/chunks/{token-usage-3X5WMTG2.js → token-usage-M7RRDPXO.js} +2 -2
  275. package/dist/cli/chunks/{transformers-MVL4C5IX.js → transformers-4TC35KKS.js} +2 -2
  276. package/dist/cli/chunks/{tree-sitter-wasm-parser-SLW65ZFO.js → tree-sitter-wasm-parser-F4LTKAWD.js} +2 -2
  277. package/dist/cli/chunks/{types-TG5P3CRS.js → types-NBXV6LXQ.js} +2 -2
  278. package/dist/cli/chunks/unified-memory-OVFEPRPS.js +2 -0
  279. package/dist/cli/chunks/unified-memory-hnsw-KKRSCZHR.js +2 -0
  280. package/dist/cli/chunks/unified-persistence-7GLR4RI3.js +2 -0
  281. package/dist/cli/chunks/{upgrade-ETBHDEPY.js → upgrade-4BGOU5RM.js} +2 -2
  282. package/dist/cli/chunks/{validate-C2A73LZK.js → validate-EDWAR63H.js} +2 -2
  283. package/dist/cli/chunks/{validate-swarm-67XN42ML.js → validate-swarm-VI72CPR7.js} +2 -2
  284. package/dist/cli/chunks/visual-security-2FUM5GLI.js +2 -0
  285. package/dist/cli/chunks/{web-tree-sitter-USJN77P4.js → web-tree-sitter-Y5XBRQXF.js} +2 -2
  286. package/dist/cli/chunks/{windsurf-installer-5GGZXGJW.js → windsurf-installer-VEX23WAF.js} +2 -2
  287. package/dist/cli/chunks/{witness-chain-IWS5ZHHL.js → witness-chain-3YNL6YGY.js} +2 -2
  288. package/dist/cli/chunks/witness-chain-MH6GA5L6.js +2 -0
  289. package/dist/cli/chunks/witness-chain-repair-MJZGZRWT.js +2 -0
  290. package/dist/cli/chunks/{witness-chain-verifier-3GEADWPE.js → witness-chain-verifier-TTJYXTBE.js} +2 -2
  291. package/dist/cli/chunks/{witness-key-manager-ZWEIK3VJ.js → witness-key-manager-EM6YXYOY.js} +2 -2
  292. package/dist/cli/chunks/{workflow-KHMVVBBA.js → workflow-2RBDOM7V.js} +4 -4
  293. package/dist/cli/chunks/workflow-orchestrator-H6G65YKU.js +2 -0
  294. package/dist/cli/chunks/wrappers-5OTAVVOV.js +2 -0
  295. package/dist/cli/commands/ci.js +1 -1
  296. package/dist/cli/commands/test.js +18 -3
  297. package/dist/cli/handlers/init-handler.d.ts +2 -0
  298. package/dist/cli/handlers/init-handler.js +8 -2
  299. package/dist/cli/index.js +8 -0
  300. package/dist/coordination/handlers/test-execution-handlers.js +13 -8
  301. package/dist/coordination/index.d.ts +1 -1
  302. package/dist/coordination/queen-event-handlers.js +9 -6
  303. package/dist/coordination/result-saver.js +1 -1
  304. package/dist/coordination/services/index.d.ts +1 -1
  305. package/dist/coordination/services/task-audit-logger.d.ts +38 -13
  306. package/dist/coordination/services/task-audit-logger.js +33 -5
  307. package/dist/coordination/task-executor.d.ts +5 -0
  308. package/dist/coordination/task-executor.js +10 -5
  309. package/dist/domains/test-generation/coordinator.js +6 -5
  310. package/dist/domains/test-generation/interfaces.d.ts +11 -1
  311. package/dist/domains/test-generation/services/behavior-example-validation.d.ts +36 -0
  312. package/dist/domains/test-generation/services/behavior-example-validation.js +89 -0
  313. package/dist/domains/test-generation/services/behavior-examples.d.ts +8 -0
  314. package/dist/domains/test-generation/services/behavior-examples.js +65 -0
  315. package/dist/domains/test-generation/services/test-generator.d.ts +1 -1
  316. package/dist/domains/test-generation/services/test-generator.js +59 -30
  317. package/dist/domains/visual-accessibility/services/axe-core-audit.d.ts +0 -15
  318. package/dist/domains/visual-accessibility/services/axe-core-audit.js +12 -10
  319. package/dist/init/browser-engine-installer.d.ts +5 -5
  320. package/dist/init/browser-engine-installer.js +28 -6
  321. package/dist/init/init-wizard.d.ts +2 -0
  322. package/dist/init/orchestrator.js +1 -0
  323. package/dist/init/phases/09-assets.js +8 -18
  324. package/dist/init/phases/phase-interface.d.ts +2 -0
  325. package/dist/integrations/agentic-flow/reasoning-bank/index.d.ts +2 -5
  326. package/dist/integrations/vibium/client.d.ts +1 -0
  327. package/dist/integrations/vibium/client.js +24 -11
  328. package/dist/integrations/vibium/runtime.d.ts +14 -0
  329. package/dist/integrations/vibium/runtime.js +94 -0
  330. package/dist/kernel/pattern-fts-self-heal.d.ts +63 -0
  331. package/dist/kernel/pattern-fts-self-heal.js +193 -0
  332. package/dist/kernel/process-lifecycle.d.ts +60 -0
  333. package/dist/kernel/process-lifecycle.js +91 -0
  334. package/dist/kernel/unified-memory-schemas.d.ts +15 -1
  335. package/dist/kernel/unified-memory-schemas.js +53 -25
  336. package/dist/kernel/unified-memory.js +31 -34
  337. package/dist/kernel/unified-persistence.js +12 -6
  338. package/dist/learning/experience-capture.d.ts +2 -1
  339. package/dist/learning/experience-capture.js +23 -8
  340. package/dist/learning/pattern-store.d.ts +1 -1
  341. package/dist/learning/pattern-store.js +27 -30
  342. package/dist/learning/qe-patterns.d.ts +6 -0
  343. package/dist/learning/qe-reasoning-bank.d.ts +1 -0
  344. package/dist/learning/qe-reasoning-bank.js +14 -4
  345. package/dist/learning/real-qe-reasoning-bank.d.ts +9 -4
  346. package/dist/learning/real-qe-reasoning-bank.js +28 -4
  347. package/dist/learning/rvf-pattern-store.js +19 -19
  348. package/dist/learning/sqlite-persistence.js +9 -24
  349. package/dist/mcp/bundle.js +508 -545
  350. package/dist/mcp/entry.js +52 -6
  351. package/dist/mcp/handlers/domain-handler-configs.js +12 -4
  352. package/dist/mcp/handlers/task-handlers.js +11 -7
  353. package/dist/mcp/protocol-server.js +18 -3
  354. package/dist/mcp/services/reasoning-bank-service.d.ts +6 -1
  355. package/dist/mcp/services/reasoning-bank-service.js +5 -1
  356. package/dist/mcp/tools/test-execution/e2e-execute.js +9 -1
  357. package/dist/mcp/tools/test-generation/generate.d.ts +6 -1
  358. package/dist/mcp/tools/test-generation/generate.js +8 -0
  359. package/dist/mcp/types.d.ts +6 -2
  360. package/dist/shared/error-utils.d.ts +15 -0
  361. package/dist/shared/error-utils.js +21 -0
  362. package/dist/shared/events/domain-events.d.ts +2 -1
  363. package/package.json +10 -6
  364. package/dist/cli/chunks/adapter-UYOJPTOX.js +0 -2
  365. package/dist/cli/chunks/aqe-learning-engine-JR5AVQXR.js +0 -2
  366. package/dist/cli/chunks/base-DRZ2LS6X.js +0 -2
  367. package/dist/cli/chunks/browser-workflow-CJ7T3MXF.js +0 -2
  368. package/dist/cli/chunks/chunk-4N23RFDU.js +0 -2
  369. package/dist/cli/chunks/chunk-AHKELLIO.js +0 -12
  370. package/dist/cli/chunks/chunk-MJS53PRX.js +0 -2
  371. package/dist/cli/chunks/chunk-PZPWRQ2M.js +0 -21
  372. package/dist/cli/chunks/chunk-QGA55PFM.js +0 -12
  373. package/dist/cli/chunks/chunk-TCHGOB2N.js +0 -2
  374. package/dist/cli/chunks/chunk-Z6GGIRQQ.js +0 -65
  375. package/dist/cli/chunks/client-KHWJT6FB.js +0 -2
  376. package/dist/cli/chunks/core-handlers-HING5RRG.js +0 -2
  377. package/dist/cli/chunks/cross-domain-router-PQTD6AZN.js +0 -2
  378. package/dist/cli/chunks/dream-WUGRSNCV.js +0 -2
  379. package/dist/cli/chunks/heartbeat-scheduler-33XX5XNQ.js +0 -2
  380. package/dist/cli/chunks/hnsw-adapter-XQPERX3H.js +0 -2
  381. package/dist/cli/chunks/hnsw-index-2GNXTWHH.js +0 -2
  382. package/dist/cli/chunks/hybrid-backend-CCF7URKI.js +0 -2
  383. package/dist/cli/chunks/impact-analyzer-HGKAZWIG.js +0 -2
  384. package/dist/cli/chunks/init-wizard-72MFBI3G.js +0 -2
  385. package/dist/cli/chunks/kernel-BRCBVMSK.js +0 -2
  386. package/dist/cli/chunks/knowledge-graph-DG44IPEI.js +0 -2
  387. package/dist/cli/chunks/llm-router-service-24KXFX32.js +0 -2
  388. package/dist/cli/chunks/load-test-N4TAYJY3.js +0 -2
  389. package/dist/cli/chunks/memory-backend-NVYFYVAU.js +0 -2
  390. package/dist/cli/chunks/memory-handlers-UTWCNCHL.js +0 -2
  391. package/dist/cli/chunks/pattern-null-store-SBPNYDBR.js +0 -2
  392. package/dist/cli/chunks/protocol-executor-IBYEII5Q.js +0 -2
  393. package/dist/cli/chunks/qe-reasoning-bank-7IETWW6W.js +0 -2
  394. package/dist/cli/chunks/queen-coordinator-NHUK2MWJ.js +0 -2
  395. package/dist/cli/chunks/router-SRSO3IHF.js +0 -2
  396. package/dist/cli/chunks/routing-feedback-PASRE5HY.js +0 -2
  397. package/dist/cli/chunks/rvf-dual-writer-4M4J67OU.js +0 -2
  398. package/dist/cli/chunks/rvf-migration-adapter-TSXGT5LF.js +0 -2
  399. package/dist/cli/chunks/rvf-native-adapter-MOF3E7BR.js +0 -2
  400. package/dist/cli/chunks/safe-db-QJLFO33B.js +0 -2
  401. package/dist/cli/chunks/schedule-YIVXW5O2.js +0 -2
  402. package/dist/cli/chunks/scheduler-AON7DWSJ.js +0 -2
  403. package/dist/cli/chunks/sqlite-persistence-75VHKKQB.js +0 -2
  404. package/dist/cli/chunks/sync-26CEGSTC.js +0 -2
  405. package/dist/cli/chunks/task-handlers-GYBAWKE2.js +0 -9
  406. package/dist/cli/chunks/test-MPC5HRH5.js +0 -33
  407. package/dist/cli/chunks/token-bootstrap-2Y2XITBX.js +0 -2
  408. package/dist/cli/chunks/unified-memory-UCQ6AB32.js +0 -2
  409. package/dist/cli/chunks/unified-memory-hnsw-IXYUMKRR.js +0 -2
  410. package/dist/cli/chunks/unified-persistence-7E6JQ4FZ.js +0 -2
  411. package/dist/cli/chunks/vibium-NILGKHLN.js +0 -2
  412. package/dist/cli/chunks/visual-security-4VZXPEVG.js +0 -2
  413. package/dist/cli/chunks/witness-chain-JQA2VPZI.js +0 -2
  414. package/dist/cli/chunks/witness-chain-repair-4UA7IPS3.js +0 -2
  415. package/dist/cli/chunks/workflow-orchestrator-GI5NQH7C.js +0 -2
  416. package/dist/cli/chunks/wrappers-N6XIK5PT.js +0 -2
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.6");process.exit(0)}
2
- import{b as fe}from"./chunk-FZOBD67M.js";import{a as gt}from"./chunk-TVYY3OCX.js";import{a as mt,b as pt}from"./chunk-ZSPU4MOS.js";import{j as I}from"./chunk-NQZ5AR3D.js";import{a as ut,b as dt}from"./chunk-NHWGMJAP.js";import{a as rt}from"./chunk-QZANMBIT.js";import{a as ot,b as ct,c as lt}from"./chunk-7LPR6HJG.js";import{a as he}from"./chunk-7D3V65N5.js";import{b as at}from"./chunk-CCK4BF76.js";import{k as w,o as pe}from"./chunk-2JVWITNK.js";import{b as M,d as st}from"./chunk-AIRGNL55.js";import{a as C,c as T,d as y}from"./chunk-KNNISEDY.js";import{a as ln}from"./chunk-TCHGOB2N.js";import{e as it}from"./chunk-FBMN7B46.js";import{a as h,b as nt,c as k}from"./chunk-MJS53PRX.js";import{i as v}from"./chunk-DPYSUDAO.js";import{R as on,S as cn}from"./chunk-DUYOVM5I.js";import{b as G,d as an,f as tt}from"./chunk-64VGZQLB.js";function yt(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&&(gn.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=>pn.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=hn[n];return{complexity:n,recommendedModel:i,factors:e,score:t,timestamp:new Date}}var gn,mn,pn,S,hn,Tt=G(()=>{"use strict";gn=["security-compliance","chaos-resilience","defect-intelligence"],mn=["code-intelligence","contract-testing","quality-assessment","learning-optimization"],pn=["sast","dast","vulnerability","owasp","chaos-testing","resilience","fault-injection","mutation-testing"],S={critical:70,complex:45,moderate:20},hn={critical:"opus",complex:"sonnet",moderate:"sonnet",simple:"haiku"}});var R,Ce=G(()=>{"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(),c=Math.sqrt(-2*Math.log(Math.max(s,1e-10)))*Math.cos(2*Math.PI*o);i[r]=c*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 l=0;l<32;l++){let u=this.biasHidden[l];for(let d=0;d<4;d++)u+=e[d]*this.weightsInputHidden[d*32+l];i[l]=Math.max(0,u)}let r=new Float32Array(3);for(let l=0;l<3;l++){let u=this.biasOutput[l];for(let d=0;d<32;d++)u+=i[d]*this.weightsHiddenOutput[d*3+l];r[l]=u}let s=this.softmax(r),o=new Float32Array(3);for(let l=0;l<3;l++)o[l]=(l===t?1:0)-s[l],o[l]*=n*this.learningRate;for(let l=0;l<32;l++)for(let u=0;u<3;u++)this.weightsHiddenOutput[l*3+u]+=i[l]*o[u];for(let l=0;l<3;l++)this.biasOutput[l]+=o[l];let c=new Float32Array(32);for(let l=0;l<32;l++){if(i[l]<=0)continue;let u=0;for(let d=0;d<3;d++)u+=o[d]*this.weightsHiddenOutput[l*3+d];c[l]=u}for(let l=0;l<4;l++)for(let u=0;u<32;u++)this.weightsInputHidden[l*32+u]+=e[l]*c[u];for(let l=0;l<32;l++)this.biasHidden[l]+=c[l]}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 Ct={};an(Ct,{NeuralTinyDancerRouter:()=>W,SimpleNeuralRouter:()=>R,createNeuralTinyDancerRouter:()=>Dn});import{performance as vt}from"perf_hooks";function Dn(a){return new W(a)}var fn,yn,Tn,vn,Cn,bn,kn,Sn,W,bt=G(()=>{"use strict";be();Ce();Ce();fn=1e3,yn=.1,Tn=.2,vn=50,Cn=.01,bn=["haiku","sonnet","opus"],kn={haiku:0,sonnet:1,opus:2},Sn={"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},W=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 H(e),this.neuralNet=new R(e.learningRate??Cn),this.circuitBreakerThreshold=e.circuitBreakerThreshold??Tn,this.shadowModeDecisionLimit=e.shadowModeDecisions??fn,this.shadowModeMaxDisagreement=e.shadowModeMaxDisagreement??yn,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=vt.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=bn[s],c=r[s];if(this.totalNeuralDecisions++,this.shadowModeActive){let g=n.model===o;return g||this.shadowDisagreements++,this.shadowDecisions.push({taskDescription:e.description.slice(0,100),ruleDecision:n.model,neuralDecision:o,agreed:g,neuralConfidence:c,timestamp:new Date}),this.evaluateShadowModeExit(),n}let l=vt.now()-t,u=this.computeEmpiricalConfidenceBounds(r);return c<.3||u.calibrationScore>.8?n:{model:o,confidence:c,uncertainty:1-c,triggerMultiModel:n.triggerMultiModel,triggerHumanReview:n.triggerHumanReview,complexity:n.complexity,classification:n.classification,latencyMs:l,reasoning:this.buildNeuralReasoning(o,c,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),c=e.domain??"",l=Sn[c]??.25,u=this.domainSuccessRates.get(c),d=u?u.success/Math.max(1,u.total):.7;return[n,o,l,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",c=this.domainSuccessRates.get(o)??{success:0,total:0};c.total++,n&&c.success++,this.domainSuccessRates.set(o,c),this.recentOutcomes.push(n),this.recentOutcomes.length>vn&&this.recentOutcomes.shift(),this.checkCircuitBreaker();let l=this.extractFeatures(e,t.classification),u=kn[r],d=(i-.5)*2;try{this.neuralNet.updateWeights(l,u,d),this.totalWeightUpdates++}catch{}let g=this.neuralNet.forward(l),p=this.argmax(g),f=1-g[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((c,l)=>c-l),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 kt}from"perf_hooks";function St(a){try{let{getRuVectorFeatureFlags:e}=(cn(),tt(on));if(e().useNeuralRouting){let{NeuralTinyDancerRouter:n}=(bt(),tt(Ct));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 H(a)}var H,be=G(()=>{"use strict";Tt();H=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=kt.now(),n=yt(e),i=this.calculateConfidence(n),r=1-i,s=this.isSecurityTask(e),o=s&&i<this.securityConfidenceThreshold||i<this.confidenceThreshold&&n.complexity!=="simple",c=r>this.uncertaintyThreshold||s&&n.complexity==="critical",l=kt.now()-t,u=this.buildReasoning(n,i,s,o,c),d={model:n.recommendedModel,confidence:i,uncertainty:r,triggerMultiModel:o,triggerHumanReview:c,complexity:n.complexity,classification:n,latencyMs:l,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 g=Math.abs(t-d);g<r&&(r=g)}let s=.55,o=.35,c=Math.min(r/25,1),l=s+c*o,u=n!=="simple"?Math.min(.05,e.factors.length*.01):0;return Math.min(.95,l+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(c=>c.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 un={enableConsoleLog:!0,maxEntries:1e3,logPrefix:"[TASK]"},j=class{entries=[];config;constructor(e={}){this.config={...un,...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 ye(a){return new j(a)}pe();st();var Te=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=v();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.7");process.exit(0)}
2
+ import{b as fe}from"./chunk-EADSQN5T.js";import{a as gt}from"./chunk-A3DK3XNZ.js";import{a as mt,b as pt}from"./chunk-YRHTQZU4.js";import{j as I}from"./chunk-6PJPQGF4.js";import{a as ut,b as dt}from"./chunk-CVOQ6ESD.js";import{a as rt}from"./chunk-DYTQHRUS.js";import{a as ot,b as ct,c as lt}from"./chunk-HZY42OVU.js";import{a as he}from"./chunk-HYOPJHHW.js";import{b as at}from"./chunk-YMW57PEL.js";import{o as M,s as pe}from"./chunk-QUORH2MG.js";import{b as w,d as st}from"./chunk-OIDWDGLG.js";import{a as C,c as T,d as y}from"./chunk-Y6AKKQIQ.js";import{a as un}from"./chunk-TW3SR4TS.js";import{e as it}from"./chunk-5GFKTJ65.js";import{a as h,b as nt,e as k}from"./chunk-ZUOVNFXK.js";import{i as v}from"./chunk-FW4DJ4FJ.js";import{R as cn,S as ln}from"./chunk-AEUEMVJK.js";import{b as G,d as on,f as tt}from"./chunk-YO4ESCB4.js";function Tt(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&&(mn.includes(a.domain)?(t+=30,e.push({name:"complex-domain",weight:30,description:`Domain '${a.domain}' requires complex reasoning`})):pn.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=>hn.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=fn[n];return{complexity:n,recommendedModel:i,factors:e,score:t,timestamp:new Date}}var mn,pn,hn,S,fn,vt=G(()=>{"use strict";mn=["security-compliance","chaos-resilience","defect-intelligence"],pn=["code-intelligence","contract-testing","quality-assessment","learning-optimization"],hn=["sast","dast","vulnerability","owasp","chaos-testing","resilience","fault-injection","mutation-testing"],S={critical:70,complex:45,moderate:20},fn={critical:"opus",complex:"sonnet",moderate:"sonnet",simple:"haiku"}});var R,Ce=G(()=>{"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(),c=Math.sqrt(-2*Math.log(Math.max(s,1e-10)))*Math.cos(2*Math.PI*o);i[r]=c*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 l=0;l<32;l++){let u=this.biasHidden[l];for(let d=0;d<4;d++)u+=e[d]*this.weightsInputHidden[d*32+l];i[l]=Math.max(0,u)}let r=new Float32Array(3);for(let l=0;l<3;l++){let u=this.biasOutput[l];for(let d=0;d<32;d++)u+=i[d]*this.weightsHiddenOutput[d*3+l];r[l]=u}let s=this.softmax(r),o=new Float32Array(3);for(let l=0;l<3;l++)o[l]=(l===t?1:0)-s[l],o[l]*=n*this.learningRate;for(let l=0;l<32;l++)for(let u=0;u<3;u++)this.weightsHiddenOutput[l*3+u]+=i[l]*o[u];for(let l=0;l<3;l++)this.biasOutput[l]+=o[l];let c=new Float32Array(32);for(let l=0;l<32;l++){if(i[l]<=0)continue;let u=0;for(let d=0;d<3;d++)u+=o[d]*this.weightsHiddenOutput[l*3+d];c[l]=u}for(let l=0;l<4;l++)for(let u=0;u<32;u++)this.weightsInputHidden[l*32+u]+=e[l]*c[u];for(let l=0;l<32;l++)this.biasHidden[l]+=c[l]}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 bt={};on(bt,{NeuralTinyDancerRouter:()=>W,SimpleNeuralRouter:()=>R,createNeuralTinyDancerRouter:()=>An});import{performance as Ct}from"perf_hooks";function An(a){return new W(a)}var yn,Tn,vn,Cn,bn,kn,Sn,Dn,W,kt=G(()=>{"use strict";be();Ce();Ce();yn=1e3,Tn=.1,vn=.2,Cn=50,bn=.01,kn=["haiku","sonnet","opus"],Sn={haiku:0,sonnet:1,opus:2},Dn={"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},W=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 H(e),this.neuralNet=new R(e.learningRate??bn),this.circuitBreakerThreshold=e.circuitBreakerThreshold??vn,this.shadowModeDecisionLimit=e.shadowModeDecisions??yn,this.shadowModeMaxDisagreement=e.shadowModeMaxDisagreement??Tn,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=Ct.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=kn[s],c=r[s];if(this.totalNeuralDecisions++,this.shadowModeActive){let g=n.model===o;return g||this.shadowDisagreements++,this.shadowDecisions.push({taskDescription:e.description.slice(0,100),ruleDecision:n.model,neuralDecision:o,agreed:g,neuralConfidence:c,timestamp:new Date}),this.evaluateShadowModeExit(),n}let l=Ct.now()-t,u=this.computeEmpiricalConfidenceBounds(r);return c<.3||u.calibrationScore>.8?n:{model:o,confidence:c,uncertainty:1-c,triggerMultiModel:n.triggerMultiModel,triggerHumanReview:n.triggerHumanReview,complexity:n.complexity,classification:n.classification,latencyMs:l,reasoning:this.buildNeuralReasoning(o,c,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),c=e.domain??"",l=Dn[c]??.25,u=this.domainSuccessRates.get(c),d=u?u.success/Math.max(1,u.total):.7;return[n,o,l,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",c=this.domainSuccessRates.get(o)??{success:0,total:0};c.total++,n&&c.success++,this.domainSuccessRates.set(o,c),this.recentOutcomes.push(n),this.recentOutcomes.length>Cn&&this.recentOutcomes.shift(),this.checkCircuitBreaker();let l=this.extractFeatures(e,t.classification),u=Sn[r],d=(i-.5)*2;try{this.neuralNet.updateWeights(l,u,d),this.totalWeightUpdates++}catch{}let g=this.neuralNet.forward(l),p=this.argmax(g),f=1-g[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((c,l)=>c-l),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 St}from"perf_hooks";function Dt(a){try{let{getRuVectorFeatureFlags:e}=(ln(),tt(cn));if(e().useNeuralRouting){let{NeuralTinyDancerRouter:n}=(kt(),tt(bt));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 H(a)}var H,be=G(()=>{"use strict";vt();H=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=St.now(),n=Tt(e),i=this.calculateConfidence(n),r=1-i,s=this.isSecurityTask(e),o=s&&i<this.securityConfidenceThreshold||i<this.confidenceThreshold&&n.complexity!=="simple",c=r>this.uncertaintyThreshold||s&&n.complexity==="critical",l=St.now()-t,u=this.buildReasoning(n,i,s,o,c),d={model:n.recommendedModel,confidence:i,uncertainty:r,triggerMultiModel:o,triggerHumanReview:c,complexity:n.complexity,classification:n,latencyMs:l,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 g=Math.abs(t-d);g<r&&(r=g)}let s=.55,o=.35,c=Math.min(r/25,1),l=s+c*o,u=n!=="simple"?Math.min(.05,e.factors.length*.01):0;return Math.min(.95,l+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(c=>c.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}}}});import{randomUUID as ht}from"node:crypto";var dn={enableConsoleLog:!0,maxEntries:1e3,logPrefix:"[TASK]"},j=class{entries=[];config;generation=ht();recordedEntries=0;droppedEntries=0;constructor(e={}){if(this.config={...dn,...e},!Number.isSafeInteger(this.config.maxEntries)||this.config.maxEntries<0)throw new RangeError("maxEntries must be a non-negative safe integer")}log(e,t,n){let i={sequence:++this.recordedEntries,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){let r=this.entries.length-this.config.maxEntries;this.entries.splice(0,r),this.droppedEntries+=r}if(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 n===0?[]:t.slice(-n)}getSnapshot(e){return{...this.getWindow(),entries:this.getEntries(e)}}getWindow(){return{generation:this.generation,recordedEntries:this.recordedEntries,retainedEntries:this.entries.length,droppedEntries:this.droppedEntries,firstRetainedSequence:this.entries[0]?.sequence??null,lastRetainedSequence:this.entries[this.entries.length-1]?.sequence??null,disposition:this.droppedEntries>0?"truncated":"complete"}}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{...this.getWindow(),basis:"retained-window",totalEntries:this.entries.length,operationCounts:e,taskCount:t.size,agentCount:n.size}}clear(){this.entries.length=0,this.generation=ht(),this.recordedEntries=0,this.droppedEntries=0}};function ye(a){return new j(a)}pe();st();var Te=class{memory;initialized=!1;constructor(e){this.memory=e??M()}async initialize(){this.initialized||(this.memory.isInitialized()||await this.memory.initialize(),this.initialized=!0)}async saveSnapshot(e){this.ensureInitialized();let t=v();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
@@ -118,7 +118,7 @@ import{b as fe}from"./chunk-FZOBD67M.js";import{a as gt}from"./chunk-TVYY3OCX.js
118
118
  `).run(new Date(n-r).toISOString()),l=t.prepare(`
119
119
  DELETE FROM mincut_alerts
120
120
  WHERE timestamp < ? AND acknowledged = 1
121
- `).run(new Date(n-s).toISOString());return{historyDeleted:o.changes,snapshotsDeleted:c.changes,alertsDeleted:l.changes}}ensureInitialized(){if(!this.initialized)throw new Error("MinCutPersistence not initialized. Call initialize() first.")}rowToSnapshot(e){return{timestamp:new Date(e.timestamp),vertices:M(e.vertices_json),edges:M(e.edges_json),stats:{vertexCount:e.vertex_count,edgeCount:e.edge_count,totalWeight:e.total_weight,averageDegree:e.edge_count>0&&e.vertex_count>0?e.edge_count*2/e.vertex_count:0,density:e.vertex_count>1?e.edge_count/(e.vertex_count*(e.vertex_count-1)/2):0,isConnected:e.is_connected===1,componentCount:e.component_count}}}rowToAlert(e){return{id:e.id,severity:e.severity,message:e.message,minCutValue:e.mincut_value,threshold:e.threshold,affectedVertices:e.affected_vertices_json?M(e.affected_vertices_json):[],remediations:e.remediations_json?M(e.remediations_json):[],acknowledged:e.acknowledged===1,timestamp:new Date(e.timestamp)}}};function ht(a){return new Te(a)}var dn={...ot,autoUpdateFromEvents:!0,persistData:!0,snapshotIntervalMs:6e4,includeInQueenHealth:!0,minHealthIssueSeverity:"medium"},ve=class{constructor(e,t,n={}){this.eventBus=e;this.agentCoordinator=t;this.config={...dn,...n},this.graph=n.sharedGraph??at(),this.monitor=ct(this.graph,this.config,this.eventBus),this.persistence=ht()}eventBus;agentCoordinator;config;graph;monitor;persistence;eventSubscriptions=[];snapshotTimer=null;initialized=!1;async initialize(){this.initialized||(this.config.persistData&&await this.persistence.initialize(),await this.buildGraphFromAgents(),this.config.autoUpdateFromEvents&&this.subscribeToEvents(),this.monitor.start(),this.config.persistData&&this.startSnapshotTimer(),this.initialized=!0)}async dispose(){this.monitor.stop(),this.snapshotTimer&&(clearInterval(this.snapshotTimer),this.snapshotTimer=null);for(let e of this.eventSubscriptions)e();if(this.eventSubscriptions=[],this.config.persistData)try{await this.saveSnapshot()}catch{}this.initialized=!1}async buildGraphFromAgents(){this.config.sharedGraph||this.graph.clear();let e=this.agentCoordinator.listAgents();for(let t of C)this.graph.addVertex({id:`domain:${t}`,type:"domain",domain:t,weight:2,createdAt:new Date});for(let t of e)this.addAgentVertex(t);this.buildCoordinationEdges(e)}addAgentVertex(e){let t=e,n={id:`agent:${e.id}`,type:"agent",domain:e.domain,capabilities:t.capabilities,weight:1,createdAt:e.startedAt??new Date,metadata:{status:e.status,taskCount:t.taskCount??0,health:t.health??1}};if(this.graph.addVertex(n),e.domain){let i=`domain:${e.domain}`;this.graph.hasVertex(i)&&this.graph.addEdge({source:`agent:${e.id}`,target:i,weight:1,type:"coordination",bidirectional:!0})}}buildCoordinationEdges(e){let t=new Map;for(let i of e)if(i.domain){let r=t.get(i.domain)||[];r.push(i),t.set(i.domain,r)}for(let[i,r]of t)for(let s=0;s<r.length;s++)for(let o=s+1;o<r.length;o++)this.graph.addEdge({source:`agent:${r[s].id}`,target:`agent:${r[o].id}`,weight:.5,type:"communication",bidirectional:!0});let n=[["test-generation","test-execution"],["test-execution","coverage-analysis"],["coverage-analysis","quality-assessment"],["quality-assessment","defect-intelligence"],["requirements-validation","test-generation"],["code-intelligence","test-generation"],["security-compliance","quality-assessment"],["contract-testing","test-execution"],["visual-accessibility","quality-assessment"],["chaos-resilience","test-execution"],["learning-optimization","defect-intelligence"]];for(let[i,r]of n){let s=`domain:${i}`,o=`domain:${r}`;this.graph.hasVertex(s)&&this.graph.hasVertex(o)&&this.graph.addEdge({source:s,target:o,weight:1.5,type:"workflow",bidirectional:!1})}}subscribeToEvents(){let e=async l=>{let{agentId:u,domain:d,type:g,capabilities:p}=l.payload;this.addAgentVertex({id:u,name:`${d}-${g}`,domain:d,type:g,status:"running",startedAt:new Date,capabilities:p,health:1,taskCount:0}),this.config.persistData&&await this.persistence.recordHistory({minCutValue:this.monitor.getMinCutValue(),vertexCount:this.graph.vertexCount,edgeCount:this.graph.edgeCount})},t=async l=>{let{agentId:u}=l.payload;this.graph.removeVertex(`agent:${u}`),this.monitor.checkHealth().status==="critical"&&await this.reportHealthIssue({severity:"high",message:`Agent ${u} termination caused critical MinCut degradation`,timestamp:new Date})},n=async l=>{let{agentId:u,status:d}=l.payload,g=`agent:${u}`,p=this.graph.getVertex(g);p&&this.graph.addVertex({...p,metadata:{...p.metadata,status:d}})},i=async l=>{let{fromAgent:u,toAgent:d}=l.payload,g=`agent:${u}`,p=`agent:${d}`;if(this.graph.hasVertex(g)&&this.graph.hasVertex(p)){let f=this.graph.getEdge(g,p);f?this.graph.addEdge({...f,weight:Math.min(f.weight+.1,3),lastActivity:new Date,messageCount:(f.messageCount??0)+1}):this.graph.addEdge({source:g,target:p,weight:.5,type:"communication",bidirectional:!0,lastActivity:new Date,messageCount:1})}},r=this.eventBus.subscribe("QueenAgentSpawned",e),s=this.eventBus.subscribe("QueenAgentTerminated",t),o=this.eventBus.subscribe("QueenAgentStatusChanged",n),c=this.eventBus.subscribe("QueenTaskCoordination",i);this.eventSubscriptions.push(()=>r.unsubscribe(),()=>s.unsubscribe(),()=>o.unsubscribe(),()=>c.unsubscribe())}getMinCutHealth(){return this.monitor.getHealth()}isEmptyTopology(){return this.graph.getVerticesByType("agent").length===0}getHealthIssuesFromMinCut(){if(this.isEmptyTopology())return[];let e=this.monitor.getActiveAlerts(),t=[];for(let i of e){let r=this.mapSeverity(i.severity);this.severityValue(r)>=this.severityValue(this.config.minHealthIssueSeverity)&&t.push({severity:r,message:`MinCut: ${i.message}`,timestamp:i.timestamp})}let n=this.monitor.getWeakVertices();for(let i of n.slice(0,3))i.riskScore>.7&&t.push({severity:"high",message:`Weak agent topology: ${i.reason} (risk: ${(i.riskScore*100).toFixed(0)}%)`,timestamp:new Date,domain:i.vertex.domain});return t}extendQueenHealth(e){if(!this.config.includeInQueenHealth)return e;let t=this.getMinCutHealth(),n=this.getHealthIssuesFromMinCut(),i=e.status;return t.status==="critical"&&i==="healthy"&&(i="degraded"),{...e,status:i,issues:[...e.issues,...n],minCut:t}}extendQueenMetrics(e){let t=this.monitor.getHealth(),n=this.graph.getStats();return{...e,minCutValue:t.minCutValue,weakVertexCount:t.weakVertexCount,topologyDensity:n.density}}async saveSnapshot(){if(!this.config.persistData)return;let e=this.graph.snapshot();await this.persistence.saveSnapshot(e)}startSnapshotTimer(){this.snapshotTimer=setInterval(async()=>{this.isEmptyTopology()||(await this.saveSnapshot(),await this.persistence.recordHistory({minCutValue:this.monitor.getMinCutValue(),vertexCount:this.graph.vertexCount,edgeCount:this.graph.edgeCount}))},this.config.snapshotIntervalMs)}getGraph(){return this.graph}getMonitor(){return this.monitor}getPersistence(){return this.persistence}getMinCutValue(){return this.monitor.getMinCutValue()}getWeakVertices(){return this.monitor.getWeakVertices()}isTopologyCritical(){return this.monitor.isCritical()}addVertex(e){this.graph.addVertex(e)}addEdge(e){this.graph.addEdge(e)}removeVertex(e){return this.graph.removeVertex(e)}async refreshGraph(){await this.buildGraphFromAgents()}async reportHealthIssue(e){await this.eventBus.publish({id:v(),type:"MinCutHealthIssue",source:"mincut-bridge",timestamp:new Date,payload:{issue:e}})}mapSeverity(e){return e}severityValue(e){return{critical:5,high:4,medium:3,low:2,info:1}[e]}};function ft(a,e,t){return new ve(a,e,t)}be();import{performance as Mt}from"perf_hooks";var xn={multiModel:.8,humanReview:.2,security:.85,escalation:.6},An={trivial:["booster","haiku"],simple:["haiku"],moderate:["sonnet"],complex:["sonnet","opus"],critical:["opus"]},En={enabled:!0,preferCheaperModels:!0,costPerMillionTokens:{haiku:{input:.25,output:1.25},sonnet:{input:3,output:15},opus:{input:15,output:75}},dailyCostLimit:0,costAlertThreshold:.8},Mn={enabled:!0,maxAttempts:2,retryDelayMs:1e3,chain:{booster:"haiku",haiku:"sonnet",sonnet:"opus",opus:null}},D={confidence:xn,tierMapping:An,costOptimization:En,fallback:Mn,verbose:!1,enableEMACalibration:!0,enableAutoEscalation:!0,enableNeuralRouting:!1};function Dt(a=D){let e=structuredClone(a);return process.env.ROUTING_CONFIDENCE_MULTI_MODEL&&(e.confidence.multiModel=parseFloat(process.env.ROUTING_CONFIDENCE_MULTI_MODEL)),process.env.ROUTING_CONFIDENCE_HUMAN_REVIEW&&(e.confidence.humanReview=parseFloat(process.env.ROUTING_CONFIDENCE_HUMAN_REVIEW)),process.env.ROUTING_CONFIDENCE_SECURITY&&(e.confidence.security=parseFloat(process.env.ROUTING_CONFIDENCE_SECURITY)),process.env.ROUTING_CONFIDENCE_ESCALATION&&(e.confidence.escalation=parseFloat(process.env.ROUTING_CONFIDENCE_ESCALATION)),process.env.ROUTING_COST_DAILY_LIMIT&&(e.costOptimization.dailyCostLimit=parseFloat(process.env.ROUTING_COST_DAILY_LIMIT)),process.env.ROUTING_COST_PREFER_CHEAPER&&(e.costOptimization.preferCheaperModels=process.env.ROUTING_COST_PREFER_CHEAPER.toLowerCase()==="true"),process.env.ROUTING_FALLBACK_ENABLED&&(e.fallback.enabled=process.env.ROUTING_FALLBACK_ENABLED.toLowerCase()==="true"),process.env.ROUTING_FALLBACK_MAX_ATTEMPTS&&(e.fallback.maxAttempts=parseInt(process.env.ROUTING_FALLBACK_MAX_ATTEMPTS,10)),process.env.ROUTING_VERBOSE&&(e.verbose=process.env.ROUTING_VERBOSE.toLowerCase()==="true"),e}function xt(a,e,t=D){if(e/100<=.2)return t.tierMapping.trivial;switch(a){case"simple":return t.tierMapping.simple;case"moderate":return t.tierMapping.moderate;case"complex":return t.tierMapping.complex;case"critical":return t.tierMapping.critical}}function At(a,e=D){return e.fallback.enabled?e.fallback.chain[a]??null:null}function ke(a){switch(a){case"booster":case"haiku":return"haiku";case"sonnet":return"sonnet";case"opus":return"opus"}}function Et(a,e,t,n=D){let i=n.costOptimization.costPerMillionTokens[a],r=e/1e6*i.input,s=t/1e6*i.output;return r+s}function Se(a){let{confidence:e}=a;if(e.multiModel<0||e.multiModel>1)throw new Error("multiModel confidence must be between 0 and 1");if(e.humanReview<0||e.humanReview>1)throw new Error("humanReview confidence must be between 0 and 1");if(e.security<0||e.security>1)throw new Error("security confidence must be between 0 and 1");if(e.escalation<0||e.escalation>1)throw new Error("escalation confidence must be between 0 and 1");if(a.costOptimization.dailyCostLimit<0)throw new Error("dailyCostLimit must be non-negative");if(a.costOptimization.costAlertThreshold<0||a.costOptimization.costAlertThreshold>1)throw new Error("costAlertThreshold must be between 0 and 1");if(a.fallback.maxAttempts<0)throw new Error("maxAttempts must be non-negative");if(a.fallback.retryDelayMs<0)throw new Error("retryDelayMs must be non-negative")}var V=class{tinyDancer;routingConfig;enableCostTracking;avgInputTokens;avgOutputTokens;totalCost=0;costByModel={haiku:0,sonnet:0,opus:0};totalTasks=0;dailyCost=0;lastCostReset=new Date;outcomes=[];maxOutcomes=1e3;constructor(e={}){this.tinyDancer=St(e.tinyDancer);let t=this.mergeRoutingConfig(e.routing);this.routingConfig=Dt(t),Se(this.routingConfig),this.enableCostTracking=e.enableCostTracking??!0,this.avgInputTokens=e.avgInputTokens??2e3,this.avgOutputTokens=e.avgOutputTokens??500}async route(e){let t=Mt.now();this.checkDailyCostReset();let n=await this.tinyDancer.route(e),i=void 0,s=xt(n.complexity,n.classification.score,this.routingConfig)[0],o=ke(s),c=this.buildFallbackChain(s),l=this.enableCostTracking?Et(o,this.avgInputTokens,this.avgOutputTokens,this.routingConfig):0;this.checkCostLimits(l);let u=this.buildQueenReasoning(n,s,c,l),d=Mt.now()-t,g={tier:s,model:o,complexity:n.complexity,confidence:n.confidence,triggerMultiModel:n.triggerMultiModel,triggerHumanReview:n.triggerHumanReview,fallbackTiers:c,estimatedCost:l,reasoning:u,latencyMs:d,tinyDancerResult:n,advisorResult:i,timestamp:new Date};return this.enableCostTracking&&(this.totalCost+=l,this.costByModel[o]+=l,this.dailyCost+=l),this.totalTasks++,this.routingConfig.verbose&&console.log(`[QueenRouter] Route: ${s} (${o}) complexity=${n.complexity}, confidence=${(n.confidence*100).toFixed(1)}%, cost=$${l.toFixed(4)}`),g}recordOutcome(e,t,n,i,r=i?1:0,s=0,o=0,c){let l={task:e,decision:t,usedTier:n,success:i,qualityScore:r,durationMs:s,fallbackAttempts:o,error:c,timestamp:new Date};this.outcomes.push(l),this.outcomes.length>this.maxOutcomes&&this.outcomes.shift(),this.tinyDancer.recordOutcome?.(e,t.tinyDancerResult,i,r,ke(n),s),this.routingConfig.verbose&&console.log(`[QueenRouter] Recorded outcome: tier=${n}, success=${i}, quality=${(r*100).toFixed(0)}%, fallbacks=${o}`)}getSuccessRateByTier(){let e={booster:{success:0,total:0},haiku:{success:0,total:0},sonnet:{success:0,total:0},opus:{success:0,total:0}};for(let t of this.outcomes){let n=t.usedTier;e[n].total++,t.success&&e[n].success++}return{booster:e.booster.total>0?e.booster.success/e.booster.total:0,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}}getFallbackStats(){let e=this.outcomes.filter(i=>i.fallbackAttempts>0),t=e.filter(i=>i.success),n=e.reduce((i,r)=>i+r.fallbackAttempts,0);return{totalWithFallback:e.length,avgFallbackAttempts:e.length>0?n/e.length:0,fallbackSuccessRate:e.length>0?t.length/e.length:0}}getCostStats(){return{totalCost:this.totalCost,costByModel:{...this.costByModel},totalTasks:this.totalTasks,avgCostPerTask:this.totalTasks>0?this.totalCost/this.totalTasks:0,dailyCost:this.dailyCost,lastReset:this.lastCostReset}}getOutcomes(){return this.outcomes}getConfig(){return this.routingConfig}updateConfidenceThresholds(e){Object.assign(this.routingConfig.confidence,e),Se(this.routingConfig),this.routingConfig.verbose&&console.log("[QueenRouter] Updated confidence thresholds:",e)}reset(){this.totalCost=0,this.costByModel={haiku:0,sonnet:0,opus:0},this.totalTasks=0,this.dailyCost=0,this.lastCostReset=new Date,this.outcomes=[],this.tinyDancer.reset?.()}buildFallbackChain(e){let t=[];if(!this.routingConfig.fallback.enabled)return t;let n=e,i=0;for(;n&&i<this.routingConfig.fallback.maxAttempts;){let r=At(n,this.routingConfig);if(r)t.push(r),n=r;else break;i++}return t}buildQueenReasoning(e,t,n,i){let r=[];return r.push(e.reasoning),r.push(`Assigned to ${t.toUpperCase()} tier.`),n.length>0&&r.push(`Fallback chain: ${n.map(s=>s.toUpperCase()).join(" \u2192 ")}.`),this.enableCostTracking&&i>0&&r.push(`Estimated cost: $${i.toFixed(4)}.`),r.join(" ")}checkDailyCostReset(){let e=new Date,t=this.lastCostReset;(e.getUTCDate()!==t.getUTCDate()||e.getUTCMonth()!==t.getUTCMonth()||e.getUTCFullYear()!==t.getUTCFullYear())&&(this.dailyCost=0,this.lastCostReset=e,this.routingConfig.verbose&&console.log("[QueenRouter] Reset daily cost tracking"))}checkCostLimits(e){if(!this.routingConfig.costOptimization.enabled)return;let{dailyCostLimit:t,costAlertThreshold:n}=this.routingConfig.costOptimization;if(t>0){let i=this.dailyCost+e,r=i/t;i>t?console.warn(`[QueenRouter] COST LIMIT EXCEEDED: Daily cost $${i.toFixed(2)} exceeds limit of $${t.toFixed(2)}`):r>=n&&console.warn(`[QueenRouter] Cost alert: ${(r*100).toFixed(0)}% of daily limit ($${i.toFixed(2)} / $${t.toFixed(2)})`)}}mergeRoutingConfig(e){if(!e)return structuredClone(D);let t=structuredClone(D);return e.confidence&&(t.confidence={...t.confidence,...e.confidence}),e.tierMapping&&(t.tierMapping={...t.tierMapping,...e.tierMapping}),e.costOptimization&&(t.costOptimization={...t.costOptimization,...e.costOptimization,costPerMillionTokens:e.costOptimization.costPerMillionTokens?{...t.costOptimization.costPerMillionTokens,...e.costOptimization.costPerMillionTokens}:t.costOptimization.costPerMillionTokens}),e.fallback&&(t.fallback={...t.fallback,...e.fallback,chain:e.fallback.chain?{...t.fallback.chain,...e.fallback.chain}:t.fallback.chain}),e.verbose!==void 0&&(t.verbose=e.verbose),t}};k();var wt=20,xe=class{db=null;initialized=!1;initialize(e){if(!this.initialized){this.db=e;try{this.db.exec(`
121
+ `).run(new Date(n-s).toISOString());return{historyDeleted:o.changes,snapshotsDeleted:c.changes,alertsDeleted:l.changes}}ensureInitialized(){if(!this.initialized)throw new Error("MinCutPersistence not initialized. Call initialize() first.")}rowToSnapshot(e){return{timestamp:new Date(e.timestamp),vertices:w(e.vertices_json),edges:w(e.edges_json),stats:{vertexCount:e.vertex_count,edgeCount:e.edge_count,totalWeight:e.total_weight,averageDegree:e.edge_count>0&&e.vertex_count>0?e.edge_count*2/e.vertex_count:0,density:e.vertex_count>1?e.edge_count/(e.vertex_count*(e.vertex_count-1)/2):0,isConnected:e.is_connected===1,componentCount:e.component_count}}}rowToAlert(e){return{id:e.id,severity:e.severity,message:e.message,minCutValue:e.mincut_value,threshold:e.threshold,affectedVertices:e.affected_vertices_json?w(e.affected_vertices_json):[],remediations:e.remediations_json?w(e.remediations_json):[],acknowledged:e.acknowledged===1,timestamp:new Date(e.timestamp)}}};function ft(a){return new Te(a)}var gn={...ot,autoUpdateFromEvents:!0,persistData:!0,snapshotIntervalMs:6e4,includeInQueenHealth:!0,minHealthIssueSeverity:"medium"},ve=class{constructor(e,t,n={}){this.eventBus=e;this.agentCoordinator=t;this.config={...gn,...n},this.graph=n.sharedGraph??at(),this.monitor=ct(this.graph,this.config,this.eventBus),this.persistence=ft()}eventBus;agentCoordinator;config;graph;monitor;persistence;eventSubscriptions=[];snapshotTimer=null;initialized=!1;async initialize(){this.initialized||(this.config.persistData&&await this.persistence.initialize(),await this.buildGraphFromAgents(),this.config.autoUpdateFromEvents&&this.subscribeToEvents(),this.monitor.start(),this.config.persistData&&this.startSnapshotTimer(),this.initialized=!0)}async dispose(){this.monitor.stop(),this.snapshotTimer&&(clearInterval(this.snapshotTimer),this.snapshotTimer=null);for(let e of this.eventSubscriptions)e();if(this.eventSubscriptions=[],this.config.persistData)try{await this.saveSnapshot()}catch{}this.initialized=!1}async buildGraphFromAgents(){this.config.sharedGraph||this.graph.clear();let e=this.agentCoordinator.listAgents();for(let t of C)this.graph.addVertex({id:`domain:${t}`,type:"domain",domain:t,weight:2,createdAt:new Date});for(let t of e)this.addAgentVertex(t);this.buildCoordinationEdges(e)}addAgentVertex(e){let t=e,n={id:`agent:${e.id}`,type:"agent",domain:e.domain,capabilities:t.capabilities,weight:1,createdAt:e.startedAt??new Date,metadata:{status:e.status,taskCount:t.taskCount??0,health:t.health??1}};if(this.graph.addVertex(n),e.domain){let i=`domain:${e.domain}`;this.graph.hasVertex(i)&&this.graph.addEdge({source:`agent:${e.id}`,target:i,weight:1,type:"coordination",bidirectional:!0})}}buildCoordinationEdges(e){let t=new Map;for(let i of e)if(i.domain){let r=t.get(i.domain)||[];r.push(i),t.set(i.domain,r)}for(let[i,r]of t)for(let s=0;s<r.length;s++)for(let o=s+1;o<r.length;o++)this.graph.addEdge({source:`agent:${r[s].id}`,target:`agent:${r[o].id}`,weight:.5,type:"communication",bidirectional:!0});let n=[["test-generation","test-execution"],["test-execution","coverage-analysis"],["coverage-analysis","quality-assessment"],["quality-assessment","defect-intelligence"],["requirements-validation","test-generation"],["code-intelligence","test-generation"],["security-compliance","quality-assessment"],["contract-testing","test-execution"],["visual-accessibility","quality-assessment"],["chaos-resilience","test-execution"],["learning-optimization","defect-intelligence"]];for(let[i,r]of n){let s=`domain:${i}`,o=`domain:${r}`;this.graph.hasVertex(s)&&this.graph.hasVertex(o)&&this.graph.addEdge({source:s,target:o,weight:1.5,type:"workflow",bidirectional:!1})}}subscribeToEvents(){let e=async l=>{let{agentId:u,domain:d,type:g,capabilities:p}=l.payload;this.addAgentVertex({id:u,name:`${d}-${g}`,domain:d,type:g,status:"running",startedAt:new Date,capabilities:p,health:1,taskCount:0}),this.config.persistData&&await this.persistence.recordHistory({minCutValue:this.monitor.getMinCutValue(),vertexCount:this.graph.vertexCount,edgeCount:this.graph.edgeCount})},t=async l=>{let{agentId:u}=l.payload;this.graph.removeVertex(`agent:${u}`),this.monitor.checkHealth().status==="critical"&&await this.reportHealthIssue({severity:"high",message:`Agent ${u} termination caused critical MinCut degradation`,timestamp:new Date})},n=async l=>{let{agentId:u,status:d}=l.payload,g=`agent:${u}`,p=this.graph.getVertex(g);p&&this.graph.addVertex({...p,metadata:{...p.metadata,status:d}})},i=async l=>{let{fromAgent:u,toAgent:d}=l.payload,g=`agent:${u}`,p=`agent:${d}`;if(this.graph.hasVertex(g)&&this.graph.hasVertex(p)){let f=this.graph.getEdge(g,p);f?this.graph.addEdge({...f,weight:Math.min(f.weight+.1,3),lastActivity:new Date,messageCount:(f.messageCount??0)+1}):this.graph.addEdge({source:g,target:p,weight:.5,type:"communication",bidirectional:!0,lastActivity:new Date,messageCount:1})}},r=this.eventBus.subscribe("QueenAgentSpawned",e),s=this.eventBus.subscribe("QueenAgentTerminated",t),o=this.eventBus.subscribe("QueenAgentStatusChanged",n),c=this.eventBus.subscribe("QueenTaskCoordination",i);this.eventSubscriptions.push(()=>r.unsubscribe(),()=>s.unsubscribe(),()=>o.unsubscribe(),()=>c.unsubscribe())}getMinCutHealth(){return this.monitor.getHealth()}isEmptyTopology(){return this.graph.getVerticesByType("agent").length===0}getHealthIssuesFromMinCut(){if(this.isEmptyTopology())return[];let e=this.monitor.getActiveAlerts(),t=[];for(let i of e){let r=this.mapSeverity(i.severity);this.severityValue(r)>=this.severityValue(this.config.minHealthIssueSeverity)&&t.push({severity:r,message:`MinCut: ${i.message}`,timestamp:i.timestamp})}let n=this.monitor.getWeakVertices();for(let i of n.slice(0,3))i.riskScore>.7&&t.push({severity:"high",message:`Weak agent topology: ${i.reason} (risk: ${(i.riskScore*100).toFixed(0)}%)`,timestamp:new Date,domain:i.vertex.domain});return t}extendQueenHealth(e){if(!this.config.includeInQueenHealth)return e;let t=this.getMinCutHealth(),n=this.getHealthIssuesFromMinCut(),i=e.status;return t.status==="critical"&&i==="healthy"&&(i="degraded"),{...e,status:i,issues:[...e.issues,...n],minCut:t}}extendQueenMetrics(e){let t=this.monitor.getHealth(),n=this.graph.getStats();return{...e,minCutValue:t.minCutValue,weakVertexCount:t.weakVertexCount,topologyDensity:n.density}}async saveSnapshot(){if(!this.config.persistData)return;let e=this.graph.snapshot();await this.persistence.saveSnapshot(e)}startSnapshotTimer(){this.snapshotTimer=setInterval(async()=>{this.isEmptyTopology()||(await this.saveSnapshot(),await this.persistence.recordHistory({minCutValue:this.monitor.getMinCutValue(),vertexCount:this.graph.vertexCount,edgeCount:this.graph.edgeCount}))},this.config.snapshotIntervalMs)}getGraph(){return this.graph}getMonitor(){return this.monitor}getPersistence(){return this.persistence}getMinCutValue(){return this.monitor.getMinCutValue()}getWeakVertices(){return this.monitor.getWeakVertices()}isTopologyCritical(){return this.monitor.isCritical()}addVertex(e){this.graph.addVertex(e)}addEdge(e){this.graph.addEdge(e)}removeVertex(e){return this.graph.removeVertex(e)}async refreshGraph(){await this.buildGraphFromAgents()}async reportHealthIssue(e){await this.eventBus.publish({id:v(),type:"MinCutHealthIssue",source:"mincut-bridge",timestamp:new Date,payload:{issue:e}})}mapSeverity(e){return e}severityValue(e){return{critical:5,high:4,medium:3,low:2,info:1}[e]}};function yt(a,e,t){return new ve(a,e,t)}be();import{performance as Mt}from"perf_hooks";var xn={multiModel:.8,humanReview:.2,security:.85,escalation:.6},En={trivial:["booster","haiku"],simple:["haiku"],moderate:["sonnet"],complex:["sonnet","opus"],critical:["opus"]},wn={enabled:!0,preferCheaperModels:!0,costPerMillionTokens:{haiku:{input:.25,output:1.25},sonnet:{input:3,output:15},opus:{input:15,output:75}},dailyCostLimit:0,costAlertThreshold:.8},Mn={enabled:!0,maxAttempts:2,retryDelayMs:1e3,chain:{booster:"haiku",haiku:"sonnet",sonnet:"opus",opus:null}},D={confidence:xn,tierMapping:En,costOptimization:wn,fallback:Mn,verbose:!1,enableEMACalibration:!0,enableAutoEscalation:!0,enableNeuralRouting:!1};function At(a=D){let e=structuredClone(a);return process.env.ROUTING_CONFIDENCE_MULTI_MODEL&&(e.confidence.multiModel=parseFloat(process.env.ROUTING_CONFIDENCE_MULTI_MODEL)),process.env.ROUTING_CONFIDENCE_HUMAN_REVIEW&&(e.confidence.humanReview=parseFloat(process.env.ROUTING_CONFIDENCE_HUMAN_REVIEW)),process.env.ROUTING_CONFIDENCE_SECURITY&&(e.confidence.security=parseFloat(process.env.ROUTING_CONFIDENCE_SECURITY)),process.env.ROUTING_CONFIDENCE_ESCALATION&&(e.confidence.escalation=parseFloat(process.env.ROUTING_CONFIDENCE_ESCALATION)),process.env.ROUTING_COST_DAILY_LIMIT&&(e.costOptimization.dailyCostLimit=parseFloat(process.env.ROUTING_COST_DAILY_LIMIT)),process.env.ROUTING_COST_PREFER_CHEAPER&&(e.costOptimization.preferCheaperModels=process.env.ROUTING_COST_PREFER_CHEAPER.toLowerCase()==="true"),process.env.ROUTING_FALLBACK_ENABLED&&(e.fallback.enabled=process.env.ROUTING_FALLBACK_ENABLED.toLowerCase()==="true"),process.env.ROUTING_FALLBACK_MAX_ATTEMPTS&&(e.fallback.maxAttempts=parseInt(process.env.ROUTING_FALLBACK_MAX_ATTEMPTS,10)),process.env.ROUTING_VERBOSE&&(e.verbose=process.env.ROUTING_VERBOSE.toLowerCase()==="true"),e}function xt(a,e,t=D){if(e/100<=.2)return t.tierMapping.trivial;switch(a){case"simple":return t.tierMapping.simple;case"moderate":return t.tierMapping.moderate;case"complex":return t.tierMapping.complex;case"critical":return t.tierMapping.critical}}function Et(a,e=D){return e.fallback.enabled?e.fallback.chain[a]??null:null}function ke(a){switch(a){case"booster":case"haiku":return"haiku";case"sonnet":return"sonnet";case"opus":return"opus"}}function wt(a,e,t,n=D){let i=n.costOptimization.costPerMillionTokens[a],r=e/1e6*i.input,s=t/1e6*i.output;return r+s}function Se(a){let{confidence:e}=a;if(e.multiModel<0||e.multiModel>1)throw new Error("multiModel confidence must be between 0 and 1");if(e.humanReview<0||e.humanReview>1)throw new Error("humanReview confidence must be between 0 and 1");if(e.security<0||e.security>1)throw new Error("security confidence must be between 0 and 1");if(e.escalation<0||e.escalation>1)throw new Error("escalation confidence must be between 0 and 1");if(a.costOptimization.dailyCostLimit<0)throw new Error("dailyCostLimit must be non-negative");if(a.costOptimization.costAlertThreshold<0||a.costOptimization.costAlertThreshold>1)throw new Error("costAlertThreshold must be between 0 and 1");if(a.fallback.maxAttempts<0)throw new Error("maxAttempts must be non-negative");if(a.fallback.retryDelayMs<0)throw new Error("retryDelayMs must be non-negative")}var V=class{tinyDancer;routingConfig;enableCostTracking;avgInputTokens;avgOutputTokens;totalCost=0;costByModel={haiku:0,sonnet:0,opus:0};totalTasks=0;dailyCost=0;lastCostReset=new Date;outcomes=[];maxOutcomes=1e3;constructor(e={}){this.tinyDancer=Dt(e.tinyDancer);let t=this.mergeRoutingConfig(e.routing);this.routingConfig=At(t),Se(this.routingConfig),this.enableCostTracking=e.enableCostTracking??!0,this.avgInputTokens=e.avgInputTokens??2e3,this.avgOutputTokens=e.avgOutputTokens??500}async route(e){let t=Mt.now();this.checkDailyCostReset();let n=await this.tinyDancer.route(e),i=void 0,s=xt(n.complexity,n.classification.score,this.routingConfig)[0],o=ke(s),c=this.buildFallbackChain(s),l=this.enableCostTracking?wt(o,this.avgInputTokens,this.avgOutputTokens,this.routingConfig):0;this.checkCostLimits(l);let u=this.buildQueenReasoning(n,s,c,l),d=Mt.now()-t,g={tier:s,model:o,complexity:n.complexity,confidence:n.confidence,triggerMultiModel:n.triggerMultiModel,triggerHumanReview:n.triggerHumanReview,fallbackTiers:c,estimatedCost:l,reasoning:u,latencyMs:d,tinyDancerResult:n,advisorResult:i,timestamp:new Date};return this.enableCostTracking&&(this.totalCost+=l,this.costByModel[o]+=l,this.dailyCost+=l),this.totalTasks++,this.routingConfig.verbose&&console.log(`[QueenRouter] Route: ${s} (${o}) complexity=${n.complexity}, confidence=${(n.confidence*100).toFixed(1)}%, cost=$${l.toFixed(4)}`),g}recordOutcome(e,t,n,i,r=i?1:0,s=0,o=0,c){let l={task:e,decision:t,usedTier:n,success:i,qualityScore:r,durationMs:s,fallbackAttempts:o,error:c,timestamp:new Date};this.outcomes.push(l),this.outcomes.length>this.maxOutcomes&&this.outcomes.shift(),this.tinyDancer.recordOutcome?.(e,t.tinyDancerResult,i,r,ke(n),s),this.routingConfig.verbose&&console.log(`[QueenRouter] Recorded outcome: tier=${n}, success=${i}, quality=${(r*100).toFixed(0)}%, fallbacks=${o}`)}getSuccessRateByTier(){let e={booster:{success:0,total:0},haiku:{success:0,total:0},sonnet:{success:0,total:0},opus:{success:0,total:0}};for(let t of this.outcomes){let n=t.usedTier;e[n].total++,t.success&&e[n].success++}return{booster:e.booster.total>0?e.booster.success/e.booster.total:0,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}}getFallbackStats(){let e=this.outcomes.filter(i=>i.fallbackAttempts>0),t=e.filter(i=>i.success),n=e.reduce((i,r)=>i+r.fallbackAttempts,0);return{totalWithFallback:e.length,avgFallbackAttempts:e.length>0?n/e.length:0,fallbackSuccessRate:e.length>0?t.length/e.length:0}}getCostStats(){return{totalCost:this.totalCost,costByModel:{...this.costByModel},totalTasks:this.totalTasks,avgCostPerTask:this.totalTasks>0?this.totalCost/this.totalTasks:0,dailyCost:this.dailyCost,lastReset:this.lastCostReset}}getOutcomes(){return this.outcomes}getConfig(){return this.routingConfig}updateConfidenceThresholds(e){Object.assign(this.routingConfig.confidence,e),Se(this.routingConfig),this.routingConfig.verbose&&console.log("[QueenRouter] Updated confidence thresholds:",e)}reset(){this.totalCost=0,this.costByModel={haiku:0,sonnet:0,opus:0},this.totalTasks=0,this.dailyCost=0,this.lastCostReset=new Date,this.outcomes=[],this.tinyDancer.reset?.()}buildFallbackChain(e){let t=[];if(!this.routingConfig.fallback.enabled)return t;let n=e,i=0;for(;n&&i<this.routingConfig.fallback.maxAttempts;){let r=Et(n,this.routingConfig);if(r)t.push(r),n=r;else break;i++}return t}buildQueenReasoning(e,t,n,i){let r=[];return r.push(e.reasoning),r.push(`Assigned to ${t.toUpperCase()} tier.`),n.length>0&&r.push(`Fallback chain: ${n.map(s=>s.toUpperCase()).join(" \u2192 ")}.`),this.enableCostTracking&&i>0&&r.push(`Estimated cost: $${i.toFixed(4)}.`),r.join(" ")}checkDailyCostReset(){let e=new Date,t=this.lastCostReset;(e.getUTCDate()!==t.getUTCDate()||e.getUTCMonth()!==t.getUTCMonth()||e.getUTCFullYear()!==t.getUTCFullYear())&&(this.dailyCost=0,this.lastCostReset=e,this.routingConfig.verbose&&console.log("[QueenRouter] Reset daily cost tracking"))}checkCostLimits(e){if(!this.routingConfig.costOptimization.enabled)return;let{dailyCostLimit:t,costAlertThreshold:n}=this.routingConfig.costOptimization;if(t>0){let i=this.dailyCost+e,r=i/t;i>t?console.warn(`[QueenRouter] COST LIMIT EXCEEDED: Daily cost $${i.toFixed(2)} exceeds limit of $${t.toFixed(2)}`):r>=n&&console.warn(`[QueenRouter] Cost alert: ${(r*100).toFixed(0)}% of daily limit ($${i.toFixed(2)} / $${t.toFixed(2)})`)}}mergeRoutingConfig(e){if(!e)return structuredClone(D);let t=structuredClone(D);return e.confidence&&(t.confidence={...t.confidence,...e.confidence}),e.tierMapping&&(t.tierMapping={...t.tierMapping,...e.tierMapping}),e.costOptimization&&(t.costOptimization={...t.costOptimization,...e.costOptimization,costPerMillionTokens:e.costOptimization.costPerMillionTokens?{...t.costOptimization.costPerMillionTokens,...e.costOptimization.costPerMillionTokens}:t.costOptimization.costPerMillionTokens}),e.fallback&&(t.fallback={...t.fallback,...e.fallback,chain:e.fallback.chain?{...t.fallback.chain,...e.fallback.chain}:t.fallback.chain}),e.verbose!==void 0&&(t.verbose=e.verbose),t}};k();var It=20,Ae=class{db=null;initialized=!1;initialize(e){if(!this.initialized){this.db=e;try{this.db.exec(`
122
122
  CREATE TABLE IF NOT EXISTS qe_agent_co_execution (
123
123
  id INTEGER PRIMARY KEY AUTOINCREMENT,
124
124
  agent_a TEXT NOT NULL,
@@ -145,7 +145,7 @@ import{b as fe}from"./chunk-FZOBD67M.js";import{a as gt}from"./chunk-TVYY3OCX.js
145
145
  FROM qe_agent_co_execution
146
146
  WHERE agent_a = ? AND agent_b = ?
147
147
  GROUP BY agent_a, agent_b
148
- `).get(n,i);if(!r)return null;let s=r.total_executions>0?r.success_count/r.total_executions:0,o=Math.min(1,r.success_count/wt);return{agentA:r.agent_a,agentB:r.agent_b,totalExecutions:r.total_executions,successCount:r.success_count,successRate:s,behavioralConfidence:o}}catch(r){return console.debug(`[CoExecutionRepository] Stats error: ${h(r)}`),null}}getCoExecutionPartners(e,t=10){if(!this.db)return[];try{return this.db.prepare(`
148
+ `).get(n,i);if(!r)return null;let s=r.total_executions>0?r.success_count/r.total_executions:0,o=Math.min(1,r.success_count/It);return{agentA:r.agent_a,agentB:r.agent_b,totalExecutions:r.total_executions,successCount:r.success_count,successRate:s,behavioralConfidence:o}}catch(r){return console.debug(`[CoExecutionRepository] Stats error: ${h(r)}`),null}}getCoExecutionPartners(e,t=10){if(!this.db)return[];try{return this.db.prepare(`
149
149
  SELECT
150
150
  agent_a,
151
151
  agent_b,
@@ -156,15 +156,15 @@ import{b as fe}from"./chunk-FZOBD67M.js";import{a as gt}from"./chunk-TVYY3OCX.js
156
156
  GROUP BY agent_a, agent_b
157
157
  ORDER BY success_count DESC
158
158
  LIMIT ?
159
- `).all(e,e,t).map(i=>{let r=i.total_executions>0?i.success_count/i.total_executions:0;return{agentA:i.agent_a,agentB:i.agent_b,totalExecutions:i.total_executions,successCount:i.success_count,successRate:r,behavioralConfidence:Math.min(1,i.success_count/wt)}})}catch(n){return console.debug(`[CoExecutionRepository] Partners error: ${h(n)}`),[]}}recordSwarmCoExecution(e,t,n,i){if(!(!this.db||e.length<2))try{let r=this.db.prepare(`
159
+ `).all(e,e,t).map(i=>{let r=i.total_executions>0?i.success_count/i.total_executions:0;return{agentA:i.agent_a,agentB:i.agent_b,totalExecutions:i.total_executions,successCount:i.success_count,successRate:r,behavioralConfidence:Math.min(1,i.success_count/It)}})}catch(n){return console.debug(`[CoExecutionRepository] Partners error: ${h(n)}`),[]}}recordSwarmCoExecution(e,t,n,i){if(!(!this.db||e.length<2))try{let r=this.db.prepare(`
160
160
  INSERT INTO qe_agent_co_execution (agent_a, agent_b, domain, success, task_description)
161
161
  VALUES (?, ?, ?, ?, ?)
162
- `);this.db.transaction(()=>{for(let o=0;o<e.length;o++)for(let c=o+1;c<e.length;c++){let[l,u]=[e[o],e[c]].sort();r.run(l,u,t,n?1:0,i?.slice(0,500)||null)}})()}catch(r){console.debug(`[CoExecutionRepository] Swarm record error: ${h(r)}`)}}},De=null;function It(){return De||(De=new xe),De}import{readFileSync as wn,existsSync as In,readdirSync as Rn}from"fs";import{join as _n,basename as Pn}from"path";function Rt(a){let e=a.split(`
162
+ `);this.db.transaction(()=>{for(let o=0;o<e.length;o++)for(let c=o+1;c<e.length;c++){let[l,u]=[e[o],e[c]].sort();r.run(l,u,t,n?1:0,i?.slice(0,500)||null)}})()}catch(r){console.debug(`[CoExecutionRepository] Swarm record error: ${h(r)}`)}}},De=null;function Rt(){return De||(De=new Ae),De}import{readFileSync as In,existsSync as Rn,readdirSync as _n}from"fs";import{join as Pn,basename as Fn}from"path";function _t(a){let e=a.split(`
163
163
  `);if(e.length<2||e[0].trim()!=="---")return null;for(let t=1;t<e.length;t++)if(e[t].trim()==="---")return e.slice(1,t).join(`
164
- `);return null}function _(a){let e=a.trim();return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function Fn(a){let e=Rt(a);if(!e)return null;let t=e.split(`
165
- `),n=-1;for(let l=0;l<t.length;l++)if(/^dependencies:\s*$/.test(t[l])){n=l+1;break}if(n===-1)return null;let i=[];for(let l=n;l<t.length;l++){let u=t[l];if(u.trim()!==""){if(u.length>0&&u[0]!==" "&&u[0]!==" ")break;i.push(u)}}if(i.length===0)return null;let r={},s={section:"none",item:{},inList:!1},o=()=>{s.item.name&&(r.agents||(r.agents=[]),r.agents.push({name:s.item.name,type:s.item.type||"hard",reason:s.item.reason||""}),s.item={})},c=()=>{s.item.name&&(r.mcpServers||(r.mcpServers=[]),r.mcpServers.push({name:s.item.name,required:s.item.required==="true"}),s.item={})};for(let l of i){let u=l.trim();if(u==="")continue;let d=u.match(/^(agents|mcp_servers|models):\s*$/);if(d){s.section==="agents"&&s.inList&&o(),s.section==="mcp_servers"&&s.inList&&c(),s.inList=!1,s.section=d[1];continue}if(s.section==="agents"||s.section==="mcp_servers"){let g=u.match(/^-\s+(\w+):\s*(.*)$/);if(g){s.inList&&(s.section==="agents"?o():c()),s.inList=!0,s.item={[g[1]]:_(g[2])};continue}if(s.inList){let p=u.match(/^(\w+):\s*(.*)$/);if(p){s.item[p[1]]=_(p[2]);continue}}}if(s.section==="models"){r.models||(r.models={});let g=u.match(/^(\w+):\s*(.*)$/);if(g){let f=_(g[2]);if(g[1]==="minimum")r.models={...r.models,minimum:f};else if(g[1]==="capabilities"){let q=f.match(/^\[(.+)]$/);q&&(r.models={...r.models,capabilities:q[1].split(",").map(sn=>_(sn.trim()))})}}let p=u.match(/^-\s+(.+)$/);if(p&&r.models){let f=r.models.capabilities||[];r.models={...r.models,capabilities:[...f,_(p[1])]}}}}return s.section==="agents"&&s.inList&&o(),s.section==="mcp_servers"&&s.inList&&c(),!r.agents&&!r.mcpServers&&!r.models?null:r}function Hn(a){let e=Rt(a);if(!e)return null;for(let t of e.split(`
166
- `)){let n=t.match(/^name:\s*(.+)$/);if(n)return _(n[1])}return null}function _t(a){let e=new Map,t=[];if(!In(a))return t.push(`Agents directory not found: ${a}`),{nodes:e,spawnOrder:[],cycles:[],warnings:t};let n=Rn(a).filter(s=>s.startsWith("qe-")&&s.endsWith(".md"));for(let s of n){let o;try{o=wn(_n(a,s),"utf-8")}catch{t.push(`Failed to read agent file: ${s}`);continue}let c=Hn(o)||Pn(s,".md"),l=Fn(o),u=[],d=[],g=[];if(l?.agents)for(let p of l.agents)p.type==="hard"?u.push(p.name):p.type==="soft"?d.push(p.name):p.type==="peer"&&g.push(p.name);e.set(c,{agentName:c,hardDeps:u,softDeps:d,peerDeps:g,dependencies:l||{}})}let i=new Set(e.keys());for(let[s,o]of e)for(let c of o.hardDeps)i.has(c)||t.push(`Agent "${s}" declares hard dependency on "${c}" which is not in the agent directory`);let r=On(e);for(let s of r)t.push(`Dependency cycle detected: ${s.join(" -> ")}`);return{nodes:e,spawnOrder:Nn(e,r),cycles:r,warnings:t}}function On(a){let e=[],t=new Set,n=new Set,i=[];function r(s){t.add(s),n.add(s),i.push(s);let o=a.get(s);if(o){for(let c of o.hardDeps)if(!t.has(c)&&a.has(c))r(c);else if(n.has(c)){let l=i.indexOf(c);l!==-1&&e.push([...i.slice(l),c])}}i.pop(),n.delete(s)}for(let s of a.keys())t.has(s)||r(s);return e}function Nn(a,e){let t=new Set(e.flat()),n=[],i=new Set,r=new Set;function s(o){if(i.has(o)||t.has(o)||r.has(o))return;r.add(o);let c=a.get(o);if(c)for(let l of c.hardDeps)a.has(l)&&s(l);r.delete(o),i.add(o),n.push(o)}for(let o of a.keys())s(o);for(let o of t)n.includes(o)||n.push(o);return n}function Pt(a,e){let t=new Set(a),n=[],i=[];for(let c of a){let l=e.nodes.get(c);if(!l)continue;let u=l.hardDeps.filter(d=>!t.has(d));u.length>0&&(i.push({agent:c,missing:u}),n.push(`Advisory: "${c}" has unsatisfied hard dependencies: ${u.join(", ")}. Proceeding anyway.`))}let r=[],s=new Set,o=new Set(a);for(;o.size>0;){let c=[];for(let l of o){let u=e.nodes.get(l);if(!u){c.push(l);continue}u.hardDeps.filter(g=>t.has(g)).every(g=>s.has(g))&&c.push(l)}if(c.length===0){n.push(`Could not resolve dependency ordering for: ${[...o].join(", ")}. Placing in final phase.`),r.push([...o]);break}r.push(c);for(let l of c)s.add(l),o.delete(l);o=new Set([...o])}return{phases:r,unsatisfiedHardDeps:i,warnings:n}}var Ae={defaultTtlMs:0,cleanupIntervalMs:6e4,maxMailboxSize:1e3};var O=class{mailboxes=new Map;messageHandlers=new Map;broadcastHandlers=new Map;domainAgents=new Map;cognitiveRouter=null;cognitiveRouterInitialized=!1;compressedMessages=new Map;createMailbox(e,t){let n=this.mailboxes.get(e);if(n)return this.toSnapshot(n);let i={agentId:e,domain:t,messages:[],unreadCount:0,lastRead:Date.now()};this.mailboxes.set(e,i);let r=this.domainAgents.get(t);return r||(r=new Set,this.domainAgents.set(t,r)),r.add(e),this.toSnapshot(i)}getMailbox(e){let t=this.mailboxes.get(e);if(t)return this.toSnapshot(t)}deleteMailbox(e){let t=this.mailboxes.get(e);if(!t)return!1;let n=this.domainAgents.get(t.domain);n&&(n.delete(e),n.size===0&&this.domainAgents.delete(t.domain));for(let i of t.messages)this.compressedMessages.delete(i.id);return this.messageHandlers.delete(e),this.mailboxes.delete(e),!0}send(e){if(e.to==="broadcast"){this.broadcast(e.domain,e);return}let t=this.mailboxes.get(e.to);if(!t)throw new Error(`No mailbox found for agent '${e.to}'. Create a mailbox first with createMailbox().`);let n=this.compressViaCognitive(e);t.messages.push(n),t.unreadCount++;let i=this.messageHandlers.get(e.to);if(i)for(let r of i)try{r(e)}catch{}}broadcast(e,t){let n=this.domainAgents.get(e);if(!n)return;for(let r of n){if(r===t.from)continue;let s=this.mailboxes.get(r);if(s){s.messages.push(t),s.unreadCount++;let o=this.messageHandlers.get(r);if(o)for(let c of o)try{c(t)}catch{}}}let i=this.broadcastHandlers.get(e);if(i)for(let r of i)try{r(e,t)}catch{}}receive(e,t){let n=this.mailboxes.get(e);if(!n||n.unreadCount===0)return[];let i=Date.now(),r=n.messages.length-n.unreadCount,s=n.messages.slice(r);return s=s.filter(o=>!this.isExpired(o,i)),t?.type&&(s=s.filter(o=>o.type===t.type)),t?.since!==void 0&&(s=s.filter(o=>o.timestamp>=t.since)),t?.limit!==void 0&&t.limit>0&&(s=s.slice(0,t.limit)),n.unreadCount=0,n.lastRead=i,this.decompressMessages(s)}peek(e){let t=this.mailboxes.get(e);if(!t)return 0;let n=Date.now(),i=t.messages.length-t.unreadCount,r=0;for(let s=i;s<t.messages.length;s++)this.isExpired(t.messages[s],n)||r++;return r}cleanup(e){let t=Date.now(),n=t-e,i=0;for(let r of this.mailboxes.values()){let s=r.messages.length,o=r.messages.length-r.unreadCount;r.messages=r.messages.filter((l,u)=>l.timestamp<n?(this.compressedMessages.delete(l.id),!1):this.isExpired(l,t)?(this.compressedMessages.delete(l.id),!1):!0);let c=s-r.messages.length;i+=c,c>0&&(r.unreadCount=r.messages.filter(l=>l.timestamp>r.lastRead).length)}return i}onMessage(e,t){let n=this.messageHandlers.get(e);return n||(n=[],this.messageHandlers.set(e,n)),n.push(t),()=>{let i=this.messageHandlers.get(e);if(i){let r=i.indexOf(t);r>=0&&i.splice(r,1)}}}onBroadcast(e,t){let n=this.broadcastHandlers.get(e);return n||(n=[],this.broadcastHandlers.set(e,n)),n.push(t),()=>{let i=this.broadcastHandlers.get(e);if(i){let r=i.indexOf(t);r>=0&&i.splice(r,1)}}}getAgentsInDomain(e){let t=this.domainAgents.get(e);return t?Array.from(t):[]}getDomains(){return Array.from(this.domainAgents.keys())}get size(){return this.mailboxes.size}clear(){this.mailboxes.clear(),this.messageHandlers.clear(),this.broadcastHandlers.clear(),this.domainAgents.clear(),this.compressedMessages.clear(),this.cognitiveRouter=null,this.cognitiveRouterInitialized=!1}isExpired(e,t){return!e.ttl||e.ttl<=0?!1:t>e.timestamp+e.ttl}toSnapshot(e){return{agentId:e.agentId,domain:e.domain,messages:[...e.messages],unreadCount:e.unreadCount,lastRead:e.lastRead}}ensureCognitiveRouter(){if(this.cognitiveRouterInitialized)return this.cognitiveRouter;if(this.cognitiveRouterInitialized=!0,!pt())return null;try{this.cognitiveRouter=mt()??null}catch{this.cognitiveRouter=null}return this.cognitiveRouter}compressViaCognitive(e){try{let t=this.ensureCognitiveRouter();if(!t)return e;let n=`${e.from}->${e.to}`,i=t.send(n,e.from,e.to,e.payload);return i.compressed&&i.compressedSize<i.originalSize?(this.compressedMessages.set(e.id,i),{...e,payload:i.payload}):e}catch{return e}}decompressMessages(e){let t=this.cognitiveRouter;return!t||this.compressedMessages.size===0?e:e.map(n=>{try{let i=this.compressedMessages.get(n.id);if(!i)return n;let r=t.receive(i);return this.compressedMessages.delete(n.id),{...n,payload:r}}catch{return n}})}getCognitiveRoutingStats(){return this.cognitiveRouter?this.cognitiveRouter.getStats():null}};import{randomUUID as Ft}from"node:crypto";st();import{randomUUID as K}from"node:crypto";var Y=class{spans=new Map;traceIndex=new Map;maxSpans;constructor(e=1e4){this.maxSpans=e}startTrace(e){let t=K(),n=K(),i={traceId:t,spanId:n},r=this.createSpan(i,e);return{context:i,span:r}}startSpan(e){let t=e.parentContext,n=t?.traceId??K(),i=K(),r={traceId:n,spanId:i,parentSpanId:t?.spanId,baggage:t?.baggage},s=this.createSpan(r,e);return{context:r,span:s}}completeSpan(e){let t=this.spans.get(e);t&&(t.endTime=Date.now(),t.status="completed")}failSpan(e,t){let n=this.spans.get(e);n&&(n.endTime=Date.now(),n.status="error",n.errorMessage=t)}getTrace(e){let t=this.traceIndex.get(e);return t?Array.from(t).map(n=>this.spans.get(n)).filter(n=>n!==void 0).sort((n,i)=>n.startTime-i.startTime):[]}getSpan(e){return this.spans.get(e)}getActiveSpans(){return Array.from(this.spans.values()).filter(e=>e.status==="active")}getStats(){let e=new Set,t=new Set;for(let[n,i]of this.traceIndex)Array.from(i).map(s=>this.spans.get(s)).filter(s=>s!==void 0).some(s=>s.status==="active")?e.add(n):t.add(n);return{totalSpans:this.spans.size,activeTraces:e.size,completedTraces:t.size}}purge(e){let t=Date.now()-e,n=0;for(let[i,r]of this.traceIndex){let s=Array.from(r).map(l=>this.spans.get(l)).filter(l=>l!==void 0),o=s.every(l=>l.status!=="active"),c=s.every(l=>(l.endTime??l.startTime)<t);if(o&&c){for(let l of r)this.spans.delete(l),n++;this.traceIndex.delete(i)}}return n}dispose(){this.spans.clear(),this.traceIndex.clear()}createSpan(e,t){this.spans.size>=this.maxSpans&&this.purge(6e4);let n={traceId:e.traceId,spanId:e.spanId,parentSpanId:e.parentSpanId,operationName:t.operationName,agentId:t.agentId,domain:t.domain,startTime:Date.now(),tags:t.tags??{},status:"active"};this.spans.set(e.spanId,n);let i=this.traceIndex.get(e.traceId);return i||(i=new Set,this.traceIndex.set(e.traceId,i)),i.add(e.spanId),n}},Ln="trace:";function Z(a){return`${Ln}${JSON.stringify({traceId:a.traceId,spanId:a.spanId,parentSpanId:a.parentSpanId})}`}function Ee(a){return new Y(a)}var X=class{mailbox;config;teams=new Map;registeredAgents=new Set;agentDomains=new Map;subscriptions=new Map;cleanupTimer=null;initialized=!1;constructor(e,t){this.mailbox=e??new O,this.config={...Ae,...t}}initialize(e){this.initialized||(e&&Object.assign(this.config,e),this.config.cleanupIntervalMs>0&&(this.cleanupTimer=setInterval(()=>{this.performCleanup()},this.config.cleanupIntervalMs)),this.initialized=!0)}shutdown(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null),this.mailbox.clear(),this.teams.clear(),this.registeredAgents.clear(),this.agentDomains.clear(),this.subscriptions.clear(),this.initialized=!1}createTeam(e){if(this.teams.has(e.domain))throw new Error(`Team already exists for domain '${e.domain}'. Use getTeamStatus() to inspect the existing team.`);let t={domain:e.domain,leadAgentId:e.leadAgentId,maxTeammates:e.maxTeammates,teammateIds:[...e.teammateIds],autoAssignEnabled:e.autoAssignEnabled};this.teams.set(e.domain,t),this.registerAgent(e.leadAgentId,e.domain);for(let n of e.teammateIds)this.registerAgent(n,e.domain)}getTeamStatus(e){let t=this.teams.get(e);if(!t)return;let n=[t.leadAgentId,...t.teammateIds],i=n.filter(s=>this.mailbox.peek(s)===0),r=0;for(let s of n)r+=this.mailbox.peek(s);return{domain:t.domain,leadAgentId:t.leadAgentId,teammateIds:[...t.teammateIds],activeAgentCount:n.filter(s=>this.registeredAgents.has(s)).length,idleAgentIds:i,totalUnreadMessages:r}}registerAgent(e,t){if(this.registeredAgents.has(e))return;this.registeredAgents.add(e),this.agentDomains.set(e,t),this.mailbox.createMailbox(e,t);let n=this.teams.get(t);n&&n.autoAssignEnabled&&e!==n.leadAgentId&&!n.teammateIds.includes(e)&&n.teammateIds.length<n.maxTeammates&&n.teammateIds.push(e)}unregisterAgent(e){if(!this.registeredAgents.has(e))return!1;let t=this.agentDomains.get(e);if(t){let n=this.teams.get(t);if(n){let i=n.teammateIds.indexOf(e);i>=0&&n.teammateIds.splice(i,1)}}return this.mailbox.deleteMailbox(e),this.subscriptions.delete(e),this.registeredAgents.delete(e),this.agentDomains.delete(e),!0}sendMessage(e,t,n,i,r){this.validateAgent(e,"sender"),this.validateAgent(t,"recipient");let s=this.agentDomains.get(e),o=r?.traceContext?Z(r.traceContext):r?.correlationId,c={id:Ft(),from:e,to:t,domain:r?.domain??s,type:n,payload:i,timestamp:Date.now(),correlationId:o,replyTo:r?.replyTo,ttl:r?.ttl??(this.config.defaultTtlMs>0?this.config.defaultTtlMs:void 0)};return this.mailbox.send(c),this.notifySubscribers(t,c),c}broadcast(e,t,n,i){let r=i?.from??"__system__";r!=="__system__"&&this.validateAgent(r,"broadcast sender");let s=i?.traceContext?Z(i.traceContext):i?.correlationId,o={id:Ft(),from:r,to:"broadcast",domain:e,type:t,payload:n,timestamp:Date.now(),correlationId:s,ttl:i?.ttl??(this.config.defaultTtlMs>0?this.config.defaultTtlMs:void 0)};this.mailbox.broadcast(e,o);let c=this.mailbox.getAgentsInDomain(e);for(let l of c)l!==r&&this.notifySubscribers(l,o);return o}onMessage(e,t){this.validateAgent(e,"subscription target");let n=this.subscriptions.get(e);return n||(n=[],this.subscriptions.set(e,n)),n.push(t),()=>{let i=this.subscriptions.get(e);if(i){let r=i.indexOf(t);r>=0&&i.splice(r,1)}}}getIdleAgents(e){let t=[],n=e?this.mailbox.getAgentsInDomain(e):Array.from(this.registeredAgents);for(let i of n)this.mailbox.peek(i)===0&&t.push(i);return t}isRegistered(e){return this.registeredAgents.has(e)}getAgentDomain(e){return this.agentDomains.get(e)}getRegisteredAgents(){return Array.from(this.registeredAgents)}getUnreadCount(e){return this.mailbox.peek(e)}receiveMessages(e){return this.mailbox.receive(e)}getMailboxService(){return this.mailbox}validateAgent(e,t){if(!this.registeredAgents.has(e))throw new Error(`Unknown ${t} '${e}'. Register the agent first with registerAgent() or createTeam().`)}notifySubscribers(e,t){let n=this.subscriptions.get(e);if(!(!n||n.length===0))for(let i of n)try{i(t)}catch{}}performCleanup(){let e=this.config.defaultTtlMs>0?this.config.defaultTtlMs*10:this.config.cleanupIntervalMs*60;this.mailbox.cleanup(e)}};function Me(a){return new X(void 0,a)}var Ht={maxActiveTeams:13,defaultTeamSize:3,autoScaleEnabled:!1,scaleUpThreshold:10,scaleDownIdleMs:6e4},J=class a{static SYSTEM_AGENT_ID="__dtm_system__";static SYSTEM_DOMAIN="__system__";adapter;config;teams=new Map;systemAgentRegistered=!1;constructor(e,t){this.adapter=e,this.config={...Ht,...t}}createDomainTeam(e,t,n){if(this.teams.has(e))throw new Error(`Domain team already exists for '${e}'. Use getDomainTeam() to inspect the existing team.`);if(this.teams.size>=this.config.maxActiveTeams)throw new Error(`Maximum active teams (${this.config.maxActiveTeams}) reached. Remove an existing team before creating a new one.`);let i=n?[...n]:[],r=this.getMaxTeamSize(e);i.length+1>r&&(i.length=r-1);let s=Date.now(),o={domain:e,leadAgentId:t,teammateIds:i,createdAt:s,taskCount:0,completedCount:0,lastActivity:new Map};o.lastActivity.set(t,s);for(let l of i)o.lastActivity.set(l,s);this.teams.set(e,o);let c={domain:e,leadAgentId:t,maxTeammates:r-1,teammateIds:i,autoAssignEnabled:!1};return this.adapter.createTeam(c),this.toSnapshot(o)}removeDomainTeam(e){let t=this.teams.get(e);if(!t)return!1;for(let n of[t.leadAgentId,...t.teammateIds])this.adapter.unregisterAgent(n);return this.teams.delete(e),!0}getDomainTeam(e){let t=this.teams.get(e);return t?this.toSnapshot(t):void 0}addTeammate(e,t){let n=this.teams.get(e);if(!n||t===n.leadAgentId||n.teammateIds.includes(t))return!1;let i=this.getMaxTeamSize(e);return 1+n.teammateIds.length>=i?!1:(n.teammateIds.push(t),n.lastActivity.set(t,Date.now()),this.adapter.registerAgent(t,e),!0)}listDomainTeams(){return Array.from(this.teams.values(),e=>this.toSnapshot(e))}assignTaskToTeam(e,t,n){let i=this.teams.get(e);return i?(this.ensureSystemAgent(),this.adapter.sendMessage(a.SYSTEM_AGENT_ID,i.leadAgentId,"task-assignment",{taskId:t,payload:n},{domain:e}),i.taskCount++,i.lastActivity.set(i.leadAgentId,Date.now()),!0):!1}broadcastToDomain(e,t,n){let i=this.teams.get(e);if(!i)throw new Error(`No domain team found for '${e}'. Create a team first with createDomainTeam().`);this.adapter.broadcast(e,t,n,{from:"__system__"});let r=Date.now();i.lastActivity.set(i.leadAgentId,r);for(let s of i.teammateIds)i.lastActivity.set(s,r)}getTeamHealth(e){let t=this.teams.get(e);if(!t)return;let n=[t.leadAgentId,...t.teammateIds],i=n.length,r=0,s=0,o=0;for(let l of n)if(this.adapter.isRegistered(l)){r++;let u=this.adapter.getUnreadCount(l);o+=u,u===0&&s++}let c=t.taskCount-t.completedCount;return{domain:e,teamSize:i,activeAgents:r,idleAgents:s,pendingMessages:o,tasksPending:c,tasksCompleted:t.completedCount,healthy:r>0&&r===i&&c<this.config.scaleUpThreshold*2}}scaleTeam(e,t){let n=this.teams.get(e);if(!n)throw new Error(`No domain team found for '${e}'. Create a team first with createDomainTeam().`);let i=Math.max(this.getMaxTeamSize(e),t,this.config.maxActiveTeams),r=Math.max(1,Math.min(t,i)),s=1+n.teammateIds.length,o=[],c=[];if(r>s){let l=r-s;for(let u=0;u<l;u++){let d=`${e}-teammate-${Date.now()}-${u}`;n.teammateIds.push(d),n.lastActivity.set(d,Date.now()),this.adapter.registerAgent(d,e),o.push(d)}}else if(r<s){let l=s-r;for(let u=0;u<l;u++){let d=n.teammateIds.pop();d&&(n.lastActivity.delete(d),this.adapter.unregisterAgent(d),c.push(d))}}return{domain:e,previousSize:s,newSize:1+n.teammateIds.length,addedAgents:o,removedAgents:c}}getIdleTeammates(e){if(e){let n=this.teams.get(e);return n?this.getIdleAgentsForTeam(n):[]}let t=[];for(let n of this.teams.values())t.push(...this.getIdleAgentsForTeam(n));return t}rebalance(){let e=[],t=new Set,n=Array.from(this.teams.values(),s=>{let o=this.getTargetTeamSize(s.domain),c=1+s.teammateIds.length,l=this.getIdleAgentsForTeam(s).filter(u=>u!==s.leadAgentId);return{domain:s.domain,team:s,currentSize:c,targetSize:o,idleTeammates:l}}),i=n.filter(s=>s.currentSize>s.targetSize&&s.idleTeammates.length>0).sort((s,o)=>o.currentSize-o.targetSize-(s.currentSize-s.targetSize)),r=n.filter(s=>s.currentSize<s.targetSize).sort((s,o)=>s.currentSize-s.targetSize-(o.currentSize-o.targetSize));for(let s of i)for(let o of r){if(o.currentSize>=o.targetSize)continue;if(s.idleTeammates.length===0)break;if(o.currentSize>=this.getMaxTeamSize(o.domain))continue;let c=s.idleTeammates.shift(),l=s.team.teammateIds.indexOf(c);l>=0&&s.team.teammateIds.splice(l,1),s.team.lastActivity.delete(c),s.currentSize--,this.adapter.unregisterAgent(c),this.adapter.registerAgent(c,o.domain),o.team.teammateIds.push(c),o.team.lastActivity.set(c,Date.now()),o.currentSize++,e.push({agentId:c,fromDomain:s.domain,toDomain:o.domain}),t.add(s.domain),t.add(o.domain)}return{moves:e,teamsAffected:t.size}}dispose(){for(let e of this.teams.values())for(let t of[e.leadAgentId,...e.teammateIds])this.adapter.unregisterAgent(t);this.teams.clear(),this.systemAgentRegistered&&(this.adapter.unregisterAgent(a.SYSTEM_AGENT_ID),this.systemAgentRegistered=!1)}markTaskCompleted(e){let t=this.teams.get(e);return t?(t.completedCount<t.taskCount&&t.completedCount++,!0):!1}ensureSystemAgent(){this.systemAgentRegistered||(this.adapter.registerAgent(a.SYSTEM_AGENT_ID,a.SYSTEM_DOMAIN),this.systemAgentRegistered=!0)}getMaxTeamSize(e){return this.config.domainTeamSizes&&e in this.config.domainTeamSizes?this.config.domainTeamSizes[e]:this.config.defaultTeamSize}getTargetTeamSize(e){return this.getMaxTeamSize(e)}getIdleAgentsForTeam(e){let t=[];for(let n of[e.leadAgentId,...e.teammateIds])this.adapter.isRegistered(n)&&this.adapter.getUnreadCount(n)===0&&t.push(n);return t}toSnapshot(e){return{domain:e.domain,leadAgentId:e.leadAgentId,teammateIds:[...e.teammateIds],createdAt:e.createdAt,taskCount:e.taskCount,completedCount:e.completedCount}}};function we(a,e){return new J(a,e)}k();var te={failureThreshold:3,resetTimeoutMs:6e4,halfOpenSuccessThreshold:2,failureWindowMs:12e4,cascadeEnabled:!1,cascadeTargets:void 0},ee=class extends Error{domain;retryAfterMs;constructor(e,t){let n=t!=null?` (retry after ${t}ms)`:"";super(`Circuit breaker is open for domain '${e}'${n}`),this.name="DomainCircuitOpenError",this.domain=e,this.retryAfterMs=t}},x=class{state="closed";failures=[];totalRequests=0;totalSuccesses=0;totalFailures=0;rejectedCount=0;lastFailureTime;lastSuccessTime;openedAt;halfOpenSuccesses=0;config;stateChangeHandlers=new Set;domain;constructor(e,t){this.domain=e,this.config={...te,...t}}canExecute(){let e=this.getState();return e==="closed"?!0:e!=="open"}async execute(e){if(this.totalRequests++,this.getState()==="open")throw this.rejectedCount++,this.emitEvent({type:"request-rejected",domain:this.domain,timestamp:Date.now(),metadata:{retryAfterMs:this.getTimeUntilTransition()}}),new ee(this.domain,this.getTimeUntilTransition());try{let n=await e();return this.recordSuccess(),n}catch(n){throw this.recordFailure(nt(n)),n}}recordSuccess(){this.totalSuccesses++,this.lastSuccessTime=Date.now(),this.getState()==="half-open"&&(this.halfOpenSuccesses++,console.log(`[DomainCircuitBreaker:${this.domain}] Half-open success ${this.halfOpenSuccesses}/${this.config.halfOpenSuccessThreshold}`),this.halfOpenSuccesses>=this.config.halfOpenSuccessThreshold&&this.transitionTo("closed"))}recordFailure(e){this.totalFailures++,this.lastFailureTime=Date.now(),this.failures.push({timestamp:Date.now(),message:e.message}),this.cleanOldFailures();let t=this.getState();if(t==="half-open"){console.log(`[DomainCircuitBreaker:${this.domain}] Failure in half-open state, re-opening`),this.transitionTo("open");return}t==="closed"&&this.failures.length>=this.config.failureThreshold&&(console.log(`[DomainCircuitBreaker:${this.domain}] Failure threshold reached (${this.failures.length}/${this.config.failureThreshold}), opening circuit`),this.transitionTo("open"))}getState(){return this.state==="open"&&this.openedAt!=null&&Date.now()-this.openedAt>=this.config.resetTimeoutMs&&this.transitionTo("half-open"),this.state}getStats(){let e=this.getState();return{domain:this.domain,state:e,totalRequests:this.totalRequests,successCount:this.totalSuccesses,failureCount:this.totalFailures,rejectedCount:this.rejectedCount,lastFailureTime:this.lastFailureTime,lastSuccessTime:this.lastSuccessTime,openedAt:this.openedAt,timeUntilHalfOpen:e==="open"?this.getTimeUntilTransition():void 0,consecutiveSuccesses:this.halfOpenSuccesses}}reset(){let e=this.state;this.state="closed",this.failures=[],this.halfOpenSuccesses=0,this.openedAt=void 0,e!=="closed"&&(console.log(`[DomainCircuitBreaker:${this.domain}] Manually reset from '${e}' to 'closed'`),this.emitEvent({type:"state-change",domain:this.domain,previousState:e,newState:"closed",timestamp:Date.now(),metadata:{trigger:"manual-reset"}}))}forceOpen(){console.log(`[DomainCircuitBreaker:${this.domain}] Force-opening circuit`),this.transitionTo("open")}getRecentFailures(e=5){return this.failures.slice(-e).map(t=>`[${new Date(t.timestamp).toISOString()}] ${t.message}`)}onStateChange(e){return this.stateChangeHandlers.add(e),()=>{this.stateChangeHandlers.delete(e)}}getConfig(){return this.config}transitionTo(e){let t=this.state;if(t!==e){switch(this.state=e,e){case"open":this.openedAt=Date.now(),this.halfOpenSuccesses=0;break;case"half-open":this.halfOpenSuccesses=0,console.log(`[DomainCircuitBreaker:${this.domain}] Transitioning to half-open, allowing probe requests`);break;case"closed":this.failures=[],this.openedAt=void 0,this.halfOpenSuccesses=0,console.log(`[DomainCircuitBreaker:${this.domain}] Circuit closed, domain is healthy`);break}this.emitEvent({type:"state-change",domain:this.domain,previousState:t,newState:e,timestamp:Date.now()})}}cleanOldFailures(){let e=Date.now()-this.config.failureWindowMs;this.failures=this.failures.filter(t=>t.timestamp>e)}getTimeUntilTransition(){if(this.state==="open"&&this.openedAt!=null){let e=Date.now()-this.openedAt,t=this.config.resetTimeoutMs-e;return Math.max(0,t)}}emitEvent(e){for(let t of this.stateChangeHandlers)try{t(e)}catch(n){console.log(`[DomainCircuitBreaker:${this.domain}] State change handler error: ${h(n)}`)}}};k();var Ie={critical:{failureThreshold:2,resetTimeoutMs:3e4,halfOpenSuccessThreshold:2,failureWindowMs:6e4,cascadeEnabled:!1,cascadeTargets:void 0},standard:{failureThreshold:3,resetTimeoutMs:6e4,halfOpenSuccessThreshold:2,failureWindowMs:12e4,cascadeEnabled:!1,cascadeTargets:void 0},lenient:{failureThreshold:5,resetTimeoutMs:12e4,halfOpenSuccessThreshold:3,failureWindowMs:3e5,cascadeEnabled:!1,cascadeTargets:void 0}},Ot={"test-generation":"critical","test-execution":"critical","coverage-analysis":"critical","quality-assessment":"critical","security-compliance":"critical","defect-intelligence":"standard","requirements-validation":"standard","code-intelligence":"standard","contract-testing":"standard","visual-accessibility":"lenient","chaos-resilience":"lenient","learning-optimization":"lenient","enterprise-integration":"standard"},N=class{breakers=new Map;defaultConfig;globalHandlers=new Set;constructor(e){this.defaultConfig={...te,...e}}getBreaker(e){let t=this.breakers.get(e);if(!t){let n=Ot[e],i=n?{...this.defaultConfig,...Ie[n]}:this.defaultConfig;t=new x(e,i),this.breakers.set(e,t),t.onStateChange(r=>this.handleBreakerEvent(r)),console.log(`[DomainBreakerRegistry] Created breaker for '${e}' (criticality: ${n??"default"})`)}return t}configureBreaker(e,t){let n={...this.defaultConfig,...t},i=new x(e,n);i.onStateChange(r=>this.handleBreakerEvent(r)),this.breakers.set(e,i),console.log(`[DomainBreakerRegistry] Reconfigured breaker for '${e}'`)}configureCriticality(e,t){let n=Ie[t];this.configureBreaker(e,n),console.log(`[DomainBreakerRegistry] Set '${e}' criticality to '${t}'`)}canExecuteInDomain(e){return this.getBreaker(e).canExecute()}async executeInDomain(e,t){return this.getBreaker(e).execute(t)}getAllStats(){let e=new Map;for(let[t,n]of this.breakers)e.set(t,n.getStats());return e}getOpenDomains(){let e=[];for(let[t,n]of this.breakers)n.getState()==="open"&&e.push(t);return e}getHealthyDomains(){let e=[];for(let[t,n]of this.breakers)n.getState()==="closed"&&e.push(t);return e}getDegradedDomains(){let e=[];for(let[t,n]of this.breakers)n.getState()==="half-open"&&e.push(t);return e}getHealthSummary(){let e=0,t=0,n=0;for(let i of this.breakers.values())switch(i.getState()){case"closed":e++;break;case"half-open":t++;break;case"open":n++;break}return{healthy:e,degraded:t,open:n,total:this.breakers.size}}resetAll(){for(let e of this.breakers.values())e.reset();console.log(`[DomainBreakerRegistry] Reset all ${this.breakers.size} breakers`)}reset(e){let t=this.breakers.get(e);t&&t.reset()}onAnyStateChange(e){return this.globalHandlers.add(e),()=>{this.globalHandlers.delete(e)}}handleBreakerEvent(e){for(let t of this.globalHandlers)try{t(e)}catch(n){console.log(`[DomainBreakerRegistry] Global handler error: ${h(n)}`)}e.type==="state-change"&&e.newState==="open"&&this.propagateCascade(e.domain)}propagateCascade(e){let t=this.breakers.get(e);if(!t)return;let n=t.getConfig();if(!(!n.cascadeEnabled||!n.cascadeTargets?.length))for(let i of n.cascadeTargets){if(i===e)continue;let r=this.getBreaker(i);if(r.getState()!=="open"){console.log(`[DomainBreakerRegistry] Cascading open from '${e}' to '${i}'`),r.forceOpen();let o={type:"cascade-triggered",domain:i,timestamp:Date.now(),metadata:{sourceDomain:e,cascadedFrom:e}};for(let c of this.globalHandlers)try{c(o)}catch(l){console.log(`[DomainBreakerRegistry] Cascade event handler error: ${h(l)}`)}}}}};function Nt(a){return new N(a)}var A=["smoke","standard","deep","crisis"];var L=["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","requirements-validation","code-intelligence","security-compliance","contract-testing","visual-accessibility","chaos-resilience","learning-optimization","enterprise-integration"],ne=["test-generation","coverage-analysis","quality-assessment"],Re={"test-generation":["generator","specialist"],"test-execution":["tester","coordinator"],"coverage-analysis":["analyzer","specialist"],"quality-assessment":["analyzer","validator"],"defect-intelligence":["analyzer","specialist"],"requirements-validation":["validator","reviewer"],"code-intelligence":["analyzer","specialist"],"security-compliance":["analyzer","validator"],"contract-testing":["tester","validator"],"visual-accessibility":["tester","validator"],"chaos-resilience":["tester","specialist"],"learning-optimization":["optimizer","specialist"],"enterprise-integration":["coordinator","validator"]},Qn={tier:"smoke",maxAgents:3,agentTeamsEnabled:!1,domains:["test-execution","quality-assessment"],estimatedCost:"minimal",description:"Lightweight smoke test on every commit. Runs core test execution and quality assessment with minimal agent count to catch obvious regressions quickly.",triggers:[{type:"commit"},{type:"schedule",conditions:{interval:"hourly"}}]},Bn={tier:"standard",maxAgents:7,agentTeamsEnabled:!1,domains:["test-generation","test-execution","coverage-analysis","quality-assessment","security-compliance"],estimatedCost:"moderate",description:"Standard validation for pull requests. Covers test generation, execution, coverage, quality, and security across up to 7 agents. Agent teams are optional.",triggers:[{type:"pr"},{type:"manual"}]},$n={tier:"deep",maxAgents:15,agentTeamsEnabled:!0,domains:[...L],estimatedCost:"high",description:"Deep validation for pre-release and critical path changes. Activates all 13 domains with up to 15 agents and full agent team collaboration.",triggers:[{type:"release"},{type:"pr",conditions:{criticalPath:!0}},{type:"manual",conditions:{requestedTier:"deep"}}]},Un={tier:"crisis",maxAgents:15,agentTeamsEnabled:!0,domains:[...L],estimatedCost:"unlimited",description:"Crisis response for production incidents. All domains active with competing hypotheses enabled. Unlimited cost budget to resolve incidents as fast as possible.",triggers:[{type:"incident"},{type:"manual",conditions:{requestedTier:"crisis"}}]},_e={smoke:Qn,standard:Bn,deep:$n,crisis:Un};var zn=["password","secret","token","crypto","auth","credential","jwt","oauth"],qn=["async","await","Promise","setTimeout","setInterval","Worker","mutex","lock"],Gn={securityKeywords:zn,concurrencyKeywords:qn,enableDimensionOverrides:!1};function jn(a,e){let t=a+e;return t<=8?"trivial":t<=20?"simple":t<=40?"moderate":t<=70?"complex":"critical"}var Q=class{config;constructor(e){this.config={...Gn,...e}}analyzeExtendedDimensions(e){let t=e.split(`
167
- `),n=Math.max(t.length,1),i=this.countKeywordLines(t,this.config.securityKeywords),r=ie(i/n,0,1),s=this.countKeywordLines(t,this.config.concurrencyKeywords),o=ie(s/n,0,1),c=this.countPatternMatches(e,/\.(map|filter|reduce|flatMap|forEach)\s*\(/g),l=ie(c/n,0,1),u=this.countPatternMatches(e,/^export\s/gm),d=Math.max(this.countPatternMatches(e,/^(export\s+)?(const|let|var|function|class|interface|type|enum)\s/gm),1),g=ie(u/d,0,1);return{securitySurface:r,concurrency:o,dataFlow:l,apiSurface:g}}compose(e,t,n){let i=jn(e.cyclomatic,e.cognitive),r=this.analyzeExtendedDimensions(n),s=[],o=[],c;switch(i){case"trivial":case"simple":s.push({agentType:"qe-test-generator",priority:1,reason:`${i} complexity \u2014 basic test generation sufficient`}),o.push("unit"),c="haiku";break;case"moderate":s.push({agentType:"qe-test-generator",priority:1,reason:"Moderate complexity requires thorough test generation"},{agentType:"qe-code-intelligence",priority:2,reason:"Moderate complexity benefits from code intelligence analysis"}),o.push("unit","integration"),c="sonnet";break;case"complex":s.push({agentType:"qe-test-generator",priority:1,reason:"Complex code needs comprehensive test generation"},{agentType:"qe-security-scanner",priority:2,reason:"High complexity warrants security analysis"},{agentType:"qe-code-intelligence",priority:2,reason:"Complex code requires deep code intelligence"}),o.push("unit","integration","security"),c="sonnet";break;case"critical":s.push({agentType:"qe-test-generator",priority:1,reason:"Critical complexity demands full test generation"},{agentType:"qe-security-scanner",priority:1,reason:"Critical complexity mandates security scanning"},{agentType:"qe-code-intelligence",priority:1,reason:"Critical complexity requires deep analysis"},{agentType:"qe-chaos-resilience",priority:2,reason:"Critical systems need chaos/resilience testing"},{agentType:"qe-performance",priority:2,reason:"Critical complexity warrants performance analysis"}),o.push("unit","integration","security","chaos","performance"),c="opus";break}return r.securitySurface>.3&&(s.some(l=>l.agentType==="qe-security-scanner")||s.push({agentType:"qe-security-scanner",priority:2,reason:`High security surface (${(r.securitySurface*100).toFixed(0)}%) \u2014 security scanning recommended`}),o.includes("security")||o.push("security")),r.concurrency>.3&&(s.some(l=>l.agentType==="qe-chaos-resilience")||s.push({agentType:"qe-chaos-resilience",priority:2,reason:`High concurrency (${(r.concurrency*100).toFixed(0)}%) \u2014 chaos/resilience testing recommended`}),o.includes("chaos")||o.push("chaos")),r.apiSurface>.5&&(o.includes("integration")||o.push("integration")),s.sort((l,u)=>l.priority-u.priority),{agents:s,testTypes:o,recommendedTier:c,complexityCategory:i}}countKeywordLines(e,t){let n=0;for(let i of e)for(let r of t)if(i.includes(r)){n++;break}return n}countPatternMatches(e,t){let n=e.match(t);return n?n.length:0}};function ie(a,e,t){return Math.max(e,Math.min(t,a))}var Lt=200,Qt=10,Bt=3,re=class{configs;history=[];escalationCount=0;deescalationCount=0;constructor(e){this.configs={..._e,...e}}selectTier(e){let t,n;if(e.manualOverride)return t=e.manualOverride,n=`Manual override to "${t}" tier`,this.buildResult(t,n,e);if(e.trigger==="incident"||e.isHotfix)return t="crisis",n=e.isHotfix?"Hotfix deployment triggers crisis-level validation":"Production incident triggers crisis-level response",this.buildResult(t,n,e);if(e.trigger==="release")return t="deep",n="Pre-release validation requires deep tier across all domains",this.buildResult(t,n,e);if(e.trigger==="pr"){let i=e.changedFiles!==void 0&&e.changedFiles>Qt,r=e.affectedDomains!==void 0&&e.affectedDomains.length>Bt;if(i||r){t="deep";let s=[];return i&&s.push(`>${Qt} changed files (${e.changedFiles})`),r&&s.push(`>${Bt} affected domains (${e.affectedDomains.length})`),n=`PR escalated to deep tier: ${s.join(" and ")}`,this.buildResult(t,n,e)}return t="standard",n="Pull request triggers standard tier validation",this.buildResult(t,n,e)}return t="smoke",n=e.trigger==="commit"?"Commit triggers lightweight smoke validation":`Trigger "${e.trigger}" defaults to smoke tier`,this.buildResult(t,n,e)}allocateAgents(e,t){let n=this.resolveTargetDomains(e,t);if(n.length===0)return[];let i=e.maxAgents;return n.length>=i?this.allocateWithPriority(n,i):this.allocateWithSurplus(n,i)}escalate(e,t){let n=A.indexOf(e),i=Math.min(n+1,A.length-1),r=A[i],s=e!==r,o=s?`Escalated from "${e}" to "${r}": ${t}`:`Already at maximum tier "${e}", cannot escalate further`;return s&&this.escalationCount++,this.buildResult(r,o,{trigger:"manual"})}deescalate(e){let t=A.indexOf(e),n=Math.max(t-1,0),i=A[n],r=e!==i,s=r?`De-escalated from "${e}" to "${i}"`:`Already at minimum tier "${e}", cannot de-escalate further`;return r&&this.deescalationCount++,this.buildResult(i,s,{trigger:"manual"})}getStats(){let e={smoke:0,standard:0,deep:0,crisis:0};for(let t of this.history)e[t.tier]++;return{totalSelections:this.history.length,selectionsByTier:e,escalationCount:this.escalationCount,deescalationCount:this.deescalationCount,recentSelections:[...this.history].slice(-20)}}_teamComposer;setTeamComposer(e){this._teamComposer=e}selectTierWithComposition(e,t,n){let i=this.selectTier(e);if(!t||!n)return{...i,composition:void 0};let s=(this._teamComposer??new Q).compose(t,i.selectedTier,n);return{...i,composition:s}}buildResult(e,t,n){let i=this.configs[e],r=this.allocateAgents(i,n.affectedDomains),s={tier:e,reason:t,timestamp:Date.now(),trigger:n.trigger};return this.history.push(s),this.history.length>Lt&&this.history.splice(0,this.history.length-Lt),{selectedTier:e,config:i,reason:t,agentAllocation:r}}resolveTargetDomains(e,t){let n=e.domains.includes("all")?L:e.domains;if(!t||t.length===0)return[...n];let i=new Set(n),r=t.filter(s=>i.has(s));return r.length>0?r:[...n]}allocateWithPriority(e,t){let n=new Set(ne),i=[],r=t,s=e.filter(c=>n.has(c)),o=e.filter(c=>!n.has(c));for(let c of s){if(r<=0)break;i.push(this.createAllocation(c,1)),r--}for(let c of o){if(r<=0)break;i.push(this.createAllocation(c,1)),r--}return i}allocateWithSurplus(e,t){let n=new Set(ne),i=new Map;for(let u of e)i.set(u,1);let r=t-e.length,s=e.filter(u=>n.has(u)),o=e.filter(u=>!n.has(u)),c=0;for(;r>0&&s.length>0;){let u=s[c%s.length];if(i.set(u,(i.get(u)??0)+1),r--,c++,c>=s.length*2)break}let l=0;for(;r>0&&o.length>0;){let u=o[l%o.length];i.set(u,(i.get(u)??0)+1),r--,l++}for(;r>0&&s.length>0;){let u=s[c%s.length];i.set(u,(i.get(u)??0)+1),r--,c++}return e.map(u=>this.createAllocation(u,i.get(u)??1))}createAllocation(e,t){let n=Re[e]??["specialist"];return{domain:e,agentCount:t,agentTypes:[...n]}}};function Pe(a){return new re(a)}k();var ae={enabled:!0,minQualityScore:.6,rejectOnFailure:!0,gates:[{name:"test-pass-rate",type:"test-pass-rate",threshold:.8,weight:.35,required:!0},{name:"coverage",type:"coverage",threshold:0,weight:.25,required:!1},{name:"security",type:"security",threshold:0,weight:.25,required:!0},{name:"performance",type:"performance",threshold:3e4,weight:.15,required:!1}]},se=class{config;constructor(e={}){this.config={...ae,...e},e.gates&&(this.config={...this.config,gates:e.gates})}evaluate(e){if(!this.config.enabled)return console.log("[QualityGateEnforcer] Gates disabled, auto-passing"),{passed:!0,score:1,exitCode:0,gates:[],reason:"Quality gates disabled"};if(e.status==="failed")return console.log(`[QualityGateEnforcer] Task ${e.taskId} has failed status`),{passed:!1,score:0,exitCode:this.config.rejectOnFailure?2:0,gates:[],reason:"Task reported failed status"};let t=[],n=[];for(let d of this.config.gates){let g=this.checkGate(d,e);t.push(g),!g.passed&&d.required&&n.push(d.name)}let i=this.config.gates.reduce((d,g)=>d+g.weight,0),r=i>0?t.reduce((d,g)=>{let p=this.config.gates.find(q=>q.name===g.gate);if(!p)return d;let f=g.passed?1:this.computePartialScore(g);return d+f*(p.weight/i)},0):1,s=n.length>0,o=r<this.config.minQualityScore,c=!s&&!o,l;if(!c){let d=[];s&&d.push(`Required gates failed: ${n.join(", ")}`),o&&d.push(`Score ${r.toFixed(3)} below minimum ${this.config.minQualityScore}`),l=d.join("; ")}let u=!c&&this.config.rejectOnFailure?2:0;return console.log(`[QualityGateEnforcer] Task ${e.taskId}: ${c?"PASSED":"FAILED"} (score=${r.toFixed(3)}, gates=${t.filter(d=>d.passed).length}/${t.length})`),{passed:c,score:r,exitCode:u,gates:t,reason:l}}getConfig(){return{...this.config}}checkGate(e,t){let n=this.extractMetricForGate(e,t),i=this.meetsThreshold(e,n);return{gate:e.name,passed:i,actual:n,threshold:e.threshold,weight:e.weight}}extractMetricForGate(e,t){let n=t.metrics;switch(e.type){case"coverage":return n.coverageChange??0;case"test-pass-rate":{let i=n.testsPassed??0,r=n.testsFailed??0,s=i+r;return s>0?i/s:1}case"security":return n.securityIssues??0;case"performance":return n.performanceMs??t.duration;case"custom":{let i=t.output[e.name];return typeof i=="number"?i:0}default:return 0}}meetsThreshold(e,t){switch(e.type){case"security":return t<=e.threshold;case"performance":return t<=e.threshold;default:return t>=e.threshold}}computePartialScore(e){let t=this.config.gates.find(n=>n.name===e.gate);if(!t)return 0;switch(t.type){case"security":case"performance":{if(t.threshold===0)return 0;let n=t.threshold/e.actual;return Math.max(0,Math.min(1,n))}default:{if(t.threshold===0)return 1;let n=e.actual/t.threshold;return Math.max(0,Math.min(1,n))}}}};var Wn={trainPatterns:!0,qualityGate:ae,patternDomains:["test-generation","coverage-analysis","security-compliance","quality-assessment","defect-intelligence","contract-testing"],emitEvents:!0,maxPatternsPerTask:5},Vn={"test-generation":{types:["test-template","assertion-pattern","mock-pattern"],contentKeys:["testCode","template","assertions","mocks"],baseConfidence:.6},"coverage-analysis":{types:["coverage-strategy","mutation-strategy"],contentKeys:["coverageReport","gaps","strategy","recommendations"],baseConfidence:.55},"security-compliance":{types:["security-pattern","vulnerability-fix"],contentKeys:["findings","fixes","recommendations","rules"],baseConfidence:.5},"quality-assessment":{types:["quality-rule","threshold-pattern"],contentKeys:["rules","thresholds","assessments"],baseConfidence:.5},"defect-intelligence":{types:["defect-pattern","root-cause"],contentKeys:["rootCause","pattern","prediction","analysis"],baseConfidence:.45},"contract-testing":{types:["api-contract","schema-pattern"],contentKeys:["contract","schema","endpoints","violations"],baseConfidence:.55},"test-execution":{types:["flaky-fix","retry-strategy"],contentKeys:["flakyTests","retryPolicy","stabilization"],baseConfidence:.5},"visual-accessibility":{types:["visual-baseline","a11y-check"],contentKeys:["baseline","violations","wcagResults"],baseConfidence:.5},"chaos-resilience":{types:["perf-benchmark","resilience-pattern"],contentKeys:["benchmark","faultInjection","recoveryTime"],baseConfidence:.45}},oe=class{config;gateEnforcer;patternStore;completionHandlers=new Set;stats={totalProcessed:0,accepted:0,rejected:0,patternsExtracted:0};constructor(e={},t){this.config={...Wn,...e},e.qualityGate&&(this.config={...this.config,qualityGate:{...ae,...e.qualityGate}}),this.gateEnforcer=new se(this.config.qualityGate),this.patternStore=t??null}async onTaskCompleted(e){this.stats.totalProcessed++,console.log(`[TaskCompletedHook] Processing task ${e.taskId} (agent=${e.agentId}, domain=${e.domain}, status=${e.status})`);let t=this.gateEnforcer.evaluate(e);if(!t.passed&&this.config.qualityGate.rejectOnFailure){this.stats.rejected++;let r={action:"reject",exitCode:2,reason:t.reason||"Quality gate check failed",gateResult:t};return console.log(`[TaskCompletedHook] Task ${e.taskId} REJECTED: ${r.reason}`),this.emitCompletion(e.taskId,r),r}let n=0;if(this.config.trainPatterns&&this.patternStore){let r=this.extractPatterns(e);n=await this.storePatterns(r,e),this.stats.patternsExtracted+=n}this.stats.accepted++;let i={action:"accept",patternsExtracted:n};return console.log(`[TaskCompletedHook] Task ${e.taskId} ACCEPTED (score=${t.score.toFixed(3)}, patterns=${n})`),this.emitCompletion(e.taskId,i),i}extractPatterns(e){let t=[],n=e.domain;if(!this.config.patternDomains.includes(n))return t;let i=Vn[n];if(!i)return this.extractGenericPatterns(e);let r=this.computeConfidenceBoost(e.metrics);for(let s of i.types){if(t.length>=this.config.maxPatternsPerTask)break;for(let o of i.contentKeys){if(t.length>=this.config.maxPatternsPerTask)break;let c=e.output[o];if(c==null)continue;let l=typeof c=="string"?c:JSON.stringify(c);if(l.length<10)continue;let u=Math.min(1,i.baseConfidence+r);t.push({domain:n,type:s,content:l,confidence:u,metadata:{sourceTaskId:e.taskId,sourceAgent:e.agentId,taskType:e.type,duration:e.duration,extractedFrom:o,timestamp:e.timestamp}})}}return t}onCompletion(e){this.completionHandlers.add(e)}offCompletion(e){this.completionHandlers.delete(e)}getStats(){return{...this.stats}}resetStats(){this.stats={totalProcessed:0,accepted:0,rejected:0,patternsExtracted:0}}async storePatterns(e,t){if(!this.patternStore||e.length===0)return 0;let n=0;for(let i of e)try{let r=await this.patternStore.store(i),s=t.status==="completed";await this.patternStore.recordOutcome(r,s),n++}catch(r){console.error(`[TaskCompletedHook] Failed to store pattern: ${h(r)}`)}return n>0&&console.log(`[TaskCompletedHook] Stored ${n}/${e.length} patterns from task ${t.taskId}`),n}extractGenericPatterns(e){let t=[];for(let[n,i]of Object.entries(e.output)){if(t.length>=this.config.maxPatternsPerTask)break;if(i==null)continue;let r=typeof i=="string"?i:JSON.stringify(i);r.length<10||t.push({domain:e.domain,type:"generic",content:r,confidence:.3+this.computeConfidenceBoost(e.metrics),metadata:{sourceTaskId:e.taskId,sourceAgent:e.agentId,taskType:e.type,extractedFrom:n,timestamp:e.timestamp}})}return t}computeConfidenceBoost(e){let t=0,n=e.testsPassed??0,i=e.testsFailed??0,r=n+i;return r>0&&(t+=n/r*.15),e.coverageChange!==void 0&&e.coverageChange>0&&(t+=Math.min(.1,e.coverageChange*.5)),e.securityIssues!==void 0&&e.securityIssues===0&&(t+=.1),e.performanceMs!==void 0&&e.performanceMs<5e3&&(t+=.05),Math.min(.4,t)}emitCompletion(e,t){if(this.config.emitEvents)for(let n of this.completionHandlers)try{n(e,t)}catch(i){console.error(`[TaskCompletedHook] Completion handler error: ${h(i)}`)}}};k();var Kn={"test-template":"test-template","assertion-pattern":"assertion-pattern","mock-pattern":"mock-pattern","coverage-strategy":"coverage-strategy","mutation-strategy":"mutation-strategy","security-pattern":"error-handling","vulnerability-fix":"error-handling","quality-rule":"test-template","threshold-pattern":"test-template","defect-pattern":"error-handling","root-cause":"error-handling","api-contract":"api-contract","schema-pattern":"api-contract","flaky-fix":"flaky-fix","retry-strategy":"flaky-fix","visual-baseline":"visual-baseline","a11y-check":"a11y-check","perf-benchmark":"perf-benchmark","resilience-pattern":"perf-benchmark",generic:"test-template"};function Yn(a){return Kn[a]??"test-template"}function Zn(a){let e=he(a.domain);if(e)return e;let t=he(a.content);return t||"test-generation"}function Xn(a){let e=0;for(let t=0;t<a.length;t++){let n=a.charCodeAt(t);e=(e<<5)-e+n,e=e&e}return Math.abs(e).toString(36).slice(0,8)}var ce=class{constructor(e){this.reasoningBank=e}reasoningBank;async store(e){let t=Zn(e),n=Yn(e.type),i=Xn(e.content),r=`${t}-${e.type}-${i}`,s=[t,e.type,...e.metadata.sourceTaskId?[`task:${e.metadata.sourceTaskId}`]:[]],o={patternType:n,name:r,description:`Auto-extracted ${e.type} pattern from ${e.domain} domain`,template:{type:"prompt",content:e.content,variables:[]},context:{tags:s},confidence:e.confidence};try{let c=await this.reasoningBank.storePattern(o);if(c.success)return c.value.id;throw console.error(`[ReasoningBankPatternStore] Failed to store pattern: ${c.error.message}`),c.error}catch(c){throw console.error(`[ReasoningBankPatternStore] Store error: ${h(c)}`),c}}async recordOutcome(e,t){let n={patternId:e,success:t};try{let i=await this.reasoningBank.recordOutcome(n);i.success||console.error(`[ReasoningBankPatternStore] Failed to record outcome: ${i.error.message}`)}catch(i){console.error(`[ReasoningBankPatternStore] recordOutcome error: ${h(i)}`)}}};ln();var Fe={maxHypothesesPerInvestigation:5,convergenceThreshold:.2,investigationTimeoutMs:3e5,minEvidenceForConvergence:3,autoRejectThreshold:.15};import{randomUUID as He}from"node:crypto";var le=class{investigations=new Map;config;constructor(e){this.config={...Fe,...e}}createInvestigation(e,t,n){let i=`inv-${He().slice(0,8)}`,r=Date.now(),s={id:i,taskId:e,domain:t,description:n,hypotheses:[],status:"open",maxHypotheses:this.config.maxHypothesesPerInvestigation,convergenceThreshold:this.config.convergenceThreshold,createdAt:r,updatedAt:r};return this.investigations.set(i,s),this.toSnapshot(s)}addHypothesis(e,t,n,i){let r=this.getInvestigationMutable(e);if(r.hypotheses.length>=r.maxHypotheses)throw new Error(`Investigation ${e} already has ${r.maxHypotheses} hypotheses (max)`);let s={id:`hyp-${He().slice(0,8)}`,description:t,investigatorAgentId:i,strategy:n,status:"pending",evidence:[],confidenceScore:.5,createdAt:Date.now(),updatedAt:Date.now()};return r.hypotheses.push(s),r.updatedAt=Date.now(),r.status==="open"&&(r.status="investigating"),s}startHypothesis(e,t){let n=this.getInvestigationMutable(e),i=this.findHypothesis(n,t);if(i.status!=="pending")throw new Error(`Hypothesis ${t} cannot be started (current status: ${i.status})`);i.status="investigating",i.updatedAt=Date.now(),n.updatedAt=Date.now()}completeHypothesis(e,t){let n=this.getInvestigationMutable(e),i=this.findHypothesis(n,t);i.status="completed",i.updatedAt=Date.now(),n.updatedAt=Date.now()}submitEvidence(e,t,n){let i=this.getInvestigationMutable(e),r=this.findHypothesis(i,t),s={...n,id:`evi-${He().slice(0,8)}`,hypothesisId:t,timestamp:Date.now()};return r.evidence.push(s),r.confidenceScore=this.calculateConfidence(r),r.updatedAt=Date.now(),i.updatedAt=Date.now(),r.confidenceScore<this.config.autoRejectThreshold&&r.evidence.length>=2&&(r.status="rejected"),s}converge(e){let t=this.getInvestigationMutable(e),n=t.hypotheses.reduce((l,u)=>l+u.evidence.length,0);if(n<this.config.minEvidenceForConvergence){t.status="inconclusive";let l={winningHypothesisId:null,confidence:0,evidenceSummary:`Insufficient evidence (${n}/${this.config.minEvidenceForConvergence} required)`,rejectedHypotheses:t.hypotheses.filter(u=>u.status==="rejected").map(u=>u.id),method:"evidence-scoring"};return t.convergenceResult=l,t.updatedAt=Date.now(),l}let i=[...t.hypotheses].filter(l=>l.status!=="rejected").sort((l,u)=>u.confidenceScore-l.confidenceScore),r="evidence-scoring",s=null,o=0;i.length===0?t.status="inconclusive":i.length===1?(s=i[0].id,o=i[0].confidenceScore,r="unanimous",t.status="converged"):i[0].confidenceScore-i[1].confidenceScore>=t.convergenceThreshold?(s=i[0].id,o=i[0].confidenceScore,t.status="converged"):t.status="inconclusive";let c={winningHypothesisId:s,confidence:o,evidenceSummary:this.buildEvidenceSummary(t),rejectedHypotheses:t.hypotheses.filter(l=>l.status==="rejected").map(l=>l.id),method:r};return t.convergenceResult=c,t.updatedAt=Date.now(),c}getInvestigation(e){let t=this.investigations.get(e);return t?this.toSnapshot(t):void 0}listInvestigations(){return Array.from(this.investigations.values()).map(e=>this.toSnapshot(e))}getConfig(){return this.config}dispose(){this.investigations.clear()}getInvestigationMutable(e){let t=this.investigations.get(e);if(!t)throw new Error(`Investigation ${e} not found`);return t}findHypothesis(e,t){let n=e.hypotheses.find(i=>i.id===t);if(!n)throw new Error(`Hypothesis ${t} not found in investigation ${e.id}`);return n}calculateConfidence(e){if(e.evidence.length===0)return .5;let t=0,n=0;for(let r of e.evidence)r.supports?t+=r.weight:n+=r.weight;let i=t+n;return i===0?.5:Math.min(1,Math.max(0,t/i))}buildEvidenceSummary(e){let t=[];for(let n of e.hypotheses){let i=n.evidence.filter(s=>s.supports).length,r=n.evidence.filter(s=>!s.supports).length;t.push(`${n.id}: ${i} supporting, ${r} refuting (confidence: ${n.confidenceScore.toFixed(2)})`)}return t.join("; ")}toSnapshot(e){return{...e,hypotheses:e.hypotheses.map(t=>({...t,evidence:[...t.evidence]}))}}};function Oe(a){return new le(a)}import{randomUUID as Jn}from"node:crypto";var Ne={localFleetId:"local",heartbeatIntervalMs:3e4,serviceTimeoutMs:9e4,maxPendingMessages:5e3,maxRoutes:100};var de=class{config;services=new Map;routes=[];outbox=[];inbox=[];handlers=[];messagesSent=0;messagesReceived=0;constructor(e){this.config={...Ne,...e}}registerService(e,t,n,i){if(this.services.has(e))throw new Error(`Service '${e}' already registered`);let r=Date.now(),s={fleetId:e,name:t,domains:[...n],status:"active",registeredAt:r,lastHeartbeat:r,metadata:i};return this.services.set(e,s),ue(s)}deregisterService(e){let t=this.services.get(e);if(!t)return!1;t.status="deregistered";for(let n=this.routes.length-1;n>=0;n--)this.routes[n].targetFleetId===e&&this.routes.splice(n,1);return this.services.delete(e),!0}heartbeat(e){let t=this.services.get(e);return t?(t.lastHeartbeat=Date.now(),(t.status==="degraded"||t.status==="unreachable")&&(t.status="active"),!0):!1}addRoute(e,t,n,i=0){if(this.routes.length>=this.config.maxRoutes)throw new Error(`Maximum routes (${this.config.maxRoutes}) reached`);let r={sourceDomain:e,targetDomain:t,targetFleetId:n,priority:i,active:!0};return this.routes.push(r),this.routes.sort((s,o)=>o.priority-s.priority),$t(r)}removeRoute(e,t){let n=this.routes.findIndex(i=>i.sourceDomain===e&&i.targetFleetId===t);return n<0?!1:(this.routes.splice(n,1),!0)}send(e,t,n,i,r,s){let o=e==="any"?this.resolveRoute(t,n):e;if(!o)throw new Error(`No route found for ${t} -> ${n}`);let c={id:Jn(),sourceFleetId:this.config.localFleetId,targetFleetId:o,sourceDomain:t,targetDomain:n,type:i,payload:r,timestamp:Date.now(),ttl:s?.ttl,correlationId:s?.correlationId};return this.outbox.length>=this.config.maxPendingMessages&&this.outbox.shift(),this.outbox.push(c),this.messagesSent++,c}receive(e){this.inbox.length>=this.config.maxPendingMessages&&this.inbox.shift(),this.inbox.push(e),this.messagesReceived++;for(let t of this.handlers)try{t(e)}catch{}}onMessage(e){return this.handlers.push(e),()=>{let t=this.handlers.indexOf(e);t>=0&&this.handlers.splice(t,1)}}drainOutbox(){let e=[...this.outbox];return this.outbox.length=0,e}drainInbox(){let e=[...this.inbox];return this.inbox.length=0,e}findServicesByDomain(e){return Array.from(this.services.values()).filter(t=>t.status==="active"&&t.domains.includes(e)).map(ue)}getService(e){let t=this.services.get(e);return t?ue(t):void 0}listServices(){return Array.from(this.services.values()).map(ue)}listRoutes(){return this.routes.map($t)}checkHealth(){let e=Date.now();for(let t of this.services.values()){if(t.status==="deregistered")continue;let n=e-t.lastHeartbeat;n>this.config.serviceTimeoutMs?t.status="unreachable":n>this.config.serviceTimeoutMs*.6&&(t.status="degraded")}}getHealth(){return{localFleetId:this.config.localFleetId,connectedServices:Array.from(this.services.values()).filter(e=>e.status==="active").length,activeRoutes:this.routes.filter(e=>e.active).length,pendingMessages:this.outbox.length+this.inbox.length,messagesSent:this.messagesSent,messagesReceived:this.messagesReceived}}dispose(){this.services.clear(),this.routes.length=0,this.outbox.length=0,this.inbox.length=0,this.handlers.length=0}resolveRoute(e,t){for(let i of this.routes)if(i.active&&i.sourceDomain===e&&i.targetDomain===t){let r=this.services.get(i.targetFleetId);if(r&&r.status==="active")return i.targetFleetId}let n=this.findServicesByDomain(t);return n.length>0?n[0].fleetId:void 0}};function ue(a){return{fleetId:a.fleetId,name:a.name,domains:[...a.domains],status:a.status,registeredAt:a.registeredAt,lastHeartbeat:a.lastHeartbeat,metadata:a.metadata,endpoint:void 0}}function $t(a){return{sourceDomain:a.sourceDomain,targetDomain:a.targetDomain,targetFleetId:a.targetFleetId,priority:a.priority,active:a.active}}function Le(a){return new de(a)}var Ut={name:"default",scaleUpQueueRatio:3,scaleDownIdleRatio:.5,errorRateScaleUpThreshold:.3,minAgents:2,maxAgents:15,cooldownMs:3e4,sampleWindowSize:5},Qe={defaultPolicy:Ut,metricsHistorySize:100,decisionHistorySize:50};import{randomUUID as ei}from"node:crypto";pe();k();var ge=class a{config;policy;metricsHistory=[];events=[];lastScaleTime=0;scaleUpCount=0;scaleDownCount=0;totalDecisions=0;currentAgents;lastDecision;db=null;persistCount=0;static KV_NAMESPACE="scaling-metrics";static KV_KEY="dynamic-scaler-snapshot";static PERSIST_INTERVAL=10;static KV_TTL=7200;constructor(e=2,t){this.config={...Qe,...t},this.policy=this.config.defaultPolicy,this.currentAgents=e}recordMetrics(e){this.metricsHistory.push(e),this.metricsHistory.length>this.config.metricsHistorySize&&this.metricsHistory.shift(),this.persistCount++,this.persistCount%a.PERSIST_INTERVAL===0&&this.persistSnapshot().catch(()=>{})}evaluate(){let e=this.getAverageMetrics(),t=Date.now();if(this.totalDecisions++,t-this.lastScaleTime<this.policy.cooldownMs){let o={action:"maintain",currentAgents:this.currentAgents,targetAgents:this.currentAgents,reason:"Cooldown period active",metrics:e,timestamp:t};return this.lastDecision=o,o}let n="maintain",i=this.currentAgents,r="Workload within acceptable range";if(e.errorRate>this.policy.errorRateScaleUpThreshold)n="scale-up",i=Math.min(this.currentAgents+2,this.policy.maxAgents),r=`High error rate (${(e.errorRate*100).toFixed(1)}% > ${(this.policy.errorRateScaleUpThreshold*100).toFixed(1)}% threshold)`;else if(this.currentAgents>0&&e.queueDepth/Math.max(1,this.currentAgents)>this.policy.scaleUpQueueRatio){n="scale-up";let o=Math.ceil(e.queueDepth/this.policy.scaleUpQueueRatio);i=Math.min(o,this.policy.maxAgents),r=`Queue depth ratio ${(e.queueDepth/Math.max(1,this.currentAgents)).toFixed(1)} > ${this.policy.scaleUpQueueRatio} threshold`}if(n==="maintain"&&this.currentAgents>this.policy.minAgents){let o=this.currentAgents>0?e.idleAgents/this.currentAgents:0;if(o>this.policy.scaleDownIdleRatio){n="scale-down";let c=Math.floor(e.idleAgents*.5);i=Math.max(this.currentAgents-c,this.policy.minAgents),r=`Idle ratio ${(o*100).toFixed(1)}% > ${(this.policy.scaleDownIdleRatio*100).toFixed(1)}% threshold`}}i=Math.max(this.policy.minAgents,Math.min(this.policy.maxAgents,i)),i===this.currentAgents&&(n="maintain");let s={action:n,currentAgents:this.currentAgents,targetAgents:i,reason:r,metrics:e,timestamp:t};return this.lastDecision=s,s}async execute(e,t){let n={id:`scale-${ei().slice(0,8)}`,decision:e,executedAt:Date.now(),success:!0};if(e.action==="maintain")return this.recordEvent(n),n;try{if(t&&!await t(e.currentAgents,e.targetAgents)){let r={...n,success:!1,error:"Executor returned false"};return this.recordEvent(r),r}return this.currentAgents=e.targetAgents,this.lastScaleTime=Date.now(),e.action==="scale-up"&&this.scaleUpCount++,e.action==="scale-down"&&this.scaleDownCount++,this.recordEvent(n),n}catch(i){let r={...n,success:!1,error:h(i)};return this.recordEvent(r),r}}setPolicy(e){this.policy=e}getPolicy(){return{...this.policy}}getCurrentAgents(){return this.currentAgents}getStats(){return{scaleUpCount:this.scaleUpCount,scaleDownCount:this.scaleDownCount,totalDecisions:this.totalDecisions,currentAgents:this.currentAgents,policyName:this.policy.name,lastDecision:this.lastDecision,recentEvents:[...this.events].slice(-10)}}getMetricsHistory(){return[...this.metricsHistory]}async initialize(){try{this.db=w(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(e){console.warn("[DynamicScaler] DB init failed, using memory-only:",h(e)),this.db=null}}dispose(){this.metricsHistory.length=0,this.events.length=0}getAverageMetrics(){let e=this.metricsHistory.slice(-this.policy.sampleWindowSize);if(e.length===0)return{queueDepth:0,activeAgents:this.currentAgents,idleAgents:0,avgTaskDurationMs:0,errorRate:0,throughput:0,timestamp:Date.now()};let t=n=>e.reduce((i,r)=>i+n(r),0)/e.length;return{queueDepth:Math.round(t(n=>n.queueDepth)),activeAgents:Math.round(t(n=>n.activeAgents)),idleAgents:Math.round(t(n=>n.idleAgents)),avgTaskDurationMs:Math.round(t(n=>n.avgTaskDurationMs)),errorRate:t(n=>n.errorRate),throughput:t(n=>n.throughput),timestamp:Date.now()}}recordEvent(e){this.events.push(e),this.events.length>this.config.decisionHistorySize&&this.events.shift(),this.persistCount++,this.persistCount%a.PERSIST_INTERVAL===0&&this.persistSnapshot().catch(()=>{})}async loadFromKv(){if(this.db)try{let e=await this.db.kvGet(a.KV_KEY,a.KV_NAMESPACE);if(e){if(Array.isArray(e.metricsHistory))for(let t of e.metricsHistory)this.metricsHistory.push(t);if(Array.isArray(e.events))for(let t of e.events)this.events.push(t)}}catch(e){console.warn("[DynamicScaler] Failed to load KV snapshot:",h(e))}}async persistSnapshot(){if(this.db)try{let e={metricsHistory:this.metricsHistory.slice(-50),events:this.events.slice(-50)};await this.db.kvSet(a.KV_KEY,e,a.KV_NAMESPACE,a.KV_TTL)}catch(e){console.warn("[DynamicScaler] Failed to persist KV snapshot:",h(e))}}};function Be(a,e){return new ge(a,e)}var ti=[{name:"Core Testing",domains:["test-generation","test-execution","coverage-analysis","quality-assessment"],priority:"p0",description:"Core testing workflow domains"},{name:"Intelligence",domains:["defect-intelligence","code-intelligence","requirements-validation","security-compliance"],priority:"p0",description:"Intelligence and analysis domains"},{name:"Specialized",domains:["contract-testing","visual-accessibility","chaos-resilience","learning-optimization"],priority:"p1",description:"Specialized testing domains"}],P={"generate-tests":["test-generation"],"execute-tests":["test-execution"],"analyze-coverage":["coverage-analysis"],"assess-quality":["quality-assessment"],"predict-defects":["defect-intelligence"],"validate-requirements":["requirements-validation"],"index-code":["code-intelligence"],"scan-security":["security-compliance"],"validate-contracts":["contract-testing"],"test-accessibility":["visual-accessibility"],"run-chaos":["chaos-resilience"],"optimize-learning":["learning-optimization"],"cross-domain-workflow":[],"protocol-execution":[],"ideation-assessment":["requirements-validation","coverage-analysis","security-compliance"]},zt={maxConcurrentTasks:50,defaultTaskTimeout:3e5,taskRetryLimit:3,workStealing:{enabled:!0,idleThreshold:5e3,loadThreshold:10,stealBatchSize:3,checkInterval:1e4},enableMetrics:!0,metricsInterval:6e4,priorityWeights:{p0:100,p1:50,p2:25,p3:10},enableRouting:!0};function qt(a){P["cross-domain-workflow"]=a,P["protocol-execution"]=a}import{readFileSync as ii,existsSync as ri}from"fs";import{join as si}from"path";import{parse as ai}from"yaml";pe();import{randomUUID as ni}from"crypto";var B={RISK_WEIGHTS:2160*60*60*1e3,SFDIPOT_WEIGHTS:2160*60*60*1e3,FLAKY_PATTERNS:720*60*60*1e3,AC_QUALITY:1440*60*60*1e3};function $(a,e){let t=Date.now(),n=ni().split("-")[0];return`${e||a}-signal-${t}-${n}`}function U(a){return new Date(Date.now()+a).toISOString()}function E(a){return new Date(a.expiresAt)<new Date}var b={STRATEGIC:"qcsd/strategic",TACTICAL:"qcsd/tactical",OPERATIONAL:"qcsd/operational",QUALITY_CRITERIA:"qcsd/quality-criteria"},Ue=class{memory;initialized=!1;constructor(e={}){this.memory=e.memoryManager||w()}async initialize(){this.initialized||(await this.memory.initialize(),this.initialized=!0,console.log("[CrossPhaseMemory] Initialized with UnifiedMemoryManager"))}async storeRiskSignal(e,t){await this.ensureInitialized();let n={id:$("strategic","risk"),timestamp:new Date().toISOString(),source:"production",target:"ideation",loopType:"strategic",version:"1.0.0",expiresAt:U(B.RISK_WEIGHTS),riskWeights:e,recommendations:t};return await this.store(b.STRATEGIC,n),n}async queryRiskSignals(){return await this.ensureInitialized(),(await this.queryByNamespace(b.STRATEGIC)).filter(t=>!E(t))}async storeSFDIPOTSignal(e,t,n){await this.ensureInitialized();let i={id:$("tactical","sfdipot"),timestamp:new Date().toISOString(),source:"production",target:"refinement",loopType:"tactical",version:"1.0.0",expiresAt:U(B.SFDIPOT_WEIGHTS),factorWeights:e,featureContext:t,recommendations:n};return await this.store(b.TACTICAL,i),i}async querySFDIPOTSignals(e){await this.ensureInitialized();let t=await this.queryByNamespace(b.TACTICAL);return t=t.filter(n=>!E(n)),e&&(t=t.filter(n=>n.featureContext.toLowerCase().includes(e.toLowerCase()))),t}async storeTestHealthSignal(e,t,n){await this.ensureInitialized();let i={id:$("operational","test-health"),timestamp:new Date().toISOString(),source:"cicd",target:"development",loopType:"operational",version:"1.0.0",expiresAt:U(B.FLAKY_PATTERNS),flakyPatterns:e,gateFailures:t,recommendations:n};return await this.store(b.OPERATIONAL,i),i}async queryTestHealthSignals(){return await this.ensureInitialized(),(await this.queryByNamespace(b.OPERATIONAL)).filter(t=>!E(t))}async storeACQualitySignal(e,t,n){await this.ensureInitialized();let i={id:$("quality-criteria","ac-quality"),timestamp:new Date().toISOString(),source:"development",target:"refinement",loopType:"quality-criteria",version:"1.0.0",expiresAt:U(B.AC_QUALITY),untestablePatterns:e,coverageGaps:t,recommendations:n};return await this.store(b.QUALITY_CRITERIA,i),i}async queryACQualitySignals(){return await this.ensureInitialized(),(await this.queryByNamespace(b.QUALITY_CRITERIA)).filter(t=>!E(t))}async store(e,t){let n=new Date(t.expiresAt).getTime(),i=Math.max(0,Math.floor((n-Date.now())/1e3));await this.memory.kvSet(t.id,t,e,i>0?i:void 0),console.log(`[CrossPhaseMemory] Stored signal: ${t.id} in ${e}`)}async queryByNamespace(e){let t=await this.memory.kvSearch("*",e,1e3),n=[];for(let i of t){let r=await this.memory.kvGet(i,e);r&&n.push(r)}return n.sort((i,r)=>new Date(r.timestamp).getTime()-new Date(i.timestamp).getTime())}async delete(e,t){let n=await this.memory.kvDelete(t,e);return n&&console.log(`[CrossPhaseMemory] Deleted signal: ${t}`),n}async cleanupExpired(){let e={deleted:0,namespaces:{}};for(let t of Object.values(b)){let n=await this.queryByNamespace(t),i=0;for(let r of n)E(r)&&(await this.delete(t,r.id),i++,e.deleted++);i>0&&(e.namespaces[t]=i)}return e.deleted>0&&console.log(`[CrossPhaseMemory] Cleanup: deleted ${e.deleted} expired signals`),e}async getStats(){await this.ensureInitialized();let e={totalSignals:0,byLoop:{strategic:0,tactical:0,operational:0,"quality-criteria":0},byNamespace:{},oldestSignal:null,newestSignal:null},t=null,n=null;for(let i of Object.values(b)){let s=(await this.queryByNamespace(i)).filter(o=>!E(o));e.byNamespace[i]=s.length,e.totalSignals+=s.length;for(let o of s){e.byLoop[o.loopType]++;let c=new Date(o.timestamp);(!t||c<t)&&(t=c,e.oldestSignal=o.timestamp),(!n||c>n)&&(n=c,e.newestSignal=o.timestamp)}}return e}async ensureInitialized(){this.initialized||await this.initialize()}},$e=null;function Gt(a){return $e||($e=new Ue(a)),$e}function ze(a){let e=Object.getOwnPropertyNames(a);for(let t of e){let n=a[t];n&&typeof n=="object"&&!Object.isFrozen(n)&&ze(n)}return Object.freeze(a)}function qe(a){let e=structuredClone(a);return ze(e)}function Ge(a){return a===0?"success":a===2?"model_blocking":"user_error"}var We=class{config=null;memory;configPath;listeners=new Map;constructor(e){this.configPath=e||si(process.cwd(),".claude/hooks/cross-phase-memory.yaml"),this.memory=Gt()}async initialize(){if(process.env.AQE_HOOKS_DISABLED==="true")return console.log("[CrossPhaseHooks] All hooks disabled via AQE_HOOKS_DISABLED"),!1;if(!ri(this.configPath))return console.warn(`[CrossPhaseHooks] Config not found: ${this.configPath}`),!1;try{let e=ii(this.configPath,"utf-8"),t=ai(e);return t.enabled?(this.config=qe(t),await this.memory.initialize(),console.log(`[CrossPhaseHooks] Initialized with ${Object.keys(this.config.hooks).length} hooks`),!0):(console.log("[CrossPhaseHooks] Hooks disabled in config"),!1)}catch(e){return console.error("[CrossPhaseHooks] Failed to load config:",e),!1}}async onAgentComplete(e,t){if(!this.config||process.env.AQE_HOOKS_DISABLED==="true")return;let n=this.filterManagedHooks(Object.entries(this.config.hooks).filter(([i,r])=>r.trigger.event==="agent-complete"&&r.trigger.agent===e));for(let[i,r]of n)this.checkConditions(r.trigger.conditions,t)&&(console.log(`[CrossPhaseHooks] Executing hook: ${i}`),await this.executeActions(r.actions,t))}async onPhaseStart(e,t={}){if(!this.config)return{};if(process.env.AQE_HOOKS_DISABLED==="true")return{};let n={},i=this.filterManagedHooks(Object.entries(this.config.hooks).filter(([r,s])=>s.trigger.event==="phase-start"&&s.trigger.phase===e));for(let[r,s]of i){console.log(`[CrossPhaseHooks] Executing phase-start hook: ${r}`);for(let o of s.actions)if(o.type==="query-signals"&&o.injectInto){let c=await this.querySignalsForInjection(o.namespace,o.maxAge,o.filterBy?t[o.filterBy]:void 0);for(let l of o.injectInto)n[l]||(n[l]=[]),n[l].push(...c)}}return n}async onPhaseEnd(e,t){if(!this.config||process.env.AQE_HOOKS_DISABLED==="true")return;let n=this.filterManagedHooks(Object.entries(this.config.hooks).filter(([i,r])=>r.trigger.event==="phase-end"&&r.trigger.phase===e));for(let[i,r]of n)console.log(`[CrossPhaseHooks] Executing phase-end hook: ${i}`),await this.executeActions(r.actions,t)}async executeActions(e,t){for(let n of e)try{await this.executeAction(n,t)}catch(i){let r=i?.exitCode;if(typeof r=="number"){let s=Ge(r);if(s==="model_blocking")throw console.error(`[CrossPhaseHooks] Model-blocking hook failure (exit ${r}):`,i),i;console.warn(`[CrossPhaseHooks] Hook ${s} (exit ${r}):`,i)}else console.error("[CrossPhaseHooks] Action failed:",i)}}async executeAction(e,t){switch(e.type){case"store-signal":await this.executeStoreSignal(e,t);break;case"query-signals":break;case"notify-agent":await this.executeNotifyAgent(e,t);break;case"invoke-agent":await this.executeInvokeAgent(e,t);break;case"conditional":e.condition&&e.action&&this.evaluateCondition(e.condition,t)&&await this.executeAction(e.action,t);break;case"delete-expired":await this.memory.cleanupExpired();break;default:console.warn(`[CrossPhaseHooks] Unknown action type: ${e.type}`)}}async executeStoreSignal(e,t){if(!e.loop||!e.namespace||!e.extract)return;let n=this.extractFromContext(e.extract,t);switch(e.loop){case"strategic":await this.memory.storeRiskSignal(n.riskWeights||[],n.recommendations||{forRiskAssessor:[],forQualityCriteria:[]});break;case"tactical":await this.memory.storeSFDIPOTSignal(n.factorWeights||[],n.featureContext||"unknown",n.recommendations||{forProductFactorsAssessor:[]});break;case"operational":await this.memory.storeTestHealthSignal(n.flakyPatterns||[],n.gateFailures||[],n.recommendations||{forTestArchitect:[],antiPatterns:[]});break;case"quality-criteria":await this.memory.storeACQualitySignal(n.untestablePatterns||[],n.coverageGaps||[],n.recommendations||{forRequirementsValidator:[],acTemplates:{}});break}this.emit("signal-stored",{loop:e.loop,namespace:e.namespace})}async executeNotifyAgent(e,t){!e.target||!e.message||await this.isBlockedUrl(e.target)||(console.log(`[CrossPhaseHooks] Notify ${e.target}: ${e.message}`),this.emit("agent-notification",{target:e.target,message:e.message,priority:e.priority||"normal",context:t}))}async executeInvokeAgent(e,t){e.target&&(await this.isBlockedUrl(e.target)||(console.log(`[CrossPhaseHooks] Invoke agent: ${e.target}`),this.emit("agent-invocation",{agent:e.target,input:{...t,...e.input||{}}})))}async querySignalsForInjection(e,t,n){let r=await this.memory.queryByNamespace(e);if(t){let s=this.parseMaxAge(t),o=Date.now()-s;r=r.filter(c=>new Date(c.timestamp).getTime()>o)}return r}formatSignalsForInjection(e){if(e.length===0)return"";let t=`## CROSS-PHASE LEARNING SIGNALS
164
+ `);return null}function _(a){let e=a.trim();return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function Hn(a){let e=_t(a);if(!e)return null;let t=e.split(`
165
+ `),n=-1;for(let l=0;l<t.length;l++)if(/^dependencies:\s*$/.test(t[l])){n=l+1;break}if(n===-1)return null;let i=[];for(let l=n;l<t.length;l++){let u=t[l];if(u.trim()!==""){if(u.length>0&&u[0]!==" "&&u[0]!==" ")break;i.push(u)}}if(i.length===0)return null;let r={},s={section:"none",item:{},inList:!1},o=()=>{s.item.name&&(r.agents||(r.agents=[]),r.agents.push({name:s.item.name,type:s.item.type||"hard",reason:s.item.reason||""}),s.item={})},c=()=>{s.item.name&&(r.mcpServers||(r.mcpServers=[]),r.mcpServers.push({name:s.item.name,required:s.item.required==="true"}),s.item={})};for(let l of i){let u=l.trim();if(u==="")continue;let d=u.match(/^(agents|mcp_servers|models):\s*$/);if(d){s.section==="agents"&&s.inList&&o(),s.section==="mcp_servers"&&s.inList&&c(),s.inList=!1,s.section=d[1];continue}if(s.section==="agents"||s.section==="mcp_servers"){let g=u.match(/^-\s+(\w+):\s*(.*)$/);if(g){s.inList&&(s.section==="agents"?o():c()),s.inList=!0,s.item={[g[1]]:_(g[2])};continue}if(s.inList){let p=u.match(/^(\w+):\s*(.*)$/);if(p){s.item[p[1]]=_(p[2]);continue}}}if(s.section==="models"){r.models||(r.models={});let g=u.match(/^(\w+):\s*(.*)$/);if(g){let f=_(g[2]);if(g[1]==="minimum")r.models={...r.models,minimum:f};else if(g[1]==="capabilities"){let z=f.match(/^\[(.+)]$/);z&&(r.models={...r.models,capabilities:z[1].split(",").map(an=>_(an.trim()))})}}let p=u.match(/^-\s+(.+)$/);if(p&&r.models){let f=r.models.capabilities||[];r.models={...r.models,capabilities:[...f,_(p[1])]}}}}return s.section==="agents"&&s.inList&&o(),s.section==="mcp_servers"&&s.inList&&c(),!r.agents&&!r.mcpServers&&!r.models?null:r}function On(a){let e=_t(a);if(!e)return null;for(let t of e.split(`
166
+ `)){let n=t.match(/^name:\s*(.+)$/);if(n)return _(n[1])}return null}function Pt(a){let e=new Map,t=[];if(!Rn(a))return t.push(`Agents directory not found: ${a}`),{nodes:e,spawnOrder:[],cycles:[],warnings:t};let n=_n(a).filter(s=>s.startsWith("qe-")&&s.endsWith(".md"));for(let s of n){let o;try{o=In(Pn(a,s),"utf-8")}catch{t.push(`Failed to read agent file: ${s}`);continue}let c=On(o)||Fn(s,".md"),l=Hn(o),u=[],d=[],g=[];if(l?.agents)for(let p of l.agents)p.type==="hard"?u.push(p.name):p.type==="soft"?d.push(p.name):p.type==="peer"&&g.push(p.name);e.set(c,{agentName:c,hardDeps:u,softDeps:d,peerDeps:g,dependencies:l||{}})}let i=new Set(e.keys());for(let[s,o]of e)for(let c of o.hardDeps)i.has(c)||t.push(`Agent "${s}" declares hard dependency on "${c}" which is not in the agent directory`);let r=Nn(e);for(let s of r)t.push(`Dependency cycle detected: ${s.join(" -> ")}`);return{nodes:e,spawnOrder:Ln(e,r),cycles:r,warnings:t}}function Nn(a){let e=[],t=new Set,n=new Set,i=[];function r(s){t.add(s),n.add(s),i.push(s);let o=a.get(s);if(o){for(let c of o.hardDeps)if(!t.has(c)&&a.has(c))r(c);else if(n.has(c)){let l=i.indexOf(c);l!==-1&&e.push([...i.slice(l),c])}}i.pop(),n.delete(s)}for(let s of a.keys())t.has(s)||r(s);return e}function Ln(a,e){let t=new Set(e.flat()),n=[],i=new Set,r=new Set;function s(o){if(i.has(o)||t.has(o)||r.has(o))return;r.add(o);let c=a.get(o);if(c)for(let l of c.hardDeps)a.has(l)&&s(l);r.delete(o),i.add(o),n.push(o)}for(let o of a.keys())s(o);for(let o of t)n.includes(o)||n.push(o);return n}function Ft(a,e){let t=new Set(a),n=[],i=[];for(let c of a){let l=e.nodes.get(c);if(!l)continue;let u=l.hardDeps.filter(d=>!t.has(d));u.length>0&&(i.push({agent:c,missing:u}),n.push(`Advisory: "${c}" has unsatisfied hard dependencies: ${u.join(", ")}. Proceeding anyway.`))}let r=[],s=new Set,o=new Set(a);for(;o.size>0;){let c=[];for(let l of o){let u=e.nodes.get(l);if(!u){c.push(l);continue}u.hardDeps.filter(g=>t.has(g)).every(g=>s.has(g))&&c.push(l)}if(c.length===0){n.push(`Could not resolve dependency ordering for: ${[...o].join(", ")}. Placing in final phase.`),r.push([...o]);break}r.push(c);for(let l of c)s.add(l),o.delete(l);o=new Set([...o])}return{phases:r,unsatisfiedHardDeps:i,warnings:n}}var xe={defaultTtlMs:0,cleanupIntervalMs:6e4,maxMailboxSize:1e3};var O=class{mailboxes=new Map;messageHandlers=new Map;broadcastHandlers=new Map;domainAgents=new Map;cognitiveRouter=null;cognitiveRouterInitialized=!1;compressedMessages=new Map;createMailbox(e,t){let n=this.mailboxes.get(e);if(n)return this.toSnapshot(n);let i={agentId:e,domain:t,messages:[],unreadCount:0,lastRead:Date.now()};this.mailboxes.set(e,i);let r=this.domainAgents.get(t);return r||(r=new Set,this.domainAgents.set(t,r)),r.add(e),this.toSnapshot(i)}getMailbox(e){let t=this.mailboxes.get(e);if(t)return this.toSnapshot(t)}deleteMailbox(e){let t=this.mailboxes.get(e);if(!t)return!1;let n=this.domainAgents.get(t.domain);n&&(n.delete(e),n.size===0&&this.domainAgents.delete(t.domain));for(let i of t.messages)this.compressedMessages.delete(i.id);return this.messageHandlers.delete(e),this.mailboxes.delete(e),!0}send(e){if(e.to==="broadcast"){this.broadcast(e.domain,e);return}let t=this.mailboxes.get(e.to);if(!t)throw new Error(`No mailbox found for agent '${e.to}'. Create a mailbox first with createMailbox().`);let n=this.compressViaCognitive(e);t.messages.push(n),t.unreadCount++;let i=this.messageHandlers.get(e.to);if(i)for(let r of i)try{r(e)}catch{}}broadcast(e,t){let n=this.domainAgents.get(e);if(!n)return;for(let r of n){if(r===t.from)continue;let s=this.mailboxes.get(r);if(s){s.messages.push(t),s.unreadCount++;let o=this.messageHandlers.get(r);if(o)for(let c of o)try{c(t)}catch{}}}let i=this.broadcastHandlers.get(e);if(i)for(let r of i)try{r(e,t)}catch{}}receive(e,t){let n=this.mailboxes.get(e);if(!n||n.unreadCount===0)return[];let i=Date.now(),r=n.messages.length-n.unreadCount,s=n.messages.slice(r);return s=s.filter(o=>!this.isExpired(o,i)),t?.type&&(s=s.filter(o=>o.type===t.type)),t?.since!==void 0&&(s=s.filter(o=>o.timestamp>=t.since)),t?.limit!==void 0&&t.limit>0&&(s=s.slice(0,t.limit)),n.unreadCount=0,n.lastRead=i,this.decompressMessages(s)}peek(e){let t=this.mailboxes.get(e);if(!t)return 0;let n=Date.now(),i=t.messages.length-t.unreadCount,r=0;for(let s=i;s<t.messages.length;s++)this.isExpired(t.messages[s],n)||r++;return r}cleanup(e){let t=Date.now(),n=t-e,i=0;for(let r of this.mailboxes.values()){let s=r.messages.length,o=r.messages.length-r.unreadCount;r.messages=r.messages.filter((l,u)=>l.timestamp<n?(this.compressedMessages.delete(l.id),!1):this.isExpired(l,t)?(this.compressedMessages.delete(l.id),!1):!0);let c=s-r.messages.length;i+=c,c>0&&(r.unreadCount=r.messages.filter(l=>l.timestamp>r.lastRead).length)}return i}onMessage(e,t){let n=this.messageHandlers.get(e);return n||(n=[],this.messageHandlers.set(e,n)),n.push(t),()=>{let i=this.messageHandlers.get(e);if(i){let r=i.indexOf(t);r>=0&&i.splice(r,1)}}}onBroadcast(e,t){let n=this.broadcastHandlers.get(e);return n||(n=[],this.broadcastHandlers.set(e,n)),n.push(t),()=>{let i=this.broadcastHandlers.get(e);if(i){let r=i.indexOf(t);r>=0&&i.splice(r,1)}}}getAgentsInDomain(e){let t=this.domainAgents.get(e);return t?Array.from(t):[]}getDomains(){return Array.from(this.domainAgents.keys())}get size(){return this.mailboxes.size}clear(){this.mailboxes.clear(),this.messageHandlers.clear(),this.broadcastHandlers.clear(),this.domainAgents.clear(),this.compressedMessages.clear(),this.cognitiveRouter=null,this.cognitiveRouterInitialized=!1}isExpired(e,t){return!e.ttl||e.ttl<=0?!1:t>e.timestamp+e.ttl}toSnapshot(e){return{agentId:e.agentId,domain:e.domain,messages:[...e.messages],unreadCount:e.unreadCount,lastRead:e.lastRead}}ensureCognitiveRouter(){if(this.cognitiveRouterInitialized)return this.cognitiveRouter;if(this.cognitiveRouterInitialized=!0,!pt())return null;try{this.cognitiveRouter=mt()??null}catch{this.cognitiveRouter=null}return this.cognitiveRouter}compressViaCognitive(e){try{let t=this.ensureCognitiveRouter();if(!t)return e;let n=`${e.from}->${e.to}`,i=t.send(n,e.from,e.to,e.payload);return i.compressed&&i.compressedSize<i.originalSize?(this.compressedMessages.set(e.id,i),{...e,payload:i.payload}):e}catch{return e}}decompressMessages(e){let t=this.cognitiveRouter;return!t||this.compressedMessages.size===0?e:e.map(n=>{try{let i=this.compressedMessages.get(n.id);if(!i)return n;let r=t.receive(i);return this.compressedMessages.delete(n.id),{...n,payload:r}}catch{return n}})}getCognitiveRoutingStats(){return this.cognitiveRouter?this.cognitiveRouter.getStats():null}};import{randomUUID as Ht}from"node:crypto";st();import{randomUUID as K}from"node:crypto";var Y=class{spans=new Map;traceIndex=new Map;maxSpans;constructor(e=1e4){this.maxSpans=e}startTrace(e){let t=K(),n=K(),i={traceId:t,spanId:n},r=this.createSpan(i,e);return{context:i,span:r}}startSpan(e){let t=e.parentContext,n=t?.traceId??K(),i=K(),r={traceId:n,spanId:i,parentSpanId:t?.spanId,baggage:t?.baggage},s=this.createSpan(r,e);return{context:r,span:s}}completeSpan(e){let t=this.spans.get(e);t&&(t.endTime=Date.now(),t.status="completed")}failSpan(e,t){let n=this.spans.get(e);n&&(n.endTime=Date.now(),n.status="error",n.errorMessage=t)}getTrace(e){let t=this.traceIndex.get(e);return t?Array.from(t).map(n=>this.spans.get(n)).filter(n=>n!==void 0).sort((n,i)=>n.startTime-i.startTime):[]}getSpan(e){return this.spans.get(e)}getActiveSpans(){return Array.from(this.spans.values()).filter(e=>e.status==="active")}getStats(){let e=new Set,t=new Set;for(let[n,i]of this.traceIndex)Array.from(i).map(s=>this.spans.get(s)).filter(s=>s!==void 0).some(s=>s.status==="active")?e.add(n):t.add(n);return{totalSpans:this.spans.size,activeTraces:e.size,completedTraces:t.size}}purge(e){let t=Date.now()-e,n=0;for(let[i,r]of this.traceIndex){let s=Array.from(r).map(l=>this.spans.get(l)).filter(l=>l!==void 0),o=s.every(l=>l.status!=="active"),c=s.every(l=>(l.endTime??l.startTime)<t);if(o&&c){for(let l of r)this.spans.delete(l),n++;this.traceIndex.delete(i)}}return n}dispose(){this.spans.clear(),this.traceIndex.clear()}createSpan(e,t){this.spans.size>=this.maxSpans&&this.purge(6e4);let n={traceId:e.traceId,spanId:e.spanId,parentSpanId:e.parentSpanId,operationName:t.operationName,agentId:t.agentId,domain:t.domain,startTime:Date.now(),tags:t.tags??{},status:"active"};this.spans.set(e.spanId,n);let i=this.traceIndex.get(e.traceId);return i||(i=new Set,this.traceIndex.set(e.traceId,i)),i.add(e.spanId),n}},Qn="trace:";function Z(a){return`${Qn}${JSON.stringify({traceId:a.traceId,spanId:a.spanId,parentSpanId:a.parentSpanId})}`}function Ee(a){return new Y(a)}var X=class{mailbox;config;teams=new Map;registeredAgents=new Set;agentDomains=new Map;subscriptions=new Map;cleanupTimer=null;initialized=!1;constructor(e,t){this.mailbox=e??new O,this.config={...xe,...t}}initialize(e){this.initialized||(e&&Object.assign(this.config,e),this.config.cleanupIntervalMs>0&&(this.cleanupTimer=setInterval(()=>{this.performCleanup()},this.config.cleanupIntervalMs)),this.initialized=!0)}shutdown(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null),this.mailbox.clear(),this.teams.clear(),this.registeredAgents.clear(),this.agentDomains.clear(),this.subscriptions.clear(),this.initialized=!1}createTeam(e){if(this.teams.has(e.domain))throw new Error(`Team already exists for domain '${e.domain}'. Use getTeamStatus() to inspect the existing team.`);let t={domain:e.domain,leadAgentId:e.leadAgentId,maxTeammates:e.maxTeammates,teammateIds:[...e.teammateIds],autoAssignEnabled:e.autoAssignEnabled};this.teams.set(e.domain,t),this.registerAgent(e.leadAgentId,e.domain);for(let n of e.teammateIds)this.registerAgent(n,e.domain)}getTeamStatus(e){let t=this.teams.get(e);if(!t)return;let n=[t.leadAgentId,...t.teammateIds],i=n.filter(s=>this.mailbox.peek(s)===0),r=0;for(let s of n)r+=this.mailbox.peek(s);return{domain:t.domain,leadAgentId:t.leadAgentId,teammateIds:[...t.teammateIds],activeAgentCount:n.filter(s=>this.registeredAgents.has(s)).length,idleAgentIds:i,totalUnreadMessages:r}}registerAgent(e,t){if(this.registeredAgents.has(e))return;this.registeredAgents.add(e),this.agentDomains.set(e,t),this.mailbox.createMailbox(e,t);let n=this.teams.get(t);n&&n.autoAssignEnabled&&e!==n.leadAgentId&&!n.teammateIds.includes(e)&&n.teammateIds.length<n.maxTeammates&&n.teammateIds.push(e)}unregisterAgent(e){if(!this.registeredAgents.has(e))return!1;let t=this.agentDomains.get(e);if(t){let n=this.teams.get(t);if(n){let i=n.teammateIds.indexOf(e);i>=0&&n.teammateIds.splice(i,1)}}return this.mailbox.deleteMailbox(e),this.subscriptions.delete(e),this.registeredAgents.delete(e),this.agentDomains.delete(e),!0}sendMessage(e,t,n,i,r){this.validateAgent(e,"sender"),this.validateAgent(t,"recipient");let s=this.agentDomains.get(e),o=r?.traceContext?Z(r.traceContext):r?.correlationId,c={id:Ht(),from:e,to:t,domain:r?.domain??s,type:n,payload:i,timestamp:Date.now(),correlationId:o,replyTo:r?.replyTo,ttl:r?.ttl??(this.config.defaultTtlMs>0?this.config.defaultTtlMs:void 0)};return this.mailbox.send(c),this.notifySubscribers(t,c),c}broadcast(e,t,n,i){let r=i?.from??"__system__";r!=="__system__"&&this.validateAgent(r,"broadcast sender");let s=i?.traceContext?Z(i.traceContext):i?.correlationId,o={id:Ht(),from:r,to:"broadcast",domain:e,type:t,payload:n,timestamp:Date.now(),correlationId:s,ttl:i?.ttl??(this.config.defaultTtlMs>0?this.config.defaultTtlMs:void 0)};this.mailbox.broadcast(e,o);let c=this.mailbox.getAgentsInDomain(e);for(let l of c)l!==r&&this.notifySubscribers(l,o);return o}onMessage(e,t){this.validateAgent(e,"subscription target");let n=this.subscriptions.get(e);return n||(n=[],this.subscriptions.set(e,n)),n.push(t),()=>{let i=this.subscriptions.get(e);if(i){let r=i.indexOf(t);r>=0&&i.splice(r,1)}}}getIdleAgents(e){let t=[],n=e?this.mailbox.getAgentsInDomain(e):Array.from(this.registeredAgents);for(let i of n)this.mailbox.peek(i)===0&&t.push(i);return t}isRegistered(e){return this.registeredAgents.has(e)}getAgentDomain(e){return this.agentDomains.get(e)}getRegisteredAgents(){return Array.from(this.registeredAgents)}getUnreadCount(e){return this.mailbox.peek(e)}receiveMessages(e){return this.mailbox.receive(e)}getMailboxService(){return this.mailbox}validateAgent(e,t){if(!this.registeredAgents.has(e))throw new Error(`Unknown ${t} '${e}'. Register the agent first with registerAgent() or createTeam().`)}notifySubscribers(e,t){let n=this.subscriptions.get(e);if(!(!n||n.length===0))for(let i of n)try{i(t)}catch{}}performCleanup(){let e=this.config.defaultTtlMs>0?this.config.defaultTtlMs*10:this.config.cleanupIntervalMs*60;this.mailbox.cleanup(e)}};function we(a){return new X(void 0,a)}var Ot={maxActiveTeams:13,defaultTeamSize:3,autoScaleEnabled:!1,scaleUpThreshold:10,scaleDownIdleMs:6e4},J=class a{static SYSTEM_AGENT_ID="__dtm_system__";static SYSTEM_DOMAIN="__system__";adapter;config;teams=new Map;systemAgentRegistered=!1;constructor(e,t){this.adapter=e,this.config={...Ot,...t}}createDomainTeam(e,t,n){if(this.teams.has(e))throw new Error(`Domain team already exists for '${e}'. Use getDomainTeam() to inspect the existing team.`);if(this.teams.size>=this.config.maxActiveTeams)throw new Error(`Maximum active teams (${this.config.maxActiveTeams}) reached. Remove an existing team before creating a new one.`);let i=n?[...n]:[],r=this.getMaxTeamSize(e);i.length+1>r&&(i.length=r-1);let s=Date.now(),o={domain:e,leadAgentId:t,teammateIds:i,createdAt:s,taskCount:0,completedCount:0,lastActivity:new Map};o.lastActivity.set(t,s);for(let l of i)o.lastActivity.set(l,s);this.teams.set(e,o);let c={domain:e,leadAgentId:t,maxTeammates:r-1,teammateIds:i,autoAssignEnabled:!1};return this.adapter.createTeam(c),this.toSnapshot(o)}removeDomainTeam(e){let t=this.teams.get(e);if(!t)return!1;for(let n of[t.leadAgentId,...t.teammateIds])this.adapter.unregisterAgent(n);return this.teams.delete(e),!0}getDomainTeam(e){let t=this.teams.get(e);return t?this.toSnapshot(t):void 0}addTeammate(e,t){let n=this.teams.get(e);if(!n||t===n.leadAgentId||n.teammateIds.includes(t))return!1;let i=this.getMaxTeamSize(e);return 1+n.teammateIds.length>=i?!1:(n.teammateIds.push(t),n.lastActivity.set(t,Date.now()),this.adapter.registerAgent(t,e),!0)}listDomainTeams(){return Array.from(this.teams.values(),e=>this.toSnapshot(e))}assignTaskToTeam(e,t,n){let i=this.teams.get(e);return i?(this.ensureSystemAgent(),this.adapter.sendMessage(a.SYSTEM_AGENT_ID,i.leadAgentId,"task-assignment",{taskId:t,payload:n},{domain:e}),i.taskCount++,i.lastActivity.set(i.leadAgentId,Date.now()),!0):!1}broadcastToDomain(e,t,n){let i=this.teams.get(e);if(!i)throw new Error(`No domain team found for '${e}'. Create a team first with createDomainTeam().`);this.adapter.broadcast(e,t,n,{from:"__system__"});let r=Date.now();i.lastActivity.set(i.leadAgentId,r);for(let s of i.teammateIds)i.lastActivity.set(s,r)}getTeamHealth(e){let t=this.teams.get(e);if(!t)return;let n=[t.leadAgentId,...t.teammateIds],i=n.length,r=0,s=0,o=0;for(let l of n)if(this.adapter.isRegistered(l)){r++;let u=this.adapter.getUnreadCount(l);o+=u,u===0&&s++}let c=t.taskCount-t.completedCount;return{domain:e,teamSize:i,activeAgents:r,idleAgents:s,pendingMessages:o,tasksPending:c,tasksCompleted:t.completedCount,healthy:r>0&&r===i&&c<this.config.scaleUpThreshold*2}}scaleTeam(e,t){let n=this.teams.get(e);if(!n)throw new Error(`No domain team found for '${e}'. Create a team first with createDomainTeam().`);let i=Math.max(this.getMaxTeamSize(e),t,this.config.maxActiveTeams),r=Math.max(1,Math.min(t,i)),s=1+n.teammateIds.length,o=[],c=[];if(r>s){let l=r-s;for(let u=0;u<l;u++){let d=`${e}-teammate-${Date.now()}-${u}`;n.teammateIds.push(d),n.lastActivity.set(d,Date.now()),this.adapter.registerAgent(d,e),o.push(d)}}else if(r<s){let l=s-r;for(let u=0;u<l;u++){let d=n.teammateIds.pop();d&&(n.lastActivity.delete(d),this.adapter.unregisterAgent(d),c.push(d))}}return{domain:e,previousSize:s,newSize:1+n.teammateIds.length,addedAgents:o,removedAgents:c}}getIdleTeammates(e){if(e){let n=this.teams.get(e);return n?this.getIdleAgentsForTeam(n):[]}let t=[];for(let n of this.teams.values())t.push(...this.getIdleAgentsForTeam(n));return t}rebalance(){let e=[],t=new Set,n=Array.from(this.teams.values(),s=>{let o=this.getTargetTeamSize(s.domain),c=1+s.teammateIds.length,l=this.getIdleAgentsForTeam(s).filter(u=>u!==s.leadAgentId);return{domain:s.domain,team:s,currentSize:c,targetSize:o,idleTeammates:l}}),i=n.filter(s=>s.currentSize>s.targetSize&&s.idleTeammates.length>0).sort((s,o)=>o.currentSize-o.targetSize-(s.currentSize-s.targetSize)),r=n.filter(s=>s.currentSize<s.targetSize).sort((s,o)=>s.currentSize-s.targetSize-(o.currentSize-o.targetSize));for(let s of i)for(let o of r){if(o.currentSize>=o.targetSize)continue;if(s.idleTeammates.length===0)break;if(o.currentSize>=this.getMaxTeamSize(o.domain))continue;let c=s.idleTeammates.shift(),l=s.team.teammateIds.indexOf(c);l>=0&&s.team.teammateIds.splice(l,1),s.team.lastActivity.delete(c),s.currentSize--,this.adapter.unregisterAgent(c),this.adapter.registerAgent(c,o.domain),o.team.teammateIds.push(c),o.team.lastActivity.set(c,Date.now()),o.currentSize++,e.push({agentId:c,fromDomain:s.domain,toDomain:o.domain}),t.add(s.domain),t.add(o.domain)}return{moves:e,teamsAffected:t.size}}dispose(){for(let e of this.teams.values())for(let t of[e.leadAgentId,...e.teammateIds])this.adapter.unregisterAgent(t);this.teams.clear(),this.systemAgentRegistered&&(this.adapter.unregisterAgent(a.SYSTEM_AGENT_ID),this.systemAgentRegistered=!1)}markTaskCompleted(e){let t=this.teams.get(e);return t?(t.completedCount<t.taskCount&&t.completedCount++,!0):!1}ensureSystemAgent(){this.systemAgentRegistered||(this.adapter.registerAgent(a.SYSTEM_AGENT_ID,a.SYSTEM_DOMAIN),this.systemAgentRegistered=!0)}getMaxTeamSize(e){return this.config.domainTeamSizes&&e in this.config.domainTeamSizes?this.config.domainTeamSizes[e]:this.config.defaultTeamSize}getTargetTeamSize(e){return this.getMaxTeamSize(e)}getIdleAgentsForTeam(e){let t=[];for(let n of[e.leadAgentId,...e.teammateIds])this.adapter.isRegistered(n)&&this.adapter.getUnreadCount(n)===0&&t.push(n);return t}toSnapshot(e){return{domain:e.domain,leadAgentId:e.leadAgentId,teammateIds:[...e.teammateIds],createdAt:e.createdAt,taskCount:e.taskCount,completedCount:e.completedCount}}};function Me(a,e){return new J(a,e)}k();var te={failureThreshold:3,resetTimeoutMs:6e4,halfOpenSuccessThreshold:2,failureWindowMs:12e4,cascadeEnabled:!1,cascadeTargets:void 0},ee=class extends Error{domain;retryAfterMs;constructor(e,t){let n=t!=null?` (retry after ${t}ms)`:"";super(`Circuit breaker is open for domain '${e}'${n}`),this.name="DomainCircuitOpenError",this.domain=e,this.retryAfterMs=t}},A=class{state="closed";failures=[];totalRequests=0;totalSuccesses=0;totalFailures=0;rejectedCount=0;lastFailureTime;lastSuccessTime;openedAt;halfOpenSuccesses=0;config;stateChangeHandlers=new Set;domain;constructor(e,t){this.domain=e,this.config={...te,...t}}canExecute(){let e=this.getState();return e==="closed"?!0:e!=="open"}async execute(e){if(this.totalRequests++,this.getState()==="open")throw this.rejectedCount++,this.emitEvent({type:"request-rejected",domain:this.domain,timestamp:Date.now(),metadata:{retryAfterMs:this.getTimeUntilTransition()}}),new ee(this.domain,this.getTimeUntilTransition());try{let n=await e();return this.recordSuccess(),n}catch(n){throw this.recordFailure(nt(n)),n}}recordSuccess(){this.totalSuccesses++,this.lastSuccessTime=Date.now(),this.getState()==="half-open"&&(this.halfOpenSuccesses++,console.log(`[DomainCircuitBreaker:${this.domain}] Half-open success ${this.halfOpenSuccesses}/${this.config.halfOpenSuccessThreshold}`),this.halfOpenSuccesses>=this.config.halfOpenSuccessThreshold&&this.transitionTo("closed"))}recordFailure(e){this.totalFailures++,this.lastFailureTime=Date.now(),this.failures.push({timestamp:Date.now(),message:e.message}),this.cleanOldFailures();let t=this.getState();if(t==="half-open"){console.log(`[DomainCircuitBreaker:${this.domain}] Failure in half-open state, re-opening`),this.transitionTo("open");return}t==="closed"&&this.failures.length>=this.config.failureThreshold&&(console.log(`[DomainCircuitBreaker:${this.domain}] Failure threshold reached (${this.failures.length}/${this.config.failureThreshold}), opening circuit`),this.transitionTo("open"))}getState(){return this.state==="open"&&this.openedAt!=null&&Date.now()-this.openedAt>=this.config.resetTimeoutMs&&this.transitionTo("half-open"),this.state}getStats(){let e=this.getState();return{domain:this.domain,state:e,totalRequests:this.totalRequests,successCount:this.totalSuccesses,failureCount:this.totalFailures,rejectedCount:this.rejectedCount,lastFailureTime:this.lastFailureTime,lastSuccessTime:this.lastSuccessTime,openedAt:this.openedAt,timeUntilHalfOpen:e==="open"?this.getTimeUntilTransition():void 0,consecutiveSuccesses:this.halfOpenSuccesses}}reset(){let e=this.state;this.state="closed",this.failures=[],this.halfOpenSuccesses=0,this.openedAt=void 0,e!=="closed"&&(console.log(`[DomainCircuitBreaker:${this.domain}] Manually reset from '${e}' to 'closed'`),this.emitEvent({type:"state-change",domain:this.domain,previousState:e,newState:"closed",timestamp:Date.now(),metadata:{trigger:"manual-reset"}}))}forceOpen(){console.log(`[DomainCircuitBreaker:${this.domain}] Force-opening circuit`),this.transitionTo("open")}getRecentFailures(e=5){return this.failures.slice(-e).map(t=>`[${new Date(t.timestamp).toISOString()}] ${t.message}`)}onStateChange(e){return this.stateChangeHandlers.add(e),()=>{this.stateChangeHandlers.delete(e)}}getConfig(){return this.config}transitionTo(e){let t=this.state;if(t!==e){switch(this.state=e,e){case"open":this.openedAt=Date.now(),this.halfOpenSuccesses=0;break;case"half-open":this.halfOpenSuccesses=0,console.log(`[DomainCircuitBreaker:${this.domain}] Transitioning to half-open, allowing probe requests`);break;case"closed":this.failures=[],this.openedAt=void 0,this.halfOpenSuccesses=0,console.log(`[DomainCircuitBreaker:${this.domain}] Circuit closed, domain is healthy`);break}this.emitEvent({type:"state-change",domain:this.domain,previousState:t,newState:e,timestamp:Date.now()})}}cleanOldFailures(){let e=Date.now()-this.config.failureWindowMs;this.failures=this.failures.filter(t=>t.timestamp>e)}getTimeUntilTransition(){if(this.state==="open"&&this.openedAt!=null){let e=Date.now()-this.openedAt,t=this.config.resetTimeoutMs-e;return Math.max(0,t)}}emitEvent(e){for(let t of this.stateChangeHandlers)try{t(e)}catch(n){console.log(`[DomainCircuitBreaker:${this.domain}] State change handler error: ${h(n)}`)}}};k();var Ie={critical:{failureThreshold:2,resetTimeoutMs:3e4,halfOpenSuccessThreshold:2,failureWindowMs:6e4,cascadeEnabled:!1,cascadeTargets:void 0},standard:{failureThreshold:3,resetTimeoutMs:6e4,halfOpenSuccessThreshold:2,failureWindowMs:12e4,cascadeEnabled:!1,cascadeTargets:void 0},lenient:{failureThreshold:5,resetTimeoutMs:12e4,halfOpenSuccessThreshold:3,failureWindowMs:3e5,cascadeEnabled:!1,cascadeTargets:void 0}},Nt={"test-generation":"critical","test-execution":"critical","coverage-analysis":"critical","quality-assessment":"critical","security-compliance":"critical","defect-intelligence":"standard","requirements-validation":"standard","code-intelligence":"standard","contract-testing":"standard","visual-accessibility":"lenient","chaos-resilience":"lenient","learning-optimization":"lenient","enterprise-integration":"standard"},N=class{breakers=new Map;defaultConfig;globalHandlers=new Set;constructor(e){this.defaultConfig={...te,...e}}getBreaker(e){let t=this.breakers.get(e);if(!t){let n=Nt[e],i=n?{...this.defaultConfig,...Ie[n]}:this.defaultConfig;t=new A(e,i),this.breakers.set(e,t),t.onStateChange(r=>this.handleBreakerEvent(r)),console.log(`[DomainBreakerRegistry] Created breaker for '${e}' (criticality: ${n??"default"})`)}return t}configureBreaker(e,t){let n={...this.defaultConfig,...t},i=new A(e,n);i.onStateChange(r=>this.handleBreakerEvent(r)),this.breakers.set(e,i),console.log(`[DomainBreakerRegistry] Reconfigured breaker for '${e}'`)}configureCriticality(e,t){let n=Ie[t];this.configureBreaker(e,n),console.log(`[DomainBreakerRegistry] Set '${e}' criticality to '${t}'`)}canExecuteInDomain(e){return this.getBreaker(e).canExecute()}async executeInDomain(e,t){return this.getBreaker(e).execute(t)}getAllStats(){let e=new Map;for(let[t,n]of this.breakers)e.set(t,n.getStats());return e}getOpenDomains(){let e=[];for(let[t,n]of this.breakers)n.getState()==="open"&&e.push(t);return e}getHealthyDomains(){let e=[];for(let[t,n]of this.breakers)n.getState()==="closed"&&e.push(t);return e}getDegradedDomains(){let e=[];for(let[t,n]of this.breakers)n.getState()==="half-open"&&e.push(t);return e}getHealthSummary(){let e=0,t=0,n=0;for(let i of this.breakers.values())switch(i.getState()){case"closed":e++;break;case"half-open":t++;break;case"open":n++;break}return{healthy:e,degraded:t,open:n,total:this.breakers.size}}resetAll(){for(let e of this.breakers.values())e.reset();console.log(`[DomainBreakerRegistry] Reset all ${this.breakers.size} breakers`)}reset(e){let t=this.breakers.get(e);t&&t.reset()}onAnyStateChange(e){return this.globalHandlers.add(e),()=>{this.globalHandlers.delete(e)}}handleBreakerEvent(e){for(let t of this.globalHandlers)try{t(e)}catch(n){console.log(`[DomainBreakerRegistry] Global handler error: ${h(n)}`)}e.type==="state-change"&&e.newState==="open"&&this.propagateCascade(e.domain)}propagateCascade(e){let t=this.breakers.get(e);if(!t)return;let n=t.getConfig();if(!(!n.cascadeEnabled||!n.cascadeTargets?.length))for(let i of n.cascadeTargets){if(i===e)continue;let r=this.getBreaker(i);if(r.getState()!=="open"){console.log(`[DomainBreakerRegistry] Cascading open from '${e}' to '${i}'`),r.forceOpen();let o={type:"cascade-triggered",domain:i,timestamp:Date.now(),metadata:{sourceDomain:e,cascadedFrom:e}};for(let c of this.globalHandlers)try{c(o)}catch(l){console.log(`[DomainBreakerRegistry] Cascade event handler error: ${h(l)}`)}}}}};function Lt(a){return new N(a)}var x=["smoke","standard","deep","crisis"];var L=["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","requirements-validation","code-intelligence","security-compliance","contract-testing","visual-accessibility","chaos-resilience","learning-optimization","enterprise-integration"],ne=["test-generation","coverage-analysis","quality-assessment"],Re={"test-generation":["generator","specialist"],"test-execution":["tester","coordinator"],"coverage-analysis":["analyzer","specialist"],"quality-assessment":["analyzer","validator"],"defect-intelligence":["analyzer","specialist"],"requirements-validation":["validator","reviewer"],"code-intelligence":["analyzer","specialist"],"security-compliance":["analyzer","validator"],"contract-testing":["tester","validator"],"visual-accessibility":["tester","validator"],"chaos-resilience":["tester","specialist"],"learning-optimization":["optimizer","specialist"],"enterprise-integration":["coordinator","validator"]},Bn={tier:"smoke",maxAgents:3,agentTeamsEnabled:!1,domains:["test-execution","quality-assessment"],estimatedCost:"minimal",description:"Lightweight smoke test on every commit. Runs core test execution and quality assessment with minimal agent count to catch obvious regressions quickly.",triggers:[{type:"commit"},{type:"schedule",conditions:{interval:"hourly"}}]},$n={tier:"standard",maxAgents:7,agentTeamsEnabled:!1,domains:["test-generation","test-execution","coverage-analysis","quality-assessment","security-compliance"],estimatedCost:"moderate",description:"Standard validation for pull requests. Covers test generation, execution, coverage, quality, and security across up to 7 agents. Agent teams are optional.",triggers:[{type:"pr"},{type:"manual"}]},Un={tier:"deep",maxAgents:15,agentTeamsEnabled:!0,domains:[...L],estimatedCost:"high",description:"Deep validation for pre-release and critical path changes. Activates all 13 domains with up to 15 agents and full agent team collaboration.",triggers:[{type:"release"},{type:"pr",conditions:{criticalPath:!0}},{type:"manual",conditions:{requestedTier:"deep"}}]},qn={tier:"crisis",maxAgents:15,agentTeamsEnabled:!0,domains:[...L],estimatedCost:"unlimited",description:"Crisis response for production incidents. All domains active with competing hypotheses enabled. Unlimited cost budget to resolve incidents as fast as possible.",triggers:[{type:"incident"},{type:"manual",conditions:{requestedTier:"crisis"}}]},_e={smoke:Bn,standard:$n,deep:Un,crisis:qn};var zn=["password","secret","token","crypto","auth","credential","jwt","oauth"],Gn=["async","await","Promise","setTimeout","setInterval","Worker","mutex","lock"],jn={securityKeywords:zn,concurrencyKeywords:Gn,enableDimensionOverrides:!1};function Wn(a,e){let t=a+e;return t<=8?"trivial":t<=20?"simple":t<=40?"moderate":t<=70?"complex":"critical"}var Q=class{config;constructor(e){this.config={...jn,...e}}analyzeExtendedDimensions(e){let t=e.split(`
167
+ `),n=Math.max(t.length,1),i=this.countKeywordLines(t,this.config.securityKeywords),r=ie(i/n,0,1),s=this.countKeywordLines(t,this.config.concurrencyKeywords),o=ie(s/n,0,1),c=this.countPatternMatches(e,/\.(map|filter|reduce|flatMap|forEach)\s*\(/g),l=ie(c/n,0,1),u=this.countPatternMatches(e,/^export\s/gm),d=Math.max(this.countPatternMatches(e,/^(export\s+)?(const|let|var|function|class|interface|type|enum)\s/gm),1),g=ie(u/d,0,1);return{securitySurface:r,concurrency:o,dataFlow:l,apiSurface:g}}compose(e,t,n){let i=Wn(e.cyclomatic,e.cognitive),r=this.analyzeExtendedDimensions(n),s=[],o=[],c;switch(i){case"trivial":case"simple":s.push({agentType:"qe-test-generator",priority:1,reason:`${i} complexity \u2014 basic test generation sufficient`}),o.push("unit"),c="haiku";break;case"moderate":s.push({agentType:"qe-test-generator",priority:1,reason:"Moderate complexity requires thorough test generation"},{agentType:"qe-code-intelligence",priority:2,reason:"Moderate complexity benefits from code intelligence analysis"}),o.push("unit","integration"),c="sonnet";break;case"complex":s.push({agentType:"qe-test-generator",priority:1,reason:"Complex code needs comprehensive test generation"},{agentType:"qe-security-scanner",priority:2,reason:"High complexity warrants security analysis"},{agentType:"qe-code-intelligence",priority:2,reason:"Complex code requires deep code intelligence"}),o.push("unit","integration","security"),c="sonnet";break;case"critical":s.push({agentType:"qe-test-generator",priority:1,reason:"Critical complexity demands full test generation"},{agentType:"qe-security-scanner",priority:1,reason:"Critical complexity mandates security scanning"},{agentType:"qe-code-intelligence",priority:1,reason:"Critical complexity requires deep analysis"},{agentType:"qe-chaos-resilience",priority:2,reason:"Critical systems need chaos/resilience testing"},{agentType:"qe-performance",priority:2,reason:"Critical complexity warrants performance analysis"}),o.push("unit","integration","security","chaos","performance"),c="opus";break}return r.securitySurface>.3&&(s.some(l=>l.agentType==="qe-security-scanner")||s.push({agentType:"qe-security-scanner",priority:2,reason:`High security surface (${(r.securitySurface*100).toFixed(0)}%) \u2014 security scanning recommended`}),o.includes("security")||o.push("security")),r.concurrency>.3&&(s.some(l=>l.agentType==="qe-chaos-resilience")||s.push({agentType:"qe-chaos-resilience",priority:2,reason:`High concurrency (${(r.concurrency*100).toFixed(0)}%) \u2014 chaos/resilience testing recommended`}),o.includes("chaos")||o.push("chaos")),r.apiSurface>.5&&(o.includes("integration")||o.push("integration")),s.sort((l,u)=>l.priority-u.priority),{agents:s,testTypes:o,recommendedTier:c,complexityCategory:i}}countKeywordLines(e,t){let n=0;for(let i of e)for(let r of t)if(i.includes(r)){n++;break}return n}countPatternMatches(e,t){let n=e.match(t);return n?n.length:0}};function ie(a,e,t){return Math.max(e,Math.min(t,a))}var Qt=200,Bt=10,$t=3,re=class{configs;history=[];escalationCount=0;deescalationCount=0;constructor(e){this.configs={..._e,...e}}selectTier(e){let t,n;if(e.manualOverride)return t=e.manualOverride,n=`Manual override to "${t}" tier`,this.buildResult(t,n,e);if(e.trigger==="incident"||e.isHotfix)return t="crisis",n=e.isHotfix?"Hotfix deployment triggers crisis-level validation":"Production incident triggers crisis-level response",this.buildResult(t,n,e);if(e.trigger==="release")return t="deep",n="Pre-release validation requires deep tier across all domains",this.buildResult(t,n,e);if(e.trigger==="pr"){let i=e.changedFiles!==void 0&&e.changedFiles>Bt,r=e.affectedDomains!==void 0&&e.affectedDomains.length>$t;if(i||r){t="deep";let s=[];return i&&s.push(`>${Bt} changed files (${e.changedFiles})`),r&&s.push(`>${$t} affected domains (${e.affectedDomains.length})`),n=`PR escalated to deep tier: ${s.join(" and ")}`,this.buildResult(t,n,e)}return t="standard",n="Pull request triggers standard tier validation",this.buildResult(t,n,e)}return t="smoke",n=e.trigger==="commit"?"Commit triggers lightweight smoke validation":`Trigger "${e.trigger}" defaults to smoke tier`,this.buildResult(t,n,e)}allocateAgents(e,t){let n=this.resolveTargetDomains(e,t);if(n.length===0)return[];let i=e.maxAgents;return n.length>=i?this.allocateWithPriority(n,i):this.allocateWithSurplus(n,i)}escalate(e,t){let n=x.indexOf(e),i=Math.min(n+1,x.length-1),r=x[i],s=e!==r,o=s?`Escalated from "${e}" to "${r}": ${t}`:`Already at maximum tier "${e}", cannot escalate further`;return s&&this.escalationCount++,this.buildResult(r,o,{trigger:"manual"})}deescalate(e){let t=x.indexOf(e),n=Math.max(t-1,0),i=x[n],r=e!==i,s=r?`De-escalated from "${e}" to "${i}"`:`Already at minimum tier "${e}", cannot de-escalate further`;return r&&this.deescalationCount++,this.buildResult(i,s,{trigger:"manual"})}getStats(){let e={smoke:0,standard:0,deep:0,crisis:0};for(let t of this.history)e[t.tier]++;return{totalSelections:this.history.length,selectionsByTier:e,escalationCount:this.escalationCount,deescalationCount:this.deescalationCount,recentSelections:[...this.history].slice(-20)}}_teamComposer;setTeamComposer(e){this._teamComposer=e}selectTierWithComposition(e,t,n){let i=this.selectTier(e);if(!t||!n)return{...i,composition:void 0};let s=(this._teamComposer??new Q).compose(t,i.selectedTier,n);return{...i,composition:s}}buildResult(e,t,n){let i=this.configs[e],r=this.allocateAgents(i,n.affectedDomains),s={tier:e,reason:t,timestamp:Date.now(),trigger:n.trigger};return this.history.push(s),this.history.length>Qt&&this.history.splice(0,this.history.length-Qt),{selectedTier:e,config:i,reason:t,agentAllocation:r}}resolveTargetDomains(e,t){let n=e.domains.includes("all")?L:e.domains;if(!t||t.length===0)return[...n];let i=new Set(n),r=t.filter(s=>i.has(s));return r.length>0?r:[...n]}allocateWithPriority(e,t){let n=new Set(ne),i=[],r=t,s=e.filter(c=>n.has(c)),o=e.filter(c=>!n.has(c));for(let c of s){if(r<=0)break;i.push(this.createAllocation(c,1)),r--}for(let c of o){if(r<=0)break;i.push(this.createAllocation(c,1)),r--}return i}allocateWithSurplus(e,t){let n=new Set(ne),i=new Map;for(let u of e)i.set(u,1);let r=t-e.length,s=e.filter(u=>n.has(u)),o=e.filter(u=>!n.has(u)),c=0;for(;r>0&&s.length>0;){let u=s[c%s.length];if(i.set(u,(i.get(u)??0)+1),r--,c++,c>=s.length*2)break}let l=0;for(;r>0&&o.length>0;){let u=o[l%o.length];i.set(u,(i.get(u)??0)+1),r--,l++}for(;r>0&&s.length>0;){let u=s[c%s.length];i.set(u,(i.get(u)??0)+1),r--,c++}return e.map(u=>this.createAllocation(u,i.get(u)??1))}createAllocation(e,t){let n=Re[e]??["specialist"];return{domain:e,agentCount:t,agentTypes:[...n]}}};function Pe(a){return new re(a)}k();var ae={enabled:!0,minQualityScore:.6,rejectOnFailure:!0,gates:[{name:"test-pass-rate",type:"test-pass-rate",threshold:.8,weight:.35,required:!0},{name:"coverage",type:"coverage",threshold:0,weight:.25,required:!1},{name:"security",type:"security",threshold:0,weight:.25,required:!0},{name:"performance",type:"performance",threshold:3e4,weight:.15,required:!1}]},se=class{config;constructor(e={}){this.config={...ae,...e},e.gates&&(this.config={...this.config,gates:e.gates})}evaluate(e){if(!this.config.enabled)return console.log("[QualityGateEnforcer] Gates disabled, auto-passing"),{passed:!0,score:1,exitCode:0,gates:[],reason:"Quality gates disabled"};if(e.status==="failed")return console.log(`[QualityGateEnforcer] Task ${e.taskId} has failed status`),{passed:!1,score:0,exitCode:this.config.rejectOnFailure?2:0,gates:[],reason:"Task reported failed status"};let t=[],n=[];for(let d of this.config.gates){let g=this.checkGate(d,e);t.push(g),!g.passed&&d.required&&n.push(d.name)}let i=this.config.gates.reduce((d,g)=>d+g.weight,0),r=i>0?t.reduce((d,g)=>{let p=this.config.gates.find(z=>z.name===g.gate);if(!p)return d;let f=g.passed?1:this.computePartialScore(g);return d+f*(p.weight/i)},0):1,s=n.length>0,o=r<this.config.minQualityScore,c=!s&&!o,l;if(!c){let d=[];s&&d.push(`Required gates failed: ${n.join(", ")}`),o&&d.push(`Score ${r.toFixed(3)} below minimum ${this.config.minQualityScore}`),l=d.join("; ")}let u=!c&&this.config.rejectOnFailure?2:0;return console.log(`[QualityGateEnforcer] Task ${e.taskId}: ${c?"PASSED":"FAILED"} (score=${r.toFixed(3)}, gates=${t.filter(d=>d.passed).length}/${t.length})`),{passed:c,score:r,exitCode:u,gates:t,reason:l}}getConfig(){return{...this.config}}checkGate(e,t){let n=this.extractMetricForGate(e,t),i=this.meetsThreshold(e,n);return{gate:e.name,passed:i,actual:n,threshold:e.threshold,weight:e.weight}}extractMetricForGate(e,t){let n=t.metrics;switch(e.type){case"coverage":return n.coverageChange??0;case"test-pass-rate":{let i=n.testsPassed??0,r=n.testsFailed??0,s=i+r;return s>0?i/s:1}case"security":return n.securityIssues??0;case"performance":return n.performanceMs??t.duration;case"custom":{let i=t.output[e.name];return typeof i=="number"?i:0}default:return 0}}meetsThreshold(e,t){switch(e.type){case"security":return t<=e.threshold;case"performance":return t<=e.threshold;default:return t>=e.threshold}}computePartialScore(e){let t=this.config.gates.find(n=>n.name===e.gate);if(!t)return 0;switch(t.type){case"security":case"performance":{if(t.threshold===0)return 0;let n=t.threshold/e.actual;return Math.max(0,Math.min(1,n))}default:{if(t.threshold===0)return 1;let n=e.actual/t.threshold;return Math.max(0,Math.min(1,n))}}}};var Vn={trainPatterns:!0,qualityGate:ae,patternDomains:["test-generation","coverage-analysis","security-compliance","quality-assessment","defect-intelligence","contract-testing"],emitEvents:!0,maxPatternsPerTask:5},Kn={"test-generation":{types:["test-template","assertion-pattern","mock-pattern"],contentKeys:["testCode","template","assertions","mocks"],baseConfidence:.6},"coverage-analysis":{types:["coverage-strategy","mutation-strategy"],contentKeys:["coverageReport","gaps","strategy","recommendations"],baseConfidence:.55},"security-compliance":{types:["security-pattern","vulnerability-fix"],contentKeys:["findings","fixes","recommendations","rules"],baseConfidence:.5},"quality-assessment":{types:["quality-rule","threshold-pattern"],contentKeys:["rules","thresholds","assessments"],baseConfidence:.5},"defect-intelligence":{types:["defect-pattern","root-cause"],contentKeys:["rootCause","pattern","prediction","analysis"],baseConfidence:.45},"contract-testing":{types:["api-contract","schema-pattern"],contentKeys:["contract","schema","endpoints","violations"],baseConfidence:.55},"test-execution":{types:["flaky-fix","retry-strategy"],contentKeys:["flakyTests","retryPolicy","stabilization"],baseConfidence:.5},"visual-accessibility":{types:["visual-baseline","a11y-check"],contentKeys:["baseline","violations","wcagResults"],baseConfidence:.5},"chaos-resilience":{types:["perf-benchmark","resilience-pattern"],contentKeys:["benchmark","faultInjection","recoveryTime"],baseConfidence:.45}},oe=class{config;gateEnforcer;patternStore;completionHandlers=new Set;stats={totalProcessed:0,accepted:0,rejected:0,patternsExtracted:0};constructor(e={},t){this.config={...Vn,...e},e.qualityGate&&(this.config={...this.config,qualityGate:{...ae,...e.qualityGate}}),this.gateEnforcer=new se(this.config.qualityGate),this.patternStore=t??null}async onTaskCompleted(e){this.stats.totalProcessed++,console.log(`[TaskCompletedHook] Processing task ${e.taskId} (agent=${e.agentId}, domain=${e.domain}, status=${e.status})`);let t=this.gateEnforcer.evaluate(e);if(!t.passed&&this.config.qualityGate.rejectOnFailure){this.stats.rejected++;let r={action:"reject",exitCode:2,reason:t.reason||"Quality gate check failed",gateResult:t};return console.log(`[TaskCompletedHook] Task ${e.taskId} REJECTED: ${r.reason}`),this.emitCompletion(e.taskId,r),r}let n=0;if(this.config.trainPatterns&&this.patternStore){let r=this.extractPatterns(e);n=await this.storePatterns(r,e),this.stats.patternsExtracted+=n}this.stats.accepted++;let i={action:"accept",patternsExtracted:n};return console.log(`[TaskCompletedHook] Task ${e.taskId} ACCEPTED (score=${t.score.toFixed(3)}, patterns=${n})`),this.emitCompletion(e.taskId,i),i}extractPatterns(e){let t=[],n=e.domain;if(!this.config.patternDomains.includes(n))return t;let i=Kn[n];if(!i)return this.extractGenericPatterns(e);let r=this.computeConfidenceBoost(e.metrics);for(let s of i.types){if(t.length>=this.config.maxPatternsPerTask)break;for(let o of i.contentKeys){if(t.length>=this.config.maxPatternsPerTask)break;let c=e.output[o];if(c==null)continue;let l=typeof c=="string"?c:JSON.stringify(c);if(l.length<10)continue;let u=Math.min(1,i.baseConfidence+r);t.push({domain:n,type:s,content:l,confidence:u,metadata:{sourceTaskId:e.taskId,sourceAgent:e.agentId,taskType:e.type,duration:e.duration,extractedFrom:o,timestamp:e.timestamp}})}}return t}onCompletion(e){this.completionHandlers.add(e)}offCompletion(e){this.completionHandlers.delete(e)}getStats(){return{...this.stats}}resetStats(){this.stats={totalProcessed:0,accepted:0,rejected:0,patternsExtracted:0}}async storePatterns(e,t){if(!this.patternStore||e.length===0)return 0;let n=0;for(let i of e)try{let r=await this.patternStore.store(i),s=t.status==="completed";await this.patternStore.recordOutcome(r,s),n++}catch(r){console.error(`[TaskCompletedHook] Failed to store pattern: ${h(r)}`)}return n>0&&console.log(`[TaskCompletedHook] Stored ${n}/${e.length} patterns from task ${t.taskId}`),n}extractGenericPatterns(e){let t=[];for(let[n,i]of Object.entries(e.output)){if(t.length>=this.config.maxPatternsPerTask)break;if(i==null)continue;let r=typeof i=="string"?i:JSON.stringify(i);r.length<10||t.push({domain:e.domain,type:"generic",content:r,confidence:.3+this.computeConfidenceBoost(e.metrics),metadata:{sourceTaskId:e.taskId,sourceAgent:e.agentId,taskType:e.type,extractedFrom:n,timestamp:e.timestamp}})}return t}computeConfidenceBoost(e){let t=0,n=e.testsPassed??0,i=e.testsFailed??0,r=n+i;return r>0&&(t+=n/r*.15),e.coverageChange!==void 0&&e.coverageChange>0&&(t+=Math.min(.1,e.coverageChange*.5)),e.securityIssues!==void 0&&e.securityIssues===0&&(t+=.1),e.performanceMs!==void 0&&e.performanceMs<5e3&&(t+=.05),Math.min(.4,t)}emitCompletion(e,t){if(this.config.emitEvents)for(let n of this.completionHandlers)try{n(e,t)}catch(i){console.error(`[TaskCompletedHook] Completion handler error: ${h(i)}`)}}};k();var Yn={"test-template":"test-template","assertion-pattern":"assertion-pattern","mock-pattern":"mock-pattern","coverage-strategy":"coverage-strategy","mutation-strategy":"mutation-strategy","security-pattern":"error-handling","vulnerability-fix":"error-handling","quality-rule":"test-template","threshold-pattern":"test-template","defect-pattern":"error-handling","root-cause":"error-handling","api-contract":"api-contract","schema-pattern":"api-contract","flaky-fix":"flaky-fix","retry-strategy":"flaky-fix","visual-baseline":"visual-baseline","a11y-check":"a11y-check","perf-benchmark":"perf-benchmark","resilience-pattern":"perf-benchmark",generic:"test-template"};function Zn(a){return Yn[a]??"test-template"}function Xn(a){let e=he(a.domain);if(e)return e;let t=he(a.content);return t||"test-generation"}function Jn(a){let e=0;for(let t=0;t<a.length;t++){let n=a.charCodeAt(t);e=(e<<5)-e+n,e=e&e}return Math.abs(e).toString(36).slice(0,8)}var ce=class{constructor(e){this.reasoningBank=e}reasoningBank;async store(e){let t=Xn(e),n=Zn(e.type),i=Jn(e.content),r=`${t}-${e.type}-${i}`,s=[t,e.type,...e.metadata.sourceTaskId?[`task:${e.metadata.sourceTaskId}`]:[]],o={patternType:n,name:r,description:`Auto-extracted ${e.type} pattern from ${e.domain} domain`,template:{type:"prompt",content:e.content,variables:[]},context:{tags:s},confidence:e.confidence};try{let c=await this.reasoningBank.storePattern(o);if(c.success)return c.value.id;throw console.error(`[ReasoningBankPatternStore] Failed to store pattern: ${c.error.message}`),c.error}catch(c){throw console.error(`[ReasoningBankPatternStore] Store error: ${h(c)}`),c}}async recordOutcome(e,t){let n={patternId:e,success:t};try{let i=await this.reasoningBank.recordOutcome(n);i.success||console.error(`[ReasoningBankPatternStore] Failed to record outcome: ${i.error.message}`)}catch(i){console.error(`[ReasoningBankPatternStore] recordOutcome error: ${h(i)}`)}}};un();var Fe={maxHypothesesPerInvestigation:5,convergenceThreshold:.2,investigationTimeoutMs:3e5,minEvidenceForConvergence:3,autoRejectThreshold:.15};import{randomUUID as He}from"node:crypto";var le=class{investigations=new Map;config;constructor(e){this.config={...Fe,...e}}createInvestigation(e,t,n){let i=`inv-${He().slice(0,8)}`,r=Date.now(),s={id:i,taskId:e,domain:t,description:n,hypotheses:[],status:"open",maxHypotheses:this.config.maxHypothesesPerInvestigation,convergenceThreshold:this.config.convergenceThreshold,createdAt:r,updatedAt:r};return this.investigations.set(i,s),this.toSnapshot(s)}addHypothesis(e,t,n,i){let r=this.getInvestigationMutable(e);if(r.hypotheses.length>=r.maxHypotheses)throw new Error(`Investigation ${e} already has ${r.maxHypotheses} hypotheses (max)`);let s={id:`hyp-${He().slice(0,8)}`,description:t,investigatorAgentId:i,strategy:n,status:"pending",evidence:[],confidenceScore:.5,createdAt:Date.now(),updatedAt:Date.now()};return r.hypotheses.push(s),r.updatedAt=Date.now(),r.status==="open"&&(r.status="investigating"),s}startHypothesis(e,t){let n=this.getInvestigationMutable(e),i=this.findHypothesis(n,t);if(i.status!=="pending")throw new Error(`Hypothesis ${t} cannot be started (current status: ${i.status})`);i.status="investigating",i.updatedAt=Date.now(),n.updatedAt=Date.now()}completeHypothesis(e,t){let n=this.getInvestigationMutable(e),i=this.findHypothesis(n,t);i.status="completed",i.updatedAt=Date.now(),n.updatedAt=Date.now()}submitEvidence(e,t,n){let i=this.getInvestigationMutable(e),r=this.findHypothesis(i,t),s={...n,id:`evi-${He().slice(0,8)}`,hypothesisId:t,timestamp:Date.now()};return r.evidence.push(s),r.confidenceScore=this.calculateConfidence(r),r.updatedAt=Date.now(),i.updatedAt=Date.now(),r.confidenceScore<this.config.autoRejectThreshold&&r.evidence.length>=2&&(r.status="rejected"),s}converge(e){let t=this.getInvestigationMutable(e),n=t.hypotheses.reduce((l,u)=>l+u.evidence.length,0);if(n<this.config.minEvidenceForConvergence){t.status="inconclusive";let l={winningHypothesisId:null,confidence:0,evidenceSummary:`Insufficient evidence (${n}/${this.config.minEvidenceForConvergence} required)`,rejectedHypotheses:t.hypotheses.filter(u=>u.status==="rejected").map(u=>u.id),method:"evidence-scoring"};return t.convergenceResult=l,t.updatedAt=Date.now(),l}let i=[...t.hypotheses].filter(l=>l.status!=="rejected").sort((l,u)=>u.confidenceScore-l.confidenceScore),r="evidence-scoring",s=null,o=0;i.length===0?t.status="inconclusive":i.length===1?(s=i[0].id,o=i[0].confidenceScore,r="unanimous",t.status="converged"):i[0].confidenceScore-i[1].confidenceScore>=t.convergenceThreshold?(s=i[0].id,o=i[0].confidenceScore,t.status="converged"):t.status="inconclusive";let c={winningHypothesisId:s,confidence:o,evidenceSummary:this.buildEvidenceSummary(t),rejectedHypotheses:t.hypotheses.filter(l=>l.status==="rejected").map(l=>l.id),method:r};return t.convergenceResult=c,t.updatedAt=Date.now(),c}getInvestigation(e){let t=this.investigations.get(e);return t?this.toSnapshot(t):void 0}listInvestigations(){return Array.from(this.investigations.values()).map(e=>this.toSnapshot(e))}getConfig(){return this.config}dispose(){this.investigations.clear()}getInvestigationMutable(e){let t=this.investigations.get(e);if(!t)throw new Error(`Investigation ${e} not found`);return t}findHypothesis(e,t){let n=e.hypotheses.find(i=>i.id===t);if(!n)throw new Error(`Hypothesis ${t} not found in investigation ${e.id}`);return n}calculateConfidence(e){if(e.evidence.length===0)return .5;let t=0,n=0;for(let r of e.evidence)r.supports?t+=r.weight:n+=r.weight;let i=t+n;return i===0?.5:Math.min(1,Math.max(0,t/i))}buildEvidenceSummary(e){let t=[];for(let n of e.hypotheses){let i=n.evidence.filter(s=>s.supports).length,r=n.evidence.filter(s=>!s.supports).length;t.push(`${n.id}: ${i} supporting, ${r} refuting (confidence: ${n.confidenceScore.toFixed(2)})`)}return t.join("; ")}toSnapshot(e){return{...e,hypotheses:e.hypotheses.map(t=>({...t,evidence:[...t.evidence]}))}}};function Oe(a){return new le(a)}import{randomUUID as ei}from"node:crypto";var Ne={localFleetId:"local",heartbeatIntervalMs:3e4,serviceTimeoutMs:9e4,maxPendingMessages:5e3,maxRoutes:100};var de=class{config;services=new Map;routes=[];outbox=[];inbox=[];handlers=[];messagesSent=0;messagesReceived=0;constructor(e){this.config={...Ne,...e}}registerService(e,t,n,i){if(this.services.has(e))throw new Error(`Service '${e}' already registered`);let r=Date.now(),s={fleetId:e,name:t,domains:[...n],status:"active",registeredAt:r,lastHeartbeat:r,metadata:i};return this.services.set(e,s),ue(s)}deregisterService(e){let t=this.services.get(e);if(!t)return!1;t.status="deregistered";for(let n=this.routes.length-1;n>=0;n--)this.routes[n].targetFleetId===e&&this.routes.splice(n,1);return this.services.delete(e),!0}heartbeat(e){let t=this.services.get(e);return t?(t.lastHeartbeat=Date.now(),(t.status==="degraded"||t.status==="unreachable")&&(t.status="active"),!0):!1}addRoute(e,t,n,i=0){if(this.routes.length>=this.config.maxRoutes)throw new Error(`Maximum routes (${this.config.maxRoutes}) reached`);let r={sourceDomain:e,targetDomain:t,targetFleetId:n,priority:i,active:!0};return this.routes.push(r),this.routes.sort((s,o)=>o.priority-s.priority),Ut(r)}removeRoute(e,t){let n=this.routes.findIndex(i=>i.sourceDomain===e&&i.targetFleetId===t);return n<0?!1:(this.routes.splice(n,1),!0)}send(e,t,n,i,r,s){let o=e==="any"?this.resolveRoute(t,n):e;if(!o)throw new Error(`No route found for ${t} -> ${n}`);let c={id:ei(),sourceFleetId:this.config.localFleetId,targetFleetId:o,sourceDomain:t,targetDomain:n,type:i,payload:r,timestamp:Date.now(),ttl:s?.ttl,correlationId:s?.correlationId};return this.outbox.length>=this.config.maxPendingMessages&&this.outbox.shift(),this.outbox.push(c),this.messagesSent++,c}receive(e){this.inbox.length>=this.config.maxPendingMessages&&this.inbox.shift(),this.inbox.push(e),this.messagesReceived++;for(let t of this.handlers)try{t(e)}catch{}}onMessage(e){return this.handlers.push(e),()=>{let t=this.handlers.indexOf(e);t>=0&&this.handlers.splice(t,1)}}drainOutbox(){let e=[...this.outbox];return this.outbox.length=0,e}drainInbox(){let e=[...this.inbox];return this.inbox.length=0,e}findServicesByDomain(e){return Array.from(this.services.values()).filter(t=>t.status==="active"&&t.domains.includes(e)).map(ue)}getService(e){let t=this.services.get(e);return t?ue(t):void 0}listServices(){return Array.from(this.services.values()).map(ue)}listRoutes(){return this.routes.map(Ut)}checkHealth(){let e=Date.now();for(let t of this.services.values()){if(t.status==="deregistered")continue;let n=e-t.lastHeartbeat;n>this.config.serviceTimeoutMs?t.status="unreachable":n>this.config.serviceTimeoutMs*.6&&(t.status="degraded")}}getHealth(){return{localFleetId:this.config.localFleetId,connectedServices:Array.from(this.services.values()).filter(e=>e.status==="active").length,activeRoutes:this.routes.filter(e=>e.active).length,pendingMessages:this.outbox.length+this.inbox.length,messagesSent:this.messagesSent,messagesReceived:this.messagesReceived}}dispose(){this.services.clear(),this.routes.length=0,this.outbox.length=0,this.inbox.length=0,this.handlers.length=0}resolveRoute(e,t){for(let i of this.routes)if(i.active&&i.sourceDomain===e&&i.targetDomain===t){let r=this.services.get(i.targetFleetId);if(r&&r.status==="active")return i.targetFleetId}let n=this.findServicesByDomain(t);return n.length>0?n[0].fleetId:void 0}};function ue(a){return{fleetId:a.fleetId,name:a.name,domains:[...a.domains],status:a.status,registeredAt:a.registeredAt,lastHeartbeat:a.lastHeartbeat,metadata:a.metadata,endpoint:void 0}}function Ut(a){return{sourceDomain:a.sourceDomain,targetDomain:a.targetDomain,targetFleetId:a.targetFleetId,priority:a.priority,active:a.active}}function Le(a){return new de(a)}var qt={name:"default",scaleUpQueueRatio:3,scaleDownIdleRatio:.5,errorRateScaleUpThreshold:.3,minAgents:2,maxAgents:15,cooldownMs:3e4,sampleWindowSize:5},Qe={defaultPolicy:qt,metricsHistorySize:100,decisionHistorySize:50};import{randomUUID as ti}from"node:crypto";pe();k();var ge=class a{config;policy;metricsHistory=[];events=[];lastScaleTime=0;scaleUpCount=0;scaleDownCount=0;totalDecisions=0;currentAgents;lastDecision;db=null;persistCount=0;static KV_NAMESPACE="scaling-metrics";static KV_KEY="dynamic-scaler-snapshot";static PERSIST_INTERVAL=10;static KV_TTL=7200;constructor(e=2,t){this.config={...Qe,...t},this.policy=this.config.defaultPolicy,this.currentAgents=e}recordMetrics(e){this.metricsHistory.push(e),this.metricsHistory.length>this.config.metricsHistorySize&&this.metricsHistory.shift(),this.persistCount++,this.persistCount%a.PERSIST_INTERVAL===0&&this.persistSnapshot().catch(()=>{})}evaluate(){let e=this.getAverageMetrics(),t=Date.now();if(this.totalDecisions++,t-this.lastScaleTime<this.policy.cooldownMs){let o={action:"maintain",currentAgents:this.currentAgents,targetAgents:this.currentAgents,reason:"Cooldown period active",metrics:e,timestamp:t};return this.lastDecision=o,o}let n="maintain",i=this.currentAgents,r="Workload within acceptable range";if(e.errorRate>this.policy.errorRateScaleUpThreshold)n="scale-up",i=Math.min(this.currentAgents+2,this.policy.maxAgents),r=`High error rate (${(e.errorRate*100).toFixed(1)}% > ${(this.policy.errorRateScaleUpThreshold*100).toFixed(1)}% threshold)`;else if(this.currentAgents>0&&e.queueDepth/Math.max(1,this.currentAgents)>this.policy.scaleUpQueueRatio){n="scale-up";let o=Math.ceil(e.queueDepth/this.policy.scaleUpQueueRatio);i=Math.min(o,this.policy.maxAgents),r=`Queue depth ratio ${(e.queueDepth/Math.max(1,this.currentAgents)).toFixed(1)} > ${this.policy.scaleUpQueueRatio} threshold`}if(n==="maintain"&&this.currentAgents>this.policy.minAgents){let o=this.currentAgents>0?e.idleAgents/this.currentAgents:0;if(o>this.policy.scaleDownIdleRatio){n="scale-down";let c=Math.floor(e.idleAgents*.5);i=Math.max(this.currentAgents-c,this.policy.minAgents),r=`Idle ratio ${(o*100).toFixed(1)}% > ${(this.policy.scaleDownIdleRatio*100).toFixed(1)}% threshold`}}i=Math.max(this.policy.minAgents,Math.min(this.policy.maxAgents,i)),i===this.currentAgents&&(n="maintain");let s={action:n,currentAgents:this.currentAgents,targetAgents:i,reason:r,metrics:e,timestamp:t};return this.lastDecision=s,s}async execute(e,t){let n={id:`scale-${ti().slice(0,8)}`,decision:e,executedAt:Date.now(),success:!0};if(e.action==="maintain")return this.recordEvent(n),n;try{if(t&&!await t(e.currentAgents,e.targetAgents)){let r={...n,success:!1,error:"Executor returned false"};return this.recordEvent(r),r}return this.currentAgents=e.targetAgents,this.lastScaleTime=Date.now(),e.action==="scale-up"&&this.scaleUpCount++,e.action==="scale-down"&&this.scaleDownCount++,this.recordEvent(n),n}catch(i){let r={...n,success:!1,error:h(i)};return this.recordEvent(r),r}}setPolicy(e){this.policy=e}getPolicy(){return{...this.policy}}getCurrentAgents(){return this.currentAgents}getStats(){return{scaleUpCount:this.scaleUpCount,scaleDownCount:this.scaleDownCount,totalDecisions:this.totalDecisions,currentAgents:this.currentAgents,policyName:this.policy.name,lastDecision:this.lastDecision,recentEvents:[...this.events].slice(-10)}}getMetricsHistory(){return[...this.metricsHistory]}async initialize(){try{this.db=M(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(e){console.warn("[DynamicScaler] DB init failed, using memory-only:",h(e)),this.db=null}}dispose(){this.metricsHistory.length=0,this.events.length=0}getAverageMetrics(){let e=this.metricsHistory.slice(-this.policy.sampleWindowSize);if(e.length===0)return{queueDepth:0,activeAgents:this.currentAgents,idleAgents:0,avgTaskDurationMs:0,errorRate:0,throughput:0,timestamp:Date.now()};let t=n=>e.reduce((i,r)=>i+n(r),0)/e.length;return{queueDepth:Math.round(t(n=>n.queueDepth)),activeAgents:Math.round(t(n=>n.activeAgents)),idleAgents:Math.round(t(n=>n.idleAgents)),avgTaskDurationMs:Math.round(t(n=>n.avgTaskDurationMs)),errorRate:t(n=>n.errorRate),throughput:t(n=>n.throughput),timestamp:Date.now()}}recordEvent(e){this.events.push(e),this.events.length>this.config.decisionHistorySize&&this.events.shift(),this.persistCount++,this.persistCount%a.PERSIST_INTERVAL===0&&this.persistSnapshot().catch(()=>{})}async loadFromKv(){if(this.db)try{let e=await this.db.kvGet(a.KV_KEY,a.KV_NAMESPACE);if(e){if(Array.isArray(e.metricsHistory))for(let t of e.metricsHistory)this.metricsHistory.push(t);if(Array.isArray(e.events))for(let t of e.events)this.events.push(t)}}catch(e){console.warn("[DynamicScaler] Failed to load KV snapshot:",h(e))}}async persistSnapshot(){if(this.db)try{let e={metricsHistory:this.metricsHistory.slice(-50),events:this.events.slice(-50)};await this.db.kvSet(a.KV_KEY,e,a.KV_NAMESPACE,a.KV_TTL)}catch(e){console.warn("[DynamicScaler] Failed to persist KV snapshot:",h(e))}}};function Be(a,e){return new ge(a,e)}var ni=[{name:"Core Testing",domains:["test-generation","test-execution","coverage-analysis","quality-assessment"],priority:"p0",description:"Core testing workflow domains"},{name:"Intelligence",domains:["defect-intelligence","code-intelligence","requirements-validation","security-compliance"],priority:"p0",description:"Intelligence and analysis domains"},{name:"Specialized",domains:["contract-testing","visual-accessibility","chaos-resilience","learning-optimization"],priority:"p1",description:"Specialized testing domains"}],P={"generate-tests":["test-generation"],"execute-tests":["test-execution"],"analyze-coverage":["coverage-analysis"],"assess-quality":["quality-assessment"],"predict-defects":["defect-intelligence"],"validate-requirements":["requirements-validation"],"index-code":["code-intelligence"],"scan-security":["security-compliance"],"validate-contracts":["contract-testing"],"test-accessibility":["visual-accessibility"],"run-chaos":["chaos-resilience"],"optimize-learning":["learning-optimization"],"cross-domain-workflow":[],"protocol-execution":[],"ideation-assessment":["requirements-validation","coverage-analysis","security-compliance"]},zt={maxConcurrentTasks:50,defaultTaskTimeout:3e5,taskRetryLimit:3,workStealing:{enabled:!0,idleThreshold:5e3,loadThreshold:10,stealBatchSize:3,checkInterval:1e4},enableMetrics:!0,metricsInterval:6e4,priorityWeights:{p0:100,p1:50,p2:25,p3:10},enableRouting:!0};function Gt(a){P["cross-domain-workflow"]=a,P["protocol-execution"]=a}import{readFileSync as ri,existsSync as si}from"fs";import{join as ai}from"path";import{parse as oi}from"yaml";pe();import{randomUUID as ii}from"crypto";var B={RISK_WEIGHTS:2160*60*60*1e3,SFDIPOT_WEIGHTS:2160*60*60*1e3,FLAKY_PATTERNS:720*60*60*1e3,AC_QUALITY:1440*60*60*1e3};function $(a,e){let t=Date.now(),n=ii().split("-")[0];return`${e||a}-signal-${t}-${n}`}function U(a){return new Date(Date.now()+a).toISOString()}function E(a){return new Date(a.expiresAt)<new Date}var b={STRATEGIC:"qcsd/strategic",TACTICAL:"qcsd/tactical",OPERATIONAL:"qcsd/operational",QUALITY_CRITERIA:"qcsd/quality-criteria"},Ue=class{memory;initialized=!1;constructor(e={}){this.memory=e.memoryManager||M()}async initialize(){this.initialized||(await this.memory.initialize(),this.initialized=!0,console.log("[CrossPhaseMemory] Initialized with UnifiedMemoryManager"))}async storeRiskSignal(e,t){await this.ensureInitialized();let n={id:$("strategic","risk"),timestamp:new Date().toISOString(),source:"production",target:"ideation",loopType:"strategic",version:"1.0.0",expiresAt:U(B.RISK_WEIGHTS),riskWeights:e,recommendations:t};return await this.store(b.STRATEGIC,n),n}async queryRiskSignals(){return await this.ensureInitialized(),(await this.queryByNamespace(b.STRATEGIC)).filter(t=>!E(t))}async storeSFDIPOTSignal(e,t,n){await this.ensureInitialized();let i={id:$("tactical","sfdipot"),timestamp:new Date().toISOString(),source:"production",target:"refinement",loopType:"tactical",version:"1.0.0",expiresAt:U(B.SFDIPOT_WEIGHTS),factorWeights:e,featureContext:t,recommendations:n};return await this.store(b.TACTICAL,i),i}async querySFDIPOTSignals(e){await this.ensureInitialized();let t=await this.queryByNamespace(b.TACTICAL);return t=t.filter(n=>!E(n)),e&&(t=t.filter(n=>n.featureContext.toLowerCase().includes(e.toLowerCase()))),t}async storeTestHealthSignal(e,t,n){await this.ensureInitialized();let i={id:$("operational","test-health"),timestamp:new Date().toISOString(),source:"cicd",target:"development",loopType:"operational",version:"1.0.0",expiresAt:U(B.FLAKY_PATTERNS),flakyPatterns:e,gateFailures:t,recommendations:n};return await this.store(b.OPERATIONAL,i),i}async queryTestHealthSignals(){return await this.ensureInitialized(),(await this.queryByNamespace(b.OPERATIONAL)).filter(t=>!E(t))}async storeACQualitySignal(e,t,n){await this.ensureInitialized();let i={id:$("quality-criteria","ac-quality"),timestamp:new Date().toISOString(),source:"development",target:"refinement",loopType:"quality-criteria",version:"1.0.0",expiresAt:U(B.AC_QUALITY),untestablePatterns:e,coverageGaps:t,recommendations:n};return await this.store(b.QUALITY_CRITERIA,i),i}async queryACQualitySignals(){return await this.ensureInitialized(),(await this.queryByNamespace(b.QUALITY_CRITERIA)).filter(t=>!E(t))}async store(e,t){let n=new Date(t.expiresAt).getTime(),i=Math.max(0,Math.floor((n-Date.now())/1e3));await this.memory.kvSet(t.id,t,e,i>0?i:void 0),console.log(`[CrossPhaseMemory] Stored signal: ${t.id} in ${e}`)}async queryByNamespace(e){let t=await this.memory.kvSearch("*",e,1e3),n=[];for(let i of t){let r=await this.memory.kvGet(i,e);r&&n.push(r)}return n.sort((i,r)=>new Date(r.timestamp).getTime()-new Date(i.timestamp).getTime())}async delete(e,t){let n=await this.memory.kvDelete(t,e);return n&&console.log(`[CrossPhaseMemory] Deleted signal: ${t}`),n}async cleanupExpired(){let e={deleted:0,namespaces:{}};for(let t of Object.values(b)){let n=await this.queryByNamespace(t),i=0;for(let r of n)E(r)&&(await this.delete(t,r.id),i++,e.deleted++);i>0&&(e.namespaces[t]=i)}return e.deleted>0&&console.log(`[CrossPhaseMemory] Cleanup: deleted ${e.deleted} expired signals`),e}async getStats(){await this.ensureInitialized();let e={totalSignals:0,byLoop:{strategic:0,tactical:0,operational:0,"quality-criteria":0},byNamespace:{},oldestSignal:null,newestSignal:null},t=null,n=null;for(let i of Object.values(b)){let s=(await this.queryByNamespace(i)).filter(o=>!E(o));e.byNamespace[i]=s.length,e.totalSignals+=s.length;for(let o of s){e.byLoop[o.loopType]++;let c=new Date(o.timestamp);(!t||c<t)&&(t=c,e.oldestSignal=o.timestamp),(!n||c>n)&&(n=c,e.newestSignal=o.timestamp)}}return e}async ensureInitialized(){this.initialized||await this.initialize()}},$e=null;function jt(a){return $e||($e=new Ue(a)),$e}function qe(a){let e=Object.getOwnPropertyNames(a);for(let t of e){let n=a[t];n&&typeof n=="object"&&!Object.isFrozen(n)&&qe(n)}return Object.freeze(a)}function ze(a){let e=structuredClone(a);return qe(e)}function Ge(a){return a===0?"success":a===2?"model_blocking":"user_error"}var We=class{config=null;memory;configPath;listeners=new Map;constructor(e){this.configPath=e||ai(process.cwd(),".claude/hooks/cross-phase-memory.yaml"),this.memory=jt()}async initialize(){if(process.env.AQE_HOOKS_DISABLED==="true")return console.log("[CrossPhaseHooks] All hooks disabled via AQE_HOOKS_DISABLED"),!1;if(!si(this.configPath))return console.warn(`[CrossPhaseHooks] Config not found: ${this.configPath}`),!1;try{let e=ri(this.configPath,"utf-8"),t=oi(e);return t.enabled?(this.config=ze(t),await this.memory.initialize(),console.log(`[CrossPhaseHooks] Initialized with ${Object.keys(this.config.hooks).length} hooks`),!0):(console.log("[CrossPhaseHooks] Hooks disabled in config"),!1)}catch(e){return console.error("[CrossPhaseHooks] Failed to load config:",e),!1}}async onAgentComplete(e,t){if(!this.config||process.env.AQE_HOOKS_DISABLED==="true")return;let n=this.filterManagedHooks(Object.entries(this.config.hooks).filter(([i,r])=>r.trigger.event==="agent-complete"&&r.trigger.agent===e));for(let[i,r]of n)this.checkConditions(r.trigger.conditions,t)&&(console.log(`[CrossPhaseHooks] Executing hook: ${i}`),await this.executeActions(r.actions,t))}async onPhaseStart(e,t={}){if(!this.config)return{};if(process.env.AQE_HOOKS_DISABLED==="true")return{};let n={},i=this.filterManagedHooks(Object.entries(this.config.hooks).filter(([r,s])=>s.trigger.event==="phase-start"&&s.trigger.phase===e));for(let[r,s]of i){console.log(`[CrossPhaseHooks] Executing phase-start hook: ${r}`);for(let o of s.actions)if(o.type==="query-signals"&&o.injectInto){let c=await this.querySignalsForInjection(o.namespace,o.maxAge,o.filterBy?t[o.filterBy]:void 0);for(let l of o.injectInto)n[l]||(n[l]=[]),n[l].push(...c)}}return n}async onPhaseEnd(e,t){if(!this.config||process.env.AQE_HOOKS_DISABLED==="true")return;let n=this.filterManagedHooks(Object.entries(this.config.hooks).filter(([i,r])=>r.trigger.event==="phase-end"&&r.trigger.phase===e));for(let[i,r]of n)console.log(`[CrossPhaseHooks] Executing phase-end hook: ${i}`),await this.executeActions(r.actions,t)}async executeActions(e,t){for(let n of e)try{await this.executeAction(n,t)}catch(i){let r=i?.exitCode;if(typeof r=="number"){let s=Ge(r);if(s==="model_blocking")throw console.error(`[CrossPhaseHooks] Model-blocking hook failure (exit ${r}):`,i),i;console.warn(`[CrossPhaseHooks] Hook ${s} (exit ${r}):`,i)}else console.error("[CrossPhaseHooks] Action failed:",i)}}async executeAction(e,t){switch(e.type){case"store-signal":await this.executeStoreSignal(e,t);break;case"query-signals":break;case"notify-agent":await this.executeNotifyAgent(e,t);break;case"invoke-agent":await this.executeInvokeAgent(e,t);break;case"conditional":e.condition&&e.action&&this.evaluateCondition(e.condition,t)&&await this.executeAction(e.action,t);break;case"delete-expired":await this.memory.cleanupExpired();break;default:console.warn(`[CrossPhaseHooks] Unknown action type: ${e.type}`)}}async executeStoreSignal(e,t){if(!e.loop||!e.namespace||!e.extract)return;let n=this.extractFromContext(e.extract,t);switch(e.loop){case"strategic":await this.memory.storeRiskSignal(n.riskWeights||[],n.recommendations||{forRiskAssessor:[],forQualityCriteria:[]});break;case"tactical":await this.memory.storeSFDIPOTSignal(n.factorWeights||[],n.featureContext||"unknown",n.recommendations||{forProductFactorsAssessor:[]});break;case"operational":await this.memory.storeTestHealthSignal(n.flakyPatterns||[],n.gateFailures||[],n.recommendations||{forTestArchitect:[],antiPatterns:[]});break;case"quality-criteria":await this.memory.storeACQualitySignal(n.untestablePatterns||[],n.coverageGaps||[],n.recommendations||{forRequirementsValidator:[],acTemplates:{}});break}this.emit("signal-stored",{loop:e.loop,namespace:e.namespace})}async executeNotifyAgent(e,t){!e.target||!e.message||await this.isBlockedUrl(e.target)||(console.log(`[CrossPhaseHooks] Notify ${e.target}: ${e.message}`),this.emit("agent-notification",{target:e.target,message:e.message,priority:e.priority||"normal",context:t}))}async executeInvokeAgent(e,t){e.target&&(await this.isBlockedUrl(e.target)||(console.log(`[CrossPhaseHooks] Invoke agent: ${e.target}`),this.emit("agent-invocation",{agent:e.target,input:{...t,...e.input||{}}})))}async querySignalsForInjection(e,t,n){let r=await this.memory.queryByNamespace(e);if(t){let s=this.parseMaxAge(t),o=Date.now()-s;r=r.filter(c=>new Date(c.timestamp).getTime()>o)}return r}formatSignalsForInjection(e){if(e.length===0)return"";let t=`## CROSS-PHASE LEARNING SIGNALS
168
168
 
169
169
  `;t+=`The following signals have been automatically injected from previous phases.
170
170
  `,t+=`Apply these learnings to your analysis.
@@ -177,4 +177,4 @@ import{b as fe}from"./chunk-FZOBD67M.js";import{a as gt}from"./chunk-TVYY3OCX.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 fe(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),c=isNaN(Number(s))?s:Number(s),l=typeof o=="number"?o:Number(o),u=typeof c=="number"?c:Number(c);switch(r){case">":return l>u;case"<":return l<u;case">=":return l>=u;case"<=":return l<=u;case"==":return o==c;case"!=":return o!=c;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`)}},je=null;function jt(a){return je||(je=new We(a)),je}function F(a,e){let t=a.get(e);return t?.status!=="cancelled"?{ignored:!1,settledNow:!1}:t.cancellationResultPending?(a.set(e,{...t,cancellationResultPending:!1}),{ignored:!0,settledNow:!0}):{ignored:!0,settledNow:!1}}function Wt(a,e){let t=[];for(let s of e){let o=a.router.subscribeToDoamin(s,async c=>{await oi(a,c)});t.push(o)}let n=a.router.subscribeToEventType("TaskCompleted",async s=>{await ci(a,s)});t.push(n);let i=a.router.subscribeToEventType("TaskFailed",async s=>{await li(a,s)});t.push(i);let r=a.router.subscribeToEventType("AgentStatusChanged",async s=>{await ui(a,s)});return t.push(r),t}async function oi(a,e){a.domainLastActivity.set(e.source,new Date),await a.processQueue()}async function ci(a,e){let{taskId:t,result:n}=e.payload,i=F(a.tasks,t);if(i.ignored){i.settledNow&&(a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1),await a.processQueue());return}let r=a.tasks.get(t);if(r){(r.status==="running"||r.status==="assigned")&&(a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1));let s=r.startedAt?Date.now()-r.startedAt.getTime():0;a.tasks.set(t,{...r,status:"completed",completedAt:new Date,result:n}),a.tasksCompleted++,a.taskDurations.push(s),a.auditLogger.logComplete(t,r.assignedAgents[0]);try{let o=jt(),c=r.assignedAgents[0];c&&await o.onAgentComplete(c,{taskId:t,taskType:r.task.type,domain:r.assignedDomain,result:n,duration:s})}catch(o){console.warn("[QueenCoordinator] Cross-phase hook error:",o)}try{await I.afterTaskExecution({taskId:t,taskType:r.task.type,agentId:r.assignedAgents[0]||"unknown",domain:r.assignedDomain||"test-generation",priority:r.task.priority},!0,0,0)}catch(o){console.warn("[QueenCoordinator] Governance tracking error:",o)}if(a.domainBreakerRegistry&&r.assignedDomain&&a.domainBreakerRegistry.getBreaker(r.assignedDomain).recordSuccess(),a.traceCollector){let o=a.taskTraceContexts.get(t);o&&(a.traceCollector.completeSpan(o.spanId),a.taskTraceContexts.delete(t))}if(a.taskCompletedHook)try{let o=typeof n=="object"&&n!==null?n:null;if(o===null)console.error(`[QueenCoordinator] Pattern training skipped for task ${t}: result is not an object (got ${typeof n})`);else{let c=di(o,t);if(c){let l={taskId:t,agentId:r.assignedAgents[0]||"unknown",domain:r.assignedDomain||"test-generation",type:r.task.type,status:"completed",output:o,metrics:c,duration:s,timestamp:Date.now()};a.taskCompletedHook.onTaskCompleted(l).catch(u=>{console.warn("[QueenCoordinator] Pattern training error:",u)})}}}catch(o){console.warn("[QueenCoordinator] Pattern training setup error:",o)}}await a.processQueue()}async function li(a,e){let{taskId:t,error:n}=e.payload,i=F(a.tasks,t);if(i.ignored){i.settledNow&&(a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1),await a.processQueue());return}let r=a.tasks.get(t);if(r){if((r.status==="running"||r.status==="assigned")&&(a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1)),a.domainBreakerRegistry&&r.assignedDomain&&a.domainBreakerRegistry.getBreaker(r.assignedDomain).recordFailure(new Error(n||"Task failed")),a.traceCollector){let s=a.taskTraceContexts.get(t);s&&(a.traceCollector.failSpan(s.spanId,n||"Task failed"),a.taskTraceContexts.delete(t))}if(r.retryCount<a.config.taskRetryLimit){a.auditLogger.logFail(t,r.assignedAgents[0],n);let s={...r,status:"queued",retryCount:r.retryCount+1,error:n};a.tasks.set(t,s),a.enqueueTask(r.task)}else{a.tasks.set(t,{...r,status:"failed",completedAt:new Date,error:n}),a.tasksFailed++,a.auditLogger.logFail(t,r.assignedAgents[0],n);try{await I.afterTaskExecution({taskId:t,taskType:r.task.type,agentId:r.assignedAgents[0]||"unknown",domain:r.assignedDomain||"test-generation",priority:r.task.priority},!1,0,0)}catch(s){console.warn("[QueenCoordinator] Governance tracking error:",s)}if(a.hypothesisManager&&(r.task.priority==="p0"||r.task.priority==="p1"))try{let s=r.assignedDomain||"test-generation",o=a.hypothesisManager.createInvestigation(t,s,`Root cause analysis for ${r.task.type} failure: ${n}`);a.hypothesisManager.addHypothesis(o.id,`Infrastructure failure in domain '${s}' caused task ${t} to fail`,"log-analysis",`${s}-lead`),a.hypothesisManager.addHypothesis(o.id,`Logic/configuration error in task payload caused ${r.task.type} to fail: ${n}`,"code-analysis",r.assignedAgents[0]||"unknown"),console.log(`[QueenCoordinator] Competing hypotheses investigation created: ${o.id}`)}catch(s){console.warn("[QueenCoordinator] Hypothesis creation error:",s)}}}await a.processQueue()}async function ui(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 di(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 Vt(a,e,t){let n=a.listAgents({domain:e}),i=n.filter(c=>c.status==="running").length,r=n.filter(c=>c.status==="idle").length,s=n.filter(c=>c.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 gi=dt();function Kt(a,e,t){let n=a.get(t.priority);n&&ut(n,t,gi);for(let i of t.targetDomains){let r=e.get(i);r&&r.push(t)}}function me(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 Ve(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 z(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){me(a.taskQueue,a.domainQueues,n),a.runningTaskCounter++;try{await Ke(a,n)}catch(i){throw a.runningTaskCounter--,i}if(a.runningTaskCounter>=a.config.maxConcurrentTasks)return}}}function Yt(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 Ke(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?Ye(a,e,n):y(new Error("No healthy domain available for task"))}async function Ye(a,e,t){let n;if(a.tinyDancerRouter){let l={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:l[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(l){console.warn(`[Queen] Domain team setup for '${t}' failed (continuing):`,l)}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);if(a.tasks.get(e.id)?.status==="cancelled")return s.success&&await a.agentCoordinator.stop(s.value),a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1),T(e.id);let o=[];s.success&&o.push(s.value);let c={taskId:e.id,task:e,status:"running",assignedDomain:t,assignedAgents:o,startedAt:new Date,retryCount:0};a.tasks.set(e.id,c),a.domainLastActivity.set(t,new Date);for(let l of o)a.auditLogger.logAssign(e.id,l,t);if(await a.publishEvent("TaskAssigned",{taskId:e.id,domain:t,agentIds:o}),a.domainPlugins){let l=a.domainPlugins.get(t);if(l?.executeTask&&l.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 l.executeTask(u,g=>mi(a,g));if(!d.success){let g=F(a.tasks,e.id);return g.ignored?(g.settledNow&&(a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1),await z(a)),T(e.id)):(a.tasks.set(e.id,{...c,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))}return T(e.id)}if(l)try{await l.handleEvent({id:v(),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 T(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=F(a.tasks,e.taskId);if(n.ignored){n.settledNow&&(a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1),await z(a));return}let i={...t,status:e.success?"completed":"failed",completedAt:new Date,result:e.data,error:e.error};if(a.tasks.set(e.taskId,i),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 r of t.assignedAgents)await a.agentCoordinator.stop(r);await a.publishEvent(e.success?"TaskCompleted":"TaskFailed",{taskId:e.taskId,domain:t.assignedDomain,result:e.data,error:e.error,duration:e.duration}),await z(a)}function Zt(a,e){return(P[e.type]||[]).includes(a)}k();async function Xt(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 c=r.find(l=>Zt(t[0],l));if(c){let l=t.shift();a.removeFromQueues(c),a.auditLogger.logSteal(c.id,i,l),await a.assignTaskToDomain(c,l),e++,a.tasksStolen++,await a.publishEvent("TaskStolen",{taskId:c.id,fromDomain:i,toDomain:l})}}}return e}function Ze(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 Xe(a){return typeof a.setMinCutBridge=="function"}function Jt(a,e){for(let[t,n]of a)Xe(n)&&(n.setMinCutBridge(e),console.log(`[QueenCoordinator] MinCut bridge injected into ${t}`))}async function en(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 tn(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 nn(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 Je(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 c=o.completedAt?.getTime()||o.startedAt?.getTime()||0;c>0&&n-c>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 c=0;c<s;c++){let l=o.next().value;l!==void 0&&e.delete(l)}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 rn(a,e){return a&&a.size>0?Array.from(a.keys()):[...e]}var m=it.create("QueenCoordinator");qt(C);var et=class{constructor(e,t,n,i,r,s,o,c={}){this.eventBus=e;this.agentCoordinator=t;this.memory=n;this.router=i;this.protocolExecutor=r;this.workflowExecutor=s;this.domainPlugins=o;this.config={...zt,...c},this.auditLogger=ye({enableConsoleLog:this.config.enableMetrics,maxEntries:1e3,logPrefix:"[QUEEN]"}),["p0","p1","p2","p3"].forEach(l=>{this.taskQueue.set(l,[])}),this.config.enableRouting!==!1&&(this.tinyDancerRouter=new V(this.config.routing)),C.forEach(l=>{this.domainQueues.set(l,[]),this.domainLastActivity.set(l,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 rt(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=Ze(this.config,()=>this.triggerWorkStealing().then(()=>{}))),this.config.enableMetrics&&(this.metricsTimer=nn(this.createMetricsContext())),this.cleanupTimer=setInterval(()=>{Je(this.tasks,this.taskTraceContexts,36e5)},3e5),this.cleanupTimer.unref(),await en(this.memory,this.tasks,e=>this.enqueueTaskInternal(e)),this.minCutBridge=ft(this.eventBus,this.agentCoordinator,{autoUpdateFromEvents:!0,persistData:!0,includeInQueenHealth:!0,sharedGraph:lt()}),await this.minCutBridge.initialize(),this.domainPlugins&&Jt(this.domainPlugins,this.minCutBridge);try{await I.initialize(),m.info("Governance adapter initialized")}catch(e){m.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=_t(t),this.availableMcpServers=gt(process.cwd());let{getUnifiedMemory:n}=await import("./unified-memory-UCQ6AB32.js"),i=n();await i.initialize(),this.coExecutionRepo=It(),this.coExecutionRepo.initialize(i.getDatabase()),this.dependencyGraph.warnings.length>0&&m.warn(`Dependency graph: ${this.dependencyGraph.warnings.length} warning(s)`,{warnings:this.dependencyGraph.warnings.slice(0,5)}),m.info("Dependency intelligence initialized",{agents:this.dependencyGraph.nodes.size,mcpServers:this.availableMcpServers.length})}catch(e){m.warn("Dependency intelligence initialization failed (continuing)",{error:e})}await this.publishEvent("QueenInitialized",{timestamp:new Date,config:this.config,domains:C}),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 tn(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_${v()}`,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){m.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 Ke(this.createTaskContext(),n);return r.success?(this.tasksReceived++,await this.publishEvent("TaskSubmitted",{taskId:t,task:n}),T(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==="cancelled")return T(void 0);if(t.status==="completed"||t.status==="failed")return y(new Error(`Task already finished: ${e}`));let n=t.status==="running"||t.status==="assigned";this.tasks.set(e,{...t,status:"cancelled",completedAt:new Date,cancellationResultPending:n}),me(this.taskQueue,this.domainQueues,t.task);for(let i of t.assignedAgents)await this.agentCoordinator.stop(i);return this.auditLogger.logCancel(e),await this.publishEvent("TaskCancelled",{taskId:e}),T(void 0)}getTaskStatus(e){return this.tasks.get(e)}listTasks(e){return Yt(this.tasks,e)}getDomainHealth(e){if(this.domainPlugins){let t=this.domainPlugins.get(e);if(t)return t.getHealth()}return Vt(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 C.filter(n=>{let i=this.domainLastActivity.get(n);return this.getDomainLoad(n)===0&&i&&e-i.getTime()>t})}getBusyDomains(){return C.filter(e=>this.getDomainLoad(e)>this.config.workStealing.loadThreshold)}getSpawnPlan(e){return this.dependencyGraph?Pt(e,this.dependencyGraph):{phases:[e],warnings:[],unsatisfiedHardDeps:[]}}getDependencyGraph(){return this.dependencyGraph}enableWorkStealing(){this.workStealingTimer||(this.workStealingTimer=Ze(this.config,()=>this.triggerWorkStealing().then(()=>{})))}disableWorkStealing(){this.workStealingTimer&&(clearInterval(this.workStealingTimer),this.workStealingTimer=null)}async triggerWorkStealing(){return Xt(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(c=>c.required&&!this.availableMcpServers.includes(c.name));if(o.length>0){m.warn(`Pre-spawn MCP advisory: ${r.agentName} needs ${o.map(c=>c.name).join(", ")}`,{agent:r.agentName,domain:e,missing:o.map(c=>c.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)||m.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)||m.warn(`Agent ${i.value} could not join ${e} team (full or max teams reached)`)}}catch(r){m.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=rn(this.domainPlugins,C);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,c="healthy";n>0?c="unhealthy":i>r.length/2&&(c="degraded");let l={status:c,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(l):l}getMetrics(){let e=new Map;for(let o of C){let c=this.getDomainLoad(o);e.set(o,c)}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 m.warn("Cannot inject MinCut bridge: bridge not initialized"),!1;if(!this.domainPlugins)return m.warn("Cannot inject MinCut bridge: no domain plugins registered"),!1;let t=this.domainPlugins.get(e);return t?Xe(t)?(t.setMinCutBridge(this.minCutBridge),m.info(`MinCut bridge injected into ${e} (late binding)`),!0):(m.warn(`Domain ${e} does not support MinCut integration`),!1):(m.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 ce(e);this.taskCompletedHook=new oe({},t),m.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}),T(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}),T(n.value.executionId)):n}cleanupCompletedTasks(e=36e5){return Je(this.tasks,this.taskTraceContexts,e)}subscribeToEvents(){this.eventSubscriptionIds=Wt(this.createEventHandlerContext(),C)}enqueueTaskInternal(e){Kt(this.taskQueue,this.domainQueues,e)}async publishEvent(e,t){await this.eventBus.publish({id:v(),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,Ve(this.taskQueue,e)),this.publishEvent("TaskQueued",{taskId:e.id,task:e,position:Ve(this.taskQueue,e)}),T(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 m.info(`Fleet tier: ${n.selectedTier} (${n.reason})`),n.selectedTier}catch(t){m.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){m.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=Nt(),m.info("Domain circuit breaker registry initialized")}catch(e){m.warn("Circuit breaker initialization failed (continuing)",{error:e})}if(this.config.enableDomainTeams!==!1)try{this.agentTeamsAdapter=Me(),this.agentTeamsAdapter.initialize(),this.domainTeamManager=we(this.agentTeamsAdapter),m.info("Domain team manager initialized")}catch(e){m.warn("Domain team manager initialization failed (continuing)",{error:e})}if(this.config.enableFleetTiers!==!1)try{this.tierSelector=Pe(),m.info("Fleet tier selector initialized")}catch(e){m.warn("Tier selector initialization failed (continuing)",{error:e})}try{this.traceCollector=Ee(),m.info("Trace collector initialized")}catch(e){m.warn("Trace collector initialization failed (continuing)",{error:e})}try{this.hypothesisManager=Oe(),this.federationMailbox=Le(),this.dynamicScaler=Be(),m.info("Phase 4 modules initialized (hypotheses, federation, scaling)")}catch(e){m.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:()=>z(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=>me(e.taskQueue,e.domainQueues,t),assignTaskToDomain:(t,n)=>Ye(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 ho(a,e,t,n,i,r){return new et(a.eventBus,a.coordinator,a.memory,e,t,n,i,r)}export{ti as a,P as b,et as c,ho 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 fe(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),c=isNaN(Number(s))?s:Number(s),l=typeof o=="number"?o:Number(o),u=typeof c=="number"?c:Number(c);switch(r){case">":return l>u;case"<":return l<u;case">=":return l>=u;case"<=":return l<=u;case"==":return o==c;case"!=":return o!=c;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`)}},je=null;function Wt(a){return je||(je=new We(a)),je}function F(a,e){let t=a.get(e);return t?.status!=="cancelled"?{ignored:!1,settledNow:!1}:t.cancellationResultPending?(a.set(e,{...t,cancellationResultPending:!1}),{ignored:!0,settledNow:!0}):{ignored:!0,settledNow:!1}}function Vt(a,e){let t=[];for(let s of e){let o=a.router.subscribeToDoamin(s,async c=>{await ci(a,c)});t.push(o)}let n=a.router.subscribeToEventType("TaskCompleted",async s=>{await li(a,s)});t.push(n);let i=a.router.subscribeToEventType("TaskFailed",async s=>{await ui(a,s)});t.push(i);let r=a.router.subscribeToEventType("AgentStatusChanged",async s=>{await di(a,s)});return t.push(r),t}async function ci(a,e){a.domainLastActivity.set(e.source,new Date),await a.processQueue()}async function li(a,e){let{taskId:t,result:n}=e.payload,i=F(a.tasks,t);if(i.ignored){i.settledNow&&(a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1),await a.processQueue());return}let r=a.tasks.get(t);if(r){(r.status==="running"||r.status==="assigned")&&(a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1));let s=r.startedAt?Date.now()-r.startedAt.getTime():0;a.tasks.set(t,{...r,status:"completed",completedAt:new Date,result:n}),a.tasksCompleted++,a.taskDurations.push(s),a.auditLogger.logComplete(t,r.assignedAgents[0]);try{let o=Wt(),c=r.assignedAgents[0];c&&await o.onAgentComplete(c,{taskId:t,taskType:r.task.type,domain:r.assignedDomain,result:n,duration:s})}catch(o){console.warn("[QueenCoordinator] Cross-phase hook error:",o)}try{await I.afterTaskExecution({taskId:t,taskType:r.task.type,agentId:r.assignedAgents[0]||"unknown",domain:r.assignedDomain||"test-generation",priority:r.task.priority},!0,0,0)}catch(o){console.warn("[QueenCoordinator] Governance tracking error:",o)}if(a.domainBreakerRegistry&&r.assignedDomain&&a.domainBreakerRegistry.getBreaker(r.assignedDomain).recordSuccess(),a.traceCollector){let o=a.taskTraceContexts.get(t);o&&(a.traceCollector.completeSpan(o.spanId),a.taskTraceContexts.delete(t))}if(a.taskCompletedHook)try{let o=typeof n=="object"&&n!==null?n:null;if(o===null)console.error(`[QueenCoordinator] Pattern training skipped for task ${t}: result is not an object (got ${typeof n})`);else{let c=gi(o,t);if(c){let l={taskId:t,agentId:r.assignedAgents[0]||"unknown",domain:r.assignedDomain||"test-generation",type:r.task.type,status:"completed",output:o,metrics:c,duration:s,timestamp:Date.now()};a.taskCompletedHook.onTaskCompleted(l).catch(u=>{console.warn("[QueenCoordinator] Pattern training error:",u)})}}}catch(o){console.warn("[QueenCoordinator] Pattern training setup error:",o)}}await a.processQueue()}async function ui(a,e){let{taskId:t,error:n,callerError:i}=e.payload,r=F(a.tasks,t);if(r.ignored){r.settledNow&&(a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1),await a.processQueue());return}let s=a.tasks.get(t);if(s){if((s.status==="running"||s.status==="assigned")&&(a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1)),a.domainBreakerRegistry&&s.assignedDomain&&!i&&a.domainBreakerRegistry.getBreaker(s.assignedDomain).recordFailure(new Error(n||"Task failed")),a.traceCollector){let o=a.taskTraceContexts.get(t);o&&(a.traceCollector.failSpan(o.spanId,n||"Task failed"),a.taskTraceContexts.delete(t))}if(!i&&s.retryCount<a.config.taskRetryLimit){a.auditLogger.logFail(t,s.assignedAgents[0],n);let o={...s,status:"queued",retryCount:s.retryCount+1,error:n};a.tasks.set(t,o),a.enqueueTask(s.task)}else{a.tasks.set(t,{...s,status:"failed",completedAt:new Date,error:n}),a.tasksFailed++,a.auditLogger.logFail(t,s.assignedAgents[0],n);try{await I.afterTaskExecution({taskId:t,taskType:s.task.type,agentId:s.assignedAgents[0]||"unknown",domain:s.assignedDomain||"test-generation",priority:s.task.priority},!1,0,0)}catch(o){console.warn("[QueenCoordinator] Governance tracking error:",o)}if(!i&&a.hypothesisManager&&(s.task.priority==="p0"||s.task.priority==="p1"))try{let o=s.assignedDomain||"test-generation",c=a.hypothesisManager.createInvestigation(t,o,`Root cause analysis for ${s.task.type} failure: ${n}`);a.hypothesisManager.addHypothesis(c.id,`Infrastructure failure in domain '${o}' caused task ${t} to fail`,"log-analysis",`${o}-lead`),a.hypothesisManager.addHypothesis(c.id,`Logic/configuration error in task payload caused ${s.task.type} to fail: ${n}`,"code-analysis",s.assignedAgents[0]||"unknown"),console.log(`[QueenCoordinator] Competing hypotheses investigation created: ${c.id}`)}catch(o){console.warn("[QueenCoordinator] Hypothesis creation error:",o)}}}await a.processQueue()}async function di(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 gi(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 Kt(a,e,t){let n=a.listAgents({domain:e}),i=n.filter(c=>c.status==="running").length,r=n.filter(c=>c.status==="idle").length,s=n.filter(c=>c.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 mi=dt();function Yt(a,e,t){let n=a.get(t.priority);n&&ut(n,t,mi);for(let i of t.targetDomains){let r=e.get(i);r&&r.push(t)}}function me(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 Ve(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 q(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){me(a.taskQueue,a.domainQueues,n),a.runningTaskCounter++;try{await Ke(a,n)}catch(i){throw a.runningTaskCounter--,i}if(a.runningTaskCounter>=a.config.maxConcurrentTasks)return}}}function Zt(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 Ke(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?Ye(a,e,n):y(new Error("No healthy domain available for task"))}async function Ye(a,e,t){let n;if(a.tinyDancerRouter){let l={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:l[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(l){console.warn(`[Queen] Domain team setup for '${t}' failed (continuing):`,l)}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);if(a.tasks.get(e.id)?.status==="cancelled")return s.success&&await a.agentCoordinator.stop(s.value),a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1),T(e.id);let o=[];s.success&&o.push(s.value);let c={taskId:e.id,task:e,status:"running",assignedDomain:t,assignedAgents:o,startedAt:new Date,retryCount:0};a.tasks.set(e.id,c),a.domainLastActivity.set(t,new Date);for(let l of o)a.auditLogger.logAssign(e.id,l,t);if(await a.publishEvent("TaskAssigned",{taskId:e.id,domain:t,agentIds:o}),a.domainPlugins){let l=a.domainPlugins.get(t);if(l?.executeTask&&l.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 l.executeTask(u,g=>pi(a,g));if(!d.success){let g=F(a.tasks,e.id);return g.ignored?(g.settledNow&&(a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1),await q(a)),T(e.id)):(a.tasks.set(e.id,{...c,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))}return T(e.id)}if(l)try{await l.handleEvent({id:v(),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 T(e.id)}async function pi(a,e){let t=a.tasks.get(e.taskId);if(!t){console.warn(`[Queen] Received completion for unknown task: ${e.taskId}`);return}let n=F(a.tasks,e.taskId);if(n.ignored){n.settledNow&&(a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1),await q(a));return}let i={...t,status:e.success?"completed":"failed",completedAt:new Date,result:e.data,error:e.error};if(a.tasks.set(e.taskId,i),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 r of t.assignedAgents)await a.agentCoordinator.stop(r);await a.publishEvent(e.success?"TaskCompleted":"TaskFailed",{taskId:e.taskId,domain:t.assignedDomain,result:e.data,error:e.error,duration:e.duration}),await q(a)}function Xt(a,e){return(P[e.type]||[]).includes(a)}k();async function Jt(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 c=r.find(l=>Xt(t[0],l));if(c){let l=t.shift();a.removeFromQueues(c),a.auditLogger.logSteal(c.id,i,l),await a.assignTaskToDomain(c,l),e++,a.tasksStolen++,await a.publishEvent("TaskStolen",{taskId:c.id,fromDomain:i,toDomain:l})}}}return e}function Ze(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 Xe(a){return typeof a.setMinCutBridge=="function"}function en(a,e){for(let[t,n]of a)Xe(n)&&(n.setMinCutBridge(e),console.log(`[QueenCoordinator] MinCut bridge injected into ${t}`))}async function tn(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 nn(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 rn(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 Je(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 c=o.completedAt?.getTime()||o.startedAt?.getTime()||0;c>0&&n-c>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 c=0;c<s;c++){let l=o.next().value;l!==void 0&&e.delete(l)}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 sn(a,e){return a&&a.size>0?Array.from(a.keys()):[...e]}var m=it.create("QueenCoordinator");Gt(C);var et=class{constructor(e,t,n,i,r,s,o,c={}){this.eventBus=e;this.agentCoordinator=t;this.memory=n;this.router=i;this.protocolExecutor=r;this.workflowExecutor=s;this.domainPlugins=o;this.config={...zt,...c},this.auditLogger=ye({enableConsoleLog:this.config.enableMetrics,maxEntries:1e3,logPrefix:"[QUEEN]"}),["p0","p1","p2","p3"].forEach(l=>{this.taskQueue.set(l,[])}),this.config.enableRouting!==!1&&(this.tinyDancerRouter=new V(this.config.routing)),C.forEach(l=>{this.domainQueues.set(l,[]),this.domainLastActivity.set(l,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 rt(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=Ze(this.config,()=>this.triggerWorkStealing().then(()=>{}))),this.config.enableMetrics&&(this.metricsTimer=rn(this.createMetricsContext())),this.cleanupTimer=setInterval(()=>{Je(this.tasks,this.taskTraceContexts,36e5)},3e5),this.cleanupTimer.unref(),await tn(this.memory,this.tasks,e=>this.enqueueTaskInternal(e)),this.minCutBridge=yt(this.eventBus,this.agentCoordinator,{autoUpdateFromEvents:!0,persistData:!0,includeInQueenHealth:!0,sharedGraph:lt()}),await this.minCutBridge.initialize(),this.domainPlugins&&en(this.domainPlugins,this.minCutBridge);try{await I.initialize(),m.info("Governance adapter initialized")}catch(e){m.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=Pt(t),this.availableMcpServers=gt(process.cwd());let{getUnifiedMemory:n}=await import("./unified-memory-OVFEPRPS.js"),i=n();await i.initialize(),this.coExecutionRepo=Rt(),this.coExecutionRepo.initialize(i.getDatabase()),this.dependencyGraph.warnings.length>0&&m.warn(`Dependency graph: ${this.dependencyGraph.warnings.length} warning(s)`,{warnings:this.dependencyGraph.warnings.slice(0,5)}),m.info("Dependency intelligence initialized",{agents:this.dependencyGraph.nodes.size,mcpServers:this.availableMcpServers.length})}catch(e){m.warn("Dependency intelligence initialization failed (continuing)",{error:e})}await this.publishEvent("QueenInitialized",{timestamp:new Date,config:this.config,domains:C}),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 nn(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_${v()}`,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){m.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 Ke(this.createTaskContext(),n);return r.success?(this.tasksReceived++,await this.publishEvent("TaskSubmitted",{taskId:t,task:n}),T(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==="cancelled")return T(void 0);if(t.status==="completed"||t.status==="failed")return y(new Error(`Task already finished: ${e}`));let n=t.status==="running"||t.status==="assigned";this.tasks.set(e,{...t,status:"cancelled",completedAt:new Date,cancellationResultPending:n}),me(this.taskQueue,this.domainQueues,t.task);for(let i of t.assignedAgents)await this.agentCoordinator.stop(i);return this.auditLogger.logCancel(e),await this.publishEvent("TaskCancelled",{taskId:e}),T(void 0)}getTaskStatus(e){return this.tasks.get(e)}listTasks(e){return Zt(this.tasks,e)}getDomainHealth(e){if(this.domainPlugins){let t=this.domainPlugins.get(e);if(t)return t.getHealth()}return Kt(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 C.filter(n=>{let i=this.domainLastActivity.get(n);return this.getDomainLoad(n)===0&&i&&e-i.getTime()>t})}getBusyDomains(){return C.filter(e=>this.getDomainLoad(e)>this.config.workStealing.loadThreshold)}getSpawnPlan(e){return this.dependencyGraph?Ft(e,this.dependencyGraph):{phases:[e],warnings:[],unsatisfiedHardDeps:[]}}getDependencyGraph(){return this.dependencyGraph}enableWorkStealing(){this.workStealingTimer||(this.workStealingTimer=Ze(this.config,()=>this.triggerWorkStealing().then(()=>{})))}disableWorkStealing(){this.workStealingTimer&&(clearInterval(this.workStealingTimer),this.workStealingTimer=null)}async triggerWorkStealing(){return Jt(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(c=>c.required&&!this.availableMcpServers.includes(c.name));if(o.length>0){m.warn(`Pre-spawn MCP advisory: ${r.agentName} needs ${o.map(c=>c.name).join(", ")}`,{agent:r.agentName,domain:e,missing:o.map(c=>c.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)||m.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)||m.warn(`Agent ${i.value} could not join ${e} team (full or max teams reached)`)}}catch(r){m.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=sn(this.domainPlugins,C);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,c="healthy";n>0?c="unhealthy":i>r.length/2&&(c="degraded");let l={status:c,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(l):l}getMetrics(){let e=new Map;for(let o of C){let c=this.getDomainLoad(o);e.set(o,c)}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 m.warn("Cannot inject MinCut bridge: bridge not initialized"),!1;if(!this.domainPlugins)return m.warn("Cannot inject MinCut bridge: no domain plugins registered"),!1;let t=this.domainPlugins.get(e);return t?Xe(t)?(t.setMinCutBridge(this.minCutBridge),m.info(`MinCut bridge injected into ${e} (late binding)`),!0):(m.warn(`Domain ${e} does not support MinCut integration`),!1):(m.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 ce(e);this.taskCompletedHook=new oe({},t),m.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}),T(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}),T(n.value.executionId)):n}cleanupCompletedTasks(e=36e5){return Je(this.tasks,this.taskTraceContexts,e)}subscribeToEvents(){this.eventSubscriptionIds=Vt(this.createEventHandlerContext(),C)}enqueueTaskInternal(e){Yt(this.taskQueue,this.domainQueues,e)}async publishEvent(e,t){await this.eventBus.publish({id:v(),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,Ve(this.taskQueue,e)),this.publishEvent("TaskQueued",{taskId:e.id,task:e,position:Ve(this.taskQueue,e)}),T(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 m.info(`Fleet tier: ${n.selectedTier} (${n.reason})`),n.selectedTier}catch(t){m.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){m.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=Lt(),m.info("Domain circuit breaker registry initialized")}catch(e){m.warn("Circuit breaker initialization failed (continuing)",{error:e})}if(this.config.enableDomainTeams!==!1)try{this.agentTeamsAdapter=we(),this.agentTeamsAdapter.initialize(),this.domainTeamManager=Me(this.agentTeamsAdapter),m.info("Domain team manager initialized")}catch(e){m.warn("Domain team manager initialization failed (continuing)",{error:e})}if(this.config.enableFleetTiers!==!1)try{this.tierSelector=Pe(),m.info("Fleet tier selector initialized")}catch(e){m.warn("Tier selector initialization failed (continuing)",{error:e})}try{this.traceCollector=Ee(),m.info("Trace collector initialized")}catch(e){m.warn("Trace collector initialization failed (continuing)",{error:e})}try{this.hypothesisManager=Oe(),this.federationMailbox=Le(),this.dynamicScaler=Be(),m.info("Phase 4 modules initialized (hypotheses, federation, scaling)")}catch(e){m.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:()=>q(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=>me(e.taskQueue,e.domainQueues,t),assignTaskToDomain:(t,n)=>Ye(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 yo(a,e,t,n,i,r){return new et(a.eventBus,a.coordinator,a.memory,e,t,n,i,r)}export{ni as a,P as b,et as c,yo as d};