agentic-qe 3.15.16 → 3.15.17

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 (415) hide show
  1. package/.claude/skills/skills-manifest.json +1 -1
  2. package/CHANGELOG.md +78 -0
  3. package/assets/skills/skills-manifest.json +1 -1
  4. package/dist/cli/bundle.js +6 -6
  5. package/dist/cli/chunks/adapter-OMILP6KH.js +2 -0
  6. package/dist/cli/chunks/{agent-booster-wasm-45NWEKVS.js → agent-booster-wasm-6BUOFQZA.js} +2 -2
  7. package/dist/cli/chunks/{agent-handler-LVHMYFEF.js → agent-handler-HPDK3JI3.js} +2 -2
  8. package/dist/cli/chunks/{agent-memory-branch-YDWOJFEQ.js → agent-memory-branch-5QKUTWK5.js} +2 -2
  9. package/dist/cli/chunks/aqe-learning-engine-OXH5CCOS.js +2 -0
  10. package/dist/cli/chunks/{arena-CZKHXDDS.js → arena-7OKPMNHD.js} +2 -2
  11. package/dist/cli/chunks/{arena-ELDZH3CZ.js → arena-HZ35LESR.js} +4 -4
  12. package/dist/cli/chunks/{audit-5MT4T47Z.js → audit-XI575SVK.js} +3 -3
  13. package/dist/cli/chunks/base-MAK2BLTG.js +2 -0
  14. package/dist/cli/chunks/{better-sqlite3-6TGYPC2B.js → better-sqlite3-YO5X7ZJS.js} +2 -2
  15. package/dist/cli/chunks/{brain-handler-HQWZFO52.js → brain-handler-GCQZFZGQ.js} +3 -3
  16. package/dist/cli/chunks/{branch-enumerator-WVILM4SO.js → branch-enumerator-N6G44UU2.js} +2 -2
  17. package/dist/cli/chunks/{browser-RX5ALU3H.js → browser-EVKPTLOI.js} +2 -2
  18. package/dist/cli/chunks/browser-workflow-IR3VF2TL.js +2 -0
  19. package/dist/cli/chunks/{chunk-F742SZAX.js → chunk-2EQK7B5L.js} +2 -2
  20. package/dist/cli/chunks/{chunk-5NNNEWLS.js → chunk-2PCEMDIX.js} +67 -65
  21. package/dist/cli/chunks/{chunk-FBDVGRSC.js → chunk-2UUZCQSD.js} +7 -7
  22. package/dist/cli/chunks/{chunk-AG2EWGXS.js → chunk-2YWYW7NU.js} +2 -2
  23. package/dist/cli/chunks/{chunk-4LQFBY5L.js → chunk-45223KK6.js} +3 -3
  24. package/dist/cli/chunks/chunk-4EJLHNER.js +12 -0
  25. package/dist/cli/chunks/{chunk-KQYJ4VQ5.js → chunk-4L6WX5KC.js} +1 -1
  26. package/dist/cli/chunks/{chunk-KVF4NXGQ.js → chunk-4NKZU2JZ.js} +2 -2
  27. package/dist/cli/chunks/{chunk-YRAX7SFJ.js → chunk-4UKTIQDT.js} +2 -2
  28. package/dist/cli/chunks/{chunk-YTHTQPWR.js → chunk-4YM45Z5B.js} +1 -1
  29. package/dist/cli/chunks/{chunk-XIIQ5QTT.js → chunk-5FSPELOG.js} +2 -2
  30. package/dist/cli/chunks/{chunk-LKTTUHLF.js → chunk-5WATBVU6.js} +2 -2
  31. package/dist/cli/chunks/{chunk-SR52XP5F.js → chunk-5WYZVSL2.js} +1 -1
  32. package/dist/cli/chunks/{chunk-GQ6TUIKY.js → chunk-6LSZCEW2.js} +1 -1
  33. package/dist/cli/chunks/{chunk-NDJ7P2EP.js → chunk-6V6BD6PH.js} +1 -1
  34. package/dist/cli/chunks/{chunk-63GMRQ25.js → chunk-74MDUIAZ.js} +1 -1
  35. package/dist/cli/chunks/{chunk-4D4DENG6.js → chunk-776K4ZLE.js} +2 -2
  36. package/dist/cli/chunks/{chunk-ZJH5MU2I.js → chunk-7BSOO3CY.js} +2 -2
  37. package/dist/cli/chunks/{chunk-IOQ6ZQ5W.js → chunk-7SNSI4VY.js} +1 -1
  38. package/dist/cli/chunks/{chunk-LRSX2FJM.js → chunk-A4BVDYIL.js} +1 -1
  39. package/dist/cli/chunks/{chunk-SASBO5Y5.js → chunk-AGCS5GSO.js} +2 -2
  40. package/dist/cli/chunks/{chunk-GAHNO6JJ.js → chunk-AVHYJ3XP.js} +2 -2
  41. package/dist/cli/chunks/{chunk-CGGUM2YJ.js → chunk-BE7ZHM34.js} +2 -2
  42. package/dist/cli/chunks/{chunk-7TE5ONQQ.js → chunk-BHQ2DLJU.js} +1 -1
  43. package/dist/cli/chunks/{chunk-IESR7TNB.js → chunk-BKHEQIRZ.js} +2 -2
  44. package/dist/cli/chunks/{chunk-J4ELZNLY.js → chunk-BSIWI4ES.js} +2 -2
  45. package/dist/cli/chunks/{chunk-NVEWF4JV.js → chunk-C7QLLMYI.js} +1 -1
  46. package/dist/cli/chunks/{chunk-V5NHZV7S.js → chunk-CMN7PU2H.js} +2 -2
  47. package/dist/cli/chunks/{chunk-PPUZWYUG.js → chunk-COTQ44YO.js} +2 -2
  48. package/dist/cli/chunks/{chunk-5V3TI2LG.js → chunk-CQER6IJ5.js} +1 -1
  49. package/dist/cli/chunks/{chunk-SI6DPU5D.js → chunk-CVPXHDQU.js} +1 -1
  50. package/dist/cli/chunks/{chunk-6ZBXSOX6.js → chunk-CVYPMGUM.js} +2 -2
  51. package/dist/cli/chunks/{chunk-DXD6K2ZP.js → chunk-CXCMATZ6.js} +2 -2
  52. package/dist/cli/chunks/{chunk-PF7RBAYL.js → chunk-D75GLKEL.js} +2 -2
  53. package/dist/cli/chunks/chunk-DCDSN67A.js +2 -0
  54. package/dist/cli/chunks/{chunk-MAFQV4U4.js → chunk-DHKSPOUQ.js} +2 -2
  55. package/dist/cli/chunks/{chunk-RJIEG3NA.js → chunk-DJDVD6RM.js} +2 -2
  56. package/dist/cli/chunks/{chunk-GFWHUQSF.js → chunk-DNVRTJKB.js} +2 -2
  57. package/dist/cli/chunks/{chunk-G5RHFBAY.js → chunk-DS5IFRY6.js} +2 -2
  58. package/dist/cli/chunks/{chunk-BEKDKVQT.js → chunk-E7XIMOKW.js} +2 -2
  59. package/dist/cli/chunks/{chunk-5JZRZI4S.js → chunk-ECKHDHR2.js} +2 -2
  60. package/dist/cli/chunks/chunk-EPVPXHL7.js +2 -0
  61. package/dist/cli/chunks/{chunk-HVRRLYX6.js → chunk-ERYADKMZ.js} +2 -2
  62. package/dist/cli/chunks/{chunk-SUDMM5SO.js → chunk-EUWG2JG4.js} +2 -2
  63. package/dist/cli/chunks/{chunk-VSIKHWZ4.js → chunk-FAQ24UHB.js} +3 -3
  64. package/dist/cli/chunks/{chunk-YNMJEDN5.js → chunk-FBBPRVNF.js} +2 -2
  65. package/dist/cli/chunks/{chunk-72XSEQMW.js → chunk-FBSBXCZS.js} +2 -2
  66. package/dist/cli/chunks/{chunk-J7I6PABJ.js → chunk-G2X3OLMN.js} +2 -2
  67. package/dist/cli/chunks/{chunk-YU2BDRSD.js → chunk-GG7PMTHD.js} +1 -1
  68. package/dist/cli/chunks/{chunk-HLUXXCHF.js → chunk-GN6OE3JT.js} +1 -1
  69. package/dist/cli/chunks/{chunk-AGRV5B3T.js → chunk-GPPTRKEM.js} +2 -2
  70. package/dist/cli/chunks/{chunk-ZQ2XW3IP.js → chunk-H2LHWZRE.js} +2 -2
  71. package/dist/cli/chunks/{chunk-6DPYNAOK.js → chunk-HAQJFUAQ.js} +2 -2
  72. package/dist/cli/chunks/{chunk-SSUAAX3F.js → chunk-HD6W6PHV.js} +2 -2
  73. package/dist/cli/chunks/{chunk-L2DWPVNJ.js → chunk-HFZD5KLR.js} +1 -1
  74. package/dist/cli/chunks/{chunk-QVDCVD5D.js → chunk-HRUHHHVR.js} +2 -2
  75. package/dist/cli/chunks/{chunk-PINSJCM3.js → chunk-HVT7RMGV.js} +1 -1
  76. package/dist/cli/chunks/chunk-HWQPMUSN.js +2 -0
  77. package/dist/cli/chunks/{chunk-4NFQLP6R.js → chunk-HZ5O7G2P.js} +1 -1
  78. package/dist/cli/chunks/{chunk-C6D5AHBO.js → chunk-IHQGNDMX.js} +2 -2
  79. package/dist/cli/chunks/{chunk-QQWBWEJS.js → chunk-IJSROBM6.js} +3 -3
  80. package/dist/cli/chunks/{chunk-OCV2XEWQ.js → chunk-IJZFJPHS.js} +2 -2
  81. package/dist/cli/chunks/{chunk-N7HL5PHH.js → chunk-IKB3M7OF.js} +1 -1
  82. package/dist/cli/chunks/{chunk-24OX5TQJ.js → chunk-INI3Q4CN.js} +1 -1
  83. package/dist/cli/chunks/{chunk-SJ6Y4725.js → chunk-IOWEBPXJ.js} +2 -2
  84. package/dist/cli/chunks/{chunk-VXFLJNCA.js → chunk-IQL6XRF5.js} +2 -2
  85. package/dist/cli/chunks/{chunk-WP4RETKG.js → chunk-IRHXGCQR.js} +2 -2
  86. package/dist/cli/chunks/{chunk-63ZKI4PX.js → chunk-J3QFJI2Y.js} +2 -2
  87. package/dist/cli/chunks/{chunk-UHEOGZLX.js → chunk-J6QRNQJF.js} +5 -5
  88. package/dist/cli/chunks/{chunk-KNSRL6NO.js → chunk-J7Q5TXFZ.js} +2 -2
  89. package/dist/cli/chunks/{chunk-L6QSTQME.js → chunk-JHKKIJT2.js} +2 -2
  90. package/dist/cli/chunks/{chunk-VMDFFTCK.js → chunk-JI33PMPZ.js} +1 -1
  91. package/dist/cli/chunks/{chunk-E3D4GPLP.js → chunk-JRIJM4LE.js} +3 -3
  92. package/dist/cli/chunks/{chunk-XIQW7EFL.js → chunk-JVWZAE2H.js} +2 -2
  93. package/dist/cli/chunks/{chunk-YPBSUGMI.js → chunk-K7WAI662.js} +1 -1
  94. package/dist/cli/chunks/{chunk-RV74I3YO.js → chunk-KB34MTFZ.js} +2 -2
  95. package/dist/cli/chunks/{chunk-MI5MFHRA.js → chunk-KPIPVSIP.js} +2 -2
  96. package/dist/cli/chunks/{chunk-Y4PFUMOU.js → chunk-KR2TAAF6.js} +1 -1
  97. package/dist/cli/chunks/{chunk-W5HQUIML.js → chunk-KT2QCXO6.js} +2 -2
  98. package/dist/cli/chunks/{chunk-SSYAQZXA.js → chunk-KTORRIX3.js} +2 -2
  99. package/dist/cli/chunks/{chunk-CRPIYUTJ.js → chunk-LCWEQRZI.js} +2 -2
  100. package/dist/cli/chunks/{chunk-NO3IV5Q5.js → chunk-LG5PPJT7.js} +1 -1
  101. package/dist/cli/chunks/{chunk-5VZL4UVN.js → chunk-LIF6UWHV.js} +2 -2
  102. package/dist/cli/chunks/{chunk-32BPDLRZ.js → chunk-LN7NKE3N.js} +2 -2
  103. package/dist/cli/chunks/{chunk-ZB3LEFYG.js → chunk-LOLSZG5J.js} +2 -2
  104. package/dist/cli/chunks/{chunk-6XXZDV2C.js → chunk-LOMT4UC2.js} +2 -2
  105. package/dist/cli/chunks/{chunk-JDIYMZCQ.js → chunk-LRKLATSH.js} +2 -2
  106. package/dist/cli/chunks/{chunk-5SPCGMBB.js → chunk-LRY6UIRI.js} +2 -2
  107. package/dist/cli/chunks/{chunk-5PBLPQ5T.js → chunk-LV7UIK4Q.js} +2 -2
  108. package/dist/cli/chunks/{chunk-FDDC72IA.js → chunk-M2YI5YUR.js} +2 -2
  109. package/dist/cli/chunks/{chunk-D6COXLYE.js → chunk-MCXW3DKE.js} +2 -2
  110. package/dist/cli/chunks/{chunk-J442IZLE.js → chunk-MGZ6XZHU.js} +1 -1
  111. package/dist/cli/chunks/{chunk-TIUKLYAI.js → chunk-MLMD3I75.js} +1 -1
  112. package/dist/cli/chunks/{chunk-PHT5N7SC.js → chunk-MVVVGQJ6.js} +2 -2
  113. package/dist/cli/chunks/{chunk-525CFDUE.js → chunk-ND72UDVH.js} +2 -2
  114. package/dist/cli/chunks/{chunk-XWUWX7BV.js → chunk-NE3LRUNC.js} +4 -4
  115. package/dist/cli/chunks/{chunk-DTMAS2GB.js → chunk-NKUHMA4T.js} +2 -2
  116. package/dist/cli/chunks/{chunk-QPEOLAAS.js → chunk-NQFDJ6BT.js} +1 -1
  117. package/dist/cli/chunks/{chunk-MO55CVMT.js → chunk-NZJVDOUN.js} +14 -14
  118. package/dist/cli/chunks/{chunk-NZU4ACBZ.js → chunk-O7VJ3VKD.js} +2 -2
  119. package/dist/cli/chunks/{chunk-32GN3JKR.js → chunk-OJIUIEI4.js} +1 -1
  120. package/dist/cli/chunks/{chunk-UNGBRZDK.js → chunk-OO2M2QUV.js} +3 -3
  121. package/dist/cli/chunks/{chunk-CJSHWQXP.js → chunk-ORQ2YBRR.js} +2 -2
  122. package/dist/cli/chunks/chunk-OWIQR6N2.js +4 -0
  123. package/dist/cli/chunks/{chunk-NAEWCFQT.js → chunk-OWIZBZLN.js} +2 -2
  124. package/dist/cli/chunks/{chunk-24QHCVX6.js → chunk-P3D7SEHW.js} +1 -1
  125. package/dist/cli/chunks/{chunk-YLMNVLDK.js → chunk-P4OB6WDJ.js} +1 -1
  126. package/dist/cli/chunks/{chunk-PEQDY4BO.js → chunk-PCL5JRKN.js} +2 -2
  127. package/dist/cli/chunks/{chunk-IUBJVHNB.js → chunk-PIWGKGWP.js} +2 -2
  128. package/dist/cli/chunks/{chunk-GJYHWYXR.js → chunk-PK34KJH7.js} +2 -2
  129. package/dist/cli/chunks/{chunk-5B5QPCNU.js → chunk-POPSZDI2.js} +4 -4
  130. package/dist/cli/chunks/{chunk-HCH4Y6XX.js → chunk-Q6F3DYZN.js} +2 -2
  131. package/dist/cli/chunks/{chunk-SHKOCGNK.js → chunk-QJSSUBO3.js} +2 -2
  132. package/dist/cli/chunks/{chunk-DVYHMDFR.js → chunk-QN7HP2UW.js} +421 -418
  133. package/dist/cli/chunks/{chunk-ZFL436FN.js → chunk-QSQNXBD2.js} +2 -2
  134. package/dist/cli/chunks/{chunk-TVGI32MB.js → chunk-QTQDX4TZ.js} +3 -3
  135. package/dist/cli/chunks/{chunk-EK7OLYOZ.js → chunk-R3KBOQ3O.js} +2 -2
  136. package/dist/cli/chunks/{chunk-LE4QJREF.js → chunk-REY52O7J.js} +1 -1
  137. package/dist/cli/chunks/{chunk-LQLPB2T6.js → chunk-RKCN4B26.js} +2 -2
  138. package/dist/cli/chunks/{chunk-ZR2TKVXQ.js → chunk-S3DT5TPR.js} +2 -2
  139. package/dist/cli/chunks/{chunk-6ICX3FEG.js → chunk-S3TBOKAZ.js} +22 -22
  140. package/dist/cli/chunks/{chunk-JHQCRRJI.js → chunk-SAEECT23.js} +2 -2
  141. package/dist/cli/chunks/{chunk-VWPM27GU.js → chunk-SAZ4PJBR.js} +2 -2
  142. package/dist/cli/chunks/{chunk-KPRCB5LT.js → chunk-SFITYZLV.js} +2 -2
  143. package/dist/cli/chunks/{chunk-5LAVKGLH.js → chunk-SRBCBVSI.js} +2 -2
  144. package/dist/cli/chunks/{chunk-O5W3FIO6.js → chunk-SUAZ5Z47.js} +2 -2
  145. package/dist/cli/chunks/{chunk-KU2AUFGX.js → chunk-TDZ6N43D.js} +2 -2
  146. package/dist/cli/chunks/{chunk-YAPLJR7K.js → chunk-TIVKDIF7.js} +2 -2
  147. package/dist/cli/chunks/{chunk-U2A7NHZA.js → chunk-TM75GAXG.js} +2 -2
  148. package/dist/cli/chunks/{chunk-A5GBXCP5.js → chunk-TWBZONKT.js} +2 -2
  149. package/dist/cli/chunks/{chunk-I7MQIM2U.js → chunk-U4S74IIZ.js} +1 -1
  150. package/dist/cli/chunks/{chunk-3HD7E6HN.js → chunk-U5SMBJ6F.js} +2 -2
  151. package/dist/cli/chunks/{chunk-JQ3DYUMS.js → chunk-UHJVZEQA.js} +2 -2
  152. package/dist/cli/chunks/{chunk-C5FP5GW3.js → chunk-UOVCTK5L.js} +2 -2
  153. package/dist/cli/chunks/{chunk-HJ6ZGVTB.js → chunk-VDEKVIP5.js} +2 -2
  154. package/dist/cli/chunks/{chunk-KXCLACFG.js → chunk-VITV7AEC.js} +2 -2
  155. package/dist/cli/chunks/{chunk-P3EYRILV.js → chunk-VKREKVFI.js} +2 -2
  156. package/dist/cli/chunks/{chunk-2H4XH6FT.js → chunk-VLTDW7XJ.js} +2 -2
  157. package/dist/cli/chunks/{chunk-MD43XRX5.js → chunk-VQFV2IPV.js} +1 -1
  158. package/dist/cli/chunks/{chunk-67Z5R7RJ.js → chunk-VYPVU3JF.js} +2 -2
  159. package/dist/cli/chunks/{chunk-SDLWKRVL.js → chunk-WAOEQA3W.js} +2 -2
  160. package/dist/cli/chunks/{chunk-IOYG4VFL.js → chunk-WBDWHHKP.js} +2 -2
  161. package/dist/cli/chunks/{chunk-ASEOFRIG.js → chunk-WX4PO65Q.js} +2 -2
  162. package/dist/cli/chunks/chunk-X2DWHGCC.js +6 -0
  163. package/dist/cli/chunks/{chunk-CEYSYSK5.js → chunk-X5QD76IU.js} +2 -2
  164. package/dist/cli/chunks/{chunk-GSKMOPL7.js → chunk-XBTGEYED.js} +2 -2
  165. package/dist/cli/chunks/{chunk-FL64OUBA.js → chunk-XEMCHGAJ.js} +2 -2
  166. package/dist/cli/chunks/{chunk-2YZ4G6NW.js → chunk-XEYFZLIT.js} +1 -1
  167. package/dist/cli/chunks/{chunk-EA4YQVKS.js → chunk-XFTX3KLE.js} +1 -1
  168. package/dist/cli/chunks/{chunk-HGWXF45W.js → chunk-XPTCQKVE.js} +1 -1
  169. package/dist/cli/chunks/{chunk-CAKMOVZ6.js → chunk-YAJOBZE5.js} +2 -2
  170. package/dist/cli/chunks/{chunk-NQXXI77K.js → chunk-YCVLKU6H.js} +2 -2
  171. package/dist/cli/chunks/{chunk-AR67RJPY.js → chunk-YD2C6EPN.js} +2 -2
  172. package/dist/cli/chunks/{chunk-S75SOOZL.js → chunk-YKRLUTK7.js} +2 -2
  173. package/dist/cli/chunks/{chunk-IOKYCMTJ.js → chunk-YMUY3TES.js} +2 -2
  174. package/dist/cli/chunks/{chunk-5QO3R3TU.js → chunk-YR5QBUHZ.js} +2 -2
  175. package/dist/cli/chunks/{chunk-AJMJNQMP.js → chunk-Z7SKUC6P.js} +1 -1
  176. package/dist/cli/chunks/{chunk-KITOPKRG.js → chunk-ZAQMRFBB.js} +2 -2
  177. package/dist/cli/chunks/{chunk-AAMLQ2LF.js → chunk-ZC3KDNJW.js} +3 -3
  178. package/dist/cli/chunks/{chunk-VJCIEHEF.js → chunk-ZGV7L4MW.js} +1 -1
  179. package/dist/cli/chunks/{chunk-BY5OF7OH.js → chunk-ZN35XSKF.js} +2 -2
  180. package/dist/cli/chunks/{chunk-KKU2QGSJ.js → chunk-ZNXM6WVL.js} +2 -2
  181. package/dist/cli/chunks/{chunk-FLNAW7C4.js → chunk-ZP5AWQRO.js} +2 -2
  182. package/dist/cli/chunks/{chunk-IHRXZZQM.js → chunk-ZTP3DQ5M.js} +1 -1
  183. package/dist/cli/chunks/{chunk-OAEE6JWQ.js → chunk-ZVMSSCTH.js} +2 -2
  184. package/dist/cli/chunks/{chunk-M7WJCTG3.js → chunk-ZWUF27P4.js} +2 -2
  185. package/dist/cli/chunks/{ci-MFUR4CWV.js → ci-3RTTTS2D.js} +2 -2
  186. package/dist/cli/chunks/{ci-config-PNDLQ6XV.js → ci-config-XRUR3I4K.js} +2 -2
  187. package/dist/cli/chunks/{ci-output-PFZ4M7NC.js → ci-output-E5IAMU2U.js} +2 -2
  188. package/dist/cli/chunks/{circuit-breaker-5HH6NLZN.js → circuit-breaker-SHR2P44P.js} +2 -2
  189. package/dist/cli/chunks/{claude-flow-setup-QCKYLGLC.js → claude-flow-setup-ZDDILFMF.js} +2 -2
  190. package/dist/cli/chunks/client-NO5FOWT4.js +2 -0
  191. package/dist/cli/chunks/{cline-installer-EASVPFXR.js → cline-installer-BGYVUM6G.js} +2 -2
  192. package/dist/cli/chunks/{code-UJXDVYRK.js → code-PJ4MC3MC.js} +3 -3
  193. package/dist/cli/chunks/{code-index-extractor-BZJ3UDP4.js → code-index-extractor-IW2P22YG.js} +2 -2
  194. package/dist/cli/chunks/{codex-installer-XSQZUVOZ.js → codex-installer-A7WZ6OGL.js} +2 -2
  195. package/dist/cli/chunks/{completions-OWOOJFI2.js → completions-KS23WD5J.js} +2 -2
  196. package/dist/cli/chunks/{complexity-analyzer-KP5TOHDT.js → complexity-analyzer-Q7GLSR2E.js} +2 -2
  197. package/dist/cli/chunks/{continuedev-installer-IFKQXLHM.js → continuedev-installer-SK55BFW2.js} +2 -2
  198. package/dist/cli/chunks/copilot-installer-3N5J3WTM.js +3 -0
  199. package/dist/cli/chunks/core-handlers-JNAZPXE2.js +2 -0
  200. package/dist/cli/chunks/{cost-tracker-MMDDNKZB.js → cost-tracker-NENVSO4A.js} +2 -2
  201. package/dist/cli/chunks/{coverage-LUH2B7NT.js → coverage-5L7UQWDH.js} +3 -3
  202. package/dist/cli/chunks/cross-domain-router-HEBM767Z.js +2 -0
  203. package/dist/cli/chunks/{cursor-installer-4YLM5GWM.js → cursor-installer-XXBO2ZE6.js} +2 -2
  204. package/dist/cli/chunks/{daemon-MZKVM4CJ.js → daemon-CDCQU3LR.js} +3 -3
  205. package/dist/cli/chunks/{daemon-CAVZ7OFV.js → daemon-JEBJGEUK.js} +4 -4
  206. package/dist/cli/chunks/{dag-attention-scheduler-X4CYW665.js → dag-attention-scheduler-HOMMF7FA.js} +2 -2
  207. package/dist/cli/chunks/{detect-7BM2XINO.js → detect-FXCOUG6X.js} +2 -2
  208. package/dist/cli/chunks/{dist-node-Y5APLEYB.js → dist-node-GXQ7FMTY.js} +2 -2
  209. package/dist/cli/chunks/{domain-handler-X3ZRJNAH.js → domain-handler-TI3JBAPC.js} +2 -2
  210. package/dist/cli/chunks/{domain-plugins-2UW5KQJB.js → domain-plugins-R7LTUM32.js} +2 -2
  211. package/dist/cli/chunks/{domain-transfer-35W4CIBV.js → domain-transfer-LBIAFHIQ.js} +2 -2
  212. package/dist/cli/chunks/dream-GQDCEJMS.js +2 -0
  213. package/dist/cli/chunks/embed-and-insert-pattern-33KLHDD5.js +3 -0
  214. package/dist/cli/chunks/{embedding-space-SBM2MZD2.js → embedding-space-HHLWTBF5.js} +2 -2
  215. package/dist/cli/chunks/{eval-4QA2SROK.js → eval-KDOZMAXJ.js} +2 -2
  216. package/dist/cli/chunks/{experience-capture-middleware-Z6BF6KYM.js → experience-capture-middleware-X45PECQN.js} +3 -3
  217. package/dist/cli/chunks/{fast-paths-FIORX6GN.js → fast-paths-462V6UUB.js} +2 -2
  218. package/dist/cli/chunks/{feature-flags-ZOO7LMIC.js → feature-flags-G66OT3AS.js} +2 -2
  219. package/dist/cli/chunks/{feature-flags-6LYI2T4G.js → feature-flags-NIRQ4YDM.js} +2 -2
  220. package/dist/cli/chunks/file-discovery-33USPLB5.js +2 -0
  221. package/dist/cli/chunks/{fleet-7WF53H4F.js → fleet-PXWGB7CU.js} +3 -3
  222. package/dist/cli/chunks/{gnn-wrapper-KJ6B7BRM.js → gnn-wrapper-7MUW3M5M.js} +2 -2
  223. package/dist/cli/chunks/{heartbeat-handler-DEKKMOVW.js → heartbeat-handler-5237PB35.js} +4 -4
  224. package/dist/cli/chunks/heartbeat-scheduler-LIXLC5IH.js +2 -0
  225. package/dist/cli/chunks/hnsw-adapter-62D5UH27.js +2 -0
  226. package/dist/cli/chunks/hnsw-index-GSGUMQQC.js +2 -0
  227. package/dist/cli/chunks/{hnsw-legacy-bridge-L27WS27N.js → hnsw-legacy-bridge-OSQPW7JP.js} +2 -2
  228. package/dist/cli/chunks/{hnswlib-node-4YOQC6L4.js → hnswlib-node-GX6WG2GB.js} +2 -2
  229. package/dist/cli/chunks/{hooks-TAOKV4EJ.js → hooks-GUWHL7VC.js} +10 -10
  230. package/dist/cli/chunks/hybrid-backend-FRWP4BOY.js +2 -0
  231. package/dist/cli/chunks/{hypergraph-engine-BODRJLHL.js → hypergraph-engine-SRWLLCU3.js} +2 -2
  232. package/dist/cli/chunks/{hypergraph-handler-RKMYJNTU.js → hypergraph-handler-AVOPRHHO.js} +3 -3
  233. package/dist/cli/chunks/impact-analyzer-7KF3AQXV.js +2 -0
  234. package/dist/cli/chunks/{init-guard-MXHSLSB2.js → init-guard-P4N6EVZS.js} +2 -2
  235. package/dist/cli/chunks/{init-handler-HUE57IFW.js → init-handler-LRGWOJMD.js} +6 -6
  236. package/dist/cli/chunks/init-wizard-XWWAXY25.js +2 -0
  237. package/dist/cli/chunks/kernel-ZEJPNDBW.js +2 -0
  238. package/dist/cli/chunks/{kilocode-installer-S333IKYQ.js → kilocode-installer-7R2EPOQ6.js} +2 -2
  239. package/dist/cli/chunks/{kiro-installer-WM5DLQWC.js → kiro-installer-QNM7DPOB.js} +2 -2
  240. package/dist/cli/chunks/knowledge-graph-RRZQS7KY.js +2 -0
  241. package/dist/cli/chunks/{learning-LNHMQLH5.js → learning-7OIZBPXZ.js} +3 -3
  242. package/dist/cli/chunks/{llm-router-EWFXYZZR.js → llm-router-SIDXES23.js} +4 -4
  243. package/dist/cli/chunks/llm-router-service-3OSW67LC.js +2 -0
  244. package/dist/cli/chunks/{load-FGYGWVDK.js → load-EI2E2C3S.js} +2 -2
  245. package/dist/cli/chunks/load-test-7TRIH2WJ.js +2 -0
  246. package/dist/cli/chunks/{mcp-2FHNAAOM.js → mcp-IOE5WOCS.js} +2 -2
  247. package/dist/cli/chunks/{memory-DZMQ73AB.js → memory-DLYGJAP7.js} +5 -5
  248. package/dist/cli/chunks/memory-backend-G7ZW6Q2B.js +2 -0
  249. package/dist/cli/chunks/memory-handlers-TPF3KCO5.js +2 -0
  250. package/dist/cli/chunks/{multi-model-executor-6F2UAEUW.js → multi-model-executor-WHH4YCHM.js} +2 -2
  251. package/dist/cli/chunks/{opencode-installer-XY3BGOTZ.js → opencode-installer-63FDZAMS.js} +2 -2
  252. package/dist/cli/chunks/{orchestrator-B4CNKUOS.js → orchestrator-3LA776KK.js} +5 -5
  253. package/dist/cli/chunks/pattern-null-store-OU3ZC3NR.js +2 -0
  254. package/dist/cli/chunks/{pattern-usage-recorder-R4GUFNMD.js → pattern-usage-recorder-NW54QUGI.js} +2 -2
  255. package/dist/cli/chunks/{pipeline-FG5RKVRO.js → pipeline-P3TYX6J6.js} +2 -2
  256. package/dist/cli/chunks/{platform-3BT4KEVJ.js → platform-FNA2WLI6.js} +2 -2
  257. package/dist/cli/chunks/{plugin-WI4RIN7O.js → plugin-NJS7BC2S.js} +2 -2
  258. package/dist/cli/chunks/{prime-radiant-advanced-wasm-7ECDNQFS.js → prime-radiant-advanced-wasm-NIAVL2OT.js} +2 -2
  259. package/dist/cli/chunks/project-root-GMOFJEKD.js +2 -0
  260. package/dist/cli/chunks/protocol-executor-AD345XRO.js +2 -0
  261. package/dist/cli/chunks/{protocol-handler-WNODKPGW.js → protocol-handler-JU5C4JHY.js} +2 -2
  262. package/dist/cli/chunks/{prove-5RHAEPYZ.js → prove-35VOSLYP.js} +2 -2
  263. package/dist/cli/chunks/qe-reasoning-bank-NLTP26RC.js +2 -0
  264. package/dist/cli/chunks/{quality-WPHR7BGQ.js → quality-ET74X7HN.js} +2 -2
  265. package/dist/cli/chunks/{quality-gate-4RKTEZMX.js → quality-gate-FEDQISNB.js} +3 -3
  266. package/dist/cli/chunks/queen-coordinator-2TB4FWS6.js +2 -0
  267. package/dist/cli/chunks/real-embeddings-II6CXTCI.js +2 -0
  268. package/dist/cli/chunks/{ref-validation-TPAWHOHH.js → ref-validation-DTBPYCEB.js} +2 -2
  269. package/dist/cli/chunks/{roocode-installer-7AVHFNDI.js → roocode-installer-LYQEMR4J.js} +2 -2
  270. package/dist/cli/chunks/router-PLM3MWME.js +2 -0
  271. package/dist/cli/chunks/routing-feedback-I7VOX2HU.js +2 -0
  272. package/dist/cli/chunks/{routing-handler-YKEDVJSH.js → routing-handler-DJOJFPII.js} +2 -2
  273. package/dist/cli/chunks/{ruvector-commands-JUAMM354.js → ruvector-commands-VXYGJDPW.js} +2 -2
  274. package/dist/cli/chunks/rvf-dual-writer-GQZHFWO2.js +2 -0
  275. package/dist/cli/chunks/rvf-migration-adapter-3TVKBCAM.js +2 -0
  276. package/dist/cli/chunks/rvf-migration-coordinator-XUHKLMT6.js +2 -0
  277. package/dist/cli/chunks/rvf-native-adapter-5GUTYOWS.js +2 -0
  278. package/dist/cli/chunks/{rvf-store-integrity-VJDUIRTX.js → rvf-store-integrity-GA2ZYOEG.js} +2 -2
  279. package/dist/cli/chunks/safe-db-RZPQGLGQ.js +2 -0
  280. package/dist/cli/chunks/schedule-G7JMQDUX.js +2 -0
  281. package/dist/cli/chunks/scheduler-4SEGPCKD.js +2 -0
  282. package/dist/cli/chunks/{security-ORDN3RD2.js → security-MM6YOECX.js} +3 -3
  283. package/dist/cli/chunks/{shared-rvf-adapter-CF4BCIO7.js → shared-rvf-adapter-6AHPA3V5.js} +2 -2
  284. package/dist/cli/chunks/{shared-rvf-dual-writer-C32UBR6D.js → shared-rvf-dual-writer-EYAVY2GZ.js} +2 -2
  285. package/dist/cli/chunks/sqlite-persistence-IVE4SQXR.js +2 -0
  286. package/dist/cli/chunks/{standalone-memory-OXRJYZXN.js → standalone-memory-A3PLB4CZ.js} +2 -2
  287. package/dist/cli/chunks/{status-handler-BCX5D4HY.js → status-handler-OSSFAP4Z.js} +2 -2
  288. package/dist/cli/chunks/{structural-health-LFG7RUU6.js → structural-health-PGY5XUNO.js} +2 -2
  289. package/dist/cli/chunks/{sync-YJEE2K2L.js → sync-CWEHYGNN.js} +2 -2
  290. package/dist/cli/chunks/sync-PM6D7EQF.js +2 -0
  291. package/dist/cli/chunks/{task-handler-6LXKPTXJ.js → task-handler-LHMQ75W4.js} +2 -2
  292. package/dist/cli/chunks/{task-handlers-CILP36I7.js → task-handlers-S2TX5FTR.js} +3 -3
  293. package/dist/cli/chunks/test-4EGZZ6NJ.js +34 -0
  294. package/dist/cli/chunks/test-runner-process-72YACW6M.js +2 -0
  295. package/dist/cli/chunks/{test-scheduling-ISI2O4Q5.js → test-scheduling-YJQHH3XE.js} +3 -3
  296. package/dist/cli/chunks/{token-bootstrap-VUELSBOS.js → token-bootstrap-DJNETMVW.js} +2 -2
  297. package/dist/cli/chunks/{token-usage-XOC5KG7S.js → token-usage-WPNOJR6H.js} +2 -2
  298. package/dist/cli/chunks/{transformers-LSLQAARK.js → transformers-4MRPXCPU.js} +2 -2
  299. package/dist/cli/chunks/tree-sitter-wasm-parser-UVWSDXFR.js +2 -0
  300. package/dist/cli/chunks/{types-5BLCGLCR.js → types-6P5FB4EB.js} +2 -2
  301. package/dist/cli/chunks/unified-memory-2VMGSGQL.js +2 -0
  302. package/dist/cli/chunks/unified-memory-hnsw-3KULVD3N.js +2 -0
  303. package/dist/cli/chunks/unified-persistence-QCSLU2SV.js +2 -0
  304. package/dist/cli/chunks/{upgrade-RQJYLK3J.js → upgrade-4ICTN63Y.js} +2 -2
  305. package/dist/cli/chunks/{validate-QBHWXXCK.js → validate-HQF5GZ7L.js} +2 -2
  306. package/dist/cli/chunks/{validate-swarm-IKXBKFB5.js → validate-swarm-45JYG7VW.js} +2 -2
  307. package/dist/cli/chunks/visual-security-ZYP2KPH7.js +2 -0
  308. package/dist/cli/chunks/{web-tree-sitter-ZF6FIE5R.js → web-tree-sitter-UOTWZLNH.js} +2 -2
  309. package/dist/cli/chunks/{windsurf-installer-HQGDZT5D.js → windsurf-installer-WDWSBXGN.js} +2 -2
  310. package/dist/cli/chunks/witness-chain-5QRT7EMX.js +2 -0
  311. package/dist/cli/chunks/{witness-chain-DCHCAMSQ.js → witness-chain-DOYMNPC7.js} +2 -2
  312. package/dist/cli/chunks/{witness-chain-repair-PUX2NFDL.js → witness-chain-repair-CUF2AFQB.js} +2 -2
  313. package/dist/cli/chunks/{witness-chain-verifier-PX2OQ6XT.js → witness-chain-verifier-JB42X62J.js} +2 -2
  314. package/dist/cli/chunks/{witness-key-manager-RXYQNFJB.js → witness-key-manager-LXXO6L2G.js} +2 -2
  315. package/dist/cli/chunks/{workflow-FBKCA4H6.js → workflow-6ARK47NF.js} +4 -4
  316. package/dist/cli/chunks/workflow-orchestrator-RYDDWIXN.js +2 -0
  317. package/dist/cli/chunks/{wrappers-TWSKBTWD.js → wrappers-CYQBOMPL.js} +2 -2
  318. package/dist/cli/commands/test.js +26 -4
  319. package/dist/coordination/handlers/test-execution-handlers.js +64 -20
  320. package/dist/domains/code-intelligence/services/semantic-analyzer.d.ts +8 -3
  321. package/dist/domains/code-intelligence/services/semantic-analyzer.js +39 -25
  322. package/dist/domains/code-intelligence/services/text-relevance.d.ts +32 -0
  323. package/dist/domains/code-intelligence/services/text-relevance.js +63 -0
  324. package/dist/domains/test-execution/coordinator.d.ts +3 -1
  325. package/dist/domains/test-execution/coordinator.js +13 -4
  326. package/dist/domains/test-execution/interfaces.d.ts +5 -0
  327. package/dist/domains/test-execution/plugin.js +2 -0
  328. package/dist/domains/test-execution/services/flaky-detector.d.ts +9 -1
  329. package/dist/domains/test-execution/services/flaky-detector.js +26 -8
  330. package/dist/domains/test-execution/services/retry-handler.d.ts +7 -1
  331. package/dist/domains/test-execution/services/retry-handler.js +44 -5
  332. package/dist/domains/test-execution/services/runner-test-cases.d.ts +2 -0
  333. package/dist/domains/test-execution/services/runner-test-cases.js +7 -3
  334. package/dist/domains/test-execution/services/test-executor.d.ts +5 -1
  335. package/dist/domains/test-execution/services/test-executor.js +79 -15
  336. package/dist/init/copilot-installer.d.ts +6 -0
  337. package/dist/init/copilot-installer.js +37 -17
  338. package/dist/init/platform-config-generator.d.ts +10 -0
  339. package/dist/init/platform-config-generator.js +26 -1
  340. package/dist/kernel/unified-memory.d.ts +8 -0
  341. package/dist/kernel/unified-memory.js +13 -0
  342. package/dist/learning/embedder-endpoint-client.d.ts +45 -0
  343. package/dist/learning/embedder-endpoint-client.js +98 -3
  344. package/dist/learning/embedding-space-registry.d.ts +75 -0
  345. package/dist/learning/embedding-space-registry.js +142 -0
  346. package/dist/learning/real-embeddings.d.ts +3 -0
  347. package/dist/learning/real-embeddings.js +49 -11
  348. package/dist/mcp/bundle.js +564 -555
  349. package/dist/mcp/protocol-server.js +1 -1
  350. package/dist/shared/embeddings/index.d.ts +2 -2
  351. package/dist/shared/embeddings/index.js +1 -1
  352. package/dist/shared/embeddings/nomic-embedder.d.ts +8 -2
  353. package/dist/shared/embeddings/nomic-embedder.js +19 -11
  354. package/dist/shared/embeddings/ollama-client.d.ts +28 -2
  355. package/dist/shared/embeddings/ollama-client.js +84 -22
  356. package/dist/shared/embeddings/types.d.ts +15 -0
  357. package/dist/shared/embeddings/types.js +4 -0
  358. package/dist/shared/pytest-junit-report.d.ts +93 -0
  359. package/dist/shared/pytest-junit-report.js +241 -0
  360. package/dist/shared/test-runner-project.d.ts +51 -1
  361. package/dist/shared/test-runner-project.js +140 -25
  362. package/package.json +1 -1
  363. package/dist/cli/chunks/adapter-6CQ2PIP5.js +0 -2
  364. package/dist/cli/chunks/aqe-learning-engine-73RR52VS.js +0 -2
  365. package/dist/cli/chunks/base-SMCMMVGP.js +0 -2
  366. package/dist/cli/chunks/browser-workflow-A2MEZ66K.js +0 -2
  367. package/dist/cli/chunks/chunk-EGYE5UPQ.js +0 -2
  368. package/dist/cli/chunks/chunk-KL7OKSU2.js +0 -4
  369. package/dist/cli/chunks/chunk-M4FRQ4TE.js +0 -12
  370. package/dist/cli/chunks/chunk-UE5ZOZR2.js +0 -2
  371. package/dist/cli/chunks/client-MHQRTZM4.js +0 -2
  372. package/dist/cli/chunks/copilot-installer-IGJ6KGQY.js +0 -3
  373. package/dist/cli/chunks/core-handlers-UAK3LLJE.js +0 -2
  374. package/dist/cli/chunks/cross-domain-router-WTRZQPNQ.js +0 -2
  375. package/dist/cli/chunks/dream-EJY24JN6.js +0 -2
  376. package/dist/cli/chunks/embed-and-insert-pattern-COG4C7ZI.js +0 -3
  377. package/dist/cli/chunks/file-discovery-UZSFSS4V.js +0 -2
  378. package/dist/cli/chunks/heartbeat-scheduler-NVR356I7.js +0 -2
  379. package/dist/cli/chunks/hnsw-adapter-LFMPLUJU.js +0 -2
  380. package/dist/cli/chunks/hnsw-index-POCPMVJH.js +0 -2
  381. package/dist/cli/chunks/hybrid-backend-4STAO7CV.js +0 -2
  382. package/dist/cli/chunks/impact-analyzer-3VIIISBQ.js +0 -2
  383. package/dist/cli/chunks/init-wizard-PL6QN6RQ.js +0 -2
  384. package/dist/cli/chunks/kernel-CCDWT7KS.js +0 -2
  385. package/dist/cli/chunks/knowledge-graph-KFOMEN3H.js +0 -2
  386. package/dist/cli/chunks/llm-router-service-7NBE2EX6.js +0 -2
  387. package/dist/cli/chunks/load-test-UNZUWY3F.js +0 -2
  388. package/dist/cli/chunks/memory-backend-DFGKWA2Q.js +0 -2
  389. package/dist/cli/chunks/memory-handlers-MP426XRJ.js +0 -2
  390. package/dist/cli/chunks/pattern-null-store-SSVF5TE5.js +0 -2
  391. package/dist/cli/chunks/project-root-BEANNYWU.js +0 -2
  392. package/dist/cli/chunks/protocol-executor-FQVIHXZ7.js +0 -2
  393. package/dist/cli/chunks/qe-reasoning-bank-5TFYSE24.js +0 -2
  394. package/dist/cli/chunks/queen-coordinator-Y2OUL7IN.js +0 -2
  395. package/dist/cli/chunks/real-embeddings-OXLYU7JW.js +0 -2
  396. package/dist/cli/chunks/router-EP34O3KB.js +0 -2
  397. package/dist/cli/chunks/routing-feedback-FJCRKXNG.js +0 -2
  398. package/dist/cli/chunks/rvf-dual-writer-ILITJSFG.js +0 -2
  399. package/dist/cli/chunks/rvf-migration-adapter-XF6W4C2N.js +0 -2
  400. package/dist/cli/chunks/rvf-migration-coordinator-CMKG56AR.js +0 -2
  401. package/dist/cli/chunks/rvf-native-adapter-7YFW6S4Y.js +0 -2
  402. package/dist/cli/chunks/safe-db-TCAU4FUT.js +0 -2
  403. package/dist/cli/chunks/schedule-NB5KV435.js +0 -2
  404. package/dist/cli/chunks/scheduler-JKXGKVK6.js +0 -2
  405. package/dist/cli/chunks/sqlite-persistence-IXCNZRTW.js +0 -2
  406. package/dist/cli/chunks/sync-OSF7C2NL.js +0 -2
  407. package/dist/cli/chunks/test-SD457QJ6.js +0 -34
  408. package/dist/cli/chunks/test-runner-process-VKD65QQU.js +0 -2
  409. package/dist/cli/chunks/tree-sitter-wasm-parser-YAIPHRIL.js +0 -2
  410. package/dist/cli/chunks/unified-memory-GI76TXFV.js +0 -2
  411. package/dist/cli/chunks/unified-memory-hnsw-GXJ5BTZO.js +0 -2
  412. package/dist/cli/chunks/unified-persistence-OP7FDQPD.js +0 -2
  413. package/dist/cli/chunks/visual-security-GZ2MOKWB.js +0 -2
  414. package/dist/cli/chunks/witness-chain-P3XXXA62.js +0 -2
  415. package/dist/cli/chunks/workflow-orchestrator-P2APAJAA.js +0 -2
@@ -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.15.16");process.exit(0)}
2
- import{b as h,d as v,f as T}from"./chunk-AJMJNQMP.js";var y={};v(y,{DotProductAttention:()=>z,FlashAttention:()=>k,HyperbolicAttention:()=>C,LinearAttention:()=>j,MoEAttention:()=>W,MultiHeadAttention:()=>F,RuvectorLayer:()=>I,SonaEngine:()=>K,TensorCompress:()=>E,default:()=>_,differentiableSearch:()=>L,getCompressionLevel:()=>B,hierarchicalForward:()=>V,init:()=>D,pipeline:()=>q});import{createRequire as A}from"module";var O,g,_,I,E,L,V,B,D,k,z,F,C,j,W,K,q,R=h(()=>{O=A(import.meta.url),g=O("@ruvector/rvf-node"),_=g,{RuvectorLayer:I,TensorCompress:E,differentiableSearch:L,hierarchicalForward:V,getCompressionLevel:B,init:D,FlashAttention:k,DotProductAttention:z,MultiHeadAttention:F,HyperbolicAttention:C,LinearAttention:j,MoEAttention:W,SonaEngine:K,pipeline:q}=g||{}});var Z={};v(Z,{createRvfStore:()=>$,isRvfNativeAvailable:()=>X,openRvfStore:()=>G,openRvfStoreReadonly:()=>U});import{readFileSync as J,writeFileSync as H,copyFileSync as Q,existsSync as Y}from"fs";function c(){if(S)return m;S=!0;try{let s=(R(),T(y));!s.RvfDatabase&&s.default&&s.default.RvfDatabase&&(s=s.default),m=s}catch{m=null}return m}function w(s){return`${s}.idmap.json`}function N(s){let e=w(s),t=new Map,n=new Map,i=1;if(Y(e))try{let r=JSON.parse(J(e,"utf-8"));i=r.nextLabel;for(let[a,p]of r.entries)t.set(a,p),n.set(p,a)}catch{}return{strToNum:t,numToStr:n,nextLabel:i}}function b(s,e,t){let n={nextLabel:t,entries:Array.from(e.entries())};H(w(s),JSON.stringify(n),"utf-8")}function $(s,e){let t=c();if(!t)throw new Error("@ruvector/rvf-node is not available \u2014 install the package or check platform compatibility");let n=t.RvfDatabase.create(s,{dimension:e}),i=n.dimension();return new d(n,s,i,new Map,new Map,1)}function G(s){let e=c();if(!e)throw new Error("@ruvector/rvf-node is not available \u2014 install the package or check platform compatibility");let t=e.RvfDatabase.open(s),n=t.dimension(),{strToNum:i,numToStr:r,nextLabel:a}=N(s);return new d(t,s,n,i,r,a)}function U(s){let e=c();if(!e)throw new Error("@ruvector/rvf-node is not available \u2014 install the package or check platform compatibility");let t=e.RvfDatabase.openReadonly(s),n=t.dimension(),{strToNum:i,numToStr:r,nextLabel:a}=N(s);return new d(t,s,n,i,r,a)}function X(){return process.env.AQE_MEMORY_BACKEND==="memory"?!1:c()!==null}var m,S,d,P=h(()=>{m=null,S=!1;d=class s{db;_path;_dimension;strToNum;numToStr;nextLabel;_open;constructor(e,t,n,i,r,a){this.db=e,this._path=t,this._dimension=n,this.strToNum=i,this.numToStr=r,this.nextLabel=a,this._open=!0}ingest(e){if(this.ensureOpen(),e.length===0)return{accepted:0,rejected:0};let t=this._dimension,n=new Float32Array(e.length*t),i=[],r=[];for(let o=0;o<e.length;o++){let{id:u,vector:f,metadata:x}=e[o],l=this.strToNum.get(u);l===void 0&&(l=this.nextLabel++,this.strToNum.set(u,l),this.numToStr.set(l,u)),i.push(l),r.push(x);let M=f instanceof Float32Array?f:new Float32Array(f);n.set(M.subarray(0,t),o*t)}let a;if(r.some(o=>o!==void 0)&&typeof this.db.ingestBatchWithMetadata=="function"){let o=r.map(u=>u?JSON.stringify(u):"");a=this.db.ingestBatchWithMetadata(n,i,o)}else a=this.db.ingestBatch(n,i);return this.persistIdMap(),{accepted:a.accepted,rejected:a.rejected}}has(e){return this.ensureOpen(),this.strToNum.has(e)}search(e,t){this.ensureOpen();let n=e instanceof Float32Array?e:new Float32Array(e);return this.db.query(n,t).map(r=>{let a=this.numToStr.get(r.id);return a===void 0?null:{id:a,distance:r.distance,score:1/(1+r.distance)}}).filter(r=>r!==null)}delete(e){this.ensureOpen();let t=[];for(let i of e){let r=this.strToNum.get(i);r!==void 0&&t.push(r)}if(t.length===0)return 0;let n=this.db.delete(t);for(let i of e){let r=this.strToNum.get(i);r!==void 0&&(this.strToNum.delete(i),this.numToStr.delete(r))}return this.persistIdMap(),n.deleted}fork(e){this.ensureOpen(),Q(this._path,e);let t=new Map(this.strToNum),n=new Map(this.numToStr);b(e,t,this.nextLabel);let r=c().RvfDatabase.open(e);return new s(r,e,this._dimension,t,n,this.nextLabel)}status(){this.ensureOpen();let e=this.db.status(),n=this.db.segments().filter(i=>i.segType==="witness");return{totalVectors:e.totalVectors,totalSegments:e.totalSegments,fileSizeBytes:e.fileSize,epoch:e.currentEpoch,witnessValid:n.length>0,witnessEntries:n.length,deadSpaceRatio:typeof e.deadSpaceRatio=="number"?e.deadSpaceRatio:0}}dimension(){return this._dimension}size(){return this.ensureOpen(),this.db.status().totalVectors}compact(){this.ensureOpen();try{let e=this.db.compact();return e&&typeof e=="object"?{segmentsCompacted:typeof e.segmentsCompacted=="number"?e.segmentsCompacted:0,bytesReclaimed:typeof e.bytesReclaimed=="number"?e.bytesReclaimed:0,epoch:typeof e.epoch=="number"?e.epoch:0}:{segmentsCompacted:0,bytesReclaimed:0,epoch:0}}catch{return null}}close(){this._open&&(this.db.close(),this._open=!1)}isOpen(){return this._open}path(){return this._path}embedKernel(e){return this.ensureOpen(),this.db.embedKernel(0,99,0,e,0,"")}extractKernel(){return this.ensureOpen(),this.db.extractKernel()}verifyWitness(){this.ensureOpen();let e=this.tryNative("verifyWitness");return e?{valid:e.valid??!0,totalEntries:e.totalEntries??0,errors:Array.isArray(e.errors)?e.errors:[]}:{valid:!0,totalEntries:0,errors:[]}}sign(e){this.ensureOpen();let t=this.tryNative("sign",e);return typeof t=="string"?t:null}fileId(){this.ensureOpen();let e=this.tryNative("fileId");return typeof e=="string"?e:null}parentId(){this.ensureOpen();let e=this.tryNative("parentId");return typeof e=="string"?e:null}lineageDepth(){this.ensureOpen();let e=this.tryNative("lineageDepth");return typeof e=="number"?e:0}indexStats(){let e=this.status();return{totalVectors:e.totalVectors,dimension:this._dimension,totalSegments:e.totalSegments,fileSizeBytes:e.fileSizeBytes,epoch:e.epoch,witnessValid:e.witnessValid,witnessEntries:e.witnessEntries,idMapSize:this.strToNum.size}}freeze(){this.ensureOpen();let e=this.tryNative("freeze");return typeof e=="number"?e:0}derive(e){this.ensureOpen();let t=c();if(typeof this.db.derive=="function")try{let n=this.db.derive(e),i=new Map(this.strToNum),r=new Map(this.numToStr);return b(e,i,this.nextLabel),new s(n,e,this._dimension,i,r,this.nextLabel)}catch{}return this.fork(e)}ensureOpen(){if(!this._open)throw new Error("RVF database is closed")}tryNative(e,...t){if(typeof this.db[e]!="function")return null;try{return this.db[e](...t)}catch{return null}}persistIdMap(){b(this._path,this.strToNum,this.nextLabel)}}});export{$ as a,G as b,U as c,X as d,Z as e,P as f};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.17");process.exit(0)}
2
+ import{b as h,d as v,f as T}from"./chunk-Z7SKUC6P.js";var y={};v(y,{DotProductAttention:()=>z,FlashAttention:()=>k,HyperbolicAttention:()=>C,LinearAttention:()=>j,MoEAttention:()=>W,MultiHeadAttention:()=>F,RuvectorLayer:()=>I,SonaEngine:()=>K,TensorCompress:()=>E,default:()=>_,differentiableSearch:()=>L,getCompressionLevel:()=>B,hierarchicalForward:()=>V,init:()=>D,pipeline:()=>q});import{createRequire as A}from"module";var O,g,_,I,E,L,V,B,D,k,z,F,C,j,W,K,q,R=h(()=>{O=A(import.meta.url),g=O("@ruvector/rvf-node"),_=g,{RuvectorLayer:I,TensorCompress:E,differentiableSearch:L,hierarchicalForward:V,getCompressionLevel:B,init:D,FlashAttention:k,DotProductAttention:z,MultiHeadAttention:F,HyperbolicAttention:C,LinearAttention:j,MoEAttention:W,SonaEngine:K,pipeline:q}=g||{}});var Z={};v(Z,{createRvfStore:()=>$,isRvfNativeAvailable:()=>X,openRvfStore:()=>G,openRvfStoreReadonly:()=>U});import{readFileSync as J,writeFileSync as H,copyFileSync as Q,existsSync as Y}from"fs";function c(){if(S)return m;S=!0;try{let s=(R(),T(y));!s.RvfDatabase&&s.default&&s.default.RvfDatabase&&(s=s.default),m=s}catch{m=null}return m}function w(s){return`${s}.idmap.json`}function N(s){let e=w(s),t=new Map,n=new Map,i=1;if(Y(e))try{let r=JSON.parse(J(e,"utf-8"));i=r.nextLabel;for(let[a,p]of r.entries)t.set(a,p),n.set(p,a)}catch{}return{strToNum:t,numToStr:n,nextLabel:i}}function b(s,e,t){let n={nextLabel:t,entries:Array.from(e.entries())};H(w(s),JSON.stringify(n),"utf-8")}function $(s,e){let t=c();if(!t)throw new Error("@ruvector/rvf-node is not available \u2014 install the package or check platform compatibility");let n=t.RvfDatabase.create(s,{dimension:e}),i=n.dimension();return new d(n,s,i,new Map,new Map,1)}function G(s){let e=c();if(!e)throw new Error("@ruvector/rvf-node is not available \u2014 install the package or check platform compatibility");let t=e.RvfDatabase.open(s),n=t.dimension(),{strToNum:i,numToStr:r,nextLabel:a}=N(s);return new d(t,s,n,i,r,a)}function U(s){let e=c();if(!e)throw new Error("@ruvector/rvf-node is not available \u2014 install the package or check platform compatibility");let t=e.RvfDatabase.openReadonly(s),n=t.dimension(),{strToNum:i,numToStr:r,nextLabel:a}=N(s);return new d(t,s,n,i,r,a)}function X(){return process.env.AQE_MEMORY_BACKEND==="memory"?!1:c()!==null}var m,S,d,P=h(()=>{m=null,S=!1;d=class s{db;_path;_dimension;strToNum;numToStr;nextLabel;_open;constructor(e,t,n,i,r,a){this.db=e,this._path=t,this._dimension=n,this.strToNum=i,this.numToStr=r,this.nextLabel=a,this._open=!0}ingest(e){if(this.ensureOpen(),e.length===0)return{accepted:0,rejected:0};let t=this._dimension,n=new Float32Array(e.length*t),i=[],r=[];for(let o=0;o<e.length;o++){let{id:u,vector:f,metadata:x}=e[o],l=this.strToNum.get(u);l===void 0&&(l=this.nextLabel++,this.strToNum.set(u,l),this.numToStr.set(l,u)),i.push(l),r.push(x);let M=f instanceof Float32Array?f:new Float32Array(f);n.set(M.subarray(0,t),o*t)}let a;if(r.some(o=>o!==void 0)&&typeof this.db.ingestBatchWithMetadata=="function"){let o=r.map(u=>u?JSON.stringify(u):"");a=this.db.ingestBatchWithMetadata(n,i,o)}else a=this.db.ingestBatch(n,i);return this.persistIdMap(),{accepted:a.accepted,rejected:a.rejected}}has(e){return this.ensureOpen(),this.strToNum.has(e)}search(e,t){this.ensureOpen();let n=e instanceof Float32Array?e:new Float32Array(e);return this.db.query(n,t).map(r=>{let a=this.numToStr.get(r.id);return a===void 0?null:{id:a,distance:r.distance,score:1/(1+r.distance)}}).filter(r=>r!==null)}delete(e){this.ensureOpen();let t=[];for(let i of e){let r=this.strToNum.get(i);r!==void 0&&t.push(r)}if(t.length===0)return 0;let n=this.db.delete(t);for(let i of e){let r=this.strToNum.get(i);r!==void 0&&(this.strToNum.delete(i),this.numToStr.delete(r))}return this.persistIdMap(),n.deleted}fork(e){this.ensureOpen(),Q(this._path,e);let t=new Map(this.strToNum),n=new Map(this.numToStr);b(e,t,this.nextLabel);let r=c().RvfDatabase.open(e);return new s(r,e,this._dimension,t,n,this.nextLabel)}status(){this.ensureOpen();let e=this.db.status(),n=this.db.segments().filter(i=>i.segType==="witness");return{totalVectors:e.totalVectors,totalSegments:e.totalSegments,fileSizeBytes:e.fileSize,epoch:e.currentEpoch,witnessValid:n.length>0,witnessEntries:n.length,deadSpaceRatio:typeof e.deadSpaceRatio=="number"?e.deadSpaceRatio:0}}dimension(){return this._dimension}size(){return this.ensureOpen(),this.db.status().totalVectors}compact(){this.ensureOpen();try{let e=this.db.compact();return e&&typeof e=="object"?{segmentsCompacted:typeof e.segmentsCompacted=="number"?e.segmentsCompacted:0,bytesReclaimed:typeof e.bytesReclaimed=="number"?e.bytesReclaimed:0,epoch:typeof e.epoch=="number"?e.epoch:0}:{segmentsCompacted:0,bytesReclaimed:0,epoch:0}}catch{return null}}close(){this._open&&(this.db.close(),this._open=!1)}isOpen(){return this._open}path(){return this._path}embedKernel(e){return this.ensureOpen(),this.db.embedKernel(0,99,0,e,0,"")}extractKernel(){return this.ensureOpen(),this.db.extractKernel()}verifyWitness(){this.ensureOpen();let e=this.tryNative("verifyWitness");return e?{valid:e.valid??!0,totalEntries:e.totalEntries??0,errors:Array.isArray(e.errors)?e.errors:[]}:{valid:!0,totalEntries:0,errors:[]}}sign(e){this.ensureOpen();let t=this.tryNative("sign",e);return typeof t=="string"?t:null}fileId(){this.ensureOpen();let e=this.tryNative("fileId");return typeof e=="string"?e:null}parentId(){this.ensureOpen();let e=this.tryNative("parentId");return typeof e=="string"?e:null}lineageDepth(){this.ensureOpen();let e=this.tryNative("lineageDepth");return typeof e=="number"?e:0}indexStats(){let e=this.status();return{totalVectors:e.totalVectors,dimension:this._dimension,totalSegments:e.totalSegments,fileSizeBytes:e.fileSizeBytes,epoch:e.epoch,witnessValid:e.witnessValid,witnessEntries:e.witnessEntries,idMapSize:this.strToNum.size}}freeze(){this.ensureOpen();let e=this.tryNative("freeze");return typeof e=="number"?e:0}derive(e){this.ensureOpen();let t=c();if(typeof this.db.derive=="function")try{let n=this.db.derive(e),i=new Map(this.strToNum),r=new Map(this.numToStr);return b(e,i,this.nextLabel),new s(n,e,this._dimension,i,r,this.nextLabel)}catch{}return this.fork(e)}ensureOpen(){if(!this._open)throw new Error("RVF database is closed")}tryNative(e,...t){if(typeof this.db[e]!="function")return null;try{return this.db[e](...t)}catch{return null}}persistIdMap(){b(this._path,this.strToNum,this.nextLabel)}}});export{$ as a,G as b,U as c,X as d,Z as e,P as f};
@@ -1,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.15.16");process.exit(0)}
2
- import{b as we}from"./chunk-J442IZLE.js";import{a as Dt}from"./chunk-24QHCVX6.js";import{a as kt,b as St}from"./chunk-PEQDY4BO.js";import{a as Ct,b as bt}from"./chunk-4D4DENG6.js";import{j as _}from"./chunk-LQLPB2T6.js";import{a as ft}from"./chunk-63GMRQ25.js";import{a as Tt,b as Ee,c as vt}from"./chunk-PHT5N7SC.js";import{a as xe}from"./chunk-EA4YQVKS.js";import{b as yt}from"./chunk-N7HL5PHH.js";import{i as C}from"./chunk-HGWXF45W.js";import{B as Ae,w as R}from"./chunk-MO55CVMT.js";import{c as De,d as An}from"./chunk-JDIYMZCQ.js";import{b as I,d as pt}from"./chunk-V5NHZV7S.js";import{a as ht,e as xn}from"./chunk-S75SOOZL.js";import{a as v,c as y,d as f}from"./chunk-LE4QJREF.js";import{a as Dn}from"./chunk-YAPLJR7K.js";import{c as gt}from"./chunk-G5RHFBAY.js";import{R as kn,S as Sn}from"./chunk-L6QSTQME.js";import{a as h,b as Z,e as k}from"./chunk-KNSRL6NO.js";import{b as Y,d as bn,f as mt}from"./chunk-AJMJNQMP.js";function wt(s){let e=[],t=0;if(s.fileCount!==void 0&&(s.fileCount>20?(t+=25,e.push({name:"very-high-file-count",weight:25,description:`Task involves ${s.fileCount} files (>20)`})):s.fileCount>10?(t+=20,e.push({name:"high-file-count",weight:20,description:`Task involves ${s.fileCount} files (>10)`})):s.fileCount>5&&(t+=10,e.push({name:"moderate-file-count",weight:10,description:`Task involves ${s.fileCount} files (>5)`}))),s.domain&&(Mn.includes(s.domain)?(t+=30,e.push({name:"complex-domain",weight:30,description:`Domain '${s.domain}' requires complex reasoning`})):In.includes(s.domain)&&(t+=15,e.push({name:"moderate-domain",weight:15,description:`Domain '${s.domain}' has moderate complexity`}))),s.crossComponent&&(t+=25,e.push({name:"cross-component",weight:25,description:"Task spans multiple components/modules"})),s.priority==="critical"?(t+=25,e.push({name:"critical-priority",weight:25,description:"Critical priority requires careful attention"})):s.priority==="high"&&(t+=15,e.push({name:"high-priority",weight:15,description:"High priority task"})),s.requiredCapabilities){let r=s.requiredCapabilities.filter(a=>Rn.includes(a)).length;if(r>0){let a=Math.min(20,r*10);t+=a,e.push({name:"complex-capabilities",weight:a,description:`Requires ${r} complex capabilit${r===1?"y":"ies"}`})}}s.requiresExternalApis&&(t+=10,e.push({name:"external-apis",weight:10,description:"Requires external API integration"})),s.involvesDatabaseOps&&(t+=10,e.push({name:"database-ops",weight:10,description:"Involves database operations"})),s.timeSensitive&&(t+=5,e.push({name:"time-sensitive",weight:5,description:"Time-sensitive task"})),s.estimatedLinesAffected!==void 0&&(s.estimatedLinesAffected>500?(t+=15,e.push({name:"large-change",weight:15,description:`Estimated ${s.estimatedLinesAffected} lines affected (>500)`})):s.estimatedLinesAffected>200&&(t+=10,e.push({name:"medium-change",weight:10,description:`Estimated ${s.estimatedLinesAffected} lines affected (>200)`}))),(s.type==="security-scan"||s.type==="vulnerability-assessment")&&(t+=20,e.push({name:"security-task",weight:20,description:"Security-related task requires careful analysis"}));let n=t>=S.critical?"critical":t>=S.complex?"complex":t>=S.moderate?"moderate":"simple",i=_n[n];return{complexity:n,recommendedModel:i,factors:e,score:t,timestamp:new Date}}var Mn,In,Rn,S,_n,Mt=Y(()=>{"use strict";Mn=["security-compliance","chaos-resilience","defect-intelligence"],In=["code-intelligence","contract-testing","quality-assessment","learning-optimization"],Rn=["sast","dast","vulnerability","owasp","chaos-testing","resilience","fault-injection","mutation-testing"],S={critical:70,complex:45,moderate:20},_n={critical:"opus",complex:"sonnet",moderate:"sonnet",simple:"haiku"}});var P,_e=Y(()=>{"use strict";P=class{weightsInputHidden;weightsHiddenOutput;biasHidden;biasOutput;learningRate;constructor(e=.01){this.learningRate=e,this.weightsInputHidden=this.xavierInit(4,32),this.weightsHiddenOutput=this.xavierInit(32,3),this.biasHidden=new Float32Array(32),this.biasOutput=new Float32Array(3)}xavierInit(e,t){let n=Math.sqrt(2/(e+t)),i=new Float32Array(e*t);for(let r=0;r<i.length;r++){let a=Math.random(),o=Math.random(),l=Math.sqrt(-2*Math.log(Math.max(a,1e-10)))*Math.cos(2*Math.PI*o);i[r]=l*n}return i}forward(e){if(e.length!==4)throw new Error(`Expected 4 features, got ${e.length}`);let t=new Float32Array(32);for(let i=0;i<32;i++){let r=this.biasHidden[i];for(let a=0;a<4;a++)r+=e[a]*this.weightsInputHidden[a*32+i];t[i]=Math.max(0,r)}let n=new Float32Array(3);for(let i=0;i<3;i++){let r=this.biasOutput[i];for(let a=0;a<32;a++)r+=t[a]*this.weightsHiddenOutput[a*3+i];n[i]=r}return this.softmax(n)}softmax(e){let t=Math.max(...e),n=new Float32Array(e.length),i=0;for(let a=0;a<e.length;a++)n[a]=Math.exp(e[a]-t),i+=n[a];let r=[];for(let a=0;a<e.length;a++)r.push(n[a]/i);return r}updateWeights(e,t,n){let i=new Float32Array(32);for(let c=0;c<32;c++){let u=this.biasHidden[c];for(let d=0;d<4;d++)u+=e[d]*this.weightsInputHidden[d*32+c];i[c]=Math.max(0,u)}let r=new Float32Array(3);for(let c=0;c<3;c++){let u=this.biasOutput[c];for(let d=0;d<32;d++)u+=i[d]*this.weightsHiddenOutput[d*3+c];r[c]=u}let a=this.softmax(r),o=new Float32Array(3);for(let c=0;c<3;c++)o[c]=(c===t?1:0)-a[c],o[c]*=n*this.learningRate;for(let c=0;c<32;c++)for(let u=0;u<3;u++)this.weightsHiddenOutput[c*3+u]+=i[c]*o[u];for(let c=0;c<3;c++)this.biasOutput[c]+=o[c];let l=new Float32Array(32);for(let c=0;c<32;c++){if(i[c]<=0)continue;let u=0;for(let d=0;d<3;d++)u+=o[d]*this.weightsHiddenOutput[c*3+d];l[c]=u}for(let c=0;c<4;c++)for(let u=0;u<32;u++)this.weightsInputHidden[c*32+u]+=e[c]*l[u];for(let c=0;c<32;c++)this.biasHidden[c]+=l[c]}serialize(){return{weightsInputHidden:Array.from(this.weightsInputHidden),weightsHiddenOutput:Array.from(this.weightsHiddenOutput),biasHidden:Array.from(this.biasHidden),biasOutput:Array.from(this.biasOutput)}}deserialize(e){e.weightsInputHidden.length===128&&(this.weightsInputHidden=new Float32Array(e.weightsInputHidden)),e.weightsHiddenOutput.length===96&&(this.weightsHiddenOutput=new Float32Array(e.weightsHiddenOutput)),e.biasHidden.length===32&&(this.biasHidden=new Float32Array(e.biasHidden)),e.biasOutput.length===3&&(this.biasOutput=new Float32Array(e.biasOutput))}}});var Rt={};bn(Rt,{NeuralTinyDancerRouter:()=>J,SimpleNeuralRouter:()=>P,createNeuralTinyDancerRouter:()=>$n});import{performance as It}from"perf_hooks";function $n(s){return new J(s)}var Pn,Fn,Hn,On,Nn,Ln,Qn,Bn,J,_t=Y(()=>{"use strict";Pe();_e();_e();Pn=1e3,Fn=.1,Hn=.2,On=50,Nn=.01,Ln=["haiku","sonnet","opus"],Qn={haiku:0,sonnet:1,opus:2},Bn={"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},J=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 L(e),this.neuralNet=new P(e.learningRate??Nn),this.circuitBreakerThreshold=e.circuitBreakerThreshold??Hn,this.shadowModeDecisionLimit=e.shadowModeDecisions??Pn,this.shadowModeMaxDisagreement=e.shadowModeMaxDisagreement??Fn,e.forceShadowMode!==void 0?(this.shadowModeActive=e.forceShadowMode,this.neuralPrimary=!e.forceShadowMode):(this.shadowModeActive=!0,this.neuralPrimary=!1),this.tryLoadNativeRouter()}tryLoadNativeRouter(){this.nativeRouterAvailable=!1}async route(e){let t=It.now(),n=await this.ruleRouter.route(e);if(this.circuitBreakerTripped)return n;let i=this.extractFeatures(e,n.classification),r;try{r=this.neuralNet.forward(i)}catch{return this.tripCircuitBreaker(),n}let a=this.argmax(r),o=Ln[a],l=r[a];if(this.totalNeuralDecisions++,this.shadowModeActive){let m=n.model===o;return m||this.shadowDisagreements++,this.shadowDecisions.push({taskDescription:e.description.slice(0,100),ruleDecision:n.model,neuralDecision:o,agreed:m,neuralConfidence:l,timestamp:new Date}),this.evaluateShadowModeExit(),n}let c=It.now()-t,u=this.computeEmpiricalConfidenceBounds(r);return l<.3||u.calibrationScore>.8?n:{model:o,confidence:l,uncertainty:1-l,triggerMultiModel:n.triggerMultiModel,triggerHumanReview:n.triggerHumanReview,complexity:n.complexity,classification:n.classification,latencyMs:c,reasoning:this.buildNeuralReasoning(o,l,r,n,u)}}extractFeatures(e,t){let n=Math.min(1,t.score/100),i=e.description.length,r=e.context?.code?.length??0,a=(i+r)/4,o=Math.min(1,a/1e4),l=e.domain??"",c=Bn[l]??.25,u=this.domainSuccessRates.get(l),d=u?u.success/Math.max(1,u.total):.7;return[n,o,c,d]}recordNeuralOutcome(e,t,n,i=n?1:0,r=t.model,a=0){this.ruleRouter.recordOutcome(e,t,n,i,r,a);let o=e.domain??"unknown",l=this.domainSuccessRates.get(o)??{success:0,total:0};l.total++,n&&l.success++,this.domainSuccessRates.set(o,l),this.recentOutcomes.push(n),this.recentOutcomes.length>On&&this.recentOutcomes.shift(),this.checkCircuitBreaker();let c=this.extractFeatures(e,t.classification),u=Qn[r],d=(i-.5)*2;try{this.neuralNet.updateWeights(c,u,d),this.totalWeightUpdates++}catch{}let m=this.neuralNet.forward(c),p=this.argmax(m),T=1-m[u];this.calibrationScores.push(T),this.calibrationScores.length>this.maxCalibrationScores&&this.calibrationScores.shift()}computeEmpiricalConfidenceBounds(e){let n=Math.max(...e),i=1-n;if(this.calibrationScores.length<10)return{lower:0,upper:1,coverageLevel:.9,calibrationScore:i};let r=[...this.calibrationScores].sort((l,c)=>l-c),a=Math.ceil(.9*r.length)-1,o=r[Math.min(a,r.length-1)];return{lower:Math.max(0,n-o),upper:Math.min(1,n+o),coverageLevel:.9,calibrationScore:i}}computeConformalBounds(e){return this.computeEmpiricalConfidenceBounds(e)}evaluateShadowModeExit(){if(!this.shadowModeActive||this.config.forceShadowMode===!0)return;let e=this.shadowDecisions.length;if(e<this.shadowModeDecisionLimit)return;this.shadowDisagreements/e<=this.shadowModeMaxDisagreement&&(this.shadowModeActive=!1,this.neuralPrimary=!0)}checkCircuitBreaker(){if(this.recentOutcomes.length<10)return;let t=this.recentOutcomes.filter(n=>!n).length/this.recentOutcomes.length;t>this.circuitBreakerThreshold?this.tripCircuitBreaker():this.circuitBreakerTripped&&t<this.circuitBreakerThreshold*.5&&(this.circuitBreakerTripped=!1)}tripCircuitBreaker(){this.circuitBreakerTripped=!0,this.neuralPrimary=!1}buildNeuralReasoning(e,t,n,i,r){let a=[];return a.push(`[Neural] Routing to ${e.toUpperCase()}`),a.push(`with ${(t*100).toFixed(0)}% neural confidence.`),a.push(`Tier probabilities: haiku=${(n[0]*100).toFixed(0)}%,`),a.push(`sonnet=${(n[1]*100).toFixed(0)}%,`),a.push(`opus=${(n[2]*100).toFixed(0)}%.`),e!==i.model&&a.push(`Rule-based would choose ${i.model.toUpperCase()}.`),a.push(`Empirical bounds: [${r.lower.toFixed(2)}, ${r.upper.toFixed(2)}]`),a.push(`at ${(r.coverageLevel*100).toFixed(0)}% coverage.`),a.join(" ")}argmax(e){let t=0,n=e[0];for(let i=1;i<e.length;i++)e[i]>n&&(n=e[i],t=i);return t}getNeuralStats(){let e=this.shadowDecisions.length,t=e>0?this.shadowDisagreements/e:0,n=this.recentOutcomes.filter(r=>!r).length,i=this.recentOutcomes.length>0?n/this.recentOutcomes.length:0;return{shadowModeActive:this.shadowModeActive,shadowDecisions:e,disagreementRate:t,circuitBreakerTripped:this.circuitBreakerTripped,recentErrorRate:i,totalNeuralDecisions:this.totalNeuralDecisions,totalWeightUpdates:this.totalWeightUpdates,neuralPrimary:this.neuralPrimary}}getShadowDecisionLogs(){return this.shadowDecisions}getRuleRouter(){return this.ruleRouter}getNeuralNet(){return this.neuralNet}isNativeRouterAvailable(){return this.nativeRouterAvailable}isShadowModeActive(){return this.shadowModeActive}isNeuralPrimary(){return this.neuralPrimary}isCircuitBreakerTripped(){return this.circuitBreakerTripped}resetCircuitBreaker(){this.circuitBreakerTripped=!1,this.recentOutcomes=[]}getStats(){return this.ruleRouter.getStats()}getConfig(){return this.ruleRouter.getConfig()}reset(){this.ruleRouter.reset(),this.shadowDecisions=[],this.shadowDisagreements=0,this.circuitBreakerTripped=!1,this.recentOutcomes=[],this.totalNeuralDecisions=0,this.totalWeightUpdates=0,this.calibrationScores=[],this.domainSuccessRates.clear(),this.config.forceShadowMode!==void 0?(this.shadowModeActive=this.config.forceShadowMode,this.neuralPrimary=!this.config.forceShadowMode):(this.shadowModeActive=!0,this.neuralPrimary=!1)}}});import{performance as Pt}from"perf_hooks";function Ft(s){try{let{getRuVectorFeatureFlags:e}=(Sn(),mt(kn));if(e().useNeuralRouting){let{NeuralTinyDancerRouter:n}=(_t(),mt(Rt));return new n(s)}}catch(e){process.env.DEBUG&&console.debug("[Router] Neural router unavailable, using rule-based:",e instanceof Error?e.message:e)}return new L(s)}var L,Pe=Y(()=>{"use strict";Mt();L=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=Pt.now(),n=wt(e),i=this.calculateConfidence(n),r=1-i,a=this.isSecurityTask(e),o=a&&i<this.securityConfidenceThreshold||i<this.confidenceThreshold&&n.complexity!=="simple",l=r>this.uncertaintyThreshold||a&&n.complexity==="critical",c=Pt.now()-t,u=this.buildReasoning(n,i,a,o,l),d={model:n.recommendedModel,confidence:i,uncertainty:r,triggerMultiModel:o,triggerHumanReview:l,complexity:n.complexity,classification:n,latencyMs:c,reasoning:u};return this.updateStats(d),this.verbose&&console.log(`[TinyDancer] Route: ${n.recommendedModel} (complexity=${n.complexity}, confidence=${(i*100).toFixed(1)}%)`),d}calculateConfidence(e){let{score:t,complexity:n}=e;if(n==="simple"&&t<10)return .9;if(n==="critical"&&t>85)return .92;let i=[S.moderate,S.complex,S.critical],r=1/0;for(let d of i){let m=Math.abs(t-d);m<r&&(r=m)}let a=.55,o=.35,l=Math.min(r/25,1),c=a+l*o,u=n!=="simple"?Math.min(.05,e.factors.length*.01):0;return Math.min(.95,c+u)}isSecurityTask(e){let t=e;if(t.type==="security-scan"||t.type==="vulnerability-assessment"||e.domain==="security-compliance")return!0;let n=["sast","dast","vulnerability","owasp","security-scanning"];if(e.requiredCapabilities?.some(a=>n.includes(a)))return!0;let i=["security","vulnerability","cve","owasp","exploit","injection"],r=e.description.toLowerCase();return!!i.some(a=>r.includes(a))}buildReasoning(e,t,n,i,r){let a=[];if(a.push(`Routing to ${e.recommendedModel.toUpperCase()}`),a.push(`(complexity: ${e.complexity}, score: ${e.score})`),a.push(`with ${(t*100).toFixed(0)}% confidence.`),e.factors.length>0){let o=e.factors.slice(0,3).map(l=>l.name).join(", ");a.push(`Key factors: ${o}.`)}return n&&a.push("Security-sensitive task detected."),i&&a.push("Multi-model verification recommended due to uncertainty."),r&&a.push("Human review flagged due to high uncertainty or criticality."),a.join(" ")}updateStats(e){this.totalRouted++,this.routesByModel[e.model]++,this.routesByComplexity[e.complexity]++,this.totalConfidence+=e.confidence,this.totalLatencyMs+=e.latencyMs,e.triggerMultiModel&&this.multiModelTriggers++,e.triggerHumanReview&&this.humanReviewTriggers++}recordOutcome(e,t,n,i=n?1:0,r=t.model,a=0){if(!this.enableLearning)return;let o={task:e,routeResult:t,success:n,qualityScore:i,actualModelUsed:r,durationMs:a,timestamp:new Date};this.outcomes.push(o),this.outcomes.length>this.maxOutcomes&&this.outcomes.shift(),this.verbose&&console.log(`[TinyDancer] Recorded outcome: success=${n}, quality=${(i*100).toFixed(0)}%, model=${r}`)}getStats(){return{totalRouted:this.totalRouted,routesByModel:{...this.routesByModel},routesByComplexity:{...this.routesByComplexity},multiModelTriggers:this.multiModelTriggers,advisorConsultations:this.advisorConsultations,humanReviewTriggers:this.humanReviewTriggers,avgConfidence:this.totalRouted>0?this.totalConfidence/this.totalRouted:0,avgLatencyMs:this.totalRouted>0?this.totalLatencyMs/this.totalRouted:0,outcomesRecorded:this.outcomes.length}}getOutcomes(){return this.outcomes}getSuccessRateByModel(){let e={haiku:{success:0,total:0},sonnet:{success:0,total:0},opus:{success:0,total:0}};for(let t of this.outcomes){let n=t.actualModelUsed;e[n].total++,t.success&&e[n].success++}return{haiku:e.haiku.total>0?e.haiku.success/e.haiku.total:0,sonnet:e.sonnet.total>0?e.sonnet.success/e.sonnet.total:0,opus:e.opus.total>0?e.opus.success/e.opus.total:0}}reset(){this.totalRouted=0,this.routesByModel={haiku:0,sonnet:0,opus:0},this.routesByComplexity={simple:0,moderate:0,complex:0,critical:0},this.multiModelTriggers=0,this.advisorConsultations=0,this.humanReviewTriggers=0,this.totalConfidence=0,this.totalLatencyMs=0,this.outcomes=[]}getConfig(){return{confidenceThreshold:this.confidenceThreshold,uncertaintyThreshold:this.uncertaintyThreshold,securityConfidenceThreshold:this.securityConfidenceThreshold,enableLearning:this.enableLearning,verbose:this.verbose}}}});import{randomUUID as At}from"node:crypto";var En={enableConsoleLog:!0,maxEntries:1e3,logPrefix:"[TASK]"},X=class{entries=[];config;generation=At();recordedEntries=0;droppedEntries=0;constructor(e={}){if(this.config={...En,...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}`:"",a=n?.domain?` (${n.domain})`:"";console.log(`${this.config.logPrefix} ${e.toUpperCase()} ${t}${r}${a}`)}}logSubmit(e,t){this.log("submit",e,{details:t})}logAssign(e,t,n){this.log("assign",e,{agentId:t,domain:n})}logReassign(e,t,n,i){this.log("reassign",e,{agentId:n,domain:i,details:{fromAgent:t}})}logComplete(e,t){this.log("complete",e,{agentId:t})}logFail(e,t,n){this.log("fail",e,{agentId:t,details:n?{error:n}:void 0})}logCancel(e){this.log("cancel",e)}logSteal(e,t,n){this.log("steal",e,{domain:n,details:{fromDomain:t}})}logQueue(e,t){this.log("queue",e,{details:{position:t}})}logDequeue(e){this.log("dequeue",e)}getEntries(e){let t=[...this.entries];e&&(e.operation&&(t=t.filter(i=>i.operation===e.operation)),e.taskId&&(t=t.filter(i=>i.taskId===e.taskId)),e.agentId&&(t=t.filter(i=>i.agentId===e.agentId)),e.domain&&(t=t.filter(i=>i.domain===e.domain)),e.fromTimestamp&&(t=t.filter(i=>i.timestamp>=e.fromTimestamp)),e.toTimestamp&&(t=t.filter(i=>i.timestamp<=e.toTimestamp)));let n=e?.limit??t.length;return 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=At(),this.recordedEntries=0,this.droppedEntries=0}};function Me(s){return new X(s)}Ae();pt();var Ie=class{memory;initialized=!1;constructor(e){this.memory=e??R()}async initialize(){this.initialized||(this.memory.isInitialized()||await this.memory.initialize(),this.initialized=!0)}async saveSnapshot(e){this.ensureInitialized();let t=C(),n=this.memory.getDatabase();return await this.memory.writeWhenUnlocked(()=>n.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.17");process.exit(0)}
2
+ import{b as we}from"./chunk-MGZ6XZHU.js";import{a as Dt}from"./chunk-P3D7SEHW.js";import{a as kt,b as St}from"./chunk-PCL5JRKN.js";import{a as Ct,b as bt}from"./chunk-776K4ZLE.js";import{j as _}from"./chunk-RKCN4B26.js";import{a as ft}from"./chunk-74MDUIAZ.js";import{a as Tt,b as Ee,c as vt}from"./chunk-MVVVGQJ6.js";import{a as xe}from"./chunk-XFTX3KLE.js";import{b as yt}from"./chunk-IKB3M7OF.js";import{i as C}from"./chunk-XPTCQKVE.js";import{C as Ae,w as R}from"./chunk-NZJVDOUN.js";import{b as I,d as pt}from"./chunk-CMN7PU2H.js";import{a as ht,e as xn}from"./chunk-YKRLUTK7.js";import{c as De,d as An}from"./chunk-LRKLATSH.js";import{a as v,c as y,d as f}from"./chunk-REY52O7J.js";import{a as Dn}from"./chunk-TIVKDIF7.js";import{c as gt}from"./chunk-DS5IFRY6.js";import{R as kn,S as Sn}from"./chunk-JHKKIJT2.js";import{a as h,b as Z,e as k}from"./chunk-J7Q5TXFZ.js";import{b as Y,d as bn,f as mt}from"./chunk-Z7SKUC6P.js";function wt(s){let e=[],t=0;if(s.fileCount!==void 0&&(s.fileCount>20?(t+=25,e.push({name:"very-high-file-count",weight:25,description:`Task involves ${s.fileCount} files (>20)`})):s.fileCount>10?(t+=20,e.push({name:"high-file-count",weight:20,description:`Task involves ${s.fileCount} files (>10)`})):s.fileCount>5&&(t+=10,e.push({name:"moderate-file-count",weight:10,description:`Task involves ${s.fileCount} files (>5)`}))),s.domain&&(Mn.includes(s.domain)?(t+=30,e.push({name:"complex-domain",weight:30,description:`Domain '${s.domain}' requires complex reasoning`})):In.includes(s.domain)&&(t+=15,e.push({name:"moderate-domain",weight:15,description:`Domain '${s.domain}' has moderate complexity`}))),s.crossComponent&&(t+=25,e.push({name:"cross-component",weight:25,description:"Task spans multiple components/modules"})),s.priority==="critical"?(t+=25,e.push({name:"critical-priority",weight:25,description:"Critical priority requires careful attention"})):s.priority==="high"&&(t+=15,e.push({name:"high-priority",weight:15,description:"High priority task"})),s.requiredCapabilities){let r=s.requiredCapabilities.filter(a=>Rn.includes(a)).length;if(r>0){let a=Math.min(20,r*10);t+=a,e.push({name:"complex-capabilities",weight:a,description:`Requires ${r} complex capabilit${r===1?"y":"ies"}`})}}s.requiresExternalApis&&(t+=10,e.push({name:"external-apis",weight:10,description:"Requires external API integration"})),s.involvesDatabaseOps&&(t+=10,e.push({name:"database-ops",weight:10,description:"Involves database operations"})),s.timeSensitive&&(t+=5,e.push({name:"time-sensitive",weight:5,description:"Time-sensitive task"})),s.estimatedLinesAffected!==void 0&&(s.estimatedLinesAffected>500?(t+=15,e.push({name:"large-change",weight:15,description:`Estimated ${s.estimatedLinesAffected} lines affected (>500)`})):s.estimatedLinesAffected>200&&(t+=10,e.push({name:"medium-change",weight:10,description:`Estimated ${s.estimatedLinesAffected} lines affected (>200)`}))),(s.type==="security-scan"||s.type==="vulnerability-assessment")&&(t+=20,e.push({name:"security-task",weight:20,description:"Security-related task requires careful analysis"}));let n=t>=S.critical?"critical":t>=S.complex?"complex":t>=S.moderate?"moderate":"simple",i=_n[n];return{complexity:n,recommendedModel:i,factors:e,score:t,timestamp:new Date}}var Mn,In,Rn,S,_n,Mt=Y(()=>{"use strict";Mn=["security-compliance","chaos-resilience","defect-intelligence"],In=["code-intelligence","contract-testing","quality-assessment","learning-optimization"],Rn=["sast","dast","vulnerability","owasp","chaos-testing","resilience","fault-injection","mutation-testing"],S={critical:70,complex:45,moderate:20},_n={critical:"opus",complex:"sonnet",moderate:"sonnet",simple:"haiku"}});var P,_e=Y(()=>{"use strict";P=class{weightsInputHidden;weightsHiddenOutput;biasHidden;biasOutput;learningRate;constructor(e=.01){this.learningRate=e,this.weightsInputHidden=this.xavierInit(4,32),this.weightsHiddenOutput=this.xavierInit(32,3),this.biasHidden=new Float32Array(32),this.biasOutput=new Float32Array(3)}xavierInit(e,t){let n=Math.sqrt(2/(e+t)),i=new Float32Array(e*t);for(let r=0;r<i.length;r++){let a=Math.random(),o=Math.random(),l=Math.sqrt(-2*Math.log(Math.max(a,1e-10)))*Math.cos(2*Math.PI*o);i[r]=l*n}return i}forward(e){if(e.length!==4)throw new Error(`Expected 4 features, got ${e.length}`);let t=new Float32Array(32);for(let i=0;i<32;i++){let r=this.biasHidden[i];for(let a=0;a<4;a++)r+=e[a]*this.weightsInputHidden[a*32+i];t[i]=Math.max(0,r)}let n=new Float32Array(3);for(let i=0;i<3;i++){let r=this.biasOutput[i];for(let a=0;a<32;a++)r+=t[a]*this.weightsHiddenOutput[a*3+i];n[i]=r}return this.softmax(n)}softmax(e){let t=Math.max(...e),n=new Float32Array(e.length),i=0;for(let a=0;a<e.length;a++)n[a]=Math.exp(e[a]-t),i+=n[a];let r=[];for(let a=0;a<e.length;a++)r.push(n[a]/i);return r}updateWeights(e,t,n){let i=new Float32Array(32);for(let c=0;c<32;c++){let u=this.biasHidden[c];for(let d=0;d<4;d++)u+=e[d]*this.weightsInputHidden[d*32+c];i[c]=Math.max(0,u)}let r=new Float32Array(3);for(let c=0;c<3;c++){let u=this.biasOutput[c];for(let d=0;d<32;d++)u+=i[d]*this.weightsHiddenOutput[d*3+c];r[c]=u}let a=this.softmax(r),o=new Float32Array(3);for(let c=0;c<3;c++)o[c]=(c===t?1:0)-a[c],o[c]*=n*this.learningRate;for(let c=0;c<32;c++)for(let u=0;u<3;u++)this.weightsHiddenOutput[c*3+u]+=i[c]*o[u];for(let c=0;c<3;c++)this.biasOutput[c]+=o[c];let l=new Float32Array(32);for(let c=0;c<32;c++){if(i[c]<=0)continue;let u=0;for(let d=0;d<3;d++)u+=o[d]*this.weightsHiddenOutput[c*3+d];l[c]=u}for(let c=0;c<4;c++)for(let u=0;u<32;u++)this.weightsInputHidden[c*32+u]+=e[c]*l[u];for(let c=0;c<32;c++)this.biasHidden[c]+=l[c]}serialize(){return{weightsInputHidden:Array.from(this.weightsInputHidden),weightsHiddenOutput:Array.from(this.weightsHiddenOutput),biasHidden:Array.from(this.biasHidden),biasOutput:Array.from(this.biasOutput)}}deserialize(e){e.weightsInputHidden.length===128&&(this.weightsInputHidden=new Float32Array(e.weightsInputHidden)),e.weightsHiddenOutput.length===96&&(this.weightsHiddenOutput=new Float32Array(e.weightsHiddenOutput)),e.biasHidden.length===32&&(this.biasHidden=new Float32Array(e.biasHidden)),e.biasOutput.length===3&&(this.biasOutput=new Float32Array(e.biasOutput))}}});var Rt={};bn(Rt,{NeuralTinyDancerRouter:()=>J,SimpleNeuralRouter:()=>P,createNeuralTinyDancerRouter:()=>$n});import{performance as It}from"perf_hooks";function $n(s){return new J(s)}var Pn,Fn,Hn,On,Nn,Ln,Qn,Bn,J,_t=Y(()=>{"use strict";Pe();_e();_e();Pn=1e3,Fn=.1,Hn=.2,On=50,Nn=.01,Ln=["haiku","sonnet","opus"],Qn={haiku:0,sonnet:1,opus:2},Bn={"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},J=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 L(e),this.neuralNet=new P(e.learningRate??Nn),this.circuitBreakerThreshold=e.circuitBreakerThreshold??Hn,this.shadowModeDecisionLimit=e.shadowModeDecisions??Pn,this.shadowModeMaxDisagreement=e.shadowModeMaxDisagreement??Fn,e.forceShadowMode!==void 0?(this.shadowModeActive=e.forceShadowMode,this.neuralPrimary=!e.forceShadowMode):(this.shadowModeActive=!0,this.neuralPrimary=!1),this.tryLoadNativeRouter()}tryLoadNativeRouter(){this.nativeRouterAvailable=!1}async route(e){let t=It.now(),n=await this.ruleRouter.route(e);if(this.circuitBreakerTripped)return n;let i=this.extractFeatures(e,n.classification),r;try{r=this.neuralNet.forward(i)}catch{return this.tripCircuitBreaker(),n}let a=this.argmax(r),o=Ln[a],l=r[a];if(this.totalNeuralDecisions++,this.shadowModeActive){let m=n.model===o;return m||this.shadowDisagreements++,this.shadowDecisions.push({taskDescription:e.description.slice(0,100),ruleDecision:n.model,neuralDecision:o,agreed:m,neuralConfidence:l,timestamp:new Date}),this.evaluateShadowModeExit(),n}let c=It.now()-t,u=this.computeEmpiricalConfidenceBounds(r);return l<.3||u.calibrationScore>.8?n:{model:o,confidence:l,uncertainty:1-l,triggerMultiModel:n.triggerMultiModel,triggerHumanReview:n.triggerHumanReview,complexity:n.complexity,classification:n.classification,latencyMs:c,reasoning:this.buildNeuralReasoning(o,l,r,n,u)}}extractFeatures(e,t){let n=Math.min(1,t.score/100),i=e.description.length,r=e.context?.code?.length??0,a=(i+r)/4,o=Math.min(1,a/1e4),l=e.domain??"",c=Bn[l]??.25,u=this.domainSuccessRates.get(l),d=u?u.success/Math.max(1,u.total):.7;return[n,o,c,d]}recordNeuralOutcome(e,t,n,i=n?1:0,r=t.model,a=0){this.ruleRouter.recordOutcome(e,t,n,i,r,a);let o=e.domain??"unknown",l=this.domainSuccessRates.get(o)??{success:0,total:0};l.total++,n&&l.success++,this.domainSuccessRates.set(o,l),this.recentOutcomes.push(n),this.recentOutcomes.length>On&&this.recentOutcomes.shift(),this.checkCircuitBreaker();let c=this.extractFeatures(e,t.classification),u=Qn[r],d=(i-.5)*2;try{this.neuralNet.updateWeights(c,u,d),this.totalWeightUpdates++}catch{}let m=this.neuralNet.forward(c),p=this.argmax(m),T=1-m[u];this.calibrationScores.push(T),this.calibrationScores.length>this.maxCalibrationScores&&this.calibrationScores.shift()}computeEmpiricalConfidenceBounds(e){let n=Math.max(...e),i=1-n;if(this.calibrationScores.length<10)return{lower:0,upper:1,coverageLevel:.9,calibrationScore:i};let r=[...this.calibrationScores].sort((l,c)=>l-c),a=Math.ceil(.9*r.length)-1,o=r[Math.min(a,r.length-1)];return{lower:Math.max(0,n-o),upper:Math.min(1,n+o),coverageLevel:.9,calibrationScore:i}}computeConformalBounds(e){return this.computeEmpiricalConfidenceBounds(e)}evaluateShadowModeExit(){if(!this.shadowModeActive||this.config.forceShadowMode===!0)return;let e=this.shadowDecisions.length;if(e<this.shadowModeDecisionLimit)return;this.shadowDisagreements/e<=this.shadowModeMaxDisagreement&&(this.shadowModeActive=!1,this.neuralPrimary=!0)}checkCircuitBreaker(){if(this.recentOutcomes.length<10)return;let t=this.recentOutcomes.filter(n=>!n).length/this.recentOutcomes.length;t>this.circuitBreakerThreshold?this.tripCircuitBreaker():this.circuitBreakerTripped&&t<this.circuitBreakerThreshold*.5&&(this.circuitBreakerTripped=!1)}tripCircuitBreaker(){this.circuitBreakerTripped=!0,this.neuralPrimary=!1}buildNeuralReasoning(e,t,n,i,r){let a=[];return a.push(`[Neural] Routing to ${e.toUpperCase()}`),a.push(`with ${(t*100).toFixed(0)}% neural confidence.`),a.push(`Tier probabilities: haiku=${(n[0]*100).toFixed(0)}%,`),a.push(`sonnet=${(n[1]*100).toFixed(0)}%,`),a.push(`opus=${(n[2]*100).toFixed(0)}%.`),e!==i.model&&a.push(`Rule-based would choose ${i.model.toUpperCase()}.`),a.push(`Empirical bounds: [${r.lower.toFixed(2)}, ${r.upper.toFixed(2)}]`),a.push(`at ${(r.coverageLevel*100).toFixed(0)}% coverage.`),a.join(" ")}argmax(e){let t=0,n=e[0];for(let i=1;i<e.length;i++)e[i]>n&&(n=e[i],t=i);return t}getNeuralStats(){let e=this.shadowDecisions.length,t=e>0?this.shadowDisagreements/e:0,n=this.recentOutcomes.filter(r=>!r).length,i=this.recentOutcomes.length>0?n/this.recentOutcomes.length:0;return{shadowModeActive:this.shadowModeActive,shadowDecisions:e,disagreementRate:t,circuitBreakerTripped:this.circuitBreakerTripped,recentErrorRate:i,totalNeuralDecisions:this.totalNeuralDecisions,totalWeightUpdates:this.totalWeightUpdates,neuralPrimary:this.neuralPrimary}}getShadowDecisionLogs(){return this.shadowDecisions}getRuleRouter(){return this.ruleRouter}getNeuralNet(){return this.neuralNet}isNativeRouterAvailable(){return this.nativeRouterAvailable}isShadowModeActive(){return this.shadowModeActive}isNeuralPrimary(){return this.neuralPrimary}isCircuitBreakerTripped(){return this.circuitBreakerTripped}resetCircuitBreaker(){this.circuitBreakerTripped=!1,this.recentOutcomes=[]}getStats(){return this.ruleRouter.getStats()}getConfig(){return this.ruleRouter.getConfig()}reset(){this.ruleRouter.reset(),this.shadowDecisions=[],this.shadowDisagreements=0,this.circuitBreakerTripped=!1,this.recentOutcomes=[],this.totalNeuralDecisions=0,this.totalWeightUpdates=0,this.calibrationScores=[],this.domainSuccessRates.clear(),this.config.forceShadowMode!==void 0?(this.shadowModeActive=this.config.forceShadowMode,this.neuralPrimary=!this.config.forceShadowMode):(this.shadowModeActive=!0,this.neuralPrimary=!1)}}});import{performance as Pt}from"perf_hooks";function Ft(s){try{let{getRuVectorFeatureFlags:e}=(Sn(),mt(kn));if(e().useNeuralRouting){let{NeuralTinyDancerRouter:n}=(_t(),mt(Rt));return new n(s)}}catch(e){process.env.DEBUG&&console.debug("[Router] Neural router unavailable, using rule-based:",e instanceof Error?e.message:e)}return new L(s)}var L,Pe=Y(()=>{"use strict";Mt();L=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=Pt.now(),n=wt(e),i=this.calculateConfidence(n),r=1-i,a=this.isSecurityTask(e),o=a&&i<this.securityConfidenceThreshold||i<this.confidenceThreshold&&n.complexity!=="simple",l=r>this.uncertaintyThreshold||a&&n.complexity==="critical",c=Pt.now()-t,u=this.buildReasoning(n,i,a,o,l),d={model:n.recommendedModel,confidence:i,uncertainty:r,triggerMultiModel:o,triggerHumanReview:l,complexity:n.complexity,classification:n,latencyMs:c,reasoning:u};return this.updateStats(d),this.verbose&&console.log(`[TinyDancer] Route: ${n.recommendedModel} (complexity=${n.complexity}, confidence=${(i*100).toFixed(1)}%)`),d}calculateConfidence(e){let{score:t,complexity:n}=e;if(n==="simple"&&t<10)return .9;if(n==="critical"&&t>85)return .92;let i=[S.moderate,S.complex,S.critical],r=1/0;for(let d of i){let m=Math.abs(t-d);m<r&&(r=m)}let a=.55,o=.35,l=Math.min(r/25,1),c=a+l*o,u=n!=="simple"?Math.min(.05,e.factors.length*.01):0;return Math.min(.95,c+u)}isSecurityTask(e){let t=e;if(t.type==="security-scan"||t.type==="vulnerability-assessment"||e.domain==="security-compliance")return!0;let n=["sast","dast","vulnerability","owasp","security-scanning"];if(e.requiredCapabilities?.some(a=>n.includes(a)))return!0;let i=["security","vulnerability","cve","owasp","exploit","injection"],r=e.description.toLowerCase();return!!i.some(a=>r.includes(a))}buildReasoning(e,t,n,i,r){let a=[];if(a.push(`Routing to ${e.recommendedModel.toUpperCase()}`),a.push(`(complexity: ${e.complexity}, score: ${e.score})`),a.push(`with ${(t*100).toFixed(0)}% confidence.`),e.factors.length>0){let o=e.factors.slice(0,3).map(l=>l.name).join(", ");a.push(`Key factors: ${o}.`)}return n&&a.push("Security-sensitive task detected."),i&&a.push("Multi-model verification recommended due to uncertainty."),r&&a.push("Human review flagged due to high uncertainty or criticality."),a.join(" ")}updateStats(e){this.totalRouted++,this.routesByModel[e.model]++,this.routesByComplexity[e.complexity]++,this.totalConfidence+=e.confidence,this.totalLatencyMs+=e.latencyMs,e.triggerMultiModel&&this.multiModelTriggers++,e.triggerHumanReview&&this.humanReviewTriggers++}recordOutcome(e,t,n,i=n?1:0,r=t.model,a=0){if(!this.enableLearning)return;let o={task:e,routeResult:t,success:n,qualityScore:i,actualModelUsed:r,durationMs:a,timestamp:new Date};this.outcomes.push(o),this.outcomes.length>this.maxOutcomes&&this.outcomes.shift(),this.verbose&&console.log(`[TinyDancer] Recorded outcome: success=${n}, quality=${(i*100).toFixed(0)}%, model=${r}`)}getStats(){return{totalRouted:this.totalRouted,routesByModel:{...this.routesByModel},routesByComplexity:{...this.routesByComplexity},multiModelTriggers:this.multiModelTriggers,advisorConsultations:this.advisorConsultations,humanReviewTriggers:this.humanReviewTriggers,avgConfidence:this.totalRouted>0?this.totalConfidence/this.totalRouted:0,avgLatencyMs:this.totalRouted>0?this.totalLatencyMs/this.totalRouted:0,outcomesRecorded:this.outcomes.length}}getOutcomes(){return this.outcomes}getSuccessRateByModel(){let e={haiku:{success:0,total:0},sonnet:{success:0,total:0},opus:{success:0,total:0}};for(let t of this.outcomes){let n=t.actualModelUsed;e[n].total++,t.success&&e[n].success++}return{haiku:e.haiku.total>0?e.haiku.success/e.haiku.total:0,sonnet:e.sonnet.total>0?e.sonnet.success/e.sonnet.total:0,opus:e.opus.total>0?e.opus.success/e.opus.total:0}}reset(){this.totalRouted=0,this.routesByModel={haiku:0,sonnet:0,opus:0},this.routesByComplexity={simple:0,moderate:0,complex:0,critical:0},this.multiModelTriggers=0,this.advisorConsultations=0,this.humanReviewTriggers=0,this.totalConfidence=0,this.totalLatencyMs=0,this.outcomes=[]}getConfig(){return{confidenceThreshold:this.confidenceThreshold,uncertaintyThreshold:this.uncertaintyThreshold,securityConfidenceThreshold:this.securityConfidenceThreshold,enableLearning:this.enableLearning,verbose:this.verbose}}}});import{randomUUID as At}from"node:crypto";var En={enableConsoleLog:!0,maxEntries:1e3,logPrefix:"[TASK]"},X=class{entries=[];config;generation=At();recordedEntries=0;droppedEntries=0;constructor(e={}){if(this.config={...En,...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}`:"",a=n?.domain?` (${n.domain})`:"";console.log(`${this.config.logPrefix} ${e.toUpperCase()} ${t}${r}${a}`)}}logSubmit(e,t){this.log("submit",e,{details:t})}logAssign(e,t,n){this.log("assign",e,{agentId:t,domain:n})}logReassign(e,t,n,i){this.log("reassign",e,{agentId:n,domain:i,details:{fromAgent:t}})}logComplete(e,t){this.log("complete",e,{agentId:t})}logFail(e,t,n){this.log("fail",e,{agentId:t,details:n?{error:n}:void 0})}logCancel(e){this.log("cancel",e)}logSteal(e,t,n){this.log("steal",e,{domain:n,details:{fromDomain:t}})}logQueue(e,t){this.log("queue",e,{details:{position:t}})}logDequeue(e){this.log("dequeue",e)}getEntries(e){let t=[...this.entries];e&&(e.operation&&(t=t.filter(i=>i.operation===e.operation)),e.taskId&&(t=t.filter(i=>i.taskId===e.taskId)),e.agentId&&(t=t.filter(i=>i.agentId===e.agentId)),e.domain&&(t=t.filter(i=>i.domain===e.domain)),e.fromTimestamp&&(t=t.filter(i=>i.timestamp>=e.fromTimestamp)),e.toTimestamp&&(t=t.filter(i=>i.timestamp<=e.toTimestamp)));let n=e?.limit??t.length;return 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=At(),this.recordedEntries=0,this.droppedEntries=0}};function Me(s){return new X(s)}Ae();pt();var Ie=class{memory;initialized=!1;constructor(e){this.memory=e??R()}async initialize(){this.initialized||(this.memory.isInitialized()||await this.memory.initialize(),this.initialized=!0)}async saveSnapshot(e){this.ensureInitialized();let t=C(),n=this.memory.getDatabase();return await this.memory.writeWhenUnlocked(()=>n.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 we}from"./chunk-J442IZLE.js";import{a as Dt}from"./chunk-24QHCVX6.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 we(e);return t.safe?!1:(console.warn(`[CrossPhaseHooks] SSRF blocked: ${t.reason}`),!0)}checkConditions(e,t){return!e||e.length===0?!0:e.every(n=>this.evaluateCondition(n,t))}evaluateCondition(e,t){try{let n=e.split(/\s*(>|<|>=|<=|==|!=)\s*/);if(n.length!==3)return!1;let[i,r,a]=n,o=this.getValueFromPath(t,i),l=isNaN(Number(a))?a:Number(a),c=typeof o=="number"?o:Number(o),u=typeof l=="number"?l:Number(l);switch(r){case">":return c>u;case"<":return c<u;case">=":return c>=u;case"<=":return c<=u;case"==":return o==l;case"!=":return o!=l;default:return!1}}catch{return!1}}getValueFromPath(e,t){return t.split(".").reduce((n,i)=>{if(n&&typeof n=="object"&&Object.hasOwn(n,i))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`)}},rt=null;function rn(s){return rt||(rt=new st(s)),rt}function H(s,e){let t=s.get(e);return t?.status!=="cancelled"?{ignored:!1,settledNow:!1}:t.cancellationResultPending?(s.set(e,{...t,cancellationResultPending:!1}),{ignored:!0,settledNow:!0}):{ignored:!0,settledNow:!1}}function sn(s,e){let t=[];for(let a of e){let o=s.router.subscribeToDoamin(a,async l=>{await Di(s,l)});t.push(o)}let n=s.router.subscribeToEventType("TaskCompleted",async a=>{await Ai(s,a)});t.push(n);let i=s.router.subscribeToEventType("TaskFailed",async a=>{await xi(s,a)});t.push(i);let r=s.router.subscribeToEventType("AgentStatusChanged",async a=>{await Ei(s,a)});return t.push(r),t}async function Di(s,e){s.domainLastActivity.set(e.source,new Date),await s.processQueue()}async function an(s,e){for(let t of e.assignedAgents)await s.agentCoordinator.stop(t)}async function Ai(s,e){let{taskId:t,result:n}=e.payload,i=H(s.tasks,t);if(i.ignored){i.settledNow&&(s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),await s.processQueue());return}let r=s.tasks.get(t);if(r){await an(s,r),(r.status==="running"||r.status==="assigned")&&(s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1));let a=r.startedAt?Date.now()-r.startedAt.getTime():0;s.tasks.set(t,{...r,status:"completed",completedAt:new Date,result:n}),s.tasksCompleted++,s.taskDurations.push(a),s.auditLogger.logComplete(t,r.assignedAgents[0]);try{let o=rn(),l=r.assignedAgents[0];l&&await o.onAgentComplete(l,{taskId:t,taskType:r.task.type,domain:r.assignedDomain,result:n,duration:a})}catch(o){console.warn("[QueenCoordinator] Cross-phase hook error:",o)}try{await _.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(s.domainBreakerRegistry&&r.assignedDomain&&s.domainBreakerRegistry.getBreaker(r.assignedDomain).recordSuccess(),s.traceCollector){let o=s.taskTraceContexts.get(t);o&&(s.traceCollector.completeSpan(o.spanId),s.taskTraceContexts.delete(t))}if(s.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 l=wi(o,t);if(l){let c={taskId:t,agentId:r.assignedAgents[0]||"unknown",domain:r.assignedDomain||"test-generation",type:r.task.type,status:"completed",output:o,metrics:l,duration:a,timestamp:Date.now()};s.taskCompletedHook.onTaskCompleted(c).catch(u=>{console.warn("[QueenCoordinator] Pattern training error:",u)})}}}catch(o){console.warn("[QueenCoordinator] Pattern training setup error:",o)}}await s.processQueue()}async function xi(s,e){let{taskId:t,error:n,callerError:i}=e.payload,r=H(s.tasks,t);if(r.ignored){r.settledNow&&(s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),await s.processQueue());return}let a=s.tasks.get(t);if(a){if(await an(s,a),(a.status==="running"||a.status==="assigned")&&(s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1)),s.domainBreakerRegistry&&a.assignedDomain&&!i&&s.domainBreakerRegistry.getBreaker(a.assignedDomain).recordFailure(new Error(n||"Task failed")),s.traceCollector){let l=s.taskTraceContexts.get(t);l&&(s.traceCollector.failSpan(l.spanId,n||"Task failed"),s.taskTraceContexts.delete(t))}let o=a.task.executionOwner==="caller";if(!i&&!o&&a.retryCount<s.config.taskRetryLimit){s.auditLogger.logFail(t,a.assignedAgents[0],n);let l={...a,status:"queued",retryCount:a.retryCount+1,error:n};s.tasks.set(t,l),s.enqueueTask(a.task)}else{s.tasks.set(t,{...a,status:"failed",completedAt:new Date,error:n}),s.tasksFailed++,s.auditLogger.logFail(t,a.assignedAgents[0],n);try{await _.afterTaskExecution({taskId:t,taskType:a.task.type,agentId:a.assignedAgents[0]||"unknown",domain:a.assignedDomain||"test-generation",priority:a.task.priority},!1,0,0)}catch(l){console.warn("[QueenCoordinator] Governance tracking error:",l)}if(!i&&s.hypothesisManager&&(a.task.priority==="p0"||a.task.priority==="p1"))try{let l=a.assignedDomain||"test-generation",c=s.hypothesisManager.createInvestigation(t,l,`Root cause analysis for ${a.task.type} failure: ${n}`);s.hypothesisManager.addHypothesis(c.id,`Infrastructure failure in domain '${l}' caused task ${t} to fail`,"log-analysis",`${l}-lead`),s.hypothesisManager.addHypothesis(c.id,`Logic/configuration error in task payload caused ${a.task.type} to fail: ${n}`,"code-analysis",a.assignedAgents[0]||"unknown"),console.log(`[QueenCoordinator] Competing hypotheses investigation created: ${c.id}`)}catch(l){console.warn("[QueenCoordinator] Hypothesis creation error:",l)}}}await s.processQueue()}async function Ei(s,e){let{agentId:t,status:n,domain:i}=e.payload;s.domainLastActivity.set(i,new Date),(n==="completed"||n==="failed")&&await s.processQueue()}function wi(s,e){if("metrics"in s&&typeof s.metrics=="object"&&s.metrics!==null){let t=s.metrics;return{testsPassed:typeof t.testsPassed=="number"?t.testsPassed:void 0,testsFailed:typeof t.testsFailed=="number"?t.testsFailed:void 0,coverageChange:typeof t.coverageChange=="number"?t.coverageChange:void 0,securityIssues:typeof t.securityIssues=="number"?t.securityIssues:void 0,performanceMs:typeof t.performanceMs=="number"?t.performanceMs:void 0,linesChanged:typeof t.linesChanged=="number"?t.linesChanged:void 0}}return"testsPassed"in s||"testsFailed"in s?{testsPassed:typeof s.testsPassed=="number"?s.testsPassed:void 0,testsFailed:typeof s.testsFailed=="number"?s.testsFailed:void 0,coverageChange:typeof s.coverageChange=="number"?s.coverageChange:void 0,securityIssues:typeof s.securityIssues=="number"?s.securityIssues:void 0,performanceMs:typeof s.performanceMs=="number"?s.performanceMs:void 0,linesChanged:typeof s.linesChanged=="number"?s.linesChanged:void 0}:(console.error(`[QueenCoordinator] Pattern training skipped for task ${e}: result object has no recognizable metrics shape (keys: ${Object.keys(s).join(", ")})`),null)}function on(s,e,t){let n=s.listAgents({domain:e}),i=n.filter(l=>l.status==="running").length,r=n.filter(l=>l.status==="idle").length,a=n.filter(l=>l.status==="failed").length,o;return a>0&&a>=n.length/2?o="unhealthy":a>0?o="degraded":i>0?o="healthy":o="idle",{status:o,agents:{total:n.length,active:i,idle:r,failed:a},lastActivity:t,errors:[]}}function j(s,e,t){let n=[];for(let i of t){let r=s.get(i);if(!r)n.push(`${i} (domain not loaded)`);else if(!r.executeTask||!r.canHandleTask?.(e)){let a=r.getSupportedTaskTypes?.()??[];n.push(a.length>0?`${i} (supported: ${a.join(", ")})`:i)}}return n}function Mi(s,e){let t=[];for(let[n,i]of s)i.executeTask&&i.canHandleTask?.(e)&&t.push(n);return t}function at(s,e,t){if(e.length>0)return e;let n=E(s);return n.length>0||!t?n:Mi(t,s)}function ve(s,e){return`No handler for task type '${s}' in domain ${e.join("; ")}`}k();k();var ln=St();function ot(s,e,t){let n=s.get(t.priority);n&&kt(n,t,ln);for(let i of t.targetDomains){let r=e.get(i);r&&r.push(t)}}function N(s,e,t){let n=s.get(t.priority);if(n){let i=n.findIndex(r=>r.id===t.id);i!==-1&&n.splice(i,1)}for(let i of t.targetDomains){let r=e.get(i);if(r){let a=r.findIndex(o=>o.id===t.id);a!==-1&&r.splice(a,1)}}}function be(s,e){let t=0;for(let n of["p0","p1","p2","p3"]){let i=s.get(n);if(i){if(n===e.priority){t+=i.findIndex(r=>r.id===e.id);break}t+=i.length}}return t}async function M(s){if(!(s.runningTaskCounter>=s.config.maxConcurrentTasks)){O.set(s.tasks,(O.get(s.tasks)??0)+1);try{do{Ce.delete(s.tasks);for(let e of["p0","p1","p2","p3"]){let t=s.taskQueue.get(e);if(!t||t.length===0)continue;let n=cn(s,t);for(;n;){N(s.taskQueue,s.domainQueues,n),s.runningTaskCounter++;let i;try{i=await Se(s,n)}catch(r){throw s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),r}if(!i.success&&(s.tasks.get(n.id)?.status??"queued")==="queued"&&await ke(s,n,void 0,i.error.message),s.runningTaskCounter>=s.config.maxConcurrentTasks)return;n=cn(s,t)}}}while(Ce.has(s.tasks)&&s.runningTaskCounter<s.config.maxConcurrentTasks)}finally{let e=(O.get(s.tasks)??1)-1;e>0?O.set(s.tasks,e):(O.delete(s.tasks),Ce.delete(s.tasks))}}}var O=new WeakMap,Ce=new WeakSet;async function V(s){if(s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),O.has(s.tasks)){Ce.add(s.tasks);return}M(s).catch(e=>{console.warn("[Queen] Queue drain after a released slot failed:",h(e))})}function cn(s,e){let t=e.shift();for(;t;){let n=s.tasks.get(t.id)?.status;if(n===void 0||n==="queued")return t;N(s.taskQueue,s.domainQueues,t),t=e.shift()}}async function ke(s,e,t,n){s.tasks.set(e.id,{taskId:e.id,task:e,status:"failed",assignedDomain:t,assignedAgents:[],retryCount:s.tasks.get(e.id)?.retryCount??0,error:n,completedAt:new Date}),s.tasksFailed++,s.auditLogger.logFail(e.id,void 0,n),await s.publishEvent("TaskFailed",{taskId:e.id,domain:t,error:n}),await V(s)}function un(s,e){let t=Array.from(s.values());return e&&(e.status&&(t=t.filter(n=>n.status===e.status)),e.domain&&(t=t.filter(n=>n.assignedDomain===e.domain)),e.priority&&(t=t.filter(n=>n.task.priority===e.priority)),e.type&&(t=t.filter(n=>n.task.type===e.type)),e.fromDate&&(t=t.filter(n=>n.task.createdAt>=e.fromDate)),e.toDate&&(t=t.filter(n=>n.task.createdAt<=e.toDate))),t}async function Se(s,e){let t=e.targetDomains.length>0?e.targetDomains:E(e.type);if(t.length===0)return f(new Error(`No domains configured for task type: ${e.type}`));let n,i=1/0;for(let r of t){let a=s.getDomainLoad(r);s.getDomainHealth(r)?.status!=="unhealthy"&&a<i&&(i=a,n=r)}return n?dn(s,e,n):f(new Error("No healthy domain available for task"))}async function dn(s,e,t){if(e.executionOwner!=="caller"&&s.domainPlugins){let c=j(s.domainPlugins,e.type,[t]);if(c.length>0)return Ii(s,e,t,ve(e.type,c))}let n;if(s.tinyDancerRouter){let c={p0:"critical",p1:"high",p2:"normal",p3:"low"},u={description:`${e.type}: ${JSON.stringify(e.payload).slice(0,200)}`,type:e.type,domain:t,priority:Object.hasOwn(c,e.priority)?c[e.priority]:"normal"};n=await s.tinyDancerRouter.route(u),s.config.enableMetrics&&console.log(`[Queen] TinyDancer routing: ${e.type} \u2192 tier=${n.tier}, model=${n.model}, cost=$${n.estimatedCost.toFixed(4)}`)}if(s.domainBreakerRegistry&&!s.domainBreakerRegistry.canExecuteInDomain(t))return f(new Error(`Domain '${t}' circuit breaker is open \u2014 too many recent failures`));if(s.domainTeamManager)try{if(!s.domainTeamManager.getDomainTeam(t)){let u=`${t}-lead`;s.domainTeamManager.createDomainTeam(t,u)}}catch(c){console.warn(`[Queen] Domain team setup for '${t}' failed (continuing):`,c)}let i=n?.tier||"task-worker",r=["task-execution",e.type,...n?[`model:${n.model}`]:[],...n?.triggerMultiModel?["advisor:triggerMultiModel"]:[]],a=await s.requestAgentSpawn(t,i,r,e.id);if(s.tasks.get(e.id)?.status==="cancelled")return a.success&&await s.agentCoordinator.stop(a.value),await V(s),y(e.id);let o=[];a.success&&o.push(a.value);let l={taskId:e.id,task:e,status:"running",assignedDomain:t,assignedAgents:o,startedAt:new Date,retryCount:0};s.tasks.set(e.id,l),s.domainLastActivity.set(t,new Date);for(let c of o)s.auditLogger.logAssign(e.id,c,t);if(await s.publishEvent("TaskAssigned",{taskId:e.id,domain:t,agentIds:o}),e.executionOwner==="caller")return y(e.id);if(s.domainPlugins){let c=s.domainPlugins.get(t);if(c?.executeTask&&c.canHandleTask?.(e.type)){let u={taskId:e.id,taskType:e.type,payload:e.payload,priority:e.priority,timeout:e.timeout,correlationId:e.correlationId},d;try{d=await c.executeTask(u,m=>Ri(s,m))}catch(m){d=f(Z(m))}if(!d.success){let m=H(s.tasks,e.id);return m.ignored?(m.settledNow&&await V(s),y(e.id)):s.tasks.get(e.id)?.status!=="running"?f(d.error):(s.tasks.set(e.id,{...l,status:"failed",error:d.error.message,completedAt:new Date}),s.tasksFailed++,s.auditLogger.logFail(e.id,o[0],d.error.message),await s.publishEvent("TaskFailed",{taskId:e.id,domain:t,error:d.error.message}),await V(s),f(d.error))}return y(e.id)}}return y(e.id)}async function Ii(s,e,t,n){let i=s.taskTraceContexts.get(e.id);return s.traceCollector&&i&&(s.traceCollector.failSpan(i.spanId,n),s.taskTraceContexts.delete(e.id)),await ke(s,e,t,n),y(e.id)}async function mn(s,e,t){let n=s.tasks.get(e.id)?.status;if(n!==void 0&&n!=="queued")return!1;s.runningTaskCounter++;let i;try{i=await dn(s,e,t)}catch(a){throw s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),a}!i.success&&(s.tasks.get(e.id)?.status??"queued")==="queued"&&await ke(s,e,t,i.error.message);let r=s.tasks.get(e.id);return r?.assignedDomain===t&&(r.status==="running"||r.status==="completed")}async function Ri(s,e){let t=s.tasks.get(e.taskId);if(!t){console.warn(`[Queen] Received completion for unknown task: ${e.taskId}`);return}let n=H(s.tasks,e.taskId);if(n.ignored){n.settledNow&&(s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),await M(s));return}let i={...t,status:e.success?"completed":"failed",completedAt:new Date,result:e.data,error:e.error};if(s.tasks.set(e.taskId,i),e.success?(s.tasksCompleted++,s.taskDurations.push(e.duration),s.auditLogger.logComplete(e.taskId,t.assignedAgents[0])):(s.tasksFailed++,s.auditLogger.logFail(e.taskId,t.assignedAgents[0],e.error||"Unknown error")),s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),s.coExecutionRepo&&t.assignedAgents.length>=2)try{s.coExecutionRepo.recordSwarmCoExecution(t.assignedAgents,t.assignedDomain||"unknown",e.success,t.task.type)}catch{}for(let r of t.assignedAgents)await s.agentCoordinator.stop(r);await s.publishEvent(e.success?"TaskCompleted":"TaskFailed",{taskId:e.taskId,domain:t.assignedDomain,result:e.data,error:e.error,duration:e.duration}),await M(s)}function _i(s,e){return E(e.type).includes(s)}function gn(s,e,t){return _i(e,t)?t.executionOwner==="caller"||!s?!0:j(s,t.type,[e]).length===0:!1}k();async function pn(s){let e=0,t=s.getIdleDomains(),n=s.getBusyDomains();if(t.length===0||n.length===0)return 0;n.sort((i,r)=>s.getDomainLoad(r)-s.getDomainLoad(i));for(let i of n){if(t.length===0)break;let r=s.domainQueues.get(i)||[],a=Math.min(r.length,s.config.workStealing.stealBatchSize);for(let o=0;o<a&&t.length>0&&s.availableSlots()>0;o++){let l=r.find(c=>s.canExecuteInDomain(t[0],c));if(l){let c=t.shift();if(s.removeFromQueues(l),!await s.assignTaskToDomain(l,c))continue;s.auditLogger.logSteal(l.id,i,c),e++,s.tasksStolen++,await s.publishEvent("TaskStolen",{taskId:l.id,fromDomain:i,toDomain:c})}}}return e}function ct(s,e){let t=0,n=10,i=setInterval(async()=>{try{await e(),t=0}catch(r){t++;let a=Math.min(1e3*Math.pow(2,t),3e4);if(console.warn(`[QueenCoordinator] Work-stealing failed (attempt ${t}), backing off ${a}ms`,h(r)),t>n){console.error(`[QueenCoordinator] Work-stealing exceeded ${n} consecutive failures, stopping interval`),clearInterval(i);return}await new Promise(o=>setTimeout(o,a))}},s.workStealing.checkInterval);return i}function lt(s){return typeof s.setMinCutBridge=="function"}function hn(s,e){for(let[t,n]of s)lt(n)&&(n.setMinCutBridge(e),console.log(`[QueenCoordinator] MinCut bridge injected into ${t}`))}async function fn(s,e,t){try{let n=await s.get("queen:state");if(n){for(let[i,r]of n.tasks)if(r.status==="queued"){if(r.task.executionOwner==="caller"){e.set(i,{...r,status:"failed",error:"Caller-owned task was interrupted before completion; submit a new request.",completedAt:new Date});continue}e.set(i,r),t(r.task)}}}catch(n){console.debug("[QueenCoordinator] State loading failed:",n instanceof Error?n.message:n)}}async function yn(s,e){let t=Array.from(e.entries()).filter(([,n])=>n.status==="queued");await s.set("queen:state",{tasks:t},{namespace:"queen-coordinator",persist:!0})}function Tn(s){return setInterval(async()=>{let e=s.getMetrics();if(await s.publishEvent("MetricsCollected",{metrics:e}),await s.memory.set(`queen:metrics:${Date.now()}`,e,{ttl:86400,namespace:"queen-coordinator"}),s.dynamicScaler)try{let t=s.getAverageTaskDuration(),n={queueDepth:s.getQueuedTaskCount(),activeAgents:s.getActiveAgentCount(),idleAgents:s.getIdleAgentCount(),avgTaskDurationMs:t,errorRate:s.getTasksReceived()>0?s.getTasksFailed()/s.getTasksReceived():0,throughput:e.uptime>0?s.getTasksCompleted()/(e.uptime/1e3):0,timestamp:Date.now()};s.dynamicScaler.recordMetrics(n);let i=s.dynamicScaler.evaluate();i&&i.action!=="maintain"&&(console.log(`[QueenCoordinator] Dynamic scaler: ${i.action} to ${i.targetAgents} agents \u2014 ${i.reason}`),s.dynamicScaler.execute(i).catch(r=>{console.warn("[QueenCoordinator] Dynamic scaling execution error:",r)}))}catch(t){console.warn("[QueenCoordinator] Dynamic scaler metrics error:",t)}},s.config.metricsInterval)}function ut(s,e,t=36e5){let n=Date.now(),i=0;for(let[a,o]of s)if(o.status==="completed"||o.status==="failed"||o.status==="cancelled"){let l=o.completedAt?.getTime()||o.startedAt?.getTime()||0;l>0&&n-l>t&&(s.delete(a),e.delete(a),i++)}let r=1e4;if(e.size>r){let a=e.size-r,o=e.keys();for(let l=0;l<a;l++){let c=o.next().value;c!==void 0&&e.delete(c)}console.log(`[QueenCoordinator] Evicted ${a} oldest trace contexts (max: ${r})`)}return i>0&&console.log(`[QueenCoordinator] Cleaned up ${i} old tasks (retention: ${t}ms)`),i}function vn(s,e){return s&&s.size>0?Array.from(s.keys()):[...e]}var g=gt.create("QueenCoordinator");tn(v);var dt=class{constructor(e,t,n,i,r,a,o,l={}){this.eventBus=e;this.agentCoordinator=t;this.memory=n;this.router=i;this.protocolExecutor=r;this.workflowExecutor=a;this.domainPlugins=o;this.config={...en,...l},this.auditLogger=Me({enableConsoleLog:this.config.enableMetrics,maxEntries:1e3,logPrefix:"[QUEEN]"}),["p0","p1","p2","p3"].forEach(c=>{this.taskQueue.set(c,[])}),this.config.enableRouting!==!1&&(this.tinyDancerRouter=new ee(this.config.routing)),v.forEach(c=>{this.domainQueues.set(c,[]),this.domainLastActivity.set(c,new Date)})}eventBus;agentCoordinator;memory;router;protocolExecutor;workflowExecutor;domainPlugins;config;tasks=new Map;taskQueue=new Map;domainQueues=new Map;domainLastActivity=new Map;initialized=!1;workStealingTimer=null;metricsTimer=null;cleanupTimer=null;startTime=new Date;eventSubscriptionIds=[];runningTaskCounter=0;tasksReceived=0;tasksCompleted=0;tasksFailed=0;tasksStolen=0;taskDurations=new ft(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=ct(this.config,()=>this.triggerWorkStealing().then(()=>{}))),this.config.enableMetrics&&(this.metricsTimer=Tn(this.createMetricsContext())),this.cleanupTimer=setInterval(()=>{ut(this.tasks,this.taskTraceContexts,36e5)},3e5),this.cleanupTimer.unref(),await fn(this.memory,this.tasks,e=>this.enqueueTaskInternal(e)),this.minCutBridge=Et(this.eventBus,this.agentCoordinator,{autoUpdateFromEvents:!0,persistData:!0,includeInQueenHealth:!0,sharedGraph:vt()}),await this.minCutBridge.initialize(),this.domainPlugins&&hn(this.domainPlugins,this.minCutBridge);try{await _.initialize(),g.info("Governance adapter initialized")}catch(e){g.warn("Governance initialization failed (continuing)",{error:e})}this.initializeSubsystems();try{let{join:e}=await import("path"),t=e(process.cwd(),".claude","agents","v3");this.dependencyGraph=qt(t),this.availableMcpServers=Dt(process.cwd());let{getUnifiedMemory:n}=await import("./unified-memory-GI76TXFV.js"),i=n();await i.initialize(),this.coExecutionRepo=$t(),this.coExecutionRepo.initialize(i.getDatabase()),this.dependencyGraph.warnings.length>0&&g.warn(`Dependency graph: ${this.dependencyGraph.warnings.length} warning(s)`,{warnings:this.dependencyGraph.warnings.slice(0,5)}),g.info("Dependency intelligence initialized",{agents:this.dependencyGraph.nodes.size,mcpServers:this.availableMcpServers.length})}catch(e){g.warn("Dependency intelligence initialization failed (continuing)",{error:e})}await this.publishEvent("QueenInitialized",{timestamp:new Date,config:this.config,domains:v}),this.initialized=!0}}async dispose(){this.workStealingTimer&&(clearInterval(this.workStealingTimer),this.workStealingTimer=null),this.metricsTimer&&(clearInterval(this.metricsTimer),this.metricsTimer=null),this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null),this.minCutBridge&&(await this.minCutBridge.dispose(),this.minCutBridge=null),this.domainTeamManager&&(this.domainTeamManager.dispose(),this.domainTeamManager=null),this.agentTeamsAdapter&&(this.agentTeamsAdapter.shutdown(),this.agentTeamsAdapter=null),this.domainBreakerRegistry=null,this.tierSelector=null,this.traceCollector&&(this.traceCollector.dispose(),this.traceCollector=null),this.hypothesisManager&&(this.hypothesisManager.dispose(),this.hypothesisManager=null),this.federationMailbox&&(this.federationMailbox.dispose(),this.federationMailbox=null),this.dynamicScaler&&(this.dynamicScaler.dispose(),this.dynamicScaler=null),await yn(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}validateTaskExecutable(e,t=[]){let n=at(e,t,this.domainPlugins);if(n.length===0)return f(new Error(`Unknown task type '${e}': no domain is configured for it and no loaded domain handles it. Pass a target domain.`));if(!this.domainPlugins)return y(void 0);let i=j(this.domainPlugins,e,n);return i.length===0?y(void 0):f(new Error(ve(e,i)))}async submitTask(e){if(!this.initialized)return f(new Error("Queen Coordinator not initialized"));let t=`task_${C()}`,n={...e,targetDomains:E(e.type).length>0?e.targetDomains:[...at(e.type,e.targetDomains,this.domainPlugins)],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 _.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}),f(new Error(`Task blocked by governance: ${r.reason}`))}catch(r){g.warn("Governance check error (continuing)",{error:r})}this.runningTaskCounter++;try{if(this.runningTaskCounter>this.config.maxConcurrentTasks)return this.runningTaskCounter--,this.queueTask(n);this.auditLogger.logSubmit(t,{type:n.type,priority:n.priority}),this.selectFleetTier(n),this.startTaskTrace(n,t);let r=await Se(this.createTaskContext(),n);return r.success?(this.tasksReceived++,await this.publishEvent("TaskSubmitted",{taskId:t,task:n}),y(t)):(this.tasks.has(t)||(this.runningTaskCounter=Math.max(0,this.runningTaskCounter-1)),r)}catch(r){throw this.runningTaskCounter=Math.max(0,this.runningTaskCounter-1),r}}async cancelTask(e){let t=this.tasks.get(e);if(!t)return f(new Error(`Task not found: ${e}`));if(t.status==="cancelled")return y(void 0);if(t.status==="completed"||t.status==="failed")return f(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}),N(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}),y(void 0)}getTaskStatus(e){return this.tasks.get(e)}listTasks(e){return un(this.tasks,e)}getDomainHealth(e){if(this.domainPlugins){let t=this.domainPlugins.get(e);if(t)return t.getHealth()}return on(this.agentCoordinator,e,this.domainLastActivity.get(e))}getDomainLoad(e){let t=this.domainQueues.get(e)||[],n=Array.from(this.tasks.values()).filter(i=>i.assignedDomain===e&&i.status==="running");return t.length+n.length}getIdleDomains(){let e=Date.now(),t=this.config.workStealing.idleThreshold;return v.filter(n=>{let i=this.domainLastActivity.get(n);return this.getDomainLoad(n)===0&&i&&e-i.getTime()>t})}getBusyDomains(){return v.filter(e=>this.getDomainLoad(e)>this.config.workStealing.loadThreshold)}getSpawnPlan(e){return this.dependencyGraph?zt(e,this.dependencyGraph):{phases:[e],warnings:[],unsatisfiedHardDeps:[]}}getDependencyGraph(){return this.dependencyGraph}enableWorkStealing(){this.workStealingTimer||(this.workStealingTimer=ct(this.config,()=>this.triggerWorkStealing().then(()=>{})))}disableWorkStealing(){this.workStealingTimer&&(clearInterval(this.workStealingTimer),this.workStealingTimer=null)}async triggerWorkStealing(){return pn(this.createWorkStealingContext())}listAllAgents(){return this.agentCoordinator.listAgents()}getAgentsByDomain(e){return this.agentCoordinator.listAgents({domain:e})}async requestAgentSpawn(e,t,n,i){if(!this.agentCoordinator.canSpawn())return f(new Error("Maximum concurrent agents reached (15)"));if(this.dependencyGraph&&this.availableMcpServers.length>0)try{for(let[,a]of this.dependencyGraph.nodes){let o=a.dependencies.mcpServers;if(!o||o.length===0)continue;let l=o.filter(c=>c.required&&!this.availableMcpServers.includes(c.name));if(l.length>0){g.warn(`Pre-spawn MCP advisory: ${a.agentName} needs ${l.map(c=>c.name).join(", ")}`,{agent:a.agentName,domain:e,missing:l.map(c=>c.name)});break}}}catch{}let r=await this.agentCoordinator.spawn({name:`${e}-${t}-${Date.now()}`,domain:e,type:t,capabilities:n});if(r.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,r.value)||g.warn(`Agent ${r.value} could not join ${e} team (full)`);else try{this.domainTeamManager.createDomainTeam(e,r.value)}catch{this.domainTeamManager.addTeammate(e,r.value)||g.warn(`Agent ${r.value} could not join ${e} team (full or max teams reached)`)}}catch(a){g.warn(`Auto-team-wiring failed for ${r.value}`,{error:a})}await this.publishEvent("AgentSpawned",{agentId:r.value,domain:e,type:t,capabilities:n,...i?{taskId:i}:{}})}return r}getHealth(){let e=new Map,t=[],n=0,i=0,r=vn(this.domainPlugins,v);for(let u of r){let d=this.getDomainHealth(u);d&&(e.set(u,d),d.status==="unhealthy"?(n++,t.push({domain:u,severity:"high",message:`Domain ${u} is unhealthy`,timestamp:new Date})):d.status==="degraded"&&(i++,t.push({domain:u,severity:"medium",message:`Domain ${u} is degraded`,timestamp:new Date})))}let a=this.agentCoordinator.listAgents(),o=a.filter(u=>u.status==="running").length,l="healthy";n>0?l="unhealthy":i>r.length/2&&(l="degraded");let c={status:l,domainHealth:e,totalAgents:a.length,activeAgents:o,pendingTasks:this.getQueuedTaskCount(),runningTasks:this.getRunningTaskCount(),workStealingActive:this.workStealingTimer!==null,lastHealthCheck:new Date,issues:t};return this.minCutBridge?this.minCutBridge.extendQueenHealth(c):c}getMetrics(){let e=new Map;for(let o of v){let l=this.getDomainLoad(o);e.set(o,l)}let t=this.agentCoordinator.listAgents(),n=t.filter(o=>o.status==="running").length,i=t.length>0?n/t.length:0,r=this.taskDurations.average(),a={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(a):a}getMinCutBridge(){return this.minCutBridge}injectMinCutBridgeIntoDomain(e){if(!this.minCutBridge)return g.warn("Cannot inject MinCut bridge: bridge not initialized"),!1;if(!this.domainPlugins)return g.warn("Cannot inject MinCut bridge: no domain plugins registered"),!1;let t=this.domainPlugins.get(e);return t?lt(t)?(t.setMinCutBridge(this.minCutBridge),g.info(`MinCut bridge injected into ${e} (late binding)`),!0):(g.warn(`Domain ${e} does not support MinCut integration`),!1):(g.warn(`Cannot inject MinCut bridge: domain ${e} not found`),!1)}getTinyDancerRouter(){return this.tinyDancerRouter}getDomainBreakerRegistry(){return this.domainBreakerRegistry}getDomainTeamManager(){return this.domainTeamManager}getAgentTeamsAdapter(){return this.agentTeamsAdapter}getTierSelector(){return this.tierSelector}getTraceCollector(){return this.traceCollector}getHypothesisManager(){return this.hypothesisManager}getFederationMailbox(){return this.federationMailbox}getDynamicScaler(){return this.dynamicScaler}connectReasoningBank(e){let t=new pe(e);this.taskCompletedHook=new ge({},t),g.info("ReasoningBank connected for pattern training")}async executeProtocol(e,t){if(!this.protocolExecutor)return f(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}),y(n.value.executionId)):n}async executeWorkflow(e,t){if(!this.workflowExecutor)return f(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}),y(n.value.executionId)):n}cleanupCompletedTasks(e=36e5){return ut(this.tasks,this.taskTraceContexts,e)}subscribeToEvents(){this.eventSubscriptionIds=sn(this.createEventHandlerContext(),v)}enqueueTaskInternal(e){ot(this.taskQueue,this.domainQueues,e)}async publishEvent(e,t){await this.eventBus.publish({id:C(),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,be(this.taskQueue,e)),this.publishEvent("TaskQueued",{taskId:e.id,task:e,position:be(this.taskQueue,e)}),y(e.id)}selectFleetTier(e){if(this.tierSelector)try{let t={trigger:e.payload?.trigger??"manual",changedFiles:e.payload?.changedFiles,affectedDomains:e.targetDomains,severity:e.priority==="p0"?"critical":e.priority==="p1"?"high":void 0,isHotfix:e.payload?.isHotfix},n=this.tierSelector.selectTier(t);return g.info(`Fleet tier: ${n.selectedTier} (${n.reason})`),n.selectedTier}catch(t){g.warn("Tier selection error (continuing)",{error:t});return}}startTaskTrace(e,t){if(this.traceCollector)try{let{context:n}=this.traceCollector.startTrace({operationName:e.type,agentId:e.requester||"queen",domain:e.targetDomains[0]||"test-generation",tags:{taskId:t,priority:e.priority}});if(this.taskTraceContexts.size>=1e4){let r=this.taskTraceContexts.keys().next().value;r!==void 0&&this.taskTraceContexts.delete(r)}this.taskTraceContexts.set(t,n)}catch(n){g.warn("Trace start error (continuing)",{error:n})}}getRunningTaskCount(){return Array.from(this.tasks.values()).filter(e=>e.status==="running"||e.status==="assigned").length}getQueuedTaskCount(){return Array.from(this.tasks.values()).filter(e=>e.status==="queued").length}initializeSubsystems(){if(this.config.enableCircuitBreakers!==!1)try{this.domainBreakerRegistry=Vt(),g.info("Domain circuit breaker registry initialized")}catch(e){g.warn("Circuit breaker initialization failed (continuing)",{error:e})}if(this.config.enableDomainTeams!==!1)try{this.agentTeamsAdapter=Be(),this.agentTeamsAdapter.initialize(),this.domainTeamManager=$e(this.agentTeamsAdapter),g.info("Domain team manager initialized")}catch(e){g.warn("Domain team manager initialization failed (continuing)",{error:e})}if(this.config.enableFleetTiers!==!1)try{this.tierSelector=Ge(),g.info("Fleet tier selector initialized")}catch(e){g.warn("Tier selector initialization failed (continuing)",{error:e})}try{this.traceCollector=Qe(),g.info("Trace collector initialized")}catch(e){g.warn("Trace collector initialization failed (continuing)",{error:e})}try{this.hypothesisManager=Ve(),this.federationMailbox=Ye(),this.dynamicScaler=Xe(),g.info("Phase 4 modules initialized (hypotheses, federation, scaling)")}catch(e){g.warn("Phase 4 initialization failed (continuing)",{error:e})}}createEventHandlerContext(){let e=this;return{config:e.config,tasks:e.tasks,domainLastActivity:e.domainLastActivity,auditLogger:e.auditLogger,router:e.router,agentCoordinator:e.agentCoordinator,get runningTaskCounter(){return e.runningTaskCounter},set runningTaskCounter(t){e.runningTaskCounter=t},get tasksCompleted(){return e.tasksCompleted},set tasksCompleted(t){e.tasksCompleted=t},get tasksFailed(){return e.tasksFailed},set tasksFailed(t){e.tasksFailed=t},taskDurations:e.taskDurations,get domainBreakerRegistry(){return e.domainBreakerRegistry},get traceCollector(){return e.traceCollector},taskTraceContexts:e.taskTraceContexts,get taskCompletedHook(){return e.taskCompletedHook},get hypothesisManager(){return e.hypothesisManager},processQueue:()=>M(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,r)=>e.requestAgentSpawn(t,n,i,r),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),availableSlots:()=>e.config.maxConcurrentTasks-e.runningTaskCounter,canExecuteInDomain:(t,n)=>(e.tasks.get(n.id)?.status??"queued")==="queued"&&gn(e.domainPlugins,t,n),removeFromQueues:t=>N(e.taskQueue,e.domainQueues,t),assignTaskToDomain:(t,n)=>mn(e.createTaskContext(),t,n),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 Go(s,e,t,n,i,r){return new dt(s.eventBus,s.coordinator,s.memory,e,t,n,i,r)}export{Ti as a,q as b,dt as c,Go 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 we(e);return t.safe?!1:(console.warn(`[CrossPhaseHooks] SSRF blocked: ${t.reason}`),!0)}checkConditions(e,t){return!e||e.length===0?!0:e.every(n=>this.evaluateCondition(n,t))}evaluateCondition(e,t){try{let n=e.split(/\s*(>|<|>=|<=|==|!=)\s*/);if(n.length!==3)return!1;let[i,r,a]=n,o=this.getValueFromPath(t,i),l=isNaN(Number(a))?a:Number(a),c=typeof o=="number"?o:Number(o),u=typeof l=="number"?l:Number(l);switch(r){case">":return c>u;case"<":return c<u;case">=":return c>=u;case"<=":return c<=u;case"==":return o==l;case"!=":return o!=l;default:return!1}}catch{return!1}}getValueFromPath(e,t){return t.split(".").reduce((n,i)=>{if(n&&typeof n=="object"&&Object.hasOwn(n,i))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`)}},rt=null;function rn(s){return rt||(rt=new st(s)),rt}function H(s,e){let t=s.get(e);return t?.status!=="cancelled"?{ignored:!1,settledNow:!1}:t.cancellationResultPending?(s.set(e,{...t,cancellationResultPending:!1}),{ignored:!0,settledNow:!0}):{ignored:!0,settledNow:!1}}function sn(s,e){let t=[];for(let a of e){let o=s.router.subscribeToDoamin(a,async l=>{await Di(s,l)});t.push(o)}let n=s.router.subscribeToEventType("TaskCompleted",async a=>{await Ai(s,a)});t.push(n);let i=s.router.subscribeToEventType("TaskFailed",async a=>{await xi(s,a)});t.push(i);let r=s.router.subscribeToEventType("AgentStatusChanged",async a=>{await Ei(s,a)});return t.push(r),t}async function Di(s,e){s.domainLastActivity.set(e.source,new Date),await s.processQueue()}async function an(s,e){for(let t of e.assignedAgents)await s.agentCoordinator.stop(t)}async function Ai(s,e){let{taskId:t,result:n}=e.payload,i=H(s.tasks,t);if(i.ignored){i.settledNow&&(s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),await s.processQueue());return}let r=s.tasks.get(t);if(r){await an(s,r),(r.status==="running"||r.status==="assigned")&&(s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1));let a=r.startedAt?Date.now()-r.startedAt.getTime():0;s.tasks.set(t,{...r,status:"completed",completedAt:new Date,result:n}),s.tasksCompleted++,s.taskDurations.push(a),s.auditLogger.logComplete(t,r.assignedAgents[0]);try{let o=rn(),l=r.assignedAgents[0];l&&await o.onAgentComplete(l,{taskId:t,taskType:r.task.type,domain:r.assignedDomain,result:n,duration:a})}catch(o){console.warn("[QueenCoordinator] Cross-phase hook error:",o)}try{await _.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(s.domainBreakerRegistry&&r.assignedDomain&&s.domainBreakerRegistry.getBreaker(r.assignedDomain).recordSuccess(),s.traceCollector){let o=s.taskTraceContexts.get(t);o&&(s.traceCollector.completeSpan(o.spanId),s.taskTraceContexts.delete(t))}if(s.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 l=wi(o,t);if(l){let c={taskId:t,agentId:r.assignedAgents[0]||"unknown",domain:r.assignedDomain||"test-generation",type:r.task.type,status:"completed",output:o,metrics:l,duration:a,timestamp:Date.now()};s.taskCompletedHook.onTaskCompleted(c).catch(u=>{console.warn("[QueenCoordinator] Pattern training error:",u)})}}}catch(o){console.warn("[QueenCoordinator] Pattern training setup error:",o)}}await s.processQueue()}async function xi(s,e){let{taskId:t,error:n,callerError:i}=e.payload,r=H(s.tasks,t);if(r.ignored){r.settledNow&&(s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),await s.processQueue());return}let a=s.tasks.get(t);if(a){if(await an(s,a),(a.status==="running"||a.status==="assigned")&&(s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1)),s.domainBreakerRegistry&&a.assignedDomain&&!i&&s.domainBreakerRegistry.getBreaker(a.assignedDomain).recordFailure(new Error(n||"Task failed")),s.traceCollector){let l=s.taskTraceContexts.get(t);l&&(s.traceCollector.failSpan(l.spanId,n||"Task failed"),s.taskTraceContexts.delete(t))}let o=a.task.executionOwner==="caller";if(!i&&!o&&a.retryCount<s.config.taskRetryLimit){s.auditLogger.logFail(t,a.assignedAgents[0],n);let l={...a,status:"queued",retryCount:a.retryCount+1,error:n};s.tasks.set(t,l),s.enqueueTask(a.task)}else{s.tasks.set(t,{...a,status:"failed",completedAt:new Date,error:n}),s.tasksFailed++,s.auditLogger.logFail(t,a.assignedAgents[0],n);try{await _.afterTaskExecution({taskId:t,taskType:a.task.type,agentId:a.assignedAgents[0]||"unknown",domain:a.assignedDomain||"test-generation",priority:a.task.priority},!1,0,0)}catch(l){console.warn("[QueenCoordinator] Governance tracking error:",l)}if(!i&&s.hypothesisManager&&(a.task.priority==="p0"||a.task.priority==="p1"))try{let l=a.assignedDomain||"test-generation",c=s.hypothesisManager.createInvestigation(t,l,`Root cause analysis for ${a.task.type} failure: ${n}`);s.hypothesisManager.addHypothesis(c.id,`Infrastructure failure in domain '${l}' caused task ${t} to fail`,"log-analysis",`${l}-lead`),s.hypothesisManager.addHypothesis(c.id,`Logic/configuration error in task payload caused ${a.task.type} to fail: ${n}`,"code-analysis",a.assignedAgents[0]||"unknown"),console.log(`[QueenCoordinator] Competing hypotheses investigation created: ${c.id}`)}catch(l){console.warn("[QueenCoordinator] Hypothesis creation error:",l)}}}await s.processQueue()}async function Ei(s,e){let{agentId:t,status:n,domain:i}=e.payload;s.domainLastActivity.set(i,new Date),(n==="completed"||n==="failed")&&await s.processQueue()}function wi(s,e){if("metrics"in s&&typeof s.metrics=="object"&&s.metrics!==null){let t=s.metrics;return{testsPassed:typeof t.testsPassed=="number"?t.testsPassed:void 0,testsFailed:typeof t.testsFailed=="number"?t.testsFailed:void 0,coverageChange:typeof t.coverageChange=="number"?t.coverageChange:void 0,securityIssues:typeof t.securityIssues=="number"?t.securityIssues:void 0,performanceMs:typeof t.performanceMs=="number"?t.performanceMs:void 0,linesChanged:typeof t.linesChanged=="number"?t.linesChanged:void 0}}return"testsPassed"in s||"testsFailed"in s?{testsPassed:typeof s.testsPassed=="number"?s.testsPassed:void 0,testsFailed:typeof s.testsFailed=="number"?s.testsFailed:void 0,coverageChange:typeof s.coverageChange=="number"?s.coverageChange:void 0,securityIssues:typeof s.securityIssues=="number"?s.securityIssues:void 0,performanceMs:typeof s.performanceMs=="number"?s.performanceMs:void 0,linesChanged:typeof s.linesChanged=="number"?s.linesChanged:void 0}:(console.error(`[QueenCoordinator] Pattern training skipped for task ${e}: result object has no recognizable metrics shape (keys: ${Object.keys(s).join(", ")})`),null)}function on(s,e,t){let n=s.listAgents({domain:e}),i=n.filter(l=>l.status==="running").length,r=n.filter(l=>l.status==="idle").length,a=n.filter(l=>l.status==="failed").length,o;return a>0&&a>=n.length/2?o="unhealthy":a>0?o="degraded":i>0?o="healthy":o="idle",{status:o,agents:{total:n.length,active:i,idle:r,failed:a},lastActivity:t,errors:[]}}function j(s,e,t){let n=[];for(let i of t){let r=s.get(i);if(!r)n.push(`${i} (domain not loaded)`);else if(!r.executeTask||!r.canHandleTask?.(e)){let a=r.getSupportedTaskTypes?.()??[];n.push(a.length>0?`${i} (supported: ${a.join(", ")})`:i)}}return n}function Mi(s,e){let t=[];for(let[n,i]of s)i.executeTask&&i.canHandleTask?.(e)&&t.push(n);return t}function at(s,e,t){if(e.length>0)return e;let n=E(s);return n.length>0||!t?n:Mi(t,s)}function ve(s,e){return`No handler for task type '${s}' in domain ${e.join("; ")}`}k();k();var ln=St();function ot(s,e,t){let n=s.get(t.priority);n&&kt(n,t,ln);for(let i of t.targetDomains){let r=e.get(i);r&&r.push(t)}}function N(s,e,t){let n=s.get(t.priority);if(n){let i=n.findIndex(r=>r.id===t.id);i!==-1&&n.splice(i,1)}for(let i of t.targetDomains){let r=e.get(i);if(r){let a=r.findIndex(o=>o.id===t.id);a!==-1&&r.splice(a,1)}}}function be(s,e){let t=0;for(let n of["p0","p1","p2","p3"]){let i=s.get(n);if(i){if(n===e.priority){t+=i.findIndex(r=>r.id===e.id);break}t+=i.length}}return t}async function M(s){if(!(s.runningTaskCounter>=s.config.maxConcurrentTasks)){O.set(s.tasks,(O.get(s.tasks)??0)+1);try{do{Ce.delete(s.tasks);for(let e of["p0","p1","p2","p3"]){let t=s.taskQueue.get(e);if(!t||t.length===0)continue;let n=cn(s,t);for(;n;){N(s.taskQueue,s.domainQueues,n),s.runningTaskCounter++;let i;try{i=await Se(s,n)}catch(r){throw s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),r}if(!i.success&&(s.tasks.get(n.id)?.status??"queued")==="queued"&&await ke(s,n,void 0,i.error.message),s.runningTaskCounter>=s.config.maxConcurrentTasks)return;n=cn(s,t)}}}while(Ce.has(s.tasks)&&s.runningTaskCounter<s.config.maxConcurrentTasks)}finally{let e=(O.get(s.tasks)??1)-1;e>0?O.set(s.tasks,e):(O.delete(s.tasks),Ce.delete(s.tasks))}}}var O=new WeakMap,Ce=new WeakSet;async function V(s){if(s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),O.has(s.tasks)){Ce.add(s.tasks);return}M(s).catch(e=>{console.warn("[Queen] Queue drain after a released slot failed:",h(e))})}function cn(s,e){let t=e.shift();for(;t;){let n=s.tasks.get(t.id)?.status;if(n===void 0||n==="queued")return t;N(s.taskQueue,s.domainQueues,t),t=e.shift()}}async function ke(s,e,t,n){s.tasks.set(e.id,{taskId:e.id,task:e,status:"failed",assignedDomain:t,assignedAgents:[],retryCount:s.tasks.get(e.id)?.retryCount??0,error:n,completedAt:new Date}),s.tasksFailed++,s.auditLogger.logFail(e.id,void 0,n),await s.publishEvent("TaskFailed",{taskId:e.id,domain:t,error:n}),await V(s)}function un(s,e){let t=Array.from(s.values());return e&&(e.status&&(t=t.filter(n=>n.status===e.status)),e.domain&&(t=t.filter(n=>n.assignedDomain===e.domain)),e.priority&&(t=t.filter(n=>n.task.priority===e.priority)),e.type&&(t=t.filter(n=>n.task.type===e.type)),e.fromDate&&(t=t.filter(n=>n.task.createdAt>=e.fromDate)),e.toDate&&(t=t.filter(n=>n.task.createdAt<=e.toDate))),t}async function Se(s,e){let t=e.targetDomains.length>0?e.targetDomains:E(e.type);if(t.length===0)return f(new Error(`No domains configured for task type: ${e.type}`));let n,i=1/0;for(let r of t){let a=s.getDomainLoad(r);s.getDomainHealth(r)?.status!=="unhealthy"&&a<i&&(i=a,n=r)}return n?dn(s,e,n):f(new Error("No healthy domain available for task"))}async function dn(s,e,t){if(e.executionOwner!=="caller"&&s.domainPlugins){let c=j(s.domainPlugins,e.type,[t]);if(c.length>0)return Ii(s,e,t,ve(e.type,c))}let n;if(s.tinyDancerRouter){let c={p0:"critical",p1:"high",p2:"normal",p3:"low"},u={description:`${e.type}: ${JSON.stringify(e.payload).slice(0,200)}`,type:e.type,domain:t,priority:Object.hasOwn(c,e.priority)?c[e.priority]:"normal"};n=await s.tinyDancerRouter.route(u),s.config.enableMetrics&&console.log(`[Queen] TinyDancer routing: ${e.type} \u2192 tier=${n.tier}, model=${n.model}, cost=$${n.estimatedCost.toFixed(4)}`)}if(s.domainBreakerRegistry&&!s.domainBreakerRegistry.canExecuteInDomain(t))return f(new Error(`Domain '${t}' circuit breaker is open \u2014 too many recent failures`));if(s.domainTeamManager)try{if(!s.domainTeamManager.getDomainTeam(t)){let u=`${t}-lead`;s.domainTeamManager.createDomainTeam(t,u)}}catch(c){console.warn(`[Queen] Domain team setup for '${t}' failed (continuing):`,c)}let i=n?.tier||"task-worker",r=["task-execution",e.type,...n?[`model:${n.model}`]:[],...n?.triggerMultiModel?["advisor:triggerMultiModel"]:[]],a=await s.requestAgentSpawn(t,i,r,e.id);if(s.tasks.get(e.id)?.status==="cancelled")return a.success&&await s.agentCoordinator.stop(a.value),await V(s),y(e.id);let o=[];a.success&&o.push(a.value);let l={taskId:e.id,task:e,status:"running",assignedDomain:t,assignedAgents:o,startedAt:new Date,retryCount:0};s.tasks.set(e.id,l),s.domainLastActivity.set(t,new Date);for(let c of o)s.auditLogger.logAssign(e.id,c,t);if(await s.publishEvent("TaskAssigned",{taskId:e.id,domain:t,agentIds:o}),e.executionOwner==="caller")return y(e.id);if(s.domainPlugins){let c=s.domainPlugins.get(t);if(c?.executeTask&&c.canHandleTask?.(e.type)){let u={taskId:e.id,taskType:e.type,payload:e.payload,priority:e.priority,timeout:e.timeout,correlationId:e.correlationId},d;try{d=await c.executeTask(u,m=>Ri(s,m))}catch(m){d=f(Z(m))}if(!d.success){let m=H(s.tasks,e.id);return m.ignored?(m.settledNow&&await V(s),y(e.id)):s.tasks.get(e.id)?.status!=="running"?f(d.error):(s.tasks.set(e.id,{...l,status:"failed",error:d.error.message,completedAt:new Date}),s.tasksFailed++,s.auditLogger.logFail(e.id,o[0],d.error.message),await s.publishEvent("TaskFailed",{taskId:e.id,domain:t,error:d.error.message}),await V(s),f(d.error))}return y(e.id)}}return y(e.id)}async function Ii(s,e,t,n){let i=s.taskTraceContexts.get(e.id);return s.traceCollector&&i&&(s.traceCollector.failSpan(i.spanId,n),s.taskTraceContexts.delete(e.id)),await ke(s,e,t,n),y(e.id)}async function mn(s,e,t){let n=s.tasks.get(e.id)?.status;if(n!==void 0&&n!=="queued")return!1;s.runningTaskCounter++;let i;try{i=await dn(s,e,t)}catch(a){throw s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),a}!i.success&&(s.tasks.get(e.id)?.status??"queued")==="queued"&&await ke(s,e,t,i.error.message);let r=s.tasks.get(e.id);return r?.assignedDomain===t&&(r.status==="running"||r.status==="completed")}async function Ri(s,e){let t=s.tasks.get(e.taskId);if(!t){console.warn(`[Queen] Received completion for unknown task: ${e.taskId}`);return}let n=H(s.tasks,e.taskId);if(n.ignored){n.settledNow&&(s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),await M(s));return}let i={...t,status:e.success?"completed":"failed",completedAt:new Date,result:e.data,error:e.error};if(s.tasks.set(e.taskId,i),e.success?(s.tasksCompleted++,s.taskDurations.push(e.duration),s.auditLogger.logComplete(e.taskId,t.assignedAgents[0])):(s.tasksFailed++,s.auditLogger.logFail(e.taskId,t.assignedAgents[0],e.error||"Unknown error")),s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),s.coExecutionRepo&&t.assignedAgents.length>=2)try{s.coExecutionRepo.recordSwarmCoExecution(t.assignedAgents,t.assignedDomain||"unknown",e.success,t.task.type)}catch{}for(let r of t.assignedAgents)await s.agentCoordinator.stop(r);await s.publishEvent(e.success?"TaskCompleted":"TaskFailed",{taskId:e.taskId,domain:t.assignedDomain,result:e.data,error:e.error,duration:e.duration}),await M(s)}function _i(s,e){return E(e.type).includes(s)}function gn(s,e,t){return _i(e,t)?t.executionOwner==="caller"||!s?!0:j(s,t.type,[e]).length===0:!1}k();async function pn(s){let e=0,t=s.getIdleDomains(),n=s.getBusyDomains();if(t.length===0||n.length===0)return 0;n.sort((i,r)=>s.getDomainLoad(r)-s.getDomainLoad(i));for(let i of n){if(t.length===0)break;let r=s.domainQueues.get(i)||[],a=Math.min(r.length,s.config.workStealing.stealBatchSize);for(let o=0;o<a&&t.length>0&&s.availableSlots()>0;o++){let l=r.find(c=>s.canExecuteInDomain(t[0],c));if(l){let c=t.shift();if(s.removeFromQueues(l),!await s.assignTaskToDomain(l,c))continue;s.auditLogger.logSteal(l.id,i,c),e++,s.tasksStolen++,await s.publishEvent("TaskStolen",{taskId:l.id,fromDomain:i,toDomain:c})}}}return e}function ct(s,e){let t=0,n=10,i=setInterval(async()=>{try{await e(),t=0}catch(r){t++;let a=Math.min(1e3*Math.pow(2,t),3e4);if(console.warn(`[QueenCoordinator] Work-stealing failed (attempt ${t}), backing off ${a}ms`,h(r)),t>n){console.error(`[QueenCoordinator] Work-stealing exceeded ${n} consecutive failures, stopping interval`),clearInterval(i);return}await new Promise(o=>setTimeout(o,a))}},s.workStealing.checkInterval);return i}function lt(s){return typeof s.setMinCutBridge=="function"}function hn(s,e){for(let[t,n]of s)lt(n)&&(n.setMinCutBridge(e),console.log(`[QueenCoordinator] MinCut bridge injected into ${t}`))}async function fn(s,e,t){try{let n=await s.get("queen:state");if(n){for(let[i,r]of n.tasks)if(r.status==="queued"){if(r.task.executionOwner==="caller"){e.set(i,{...r,status:"failed",error:"Caller-owned task was interrupted before completion; submit a new request.",completedAt:new Date});continue}e.set(i,r),t(r.task)}}}catch(n){console.debug("[QueenCoordinator] State loading failed:",n instanceof Error?n.message:n)}}async function yn(s,e){let t=Array.from(e.entries()).filter(([,n])=>n.status==="queued");await s.set("queen:state",{tasks:t},{namespace:"queen-coordinator",persist:!0})}function Tn(s){return setInterval(async()=>{let e=s.getMetrics();if(await s.publishEvent("MetricsCollected",{metrics:e}),await s.memory.set(`queen:metrics:${Date.now()}`,e,{ttl:86400,namespace:"queen-coordinator"}),s.dynamicScaler)try{let t=s.getAverageTaskDuration(),n={queueDepth:s.getQueuedTaskCount(),activeAgents:s.getActiveAgentCount(),idleAgents:s.getIdleAgentCount(),avgTaskDurationMs:t,errorRate:s.getTasksReceived()>0?s.getTasksFailed()/s.getTasksReceived():0,throughput:e.uptime>0?s.getTasksCompleted()/(e.uptime/1e3):0,timestamp:Date.now()};s.dynamicScaler.recordMetrics(n);let i=s.dynamicScaler.evaluate();i&&i.action!=="maintain"&&(console.log(`[QueenCoordinator] Dynamic scaler: ${i.action} to ${i.targetAgents} agents \u2014 ${i.reason}`),s.dynamicScaler.execute(i).catch(r=>{console.warn("[QueenCoordinator] Dynamic scaling execution error:",r)}))}catch(t){console.warn("[QueenCoordinator] Dynamic scaler metrics error:",t)}},s.config.metricsInterval)}function ut(s,e,t=36e5){let n=Date.now(),i=0;for(let[a,o]of s)if(o.status==="completed"||o.status==="failed"||o.status==="cancelled"){let l=o.completedAt?.getTime()||o.startedAt?.getTime()||0;l>0&&n-l>t&&(s.delete(a),e.delete(a),i++)}let r=1e4;if(e.size>r){let a=e.size-r,o=e.keys();for(let l=0;l<a;l++){let c=o.next().value;c!==void 0&&e.delete(c)}console.log(`[QueenCoordinator] Evicted ${a} oldest trace contexts (max: ${r})`)}return i>0&&console.log(`[QueenCoordinator] Cleaned up ${i} old tasks (retention: ${t}ms)`),i}function vn(s,e){return s&&s.size>0?Array.from(s.keys()):[...e]}var g=gt.create("QueenCoordinator");tn(v);var dt=class{constructor(e,t,n,i,r,a,o,l={}){this.eventBus=e;this.agentCoordinator=t;this.memory=n;this.router=i;this.protocolExecutor=r;this.workflowExecutor=a;this.domainPlugins=o;this.config={...en,...l},this.auditLogger=Me({enableConsoleLog:this.config.enableMetrics,maxEntries:1e3,logPrefix:"[QUEEN]"}),["p0","p1","p2","p3"].forEach(c=>{this.taskQueue.set(c,[])}),this.config.enableRouting!==!1&&(this.tinyDancerRouter=new ee(this.config.routing)),v.forEach(c=>{this.domainQueues.set(c,[]),this.domainLastActivity.set(c,new Date)})}eventBus;agentCoordinator;memory;router;protocolExecutor;workflowExecutor;domainPlugins;config;tasks=new Map;taskQueue=new Map;domainQueues=new Map;domainLastActivity=new Map;initialized=!1;workStealingTimer=null;metricsTimer=null;cleanupTimer=null;startTime=new Date;eventSubscriptionIds=[];runningTaskCounter=0;tasksReceived=0;tasksCompleted=0;tasksFailed=0;tasksStolen=0;taskDurations=new ft(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=ct(this.config,()=>this.triggerWorkStealing().then(()=>{}))),this.config.enableMetrics&&(this.metricsTimer=Tn(this.createMetricsContext())),this.cleanupTimer=setInterval(()=>{ut(this.tasks,this.taskTraceContexts,36e5)},3e5),this.cleanupTimer.unref(),await fn(this.memory,this.tasks,e=>this.enqueueTaskInternal(e)),this.minCutBridge=Et(this.eventBus,this.agentCoordinator,{autoUpdateFromEvents:!0,persistData:!0,includeInQueenHealth:!0,sharedGraph:vt()}),await this.minCutBridge.initialize(),this.domainPlugins&&hn(this.domainPlugins,this.minCutBridge);try{await _.initialize(),g.info("Governance adapter initialized")}catch(e){g.warn("Governance initialization failed (continuing)",{error:e})}this.initializeSubsystems();try{let{join:e}=await import("path"),t=e(process.cwd(),".claude","agents","v3");this.dependencyGraph=qt(t),this.availableMcpServers=Dt(process.cwd());let{getUnifiedMemory:n}=await import("./unified-memory-2VMGSGQL.js"),i=n();await i.initialize(),this.coExecutionRepo=$t(),this.coExecutionRepo.initialize(i.getDatabase()),this.dependencyGraph.warnings.length>0&&g.warn(`Dependency graph: ${this.dependencyGraph.warnings.length} warning(s)`,{warnings:this.dependencyGraph.warnings.slice(0,5)}),g.info("Dependency intelligence initialized",{agents:this.dependencyGraph.nodes.size,mcpServers:this.availableMcpServers.length})}catch(e){g.warn("Dependency intelligence initialization failed (continuing)",{error:e})}await this.publishEvent("QueenInitialized",{timestamp:new Date,config:this.config,domains:v}),this.initialized=!0}}async dispose(){this.workStealingTimer&&(clearInterval(this.workStealingTimer),this.workStealingTimer=null),this.metricsTimer&&(clearInterval(this.metricsTimer),this.metricsTimer=null),this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null),this.minCutBridge&&(await this.minCutBridge.dispose(),this.minCutBridge=null),this.domainTeamManager&&(this.domainTeamManager.dispose(),this.domainTeamManager=null),this.agentTeamsAdapter&&(this.agentTeamsAdapter.shutdown(),this.agentTeamsAdapter=null),this.domainBreakerRegistry=null,this.tierSelector=null,this.traceCollector&&(this.traceCollector.dispose(),this.traceCollector=null),this.hypothesisManager&&(this.hypothesisManager.dispose(),this.hypothesisManager=null),this.federationMailbox&&(this.federationMailbox.dispose(),this.federationMailbox=null),this.dynamicScaler&&(this.dynamicScaler.dispose(),this.dynamicScaler=null),await yn(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}validateTaskExecutable(e,t=[]){let n=at(e,t,this.domainPlugins);if(n.length===0)return f(new Error(`Unknown task type '${e}': no domain is configured for it and no loaded domain handles it. Pass a target domain.`));if(!this.domainPlugins)return y(void 0);let i=j(this.domainPlugins,e,n);return i.length===0?y(void 0):f(new Error(ve(e,i)))}async submitTask(e){if(!this.initialized)return f(new Error("Queen Coordinator not initialized"));let t=`task_${C()}`,n={...e,targetDomains:E(e.type).length>0?e.targetDomains:[...at(e.type,e.targetDomains,this.domainPlugins)],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 _.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}),f(new Error(`Task blocked by governance: ${r.reason}`))}catch(r){g.warn("Governance check error (continuing)",{error:r})}this.runningTaskCounter++;try{if(this.runningTaskCounter>this.config.maxConcurrentTasks)return this.runningTaskCounter--,this.queueTask(n);this.auditLogger.logSubmit(t,{type:n.type,priority:n.priority}),this.selectFleetTier(n),this.startTaskTrace(n,t);let r=await Se(this.createTaskContext(),n);return r.success?(this.tasksReceived++,await this.publishEvent("TaskSubmitted",{taskId:t,task:n}),y(t)):(this.tasks.has(t)||(this.runningTaskCounter=Math.max(0,this.runningTaskCounter-1)),r)}catch(r){throw this.runningTaskCounter=Math.max(0,this.runningTaskCounter-1),r}}async cancelTask(e){let t=this.tasks.get(e);if(!t)return f(new Error(`Task not found: ${e}`));if(t.status==="cancelled")return y(void 0);if(t.status==="completed"||t.status==="failed")return f(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}),N(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}),y(void 0)}getTaskStatus(e){return this.tasks.get(e)}listTasks(e){return un(this.tasks,e)}getDomainHealth(e){if(this.domainPlugins){let t=this.domainPlugins.get(e);if(t)return t.getHealth()}return on(this.agentCoordinator,e,this.domainLastActivity.get(e))}getDomainLoad(e){let t=this.domainQueues.get(e)||[],n=Array.from(this.tasks.values()).filter(i=>i.assignedDomain===e&&i.status==="running");return t.length+n.length}getIdleDomains(){let e=Date.now(),t=this.config.workStealing.idleThreshold;return v.filter(n=>{let i=this.domainLastActivity.get(n);return this.getDomainLoad(n)===0&&i&&e-i.getTime()>t})}getBusyDomains(){return v.filter(e=>this.getDomainLoad(e)>this.config.workStealing.loadThreshold)}getSpawnPlan(e){return this.dependencyGraph?zt(e,this.dependencyGraph):{phases:[e],warnings:[],unsatisfiedHardDeps:[]}}getDependencyGraph(){return this.dependencyGraph}enableWorkStealing(){this.workStealingTimer||(this.workStealingTimer=ct(this.config,()=>this.triggerWorkStealing().then(()=>{})))}disableWorkStealing(){this.workStealingTimer&&(clearInterval(this.workStealingTimer),this.workStealingTimer=null)}async triggerWorkStealing(){return pn(this.createWorkStealingContext())}listAllAgents(){return this.agentCoordinator.listAgents()}getAgentsByDomain(e){return this.agentCoordinator.listAgents({domain:e})}async requestAgentSpawn(e,t,n,i){if(!this.agentCoordinator.canSpawn())return f(new Error("Maximum concurrent agents reached (15)"));if(this.dependencyGraph&&this.availableMcpServers.length>0)try{for(let[,a]of this.dependencyGraph.nodes){let o=a.dependencies.mcpServers;if(!o||o.length===0)continue;let l=o.filter(c=>c.required&&!this.availableMcpServers.includes(c.name));if(l.length>0){g.warn(`Pre-spawn MCP advisory: ${a.agentName} needs ${l.map(c=>c.name).join(", ")}`,{agent:a.agentName,domain:e,missing:l.map(c=>c.name)});break}}}catch{}let r=await this.agentCoordinator.spawn({name:`${e}-${t}-${Date.now()}`,domain:e,type:t,capabilities:n});if(r.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,r.value)||g.warn(`Agent ${r.value} could not join ${e} team (full)`);else try{this.domainTeamManager.createDomainTeam(e,r.value)}catch{this.domainTeamManager.addTeammate(e,r.value)||g.warn(`Agent ${r.value} could not join ${e} team (full or max teams reached)`)}}catch(a){g.warn(`Auto-team-wiring failed for ${r.value}`,{error:a})}await this.publishEvent("AgentSpawned",{agentId:r.value,domain:e,type:t,capabilities:n,...i?{taskId:i}:{}})}return r}getHealth(){let e=new Map,t=[],n=0,i=0,r=vn(this.domainPlugins,v);for(let u of r){let d=this.getDomainHealth(u);d&&(e.set(u,d),d.status==="unhealthy"?(n++,t.push({domain:u,severity:"high",message:`Domain ${u} is unhealthy`,timestamp:new Date})):d.status==="degraded"&&(i++,t.push({domain:u,severity:"medium",message:`Domain ${u} is degraded`,timestamp:new Date})))}let a=this.agentCoordinator.listAgents(),o=a.filter(u=>u.status==="running").length,l="healthy";n>0?l="unhealthy":i>r.length/2&&(l="degraded");let c={status:l,domainHealth:e,totalAgents:a.length,activeAgents:o,pendingTasks:this.getQueuedTaskCount(),runningTasks:this.getRunningTaskCount(),workStealingActive:this.workStealingTimer!==null,lastHealthCheck:new Date,issues:t};return this.minCutBridge?this.minCutBridge.extendQueenHealth(c):c}getMetrics(){let e=new Map;for(let o of v){let l=this.getDomainLoad(o);e.set(o,l)}let t=this.agentCoordinator.listAgents(),n=t.filter(o=>o.status==="running").length,i=t.length>0?n/t.length:0,r=this.taskDurations.average(),a={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(a):a}getMinCutBridge(){return this.minCutBridge}injectMinCutBridgeIntoDomain(e){if(!this.minCutBridge)return g.warn("Cannot inject MinCut bridge: bridge not initialized"),!1;if(!this.domainPlugins)return g.warn("Cannot inject MinCut bridge: no domain plugins registered"),!1;let t=this.domainPlugins.get(e);return t?lt(t)?(t.setMinCutBridge(this.minCutBridge),g.info(`MinCut bridge injected into ${e} (late binding)`),!0):(g.warn(`Domain ${e} does not support MinCut integration`),!1):(g.warn(`Cannot inject MinCut bridge: domain ${e} not found`),!1)}getTinyDancerRouter(){return this.tinyDancerRouter}getDomainBreakerRegistry(){return this.domainBreakerRegistry}getDomainTeamManager(){return this.domainTeamManager}getAgentTeamsAdapter(){return this.agentTeamsAdapter}getTierSelector(){return this.tierSelector}getTraceCollector(){return this.traceCollector}getHypothesisManager(){return this.hypothesisManager}getFederationMailbox(){return this.federationMailbox}getDynamicScaler(){return this.dynamicScaler}connectReasoningBank(e){let t=new pe(e);this.taskCompletedHook=new ge({},t),g.info("ReasoningBank connected for pattern training")}async executeProtocol(e,t){if(!this.protocolExecutor)return f(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}),y(n.value.executionId)):n}async executeWorkflow(e,t){if(!this.workflowExecutor)return f(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}),y(n.value.executionId)):n}cleanupCompletedTasks(e=36e5){return ut(this.tasks,this.taskTraceContexts,e)}subscribeToEvents(){this.eventSubscriptionIds=sn(this.createEventHandlerContext(),v)}enqueueTaskInternal(e){ot(this.taskQueue,this.domainQueues,e)}async publishEvent(e,t){await this.eventBus.publish({id:C(),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,be(this.taskQueue,e)),this.publishEvent("TaskQueued",{taskId:e.id,task:e,position:be(this.taskQueue,e)}),y(e.id)}selectFleetTier(e){if(this.tierSelector)try{let t={trigger:e.payload?.trigger??"manual",changedFiles:e.payload?.changedFiles,affectedDomains:e.targetDomains,severity:e.priority==="p0"?"critical":e.priority==="p1"?"high":void 0,isHotfix:e.payload?.isHotfix},n=this.tierSelector.selectTier(t);return g.info(`Fleet tier: ${n.selectedTier} (${n.reason})`),n.selectedTier}catch(t){g.warn("Tier selection error (continuing)",{error:t});return}}startTaskTrace(e,t){if(this.traceCollector)try{let{context:n}=this.traceCollector.startTrace({operationName:e.type,agentId:e.requester||"queen",domain:e.targetDomains[0]||"test-generation",tags:{taskId:t,priority:e.priority}});if(this.taskTraceContexts.size>=1e4){let r=this.taskTraceContexts.keys().next().value;r!==void 0&&this.taskTraceContexts.delete(r)}this.taskTraceContexts.set(t,n)}catch(n){g.warn("Trace start error (continuing)",{error:n})}}getRunningTaskCount(){return Array.from(this.tasks.values()).filter(e=>e.status==="running"||e.status==="assigned").length}getQueuedTaskCount(){return Array.from(this.tasks.values()).filter(e=>e.status==="queued").length}initializeSubsystems(){if(this.config.enableCircuitBreakers!==!1)try{this.domainBreakerRegistry=Vt(),g.info("Domain circuit breaker registry initialized")}catch(e){g.warn("Circuit breaker initialization failed (continuing)",{error:e})}if(this.config.enableDomainTeams!==!1)try{this.agentTeamsAdapter=Be(),this.agentTeamsAdapter.initialize(),this.domainTeamManager=$e(this.agentTeamsAdapter),g.info("Domain team manager initialized")}catch(e){g.warn("Domain team manager initialization failed (continuing)",{error:e})}if(this.config.enableFleetTiers!==!1)try{this.tierSelector=Ge(),g.info("Fleet tier selector initialized")}catch(e){g.warn("Tier selector initialization failed (continuing)",{error:e})}try{this.traceCollector=Qe(),g.info("Trace collector initialized")}catch(e){g.warn("Trace collector initialization failed (continuing)",{error:e})}try{this.hypothesisManager=Ve(),this.federationMailbox=Ye(),this.dynamicScaler=Xe(),g.info("Phase 4 modules initialized (hypotheses, federation, scaling)")}catch(e){g.warn("Phase 4 initialization failed (continuing)",{error:e})}}createEventHandlerContext(){let e=this;return{config:e.config,tasks:e.tasks,domainLastActivity:e.domainLastActivity,auditLogger:e.auditLogger,router:e.router,agentCoordinator:e.agentCoordinator,get runningTaskCounter(){return e.runningTaskCounter},set runningTaskCounter(t){e.runningTaskCounter=t},get tasksCompleted(){return e.tasksCompleted},set tasksCompleted(t){e.tasksCompleted=t},get tasksFailed(){return e.tasksFailed},set tasksFailed(t){e.tasksFailed=t},taskDurations:e.taskDurations,get domainBreakerRegistry(){return e.domainBreakerRegistry},get traceCollector(){return e.traceCollector},taskTraceContexts:e.taskTraceContexts,get taskCompletedHook(){return e.taskCompletedHook},get hypothesisManager(){return e.hypothesisManager},processQueue:()=>M(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,r)=>e.requestAgentSpawn(t,n,i,r),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),availableSlots:()=>e.config.maxConcurrentTasks-e.runningTaskCounter,canExecuteInDomain:(t,n)=>(e.tasks.get(n.id)?.status??"queued")==="queued"&&gn(e.domainPlugins,t,n),removeFromQueues:t=>N(e.taskQueue,e.domainQueues,t),assignTaskToDomain:(t,n)=>mn(e.createTaskContext(),t,n),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 Go(s,e,t,n,i,r){return new dt(s.eventBus,s.coordinator,s.memory,e,t,n,i,r)}export{Ti as a,q as b,dt as c,Go 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.15.16");process.exit(0)}
2
- import{c as h,d as $}from"./chunk-AGRV5B3T.js";import{a as b,b as y,c as R,e as S,f as A}from"./chunk-I7MQIM2U.js";import{e as N,f as w}from"./chunk-ZFL436FN.js";import{a as g,f as C}from"./chunk-AJMJNQMP.js";$();var i=null,f=!1,p=class extends Error{constructor(e){super(e instanceof Error?e.message:String(e));this.lockError=e;this.name="RvfLiveLockError"}lockError};function V(r){i=r,f=r!==null}var B=(()=>{let r=process.env.AQE_RVF_SIZE_GUARD_BYTES,t=r?Number(r):NaN;return Number.isFinite(t)&&t>0?t:256*1024*1024})(),F=(()=>{let r=process.env.AQE_RVF_DEAD_RATIO_THRESHOLD,t=r?Number(r):NaN;return Number.isFinite(t)&&t>0&&t<=1?t:.3})();function k(r=".agentic-qe",t=384){if(f)return i;f=!0;try{let{isRvfNativeAvailable:e,createRvfStore:n,openRvfStore:o}=(w(),C(N));if(!e())return console.warn("[RVF] Native bindings unavailable \u2014 agent branching and dream COW disabled. Install @ruvector/rvf-node to enable."),null;let s=g("path"),l=s.isAbsolute(r)?r:s.join(process.env.AQE_PROJECT_ROOT??h(),r),u=s.join(l,"patterns.rvf");return i=_(o,n,u,t),T(i,u),i}catch(e){return e instanceof p||console.warn("[RVF] Shared adapter init failed:",e instanceof Error?e.message:e),null}}function _(r,t,e,n){let o=()=>{try{return{adapter:r(e),err:null}}catch(a){return{adapter:null,err:a}}},{adapter:s,err:l}=o(),u=!1;if(!s&&R(l))try{let a=g("fs"),c=`${e}.lock`;a.existsSync(c)&&y(e)?(u=!0,console.warn(`[RVF] ${e} is locked by a live process (pid ${b(e)}) \u2014 not breaking the lock; degrading to SQLite for this run.`)):S(e)&&(console.warn(`[RVF] Removed stale lock file at ${c} (prior process exited without closing). Retrying open. If you see this repeatedly under live concurrency, file an issue.`),{adapter:s,err:l}=o())}catch(a){process.env.DEBUG&&console.debug("[RVF] stale-lock recovery failed:",a instanceof Error?a.message:a)}if(u)throw new p(l);if(s){let a=s.dimension();if(a===n)return s;console.warn(`[RVF] patterns.rvf dimension mismatch: file=${a} requested=${n} \u2014 closing and degrading. Delete the .rvf file to recreate at the requested dim.`);try{s.close()}catch{}throw new Error(`RVF dimension mismatch (file=${a}, requested=${n})`)}try{return t(e,n)}catch(a){let c;try{c=r(e)}catch(m){if(R(m))throw m;if(A(e,a instanceof Error?a.message:String(a),m))return t(e,n);throw a instanceof Error?a:new Error(String(a))}let v=c.dimension();if(v!==n){try{c.close()}catch{}throw new Error(`RVF dimension mismatch after race (file=${v}, requested=${n})`)}return c}}function E(r,t){if(t?.force)return{shouldCompact:!0,trigger:"force"};let e=t?.sizeGuardBytes??B,n=t?.deadRatioThreshold??F;return r.fileSizeBytes>=e?{shouldCompact:!0,trigger:"size-guard"}:(r.deadSpaceRatio??0)>=n?{shouldCompact:!0,trigger:"dead-ratio"}:{shouldCompact:!1,trigger:"none"}}function q(r){if(!i)return null;let t;try{t=i.status()}catch{return null}let e=E(t,r);if(!e.shouldCompact)return null;let n=t.fileSizeBytes,o;try{o=i.compact()}catch{return null}return o?((o.bytesReclaimed>0||o.segmentsCompacted>0)&&console.log(`[RVF] compacted patterns.rvf: reclaimed ${d(o.bytesReclaimed)} (${o.segmentsCompacted} segments, fileSize ${d(n)} \u2192 ${d(Math.max(0,n-o.bytesReclaimed))}, trigger: ${e.trigger})`),o):null}function T(r,t){try{let e=r.status(),n=E(e);if(!n.shouldCompact)return null;let o=r.compact();return o&&(o.bytesReclaimed>0||o.segmentsCompacted>0)&&console.log(`[RVF] boot-time compact (${t}): reclaimed ${d(o.bytesReclaimed)} from ${o.segmentsCompacted} segments (trigger: ${n.trigger})`),o}catch(e){return process.env.DEBUG&&console.debug("[RVF] boot-time compact guard skipped:",e instanceof Error?e.message:e),null}}function d(r){if(!Number.isFinite(r)||r<0)return`${r}B`;let t=["B","KB","MB","GB","TB"],e=0,n=r;for(;n>=1024&&e<t.length-1;)n/=1024,e++;return`${n.toFixed(e===0?0:1)}${t[e]}`}function z(){if(i){try{i.close()}catch{}i=null}f=!1}export{p as a,V as b,k as c,_ as d,E as e,q as f,T as g,z as h};
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.17");process.exit(0)}
2
+ import{c as h,d as $}from"./chunk-GPPTRKEM.js";import{a as b,b as y,c as R,e as S,f as A}from"./chunk-U4S74IIZ.js";import{e as N,f as w}from"./chunk-QSQNXBD2.js";import{a as g,f as C}from"./chunk-Z7SKUC6P.js";$();var i=null,f=!1,p=class extends Error{constructor(e){super(e instanceof Error?e.message:String(e));this.lockError=e;this.name="RvfLiveLockError"}lockError};function V(r){i=r,f=r!==null}var B=(()=>{let r=process.env.AQE_RVF_SIZE_GUARD_BYTES,t=r?Number(r):NaN;return Number.isFinite(t)&&t>0?t:256*1024*1024})(),F=(()=>{let r=process.env.AQE_RVF_DEAD_RATIO_THRESHOLD,t=r?Number(r):NaN;return Number.isFinite(t)&&t>0&&t<=1?t:.3})();function k(r=".agentic-qe",t=384){if(f)return i;f=!0;try{let{isRvfNativeAvailable:e,createRvfStore:n,openRvfStore:o}=(w(),C(N));if(!e())return console.warn("[RVF] Native bindings unavailable \u2014 agent branching and dream COW disabled. Install @ruvector/rvf-node to enable."),null;let s=g("path"),l=s.isAbsolute(r)?r:s.join(process.env.AQE_PROJECT_ROOT??h(),r),u=s.join(l,"patterns.rvf");return i=_(o,n,u,t),T(i,u),i}catch(e){return e instanceof p||console.warn("[RVF] Shared adapter init failed:",e instanceof Error?e.message:e),null}}function _(r,t,e,n){let o=()=>{try{return{adapter:r(e),err:null}}catch(a){return{adapter:null,err:a}}},{adapter:s,err:l}=o(),u=!1;if(!s&&R(l))try{let a=g("fs"),c=`${e}.lock`;a.existsSync(c)&&y(e)?(u=!0,console.warn(`[RVF] ${e} is locked by a live process (pid ${b(e)}) \u2014 not breaking the lock; degrading to SQLite for this run.`)):S(e)&&(console.warn(`[RVF] Removed stale lock file at ${c} (prior process exited without closing). Retrying open. If you see this repeatedly under live concurrency, file an issue.`),{adapter:s,err:l}=o())}catch(a){process.env.DEBUG&&console.debug("[RVF] stale-lock recovery failed:",a instanceof Error?a.message:a)}if(u)throw new p(l);if(s){let a=s.dimension();if(a===n)return s;console.warn(`[RVF] patterns.rvf dimension mismatch: file=${a} requested=${n} \u2014 closing and degrading. Delete the .rvf file to recreate at the requested dim.`);try{s.close()}catch{}throw new Error(`RVF dimension mismatch (file=${a}, requested=${n})`)}try{return t(e,n)}catch(a){let c;try{c=r(e)}catch(m){if(R(m))throw m;if(A(e,a instanceof Error?a.message:String(a),m))return t(e,n);throw a instanceof Error?a:new Error(String(a))}let v=c.dimension();if(v!==n){try{c.close()}catch{}throw new Error(`RVF dimension mismatch after race (file=${v}, requested=${n})`)}return c}}function E(r,t){if(t?.force)return{shouldCompact:!0,trigger:"force"};let e=t?.sizeGuardBytes??B,n=t?.deadRatioThreshold??F;return r.fileSizeBytes>=e?{shouldCompact:!0,trigger:"size-guard"}:(r.deadSpaceRatio??0)>=n?{shouldCompact:!0,trigger:"dead-ratio"}:{shouldCompact:!1,trigger:"none"}}function q(r){if(!i)return null;let t;try{t=i.status()}catch{return null}let e=E(t,r);if(!e.shouldCompact)return null;let n=t.fileSizeBytes,o;try{o=i.compact()}catch{return null}return o?((o.bytesReclaimed>0||o.segmentsCompacted>0)&&console.log(`[RVF] compacted patterns.rvf: reclaimed ${d(o.bytesReclaimed)} (${o.segmentsCompacted} segments, fileSize ${d(n)} \u2192 ${d(Math.max(0,n-o.bytesReclaimed))}, trigger: ${e.trigger})`),o):null}function T(r,t){try{let e=r.status(),n=E(e);if(!n.shouldCompact)return null;let o=r.compact();return o&&(o.bytesReclaimed>0||o.segmentsCompacted>0)&&console.log(`[RVF] boot-time compact (${t}): reclaimed ${d(o.bytesReclaimed)} from ${o.segmentsCompacted} segments (trigger: ${n.trigger})`),o}catch(e){return process.env.DEBUG&&console.debug("[RVF] boot-time compact guard skipped:",e instanceof Error?e.message:e),null}}function d(r){if(!Number.isFinite(r)||r<0)return`${r}B`;let t=["B","KB","MB","GB","TB"],e=0,n=r;for(;n>=1024&&e<t.length-1;)n/=1024,e++;return`${n.toFixed(e===0?0:1)}${t[e]}`}function z(){if(i){try{i.close()}catch{}i=null}f=!1}export{p as a,V as b,k as c,_ as d,E as e,q as f,T as g,z as h};
@@ -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.15.16");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.17");process.exit(0)}
2
2
  var t=["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","requirements-validation","code-intelligence","security-compliance","contract-testing","visual-accessibility","chaos-resilience","learning-optimization","enterprise-integration","coordination"];function i(e){return typeof e=="string"&&t.includes(e)}function o(e){return{success:!0,value:e}}function a(e){return{success:!1,error:e}}var n=["p0","p1","p2","p3"];function s(e){return typeof e=="string"&&n.includes(e)}function l(e){return`Invalid priority: ${e===""?"(empty)":String(e)}. Valid priorities: ${n.join(", ")}`}export{t as a,i as b,o as c,a as d,s as e,l as f};