agentic-qe 3.9.14 → 3.9.15

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 (298) hide show
  1. package/.claude/skills/accessibility-testing/SKILL.md +18 -0
  2. package/.claude/skills/enterprise-integration-testing/SKILL.md +1 -1
  3. package/.claude/skills/pentest-validation/SKILL.md +1 -1
  4. package/.claude/skills/qe-browser/evals/qe-browser.yaml +46 -63
  5. package/.claude/skills/qe-browser/scripts/smoke-test.sh +16 -4
  6. package/.claude/skills/skills-manifest.json +1 -1
  7. package/CHANGELOG.md +27 -0
  8. package/assets/skills/accessibility-testing/SKILL.md +18 -0
  9. package/assets/skills/qe-browser/evals/qe-browser.yaml +46 -63
  10. package/assets/skills/qe-browser/scripts/smoke-test.sh +16 -4
  11. package/assets/skills/skills-manifest.json +1 -1
  12. package/dist/cli/bundle.js +5 -5
  13. package/dist/cli/chunks/adapter-P2EPBJLF.js +2 -0
  14. package/dist/cli/chunks/{agent-booster-wasm-O6EXMPMF.js → agent-booster-wasm-NA2VN5U2.js} +2 -2
  15. package/dist/cli/chunks/{agent-handler-4LPJVTJU.js → agent-handler-NRIF5IOC.js} +2 -2
  16. package/dist/cli/chunks/{agent-memory-branch-PRR323JZ.js → agent-memory-branch-NW3UB2UW.js} +2 -2
  17. package/dist/cli/chunks/aqe-learning-engine-6UITO3NJ.js +2 -0
  18. package/dist/cli/chunks/{audit-YCKXQOXD.js → audit-5CSEDVJR.js} +2 -2
  19. package/dist/cli/chunks/base-JHBJXVGP.js +2 -0
  20. package/dist/cli/chunks/{better-sqlite3-44RIH62G.js → better-sqlite3-FZ32SHZ6.js} +2 -2
  21. package/dist/cli/chunks/{brain-handler-IAYJBAFL.js → brain-handler-ISVST4MR.js} +3 -3
  22. package/dist/cli/chunks/{branch-enumerator-RVVS2UYR.js → branch-enumerator-IUHWHIMV.js} +2 -2
  23. package/dist/cli/chunks/{browser-L6IKC4PR.js → browser-D4F3327X.js} +2 -2
  24. package/dist/cli/chunks/browser-workflow-U4OON5DZ.js +2 -0
  25. package/dist/cli/chunks/{chunk-WE7KIXR6.js → chunk-2BBKAX7X.js} +2 -2
  26. package/dist/cli/chunks/{chunk-DNFDSDKE.js → chunk-2CN2NPJQ.js} +2 -2
  27. package/dist/cli/chunks/{chunk-QLWP7ZIT.js → chunk-2L5ZFBHP.js} +2 -2
  28. package/dist/cli/chunks/{chunk-DMZ2XOEW.js → chunk-2XW36KDQ.js} +2 -2
  29. package/dist/cli/chunks/{chunk-HEQ23HBE.js → chunk-37ZSWRRP.js} +2 -2
  30. package/dist/cli/chunks/{chunk-SY74WSBN.js → chunk-3BA2FGSA.js} +2 -2
  31. package/dist/cli/chunks/{chunk-MXIFVOYA.js → chunk-3FUKJT4S.js} +2 -2
  32. package/dist/cli/chunks/{chunk-YPMBD44A.js → chunk-3NIHJIWP.js} +2 -2
  33. package/dist/cli/chunks/{chunk-3GIZRGX6.js → chunk-3RSPEFU3.js} +2 -2
  34. package/dist/cli/chunks/{chunk-M2RO34V7.js → chunk-3Y4YZDHJ.js} +4 -4
  35. package/dist/cli/chunks/{chunk-LKGLKX2A.js → chunk-4M7RBSW6.js} +2 -2
  36. package/dist/cli/chunks/{chunk-5U6M4XCP.js → chunk-4T36OQUK.js} +3 -3
  37. package/dist/cli/chunks/{chunk-ME4LVBTT.js → chunk-56YHSI6R.js} +2 -2
  38. package/dist/cli/chunks/{chunk-S2KGZJHS.js → chunk-62MVVEGH.js} +1 -1
  39. package/dist/cli/chunks/{chunk-MFGYMNNY.js → chunk-65QA7MYW.js} +2 -2
  40. package/dist/cli/chunks/{chunk-4EQWK6P6.js → chunk-6AMD4PZB.js} +2 -2
  41. package/dist/cli/chunks/{chunk-J5YOXLBD.js → chunk-6BHAGCZD.js} +1 -1
  42. package/dist/cli/chunks/{chunk-6J6GXRHX.js → chunk-6F3H2C5H.js} +3 -3
  43. package/dist/cli/chunks/{chunk-J3XLOHWB.js → chunk-6OEGZSRK.js} +2 -2
  44. package/dist/cli/chunks/{chunk-5MWNXDQW.js → chunk-6TOUMCSE.js} +2 -2
  45. package/dist/cli/chunks/{chunk-KFAN5FZM.js → chunk-6Z7LYE2B.js} +2 -2
  46. package/dist/cli/chunks/{chunk-KJB6JJXT.js → chunk-7J5KWUC2.js} +1 -1
  47. package/dist/cli/chunks/{chunk-IH4OOAEP.js → chunk-7ZPNQ3T6.js} +1 -1
  48. package/dist/cli/chunks/{chunk-KHUFPJE4.js → chunk-AE65B2ZE.js} +2 -2
  49. package/dist/cli/chunks/{chunk-BNPJMPM3.js → chunk-AVKUFN3C.js} +2 -2
  50. package/dist/cli/chunks/{chunk-3ZKTPPIC.js → chunk-B4BOOOYM.js} +1 -1
  51. package/dist/cli/chunks/{chunk-A2TK52B2.js → chunk-BGUCXJEJ.js} +2 -2
  52. package/dist/cli/chunks/{chunk-TOSFK4VG.js → chunk-C5BRTU4V.js} +1 -1
  53. package/dist/cli/chunks/{chunk-BFCMOMOF.js → chunk-CF3W34BA.js} +1 -1
  54. package/dist/cli/chunks/{chunk-RQFC7Q33.js → chunk-CSB2M7IX.js} +2 -2
  55. package/dist/cli/chunks/{chunk-DGUAAG3T.js → chunk-CUQBOVRP.js} +1 -1
  56. package/dist/cli/chunks/{chunk-KVN4FTPT.js → chunk-CWWUBZNX.js} +2 -2
  57. package/dist/cli/chunks/{chunk-VEAVDXXT.js → chunk-D32YCVCA.js} +2 -2
  58. package/dist/cli/chunks/{chunk-ORHCO2I7.js → chunk-D3FV5NNA.js} +2 -2
  59. package/dist/cli/chunks/{chunk-JNLKLC7G.js → chunk-D3ZUSXFY.js} +2 -2
  60. package/dist/cli/chunks/{chunk-IOHDE27P.js → chunk-DATFN5DG.js} +2 -2
  61. package/dist/cli/chunks/{chunk-ZCRLZINE.js → chunk-DPEG44BS.js} +2 -2
  62. package/dist/cli/chunks/{chunk-GIUAY4KY.js → chunk-DYQ7HTEU.js} +3 -3
  63. package/dist/cli/chunks/{chunk-WUYJYRBY.js → chunk-E3EDVRB5.js} +1 -1
  64. package/dist/cli/chunks/{chunk-JOGKQTCU.js → chunk-ELLNKP3I.js} +3 -3
  65. package/dist/cli/chunks/{chunk-Q4DAYLH4.js → chunk-EORSYD66.js} +2 -2
  66. package/dist/cli/chunks/{chunk-GALNZTYE.js → chunk-ESQSX37W.js} +2 -2
  67. package/dist/cli/chunks/{chunk-ERMIIRYN.js → chunk-EY2DGYQX.js} +1 -1
  68. package/dist/cli/chunks/chunk-FEVTMHO6.js +2 -0
  69. package/dist/cli/chunks/{chunk-3PZ2QLLR.js → chunk-FSOY2XB4.js} +3 -3
  70. package/dist/cli/chunks/{chunk-PZF5ISGS.js → chunk-FW6QBTPE.js} +1 -1
  71. package/dist/cli/chunks/{chunk-ZU5VHW6P.js → chunk-G3FUOFXA.js} +2 -2
  72. package/dist/cli/chunks/{chunk-JWR3NNFA.js → chunk-GHEO5YVA.js} +1 -1
  73. package/dist/cli/chunks/{chunk-7732TLNA.js → chunk-GLJ6CJNY.js} +2 -2
  74. package/dist/cli/chunks/{chunk-L4IWZXSC.js → chunk-GWUO3RY5.js} +1 -1
  75. package/dist/cli/chunks/{chunk-BOMJHE4I.js → chunk-H6DAP4KS.js} +2 -2
  76. package/dist/cli/chunks/{chunk-6EZY2QVM.js → chunk-HJNFBJT5.js} +8 -8
  77. package/dist/cli/chunks/{chunk-I3P5RZX7.js → chunk-HNAQNAGI.js} +3 -3
  78. package/dist/cli/chunks/{chunk-Z3PSKGBO.js → chunk-HPY7HGVQ.js} +2 -2
  79. package/dist/cli/chunks/{chunk-OGLS6HB4.js → chunk-HWK27KJK.js} +1 -1
  80. package/dist/cli/chunks/{chunk-2L3BCZ2F.js → chunk-ICXWXO5P.js} +1 -1
  81. package/dist/cli/chunks/{chunk-6BK2S2WE.js → chunk-IHDW4HW7.js} +2 -2
  82. package/dist/cli/chunks/{chunk-NWZYULZE.js → chunk-II5KTTIS.js} +4 -4
  83. package/dist/cli/chunks/{chunk-VUS4VRPQ.js → chunk-IMLH32AG.js} +2 -2
  84. package/dist/cli/chunks/{chunk-S6SM7LJK.js → chunk-IPTGPCEL.js} +2 -2
  85. package/dist/cli/chunks/{chunk-JLBUS4PR.js → chunk-IPVKVPAF.js} +2 -2
  86. package/dist/cli/chunks/{chunk-FNKKENLS.js → chunk-ISNXE6TP.js} +2 -2
  87. package/dist/cli/chunks/{chunk-LWHM5BWD.js → chunk-JAIIPEE6.js} +2 -2
  88. package/dist/cli/chunks/{chunk-UIYK4Y7K.js → chunk-JJDHD7SC.js} +2 -2
  89. package/dist/cli/chunks/{chunk-VDGWDDBC.js → chunk-JQRR37YY.js} +2 -2
  90. package/dist/cli/chunks/{chunk-DD4T7ZUM.js → chunk-KJTXY3DW.js} +1 -1
  91. package/dist/cli/chunks/{chunk-UUVTLYUK.js → chunk-KKBSX43Q.js} +2 -2
  92. package/dist/cli/chunks/{chunk-ZFZX2NA3.js → chunk-LLVS3UYZ.js} +2 -2
  93. package/dist/cli/chunks/{chunk-3NUMJB3U.js → chunk-LNUWNRRJ.js} +9 -9
  94. package/dist/cli/chunks/{chunk-G7L5Y47C.js → chunk-MBDX4OHD.js} +1 -1
  95. package/dist/cli/chunks/{chunk-P5YSBYZV.js → chunk-MHL6CPGY.js} +1 -1
  96. package/dist/cli/chunks/{chunk-VQB5SLXZ.js → chunk-MO4Q5ZGE.js} +2 -2
  97. package/dist/cli/chunks/{chunk-XNXOW7BQ.js → chunk-MS6T4VCU.js} +2 -2
  98. package/dist/cli/chunks/chunk-N2RPLPVG.js +18 -0
  99. package/dist/cli/chunks/{chunk-AEQMQVDJ.js → chunk-NL2PQLRD.js} +2 -2
  100. package/dist/cli/chunks/{chunk-PFSSI3YR.js → chunk-NWMYV7KG.js} +2 -2
  101. package/dist/cli/chunks/{chunk-G2KQUEGY.js → chunk-O6CHLZYT.js} +2 -2
  102. package/dist/cli/chunks/{chunk-VU4QET3C.js → chunk-O6J7MKRV.js} +2 -2
  103. package/dist/cli/chunks/{chunk-IL3ESNHA.js → chunk-OBZMQFWG.js} +3 -3
  104. package/dist/cli/chunks/{chunk-CGC63MGF.js → chunk-OHESV6I3.js} +4 -4
  105. package/dist/cli/chunks/{chunk-OZBTC26R.js → chunk-OMTYOIOS.js} +2 -2
  106. package/dist/cli/chunks/{chunk-5DWTU2PN.js → chunk-ORKGVVXK.js} +1 -1
  107. package/dist/cli/chunks/{chunk-UG2J5MTY.js → chunk-OUP2X3LT.js} +1 -1
  108. package/dist/cli/chunks/{chunk-GOTVYSX5.js → chunk-PSOIVDD2.js} +3 -3
  109. package/dist/cli/chunks/{chunk-FWI7PK4X.js → chunk-Q3E6Z2RQ.js} +1 -1
  110. package/dist/cli/chunks/{chunk-FFACJODG.js → chunk-Q3GDSFGA.js} +2 -2
  111. package/dist/cli/chunks/{chunk-TJOZPPZR.js → chunk-QNLZKD7E.js} +2 -2
  112. package/dist/cli/chunks/{chunk-WVN4YJSF.js → chunk-R4G64UH3.js} +1 -1
  113. package/dist/cli/chunks/{chunk-WELNFHDN.js → chunk-REUGPZIA.js} +1 -1
  114. package/dist/cli/chunks/{chunk-D6APBW66.js → chunk-RODJK6G6.js} +1 -1
  115. package/dist/cli/chunks/{chunk-AOYN6XYJ.js → chunk-RPOW5LWO.js} +1 -1
  116. package/dist/cli/chunks/{chunk-YZBY4ZRF.js → chunk-RSOOENGE.js} +2 -2
  117. package/dist/cli/chunks/{chunk-4JYLXYAH.js → chunk-RTVD7SZQ.js} +1 -1
  118. package/dist/cli/chunks/{chunk-QUK34CSU.js → chunk-RWVFOXYM.js} +1 -1
  119. package/dist/cli/chunks/{chunk-SUXUCW5I.js → chunk-SSQ42GI7.js} +2 -2
  120. package/dist/cli/chunks/{chunk-7IJBZGZY.js → chunk-SXUX6PTE.js} +1 -1
  121. package/dist/cli/chunks/{chunk-HJJTLOWZ.js → chunk-TJDAXI6E.js} +2 -2
  122. package/dist/cli/chunks/{chunk-AHVUILGE.js → chunk-TZWCVGG2.js} +1 -1
  123. package/dist/cli/chunks/{chunk-WSZVSDD5.js → chunk-U4WDJPRL.js} +2 -2
  124. package/dist/cli/chunks/{chunk-GM5LIYLQ.js → chunk-UZOFXYNC.js} +2 -2
  125. package/dist/cli/chunks/{chunk-NWGIQCCO.js → chunk-V65DK6ZZ.js} +1 -1
  126. package/dist/cli/chunks/{chunk-Y3X5OS5F.js → chunk-V6QARSVQ.js} +2 -2
  127. package/dist/cli/chunks/{chunk-LJ3WQIBN.js → chunk-V775NJOM.js} +1 -1
  128. package/dist/cli/chunks/{chunk-FYBTGEOV.js → chunk-VBEVZUQW.js} +1 -1
  129. package/dist/cli/chunks/{chunk-6GKXC6DE.js → chunk-VDDQSW4L.js} +2 -2
  130. package/dist/cli/chunks/{chunk-VVKENR4I.js → chunk-W4PUKTBF.js} +1 -1
  131. package/dist/cli/chunks/{chunk-XH774Q6Z.js → chunk-WAQ3U4FC.js} +1 -1
  132. package/dist/cli/chunks/{chunk-I5U64MHU.js → chunk-WCOJGDGO.js} +2 -2
  133. package/dist/cli/chunks/{chunk-JN7MSUGK.js → chunk-WI6UA5HV.js} +2 -2
  134. package/dist/cli/chunks/{chunk-GUEK5DOK.js → chunk-XALB3KRR.js} +2 -2
  135. package/dist/cli/chunks/{chunk-5HUAD4UU.js → chunk-XXRDI53H.js} +2 -2
  136. package/dist/cli/chunks/{chunk-DJLRRCR6.js → chunk-YCYFUYCE.js} +2 -2
  137. package/dist/cli/chunks/{chunk-4RDTR2OF.js → chunk-ZHTCZGML.js} +2 -2
  138. package/dist/cli/chunks/{chunk-36YZ2UF7.js → chunk-ZOAPOVYW.js} +2 -2
  139. package/dist/cli/chunks/{chunk-UAAJ3BSW.js → chunk-ZSC7NHK3.js} +2 -2
  140. package/dist/cli/chunks/{ci-QQ4F5TYO.js → ci-BGUUHDUS.js} +2 -2
  141. package/dist/cli/chunks/{ci-output-QC4WRENA.js → ci-output-CDFRGBNU.js} +2 -2
  142. package/dist/cli/chunks/{circuit-breaker-HFQUNYTK.js → circuit-breaker-S3NFX6RQ.js} +2 -2
  143. package/dist/cli/chunks/{claude-flow-setup-XNSCWIUN.js → claude-flow-setup-AJIPJFMC.js} +2 -2
  144. package/dist/cli/chunks/client-UHHMKUPF.js +2 -0
  145. package/dist/cli/chunks/{cline-installer-S3CECBYL.js → cline-installer-6O4KZ5UH.js} +2 -2
  146. package/dist/cli/chunks/{code-QHUELDUH.js → code-IZALXUL5.js} +2 -2
  147. package/dist/cli/chunks/{code-index-extractor-QLA5EQTE.js → code-index-extractor-N7VDH4XF.js} +2 -2
  148. package/dist/cli/chunks/{codex-installer-CQ7JNNOA.js → codex-installer-35GTWCFJ.js} +2 -2
  149. package/dist/cli/chunks/{completions-S33U3KIT.js → completions-XPJFHGG2.js} +2 -2
  150. package/dist/cli/chunks/{complexity-analyzer-J7IEW3EM.js → complexity-analyzer-DNLCJGUJ.js} +2 -2
  151. package/dist/cli/chunks/{continuedev-installer-DVU24D37.js → continuedev-installer-PXAIKNYO.js} +2 -2
  152. package/dist/cli/chunks/{copilot-installer-DYISOPBC.js → copilot-installer-2TQ5IZNY.js} +2 -2
  153. package/dist/cli/chunks/{cost-tracker-URJADKKS.js → cost-tracker-A5XH4W6S.js} +2 -2
  154. package/dist/cli/chunks/{coverage-NGMKJNW6.js → coverage-EPIMXTLW.js} +3 -3
  155. package/dist/cli/chunks/cross-domain-router-GEBXTPZW.js +2 -0
  156. package/dist/cli/chunks/{cursor-installer-DFBJRDSY.js → cursor-installer-WMMRPW44.js} +2 -2
  157. package/dist/cli/chunks/{daemon-JSKKVVCV.js → daemon-55DSODOH.js} +3 -3
  158. package/dist/cli/chunks/{dag-attention-scheduler-YITFS6MR.js → dag-attention-scheduler-5DSWXMMK.js} +2 -2
  159. package/dist/cli/chunks/{detect-5APZP2D3.js → detect-NOS46AWN.js} +2 -2
  160. package/dist/cli/chunks/{domain-handler-WHH6XPSZ.js → domain-handler-BFRNU6S3.js} +2 -2
  161. package/dist/cli/chunks/{domain-transfer-SERX53SS.js → domain-transfer-BPSA4HFR.js} +2 -2
  162. package/dist/cli/chunks/dream-XBRGYPBC.js +2 -0
  163. package/dist/cli/chunks/esm-node-EV4HOHTZ.js +2 -0
  164. package/dist/cli/chunks/eval-YDLM23FB.js +15 -0
  165. package/dist/cli/chunks/{fast-paths-4MSOOJVK.js → fast-paths-GISZ7HBO.js} +2 -2
  166. package/dist/cli/chunks/{feature-flags-WJT57IEJ.js → feature-flags-3FLJF6CQ.js} +2 -2
  167. package/dist/cli/chunks/{feature-flags-564YFR65.js → feature-flags-5WGZLUPQ.js} +2 -2
  168. package/dist/cli/chunks/{file-discovery-5QVG65WF.js → file-discovery-PPHUMFSI.js} +2 -2
  169. package/dist/cli/chunks/{fleet-CF5JRK5B.js → fleet-LHFZ53FS.js} +3 -3
  170. package/dist/cli/chunks/{gnn-wrapper-NYQ77563.js → gnn-wrapper-Z45DRWGI.js} +2 -2
  171. package/dist/cli/chunks/{heartbeat-handler-42QJPKHE.js → heartbeat-handler-VMLJ5PDH.js} +4 -4
  172. package/dist/cli/chunks/{heartbeat-scheduler-7XEAV74Y.js → heartbeat-scheduler-GUWYDHEY.js} +2 -2
  173. package/dist/cli/chunks/hnsw-adapter-BG73YVXI.js +2 -0
  174. package/dist/cli/chunks/hnsw-index-K73ZTLJN.js +2 -0
  175. package/dist/cli/chunks/{hnsw-legacy-bridge-ZRR6PGWN.js → hnsw-legacy-bridge-S7UZWDUP.js} +2 -2
  176. package/dist/cli/chunks/{hnswlib-node-DY7NOW76.js → hnswlib-node-MIAAS7OI.js} +2 -2
  177. package/dist/cli/chunks/{hooks-IRRHEJLR.js → hooks-ZN4FV5XS.js} +6 -6
  178. package/dist/cli/chunks/{hybrid-router-S4JXJLUY.js → hybrid-router-Y6LBFPL7.js} +2 -2
  179. package/dist/cli/chunks/{hypergraph-engine-WFHZJMP2.js → hypergraph-engine-KK73LZYZ.js} +2 -2
  180. package/dist/cli/chunks/{hypergraph-handler-LHUKR7PT.js → hypergraph-handler-OBGDPIWG.js} +3 -3
  181. package/dist/cli/chunks/impact-analyzer-GWIUYYCQ.js +2 -0
  182. package/dist/cli/chunks/{init-handler-ZBIW7PSB.js → init-handler-JJJ7VHM4.js} +6 -6
  183. package/dist/cli/chunks/init-wizard-RIJJAKE3.js +2 -0
  184. package/dist/cli/chunks/kernel-SIPBCRGL.js +2 -0
  185. package/dist/cli/chunks/{kilocode-installer-JYHA4NW7.js → kilocode-installer-EF6DPX2D.js} +2 -2
  186. package/dist/cli/chunks/{kiro-installer-OBXTRK77.js → kiro-installer-SG74CEVO.js} +2 -2
  187. package/dist/cli/chunks/knowledge-graph-NOYZXHIG.js +2 -0
  188. package/dist/cli/chunks/{learning-OAEJHEJD.js → learning-LVWYMHF6.js} +3 -3
  189. package/dist/cli/chunks/{llm-router-NNEOZAVB.js → llm-router-QFK7MNPY.js} +4 -4
  190. package/dist/cli/chunks/{load-WIKLBESW.js → load-6XPV4WA2.js} +2 -2
  191. package/dist/cli/chunks/load-test-DIMUH75F.js +2 -0
  192. package/dist/cli/chunks/{mcp-KR43GFGP.js → mcp-GZXOPYMH.js} +2 -2
  193. package/dist/cli/chunks/{memory-KQIYKAYU.js → memory-QTE2Z5HU.js} +5 -5
  194. package/dist/cli/chunks/memory-backend-IWOGO4BV.js +2 -0
  195. package/dist/cli/chunks/{memory-handlers-LAI4AO4O.js → memory-handlers-PC4P4YEF.js} +2 -2
  196. package/dist/cli/chunks/{multi-model-executor-NPS3VOAR.js → multi-model-executor-FZOPSUOT.js} +2 -2
  197. package/dist/cli/chunks/{opencode-installer-FE475WME.js → opencode-installer-CITDTCUQ.js} +2 -2
  198. package/dist/cli/chunks/{orchestrator-MW4MZ3RW.js → orchestrator-ZTG7MFHQ.js} +20 -20
  199. package/dist/cli/chunks/{pipeline-R2TGZSUA.js → pipeline-QXO4EJP4.js} +2 -2
  200. package/dist/cli/chunks/{platform-N2GZBCBP.js → platform-JJEDYCAK.js} +2 -2
  201. package/dist/cli/chunks/{plugin-V2AQF23V.js → plugin-ZEKRM6F7.js} +2 -2
  202. package/dist/cli/chunks/{prime-radiant-advanced-wasm-ZQSYRLRS.js → prime-radiant-advanced-wasm-GRS4T6LR.js} +2 -2
  203. package/dist/cli/chunks/protocol-executor-NT4TILJW.js +2 -0
  204. package/dist/cli/chunks/{protocol-handler-V3U724F2.js → protocol-handler-KWI2T6OR.js} +2 -2
  205. package/dist/cli/chunks/{prove-NCH56HZB.js → prove-7FJN2HEH.js} +2 -2
  206. package/dist/cli/chunks/{provider-manager-7NUHS3T5.js → provider-manager-QYYZZLLO.js} +2 -2
  207. package/dist/cli/chunks/qe-reasoning-bank-VDROHXFS.js +2 -0
  208. package/dist/cli/chunks/{quality-J3IVPPPW.js → quality-4NHO2NY5.js} +2 -2
  209. package/dist/cli/chunks/queen-coordinator-7LO73IV3.js +2 -0
  210. package/dist/cli/chunks/{real-embeddings-VURZXAEY.js → real-embeddings-SIELAOWX.js} +2 -2
  211. package/dist/cli/chunks/{roocode-installer-STWFJGMR.js → roocode-installer-ANYXH3NR.js} +2 -2
  212. package/dist/cli/chunks/router-SFVOLN2W.js +2 -0
  213. package/dist/cli/chunks/routing-feedback-MRFV7WUZ.js +2 -0
  214. package/dist/cli/chunks/{routing-handler-6GZT7EXM.js → routing-handler-6QQHK4KV.js} +2 -2
  215. package/dist/cli/chunks/{ruvector-commands-LCPAH6WH.js → ruvector-commands-YEUA3MZB.js} +2 -2
  216. package/dist/cli/chunks/{rvf-dual-writer-76LWFT5X.js → rvf-dual-writer-UJFRHPVE.js} +2 -2
  217. package/dist/cli/chunks/{rvf-migration-adapter-G7KFWJKY.js → rvf-migration-adapter-CSDFG7UA.js} +2 -2
  218. package/dist/cli/chunks/{rvf-migration-coordinator-3DXOUPWF.js → rvf-migration-coordinator-QO7OENQF.js} +2 -2
  219. package/dist/cli/chunks/rvf-native-adapter-6L7FZZC7.js +2 -0
  220. package/dist/cli/chunks/safe-db-PYWBVGOV.js +2 -0
  221. package/dist/cli/chunks/schedule-BUQU75HY.js +2 -0
  222. package/dist/cli/chunks/scheduler-XOSKWZO2.js +2 -0
  223. package/dist/cli/chunks/{security-XDBPYA5T.js → security-QCIUC5FX.js} +3 -3
  224. package/dist/cli/chunks/shared-rvf-adapter-OZ7S4ZQL.js +2 -0
  225. package/dist/cli/chunks/{shared-rvf-dual-writer-UGXTS2XI.js → shared-rvf-dual-writer-LVJJS3PD.js} +2 -2
  226. package/dist/cli/chunks/sqlite-persistence-7UXQZ5Y6.js +2 -0
  227. package/dist/cli/chunks/{status-handler-ZLXES3QL.js → status-handler-O77A4JWM.js} +2 -2
  228. package/dist/cli/chunks/{structural-health-4PFCOQ7T.js → structural-health-WIIBIIQI.js} +2 -2
  229. package/dist/cli/chunks/{sync-3DROIEZN.js → sync-UN6D6OF2.js} +2 -2
  230. package/dist/cli/chunks/{task-handler-4UGZ5VIE.js → task-handler-RBOSMJCK.js} +2 -2
  231. package/dist/cli/chunks/{task-handlers-I5VVBTWI.js → task-handlers-VWMXQKAT.js} +2 -2
  232. package/dist/cli/chunks/{test-Z2MM7O5A.js → test-XK5M3PGT.js} +4 -4
  233. package/dist/cli/chunks/{test-scheduling-AP76GKN5.js → test-scheduling-CTQ3JJ7G.js} +3 -3
  234. package/dist/cli/chunks/{token-bootstrap-P54N6PZV.js → token-bootstrap-D5CQ3I5M.js} +2 -2
  235. package/dist/cli/chunks/{token-usage-AXAZTPA6.js → token-usage-L4QSLWQ5.js} +2 -2
  236. package/dist/cli/chunks/{transformers-VOZ2Z7FS.js → transformers-SRPJDBKA.js} +2 -2
  237. package/dist/cli/chunks/{tree-sitter-wasm-parser-IYKLBTXB.js → tree-sitter-wasm-parser-DOU5ITWB.js} +2 -2
  238. package/dist/cli/chunks/{types-TKDH5EBW.js → types-LECYZUBN.js} +2 -2
  239. package/dist/cli/chunks/unified-memory-L6735TFM.js +2 -0
  240. package/dist/cli/chunks/unified-memory-hnsw-7TZNEDGY.js +2 -0
  241. package/dist/cli/chunks/unified-persistence-FNYZ3C2B.js +2 -0
  242. package/dist/cli/chunks/{validate-ZGF5FVZE.js → validate-SIKNIS6B.js} +2 -2
  243. package/dist/cli/chunks/{validate-swarm-OPWWUWYA.js → validate-swarm-EHAMMILJ.js} +2 -2
  244. package/dist/cli/chunks/{vibium-HEQUGRKJ.js → vibium-LJ4NYXMZ.js} +2 -2
  245. package/dist/cli/chunks/visual-security-SMPZPDY4.js +2 -0
  246. package/dist/cli/chunks/{web-tree-sitter-JZ7JCJJR.js → web-tree-sitter-DZQ3T4JD.js} +2 -2
  247. package/dist/cli/chunks/{windsurf-installer-2SGRCS6C.js → windsurf-installer-U6Z73O6J.js} +2 -2
  248. package/dist/cli/chunks/witness-chain-FNCOTWFA.js +2 -0
  249. package/dist/cli/chunks/{witness-chain-LJUYOCB5.js → witness-chain-JE3QU4YP.js} +2 -2
  250. package/dist/cli/chunks/{workflow-QORI3KO7.js → workflow-62QXGZQO.js} +4 -4
  251. package/dist/cli/chunks/workflow-orchestrator-RCR4N7OA.js +2 -0
  252. package/dist/cli/chunks/{wrappers-3NR7LNB5.js → wrappers-CAX5EZSH.js} +2 -2
  253. package/dist/cli/commands/eval.js +86 -0
  254. package/dist/init/browser-engine-installer.d.ts +60 -1
  255. package/dist/init/browser-engine-installer.js +73 -3
  256. package/dist/init/phases/09-assets.js +9 -2
  257. package/dist/mcp/bundle.js +1 -1
  258. package/dist/validation/command-eval-runner.d.ts +154 -0
  259. package/dist/validation/command-eval-runner.js +293 -0
  260. package/dist/validation/index.d.ts +2 -0
  261. package/dist/validation/index.js +4 -0
  262. package/package.json +1 -1
  263. package/dist/cli/chunks/adapter-W2EM7ZQ7.js +0 -2
  264. package/dist/cli/chunks/aqe-learning-engine-JQMPNHQU.js +0 -2
  265. package/dist/cli/chunks/base-EOPYE6JR.js +0 -2
  266. package/dist/cli/chunks/browser-workflow-CSARLAJD.js +0 -2
  267. package/dist/cli/chunks/chunk-53KLVMAT.js +0 -18
  268. package/dist/cli/chunks/chunk-STYNOKOM.js +0 -2
  269. package/dist/cli/chunks/client-3GECKJWB.js +0 -2
  270. package/dist/cli/chunks/cross-domain-router-UYONX76U.js +0 -2
  271. package/dist/cli/chunks/dream-Z5QDQJSM.js +0 -2
  272. package/dist/cli/chunks/esm-node-FOI5Y3O2.js +0 -2
  273. package/dist/cli/chunks/eval-FM3BLVFO.js +0 -15
  274. package/dist/cli/chunks/hnsw-adapter-NOAQ76QF.js +0 -2
  275. package/dist/cli/chunks/hnsw-index-KDIZQRSB.js +0 -2
  276. package/dist/cli/chunks/impact-analyzer-VDXJBWFG.js +0 -2
  277. package/dist/cli/chunks/init-wizard-Q6DEACKX.js +0 -2
  278. package/dist/cli/chunks/kernel-YNQOGTM5.js +0 -2
  279. package/dist/cli/chunks/knowledge-graph-GOZG3YOM.js +0 -2
  280. package/dist/cli/chunks/load-test-UJLTMPXW.js +0 -2
  281. package/dist/cli/chunks/memory-backend-WJH6XER3.js +0 -2
  282. package/dist/cli/chunks/protocol-executor-LYYYHXAX.js +0 -2
  283. package/dist/cli/chunks/qe-reasoning-bank-JK4UKLYY.js +0 -2
  284. package/dist/cli/chunks/queen-coordinator-6OKLSCHV.js +0 -2
  285. package/dist/cli/chunks/router-DDZHCGUD.js +0 -2
  286. package/dist/cli/chunks/routing-feedback-BA66F37P.js +0 -2
  287. package/dist/cli/chunks/rvf-native-adapter-TXTRJNPW.js +0 -2
  288. package/dist/cli/chunks/safe-db-IFBVWIGF.js +0 -2
  289. package/dist/cli/chunks/schedule-WMZLOPCW.js +0 -2
  290. package/dist/cli/chunks/scheduler-WBORWJD5.js +0 -2
  291. package/dist/cli/chunks/shared-rvf-adapter-SQQ27EEI.js +0 -2
  292. package/dist/cli/chunks/sqlite-persistence-XH47B3BG.js +0 -2
  293. package/dist/cli/chunks/unified-memory-NHJHPLIC.js +0 -2
  294. package/dist/cli/chunks/unified-memory-hnsw-IMMCI2XK.js +0 -2
  295. package/dist/cli/chunks/unified-persistence-JS6CEV35.js +0 -2
  296. package/dist/cli/chunks/visual-security-XLO5JBVP.js +0 -2
  297. package/dist/cli/chunks/witness-chain-PPWPHYTY.js +0 -2
  298. package/dist/cli/chunks/workflow-orchestrator-H4DKRHVP.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.14");process.exit(0)}
2
- import{b as ye}from"./chunk-FWI7PK4X.js";import{a as ht,b as ft}from"./chunk-3GIZRGX6.js";import{a as yt}from"./chunk-L4IWZXSC.js";import{a as mt,b as pt}from"./chunk-VDGWDDBC.js";import{b as gt,d as z}from"./chunk-D6APBW66.js";import{j as I}from"./chunk-FNKKENLS.js";import{a as ct}from"./chunk-2L3BCZ2F.js";import{a as fe}from"./chunk-NWGIQCCO.js";import{k as w,o as he}from"./chunk-ZFZX2NA3.js";import{a as un}from"./chunk-STYNOKOM.js";import{c as ut}from"./chunk-GUEK5DOK.js";import{b as E,d as dt}from"./chunk-DMZ2XOEW.js";import{a as T,b as C,c as y}from"./chunk-PZF5ISGS.js";import{a as p,b as lt,c as k}from"./chunk-UIYK4Y7K.js";import{f}from"./chunk-G7L5Y47C.js";import{R as dn,S as gn}from"./chunk-5HUAD4UU.js";import{c as G,e as cn,g as ot}from"./chunk-DGUAAG3T.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.15");process.exit(0)}
2
+ import{b as ye}from"./chunk-Q3E6Z2RQ.js";import{a as ht,b as ft}from"./chunk-3RSPEFU3.js";import{a as yt}from"./chunk-GWUO3RY5.js";import{a as mt,b as pt}from"./chunk-JQRR37YY.js";import{b as gt,d as z}from"./chunk-RODJK6G6.js";import{j as I}from"./chunk-ISNXE6TP.js";import{a as ct}from"./chunk-ICXWXO5P.js";import{a as fe}from"./chunk-V65DK6ZZ.js";import{k as w,o as he}from"./chunk-LLVS3UYZ.js";import{a as un}from"./chunk-FEVTMHO6.js";import{c as ut}from"./chunk-XALB3KRR.js";import{b as E,d as dt}from"./chunk-2XW36KDQ.js";import{a as T,b as C,c as y}from"./chunk-FW6QBTPE.js";import{a as p,b as lt,c as k}from"./chunk-JJDHD7SC.js";import{f}from"./chunk-MBDX4OHD.js";import{R as dn,S as gn}from"./chunk-XXRDI53H.js";import{c as G,e as cn,g as ot}from"./chunk-CUQBOVRP.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-FWI7PK4X.js";import{a as ht,b as ft}from"./chunk-3GI
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-NHJHPLIC.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-L6735TFM.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.14");process.exit(0)}
2
- import{c as t,e as o}from"./chunk-DGUAAG3T.js";var L={};o(L,{DotProductAttention:()=>d,FlashAttention:()=>u,HyperbolicAttention:()=>f,LinearAttention:()=>h,MoEAttention:()=>_,MultiHeadAttention:()=>A,RuvectorLayer:()=>a,SonaEngine:()=>b,TensorCompress:()=>c,default:()=>n,differentiableSearch:()=>l,getCompressionLevel:()=>p,hierarchicalForward:()=>s,init:()=>m,pipeline:()=>q});import{createRequire as r}from"module";var i,e,n,a,c,l,s,p,m,u,d,A,f,h,_,b,q,g=t(()=>{i=r(import.meta.url),e=i("better-sqlite3"),n=e,{RuvectorLayer:a,TensorCompress:c,differentiableSearch:l,hierarchicalForward:s,getCompressionLevel:p,init:m,FlashAttention:u,DotProductAttention:d,MultiHeadAttention:A,HyperbolicAttention:f,LinearAttention:h,MoEAttention:_,SonaEngine:b,pipeline:q}=e||{}});export{n as a,a as b,c,l as d,s as e,p as f,m as g,u as h,d as i,A as j,f as k,h as l,_ as m,b as n,q as o,L as p,g 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.15");process.exit(0)}
2
+ import{c as t,e as o}from"./chunk-CUQBOVRP.js";var L={};o(L,{DotProductAttention:()=>d,FlashAttention:()=>u,HyperbolicAttention:()=>f,LinearAttention:()=>h,MoEAttention:()=>_,MultiHeadAttention:()=>A,RuvectorLayer:()=>a,SonaEngine:()=>b,TensorCompress:()=>c,default:()=>n,differentiableSearch:()=>l,getCompressionLevel:()=>p,hierarchicalForward:()=>s,init:()=>m,pipeline:()=>q});import{createRequire as r}from"module";var i,e,n,a,c,l,s,p,m,u,d,A,f,h,_,b,q,g=t(()=>{i=r(import.meta.url),e=i("better-sqlite3"),n=e,{RuvectorLayer:a,TensorCompress:c,differentiableSearch:l,hierarchicalForward:s,getCompressionLevel:p,init:m,FlashAttention:u,DotProductAttention:d,MultiHeadAttention:A,HyperbolicAttention:f,LinearAttention:h,MoEAttention:_,SonaEngine:b,pipeline:q}=e||{}});export{n as a,a as b,c,l as d,s as e,p as f,m as g,u as h,d as i,A as j,f as k,h as l,_ as m,b as n,q as o,L as p,g as q};
@@ -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.14");process.exit(0)}
2
- import{k as K,o as ot}from"./chunk-ZFZX2NA3.js";import{a as rt}from"./chunk-STYNOKOM.js";import{c as U}from"./chunk-GUEK5DOK.js";import{a as j,c as et}from"./chunk-UIYK4Y7K.js";import{a as G,d as at}from"./chunk-JNLKLC7G.js";import{a as nt,b as it}from"./chunk-DJLRRCR6.js";import{c as H,e as V,g as w}from"./chunk-DGUAAG3T.js";var Z={};V(Z,{DotProductAttention:()=>yt,FlashAttention:()=>ft,HyperbolicAttention:()=>bt,LinearAttention:()=>vt,MoEAttention:()=>Et,MultiHeadAttention:()=>At,RuvectorLayer:()=>ut,SonaEngine:()=>P,TensorCompress:()=>mt,default:()=>ct,differentiableSearch:()=>ht,getCompressionLevel:()=>pt,hierarchicalForward:()=>dt,init:()=>gt,pipeline:()=>Ft});import{createRequire as st}from"module";var lt,$,ct,ut,mt,ht,dt,pt,gt,ft,yt,At,bt,vt,Et,P,Ft,k=H(()=>{lt=st(import.meta.url),$=lt("@ruvector/sona"),ct=$,{RuvectorLayer:ut,TensorCompress:mt,differentiableSearch:ht,hierarchicalForward:dt,getCompressionLevel:pt,init:gt,FlashAttention:ft,DotProductAttention:yt,MultiHeadAttention:At,HyperbolicAttention:bt,LinearAttention:vt,MoEAttention:Et,SonaEngine:P,pipeline:Ft}=$||{}});var N={};V(N,{DotProductAttention:()=>It,FlashAttention:()=>zt,HyperbolicAttention:()=>_t,LinearAttention:()=>Ht,MoEAttention:()=>Vt,MultiHeadAttention:()=>qt,RuvectorLayer:()=>Qt,SonaEngine:()=>jt,TensorCompress:()=>Nt,default:()=>xt,differentiableSearch:()=>Ot,getCompressionLevel:()=>Wt,hierarchicalForward:()=>Dt,init:()=>Bt,pipeline:()=>Ut});import{createRequire as kt}from"module";var Rt,X,xt,Qt,Nt,Ot,Dt,Wt,Bt,zt,It,qt,_t,Ht,Vt,jt,Ut,O=H(()=>{Rt=kt(import.meta.url),X=Rt("@ruvector/attention"),xt=X,{RuvectorLayer:Qt,TensorCompress:Nt,differentiableSearch:Ot,hierarchicalForward:Dt,getCompressionLevel:Wt,init:Bt,FlashAttention:zt,DotProductAttention:It,MultiHeadAttention:qt,HyperbolicAttention:_t,LinearAttention:Ht,MoEAttention:Vt,SonaEngine:jt,pipeline:Ut}=X||{}});k();at();import{randomUUID as Ct}from"crypto";rt();import{createRequire as wt}from"module";var f=U.create("sona-three-loop"),S=wt(import.meta.url),M=null,J=!1;function St(){if(J)return M;J=!0;try{let l=S("@ruvector/learning-wasm"),t=S("fs"),e=S("path"),r=e.join(e.dirname(S.resolve("@ruvector/learning-wasm")),"ruvector_learning_wasm_bg.wasm");l.initSync({module:t.readFileSync(r)}),M=l,f.info("WASM MicroLoRA loaded from @ruvector/learning-wasm (6.4x faster than TS)")}catch{M=null,f.debug("@ruvector/learning-wasm not available, using TypeScript MicroLoRA")}return M}var Mt={dimension:384,microLoraLr:.001,consolidationInterval:100,ewcLambda:1e3,taskBoundaryZScoreThreshold:2.5,fisherDecay:.9,fisherSampleSize:200,importanceThreshold:.01},R=class{adaptationVector;baseWeights;lr;adaptationCount=0;constructor(t,e=.001){this.adaptationVector=new Float32Array(t),this.baseWeights=new Float32Array(t),this.lr=e}adapt(t){let e=this.baseWeights.length,r=new Float32Array(e),a=Math.min(t.length,e);for(let n=0;n<e;n++){let o=n<a?t[n]:0;r[n]=this.baseWeights[n]+this.adaptationVector[n]+this.lr*o}for(let n=0;n<a;n++)this.adaptationVector[n]+=this.lr*t[n];return this.adaptationCount++,r}consolidate(){let t=this.adaptationCount,e=this.baseWeights.length;for(let r=0;r<e;r++)this.baseWeights[r]+=this.adaptationVector[r],this.adaptationVector[r]=0;return this.adaptationCount=0,t}getAdaptationCount(){return this.adaptationCount}getEffectiveWeights(){let t=this.baseWeights.length,e=new Float32Array(t);for(let r=0;r<t;r++)e[r]=this.baseWeights[r]+this.adaptationVector[r];return e}getAdaptationMagnitude(){let t=0;for(let e=0;e<this.adaptationVector.length;e++)t+=this.adaptationVector[e]*this.adaptationVector[e];return Math.sqrt(t)}resetAdaptation(){this.adaptationVector.fill(0),this.adaptationCount=0}},x=class{fisherMatrix;optimalParams;lambda;fisherDecay;zScoreThreshold;importanceThreshold;gradientHistory=[];gradientMean=0;gradientVariance=0;taskBoundaryCount=0;consolidationCount=0;constructor(t,e=1e3,r=.9,a=2.5,n=.01){this.fisherMatrix=new Float32Array(t),this.optimalParams=new Float32Array(t),this.lambda=e,this.fisherDecay=r,this.zScoreThreshold=a,this.importanceThreshold=n}detectTaskBoundary(t){let e=0;for(let i=0;i<t.length;i++)e+=t[i]*t[i];if(e=Math.sqrt(e),this.gradientHistory.length<5)return this.gradientHistory.push(e),this.updateGradientStats(),!1;let r=Math.sqrt(this.gradientVariance),a=0,n=Math.abs(e-this.gradientMean);return r>1e-10?a=n/r:n>1e-10&&this.gradientMean>1e-10&&(a=n/(this.gradientMean*.01+1e-10)),this.gradientHistory.push(e),this.gradientHistory.length>100&&this.gradientHistory.shift(),this.updateGradientStats(),a>this.zScoreThreshold?(this.taskBoundaryCount++,!0):!1}computeLoss(t){let e=0,r=Math.min(t.length,this.fisherMatrix.length,this.optimalParams.length);for(let a=0;a<r;a++){let n=t[a]-this.optimalParams[a];e+=this.fisherMatrix[a]*n*n}return this.lambda/2*e}updateFisher(t,e){if(t.length===0)return;let r=this.fisherMatrix.length,a=new Float32Array(r);for(let s of t){let u=Math.min(s.length,r);for(let c=0;c<u;c++)a[c]+=s[c]*s[c]}let n=t.length;for(let s=0;s<r;s++)a[s]/=n;let o=this.fisherDecay;for(let s=0;s<r;s++)this.fisherMatrix[s]=o*this.fisherMatrix[s]+(1-o)*a[s];let i=Math.min(e.length,r);for(let s=0;s<i;s++)this.optimalParams[s]=e[s];this.consolidationCount++}getMetrics(){let t=this.fisherMatrix.length,e=0,r=0,a=0;for(let n=0;n<t;n++)e+=this.fisherMatrix[n],this.fisherMatrix[n]>r&&(r=this.fisherMatrix[n]),this.fisherMatrix[n]>this.importanceThreshold&&a++;return{regularizationLoss:0,taskBoundariesDetected:this.taskBoundaryCount,fisherTrace:e,avgFisherImportance:t>0?e/t:0,maxFisherImportance:r,protectedParams:a,consolidationCycles:this.consolidationCount,lambda:this.lambda}}getTaskBoundaryCount(){return this.taskBoundaryCount}getFisherDiagonal(){return new Float32Array(this.fisherMatrix)}getOptimalParams(){return new Float32Array(this.optimalParams)}loadFisher(t,e){let r=this.fisherMatrix.length,a=Math.min(t.length,r),n=Math.min(e.length,r);for(let o=0;o<a;o++)this.fisherMatrix[o]=t[o];for(let o=0;o<n;o++)this.optimalParams[o]=e[o]}updateGradientStats(){let t=this.gradientHistory.length;if(t===0)return;let e=0;for(let a of this.gradientHistory)e+=a;e/=t;let r=0;for(let a of this.gradientHistory){let n=a-e;r+=n*n}r=t>1?r/(t-1):0,this.gradientMean=e,this.gradientVariance=r}},C=class{config;microLora;ewc;nativeEngine;wasmLora=null;requestCount=0;lastConsolidationRequest=0;peerStates=new Map;gradientBuffer=[];lastFeatures=null;constructor(t={},e){this.config={...Mt,...t},this.nativeEngine=e??null,this.microLora=new R(this.config.dimension,this.config.microLoraLr),this.ewc=new x(this.config.dimension,this.config.ewcLambda,this.config.fisherDecay,this.config.taskBoundaryZScoreThreshold,this.config.importanceThreshold);let r=St();if(r)try{this.wasmLora=new r.WasmMicroLoRA(this.config.dimension,1,this.config.microLoraLr),f.info("SONA Three-Loop using WASM MicroLoRA (0.07us/adapt)")}catch(a){f.debug("WASM MicroLoRA creation failed, falling back",{error:String(a)}),this.wasmLora=null}!this.wasmLora&&this.nativeEngine&&f.info("SONA Three-Loop using native @ruvector/sona engine for MicroLoRA delegation")}instantAdapt(t){let e=performance.now(),r;if(this.wasmLora)try{let o=new Float32Array(t),i=this.wasmLora.adapt(o);i&&i.length>0?(r=i,this.microLora.adapt(t)):r=this.microLora.adapt(t)}catch{r=this.microLora.adapt(t)}else if(this.nativeEngine)try{let o=this.nativeEngine.applyMicroLora(t);r=new Float32Array(o),this.microLora.adapt(t)}catch{r=this.microLora.adapt(t)}else r=this.microLora.adapt(t);let a=this.microLora.getAdaptationMagnitude();this.requestCount++,this.lastFeatures=[...t];let n=(performance.now()-e)*1e3;return{adaptedWeights:r,latencyUs:n,applied:!0,magnitude:a,requestIndex:this.requestCount}}recordOutcome(t,e){if(this.lastFeatures===null){f.warn("recordOutcome called without a preceding instantAdapt()");return}let r=this.lastFeatures.length,a=new Float32Array(r);for(let n=0;n<r;n++)a[n]=t*this.lastFeatures[n];this.gradientBuffer.push(a),this.gradientBuffer.length>this.config.fisherSampleSize&&this.gradientBuffer.shift(),this.lastFeatures=null}backgroundConsolidate(){let t=performance.now();if(this.nativeEngine)try{this.nativeEngine.forceLearn(),this.nativeEngine.tick()}catch(i){f.warn("Native SONA background learning failed, continuing with TypeScript",{error:String(i)})}let e=this.ewc.computeLoss(this.microLora.getEffectiveWeights()),r=!1;if(this.gradientBuffer.length>0){let i=this.gradientBuffer[this.gradientBuffer.length-1];r=this.ewc.detectTaskBoundary(i)}if(r&&this.gradientBuffer.length>0&&(this.ewc.updateFisher(this.gradientBuffer,this.microLora.getEffectiveWeights()),f.info("Task boundary detected, Fisher updated",{boundaries:this.ewc.getTaskBoundaryCount(),requestCount:this.requestCount})),this.gradientBuffer.length>1){let i=!1,s=this.gradientBuffer[0];for(let u=1;u<this.gradientBuffer.length&&!i;u++)for(let c=0;c<s.length;c++)if(Math.abs(this.gradientBuffer[u][c]-s[c])>1e-8){i=!0;break}i||f.warn("All gradient samples identical \u2014 Fisher estimate may be poor. Ensure recordOutcome() is called with diverse rewards.")}let a=this.microLora.consolidate();this.applyEWCRegularization();let n=this.ewc.computeLoss(this.microLora.getEffectiveWeights());this.lastConsolidationRequest=this.requestCount,this.gradientBuffer=[];let o=performance.now()-t;return{consolidated:a>0||r,adaptationsMerged:a,ewcLossBefore:e,ewcLossAfter:n,taskBoundaryDetected:r,durationMs:o}}shouldConsolidate(){return this.requestCount-this.lastConsolidationRequest>=this.config.consolidationInterval}syncWithPeers(t){if(t.length===0)return;for(let i of t)this.peerStates.set(i.peerId,i);let e=this.config.dimension,r=new Float32Array(e),a=new Float32Array(e),n=this.ewc.getFisherDiagonal(),o=this.microLora.adaptationVector;for(let i=0;i<e;i++){let s=n[i]+1e-10;r[i]+=s*o[i],a[i]+=s}for(let i of t){let s=Math.min(i.adaptationVector.length,e);for(let u=0;u<s;u++){let c=(u<i.fisherDiagonal.length?i.fisherDiagonal[u]:0)+1e-10;r[u]+=c*i.adaptationVector[u],a[u]+=c}}for(let i=0;i<e;i++)this.microLora.adaptationVector[i]=r[i]/a[i];f.debug("Synced with peers",{peerCount:t.length,peersStored:this.peerStates.size})}getLocalPeerState(t,e){return{peerId:t,domain:e,adaptationVector:new Float32Array(this.microLora.adaptationVector),fisherDiagonal:this.ewc.getFisherDiagonal(),requestCount:this.requestCount,lastUpdateMs:Date.now()}}getEWCMetrics(){let t=this.ewc.getMetrics();return t.regularizationLoss=this.ewc.computeLoss(this.microLora.getEffectiveWeights()),t}getFisherDiagonal(){return this.ewc.getFisherDiagonal()}getOptimalParams(){return this.ewc.getOptimalParams()}loadFisher(t,e){this.ewc.loadFisher(t,e)}getBaseWeights(){return new Float32Array(this.microLora.baseWeights)}setBaseWeights(t){let e=Math.min(t.length,this.microLora.baseWeights.length);for(let r=0;r<e;r++)this.microLora.baseWeights[r]=t[r]}getEffectiveWeights(){return this.microLora.getEffectiveWeights()}getRequestCount(){return this.requestCount}getConfig(){return{...this.config}}getPeerStates(){return new Map(this.peerStates)}getMicroLoRA(){return this.microLora}getEWC(){return this.ewc}applyEWCRegularization(){let t=this.config.dimension,e=this.ewc.fisherMatrix,r=this.ewc.optimalParams,a=this.microLora.baseWeights,n=.01;for(let o=0;o<t;o++)if(e[o]>this.config.importanceThreshold){let i=a[o]-r[o];a[o]-=n*e[o]*i}}persistFisher(t,e){let r=this.ewc.getMetrics();t(e,this.ewc.getFisherDiagonal(),this.ewc.getOptimalParams(),this.getBaseWeights(),{taskBoundaries:r.taskBoundariesDetected,consolidationCycles:r.consolidationCycles,requestCount:this.requestCount,ewcLambda:r.lambda}),f.info("Fisher matrix persisted to SQLite",{domain:e,requestCount:this.requestCount,taskBoundaries:r.taskBoundariesDetected})}restoreFisher(t){this.ewc.loadFisher(t.fisherDiagonal,t.optimalParams),t.baseWeights&&this.setBaseWeights(t.baseWeights),this.requestCount=t.requestCount,f.info("Fisher matrix restored from SQLite",{requestCount:t.requestCount,dimension:t.fisherDiagonal.length})}};var Lt={hiddenDim:256,embeddingDim:384,microLoraRank:1,baseLoraRank:8,microLoraLr:.001,baseLoraLr:1e-4,ewcLambda:1e3,patternClusters:50,trajectoryCapacity:1e4,backgroundIntervalMs:36e5,qualityThreshold:.5,enableSimd:!0,minConfidence:.5,maxPatterns:1e4},Q=class{patterns;trajectoryMap;maxPatterns;constructor(t=1e4){this.patterns=new Map,this.trajectoryMap=new Map,this.maxPatterns=t}register(t){if(this.patterns.size>=this.maxPatterns&&!this.patterns.has(t.id)){let e=Array.from(this.patterns.entries()).sort(([,r],[,a])=>(r.lastUsedAt?.getTime()??r.createdAt.getTime())-(a.lastUsedAt?.getTime()??a.createdAt.getTime()))[0];e&&this.patterns.delete(e[0])}this.patterns.set(t.id,t)}get(t){return this.patterns.get(t)}getByTrajectory(t){let e=this.trajectoryMap.get(t);return e?this.patterns.get(e):void 0}associateTrajectory(t,e){this.trajectoryMap.set(t,e)}update(t,e){let r=this.patterns.get(t);return r?(this.patterns.set(t,{...r,...e}),!0):!1}getAll(){return Array.from(this.patterns.values())}getByType(t){return Array.from(this.patterns.values()).filter(e=>e.type===t)}getByDomain(t){return Array.from(this.patterns.values()).filter(e=>e.domain===t)}clear(){this.patterns.clear(),this.trajectoryMap.clear()}size(){return this.patterns.size}},v=class{engine;registry;config;adaptationTimes=[];cacheHits=0;totalAdaptations=0;threeLoopEngine=null;fisherPersistFn=null;fisherDomain="default";constructor(t={}){this.config={...Lt,...t};let e={hiddenDim:this.config.hiddenDim,embeddingDim:this.config.embeddingDim,microLoraRank:this.config.microLoraRank,baseLoraRank:this.config.baseLoraRank,microLoraLr:this.config.microLoraLr,baseLoraLr:this.config.baseLoraLr,ewcLambda:this.config.ewcLambda,patternClusters:this.config.patternClusters,trajectoryCapacity:this.config.trajectoryCapacity,backgroundIntervalMs:this.config.backgroundIntervalMs,qualityThreshold:this.config.qualityThreshold,enableSimd:this.config.enableSimd};this.engine=P.withConfig(e),this.registry=new Q(this.config.maxPatterns??1e4)}async adaptPattern(t,e,r){let a=performance.now();try{let n=this.createStateEmbedding(t),o=this.engine.findPatterns(n,5),i=[];for(let m of o){let g=this.findByRawPattern(m);if(g||(g=this.createQEPatternFromRaw(m,e,r)),g.type===e&&g.domain===r&&g.confidence>=(this.config.minConfidence??.5)){let h=this.calculateSimilarity(n,m.centroid);i.push({pattern:g,similarity:h})}}if(i.length===0){let m=performance.now()-a;return this.recordAdaptation(m),{success:!1,pattern:null,adaptationTimeMs:m,similarity:0,reasoning:"No suitable pattern found"}}let s=i[0],u={...s.pattern,usageCount:s.pattern.usageCount+1,lastUsedAt:new Date};this.registry.update(u.id,u);let c=performance.now()-a;return this.recordAdaptation(c),{success:!0,pattern:u,adaptationTimeMs:c,similarity:s.similarity,reasoning:`Pattern adapted from @ruvector/sona with ${s.similarity.toFixed(3)} similarity`}}catch(n){let o=performance.now()-a;return this.recordAdaptation(o),{success:!1,pattern:null,adaptationTimeMs:o,similarity:0,reasoning:`Adaptation failed: ${n.message}`}}}recallPattern(t,e,r){let a=this.createStateEmbedding(t),n=this.engine.findPatterns(a,1);for(let o of n){let i=this.findByRawPattern(o);if(i&&i.type===e&&i.domain===r)return i}return null}storePattern(t){this.registry.register(t);let e=this.engine.beginTrajectory(t.stateEmbedding),r=this.createActionEmbedding(t.action),a=new Array(r.length).fill(1),n=t.outcome.success?t.outcome.quality:-t.outcome.quality;this.engine.addTrajectoryStep(e,r,a,n),this.engine.endTrajectory(e,t.outcome.quality),this.registry.associateTrajectory(e,t.id)}storePatternsBatch(t){for(let e of t)this.storePattern(e)}createPattern(t,e,r,a,n,o){let i={id:`qesona-${Date.now()}-${Ct().slice(0,7)}`,type:a,domain:n,stateEmbedding:this.createStateEmbedding(t),action:e,outcome:r,confidence:.5,usageCount:0,createdAt:new Date,metadata:o};return this.storePattern(i),i}updatePattern(t,e,r){let a=this.registry.get(t);if(!a)return!1;let n=e?r:-r,i=a.confidence+.1*(n-a.confidence),s={...a,confidence:Math.max(0,Math.min(1,i)),usageCount:a.usageCount+1,lastUsedAt:new Date};return this.registry.update(t,s)}applyMicroLora(t){return this.engine.applyMicroLora(t)}applyBaseLora(t,e){return this.engine.applyBaseLora(t,e)}forceLearn(){return this.engine.forceLearn()}tick(){return this.engine.tick()}getAllPatterns(){return this.registry.getAll()}getPatternsByType(t){return this.registry.getByType(t)}getPatternsByDomain(t){return this.registry.getByDomain(t)}getStats(){let t=this.registry.getAll(),e=this.engine.getStats(),r={"test-generation":0,"defect-prediction":0,"coverage-optimization":0,"quality-assessment":0,"resource-allocation":0};for(let a of t)r[a.type]++;return{totalPatterns:t.length,patternsByType:r,avgAdaptationTimeMs:this.avgAdaptationTime(),minAdaptationTimeMs:this.minAdaptationTime(),maxAdaptationTimeMs:this.maxAdaptationTime(),totalAdaptations:this.totalAdaptations,cacheHitRate:this.totalAdaptations>0?this.cacheHits/this.totalAdaptations:0,engineStats:e}}clear(){this.registry.clear(),this.adaptationTimes=[],this.cacheHits=0,this.totalAdaptations=0}exportPatterns(){return this.registry.getAll()}importPatterns(t){this.clear(),this.storePatternsBatch(t)}getConfig(){return{...this.config}}setEnabled(t){this.engine.setEnabled(t)}isEnabled(){return this.engine.isEnabled()}createStateEmbedding(t){let e=t.features;if(e.length===0)return new Array(this.config.embeddingDim??384).fill(0);let r=Math.max(...e.map(Math.abs));if(r===0)return[...e];let a=e.map(o=>o/r),n=this.config.embeddingDim??384;return a.length>=n?a.slice(0,n):[...a,...new Array(n-a.length).fill(0)]}createActionEmbedding(t){let e=[],r=this.hashCode(t.type);if(e.push(r%1e3/1e3),typeof t.value=="number")e.push(Math.min(1,Math.max(-1,t.value)));else if(typeof t.value=="string"){let n=this.hashCode(t.value);e.push(n%1e3/1e3)}else if(Array.isArray(t.value))for(let n of t.value.slice(0,10))typeof n=="number"&&e.push(Math.min(1,Math.max(-1,n)));let a=this.config.embeddingDim??384;for(;e.length<a;)e.push(0);return e.slice(0,a)}findByRawPattern(t){let e=this.registry.getAll();for(let r of e)if(r.rawPattern?.patternType===t.id)return r}createQEPatternFromRaw(t,e,r){let a={centroid:t.centroid,clusterSize:1,totalWeight:1,avgQuality:t.avgQuality,createdAt:new Date().toISOString(),lastAccessed:new Date().toISOString(),accessCount:0,patternType:t.patternType};return{id:`qesona-${t.id}`,type:e,domain:r,stateEmbedding:t.centroid,action:{type:"learned",value:t.patternType},outcome:{reward:t.avgQuality,success:t.avgQuality>.5,quality:t.avgQuality},confidence:t.avgQuality,usageCount:0,createdAt:new Date,rawPattern:a}}calculateSimilarity(t,e){let r=Math.min(t.length,e.length),a=0,n=0,o=0;for(let s=0;s<r;s++)a+=t[s]*e[s],n+=t[s]*t[s],o+=e[s]*e[s];return(a/(Math.sqrt(n)*Math.sqrt(o)+1e-10)+1)/2}hashCode(t){let e=0;for(let r=0;r<t.length;r++)e=(e<<5)-e+t.charCodeAt(r),e=e|0;return Math.abs(e)}recordAdaptation(t){this.adaptationTimes.push(t),this.totalAdaptations++,this.adaptationTimes.length>1e3&&this.adaptationTimes.shift()}avgAdaptationTime(){return this.adaptationTimes.length===0?0:this.adaptationTimes.reduce((e,r)=>e+r,0)/this.adaptationTimes.length}minAdaptationTime(){return this.adaptationTimes.length===0?0:Math.min(...this.adaptationTimes)}maxAdaptationTime(){return this.adaptationTimes.length===0?0:Math.max(...this.adaptationTimes)}initThreeLoopEngine(t){this.threeLoopEngine=new C({dimension:this.config.embeddingDim??384,microLoraLr:this.config.microLoraLr??.001,ewcLambda:this.config.ewcLambda??1e3,...t},this.engine)}getThreeLoopEngine(){return this.threeLoopEngine}instantAdapt(t){return this.threeLoopEngine?this.threeLoopEngine.instantAdapt(t):null}recordOutcome(t,e){this.threeLoopEngine&&this.threeLoopEngine.recordOutcome(t,e)}backgroundConsolidate(){if(!this.threeLoopEngine)return null;let t=this.threeLoopEngine.backgroundConsolidate();if(t&&(t.consolidated||t.taskBoundaryDetected)&&this.fisherPersistFn)try{this.threeLoopEngine.persistFisher(this.fisherPersistFn,this.fisherDomain)}catch(e){console.warn("[QESONA] Fisher persistence failed:",e instanceof Error?e.message:e)}return t}setFisherPersistence(t,e){this.fisherPersistFn=t,this.fisherDomain=e}syncWithPeers(t){this.threeLoopEngine&&this.threeLoopEngine.syncWithPeers(t)}getEWCMetrics(){return this.threeLoopEngine?this.threeLoopEngine.getEWCMetrics():null}shouldConsolidate(){return this.threeLoopEngine?this.threeLoopEngine.shouldConsolidate():!1}getLocalPeerState(t,e){return this.threeLoopEngine?this.threeLoopEngine.getLocalPeerState(t,e):null}isThreeLoopEnabled(){return this.threeLoopEngine!==null}async verifyPerformance(t=1e3){let e=[],r={id:"test-state",features:new Array(384).fill(0).map(()=>G())};for(let s=0;s<t;s++){let u=performance.now();await this.adaptPattern(r,"test-generation","test-generation");let c=performance.now();e.push({iteration:s,timeMs:c-u})}let a=e.map(s=>s.timeMs),n=a.reduce((s,u)=>s+u,0)/a.length,o=Math.min(...a),i=Math.max(...a);return{targetMet:n<.05,avgTimeMs:n,minTimeMs:o,maxTimeMs:i,details:e}}};function Tt(l){return new v(l)}function Pt(l,t){return new v({...t,maxPatterns:t?.maxPatterns||5e3})}ot();et();var F=null,D=null,W=null,B=null,z=null,I=null,q=!1;try{let l=(O(),w(N));F=l.FlashAttention,D=l.DotProductAttention,W=l.MultiHeadAttention,B=l.HyperbolicAttention,z=l.LinearAttention,I=l.MoEAttention,q=!0}catch{}function Gt(){return q}function A(){if(!q)throw new Error("@ruvector/attention native module is not available on this platform. Install the appropriate optional dependency for your platform, or use a platform where pre-built binaries are available.")}var T={"test-similarity":{dim:384,strategy:"flash",blockSize:64},"code-embedding":{dim:512,strategy:"flash",blockSize:128},"defect-matching":{dim:384,strategy:"flash",blockSize:64},"coverage-analysis":{dim:384,strategy:"flash",blockSize:256},"pattern-adaptation":{dim:256,strategy:"flash",blockSize:32}},Kt={"test-similarity":{enabled:!0,microLoRARank:4,targetAdaptationMs:.05,patternCacheSize:1e3},"code-embedding":{enabled:!0,microLoRARank:2,targetAdaptationMs:.03,patternCacheSize:5e3},"defect-matching":{enabled:!0,microLoRARank:8,targetAdaptationMs:.05,patternCacheSize:2e3},"coverage-analysis":{enabled:!1,microLoRARank:2,targetAdaptationMs:.01,patternCacheSize:100},"pattern-adaptation":{enabled:!0,microLoRARank:2,targetAdaptationMs:.05,patternCacheSize:1e4}},$t={"test-similarity":{latency:{before:50,after:15},memory:{before:200,after:80},throughput:{min:1e3}},"code-embedding":{latency:{before:50,after:15},memory:{before:200,after:80},throughput:{min:2e3}},"defect-matching":{latency:{before:20,after:5},memory:{before:150,after:50},throughput:{min:500}},"coverage-analysis":{latency:{before:100,after:1},memory:{before:100,after:30},throughput:{min:1e4}},"pattern-adaptation":{latency:{before:2,after:.05},memory:{before:50,after:20},throughput:{min:2e4}}};function Zt(l){return l<=128?{queryChunkSize:128,kvChunkSize:128}:l<=256?{queryChunkSize:256,kvChunkSize:256}:l<=512?{queryChunkSize:512,kvChunkSize:512}:l<=1024?{queryChunkSize:1024,kvChunkSize:1024}:{queryChunkSize:1024,kvChunkSize:2048}}var E=class{static create(t){switch(A(),t.strategy){case"flash":return new F(t.dim,t.blockSize);case"dot-product":return new D(t.dim);case"multi-head":return new W(t.dim,t.numHeads??8);case"hyperbolic":return new B(t.dim,t.curvature);case"linear":return new z(t.dim,t.features);case"moe":return I.simple(t.dim,t.moeConfig?.numExperts??8,t.moeConfig?.topK??2);default:return new F(t.dim,t.blockSize)}}},L=class l{attention;config;workload;metrics=[];db=null;persistCount=0;static KV_NAMESPACE="attention-metrics";static KV_TTL=3600;static PERSIST_INTERVAL=10;constructor(t,e){this.workload=t;let r=T[t];this.config={...r,...e},this.attention=E.create(this.config)}async initialize(){try{this.db=K(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(t){console.warn("[QEFlashAttention] DB init failed, using memory-only:",j(t)),this.db=null}}async computeFlashAttention(t,e,r,a,n){let o=performance.now(),i=process.memoryUsage().heapUsed/1024/1024,s=this.toFloat32Array(t,a,n),u=this.splitMatrix(e,a,n),c=this.splitMatrix(r,a,n),m,g=this.attention;typeof g.compute=="function"?m=g.compute(s,u,c):(A(),m=new F(this.config.dim).compute(s,u,c));let h=performance.now(),d=process.memoryUsage().heapUsed/1024/1024;return this.metrics.push({timeMs:h-o,memoryMB:d-i,speedup:1,throughput:a*a/((h-o)/1e3),peakMemoryMB:d}),this.maybePersistToKv(),m}async computeBaselineAttention(t,e,r,a,n){let o=performance.now(),i=process.memoryUsage().heapUsed/1024/1024,s=new Float32Array(a*a),u=1/Math.sqrt(n);for(let h=0;h<a;h++)for(let d=0;d<a;d++){let b=0;for(let p=0;p<n;p++)b+=t[h*n+p]*e[d*n+p];s[h*a+d]=b*u}for(let h=0;h<a;h++){let d=h*a,b=d+a,p=s.subarray(d,b),tt=Math.max(...p),_=0;for(let y=0;y<a;y++)p[y]=Math.exp(p[y]-tt),_+=p[y];for(let y=0;y<a;y++)p[y]/=_}let c=new Float32Array(a*n);for(let h=0;h<a;h++)for(let d=0;d<a;d++){let b=s[h*a+d];for(let p=0;p<n;p++)c[h*n+p]+=b*r[d*n+p]}let m=performance.now(),g=process.memoryUsage().heapUsed/1024/1024;return c}async computeTestSimilarity(t,e,r=5){let a=e.length,n=t.length,o=new Float32Array(a*n),i=new Float32Array(a*n);for(let m=0;m<a;m++)o.set(t,m*n),i.set(e[m],m*n);let s=new Float32Array(a*n),u=await this.computeFlashAttention(o,i,s,a,n),c=[];for(let m=0;m<a;m++)c.push({index:m,similarity:u[m*n]});return c.sort((m,g)=>g.similarity-m.similarity),c.slice(0,r)}async generateCodeEmbedding(t,e){let r=t.length/e.length,a=e.length;return await this.computeFlashAttention(t,e,t,r,a)}async matchDefectPattern(t,e){let r=e.length,a=t.length,n=new Float32Array(r*a),o=new Float32Array(r*a);for(let c=0;c<r;c++)n.set(t,c*a),o.set(e[c],c*a);let i=new Float32Array(r*a),s=await this.computeFlashAttention(n,o,i,r,a),u=[];for(let c=0;c<r;c++)u.push({pattern:c,score:s[c*a]});return u.sort((c,m)=>m.score-c.score),u}getMetrics(){return[...this.metrics]}getAverageSpeedup(){return this.metrics.length===0?1:this.metrics.reduce((t,e)=>t+e.speedup,0)/this.metrics.length}getConfig(){return{...this.config}}updateConfig(t){this.config={...this.config,...t},this.attention=E.create(this.config)}changeStrategy(t){this.config.strategy=t,this.attention=E.create(this.config)}resetMetrics(){this.metrics=[]}getWorkload(){return this.workload}dispose(){this.metrics=[]}async persistToKv(){if(!this.db)return;let t=`attention-metrics-${this.workload}`,e={workload:this.workload,metrics:this.metrics.slice(-50),savedAt:Date.now()};await this.db.kvSet(t,e,l.KV_NAMESPACE,l.KV_TTL)}async loadFromKv(){if(!this.db)return;let t=`attention-metrics-${this.workload}`,e=await this.db.kvGet(t,l.KV_NAMESPACE);e?.metrics?.length&&(this.metrics=e.metrics)}maybePersistToKv(){this.persistCount++,this.persistCount>=l.PERSIST_INTERVAL&&(this.persistCount=0,this.persistToKv().catch(()=>{}))}toFloat32Array(t,e,r){return t.slice(0,r)}splitMatrix(t,e,r){let a=[];for(let n=0;n<e;n++)a.push(t.slice(n*r,(n+1)*r));return a}};async function Y(l,t){let e=new L(l,t);return await e.initialize(),e}function Jt(l){return{...T[l]}}function Xt(){return Object.keys(T)}function Yt(){return A(),F}function te(){return A(),D}function ee(){return A(),W}function re(){return A(),B}function ae(){return A(),z}function ne(){return A(),I}function ie(l){return l instanceof Float32Array?l:new Float32Array(l)}function oe(l){return Array.from(l)}async function se(l,t,e,r){let a=await Y(l),n=[],o=t[0].length,i=e.length;for(let s of t){let u=new Float32Array(i*o),c=new Float32Array(i*o),m=new Float32Array(i*o);u.set(s,0);for(let h=0;h<i;h++)c.set(e[h],h*o),m.set(r[h],h*o);let g=await a.computeFlashAttention(u,c,m,i,o);n.push(g.slice(0,o))}return a.dispose(),n}function We(){return{"@ruvector/sona":"^0.1.5","@ruvector/attention":"^0.1.4","@ruvector/gnn":"^0.1.22"}}function Be(){let l={sona:!1,attention:!1,gnn:!1,all:!1};try{k(),l.sona=!0}catch{}try{O(),l.attention=!0}catch{}try{let t=(it(),w(nt));t.init();let e=new Float32Array([.1,.2,.3]),r=[new Float32Array([.1,.2,.3]),new Float32Array([.4,.5,.6])],a=t.differentiableSearch(e,r,1,1);a&&Array.isArray(a.indices)&&Array.isArray(a.weights)&&(l.gnn=!0)}catch{}return l.all=l.sona&&l.attention&&l.gnn,l}async function ze(){let{initGNN:l}=await import("./gnn-wrapper-NYQ77563.js");return[l(),"SONA: Ready (no initialization required)","Attention: Ready (no initialization required)"]}export{v as a,Tt as b,Pt as c,Gt as d,T as e,Kt as f,$t as g,Zt as h,L as i,Y as j,Jt as k,Xt as l,Yt as m,te as n,ee as o,re as p,ae as q,ne as r,ie as s,oe as t,se as u,We as v,Be as w,ze as x};
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.15");process.exit(0)}
2
+ import{k as K,o as ot}from"./chunk-LLVS3UYZ.js";import{a as rt}from"./chunk-FEVTMHO6.js";import{c as U}from"./chunk-XALB3KRR.js";import{a as j,c as et}from"./chunk-JJDHD7SC.js";import{a as G,d as at}from"./chunk-D3ZUSXFY.js";import{a as nt,b as it}from"./chunk-YCYFUYCE.js";import{c as H,e as V,g as w}from"./chunk-CUQBOVRP.js";var Z={};V(Z,{DotProductAttention:()=>yt,FlashAttention:()=>ft,HyperbolicAttention:()=>bt,LinearAttention:()=>vt,MoEAttention:()=>Et,MultiHeadAttention:()=>At,RuvectorLayer:()=>ut,SonaEngine:()=>P,TensorCompress:()=>mt,default:()=>ct,differentiableSearch:()=>ht,getCompressionLevel:()=>pt,hierarchicalForward:()=>dt,init:()=>gt,pipeline:()=>Ft});import{createRequire as st}from"module";var lt,$,ct,ut,mt,ht,dt,pt,gt,ft,yt,At,bt,vt,Et,P,Ft,k=H(()=>{lt=st(import.meta.url),$=lt("@ruvector/sona"),ct=$,{RuvectorLayer:ut,TensorCompress:mt,differentiableSearch:ht,hierarchicalForward:dt,getCompressionLevel:pt,init:gt,FlashAttention:ft,DotProductAttention:yt,MultiHeadAttention:At,HyperbolicAttention:bt,LinearAttention:vt,MoEAttention:Et,SonaEngine:P,pipeline:Ft}=$||{}});var N={};V(N,{DotProductAttention:()=>It,FlashAttention:()=>zt,HyperbolicAttention:()=>_t,LinearAttention:()=>Ht,MoEAttention:()=>Vt,MultiHeadAttention:()=>qt,RuvectorLayer:()=>Qt,SonaEngine:()=>jt,TensorCompress:()=>Nt,default:()=>xt,differentiableSearch:()=>Ot,getCompressionLevel:()=>Wt,hierarchicalForward:()=>Dt,init:()=>Bt,pipeline:()=>Ut});import{createRequire as kt}from"module";var Rt,X,xt,Qt,Nt,Ot,Dt,Wt,Bt,zt,It,qt,_t,Ht,Vt,jt,Ut,O=H(()=>{Rt=kt(import.meta.url),X=Rt("@ruvector/attention"),xt=X,{RuvectorLayer:Qt,TensorCompress:Nt,differentiableSearch:Ot,hierarchicalForward:Dt,getCompressionLevel:Wt,init:Bt,FlashAttention:zt,DotProductAttention:It,MultiHeadAttention:qt,HyperbolicAttention:_t,LinearAttention:Ht,MoEAttention:Vt,SonaEngine:jt,pipeline:Ut}=X||{}});k();at();import{randomUUID as Ct}from"crypto";rt();import{createRequire as wt}from"module";var f=U.create("sona-three-loop"),S=wt(import.meta.url),M=null,J=!1;function St(){if(J)return M;J=!0;try{let l=S("@ruvector/learning-wasm"),t=S("fs"),e=S("path"),r=e.join(e.dirname(S.resolve("@ruvector/learning-wasm")),"ruvector_learning_wasm_bg.wasm");l.initSync({module:t.readFileSync(r)}),M=l,f.info("WASM MicroLoRA loaded from @ruvector/learning-wasm (6.4x faster than TS)")}catch{M=null,f.debug("@ruvector/learning-wasm not available, using TypeScript MicroLoRA")}return M}var Mt={dimension:384,microLoraLr:.001,consolidationInterval:100,ewcLambda:1e3,taskBoundaryZScoreThreshold:2.5,fisherDecay:.9,fisherSampleSize:200,importanceThreshold:.01},R=class{adaptationVector;baseWeights;lr;adaptationCount=0;constructor(t,e=.001){this.adaptationVector=new Float32Array(t),this.baseWeights=new Float32Array(t),this.lr=e}adapt(t){let e=this.baseWeights.length,r=new Float32Array(e),a=Math.min(t.length,e);for(let n=0;n<e;n++){let o=n<a?t[n]:0;r[n]=this.baseWeights[n]+this.adaptationVector[n]+this.lr*o}for(let n=0;n<a;n++)this.adaptationVector[n]+=this.lr*t[n];return this.adaptationCount++,r}consolidate(){let t=this.adaptationCount,e=this.baseWeights.length;for(let r=0;r<e;r++)this.baseWeights[r]+=this.adaptationVector[r],this.adaptationVector[r]=0;return this.adaptationCount=0,t}getAdaptationCount(){return this.adaptationCount}getEffectiveWeights(){let t=this.baseWeights.length,e=new Float32Array(t);for(let r=0;r<t;r++)e[r]=this.baseWeights[r]+this.adaptationVector[r];return e}getAdaptationMagnitude(){let t=0;for(let e=0;e<this.adaptationVector.length;e++)t+=this.adaptationVector[e]*this.adaptationVector[e];return Math.sqrt(t)}resetAdaptation(){this.adaptationVector.fill(0),this.adaptationCount=0}},x=class{fisherMatrix;optimalParams;lambda;fisherDecay;zScoreThreshold;importanceThreshold;gradientHistory=[];gradientMean=0;gradientVariance=0;taskBoundaryCount=0;consolidationCount=0;constructor(t,e=1e3,r=.9,a=2.5,n=.01){this.fisherMatrix=new Float32Array(t),this.optimalParams=new Float32Array(t),this.lambda=e,this.fisherDecay=r,this.zScoreThreshold=a,this.importanceThreshold=n}detectTaskBoundary(t){let e=0;for(let i=0;i<t.length;i++)e+=t[i]*t[i];if(e=Math.sqrt(e),this.gradientHistory.length<5)return this.gradientHistory.push(e),this.updateGradientStats(),!1;let r=Math.sqrt(this.gradientVariance),a=0,n=Math.abs(e-this.gradientMean);return r>1e-10?a=n/r:n>1e-10&&this.gradientMean>1e-10&&(a=n/(this.gradientMean*.01+1e-10)),this.gradientHistory.push(e),this.gradientHistory.length>100&&this.gradientHistory.shift(),this.updateGradientStats(),a>this.zScoreThreshold?(this.taskBoundaryCount++,!0):!1}computeLoss(t){let e=0,r=Math.min(t.length,this.fisherMatrix.length,this.optimalParams.length);for(let a=0;a<r;a++){let n=t[a]-this.optimalParams[a];e+=this.fisherMatrix[a]*n*n}return this.lambda/2*e}updateFisher(t,e){if(t.length===0)return;let r=this.fisherMatrix.length,a=new Float32Array(r);for(let s of t){let u=Math.min(s.length,r);for(let c=0;c<u;c++)a[c]+=s[c]*s[c]}let n=t.length;for(let s=0;s<r;s++)a[s]/=n;let o=this.fisherDecay;for(let s=0;s<r;s++)this.fisherMatrix[s]=o*this.fisherMatrix[s]+(1-o)*a[s];let i=Math.min(e.length,r);for(let s=0;s<i;s++)this.optimalParams[s]=e[s];this.consolidationCount++}getMetrics(){let t=this.fisherMatrix.length,e=0,r=0,a=0;for(let n=0;n<t;n++)e+=this.fisherMatrix[n],this.fisherMatrix[n]>r&&(r=this.fisherMatrix[n]),this.fisherMatrix[n]>this.importanceThreshold&&a++;return{regularizationLoss:0,taskBoundariesDetected:this.taskBoundaryCount,fisherTrace:e,avgFisherImportance:t>0?e/t:0,maxFisherImportance:r,protectedParams:a,consolidationCycles:this.consolidationCount,lambda:this.lambda}}getTaskBoundaryCount(){return this.taskBoundaryCount}getFisherDiagonal(){return new Float32Array(this.fisherMatrix)}getOptimalParams(){return new Float32Array(this.optimalParams)}loadFisher(t,e){let r=this.fisherMatrix.length,a=Math.min(t.length,r),n=Math.min(e.length,r);for(let o=0;o<a;o++)this.fisherMatrix[o]=t[o];for(let o=0;o<n;o++)this.optimalParams[o]=e[o]}updateGradientStats(){let t=this.gradientHistory.length;if(t===0)return;let e=0;for(let a of this.gradientHistory)e+=a;e/=t;let r=0;for(let a of this.gradientHistory){let n=a-e;r+=n*n}r=t>1?r/(t-1):0,this.gradientMean=e,this.gradientVariance=r}},C=class{config;microLora;ewc;nativeEngine;wasmLora=null;requestCount=0;lastConsolidationRequest=0;peerStates=new Map;gradientBuffer=[];lastFeatures=null;constructor(t={},e){this.config={...Mt,...t},this.nativeEngine=e??null,this.microLora=new R(this.config.dimension,this.config.microLoraLr),this.ewc=new x(this.config.dimension,this.config.ewcLambda,this.config.fisherDecay,this.config.taskBoundaryZScoreThreshold,this.config.importanceThreshold);let r=St();if(r)try{this.wasmLora=new r.WasmMicroLoRA(this.config.dimension,1,this.config.microLoraLr),f.info("SONA Three-Loop using WASM MicroLoRA (0.07us/adapt)")}catch(a){f.debug("WASM MicroLoRA creation failed, falling back",{error:String(a)}),this.wasmLora=null}!this.wasmLora&&this.nativeEngine&&f.info("SONA Three-Loop using native @ruvector/sona engine for MicroLoRA delegation")}instantAdapt(t){let e=performance.now(),r;if(this.wasmLora)try{let o=new Float32Array(t),i=this.wasmLora.adapt(o);i&&i.length>0?(r=i,this.microLora.adapt(t)):r=this.microLora.adapt(t)}catch{r=this.microLora.adapt(t)}else if(this.nativeEngine)try{let o=this.nativeEngine.applyMicroLora(t);r=new Float32Array(o),this.microLora.adapt(t)}catch{r=this.microLora.adapt(t)}else r=this.microLora.adapt(t);let a=this.microLora.getAdaptationMagnitude();this.requestCount++,this.lastFeatures=[...t];let n=(performance.now()-e)*1e3;return{adaptedWeights:r,latencyUs:n,applied:!0,magnitude:a,requestIndex:this.requestCount}}recordOutcome(t,e){if(this.lastFeatures===null){f.warn("recordOutcome called without a preceding instantAdapt()");return}let r=this.lastFeatures.length,a=new Float32Array(r);for(let n=0;n<r;n++)a[n]=t*this.lastFeatures[n];this.gradientBuffer.push(a),this.gradientBuffer.length>this.config.fisherSampleSize&&this.gradientBuffer.shift(),this.lastFeatures=null}backgroundConsolidate(){let t=performance.now();if(this.nativeEngine)try{this.nativeEngine.forceLearn(),this.nativeEngine.tick()}catch(i){f.warn("Native SONA background learning failed, continuing with TypeScript",{error:String(i)})}let e=this.ewc.computeLoss(this.microLora.getEffectiveWeights()),r=!1;if(this.gradientBuffer.length>0){let i=this.gradientBuffer[this.gradientBuffer.length-1];r=this.ewc.detectTaskBoundary(i)}if(r&&this.gradientBuffer.length>0&&(this.ewc.updateFisher(this.gradientBuffer,this.microLora.getEffectiveWeights()),f.info("Task boundary detected, Fisher updated",{boundaries:this.ewc.getTaskBoundaryCount(),requestCount:this.requestCount})),this.gradientBuffer.length>1){let i=!1,s=this.gradientBuffer[0];for(let u=1;u<this.gradientBuffer.length&&!i;u++)for(let c=0;c<s.length;c++)if(Math.abs(this.gradientBuffer[u][c]-s[c])>1e-8){i=!0;break}i||f.warn("All gradient samples identical \u2014 Fisher estimate may be poor. Ensure recordOutcome() is called with diverse rewards.")}let a=this.microLora.consolidate();this.applyEWCRegularization();let n=this.ewc.computeLoss(this.microLora.getEffectiveWeights());this.lastConsolidationRequest=this.requestCount,this.gradientBuffer=[];let o=performance.now()-t;return{consolidated:a>0||r,adaptationsMerged:a,ewcLossBefore:e,ewcLossAfter:n,taskBoundaryDetected:r,durationMs:o}}shouldConsolidate(){return this.requestCount-this.lastConsolidationRequest>=this.config.consolidationInterval}syncWithPeers(t){if(t.length===0)return;for(let i of t)this.peerStates.set(i.peerId,i);let e=this.config.dimension,r=new Float32Array(e),a=new Float32Array(e),n=this.ewc.getFisherDiagonal(),o=this.microLora.adaptationVector;for(let i=0;i<e;i++){let s=n[i]+1e-10;r[i]+=s*o[i],a[i]+=s}for(let i of t){let s=Math.min(i.adaptationVector.length,e);for(let u=0;u<s;u++){let c=(u<i.fisherDiagonal.length?i.fisherDiagonal[u]:0)+1e-10;r[u]+=c*i.adaptationVector[u],a[u]+=c}}for(let i=0;i<e;i++)this.microLora.adaptationVector[i]=r[i]/a[i];f.debug("Synced with peers",{peerCount:t.length,peersStored:this.peerStates.size})}getLocalPeerState(t,e){return{peerId:t,domain:e,adaptationVector:new Float32Array(this.microLora.adaptationVector),fisherDiagonal:this.ewc.getFisherDiagonal(),requestCount:this.requestCount,lastUpdateMs:Date.now()}}getEWCMetrics(){let t=this.ewc.getMetrics();return t.regularizationLoss=this.ewc.computeLoss(this.microLora.getEffectiveWeights()),t}getFisherDiagonal(){return this.ewc.getFisherDiagonal()}getOptimalParams(){return this.ewc.getOptimalParams()}loadFisher(t,e){this.ewc.loadFisher(t,e)}getBaseWeights(){return new Float32Array(this.microLora.baseWeights)}setBaseWeights(t){let e=Math.min(t.length,this.microLora.baseWeights.length);for(let r=0;r<e;r++)this.microLora.baseWeights[r]=t[r]}getEffectiveWeights(){return this.microLora.getEffectiveWeights()}getRequestCount(){return this.requestCount}getConfig(){return{...this.config}}getPeerStates(){return new Map(this.peerStates)}getMicroLoRA(){return this.microLora}getEWC(){return this.ewc}applyEWCRegularization(){let t=this.config.dimension,e=this.ewc.fisherMatrix,r=this.ewc.optimalParams,a=this.microLora.baseWeights,n=.01;for(let o=0;o<t;o++)if(e[o]>this.config.importanceThreshold){let i=a[o]-r[o];a[o]-=n*e[o]*i}}persistFisher(t,e){let r=this.ewc.getMetrics();t(e,this.ewc.getFisherDiagonal(),this.ewc.getOptimalParams(),this.getBaseWeights(),{taskBoundaries:r.taskBoundariesDetected,consolidationCycles:r.consolidationCycles,requestCount:this.requestCount,ewcLambda:r.lambda}),f.info("Fisher matrix persisted to SQLite",{domain:e,requestCount:this.requestCount,taskBoundaries:r.taskBoundariesDetected})}restoreFisher(t){this.ewc.loadFisher(t.fisherDiagonal,t.optimalParams),t.baseWeights&&this.setBaseWeights(t.baseWeights),this.requestCount=t.requestCount,f.info("Fisher matrix restored from SQLite",{requestCount:t.requestCount,dimension:t.fisherDiagonal.length})}};var Lt={hiddenDim:256,embeddingDim:384,microLoraRank:1,baseLoraRank:8,microLoraLr:.001,baseLoraLr:1e-4,ewcLambda:1e3,patternClusters:50,trajectoryCapacity:1e4,backgroundIntervalMs:36e5,qualityThreshold:.5,enableSimd:!0,minConfidence:.5,maxPatterns:1e4},Q=class{patterns;trajectoryMap;maxPatterns;constructor(t=1e4){this.patterns=new Map,this.trajectoryMap=new Map,this.maxPatterns=t}register(t){if(this.patterns.size>=this.maxPatterns&&!this.patterns.has(t.id)){let e=Array.from(this.patterns.entries()).sort(([,r],[,a])=>(r.lastUsedAt?.getTime()??r.createdAt.getTime())-(a.lastUsedAt?.getTime()??a.createdAt.getTime()))[0];e&&this.patterns.delete(e[0])}this.patterns.set(t.id,t)}get(t){return this.patterns.get(t)}getByTrajectory(t){let e=this.trajectoryMap.get(t);return e?this.patterns.get(e):void 0}associateTrajectory(t,e){this.trajectoryMap.set(t,e)}update(t,e){let r=this.patterns.get(t);return r?(this.patterns.set(t,{...r,...e}),!0):!1}getAll(){return Array.from(this.patterns.values())}getByType(t){return Array.from(this.patterns.values()).filter(e=>e.type===t)}getByDomain(t){return Array.from(this.patterns.values()).filter(e=>e.domain===t)}clear(){this.patterns.clear(),this.trajectoryMap.clear()}size(){return this.patterns.size}},v=class{engine;registry;config;adaptationTimes=[];cacheHits=0;totalAdaptations=0;threeLoopEngine=null;fisherPersistFn=null;fisherDomain="default";constructor(t={}){this.config={...Lt,...t};let e={hiddenDim:this.config.hiddenDim,embeddingDim:this.config.embeddingDim,microLoraRank:this.config.microLoraRank,baseLoraRank:this.config.baseLoraRank,microLoraLr:this.config.microLoraLr,baseLoraLr:this.config.baseLoraLr,ewcLambda:this.config.ewcLambda,patternClusters:this.config.patternClusters,trajectoryCapacity:this.config.trajectoryCapacity,backgroundIntervalMs:this.config.backgroundIntervalMs,qualityThreshold:this.config.qualityThreshold,enableSimd:this.config.enableSimd};this.engine=P.withConfig(e),this.registry=new Q(this.config.maxPatterns??1e4)}async adaptPattern(t,e,r){let a=performance.now();try{let n=this.createStateEmbedding(t),o=this.engine.findPatterns(n,5),i=[];for(let m of o){let g=this.findByRawPattern(m);if(g||(g=this.createQEPatternFromRaw(m,e,r)),g.type===e&&g.domain===r&&g.confidence>=(this.config.minConfidence??.5)){let h=this.calculateSimilarity(n,m.centroid);i.push({pattern:g,similarity:h})}}if(i.length===0){let m=performance.now()-a;return this.recordAdaptation(m),{success:!1,pattern:null,adaptationTimeMs:m,similarity:0,reasoning:"No suitable pattern found"}}let s=i[0],u={...s.pattern,usageCount:s.pattern.usageCount+1,lastUsedAt:new Date};this.registry.update(u.id,u);let c=performance.now()-a;return this.recordAdaptation(c),{success:!0,pattern:u,adaptationTimeMs:c,similarity:s.similarity,reasoning:`Pattern adapted from @ruvector/sona with ${s.similarity.toFixed(3)} similarity`}}catch(n){let o=performance.now()-a;return this.recordAdaptation(o),{success:!1,pattern:null,adaptationTimeMs:o,similarity:0,reasoning:`Adaptation failed: ${n.message}`}}}recallPattern(t,e,r){let a=this.createStateEmbedding(t),n=this.engine.findPatterns(a,1);for(let o of n){let i=this.findByRawPattern(o);if(i&&i.type===e&&i.domain===r)return i}return null}storePattern(t){this.registry.register(t);let e=this.engine.beginTrajectory(t.stateEmbedding),r=this.createActionEmbedding(t.action),a=new Array(r.length).fill(1),n=t.outcome.success?t.outcome.quality:-t.outcome.quality;this.engine.addTrajectoryStep(e,r,a,n),this.engine.endTrajectory(e,t.outcome.quality),this.registry.associateTrajectory(e,t.id)}storePatternsBatch(t){for(let e of t)this.storePattern(e)}createPattern(t,e,r,a,n,o){let i={id:`qesona-${Date.now()}-${Ct().slice(0,7)}`,type:a,domain:n,stateEmbedding:this.createStateEmbedding(t),action:e,outcome:r,confidence:.5,usageCount:0,createdAt:new Date,metadata:o};return this.storePattern(i),i}updatePattern(t,e,r){let a=this.registry.get(t);if(!a)return!1;let n=e?r:-r,i=a.confidence+.1*(n-a.confidence),s={...a,confidence:Math.max(0,Math.min(1,i)),usageCount:a.usageCount+1,lastUsedAt:new Date};return this.registry.update(t,s)}applyMicroLora(t){return this.engine.applyMicroLora(t)}applyBaseLora(t,e){return this.engine.applyBaseLora(t,e)}forceLearn(){return this.engine.forceLearn()}tick(){return this.engine.tick()}getAllPatterns(){return this.registry.getAll()}getPatternsByType(t){return this.registry.getByType(t)}getPatternsByDomain(t){return this.registry.getByDomain(t)}getStats(){let t=this.registry.getAll(),e=this.engine.getStats(),r={"test-generation":0,"defect-prediction":0,"coverage-optimization":0,"quality-assessment":0,"resource-allocation":0};for(let a of t)r[a.type]++;return{totalPatterns:t.length,patternsByType:r,avgAdaptationTimeMs:this.avgAdaptationTime(),minAdaptationTimeMs:this.minAdaptationTime(),maxAdaptationTimeMs:this.maxAdaptationTime(),totalAdaptations:this.totalAdaptations,cacheHitRate:this.totalAdaptations>0?this.cacheHits/this.totalAdaptations:0,engineStats:e}}clear(){this.registry.clear(),this.adaptationTimes=[],this.cacheHits=0,this.totalAdaptations=0}exportPatterns(){return this.registry.getAll()}importPatterns(t){this.clear(),this.storePatternsBatch(t)}getConfig(){return{...this.config}}setEnabled(t){this.engine.setEnabled(t)}isEnabled(){return this.engine.isEnabled()}createStateEmbedding(t){let e=t.features;if(e.length===0)return new Array(this.config.embeddingDim??384).fill(0);let r=Math.max(...e.map(Math.abs));if(r===0)return[...e];let a=e.map(o=>o/r),n=this.config.embeddingDim??384;return a.length>=n?a.slice(0,n):[...a,...new Array(n-a.length).fill(0)]}createActionEmbedding(t){let e=[],r=this.hashCode(t.type);if(e.push(r%1e3/1e3),typeof t.value=="number")e.push(Math.min(1,Math.max(-1,t.value)));else if(typeof t.value=="string"){let n=this.hashCode(t.value);e.push(n%1e3/1e3)}else if(Array.isArray(t.value))for(let n of t.value.slice(0,10))typeof n=="number"&&e.push(Math.min(1,Math.max(-1,n)));let a=this.config.embeddingDim??384;for(;e.length<a;)e.push(0);return e.slice(0,a)}findByRawPattern(t){let e=this.registry.getAll();for(let r of e)if(r.rawPattern?.patternType===t.id)return r}createQEPatternFromRaw(t,e,r){let a={centroid:t.centroid,clusterSize:1,totalWeight:1,avgQuality:t.avgQuality,createdAt:new Date().toISOString(),lastAccessed:new Date().toISOString(),accessCount:0,patternType:t.patternType};return{id:`qesona-${t.id}`,type:e,domain:r,stateEmbedding:t.centroid,action:{type:"learned",value:t.patternType},outcome:{reward:t.avgQuality,success:t.avgQuality>.5,quality:t.avgQuality},confidence:t.avgQuality,usageCount:0,createdAt:new Date,rawPattern:a}}calculateSimilarity(t,e){let r=Math.min(t.length,e.length),a=0,n=0,o=0;for(let s=0;s<r;s++)a+=t[s]*e[s],n+=t[s]*t[s],o+=e[s]*e[s];return(a/(Math.sqrt(n)*Math.sqrt(o)+1e-10)+1)/2}hashCode(t){let e=0;for(let r=0;r<t.length;r++)e=(e<<5)-e+t.charCodeAt(r),e=e|0;return Math.abs(e)}recordAdaptation(t){this.adaptationTimes.push(t),this.totalAdaptations++,this.adaptationTimes.length>1e3&&this.adaptationTimes.shift()}avgAdaptationTime(){return this.adaptationTimes.length===0?0:this.adaptationTimes.reduce((e,r)=>e+r,0)/this.adaptationTimes.length}minAdaptationTime(){return this.adaptationTimes.length===0?0:Math.min(...this.adaptationTimes)}maxAdaptationTime(){return this.adaptationTimes.length===0?0:Math.max(...this.adaptationTimes)}initThreeLoopEngine(t){this.threeLoopEngine=new C({dimension:this.config.embeddingDim??384,microLoraLr:this.config.microLoraLr??.001,ewcLambda:this.config.ewcLambda??1e3,...t},this.engine)}getThreeLoopEngine(){return this.threeLoopEngine}instantAdapt(t){return this.threeLoopEngine?this.threeLoopEngine.instantAdapt(t):null}recordOutcome(t,e){this.threeLoopEngine&&this.threeLoopEngine.recordOutcome(t,e)}backgroundConsolidate(){if(!this.threeLoopEngine)return null;let t=this.threeLoopEngine.backgroundConsolidate();if(t&&(t.consolidated||t.taskBoundaryDetected)&&this.fisherPersistFn)try{this.threeLoopEngine.persistFisher(this.fisherPersistFn,this.fisherDomain)}catch(e){console.warn("[QESONA] Fisher persistence failed:",e instanceof Error?e.message:e)}return t}setFisherPersistence(t,e){this.fisherPersistFn=t,this.fisherDomain=e}syncWithPeers(t){this.threeLoopEngine&&this.threeLoopEngine.syncWithPeers(t)}getEWCMetrics(){return this.threeLoopEngine?this.threeLoopEngine.getEWCMetrics():null}shouldConsolidate(){return this.threeLoopEngine?this.threeLoopEngine.shouldConsolidate():!1}getLocalPeerState(t,e){return this.threeLoopEngine?this.threeLoopEngine.getLocalPeerState(t,e):null}isThreeLoopEnabled(){return this.threeLoopEngine!==null}async verifyPerformance(t=1e3){let e=[],r={id:"test-state",features:new Array(384).fill(0).map(()=>G())};for(let s=0;s<t;s++){let u=performance.now();await this.adaptPattern(r,"test-generation","test-generation");let c=performance.now();e.push({iteration:s,timeMs:c-u})}let a=e.map(s=>s.timeMs),n=a.reduce((s,u)=>s+u,0)/a.length,o=Math.min(...a),i=Math.max(...a);return{targetMet:n<.05,avgTimeMs:n,minTimeMs:o,maxTimeMs:i,details:e}}};function Tt(l){return new v(l)}function Pt(l,t){return new v({...t,maxPatterns:t?.maxPatterns||5e3})}ot();et();var F=null,D=null,W=null,B=null,z=null,I=null,q=!1;try{let l=(O(),w(N));F=l.FlashAttention,D=l.DotProductAttention,W=l.MultiHeadAttention,B=l.HyperbolicAttention,z=l.LinearAttention,I=l.MoEAttention,q=!0}catch{}function Gt(){return q}function A(){if(!q)throw new Error("@ruvector/attention native module is not available on this platform. Install the appropriate optional dependency for your platform, or use a platform where pre-built binaries are available.")}var T={"test-similarity":{dim:384,strategy:"flash",blockSize:64},"code-embedding":{dim:512,strategy:"flash",blockSize:128},"defect-matching":{dim:384,strategy:"flash",blockSize:64},"coverage-analysis":{dim:384,strategy:"flash",blockSize:256},"pattern-adaptation":{dim:256,strategy:"flash",blockSize:32}},Kt={"test-similarity":{enabled:!0,microLoRARank:4,targetAdaptationMs:.05,patternCacheSize:1e3},"code-embedding":{enabled:!0,microLoRARank:2,targetAdaptationMs:.03,patternCacheSize:5e3},"defect-matching":{enabled:!0,microLoRARank:8,targetAdaptationMs:.05,patternCacheSize:2e3},"coverage-analysis":{enabled:!1,microLoRARank:2,targetAdaptationMs:.01,patternCacheSize:100},"pattern-adaptation":{enabled:!0,microLoRARank:2,targetAdaptationMs:.05,patternCacheSize:1e4}},$t={"test-similarity":{latency:{before:50,after:15},memory:{before:200,after:80},throughput:{min:1e3}},"code-embedding":{latency:{before:50,after:15},memory:{before:200,after:80},throughput:{min:2e3}},"defect-matching":{latency:{before:20,after:5},memory:{before:150,after:50},throughput:{min:500}},"coverage-analysis":{latency:{before:100,after:1},memory:{before:100,after:30},throughput:{min:1e4}},"pattern-adaptation":{latency:{before:2,after:.05},memory:{before:50,after:20},throughput:{min:2e4}}};function Zt(l){return l<=128?{queryChunkSize:128,kvChunkSize:128}:l<=256?{queryChunkSize:256,kvChunkSize:256}:l<=512?{queryChunkSize:512,kvChunkSize:512}:l<=1024?{queryChunkSize:1024,kvChunkSize:1024}:{queryChunkSize:1024,kvChunkSize:2048}}var E=class{static create(t){switch(A(),t.strategy){case"flash":return new F(t.dim,t.blockSize);case"dot-product":return new D(t.dim);case"multi-head":return new W(t.dim,t.numHeads??8);case"hyperbolic":return new B(t.dim,t.curvature);case"linear":return new z(t.dim,t.features);case"moe":return I.simple(t.dim,t.moeConfig?.numExperts??8,t.moeConfig?.topK??2);default:return new F(t.dim,t.blockSize)}}},L=class l{attention;config;workload;metrics=[];db=null;persistCount=0;static KV_NAMESPACE="attention-metrics";static KV_TTL=3600;static PERSIST_INTERVAL=10;constructor(t,e){this.workload=t;let r=T[t];this.config={...r,...e},this.attention=E.create(this.config)}async initialize(){try{this.db=K(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(t){console.warn("[QEFlashAttention] DB init failed, using memory-only:",j(t)),this.db=null}}async computeFlashAttention(t,e,r,a,n){let o=performance.now(),i=process.memoryUsage().heapUsed/1024/1024,s=this.toFloat32Array(t,a,n),u=this.splitMatrix(e,a,n),c=this.splitMatrix(r,a,n),m,g=this.attention;typeof g.compute=="function"?m=g.compute(s,u,c):(A(),m=new F(this.config.dim).compute(s,u,c));let h=performance.now(),d=process.memoryUsage().heapUsed/1024/1024;return this.metrics.push({timeMs:h-o,memoryMB:d-i,speedup:1,throughput:a*a/((h-o)/1e3),peakMemoryMB:d}),this.maybePersistToKv(),m}async computeBaselineAttention(t,e,r,a,n){let o=performance.now(),i=process.memoryUsage().heapUsed/1024/1024,s=new Float32Array(a*a),u=1/Math.sqrt(n);for(let h=0;h<a;h++)for(let d=0;d<a;d++){let b=0;for(let p=0;p<n;p++)b+=t[h*n+p]*e[d*n+p];s[h*a+d]=b*u}for(let h=0;h<a;h++){let d=h*a,b=d+a,p=s.subarray(d,b),tt=Math.max(...p),_=0;for(let y=0;y<a;y++)p[y]=Math.exp(p[y]-tt),_+=p[y];for(let y=0;y<a;y++)p[y]/=_}let c=new Float32Array(a*n);for(let h=0;h<a;h++)for(let d=0;d<a;d++){let b=s[h*a+d];for(let p=0;p<n;p++)c[h*n+p]+=b*r[d*n+p]}let m=performance.now(),g=process.memoryUsage().heapUsed/1024/1024;return c}async computeTestSimilarity(t,e,r=5){let a=e.length,n=t.length,o=new Float32Array(a*n),i=new Float32Array(a*n);for(let m=0;m<a;m++)o.set(t,m*n),i.set(e[m],m*n);let s=new Float32Array(a*n),u=await this.computeFlashAttention(o,i,s,a,n),c=[];for(let m=0;m<a;m++)c.push({index:m,similarity:u[m*n]});return c.sort((m,g)=>g.similarity-m.similarity),c.slice(0,r)}async generateCodeEmbedding(t,e){let r=t.length/e.length,a=e.length;return await this.computeFlashAttention(t,e,t,r,a)}async matchDefectPattern(t,e){let r=e.length,a=t.length,n=new Float32Array(r*a),o=new Float32Array(r*a);for(let c=0;c<r;c++)n.set(t,c*a),o.set(e[c],c*a);let i=new Float32Array(r*a),s=await this.computeFlashAttention(n,o,i,r,a),u=[];for(let c=0;c<r;c++)u.push({pattern:c,score:s[c*a]});return u.sort((c,m)=>m.score-c.score),u}getMetrics(){return[...this.metrics]}getAverageSpeedup(){return this.metrics.length===0?1:this.metrics.reduce((t,e)=>t+e.speedup,0)/this.metrics.length}getConfig(){return{...this.config}}updateConfig(t){this.config={...this.config,...t},this.attention=E.create(this.config)}changeStrategy(t){this.config.strategy=t,this.attention=E.create(this.config)}resetMetrics(){this.metrics=[]}getWorkload(){return this.workload}dispose(){this.metrics=[]}async persistToKv(){if(!this.db)return;let t=`attention-metrics-${this.workload}`,e={workload:this.workload,metrics:this.metrics.slice(-50),savedAt:Date.now()};await this.db.kvSet(t,e,l.KV_NAMESPACE,l.KV_TTL)}async loadFromKv(){if(!this.db)return;let t=`attention-metrics-${this.workload}`,e=await this.db.kvGet(t,l.KV_NAMESPACE);e?.metrics?.length&&(this.metrics=e.metrics)}maybePersistToKv(){this.persistCount++,this.persistCount>=l.PERSIST_INTERVAL&&(this.persistCount=0,this.persistToKv().catch(()=>{}))}toFloat32Array(t,e,r){return t.slice(0,r)}splitMatrix(t,e,r){let a=[];for(let n=0;n<e;n++)a.push(t.slice(n*r,(n+1)*r));return a}};async function Y(l,t){let e=new L(l,t);return await e.initialize(),e}function Jt(l){return{...T[l]}}function Xt(){return Object.keys(T)}function Yt(){return A(),F}function te(){return A(),D}function ee(){return A(),W}function re(){return A(),B}function ae(){return A(),z}function ne(){return A(),I}function ie(l){return l instanceof Float32Array?l:new Float32Array(l)}function oe(l){return Array.from(l)}async function se(l,t,e,r){let a=await Y(l),n=[],o=t[0].length,i=e.length;for(let s of t){let u=new Float32Array(i*o),c=new Float32Array(i*o),m=new Float32Array(i*o);u.set(s,0);for(let h=0;h<i;h++)c.set(e[h],h*o),m.set(r[h],h*o);let g=await a.computeFlashAttention(u,c,m,i,o);n.push(g.slice(0,o))}return a.dispose(),n}function We(){return{"@ruvector/sona":"^0.1.5","@ruvector/attention":"^0.1.4","@ruvector/gnn":"^0.1.22"}}function Be(){let l={sona:!1,attention:!1,gnn:!1,all:!1};try{k(),l.sona=!0}catch{}try{O(),l.attention=!0}catch{}try{let t=(it(),w(nt));t.init();let e=new Float32Array([.1,.2,.3]),r=[new Float32Array([.1,.2,.3]),new Float32Array([.4,.5,.6])],a=t.differentiableSearch(e,r,1,1);a&&Array.isArray(a.indices)&&Array.isArray(a.weights)&&(l.gnn=!0)}catch{}return l.all=l.sona&&l.attention&&l.gnn,l}async function ze(){let{initGNN:l}=await import("./gnn-wrapper-Z45DRWGI.js");return[l(),"SONA: Ready (no initialization required)","Attention: Ready (no initialization required)"]}export{v as a,Tt as b,Pt as c,Gt as d,T as e,Kt as f,$t as g,Zt as h,L as i,Y as j,Jt as k,Xt as l,Yt as m,te as n,ee as o,re as p,ae as q,ne as r,ie as s,oe as t,se as u,We as v,Be as w,ze as x};
@@ -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.14");process.exit(0)}
2
- import{a as l}from"./chunk-2L3BCZ2F.js";import{a as m}from"./chunk-PZF5ISGS.js";import{f as a}from"./chunk-G7L5Y47C.js";var u=class{constructor(t,e){this.eventBus=t;this.maxHistorySize=e?.maxHistorySize??1e4,this.eventHistory=new l(this.maxHistorySize),this.correlationTimeout=e?.correlationTimeout??6e4,this.maxEventsPerCorrelation=e?.maxEventsPerCorrelation??100}eventBus;subscriptions=new Map;correlations=new Map;eventHistory;routes=[];domainSubscriptions=new Map;maxHistorySize;correlationTimeout;maxEventsPerCorrelation;initialized=!1;async initialize(){if(!this.initialized){for(let t of m){let e=this.eventBus.subscribeToChannel(t,async i=>{await this.handleIncomingEvent(i)});this.domainSubscriptions.set(t,e)}this.eventBus.subscribe("*",async t=>{m.includes(t.source)||await this.handleIncomingEvent(t)}),this.initialized=!0}}subscribeToDoamin(t,e){let i=`sub_domain_${a()}`;return this.subscriptions.set(i,{id:i,type:"domain",filter:t,handler:e,active:!0}),i}subscribeToEventType(t,e){let i=`sub_type_${a()}`;return this.subscriptions.set(i,{id:i,type:"eventType",filter:t,handler:e,active:!0}),i}unsubscribe(t){let e=this.subscriptions.get(t);return e?(e.active=!1,this.subscriptions.delete(t),!0):!1}async route(t){this.addToHistory(t),t.correlationId&&this.trackCorrelation(t);let i=this.findMatchingSubscriptions(t).map(async o=>{try{await o.handler(t)}catch(n){console.error(`Error in subscription handler ${o.id}:`,n instanceof Error?n.message:n)}}),r=await this.applyRoutes(t);await Promise.allSettled([...i,...r])}getCorrelation(t){let e=this.correlations.get(t);if(e)return{correlationId:e.correlationId,events:[...e.events],domains:new Set(e.domains),startedAt:e.startedAt,lastEventAt:e.lastEventAt,complete:e.complete}}trackCorrelation(t){if(!t.correlationId)return;let e=this.correlations.get(t.correlationId);e||(e={correlationId:t.correlationId,events:[],domains:new Set,startedAt:t.timestamp,lastEventAt:t.timestamp,complete:!1,timeout:null},this.correlations.set(t.correlationId,e)),e.events.length<this.maxEventsPerCorrelation&&(e.events.push(t),e.domains.add(t.source),e.lastEventAt=t.timestamp),e.timeout&&clearTimeout(e.timeout),e.timeout=setTimeout(()=>{e.complete=!0,e.timeout=null},this.correlationTimeout)}aggregate(t,e){let i=this.eventHistory.toArray().filter(s=>s.timestamp>=t&&s.timestamp<=e),r=new Map,o=new Map;for(let s of i)r.set(s.type,(r.get(s.type)??0)+1),o.set(s.source,(o.get(s.source)??0)+1);let n={totalEvents:i.length,uniqueEventTypes:r.size,uniqueDomains:o.size,eventsPerSecond:i.length>0?i.length/((e.getTime()-t.getTime())/1e3):0};return{id:a(),windowStart:t,windowEnd:e,events:i,countByType:r,countByDomain:o,metrics:n}}getHistory(t){let e=this.eventHistory.toArray();return t&&(t.eventTypes?.length&&(e=e.filter(i=>t.eventTypes.includes(i.type))),t.domains?.length&&(e=e.filter(i=>t.domains.includes(i.source))),t.fromTimestamp&&(e=e.filter(i=>i.timestamp>=t.fromTimestamp)),t.toTimestamp&&(e=e.filter(i=>i.timestamp<=t.toTimestamp)),t.limit&&(e=e.slice(-t.limit))),e}addRoute(t){let e=t.priority??0,i=this.routes.findIndex(r=>(r.priority??0)<e);i===-1?this.routes.push(t):this.routes.splice(i,0,t)}removeRoute(t,e){let i=this.routes.findIndex(r=>r.eventPattern===t&&(e===void 0||r.source===e));return i!==-1?(this.routes.splice(i,1),!0):!1}async dispose(){this.subscriptions.clear();for(let t of this.domainSubscriptions.values())t.unsubscribe();this.domainSubscriptions.clear();for(let t of this.correlations.values())t.timeout&&clearTimeout(t.timeout);this.correlations.clear(),this.eventHistory.clear(),this.initialized=!1}async handleIncomingEvent(t){await this.route(t)}findMatchingSubscriptions(t){let e=[];for(let i of this.subscriptions.values())i.active&&(i.type==="domain"&&i.filter===t.source||i.type==="eventType"&&this.matchEventType(t.type,i.filter))&&e.push(i);return e}matchEventType(t,e){if(e==="*")return!0;let i=e.replace(/\\/g,"\\\\").replace(/\./g,"\\.").replace(/\*/g,".*");return new RegExp(`^${i}$`).test(t)}async applyRoutes(t){let e=[];for(let i of this.routes){if(!(i.source==="*"||i.source===t.source||Array.isArray(i.source)&&i.source.includes(t.source))||!this.matchEventType(t.type,i.eventPattern)||i.filter&&!i.filter(t))continue;let o=i.transform?i.transform(t):t;for(let n of i.targets)n!==t.source&&e.push(this.eventBus.publish({...o,id:a(),correlationId:t.correlationId??t.id}))}return e}addToHistory(t){this.eventHistory.push(t)}};function y(c,t){return new u(c,t)}export{u as a,y 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.15");process.exit(0)}
2
+ import{a as l}from"./chunk-ICXWXO5P.js";import{a as m}from"./chunk-FW6QBTPE.js";import{f as a}from"./chunk-MBDX4OHD.js";var u=class{constructor(t,e){this.eventBus=t;this.maxHistorySize=e?.maxHistorySize??1e4,this.eventHistory=new l(this.maxHistorySize),this.correlationTimeout=e?.correlationTimeout??6e4,this.maxEventsPerCorrelation=e?.maxEventsPerCorrelation??100}eventBus;subscriptions=new Map;correlations=new Map;eventHistory;routes=[];domainSubscriptions=new Map;maxHistorySize;correlationTimeout;maxEventsPerCorrelation;initialized=!1;async initialize(){if(!this.initialized){for(let t of m){let e=this.eventBus.subscribeToChannel(t,async i=>{await this.handleIncomingEvent(i)});this.domainSubscriptions.set(t,e)}this.eventBus.subscribe("*",async t=>{m.includes(t.source)||await this.handleIncomingEvent(t)}),this.initialized=!0}}subscribeToDoamin(t,e){let i=`sub_domain_${a()}`;return this.subscriptions.set(i,{id:i,type:"domain",filter:t,handler:e,active:!0}),i}subscribeToEventType(t,e){let i=`sub_type_${a()}`;return this.subscriptions.set(i,{id:i,type:"eventType",filter:t,handler:e,active:!0}),i}unsubscribe(t){let e=this.subscriptions.get(t);return e?(e.active=!1,this.subscriptions.delete(t),!0):!1}async route(t){this.addToHistory(t),t.correlationId&&this.trackCorrelation(t);let i=this.findMatchingSubscriptions(t).map(async o=>{try{await o.handler(t)}catch(n){console.error(`Error in subscription handler ${o.id}:`,n instanceof Error?n.message:n)}}),r=await this.applyRoutes(t);await Promise.allSettled([...i,...r])}getCorrelation(t){let e=this.correlations.get(t);if(e)return{correlationId:e.correlationId,events:[...e.events],domains:new Set(e.domains),startedAt:e.startedAt,lastEventAt:e.lastEventAt,complete:e.complete}}trackCorrelation(t){if(!t.correlationId)return;let e=this.correlations.get(t.correlationId);e||(e={correlationId:t.correlationId,events:[],domains:new Set,startedAt:t.timestamp,lastEventAt:t.timestamp,complete:!1,timeout:null},this.correlations.set(t.correlationId,e)),e.events.length<this.maxEventsPerCorrelation&&(e.events.push(t),e.domains.add(t.source),e.lastEventAt=t.timestamp),e.timeout&&clearTimeout(e.timeout),e.timeout=setTimeout(()=>{e.complete=!0,e.timeout=null},this.correlationTimeout)}aggregate(t,e){let i=this.eventHistory.toArray().filter(s=>s.timestamp>=t&&s.timestamp<=e),r=new Map,o=new Map;for(let s of i)r.set(s.type,(r.get(s.type)??0)+1),o.set(s.source,(o.get(s.source)??0)+1);let n={totalEvents:i.length,uniqueEventTypes:r.size,uniqueDomains:o.size,eventsPerSecond:i.length>0?i.length/((e.getTime()-t.getTime())/1e3):0};return{id:a(),windowStart:t,windowEnd:e,events:i,countByType:r,countByDomain:o,metrics:n}}getHistory(t){let e=this.eventHistory.toArray();return t&&(t.eventTypes?.length&&(e=e.filter(i=>t.eventTypes.includes(i.type))),t.domains?.length&&(e=e.filter(i=>t.domains.includes(i.source))),t.fromTimestamp&&(e=e.filter(i=>i.timestamp>=t.fromTimestamp)),t.toTimestamp&&(e=e.filter(i=>i.timestamp<=t.toTimestamp)),t.limit&&(e=e.slice(-t.limit))),e}addRoute(t){let e=t.priority??0,i=this.routes.findIndex(r=>(r.priority??0)<e);i===-1?this.routes.push(t):this.routes.splice(i,0,t)}removeRoute(t,e){let i=this.routes.findIndex(r=>r.eventPattern===t&&(e===void 0||r.source===e));return i!==-1?(this.routes.splice(i,1),!0):!1}async dispose(){this.subscriptions.clear();for(let t of this.domainSubscriptions.values())t.unsubscribe();this.domainSubscriptions.clear();for(let t of this.correlations.values())t.timeout&&clearTimeout(t.timeout);this.correlations.clear(),this.eventHistory.clear(),this.initialized=!1}async handleIncomingEvent(t){await this.route(t)}findMatchingSubscriptions(t){let e=[];for(let i of this.subscriptions.values())i.active&&(i.type==="domain"&&i.filter===t.source||i.type==="eventType"&&this.matchEventType(t.type,i.filter))&&e.push(i);return e}matchEventType(t,e){if(e==="*")return!0;let i=e.replace(/\\/g,"\\\\").replace(/\./g,"\\.").replace(/\*/g,".*");return new RegExp(`^${i}$`).test(t)}async applyRoutes(t){let e=[];for(let i of this.routes){if(!(i.source==="*"||i.source===t.source||Array.isArray(i.source)&&i.source.includes(t.source))||!this.matchEventType(t.type,i.eventPattern)||i.filter&&!i.filter(t))continue;let o=i.transform?i.transform(t):t;for(let n of i.targets)n!==t.source&&e.push(this.eventBus.publish({...o,id:a(),correlationId:t.correlationId??t.id}))}return e}addToHistory(t){this.eventHistory.push(t)}};function y(c,t){return new u(c,t)}export{u as a,y as b};
@@ -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.14");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.15");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.14");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.15");process.exit(0)}
2
2
  function c(r,e,o){let n=new Error(r);return n.name="LLMError",n.code=e,n.provider=o?.provider,n.model=o?.model,n.retryable=o?.retryable??!1,n.retryAfterMs=o?.retryAfterMs,n.cause=o?.cause,n}function p(r){return r instanceof Error&&"code"in r&&typeof r.code=="string"}var a={"claude-sonnet-4-5":{canonical:"Claude Sonnet 4.5",family:"claude",tier:"standard",providers:{anthropic:"claude-sonnet-4-5-20250929",openrouter:"anthropic/claude-sonnet-4.5",bedrock:"anthropic.claude-sonnet-4-5-v2:0"}},"claude-opus-4":{canonical:"Claude Opus 4",family:"claude",tier:"flagship",providers:{anthropic:"claude-opus-4-20250514",openrouter:"anthropic/claude-opus-4",bedrock:"anthropic.claude-opus-4-v1:0"}},"claude-opus-4-5":{canonical:"Claude Opus 4.5",family:"claude",tier:"flagship",providers:{anthropic:"claude-opus-4-5-20251101",openrouter:"anthropic/claude-opus-4.5",bedrock:"anthropic.claude-opus-4-5-v1:0"}},"claude-haiku-3-5":{canonical:"Claude Haiku 3.5",family:"claude",tier:"economy",providers:{anthropic:"claude-3-5-haiku-20241022",openrouter:"anthropic/claude-3.5-haiku",bedrock:"anthropic.claude-3-5-haiku-v1:0"}},"claude-sonnet-4":{canonical:"Claude Sonnet 4",family:"claude",tier:"standard",providers:{anthropic:"claude-sonnet-4-20250514",openrouter:"anthropic/claude-sonnet-4",bedrock:"anthropic.claude-sonnet-4-v1:0"}},"claude-opus-4-7":{canonical:"Claude Opus 4.7",family:"claude",tier:"flagship",providers:{anthropic:"claude-opus-4-7",openrouter:"anthropic/claude-opus-4.7",bedrock:"anthropic.claude-opus-4-7-v1:0"}},"claude-sonnet-4-6":{canonical:"Claude Sonnet 4.6",family:"claude",tier:"standard",providers:{anthropic:"claude-sonnet-4-6",openrouter:"anthropic/claude-sonnet-4.6",bedrock:"anthropic.claude-sonnet-4-6-v1:0"}},"claude-haiku-4-5":{canonical:"Claude Haiku 4.5",family:"claude",tier:"economy",providers:{anthropic:"claude-haiku-4-5-20251001",openrouter:"anthropic/claude-haiku-4.5",bedrock:"anthropic.claude-haiku-4-5-v1:0"}},"gpt-4o":{canonical:"GPT-4o",family:"gpt",tier:"standard",providers:{openai:"gpt-4o",azure:"gpt-4o",openrouter:"openai/gpt-4o"}},"gpt-4o-mini":{canonical:"GPT-4o Mini",family:"gpt",tier:"economy",providers:{openai:"gpt-4o-mini",azure:"gpt-4o-mini",openrouter:"openai/gpt-4o-mini"}},"gpt-4-turbo":{canonical:"GPT-4 Turbo",family:"gpt",tier:"premium",providers:{openai:"gpt-4-turbo",azure:"gpt-4-turbo",openrouter:"openai/gpt-4-turbo"}},"gpt-4":{canonical:"GPT-4",family:"gpt",tier:"premium",providers:{openai:"gpt-4",azure:"gpt-4",openrouter:"openai/gpt-4"}},o1:{canonical:"OpenAI o1",family:"gpt",tier:"flagship",providers:{openai:"o1",azure:"o1",openrouter:"openai/o1"}},"o1-mini":{canonical:"OpenAI o1 Mini",family:"gpt",tier:"standard",providers:{openai:"o1-mini",azure:"o1-mini",openrouter:"openai/o1-mini"}},"gemini-pro":{canonical:"Gemini Pro",family:"gemini",tier:"standard",providers:{gemini:"gemini-pro",openrouter:"google/gemini-pro"}},"gemini-pro-1.5":{canonical:"Gemini Pro 1.5",family:"gemini",tier:"standard",providers:{gemini:"gemini-1.5-pro",openrouter:"google/gemini-pro-1.5"}},"gemini-flash-1.5":{canonical:"Gemini Flash 1.5",family:"gemini",tier:"economy",providers:{gemini:"gemini-1.5-flash",openrouter:"google/gemini-flash-1.5"}},"gemini-ultra":{canonical:"Gemini Ultra",family:"gemini",tier:"flagship",providers:{gemini:"gemini-ultra",openrouter:"google/gemini-ultra"}},llama3:{canonical:"Llama 3",family:"llama",tier:"economy",providers:{ollama:"llama3",openrouter:"meta-llama/llama-3-8b-instruct"}},"llama3.1":{canonical:"Llama 3.1",family:"llama",tier:"economy",providers:{ollama:"llama3.1",openrouter:"meta-llama/llama-3.1-8b-instruct"}},codellama:{canonical:"CodeLlama",family:"llama",tier:"economy",providers:{ollama:"codellama",openrouter:"meta-llama/codellama-34b-instruct"}},mistral:{canonical:"Mistral",family:"mistral",tier:"economy",providers:{ollama:"mistral",openrouter:"mistralai/mistral-7b-instruct"}},mixtral:{canonical:"Mixtral",family:"mistral",tier:"standard",providers:{ollama:"mixtral",openrouter:"mistralai/mixtral-8x7b-instruct"}},phi3:{canonical:"Phi-3",family:"phi",tier:"economy",providers:{ollama:"phi3",azure:"phi-3-mini-128k-instruct"}},qwen2:{canonical:"Qwen 2",family:"qwen",tier:"economy",providers:{ollama:"qwen2",openrouter:"qwen/qwen-2-7b-instruct"}}};function l(){let r=new Map;for(let[e,o]of Object.entries(a)){r.set(e,e),r.set(e.toLowerCase(),e);for(let[n,t]of Object.entries(o.providers))t&&(r.set(t,e),r.set(t.toLowerCase(),e),r.set(`${n}/${t}`,e),r.set(`${n}/${t}`.toLowerCase(),e))}return r}var i=l();function m(r,e){let o=s(r),n=a[o];if(!n)throw new Error(`Unknown model: ${r}`);let t=n.providers[e];if(!t)throw new Error(`Model '${o}' (${n.canonical}) is not available on provider '${e}'`);return t}function s(r){let e=i.get(r);if(e||(e=i.get(r.toLowerCase()),e))return e;let o=[/^anthropic\//i,/^openai\//i,/^google\//i,/^meta-llama\//i,/^mistralai\//i,/^qwen\//i];for(let n of o){let t=r.replace(n,"");if(e=i.get(t),e||(e=i.get(t.toLowerCase()),e))return e}throw new Error(`Unknown model ID: ${r}`)}function d(r){try{let e=s(r);return a[e]}catch{return}}export{c as a,p as b,m as c,s as d,d as e};
@@ -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.14");process.exit(0)}
2
- import{a as I}from"./chunk-36YZ2UF7.js";import{n as F,o as q}from"./chunk-ZFZX2NA3.js";import{a as A,b as m,c as d}from"./chunk-PZF5ISGS.js";import{a as b,b as W,c as O}from"./chunk-UIYK4Y7K.js";import{f as D}from"./chunk-G7L5Y47C.js";import{g as T}from"./chunk-DGUAAG3T.js";O();var w={WorkflowStarted:"workflow.WorkflowStarted",WorkflowCompleted:"workflow.WorkflowCompleted",WorkflowFailed:"workflow.WorkflowFailed",WorkflowCancelled:"workflow.WorkflowCancelled",StepStarted:"workflow.StepStarted",StepCompleted:"workflow.StepCompleted",StepFailed:"workflow.StepFailed",StepSkipped:"workflow.StepSkipped",StepAwaitingApproval:"workflow.StepAwaitingApproval",StepApproved:"workflow.StepApproved",StepRejected:"workflow.StepRejected"},E={maxConcurrentWorkflows:10,defaultStepTimeout:6e4,defaultWorkflowTimeout:6e5,enableEventTriggers:!0,persistExecutions:!0};function S(){try{let{getUnifiedMemory:s}=(q(),T(F)),e=s();return e.isInitialized()?e.getDatabase():null}catch{return null}}var N={id:"quality-gate-check",domain:"quality-assessment",action:"gate-check",async execute(s){let e=typeof s.coverageMin=="number"?s.coverageMin:80,t=typeof s.testsPassingMin=="number"?s.testsPassingMin:90,i=typeof s.maxBugs=="number"?s.maxBugs:5,r=typeof s.currentCoverage=="number"?s.currentCoverage:null,n=typeof s.currentTestsPassingRate=="number"?s.currentTestsPassingRate:null,o=typeof s.currentBugs=="number"?s.currentBugs:null;if(r===null||n===null||o===null){let p=S();if(p)try{if(r===null&&(r=p.prepare("SELECT after_lines FROM coverage_sessions ORDER BY created_at DESC LIMIT 1").get()?.after_lines??0),n===null){let y=p.prepare(`SELECT COUNT(*) as total,
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.15");process.exit(0)}
2
+ import{a as I}from"./chunk-ZOAPOVYW.js";import{n as F,o as q}from"./chunk-LLVS3UYZ.js";import{a as A,b as m,c as d}from"./chunk-FW6QBTPE.js";import{a as b,b as W,c as O}from"./chunk-JJDHD7SC.js";import{f as D}from"./chunk-MBDX4OHD.js";import{g as T}from"./chunk-CUQBOVRP.js";O();var w={WorkflowStarted:"workflow.WorkflowStarted",WorkflowCompleted:"workflow.WorkflowCompleted",WorkflowFailed:"workflow.WorkflowFailed",WorkflowCancelled:"workflow.WorkflowCancelled",StepStarted:"workflow.StepStarted",StepCompleted:"workflow.StepCompleted",StepFailed:"workflow.StepFailed",StepSkipped:"workflow.StepSkipped",StepAwaitingApproval:"workflow.StepAwaitingApproval",StepApproved:"workflow.StepApproved",StepRejected:"workflow.StepRejected"},E={maxConcurrentWorkflows:10,defaultStepTimeout:6e4,defaultWorkflowTimeout:6e5,enableEventTriggers:!0,persistExecutions:!0};function S(){try{let{getUnifiedMemory:s}=(q(),T(F)),e=s();return e.isInitialized()?e.getDatabase():null}catch{return null}}var N={id:"quality-gate-check",domain:"quality-assessment",action:"gate-check",async execute(s){let e=typeof s.coverageMin=="number"?s.coverageMin:80,t=typeof s.testsPassingMin=="number"?s.testsPassingMin:90,i=typeof s.maxBugs=="number"?s.maxBugs:5,r=typeof s.currentCoverage=="number"?s.currentCoverage:null,n=typeof s.currentTestsPassingRate=="number"?s.currentTestsPassingRate:null,o=typeof s.currentBugs=="number"?s.currentBugs:null;if(r===null||n===null||o===null){let p=S();if(p)try{if(r===null&&(r=p.prepare("SELECT after_lines FROM coverage_sessions ORDER BY created_at DESC LIMIT 1").get()?.after_lines??0),n===null){let y=p.prepare(`SELECT COUNT(*) as total,
3
3
  SUM(CASE WHEN passed = 1 THEN 1 ELSE 0 END) as passed
4
4
  FROM test_outcomes
5
5
  WHERE created_at > datetime('now', '-7 days')`).get();n=y&&y.total>0?y.passed/y.total*100:0}o===null&&(o=p.prepare(`SELECT COUNT(*) as bugs FROM test_outcomes
@@ -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.14");process.exit(0)}
2
- import{a as M}from"./chunk-VQB5SLXZ.js";import{f as y,o as T}from"./chunk-ZFZX2NA3.js";import{a as p,c as S}from"./chunk-UIYK4Y7K.js";import{f as b}from"./chunk-G7L5Y47C.js";T();S();import*as c from"path";import*as d from"fs";var m=null,u=null,l=null;function R(o){l=o}async function P(){return m||u||(u=(async()=>{let o=y(),e=c.join(o,".agentic-qe");d.existsSync(e)||d.mkdirSync(e,{recursive:!0});let r=new M({sqlite:{path:c.join(e,"memory.db"),walMode:!0,poolSize:3,busyTimeout:5e3},enableFallback:!0,defaultNamespace:"mcp-tools"});return await r.initialize(),m=r,r})(),u)}function $(){if(l)try{l()}catch{}m&&(m.dispose().catch(()=>{}),m=null),u=null}async function D(o){return o?.memory?o.memory:P()}var C={info:(o,e)=>console.log(`[MCP-TOOL] ${o}`,e||""),warn:(o,e)=>console.warn(`[MCP-TOOL] \u26A0\uFE0F ${o}`,e||""),error:(o,e)=>console.error(`[MCP-TOOL] \u274C ${o}`,e||"")},h=class{logger=C;currentDataSource="real";setLogger(e){this.logger=e}markAsDemoData(e,r){this.currentDataSource=e.demoMode?"demo":"fallback",this.logger.warn(`${this.config.name} returning ${this.currentDataSource} data`,{reason:r,requestId:e.requestId,demoMode:e.demoMode})}markAsRealData(){this.currentDataSource="real"}isDemoMode(e){return e.demoMode===!0}validate(e){let r=[];if(typeof e!="object"||e===null)return{valid:!1,errors:["Parameters must be an object"]};let t=e,{properties:a,required:n}=this.config.schema;if(n)for(let i of n)i in t||r.push(`Missing required field: ${i}`);for(let[i,s]of Object.entries(t)){let g=a[i];if(!g)continue;let f=this.validateType(i,s,g);f&&r.push(f)}return{valid:r.length===0,errors:r}}validateType(e,r,t){if(r==null)return null;let a=Array.isArray(r)?"array":typeof r;if(t.type==="array"&&!Array.isArray(r))return`${e} must be an array`;if(t.type!=="array"&&a!==t.type)return`${e} must be of type ${t.type}, got ${a}`;if(t.enum&&!t.enum.includes(r))return`${e} must be one of: ${t.enum.join(", ")}`;if(t.type==="number"){let n=r;if(t.minimum!==void 0&&n<t.minimum)return`${e} must be >= ${t.minimum}`;if(t.maximum!==void 0&&n>t.maximum)return`${e} must be <= ${t.maximum}`}if(t.type==="string"){let n=r;if(t.minLength!==void 0&&n.length<t.minLength)return`${e} must be at least ${t.minLength} characters`;if(t.maxLength!==void 0&&n.length>t.maxLength)return`${e} must be at most ${t.maxLength} characters`}return null}async invoke(e,r={}){let t=Date.now(),a=b();this.currentDataSource="real";let n=this.validate(e);if(!n.valid)return{success:!1,error:`Validation failed: ${n.errors.join("; ")}`,metadata:this.createMetadata(t,a)};let i={requestId:a,startTime:t,streaming:r.streaming,onStream:r.onStream,abortSignal:r.abortSignal,demoMode:r.demoMode};try{let s=await this.execute(e,i);return{...s,metadata:{...s.metadata,...this.createMetadata(t,a)}}}catch(s){return{success:!1,error:p(s),metadata:this.createMetadata(t,a)}}}createMetadata(e,r){return{executionTime:Date.now()-e,timestamp:new Date().toISOString(),requestId:r,domain:this.config.domain,toolName:this.config.name,dataSource:this.currentDataSource}}emitStream(e,r){e.streaming&&e.onStream&&e.onStream(r)}isAborted(e){return e.abortSignal?.aborted??!1}get name(){return this.config.name}get description(){return this.config.description}get domain(){return this.config.domain}getSchema(){return this.config.schema}get timeout(){return this.config.timeout??6e4}get supportsStreaming(){return this.config.streaming??!1}resetInstanceCache(){}};export{R as a,P as b,$ as c,D as d,C as e,h as f};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.15");process.exit(0)}
2
+ import{a as M}from"./chunk-MO4Q5ZGE.js";import{f as y,o as T}from"./chunk-LLVS3UYZ.js";import{a as p,c as S}from"./chunk-JJDHD7SC.js";import{f as b}from"./chunk-MBDX4OHD.js";T();S();import*as c from"path";import*as d from"fs";var m=null,u=null,l=null;function R(o){l=o}async function P(){return m||u||(u=(async()=>{let o=y(),e=c.join(o,".agentic-qe");d.existsSync(e)||d.mkdirSync(e,{recursive:!0});let r=new M({sqlite:{path:c.join(e,"memory.db"),walMode:!0,poolSize:3,busyTimeout:5e3},enableFallback:!0,defaultNamespace:"mcp-tools"});return await r.initialize(),m=r,r})(),u)}function $(){if(l)try{l()}catch{}m&&(m.dispose().catch(()=>{}),m=null),u=null}async function D(o){return o?.memory?o.memory:P()}var C={info:(o,e)=>console.log(`[MCP-TOOL] ${o}`,e||""),warn:(o,e)=>console.warn(`[MCP-TOOL] \u26A0\uFE0F ${o}`,e||""),error:(o,e)=>console.error(`[MCP-TOOL] \u274C ${o}`,e||"")},h=class{logger=C;currentDataSource="real";setLogger(e){this.logger=e}markAsDemoData(e,r){this.currentDataSource=e.demoMode?"demo":"fallback",this.logger.warn(`${this.config.name} returning ${this.currentDataSource} data`,{reason:r,requestId:e.requestId,demoMode:e.demoMode})}markAsRealData(){this.currentDataSource="real"}isDemoMode(e){return e.demoMode===!0}validate(e){let r=[];if(typeof e!="object"||e===null)return{valid:!1,errors:["Parameters must be an object"]};let t=e,{properties:a,required:n}=this.config.schema;if(n)for(let i of n)i in t||r.push(`Missing required field: ${i}`);for(let[i,s]of Object.entries(t)){let g=a[i];if(!g)continue;let f=this.validateType(i,s,g);f&&r.push(f)}return{valid:r.length===0,errors:r}}validateType(e,r,t){if(r==null)return null;let a=Array.isArray(r)?"array":typeof r;if(t.type==="array"&&!Array.isArray(r))return`${e} must be an array`;if(t.type!=="array"&&a!==t.type)return`${e} must be of type ${t.type}, got ${a}`;if(t.enum&&!t.enum.includes(r))return`${e} must be one of: ${t.enum.join(", ")}`;if(t.type==="number"){let n=r;if(t.minimum!==void 0&&n<t.minimum)return`${e} must be >= ${t.minimum}`;if(t.maximum!==void 0&&n>t.maximum)return`${e} must be <= ${t.maximum}`}if(t.type==="string"){let n=r;if(t.minLength!==void 0&&n.length<t.minLength)return`${e} must be at least ${t.minLength} characters`;if(t.maxLength!==void 0&&n.length>t.maxLength)return`${e} must be at most ${t.maxLength} characters`}return null}async invoke(e,r={}){let t=Date.now(),a=b();this.currentDataSource="real";let n=this.validate(e);if(!n.valid)return{success:!1,error:`Validation failed: ${n.errors.join("; ")}`,metadata:this.createMetadata(t,a)};let i={requestId:a,startTime:t,streaming:r.streaming,onStream:r.onStream,abortSignal:r.abortSignal,demoMode:r.demoMode};try{let s=await this.execute(e,i);return{...s,metadata:{...s.metadata,...this.createMetadata(t,a)}}}catch(s){return{success:!1,error:p(s),metadata:this.createMetadata(t,a)}}}createMetadata(e,r){return{executionTime:Date.now()-e,timestamp:new Date().toISOString(),requestId:r,domain:this.config.domain,toolName:this.config.name,dataSource:this.currentDataSource}}emitStream(e,r){e.streaming&&e.onStream&&e.onStream(r)}isAborted(e){return e.abortSignal?.aborted??!1}get name(){return this.config.name}get description(){return this.config.description}get domain(){return this.config.domain}getSchema(){return this.config.schema}get timeout(){return this.config.timeout??6e4}get supportsStreaming(){return this.config.streaming??!1}resetInstanceCache(){}};export{R as a,P as b,$ as c,D as d,C as e,h 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.14");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.15");process.exit(0)}
2
2
  import{existsSync as _,readdirSync as d,statSync as w}from"fs";import{join as i,extname as E}from"path";var T=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".pyw",".go",".rs",".java",".kt",".kts",".rb",".cs",".php",".swift",".c",".h",".cpp",".hpp",".cc",".scala"]),v=[".test.",".spec.","_test.","_spec."],b=new Set(["node_modules","dist","build","coverage",".git","__pycache__",".venv","venv",".tox",".mypy_cache","target",".gradle","vendor",".bundle",".next",".nuxt",".output"]);function O(s,p={}){let{maxDepth:f=6,includeTests:m=!1,testsOnly:x=!1,extraExtensions:S=[]}=p;if(!_(s))return[];let o=w(s);if(o.isFile())return[s];if(!o.isDirectory())return[];let y=new Set(S.map(t=>t.startsWith(".")?t:`.${t}`)),n=[];function r(t,c){if(c>f)return;let a;try{a=d(t,{withFileTypes:!0})}catch{return}for(let e of a)if(e.isDirectory()){if(b.has(e.name))continue;r(i(t,e.name),c+1)}else if(e.isFile()){let u=E(e.name).toLowerCase();if(!(T.has(u)||y.has(u))||e.name.endsWith(".d.ts"))continue;let l=v.some(h=>e.name.includes(h))||e.name.startsWith("test_");x?l&&n.push(i(t,e.name)):(m||!l)&&n.push(i(t,e.name))}}return r(s,0),n}export{T as a,O as b};