agentic-qe 3.9.2 → 3.9.3

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 (286) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/dist/cli/bundle.js +5 -5
  3. package/dist/cli/chunks/adapter-WKI55MLS.js +2 -0
  4. package/dist/cli/chunks/{agent-booster-wasm-AKAOHSCX.js → agent-booster-wasm-W6GGSB43.js} +2 -2
  5. package/dist/cli/chunks/{agent-handler-MTGPOUVP.js → agent-handler-3IRN5WBS.js} +2 -2
  6. package/dist/cli/chunks/{agent-memory-branch-UFPKWUFK.js → agent-memory-branch-SO63CIPJ.js} +2 -2
  7. package/dist/cli/chunks/aqe-learning-engine-QQHHH3ZL.js +2 -0
  8. package/dist/cli/chunks/{audit-VBEZHNHO.js → audit-TONGHW5H.js} +2 -2
  9. package/dist/cli/chunks/base-3ENVJTIL.js +2 -0
  10. package/dist/cli/chunks/{better-sqlite3-IRPHIXRU.js → better-sqlite3-OK5DP5FC.js} +2 -2
  11. package/dist/cli/chunks/{brain-handler-7EO3FFRZ.js → brain-handler-MC2S3UHL.js} +3 -3
  12. package/dist/cli/chunks/{branch-enumerator-MZRGP35N.js → branch-enumerator-PRKJKPAE.js} +2 -2
  13. package/dist/cli/chunks/{browser-VSIWQE7J.js → browser-WTMMBSU3.js} +2 -2
  14. package/dist/cli/chunks/browser-workflow-QVT343YP.js +2 -0
  15. package/dist/cli/chunks/{chunk-563PJBDM.js → chunk-2CPNZVGL.js} +2 -2
  16. package/dist/cli/chunks/{chunk-XFMKJ3UD.js → chunk-2GZ4EG3L.js} +1 -1
  17. package/dist/cli/chunks/{chunk-X6LCMOGC.js → chunk-2IU6WK32.js} +2 -2
  18. package/dist/cli/chunks/{chunk-PNL5G6TE.js → chunk-3GMN3PNP.js} +2 -2
  19. package/dist/cli/chunks/{chunk-56IWS2KY.js → chunk-3Q5FG6M3.js} +2 -2
  20. package/dist/cli/chunks/{chunk-WXWY2GAF.js → chunk-53YFAERL.js} +2 -2
  21. package/dist/cli/chunks/{chunk-LMMEUVE5.js → chunk-5B2KXDWF.js} +1 -1
  22. package/dist/cli/chunks/{chunk-TTOE336G.js → chunk-5OL6UOBM.js} +3 -3
  23. package/dist/cli/chunks/{chunk-XH53ARZD.js → chunk-5UMSMRJC.js} +2 -2
  24. package/dist/cli/chunks/{chunk-NRCKGXJJ.js → chunk-5YUNMBIH.js} +1 -1
  25. package/dist/cli/chunks/{chunk-QNBQBSAI.js → chunk-66RCUQCI.js} +2 -2
  26. package/dist/cli/chunks/{chunk-MY4LMIG7.js → chunk-6B4CTO5D.js} +2 -2
  27. package/dist/cli/chunks/{chunk-JOVINE23.js → chunk-6N26CWST.js} +2 -2
  28. package/dist/cli/chunks/{chunk-YXCU4CJX.js → chunk-7ASGPJWU.js} +1 -1
  29. package/dist/cli/chunks/{chunk-2Z2TFEOL.js → chunk-7HTSXZ77.js} +2 -2
  30. package/dist/cli/chunks/{chunk-QIH3E775.js → chunk-7JBIDAXT.js} +2 -2
  31. package/dist/cli/chunks/{chunk-4PKXIBX2.js → chunk-AS5WPUDR.js} +1 -1
  32. package/dist/cli/chunks/{chunk-GITD7SRQ.js → chunk-AWSYGQEB.js} +2 -2
  33. package/dist/cli/chunks/{chunk-AA33R5U4.js → chunk-BK445WWE.js} +2 -2
  34. package/dist/cli/chunks/{chunk-4LA7IW3V.js → chunk-BRCCPQXN.js} +1 -1
  35. package/dist/cli/chunks/{chunk-SRRFWTNF.js → chunk-CF4T4YSL.js} +2 -2
  36. package/dist/cli/chunks/{chunk-AKSJQ6B3.js → chunk-COIFERYS.js} +2 -2
  37. package/dist/cli/chunks/{chunk-N3F3CX4V.js → chunk-CU36MONI.js} +2 -2
  38. package/dist/cli/chunks/{chunk-65M7C6SH.js → chunk-D5AQDGTS.js} +1 -1
  39. package/dist/cli/chunks/{chunk-4D2ZG2QO.js → chunk-D5GIV6O7.js} +1 -1
  40. package/dist/cli/chunks/{chunk-XYJL6DKI.js → chunk-DBEU5ISS.js} +2 -2
  41. package/dist/cli/chunks/{chunk-DNLMZTE2.js → chunk-DBSVEWWL.js} +1 -1
  42. package/dist/cli/chunks/{chunk-5AUKULWO.js → chunk-DGRO6LSI.js} +2 -2
  43. package/dist/cli/chunks/{chunk-KTYUCZEM.js → chunk-DKOOKULB.js} +5 -5
  44. package/dist/cli/chunks/{chunk-V6XBAZNH.js → chunk-DTNXHRUF.js} +1 -1
  45. package/dist/cli/chunks/{chunk-UKDOMLBI.js → chunk-ELU576GE.js} +3 -3
  46. package/dist/cli/chunks/{chunk-NM6TIEJ3.js → chunk-ERWNQ6NC.js} +3 -3
  47. package/dist/cli/chunks/{chunk-E25S5E2D.js → chunk-EVIXQR4O.js} +1 -1
  48. package/dist/cli/chunks/{chunk-7SLN2JGP.js → chunk-EXTVDKH7.js} +3 -3
  49. package/dist/cli/chunks/{chunk-DSE57A5N.js → chunk-F6O5XLIE.js} +1 -1
  50. package/dist/cli/chunks/{chunk-7NOIIC7G.js → chunk-FIQ62VOQ.js} +1 -1
  51. package/dist/cli/chunks/chunk-FONTSK2O.js +2 -0
  52. package/dist/cli/chunks/{chunk-RITN3XR4.js → chunk-FR26EINS.js} +2 -2
  53. package/dist/cli/chunks/{chunk-Y6O7CDLI.js → chunk-FSUS5TV6.js} +2 -2
  54. package/dist/cli/chunks/{chunk-WG4GHAML.js → chunk-GBLX5XOH.js} +2 -2
  55. package/dist/cli/chunks/{chunk-KZUJBZ7B.js → chunk-GGEVILIS.js} +2 -2
  56. package/dist/cli/chunks/{chunk-L5YEPSDU.js → chunk-GGKV5IQR.js} +2 -2
  57. package/dist/cli/chunks/{chunk-BY47GV4T.js → chunk-GGQCAQM4.js} +2 -2
  58. package/dist/cli/chunks/{chunk-2VVV73PW.js → chunk-HJEWQD2B.js} +1 -1
  59. package/dist/cli/chunks/{chunk-VUAO4VFC.js → chunk-HVOOYPW6.js} +2 -2
  60. package/dist/cli/chunks/{chunk-Z54EO6E6.js → chunk-IOW7QTYT.js} +2 -2
  61. package/dist/cli/chunks/{chunk-CQP7ZFME.js → chunk-ITFNPXZL.js} +2 -2
  62. package/dist/cli/chunks/{chunk-25LFUL2K.js → chunk-J7QGH6PG.js} +2 -2
  63. package/dist/cli/chunks/{chunk-KQTJ2YLI.js → chunk-JF6AXXAL.js} +4 -4
  64. package/dist/cli/chunks/{chunk-J4BS6IWE.js → chunk-JI5MNJSU.js} +1 -1
  65. package/dist/cli/chunks/{chunk-4UH25U4O.js → chunk-JTIWAUWW.js} +1 -1
  66. package/dist/cli/chunks/{chunk-X35GP7TR.js → chunk-JXE2DFXM.js} +1 -1
  67. package/dist/cli/chunks/{chunk-L5WZUPZF.js → chunk-JZXSKPQB.js} +2 -2
  68. package/dist/cli/chunks/{chunk-2WBCYSUN.js → chunk-K2DDNM4V.js} +8 -8
  69. package/dist/cli/chunks/{chunk-TKF447CW.js → chunk-KV32LAKU.js} +1 -1
  70. package/dist/cli/chunks/{chunk-GCMVJS5X.js → chunk-LDLLHLKE.js} +2 -2
  71. package/dist/cli/chunks/{chunk-QODE4LM6.js → chunk-LHDR6E6F.js} +2 -2
  72. package/dist/cli/chunks/{chunk-DHE66JRR.js → chunk-LMN72H3V.js} +1 -1
  73. package/dist/cli/chunks/{chunk-GK72GUHA.js → chunk-LQDAH47F.js} +2 -2
  74. package/dist/cli/chunks/{chunk-FRJLP7IB.js → chunk-LRE4A464.js} +2 -2
  75. package/dist/cli/chunks/{chunk-HW4ISY5B.js → chunk-M3EFT3XR.js} +3 -3
  76. package/dist/cli/chunks/chunk-M7PGW5Z5.js +2 -0
  77. package/dist/cli/chunks/{chunk-3GZKAORV.js → chunk-MNZ2HHKI.js} +2 -2
  78. package/dist/cli/chunks/{chunk-KBA7FBK3.js → chunk-MSKVWOND.js} +3 -3
  79. package/dist/cli/chunks/{chunk-RC5CPXON.js → chunk-NZLJWXXM.js} +2 -2
  80. package/dist/cli/chunks/{chunk-RJROC5M3.js → chunk-O2O5RO4H.js} +2 -2
  81. package/dist/cli/chunks/{chunk-6SOJVEU7.js → chunk-OBOCKH47.js} +2 -2
  82. package/dist/cli/chunks/{chunk-DBE34QES.js → chunk-OJKGRB6D.js} +2 -2
  83. package/dist/cli/chunks/{chunk-4DAOZQ3V.js → chunk-OV6H3TRU.js} +2 -2
  84. package/dist/cli/chunks/{chunk-SDTVHR63.js → chunk-OXR2FPHK.js} +2 -2
  85. package/dist/cli/chunks/{chunk-T5GV6UIO.js → chunk-OZNJZMQL.js} +2 -2
  86. package/dist/cli/chunks/{chunk-Q4A72ZTV.js → chunk-P4RYVWIR.js} +2 -2
  87. package/dist/cli/chunks/{chunk-VL7YOOC2.js → chunk-P6OZKWNK.js} +2 -2
  88. package/dist/cli/chunks/{chunk-SGAW2WLI.js → chunk-PD5YPC2A.js} +4 -4
  89. package/dist/cli/chunks/{chunk-BKCTNRC5.js → chunk-PKIBG7OJ.js} +2 -2
  90. package/dist/cli/chunks/{chunk-CQBSGYRA.js → chunk-PRIWFNVU.js} +2 -2
  91. package/dist/cli/chunks/{chunk-RQGYJK7H.js → chunk-PS6KLLLQ.js} +2 -2
  92. package/dist/cli/chunks/{chunk-NJY7ZA77.js → chunk-QAXJOCTW.js} +1 -1
  93. package/dist/cli/chunks/{chunk-PJFLO37I.js → chunk-QB2LOM5O.js} +2 -2
  94. package/dist/cli/chunks/{chunk-SNVM4YJS.js → chunk-RRELDHZY.js} +2 -2
  95. package/dist/cli/chunks/{chunk-VHVWAXCF.js → chunk-S23UV7FV.js} +1 -1
  96. package/dist/cli/chunks/{chunk-KZTO5EVM.js → chunk-SDHZLA45.js} +2 -2
  97. package/dist/cli/chunks/{chunk-5L6AU3QK.js → chunk-SFFI3MDN.js} +2 -2
  98. package/dist/cli/chunks/{chunk-BOH22AKC.js → chunk-SJLDTV5B.js} +2 -2
  99. package/dist/cli/chunks/{chunk-QEQTC4WQ.js → chunk-SVXIAQRW.js} +2 -2
  100. package/dist/cli/chunks/{chunk-CL3K5EJK.js → chunk-T4GTFSB2.js} +2 -2
  101. package/dist/cli/chunks/{chunk-Z5HXGVXZ.js → chunk-T4RR4YMH.js} +1 -1
  102. package/dist/cli/chunks/{chunk-STE42EMB.js → chunk-T5MWENBA.js} +2 -2
  103. package/dist/cli/chunks/{chunk-BIVIPF4O.js → chunk-TA454OEB.js} +1 -1
  104. package/dist/cli/chunks/{chunk-MN742FIH.js → chunk-TPFE3BAI.js} +2 -2
  105. package/dist/cli/chunks/{chunk-CCYMJKWX.js → chunk-TSS6LXJ6.js} +1 -1
  106. package/dist/cli/chunks/{chunk-5RL66XSH.js → chunk-TTEXJW2U.js} +2 -2
  107. package/dist/cli/chunks/{chunk-S3RDH5CI.js → chunk-TUHIFT65.js} +2 -2
  108. package/dist/cli/chunks/{chunk-QPRVX4H2.js → chunk-U6QQS5Z3.js} +2 -2
  109. package/dist/cli/chunks/{chunk-727BDQ3K.js → chunk-UC3RA5LW.js} +2 -2
  110. package/dist/cli/chunks/{chunk-4FT3PND7.js → chunk-UVWKIP3U.js} +3 -3
  111. package/dist/cli/chunks/{chunk-FAXVVLPL.js → chunk-VNSRA5PY.js} +2 -2
  112. package/dist/cli/chunks/{chunk-ICDXWIFZ.js → chunk-WAWCNUIJ.js} +1 -1
  113. package/dist/cli/chunks/{chunk-FUIHWBVF.js → chunk-WDTFG5AG.js} +1 -1
  114. package/dist/cli/chunks/{chunk-2EC5Z2J4.js → chunk-WIY3V5VQ.js} +9 -9
  115. package/dist/cli/chunks/{chunk-PFNFC43Q.js → chunk-WLK5UVRJ.js} +1 -1
  116. package/dist/cli/chunks/{chunk-34U7JDCN.js → chunk-WSVWVIVR.js} +2 -2
  117. package/dist/cli/chunks/{chunk-KDDZYXP4.js → chunk-X5C73DW5.js} +2 -2
  118. package/dist/cli/chunks/{chunk-SCF7NRVE.js → chunk-XJII5WMD.js} +1 -1
  119. package/dist/cli/chunks/{chunk-JV7LX6OT.js → chunk-YTBE2MEW.js} +4 -4
  120. package/dist/cli/chunks/{chunk-GPLERTZU.js → chunk-Z4V3XV7E.js} +2 -2
  121. package/dist/cli/chunks/{chunk-KNVAAVHH.js → chunk-ZMUVSL5Q.js} +2 -2
  122. package/dist/cli/chunks/{chunk-4Z27TRQF.js → chunk-ZQCU62JJ.js} +2 -2
  123. package/dist/cli/chunks/{chunk-4FMHBBG5.js → chunk-ZTIPMKUS.js} +1 -1
  124. package/dist/cli/chunks/{chunk-Z2IKNC5M.js → chunk-ZVMAE5JD.js} +1 -1
  125. package/dist/cli/chunks/{ci-2BCOBWFG.js → ci-XQEZTRJN.js} +2 -2
  126. package/dist/cli/chunks/{ci-output-FB4OJHAC.js → ci-output-ZWGXOIUD.js} +2 -2
  127. package/dist/cli/chunks/{claude-flow-setup-NEEFZTMB.js → claude-flow-setup-PFJFHZSD.js} +2 -2
  128. package/dist/cli/chunks/client-VUKA3X4R.js +2 -0
  129. package/dist/cli/chunks/{cline-installer-ODO2PS4K.js → cline-installer-L3WC4KUM.js} +2 -2
  130. package/dist/cli/chunks/{code-NSOF62VE.js → code-QMDXXY6C.js} +2 -2
  131. package/dist/cli/chunks/{code-index-extractor-YQL5XN52.js → code-index-extractor-YTPMAZPU.js} +2 -2
  132. package/dist/cli/chunks/{codex-installer-SPEY6VYT.js → codex-installer-KO5G7LHQ.js} +2 -2
  133. package/dist/cli/chunks/{completions-OWKBUMBE.js → completions-KVDPIXMY.js} +2 -2
  134. package/dist/cli/chunks/{complexity-analyzer-PGTXKP73.js → complexity-analyzer-KNIBPEC3.js} +2 -2
  135. package/dist/cli/chunks/{continuedev-installer-KGOXAC7L.js → continuedev-installer-N2GWI5PC.js} +2 -2
  136. package/dist/cli/chunks/{copilot-installer-BF3UA3TG.js → copilot-installer-EX3UTDQN.js} +2 -2
  137. package/dist/cli/chunks/{cost-tracker-2HDJ66E2.js → cost-tracker-XX6OMP37.js} +2 -2
  138. package/dist/cli/chunks/{coverage-KPA2PHIN.js → coverage-FHDDNCPO.js} +3 -3
  139. package/dist/cli/chunks/cross-domain-router-5SUV5AP6.js +2 -0
  140. package/dist/cli/chunks/{cursor-installer-7CDZFHTV.js → cursor-installer-M47YCQU7.js} +2 -2
  141. package/dist/cli/chunks/{daemon-4BPGCKDJ.js → daemon-EV3RXWAG.js} +3 -3
  142. package/dist/cli/chunks/{dag-attention-scheduler-2MAVGSBB.js → dag-attention-scheduler-J7JDWG5J.js} +2 -2
  143. package/dist/cli/chunks/{detect-WRPWTGP5.js → detect-4P5RKV5J.js} +2 -2
  144. package/dist/cli/chunks/{domain-handler-JZVSJ7AG.js → domain-handler-Q35TYDGA.js} +2 -2
  145. package/dist/cli/chunks/{domain-transfer-XGIZOR2X.js → domain-transfer-XC34MV5U.js} +2 -2
  146. package/dist/cli/chunks/dream-2UNEPNI2.js +2 -0
  147. package/dist/cli/chunks/esm-node-TPR2KU6L.js +2 -0
  148. package/dist/cli/chunks/{eval-T7YPAS4G.js → eval-QZGRW7XD.js} +2 -2
  149. package/dist/cli/chunks/{fast-paths-QECJTKCQ.js → fast-paths-O42GG56B.js} +2 -2
  150. package/dist/cli/chunks/{feature-flags-LIFURSFZ.js → feature-flags-G6SJTDVO.js} +2 -2
  151. package/dist/cli/chunks/{feature-flags-R4QZYTIW.js → feature-flags-GIGWUPEX.js} +2 -2
  152. package/dist/cli/chunks/{file-discovery-4W3K3W4C.js → file-discovery-D4NXB3JP.js} +2 -2
  153. package/dist/cli/chunks/{fleet-NLLQWCI5.js → fleet-ZXZ5AAPW.js} +3 -3
  154. package/dist/cli/chunks/{gnn-wrapper-XEII72LN.js → gnn-wrapper-YK6NAPJV.js} +2 -2
  155. package/dist/cli/chunks/{heartbeat-handler-DJ65RE5D.js → heartbeat-handler-DD4T6U36.js} +4 -4
  156. package/dist/cli/chunks/{heartbeat-scheduler-H664265Q.js → heartbeat-scheduler-CBPO5KUB.js} +2 -2
  157. package/dist/cli/chunks/hnsw-adapter-BLMGBVDE.js +2 -0
  158. package/dist/cli/chunks/hnsw-index-UWMXU7RN.js +2 -0
  159. package/dist/cli/chunks/{hnsw-legacy-bridge-SQIDTWAA.js → hnsw-legacy-bridge-REKPPJ75.js} +2 -2
  160. package/dist/cli/chunks/{hnswlib-node-WICYCU5U.js → hnswlib-node-PMWK24KT.js} +2 -2
  161. package/dist/cli/chunks/{hooks-GZUHUD63.js → hooks-UDKFTCJ7.js} +6 -6
  162. package/dist/cli/chunks/{hypergraph-engine-MLCDZ6BL.js → hypergraph-engine-FIAZJD7K.js} +2 -2
  163. package/dist/cli/chunks/{hypergraph-handler-NNDDI4R3.js → hypergraph-handler-NN2EBNBW.js} +3 -3
  164. package/dist/cli/chunks/impact-analyzer-RK2VPRRL.js +2 -0
  165. package/dist/cli/chunks/{init-handler-IJ6BHE6A.js → init-handler-RK256F2M.js} +6 -6
  166. package/dist/cli/chunks/init-wizard-HA2VADPV.js +2 -0
  167. package/dist/cli/chunks/kernel-QMZBPOWP.js +2 -0
  168. package/dist/cli/chunks/{kilocode-installer-EPZFFPFE.js → kilocode-installer-6XPW7IAO.js} +2 -2
  169. package/dist/cli/chunks/{kiro-installer-5VACG3HU.js → kiro-installer-DOHZGTBZ.js} +2 -2
  170. package/dist/cli/chunks/knowledge-graph-INYQCVMS.js +2 -0
  171. package/dist/cli/chunks/{learning-6FITK6XY.js → learning-GRSMZRPZ.js} +3 -3
  172. package/dist/cli/chunks/{llm-router-4DDC6AKJ.js → llm-router-MTZPLM7A.js} +2 -2
  173. package/dist/cli/chunks/{load-KGDNVUBX.js → load-CQXXMUR7.js} +2 -2
  174. package/dist/cli/chunks/load-test-YSEU2TUL.js +2 -0
  175. package/dist/cli/chunks/mcp-IIPV4IWF.js +2 -0
  176. package/dist/cli/chunks/{memory-II4I4QMO.js → memory-GIODHUAL.js} +5 -5
  177. package/dist/cli/chunks/memory-backend-MNSPY44E.js +2 -0
  178. package/dist/cli/chunks/{memory-handlers-TQXTOJGQ.js → memory-handlers-O6UVJSAG.js} +2 -2
  179. package/dist/cli/chunks/{opencode-installer-EU6JCWBW.js → opencode-installer-DDIIEIKL.js} +2 -2
  180. package/dist/cli/chunks/{orchestrator-YLMGJVSP.js → orchestrator-PAQTJDA3.js} +18 -19
  181. package/dist/cli/chunks/{pipeline-MPZJWYKK.js → pipeline-6HFLH75G.js} +2 -2
  182. package/dist/cli/chunks/{platform-YH35ZZFZ.js → platform-UKK776G2.js} +2 -2
  183. package/dist/cli/chunks/{plugin-B7JYZFNQ.js → plugin-ERW5YBXU.js} +2 -2
  184. package/dist/cli/chunks/{prime-radiant-advanced-wasm-KTUK6UE2.js → prime-radiant-advanced-wasm-WB5A4ULB.js} +2 -2
  185. package/dist/cli/chunks/protocol-executor-CBKER6RL.js +2 -0
  186. package/dist/cli/chunks/{protocol-handler-3NXMVU34.js → protocol-handler-AKDFZI6G.js} +2 -2
  187. package/dist/cli/chunks/{prove-H5LMGSUC.js → prove-GT5XEWVF.js} +2 -2
  188. package/dist/cli/chunks/qe-reasoning-bank-C3J4RA2M.js +2 -0
  189. package/dist/cli/chunks/{quality-RCWHY6GO.js → quality-VZAG6B54.js} +2 -2
  190. package/dist/cli/chunks/queen-coordinator-ZXTNAEYV.js +2 -0
  191. package/dist/cli/chunks/{real-embeddings-NKH4VURF.js → real-embeddings-KOOT5MTA.js} +2 -2
  192. package/dist/cli/chunks/{roocode-installer-SB7QJYM3.js → roocode-installer-KHGDU6QK.js} +2 -2
  193. package/dist/cli/chunks/router-YMQF6M2D.js +2 -0
  194. package/dist/cli/chunks/routing-feedback-MM7LNDS7.js +2 -0
  195. package/dist/cli/chunks/{routing-handler-SY7GKG2W.js → routing-handler-HVCNYSJM.js} +2 -2
  196. package/dist/cli/chunks/{ruvector-commands-HATTO3UQ.js → ruvector-commands-D46MOJ32.js} +2 -2
  197. package/dist/cli/chunks/{rvf-dual-writer-D57EXQUD.js → rvf-dual-writer-WASNBBMN.js} +2 -2
  198. package/dist/cli/chunks/{rvf-migration-adapter-OWDYN6KD.js → rvf-migration-adapter-ESLGEE5X.js} +2 -2
  199. package/dist/cli/chunks/{rvf-migration-coordinator-SIQVJB5S.js → rvf-migration-coordinator-S5NAMHTP.js} +2 -2
  200. package/dist/cli/chunks/rvf-native-adapter-3EEWPK4C.js +2 -0
  201. package/dist/cli/chunks/safe-db-5P6ABYNG.js +2 -0
  202. package/dist/cli/chunks/schedule-ZGESH3FK.js +2 -0
  203. package/dist/cli/chunks/scheduler-AC4AA2BD.js +2 -0
  204. package/dist/cli/chunks/{security-DS3XLZWN.js → security-4AHBDCJJ.js} +3 -3
  205. package/dist/cli/chunks/shared-rvf-adapter-UQQUEC52.js +2 -0
  206. package/dist/cli/chunks/{shared-rvf-dual-writer-YB7AH6XJ.js → shared-rvf-dual-writer-ZFNW4C3N.js} +2 -2
  207. package/dist/cli/chunks/sqlite-persistence-KXDW2Q66.js +2 -0
  208. package/dist/cli/chunks/{status-handler-TUYHE4FT.js → status-handler-ZVC4HX5J.js} +2 -2
  209. package/dist/cli/chunks/{structural-health-XNGBNRRD.js → structural-health-DPFQ4GEF.js} +2 -2
  210. package/dist/cli/chunks/{sync-K6CIRKBB.js → sync-7A5JMQNB.js} +2 -2
  211. package/dist/cli/chunks/{task-handler-7PJY67DR.js → task-handler-OFZ5YMXH.js} +2 -2
  212. package/dist/cli/chunks/{task-handlers-WB5CDWUR.js → task-handlers-IRSHSFQW.js} +2 -2
  213. package/dist/cli/chunks/{test-WV5ALEBB.js → test-F6XPB2DN.js} +4 -4
  214. package/dist/cli/chunks/{test-scheduling-N55ZGGA2.js → test-scheduling-CPHQ7DBP.js} +3 -3
  215. package/dist/cli/chunks/{token-bootstrap-SINWHAKR.js → token-bootstrap-5YD6K4LL.js} +2 -2
  216. package/dist/cli/chunks/{token-usage-R7TGEVGL.js → token-usage-KQYGQAEK.js} +2 -2
  217. package/dist/cli/chunks/{transformers-6DBLXPV7.js → transformers-P7TT2MJB.js} +2 -2
  218. package/dist/cli/chunks/{tree-sitter-wasm-parser-7C7FKMQW.js → tree-sitter-wasm-parser-SUSDXGOP.js} +2 -2
  219. package/dist/cli/chunks/{types-VNPMOKQT.js → types-OEGMO7AH.js} +2 -2
  220. package/dist/cli/chunks/unified-memory-MNW25PVU.js +2 -0
  221. package/dist/cli/chunks/unified-memory-hnsw-4RZRP37O.js +2 -0
  222. package/dist/cli/chunks/unified-persistence-6UBNXF25.js +2 -0
  223. package/dist/cli/chunks/{validate-53MNIRAF.js → validate-XI4GTLQR.js} +2 -2
  224. package/dist/cli/chunks/{validate-swarm-ZY4RGUFO.js → validate-swarm-UZQR6AWZ.js} +2 -2
  225. package/dist/cli/chunks/{vibium-PBADBIV6.js → vibium-VPJH2KD5.js} +2 -2
  226. package/dist/cli/chunks/visual-security-7742DBSK.js +2 -0
  227. package/dist/cli/chunks/{web-tree-sitter-O7VI6RLB.js → web-tree-sitter-LUNFY67E.js} +2 -2
  228. package/dist/cli/chunks/{windsurf-installer-HV3C3TAD.js → windsurf-installer-LTJCP7AT.js} +2 -2
  229. package/dist/cli/chunks/witness-chain-QVPNOHDC.js +2 -0
  230. package/dist/cli/chunks/{witness-chain-4WIMYP4X.js → witness-chain-YWBIN5MQ.js} +2 -2
  231. package/dist/cli/chunks/{workflow-5RVAQ4TM.js → workflow-UGXLNO36.js} +4 -4
  232. package/dist/cli/chunks/workflow-orchestrator-K3Q2GOEG.js +2 -0
  233. package/dist/cli/chunks/{wrappers-RRHCCA3E.js → wrappers-LUJRP2YI.js} +2 -2
  234. package/dist/cli/commands/mcp.js +27 -17
  235. package/dist/init/phases/06-code-intelligence.d.ts +33 -1
  236. package/dist/init/phases/06-code-intelligence.js +125 -10
  237. package/dist/init/phases/10-workers.d.ts +0 -14
  238. package/dist/init/phases/10-workers.js +19 -164
  239. package/dist/kernel/hnsw-adapter.d.ts +14 -0
  240. package/dist/kernel/hnsw-adapter.js +25 -1
  241. package/dist/kernel/hnsw-index-provider.d.ts +16 -0
  242. package/dist/kernel/native-hnsw-backend.d.ts +11 -0
  243. package/dist/kernel/native-hnsw-backend.js +20 -0
  244. package/dist/kernel/progressive-hnsw-backend.d.ts +9 -0
  245. package/dist/kernel/progressive-hnsw-backend.js +41 -12
  246. package/dist/kernel/unified-memory.js +10 -0
  247. package/dist/mcp/bundle.js +216 -216
  248. package/dist/optimization/token-optimizer-service.d.ts +31 -2
  249. package/dist/optimization/token-optimizer-service.js +85 -23
  250. package/package.json +1 -1
  251. package/dist/cli/chunks/adapter-53WBPKXU.js +0 -2
  252. package/dist/cli/chunks/aqe-learning-engine-MV7NGY24.js +0 -2
  253. package/dist/cli/chunks/base-DZVGMQN2.js +0 -2
  254. package/dist/cli/chunks/browser-workflow-3J5YNMEI.js +0 -2
  255. package/dist/cli/chunks/chunk-LCAA6H4J.js +0 -2
  256. package/dist/cli/chunks/chunk-XIBVVZGB.js +0 -2
  257. package/dist/cli/chunks/client-EF555KYW.js +0 -2
  258. package/dist/cli/chunks/cross-domain-router-GXFNK5TS.js +0 -2
  259. package/dist/cli/chunks/dream-3IKF5XH4.js +0 -2
  260. package/dist/cli/chunks/esm-node-DHAE52OW.js +0 -2
  261. package/dist/cli/chunks/hnsw-adapter-DML5KXQR.js +0 -2
  262. package/dist/cli/chunks/hnsw-index-BUPPGVR6.js +0 -2
  263. package/dist/cli/chunks/impact-analyzer-DPTMJRYS.js +0 -2
  264. package/dist/cli/chunks/init-wizard-35PUDJPW.js +0 -2
  265. package/dist/cli/chunks/kernel-2HZ44ZJ4.js +0 -2
  266. package/dist/cli/chunks/knowledge-graph-JL62G72U.js +0 -2
  267. package/dist/cli/chunks/load-test-LN245SSD.js +0 -2
  268. package/dist/cli/chunks/mcp-4LETGVIV.js +0 -2
  269. package/dist/cli/chunks/memory-backend-SVM7YRIE.js +0 -2
  270. package/dist/cli/chunks/protocol-executor-IEN2XB4L.js +0 -2
  271. package/dist/cli/chunks/qe-reasoning-bank-Q3ZV3JRG.js +0 -2
  272. package/dist/cli/chunks/queen-coordinator-E6ON3JUR.js +0 -2
  273. package/dist/cli/chunks/router-WMC3LZ3C.js +0 -2
  274. package/dist/cli/chunks/routing-feedback-VKCZRCE3.js +0 -2
  275. package/dist/cli/chunks/rvf-native-adapter-C7NBH5UN.js +0 -2
  276. package/dist/cli/chunks/safe-db-5KLXCNXN.js +0 -2
  277. package/dist/cli/chunks/schedule-HAWWOXWB.js +0 -2
  278. package/dist/cli/chunks/scheduler-HTRDY5BC.js +0 -2
  279. package/dist/cli/chunks/shared-rvf-adapter-6I2Z5UGL.js +0 -2
  280. package/dist/cli/chunks/sqlite-persistence-WNNRGTGG.js +0 -2
  281. package/dist/cli/chunks/unified-memory-72SKVZ7Y.js +0 -2
  282. package/dist/cli/chunks/unified-memory-hnsw-TMN2L77W.js +0 -2
  283. package/dist/cli/chunks/unified-persistence-MDN3SRCR.js +0 -2
  284. package/dist/cli/chunks/visual-security-TRBCXPIB.js +0 -2
  285. package/dist/cli/chunks/witness-chain-JOI2YYGK.js +0 -2
  286. package/dist/cli/chunks/workflow-orchestrator-2NQ72S3C.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.2");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.3");process.exit(0)}
2
2
  var s={"test-generation":/test|spec|describe|it\(|expect|assert|mock|stub|fixture|tdd|bdd/i,"test-execution":/run|execute|parallel|retry|flaky|timeout|worker|orchestrat/i,"coverage-analysis":/coverage|branch|line|uncovered|gap|untested|percentage|sublinear/i,"quality-assessment":/quality|gate|deploy|readiness|metric|threshold|sla|score/i,"defect-intelligence":/defect|bug|predict|root.?cause|regression|failure|incident/i,"requirements-validation":/requirement|bdd|gherkin|testabil|accept|criteri|scenario/i,"code-intelligence":/semantic|knowledge|graph|ast|symbol|reference|impact|depend/i,"security-compliance":/vuln|cve|owasp|xss|sqli|injection|csrf|auth|secret|compliance|sast|dast/i,"contract-testing":/contract|pact|openapi|swagger|graphql|schema|endpoint|api/i,"visual-accessibility":/screenshot|visual|snapshot|pixel|percy|a11y|aria|wcag|screen.?reader|accessible|contrast/i,"chaos-resilience":/chaos|resilience|fault|inject|blast|recover|latency|failure|stress|load/i,"learning-optimization":/learn|pattern|optim|neural|embedding|vector|memory|adapt|train/i};function l(e){for(let[t,a]of Object.entries(s))if(a.test(e))return t;return null}function m(e){let t=[];for(let[a,n]of Object.entries(s))n.test(e)&&t.push(a);return t}function u(e){return e}function d(e){let t=Math.min(e.usageCount/100,1);return e.confidence*.3+t*.2+e.successRate*.5}var c=3;function p(e,t,a=.4){let n=e.tier==="short-term"&&e.successfulUses>=c,r=e.successRate>=.7&&e.confidence>=.6,i=t===void 0||t<a,o;return n?r?i||(o="coherence_violation"):o="low_quality":o="insufficient_usage",{meetsUsageCriteria:n,meetsQualityCriteria:r,meetsCoherenceCriteria:i,blockReason:o}}function y(e){let t=[];if(e.id||t.push("Pattern ID is required"),e.patternType||t.push("Pattern type is required"),e.qeDomain||t.push("QE domain is required"),e.name||t.push("Pattern name is required"),e.template?.content||t.push("Template content is required"),e.confidence!==void 0&&(e.confidence<0||e.confidence>1)&&t.push("Confidence must be between 0 and 1"),e.successRate!==void 0&&(e.successRate<0||e.successRate>1)&&t.push("Success rate must be between 0 and 1"),e.template?.variables){let a=new Set;for(let n of e.template.variables)a.has(n.name)&&t.push(`Duplicate variable name: ${n.name}`),a.add(n.name),e.template.content.includes(`{{${n.name}}}`)||t.push(`Variable ${n.name} not referenced in template`)}return{valid:t.length===0,errors:t}}function f(e,t){let a=e.content;for(let n of e.variables){let r=t[n.name]??n.defaultValue;if(n.required&&r===void 0)throw new Error(`Required variable ${n.name} not provided`);if(r!==void 0){let i=`{{${n.name}}}`,o=typeof r=="object"?JSON.stringify(r):String(r);a=a.split(i).join(o)}}return a}var g=Object.keys(s);export{l as a,m as b,u as c,d,c as e,p as f,y as g,f as h,g as i};
@@ -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.2");process.exit(0)}
2
- import{g}from"./chunk-UKDOMLBI.js";import{b as p,c as d}from"./chunk-BIVIPF4O.js";import{b as m,c as f}from"./chunk-SDTVHR63.js";import{f as h}from"./chunk-E25S5E2D.js";f();var I={maxDepth:5,riskWeights:{directImpact:.4,transitiveImpact:.2,testCoverage:.2,criticalPath:.15,dependencyCount:.05},testPatterns:["**/*.test.ts","**/*.test.tsx","**/*.spec.ts","**/*.spec.tsx","**/test_*.py","**/*_test.py","**/*_test.go"],criticalPaths:["**/auth/**","**/security/**","**/payment/**","**/api/**","**/core/**"],namespace:"code-intelligence:impact"},u=class{constructor(e,t,i={}){this.memory=e;this.config={...I,...i},this.knowledgeGraph=t||new g(e)}config;knowledgeGraph;async analyzeImpact(e){try{let{changedFiles:t,depth:i=this.config.maxDepth,includeTests:n=!0}=e;if(t.length===0)return p({directImpact:[],transitiveImpact:[],impactedTests:[],riskLevel:"info",recommendations:[]});let r=await this.analyzeDirectImpact(t),l=await this.analyzeTransitiveImpact(t,r,i),s=[];if(n){let a=await this.getImpactedTests(t);a.success&&(s=a.value)}let c={directImpact:r,transitiveImpact:l,impactedTests:s,riskLevel:"info",recommendations:[]};return c.riskLevel=this.calculateRiskLevel(c),c.recommendations=this.getRecommendations(c),await this.storeAnalysis(t,c),p(c)}catch(t){return d(m(t))}}async getImpactedTests(e){try{let t=new Set;for(let i of e){if(this.isTestFile(i)){t.add(i);continue}let n=await this.knowledgeGraph.mapDependencies({files:[i],direction:"incoming",depth:3});if(n.success)for(let s of n.value.nodes)this.isTestFile(s.path)&&t.add(s.path);let r=this.getBaseName(i),l=[`${r}.test`,`${r}.spec`,`test_${r}`,`${r}_test`];for(let s of l){let c=await this.memory.search(`code-intelligence:kg:node:*${s}*`,10);for(let a of c){let o=await this.memory.get(a);o?.properties?.path&&this.isTestFile(o.properties.path)&&t.add(o.properties.path)}}}return p(Array.from(t))}catch(t){return d(m(t))}}calculateRiskLevel(e){let t=this.config.riskWeights,i=0,n=Math.min(1,e.directImpact.length/10);i+=n*t.directImpact;let r=Math.min(1,e.transitiveImpact.length/20);i+=r*t.transitiveImpact;let l=e.impactedTests.length>0?Math.max(0,1-e.impactedTests.length/(e.directImpact.length||1)):1;i+=l*t.testCoverage;let s=this.countCriticalFiles([...e.directImpact.map(o=>o.file),...e.transitiveImpact.map(o=>o.file)]),c=Math.min(1,s/5);i+=c*t.criticalPath;let a=this.calculateAverageRiskScore([...e.directImpact,...e.transitiveImpact]);return i+=a*t.dependencyCount,i>=.8?"critical":i>=.6?"high":i>=.4?"medium":i>=.2?"low":"info"}getRecommendations(e){let t=[];(e.riskLevel==="critical"||e.riskLevel==="high")&&t.push("This change has significant impact - consider peer review before merging"),e.impactedTests.length===0&&e.directImpact.length>0?t.push("No tests found for impacted files - add test coverage"):e.impactedTests.length<e.directImpact.length/2&&t.push("Test coverage appears low for impacted files"),e.impactedTests.length>0&&(e.impactedTests.length<=10?t.push(`Run these ${e.impactedTests.length} tests: ${e.impactedTests.slice(0,3).join(", ")}${e.impactedTests.length>3?"...":""}`):t.push(`Run all ${e.impactedTests.length} impacted tests before deployment`));let i=[...e.directImpact,...e.transitiveImpact].filter(r=>this.isCriticalPath(r.file));i.length>0&&t.push(`${i.length} critical path files affected - extra scrutiny recommended`),e.transitiveImpact.length>10&&t.push("Large transitive impact - consider breaking down into smaller changes");let n=[...e.directImpact,...e.transitiveImpact].filter(r=>r.riskScore>=.7);return n.length>0&&t.push(`${n.length} high-risk files impacted: ${n.slice(0,2).map(r=>this.getFileName(r.file)).join(", ")}`),t}async analyzeDirectImpact(e){let t=[];for(let i of e){let n=await this.knowledgeGraph.mapDependencies({files:[i],direction:"incoming",depth:1});if(n.success){let{nodes:r,edges:l}=n.value;for(let s of r){if(s.path===i)continue;let c=l.find(o=>o.target===s.id||o.source===s.id),a=this.calculateFileRiskScore(s.path,s.inDegree,s.outDegree);t.push({file:s.path,reason:`Directly ${c?.type||"depends on"} ${this.getFileName(i)}`,distance:1,riskScore:a})}}}return this.deduplicateImpact(t)}async analyzeTransitiveImpact(e,t,i){let n=[],r=new Set([...e,...t.map(s=>s.file)]),l=t.map(s=>({file:s.file,distance:1}));for(;l.length>0;){let s=l.shift();if(s.distance>=i)continue;let c=await this.knowledgeGraph.mapDependencies({files:[s.file],direction:"incoming",depth:1});if(c.success)for(let a of c.value.nodes){if(r.has(a.path)||a.path===s.file)continue;r.add(a.path);let o=this.calculateFileRiskScore(a.path,a.inDegree,a.outDegree,s.distance+1);n.push({file:a.path,reason:`Transitively depends via ${this.getFileName(s.file)}`,distance:s.distance+1,riskScore:o}),l.push({file:a.path,distance:s.distance+1})}}return this.deduplicateImpact(n)}calculateFileRiskScore(e,t,i,n=1){let r=0;return r+=Math.min(.3,t/20),r+=Math.min(.2,i/30),this.isCriticalPath(e)&&(r+=.3),this.isEntryPoint(e)&&(r+=.2),r=r*Math.pow(.8,n-1),Math.min(1,Math.max(0,r))}calculateAverageRiskScore(e){return e.length===0?0:e.reduce((i,n)=>i+n.riskScore,0)/e.length}countCriticalFiles(e){return e.filter(t=>this.isCriticalPath(t)).length}isTestFile(e){return[/\.test\.[tj]sx?$/,/\.spec\.[tj]sx?$/,/_test\.[tj]sx?$/,/test_.*\.py$/,/.*_test\.py$/,/.*_test\.go$/].some(i=>i.test(e))}isCriticalPath(e){return this.config.criticalPaths.map(i=>i.replace(/\*\*/g,".*").replace(/\*/g,"[^/]*")).some(i=>new RegExp(i).test(e))}isEntryPoint(e){return[/\/index\.[tj]sx?$/,/\/main\.[tj]sx?$/,/\/app\.[tj]sx?$/,/^src\/[^/]+\.[tj]sx?$/,/\/server\.[tj]sx?$/,/\/__init__\.py$/,/\/main\.go$/].some(i=>i.test(e))}getBaseName(e){return this.getFileName(e).replace(/\.[^.]+$/,"")}getFileName(e){return e.split(/[/\\]/).pop()||e}deduplicateImpact(e){let t=new Map;for(let i of e){let n=t.get(i.file);(!n||i.distance<n.distance)&&t.set(i.file,i)}return Array.from(t.values()).sort((i,n)=>n.riskScore!==i.riskScore?n.riskScore-i.riskScore:i.distance-n.distance)}async storeAnalysis(e,t){let i=h();await this.memory.set(`${this.config.namespace}:analysis:${i}`,{id:i,changedFiles:e,analysis:t,timestamp:new Date().toISOString()},{namespace:this.config.namespace,persist:!0})}};export{u as a};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.3");process.exit(0)}
2
+ import{g}from"./chunk-ELU576GE.js";import{b as p,c as d}from"./chunk-TA454OEB.js";import{b as m,c as f}from"./chunk-OXR2FPHK.js";import{f as h}from"./chunk-EVIXQR4O.js";f();var I={maxDepth:5,riskWeights:{directImpact:.4,transitiveImpact:.2,testCoverage:.2,criticalPath:.15,dependencyCount:.05},testPatterns:["**/*.test.ts","**/*.test.tsx","**/*.spec.ts","**/*.spec.tsx","**/test_*.py","**/*_test.py","**/*_test.go"],criticalPaths:["**/auth/**","**/security/**","**/payment/**","**/api/**","**/core/**"],namespace:"code-intelligence:impact"},u=class{constructor(e,t,i={}){this.memory=e;this.config={...I,...i},this.knowledgeGraph=t||new g(e)}config;knowledgeGraph;async analyzeImpact(e){try{let{changedFiles:t,depth:i=this.config.maxDepth,includeTests:n=!0}=e;if(t.length===0)return p({directImpact:[],transitiveImpact:[],impactedTests:[],riskLevel:"info",recommendations:[]});let r=await this.analyzeDirectImpact(t),l=await this.analyzeTransitiveImpact(t,r,i),s=[];if(n){let a=await this.getImpactedTests(t);a.success&&(s=a.value)}let c={directImpact:r,transitiveImpact:l,impactedTests:s,riskLevel:"info",recommendations:[]};return c.riskLevel=this.calculateRiskLevel(c),c.recommendations=this.getRecommendations(c),await this.storeAnalysis(t,c),p(c)}catch(t){return d(m(t))}}async getImpactedTests(e){try{let t=new Set;for(let i of e){if(this.isTestFile(i)){t.add(i);continue}let n=await this.knowledgeGraph.mapDependencies({files:[i],direction:"incoming",depth:3});if(n.success)for(let s of n.value.nodes)this.isTestFile(s.path)&&t.add(s.path);let r=this.getBaseName(i),l=[`${r}.test`,`${r}.spec`,`test_${r}`,`${r}_test`];for(let s of l){let c=await this.memory.search(`code-intelligence:kg:node:*${s}*`,10);for(let a of c){let o=await this.memory.get(a);o?.properties?.path&&this.isTestFile(o.properties.path)&&t.add(o.properties.path)}}}return p(Array.from(t))}catch(t){return d(m(t))}}calculateRiskLevel(e){let t=this.config.riskWeights,i=0,n=Math.min(1,e.directImpact.length/10);i+=n*t.directImpact;let r=Math.min(1,e.transitiveImpact.length/20);i+=r*t.transitiveImpact;let l=e.impactedTests.length>0?Math.max(0,1-e.impactedTests.length/(e.directImpact.length||1)):1;i+=l*t.testCoverage;let s=this.countCriticalFiles([...e.directImpact.map(o=>o.file),...e.transitiveImpact.map(o=>o.file)]),c=Math.min(1,s/5);i+=c*t.criticalPath;let a=this.calculateAverageRiskScore([...e.directImpact,...e.transitiveImpact]);return i+=a*t.dependencyCount,i>=.8?"critical":i>=.6?"high":i>=.4?"medium":i>=.2?"low":"info"}getRecommendations(e){let t=[];(e.riskLevel==="critical"||e.riskLevel==="high")&&t.push("This change has significant impact - consider peer review before merging"),e.impactedTests.length===0&&e.directImpact.length>0?t.push("No tests found for impacted files - add test coverage"):e.impactedTests.length<e.directImpact.length/2&&t.push("Test coverage appears low for impacted files"),e.impactedTests.length>0&&(e.impactedTests.length<=10?t.push(`Run these ${e.impactedTests.length} tests: ${e.impactedTests.slice(0,3).join(", ")}${e.impactedTests.length>3?"...":""}`):t.push(`Run all ${e.impactedTests.length} impacted tests before deployment`));let i=[...e.directImpact,...e.transitiveImpact].filter(r=>this.isCriticalPath(r.file));i.length>0&&t.push(`${i.length} critical path files affected - extra scrutiny recommended`),e.transitiveImpact.length>10&&t.push("Large transitive impact - consider breaking down into smaller changes");let n=[...e.directImpact,...e.transitiveImpact].filter(r=>r.riskScore>=.7);return n.length>0&&t.push(`${n.length} high-risk files impacted: ${n.slice(0,2).map(r=>this.getFileName(r.file)).join(", ")}`),t}async analyzeDirectImpact(e){let t=[];for(let i of e){let n=await this.knowledgeGraph.mapDependencies({files:[i],direction:"incoming",depth:1});if(n.success){let{nodes:r,edges:l}=n.value;for(let s of r){if(s.path===i)continue;let c=l.find(o=>o.target===s.id||o.source===s.id),a=this.calculateFileRiskScore(s.path,s.inDegree,s.outDegree);t.push({file:s.path,reason:`Directly ${c?.type||"depends on"} ${this.getFileName(i)}`,distance:1,riskScore:a})}}}return this.deduplicateImpact(t)}async analyzeTransitiveImpact(e,t,i){let n=[],r=new Set([...e,...t.map(s=>s.file)]),l=t.map(s=>({file:s.file,distance:1}));for(;l.length>0;){let s=l.shift();if(s.distance>=i)continue;let c=await this.knowledgeGraph.mapDependencies({files:[s.file],direction:"incoming",depth:1});if(c.success)for(let a of c.value.nodes){if(r.has(a.path)||a.path===s.file)continue;r.add(a.path);let o=this.calculateFileRiskScore(a.path,a.inDegree,a.outDegree,s.distance+1);n.push({file:a.path,reason:`Transitively depends via ${this.getFileName(s.file)}`,distance:s.distance+1,riskScore:o}),l.push({file:a.path,distance:s.distance+1})}}return this.deduplicateImpact(n)}calculateFileRiskScore(e,t,i,n=1){let r=0;return r+=Math.min(.3,t/20),r+=Math.min(.2,i/30),this.isCriticalPath(e)&&(r+=.3),this.isEntryPoint(e)&&(r+=.2),r=r*Math.pow(.8,n-1),Math.min(1,Math.max(0,r))}calculateAverageRiskScore(e){return e.length===0?0:e.reduce((i,n)=>i+n.riskScore,0)/e.length}countCriticalFiles(e){return e.filter(t=>this.isCriticalPath(t)).length}isTestFile(e){return[/\.test\.[tj]sx?$/,/\.spec\.[tj]sx?$/,/_test\.[tj]sx?$/,/test_.*\.py$/,/.*_test\.py$/,/.*_test\.go$/].some(i=>i.test(e))}isCriticalPath(e){return this.config.criticalPaths.map(i=>i.replace(/\*\*/g,".*").replace(/\*/g,"[^/]*")).some(i=>new RegExp(i).test(e))}isEntryPoint(e){return[/\/index\.[tj]sx?$/,/\/main\.[tj]sx?$/,/\/app\.[tj]sx?$/,/^src\/[^/]+\.[tj]sx?$/,/\/server\.[tj]sx?$/,/\/__init__\.py$/,/\/main\.go$/].some(i=>i.test(e))}getBaseName(e){return this.getFileName(e).replace(/\.[^.]+$/,"")}getFileName(e){return e.split(/[/\\]/).pop()||e}deduplicateImpact(e){let t=new Map;for(let i of e){let n=t.get(i.file);(!n||i.distance<n.distance)&&t.set(i.file,i)}return Array.from(t.values()).sort((i,n)=>n.riskScore!==i.riskScore?n.riskScore-i.riskScore:i.distance-n.distance)}async storeAnalysis(e,t){let i=h();await this.memory.set(`${this.config.namespace}:analysis:${i}`,{id:i,changedFiles:e,analysis:t,timestamp:new Date().toISOString()},{namespace:this.config.namespace,persist:!0})}};export{u as a};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.2");process.exit(0)}
2
- import{a as g}from"./chunk-VL7YOOC2.js";import{b as p,c}from"./chunk-BIVIPF4O.js";import{a as x,b as f,c as w}from"./chunk-SDTVHR63.js";import{f as v}from"./chunk-E25S5E2D.js";w();var l={ProtocolStarted:"coordination.ProtocolStarted",ProtocolCompleted:"coordination.ProtocolCompleted",ProtocolFailed:"coordination.ProtocolFailed",ProtocolCancelled:"coordination.ProtocolCancelled",ActionStarted:"coordination.ActionStarted",ActionCompleted:"coordination.ActionCompleted",ActionFailed:"coordination.ActionFailed"},E=class{constructor(e,t,o){this.eventBus=e;this.memory=t;this.getDomainAPI=o}protocols=new Map;executions=new Map;scheduledProtocols=new Map;schedulerRunning=!1;registerProtocol(e){this.protocols.set(e.id,e),e.schedule.type==="event"&&e.enabled&&this.setupEventTriggers(e),(e.schedule.type==="cron"||e.schedule.type==="interval")&&e.enabled&&this.scheduleProtocol(e)}unregisterProtocol(e){if(!this.protocols.get(e))return!1;let o=this.scheduledProtocols.get(e);return o?.intervalId&&clearInterval(o.intervalId),this.scheduledProtocols.delete(e),this.protocols.delete(e),!0}getProtocol(e){return this.protocols.get(e)}listProtocols(){return Array.from(this.protocols.values())}async execute(e,t){let o=this.protocols.get(e);return o?o.enabled?this.executeProtocol(o,t):c(new Error(`Protocol is disabled: ${e}`)):c(new Error(`Protocol not found: ${e}`))}async executeOnEvent(e,t){let o=this.protocols.get(e);return o?o.enabled?this.executeProtocol(o,void 0,t):c(new Error(`Protocol is disabled: ${e}`)):c(new Error(`Protocol not found: ${e}`))}getExecution(e){let t=this.executions.get(e);if(t)return this.toImmutableExecution(t.execution)}listActiveExecutions(){return Array.from(this.executions.values()).filter(e=>e.execution.status==="running"||e.execution.status==="paused").map(e=>this.toImmutableExecution(e.execution))}async cancelExecution(e){let t=this.executions.get(e);return t?t.execution.status!=="running"&&t.execution.status!=="paused"?c(new Error(`Cannot cancel execution in status: ${t.execution.status}`)):(t.cancelled=!0,t.execution.status="cancelled",t.execution.completedAt=new Date,await this.publishEvent(l.ProtocolCancelled,{executionId:e,protocolId:t.protocol.id}),p(void 0)):c(new Error(`Execution not found: ${e}`))}async pauseExecution(e){let t=this.executions.get(e);return t?t.execution.status!=="running"?c(new Error(`Cannot pause execution in status: ${t.execution.status}`)):(t.paused=!0,t.execution.status="paused",p(void 0)):c(new Error(`Execution not found: ${e}`))}async resumeExecution(e){let t=this.executions.get(e);return t?t.execution.status!=="paused"?c(new Error(`Cannot resume execution in status: ${t.execution.status}`)):(t.paused=!1,t.execution.status="running",p(void 0)):c(new Error(`Execution not found: ${e}`))}startScheduler(){if(!this.schedulerRunning){this.schedulerRunning=!0;for(let e of this.protocols.values())e.enabled&&(e.schedule.type==="interval"||e.schedule.type==="cron")&&this.scheduleProtocol(e)}}stopScheduler(){this.schedulerRunning=!1;for(let e of this.scheduledProtocols.values())e.intervalId&&(clearInterval(e.intervalId),e.intervalId=void 0)}async dispose(){this.stopScheduler(),this.protocols.clear(),this.executions.clear(),this.scheduledProtocols.clear()}async executeProtocol(e,t,o){let r=v(),a=o?.correlationId??r,n={executionId:r,protocolId:e.id,status:"running",participants:[...e.participants],results:new Map,startedAt:new Date,correlationId:a,triggeredBy:o},u={execution:n,protocol:e,params:t,actionResults:new Map,cancelled:!1,paused:!1};this.executions.set(r,u),await this.publishEvent(l.ProtocolStarted,{executionId:r,protocolId:e.id,participants:e.participants},a);try{await this.executeActions(u);let i=Array.from(u.actionResults.values()).some(s=>s.status==="failed");return u.cancelled?n.status="cancelled":i?(n.status="failed",await this.publishEvent(l.ProtocolFailed,{executionId:r,protocolId:e.id,failedActions:Array.from(u.actionResults.values()).filter(s=>s.status==="failed").map(s=>s.actionId)},a)):(n.status="completed",await this.publishEvent(l.ProtocolCompleted,{executionId:r,protocolId:e.id,duration:Date.now()-n.startedAt.getTime()},a)),n.completedAt=new Date,n.results=u.actionResults,await this.storeExecutionHistory(n),p(this.toImmutableExecution(n))}catch(i){return n.status="failed",n.completedAt=new Date,await this.publishEvent(l.ProtocolFailed,{executionId:r,protocolId:e.id,error:x(i)},a),c(f(i))}}async executeActions(e){let{protocol:t,actionResults:o}=e,r=new Set(t.actions.map(n=>n.id)),a=new Set;for(;r.size>0&&!e.cancelled;){for(;e.paused&&!e.cancelled;)await this.sleep(100);if(e.cancelled)break;let n=t.actions.filter(i=>r.has(i.id)&&this.dependenciesSatisfied(i,a));if(n.length===0&&r.size>0)throw new Error(`Deadlock detected: actions ${Array.from(r).join(", ")} cannot proceed`);let u=await Promise.allSettled(n.map(i=>this.executeAction(i,e)));for(let i=0;i<n.length;i++){let s=n[i],d=u[i],m;d.status==="fulfilled"?m=d.value:m={actionId:s.id,status:"failed",error:d.reason instanceof Error?d.reason.message:String(d.reason)},o.set(s.id,m),r.delete(s.id),m.status==="completed"&&a.add(s.id)}}for(let n of r)o.set(n,{actionId:n,status:e.cancelled?"cancelled":"skipped"})}async executeAction(e,t){let o=new Date;await this.publishEvent(l.ActionStarted,{executionId:t.execution.executionId,actionId:e.id,actionName:e.name,targetDomain:e.targetDomain},t.execution.correlationId);let r=0,a=e.retry?.maxAttempts??1,n;for(;r<a;){r++;try{let i=this.getDomainAPI(e.targetDomain);if(!i)throw new Error(`Domain API not available: ${e.targetDomain}`);let s=i[e.method];if(typeof s!="function")throw new Error(`Method ${e.method} not found on domain ${e.targetDomain}`);let d={...e.params,...t.params},m=await this.executeWithTimeout(s.bind(i)(d),e.timeout??3e4),h=new Date;return await this.publishEvent(l.ActionCompleted,{executionId:t.execution.executionId,actionId:e.id,duration:h.getTime()-o.getTime()},t.execution.correlationId),{actionId:e.id,status:"completed",startedAt:o,completedAt:h,duration:h.getTime()-o.getTime(),result:m,retryAttempts:r>1?r-1:void 0}}catch(i){if(n=f(i),r<a&&e.retry){let s=e.retry.backoffMs*Math.pow(e.retry.backoffMultiplier??2,r-1);await this.sleep(s)}}}let u=new Date;return await this.publishEvent(l.ActionFailed,{executionId:t.execution.executionId,actionId:e.id,error:n?.message??"Unknown error",attempts:r},t.execution.correlationId),{actionId:e.id,status:"failed",startedAt:o,completedAt:u,duration:u.getTime()-o.getTime(),error:n?.message??"Unknown error",retryAttempts:r>1?r-1:void 0}}dependenciesSatisfied(e,t){return!e.dependsOn||e.dependsOn.length===0?!0:e.dependsOn.every(o=>t.has(o))}async executeWithTimeout(e,t){return Promise.race([e,new Promise((o,r)=>setTimeout(()=>r(new Error("Action timeout")),t))])}setupEventTriggers(e){if(e.schedule.type==="event")for(let t of e.schedule.triggerEvents)this.eventBus.subscribe(t,async o=>{await this.executeOnEvent(e.id,o)})}scheduleProtocol(e){if(e.schedule.type==="interval"){let t={protocolId:e.id,schedule:e.schedule};t.intervalId=setInterval(async()=>{this.schedulerRunning&&await this.execute(e.id)},e.schedule.intervalMs),this.scheduledProtocols.set(e.id,t)}}async storeExecutionHistory(e){let t=`protocol-execution:${e.executionId}`;await this.memory.set(t,{...e,results:Object.fromEntries(e.results)},{namespace:"coordination",ttl:864e5})}toImmutableExecution(e){return{executionId:e.executionId,protocolId:e.protocolId,status:e.status,participants:[...e.participants],results:new Map(e.results),startedAt:e.startedAt,completedAt:e.completedAt,correlationId:e.correlationId,triggeredBy:e.triggeredBy}}async publishEvent(e,t,o){let r=g(e,"learning-optimization",t,o);await this.eventBus.publish(r)}sleep(e){return new Promise(t=>setTimeout(t,e))}};function S(P,e,t){return new E(P,e,t)}export{E as a,S 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.3");process.exit(0)}
2
+ import{a as g}from"./chunk-P6OZKWNK.js";import{b as p,c}from"./chunk-TA454OEB.js";import{a as x,b as f,c as w}from"./chunk-OXR2FPHK.js";import{f as v}from"./chunk-EVIXQR4O.js";w();var l={ProtocolStarted:"coordination.ProtocolStarted",ProtocolCompleted:"coordination.ProtocolCompleted",ProtocolFailed:"coordination.ProtocolFailed",ProtocolCancelled:"coordination.ProtocolCancelled",ActionStarted:"coordination.ActionStarted",ActionCompleted:"coordination.ActionCompleted",ActionFailed:"coordination.ActionFailed"},E=class{constructor(e,t,o){this.eventBus=e;this.memory=t;this.getDomainAPI=o}protocols=new Map;executions=new Map;scheduledProtocols=new Map;schedulerRunning=!1;registerProtocol(e){this.protocols.set(e.id,e),e.schedule.type==="event"&&e.enabled&&this.setupEventTriggers(e),(e.schedule.type==="cron"||e.schedule.type==="interval")&&e.enabled&&this.scheduleProtocol(e)}unregisterProtocol(e){if(!this.protocols.get(e))return!1;let o=this.scheduledProtocols.get(e);return o?.intervalId&&clearInterval(o.intervalId),this.scheduledProtocols.delete(e),this.protocols.delete(e),!0}getProtocol(e){return this.protocols.get(e)}listProtocols(){return Array.from(this.protocols.values())}async execute(e,t){let o=this.protocols.get(e);return o?o.enabled?this.executeProtocol(o,t):c(new Error(`Protocol is disabled: ${e}`)):c(new Error(`Protocol not found: ${e}`))}async executeOnEvent(e,t){let o=this.protocols.get(e);return o?o.enabled?this.executeProtocol(o,void 0,t):c(new Error(`Protocol is disabled: ${e}`)):c(new Error(`Protocol not found: ${e}`))}getExecution(e){let t=this.executions.get(e);if(t)return this.toImmutableExecution(t.execution)}listActiveExecutions(){return Array.from(this.executions.values()).filter(e=>e.execution.status==="running"||e.execution.status==="paused").map(e=>this.toImmutableExecution(e.execution))}async cancelExecution(e){let t=this.executions.get(e);return t?t.execution.status!=="running"&&t.execution.status!=="paused"?c(new Error(`Cannot cancel execution in status: ${t.execution.status}`)):(t.cancelled=!0,t.execution.status="cancelled",t.execution.completedAt=new Date,await this.publishEvent(l.ProtocolCancelled,{executionId:e,protocolId:t.protocol.id}),p(void 0)):c(new Error(`Execution not found: ${e}`))}async pauseExecution(e){let t=this.executions.get(e);return t?t.execution.status!=="running"?c(new Error(`Cannot pause execution in status: ${t.execution.status}`)):(t.paused=!0,t.execution.status="paused",p(void 0)):c(new Error(`Execution not found: ${e}`))}async resumeExecution(e){let t=this.executions.get(e);return t?t.execution.status!=="paused"?c(new Error(`Cannot resume execution in status: ${t.execution.status}`)):(t.paused=!1,t.execution.status="running",p(void 0)):c(new Error(`Execution not found: ${e}`))}startScheduler(){if(!this.schedulerRunning){this.schedulerRunning=!0;for(let e of this.protocols.values())e.enabled&&(e.schedule.type==="interval"||e.schedule.type==="cron")&&this.scheduleProtocol(e)}}stopScheduler(){this.schedulerRunning=!1;for(let e of this.scheduledProtocols.values())e.intervalId&&(clearInterval(e.intervalId),e.intervalId=void 0)}async dispose(){this.stopScheduler(),this.protocols.clear(),this.executions.clear(),this.scheduledProtocols.clear()}async executeProtocol(e,t,o){let r=v(),a=o?.correlationId??r,n={executionId:r,protocolId:e.id,status:"running",participants:[...e.participants],results:new Map,startedAt:new Date,correlationId:a,triggeredBy:o},u={execution:n,protocol:e,params:t,actionResults:new Map,cancelled:!1,paused:!1};this.executions.set(r,u),await this.publishEvent(l.ProtocolStarted,{executionId:r,protocolId:e.id,participants:e.participants},a);try{await this.executeActions(u);let i=Array.from(u.actionResults.values()).some(s=>s.status==="failed");return u.cancelled?n.status="cancelled":i?(n.status="failed",await this.publishEvent(l.ProtocolFailed,{executionId:r,protocolId:e.id,failedActions:Array.from(u.actionResults.values()).filter(s=>s.status==="failed").map(s=>s.actionId)},a)):(n.status="completed",await this.publishEvent(l.ProtocolCompleted,{executionId:r,protocolId:e.id,duration:Date.now()-n.startedAt.getTime()},a)),n.completedAt=new Date,n.results=u.actionResults,await this.storeExecutionHistory(n),p(this.toImmutableExecution(n))}catch(i){return n.status="failed",n.completedAt=new Date,await this.publishEvent(l.ProtocolFailed,{executionId:r,protocolId:e.id,error:x(i)},a),c(f(i))}}async executeActions(e){let{protocol:t,actionResults:o}=e,r=new Set(t.actions.map(n=>n.id)),a=new Set;for(;r.size>0&&!e.cancelled;){for(;e.paused&&!e.cancelled;)await this.sleep(100);if(e.cancelled)break;let n=t.actions.filter(i=>r.has(i.id)&&this.dependenciesSatisfied(i,a));if(n.length===0&&r.size>0)throw new Error(`Deadlock detected: actions ${Array.from(r).join(", ")} cannot proceed`);let u=await Promise.allSettled(n.map(i=>this.executeAction(i,e)));for(let i=0;i<n.length;i++){let s=n[i],d=u[i],m;d.status==="fulfilled"?m=d.value:m={actionId:s.id,status:"failed",error:d.reason instanceof Error?d.reason.message:String(d.reason)},o.set(s.id,m),r.delete(s.id),m.status==="completed"&&a.add(s.id)}}for(let n of r)o.set(n,{actionId:n,status:e.cancelled?"cancelled":"skipped"})}async executeAction(e,t){let o=new Date;await this.publishEvent(l.ActionStarted,{executionId:t.execution.executionId,actionId:e.id,actionName:e.name,targetDomain:e.targetDomain},t.execution.correlationId);let r=0,a=e.retry?.maxAttempts??1,n;for(;r<a;){r++;try{let i=this.getDomainAPI(e.targetDomain);if(!i)throw new Error(`Domain API not available: ${e.targetDomain}`);let s=i[e.method];if(typeof s!="function")throw new Error(`Method ${e.method} not found on domain ${e.targetDomain}`);let d={...e.params,...t.params},m=await this.executeWithTimeout(s.bind(i)(d),e.timeout??3e4),h=new Date;return await this.publishEvent(l.ActionCompleted,{executionId:t.execution.executionId,actionId:e.id,duration:h.getTime()-o.getTime()},t.execution.correlationId),{actionId:e.id,status:"completed",startedAt:o,completedAt:h,duration:h.getTime()-o.getTime(),result:m,retryAttempts:r>1?r-1:void 0}}catch(i){if(n=f(i),r<a&&e.retry){let s=e.retry.backoffMs*Math.pow(e.retry.backoffMultiplier??2,r-1);await this.sleep(s)}}}let u=new Date;return await this.publishEvent(l.ActionFailed,{executionId:t.execution.executionId,actionId:e.id,error:n?.message??"Unknown error",attempts:r},t.execution.correlationId),{actionId:e.id,status:"failed",startedAt:o,completedAt:u,duration:u.getTime()-o.getTime(),error:n?.message??"Unknown error",retryAttempts:r>1?r-1:void 0}}dependenciesSatisfied(e,t){return!e.dependsOn||e.dependsOn.length===0?!0:e.dependsOn.every(o=>t.has(o))}async executeWithTimeout(e,t){return Promise.race([e,new Promise((o,r)=>setTimeout(()=>r(new Error("Action timeout")),t))])}setupEventTriggers(e){if(e.schedule.type==="event")for(let t of e.schedule.triggerEvents)this.eventBus.subscribe(t,async o=>{await this.executeOnEvent(e.id,o)})}scheduleProtocol(e){if(e.schedule.type==="interval"){let t={protocolId:e.id,schedule:e.schedule};t.intervalId=setInterval(async()=>{this.schedulerRunning&&await this.execute(e.id)},e.schedule.intervalMs),this.scheduledProtocols.set(e.id,t)}}async storeExecutionHistory(e){let t=`protocol-execution:${e.executionId}`;await this.memory.set(t,{...e,results:Object.fromEntries(e.results)},{namespace:"coordination",ttl:864e5})}toImmutableExecution(e){return{executionId:e.executionId,protocolId:e.protocolId,status:e.status,participants:[...e.participants],results:new Map(e.results),startedAt:e.startedAt,completedAt:e.completedAt,correlationId:e.correlationId,triggeredBy:e.triggeredBy}}async publishEvent(e,t,o){let r=g(e,"learning-optimization",t,o);await this.eventBus.publish(r)}sleep(e){return new Promise(t=>setTimeout(t,e))}};function S(P,e,t){return new E(P,e,t)}export{E as a,S as b};
@@ -1,4 +1,4 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.2");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.3");process.exit(0)}
2
2
  var h={0:"sqlite-only",1:"hybrid",2:"dual-write-sqlite-primary",3:"dual-write-rvf-primary",4:"rvf-primary"},g=class{config;db=null;rvfStore=null;totalWrites=0;totalReads=0;rvfWriteFailures=0;rvfReadFailures=0;fallbacksUsed=0;sqliteLatencies=[];rvfLatencies=[];sqliteWriteLatencies=[];rvfWriteLatencies=[];constructor(e){this.config={rvfPath:".agentic-qe/patterns.rvf",dimensions:384,enableFallback:!0,...e}}setSqliteDb(e){this.db=e}setRvfStore(e){this.rvfStore=e}get stage(){return this.config.stage}setStage(e){this.config={...this.config,stage:e}}write(e,t){this.totalWrites++;let s={sqliteSuccess:!1,rvfSuccess:!1,stage:this.config.stage,fallbackUsed:!1},n=this.config.stage<4,o=this.config.stage>=2;if(n&&this.db){let i=performance.now();try{let r=Buffer.from(t instanceof Float32Array?t.buffer:new Float32Array(t).buffer);this.db.prepare(`
3
3
  INSERT INTO qe_pattern_embeddings (pattern_id, embedding, dimension, model, created_at)
4
4
  VALUES (?, ?, ?, 'all-MiniLM-L6-v2', datetime('now'))
@@ -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.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=`
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.3");process.exit(0)}
2
+ import{d as k,f as we}from"./chunk-RRELDHZY.js";import{a as ye}from"./chunk-FONTSK2O.js";import{c as Q}from"./chunk-6N26CWST.js";import{b as C,d as Z}from"./chunk-CU36MONI.js";import{a as V,c as be}from"./chunk-OXR2FPHK.js";import{a as J,b as Xe}from"./chunk-DBEU5ISS.js";import{a as ee,d as b,e as te,f as ne}from"./chunk-ZMUVSL5Q.js";import{a as v,e as De}from"./chunk-TPFE3BAI.js";import{c as R,e as ve}from"./chunk-7ASGPJWU.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.2");process.exit(0)}
2
- import{e as s,f as u}from"./chunk-RQGYJK7H.js";import{a as o,c as d,e as f,g as v}from"./chunk-YXCU4CJX.js";var R={};f(R,{getSharedRvfAdapter:()=>c,resetSharedRvfAdapter:()=>p});function c(a=".agentic-qe",n=384){if(r)return e;r=!0;try{let{isRvfNativeAvailable:t,createRvfStore:i}=(u(),v(s));if(!t())return console.warn("[RVF] Native bindings unavailable \u2014 agent branching and dream COW disabled. Install @ruvector/rvf-node to enable."),null;let l=o("path");return e=i(l.join(a,"patterns.rvf"),n),e}catch(t){return console.warn("[RVF] Shared adapter init failed:",t instanceof Error?t.message:t),null}}function p(){if(e){try{e.close()}catch{}e=null}r=!1}var e,r,h=d(()=>{e=null,r=!1});export{c as a,p as b,R as c,h as d};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.3");process.exit(0)}
2
+ import{e as s,f as u}from"./chunk-PS6KLLLQ.js";import{a as o,c as d,e as f,g as v}from"./chunk-7ASGPJWU.js";var R={};f(R,{getSharedRvfAdapter:()=>c,resetSharedRvfAdapter:()=>p});function c(a=".agentic-qe",n=384){if(r)return e;r=!0;try{let{isRvfNativeAvailable:t,createRvfStore:i}=(u(),v(s));if(!t())return console.warn("[RVF] Native bindings unavailable \u2014 agent branching and dream COW disabled. Install @ruvector/rvf-node to enable."),null;let l=o("path");return e=i(l.join(a,"patterns.rvf"),n),e}catch(t){return console.warn("[RVF] Shared adapter init failed:",t instanceof Error?t.message:t),null}}function p(){if(e){try{e.close()}catch{}e=null}r=!1}var e,r,h=d(()=>{e=null,r=!1});export{c as a,p as b,R as c,h as d};
@@ -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.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(`
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.3");process.exit(0)}
2
+ import{b as ye}from"./chunk-S23UV7FV.js";import{a as ht,b as ft}from"./chunk-NZLJWXXM.js";import{a as yt}from"./chunk-5YUNMBIH.js";import{a as mt,b as pt}from"./chunk-X5C73DW5.js";import{b as gt,d as z}from"./chunk-T4RR4YMH.js";import{j as I}from"./chunk-P4RYVWIR.js";import{a as ct}from"./chunk-FIQ62VOQ.js";import{a as fe}from"./chunk-KV32LAKU.js";import{k as w,o as he}from"./chunk-LQDAH47F.js";import{a as un}from"./chunk-FONTSK2O.js";import{c as ut}from"./chunk-6N26CWST.js";import{b as E,d as dt}from"./chunk-CU36MONI.js";import{a as T,b as C,c as y}from"./chunk-TA454OEB.js";import{a as p,b as lt,c as k}from"./chunk-OXR2FPHK.js";import{f}from"./chunk-EVIXQR4O.js";import{R as dn,S as gn}from"./chunk-OJKGRB6D.js";import{c as G,e as cn,g as ot}from"./chunk-7ASGPJWU.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-VHVWAXCF.js";import{a as ht,b as ft}from"./chunk-RC5
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-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};
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-MNW25PVU.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};
@@ -0,0 +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.3");process.exit(0)}
2
+ import{a as ne,b as oe}from"./chunk-UC3RA5LW.js";import{S as ie,i as j,p as q}from"./chunk-OJKGRB6D.js";import{c as v,e as $,g as W}from"./chunk-7ASGPJWU.js";var R,E=v(()=>{"use strict";R={dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"}});function ae(){if(V)return k!==null;try{let o=(oe(),W(ne));if(k=o.differentiableSearch,P=o.init,P)try{P()}catch{}return V=!0,!0}catch{return V=!0,!1}}function B(o){let e=0;for(let t=0;t<o.length;t++)e+=o[t]*o[t];return Math.sqrt(e)}function se(o,e,t,r){let n=t*r;if(n===0)return 0;let i=0,a=Math.min(o.length,e.length);for(let s=0;s<a;s++)i+=o[s]*e[s];return i/n}function U(o,e){let t=0,r=Math.min(o.length,e.length);for(let n=0;n<r;n++){let i=o[n]-e[n];t+=i*i}return Math.sqrt(t)}function ce(o,e){if(o.length===e)return o;let t=new Float32Array(e);if(o.length>e){let r=o.length/e;for(let n=0;n<e;n++){let i=Math.floor(n*r),a=Math.floor((n+1)*r),s=0;for(let c=i;c<a;c++)s+=o[c];t[n]=s/(a-i)}}else for(let r=0;r<o.length;r++)t[r]=o[r];return t}var k,P,V,w,O=v(()=>{"use strict";E();k=null,P=null,V=!1;w=class{config;entries=[];idToIndex=new Map;hasRuvector=!1;loaded=!1;constructor(e){this.config={...R,...e}}ensureLoaded(){this.loaded||(this.hasRuvector=ae(),this.loaded=!0)}normalizeVector(e){return e.length===this.config.dimensions?e:ce(e,this.config.dimensions)}add(e,t,r){this.ensureLoaded();let n=this.normalizeVector(t),i=B(n);if(this.idToIndex.has(e)){let s=this.idToIndex.get(e);this.entries[s]={id:e,vector:n,norm:i,metadata:r};return}let a=this.entries.length;this.entries.push({id:e,vector:n,norm:i,metadata:r}),this.idToIndex.set(e,a)}search(e,t){if(this.ensureLoaded(),this.entries.length===0)return[];let r=this.normalizeVector(e),n=B(r),i=Math.min(t,this.entries.length),a=this.entries.length>0?this.entries[0].vector.length:0,s=r.length===a;if(this.config.metric==="cosine")return this.bruteForcSearch(r,n,i);if(this.hasRuvector&&s&&k)try{let c=this.entries.map(u=>u.vector),l=k(r,c,i,1).indices.map(u=>{let h=this.entries[u],p=-U(r,h.vector);return{id:h.id,score:p,metadata:h.metadata}});return l.sort((u,h)=>h.score-u.score),l}catch{}return this.bruteForcSearch(r,n,i)}bruteForcSearch(e,t,r){let n=[];for(let i of this.entries){let a;this.config.metric==="cosine"?a=se(e,i.vector,t,i.norm):a=-U(e,i.vector),n.push({id:i.id,score:a,metadata:i.metadata})}return n.sort((i,a)=>a.score-i.score),n.slice(0,r)}remove(e){let t=this.idToIndex.get(e);if(t===void 0)return!1;let r=this.entries.length-1;if(t!==r){let n=this.entries[r];this.entries[t]=n,this.idToIndex.set(n.id,t)}return this.entries.pop(),this.idToIndex.delete(e),!0}size(){return this.entries.length}dimensions(){return this.config.dimensions}recall(){return this.hasRuvector,1}isRuvectorAvailable(){return this.ensureLoaded(),this.hasRuvector}getConfig(){return{...this.config}}clear(){this.entries=[],this.idToIndex.clear()}dispose(){this.clear()}}});import{createRequire as le}from"module";function ue(){if(K){if(A)return A;throw new b(J??"Unknown load error")}K=!0;try{let o=he("@ruvector/router");if(!o.VectorDb||!o.DistanceMetric)throw new Error("@ruvector/router module missing VectorDb or DistanceMetric exports");return A=o,A}catch(o){let e=o instanceof Error?o.message:String(o);throw J=e,new b(e)}}function D(o){let e=0;for(let t=0;t<o.length;t++)e+=o[t]*o[t];return Math.sqrt(e)}function Q(o,e,t,r){let n=t*r;if(n===0)return 0;let i=0,a=Math.min(o.length,e.length);for(let s=0;s<a;s++)i+=o[s]*e[s];return i/n}function de(o,e){if(o.length===e)return o;let t=new Float32Array(e);if(o.length>e){let r=o.length/e;for(let n=0;n<e;n++){let i=Math.floor(n*r),a=Math.floor((n+1)*r),s=0;for(let c=i;c<a;c++)s+=o[c];t[n]=s/(a-i)}}else for(let r=0;r<o.length;r++)t[r]=o[r];return t}var he,b,A,K,J,x,X=v(()=>{"use strict";E();he=le(import.meta.url),b=class extends Error{constructor(e){super(`Native HNSW backend unavailable: ${e}`),this.name="NativeHnswUnavailableError"}},A=null,K=!1,J=null;x=class{config;nativeDb=null;metadataStore=new Map;vectorStore=new Map;normStore=new Map;operationLock=Promise.resolve();highFallbackWarningEmitted=!1;_metrics={totalSearches:0,totalAdds:0,totalRemoves:0,avgSearchLatencyMs:0,maxSearchLatencyMs:0,lastSearchLatencyMs:0,fallbackSearchCount:0,bruteForceSearchCount:0,nativeSearchCount:0,fallbackRate:0,allSearchesBruteForce:!1};constructor(e){this.config={...R,...e};let t=ue(),r=this.config.metric==="cosine"?t.DistanceMetric.Cosine:t.DistanceMetric.Euclidean;try{this.nativeDb=new t.VectorDb({dimensions:this.config.dimensions,distanceMetric:r,hnswM:this.config.M,hnswEfConstruction:this.config.efConstruction,hnswEfSearch:this.config.efSearch})}catch(n){let i=n instanceof Error?n.message:String(n);throw new b(`VectorDb creation failed: ${i}`)}}add(e,t,r){let n=this.normalizeVector(t),i=D(n);if(this.vectorStore.has(e))try{this.nativeDb.delete(String(e))}catch{}this.nativeDb.insert(String(e),n),this.vectorStore.set(e,n),this.normStore.set(e,i),r&&this.metadataStore.set(e,r),this._metrics.totalAdds++}search(e,t){let r=performance.now();if(this.vectorStore.size===0)return[];let n=this.normalizeVector(e),i=D(n),a=Math.min(t,this.vectorStore.size),s;try{s=this.nativeDb.search(n,a).map(l=>{let u=Number(l.id),h=this.vectorStore.get(u),p=this.normStore.get(u)??0,g;return this.config.metric==="cosine"&&h?g=Q(n,h,i,p):g=-l.score,{id:u,score:g,metadata:this.metadataStore.get(u)}}),s.sort((l,u)=>u.score-l.score),this._metrics.nativeSearchCount++}catch{this._metrics.fallbackSearchCount++,this._metrics.bruteForceSearchCount++,console.warn(`[NativeHNSW] FALLBACK: Using brute-force linear scan (@ruvector/router search failed). Index size: ${this.vectorStore.size}`),s=this.bruteForceSearch(n,i,a)}let c=performance.now()-r;return this.updateSearchMetrics(c),this._metrics.fallbackRate=this._metrics.fallbackSearchCount/this._metrics.totalSearches,this._metrics.allSearchesBruteForce=this._metrics.nativeSearchCount===0&&this._metrics.totalSearches>0,!this.highFallbackWarningEmitted&&this._metrics.fallbackRate>.5&&this._metrics.totalSearches>=10&&(this.highFallbackWarningEmitted=!0,console.error(`[NativeHNSW] WARNING: ${(this._metrics.fallbackRate*100).toFixed(0)}% of searches are using brute-force fallback. Native HNSW may not be functioning correctly. Consider rebuilding the index or checking @ruvector/router installation.`)),c>50&&console.warn(`[NativeHNSW] search took ${c.toFixed(1)}ms (k=${t}, results=${s.length})`),s}remove(e){if(!this.vectorStore.has(e))return!1;try{this.nativeDb.delete(String(e))}catch{}return this.vectorStore.delete(e),this.normStore.delete(e),this.metadataStore.delete(e),this._metrics.totalRemoves++,!0}size(){return this.vectorStore.size}dimensions(){return this.config.dimensions}recall(){let e=this.config.efSearch/this.config.M;return e>=10?.99:e>=5?.97:e>=3?.95:.9}getMetrics(){return{...this._metrics}}get lastSearchLatencyMs(){return this._metrics.lastSearchLatencyMs}getConfig(){return{...this.config}}clear(){if(this.nativeDb){for(let e of this.vectorStore.keys())try{this.nativeDb.delete(String(e))}catch{}this.vectorStore.clear(),this.normStore.clear(),this.metadataStore.clear()}}dispose(){this.vectorStore.clear(),this.normStore.clear(),this.metadataStore.clear(),this.nativeDb=null}isNativeAvailable(){return this.nativeDb!==null}normalizeVector(e){return e.length===this.config.dimensions?e:de(e,this.config.dimensions)}updateSearchMetrics(e){this._metrics.totalSearches++,this._metrics.lastSearchLatencyMs=e,e>this._metrics.maxSearchLatencyMs&&(this._metrics.maxSearchLatencyMs=e);let t=this._metrics.totalSearches;this._metrics.avgSearchLatencyMs=this._metrics.avgSearchLatencyMs*((t-1)/t)+e/t}bruteForceSearch(e,t,r){let n=[];for(let[i,a]of this.vectorStore){let s=this.normStore.get(i)??D(a),c=this.config.metric==="cosine"?Q(e,a,t,s):-(function(){let d=0,l=Math.min(e.length,a.length);for(let u=0;u<l;u++){let h=e[u]-a[u];d+=h*h}return Math.sqrt(d)})();n.push({id:i,score:c,metadata:this.metadataStore.get(i)})}return n.sort((i,a)=>a.score-i.score),n.slice(0,r)}}});function Y(o,e){let t=Array.from({length:e},()=>new Float64Array(e));for(let r=0;r<e;r++){let n=o[r].length;t[r][r]=n;for(let i of o[r])t[r][i]=-1}return t}function F(o,e){let t=e.length,r=new Float64Array(t);for(let n=0;n<t;n++){let i=o[n].length;r[n]=i*e[n];for(let a of o[n])r[n]-=e[a]}return r}function H(o){let e=0;for(let t=0;t<o.length;t++)e+=o[t]*o[t];return Math.sqrt(e)}function I(o){let e=H(o);if(e>0)for(let t=0;t<o.length;t++)o[t]/=e}function y(o,e){let t=0;for(let r=0;r<o.length;r++)t+=o[r]*e[r];for(let r=0;r<o.length;r++)o[r]-=t*e[r]}function S(o,e,t=100,r=1e-6){if(e<=1)return 0;if(e===2)return o[0].includes(1)?2:0;let n=new Float64Array(e).fill(1/Math.sqrt(e)),i=new Float64Array(e);for(let l=0;l<e;l++)i[l]=Math.random()-.5;y(i,n),I(i);let a=0;for(let l=0;l<30;l++){let u=F(o,i);if(y(u,n),a=H(u),a>0)for(let h=0;h<e;h++)i[h]=u[h]/a}if(a<r)return 0;let s=new Float64Array(e);for(let l=0;l<e;l++)s[l]=Math.random()-.5;y(s,n),I(s);let c=0;for(let l=0;l<t;l++){let u=F(o,s),h=new Float64Array(e);for(let m=0;m<e;m++)h[m]=a*s[m]-u[m];y(h,n);let p=H(h);if(p<r)break;let g=p;for(let m=0;m<e;m++)s[m]=h[m]/p;if(Math.abs(g-c)<r)break;c=g}let d=a-c;return Math.max(0,d)}function C(o,e,t=100,r=1e-6){return S(o,e,t,r)}function N(o,e,t=50,r){if(e<=1)return 0;let n=r??S(o,e);if(n<1e-10)return 1/0;let a=2*Math.max(...o.map(d=>d.length),1),c=2*(Math.log(a/n)/(a-n));return Math.max(0,c)}function M(o,e,t){let r=1-Math.exp(-o/.05),n=1-Math.exp(-e/.5),i=t===1/0?0:1/(1+t/5),a=.4*r+.3*n+.3*i;return Math.max(0,Math.min(1,a))}var _=v(()=>{"use strict"});var te={};$(te,{ALERT_THRESHOLDS:()=>me,DEFAULT_HNSW_HEALTH_CONFIG:()=>Z,HnswHealthMonitor:()=>L,_resetNativeLoader:()=>pe,approximateFiedlerValue:()=>S,approximateSpectralGap:()=>C,buildAdjacencyFromIndex:()=>ee,buildLaplacian:()=>Y,computeCoherenceScore:()=>M,createHnswHealthMonitor:()=>be,deflateVector:()=>y,estimateEffectiveResistance:()=>N,laplacianMultiply:()=>F,normalizeInPlace:()=>I,vectorNorm:()=>H});function fe(){return z?T:(z=!0,T=null,null)}function pe(){T=null,z=!1}function ee(o,e=16,t){let r=o.size();if(r===0)return{adjacency:[],nodeCount:0,adjacencySource:"approximate"};let n=Array.from({length:r},()=>[]),i=Math.min(e,r-1);if(i===0)return{adjacency:n,nodeCount:r,adjacencySource:"approximate"};if(t&&t.size>0){let a=Array.from(t.keys()).slice(0,r),s=new Map;for(let c=0;c<a.length;c++)s.set(a[c],c);for(let c=0;c<a.length;c++){let d=t.get(a[c]);if(!d)continue;let l=o.search(d,i+1);for(let u of l){if(u.id===a[c])continue;let h=s.get(u.id);h!==void 0&&(n[c].includes(h)||n[c].push(h),n[h].includes(c)||n[h].push(c))}}return{adjacency:n,nodeCount:r,adjacencySource:"actual-search"}}console.warn("[HnswHealthMonitor] No stored vectors provided \u2014 using approximate circular adjacency. Pass stored vectors for accurate health metrics.");for(let a=0;a<r;a++)for(let s=0;s<i;s++){let c=(a+s+1)%r;n[a].includes(c)||n[a].push(c),n[c].includes(a)||n[c].push(a)}return{adjacency:n,nodeCount:r,adjacencySource:"approximate"}}function be(o){return new L(o)}var Z,me,T,z,L,re=v(()=>{"use strict";_();_();Z={fiedlerThreshold:.01,spectralGapThreshold:.1,resistanceThreshold:10,coherenceThreshold:.3,maxPowerIterations:100,convergenceTolerance:1e-6,resistanceSampleSize:50,maxHistoryEntries:200,minIndexSize:3},me={FragileIndex:.01,PoorExpansion:.1,HighResistance:10,LowCoherence:.3},T=null,z=!1;L=class{config;alerts=[];history=[];lastReport=null;useNative=!1;nativeChecked=!1;constructor(e){this.config={...Z,...e}}checkHealth(e){let t=performance.now(),r=e.size();if(r<this.config.minIndexSize)return this.createSmallIndexReport(r,performance.now()-t);this.nativeChecked||(this.nativeChecked=!0,this.useNative=fe()!==null);let{adjacency:n,nodeCount:i,adjacencySource:a}=ee(e),s=this.useNative?this.computeNativeMetrics(n):this.computeApproximateMetrics(n,i),c=this.generateAlerts(s);this.alerts.length=0,this.alerts.push(...c);let d=performance.now()-t,l={healthy:c.length===0,metrics:s,alerts:c,indexSize:r,usedNativeBackend:this.useNative,adjacencySource:a,checkDurationMs:d,checkedAt:new Date};return this.addHistoryPoint({coherenceScore:s.coherenceScore,fiedlerValue:s.fiedlerValue,indexSize:r,healthy:l.healthy,timestamp:l.checkedAt}),this.lastReport=l,l}getAlerts(){return[...this.alerts]}getMetricsHistory(e){let t=[...this.history];return e!==void 0&&e<t.length?t.slice(-e):t}isHealthy(){return this.lastReport===null?!0:this.lastReport.healthy}getLastReport(){return this.lastReport}clearHistory(){this.history.length=0,this.alerts.length=0,this.lastReport=null}computeNativeMetrics(e){let t=T,r=t.computeFiedlerValue(e),n=t.computeSpectralGap(e),i=t.computeEffectiveResistance(e),a=M(r,n,i);return{fiedlerValue:r,spectralGap:n,effectiveResistance:i,coherenceScore:a}}computeApproximateMetrics(e,t){let r=S(e,t,this.config.maxPowerIterations,this.config.convergenceTolerance),n=C(e,t,this.config.maxPowerIterations,this.config.convergenceTolerance),i=N(e,t,this.config.resistanceSampleSize,r),a=M(r,n,i);return{fiedlerValue:r,spectralGap:n,effectiveResistance:i,coherenceScore:a}}generateAlerts(e){let t=[],r=new Date;return e.fiedlerValue<this.config.fiedlerThreshold&&t.push({type:"FragileIndex",message:`Fiedler value ${e.fiedlerValue.toFixed(6)} is below threshold ${this.config.fiedlerThreshold}. The index graph has weak algebraic connectivity.`,value:e.fiedlerValue,threshold:this.config.fiedlerThreshold,timestamp:r}),e.spectralGap<this.config.spectralGapThreshold&&t.push({type:"PoorExpansion",message:`Spectral gap ${e.spectralGap.toFixed(6)} is below threshold ${this.config.spectralGapThreshold}. The index graph has poor expansion properties.`,value:e.spectralGap,threshold:this.config.spectralGapThreshold,timestamp:r}),e.effectiveResistance>this.config.resistanceThreshold&&t.push({type:"HighResistance",message:`Average effective resistance ${e.effectiveResistance.toFixed(4)} exceeds threshold ${this.config.resistanceThreshold}. Nodes are poorly connected.`,value:e.effectiveResistance,threshold:this.config.resistanceThreshold,timestamp:r}),e.coherenceScore<this.config.coherenceThreshold&&t.push({type:"LowCoherence",message:`Coherence score ${e.coherenceScore.toFixed(4)} is below threshold ${this.config.coherenceThreshold}. Overall index health is degraded.`,value:e.coherenceScore,threshold:this.config.coherenceThreshold,timestamp:r}),t}createSmallIndexReport(e,t){let r={fiedlerValue:e>0?1:0,spectralGap:e>0?1:0,effectiveResistance:e>0?.5:0,coherenceScore:e>0?1:0},n={healthy:!0,metrics:r,alerts:[],indexSize:e,usedNativeBackend:!1,adjacencySource:"approximate",checkDurationMs:t,checkedAt:new Date};return this.addHistoryPoint({coherenceScore:r.coherenceScore,fiedlerValue:r.fiedlerValue,indexSize:e,healthy:!0,timestamp:n.checkedAt}),this.lastReport=n,n}addHistoryPoint(e){this.history.push(e),this.history.length>this.config.maxHistoryEntries&&this.history.splice(0,this.history.length-this.config.maxHistoryEntries)}}});var ve={};$(ve,{HnswAdapter:()=>G});var ge,f,G,ye=v(()=>{O();X();ie();ge={patterns:{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"},"qe-memory":{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"},learning:{dimensions:384,M:16,efConstruction:200,efSearch:50,metric:"cosine"},coverage:{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"}},f=new Map,G=class o{backend;_isNativeBackend;indexName;stringToNumericId=new Map;numericToStringId=new Map;nextAutoId=0;healthMonitor=null;healthMonitorLoaded=!1;operationsSinceLastCheck=0;healthCheckFrequency=100;lastHealthReport=null;constructor(e,t){this.indexName=e;let n={...ge[e]??{},...t},{backend:i,isNative:a}=o.createBackend(n);this.backend=i,this._isNativeBackend=a}add(e,t,r){this.backend.add(e,t,r),this.maybeRunHealthCheck()}search(e,t){let r=performance.now(),n=this.backend.search(e,t),i=performance.now()-r;return i>50&&console.warn(`[HNSW] search took ${i.toFixed(1)}ms (k=${t}, results=${n.length})`),this._lastSearchLatencyMs=i,n}_lastSearchLatencyMs=0;get lastSearchLatencyMs(){return this._lastSearchLatencyMs}remove(e){return this.backend.remove(e)}size(){return this.backend.size()}dimensions(){return this.backend.dimensions()}recall(){return this.backend.recall()}addByStringId(e,t){let r=this.stringToNumericId.get(e);r!==void 0?this.backend.remove(r):(r=this.nextAutoId++,this.stringToNumericId.set(e,r),this.numericToStringId.set(r,e)),this.backend.add(r,new Float32Array(t))}searchByArray(e,t){return this.backend.search(new Float32Array(e),t).map(n=>({id:this.numericToStringId.get(n.id)??String(n.id),score:n.score}))}removeByStringId(e){let t=this.stringToNumericId.get(e);if(t===void 0)return!1;let r=this.backend.remove(t);return r&&(this.stringToNumericId.delete(e),this.numericToStringId.delete(t)),r}clear(){this.backend.clear?.(),this.stringToNumericId.clear(),this.numericToStringId.clear(),this.nextAutoId=0}dispose(){try{this.backend.dispose?.()}catch{}this.stringToNumericId.clear(),this.numericToStringId.clear(),this.nextAutoId=0}isRuvectorAvailable(){return this.backend instanceof w?this.backend.isRuvectorAvailable():this.backend instanceof x?this.backend.isNativeAvailable():!1}isNativeBackend(){return this._isNativeBackend}getName(){return this.indexName}setHealthCheckFrequency(e){this.healthCheckFrequency=Math.max(1,e)}getHealthCheckFrequency(){return this.healthCheckFrequency}getLastHealthReport(){return this.lastHealthReport}getHealthMonitor(){return this.healthMonitor}maybeRunHealthCheck(){if(q()&&(this.operationsSinceLastCheck++,!(this.operationsSinceLastCheck<this.healthCheckFrequency)&&(this.operationsSinceLastCheck=0,this.ensureHealthMonitor(),this.healthMonitor)))try{this.lastHealthReport=this.healthMonitor.checkHealth(this.backend),this.lastHealthReport.healthy||console.warn(`[HNSW-Health] Index "${this.indexName}" health check failed: ${this.lastHealthReport.alerts.length} alert(s). Coherence: ${this.lastHealthReport.metrics.coherenceScore.toFixed(3)}`)}catch(e){console.warn(`[HNSW-Health] Health check error for "${this.indexName}":`,e)}}ensureHealthMonitor(){if(!this.healthMonitorLoaded){this.healthMonitorLoaded=!0;try{let e=(re(),W(te));this.healthMonitor=e.createHnswHealthMonitor()}catch(e){process.env.DEBUG&&console.debug("[HNSW-Health] Monitor module unavailable:",e instanceof Error?e.message:e),this.healthMonitor=null}}}static createBackend(e){if(j())try{return{backend:new x(e),isNative:!0}}catch(t){t instanceof b?console.info(`[HNSW] Native backend unavailable, falling back to JS: ${t.message}`):console.warn("[HNSW] Unexpected error creating native backend, falling back to JS:",t)}return{backend:new w(e),isNative:!1}}static create(e,t){let r=f.get(e);if(r instanceof o)return r;let n=new o(e,t);return f.set(e,n),n}static get(e){let t=f.get(e);return t instanceof o?t:void 0}static close(e){let t=f.get(e);t instanceof o&&t.dispose(),f.delete(e)}static closeAll(){for(let[e]of f)o.close(e);f.clear()}static listIndexes(){return Array.from(f.keys())}}});export{G as a,ve as b,ye as c};
@@ -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.2");process.exit(0)}
2
- import{h as s,k as o,o as m}from"./chunk-GK72GUHA.js";import{a as u}from"./chunk-XIBVVZGB.js";import{c as r}from"./chunk-JOVINE23.js";import{a,e as c}from"./chunk-MN742FIH.js";m();c();u();var l=r.create("hybrid-backend"),d=class{unifiedMemory=null;config;cleanupInterval;cleanupCount=0;initialized=!1;constructor(e){this.config={sqlite:{path:e?.sqlite?.path??".agentic-qe/memory.db",walMode:e?.sqlite?.walMode??!0,poolSize:e?.sqlite?.poolSize??5,busyTimeout:e?.sqlite?.busyTimeout??a.BUSY_TIMEOUT_MS,...e?.sqlite},agentdb:{path:e?.agentdb?.path??".agentic-qe/memory.db",...e?.agentdb},enableFallback:e?.enableFallback??!0,defaultNamespace:e?.defaultNamespace??"default",cleanupInterval:e?.cleanupInterval??a.CLEANUP_INTERVAL_MS}}async initialize(){if(this.initialized)return;let e={dbPath:this.config.sqlite.path??s.dbPath,walMode:this.config.sqlite.walMode??!0,busyTimeout:this.config.sqlite.busyTimeout??a.BUSY_TIMEOUT_MS};this.unifiedMemory=o(e),await this.unifiedMemory.initialize(),this.cleanupInterval=setInterval(()=>this.cleanup(),this.config.cleanupInterval),this.cleanupInterval.unref&&this.cleanupInterval.unref(),this.initialized=!0,console.log(`[HybridBackend] Initialized with unified memory: ${this.unifiedMemory.getDbPath()}`)}async dispose(){this.cleanupInterval&&clearInterval(this.cleanupInterval),this.initialized=!1}async set(e,i,t){this.ensureInitialized();let n=t?.namespace??this.config.defaultNamespace;await this.unifiedMemory.kvSet(e,i,n,t?.ttl)}async get(e){return this.ensureInitialized(),this.unifiedMemory.kvGet(e,this.config.defaultNamespace)}async delete(e){this.ensureInitialized();let i=await this.unifiedMemory.kvDelete(e,this.config.defaultNamespace),t=await this.unifiedMemory.vectorDelete(e);return i||t}async has(e){return this.ensureInitialized(),this.unifiedMemory.kvExists(e,this.config.defaultNamespace)}async search(e,i=100){return this.ensureInitialized(),this.unifiedMemory.kvSearch(e,this.config.defaultNamespace,i)}async vectorSearch(e,i){return this.ensureInitialized(),(await this.unifiedMemory.vectorSearch(e,i)).map(n=>({key:n.id,score:n.score,metadata:n.metadata}))}async storeVector(e,i,t){this.ensureInitialized(),await this.unifiedMemory.vectorStore(e,i,this.config.defaultNamespace,t)}getHealth(){return{sqlite:this.unifiedMemory?.isInitialized()?"healthy":"unavailable",sqlitePersistent:!0,agentdb:this.unifiedMemory?.isInitialized()?"healthy":"unavailable",fallback:"inactive"}}isPersistent(){return this.unifiedMemory?.isInitialized()??!1}getConfig(){return{...this.config}}async setWithBackend(e,i,t,n){await this.set(e,i,n)}async getVectorStats(){if(!this.unifiedMemory?.isInitialized())return null;let e=await this.unifiedMemory.vectorCount(),i=this.unifiedMemory.getStats();return{vectorCount:e,indexSize:i.vectorIndexSize}}getUnifiedMemory(){return this.unifiedMemory}async count(e){return this.ensureInitialized(),this.unifiedMemory.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.3");process.exit(0)}
2
+ import{h as s,k as o,o as m}from"./chunk-LQDAH47F.js";import{a as u}from"./chunk-FONTSK2O.js";import{c as r}from"./chunk-6N26CWST.js";import{a,e as c}from"./chunk-TPFE3BAI.js";m();c();u();var l=r.create("hybrid-backend"),d=class{unifiedMemory=null;config;cleanupInterval;cleanupCount=0;initialized=!1;constructor(e){this.config={sqlite:{path:e?.sqlite?.path??".agentic-qe/memory.db",walMode:e?.sqlite?.walMode??!0,poolSize:e?.sqlite?.poolSize??5,busyTimeout:e?.sqlite?.busyTimeout??a.BUSY_TIMEOUT_MS,...e?.sqlite},agentdb:{path:e?.agentdb?.path??".agentic-qe/memory.db",...e?.agentdb},enableFallback:e?.enableFallback??!0,defaultNamespace:e?.defaultNamespace??"default",cleanupInterval:e?.cleanupInterval??a.CLEANUP_INTERVAL_MS}}async initialize(){if(this.initialized)return;let e={dbPath:this.config.sqlite.path??s.dbPath,walMode:this.config.sqlite.walMode??!0,busyTimeout:this.config.sqlite.busyTimeout??a.BUSY_TIMEOUT_MS};this.unifiedMemory=o(e),await this.unifiedMemory.initialize(),this.cleanupInterval=setInterval(()=>this.cleanup(),this.config.cleanupInterval),this.cleanupInterval.unref&&this.cleanupInterval.unref(),this.initialized=!0,console.log(`[HybridBackend] Initialized with unified memory: ${this.unifiedMemory.getDbPath()}`)}async dispose(){this.cleanupInterval&&clearInterval(this.cleanupInterval),this.initialized=!1}async set(e,i,t){this.ensureInitialized();let n=t?.namespace??this.config.defaultNamespace;await this.unifiedMemory.kvSet(e,i,n,t?.ttl)}async get(e){return this.ensureInitialized(),this.unifiedMemory.kvGet(e,this.config.defaultNamespace)}async delete(e){this.ensureInitialized();let i=await this.unifiedMemory.kvDelete(e,this.config.defaultNamespace),t=await this.unifiedMemory.vectorDelete(e);return i||t}async has(e){return this.ensureInitialized(),this.unifiedMemory.kvExists(e,this.config.defaultNamespace)}async search(e,i=100){return this.ensureInitialized(),this.unifiedMemory.kvSearch(e,this.config.defaultNamespace,i)}async vectorSearch(e,i){return this.ensureInitialized(),(await this.unifiedMemory.vectorSearch(e,i)).map(n=>({key:n.id,score:n.score,metadata:n.metadata}))}async storeVector(e,i,t){this.ensureInitialized(),await this.unifiedMemory.vectorStore(e,i,this.config.defaultNamespace,t)}getHealth(){return{sqlite:this.unifiedMemory?.isInitialized()?"healthy":"unavailable",sqlitePersistent:!0,agentdb:this.unifiedMemory?.isInitialized()?"healthy":"unavailable",fallback:"inactive"}}isPersistent(){return this.unifiedMemory?.isInitialized()??!1}getConfig(){return{...this.config}}async setWithBackend(e,i,t,n){await this.set(e,i,n)}async getVectorStats(){if(!this.unifiedMemory?.isInitialized())return null;let e=await this.unifiedMemory.vectorCount(),i=this.unifiedMemory.getStats();return{vectorCount:e,indexSize:i.vectorIndexSize}}getUnifiedMemory(){return this.unifiedMemory}async count(e){return this.ensureInitialized(),this.unifiedMemory.getDatabase().prepare(`
3
3
  SELECT COUNT(*) as count FROM kv_store
4
4
  WHERE namespace LIKE ?
5
5
  AND (expires_at IS NULL OR expires_at > ?)