agentic-qe 3.14.8 → 3.15.1

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 (375) hide show
  1. package/.claude/skills/release/SKILL.md +6 -0
  2. package/.claude/skills/skills-manifest.json +1 -1
  3. package/CHANGELOG.md +189 -0
  4. package/README.md +143 -366
  5. package/assets/readme/credit-ruflo.svg +1 -0
  6. package/assets/readme/credit-ruvector.svg +1 -0
  7. package/assets/readme/project-header.svg +1 -0
  8. package/assets/readme/quality-loop.svg +1 -0
  9. package/assets/skills/skills-manifest.json +1 -1
  10. package/dist/adapters/a2a/notifications/retry-queue.js +5 -1
  11. package/dist/adapters/ag-ui/json-patch.js +14 -7
  12. package/dist/adapters/ag-ui/state-delta-cache.js +20 -12
  13. package/dist/cli/bundle.js +5 -5
  14. package/dist/cli/chunks/adapter-Q6RPGMUE.js +2 -0
  15. package/dist/cli/chunks/{agent-booster-wasm-67OKGDGZ.js → agent-booster-wasm-XUHRLKWP.js} +2 -2
  16. package/dist/cli/chunks/{agent-handler-4HZEQ3WQ.js → agent-handler-CL7MJP5W.js} +2 -2
  17. package/dist/cli/chunks/{agent-memory-branch-IBHZQSRN.js → agent-memory-branch-F7RV72FC.js} +2 -2
  18. package/dist/cli/chunks/aqe-learning-engine-JQPXIU7C.js +2 -0
  19. package/dist/cli/chunks/{arena-LCLRGUIK.js → arena-GRRNK7IN.js} +4 -4
  20. package/dist/cli/chunks/{arena-EJBIGSF4.js → arena-LHLVOQHW.js} +2 -2
  21. package/dist/cli/chunks/{audit-PY4JNDQQ.js → audit-EOP2K34L.js} +3 -3
  22. package/dist/cli/chunks/base-5SK64NXB.js +2 -0
  23. package/dist/cli/chunks/{better-sqlite3-2JG5K6XT.js → better-sqlite3-YERQ5DOL.js} +2 -2
  24. package/dist/cli/chunks/{brain-handler-3UYK55GA.js → brain-handler-FBXBM5XE.js} +3 -3
  25. package/dist/cli/chunks/{branch-enumerator-GOSWOX46.js → branch-enumerator-NWO6LNHB.js} +2 -2
  26. package/dist/cli/chunks/{browser-DC2JV47Z.js → browser-EDCG7TNF.js} +2 -2
  27. package/dist/cli/chunks/browser-workflow-WN7XNTCJ.js +2 -0
  28. package/dist/cli/chunks/{chunk-Z5UZOYQS.js → chunk-25IWHVMW.js} +2 -2
  29. package/dist/cli/chunks/chunk-27S47AYK.js +3 -0
  30. package/dist/cli/chunks/{chunk-SUNXA2UR.js → chunk-2IPBCXTT.js} +2 -2
  31. package/dist/cli/chunks/chunk-2K3QFLX2.js +2 -0
  32. package/dist/cli/chunks/{chunk-775WGWLL.js → chunk-35XRY6ZW.js} +2 -2
  33. package/dist/cli/chunks/{chunk-RTD4U7IW.js → chunk-3NOSMJS4.js} +2 -2
  34. package/dist/cli/chunks/{chunk-GVLRE3BV.js → chunk-3TZRJ5QD.js} +3 -3
  35. package/dist/cli/chunks/{chunk-RJJIPTVH.js → chunk-46DUU44C.js} +2 -2
  36. package/dist/cli/chunks/{chunk-H5UH234L.js → chunk-4AEFJEZH.js} +1 -1
  37. package/dist/cli/chunks/{chunk-EXQGHTPD.js → chunk-4KHSWNFW.js} +4 -4
  38. package/dist/cli/chunks/{chunk-CLUHGBLN.js → chunk-4KSCJ462.js} +1 -1
  39. package/dist/cli/chunks/{chunk-3EKG7HFV.js → chunk-4P7CGSRL.js} +3 -3
  40. package/dist/cli/chunks/{chunk-XFT4FYTC.js → chunk-4THIRDBL.js} +2 -2
  41. package/dist/cli/chunks/{chunk-7TNCEVWX.js → chunk-4XEZ562Q.js} +2 -2
  42. package/dist/cli/chunks/{chunk-CIEXUYY7.js → chunk-53C7TGC4.js} +1 -1
  43. package/dist/cli/chunks/{chunk-LQVS5IWH.js → chunk-53HWWWFZ.js} +2 -2
  44. package/dist/cli/chunks/{chunk-EMOZ5O5S.js → chunk-54JYUOSR.js} +1 -1
  45. package/dist/cli/chunks/{chunk-J24AJEDE.js → chunk-5B5TA3X4.js} +2 -2
  46. package/dist/cli/chunks/{chunk-BITFGVZ4.js → chunk-5C4UYXQL.js} +2 -2
  47. package/dist/cli/chunks/{chunk-F6JJNBE5.js → chunk-5JJWVFUV.js} +1 -1
  48. package/dist/cli/chunks/{chunk-M7QKCHLQ.js → chunk-5QEXDXHQ.js} +2 -2
  49. package/dist/cli/chunks/{chunk-I6NZFBT3.js → chunk-5TEDVUEB.js} +2 -2
  50. package/dist/cli/chunks/{chunk-673XJBGW.js → chunk-66HKJJFH.js} +2 -2
  51. package/dist/cli/chunks/{chunk-AR2S4DOB.js → chunk-6AVVC7Y3.js} +1 -1
  52. package/dist/cli/chunks/{chunk-EBV3WFIR.js → chunk-6DF6X3SZ.js} +2 -2
  53. package/dist/cli/chunks/{chunk-GHMJFICO.js → chunk-6MGJMGAD.js} +2 -2
  54. package/dist/cli/chunks/{chunk-XECZYQT5.js → chunk-6Q7PWKWV.js} +2 -2
  55. package/dist/cli/chunks/{chunk-VV2JVYOI.js → chunk-6U6JQS4Z.js} +2 -2
  56. package/dist/cli/chunks/{chunk-BHPTHC5O.js → chunk-6WW6A6JM.js} +2 -2
  57. package/dist/cli/chunks/{chunk-G3C7Z6FO.js → chunk-7B3XVVYP.js} +2 -2
  58. package/dist/cli/chunks/{chunk-J5HTQHJK.js → chunk-7FGSX4UD.js} +2 -2
  59. package/dist/cli/chunks/{chunk-YIWBJ637.js → chunk-A5LOELVV.js} +2 -2
  60. package/dist/cli/chunks/{chunk-VCSNNLWL.js → chunk-ADEYBXAS.js} +2 -2
  61. package/dist/cli/chunks/{chunk-A53MMSGC.js → chunk-ALLABEUK.js} +2 -2
  62. package/dist/cli/chunks/{chunk-HBAFXWSO.js → chunk-ARGMYSDY.js} +1 -1
  63. package/dist/cli/chunks/{chunk-HPVYJ6JH.js → chunk-ARWSPV2C.js} +2 -2
  64. package/dist/cli/chunks/{chunk-VSPNIDQK.js → chunk-AVOYMVD6.js} +2 -2
  65. package/dist/cli/chunks/{chunk-BUVJIVFG.js → chunk-B3DWOR5R.js} +1 -1
  66. package/dist/cli/chunks/{chunk-K6EOHGKS.js → chunk-BW7S6LIJ.js} +2 -2
  67. package/dist/cli/chunks/{chunk-4HXFPBAA.js → chunk-C3BW3Q27.js} +1 -1
  68. package/dist/cli/chunks/{chunk-JRK5GX56.js → chunk-CFZJEOCD.js} +1 -1
  69. package/dist/cli/chunks/{chunk-3S5IIK32.js → chunk-CHX65QXY.js} +1 -1
  70. package/dist/cli/chunks/{chunk-FRC7AFB4.js → chunk-CTK7NMSJ.js} +2 -2
  71. package/dist/cli/chunks/{chunk-RM6OC35G.js → chunk-CTLHNFPM.js} +1 -1
  72. package/dist/cli/chunks/{chunk-3576QGPP.js → chunk-D3LREV4P.js} +1 -1
  73. package/dist/cli/chunks/{chunk-TCQWVVSR.js → chunk-DKWB4ERY.js} +1 -1
  74. package/dist/cli/chunks/{chunk-JQAJUXRE.js → chunk-DREYYJ7A.js} +2 -2
  75. package/dist/cli/chunks/{chunk-OZJQN7YE.js → chunk-DV7I6CRH.js} +2 -2
  76. package/dist/cli/chunks/{chunk-AEYJ4ZLA.js → chunk-EQ3BJS37.js} +1 -1
  77. package/dist/cli/chunks/{chunk-KNSQWM2E.js → chunk-FIIHSEXP.js} +2 -2
  78. package/dist/cli/chunks/{chunk-LRGTPUJA.js → chunk-FQYXPSWD.js} +2 -2
  79. package/dist/cli/chunks/{chunk-QQVE65ER.js → chunk-FRGNM6SW.js} +2 -2
  80. package/dist/cli/chunks/{chunk-AOD2ES44.js → chunk-FTHXV7N7.js} +2 -2
  81. package/dist/cli/chunks/{chunk-DZHXCOSK.js → chunk-GAKVCN3C.js} +1 -1
  82. package/dist/cli/chunks/{chunk-LMAI74EP.js → chunk-GDSYJHVB.js} +1 -1
  83. package/dist/cli/chunks/{chunk-VAXTPLO3.js → chunk-GUHJWBPN.js} +2 -2
  84. package/dist/cli/chunks/{chunk-OX7MJFLC.js → chunk-GUKBN3BS.js} +2 -2
  85. package/dist/cli/chunks/{chunk-R6I5I724.js → chunk-HU4QGCIJ.js} +2 -2
  86. package/dist/cli/chunks/{chunk-LTHV4PIG.js → chunk-HVAYG54D.js} +2 -2
  87. package/dist/cli/chunks/{chunk-AJMAKUS3.js → chunk-IUGY6Z4Q.js} +2 -2
  88. package/dist/cli/chunks/{chunk-WFKE7NZ5.js → chunk-J2WALRWR.js} +2 -2
  89. package/dist/cli/chunks/{chunk-Z6G3QVZ4.js → chunk-J4ULR4QR.js} +19 -19
  90. package/dist/cli/chunks/{chunk-YHX74M7C.js → chunk-JEXPSOT2.js} +2 -2
  91. package/dist/cli/chunks/{chunk-25EEIAHS.js → chunk-JHKMUY4W.js} +2 -2
  92. package/dist/cli/chunks/{chunk-L5T32SRF.js → chunk-JQVECGYL.js} +1 -1
  93. package/dist/cli/chunks/{chunk-UHLZKH6B.js → chunk-JSHASVQ2.js} +25 -25
  94. package/dist/cli/chunks/{chunk-SPS472C5.js → chunk-JW2HNT3J.js} +2 -2
  95. package/dist/cli/chunks/{chunk-SMBGK7XI.js → chunk-JY6HWYC4.js} +1 -1
  96. package/dist/cli/chunks/{chunk-F57FTFWS.js → chunk-JYF3QF4C.js} +2 -2
  97. package/dist/cli/chunks/{chunk-CBWM5NOO.js → chunk-K4NB3MYN.js} +2 -2
  98. package/dist/cli/chunks/{chunk-LKFBW2QM.js → chunk-KBK4GBJQ.js} +2 -2
  99. package/dist/cli/chunks/{chunk-6F7MFHTY.js → chunk-KHVWIUAF.js} +2 -2
  100. package/dist/cli/chunks/{chunk-JDOVO4E4.js → chunk-KP6LNSDO.js} +126 -130
  101. package/dist/cli/chunks/{chunk-T53ZN4NO.js → chunk-KTBA2HJC.js} +2 -2
  102. package/dist/cli/chunks/{chunk-WVEHKAIH.js → chunk-L5GEWKR3.js} +3 -3
  103. package/dist/cli/chunks/chunk-LDDIYDIP.js +742 -0
  104. package/dist/cli/chunks/{chunk-QPACHVDI.js → chunk-LI7N45GM.js} +1 -1
  105. package/dist/cli/chunks/{chunk-UQGIC5OX.js → chunk-LQI5GVH7.js} +1 -1
  106. package/dist/cli/chunks/{chunk-T4WQPE77.js → chunk-MEOAKMKF.js} +1 -1
  107. package/dist/cli/chunks/{chunk-BT3MI2BW.js → chunk-N4HQ6FE2.js} +1 -1
  108. package/dist/cli/chunks/{chunk-JRLZ7LZ3.js → chunk-N5OSH5JO.js} +2 -2
  109. package/dist/cli/chunks/{chunk-BZIPW2PA.js → chunk-NF6SLLE6.js} +2 -2
  110. package/dist/cli/chunks/{chunk-QYCZYJH7.js → chunk-NGDRSF6Y.js} +2 -2
  111. package/dist/cli/chunks/{chunk-O4QB2GFL.js → chunk-NK2BR4QZ.js} +2 -2
  112. package/dist/cli/chunks/{chunk-B2QKBQYD.js → chunk-NS4RIZ4F.js} +1 -1
  113. package/dist/cli/chunks/{chunk-CQEWL32R.js → chunk-NTLWHLAY.js} +1 -1
  114. package/dist/cli/chunks/{chunk-NWUFTLSF.js → chunk-NWNZMXNO.js} +2 -2
  115. package/dist/cli/chunks/{chunk-6GJWT2OY.js → chunk-OABFAREV.js} +2 -2
  116. package/dist/cli/chunks/{chunk-T7YCNOW5.js → chunk-OH4SKOAM.js} +2 -2
  117. package/dist/cli/chunks/{chunk-BL6273KR.js → chunk-OKS25EGZ.js} +3 -3
  118. package/dist/cli/chunks/{chunk-NJEEKYEP.js → chunk-OPBPFNBO.js} +2 -2
  119. package/dist/cli/chunks/{chunk-SKJQKOFJ.js → chunk-P24ZBDZY.js} +2 -2
  120. package/dist/cli/chunks/{chunk-KKXH25IH.js → chunk-PBWR2SKH.js} +2 -2
  121. package/dist/cli/chunks/{chunk-TGRHO4ES.js → chunk-PDLVO3ZR.js} +2 -2
  122. package/dist/cli/chunks/{chunk-GK5WLUX3.js → chunk-PGARKOE6.js} +1 -1
  123. package/dist/cli/chunks/{chunk-XAESN54Q.js → chunk-PNK5KHSI.js} +1 -1
  124. package/dist/cli/chunks/{chunk-BFIXUKOR.js → chunk-PZBYZV5M.js} +1 -1
  125. package/dist/cli/chunks/{chunk-EKO5QL2B.js → chunk-PZDI7WQ3.js} +1 -1
  126. package/dist/cli/chunks/{chunk-BCCSV3RH.js → chunk-Q7ONRZBD.js} +1 -1
  127. package/dist/cli/chunks/{chunk-N3ASALOL.js → chunk-QMHWJBD3.js} +2 -2
  128. package/dist/cli/chunks/{chunk-OA75C4HY.js → chunk-QOOADAT7.js} +2 -2
  129. package/dist/cli/chunks/{chunk-ES7TAJRJ.js → chunk-QVTV47TM.js} +2 -2
  130. package/dist/cli/chunks/{chunk-7X3LMTRA.js → chunk-R2ICZKQA.js} +2 -2
  131. package/dist/cli/chunks/{chunk-D2Y36V5J.js → chunk-RDI3W4H6.js} +2 -2
  132. package/dist/cli/chunks/{chunk-QP7EKLWU.js → chunk-REGPCPEJ.js} +2 -2
  133. package/dist/cli/chunks/{chunk-U2QTL5T2.js → chunk-RXKOZ6VS.js} +3 -3
  134. package/dist/cli/chunks/{chunk-OVMG6EEF.js → chunk-SRXXPZVT.js} +2 -2
  135. package/dist/cli/chunks/{chunk-CXUC7YKA.js → chunk-SUFXUM6W.js} +2 -2
  136. package/dist/cli/chunks/{chunk-77WL5HQW.js → chunk-T5K6ZCA6.js} +1 -1
  137. package/dist/cli/chunks/{chunk-3X2JSW3R.js → chunk-TBCQWD5A.js} +1 -1
  138. package/dist/cli/chunks/{chunk-BOIUENWW.js → chunk-TCJ65NPY.js} +1 -1
  139. package/dist/cli/chunks/{chunk-HE3BDBAO.js → chunk-TJCMG3QE.js} +2 -2
  140. package/dist/cli/chunks/{chunk-56M4QNXU.js → chunk-TLUMENRZ.js} +2 -2
  141. package/dist/cli/chunks/{chunk-JTOFLDU7.js → chunk-TR37Q7A6.js} +6 -6
  142. package/dist/cli/chunks/{chunk-SVP3BP52.js → chunk-UE33MZOC.js} +2 -2
  143. package/dist/cli/chunks/{chunk-T6W2EYHC.js → chunk-UGUZFUQG.js} +2 -2
  144. package/dist/cli/chunks/{chunk-3FCHH4VP.js → chunk-UOHZRR5C.js} +1 -1
  145. package/dist/cli/chunks/{chunk-QKM4XT2F.js → chunk-UTFNHITI.js} +2 -2
  146. package/dist/cli/chunks/{chunk-6GNWVPMR.js → chunk-V3ISBQ5Q.js} +2 -2
  147. package/dist/cli/chunks/{chunk-6VTC3OHD.js → chunk-V5RP2SU3.js} +2 -2
  148. package/dist/cli/chunks/{chunk-5X4HDW5W.js → chunk-VEKRK3R6.js} +2 -2
  149. package/dist/cli/chunks/{chunk-TUZNWRYC.js → chunk-VGYLV6VD.js} +1 -1
  150. package/dist/cli/chunks/{chunk-C647D42G.js → chunk-VLL7ASGH.js} +2 -2
  151. package/dist/cli/chunks/{chunk-QH7C4PTX.js → chunk-W5HQQTVH.js} +1 -1
  152. package/dist/cli/chunks/{chunk-A5CLVZC3.js → chunk-W5NHBYYS.js} +2 -2
  153. package/dist/cli/chunks/{chunk-ISBOHF6Y.js → chunk-W6K77PQR.js} +1 -1
  154. package/dist/cli/chunks/{chunk-AUFV2G2J.js → chunk-WFDDWRWY.js} +5 -5
  155. package/dist/cli/chunks/{chunk-AJ5PCJQ2.js → chunk-WHBDSJUE.js} +3 -3
  156. package/dist/cli/chunks/{chunk-4RNCVSVN.js → chunk-WONHFDWF.js} +2 -2
  157. package/dist/cli/chunks/{chunk-VW7AXJQS.js → chunk-WPG6SW7C.js} +2 -2
  158. package/dist/cli/chunks/{chunk-GA63ESNT.js → chunk-WQZR6DS6.js} +2 -2
  159. package/dist/cli/chunks/{chunk-G36RZF2Y.js → chunk-WTFVYFRZ.js} +1 -1
  160. package/dist/cli/chunks/{chunk-F2WAB4WK.js → chunk-WYE3ICSL.js} +2 -2
  161. package/dist/cli/chunks/{chunk-TT45RCLN.js → chunk-X4PGLEPQ.js} +2 -2
  162. package/dist/cli/chunks/{chunk-QDRFLM77.js → chunk-X6W35QXO.js} +2 -2
  163. package/dist/cli/chunks/{chunk-HHANMCD2.js → chunk-XCVD57GW.js} +1 -1
  164. package/dist/cli/chunks/{chunk-GQJ4QDEN.js → chunk-XYZUBAR6.js} +4 -4
  165. package/dist/cli/chunks/{chunk-TP7L4EX6.js → chunk-XZGRHJGC.js} +2 -2
  166. package/dist/cli/chunks/{chunk-BTBJ2NLH.js → chunk-YDM2DPUU.js} +2 -2
  167. package/dist/cli/chunks/{chunk-NEXBTLN6.js → chunk-YDMPTCJ3.js} +2 -2
  168. package/dist/cli/chunks/{chunk-4PY44TKH.js → chunk-YM3GAJMN.js} +2 -2
  169. package/dist/cli/chunks/{chunk-UNFE4RPV.js → chunk-YTMWPGVR.js} +1 -1
  170. package/dist/cli/chunks/{chunk-DSJJHPPS.js → chunk-YWX7KLNG.js} +3 -3
  171. package/dist/cli/chunks/{chunk-UIWXKRTK.js → chunk-ZE6WJDXM.js} +2 -2
  172. package/dist/cli/chunks/{chunk-W7JUD4EZ.js → chunk-ZX4I7IND.js} +2 -2
  173. package/dist/cli/chunks/{chunk-PVJLQ2YZ.js → chunk-ZZV6GR46.js} +1 -1
  174. package/dist/cli/chunks/{ci-5LIV2HW5.js → ci-K7DG4GSO.js} +3 -3
  175. package/dist/cli/chunks/{ci-output-UO5BDFU4.js → ci-output-EBSUG6HP.js} +2 -2
  176. package/dist/cli/chunks/{circuit-breaker-UQDPXYRD.js → circuit-breaker-P6N6YIRZ.js} +2 -2
  177. package/dist/cli/chunks/{claude-flow-setup-62QES3QX.js → claude-flow-setup-P6EZPQZT.js} +2 -2
  178. package/dist/cli/chunks/client-ZYH66YRI.js +2 -0
  179. package/dist/cli/chunks/{cline-installer-X7VZTSZG.js → cline-installer-EVZZ3EFY.js} +2 -2
  180. package/dist/cli/chunks/{code-H3BF4L4H.js → code-3WLBG2XK.js} +3 -3
  181. package/dist/cli/chunks/{code-index-extractor-BJGFZGGL.js → code-index-extractor-ZP6D4WL2.js} +2 -2
  182. package/dist/cli/chunks/{codex-installer-KVZWKU6S.js → codex-installer-XAUI4SB7.js} +2 -2
  183. package/dist/cli/chunks/{completions-YMILE6V7.js → completions-RHFNDDG3.js} +2 -2
  184. package/dist/cli/chunks/{complexity-analyzer-J26N2PWG.js → complexity-analyzer-DCW7Q3OR.js} +2 -2
  185. package/dist/cli/chunks/{continuedev-installer-MAR42OV7.js → continuedev-installer-53SQA5T6.js} +2 -2
  186. package/dist/cli/chunks/{copilot-installer-CVOJF6OT.js → copilot-installer-SXXMFB6T.js} +2 -2
  187. package/dist/cli/chunks/core-handlers-XKSPHEHE.js +2 -0
  188. package/dist/cli/chunks/{cost-tracker-SXLWXE55.js → cost-tracker-CKLDQ5AZ.js} +2 -2
  189. package/dist/cli/chunks/{coverage-D7HCHFP3.js → coverage-AWCS2SP7.js} +3 -3
  190. package/dist/cli/chunks/cross-domain-router-6VYNFQZA.js +2 -0
  191. package/dist/cli/chunks/{cursor-installer-X37VHIKW.js → cursor-installer-4TYF5V5J.js} +2 -2
  192. package/dist/cli/chunks/{daemon-LIW47IDM.js → daemon-CTZXGN5V.js} +4 -4
  193. package/dist/cli/chunks/{daemon-JN7SOH6F.js → daemon-OOY4H6RJ.js} +3 -3
  194. package/dist/cli/chunks/{dag-attention-scheduler-QCHHIZBT.js → dag-attention-scheduler-3WG24Q33.js} +2 -2
  195. package/dist/cli/chunks/{detect-WRFCWAX5.js → detect-O7MUZ6NX.js} +2 -2
  196. package/dist/cli/chunks/{dist-node-6FWT4XZO.js → dist-node-H4XI7BAF.js} +2 -2
  197. package/dist/cli/chunks/{domain-handler-SNFPNMRT.js → domain-handler-FU4WZ23B.js} +2 -2
  198. package/dist/cli/chunks/{domain-plugins-MXKHH62P.js → domain-plugins-XK26KYNJ.js} +2 -2
  199. package/dist/cli/chunks/{domain-transfer-47UJNERX.js → domain-transfer-6B5NOVH6.js} +2 -2
  200. package/dist/cli/chunks/dream-DRSSIHPP.js +2 -0
  201. package/dist/cli/chunks/{embed-and-insert-pattern-LZFAUNBQ.js → embed-and-insert-pattern-XNZXPZNL.js} +2 -2
  202. package/dist/cli/chunks/{eval-AMUXTMJB.js → eval-J3Q5TTI7.js} +2 -2
  203. package/dist/cli/chunks/{experience-capture-middleware-3D65TR2C.js → experience-capture-middleware-COKIGMXW.js} +3 -3
  204. package/dist/cli/chunks/{fast-paths-Y7BBMM56.js → fast-paths-IHWPJI6I.js} +2 -2
  205. package/dist/cli/chunks/{feature-flags-VESRRQ6V.js → feature-flags-G7ONDNTT.js} +2 -2
  206. package/dist/cli/chunks/{feature-flags-JMQQ7JW4.js → feature-flags-WUXFWZLR.js} +2 -2
  207. package/dist/cli/chunks/{file-discovery-JJKQQUV6.js → file-discovery-JN3YMBOJ.js} +2 -2
  208. package/dist/cli/chunks/{fleet-WIGHICJF.js → fleet-OUHUZJE4.js} +3 -3
  209. package/dist/cli/chunks/{gnn-wrapper-BFNPETTT.js → gnn-wrapper-PRH55ZT6.js} +2 -2
  210. package/dist/cli/chunks/{heartbeat-handler-HDXKTGUI.js → heartbeat-handler-6YF35AQS.js} +4 -4
  211. package/dist/cli/chunks/heartbeat-scheduler-FMICCNWK.js +2 -0
  212. package/dist/cli/chunks/hnsw-adapter-4TGBNJEZ.js +2 -0
  213. package/dist/cli/chunks/hnsw-index-J4NSCPAZ.js +2 -0
  214. package/dist/cli/chunks/{hnsw-legacy-bridge-6A7OTAPT.js → hnsw-legacy-bridge-7PAFSTJO.js} +2 -2
  215. package/dist/cli/chunks/{hnswlib-node-LKV2H47B.js → hnswlib-node-UETDZNNN.js} +2 -2
  216. package/dist/cli/chunks/{hooks-KDSFYQQG.js → hooks-QQNUKQAS.js} +10 -10
  217. package/dist/cli/chunks/hybrid-backend-NKPA3QE7.js +2 -0
  218. package/dist/cli/chunks/{hypergraph-engine-GDLPEPUC.js → hypergraph-engine-5GDGE3ET.js} +2 -2
  219. package/dist/cli/chunks/{hypergraph-handler-4UMFA2EW.js → hypergraph-handler-C3F2OJYA.js} +3 -3
  220. package/dist/cli/chunks/impact-analyzer-MWX7XY7X.js +2 -0
  221. package/dist/cli/chunks/{init-handler-4GCHPQHD.js → init-handler-C7ZBDAC5.js} +6 -6
  222. package/dist/cli/chunks/init-wizard-EX5N5Q7X.js +2 -0
  223. package/dist/cli/chunks/kernel-EQLZDHDD.js +2 -0
  224. package/dist/cli/chunks/{kilocode-installer-HJZMT2G5.js → kilocode-installer-VLJENC76.js} +2 -2
  225. package/dist/cli/chunks/{kiro-installer-WUPY67HG.js → kiro-installer-UYPYM6LA.js} +2 -2
  226. package/dist/cli/chunks/knowledge-graph-A3WSMQ6U.js +2 -0
  227. package/dist/cli/chunks/{learning-AXKIS7IG.js → learning-SFIWIG6Z.js} +3 -3
  228. package/dist/cli/chunks/{llm-router-HUDPNZLJ.js → llm-router-V633KAS5.js} +4 -4
  229. package/dist/cli/chunks/llm-router-service-A6XYWTL6.js +2 -0
  230. package/dist/cli/chunks/{load-RM44POD7.js → load-UWZV4JRA.js} +2 -2
  231. package/dist/cli/chunks/load-test-WF2PCXLI.js +2 -0
  232. package/dist/cli/chunks/{mcp-5JVQRBOP.js → mcp-XVFHUKCP.js} +2 -2
  233. package/dist/cli/chunks/{memory-VGZ2V6PL.js → memory-BQ5652VK.js} +5 -5
  234. package/dist/cli/chunks/memory-backend-BKGLI2RF.js +2 -0
  235. package/dist/cli/chunks/{memory-handlers-EI537Z32.js → memory-handlers-PWI3G4P4.js} +2 -2
  236. package/dist/cli/chunks/{multi-model-executor-WPRKCSCM.js → multi-model-executor-X6AQ7VVR.js} +2 -2
  237. package/dist/cli/chunks/{opencode-installer-YAJMRCQO.js → opencode-installer-N3V2Z4EF.js} +2 -2
  238. package/dist/cli/chunks/{orchestrator-MUGWBUYP.js → orchestrator-KNEKS4F7.js} +5 -5
  239. package/dist/cli/chunks/pattern-null-store-YTBLEH7D.js +2 -0
  240. package/dist/cli/chunks/{pattern-usage-recorder-ZQJJ2YNG.js → pattern-usage-recorder-MZIM6XWU.js} +2 -2
  241. package/dist/cli/chunks/{pipeline-F4DXDUDC.js → pipeline-LNLBKSXR.js} +2 -2
  242. package/dist/cli/chunks/{platform-HI3A3OWF.js → platform-OMUDXHD3.js} +2 -2
  243. package/dist/cli/chunks/{plugin-XRITPTR7.js → plugin-HGY6KKZW.js} +2 -2
  244. package/dist/cli/chunks/{prime-radiant-advanced-wasm-HHNJP7CQ.js → prime-radiant-advanced-wasm-LZBHLQYN.js} +2 -2
  245. package/dist/cli/chunks/{project-root-2VN4WO2A.js → project-root-VPSCDBMD.js} +2 -2
  246. package/dist/cli/chunks/protocol-executor-HFR2D54O.js +2 -0
  247. package/dist/cli/chunks/{protocol-handler-ZEVHSEBG.js → protocol-handler-LZXT3TXU.js} +2 -2
  248. package/dist/cli/chunks/{prove-C4BLZWBS.js → prove-I4VKQEYQ.js} +2 -2
  249. package/dist/cli/chunks/qe-reasoning-bank-MYFBQUYV.js +2 -0
  250. package/dist/cli/chunks/{quality-M3DTE4KK.js → quality-VVAWK2DD.js} +2 -2
  251. package/dist/cli/chunks/{quality-gate-V6KS7ML3.js → quality-gate-RGXLWYT6.js} +3 -3
  252. package/dist/cli/chunks/queen-coordinator-CQQMOTIW.js +2 -0
  253. package/dist/cli/chunks/{real-embeddings-YWSE3IRT.js → real-embeddings-WM66PMQ6.js} +2 -2
  254. package/dist/cli/chunks/{ref-validation-ZWOTFA3T.js → ref-validation-ZIWJNI6M.js} +2 -2
  255. package/dist/cli/chunks/{roocode-installer-GJBIWETD.js → roocode-installer-QYSI3STC.js} +2 -2
  256. package/dist/cli/chunks/router-GKWLPA3N.js +2 -0
  257. package/dist/cli/chunks/routing-feedback-WA4D5JRF.js +2 -0
  258. package/dist/cli/chunks/{routing-handler-CFYLGNAR.js → routing-handler-BID3EOLE.js} +2 -2
  259. package/dist/cli/chunks/{ruvector-commands-EDKG456B.js → ruvector-commands-DXIFMF4W.js} +2 -2
  260. package/dist/cli/chunks/rvf-dual-writer-H3ZXS5MA.js +2 -0
  261. package/dist/cli/chunks/rvf-migration-adapter-J7MTCOQA.js +2 -0
  262. package/dist/cli/chunks/{rvf-migration-coordinator-ZMEYMAI6.js → rvf-migration-coordinator-EV5E6SAO.js} +2 -2
  263. package/dist/cli/chunks/rvf-native-adapter-HXBY4VYI.js +2 -0
  264. package/dist/cli/chunks/{rvf-store-integrity-AH6PNJP6.js → rvf-store-integrity-IT6DCCJK.js} +2 -2
  265. package/dist/cli/chunks/safe-db-INVJ5LHR.js +2 -0
  266. package/dist/cli/chunks/schedule-XRIPPL52.js +2 -0
  267. package/dist/cli/chunks/scheduler-HBN3KPRW.js +2 -0
  268. package/dist/cli/chunks/{security-ZU2GW3ZM.js → security-AAFAEATQ.js} +3 -3
  269. package/dist/cli/chunks/{shared-rvf-adapter-5FOVSL3T.js → shared-rvf-adapter-QIHSYHAF.js} +2 -2
  270. package/dist/cli/chunks/{shared-rvf-dual-writer-IO4DC4XV.js → shared-rvf-dual-writer-V7OZ6TBR.js} +2 -2
  271. package/dist/cli/chunks/sqlite-persistence-6KNLT5Q2.js +2 -0
  272. package/dist/cli/chunks/{standalone-memory-3UXDZ7HI.js → standalone-memory-ALZI6VPX.js} +2 -2
  273. package/dist/cli/chunks/{status-handler-264CHTWS.js → status-handler-DED5A3OW.js} +2 -2
  274. package/dist/cli/chunks/{structural-health-E2QPUOZE.js → structural-health-CB7L3NWH.js} +2 -2
  275. package/dist/cli/chunks/{sync-2ACMWM7D.js → sync-QNPGETIO.js} +2 -2
  276. package/dist/cli/chunks/{sync-N2L2OST4.js → sync-S6Z2U46T.js} +2 -2
  277. package/dist/cli/chunks/{task-handler-IB5CVOTY.js → task-handler-CGHXYFIF.js} +2 -2
  278. package/dist/cli/chunks/{task-handlers-QBMYNJHE.js → task-handlers-A6BGQJIB.js} +3 -3
  279. package/dist/cli/chunks/{test-7RGLRDSP.js → test-IISTF5W6.js} +4 -4
  280. package/dist/cli/chunks/{test-scheduling-RJABJT2W.js → test-scheduling-FKYX4OLF.js} +7 -7
  281. package/dist/cli/chunks/{token-bootstrap-JVHMHB72.js → token-bootstrap-OKO3JEKT.js} +2 -2
  282. package/dist/cli/chunks/{token-usage-3ECHQVCY.js → token-usage-25BRFKJ5.js} +2 -2
  283. package/dist/cli/chunks/{transformers-KJH3IJWI.js → transformers-TBVVSZMF.js} +2 -2
  284. package/dist/cli/chunks/{tree-sitter-wasm-parser-XN6PFI32.js → tree-sitter-wasm-parser-N7KCOQT4.js} +2 -2
  285. package/dist/cli/chunks/{types-5BAPXOLS.js → types-TFHWJGRK.js} +2 -2
  286. package/dist/cli/chunks/unified-memory-WVELSL6T.js +2 -0
  287. package/dist/cli/chunks/unified-memory-hnsw-7P5MVKXD.js +2 -0
  288. package/dist/cli/chunks/unified-persistence-YLFCEWYY.js +2 -0
  289. package/dist/cli/chunks/{upgrade-S5NFQZID.js → upgrade-4VWQU7RD.js} +2 -2
  290. package/dist/cli/chunks/{validate-BIBWOLJD.js → validate-FF7WVXMP.js} +2 -2
  291. package/dist/cli/chunks/{validate-swarm-WAA3LBHH.js → validate-swarm-NRLH4EDC.js} +2 -2
  292. package/dist/cli/chunks/visual-security-T5OM742H.js +2 -0
  293. package/dist/cli/chunks/{web-tree-sitter-OTBQTHAV.js → web-tree-sitter-VVU3LULW.js} +2 -2
  294. package/dist/cli/chunks/{windsurf-installer-NNQ22EW6.js → windsurf-installer-Q2ZNWG2D.js} +2 -2
  295. package/dist/cli/chunks/witness-chain-D6X4OZP5.js +2 -0
  296. package/dist/cli/chunks/{witness-chain-E7MUBOJW.js → witness-chain-FP3D4PQL.js} +2 -2
  297. package/dist/cli/chunks/{witness-chain-repair-FW4QSN4C.js → witness-chain-repair-3LG4BF7C.js} +2 -2
  298. package/dist/cli/chunks/{witness-chain-verifier-YMROEBVL.js → witness-chain-verifier-LACGL6BK.js} +2 -2
  299. package/dist/cli/chunks/{witness-key-manager-4CGRNDMJ.js → witness-key-manager-GQZIB5ZE.js} +2 -2
  300. package/dist/cli/chunks/{workflow-4VRSTRAN.js → workflow-JPA5Y7L6.js} +4 -4
  301. package/dist/cli/chunks/workflow-orchestrator-OORDDKT3.js +2 -0
  302. package/dist/cli/chunks/{wrappers-4M4UTGEU.js → wrappers-2B5NHICD.js} +2 -2
  303. package/dist/cli/utils/workflow-parser.js +73 -57
  304. package/dist/domains/code-intelligence/services/metric-collector/test-counter.d.ts +1 -1
  305. package/dist/domains/code-intelligence/services/metric-collector/test-counter.js +17 -15
  306. package/dist/domains/test-execution/services/retry-handler.js +6 -3
  307. package/dist/governance/ab-benchmarking.d.ts +5 -1
  308. package/dist/governance/ab-benchmarking.js +64 -29
  309. package/dist/mcp/bundle.js +414 -412
  310. package/dist/mcp/security/rate-limiter.d.ts +1 -0
  311. package/dist/mcp/security/rate-limiter.js +22 -5
  312. package/dist/mcp/services/session-store.js +17 -17
  313. package/dist/mcp/tools/planning/goap-status.d.ts +2 -0
  314. package/dist/mcp/tools/planning/goap-status.js +8 -2
  315. package/dist/planning/goap-planner.d.ts +3 -0
  316. package/dist/planning/goap-planner.js +80 -37
  317. package/dist/shared/embeddings/embedding-cache.js +1 -1
  318. package/dist/shared/embeddings/nomic-embedder.js +17 -7
  319. package/dist/shared/embeddings/ollama-client.js +5 -3
  320. package/dist/shared/git/git-analyzer.js +31 -30
  321. package/dist/shared/http/http-client.js +20 -13
  322. package/dist/shared/io/file-reader.js +11 -8
  323. package/dist/shared/llm/cache.d.ts +8 -29
  324. package/dist/shared/llm/cache.js +6 -2
  325. package/dist/shared/llm/cost-tracker.js +2 -1
  326. package/dist/shared/llm/provider-manager.js +4 -22
  327. package/dist/shared/llm/providers/gemini.d.ts +1 -0
  328. package/dist/shared/llm/providers/gemini.js +14 -5
  329. package/dist/shared/llm/providers/openrouter.js +6 -3
  330. package/dist/shared/metrics/code-metrics.js +1 -1
  331. package/dist/shared/metrics/system-metrics.js +8 -2
  332. package/dist/shared/retry-engine.js +2 -12
  333. package/dist/test-scheduling/executors/vitest-executor.js +26 -17
  334. package/package.json +3 -1
  335. package/dist/cli/chunks/adapter-XYCOXQCC.js +0 -2
  336. package/dist/cli/chunks/aqe-learning-engine-DTJCROTG.js +0 -2
  337. package/dist/cli/chunks/base-5TQ34GMD.js +0 -2
  338. package/dist/cli/chunks/browser-workflow-KWX4ESTJ.js +0 -2
  339. package/dist/cli/chunks/chunk-7STWD4KJ.js +0 -3
  340. package/dist/cli/chunks/chunk-PFXCRRR6.js +0 -736
  341. package/dist/cli/chunks/chunk-U64QORFO.js +0 -2
  342. package/dist/cli/chunks/client-AJZKCP4I.js +0 -2
  343. package/dist/cli/chunks/core-handlers-MQHEMGDV.js +0 -2
  344. package/dist/cli/chunks/cross-domain-router-3QNMZV5R.js +0 -2
  345. package/dist/cli/chunks/dream-OSWAITPT.js +0 -2
  346. package/dist/cli/chunks/heartbeat-scheduler-BVRVVIE2.js +0 -2
  347. package/dist/cli/chunks/hnsw-adapter-MZTHXULS.js +0 -2
  348. package/dist/cli/chunks/hnsw-index-KHEX4VDG.js +0 -2
  349. package/dist/cli/chunks/hybrid-backend-2B3LCLR4.js +0 -2
  350. package/dist/cli/chunks/impact-analyzer-4R4VWOGQ.js +0 -2
  351. package/dist/cli/chunks/init-wizard-TAOPXHHD.js +0 -2
  352. package/dist/cli/chunks/kernel-6I6VZUWY.js +0 -2
  353. package/dist/cli/chunks/knowledge-graph-KFMTTUR5.js +0 -2
  354. package/dist/cli/chunks/llm-router-service-2D74XVM3.js +0 -2
  355. package/dist/cli/chunks/load-test-53FWOWNS.js +0 -2
  356. package/dist/cli/chunks/memory-backend-KFJDDPEZ.js +0 -2
  357. package/dist/cli/chunks/pattern-null-store-7DMU5CJ4.js +0 -2
  358. package/dist/cli/chunks/protocol-executor-2EMTBTMG.js +0 -2
  359. package/dist/cli/chunks/qe-reasoning-bank-VZHZZPHE.js +0 -2
  360. package/dist/cli/chunks/queen-coordinator-7MYTTUHI.js +0 -2
  361. package/dist/cli/chunks/router-ZD4LXAWA.js +0 -2
  362. package/dist/cli/chunks/routing-feedback-FSLMDVGD.js +0 -2
  363. package/dist/cli/chunks/rvf-dual-writer-LTKTDRFS.js +0 -2
  364. package/dist/cli/chunks/rvf-migration-adapter-IF24EVC5.js +0 -2
  365. package/dist/cli/chunks/rvf-native-adapter-E6JNBKMZ.js +0 -2
  366. package/dist/cli/chunks/safe-db-F6TRB5KZ.js +0 -2
  367. package/dist/cli/chunks/schedule-HBD4BYTE.js +0 -2
  368. package/dist/cli/chunks/scheduler-6FYWPMQC.js +0 -2
  369. package/dist/cli/chunks/sqlite-persistence-DOU72F5Z.js +0 -2
  370. package/dist/cli/chunks/unified-memory-GHAYAXWZ.js +0 -2
  371. package/dist/cli/chunks/unified-memory-hnsw-CCC63YXT.js +0 -2
  372. package/dist/cli/chunks/unified-persistence-HKRHI5PG.js +0 -2
  373. package/dist/cli/chunks/visual-security-APOXJ3Q3.js +0 -2
  374. package/dist/cli/chunks/witness-chain-7IP5IJGT.js +0 -2
  375. package/dist/cli/chunks/workflow-orchestrator-2HNW5ZMQ.js +0 -2
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.8");process.exit(0)}
2
- import{b as fe}from"./chunk-TCQWVVSR.js";import{a as pt}from"./chunk-77WL5HQW.js";import{a as gt,b as mt}from"./chunk-K6EOHGKS.js";import{a as ut,b as dt}from"./chunk-G3C7Z6FO.js";import{j as I}from"./chunk-JTOFLDU7.js";import{a as st}from"./chunk-3FCHH4VP.js";import{a as ot,b as ct,c as lt}from"./chunk-D2Y36V5J.js";import{b as at}from"./chunk-BUVJIVFG.js";import{a as he}from"./chunk-GK5WLUX3.js";import{o as M,s as pe}from"./chunk-BZIPW2PA.js";import{b as w,d as rt}from"./chunk-BITFGVZ4.js";import{i as v}from"./chunk-UQGIC5OX.js";import{a as C,c as T,d as y}from"./chunk-EKO5QL2B.js";import{a as un}from"./chunk-U64QORFO.js";import{e as it}from"./chunk-J5HTQHJK.js";import{a as h,b as nt,e as k}from"./chunk-HPVYJ6JH.js";import{R as cn,S as ln}from"./chunk-R6I5I724.js";import{b as G,d as on,f as tt}from"./chunk-XAESN54Q.js";function Tt(a){let e=[],t=0;if(a.fileCount!==void 0&&(a.fileCount>20?(t+=25,e.push({name:"very-high-file-count",weight:25,description:`Task involves ${a.fileCount} files (>20)`})):a.fileCount>10?(t+=20,e.push({name:"high-file-count",weight:20,description:`Task involves ${a.fileCount} files (>10)`})):a.fileCount>5&&(t+=10,e.push({name:"moderate-file-count",weight:10,description:`Task involves ${a.fileCount} files (>5)`}))),a.domain&&(mn.includes(a.domain)?(t+=30,e.push({name:"complex-domain",weight:30,description:`Domain '${a.domain}' requires complex reasoning`})):pn.includes(a.domain)&&(t+=15,e.push({name:"moderate-domain",weight:15,description:`Domain '${a.domain}' has moderate complexity`}))),a.crossComponent&&(t+=25,e.push({name:"cross-component",weight:25,description:"Task spans multiple components/modules"})),a.priority==="critical"?(t+=25,e.push({name:"critical-priority",weight:25,description:"Critical priority requires careful attention"})):a.priority==="high"&&(t+=15,e.push({name:"high-priority",weight:15,description:"High priority task"})),a.requiredCapabilities){let r=a.requiredCapabilities.filter(s=>hn.includes(s)).length;if(r>0){let s=Math.min(20,r*10);t+=s,e.push({name:"complex-capabilities",weight:s,description:`Requires ${r} complex capabilit${r===1?"y":"ies"}`})}}a.requiresExternalApis&&(t+=10,e.push({name:"external-apis",weight:10,description:"Requires external API integration"})),a.involvesDatabaseOps&&(t+=10,e.push({name:"database-ops",weight:10,description:"Involves database operations"})),a.timeSensitive&&(t+=5,e.push({name:"time-sensitive",weight:5,description:"Time-sensitive task"})),a.estimatedLinesAffected!==void 0&&(a.estimatedLinesAffected>500?(t+=15,e.push({name:"large-change",weight:15,description:`Estimated ${a.estimatedLinesAffected} lines affected (>500)`})):a.estimatedLinesAffected>200&&(t+=10,e.push({name:"medium-change",weight:10,description:`Estimated ${a.estimatedLinesAffected} lines affected (>200)`}))),(a.type==="security-scan"||a.type==="vulnerability-assessment")&&(t+=20,e.push({name:"security-task",weight:20,description:"Security-related task requires careful analysis"}));let n=t>=S.critical?"critical":t>=S.complex?"complex":t>=S.moderate?"moderate":"simple",i=fn[n];return{complexity:n,recommendedModel:i,factors:e,score:t,timestamp:new Date}}var mn,pn,hn,S,fn,vt=G(()=>{"use strict";mn=["security-compliance","chaos-resilience","defect-intelligence"],pn=["code-intelligence","contract-testing","quality-assessment","learning-optimization"],hn=["sast","dast","vulnerability","owasp","chaos-testing","resilience","fault-injection","mutation-testing"],S={critical:70,complex:45,moderate:20},fn={critical:"opus",complex:"sonnet",moderate:"sonnet",simple:"haiku"}});var R,Ce=G(()=>{"use strict";R=class{weightsInputHidden;weightsHiddenOutput;biasHidden;biasOutput;learningRate;constructor(e=.01){this.learningRate=e,this.weightsInputHidden=this.xavierInit(4,32),this.weightsHiddenOutput=this.xavierInit(32,3),this.biasHidden=new Float32Array(32),this.biasOutput=new Float32Array(3)}xavierInit(e,t){let n=Math.sqrt(2/(e+t)),i=new Float32Array(e*t);for(let r=0;r<i.length;r++){let s=Math.random(),o=Math.random(),c=Math.sqrt(-2*Math.log(Math.max(s,1e-10)))*Math.cos(2*Math.PI*o);i[r]=c*n}return i}forward(e){if(e.length!==4)throw new Error(`Expected 4 features, got ${e.length}`);let t=new Float32Array(32);for(let i=0;i<32;i++){let r=this.biasHidden[i];for(let s=0;s<4;s++)r+=e[s]*this.weightsInputHidden[s*32+i];t[i]=Math.max(0,r)}let n=new Float32Array(3);for(let i=0;i<3;i++){let r=this.biasOutput[i];for(let s=0;s<32;s++)r+=t[s]*this.weightsHiddenOutput[s*3+i];n[i]=r}return this.softmax(n)}softmax(e){let t=Math.max(...e),n=new Float32Array(e.length),i=0;for(let s=0;s<e.length;s++)n[s]=Math.exp(e[s]-t),i+=n[s];let r=[];for(let s=0;s<e.length;s++)r.push(n[s]/i);return r}updateWeights(e,t,n){let i=new Float32Array(32);for(let l=0;l<32;l++){let u=this.biasHidden[l];for(let d=0;d<4;d++)u+=e[d]*this.weightsInputHidden[d*32+l];i[l]=Math.max(0,u)}let r=new Float32Array(3);for(let l=0;l<3;l++){let u=this.biasOutput[l];for(let d=0;d<32;d++)u+=i[d]*this.weightsHiddenOutput[d*3+l];r[l]=u}let s=this.softmax(r),o=new Float32Array(3);for(let l=0;l<3;l++)o[l]=(l===t?1:0)-s[l],o[l]*=n*this.learningRate;for(let l=0;l<32;l++)for(let u=0;u<3;u++)this.weightsHiddenOutput[l*3+u]+=i[l]*o[u];for(let l=0;l<3;l++)this.biasOutput[l]+=o[l];let c=new Float32Array(32);for(let l=0;l<32;l++){if(i[l]<=0)continue;let u=0;for(let d=0;d<3;d++)u+=o[d]*this.weightsHiddenOutput[l*3+d];c[l]=u}for(let l=0;l<4;l++)for(let u=0;u<32;u++)this.weightsInputHidden[l*32+u]+=e[l]*c[u];for(let l=0;l<32;l++)this.biasHidden[l]+=c[l]}serialize(){return{weightsInputHidden:Array.from(this.weightsInputHidden),weightsHiddenOutput:Array.from(this.weightsHiddenOutput),biasHidden:Array.from(this.biasHidden),biasOutput:Array.from(this.biasOutput)}}deserialize(e){e.weightsInputHidden.length===128&&(this.weightsInputHidden=new Float32Array(e.weightsInputHidden)),e.weightsHiddenOutput.length===96&&(this.weightsHiddenOutput=new Float32Array(e.weightsHiddenOutput)),e.biasHidden.length===32&&(this.biasHidden=new Float32Array(e.biasHidden)),e.biasOutput.length===3&&(this.biasOutput=new Float32Array(e.biasOutput))}}});var bt={};on(bt,{NeuralTinyDancerRouter:()=>W,SimpleNeuralRouter:()=>R,createNeuralTinyDancerRouter:()=>An});import{performance as Ct}from"perf_hooks";function An(a){return new W(a)}var yn,Tn,vn,Cn,bn,kn,Sn,Dn,W,kt=G(()=>{"use strict";be();Ce();Ce();yn=1e3,Tn=.1,vn=.2,Cn=50,bn=.01,kn=["haiku","sonnet","opus"],Sn={haiku:0,sonnet:1,opus:2},Dn={"test-generation":.1,"test-execution":.15,"coverage-analysis":.2,"quality-assessment":.3,"requirements-validation":.35,"code-intelligence":.4,"contract-testing":.45,"visual-accessibility":.5,"learning-optimization":.55,"defect-intelligence":.7,"chaos-resilience":.8,"security-compliance":.9},W=class{ruleRouter;neuralNet;circuitBreakerThreshold;shadowModeDecisionLimit;shadowModeMaxDisagreement;shadowModeActive;shadowDecisions=[];shadowDisagreements=0;circuitBreakerTripped=!1;recentOutcomes=[];totalNeuralDecisions=0;totalWeightUpdates=0;neuralPrimary=!1;calibrationScores=[];maxCalibrationScores=500;domainSuccessRates=new Map;config;nativeRouterAvailable=!1;constructor(e={}){this.config=e,this.ruleRouter=new H(e),this.neuralNet=new R(e.learningRate??bn),this.circuitBreakerThreshold=e.circuitBreakerThreshold??vn,this.shadowModeDecisionLimit=e.shadowModeDecisions??yn,this.shadowModeMaxDisagreement=e.shadowModeMaxDisagreement??Tn,e.forceShadowMode!==void 0?(this.shadowModeActive=e.forceShadowMode,this.neuralPrimary=!e.forceShadowMode):(this.shadowModeActive=!0,this.neuralPrimary=!1),this.tryLoadNativeRouter()}tryLoadNativeRouter(){this.nativeRouterAvailable=!1}async route(e){let t=Ct.now(),n=await this.ruleRouter.route(e);if(this.circuitBreakerTripped)return n;let i=this.extractFeatures(e,n.classification),r;try{r=this.neuralNet.forward(i)}catch{return this.tripCircuitBreaker(),n}let s=this.argmax(r),o=kn[s],c=r[s];if(this.totalNeuralDecisions++,this.shadowModeActive){let g=n.model===o;return g||this.shadowDisagreements++,this.shadowDecisions.push({taskDescription:e.description.slice(0,100),ruleDecision:n.model,neuralDecision:o,agreed:g,neuralConfidence:c,timestamp:new Date}),this.evaluateShadowModeExit(),n}let l=Ct.now()-t,u=this.computeEmpiricalConfidenceBounds(r);return c<.3||u.calibrationScore>.8?n:{model:o,confidence:c,uncertainty:1-c,triggerMultiModel:n.triggerMultiModel,triggerHumanReview:n.triggerHumanReview,complexity:n.complexity,classification:n.classification,latencyMs:l,reasoning:this.buildNeuralReasoning(o,c,r,n,u)}}extractFeatures(e,t){let n=Math.min(1,t.score/100),i=e.description.length,r=e.context?.code?.length??0,s=(i+r)/4,o=Math.min(1,s/1e4),c=e.domain??"",l=Dn[c]??.25,u=this.domainSuccessRates.get(c),d=u?u.success/Math.max(1,u.total):.7;return[n,o,l,d]}recordNeuralOutcome(e,t,n,i=n?1:0,r=t.model,s=0){this.ruleRouter.recordOutcome(e,t,n,i,r,s);let o=e.domain??"unknown",c=this.domainSuccessRates.get(o)??{success:0,total:0};c.total++,n&&c.success++,this.domainSuccessRates.set(o,c),this.recentOutcomes.push(n),this.recentOutcomes.length>Cn&&this.recentOutcomes.shift(),this.checkCircuitBreaker();let l=this.extractFeatures(e,t.classification),u=Sn[r],d=(i-.5)*2;try{this.neuralNet.updateWeights(l,u,d),this.totalWeightUpdates++}catch{}let g=this.neuralNet.forward(l),p=this.argmax(g),f=1-g[u];this.calibrationScores.push(f),this.calibrationScores.length>this.maxCalibrationScores&&this.calibrationScores.shift()}computeEmpiricalConfidenceBounds(e){let n=Math.max(...e),i=1-n;if(this.calibrationScores.length<10)return{lower:0,upper:1,coverageLevel:.9,calibrationScore:i};let r=[...this.calibrationScores].sort((c,l)=>c-l),s=Math.ceil(.9*r.length)-1,o=r[Math.min(s,r.length-1)];return{lower:Math.max(0,n-o),upper:Math.min(1,n+o),coverageLevel:.9,calibrationScore:i}}computeConformalBounds(e){return this.computeEmpiricalConfidenceBounds(e)}evaluateShadowModeExit(){if(!this.shadowModeActive||this.config.forceShadowMode===!0)return;let e=this.shadowDecisions.length;if(e<this.shadowModeDecisionLimit)return;this.shadowDisagreements/e<=this.shadowModeMaxDisagreement&&(this.shadowModeActive=!1,this.neuralPrimary=!0)}checkCircuitBreaker(){if(this.recentOutcomes.length<10)return;let t=this.recentOutcomes.filter(n=>!n).length/this.recentOutcomes.length;t>this.circuitBreakerThreshold?this.tripCircuitBreaker():this.circuitBreakerTripped&&t<this.circuitBreakerThreshold*.5&&(this.circuitBreakerTripped=!1)}tripCircuitBreaker(){this.circuitBreakerTripped=!0,this.neuralPrimary=!1}buildNeuralReasoning(e,t,n,i,r){let s=[];return s.push(`[Neural] Routing to ${e.toUpperCase()}`),s.push(`with ${(t*100).toFixed(0)}% neural confidence.`),s.push(`Tier probabilities: haiku=${(n[0]*100).toFixed(0)}%,`),s.push(`sonnet=${(n[1]*100).toFixed(0)}%,`),s.push(`opus=${(n[2]*100).toFixed(0)}%.`),e!==i.model&&s.push(`Rule-based would choose ${i.model.toUpperCase()}.`),s.push(`Empirical bounds: [${r.lower.toFixed(2)}, ${r.upper.toFixed(2)}]`),s.push(`at ${(r.coverageLevel*100).toFixed(0)}% coverage.`),s.join(" ")}argmax(e){let t=0,n=e[0];for(let i=1;i<e.length;i++)e[i]>n&&(n=e[i],t=i);return t}getNeuralStats(){let e=this.shadowDecisions.length,t=e>0?this.shadowDisagreements/e:0,n=this.recentOutcomes.filter(r=>!r).length,i=this.recentOutcomes.length>0?n/this.recentOutcomes.length:0;return{shadowModeActive:this.shadowModeActive,shadowDecisions:e,disagreementRate:t,circuitBreakerTripped:this.circuitBreakerTripped,recentErrorRate:i,totalNeuralDecisions:this.totalNeuralDecisions,totalWeightUpdates:this.totalWeightUpdates,neuralPrimary:this.neuralPrimary}}getShadowDecisionLogs(){return this.shadowDecisions}getRuleRouter(){return this.ruleRouter}getNeuralNet(){return this.neuralNet}isNativeRouterAvailable(){return this.nativeRouterAvailable}isShadowModeActive(){return this.shadowModeActive}isNeuralPrimary(){return this.neuralPrimary}isCircuitBreakerTripped(){return this.circuitBreakerTripped}resetCircuitBreaker(){this.circuitBreakerTripped=!1,this.recentOutcomes=[]}getStats(){return this.ruleRouter.getStats()}getConfig(){return this.ruleRouter.getConfig()}reset(){this.ruleRouter.reset(),this.shadowDecisions=[],this.shadowDisagreements=0,this.circuitBreakerTripped=!1,this.recentOutcomes=[],this.totalNeuralDecisions=0,this.totalWeightUpdates=0,this.calibrationScores=[],this.domainSuccessRates.clear(),this.config.forceShadowMode!==void 0?(this.shadowModeActive=this.config.forceShadowMode,this.neuralPrimary=!this.config.forceShadowMode):(this.shadowModeActive=!0,this.neuralPrimary=!1)}}});import{performance as St}from"perf_hooks";function Dt(a){try{let{getRuVectorFeatureFlags:e}=(ln(),tt(cn));if(e().useNeuralRouting){let{NeuralTinyDancerRouter:n}=(kt(),tt(bt));return new n(a)}}catch(e){process.env.DEBUG&&console.debug("[Router] Neural router unavailable, using rule-based:",e instanceof Error?e.message:e)}return new H(a)}var H,be=G(()=>{"use strict";vt();H=class{confidenceThreshold;uncertaintyThreshold;securityConfidenceThreshold;enableLearning;verbose;executor;totalRouted=0;routesByModel={haiku:0,sonnet:0,opus:0};routesByComplexity={simple:0,moderate:0,complex:0,critical:0};multiModelTriggers=0;humanReviewTriggers=0;advisorConsultations=0;totalConfidence=0;totalLatencyMs=0;outcomes=[];maxOutcomes=1e3;constructor(e={}){this.confidenceThreshold=e.confidenceThreshold??.8,this.uncertaintyThreshold=e.uncertaintyThreshold??.2,this.securityConfidenceThreshold=e.securityConfidenceThreshold??.85,this.enableLearning=e.enableLearning??!0,this.verbose=e.verbose??!1,this.executor=e.executor}hasExecutor(){return this.executor!==void 0}async routeWithAdvisor(e,t){let n=await this.route(e);if(!n.triggerMultiModel||!this.executor||!t)return{route:n};let i=await this.executor.consult(t,{agentName:e.agentId??e.id??"unknown",triggerReason:`tiny_dancer.confidence=${n.confidence.toFixed(2)}<${this.confidenceThreshold}`});return this.advisorConsultations++,{route:n,advisor:i}}async route(e){let t=St.now(),n=Tt(e),i=this.calculateConfidence(n),r=1-i,s=this.isSecurityTask(e),o=s&&i<this.securityConfidenceThreshold||i<this.confidenceThreshold&&n.complexity!=="simple",c=r>this.uncertaintyThreshold||s&&n.complexity==="critical",l=St.now()-t,u=this.buildReasoning(n,i,s,o,c),d={model:n.recommendedModel,confidence:i,uncertainty:r,triggerMultiModel:o,triggerHumanReview:c,complexity:n.complexity,classification:n,latencyMs:l,reasoning:u};return this.updateStats(d),this.verbose&&console.log(`[TinyDancer] Route: ${n.recommendedModel} (complexity=${n.complexity}, confidence=${(i*100).toFixed(1)}%)`),d}calculateConfidence(e){let{score:t,complexity:n}=e;if(n==="simple"&&t<10)return .9;if(n==="critical"&&t>85)return .92;let i=[S.moderate,S.complex,S.critical],r=1/0;for(let d of i){let g=Math.abs(t-d);g<r&&(r=g)}let s=.55,o=.35,c=Math.min(r/25,1),l=s+c*o,u=n!=="simple"?Math.min(.05,e.factors.length*.01):0;return Math.min(.95,l+u)}isSecurityTask(e){let t=e;if(t.type==="security-scan"||t.type==="vulnerability-assessment"||e.domain==="security-compliance")return!0;let n=["sast","dast","vulnerability","owasp","security-scanning"];if(e.requiredCapabilities?.some(s=>n.includes(s)))return!0;let i=["security","vulnerability","cve","owasp","exploit","injection"],r=e.description.toLowerCase();return!!i.some(s=>r.includes(s))}buildReasoning(e,t,n,i,r){let s=[];if(s.push(`Routing to ${e.recommendedModel.toUpperCase()}`),s.push(`(complexity: ${e.complexity}, score: ${e.score})`),s.push(`with ${(t*100).toFixed(0)}% confidence.`),e.factors.length>0){let o=e.factors.slice(0,3).map(c=>c.name).join(", ");s.push(`Key factors: ${o}.`)}return n&&s.push("Security-sensitive task detected."),i&&s.push("Multi-model verification recommended due to uncertainty."),r&&s.push("Human review flagged due to high uncertainty or criticality."),s.join(" ")}updateStats(e){this.totalRouted++,this.routesByModel[e.model]++,this.routesByComplexity[e.complexity]++,this.totalConfidence+=e.confidence,this.totalLatencyMs+=e.latencyMs,e.triggerMultiModel&&this.multiModelTriggers++,e.triggerHumanReview&&this.humanReviewTriggers++}recordOutcome(e,t,n,i=n?1:0,r=t.model,s=0){if(!this.enableLearning)return;let o={task:e,routeResult:t,success:n,qualityScore:i,actualModelUsed:r,durationMs:s,timestamp:new Date};this.outcomes.push(o),this.outcomes.length>this.maxOutcomes&&this.outcomes.shift(),this.verbose&&console.log(`[TinyDancer] Recorded outcome: success=${n}, quality=${(i*100).toFixed(0)}%, model=${r}`)}getStats(){return{totalRouted:this.totalRouted,routesByModel:{...this.routesByModel},routesByComplexity:{...this.routesByComplexity},multiModelTriggers:this.multiModelTriggers,advisorConsultations:this.advisorConsultations,humanReviewTriggers:this.humanReviewTriggers,avgConfidence:this.totalRouted>0?this.totalConfidence/this.totalRouted:0,avgLatencyMs:this.totalRouted>0?this.totalLatencyMs/this.totalRouted:0,outcomesRecorded:this.outcomes.length}}getOutcomes(){return this.outcomes}getSuccessRateByModel(){let e={haiku:{success:0,total:0},sonnet:{success:0,total:0},opus:{success:0,total:0}};for(let t of this.outcomes){let n=t.actualModelUsed;e[n].total++,t.success&&e[n].success++}return{haiku:e.haiku.total>0?e.haiku.success/e.haiku.total:0,sonnet:e.sonnet.total>0?e.sonnet.success/e.sonnet.total:0,opus:e.opus.total>0?e.opus.success/e.opus.total:0}}reset(){this.totalRouted=0,this.routesByModel={haiku:0,sonnet:0,opus:0},this.routesByComplexity={simple:0,moderate:0,complex:0,critical:0},this.multiModelTriggers=0,this.advisorConsultations=0,this.humanReviewTriggers=0,this.totalConfidence=0,this.totalLatencyMs=0,this.outcomes=[]}getConfig(){return{confidenceThreshold:this.confidenceThreshold,uncertaintyThreshold:this.uncertaintyThreshold,securityConfidenceThreshold:this.securityConfidenceThreshold,enableLearning:this.enableLearning,verbose:this.verbose}}}});import{randomUUID as ht}from"node:crypto";var dn={enableConsoleLog:!0,maxEntries:1e3,logPrefix:"[TASK]"},j=class{entries=[];config;generation=ht();recordedEntries=0;droppedEntries=0;constructor(e={}){if(this.config={...dn,...e},!Number.isSafeInteger(this.config.maxEntries)||this.config.maxEntries<0)throw new RangeError("maxEntries must be a non-negative safe integer")}log(e,t,n){let i={sequence:++this.recordedEntries,timestamp:new Date,operation:e,taskId:t,agentId:n?.agentId,domain:n?.domain,details:n?.details};if(this.entries.push(i),this.entries.length>this.config.maxEntries){let r=this.entries.length-this.config.maxEntries;this.entries.splice(0,r),this.droppedEntries+=r}if(this.config.enableConsoleLog){let r=n?.agentId?` by ${n.agentId}`:"",s=n?.domain?` (${n.domain})`:"";console.log(`${this.config.logPrefix} ${e.toUpperCase()} ${t}${r}${s}`)}}logSubmit(e,t){this.log("submit",e,{details:t})}logAssign(e,t,n){this.log("assign",e,{agentId:t,domain:n})}logReassign(e,t,n,i){this.log("reassign",e,{agentId:n,domain:i,details:{fromAgent:t}})}logComplete(e,t){this.log("complete",e,{agentId:t})}logFail(e,t,n){this.log("fail",e,{agentId:t,details:n?{error:n}:void 0})}logCancel(e){this.log("cancel",e)}logSteal(e,t,n){this.log("steal",e,{domain:n,details:{fromDomain:t}})}logQueue(e,t){this.log("queue",e,{details:{position:t}})}logDequeue(e){this.log("dequeue",e)}getEntries(e){let t=[...this.entries];e&&(e.operation&&(t=t.filter(i=>i.operation===e.operation)),e.taskId&&(t=t.filter(i=>i.taskId===e.taskId)),e.agentId&&(t=t.filter(i=>i.agentId===e.agentId)),e.domain&&(t=t.filter(i=>i.domain===e.domain)),e.fromTimestamp&&(t=t.filter(i=>i.timestamp>=e.fromTimestamp)),e.toTimestamp&&(t=t.filter(i=>i.timestamp<=e.toTimestamp)));let n=e?.limit??t.length;return n===0?[]:t.slice(-n)}getSnapshot(e){return{...this.getWindow(),entries:this.getEntries(e)}}getWindow(){return{generation:this.generation,recordedEntries:this.recordedEntries,retainedEntries:this.entries.length,droppedEntries:this.droppedEntries,firstRetainedSequence:this.entries[0]?.sequence??null,lastRetainedSequence:this.entries[this.entries.length-1]?.sequence??null,disposition:this.droppedEntries>0?"truncated":"complete"}}getStatistics(){let e={submit:0,assign:0,reassign:0,complete:0,fail:0,cancel:0,steal:0,queue:0,dequeue:0},t=new Set,n=new Set;for(let i of this.entries)e[i.operation]++,t.add(i.taskId),i.agentId&&n.add(i.agentId);return{...this.getWindow(),basis:"retained-window",totalEntries:this.entries.length,operationCounts:e,taskCount:t.size,agentCount:n.size}}clear(){this.entries.length=0,this.generation=ht(),this.recordedEntries=0,this.droppedEntries=0}};function ye(a){return new j(a)}pe();rt();var Te=class{memory;initialized=!1;constructor(e){this.memory=e??M()}async initialize(){this.initialized||(this.memory.isInitialized()||await this.memory.initialize(),this.initialized=!0)}async saveSnapshot(e){this.ensureInitialized();let t=v();return this.memory.getDatabase().prepare(`
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.15.1");process.exit(0)}
2
+ import{b as fe}from"./chunk-DKWB4ERY.js";import{a as pt}from"./chunk-T5K6ZCA6.js";import{a as gt,b as mt}from"./chunk-BW7S6LIJ.js";import{a as ut,b as dt}from"./chunk-7B3XVVYP.js";import{j as I}from"./chunk-TR37Q7A6.js";import{a as st}from"./chunk-UOHZRR5C.js";import{a as ot,b as ct,c as lt}from"./chunk-RDI3W4H6.js";import{b as at}from"./chunk-B3DWOR5R.js";import{a as he}from"./chunk-PGARKOE6.js";import{o as M,s as pe}from"./chunk-NF6SLLE6.js";import{b as w,d as rt}from"./chunk-5C4UYXQL.js";import{i as v}from"./chunk-LQI5GVH7.js";import{a as C,c as T,d as y}from"./chunk-PZDI7WQ3.js";import{a as un}from"./chunk-2K3QFLX2.js";import{e as it}from"./chunk-7FGSX4UD.js";import{a as h,b as nt,e as k}from"./chunk-ARWSPV2C.js";import{R as cn,S as ln}from"./chunk-HU4QGCIJ.js";import{b as G,d as on,f as tt}from"./chunk-PNK5KHSI.js";function Tt(a){let e=[],t=0;if(a.fileCount!==void 0&&(a.fileCount>20?(t+=25,e.push({name:"very-high-file-count",weight:25,description:`Task involves ${a.fileCount} files (>20)`})):a.fileCount>10?(t+=20,e.push({name:"high-file-count",weight:20,description:`Task involves ${a.fileCount} files (>10)`})):a.fileCount>5&&(t+=10,e.push({name:"moderate-file-count",weight:10,description:`Task involves ${a.fileCount} files (>5)`}))),a.domain&&(mn.includes(a.domain)?(t+=30,e.push({name:"complex-domain",weight:30,description:`Domain '${a.domain}' requires complex reasoning`})):pn.includes(a.domain)&&(t+=15,e.push({name:"moderate-domain",weight:15,description:`Domain '${a.domain}' has moderate complexity`}))),a.crossComponent&&(t+=25,e.push({name:"cross-component",weight:25,description:"Task spans multiple components/modules"})),a.priority==="critical"?(t+=25,e.push({name:"critical-priority",weight:25,description:"Critical priority requires careful attention"})):a.priority==="high"&&(t+=15,e.push({name:"high-priority",weight:15,description:"High priority task"})),a.requiredCapabilities){let r=a.requiredCapabilities.filter(s=>hn.includes(s)).length;if(r>0){let s=Math.min(20,r*10);t+=s,e.push({name:"complex-capabilities",weight:s,description:`Requires ${r} complex capabilit${r===1?"y":"ies"}`})}}a.requiresExternalApis&&(t+=10,e.push({name:"external-apis",weight:10,description:"Requires external API integration"})),a.involvesDatabaseOps&&(t+=10,e.push({name:"database-ops",weight:10,description:"Involves database operations"})),a.timeSensitive&&(t+=5,e.push({name:"time-sensitive",weight:5,description:"Time-sensitive task"})),a.estimatedLinesAffected!==void 0&&(a.estimatedLinesAffected>500?(t+=15,e.push({name:"large-change",weight:15,description:`Estimated ${a.estimatedLinesAffected} lines affected (>500)`})):a.estimatedLinesAffected>200&&(t+=10,e.push({name:"medium-change",weight:10,description:`Estimated ${a.estimatedLinesAffected} lines affected (>200)`}))),(a.type==="security-scan"||a.type==="vulnerability-assessment")&&(t+=20,e.push({name:"security-task",weight:20,description:"Security-related task requires careful analysis"}));let n=t>=S.critical?"critical":t>=S.complex?"complex":t>=S.moderate?"moderate":"simple",i=fn[n];return{complexity:n,recommendedModel:i,factors:e,score:t,timestamp:new Date}}var mn,pn,hn,S,fn,vt=G(()=>{"use strict";mn=["security-compliance","chaos-resilience","defect-intelligence"],pn=["code-intelligence","contract-testing","quality-assessment","learning-optimization"],hn=["sast","dast","vulnerability","owasp","chaos-testing","resilience","fault-injection","mutation-testing"],S={critical:70,complex:45,moderate:20},fn={critical:"opus",complex:"sonnet",moderate:"sonnet",simple:"haiku"}});var R,Ce=G(()=>{"use strict";R=class{weightsInputHidden;weightsHiddenOutput;biasHidden;biasOutput;learningRate;constructor(e=.01){this.learningRate=e,this.weightsInputHidden=this.xavierInit(4,32),this.weightsHiddenOutput=this.xavierInit(32,3),this.biasHidden=new Float32Array(32),this.biasOutput=new Float32Array(3)}xavierInit(e,t){let n=Math.sqrt(2/(e+t)),i=new Float32Array(e*t);for(let r=0;r<i.length;r++){let s=Math.random(),o=Math.random(),c=Math.sqrt(-2*Math.log(Math.max(s,1e-10)))*Math.cos(2*Math.PI*o);i[r]=c*n}return i}forward(e){if(e.length!==4)throw new Error(`Expected 4 features, got ${e.length}`);let t=new Float32Array(32);for(let i=0;i<32;i++){let r=this.biasHidden[i];for(let s=0;s<4;s++)r+=e[s]*this.weightsInputHidden[s*32+i];t[i]=Math.max(0,r)}let n=new Float32Array(3);for(let i=0;i<3;i++){let r=this.biasOutput[i];for(let s=0;s<32;s++)r+=t[s]*this.weightsHiddenOutput[s*3+i];n[i]=r}return this.softmax(n)}softmax(e){let t=Math.max(...e),n=new Float32Array(e.length),i=0;for(let s=0;s<e.length;s++)n[s]=Math.exp(e[s]-t),i+=n[s];let r=[];for(let s=0;s<e.length;s++)r.push(n[s]/i);return r}updateWeights(e,t,n){let i=new Float32Array(32);for(let l=0;l<32;l++){let u=this.biasHidden[l];for(let d=0;d<4;d++)u+=e[d]*this.weightsInputHidden[d*32+l];i[l]=Math.max(0,u)}let r=new Float32Array(3);for(let l=0;l<3;l++){let u=this.biasOutput[l];for(let d=0;d<32;d++)u+=i[d]*this.weightsHiddenOutput[d*3+l];r[l]=u}let s=this.softmax(r),o=new Float32Array(3);for(let l=0;l<3;l++)o[l]=(l===t?1:0)-s[l],o[l]*=n*this.learningRate;for(let l=0;l<32;l++)for(let u=0;u<3;u++)this.weightsHiddenOutput[l*3+u]+=i[l]*o[u];for(let l=0;l<3;l++)this.biasOutput[l]+=o[l];let c=new Float32Array(32);for(let l=0;l<32;l++){if(i[l]<=0)continue;let u=0;for(let d=0;d<3;d++)u+=o[d]*this.weightsHiddenOutput[l*3+d];c[l]=u}for(let l=0;l<4;l++)for(let u=0;u<32;u++)this.weightsInputHidden[l*32+u]+=e[l]*c[u];for(let l=0;l<32;l++)this.biasHidden[l]+=c[l]}serialize(){return{weightsInputHidden:Array.from(this.weightsInputHidden),weightsHiddenOutput:Array.from(this.weightsHiddenOutput),biasHidden:Array.from(this.biasHidden),biasOutput:Array.from(this.biasOutput)}}deserialize(e){e.weightsInputHidden.length===128&&(this.weightsInputHidden=new Float32Array(e.weightsInputHidden)),e.weightsHiddenOutput.length===96&&(this.weightsHiddenOutput=new Float32Array(e.weightsHiddenOutput)),e.biasHidden.length===32&&(this.biasHidden=new Float32Array(e.biasHidden)),e.biasOutput.length===3&&(this.biasOutput=new Float32Array(e.biasOutput))}}});var bt={};on(bt,{NeuralTinyDancerRouter:()=>W,SimpleNeuralRouter:()=>R,createNeuralTinyDancerRouter:()=>An});import{performance as Ct}from"perf_hooks";function An(a){return new W(a)}var yn,Tn,vn,Cn,bn,kn,Sn,Dn,W,kt=G(()=>{"use strict";be();Ce();Ce();yn=1e3,Tn=.1,vn=.2,Cn=50,bn=.01,kn=["haiku","sonnet","opus"],Sn={haiku:0,sonnet:1,opus:2},Dn={"test-generation":.1,"test-execution":.15,"coverage-analysis":.2,"quality-assessment":.3,"requirements-validation":.35,"code-intelligence":.4,"contract-testing":.45,"visual-accessibility":.5,"learning-optimization":.55,"defect-intelligence":.7,"chaos-resilience":.8,"security-compliance":.9},W=class{ruleRouter;neuralNet;circuitBreakerThreshold;shadowModeDecisionLimit;shadowModeMaxDisagreement;shadowModeActive;shadowDecisions=[];shadowDisagreements=0;circuitBreakerTripped=!1;recentOutcomes=[];totalNeuralDecisions=0;totalWeightUpdates=0;neuralPrimary=!1;calibrationScores=[];maxCalibrationScores=500;domainSuccessRates=new Map;config;nativeRouterAvailable=!1;constructor(e={}){this.config=e,this.ruleRouter=new H(e),this.neuralNet=new R(e.learningRate??bn),this.circuitBreakerThreshold=e.circuitBreakerThreshold??vn,this.shadowModeDecisionLimit=e.shadowModeDecisions??yn,this.shadowModeMaxDisagreement=e.shadowModeMaxDisagreement??Tn,e.forceShadowMode!==void 0?(this.shadowModeActive=e.forceShadowMode,this.neuralPrimary=!e.forceShadowMode):(this.shadowModeActive=!0,this.neuralPrimary=!1),this.tryLoadNativeRouter()}tryLoadNativeRouter(){this.nativeRouterAvailable=!1}async route(e){let t=Ct.now(),n=await this.ruleRouter.route(e);if(this.circuitBreakerTripped)return n;let i=this.extractFeatures(e,n.classification),r;try{r=this.neuralNet.forward(i)}catch{return this.tripCircuitBreaker(),n}let s=this.argmax(r),o=kn[s],c=r[s];if(this.totalNeuralDecisions++,this.shadowModeActive){let g=n.model===o;return g||this.shadowDisagreements++,this.shadowDecisions.push({taskDescription:e.description.slice(0,100),ruleDecision:n.model,neuralDecision:o,agreed:g,neuralConfidence:c,timestamp:new Date}),this.evaluateShadowModeExit(),n}let l=Ct.now()-t,u=this.computeEmpiricalConfidenceBounds(r);return c<.3||u.calibrationScore>.8?n:{model:o,confidence:c,uncertainty:1-c,triggerMultiModel:n.triggerMultiModel,triggerHumanReview:n.triggerHumanReview,complexity:n.complexity,classification:n.classification,latencyMs:l,reasoning:this.buildNeuralReasoning(o,c,r,n,u)}}extractFeatures(e,t){let n=Math.min(1,t.score/100),i=e.description.length,r=e.context?.code?.length??0,s=(i+r)/4,o=Math.min(1,s/1e4),c=e.domain??"",l=Dn[c]??.25,u=this.domainSuccessRates.get(c),d=u?u.success/Math.max(1,u.total):.7;return[n,o,l,d]}recordNeuralOutcome(e,t,n,i=n?1:0,r=t.model,s=0){this.ruleRouter.recordOutcome(e,t,n,i,r,s);let o=e.domain??"unknown",c=this.domainSuccessRates.get(o)??{success:0,total:0};c.total++,n&&c.success++,this.domainSuccessRates.set(o,c),this.recentOutcomes.push(n),this.recentOutcomes.length>Cn&&this.recentOutcomes.shift(),this.checkCircuitBreaker();let l=this.extractFeatures(e,t.classification),u=Sn[r],d=(i-.5)*2;try{this.neuralNet.updateWeights(l,u,d),this.totalWeightUpdates++}catch{}let g=this.neuralNet.forward(l),p=this.argmax(g),f=1-g[u];this.calibrationScores.push(f),this.calibrationScores.length>this.maxCalibrationScores&&this.calibrationScores.shift()}computeEmpiricalConfidenceBounds(e){let n=Math.max(...e),i=1-n;if(this.calibrationScores.length<10)return{lower:0,upper:1,coverageLevel:.9,calibrationScore:i};let r=[...this.calibrationScores].sort((c,l)=>c-l),s=Math.ceil(.9*r.length)-1,o=r[Math.min(s,r.length-1)];return{lower:Math.max(0,n-o),upper:Math.min(1,n+o),coverageLevel:.9,calibrationScore:i}}computeConformalBounds(e){return this.computeEmpiricalConfidenceBounds(e)}evaluateShadowModeExit(){if(!this.shadowModeActive||this.config.forceShadowMode===!0)return;let e=this.shadowDecisions.length;if(e<this.shadowModeDecisionLimit)return;this.shadowDisagreements/e<=this.shadowModeMaxDisagreement&&(this.shadowModeActive=!1,this.neuralPrimary=!0)}checkCircuitBreaker(){if(this.recentOutcomes.length<10)return;let t=this.recentOutcomes.filter(n=>!n).length/this.recentOutcomes.length;t>this.circuitBreakerThreshold?this.tripCircuitBreaker():this.circuitBreakerTripped&&t<this.circuitBreakerThreshold*.5&&(this.circuitBreakerTripped=!1)}tripCircuitBreaker(){this.circuitBreakerTripped=!0,this.neuralPrimary=!1}buildNeuralReasoning(e,t,n,i,r){let s=[];return s.push(`[Neural] Routing to ${e.toUpperCase()}`),s.push(`with ${(t*100).toFixed(0)}% neural confidence.`),s.push(`Tier probabilities: haiku=${(n[0]*100).toFixed(0)}%,`),s.push(`sonnet=${(n[1]*100).toFixed(0)}%,`),s.push(`opus=${(n[2]*100).toFixed(0)}%.`),e!==i.model&&s.push(`Rule-based would choose ${i.model.toUpperCase()}.`),s.push(`Empirical bounds: [${r.lower.toFixed(2)}, ${r.upper.toFixed(2)}]`),s.push(`at ${(r.coverageLevel*100).toFixed(0)}% coverage.`),s.join(" ")}argmax(e){let t=0,n=e[0];for(let i=1;i<e.length;i++)e[i]>n&&(n=e[i],t=i);return t}getNeuralStats(){let e=this.shadowDecisions.length,t=e>0?this.shadowDisagreements/e:0,n=this.recentOutcomes.filter(r=>!r).length,i=this.recentOutcomes.length>0?n/this.recentOutcomes.length:0;return{shadowModeActive:this.shadowModeActive,shadowDecisions:e,disagreementRate:t,circuitBreakerTripped:this.circuitBreakerTripped,recentErrorRate:i,totalNeuralDecisions:this.totalNeuralDecisions,totalWeightUpdates:this.totalWeightUpdates,neuralPrimary:this.neuralPrimary}}getShadowDecisionLogs(){return this.shadowDecisions}getRuleRouter(){return this.ruleRouter}getNeuralNet(){return this.neuralNet}isNativeRouterAvailable(){return this.nativeRouterAvailable}isShadowModeActive(){return this.shadowModeActive}isNeuralPrimary(){return this.neuralPrimary}isCircuitBreakerTripped(){return this.circuitBreakerTripped}resetCircuitBreaker(){this.circuitBreakerTripped=!1,this.recentOutcomes=[]}getStats(){return this.ruleRouter.getStats()}getConfig(){return this.ruleRouter.getConfig()}reset(){this.ruleRouter.reset(),this.shadowDecisions=[],this.shadowDisagreements=0,this.circuitBreakerTripped=!1,this.recentOutcomes=[],this.totalNeuralDecisions=0,this.totalWeightUpdates=0,this.calibrationScores=[],this.domainSuccessRates.clear(),this.config.forceShadowMode!==void 0?(this.shadowModeActive=this.config.forceShadowMode,this.neuralPrimary=!this.config.forceShadowMode):(this.shadowModeActive=!0,this.neuralPrimary=!1)}}});import{performance as St}from"perf_hooks";function Dt(a){try{let{getRuVectorFeatureFlags:e}=(ln(),tt(cn));if(e().useNeuralRouting){let{NeuralTinyDancerRouter:n}=(kt(),tt(bt));return new n(a)}}catch(e){process.env.DEBUG&&console.debug("[Router] Neural router unavailable, using rule-based:",e instanceof Error?e.message:e)}return new H(a)}var H,be=G(()=>{"use strict";vt();H=class{confidenceThreshold;uncertaintyThreshold;securityConfidenceThreshold;enableLearning;verbose;executor;totalRouted=0;routesByModel={haiku:0,sonnet:0,opus:0};routesByComplexity={simple:0,moderate:0,complex:0,critical:0};multiModelTriggers=0;humanReviewTriggers=0;advisorConsultations=0;totalConfidence=0;totalLatencyMs=0;outcomes=[];maxOutcomes=1e3;constructor(e={}){this.confidenceThreshold=e.confidenceThreshold??.8,this.uncertaintyThreshold=e.uncertaintyThreshold??.2,this.securityConfidenceThreshold=e.securityConfidenceThreshold??.85,this.enableLearning=e.enableLearning??!0,this.verbose=e.verbose??!1,this.executor=e.executor}hasExecutor(){return this.executor!==void 0}async routeWithAdvisor(e,t){let n=await this.route(e);if(!n.triggerMultiModel||!this.executor||!t)return{route:n};let i=await this.executor.consult(t,{agentName:e.agentId??e.id??"unknown",triggerReason:`tiny_dancer.confidence=${n.confidence.toFixed(2)}<${this.confidenceThreshold}`});return this.advisorConsultations++,{route:n,advisor:i}}async route(e){let t=St.now(),n=Tt(e),i=this.calculateConfidence(n),r=1-i,s=this.isSecurityTask(e),o=s&&i<this.securityConfidenceThreshold||i<this.confidenceThreshold&&n.complexity!=="simple",c=r>this.uncertaintyThreshold||s&&n.complexity==="critical",l=St.now()-t,u=this.buildReasoning(n,i,s,o,c),d={model:n.recommendedModel,confidence:i,uncertainty:r,triggerMultiModel:o,triggerHumanReview:c,complexity:n.complexity,classification:n,latencyMs:l,reasoning:u};return this.updateStats(d),this.verbose&&console.log(`[TinyDancer] Route: ${n.recommendedModel} (complexity=${n.complexity}, confidence=${(i*100).toFixed(1)}%)`),d}calculateConfidence(e){let{score:t,complexity:n}=e;if(n==="simple"&&t<10)return .9;if(n==="critical"&&t>85)return .92;let i=[S.moderate,S.complex,S.critical],r=1/0;for(let d of i){let g=Math.abs(t-d);g<r&&(r=g)}let s=.55,o=.35,c=Math.min(r/25,1),l=s+c*o,u=n!=="simple"?Math.min(.05,e.factors.length*.01):0;return Math.min(.95,l+u)}isSecurityTask(e){let t=e;if(t.type==="security-scan"||t.type==="vulnerability-assessment"||e.domain==="security-compliance")return!0;let n=["sast","dast","vulnerability","owasp","security-scanning"];if(e.requiredCapabilities?.some(s=>n.includes(s)))return!0;let i=["security","vulnerability","cve","owasp","exploit","injection"],r=e.description.toLowerCase();return!!i.some(s=>r.includes(s))}buildReasoning(e,t,n,i,r){let s=[];if(s.push(`Routing to ${e.recommendedModel.toUpperCase()}`),s.push(`(complexity: ${e.complexity}, score: ${e.score})`),s.push(`with ${(t*100).toFixed(0)}% confidence.`),e.factors.length>0){let o=e.factors.slice(0,3).map(c=>c.name).join(", ");s.push(`Key factors: ${o}.`)}return n&&s.push("Security-sensitive task detected."),i&&s.push("Multi-model verification recommended due to uncertainty."),r&&s.push("Human review flagged due to high uncertainty or criticality."),s.join(" ")}updateStats(e){this.totalRouted++,this.routesByModel[e.model]++,this.routesByComplexity[e.complexity]++,this.totalConfidence+=e.confidence,this.totalLatencyMs+=e.latencyMs,e.triggerMultiModel&&this.multiModelTriggers++,e.triggerHumanReview&&this.humanReviewTriggers++}recordOutcome(e,t,n,i=n?1:0,r=t.model,s=0){if(!this.enableLearning)return;let o={task:e,routeResult:t,success:n,qualityScore:i,actualModelUsed:r,durationMs:s,timestamp:new Date};this.outcomes.push(o),this.outcomes.length>this.maxOutcomes&&this.outcomes.shift(),this.verbose&&console.log(`[TinyDancer] Recorded outcome: success=${n}, quality=${(i*100).toFixed(0)}%, model=${r}`)}getStats(){return{totalRouted:this.totalRouted,routesByModel:{...this.routesByModel},routesByComplexity:{...this.routesByComplexity},multiModelTriggers:this.multiModelTriggers,advisorConsultations:this.advisorConsultations,humanReviewTriggers:this.humanReviewTriggers,avgConfidence:this.totalRouted>0?this.totalConfidence/this.totalRouted:0,avgLatencyMs:this.totalRouted>0?this.totalLatencyMs/this.totalRouted:0,outcomesRecorded:this.outcomes.length}}getOutcomes(){return this.outcomes}getSuccessRateByModel(){let e={haiku:{success:0,total:0},sonnet:{success:0,total:0},opus:{success:0,total:0}};for(let t of this.outcomes){let n=t.actualModelUsed;e[n].total++,t.success&&e[n].success++}return{haiku:e.haiku.total>0?e.haiku.success/e.haiku.total:0,sonnet:e.sonnet.total>0?e.sonnet.success/e.sonnet.total:0,opus:e.opus.total>0?e.opus.success/e.opus.total:0}}reset(){this.totalRouted=0,this.routesByModel={haiku:0,sonnet:0,opus:0},this.routesByComplexity={simple:0,moderate:0,complex:0,critical:0},this.multiModelTriggers=0,this.advisorConsultations=0,this.humanReviewTriggers=0,this.totalConfidence=0,this.totalLatencyMs=0,this.outcomes=[]}getConfig(){return{confidenceThreshold:this.confidenceThreshold,uncertaintyThreshold:this.uncertaintyThreshold,securityConfidenceThreshold:this.securityConfidenceThreshold,enableLearning:this.enableLearning,verbose:this.verbose}}}});import{randomUUID as ht}from"node:crypto";var dn={enableConsoleLog:!0,maxEntries:1e3,logPrefix:"[TASK]"},j=class{entries=[];config;generation=ht();recordedEntries=0;droppedEntries=0;constructor(e={}){if(this.config={...dn,...e},!Number.isSafeInteger(this.config.maxEntries)||this.config.maxEntries<0)throw new RangeError("maxEntries must be a non-negative safe integer")}log(e,t,n){let i={sequence:++this.recordedEntries,timestamp:new Date,operation:e,taskId:t,agentId:n?.agentId,domain:n?.domain,details:n?.details};if(this.entries.push(i),this.entries.length>this.config.maxEntries){let r=this.entries.length-this.config.maxEntries;this.entries.splice(0,r),this.droppedEntries+=r}if(this.config.enableConsoleLog){let r=n?.agentId?` by ${n.agentId}`:"",s=n?.domain?` (${n.domain})`:"";console.log(`${this.config.logPrefix} ${e.toUpperCase()} ${t}${r}${s}`)}}logSubmit(e,t){this.log("submit",e,{details:t})}logAssign(e,t,n){this.log("assign",e,{agentId:t,domain:n})}logReassign(e,t,n,i){this.log("reassign",e,{agentId:n,domain:i,details:{fromAgent:t}})}logComplete(e,t){this.log("complete",e,{agentId:t})}logFail(e,t,n){this.log("fail",e,{agentId:t,details:n?{error:n}:void 0})}logCancel(e){this.log("cancel",e)}logSteal(e,t,n){this.log("steal",e,{domain:n,details:{fromDomain:t}})}logQueue(e,t){this.log("queue",e,{details:{position:t}})}logDequeue(e){this.log("dequeue",e)}getEntries(e){let t=[...this.entries];e&&(e.operation&&(t=t.filter(i=>i.operation===e.operation)),e.taskId&&(t=t.filter(i=>i.taskId===e.taskId)),e.agentId&&(t=t.filter(i=>i.agentId===e.agentId)),e.domain&&(t=t.filter(i=>i.domain===e.domain)),e.fromTimestamp&&(t=t.filter(i=>i.timestamp>=e.fromTimestamp)),e.toTimestamp&&(t=t.filter(i=>i.timestamp<=e.toTimestamp)));let n=e?.limit??t.length;return n===0?[]:t.slice(-n)}getSnapshot(e){return{...this.getWindow(),entries:this.getEntries(e)}}getWindow(){return{generation:this.generation,recordedEntries:this.recordedEntries,retainedEntries:this.entries.length,droppedEntries:this.droppedEntries,firstRetainedSequence:this.entries[0]?.sequence??null,lastRetainedSequence:this.entries[this.entries.length-1]?.sequence??null,disposition:this.droppedEntries>0?"truncated":"complete"}}getStatistics(){let e={submit:0,assign:0,reassign:0,complete:0,fail:0,cancel:0,steal:0,queue:0,dequeue:0},t=new Set,n=new Set;for(let i of this.entries)e[i.operation]++,t.add(i.taskId),i.agentId&&n.add(i.agentId);return{...this.getWindow(),basis:"retained-window",totalEntries:this.entries.length,operationCounts:e,taskCount:t.size,agentCount:n.size}}clear(){this.entries.length=0,this.generation=ht(),this.recordedEntries=0,this.droppedEntries=0}};function ye(a){return new j(a)}pe();rt();var Te=class{memory;initialized=!1;constructor(e){this.memory=e??M()}async initialize(){this.initialized||(this.memory.isInitialized()||await this.memory.initialize(),this.initialized=!0)}async saveSnapshot(e){this.ensureInitialized();let t=v();return this.memory.getDatabase().prepare(`
3
3
  INSERT INTO mincut_snapshots (
4
4
  id, timestamp, vertex_count, edge_count, total_weight,
5
5
  is_connected, component_count, vertices_json, edges_json
@@ -177,4 +177,4 @@ import{b as fe}from"./chunk-TCQWVVSR.js";import{a as pt}from"./chunk-77WL5HQW.js
177
177
  `;let i=this.getRecommendations(n);if(i.length>0){t+=`**Recommendations:**
178
178
  `;for(let r of i)t+=`- ${r}
179
179
  `;t+=`
180
- `}}return t}getRecommendations(e){switch(e.loopType){case"strategic":return[...e.recommendations.forRiskAssessor,...e.recommendations.forQualityCriteria];case"tactical":return e.recommendations.forProductFactorsAssessor;case"operational":return[...e.recommendations.forTestArchitect,...e.recommendations.antiPatterns];case"quality-criteria":return e.recommendations.forRequirementsValidator;default:return[]}}filterManagedHooks(e){if(process.env.AQE_HOOKS_MANAGED_ONLY!=="true")return e;let t=e.filter(([n])=>n.startsWith("managed:"));return t.length<e.length&&console.log(`[CrossPhaseHooks] AQE_HOOKS_MANAGED_ONLY: filtered ${e.length-t.length} non-managed hooks`),t}async isBlockedUrl(e){if(!e.includes("://"))return!1;let t=await fe(e);return t.safe?!1:(console.warn(`[CrossPhaseHooks] SSRF blocked: ${t.reason}`),!0)}checkConditions(e,t){return!e||e.length===0?!0:e.every(n=>this.evaluateCondition(n,t))}evaluateCondition(e,t){try{let n=e.split(/\s*(>|<|>=|<=|==|!=)\s*/);if(n.length!==3)return!1;let[i,r,s]=n,o=this.getValueFromPath(t,i),c=isNaN(Number(s))?s:Number(s),l=typeof o=="number"?o:Number(o),u=typeof c=="number"?c:Number(c);switch(r){case">":return l>u;case"<":return l<u;case">=":return l>=u;case"<=":return l<=u;case"==":return o==c;case"!=":return o!=c;default:return!1}}catch{return!1}}getValueFromPath(e,t){return t.split(".").reduce((n,i)=>{if(n&&typeof n=="object"&&i in n)return n[i]},e)}extractFromContext(e,t){let n={};for(let[i,r]of Object.entries(e))n[i]=this.getValueFromPath(t,r);return n}parseMaxAge(e){let t=e.match(/^(\d+)(d|h|m|s)$/);if(!t)return 0;let[,n,i]=t,r=parseInt(n,10);switch(i){case"d":return r*24*60*60*1e3;case"h":return r*60*60*1e3;case"m":return r*60*1e3;case"s":return r*1e3;default:return 0}}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t)}off(e,t){this.listeners.get(e)?.delete(t)}emit(e,t){this.listeners.get(e)?.forEach(n=>n(t))}async runCleanup(){if(!this.config?.cleanup.enabled)return;console.log("[CrossPhaseHooks] Running cleanup...");let e=await this.memory.cleanupExpired();console.log(`[CrossPhaseHooks] Cleanup complete: ${e.deleted} signals deleted`)}},je=null;function Wt(a){return je||(je=new We(a)),je}function F(a,e){let t=a.get(e);return t?.status!=="cancelled"?{ignored:!1,settledNow:!1}:t.cancellationResultPending?(a.set(e,{...t,cancellationResultPending:!1}),{ignored:!0,settledNow:!0}):{ignored:!0,settledNow:!1}}function Vt(a,e){let t=[];for(let s of e){let o=a.router.subscribeToDoamin(s,async c=>{await ci(a,c)});t.push(o)}let n=a.router.subscribeToEventType("TaskCompleted",async s=>{await li(a,s)});t.push(n);let i=a.router.subscribeToEventType("TaskFailed",async s=>{await ui(a,s)});t.push(i);let r=a.router.subscribeToEventType("AgentStatusChanged",async s=>{await di(a,s)});return t.push(r),t}async function ci(a,e){a.domainLastActivity.set(e.source,new Date),await a.processQueue()}async function li(a,e){let{taskId:t,result:n}=e.payload,i=F(a.tasks,t);if(i.ignored){i.settledNow&&(a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1),await a.processQueue());return}let r=a.tasks.get(t);if(r){(r.status==="running"||r.status==="assigned")&&(a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1));let s=r.startedAt?Date.now()-r.startedAt.getTime():0;a.tasks.set(t,{...r,status:"completed",completedAt:new Date,result:n}),a.tasksCompleted++,a.taskDurations.push(s),a.auditLogger.logComplete(t,r.assignedAgents[0]);try{let o=Wt(),c=r.assignedAgents[0];c&&await o.onAgentComplete(c,{taskId:t,taskType:r.task.type,domain:r.assignedDomain,result:n,duration:s})}catch(o){console.warn("[QueenCoordinator] Cross-phase hook error:",o)}try{await I.afterTaskExecution({taskId:t,taskType:r.task.type,agentId:r.assignedAgents[0]||"unknown",domain:r.assignedDomain||"test-generation",priority:r.task.priority},!0,0,0)}catch(o){console.warn("[QueenCoordinator] Governance tracking error:",o)}if(a.domainBreakerRegistry&&r.assignedDomain&&a.domainBreakerRegistry.getBreaker(r.assignedDomain).recordSuccess(),a.traceCollector){let o=a.taskTraceContexts.get(t);o&&(a.traceCollector.completeSpan(o.spanId),a.taskTraceContexts.delete(t))}if(a.taskCompletedHook)try{let o=typeof n=="object"&&n!==null?n:null;if(o===null)console.error(`[QueenCoordinator] Pattern training skipped for task ${t}: result is not an object (got ${typeof n})`);else{let c=gi(o,t);if(c){let l={taskId:t,agentId:r.assignedAgents[0]||"unknown",domain:r.assignedDomain||"test-generation",type:r.task.type,status:"completed",output:o,metrics:c,duration:s,timestamp:Date.now()};a.taskCompletedHook.onTaskCompleted(l).catch(u=>{console.warn("[QueenCoordinator] Pattern training error:",u)})}}}catch(o){console.warn("[QueenCoordinator] Pattern training setup error:",o)}}await a.processQueue()}async function ui(a,e){let{taskId:t,error:n,callerError:i}=e.payload,r=F(a.tasks,t);if(r.ignored){r.settledNow&&(a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1),await a.processQueue());return}let s=a.tasks.get(t);if(s){if((s.status==="running"||s.status==="assigned")&&(a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1)),a.domainBreakerRegistry&&s.assignedDomain&&!i&&a.domainBreakerRegistry.getBreaker(s.assignedDomain).recordFailure(new Error(n||"Task failed")),a.traceCollector){let o=a.taskTraceContexts.get(t);o&&(a.traceCollector.failSpan(o.spanId,n||"Task failed"),a.taskTraceContexts.delete(t))}if(!i&&s.retryCount<a.config.taskRetryLimit){a.auditLogger.logFail(t,s.assignedAgents[0],n);let o={...s,status:"queued",retryCount:s.retryCount+1,error:n};a.tasks.set(t,o),a.enqueueTask(s.task)}else{a.tasks.set(t,{...s,status:"failed",completedAt:new Date,error:n}),a.tasksFailed++,a.auditLogger.logFail(t,s.assignedAgents[0],n);try{await I.afterTaskExecution({taskId:t,taskType:s.task.type,agentId:s.assignedAgents[0]||"unknown",domain:s.assignedDomain||"test-generation",priority:s.task.priority},!1,0,0)}catch(o){console.warn("[QueenCoordinator] Governance tracking error:",o)}if(!i&&a.hypothesisManager&&(s.task.priority==="p0"||s.task.priority==="p1"))try{let o=s.assignedDomain||"test-generation",c=a.hypothesisManager.createInvestigation(t,o,`Root cause analysis for ${s.task.type} failure: ${n}`);a.hypothesisManager.addHypothesis(c.id,`Infrastructure failure in domain '${o}' caused task ${t} to fail`,"log-analysis",`${o}-lead`),a.hypothesisManager.addHypothesis(c.id,`Logic/configuration error in task payload caused ${s.task.type} to fail: ${n}`,"code-analysis",s.assignedAgents[0]||"unknown"),console.log(`[QueenCoordinator] Competing hypotheses investigation created: ${c.id}`)}catch(o){console.warn("[QueenCoordinator] Hypothesis creation error:",o)}}}await a.processQueue()}async function di(a,e){let{agentId:t,status:n,domain:i}=e.payload;a.domainLastActivity.set(i,new Date),(n==="completed"||n==="failed")&&await a.processQueue()}function gi(a,e){if("metrics"in a&&typeof a.metrics=="object"&&a.metrics!==null){let t=a.metrics;return{testsPassed:typeof t.testsPassed=="number"?t.testsPassed:void 0,testsFailed:typeof t.testsFailed=="number"?t.testsFailed:void 0,coverageChange:typeof t.coverageChange=="number"?t.coverageChange:void 0,securityIssues:typeof t.securityIssues=="number"?t.securityIssues:void 0,performanceMs:typeof t.performanceMs=="number"?t.performanceMs:void 0,linesChanged:typeof t.linesChanged=="number"?t.linesChanged:void 0}}return"testsPassed"in a||"testsFailed"in a?{testsPassed:typeof a.testsPassed=="number"?a.testsPassed:void 0,testsFailed:typeof a.testsFailed=="number"?a.testsFailed:void 0,coverageChange:typeof a.coverageChange=="number"?a.coverageChange:void 0,securityIssues:typeof a.securityIssues=="number"?a.securityIssues:void 0,performanceMs:typeof a.performanceMs=="number"?a.performanceMs:void 0,linesChanged:typeof a.linesChanged=="number"?a.linesChanged:void 0}:(console.error(`[QueenCoordinator] Pattern training skipped for task ${e}: result object has no recognizable metrics shape (keys: ${Object.keys(a).join(", ")})`),null)}function Kt(a,e,t){let n=a.listAgents({domain:e}),i=n.filter(c=>c.status==="running").length,r=n.filter(c=>c.status==="idle").length,s=n.filter(c=>c.status==="failed").length,o;return s>0&&s>=n.length/2?o="unhealthy":s>0?o="degraded":i>0?o="healthy":o="idle",{status:o,agents:{total:n.length,active:i,idle:r,failed:s},lastActivity:t,errors:[]}}var mi=mt();function Yt(a,e,t){let n=a.get(t.priority);n&&gt(n,t,mi);for(let i of t.targetDomains){let r=e.get(i);r&&r.push(t)}}function me(a,e,t){let n=a.get(t.priority);if(n){let i=n.findIndex(r=>r.id===t.id);i!==-1&&n.splice(i,1)}for(let i of t.targetDomains){let r=e.get(i);if(r){let s=r.findIndex(o=>o.id===t.id);s!==-1&&r.splice(s,1)}}}function Ve(a,e){let t=0;for(let n of["p0","p1","p2","p3"]){let i=a.get(n);if(i){if(n===e.priority){t+=i.findIndex(r=>r.id===e.id);break}t+=i.length}}return t}async function q(a){if(!(a.runningTaskCounter>=a.config.maxConcurrentTasks))for(let e of["p0","p1","p2","p3"]){let t=a.taskQueue.get(e);if(!t||t.length===0)continue;let n=t.shift();if(n){me(a.taskQueue,a.domainQueues,n),a.runningTaskCounter++;try{await Ke(a,n)}catch(i){throw a.runningTaskCounter--,i}if(a.runningTaskCounter>=a.config.maxConcurrentTasks)return}}}function Zt(a,e){let t=Array.from(a.values());return e&&(e.status&&(t=t.filter(n=>n.status===e.status)),e.domain&&(t=t.filter(n=>n.assignedDomain===e.domain)),e.priority&&(t=t.filter(n=>n.task.priority===e.priority)),e.type&&(t=t.filter(n=>n.task.type===e.type)),e.fromDate&&(t=t.filter(n=>n.task.createdAt>=e.fromDate)),e.toDate&&(t=t.filter(n=>n.task.createdAt<=e.toDate))),t}async function Ke(a,e){let t=e.targetDomains.length>0?e.targetDomains:P[e.type]||[];if(t.length===0)return y(new Error(`No domains configured for task type: ${e.type}`));let n,i=1/0;for(let r of t){let s=a.getDomainLoad(r);a.getDomainHealth(r)?.status!=="unhealthy"&&s<i&&(i=s,n=r)}return n?Ye(a,e,n):y(new Error("No healthy domain available for task"))}async function Ye(a,e,t){let n;if(a.tinyDancerRouter){let l={p0:"critical",p1:"high",p2:"normal",p3:"low"},u={description:`${e.type}: ${JSON.stringify(e.payload).slice(0,200)}`,type:e.type,domain:t,priority:l[e.priority]};n=await a.tinyDancerRouter.route(u),a.config.enableMetrics&&console.log(`[Queen] TinyDancer routing: ${e.type} \u2192 tier=${n.tier}, model=${n.model}, cost=$${n.estimatedCost.toFixed(4)}`)}if(a.domainBreakerRegistry&&!a.domainBreakerRegistry.canExecuteInDomain(t))return y(new Error(`Domain '${t}' circuit breaker is open \u2014 too many recent failures`));if(a.domainTeamManager)try{if(!a.domainTeamManager.getDomainTeam(t)){let u=`${t}-lead`;a.domainTeamManager.createDomainTeam(t,u)}}catch(l){console.warn(`[Queen] Domain team setup for '${t}' failed (continuing):`,l)}let i=n?.tier||"task-worker",r=["task-execution",e.type,...n?[`model:${n.model}`]:[],...n?.triggerMultiModel?["advisor:triggerMultiModel"]:[]],s=await a.requestAgentSpawn(t,i,r);if(a.tasks.get(e.id)?.status==="cancelled")return s.success&&await a.agentCoordinator.stop(s.value),a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1),T(e.id);let o=[];s.success&&o.push(s.value);let c={taskId:e.id,task:e,status:"running",assignedDomain:t,assignedAgents:o,startedAt:new Date,retryCount:0};a.tasks.set(e.id,c),a.domainLastActivity.set(t,new Date);for(let l of o)a.auditLogger.logAssign(e.id,l,t);if(await a.publishEvent("TaskAssigned",{taskId:e.id,domain:t,agentIds:o}),a.domainPlugins){let l=a.domainPlugins.get(t);if(l?.executeTask&&l.canHandleTask?.(e.type)){let u={taskId:e.id,taskType:e.type,payload:e.payload,priority:e.priority,timeout:e.timeout,correlationId:e.correlationId},d=await l.executeTask(u,g=>pi(a,g));if(!d.success){let g=F(a.tasks,e.id);return g.ignored?(g.settledNow&&(a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1),await q(a)),T(e.id)):(a.tasks.set(e.id,{...c,status:"failed",error:d.error.message,completedAt:new Date}),a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1),a.tasksFailed++,a.auditLogger.logFail(e.id,o[0],d.error.message),y(d.error))}return T(e.id)}if(l)try{await l.handleEvent({id:v(),type:"TaskAssigned",timestamp:new Date,source:"queen-coordinator",correlationId:e.correlationId,payload:{task:e}}),console.warn(`[Queen] Domain ${t} has no executeTask handler, using event fallback`)}catch(u){console.warn(`[Queen] Failed to invoke domain ${t} event handler:`,u)}}return T(e.id)}async function pi(a,e){let t=a.tasks.get(e.taskId);if(!t){console.warn(`[Queen] Received completion for unknown task: ${e.taskId}`);return}let n=F(a.tasks,e.taskId);if(n.ignored){n.settledNow&&(a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1),await q(a));return}let i={...t,status:e.success?"completed":"failed",completedAt:new Date,result:e.data,error:e.error};if(a.tasks.set(e.taskId,i),e.success?(a.tasksCompleted++,a.taskDurations.push(e.duration),a.auditLogger.logComplete(e.taskId,t.assignedAgents[0])):(a.tasksFailed++,a.auditLogger.logFail(e.taskId,t.assignedAgents[0],e.error||"Unknown error")),a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1),a.coExecutionRepo&&t.assignedAgents.length>=2)try{a.coExecutionRepo.recordSwarmCoExecution(t.assignedAgents,t.assignedDomain||"unknown",e.success,t.task.type)}catch{}for(let r of t.assignedAgents)await a.agentCoordinator.stop(r);await a.publishEvent(e.success?"TaskCompleted":"TaskFailed",{taskId:e.taskId,domain:t.assignedDomain,result:e.data,error:e.error,duration:e.duration}),await q(a)}function Xt(a,e){return(P[e.type]||[]).includes(a)}k();async function Jt(a){let e=0,t=a.getIdleDomains(),n=a.getBusyDomains();if(t.length===0||n.length===0)return 0;n.sort((i,r)=>a.getDomainLoad(r)-a.getDomainLoad(i));for(let i of n){if(t.length===0)break;let r=a.domainQueues.get(i)||[],s=Math.min(r.length,a.config.workStealing.stealBatchSize);for(let o=0;o<s&&t.length>0;o++){let c=r.find(l=>Xt(t[0],l));if(c){let l=t.shift();a.removeFromQueues(c),a.auditLogger.logSteal(c.id,i,l),await a.assignTaskToDomain(c,l),e++,a.tasksStolen++,await a.publishEvent("TaskStolen",{taskId:c.id,fromDomain:i,toDomain:l})}}}return e}function Ze(a,e){let t=0,n=10,i=setInterval(async()=>{try{await e(),t=0}catch(r){t++;let s=Math.min(1e3*Math.pow(2,t),3e4);if(console.warn(`[QueenCoordinator] Work-stealing failed (attempt ${t}), backing off ${s}ms`,h(r)),t>n){console.error(`[QueenCoordinator] Work-stealing exceeded ${n} consecutive failures, stopping interval`),clearInterval(i);return}await new Promise(o=>setTimeout(o,s))}},a.workStealing.checkInterval);return i}function Xe(a){return typeof a.setMinCutBridge=="function"}function en(a,e){for(let[t,n]of a)Xe(n)&&(n.setMinCutBridge(e),console.log(`[QueenCoordinator] MinCut bridge injected into ${t}`))}async function tn(a,e,t){try{let n=await a.get("queen:state");if(n)for(let[i,r]of n.tasks)r.status==="queued"&&(e.set(i,r),t(r.task))}catch(n){console.debug("[QueenCoordinator] State loading failed:",n instanceof Error?n.message:n)}}async function nn(a,e){let t=Array.from(e.entries()).filter(([,n])=>n.status==="queued");await a.set("queen:state",{tasks:t},{namespace:"queen-coordinator",persist:!0})}function rn(a){return setInterval(async()=>{let e=a.getMetrics();if(await a.publishEvent("MetricsCollected",{metrics:e}),await a.memory.set(`queen:metrics:${Date.now()}`,e,{ttl:86400,namespace:"queen-coordinator"}),a.dynamicScaler)try{let t=a.getAverageTaskDuration(),n={queueDepth:a.getQueuedTaskCount(),activeAgents:a.getActiveAgentCount(),idleAgents:a.getIdleAgentCount(),avgTaskDurationMs:t,errorRate:a.getTasksReceived()>0?a.getTasksFailed()/a.getTasksReceived():0,throughput:e.uptime>0?a.getTasksCompleted()/(e.uptime/1e3):0,timestamp:Date.now()};a.dynamicScaler.recordMetrics(n);let i=a.dynamicScaler.evaluate();i&&i.action!=="maintain"&&(console.log(`[QueenCoordinator] Dynamic scaler: ${i.action} to ${i.targetAgents} agents \u2014 ${i.reason}`),a.dynamicScaler.execute(i).catch(r=>{console.warn("[QueenCoordinator] Dynamic scaling execution error:",r)}))}catch(t){console.warn("[QueenCoordinator] Dynamic scaler metrics error:",t)}},a.config.metricsInterval)}function Je(a,e,t=36e5){let n=Date.now(),i=0;for(let[s,o]of a)if(o.status==="completed"||o.status==="failed"||o.status==="cancelled"){let c=o.completedAt?.getTime()||o.startedAt?.getTime()||0;c>0&&n-c>t&&(a.delete(s),e.delete(s),i++)}let r=1e4;if(e.size>r){let s=e.size-r,o=e.keys();for(let c=0;c<s;c++){let l=o.next().value;l!==void 0&&e.delete(l)}console.log(`[QueenCoordinator] Evicted ${s} oldest trace contexts (max: ${r})`)}return i>0&&console.log(`[QueenCoordinator] Cleaned up ${i} old tasks (retention: ${t}ms)`),i}function sn(a,e){return a&&a.size>0?Array.from(a.keys()):[...e]}var m=it.create("QueenCoordinator");Gt(C);var et=class{constructor(e,t,n,i,r,s,o,c={}){this.eventBus=e;this.agentCoordinator=t;this.memory=n;this.router=i;this.protocolExecutor=r;this.workflowExecutor=s;this.domainPlugins=o;this.config={...zt,...c},this.auditLogger=ye({enableConsoleLog:this.config.enableMetrics,maxEntries:1e3,logPrefix:"[QUEEN]"}),["p0","p1","p2","p3"].forEach(l=>{this.taskQueue.set(l,[])}),this.config.enableRouting!==!1&&(this.tinyDancerRouter=new V(this.config.routing)),C.forEach(l=>{this.domainQueues.set(l,[]),this.domainLastActivity.set(l,new Date)})}eventBus;agentCoordinator;memory;router;protocolExecutor;workflowExecutor;domainPlugins;config;tasks=new Map;taskQueue=new Map;domainQueues=new Map;domainLastActivity=new Map;initialized=!1;workStealingTimer=null;metricsTimer=null;cleanupTimer=null;startTime=new Date;eventSubscriptionIds=[];runningTaskCounter=0;tasksReceived=0;tasksCompleted=0;tasksFailed=0;tasksStolen=0;taskDurations=new st(1e3);protocolsExecuted=0;workflowsExecuted=0;auditLogger;minCutBridge=null;tinyDancerRouter=null;domainBreakerRegistry=null;domainTeamManager=null;agentTeamsAdapter=null;tierSelector=null;taskCompletedHook=null;traceCollector=null;taskTraceContexts=new Map;hypothesisManager=null;federationMailbox=null;dynamicScaler=null;coExecutionRepo=null;dependencyGraph=null;availableMcpServers=[];async initialize(){if(!this.initialized){this.startTime=new Date,await this.router.initialize(),this.subscribeToEvents(),this.config.workStealing.enabled&&(this.workStealingTimer=Ze(this.config,()=>this.triggerWorkStealing().then(()=>{}))),this.config.enableMetrics&&(this.metricsTimer=rn(this.createMetricsContext())),this.cleanupTimer=setInterval(()=>{Je(this.tasks,this.taskTraceContexts,36e5)},3e5),this.cleanupTimer.unref(),await tn(this.memory,this.tasks,e=>this.enqueueTaskInternal(e)),this.minCutBridge=yt(this.eventBus,this.agentCoordinator,{autoUpdateFromEvents:!0,persistData:!0,includeInQueenHealth:!0,sharedGraph:lt()}),await this.minCutBridge.initialize(),this.domainPlugins&&en(this.domainPlugins,this.minCutBridge);try{await I.initialize(),m.info("Governance adapter initialized")}catch(e){m.warn("Governance initialization failed (continuing)",{error:e})}this.initializeSubsystems();try{let{join:e}=await import("path"),t=e(process.cwd(),".claude","agents","v3");this.dependencyGraph=Pt(t),this.availableMcpServers=pt(process.cwd());let{getUnifiedMemory:n}=await import("./unified-memory-GHAYAXWZ.js"),i=n();await i.initialize(),this.coExecutionRepo=Rt(),this.coExecutionRepo.initialize(i.getDatabase()),this.dependencyGraph.warnings.length>0&&m.warn(`Dependency graph: ${this.dependencyGraph.warnings.length} warning(s)`,{warnings:this.dependencyGraph.warnings.slice(0,5)}),m.info("Dependency intelligence initialized",{agents:this.dependencyGraph.nodes.size,mcpServers:this.availableMcpServers.length})}catch(e){m.warn("Dependency intelligence initialization failed (continuing)",{error:e})}await this.publishEvent("QueenInitialized",{timestamp:new Date,config:this.config,domains:C}),this.initialized=!0}}async dispose(){this.workStealingTimer&&(clearInterval(this.workStealingTimer),this.workStealingTimer=null),this.metricsTimer&&(clearInterval(this.metricsTimer),this.metricsTimer=null),this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null),this.minCutBridge&&(await this.minCutBridge.dispose(),this.minCutBridge=null),this.domainTeamManager&&(this.domainTeamManager.dispose(),this.domainTeamManager=null),this.agentTeamsAdapter&&(this.agentTeamsAdapter.shutdown(),this.agentTeamsAdapter=null),this.domainBreakerRegistry=null,this.tierSelector=null,this.traceCollector&&(this.traceCollector.dispose(),this.traceCollector=null),this.hypothesisManager&&(this.hypothesisManager.dispose(),this.hypothesisManager=null),this.federationMailbox&&(this.federationMailbox.dispose(),this.federationMailbox=null),this.dynamicScaler&&(this.dynamicScaler.dispose(),this.dynamicScaler=null),await nn(this.memory,this.tasks);for(let[e,t]of this.tasks)(t.status==="queued"||t.status==="running")&&await this.cancelTask(e);await this.publishEvent("QueenShutdown",{timestamp:new Date,metrics:this.getMetrics()});for(let e of this.eventSubscriptionIds)this.router.unsubscribe(e);this.eventSubscriptionIds=[],await this.router.dispose(),this.initialized=!1}async submitTask(e){if(!this.initialized)return y(new Error("Queen Coordinator not initialized"));let t=`task_${v()}`,n={...e,id:t,createdAt:new Date,timeout:e.timeout||this.config.defaultTaskTimeout},i={taskId:n.id,taskType:n.type,agentId:n.requester||`queen-task:${n.id}`,domain:n.targetDomains[0]||"test-generation",priority:n.priority,payload:n.payload};try{let r=await I.beforeTaskExecution(i);if(!r.allowed)return this.auditLogger.logFail(t,"governance",r.reason||"Governance check failed"),await this.publishEvent("TaskRejected",{taskId:t,reason:r.reason,escalate:r.escalate}),y(new Error(`Task blocked by governance: ${r.reason}`))}catch(r){m.warn("Governance check error (continuing)",{error:r})}this.runningTaskCounter++;try{if(this.runningTaskCounter>this.config.maxConcurrentTasks)return this.runningTaskCounter--,this.queueTask(n);this.auditLogger.logSubmit(t,{type:n.type,priority:n.priority}),this.selectFleetTier(n),this.startTaskTrace(n,t);let r=await Ke(this.createTaskContext(),n);return r.success?(this.tasksReceived++,await this.publishEvent("TaskSubmitted",{taskId:t,task:n}),T(t)):(this.runningTaskCounter--,r)}catch(r){throw this.runningTaskCounter--,r}}async cancelTask(e){let t=this.tasks.get(e);if(!t)return y(new Error(`Task not found: ${e}`));if(t.status==="cancelled")return T(void 0);if(t.status==="completed"||t.status==="failed")return y(new Error(`Task already finished: ${e}`));let n=t.status==="running"||t.status==="assigned";this.tasks.set(e,{...t,status:"cancelled",completedAt:new Date,cancellationResultPending:n}),me(this.taskQueue,this.domainQueues,t.task);for(let i of t.assignedAgents)await this.agentCoordinator.stop(i);return this.auditLogger.logCancel(e),await this.publishEvent("TaskCancelled",{taskId:e}),T(void 0)}getTaskStatus(e){return this.tasks.get(e)}listTasks(e){return Zt(this.tasks,e)}getDomainHealth(e){if(this.domainPlugins){let t=this.domainPlugins.get(e);if(t)return t.getHealth()}return Kt(this.agentCoordinator,e,this.domainLastActivity.get(e))}getDomainLoad(e){let t=this.domainQueues.get(e)||[],n=Array.from(this.tasks.values()).filter(i=>i.assignedDomain===e&&i.status==="running");return t.length+n.length}getIdleDomains(){let e=Date.now(),t=this.config.workStealing.idleThreshold;return C.filter(n=>{let i=this.domainLastActivity.get(n);return this.getDomainLoad(n)===0&&i&&e-i.getTime()>t})}getBusyDomains(){return C.filter(e=>this.getDomainLoad(e)>this.config.workStealing.loadThreshold)}getSpawnPlan(e){return this.dependencyGraph?Ft(e,this.dependencyGraph):{phases:[e],warnings:[],unsatisfiedHardDeps:[]}}getDependencyGraph(){return this.dependencyGraph}enableWorkStealing(){this.workStealingTimer||(this.workStealingTimer=Ze(this.config,()=>this.triggerWorkStealing().then(()=>{})))}disableWorkStealing(){this.workStealingTimer&&(clearInterval(this.workStealingTimer),this.workStealingTimer=null)}async triggerWorkStealing(){return Jt(this.createWorkStealingContext())}listAllAgents(){return this.agentCoordinator.listAgents()}getAgentsByDomain(e){return this.agentCoordinator.listAgents({domain:e})}async requestAgentSpawn(e,t,n){if(!this.agentCoordinator.canSpawn())return y(new Error("Maximum concurrent agents reached (15)"));if(this.dependencyGraph&&this.availableMcpServers.length>0)try{for(let[,r]of this.dependencyGraph.nodes){let s=r.dependencies.mcpServers;if(!s||s.length===0)continue;let o=s.filter(c=>c.required&&!this.availableMcpServers.includes(c.name));if(o.length>0){m.warn(`Pre-spawn MCP advisory: ${r.agentName} needs ${o.map(c=>c.name).join(", ")}`,{agent:r.agentName,domain:e,missing:o.map(c=>c.name)});break}}}catch{}let i=await this.agentCoordinator.spawn({name:`${e}-${t}-${Date.now()}`,domain:e,type:t,capabilities:n});if(i.success){if(this.domainLastActivity.set(e,new Date),this.domainTeamManager&&typeof this.domainTeamManager.getDomainTeam=="function")try{if(this.domainTeamManager.getDomainTeam(e))this.domainTeamManager.addTeammate(e,i.value)||m.warn(`Agent ${i.value} could not join ${e} team (full)`);else try{this.domainTeamManager.createDomainTeam(e,i.value)}catch{this.domainTeamManager.addTeammate(e,i.value)||m.warn(`Agent ${i.value} could not join ${e} team (full or max teams reached)`)}}catch(r){m.warn(`Auto-team-wiring failed for ${i.value}`,{error:r})}await this.publishEvent("AgentSpawned",{agentId:i.value,domain:e,type:t,capabilities:n})}return i}getHealth(){let e=new Map,t=[],n=0,i=0,r=sn(this.domainPlugins,C);for(let u of r){let d=this.getDomainHealth(u);d&&(e.set(u,d),d.status==="unhealthy"?(n++,t.push({domain:u,severity:"high",message:`Domain ${u} is unhealthy`,timestamp:new Date})):d.status==="degraded"&&(i++,t.push({domain:u,severity:"medium",message:`Domain ${u} is degraded`,timestamp:new Date})))}let s=this.agentCoordinator.listAgents(),o=s.filter(u=>u.status==="running").length,c="healthy";n>0?c="unhealthy":i>r.length/2&&(c="degraded");let l={status:c,domainHealth:e,totalAgents:s.length,activeAgents:o,pendingTasks:this.getQueuedTaskCount(),runningTasks:this.getRunningTaskCount(),workStealingActive:this.workStealingTimer!==null,lastHealthCheck:new Date,issues:t};return this.minCutBridge?this.minCutBridge.extendQueenHealth(l):l}getMetrics(){let e=new Map;for(let o of C){let c=this.getDomainLoad(o);e.set(o,c)}let t=this.agentCoordinator.listAgents(),n=t.filter(o=>o.status==="running").length,i=t.length>0?n/t.length:0,r=this.taskDurations.average(),s={tasksReceived:this.tasksReceived,tasksCompleted:this.tasksCompleted,tasksFailed:this.tasksFailed,tasksStolen:this.tasksStolen,averageTaskDuration:r,domainUtilization:e,agentUtilization:i,protocolsExecuted:this.protocolsExecuted,workflowsExecuted:this.workflowsExecuted,uptime:Date.now()-this.startTime.getTime()};return this.minCutBridge?this.minCutBridge.extendQueenMetrics(s):s}getMinCutBridge(){return this.minCutBridge}injectMinCutBridgeIntoDomain(e){if(!this.minCutBridge)return m.warn("Cannot inject MinCut bridge: bridge not initialized"),!1;if(!this.domainPlugins)return m.warn("Cannot inject MinCut bridge: no domain plugins registered"),!1;let t=this.domainPlugins.get(e);return t?Xe(t)?(t.setMinCutBridge(this.minCutBridge),m.info(`MinCut bridge injected into ${e} (late binding)`),!0):(m.warn(`Domain ${e} does not support MinCut integration`),!1):(m.warn(`Cannot inject MinCut bridge: domain ${e} not found`),!1)}getTinyDancerRouter(){return this.tinyDancerRouter}getDomainBreakerRegistry(){return this.domainBreakerRegistry}getDomainTeamManager(){return this.domainTeamManager}getAgentTeamsAdapter(){return this.agentTeamsAdapter}getTierSelector(){return this.tierSelector}getTraceCollector(){return this.traceCollector}getHypothesisManager(){return this.hypothesisManager}getFederationMailbox(){return this.federationMailbox}getDynamicScaler(){return this.dynamicScaler}connectReasoningBank(e){let t=new ce(e);this.taskCompletedHook=new oe({},t),m.info("ReasoningBank connected for pattern training")}async executeProtocol(e,t){if(!this.protocolExecutor)return y(new Error("Protocol executor not configured"));let n=await this.protocolExecutor.execute(e,t);return n.success?(this.protocolsExecuted++,await this.publishEvent("ProtocolExecuted",{protocolId:e,executionId:n.value.executionId}),T(n.value.executionId)):n}async executeWorkflow(e,t){if(!this.workflowExecutor)return y(new Error("Workflow executor not configured"));let n=await this.workflowExecutor.execute(e,t);return n.success?(this.workflowsExecuted++,await this.publishEvent("WorkflowExecuted",{workflowId:e,executionId:n.value.executionId}),T(n.value.executionId)):n}cleanupCompletedTasks(e=36e5){return Je(this.tasks,this.taskTraceContexts,e)}subscribeToEvents(){this.eventSubscriptionIds=Vt(this.createEventHandlerContext(),C)}enqueueTaskInternal(e){Yt(this.taskQueue,this.domainQueues,e)}async publishEvent(e,t){await this.eventBus.publish({id:v(),type:`Queen${e}`,timestamp:new Date,source:"queen-coordinator",payload:t})}queueTask(e){this.enqueueTaskInternal(e);let t={taskId:e.id,task:e,status:"queued",assignedAgents:[],retryCount:0};return this.tasks.set(e.id,t),this.tasksReceived++,this.auditLogger.logSubmit(e.id,{type:e.type,priority:e.priority}),this.auditLogger.logQueue(e.id,Ve(this.taskQueue,e)),this.publishEvent("TaskQueued",{taskId:e.id,task:e,position:Ve(this.taskQueue,e)}),T(e.id)}selectFleetTier(e){if(this.tierSelector)try{let t={trigger:e.payload?.trigger??"manual",changedFiles:e.payload?.changedFiles,affectedDomains:e.targetDomains,severity:e.priority==="p0"?"critical":e.priority==="p1"?"high":void 0,isHotfix:e.payload?.isHotfix},n=this.tierSelector.selectTier(t);return m.info(`Fleet tier: ${n.selectedTier} (${n.reason})`),n.selectedTier}catch(t){m.warn("Tier selection error (continuing)",{error:t});return}}startTaskTrace(e,t){if(this.traceCollector)try{let{context:n}=this.traceCollector.startTrace({operationName:e.type,agentId:e.requester||"queen",domain:e.targetDomains[0]||"test-generation",tags:{taskId:t,priority:e.priority}});if(this.taskTraceContexts.size>=1e4){let r=this.taskTraceContexts.keys().next().value;r!==void 0&&this.taskTraceContexts.delete(r)}this.taskTraceContexts.set(t,n)}catch(n){m.warn("Trace start error (continuing)",{error:n})}}getRunningTaskCount(){return Array.from(this.tasks.values()).filter(e=>e.status==="running"||e.status==="assigned").length}getQueuedTaskCount(){return Array.from(this.tasks.values()).filter(e=>e.status==="queued").length}initializeSubsystems(){if(this.config.enableCircuitBreakers!==!1)try{this.domainBreakerRegistry=Lt(),m.info("Domain circuit breaker registry initialized")}catch(e){m.warn("Circuit breaker initialization failed (continuing)",{error:e})}if(this.config.enableDomainTeams!==!1)try{this.agentTeamsAdapter=we(),this.agentTeamsAdapter.initialize(),this.domainTeamManager=Me(this.agentTeamsAdapter),m.info("Domain team manager initialized")}catch(e){m.warn("Domain team manager initialization failed (continuing)",{error:e})}if(this.config.enableFleetTiers!==!1)try{this.tierSelector=Pe(),m.info("Fleet tier selector initialized")}catch(e){m.warn("Tier selector initialization failed (continuing)",{error:e})}try{this.traceCollector=Ee(),m.info("Trace collector initialized")}catch(e){m.warn("Trace collector initialization failed (continuing)",{error:e})}try{this.hypothesisManager=Oe(),this.federationMailbox=Le(),this.dynamicScaler=Be(),m.info("Phase 4 modules initialized (hypotheses, federation, scaling)")}catch(e){m.warn("Phase 4 initialization failed (continuing)",{error:e})}}createEventHandlerContext(){let e=this;return{config:e.config,tasks:e.tasks,domainLastActivity:e.domainLastActivity,auditLogger:e.auditLogger,router:e.router,agentCoordinator:e.agentCoordinator,get runningTaskCounter(){return e.runningTaskCounter},set runningTaskCounter(t){e.runningTaskCounter=t},get tasksCompleted(){return e.tasksCompleted},set tasksCompleted(t){e.tasksCompleted=t},get tasksFailed(){return e.tasksFailed},set tasksFailed(t){e.tasksFailed=t},taskDurations:e.taskDurations,get domainBreakerRegistry(){return e.domainBreakerRegistry},get traceCollector(){return e.traceCollector},taskTraceContexts:e.taskTraceContexts,get taskCompletedHook(){return e.taskCompletedHook},get hypothesisManager(){return e.hypothesisManager},processQueue:()=>q(e.createTaskContext()),enqueueTask:t=>e.enqueueTaskInternal(t)}}createTaskContext(){let e=this;return{config:e.config,tasks:e.tasks,taskQueue:e.taskQueue,domainQueues:e.domainQueues,domainLastActivity:e.domainLastActivity,auditLogger:e.auditLogger,agentCoordinator:e.agentCoordinator,domainPlugins:e.domainPlugins,get runningTaskCounter(){return e.runningTaskCounter},set runningTaskCounter(t){e.runningTaskCounter=t},get tasksReceived(){return e.tasksReceived},set tasksReceived(t){e.tasksReceived=t},get tasksCompleted(){return e.tasksCompleted},set tasksCompleted(t){e.tasksCompleted=t},get tasksFailed(){return e.tasksFailed},set tasksFailed(t){e.tasksFailed=t},taskDurations:e.taskDurations,get tinyDancerRouter(){return e.tinyDancerRouter},get domainBreakerRegistry(){return e.domainBreakerRegistry},get domainTeamManager(){return e.domainTeamManager},get tierSelector(){return e.tierSelector},get traceCollector(){return e.traceCollector},taskTraceContexts:e.taskTraceContexts,get coExecutionRepo(){return e.coExecutionRepo},requestAgentSpawn:(t,n,i)=>e.requestAgentSpawn(t,n,i),publishEvent:(t,n)=>e.publishEvent(t,n),getDomainLoad:t=>e.getDomainLoad(t),getDomainHealth:t=>e.getDomainHealth(t)}}createWorkStealingContext(){let e=this;return{config:e.config,domainQueues:e.domainQueues,auditLogger:e.auditLogger,get tasksStolen(){return e.tasksStolen},set tasksStolen(t){e.tasksStolen=t},getIdleDomains:()=>e.getIdleDomains(),getBusyDomains:()=>e.getBusyDomains(),getDomainLoad:t=>e.getDomainLoad(t),removeFromQueues:t=>me(e.taskQueue,e.domainQueues,t),assignTaskToDomain:(t,n)=>Ye(e.createTaskContext(),t,n).then(()=>{}),publishEvent:(t,n)=>e.publishEvent(t,n)}}createMetricsContext(){let e=this;return{config:e.config,memory:e.memory,get dynamicScaler(){return e.dynamicScaler},getMetrics:()=>e.getMetrics(),publishEvent:(t,n)=>e.publishEvent(t,n),getQueuedTaskCount:()=>e.getQueuedTaskCount(),getActiveAgentCount:()=>e.agentCoordinator.listAgents().filter(t=>t.status==="running").length,getIdleAgentCount:()=>e.agentCoordinator.listAgents().filter(t=>t.status==="idle").length,getAverageTaskDuration:()=>e.taskDurations.average(),getTasksReceived:()=>e.tasksReceived,getTasksFailed:()=>e.tasksFailed,getTasksCompleted:()=>e.tasksCompleted}}};function yo(a,e,t,n,i,r){return new et(a.eventBus,a.coordinator,a.memory,e,t,n,i,r)}export{ni as a,P as b,et as c,yo as d};
180
+ `}}return t}getRecommendations(e){switch(e.loopType){case"strategic":return[...e.recommendations.forRiskAssessor,...e.recommendations.forQualityCriteria];case"tactical":return e.recommendations.forProductFactorsAssessor;case"operational":return[...e.recommendations.forTestArchitect,...e.recommendations.antiPatterns];case"quality-criteria":return e.recommendations.forRequirementsValidator;default:return[]}}filterManagedHooks(e){if(process.env.AQE_HOOKS_MANAGED_ONLY!=="true")return e;let t=e.filter(([n])=>n.startsWith("managed:"));return t.length<e.length&&console.log(`[CrossPhaseHooks] AQE_HOOKS_MANAGED_ONLY: filtered ${e.length-t.length} non-managed hooks`),t}async isBlockedUrl(e){if(!e.includes("://"))return!1;let t=await fe(e);return t.safe?!1:(console.warn(`[CrossPhaseHooks] SSRF blocked: ${t.reason}`),!0)}checkConditions(e,t){return!e||e.length===0?!0:e.every(n=>this.evaluateCondition(n,t))}evaluateCondition(e,t){try{let n=e.split(/\s*(>|<|>=|<=|==|!=)\s*/);if(n.length!==3)return!1;let[i,r,s]=n,o=this.getValueFromPath(t,i),c=isNaN(Number(s))?s:Number(s),l=typeof o=="number"?o:Number(o),u=typeof c=="number"?c:Number(c);switch(r){case">":return l>u;case"<":return l<u;case">=":return l>=u;case"<=":return l<=u;case"==":return o==c;case"!=":return o!=c;default:return!1}}catch{return!1}}getValueFromPath(e,t){return t.split(".").reduce((n,i)=>{if(n&&typeof n=="object"&&i in n)return n[i]},e)}extractFromContext(e,t){let n={};for(let[i,r]of Object.entries(e))n[i]=this.getValueFromPath(t,r);return n}parseMaxAge(e){let t=e.match(/^(\d+)(d|h|m|s)$/);if(!t)return 0;let[,n,i]=t,r=parseInt(n,10);switch(i){case"d":return r*24*60*60*1e3;case"h":return r*60*60*1e3;case"m":return r*60*1e3;case"s":return r*1e3;default:return 0}}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t)}off(e,t){this.listeners.get(e)?.delete(t)}emit(e,t){this.listeners.get(e)?.forEach(n=>n(t))}async runCleanup(){if(!this.config?.cleanup.enabled)return;console.log("[CrossPhaseHooks] Running cleanup...");let e=await this.memory.cleanupExpired();console.log(`[CrossPhaseHooks] Cleanup complete: ${e.deleted} signals deleted`)}},je=null;function Wt(a){return je||(je=new We(a)),je}function F(a,e){let t=a.get(e);return t?.status!=="cancelled"?{ignored:!1,settledNow:!1}:t.cancellationResultPending?(a.set(e,{...t,cancellationResultPending:!1}),{ignored:!0,settledNow:!0}):{ignored:!0,settledNow:!1}}function Vt(a,e){let t=[];for(let s of e){let o=a.router.subscribeToDoamin(s,async c=>{await ci(a,c)});t.push(o)}let n=a.router.subscribeToEventType("TaskCompleted",async s=>{await li(a,s)});t.push(n);let i=a.router.subscribeToEventType("TaskFailed",async s=>{await ui(a,s)});t.push(i);let r=a.router.subscribeToEventType("AgentStatusChanged",async s=>{await di(a,s)});return t.push(r),t}async function ci(a,e){a.domainLastActivity.set(e.source,new Date),await a.processQueue()}async function li(a,e){let{taskId:t,result:n}=e.payload,i=F(a.tasks,t);if(i.ignored){i.settledNow&&(a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1),await a.processQueue());return}let r=a.tasks.get(t);if(r){(r.status==="running"||r.status==="assigned")&&(a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1));let s=r.startedAt?Date.now()-r.startedAt.getTime():0;a.tasks.set(t,{...r,status:"completed",completedAt:new Date,result:n}),a.tasksCompleted++,a.taskDurations.push(s),a.auditLogger.logComplete(t,r.assignedAgents[0]);try{let o=Wt(),c=r.assignedAgents[0];c&&await o.onAgentComplete(c,{taskId:t,taskType:r.task.type,domain:r.assignedDomain,result:n,duration:s})}catch(o){console.warn("[QueenCoordinator] Cross-phase hook error:",o)}try{await I.afterTaskExecution({taskId:t,taskType:r.task.type,agentId:r.assignedAgents[0]||"unknown",domain:r.assignedDomain||"test-generation",priority:r.task.priority},!0,0,0)}catch(o){console.warn("[QueenCoordinator] Governance tracking error:",o)}if(a.domainBreakerRegistry&&r.assignedDomain&&a.domainBreakerRegistry.getBreaker(r.assignedDomain).recordSuccess(),a.traceCollector){let o=a.taskTraceContexts.get(t);o&&(a.traceCollector.completeSpan(o.spanId),a.taskTraceContexts.delete(t))}if(a.taskCompletedHook)try{let o=typeof n=="object"&&n!==null?n:null;if(o===null)console.error(`[QueenCoordinator] Pattern training skipped for task ${t}: result is not an object (got ${typeof n})`);else{let c=gi(o,t);if(c){let l={taskId:t,agentId:r.assignedAgents[0]||"unknown",domain:r.assignedDomain||"test-generation",type:r.task.type,status:"completed",output:o,metrics:c,duration:s,timestamp:Date.now()};a.taskCompletedHook.onTaskCompleted(l).catch(u=>{console.warn("[QueenCoordinator] Pattern training error:",u)})}}}catch(o){console.warn("[QueenCoordinator] Pattern training setup error:",o)}}await a.processQueue()}async function ui(a,e){let{taskId:t,error:n,callerError:i}=e.payload,r=F(a.tasks,t);if(r.ignored){r.settledNow&&(a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1),await a.processQueue());return}let s=a.tasks.get(t);if(s){if((s.status==="running"||s.status==="assigned")&&(a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1)),a.domainBreakerRegistry&&s.assignedDomain&&!i&&a.domainBreakerRegistry.getBreaker(s.assignedDomain).recordFailure(new Error(n||"Task failed")),a.traceCollector){let o=a.taskTraceContexts.get(t);o&&(a.traceCollector.failSpan(o.spanId,n||"Task failed"),a.taskTraceContexts.delete(t))}if(!i&&s.retryCount<a.config.taskRetryLimit){a.auditLogger.logFail(t,s.assignedAgents[0],n);let o={...s,status:"queued",retryCount:s.retryCount+1,error:n};a.tasks.set(t,o),a.enqueueTask(s.task)}else{a.tasks.set(t,{...s,status:"failed",completedAt:new Date,error:n}),a.tasksFailed++,a.auditLogger.logFail(t,s.assignedAgents[0],n);try{await I.afterTaskExecution({taskId:t,taskType:s.task.type,agentId:s.assignedAgents[0]||"unknown",domain:s.assignedDomain||"test-generation",priority:s.task.priority},!1,0,0)}catch(o){console.warn("[QueenCoordinator] Governance tracking error:",o)}if(!i&&a.hypothesisManager&&(s.task.priority==="p0"||s.task.priority==="p1"))try{let o=s.assignedDomain||"test-generation",c=a.hypothesisManager.createInvestigation(t,o,`Root cause analysis for ${s.task.type} failure: ${n}`);a.hypothesisManager.addHypothesis(c.id,`Infrastructure failure in domain '${o}' caused task ${t} to fail`,"log-analysis",`${o}-lead`),a.hypothesisManager.addHypothesis(c.id,`Logic/configuration error in task payload caused ${s.task.type} to fail: ${n}`,"code-analysis",s.assignedAgents[0]||"unknown"),console.log(`[QueenCoordinator] Competing hypotheses investigation created: ${c.id}`)}catch(o){console.warn("[QueenCoordinator] Hypothesis creation error:",o)}}}await a.processQueue()}async function di(a,e){let{agentId:t,status:n,domain:i}=e.payload;a.domainLastActivity.set(i,new Date),(n==="completed"||n==="failed")&&await a.processQueue()}function gi(a,e){if("metrics"in a&&typeof a.metrics=="object"&&a.metrics!==null){let t=a.metrics;return{testsPassed:typeof t.testsPassed=="number"?t.testsPassed:void 0,testsFailed:typeof t.testsFailed=="number"?t.testsFailed:void 0,coverageChange:typeof t.coverageChange=="number"?t.coverageChange:void 0,securityIssues:typeof t.securityIssues=="number"?t.securityIssues:void 0,performanceMs:typeof t.performanceMs=="number"?t.performanceMs:void 0,linesChanged:typeof t.linesChanged=="number"?t.linesChanged:void 0}}return"testsPassed"in a||"testsFailed"in a?{testsPassed:typeof a.testsPassed=="number"?a.testsPassed:void 0,testsFailed:typeof a.testsFailed=="number"?a.testsFailed:void 0,coverageChange:typeof a.coverageChange=="number"?a.coverageChange:void 0,securityIssues:typeof a.securityIssues=="number"?a.securityIssues:void 0,performanceMs:typeof a.performanceMs=="number"?a.performanceMs:void 0,linesChanged:typeof a.linesChanged=="number"?a.linesChanged:void 0}:(console.error(`[QueenCoordinator] Pattern training skipped for task ${e}: result object has no recognizable metrics shape (keys: ${Object.keys(a).join(", ")})`),null)}function Kt(a,e,t){let n=a.listAgents({domain:e}),i=n.filter(c=>c.status==="running").length,r=n.filter(c=>c.status==="idle").length,s=n.filter(c=>c.status==="failed").length,o;return s>0&&s>=n.length/2?o="unhealthy":s>0?o="degraded":i>0?o="healthy":o="idle",{status:o,agents:{total:n.length,active:i,idle:r,failed:s},lastActivity:t,errors:[]}}var mi=mt();function Yt(a,e,t){let n=a.get(t.priority);n&&gt(n,t,mi);for(let i of t.targetDomains){let r=e.get(i);r&&r.push(t)}}function me(a,e,t){let n=a.get(t.priority);if(n){let i=n.findIndex(r=>r.id===t.id);i!==-1&&n.splice(i,1)}for(let i of t.targetDomains){let r=e.get(i);if(r){let s=r.findIndex(o=>o.id===t.id);s!==-1&&r.splice(s,1)}}}function Ve(a,e){let t=0;for(let n of["p0","p1","p2","p3"]){let i=a.get(n);if(i){if(n===e.priority){t+=i.findIndex(r=>r.id===e.id);break}t+=i.length}}return t}async function q(a){if(!(a.runningTaskCounter>=a.config.maxConcurrentTasks))for(let e of["p0","p1","p2","p3"]){let t=a.taskQueue.get(e);if(!t||t.length===0)continue;let n=t.shift();if(n){me(a.taskQueue,a.domainQueues,n),a.runningTaskCounter++;try{await Ke(a,n)}catch(i){throw a.runningTaskCounter--,i}if(a.runningTaskCounter>=a.config.maxConcurrentTasks)return}}}function Zt(a,e){let t=Array.from(a.values());return e&&(e.status&&(t=t.filter(n=>n.status===e.status)),e.domain&&(t=t.filter(n=>n.assignedDomain===e.domain)),e.priority&&(t=t.filter(n=>n.task.priority===e.priority)),e.type&&(t=t.filter(n=>n.task.type===e.type)),e.fromDate&&(t=t.filter(n=>n.task.createdAt>=e.fromDate)),e.toDate&&(t=t.filter(n=>n.task.createdAt<=e.toDate))),t}async function Ke(a,e){let t=e.targetDomains.length>0?e.targetDomains:P[e.type]||[];if(t.length===0)return y(new Error(`No domains configured for task type: ${e.type}`));let n,i=1/0;for(let r of t){let s=a.getDomainLoad(r);a.getDomainHealth(r)?.status!=="unhealthy"&&s<i&&(i=s,n=r)}return n?Ye(a,e,n):y(new Error("No healthy domain available for task"))}async function Ye(a,e,t){let n;if(a.tinyDancerRouter){let l={p0:"critical",p1:"high",p2:"normal",p3:"low"},u={description:`${e.type}: ${JSON.stringify(e.payload).slice(0,200)}`,type:e.type,domain:t,priority:l[e.priority]};n=await a.tinyDancerRouter.route(u),a.config.enableMetrics&&console.log(`[Queen] TinyDancer routing: ${e.type} \u2192 tier=${n.tier}, model=${n.model}, cost=$${n.estimatedCost.toFixed(4)}`)}if(a.domainBreakerRegistry&&!a.domainBreakerRegistry.canExecuteInDomain(t))return y(new Error(`Domain '${t}' circuit breaker is open \u2014 too many recent failures`));if(a.domainTeamManager)try{if(!a.domainTeamManager.getDomainTeam(t)){let u=`${t}-lead`;a.domainTeamManager.createDomainTeam(t,u)}}catch(l){console.warn(`[Queen] Domain team setup for '${t}' failed (continuing):`,l)}let i=n?.tier||"task-worker",r=["task-execution",e.type,...n?[`model:${n.model}`]:[],...n?.triggerMultiModel?["advisor:triggerMultiModel"]:[]],s=await a.requestAgentSpawn(t,i,r);if(a.tasks.get(e.id)?.status==="cancelled")return s.success&&await a.agentCoordinator.stop(s.value),a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1),T(e.id);let o=[];s.success&&o.push(s.value);let c={taskId:e.id,task:e,status:"running",assignedDomain:t,assignedAgents:o,startedAt:new Date,retryCount:0};a.tasks.set(e.id,c),a.domainLastActivity.set(t,new Date);for(let l of o)a.auditLogger.logAssign(e.id,l,t);if(await a.publishEvent("TaskAssigned",{taskId:e.id,domain:t,agentIds:o}),a.domainPlugins){let l=a.domainPlugins.get(t);if(l?.executeTask&&l.canHandleTask?.(e.type)){let u={taskId:e.id,taskType:e.type,payload:e.payload,priority:e.priority,timeout:e.timeout,correlationId:e.correlationId},d=await l.executeTask(u,g=>pi(a,g));if(!d.success){let g=F(a.tasks,e.id);return g.ignored?(g.settledNow&&(a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1),await q(a)),T(e.id)):(a.tasks.set(e.id,{...c,status:"failed",error:d.error.message,completedAt:new Date}),a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1),a.tasksFailed++,a.auditLogger.logFail(e.id,o[0],d.error.message),y(d.error))}return T(e.id)}if(l)try{await l.handleEvent({id:v(),type:"TaskAssigned",timestamp:new Date,source:"queen-coordinator",correlationId:e.correlationId,payload:{task:e}}),console.warn(`[Queen] Domain ${t} has no executeTask handler, using event fallback`)}catch(u){console.warn(`[Queen] Failed to invoke domain ${t} event handler:`,u)}}return T(e.id)}async function pi(a,e){let t=a.tasks.get(e.taskId);if(!t){console.warn(`[Queen] Received completion for unknown task: ${e.taskId}`);return}let n=F(a.tasks,e.taskId);if(n.ignored){n.settledNow&&(a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1),await q(a));return}let i={...t,status:e.success?"completed":"failed",completedAt:new Date,result:e.data,error:e.error};if(a.tasks.set(e.taskId,i),e.success?(a.tasksCompleted++,a.taskDurations.push(e.duration),a.auditLogger.logComplete(e.taskId,t.assignedAgents[0])):(a.tasksFailed++,a.auditLogger.logFail(e.taskId,t.assignedAgents[0],e.error||"Unknown error")),a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1),a.coExecutionRepo&&t.assignedAgents.length>=2)try{a.coExecutionRepo.recordSwarmCoExecution(t.assignedAgents,t.assignedDomain||"unknown",e.success,t.task.type)}catch{}for(let r of t.assignedAgents)await a.agentCoordinator.stop(r);await a.publishEvent(e.success?"TaskCompleted":"TaskFailed",{taskId:e.taskId,domain:t.assignedDomain,result:e.data,error:e.error,duration:e.duration}),await q(a)}function Xt(a,e){return(P[e.type]||[]).includes(a)}k();async function Jt(a){let e=0,t=a.getIdleDomains(),n=a.getBusyDomains();if(t.length===0||n.length===0)return 0;n.sort((i,r)=>a.getDomainLoad(r)-a.getDomainLoad(i));for(let i of n){if(t.length===0)break;let r=a.domainQueues.get(i)||[],s=Math.min(r.length,a.config.workStealing.stealBatchSize);for(let o=0;o<s&&t.length>0;o++){let c=r.find(l=>Xt(t[0],l));if(c){let l=t.shift();a.removeFromQueues(c),a.auditLogger.logSteal(c.id,i,l),await a.assignTaskToDomain(c,l),e++,a.tasksStolen++,await a.publishEvent("TaskStolen",{taskId:c.id,fromDomain:i,toDomain:l})}}}return e}function Ze(a,e){let t=0,n=10,i=setInterval(async()=>{try{await e(),t=0}catch(r){t++;let s=Math.min(1e3*Math.pow(2,t),3e4);if(console.warn(`[QueenCoordinator] Work-stealing failed (attempt ${t}), backing off ${s}ms`,h(r)),t>n){console.error(`[QueenCoordinator] Work-stealing exceeded ${n} consecutive failures, stopping interval`),clearInterval(i);return}await new Promise(o=>setTimeout(o,s))}},a.workStealing.checkInterval);return i}function Xe(a){return typeof a.setMinCutBridge=="function"}function en(a,e){for(let[t,n]of a)Xe(n)&&(n.setMinCutBridge(e),console.log(`[QueenCoordinator] MinCut bridge injected into ${t}`))}async function tn(a,e,t){try{let n=await a.get("queen:state");if(n)for(let[i,r]of n.tasks)r.status==="queued"&&(e.set(i,r),t(r.task))}catch(n){console.debug("[QueenCoordinator] State loading failed:",n instanceof Error?n.message:n)}}async function nn(a,e){let t=Array.from(e.entries()).filter(([,n])=>n.status==="queued");await a.set("queen:state",{tasks:t},{namespace:"queen-coordinator",persist:!0})}function rn(a){return setInterval(async()=>{let e=a.getMetrics();if(await a.publishEvent("MetricsCollected",{metrics:e}),await a.memory.set(`queen:metrics:${Date.now()}`,e,{ttl:86400,namespace:"queen-coordinator"}),a.dynamicScaler)try{let t=a.getAverageTaskDuration(),n={queueDepth:a.getQueuedTaskCount(),activeAgents:a.getActiveAgentCount(),idleAgents:a.getIdleAgentCount(),avgTaskDurationMs:t,errorRate:a.getTasksReceived()>0?a.getTasksFailed()/a.getTasksReceived():0,throughput:e.uptime>0?a.getTasksCompleted()/(e.uptime/1e3):0,timestamp:Date.now()};a.dynamicScaler.recordMetrics(n);let i=a.dynamicScaler.evaluate();i&&i.action!=="maintain"&&(console.log(`[QueenCoordinator] Dynamic scaler: ${i.action} to ${i.targetAgents} agents \u2014 ${i.reason}`),a.dynamicScaler.execute(i).catch(r=>{console.warn("[QueenCoordinator] Dynamic scaling execution error:",r)}))}catch(t){console.warn("[QueenCoordinator] Dynamic scaler metrics error:",t)}},a.config.metricsInterval)}function Je(a,e,t=36e5){let n=Date.now(),i=0;for(let[s,o]of a)if(o.status==="completed"||o.status==="failed"||o.status==="cancelled"){let c=o.completedAt?.getTime()||o.startedAt?.getTime()||0;c>0&&n-c>t&&(a.delete(s),e.delete(s),i++)}let r=1e4;if(e.size>r){let s=e.size-r,o=e.keys();for(let c=0;c<s;c++){let l=o.next().value;l!==void 0&&e.delete(l)}console.log(`[QueenCoordinator] Evicted ${s} oldest trace contexts (max: ${r})`)}return i>0&&console.log(`[QueenCoordinator] Cleaned up ${i} old tasks (retention: ${t}ms)`),i}function sn(a,e){return a&&a.size>0?Array.from(a.keys()):[...e]}var m=it.create("QueenCoordinator");Gt(C);var et=class{constructor(e,t,n,i,r,s,o,c={}){this.eventBus=e;this.agentCoordinator=t;this.memory=n;this.router=i;this.protocolExecutor=r;this.workflowExecutor=s;this.domainPlugins=o;this.config={...zt,...c},this.auditLogger=ye({enableConsoleLog:this.config.enableMetrics,maxEntries:1e3,logPrefix:"[QUEEN]"}),["p0","p1","p2","p3"].forEach(l=>{this.taskQueue.set(l,[])}),this.config.enableRouting!==!1&&(this.tinyDancerRouter=new V(this.config.routing)),C.forEach(l=>{this.domainQueues.set(l,[]),this.domainLastActivity.set(l,new Date)})}eventBus;agentCoordinator;memory;router;protocolExecutor;workflowExecutor;domainPlugins;config;tasks=new Map;taskQueue=new Map;domainQueues=new Map;domainLastActivity=new Map;initialized=!1;workStealingTimer=null;metricsTimer=null;cleanupTimer=null;startTime=new Date;eventSubscriptionIds=[];runningTaskCounter=0;tasksReceived=0;tasksCompleted=0;tasksFailed=0;tasksStolen=0;taskDurations=new st(1e3);protocolsExecuted=0;workflowsExecuted=0;auditLogger;minCutBridge=null;tinyDancerRouter=null;domainBreakerRegistry=null;domainTeamManager=null;agentTeamsAdapter=null;tierSelector=null;taskCompletedHook=null;traceCollector=null;taskTraceContexts=new Map;hypothesisManager=null;federationMailbox=null;dynamicScaler=null;coExecutionRepo=null;dependencyGraph=null;availableMcpServers=[];async initialize(){if(!this.initialized){this.startTime=new Date,await this.router.initialize(),this.subscribeToEvents(),this.config.workStealing.enabled&&(this.workStealingTimer=Ze(this.config,()=>this.triggerWorkStealing().then(()=>{}))),this.config.enableMetrics&&(this.metricsTimer=rn(this.createMetricsContext())),this.cleanupTimer=setInterval(()=>{Je(this.tasks,this.taskTraceContexts,36e5)},3e5),this.cleanupTimer.unref(),await tn(this.memory,this.tasks,e=>this.enqueueTaskInternal(e)),this.minCutBridge=yt(this.eventBus,this.agentCoordinator,{autoUpdateFromEvents:!0,persistData:!0,includeInQueenHealth:!0,sharedGraph:lt()}),await this.minCutBridge.initialize(),this.domainPlugins&&en(this.domainPlugins,this.minCutBridge);try{await I.initialize(),m.info("Governance adapter initialized")}catch(e){m.warn("Governance initialization failed (continuing)",{error:e})}this.initializeSubsystems();try{let{join:e}=await import("path"),t=e(process.cwd(),".claude","agents","v3");this.dependencyGraph=Pt(t),this.availableMcpServers=pt(process.cwd());let{getUnifiedMemory:n}=await import("./unified-memory-WVELSL6T.js"),i=n();await i.initialize(),this.coExecutionRepo=Rt(),this.coExecutionRepo.initialize(i.getDatabase()),this.dependencyGraph.warnings.length>0&&m.warn(`Dependency graph: ${this.dependencyGraph.warnings.length} warning(s)`,{warnings:this.dependencyGraph.warnings.slice(0,5)}),m.info("Dependency intelligence initialized",{agents:this.dependencyGraph.nodes.size,mcpServers:this.availableMcpServers.length})}catch(e){m.warn("Dependency intelligence initialization failed (continuing)",{error:e})}await this.publishEvent("QueenInitialized",{timestamp:new Date,config:this.config,domains:C}),this.initialized=!0}}async dispose(){this.workStealingTimer&&(clearInterval(this.workStealingTimer),this.workStealingTimer=null),this.metricsTimer&&(clearInterval(this.metricsTimer),this.metricsTimer=null),this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null),this.minCutBridge&&(await this.minCutBridge.dispose(),this.minCutBridge=null),this.domainTeamManager&&(this.domainTeamManager.dispose(),this.domainTeamManager=null),this.agentTeamsAdapter&&(this.agentTeamsAdapter.shutdown(),this.agentTeamsAdapter=null),this.domainBreakerRegistry=null,this.tierSelector=null,this.traceCollector&&(this.traceCollector.dispose(),this.traceCollector=null),this.hypothesisManager&&(this.hypothesisManager.dispose(),this.hypothesisManager=null),this.federationMailbox&&(this.federationMailbox.dispose(),this.federationMailbox=null),this.dynamicScaler&&(this.dynamicScaler.dispose(),this.dynamicScaler=null),await nn(this.memory,this.tasks);for(let[e,t]of this.tasks)(t.status==="queued"||t.status==="running")&&await this.cancelTask(e);await this.publishEvent("QueenShutdown",{timestamp:new Date,metrics:this.getMetrics()});for(let e of this.eventSubscriptionIds)this.router.unsubscribe(e);this.eventSubscriptionIds=[],await this.router.dispose(),this.initialized=!1}async submitTask(e){if(!this.initialized)return y(new Error("Queen Coordinator not initialized"));let t=`task_${v()}`,n={...e,id:t,createdAt:new Date,timeout:e.timeout||this.config.defaultTaskTimeout},i={taskId:n.id,taskType:n.type,agentId:n.requester||`queen-task:${n.id}`,domain:n.targetDomains[0]||"test-generation",priority:n.priority,payload:n.payload};try{let r=await I.beforeTaskExecution(i);if(!r.allowed)return this.auditLogger.logFail(t,"governance",r.reason||"Governance check failed"),await this.publishEvent("TaskRejected",{taskId:t,reason:r.reason,escalate:r.escalate}),y(new Error(`Task blocked by governance: ${r.reason}`))}catch(r){m.warn("Governance check error (continuing)",{error:r})}this.runningTaskCounter++;try{if(this.runningTaskCounter>this.config.maxConcurrentTasks)return this.runningTaskCounter--,this.queueTask(n);this.auditLogger.logSubmit(t,{type:n.type,priority:n.priority}),this.selectFleetTier(n),this.startTaskTrace(n,t);let r=await Ke(this.createTaskContext(),n);return r.success?(this.tasksReceived++,await this.publishEvent("TaskSubmitted",{taskId:t,task:n}),T(t)):(this.runningTaskCounter--,r)}catch(r){throw this.runningTaskCounter--,r}}async cancelTask(e){let t=this.tasks.get(e);if(!t)return y(new Error(`Task not found: ${e}`));if(t.status==="cancelled")return T(void 0);if(t.status==="completed"||t.status==="failed")return y(new Error(`Task already finished: ${e}`));let n=t.status==="running"||t.status==="assigned";this.tasks.set(e,{...t,status:"cancelled",completedAt:new Date,cancellationResultPending:n}),me(this.taskQueue,this.domainQueues,t.task);for(let i of t.assignedAgents)await this.agentCoordinator.stop(i);return this.auditLogger.logCancel(e),await this.publishEvent("TaskCancelled",{taskId:e}),T(void 0)}getTaskStatus(e){return this.tasks.get(e)}listTasks(e){return Zt(this.tasks,e)}getDomainHealth(e){if(this.domainPlugins){let t=this.domainPlugins.get(e);if(t)return t.getHealth()}return Kt(this.agentCoordinator,e,this.domainLastActivity.get(e))}getDomainLoad(e){let t=this.domainQueues.get(e)||[],n=Array.from(this.tasks.values()).filter(i=>i.assignedDomain===e&&i.status==="running");return t.length+n.length}getIdleDomains(){let e=Date.now(),t=this.config.workStealing.idleThreshold;return C.filter(n=>{let i=this.domainLastActivity.get(n);return this.getDomainLoad(n)===0&&i&&e-i.getTime()>t})}getBusyDomains(){return C.filter(e=>this.getDomainLoad(e)>this.config.workStealing.loadThreshold)}getSpawnPlan(e){return this.dependencyGraph?Ft(e,this.dependencyGraph):{phases:[e],warnings:[],unsatisfiedHardDeps:[]}}getDependencyGraph(){return this.dependencyGraph}enableWorkStealing(){this.workStealingTimer||(this.workStealingTimer=Ze(this.config,()=>this.triggerWorkStealing().then(()=>{})))}disableWorkStealing(){this.workStealingTimer&&(clearInterval(this.workStealingTimer),this.workStealingTimer=null)}async triggerWorkStealing(){return Jt(this.createWorkStealingContext())}listAllAgents(){return this.agentCoordinator.listAgents()}getAgentsByDomain(e){return this.agentCoordinator.listAgents({domain:e})}async requestAgentSpawn(e,t,n){if(!this.agentCoordinator.canSpawn())return y(new Error("Maximum concurrent agents reached (15)"));if(this.dependencyGraph&&this.availableMcpServers.length>0)try{for(let[,r]of this.dependencyGraph.nodes){let s=r.dependencies.mcpServers;if(!s||s.length===0)continue;let o=s.filter(c=>c.required&&!this.availableMcpServers.includes(c.name));if(o.length>0){m.warn(`Pre-spawn MCP advisory: ${r.agentName} needs ${o.map(c=>c.name).join(", ")}`,{agent:r.agentName,domain:e,missing:o.map(c=>c.name)});break}}}catch{}let i=await this.agentCoordinator.spawn({name:`${e}-${t}-${Date.now()}`,domain:e,type:t,capabilities:n});if(i.success){if(this.domainLastActivity.set(e,new Date),this.domainTeamManager&&typeof this.domainTeamManager.getDomainTeam=="function")try{if(this.domainTeamManager.getDomainTeam(e))this.domainTeamManager.addTeammate(e,i.value)||m.warn(`Agent ${i.value} could not join ${e} team (full)`);else try{this.domainTeamManager.createDomainTeam(e,i.value)}catch{this.domainTeamManager.addTeammate(e,i.value)||m.warn(`Agent ${i.value} could not join ${e} team (full or max teams reached)`)}}catch(r){m.warn(`Auto-team-wiring failed for ${i.value}`,{error:r})}await this.publishEvent("AgentSpawned",{agentId:i.value,domain:e,type:t,capabilities:n})}return i}getHealth(){let e=new Map,t=[],n=0,i=0,r=sn(this.domainPlugins,C);for(let u of r){let d=this.getDomainHealth(u);d&&(e.set(u,d),d.status==="unhealthy"?(n++,t.push({domain:u,severity:"high",message:`Domain ${u} is unhealthy`,timestamp:new Date})):d.status==="degraded"&&(i++,t.push({domain:u,severity:"medium",message:`Domain ${u} is degraded`,timestamp:new Date})))}let s=this.agentCoordinator.listAgents(),o=s.filter(u=>u.status==="running").length,c="healthy";n>0?c="unhealthy":i>r.length/2&&(c="degraded");let l={status:c,domainHealth:e,totalAgents:s.length,activeAgents:o,pendingTasks:this.getQueuedTaskCount(),runningTasks:this.getRunningTaskCount(),workStealingActive:this.workStealingTimer!==null,lastHealthCheck:new Date,issues:t};return this.minCutBridge?this.minCutBridge.extendQueenHealth(l):l}getMetrics(){let e=new Map;for(let o of C){let c=this.getDomainLoad(o);e.set(o,c)}let t=this.agentCoordinator.listAgents(),n=t.filter(o=>o.status==="running").length,i=t.length>0?n/t.length:0,r=this.taskDurations.average(),s={tasksReceived:this.tasksReceived,tasksCompleted:this.tasksCompleted,tasksFailed:this.tasksFailed,tasksStolen:this.tasksStolen,averageTaskDuration:r,domainUtilization:e,agentUtilization:i,protocolsExecuted:this.protocolsExecuted,workflowsExecuted:this.workflowsExecuted,uptime:Date.now()-this.startTime.getTime()};return this.minCutBridge?this.minCutBridge.extendQueenMetrics(s):s}getMinCutBridge(){return this.minCutBridge}injectMinCutBridgeIntoDomain(e){if(!this.minCutBridge)return m.warn("Cannot inject MinCut bridge: bridge not initialized"),!1;if(!this.domainPlugins)return m.warn("Cannot inject MinCut bridge: no domain plugins registered"),!1;let t=this.domainPlugins.get(e);return t?Xe(t)?(t.setMinCutBridge(this.minCutBridge),m.info(`MinCut bridge injected into ${e} (late binding)`),!0):(m.warn(`Domain ${e} does not support MinCut integration`),!1):(m.warn(`Cannot inject MinCut bridge: domain ${e} not found`),!1)}getTinyDancerRouter(){return this.tinyDancerRouter}getDomainBreakerRegistry(){return this.domainBreakerRegistry}getDomainTeamManager(){return this.domainTeamManager}getAgentTeamsAdapter(){return this.agentTeamsAdapter}getTierSelector(){return this.tierSelector}getTraceCollector(){return this.traceCollector}getHypothesisManager(){return this.hypothesisManager}getFederationMailbox(){return this.federationMailbox}getDynamicScaler(){return this.dynamicScaler}connectReasoningBank(e){let t=new ce(e);this.taskCompletedHook=new oe({},t),m.info("ReasoningBank connected for pattern training")}async executeProtocol(e,t){if(!this.protocolExecutor)return y(new Error("Protocol executor not configured"));let n=await this.protocolExecutor.execute(e,t);return n.success?(this.protocolsExecuted++,await this.publishEvent("ProtocolExecuted",{protocolId:e,executionId:n.value.executionId}),T(n.value.executionId)):n}async executeWorkflow(e,t){if(!this.workflowExecutor)return y(new Error("Workflow executor not configured"));let n=await this.workflowExecutor.execute(e,t);return n.success?(this.workflowsExecuted++,await this.publishEvent("WorkflowExecuted",{workflowId:e,executionId:n.value.executionId}),T(n.value.executionId)):n}cleanupCompletedTasks(e=36e5){return Je(this.tasks,this.taskTraceContexts,e)}subscribeToEvents(){this.eventSubscriptionIds=Vt(this.createEventHandlerContext(),C)}enqueueTaskInternal(e){Yt(this.taskQueue,this.domainQueues,e)}async publishEvent(e,t){await this.eventBus.publish({id:v(),type:`Queen${e}`,timestamp:new Date,source:"queen-coordinator",payload:t})}queueTask(e){this.enqueueTaskInternal(e);let t={taskId:e.id,task:e,status:"queued",assignedAgents:[],retryCount:0};return this.tasks.set(e.id,t),this.tasksReceived++,this.auditLogger.logSubmit(e.id,{type:e.type,priority:e.priority}),this.auditLogger.logQueue(e.id,Ve(this.taskQueue,e)),this.publishEvent("TaskQueued",{taskId:e.id,task:e,position:Ve(this.taskQueue,e)}),T(e.id)}selectFleetTier(e){if(this.tierSelector)try{let t={trigger:e.payload?.trigger??"manual",changedFiles:e.payload?.changedFiles,affectedDomains:e.targetDomains,severity:e.priority==="p0"?"critical":e.priority==="p1"?"high":void 0,isHotfix:e.payload?.isHotfix},n=this.tierSelector.selectTier(t);return m.info(`Fleet tier: ${n.selectedTier} (${n.reason})`),n.selectedTier}catch(t){m.warn("Tier selection error (continuing)",{error:t});return}}startTaskTrace(e,t){if(this.traceCollector)try{let{context:n}=this.traceCollector.startTrace({operationName:e.type,agentId:e.requester||"queen",domain:e.targetDomains[0]||"test-generation",tags:{taskId:t,priority:e.priority}});if(this.taskTraceContexts.size>=1e4){let r=this.taskTraceContexts.keys().next().value;r!==void 0&&this.taskTraceContexts.delete(r)}this.taskTraceContexts.set(t,n)}catch(n){m.warn("Trace start error (continuing)",{error:n})}}getRunningTaskCount(){return Array.from(this.tasks.values()).filter(e=>e.status==="running"||e.status==="assigned").length}getQueuedTaskCount(){return Array.from(this.tasks.values()).filter(e=>e.status==="queued").length}initializeSubsystems(){if(this.config.enableCircuitBreakers!==!1)try{this.domainBreakerRegistry=Lt(),m.info("Domain circuit breaker registry initialized")}catch(e){m.warn("Circuit breaker initialization failed (continuing)",{error:e})}if(this.config.enableDomainTeams!==!1)try{this.agentTeamsAdapter=we(),this.agentTeamsAdapter.initialize(),this.domainTeamManager=Me(this.agentTeamsAdapter),m.info("Domain team manager initialized")}catch(e){m.warn("Domain team manager initialization failed (continuing)",{error:e})}if(this.config.enableFleetTiers!==!1)try{this.tierSelector=Pe(),m.info("Fleet tier selector initialized")}catch(e){m.warn("Tier selector initialization failed (continuing)",{error:e})}try{this.traceCollector=Ee(),m.info("Trace collector initialized")}catch(e){m.warn("Trace collector initialization failed (continuing)",{error:e})}try{this.hypothesisManager=Oe(),this.federationMailbox=Le(),this.dynamicScaler=Be(),m.info("Phase 4 modules initialized (hypotheses, federation, scaling)")}catch(e){m.warn("Phase 4 initialization failed (continuing)",{error:e})}}createEventHandlerContext(){let e=this;return{config:e.config,tasks:e.tasks,domainLastActivity:e.domainLastActivity,auditLogger:e.auditLogger,router:e.router,agentCoordinator:e.agentCoordinator,get runningTaskCounter(){return e.runningTaskCounter},set runningTaskCounter(t){e.runningTaskCounter=t},get tasksCompleted(){return e.tasksCompleted},set tasksCompleted(t){e.tasksCompleted=t},get tasksFailed(){return e.tasksFailed},set tasksFailed(t){e.tasksFailed=t},taskDurations:e.taskDurations,get domainBreakerRegistry(){return e.domainBreakerRegistry},get traceCollector(){return e.traceCollector},taskTraceContexts:e.taskTraceContexts,get taskCompletedHook(){return e.taskCompletedHook},get hypothesisManager(){return e.hypothesisManager},processQueue:()=>q(e.createTaskContext()),enqueueTask:t=>e.enqueueTaskInternal(t)}}createTaskContext(){let e=this;return{config:e.config,tasks:e.tasks,taskQueue:e.taskQueue,domainQueues:e.domainQueues,domainLastActivity:e.domainLastActivity,auditLogger:e.auditLogger,agentCoordinator:e.agentCoordinator,domainPlugins:e.domainPlugins,get runningTaskCounter(){return e.runningTaskCounter},set runningTaskCounter(t){e.runningTaskCounter=t},get tasksReceived(){return e.tasksReceived},set tasksReceived(t){e.tasksReceived=t},get tasksCompleted(){return e.tasksCompleted},set tasksCompleted(t){e.tasksCompleted=t},get tasksFailed(){return e.tasksFailed},set tasksFailed(t){e.tasksFailed=t},taskDurations:e.taskDurations,get tinyDancerRouter(){return e.tinyDancerRouter},get domainBreakerRegistry(){return e.domainBreakerRegistry},get domainTeamManager(){return e.domainTeamManager},get tierSelector(){return e.tierSelector},get traceCollector(){return e.traceCollector},taskTraceContexts:e.taskTraceContexts,get coExecutionRepo(){return e.coExecutionRepo},requestAgentSpawn:(t,n,i)=>e.requestAgentSpawn(t,n,i),publishEvent:(t,n)=>e.publishEvent(t,n),getDomainLoad:t=>e.getDomainLoad(t),getDomainHealth:t=>e.getDomainHealth(t)}}createWorkStealingContext(){let e=this;return{config:e.config,domainQueues:e.domainQueues,auditLogger:e.auditLogger,get tasksStolen(){return e.tasksStolen},set tasksStolen(t){e.tasksStolen=t},getIdleDomains:()=>e.getIdleDomains(),getBusyDomains:()=>e.getBusyDomains(),getDomainLoad:t=>e.getDomainLoad(t),removeFromQueues:t=>me(e.taskQueue,e.domainQueues,t),assignTaskToDomain:(t,n)=>Ye(e.createTaskContext(),t,n).then(()=>{}),publishEvent:(t,n)=>e.publishEvent(t,n)}}createMetricsContext(){let e=this;return{config:e.config,memory:e.memory,get dynamicScaler(){return e.dynamicScaler},getMetrics:()=>e.getMetrics(),publishEvent:(t,n)=>e.publishEvent(t,n),getQueuedTaskCount:()=>e.getQueuedTaskCount(),getActiveAgentCount:()=>e.agentCoordinator.listAgents().filter(t=>t.status==="running").length,getIdleAgentCount:()=>e.agentCoordinator.listAgents().filter(t=>t.status==="idle").length,getAverageTaskDuration:()=>e.taskDurations.average(),getTasksReceived:()=>e.tasksReceived,getTasksFailed:()=>e.tasksFailed,getTasksCompleted:()=>e.tasksCompleted}}};function yo(a,e,t,n,i,r){return new et(a.eventBus,a.coordinator,a.memory,e,t,n,i,r)}export{ni as a,P as b,et as c,yo as d};
@@ -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.14.8");process.exit(0)}
2
- var e=null,f=null,t=null,u=!1;async function W(){return u&&!t?e:t||(t=(async()=>{try{if(process.env.AQE_RVF_MODE==="sqlite-only"||process.env.AQE_MEMORY_BACKEND==="memory")return null;let{isRvfNativeAvailable:d}=await import("./rvf-native-adapter-E6JNBKMZ.js");if(!d())return null;let{getUnifiedMemory:v,findProjectRoot:p}=await import("./unified-memory-GHAYAXWZ.js"),o=v().getDatabase();if(!o)return null;let{join:m}=await import("node:path"),g=m(process.env.AQE_PROJECT_ROOT??p(),".agentic-qe","brain.rvf"),{RvfDualWriter:R}=await import("./rvf-dual-writer-LTKTDRFS.js"),l=new R(o,{rvfPath:g,mode:"dual-write",dimensions:384});await l.initialize(),e=l;try{let{getRvfMigrationStage:y}=await import("./feature-flags-VESRRQ6V.js"),a=y();if(a>=2){let{RvfMigrationAdapter:A}=await import("./rvf-migration-adapter-IF24EVC5.js"),s=new A({stage:a});s.setSqliteDb(o);let{getSharedRvfAdapter:D}=await import("./shared-rvf-adapter-5FOVSL3T.js"),i=D();if(i){let h={ingest:n=>i.ingest(n),search:(n,M)=>i.search(n,M).map(c=>({id:c.id,score:c.score})),delete:n=>i.delete(n),status:()=>i.status(),close:()=>{}};s.setRvfStore(h)}f=s,console.log(`[RVF] Migration adapter active at stage ${a} (${["sqlite-only","hybrid","dual-sqlite","dual-rvf","rvf-primary"][a]})`)}}catch{}return l}catch(r){return(process.env.DEBUG||process.env.AQE_VERBOSE)&&console.debug("[RVF] Dual-writer init failed, degrading to sqlite-only:",r instanceof Error?r.message:r),null}finally{u=!0,t=null,import("./base-5TQ34GMD.js").then(({registerRvfResetFn:r})=>r(w)).catch(()=>{})}})(),t)}function S(){return e}function b(){return f}function w(){if(e){try{e.close()}catch{}e=null}f=null,t=null,u=!1}export{W as a,S as b,b as c,w as d};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.1");process.exit(0)}
2
+ var e=null,f=null,t=null,u=!1;async function W(){return u&&!t?e:t||(t=(async()=>{try{if(process.env.AQE_RVF_MODE==="sqlite-only"||process.env.AQE_MEMORY_BACKEND==="memory")return null;let{isRvfNativeAvailable:d}=await import("./rvf-native-adapter-HXBY4VYI.js");if(!d())return null;let{getUnifiedMemory:v,findProjectRoot:p}=await import("./unified-memory-WVELSL6T.js"),o=v().getDatabase();if(!o)return null;let{join:m}=await import("node:path"),g=m(process.env.AQE_PROJECT_ROOT??p(),".agentic-qe","brain.rvf"),{RvfDualWriter:R}=await import("./rvf-dual-writer-H3ZXS5MA.js"),l=new R(o,{rvfPath:g,mode:"dual-write",dimensions:384});await l.initialize(),e=l;try{let{getRvfMigrationStage:y}=await import("./feature-flags-G7ONDNTT.js"),a=y();if(a>=2){let{RvfMigrationAdapter:A}=await import("./rvf-migration-adapter-J7MTCOQA.js"),s=new A({stage:a});s.setSqliteDb(o);let{getSharedRvfAdapter:D}=await import("./shared-rvf-adapter-QIHSYHAF.js"),i=D();if(i){let h={ingest:n=>i.ingest(n),search:(n,M)=>i.search(n,M).map(c=>({id:c.id,score:c.score})),delete:n=>i.delete(n),status:()=>i.status(),close:()=>{}};s.setRvfStore(h)}f=s,console.log(`[RVF] Migration adapter active at stage ${a} (${["sqlite-only","hybrid","dual-sqlite","dual-rvf","rvf-primary"][a]})`)}}catch{}return l}catch(r){return(process.env.DEBUG||process.env.AQE_VERBOSE)&&console.debug("[RVF] Dual-writer init failed, degrading to sqlite-only:",r instanceof Error?r.message:r),null}finally{u=!0,t=null,import("./base-5SK64NXB.js").then(({registerRvfResetFn:r})=>r(w)).catch(()=>{})}})(),t)}function S(){return e}function b(){return f}function w(){if(e){try{e.close()}catch{}e=null}f=null,t=null,u=!1}export{W as a,S as b,b as c,w as d};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.8");process.exit(0)}
2
- import{b as t,d as o}from"./chunk-XAESN54Q.js";var L={};o(L,{DotProductAttention:()=>d,FlashAttention:()=>m,HyperbolicAttention:()=>f,LinearAttention:()=>h,MoEAttention:()=>_,MultiHeadAttention:()=>A,RuvectorLayer:()=>a,SonaEngine:()=>g,TensorCompress:()=>c,default:()=>i,differentiableSearch:()=>l,getCompressionLevel:()=>s,hierarchicalForward:()=>p,init:()=>u,pipeline:()=>v});import{createRequire as n}from"module";var r,e,i,a,c,l,p,s,u,m,d,A,f,h,_,g,v,b=t(()=>{r=n(import.meta.url),e=r("@ruvector/gnn"),i=e,{RuvectorLayer:a,TensorCompress:c,differentiableSearch:l,hierarchicalForward:p,getCompressionLevel:s,init:u,FlashAttention:m,DotProductAttention:d,MultiHeadAttention:A,HyperbolicAttention:f,LinearAttention:h,MoEAttention:_,SonaEngine:g,pipeline:v}=e||{}});export{L as a,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.15.1");process.exit(0)}
2
+ import{b as t,d as o}from"./chunk-PNK5KHSI.js";var L={};o(L,{DotProductAttention:()=>d,FlashAttention:()=>m,HyperbolicAttention:()=>f,LinearAttention:()=>h,MoEAttention:()=>_,MultiHeadAttention:()=>A,RuvectorLayer:()=>a,SonaEngine:()=>g,TensorCompress:()=>c,default:()=>i,differentiableSearch:()=>l,getCompressionLevel:()=>s,hierarchicalForward:()=>p,init:()=>u,pipeline:()=>v});import{createRequire as n}from"module";var r,e,i,a,c,l,p,s,u,m,d,A,f,h,_,g,v,b=t(()=>{r=n(import.meta.url),e=r("@ruvector/gnn"),i=e,{RuvectorLayer:a,TensorCompress:c,differentiableSearch:l,hierarchicalForward:p,getCompressionLevel:s,init:u,FlashAttention:m,DotProductAttention:d,MultiHeadAttention:A,HyperbolicAttention:f,LinearAttention:h,MoEAttention:_,SonaEngine:g,pipeline:v}=e||{}});export{L as a,b};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.8");process.exit(0)}
2
- import{a as ae,b as oe}from"./chunk-VW7AXJQS.js";import{S as ie,i as D,p as $}from"./chunk-R6I5I724.js";import{b as g,d as ne,f as W}from"./chunk-XAESN54Q.js";var I,E=g(()=>{"use strict";I={dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"}});function se(){if(z)return A!==null;try{let i=(oe(),W(ae));if(A=i.differentiableSearch,P=i.init,P)try{P()}catch{}return z=!0,!0}catch{return z=!0,!1}}function j(i){let e=0;for(let r=0;r<i.length;r++)e+=i[r]*i[r];return Math.sqrt(e)}function ce(i,e,r,t){let n=r*t;if(n===0)return 0;let a=0,o=Math.min(i.length,e.length);for(let c=0;c<o;c++)a+=i[c]*e[c];return a/n}function q(i,e){let r=0,t=Math.min(i.length,e.length);for(let n=0;n<t;n++){let a=i[n]-e[n];r+=a*a}return Math.sqrt(r)}function le(i,e){if(i.length===e)return i;let r=new Float32Array(e);if(i.length>e){let t=i.length/e;for(let n=0;n<e;n++){let a=Math.floor(n*t),o=Math.floor((n+1)*t),c=0;for(let s=a;s<o;s++)c+=i[s];r[n]=c/(o-a)}}else for(let t=0;t<i.length;t++)r[t]=i[t];return r}var A,P,z,S,B=g(()=>{"use strict";E();A=null,P=null,z=!1;S=class{config;entries=[];idToIndex=new Map;hasRuvector=!1;loaded=!1;constructor(e){this.config={...I,...e}}ensureLoaded(){this.loaded||(this.hasRuvector=se(),this.loaded=!0)}normalizeVector(e){return e.length===this.config.dimensions?e:le(e,this.config.dimensions)}add(e,r,t){this.ensureLoaded();let n=this.normalizeVector(r),a=j(n);if(this.idToIndex.has(e)){let c=this.idToIndex.get(e);this.entries[c]={id:e,vector:n,norm:a,metadata:t};return}let o=this.entries.length;this.entries.push({id:e,vector:n,norm:a,metadata:t}),this.idToIndex.set(e,o)}search(e,r){if(this.ensureLoaded(),this.entries.length===0)return[];let t=this.normalizeVector(e),n=j(t),a=Math.min(r,this.entries.length),o=this.entries.length>0?this.entries[0].vector.length:0,c=t.length===o;if(this.config.metric==="cosine")return this.bruteForcSearch(t,n,a);if(this.hasRuvector&&c&&A)try{let s=this.entries.map(u=>u.vector),l=A(t,s,a,1).indices.map(u=>{let h=this.entries[u],m=-q(t,h.vector);return{id:h.id,score:m,metadata:h.metadata}});return l.sort((u,h)=>h.score-u.score),l}catch{}return this.bruteForcSearch(t,n,a)}bruteForcSearch(e,r,t){let n=[];for(let a of this.entries){let o;this.config.metric==="cosine"?o=ce(e,a.vector,r,a.norm):o=-q(e,a.vector),n.push({id:a.id,score:o,metadata:a.metadata})}return n.sort((a,o)=>o.score-a.score),n.slice(0,t)}remove(e){let r=this.idToIndex.get(e);if(r===void 0)return!1;let t=this.entries.length-1;if(r!==t){let n=this.entries[t];this.entries[r]=n,this.idToIndex.set(n.id,r)}return this.entries.pop(),this.idToIndex.delete(e),!0}size(){return this.entries.length}dimensions(){return this.config.dimensions}recall(){return this.hasRuvector,1}isRuvectorAvailable(){return this.ensureLoaded(),this.hasRuvector}getConfig(){return{...this.config}}clear(){this.entries=[],this.idToIndex.clear()}dispose(){this.clear()}}});import{createRequire as he}from"module";function de(){if(U){if(k)return k;throw new b(O??"Unknown load error")}U=!0;try{let i=ue("hnswlib-node");if(!i.HierarchicalNSW)throw new Error("hnswlib-node module missing HierarchicalNSW export");return k=i,k}catch(i){let e=i instanceof Error?i.message:String(i);throw O=e,new b(e)}}function me(i,e){if(i.length===e)return i;let r=new Float32Array(e);if(i.length>e){let t=i.length/e;for(let n=0;n<e;n++){let a=Math.floor(n*t),o=Math.floor((n+1)*t),c=0;for(let s=a;s<o;s++)c+=i[s];r[n]=c/(o-a)}}else for(let t=0;t<i.length;t++)r[t]=i[t];return r}function K(i){let e=new Array(i.length);for(let r=0;r<i.length;r++)e[r]=i[r];return e}var ue,b,k,U,O,J,w,Q=g(()=>{"use strict";E();ue=he(import.meta.url),b=class extends Error{constructor(e){super(`Native HNSW backend unavailable: ${e}`),this.name="NativeHnswUnavailableError"}},k=null,U=!1,O=null;J=1e4,w=class{config;nativeIndex=null;currentMaxElements=J;liveIds=new Set;metadataStore=new Map;_metrics={totalSearches:0,totalAdds:0,totalRemoves:0,avgSearchLatencyMs:0,maxSearchLatencyMs:0,lastSearchLatencyMs:0,fallbackSearchCount:0,bruteForceSearchCount:0,nativeSearchCount:0,fallbackRate:0,allSearchesBruteForce:!1};constructor(e){this.config={...I,...e},this.nativeIndex=this.createFreshIndex()}createFreshIndex(){let e=de(),r=this.config.metric==="euclidean"?"l2":"cosine";try{let t=new e.HierarchicalNSW(r,this.config.dimensions);return t.initIndex(this.currentMaxElements,this.config.M,this.config.efConstruction,100,!0),t.setEf(this.config.efSearch),t}catch(t){let n=t instanceof Error?t.message:String(t);throw new b(`HierarchicalNSW init failed: ${n}`)}}add(e,r,t){if(!this.nativeIndex)throw new Error("NativeHnswBackend has been disposed");let n=this.normalizeVector(r);if(!this.liveIds.has(e)&&this.liveIds.size>=this.currentMaxElements){let a=this.currentMaxElements*2;this.nativeIndex.resizeIndex(a),this.currentMaxElements=a}this.nativeIndex.addPoint(K(n),e,!0),this.liveIds.add(e),t?this.metadataStore.set(e,t):this.metadataStore.delete(e),this._metrics.totalAdds++}search(e,r){if(!this.nativeIndex)throw new Error("NativeHnswBackend has been disposed");if(this.liveIds.size===0||r<=0)return[];let t=performance.now(),n=this.normalizeVector(e),a=Math.min(r,this.liveIds.size),o=Math.min(this.liveIds.size,Math.max(a,this.config.efSearch)*2),c=this.nativeIndex.searchKnn(K(n),o),s=this.config.metric==="cosine",d=new Map;for(let h=0;h<c.neighbors.length;h++){let m=c.neighbors[h];if(!this.liveIds.has(m))continue;let x=c.distances[h],f=s?1-x:-x,G=d.get(m);(G===void 0||f>G.score)&&d.set(m,{id:m,score:f,metadata:this.metadataStore.get(m)})}let l=Array.from(d.values());l.sort((h,m)=>m.score-h.score),l.length>a&&(l.length=a);let u=performance.now()-t;return this.updateSearchMetrics(u),this._metrics.nativeSearchCount=this._metrics.totalSearches,u>50&&console.warn(`[NativeHNSW] search took ${u.toFixed(1)}ms (k=${r}, results=${l.length})`),l}remove(e){if(!this.nativeIndex||!this.liveIds.has(e))return!1;try{this.nativeIndex.markDelete(e)}catch{return!1}return this.liveIds.delete(e),this.metadataStore.delete(e),this._metrics.totalRemoves++,!0}size(){return this.liveIds.size}dimensions(){return this.config.dimensions}recall(){return .99}getMetrics(){return{...this._metrics}}get lastSearchLatencyMs(){return this._metrics.lastSearchLatencyMs}getConfig(){return{...this.config}}clear(){this.nativeIndex&&(this.liveIds.clear(),this.metadataStore.clear(),this.currentMaxElements=J,this.nativeIndex=this.createFreshIndex())}dispose(){this.liveIds.clear(),this.metadataStore.clear(),this.nativeIndex=null}isNativeAvailable(){return this.nativeIndex!==null}normalizeVector(e){return e.length===this.config.dimensions?e:me(e,this.config.dimensions)}updateSearchMetrics(e){this._metrics.totalSearches++,this._metrics.lastSearchLatencyMs=e,e>this._metrics.maxSearchLatencyMs&&(this._metrics.maxSearchLatencyMs=e);let r=this._metrics.totalSearches;this._metrics.avgSearchLatencyMs=this._metrics.avgSearchLatencyMs*((r-1)/r)+e/r}}});function X(i,e){let r=Array.from({length:e},()=>new Float64Array(e));for(let t=0;t<e;t++){let n=i[t].length;r[t][t]=n;for(let a of i[t])r[t][a]=-1}return r}function N(i,e){let r=e.length,t=new Float64Array(r);for(let n=0;n<r;n++){let a=i[n].length;t[n]=a*e[n];for(let o of i[n])t[n]-=e[o]}return t}function H(i){let e=0;for(let r=0;r<i.length;r++)e+=i[r]*i[r];return Math.sqrt(e)}function R(i){let e=H(i);if(e>0)for(let r=0;r<i.length;r++)i[r]/=e}function v(i,e){let r=0;for(let t=0;t<i.length;t++)r+=i[t]*e[t];for(let t=0;t<i.length;t++)i[t]-=r*e[t]}function y(i,e,r=100,t=1e-6){if(e<=1)return 0;if(e===2)return i[0].includes(1)?2:0;let n=new Float64Array(e).fill(1/Math.sqrt(e)),a=new Float64Array(e);for(let l=0;l<e;l++)a[l]=Math.random()-.5;v(a,n),R(a);let o=0;for(let l=0;l<30;l++){let u=N(i,a);if(v(u,n),o=H(u),o>0)for(let h=0;h<e;h++)a[h]=u[h]/o}if(o<t)return 0;let c=new Float64Array(e);for(let l=0;l<e;l++)c[l]=Math.random()-.5;v(c,n),R(c);let s=0;for(let l=0;l<r;l++){let u=N(i,c),h=new Float64Array(e);for(let f=0;f<e;f++)h[f]=o*c[f]-u[f];v(h,n);let m=H(h);if(m<t)break;let x=m;for(let f=0;f<e;f++)c[f]=h[f]/m;if(Math.abs(x-s)<t)break;s=x}let d=o-s;return Math.max(0,d)}function F(i,e,r=100,t=1e-6){return y(i,e,r,t)}function C(i,e,r=50,t){if(e<=1)return 0;let n=t??y(i,e);if(n<1e-10)return 1/0;let o=2*Math.max(...i.map(d=>d.length),1),s=2*(Math.log(o/n)/(o-n));return Math.max(0,s)}function M(i,e,r){let t=1-Math.exp(-i/.05),n=1-Math.exp(-e/.5),a=r===1/0?0:1/(1+r/5),o=.4*t+.3*n+.3*a;return Math.max(0,Math.min(1,o))}var _=g(()=>{"use strict"});var ee={};ne(ee,{ALERT_THRESHOLDS:()=>fe,DEFAULT_HNSW_HEALTH_CONFIG:()=>Y,HnswHealthMonitor:()=>L,_resetNativeLoader:()=>be,approximateFiedlerValue:()=>y,approximateSpectralGap:()=>F,buildAdjacencyFromIndex:()=>Z,buildLaplacian:()=>X,computeCoherenceScore:()=>M,createHnswHealthMonitor:()=>ge,deflateVector:()=>v,estimateEffectiveResistance:()=>C,laplacianMultiply:()=>N,normalizeInPlace:()=>R,vectorNorm:()=>H});function pe(){return V?T:(V=!0,T=null,null)}function be(){T=null,V=!1}function Z(i,e=16,r){let t=i.size();if(t===0)return{adjacency:[],nodeCount:0,adjacencySource:"approximate"};let n=Array.from({length:t},()=>[]),a=Math.min(e,t-1);if(a===0)return{adjacency:n,nodeCount:t,adjacencySource:"approximate"};if(r&&r.size>0){let o=Array.from(r.keys()).slice(0,t),c=new Map;for(let s=0;s<o.length;s++)c.set(o[s],s);for(let s=0;s<o.length;s++){let d=r.get(o[s]);if(!d)continue;let l=i.search(d,a+1);for(let u of l){if(u.id===o[s])continue;let h=c.get(u.id);h!==void 0&&(n[s].includes(h)||n[s].push(h),n[h].includes(s)||n[h].push(s))}}return{adjacency:n,nodeCount:t,adjacencySource:"actual-search"}}console.warn("[HnswHealthMonitor] No stored vectors provided \u2014 using approximate circular adjacency. Pass stored vectors for accurate health metrics.");for(let o=0;o<t;o++)for(let c=0;c<a;c++){let s=(o+c+1)%t;n[o].includes(s)||n[o].push(s),n[s].includes(o)||n[s].push(o)}return{adjacency:n,nodeCount:t,adjacencySource:"approximate"}}function ge(i){return new L(i)}var Y,fe,T,V,L,te=g(()=>{"use strict";_();_();Y={fiedlerThreshold:.01,spectralGapThreshold:.1,resistanceThreshold:10,coherenceThreshold:.3,maxPowerIterations:100,convergenceTolerance:1e-6,resistanceSampleSize:50,maxHistoryEntries:200,minIndexSize:3},fe={FragileIndex:.01,PoorExpansion:.1,HighResistance:10,LowCoherence:.3},T=null,V=!1;L=class{config;alerts=[];history=[];lastReport=null;useNative=!1;nativeChecked=!1;constructor(e){this.config={...Y,...e}}checkHealth(e){let r=performance.now(),t=e.size();if(t<this.config.minIndexSize)return this.createSmallIndexReport(t,performance.now()-r);this.nativeChecked||(this.nativeChecked=!0,this.useNative=pe()!==null);let{adjacency:n,nodeCount:a,adjacencySource:o}=Z(e),c=this.useNative?this.computeNativeMetrics(n):this.computeApproximateMetrics(n,a),s=this.generateAlerts(c);this.alerts.length=0,this.alerts.push(...s);let d=performance.now()-r,l={healthy:s.length===0,metrics:c,alerts:s,indexSize:t,usedNativeBackend:this.useNative,adjacencySource:o,checkDurationMs:d,checkedAt:new Date};return this.addHistoryPoint({coherenceScore:c.coherenceScore,fiedlerValue:c.fiedlerValue,indexSize:t,healthy:l.healthy,timestamp:l.checkedAt}),this.lastReport=l,l}getAlerts(){return[...this.alerts]}getMetricsHistory(e){let r=[...this.history];return e!==void 0&&e<r.length?r.slice(-e):r}isHealthy(){return this.lastReport===null?!0:this.lastReport.healthy}getLastReport(){return this.lastReport}clearHistory(){this.history.length=0,this.alerts.length=0,this.lastReport=null}computeNativeMetrics(e){let r=T,t=r.computeFiedlerValue(e),n=r.computeSpectralGap(e),a=r.computeEffectiveResistance(e),o=M(t,n,a);return{fiedlerValue:t,spectralGap:n,effectiveResistance:a,coherenceScore:o}}computeApproximateMetrics(e,r){let t=y(e,r,this.config.maxPowerIterations,this.config.convergenceTolerance),n=F(e,r,this.config.maxPowerIterations,this.config.convergenceTolerance),a=C(e,r,this.config.resistanceSampleSize,t),o=M(t,n,a);return{fiedlerValue:t,spectralGap:n,effectiveResistance:a,coherenceScore:o}}generateAlerts(e){let r=[],t=new Date;return e.fiedlerValue<this.config.fiedlerThreshold&&r.push({type:"FragileIndex",message:`Fiedler value ${e.fiedlerValue.toFixed(6)} is below threshold ${this.config.fiedlerThreshold}. The index graph has weak algebraic connectivity.`,value:e.fiedlerValue,threshold:this.config.fiedlerThreshold,timestamp:t}),e.spectralGap<this.config.spectralGapThreshold&&r.push({type:"PoorExpansion",message:`Spectral gap ${e.spectralGap.toFixed(6)} is below threshold ${this.config.spectralGapThreshold}. The index graph has poor expansion properties.`,value:e.spectralGap,threshold:this.config.spectralGapThreshold,timestamp:t}),e.effectiveResistance>this.config.resistanceThreshold&&r.push({type:"HighResistance",message:`Average effective resistance ${e.effectiveResistance.toFixed(4)} exceeds threshold ${this.config.resistanceThreshold}. Nodes are poorly connected.`,value:e.effectiveResistance,threshold:this.config.resistanceThreshold,timestamp:t}),e.coherenceScore<this.config.coherenceThreshold&&r.push({type:"LowCoherence",message:`Coherence score ${e.coherenceScore.toFixed(4)} is below threshold ${this.config.coherenceThreshold}. Overall index health is degraded.`,value:e.coherenceScore,threshold:this.config.coherenceThreshold,timestamp:t}),r}createSmallIndexReport(e,r){let t={fiedlerValue:e>0?1:0,spectralGap:e>0?1:0,effectiveResistance:e>0?.5:0,coherenceScore:e>0?1:0},n={healthy:!0,metrics:t,alerts:[],indexSize:e,usedNativeBackend:!1,adjacencySource:"approximate",checkDurationMs:r,checkedAt:new Date};return this.addHistoryPoint({coherenceScore:t.coherenceScore,fiedlerValue:t.fiedlerValue,indexSize:e,healthy:!0,timestamp:n.checkedAt}),this.lastReport=n,n}addHistoryPoint(e){this.history.push(e),this.history.length>this.config.maxHistoryEntries&&this.history.splice(0,this.history.length-this.config.maxHistoryEntries)}}});var ve,p,re,ye=g(()=>{B();Q();ie();ve={patterns:{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"},"qe-memory":{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"},learning:{dimensions:384,M:16,efConstruction:200,efSearch:50,metric:"cosine"},coverage:{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"}},p=new Map,re=class i{backend;_isNativeBackend;indexName;stringToNumericId=new Map;numericToStringId=new Map;nextAutoId=0;healthMonitor=null;healthMonitorLoaded=!1;operationsSinceLastCheck=0;healthCheckFrequency=100;lastHealthReport=null;constructor(e,r){this.indexName=e;let n={...ve[e]??{},...r},{backend:a,isNative:o}=i.createBackend(n);this.backend=a,this._isNativeBackend=o}add(e,r,t){this.backend.add(e,r,t),this.maybeRunHealthCheck()}search(e,r){let t=performance.now(),n=this.backend.search(e,r),a=performance.now()-t;return a>50&&console.warn(`[HNSW] search took ${a.toFixed(1)}ms (k=${r}, results=${n.length})`),this._lastSearchLatencyMs=a,n}_lastSearchLatencyMs=0;get lastSearchLatencyMs(){return this._lastSearchLatencyMs}remove(e){return this.backend.remove(e)}size(){return this.backend.size()}dimensions(){return this.backend.dimensions()}recall(){return this.backend.recall()}addByStringId(e,r){let t=this.stringToNumericId.get(e);t!==void 0?this.backend.remove(t):(t=this.nextAutoId++,this.stringToNumericId.set(e,t),this.numericToStringId.set(t,e)),this.backend.add(t,new Float32Array(r))}searchByArray(e,r){return this.backend.search(new Float32Array(e),r).map(n=>({id:this.numericToStringId.get(n.id)??String(n.id),score:n.score}))}removeByStringId(e){let r=this.stringToNumericId.get(e);if(r===void 0)return!1;let t=this.backend.remove(r);return t&&(this.stringToNumericId.delete(e),this.numericToStringId.delete(r)),t}clear(){this.backend.clear?.(),this.stringToNumericId.clear(),this.numericToStringId.clear(),this.nextAutoId=0}dispose(){try{this.backend.dispose?.()}catch{}this.stringToNumericId.clear(),this.numericToStringId.clear(),this.nextAutoId=0}isRuvectorAvailable(){return this.backend instanceof S?this.backend.isRuvectorAvailable():this.backend instanceof w?this.backend.isNativeAvailable():!1}isNativeBackend(){return this._isNativeBackend}getName(){return this.indexName}setHealthCheckFrequency(e){this.healthCheckFrequency=Math.max(1,e)}getHealthCheckFrequency(){return this.healthCheckFrequency}getLastHealthReport(){return this.lastHealthReport}getHealthMonitor(){return this.healthMonitor}maybeRunHealthCheck(){if($()&&(this.operationsSinceLastCheck++,!(this.operationsSinceLastCheck<this.healthCheckFrequency)&&(this.operationsSinceLastCheck=0,this.ensureHealthMonitor(),this.healthMonitor)))try{this.lastHealthReport=this.healthMonitor.checkHealth(this.backend),this.lastHealthReport.healthy||console.warn(`[HNSW-Health] Index "${this.indexName}" health check failed: ${this.lastHealthReport.alerts.length} alert(s). Coherence: ${this.lastHealthReport.metrics.coherenceScore.toFixed(3)}`)}catch(e){console.warn(`[HNSW-Health] Health check error for "${this.indexName}":`,e)}}ensureHealthMonitor(){if(!this.healthMonitorLoaded){this.healthMonitorLoaded=!0;try{let e=(te(),W(ee));this.healthMonitor=e.createHnswHealthMonitor()}catch(e){process.env.DEBUG&&console.debug("[HNSW-Health] Monitor module unavailable:",e instanceof Error?e.message:e),this.healthMonitor=null}}}static createBackend(e){if(D())try{return{backend:new w(e),isNative:!0}}catch(r){r instanceof b?console.info(`[HNSW] Native backend unavailable, falling back to JS: ${r.message}`):console.warn("[HNSW] Unexpected error creating native backend, falling back to JS:",r)}return{backend:new S(e),isNative:!1}}static create(e,r){let t=p.get(e);if(t instanceof i)return t;let n=new i(e,r);return p.set(e,n),n}static get(e){let r=p.get(e);return r instanceof i?r:void 0}static close(e){let r=p.get(e);r instanceof i&&r.dispose(),p.delete(e)}static closeAll(){for(let[e]of p)i.close(e);p.clear()}static listIndexes(){return Array.from(p.keys())}}});export{re as a,ye 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.15.1");process.exit(0)}
2
+ import{a as ae,b as oe}from"./chunk-WPG6SW7C.js";import{S as ie,i as D,p as $}from"./chunk-HU4QGCIJ.js";import{b as g,d as ne,f as W}from"./chunk-PNK5KHSI.js";var I,E=g(()=>{"use strict";I={dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"}});function se(){if(z)return A!==null;try{let i=(oe(),W(ae));if(A=i.differentiableSearch,P=i.init,P)try{P()}catch{}return z=!0,!0}catch{return z=!0,!1}}function j(i){let e=0;for(let r=0;r<i.length;r++)e+=i[r]*i[r];return Math.sqrt(e)}function ce(i,e,r,t){let n=r*t;if(n===0)return 0;let a=0,o=Math.min(i.length,e.length);for(let c=0;c<o;c++)a+=i[c]*e[c];return a/n}function q(i,e){let r=0,t=Math.min(i.length,e.length);for(let n=0;n<t;n++){let a=i[n]-e[n];r+=a*a}return Math.sqrt(r)}function le(i,e){if(i.length===e)return i;let r=new Float32Array(e);if(i.length>e){let t=i.length/e;for(let n=0;n<e;n++){let a=Math.floor(n*t),o=Math.floor((n+1)*t),c=0;for(let s=a;s<o;s++)c+=i[s];r[n]=c/(o-a)}}else for(let t=0;t<i.length;t++)r[t]=i[t];return r}var A,P,z,S,B=g(()=>{"use strict";E();A=null,P=null,z=!1;S=class{config;entries=[];idToIndex=new Map;hasRuvector=!1;loaded=!1;constructor(e){this.config={...I,...e}}ensureLoaded(){this.loaded||(this.hasRuvector=se(),this.loaded=!0)}normalizeVector(e){return e.length===this.config.dimensions?e:le(e,this.config.dimensions)}add(e,r,t){this.ensureLoaded();let n=this.normalizeVector(r),a=j(n);if(this.idToIndex.has(e)){let c=this.idToIndex.get(e);this.entries[c]={id:e,vector:n,norm:a,metadata:t};return}let o=this.entries.length;this.entries.push({id:e,vector:n,norm:a,metadata:t}),this.idToIndex.set(e,o)}search(e,r){if(this.ensureLoaded(),this.entries.length===0)return[];let t=this.normalizeVector(e),n=j(t),a=Math.min(r,this.entries.length),o=this.entries.length>0?this.entries[0].vector.length:0,c=t.length===o;if(this.config.metric==="cosine")return this.bruteForcSearch(t,n,a);if(this.hasRuvector&&c&&A)try{let s=this.entries.map(u=>u.vector),l=A(t,s,a,1).indices.map(u=>{let h=this.entries[u],m=-q(t,h.vector);return{id:h.id,score:m,metadata:h.metadata}});return l.sort((u,h)=>h.score-u.score),l}catch{}return this.bruteForcSearch(t,n,a)}bruteForcSearch(e,r,t){let n=[];for(let a of this.entries){let o;this.config.metric==="cosine"?o=ce(e,a.vector,r,a.norm):o=-q(e,a.vector),n.push({id:a.id,score:o,metadata:a.metadata})}return n.sort((a,o)=>o.score-a.score),n.slice(0,t)}remove(e){let r=this.idToIndex.get(e);if(r===void 0)return!1;let t=this.entries.length-1;if(r!==t){let n=this.entries[t];this.entries[r]=n,this.idToIndex.set(n.id,r)}return this.entries.pop(),this.idToIndex.delete(e),!0}size(){return this.entries.length}dimensions(){return this.config.dimensions}recall(){return this.hasRuvector,1}isRuvectorAvailable(){return this.ensureLoaded(),this.hasRuvector}getConfig(){return{...this.config}}clear(){this.entries=[],this.idToIndex.clear()}dispose(){this.clear()}}});import{createRequire as he}from"module";function de(){if(U){if(k)return k;throw new b(O??"Unknown load error")}U=!0;try{let i=ue("hnswlib-node");if(!i.HierarchicalNSW)throw new Error("hnswlib-node module missing HierarchicalNSW export");return k=i,k}catch(i){let e=i instanceof Error?i.message:String(i);throw O=e,new b(e)}}function me(i,e){if(i.length===e)return i;let r=new Float32Array(e);if(i.length>e){let t=i.length/e;for(let n=0;n<e;n++){let a=Math.floor(n*t),o=Math.floor((n+1)*t),c=0;for(let s=a;s<o;s++)c+=i[s];r[n]=c/(o-a)}}else for(let t=0;t<i.length;t++)r[t]=i[t];return r}function K(i){let e=new Array(i.length);for(let r=0;r<i.length;r++)e[r]=i[r];return e}var ue,b,k,U,O,J,w,Q=g(()=>{"use strict";E();ue=he(import.meta.url),b=class extends Error{constructor(e){super(`Native HNSW backend unavailable: ${e}`),this.name="NativeHnswUnavailableError"}},k=null,U=!1,O=null;J=1e4,w=class{config;nativeIndex=null;currentMaxElements=J;liveIds=new Set;metadataStore=new Map;_metrics={totalSearches:0,totalAdds:0,totalRemoves:0,avgSearchLatencyMs:0,maxSearchLatencyMs:0,lastSearchLatencyMs:0,fallbackSearchCount:0,bruteForceSearchCount:0,nativeSearchCount:0,fallbackRate:0,allSearchesBruteForce:!1};constructor(e){this.config={...I,...e},this.nativeIndex=this.createFreshIndex()}createFreshIndex(){let e=de(),r=this.config.metric==="euclidean"?"l2":"cosine";try{let t=new e.HierarchicalNSW(r,this.config.dimensions);return t.initIndex(this.currentMaxElements,this.config.M,this.config.efConstruction,100,!0),t.setEf(this.config.efSearch),t}catch(t){let n=t instanceof Error?t.message:String(t);throw new b(`HierarchicalNSW init failed: ${n}`)}}add(e,r,t){if(!this.nativeIndex)throw new Error("NativeHnswBackend has been disposed");let n=this.normalizeVector(r);if(!this.liveIds.has(e)&&this.liveIds.size>=this.currentMaxElements){let a=this.currentMaxElements*2;this.nativeIndex.resizeIndex(a),this.currentMaxElements=a}this.nativeIndex.addPoint(K(n),e,!0),this.liveIds.add(e),t?this.metadataStore.set(e,t):this.metadataStore.delete(e),this._metrics.totalAdds++}search(e,r){if(!this.nativeIndex)throw new Error("NativeHnswBackend has been disposed");if(this.liveIds.size===0||r<=0)return[];let t=performance.now(),n=this.normalizeVector(e),a=Math.min(r,this.liveIds.size),o=Math.min(this.liveIds.size,Math.max(a,this.config.efSearch)*2),c=this.nativeIndex.searchKnn(K(n),o),s=this.config.metric==="cosine",d=new Map;for(let h=0;h<c.neighbors.length;h++){let m=c.neighbors[h];if(!this.liveIds.has(m))continue;let x=c.distances[h],f=s?1-x:-x,G=d.get(m);(G===void 0||f>G.score)&&d.set(m,{id:m,score:f,metadata:this.metadataStore.get(m)})}let l=Array.from(d.values());l.sort((h,m)=>m.score-h.score),l.length>a&&(l.length=a);let u=performance.now()-t;return this.updateSearchMetrics(u),this._metrics.nativeSearchCount=this._metrics.totalSearches,u>50&&console.warn(`[NativeHNSW] search took ${u.toFixed(1)}ms (k=${r}, results=${l.length})`),l}remove(e){if(!this.nativeIndex||!this.liveIds.has(e))return!1;try{this.nativeIndex.markDelete(e)}catch{return!1}return this.liveIds.delete(e),this.metadataStore.delete(e),this._metrics.totalRemoves++,!0}size(){return this.liveIds.size}dimensions(){return this.config.dimensions}recall(){return .99}getMetrics(){return{...this._metrics}}get lastSearchLatencyMs(){return this._metrics.lastSearchLatencyMs}getConfig(){return{...this.config}}clear(){this.nativeIndex&&(this.liveIds.clear(),this.metadataStore.clear(),this.currentMaxElements=J,this.nativeIndex=this.createFreshIndex())}dispose(){this.liveIds.clear(),this.metadataStore.clear(),this.nativeIndex=null}isNativeAvailable(){return this.nativeIndex!==null}normalizeVector(e){return e.length===this.config.dimensions?e:me(e,this.config.dimensions)}updateSearchMetrics(e){this._metrics.totalSearches++,this._metrics.lastSearchLatencyMs=e,e>this._metrics.maxSearchLatencyMs&&(this._metrics.maxSearchLatencyMs=e);let r=this._metrics.totalSearches;this._metrics.avgSearchLatencyMs=this._metrics.avgSearchLatencyMs*((r-1)/r)+e/r}}});function X(i,e){let r=Array.from({length:e},()=>new Float64Array(e));for(let t=0;t<e;t++){let n=i[t].length;r[t][t]=n;for(let a of i[t])r[t][a]=-1}return r}function N(i,e){let r=e.length,t=new Float64Array(r);for(let n=0;n<r;n++){let a=i[n].length;t[n]=a*e[n];for(let o of i[n])t[n]-=e[o]}return t}function H(i){let e=0;for(let r=0;r<i.length;r++)e+=i[r]*i[r];return Math.sqrt(e)}function R(i){let e=H(i);if(e>0)for(let r=0;r<i.length;r++)i[r]/=e}function v(i,e){let r=0;for(let t=0;t<i.length;t++)r+=i[t]*e[t];for(let t=0;t<i.length;t++)i[t]-=r*e[t]}function y(i,e,r=100,t=1e-6){if(e<=1)return 0;if(e===2)return i[0].includes(1)?2:0;let n=new Float64Array(e).fill(1/Math.sqrt(e)),a=new Float64Array(e);for(let l=0;l<e;l++)a[l]=Math.random()-.5;v(a,n),R(a);let o=0;for(let l=0;l<30;l++){let u=N(i,a);if(v(u,n),o=H(u),o>0)for(let h=0;h<e;h++)a[h]=u[h]/o}if(o<t)return 0;let c=new Float64Array(e);for(let l=0;l<e;l++)c[l]=Math.random()-.5;v(c,n),R(c);let s=0;for(let l=0;l<r;l++){let u=N(i,c),h=new Float64Array(e);for(let f=0;f<e;f++)h[f]=o*c[f]-u[f];v(h,n);let m=H(h);if(m<t)break;let x=m;for(let f=0;f<e;f++)c[f]=h[f]/m;if(Math.abs(x-s)<t)break;s=x}let d=o-s;return Math.max(0,d)}function F(i,e,r=100,t=1e-6){return y(i,e,r,t)}function C(i,e,r=50,t){if(e<=1)return 0;let n=t??y(i,e);if(n<1e-10)return 1/0;let o=2*Math.max(...i.map(d=>d.length),1),s=2*(Math.log(o/n)/(o-n));return Math.max(0,s)}function M(i,e,r){let t=1-Math.exp(-i/.05),n=1-Math.exp(-e/.5),a=r===1/0?0:1/(1+r/5),o=.4*t+.3*n+.3*a;return Math.max(0,Math.min(1,o))}var _=g(()=>{"use strict"});var ee={};ne(ee,{ALERT_THRESHOLDS:()=>fe,DEFAULT_HNSW_HEALTH_CONFIG:()=>Y,HnswHealthMonitor:()=>L,_resetNativeLoader:()=>be,approximateFiedlerValue:()=>y,approximateSpectralGap:()=>F,buildAdjacencyFromIndex:()=>Z,buildLaplacian:()=>X,computeCoherenceScore:()=>M,createHnswHealthMonitor:()=>ge,deflateVector:()=>v,estimateEffectiveResistance:()=>C,laplacianMultiply:()=>N,normalizeInPlace:()=>R,vectorNorm:()=>H});function pe(){return V?T:(V=!0,T=null,null)}function be(){T=null,V=!1}function Z(i,e=16,r){let t=i.size();if(t===0)return{adjacency:[],nodeCount:0,adjacencySource:"approximate"};let n=Array.from({length:t},()=>[]),a=Math.min(e,t-1);if(a===0)return{adjacency:n,nodeCount:t,adjacencySource:"approximate"};if(r&&r.size>0){let o=Array.from(r.keys()).slice(0,t),c=new Map;for(let s=0;s<o.length;s++)c.set(o[s],s);for(let s=0;s<o.length;s++){let d=r.get(o[s]);if(!d)continue;let l=i.search(d,a+1);for(let u of l){if(u.id===o[s])continue;let h=c.get(u.id);h!==void 0&&(n[s].includes(h)||n[s].push(h),n[h].includes(s)||n[h].push(s))}}return{adjacency:n,nodeCount:t,adjacencySource:"actual-search"}}console.warn("[HnswHealthMonitor] No stored vectors provided \u2014 using approximate circular adjacency. Pass stored vectors for accurate health metrics.");for(let o=0;o<t;o++)for(let c=0;c<a;c++){let s=(o+c+1)%t;n[o].includes(s)||n[o].push(s),n[s].includes(o)||n[s].push(o)}return{adjacency:n,nodeCount:t,adjacencySource:"approximate"}}function ge(i){return new L(i)}var Y,fe,T,V,L,te=g(()=>{"use strict";_();_();Y={fiedlerThreshold:.01,spectralGapThreshold:.1,resistanceThreshold:10,coherenceThreshold:.3,maxPowerIterations:100,convergenceTolerance:1e-6,resistanceSampleSize:50,maxHistoryEntries:200,minIndexSize:3},fe={FragileIndex:.01,PoorExpansion:.1,HighResistance:10,LowCoherence:.3},T=null,V=!1;L=class{config;alerts=[];history=[];lastReport=null;useNative=!1;nativeChecked=!1;constructor(e){this.config={...Y,...e}}checkHealth(e){let r=performance.now(),t=e.size();if(t<this.config.minIndexSize)return this.createSmallIndexReport(t,performance.now()-r);this.nativeChecked||(this.nativeChecked=!0,this.useNative=pe()!==null);let{adjacency:n,nodeCount:a,adjacencySource:o}=Z(e),c=this.useNative?this.computeNativeMetrics(n):this.computeApproximateMetrics(n,a),s=this.generateAlerts(c);this.alerts.length=0,this.alerts.push(...s);let d=performance.now()-r,l={healthy:s.length===0,metrics:c,alerts:s,indexSize:t,usedNativeBackend:this.useNative,adjacencySource:o,checkDurationMs:d,checkedAt:new Date};return this.addHistoryPoint({coherenceScore:c.coherenceScore,fiedlerValue:c.fiedlerValue,indexSize:t,healthy:l.healthy,timestamp:l.checkedAt}),this.lastReport=l,l}getAlerts(){return[...this.alerts]}getMetricsHistory(e){let r=[...this.history];return e!==void 0&&e<r.length?r.slice(-e):r}isHealthy(){return this.lastReport===null?!0:this.lastReport.healthy}getLastReport(){return this.lastReport}clearHistory(){this.history.length=0,this.alerts.length=0,this.lastReport=null}computeNativeMetrics(e){let r=T,t=r.computeFiedlerValue(e),n=r.computeSpectralGap(e),a=r.computeEffectiveResistance(e),o=M(t,n,a);return{fiedlerValue:t,spectralGap:n,effectiveResistance:a,coherenceScore:o}}computeApproximateMetrics(e,r){let t=y(e,r,this.config.maxPowerIterations,this.config.convergenceTolerance),n=F(e,r,this.config.maxPowerIterations,this.config.convergenceTolerance),a=C(e,r,this.config.resistanceSampleSize,t),o=M(t,n,a);return{fiedlerValue:t,spectralGap:n,effectiveResistance:a,coherenceScore:o}}generateAlerts(e){let r=[],t=new Date;return e.fiedlerValue<this.config.fiedlerThreshold&&r.push({type:"FragileIndex",message:`Fiedler value ${e.fiedlerValue.toFixed(6)} is below threshold ${this.config.fiedlerThreshold}. The index graph has weak algebraic connectivity.`,value:e.fiedlerValue,threshold:this.config.fiedlerThreshold,timestamp:t}),e.spectralGap<this.config.spectralGapThreshold&&r.push({type:"PoorExpansion",message:`Spectral gap ${e.spectralGap.toFixed(6)} is below threshold ${this.config.spectralGapThreshold}. The index graph has poor expansion properties.`,value:e.spectralGap,threshold:this.config.spectralGapThreshold,timestamp:t}),e.effectiveResistance>this.config.resistanceThreshold&&r.push({type:"HighResistance",message:`Average effective resistance ${e.effectiveResistance.toFixed(4)} exceeds threshold ${this.config.resistanceThreshold}. Nodes are poorly connected.`,value:e.effectiveResistance,threshold:this.config.resistanceThreshold,timestamp:t}),e.coherenceScore<this.config.coherenceThreshold&&r.push({type:"LowCoherence",message:`Coherence score ${e.coherenceScore.toFixed(4)} is below threshold ${this.config.coherenceThreshold}. Overall index health is degraded.`,value:e.coherenceScore,threshold:this.config.coherenceThreshold,timestamp:t}),r}createSmallIndexReport(e,r){let t={fiedlerValue:e>0?1:0,spectralGap:e>0?1:0,effectiveResistance:e>0?.5:0,coherenceScore:e>0?1:0},n={healthy:!0,metrics:t,alerts:[],indexSize:e,usedNativeBackend:!1,adjacencySource:"approximate",checkDurationMs:r,checkedAt:new Date};return this.addHistoryPoint({coherenceScore:t.coherenceScore,fiedlerValue:t.fiedlerValue,indexSize:e,healthy:!0,timestamp:n.checkedAt}),this.lastReport=n,n}addHistoryPoint(e){this.history.push(e),this.history.length>this.config.maxHistoryEntries&&this.history.splice(0,this.history.length-this.config.maxHistoryEntries)}}});var ve,p,re,ye=g(()=>{B();Q();ie();ve={patterns:{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"},"qe-memory":{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"},learning:{dimensions:384,M:16,efConstruction:200,efSearch:50,metric:"cosine"},coverage:{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"}},p=new Map,re=class i{backend;_isNativeBackend;indexName;stringToNumericId=new Map;numericToStringId=new Map;nextAutoId=0;healthMonitor=null;healthMonitorLoaded=!1;operationsSinceLastCheck=0;healthCheckFrequency=100;lastHealthReport=null;constructor(e,r){this.indexName=e;let n={...ve[e]??{},...r},{backend:a,isNative:o}=i.createBackend(n);this.backend=a,this._isNativeBackend=o}add(e,r,t){this.backend.add(e,r,t),this.maybeRunHealthCheck()}search(e,r){let t=performance.now(),n=this.backend.search(e,r),a=performance.now()-t;return a>50&&console.warn(`[HNSW] search took ${a.toFixed(1)}ms (k=${r}, results=${n.length})`),this._lastSearchLatencyMs=a,n}_lastSearchLatencyMs=0;get lastSearchLatencyMs(){return this._lastSearchLatencyMs}remove(e){return this.backend.remove(e)}size(){return this.backend.size()}dimensions(){return this.backend.dimensions()}recall(){return this.backend.recall()}addByStringId(e,r){let t=this.stringToNumericId.get(e);t!==void 0?this.backend.remove(t):(t=this.nextAutoId++,this.stringToNumericId.set(e,t),this.numericToStringId.set(t,e)),this.backend.add(t,new Float32Array(r))}searchByArray(e,r){return this.backend.search(new Float32Array(e),r).map(n=>({id:this.numericToStringId.get(n.id)??String(n.id),score:n.score}))}removeByStringId(e){let r=this.stringToNumericId.get(e);if(r===void 0)return!1;let t=this.backend.remove(r);return t&&(this.stringToNumericId.delete(e),this.numericToStringId.delete(r)),t}clear(){this.backend.clear?.(),this.stringToNumericId.clear(),this.numericToStringId.clear(),this.nextAutoId=0}dispose(){try{this.backend.dispose?.()}catch{}this.stringToNumericId.clear(),this.numericToStringId.clear(),this.nextAutoId=0}isRuvectorAvailable(){return this.backend instanceof S?this.backend.isRuvectorAvailable():this.backend instanceof w?this.backend.isNativeAvailable():!1}isNativeBackend(){return this._isNativeBackend}getName(){return this.indexName}setHealthCheckFrequency(e){this.healthCheckFrequency=Math.max(1,e)}getHealthCheckFrequency(){return this.healthCheckFrequency}getLastHealthReport(){return this.lastHealthReport}getHealthMonitor(){return this.healthMonitor}maybeRunHealthCheck(){if($()&&(this.operationsSinceLastCheck++,!(this.operationsSinceLastCheck<this.healthCheckFrequency)&&(this.operationsSinceLastCheck=0,this.ensureHealthMonitor(),this.healthMonitor)))try{this.lastHealthReport=this.healthMonitor.checkHealth(this.backend),this.lastHealthReport.healthy||console.warn(`[HNSW-Health] Index "${this.indexName}" health check failed: ${this.lastHealthReport.alerts.length} alert(s). Coherence: ${this.lastHealthReport.metrics.coherenceScore.toFixed(3)}`)}catch(e){console.warn(`[HNSW-Health] Health check error for "${this.indexName}":`,e)}}ensureHealthMonitor(){if(!this.healthMonitorLoaded){this.healthMonitorLoaded=!0;try{let e=(te(),W(ee));this.healthMonitor=e.createHnswHealthMonitor()}catch(e){process.env.DEBUG&&console.debug("[HNSW-Health] Monitor module unavailable:",e instanceof Error?e.message:e),this.healthMonitor=null}}}static createBackend(e){if(D())try{return{backend:new w(e),isNative:!0}}catch(r){r instanceof b?console.info(`[HNSW] Native backend unavailable, falling back to JS: ${r.message}`):console.warn("[HNSW] Unexpected error creating native backend, falling back to JS:",r)}return{backend:new S(e),isNative:!1}}static create(e,r){let t=p.get(e);if(t instanceof i)return t;let n=new i(e,r);return p.set(e,n),n}static get(e){let r=p.get(e);return r instanceof i?r:void 0}static close(e){let r=p.get(e);r instanceof i&&r.dispose(),p.delete(e)}static closeAll(){for(let[e]of p)i.close(e);p.clear()}static listIndexes(){return Array.from(p.keys())}}});export{re as a,ye 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.14.8");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.15.1");process.exit(0)}
2
2
  import{writeFileSync as d,readFileSync as m}from"node:fs";import{resolve as f,dirname as u,join as g}from"node:path";import{mkdirSync as h}from"node:fs";import{fileURLToPath as v}from"node:url";function y(){try{let e=typeof __dirname<"u"?__dirname:u(v(import.meta.url));for(let n=0;n<5;n++){let t=g(e,"package.json");try{let o=JSON.parse(m(t,"utf-8"));if(o.version)return o.version}catch{}e=u(e)}}catch{}return"unknown"}function l(e){return e.status??e.evidence?.completeness??"unverified"}var R=["-F, --format <format>","Output format (text|json|sarif|junit|markdown)","text"],T=["-o, --output <path>","Write output to file instead of stdout"];function w(e,n,t){if(n){let o=f(n);h(u(o),{recursive:!0}),d(o,e,"utf-8"),t&&console.log(t),console.log(`Output written to: ${o}`)}else console.log(e)}function $(e){return JSON.stringify(e,null,2)}var S="https://raw.githubusercontent.com/oasis-tcs/sarif-spec/main/sarif-2.1/schema/sarif-schema-2.1.0.json";function F(e){let n=l(e),t=s=>{switch(s.toLowerCase()){case"critical":case"high":return"error";case"medium":return"warning";case"low":case"info":return"note";default:return"warning"}},o=new Map,r=[];for(let s of e.vulnerabilities){let a=s.ruleId||`AQE/${s.type.replace(/\s+/g,"-").toLowerCase()}`;o.has(a)||o.set(a,{id:a,name:s.type,shortDescription:s.type,...s.cweId?{helpUri:`https://cwe.mitre.org/data/definitions/${s.cweId.replace("CWE-","")}.html`}:{}}),r.push({ruleId:a,level:t(s.severity),message:{text:s.message},locations:[{physicalLocation:{artifactLocation:{uri:s.file,uriBaseId:"%SRCROOT%"},region:{startLine:s.line,startColumn:1}}}],...s.cweId?{taxa:[{id:s.cweId,toolComponent:{name:"CWE"}}]}:{}})}let i={$schema:S,version:"2.1.0",runs:[{tool:{driver:{name:"agentic-qe",version:y(),informationUri:"https://github.com/proffesor-for-testing/agentic-qe",rules:Array.from(o.values()).map(s=>({id:s.id,name:s.name,shortDescription:{text:s.shortDescription},...s.helpUri?{helpUri:s.helpUri}:{},defaultConfiguration:{level:"warning"}}))}},results:r,properties:{securityScan:{status:n,target:e.target,scanType:e.scanType,coverage:e.evidence?e.coverage:void 0,evidence:e.evidence,discovery:e.discovery,checks:e.checks}},invocations:[{executionSuccessful:n==="complete",...n==="complete"?{}:{toolExecutionNotifications:[{level:"warning",message:{text:`Security analysis ${n}; findings do not establish complete coverage.`}}]}}]}]};return JSON.stringify(i,null,2)}function c(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function A(e){let n=e.tests||[],t=e.passed+e.failed+e.skipped,o=(e.duration/1e3).toFixed(3),r=`<?xml version="1.0" encoding="UTF-8"?>
3
3
  `;if(r+=`<testsuites tests="${t}" failures="${e.failed}" errors="0" time="${o}">
4
4
  `,r+=` <testsuite name="aqe-test-run" tests="${t}" failures="${e.failed}" errors="0" skipped="${e.skipped}" time="${o}" id="${c(e.runId)}">
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.8");process.exit(0)}
2
- import{a as h}from"./chunk-U64QORFO.js";import{e as m}from"./chunk-J5HTQHJK.js";h();var g=m.create("regret-tracker"),l=50,R=.9,d=1.1;function f(o,t){let e=o.length;if(e<2)return 0;let n=0,r=0,i=0,a=0;for(let s=0;s<e;s++)n+=o[s],r+=t[s],i+=o[s]*t[s],a+=o[s]*o[s];let u=e*a-n*n;return Math.abs(u)<1e-10?0:(e*i-n*r)/u}var c=class{domains=new Map;alertCallbacks=[];alerts=[];maxAlerts;recentWindow;constructor(t){this.maxAlerts=t?.maxAlerts??100,this.recentWindow=t?.recentWindow??20}recordDecision(t,e,n){let r=this.getOrCreateDomainState(t),i=Math.max(0,n-e);if(r.cumulativeRegret+=i,r.decisionCount++,r.points.push({decisionCount:r.decisionCount,cumulativeRegret:r.cumulativeRegret,timestamp:Date.now()}),r.decisionCount>=l){let a=this.classifyGrowthRate(r.points);r.lastGrowthRate!=="insufficient_data"&&a!==r.lastGrowthRate&&this.emitAlert(t,r.lastGrowthRate,a),r.lastGrowthRate=a}}getCumulativeRegret(t){return this.domains.get(t)?.cumulativeRegret??0}getRegretCurve(t){let e=this.domains.get(t);return e?[...e.points]:[]}getRegretGrowthRate(t){let e=this.domains.get(t);return e?this.classifyGrowthRate(e.points):"insufficient_data"}detectStagnation(t){let e=this.getRegretGrowthRate(t);return e==="linear"||e==="superlinear"}getHealthSummary(){let t=[];for(let[e,n]of this.domains){let r=this.classifyGrowthRate(n.points),i=this.computeLogLogSlope(n.points),a=this.computeRecentAvgRegret(n);t.push({domain:e,totalDecisions:n.decisionCount,cumulativeRegret:n.cumulativeRegret,growthRate:r,stagnating:r==="linear"||r==="superlinear",slope:i,recentAvgRegret:a})}return t.sort((e,n)=>e.domain.localeCompare(n.domain)),t}onAlert(t){this.alertCallbacks.push(t)}getAlerts(){return[...this.alerts]}getTrackedDomains(){return[...this.domains.keys()].sort()}getTotalDecisions(){let t=0;for(let e of this.domains.values())t+=e.decisionCount;return t}reset(t){t?this.domains.delete(t):(this.domains.clear(),this.alerts=[])}getOrCreateDomainState(t){let e=this.domains.get(t);return e||(e={points:[],cumulativeRegret:0,decisionCount:0,lastGrowthRate:"insufficient_data"},this.domains.set(t,e)),e}classifyGrowthRate(t){if(t.length<l)return"insufficient_data";let e=this.computeLogLogSlope(t);return e===void 0?"insufficient_data":e<R?"sublinear":e<=d?"linear":"superlinear"}computeLogLogSlope(t){if(t.length<l)return;let e=t.filter(i=>i.cumulativeRegret>0&&i.decisionCount>0);if(e.length<2)return;let n=e.map(i=>Math.log(i.decisionCount)),r=e.map(i=>Math.log(i.cumulativeRegret));return f(n,r)}computeRecentAvgRegret(t){if(t.points.length<2)return 0;let e=Math.min(this.recentWindow,t.points.length),n=t.points.slice(-e),r=n[0],i=n[n.length-1],a=i.cumulativeRegret-r.cumulativeRegret,u=i.decisionCount-r.decisionCount;return u<=0?0:a/u}emitAlert(t,e,n){let r={domain:t,previousRate:e,newRate:n,timestamp:Date.now(),message:`Domain "${t}" regret growth changed from ${e} to ${n}`};this.alerts.push(r),this.alerts.length>this.maxAlerts&&this.alerts.shift(),g.info("Regret growth rate transition",{domain:t,previousRate:e,newRate:n});for(let i of this.alertCallbacks)try{i(r)}catch(a){g.error("Alert callback error",a instanceof Error?a:void 0)}}};function b(o){return new c(o)}export{b as a};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.1");process.exit(0)}
2
+ import{a as h}from"./chunk-2K3QFLX2.js";import{e as m}from"./chunk-7FGSX4UD.js";h();var g=m.create("regret-tracker"),l=50,R=.9,d=1.1;function f(o,t){let e=o.length;if(e<2)return 0;let n=0,r=0,i=0,a=0;for(let s=0;s<e;s++)n+=o[s],r+=t[s],i+=o[s]*t[s],a+=o[s]*o[s];let u=e*a-n*n;return Math.abs(u)<1e-10?0:(e*i-n*r)/u}var c=class{domains=new Map;alertCallbacks=[];alerts=[];maxAlerts;recentWindow;constructor(t){this.maxAlerts=t?.maxAlerts??100,this.recentWindow=t?.recentWindow??20}recordDecision(t,e,n){let r=this.getOrCreateDomainState(t),i=Math.max(0,n-e);if(r.cumulativeRegret+=i,r.decisionCount++,r.points.push({decisionCount:r.decisionCount,cumulativeRegret:r.cumulativeRegret,timestamp:Date.now()}),r.decisionCount>=l){let a=this.classifyGrowthRate(r.points);r.lastGrowthRate!=="insufficient_data"&&a!==r.lastGrowthRate&&this.emitAlert(t,r.lastGrowthRate,a),r.lastGrowthRate=a}}getCumulativeRegret(t){return this.domains.get(t)?.cumulativeRegret??0}getRegretCurve(t){let e=this.domains.get(t);return e?[...e.points]:[]}getRegretGrowthRate(t){let e=this.domains.get(t);return e?this.classifyGrowthRate(e.points):"insufficient_data"}detectStagnation(t){let e=this.getRegretGrowthRate(t);return e==="linear"||e==="superlinear"}getHealthSummary(){let t=[];for(let[e,n]of this.domains){let r=this.classifyGrowthRate(n.points),i=this.computeLogLogSlope(n.points),a=this.computeRecentAvgRegret(n);t.push({domain:e,totalDecisions:n.decisionCount,cumulativeRegret:n.cumulativeRegret,growthRate:r,stagnating:r==="linear"||r==="superlinear",slope:i,recentAvgRegret:a})}return t.sort((e,n)=>e.domain.localeCompare(n.domain)),t}onAlert(t){this.alertCallbacks.push(t)}getAlerts(){return[...this.alerts]}getTrackedDomains(){return[...this.domains.keys()].sort()}getTotalDecisions(){let t=0;for(let e of this.domains.values())t+=e.decisionCount;return t}reset(t){t?this.domains.delete(t):(this.domains.clear(),this.alerts=[])}getOrCreateDomainState(t){let e=this.domains.get(t);return e||(e={points:[],cumulativeRegret:0,decisionCount:0,lastGrowthRate:"insufficient_data"},this.domains.set(t,e)),e}classifyGrowthRate(t){if(t.length<l)return"insufficient_data";let e=this.computeLogLogSlope(t);return e===void 0?"insufficient_data":e<R?"sublinear":e<=d?"linear":"superlinear"}computeLogLogSlope(t){if(t.length<l)return;let e=t.filter(i=>i.cumulativeRegret>0&&i.decisionCount>0);if(e.length<2)return;let n=e.map(i=>Math.log(i.decisionCount)),r=e.map(i=>Math.log(i.cumulativeRegret));return f(n,r)}computeRecentAvgRegret(t){if(t.points.length<2)return 0;let e=Math.min(this.recentWindow,t.points.length),n=t.points.slice(-e),r=n[0],i=n[n.length-1],a=i.cumulativeRegret-r.cumulativeRegret,u=i.decisionCount-r.decisionCount;return u<=0?0:a/u}emitAlert(t,e,n){let r={domain:t,previousRate:e,newRate:n,timestamp:Date.now(),message:`Domain "${t}" regret growth changed from ${e} to ${n}`};this.alerts.push(r),this.alerts.length>this.maxAlerts&&this.alerts.shift(),g.info("Regret growth rate transition",{domain:t,previousRate:e,newRate:n});for(let i of this.alertCallbacks)try{i(r)}catch(a){g.error("Alert callback error",a instanceof Error?a:void 0)}}};function b(o){return new c(o)}export{b as a};
@@ -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.14.8");process.exit(0)}
2
- import{b as l,d as y}from"./chunk-BITFGVZ4.js";y();import{copyFileSync as k,existsSync as c,readFileSync as u,writeFileSync as s}from"fs";function J(n,r){let e=typeof r=="string"?Buffer.from(r,"utf-8"):r;try{if(c(n)&&u(n).equals(e))return!1}catch{}return typeof r=="string"?s(n,r,"utf-8"):s(n,r),!0}function S(n,r){try{if(c(r)&&u(r).equals(u(n)))return!1}catch{}return k(n,r),!0}function E(n,r,e){try{if(c(n)){let t=o=>o.split(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.1");process.exit(0)}
2
+ import{b as l,d as y}from"./chunk-5C4UYXQL.js";y();import{copyFileSync as k,existsSync as c,readFileSync as u,writeFileSync as s}from"fs";function J(n,r){let e=typeof r=="string"?Buffer.from(r,"utf-8"):r;try{if(c(n)&&u(n).equals(e))return!1}catch{}return typeof r=="string"?s(n,r,"utf-8"):s(n,r),!0}function S(n,r){try{if(c(r)&&u(r).equals(u(n)))return!1}catch{}return k(n,r),!0}function E(n,r,e){try{if(c(n)){let t=o=>o.split(`
3
3
  `).filter(i=>!e.test(i)).join(`
4
4
  `);if(t(u(n,"utf-8"))===t(r))return!1}}catch{}return s(n,r,"utf-8"),!0}var I=/^\*Generated by AQE v3 init on [^*]+\*$/;function a(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function d(n){return JSON.stringify(n,(r,e)=>{if(!a(e))return e;let t={};for(let o of Object.keys(e).sort())t[o]=e[o];return t})}function w(n,r){return d(n)===d(r)}function f(n,r){let e=n;for(let t of r){if(!a(e))return;e=e[t]}return e}function g(n,r,e){let t=n;for(let i of r.slice(0,-1)){if(!a(t[i]))return;t=t[i]}let o=r[r.length-1];o in t&&(t[o]=e)}function p(n,r,e){if(!a(n))return!0;let t=JSON.parse(JSON.stringify(r));for(let o of e){let i=f(n,o);i!==void 0&&f(t,o)!==void 0&&g(t,o,i)}if(!w(n,t))return!0;for(let o of e){let i=f(n,o);i!==void 0&&f(r,o)!==void 0&&g(r,o,i)}return!1}function R(n){if(c(n))try{return l(u(n,"utf-8"))}catch{return}}function N(n,r,e=[]){let t=R(n);return t!==void 0&&!p(t,r,e)?!1:(s(n,JSON.stringify(r,null,2),"utf-8"),!0)}export{J as a,S as b,E as c,I as d,p as e,N 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.14.8");process.exit(0)}
2
- import{e as l,l as c}from"./chunk-KKXH25IH.js";import{a as i}from"./chunk-T4WQPE77.js";import{a as n,e as h}from"./chunk-HPVYJ6JH.js";h();var d=class extends c{config={name:"qe/tests/schedule",description:"Schedule and execute tests using phase-based pipeline with git-aware selection and flaky tracking. Runs tests in phases (unit, integration, e2e), selects affected tests from git changes, and tracks flaky tests.",domain:"test-execution",schema:this.buildSchema()};buildSchema(){return{type:"object",properties:{cwd:{type:"string",description:"Working directory for test execution (defaults to project root)"},gitRef:{type:"string",description:'Git ref to compare for affected test selection (e.g., "main", "HEAD~3")'},useGitAware:{type:"boolean",description:"Enable git-aware test selection to only run affected tests",default:!0},trackFlaky:{type:"boolean",description:"Enable flaky test tracking and quarantine",default:!0}}}}async execute(s,o){if(s.gitRef!==void 0){let a=i(s.gitRef,"gitRef");if(a)return{success:!1,error:a}}try{let{runTestPipeline:a}=await import("./test-scheduling-RJABJT2W.js"),u=await l(o),t=await a({cwd:s.cwd||process.cwd(),memory:u,baseRef:s.gitRef,flakyHistoryPath:s.trackFlaky!==!1?".agentic-qe/flaky-history.json":void 0,runAllTests:s.useGitAware===!1}),f=t.phaseResults.reduce((e,r)=>e+r.totalTests,0),p=t.phaseResults.reduce((e,r)=>e+r.passed,0),g=t.phaseResults.reduce((e,r)=>e+r.failed,0);return{success:!0,data:{pipelineId:o.requestId,phases:t.phaseResults.map(e=>({phaseId:e.phaseId,phaseName:e.phaseName,totalTests:e.totalTests,passed:e.passed,failed:e.failed,passRate:e.passRate,durationMs:e.durationMs})),gitAware:{enabled:!t.ranAllTests,selectedTests:t.selectedTests.length,gitRef:s.gitRef},flakyTracking:{enabled:s.trackFlaky!==!1},totalDuration:t.totalDurationMs,ranAllTests:t.ranAllTests,summary:`Executed ${t.phaseResults.length} phases, ${f} tests (${p} passed, ${g} failed) in ${t.totalDurationMs}ms`}}}catch(a){return{success:!1,error:n(a)}}}};export{d as a};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.1");process.exit(0)}
2
+ import{e as l,l as c}from"./chunk-PBWR2SKH.js";import{a as i}from"./chunk-MEOAKMKF.js";import{a as n,e as h}from"./chunk-ARWSPV2C.js";h();var d=class extends c{config={name:"qe/tests/schedule",description:"Schedule and execute tests using phase-based pipeline with git-aware selection and flaky tracking. Runs tests in phases (unit, integration, e2e), selects affected tests from git changes, and tracks flaky tests.",domain:"test-execution",schema:this.buildSchema()};buildSchema(){return{type:"object",properties:{cwd:{type:"string",description:"Working directory for test execution (defaults to project root)"},gitRef:{type:"string",description:'Git ref to compare for affected test selection (e.g., "main", "HEAD~3")'},useGitAware:{type:"boolean",description:"Enable git-aware test selection to only run affected tests",default:!0},trackFlaky:{type:"boolean",description:"Enable flaky test tracking and quarantine",default:!0}}}}async execute(s,o){if(s.gitRef!==void 0){let a=i(s.gitRef,"gitRef");if(a)return{success:!1,error:a}}try{let{runTestPipeline:a}=await import("./test-scheduling-FKYX4OLF.js"),u=await l(o),t=await a({cwd:s.cwd||process.cwd(),memory:u,baseRef:s.gitRef,flakyHistoryPath:s.trackFlaky!==!1?".agentic-qe/flaky-history.json":void 0,runAllTests:s.useGitAware===!1}),f=t.phaseResults.reduce((e,r)=>e+r.totalTests,0),p=t.phaseResults.reduce((e,r)=>e+r.passed,0),g=t.phaseResults.reduce((e,r)=>e+r.failed,0);return{success:!0,data:{pipelineId:o.requestId,phases:t.phaseResults.map(e=>({phaseId:e.phaseId,phaseName:e.phaseName,totalTests:e.totalTests,passed:e.passed,failed:e.failed,passRate:e.passRate,durationMs:e.durationMs})),gitAware:{enabled:!t.ranAllTests,selectedTests:t.selectedTests.length,gitRef:s.gitRef},flakyTracking:{enabled:s.trackFlaky!==!1},totalDuration:t.totalDurationMs,ranAllTests:t.ranAllTests,summary:`Executed ${t.phaseResults.length} phases, ${f} tests (${p} passed, ${g} failed) in ${t.totalDurationMs}ms`}}}catch(a){return{success:!1,error:n(a)}}}};export{d as a};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.8");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.15.1");process.exit(0)}
2
2
  var i=class{s0;s1;s2;s3;constructor(s){this.s0=this.splitmix32(s),this.s1=this.splitmix32(this.s0),this.s2=this.splitmix32(this.s1),this.s3=this.splitmix32(this.s2)}splitmix32(s){return s=s+2654435769|0,s=Math.imul(s^s>>>16,2246822507),s=Math.imul(s^s>>>13,3266489909),(s^s>>>16)>>>0}next(){let s=this.s3,t=this.s0;return this.s3=this.s2,this.s2=this.s1,this.s1=t,t^=t<<11,t^=t>>>8,this.s0=t^s^s>>>19,this.s0>>>0}nextFloat(){return this.next()/4294967296}nextGaussian(){let s=this.nextFloat()||1e-10,t=this.nextFloat();return Math.sqrt(-2*Math.log(s))*Math.cos(2*Math.PI*t)}};export{i as a};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.8");process.exit(0)}
2
- import{b as P,c as q,d as R,e as D,g as O,h as x,i as j,j as $,k as L,l as N,m as Q,n as M}from"./chunk-775WGWLL.js";import{b as v,d as T}from"./chunk-BITFGVZ4.js";import{a as y,e as A}from"./chunk-HPVYJ6JH.js";import{a as _,b as re}from"./chunk-SPS472C5.js";T();import{existsSync as f,mkdirSync as U,writeFileSync as b,readFileSync as C,copyFileSync as se}from"fs";import{join as p,dirname as ae}from"path";async function z(t,e){if(!e.hooks.claudeCode)return!1;let n=p(t,".claude");f(n)||U(n,{recursive:!0});let r=p(n,"settings.json"),s={};if(f(r))try{let m=C(r,"utf-8");s=v(m)}catch{s={}}let i={PreToolUse:[{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" guard --file "$TOOL_INPUT_file_path" --json',timeout:3,continueOnError:!0}]},{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" pre-edit --file "$TOOL_INPUT_file_path" --json',timeout:5,continueOnError:!0}]},{matcher:"^Bash$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" pre-command --command "$TOOL_INPUT_command" --json',timeout:3,continueOnError:!0}]},{matcher:"^Task$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" pre-task --description "$TOOL_INPUT_prompt" --json',timeout:5,continueOnError:!0}]}],PostToolUse:[{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" post-edit --file "$TOOL_INPUT_file_path" --success --json',timeout:5,continueOnError:!0}]},{matcher:"^Bash$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" post-command --command "$TOOL_INPUT_command" --success true --json',timeout:5,continueOnError:!0}]},{matcher:"^Task$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" post-task --task-id "$TOOL_RESULT_agent_id" --agent "$TOOL_INPUT_subagent_type" --success true --description "$TOOL_INPUT_prompt" --json',timeout:5,continueOnError:!0}]}],UserPromptSubmit:[{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" route --json',timeout:5,continueOnError:!0}]}],SessionStart:[{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" session-start --session-id "$SESSION_ID" --json',timeout:10,continueOnError:!0}]}],Stop:[{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" session-end --save-state --json',timeout:5,continueOnError:!0}]},{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" post-route --success true --json',timeout:5,continueOnError:!0}]}]},u=s.hooks||{};s.hooks=O(u,i);let l=s.env;s.env=x(l,j(e));let d=L(e,t);$(s,d);let a=s.enabledMcpjsonServers||[];return a=a.filter(m=>m!=="aqe"),a.includes("agentic-qe")||a.push("agentic-qe"),s.enabledMcpjsonServers=a,D(r),b(r,JSON.stringify(s,null,2),"utf-8"),await oe(t),!0}async function oe(t){let e=p(t,".claude","hooks");f(e)||U(e,{recursive:!0});let n=p(e,"cross-phase-memory.yaml");if(f(n))return;let r=[p(ae(import.meta.url.replace("file://","")),"..","..","assets","hooks","cross-phase-memory.yaml"),p(process.cwd(),"assets","hooks","cross-phase-memory.yaml"),p(process.cwd(),"v3","assets","hooks","cross-phase-memory.yaml")];for(let i of r)try{if(f(i)){se(i,n),console.log(" \u2713 Cross-phase memory hooks installed");return}}catch{}b(n,`# Cross-Phase Memory Hooks Configuration
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.15.1");process.exit(0)}
2
+ import{b as P,c as q,d as R,e as D,g as O,h as x,i as j,j as $,k as L,l as N,m as Q,n as M}from"./chunk-35XRY6ZW.js";import{b as v,d as T}from"./chunk-5C4UYXQL.js";import{a as y,e as A}from"./chunk-ARWSPV2C.js";import{a as _,b as re}from"./chunk-JW2HNT3J.js";T();import{existsSync as f,mkdirSync as U,writeFileSync as b,readFileSync as C,copyFileSync as se}from"fs";import{join as p,dirname as ae}from"path";async function z(t,e){if(!e.hooks.claudeCode)return!1;let n=p(t,".claude");f(n)||U(n,{recursive:!0});let r=p(n,"settings.json"),s={};if(f(r))try{let m=C(r,"utf-8");s=v(m)}catch{s={}}let i={PreToolUse:[{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" guard --file "$TOOL_INPUT_file_path" --json',timeout:3,continueOnError:!0}]},{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" pre-edit --file "$TOOL_INPUT_file_path" --json',timeout:5,continueOnError:!0}]},{matcher:"^Bash$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" pre-command --command "$TOOL_INPUT_command" --json',timeout:3,continueOnError:!0}]},{matcher:"^Task$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" pre-task --description "$TOOL_INPUT_prompt" --json',timeout:5,continueOnError:!0}]}],PostToolUse:[{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" post-edit --file "$TOOL_INPUT_file_path" --success --json',timeout:5,continueOnError:!0}]},{matcher:"^Bash$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" post-command --command "$TOOL_INPUT_command" --success true --json',timeout:5,continueOnError:!0}]},{matcher:"^Task$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" post-task --task-id "$TOOL_RESULT_agent_id" --agent "$TOOL_INPUT_subagent_type" --success true --description "$TOOL_INPUT_prompt" --json',timeout:5,continueOnError:!0}]}],UserPromptSubmit:[{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" route --json',timeout:5,continueOnError:!0}]}],SessionStart:[{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" session-start --session-id "$SESSION_ID" --json',timeout:10,continueOnError:!0}]}],Stop:[{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" session-end --save-state --json',timeout:5,continueOnError:!0}]},{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" post-route --success true --json',timeout:5,continueOnError:!0}]}]},u=s.hooks||{};s.hooks=O(u,i);let l=s.env;s.env=x(l,j(e));let d=L(e,t);$(s,d);let a=s.enabledMcpjsonServers||[];return a=a.filter(m=>m!=="aqe"),a.includes("agentic-qe")||a.push("agentic-qe"),s.enabledMcpjsonServers=a,D(r),b(r,JSON.stringify(s,null,2),"utf-8"),await oe(t),!0}async function oe(t){let e=p(t,".claude","hooks");f(e)||U(e,{recursive:!0});let n=p(e,"cross-phase-memory.yaml");if(f(n))return;let r=[p(ae(import.meta.url.replace("file://","")),"..","..","assets","hooks","cross-phase-memory.yaml"),p(process.cwd(),"assets","hooks","cross-phase-memory.yaml"),p(process.cwd(),"v3","assets","hooks","cross-phase-memory.yaml")];for(let i of r)try{if(f(i)){se(i,n),console.log(" \u2713 Cross-phase memory hooks installed");return}}catch{}b(n,`# Cross-Phase Memory Hooks Configuration
3
3
  # Generated by aqe init
4
4
  # See: https://github.com/anthropics/agentic-qe/docs/cross-phase-memory.md
5
5
 
@@ -276,7 +276,7 @@ aqe init --auto
276
276
  `).run("aqe_version",JSON.stringify(e),i),s.prepare(`
277
277
  INSERT OR REPLACE INTO kv_store (key, namespace, value, created_at)
278
278
  VALUES (?, '_system', ?, ?)
279
- `).run("init_timestamp",JSON.stringify(new Date().toISOString()),i),s.close(),console.log(` \u2713 Version ${e} written to memory.db`),!0}catch(i){return s.close(),console.warn(` \u26A0 Could not write version: ${y(i)}`),!1}}catch(r){return console.warn(` \u26A0 Could not open memory.db: ${y(r)}`),!1}}async function V(t){let e=null;try{e=(await import("./better-sqlite3-2JG5K6XT.js")).default}catch{throw new Error(`SQLite persistence REQUIRED but better-sqlite3 is not installed.
279
+ `).run("init_timestamp",JSON.stringify(new Date().toISOString()),i),s.close(),console.log(` \u2713 Version ${e} written to memory.db`),!0}catch(i){return s.close(),console.warn(` \u26A0 Could not write version: ${y(i)}`),!1}}catch(r){return console.warn(` \u26A0 Could not open memory.db: ${y(r)}`),!1}}async function V(t){let e=null;try{e=(await import("./better-sqlite3-YERQ5DOL.js")).default}catch{throw new Error(`SQLite persistence REQUIRED but better-sqlite3 is not installed.
280
280
  Install it with: npm install better-sqlite3
281
281
  If you see native compilation errors, ensure build tools are installed:
282
282
  - macOS: xcode-select --install
@@ -302,7 +302,7 @@ Database path: ${r}
302
302
  Ensure the directory is writable and has sufficient disk space.`)}}async function J(t){let e=o(t,".agentic-qe","memory.db");if(!h(e))return!1;try{let n=_(e),r=n.prepare(`
303
303
  SELECT COUNT(*) as count FROM kv_store
304
304
  WHERE namespace = 'code-intelligence:kg'
305
- `).get();return n.close(),r.count>0}catch{return!1}}async function B(t){try{let{KnowledgeGraphService:e}=await import("./knowledge-graph-KFMTTUR5.js"),{InMemoryBackend:n}=await import("./memory-backend-KFJDDPEZ.js"),r=new n;await r.initialize();let s=new e(r,{namespace:"code-intelligence:kg",enableVectorEmbeddings:!0}),{glob:i}=await import("tinyglobby"),u=await i(["**/*.ts","**/*.tsx","**/*.js","**/*.jsx","**/*.py"],{cwd:t,ignore:["node_modules/**","dist/**","coverage/**",".agentic-qe/**"],expandDirectories:!1}),l=await s.index({paths:u.map(d=>o(t,d)),incremental:!1,includeTests:!0});return s.destroy(),l.success?{status:"indexed",entries:l.value.nodesCreated+l.value.edgesCreated}:{status:"error",entries:0}}catch(e){return console.warn("Code intelligence scan warning:",y(e)),{status:"skipped",entries:0}}}async function H(t){let e=o(t,".agentic-qe","memory.db");try{let n=_(e),r=n.prepare(`
305
+ `).get();return n.close(),r.count>0}catch{return!1}}async function B(t){try{let{KnowledgeGraphService:e}=await import("./knowledge-graph-A3WSMQ6U.js"),{InMemoryBackend:n}=await import("./memory-backend-BKGLI2RF.js"),r=new n;await r.initialize();let s=new e(r,{namespace:"code-intelligence:kg",enableVectorEmbeddings:!0}),{glob:i}=await import("tinyglobby"),u=await i(["**/*.ts","**/*.tsx","**/*.js","**/*.jsx","**/*.py"],{cwd:t,ignore:["node_modules/**","dist/**","coverage/**",".agentic-qe/**"],expandDirectories:!1}),l=await s.index({paths:u.map(d=>o(t,d)),incremental:!1,includeTests:!0});return s.destroy(),l.success?{status:"indexed",entries:l.value.nodesCreated+l.value.edgesCreated}:{status:"error",entries:0}}catch(e){return console.warn("Code intelligence scan warning:",y(e)),{status:"skipped",entries:0}}}async function H(t){let e=o(t,".agentic-qe","memory.db");try{let n=_(e),r=n.prepare(`
306
306
  SELECT COUNT(*) as count FROM kv_store
307
307
  WHERE namespace LIKE 'code-intelligence:kg%'
308
308
  `).get();return n.close(),r.count}catch{return 0}}async function X(t,e,n){if(!e.learning.enabled)return 0;let r=o(t,".agentic-qe","data");h(r)||k(r,{recursive:!0});let s=o(r,"hnsw");h(s)||k(s,{recursive:!0});let i=o(r,"learning-config.json"),u={embeddingModel:e.learning.embeddingModel,hnswConfig:e.learning.hnswConfig,qualityThreshold:e.learning.qualityThreshold,promotionThreshold:e.learning.promotionThreshold,databasePath:o(r,"memory.db"),hnswIndexPath:o(s,"index.bin"),initialized:new Date().toISOString()};E(i,JSON.stringify(u,null,2),"utf-8");let l=0;if(e.learning.pretrainedPatterns&&n){let d=n,a=new Map;for(let g of d.patterns){let c=g.domain||"general";a.has(c)||a.set(c,[]),a.get(c).push(g)}let m=o(r,"pretrained-index.json"),S={version:d.version,totalPatterns:d.statistics.totalPatterns,domains:Array.from(a.entries()).map(([g,c])=>({name:g,patternCount:c.length})),loadedAt:new Date().toISOString()};E(m,JSON.stringify(S,null,2),"utf-8");for(let[g,c]of a){let w=o(r,"patterns",g);h(w)||k(w,{recursive:!0});let ne=o(w,"patterns.json");E(ne,JSON.stringify(c,null,2),"utf-8"),l+=c.length}return l}return 0}async function K(t,e){if(!e.workers.daemonAutoStart||e.workers.enabled.length===0)return 0;let n=o(t,".agentic-qe","workers");h(n)||k(n,{recursive:!0});let r={},s={"pattern-consolidator":6e4,"coverage-gap-scanner":3e5,"flaky-test-detector":6e5,"routing-accuracy-monitor":12e4};for(let a of e.workers.enabled)r[a]={name:a,enabled:!0,interval:e.workers.intervals[a]||s[a]||6e4,lastRun:null,status:"pending"};let i=o(n,"registry.json"),u={version:e.version,maxConcurrent:e.workers.maxConcurrent,workers:r,createdAt:new Date().toISOString(),daemonPid:null};E(i,JSON.stringify(u,null,2),"utf-8");for(let a of e.workers.enabled){let m=o(n,`${a}.json`),S={name:a,enabled:!0,interval:e.workers.intervals[a]||s[a]||6e4,projectRoot:t,dataDir:o(t,".agentic-qe","data"),createdAt:new Date().toISOString()};E(m,JSON.stringify(S,null,2),"utf-8")}let l=o(n,"start-daemon.cjs");return E(l,`#!/usr/bin/env node
@@ -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.14.8");process.exit(0)}
2
- import{a as l,d as b}from"./chunk-SVP3BP52.js";import{a as d,b as g}from"./chunk-GA63ESNT.js";import{a as f}from"./chunk-U64QORFO.js";import{e as p}from"./chunk-J5HTQHJK.js";f();g();b();var v={dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine",namespace:"coverage-hnsw",maxElements:1e5},S=p.create("coverage-analysis/hnsw-index"),u=class{constructor(e,t={}){this.memory=e;this.config={...v,...t},this.stats={vectorCount:0,searchOperations:0,insertOperations:0}}memory;config;stats;searchLatencies=[];backendType="ruvector-gnn";adapter=null;initialized=!1;metadataStore=new Map;async initialize(){if(this.initialized)return;let e=this.config.metric==="cosine"?"cosine":"euclidean",t=`coverage-${this.config.namespace}`;d.close(t),this.adapter=d.create(t,{dimensions:this.config.dimensions,M:this.config.M,efConstruction:this.config.efConstruction,efSearch:this.config.efSearch,metric:e}),S.info(`HnswAdapter initialized: dimension=${this.config.dimensions}, metric=${this.config.metric}, M=${this.config.M} (unified backend via ADR-071)`),this.initialized=!0}isNativeAvailable(){return this.initialized&&this.adapter!==null}getBackendType(){return this.backendType}isRuvectorAvailable(){return this.initialized&&this.adapter!==null&&this.adapter.isRuvectorAvailable()}async insert(e,t,a){this.initialized||await this.initialize(),t=this.validateVector(t),this.adapter.addByStringId(e,t),a&&this.metadataStore.set(e,a),this.stats.insertOperations++,this.stats.vectorCount=this.adapter.size()}async search(e,t){this.initialized||await this.initialize(),e=this.validateVector(e);let a=performance.now(),n=[];this.adapter.size()>0&&(n=this.adapter.searchByArray(e,t).map(({id:i,score:o})=>({key:i,score:o,distance:1-o,metadata:this.metadataStore.get(i)})));let s=performance.now()-a;return this.recordSearchLatency(s),this.stats.searchOperations++,n}async batchInsert(e){this.initialized||await this.initialize();let t=100;for(let a=0;a<e.length;a+=t){let n=e.slice(a,a+t);await Promise.all(n.map(r=>this.insert(r.key,r.vector,r.metadata)))}}async delete(e){if(!this.adapter)return!1;let t=this.adapter.removeByStringId(e);if(t){this.metadataStore.delete(e);let a=this.buildKey(e);await this.memory.delete(a),this.stats.vectorCount=this.adapter.size()}return t}async getStats(){return{nativeHNSW:this.initialized&&this.adapter!==null,backendType:this.backendType,vectorCount:this.stats.vectorCount,indexSizeBytes:this.stats.vectorCount*this.config.dimensions*4,avgSearchLatencyMs:this.calculateAvgLatency(),p95SearchLatencyMs:this.calculatePercentileLatency(95),p99SearchLatencyMs:this.calculatePercentileLatency(99),searchOperations:this.stats.searchOperations,insertOperations:this.stats.insertOperations}}async clear(){this.metadataStore.clear(),this.adapter&&this.adapter.clear(),this.stats.vectorCount=0,this.searchLatencies=[]}validateVector(e){if(e.length!==this.config.dimensions)return this.resizeVector(e,this.config.dimensions);for(let t=0;t<e.length;t++)if(!Number.isFinite(e[t]))throw new Error(`Invalid vector value at index ${t}: ${e[t]}`);return e}resizeVector(e,t){if(e.length===t)return e;if(e.length>t){let n=new Array(t).fill(0),r=e.length/t;for(let s=0;s<t;s++){let h=Math.floor(s*r),i=Math.floor((s+1)*r),o=0;for(let m=h;m<i;m++)o+=e[m];n[s]=o/(i-h)}return n}let a=new Array(t).fill(0);for(let n=0;n<e.length;n++)a[n]=e[n];return a}buildKey(e){return`${this.config.namespace}:${e}`}recordSearchLatency(e){this.searchLatencies.push(e);let t=1e3;this.searchLatencies.length>t&&(this.searchLatencies=this.searchLatencies.slice(-t))}calculateAvgLatency(){return this.searchLatencies.length===0?0:this.searchLatencies.reduce((t,a)=>t+a,0)/this.searchLatencies.length}calculatePercentileLatency(e){if(this.searchLatencies.length===0)return 0;let t=[...this.searchLatencies].sort((n,r)=>n-r),a=Math.ceil(e/100*t.length)-1;return t[Math.max(0,a)]}setEfSearch(e){this.config.efSearch=e}};function C(c,e){return new u(c,e)}async function H(c,e=1e4,t=1e3){let n=performance.now();for(let i=0;i<e;i++){let o=Array.from({length:384},()=>l());await c.insert(`bench-${i}`,o)}let r=performance.now()-n,s=performance.now();for(let i=0;i<t;i++){let o=Array.from({length:384},()=>l());await c.search(o,10)}let h=performance.now()-s;return{insertTimeMs:r,searchTimeMs:h,avgSearchLatencyMs:h/t,isNative:c.isNativeAvailable(),backendType:c.getBackendType()}}export{v as a,u as b,C as c,H as d};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.1");process.exit(0)}
2
+ import{a as l,d as b}from"./chunk-UE33MZOC.js";import{a as d,b as g}from"./chunk-WQZR6DS6.js";import{a as f}from"./chunk-2K3QFLX2.js";import{e as p}from"./chunk-7FGSX4UD.js";f();g();b();var v={dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine",namespace:"coverage-hnsw",maxElements:1e5},S=p.create("coverage-analysis/hnsw-index"),u=class{constructor(e,t={}){this.memory=e;this.config={...v,...t},this.stats={vectorCount:0,searchOperations:0,insertOperations:0}}memory;config;stats;searchLatencies=[];backendType="ruvector-gnn";adapter=null;initialized=!1;metadataStore=new Map;async initialize(){if(this.initialized)return;let e=this.config.metric==="cosine"?"cosine":"euclidean",t=`coverage-${this.config.namespace}`;d.close(t),this.adapter=d.create(t,{dimensions:this.config.dimensions,M:this.config.M,efConstruction:this.config.efConstruction,efSearch:this.config.efSearch,metric:e}),S.info(`HnswAdapter initialized: dimension=${this.config.dimensions}, metric=${this.config.metric}, M=${this.config.M} (unified backend via ADR-071)`),this.initialized=!0}isNativeAvailable(){return this.initialized&&this.adapter!==null}getBackendType(){return this.backendType}isRuvectorAvailable(){return this.initialized&&this.adapter!==null&&this.adapter.isRuvectorAvailable()}async insert(e,t,a){this.initialized||await this.initialize(),t=this.validateVector(t),this.adapter.addByStringId(e,t),a&&this.metadataStore.set(e,a),this.stats.insertOperations++,this.stats.vectorCount=this.adapter.size()}async search(e,t){this.initialized||await this.initialize(),e=this.validateVector(e);let a=performance.now(),n=[];this.adapter.size()>0&&(n=this.adapter.searchByArray(e,t).map(({id:i,score:o})=>({key:i,score:o,distance:1-o,metadata:this.metadataStore.get(i)})));let s=performance.now()-a;return this.recordSearchLatency(s),this.stats.searchOperations++,n}async batchInsert(e){this.initialized||await this.initialize();let t=100;for(let a=0;a<e.length;a+=t){let n=e.slice(a,a+t);await Promise.all(n.map(r=>this.insert(r.key,r.vector,r.metadata)))}}async delete(e){if(!this.adapter)return!1;let t=this.adapter.removeByStringId(e);if(t){this.metadataStore.delete(e);let a=this.buildKey(e);await this.memory.delete(a),this.stats.vectorCount=this.adapter.size()}return t}async getStats(){return{nativeHNSW:this.initialized&&this.adapter!==null,backendType:this.backendType,vectorCount:this.stats.vectorCount,indexSizeBytes:this.stats.vectorCount*this.config.dimensions*4,avgSearchLatencyMs:this.calculateAvgLatency(),p95SearchLatencyMs:this.calculatePercentileLatency(95),p99SearchLatencyMs:this.calculatePercentileLatency(99),searchOperations:this.stats.searchOperations,insertOperations:this.stats.insertOperations}}async clear(){this.metadataStore.clear(),this.adapter&&this.adapter.clear(),this.stats.vectorCount=0,this.searchLatencies=[]}validateVector(e){if(e.length!==this.config.dimensions)return this.resizeVector(e,this.config.dimensions);for(let t=0;t<e.length;t++)if(!Number.isFinite(e[t]))throw new Error(`Invalid vector value at index ${t}: ${e[t]}`);return e}resizeVector(e,t){if(e.length===t)return e;if(e.length>t){let n=new Array(t).fill(0),r=e.length/t;for(let s=0;s<t;s++){let h=Math.floor(s*r),i=Math.floor((s+1)*r),o=0;for(let m=h;m<i;m++)o+=e[m];n[s]=o/(i-h)}return n}let a=new Array(t).fill(0);for(let n=0;n<e.length;n++)a[n]=e[n];return a}buildKey(e){return`${this.config.namespace}:${e}`}recordSearchLatency(e){this.searchLatencies.push(e);let t=1e3;this.searchLatencies.length>t&&(this.searchLatencies=this.searchLatencies.slice(-t))}calculateAvgLatency(){return this.searchLatencies.length===0?0:this.searchLatencies.reduce((t,a)=>t+a,0)/this.searchLatencies.length}calculatePercentileLatency(e){if(this.searchLatencies.length===0)return 0;let t=[...this.searchLatencies].sort((n,r)=>n-r),a=Math.ceil(e/100*t.length)-1;return t[Math.max(0,a)]}setEfSearch(e){this.config.efSearch=e}};function C(c,e){return new u(c,e)}async function H(c,e=1e4,t=1e3){let n=performance.now();for(let i=0;i<e;i++){let o=Array.from({length:384},()=>l());await c.insert(`bench-${i}`,o)}let r=performance.now()-n,s=performance.now();for(let i=0;i<t;i++){let o=Array.from({length:384},()=>l());await c.search(o,10)}let h=performance.now()-s;return{insertTimeMs:r,searchTimeMs:h,avgSearchLatencyMs:h/t,isNative:c.isNativeAvailable(),backendType:c.getBackendType()}}export{v as a,u as b,C as c,H as d};