agentic-qe 3.9.1 → 3.9.2

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 (277) hide show
  1. package/.claude/skills/skills-manifest.json +1 -1
  2. package/CHANGELOG.md +11 -0
  3. package/dist/cli/bundle.js +8 -8
  4. package/dist/cli/chunks/adapter-53WBPKXU.js +2 -0
  5. package/dist/cli/chunks/{agent-booster-wasm-UH2J6BNA.js → agent-booster-wasm-AKAOHSCX.js} +2 -2
  6. package/dist/cli/chunks/{agent-handler-ZCBWQE3X.js → agent-handler-MTGPOUVP.js} +2 -2
  7. package/dist/cli/chunks/{agent-memory-branch-2BAVI7UW.js → agent-memory-branch-UFPKWUFK.js} +2 -2
  8. package/dist/cli/chunks/aqe-learning-engine-MV7NGY24.js +2 -0
  9. package/dist/cli/chunks/{audit-G5UIJBSQ.js → audit-VBEZHNHO.js} +2 -2
  10. package/dist/cli/chunks/base-DZVGMQN2.js +2 -0
  11. package/dist/cli/chunks/{better-sqlite3-YHIAPPVT.js → better-sqlite3-IRPHIXRU.js} +2 -2
  12. package/dist/cli/chunks/{brain-handler-5EE3J5PR.js → brain-handler-7EO3FFRZ.js} +3 -3
  13. package/dist/cli/chunks/{branch-enumerator-OV54PID5.js → branch-enumerator-MZRGP35N.js} +2 -2
  14. package/dist/cli/chunks/{browser-7RZGKOEO.js → browser-VSIWQE7J.js} +2 -2
  15. package/dist/cli/chunks/browser-workflow-3J5YNMEI.js +2 -0
  16. package/dist/cli/chunks/{chunk-YUQIXT3G.js → chunk-25LFUL2K.js} +2 -2
  17. package/dist/cli/chunks/{chunk-UWDBFPHQ.js → chunk-2EC5Z2J4.js} +14 -14
  18. package/dist/cli/chunks/{chunk-UBKK7KCR.js → chunk-2VVV73PW.js} +1 -1
  19. package/dist/cli/chunks/{chunk-SVNX4UWR.js → chunk-2WBCYSUN.js} +8 -8
  20. package/dist/cli/chunks/{chunk-HTXSUTWL.js → chunk-2Z2TFEOL.js} +2 -2
  21. package/dist/cli/chunks/{chunk-XUFHYPZK.js → chunk-34U7JDCN.js} +2 -2
  22. package/dist/cli/chunks/{chunk-43M6Y6VF.js → chunk-3GZKAORV.js} +2 -2
  23. package/dist/cli/chunks/{chunk-3VAKR43Z.js → chunk-4D2ZG2QO.js} +1 -1
  24. package/dist/cli/chunks/{chunk-NG3BKE7V.js → chunk-4DAOZQ3V.js} +2 -2
  25. package/dist/cli/chunks/{chunk-D4PSFWND.js → chunk-4FMHBBG5.js} +1 -1
  26. package/dist/cli/chunks/{chunk-V4HM4QAO.js → chunk-4FT3PND7.js} +3 -3
  27. package/dist/cli/chunks/{chunk-RU6Q5HOC.js → chunk-4LA7IW3V.js} +1 -1
  28. package/dist/cli/chunks/{chunk-XPB6ZVQY.js → chunk-4PKXIBX2.js} +1 -1
  29. package/dist/cli/chunks/{chunk-C24ZDUCM.js → chunk-4UH25U4O.js} +1 -1
  30. package/dist/cli/chunks/{chunk-7JQTHPCD.js → chunk-4Z27TRQF.js} +2 -2
  31. package/dist/cli/chunks/{chunk-WLXEDOG4.js → chunk-563PJBDM.js} +2 -2
  32. package/dist/cli/chunks/{chunk-XTLA4F5Z.js → chunk-56IWS2KY.js} +2 -2
  33. package/dist/cli/chunks/{chunk-XP6XKBNW.js → chunk-5AUKULWO.js} +2 -2
  34. package/dist/cli/chunks/{chunk-X4MZYBOU.js → chunk-5L6AU3QK.js} +2 -2
  35. package/dist/cli/chunks/{chunk-4XBY5JDT.js → chunk-5RL66XSH.js} +2 -2
  36. package/dist/cli/chunks/{chunk-EQFZQPFN.js → chunk-65M7C6SH.js} +1 -1
  37. package/dist/cli/chunks/{chunk-7YUOUVN7.js → chunk-6SOJVEU7.js} +2 -2
  38. package/dist/cli/chunks/{chunk-35H73OPP.js → chunk-727BDQ3K.js} +2 -2
  39. package/dist/cli/chunks/{chunk-5GPTM2RV.js → chunk-7NOIIC7G.js} +1 -1
  40. package/dist/cli/chunks/{chunk-US7INRP2.js → chunk-7SLN2JGP.js} +3 -3
  41. package/dist/cli/chunks/{chunk-E33KQBMW.js → chunk-AA33R5U4.js} +2 -2
  42. package/dist/cli/chunks/{chunk-O636JKJR.js → chunk-AKSJQ6B3.js} +2 -2
  43. package/dist/cli/chunks/{chunk-5LDBKZ6P.js → chunk-BIVIPF4O.js} +1 -1
  44. package/dist/cli/chunks/{chunk-JCEY7RLP.js → chunk-BKCTNRC5.js} +2 -2
  45. package/dist/cli/chunks/{chunk-TL7ABIMP.js → chunk-BOH22AKC.js} +2 -2
  46. package/dist/cli/chunks/{chunk-3JESHZQM.js → chunk-BY47GV4T.js} +2 -2
  47. package/dist/cli/chunks/{chunk-IJKYJGJL.js → chunk-CCYMJKWX.js} +1 -1
  48. package/dist/cli/chunks/{chunk-YYYB2JN5.js → chunk-CL3K5EJK.js} +2 -2
  49. package/dist/cli/chunks/{chunk-KIGRLIU4.js → chunk-CQBSGYRA.js} +2 -2
  50. package/dist/cli/chunks/{chunk-HAUXLXKZ.js → chunk-CQP7ZFME.js} +2 -2
  51. package/dist/cli/chunks/{chunk-MZ54VM6A.js → chunk-DBE34QES.js} +2 -2
  52. package/dist/cli/chunks/{chunk-WXXAAXNS.js → chunk-DHE66JRR.js} +1 -1
  53. package/dist/cli/chunks/{chunk-VEWIT6VN.js → chunk-DNLMZTE2.js} +1 -1
  54. package/dist/cli/chunks/{chunk-QAYTL6KC.js → chunk-DSE57A5N.js} +1 -1
  55. package/dist/cli/chunks/{chunk-UB7RGVKO.js → chunk-E25S5E2D.js} +1 -1
  56. package/dist/cli/chunks/{chunk-XU6L2VJY.js → chunk-FAXVVLPL.js} +2 -2
  57. package/dist/cli/chunks/chunk-FRJLP7IB.js +2 -0
  58. package/dist/cli/chunks/{chunk-LCOEBFAB.js → chunk-FUIHWBVF.js} +1 -1
  59. package/dist/cli/chunks/{chunk-6BSJNG2S.js → chunk-GCMVJS5X.js} +2 -2
  60. package/dist/cli/chunks/{chunk-VCCMCFDU.js → chunk-GITD7SRQ.js} +2 -2
  61. package/dist/cli/chunks/{chunk-24E47G3D.js → chunk-GK72GUHA.js} +2 -2
  62. package/dist/cli/chunks/{chunk-TOLYWONQ.js → chunk-GPLERTZU.js} +2 -2
  63. package/dist/cli/chunks/{chunk-V4U3CTS2.js → chunk-HW4ISY5B.js} +3 -3
  64. package/dist/cli/chunks/{chunk-WDJBGXC2.js → chunk-ICDXWIFZ.js} +1 -1
  65. package/dist/cli/chunks/{chunk-RXVYOXDB.js → chunk-J4BS6IWE.js} +1 -1
  66. package/dist/cli/chunks/{chunk-A57BEPL7.js → chunk-JOVINE23.js} +2 -2
  67. package/dist/cli/chunks/{chunk-I5WZ2NM2.js → chunk-JV7LX6OT.js} +4 -4
  68. package/dist/cli/chunks/{chunk-VY74OMGQ.js → chunk-KBA7FBK3.js} +3 -3
  69. package/dist/cli/chunks/{chunk-3WQNW6CH.js → chunk-KDDZYXP4.js} +2 -2
  70. package/dist/cli/chunks/{chunk-ZEUVPLGX.js → chunk-KNVAAVHH.js} +2 -2
  71. package/dist/cli/chunks/{chunk-YQWB4QUP.js → chunk-KQTJ2YLI.js} +4 -4
  72. package/dist/cli/chunks/{chunk-5KBQQP3X.js → chunk-KTYUCZEM.js} +2 -2
  73. package/dist/cli/chunks/{chunk-AREIP4FX.js → chunk-KZTO5EVM.js} +2 -2
  74. package/dist/cli/chunks/{chunk-L4H54Z27.js → chunk-KZUJBZ7B.js} +2 -2
  75. package/dist/cli/chunks/{chunk-IHWSNYL2.js → chunk-L5WZUPZF.js} +2 -2
  76. package/dist/cli/chunks/{chunk-OFNIQCGX.js → chunk-L5YEPSDU.js} +2 -2
  77. package/dist/cli/chunks/{chunk-4XREPCBZ.js → chunk-LCAA6H4J.js} +2 -2
  78. package/dist/cli/chunks/{chunk-TPXYS3WG.js → chunk-LMMEUVE5.js} +1 -1
  79. package/dist/cli/chunks/{chunk-SGRN6JFB.js → chunk-MN742FIH.js} +2 -2
  80. package/dist/cli/chunks/{chunk-DMGLX76J.js → chunk-MY4LMIG7.js} +2 -2
  81. package/dist/cli/chunks/{chunk-JSOBRKMA.js → chunk-N3F3CX4V.js} +2 -2
  82. package/dist/cli/chunks/{chunk-7ATLJCSG.js → chunk-NJY7ZA77.js} +1 -1
  83. package/dist/cli/chunks/{chunk-XE2YAYU5.js → chunk-NM6TIEJ3.js} +3 -3
  84. package/dist/cli/chunks/{chunk-ZSRQHJEW.js → chunk-NRCKGXJJ.js} +1 -1
  85. package/dist/cli/chunks/{chunk-IQPXANCE.js → chunk-PFNFC43Q.js} +1 -1
  86. package/dist/cli/chunks/{chunk-VNYGVG4Y.js → chunk-PJFLO37I.js} +2 -2
  87. package/dist/cli/chunks/{chunk-4LWXZCSD.js → chunk-PNL5G6TE.js} +2 -2
  88. package/dist/cli/chunks/{chunk-POLFT2PQ.js → chunk-Q4A72ZTV.js} +2 -2
  89. package/dist/cli/chunks/{chunk-6YC24TPL.js → chunk-QEQTC4WQ.js} +2 -2
  90. package/dist/cli/chunks/{chunk-NB47YT6A.js → chunk-QIH3E775.js} +2 -2
  91. package/dist/cli/chunks/{chunk-FRNB4CH2.js → chunk-QNBQBSAI.js} +2 -2
  92. package/dist/cli/chunks/{chunk-NG4TE3OW.js → chunk-QODE4LM6.js} +2 -2
  93. package/dist/cli/chunks/{chunk-BEHP3DEF.js → chunk-QPRVX4H2.js} +2 -2
  94. package/dist/cli/chunks/{chunk-RWXI7XAR.js → chunk-RC5CPXON.js} +2 -2
  95. package/dist/cli/chunks/{chunk-FPRL6UDF.js → chunk-RITN3XR4.js} +2 -2
  96. package/dist/cli/chunks/{chunk-FWDKVTK4.js → chunk-RJROC5M3.js} +2 -2
  97. package/dist/cli/chunks/{chunk-RV6SGDET.js → chunk-RQGYJK7H.js} +2 -2
  98. package/dist/cli/chunks/{chunk-B2I7BJLL.js → chunk-S3RDH5CI.js} +2 -2
  99. package/dist/cli/chunks/{chunk-4TNXEANY.js → chunk-SCF7NRVE.js} +1 -1
  100. package/dist/cli/chunks/{chunk-UN4PA4M2.js → chunk-SDTVHR63.js} +2 -2
  101. package/dist/cli/chunks/{chunk-WDV6TN7E.js → chunk-SGAW2WLI.js} +6 -6
  102. package/dist/cli/chunks/{chunk-AFPMCMVX.js → chunk-SNVM4YJS.js} +2 -2
  103. package/dist/cli/chunks/{chunk-OTSJU5LH.js → chunk-SRRFWTNF.js} +2 -2
  104. package/dist/cli/chunks/{chunk-Y2ZEDXTV.js → chunk-STE42EMB.js} +2 -2
  105. package/dist/cli/chunks/{chunk-GNUUBTSX.js → chunk-T5GV6UIO.js} +2 -2
  106. package/dist/cli/chunks/{chunk-DC3HPOOJ.js → chunk-TKF447CW.js} +1 -1
  107. package/dist/cli/chunks/{chunk-XSITQBYB.js → chunk-TTOE336G.js} +3 -3
  108. package/dist/cli/chunks/{chunk-7ZNINH6J.js → chunk-UKDOMLBI.js} +3 -3
  109. package/dist/cli/chunks/{chunk-GJW6V35N.js → chunk-V6XBAZNH.js} +1 -1
  110. package/dist/cli/chunks/{chunk-GLIFZWV2.js → chunk-VHVWAXCF.js} +1 -1
  111. package/dist/cli/chunks/{chunk-RKIGOARX.js → chunk-VL7YOOC2.js} +2 -2
  112. package/dist/cli/chunks/{chunk-QMFP5OKH.js → chunk-VUAO4VFC.js} +2 -2
  113. package/dist/cli/chunks/{chunk-36X2O3BL.js → chunk-WG4GHAML.js} +2 -2
  114. package/dist/cli/chunks/{chunk-O6QQ4HLS.js → chunk-WXWY2GAF.js} +2 -2
  115. package/dist/cli/chunks/{chunk-XRVUSKQV.js → chunk-X35GP7TR.js} +1 -1
  116. package/dist/cli/chunks/{chunk-UMGWGX7C.js → chunk-X6LCMOGC.js} +2 -2
  117. package/dist/cli/chunks/{chunk-VO3OVD5D.js → chunk-XFMKJ3UD.js} +1 -1
  118. package/dist/cli/chunks/{chunk-I7TA453K.js → chunk-XH53ARZD.js} +2 -2
  119. package/dist/cli/chunks/chunk-XIBVVZGB.js +2 -0
  120. package/dist/cli/chunks/{chunk-GFNUESMU.js → chunk-XYJL6DKI.js} +2 -2
  121. package/dist/cli/chunks/{chunk-IF6GW6IY.js → chunk-Y6O7CDLI.js} +2 -2
  122. package/dist/cli/chunks/{chunk-UZZCWWIG.js → chunk-YXCU4CJX.js} +1 -1
  123. package/dist/cli/chunks/{chunk-D55PSO5D.js → chunk-Z2IKNC5M.js} +1 -1
  124. package/dist/cli/chunks/{chunk-RAJO7VML.js → chunk-Z54EO6E6.js} +2 -2
  125. package/dist/cli/chunks/{chunk-4BHOAQJH.js → chunk-Z5HXGVXZ.js} +1 -1
  126. package/dist/cli/chunks/{ci-N4NTYAAI.js → ci-2BCOBWFG.js} +2 -2
  127. package/dist/cli/chunks/{ci-output-XYR2PSYH.js → ci-output-FB4OJHAC.js} +2 -2
  128. package/dist/cli/chunks/{claude-flow-setup-FX7PRBJV.js → claude-flow-setup-NEEFZTMB.js} +2 -2
  129. package/dist/cli/chunks/client-EF555KYW.js +2 -0
  130. package/dist/cli/chunks/{cline-installer-GTHQOK7U.js → cline-installer-ODO2PS4K.js} +2 -2
  131. package/dist/cli/chunks/{code-4G6ZHVNI.js → code-NSOF62VE.js} +2 -2
  132. package/dist/cli/chunks/{code-index-extractor-MKJTP5AK.js → code-index-extractor-YQL5XN52.js} +2 -2
  133. package/dist/cli/chunks/{codex-installer-UGS773DT.js → codex-installer-SPEY6VYT.js} +2 -2
  134. package/dist/cli/chunks/{completions-B3BXNXAU.js → completions-OWKBUMBE.js} +2 -2
  135. package/dist/cli/chunks/{complexity-analyzer-PMN77CUP.js → complexity-analyzer-PGTXKP73.js} +2 -2
  136. package/dist/cli/chunks/{continuedev-installer-3DYKSIP3.js → continuedev-installer-KGOXAC7L.js} +2 -2
  137. package/dist/cli/chunks/{copilot-installer-IUC5HDHD.js → copilot-installer-BF3UA3TG.js} +2 -2
  138. package/dist/cli/chunks/{cost-tracker-GSGQ7O5T.js → cost-tracker-2HDJ66E2.js} +2 -2
  139. package/dist/cli/chunks/{coverage-PO72QC3P.js → coverage-KPA2PHIN.js} +3 -3
  140. package/dist/cli/chunks/cross-domain-router-GXFNK5TS.js +2 -0
  141. package/dist/cli/chunks/{cursor-installer-FK53S3ZL.js → cursor-installer-7CDZFHTV.js} +2 -2
  142. package/dist/cli/chunks/{daemon-4UIQTQ73.js → daemon-4BPGCKDJ.js} +3 -3
  143. package/dist/cli/chunks/{dag-attention-scheduler-ZGIMLECE.js → dag-attention-scheduler-2MAVGSBB.js} +2 -2
  144. package/dist/cli/chunks/{detect-XXHLTLL7.js → detect-WRPWTGP5.js} +2 -2
  145. package/dist/cli/chunks/{domain-handler-PPGFP7P4.js → domain-handler-JZVSJ7AG.js} +2 -2
  146. package/dist/cli/chunks/{domain-transfer-Q5UAE65W.js → domain-transfer-XGIZOR2X.js} +2 -2
  147. package/dist/cli/chunks/dream-3IKF5XH4.js +2 -0
  148. package/dist/cli/chunks/esm-node-DHAE52OW.js +2 -0
  149. package/dist/cli/chunks/{eval-JVJKHSTQ.js → eval-T7YPAS4G.js} +2 -2
  150. package/dist/cli/chunks/{fast-paths-3KX4ZV66.js → fast-paths-QECJTKCQ.js} +2 -2
  151. package/dist/cli/chunks/{feature-flags-GKHHG2I2.js → feature-flags-LIFURSFZ.js} +2 -2
  152. package/dist/cli/chunks/{feature-flags-2NOVE7DL.js → feature-flags-R4QZYTIW.js} +2 -2
  153. package/dist/cli/chunks/{file-discovery-XFSGQNM3.js → file-discovery-4W3K3W4C.js} +2 -2
  154. package/dist/cli/chunks/{fleet-FOIDAXLR.js → fleet-NLLQWCI5.js} +3 -3
  155. package/dist/cli/chunks/{gnn-wrapper-HPCQREKP.js → gnn-wrapper-XEII72LN.js} +2 -2
  156. package/dist/cli/chunks/{heartbeat-handler-HTR3EFFV.js → heartbeat-handler-DJ65RE5D.js} +4 -4
  157. package/dist/cli/chunks/{heartbeat-scheduler-NZQWN7CH.js → heartbeat-scheduler-H664265Q.js} +2 -2
  158. package/dist/cli/chunks/hnsw-adapter-DML5KXQR.js +2 -0
  159. package/dist/cli/chunks/hnsw-index-BUPPGVR6.js +2 -0
  160. package/dist/cli/chunks/{hnsw-legacy-bridge-H6OA3AA3.js → hnsw-legacy-bridge-SQIDTWAA.js} +2 -2
  161. package/dist/cli/chunks/{hnswlib-node-FF27BDMD.js → hnswlib-node-WICYCU5U.js} +2 -2
  162. package/dist/cli/chunks/{hooks-63NZQ7NH.js → hooks-GZUHUD63.js} +6 -6
  163. package/dist/cli/chunks/{hypergraph-engine-XMSLA4XH.js → hypergraph-engine-MLCDZ6BL.js} +2 -2
  164. package/dist/cli/chunks/{hypergraph-handler-ID6J6GS2.js → hypergraph-handler-NNDDI4R3.js} +3 -3
  165. package/dist/cli/chunks/impact-analyzer-DPTMJRYS.js +2 -0
  166. package/dist/cli/chunks/{init-handler-CIKZGGAY.js → init-handler-IJ6BHE6A.js} +6 -6
  167. package/dist/cli/chunks/init-wizard-35PUDJPW.js +2 -0
  168. package/dist/cli/chunks/kernel-2HZ44ZJ4.js +2 -0
  169. package/dist/cli/chunks/{kilocode-installer-N7NLISYY.js → kilocode-installer-EPZFFPFE.js} +2 -2
  170. package/dist/cli/chunks/{kiro-installer-U6XIPAT3.js → kiro-installer-5VACG3HU.js} +2 -2
  171. package/dist/cli/chunks/knowledge-graph-JL62G72U.js +2 -0
  172. package/dist/cli/chunks/{learning-NKOF7KDJ.js → learning-6FITK6XY.js} +3 -3
  173. package/dist/cli/chunks/{llm-router-34WHT3PH.js → llm-router-4DDC6AKJ.js} +2 -2
  174. package/dist/cli/chunks/{load-ZW4Z3YLT.js → load-KGDNVUBX.js} +2 -2
  175. package/dist/cli/chunks/load-test-LN245SSD.js +2 -0
  176. package/dist/cli/chunks/{mcp-6R7SVGKO.js → mcp-4LETGVIV.js} +2 -2
  177. package/dist/cli/chunks/{memory-OUYCBU4M.js → memory-II4I4QMO.js} +5 -5
  178. package/dist/cli/chunks/memory-backend-SVM7YRIE.js +2 -0
  179. package/dist/cli/chunks/memory-handlers-TQXTOJGQ.js +2 -0
  180. package/dist/cli/chunks/{opencode-installer-FR75GHFU.js → opencode-installer-EU6JCWBW.js} +2 -2
  181. package/dist/cli/chunks/{orchestrator-AK7ZMVNH.js → orchestrator-YLMGJVSP.js} +5 -5
  182. package/dist/cli/chunks/{pipeline-CFOPG7EM.js → pipeline-MPZJWYKK.js} +2 -2
  183. package/dist/cli/chunks/{platform-NY3ULBR7.js → platform-YH35ZZFZ.js} +2 -2
  184. package/dist/cli/chunks/{plugin-LRANQYUR.js → plugin-B7JYZFNQ.js} +2 -2
  185. package/dist/cli/chunks/{prime-radiant-advanced-wasm-6KEIU55P.js → prime-radiant-advanced-wasm-KTUK6UE2.js} +2 -2
  186. package/dist/cli/chunks/protocol-executor-IEN2XB4L.js +2 -0
  187. package/dist/cli/chunks/{protocol-handler-ESSZGJ7R.js → protocol-handler-3NXMVU34.js} +2 -2
  188. package/dist/cli/chunks/{prove-EF2PPY65.js → prove-H5LMGSUC.js} +2 -2
  189. package/dist/cli/chunks/qe-reasoning-bank-Q3ZV3JRG.js +2 -0
  190. package/dist/cli/chunks/{quality-AYBXB635.js → quality-RCWHY6GO.js} +2 -2
  191. package/dist/cli/chunks/queen-coordinator-E6ON3JUR.js +2 -0
  192. package/dist/cli/chunks/{real-embeddings-QPBXE7MA.js → real-embeddings-NKH4VURF.js} +2 -2
  193. package/dist/cli/chunks/{roocode-installer-UF6MMBH6.js → roocode-installer-SB7QJYM3.js} +2 -2
  194. package/dist/cli/chunks/router-WMC3LZ3C.js +2 -0
  195. package/dist/cli/chunks/routing-feedback-VKCZRCE3.js +2 -0
  196. package/dist/cli/chunks/{routing-handler-5TVKFU7V.js → routing-handler-SY7GKG2W.js} +2 -2
  197. package/dist/cli/chunks/{ruvector-commands-E33VXFIA.js → ruvector-commands-HATTO3UQ.js} +2 -2
  198. package/dist/cli/chunks/{rvf-dual-writer-O3AZKD24.js → rvf-dual-writer-D57EXQUD.js} +2 -2
  199. package/dist/cli/chunks/{rvf-migration-adapter-IKEUZ2HX.js → rvf-migration-adapter-OWDYN6KD.js} +2 -2
  200. package/dist/cli/chunks/{rvf-migration-coordinator-M4H7W4RN.js → rvf-migration-coordinator-SIQVJB5S.js} +2 -2
  201. package/dist/cli/chunks/rvf-native-adapter-C7NBH5UN.js +2 -0
  202. package/dist/cli/chunks/safe-db-5KLXCNXN.js +2 -0
  203. package/dist/cli/chunks/schedule-HAWWOXWB.js +2 -0
  204. package/dist/cli/chunks/scheduler-HTRDY5BC.js +2 -0
  205. package/dist/cli/chunks/{security-ZLWT7IU3.js → security-DS3XLZWN.js} +3 -3
  206. package/dist/cli/chunks/shared-rvf-adapter-6I2Z5UGL.js +2 -0
  207. package/dist/cli/chunks/{shared-rvf-dual-writer-G43LQDIV.js → shared-rvf-dual-writer-YB7AH6XJ.js} +2 -2
  208. package/dist/cli/chunks/sqlite-persistence-WNNRGTGG.js +2 -0
  209. package/dist/cli/chunks/{status-handler-7P23CXUI.js → status-handler-TUYHE4FT.js} +2 -2
  210. package/dist/cli/chunks/{structural-health-SCNBNL7K.js → structural-health-XNGBNRRD.js} +2 -2
  211. package/dist/cli/chunks/{sync-BYZBBH65.js → sync-K6CIRKBB.js} +2 -2
  212. package/dist/cli/chunks/{task-handler-DWJQXZ2K.js → task-handler-7PJY67DR.js} +2 -2
  213. package/dist/cli/chunks/task-handlers-WB5CDWUR.js +2 -0
  214. package/dist/cli/chunks/{test-2JSS4XW7.js → test-WV5ALEBB.js} +4 -4
  215. package/dist/cli/chunks/{test-scheduling-TWJ5I7N3.js → test-scheduling-N55ZGGA2.js} +3 -3
  216. package/dist/cli/chunks/token-bootstrap-SINWHAKR.js +2 -0
  217. package/dist/cli/chunks/{token-usage-EQ4HM4EZ.js → token-usage-R7TGEVGL.js} +2 -2
  218. package/dist/cli/chunks/{transformers-PBIR5U5S.js → transformers-6DBLXPV7.js} +2 -2
  219. package/dist/cli/chunks/{tree-sitter-wasm-parser-X3L2GXUX.js → tree-sitter-wasm-parser-7C7FKMQW.js} +2 -2
  220. package/dist/cli/chunks/{types-OD43K2NP.js → types-VNPMOKQT.js} +2 -2
  221. package/dist/cli/chunks/unified-memory-72SKVZ7Y.js +2 -0
  222. package/dist/cli/chunks/unified-memory-hnsw-TMN2L77W.js +2 -0
  223. package/dist/cli/chunks/unified-persistence-MDN3SRCR.js +2 -0
  224. package/dist/cli/chunks/{validate-POMLT2KU.js → validate-53MNIRAF.js} +2 -2
  225. package/dist/cli/chunks/{validate-swarm-UOC4JGZT.js → validate-swarm-ZY4RGUFO.js} +2 -2
  226. package/dist/cli/chunks/{vibium-5JF6LAXI.js → vibium-PBADBIV6.js} +2 -2
  227. package/dist/cli/chunks/visual-security-TRBCXPIB.js +2 -0
  228. package/dist/cli/chunks/{web-tree-sitter-R7WR7J7B.js → web-tree-sitter-O7VI6RLB.js} +2 -2
  229. package/dist/cli/chunks/{windsurf-installer-ZSPEUBKR.js → windsurf-installer-HV3C3TAD.js} +2 -2
  230. package/dist/cli/chunks/{witness-chain-CFSPCXHG.js → witness-chain-4WIMYP4X.js} +2 -2
  231. package/dist/cli/chunks/witness-chain-JOI2YYGK.js +2 -0
  232. package/dist/cli/chunks/{workflow-YNQT3OW2.js → workflow-5RVAQ4TM.js} +4 -4
  233. package/dist/cli/chunks/workflow-orchestrator-2NQ72S3C.js +2 -0
  234. package/dist/cli/chunks/{wrappers-BP4FODVH.js → wrappers-RRHCCA3E.js} +2 -2
  235. package/dist/cli/index.js +10 -15
  236. package/dist/learning/pattern-store.js +25 -3
  237. package/dist/learning/rvf-pattern-store.d.ts +3 -0
  238. package/dist/learning/rvf-pattern-store.js +4 -2
  239. package/dist/mcp/bundle.js +223 -223
  240. package/package.json +1 -1
  241. package/dist/cli/chunks/adapter-NTM4ZH3P.js +0 -2
  242. package/dist/cli/chunks/aqe-learning-engine-RVX6MPYK.js +0 -2
  243. package/dist/cli/chunks/base-7HKNQ6UP.js +0 -2
  244. package/dist/cli/chunks/browser-workflow-UOFSQK7X.js +0 -2
  245. package/dist/cli/chunks/chunk-U5JQGRHZ.js +0 -2
  246. package/dist/cli/chunks/client-CRRENRK4.js +0 -2
  247. package/dist/cli/chunks/cross-domain-router-FSCGJG3B.js +0 -2
  248. package/dist/cli/chunks/dream-PONKQULG.js +0 -2
  249. package/dist/cli/chunks/esm-node-XLWDJRBX.js +0 -2
  250. package/dist/cli/chunks/hnsw-adapter-BNA5WUAB.js +0 -2
  251. package/dist/cli/chunks/hnsw-index-RQIIAE7S.js +0 -2
  252. package/dist/cli/chunks/impact-analyzer-FS2UNVP4.js +0 -2
  253. package/dist/cli/chunks/init-wizard-TUU5PPY6.js +0 -2
  254. package/dist/cli/chunks/kernel-XFG42WAG.js +0 -2
  255. package/dist/cli/chunks/knowledge-graph-XV7FPU2T.js +0 -2
  256. package/dist/cli/chunks/load-test-F4L7RTXJ.js +0 -2
  257. package/dist/cli/chunks/memory-backend-DTJD2DWF.js +0 -2
  258. package/dist/cli/chunks/memory-handlers-WNXKZRNM.js +0 -2
  259. package/dist/cli/chunks/protocol-executor-6W4PS2D4.js +0 -2
  260. package/dist/cli/chunks/qe-reasoning-bank-7G3TZLEA.js +0 -2
  261. package/dist/cli/chunks/queen-coordinator-NFPKGMQN.js +0 -2
  262. package/dist/cli/chunks/router-F4B7Q66G.js +0 -2
  263. package/dist/cli/chunks/routing-feedback-5CIDDW7P.js +0 -2
  264. package/dist/cli/chunks/rvf-native-adapter-UX3WAPIP.js +0 -2
  265. package/dist/cli/chunks/safe-db-QBBNXEVK.js +0 -2
  266. package/dist/cli/chunks/schedule-GFT4NN6Z.js +0 -2
  267. package/dist/cli/chunks/scheduler-CQ56T7DB.js +0 -2
  268. package/dist/cli/chunks/shared-rvf-adapter-EXACQ2PT.js +0 -2
  269. package/dist/cli/chunks/sqlite-persistence-JHSUZPAW.js +0 -2
  270. package/dist/cli/chunks/task-handlers-35JIXVRW.js +0 -2
  271. package/dist/cli/chunks/token-bootstrap-LLLNJT5V.js +0 -2
  272. package/dist/cli/chunks/unified-memory-YPHONR2T.js +0 -2
  273. package/dist/cli/chunks/unified-memory-hnsw-HJS4OXWM.js +0 -2
  274. package/dist/cli/chunks/unified-persistence-EFZRO6AW.js +0 -2
  275. package/dist/cli/chunks/visual-security-7KWFLYNB.js +0 -2
  276. package/dist/cli/chunks/witness-chain-RWU6WT37.js +0 -2
  277. package/dist/cli/chunks/workflow-orchestrator-Z6TAVMQP.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.9.1");process.exit(0)}
2
- import{k as K,o as ot}from"./chunk-24E47G3D.js";import{a as rt}from"./chunk-U5JQGRHZ.js";import{c as U}from"./chunk-A57BEPL7.js";import{a as j,c as et}from"./chunk-UN4PA4M2.js";import{a as G,d as at}from"./chunk-XUFHYPZK.js";import{a as nt,b as it}from"./chunk-35H73OPP.js";import{c as H,e as V,g as w}from"./chunk-UZZCWWIG.js";var Z={};V(Z,{DotProductAttention:()=>yt,FlashAttention:()=>ft,HyperbolicAttention:()=>bt,LinearAttention:()=>vt,MoEAttention:()=>Et,MultiHeadAttention:()=>At,RuvectorLayer:()=>ut,SonaEngine:()=>P,TensorCompress:()=>mt,default:()=>ct,differentiableSearch:()=>ht,getCompressionLevel:()=>pt,hierarchicalForward:()=>dt,init:()=>gt,pipeline:()=>Ft});import{createRequire as st}from"module";var lt,$,ct,ut,mt,ht,dt,pt,gt,ft,yt,At,bt,vt,Et,P,Ft,k=H(()=>{lt=st(import.meta.url),$=lt("@ruvector/sona"),ct=$,{RuvectorLayer:ut,TensorCompress:mt,differentiableSearch:ht,hierarchicalForward:dt,getCompressionLevel:pt,init:gt,FlashAttention:ft,DotProductAttention:yt,MultiHeadAttention:At,HyperbolicAttention:bt,LinearAttention:vt,MoEAttention:Et,SonaEngine:P,pipeline:Ft}=$||{}});var N={};V(N,{DotProductAttention:()=>It,FlashAttention:()=>zt,HyperbolicAttention:()=>_t,LinearAttention:()=>Ht,MoEAttention:()=>Vt,MultiHeadAttention:()=>qt,RuvectorLayer:()=>Qt,SonaEngine:()=>jt,TensorCompress:()=>Nt,default:()=>xt,differentiableSearch:()=>Ot,getCompressionLevel:()=>Wt,hierarchicalForward:()=>Dt,init:()=>Bt,pipeline:()=>Ut});import{createRequire as kt}from"module";var Rt,X,xt,Qt,Nt,Ot,Dt,Wt,Bt,zt,It,qt,_t,Ht,Vt,jt,Ut,O=H(()=>{Rt=kt(import.meta.url),X=Rt("@ruvector/attention"),xt=X,{RuvectorLayer:Qt,TensorCompress:Nt,differentiableSearch:Ot,hierarchicalForward:Dt,getCompressionLevel:Wt,init:Bt,FlashAttention:zt,DotProductAttention:It,MultiHeadAttention:qt,HyperbolicAttention:_t,LinearAttention:Ht,MoEAttention:Vt,SonaEngine:jt,pipeline:Ut}=X||{}});k();at();import{randomUUID as Ct}from"crypto";rt();import{createRequire as wt}from"module";var f=U.create("sona-three-loop"),S=wt(import.meta.url),M=null,J=!1;function St(){if(J)return M;J=!0;try{let l=S("@ruvector/learning-wasm"),t=S("fs"),e=S("path"),r=e.join(e.dirname(S.resolve("@ruvector/learning-wasm")),"ruvector_learning_wasm_bg.wasm");l.initSync({module:t.readFileSync(r)}),M=l,f.info("WASM MicroLoRA loaded from @ruvector/learning-wasm (6.4x faster than TS)")}catch{M=null,f.debug("@ruvector/learning-wasm not available, using TypeScript MicroLoRA")}return M}var Mt={dimension:384,microLoraLr:.001,consolidationInterval:100,ewcLambda:1e3,taskBoundaryZScoreThreshold:2.5,fisherDecay:.9,fisherSampleSize:200,importanceThreshold:.01},R=class{adaptationVector;baseWeights;lr;adaptationCount=0;constructor(t,e=.001){this.adaptationVector=new Float32Array(t),this.baseWeights=new Float32Array(t),this.lr=e}adapt(t){let e=this.baseWeights.length,r=new Float32Array(e),a=Math.min(t.length,e);for(let n=0;n<e;n++){let o=n<a?t[n]:0;r[n]=this.baseWeights[n]+this.adaptationVector[n]+this.lr*o}for(let n=0;n<a;n++)this.adaptationVector[n]+=this.lr*t[n];return this.adaptationCount++,r}consolidate(){let t=this.adaptationCount,e=this.baseWeights.length;for(let r=0;r<e;r++)this.baseWeights[r]+=this.adaptationVector[r],this.adaptationVector[r]=0;return this.adaptationCount=0,t}getAdaptationCount(){return this.adaptationCount}getEffectiveWeights(){let t=this.baseWeights.length,e=new Float32Array(t);for(let r=0;r<t;r++)e[r]=this.baseWeights[r]+this.adaptationVector[r];return e}getAdaptationMagnitude(){let t=0;for(let e=0;e<this.adaptationVector.length;e++)t+=this.adaptationVector[e]*this.adaptationVector[e];return Math.sqrt(t)}resetAdaptation(){this.adaptationVector.fill(0),this.adaptationCount=0}},x=class{fisherMatrix;optimalParams;lambda;fisherDecay;zScoreThreshold;importanceThreshold;gradientHistory=[];gradientMean=0;gradientVariance=0;taskBoundaryCount=0;consolidationCount=0;constructor(t,e=1e3,r=.9,a=2.5,n=.01){this.fisherMatrix=new Float32Array(t),this.optimalParams=new Float32Array(t),this.lambda=e,this.fisherDecay=r,this.zScoreThreshold=a,this.importanceThreshold=n}detectTaskBoundary(t){let e=0;for(let i=0;i<t.length;i++)e+=t[i]*t[i];if(e=Math.sqrt(e),this.gradientHistory.length<5)return this.gradientHistory.push(e),this.updateGradientStats(),!1;let r=Math.sqrt(this.gradientVariance),a=0,n=Math.abs(e-this.gradientMean);return r>1e-10?a=n/r:n>1e-10&&this.gradientMean>1e-10&&(a=n/(this.gradientMean*.01+1e-10)),this.gradientHistory.push(e),this.gradientHistory.length>100&&this.gradientHistory.shift(),this.updateGradientStats(),a>this.zScoreThreshold?(this.taskBoundaryCount++,!0):!1}computeLoss(t){let e=0,r=Math.min(t.length,this.fisherMatrix.length,this.optimalParams.length);for(let a=0;a<r;a++){let n=t[a]-this.optimalParams[a];e+=this.fisherMatrix[a]*n*n}return this.lambda/2*e}updateFisher(t,e){if(t.length===0)return;let r=this.fisherMatrix.length,a=new Float32Array(r);for(let s of t){let u=Math.min(s.length,r);for(let c=0;c<u;c++)a[c]+=s[c]*s[c]}let n=t.length;for(let s=0;s<r;s++)a[s]/=n;let o=this.fisherDecay;for(let s=0;s<r;s++)this.fisherMatrix[s]=o*this.fisherMatrix[s]+(1-o)*a[s];let i=Math.min(e.length,r);for(let s=0;s<i;s++)this.optimalParams[s]=e[s];this.consolidationCount++}getMetrics(){let t=this.fisherMatrix.length,e=0,r=0,a=0;for(let n=0;n<t;n++)e+=this.fisherMatrix[n],this.fisherMatrix[n]>r&&(r=this.fisherMatrix[n]),this.fisherMatrix[n]>this.importanceThreshold&&a++;return{regularizationLoss:0,taskBoundariesDetected:this.taskBoundaryCount,fisherTrace:e,avgFisherImportance:t>0?e/t:0,maxFisherImportance:r,protectedParams:a,consolidationCycles:this.consolidationCount,lambda:this.lambda}}getTaskBoundaryCount(){return this.taskBoundaryCount}getFisherDiagonal(){return new Float32Array(this.fisherMatrix)}getOptimalParams(){return new Float32Array(this.optimalParams)}loadFisher(t,e){let r=this.fisherMatrix.length,a=Math.min(t.length,r),n=Math.min(e.length,r);for(let o=0;o<a;o++)this.fisherMatrix[o]=t[o];for(let o=0;o<n;o++)this.optimalParams[o]=e[o]}updateGradientStats(){let t=this.gradientHistory.length;if(t===0)return;let e=0;for(let a of this.gradientHistory)e+=a;e/=t;let r=0;for(let a of this.gradientHistory){let n=a-e;r+=n*n}r=t>1?r/(t-1):0,this.gradientMean=e,this.gradientVariance=r}},C=class{config;microLora;ewc;nativeEngine;wasmLora=null;requestCount=0;lastConsolidationRequest=0;peerStates=new Map;gradientBuffer=[];lastFeatures=null;constructor(t={},e){this.config={...Mt,...t},this.nativeEngine=e??null,this.microLora=new R(this.config.dimension,this.config.microLoraLr),this.ewc=new x(this.config.dimension,this.config.ewcLambda,this.config.fisherDecay,this.config.taskBoundaryZScoreThreshold,this.config.importanceThreshold);let r=St();if(r)try{this.wasmLora=new r.WasmMicroLoRA(this.config.dimension,1,this.config.microLoraLr),f.info("SONA Three-Loop using WASM MicroLoRA (0.07us/adapt)")}catch(a){f.debug("WASM MicroLoRA creation failed, falling back",{error:String(a)}),this.wasmLora=null}!this.wasmLora&&this.nativeEngine&&f.info("SONA Three-Loop using native @ruvector/sona engine for MicroLoRA delegation")}instantAdapt(t){let e=performance.now(),r;if(this.wasmLora)try{let o=new Float32Array(t),i=this.wasmLora.adapt(o);i&&i.length>0?(r=i,this.microLora.adapt(t)):r=this.microLora.adapt(t)}catch{r=this.microLora.adapt(t)}else if(this.nativeEngine)try{let o=this.nativeEngine.applyMicroLora(t);r=new Float32Array(o),this.microLora.adapt(t)}catch{r=this.microLora.adapt(t)}else r=this.microLora.adapt(t);let a=this.microLora.getAdaptationMagnitude();this.requestCount++,this.lastFeatures=[...t];let n=(performance.now()-e)*1e3;return{adaptedWeights:r,latencyUs:n,applied:!0,magnitude:a,requestIndex:this.requestCount}}recordOutcome(t,e){if(this.lastFeatures===null){f.warn("recordOutcome called without a preceding instantAdapt()");return}let r=this.lastFeatures.length,a=new Float32Array(r);for(let n=0;n<r;n++)a[n]=t*this.lastFeatures[n];this.gradientBuffer.push(a),this.gradientBuffer.length>this.config.fisherSampleSize&&this.gradientBuffer.shift(),this.lastFeatures=null}backgroundConsolidate(){let t=performance.now();if(this.nativeEngine)try{this.nativeEngine.forceLearn(),this.nativeEngine.tick()}catch(i){f.warn("Native SONA background learning failed, continuing with TypeScript",{error:String(i)})}let e=this.ewc.computeLoss(this.microLora.getEffectiveWeights()),r=!1;if(this.gradientBuffer.length>0){let i=this.gradientBuffer[this.gradientBuffer.length-1];r=this.ewc.detectTaskBoundary(i)}if(r&&this.gradientBuffer.length>0&&(this.ewc.updateFisher(this.gradientBuffer,this.microLora.getEffectiveWeights()),f.info("Task boundary detected, Fisher updated",{boundaries:this.ewc.getTaskBoundaryCount(),requestCount:this.requestCount})),this.gradientBuffer.length>1){let i=!1,s=this.gradientBuffer[0];for(let u=1;u<this.gradientBuffer.length&&!i;u++)for(let c=0;c<s.length;c++)if(Math.abs(this.gradientBuffer[u][c]-s[c])>1e-8){i=!0;break}i||f.warn("All gradient samples identical \u2014 Fisher estimate may be poor. Ensure recordOutcome() is called with diverse rewards.")}let a=this.microLora.consolidate();this.applyEWCRegularization();let n=this.ewc.computeLoss(this.microLora.getEffectiveWeights());this.lastConsolidationRequest=this.requestCount,this.gradientBuffer=[];let o=performance.now()-t;return{consolidated:a>0||r,adaptationsMerged:a,ewcLossBefore:e,ewcLossAfter:n,taskBoundaryDetected:r,durationMs:o}}shouldConsolidate(){return this.requestCount-this.lastConsolidationRequest>=this.config.consolidationInterval}syncWithPeers(t){if(t.length===0)return;for(let i of t)this.peerStates.set(i.peerId,i);let e=this.config.dimension,r=new Float32Array(e),a=new Float32Array(e),n=this.ewc.getFisherDiagonal(),o=this.microLora.adaptationVector;for(let i=0;i<e;i++){let s=n[i]+1e-10;r[i]+=s*o[i],a[i]+=s}for(let i of t){let s=Math.min(i.adaptationVector.length,e);for(let u=0;u<s;u++){let c=(u<i.fisherDiagonal.length?i.fisherDiagonal[u]:0)+1e-10;r[u]+=c*i.adaptationVector[u],a[u]+=c}}for(let i=0;i<e;i++)this.microLora.adaptationVector[i]=r[i]/a[i];f.debug("Synced with peers",{peerCount:t.length,peersStored:this.peerStates.size})}getLocalPeerState(t,e){return{peerId:t,domain:e,adaptationVector:new Float32Array(this.microLora.adaptationVector),fisherDiagonal:this.ewc.getFisherDiagonal(),requestCount:this.requestCount,lastUpdateMs:Date.now()}}getEWCMetrics(){let t=this.ewc.getMetrics();return t.regularizationLoss=this.ewc.computeLoss(this.microLora.getEffectiveWeights()),t}getFisherDiagonal(){return this.ewc.getFisherDiagonal()}getOptimalParams(){return this.ewc.getOptimalParams()}loadFisher(t,e){this.ewc.loadFisher(t,e)}getBaseWeights(){return new Float32Array(this.microLora.baseWeights)}setBaseWeights(t){let e=Math.min(t.length,this.microLora.baseWeights.length);for(let r=0;r<e;r++)this.microLora.baseWeights[r]=t[r]}getEffectiveWeights(){return this.microLora.getEffectiveWeights()}getRequestCount(){return this.requestCount}getConfig(){return{...this.config}}getPeerStates(){return new Map(this.peerStates)}getMicroLoRA(){return this.microLora}getEWC(){return this.ewc}applyEWCRegularization(){let t=this.config.dimension,e=this.ewc.fisherMatrix,r=this.ewc.optimalParams,a=this.microLora.baseWeights,n=.01;for(let o=0;o<t;o++)if(e[o]>this.config.importanceThreshold){let i=a[o]-r[o];a[o]-=n*e[o]*i}}persistFisher(t,e){let r=this.ewc.getMetrics();t(e,this.ewc.getFisherDiagonal(),this.ewc.getOptimalParams(),this.getBaseWeights(),{taskBoundaries:r.taskBoundariesDetected,consolidationCycles:r.consolidationCycles,requestCount:this.requestCount,ewcLambda:r.lambda}),f.info("Fisher matrix persisted to SQLite",{domain:e,requestCount:this.requestCount,taskBoundaries:r.taskBoundariesDetected})}restoreFisher(t){this.ewc.loadFisher(t.fisherDiagonal,t.optimalParams),t.baseWeights&&this.setBaseWeights(t.baseWeights),this.requestCount=t.requestCount,f.info("Fisher matrix restored from SQLite",{requestCount:t.requestCount,dimension:t.fisherDiagonal.length})}};var Lt={hiddenDim:256,embeddingDim:384,microLoraRank:1,baseLoraRank:8,microLoraLr:.001,baseLoraLr:1e-4,ewcLambda:1e3,patternClusters:50,trajectoryCapacity:1e4,backgroundIntervalMs:36e5,qualityThreshold:.5,enableSimd:!0,minConfidence:.5,maxPatterns:1e4},Q=class{patterns;trajectoryMap;maxPatterns;constructor(t=1e4){this.patterns=new Map,this.trajectoryMap=new Map,this.maxPatterns=t}register(t){if(this.patterns.size>=this.maxPatterns&&!this.patterns.has(t.id)){let e=Array.from(this.patterns.entries()).sort(([,r],[,a])=>(r.lastUsedAt?.getTime()??r.createdAt.getTime())-(a.lastUsedAt?.getTime()??a.createdAt.getTime()))[0];e&&this.patterns.delete(e[0])}this.patterns.set(t.id,t)}get(t){return this.patterns.get(t)}getByTrajectory(t){let e=this.trajectoryMap.get(t);return e?this.patterns.get(e):void 0}associateTrajectory(t,e){this.trajectoryMap.set(t,e)}update(t,e){let r=this.patterns.get(t);return r?(this.patterns.set(t,{...r,...e}),!0):!1}getAll(){return Array.from(this.patterns.values())}getByType(t){return Array.from(this.patterns.values()).filter(e=>e.type===t)}getByDomain(t){return Array.from(this.patterns.values()).filter(e=>e.domain===t)}clear(){this.patterns.clear(),this.trajectoryMap.clear()}size(){return this.patterns.size}},v=class{engine;registry;config;adaptationTimes=[];cacheHits=0;totalAdaptations=0;threeLoopEngine=null;fisherPersistFn=null;fisherDomain="default";constructor(t={}){this.config={...Lt,...t};let e={hiddenDim:this.config.hiddenDim,embeddingDim:this.config.embeddingDim,microLoraRank:this.config.microLoraRank,baseLoraRank:this.config.baseLoraRank,microLoraLr:this.config.microLoraLr,baseLoraLr:this.config.baseLoraLr,ewcLambda:this.config.ewcLambda,patternClusters:this.config.patternClusters,trajectoryCapacity:this.config.trajectoryCapacity,backgroundIntervalMs:this.config.backgroundIntervalMs,qualityThreshold:this.config.qualityThreshold,enableSimd:this.config.enableSimd};this.engine=P.withConfig(e),this.registry=new Q(this.config.maxPatterns??1e4)}async adaptPattern(t,e,r){let a=performance.now();try{let n=this.createStateEmbedding(t),o=this.engine.findPatterns(n,5),i=[];for(let m of o){let g=this.findByRawPattern(m);if(g||(g=this.createQEPatternFromRaw(m,e,r)),g.type===e&&g.domain===r&&g.confidence>=(this.config.minConfidence??.5)){let h=this.calculateSimilarity(n,m.centroid);i.push({pattern:g,similarity:h})}}if(i.length===0){let m=performance.now()-a;return this.recordAdaptation(m),{success:!1,pattern:null,adaptationTimeMs:m,similarity:0,reasoning:"No suitable pattern found"}}let s=i[0],u={...s.pattern,usageCount:s.pattern.usageCount+1,lastUsedAt:new Date};this.registry.update(u.id,u);let c=performance.now()-a;return this.recordAdaptation(c),{success:!0,pattern:u,adaptationTimeMs:c,similarity:s.similarity,reasoning:`Pattern adapted from @ruvector/sona with ${s.similarity.toFixed(3)} similarity`}}catch(n){let o=performance.now()-a;return this.recordAdaptation(o),{success:!1,pattern:null,adaptationTimeMs:o,similarity:0,reasoning:`Adaptation failed: ${n.message}`}}}recallPattern(t,e,r){let a=this.createStateEmbedding(t),n=this.engine.findPatterns(a,1);for(let o of n){let i=this.findByRawPattern(o);if(i&&i.type===e&&i.domain===r)return i}return null}storePattern(t){this.registry.register(t);let e=this.engine.beginTrajectory(t.stateEmbedding),r=this.createActionEmbedding(t.action),a=new Array(r.length).fill(1),n=t.outcome.success?t.outcome.quality:-t.outcome.quality;this.engine.addTrajectoryStep(e,r,a,n),this.engine.endTrajectory(e,t.outcome.quality),this.registry.associateTrajectory(e,t.id)}storePatternsBatch(t){for(let e of t)this.storePattern(e)}createPattern(t,e,r,a,n,o){let i={id:`qesona-${Date.now()}-${Ct().slice(0,7)}`,type:a,domain:n,stateEmbedding:this.createStateEmbedding(t),action:e,outcome:r,confidence:.5,usageCount:0,createdAt:new Date,metadata:o};return this.storePattern(i),i}updatePattern(t,e,r){let a=this.registry.get(t);if(!a)return!1;let n=e?r:-r,i=a.confidence+.1*(n-a.confidence),s={...a,confidence:Math.max(0,Math.min(1,i)),usageCount:a.usageCount+1,lastUsedAt:new Date};return this.registry.update(t,s)}applyMicroLora(t){return this.engine.applyMicroLora(t)}applyBaseLora(t,e){return this.engine.applyBaseLora(t,e)}forceLearn(){return this.engine.forceLearn()}tick(){return this.engine.tick()}getAllPatterns(){return this.registry.getAll()}getPatternsByType(t){return this.registry.getByType(t)}getPatternsByDomain(t){return this.registry.getByDomain(t)}getStats(){let t=this.registry.getAll(),e=this.engine.getStats(),r={"test-generation":0,"defect-prediction":0,"coverage-optimization":0,"quality-assessment":0,"resource-allocation":0};for(let a of t)r[a.type]++;return{totalPatterns:t.length,patternsByType:r,avgAdaptationTimeMs:this.avgAdaptationTime(),minAdaptationTimeMs:this.minAdaptationTime(),maxAdaptationTimeMs:this.maxAdaptationTime(),totalAdaptations:this.totalAdaptations,cacheHitRate:this.totalAdaptations>0?this.cacheHits/this.totalAdaptations:0,engineStats:e}}clear(){this.registry.clear(),this.adaptationTimes=[],this.cacheHits=0,this.totalAdaptations=0}exportPatterns(){return this.registry.getAll()}importPatterns(t){this.clear(),this.storePatternsBatch(t)}getConfig(){return{...this.config}}setEnabled(t){this.engine.setEnabled(t)}isEnabled(){return this.engine.isEnabled()}createStateEmbedding(t){let e=t.features;if(e.length===0)return new Array(this.config.embeddingDim??384).fill(0);let r=Math.max(...e.map(Math.abs));if(r===0)return[...e];let a=e.map(o=>o/r),n=this.config.embeddingDim??384;return a.length>=n?a.slice(0,n):[...a,...new Array(n-a.length).fill(0)]}createActionEmbedding(t){let e=[],r=this.hashCode(t.type);if(e.push(r%1e3/1e3),typeof t.value=="number")e.push(Math.min(1,Math.max(-1,t.value)));else if(typeof t.value=="string"){let n=this.hashCode(t.value);e.push(n%1e3/1e3)}else if(Array.isArray(t.value))for(let n of t.value.slice(0,10))typeof n=="number"&&e.push(Math.min(1,Math.max(-1,n)));let a=this.config.embeddingDim??384;for(;e.length<a;)e.push(0);return e.slice(0,a)}findByRawPattern(t){let e=this.registry.getAll();for(let r of e)if(r.rawPattern?.patternType===t.id)return r}createQEPatternFromRaw(t,e,r){let a={centroid:t.centroid,clusterSize:1,totalWeight:1,avgQuality:t.avgQuality,createdAt:new Date().toISOString(),lastAccessed:new Date().toISOString(),accessCount:0,patternType:t.patternType};return{id:`qesona-${t.id}`,type:e,domain:r,stateEmbedding:t.centroid,action:{type:"learned",value:t.patternType},outcome:{reward:t.avgQuality,success:t.avgQuality>.5,quality:t.avgQuality},confidence:t.avgQuality,usageCount:0,createdAt:new Date,rawPattern:a}}calculateSimilarity(t,e){let r=Math.min(t.length,e.length),a=0,n=0,o=0;for(let s=0;s<r;s++)a+=t[s]*e[s],n+=t[s]*t[s],o+=e[s]*e[s];return(a/(Math.sqrt(n)*Math.sqrt(o)+1e-10)+1)/2}hashCode(t){let e=0;for(let r=0;r<t.length;r++)e=(e<<5)-e+t.charCodeAt(r),e=e|0;return Math.abs(e)}recordAdaptation(t){this.adaptationTimes.push(t),this.totalAdaptations++,this.adaptationTimes.length>1e3&&this.adaptationTimes.shift()}avgAdaptationTime(){return this.adaptationTimes.length===0?0:this.adaptationTimes.reduce((e,r)=>e+r,0)/this.adaptationTimes.length}minAdaptationTime(){return this.adaptationTimes.length===0?0:Math.min(...this.adaptationTimes)}maxAdaptationTime(){return this.adaptationTimes.length===0?0:Math.max(...this.adaptationTimes)}initThreeLoopEngine(t){this.threeLoopEngine=new C({dimension:this.config.embeddingDim??384,microLoraLr:this.config.microLoraLr??.001,ewcLambda:this.config.ewcLambda??1e3,...t},this.engine)}getThreeLoopEngine(){return this.threeLoopEngine}instantAdapt(t){return this.threeLoopEngine?this.threeLoopEngine.instantAdapt(t):null}recordOutcome(t,e){this.threeLoopEngine&&this.threeLoopEngine.recordOutcome(t,e)}backgroundConsolidate(){if(!this.threeLoopEngine)return null;let t=this.threeLoopEngine.backgroundConsolidate();if(t&&(t.consolidated||t.taskBoundaryDetected)&&this.fisherPersistFn)try{this.threeLoopEngine.persistFisher(this.fisherPersistFn,this.fisherDomain)}catch(e){console.warn("[QESONA] Fisher persistence failed:",e instanceof Error?e.message:e)}return t}setFisherPersistence(t,e){this.fisherPersistFn=t,this.fisherDomain=e}syncWithPeers(t){this.threeLoopEngine&&this.threeLoopEngine.syncWithPeers(t)}getEWCMetrics(){return this.threeLoopEngine?this.threeLoopEngine.getEWCMetrics():null}shouldConsolidate(){return this.threeLoopEngine?this.threeLoopEngine.shouldConsolidate():!1}getLocalPeerState(t,e){return this.threeLoopEngine?this.threeLoopEngine.getLocalPeerState(t,e):null}isThreeLoopEnabled(){return this.threeLoopEngine!==null}async verifyPerformance(t=1e3){let e=[],r={id:"test-state",features:new Array(384).fill(0).map(()=>G())};for(let s=0;s<t;s++){let u=performance.now();await this.adaptPattern(r,"test-generation","test-generation");let c=performance.now();e.push({iteration:s,timeMs:c-u})}let a=e.map(s=>s.timeMs),n=a.reduce((s,u)=>s+u,0)/a.length,o=Math.min(...a),i=Math.max(...a);return{targetMet:n<.05,avgTimeMs:n,minTimeMs:o,maxTimeMs:i,details:e}}};function Tt(l){return new v(l)}function Pt(l,t){return new v({...t,maxPatterns:t?.maxPatterns||5e3})}ot();et();var F=null,D=null,W=null,B=null,z=null,I=null,q=!1;try{let l=(O(),w(N));F=l.FlashAttention,D=l.DotProductAttention,W=l.MultiHeadAttention,B=l.HyperbolicAttention,z=l.LinearAttention,I=l.MoEAttention,q=!0}catch{}function Gt(){return q}function A(){if(!q)throw new Error("@ruvector/attention native module is not available on this platform. Install the appropriate optional dependency for your platform, or use a platform where pre-built binaries are available.")}var T={"test-similarity":{dim:384,strategy:"flash",blockSize:64},"code-embedding":{dim:512,strategy:"flash",blockSize:128},"defect-matching":{dim:384,strategy:"flash",blockSize:64},"coverage-analysis":{dim:384,strategy:"flash",blockSize:256},"pattern-adaptation":{dim:256,strategy:"flash",blockSize:32}},Kt={"test-similarity":{enabled:!0,microLoRARank:4,targetAdaptationMs:.05,patternCacheSize:1e3},"code-embedding":{enabled:!0,microLoRARank:2,targetAdaptationMs:.03,patternCacheSize:5e3},"defect-matching":{enabled:!0,microLoRARank:8,targetAdaptationMs:.05,patternCacheSize:2e3},"coverage-analysis":{enabled:!1,microLoRARank:2,targetAdaptationMs:.01,patternCacheSize:100},"pattern-adaptation":{enabled:!0,microLoRARank:2,targetAdaptationMs:.05,patternCacheSize:1e4}},$t={"test-similarity":{latency:{before:50,after:15},memory:{before:200,after:80},throughput:{min:1e3}},"code-embedding":{latency:{before:50,after:15},memory:{before:200,after:80},throughput:{min:2e3}},"defect-matching":{latency:{before:20,after:5},memory:{before:150,after:50},throughput:{min:500}},"coverage-analysis":{latency:{before:100,after:1},memory:{before:100,after:30},throughput:{min:1e4}},"pattern-adaptation":{latency:{before:2,after:.05},memory:{before:50,after:20},throughput:{min:2e4}}};function Zt(l){return l<=128?{queryChunkSize:128,kvChunkSize:128}:l<=256?{queryChunkSize:256,kvChunkSize:256}:l<=512?{queryChunkSize:512,kvChunkSize:512}:l<=1024?{queryChunkSize:1024,kvChunkSize:1024}:{queryChunkSize:1024,kvChunkSize:2048}}var E=class{static create(t){switch(A(),t.strategy){case"flash":return new F(t.dim,t.blockSize);case"dot-product":return new D(t.dim);case"multi-head":return new W(t.dim,t.numHeads??8);case"hyperbolic":return new B(t.dim,t.curvature);case"linear":return new z(t.dim,t.features);case"moe":return I.simple(t.dim,t.moeConfig?.numExperts??8,t.moeConfig?.topK??2);default:return new F(t.dim,t.blockSize)}}},L=class l{attention;config;workload;metrics=[];db=null;persistCount=0;static KV_NAMESPACE="attention-metrics";static KV_TTL=3600;static PERSIST_INTERVAL=10;constructor(t,e){this.workload=t;let r=T[t];this.config={...r,...e},this.attention=E.create(this.config)}async initialize(){try{this.db=K(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(t){console.warn("[QEFlashAttention] DB init failed, using memory-only:",j(t)),this.db=null}}async computeFlashAttention(t,e,r,a,n){let o=performance.now(),i=process.memoryUsage().heapUsed/1024/1024,s=this.toFloat32Array(t,a,n),u=this.splitMatrix(e,a,n),c=this.splitMatrix(r,a,n),m,g=this.attention;typeof g.compute=="function"?m=g.compute(s,u,c):(A(),m=new F(this.config.dim).compute(s,u,c));let h=performance.now(),d=process.memoryUsage().heapUsed/1024/1024;return this.metrics.push({timeMs:h-o,memoryMB:d-i,speedup:1,throughput:a*a/((h-o)/1e3),peakMemoryMB:d}),this.maybePersistToKv(),m}async computeBaselineAttention(t,e,r,a,n){let o=performance.now(),i=process.memoryUsage().heapUsed/1024/1024,s=new Float32Array(a*a),u=1/Math.sqrt(n);for(let h=0;h<a;h++)for(let d=0;d<a;d++){let b=0;for(let p=0;p<n;p++)b+=t[h*n+p]*e[d*n+p];s[h*a+d]=b*u}for(let h=0;h<a;h++){let d=h*a,b=d+a,p=s.subarray(d,b),tt=Math.max(...p),_=0;for(let y=0;y<a;y++)p[y]=Math.exp(p[y]-tt),_+=p[y];for(let y=0;y<a;y++)p[y]/=_}let c=new Float32Array(a*n);for(let h=0;h<a;h++)for(let d=0;d<a;d++){let b=s[h*a+d];for(let p=0;p<n;p++)c[h*n+p]+=b*r[d*n+p]}let m=performance.now(),g=process.memoryUsage().heapUsed/1024/1024;return c}async computeTestSimilarity(t,e,r=5){let a=e.length,n=t.length,o=new Float32Array(a*n),i=new Float32Array(a*n);for(let m=0;m<a;m++)o.set(t,m*n),i.set(e[m],m*n);let s=new Float32Array(a*n),u=await this.computeFlashAttention(o,i,s,a,n),c=[];for(let m=0;m<a;m++)c.push({index:m,similarity:u[m*n]});return c.sort((m,g)=>g.similarity-m.similarity),c.slice(0,r)}async generateCodeEmbedding(t,e){let r=t.length/e.length,a=e.length;return await this.computeFlashAttention(t,e,t,r,a)}async matchDefectPattern(t,e){let r=e.length,a=t.length,n=new Float32Array(r*a),o=new Float32Array(r*a);for(let c=0;c<r;c++)n.set(t,c*a),o.set(e[c],c*a);let i=new Float32Array(r*a),s=await this.computeFlashAttention(n,o,i,r,a),u=[];for(let c=0;c<r;c++)u.push({pattern:c,score:s[c*a]});return u.sort((c,m)=>m.score-c.score),u}getMetrics(){return[...this.metrics]}getAverageSpeedup(){return this.metrics.length===0?1:this.metrics.reduce((t,e)=>t+e.speedup,0)/this.metrics.length}getConfig(){return{...this.config}}updateConfig(t){this.config={...this.config,...t},this.attention=E.create(this.config)}changeStrategy(t){this.config.strategy=t,this.attention=E.create(this.config)}resetMetrics(){this.metrics=[]}getWorkload(){return this.workload}dispose(){this.metrics=[]}async persistToKv(){if(!this.db)return;let t=`attention-metrics-${this.workload}`,e={workload:this.workload,metrics:this.metrics.slice(-50),savedAt:Date.now()};await this.db.kvSet(t,e,l.KV_NAMESPACE,l.KV_TTL)}async loadFromKv(){if(!this.db)return;let t=`attention-metrics-${this.workload}`,e=await this.db.kvGet(t,l.KV_NAMESPACE);e?.metrics?.length&&(this.metrics=e.metrics)}maybePersistToKv(){this.persistCount++,this.persistCount>=l.PERSIST_INTERVAL&&(this.persistCount=0,this.persistToKv().catch(()=>{}))}toFloat32Array(t,e,r){return t.slice(0,r)}splitMatrix(t,e,r){let a=[];for(let n=0;n<e;n++)a.push(t.slice(n*r,(n+1)*r));return a}};async function Y(l,t){let e=new L(l,t);return await e.initialize(),e}function Jt(l){return{...T[l]}}function Xt(){return Object.keys(T)}function Yt(){return A(),F}function te(){return A(),D}function ee(){return A(),W}function re(){return A(),B}function ae(){return A(),z}function ne(){return A(),I}function ie(l){return l instanceof Float32Array?l:new Float32Array(l)}function oe(l){return Array.from(l)}async function se(l,t,e,r){let a=await Y(l),n=[],o=t[0].length,i=e.length;for(let s of t){let u=new Float32Array(i*o),c=new Float32Array(i*o),m=new Float32Array(i*o);u.set(s,0);for(let h=0;h<i;h++)c.set(e[h],h*o),m.set(r[h],h*o);let g=await a.computeFlashAttention(u,c,m,i,o);n.push(g.slice(0,o))}return a.dispose(),n}function We(){return{"@ruvector/sona":"^0.1.5","@ruvector/attention":"^0.1.4","@ruvector/gnn":"^0.1.22"}}function Be(){let l={sona:!1,attention:!1,gnn:!1,all:!1};try{k(),l.sona=!0}catch{}try{O(),l.attention=!0}catch{}try{let t=(it(),w(nt));t.init();let e=new Float32Array([.1,.2,.3]),r=[new Float32Array([.1,.2,.3]),new Float32Array([.4,.5,.6])],a=t.differentiableSearch(e,r,1,1);a&&Array.isArray(a.indices)&&Array.isArray(a.weights)&&(l.gnn=!0)}catch{}return l.all=l.sona&&l.attention&&l.gnn,l}async function ze(){let{initGNN:l}=await import("./gnn-wrapper-HPCQREKP.js");return[l(),"SONA: Ready (no initialization required)","Attention: Ready (no initialization required)"]}export{v as a,Tt as b,Pt as c,Gt as d,T as e,Kt as f,$t as g,Zt as h,L as i,Y as j,Jt as k,Xt as l,Yt as m,te as n,ee as o,re as p,ae as q,ne as r,ie as s,oe as t,se as u,We as v,Be as w,ze as x};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.2");process.exit(0)}
2
+ import{k as K,o as ot}from"./chunk-GK72GUHA.js";import{a as rt}from"./chunk-XIBVVZGB.js";import{c as U}from"./chunk-JOVINE23.js";import{a as j,c as et}from"./chunk-SDTVHR63.js";import{a as G,d as at}from"./chunk-34U7JDCN.js";import{a as nt,b as it}from"./chunk-727BDQ3K.js";import{c as H,e as V,g as w}from"./chunk-YXCU4CJX.js";var Z={};V(Z,{DotProductAttention:()=>yt,FlashAttention:()=>ft,HyperbolicAttention:()=>bt,LinearAttention:()=>vt,MoEAttention:()=>Et,MultiHeadAttention:()=>At,RuvectorLayer:()=>ut,SonaEngine:()=>P,TensorCompress:()=>mt,default:()=>ct,differentiableSearch:()=>ht,getCompressionLevel:()=>pt,hierarchicalForward:()=>dt,init:()=>gt,pipeline:()=>Ft});import{createRequire as st}from"module";var lt,$,ct,ut,mt,ht,dt,pt,gt,ft,yt,At,bt,vt,Et,P,Ft,k=H(()=>{lt=st(import.meta.url),$=lt("@ruvector/sona"),ct=$,{RuvectorLayer:ut,TensorCompress:mt,differentiableSearch:ht,hierarchicalForward:dt,getCompressionLevel:pt,init:gt,FlashAttention:ft,DotProductAttention:yt,MultiHeadAttention:At,HyperbolicAttention:bt,LinearAttention:vt,MoEAttention:Et,SonaEngine:P,pipeline:Ft}=$||{}});var N={};V(N,{DotProductAttention:()=>It,FlashAttention:()=>zt,HyperbolicAttention:()=>_t,LinearAttention:()=>Ht,MoEAttention:()=>Vt,MultiHeadAttention:()=>qt,RuvectorLayer:()=>Qt,SonaEngine:()=>jt,TensorCompress:()=>Nt,default:()=>xt,differentiableSearch:()=>Ot,getCompressionLevel:()=>Wt,hierarchicalForward:()=>Dt,init:()=>Bt,pipeline:()=>Ut});import{createRequire as kt}from"module";var Rt,X,xt,Qt,Nt,Ot,Dt,Wt,Bt,zt,It,qt,_t,Ht,Vt,jt,Ut,O=H(()=>{Rt=kt(import.meta.url),X=Rt("@ruvector/attention"),xt=X,{RuvectorLayer:Qt,TensorCompress:Nt,differentiableSearch:Ot,hierarchicalForward:Dt,getCompressionLevel:Wt,init:Bt,FlashAttention:zt,DotProductAttention:It,MultiHeadAttention:qt,HyperbolicAttention:_t,LinearAttention:Ht,MoEAttention:Vt,SonaEngine:jt,pipeline:Ut}=X||{}});k();at();import{randomUUID as Ct}from"crypto";rt();import{createRequire as wt}from"module";var f=U.create("sona-three-loop"),S=wt(import.meta.url),M=null,J=!1;function St(){if(J)return M;J=!0;try{let l=S("@ruvector/learning-wasm"),t=S("fs"),e=S("path"),r=e.join(e.dirname(S.resolve("@ruvector/learning-wasm")),"ruvector_learning_wasm_bg.wasm");l.initSync({module:t.readFileSync(r)}),M=l,f.info("WASM MicroLoRA loaded from @ruvector/learning-wasm (6.4x faster than TS)")}catch{M=null,f.debug("@ruvector/learning-wasm not available, using TypeScript MicroLoRA")}return M}var Mt={dimension:384,microLoraLr:.001,consolidationInterval:100,ewcLambda:1e3,taskBoundaryZScoreThreshold:2.5,fisherDecay:.9,fisherSampleSize:200,importanceThreshold:.01},R=class{adaptationVector;baseWeights;lr;adaptationCount=0;constructor(t,e=.001){this.adaptationVector=new Float32Array(t),this.baseWeights=new Float32Array(t),this.lr=e}adapt(t){let e=this.baseWeights.length,r=new Float32Array(e),a=Math.min(t.length,e);for(let n=0;n<e;n++){let o=n<a?t[n]:0;r[n]=this.baseWeights[n]+this.adaptationVector[n]+this.lr*o}for(let n=0;n<a;n++)this.adaptationVector[n]+=this.lr*t[n];return this.adaptationCount++,r}consolidate(){let t=this.adaptationCount,e=this.baseWeights.length;for(let r=0;r<e;r++)this.baseWeights[r]+=this.adaptationVector[r],this.adaptationVector[r]=0;return this.adaptationCount=0,t}getAdaptationCount(){return this.adaptationCount}getEffectiveWeights(){let t=this.baseWeights.length,e=new Float32Array(t);for(let r=0;r<t;r++)e[r]=this.baseWeights[r]+this.adaptationVector[r];return e}getAdaptationMagnitude(){let t=0;for(let e=0;e<this.adaptationVector.length;e++)t+=this.adaptationVector[e]*this.adaptationVector[e];return Math.sqrt(t)}resetAdaptation(){this.adaptationVector.fill(0),this.adaptationCount=0}},x=class{fisherMatrix;optimalParams;lambda;fisherDecay;zScoreThreshold;importanceThreshold;gradientHistory=[];gradientMean=0;gradientVariance=0;taskBoundaryCount=0;consolidationCount=0;constructor(t,e=1e3,r=.9,a=2.5,n=.01){this.fisherMatrix=new Float32Array(t),this.optimalParams=new Float32Array(t),this.lambda=e,this.fisherDecay=r,this.zScoreThreshold=a,this.importanceThreshold=n}detectTaskBoundary(t){let e=0;for(let i=0;i<t.length;i++)e+=t[i]*t[i];if(e=Math.sqrt(e),this.gradientHistory.length<5)return this.gradientHistory.push(e),this.updateGradientStats(),!1;let r=Math.sqrt(this.gradientVariance),a=0,n=Math.abs(e-this.gradientMean);return r>1e-10?a=n/r:n>1e-10&&this.gradientMean>1e-10&&(a=n/(this.gradientMean*.01+1e-10)),this.gradientHistory.push(e),this.gradientHistory.length>100&&this.gradientHistory.shift(),this.updateGradientStats(),a>this.zScoreThreshold?(this.taskBoundaryCount++,!0):!1}computeLoss(t){let e=0,r=Math.min(t.length,this.fisherMatrix.length,this.optimalParams.length);for(let a=0;a<r;a++){let n=t[a]-this.optimalParams[a];e+=this.fisherMatrix[a]*n*n}return this.lambda/2*e}updateFisher(t,e){if(t.length===0)return;let r=this.fisherMatrix.length,a=new Float32Array(r);for(let s of t){let u=Math.min(s.length,r);for(let c=0;c<u;c++)a[c]+=s[c]*s[c]}let n=t.length;for(let s=0;s<r;s++)a[s]/=n;let o=this.fisherDecay;for(let s=0;s<r;s++)this.fisherMatrix[s]=o*this.fisherMatrix[s]+(1-o)*a[s];let i=Math.min(e.length,r);for(let s=0;s<i;s++)this.optimalParams[s]=e[s];this.consolidationCount++}getMetrics(){let t=this.fisherMatrix.length,e=0,r=0,a=0;for(let n=0;n<t;n++)e+=this.fisherMatrix[n],this.fisherMatrix[n]>r&&(r=this.fisherMatrix[n]),this.fisherMatrix[n]>this.importanceThreshold&&a++;return{regularizationLoss:0,taskBoundariesDetected:this.taskBoundaryCount,fisherTrace:e,avgFisherImportance:t>0?e/t:0,maxFisherImportance:r,protectedParams:a,consolidationCycles:this.consolidationCount,lambda:this.lambda}}getTaskBoundaryCount(){return this.taskBoundaryCount}getFisherDiagonal(){return new Float32Array(this.fisherMatrix)}getOptimalParams(){return new Float32Array(this.optimalParams)}loadFisher(t,e){let r=this.fisherMatrix.length,a=Math.min(t.length,r),n=Math.min(e.length,r);for(let o=0;o<a;o++)this.fisherMatrix[o]=t[o];for(let o=0;o<n;o++)this.optimalParams[o]=e[o]}updateGradientStats(){let t=this.gradientHistory.length;if(t===0)return;let e=0;for(let a of this.gradientHistory)e+=a;e/=t;let r=0;for(let a of this.gradientHistory){let n=a-e;r+=n*n}r=t>1?r/(t-1):0,this.gradientMean=e,this.gradientVariance=r}},C=class{config;microLora;ewc;nativeEngine;wasmLora=null;requestCount=0;lastConsolidationRequest=0;peerStates=new Map;gradientBuffer=[];lastFeatures=null;constructor(t={},e){this.config={...Mt,...t},this.nativeEngine=e??null,this.microLora=new R(this.config.dimension,this.config.microLoraLr),this.ewc=new x(this.config.dimension,this.config.ewcLambda,this.config.fisherDecay,this.config.taskBoundaryZScoreThreshold,this.config.importanceThreshold);let r=St();if(r)try{this.wasmLora=new r.WasmMicroLoRA(this.config.dimension,1,this.config.microLoraLr),f.info("SONA Three-Loop using WASM MicroLoRA (0.07us/adapt)")}catch(a){f.debug("WASM MicroLoRA creation failed, falling back",{error:String(a)}),this.wasmLora=null}!this.wasmLora&&this.nativeEngine&&f.info("SONA Three-Loop using native @ruvector/sona engine for MicroLoRA delegation")}instantAdapt(t){let e=performance.now(),r;if(this.wasmLora)try{let o=new Float32Array(t),i=this.wasmLora.adapt(o);i&&i.length>0?(r=i,this.microLora.adapt(t)):r=this.microLora.adapt(t)}catch{r=this.microLora.adapt(t)}else if(this.nativeEngine)try{let o=this.nativeEngine.applyMicroLora(t);r=new Float32Array(o),this.microLora.adapt(t)}catch{r=this.microLora.adapt(t)}else r=this.microLora.adapt(t);let a=this.microLora.getAdaptationMagnitude();this.requestCount++,this.lastFeatures=[...t];let n=(performance.now()-e)*1e3;return{adaptedWeights:r,latencyUs:n,applied:!0,magnitude:a,requestIndex:this.requestCount}}recordOutcome(t,e){if(this.lastFeatures===null){f.warn("recordOutcome called without a preceding instantAdapt()");return}let r=this.lastFeatures.length,a=new Float32Array(r);for(let n=0;n<r;n++)a[n]=t*this.lastFeatures[n];this.gradientBuffer.push(a),this.gradientBuffer.length>this.config.fisherSampleSize&&this.gradientBuffer.shift(),this.lastFeatures=null}backgroundConsolidate(){let t=performance.now();if(this.nativeEngine)try{this.nativeEngine.forceLearn(),this.nativeEngine.tick()}catch(i){f.warn("Native SONA background learning failed, continuing with TypeScript",{error:String(i)})}let e=this.ewc.computeLoss(this.microLora.getEffectiveWeights()),r=!1;if(this.gradientBuffer.length>0){let i=this.gradientBuffer[this.gradientBuffer.length-1];r=this.ewc.detectTaskBoundary(i)}if(r&&this.gradientBuffer.length>0&&(this.ewc.updateFisher(this.gradientBuffer,this.microLora.getEffectiveWeights()),f.info("Task boundary detected, Fisher updated",{boundaries:this.ewc.getTaskBoundaryCount(),requestCount:this.requestCount})),this.gradientBuffer.length>1){let i=!1,s=this.gradientBuffer[0];for(let u=1;u<this.gradientBuffer.length&&!i;u++)for(let c=0;c<s.length;c++)if(Math.abs(this.gradientBuffer[u][c]-s[c])>1e-8){i=!0;break}i||f.warn("All gradient samples identical \u2014 Fisher estimate may be poor. Ensure recordOutcome() is called with diverse rewards.")}let a=this.microLora.consolidate();this.applyEWCRegularization();let n=this.ewc.computeLoss(this.microLora.getEffectiveWeights());this.lastConsolidationRequest=this.requestCount,this.gradientBuffer=[];let o=performance.now()-t;return{consolidated:a>0||r,adaptationsMerged:a,ewcLossBefore:e,ewcLossAfter:n,taskBoundaryDetected:r,durationMs:o}}shouldConsolidate(){return this.requestCount-this.lastConsolidationRequest>=this.config.consolidationInterval}syncWithPeers(t){if(t.length===0)return;for(let i of t)this.peerStates.set(i.peerId,i);let e=this.config.dimension,r=new Float32Array(e),a=new Float32Array(e),n=this.ewc.getFisherDiagonal(),o=this.microLora.adaptationVector;for(let i=0;i<e;i++){let s=n[i]+1e-10;r[i]+=s*o[i],a[i]+=s}for(let i of t){let s=Math.min(i.adaptationVector.length,e);for(let u=0;u<s;u++){let c=(u<i.fisherDiagonal.length?i.fisherDiagonal[u]:0)+1e-10;r[u]+=c*i.adaptationVector[u],a[u]+=c}}for(let i=0;i<e;i++)this.microLora.adaptationVector[i]=r[i]/a[i];f.debug("Synced with peers",{peerCount:t.length,peersStored:this.peerStates.size})}getLocalPeerState(t,e){return{peerId:t,domain:e,adaptationVector:new Float32Array(this.microLora.adaptationVector),fisherDiagonal:this.ewc.getFisherDiagonal(),requestCount:this.requestCount,lastUpdateMs:Date.now()}}getEWCMetrics(){let t=this.ewc.getMetrics();return t.regularizationLoss=this.ewc.computeLoss(this.microLora.getEffectiveWeights()),t}getFisherDiagonal(){return this.ewc.getFisherDiagonal()}getOptimalParams(){return this.ewc.getOptimalParams()}loadFisher(t,e){this.ewc.loadFisher(t,e)}getBaseWeights(){return new Float32Array(this.microLora.baseWeights)}setBaseWeights(t){let e=Math.min(t.length,this.microLora.baseWeights.length);for(let r=0;r<e;r++)this.microLora.baseWeights[r]=t[r]}getEffectiveWeights(){return this.microLora.getEffectiveWeights()}getRequestCount(){return this.requestCount}getConfig(){return{...this.config}}getPeerStates(){return new Map(this.peerStates)}getMicroLoRA(){return this.microLora}getEWC(){return this.ewc}applyEWCRegularization(){let t=this.config.dimension,e=this.ewc.fisherMatrix,r=this.ewc.optimalParams,a=this.microLora.baseWeights,n=.01;for(let o=0;o<t;o++)if(e[o]>this.config.importanceThreshold){let i=a[o]-r[o];a[o]-=n*e[o]*i}}persistFisher(t,e){let r=this.ewc.getMetrics();t(e,this.ewc.getFisherDiagonal(),this.ewc.getOptimalParams(),this.getBaseWeights(),{taskBoundaries:r.taskBoundariesDetected,consolidationCycles:r.consolidationCycles,requestCount:this.requestCount,ewcLambda:r.lambda}),f.info("Fisher matrix persisted to SQLite",{domain:e,requestCount:this.requestCount,taskBoundaries:r.taskBoundariesDetected})}restoreFisher(t){this.ewc.loadFisher(t.fisherDiagonal,t.optimalParams),t.baseWeights&&this.setBaseWeights(t.baseWeights),this.requestCount=t.requestCount,f.info("Fisher matrix restored from SQLite",{requestCount:t.requestCount,dimension:t.fisherDiagonal.length})}};var Lt={hiddenDim:256,embeddingDim:384,microLoraRank:1,baseLoraRank:8,microLoraLr:.001,baseLoraLr:1e-4,ewcLambda:1e3,patternClusters:50,trajectoryCapacity:1e4,backgroundIntervalMs:36e5,qualityThreshold:.5,enableSimd:!0,minConfidence:.5,maxPatterns:1e4},Q=class{patterns;trajectoryMap;maxPatterns;constructor(t=1e4){this.patterns=new Map,this.trajectoryMap=new Map,this.maxPatterns=t}register(t){if(this.patterns.size>=this.maxPatterns&&!this.patterns.has(t.id)){let e=Array.from(this.patterns.entries()).sort(([,r],[,a])=>(r.lastUsedAt?.getTime()??r.createdAt.getTime())-(a.lastUsedAt?.getTime()??a.createdAt.getTime()))[0];e&&this.patterns.delete(e[0])}this.patterns.set(t.id,t)}get(t){return this.patterns.get(t)}getByTrajectory(t){let e=this.trajectoryMap.get(t);return e?this.patterns.get(e):void 0}associateTrajectory(t,e){this.trajectoryMap.set(t,e)}update(t,e){let r=this.patterns.get(t);return r?(this.patterns.set(t,{...r,...e}),!0):!1}getAll(){return Array.from(this.patterns.values())}getByType(t){return Array.from(this.patterns.values()).filter(e=>e.type===t)}getByDomain(t){return Array.from(this.patterns.values()).filter(e=>e.domain===t)}clear(){this.patterns.clear(),this.trajectoryMap.clear()}size(){return this.patterns.size}},v=class{engine;registry;config;adaptationTimes=[];cacheHits=0;totalAdaptations=0;threeLoopEngine=null;fisherPersistFn=null;fisherDomain="default";constructor(t={}){this.config={...Lt,...t};let e={hiddenDim:this.config.hiddenDim,embeddingDim:this.config.embeddingDim,microLoraRank:this.config.microLoraRank,baseLoraRank:this.config.baseLoraRank,microLoraLr:this.config.microLoraLr,baseLoraLr:this.config.baseLoraLr,ewcLambda:this.config.ewcLambda,patternClusters:this.config.patternClusters,trajectoryCapacity:this.config.trajectoryCapacity,backgroundIntervalMs:this.config.backgroundIntervalMs,qualityThreshold:this.config.qualityThreshold,enableSimd:this.config.enableSimd};this.engine=P.withConfig(e),this.registry=new Q(this.config.maxPatterns??1e4)}async adaptPattern(t,e,r){let a=performance.now();try{let n=this.createStateEmbedding(t),o=this.engine.findPatterns(n,5),i=[];for(let m of o){let g=this.findByRawPattern(m);if(g||(g=this.createQEPatternFromRaw(m,e,r)),g.type===e&&g.domain===r&&g.confidence>=(this.config.minConfidence??.5)){let h=this.calculateSimilarity(n,m.centroid);i.push({pattern:g,similarity:h})}}if(i.length===0){let m=performance.now()-a;return this.recordAdaptation(m),{success:!1,pattern:null,adaptationTimeMs:m,similarity:0,reasoning:"No suitable pattern found"}}let s=i[0],u={...s.pattern,usageCount:s.pattern.usageCount+1,lastUsedAt:new Date};this.registry.update(u.id,u);let c=performance.now()-a;return this.recordAdaptation(c),{success:!0,pattern:u,adaptationTimeMs:c,similarity:s.similarity,reasoning:`Pattern adapted from @ruvector/sona with ${s.similarity.toFixed(3)} similarity`}}catch(n){let o=performance.now()-a;return this.recordAdaptation(o),{success:!1,pattern:null,adaptationTimeMs:o,similarity:0,reasoning:`Adaptation failed: ${n.message}`}}}recallPattern(t,e,r){let a=this.createStateEmbedding(t),n=this.engine.findPatterns(a,1);for(let o of n){let i=this.findByRawPattern(o);if(i&&i.type===e&&i.domain===r)return i}return null}storePattern(t){this.registry.register(t);let e=this.engine.beginTrajectory(t.stateEmbedding),r=this.createActionEmbedding(t.action),a=new Array(r.length).fill(1),n=t.outcome.success?t.outcome.quality:-t.outcome.quality;this.engine.addTrajectoryStep(e,r,a,n),this.engine.endTrajectory(e,t.outcome.quality),this.registry.associateTrajectory(e,t.id)}storePatternsBatch(t){for(let e of t)this.storePattern(e)}createPattern(t,e,r,a,n,o){let i={id:`qesona-${Date.now()}-${Ct().slice(0,7)}`,type:a,domain:n,stateEmbedding:this.createStateEmbedding(t),action:e,outcome:r,confidence:.5,usageCount:0,createdAt:new Date,metadata:o};return this.storePattern(i),i}updatePattern(t,e,r){let a=this.registry.get(t);if(!a)return!1;let n=e?r:-r,i=a.confidence+.1*(n-a.confidence),s={...a,confidence:Math.max(0,Math.min(1,i)),usageCount:a.usageCount+1,lastUsedAt:new Date};return this.registry.update(t,s)}applyMicroLora(t){return this.engine.applyMicroLora(t)}applyBaseLora(t,e){return this.engine.applyBaseLora(t,e)}forceLearn(){return this.engine.forceLearn()}tick(){return this.engine.tick()}getAllPatterns(){return this.registry.getAll()}getPatternsByType(t){return this.registry.getByType(t)}getPatternsByDomain(t){return this.registry.getByDomain(t)}getStats(){let t=this.registry.getAll(),e=this.engine.getStats(),r={"test-generation":0,"defect-prediction":0,"coverage-optimization":0,"quality-assessment":0,"resource-allocation":0};for(let a of t)r[a.type]++;return{totalPatterns:t.length,patternsByType:r,avgAdaptationTimeMs:this.avgAdaptationTime(),minAdaptationTimeMs:this.minAdaptationTime(),maxAdaptationTimeMs:this.maxAdaptationTime(),totalAdaptations:this.totalAdaptations,cacheHitRate:this.totalAdaptations>0?this.cacheHits/this.totalAdaptations:0,engineStats:e}}clear(){this.registry.clear(),this.adaptationTimes=[],this.cacheHits=0,this.totalAdaptations=0}exportPatterns(){return this.registry.getAll()}importPatterns(t){this.clear(),this.storePatternsBatch(t)}getConfig(){return{...this.config}}setEnabled(t){this.engine.setEnabled(t)}isEnabled(){return this.engine.isEnabled()}createStateEmbedding(t){let e=t.features;if(e.length===0)return new Array(this.config.embeddingDim??384).fill(0);let r=Math.max(...e.map(Math.abs));if(r===0)return[...e];let a=e.map(o=>o/r),n=this.config.embeddingDim??384;return a.length>=n?a.slice(0,n):[...a,...new Array(n-a.length).fill(0)]}createActionEmbedding(t){let e=[],r=this.hashCode(t.type);if(e.push(r%1e3/1e3),typeof t.value=="number")e.push(Math.min(1,Math.max(-1,t.value)));else if(typeof t.value=="string"){let n=this.hashCode(t.value);e.push(n%1e3/1e3)}else if(Array.isArray(t.value))for(let n of t.value.slice(0,10))typeof n=="number"&&e.push(Math.min(1,Math.max(-1,n)));let a=this.config.embeddingDim??384;for(;e.length<a;)e.push(0);return e.slice(0,a)}findByRawPattern(t){let e=this.registry.getAll();for(let r of e)if(r.rawPattern?.patternType===t.id)return r}createQEPatternFromRaw(t,e,r){let a={centroid:t.centroid,clusterSize:1,totalWeight:1,avgQuality:t.avgQuality,createdAt:new Date().toISOString(),lastAccessed:new Date().toISOString(),accessCount:0,patternType:t.patternType};return{id:`qesona-${t.id}`,type:e,domain:r,stateEmbedding:t.centroid,action:{type:"learned",value:t.patternType},outcome:{reward:t.avgQuality,success:t.avgQuality>.5,quality:t.avgQuality},confidence:t.avgQuality,usageCount:0,createdAt:new Date,rawPattern:a}}calculateSimilarity(t,e){let r=Math.min(t.length,e.length),a=0,n=0,o=0;for(let s=0;s<r;s++)a+=t[s]*e[s],n+=t[s]*t[s],o+=e[s]*e[s];return(a/(Math.sqrt(n)*Math.sqrt(o)+1e-10)+1)/2}hashCode(t){let e=0;for(let r=0;r<t.length;r++)e=(e<<5)-e+t.charCodeAt(r),e=e|0;return Math.abs(e)}recordAdaptation(t){this.adaptationTimes.push(t),this.totalAdaptations++,this.adaptationTimes.length>1e3&&this.adaptationTimes.shift()}avgAdaptationTime(){return this.adaptationTimes.length===0?0:this.adaptationTimes.reduce((e,r)=>e+r,0)/this.adaptationTimes.length}minAdaptationTime(){return this.adaptationTimes.length===0?0:Math.min(...this.adaptationTimes)}maxAdaptationTime(){return this.adaptationTimes.length===0?0:Math.max(...this.adaptationTimes)}initThreeLoopEngine(t){this.threeLoopEngine=new C({dimension:this.config.embeddingDim??384,microLoraLr:this.config.microLoraLr??.001,ewcLambda:this.config.ewcLambda??1e3,...t},this.engine)}getThreeLoopEngine(){return this.threeLoopEngine}instantAdapt(t){return this.threeLoopEngine?this.threeLoopEngine.instantAdapt(t):null}recordOutcome(t,e){this.threeLoopEngine&&this.threeLoopEngine.recordOutcome(t,e)}backgroundConsolidate(){if(!this.threeLoopEngine)return null;let t=this.threeLoopEngine.backgroundConsolidate();if(t&&(t.consolidated||t.taskBoundaryDetected)&&this.fisherPersistFn)try{this.threeLoopEngine.persistFisher(this.fisherPersistFn,this.fisherDomain)}catch(e){console.warn("[QESONA] Fisher persistence failed:",e instanceof Error?e.message:e)}return t}setFisherPersistence(t,e){this.fisherPersistFn=t,this.fisherDomain=e}syncWithPeers(t){this.threeLoopEngine&&this.threeLoopEngine.syncWithPeers(t)}getEWCMetrics(){return this.threeLoopEngine?this.threeLoopEngine.getEWCMetrics():null}shouldConsolidate(){return this.threeLoopEngine?this.threeLoopEngine.shouldConsolidate():!1}getLocalPeerState(t,e){return this.threeLoopEngine?this.threeLoopEngine.getLocalPeerState(t,e):null}isThreeLoopEnabled(){return this.threeLoopEngine!==null}async verifyPerformance(t=1e3){let e=[],r={id:"test-state",features:new Array(384).fill(0).map(()=>G())};for(let s=0;s<t;s++){let u=performance.now();await this.adaptPattern(r,"test-generation","test-generation");let c=performance.now();e.push({iteration:s,timeMs:c-u})}let a=e.map(s=>s.timeMs),n=a.reduce((s,u)=>s+u,0)/a.length,o=Math.min(...a),i=Math.max(...a);return{targetMet:n<.05,avgTimeMs:n,minTimeMs:o,maxTimeMs:i,details:e}}};function Tt(l){return new v(l)}function Pt(l,t){return new v({...t,maxPatterns:t?.maxPatterns||5e3})}ot();et();var F=null,D=null,W=null,B=null,z=null,I=null,q=!1;try{let l=(O(),w(N));F=l.FlashAttention,D=l.DotProductAttention,W=l.MultiHeadAttention,B=l.HyperbolicAttention,z=l.LinearAttention,I=l.MoEAttention,q=!0}catch{}function Gt(){return q}function A(){if(!q)throw new Error("@ruvector/attention native module is not available on this platform. Install the appropriate optional dependency for your platform, or use a platform where pre-built binaries are available.")}var T={"test-similarity":{dim:384,strategy:"flash",blockSize:64},"code-embedding":{dim:512,strategy:"flash",blockSize:128},"defect-matching":{dim:384,strategy:"flash",blockSize:64},"coverage-analysis":{dim:384,strategy:"flash",blockSize:256},"pattern-adaptation":{dim:256,strategy:"flash",blockSize:32}},Kt={"test-similarity":{enabled:!0,microLoRARank:4,targetAdaptationMs:.05,patternCacheSize:1e3},"code-embedding":{enabled:!0,microLoRARank:2,targetAdaptationMs:.03,patternCacheSize:5e3},"defect-matching":{enabled:!0,microLoRARank:8,targetAdaptationMs:.05,patternCacheSize:2e3},"coverage-analysis":{enabled:!1,microLoRARank:2,targetAdaptationMs:.01,patternCacheSize:100},"pattern-adaptation":{enabled:!0,microLoRARank:2,targetAdaptationMs:.05,patternCacheSize:1e4}},$t={"test-similarity":{latency:{before:50,after:15},memory:{before:200,after:80},throughput:{min:1e3}},"code-embedding":{latency:{before:50,after:15},memory:{before:200,after:80},throughput:{min:2e3}},"defect-matching":{latency:{before:20,after:5},memory:{before:150,after:50},throughput:{min:500}},"coverage-analysis":{latency:{before:100,after:1},memory:{before:100,after:30},throughput:{min:1e4}},"pattern-adaptation":{latency:{before:2,after:.05},memory:{before:50,after:20},throughput:{min:2e4}}};function Zt(l){return l<=128?{queryChunkSize:128,kvChunkSize:128}:l<=256?{queryChunkSize:256,kvChunkSize:256}:l<=512?{queryChunkSize:512,kvChunkSize:512}:l<=1024?{queryChunkSize:1024,kvChunkSize:1024}:{queryChunkSize:1024,kvChunkSize:2048}}var E=class{static create(t){switch(A(),t.strategy){case"flash":return new F(t.dim,t.blockSize);case"dot-product":return new D(t.dim);case"multi-head":return new W(t.dim,t.numHeads??8);case"hyperbolic":return new B(t.dim,t.curvature);case"linear":return new z(t.dim,t.features);case"moe":return I.simple(t.dim,t.moeConfig?.numExperts??8,t.moeConfig?.topK??2);default:return new F(t.dim,t.blockSize)}}},L=class l{attention;config;workload;metrics=[];db=null;persistCount=0;static KV_NAMESPACE="attention-metrics";static KV_TTL=3600;static PERSIST_INTERVAL=10;constructor(t,e){this.workload=t;let r=T[t];this.config={...r,...e},this.attention=E.create(this.config)}async initialize(){try{this.db=K(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(t){console.warn("[QEFlashAttention] DB init failed, using memory-only:",j(t)),this.db=null}}async computeFlashAttention(t,e,r,a,n){let o=performance.now(),i=process.memoryUsage().heapUsed/1024/1024,s=this.toFloat32Array(t,a,n),u=this.splitMatrix(e,a,n),c=this.splitMatrix(r,a,n),m,g=this.attention;typeof g.compute=="function"?m=g.compute(s,u,c):(A(),m=new F(this.config.dim).compute(s,u,c));let h=performance.now(),d=process.memoryUsage().heapUsed/1024/1024;return this.metrics.push({timeMs:h-o,memoryMB:d-i,speedup:1,throughput:a*a/((h-o)/1e3),peakMemoryMB:d}),this.maybePersistToKv(),m}async computeBaselineAttention(t,e,r,a,n){let o=performance.now(),i=process.memoryUsage().heapUsed/1024/1024,s=new Float32Array(a*a),u=1/Math.sqrt(n);for(let h=0;h<a;h++)for(let d=0;d<a;d++){let b=0;for(let p=0;p<n;p++)b+=t[h*n+p]*e[d*n+p];s[h*a+d]=b*u}for(let h=0;h<a;h++){let d=h*a,b=d+a,p=s.subarray(d,b),tt=Math.max(...p),_=0;for(let y=0;y<a;y++)p[y]=Math.exp(p[y]-tt),_+=p[y];for(let y=0;y<a;y++)p[y]/=_}let c=new Float32Array(a*n);for(let h=0;h<a;h++)for(let d=0;d<a;d++){let b=s[h*a+d];for(let p=0;p<n;p++)c[h*n+p]+=b*r[d*n+p]}let m=performance.now(),g=process.memoryUsage().heapUsed/1024/1024;return c}async computeTestSimilarity(t,e,r=5){let a=e.length,n=t.length,o=new Float32Array(a*n),i=new Float32Array(a*n);for(let m=0;m<a;m++)o.set(t,m*n),i.set(e[m],m*n);let s=new Float32Array(a*n),u=await this.computeFlashAttention(o,i,s,a,n),c=[];for(let m=0;m<a;m++)c.push({index:m,similarity:u[m*n]});return c.sort((m,g)=>g.similarity-m.similarity),c.slice(0,r)}async generateCodeEmbedding(t,e){let r=t.length/e.length,a=e.length;return await this.computeFlashAttention(t,e,t,r,a)}async matchDefectPattern(t,e){let r=e.length,a=t.length,n=new Float32Array(r*a),o=new Float32Array(r*a);for(let c=0;c<r;c++)n.set(t,c*a),o.set(e[c],c*a);let i=new Float32Array(r*a),s=await this.computeFlashAttention(n,o,i,r,a),u=[];for(let c=0;c<r;c++)u.push({pattern:c,score:s[c*a]});return u.sort((c,m)=>m.score-c.score),u}getMetrics(){return[...this.metrics]}getAverageSpeedup(){return this.metrics.length===0?1:this.metrics.reduce((t,e)=>t+e.speedup,0)/this.metrics.length}getConfig(){return{...this.config}}updateConfig(t){this.config={...this.config,...t},this.attention=E.create(this.config)}changeStrategy(t){this.config.strategy=t,this.attention=E.create(this.config)}resetMetrics(){this.metrics=[]}getWorkload(){return this.workload}dispose(){this.metrics=[]}async persistToKv(){if(!this.db)return;let t=`attention-metrics-${this.workload}`,e={workload:this.workload,metrics:this.metrics.slice(-50),savedAt:Date.now()};await this.db.kvSet(t,e,l.KV_NAMESPACE,l.KV_TTL)}async loadFromKv(){if(!this.db)return;let t=`attention-metrics-${this.workload}`,e=await this.db.kvGet(t,l.KV_NAMESPACE);e?.metrics?.length&&(this.metrics=e.metrics)}maybePersistToKv(){this.persistCount++,this.persistCount>=l.PERSIST_INTERVAL&&(this.persistCount=0,this.persistToKv().catch(()=>{}))}toFloat32Array(t,e,r){return t.slice(0,r)}splitMatrix(t,e,r){let a=[];for(let n=0;n<e;n++)a.push(t.slice(n*r,(n+1)*r));return a}};async function Y(l,t){let e=new L(l,t);return await e.initialize(),e}function Jt(l){return{...T[l]}}function Xt(){return Object.keys(T)}function Yt(){return A(),F}function te(){return A(),D}function ee(){return A(),W}function re(){return A(),B}function ae(){return A(),z}function ne(){return A(),I}function ie(l){return l instanceof Float32Array?l:new Float32Array(l)}function oe(l){return Array.from(l)}async function se(l,t,e,r){let a=await Y(l),n=[],o=t[0].length,i=e.length;for(let s of t){let u=new Float32Array(i*o),c=new Float32Array(i*o),m=new Float32Array(i*o);u.set(s,0);for(let h=0;h<i;h++)c.set(e[h],h*o),m.set(r[h],h*o);let g=await a.computeFlashAttention(u,c,m,i,o);n.push(g.slice(0,o))}return a.dispose(),n}function We(){return{"@ruvector/sona":"^0.1.5","@ruvector/attention":"^0.1.4","@ruvector/gnn":"^0.1.22"}}function Be(){let l={sona:!1,attention:!1,gnn:!1,all:!1};try{k(),l.sona=!0}catch{}try{O(),l.attention=!0}catch{}try{let t=(it(),w(nt));t.init();let e=new Float32Array([.1,.2,.3]),r=[new Float32Array([.1,.2,.3]),new Float32Array([.4,.5,.6])],a=t.differentiableSearch(e,r,1,1);a&&Array.isArray(a.indices)&&Array.isArray(a.weights)&&(l.gnn=!0)}catch{}return l.all=l.sona&&l.attention&&l.gnn,l}async function ze(){let{initGNN:l}=await import("./gnn-wrapper-XEII72LN.js");return[l(),"SONA: Ready (no initialization required)","Attention: Ready (no initialization required)"]}export{v as a,Tt as b,Pt as c,Gt as d,T as e,Kt as f,$t as g,Zt as h,L as i,Y as j,Jt as k,Xt as l,Yt as m,te as n,ee as o,re as p,ae as q,ne as r,ie as s,oe as t,se as u,We as v,Be as w,ze as x};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.1");process.exit(0)}
2
- import{d as k,f as we}from"./chunk-AFPMCMVX.js";import{a as ye}from"./chunk-U5JQGRHZ.js";import{c as Q}from"./chunk-A57BEPL7.js";import{b as C,d as Z}from"./chunk-JSOBRKMA.js";import{a as V,c as be}from"./chunk-UN4PA4M2.js";import{a as J,b as Xe}from"./chunk-GFNUESMU.js";import{a as ee,d as b,e as te,f as ne}from"./chunk-ZEUVPLGX.js";import{a as v,e as De}from"./chunk-SGRN6JFB.js";import{c as R,e as ve}from"./chunk-UZZCWWIG.js";function O(i){if(!q.has(i))throw new Error(`Invalid table name: "${i}" is not in the allowlist`);return i}function ze(i){let e=i.split(".");if(e.length>2)throw new Error(`Invalid SQL identifier: "${i}" has too many parts (max: schema.table)`);for(let t of e)if(!re.test(t))throw new Error(`Invalid SQL identifier: "${i}" \u2014 part "${t}" does not match pattern ${re}`);return i}var q,re,z=R(()=>{"use strict";q=new Set(["schema_version","kv_store","vectors","rl_q_values","goap_goals","goap_actions","goap_plans","goap_plan_signatures","concept_nodes","concept_edges","dream_cycles","dream_insights","qe_patterns","qe_pattern_embeddings","qe_pattern_usage","qe_trajectories","embeddings","execution_results","executed_steps","mincut_snapshots","mincut_history","mincut_weak_vertices","mincut_alerts","mincut_healing_actions","mincut_observations","sona_patterns","sona_fisher_matrices","test_outcomes","routing_outcomes","coverage_sessions","patterns","hypergraph_nodes","hypergraph_edges","hypergraph_vertices","hypergraph_hyperedges","hypergraph_edge_vertices","hypergraph_vertex_properties","hypergraph_edge_properties","captured_experiences","experience_applications","witness_chain","witness_chain_receipts","witness_chain_archive","trajectories","trajectory_steps","pattern_evolution_events","pattern_relationships","pattern_versions","learning_daily_snapshots","metrics_outcomes","experience_consolidation_log","qe_pattern_reuse","qe_agent_co_execution"]);re=/^[a-z_][a-z0-9_]{0,62}$/});var D,se,oe,ie,ae,ce,Te,Ee,de,ue,le,pe,ge=R(()=>{"use strict";we();D=9,se=`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.2");process.exit(0)}
2
+ import{d as k,f as we}from"./chunk-SNVM4YJS.js";import{a as ye}from"./chunk-XIBVVZGB.js";import{c as Q}from"./chunk-JOVINE23.js";import{b as C,d as Z}from"./chunk-N3F3CX4V.js";import{a as V,c as be}from"./chunk-SDTVHR63.js";import{a as J,b as Xe}from"./chunk-XYJL6DKI.js";import{a as ee,d as b,e as te,f as ne}from"./chunk-KNVAAVHH.js";import{a as v,e as De}from"./chunk-MN742FIH.js";import{c as R,e as ve}from"./chunk-YXCU4CJX.js";function O(i){if(!q.has(i))throw new Error(`Invalid table name: "${i}" is not in the allowlist`);return i}function ze(i){let e=i.split(".");if(e.length>2)throw new Error(`Invalid SQL identifier: "${i}" has too many parts (max: schema.table)`);for(let t of e)if(!re.test(t))throw new Error(`Invalid SQL identifier: "${i}" \u2014 part "${t}" does not match pattern ${re}`);return i}var q,re,z=R(()=>{"use strict";q=new Set(["schema_version","kv_store","vectors","rl_q_values","goap_goals","goap_actions","goap_plans","goap_plan_signatures","concept_nodes","concept_edges","dream_cycles","dream_insights","qe_patterns","qe_pattern_embeddings","qe_pattern_usage","qe_trajectories","embeddings","execution_results","executed_steps","mincut_snapshots","mincut_history","mincut_weak_vertices","mincut_alerts","mincut_healing_actions","mincut_observations","sona_patterns","sona_fisher_matrices","test_outcomes","routing_outcomes","coverage_sessions","patterns","hypergraph_nodes","hypergraph_edges","hypergraph_vertices","hypergraph_hyperedges","hypergraph_edge_vertices","hypergraph_vertex_properties","hypergraph_edge_properties","captured_experiences","experience_applications","witness_chain","witness_chain_receipts","witness_chain_archive","trajectories","trajectory_steps","pattern_evolution_events","pattern_relationships","pattern_versions","learning_daily_snapshots","metrics_outcomes","experience_consolidation_log","qe_pattern_reuse","qe_agent_co_execution"]);re=/^[a-z_][a-z0-9_]{0,62}$/});var D,se,oe,ie,ae,ce,Te,Ee,de,ue,le,pe,ge=R(()=>{"use strict";we();D=9,se=`
3
3
  CREATE TABLE IF NOT EXISTS schema_version (
4
4
  id INTEGER PRIMARY KEY CHECK (id = 1),
5
5
  version INTEGER NOT NULL,
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.1");process.exit(0)}
2
- import{a as n}from"./chunk-43M6Y6VF.js";import{a as o}from"./chunk-QMFP5OKH.js";import{a,e as c}from"./chunk-SGRN6JFB.js";c();var M=a.CLEANUP_INTERVAL_MS,y=".agentic-qe/memory.db";async function d(r,t=!0){let e;switch(r.type){case"memory":e=new o;break;case"sqlite":e=new n({sqlite:r.sqlite,enableFallback:!0});break;case"agentdb":e=new n({sqlite:{path:r.agentdb?.path??y},enableFallback:!0});break;case"hybrid":e=new n(r.hybrid);break;default:throw new Error(`Unknown memory backend type: ${r.type}`)}return t&&await e.initialize(),{backend:e,type:r.type,initialized:t}}async function u(r=!0){let t=process.env.AQE_MEMORY_BACKEND??"memory",e=process.env.AQE_MEMORY_PATH??".agentic-qe",i={type:t,sqlite:{path:`${e}/memory.db`,walMode:!0},agentdb:{path:`${e}/memory.db`},hybrid:{enableFallback:!0,sqlite:{path:`${e}/memory.db`}}};return d(i,r)}export{d as a,u as b};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.2");process.exit(0)}
2
+ import{a as n}from"./chunk-3GZKAORV.js";import{a as o}from"./chunk-VUAO4VFC.js";import{a,e as c}from"./chunk-MN742FIH.js";c();var M=a.CLEANUP_INTERVAL_MS,y=".agentic-qe/memory.db";async function d(r,t=!0){let e;switch(r.type){case"memory":e=new o;break;case"sqlite":e=new n({sqlite:r.sqlite,enableFallback:!0});break;case"agentdb":e=new n({sqlite:{path:r.agentdb?.path??y},enableFallback:!0});break;case"hybrid":e=new n(r.hybrid);break;default:throw new Error(`Unknown memory backend type: ${r.type}`)}return t&&await e.initialize(),{backend:e,type:r.type,initialized:t}}async function u(r=!0){let t=process.env.AQE_MEMORY_BACKEND??"memory",e=process.env.AQE_MEMORY_PATH??".agentic-qe",i={type:t,sqlite:{path:`${e}/memory.db`,walMode:!0},agentdb:{path:`${e}/memory.db`},hybrid:{enableFallback:!0,sqlite:{path:`${e}/memory.db`}}};return d(i,r)}export{d as a,u as b};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.1");process.exit(0)}
2
- import{b as ye}from"./chunk-GLIFZWV2.js";import{a as ht,b as ft}from"./chunk-RWXI7XAR.js";import{a as yt}from"./chunk-ZSRQHJEW.js";import{a as mt,b as pt}from"./chunk-3WQNW6CH.js";import{b as gt,d as z}from"./chunk-4BHOAQJH.js";import{j as I}from"./chunk-POLFT2PQ.js";import{a as ct}from"./chunk-5GPTM2RV.js";import{a as fe}from"./chunk-DC3HPOOJ.js";import{k as w,o as he}from"./chunk-24E47G3D.js";import{a as un}from"./chunk-U5JQGRHZ.js";import{c as ut}from"./chunk-A57BEPL7.js";import{b as E,d as dt}from"./chunk-JSOBRKMA.js";import{a as T,b as C,c as y}from"./chunk-5LDBKZ6P.js";import{a as p,b as lt,c as k}from"./chunk-UN4PA4M2.js";import{f}from"./chunk-UB7RGVKO.js";import{R as dn,S as gn}from"./chunk-MZ54VM6A.js";import{c as G,e as cn,g as ot}from"./chunk-UZZCWWIG.js";function Ct(s){let e=[],t=0;if(s.fileCount!==void 0&&(s.fileCount>20?(t+=25,e.push({name:"very-high-file-count",weight:25,description:`Task involves ${s.fileCount} files (>20)`})):s.fileCount>10?(t+=20,e.push({name:"high-file-count",weight:20,description:`Task involves ${s.fileCount} files (>10)`})):s.fileCount>5&&(t+=10,e.push({name:"moderate-file-count",weight:10,description:`Task involves ${s.fileCount} files (>5)`}))),s.domain&&(hn.includes(s.domain)?(t+=30,e.push({name:"complex-domain",weight:30,description:`Domain '${s.domain}' requires complex reasoning`})):fn.includes(s.domain)&&(t+=15,e.push({name:"moderate-domain",weight:15,description:`Domain '${s.domain}' has moderate complexity`}))),s.crossComponent&&(t+=25,e.push({name:"cross-component",weight:25,description:"Task spans multiple components/modules"})),s.priority==="critical"?(t+=25,e.push({name:"critical-priority",weight:25,description:"Critical priority requires careful attention"})):s.priority==="high"&&(t+=15,e.push({name:"high-priority",weight:15,description:"High priority task"})),s.requiredCapabilities){let r=s.requiredCapabilities.filter(a=>yn.includes(a)).length;if(r>0){let a=Math.min(20,r*10);t+=a,e.push({name:"complex-capabilities",weight:a,description:`Requires ${r} complex capabilit${r===1?"y":"ies"}`})}}s.requiresExternalApis&&(t+=10,e.push({name:"external-apis",weight:10,description:"Requires external API integration"})),s.involvesDatabaseOps&&(t+=10,e.push({name:"database-ops",weight:10,description:"Involves database operations"})),s.timeSensitive&&(t+=5,e.push({name:"time-sensitive",weight:5,description:"Time-sensitive task"})),s.estimatedLinesAffected!==void 0&&(s.estimatedLinesAffected>500?(t+=15,e.push({name:"large-change",weight:15,description:`Estimated ${s.estimatedLinesAffected} lines affected (>500)`})):s.estimatedLinesAffected>200&&(t+=10,e.push({name:"medium-change",weight:10,description:`Estimated ${s.estimatedLinesAffected} lines affected (>200)`}))),(s.type==="security-scan"||s.type==="vulnerability-assessment")&&(t+=20,e.push({name:"security-task",weight:20,description:"Security-related task requires careful analysis"}));let n=t>=S.critical?"critical":t>=S.complex?"complex":t>=S.moderate?"moderate":"simple",i=Tn[n];return{complexity:n,recommendedModel:i,factors:e,score:t,timestamp:new Date}}var hn,fn,yn,S,Tn,bt=G(()=>{"use strict";hn=["security-compliance","chaos-resilience","defect-intelligence"],fn=["code-intelligence","contract-testing","quality-assessment","learning-optimization"],yn=["sast","dast","vulnerability","owasp","chaos-testing","resilience","fault-injection","mutation-testing"],S={critical:70,complex:45,moderate:20},Tn={critical:"opus",complex:"sonnet",moderate:"sonnet",simple:"haiku"}});var R,De=G(()=>{"use strict";R=class{weightsInputHidden;weightsHiddenOutput;biasHidden;biasOutput;learningRate;constructor(e=.01){this.learningRate=e,this.weightsInputHidden=this.xavierInit(4,32),this.weightsHiddenOutput=this.xavierInit(32,3),this.biasHidden=new Float32Array(32),this.biasOutput=new Float32Array(3)}xavierInit(e,t){let n=Math.sqrt(2/(e+t)),i=new Float32Array(e*t);for(let r=0;r<i.length;r++){let a=Math.random(),o=Math.random(),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 St={};cn(St,{NeuralTinyDancerRouter:()=>V,SimpleNeuralRouter:()=>R,createNeuralTinyDancerRouter:()=>Mn});import{performance as kt}from"perf_hooks";function Mn(s){return new V(s)}var vn,Cn,bn,kn,Sn,xn,Dn,An,V,xt=G(()=>{"use strict";Ae();De();De();vn=1e3,Cn=.1,bn=.2,kn=50,Sn=.01,xn=["haiku","sonnet","opus"],Dn={haiku:0,sonnet:1,opus:2},An={"test-generation":.1,"test-execution":.15,"coverage-analysis":.2,"quality-assessment":.3,"requirements-validation":.35,"code-intelligence":.4,"contract-testing":.45,"visual-accessibility":.5,"learning-optimization":.55,"defect-intelligence":.7,"chaos-resilience":.8,"security-compliance":.9},V=class{ruleRouter;neuralNet;circuitBreakerThreshold;shadowModeDecisionLimit;shadowModeMaxDisagreement;shadowModeActive;shadowDecisions=[];shadowDisagreements=0;circuitBreakerTripped=!1;recentOutcomes=[];totalNeuralDecisions=0;totalWeightUpdates=0;neuralPrimary=!1;calibrationScores=[];maxCalibrationScores=500;domainSuccessRates=new Map;config;nativeRouterAvailable=!1;constructor(e={}){this.config=e,this.ruleRouter=new H(e),this.neuralNet=new R(e.learningRate??Sn),this.circuitBreakerThreshold=e.circuitBreakerThreshold??bn,this.shadowModeDecisionLimit=e.shadowModeDecisions??vn,this.shadowModeMaxDisagreement=e.shadowModeMaxDisagreement??Cn,e.forceShadowMode!==void 0?(this.shadowModeActive=e.forceShadowMode,this.neuralPrimary=!e.forceShadowMode):(this.shadowModeActive=!0,this.neuralPrimary=!1),this.tryLoadNativeRouter()}tryLoadNativeRouter(){this.nativeRouterAvailable=!1}async route(e){let t=kt.now(),n=await this.ruleRouter.route(e);if(this.circuitBreakerTripped)return n;let i=this.extractFeatures(e,n.classification),r;try{r=this.neuralNet.forward(i)}catch{return this.tripCircuitBreaker(),n}let a=this.argmax(r),o=xn[a],l=r[a];if(this.totalNeuralDecisions++,this.shadowModeActive){let g=n.model===o;return g||this.shadowDisagreements++,this.shadowDecisions.push({taskDescription:e.description.slice(0,100),ruleDecision:n.model,neuralDecision:o,agreed:g,neuralConfidence:l,timestamp:new Date}),this.evaluateShadowModeExit(),n}let c=kt.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=An[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>kn&&this.recentOutcomes.shift(),this.checkCircuitBreaker();let c=this.extractFeatures(e,t.classification),u=Dn[r],d=(i-.5)*2;try{this.neuralNet.updateWeights(c,u,d),this.totalWeightUpdates++}catch{}let g=this.neuralNet.forward(c),h=this.argmax(g),b=1-g[u];this.calibrationScores.push(b),this.calibrationScores.length>this.maxCalibrationScores&&this.calibrationScores.shift()}computeEmpiricalConfidenceBounds(e){let n=Math.max(...e),i=1-n;if(this.calibrationScores.length<10)return{lower:0,upper:1,coverageLevel:.9,calibrationScore:i};let r=[...this.calibrationScores].sort((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 Dt}from"perf_hooks";function At(s){try{let{getRuVectorFeatureFlags:e}=(gn(),ot(dn));if(e().useNeuralRouting){let{NeuralTinyDancerRouter:n}=(xt(),ot(St));return new n(s)}}catch(e){process.env.DEBUG&&console.debug("[Router] Neural router unavailable, using rule-based:",e instanceof Error?e.message:e)}return new H(s)}var H,Ae=G(()=>{"use strict";bt();H=class{confidenceThreshold;uncertaintyThreshold;securityConfidenceThreshold;enableLearning;verbose;totalRouted=0;routesByModel={haiku:0,sonnet:0,opus:0};routesByComplexity={simple:0,moderate:0,complex:0,critical:0};multiModelTriggers=0;humanReviewTriggers=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}async route(e){let t=Dt.now(),n=Ct(e),i=this.calculateConfidence(n),r=1-i,a=this.isSecurityTask(e),o=a&&i<this.securityConfidenceThreshold||i<this.confidenceThreshold&&n.complexity!=="simple",l=r>this.uncertaintyThreshold||a&&n.complexity==="critical",c=Dt.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 g=Math.abs(t-d);g<r&&(r=g)}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,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.humanReviewTriggers=0,this.totalConfidence=0,this.totalLatencyMs=0,this.outcomes=[]}getConfig(){return{confidenceThreshold:this.confidenceThreshold,uncertaintyThreshold:this.uncertaintyThreshold,securityConfidenceThreshold:this.securityConfidenceThreshold,enableLearning:this.enableLearning,verbose:this.verbose}}}});var mn={enableConsoleLog:!0,maxEntries:1e3,logPrefix:"[TASK]"},q=class{entries=[];config;constructor(e={}){this.config={...mn,...e}}log(e,t,n){let i={timestamp:new Date,operation:e,taskId:t,agentId:n?.agentId,domain:n?.domain,details:n?.details};if(this.entries.push(i),this.entries.length>this.config.maxEntries&&this.entries.splice(0,this.entries.length-this.config.maxEntries),this.config.enableConsoleLog){let r=n?.agentId?` by ${n.agentId}`:"",a=n?.domain?` (${n.domain})`:"";console.log(`${this.config.logPrefix} ${e.toUpperCase()} ${t}${r}${a}`)}}logSubmit(e,t){this.log("submit",e,{details:t})}logAssign(e,t,n){this.log("assign",e,{agentId:t,domain:n})}logReassign(e,t,n,i){this.log("reassign",e,{agentId:n,domain:i,details:{fromAgent:t}})}logComplete(e,t){this.log("complete",e,{agentId:t})}logFail(e,t,n){this.log("fail",e,{agentId:t,details:n?{error:n}:void 0})}logCancel(e){this.log("cancel",e)}logSteal(e,t,n){this.log("steal",e,{domain:n,details:{fromDomain:t}})}logQueue(e,t){this.log("queue",e,{details:{position:t}})}logDequeue(e){this.log("dequeue",e)}getEntries(e){let t=[...this.entries];e&&(e.operation&&(t=t.filter(i=>i.operation===e.operation)),e.taskId&&(t=t.filter(i=>i.taskId===e.taskId)),e.agentId&&(t=t.filter(i=>i.agentId===e.agentId)),e.domain&&(t=t.filter(i=>i.domain===e.domain)),e.fromTimestamp&&(t=t.filter(i=>i.timestamp>=e.fromTimestamp)),e.toTimestamp&&(t=t.filter(i=>i.timestamp<=e.toTimestamp)));let n=e?.limit??t.length;return t.slice(-n)}getStatistics(){let e={submit:0,assign:0,reassign:0,complete:0,fail:0,cancel:0,steal:0,queue:0,dequeue:0},t=new Set,n=new Set;for(let i of this.entries)e[i.operation]++,t.add(i.taskId),i.agentId&&n.add(i.agentId);return{totalEntries:this.entries.length,operationCounts:e,taskCount:t.size,agentCount:n.size}}clear(){this.entries.length=0}};function Te(s){return new q(s)}var j={healthyThreshold:3,warningThreshold:2,checkIntervalMs:5e3,maxHistoryEntries:100,alertsEnabled:!0,alertCooldownMs:6e4,selfHealingEnabled:!1,maxHealingActionsPerMinute:5};var ve=class{calculator;config;eventBus;persistence;graph;history=[];alerts=new Map;lastAlertTime=new Map;monitoringInterval=null;isMonitoring=!1;constructor(e,t={},n,i){this.graph=e,this.config={...j,...t},this.calculator=gt(),this.eventBus=n,this.persistence=i}start(){this.isMonitoring||(this.isMonitoring=!0,this.monitoringInterval=setInterval(()=>this.checkHealth(),this.config.checkIntervalMs),this.checkHealth())}stop(){this.monitoringInterval&&(clearInterval(this.monitoringInterval),this.monitoringInterval=null),this.isMonitoring=!1}updateGraph(e){this.graph=e,this.isMonitoring&&this.checkHealth()}isEmptyTopology(){return this.graph.getVerticesByType("agent").length===0}checkHealth(){let e=this.calculator.getMinCutValue(this.graph),t=this.calculator.findWeakVertices(this.graph),n=this.isEmptyTopology()?"idle":this.determineStatus(e),i=this.calculateTrend();return this.recordHistory(e),this.isEmptyTopology()||this.checkAlertConditions(e,t,n),this.persistence&&t.length>0&&this.persistence.saveWeakVertices(t).catch(r=>console.warn("[MinCutHealthMonitor] Failed to persist weak vertices:",r)),this.emitEvent("mincut.updated",e,{status:n,weakVertexCount:t.length}),{status:n,minCutValue:e,healthyThreshold:this.config.healthyThreshold,warningThreshold:this.config.warningThreshold,weakVertexCount:t.length,topWeakVertices:t.slice(0,5),trend:i,history:this.history.slice(-20),lastUpdated:new Date}}getHealth(){let e=this.calculator.getMinCutValue(this.graph),t=this.calculator.findWeakVertices(this.graph);return{status:this.isEmptyTopology()?"idle":this.determineStatus(e),minCutValue:e,healthyThreshold:this.config.healthyThreshold,warningThreshold:this.config.warningThreshold,weakVertexCount:t.length,topWeakVertices:t.slice(0,5),trend:this.calculateTrend(),history:this.history.slice(-20),lastUpdated:new Date}}getMinCutValue(){return this.calculator.getMinCutValue(this.graph)}getWeakVertices(){return this.calculator.findWeakVertices(this.graph)}isCritical(){return this.calculator.getMinCutValue(this.graph)<this.config.warningThreshold}isHealthy(){return this.calculator.getMinCutValue(this.graph)>=this.config.healthyThreshold}getActiveAlerts(){return Array.from(this.alerts.values()).filter(e=>!e.acknowledged).sort((e,t)=>{let n={critical:0,high:1,medium:2,low:3,info:4};return n[e.severity]-n[t.severity]})}getAllAlerts(){return Array.from(this.alerts.values())}acknowledgeAlert(e){let t=this.alerts.get(e);return t?(t.acknowledged=!0,!0):!1}clearAcknowledgedAlerts(){let e=[];for(let[t,n]of this.alerts)n.acknowledged&&e.push(t);for(let t of e)this.alerts.delete(t);return e.length}getHistory(){return[...this.history]}getTrend(){return this.calculateTrend()}getStats(e=6e4){let t=Date.now()-e,n=this.history.filter(r=>r.timestamp.getTime()>t);if(n.length===0){let r=this.calculator.getMinCutValue(this.graph);return{min:r,max:r,average:r,count:0}}let i=n.map(r=>r.value);return{min:Math.min(...i),max:Math.max(...i),average:i.reduce((r,a)=>r+a,0)/i.length,count:n.length}}updateConfig(e){Object.assign(this.config,e),e.checkIntervalMs&&this.isMonitoring&&(this.stop(),this.start())}getConfig(){return{...this.config}}determineStatus(e){return e>=this.config.healthyThreshold?"healthy":e>=this.config.warningThreshold?"warning":"critical"}calculateTrend(){if(this.history.length<3)return"stable";let e=this.history.slice(-5),t=e[0].value,i=e[e.length-1].value-t,a=e.reduce((o,l)=>o+l.value,0)/e.length*.1;return i>a?"improving":i<-a?"degrading":"stable"}recordHistory(e){let t={timestamp:new Date,value:e,vertexCount:this.graph.vertexCount,edgeCount:this.graph.edgeCount};for(this.history.push(t);this.history.length>this.config.maxHistoryEntries;)this.history.shift()}checkAlertConditions(e,t,n){if(!this.config.alertsEnabled)return;let i=Date.now();n==="critical"?this.maybeGenerateAlert("critical-threshold","critical",`MinCut value (${e.toFixed(2)}) is below critical threshold (${this.config.warningThreshold})`,e,this.config.warningThreshold,t):n==="warning"&&this.maybeGenerateAlert("warning-threshold","high",`MinCut value (${e.toFixed(2)}) is below healthy threshold (${this.config.healthyThreshold})`,e,this.config.healthyThreshold,t);let r=t.filter(o=>o.weightedDegree===0);r.length>0&&this.maybeGenerateAlert("isolated-vertices","high",`${r.length} isolated vertex(es) detected`,e,0,r);let a=t.filter(o=>o.riskScore>.8);a.length>0&&this.maybeGenerateAlert("critical-vertices","medium",`${a.length} critical vertex(es) with high risk score`,e,0,a)}maybeGenerateAlert(e,t,n,i,r,a){let o=Date.now(),l=this.lastAlertTime.get(e)||0;if(o-l<this.config.alertCooldownMs)return;let c={id:f(),severity:t,message:n,minCutValue:i,threshold:r,affectedVertices:a.map(u=>u.vertexId),timestamp:new Date,acknowledged:!1,remediations:a.flatMap(u=>u.suggestions).slice(0,5)};this.alerts.set(c.id,c),this.persistence&&this.persistence.saveAlert(c).catch(u=>console.warn("[MinCutHealthMonitor] Failed to persist alert:",u)),this.lastAlertTime.set(e,o),this.emitEvent("mincut.alert.generated",i,{alert:c})}emitEvent(e,t,n){if(!this.eventBus)return;let i={id:f(),type:e,source:"coordination",timestamp:new Date,correlationId:f(),payload:{minCutValue:t,...n}};this.eventBus.publish(i).catch(r=>{console.error("Failed to publish MinCut event:",r)})}};function W(s,e,t,n){return new ve(s,e,t,n)}he();dt();var Ce=class{memory;initialized=!1;constructor(e){this.memory=e??w()}async initialize(){this.initialized||(this.memory.isInitialized()||await this.memory.initialize(),this.initialized=!0)}async saveSnapshot(e){this.ensureInitialized();let t=f();return this.memory.getDatabase().prepare(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.2");process.exit(0)}
2
+ import{b as ye}from"./chunk-VHVWAXCF.js";import{a as ht,b as ft}from"./chunk-RC5CPXON.js";import{a as yt}from"./chunk-NRCKGXJJ.js";import{a as mt,b as pt}from"./chunk-KDDZYXP4.js";import{b as gt,d as z}from"./chunk-Z5HXGVXZ.js";import{j as I}from"./chunk-Q4A72ZTV.js";import{a as ct}from"./chunk-7NOIIC7G.js";import{a as fe}from"./chunk-TKF447CW.js";import{k as w,o as he}from"./chunk-GK72GUHA.js";import{a as un}from"./chunk-XIBVVZGB.js";import{c as ut}from"./chunk-JOVINE23.js";import{b as E,d as dt}from"./chunk-N3F3CX4V.js";import{a as T,b as C,c as y}from"./chunk-BIVIPF4O.js";import{a as p,b as lt,c as k}from"./chunk-SDTVHR63.js";import{f}from"./chunk-E25S5E2D.js";import{R as dn,S as gn}from"./chunk-DBE34QES.js";import{c as G,e as cn,g as ot}from"./chunk-YXCU4CJX.js";function Ct(s){let e=[],t=0;if(s.fileCount!==void 0&&(s.fileCount>20?(t+=25,e.push({name:"very-high-file-count",weight:25,description:`Task involves ${s.fileCount} files (>20)`})):s.fileCount>10?(t+=20,e.push({name:"high-file-count",weight:20,description:`Task involves ${s.fileCount} files (>10)`})):s.fileCount>5&&(t+=10,e.push({name:"moderate-file-count",weight:10,description:`Task involves ${s.fileCount} files (>5)`}))),s.domain&&(hn.includes(s.domain)?(t+=30,e.push({name:"complex-domain",weight:30,description:`Domain '${s.domain}' requires complex reasoning`})):fn.includes(s.domain)&&(t+=15,e.push({name:"moderate-domain",weight:15,description:`Domain '${s.domain}' has moderate complexity`}))),s.crossComponent&&(t+=25,e.push({name:"cross-component",weight:25,description:"Task spans multiple components/modules"})),s.priority==="critical"?(t+=25,e.push({name:"critical-priority",weight:25,description:"Critical priority requires careful attention"})):s.priority==="high"&&(t+=15,e.push({name:"high-priority",weight:15,description:"High priority task"})),s.requiredCapabilities){let r=s.requiredCapabilities.filter(a=>yn.includes(a)).length;if(r>0){let a=Math.min(20,r*10);t+=a,e.push({name:"complex-capabilities",weight:a,description:`Requires ${r} complex capabilit${r===1?"y":"ies"}`})}}s.requiresExternalApis&&(t+=10,e.push({name:"external-apis",weight:10,description:"Requires external API integration"})),s.involvesDatabaseOps&&(t+=10,e.push({name:"database-ops",weight:10,description:"Involves database operations"})),s.timeSensitive&&(t+=5,e.push({name:"time-sensitive",weight:5,description:"Time-sensitive task"})),s.estimatedLinesAffected!==void 0&&(s.estimatedLinesAffected>500?(t+=15,e.push({name:"large-change",weight:15,description:`Estimated ${s.estimatedLinesAffected} lines affected (>500)`})):s.estimatedLinesAffected>200&&(t+=10,e.push({name:"medium-change",weight:10,description:`Estimated ${s.estimatedLinesAffected} lines affected (>200)`}))),(s.type==="security-scan"||s.type==="vulnerability-assessment")&&(t+=20,e.push({name:"security-task",weight:20,description:"Security-related task requires careful analysis"}));let n=t>=S.critical?"critical":t>=S.complex?"complex":t>=S.moderate?"moderate":"simple",i=Tn[n];return{complexity:n,recommendedModel:i,factors:e,score:t,timestamp:new Date}}var hn,fn,yn,S,Tn,bt=G(()=>{"use strict";hn=["security-compliance","chaos-resilience","defect-intelligence"],fn=["code-intelligence","contract-testing","quality-assessment","learning-optimization"],yn=["sast","dast","vulnerability","owasp","chaos-testing","resilience","fault-injection","mutation-testing"],S={critical:70,complex:45,moderate:20},Tn={critical:"opus",complex:"sonnet",moderate:"sonnet",simple:"haiku"}});var R,De=G(()=>{"use strict";R=class{weightsInputHidden;weightsHiddenOutput;biasHidden;biasOutput;learningRate;constructor(e=.01){this.learningRate=e,this.weightsInputHidden=this.xavierInit(4,32),this.weightsHiddenOutput=this.xavierInit(32,3),this.biasHidden=new Float32Array(32),this.biasOutput=new Float32Array(3)}xavierInit(e,t){let n=Math.sqrt(2/(e+t)),i=new Float32Array(e*t);for(let r=0;r<i.length;r++){let a=Math.random(),o=Math.random(),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 St={};cn(St,{NeuralTinyDancerRouter:()=>V,SimpleNeuralRouter:()=>R,createNeuralTinyDancerRouter:()=>Mn});import{performance as kt}from"perf_hooks";function Mn(s){return new V(s)}var vn,Cn,bn,kn,Sn,xn,Dn,An,V,xt=G(()=>{"use strict";Ae();De();De();vn=1e3,Cn=.1,bn=.2,kn=50,Sn=.01,xn=["haiku","sonnet","opus"],Dn={haiku:0,sonnet:1,opus:2},An={"test-generation":.1,"test-execution":.15,"coverage-analysis":.2,"quality-assessment":.3,"requirements-validation":.35,"code-intelligence":.4,"contract-testing":.45,"visual-accessibility":.5,"learning-optimization":.55,"defect-intelligence":.7,"chaos-resilience":.8,"security-compliance":.9},V=class{ruleRouter;neuralNet;circuitBreakerThreshold;shadowModeDecisionLimit;shadowModeMaxDisagreement;shadowModeActive;shadowDecisions=[];shadowDisagreements=0;circuitBreakerTripped=!1;recentOutcomes=[];totalNeuralDecisions=0;totalWeightUpdates=0;neuralPrimary=!1;calibrationScores=[];maxCalibrationScores=500;domainSuccessRates=new Map;config;nativeRouterAvailable=!1;constructor(e={}){this.config=e,this.ruleRouter=new H(e),this.neuralNet=new R(e.learningRate??Sn),this.circuitBreakerThreshold=e.circuitBreakerThreshold??bn,this.shadowModeDecisionLimit=e.shadowModeDecisions??vn,this.shadowModeMaxDisagreement=e.shadowModeMaxDisagreement??Cn,e.forceShadowMode!==void 0?(this.shadowModeActive=e.forceShadowMode,this.neuralPrimary=!e.forceShadowMode):(this.shadowModeActive=!0,this.neuralPrimary=!1),this.tryLoadNativeRouter()}tryLoadNativeRouter(){this.nativeRouterAvailable=!1}async route(e){let t=kt.now(),n=await this.ruleRouter.route(e);if(this.circuitBreakerTripped)return n;let i=this.extractFeatures(e,n.classification),r;try{r=this.neuralNet.forward(i)}catch{return this.tripCircuitBreaker(),n}let a=this.argmax(r),o=xn[a],l=r[a];if(this.totalNeuralDecisions++,this.shadowModeActive){let g=n.model===o;return g||this.shadowDisagreements++,this.shadowDecisions.push({taskDescription:e.description.slice(0,100),ruleDecision:n.model,neuralDecision:o,agreed:g,neuralConfidence:l,timestamp:new Date}),this.evaluateShadowModeExit(),n}let c=kt.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=An[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>kn&&this.recentOutcomes.shift(),this.checkCircuitBreaker();let c=this.extractFeatures(e,t.classification),u=Dn[r],d=(i-.5)*2;try{this.neuralNet.updateWeights(c,u,d),this.totalWeightUpdates++}catch{}let g=this.neuralNet.forward(c),h=this.argmax(g),b=1-g[u];this.calibrationScores.push(b),this.calibrationScores.length>this.maxCalibrationScores&&this.calibrationScores.shift()}computeEmpiricalConfidenceBounds(e){let n=Math.max(...e),i=1-n;if(this.calibrationScores.length<10)return{lower:0,upper:1,coverageLevel:.9,calibrationScore:i};let r=[...this.calibrationScores].sort((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 Dt}from"perf_hooks";function At(s){try{let{getRuVectorFeatureFlags:e}=(gn(),ot(dn));if(e().useNeuralRouting){let{NeuralTinyDancerRouter:n}=(xt(),ot(St));return new n(s)}}catch(e){process.env.DEBUG&&console.debug("[Router] Neural router unavailable, using rule-based:",e instanceof Error?e.message:e)}return new H(s)}var H,Ae=G(()=>{"use strict";bt();H=class{confidenceThreshold;uncertaintyThreshold;securityConfidenceThreshold;enableLearning;verbose;totalRouted=0;routesByModel={haiku:0,sonnet:0,opus:0};routesByComplexity={simple:0,moderate:0,complex:0,critical:0};multiModelTriggers=0;humanReviewTriggers=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}async route(e){let t=Dt.now(),n=Ct(e),i=this.calculateConfidence(n),r=1-i,a=this.isSecurityTask(e),o=a&&i<this.securityConfidenceThreshold||i<this.confidenceThreshold&&n.complexity!=="simple",l=r>this.uncertaintyThreshold||a&&n.complexity==="critical",c=Dt.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 g=Math.abs(t-d);g<r&&(r=g)}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,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.humanReviewTriggers=0,this.totalConfidence=0,this.totalLatencyMs=0,this.outcomes=[]}getConfig(){return{confidenceThreshold:this.confidenceThreshold,uncertaintyThreshold:this.uncertaintyThreshold,securityConfidenceThreshold:this.securityConfidenceThreshold,enableLearning:this.enableLearning,verbose:this.verbose}}}});var mn={enableConsoleLog:!0,maxEntries:1e3,logPrefix:"[TASK]"},q=class{entries=[];config;constructor(e={}){this.config={...mn,...e}}log(e,t,n){let i={timestamp:new Date,operation:e,taskId:t,agentId:n?.agentId,domain:n?.domain,details:n?.details};if(this.entries.push(i),this.entries.length>this.config.maxEntries&&this.entries.splice(0,this.entries.length-this.config.maxEntries),this.config.enableConsoleLog){let r=n?.agentId?` by ${n.agentId}`:"",a=n?.domain?` (${n.domain})`:"";console.log(`${this.config.logPrefix} ${e.toUpperCase()} ${t}${r}${a}`)}}logSubmit(e,t){this.log("submit",e,{details:t})}logAssign(e,t,n){this.log("assign",e,{agentId:t,domain:n})}logReassign(e,t,n,i){this.log("reassign",e,{agentId:n,domain:i,details:{fromAgent:t}})}logComplete(e,t){this.log("complete",e,{agentId:t})}logFail(e,t,n){this.log("fail",e,{agentId:t,details:n?{error:n}:void 0})}logCancel(e){this.log("cancel",e)}logSteal(e,t,n){this.log("steal",e,{domain:n,details:{fromDomain:t}})}logQueue(e,t){this.log("queue",e,{details:{position:t}})}logDequeue(e){this.log("dequeue",e)}getEntries(e){let t=[...this.entries];e&&(e.operation&&(t=t.filter(i=>i.operation===e.operation)),e.taskId&&(t=t.filter(i=>i.taskId===e.taskId)),e.agentId&&(t=t.filter(i=>i.agentId===e.agentId)),e.domain&&(t=t.filter(i=>i.domain===e.domain)),e.fromTimestamp&&(t=t.filter(i=>i.timestamp>=e.fromTimestamp)),e.toTimestamp&&(t=t.filter(i=>i.timestamp<=e.toTimestamp)));let n=e?.limit??t.length;return t.slice(-n)}getStatistics(){let e={submit:0,assign:0,reassign:0,complete:0,fail:0,cancel:0,steal:0,queue:0,dequeue:0},t=new Set,n=new Set;for(let i of this.entries)e[i.operation]++,t.add(i.taskId),i.agentId&&n.add(i.agentId);return{totalEntries:this.entries.length,operationCounts:e,taskCount:t.size,agentCount:n.size}}clear(){this.entries.length=0}};function Te(s){return new q(s)}var j={healthyThreshold:3,warningThreshold:2,checkIntervalMs:5e3,maxHistoryEntries:100,alertsEnabled:!0,alertCooldownMs:6e4,selfHealingEnabled:!1,maxHealingActionsPerMinute:5};var ve=class{calculator;config;eventBus;persistence;graph;history=[];alerts=new Map;lastAlertTime=new Map;monitoringInterval=null;isMonitoring=!1;constructor(e,t={},n,i){this.graph=e,this.config={...j,...t},this.calculator=gt(),this.eventBus=n,this.persistence=i}start(){this.isMonitoring||(this.isMonitoring=!0,this.monitoringInterval=setInterval(()=>this.checkHealth(),this.config.checkIntervalMs),this.checkHealth())}stop(){this.monitoringInterval&&(clearInterval(this.monitoringInterval),this.monitoringInterval=null),this.isMonitoring=!1}updateGraph(e){this.graph=e,this.isMonitoring&&this.checkHealth()}isEmptyTopology(){return this.graph.getVerticesByType("agent").length===0}checkHealth(){let e=this.calculator.getMinCutValue(this.graph),t=this.calculator.findWeakVertices(this.graph),n=this.isEmptyTopology()?"idle":this.determineStatus(e),i=this.calculateTrend();return this.recordHistory(e),this.isEmptyTopology()||this.checkAlertConditions(e,t,n),this.persistence&&t.length>0&&this.persistence.saveWeakVertices(t).catch(r=>console.warn("[MinCutHealthMonitor] Failed to persist weak vertices:",r)),this.emitEvent("mincut.updated",e,{status:n,weakVertexCount:t.length}),{status:n,minCutValue:e,healthyThreshold:this.config.healthyThreshold,warningThreshold:this.config.warningThreshold,weakVertexCount:t.length,topWeakVertices:t.slice(0,5),trend:i,history:this.history.slice(-20),lastUpdated:new Date}}getHealth(){let e=this.calculator.getMinCutValue(this.graph),t=this.calculator.findWeakVertices(this.graph);return{status:this.isEmptyTopology()?"idle":this.determineStatus(e),minCutValue:e,healthyThreshold:this.config.healthyThreshold,warningThreshold:this.config.warningThreshold,weakVertexCount:t.length,topWeakVertices:t.slice(0,5),trend:this.calculateTrend(),history:this.history.slice(-20),lastUpdated:new Date}}getMinCutValue(){return this.calculator.getMinCutValue(this.graph)}getWeakVertices(){return this.calculator.findWeakVertices(this.graph)}isCritical(){return this.calculator.getMinCutValue(this.graph)<this.config.warningThreshold}isHealthy(){return this.calculator.getMinCutValue(this.graph)>=this.config.healthyThreshold}getActiveAlerts(){return Array.from(this.alerts.values()).filter(e=>!e.acknowledged).sort((e,t)=>{let n={critical:0,high:1,medium:2,low:3,info:4};return n[e.severity]-n[t.severity]})}getAllAlerts(){return Array.from(this.alerts.values())}acknowledgeAlert(e){let t=this.alerts.get(e);return t?(t.acknowledged=!0,!0):!1}clearAcknowledgedAlerts(){let e=[];for(let[t,n]of this.alerts)n.acknowledged&&e.push(t);for(let t of e)this.alerts.delete(t);return e.length}getHistory(){return[...this.history]}getTrend(){return this.calculateTrend()}getStats(e=6e4){let t=Date.now()-e,n=this.history.filter(r=>r.timestamp.getTime()>t);if(n.length===0){let r=this.calculator.getMinCutValue(this.graph);return{min:r,max:r,average:r,count:0}}let i=n.map(r=>r.value);return{min:Math.min(...i),max:Math.max(...i),average:i.reduce((r,a)=>r+a,0)/i.length,count:n.length}}updateConfig(e){Object.assign(this.config,e),e.checkIntervalMs&&this.isMonitoring&&(this.stop(),this.start())}getConfig(){return{...this.config}}determineStatus(e){return e>=this.config.healthyThreshold?"healthy":e>=this.config.warningThreshold?"warning":"critical"}calculateTrend(){if(this.history.length<3)return"stable";let e=this.history.slice(-5),t=e[0].value,i=e[e.length-1].value-t,a=e.reduce((o,l)=>o+l.value,0)/e.length*.1;return i>a?"improving":i<-a?"degrading":"stable"}recordHistory(e){let t={timestamp:new Date,value:e,vertexCount:this.graph.vertexCount,edgeCount:this.graph.edgeCount};for(this.history.push(t);this.history.length>this.config.maxHistoryEntries;)this.history.shift()}checkAlertConditions(e,t,n){if(!this.config.alertsEnabled)return;let i=Date.now();n==="critical"?this.maybeGenerateAlert("critical-threshold","critical",`MinCut value (${e.toFixed(2)}) is below critical threshold (${this.config.warningThreshold})`,e,this.config.warningThreshold,t):n==="warning"&&this.maybeGenerateAlert("warning-threshold","high",`MinCut value (${e.toFixed(2)}) is below healthy threshold (${this.config.healthyThreshold})`,e,this.config.healthyThreshold,t);let r=t.filter(o=>o.weightedDegree===0);r.length>0&&this.maybeGenerateAlert("isolated-vertices","high",`${r.length} isolated vertex(es) detected`,e,0,r);let a=t.filter(o=>o.riskScore>.8);a.length>0&&this.maybeGenerateAlert("critical-vertices","medium",`${a.length} critical vertex(es) with high risk score`,e,0,a)}maybeGenerateAlert(e,t,n,i,r,a){let o=Date.now(),l=this.lastAlertTime.get(e)||0;if(o-l<this.config.alertCooldownMs)return;let c={id:f(),severity:t,message:n,minCutValue:i,threshold:r,affectedVertices:a.map(u=>u.vertexId),timestamp:new Date,acknowledged:!1,remediations:a.flatMap(u=>u.suggestions).slice(0,5)};this.alerts.set(c.id,c),this.persistence&&this.persistence.saveAlert(c).catch(u=>console.warn("[MinCutHealthMonitor] Failed to persist alert:",u)),this.lastAlertTime.set(e,o),this.emitEvent("mincut.alert.generated",i,{alert:c})}emitEvent(e,t,n){if(!this.eventBus)return;let i={id:f(),type:e,source:"coordination",timestamp:new Date,correlationId:f(),payload:{minCutValue:t,...n}};this.eventBus.publish(i).catch(r=>{console.error("Failed to publish MinCut event:",r)})}};function W(s,e,t,n){return new ve(s,e,t,n)}he();dt();var Ce=class{memory;initialized=!1;constructor(e){this.memory=e??w()}async initialize(){this.initialized||(this.memory.isInitialized()||await this.memory.initialize(),this.initialized=!0)}async saveSnapshot(e){this.ensureInitialized();let t=f();return this.memory.getDatabase().prepare(`
3
3
  INSERT INTO mincut_snapshots (
4
4
  id, timestamp, vertex_count, edge_count, total_weight,
5
5
  is_connected, component_count, vertices_json, edges_json
@@ -177,4 +177,4 @@ import{b as ye}from"./chunk-GLIFZWV2.js";import{a as ht,b as ft}from"./chunk-RWX
177
177
  `;let i=this.getRecommendations(n);if(i.length>0){t+=`**Recommendations:**
178
178
  `;for(let r of i)t+=`- ${r}
179
179
  `;t+=`
180
- `}}return t}getRecommendations(e){switch(e.loopType){case"strategic":return[...e.recommendations.forRiskAssessor,...e.recommendations.forQualityCriteria];case"tactical":return e.recommendations.forProductFactorsAssessor;case"operational":return[...e.recommendations.forTestArchitect,...e.recommendations.antiPatterns];case"quality-criteria":return e.recommendations.forRequirementsValidator;default:return[]}}filterManagedHooks(e){if(process.env.AQE_HOOKS_MANAGED_ONLY!=="true")return e;let t=e.filter(([n])=>n.startsWith("managed:"));return t.length<e.length&&console.log(`[CrossPhaseHooks] AQE_HOOKS_MANAGED_ONLY: filtered ${e.length-t.length} non-managed hooks`),t}async isBlockedUrl(e){if(!e.includes("://"))return!1;let t=await ye(e);return t.safe?!1:(console.warn(`[CrossPhaseHooks] SSRF blocked: ${t.reason}`),!0)}checkConditions(e,t){return!e||e.length===0?!0:e.every(n=>this.evaluateCondition(n,t))}evaluateCondition(e,t){try{let n=e.split(/\s*(>|<|>=|<=|==|!=)\s*/);if(n.length!==3)return!1;let[i,r,a]=n,o=this.getValueFromPath(t,i),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"&&i in n)return n[i]},e)}extractFromContext(e,t){let n={};for(let[i,r]of Object.entries(e))n[i]=this.getValueFromPath(t,r);return n}parseMaxAge(e){let t=e.match(/^(\d+)(d|h|m|s)$/);if(!t)return 0;let[,n,i]=t,r=parseInt(n,10);switch(i){case"d":return r*24*60*60*1e3;case"h":return r*60*60*1e3;case"m":return r*60*1e3;case"s":return r*1e3;default:return 0}}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t)}off(e,t){this.listeners.get(e)?.delete(t)}emit(e,t){this.listeners.get(e)?.forEach(n=>n(t))}async runCleanup(){if(!this.config?.cleanup.enabled)return;console.log("[CrossPhaseHooks] Running cleanup...");let e=await this.memory.cleanupExpired();console.log(`[CrossPhaseHooks] Cleanup complete: ${e.deleted} signals deleted`)}},Ze=null;function Kt(s){return Ze||(Ze=new Xe(s)),Ze}function Yt(s,e){let t=[];for(let a of e){let o=s.router.subscribeToDoamin(a,async l=>{await ui(s,l)});t.push(o)}let n=s.router.subscribeToEventType("TaskCompleted",async a=>{await di(s,a)});t.push(n);let i=s.router.subscribeToEventType("TaskFailed",async a=>{await gi(s,a)});t.push(i);let r=s.router.subscribeToEventType("AgentStatusChanged",async a=>{await mi(s,a)});return t.push(r),t}async function ui(s,e){s.domainLastActivity.set(e.source,new Date),await s.processQueue()}async function di(s,e){let{taskId:t,result:n}=e.payload,i=s.tasks.get(t);if(i){(i.status==="running"||i.status==="assigned")&&(s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1));let r=i.startedAt?Date.now()-i.startedAt.getTime():0;s.tasks.set(t,{...i,status:"completed",completedAt:new Date,result:n}),s.tasksCompleted++,s.taskDurations.push(r),s.auditLogger.logComplete(t,i.assignedAgents[0]);try{let a=Kt(),o=i.assignedAgents[0];o&&await a.onAgentComplete(o,{taskId:t,taskType:i.task.type,domain:i.assignedDomain,result:n,duration:r})}catch(a){console.warn("[QueenCoordinator] Cross-phase hook error:",a)}try{await I.afterTaskExecution({taskId:t,taskType:i.task.type,agentId:i.assignedAgents[0]||"unknown",domain:i.assignedDomain||"test-generation",priority:i.task.priority},!0,0,0)}catch(a){console.warn("[QueenCoordinator] Governance tracking error:",a)}if(s.domainBreakerRegistry&&i.assignedDomain&&s.domainBreakerRegistry.getBreaker(i.assignedDomain).recordSuccess(),s.traceCollector){let a=s.taskTraceContexts.get(t);a&&(s.traceCollector.completeSpan(a.spanId),s.taskTraceContexts.delete(t))}if(s.taskCompletedHook)try{let a=typeof n=="object"&&n!==null?n:null;if(a===null)console.error(`[QueenCoordinator] Pattern training skipped for task ${t}: result is not an object (got ${typeof n})`);else{let o=pi(a,t);if(o){let l={taskId:t,agentId:i.assignedAgents[0]||"unknown",domain:i.assignedDomain||"test-generation",type:i.task.type,status:"completed",output:a,metrics:o,duration:r,timestamp:Date.now()};s.taskCompletedHook.onTaskCompleted(l).catch(c=>{console.warn("[QueenCoordinator] Pattern training error:",c)})}}}catch(a){console.warn("[QueenCoordinator] Pattern training setup error:",a)}}await s.processQueue()}async function gi(s,e){let{taskId:t,error:n}=e.payload,i=s.tasks.get(t);if(i){if((i.status==="running"||i.status==="assigned")&&(s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1)),s.domainBreakerRegistry&&i.assignedDomain&&s.domainBreakerRegistry.getBreaker(i.assignedDomain).recordFailure(new Error(n||"Task failed")),s.traceCollector){let r=s.taskTraceContexts.get(t);r&&(s.traceCollector.failSpan(r.spanId,n||"Task failed"),s.taskTraceContexts.delete(t))}if(i.retryCount<s.config.taskRetryLimit){s.auditLogger.logFail(t,i.assignedAgents[0],n);let r={...i,status:"queued",retryCount:i.retryCount+1,error:n};s.tasks.set(t,r),s.enqueueTask(i.task)}else{s.tasks.set(t,{...i,status:"failed",completedAt:new Date,error:n}),s.tasksFailed++,s.auditLogger.logFail(t,i.assignedAgents[0],n);try{await I.afterTaskExecution({taskId:t,taskType:i.task.type,agentId:i.assignedAgents[0]||"unknown",domain:i.assignedDomain||"test-generation",priority:i.task.priority},!1,0,0)}catch(r){console.warn("[QueenCoordinator] Governance tracking error:",r)}if(s.hypothesisManager&&(i.task.priority==="p0"||i.task.priority==="p1"))try{let r=i.assignedDomain||"test-generation",a=s.hypothesisManager.createInvestigation(t,r,`Root cause analysis for ${i.task.type} failure: ${n}`);s.hypothesisManager.addHypothesis(a.id,`Infrastructure failure in domain '${r}' caused task ${t} to fail`,"log-analysis",`${r}-lead`),s.hypothesisManager.addHypothesis(a.id,`Logic/configuration error in task payload caused ${i.task.type} to fail: ${n}`,"code-analysis",i.assignedAgents[0]||"unknown"),console.log(`[QueenCoordinator] Competing hypotheses investigation created: ${a.id}`)}catch(r){console.warn("[QueenCoordinator] Hypothesis creation error:",r)}}}await s.processQueue()}async function mi(s,e){let{agentId:t,status:n,domain:i}=e.payload;s.domainLastActivity.set(i,new Date),(n==="completed"||n==="failed")&&await s.processQueue()}function pi(s,e){if("metrics"in s&&typeof s.metrics=="object"&&s.metrics!==null){let t=s.metrics;return{testsPassed:typeof t.testsPassed=="number"?t.testsPassed:void 0,testsFailed:typeof t.testsFailed=="number"?t.testsFailed:void 0,coverageChange:typeof t.coverageChange=="number"?t.coverageChange:void 0,securityIssues:typeof t.securityIssues=="number"?t.securityIssues:void 0,performanceMs:typeof t.performanceMs=="number"?t.performanceMs:void 0,linesChanged:typeof t.linesChanged=="number"?t.linesChanged:void 0}}return"testsPassed"in s||"testsFailed"in s?{testsPassed:typeof s.testsPassed=="number"?s.testsPassed:void 0,testsFailed:typeof s.testsFailed=="number"?s.testsFailed:void 0,coverageChange:typeof s.coverageChange=="number"?s.coverageChange:void 0,securityIssues:typeof s.securityIssues=="number"?s.securityIssues:void 0,performanceMs:typeof s.performanceMs=="number"?s.performanceMs:void 0,linesChanged:typeof s.linesChanged=="number"?s.linesChanged:void 0}:(console.error(`[QueenCoordinator] Pattern training skipped for task ${e}: result object has no recognizable metrics shape (keys: ${Object.keys(s).join(", ")})`),null)}function Zt(s,e,t){let n=s.listAgents({domain:e}),i=n.filter(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:[]}}var hi=ft();function Xt(s,e,t){let n=s.get(t.priority);n&&ht(n,t,hi);for(let i of t.targetDomains){let r=e.get(i);r&&r.push(t)}}function pe(s,e,t){let n=s.get(t.priority);if(n){let i=n.findIndex(r=>r.id===t.id);i!==-1&&n.splice(i,1)}for(let i of t.targetDomains){let r=e.get(i);if(r){let a=r.findIndex(o=>o.id===t.id);a!==-1&&r.splice(a,1)}}}function Je(s,e){let t=0;for(let n of["p0","p1","p2","p3"]){let i=s.get(n);if(i){if(n===e.priority){t+=i.findIndex(r=>r.id===e.id);break}t+=i.length}}return t}async function et(s){if(!(s.runningTaskCounter>=s.config.maxConcurrentTasks))for(let e of["p0","p1","p2","p3"]){let t=s.taskQueue.get(e);if(!t||t.length===0)continue;let n=t.shift();if(n){pe(s.taskQueue,s.domainQueues,n),s.runningTaskCounter++;try{await tt(s,n)}catch(i){throw s.runningTaskCounter--,i}if(s.runningTaskCounter>=s.config.maxConcurrentTasks)return}}}function Jt(s,e){let t=Array.from(s.values());return e&&(e.status&&(t=t.filter(n=>n.status===e.status)),e.domain&&(t=t.filter(n=>n.assignedDomain===e.domain)),e.priority&&(t=t.filter(n=>n.task.priority===e.priority)),e.type&&(t=t.filter(n=>n.task.type===e.type)),e.fromDate&&(t=t.filter(n=>n.task.createdAt>=e.fromDate)),e.toDate&&(t=t.filter(n=>n.task.createdAt<=e.toDate))),t}async function tt(s,e){let t=e.targetDomains.length>0?e.targetDomains:P[e.type]||[];if(t.length===0)return y(new Error(`No domains configured for task type: ${e.type}`));let n,i=1/0;for(let r of t){let a=s.getDomainLoad(r);s.getDomainHealth(r)?.status!=="unhealthy"&&a<i&&(i=a,n=r)}return n?nt(s,e,n):y(new Error("No healthy domain available for task"))}async function nt(s,e,t){let n;if(s.tinyDancerRouter){let l={p0:"critical",p1:"high",p2:"normal",p3:"low"},c={description:`${e.type}: ${JSON.stringify(e.payload).slice(0,200)}`,type:e.type,domain:t,priority:l[e.priority]};n=await s.tinyDancerRouter.route(c),s.config.enableMetrics&&console.log(`[Queen] TinyDancer routing: ${e.type} \u2192 tier=${n.tier}, model=${n.model}, cost=$${n.estimatedCost.toFixed(4)}`)}if(s.domainBreakerRegistry&&!s.domainBreakerRegistry.canExecuteInDomain(t))return y(new Error(`Domain '${t}' circuit breaker is open \u2014 too many recent failures`));if(s.domainTeamManager)try{if(!s.domainTeamManager.getDomainTeam(t)){let c=`${t}-lead`;s.domainTeamManager.createDomainTeam(t,c)}}catch(l){console.warn(`[Queen] Domain team setup for '${t}' failed (continuing):`,l)}let i=n?.tier||"task-worker",r=await s.requestAgentSpawn(t,i,["task-execution",e.type,...n?[`model:${n.model}`]:[]]),a=[];r.success&&a.push(r.value);let o={taskId:e.id,task:e,status:"running",assignedDomain:t,assignedAgents:a,startedAt:new Date,retryCount:0};s.tasks.set(e.id,o),s.domainLastActivity.set(t,new Date);for(let l of a)s.auditLogger.logAssign(e.id,l,t);if(await s.publishEvent("TaskAssigned",{taskId:e.id,domain:t,agentIds:a}),s.domainPlugins){let l=s.domainPlugins.get(t);if(l?.executeTask&&l.canHandleTask?.(e.type)){let c={taskId:e.id,taskType:e.type,payload:e.payload,priority:e.priority,timeout:e.timeout,correlationId:e.correlationId},u=await l.executeTask(c,d=>fi(s,d));return u.success?C(e.id):(s.tasks.set(e.id,{...o,status:"failed",error:u.error.message,completedAt:new Date}),s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),s.tasksFailed++,s.auditLogger.logFail(e.id,a[0],u.error.message),y(u.error))}if(l)try{await l.handleEvent({id:f(),type:"TaskAssigned",timestamp:new Date,source:"queen-coordinator",correlationId:e.correlationId,payload:{task:e}}),console.warn(`[Queen] Domain ${t} has no executeTask handler, using event fallback`)}catch(c){console.warn(`[Queen] Failed to invoke domain ${t} event handler:`,c)}}return C(e.id)}async function fi(s,e){let t=s.tasks.get(e.taskId);if(!t){console.warn(`[Queen] Received completion for unknown task: ${e.taskId}`);return}let n={...t,status:e.success?"completed":"failed",completedAt:new Date,result:e.data,error:e.error};if(s.tasks.set(e.taskId,n),e.success?(s.tasksCompleted++,s.taskDurations.push(e.duration),s.auditLogger.logComplete(e.taskId,t.assignedAgents[0])):(s.tasksFailed++,s.auditLogger.logFail(e.taskId,t.assignedAgents[0],e.error||"Unknown error")),s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),s.coExecutionRepo&&t.assignedAgents.length>=2)try{s.coExecutionRepo.recordSwarmCoExecution(t.assignedAgents,t.assignedDomain||"unknown",e.success,t.task.type)}catch{}for(let i of t.assignedAgents)await s.agentCoordinator.stop(i);await s.publishEvent(e.success?"TaskCompleted":"TaskFailed",{taskId:e.taskId,domain:t.assignedDomain,result:e.data,error:e.error,duration:e.duration}),await et(s)}function en(s,e){return(P[e.type]||[]).includes(s)}k();async function tn(s){let e=0,t=s.getIdleDomains(),n=s.getBusyDomains();if(t.length===0||n.length===0)return 0;n.sort((i,r)=>s.getDomainLoad(r)-s.getDomainLoad(i));for(let i of n){if(t.length===0)break;let r=s.domainQueues.get(i)||[],a=Math.min(r.length,s.config.workStealing.stealBatchSize);for(let o=0;o<a&&t.length>0;o++){let l=r.find(c=>en(t[0],c));if(l){let c=t.shift();s.removeFromQueues(l),s.auditLogger.logSteal(l.id,i,c),await s.assignTaskToDomain(l,c),e++,s.tasksStolen++,await s.publishEvent("TaskStolen",{taskId:l.id,fromDomain:i,toDomain:c})}}}return e}function it(s,e){let t=0,n=10,i;return i=setInterval(async()=>{try{await e(),t=0}catch(r){t++;let a=Math.min(1e3*Math.pow(2,t),3e4);if(console.warn(`[QueenCoordinator] Work-stealing failed (attempt ${t}), backing off ${a}ms`,p(r)),t>n){console.error(`[QueenCoordinator] Work-stealing exceeded ${n} consecutive failures, stopping interval`),clearInterval(i);return}await new Promise(o=>setTimeout(o,a))}},s.workStealing.checkInterval),i}function rt(s){return typeof s.setMinCutBridge=="function"}function nn(s,e){for(let[t,n]of s)rt(n)&&(n.setMinCutBridge(e),console.log(`[QueenCoordinator] MinCut bridge injected into ${t}`))}async function rn(s,e,t){try{let n=await s.get("queen:state");if(n)for(let[i,r]of n.tasks)r.status==="queued"&&(e.set(i,r),t(r.task))}catch(n){console.debug("[QueenCoordinator] State loading failed:",n instanceof Error?n.message:n)}}async function an(s,e){let t=Array.from(e.entries()).filter(([,n])=>n.status==="queued");await s.set("queen:state",{tasks:t},{namespace:"queen-coordinator",persist:!0})}function sn(s){return setInterval(async()=>{let e=s.getMetrics();if(await s.publishEvent("MetricsCollected",{metrics:e}),await s.memory.set(`queen:metrics:${Date.now()}`,e,{ttl:864e5,namespace:"queen-coordinator"}),s.dynamicScaler)try{let t=s.getAverageTaskDuration(),n={queueDepth:s.getQueuedTaskCount(),activeAgents:s.getActiveAgentCount(),idleAgents:s.getIdleAgentCount(),avgTaskDurationMs:t,errorRate:s.getTasksReceived()>0?s.getTasksFailed()/s.getTasksReceived():0,throughput:e.uptime>0?s.getTasksCompleted()/(e.uptime/1e3):0,timestamp:Date.now()};s.dynamicScaler.recordMetrics(n);let i=s.dynamicScaler.evaluate();i&&i.action!=="maintain"&&(console.log(`[QueenCoordinator] Dynamic scaler: ${i.action} to ${i.targetAgents} agents \u2014 ${i.reason}`),s.dynamicScaler.execute(i).catch(r=>{console.warn("[QueenCoordinator] Dynamic scaling execution error:",r)}))}catch(t){console.warn("[QueenCoordinator] Dynamic scaler metrics error:",t)}},s.config.metricsInterval)}function at(s,e,t=36e5){let n=Date.now(),i=0;for(let[a,o]of s)if(o.status==="completed"||o.status==="failed"||o.status==="cancelled"){let 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 on(s,e){return s&&s.size>0?Array.from(s.keys()):[...e]}var m=ut.create("QueenCoordinator");Wt(T);var st=class{constructor(e,t,n,i,r,a,o,l={}){this.eventBus=e;this.agentCoordinator=t;this.memory=n;this.router=i;this.protocolExecutor=r;this.workflowExecutor=a;this.domainPlugins=o;this.config={...jt,...l},this.auditLogger=Te({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 K(this.config.routing)),T.forEach(c=>{this.domainQueues.set(c,[]),this.domainLastActivity.set(c,new Date)})}config;tasks=new Map;taskQueue=new Map;domainQueues=new Map;domainLastActivity=new Map;initialized=!1;workStealingTimer=null;metricsTimer=null;cleanupTimer=null;startTime=new Date;eventSubscriptionIds=[];runningTaskCounter=0;tasksReceived=0;tasksCompleted=0;tasksFailed=0;tasksStolen=0;taskDurations=new ct(1e3);protocolsExecuted=0;workflowsExecuted=0;auditLogger;minCutBridge=null;tinyDancerRouter=null;domainBreakerRegistry=null;domainTeamManager=null;agentTeamsAdapter=null;tierSelector=null;taskCompletedHook=null;traceCollector=null;taskTraceContexts=new Map;hypothesisManager=null;federationMailbox=null;dynamicScaler=null;coExecutionRepo=null;dependencyGraph=null;availableMcpServers=[];async initialize(){if(!this.initialized){this.startTime=new Date,await this.router.initialize(),this.subscribeToEvents(),this.config.workStealing.enabled&&(this.workStealingTimer=it(this.config,()=>this.triggerWorkStealing().then(()=>{}))),this.config.enableMetrics&&(this.metricsTimer=sn(this.createMetricsContext())),this.cleanupTimer=setInterval(()=>{at(this.tasks,this.taskTraceContexts,36e5)},3e5),this.cleanupTimer.unref(),await rn(this.memory,this.tasks,e=>this.enqueueTaskInternal(e)),this.minCutBridge=vt(this.eventBus,this.agentCoordinator,{autoUpdateFromEvents:!0,persistData:!0,includeInQueenHealth:!0,sharedGraph:xe()}),await this.minCutBridge.initialize(),this.domainPlugins&&nn(this.domainPlugins,this.minCutBridge);try{await I.initialize(),m.info("Governance adapter initialized")}catch(e){m.warn("Governance initialization failed (continuing)",{error:e})}this.initializeSubsystems();try{let{join:e}=await import("path"),t=e(process.cwd(),".claude","agents","v3");this.dependencyGraph=Ft(t),this.availableMcpServers=yt(process.cwd());let{getUnifiedMemory:n}=await import("./unified-memory-YPHONR2T.js"),i=n();await i.initialize(),this.coExecutionRepo=Pt(),this.coExecutionRepo.initialize(i.getDatabase()),this.dependencyGraph.warnings.length>0&&m.warn(`Dependency graph: ${this.dependencyGraph.warnings.length} warning(s)`,{warnings:this.dependencyGraph.warnings.slice(0,5)}),m.info("Dependency intelligence initialized",{agents:this.dependencyGraph.nodes.size,mcpServers:this.availableMcpServers.length})}catch(e){m.warn("Dependency intelligence initialization failed (continuing)",{error:e})}await this.publishEvent("QueenInitialized",{timestamp:new Date,config:this.config,domains:T}),this.initialized=!0}}async dispose(){this.workStealingTimer&&(clearInterval(this.workStealingTimer),this.workStealingTimer=null),this.metricsTimer&&(clearInterval(this.metricsTimer),this.metricsTimer=null),this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null),this.minCutBridge&&(await this.minCutBridge.dispose(),this.minCutBridge=null),this.domainTeamManager&&(this.domainTeamManager.dispose(),this.domainTeamManager=null),this.agentTeamsAdapter&&(this.agentTeamsAdapter.shutdown(),this.agentTeamsAdapter=null),this.domainBreakerRegistry=null,this.tierSelector=null,this.traceCollector&&(this.traceCollector.dispose(),this.traceCollector=null),this.hypothesisManager&&(this.hypothesisManager.dispose(),this.hypothesisManager=null),this.federationMailbox&&(this.federationMailbox.dispose(),this.federationMailbox=null),this.dynamicScaler&&(this.dynamicScaler.dispose(),this.dynamicScaler=null),await an(this.memory,this.tasks);for(let[e,t]of this.tasks)(t.status==="queued"||t.status==="running")&&await this.cancelTask(e);await this.publishEvent("QueenShutdown",{timestamp:new Date,metrics:this.getMetrics()});for(let e of this.eventSubscriptionIds)this.router.unsubscribe(e);this.eventSubscriptionIds=[],await this.router.dispose(),this.initialized=!1}async submitTask(e){if(!this.initialized)return y(new Error("Queen Coordinator not initialized"));let t=`task_${f()}`,n={...e,id:t,createdAt:new Date,timeout:e.timeout||this.config.defaultTaskTimeout},i={taskId:n.id,taskType:n.type,agentId:n.requester||"unknown",domain:n.targetDomains[0]||"test-generation",priority:n.priority,payload:n.payload};try{let r=await I.beforeTaskExecution(i);if(!r.allowed)return this.auditLogger.logFail(t,"governance",r.reason||"Governance check failed"),await this.publishEvent("TaskRejected",{taskId:t,reason:r.reason,escalate:r.escalate}),y(new Error(`Task blocked by governance: ${r.reason}`))}catch(r){m.warn("Governance check error (continuing)",{error:r})}this.runningTaskCounter++;try{if(this.runningTaskCounter>this.config.maxConcurrentTasks)return this.runningTaskCounter--,this.queueTask(n);this.auditLogger.logSubmit(t,{type:n.type,priority:n.priority}),this.selectFleetTier(n),this.startTaskTrace(n,t);let r=await tt(this.createTaskContext(),n);return r.success?(this.tasksReceived++,await this.publishEvent("TaskSubmitted",{taskId:t,task:n}),C(t)):(this.runningTaskCounter--,r)}catch(r){throw this.runningTaskCounter--,r}}async cancelTask(e){let t=this.tasks.get(e);if(!t)return y(new Error(`Task not found: ${e}`));if(t.status==="completed"||t.status==="failed")return y(new Error(`Task already finished: ${e}`));(t.status==="running"||t.status==="assigned")&&(this.runningTaskCounter=Math.max(0,this.runningTaskCounter-1)),this.tasks.set(e,{...t,status:"cancelled",completedAt:new Date}),pe(this.taskQueue,this.domainQueues,t.task);for(let n of t.assignedAgents)await this.agentCoordinator.stop(n);return this.auditLogger.logCancel(e),await this.publishEvent("TaskCancelled",{taskId:e}),C(void 0)}getTaskStatus(e){return this.tasks.get(e)}listTasks(e){return Jt(this.tasks,e)}getDomainHealth(e){if(this.domainPlugins){let t=this.domainPlugins.get(e);if(t)return t.getHealth()}return Zt(this.agentCoordinator,e,this.domainLastActivity.get(e))}getDomainLoad(e){let t=this.domainQueues.get(e)||[],n=Array.from(this.tasks.values()).filter(i=>i.assignedDomain===e&&i.status==="running");return t.length+n.length}getIdleDomains(){let e=Date.now(),t=this.config.workStealing.idleThreshold;return T.filter(n=>{let i=this.domainLastActivity.get(n);return this.getDomainLoad(n)===0&&i&&e-i.getTime()>t})}getBusyDomains(){return T.filter(e=>this.getDomainLoad(e)>this.config.workStealing.loadThreshold)}getSpawnPlan(e){return this.dependencyGraph?Ot(e,this.dependencyGraph):{phases:[e],warnings:[],unsatisfiedHardDeps:[]}}getDependencyGraph(){return this.dependencyGraph}enableWorkStealing(){this.workStealingTimer||(this.workStealingTimer=it(this.config,()=>this.triggerWorkStealing().then(()=>{})))}disableWorkStealing(){this.workStealingTimer&&(clearInterval(this.workStealingTimer),this.workStealingTimer=null)}async triggerWorkStealing(){return tn(this.createWorkStealingContext())}listAllAgents(){return this.agentCoordinator.listAgents()}getAgentsByDomain(e){return this.agentCoordinator.listAgents({domain:e})}async requestAgentSpawn(e,t,n){if(!this.agentCoordinator.canSpawn())return y(new Error("Maximum concurrent agents reached (15)"));if(this.dependencyGraph&&this.availableMcpServers.length>0)try{for(let[,r]of this.dependencyGraph.nodes){let a=r.dependencies.mcpServers;if(!a||a.length===0)continue;let o=a.filter(l=>l.required&&!this.availableMcpServers.includes(l.name));if(o.length>0){m.warn(`Pre-spawn MCP advisory: ${r.agentName} needs ${o.map(l=>l.name).join(", ")}`,{agent:r.agentName,domain:e,missing:o.map(l=>l.name)});break}}}catch{}let i=await this.agentCoordinator.spawn({name:`${e}-${t}-${Date.now()}`,domain:e,type:t,capabilities:n});if(i.success){if(this.domainLastActivity.set(e,new Date),this.domainTeamManager&&typeof this.domainTeamManager.getDomainTeam=="function")try{if(this.domainTeamManager.getDomainTeam(e))this.domainTeamManager.addTeammate(e,i.value)||m.warn(`Agent ${i.value} could not join ${e} team (full)`);else try{this.domainTeamManager.createDomainTeam(e,i.value)}catch{this.domainTeamManager.addTeammate(e,i.value)||m.warn(`Agent ${i.value} could not join ${e} team (full or max teams reached)`)}}catch(r){m.warn(`Auto-team-wiring failed for ${i.value}`,{error:r})}await this.publishEvent("AgentSpawned",{agentId:i.value,domain:e,type:t,capabilities:n})}return i}getHealth(){let e=new Map,t=[],n=0,i=0,r=on(this.domainPlugins,T);for(let u of r){let d=this.getDomainHealth(u);d&&(e.set(u,d),d.status==="unhealthy"?(n++,t.push({domain:u,severity:"high",message:`Domain ${u} is unhealthy`,timestamp:new Date})):d.status==="degraded"&&(i++,t.push({domain:u,severity:"medium",message:`Domain ${u} is degraded`,timestamp:new Date})))}let a=this.agentCoordinator.listAgents(),o=a.filter(u=>u.status==="running").length,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,t=0;for(let l of T){let c=this.getDomainLoad(l);e.set(l,c),t+=c}let n=this.agentCoordinator.listAgents(),i=n.filter(l=>l.status==="running").length,r=n.length>0?i/n.length:0,a=this.taskDurations.average(),o={tasksReceived:this.tasksReceived,tasksCompleted:this.tasksCompleted,tasksFailed:this.tasksFailed,tasksStolen:this.tasksStolen,averageTaskDuration:a,domainUtilization:e,agentUtilization:r,protocolsExecuted:this.protocolsExecuted,workflowsExecuted:this.workflowsExecuted,uptime:Date.now()-this.startTime.getTime()};return this.minCutBridge?this.minCutBridge.extendQueenMetrics(o):o}getMinCutBridge(){return this.minCutBridge}injectMinCutBridgeIntoDomain(e){if(!this.minCutBridge)return m.warn("Cannot inject MinCut bridge: bridge not initialized"),!1;if(!this.domainPlugins)return m.warn("Cannot inject MinCut bridge: no domain plugins registered"),!1;let t=this.domainPlugins.get(e);return t?rt(t)?(t.setMinCutBridge(this.minCutBridge),m.info(`MinCut bridge injected into ${e} (late binding)`),!0):(m.warn(`Domain ${e} does not support MinCut integration`),!1):(m.warn(`Cannot inject MinCut bridge: domain ${e} not found`),!1)}getTinyDancerRouter(){return this.tinyDancerRouter}getDomainBreakerRegistry(){return this.domainBreakerRegistry}getDomainTeamManager(){return this.domainTeamManager}getAgentTeamsAdapter(){return this.agentTeamsAdapter}getTierSelector(){return this.tierSelector}getTraceCollector(){return this.traceCollector}getHypothesisManager(){return this.hypothesisManager}getFederationMailbox(){return this.federationMailbox}getDynamicScaler(){return this.dynamicScaler}connectReasoningBank(e){let t=new ce(e);this.taskCompletedHook=new le({},t),m.info("ReasoningBank connected for pattern training")}async executeProtocol(e,t){if(!this.protocolExecutor)return y(new Error("Protocol executor not configured"));let n=await this.protocolExecutor.execute(e,t);return n.success?(this.protocolsExecuted++,await this.publishEvent("ProtocolExecuted",{protocolId:e,executionId:n.value.executionId}),C(n.value.executionId)):n}async executeWorkflow(e,t){if(!this.workflowExecutor)return y(new Error("Workflow executor not configured"));let n=await this.workflowExecutor.execute(e,t);return n.success?(this.workflowsExecuted++,await this.publishEvent("WorkflowExecuted",{workflowId:e,executionId:n.value.executionId}),C(n.value.executionId)):n}cleanupCompletedTasks(e=36e5){return at(this.tasks,this.taskTraceContexts,e)}subscribeToEvents(){this.eventSubscriptionIds=Yt(this.createEventHandlerContext(),T)}enqueueTaskInternal(e){Xt(this.taskQueue,this.domainQueues,e)}async publishEvent(e,t){await this.eventBus.publish({id:f(),type:`Queen${e}`,timestamp:new Date,source:"queen-coordinator",payload:t})}queueTask(e){this.enqueueTaskInternal(e);let t={taskId:e.id,task:e,status:"queued",assignedAgents:[],retryCount:0};return this.tasks.set(e.id,t),this.tasksReceived++,this.auditLogger.logSubmit(e.id,{type:e.type,priority:e.priority}),this.auditLogger.logQueue(e.id,Je(this.taskQueue,e)),this.publishEvent("TaskQueued",{taskId:e.id,task:e,position:Je(this.taskQueue,e)}),C(e.id)}selectFleetTier(e){if(this.tierSelector)try{let t={trigger:e.payload?.trigger??"manual",changedFiles:e.payload?.changedFiles,affectedDomains:e.targetDomains,severity:e.priority==="p0"?"critical":e.priority==="p1"?"high":void 0,isHotfix:e.payload?.isHotfix},n=this.tierSelector.selectTier(t);return m.info(`Fleet tier: ${n.selectedTier} (${n.reason})`),n.selectedTier}catch(t){m.warn("Tier selection error (continuing)",{error:t});return}}startTaskTrace(e,t){if(this.traceCollector)try{let{context:n}=this.traceCollector.startTrace({operationName:e.type,agentId:e.requester||"queen",domain:e.targetDomains[0]||"test-generation",tags:{taskId:t,priority:e.priority}});if(this.taskTraceContexts.size>=1e4){let r=this.taskTraceContexts.keys().next().value;r!==void 0&&this.taskTraceContexts.delete(r)}this.taskTraceContexts.set(t,n)}catch(n){m.warn("Trace start error (continuing)",{error:n})}}getRunningTaskCount(){return Array.from(this.tasks.values()).filter(e=>e.status==="running"||e.status==="assigned").length}getQueuedTaskCount(){return Array.from(this.tasks.values()).filter(e=>e.status==="queued").length}initializeSubsystems(){if(this.config.enableCircuitBreakers!==!1)try{this.domainBreakerRegistry=Qt(),m.info("Domain circuit breaker registry initialized")}catch(e){m.warn("Circuit breaker initialization failed (continuing)",{error:e})}if(this.config.enableDomainTeams!==!1)try{this.agentTeamsAdapter=Pe(),this.agentTeamsAdapter.initialize(),this.domainTeamManager=He(this.agentTeamsAdapter),m.info("Domain team manager initialized")}catch(e){m.warn("Domain team manager initialization failed (continuing)",{error:e})}if(this.config.enableFleetTiers!==!1)try{this.tierSelector=Le(),m.info("Fleet tier selector initialized")}catch(e){m.warn("Tier selector initialization failed (continuing)",{error:e})}try{this.traceCollector=_e(),m.info("Trace collector initialized")}catch(e){m.warn("Trace collector initialization failed (continuing)",{error:e})}try{this.hypothesisManager=$e(),this.federationMailbox=Ge(),this.dynamicScaler=qe(),m.info("Phase 4 modules initialized (hypotheses, federation, scaling)")}catch(e){m.warn("Phase 4 initialization failed (continuing)",{error:e})}}createEventHandlerContext(){let e=this;return{config:e.config,tasks:e.tasks,domainLastActivity:e.domainLastActivity,auditLogger:e.auditLogger,router:e.router,agentCoordinator:e.agentCoordinator,get runningTaskCounter(){return e.runningTaskCounter},set runningTaskCounter(t){e.runningTaskCounter=t},get tasksCompleted(){return e.tasksCompleted},set tasksCompleted(t){e.tasksCompleted=t},get tasksFailed(){return e.tasksFailed},set tasksFailed(t){e.tasksFailed=t},taskDurations:e.taskDurations,get domainBreakerRegistry(){return e.domainBreakerRegistry},get traceCollector(){return e.traceCollector},taskTraceContexts:e.taskTraceContexts,get taskCompletedHook(){return e.taskCompletedHook},get hypothesisManager(){return e.hypothesisManager},processQueue:()=>et(e.createTaskContext()),enqueueTask:t=>e.enqueueTaskInternal(t)}}createTaskContext(){let e=this;return{config:e.config,tasks:e.tasks,taskQueue:e.taskQueue,domainQueues:e.domainQueues,domainLastActivity:e.domainLastActivity,auditLogger:e.auditLogger,agentCoordinator:e.agentCoordinator,domainPlugins:e.domainPlugins,get runningTaskCounter(){return e.runningTaskCounter},set runningTaskCounter(t){e.runningTaskCounter=t},get tasksReceived(){return e.tasksReceived},set tasksReceived(t){e.tasksReceived=t},get tasksCompleted(){return e.tasksCompleted},set tasksCompleted(t){e.tasksCompleted=t},get tasksFailed(){return e.tasksFailed},set tasksFailed(t){e.tasksFailed=t},taskDurations:e.taskDurations,get tinyDancerRouter(){return e.tinyDancerRouter},get domainBreakerRegistry(){return e.domainBreakerRegistry},get domainTeamManager(){return e.domainTeamManager},get tierSelector(){return e.tierSelector},get traceCollector(){return e.traceCollector},taskTraceContexts:e.taskTraceContexts,get coExecutionRepo(){return e.coExecutionRepo},requestAgentSpawn:(t,n,i)=>e.requestAgentSpawn(t,n,i),publishEvent:(t,n)=>e.publishEvent(t,n),getDomainLoad:t=>e.getDomainLoad(t),getDomainHealth:t=>e.getDomainHealth(t)}}createWorkStealingContext(){let e=this;return{config:e.config,domainQueues:e.domainQueues,auditLogger:e.auditLogger,get tasksStolen(){return e.tasksStolen},set tasksStolen(t){e.tasksStolen=t},getIdleDomains:()=>e.getIdleDomains(),getBusyDomains:()=>e.getBusyDomains(),getDomainLoad:t=>e.getDomainLoad(t),removeFromQueues:t=>pe(e.taskQueue,e.domainQueues,t),assignTaskToDomain:(t,n)=>nt(e.createTaskContext(),t,n).then(()=>{}),publishEvent:(t,n)=>e.publishEvent(t,n)}}createMetricsContext(){let e=this;return{config:e.config,memory:e.memory,get dynamicScaler(){return e.dynamicScaler},getMetrics:()=>e.getMetrics(),publishEvent:(t,n)=>e.publishEvent(t,n),getQueuedTaskCount:()=>e.getQueuedTaskCount(),getActiveAgentCount:()=>e.agentCoordinator.listAgents().filter(t=>t.status==="running").length,getIdleAgentCount:()=>e.agentCoordinator.listAgents().filter(t=>t.status==="idle").length,getAverageTaskDuration:()=>e.taskDurations.average(),getTasksReceived:()=>e.tasksReceived,getTasksFailed:()=>e.tasksFailed,getTasksCompleted:()=>e.tasksCompleted}}};function Lo(s,e,t,n,i,r){return new st(s.eventBus,s.coordinator,s.memory,e,t,n,i,r)}export{xe as a,or as b,ri as c,P as d,st as e,Lo as f};
180
+ `}}return t}getRecommendations(e){switch(e.loopType){case"strategic":return[...e.recommendations.forRiskAssessor,...e.recommendations.forQualityCriteria];case"tactical":return e.recommendations.forProductFactorsAssessor;case"operational":return[...e.recommendations.forTestArchitect,...e.recommendations.antiPatterns];case"quality-criteria":return e.recommendations.forRequirementsValidator;default:return[]}}filterManagedHooks(e){if(process.env.AQE_HOOKS_MANAGED_ONLY!=="true")return e;let t=e.filter(([n])=>n.startsWith("managed:"));return t.length<e.length&&console.log(`[CrossPhaseHooks] AQE_HOOKS_MANAGED_ONLY: filtered ${e.length-t.length} non-managed hooks`),t}async isBlockedUrl(e){if(!e.includes("://"))return!1;let t=await ye(e);return t.safe?!1:(console.warn(`[CrossPhaseHooks] SSRF blocked: ${t.reason}`),!0)}checkConditions(e,t){return!e||e.length===0?!0:e.every(n=>this.evaluateCondition(n,t))}evaluateCondition(e,t){try{let n=e.split(/\s*(>|<|>=|<=|==|!=)\s*/);if(n.length!==3)return!1;let[i,r,a]=n,o=this.getValueFromPath(t,i),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"&&i in n)return n[i]},e)}extractFromContext(e,t){let n={};for(let[i,r]of Object.entries(e))n[i]=this.getValueFromPath(t,r);return n}parseMaxAge(e){let t=e.match(/^(\d+)(d|h|m|s)$/);if(!t)return 0;let[,n,i]=t,r=parseInt(n,10);switch(i){case"d":return r*24*60*60*1e3;case"h":return r*60*60*1e3;case"m":return r*60*1e3;case"s":return r*1e3;default:return 0}}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t)}off(e,t){this.listeners.get(e)?.delete(t)}emit(e,t){this.listeners.get(e)?.forEach(n=>n(t))}async runCleanup(){if(!this.config?.cleanup.enabled)return;console.log("[CrossPhaseHooks] Running cleanup...");let e=await this.memory.cleanupExpired();console.log(`[CrossPhaseHooks] Cleanup complete: ${e.deleted} signals deleted`)}},Ze=null;function Kt(s){return Ze||(Ze=new Xe(s)),Ze}function Yt(s,e){let t=[];for(let a of e){let o=s.router.subscribeToDoamin(a,async l=>{await ui(s,l)});t.push(o)}let n=s.router.subscribeToEventType("TaskCompleted",async a=>{await di(s,a)});t.push(n);let i=s.router.subscribeToEventType("TaskFailed",async a=>{await gi(s,a)});t.push(i);let r=s.router.subscribeToEventType("AgentStatusChanged",async a=>{await mi(s,a)});return t.push(r),t}async function ui(s,e){s.domainLastActivity.set(e.source,new Date),await s.processQueue()}async function di(s,e){let{taskId:t,result:n}=e.payload,i=s.tasks.get(t);if(i){(i.status==="running"||i.status==="assigned")&&(s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1));let r=i.startedAt?Date.now()-i.startedAt.getTime():0;s.tasks.set(t,{...i,status:"completed",completedAt:new Date,result:n}),s.tasksCompleted++,s.taskDurations.push(r),s.auditLogger.logComplete(t,i.assignedAgents[0]);try{let a=Kt(),o=i.assignedAgents[0];o&&await a.onAgentComplete(o,{taskId:t,taskType:i.task.type,domain:i.assignedDomain,result:n,duration:r})}catch(a){console.warn("[QueenCoordinator] Cross-phase hook error:",a)}try{await I.afterTaskExecution({taskId:t,taskType:i.task.type,agentId:i.assignedAgents[0]||"unknown",domain:i.assignedDomain||"test-generation",priority:i.task.priority},!0,0,0)}catch(a){console.warn("[QueenCoordinator] Governance tracking error:",a)}if(s.domainBreakerRegistry&&i.assignedDomain&&s.domainBreakerRegistry.getBreaker(i.assignedDomain).recordSuccess(),s.traceCollector){let a=s.taskTraceContexts.get(t);a&&(s.traceCollector.completeSpan(a.spanId),s.taskTraceContexts.delete(t))}if(s.taskCompletedHook)try{let a=typeof n=="object"&&n!==null?n:null;if(a===null)console.error(`[QueenCoordinator] Pattern training skipped for task ${t}: result is not an object (got ${typeof n})`);else{let o=pi(a,t);if(o){let l={taskId:t,agentId:i.assignedAgents[0]||"unknown",domain:i.assignedDomain||"test-generation",type:i.task.type,status:"completed",output:a,metrics:o,duration:r,timestamp:Date.now()};s.taskCompletedHook.onTaskCompleted(l).catch(c=>{console.warn("[QueenCoordinator] Pattern training error:",c)})}}}catch(a){console.warn("[QueenCoordinator] Pattern training setup error:",a)}}await s.processQueue()}async function gi(s,e){let{taskId:t,error:n}=e.payload,i=s.tasks.get(t);if(i){if((i.status==="running"||i.status==="assigned")&&(s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1)),s.domainBreakerRegistry&&i.assignedDomain&&s.domainBreakerRegistry.getBreaker(i.assignedDomain).recordFailure(new Error(n||"Task failed")),s.traceCollector){let r=s.taskTraceContexts.get(t);r&&(s.traceCollector.failSpan(r.spanId,n||"Task failed"),s.taskTraceContexts.delete(t))}if(i.retryCount<s.config.taskRetryLimit){s.auditLogger.logFail(t,i.assignedAgents[0],n);let r={...i,status:"queued",retryCount:i.retryCount+1,error:n};s.tasks.set(t,r),s.enqueueTask(i.task)}else{s.tasks.set(t,{...i,status:"failed",completedAt:new Date,error:n}),s.tasksFailed++,s.auditLogger.logFail(t,i.assignedAgents[0],n);try{await I.afterTaskExecution({taskId:t,taskType:i.task.type,agentId:i.assignedAgents[0]||"unknown",domain:i.assignedDomain||"test-generation",priority:i.task.priority},!1,0,0)}catch(r){console.warn("[QueenCoordinator] Governance tracking error:",r)}if(s.hypothesisManager&&(i.task.priority==="p0"||i.task.priority==="p1"))try{let r=i.assignedDomain||"test-generation",a=s.hypothesisManager.createInvestigation(t,r,`Root cause analysis for ${i.task.type} failure: ${n}`);s.hypothesisManager.addHypothesis(a.id,`Infrastructure failure in domain '${r}' caused task ${t} to fail`,"log-analysis",`${r}-lead`),s.hypothesisManager.addHypothesis(a.id,`Logic/configuration error in task payload caused ${i.task.type} to fail: ${n}`,"code-analysis",i.assignedAgents[0]||"unknown"),console.log(`[QueenCoordinator] Competing hypotheses investigation created: ${a.id}`)}catch(r){console.warn("[QueenCoordinator] Hypothesis creation error:",r)}}}await s.processQueue()}async function mi(s,e){let{agentId:t,status:n,domain:i}=e.payload;s.domainLastActivity.set(i,new Date),(n==="completed"||n==="failed")&&await s.processQueue()}function pi(s,e){if("metrics"in s&&typeof s.metrics=="object"&&s.metrics!==null){let t=s.metrics;return{testsPassed:typeof t.testsPassed=="number"?t.testsPassed:void 0,testsFailed:typeof t.testsFailed=="number"?t.testsFailed:void 0,coverageChange:typeof t.coverageChange=="number"?t.coverageChange:void 0,securityIssues:typeof t.securityIssues=="number"?t.securityIssues:void 0,performanceMs:typeof t.performanceMs=="number"?t.performanceMs:void 0,linesChanged:typeof t.linesChanged=="number"?t.linesChanged:void 0}}return"testsPassed"in s||"testsFailed"in s?{testsPassed:typeof s.testsPassed=="number"?s.testsPassed:void 0,testsFailed:typeof s.testsFailed=="number"?s.testsFailed:void 0,coverageChange:typeof s.coverageChange=="number"?s.coverageChange:void 0,securityIssues:typeof s.securityIssues=="number"?s.securityIssues:void 0,performanceMs:typeof s.performanceMs=="number"?s.performanceMs:void 0,linesChanged:typeof s.linesChanged=="number"?s.linesChanged:void 0}:(console.error(`[QueenCoordinator] Pattern training skipped for task ${e}: result object has no recognizable metrics shape (keys: ${Object.keys(s).join(", ")})`),null)}function Zt(s,e,t){let n=s.listAgents({domain:e}),i=n.filter(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:[]}}var hi=ft();function Xt(s,e,t){let n=s.get(t.priority);n&&ht(n,t,hi);for(let i of t.targetDomains){let r=e.get(i);r&&r.push(t)}}function pe(s,e,t){let n=s.get(t.priority);if(n){let i=n.findIndex(r=>r.id===t.id);i!==-1&&n.splice(i,1)}for(let i of t.targetDomains){let r=e.get(i);if(r){let a=r.findIndex(o=>o.id===t.id);a!==-1&&r.splice(a,1)}}}function Je(s,e){let t=0;for(let n of["p0","p1","p2","p3"]){let i=s.get(n);if(i){if(n===e.priority){t+=i.findIndex(r=>r.id===e.id);break}t+=i.length}}return t}async function et(s){if(!(s.runningTaskCounter>=s.config.maxConcurrentTasks))for(let e of["p0","p1","p2","p3"]){let t=s.taskQueue.get(e);if(!t||t.length===0)continue;let n=t.shift();if(n){pe(s.taskQueue,s.domainQueues,n),s.runningTaskCounter++;try{await tt(s,n)}catch(i){throw s.runningTaskCounter--,i}if(s.runningTaskCounter>=s.config.maxConcurrentTasks)return}}}function Jt(s,e){let t=Array.from(s.values());return e&&(e.status&&(t=t.filter(n=>n.status===e.status)),e.domain&&(t=t.filter(n=>n.assignedDomain===e.domain)),e.priority&&(t=t.filter(n=>n.task.priority===e.priority)),e.type&&(t=t.filter(n=>n.task.type===e.type)),e.fromDate&&(t=t.filter(n=>n.task.createdAt>=e.fromDate)),e.toDate&&(t=t.filter(n=>n.task.createdAt<=e.toDate))),t}async function tt(s,e){let t=e.targetDomains.length>0?e.targetDomains:P[e.type]||[];if(t.length===0)return y(new Error(`No domains configured for task type: ${e.type}`));let n,i=1/0;for(let r of t){let a=s.getDomainLoad(r);s.getDomainHealth(r)?.status!=="unhealthy"&&a<i&&(i=a,n=r)}return n?nt(s,e,n):y(new Error("No healthy domain available for task"))}async function nt(s,e,t){let n;if(s.tinyDancerRouter){let l={p0:"critical",p1:"high",p2:"normal",p3:"low"},c={description:`${e.type}: ${JSON.stringify(e.payload).slice(0,200)}`,type:e.type,domain:t,priority:l[e.priority]};n=await s.tinyDancerRouter.route(c),s.config.enableMetrics&&console.log(`[Queen] TinyDancer routing: ${e.type} \u2192 tier=${n.tier}, model=${n.model}, cost=$${n.estimatedCost.toFixed(4)}`)}if(s.domainBreakerRegistry&&!s.domainBreakerRegistry.canExecuteInDomain(t))return y(new Error(`Domain '${t}' circuit breaker is open \u2014 too many recent failures`));if(s.domainTeamManager)try{if(!s.domainTeamManager.getDomainTeam(t)){let c=`${t}-lead`;s.domainTeamManager.createDomainTeam(t,c)}}catch(l){console.warn(`[Queen] Domain team setup for '${t}' failed (continuing):`,l)}let i=n?.tier||"task-worker",r=await s.requestAgentSpawn(t,i,["task-execution",e.type,...n?[`model:${n.model}`]:[]]),a=[];r.success&&a.push(r.value);let o={taskId:e.id,task:e,status:"running",assignedDomain:t,assignedAgents:a,startedAt:new Date,retryCount:0};s.tasks.set(e.id,o),s.domainLastActivity.set(t,new Date);for(let l of a)s.auditLogger.logAssign(e.id,l,t);if(await s.publishEvent("TaskAssigned",{taskId:e.id,domain:t,agentIds:a}),s.domainPlugins){let l=s.domainPlugins.get(t);if(l?.executeTask&&l.canHandleTask?.(e.type)){let c={taskId:e.id,taskType:e.type,payload:e.payload,priority:e.priority,timeout:e.timeout,correlationId:e.correlationId},u=await l.executeTask(c,d=>fi(s,d));return u.success?C(e.id):(s.tasks.set(e.id,{...o,status:"failed",error:u.error.message,completedAt:new Date}),s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),s.tasksFailed++,s.auditLogger.logFail(e.id,a[0],u.error.message),y(u.error))}if(l)try{await l.handleEvent({id:f(),type:"TaskAssigned",timestamp:new Date,source:"queen-coordinator",correlationId:e.correlationId,payload:{task:e}}),console.warn(`[Queen] Domain ${t} has no executeTask handler, using event fallback`)}catch(c){console.warn(`[Queen] Failed to invoke domain ${t} event handler:`,c)}}return C(e.id)}async function fi(s,e){let t=s.tasks.get(e.taskId);if(!t){console.warn(`[Queen] Received completion for unknown task: ${e.taskId}`);return}let n={...t,status:e.success?"completed":"failed",completedAt:new Date,result:e.data,error:e.error};if(s.tasks.set(e.taskId,n),e.success?(s.tasksCompleted++,s.taskDurations.push(e.duration),s.auditLogger.logComplete(e.taskId,t.assignedAgents[0])):(s.tasksFailed++,s.auditLogger.logFail(e.taskId,t.assignedAgents[0],e.error||"Unknown error")),s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),s.coExecutionRepo&&t.assignedAgents.length>=2)try{s.coExecutionRepo.recordSwarmCoExecution(t.assignedAgents,t.assignedDomain||"unknown",e.success,t.task.type)}catch{}for(let i of t.assignedAgents)await s.agentCoordinator.stop(i);await s.publishEvent(e.success?"TaskCompleted":"TaskFailed",{taskId:e.taskId,domain:t.assignedDomain,result:e.data,error:e.error,duration:e.duration}),await et(s)}function en(s,e){return(P[e.type]||[]).includes(s)}k();async function tn(s){let e=0,t=s.getIdleDomains(),n=s.getBusyDomains();if(t.length===0||n.length===0)return 0;n.sort((i,r)=>s.getDomainLoad(r)-s.getDomainLoad(i));for(let i of n){if(t.length===0)break;let r=s.domainQueues.get(i)||[],a=Math.min(r.length,s.config.workStealing.stealBatchSize);for(let o=0;o<a&&t.length>0;o++){let l=r.find(c=>en(t[0],c));if(l){let c=t.shift();s.removeFromQueues(l),s.auditLogger.logSteal(l.id,i,c),await s.assignTaskToDomain(l,c),e++,s.tasksStolen++,await s.publishEvent("TaskStolen",{taskId:l.id,fromDomain:i,toDomain:c})}}}return e}function it(s,e){let t=0,n=10,i;return i=setInterval(async()=>{try{await e(),t=0}catch(r){t++;let a=Math.min(1e3*Math.pow(2,t),3e4);if(console.warn(`[QueenCoordinator] Work-stealing failed (attempt ${t}), backing off ${a}ms`,p(r)),t>n){console.error(`[QueenCoordinator] Work-stealing exceeded ${n} consecutive failures, stopping interval`),clearInterval(i);return}await new Promise(o=>setTimeout(o,a))}},s.workStealing.checkInterval),i}function rt(s){return typeof s.setMinCutBridge=="function"}function nn(s,e){for(let[t,n]of s)rt(n)&&(n.setMinCutBridge(e),console.log(`[QueenCoordinator] MinCut bridge injected into ${t}`))}async function rn(s,e,t){try{let n=await s.get("queen:state");if(n)for(let[i,r]of n.tasks)r.status==="queued"&&(e.set(i,r),t(r.task))}catch(n){console.debug("[QueenCoordinator] State loading failed:",n instanceof Error?n.message:n)}}async function an(s,e){let t=Array.from(e.entries()).filter(([,n])=>n.status==="queued");await s.set("queen:state",{tasks:t},{namespace:"queen-coordinator",persist:!0})}function sn(s){return setInterval(async()=>{let e=s.getMetrics();if(await s.publishEvent("MetricsCollected",{metrics:e}),await s.memory.set(`queen:metrics:${Date.now()}`,e,{ttl:864e5,namespace:"queen-coordinator"}),s.dynamicScaler)try{let t=s.getAverageTaskDuration(),n={queueDepth:s.getQueuedTaskCount(),activeAgents:s.getActiveAgentCount(),idleAgents:s.getIdleAgentCount(),avgTaskDurationMs:t,errorRate:s.getTasksReceived()>0?s.getTasksFailed()/s.getTasksReceived():0,throughput:e.uptime>0?s.getTasksCompleted()/(e.uptime/1e3):0,timestamp:Date.now()};s.dynamicScaler.recordMetrics(n);let i=s.dynamicScaler.evaluate();i&&i.action!=="maintain"&&(console.log(`[QueenCoordinator] Dynamic scaler: ${i.action} to ${i.targetAgents} agents \u2014 ${i.reason}`),s.dynamicScaler.execute(i).catch(r=>{console.warn("[QueenCoordinator] Dynamic scaling execution error:",r)}))}catch(t){console.warn("[QueenCoordinator] Dynamic scaler metrics error:",t)}},s.config.metricsInterval)}function at(s,e,t=36e5){let n=Date.now(),i=0;for(let[a,o]of s)if(o.status==="completed"||o.status==="failed"||o.status==="cancelled"){let 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 on(s,e){return s&&s.size>0?Array.from(s.keys()):[...e]}var m=ut.create("QueenCoordinator");Wt(T);var st=class{constructor(e,t,n,i,r,a,o,l={}){this.eventBus=e;this.agentCoordinator=t;this.memory=n;this.router=i;this.protocolExecutor=r;this.workflowExecutor=a;this.domainPlugins=o;this.config={...jt,...l},this.auditLogger=Te({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 K(this.config.routing)),T.forEach(c=>{this.domainQueues.set(c,[]),this.domainLastActivity.set(c,new Date)})}config;tasks=new Map;taskQueue=new Map;domainQueues=new Map;domainLastActivity=new Map;initialized=!1;workStealingTimer=null;metricsTimer=null;cleanupTimer=null;startTime=new Date;eventSubscriptionIds=[];runningTaskCounter=0;tasksReceived=0;tasksCompleted=0;tasksFailed=0;tasksStolen=0;taskDurations=new ct(1e3);protocolsExecuted=0;workflowsExecuted=0;auditLogger;minCutBridge=null;tinyDancerRouter=null;domainBreakerRegistry=null;domainTeamManager=null;agentTeamsAdapter=null;tierSelector=null;taskCompletedHook=null;traceCollector=null;taskTraceContexts=new Map;hypothesisManager=null;federationMailbox=null;dynamicScaler=null;coExecutionRepo=null;dependencyGraph=null;availableMcpServers=[];async initialize(){if(!this.initialized){this.startTime=new Date,await this.router.initialize(),this.subscribeToEvents(),this.config.workStealing.enabled&&(this.workStealingTimer=it(this.config,()=>this.triggerWorkStealing().then(()=>{}))),this.config.enableMetrics&&(this.metricsTimer=sn(this.createMetricsContext())),this.cleanupTimer=setInterval(()=>{at(this.tasks,this.taskTraceContexts,36e5)},3e5),this.cleanupTimer.unref(),await rn(this.memory,this.tasks,e=>this.enqueueTaskInternal(e)),this.minCutBridge=vt(this.eventBus,this.agentCoordinator,{autoUpdateFromEvents:!0,persistData:!0,includeInQueenHealth:!0,sharedGraph:xe()}),await this.minCutBridge.initialize(),this.domainPlugins&&nn(this.domainPlugins,this.minCutBridge);try{await I.initialize(),m.info("Governance adapter initialized")}catch(e){m.warn("Governance initialization failed (continuing)",{error:e})}this.initializeSubsystems();try{let{join:e}=await import("path"),t=e(process.cwd(),".claude","agents","v3");this.dependencyGraph=Ft(t),this.availableMcpServers=yt(process.cwd());let{getUnifiedMemory:n}=await import("./unified-memory-72SKVZ7Y.js"),i=n();await i.initialize(),this.coExecutionRepo=Pt(),this.coExecutionRepo.initialize(i.getDatabase()),this.dependencyGraph.warnings.length>0&&m.warn(`Dependency graph: ${this.dependencyGraph.warnings.length} warning(s)`,{warnings:this.dependencyGraph.warnings.slice(0,5)}),m.info("Dependency intelligence initialized",{agents:this.dependencyGraph.nodes.size,mcpServers:this.availableMcpServers.length})}catch(e){m.warn("Dependency intelligence initialization failed (continuing)",{error:e})}await this.publishEvent("QueenInitialized",{timestamp:new Date,config:this.config,domains:T}),this.initialized=!0}}async dispose(){this.workStealingTimer&&(clearInterval(this.workStealingTimer),this.workStealingTimer=null),this.metricsTimer&&(clearInterval(this.metricsTimer),this.metricsTimer=null),this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null),this.minCutBridge&&(await this.minCutBridge.dispose(),this.minCutBridge=null),this.domainTeamManager&&(this.domainTeamManager.dispose(),this.domainTeamManager=null),this.agentTeamsAdapter&&(this.agentTeamsAdapter.shutdown(),this.agentTeamsAdapter=null),this.domainBreakerRegistry=null,this.tierSelector=null,this.traceCollector&&(this.traceCollector.dispose(),this.traceCollector=null),this.hypothesisManager&&(this.hypothesisManager.dispose(),this.hypothesisManager=null),this.federationMailbox&&(this.federationMailbox.dispose(),this.federationMailbox=null),this.dynamicScaler&&(this.dynamicScaler.dispose(),this.dynamicScaler=null),await an(this.memory,this.tasks);for(let[e,t]of this.tasks)(t.status==="queued"||t.status==="running")&&await this.cancelTask(e);await this.publishEvent("QueenShutdown",{timestamp:new Date,metrics:this.getMetrics()});for(let e of this.eventSubscriptionIds)this.router.unsubscribe(e);this.eventSubscriptionIds=[],await this.router.dispose(),this.initialized=!1}async submitTask(e){if(!this.initialized)return y(new Error("Queen Coordinator not initialized"));let t=`task_${f()}`,n={...e,id:t,createdAt:new Date,timeout:e.timeout||this.config.defaultTaskTimeout},i={taskId:n.id,taskType:n.type,agentId:n.requester||"unknown",domain:n.targetDomains[0]||"test-generation",priority:n.priority,payload:n.payload};try{let r=await I.beforeTaskExecution(i);if(!r.allowed)return this.auditLogger.logFail(t,"governance",r.reason||"Governance check failed"),await this.publishEvent("TaskRejected",{taskId:t,reason:r.reason,escalate:r.escalate}),y(new Error(`Task blocked by governance: ${r.reason}`))}catch(r){m.warn("Governance check error (continuing)",{error:r})}this.runningTaskCounter++;try{if(this.runningTaskCounter>this.config.maxConcurrentTasks)return this.runningTaskCounter--,this.queueTask(n);this.auditLogger.logSubmit(t,{type:n.type,priority:n.priority}),this.selectFleetTier(n),this.startTaskTrace(n,t);let r=await tt(this.createTaskContext(),n);return r.success?(this.tasksReceived++,await this.publishEvent("TaskSubmitted",{taskId:t,task:n}),C(t)):(this.runningTaskCounter--,r)}catch(r){throw this.runningTaskCounter--,r}}async cancelTask(e){let t=this.tasks.get(e);if(!t)return y(new Error(`Task not found: ${e}`));if(t.status==="completed"||t.status==="failed")return y(new Error(`Task already finished: ${e}`));(t.status==="running"||t.status==="assigned")&&(this.runningTaskCounter=Math.max(0,this.runningTaskCounter-1)),this.tasks.set(e,{...t,status:"cancelled",completedAt:new Date}),pe(this.taskQueue,this.domainQueues,t.task);for(let n of t.assignedAgents)await this.agentCoordinator.stop(n);return this.auditLogger.logCancel(e),await this.publishEvent("TaskCancelled",{taskId:e}),C(void 0)}getTaskStatus(e){return this.tasks.get(e)}listTasks(e){return Jt(this.tasks,e)}getDomainHealth(e){if(this.domainPlugins){let t=this.domainPlugins.get(e);if(t)return t.getHealth()}return Zt(this.agentCoordinator,e,this.domainLastActivity.get(e))}getDomainLoad(e){let t=this.domainQueues.get(e)||[],n=Array.from(this.tasks.values()).filter(i=>i.assignedDomain===e&&i.status==="running");return t.length+n.length}getIdleDomains(){let e=Date.now(),t=this.config.workStealing.idleThreshold;return T.filter(n=>{let i=this.domainLastActivity.get(n);return this.getDomainLoad(n)===0&&i&&e-i.getTime()>t})}getBusyDomains(){return T.filter(e=>this.getDomainLoad(e)>this.config.workStealing.loadThreshold)}getSpawnPlan(e){return this.dependencyGraph?Ot(e,this.dependencyGraph):{phases:[e],warnings:[],unsatisfiedHardDeps:[]}}getDependencyGraph(){return this.dependencyGraph}enableWorkStealing(){this.workStealingTimer||(this.workStealingTimer=it(this.config,()=>this.triggerWorkStealing().then(()=>{})))}disableWorkStealing(){this.workStealingTimer&&(clearInterval(this.workStealingTimer),this.workStealingTimer=null)}async triggerWorkStealing(){return tn(this.createWorkStealingContext())}listAllAgents(){return this.agentCoordinator.listAgents()}getAgentsByDomain(e){return this.agentCoordinator.listAgents({domain:e})}async requestAgentSpawn(e,t,n){if(!this.agentCoordinator.canSpawn())return y(new Error("Maximum concurrent agents reached (15)"));if(this.dependencyGraph&&this.availableMcpServers.length>0)try{for(let[,r]of this.dependencyGraph.nodes){let a=r.dependencies.mcpServers;if(!a||a.length===0)continue;let o=a.filter(l=>l.required&&!this.availableMcpServers.includes(l.name));if(o.length>0){m.warn(`Pre-spawn MCP advisory: ${r.agentName} needs ${o.map(l=>l.name).join(", ")}`,{agent:r.agentName,domain:e,missing:o.map(l=>l.name)});break}}}catch{}let i=await this.agentCoordinator.spawn({name:`${e}-${t}-${Date.now()}`,domain:e,type:t,capabilities:n});if(i.success){if(this.domainLastActivity.set(e,new Date),this.domainTeamManager&&typeof this.domainTeamManager.getDomainTeam=="function")try{if(this.domainTeamManager.getDomainTeam(e))this.domainTeamManager.addTeammate(e,i.value)||m.warn(`Agent ${i.value} could not join ${e} team (full)`);else try{this.domainTeamManager.createDomainTeam(e,i.value)}catch{this.domainTeamManager.addTeammate(e,i.value)||m.warn(`Agent ${i.value} could not join ${e} team (full or max teams reached)`)}}catch(r){m.warn(`Auto-team-wiring failed for ${i.value}`,{error:r})}await this.publishEvent("AgentSpawned",{agentId:i.value,domain:e,type:t,capabilities:n})}return i}getHealth(){let e=new Map,t=[],n=0,i=0,r=on(this.domainPlugins,T);for(let u of r){let d=this.getDomainHealth(u);d&&(e.set(u,d),d.status==="unhealthy"?(n++,t.push({domain:u,severity:"high",message:`Domain ${u} is unhealthy`,timestamp:new Date})):d.status==="degraded"&&(i++,t.push({domain:u,severity:"medium",message:`Domain ${u} is degraded`,timestamp:new Date})))}let a=this.agentCoordinator.listAgents(),o=a.filter(u=>u.status==="running").length,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,t=0;for(let l of T){let c=this.getDomainLoad(l);e.set(l,c),t+=c}let n=this.agentCoordinator.listAgents(),i=n.filter(l=>l.status==="running").length,r=n.length>0?i/n.length:0,a=this.taskDurations.average(),o={tasksReceived:this.tasksReceived,tasksCompleted:this.tasksCompleted,tasksFailed:this.tasksFailed,tasksStolen:this.tasksStolen,averageTaskDuration:a,domainUtilization:e,agentUtilization:r,protocolsExecuted:this.protocolsExecuted,workflowsExecuted:this.workflowsExecuted,uptime:Date.now()-this.startTime.getTime()};return this.minCutBridge?this.minCutBridge.extendQueenMetrics(o):o}getMinCutBridge(){return this.minCutBridge}injectMinCutBridgeIntoDomain(e){if(!this.minCutBridge)return m.warn("Cannot inject MinCut bridge: bridge not initialized"),!1;if(!this.domainPlugins)return m.warn("Cannot inject MinCut bridge: no domain plugins registered"),!1;let t=this.domainPlugins.get(e);return t?rt(t)?(t.setMinCutBridge(this.minCutBridge),m.info(`MinCut bridge injected into ${e} (late binding)`),!0):(m.warn(`Domain ${e} does not support MinCut integration`),!1):(m.warn(`Cannot inject MinCut bridge: domain ${e} not found`),!1)}getTinyDancerRouter(){return this.tinyDancerRouter}getDomainBreakerRegistry(){return this.domainBreakerRegistry}getDomainTeamManager(){return this.domainTeamManager}getAgentTeamsAdapter(){return this.agentTeamsAdapter}getTierSelector(){return this.tierSelector}getTraceCollector(){return this.traceCollector}getHypothesisManager(){return this.hypothesisManager}getFederationMailbox(){return this.federationMailbox}getDynamicScaler(){return this.dynamicScaler}connectReasoningBank(e){let t=new ce(e);this.taskCompletedHook=new le({},t),m.info("ReasoningBank connected for pattern training")}async executeProtocol(e,t){if(!this.protocolExecutor)return y(new Error("Protocol executor not configured"));let n=await this.protocolExecutor.execute(e,t);return n.success?(this.protocolsExecuted++,await this.publishEvent("ProtocolExecuted",{protocolId:e,executionId:n.value.executionId}),C(n.value.executionId)):n}async executeWorkflow(e,t){if(!this.workflowExecutor)return y(new Error("Workflow executor not configured"));let n=await this.workflowExecutor.execute(e,t);return n.success?(this.workflowsExecuted++,await this.publishEvent("WorkflowExecuted",{workflowId:e,executionId:n.value.executionId}),C(n.value.executionId)):n}cleanupCompletedTasks(e=36e5){return at(this.tasks,this.taskTraceContexts,e)}subscribeToEvents(){this.eventSubscriptionIds=Yt(this.createEventHandlerContext(),T)}enqueueTaskInternal(e){Xt(this.taskQueue,this.domainQueues,e)}async publishEvent(e,t){await this.eventBus.publish({id:f(),type:`Queen${e}`,timestamp:new Date,source:"queen-coordinator",payload:t})}queueTask(e){this.enqueueTaskInternal(e);let t={taskId:e.id,task:e,status:"queued",assignedAgents:[],retryCount:0};return this.tasks.set(e.id,t),this.tasksReceived++,this.auditLogger.logSubmit(e.id,{type:e.type,priority:e.priority}),this.auditLogger.logQueue(e.id,Je(this.taskQueue,e)),this.publishEvent("TaskQueued",{taskId:e.id,task:e,position:Je(this.taskQueue,e)}),C(e.id)}selectFleetTier(e){if(this.tierSelector)try{let t={trigger:e.payload?.trigger??"manual",changedFiles:e.payload?.changedFiles,affectedDomains:e.targetDomains,severity:e.priority==="p0"?"critical":e.priority==="p1"?"high":void 0,isHotfix:e.payload?.isHotfix},n=this.tierSelector.selectTier(t);return m.info(`Fleet tier: ${n.selectedTier} (${n.reason})`),n.selectedTier}catch(t){m.warn("Tier selection error (continuing)",{error:t});return}}startTaskTrace(e,t){if(this.traceCollector)try{let{context:n}=this.traceCollector.startTrace({operationName:e.type,agentId:e.requester||"queen",domain:e.targetDomains[0]||"test-generation",tags:{taskId:t,priority:e.priority}});if(this.taskTraceContexts.size>=1e4){let r=this.taskTraceContexts.keys().next().value;r!==void 0&&this.taskTraceContexts.delete(r)}this.taskTraceContexts.set(t,n)}catch(n){m.warn("Trace start error (continuing)",{error:n})}}getRunningTaskCount(){return Array.from(this.tasks.values()).filter(e=>e.status==="running"||e.status==="assigned").length}getQueuedTaskCount(){return Array.from(this.tasks.values()).filter(e=>e.status==="queued").length}initializeSubsystems(){if(this.config.enableCircuitBreakers!==!1)try{this.domainBreakerRegistry=Qt(),m.info("Domain circuit breaker registry initialized")}catch(e){m.warn("Circuit breaker initialization failed (continuing)",{error:e})}if(this.config.enableDomainTeams!==!1)try{this.agentTeamsAdapter=Pe(),this.agentTeamsAdapter.initialize(),this.domainTeamManager=He(this.agentTeamsAdapter),m.info("Domain team manager initialized")}catch(e){m.warn("Domain team manager initialization failed (continuing)",{error:e})}if(this.config.enableFleetTiers!==!1)try{this.tierSelector=Le(),m.info("Fleet tier selector initialized")}catch(e){m.warn("Tier selector initialization failed (continuing)",{error:e})}try{this.traceCollector=_e(),m.info("Trace collector initialized")}catch(e){m.warn("Trace collector initialization failed (continuing)",{error:e})}try{this.hypothesisManager=$e(),this.federationMailbox=Ge(),this.dynamicScaler=qe(),m.info("Phase 4 modules initialized (hypotheses, federation, scaling)")}catch(e){m.warn("Phase 4 initialization failed (continuing)",{error:e})}}createEventHandlerContext(){let e=this;return{config:e.config,tasks:e.tasks,domainLastActivity:e.domainLastActivity,auditLogger:e.auditLogger,router:e.router,agentCoordinator:e.agentCoordinator,get runningTaskCounter(){return e.runningTaskCounter},set runningTaskCounter(t){e.runningTaskCounter=t},get tasksCompleted(){return e.tasksCompleted},set tasksCompleted(t){e.tasksCompleted=t},get tasksFailed(){return e.tasksFailed},set tasksFailed(t){e.tasksFailed=t},taskDurations:e.taskDurations,get domainBreakerRegistry(){return e.domainBreakerRegistry},get traceCollector(){return e.traceCollector},taskTraceContexts:e.taskTraceContexts,get taskCompletedHook(){return e.taskCompletedHook},get hypothesisManager(){return e.hypothesisManager},processQueue:()=>et(e.createTaskContext()),enqueueTask:t=>e.enqueueTaskInternal(t)}}createTaskContext(){let e=this;return{config:e.config,tasks:e.tasks,taskQueue:e.taskQueue,domainQueues:e.domainQueues,domainLastActivity:e.domainLastActivity,auditLogger:e.auditLogger,agentCoordinator:e.agentCoordinator,domainPlugins:e.domainPlugins,get runningTaskCounter(){return e.runningTaskCounter},set runningTaskCounter(t){e.runningTaskCounter=t},get tasksReceived(){return e.tasksReceived},set tasksReceived(t){e.tasksReceived=t},get tasksCompleted(){return e.tasksCompleted},set tasksCompleted(t){e.tasksCompleted=t},get tasksFailed(){return e.tasksFailed},set tasksFailed(t){e.tasksFailed=t},taskDurations:e.taskDurations,get tinyDancerRouter(){return e.tinyDancerRouter},get domainBreakerRegistry(){return e.domainBreakerRegistry},get domainTeamManager(){return e.domainTeamManager},get tierSelector(){return e.tierSelector},get traceCollector(){return e.traceCollector},taskTraceContexts:e.taskTraceContexts,get coExecutionRepo(){return e.coExecutionRepo},requestAgentSpawn:(t,n,i)=>e.requestAgentSpawn(t,n,i),publishEvent:(t,n)=>e.publishEvent(t,n),getDomainLoad:t=>e.getDomainLoad(t),getDomainHealth:t=>e.getDomainHealth(t)}}createWorkStealingContext(){let e=this;return{config:e.config,domainQueues:e.domainQueues,auditLogger:e.auditLogger,get tasksStolen(){return e.tasksStolen},set tasksStolen(t){e.tasksStolen=t},getIdleDomains:()=>e.getIdleDomains(),getBusyDomains:()=>e.getBusyDomains(),getDomainLoad:t=>e.getDomainLoad(t),removeFromQueues:t=>pe(e.taskQueue,e.domainQueues,t),assignTaskToDomain:(t,n)=>nt(e.createTaskContext(),t,n).then(()=>{}),publishEvent:(t,n)=>e.publishEvent(t,n)}}createMetricsContext(){let e=this;return{config:e.config,memory:e.memory,get dynamicScaler(){return e.dynamicScaler},getMetrics:()=>e.getMetrics(),publishEvent:(t,n)=>e.publishEvent(t,n),getQueuedTaskCount:()=>e.getQueuedTaskCount(),getActiveAgentCount:()=>e.agentCoordinator.listAgents().filter(t=>t.status==="running").length,getIdleAgentCount:()=>e.agentCoordinator.listAgents().filter(t=>t.status==="idle").length,getAverageTaskDuration:()=>e.taskDurations.average(),getTasksReceived:()=>e.tasksReceived,getTasksFailed:()=>e.tasksFailed,getTasksCompleted:()=>e.tasksCompleted}}};function Lo(s,e,t,n,i,r){return new st(s.eventBus,s.coordinator,s.memory,e,t,n,i,r)}export{xe as a,or as b,ri as c,P as d,st as e,Lo as f};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.1");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.2");process.exit(0)}
2
2
  var u={0:{tier:0,name:"Agent Booster",description:"Mechanical code transforms via Rust/WASM",useCases:["var-to-const conversion","add-types","remove-console statements","promise-to-async","cjs-to-esm","func-to-arrow"],typicalLatencyMs:1,relativeCost:0,exampleModels:["agent-booster-wasm","agent-booster-typescript"],requiresNetwork:!1,complexityRange:[0,10]},1:{tier:1,name:"Haiku",description:"Fast, cost-effective for simple tasks",useCases:["Simple bug fixes","Code formatting","Documentation updates","Basic refactoring","Test generation (simple)"],typicalLatencyMs:500,relativeCost:1,exampleModels:["claude-3-5-haiku-20241022","gpt-4o-mini","gemini-flash"],requiresNetwork:!0,complexityRange:[10,35]},2:{tier:2,name:"Sonnet",description:"Balanced capability for complex reasoning",useCases:["Feature implementation","Complex refactoring","Security analysis","Performance optimization","Test generation (complex)"],typicalLatencyMs:3e3,relativeCost:2,exampleModels:["claude-sonnet-4-20250514","gpt-4o","gemini-pro"],requiresNetwork:!0,complexityRange:[35,70]},3:{tier:3,name:"Sonnet Extended",description:"Extended context for multi-step workflows",useCases:["Multi-file refactoring","Workflow orchestration","Cross-domain coordination","Large codebase analysis"],typicalLatencyMs:7e3,relativeCost:3,exampleModels:["claude-sonnet-4-20250514"],requiresNetwork:!0,complexityRange:[60,85]},4:{tier:4,name:"Opus",description:"Maximum capability for critical decisions",useCases:["Architecture design","Security audits","Complex algorithm design","Critical bug analysis","System-wide refactoring"],typicalLatencyMs:5e3,relativeCost:4,exampleModels:["claude-opus-4-5-20251101","gpt-4-turbo"],requiresNetwork:!0,complexityRange:[75,100]}},d={enabled:!0,tierBudgets:{0:{tier:0,maxCostPerRequest:0,maxRequestsPerHour:1e4,maxRequestsPerDay:1e5,maxDailyCostUsd:0,enabled:!0},1:{tier:1,maxCostPerRequest:.01,maxRequestsPerHour:100,maxRequestsPerDay:1e3,maxDailyCostUsd:5,enabled:!0},2:{tier:2,maxCostPerRequest:.1,maxRequestsPerHour:50,maxRequestsPerDay:500,maxDailyCostUsd:20,enabled:!0},3:{tier:3,maxCostPerRequest:.5,maxRequestsPerHour:20,maxRequestsPerDay:100,maxDailyCostUsd:30,enabled:!0},4:{tier:4,maxCostPerRequest:2,maxRequestsPerHour:10,maxRequestsPerDay:50,maxDailyCostUsd:50,enabled:!0}},maxDailyCostUsd:100,warningThreshold:.8,onBudgetExceeded:"downgrade",onBudgetWarning:"warn",allowCriticalOverrides:!0},y={budgetConfig:d,enableAgentBooster:!0,agentBoosterThreshold:.7,enableAutoRouting:!0,complexityThresholds:{0:10,1:35,2:70,3:85,4:100},allowManualOverrides:!0,enableDecisionCache:!0,decisionCacheTtlMs:300*1e3,enableMetrics:!0,maxDecisionTimeMs:10,fallbackTier:2,tierModels:{0:"agent-booster",1:"claude-3-5-haiku-20241022",2:"claude-sonnet-4-20250514",3:"claude-sonnet-4-20250514",4:"claude-opus-4-5-20251101"}},r=class extends Error{constructor(e,t,l){super(e);this.code=t;this.cause=l;this.name="ModelRouterError"}},a=class extends r{constructor(e,t,l){super(e,"BUDGET_EXCEEDED");this.tier=t;this.usage=l;this.name="BudgetExceededError"}},i=class extends r{constructor(o,e){super(o,"COMPLEXITY_ANALYSIS_ERROR",e),this.name="ComplexityAnalysisError"}},s=class extends r{constructor(e,t){super(e,"ROUTING_TIMEOUT");this.timeoutMs=t;this.name="RoutingTimeoutError"}};export{u as a,d as b,y as c,r as d,a as e,i as f,s as g};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.1");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.2");process.exit(0)}
2
2
  var l=["ECONNREFUSED","ETIMEOUT","ENOMEM","ENOSPC"];var s={successRate:.1,failureRate:1,viabilityThreshold:.3,rehabilitationThreshold:10,maxQuarantineDurationMs:6048e5,domainOverrides:{"security-compliance":{successRate:.05,failureRate:1,viabilityThreshold:.5},"test-generation":{successRate:.15,failureRate:1,viabilityThreshold:.2},"quality-assessment":{successRate:.1,failureRate:1,viabilityThreshold:.4}}},a=class{config;_witnessChain=null;set witnessChain(e){this._witnessChain=e}constructor(e={}){this.config={...s,...e,domainOverrides:{...s.domainOverrides,...e.domainOverrides}}}computeConfidenceUpdate(e,r,i){let{successRate:u,failureRate:o}=this.getConfigForDomain(i),n=r==="success"?u:-o;if(r==="failure")try{this._witnessChain?.append("HEBBIAN_PENALTY",{previousConfidence:e,delta:n,domain:i},"asymmetric-learning")}catch{}return c(e+n,0,1)}shouldQuarantine(e,r){let{viabilityThreshold:i}=this.getConfigForDomain(r);return{shouldQuarantine:e<i,confidence:e,viabilityThreshold:i,domain:r}}classifyFailure(e){if(e.infrastructureHealthy===!1||e.durationMs!==void 0&&e.durationMs>3e4)return"infrastructure";if(e.errorMessage){let r=e.errorMessage.toUpperCase();for(let i of l)if(r.includes(i))return"infrastructure"}return e.failureCategory==="infrastructure"?"infrastructure":(e.failureCategory==="pattern","pattern")}checkRehabilitation(e,r){let i=this.config.rehabilitationThreshold;return{canRehabilitate:e>=i,consecutiveSuccesses:e,requiredSuccesses:i,domain:r}}getConfigForDomain(e){return e&&this.config.domainOverrides?.[e]?this.config.domainOverrides[e]:{successRate:this.config.successRate,failureRate:this.config.failureRate,viabilityThreshold:this.config.viabilityThreshold}}getAsymmetryRatio(e){let{successRate:r,failureRate:i}=this.getConfigForDomain(e);return r===0?1/0:i/r}};function c(t,e,r){return t<e?e:t>r?r:t}export{a};
@@ -1,3 +1,3 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.1");process.exit(0)}
2
- import{c}from"./chunk-UZZCWWIG.js";function u(r){switch(r.toUpperCase()){case"DEBUG":return 0;case"INFO":return 1;case"WARN":case"WARNING":return 2;case"ERROR":return 3;case"SILENT":case"NONE":case"OFF":return 4;default:return 1}}var f,l=c(()=>{"use strict";f={0:"DEBUG",1:"INFO",2:"WARN",3:"ERROR",4:"SILENT"}});var a,s,g,d=c(()=>{"use strict";l();a={includeTimestamp:!0,includeLevel:!0,timestampFormat:"short",prettyPrint:!1,maxContextDepth:3},s=class r{domain;level;config;inheritedContext;constructor(e,n=1,o={},t={}){this.domain=e,this.level=n,this.config={...a,...o},this.inheritedContext=t}debug(e,n){this.level<=0&&this.output(0,e,n)}info(e,n){this.level<=1&&this.output(1,e,n)}warn(e,n){this.level<=2&&this.output(2,e,n)}error(e,n,o){if(this.level<=3){let t={...o};if(n){t.errorName=n.name,t.errorMessage=n.message,n.stack&&(t.stack=n.stack);let i=n;i.cause!==void 0&&(t.cause=String(i.cause))}this.output(3,e,t)}}isEnabled(e){return this.level<=e}getDomain(){return this.domain}child(e){return new r(this.domain,this.level,this.config,{...this.inheritedContext,...e})}output(e,n,o){let t=this.format(e,n,o);switch(e){case 0:console.debug(t);break;case 1:console.info(t);break;case 2:console.warn(t);break;case 3:console.error(t);break}}format(e,n,o){let t=[];this.config.includeTimestamp&&t.push(this.formatTimestamp()),this.config.includeLevel&&t.push(this.formatLevel(e)),t.push(`[${this.domain}]`),t.push(n);let i=this.mergeContext(o);return i&&Object.keys(i).length>0&&t.push(this.formatContext(i)),t.join(" ")}formatTimestamp(){let e=new Date;if(this.config.timestampFormat==="iso")return`[${e.toISOString()}]`;let n=String(e.getHours()).padStart(2,"0"),o=String(e.getMinutes()).padStart(2,"0"),t=String(e.getSeconds()).padStart(2,"0"),i=String(e.getMilliseconds()).padStart(3,"0");return`[${n}:${o}:${t}.${i}]`}formatLevel(e){return`[${f[e].padEnd(5)}]`}mergeContext(e){if(!(!e&&Object.keys(this.inheritedContext).length===0))return{...this.inheritedContext,...e}}formatContext(e){try{return this.config.prettyPrint?`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.2");process.exit(0)}
2
+ import{c}from"./chunk-YXCU4CJX.js";function u(r){switch(r.toUpperCase()){case"DEBUG":return 0;case"INFO":return 1;case"WARN":case"WARNING":return 2;case"ERROR":return 3;case"SILENT":case"NONE":case"OFF":return 4;default:return 1}}var f,l=c(()=>{"use strict";f={0:"DEBUG",1:"INFO",2:"WARN",3:"ERROR",4:"SILENT"}});var a,s,g,d=c(()=>{"use strict";l();a={includeTimestamp:!0,includeLevel:!0,timestampFormat:"short",prettyPrint:!1,maxContextDepth:3},s=class r{domain;level;config;inheritedContext;constructor(e,n=1,o={},t={}){this.domain=e,this.level=n,this.config={...a,...o},this.inheritedContext=t}debug(e,n){this.level<=0&&this.output(0,e,n)}info(e,n){this.level<=1&&this.output(1,e,n)}warn(e,n){this.level<=2&&this.output(2,e,n)}error(e,n,o){if(this.level<=3){let t={...o};if(n){t.errorName=n.name,t.errorMessage=n.message,n.stack&&(t.stack=n.stack);let i=n;i.cause!==void 0&&(t.cause=String(i.cause))}this.output(3,e,t)}}isEnabled(e){return this.level<=e}getDomain(){return this.domain}child(e){return new r(this.domain,this.level,this.config,{...this.inheritedContext,...e})}output(e,n,o){let t=this.format(e,n,o);switch(e){case 0:console.debug(t);break;case 1:console.info(t);break;case 2:console.warn(t);break;case 3:console.error(t);break}}format(e,n,o){let t=[];this.config.includeTimestamp&&t.push(this.formatTimestamp()),this.config.includeLevel&&t.push(this.formatLevel(e)),t.push(`[${this.domain}]`),t.push(n);let i=this.mergeContext(o);return i&&Object.keys(i).length>0&&t.push(this.formatContext(i)),t.join(" ")}formatTimestamp(){let e=new Date;if(this.config.timestampFormat==="iso")return`[${e.toISOString()}]`;let n=String(e.getHours()).padStart(2,"0"),o=String(e.getMinutes()).padStart(2,"0"),t=String(e.getSeconds()).padStart(2,"0"),i=String(e.getMilliseconds()).padStart(3,"0");return`[${n}:${o}:${t}.${i}]`}formatLevel(e){return`[${f[e].padEnd(5)}]`}mergeContext(e){if(!(!e&&Object.keys(this.inheritedContext).length===0))return{...this.inheritedContext,...e}}formatContext(e){try{return this.config.prettyPrint?`
3
3
  `+JSON.stringify(e,this.createReplacer(),2):JSON.stringify(e,this.createReplacer())}catch{return"[unserializable context]"}}createReplacer(){let e=new WeakSet,n=0;return(o,t)=>{if(typeof t=="object"&&t!==null){if(n>=this.config.maxContextDepth)return"[object]";if(e.has(t))return"[circular]";e.add(t),n++}return t instanceof Error?{name:t.name,message:t.message,stack:t.stack}:typeof t=="bigint"?t.toString():typeof t=="function"?"[function]":typeof t=="symbol"?t.toString():t}}},g=class{domain;constructor(e="null"){this.domain=e}debug(e,n){}info(e,n){}warn(e,n){}error(e,n,o){}isEnabled(e){return!1}getDomain(){return this.domain}child(e){return this}}});function F(r,e){return L.create(r,e)}var v,L,m=c(()=>{"use strict";l();d();v={defaultLevel:1,domainLevels:new Map,consoleConfig:a,silent:!1},L=class{static config={...v};static customProvider=null;static instances=new Map;static setLevel(e){this.config.defaultLevel=e,this.instances.clear()}static setLevelFromString(e){this.setLevel(u(e))}static getLevel(){return this.config.defaultLevel}static setDomainLevel(e,n){this.config.domainLevels.set(e,n),this.instances.delete(e)}static getDomainLevel(e){return this.config.domainLevels.get(e)??this.config.defaultLevel}static clearDomainLevel(e){this.config.domainLevels.delete(e),this.instances.delete(e)}static configure(e){this.config.consoleConfig={...this.config.consoleConfig,...e},this.instances.clear()}static setSilent(e){this.config.silent=e,this.instances.clear()}static isSilent(){return this.config.silent}static setProvider(e){this.customProvider=e,this.instances.clear()}static create(e,n){if(!n&&this.instances.has(e))return this.instances.get(e);let o=this.getDomainLevel(e),t;return this.config.silent?t=new g(e):this.customProvider?t=this.customProvider(e,o,n):t=new s(e,o,this.config.consoleConfig,n),n||this.instances.set(e,t),t}static getLogger(e,n){return this.create(e,n)}static reset(){this.config={defaultLevel:1,domainLevels:new Map,consoleConfig:{...a},silent:!1},this.customProvider=null,this.instances.clear()}static initFromEnv(){let e=process.env.LOG_LEVEL;e&&this.setLevelFromString(e);let n=process.env.LOG_TIMESTAMP;n!==void 0&&this.configure({includeTimestamp:n.toLowerCase()==="true"});let o=process.env.LOG_PRETTY;o!==void 0&&this.configure({prettyPrint:o.toLowerCase()==="true"})}static getStats(){return{cachedLoggers:this.instances.size,domains:Array.from(this.instances.keys()),domainOverrides:this.config.domainLevels.size,currentLevel:this.config.defaultLevel,silent:this.config.silent}}}});export{l as a,d as b,L as c,F as d,m as e};