agentic-qe 3.9.18 → 3.9.19

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 (301) hide show
  1. package/.claude/helpers/statusline-v3.cjs +1 -1
  2. package/.claude/skills/skills-manifest.json +1 -1
  3. package/CHANGELOG.md +34 -0
  4. package/assets/skills/skills-manifest.json +1 -1
  5. package/dist/cli/bundle.js +5 -5
  6. package/dist/cli/chunks/adapter-5NI3IO42.js +2 -0
  7. package/dist/cli/chunks/{agent-booster-wasm-RJHBIG5V.js → agent-booster-wasm-HVBKHNIS.js} +2 -2
  8. package/dist/cli/chunks/{agent-handler-CXS6EE2V.js → agent-handler-XNBDYRSJ.js} +2 -2
  9. package/dist/cli/chunks/{agent-memory-branch-7NV5DD5A.js → agent-memory-branch-YCVTQEMJ.js} +2 -2
  10. package/dist/cli/chunks/aqe-learning-engine-JOUK5HMO.js +2 -0
  11. package/dist/cli/chunks/{audit-3NWGSPJW.js → audit-6C2PE7OY.js} +2 -2
  12. package/dist/cli/chunks/base-DCAB7AHK.js +2 -0
  13. package/dist/cli/chunks/{better-sqlite3-NXOMSJDC.js → better-sqlite3-HZPCHUQU.js} +2 -2
  14. package/dist/cli/chunks/{brain-handler-6N5WWZVA.js → brain-handler-OV75Q2NM.js} +3 -3
  15. package/dist/cli/chunks/{branch-enumerator-I7UTOCAW.js → branch-enumerator-QW6D42HJ.js} +2 -2
  16. package/dist/cli/chunks/{browser-6VOFWA52.js → browser-5BA7Q7OR.js} +2 -2
  17. package/dist/cli/chunks/browser-workflow-A4UV73SZ.js +2 -0
  18. package/dist/cli/chunks/{chunk-QTUTQLOY.js → chunk-255CWHTF.js} +2 -2
  19. package/dist/cli/chunks/{chunk-DC3PADV3.js → chunk-2SIQ742L.js} +1 -1
  20. package/dist/cli/chunks/{chunk-XTCV5UOJ.js → chunk-2SSDY6OE.js} +2 -2
  21. package/dist/cli/chunks/{chunk-BFM47L3X.js → chunk-2WJLEZKP.js} +2 -2
  22. package/dist/cli/chunks/{chunk-QW2RFI73.js → chunk-2WM4NYM5.js} +2 -2
  23. package/dist/cli/chunks/{chunk-YNVVRND7.js → chunk-2XATUQIG.js} +2 -2
  24. package/dist/cli/chunks/{chunk-ENYQUSSK.js → chunk-3546SG2L.js} +2 -2
  25. package/dist/cli/chunks/{chunk-XBWVHO6G.js → chunk-37DTXQ6P.js} +2 -2
  26. package/dist/cli/chunks/{chunk-4ELLGWTS.js → chunk-3HQ4AZDH.js} +2 -2
  27. package/dist/cli/chunks/{chunk-PM77Z4PR.js → chunk-3X3QQZ7Q.js} +2 -2
  28. package/dist/cli/chunks/{chunk-RGLCMGNZ.js → chunk-44SPMVML.js} +2 -2
  29. package/dist/cli/chunks/{chunk-6KTF7QB3.js → chunk-5KGFDNYI.js} +2 -2
  30. package/dist/cli/chunks/{chunk-6IBFYVLK.js → chunk-5LXWEAEJ.js} +2 -2
  31. package/dist/cli/chunks/{chunk-UNPTSPAO.js → chunk-5MGRZ4YD.js} +2 -2
  32. package/dist/cli/chunks/{chunk-6ZMQL3U6.js → chunk-5R2DUR3A.js} +2 -2
  33. package/dist/cli/chunks/{chunk-MDCTQOUJ.js → chunk-5X2AUPK2.js} +1 -1
  34. package/dist/cli/chunks/{chunk-G2H4W7NN.js → chunk-6BRUQTC7.js} +1 -1
  35. package/dist/cli/chunks/{chunk-DQCWNCOT.js → chunk-7IV2RK5M.js} +2 -2
  36. package/dist/cli/chunks/{chunk-EN2A2CVT.js → chunk-7WMHLBNZ.js} +1 -1
  37. package/dist/cli/chunks/{chunk-HLXPD4Y2.js → chunk-AEET2WOI.js} +65 -65
  38. package/dist/cli/chunks/{chunk-AGPZVE6B.js → chunk-AG7J7DTM.js} +2 -2
  39. package/dist/cli/chunks/{chunk-X2T4TI7D.js → chunk-ALYUJEYA.js} +2 -2
  40. package/dist/cli/chunks/{chunk-ZHA5Z5V4.js → chunk-AOASQYOO.js} +1 -1
  41. package/dist/cli/chunks/{chunk-D7SS56EG.js → chunk-AZKVGH5I.js} +2 -2
  42. package/dist/cli/chunks/{chunk-2A4JCRAW.js → chunk-B2EHSFUW.js} +2 -2
  43. package/dist/cli/chunks/{chunk-KMHGQD76.js → chunk-B65GTWF3.js} +2 -2
  44. package/dist/cli/chunks/{chunk-S2XBAOXE.js → chunk-BB3KUX6C.js} +1 -1
  45. package/dist/cli/chunks/{chunk-ZWR4PZ4Z.js → chunk-BFBR2ZZJ.js} +2 -2
  46. package/dist/cli/chunks/{chunk-7ZIKFJ6X.js → chunk-BGTYOZRK.js} +2 -2
  47. package/dist/cli/chunks/{chunk-IJPTWPXG.js → chunk-BOUCIIUI.js} +1 -1
  48. package/dist/cli/chunks/{chunk-ZJEVL5O3.js → chunk-C5YFCM2H.js} +2 -2
  49. package/dist/cli/chunks/{chunk-MBGWDELE.js → chunk-CYLQTVIA.js} +2 -2
  50. package/dist/cli/chunks/{chunk-7OGUAZGJ.js → chunk-D2EHD2KF.js} +1 -1
  51. package/dist/cli/chunks/{chunk-MLVVYUFS.js → chunk-D74RGYKI.js} +1 -1
  52. package/dist/cli/chunks/{chunk-WKQSZTU6.js → chunk-DAPBSAVT.js} +2 -2
  53. package/dist/cli/chunks/{chunk-I3POPZT5.js → chunk-DZS7XQ2Z.js} +2 -2
  54. package/dist/cli/chunks/{chunk-R3U3ARVJ.js → chunk-EW5TQQBR.js} +2 -2
  55. package/dist/cli/chunks/{chunk-YQL6JH2Y.js → chunk-EZZJ5XD6.js} +2 -2
  56. package/dist/cli/chunks/{chunk-BGSYFAEJ.js → chunk-FJJLNCSL.js} +3 -3
  57. package/dist/cli/chunks/{chunk-VZO5I23B.js → chunk-FL2DMHOQ.js} +1 -1
  58. package/dist/cli/chunks/{chunk-7XLTLFP5.js → chunk-FNVA7U7X.js} +2 -2
  59. package/dist/cli/chunks/{chunk-JGNVI5UB.js → chunk-FPVXXQVX.js} +3 -3
  60. package/dist/cli/chunks/{chunk-VRHKEJR6.js → chunk-FT3MAIRW.js} +3 -3
  61. package/dist/cli/chunks/{chunk-J7BG55VG.js → chunk-G2V4GMPR.js} +3 -3
  62. package/dist/cli/chunks/{chunk-MJ7UYPGY.js → chunk-GJ5FON37.js} +2 -2
  63. package/dist/cli/chunks/{chunk-KYLE6ZSC.js → chunk-GL742O2V.js} +4 -4
  64. package/dist/cli/chunks/{chunk-6BGSH2YR.js → chunk-GVDLCJC5.js} +1 -1
  65. package/dist/cli/chunks/{chunk-AZGESIFV.js → chunk-GYDE5TCN.js} +1 -1
  66. package/dist/cli/chunks/{chunk-IS2PMHB5.js → chunk-GYESQBDU.js} +2 -2
  67. package/dist/cli/chunks/{chunk-BSQTOKNR.js → chunk-H4QM37XS.js} +1 -1
  68. package/dist/cli/chunks/{chunk-K5NFP7B5.js → chunk-HCSTXZYE.js} +2 -2
  69. package/dist/cli/chunks/{chunk-A26GU6YU.js → chunk-HJ7CRPZY.js} +1 -1
  70. package/dist/cli/chunks/{chunk-H5JZZH2C.js → chunk-HQFREZRX.js} +2 -2
  71. package/dist/cli/chunks/{chunk-HZKY5KPB.js → chunk-HVNW3TZS.js} +1 -1
  72. package/dist/cli/chunks/{chunk-BXTHB2A2.js → chunk-I3JRRFVT.js} +2 -2
  73. package/dist/cli/chunks/{chunk-P6HIDCTQ.js → chunk-IG2RCBHJ.js} +1 -1
  74. package/dist/cli/chunks/{chunk-WMJCFDTA.js → chunk-IPLQPBJA.js} +2 -2
  75. package/dist/cli/chunks/{chunk-DOSDUAVZ.js → chunk-IV74GAZN.js} +2 -2
  76. package/dist/cli/chunks/{chunk-EZN7QMOZ.js → chunk-J7F65KKG.js} +4 -4
  77. package/dist/cli/chunks/{chunk-SQHM6WUF.js → chunk-JCPJG2KU.js} +3 -3
  78. package/dist/cli/chunks/{chunk-XSLKR2DM.js → chunk-JLX35EPX.js} +2 -2
  79. package/dist/cli/chunks/{chunk-FDDB7QTM.js → chunk-JYHZK44T.js} +1 -1
  80. package/dist/cli/chunks/{chunk-F7XU7KZL.js → chunk-K554X3T4.js} +2 -2
  81. package/dist/cli/chunks/{chunk-Z4YHL4JU.js → chunk-KTDGHN2J.js} +1 -1
  82. package/dist/cli/chunks/{chunk-WH7ZOJCF.js → chunk-KU7OXAFY.js} +1 -1
  83. package/dist/cli/chunks/{chunk-UPP5V7Y3.js → chunk-LDBHCOM3.js} +2 -2
  84. package/dist/cli/chunks/{chunk-4666TC3P.js → chunk-LTE3CDOY.js} +2 -2
  85. package/dist/cli/chunks/{chunk-V2N7KWT7.js → chunk-M6EP724N.js} +1 -1
  86. package/dist/cli/chunks/{chunk-LVABI4OA.js → chunk-MIQAFOFO.js} +1 -1
  87. package/dist/cli/chunks/{chunk-JD6KE6DJ.js → chunk-MMVSIESL.js} +2 -2
  88. package/dist/cli/chunks/{chunk-JMK5OCWL.js → chunk-MN4366PQ.js} +2 -2
  89. package/dist/cli/chunks/{chunk-DCB2VUYM.js → chunk-MTHO6A3V.js} +1 -1
  90. package/dist/cli/chunks/{chunk-TPL3CBMS.js → chunk-N2PLNYEV.js} +1 -1
  91. package/dist/cli/chunks/{chunk-CCM7MBLA.js → chunk-NBBIA3QA.js} +2 -2
  92. package/dist/cli/chunks/{chunk-KFITGSW3.js → chunk-NMYZSZHW.js} +2 -2
  93. package/dist/cli/chunks/{chunk-5SZLQCFP.js → chunk-NPSWRGNT.js} +2 -2
  94. package/dist/cli/chunks/{chunk-BADBKGZE.js → chunk-NXO7CT5K.js} +2 -2
  95. package/dist/cli/chunks/{chunk-BRWWIY6O.js → chunk-O5ZP3CBF.js} +2 -2
  96. package/dist/cli/chunks/{chunk-RI3NTZ2I.js → chunk-O6UMETOH.js} +2 -2
  97. package/dist/cli/chunks/{chunk-3GA7M5NK.js → chunk-OEQCZBBM.js} +2 -2
  98. package/dist/cli/chunks/{chunk-VW7FKTFO.js → chunk-P6EYD4V3.js} +2 -2
  99. package/dist/cli/chunks/{chunk-QTNDHCZ7.js → chunk-PS72GF4R.js} +3 -3
  100. package/dist/cli/chunks/{chunk-UFGFV4BO.js → chunk-PUUTYV32.js} +2 -2
  101. package/dist/cli/chunks/{chunk-4BIWQLD3.js → chunk-QOK4TIE4.js} +2 -2
  102. package/dist/cli/chunks/chunk-R5IL3XD5.js +69 -0
  103. package/dist/cli/chunks/{chunk-JZTB35EQ.js → chunk-RL5CBCBV.js} +1 -1
  104. package/dist/cli/chunks/{chunk-CSYQKVZY.js → chunk-SKDDAPBV.js} +1 -1
  105. package/dist/cli/chunks/{chunk-QGSELG75.js → chunk-SKNHAGYP.js} +2 -2
  106. package/dist/cli/chunks/{chunk-YZIOM7JL.js → chunk-SLDYG7LC.js} +2 -2
  107. package/dist/cli/chunks/{chunk-6G3RNT5H.js → chunk-SRKBR4DU.js} +2 -2
  108. package/dist/cli/chunks/{chunk-4U2JKV44.js → chunk-TCUIYIZ4.js} +1 -1
  109. package/dist/cli/chunks/{chunk-BY44ODHD.js → chunk-TMAIHTE3.js} +4 -4
  110. package/dist/cli/chunks/{chunk-RPT7HCMH.js → chunk-TXCOK5DC.js} +2 -2
  111. package/dist/cli/chunks/{chunk-ODGACHEZ.js → chunk-U257SS7D.js} +2 -2
  112. package/dist/cli/chunks/{chunk-AMRUZ6XG.js → chunk-U2WMCNNR.js} +2 -2
  113. package/dist/cli/chunks/{chunk-B6BAK2JI.js → chunk-UIASVDYG.js} +2 -2
  114. package/dist/cli/chunks/{chunk-VXQK4GKV.js → chunk-V7ZPTEP7.js} +1 -1
  115. package/dist/cli/chunks/{chunk-27MW2RFA.js → chunk-VHG67L7O.js} +2 -2
  116. package/dist/cli/chunks/{chunk-NBQW7MXF.js → chunk-VLQYU7ZQ.js} +1 -1
  117. package/dist/cli/chunks/{chunk-RHYGRUNU.js → chunk-VPDZTMMB.js} +3 -3
  118. package/dist/cli/chunks/{chunk-3DLD7OMF.js → chunk-VRGXYOIN.js} +1 -1
  119. package/dist/cli/chunks/{chunk-JZG23IPV.js → chunk-VSI45JCP.js} +1 -1
  120. package/dist/cli/chunks/{chunk-OXL6JSVR.js → chunk-VWWLJBRA.js} +8 -8
  121. package/dist/cli/chunks/{chunk-WC5A7C5L.js → chunk-VXUIIZNG.js} +1 -1
  122. package/dist/cli/chunks/{chunk-FTIHPDWV.js → chunk-W3IO4FQ5.js} +2 -2
  123. package/dist/cli/chunks/{chunk-FKNYOKIK.js → chunk-WULMXLNN.js} +1 -1
  124. package/dist/cli/chunks/{chunk-ZURHHRSA.js → chunk-WZUQT2BE.js} +2 -2
  125. package/dist/cli/chunks/{chunk-TFUWIKGZ.js → chunk-XF32XZMY.js} +2 -2
  126. package/dist/cli/chunks/{chunk-KV6PIOHN.js → chunk-XKD6AFY5.js} +1 -1
  127. package/dist/cli/chunks/{chunk-6QSB4XOL.js → chunk-XP4T7CZY.js} +2 -2
  128. package/dist/cli/chunks/{chunk-5ROA7KOT.js → chunk-XQZ63XSL.js} +1 -1
  129. package/dist/cli/chunks/{chunk-54TOOHER.js → chunk-XXHJKAE6.js} +2 -2
  130. package/dist/cli/chunks/{chunk-7GGSUXVM.js → chunk-Y3GX66VZ.js} +2 -2
  131. package/dist/cli/chunks/{chunk-JBW2A2O6.js → chunk-YXLQJ226.js} +2 -2
  132. package/dist/cli/chunks/chunk-Z2E5DTKX.js +2 -0
  133. package/dist/cli/chunks/{ci-LYAVZLM3.js → ci-FTZE4PD3.js} +2 -2
  134. package/dist/cli/chunks/{ci-output-L7TR2NCN.js → ci-output-C3ORCIHU.js} +2 -2
  135. package/dist/cli/chunks/{circuit-breaker-AQOGJGKI.js → circuit-breaker-GS5OTOJZ.js} +2 -2
  136. package/dist/cli/chunks/{claude-flow-setup-SO2ZN26K.js → claude-flow-setup-RWOFP5L2.js} +2 -2
  137. package/dist/cli/chunks/client-UTNF2C5K.js +2 -0
  138. package/dist/cli/chunks/{cline-installer-XCXFH4UR.js → cline-installer-D7RGRAUH.js} +2 -2
  139. package/dist/cli/chunks/{code-3Z2HMS5I.js → code-HBDMMYHY.js} +2 -2
  140. package/dist/cli/chunks/{code-index-extractor-KE362AJX.js → code-index-extractor-B2KUPAEH.js} +2 -2
  141. package/dist/cli/chunks/{codex-installer-GTD3GFTF.js → codex-installer-MPXV4AOD.js} +2 -2
  142. package/dist/cli/chunks/{completions-EDCXRRJO.js → completions-QJS6QOZQ.js} +2 -2
  143. package/dist/cli/chunks/{complexity-analyzer-QMN3V6D3.js → complexity-analyzer-YQQXWZIL.js} +2 -2
  144. package/dist/cli/chunks/{continuedev-installer-U6HN376C.js → continuedev-installer-Z6PBKYMB.js} +2 -2
  145. package/dist/cli/chunks/{copilot-installer-54PZIREM.js → copilot-installer-RWVD44CV.js} +2 -2
  146. package/dist/cli/chunks/{cost-tracker-33O475QA.js → cost-tracker-DFPBFYWL.js} +2 -2
  147. package/dist/cli/chunks/{coverage-B7E545AJ.js → coverage-DYST26FK.js} +3 -3
  148. package/dist/cli/chunks/cross-domain-router-FCM34JOR.js +2 -0
  149. package/dist/cli/chunks/{cursor-installer-LKKSPZUM.js → cursor-installer-LL6UWKTZ.js} +2 -2
  150. package/dist/cli/chunks/{daemon-DVOHWXUR.js → daemon-6PIHFZNR.js} +3 -3
  151. package/dist/cli/chunks/{dag-attention-scheduler-EQOHQBUG.js → dag-attention-scheduler-WS3HJW4F.js} +2 -2
  152. package/dist/cli/chunks/{detect-OCB2XT6C.js → detect-J4OITSUD.js} +2 -2
  153. package/dist/cli/chunks/{dist-node-HSG4QK4G.js → dist-node-QSLD5K6K.js} +2 -2
  154. package/dist/cli/chunks/{domain-handler-USGF4CIG.js → domain-handler-BD53QZ4Q.js} +2 -2
  155. package/dist/cli/chunks/{domain-transfer-OUERZRGL.js → domain-transfer-VZBWINQL.js} +2 -2
  156. package/dist/cli/chunks/dream-6KCS7EWS.js +2 -0
  157. package/dist/cli/chunks/embed-and-insert-pattern-5UAFXNDX.js +3 -0
  158. package/dist/cli/chunks/{eval-LHYXXWFK.js → eval-GBKU6VTD.js} +2 -2
  159. package/dist/cli/chunks/{fast-paths-UTK7BN63.js → fast-paths-MYZ6GITZ.js} +2 -2
  160. package/dist/cli/chunks/{feature-flags-XB6ALB3X.js → feature-flags-2WVV66AO.js} +2 -2
  161. package/dist/cli/chunks/{feature-flags-XEP6B4GN.js → feature-flags-6ALWBTHS.js} +2 -2
  162. package/dist/cli/chunks/{file-discovery-O4DUCNHK.js → file-discovery-FOYCPGD6.js} +2 -2
  163. package/dist/cli/chunks/{fleet-37NGGRJI.js → fleet-JROEDHAT.js} +3 -3
  164. package/dist/cli/chunks/{gnn-wrapper-5E7T3IQX.js → gnn-wrapper-KAXTFFEE.js} +2 -2
  165. package/dist/cli/chunks/{heartbeat-handler-Q44PCI7K.js → heartbeat-handler-PG24CBMQ.js} +4 -4
  166. package/dist/cli/chunks/{heartbeat-scheduler-6JPB2AQS.js → heartbeat-scheduler-LSS3RD6E.js} +2 -2
  167. package/dist/cli/chunks/hnsw-adapter-PG6O67CQ.js +2 -0
  168. package/dist/cli/chunks/hnsw-index-AHYZHLNZ.js +2 -0
  169. package/dist/cli/chunks/{hnsw-legacy-bridge-B55GGQYA.js → hnsw-legacy-bridge-HYH4AJAO.js} +2 -2
  170. package/dist/cli/chunks/{hnswlib-node-B3D2XIL5.js → hnswlib-node-WTTST5LC.js} +2 -2
  171. package/dist/cli/chunks/hooks-RDZSAFQG.js +214 -0
  172. package/dist/cli/chunks/{hybrid-router-RV34PYQD.js → hybrid-router-HNPS6EFL.js} +2 -2
  173. package/dist/cli/chunks/{hypergraph-engine-FT5YK5RF.js → hypergraph-engine-JUFXRXCC.js} +2 -2
  174. package/dist/cli/chunks/{hypergraph-handler-EUS6MIYW.js → hypergraph-handler-YFRF53TF.js} +3 -3
  175. package/dist/cli/chunks/impact-analyzer-USAJVJY5.js +2 -0
  176. package/dist/cli/chunks/{init-handler-3MV32TKZ.js → init-handler-P4W5F57S.js} +6 -6
  177. package/dist/cli/chunks/init-wizard-GL7LAZID.js +2 -0
  178. package/dist/cli/chunks/kernel-2YAIESTR.js +2 -0
  179. package/dist/cli/chunks/{kilocode-installer-RZPRXQI2.js → kilocode-installer-5VWY4DMH.js} +2 -2
  180. package/dist/cli/chunks/{kiro-installer-BGDBNZHI.js → kiro-installer-PZC3BQII.js} +2 -2
  181. package/dist/cli/chunks/knowledge-graph-QSIYZRAG.js +2 -0
  182. package/dist/cli/chunks/{learning-KNEBWLEZ.js → learning-4OH4ZG25.js} +3 -3
  183. package/dist/cli/chunks/{llm-router-Q2VQPOQ3.js → llm-router-LZBR6SZQ.js} +4 -4
  184. package/dist/cli/chunks/{load-RL53SYBD.js → load-SPWP6VB3.js} +2 -2
  185. package/dist/cli/chunks/load-test-UEHSHLVN.js +2 -0
  186. package/dist/cli/chunks/{mcp-GTINFFUF.js → mcp-QYPQMM7L.js} +2 -2
  187. package/dist/cli/chunks/{memory-STPMUUAK.js → memory-54ILJMWQ.js} +5 -5
  188. package/dist/cli/chunks/memory-backend-4NE4ADPG.js +2 -0
  189. package/dist/cli/chunks/{memory-handlers-LWX3LPVF.js → memory-handlers-YK7H5UCX.js} +2 -2
  190. package/dist/cli/chunks/{multi-model-executor-36ZYYDA6.js → multi-model-executor-XAOAVPPI.js} +2 -2
  191. package/dist/cli/chunks/{opencode-installer-KTCQKS2K.js → opencode-installer-CNS4XMUF.js} +2 -2
  192. package/dist/cli/chunks/{orchestrator-6EGOOXQG.js → orchestrator-SSEMSKUI.js} +6 -6
  193. package/dist/cli/chunks/{pipeline-WSLAIOYC.js → pipeline-DS3AENTB.js} +2 -2
  194. package/dist/cli/chunks/{platform-MNUN663B.js → platform-BL6LH5NF.js} +2 -2
  195. package/dist/cli/chunks/{plugin-PLDTG4A2.js → plugin-FNXPEQ2C.js} +2 -2
  196. package/dist/cli/chunks/{prime-radiant-advanced-wasm-B4UFONWB.js → prime-radiant-advanced-wasm-E6S6BGNA.js} +2 -2
  197. package/dist/cli/chunks/protocol-executor-YI4HNXND.js +2 -0
  198. package/dist/cli/chunks/{protocol-handler-VAVLLAI2.js → protocol-handler-D4WIUU3W.js} +2 -2
  199. package/dist/cli/chunks/{prove-WVNPDWUC.js → prove-OLB3PKW6.js} +2 -2
  200. package/dist/cli/chunks/{provider-manager-VJF4D6AW.js → provider-manager-GKTQ75DT.js} +2 -2
  201. package/dist/cli/chunks/qe-reasoning-bank-ANBAXQXC.js +2 -0
  202. package/dist/cli/chunks/{quality-LTMHVQBG.js → quality-ZYJVYTUL.js} +2 -2
  203. package/dist/cli/chunks/queen-coordinator-MYYUSWVX.js +2 -0
  204. package/dist/cli/chunks/{real-embeddings-6ACQACTM.js → real-embeddings-SKJRHLCS.js} +2 -2
  205. package/dist/cli/chunks/{roocode-installer-T5ZWC3SS.js → roocode-installer-WZGKOLWE.js} +2 -2
  206. package/dist/cli/chunks/router-RYCLZ7A4.js +2 -0
  207. package/dist/cli/chunks/routing-feedback-5KSRG2UI.js +2 -0
  208. package/dist/cli/chunks/{routing-handler-Y2O2I2HM.js → routing-handler-4GIMINCI.js} +2 -2
  209. package/dist/cli/chunks/{ruvector-commands-F2V36B4W.js → ruvector-commands-YZONXZ2W.js} +2 -2
  210. package/dist/cli/chunks/{rvf-dual-writer-R6CNMPQD.js → rvf-dual-writer-WSS5GF54.js} +2 -2
  211. package/dist/cli/chunks/{rvf-migration-adapter-IDVOB3LN.js → rvf-migration-adapter-WS4HHVEU.js} +2 -2
  212. package/dist/cli/chunks/{rvf-migration-coordinator-VM4AMFZG.js → rvf-migration-coordinator-6BY5GI47.js} +2 -2
  213. package/dist/cli/chunks/rvf-native-adapter-NEIOLJRF.js +2 -0
  214. package/dist/cli/chunks/safe-db-3JQP4EPU.js +2 -0
  215. package/dist/cli/chunks/schedule-2QKCL64E.js +2 -0
  216. package/dist/cli/chunks/scheduler-FMOP45FC.js +2 -0
  217. package/dist/cli/chunks/{security-WQ7YMR6M.js → security-HCNOL2K3.js} +3 -3
  218. package/dist/cli/chunks/shared-rvf-adapter-BMFIVWMJ.js +2 -0
  219. package/dist/cli/chunks/{shared-rvf-dual-writer-HYI64CBX.js → shared-rvf-dual-writer-QRNLSDS7.js} +2 -2
  220. package/dist/cli/chunks/sqlite-persistence-I5RYLFOE.js +2 -0
  221. package/dist/cli/chunks/{status-handler-BH2WCMPA.js → status-handler-QXZ442MY.js} +2 -2
  222. package/dist/cli/chunks/{structural-health-XWX6FKVF.js → structural-health-OFYZ3Z4A.js} +2 -2
  223. package/dist/cli/chunks/{sync-PRDGCHE2.js → sync-J4BG65NF.js} +2 -2
  224. package/dist/cli/chunks/{task-handler-YFHFBMHO.js → task-handler-UBSFCKK3.js} +2 -2
  225. package/dist/cli/chunks/{task-handlers-4OQRADMG.js → task-handlers-JFUT2FQ7.js} +2 -2
  226. package/dist/cli/chunks/{test-ZBTQ4Z66.js → test-WTNAHJHH.js} +4 -4
  227. package/dist/cli/chunks/{test-scheduling-F47Y3KNO.js → test-scheduling-QREBYRGW.js} +3 -3
  228. package/dist/cli/chunks/{token-bootstrap-XOGAEQPG.js → token-bootstrap-HE5H77OL.js} +2 -2
  229. package/dist/cli/chunks/{token-usage-2KZ7WE5J.js → token-usage-V5B6K3JL.js} +2 -2
  230. package/dist/cli/chunks/{transformers-KCJ7PWZ4.js → transformers-HIVMQP4O.js} +2 -2
  231. package/dist/cli/chunks/{tree-sitter-wasm-parser-H6DL2DFA.js → tree-sitter-wasm-parser-WP2SF2M5.js} +2 -2
  232. package/dist/cli/chunks/{types-633TMIO3.js → types-7ZBTAO5Z.js} +2 -2
  233. package/dist/cli/chunks/unified-memory-2ETCY22B.js +2 -0
  234. package/dist/cli/chunks/unified-memory-hnsw-OALJW537.js +2 -0
  235. package/dist/cli/chunks/unified-persistence-SQMP7A3O.js +2 -0
  236. package/dist/cli/chunks/{upgrade-CH742GRF.js → upgrade-WIFAJDBG.js} +2 -2
  237. package/dist/cli/chunks/{validate-44WH3CKE.js → validate-W63V36GA.js} +2 -2
  238. package/dist/cli/chunks/{validate-swarm-W2A7CUM7.js → validate-swarm-CK5BM3YY.js} +2 -2
  239. package/dist/cli/chunks/{vibium-B25MIEBK.js → vibium-MJCCO36E.js} +2 -2
  240. package/dist/cli/chunks/visual-security-JUJPF2QO.js +2 -0
  241. package/dist/cli/chunks/{web-tree-sitter-B54K47HF.js → web-tree-sitter-ESERXLPK.js} +2 -2
  242. package/dist/cli/chunks/{windsurf-installer-EWL7COTI.js → windsurf-installer-FDWQ5BWI.js} +2 -2
  243. package/dist/cli/chunks/{witness-chain-DWNP7VR6.js → witness-chain-L5KSYE2S.js} +2 -2
  244. package/dist/cli/chunks/witness-chain-QJVKAAZT.js +2 -0
  245. package/dist/cli/chunks/{workflow-LT2J7U23.js → workflow-34GYJDFW.js} +4 -4
  246. package/dist/cli/chunks/workflow-orchestrator-WXB2RVVW.js +2 -0
  247. package/dist/cli/chunks/{wrappers-OAZ6MKXO.js → wrappers-VGKEBQLW.js} +2 -2
  248. package/dist/cli/commands/hooks-handlers/command-hooks.js +104 -11
  249. package/dist/cli/commands/hooks-handlers/hooks-dream-learning.d.ts +98 -0
  250. package/dist/cli/commands/hooks-handlers/hooks-dream-learning.js +285 -1
  251. package/dist/cli/commands/hooks-handlers/hooks-shared.d.ts +20 -1
  252. package/dist/cli/commands/hooks-handlers/hooks-shared.js +35 -3
  253. package/dist/cli/commands/hooks-handlers/routing-hooks.js +15 -5
  254. package/dist/cli/commands/hooks-handlers/task-hooks.js +216 -5
  255. package/dist/coordination/task-executor.js +11 -2
  256. package/dist/init/phases/07-hooks.js +2 -2
  257. package/dist/integrations/ruvector/hypergraph-engine.js +63 -4
  258. package/dist/integrations/ruvector/hypergraph-schema.d.ts +6 -2
  259. package/dist/learning/embed-and-insert-pattern.d.ts +36 -0
  260. package/dist/learning/embed-and-insert-pattern.js +52 -0
  261. package/dist/learning/pattern-store.d.ts +8 -0
  262. package/dist/learning/pattern-store.js +66 -43
  263. package/dist/mcp/bundle.js +333 -327
  264. package/dist/mcp/entry.js +21 -1
  265. package/dist/workers/workers/learning-consolidation.js +6 -1
  266. package/package.json +1 -1
  267. package/dist/cli/chunks/adapter-C7AKAAPC.js +0 -2
  268. package/dist/cli/chunks/aqe-learning-engine-7P3AXQNO.js +0 -2
  269. package/dist/cli/chunks/base-GIDVLEPA.js +0 -2
  270. package/dist/cli/chunks/browser-workflow-DAUS4Z5V.js +0 -2
  271. package/dist/cli/chunks/chunk-4XYQJ4LQ.js +0 -2
  272. package/dist/cli/chunks/chunk-NKOLFLXF.js +0 -66
  273. package/dist/cli/chunks/client-LIKTMSIP.js +0 -2
  274. package/dist/cli/chunks/cross-domain-router-SSBT32Q3.js +0 -2
  275. package/dist/cli/chunks/dream-FAHB6BWB.js +0 -2
  276. package/dist/cli/chunks/hnsw-adapter-GQM3ONQE.js +0 -2
  277. package/dist/cli/chunks/hnsw-index-XF3NY4R4.js +0 -2
  278. package/dist/cli/chunks/hooks-MOBQSJLJ.js +0 -101
  279. package/dist/cli/chunks/impact-analyzer-V6PBIMZH.js +0 -2
  280. package/dist/cli/chunks/init-wizard-7ROJWLEO.js +0 -2
  281. package/dist/cli/chunks/kernel-AOUBGDXU.js +0 -2
  282. package/dist/cli/chunks/knowledge-graph-SJA3YGMQ.js +0 -2
  283. package/dist/cli/chunks/load-test-NSHIGHCV.js +0 -2
  284. package/dist/cli/chunks/memory-backend-SZAYMQVP.js +0 -2
  285. package/dist/cli/chunks/protocol-executor-22KKAYX2.js +0 -2
  286. package/dist/cli/chunks/qe-reasoning-bank-N7ZXOAEN.js +0 -2
  287. package/dist/cli/chunks/queen-coordinator-BC54OCHH.js +0 -2
  288. package/dist/cli/chunks/router-YTQZRTIB.js +0 -2
  289. package/dist/cli/chunks/routing-feedback-AASAMEUY.js +0 -2
  290. package/dist/cli/chunks/rvf-native-adapter-VHIHJOPA.js +0 -2
  291. package/dist/cli/chunks/safe-db-NVEBL662.js +0 -2
  292. package/dist/cli/chunks/schedule-KVUFE56T.js +0 -2
  293. package/dist/cli/chunks/scheduler-6GRLJZ2A.js +0 -2
  294. package/dist/cli/chunks/shared-rvf-adapter-XORIDF3Q.js +0 -2
  295. package/dist/cli/chunks/sqlite-persistence-25TDMX6G.js +0 -2
  296. package/dist/cli/chunks/unified-memory-BTX45KY5.js +0 -2
  297. package/dist/cli/chunks/unified-memory-hnsw-MMHMQ4CP.js +0 -2
  298. package/dist/cli/chunks/unified-persistence-GA7HKYZC.js +0 -2
  299. package/dist/cli/chunks/visual-security-HPF5HCYF.js +0 -2
  300. package/dist/cli/chunks/witness-chain-LROQLFND.js +0 -2
  301. package/dist/cli/chunks/workflow-orchestrator-VFRKGG5Y.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.9.18");process.exit(0)}
2
- import{b as ye}from"./chunk-MDCTQOUJ.js";import{a as ht,b as ft}from"./chunk-ZWR4PZ4Z.js";import{a as yt}from"./chunk-WC5A7C5L.js";import{a as mt,b as pt}from"./chunk-B6BAK2JI.js";import{b as gt,d as z}from"./chunk-FDDB7QTM.js";import{j as I}from"./chunk-MJ7UYPGY.js";import{a as ct}from"./chunk-V2N7KWT7.js";import{a as fe}from"./chunk-G2H4W7NN.js";import{k as w,o as he}from"./chunk-RPT7HCMH.js";import{a as un}from"./chunk-4XYQJ4LQ.js";import{c as ut}from"./chunk-6KTF7QB3.js";import{b as E,d as dt}from"./chunk-6ZMQL3U6.js";import{a as T,b as C,c as y}from"./chunk-TPL3CBMS.js";import{a as p,b as lt,c as k}from"./chunk-UNPTSPAO.js";import{i as f}from"./chunk-LVABI4OA.js";import{R as dn,S as gn}from"./chunk-FTIHPDWV.js";import{c as G,e as cn,g as ot}from"./chunk-FKNYOKIK.js";function Ct(s){let e=[],t=0;if(s.fileCount!==void 0&&(s.fileCount>20?(t+=25,e.push({name:"very-high-file-count",weight:25,description:`Task involves ${s.fileCount} files (>20)`})):s.fileCount>10?(t+=20,e.push({name:"high-file-count",weight:20,description:`Task involves ${s.fileCount} files (>10)`})):s.fileCount>5&&(t+=10,e.push({name:"moderate-file-count",weight:10,description:`Task involves ${s.fileCount} files (>5)`}))),s.domain&&(hn.includes(s.domain)?(t+=30,e.push({name:"complex-domain",weight:30,description:`Domain '${s.domain}' requires complex reasoning`})):fn.includes(s.domain)&&(t+=15,e.push({name:"moderate-domain",weight:15,description:`Domain '${s.domain}' has moderate complexity`}))),s.crossComponent&&(t+=25,e.push({name:"cross-component",weight:25,description:"Task spans multiple components/modules"})),s.priority==="critical"?(t+=25,e.push({name:"critical-priority",weight:25,description:"Critical priority requires careful attention"})):s.priority==="high"&&(t+=15,e.push({name:"high-priority",weight:15,description:"High priority task"})),s.requiredCapabilities){let r=s.requiredCapabilities.filter(a=>yn.includes(a)).length;if(r>0){let a=Math.min(20,r*10);t+=a,e.push({name:"complex-capabilities",weight:a,description:`Requires ${r} complex capabilit${r===1?"y":"ies"}`})}}s.requiresExternalApis&&(t+=10,e.push({name:"external-apis",weight:10,description:"Requires external API integration"})),s.involvesDatabaseOps&&(t+=10,e.push({name:"database-ops",weight:10,description:"Involves database operations"})),s.timeSensitive&&(t+=5,e.push({name:"time-sensitive",weight:5,description:"Time-sensitive task"})),s.estimatedLinesAffected!==void 0&&(s.estimatedLinesAffected>500?(t+=15,e.push({name:"large-change",weight:15,description:`Estimated ${s.estimatedLinesAffected} lines affected (>500)`})):s.estimatedLinesAffected>200&&(t+=10,e.push({name:"medium-change",weight:10,description:`Estimated ${s.estimatedLinesAffected} lines affected (>200)`}))),(s.type==="security-scan"||s.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=Tn[n];return{complexity:n,recommendedModel:i,factors:e,score:t,timestamp:new Date}}var hn,fn,yn,S,Tn,bt=G(()=>{"use strict";hn=["security-compliance","chaos-resilience","defect-intelligence"],fn=["code-intelligence","contract-testing","quality-assessment","learning-optimization"],yn=["sast","dast","vulnerability","owasp","chaos-testing","resilience","fault-injection","mutation-testing"],S={critical:70,complex:45,moderate:20},Tn={critical:"opus",complex:"sonnet",moderate:"sonnet",simple:"haiku"}});var R,De=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 a=Math.random(),o=Math.random(),c=Math.sqrt(-2*Math.log(Math.max(a,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 a=0;a<4;a++)r+=e[a]*this.weightsInputHidden[a*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 a=0;a<32;a++)r+=t[a]*this.weightsHiddenOutput[a*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 a=0;a<e.length;a++)n[a]=Math.exp(e[a]-t),i+=n[a];let r=[];for(let a=0;a<e.length;a++)r.push(n[a]/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 a=this.softmax(r),o=new Float32Array(3);for(let l=0;l<3;l++)o[l]=(l===t?1:0)-a[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 St={};cn(St,{NeuralTinyDancerRouter:()=>V,SimpleNeuralRouter:()=>R,createNeuralTinyDancerRouter:()=>Mn});import{performance as kt}from"perf_hooks";function Mn(s){return new V(s)}var vn,Cn,bn,kn,Sn,xn,Dn,An,V,xt=G(()=>{"use strict";Ae();De();De();vn=1e3,Cn=.1,bn=.2,kn=50,Sn=.01,xn=["haiku","sonnet","opus"],Dn={haiku:0,sonnet:1,opus:2},An={"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},V=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??Sn),this.circuitBreakerThreshold=e.circuitBreakerThreshold??bn,this.shadowModeDecisionLimit=e.shadowModeDecisions??vn,this.shadowModeMaxDisagreement=e.shadowModeMaxDisagreement??Cn,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=kt.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 a=this.argmax(r),o=xn[a],c=r[a];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=kt.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,a=(i+r)/4,o=Math.min(1,a/1e4),c=e.domain??"",l=An[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,a=0){this.ruleRouter.recordOutcome(e,t,n,i,r,a);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>kn&&this.recentOutcomes.shift(),this.checkCircuitBreaker();let l=this.extractFeatures(e,t.classification),u=Dn[r],d=(i-.5)*2;try{this.neuralNet.updateWeights(l,u,d),this.totalWeightUpdates++}catch{}let g=this.neuralNet.forward(l),h=this.argmax(g),b=1-g[u];this.calibrationScores.push(b),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),a=Math.ceil(.9*r.length)-1,o=r[Math.min(a,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 a=[];return a.push(`[Neural] Routing to ${e.toUpperCase()}`),a.push(`with ${(t*100).toFixed(0)}% neural confidence.`),a.push(`Tier probabilities: haiku=${(n[0]*100).toFixed(0)}%,`),a.push(`sonnet=${(n[1]*100).toFixed(0)}%,`),a.push(`opus=${(n[2]*100).toFixed(0)}%.`),e!==i.model&&a.push(`Rule-based would choose ${i.model.toUpperCase()}.`),a.push(`Empirical bounds: [${r.lower.toFixed(2)}, ${r.upper.toFixed(2)}]`),a.push(`at ${(r.coverageLevel*100).toFixed(0)}% coverage.`),a.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 Dt}from"perf_hooks";function At(s){try{let{getRuVectorFeatureFlags:e}=(gn(),ot(dn));if(e().useNeuralRouting){let{NeuralTinyDancerRouter:n}=(xt(),ot(St));return new n(s)}}catch(e){process.env.DEBUG&&console.debug("[Router] Neural router unavailable, using rule-based:",e instanceof Error?e.message:e)}return new H(s)}var H,Ae=G(()=>{"use strict";bt();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=Dt.now(),n=Ct(e),i=this.calculateConfidence(n),r=1-i,a=this.isSecurityTask(e),o=a&&i<this.securityConfidenceThreshold||i<this.confidenceThreshold&&n.complexity!=="simple",c=r>this.uncertaintyThreshold||a&&n.complexity==="critical",l=Dt.now()-t,u=this.buildReasoning(n,i,a,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 a=.55,o=.35,c=Math.min(r/25,1),l=a+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(a=>n.includes(a)))return!0;let i=["security","vulnerability","cve","owasp","exploit","injection"],r=e.description.toLowerCase();return!!i.some(a=>r.includes(a))}buildReasoning(e,t,n,i,r){let a=[];if(a.push(`Routing to ${e.recommendedModel.toUpperCase()}`),a.push(`(complexity: ${e.complexity}, score: ${e.score})`),a.push(`with ${(t*100).toFixed(0)}% confidence.`),e.factors.length>0){let o=e.factors.slice(0,3).map(c=>c.name).join(", ");a.push(`Key factors: ${o}.`)}return n&&a.push("Security-sensitive task detected."),i&&a.push("Multi-model verification recommended due to uncertainty."),r&&a.push("Human review flagged due to high uncertainty or criticality."),a.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,a=0){if(!this.enableLearning)return;let o={task:e,routeResult:t,success:n,qualityScore:i,actualModelUsed:r,durationMs:a,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 mn={enableConsoleLog:!0,maxEntries:1e3,logPrefix:"[TASK]"},q=class{entries=[];config;constructor(e={}){this.config={...mn,...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}`:"",a=n?.domain?` (${n.domain})`:"";console.log(`${this.config.logPrefix} ${e.toUpperCase()} ${t}${r}${a}`)}}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 Te(s){return new q(s)}var j={healthyThreshold:3,warningThreshold:2,checkIntervalMs:5e3,maxHistoryEntries:100,alertsEnabled:!0,alertCooldownMs:6e4,selfHealingEnabled:!1,maxHealingActionsPerMinute:5};var ve=class{calculator;config;eventBus;persistence;graph;history=[];alerts=new Map;lastAlertTime=new Map;monitoringInterval=null;isMonitoring=!1;constructor(e,t={},n,i){this.graph=e,this.config={...j,...t},this.calculator=gt(),this.eventBus=n,this.persistence=i}start(){this.isMonitoring||(this.isMonitoring=!0,this.monitoringInterval=setInterval(()=>this.checkHealth(),this.config.checkIntervalMs),this.checkHealth())}stop(){this.monitoringInterval&&(clearInterval(this.monitoringInterval),this.monitoringInterval=null),this.isMonitoring=!1}updateGraph(e){this.graph=e,this.isMonitoring&&this.checkHealth()}isEmptyTopology(){return this.graph.getVerticesByType("agent").length===0}checkHealth(){let e=this.calculator.getMinCutValue(this.graph),t=this.calculator.findWeakVertices(this.graph),n=this.isEmptyTopology()?"idle":this.determineStatus(e),i=this.calculateTrend();return this.recordHistory(e),this.isEmptyTopology()||this.checkAlertConditions(e,t,n),this.persistence&&t.length>0&&this.persistence.saveWeakVertices(t).catch(r=>console.warn("[MinCutHealthMonitor] Failed to persist weak vertices:",r)),this.emitEvent("mincut.updated",e,{status:n,weakVertexCount:t.length}),{status:n,minCutValue:e,healthyThreshold:this.config.healthyThreshold,warningThreshold:this.config.warningThreshold,weakVertexCount:t.length,topWeakVertices:t.slice(0,5),trend:i,history:this.history.slice(-20),lastUpdated:new Date}}getHealth(){let e=this.calculator.getMinCutValue(this.graph),t=this.calculator.findWeakVertices(this.graph);return{status:this.isEmptyTopology()?"idle":this.determineStatus(e),minCutValue:e,healthyThreshold:this.config.healthyThreshold,warningThreshold:this.config.warningThreshold,weakVertexCount:t.length,topWeakVertices:t.slice(0,5),trend:this.calculateTrend(),history:this.history.slice(-20),lastUpdated:new Date}}getMinCutValue(){return this.calculator.getMinCutValue(this.graph)}getWeakVertices(){return this.calculator.findWeakVertices(this.graph)}isCritical(){return this.calculator.getMinCutValue(this.graph)<this.config.warningThreshold}isHealthy(){return this.calculator.getMinCutValue(this.graph)>=this.config.healthyThreshold}getActiveAlerts(){return Array.from(this.alerts.values()).filter(e=>!e.acknowledged).sort((e,t)=>{let n={critical:0,high:1,medium:2,low:3,info:4};return n[e.severity]-n[t.severity]})}getAllAlerts(){return Array.from(this.alerts.values())}acknowledgeAlert(e){let t=this.alerts.get(e);return t?(t.acknowledged=!0,!0):!1}clearAcknowledgedAlerts(){let e=[];for(let[t,n]of this.alerts)n.acknowledged&&e.push(t);for(let t of e)this.alerts.delete(t);return e.length}getHistory(){return[...this.history]}getTrend(){return this.calculateTrend()}getStats(e=6e4){let t=Date.now()-e,n=this.history.filter(r=>r.timestamp.getTime()>t);if(n.length===0){let r=this.calculator.getMinCutValue(this.graph);return{min:r,max:r,average:r,count:0}}let i=n.map(r=>r.value);return{min:Math.min(...i),max:Math.max(...i),average:i.reduce((r,a)=>r+a,0)/i.length,count:n.length}}updateConfig(e){Object.assign(this.config,e),e.checkIntervalMs&&this.isMonitoring&&(this.stop(),this.start())}getConfig(){return{...this.config}}determineStatus(e){return e>=this.config.healthyThreshold?"healthy":e>=this.config.warningThreshold?"warning":"critical"}calculateTrend(){if(this.history.length<3)return"stable";let e=this.history.slice(-5),t=e[0].value,i=e[e.length-1].value-t,a=e.reduce((o,c)=>o+c.value,0)/e.length*.1;return i>a?"improving":i<-a?"degrading":"stable"}recordHistory(e){let t={timestamp:new Date,value:e,vertexCount:this.graph.vertexCount,edgeCount:this.graph.edgeCount};for(this.history.push(t);this.history.length>this.config.maxHistoryEntries;)this.history.shift()}checkAlertConditions(e,t,n){if(!this.config.alertsEnabled)return;let i=Date.now();n==="critical"?this.maybeGenerateAlert("critical-threshold","critical",`MinCut value (${e.toFixed(2)}) is below critical threshold (${this.config.warningThreshold})`,e,this.config.warningThreshold,t):n==="warning"&&this.maybeGenerateAlert("warning-threshold","high",`MinCut value (${e.toFixed(2)}) is below healthy threshold (${this.config.healthyThreshold})`,e,this.config.healthyThreshold,t);let r=t.filter(o=>o.weightedDegree===0);r.length>0&&this.maybeGenerateAlert("isolated-vertices","high",`${r.length} isolated vertex(es) detected`,e,0,r);let a=t.filter(o=>o.riskScore>.8);a.length>0&&this.maybeGenerateAlert("critical-vertices","medium",`${a.length} critical vertex(es) with high risk score`,e,0,a)}maybeGenerateAlert(e,t,n,i,r,a){let o=Date.now(),c=this.lastAlertTime.get(e)||0;if(o-c<this.config.alertCooldownMs)return;let l={id:f(),severity:t,message:n,minCutValue:i,threshold:r,affectedVertices:a.map(u=>u.vertexId),timestamp:new Date,acknowledged:!1,remediations:a.flatMap(u=>u.suggestions).slice(0,5)};this.alerts.set(l.id,l),this.persistence&&this.persistence.saveAlert(l).catch(u=>console.warn("[MinCutHealthMonitor] Failed to persist alert:",u)),this.lastAlertTime.set(e,o),this.emitEvent("mincut.alert.generated",i,{alert:l})}emitEvent(e,t,n){if(!this.eventBus)return;let i={id:f(),type:e,source:"coordination",timestamp:new Date,correlationId:f(),payload:{minCutValue:t,...n}};this.eventBus.publish(i).catch(r=>{console.error("Failed to publish MinCut event:",r)})}};function W(s,e,t,n){return new ve(s,e,t,n)}he();dt();var Ce=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=f();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.9.19");process.exit(0)}
2
+ import{b as ye}from"./chunk-5X2AUPK2.js";import{a as ht,b as ft}from"./chunk-BFBR2ZZJ.js";import{a as yt}from"./chunk-VXUIIZNG.js";import{a as mt,b as pt}from"./chunk-UIASVDYG.js";import{b as gt,d as z}from"./chunk-JYHZK44T.js";import{j as I}from"./chunk-GJ5FON37.js";import{a as ct}from"./chunk-M6EP724N.js";import{a as fe}from"./chunk-6BRUQTC7.js";import{k as w,o as he}from"./chunk-TXCOK5DC.js";import{a as un}from"./chunk-Z2E5DTKX.js";import{c as ut}from"./chunk-5KGFDNYI.js";import{b as E,d as dt}from"./chunk-5R2DUR3A.js";import{a as T,b as C,c as y}from"./chunk-N2PLNYEV.js";import{a as p,b as lt,c as k}from"./chunk-5MGRZ4YD.js";import{i as f}from"./chunk-MIQAFOFO.js";import{R as dn,S as gn}from"./chunk-W3IO4FQ5.js";import{c as G,e as cn,g as ot}from"./chunk-WULMXLNN.js";function Ct(s){let e=[],t=0;if(s.fileCount!==void 0&&(s.fileCount>20?(t+=25,e.push({name:"very-high-file-count",weight:25,description:`Task involves ${s.fileCount} files (>20)`})):s.fileCount>10?(t+=20,e.push({name:"high-file-count",weight:20,description:`Task involves ${s.fileCount} files (>10)`})):s.fileCount>5&&(t+=10,e.push({name:"moderate-file-count",weight:10,description:`Task involves ${s.fileCount} files (>5)`}))),s.domain&&(hn.includes(s.domain)?(t+=30,e.push({name:"complex-domain",weight:30,description:`Domain '${s.domain}' requires complex reasoning`})):fn.includes(s.domain)&&(t+=15,e.push({name:"moderate-domain",weight:15,description:`Domain '${s.domain}' has moderate complexity`}))),s.crossComponent&&(t+=25,e.push({name:"cross-component",weight:25,description:"Task spans multiple components/modules"})),s.priority==="critical"?(t+=25,e.push({name:"critical-priority",weight:25,description:"Critical priority requires careful attention"})):s.priority==="high"&&(t+=15,e.push({name:"high-priority",weight:15,description:"High priority task"})),s.requiredCapabilities){let r=s.requiredCapabilities.filter(a=>yn.includes(a)).length;if(r>0){let a=Math.min(20,r*10);t+=a,e.push({name:"complex-capabilities",weight:a,description:`Requires ${r} complex capabilit${r===1?"y":"ies"}`})}}s.requiresExternalApis&&(t+=10,e.push({name:"external-apis",weight:10,description:"Requires external API integration"})),s.involvesDatabaseOps&&(t+=10,e.push({name:"database-ops",weight:10,description:"Involves database operations"})),s.timeSensitive&&(t+=5,e.push({name:"time-sensitive",weight:5,description:"Time-sensitive task"})),s.estimatedLinesAffected!==void 0&&(s.estimatedLinesAffected>500?(t+=15,e.push({name:"large-change",weight:15,description:`Estimated ${s.estimatedLinesAffected} lines affected (>500)`})):s.estimatedLinesAffected>200&&(t+=10,e.push({name:"medium-change",weight:10,description:`Estimated ${s.estimatedLinesAffected} lines affected (>200)`}))),(s.type==="security-scan"||s.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=Tn[n];return{complexity:n,recommendedModel:i,factors:e,score:t,timestamp:new Date}}var hn,fn,yn,S,Tn,bt=G(()=>{"use strict";hn=["security-compliance","chaos-resilience","defect-intelligence"],fn=["code-intelligence","contract-testing","quality-assessment","learning-optimization"],yn=["sast","dast","vulnerability","owasp","chaos-testing","resilience","fault-injection","mutation-testing"],S={critical:70,complex:45,moderate:20},Tn={critical:"opus",complex:"sonnet",moderate:"sonnet",simple:"haiku"}});var R,De=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 a=Math.random(),o=Math.random(),c=Math.sqrt(-2*Math.log(Math.max(a,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 a=0;a<4;a++)r+=e[a]*this.weightsInputHidden[a*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 a=0;a<32;a++)r+=t[a]*this.weightsHiddenOutput[a*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 a=0;a<e.length;a++)n[a]=Math.exp(e[a]-t),i+=n[a];let r=[];for(let a=0;a<e.length;a++)r.push(n[a]/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 a=this.softmax(r),o=new Float32Array(3);for(let l=0;l<3;l++)o[l]=(l===t?1:0)-a[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 St={};cn(St,{NeuralTinyDancerRouter:()=>V,SimpleNeuralRouter:()=>R,createNeuralTinyDancerRouter:()=>Mn});import{performance as kt}from"perf_hooks";function Mn(s){return new V(s)}var vn,Cn,bn,kn,Sn,xn,Dn,An,V,xt=G(()=>{"use strict";Ae();De();De();vn=1e3,Cn=.1,bn=.2,kn=50,Sn=.01,xn=["haiku","sonnet","opus"],Dn={haiku:0,sonnet:1,opus:2},An={"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},V=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??Sn),this.circuitBreakerThreshold=e.circuitBreakerThreshold??bn,this.shadowModeDecisionLimit=e.shadowModeDecisions??vn,this.shadowModeMaxDisagreement=e.shadowModeMaxDisagreement??Cn,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=kt.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 a=this.argmax(r),o=xn[a],c=r[a];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=kt.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,a=(i+r)/4,o=Math.min(1,a/1e4),c=e.domain??"",l=An[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,a=0){this.ruleRouter.recordOutcome(e,t,n,i,r,a);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>kn&&this.recentOutcomes.shift(),this.checkCircuitBreaker();let l=this.extractFeatures(e,t.classification),u=Dn[r],d=(i-.5)*2;try{this.neuralNet.updateWeights(l,u,d),this.totalWeightUpdates++}catch{}let g=this.neuralNet.forward(l),h=this.argmax(g),b=1-g[u];this.calibrationScores.push(b),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),a=Math.ceil(.9*r.length)-1,o=r[Math.min(a,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 a=[];return a.push(`[Neural] Routing to ${e.toUpperCase()}`),a.push(`with ${(t*100).toFixed(0)}% neural confidence.`),a.push(`Tier probabilities: haiku=${(n[0]*100).toFixed(0)}%,`),a.push(`sonnet=${(n[1]*100).toFixed(0)}%,`),a.push(`opus=${(n[2]*100).toFixed(0)}%.`),e!==i.model&&a.push(`Rule-based would choose ${i.model.toUpperCase()}.`),a.push(`Empirical bounds: [${r.lower.toFixed(2)}, ${r.upper.toFixed(2)}]`),a.push(`at ${(r.coverageLevel*100).toFixed(0)}% coverage.`),a.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 Dt}from"perf_hooks";function At(s){try{let{getRuVectorFeatureFlags:e}=(gn(),ot(dn));if(e().useNeuralRouting){let{NeuralTinyDancerRouter:n}=(xt(),ot(St));return new n(s)}}catch(e){process.env.DEBUG&&console.debug("[Router] Neural router unavailable, using rule-based:",e instanceof Error?e.message:e)}return new H(s)}var H,Ae=G(()=>{"use strict";bt();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=Dt.now(),n=Ct(e),i=this.calculateConfidence(n),r=1-i,a=this.isSecurityTask(e),o=a&&i<this.securityConfidenceThreshold||i<this.confidenceThreshold&&n.complexity!=="simple",c=r>this.uncertaintyThreshold||a&&n.complexity==="critical",l=Dt.now()-t,u=this.buildReasoning(n,i,a,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 a=.55,o=.35,c=Math.min(r/25,1),l=a+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(a=>n.includes(a)))return!0;let i=["security","vulnerability","cve","owasp","exploit","injection"],r=e.description.toLowerCase();return!!i.some(a=>r.includes(a))}buildReasoning(e,t,n,i,r){let a=[];if(a.push(`Routing to ${e.recommendedModel.toUpperCase()}`),a.push(`(complexity: ${e.complexity}, score: ${e.score})`),a.push(`with ${(t*100).toFixed(0)}% confidence.`),e.factors.length>0){let o=e.factors.slice(0,3).map(c=>c.name).join(", ");a.push(`Key factors: ${o}.`)}return n&&a.push("Security-sensitive task detected."),i&&a.push("Multi-model verification recommended due to uncertainty."),r&&a.push("Human review flagged due to high uncertainty or criticality."),a.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,a=0){if(!this.enableLearning)return;let o={task:e,routeResult:t,success:n,qualityScore:i,actualModelUsed:r,durationMs:a,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 mn={enableConsoleLog:!0,maxEntries:1e3,logPrefix:"[TASK]"},q=class{entries=[];config;constructor(e={}){this.config={...mn,...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}`:"",a=n?.domain?` (${n.domain})`:"";console.log(`${this.config.logPrefix} ${e.toUpperCase()} ${t}${r}${a}`)}}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 Te(s){return new q(s)}var j={healthyThreshold:3,warningThreshold:2,checkIntervalMs:5e3,maxHistoryEntries:100,alertsEnabled:!0,alertCooldownMs:6e4,selfHealingEnabled:!1,maxHealingActionsPerMinute:5};var ve=class{calculator;config;eventBus;persistence;graph;history=[];alerts=new Map;lastAlertTime=new Map;monitoringInterval=null;isMonitoring=!1;constructor(e,t={},n,i){this.graph=e,this.config={...j,...t},this.calculator=gt(),this.eventBus=n,this.persistence=i}start(){this.isMonitoring||(this.isMonitoring=!0,this.monitoringInterval=setInterval(()=>this.checkHealth(),this.config.checkIntervalMs),this.checkHealth())}stop(){this.monitoringInterval&&(clearInterval(this.monitoringInterval),this.monitoringInterval=null),this.isMonitoring=!1}updateGraph(e){this.graph=e,this.isMonitoring&&this.checkHealth()}isEmptyTopology(){return this.graph.getVerticesByType("agent").length===0}checkHealth(){let e=this.calculator.getMinCutValue(this.graph),t=this.calculator.findWeakVertices(this.graph),n=this.isEmptyTopology()?"idle":this.determineStatus(e),i=this.calculateTrend();return this.recordHistory(e),this.isEmptyTopology()||this.checkAlertConditions(e,t,n),this.persistence&&t.length>0&&this.persistence.saveWeakVertices(t).catch(r=>console.warn("[MinCutHealthMonitor] Failed to persist weak vertices:",r)),this.emitEvent("mincut.updated",e,{status:n,weakVertexCount:t.length}),{status:n,minCutValue:e,healthyThreshold:this.config.healthyThreshold,warningThreshold:this.config.warningThreshold,weakVertexCount:t.length,topWeakVertices:t.slice(0,5),trend:i,history:this.history.slice(-20),lastUpdated:new Date}}getHealth(){let e=this.calculator.getMinCutValue(this.graph),t=this.calculator.findWeakVertices(this.graph);return{status:this.isEmptyTopology()?"idle":this.determineStatus(e),minCutValue:e,healthyThreshold:this.config.healthyThreshold,warningThreshold:this.config.warningThreshold,weakVertexCount:t.length,topWeakVertices:t.slice(0,5),trend:this.calculateTrend(),history:this.history.slice(-20),lastUpdated:new Date}}getMinCutValue(){return this.calculator.getMinCutValue(this.graph)}getWeakVertices(){return this.calculator.findWeakVertices(this.graph)}isCritical(){return this.calculator.getMinCutValue(this.graph)<this.config.warningThreshold}isHealthy(){return this.calculator.getMinCutValue(this.graph)>=this.config.healthyThreshold}getActiveAlerts(){return Array.from(this.alerts.values()).filter(e=>!e.acknowledged).sort((e,t)=>{let n={critical:0,high:1,medium:2,low:3,info:4};return n[e.severity]-n[t.severity]})}getAllAlerts(){return Array.from(this.alerts.values())}acknowledgeAlert(e){let t=this.alerts.get(e);return t?(t.acknowledged=!0,!0):!1}clearAcknowledgedAlerts(){let e=[];for(let[t,n]of this.alerts)n.acknowledged&&e.push(t);for(let t of e)this.alerts.delete(t);return e.length}getHistory(){return[...this.history]}getTrend(){return this.calculateTrend()}getStats(e=6e4){let t=Date.now()-e,n=this.history.filter(r=>r.timestamp.getTime()>t);if(n.length===0){let r=this.calculator.getMinCutValue(this.graph);return{min:r,max:r,average:r,count:0}}let i=n.map(r=>r.value);return{min:Math.min(...i),max:Math.max(...i),average:i.reduce((r,a)=>r+a,0)/i.length,count:n.length}}updateConfig(e){Object.assign(this.config,e),e.checkIntervalMs&&this.isMonitoring&&(this.stop(),this.start())}getConfig(){return{...this.config}}determineStatus(e){return e>=this.config.healthyThreshold?"healthy":e>=this.config.warningThreshold?"warning":"critical"}calculateTrend(){if(this.history.length<3)return"stable";let e=this.history.slice(-5),t=e[0].value,i=e[e.length-1].value-t,a=e.reduce((o,c)=>o+c.value,0)/e.length*.1;return i>a?"improving":i<-a?"degrading":"stable"}recordHistory(e){let t={timestamp:new Date,value:e,vertexCount:this.graph.vertexCount,edgeCount:this.graph.edgeCount};for(this.history.push(t);this.history.length>this.config.maxHistoryEntries;)this.history.shift()}checkAlertConditions(e,t,n){if(!this.config.alertsEnabled)return;let i=Date.now();n==="critical"?this.maybeGenerateAlert("critical-threshold","critical",`MinCut value (${e.toFixed(2)}) is below critical threshold (${this.config.warningThreshold})`,e,this.config.warningThreshold,t):n==="warning"&&this.maybeGenerateAlert("warning-threshold","high",`MinCut value (${e.toFixed(2)}) is below healthy threshold (${this.config.healthyThreshold})`,e,this.config.healthyThreshold,t);let r=t.filter(o=>o.weightedDegree===0);r.length>0&&this.maybeGenerateAlert("isolated-vertices","high",`${r.length} isolated vertex(es) detected`,e,0,r);let a=t.filter(o=>o.riskScore>.8);a.length>0&&this.maybeGenerateAlert("critical-vertices","medium",`${a.length} critical vertex(es) with high risk score`,e,0,a)}maybeGenerateAlert(e,t,n,i,r,a){let o=Date.now(),c=this.lastAlertTime.get(e)||0;if(o-c<this.config.alertCooldownMs)return;let l={id:f(),severity:t,message:n,minCutValue:i,threshold:r,affectedVertices:a.map(u=>u.vertexId),timestamp:new Date,acknowledged:!1,remediations:a.flatMap(u=>u.suggestions).slice(0,5)};this.alerts.set(l.id,l),this.persistence&&this.persistence.saveAlert(l).catch(u=>console.warn("[MinCutHealthMonitor] Failed to persist alert:",u)),this.lastAlertTime.set(e,o),this.emitEvent("mincut.alert.generated",i,{alert:l})}emitEvent(e,t,n){if(!this.eventBus)return;let i={id:f(),type:e,source:"coordination",timestamp:new Date,correlationId:f(),payload:{minCutValue:t,...n}};this.eventBus.publish(i).catch(r=>{console.error("Failed to publish MinCut event:",r)})}};function W(s,e,t,n){return new ve(s,e,t,n)}he();dt();var Ce=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=f();return this.memory.getDatabase().prepare(`
3
3
  INSERT INTO mincut_snapshots (
4
4
  id, timestamp, vertex_count, edge_count, total_weight,
5
5
  is_connected, component_count, vertices_json, edges_json
@@ -177,4 +177,4 @@ import{b as ye}from"./chunk-MDCTQOUJ.js";import{a as ht,b as ft}from"./chunk-ZWR
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 ye(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,a]=n,o=this.getValueFromPath(t,i),c=isNaN(Number(a))?a:Number(a),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`)}},Ze=null;function Kt(s){return Ze||(Ze=new Xe(s)),Ze}function Yt(s,e){let t=[];for(let a of e){let o=s.router.subscribeToDoamin(a,async c=>{await ui(s,c)});t.push(o)}let n=s.router.subscribeToEventType("TaskCompleted",async a=>{await di(s,a)});t.push(n);let i=s.router.subscribeToEventType("TaskFailed",async a=>{await gi(s,a)});t.push(i);let r=s.router.subscribeToEventType("AgentStatusChanged",async a=>{await mi(s,a)});return t.push(r),t}async function ui(s,e){s.domainLastActivity.set(e.source,new Date),await s.processQueue()}async function di(s,e){let{taskId:t,result:n}=e.payload,i=s.tasks.get(t);if(i){(i.status==="running"||i.status==="assigned")&&(s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1));let r=i.startedAt?Date.now()-i.startedAt.getTime():0;s.tasks.set(t,{...i,status:"completed",completedAt:new Date,result:n}),s.tasksCompleted++,s.taskDurations.push(r),s.auditLogger.logComplete(t,i.assignedAgents[0]);try{let a=Kt(),o=i.assignedAgents[0];o&&await a.onAgentComplete(o,{taskId:t,taskType:i.task.type,domain:i.assignedDomain,result:n,duration:r})}catch(a){console.warn("[QueenCoordinator] Cross-phase hook error:",a)}try{await I.afterTaskExecution({taskId:t,taskType:i.task.type,agentId:i.assignedAgents[0]||"unknown",domain:i.assignedDomain||"test-generation",priority:i.task.priority},!0,0,0)}catch(a){console.warn("[QueenCoordinator] Governance tracking error:",a)}if(s.domainBreakerRegistry&&i.assignedDomain&&s.domainBreakerRegistry.getBreaker(i.assignedDomain).recordSuccess(),s.traceCollector){let a=s.taskTraceContexts.get(t);a&&(s.traceCollector.completeSpan(a.spanId),s.taskTraceContexts.delete(t))}if(s.taskCompletedHook)try{let a=typeof n=="object"&&n!==null?n:null;if(a===null)console.error(`[QueenCoordinator] Pattern training skipped for task ${t}: result is not an object (got ${typeof n})`);else{let o=pi(a,t);if(o){let c={taskId:t,agentId:i.assignedAgents[0]||"unknown",domain:i.assignedDomain||"test-generation",type:i.task.type,status:"completed",output:a,metrics:o,duration:r,timestamp:Date.now()};s.taskCompletedHook.onTaskCompleted(c).catch(l=>{console.warn("[QueenCoordinator] Pattern training error:",l)})}}}catch(a){console.warn("[QueenCoordinator] Pattern training setup error:",a)}}await s.processQueue()}async function gi(s,e){let{taskId:t,error:n}=e.payload,i=s.tasks.get(t);if(i){if((i.status==="running"||i.status==="assigned")&&(s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1)),s.domainBreakerRegistry&&i.assignedDomain&&s.domainBreakerRegistry.getBreaker(i.assignedDomain).recordFailure(new Error(n||"Task failed")),s.traceCollector){let r=s.taskTraceContexts.get(t);r&&(s.traceCollector.failSpan(r.spanId,n||"Task failed"),s.taskTraceContexts.delete(t))}if(i.retryCount<s.config.taskRetryLimit){s.auditLogger.logFail(t,i.assignedAgents[0],n);let r={...i,status:"queued",retryCount:i.retryCount+1,error:n};s.tasks.set(t,r),s.enqueueTask(i.task)}else{s.tasks.set(t,{...i,status:"failed",completedAt:new Date,error:n}),s.tasksFailed++,s.auditLogger.logFail(t,i.assignedAgents[0],n);try{await I.afterTaskExecution({taskId:t,taskType:i.task.type,agentId:i.assignedAgents[0]||"unknown",domain:i.assignedDomain||"test-generation",priority:i.task.priority},!1,0,0)}catch(r){console.warn("[QueenCoordinator] Governance tracking error:",r)}if(s.hypothesisManager&&(i.task.priority==="p0"||i.task.priority==="p1"))try{let r=i.assignedDomain||"test-generation",a=s.hypothesisManager.createInvestigation(t,r,`Root cause analysis for ${i.task.type} failure: ${n}`);s.hypothesisManager.addHypothesis(a.id,`Infrastructure failure in domain '${r}' caused task ${t} to fail`,"log-analysis",`${r}-lead`),s.hypothesisManager.addHypothesis(a.id,`Logic/configuration error in task payload caused ${i.task.type} to fail: ${n}`,"code-analysis",i.assignedAgents[0]||"unknown"),console.log(`[QueenCoordinator] Competing hypotheses investigation created: ${a.id}`)}catch(r){console.warn("[QueenCoordinator] Hypothesis creation error:",r)}}}await s.processQueue()}async function mi(s,e){let{agentId:t,status:n,domain:i}=e.payload;s.domainLastActivity.set(i,new Date),(n==="completed"||n==="failed")&&await s.processQueue()}function pi(s,e){if("metrics"in s&&typeof s.metrics=="object"&&s.metrics!==null){let t=s.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 s||"testsFailed"in s?{testsPassed:typeof s.testsPassed=="number"?s.testsPassed:void 0,testsFailed:typeof s.testsFailed=="number"?s.testsFailed:void 0,coverageChange:typeof s.coverageChange=="number"?s.coverageChange:void 0,securityIssues:typeof s.securityIssues=="number"?s.securityIssues:void 0,performanceMs:typeof s.performanceMs=="number"?s.performanceMs:void 0,linesChanged:typeof s.linesChanged=="number"?s.linesChanged:void 0}:(console.error(`[QueenCoordinator] Pattern training skipped for task ${e}: result object has no recognizable metrics shape (keys: ${Object.keys(s).join(", ")})`),null)}function Zt(s,e,t){let n=s.listAgents({domain:e}),i=n.filter(c=>c.status==="running").length,r=n.filter(c=>c.status==="idle").length,a=n.filter(c=>c.status==="failed").length,o;return a>0&&a>=n.length/2?o="unhealthy":a>0?o="degraded":i>0?o="healthy":o="idle",{status:o,agents:{total:n.length,active:i,idle:r,failed:a},lastActivity:t,errors:[]}}var hi=ft();function Xt(s,e,t){let n=s.get(t.priority);n&&ht(n,t,hi);for(let i of t.targetDomains){let r=e.get(i);r&&r.push(t)}}function pe(s,e,t){let n=s.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 a=r.findIndex(o=>o.id===t.id);a!==-1&&r.splice(a,1)}}}function Je(s,e){let t=0;for(let n of["p0","p1","p2","p3"]){let i=s.get(n);if(i){if(n===e.priority){t+=i.findIndex(r=>r.id===e.id);break}t+=i.length}}return t}async function et(s){if(!(s.runningTaskCounter>=s.config.maxConcurrentTasks))for(let e of["p0","p1","p2","p3"]){let t=s.taskQueue.get(e);if(!t||t.length===0)continue;let n=t.shift();if(n){pe(s.taskQueue,s.domainQueues,n),s.runningTaskCounter++;try{await tt(s,n)}catch(i){throw s.runningTaskCounter--,i}if(s.runningTaskCounter>=s.config.maxConcurrentTasks)return}}}function Jt(s,e){let t=Array.from(s.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 tt(s,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 a=s.getDomainLoad(r);s.getDomainHealth(r)?.status!=="unhealthy"&&a<i&&(i=a,n=r)}return n?nt(s,e,n):y(new Error("No healthy domain available for task"))}async function nt(s,e,t){let n;if(s.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 s.tinyDancerRouter.route(u),s.config.enableMetrics&&console.log(`[Queen] TinyDancer routing: ${e.type} \u2192 tier=${n.tier}, model=${n.model}, cost=$${n.estimatedCost.toFixed(4)}`)}if(s.domainBreakerRegistry&&!s.domainBreakerRegistry.canExecuteInDomain(t))return y(new Error(`Domain '${t}' circuit breaker is open \u2014 too many recent failures`));if(s.domainTeamManager)try{if(!s.domainTeamManager.getDomainTeam(t)){let u=`${t}-lead`;s.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"]:[]],a=await s.requestAgentSpawn(t,i,r),o=[];a.success&&o.push(a.value);let c={taskId:e.id,task:e,status:"running",assignedDomain:t,assignedAgents:o,startedAt:new Date,retryCount:0};s.tasks.set(e.id,c),s.domainLastActivity.set(t,new Date);for(let l of o)s.auditLogger.logAssign(e.id,l,t);if(await s.publishEvent("TaskAssigned",{taskId:e.id,domain:t,agentIds:o}),s.domainPlugins){let l=s.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=>fi(s,g));return d.success?C(e.id):(s.tasks.set(e.id,{...c,status:"failed",error:d.error.message,completedAt:new Date}),s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),s.tasksFailed++,s.auditLogger.logFail(e.id,o[0],d.error.message),y(d.error))}if(l)try{await l.handleEvent({id:f(),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 C(e.id)}async function fi(s,e){let t=s.tasks.get(e.taskId);if(!t){console.warn(`[Queen] Received completion for unknown task: ${e.taskId}`);return}let n={...t,status:e.success?"completed":"failed",completedAt:new Date,result:e.data,error:e.error};if(s.tasks.set(e.taskId,n),e.success?(s.tasksCompleted++,s.taskDurations.push(e.duration),s.auditLogger.logComplete(e.taskId,t.assignedAgents[0])):(s.tasksFailed++,s.auditLogger.logFail(e.taskId,t.assignedAgents[0],e.error||"Unknown error")),s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),s.coExecutionRepo&&t.assignedAgents.length>=2)try{s.coExecutionRepo.recordSwarmCoExecution(t.assignedAgents,t.assignedDomain||"unknown",e.success,t.task.type)}catch{}for(let i of t.assignedAgents)await s.agentCoordinator.stop(i);await s.publishEvent(e.success?"TaskCompleted":"TaskFailed",{taskId:e.taskId,domain:t.assignedDomain,result:e.data,error:e.error,duration:e.duration}),await et(s)}function en(s,e){return(P[e.type]||[]).includes(s)}k();async function tn(s){let e=0,t=s.getIdleDomains(),n=s.getBusyDomains();if(t.length===0||n.length===0)return 0;n.sort((i,r)=>s.getDomainLoad(r)-s.getDomainLoad(i));for(let i of n){if(t.length===0)break;let r=s.domainQueues.get(i)||[],a=Math.min(r.length,s.config.workStealing.stealBatchSize);for(let o=0;o<a&&t.length>0;o++){let c=r.find(l=>en(t[0],l));if(c){let l=t.shift();s.removeFromQueues(c),s.auditLogger.logSteal(c.id,i,l),await s.assignTaskToDomain(c,l),e++,s.tasksStolen++,await s.publishEvent("TaskStolen",{taskId:c.id,fromDomain:i,toDomain:l})}}}return e}function it(s,e){let t=0,n=10,i;return i=setInterval(async()=>{try{await e(),t=0}catch(r){t++;let a=Math.min(1e3*Math.pow(2,t),3e4);if(console.warn(`[QueenCoordinator] Work-stealing failed (attempt ${t}), backing off ${a}ms`,p(r)),t>n){console.error(`[QueenCoordinator] Work-stealing exceeded ${n} consecutive failures, stopping interval`),clearInterval(i);return}await new Promise(o=>setTimeout(o,a))}},s.workStealing.checkInterval),i}function rt(s){return typeof s.setMinCutBridge=="function"}function nn(s,e){for(let[t,n]of s)rt(n)&&(n.setMinCutBridge(e),console.log(`[QueenCoordinator] MinCut bridge injected into ${t}`))}async function rn(s,e,t){try{let n=await s.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 an(s,e){let t=Array.from(e.entries()).filter(([,n])=>n.status==="queued");await s.set("queen:state",{tasks:t},{namespace:"queen-coordinator",persist:!0})}function sn(s){return setInterval(async()=>{let e=s.getMetrics();if(await s.publishEvent("MetricsCollected",{metrics:e}),await s.memory.set(`queen:metrics:${Date.now()}`,e,{ttl:864e5,namespace:"queen-coordinator"}),s.dynamicScaler)try{let t=s.getAverageTaskDuration(),n={queueDepth:s.getQueuedTaskCount(),activeAgents:s.getActiveAgentCount(),idleAgents:s.getIdleAgentCount(),avgTaskDurationMs:t,errorRate:s.getTasksReceived()>0?s.getTasksFailed()/s.getTasksReceived():0,throughput:e.uptime>0?s.getTasksCompleted()/(e.uptime/1e3):0,timestamp:Date.now()};s.dynamicScaler.recordMetrics(n);let i=s.dynamicScaler.evaluate();i&&i.action!=="maintain"&&(console.log(`[QueenCoordinator] Dynamic scaler: ${i.action} to ${i.targetAgents} agents \u2014 ${i.reason}`),s.dynamicScaler.execute(i).catch(r=>{console.warn("[QueenCoordinator] Dynamic scaling execution error:",r)}))}catch(t){console.warn("[QueenCoordinator] Dynamic scaler metrics error:",t)}},s.config.metricsInterval)}function at(s,e,t=36e5){let n=Date.now(),i=0;for(let[a,o]of s)if(o.status==="completed"||o.status==="failed"||o.status==="cancelled"){let c=o.completedAt?.getTime()||o.startedAt?.getTime()||0;c>0&&n-c>t&&(s.delete(a),e.delete(a),i++)}let r=1e4;if(e.size>r){let a=e.size-r,o=e.keys();for(let c=0;c<a;c++){let l=o.next().value;l!==void 0&&e.delete(l)}console.log(`[QueenCoordinator] Evicted ${a} oldest trace contexts (max: ${r})`)}return i>0&&console.log(`[QueenCoordinator] Cleaned up ${i} old tasks (retention: ${t}ms)`),i}function on(s,e){return s&&s.size>0?Array.from(s.keys()):[...e]}var m=ut.create("QueenCoordinator");Wt(T);var st=class{constructor(e,t,n,i,r,a,o,c={}){this.eventBus=e;this.agentCoordinator=t;this.memory=n;this.router=i;this.protocolExecutor=r;this.workflowExecutor=a;this.domainPlugins=o;this.config={...jt,...c},this.auditLogger=Te({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 K(this.config.routing)),T.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 ct(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=it(this.config,()=>this.triggerWorkStealing().then(()=>{}))),this.config.enableMetrics&&(this.metricsTimer=sn(this.createMetricsContext())),this.cleanupTimer=setInterval(()=>{at(this.tasks,this.taskTraceContexts,36e5)},3e5),this.cleanupTimer.unref(),await rn(this.memory,this.tasks,e=>this.enqueueTaskInternal(e)),this.minCutBridge=vt(this.eventBus,this.agentCoordinator,{autoUpdateFromEvents:!0,persistData:!0,includeInQueenHealth:!0,sharedGraph:xe()}),await this.minCutBridge.initialize(),this.domainPlugins&&nn(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=Ft(t),this.availableMcpServers=yt(process.cwd());let{getUnifiedMemory:n}=await import("./unified-memory-BTX45KY5.js"),i=n();await i.initialize(),this.coExecutionRepo=Pt(),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:T}),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 an(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_${f()}`,n={...e,id:t,createdAt:new Date,timeout:e.timeout||this.config.defaultTaskTimeout},i={taskId:n.id,taskType:n.type,agentId:n.requester||"unknown",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 tt(this.createTaskContext(),n);return r.success?(this.tasksReceived++,await this.publishEvent("TaskSubmitted",{taskId:t,task:n}),C(t)):(this.runningTaskCounter--,r)}catch(r){throw this.runningTaskCounter--,r}}async cancelTask(e){let t=this.tasks.get(e);if(!t)return y(new Error(`Task not found: ${e}`));if(t.status==="completed"||t.status==="failed")return y(new Error(`Task already finished: ${e}`));(t.status==="running"||t.status==="assigned")&&(this.runningTaskCounter=Math.max(0,this.runningTaskCounter-1)),this.tasks.set(e,{...t,status:"cancelled",completedAt:new Date}),pe(this.taskQueue,this.domainQueues,t.task);for(let n of t.assignedAgents)await this.agentCoordinator.stop(n);return this.auditLogger.logCancel(e),await this.publishEvent("TaskCancelled",{taskId:e}),C(void 0)}getTaskStatus(e){return this.tasks.get(e)}listTasks(e){return Jt(this.tasks,e)}getDomainHealth(e){if(this.domainPlugins){let t=this.domainPlugins.get(e);if(t)return t.getHealth()}return Zt(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 T.filter(n=>{let i=this.domainLastActivity.get(n);return this.getDomainLoad(n)===0&&i&&e-i.getTime()>t})}getBusyDomains(){return T.filter(e=>this.getDomainLoad(e)>this.config.workStealing.loadThreshold)}getSpawnPlan(e){return this.dependencyGraph?Ot(e,this.dependencyGraph):{phases:[e],warnings:[],unsatisfiedHardDeps:[]}}getDependencyGraph(){return this.dependencyGraph}enableWorkStealing(){this.workStealingTimer||(this.workStealingTimer=it(this.config,()=>this.triggerWorkStealing().then(()=>{})))}disableWorkStealing(){this.workStealingTimer&&(clearInterval(this.workStealingTimer),this.workStealingTimer=null)}async triggerWorkStealing(){return tn(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 a=r.dependencies.mcpServers;if(!a||a.length===0)continue;let o=a.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=on(this.domainPlugins,T);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 a=this.agentCoordinator.listAgents(),o=a.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:a.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,t=0;for(let c of T){let l=this.getDomainLoad(c);e.set(c,l),t+=l}let n=this.agentCoordinator.listAgents(),i=n.filter(c=>c.status==="running").length,r=n.length>0?i/n.length:0,a=this.taskDurations.average(),o={tasksReceived:this.tasksReceived,tasksCompleted:this.tasksCompleted,tasksFailed:this.tasksFailed,tasksStolen:this.tasksStolen,averageTaskDuration:a,domainUtilization:e,agentUtilization:r,protocolsExecuted:this.protocolsExecuted,workflowsExecuted:this.workflowsExecuted,uptime:Date.now()-this.startTime.getTime()};return this.minCutBridge?this.minCutBridge.extendQueenMetrics(o):o}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?rt(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 le({},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}),C(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}),C(n.value.executionId)):n}cleanupCompletedTasks(e=36e5){return at(this.tasks,this.taskTraceContexts,e)}subscribeToEvents(){this.eventSubscriptionIds=Yt(this.createEventHandlerContext(),T)}enqueueTaskInternal(e){Xt(this.taskQueue,this.domainQueues,e)}async publishEvent(e,t){await this.eventBus.publish({id:f(),type:`Queen${e}`,timestamp:new Date,source:"queen-coordinator",payload:t})}queueTask(e){this.enqueueTaskInternal(e);let t={taskId:e.id,task:e,status:"queued",assignedAgents:[],retryCount:0};return this.tasks.set(e.id,t),this.tasksReceived++,this.auditLogger.logSubmit(e.id,{type:e.type,priority:e.priority}),this.auditLogger.logQueue(e.id,Je(this.taskQueue,e)),this.publishEvent("TaskQueued",{taskId:e.id,task:e,position:Je(this.taskQueue,e)}),C(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=Qt(),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=Pe(),this.agentTeamsAdapter.initialize(),this.domainTeamManager=He(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=Le(),m.info("Fleet tier selector initialized")}catch(e){m.warn("Tier selector initialization failed (continuing)",{error:e})}try{this.traceCollector=_e(),m.info("Trace collector initialized")}catch(e){m.warn("Trace collector initialization failed (continuing)",{error:e})}try{this.hypothesisManager=$e(),this.federationMailbox=Ge(),this.dynamicScaler=qe(),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:()=>et(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=>pe(e.taskQueue,e.domainQueues,t),assignTaskToDomain:(t,n)=>nt(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 Lo(s,e,t,n,i,r){return new st(s.eventBus,s.coordinator,s.memory,e,t,n,i,r)}export{xe as a,or as b,ri as c,P as d,st as e,Lo as f};
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 ye(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,a]=n,o=this.getValueFromPath(t,i),c=isNaN(Number(a))?a:Number(a),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`)}},Ze=null;function Kt(s){return Ze||(Ze=new Xe(s)),Ze}function Yt(s,e){let t=[];for(let a of e){let o=s.router.subscribeToDoamin(a,async c=>{await ui(s,c)});t.push(o)}let n=s.router.subscribeToEventType("TaskCompleted",async a=>{await di(s,a)});t.push(n);let i=s.router.subscribeToEventType("TaskFailed",async a=>{await gi(s,a)});t.push(i);let r=s.router.subscribeToEventType("AgentStatusChanged",async a=>{await mi(s,a)});return t.push(r),t}async function ui(s,e){s.domainLastActivity.set(e.source,new Date),await s.processQueue()}async function di(s,e){let{taskId:t,result:n}=e.payload,i=s.tasks.get(t);if(i){(i.status==="running"||i.status==="assigned")&&(s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1));let r=i.startedAt?Date.now()-i.startedAt.getTime():0;s.tasks.set(t,{...i,status:"completed",completedAt:new Date,result:n}),s.tasksCompleted++,s.taskDurations.push(r),s.auditLogger.logComplete(t,i.assignedAgents[0]);try{let a=Kt(),o=i.assignedAgents[0];o&&await a.onAgentComplete(o,{taskId:t,taskType:i.task.type,domain:i.assignedDomain,result:n,duration:r})}catch(a){console.warn("[QueenCoordinator] Cross-phase hook error:",a)}try{await I.afterTaskExecution({taskId:t,taskType:i.task.type,agentId:i.assignedAgents[0]||"unknown",domain:i.assignedDomain||"test-generation",priority:i.task.priority},!0,0,0)}catch(a){console.warn("[QueenCoordinator] Governance tracking error:",a)}if(s.domainBreakerRegistry&&i.assignedDomain&&s.domainBreakerRegistry.getBreaker(i.assignedDomain).recordSuccess(),s.traceCollector){let a=s.taskTraceContexts.get(t);a&&(s.traceCollector.completeSpan(a.spanId),s.taskTraceContexts.delete(t))}if(s.taskCompletedHook)try{let a=typeof n=="object"&&n!==null?n:null;if(a===null)console.error(`[QueenCoordinator] Pattern training skipped for task ${t}: result is not an object (got ${typeof n})`);else{let o=pi(a,t);if(o){let c={taskId:t,agentId:i.assignedAgents[0]||"unknown",domain:i.assignedDomain||"test-generation",type:i.task.type,status:"completed",output:a,metrics:o,duration:r,timestamp:Date.now()};s.taskCompletedHook.onTaskCompleted(c).catch(l=>{console.warn("[QueenCoordinator] Pattern training error:",l)})}}}catch(a){console.warn("[QueenCoordinator] Pattern training setup error:",a)}}await s.processQueue()}async function gi(s,e){let{taskId:t,error:n}=e.payload,i=s.tasks.get(t);if(i){if((i.status==="running"||i.status==="assigned")&&(s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1)),s.domainBreakerRegistry&&i.assignedDomain&&s.domainBreakerRegistry.getBreaker(i.assignedDomain).recordFailure(new Error(n||"Task failed")),s.traceCollector){let r=s.taskTraceContexts.get(t);r&&(s.traceCollector.failSpan(r.spanId,n||"Task failed"),s.taskTraceContexts.delete(t))}if(i.retryCount<s.config.taskRetryLimit){s.auditLogger.logFail(t,i.assignedAgents[0],n);let r={...i,status:"queued",retryCount:i.retryCount+1,error:n};s.tasks.set(t,r),s.enqueueTask(i.task)}else{s.tasks.set(t,{...i,status:"failed",completedAt:new Date,error:n}),s.tasksFailed++,s.auditLogger.logFail(t,i.assignedAgents[0],n);try{await I.afterTaskExecution({taskId:t,taskType:i.task.type,agentId:i.assignedAgents[0]||"unknown",domain:i.assignedDomain||"test-generation",priority:i.task.priority},!1,0,0)}catch(r){console.warn("[QueenCoordinator] Governance tracking error:",r)}if(s.hypothesisManager&&(i.task.priority==="p0"||i.task.priority==="p1"))try{let r=i.assignedDomain||"test-generation",a=s.hypothesisManager.createInvestigation(t,r,`Root cause analysis for ${i.task.type} failure: ${n}`);s.hypothesisManager.addHypothesis(a.id,`Infrastructure failure in domain '${r}' caused task ${t} to fail`,"log-analysis",`${r}-lead`),s.hypothesisManager.addHypothesis(a.id,`Logic/configuration error in task payload caused ${i.task.type} to fail: ${n}`,"code-analysis",i.assignedAgents[0]||"unknown"),console.log(`[QueenCoordinator] Competing hypotheses investigation created: ${a.id}`)}catch(r){console.warn("[QueenCoordinator] Hypothesis creation error:",r)}}}await s.processQueue()}async function mi(s,e){let{agentId:t,status:n,domain:i}=e.payload;s.domainLastActivity.set(i,new Date),(n==="completed"||n==="failed")&&await s.processQueue()}function pi(s,e){if("metrics"in s&&typeof s.metrics=="object"&&s.metrics!==null){let t=s.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 s||"testsFailed"in s?{testsPassed:typeof s.testsPassed=="number"?s.testsPassed:void 0,testsFailed:typeof s.testsFailed=="number"?s.testsFailed:void 0,coverageChange:typeof s.coverageChange=="number"?s.coverageChange:void 0,securityIssues:typeof s.securityIssues=="number"?s.securityIssues:void 0,performanceMs:typeof s.performanceMs=="number"?s.performanceMs:void 0,linesChanged:typeof s.linesChanged=="number"?s.linesChanged:void 0}:(console.error(`[QueenCoordinator] Pattern training skipped for task ${e}: result object has no recognizable metrics shape (keys: ${Object.keys(s).join(", ")})`),null)}function Zt(s,e,t){let n=s.listAgents({domain:e}),i=n.filter(c=>c.status==="running").length,r=n.filter(c=>c.status==="idle").length,a=n.filter(c=>c.status==="failed").length,o;return a>0&&a>=n.length/2?o="unhealthy":a>0?o="degraded":i>0?o="healthy":o="idle",{status:o,agents:{total:n.length,active:i,idle:r,failed:a},lastActivity:t,errors:[]}}var hi=ft();function Xt(s,e,t){let n=s.get(t.priority);n&&ht(n,t,hi);for(let i of t.targetDomains){let r=e.get(i);r&&r.push(t)}}function pe(s,e,t){let n=s.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 a=r.findIndex(o=>o.id===t.id);a!==-1&&r.splice(a,1)}}}function Je(s,e){let t=0;for(let n of["p0","p1","p2","p3"]){let i=s.get(n);if(i){if(n===e.priority){t+=i.findIndex(r=>r.id===e.id);break}t+=i.length}}return t}async function et(s){if(!(s.runningTaskCounter>=s.config.maxConcurrentTasks))for(let e of["p0","p1","p2","p3"]){let t=s.taskQueue.get(e);if(!t||t.length===0)continue;let n=t.shift();if(n){pe(s.taskQueue,s.domainQueues,n),s.runningTaskCounter++;try{await tt(s,n)}catch(i){throw s.runningTaskCounter--,i}if(s.runningTaskCounter>=s.config.maxConcurrentTasks)return}}}function Jt(s,e){let t=Array.from(s.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 tt(s,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 a=s.getDomainLoad(r);s.getDomainHealth(r)?.status!=="unhealthy"&&a<i&&(i=a,n=r)}return n?nt(s,e,n):y(new Error("No healthy domain available for task"))}async function nt(s,e,t){let n;if(s.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 s.tinyDancerRouter.route(u),s.config.enableMetrics&&console.log(`[Queen] TinyDancer routing: ${e.type} \u2192 tier=${n.tier}, model=${n.model}, cost=$${n.estimatedCost.toFixed(4)}`)}if(s.domainBreakerRegistry&&!s.domainBreakerRegistry.canExecuteInDomain(t))return y(new Error(`Domain '${t}' circuit breaker is open \u2014 too many recent failures`));if(s.domainTeamManager)try{if(!s.domainTeamManager.getDomainTeam(t)){let u=`${t}-lead`;s.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"]:[]],a=await s.requestAgentSpawn(t,i,r),o=[];a.success&&o.push(a.value);let c={taskId:e.id,task:e,status:"running",assignedDomain:t,assignedAgents:o,startedAt:new Date,retryCount:0};s.tasks.set(e.id,c),s.domainLastActivity.set(t,new Date);for(let l of o)s.auditLogger.logAssign(e.id,l,t);if(await s.publishEvent("TaskAssigned",{taskId:e.id,domain:t,agentIds:o}),s.domainPlugins){let l=s.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=>fi(s,g));return d.success?C(e.id):(s.tasks.set(e.id,{...c,status:"failed",error:d.error.message,completedAt:new Date}),s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),s.tasksFailed++,s.auditLogger.logFail(e.id,o[0],d.error.message),y(d.error))}if(l)try{await l.handleEvent({id:f(),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 C(e.id)}async function fi(s,e){let t=s.tasks.get(e.taskId);if(!t){console.warn(`[Queen] Received completion for unknown task: ${e.taskId}`);return}let n={...t,status:e.success?"completed":"failed",completedAt:new Date,result:e.data,error:e.error};if(s.tasks.set(e.taskId,n),e.success?(s.tasksCompleted++,s.taskDurations.push(e.duration),s.auditLogger.logComplete(e.taskId,t.assignedAgents[0])):(s.tasksFailed++,s.auditLogger.logFail(e.taskId,t.assignedAgents[0],e.error||"Unknown error")),s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),s.coExecutionRepo&&t.assignedAgents.length>=2)try{s.coExecutionRepo.recordSwarmCoExecution(t.assignedAgents,t.assignedDomain||"unknown",e.success,t.task.type)}catch{}for(let i of t.assignedAgents)await s.agentCoordinator.stop(i);await s.publishEvent(e.success?"TaskCompleted":"TaskFailed",{taskId:e.taskId,domain:t.assignedDomain,result:e.data,error:e.error,duration:e.duration}),await et(s)}function en(s,e){return(P[e.type]||[]).includes(s)}k();async function tn(s){let e=0,t=s.getIdleDomains(),n=s.getBusyDomains();if(t.length===0||n.length===0)return 0;n.sort((i,r)=>s.getDomainLoad(r)-s.getDomainLoad(i));for(let i of n){if(t.length===0)break;let r=s.domainQueues.get(i)||[],a=Math.min(r.length,s.config.workStealing.stealBatchSize);for(let o=0;o<a&&t.length>0;o++){let c=r.find(l=>en(t[0],l));if(c){let l=t.shift();s.removeFromQueues(c),s.auditLogger.logSteal(c.id,i,l),await s.assignTaskToDomain(c,l),e++,s.tasksStolen++,await s.publishEvent("TaskStolen",{taskId:c.id,fromDomain:i,toDomain:l})}}}return e}function it(s,e){let t=0,n=10,i;return i=setInterval(async()=>{try{await e(),t=0}catch(r){t++;let a=Math.min(1e3*Math.pow(2,t),3e4);if(console.warn(`[QueenCoordinator] Work-stealing failed (attempt ${t}), backing off ${a}ms`,p(r)),t>n){console.error(`[QueenCoordinator] Work-stealing exceeded ${n} consecutive failures, stopping interval`),clearInterval(i);return}await new Promise(o=>setTimeout(o,a))}},s.workStealing.checkInterval),i}function rt(s){return typeof s.setMinCutBridge=="function"}function nn(s,e){for(let[t,n]of s)rt(n)&&(n.setMinCutBridge(e),console.log(`[QueenCoordinator] MinCut bridge injected into ${t}`))}async function rn(s,e,t){try{let n=await s.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 an(s,e){let t=Array.from(e.entries()).filter(([,n])=>n.status==="queued");await s.set("queen:state",{tasks:t},{namespace:"queen-coordinator",persist:!0})}function sn(s){return setInterval(async()=>{let e=s.getMetrics();if(await s.publishEvent("MetricsCollected",{metrics:e}),await s.memory.set(`queen:metrics:${Date.now()}`,e,{ttl:864e5,namespace:"queen-coordinator"}),s.dynamicScaler)try{let t=s.getAverageTaskDuration(),n={queueDepth:s.getQueuedTaskCount(),activeAgents:s.getActiveAgentCount(),idleAgents:s.getIdleAgentCount(),avgTaskDurationMs:t,errorRate:s.getTasksReceived()>0?s.getTasksFailed()/s.getTasksReceived():0,throughput:e.uptime>0?s.getTasksCompleted()/(e.uptime/1e3):0,timestamp:Date.now()};s.dynamicScaler.recordMetrics(n);let i=s.dynamicScaler.evaluate();i&&i.action!=="maintain"&&(console.log(`[QueenCoordinator] Dynamic scaler: ${i.action} to ${i.targetAgents} agents \u2014 ${i.reason}`),s.dynamicScaler.execute(i).catch(r=>{console.warn("[QueenCoordinator] Dynamic scaling execution error:",r)}))}catch(t){console.warn("[QueenCoordinator] Dynamic scaler metrics error:",t)}},s.config.metricsInterval)}function at(s,e,t=36e5){let n=Date.now(),i=0;for(let[a,o]of s)if(o.status==="completed"||o.status==="failed"||o.status==="cancelled"){let c=o.completedAt?.getTime()||o.startedAt?.getTime()||0;c>0&&n-c>t&&(s.delete(a),e.delete(a),i++)}let r=1e4;if(e.size>r){let a=e.size-r,o=e.keys();for(let c=0;c<a;c++){let l=o.next().value;l!==void 0&&e.delete(l)}console.log(`[QueenCoordinator] Evicted ${a} oldest trace contexts (max: ${r})`)}return i>0&&console.log(`[QueenCoordinator] Cleaned up ${i} old tasks (retention: ${t}ms)`),i}function on(s,e){return s&&s.size>0?Array.from(s.keys()):[...e]}var m=ut.create("QueenCoordinator");Wt(T);var st=class{constructor(e,t,n,i,r,a,o,c={}){this.eventBus=e;this.agentCoordinator=t;this.memory=n;this.router=i;this.protocolExecutor=r;this.workflowExecutor=a;this.domainPlugins=o;this.config={...jt,...c},this.auditLogger=Te({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 K(this.config.routing)),T.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 ct(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=it(this.config,()=>this.triggerWorkStealing().then(()=>{}))),this.config.enableMetrics&&(this.metricsTimer=sn(this.createMetricsContext())),this.cleanupTimer=setInterval(()=>{at(this.tasks,this.taskTraceContexts,36e5)},3e5),this.cleanupTimer.unref(),await rn(this.memory,this.tasks,e=>this.enqueueTaskInternal(e)),this.minCutBridge=vt(this.eventBus,this.agentCoordinator,{autoUpdateFromEvents:!0,persistData:!0,includeInQueenHealth:!0,sharedGraph:xe()}),await this.minCutBridge.initialize(),this.domainPlugins&&nn(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=Ft(t),this.availableMcpServers=yt(process.cwd());let{getUnifiedMemory:n}=await import("./unified-memory-2ETCY22B.js"),i=n();await i.initialize(),this.coExecutionRepo=Pt(),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:T}),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 an(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_${f()}`,n={...e,id:t,createdAt:new Date,timeout:e.timeout||this.config.defaultTaskTimeout},i={taskId:n.id,taskType:n.type,agentId:n.requester||"unknown",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 tt(this.createTaskContext(),n);return r.success?(this.tasksReceived++,await this.publishEvent("TaskSubmitted",{taskId:t,task:n}),C(t)):(this.runningTaskCounter--,r)}catch(r){throw this.runningTaskCounter--,r}}async cancelTask(e){let t=this.tasks.get(e);if(!t)return y(new Error(`Task not found: ${e}`));if(t.status==="completed"||t.status==="failed")return y(new Error(`Task already finished: ${e}`));(t.status==="running"||t.status==="assigned")&&(this.runningTaskCounter=Math.max(0,this.runningTaskCounter-1)),this.tasks.set(e,{...t,status:"cancelled",completedAt:new Date}),pe(this.taskQueue,this.domainQueues,t.task);for(let n of t.assignedAgents)await this.agentCoordinator.stop(n);return this.auditLogger.logCancel(e),await this.publishEvent("TaskCancelled",{taskId:e}),C(void 0)}getTaskStatus(e){return this.tasks.get(e)}listTasks(e){return Jt(this.tasks,e)}getDomainHealth(e){if(this.domainPlugins){let t=this.domainPlugins.get(e);if(t)return t.getHealth()}return Zt(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 T.filter(n=>{let i=this.domainLastActivity.get(n);return this.getDomainLoad(n)===0&&i&&e-i.getTime()>t})}getBusyDomains(){return T.filter(e=>this.getDomainLoad(e)>this.config.workStealing.loadThreshold)}getSpawnPlan(e){return this.dependencyGraph?Ot(e,this.dependencyGraph):{phases:[e],warnings:[],unsatisfiedHardDeps:[]}}getDependencyGraph(){return this.dependencyGraph}enableWorkStealing(){this.workStealingTimer||(this.workStealingTimer=it(this.config,()=>this.triggerWorkStealing().then(()=>{})))}disableWorkStealing(){this.workStealingTimer&&(clearInterval(this.workStealingTimer),this.workStealingTimer=null)}async triggerWorkStealing(){return tn(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 a=r.dependencies.mcpServers;if(!a||a.length===0)continue;let o=a.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=on(this.domainPlugins,T);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 a=this.agentCoordinator.listAgents(),o=a.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:a.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,t=0;for(let c of T){let l=this.getDomainLoad(c);e.set(c,l),t+=l}let n=this.agentCoordinator.listAgents(),i=n.filter(c=>c.status==="running").length,r=n.length>0?i/n.length:0,a=this.taskDurations.average(),o={tasksReceived:this.tasksReceived,tasksCompleted:this.tasksCompleted,tasksFailed:this.tasksFailed,tasksStolen:this.tasksStolen,averageTaskDuration:a,domainUtilization:e,agentUtilization:r,protocolsExecuted:this.protocolsExecuted,workflowsExecuted:this.workflowsExecuted,uptime:Date.now()-this.startTime.getTime()};return this.minCutBridge?this.minCutBridge.extendQueenMetrics(o):o}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?rt(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 le({},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}),C(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}),C(n.value.executionId)):n}cleanupCompletedTasks(e=36e5){return at(this.tasks,this.taskTraceContexts,e)}subscribeToEvents(){this.eventSubscriptionIds=Yt(this.createEventHandlerContext(),T)}enqueueTaskInternal(e){Xt(this.taskQueue,this.domainQueues,e)}async publishEvent(e,t){await this.eventBus.publish({id:f(),type:`Queen${e}`,timestamp:new Date,source:"queen-coordinator",payload:t})}queueTask(e){this.enqueueTaskInternal(e);let t={taskId:e.id,task:e,status:"queued",assignedAgents:[],retryCount:0};return this.tasks.set(e.id,t),this.tasksReceived++,this.auditLogger.logSubmit(e.id,{type:e.type,priority:e.priority}),this.auditLogger.logQueue(e.id,Je(this.taskQueue,e)),this.publishEvent("TaskQueued",{taskId:e.id,task:e,position:Je(this.taskQueue,e)}),C(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=Qt(),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=Pe(),this.agentTeamsAdapter.initialize(),this.domainTeamManager=He(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=Le(),m.info("Fleet tier selector initialized")}catch(e){m.warn("Tier selector initialization failed (continuing)",{error:e})}try{this.traceCollector=_e(),m.info("Trace collector initialized")}catch(e){m.warn("Trace collector initialization failed (continuing)",{error:e})}try{this.hypothesisManager=$e(),this.federationMailbox=Ge(),this.dynamicScaler=qe(),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:()=>et(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=>pe(e.taskQueue,e.domainQueues,t),assignTaskToDomain:(t,n)=>nt(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 Lo(s,e,t,n,i,r){return new st(s.eventBus,s.coordinator,s.memory,e,t,n,i,r)}export{xe as a,or as b,ri as c,P as d,st as e,Lo as f};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.18");process.exit(0)}
2
- import{a as t,q as r}from"./chunk-MBGWDELE.js";import{c as l}from"./chunk-FKNYOKIK.js";function m(s,e){let o=e?.readonly??!1,n=e?.fileMustExist??!1,i=e?.busyTimeout??5e3,b=e?.walMode??!o,a=new t(s,{readonly:o,fileMustExist:n});return a.pragma(`busy_timeout = ${i}`),b&&a.pragma("journal_mode = WAL"),a}var u=l(()=>{r()});export{m as a,u as b};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.19");process.exit(0)}
2
+ import{a as t,q as r}from"./chunk-CYLQTVIA.js";import{c as l}from"./chunk-WULMXLNN.js";function m(s,e){let o=e?.readonly??!1,n=e?.fileMustExist??!1,i=e?.busyTimeout??5e3,b=e?.walMode??!o,a=new t(s,{readonly:o,fileMustExist:n});return a.pragma(`busy_timeout = ${i}`),b&&a.pragma("journal_mode = WAL"),a}var u=l(()=>{r()});export{m as a,u as b};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.18");process.exit(0)}
2
- import{a as T}from"./chunk-4XYQJ4LQ.js";import{c as S}from"./chunk-6KTF7QB3.js";import{b as C,d as P}from"./chunk-6ZMQL3U6.js";import{a as w,c as $}from"./chunk-UNPTSPAO.js";import{a as b,d as M}from"./chunk-QGSELG75.js";$();M();import{randomUUID as D}from"crypto";var x={topology:"hierarchical",maxConcurrentSkills:10,maxConcurrentModels:3,timeout:3e5,continueOnFailure:!0,retry:{maxRetries:2,retryDelayMs:1e3}},R=class{config;learner;skillValidator=null;workers=new Map;taskQueue=[];isRunning=!1;constructor(e,t){this.config={...x,...e},this.learner=t}setSkillValidator(e){this.skillValidator=e}async validateSkillsParallel(e,t,i){let s=Date.now(),a=i?.trustTier??3,n=i?.validationLevel??"eval",c=this.determineTopology(e.length,t.length),r=this.createValidationTasks(e,t,a,n),o=await this.executeTasksParallel(r,c),l=new Map;for(let u of o){let p=l.get(u.skill)||[];p.push(u),l.set(u.skill,p)}return await this.recordOutcomesToLearner(o,a,n),l}async validateSkillCrossModel(e,t,i){return(await this.validateSkillsParallel([e],t,i)).get(e)||[]}getSummary(e){let t=[],i=new Map,s=new Map;for(let[c,r]of e){i.set(c,r);for(let o of r){t.push(o);let l=s.get(o.model)||[];l.push(o),s.set(o.model,l)}}let a=t.filter(c=>c.errors.length===0&&c.evalPassRate>=.9).length,n=t.reduce((c,r)=>c+r.durationMs,0);return{totalSkills:i.size,totalModels:s.size,successCount:a,failureCount:t.length-a,overallPassRate:t.length>0?a/t.length:0,totalDurationMs:n,avgDurationMs:t.length>0?n/t.length:0,topology:this.config.topology,bySkill:i,byModel:s,results:t}}determineTopology(e,t){if(this.config.topology){let i=e*t;return i>20&&this.config.topology==="mesh"&&console.warn(`[SwarmSkillValidator] Large workload (${i} tasks) may be more efficient with hierarchical topology`),this.config.topology}return e>5||e>t*2?"hierarchical":t>5&&e<=3?"mesh":"hierarchical"}createValidationTasks(e,t,i,s){let a=[];for(let n of e)for(let c of t)a.push({id:`${n}-${c}-${Date.now()}-${D().slice(0,8)}`,skill:n,model:c,trustTier:i,validationLevel:s,timeout:this.config.timeout,retryCount:0});return a}async executeTasksParallel(e,t){this.isRunning=!0,this.taskQueue=[...e];let i=[],s=t==="hierarchical"?this.config.maxConcurrentSkills:Math.min(this.config.maxConcurrentSkills*this.config.maxConcurrentModels,e.length),a=[];for(let n=0;n<Math.min(s,e.length);n++){let c=`worker-${n}`;this.workers.set(c,{id:c,task:null,status:"idle"}),a.push(this.runWorker(c,i))}return await Promise.all(a),this.isRunning=!1,this.workers.clear(),i}async runWorker(e,t){let i=this.workers.get(e);if(i){for(;this.taskQueue.length>0&&this.isRunning;){let s=this.taskQueue.shift();if(!s)break;i.task=s,i.status="running",i.startTime=Date.now();try{let a=await this.executeValidationTask(s);t.push(a),i.result=a,i.status="completed"}catch(a){let n=this.createErrorResult(s,a);this.config.retry&&s.retryCount<this.config.retry.maxRetries&&this.config.continueOnFailure?(s.retryCount++,this.taskQueue.push(s),await this.delay(this.config.retry.retryDelayMs)):(t.push(n),i.result=n,i.status="failed")}}i.task=null,i.status="idle"}}async executeValidationTask(e){let t=Date.now();if(!this.skillValidator)return this.createSimulatedResult(e,t);let i=new Promise((n,c)=>{setTimeout(()=>c(new Error(`Validation timeout after ${e.timeout}ms`)),e.timeout)}),s=await Promise.race([this.skillValidator(e.skill,e.model,{trustTier:e.trustTier,validationLevel:e.validationLevel,timeout:e.timeout}),i]),a=Date.now()-t;return this.outcomeToResult(s,e,a)}outcomeToResult(e,t,i){let s=e.testCaseResults.filter(c=>c.passed).length,a=e.testCaseResults.length,n=a>0?s/a:e.score;return{skill:t.skill,model:t.model,schemaValid:e.validationLevel!=="schema"||e.passed,validatorPassed:e.validationLevel!=="validator"||e.passed,evalPassRate:n,durationMs:i,errors:e.passed?[]:["Validation failed"],trustTier:t.trustTier,validationLevel:t.validationLevel,retryCount:t.retryCount,timestamp:new Date}}createSimulatedResult(e,t){let i=Date.now()-t+b()*100,s=.85+b()*.15;return{skill:e.skill,model:e.model,schemaValid:!0,validatorPassed:s>.8,evalPassRate:s,durationMs:i,errors:s>.8?[]:["Simulated validation failure"],trustTier:e.trustTier,validationLevel:e.validationLevel,retryCount:e.retryCount,timestamp:new Date}}createErrorResult(e,t){let i=w(t);return{skill:e.skill,model:e.model,schemaValid:!1,validatorPassed:!1,evalPassRate:0,durationMs:0,errors:[i],trustTier:e.trustTier,validationLevel:e.validationLevel,retryCount:e.retryCount,timestamp:new Date}}async recordOutcomesToLearner(e,t,i){for(let s of e){let a={skillName:s.skill,trustTier:s.trustTier||t,validationLevel:s.validationLevel||i,model:s.model,passed:s.errors.length===0&&s.evalPassRate>=.9,score:s.evalPassRate,testCaseResults:this.createTestCaseResults(s),timestamp:s.timestamp,runId:`swarm-${Date.now()}`,metadata:{duration:s.durationMs,retryCount:s.retryCount}};await this.learner.recordValidationOutcome(a)}}createTestCaseResults(e){return[{testId:`${e.skill}-${e.model}-aggregate`,passed:e.errors.length===0,expectedPatterns:["valid-output"],actualPatterns:e.errors.length===0?["valid-output"]:[],reasoningQuality:e.evalPassRate,executionTimeMs:e.durationMs,category:"swarm-validation",priority:"high",error:e.errors.length>0?e.errors.join("; "):void 0}]}delay(e){return new Promise(t=>setTimeout(t,e))}getConfig(){return{...this.config}}isValidationRunning(){return this.isRunning}getWorkerStatus(){return Array.from(this.workers.values())}cancel(){this.isRunning=!1,this.taskQueue=[]}};function A(y,e){return new R(y,e)}var F=["security-testing","accessibility-testing","api-testing","performance-testing","visual-regression-testing","mutation-testing","contract-testing","chaos-testing","compliance-testing","penetration-testing"],I=["claude-sonnet","claude-haiku","claude-opus"];P();import{readFileSync as L,writeFileSync as E,existsSync as N}from"fs";var O={varianceThreshold:.04,regressionThreshold:.1,minSamples:3,autoUpdateManifest:!1},k=class{constructor(e,t,i={}){this.learner=e;this.manifestPath=t;this.config={...O,...i}}learner;manifestPath;config;async aggregateResults(e){let t=`agg-${Date.now()}`,i=new Date,s=this.buildSkillResultsMap(e),a=this.calculateSummary(s,e),n=await this.detectCrossModelAnomalies(e),c=await this.detectRegressions(e,this.config.regressionThreshold),r=this.generateRecommendations(s,n,c),o={timestamp:i,runId:t,summary:a,skillResults:s,crossModelAnalysis:n,regressions:c,recommendations:r,metadata:{version:"1.0.0",environment:e[0]?.metadata?.environment,generatedBy:"ValidationResultAggregator",inputs:{runIds:e.map(l=>l.runId),models:[...new Set(e.map(l=>l.model))]}}};return this.config.autoUpdateManifest&&await this.updateManifest(o),o}buildSkillResultsMap(e){let t=new Map;for(let i of e)for(let s of i.outcomes){let a=s.skillName;t.has(a)||t.set(a,{skill:a,trustTier:s.trustTier,passRateByModel:new Map,avgPassRate:0,schemaValid:!0,validatorPassed:!0,evalPassed:!0,issues:[],executionTimeMs:0,testCount:0,passedTests:0,failedTests:0});let n=t.get(a),c=s.testCaseResults.filter(r=>r.passed).length/(s.testCaseResults.length||1);n.passRateByModel.set(i.model,c),n.testCount+=s.testCaseResults.length,n.passedTests+=s.testCaseResults.filter(r=>r.passed).length,n.failedTests+=s.testCaseResults.filter(r=>!r.passed).length,n.executionTimeMs+=s.metadata?.duration||0,s.validationLevel==="schema"&&!s.passed&&(n.schemaValid=!1),s.validationLevel==="validator"&&!s.passed&&(n.validatorPassed=!1),s.validationLevel==="eval"&&!s.passed&&(n.evalPassed=!1);for(let r of s.testCaseResults)!r.passed&&r.error&&n.issues.push({skill:a,model:i.model,severity:r.priority==="critical"?"critical":r.priority==="high"?"high":r.priority==="medium"?"medium":"low",type:this.categorizeIssueType(s.validationLevel,r.error),message:r.error,testId:r.testId})}for(let i of t.values()){let s=Array.from(i.passRateByModel.values());i.avgPassRate=s.length>0?s.reduce((a,n)=>a+n,0)/s.length:0}return t}categorizeIssueType(e,t){return t.toLowerCase().includes("timeout")?"timeout":e==="schema"?"schema_failure":e==="validator"?"validator_failure":e==="eval"?"eval_failure":"error"}calculateSummary(e,t){let i=Array.from(e.values()),s=i.filter(n=>n.avgPassRate>=.9).length,a=i.length>0?i.reduce((n,c)=>n+c.avgPassRate,0)/i.length:0;return{totalSkills:i.length,passedSkills:s,failedSkills:i.length-s,avgPassRate:a,totalDurationMs:t.reduce((n,c)=>n+c.durationMs,0),totalTests:i.reduce((n,c)=>n+c.testCount,0),passedTests:i.reduce((n,c)=>n+c.passedTests,0),failedTests:i.reduce((n,c)=>n+c.failedTests,0),modelsUsed:[...new Set(t.map(n=>n.model))]}}async detectCrossModelAnomalies(e){let t=new Map,i=new Map,s=new Map;for(let d of e){t.has(d.model)||(t.set(d.model,[]),i.set(d.model,{totalTests:0,passedTests:0,skillCount:0}));for(let g of d.outcomes){let h=g.testCaseResults.filter(m=>m.passed).length/(g.testCaseResults.length||1);t.get(d.model).push(h);let f=i.get(d.model);f.totalTests+=g.testCaseResults.length,f.passedTests+=g.testCaseResults.filter(m=>m.passed).length,f.skillCount++,s.has(g.skillName)||s.set(g.skillName,{passRates:[],models:[]}),s.get(g.skillName).passRates.push(h),s.get(g.skillName).models.push(d.model)}}let a=[];for(let d of t.values())a.push(...d);let n=a.length>0?a.reduce((d,g)=>d+g,0)/a.length:0,c=a.length>1?a.reduce((d,g)=>d+Math.pow(g-n,2),0)/a.length:0,r=Math.sqrt(c),o=[],l=new Map;for(let[d,g]of t.entries()){let h=g.reduce((v,V)=>v+V,0)/g.length,f=h-n,m=i.get(d);l.set(d,{avgPassRate:h,skillCount:m.skillCount,totalTests:m.totalTests}),Math.abs(f)>this.config.varianceThreshold*2&&o.push({model:d,type:f<0?"low_performance":"high_variance",description:`Model ${d} has ${(f*100).toFixed(1)}% difference from average`,passRate:h,avgPassRate:n,deviation:Math.abs(f)})}let u=[],p=[];for(let[d,g]of s.entries()){if(g.passRates.length<2)continue;let h=g.passRates.reduce((m,v)=>m+v,0)/g.passRates.length;g.passRates.reduce((m,v)=>m+Math.pow(v-h,2),0)/g.passRates.length<this.config.varianceThreshold?u.push(d):p.push(d)}return{variance:c,stdDeviation:r,anomalies:o,consistentSkills:u,inconsistentSkills:p,modelPerformance:l}}async detectRegressions(e,t){let i=[],s=new Set;for(let a of e)for(let n of a.outcomes){let c=`${n.skillName}-${a.model}`;if(s.has(c))continue;s.add(c);let r=await this.learner.getValidationTrends(n.skillName);if(!r)continue;let o=n.testCaseResults.filter(p=>p.passed).length/(n.testCaseResults.length||1),l=r.recentPassRate,u=l-o;u>=t&&i.push({skill:n.skillName,model:a.model,previousPassRate:l,currentPassRate:o,regressionAmount:u,trend:r.overall,possibleCauses:this.analyzePossibleCauses(n,u),severity:this.categorizeRegressionSeverity(u)})}return i.sort((a,n)=>{let c={critical:0,high:1,medium:2,low:3},r=c[a.severity]-c[n.severity];return r!==0?r:n.regressionAmount-a.regressionAmount})}analyzePossibleCauses(e,t){let i=[],s=e.testCaseResults.filter(c=>!c.passed);if(s.length>0){let c=[...new Set(s.map(r=>r.category).filter(Boolean))];c.length>0&&i.push(`Failures in categories: ${c.join(", ")}`)}let a=s.filter(c=>c.priority==="critical");a.length>0&&i.push(`${a.length} critical test(s) failing`);let n=e.testCaseResults.reduce((c,r)=>c+r.reasoningQuality,0)/(e.testCaseResults.length||1);return n<.7&&i.push(`Low reasoning quality score: ${(n*100).toFixed(1)}%`),t>.3&&i.push("Possible model behavior change or prompt drift"),i.length===0&&i.push("No specific cause identified - review test details"),i}categorizeRegressionSeverity(e){return e>=.5?"critical":e>=.3?"high":e>=.15?"medium":"low"}generateRecommendations(e,t,i){let s=[];if(t.inconsistentSkills.length>0&&s.push(`Review ${t.inconsistentSkills.length} skills with inconsistent cross-model behavior: `+t.inconsistentSkills.slice(0,3).join(", ")+(t.inconsistentSkills.length>3?` and ${t.inconsistentSkills.length-3} more`:"")),t.anomalies.some(r=>r.type==="low_performance")){let r=t.anomalies.filter(o=>o.type==="low_performance").map(o=>o.model);s.push(`Investigate low performance on model(s): ${r.join(", ")}`)}let a=i.filter(r=>r.severity==="critical");a.length>0&&s.push(`URGENT: ${a.length} critical regression(s) detected - immediate review required`);let n=Array.from(e.values()).filter(r=>r.avgPassRate<.9);if(n.length>0){let r=n.filter(l=>!l.schemaValid),o=n.filter(l=>!l.validatorPassed);r.length>0&&s.push(`Fix schema validation for: ${r.map(l=>l.skill).slice(0,3).join(", ")}`),o.length>0&&s.push(`Review validator scripts for: ${o.map(l=>l.skill).slice(0,3).join(", ")}`)}return Array.from(e.values()).reduce((r,o)=>r+o.avgPassRate,0)/e.size<.8&&s.push("Overall pass rate below 80% - consider reviewing skill definitions and test expectations"),s.length===0&&s.push("All validations passing - no immediate action required"),s}async updateManifest(e){if(!N(this.manifestPath))throw new Error(`Manifest file not found: ${this.manifestPath}`);let t=C(L(this.manifestPath,"utf-8"));for(let[s,a]of e.skillResults.entries())if(t.skills&&t.skills[s]){let n=t.skills[s];n.validation||(n.validation={}),n.validation.passRate=a.avgPassRate,n.validation.lastValidated=e.timestamp.toISOString(),n.validation.status=a.avgPassRate>=.9?"passing":"failing",n.validation.passRateByModel=Object.fromEntries(a.passRateByModel)}let i=Array.from(e.skillResults.values());t.validationStatus={passing:i.filter(s=>s.avgPassRate>=.9).length,failing:i.filter(s=>s.avgPassRate<.9).length,unknown:0,skipped:t.summary?.tier0||0},t.generatedAt=new Date().toISOString(),t.lastValidationRun={runId:e.runId,timestamp:e.timestamp.toISOString(),avgPassRate:e.summary.avgPassRate,modelsUsed:e.summary.modelsUsed},E(this.manifestPath,JSON.stringify(t,null,2))}generateMarkdownReport(e){let{summary:t,crossModelAnalysis:i,regressions:s,recommendations:a,skillResults:n}=e,c=(t.avgPassRate>=.9||t.avgPassRate>=.7,"`"),r=[];if(r.push(`# Validation Report
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.19");process.exit(0)}
2
+ import{a as T}from"./chunk-Z2E5DTKX.js";import{c as S}from"./chunk-5KGFDNYI.js";import{b as C,d as P}from"./chunk-5R2DUR3A.js";import{a as w,c as $}from"./chunk-5MGRZ4YD.js";import{a as b,d as M}from"./chunk-SKNHAGYP.js";$();M();import{randomUUID as D}from"crypto";var x={topology:"hierarchical",maxConcurrentSkills:10,maxConcurrentModels:3,timeout:3e5,continueOnFailure:!0,retry:{maxRetries:2,retryDelayMs:1e3}},R=class{config;learner;skillValidator=null;workers=new Map;taskQueue=[];isRunning=!1;constructor(e,t){this.config={...x,...e},this.learner=t}setSkillValidator(e){this.skillValidator=e}async validateSkillsParallel(e,t,i){let s=Date.now(),a=i?.trustTier??3,n=i?.validationLevel??"eval",c=this.determineTopology(e.length,t.length),r=this.createValidationTasks(e,t,a,n),o=await this.executeTasksParallel(r,c),l=new Map;for(let u of o){let p=l.get(u.skill)||[];p.push(u),l.set(u.skill,p)}return await this.recordOutcomesToLearner(o,a,n),l}async validateSkillCrossModel(e,t,i){return(await this.validateSkillsParallel([e],t,i)).get(e)||[]}getSummary(e){let t=[],i=new Map,s=new Map;for(let[c,r]of e){i.set(c,r);for(let o of r){t.push(o);let l=s.get(o.model)||[];l.push(o),s.set(o.model,l)}}let a=t.filter(c=>c.errors.length===0&&c.evalPassRate>=.9).length,n=t.reduce((c,r)=>c+r.durationMs,0);return{totalSkills:i.size,totalModels:s.size,successCount:a,failureCount:t.length-a,overallPassRate:t.length>0?a/t.length:0,totalDurationMs:n,avgDurationMs:t.length>0?n/t.length:0,topology:this.config.topology,bySkill:i,byModel:s,results:t}}determineTopology(e,t){if(this.config.topology){let i=e*t;return i>20&&this.config.topology==="mesh"&&console.warn(`[SwarmSkillValidator] Large workload (${i} tasks) may be more efficient with hierarchical topology`),this.config.topology}return e>5||e>t*2?"hierarchical":t>5&&e<=3?"mesh":"hierarchical"}createValidationTasks(e,t,i,s){let a=[];for(let n of e)for(let c of t)a.push({id:`${n}-${c}-${Date.now()}-${D().slice(0,8)}`,skill:n,model:c,trustTier:i,validationLevel:s,timeout:this.config.timeout,retryCount:0});return a}async executeTasksParallel(e,t){this.isRunning=!0,this.taskQueue=[...e];let i=[],s=t==="hierarchical"?this.config.maxConcurrentSkills:Math.min(this.config.maxConcurrentSkills*this.config.maxConcurrentModels,e.length),a=[];for(let n=0;n<Math.min(s,e.length);n++){let c=`worker-${n}`;this.workers.set(c,{id:c,task:null,status:"idle"}),a.push(this.runWorker(c,i))}return await Promise.all(a),this.isRunning=!1,this.workers.clear(),i}async runWorker(e,t){let i=this.workers.get(e);if(i){for(;this.taskQueue.length>0&&this.isRunning;){let s=this.taskQueue.shift();if(!s)break;i.task=s,i.status="running",i.startTime=Date.now();try{let a=await this.executeValidationTask(s);t.push(a),i.result=a,i.status="completed"}catch(a){let n=this.createErrorResult(s,a);this.config.retry&&s.retryCount<this.config.retry.maxRetries&&this.config.continueOnFailure?(s.retryCount++,this.taskQueue.push(s),await this.delay(this.config.retry.retryDelayMs)):(t.push(n),i.result=n,i.status="failed")}}i.task=null,i.status="idle"}}async executeValidationTask(e){let t=Date.now();if(!this.skillValidator)return this.createSimulatedResult(e,t);let i=new Promise((n,c)=>{setTimeout(()=>c(new Error(`Validation timeout after ${e.timeout}ms`)),e.timeout)}),s=await Promise.race([this.skillValidator(e.skill,e.model,{trustTier:e.trustTier,validationLevel:e.validationLevel,timeout:e.timeout}),i]),a=Date.now()-t;return this.outcomeToResult(s,e,a)}outcomeToResult(e,t,i){let s=e.testCaseResults.filter(c=>c.passed).length,a=e.testCaseResults.length,n=a>0?s/a:e.score;return{skill:t.skill,model:t.model,schemaValid:e.validationLevel!=="schema"||e.passed,validatorPassed:e.validationLevel!=="validator"||e.passed,evalPassRate:n,durationMs:i,errors:e.passed?[]:["Validation failed"],trustTier:t.trustTier,validationLevel:t.validationLevel,retryCount:t.retryCount,timestamp:new Date}}createSimulatedResult(e,t){let i=Date.now()-t+b()*100,s=.85+b()*.15;return{skill:e.skill,model:e.model,schemaValid:!0,validatorPassed:s>.8,evalPassRate:s,durationMs:i,errors:s>.8?[]:["Simulated validation failure"],trustTier:e.trustTier,validationLevel:e.validationLevel,retryCount:e.retryCount,timestamp:new Date}}createErrorResult(e,t){let i=w(t);return{skill:e.skill,model:e.model,schemaValid:!1,validatorPassed:!1,evalPassRate:0,durationMs:0,errors:[i],trustTier:e.trustTier,validationLevel:e.validationLevel,retryCount:e.retryCount,timestamp:new Date}}async recordOutcomesToLearner(e,t,i){for(let s of e){let a={skillName:s.skill,trustTier:s.trustTier||t,validationLevel:s.validationLevel||i,model:s.model,passed:s.errors.length===0&&s.evalPassRate>=.9,score:s.evalPassRate,testCaseResults:this.createTestCaseResults(s),timestamp:s.timestamp,runId:`swarm-${Date.now()}`,metadata:{duration:s.durationMs,retryCount:s.retryCount}};await this.learner.recordValidationOutcome(a)}}createTestCaseResults(e){return[{testId:`${e.skill}-${e.model}-aggregate`,passed:e.errors.length===0,expectedPatterns:["valid-output"],actualPatterns:e.errors.length===0?["valid-output"]:[],reasoningQuality:e.evalPassRate,executionTimeMs:e.durationMs,category:"swarm-validation",priority:"high",error:e.errors.length>0?e.errors.join("; "):void 0}]}delay(e){return new Promise(t=>setTimeout(t,e))}getConfig(){return{...this.config}}isValidationRunning(){return this.isRunning}getWorkerStatus(){return Array.from(this.workers.values())}cancel(){this.isRunning=!1,this.taskQueue=[]}};function A(y,e){return new R(y,e)}var F=["security-testing","accessibility-testing","api-testing","performance-testing","visual-regression-testing","mutation-testing","contract-testing","chaos-testing","compliance-testing","penetration-testing"],I=["claude-sonnet","claude-haiku","claude-opus"];P();import{readFileSync as L,writeFileSync as E,existsSync as N}from"fs";var O={varianceThreshold:.04,regressionThreshold:.1,minSamples:3,autoUpdateManifest:!1},k=class{constructor(e,t,i={}){this.learner=e;this.manifestPath=t;this.config={...O,...i}}learner;manifestPath;config;async aggregateResults(e){let t=`agg-${Date.now()}`,i=new Date,s=this.buildSkillResultsMap(e),a=this.calculateSummary(s,e),n=await this.detectCrossModelAnomalies(e),c=await this.detectRegressions(e,this.config.regressionThreshold),r=this.generateRecommendations(s,n,c),o={timestamp:i,runId:t,summary:a,skillResults:s,crossModelAnalysis:n,regressions:c,recommendations:r,metadata:{version:"1.0.0",environment:e[0]?.metadata?.environment,generatedBy:"ValidationResultAggregator",inputs:{runIds:e.map(l=>l.runId),models:[...new Set(e.map(l=>l.model))]}}};return this.config.autoUpdateManifest&&await this.updateManifest(o),o}buildSkillResultsMap(e){let t=new Map;for(let i of e)for(let s of i.outcomes){let a=s.skillName;t.has(a)||t.set(a,{skill:a,trustTier:s.trustTier,passRateByModel:new Map,avgPassRate:0,schemaValid:!0,validatorPassed:!0,evalPassed:!0,issues:[],executionTimeMs:0,testCount:0,passedTests:0,failedTests:0});let n=t.get(a),c=s.testCaseResults.filter(r=>r.passed).length/(s.testCaseResults.length||1);n.passRateByModel.set(i.model,c),n.testCount+=s.testCaseResults.length,n.passedTests+=s.testCaseResults.filter(r=>r.passed).length,n.failedTests+=s.testCaseResults.filter(r=>!r.passed).length,n.executionTimeMs+=s.metadata?.duration||0,s.validationLevel==="schema"&&!s.passed&&(n.schemaValid=!1),s.validationLevel==="validator"&&!s.passed&&(n.validatorPassed=!1),s.validationLevel==="eval"&&!s.passed&&(n.evalPassed=!1);for(let r of s.testCaseResults)!r.passed&&r.error&&n.issues.push({skill:a,model:i.model,severity:r.priority==="critical"?"critical":r.priority==="high"?"high":r.priority==="medium"?"medium":"low",type:this.categorizeIssueType(s.validationLevel,r.error),message:r.error,testId:r.testId})}for(let i of t.values()){let s=Array.from(i.passRateByModel.values());i.avgPassRate=s.length>0?s.reduce((a,n)=>a+n,0)/s.length:0}return t}categorizeIssueType(e,t){return t.toLowerCase().includes("timeout")?"timeout":e==="schema"?"schema_failure":e==="validator"?"validator_failure":e==="eval"?"eval_failure":"error"}calculateSummary(e,t){let i=Array.from(e.values()),s=i.filter(n=>n.avgPassRate>=.9).length,a=i.length>0?i.reduce((n,c)=>n+c.avgPassRate,0)/i.length:0;return{totalSkills:i.length,passedSkills:s,failedSkills:i.length-s,avgPassRate:a,totalDurationMs:t.reduce((n,c)=>n+c.durationMs,0),totalTests:i.reduce((n,c)=>n+c.testCount,0),passedTests:i.reduce((n,c)=>n+c.passedTests,0),failedTests:i.reduce((n,c)=>n+c.failedTests,0),modelsUsed:[...new Set(t.map(n=>n.model))]}}async detectCrossModelAnomalies(e){let t=new Map,i=new Map,s=new Map;for(let d of e){t.has(d.model)||(t.set(d.model,[]),i.set(d.model,{totalTests:0,passedTests:0,skillCount:0}));for(let g of d.outcomes){let h=g.testCaseResults.filter(m=>m.passed).length/(g.testCaseResults.length||1);t.get(d.model).push(h);let f=i.get(d.model);f.totalTests+=g.testCaseResults.length,f.passedTests+=g.testCaseResults.filter(m=>m.passed).length,f.skillCount++,s.has(g.skillName)||s.set(g.skillName,{passRates:[],models:[]}),s.get(g.skillName).passRates.push(h),s.get(g.skillName).models.push(d.model)}}let a=[];for(let d of t.values())a.push(...d);let n=a.length>0?a.reduce((d,g)=>d+g,0)/a.length:0,c=a.length>1?a.reduce((d,g)=>d+Math.pow(g-n,2),0)/a.length:0,r=Math.sqrt(c),o=[],l=new Map;for(let[d,g]of t.entries()){let h=g.reduce((v,V)=>v+V,0)/g.length,f=h-n,m=i.get(d);l.set(d,{avgPassRate:h,skillCount:m.skillCount,totalTests:m.totalTests}),Math.abs(f)>this.config.varianceThreshold*2&&o.push({model:d,type:f<0?"low_performance":"high_variance",description:`Model ${d} has ${(f*100).toFixed(1)}% difference from average`,passRate:h,avgPassRate:n,deviation:Math.abs(f)})}let u=[],p=[];for(let[d,g]of s.entries()){if(g.passRates.length<2)continue;let h=g.passRates.reduce((m,v)=>m+v,0)/g.passRates.length;g.passRates.reduce((m,v)=>m+Math.pow(v-h,2),0)/g.passRates.length<this.config.varianceThreshold?u.push(d):p.push(d)}return{variance:c,stdDeviation:r,anomalies:o,consistentSkills:u,inconsistentSkills:p,modelPerformance:l}}async detectRegressions(e,t){let i=[],s=new Set;for(let a of e)for(let n of a.outcomes){let c=`${n.skillName}-${a.model}`;if(s.has(c))continue;s.add(c);let r=await this.learner.getValidationTrends(n.skillName);if(!r)continue;let o=n.testCaseResults.filter(p=>p.passed).length/(n.testCaseResults.length||1),l=r.recentPassRate,u=l-o;u>=t&&i.push({skill:n.skillName,model:a.model,previousPassRate:l,currentPassRate:o,regressionAmount:u,trend:r.overall,possibleCauses:this.analyzePossibleCauses(n,u),severity:this.categorizeRegressionSeverity(u)})}return i.sort((a,n)=>{let c={critical:0,high:1,medium:2,low:3},r=c[a.severity]-c[n.severity];return r!==0?r:n.regressionAmount-a.regressionAmount})}analyzePossibleCauses(e,t){let i=[],s=e.testCaseResults.filter(c=>!c.passed);if(s.length>0){let c=[...new Set(s.map(r=>r.category).filter(Boolean))];c.length>0&&i.push(`Failures in categories: ${c.join(", ")}`)}let a=s.filter(c=>c.priority==="critical");a.length>0&&i.push(`${a.length} critical test(s) failing`);let n=e.testCaseResults.reduce((c,r)=>c+r.reasoningQuality,0)/(e.testCaseResults.length||1);return n<.7&&i.push(`Low reasoning quality score: ${(n*100).toFixed(1)}%`),t>.3&&i.push("Possible model behavior change or prompt drift"),i.length===0&&i.push("No specific cause identified - review test details"),i}categorizeRegressionSeverity(e){return e>=.5?"critical":e>=.3?"high":e>=.15?"medium":"low"}generateRecommendations(e,t,i){let s=[];if(t.inconsistentSkills.length>0&&s.push(`Review ${t.inconsistentSkills.length} skills with inconsistent cross-model behavior: `+t.inconsistentSkills.slice(0,3).join(", ")+(t.inconsistentSkills.length>3?` and ${t.inconsistentSkills.length-3} more`:"")),t.anomalies.some(r=>r.type==="low_performance")){let r=t.anomalies.filter(o=>o.type==="low_performance").map(o=>o.model);s.push(`Investigate low performance on model(s): ${r.join(", ")}`)}let a=i.filter(r=>r.severity==="critical");a.length>0&&s.push(`URGENT: ${a.length} critical regression(s) detected - immediate review required`);let n=Array.from(e.values()).filter(r=>r.avgPassRate<.9);if(n.length>0){let r=n.filter(l=>!l.schemaValid),o=n.filter(l=>!l.validatorPassed);r.length>0&&s.push(`Fix schema validation for: ${r.map(l=>l.skill).slice(0,3).join(", ")}`),o.length>0&&s.push(`Review validator scripts for: ${o.map(l=>l.skill).slice(0,3).join(", ")}`)}return Array.from(e.values()).reduce((r,o)=>r+o.avgPassRate,0)/e.size<.8&&s.push("Overall pass rate below 80% - consider reviewing skill definitions and test expectations"),s.length===0&&s.push("All validations passing - no immediate action required"),s}async updateManifest(e){if(!N(this.manifestPath))throw new Error(`Manifest file not found: ${this.manifestPath}`);let t=C(L(this.manifestPath,"utf-8"));for(let[s,a]of e.skillResults.entries())if(t.skills&&t.skills[s]){let n=t.skills[s];n.validation||(n.validation={}),n.validation.passRate=a.avgPassRate,n.validation.lastValidated=e.timestamp.toISOString(),n.validation.status=a.avgPassRate>=.9?"passing":"failing",n.validation.passRateByModel=Object.fromEntries(a.passRateByModel)}let i=Array.from(e.skillResults.values());t.validationStatus={passing:i.filter(s=>s.avgPassRate>=.9).length,failing:i.filter(s=>s.avgPassRate<.9).length,unknown:0,skipped:t.summary?.tier0||0},t.generatedAt=new Date().toISOString(),t.lastValidationRun={runId:e.runId,timestamp:e.timestamp.toISOString(),avgPassRate:e.summary.avgPassRate,modelsUsed:e.summary.modelsUsed},E(this.manifestPath,JSON.stringify(t,null,2))}generateMarkdownReport(e){let{summary:t,crossModelAnalysis:i,regressions:s,recommendations:a,skillResults:n}=e,c=(t.avgPassRate>=.9||t.avgPassRate>=.7,"`"),r=[];if(r.push(`# Validation Report
3
3
 
4
4
  > ${c} Generated: ${e.timestamp.toISOString()}
5
5
  > Run ID: ${e.runId}
@@ -0,0 +1,69 @@
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.19");process.exit(0)}
2
+ import{a as w,b as A,c as O,e as D,f as $}from"./chunk-AG7J7DTM.js";import{b as S,d as z}from"./chunk-5R2DUR3A.js";import{a as b,c as F}from"./chunk-5MGRZ4YD.js";import{i as v}from"./chunk-MIQAFOFO.js";import*as I from"node:path";$();z();var P=["function","module","test","file","class"],L=["calls","imports","tests","depends_on","covers"],R=class{ensureSchema(e){e.transaction(()=>{e.exec(w),e.exec(A),e.exec(O)})()}schemaExists(e){return D(e)}getNodeTypes(){return P}getEdgeTypes(){return L}isValidNodeType(e){return P.includes(e)}isValidEdgeType(e){return L.includes(e)}getStats(e){if(!this.schemaExists(e))return{nodeCount:0,edgeCount:0};let t=e.prepare("SELECT COUNT(*) as count FROM hypergraph_nodes").get().count,r=e.prepare("SELECT COUNT(*) as count FROM hypergraph_edges").get().count;return{nodeCount:t,edgeCount:r}}dropSchema(e){let t=e.prepare("SELECT COUNT(*) as cnt FROM hypergraph_nodes").get()?.cnt??0,r=e.prepare("SELECT COUNT(*) as cnt FROM hypergraph_edges").get()?.cnt??0;if(t>0||r>0)throw new Error(`REFUSING to drop hypergraph schema: tables contain data (${t} nodes, ${r} edges). Backup and manually drop if needed.`);e.transaction(()=>{e.exec("DROP TABLE IF EXISTS hypergraph_edges"),e.exec("DROP TABLE IF EXISTS hypergraph_nodes")})()}};function H(n){return{id:n.id,type:n.type,name:n.name,file_path:n.filePath??null,line_start:n.lineStart??null,line_end:n.lineEnd??null,complexity:n.complexity??null,coverage:n.coverage??null,metadata:n.metadata?JSON.stringify(n.metadata):null,embedding:n.embedding?U(n.embedding):null}}function f(n){return{id:n.id,type:n.type,name:n.name,filePath:n.file_path??void 0,lineStart:n.line_start??void 0,lineEnd:n.line_end??void 0,complexity:n.complexity??void 0,coverage:n.coverage??void 0,metadata:n.metadata?S(n.metadata):void 0,embedding:n.embedding?W(n.embedding):void 0,createdAt:n.created_at,updatedAt:n.updated_at}}function M(n){return{id:n.id,source_id:n.sourceId,target_id:n.targetId,type:n.type,weight:n.weight??1,properties:n.properties?JSON.stringify(n.properties):null}}function C(n){return{id:n.id,sourceId:n.source_id,targetId:n.target_id,type:n.type,weight:n.weight,properties:n.properties?S(n.properties):void 0,createdAt:n.created_at}}function x(n,e,t){return`${n}--${t}-->${e}`}function U(n){let e=Buffer.alloc(n.length*4);for(let t=0;t<n.length;t++)e.writeFloatLE(n[t],t*4);return e}function W(n){let e=[],t=n.length/4;for(let r=0;r<t;r++)e.push(n.readFloatLE(r*4));return e}F();var B={maxTraversalDepth:10,maxQueryResults:1e3,enableVectorSearch:!1},_=class{config;schemaManager;initialized=!1;constructor(e){this.config={...B,...e},this.schemaManager=new R}async initialize(){this.initialized||(this.schemaManager.ensureSchema(this.config.db),this.initialized=!0)}isInitialized(){return this.initialized}async addNode(e){this.ensureInitialized();let t=v(),r={id:t,...e},i=H(r);return this.config.db.prepare(`
3
+ INSERT INTO hypergraph_nodes (id, type, name, file_path, line_start, line_end, complexity, coverage, metadata, embedding)
4
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
5
+ `).run(i.id,i.type,i.name,i.file_path,i.line_start,i.line_end,i.complexity,i.coverage,i.metadata,i.embedding),t}async addEdge(e){this.ensureInitialized();let t=x(e.sourceId,e.targetId,e.type),r={id:t,...e},i=M(r);return this.config.db.prepare(`
6
+ INSERT OR REPLACE INTO hypergraph_edges (id, source_id, target_id, type, weight, properties)
7
+ VALUES (?, ?, ?, ?, ?, ?)
8
+ `).run(i.id,i.source_id,i.target_id,i.type,i.weight,i.properties),t}async getNode(e){this.ensureInitialized();let t=this.config.db.prepare("SELECT * FROM hypergraph_nodes WHERE id = ?").get(e);return t?f(t):null}async getEdge(e){this.ensureInitialized();let t=this.config.db.prepare("SELECT * FROM hypergraph_edges WHERE id = ?").get(e);return t?C(t):null}async updateNode(e,t){this.ensureInitialized();let r=await this.getNode(e);if(!r)throw new Error(`Node not found: ${e}`);let i={...r,...t},s=H(i);this.config.db.prepare(`
9
+ UPDATE hypergraph_nodes
10
+ SET type = ?, name = ?, file_path = ?, line_start = ?, line_end = ?,
11
+ complexity = ?, coverage = ?, metadata = ?, embedding = ?,
12
+ updated_at = datetime('now')
13
+ WHERE id = ?
14
+ `).run(s.type,s.name,s.file_path,s.line_start,s.line_end,s.complexity,s.coverage,s.metadata,s.embedding,e)}async deleteNode(e){this.ensureInitialized(),this.config.db.prepare("DELETE FROM hypergraph_edges WHERE source_id = ? OR target_id = ?").run(e,e),this.config.db.prepare("DELETE FROM hypergraph_nodes WHERE id = ?").run(e)}async deleteEdge(e){this.ensureInitialized(),this.config.db.prepare("DELETE FROM hypergraph_edges WHERE id = ?").run(e)}async findNodes(e){this.ensureInitialized();let t=[],r=[];if(e.type){let u=Array.isArray(e.type)?e.type:[e.type];t.push(`type IN (${u.map(()=>"?").join(", ")})`),r.push(...u)}e.filePath&&(e.filePath.includes("%")?t.push("file_path LIKE ?"):t.push("file_path = ?"),r.push(e.filePath)),e.name&&typeof e.name=="string"&&(t.push("name = ?"),r.push(e.name)),e.minComplexity!==void 0&&(t.push("complexity >= ?"),r.push(e.minComplexity)),e.maxComplexity!==void 0&&(t.push("complexity <= ?"),r.push(e.maxComplexity)),e.minCoverage!==void 0&&(t.push("coverage >= ?"),r.push(e.minCoverage)),e.maxCoverage!==void 0&&(t.push("coverage <= ?"),r.push(e.maxCoverage));let i=t.length>0?`WHERE ${t.join(" AND ")}`:"",s=e.limit??this.config.maxQueryResults,d=`SELECT * FROM hypergraph_nodes ${i} LIMIT ?`;r.push(s);let c=this.config.db.prepare(d).all(...r).map(f);return e.name instanceof RegExp&&(c=c.filter(u=>e.name instanceof RegExp&&e.name.test(u.name))),c}async findEdges(e){this.ensureInitialized();let t=[],r=[];if(e.type){let c=Array.isArray(e.type)?e.type:[e.type];t.push(`type IN (${c.map(()=>"?").join(", ")})`),r.push(...c)}e.sourceId&&(t.push("source_id = ?"),r.push(e.sourceId)),e.targetId&&(t.push("target_id = ?"),r.push(e.targetId)),e.minWeight!==void 0&&(t.push("weight >= ?"),r.push(e.minWeight));let i=t.length>0?`WHERE ${t.join(" AND ")}`:"",s=e.limit??this.config.maxQueryResults,d=`SELECT * FROM hypergraph_edges ${i} LIMIT ?`;return r.push(s),this.config.db.prepare(d).all(...r).map(C)}async traverse(e,t=[],r=5){this.ensureInitialized();let i=new Map,s=new Map,d=[],g=0,c=[{nodeId:e,depth:0,path:{nodes:[e],edges:[]}}],u=Math.min(r,this.config.maxTraversalDepth);for(;c.length>0;){let{nodeId:a,depth:p,path:o}=c.shift();if(!i.has(a)){let l=await this.getNode(a);l&&i.set(a,l)}if(g=Math.max(g,p),p>=u){d.push(o);continue}let h={sourceId:a};t.length>0&&(h.type=t);let y=await this.findEdges(h);if(y.length===0){d.push(o);continue}for(let l of y)if(!s.has(l.id)){s.set(l.id,l);let m={nodes:[...o.nodes,l.targetId],edges:[...o.edges,l.id]};c.push({nodeId:l.targetId,depth:p+1,path:m})}}return{nodes:Array.from(i.values()),edges:Array.from(s.values()),paths:d,maxDepthReached:g}}async findUntestedFunctions(){return this.ensureInitialized(),this.config.db.prepare(`
15
+ SELECT n.* FROM hypergraph_nodes n
16
+ WHERE n.type = 'function'
17
+ AND NOT EXISTS (
18
+ SELECT 1 FROM hypergraph_edges e
19
+ JOIN hypergraph_nodes t ON t.id = e.source_id
20
+ WHERE e.target_id = n.id
21
+ AND e.type = 'covers'
22
+ AND t.type = 'test'
23
+ )
24
+ ORDER BY n.complexity DESC NULLS LAST
25
+ LIMIT ?
26
+ `).all(this.config.maxQueryResults).map(f)}async findImpactedTests(e){if(this.ensureInitialized(),e.length===0)return[];let r=`
27
+ SELECT DISTINCT t.* FROM hypergraph_nodes t
28
+ JOIN hypergraph_edges e ON e.source_id = t.id
29
+ JOIN hypergraph_nodes f ON f.id = e.target_id
30
+ WHERE t.type = 'test'
31
+ AND e.type = 'covers'
32
+ AND f.type = 'function'
33
+ AND f.file_path IN (${e.map(()=>"?").join(", ")})
34
+ LIMIT ?
35
+ `,i=[...e,this.config.maxQueryResults];return this.config.db.prepare(r).all(...i).map(f)}async findCoverageGaps(e=50){return this.ensureInitialized(),this.config.db.prepare(`
36
+ SELECT * FROM hypergraph_nodes
37
+ WHERE type = 'function'
38
+ AND coverage IS NOT NULL
39
+ AND coverage <= ?
40
+ ORDER BY coverage ASC, complexity DESC NULLS LAST
41
+ LIMIT ?
42
+ `).all(e,this.config.maxQueryResults).map(f)}async findModuleDependencies(e){this.ensureInitialized();let t=await this.findNodes({type:"module",filePath:e,limit:1});if(t.length===0){let a=await this.findNodes({type:"file",filePath:e,limit:1});if(a.length===0)throw new Error(`Module not found: ${e}`);t.push(a[0])}let r=t[0],i=await this.findEdges({sourceId:r.id,type:["imports","depends_on"]}),s=[];for(let a of i){let p=await this.getNode(a.targetId);p&&s.push(p)}let d=await this.findEdges({targetId:r.id,type:["imports","depends_on"]}),g=[];for(let a of d){let p=await this.getNode(a.sourceId);p&&g.push(p)}let c=await this.traverse(r.id,["imports","depends_on"],5),u=c.nodes.filter(a=>a.id!==r.id);return{module:r,directDependencies:s,dependents:g,transitiveDependencies:u,maxDependencyDepth:c.maxDepthReached}}async buildFromIndexResult(e){this.ensureInitialized();let t=Date.now(),r=0,i=0,s=0,d=[];return this.config.db.transaction(()=>{for(let a of e.files)try{let p=`file:${a.path}`;this.config.db.prepare("SELECT id FROM hypergraph_nodes WHERE id = ?").get(p)?i++:(this.config.db.prepare(`
43
+ INSERT INTO hypergraph_nodes (id, type, name, file_path)
44
+ VALUES (?, 'file', ?, ?)
45
+ `).run(p,a.path.split("/").pop()||a.path,a.path),r++)}catch(p){d.push({entity:`file:${a.path}`,error:b(p)})}for(let a of e.files){let p=`file:${a.path}`;for(let o of a.entities)try{let h=`${o.type}:${a.path}:${o.name}`,y=this.mapEntityTypeToNodeType(o.type);this.config.db.prepare("SELECT id FROM hypergraph_nodes WHERE id = ?").get(h)?(this.config.db.prepare(`
46
+ UPDATE hypergraph_nodes
47
+ SET line_start = ?, line_end = ?, complexity = ?, coverage = ?,
48
+ updated_at = datetime('now')
49
+ WHERE id = ?
50
+ `).run(o.lineStart,o.lineEnd,o.complexity,o.coverage,h),i++):(this.config.db.prepare(`
51
+ INSERT INTO hypergraph_nodes (id, type, name, file_path, line_start, line_end, complexity, coverage)
52
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
53
+ `).run(h,y,o.name,a.path,o.lineStart,o.lineEnd,o.complexity,o.coverage),r++);try{let m=x(p,h,"contains");this.config.db.prepare(`
54
+ INSERT OR REPLACE INTO hypergraph_edges (id, source_id, target_id, type, weight)
55
+ VALUES (?, ?, ?, 'contains', 1.0)
56
+ `).run(m,p,h),s++}catch(m){d.push({entity:`contains:${o.type}:${o.name}`,error:b(m)})}}catch(h){d.push({entity:`${o.type}:${o.name}`,error:b(h)})}}let c=[".ts",".tsx",".js",".jsx",".py",".mjs",".cjs"],u=["/index.ts","/index.tsx","/index.js","/index.jsx","/index.py"];for(let a of e.files){let p=`file:${a.path}`;for(let o of a.imports)try{let h=o;(o.startsWith("./")||o.startsWith("../"))&&(h=I.resolve(I.dirname(a.path),o));let y=`file:${h}`,l=this.config.db.prepare("SELECT id FROM hypergraph_nodes WHERE id = ?"),m=l.get(y);if(!m)for(let E of c){let T=y+E,N=l.get(T);if(N){y=T,m=N;break}}if(!m)for(let E of u){let T=y+E,N=l.get(T);if(N){y=T,m=N;break}}if(m){let E=x(p,y,"imports");this.config.db.prepare(`
57
+ INSERT OR REPLACE INTO hypergraph_edges (id, source_id, target_id, type, weight)
58
+ VALUES (?, ?, ?, 'imports', 1.0)
59
+ `).run(E,p,y),s++}}catch(h){d.push({entity:`import:${o}`,error:b(h)})}}})(),{nodesCreated:r,nodesUpdated:i,edgesCreated:s,durationMs:Date.now()-t,errors:d}}async syncWithKnowledgeGraph(e){this.ensureInitialized();let t=Date.now(),r=0,i=0,s=0,d=0,g=await this.findNodes({});for(let u of g){let a=await e.getNode(u.id);r++}return i=(await this.findEdges({})).length,{nodesSynced:r,edgesSynced:i,nodesAdded:s,nodesRemoved:d,durationMs:Date.now()-t}}async getStats(){this.ensureInitialized();let e=this.schemaManager.getStats(this.config.db),t=this.config.db.prepare(`
60
+ SELECT type, COUNT(*) as count FROM hypergraph_nodes GROUP BY type
61
+ `).all(),r={function:0,module:0,test:0,file:0,class:0};for(let g of t)g.type in r&&(r[g.type]=g.count);let i=this.config.db.prepare(`
62
+ SELECT type, COUNT(*) as count FROM hypergraph_edges GROUP BY type
63
+ `).all(),s={calls:0,imports:0,tests:0,depends_on:0,covers:0,contains:0};for(let g of i)g.type in s&&(s[g.type]=g.count);let d=this.config.db.prepare(`
64
+ SELECT
65
+ AVG(complexity) as avg_complexity,
66
+ AVG(coverage) as avg_coverage,
67
+ COUNT(CASE WHEN embedding IS NOT NULL THEN 1 END) as nodes_with_embeddings
68
+ FROM hypergraph_nodes
69
+ `).get();return{totalNodes:e.nodeCount,totalEdges:e.edgeCount,nodesByType:r,edgesByType:s,avgComplexity:d.avg_complexity??0,avgCoverage:d.avg_coverage??0,nodesWithEmbeddings:d.nodes_with_embeddings}}ensureInitialized(){if(!this.initialized)throw new Error("HypergraphEngine not initialized. Call initialize() first.")}mapEntityTypeToNodeType(e){return{function:"function",class:"class",module:"module",interface:"module",file:"file",test:"test"}[e]??"function"}};async function Q(n){let e=new _(n);return await e.initialize(),e}function J(n){return new _(n)}var X=_;export{B as a,_ as b,Q as c,J as d,X as e};
@@ -1,4 +1,4 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.18");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.19");process.exit(0)}
2
2
  var i={domain:"test-generation",bestPractices:["Follow Arrange-Act-Assert (AAA) pattern for clear test structure","One logical assertion per test - test one behavior at a time","Use descriptive test names: should_returnValue_when_condition","Mock external dependencies to isolate unit under test","Test edge cases and boundary conditions, not just happy paths","Keep tests deterministic - avoid time-dependent assertions","Use test data builders or factories for complex objects","Prefer integration tests for workflows, unit tests for logic","Maintain test independence - no shared mutable state between tests","Write failing test first (TDD Red) before implementation"],antiPatterns:[{name:"God Test",description:"A single test that verifies too many behaviors",reason:"Hard to diagnose failures, brittle, slow to run",alternative:"Split into focused tests, each verifying one behavior",detection:"expect.*expect.*expect.*expect.*expect"},{name:"Mystery Guest",description:"Test relies on external data files or state not visible in test",reason:"Tests are hard to understand and maintain",alternative:"Make test data explicit within the test or use fixtures"},{name:"Eager Test",description:"Test that verifies more than needed for the current behavior",reason:"Creates unnecessary coupling, breaks easily",alternative:"Only assert what is necessary for this specific test case"},{name:"Flaky Assertion",description:"Assertions that depend on timing, order, or external state",reason:"Creates unreliable test suite, erodes trust",alternative:"Use deterministic assertions, mock time/random",detection:"setTimeout|Date\\.now|Math\\.random"},{name:"Test Code Duplication",description:"Same setup or assertion code repeated across tests",reason:"Maintenance burden, inconsistency risk",alternative:"Extract to beforeEach, helpers, or fixtures"}],frameworkGuidance:{jest:["Use describe blocks to group related tests","Prefer toEqual for deep equality, toBe for primitives","Use jest.mock() at module level for consistent mocking","Use jest.spyOn for partial mocking of objects","Enable --coverage to track test coverage"],vitest:["Use vi.mock() for module mocking","Prefer vi.fn() over jest.fn() syntax","Use vitest/ui for interactive test debugging","Enable browser mode for component tests","Use inline snapshots for small expected values"],mocha:["Use beforeEach/afterEach for setup/teardown","Combine with chai for assertions","Use sinon for spies, stubs, and mocks","Set appropriate timeouts for async tests"],pytest:["Use fixtures for reusable test setup","Use parametrize for data-driven tests","Use conftest.py for shared fixtures","Use pytest.raises for exception testing","Use pytest-cov for coverage reporting"],junit:["Use @BeforeEach and @AfterEach for setup/teardown","Use @DisplayName for readable test names","Use @ParameterizedTest for data-driven tests","Use Mockito for mocking dependencies"],testng:["Use @BeforeMethod and @AfterMethod appropriately","Use @DataProvider for parameterized tests","Configure test groups for selective execution"],playwright:["Use page.locator() for resilient element selection","Use expect(locator) for auto-waiting assertions","Use page.waitForLoadState for navigation","Use test.describe for grouping tests","Use fixtures for reusable browser contexts"],cypress:["Use cy.intercept() for API mocking","Avoid conditional testing - use deterministic state","Use data-cy attributes for stable selectors","Use cy.within() for scoped queries","Prefer cy.contains() for text-based selection"],selenium:["Use explicit waits over implicit waits","Use Page Object Model for maintainability","Handle stale element references with retry logic","Clean up browser state between tests"]},languageGuidance:{typescript:["Use type assertions in tests for better IDE support","Create typed test fixtures and builders","Use satisfies operator for test data validation","Mock types with ts-mockito or typed mocking libs"],javascript:["Use JSDoc comments for test documentation","Consider TypeScript for larger test suites","Use ESLint with testing plugins"],python:["Use type hints in test functions","Use dataclasses for test data","Follow PEP 8 naming: test_should_do_something"],java:["Use AssertJ for fluent assertions","Use Lombok for test data classes","Follow naming: shouldDoSomething_whenCondition"],go:["Use table-driven tests for multiple cases","Use testify for assertions and mocking","Place tests in _test.go files"],rust:["Use #[test] attribute for test functions","Use assert!, assert_eq!, assert_ne! macros","Place unit tests in same file with #[cfg(test)]"],csharp:["Use xUnit or NUnit for testing","Use FluentAssertions for readable assertions","Use Moq for mocking interfaces"],kotlin:["Use kotest for BDD-style testing","Use MockK for Kotlin-first mocking","Use data classes for test fixtures"]},examples:[{title:"Unit Test Template (TypeScript + Vitest)",description:"Standard AAA pattern for unit tests",content:`describe('UserService', () => {
3
3
  describe('createUser', () => {
4
4
  it('should create user with valid data', async () => {
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.18");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.19");process.exit(0)}
2
2
  function M(u){let e=u|0;return()=>{e=e+1831565813|0;let n=Math.imul(e^e>>>15,1|e);return n=n+Math.imul(n^n>>>7,61|n)^n,((n^n>>>14)>>>0)/4294967296}}var A=2,y=10,x=200,p=1e-8,b=class{epsilon;seed;constructor(e){if(this.epsilon=e?.epsilon??.3,this.seed=e?.seed,this.epsilon<=0||this.epsilon>=1)throw new Error("SparsifierConfig.epsilon must be in (0, 1)")}sparsify(e){if(e.nodeCount<=0||e.edges.length===0)return{nodeCount:e.nodeCount,edges:[]};let n=this.seed!==void 0?M(this.seed):Math.random,t=this.approximateEffectiveResistances(e),i=e.nodeCount,r=e.edges.length,o=Math.max(1,Math.log(i)),m=this.epsilon*this.epsilon,l=Math.min(r,Math.max(i-1,A*(i-1)*(1-this.epsilon))),s=new Float64Array(r),c=0;for(let a=0;a<r;a++){let d=e.edges[a][2];s[a]=d*t[a],c+=s[a]}if(c<=0)return{nodeCount:e.nodeCount,edges:[]};let f=[];for(let a=0;a<r;a++){let[d,C,E]=e.edges[a],g=Math.min(1,s[a]/c*l);if(n()<g){let w=E/g;f.push([d,C,w])}}return{nodeCount:e.nodeCount,edges:f}}validateSpectral(e,n){let t=Math.min(y,Math.max(1,e.nodeCount-1)),i=this.computeLaplacian(e),r=this.computeLaplacian(n),o=this.computeTopEigenvalues(i,t),m=this.computeTopEigenvalues(r,t),l=[],s=!0,c=this.epsilon;for(let f=0;f<o.length;f++){if(o[f]<1e-10)continue;let a=m[f]/o[f];l.push(a),(a<1-c||a>1+c)&&(s=!1)}return{isValid:s,eigenvalueRatios:l,originalEdgeCount:e.edges.length,sparsifiedEdgeCount:n.edges.length,compressionRatio:e.edges.length>0?n.edges.length/e.edges.length:0}}computeLaplacian(e){let n=e.nodeCount,t=Array.from({length:n},()=>new Array(n).fill(0));for(let[i,r,o]of e.edges)i<0||i>=n||r<0||r>=n||(t[i][i]+=o,t[r][r]+=o,t[i][r]-=o,t[r][i]-=o);return t}computeTopEigenvalues(e,n){let t=e.length;if(t===0)return[];let i=[],r=[],o=e.map(m=>[...m]);for(let m=0;m<Math.min(n,t);m++){let l=this.powerIteration(o,t,r);if(l===null)break;i.push(l.eigenvalue),r.push(l.eigenvector),V(o,l.eigenvalue,l.eigenvector)}return i}approximateEffectiveResistances(e){let n=e.nodeCount,t=new Float64Array(n);for(let[r,o,m]of e.edges)r>=0&&r<n&&(t[r]+=m),o>=0&&o<n&&(t[o]+=m);let i=new Array(e.edges.length);for(let r=0;r<e.edges.length;r++){let[o,m]=e.edges[r],l=t[o]||1,s=t[m]||1;i[r]=1/l+1/s}return i}powerIteration(e,n,t){let i=0;for(let s=0;s<n;s++)for(let c=0;c<n;c++)i+=e[s][c]*e[s][c];if(i<p*p)return null;let r=t.length,o=new Array(n);for(let s=0;s<n;s++)o[s]=Math.sin((s+1)*(r+1)*1.618033988749895)+.1*(s-n/2);for(let s of t)h(o,s);if(R(o)<p)return null;let l=0;for(let s=0;s<x;s++){let c=L(e,o);for(let d of t)h(c,d);let f=S(c,o),a=v(c);if(a<p)return{eigenvalue:0,eigenvector:o};for(let d=0;d<n;d++)o[d]=c[d]/a;if(Math.abs(f-l)<p){l=f;break}l=f}return{eigenvalue:Math.abs(l),eigenvector:o}}};function L(u,e){let n=u.length,t=new Array(n).fill(0);for(let i=0;i<n;i++){let r=0;for(let o=0;o<n;o++)r+=u[i][o]*e[o];t[i]=r}return t}function v(u){let e=0;for(let n=0;n<u.length;n++)e+=u[n]*u[n];return Math.sqrt(e)}function R(u){let e=v(u);if(e>0)for(let n=0;n<u.length;n++)u[n]/=e;return e}function S(u,e){let n=0;for(let t=0;t<u.length;t++)n+=u[t]*e[t];return n}function h(u,e){let n=S(u,e);for(let t=0;t<u.length;t++)u[t]-=n*e[t]}function V(u,e,n){let t=n.length;for(let i=0;i<t;i++)for(let r=0;r<t;r++)u[i][r]-=e*n[i]*n[r]}export{b as a};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.18");process.exit(0)}
2
- import{c as t}from"./chunk-FKNYOKIK.js";import{randomInt as o}from"node:crypto";function a(){return Math.random()}function m(n,e){return o(n,e)}function c(n,e){return n+Math.random()*(e-n)}var r=t(()=>{"use strict"});export{a,m as b,c,r as d};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.19");process.exit(0)}
2
+ import{c as t}from"./chunk-WULMXLNN.js";import{randomInt as o}from"node:crypto";function a(){return Math.random()}function m(n,e){return o(n,e)}function c(n,e){return n+Math.random()*(e-n)}var r=t(()=>{"use strict"});export{a,m as b,c,r as d};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.18");process.exit(0)}
2
- import{g}from"./chunk-JGNVI5UB.js";import{b as p,c as d}from"./chunk-TPL3CBMS.js";import{b as m,c as f}from"./chunk-UNPTSPAO.js";import{i as h}from"./chunk-LVABI4OA.js";f();var I={maxDepth:5,riskWeights:{directImpact:.4,transitiveImpact:.2,testCoverage:.2,criticalPath:.15,dependencyCount:.05},testPatterns:["**/*.test.ts","**/*.test.tsx","**/*.spec.ts","**/*.spec.tsx","**/test_*.py","**/*_test.py","**/*_test.go"],criticalPaths:["**/auth/**","**/security/**","**/payment/**","**/api/**","**/core/**"],namespace:"code-intelligence:impact"},u=class{constructor(e,t,i={}){this.memory=e;this.config={...I,...i},this.knowledgeGraph=t||new g(e)}memory;config;knowledgeGraph;async analyzeImpact(e){try{let{changedFiles:t,depth:i=this.config.maxDepth,includeTests:n=!0}=e;if(t.length===0)return p({directImpact:[],transitiveImpact:[],impactedTests:[],riskLevel:"info",recommendations:[]});let r=await this.analyzeDirectImpact(t),l=await this.analyzeTransitiveImpact(t,r,i),s=[];if(n){let a=await this.getImpactedTests(t);a.success&&(s=a.value)}let c={directImpact:r,transitiveImpact:l,impactedTests:s,riskLevel:"info",recommendations:[]};return c.riskLevel=this.calculateRiskLevel(c),c.recommendations=this.getRecommendations(c),await this.storeAnalysis(t,c),p(c)}catch(t){return d(m(t))}}async getImpactedTests(e){try{let t=new Set;for(let i of e){if(this.isTestFile(i)){t.add(i);continue}let n=await this.knowledgeGraph.mapDependencies({files:[i],direction:"incoming",depth:3});if(n.success)for(let s of n.value.nodes)this.isTestFile(s.path)&&t.add(s.path);let r=this.getBaseName(i),l=[`${r}.test`,`${r}.spec`,`test_${r}`,`${r}_test`];for(let s of l){let c=await this.memory.search(`code-intelligence:kg:node:*${s}*`,10);for(let a of c){let o=await this.memory.get(a);o?.properties?.path&&this.isTestFile(o.properties.path)&&t.add(o.properties.path)}}}return p(Array.from(t))}catch(t){return d(m(t))}}calculateRiskLevel(e){let t=this.config.riskWeights,i=0,n=Math.min(1,e.directImpact.length/10);i+=n*t.directImpact;let r=Math.min(1,e.transitiveImpact.length/20);i+=r*t.transitiveImpact;let l=e.impactedTests.length>0?Math.max(0,1-e.impactedTests.length/(e.directImpact.length||1)):1;i+=l*t.testCoverage;let s=this.countCriticalFiles([...e.directImpact.map(o=>o.file),...e.transitiveImpact.map(o=>o.file)]),c=Math.min(1,s/5);i+=c*t.criticalPath;let a=this.calculateAverageRiskScore([...e.directImpact,...e.transitiveImpact]);return i+=a*t.dependencyCount,i>=.8?"critical":i>=.6?"high":i>=.4?"medium":i>=.2?"low":"info"}getRecommendations(e){let t=[];(e.riskLevel==="critical"||e.riskLevel==="high")&&t.push("This change has significant impact - consider peer review before merging"),e.impactedTests.length===0&&e.directImpact.length>0?t.push("No tests found for impacted files - add test coverage"):e.impactedTests.length<e.directImpact.length/2&&t.push("Test coverage appears low for impacted files"),e.impactedTests.length>0&&(e.impactedTests.length<=10?t.push(`Run these ${e.impactedTests.length} tests: ${e.impactedTests.slice(0,3).join(", ")}${e.impactedTests.length>3?"...":""}`):t.push(`Run all ${e.impactedTests.length} impacted tests before deployment`));let i=[...e.directImpact,...e.transitiveImpact].filter(r=>this.isCriticalPath(r.file));i.length>0&&t.push(`${i.length} critical path files affected - extra scrutiny recommended`),e.transitiveImpact.length>10&&t.push("Large transitive impact - consider breaking down into smaller changes");let n=[...e.directImpact,...e.transitiveImpact].filter(r=>r.riskScore>=.7);return n.length>0&&t.push(`${n.length} high-risk files impacted: ${n.slice(0,2).map(r=>this.getFileName(r.file)).join(", ")}`),t}async analyzeDirectImpact(e){let t=[];for(let i of e){let n=await this.knowledgeGraph.mapDependencies({files:[i],direction:"incoming",depth:1});if(n.success){let{nodes:r,edges:l}=n.value;for(let s of r){if(s.path===i)continue;let c=l.find(o=>o.target===s.id||o.source===s.id),a=this.calculateFileRiskScore(s.path,s.inDegree,s.outDegree);t.push({file:s.path,reason:`Directly ${c?.type||"depends on"} ${this.getFileName(i)}`,distance:1,riskScore:a})}}}return this.deduplicateImpact(t)}async analyzeTransitiveImpact(e,t,i){let n=[],r=new Set([...e,...t.map(s=>s.file)]),l=t.map(s=>({file:s.file,distance:1}));for(;l.length>0;){let s=l.shift();if(s.distance>=i)continue;let c=await this.knowledgeGraph.mapDependencies({files:[s.file],direction:"incoming",depth:1});if(c.success)for(let a of c.value.nodes){if(r.has(a.path)||a.path===s.file)continue;r.add(a.path);let o=this.calculateFileRiskScore(a.path,a.inDegree,a.outDegree,s.distance+1);n.push({file:a.path,reason:`Transitively depends via ${this.getFileName(s.file)}`,distance:s.distance+1,riskScore:o}),l.push({file:a.path,distance:s.distance+1})}}return this.deduplicateImpact(n)}calculateFileRiskScore(e,t,i,n=1){let r=0;return r+=Math.min(.3,t/20),r+=Math.min(.2,i/30),this.isCriticalPath(e)&&(r+=.3),this.isEntryPoint(e)&&(r+=.2),r=r*Math.pow(.8,n-1),Math.min(1,Math.max(0,r))}calculateAverageRiskScore(e){return e.length===0?0:e.reduce((i,n)=>i+n.riskScore,0)/e.length}countCriticalFiles(e){return e.filter(t=>this.isCriticalPath(t)).length}isTestFile(e){return[/\.test\.[tj]sx?$/,/\.spec\.[tj]sx?$/,/_test\.[tj]sx?$/,/test_.*\.py$/,/.*_test\.py$/,/.*_test\.go$/].some(i=>i.test(e))}isCriticalPath(e){return this.config.criticalPaths.map(i=>i.replace(/\*\*/g,".*").replace(/\*/g,"[^/]*")).some(i=>new RegExp(i).test(e))}isEntryPoint(e){return[/\/index\.[tj]sx?$/,/\/main\.[tj]sx?$/,/\/app\.[tj]sx?$/,/^src\/[^/]+\.[tj]sx?$/,/\/server\.[tj]sx?$/,/\/__init__\.py$/,/\/main\.go$/].some(i=>i.test(e))}getBaseName(e){return this.getFileName(e).replace(/\.[^.]+$/,"")}getFileName(e){return e.split(/[/\\]/).pop()||e}deduplicateImpact(e){let t=new Map;for(let i of e){let n=t.get(i.file);(!n||i.distance<n.distance)&&t.set(i.file,i)}return Array.from(t.values()).sort((i,n)=>n.riskScore!==i.riskScore?n.riskScore-i.riskScore:i.distance-n.distance)}async storeAnalysis(e,t){let i=h();await this.memory.set(`${this.config.namespace}:analysis:${i}`,{id:i,changedFiles:e,analysis:t,timestamp:new Date().toISOString()},{namespace:this.config.namespace,persist:!0})}};export{u as a};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.19");process.exit(0)}
2
+ import{g}from"./chunk-FPVXXQVX.js";import{b as p,c as d}from"./chunk-N2PLNYEV.js";import{b as m,c as f}from"./chunk-5MGRZ4YD.js";import{i as h}from"./chunk-MIQAFOFO.js";f();var I={maxDepth:5,riskWeights:{directImpact:.4,transitiveImpact:.2,testCoverage:.2,criticalPath:.15,dependencyCount:.05},testPatterns:["**/*.test.ts","**/*.test.tsx","**/*.spec.ts","**/*.spec.tsx","**/test_*.py","**/*_test.py","**/*_test.go"],criticalPaths:["**/auth/**","**/security/**","**/payment/**","**/api/**","**/core/**"],namespace:"code-intelligence:impact"},u=class{constructor(e,t,i={}){this.memory=e;this.config={...I,...i},this.knowledgeGraph=t||new g(e)}memory;config;knowledgeGraph;async analyzeImpact(e){try{let{changedFiles:t,depth:i=this.config.maxDepth,includeTests:n=!0}=e;if(t.length===0)return p({directImpact:[],transitiveImpact:[],impactedTests:[],riskLevel:"info",recommendations:[]});let r=await this.analyzeDirectImpact(t),l=await this.analyzeTransitiveImpact(t,r,i),s=[];if(n){let a=await this.getImpactedTests(t);a.success&&(s=a.value)}let c={directImpact:r,transitiveImpact:l,impactedTests:s,riskLevel:"info",recommendations:[]};return c.riskLevel=this.calculateRiskLevel(c),c.recommendations=this.getRecommendations(c),await this.storeAnalysis(t,c),p(c)}catch(t){return d(m(t))}}async getImpactedTests(e){try{let t=new Set;for(let i of e){if(this.isTestFile(i)){t.add(i);continue}let n=await this.knowledgeGraph.mapDependencies({files:[i],direction:"incoming",depth:3});if(n.success)for(let s of n.value.nodes)this.isTestFile(s.path)&&t.add(s.path);let r=this.getBaseName(i),l=[`${r}.test`,`${r}.spec`,`test_${r}`,`${r}_test`];for(let s of l){let c=await this.memory.search(`code-intelligence:kg:node:*${s}*`,10);for(let a of c){let o=await this.memory.get(a);o?.properties?.path&&this.isTestFile(o.properties.path)&&t.add(o.properties.path)}}}return p(Array.from(t))}catch(t){return d(m(t))}}calculateRiskLevel(e){let t=this.config.riskWeights,i=0,n=Math.min(1,e.directImpact.length/10);i+=n*t.directImpact;let r=Math.min(1,e.transitiveImpact.length/20);i+=r*t.transitiveImpact;let l=e.impactedTests.length>0?Math.max(0,1-e.impactedTests.length/(e.directImpact.length||1)):1;i+=l*t.testCoverage;let s=this.countCriticalFiles([...e.directImpact.map(o=>o.file),...e.transitiveImpact.map(o=>o.file)]),c=Math.min(1,s/5);i+=c*t.criticalPath;let a=this.calculateAverageRiskScore([...e.directImpact,...e.transitiveImpact]);return i+=a*t.dependencyCount,i>=.8?"critical":i>=.6?"high":i>=.4?"medium":i>=.2?"low":"info"}getRecommendations(e){let t=[];(e.riskLevel==="critical"||e.riskLevel==="high")&&t.push("This change has significant impact - consider peer review before merging"),e.impactedTests.length===0&&e.directImpact.length>0?t.push("No tests found for impacted files - add test coverage"):e.impactedTests.length<e.directImpact.length/2&&t.push("Test coverage appears low for impacted files"),e.impactedTests.length>0&&(e.impactedTests.length<=10?t.push(`Run these ${e.impactedTests.length} tests: ${e.impactedTests.slice(0,3).join(", ")}${e.impactedTests.length>3?"...":""}`):t.push(`Run all ${e.impactedTests.length} impacted tests before deployment`));let i=[...e.directImpact,...e.transitiveImpact].filter(r=>this.isCriticalPath(r.file));i.length>0&&t.push(`${i.length} critical path files affected - extra scrutiny recommended`),e.transitiveImpact.length>10&&t.push("Large transitive impact - consider breaking down into smaller changes");let n=[...e.directImpact,...e.transitiveImpact].filter(r=>r.riskScore>=.7);return n.length>0&&t.push(`${n.length} high-risk files impacted: ${n.slice(0,2).map(r=>this.getFileName(r.file)).join(", ")}`),t}async analyzeDirectImpact(e){let t=[];for(let i of e){let n=await this.knowledgeGraph.mapDependencies({files:[i],direction:"incoming",depth:1});if(n.success){let{nodes:r,edges:l}=n.value;for(let s of r){if(s.path===i)continue;let c=l.find(o=>o.target===s.id||o.source===s.id),a=this.calculateFileRiskScore(s.path,s.inDegree,s.outDegree);t.push({file:s.path,reason:`Directly ${c?.type||"depends on"} ${this.getFileName(i)}`,distance:1,riskScore:a})}}}return this.deduplicateImpact(t)}async analyzeTransitiveImpact(e,t,i){let n=[],r=new Set([...e,...t.map(s=>s.file)]),l=t.map(s=>({file:s.file,distance:1}));for(;l.length>0;){let s=l.shift();if(s.distance>=i)continue;let c=await this.knowledgeGraph.mapDependencies({files:[s.file],direction:"incoming",depth:1});if(c.success)for(let a of c.value.nodes){if(r.has(a.path)||a.path===s.file)continue;r.add(a.path);let o=this.calculateFileRiskScore(a.path,a.inDegree,a.outDegree,s.distance+1);n.push({file:a.path,reason:`Transitively depends via ${this.getFileName(s.file)}`,distance:s.distance+1,riskScore:o}),l.push({file:a.path,distance:s.distance+1})}}return this.deduplicateImpact(n)}calculateFileRiskScore(e,t,i,n=1){let r=0;return r+=Math.min(.3,t/20),r+=Math.min(.2,i/30),this.isCriticalPath(e)&&(r+=.3),this.isEntryPoint(e)&&(r+=.2),r=r*Math.pow(.8,n-1),Math.min(1,Math.max(0,r))}calculateAverageRiskScore(e){return e.length===0?0:e.reduce((i,n)=>i+n.riskScore,0)/e.length}countCriticalFiles(e){return e.filter(t=>this.isCriticalPath(t)).length}isTestFile(e){return[/\.test\.[tj]sx?$/,/\.spec\.[tj]sx?$/,/_test\.[tj]sx?$/,/test_.*\.py$/,/.*_test\.py$/,/.*_test\.go$/].some(i=>i.test(e))}isCriticalPath(e){return this.config.criticalPaths.map(i=>i.replace(/\*\*/g,".*").replace(/\*/g,"[^/]*")).some(i=>new RegExp(i).test(e))}isEntryPoint(e){return[/\/index\.[tj]sx?$/,/\/main\.[tj]sx?$/,/\/app\.[tj]sx?$/,/^src\/[^/]+\.[tj]sx?$/,/\/server\.[tj]sx?$/,/\/__init__\.py$/,/\/main\.go$/].some(i=>i.test(e))}getBaseName(e){return this.getFileName(e).replace(/\.[^.]+$/,"")}getFileName(e){return e.split(/[/\\]/).pop()||e}deduplicateImpact(e){let t=new Map;for(let i of e){let n=t.get(i.file);(!n||i.distance<n.distance)&&t.set(i.file,i)}return Array.from(t.values()).sort((i,n)=>n.riskScore!==i.riskScore?n.riskScore-i.riskScore:i.distance-n.distance)}async storeAnalysis(e,t){let i=h();await this.memory.set(`${this.config.namespace}:analysis:${i}`,{id:i,changedFiles:e,analysis:t,timestamp:new Date().toISOString()},{namespace:this.config.namespace,persist:!0})}};export{u as a};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.18");process.exit(0)}
2
- import{c as u}from"./chunk-FKNYOKIK.js";function t(){return{...e}}function o(r){e={...e,...r}}function i(){e={...s}}function a(){return e.useBrowserMode}function E(){return e.useScreenshotCapture}function l(){return e.useVisualRegression}function c(){return e.useE2EExecution}function f(){return e.defaultHeadless}function d(){return e.useAutoRetry}function _(){return e.logPerformanceMetrics}function I(){return e.useAxeCore}function p(){let r={};process.env.VIBIUM_USE_BROWSER_MODE!==void 0&&(r.useBrowserMode=process.env.VIBIUM_USE_BROWSER_MODE==="true"),process.env.VIBIUM_USE_SCREENSHOT_CAPTURE!==void 0&&(r.useScreenshotCapture=process.env.VIBIUM_USE_SCREENSHOT_CAPTURE==="true"),process.env.VIBIUM_USE_VISUAL_REGRESSION!==void 0&&(r.useVisualRegression=process.env.VIBIUM_USE_VISUAL_REGRESSION==="true"),process.env.VIBIUM_USE_E2E_EXECUTION!==void 0&&(r.useE2EExecution=process.env.VIBIUM_USE_E2E_EXECUTION==="true"),process.env.VIBIUM_DEFAULT_HEADLESS!==void 0&&(r.defaultHeadless=process.env.VIBIUM_DEFAULT_HEADLESS==="true"),process.env.VIBIUM_USE_AUTO_RETRY!==void 0&&(r.useAutoRetry=process.env.VIBIUM_USE_AUTO_RETRY==="true"),process.env.VIBIUM_LOG_PERFORMANCE_METRICS!==void 0&&(r.logPerformanceMetrics=process.env.VIBIUM_LOG_PERFORMANCE_METRICS==="true"),process.env.VIBIUM_USE_AXE_CORE!==void 0&&(r.useAxeCore=process.env.VIBIUM_USE_AXE_CORE==="true"),o(r)}function U(){o({defaultHeadless:!0,useAutoRetry:!0,logPerformanceMetrics:!0})}function R(){o({defaultHeadless:!1,logPerformanceMetrics:!0})}function S(){o({useBrowserMode:!1,useScreenshotCapture:!1,useVisualRegression:!1,useE2EExecution:!1,useAxeCore:!1})}var s,e,n=u(()=>{s={useBrowserMode:!0,useScreenshotCapture:!0,useVisualRegression:!0,useE2EExecution:!0,defaultHeadless:!1,useAutoRetry:!0,logPerformanceMetrics:!0,useAxeCore:!0},e={...s}});export{s as a,t as b,o as c,i as d,a as e,E as f,l as g,c as h,f as i,d as j,_ as k,I as l,p as m,U as n,R as o,S as p,n as q};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.19");process.exit(0)}
2
+ import{c as u}from"./chunk-WULMXLNN.js";function t(){return{...e}}function o(r){e={...e,...r}}function i(){e={...s}}function a(){return e.useBrowserMode}function E(){return e.useScreenshotCapture}function l(){return e.useVisualRegression}function c(){return e.useE2EExecution}function f(){return e.defaultHeadless}function d(){return e.useAutoRetry}function _(){return e.logPerformanceMetrics}function I(){return e.useAxeCore}function p(){let r={};process.env.VIBIUM_USE_BROWSER_MODE!==void 0&&(r.useBrowserMode=process.env.VIBIUM_USE_BROWSER_MODE==="true"),process.env.VIBIUM_USE_SCREENSHOT_CAPTURE!==void 0&&(r.useScreenshotCapture=process.env.VIBIUM_USE_SCREENSHOT_CAPTURE==="true"),process.env.VIBIUM_USE_VISUAL_REGRESSION!==void 0&&(r.useVisualRegression=process.env.VIBIUM_USE_VISUAL_REGRESSION==="true"),process.env.VIBIUM_USE_E2E_EXECUTION!==void 0&&(r.useE2EExecution=process.env.VIBIUM_USE_E2E_EXECUTION==="true"),process.env.VIBIUM_DEFAULT_HEADLESS!==void 0&&(r.defaultHeadless=process.env.VIBIUM_DEFAULT_HEADLESS==="true"),process.env.VIBIUM_USE_AUTO_RETRY!==void 0&&(r.useAutoRetry=process.env.VIBIUM_USE_AUTO_RETRY==="true"),process.env.VIBIUM_LOG_PERFORMANCE_METRICS!==void 0&&(r.logPerformanceMetrics=process.env.VIBIUM_LOG_PERFORMANCE_METRICS==="true"),process.env.VIBIUM_USE_AXE_CORE!==void 0&&(r.useAxeCore=process.env.VIBIUM_USE_AXE_CORE==="true"),o(r)}function U(){o({defaultHeadless:!0,useAutoRetry:!0,logPerformanceMetrics:!0})}function R(){o({defaultHeadless:!1,logPerformanceMetrics:!0})}function S(){o({useBrowserMode:!1,useScreenshotCapture:!1,useVisualRegression:!1,useE2EExecution:!1,useAxeCore:!1})}var s,e,n=u(()=>{s={useBrowserMode:!0,useScreenshotCapture:!0,useVisualRegression:!0,useE2EExecution:!0,defaultHeadless:!1,useAutoRetry:!0,logPerformanceMetrics:!0,useAxeCore:!0},e={...s}});export{s as a,t as b,o as c,i as d,a as e,E as f,l as g,c as h,f as i,d as j,_ as k,I as l,p as m,U as n,R as o,S as p,n as q};