agentic-qe 3.15.14 → 3.15.16
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.
- package/.claude/agents/v3/templates/qx-report-template.html +1 -1
- package/.claude/skills/skills-manifest.json +1 -1
- package/CHANGELOG.md +136 -0
- package/assets/agents/v3/templates/qx-report-template.html +1 -1
- package/assets/skills/skills-manifest.json +1 -1
- package/dist/audit/witness-chain.d.ts +7 -0
- package/dist/audit/witness-chain.js +10 -0
- package/dist/cli/bundle.js +6 -6
- package/dist/cli/chunks/adapter-6CQ2PIP5.js +2 -0
- package/dist/cli/chunks/agent-booster-wasm-45NWEKVS.js +2 -0
- package/dist/cli/chunks/{agent-handler-P3IY7XEE.js → agent-handler-LVHMYFEF.js} +2 -2
- package/dist/cli/chunks/{agent-memory-branch-WWKC2H3G.js → agent-memory-branch-YDWOJFEQ.js} +2 -2
- package/dist/cli/chunks/aqe-learning-engine-73RR52VS.js +2 -0
- package/dist/cli/chunks/{arena-EIV5OALF.js → arena-CZKHXDDS.js} +2 -2
- package/dist/cli/chunks/{arena-4BMFF6BS.js → arena-ELDZH3CZ.js} +4 -4
- package/dist/cli/chunks/{audit-DNTI453H.js → audit-5MT4T47Z.js} +3 -3
- package/dist/cli/chunks/base-SMCMMVGP.js +2 -0
- package/dist/cli/chunks/{better-sqlite3-TQBQGNC6.js → better-sqlite3-6TGYPC2B.js} +2 -2
- package/dist/cli/chunks/{brain-handler-HY57CNAO.js → brain-handler-HQWZFO52.js} +3 -3
- package/dist/cli/chunks/{branch-enumerator-THPMZPHQ.js → branch-enumerator-WVILM4SO.js} +2 -2
- package/dist/cli/chunks/{browser-O6JJOZCK.js → browser-RX5ALU3H.js} +2 -2
- package/dist/cli/chunks/browser-workflow-A2MEZ66K.js +2 -0
- package/dist/cli/chunks/{chunk-CIINJHOX.js → chunk-24OX5TQJ.js} +1 -1
- package/dist/cli/chunks/{chunk-6P4Q4RTC.js → chunk-24QHCVX6.js} +1 -1
- package/dist/cli/chunks/{chunk-U6IOQKCT.js → chunk-2H4XH6FT.js} +2 -2
- package/dist/cli/chunks/{chunk-OGEIHS76.js → chunk-2YZ4G6NW.js} +1 -1
- package/dist/cli/chunks/chunk-32BPDLRZ.js +27 -0
- package/dist/cli/chunks/{chunk-5PLBQZ5J.js → chunk-32GN3JKR.js} +1 -1
- package/dist/cli/chunks/{chunk-AJVLVF7V.js → chunk-3HD7E6HN.js} +2 -2
- package/dist/cli/chunks/{chunk-X7CUI7KH.js → chunk-4D4DENG6.js} +2 -2
- package/dist/cli/chunks/{chunk-E2JLAW3U.js → chunk-4LQFBY5L.js} +6 -6
- package/dist/cli/chunks/{chunk-E3QIQMMN.js → chunk-4NFQLP6R.js} +1 -1
- package/dist/cli/chunks/{chunk-7Y3LXH57.js → chunk-525CFDUE.js} +2 -2
- package/dist/cli/chunks/chunk-5B5QPCNU.js +65 -0
- package/dist/cli/chunks/{chunk-X6Q2N5S5.js → chunk-5JZRZI4S.js} +2 -2
- package/dist/cli/chunks/{chunk-MB4UKUBV.js → chunk-5LAVKGLH.js} +2 -2
- package/dist/cli/chunks/chunk-5NNNEWLS.js +755 -0
- package/dist/cli/chunks/{chunk-NKOLILT7.js → chunk-5PBLPQ5T.js} +2 -2
- package/dist/cli/chunks/chunk-5QO3R3TU.js +6 -0
- package/dist/cli/chunks/{chunk-7T6L3LFN.js → chunk-5SPCGMBB.js} +2 -2
- package/dist/cli/chunks/{chunk-2QLE6NDW.js → chunk-5V3TI2LG.js} +1 -1
- package/dist/cli/chunks/{chunk-A2T56XVL.js → chunk-5VZL4UVN.js} +2 -2
- package/dist/cli/chunks/{chunk-TWOV3I3A.js → chunk-63GMRQ25.js} +1 -1
- package/dist/cli/chunks/{chunk-YGOSSVY5.js → chunk-63ZKI4PX.js} +6 -6
- package/dist/cli/chunks/{chunk-FHPNWHY7.js → chunk-67Z5R7RJ.js} +2 -2
- package/dist/cli/chunks/{chunk-PCQZIAXB.js → chunk-6DPYNAOK.js} +2 -2
- package/dist/cli/chunks/{chunk-WCM6WE7G.js → chunk-6ICX3FEG.js} +3 -3
- package/dist/cli/chunks/{chunk-JB7R77SH.js → chunk-6XXZDV2C.js} +2 -2
- package/dist/cli/chunks/{chunk-FJOIBZUB.js → chunk-6ZBXSOX6.js} +2 -2
- package/dist/cli/chunks/{chunk-WZQADC5R.js → chunk-72XSEQMW.js} +2 -2
- package/dist/cli/chunks/{chunk-AYLEH2UF.js → chunk-7TE5ONQQ.js} +1 -1
- package/dist/cli/chunks/{chunk-7QUSNBAA.js → chunk-A5GBXCP5.js} +2 -2
- package/dist/cli/chunks/{chunk-7724KXM2.js → chunk-AAMLQ2LF.js} +3 -3
- package/dist/cli/chunks/chunk-AG2EWGXS.js +21 -0
- package/dist/cli/chunks/{chunk-2UZBLC5H.js → chunk-AGRV5B3T.js} +2 -2
- package/dist/cli/chunks/{chunk-V6SE2ZU2.js → chunk-AJMJNQMP.js} +1 -1
- package/dist/cli/chunks/{chunk-2HPNGK7A.js → chunk-AR67RJPY.js} +2 -2
- package/dist/cli/chunks/{chunk-G7HGUQAE.js → chunk-ASEOFRIG.js} +2 -2
- package/dist/cli/chunks/{chunk-7TH4PJSU.js → chunk-BEKDKVQT.js} +2 -2
- package/dist/cli/chunks/{chunk-M5JEA6ZY.js → chunk-BY5OF7OH.js} +2 -2
- package/dist/cli/chunks/{chunk-OLUOVNUF.js → chunk-C5FP5GW3.js} +2 -2
- package/dist/cli/chunks/{chunk-R5RRWLRI.js → chunk-C6D5AHBO.js} +2 -2
- package/dist/cli/chunks/{chunk-K7GFYFBO.js → chunk-CAKMOVZ6.js} +2 -2
- package/dist/cli/chunks/{chunk-6NIGSY5L.js → chunk-CEYSYSK5.js} +2 -2
- package/dist/cli/chunks/{chunk-U4TML2VD.js → chunk-CGGUM2YJ.js} +2 -2
- package/dist/cli/chunks/{chunk-YE54T2NQ.js → chunk-CJSHWQXP.js} +2 -2
- package/dist/cli/chunks/{chunk-7SQTLUEN.js → chunk-CRPIYUTJ.js} +2 -2
- package/dist/cli/chunks/{chunk-65EE2EST.js → chunk-D6COXLYE.js} +2 -2
- package/dist/cli/chunks/{chunk-4WLIOPHX.js → chunk-DTMAS2GB.js} +2 -2
- package/dist/cli/chunks/{chunk-E7QTWGPI.js → chunk-DVYHMDFR.js} +470 -411
- package/dist/cli/chunks/chunk-DXD6K2ZP.js +3 -0
- package/dist/cli/chunks/{chunk-HSDWPQQY.js → chunk-E3D4GPLP.js} +3 -3
- package/dist/cli/chunks/{chunk-JJHLGGPP.js → chunk-EA4YQVKS.js} +1 -1
- package/dist/cli/chunks/{chunk-EIEEST4T.js → chunk-EGYE5UPQ.js} +2 -2
- package/dist/cli/chunks/{chunk-O756AOUX.js → chunk-EK7OLYOZ.js} +2 -2
- package/dist/cli/chunks/{chunk-57DRT6UA.js → chunk-F742SZAX.js} +2 -2
- package/dist/cli/chunks/{chunk-6OI5SK7M.js → chunk-FBDVGRSC.js} +1 -1
- package/dist/cli/chunks/{chunk-H3C5FJRH.js → chunk-FDDC72IA.js} +2 -2
- package/dist/cli/chunks/{chunk-IQRPR4KB.js → chunk-FL64OUBA.js} +2 -2
- package/dist/cli/chunks/{chunk-BNG4J3CE.js → chunk-FLNAW7C4.js} +2 -2
- package/dist/cli/chunks/{chunk-C3OIBFAA.js → chunk-G5RHFBAY.js} +2 -2
- package/dist/cli/chunks/{chunk-NPCXGX7N.js → chunk-GAHNO6JJ.js} +2 -2
- package/dist/cli/chunks/{chunk-PNRPVQGI.js → chunk-GFWHUQSF.js} +2 -2
- package/dist/cli/chunks/{chunk-OCN53CCK.js → chunk-GJYHWYXR.js} +2 -2
- package/dist/cli/chunks/{chunk-5Z4MO2F3.js → chunk-GQ6TUIKY.js} +1 -1
- package/dist/cli/chunks/{chunk-N736GLWZ.js → chunk-GSKMOPL7.js} +2 -2
- package/dist/cli/chunks/{chunk-43XHGWYH.js → chunk-HCH4Y6XX.js} +2 -2
- package/dist/cli/chunks/{chunk-QP6GL3O5.js → chunk-HGWXF45W.js} +1 -1
- package/dist/cli/chunks/{chunk-PGN4TARY.js → chunk-HJ6ZGVTB.js} +2 -2
- package/dist/cli/chunks/{chunk-M2TG7VDK.js → chunk-HLUXXCHF.js} +1 -1
- package/dist/cli/chunks/{chunk-UMHFTQTR.js → chunk-HVRRLYX6.js} +4 -4
- package/dist/cli/chunks/{chunk-L7PC675Y.js → chunk-I7MQIM2U.js} +1 -1
- package/dist/cli/chunks/{chunk-JSSU4RIK.js → chunk-IESR7TNB.js} +2 -2
- package/dist/cli/chunks/{chunk-H4LYXLAT.js → chunk-IHRXZZQM.js} +1 -1
- package/dist/cli/chunks/{chunk-HV43NX4A.js → chunk-IOKYCMTJ.js} +6 -6
- package/dist/cli/chunks/{chunk-NZQYJCO6.js → chunk-IOQ6ZQ5W.js} +1 -1
- package/dist/cli/chunks/{chunk-JO26SG47.js → chunk-IOYG4VFL.js} +2 -2
- package/dist/cli/chunks/{chunk-6O63ZTVX.js → chunk-IUBJVHNB.js} +2 -2
- package/dist/cli/chunks/{chunk-XSPMLJCQ.js → chunk-J442IZLE.js} +1 -1
- package/dist/cli/chunks/{chunk-LTGQJYYO.js → chunk-J4ELZNLY.js} +2 -2
- package/dist/cli/chunks/chunk-J7I6PABJ.js +153 -0
- package/dist/cli/chunks/chunk-JDIYMZCQ.js +2 -0
- package/dist/cli/chunks/{chunk-TOJF3ZG4.js → chunk-JHQCRRJI.js} +2 -2
- package/dist/cli/chunks/{chunk-QUZ745UQ.js → chunk-JQ3DYUMS.js} +2 -2
- package/dist/cli/chunks/{chunk-P2TPH3TC.js → chunk-KITOPKRG.js} +2 -2
- package/dist/cli/chunks/{chunk-QNQE3EOH.js → chunk-KKU2QGSJ.js} +2 -2
- package/dist/cli/chunks/chunk-KL7OKSU2.js +4 -0
- package/dist/cli/chunks/{chunk-L5VSLPMW.js → chunk-KNSRL6NO.js} +2 -2
- package/dist/cli/chunks/{chunk-INGXD5IX.js → chunk-KPRCB5LT.js} +2 -2
- package/dist/cli/chunks/{chunk-GY4P7KAI.js → chunk-KQYJ4VQ5.js} +1 -1
- package/dist/cli/chunks/{chunk-Z2S7DNFP.js → chunk-KU2AUFGX.js} +2 -2
- package/dist/cli/chunks/{chunk-O5CEL447.js → chunk-KVF4NXGQ.js} +2 -2
- package/dist/cli/chunks/{chunk-2IJO3657.js → chunk-KXCLACFG.js} +2 -2
- package/dist/cli/chunks/{chunk-ZJGFQK27.js → chunk-L2DWPVNJ.js} +1 -1
- package/dist/cli/chunks/{chunk-E7OR6V3V.js → chunk-L6QSTQME.js} +2 -2
- package/dist/cli/chunks/{chunk-RE6JTSDM.js → chunk-LE4QJREF.js} +1 -1
- package/dist/cli/chunks/{chunk-DSQESXL4.js → chunk-LKTTUHLF.js} +2 -2
- package/dist/cli/chunks/{chunk-YGC5QKQ4.js → chunk-LQLPB2T6.js} +2 -2
- package/dist/cli/chunks/{chunk-VGZOPQQY.js → chunk-LRSX2FJM.js} +1 -1
- package/dist/cli/chunks/chunk-M4FRQ4TE.js +12 -0
- package/dist/cli/chunks/chunk-M7WJCTG3.js +2 -0
- package/dist/cli/chunks/{chunk-56NSE3LJ.js → chunk-MAFQV4U4.js} +2 -2
- package/dist/cli/chunks/{chunk-MKYOE7NE.js → chunk-MD43XRX5.js} +1 -1
- package/dist/cli/chunks/{chunk-3TF27MG5.js → chunk-MI5MFHRA.js} +2 -2
- package/dist/cli/chunks/{chunk-JK6PMLQQ.js → chunk-MO55CVMT.js} +32 -32
- package/dist/cli/chunks/{chunk-X6NJOT3V.js → chunk-N7HL5PHH.js} +1 -1
- package/dist/cli/chunks/chunk-NAEWCFQT.js +14 -0
- package/dist/cli/chunks/{chunk-WUGXXNK4.js → chunk-NDJ7P2EP.js} +1 -1
- package/dist/cli/chunks/{chunk-D5GB5PUU.js → chunk-NO3IV5Q5.js} +1 -1
- package/dist/cli/chunks/{chunk-3XACRXBY.js → chunk-NQXXI77K.js} +2 -2
- package/dist/cli/chunks/{chunk-EC65UZ77.js → chunk-NVEWF4JV.js} +1 -1
- package/dist/cli/chunks/{chunk-JI67T6Q2.js → chunk-NZU4ACBZ.js} +2 -2
- package/dist/cli/chunks/chunk-O5W3FIO6.js +63 -0
- package/dist/cli/chunks/{chunk-YEFTK4HD.js → chunk-OAEE6JWQ.js} +2 -2
- package/dist/cli/chunks/{chunk-JAOCHPYX.js → chunk-OCV2XEWQ.js} +2 -2
- package/dist/cli/chunks/{chunk-IDBA5GK2.js → chunk-P3EYRILV.js} +2 -2
- package/dist/cli/chunks/{chunk-4RPBODN5.js → chunk-PEQDY4BO.js} +2 -2
- package/dist/cli/chunks/{chunk-CPPYZYXC.js → chunk-PF7RBAYL.js} +2 -2
- package/dist/cli/chunks/{chunk-WCPSR4MJ.js → chunk-PHT5N7SC.js} +2 -2
- package/dist/cli/chunks/{chunk-O2AAYJUV.js → chunk-PINSJCM3.js} +1 -1
- package/dist/cli/chunks/{chunk-HEDGFKC5.js → chunk-PPUZWYUG.js} +2 -2
- package/dist/cli/chunks/{chunk-XMCSKYDE.js → chunk-QPEOLAAS.js} +1 -1
- package/dist/cli/chunks/{chunk-7MUO4DEH.js → chunk-QQWBWEJS.js} +18 -18
- package/dist/cli/chunks/{chunk-UFP7SN5V.js → chunk-QVDCVD5D.js} +2 -2
- package/dist/cli/chunks/{chunk-NHEG2DLN.js → chunk-RJIEG3NA.js} +2 -2
- package/dist/cli/chunks/{chunk-KJ5A54ZH.js → chunk-RV74I3YO.js} +2 -2
- package/dist/cli/chunks/{chunk-UDSB3XCG.js → chunk-S75SOOZL.js} +2 -2
- package/dist/cli/chunks/{chunk-BPDAQB3F.js → chunk-SASBO5Y5.js} +2 -2
- package/dist/cli/chunks/{chunk-VJBJRFUO.js → chunk-SDLWKRVL.js} +9 -9
- package/dist/cli/chunks/{chunk-J6ASX536.js → chunk-SHKOCGNK.js} +2 -2
- package/dist/cli/chunks/{chunk-J35JWDJE.js → chunk-SI6DPU5D.js} +1 -1
- package/dist/cli/chunks/{chunk-V3MGY76S.js → chunk-SJ6Y4725.js} +2 -2
- package/dist/cli/chunks/{chunk-FTYRPEJS.js → chunk-SR52XP5F.js} +1 -1
- package/dist/cli/chunks/{chunk-ZUE524JL.js → chunk-SSUAAX3F.js} +2 -2
- package/dist/cli/chunks/{chunk-VG32EEUG.js → chunk-SSYAQZXA.js} +2 -2
- package/dist/cli/chunks/{chunk-HTVGHHX2.js → chunk-SUDMM5SO.js} +2 -2
- package/dist/cli/chunks/{chunk-K2SMP4OD.js → chunk-TIUKLYAI.js} +1 -1
- package/dist/cli/chunks/{chunk-VCVRZD4Y.js → chunk-TVGI32MB.js} +33 -33
- package/dist/cli/chunks/{chunk-CAZM63TP.js → chunk-U2A7NHZA.js} +2 -2
- package/dist/cli/chunks/{chunk-WBC6WB32.js → chunk-UE5ZOZR2.js} +2 -2
- package/dist/cli/chunks/{chunk-BQJ7CV53.js → chunk-UHEOGZLX.js} +12 -12
- package/dist/cli/chunks/chunk-UNGBRZDK.js +12 -0
- package/dist/cli/chunks/{chunk-XN3KCKAM.js → chunk-V5NHZV7S.js} +2 -2
- package/dist/cli/chunks/{chunk-UNYTHZDZ.js → chunk-VJCIEHEF.js} +1 -1
- package/dist/cli/chunks/{chunk-5Y7UFHJD.js → chunk-VMDFFTCK.js} +1 -1
- package/dist/cli/chunks/chunk-VSIKHWZ4.js +29 -0
- package/dist/cli/chunks/{chunk-UPWLMIDY.js → chunk-VWPM27GU.js} +2 -2
- package/dist/cli/chunks/{chunk-USAKCGHC.js → chunk-VXFLJNCA.js} +2 -2
- package/dist/cli/chunks/{chunk-WKI46WWN.js → chunk-W5HQUIML.js} +2 -2
- package/dist/cli/chunks/{chunk-Z54G2YOL.js → chunk-WP4RETKG.js} +2 -2
- package/dist/cli/chunks/{chunk-IRPNEXOU.js → chunk-XIIQ5QTT.js} +2 -2
- package/dist/cli/chunks/{chunk-O32BFQV4.js → chunk-XIQW7EFL.js} +2 -2
- package/dist/cli/chunks/{chunk-TW6Z6W4X.js → chunk-XWUWX7BV.js} +13 -13
- package/dist/cli/chunks/{chunk-57FX3GP6.js → chunk-Y4PFUMOU.js} +1 -1
- package/dist/cli/chunks/chunk-YAPLJR7K.js +2 -0
- package/dist/cli/chunks/{chunk-4T7XV5KQ.js → chunk-YLMNVLDK.js} +1 -1
- package/dist/cli/chunks/{chunk-TSP6SU5V.js → chunk-YNMJEDN5.js} +2 -2
- package/dist/cli/chunks/{chunk-PWQWKYBG.js → chunk-YPBSUGMI.js} +1 -1
- package/dist/cli/chunks/{chunk-QP2HLKTS.js → chunk-YRAX7SFJ.js} +2 -2
- package/dist/cli/chunks/{chunk-O3ERGUXH.js → chunk-YTHTQPWR.js} +1 -1
- package/dist/cli/chunks/{chunk-MR2OPUSA.js → chunk-YU2BDRSD.js} +1 -1
- package/dist/cli/chunks/chunk-ZB3LEFYG.js +2 -0
- package/dist/cli/chunks/{chunk-2W5MQDHM.js → chunk-ZFL436FN.js} +2 -2
- package/dist/cli/chunks/{chunk-7MISCSL5.js → chunk-ZJH5MU2I.js} +2 -2
- package/dist/cli/chunks/{chunk-52KOPIMI.js → chunk-ZQ2XW3IP.js} +2 -2
- package/dist/cli/chunks/chunk-ZR2TKVXQ.js +14 -0
- package/dist/cli/chunks/{ci-UMA2SMNW.js → ci-MFUR4CWV.js} +2 -2
- package/dist/cli/chunks/{ci-config-UQSILJFQ.js → ci-config-PNDLQ6XV.js} +2 -2
- package/dist/cli/chunks/{ci-output-U6YZLLKH.js → ci-output-PFZ4M7NC.js} +2 -2
- package/dist/cli/chunks/{circuit-breaker-ATYQP6X2.js → circuit-breaker-5HH6NLZN.js} +2 -2
- package/dist/cli/chunks/{claude-flow-setup-6YHFD7AN.js → claude-flow-setup-QCKYLGLC.js} +2 -2
- package/dist/cli/chunks/client-MHQRTZM4.js +2 -0
- package/dist/cli/chunks/{cline-installer-EPE7IOZE.js → cline-installer-EASVPFXR.js} +2 -2
- package/dist/cli/chunks/{code-NUEJ4XYO.js → code-UJXDVYRK.js} +4 -3
- package/dist/cli/chunks/{code-index-extractor-D4DBT6OL.js → code-index-extractor-BZJ3UDP4.js} +2 -2
- package/dist/cli/chunks/{codex-installer-633SM4LR.js → codex-installer-XSQZUVOZ.js} +4 -4
- package/dist/cli/chunks/{completions-WUKVIW3L.js → completions-OWOOJFI2.js} +2 -2
- package/dist/cli/chunks/{complexity-analyzer-F73ACR5H.js → complexity-analyzer-KP5TOHDT.js} +2 -2
- package/dist/cli/chunks/{continuedev-installer-QH42TKMS.js → continuedev-installer-IFKQXLHM.js} +2 -2
- package/dist/cli/chunks/{copilot-installer-Y3XC7BTT.js → copilot-installer-IGJ6KGQY.js} +2 -2
- package/dist/cli/chunks/core-handlers-UAK3LLJE.js +2 -0
- package/dist/cli/chunks/{cost-tracker-57QPV7E3.js → cost-tracker-MMDDNKZB.js} +2 -2
- package/dist/cli/chunks/{coverage-IBCHMBCR.js → coverage-LUH2B7NT.js} +3 -3
- package/dist/cli/chunks/cross-domain-router-WTRZQPNQ.js +2 -0
- package/dist/cli/chunks/{cursor-installer-F4UYQHIN.js → cursor-installer-4YLM5GWM.js} +2 -2
- package/dist/cli/chunks/daemon-CAVZ7OFV.js +18 -0
- package/dist/cli/chunks/{daemon-XR4Q6YZF.js → daemon-MZKVM4CJ.js} +3 -3
- package/dist/cli/chunks/{dag-attention-scheduler-ZR5ZD3TW.js → dag-attention-scheduler-X4CYW665.js} +2 -2
- package/dist/cli/chunks/{detect-GEGYURLL.js → detect-7BM2XINO.js} +2 -2
- package/dist/cli/chunks/{dist-node-JU3KT2JO.js → dist-node-Y5APLEYB.js} +2 -2
- package/dist/cli/chunks/{domain-handler-7QI3FJGE.js → domain-handler-X3ZRJNAH.js} +2 -2
- package/dist/cli/chunks/{domain-plugins-O2YRM2PD.js → domain-plugins-2UW5KQJB.js} +2 -2
- package/dist/cli/chunks/{domain-transfer-7J3S2OS6.js → domain-transfer-35W4CIBV.js} +2 -2
- package/dist/cli/chunks/dream-EJY24JN6.js +2 -0
- package/dist/cli/chunks/embed-and-insert-pattern-COG4C7ZI.js +3 -0
- package/dist/cli/chunks/embedding-space-SBM2MZD2.js +2 -0
- package/dist/cli/chunks/{eval-RVMCIUOR.js → eval-4QA2SROK.js} +2 -2
- package/dist/cli/chunks/experience-capture-middleware-Z6BF6KYM.js +40 -0
- package/dist/cli/chunks/{fast-paths-QUKPKWKZ.js → fast-paths-FIORX6GN.js} +2 -2
- package/dist/cli/chunks/{feature-flags-K7JXNKJI.js → feature-flags-6LYI2T4G.js} +2 -2
- package/dist/cli/chunks/{feature-flags-5JCSKL2P.js → feature-flags-ZOO7LMIC.js} +2 -2
- package/dist/cli/chunks/file-discovery-UZSFSS4V.js +2 -0
- package/dist/cli/chunks/{fleet-II4Q6HXK.js → fleet-7WF53H4F.js} +3 -3
- package/dist/cli/chunks/{gnn-wrapper-M7VO2EMS.js → gnn-wrapper-KJ6B7BRM.js} +2 -2
- package/dist/cli/chunks/{heartbeat-handler-ND5CY26N.js → heartbeat-handler-DEKKMOVW.js} +4 -4
- package/dist/cli/chunks/heartbeat-scheduler-NVR356I7.js +2 -0
- package/dist/cli/chunks/hnsw-adapter-LFMPLUJU.js +2 -0
- package/dist/cli/chunks/hnsw-index-POCPMVJH.js +2 -0
- package/dist/cli/chunks/{hnsw-legacy-bridge-N3AUUUU7.js → hnsw-legacy-bridge-L27WS27N.js} +2 -2
- package/dist/cli/chunks/{hnswlib-node-NZY3E5EN.js → hnswlib-node-4YOQC6L4.js} +2 -2
- package/dist/cli/chunks/{hooks-QVJDTII5.js → hooks-TAOKV4EJ.js} +23 -22
- package/dist/cli/chunks/hybrid-backend-4STAO7CV.js +2 -0
- package/dist/cli/chunks/{hypergraph-engine-ZRY6MTDV.js → hypergraph-engine-BODRJLHL.js} +2 -2
- package/dist/cli/chunks/{hypergraph-handler-56DO4XZQ.js → hypergraph-handler-RKMYJNTU.js} +3 -3
- package/dist/cli/chunks/impact-analyzer-3VIIISBQ.js +2 -0
- package/dist/cli/chunks/{init-guard-DTF4EVUY.js → init-guard-MXHSLSB2.js} +2 -2
- package/dist/cli/chunks/{init-handler-M6CNQHMX.js → init-handler-HUE57IFW.js} +6 -6
- package/dist/cli/chunks/init-wizard-PL6QN6RQ.js +2 -0
- package/dist/cli/chunks/kernel-CCDWT7KS.js +2 -0
- package/dist/cli/chunks/{kilocode-installer-IJN7XKBH.js → kilocode-installer-S333IKYQ.js} +2 -2
- package/dist/cli/chunks/{kiro-installer-UKKPGPDC.js → kiro-installer-WM5DLQWC.js} +2 -2
- package/dist/cli/chunks/knowledge-graph-KFOMEN3H.js +2 -0
- package/dist/cli/chunks/{learning-W2HETWQ4.js → learning-LNHMQLH5.js} +3 -3
- package/dist/cli/chunks/{llm-router-Y546K4VX.js → llm-router-EWFXYZZR.js} +4 -4
- package/dist/cli/chunks/llm-router-service-7NBE2EX6.js +2 -0
- package/dist/cli/chunks/{load-MKAB2AXE.js → load-FGYGWVDK.js} +2 -2
- package/dist/cli/chunks/load-test-UNZUWY3F.js +2 -0
- package/dist/cli/chunks/{mcp-AZKUS6K3.js → mcp-2FHNAAOM.js} +2 -2
- package/dist/cli/chunks/{memory-ZDOQN2KU.js → memory-DZMQ73AB.js} +5 -5
- package/dist/cli/chunks/memory-backend-DFGKWA2Q.js +2 -0
- package/dist/cli/chunks/memory-handlers-MP426XRJ.js +2 -0
- package/dist/cli/chunks/{multi-model-executor-WWVXDHG4.js → multi-model-executor-6F2UAEUW.js} +2 -2
- package/dist/cli/chunks/{opencode-installer-YUJNXXWS.js → opencode-installer-XY3BGOTZ.js} +2 -2
- package/dist/cli/chunks/{orchestrator-Z6PWPLRE.js → orchestrator-B4CNKUOS.js} +17 -17
- package/dist/cli/chunks/pattern-null-store-SSVF5TE5.js +2 -0
- package/dist/cli/chunks/{pattern-usage-recorder-TPWPX32U.js → pattern-usage-recorder-R4GUFNMD.js} +2 -2
- package/dist/cli/chunks/{pipeline-4BBGTE4M.js → pipeline-FG5RKVRO.js} +2 -2
- package/dist/cli/chunks/{platform-5GSHXCV5.js → platform-3BT4KEVJ.js} +2 -2
- package/dist/cli/chunks/{plugin-OFDVF5HS.js → plugin-WI4RIN7O.js} +2 -2
- package/dist/cli/chunks/{prime-radiant-advanced-wasm-NC6MUYGJ.js → prime-radiant-advanced-wasm-7ECDNQFS.js} +2 -2
- package/dist/cli/chunks/project-root-BEANNYWU.js +2 -0
- package/dist/cli/chunks/protocol-executor-FQVIHXZ7.js +2 -0
- package/dist/cli/chunks/{protocol-handler-MPOAAEPA.js → protocol-handler-WNODKPGW.js} +2 -2
- package/dist/cli/chunks/{prove-CDKMAIVM.js → prove-5RHAEPYZ.js} +2 -2
- package/dist/cli/chunks/qe-reasoning-bank-5TFYSE24.js +2 -0
- package/dist/cli/chunks/{quality-ZH4F7R7R.js → quality-WPHR7BGQ.js} +2 -2
- package/dist/cli/chunks/{quality-gate-IDRMW6OE.js → quality-gate-4RKTEZMX.js} +3 -3
- package/dist/cli/chunks/queen-coordinator-Y2OUL7IN.js +2 -0
- package/dist/cli/chunks/real-embeddings-OXLYU7JW.js +2 -0
- package/dist/cli/chunks/{ref-validation-Z5GCGVXK.js → ref-validation-TPAWHOHH.js} +2 -2
- package/dist/cli/chunks/{roocode-installer-IZ2S7PH2.js → roocode-installer-7AVHFNDI.js} +2 -2
- package/dist/cli/chunks/router-EP34O3KB.js +2 -0
- package/dist/cli/chunks/routing-feedback-FJCRKXNG.js +2 -0
- package/dist/cli/chunks/{routing-handler-NAX35VUW.js → routing-handler-YKEDVJSH.js} +2 -2
- package/dist/cli/chunks/{ruvector-commands-5YW2SOFF.js → ruvector-commands-JUAMM354.js} +2 -2
- package/dist/cli/chunks/rvf-dual-writer-ILITJSFG.js +2 -0
- package/dist/cli/chunks/rvf-migration-adapter-XF6W4C2N.js +2 -0
- package/dist/cli/chunks/rvf-migration-coordinator-CMKG56AR.js +2 -0
- package/dist/cli/chunks/rvf-native-adapter-7YFW6S4Y.js +2 -0
- package/dist/cli/chunks/{rvf-store-integrity-IPGCAT6C.js → rvf-store-integrity-VJDUIRTX.js} +2 -2
- package/dist/cli/chunks/safe-db-TCAU4FUT.js +2 -0
- package/dist/cli/chunks/schedule-NB5KV435.js +2 -0
- package/dist/cli/chunks/scheduler-JKXGKVK6.js +2 -0
- package/dist/cli/chunks/{security-3IH4BO5Z.js → security-ORDN3RD2.js} +3 -3
- package/dist/cli/chunks/{shared-rvf-adapter-ABY7PAY2.js → shared-rvf-adapter-CF4BCIO7.js} +2 -2
- package/dist/cli/chunks/{shared-rvf-dual-writer-6KENLN2W.js → shared-rvf-dual-writer-C32UBR6D.js} +2 -2
- package/dist/cli/chunks/sqlite-persistence-IXCNZRTW.js +2 -0
- package/dist/cli/chunks/{standalone-memory-RLFAUGOW.js → standalone-memory-OXRJYZXN.js} +2 -2
- package/dist/cli/chunks/{status-handler-FCOZBPE5.js → status-handler-BCX5D4HY.js} +2 -2
- package/dist/cli/chunks/{structural-health-4RDA5UUM.js → structural-health-LFG7RUU6.js} +2 -2
- package/dist/cli/chunks/sync-OSF7C2NL.js +2 -0
- package/dist/cli/chunks/{sync-KGEEXXCC.js → sync-YJEE2K2L.js} +2 -2
- package/dist/cli/chunks/task-handler-6LXKPTXJ.js +64 -0
- package/dist/cli/chunks/{task-handlers-6H7L2UT4.js → task-handlers-CILP36I7.js} +4 -4
- package/dist/cli/chunks/{test-S7IG6EIX.js → test-SD457QJ6.js} +4 -4
- package/dist/cli/chunks/test-runner-process-VKD65QQU.js +2 -0
- package/dist/cli/chunks/{test-scheduling-7XYXI4L2.js → test-scheduling-ISI2O4Q5.js} +3 -3
- package/dist/cli/chunks/token-bootstrap-VUELSBOS.js +2 -0
- package/dist/cli/chunks/{token-usage-Y2YTPOFE.js → token-usage-XOC5KG7S.js} +2 -2
- package/dist/cli/chunks/{transformers-UCJ3HHHC.js → transformers-LSLQAARK.js} +2 -2
- package/dist/cli/chunks/tree-sitter-wasm-parser-YAIPHRIL.js +2 -0
- package/dist/cli/chunks/{types-6CMFPETH.js → types-5BLCGLCR.js} +2 -2
- package/dist/cli/chunks/unified-memory-GI76TXFV.js +2 -0
- package/dist/cli/chunks/unified-memory-hnsw-GXJ5BTZO.js +2 -0
- package/dist/cli/chunks/unified-persistence-OP7FDQPD.js +2 -0
- package/dist/cli/chunks/{upgrade-K25DN6WU.js → upgrade-RQJYLK3J.js} +2 -2
- package/dist/cli/chunks/{validate-T4V3TBY3.js → validate-QBHWXXCK.js} +2 -2
- package/dist/cli/chunks/{validate-swarm-XSRC576T.js → validate-swarm-IKXBKFB5.js} +2 -2
- package/dist/cli/chunks/visual-security-GZ2MOKWB.js +2 -0
- package/dist/cli/chunks/{web-tree-sitter-YOZXHRTN.js → web-tree-sitter-ZF6FIE5R.js} +2 -2
- package/dist/cli/chunks/{windsurf-installer-ITPU2IYL.js → windsurf-installer-HQGDZT5D.js} +2 -2
- package/dist/cli/chunks/witness-chain-DCHCAMSQ.js +2 -0
- package/dist/cli/chunks/witness-chain-P3XXXA62.js +2 -0
- package/dist/cli/chunks/witness-chain-repair-PUX2NFDL.js +2 -0
- package/dist/cli/chunks/{witness-chain-verifier-DTDSVKOG.js → witness-chain-verifier-PX2OQ6XT.js} +2 -2
- package/dist/cli/chunks/{witness-key-manager-EWACWGAW.js → witness-key-manager-RXYQNFJB.js} +2 -2
- package/dist/cli/chunks/{workflow-ZIQ4FV42.js → workflow-FBKCA4H6.js} +4 -4
- package/dist/cli/chunks/workflow-orchestrator-P2APAJAA.js +2 -0
- package/dist/cli/chunks/wrappers-TWSKBTWD.js +2 -0
- package/dist/cli/commands/code.js +4 -0
- package/dist/cli/commands/hooks-handlers/hooks-dream-learning.js +10 -2
- package/dist/cli/handlers/task-handler.d.ts +5 -0
- package/dist/cli/handlers/task-handler.js +21 -1
- package/dist/cli/utils/task-result.d.ts +11 -0
- package/dist/cli/utils/task-result.js +39 -0
- package/dist/coordination/handlers/test-execution-handlers.js +92 -58
- package/dist/coordination/mincut/mincut-persistence.js +29 -25
- package/dist/domains/code-intelligence/coordinator.d.ts +4 -0
- package/dist/domains/code-intelligence/coordinator.js +46 -13
- package/dist/domains/code-intelligence/interfaces.d.ts +10 -1
- package/dist/domains/code-intelligence/services/semantic-analyzer.d.ts +32 -7
- package/dist/domains/code-intelligence/services/semantic-analyzer.js +112 -53
- package/dist/domains/learning-optimization/services/learning-coordinator.js +1 -1
- package/dist/domains/quality-assessment/coordinator.js +2 -1
- package/dist/domains/test-execution/coordinator.js +10 -5
- package/dist/domains/test-execution/interfaces.d.ts +12 -0
- package/dist/domains/test-execution/plugin.js +6 -2
- package/dist/domains/test-execution/services/retry-handler.d.ts +2 -0
- package/dist/domains/test-execution/services/retry-handler.js +14 -9
- package/dist/domains/test-execution/services/test-executor.d.ts +1 -0
- package/dist/domains/test-execution/services/test-executor.js +28 -9
- package/dist/domains/visual-accessibility/coordinator.d.ts +15 -7
- package/dist/domains/visual-accessibility/coordinator.js +15 -7
- package/dist/domains/visual-accessibility/interfaces.d.ts +27 -3
- package/dist/domains/visual-accessibility/services/accessibility-contrast.d.ts +39 -0
- package/dist/domains/visual-accessibility/services/accessibility-contrast.js +93 -0
- package/dist/domains/visual-accessibility/services/accessibility-tester-browser.d.ts +18 -3
- package/dist/domains/visual-accessibility/services/accessibility-tester-browser.js +50 -40
- package/dist/domains/visual-accessibility/services/accessibility-tester-checks.d.ts +27 -0
- package/dist/domains/visual-accessibility/services/accessibility-tester-checks.js +137 -0
- package/dist/domains/visual-accessibility/services/accessibility-tester.d.ts +5 -0
- package/dist/domains/visual-accessibility/services/accessibility-tester.js +43 -24
- package/dist/domains/visual-accessibility/services/browser-swarm-coordinator.d.ts +2 -3
- package/dist/domains/visual-accessibility/services/browser-swarm-coordinator.js +8 -14
- package/dist/feedback/coverage-learner.js +13 -9
- package/dist/feedback/test-outcome-tracker.js +13 -9
- package/dist/governance/witness-chain.d.ts +5 -0
- package/dist/governance/witness-chain.js +22 -6
- package/dist/init/init-wizard-hooks.d.ts +1 -1
- package/dist/init/init-wizard-hooks.js +7 -8
- package/dist/init/phases/08-mcp.js +9 -0
- package/dist/init/settings-merge.d.ts +13 -0
- package/dist/init/settings-merge.js +49 -2
- package/dist/integrations/agent-booster-wasm/agent_booster_wasm.js +849 -0
- package/dist/integrations/agent-booster-wasm/agent_booster_wasm_bg.wasm +0 -0
- package/dist/integrations/agent-booster-wasm/index.d.ts +8 -0
- package/dist/integrations/agent-booster-wasm/index.js +25 -2
- package/dist/integrations/agent-booster-wasm/package.json +16 -0
- package/dist/integrations/agentic-flow/reasoning-bank/experience-replay.d.ts +22 -0
- package/dist/integrations/agentic-flow/reasoning-bank/experience-replay.js +115 -45
- package/dist/integrations/agentic-flow/reasoning-bank/pattern-evolution.d.ts +6 -0
- package/dist/integrations/agentic-flow/reasoning-bank/pattern-evolution.js +51 -33
- package/dist/integrations/agentic-flow/reasoning-bank/trajectory-tracker.js +17 -9
- package/dist/integrations/embeddings/cache/EmbeddingCache.d.ts +8 -0
- package/dist/integrations/embeddings/cache/EmbeddingCache.js +24 -10
- package/dist/integrations/ruvector/delta-tracker.d.ts +11 -0
- package/dist/integrations/ruvector/delta-tracker.js +16 -0
- package/dist/integrations/ruvector/sona-persistence.d.ts +10 -0
- package/dist/integrations/ruvector/sona-persistence.js +49 -24
- package/dist/kernel/unified-memory.d.ts +24 -0
- package/dist/kernel/unified-memory.js +63 -8
- package/dist/learning/aqe-learning-engine.js +1 -1
- package/dist/learning/dream/dream-engine.d.ts +3 -2
- package/dist/learning/dream/dream-engine.js +42 -24
- package/dist/learning/dream/dream-lock-retry.d.ts +38 -0
- package/dist/learning/dream/dream-lock-retry.js +66 -0
- package/dist/learning/dream/speculative-dreamer.js +1 -1
- package/dist/learning/embed-and-insert-pattern.js +4 -2
- package/dist/learning/embedder-endpoint-client.d.ts +31 -0
- package/dist/learning/embedder-endpoint-client.js +103 -10
- package/dist/learning/embedding-space.d.ts +12 -0
- package/dist/learning/embedding-space.js +17 -0
- package/dist/learning/experience-capture-middleware.js +25 -13
- package/dist/learning/experience-capture.js +1 -1
- package/dist/learning/experience-consolidation.d.ts +18 -0
- package/dist/learning/experience-consolidation.js +55 -8
- package/dist/learning/experience-space-verification.d.ts +71 -0
- package/dist/learning/experience-space-verification.js +147 -0
- package/dist/learning/pattern-lifecycle.d.ts +40 -4
- package/dist/learning/pattern-lifecycle.js +153 -76
- package/dist/learning/pattern-null-store.d.ts +5 -0
- package/dist/learning/pattern-null-store.js +8 -0
- package/dist/learning/pattern-promotion.js +6 -3
- package/dist/learning/pattern-store.d.ts +6 -0
- package/dist/learning/pattern-store.js +19 -6
- package/dist/learning/qe-reasoning-bank.js +2 -2
- package/dist/learning/real-embeddings.js +3 -1
- package/dist/learning/real-qe-reasoning-bank.d.ts +5 -0
- package/dist/learning/real-qe-reasoning-bank.js +77 -47
- package/dist/learning/rvf-pattern-store.js +6 -2
- package/dist/learning/sqlite-persistence.d.ts +6 -0
- package/dist/learning/sqlite-persistence.js +10 -0
- package/dist/mcp/bundle.js +642 -571
- package/dist/mcp/entry.js +4 -0
- package/dist/mcp/handlers/domain-handler-configs.js +2 -0
- package/dist/mcp/handlers/trajectory-judge.js +1 -1
- package/dist/mcp/protocol-server.js +1 -0
- package/dist/mcp/tools/visual-accessibility/index.js +8 -2
- package/dist/mcp/types.d.ts +6 -0
- package/dist/optimization/session-cache.d.ts +17 -1
- package/dist/optimization/session-cache.js +40 -36
- package/dist/planning/goap-planner.d.ts +6 -0
- package/dist/planning/goap-planner.js +35 -19
- package/dist/planning/plan-executor.js +24 -15
- package/dist/routing/co-execution-repository.js +12 -9
- package/dist/routing/routing-feedback.d.ts +8 -0
- package/dist/routing/routing-feedback.js +46 -24
- package/dist/routing/routing-outcomes-migration.js +7 -2
- package/dist/shared/llm/spend-ledger.d.ts +9 -0
- package/dist/shared/llm/spend-ledger.js +64 -39
- package/dist/shared/sqlite-lock-wait.d.ts +27 -0
- package/dist/shared/sqlite-lock-wait.js +37 -0
- package/dist/shared/sqlite-write-queue.d.ts +28 -0
- package/dist/shared/sqlite-write-queue.js +38 -0
- package/dist/shared/test-runner-project.d.ts +69 -0
- package/dist/shared/test-runner-project.js +186 -0
- package/dist/skills/security-visual-testing/index.d.ts +3 -1
- package/dist/skills/security-visual-testing/index.js +49 -35
- package/dist/skills/security-visual-testing/types.d.ts +19 -3
- package/dist/workers/workers/heartbeat-scheduler.js +5 -5
- package/dist/workers/workers/learning-consolidation.js +8 -7
- package/package.json +4 -2
- package/dist/cli/chunks/adapter-23KA2YW7.js +0 -2
- package/dist/cli/chunks/agent-booster-wasm-2DLAEZK6.js +0 -2
- package/dist/cli/chunks/aqe-learning-engine-MUICAXW5.js +0 -2
- package/dist/cli/chunks/base-XPWGYDKD.js +0 -2
- package/dist/cli/chunks/browser-workflow-UMQVBVGK.js +0 -2
- package/dist/cli/chunks/chunk-3FITMWWJ.js +0 -21
- package/dist/cli/chunks/chunk-ARRBXCII.js +0 -4
- package/dist/cli/chunks/chunk-BBYJBZHG.js +0 -14
- package/dist/cli/chunks/chunk-BM3EJLMV.js +0 -153
- package/dist/cli/chunks/chunk-D3ZZ2NLL.js +0 -62
- package/dist/cli/chunks/chunk-DLTB5KCR.js +0 -2
- package/dist/cli/chunks/chunk-DRLSJJIC.js +0 -6
- package/dist/cli/chunks/chunk-HAYKLXCT.js +0 -744
- package/dist/cli/chunks/chunk-HHBF2BZC.js +0 -65
- package/dist/cli/chunks/chunk-K7RT6ITZ.js +0 -2
- package/dist/cli/chunks/chunk-L752CNG3.js +0 -13
- package/dist/cli/chunks/chunk-MQXWG55U.js +0 -12
- package/dist/cli/chunks/chunk-WM2QRIRD.js +0 -14
- package/dist/cli/chunks/chunk-WRC3HLUY.js +0 -29
- package/dist/cli/chunks/chunk-XTZGAG6P.js +0 -27
- package/dist/cli/chunks/chunk-YKQWIXUY.js +0 -2
- package/dist/cli/chunks/client-E43GWLQH.js +0 -2
- package/dist/cli/chunks/core-handlers-R5A3SQDY.js +0 -2
- package/dist/cli/chunks/cross-domain-router-LLYVPZF6.js +0 -2
- package/dist/cli/chunks/daemon-BYYPIJ7G.js +0 -18
- package/dist/cli/chunks/dream-6C4NURSE.js +0 -2
- package/dist/cli/chunks/embed-and-insert-pattern-URES5Q6J.js +0 -3
- package/dist/cli/chunks/experience-capture-middleware-SYJQSBKE.js +0 -40
- package/dist/cli/chunks/file-discovery-J5IE5KP7.js +0 -2
- package/dist/cli/chunks/heartbeat-scheduler-FC5PBTMN.js +0 -2
- package/dist/cli/chunks/hnsw-adapter-47UIVOBG.js +0 -2
- package/dist/cli/chunks/hnsw-index-3AKVLOZQ.js +0 -2
- package/dist/cli/chunks/hybrid-backend-YAOSNX47.js +0 -2
- package/dist/cli/chunks/impact-analyzer-4FMJXM4M.js +0 -2
- package/dist/cli/chunks/init-wizard-RTLCRWDT.js +0 -2
- package/dist/cli/chunks/kernel-2OWIGGGT.js +0 -2
- package/dist/cli/chunks/knowledge-graph-25XXKDJN.js +0 -2
- package/dist/cli/chunks/llm-router-service-G3EIN4UB.js +0 -2
- package/dist/cli/chunks/load-test-D6QYNIVT.js +0 -2
- package/dist/cli/chunks/memory-backend-LDFFZMEQ.js +0 -2
- package/dist/cli/chunks/memory-handlers-3SQVY7FE.js +0 -2
- package/dist/cli/chunks/pattern-null-store-KDVRM7PW.js +0 -2
- package/dist/cli/chunks/project-root-DDGBWDP6.js +0 -2
- package/dist/cli/chunks/protocol-executor-KBOLLCWA.js +0 -2
- package/dist/cli/chunks/qe-reasoning-bank-GRXBT7FC.js +0 -2
- package/dist/cli/chunks/queen-coordinator-L2QWMJ5Q.js +0 -2
- package/dist/cli/chunks/real-embeddings-I2UVNNB3.js +0 -2
- package/dist/cli/chunks/router-FT5WJPUH.js +0 -2
- package/dist/cli/chunks/routing-feedback-EO2MKOUX.js +0 -2
- package/dist/cli/chunks/rvf-dual-writer-WHBFQJVU.js +0 -2
- package/dist/cli/chunks/rvf-migration-adapter-YT3APF2I.js +0 -2
- package/dist/cli/chunks/rvf-migration-coordinator-VUIZHTVG.js +0 -2
- package/dist/cli/chunks/rvf-native-adapter-37PUFKQD.js +0 -2
- package/dist/cli/chunks/safe-db-TDZKUOZJ.js +0 -2
- package/dist/cli/chunks/schedule-CRKTRY2A.js +0 -2
- package/dist/cli/chunks/scheduler-6ZBDVQWN.js +0 -2
- package/dist/cli/chunks/sqlite-persistence-FFJQAIKW.js +0 -2
- package/dist/cli/chunks/sync-54LUAUTK.js +0 -2
- package/dist/cli/chunks/task-handler-K3OXHYKU.js +0 -62
- package/dist/cli/chunks/test-runner-process-OTQDAJLN.js +0 -2
- package/dist/cli/chunks/token-bootstrap-3QMABE45.js +0 -2
- package/dist/cli/chunks/tree-sitter-wasm-parser-D6JTTHTP.js +0 -2
- package/dist/cli/chunks/unified-memory-QARWQKJ2.js +0 -2
- package/dist/cli/chunks/unified-memory-hnsw-LHY3DXCP.js +0 -2
- package/dist/cli/chunks/unified-persistence-WEYYGLHM.js +0 -2
- package/dist/cli/chunks/visual-security-O4ALMCXQ.js +0 -2
- package/dist/cli/chunks/witness-chain-B3YW5NMS.js +0 -2
- package/dist/cli/chunks/witness-chain-PIYR72HJ.js +0 -2
- package/dist/cli/chunks/witness-chain-repair-YUG7E3UX.js +0 -2
- package/dist/cli/chunks/workflow-orchestrator-3ZN2BCGY.js +0 -2
- package/dist/cli/chunks/wrappers-PW2O27LL.js +0 -2
|
@@ -1,26 +1,26 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{b as Ee}from"./chunk-XSPMLJCQ.js";import{a as St}from"./chunk-6P4Q4RTC.js";import{a as bt,b as kt}from"./chunk-4RPBODN5.js";import{a as vt,b as Ct}from"./chunk-X7CUI7KH.js";import{j as _}from"./chunk-YGC5QKQ4.js";import{a as ht}from"./chunk-TWOV3I3A.js";import{a as yt,b as xe,c as Tt}from"./chunk-WCPSR4MJ.js";import{a as Ae}from"./chunk-JJHLGGPP.js";import{b as ft}from"./chunk-X6NJOT3V.js";import{r as R,v as De}from"./chunk-JK6PMLQQ.js";import{b as I,d as mt}from"./chunk-XN3KCKAM.js";import{a as pt,e as Dn}from"./chunk-UDSB3XCG.js";import{i as C}from"./chunk-QP6GL3O5.js";import{a as v,c as y,d as f}from"./chunk-RE6JTSDM.js";import{a as Sn}from"./chunk-YKQWIXUY.js";import{c as gt}from"./chunk-C3OIBFAA.js";import{R as bn,S as kn}from"./chunk-E7OR6V3V.js";import{a as h,b as Z,e as k}from"./chunk-L5VSLPMW.js";import{b as Y,d as Cn,f as dt}from"./chunk-V6SE2ZU2.js";function Et(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&&(En.includes(s.domain)?(t+=30,e.push({name:"complex-domain",weight:30,description:`Domain '${s.domain}' requires complex reasoning`})):wn.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=>Mn.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=In[n];return{complexity:n,recommendedModel:i,factors:e,score:t,timestamp:new Date}}var En,wn,Mn,S,In,wt=Y(()=>{"use strict";En=["security-compliance","chaos-resilience","defect-intelligence"],wn=["code-intelligence","contract-testing","quality-assessment","learning-optimization"],Mn=["sast","dast","vulnerability","owasp","chaos-testing","resilience","fault-injection","mutation-testing"],S={critical:70,complex:45,moderate:20},In={critical:"opus",complex:"sonnet",moderate:"sonnet",simple:"haiku"}});var P,Re=Y(()=>{"use strict";P=class{weightsInputHidden;weightsHiddenOutput;biasHidden;biasOutput;learningRate;constructor(e=.01){this.learningRate=e,this.weightsInputHidden=this.xavierInit(4,32),this.weightsHiddenOutput=this.xavierInit(32,3),this.biasHidden=new Float32Array(32),this.biasOutput=new Float32Array(3)}xavierInit(e,t){let n=Math.sqrt(2/(e+t)),i=new Float32Array(e*t);for(let r=0;r<i.length;r++){let a=Math.random(),o=Math.random(),l=Math.sqrt(-2*Math.log(Math.max(a,1e-10)))*Math.cos(2*Math.PI*o);i[r]=l*n}return i}forward(e){if(e.length!==4)throw new Error(`Expected 4 features, got ${e.length}`);let t=new Float32Array(32);for(let i=0;i<32;i++){let r=this.biasHidden[i];for(let a=0;a<4;a++)r+=e[a]*this.weightsInputHidden[a*32+i];t[i]=Math.max(0,r)}let n=new Float32Array(3);for(let i=0;i<3;i++){let r=this.biasOutput[i];for(let a=0;a<32;a++)r+=t[a]*this.weightsHiddenOutput[a*3+i];n[i]=r}return this.softmax(n)}softmax(e){let t=Math.max(...e),n=new Float32Array(e.length),i=0;for(let a=0;a<e.length;a++)n[a]=Math.exp(e[a]-t),i+=n[a];let r=[];for(let a=0;a<e.length;a++)r.push(n[a]/i);return r}updateWeights(e,t,n){let i=new Float32Array(32);for(let c=0;c<32;c++){let u=this.biasHidden[c];for(let d=0;d<4;d++)u+=e[d]*this.weightsInputHidden[d*32+c];i[c]=Math.max(0,u)}let r=new Float32Array(3);for(let c=0;c<3;c++){let u=this.biasOutput[c];for(let d=0;d<32;d++)u+=i[d]*this.weightsHiddenOutput[d*3+c];r[c]=u}let a=this.softmax(r),o=new Float32Array(3);for(let c=0;c<3;c++)o[c]=(c===t?1:0)-a[c],o[c]*=n*this.learningRate;for(let c=0;c<32;c++)for(let u=0;u<3;u++)this.weightsHiddenOutput[c*3+u]+=i[c]*o[u];for(let c=0;c<3;c++)this.biasOutput[c]+=o[c];let l=new Float32Array(32);for(let c=0;c<32;c++){if(i[c]<=0)continue;let u=0;for(let d=0;d<3;d++)u+=o[d]*this.weightsHiddenOutput[c*3+d];l[c]=u}for(let c=0;c<4;c++)for(let u=0;u<32;u++)this.weightsInputHidden[c*32+u]+=e[c]*l[u];for(let c=0;c<32;c++)this.biasHidden[c]+=l[c]}serialize(){return{weightsInputHidden:Array.from(this.weightsInputHidden),weightsHiddenOutput:Array.from(this.weightsHiddenOutput),biasHidden:Array.from(this.biasHidden),biasOutput:Array.from(this.biasOutput)}}deserialize(e){e.weightsInputHidden.length===128&&(this.weightsInputHidden=new Float32Array(e.weightsInputHidden)),e.weightsHiddenOutput.length===96&&(this.weightsHiddenOutput=new Float32Array(e.weightsHiddenOutput)),e.biasHidden.length===32&&(this.biasHidden=new Float32Array(e.biasHidden)),e.biasOutput.length===3&&(this.biasOutput=new Float32Array(e.biasOutput))}}});var It={};Cn(It,{NeuralTinyDancerRouter:()=>J,SimpleNeuralRouter:()=>P,createNeuralTinyDancerRouter:()=>Qn});import{performance as Mt}from"perf_hooks";function Qn(s){return new J(s)}var Rn,_n,Pn,Fn,Hn,On,Nn,Ln,J,Rt=Y(()=>{"use strict";_e();Re();Re();Rn=1e3,_n=.1,Pn=.2,Fn=50,Hn=.01,On=["haiku","sonnet","opus"],Nn={haiku:0,sonnet:1,opus:2},Ln={"test-generation":.1,"test-execution":.15,"coverage-analysis":.2,"quality-assessment":.3,"requirements-validation":.35,"code-intelligence":.4,"contract-testing":.45,"visual-accessibility":.5,"learning-optimization":.55,"defect-intelligence":.7,"chaos-resilience":.8,"security-compliance":.9},J=class{ruleRouter;neuralNet;circuitBreakerThreshold;shadowModeDecisionLimit;shadowModeMaxDisagreement;shadowModeActive;shadowDecisions=[];shadowDisagreements=0;circuitBreakerTripped=!1;recentOutcomes=[];totalNeuralDecisions=0;totalWeightUpdates=0;neuralPrimary=!1;calibrationScores=[];maxCalibrationScores=500;domainSuccessRates=new Map;config;nativeRouterAvailable=!1;constructor(e={}){this.config=e,this.ruleRouter=new L(e),this.neuralNet=new P(e.learningRate??Hn),this.circuitBreakerThreshold=e.circuitBreakerThreshold??Pn,this.shadowModeDecisionLimit=e.shadowModeDecisions??Rn,this.shadowModeMaxDisagreement=e.shadowModeMaxDisagreement??_n,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=Mt.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=On[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=Mt.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=Ln[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>Fn&&this.recentOutcomes.shift(),this.checkCircuitBreaker();let c=this.extractFeatures(e,t.classification),u=Nn[r],d=(i-.5)*2;try{this.neuralNet.updateWeights(c,u,d),this.totalWeightUpdates++}catch{}let g=this.neuralNet.forward(c),p=this.argmax(g),T=1-g[u];this.calibrationScores.push(T),this.calibrationScores.length>this.maxCalibrationScores&&this.calibrationScores.shift()}computeEmpiricalConfidenceBounds(e){let n=Math.max(...e),i=1-n;if(this.calibrationScores.length<10)return{lower:0,upper:1,coverageLevel:.9,calibrationScore:i};let r=[...this.calibrationScores].sort((l,c)=>l-c),a=Math.ceil(.9*r.length)-1,o=r[Math.min(a,r.length-1)];return{lower:Math.max(0,n-o),upper:Math.min(1,n+o),coverageLevel:.9,calibrationScore:i}}computeConformalBounds(e){return this.computeEmpiricalConfidenceBounds(e)}evaluateShadowModeExit(){if(!this.shadowModeActive||this.config.forceShadowMode===!0)return;let e=this.shadowDecisions.length;if(e<this.shadowModeDecisionLimit)return;this.shadowDisagreements/e<=this.shadowModeMaxDisagreement&&(this.shadowModeActive=!1,this.neuralPrimary=!0)}checkCircuitBreaker(){if(this.recentOutcomes.length<10)return;let t=this.recentOutcomes.filter(n=>!n).length/this.recentOutcomes.length;t>this.circuitBreakerThreshold?this.tripCircuitBreaker():this.circuitBreakerTripped&&t<this.circuitBreakerThreshold*.5&&(this.circuitBreakerTripped=!1)}tripCircuitBreaker(){this.circuitBreakerTripped=!0,this.neuralPrimary=!1}buildNeuralReasoning(e,t,n,i,r){let a=[];return a.push(`[Neural] Routing to ${e.toUpperCase()}`),a.push(`with ${(t*100).toFixed(0)}% neural confidence.`),a.push(`Tier probabilities: haiku=${(n[0]*100).toFixed(0)}%,`),a.push(`sonnet=${(n[1]*100).toFixed(0)}%,`),a.push(`opus=${(n[2]*100).toFixed(0)}%.`),e!==i.model&&a.push(`Rule-based would choose ${i.model.toUpperCase()}.`),a.push(`Empirical bounds: [${r.lower.toFixed(2)}, ${r.upper.toFixed(2)}]`),a.push(`at ${(r.coverageLevel*100).toFixed(0)}% coverage.`),a.join(" ")}argmax(e){let t=0,n=e[0];for(let i=1;i<e.length;i++)e[i]>n&&(n=e[i],t=i);return t}getNeuralStats(){let e=this.shadowDecisions.length,t=e>0?this.shadowDisagreements/e:0,n=this.recentOutcomes.filter(r=>!r).length,i=this.recentOutcomes.length>0?n/this.recentOutcomes.length:0;return{shadowModeActive:this.shadowModeActive,shadowDecisions:e,disagreementRate:t,circuitBreakerTripped:this.circuitBreakerTripped,recentErrorRate:i,totalNeuralDecisions:this.totalNeuralDecisions,totalWeightUpdates:this.totalWeightUpdates,neuralPrimary:this.neuralPrimary}}getShadowDecisionLogs(){return this.shadowDecisions}getRuleRouter(){return this.ruleRouter}getNeuralNet(){return this.neuralNet}isNativeRouterAvailable(){return this.nativeRouterAvailable}isShadowModeActive(){return this.shadowModeActive}isNeuralPrimary(){return this.neuralPrimary}isCircuitBreakerTripped(){return this.circuitBreakerTripped}resetCircuitBreaker(){this.circuitBreakerTripped=!1,this.recentOutcomes=[]}getStats(){return this.ruleRouter.getStats()}getConfig(){return this.ruleRouter.getConfig()}reset(){this.ruleRouter.reset(),this.shadowDecisions=[],this.shadowDisagreements=0,this.circuitBreakerTripped=!1,this.recentOutcomes=[],this.totalNeuralDecisions=0,this.totalWeightUpdates=0,this.calibrationScores=[],this.domainSuccessRates.clear(),this.config.forceShadowMode!==void 0?(this.shadowModeActive=this.config.forceShadowMode,this.neuralPrimary=!this.config.forceShadowMode):(this.shadowModeActive=!0,this.neuralPrimary=!1)}}});import{performance as _t}from"perf_hooks";function Pt(s){try{let{getRuVectorFeatureFlags:e}=(kn(),dt(bn));if(e().useNeuralRouting){let{NeuralTinyDancerRouter:n}=(Rt(),dt(It));return new n(s)}}catch(e){process.env.DEBUG&&console.debug("[Router] Neural router unavailable, using rule-based:",e instanceof Error?e.message:e)}return new L(s)}var L,_e=Y(()=>{"use strict";wt();L=class{confidenceThreshold;uncertaintyThreshold;securityConfidenceThreshold;enableLearning;verbose;executor;totalRouted=0;routesByModel={haiku:0,sonnet:0,opus:0};routesByComplexity={simple:0,moderate:0,complex:0,critical:0};multiModelTriggers=0;humanReviewTriggers=0;advisorConsultations=0;totalConfidence=0;totalLatencyMs=0;outcomes=[];maxOutcomes=1e3;constructor(e={}){this.confidenceThreshold=e.confidenceThreshold??.8,this.uncertaintyThreshold=e.uncertaintyThreshold??.2,this.securityConfidenceThreshold=e.securityConfidenceThreshold??.85,this.enableLearning=e.enableLearning??!0,this.verbose=e.verbose??!1,this.executor=e.executor}hasExecutor(){return this.executor!==void 0}async routeWithAdvisor(e,t){let n=await this.route(e);if(!n.triggerMultiModel||!this.executor||!t)return{route:n};let i=await this.executor.consult(t,{agentName:e.agentId??e.id??"unknown",triggerReason:`tiny_dancer.confidence=${n.confidence.toFixed(2)}<${this.confidenceThreshold}`});return this.advisorConsultations++,{route:n,advisor:i}}async route(e){let t=_t.now(),n=Et(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=_t.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,advisorConsultations:this.advisorConsultations,humanReviewTriggers:this.humanReviewTriggers,avgConfidence:this.totalRouted>0?this.totalConfidence/this.totalRouted:0,avgLatencyMs:this.totalRouted>0?this.totalLatencyMs/this.totalRouted:0,outcomesRecorded:this.outcomes.length}}getOutcomes(){return this.outcomes}getSuccessRateByModel(){let e={haiku:{success:0,total:0},sonnet:{success:0,total:0},opus:{success:0,total:0}};for(let t of this.outcomes){let n=t.actualModelUsed;e[n].total++,t.success&&e[n].success++}return{haiku:e.haiku.total>0?e.haiku.success/e.haiku.total:0,sonnet:e.sonnet.total>0?e.sonnet.success/e.sonnet.total:0,opus:e.opus.total>0?e.opus.success/e.opus.total:0}}reset(){this.totalRouted=0,this.routesByModel={haiku:0,sonnet:0,opus:0},this.routesByComplexity={simple:0,moderate:0,complex:0,critical:0},this.multiModelTriggers=0,this.advisorConsultations=0,this.humanReviewTriggers=0,this.totalConfidence=0,this.totalLatencyMs=0,this.outcomes=[]}getConfig(){return{confidenceThreshold:this.confidenceThreshold,uncertaintyThreshold:this.uncertaintyThreshold,securityConfidenceThreshold:this.securityConfidenceThreshold,enableLearning:this.enableLearning,verbose:this.verbose}}}});import{randomUUID as Dt}from"node:crypto";var An={enableConsoleLog:!0,maxEntries:1e3,logPrefix:"[TASK]"},X=class{entries=[];config;generation=Dt();recordedEntries=0;droppedEntries=0;constructor(e={}){if(this.config={...An,...e},!Number.isSafeInteger(this.config.maxEntries)||this.config.maxEntries<0)throw new RangeError("maxEntries must be a non-negative safe integer")}log(e,t,n){let i={sequence:++this.recordedEntries,timestamp:new Date,operation:e,taskId:t,agentId:n?.agentId,domain:n?.domain,details:n?.details};if(this.entries.push(i),this.entries.length>this.config.maxEntries){let r=this.entries.length-this.config.maxEntries;this.entries.splice(0,r),this.droppedEntries+=r}if(this.config.enableConsoleLog){let r=n?.agentId?` by ${n.agentId}`:"",a=n?.domain?` (${n.domain})`:"";console.log(`${this.config.logPrefix} ${e.toUpperCase()} ${t}${r}${a}`)}}logSubmit(e,t){this.log("submit",e,{details:t})}logAssign(e,t,n){this.log("assign",e,{agentId:t,domain:n})}logReassign(e,t,n,i){this.log("reassign",e,{agentId:n,domain:i,details:{fromAgent:t}})}logComplete(e,t){this.log("complete",e,{agentId:t})}logFail(e,t,n){this.log("fail",e,{agentId:t,details:n?{error:n}:void 0})}logCancel(e){this.log("cancel",e)}logSteal(e,t,n){this.log("steal",e,{domain:n,details:{fromDomain:t}})}logQueue(e,t){this.log("queue",e,{details:{position:t}})}logDequeue(e){this.log("dequeue",e)}getEntries(e){let t=[...this.entries];e&&(e.operation&&(t=t.filter(i=>i.operation===e.operation)),e.taskId&&(t=t.filter(i=>i.taskId===e.taskId)),e.agentId&&(t=t.filter(i=>i.agentId===e.agentId)),e.domain&&(t=t.filter(i=>i.domain===e.domain)),e.fromTimestamp&&(t=t.filter(i=>i.timestamp>=e.fromTimestamp)),e.toTimestamp&&(t=t.filter(i=>i.timestamp<=e.toTimestamp)));let n=e?.limit??t.length;return n===0?[]:t.slice(-n)}getSnapshot(e){return{...this.getWindow(),entries:this.getEntries(e)}}getWindow(){return{generation:this.generation,recordedEntries:this.recordedEntries,retainedEntries:this.entries.length,droppedEntries:this.droppedEntries,firstRetainedSequence:this.entries[0]?.sequence??null,lastRetainedSequence:this.entries[this.entries.length-1]?.sequence??null,disposition:this.droppedEntries>0?"truncated":"complete"}}getStatistics(){let e={submit:0,assign:0,reassign:0,complete:0,fail:0,cancel:0,steal:0,queue:0,dequeue:0},t=new Set,n=new Set;for(let i of this.entries)e[i.operation]++,t.add(i.taskId),i.agentId&&n.add(i.agentId);return{...this.getWindow(),basis:"retained-window",totalEntries:this.entries.length,operationCounts:e,taskCount:t.size,agentCount:n.size}}clear(){this.entries.length=0,this.generation=Dt(),this.recordedEntries=0,this.droppedEntries=0}};function we(s){return new X(s)}De();mt();var Me=class{memory;initialized=!1;constructor(e){this.memory=e??R()}async initialize(){this.initialized||(this.memory.isInitialized()||await this.memory.initialize(),this.initialized=!0)}async saveSnapshot(e){this.ensureInitialized();let t=C();return this.memory.getDatabase().prepare(`
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.16");process.exit(0)}
|
|
2
|
+
import{b as we}from"./chunk-J442IZLE.js";import{a as Dt}from"./chunk-24QHCVX6.js";import{a as kt,b as St}from"./chunk-PEQDY4BO.js";import{a as Ct,b as bt}from"./chunk-4D4DENG6.js";import{j as _}from"./chunk-LQLPB2T6.js";import{a as ft}from"./chunk-63GMRQ25.js";import{a as Tt,b as Ee,c as vt}from"./chunk-PHT5N7SC.js";import{a as xe}from"./chunk-EA4YQVKS.js";import{b as yt}from"./chunk-N7HL5PHH.js";import{i as C}from"./chunk-HGWXF45W.js";import{B as Ae,w as R}from"./chunk-MO55CVMT.js";import{c as De,d as An}from"./chunk-JDIYMZCQ.js";import{b as I,d as pt}from"./chunk-V5NHZV7S.js";import{a as ht,e as xn}from"./chunk-S75SOOZL.js";import{a as v,c as y,d as f}from"./chunk-LE4QJREF.js";import{a as Dn}from"./chunk-YAPLJR7K.js";import{c as gt}from"./chunk-G5RHFBAY.js";import{R as kn,S as Sn}from"./chunk-L6QSTQME.js";import{a as h,b as Z,e as k}from"./chunk-KNSRL6NO.js";import{b as Y,d as bn,f as mt}from"./chunk-AJMJNQMP.js";function wt(s){let e=[],t=0;if(s.fileCount!==void 0&&(s.fileCount>20?(t+=25,e.push({name:"very-high-file-count",weight:25,description:`Task involves ${s.fileCount} files (>20)`})):s.fileCount>10?(t+=20,e.push({name:"high-file-count",weight:20,description:`Task involves ${s.fileCount} files (>10)`})):s.fileCount>5&&(t+=10,e.push({name:"moderate-file-count",weight:10,description:`Task involves ${s.fileCount} files (>5)`}))),s.domain&&(Mn.includes(s.domain)?(t+=30,e.push({name:"complex-domain",weight:30,description:`Domain '${s.domain}' requires complex reasoning`})):In.includes(s.domain)&&(t+=15,e.push({name:"moderate-domain",weight:15,description:`Domain '${s.domain}' has moderate complexity`}))),s.crossComponent&&(t+=25,e.push({name:"cross-component",weight:25,description:"Task spans multiple components/modules"})),s.priority==="critical"?(t+=25,e.push({name:"critical-priority",weight:25,description:"Critical priority requires careful attention"})):s.priority==="high"&&(t+=15,e.push({name:"high-priority",weight:15,description:"High priority task"})),s.requiredCapabilities){let r=s.requiredCapabilities.filter(a=>Rn.includes(a)).length;if(r>0){let a=Math.min(20,r*10);t+=a,e.push({name:"complex-capabilities",weight:a,description:`Requires ${r} complex capabilit${r===1?"y":"ies"}`})}}s.requiresExternalApis&&(t+=10,e.push({name:"external-apis",weight:10,description:"Requires external API integration"})),s.involvesDatabaseOps&&(t+=10,e.push({name:"database-ops",weight:10,description:"Involves database operations"})),s.timeSensitive&&(t+=5,e.push({name:"time-sensitive",weight:5,description:"Time-sensitive task"})),s.estimatedLinesAffected!==void 0&&(s.estimatedLinesAffected>500?(t+=15,e.push({name:"large-change",weight:15,description:`Estimated ${s.estimatedLinesAffected} lines affected (>500)`})):s.estimatedLinesAffected>200&&(t+=10,e.push({name:"medium-change",weight:10,description:`Estimated ${s.estimatedLinesAffected} lines affected (>200)`}))),(s.type==="security-scan"||s.type==="vulnerability-assessment")&&(t+=20,e.push({name:"security-task",weight:20,description:"Security-related task requires careful analysis"}));let n=t>=S.critical?"critical":t>=S.complex?"complex":t>=S.moderate?"moderate":"simple",i=_n[n];return{complexity:n,recommendedModel:i,factors:e,score:t,timestamp:new Date}}var Mn,In,Rn,S,_n,Mt=Y(()=>{"use strict";Mn=["security-compliance","chaos-resilience","defect-intelligence"],In=["code-intelligence","contract-testing","quality-assessment","learning-optimization"],Rn=["sast","dast","vulnerability","owasp","chaos-testing","resilience","fault-injection","mutation-testing"],S={critical:70,complex:45,moderate:20},_n={critical:"opus",complex:"sonnet",moderate:"sonnet",simple:"haiku"}});var P,_e=Y(()=>{"use strict";P=class{weightsInputHidden;weightsHiddenOutput;biasHidden;biasOutput;learningRate;constructor(e=.01){this.learningRate=e,this.weightsInputHidden=this.xavierInit(4,32),this.weightsHiddenOutput=this.xavierInit(32,3),this.biasHidden=new Float32Array(32),this.biasOutput=new Float32Array(3)}xavierInit(e,t){let n=Math.sqrt(2/(e+t)),i=new Float32Array(e*t);for(let r=0;r<i.length;r++){let a=Math.random(),o=Math.random(),l=Math.sqrt(-2*Math.log(Math.max(a,1e-10)))*Math.cos(2*Math.PI*o);i[r]=l*n}return i}forward(e){if(e.length!==4)throw new Error(`Expected 4 features, got ${e.length}`);let t=new Float32Array(32);for(let i=0;i<32;i++){let r=this.biasHidden[i];for(let a=0;a<4;a++)r+=e[a]*this.weightsInputHidden[a*32+i];t[i]=Math.max(0,r)}let n=new Float32Array(3);for(let i=0;i<3;i++){let r=this.biasOutput[i];for(let a=0;a<32;a++)r+=t[a]*this.weightsHiddenOutput[a*3+i];n[i]=r}return this.softmax(n)}softmax(e){let t=Math.max(...e),n=new Float32Array(e.length),i=0;for(let a=0;a<e.length;a++)n[a]=Math.exp(e[a]-t),i+=n[a];let r=[];for(let a=0;a<e.length;a++)r.push(n[a]/i);return r}updateWeights(e,t,n){let i=new Float32Array(32);for(let c=0;c<32;c++){let u=this.biasHidden[c];for(let d=0;d<4;d++)u+=e[d]*this.weightsInputHidden[d*32+c];i[c]=Math.max(0,u)}let r=new Float32Array(3);for(let c=0;c<3;c++){let u=this.biasOutput[c];for(let d=0;d<32;d++)u+=i[d]*this.weightsHiddenOutput[d*3+c];r[c]=u}let a=this.softmax(r),o=new Float32Array(3);for(let c=0;c<3;c++)o[c]=(c===t?1:0)-a[c],o[c]*=n*this.learningRate;for(let c=0;c<32;c++)for(let u=0;u<3;u++)this.weightsHiddenOutput[c*3+u]+=i[c]*o[u];for(let c=0;c<3;c++)this.biasOutput[c]+=o[c];let l=new Float32Array(32);for(let c=0;c<32;c++){if(i[c]<=0)continue;let u=0;for(let d=0;d<3;d++)u+=o[d]*this.weightsHiddenOutput[c*3+d];l[c]=u}for(let c=0;c<4;c++)for(let u=0;u<32;u++)this.weightsInputHidden[c*32+u]+=e[c]*l[u];for(let c=0;c<32;c++)this.biasHidden[c]+=l[c]}serialize(){return{weightsInputHidden:Array.from(this.weightsInputHidden),weightsHiddenOutput:Array.from(this.weightsHiddenOutput),biasHidden:Array.from(this.biasHidden),biasOutput:Array.from(this.biasOutput)}}deserialize(e){e.weightsInputHidden.length===128&&(this.weightsInputHidden=new Float32Array(e.weightsInputHidden)),e.weightsHiddenOutput.length===96&&(this.weightsHiddenOutput=new Float32Array(e.weightsHiddenOutput)),e.biasHidden.length===32&&(this.biasHidden=new Float32Array(e.biasHidden)),e.biasOutput.length===3&&(this.biasOutput=new Float32Array(e.biasOutput))}}});var Rt={};bn(Rt,{NeuralTinyDancerRouter:()=>J,SimpleNeuralRouter:()=>P,createNeuralTinyDancerRouter:()=>$n});import{performance as It}from"perf_hooks";function $n(s){return new J(s)}var Pn,Fn,Hn,On,Nn,Ln,Qn,Bn,J,_t=Y(()=>{"use strict";Pe();_e();_e();Pn=1e3,Fn=.1,Hn=.2,On=50,Nn=.01,Ln=["haiku","sonnet","opus"],Qn={haiku:0,sonnet:1,opus:2},Bn={"test-generation":.1,"test-execution":.15,"coverage-analysis":.2,"quality-assessment":.3,"requirements-validation":.35,"code-intelligence":.4,"contract-testing":.45,"visual-accessibility":.5,"learning-optimization":.55,"defect-intelligence":.7,"chaos-resilience":.8,"security-compliance":.9},J=class{ruleRouter;neuralNet;circuitBreakerThreshold;shadowModeDecisionLimit;shadowModeMaxDisagreement;shadowModeActive;shadowDecisions=[];shadowDisagreements=0;circuitBreakerTripped=!1;recentOutcomes=[];totalNeuralDecisions=0;totalWeightUpdates=0;neuralPrimary=!1;calibrationScores=[];maxCalibrationScores=500;domainSuccessRates=new Map;config;nativeRouterAvailable=!1;constructor(e={}){this.config=e,this.ruleRouter=new L(e),this.neuralNet=new P(e.learningRate??Nn),this.circuitBreakerThreshold=e.circuitBreakerThreshold??Hn,this.shadowModeDecisionLimit=e.shadowModeDecisions??Pn,this.shadowModeMaxDisagreement=e.shadowModeMaxDisagreement??Fn,e.forceShadowMode!==void 0?(this.shadowModeActive=e.forceShadowMode,this.neuralPrimary=!e.forceShadowMode):(this.shadowModeActive=!0,this.neuralPrimary=!1),this.tryLoadNativeRouter()}tryLoadNativeRouter(){this.nativeRouterAvailable=!1}async route(e){let t=It.now(),n=await this.ruleRouter.route(e);if(this.circuitBreakerTripped)return n;let i=this.extractFeatures(e,n.classification),r;try{r=this.neuralNet.forward(i)}catch{return this.tripCircuitBreaker(),n}let a=this.argmax(r),o=Ln[a],l=r[a];if(this.totalNeuralDecisions++,this.shadowModeActive){let m=n.model===o;return m||this.shadowDisagreements++,this.shadowDecisions.push({taskDescription:e.description.slice(0,100),ruleDecision:n.model,neuralDecision:o,agreed:m,neuralConfidence:l,timestamp:new Date}),this.evaluateShadowModeExit(),n}let c=It.now()-t,u=this.computeEmpiricalConfidenceBounds(r);return l<.3||u.calibrationScore>.8?n:{model:o,confidence:l,uncertainty:1-l,triggerMultiModel:n.triggerMultiModel,triggerHumanReview:n.triggerHumanReview,complexity:n.complexity,classification:n.classification,latencyMs:c,reasoning:this.buildNeuralReasoning(o,l,r,n,u)}}extractFeatures(e,t){let n=Math.min(1,t.score/100),i=e.description.length,r=e.context?.code?.length??0,a=(i+r)/4,o=Math.min(1,a/1e4),l=e.domain??"",c=Bn[l]??.25,u=this.domainSuccessRates.get(l),d=u?u.success/Math.max(1,u.total):.7;return[n,o,c,d]}recordNeuralOutcome(e,t,n,i=n?1:0,r=t.model,a=0){this.ruleRouter.recordOutcome(e,t,n,i,r,a);let o=e.domain??"unknown",l=this.domainSuccessRates.get(o)??{success:0,total:0};l.total++,n&&l.success++,this.domainSuccessRates.set(o,l),this.recentOutcomes.push(n),this.recentOutcomes.length>On&&this.recentOutcomes.shift(),this.checkCircuitBreaker();let c=this.extractFeatures(e,t.classification),u=Qn[r],d=(i-.5)*2;try{this.neuralNet.updateWeights(c,u,d),this.totalWeightUpdates++}catch{}let m=this.neuralNet.forward(c),p=this.argmax(m),T=1-m[u];this.calibrationScores.push(T),this.calibrationScores.length>this.maxCalibrationScores&&this.calibrationScores.shift()}computeEmpiricalConfidenceBounds(e){let n=Math.max(...e),i=1-n;if(this.calibrationScores.length<10)return{lower:0,upper:1,coverageLevel:.9,calibrationScore:i};let r=[...this.calibrationScores].sort((l,c)=>l-c),a=Math.ceil(.9*r.length)-1,o=r[Math.min(a,r.length-1)];return{lower:Math.max(0,n-o),upper:Math.min(1,n+o),coverageLevel:.9,calibrationScore:i}}computeConformalBounds(e){return this.computeEmpiricalConfidenceBounds(e)}evaluateShadowModeExit(){if(!this.shadowModeActive||this.config.forceShadowMode===!0)return;let e=this.shadowDecisions.length;if(e<this.shadowModeDecisionLimit)return;this.shadowDisagreements/e<=this.shadowModeMaxDisagreement&&(this.shadowModeActive=!1,this.neuralPrimary=!0)}checkCircuitBreaker(){if(this.recentOutcomes.length<10)return;let t=this.recentOutcomes.filter(n=>!n).length/this.recentOutcomes.length;t>this.circuitBreakerThreshold?this.tripCircuitBreaker():this.circuitBreakerTripped&&t<this.circuitBreakerThreshold*.5&&(this.circuitBreakerTripped=!1)}tripCircuitBreaker(){this.circuitBreakerTripped=!0,this.neuralPrimary=!1}buildNeuralReasoning(e,t,n,i,r){let a=[];return a.push(`[Neural] Routing to ${e.toUpperCase()}`),a.push(`with ${(t*100).toFixed(0)}% neural confidence.`),a.push(`Tier probabilities: haiku=${(n[0]*100).toFixed(0)}%,`),a.push(`sonnet=${(n[1]*100).toFixed(0)}%,`),a.push(`opus=${(n[2]*100).toFixed(0)}%.`),e!==i.model&&a.push(`Rule-based would choose ${i.model.toUpperCase()}.`),a.push(`Empirical bounds: [${r.lower.toFixed(2)}, ${r.upper.toFixed(2)}]`),a.push(`at ${(r.coverageLevel*100).toFixed(0)}% coverage.`),a.join(" ")}argmax(e){let t=0,n=e[0];for(let i=1;i<e.length;i++)e[i]>n&&(n=e[i],t=i);return t}getNeuralStats(){let e=this.shadowDecisions.length,t=e>0?this.shadowDisagreements/e:0,n=this.recentOutcomes.filter(r=>!r).length,i=this.recentOutcomes.length>0?n/this.recentOutcomes.length:0;return{shadowModeActive:this.shadowModeActive,shadowDecisions:e,disagreementRate:t,circuitBreakerTripped:this.circuitBreakerTripped,recentErrorRate:i,totalNeuralDecisions:this.totalNeuralDecisions,totalWeightUpdates:this.totalWeightUpdates,neuralPrimary:this.neuralPrimary}}getShadowDecisionLogs(){return this.shadowDecisions}getRuleRouter(){return this.ruleRouter}getNeuralNet(){return this.neuralNet}isNativeRouterAvailable(){return this.nativeRouterAvailable}isShadowModeActive(){return this.shadowModeActive}isNeuralPrimary(){return this.neuralPrimary}isCircuitBreakerTripped(){return this.circuitBreakerTripped}resetCircuitBreaker(){this.circuitBreakerTripped=!1,this.recentOutcomes=[]}getStats(){return this.ruleRouter.getStats()}getConfig(){return this.ruleRouter.getConfig()}reset(){this.ruleRouter.reset(),this.shadowDecisions=[],this.shadowDisagreements=0,this.circuitBreakerTripped=!1,this.recentOutcomes=[],this.totalNeuralDecisions=0,this.totalWeightUpdates=0,this.calibrationScores=[],this.domainSuccessRates.clear(),this.config.forceShadowMode!==void 0?(this.shadowModeActive=this.config.forceShadowMode,this.neuralPrimary=!this.config.forceShadowMode):(this.shadowModeActive=!0,this.neuralPrimary=!1)}}});import{performance as Pt}from"perf_hooks";function Ft(s){try{let{getRuVectorFeatureFlags:e}=(Sn(),mt(kn));if(e().useNeuralRouting){let{NeuralTinyDancerRouter:n}=(_t(),mt(Rt));return new n(s)}}catch(e){process.env.DEBUG&&console.debug("[Router] Neural router unavailable, using rule-based:",e instanceof Error?e.message:e)}return new L(s)}var L,Pe=Y(()=>{"use strict";Mt();L=class{confidenceThreshold;uncertaintyThreshold;securityConfidenceThreshold;enableLearning;verbose;executor;totalRouted=0;routesByModel={haiku:0,sonnet:0,opus:0};routesByComplexity={simple:0,moderate:0,complex:0,critical:0};multiModelTriggers=0;humanReviewTriggers=0;advisorConsultations=0;totalConfidence=0;totalLatencyMs=0;outcomes=[];maxOutcomes=1e3;constructor(e={}){this.confidenceThreshold=e.confidenceThreshold??.8,this.uncertaintyThreshold=e.uncertaintyThreshold??.2,this.securityConfidenceThreshold=e.securityConfidenceThreshold??.85,this.enableLearning=e.enableLearning??!0,this.verbose=e.verbose??!1,this.executor=e.executor}hasExecutor(){return this.executor!==void 0}async routeWithAdvisor(e,t){let n=await this.route(e);if(!n.triggerMultiModel||!this.executor||!t)return{route:n};let i=await this.executor.consult(t,{agentName:e.agentId??e.id??"unknown",triggerReason:`tiny_dancer.confidence=${n.confidence.toFixed(2)}<${this.confidenceThreshold}`});return this.advisorConsultations++,{route:n,advisor:i}}async route(e){let t=Pt.now(),n=wt(e),i=this.calculateConfidence(n),r=1-i,a=this.isSecurityTask(e),o=a&&i<this.securityConfidenceThreshold||i<this.confidenceThreshold&&n.complexity!=="simple",l=r>this.uncertaintyThreshold||a&&n.complexity==="critical",c=Pt.now()-t,u=this.buildReasoning(n,i,a,o,l),d={model:n.recommendedModel,confidence:i,uncertainty:r,triggerMultiModel:o,triggerHumanReview:l,complexity:n.complexity,classification:n,latencyMs:c,reasoning:u};return this.updateStats(d),this.verbose&&console.log(`[TinyDancer] Route: ${n.recommendedModel} (complexity=${n.complexity}, confidence=${(i*100).toFixed(1)}%)`),d}calculateConfidence(e){let{score:t,complexity:n}=e;if(n==="simple"&&t<10)return .9;if(n==="critical"&&t>85)return .92;let i=[S.moderate,S.complex,S.critical],r=1/0;for(let d of i){let m=Math.abs(t-d);m<r&&(r=m)}let a=.55,o=.35,l=Math.min(r/25,1),c=a+l*o,u=n!=="simple"?Math.min(.05,e.factors.length*.01):0;return Math.min(.95,c+u)}isSecurityTask(e){let t=e;if(t.type==="security-scan"||t.type==="vulnerability-assessment"||e.domain==="security-compliance")return!0;let n=["sast","dast","vulnerability","owasp","security-scanning"];if(e.requiredCapabilities?.some(a=>n.includes(a)))return!0;let i=["security","vulnerability","cve","owasp","exploit","injection"],r=e.description.toLowerCase();return!!i.some(a=>r.includes(a))}buildReasoning(e,t,n,i,r){let a=[];if(a.push(`Routing to ${e.recommendedModel.toUpperCase()}`),a.push(`(complexity: ${e.complexity}, score: ${e.score})`),a.push(`with ${(t*100).toFixed(0)}% confidence.`),e.factors.length>0){let o=e.factors.slice(0,3).map(l=>l.name).join(", ");a.push(`Key factors: ${o}.`)}return n&&a.push("Security-sensitive task detected."),i&&a.push("Multi-model verification recommended due to uncertainty."),r&&a.push("Human review flagged due to high uncertainty or criticality."),a.join(" ")}updateStats(e){this.totalRouted++,this.routesByModel[e.model]++,this.routesByComplexity[e.complexity]++,this.totalConfidence+=e.confidence,this.totalLatencyMs+=e.latencyMs,e.triggerMultiModel&&this.multiModelTriggers++,e.triggerHumanReview&&this.humanReviewTriggers++}recordOutcome(e,t,n,i=n?1:0,r=t.model,a=0){if(!this.enableLearning)return;let o={task:e,routeResult:t,success:n,qualityScore:i,actualModelUsed:r,durationMs:a,timestamp:new Date};this.outcomes.push(o),this.outcomes.length>this.maxOutcomes&&this.outcomes.shift(),this.verbose&&console.log(`[TinyDancer] Recorded outcome: success=${n}, quality=${(i*100).toFixed(0)}%, model=${r}`)}getStats(){return{totalRouted:this.totalRouted,routesByModel:{...this.routesByModel},routesByComplexity:{...this.routesByComplexity},multiModelTriggers:this.multiModelTriggers,advisorConsultations:this.advisorConsultations,humanReviewTriggers:this.humanReviewTriggers,avgConfidence:this.totalRouted>0?this.totalConfidence/this.totalRouted:0,avgLatencyMs:this.totalRouted>0?this.totalLatencyMs/this.totalRouted:0,outcomesRecorded:this.outcomes.length}}getOutcomes(){return this.outcomes}getSuccessRateByModel(){let e={haiku:{success:0,total:0},sonnet:{success:0,total:0},opus:{success:0,total:0}};for(let t of this.outcomes){let n=t.actualModelUsed;e[n].total++,t.success&&e[n].success++}return{haiku:e.haiku.total>0?e.haiku.success/e.haiku.total:0,sonnet:e.sonnet.total>0?e.sonnet.success/e.sonnet.total:0,opus:e.opus.total>0?e.opus.success/e.opus.total:0}}reset(){this.totalRouted=0,this.routesByModel={haiku:0,sonnet:0,opus:0},this.routesByComplexity={simple:0,moderate:0,complex:0,critical:0},this.multiModelTriggers=0,this.advisorConsultations=0,this.humanReviewTriggers=0,this.totalConfidence=0,this.totalLatencyMs=0,this.outcomes=[]}getConfig(){return{confidenceThreshold:this.confidenceThreshold,uncertaintyThreshold:this.uncertaintyThreshold,securityConfidenceThreshold:this.securityConfidenceThreshold,enableLearning:this.enableLearning,verbose:this.verbose}}}});import{randomUUID as At}from"node:crypto";var En={enableConsoleLog:!0,maxEntries:1e3,logPrefix:"[TASK]"},X=class{entries=[];config;generation=At();recordedEntries=0;droppedEntries=0;constructor(e={}){if(this.config={...En,...e},!Number.isSafeInteger(this.config.maxEntries)||this.config.maxEntries<0)throw new RangeError("maxEntries must be a non-negative safe integer")}log(e,t,n){let i={sequence:++this.recordedEntries,timestamp:new Date,operation:e,taskId:t,agentId:n?.agentId,domain:n?.domain,details:n?.details};if(this.entries.push(i),this.entries.length>this.config.maxEntries){let r=this.entries.length-this.config.maxEntries;this.entries.splice(0,r),this.droppedEntries+=r}if(this.config.enableConsoleLog){let r=n?.agentId?` by ${n.agentId}`:"",a=n?.domain?` (${n.domain})`:"";console.log(`${this.config.logPrefix} ${e.toUpperCase()} ${t}${r}${a}`)}}logSubmit(e,t){this.log("submit",e,{details:t})}logAssign(e,t,n){this.log("assign",e,{agentId:t,domain:n})}logReassign(e,t,n,i){this.log("reassign",e,{agentId:n,domain:i,details:{fromAgent:t}})}logComplete(e,t){this.log("complete",e,{agentId:t})}logFail(e,t,n){this.log("fail",e,{agentId:t,details:n?{error:n}:void 0})}logCancel(e){this.log("cancel",e)}logSteal(e,t,n){this.log("steal",e,{domain:n,details:{fromDomain:t}})}logQueue(e,t){this.log("queue",e,{details:{position:t}})}logDequeue(e){this.log("dequeue",e)}getEntries(e){let t=[...this.entries];e&&(e.operation&&(t=t.filter(i=>i.operation===e.operation)),e.taskId&&(t=t.filter(i=>i.taskId===e.taskId)),e.agentId&&(t=t.filter(i=>i.agentId===e.agentId)),e.domain&&(t=t.filter(i=>i.domain===e.domain)),e.fromTimestamp&&(t=t.filter(i=>i.timestamp>=e.fromTimestamp)),e.toTimestamp&&(t=t.filter(i=>i.timestamp<=e.toTimestamp)));let n=e?.limit??t.length;return n===0?[]:t.slice(-n)}getSnapshot(e){return{...this.getWindow(),entries:this.getEntries(e)}}getWindow(){return{generation:this.generation,recordedEntries:this.recordedEntries,retainedEntries:this.entries.length,droppedEntries:this.droppedEntries,firstRetainedSequence:this.entries[0]?.sequence??null,lastRetainedSequence:this.entries[this.entries.length-1]?.sequence??null,disposition:this.droppedEntries>0?"truncated":"complete"}}getStatistics(){let e={submit:0,assign:0,reassign:0,complete:0,fail:0,cancel:0,steal:0,queue:0,dequeue:0},t=new Set,n=new Set;for(let i of this.entries)e[i.operation]++,t.add(i.taskId),i.agentId&&n.add(i.agentId);return{...this.getWindow(),basis:"retained-window",totalEntries:this.entries.length,operationCounts:e,taskCount:t.size,agentCount:n.size}}clear(){this.entries.length=0,this.generation=At(),this.recordedEntries=0,this.droppedEntries=0}};function Me(s){return new X(s)}Ae();pt();var Ie=class{memory;initialized=!1;constructor(e){this.memory=e??R()}async initialize(){this.initialized||(this.memory.isInitialized()||await this.memory.initialize(),this.initialized=!0)}async saveSnapshot(e){this.ensureInitialized();let t=C(),n=this.memory.getDatabase();return await this.memory.writeWhenUnlocked(()=>n.prepare(`
|
|
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
|
|
6
6
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
7
|
-
`).run(t,e.timestamp.toISOString(),e.stats.vertexCount,e.stats.edgeCount,e.stats.totalWeight,e.stats.isConnected?1:0,e.stats.componentCount,JSON.stringify(e.vertices),JSON.stringify(e.edges)),await this.enforceRetention(),t}async enforceRetention(e=200){let t=this.memory.getDatabase();if(!t)return 0;let n=t.prepare("SELECT COUNT(*) as count FROM mincut_snapshots").get();if(!n||n.count<=e)return 0;let i=n.count-e;t.prepare(`
|
|
7
|
+
`).run(t,e.timestamp.toISOString(),e.stats.vertexCount,e.stats.edgeCount,e.stats.totalWeight,e.stats.isConnected?1:0,e.stats.componentCount,JSON.stringify(e.vertices),JSON.stringify(e.edges))),await this.enforceRetention(),t}async enforceRetention(e=200){let t=this.memory.getDatabase();if(!t)return 0;let n=t.prepare("SELECT COUNT(*) as count FROM mincut_snapshots").get();if(!n||n.count<=e)return 0;let i=n.count-e;await this.memory.writeWhenUnlocked(()=>t.prepare(`
|
|
8
8
|
DELETE FROM mincut_snapshots WHERE id IN (
|
|
9
9
|
SELECT id FROM mincut_snapshots ORDER BY created_at ASC LIMIT ?
|
|
10
10
|
)
|
|
11
|
-
`).run(i);let r=t.prepare("SELECT COUNT(*) as count FROM mincut_history").get();if(r.count>500){let a=r.count-500;t.prepare(`
|
|
11
|
+
`).run(i));let r=t.prepare("SELECT COUNT(*) as count FROM mincut_history").get();if(r.count>500){let a=r.count-500;await this.memory.writeWhenUnlocked(()=>t.prepare(`
|
|
12
12
|
DELETE FROM mincut_history WHERE id IN (
|
|
13
13
|
SELECT id FROM mincut_history ORDER BY created_at ASC LIMIT ?
|
|
14
14
|
)
|
|
15
|
-
`).run(a)}return i}async getSnapshot(e){this.ensureInitialized();let n=this.memory.getDatabase().prepare("SELECT * FROM mincut_snapshots WHERE id = ?").get(e);return n?this.rowToSnapshot(n):null}async getRecentSnapshots(e=10){return this.ensureInitialized(),this.memory.getDatabase().prepare(`
|
|
15
|
+
`).run(a))}return i}async getSnapshot(e){this.ensureInitialized();let n=this.memory.getDatabase().prepare("SELECT * FROM mincut_snapshots WHERE id = ?").get(e);return n?this.rowToSnapshot(n):null}async getRecentSnapshots(e=10){return this.ensureInitialized(),this.memory.getDatabase().prepare(`
|
|
16
16
|
SELECT * FROM mincut_snapshots
|
|
17
17
|
ORDER BY timestamp DESC
|
|
18
18
|
LIMIT ?
|
|
19
|
-
`).all(e).map(i=>this.rowToSnapshot(i))}async recordHistory(e){this.ensureInitialized();let
|
|
19
|
+
`).all(e).map(i=>this.rowToSnapshot(i))}async recordHistory(e){this.ensureInitialized();let t=this.memory.getDatabase(),n=await this.memory.writeWhenUnlocked(()=>t.prepare(`
|
|
20
20
|
INSERT INTO mincut_history (
|
|
21
21
|
mincut_value, vertex_count, edge_count, algorithm, duration_ms, snapshot_id
|
|
22
22
|
) VALUES (?, ?, ?, ?, ?, ?)
|
|
23
|
-
`).run(e.minCutValue,e.vertexCount,e.edgeCount,e.algorithm??"weighted-degree",e.durationMs??null,e.snapshotId??null);return Number(n.lastInsertRowid)}async getHistory(e={}){this.ensureInitialized();let t=this.memory.getDatabase(),n="SELECT * FROM mincut_history WHERE 1=1",i=[];return e.since&&(n+=" AND timestamp >= ?",i.push(e.since.toISOString())),e.until&&(n+=" AND timestamp <= ?",i.push(e.until.toISOString())),n+=" ORDER BY timestamp DESC",e.limit&&(n+=" LIMIT ?",i.push(e.limit)),t.prepare(n).all(...i).map(a=>({timestamp:new Date(a.timestamp),value:a.mincut_value,vertexCount:a.vertex_count,edgeCount:a.edge_count}))}async getHistoryStats(e=36e5){this.ensureInitialized();let t=this.memory.getDatabase(),n=new Date(Date.now()-e),i=t.prepare(`
|
|
23
|
+
`).run(e.minCutValue,e.vertexCount,e.edgeCount,e.algorithm??"weighted-degree",e.durationMs??null,e.snapshotId??null));return Number(n.lastInsertRowid)}async getHistory(e={}){this.ensureInitialized();let t=this.memory.getDatabase(),n="SELECT * FROM mincut_history WHERE 1=1",i=[];return e.since&&(n+=" AND timestamp >= ?",i.push(e.since.toISOString())),e.until&&(n+=" AND timestamp <= ?",i.push(e.until.toISOString())),n+=" ORDER BY timestamp DESC",e.limit&&(n+=" LIMIT ?",i.push(e.limit)),t.prepare(n).all(...i).map(a=>({timestamp:new Date(a.timestamp),value:a.mincut_value,vertexCount:a.vertex_count,edgeCount:a.edge_count}))}async getHistoryStats(e=36e5){this.ensureInitialized();let t=this.memory.getDatabase(),n=new Date(Date.now()-e),i=t.prepare(`
|
|
24
24
|
SELECT
|
|
25
25
|
MIN(mincut_value) as min_value,
|
|
26
26
|
MAX(mincut_value) as max_value,
|
|
@@ -47,55 +47,55 @@ import{b as Ee}from"./chunk-XSPMLJCQ.js";import{a as St}from"./chunk-6P4Q4RTC.js
|
|
|
47
47
|
id, vertex_id, weighted_degree, risk_score, reason,
|
|
48
48
|
domain, vertex_type, suggestions_json, snapshot_id
|
|
49
49
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
50
|
-
`)
|
|
50
|
+
`),a=n.transaction(o=>{i.length=0;for(let l of o){let c=C();r.run(c,l.vertexId,l.weightedDegree,l.riskScore,l.reason,l.vertex.domain??null,l.vertex.type,JSON.stringify(l.suggestions),t??null),i.push(c)}});return await this.memory.writeWhenUnlocked(()=>a(e)),i}async getUnresolvedWeakVertices(){return this.ensureInitialized(),this.memory.getDatabase().prepare(`
|
|
51
51
|
SELECT id, vertex_id, risk_score, reason, detected_at
|
|
52
52
|
FROM mincut_weak_vertices
|
|
53
53
|
WHERE resolved_at IS NULL
|
|
54
54
|
ORDER BY risk_score DESC
|
|
55
|
-
`).all().map(n=>({id:n.id,vertexId:n.vertex_id,riskScore:n.risk_score,reason:n.reason,detectedAt:new Date(n.detected_at)}))}async resolveWeakVertex(e){
|
|
55
|
+
`).all().map(n=>({id:n.id,vertexId:n.vertex_id,riskScore:n.risk_score,reason:n.reason,detectedAt:new Date(n.detected_at)}))}async resolveWeakVertex(e){this.ensureInitialized();let t=this.memory.getDatabase();return(await this.memory.writeWhenUnlocked(()=>t.prepare(`
|
|
56
56
|
UPDATE mincut_weak_vertices
|
|
57
57
|
SET resolved_at = datetime('now')
|
|
58
58
|
WHERE id = ? AND resolved_at IS NULL
|
|
59
|
-
`).run(e).changes>0}async saveAlert(e){
|
|
59
|
+
`).run(e))).changes>0}async saveAlert(e){this.ensureInitialized();let t=this.memory.getDatabase();return await this.memory.writeWhenUnlocked(()=>t.prepare(`
|
|
60
60
|
INSERT INTO mincut_alerts (
|
|
61
61
|
id, severity, message, mincut_value, threshold,
|
|
62
62
|
affected_vertices_json, remediations_json, acknowledged, timestamp
|
|
63
63
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
64
|
-
`).run(e.id,e.severity,e.message,e.minCutValue,e.threshold,JSON.stringify(e.affectedVertices),JSON.stringify(e.remediations),e.acknowledged?1:0,e.timestamp.toISOString()),e.id}async getUnacknowledgedAlerts(){return this.ensureInitialized(),this.memory.getDatabase().prepare(`
|
|
64
|
+
`).run(e.id,e.severity,e.message,e.minCutValue,e.threshold,JSON.stringify(e.affectedVertices),JSON.stringify(e.remediations),e.acknowledged?1:0,e.timestamp.toISOString())),e.id}async getUnacknowledgedAlerts(){return this.ensureInitialized(),this.memory.getDatabase().prepare(`
|
|
65
65
|
SELECT * FROM mincut_alerts
|
|
66
66
|
WHERE acknowledged = 0
|
|
67
67
|
ORDER BY timestamp DESC
|
|
68
|
-
`).all().map(n=>this.rowToAlert(n))}async acknowledgeAlert(e,t){
|
|
68
|
+
`).all().map(n=>this.rowToAlert(n))}async acknowledgeAlert(e,t){this.ensureInitialized();let n=this.memory.getDatabase();return(await this.memory.writeWhenUnlocked(()=>n.prepare(`
|
|
69
69
|
UPDATE mincut_alerts
|
|
70
70
|
SET acknowledged = 1,
|
|
71
71
|
acknowledged_at = datetime('now'),
|
|
72
72
|
acknowledged_by = ?
|
|
73
73
|
WHERE id = ? AND acknowledged = 0
|
|
74
|
-
`).run(t??null,e).changes>0}async getAlertHistory(e=50){return this.ensureInitialized(),this.memory.getDatabase().prepare(`
|
|
74
|
+
`).run(t??null,e))).changes>0}async getAlertHistory(e=50){return this.ensureInitialized(),this.memory.getDatabase().prepare(`
|
|
75
75
|
SELECT * FROM mincut_alerts
|
|
76
76
|
ORDER BY timestamp DESC
|
|
77
77
|
LIMIT ?
|
|
78
|
-
`).all(e).map(i=>this.rowToAlert(i))}async recordHealingAction(e){this.ensureInitialized();let t=C();return this.memory.
|
|
78
|
+
`).all(e).map(i=>this.rowToAlert(i))}async recordHealingAction(e){this.ensureInitialized();let t=C(),n=this.memory.getDatabase();return await this.memory.writeWhenUnlocked(()=>n.prepare(`
|
|
79
79
|
INSERT INTO mincut_healing_actions (
|
|
80
80
|
id, action_type, action_params_json, success,
|
|
81
81
|
mincut_before, mincut_after, improvement,
|
|
82
82
|
error_message, duration_ms, triggered_by,
|
|
83
83
|
snapshot_before_id, snapshot_after_id
|
|
84
84
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
85
|
-
`).run(t,e.action.type,JSON.stringify(e.action),e.success?1:0,e.minCutBefore,e.minCutAfter,e.improvement,e.error??null,e.durationMs,e.triggeredBy??null,e.snapshotBeforeId??null,e.snapshotAfterId??null),t}async getHealingHistory(e={}){this.ensureInitialized();let t=this.memory.getDatabase(),n="SELECT * FROM mincut_healing_actions WHERE 1=1",i=[];return e.successOnly&&(n+=" AND success = 1"),n+=" ORDER BY created_at DESC",e.limit&&(n+=" LIMIT ?",i.push(e.limit)),t.prepare(n).all(...i).map(a=>({id:a.id,actionType:a.action_type,success:a.success===1,improvement:a.improvement,durationMs:a.duration_ms,createdAt:new Date(a.created_at)}))}async getHealingSuccessRate(e=864e5){this.ensureInitialized();let t=this.memory.getDatabase(),n=new Date(Date.now()-e),i=t.prepare(`
|
|
85
|
+
`).run(t,e.action.type,JSON.stringify(e.action),e.success?1:0,e.minCutBefore,e.minCutAfter,e.improvement,e.error??null,e.durationMs,e.triggeredBy??null,e.snapshotBeforeId??null,e.snapshotAfterId??null)),t}async getHealingHistory(e={}){this.ensureInitialized();let t=this.memory.getDatabase(),n="SELECT * FROM mincut_healing_actions WHERE 1=1",i=[];return e.successOnly&&(n+=" AND success = 1"),n+=" ORDER BY created_at DESC",e.limit&&(n+=" LIMIT ?",i.push(e.limit)),t.prepare(n).all(...i).map(a=>({id:a.id,actionType:a.action_type,success:a.success===1,improvement:a.improvement,durationMs:a.duration_ms,createdAt:new Date(a.created_at)}))}async getHealingSuccessRate(e=864e5){this.ensureInitialized();let t=this.memory.getDatabase(),n=new Date(Date.now()-e),i=t.prepare(`
|
|
86
86
|
SELECT
|
|
87
87
|
COUNT(*) as total,
|
|
88
88
|
SUM(CASE WHEN success = 1 THEN 1 ELSE 0 END) as successful,
|
|
89
89
|
AVG(CASE WHEN success = 1 THEN improvement ELSE 0 END) as avg_improvement
|
|
90
90
|
FROM mincut_healing_actions
|
|
91
91
|
WHERE created_at >= ?
|
|
92
|
-
`).get(n.toISOString());return{total:i.total,successful:i.successful,rate:i.total>0?i.successful/i.total:0,averageImprovement:i.avg_improvement??0}}async recordObservation(e){this.ensureInitialized();let t=C(),n=this.memory.getDatabase(),i=null;return e.prediction&&(i=e.minCutValue-e.prediction.predictedMinCut),n.prepare(`
|
|
92
|
+
`).get(n.toISOString());return{total:i.total,successful:i.successful,rate:i.total>0?i.successful/i.total:0,averageImprovement:i.avg_improvement??0}}async recordObservation(e){this.ensureInitialized();let t=C(),n=this.memory.getDatabase(),i=null;return e.prediction&&(i=e.minCutValue-e.prediction.predictedMinCut),await this.memory.writeWhenUnlocked(()=>n.prepare(`
|
|
93
93
|
INSERT INTO mincut_observations (
|
|
94
94
|
id, iteration, mincut_value, weak_vertex_count,
|
|
95
95
|
weak_vertices_json, snapshot_id, prediction_json,
|
|
96
96
|
actual_vs_predicted_diff
|
|
97
97
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
98
|
-
`).run(t,e.iteration,e.minCutValue,e.weakVertices.length,JSON.stringify(e.weakVertices.map(r=>r.vertexId)),e.snapshotId??null,e.prediction?JSON.stringify(e.prediction):null,i),t}async getRecentObservations(e=20){return this.ensureInitialized(),this.memory.getDatabase().prepare(`
|
|
98
|
+
`).run(t,e.iteration,e.minCutValue,e.weakVertices.length,JSON.stringify(e.weakVertices.map(r=>r.vertexId)),e.snapshotId??null,e.prediction?JSON.stringify(e.prediction):null,i)),t}async getRecentObservations(e=20){return this.ensureInitialized(),this.memory.getDatabase().prepare(`
|
|
99
99
|
SELECT id, iteration, mincut_value, weak_vertex_count, timestamp
|
|
100
100
|
FROM mincut_observations
|
|
101
101
|
ORDER BY iteration DESC
|
|
@@ -109,16 +109,16 @@ import{b as Ee}from"./chunk-XSPMLJCQ.js";import{a as St}from"./chunk-6P4Q4RTC.js
|
|
|
109
109
|
AND actual_vs_predicted_diff IS NOT NULL
|
|
110
110
|
ORDER BY iteration DESC
|
|
111
111
|
LIMIT ?
|
|
112
|
-
`).get(e);return{count:n.count,meanAbsoluteError:n.mae??0,accuracy:n.mae!==null?Math.max(0,1-n.mae/3):0}}async cleanup(e={}){this.ensureInitialized();let t=this.memory.getDatabase(),n=Date.now(),i=e.historyMaxAge??10080*60*1e3,r=e.snapshotMaxAge??1440*60*1e3,a=e.alertMaxAge??720*60*60*1e3,o=t.prepare(`
|
|
112
|
+
`).get(e);return{count:n.count,meanAbsoluteError:n.mae??0,accuracy:n.mae!==null?Math.max(0,1-n.mae/3):0}}async cleanup(e={}){this.ensureInitialized();let t=this.memory.getDatabase(),n=Date.now(),i=e.historyMaxAge??10080*60*1e3,r=e.snapshotMaxAge??1440*60*1e3,a=e.alertMaxAge??720*60*60*1e3,o=await this.memory.writeWhenUnlocked(()=>t.prepare(`
|
|
113
113
|
DELETE FROM mincut_history
|
|
114
114
|
WHERE timestamp < ?
|
|
115
|
-
`).run(new Date(n-i).toISOString()),l=t.prepare(`
|
|
115
|
+
`).run(new Date(n-i).toISOString())),l=await this.memory.writeWhenUnlocked(()=>t.prepare(`
|
|
116
116
|
DELETE FROM mincut_snapshots
|
|
117
117
|
WHERE timestamp < ?
|
|
118
|
-
`).run(new Date(n-r).toISOString()),c=t.prepare(`
|
|
118
|
+
`).run(new Date(n-r).toISOString())),c=await this.memory.writeWhenUnlocked(()=>t.prepare(`
|
|
119
119
|
DELETE FROM mincut_alerts
|
|
120
120
|
WHERE timestamp < ? AND acknowledged = 1
|
|
121
|
-
`).run(new Date(n-a).toISOString());return{historyDeleted:o.changes,snapshotsDeleted:l.changes,alertsDeleted:c.changes}}ensureInitialized(){if(!this.initialized)throw new Error("MinCutPersistence not initialized. Call initialize() first.")}rowToSnapshot(e){return{timestamp:new Date(e.timestamp),vertices:I(e.vertices_json),edges:I(e.edges_json),stats:{vertexCount:e.vertex_count,edgeCount:e.edge_count,totalWeight:e.total_weight,averageDegree:e.edge_count>0&&e.vertex_count>0?e.edge_count*2/e.vertex_count:0,density:e.vertex_count>1?e.edge_count/(e.vertex_count*(e.vertex_count-1)/2):0,isConnected:e.is_connected===1,componentCount:e.component_count}}}rowToAlert(e){return{id:e.id,severity:e.severity,message:e.message,minCutValue:e.mincut_value,threshold:e.threshold,affectedVertices:e.affected_vertices_json?I(e.affected_vertices_json):[],remediations:e.remediations_json?I(e.remediations_json):[],acknowledged:e.acknowledged===1,timestamp:new Date(e.timestamp)}}};function At(s){return new Me(s)}var xn={...yt,autoUpdateFromEvents:!0,persistData:!0,snapshotIntervalMs:6e4,includeInQueenHealth:!0,minHealthIssueSeverity:"medium"},Ie=class{constructor(e,t,n={}){this.eventBus=e;this.agentCoordinator=t;this.config={...xn,...n},this.graph=n.sharedGraph??ft(),this.monitor=xe(this.graph,this.config,this.eventBus),this.persistence=At()}eventBus;agentCoordinator;config;graph;monitor;persistence;eventSubscriptions=[];spawnedAgentIds=new Set;taskAgentIds=new Set;snapshotTimer=null;initialized=!1;async initialize(){this.initialized||(this.config.persistData&&await this.persistence.initialize(),await this.buildGraphFromAgents(),this.config.autoUpdateFromEvents&&this.subscribeToEvents(),this.monitor.start(),this.config.persistData&&this.startSnapshotTimer(),this.initialized=!0)}async dispose(){this.monitor.stop(),this.snapshotTimer&&(clearInterval(this.snapshotTimer),this.snapshotTimer=null);for(let e of this.eventSubscriptions)e();if(this.eventSubscriptions=[],this.config.persistData)try{await this.saveSnapshot()}catch{}this.initialized=!1}async buildGraphFromAgents(){this.config.sharedGraph||this.graph.clear();let e=this.agentCoordinator.listAgents();for(let t of v)this.graph.addVertex({id:`domain:${t}`,type:"domain",domain:t,weight:2,createdAt:new Date});for(let t of e)this.addAgentVertex(t),this.spawnedAgentIds.add(t.id);this.buildCoordinationEdges(e)}addAgentVertex(e){let t=e,n={id:`agent:${e.id}`,type:"agent",domain:e.domain,capabilities:t.capabilities,weight:1,createdAt:e.startedAt??new Date,metadata:{status:e.status,taskCount:t.taskCount??0,health:t.health??1}};if(this.graph.addVertex(n),e.domain){let i=`domain:${e.domain}`;this.graph.hasVertex(i)&&this.graph.addEdge({source:`agent:${e.id}`,target:i,weight:1,type:"coordination",bidirectional:!0})}}buildCoordinationEdges(e){let t=new Map;for(let i of e)if(i.domain){let r=t.get(i.domain)||[];r.push(i),t.set(i.domain,r)}for(let[i,r]of t)for(let a=0;a<r.length;a++)for(let o=a+1;o<r.length;o++)this.graph.addEdge({source:`agent:${r[a].id}`,target:`agent:${r[o].id}`,weight:.5,type:"communication",bidirectional:!0});let n=[["test-generation","test-execution"],["test-execution","coverage-analysis"],["coverage-analysis","quality-assessment"],["quality-assessment","defect-intelligence"],["requirements-validation","test-generation"],["code-intelligence","test-generation"],["security-compliance","quality-assessment"],["contract-testing","test-execution"],["visual-accessibility","quality-assessment"],["chaos-resilience","test-execution"],["learning-optimization","defect-intelligence"]];for(let[i,r]of n){let a=`domain:${i}`,o=`domain:${r}`;this.graph.hasVertex(a)&&this.graph.hasVertex(o)&&this.graph.addEdge({source:a,target:o,weight:1.5,type:"workflow",bidirectional:!1})}}subscribeToEvents(){let e=async c=>{let{agentId:u,domain:d,type:g,capabilities:p,taskId:T}=c.payload;this.spawnedAgentIds.add(u),T&&this.taskAgentIds.add(u),this.addAgentVertex({id:u,name:`${d}-${g}`,domain:d,type:g,status:"running",startedAt:new Date,capabilities:p,health:1,taskCount:0}),this.config.persistData&&await this.persistence.recordHistory({minCutValue:this.monitor.getMinCutValue(),vertexCount:this.graph.vertexCount,edgeCount:this.graph.edgeCount})},t=async c=>{let{agentId:u}=c.payload;this.graph.removeVertex(`agent:${u}`),this.monitor.checkHealth().status==="critical"&&await this.reportHealthIssue({severity:"high",message:`Agent ${u} termination caused critical MinCut degradation`,timestamp:new Date})},n=async c=>{let{agentId:u,status:d}=c.payload,g=`agent:${u}`,p=this.graph.getVertex(g);p&&this.graph.addVertex({...p,metadata:{...p.metadata,status:d}})},i=async c=>{let{fromAgent:u,toAgent:d}=c.payload,g=`agent:${u}`,p=`agent:${d}`;if(this.graph.hasVertex(g)&&this.graph.hasVertex(p)){let T=this.graph.getEdge(g,p);T?this.graph.addEdge({...T,weight:Math.min(T.weight+.1,3),lastActivity:new Date,messageCount:(T.messageCount??0)+1}):this.graph.addEdge({source:g,target:p,weight:.5,type:"communication",bidirectional:!0,lastActivity:new Date,messageCount:1})}},r=this.eventBus.subscribe("QueenAgentSpawned",e),a=this.eventBus.subscribe("QueenAgentTerminated",t),o=this.eventBus.subscribe("QueenAgentStatusChanged",n),l=this.eventBus.subscribe("QueenTaskCoordination",i);this.eventSubscriptions.push(()=>r.unsubscribe(),()=>a.unsubscribe(),()=>o.unsubscribe(),()=>l.unsubscribe())}getMinCutHealth(){return this.monitor.getHealth()}isEmptyTopology(){return this.graph.getVerticesByType("agent").length===0}getHealthIssuesFromMinCut(){if(this.isEmptyTopology())return[];let e=this.monitor.getActiveAlerts(),t=[];for(let r of e){let a=this.mapSeverity(r.severity);this.severityValue(a)>=this.severityValue(this.config.minHealthIssueSeverity)&&t.push({severity:a,message:`MinCut: ${r.message}`,timestamp:r.timestamp})}let i=this.monitor.getWeakVertices().filter(r=>!this.isTaskAgentVertex(r.vertex.id));for(let r of i.slice(0,3))r.riskScore>.7&&t.push({severity:"high",message:`Weak agent topology: ${r.reason} (risk: ${(r.riskScore*100).toFixed(0)}%)`,timestamp:new Date,domain:r.vertex.domain});return t}pruneCompletedAgents(){if(this.spawnedAgentIds.size===0)return[];let e=new Map(this.agentCoordinator.listAgents().map(n=>[n.id,n])),t=[];for(let n of this.spawnedAgentIds){let i=e.get(n);if(i?.status==="failed"){t.push(i);continue}i&&i.status!=="completed"||(this.graph.removeVertex(`agent:${n}`),this.spawnedAgentIds.delete(n),this.taskAgentIds.delete(n))}return t}failedAgentIssues(e){return e.map(t=>({severity:"high",message:`Agent ${t.id} (${t.type}) failed`,timestamp:new Date,domain:t.domain}))}isTaskAgentVertex(e){return e.startsWith("agent:")&&this.taskAgentIds.has(e.slice(6))}getFleetMinCutHealth(){let e=this.getMinCutHealth();if(this.taskAgentIds.size===0)return{...e,fleetStatus:e.status,fleetMinCutValue:e.minCutValue,taskAgents:0};let t=this.graph.clone();for(let i of this.taskAgentIds)t.removeVertex(`agent:${i}`);let n=xe(t,this.config).getHealth();return{...e,fleetStatus:n.status,fleetMinCutValue:n.minCutValue,taskAgents:this.taskAgentIds.size}}extendQueenHealth(e){if(!this.config.includeInQueenHealth)return e;let t=this.pruneCompletedAgents(),n=this.getFleetMinCutHealth(),i=n.fleetStatus==="idle"?[]:this.getHealthIssuesFromMinCut(),r=e.status;return(n.fleetStatus==="critical"||t.length>0)&&r==="healthy"&&(r="degraded"),{...e,status:r,issues:[...e.issues,...this.failedAgentIssues(t),...i],minCut:n}}extendQueenMetrics(e){let t=this.monitor.getHealth(),n=this.graph.getStats();return{...e,minCutValue:t.minCutValue,weakVertexCount:t.weakVertexCount,topologyDensity:n.density}}async saveSnapshot(){if(!this.config.persistData)return;let e=this.graph.snapshot();await this.persistence.saveSnapshot(e)}startSnapshotTimer(){this.snapshotTimer=setInterval(async()=>{this.isEmptyTopology()||(await this.saveSnapshot(),await this.persistence.recordHistory({minCutValue:this.monitor.getMinCutValue(),vertexCount:this.graph.vertexCount,edgeCount:this.graph.edgeCount}))},this.config.snapshotIntervalMs)}getGraph(){return this.graph}getMonitor(){return this.monitor}getPersistence(){return this.persistence}getMinCutValue(){return this.monitor.getMinCutValue()}getWeakVertices(){return this.monitor.getWeakVertices()}isTopologyCritical(){return this.monitor.isCritical()}addVertex(e){this.graph.addVertex(e)}addEdge(e){this.graph.addEdge(e)}removeVertex(e){return this.graph.removeVertex(e)}async refreshGraph(){await this.buildGraphFromAgents()}async reportHealthIssue(e){await this.eventBus.publish({id:C(),type:"MinCutHealthIssue",source:"mincut-bridge",timestamp:new Date,payload:{issue:e}})}mapSeverity(e){return e}severityValue(e){return{critical:5,high:4,medium:3,low:2,info:1}[e]}};function xt(s,e,t){return new Ie(s,e,t)}_e();import{performance as Lt}from"perf_hooks";var Bn={multiModel:.8,humanReview:.2,security:.85,escalation:.6},$n={trivial:["booster","haiku"],simple:["haiku"],moderate:["sonnet"],complex:["sonnet","opus"],critical:["opus"]},Un={enabled:!0,preferCheaperModels:!0,costPerMillionTokens:{haiku:{input:.25,output:1.25},sonnet:{input:3,output:15},opus:{input:15,output:75}},dailyCostLimit:0,costAlertThreshold:.8},qn={enabled:!0,maxAttempts:2,retryDelayMs:1e3,chain:{booster:"haiku",haiku:"sonnet",sonnet:"opus",opus:null}},D={confidence:Bn,tierMapping:$n,costOptimization:Un,fallback:qn,verbose:!1,enableEMACalibration:!0,enableAutoEscalation:!0,enableNeuralRouting:!1};function Ft(s=D){let e=structuredClone(s);return process.env.ROUTING_CONFIDENCE_MULTI_MODEL&&(e.confidence.multiModel=parseFloat(process.env.ROUTING_CONFIDENCE_MULTI_MODEL)),process.env.ROUTING_CONFIDENCE_HUMAN_REVIEW&&(e.confidence.humanReview=parseFloat(process.env.ROUTING_CONFIDENCE_HUMAN_REVIEW)),process.env.ROUTING_CONFIDENCE_SECURITY&&(e.confidence.security=parseFloat(process.env.ROUTING_CONFIDENCE_SECURITY)),process.env.ROUTING_CONFIDENCE_ESCALATION&&(e.confidence.escalation=parseFloat(process.env.ROUTING_CONFIDENCE_ESCALATION)),process.env.ROUTING_COST_DAILY_LIMIT&&(e.costOptimization.dailyCostLimit=parseFloat(process.env.ROUTING_COST_DAILY_LIMIT)),process.env.ROUTING_COST_PREFER_CHEAPER&&(e.costOptimization.preferCheaperModels=process.env.ROUTING_COST_PREFER_CHEAPER.toLowerCase()==="true"),process.env.ROUTING_FALLBACK_ENABLED&&(e.fallback.enabled=process.env.ROUTING_FALLBACK_ENABLED.toLowerCase()==="true"),process.env.ROUTING_FALLBACK_MAX_ATTEMPTS&&(e.fallback.maxAttempts=parseInt(process.env.ROUTING_FALLBACK_MAX_ATTEMPTS,10)),process.env.ROUTING_VERBOSE&&(e.verbose=process.env.ROUTING_VERBOSE.toLowerCase()==="true"),e}function Ht(s,e,t=D){if(e/100<=.2)return t.tierMapping.trivial;switch(s){case"simple":return t.tierMapping.simple;case"moderate":return t.tierMapping.moderate;case"complex":return t.tierMapping.complex;case"critical":return t.tierMapping.critical}}function Ot(s,e=D){return e.fallback.enabled?e.fallback.chain[s]??null:null}function Pe(s){switch(s){case"booster":case"haiku":return"haiku";case"sonnet":return"sonnet";case"opus":return"opus"}}function Nt(s,e,t,n=D){let i=n.costOptimization.costPerMillionTokens[s],r=e/1e6*i.input,a=t/1e6*i.output;return r+a}function Fe(s){let{confidence:e}=s;if(e.multiModel<0||e.multiModel>1)throw new Error("multiModel confidence must be between 0 and 1");if(e.humanReview<0||e.humanReview>1)throw new Error("humanReview confidence must be between 0 and 1");if(e.security<0||e.security>1)throw new Error("security confidence must be between 0 and 1");if(e.escalation<0||e.escalation>1)throw new Error("escalation confidence must be between 0 and 1");if(s.costOptimization.dailyCostLimit<0)throw new Error("dailyCostLimit must be non-negative");if(s.costOptimization.costAlertThreshold<0||s.costOptimization.costAlertThreshold>1)throw new Error("costAlertThreshold must be between 0 and 1");if(s.fallback.maxAttempts<0)throw new Error("maxAttempts must be non-negative");if(s.fallback.retryDelayMs<0)throw new Error("retryDelayMs must be non-negative")}var ee=class{tinyDancer;routingConfig;enableCostTracking;avgInputTokens;avgOutputTokens;totalCost=0;costByModel={haiku:0,sonnet:0,opus:0};totalTasks=0;dailyCost=0;lastCostReset=new Date;outcomes=[];maxOutcomes=1e3;constructor(e={}){this.tinyDancer=Pt(e.tinyDancer);let t=this.mergeRoutingConfig(e.routing);this.routingConfig=Ft(t),Fe(this.routingConfig),this.enableCostTracking=e.enableCostTracking??!0,this.avgInputTokens=e.avgInputTokens??2e3,this.avgOutputTokens=e.avgOutputTokens??500}async route(e){let t=Lt.now();this.checkDailyCostReset();let n=await this.tinyDancer.route(e),i=void 0,a=Ht(n.complexity,n.classification.score,this.routingConfig)[0],o=Pe(a),l=this.buildFallbackChain(a),c=this.enableCostTracking?Nt(o,this.avgInputTokens,this.avgOutputTokens,this.routingConfig):0;this.checkCostLimits(c);let u=this.buildQueenReasoning(n,a,l,c),d=Lt.now()-t,g={tier:a,model:o,complexity:n.complexity,confidence:n.confidence,triggerMultiModel:n.triggerMultiModel,triggerHumanReview:n.triggerHumanReview,fallbackTiers:l,estimatedCost:c,reasoning:u,latencyMs:d,tinyDancerResult:n,advisorResult:i,timestamp:new Date};return this.enableCostTracking&&(this.totalCost+=c,this.costByModel[o]+=c,this.dailyCost+=c),this.totalTasks++,this.routingConfig.verbose&&console.log(`[QueenRouter] Route: ${a} (${o}) complexity=${n.complexity}, confidence=${(n.confidence*100).toFixed(1)}%, cost=$${c.toFixed(4)}`),g}recordOutcome(e,t,n,i,r=i?1:0,a=0,o=0,l){let c={task:e,decision:t,usedTier:n,success:i,qualityScore:r,durationMs:a,fallbackAttempts:o,error:l,timestamp:new Date};this.outcomes.push(c),this.outcomes.length>this.maxOutcomes&&this.outcomes.shift(),this.tinyDancer.recordOutcome?.(e,t.tinyDancerResult,i,r,Pe(n),a),this.routingConfig.verbose&&console.log(`[QueenRouter] Recorded outcome: tier=${n}, success=${i}, quality=${(r*100).toFixed(0)}%, fallbacks=${o}`)}getSuccessRateByTier(){let e={booster:{success:0,total:0},haiku:{success:0,total:0},sonnet:{success:0,total:0},opus:{success:0,total:0}};for(let t of this.outcomes){let n=t.usedTier;e[n].total++,t.success&&e[n].success++}return{booster:e.booster.total>0?e.booster.success/e.booster.total:0,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}}getFallbackStats(){let e=this.outcomes.filter(i=>i.fallbackAttempts>0),t=e.filter(i=>i.success),n=e.reduce((i,r)=>i+r.fallbackAttempts,0);return{totalWithFallback:e.length,avgFallbackAttempts:e.length>0?n/e.length:0,fallbackSuccessRate:e.length>0?t.length/e.length:0}}getCostStats(){return{totalCost:this.totalCost,costByModel:{...this.costByModel},totalTasks:this.totalTasks,avgCostPerTask:this.totalTasks>0?this.totalCost/this.totalTasks:0,dailyCost:this.dailyCost,lastReset:this.lastCostReset}}getOutcomes(){return this.outcomes}getConfig(){return this.routingConfig}updateConfidenceThresholds(e){Object.assign(this.routingConfig.confidence,e),Fe(this.routingConfig),this.routingConfig.verbose&&console.log("[QueenRouter] Updated confidence thresholds:",e)}reset(){this.totalCost=0,this.costByModel={haiku:0,sonnet:0,opus:0},this.totalTasks=0,this.dailyCost=0,this.lastCostReset=new Date,this.outcomes=[],this.tinyDancer.reset?.()}buildFallbackChain(e){let t=[];if(!this.routingConfig.fallback.enabled)return t;let n=e,i=0;for(;n&&i<this.routingConfig.fallback.maxAttempts;){let r=Ot(n,this.routingConfig);if(r)t.push(r),n=r;else break;i++}return t}buildQueenReasoning(e,t,n,i){let r=[];return r.push(e.reasoning),r.push(`Assigned to ${t.toUpperCase()} tier.`),n.length>0&&r.push(`Fallback chain: ${n.map(a=>a.toUpperCase()).join(" \u2192 ")}.`),this.enableCostTracking&&i>0&&r.push(`Estimated cost: $${i.toFixed(4)}.`),r.join(" ")}checkDailyCostReset(){let e=new Date,t=this.lastCostReset;(e.getUTCDate()!==t.getUTCDate()||e.getUTCMonth()!==t.getUTCMonth()||e.getUTCFullYear()!==t.getUTCFullYear())&&(this.dailyCost=0,this.lastCostReset=e,this.routingConfig.verbose&&console.log("[QueenRouter] Reset daily cost tracking"))}checkCostLimits(e){if(!this.routingConfig.costOptimization.enabled)return;let{dailyCostLimit:t,costAlertThreshold:n}=this.routingConfig.costOptimization;if(t>0){let i=this.dailyCost+e,r=i/t;i>t?console.warn(`[QueenRouter] COST LIMIT EXCEEDED: Daily cost $${i.toFixed(2)} exceeds limit of $${t.toFixed(2)}`):r>=n&&console.warn(`[QueenRouter] Cost alert: ${(r*100).toFixed(0)}% of daily limit ($${i.toFixed(2)} / $${t.toFixed(2)})`)}}mergeRoutingConfig(e){if(!e)return structuredClone(D);let t=structuredClone(D);return e.confidence&&(t.confidence={...t.confidence,...e.confidence}),e.tierMapping&&(t.tierMapping={...t.tierMapping,...e.tierMapping}),e.costOptimization&&(t.costOptimization={...t.costOptimization,...e.costOptimization,costPerMillionTokens:e.costOptimization.costPerMillionTokens?{...t.costOptimization.costPerMillionTokens,...e.costOptimization.costPerMillionTokens}:t.costOptimization.costPerMillionTokens}),e.fallback&&(t.fallback={...t.fallback,...e.fallback,chain:e.fallback.chain?{...t.fallback.chain,...e.fallback.chain}:t.fallback.chain}),e.verbose!==void 0&&(t.verbose=e.verbose),t}};k();var Qt=20,Oe=class{db=null;initialized=!1;initialize(e){if(!this.initialized){this.db=e;try{this.db.exec(`
|
|
121
|
+
`).run(new Date(n-a).toISOString()));return{historyDeleted:o.changes,snapshotsDeleted:l.changes,alertsDeleted:c.changes}}ensureInitialized(){if(!this.initialized)throw new Error("MinCutPersistence not initialized. Call initialize() first.")}rowToSnapshot(e){return{timestamp:new Date(e.timestamp),vertices:I(e.vertices_json),edges:I(e.edges_json),stats:{vertexCount:e.vertex_count,edgeCount:e.edge_count,totalWeight:e.total_weight,averageDegree:e.edge_count>0&&e.vertex_count>0?e.edge_count*2/e.vertex_count:0,density:e.vertex_count>1?e.edge_count/(e.vertex_count*(e.vertex_count-1)/2):0,isConnected:e.is_connected===1,componentCount:e.component_count}}}rowToAlert(e){return{id:e.id,severity:e.severity,message:e.message,minCutValue:e.mincut_value,threshold:e.threshold,affectedVertices:e.affected_vertices_json?I(e.affected_vertices_json):[],remediations:e.remediations_json?I(e.remediations_json):[],acknowledged:e.acknowledged===1,timestamp:new Date(e.timestamp)}}};function xt(s){return new Ie(s)}var wn={...Tt,autoUpdateFromEvents:!0,persistData:!0,snapshotIntervalMs:6e4,includeInQueenHealth:!0,minHealthIssueSeverity:"medium"},Re=class{constructor(e,t,n={}){this.eventBus=e;this.agentCoordinator=t;this.config={...wn,...n},this.graph=n.sharedGraph??yt(),this.monitor=Ee(this.graph,this.config,this.eventBus),this.persistence=xt()}eventBus;agentCoordinator;config;graph;monitor;persistence;eventSubscriptions=[];spawnedAgentIds=new Set;taskAgentIds=new Set;snapshotTimer=null;initialized=!1;async initialize(){this.initialized||(this.config.persistData&&await this.persistence.initialize(),await this.buildGraphFromAgents(),this.config.autoUpdateFromEvents&&this.subscribeToEvents(),this.monitor.start(),this.config.persistData&&this.startSnapshotTimer(),this.initialized=!0)}async dispose(){this.monitor.stop(),this.snapshotTimer&&(clearInterval(this.snapshotTimer),this.snapshotTimer=null);for(let e of this.eventSubscriptions)e();if(this.eventSubscriptions=[],this.config.persistData)try{await this.saveSnapshot()}catch{}this.initialized=!1}async buildGraphFromAgents(){this.config.sharedGraph||this.graph.clear();let e=this.agentCoordinator.listAgents();for(let t of v)this.graph.addVertex({id:`domain:${t}`,type:"domain",domain:t,weight:2,createdAt:new Date});for(let t of e)this.addAgentVertex(t),this.spawnedAgentIds.add(t.id);this.buildCoordinationEdges(e)}addAgentVertex(e){let t=e,n={id:`agent:${e.id}`,type:"agent",domain:e.domain,capabilities:t.capabilities,weight:1,createdAt:e.startedAt??new Date,metadata:{status:e.status,taskCount:t.taskCount??0,health:t.health??1}};if(this.graph.addVertex(n),e.domain){let i=`domain:${e.domain}`;this.graph.hasVertex(i)&&this.graph.addEdge({source:`agent:${e.id}`,target:i,weight:1,type:"coordination",bidirectional:!0})}}buildCoordinationEdges(e){let t=new Map;for(let i of e)if(i.domain){let r=t.get(i.domain)||[];r.push(i),t.set(i.domain,r)}for(let[i,r]of t)for(let a=0;a<r.length;a++)for(let o=a+1;o<r.length;o++)this.graph.addEdge({source:`agent:${r[a].id}`,target:`agent:${r[o].id}`,weight:.5,type:"communication",bidirectional:!0});let n=[["test-generation","test-execution"],["test-execution","coverage-analysis"],["coverage-analysis","quality-assessment"],["quality-assessment","defect-intelligence"],["requirements-validation","test-generation"],["code-intelligence","test-generation"],["security-compliance","quality-assessment"],["contract-testing","test-execution"],["visual-accessibility","quality-assessment"],["chaos-resilience","test-execution"],["learning-optimization","defect-intelligence"]];for(let[i,r]of n){let a=`domain:${i}`,o=`domain:${r}`;this.graph.hasVertex(a)&&this.graph.hasVertex(o)&&this.graph.addEdge({source:a,target:o,weight:1.5,type:"workflow",bidirectional:!1})}}subscribeToEvents(){let e=async c=>{let{agentId:u,domain:d,type:m,capabilities:p,taskId:T}=c.payload;this.spawnedAgentIds.add(u),T&&this.taskAgentIds.add(u),this.addAgentVertex({id:u,name:`${d}-${m}`,domain:d,type:m,status:"running",startedAt:new Date,capabilities:p,health:1,taskCount:0}),this.config.persistData&&await this.persistence.recordHistory({minCutValue:this.monitor.getMinCutValue(),vertexCount:this.graph.vertexCount,edgeCount:this.graph.edgeCount})},t=async c=>{let{agentId:u}=c.payload;this.graph.removeVertex(`agent:${u}`),this.monitor.checkHealth().status==="critical"&&await this.reportHealthIssue({severity:"high",message:`Agent ${u} termination caused critical MinCut degradation`,timestamp:new Date})},n=async c=>{let{agentId:u,status:d}=c.payload,m=`agent:${u}`,p=this.graph.getVertex(m);p&&this.graph.addVertex({...p,metadata:{...p.metadata,status:d}})},i=async c=>{let{fromAgent:u,toAgent:d}=c.payload,m=`agent:${u}`,p=`agent:${d}`;if(this.graph.hasVertex(m)&&this.graph.hasVertex(p)){let T=this.graph.getEdge(m,p);T?this.graph.addEdge({...T,weight:Math.min(T.weight+.1,3),lastActivity:new Date,messageCount:(T.messageCount??0)+1}):this.graph.addEdge({source:m,target:p,weight:.5,type:"communication",bidirectional:!0,lastActivity:new Date,messageCount:1})}},r=this.eventBus.subscribe("QueenAgentSpawned",e),a=this.eventBus.subscribe("QueenAgentTerminated",t),o=this.eventBus.subscribe("QueenAgentStatusChanged",n),l=this.eventBus.subscribe("QueenTaskCoordination",i);this.eventSubscriptions.push(()=>r.unsubscribe(),()=>a.unsubscribe(),()=>o.unsubscribe(),()=>l.unsubscribe())}getMinCutHealth(){return this.monitor.getHealth()}isEmptyTopology(){return this.graph.getVerticesByType("agent").length===0}getHealthIssuesFromMinCut(){if(this.isEmptyTopology())return[];let e=this.monitor.getActiveAlerts(),t=[];for(let r of e){let a=this.mapSeverity(r.severity);this.severityValue(a)>=this.severityValue(this.config.minHealthIssueSeverity)&&t.push({severity:a,message:`MinCut: ${r.message}`,timestamp:r.timestamp})}let i=this.monitor.getWeakVertices().filter(r=>!this.isTaskAgentVertex(r.vertex.id));for(let r of i.slice(0,3))r.riskScore>.7&&t.push({severity:"high",message:`Weak agent topology: ${r.reason} (risk: ${(r.riskScore*100).toFixed(0)}%)`,timestamp:new Date,domain:r.vertex.domain});return t}pruneCompletedAgents(){if(this.spawnedAgentIds.size===0)return[];let e=new Map(this.agentCoordinator.listAgents().map(n=>[n.id,n])),t=[];for(let n of this.spawnedAgentIds){let i=e.get(n);if(i?.status==="failed"){t.push(i);continue}i&&i.status!=="completed"||(this.graph.removeVertex(`agent:${n}`),this.spawnedAgentIds.delete(n),this.taskAgentIds.delete(n))}return t}failedAgentIssues(e){return e.map(t=>({severity:"high",message:`Agent ${t.id} (${t.type}) failed`,timestamp:new Date,domain:t.domain}))}isTaskAgentVertex(e){return e.startsWith("agent:")&&this.taskAgentIds.has(e.slice(6))}getFleetMinCutHealth(){let e=this.getMinCutHealth();if(this.taskAgentIds.size===0)return{...e,fleetStatus:e.status,fleetMinCutValue:e.minCutValue,taskAgents:0};let t=this.graph.clone();for(let i of this.taskAgentIds)t.removeVertex(`agent:${i}`);let n=Ee(t,this.config).getHealth();return{...e,fleetStatus:n.status,fleetMinCutValue:n.minCutValue,taskAgents:this.taskAgentIds.size}}extendQueenHealth(e){if(!this.config.includeInQueenHealth)return e;let t=this.pruneCompletedAgents(),n=this.getFleetMinCutHealth(),i=n.fleetStatus==="idle"?[]:this.getHealthIssuesFromMinCut(),r=e.status;return(n.fleetStatus==="critical"||t.length>0)&&r==="healthy"&&(r="degraded"),{...e,status:r,issues:[...e.issues,...this.failedAgentIssues(t),...i],minCut:n}}extendQueenMetrics(e){let t=this.monitor.getHealth(),n=this.graph.getStats();return{...e,minCutValue:t.minCutValue,weakVertexCount:t.weakVertexCount,topologyDensity:n.density}}async saveSnapshot(){if(!this.config.persistData)return;let e=this.graph.snapshot();await this.persistence.saveSnapshot(e)}startSnapshotTimer(){this.snapshotTimer=setInterval(async()=>{this.isEmptyTopology()||(await this.saveSnapshot(),await this.persistence.recordHistory({minCutValue:this.monitor.getMinCutValue(),vertexCount:this.graph.vertexCount,edgeCount:this.graph.edgeCount}))},this.config.snapshotIntervalMs)}getGraph(){return this.graph}getMonitor(){return this.monitor}getPersistence(){return this.persistence}getMinCutValue(){return this.monitor.getMinCutValue()}getWeakVertices(){return this.monitor.getWeakVertices()}isTopologyCritical(){return this.monitor.isCritical()}addVertex(e){this.graph.addVertex(e)}addEdge(e){this.graph.addEdge(e)}removeVertex(e){return this.graph.removeVertex(e)}async refreshGraph(){await this.buildGraphFromAgents()}async reportHealthIssue(e){await this.eventBus.publish({id:C(),type:"MinCutHealthIssue",source:"mincut-bridge",timestamp:new Date,payload:{issue:e}})}mapSeverity(e){return e}severityValue(e){return{critical:5,high:4,medium:3,low:2,info:1}[e]}};function Et(s,e,t){return new Re(s,e,t)}Pe();import{performance as Qt}from"perf_hooks";var Un={multiModel:.8,humanReview:.2,security:.85,escalation:.6},qn={trivial:["booster","haiku"],simple:["haiku"],moderate:["sonnet"],complex:["sonnet","opus"],critical:["opus"]},zn={enabled:!0,preferCheaperModels:!0,costPerMillionTokens:{haiku:{input:.25,output:1.25},sonnet:{input:3,output:15},opus:{input:15,output:75}},dailyCostLimit:0,costAlertThreshold:.8},Gn={enabled:!0,maxAttempts:2,retryDelayMs:1e3,chain:{booster:"haiku",haiku:"sonnet",sonnet:"opus",opus:null}},D={confidence:Un,tierMapping:qn,costOptimization:zn,fallback:Gn,verbose:!1,enableEMACalibration:!0,enableAutoEscalation:!0,enableNeuralRouting:!1};function Ht(s=D){let e=structuredClone(s);return process.env.ROUTING_CONFIDENCE_MULTI_MODEL&&(e.confidence.multiModel=parseFloat(process.env.ROUTING_CONFIDENCE_MULTI_MODEL)),process.env.ROUTING_CONFIDENCE_HUMAN_REVIEW&&(e.confidence.humanReview=parseFloat(process.env.ROUTING_CONFIDENCE_HUMAN_REVIEW)),process.env.ROUTING_CONFIDENCE_SECURITY&&(e.confidence.security=parseFloat(process.env.ROUTING_CONFIDENCE_SECURITY)),process.env.ROUTING_CONFIDENCE_ESCALATION&&(e.confidence.escalation=parseFloat(process.env.ROUTING_CONFIDENCE_ESCALATION)),process.env.ROUTING_COST_DAILY_LIMIT&&(e.costOptimization.dailyCostLimit=parseFloat(process.env.ROUTING_COST_DAILY_LIMIT)),process.env.ROUTING_COST_PREFER_CHEAPER&&(e.costOptimization.preferCheaperModels=process.env.ROUTING_COST_PREFER_CHEAPER.toLowerCase()==="true"),process.env.ROUTING_FALLBACK_ENABLED&&(e.fallback.enabled=process.env.ROUTING_FALLBACK_ENABLED.toLowerCase()==="true"),process.env.ROUTING_FALLBACK_MAX_ATTEMPTS&&(e.fallback.maxAttempts=parseInt(process.env.ROUTING_FALLBACK_MAX_ATTEMPTS,10)),process.env.ROUTING_VERBOSE&&(e.verbose=process.env.ROUTING_VERBOSE.toLowerCase()==="true"),e}function Ot(s,e,t=D){if(e/100<=.2)return t.tierMapping.trivial;switch(s){case"simple":return t.tierMapping.simple;case"moderate":return t.tierMapping.moderate;case"complex":return t.tierMapping.complex;case"critical":return t.tierMapping.critical}}function Nt(s,e=D){return e.fallback.enabled?e.fallback.chain[s]??null:null}function Fe(s){switch(s){case"booster":case"haiku":return"haiku";case"sonnet":return"sonnet";case"opus":return"opus"}}function Lt(s,e,t,n=D){let i=n.costOptimization.costPerMillionTokens[s],r=e/1e6*i.input,a=t/1e6*i.output;return r+a}function He(s){let{confidence:e}=s;if(e.multiModel<0||e.multiModel>1)throw new Error("multiModel confidence must be between 0 and 1");if(e.humanReview<0||e.humanReview>1)throw new Error("humanReview confidence must be between 0 and 1");if(e.security<0||e.security>1)throw new Error("security confidence must be between 0 and 1");if(e.escalation<0||e.escalation>1)throw new Error("escalation confidence must be between 0 and 1");if(s.costOptimization.dailyCostLimit<0)throw new Error("dailyCostLimit must be non-negative");if(s.costOptimization.costAlertThreshold<0||s.costOptimization.costAlertThreshold>1)throw new Error("costAlertThreshold must be between 0 and 1");if(s.fallback.maxAttempts<0)throw new Error("maxAttempts must be non-negative");if(s.fallback.retryDelayMs<0)throw new Error("retryDelayMs must be non-negative")}var ee=class{tinyDancer;routingConfig;enableCostTracking;avgInputTokens;avgOutputTokens;totalCost=0;costByModel={haiku:0,sonnet:0,opus:0};totalTasks=0;dailyCost=0;lastCostReset=new Date;outcomes=[];maxOutcomes=1e3;constructor(e={}){this.tinyDancer=Ft(e.tinyDancer);let t=this.mergeRoutingConfig(e.routing);this.routingConfig=Ht(t),He(this.routingConfig),this.enableCostTracking=e.enableCostTracking??!0,this.avgInputTokens=e.avgInputTokens??2e3,this.avgOutputTokens=e.avgOutputTokens??500}async route(e){let t=Qt.now();this.checkDailyCostReset();let n=await this.tinyDancer.route(e),i=void 0,a=Ot(n.complexity,n.classification.score,this.routingConfig)[0],o=Fe(a),l=this.buildFallbackChain(a),c=this.enableCostTracking?Lt(o,this.avgInputTokens,this.avgOutputTokens,this.routingConfig):0;this.checkCostLimits(c);let u=this.buildQueenReasoning(n,a,l,c),d=Qt.now()-t,m={tier:a,model:o,complexity:n.complexity,confidence:n.confidence,triggerMultiModel:n.triggerMultiModel,triggerHumanReview:n.triggerHumanReview,fallbackTiers:l,estimatedCost:c,reasoning:u,latencyMs:d,tinyDancerResult:n,advisorResult:i,timestamp:new Date};return this.enableCostTracking&&(this.totalCost+=c,this.costByModel[o]+=c,this.dailyCost+=c),this.totalTasks++,this.routingConfig.verbose&&console.log(`[QueenRouter] Route: ${a} (${o}) complexity=${n.complexity}, confidence=${(n.confidence*100).toFixed(1)}%, cost=$${c.toFixed(4)}`),m}recordOutcome(e,t,n,i,r=i?1:0,a=0,o=0,l){let c={task:e,decision:t,usedTier:n,success:i,qualityScore:r,durationMs:a,fallbackAttempts:o,error:l,timestamp:new Date};this.outcomes.push(c),this.outcomes.length>this.maxOutcomes&&this.outcomes.shift(),this.tinyDancer.recordOutcome?.(e,t.tinyDancerResult,i,r,Fe(n),a),this.routingConfig.verbose&&console.log(`[QueenRouter] Recorded outcome: tier=${n}, success=${i}, quality=${(r*100).toFixed(0)}%, fallbacks=${o}`)}getSuccessRateByTier(){let e={booster:{success:0,total:0},haiku:{success:0,total:0},sonnet:{success:0,total:0},opus:{success:0,total:0}};for(let t of this.outcomes){let n=t.usedTier;e[n].total++,t.success&&e[n].success++}return{booster:e.booster.total>0?e.booster.success/e.booster.total:0,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}}getFallbackStats(){let e=this.outcomes.filter(i=>i.fallbackAttempts>0),t=e.filter(i=>i.success),n=e.reduce((i,r)=>i+r.fallbackAttempts,0);return{totalWithFallback:e.length,avgFallbackAttempts:e.length>0?n/e.length:0,fallbackSuccessRate:e.length>0?t.length/e.length:0}}getCostStats(){return{totalCost:this.totalCost,costByModel:{...this.costByModel},totalTasks:this.totalTasks,avgCostPerTask:this.totalTasks>0?this.totalCost/this.totalTasks:0,dailyCost:this.dailyCost,lastReset:this.lastCostReset}}getOutcomes(){return this.outcomes}getConfig(){return this.routingConfig}updateConfidenceThresholds(e){Object.assign(this.routingConfig.confidence,e),He(this.routingConfig),this.routingConfig.verbose&&console.log("[QueenRouter] Updated confidence thresholds:",e)}reset(){this.totalCost=0,this.costByModel={haiku:0,sonnet:0,opus:0},this.totalTasks=0,this.dailyCost=0,this.lastCostReset=new Date,this.outcomes=[],this.tinyDancer.reset?.()}buildFallbackChain(e){let t=[];if(!this.routingConfig.fallback.enabled)return t;let n=e,i=0;for(;n&&i<this.routingConfig.fallback.maxAttempts;){let r=Nt(n,this.routingConfig);if(r)t.push(r),n=r;else break;i++}return t}buildQueenReasoning(e,t,n,i){let r=[];return r.push(e.reasoning),r.push(`Assigned to ${t.toUpperCase()} tier.`),n.length>0&&r.push(`Fallback chain: ${n.map(a=>a.toUpperCase()).join(" \u2192 ")}.`),this.enableCostTracking&&i>0&&r.push(`Estimated cost: $${i.toFixed(4)}.`),r.join(" ")}checkDailyCostReset(){let e=new Date,t=this.lastCostReset;(e.getUTCDate()!==t.getUTCDate()||e.getUTCMonth()!==t.getUTCMonth()||e.getUTCFullYear()!==t.getUTCFullYear())&&(this.dailyCost=0,this.lastCostReset=e,this.routingConfig.verbose&&console.log("[QueenRouter] Reset daily cost tracking"))}checkCostLimits(e){if(!this.routingConfig.costOptimization.enabled)return;let{dailyCostLimit:t,costAlertThreshold:n}=this.routingConfig.costOptimization;if(t>0){let i=this.dailyCost+e,r=i/t;i>t?console.warn(`[QueenRouter] COST LIMIT EXCEEDED: Daily cost $${i.toFixed(2)} exceeds limit of $${t.toFixed(2)}`):r>=n&&console.warn(`[QueenRouter] Cost alert: ${(r*100).toFixed(0)}% of daily limit ($${i.toFixed(2)} / $${t.toFixed(2)})`)}}mergeRoutingConfig(e){if(!e)return structuredClone(D);let t=structuredClone(D);return e.confidence&&(t.confidence={...t.confidence,...e.confidence}),e.tierMapping&&(t.tierMapping={...t.tierMapping,...e.tierMapping}),e.costOptimization&&(t.costOptimization={...t.costOptimization,...e.costOptimization,costPerMillionTokens:e.costOptimization.costPerMillionTokens?{...t.costOptimization.costPerMillionTokens,...e.costOptimization.costPerMillionTokens}:t.costOptimization.costPerMillionTokens}),e.fallback&&(t.fallback={...t.fallback,...e.fallback,chain:e.fallback.chain?{...t.fallback.chain,...e.fallback.chain}:t.fallback.chain}),e.verbose!==void 0&&(t.verbose=e.verbose),t}};k();An();var Bt=20,Ne=class{db=null;initialized=!1;initialize(e){if(!this.initialized){this.db=e;try{this.db.exec(`
|
|
122
122
|
CREATE TABLE IF NOT EXISTS qe_agent_co_execution (
|
|
123
123
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
124
124
|
agent_a TEXT NOT NULL,
|
|
@@ -133,10 +133,10 @@ import{b as Ee}from"./chunk-XSPMLJCQ.js";import{a as St}from"./chunk-6P4Q4RTC.js
|
|
|
133
133
|
ON qe_agent_co_execution(agent_a, agent_b);
|
|
134
134
|
CREATE INDEX IF NOT EXISTS idx_co_exec_domain
|
|
135
135
|
ON qe_agent_co_execution(domain);
|
|
136
|
-
`),this.initialized=!0}catch(t){console.error(`[CoExecutionRepository] Init error: ${h(t)}`)}}}recordCoExecution(e){if(!this.db)return;let[t,n]=[e.agentA,e.agentB].sort()
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
136
|
+
`),this.initialized=!0}catch(t){console.error(`[CoExecutionRepository] Init error: ${h(t)}`)}}}recordCoExecution(e){if(!this.db)return;let[t,n]=[e.agentA,e.agentB].sort(),i=this.db;De(i,()=>i.prepare(`
|
|
137
|
+
INSERT INTO qe_agent_co_execution (agent_a, agent_b, domain, success, task_description)
|
|
138
|
+
VALUES (?, ?, ?, ?, ?)
|
|
139
|
+
`).run(t,n,e.domain,e.success?1:0,e.taskDescription?.slice(0,500)||null)).catch(r=>{console.debug(`[CoExecutionRepository] Record error: ${h(r)}`)})}getCoExecutionStats(e,t){if(!this.db)return null;let[n,i]=[e,t].sort();try{let r=this.db.prepare(`
|
|
140
140
|
SELECT
|
|
141
141
|
agent_a,
|
|
142
142
|
agent_b,
|
|
@@ -145,7 +145,7 @@ import{b as Ee}from"./chunk-XSPMLJCQ.js";import{a as St}from"./chunk-6P4Q4RTC.js
|
|
|
145
145
|
FROM qe_agent_co_execution
|
|
146
146
|
WHERE agent_a = ? AND agent_b = ?
|
|
147
147
|
GROUP BY agent_a, agent_b
|
|
148
|
-
`).get(n,i);if(!r)return null;let a=r.total_executions>0?r.success_count/r.total_executions:0,o=Math.min(1,r.success_count/
|
|
148
|
+
`).get(n,i);if(!r)return null;let a=r.total_executions>0?r.success_count/r.total_executions:0,o=Math.min(1,r.success_count/Bt);return{agentA:r.agent_a,agentB:r.agent_b,totalExecutions:r.total_executions,successCount:r.success_count,successRate:a,behavioralConfidence:o}}catch(r){return console.debug(`[CoExecutionRepository] Stats error: ${h(r)}`),null}}getCoExecutionPartners(e,t=10){if(!this.db)return[];try{return this.db.prepare(`
|
|
149
149
|
SELECT
|
|
150
150
|
agent_a,
|
|
151
151
|
agent_b,
|
|
@@ -156,15 +156,15 @@ import{b as Ee}from"./chunk-XSPMLJCQ.js";import{a as St}from"./chunk-6P4Q4RTC.js
|
|
|
156
156
|
GROUP BY agent_a, agent_b
|
|
157
157
|
ORDER BY success_count DESC
|
|
158
158
|
LIMIT ?
|
|
159
|
-
`).all(e,e,t).map(i=>{let r=i.total_executions>0?i.success_count/i.total_executions:0;return{agentA:i.agent_a,agentB:i.agent_b,totalExecutions:i.total_executions,successCount:i.success_count,successRate:r,behavioralConfidence:Math.min(1,i.success_count/
|
|
159
|
+
`).all(e,e,t).map(i=>{let r=i.total_executions>0?i.success_count/i.total_executions:0;return{agentA:i.agent_a,agentB:i.agent_b,totalExecutions:i.total_executions,successCount:i.success_count,successRate:r,behavioralConfidence:Math.min(1,i.success_count/Bt)}})}catch(n){return console.debug(`[CoExecutionRepository] Partners error: ${h(n)}`),[]}}recordSwarmCoExecution(e,t,n,i){if(!(!this.db||e.length<2))try{let r=this.db.prepare(`
|
|
160
160
|
INSERT INTO qe_agent_co_execution (agent_a, agent_b, domain, success, task_description)
|
|
161
161
|
VALUES (?, ?, ?, ?, ?)
|
|
162
|
-
`)
|
|
162
|
+
`),a=this.db.transaction(()=>{for(let o=0;o<e.length;o++)for(let l=o+1;l<e.length;l++){let[c,u]=[e[o],e[l]].sort();r.run(c,u,t,n?1:0,i?.slice(0,500)||null)}});De(this.db,()=>a()).catch(o=>{console.debug(`[CoExecutionRepository] Swarm record error: ${h(o)}`)})}catch(r){console.debug(`[CoExecutionRepository] Swarm record error: ${h(r)}`)}}},Oe=null;function $t(){return Oe||(Oe=new Ne),Oe}import{readFileSync as Wn,existsSync as jn,readdirSync as Vn}from"fs";import{join as Kn,basename as Yn}from"path";function Ut(s){let e=s.split(`
|
|
163
163
|
`);if(e.length<2||e[0].trim()!=="---")return null;for(let t=1;t<e.length;t++)if(e[t].trim()==="---")return e.slice(1,t).join(`
|
|
164
|
-
`);return null}function F(s){let e=s.trim();return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function
|
|
165
|
-
`),n=-1;for(let c=0;c<t.length;c++)if(/^dependencies:\s*$/.test(t[c])){n=c+1;break}if(n===-1)return null;let i=[];for(let c=n;c<t.length;c++){let u=t[c];if(u.trim()!==""){if(u.length>0&&u[0]!==" "&&u[0]!==" ")break;i.push(u)}}if(i.length===0)return null;let r={},a={section:"none",item:{},inList:!1},o=()=>{a.item.name&&(r.agents||(r.agents=[]),r.agents.push({name:a.item.name,type:a.item.type||"hard",reason:a.item.reason||""}),a.item={})},l=()=>{a.item.name&&(r.mcpServers||(r.mcpServers=[]),r.mcpServers.push({name:a.item.name,required:a.item.required==="true"}),a.item={})};for(let c of i){let u=c.trim();if(u==="")continue;let d=u.match(/^(agents|mcp_servers|models):\s*$/);if(d){a.section==="agents"&&a.inList&&o(),a.section==="mcp_servers"&&a.inList&&l(),a.inList=!1,a.section=d[1];continue}if(a.section==="agents"||a.section==="mcp_servers"){let
|
|
166
|
-
`)){let n=t.match(/^name:\s*(.+)$/);if(n)return F(n[1])}return null}function Ut(s){let e=new Map,t=[];if(!Gn(s))return t.push(`Agents directory not found: ${s}`),{nodes:e,spawnOrder:[],cycles:[],warnings:t};let n=jn(s).filter(a=>a.startsWith("qe-")&&a.endsWith(".md"));for(let a of n){let o;try{o=zn(Wn(s,a),"utf-8")}catch{t.push(`Failed to read agent file: ${a}`);continue}let l=Yn(o)||Vn(a,".md"),c=Kn(o),u=[],d=[],g=[];if(c?.agents)for(let p of c.agents)p.type==="hard"?u.push(p.name):p.type==="soft"?d.push(p.name):p.type==="peer"&&g.push(p.name);e.set(l,{agentName:l,hardDeps:u,softDeps:d,peerDeps:g,dependencies:c||{}})}let i=new Set(e.keys());for(let[a,o]of e)for(let l of o.hardDeps)i.has(l)||t.push(`Agent "${a}" declares hard dependency on "${l}" which is not in the agent directory`);let r=Zn(e);for(let a of r)t.push(`Dependency cycle detected: ${a.join(" -> ")}`);return{nodes:e,spawnOrder:Xn(e,r),cycles:r,warnings:t}}function Zn(s){let e=[],t=new Set,n=new Set,i=[];function r(a){t.add(a),n.add(a),i.push(a);let o=s.get(a);if(o){for(let l of o.hardDeps)if(!t.has(l)&&s.has(l))r(l);else if(n.has(l)){let c=i.indexOf(l);c!==-1&&e.push([...i.slice(c),l])}}i.pop(),n.delete(a)}for(let a of s.keys())t.has(a)||r(a);return e}function Xn(s,e){let t=new Set(e.flat()),n=[],i=new Set,r=new Set;function a(o){if(i.has(o)||t.has(o)||r.has(o))return;r.add(o);let l=s.get(o);if(l)for(let c of l.hardDeps)s.has(c)&&a(c);r.delete(o),i.add(o),n.push(o)}for(let o of s.keys())a(o);for(let o of t)n.includes(o)||n.push(o);return n}function qt(s,e){let t=new Set(s),n=[],i=[];for(let l of s){let c=e.nodes.get(l);if(!c)continue;let u=c.hardDeps.filter(d=>!t.has(d));u.length>0&&(i.push({agent:l,missing:u}),n.push(`Advisory: "${l}" has unsatisfied hard dependencies: ${u.join(", ")}. Proceeding anyway.`))}let r=[],a=new Set,o=new Set(s);for(;o.size>0;){let l=[];for(let c of o){let u=e.nodes.get(c);if(!u){l.push(c);continue}u.hardDeps.filter(g=>t.has(g)).every(g=>a.has(g))&&l.push(c)}if(l.length===0){n.push(`Could not resolve dependency ordering for: ${[...o].join(", ")}. Placing in final phase.`),r.push([...o]);break}r.push(l);for(let c of l)a.add(c),o.delete(c);o=new Set([...o])}return{phases:r,unsatisfiedHardDeps:i,warnings:n}}var Ne={defaultTtlMs:0,cleanupIntervalMs:6e4,maxMailboxSize:1e3};var Q=class{mailboxes=new Map;messageHandlers=new Map;broadcastHandlers=new Map;domainAgents=new Map;cognitiveRouter=null;cognitiveRouterInitialized=!1;compressedMessages=new Map;createMailbox(e,t){let n=this.mailboxes.get(e);if(n)return this.toSnapshot(n);let i={agentId:e,domain:t,messages:[],unreadCount:0,lastRead:Date.now()};this.mailboxes.set(e,i);let r=this.domainAgents.get(t);return r||(r=new Set,this.domainAgents.set(t,r)),r.add(e),this.toSnapshot(i)}getMailbox(e){let t=this.mailboxes.get(e);if(t)return this.toSnapshot(t)}deleteMailbox(e){let t=this.mailboxes.get(e);if(!t)return!1;let n=this.domainAgents.get(t.domain);n&&(n.delete(e),n.size===0&&this.domainAgents.delete(t.domain));for(let i of t.messages)this.compressedMessages.delete(i.id);return this.messageHandlers.delete(e),this.mailboxes.delete(e),!0}send(e){if(e.to==="broadcast"){this.broadcast(e.domain,e);return}let t=this.mailboxes.get(e.to);if(!t)throw new Error(`No mailbox found for agent '${e.to}'. Create a mailbox first with createMailbox().`);let n=this.compressViaCognitive(e);t.messages.push(n),t.unreadCount++;let i=this.messageHandlers.get(e.to);if(i)for(let r of i)try{r(e)}catch{}}broadcast(e,t){let n=this.domainAgents.get(e);if(!n)return;for(let r of n){if(r===t.from)continue;let a=this.mailboxes.get(r);if(a){a.messages.push(t),a.unreadCount++;let o=this.messageHandlers.get(r);if(o)for(let l of o)try{l(t)}catch{}}}let i=this.broadcastHandlers.get(e);if(i)for(let r of i)try{r(e,t)}catch{}}receive(e,t){let n=this.mailboxes.get(e);if(!n||n.unreadCount===0)return[];let i=Date.now(),r=n.messages.length-n.unreadCount,a=n.messages.slice(r);return a=a.filter(o=>!this.isExpired(o,i)),t?.type&&(a=a.filter(o=>o.type===t.type)),t?.since!==void 0&&(a=a.filter(o=>o.timestamp>=t.since)),t?.limit!==void 0&&t.limit>0&&(a=a.slice(0,t.limit)),n.unreadCount=0,n.lastRead=i,this.decompressMessages(a)}peek(e){let t=this.mailboxes.get(e);if(!t)return 0;let n=Date.now(),i=t.messages.length-t.unreadCount,r=0;for(let a=i;a<t.messages.length;a++)this.isExpired(t.messages[a],n)||r++;return r}cleanup(e){let t=Date.now(),n=t-e,i=0;for(let r of this.mailboxes.values()){let a=r.messages.length,o=r.messages.length-r.unreadCount;r.messages=r.messages.filter((c,u)=>c.timestamp<n?(this.compressedMessages.delete(c.id),!1):this.isExpired(c,t)?(this.compressedMessages.delete(c.id),!1):!0);let l=a-r.messages.length;i+=l,l>0&&(r.unreadCount=r.messages.filter(c=>c.timestamp>r.lastRead).length)}return i}onMessage(e,t){let n=this.messageHandlers.get(e);return n||(n=[],this.messageHandlers.set(e,n)),n.push(t),()=>{let i=this.messageHandlers.get(e);if(i){let r=i.indexOf(t);r>=0&&i.splice(r,1)}}}onBroadcast(e,t){let n=this.broadcastHandlers.get(e);return n||(n=[],this.broadcastHandlers.set(e,n)),n.push(t),()=>{let i=this.broadcastHandlers.get(e);if(i){let r=i.indexOf(t);r>=0&&i.splice(r,1)}}}getAgentsInDomain(e){let t=this.domainAgents.get(e);return t?Array.from(t):[]}getDomains(){return Array.from(this.domainAgents.keys())}get size(){return this.mailboxes.size}clear(){this.mailboxes.clear(),this.messageHandlers.clear(),this.broadcastHandlers.clear(),this.domainAgents.clear(),this.compressedMessages.clear(),this.cognitiveRouter=null,this.cognitiveRouterInitialized=!1}isExpired(e,t){return!e.ttl||e.ttl<=0?!1:t>e.timestamp+e.ttl}toSnapshot(e){return{agentId:e.agentId,domain:e.domain,messages:[...e.messages],unreadCount:e.unreadCount,lastRead:e.lastRead}}ensureCognitiveRouter(){if(this.cognitiveRouterInitialized)return this.cognitiveRouter;if(this.cognitiveRouterInitialized=!0,!Ct())return null;try{this.cognitiveRouter=vt()??null}catch{this.cognitiveRouter=null}return this.cognitiveRouter}compressViaCognitive(e){try{let t=this.ensureCognitiveRouter();if(!t)return e;let n=`${e.from}->${e.to}`,i=t.send(n,e.from,e.to,e.payload);return i.compressed&&i.compressedSize<i.originalSize?(this.compressedMessages.set(e.id,i),{...e,payload:i.payload}):e}catch{return e}}decompressMessages(e){let t=this.cognitiveRouter;return!t||this.compressedMessages.size===0?e:e.map(n=>{try{let i=this.compressedMessages.get(n.id);if(!i)return n;let r=t.receive(i);return this.compressedMessages.delete(n.id),{...n,payload:r}}catch{return n}})}getCognitiveRoutingStats(){return this.cognitiveRouter?this.cognitiveRouter.getStats():null}};import{randomUUID as zt}from"node:crypto";mt();import{randomUUID as te}from"node:crypto";var ne=class{spans=new Map;traceIndex=new Map;maxSpans;constructor(e=1e4){this.maxSpans=e}startTrace(e){let t=te(),n=te(),i={traceId:t,spanId:n},r=this.createSpan(i,e);return{context:i,span:r}}startSpan(e){let t=e.parentContext,n=t?.traceId??te(),i=te(),r={traceId:n,spanId:i,parentSpanId:t?.spanId,baggage:t?.baggage},a=this.createSpan(r,e);return{context:r,span:a}}completeSpan(e){let t=this.spans.get(e);t&&(t.endTime=Date.now(),t.status="completed")}failSpan(e,t){let n=this.spans.get(e);n&&(n.endTime=Date.now(),n.status="error",n.errorMessage=t)}getTrace(e){let t=this.traceIndex.get(e);return t?Array.from(t).map(n=>this.spans.get(n)).filter(n=>n!==void 0).sort((n,i)=>n.startTime-i.startTime):[]}getSpan(e){return this.spans.get(e)}getActiveSpans(){return Array.from(this.spans.values()).filter(e=>e.status==="active")}getStats(){let e=new Set,t=new Set;for(let[n,i]of this.traceIndex)Array.from(i).map(a=>this.spans.get(a)).filter(a=>a!==void 0).some(a=>a.status==="active")?e.add(n):t.add(n);return{totalSpans:this.spans.size,activeTraces:e.size,completedTraces:t.size}}purge(e){let t=Date.now()-e,n=0;for(let[i,r]of this.traceIndex){let a=Array.from(r).map(c=>this.spans.get(c)).filter(c=>c!==void 0),o=a.every(c=>c.status!=="active"),l=a.every(c=>(c.endTime??c.startTime)<t);if(o&&l){for(let c of r)this.spans.delete(c),n++;this.traceIndex.delete(i)}}return n}dispose(){this.spans.clear(),this.traceIndex.clear()}createSpan(e,t){this.spans.size>=this.maxSpans&&this.purge(6e4);let n={traceId:e.traceId,spanId:e.spanId,parentSpanId:e.parentSpanId,operationName:t.operationName,agentId:t.agentId,domain:t.domain,startTime:Date.now(),tags:t.tags??{},status:"active"};this.spans.set(e.spanId,n);let i=this.traceIndex.get(e.traceId);return i||(i=new Set,this.traceIndex.set(e.traceId,i)),i.add(e.spanId),n}},Jn="trace:";function ie(s){return`${Jn}${JSON.stringify({traceId:s.traceId,spanId:s.spanId,parentSpanId:s.parentSpanId})}`}function Le(s){return new ne(s)}var re=class{mailbox;config;teams=new Map;registeredAgents=new Set;agentDomains=new Map;subscriptions=new Map;cleanupTimer=null;initialized=!1;constructor(e,t){this.mailbox=e??new Q,this.config={...Ne,...t}}initialize(e){this.initialized||(e&&Object.assign(this.config,e),this.config.cleanupIntervalMs>0&&(this.cleanupTimer=setInterval(()=>{this.performCleanup()},this.config.cleanupIntervalMs)),this.initialized=!0)}shutdown(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null),this.mailbox.clear(),this.teams.clear(),this.registeredAgents.clear(),this.agentDomains.clear(),this.subscriptions.clear(),this.initialized=!1}createTeam(e){if(this.teams.has(e.domain))throw new Error(`Team already exists for domain '${e.domain}'. Use getTeamStatus() to inspect the existing team.`);let t={domain:e.domain,leadAgentId:e.leadAgentId,maxTeammates:e.maxTeammates,teammateIds:[...e.teammateIds],autoAssignEnabled:e.autoAssignEnabled};this.teams.set(e.domain,t),this.registerAgent(e.leadAgentId,e.domain);for(let n of e.teammateIds)this.registerAgent(n,e.domain)}getTeamStatus(e){let t=this.teams.get(e);if(!t)return;let n=[t.leadAgentId,...t.teammateIds],i=n.filter(a=>this.mailbox.peek(a)===0),r=0;for(let a of n)r+=this.mailbox.peek(a);return{domain:t.domain,leadAgentId:t.leadAgentId,teammateIds:[...t.teammateIds],activeAgentCount:n.filter(a=>this.registeredAgents.has(a)).length,idleAgentIds:i,totalUnreadMessages:r}}registerAgent(e,t){if(this.registeredAgents.has(e))return;this.registeredAgents.add(e),this.agentDomains.set(e,t),this.mailbox.createMailbox(e,t);let n=this.teams.get(t);n&&n.autoAssignEnabled&&e!==n.leadAgentId&&!n.teammateIds.includes(e)&&n.teammateIds.length<n.maxTeammates&&n.teammateIds.push(e)}unregisterAgent(e){if(!this.registeredAgents.has(e))return!1;let t=this.agentDomains.get(e);if(t){let n=this.teams.get(t);if(n){let i=n.teammateIds.indexOf(e);i>=0&&n.teammateIds.splice(i,1)}}return this.mailbox.deleteMailbox(e),this.subscriptions.delete(e),this.registeredAgents.delete(e),this.agentDomains.delete(e),!0}sendMessage(e,t,n,i,r){this.validateAgent(e,"sender"),this.validateAgent(t,"recipient");let a=this.agentDomains.get(e),o=r?.traceContext?ie(r.traceContext):r?.correlationId,l={id:zt(),from:e,to:t,domain:r?.domain??a,type:n,payload:i,timestamp:Date.now(),correlationId:o,replyTo:r?.replyTo,ttl:r?.ttl??(this.config.defaultTtlMs>0?this.config.defaultTtlMs:void 0)};return this.mailbox.send(l),this.notifySubscribers(t,l),l}broadcast(e,t,n,i){let r=i?.from??"__system__";r!=="__system__"&&this.validateAgent(r,"broadcast sender");let a=i?.traceContext?ie(i.traceContext):i?.correlationId,o={id:zt(),from:r,to:"broadcast",domain:e,type:t,payload:n,timestamp:Date.now(),correlationId:a,ttl:i?.ttl??(this.config.defaultTtlMs>0?this.config.defaultTtlMs:void 0)};this.mailbox.broadcast(e,o);let l=this.mailbox.getAgentsInDomain(e);for(let c of l)c!==r&&this.notifySubscribers(c,o);return o}onMessage(e,t){this.validateAgent(e,"subscription target");let n=this.subscriptions.get(e);return n||(n=[],this.subscriptions.set(e,n)),n.push(t),()=>{let i=this.subscriptions.get(e);if(i){let r=i.indexOf(t);r>=0&&i.splice(r,1)}}}getIdleAgents(e){let t=[],n=e?this.mailbox.getAgentsInDomain(e):Array.from(this.registeredAgents);for(let i of n)this.mailbox.peek(i)===0&&t.push(i);return t}isRegistered(e){return this.registeredAgents.has(e)}getAgentDomain(e){return this.agentDomains.get(e)}getRegisteredAgents(){return Array.from(this.registeredAgents)}getUnreadCount(e){return this.mailbox.peek(e)}receiveMessages(e){return this.mailbox.receive(e)}getMailboxService(){return this.mailbox}validateAgent(e,t){if(!this.registeredAgents.has(e))throw new Error(`Unknown ${t} '${e}'. Register the agent first with registerAgent() or createTeam().`)}notifySubscribers(e,t){let n=this.subscriptions.get(e);if(!(!n||n.length===0))for(let i of n)try{i(t)}catch{}}performCleanup(){let e=this.config.defaultTtlMs>0?this.config.defaultTtlMs*10:this.config.cleanupIntervalMs*60;this.mailbox.cleanup(e)}};function Qe(s){return new re(void 0,s)}var Gt={maxActiveTeams:13,defaultTeamSize:3,autoScaleEnabled:!1,scaleUpThreshold:10,scaleDownIdleMs:6e4},se=class s{static SYSTEM_AGENT_ID="__dtm_system__";static SYSTEM_DOMAIN="__system__";adapter;config;teams=new Map;systemAgentRegistered=!1;constructor(e,t){this.adapter=e,this.config={...Gt,...t}}createDomainTeam(e,t,n){if(this.teams.has(e))throw new Error(`Domain team already exists for '${e}'. Use getDomainTeam() to inspect the existing team.`);if(this.teams.size>=this.config.maxActiveTeams)throw new Error(`Maximum active teams (${this.config.maxActiveTeams}) reached. Remove an existing team before creating a new one.`);let i=n?[...n]:[],r=this.getMaxTeamSize(e);i.length+1>r&&(i.length=r-1);let a=Date.now(),o={domain:e,leadAgentId:t,teammateIds:i,createdAt:a,taskCount:0,completedCount:0,lastActivity:new Map};o.lastActivity.set(t,a);for(let c of i)o.lastActivity.set(c,a);this.teams.set(e,o);let l={domain:e,leadAgentId:t,maxTeammates:r-1,teammateIds:i,autoAssignEnabled:!1};return this.adapter.createTeam(l),this.toSnapshot(o)}removeDomainTeam(e){let t=this.teams.get(e);if(!t)return!1;for(let n of[t.leadAgentId,...t.teammateIds])this.adapter.unregisterAgent(n);return this.teams.delete(e),!0}getDomainTeam(e){let t=this.teams.get(e);return t?this.toSnapshot(t):void 0}addTeammate(e,t){let n=this.teams.get(e);if(!n||t===n.leadAgentId||n.teammateIds.includes(t))return!1;let i=this.getMaxTeamSize(e);return 1+n.teammateIds.length>=i?!1:(n.teammateIds.push(t),n.lastActivity.set(t,Date.now()),this.adapter.registerAgent(t,e),!0)}listDomainTeams(){return Array.from(this.teams.values(),e=>this.toSnapshot(e))}assignTaskToTeam(e,t,n){let i=this.teams.get(e);return i?(this.ensureSystemAgent(),this.adapter.sendMessage(s.SYSTEM_AGENT_ID,i.leadAgentId,"task-assignment",{taskId:t,payload:n},{domain:e}),i.taskCount++,i.lastActivity.set(i.leadAgentId,Date.now()),!0):!1}broadcastToDomain(e,t,n){let i=this.teams.get(e);if(!i)throw new Error(`No domain team found for '${e}'. Create a team first with createDomainTeam().`);this.adapter.broadcast(e,t,n,{from:"__system__"});let r=Date.now();i.lastActivity.set(i.leadAgentId,r);for(let a of i.teammateIds)i.lastActivity.set(a,r)}getTeamHealth(e){let t=this.teams.get(e);if(!t)return;let n=[t.leadAgentId,...t.teammateIds],i=n.length,r=0,a=0,o=0;for(let c of n)if(this.adapter.isRegistered(c)){r++;let u=this.adapter.getUnreadCount(c);o+=u,u===0&&a++}let l=t.taskCount-t.completedCount;return{domain:e,teamSize:i,activeAgents:r,idleAgents:a,pendingMessages:o,tasksPending:l,tasksCompleted:t.completedCount,healthy:r>0&&r===i&&l<this.config.scaleUpThreshold*2}}scaleTeam(e,t){let n=this.teams.get(e);if(!n)throw new Error(`No domain team found for '${e}'. Create a team first with createDomainTeam().`);let i=Math.max(this.getMaxTeamSize(e),t,this.config.maxActiveTeams),r=Math.max(1,Math.min(t,i)),a=1+n.teammateIds.length,o=[],l=[];if(r>a){let c=r-a;for(let u=0;u<c;u++){let d=`${e}-teammate-${Date.now()}-${u}`;n.teammateIds.push(d),n.lastActivity.set(d,Date.now()),this.adapter.registerAgent(d,e),o.push(d)}}else if(r<a){let c=a-r;for(let u=0;u<c;u++){let d=n.teammateIds.pop();d&&(n.lastActivity.delete(d),this.adapter.unregisterAgent(d),l.push(d))}}return{domain:e,previousSize:a,newSize:1+n.teammateIds.length,addedAgents:o,removedAgents:l}}getIdleTeammates(e){if(e){let n=this.teams.get(e);return n?this.getIdleAgentsForTeam(n):[]}let t=[];for(let n of this.teams.values())t.push(...this.getIdleAgentsForTeam(n));return t}rebalance(){let e=[],t=new Set,n=Array.from(this.teams.values(),a=>{let o=this.getTargetTeamSize(a.domain),l=1+a.teammateIds.length,c=this.getIdleAgentsForTeam(a).filter(u=>u!==a.leadAgentId);return{domain:a.domain,team:a,currentSize:l,targetSize:o,idleTeammates:c}}),i=n.filter(a=>a.currentSize>a.targetSize&&a.idleTeammates.length>0).sort((a,o)=>o.currentSize-o.targetSize-(a.currentSize-a.targetSize)),r=n.filter(a=>a.currentSize<a.targetSize).sort((a,o)=>a.currentSize-a.targetSize-(o.currentSize-o.targetSize));for(let a of i)for(let o of r){if(o.currentSize>=o.targetSize)continue;if(a.idleTeammates.length===0)break;if(o.currentSize>=this.getMaxTeamSize(o.domain))continue;let l=a.idleTeammates.shift(),c=a.team.teammateIds.indexOf(l);c>=0&&a.team.teammateIds.splice(c,1),a.team.lastActivity.delete(l),a.currentSize--,this.adapter.unregisterAgent(l),this.adapter.registerAgent(l,o.domain),o.team.teammateIds.push(l),o.team.lastActivity.set(l,Date.now()),o.currentSize++,e.push({agentId:l,fromDomain:a.domain,toDomain:o.domain}),t.add(a.domain),t.add(o.domain)}return{moves:e,teamsAffected:t.size}}dispose(){for(let e of this.teams.values())for(let t of[e.leadAgentId,...e.teammateIds])this.adapter.unregisterAgent(t);this.teams.clear(),this.systemAgentRegistered&&(this.adapter.unregisterAgent(s.SYSTEM_AGENT_ID),this.systemAgentRegistered=!1)}markTaskCompleted(e){let t=this.teams.get(e);return t?(t.completedCount<t.taskCount&&t.completedCount++,!0):!1}ensureSystemAgent(){this.systemAgentRegistered||(this.adapter.registerAgent(s.SYSTEM_AGENT_ID,s.SYSTEM_DOMAIN),this.systemAgentRegistered=!0)}getMaxTeamSize(e){return this.config.domainTeamSizes&&e in this.config.domainTeamSizes?this.config.domainTeamSizes[e]:this.config.defaultTeamSize}getTargetTeamSize(e){return this.getMaxTeamSize(e)}getIdleAgentsForTeam(e){let t=[];for(let n of[e.leadAgentId,...e.teammateIds])this.adapter.isRegistered(n)&&this.adapter.getUnreadCount(n)===0&&t.push(n);return t}toSnapshot(e){return{domain:e.domain,leadAgentId:e.leadAgentId,teammateIds:[...e.teammateIds],createdAt:e.createdAt,taskCount:e.taskCount,completedCount:e.completedCount}}};function Be(s,e){return new se(s,e)}k();var oe={failureThreshold:3,resetTimeoutMs:6e4,halfOpenSuccessThreshold:2,failureWindowMs:12e4,cascadeEnabled:!1,cascadeTargets:void 0},ae=class extends Error{domain;retryAfterMs;constructor(e,t){let n=t!=null?` (retry after ${t}ms)`:"";super(`Circuit breaker is open for domain '${e}'${n}`),this.name="DomainCircuitOpenError",this.domain=e,this.retryAfterMs=t}},A=class{state="closed";failures=[];totalRequests=0;totalSuccesses=0;totalFailures=0;rejectedCount=0;lastFailureTime;lastSuccessTime;openedAt;halfOpenSuccesses=0;config;stateChangeHandlers=new Set;domain;constructor(e,t){this.domain=e,this.config={...oe,...t}}canExecute(){let e=this.getState();return e==="closed"?!0:e!=="open"}async execute(e){if(this.totalRequests++,this.getState()==="open")throw this.rejectedCount++,this.emitEvent({type:"request-rejected",domain:this.domain,timestamp:Date.now(),metadata:{retryAfterMs:this.getTimeUntilTransition()}}),new ae(this.domain,this.getTimeUntilTransition());try{let n=await e();return this.recordSuccess(),n}catch(n){throw this.recordFailure(Z(n)),n}}recordSuccess(){this.totalSuccesses++,this.lastSuccessTime=Date.now(),this.getState()==="half-open"&&(this.halfOpenSuccesses++,console.log(`[DomainCircuitBreaker:${this.domain}] Half-open success ${this.halfOpenSuccesses}/${this.config.halfOpenSuccessThreshold}`),this.halfOpenSuccesses>=this.config.halfOpenSuccessThreshold&&this.transitionTo("closed"))}recordFailure(e){this.totalFailures++,this.lastFailureTime=Date.now(),this.failures.push({timestamp:Date.now(),message:e.message}),this.cleanOldFailures();let t=this.getState();if(t==="half-open"){console.log(`[DomainCircuitBreaker:${this.domain}] Failure in half-open state, re-opening`),this.transitionTo("open");return}t==="closed"&&this.failures.length>=this.config.failureThreshold&&(console.log(`[DomainCircuitBreaker:${this.domain}] Failure threshold reached (${this.failures.length}/${this.config.failureThreshold}), opening circuit`),this.transitionTo("open"))}getState(){return this.state==="open"&&this.openedAt!=null&&Date.now()-this.openedAt>=this.config.resetTimeoutMs&&this.transitionTo("half-open"),this.state}getStats(){let e=this.getState();return{domain:this.domain,state:e,totalRequests:this.totalRequests,successCount:this.totalSuccesses,failureCount:this.totalFailures,rejectedCount:this.rejectedCount,lastFailureTime:this.lastFailureTime,lastSuccessTime:this.lastSuccessTime,openedAt:this.openedAt,timeUntilHalfOpen:e==="open"?this.getTimeUntilTransition():void 0,consecutiveSuccesses:this.halfOpenSuccesses}}reset(){let e=this.state;this.state="closed",this.failures=[],this.halfOpenSuccesses=0,this.openedAt=void 0,e!=="closed"&&(console.log(`[DomainCircuitBreaker:${this.domain}] Manually reset from '${e}' to 'closed'`),this.emitEvent({type:"state-change",domain:this.domain,previousState:e,newState:"closed",timestamp:Date.now(),metadata:{trigger:"manual-reset"}}))}forceOpen(){console.log(`[DomainCircuitBreaker:${this.domain}] Force-opening circuit`),this.transitionTo("open")}getRecentFailures(e=5){return this.failures.slice(-e).map(t=>`[${new Date(t.timestamp).toISOString()}] ${t.message}`)}onStateChange(e){return this.stateChangeHandlers.add(e),()=>{this.stateChangeHandlers.delete(e)}}getConfig(){return this.config}transitionTo(e){let t=this.state;if(t!==e){switch(this.state=e,e){case"open":this.openedAt=Date.now(),this.halfOpenSuccesses=0;break;case"half-open":this.halfOpenSuccesses=0,console.log(`[DomainCircuitBreaker:${this.domain}] Transitioning to half-open, allowing probe requests`);break;case"closed":this.failures=[],this.openedAt=void 0,this.halfOpenSuccesses=0,console.log(`[DomainCircuitBreaker:${this.domain}] Circuit closed, domain is healthy`);break}this.emitEvent({type:"state-change",domain:this.domain,previousState:t,newState:e,timestamp:Date.now()})}}cleanOldFailures(){let e=Date.now()-this.config.failureWindowMs;this.failures=this.failures.filter(t=>t.timestamp>e)}getTimeUntilTransition(){if(this.state==="open"&&this.openedAt!=null){let e=Date.now()-this.openedAt,t=this.config.resetTimeoutMs-e;return Math.max(0,t)}}emitEvent(e){for(let t of this.stateChangeHandlers)try{t(e)}catch(n){console.log(`[DomainCircuitBreaker:${this.domain}] State change handler error: ${h(n)}`)}}};k();var $e={critical:{failureThreshold:2,resetTimeoutMs:3e4,halfOpenSuccessThreshold:2,failureWindowMs:6e4,cascadeEnabled:!1,cascadeTargets:void 0},standard:{failureThreshold:3,resetTimeoutMs:6e4,halfOpenSuccessThreshold:2,failureWindowMs:12e4,cascadeEnabled:!1,cascadeTargets:void 0},lenient:{failureThreshold:5,resetTimeoutMs:12e4,halfOpenSuccessThreshold:3,failureWindowMs:3e5,cascadeEnabled:!1,cascadeTargets:void 0}},jt={"test-generation":"critical","test-execution":"critical","coverage-analysis":"critical","quality-assessment":"critical","security-compliance":"critical","defect-intelligence":"standard","requirements-validation":"standard","code-intelligence":"standard","contract-testing":"standard","visual-accessibility":"lenient","chaos-resilience":"lenient","learning-optimization":"lenient","enterprise-integration":"standard"},B=class{breakers=new Map;defaultConfig;globalHandlers=new Set;constructor(e){this.defaultConfig={...oe,...e}}getBreaker(e){let t=this.breakers.get(e);if(!t){let n=jt[e],i=n?{...this.defaultConfig,...$e[n]}:this.defaultConfig;t=new A(e,i),this.breakers.set(e,t),t.onStateChange(r=>this.handleBreakerEvent(r)),console.log(`[DomainBreakerRegistry] Created breaker for '${e}' (criticality: ${n??"default"})`)}return t}configureBreaker(e,t){let n={...this.defaultConfig,...t},i=new A(e,n);i.onStateChange(r=>this.handleBreakerEvent(r)),this.breakers.set(e,i),console.log(`[DomainBreakerRegistry] Reconfigured breaker for '${e}'`)}configureCriticality(e,t){let n=$e[t];this.configureBreaker(e,n),console.log(`[DomainBreakerRegistry] Set '${e}' criticality to '${t}'`)}canExecuteInDomain(e){return this.getBreaker(e).canExecute()}async executeInDomain(e,t){return this.getBreaker(e).execute(t)}getAllStats(){let e=new Map;for(let[t,n]of this.breakers)e.set(t,n.getStats());return e}getOpenDomains(){let e=[];for(let[t,n]of this.breakers)n.getState()==="open"&&e.push(t);return e}getHealthyDomains(){let e=[];for(let[t,n]of this.breakers)n.getState()==="closed"&&e.push(t);return e}getDegradedDomains(){let e=[];for(let[t,n]of this.breakers)n.getState()==="half-open"&&e.push(t);return e}getHealthSummary(){let e=0,t=0,n=0;for(let i of this.breakers.values())switch(i.getState()){case"closed":e++;break;case"half-open":t++;break;case"open":n++;break}return{healthy:e,degraded:t,open:n,total:this.breakers.size}}resetAll(){for(let e of this.breakers.values())e.reset();console.log(`[DomainBreakerRegistry] Reset all ${this.breakers.size} breakers`)}reset(e){let t=this.breakers.get(e);t&&t.reset()}onAnyStateChange(e){return this.globalHandlers.add(e),()=>{this.globalHandlers.delete(e)}}handleBreakerEvent(e){for(let t of this.globalHandlers)try{t(e)}catch(n){console.log(`[DomainBreakerRegistry] Global handler error: ${h(n)}`)}e.type==="state-change"&&e.newState==="open"&&this.propagateCascade(e.domain)}propagateCascade(e){let t=this.breakers.get(e);if(!t)return;let n=t.getConfig();if(!(!n.cascadeEnabled||!n.cascadeTargets?.length))for(let i of n.cascadeTargets){if(i===e)continue;let r=this.getBreaker(i);if(r.getState()!=="open"){console.log(`[DomainBreakerRegistry] Cascading open from '${e}' to '${i}'`),r.forceOpen();let o={type:"cascade-triggered",domain:i,timestamp:Date.now(),metadata:{sourceDomain:e,cascadedFrom:e}};for(let l of this.globalHandlers)try{l(o)}catch(c){console.log(`[DomainBreakerRegistry] Cascade event handler error: ${h(c)}`)}}}}};function Wt(s){return new B(s)}var x=["smoke","standard","deep","crisis"];var $=["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","requirements-validation","code-intelligence","security-compliance","contract-testing","visual-accessibility","chaos-resilience","learning-optimization","enterprise-integration"],ce=["test-generation","coverage-analysis","quality-assessment"],Ue={"test-generation":["generator","specialist"],"test-execution":["tester","coordinator"],"coverage-analysis":["analyzer","specialist"],"quality-assessment":["analyzer","validator"],"defect-intelligence":["analyzer","specialist"],"requirements-validation":["validator","reviewer"],"code-intelligence":["analyzer","specialist"],"security-compliance":["analyzer","validator"],"contract-testing":["tester","validator"],"visual-accessibility":["tester","validator"],"chaos-resilience":["tester","specialist"],"learning-optimization":["optimizer","specialist"],"enterprise-integration":["coordinator","validator"]},ei={tier:"smoke",maxAgents:3,agentTeamsEnabled:!1,domains:["test-execution","quality-assessment"],estimatedCost:"minimal",description:"Lightweight smoke test on every commit. Runs core test execution and quality assessment with minimal agent count to catch obvious regressions quickly.",triggers:[{type:"commit"},{type:"schedule",conditions:{interval:"hourly"}}]},ti={tier:"standard",maxAgents:7,agentTeamsEnabled:!1,domains:["test-generation","test-execution","coverage-analysis","quality-assessment","security-compliance"],estimatedCost:"moderate",description:"Standard validation for pull requests. Covers test generation, execution, coverage, quality, and security across up to 7 agents. Agent teams are optional.",triggers:[{type:"pr"},{type:"manual"}]},ni={tier:"deep",maxAgents:15,agentTeamsEnabled:!0,domains:[...$],estimatedCost:"high",description:"Deep validation for pre-release and critical path changes. Activates all 13 domains with up to 15 agents and full agent team collaboration.",triggers:[{type:"release"},{type:"pr",conditions:{criticalPath:!0}},{type:"manual",conditions:{requestedTier:"deep"}}]},ii={tier:"crisis",maxAgents:15,agentTeamsEnabled:!0,domains:[...$],estimatedCost:"unlimited",description:"Crisis response for production incidents. All domains active with competing hypotheses enabled. Unlimited cost budget to resolve incidents as fast as possible.",triggers:[{type:"incident"},{type:"manual",conditions:{requestedTier:"crisis"}}]},qe={smoke:ei,standard:ti,deep:ni,crisis:ii};var ri=["password","secret","token","crypto","auth","credential","jwt","oauth"],si=["async","await","Promise","setTimeout","setInterval","Worker","mutex","lock"],ai={securityKeywords:ri,concurrencyKeywords:si,enableDimensionOverrides:!1};function oi(s,e){let t=s+e;return t<=8?"trivial":t<=20?"simple":t<=40?"moderate":t<=70?"complex":"critical"}var U=class{config;constructor(e){this.config={...ai,...e}}analyzeExtendedDimensions(e){let t=e.split(`
|
|
167
|
-
`),n=Math.max(t.length,1),i=this.countKeywordLines(t,this.config.securityKeywords),r=le(i/n,0,1),a=this.countKeywordLines(t,this.config.concurrencyKeywords),o=le(a/n,0,1),l=this.countPatternMatches(e,/\.(map|filter|reduce|flatMap|forEach)\s*\(/g),c=le(l/n,0,1),u=this.countPatternMatches(e,/^export\s/gm),d=Math.max(this.countPatternMatches(e,/^(export\s+)?(const|let|var|function|class|interface|type|enum)\s/gm),1),g=le(u/d,0,1);return{securitySurface:r,concurrency:o,dataFlow:c,apiSurface:g}}compose(e,t,n){let i=oi(e.cyclomatic,e.cognitive),r=this.analyzeExtendedDimensions(n),a=[],o=[],l;switch(i){case"trivial":case"simple":a.push({agentType:"qe-test-generator",priority:1,reason:`${i} complexity \u2014 basic test generation sufficient`}),o.push("unit"),l="haiku";break;case"moderate":a.push({agentType:"qe-test-generator",priority:1,reason:"Moderate complexity requires thorough test generation"},{agentType:"qe-code-intelligence",priority:2,reason:"Moderate complexity benefits from code intelligence analysis"}),o.push("unit","integration"),l="sonnet";break;case"complex":a.push({agentType:"qe-test-generator",priority:1,reason:"Complex code needs comprehensive test generation"},{agentType:"qe-security-scanner",priority:2,reason:"High complexity warrants security analysis"},{agentType:"qe-code-intelligence",priority:2,reason:"Complex code requires deep code intelligence"}),o.push("unit","integration","security"),l="sonnet";break;case"critical":a.push({agentType:"qe-test-generator",priority:1,reason:"Critical complexity demands full test generation"},{agentType:"qe-security-scanner",priority:1,reason:"Critical complexity mandates security scanning"},{agentType:"qe-code-intelligence",priority:1,reason:"Critical complexity requires deep analysis"},{agentType:"qe-chaos-resilience",priority:2,reason:"Critical systems need chaos/resilience testing"},{agentType:"qe-performance",priority:2,reason:"Critical complexity warrants performance analysis"}),o.push("unit","integration","security","chaos","performance"),l="opus";break}return r.securitySurface>.3&&(a.some(c=>c.agentType==="qe-security-scanner")||a.push({agentType:"qe-security-scanner",priority:2,reason:`High security surface (${(r.securitySurface*100).toFixed(0)}%) \u2014 security scanning recommended`}),o.includes("security")||o.push("security")),r.concurrency>.3&&(a.some(c=>c.agentType==="qe-chaos-resilience")||a.push({agentType:"qe-chaos-resilience",priority:2,reason:`High concurrency (${(r.concurrency*100).toFixed(0)}%) \u2014 chaos/resilience testing recommended`}),o.includes("chaos")||o.push("chaos")),r.apiSurface>.5&&(o.includes("integration")||o.push("integration")),a.sort((c,u)=>c.priority-u.priority),{agents:a,testTypes:o,recommendedTier:l,complexityCategory:i}}countKeywordLines(e,t){let n=0;for(let i of e)for(let r of t)if(i.includes(r)){n++;break}return n}countPatternMatches(e,t){let n=e.match(t);return n?n.length:0}};function le(s,e,t){return Math.max(e,Math.min(t,s))}var Vt=200,Kt=10,Yt=3,ue=class{configs;history=[];escalationCount=0;deescalationCount=0;constructor(e){this.configs={...qe,...e}}selectTier(e){let t,n;if(e.manualOverride)return t=e.manualOverride,n=`Manual override to "${t}" tier`,this.buildResult(t,n,e);if(e.trigger==="incident"||e.isHotfix)return t="crisis",n=e.isHotfix?"Hotfix deployment triggers crisis-level validation":"Production incident triggers crisis-level response",this.buildResult(t,n,e);if(e.trigger==="release")return t="deep",n="Pre-release validation requires deep tier across all domains",this.buildResult(t,n,e);if(e.trigger==="pr"){let i=e.changedFiles!==void 0&&e.changedFiles>Kt,r=e.affectedDomains!==void 0&&e.affectedDomains.length>Yt;if(i||r){t="deep";let a=[];return i&&a.push(`>${Kt} changed files (${e.changedFiles})`),r&&a.push(`>${Yt} affected domains (${e.affectedDomains.length})`),n=`PR escalated to deep tier: ${a.join(" and ")}`,this.buildResult(t,n,e)}return t="standard",n="Pull request triggers standard tier validation",this.buildResult(t,n,e)}return t="smoke",n=e.trigger==="commit"?"Commit triggers lightweight smoke validation":`Trigger "${e.trigger}" defaults to smoke tier`,this.buildResult(t,n,e)}allocateAgents(e,t){let n=this.resolveTargetDomains(e,t);if(n.length===0)return[];let i=e.maxAgents;return n.length>=i?this.allocateWithPriority(n,i):this.allocateWithSurplus(n,i)}escalate(e,t){let n=x.indexOf(e),i=Math.min(n+1,x.length-1),r=x[i],a=e!==r,o=a?`Escalated from "${e}" to "${r}": ${t}`:`Already at maximum tier "${e}", cannot escalate further`;return a&&this.escalationCount++,this.buildResult(r,o,{trigger:"manual"})}deescalate(e){let t=x.indexOf(e),n=Math.max(t-1,0),i=x[n],r=e!==i,a=r?`De-escalated from "${e}" to "${i}"`:`Already at minimum tier "${e}", cannot de-escalate further`;return r&&this.deescalationCount++,this.buildResult(i,a,{trigger:"manual"})}getStats(){let e={smoke:0,standard:0,deep:0,crisis:0};for(let t of this.history)e[t.tier]++;return{totalSelections:this.history.length,selectionsByTier:e,escalationCount:this.escalationCount,deescalationCount:this.deescalationCount,recentSelections:[...this.history].slice(-20)}}_teamComposer;setTeamComposer(e){this._teamComposer=e}selectTierWithComposition(e,t,n){let i=this.selectTier(e);if(!t||!n)return{...i,composition:void 0};let a=(this._teamComposer??new U).compose(t,i.selectedTier,n);return{...i,composition:a}}buildResult(e,t,n){let i=this.configs[e],r=this.allocateAgents(i,n.affectedDomains),a={tier:e,reason:t,timestamp:Date.now(),trigger:n.trigger};return this.history.push(a),this.history.length>Vt&&this.history.splice(0,this.history.length-Vt),{selectedTier:e,config:i,reason:t,agentAllocation:r}}resolveTargetDomains(e,t){let n=e.domains.includes("all")?$:e.domains;if(!t||t.length===0)return[...n];let i=new Set(n),r=t.filter(a=>i.has(a));return r.length>0?r:[...n]}allocateWithPriority(e,t){let n=new Set(ce),i=[],r=t,a=e.filter(l=>n.has(l)),o=e.filter(l=>!n.has(l));for(let l of a){if(r<=0)break;i.push(this.createAllocation(l,1)),r--}for(let l of o){if(r<=0)break;i.push(this.createAllocation(l,1)),r--}return i}allocateWithSurplus(e,t){let n=new Set(ce),i=new Map;for(let u of e)i.set(u,1);let r=t-e.length,a=e.filter(u=>n.has(u)),o=e.filter(u=>!n.has(u)),l=0;for(;r>0&&a.length>0;){let u=a[l%a.length];if(i.set(u,(i.get(u)??0)+1),r--,l++,l>=a.length*2)break}let c=0;for(;r>0&&o.length>0;){let u=o[c%o.length];i.set(u,(i.get(u)??0)+1),r--,c++}for(;r>0&&a.length>0;){let u=a[l%a.length];i.set(u,(i.get(u)??0)+1),r--,l++}return e.map(u=>this.createAllocation(u,i.get(u)??1))}createAllocation(e,t){let n=Ue[e]??["specialist"];return{domain:e,agentCount:t,agentTypes:[...n]}}};function ze(s){return new ue(s)}k();var ge={enabled:!0,minQualityScore:.6,rejectOnFailure:!0,gates:[{name:"test-pass-rate",type:"test-pass-rate",threshold:.8,weight:.35,required:!0},{name:"coverage",type:"coverage",threshold:0,weight:.25,required:!1},{name:"security",type:"security",threshold:0,weight:.25,required:!0},{name:"performance",type:"performance",threshold:3e4,weight:.15,required:!1}]},de=class{config;constructor(e={}){this.config={...ge,...e},e.gates&&(this.config={...this.config,gates:e.gates})}evaluate(e){if(!this.config.enabled)return console.log("[QualityGateEnforcer] Gates disabled, auto-passing"),{passed:!0,score:1,exitCode:0,gates:[],reason:"Quality gates disabled"};if(e.status==="failed")return console.log(`[QualityGateEnforcer] Task ${e.taskId} has failed status`),{passed:!1,score:0,exitCode:this.config.rejectOnFailure?2:0,gates:[],reason:"Task reported failed status"};let t=[],n=[];for(let d of this.config.gates){let g=this.checkGate(d,e);t.push(g),!g.passed&&d.required&&n.push(d.name)}let i=this.config.gates.reduce((d,g)=>d+g.weight,0),r=i>0?t.reduce((d,g)=>{let p=this.config.gates.find(K=>K.name===g.gate);if(!p)return d;let T=g.passed?1:this.computePartialScore(g);return d+T*(p.weight/i)},0):1,a=n.length>0,o=r<this.config.minQualityScore,l=!a&&!o,c;if(!l){let d=[];a&&d.push(`Required gates failed: ${n.join(", ")}`),o&&d.push(`Score ${r.toFixed(3)} below minimum ${this.config.minQualityScore}`),c=d.join("; ")}let u=!l&&this.config.rejectOnFailure?2:0;return console.log(`[QualityGateEnforcer] Task ${e.taskId}: ${l?"PASSED":"FAILED"} (score=${r.toFixed(3)}, gates=${t.filter(d=>d.passed).length}/${t.length})`),{passed:l,score:r,exitCode:u,gates:t,reason:c}}getConfig(){return{...this.config}}checkGate(e,t){let n=this.extractMetricForGate(e,t),i=this.meetsThreshold(e,n);return{gate:e.name,passed:i,actual:n,threshold:e.threshold,weight:e.weight}}extractMetricForGate(e,t){let n=t.metrics;switch(e.type){case"coverage":return n.coverageChange??0;case"test-pass-rate":{let i=n.testsPassed??0,r=n.testsFailed??0,a=i+r;return a>0?i/a:1}case"security":return n.securityIssues??0;case"performance":return n.performanceMs??t.duration;case"custom":{let i=t.output[e.name];return typeof i=="number"?i:0}default:return 0}}meetsThreshold(e,t){switch(e.type){case"security":return t<=e.threshold;case"performance":return t<=e.threshold;default:return t>=e.threshold}}computePartialScore(e){let t=this.config.gates.find(n=>n.name===e.gate);if(!t)return 0;switch(t.type){case"security":case"performance":{if(t.threshold===0)return 0;let n=t.threshold/e.actual;return Math.max(0,Math.min(1,n))}default:{if(t.threshold===0)return 1;let n=e.actual/t.threshold;return Math.max(0,Math.min(1,n))}}}};var ci={trainPatterns:!0,qualityGate:ge,patternDomains:["test-generation","coverage-analysis","security-compliance","quality-assessment","defect-intelligence","contract-testing"],emitEvents:!0,maxPatternsPerTask:5},li={"test-generation":{types:["test-template","assertion-pattern","mock-pattern"],contentKeys:["testCode","template","assertions","mocks"],baseConfidence:.6},"coverage-analysis":{types:["coverage-strategy","mutation-strategy"],contentKeys:["coverageReport","gaps","strategy","recommendations"],baseConfidence:.55},"security-compliance":{types:["security-pattern","vulnerability-fix"],contentKeys:["findings","fixes","recommendations","rules"],baseConfidence:.5},"quality-assessment":{types:["quality-rule","threshold-pattern"],contentKeys:["rules","thresholds","assessments"],baseConfidence:.5},"defect-intelligence":{types:["defect-pattern","root-cause"],contentKeys:["rootCause","pattern","prediction","analysis"],baseConfidence:.45},"contract-testing":{types:["api-contract","schema-pattern"],contentKeys:["contract","schema","endpoints","violations"],baseConfidence:.55},"test-execution":{types:["flaky-fix","retry-strategy"],contentKeys:["flakyTests","retryPolicy","stabilization"],baseConfidence:.5},"visual-accessibility":{types:["visual-baseline","a11y-check"],contentKeys:["baseline","violations","wcagResults"],baseConfidence:.5},"chaos-resilience":{types:["perf-benchmark","resilience-pattern"],contentKeys:["benchmark","faultInjection","recoveryTime"],baseConfidence:.45}},me=class{config;gateEnforcer;patternStore;completionHandlers=new Set;stats={totalProcessed:0,accepted:0,rejected:0,patternsExtracted:0};constructor(e={},t){this.config={...ci,...e},e.qualityGate&&(this.config={...this.config,qualityGate:{...ge,...e.qualityGate}}),this.gateEnforcer=new de(this.config.qualityGate),this.patternStore=t??null}async onTaskCompleted(e){this.stats.totalProcessed++,console.log(`[TaskCompletedHook] Processing task ${e.taskId} (agent=${e.agentId}, domain=${e.domain}, status=${e.status})`);let t=this.gateEnforcer.evaluate(e);if(!t.passed&&this.config.qualityGate.rejectOnFailure){this.stats.rejected++;let r={action:"reject",exitCode:2,reason:t.reason||"Quality gate check failed",gateResult:t};return console.log(`[TaskCompletedHook] Task ${e.taskId} REJECTED: ${r.reason}`),this.emitCompletion(e.taskId,r),r}let n=0;if(this.config.trainPatterns&&this.patternStore){let r=this.extractPatterns(e);n=await this.storePatterns(r,e),this.stats.patternsExtracted+=n}this.stats.accepted++;let i={action:"accept",patternsExtracted:n};return console.log(`[TaskCompletedHook] Task ${e.taskId} ACCEPTED (score=${t.score.toFixed(3)}, patterns=${n})`),this.emitCompletion(e.taskId,i),i}extractPatterns(e){let t=[],n=e.domain;if(!this.config.patternDomains.includes(n))return t;let i=li[n];if(!i)return this.extractGenericPatterns(e);let r=this.computeConfidenceBoost(e.metrics);for(let a of i.types){if(t.length>=this.config.maxPatternsPerTask)break;for(let o of i.contentKeys){if(t.length>=this.config.maxPatternsPerTask)break;let l=e.output[o];if(l==null)continue;let c=typeof l=="string"?l:JSON.stringify(l);if(c.length<10)continue;let u=Math.min(1,i.baseConfidence+r);t.push({domain:n,type:a,content:c,confidence:u,metadata:{sourceTaskId:e.taskId,sourceAgent:e.agentId,taskType:e.type,duration:e.duration,extractedFrom:o,timestamp:e.timestamp}})}}return t}onCompletion(e){this.completionHandlers.add(e)}offCompletion(e){this.completionHandlers.delete(e)}getStats(){return{...this.stats}}resetStats(){this.stats={totalProcessed:0,accepted:0,rejected:0,patternsExtracted:0}}async storePatterns(e,t){if(!this.patternStore||e.length===0)return 0;let n=0;for(let i of e)try{let r=await this.patternStore.store(i),a=t.status==="completed";await this.patternStore.recordOutcome(r,a),n++}catch(r){console.error(`[TaskCompletedHook] Failed to store pattern: ${h(r)}`)}return n>0&&console.log(`[TaskCompletedHook] Stored ${n}/${e.length} patterns from task ${t.taskId}`),n}extractGenericPatterns(e){let t=[];for(let[n,i]of Object.entries(e.output)){if(t.length>=this.config.maxPatternsPerTask)break;if(i==null)continue;let r=typeof i=="string"?i:JSON.stringify(i);r.length<10||t.push({domain:e.domain,type:"generic",content:r,confidence:.3+this.computeConfidenceBoost(e.metrics),metadata:{sourceTaskId:e.taskId,sourceAgent:e.agentId,taskType:e.type,extractedFrom:n,timestamp:e.timestamp}})}return t}computeConfidenceBoost(e){let t=0,n=e.testsPassed??0,i=e.testsFailed??0,r=n+i;return r>0&&(t+=n/r*.15),e.coverageChange!==void 0&&e.coverageChange>0&&(t+=Math.min(.1,e.coverageChange*.5)),e.securityIssues!==void 0&&e.securityIssues===0&&(t+=.1),e.performanceMs!==void 0&&e.performanceMs<5e3&&(t+=.05),Math.min(.4,t)}emitCompletion(e,t){if(this.config.emitEvents)for(let n of this.completionHandlers)try{n(e,t)}catch(i){console.error(`[TaskCompletedHook] Completion handler error: ${h(i)}`)}}};k();var ui={"test-template":"test-template","assertion-pattern":"assertion-pattern","mock-pattern":"mock-pattern","coverage-strategy":"coverage-strategy","mutation-strategy":"mutation-strategy","security-pattern":"error-handling","vulnerability-fix":"error-handling","quality-rule":"test-template","threshold-pattern":"test-template","defect-pattern":"error-handling","root-cause":"error-handling","api-contract":"api-contract","schema-pattern":"api-contract","flaky-fix":"flaky-fix","retry-strategy":"flaky-fix","visual-baseline":"visual-baseline","a11y-check":"a11y-check","perf-benchmark":"perf-benchmark","resilience-pattern":"perf-benchmark",generic:"test-template"};function di(s){return ui[s]??"test-template"}function gi(s){let e=Ae(s.domain);if(e)return e;let t=Ae(s.content);return t||"test-generation"}function mi(s){let e=0;for(let t=0;t<s.length;t++){let n=s.charCodeAt(t);e=(e<<5)-e+n,e=e&e}return Math.abs(e).toString(36).slice(0,8)}var pe=class{constructor(e){this.reasoningBank=e}reasoningBank;async store(e){let t=gi(e),n=di(e.type),i=mi(e.content),r=`${t}-${e.type}-${i}`,a=[t,e.type,...e.metadata.sourceTaskId?[`task:${e.metadata.sourceTaskId}`]:[]],o={patternType:n,name:r,description:`Auto-extracted ${e.type} pattern from ${e.domain} domain`,template:{type:"prompt",content:e.content,variables:[]},context:{tags:a},confidence:e.confidence};try{let l=await this.reasoningBank.storePattern(o);if(l.success)return l.value.id;throw console.error(`[ReasoningBankPatternStore] Failed to store pattern: ${l.error.message}`),l.error}catch(l){throw console.error(`[ReasoningBankPatternStore] Store error: ${h(l)}`),l}}async recordOutcome(e,t){let n={patternId:e,success:t};try{let i=await this.reasoningBank.recordOutcome(n);i.success||console.error(`[ReasoningBankPatternStore] Failed to record outcome: ${i.error.message}`)}catch(i){console.error(`[ReasoningBankPatternStore] recordOutcome error: ${h(i)}`)}}};Sn();var Ge={maxHypothesesPerInvestigation:5,convergenceThreshold:.2,investigationTimeoutMs:3e5,minEvidenceForConvergence:3,autoRejectThreshold:.15};import{randomUUID as je}from"node:crypto";var he=class{investigations=new Map;config;constructor(e){this.config={...Ge,...e}}createInvestigation(e,t,n){let i=`inv-${je().slice(0,8)}`,r=Date.now(),a={id:i,taskId:e,domain:t,description:n,hypotheses:[],status:"open",maxHypotheses:this.config.maxHypothesesPerInvestigation,convergenceThreshold:this.config.convergenceThreshold,createdAt:r,updatedAt:r};return this.investigations.set(i,a),this.toSnapshot(a)}addHypothesis(e,t,n,i){let r=this.getInvestigationMutable(e);if(r.hypotheses.length>=r.maxHypotheses)throw new Error(`Investigation ${e} already has ${r.maxHypotheses} hypotheses (max)`);let a={id:`hyp-${je().slice(0,8)}`,description:t,investigatorAgentId:i,strategy:n,status:"pending",evidence:[],confidenceScore:.5,createdAt:Date.now(),updatedAt:Date.now()};return r.hypotheses.push(a),r.updatedAt=Date.now(),r.status==="open"&&(r.status="investigating"),a}startHypothesis(e,t){let n=this.getInvestigationMutable(e),i=this.findHypothesis(n,t);if(i.status!=="pending")throw new Error(`Hypothesis ${t} cannot be started (current status: ${i.status})`);i.status="investigating",i.updatedAt=Date.now(),n.updatedAt=Date.now()}completeHypothesis(e,t){let n=this.getInvestigationMutable(e),i=this.findHypothesis(n,t);i.status="completed",i.updatedAt=Date.now(),n.updatedAt=Date.now()}submitEvidence(e,t,n){let i=this.getInvestigationMutable(e),r=this.findHypothesis(i,t),a={...n,id:`evi-${je().slice(0,8)}`,hypothesisId:t,timestamp:Date.now()};return r.evidence.push(a),r.confidenceScore=this.calculateConfidence(r),r.updatedAt=Date.now(),i.updatedAt=Date.now(),r.confidenceScore<this.config.autoRejectThreshold&&r.evidence.length>=2&&(r.status="rejected"),a}converge(e){let t=this.getInvestigationMutable(e),n=t.hypotheses.reduce((c,u)=>c+u.evidence.length,0);if(n<this.config.minEvidenceForConvergence){t.status="inconclusive";let c={winningHypothesisId:null,confidence:0,evidenceSummary:`Insufficient evidence (${n}/${this.config.minEvidenceForConvergence} required)`,rejectedHypotheses:t.hypotheses.filter(u=>u.status==="rejected").map(u=>u.id),method:"evidence-scoring"};return t.convergenceResult=c,t.updatedAt=Date.now(),c}let i=[...t.hypotheses].filter(c=>c.status!=="rejected").sort((c,u)=>u.confidenceScore-c.confidenceScore),r="evidence-scoring",a=null,o=0;i.length===0?t.status="inconclusive":i.length===1?(a=i[0].id,o=i[0].confidenceScore,r="unanimous",t.status="converged"):i[0].confidenceScore-i[1].confidenceScore>=t.convergenceThreshold?(a=i[0].id,o=i[0].confidenceScore,t.status="converged"):t.status="inconclusive";let l={winningHypothesisId:a,confidence:o,evidenceSummary:this.buildEvidenceSummary(t),rejectedHypotheses:t.hypotheses.filter(c=>c.status==="rejected").map(c=>c.id),method:r};return t.convergenceResult=l,t.updatedAt=Date.now(),l}getInvestigation(e){let t=this.investigations.get(e);return t?this.toSnapshot(t):void 0}listInvestigations(){return Array.from(this.investigations.values()).map(e=>this.toSnapshot(e))}getConfig(){return this.config}dispose(){this.investigations.clear()}getInvestigationMutable(e){let t=this.investigations.get(e);if(!t)throw new Error(`Investigation ${e} not found`);return t}findHypothesis(e,t){let n=e.hypotheses.find(i=>i.id===t);if(!n)throw new Error(`Hypothesis ${t} not found in investigation ${e.id}`);return n}calculateConfidence(e){if(e.evidence.length===0)return .5;let t=0,n=0;for(let r of e.evidence)r.supports?t+=r.weight:n+=r.weight;let i=t+n;return i===0?.5:Math.min(1,Math.max(0,t/i))}buildEvidenceSummary(e){let t=[];for(let n of e.hypotheses){let i=n.evidence.filter(a=>a.supports).length,r=n.evidence.filter(a=>!a.supports).length;t.push(`${n.id}: ${i} supporting, ${r} refuting (confidence: ${n.confidenceScore.toFixed(2)})`)}return t.join("; ")}toSnapshot(e){return{...e,hypotheses:e.hypotheses.map(t=>({...t,evidence:[...t.evidence]}))}}};function We(s){return new he(s)}import{randomUUID as pi}from"node:crypto";var Ve={localFleetId:"local",heartbeatIntervalMs:3e4,serviceTimeoutMs:9e4,maxPendingMessages:5e3,maxRoutes:100};var ye=class{config;services=new Map;routes=[];outbox=[];inbox=[];handlers=[];messagesSent=0;messagesReceived=0;constructor(e){this.config={...Ve,...e}}registerService(e,t,n,i){if(this.services.has(e))throw new Error(`Service '${e}' already registered`);let r=Date.now(),a={fleetId:e,name:t,domains:[...n],status:"active",registeredAt:r,lastHeartbeat:r,metadata:i};return this.services.set(e,a),fe(a)}deregisterService(e){let t=this.services.get(e);if(!t)return!1;t.status="deregistered";for(let n=this.routes.length-1;n>=0;n--)this.routes[n].targetFleetId===e&&this.routes.splice(n,1);return this.services.delete(e),!0}heartbeat(e){let t=this.services.get(e);return t?(t.lastHeartbeat=Date.now(),(t.status==="degraded"||t.status==="unreachable")&&(t.status="active"),!0):!1}addRoute(e,t,n,i=0){if(this.routes.length>=this.config.maxRoutes)throw new Error(`Maximum routes (${this.config.maxRoutes}) reached`);let r={sourceDomain:e,targetDomain:t,targetFleetId:n,priority:i,active:!0};return this.routes.push(r),this.routes.sort((a,o)=>o.priority-a.priority),Zt(r)}removeRoute(e,t){let n=this.routes.findIndex(i=>i.sourceDomain===e&&i.targetFleetId===t);return n<0?!1:(this.routes.splice(n,1),!0)}send(e,t,n,i,r,a){let o=e==="any"?this.resolveRoute(t,n):e;if(!o)throw new Error(`No route found for ${t} -> ${n}`);let l={id:pi(),sourceFleetId:this.config.localFleetId,targetFleetId:o,sourceDomain:t,targetDomain:n,type:i,payload:r,timestamp:Date.now(),ttl:a?.ttl,correlationId:a?.correlationId};return this.outbox.length>=this.config.maxPendingMessages&&this.outbox.shift(),this.outbox.push(l),this.messagesSent++,l}receive(e){this.inbox.length>=this.config.maxPendingMessages&&this.inbox.shift(),this.inbox.push(e),this.messagesReceived++;for(let t of this.handlers)try{t(e)}catch{}}onMessage(e){return this.handlers.push(e),()=>{let t=this.handlers.indexOf(e);t>=0&&this.handlers.splice(t,1)}}drainOutbox(){let e=[...this.outbox];return this.outbox.length=0,e}drainInbox(){let e=[...this.inbox];return this.inbox.length=0,e}findServicesByDomain(e){return Array.from(this.services.values()).filter(t=>t.status==="active"&&t.domains.includes(e)).map(fe)}getService(e){let t=this.services.get(e);return t?fe(t):void 0}listServices(){return Array.from(this.services.values()).map(fe)}listRoutes(){return this.routes.map(Zt)}checkHealth(){let e=Date.now();for(let t of this.services.values()){if(t.status==="deregistered")continue;let n=e-t.lastHeartbeat;n>this.config.serviceTimeoutMs?t.status="unreachable":n>this.config.serviceTimeoutMs*.6&&(t.status="degraded")}}getHealth(){return{localFleetId:this.config.localFleetId,connectedServices:Array.from(this.services.values()).filter(e=>e.status==="active").length,activeRoutes:this.routes.filter(e=>e.active).length,pendingMessages:this.outbox.length+this.inbox.length,messagesSent:this.messagesSent,messagesReceived:this.messagesReceived}}dispose(){this.services.clear(),this.routes.length=0,this.outbox.length=0,this.inbox.length=0,this.handlers.length=0}resolveRoute(e,t){for(let i of this.routes)if(i.active&&i.sourceDomain===e&&i.targetDomain===t){let r=this.services.get(i.targetFleetId);if(r&&r.status==="active")return i.targetFleetId}let n=this.findServicesByDomain(t);return n.length>0?n[0].fleetId:void 0}};function fe(s){return{fleetId:s.fleetId,name:s.name,domains:[...s.domains],status:s.status,registeredAt:s.registeredAt,lastHeartbeat:s.lastHeartbeat,metadata:s.metadata,endpoint:void 0}}function Zt(s){return{sourceDomain:s.sourceDomain,targetDomain:s.targetDomain,targetFleetId:s.targetFleetId,priority:s.priority,active:s.active}}function Ke(s){return new ye(s)}var Xt={name:"default",scaleUpQueueRatio:3,scaleDownIdleRatio:.5,errorRateScaleUpThreshold:.3,minAgents:2,maxAgents:15,cooldownMs:3e4,sampleWindowSize:5},Ye={defaultPolicy:Xt,metricsHistorySize:100,decisionHistorySize:50};import{randomUUID as hi}from"node:crypto";De();k();var Te=class s{config;policy;metricsHistory=[];events=[];lastScaleTime=0;scaleUpCount=0;scaleDownCount=0;totalDecisions=0;currentAgents;lastDecision;db=null;persistCount=0;static KV_NAMESPACE="scaling-metrics";static KV_KEY="dynamic-scaler-snapshot";static PERSIST_INTERVAL=10;static KV_TTL=7200;constructor(e=2,t){this.config={...Ye,...t},this.policy=this.config.defaultPolicy,this.currentAgents=e}recordMetrics(e){this.metricsHistory.push(e),this.metricsHistory.length>this.config.metricsHistorySize&&this.metricsHistory.shift(),this.persistCount++,this.persistCount%s.PERSIST_INTERVAL===0&&this.persistSnapshot().catch(()=>{})}evaluate(){let e=this.getAverageMetrics(),t=Date.now();if(this.totalDecisions++,t-this.lastScaleTime<this.policy.cooldownMs){let o={action:"maintain",currentAgents:this.currentAgents,targetAgents:this.currentAgents,reason:"Cooldown period active",metrics:e,timestamp:t};return this.lastDecision=o,o}let n="maintain",i=this.currentAgents,r="Workload within acceptable range";if(e.errorRate>this.policy.errorRateScaleUpThreshold)n="scale-up",i=Math.min(this.currentAgents+2,this.policy.maxAgents),r=`High error rate (${(e.errorRate*100).toFixed(1)}% > ${(this.policy.errorRateScaleUpThreshold*100).toFixed(1)}% threshold)`;else if(this.currentAgents>0&&e.queueDepth/Math.max(1,this.currentAgents)>this.policy.scaleUpQueueRatio){n="scale-up";let o=Math.ceil(e.queueDepth/this.policy.scaleUpQueueRatio);i=Math.min(o,this.policy.maxAgents),r=`Queue depth ratio ${(e.queueDepth/Math.max(1,this.currentAgents)).toFixed(1)} > ${this.policy.scaleUpQueueRatio} threshold`}if(n==="maintain"&&this.currentAgents>this.policy.minAgents){let o=this.currentAgents>0?e.idleAgents/this.currentAgents:0;if(o>this.policy.scaleDownIdleRatio){n="scale-down";let l=Math.floor(e.idleAgents*.5);i=Math.max(this.currentAgents-l,this.policy.minAgents),r=`Idle ratio ${(o*100).toFixed(1)}% > ${(this.policy.scaleDownIdleRatio*100).toFixed(1)}% threshold`}}i=Math.max(this.policy.minAgents,Math.min(this.policy.maxAgents,i)),i===this.currentAgents&&(n="maintain");let a={action:n,currentAgents:this.currentAgents,targetAgents:i,reason:r,metrics:e,timestamp:t};return this.lastDecision=a,a}async execute(e,t){let n={id:`scale-${hi().slice(0,8)}`,decision:e,executedAt:Date.now(),success:!0};if(e.action==="maintain")return this.recordEvent(n),n;try{if(t&&!await t(e.currentAgents,e.targetAgents)){let r={...n,success:!1,error:"Executor returned false"};return this.recordEvent(r),r}return this.currentAgents=e.targetAgents,this.lastScaleTime=Date.now(),e.action==="scale-up"&&this.scaleUpCount++,e.action==="scale-down"&&this.scaleDownCount++,this.recordEvent(n),n}catch(i){let r={...n,success:!1,error:h(i)};return this.recordEvent(r),r}}setPolicy(e){this.policy=e}getPolicy(){return{...this.policy}}getCurrentAgents(){return this.currentAgents}getStats(){return{scaleUpCount:this.scaleUpCount,scaleDownCount:this.scaleDownCount,totalDecisions:this.totalDecisions,currentAgents:this.currentAgents,policyName:this.policy.name,lastDecision:this.lastDecision,recentEvents:[...this.events].slice(-10)}}getMetricsHistory(){return[...this.metricsHistory]}async initialize(){try{this.db=R(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(e){console.warn("[DynamicScaler] DB init failed, using memory-only:",h(e)),this.db=null}}dispose(){this.metricsHistory.length=0,this.events.length=0}getAverageMetrics(){let e=this.metricsHistory.slice(-this.policy.sampleWindowSize);if(e.length===0)return{queueDepth:0,activeAgents:this.currentAgents,idleAgents:0,avgTaskDurationMs:0,errorRate:0,throughput:0,timestamp:Date.now()};let t=n=>e.reduce((i,r)=>i+n(r),0)/e.length;return{queueDepth:Math.round(t(n=>n.queueDepth)),activeAgents:Math.round(t(n=>n.activeAgents)),idleAgents:Math.round(t(n=>n.idleAgents)),avgTaskDurationMs:Math.round(t(n=>n.avgTaskDurationMs)),errorRate:t(n=>n.errorRate),throughput:t(n=>n.throughput),timestamp:Date.now()}}recordEvent(e){this.events.push(e),this.events.length>this.config.decisionHistorySize&&this.events.shift(),this.persistCount++,this.persistCount%s.PERSIST_INTERVAL===0&&this.persistSnapshot().catch(()=>{})}async loadFromKv(){if(this.db)try{let e=await this.db.kvGet(s.KV_KEY,s.KV_NAMESPACE);if(e){if(Array.isArray(e.metricsHistory))for(let t of e.metricsHistory)this.metricsHistory.push(t);if(Array.isArray(e.events))for(let t of e.events)this.events.push(t)}}catch(e){console.warn("[DynamicScaler] Failed to load KV snapshot:",h(e))}}async persistSnapshot(){if(this.db)try{let e={metricsHistory:this.metricsHistory.slice(-50),events:this.events.slice(-50)};await this.db.kvSet(s.KV_KEY,e,s.KV_NAMESPACE,s.KV_TTL)}catch(e){console.warn("[DynamicScaler] Failed to persist KV snapshot:",h(e))}}};function Ze(s,e){return new Te(s,e)}var fi=[{name:"Core Testing",domains:["test-generation","test-execution","coverage-analysis","quality-assessment"],priority:"p0",description:"Core testing workflow domains"},{name:"Intelligence",domains:["defect-intelligence","code-intelligence","requirements-validation","security-compliance"],priority:"p0",description:"Intelligence and analysis domains"},{name:"Specialized",domains:["contract-testing","visual-accessibility","chaos-resilience","learning-optimization"],priority:"p1",description:"Specialized testing domains"}],q={"generate-tests":["test-generation"],"execute-tests":["test-execution"],"analyze-coverage":["coverage-analysis"],"assess-quality":["quality-assessment"],"predict-defects":["defect-intelligence"],"validate-requirements":["requirements-validation"],"index-code":["code-intelligence"],"scan-security":["security-compliance"],"validate-contracts":["contract-testing"],"test-accessibility":["visual-accessibility"],"run-chaos":["chaos-resilience"],"optimize-learning":["learning-optimization"],"cross-domain-workflow":[],"protocol-execution":[],"ideation-assessment":["requirements-validation","coverage-analysis","security-compliance"]},Jt={maxConcurrentTasks:50,defaultTaskTimeout:3e5,taskRetryLimit:3,workStealing:{enabled:!0,idleThreshold:5e3,loadThreshold:10,stealBatchSize:3,checkInterval:1e4},enableMetrics:!0,metricsInterval:6e4,priorityWeights:{p0:100,p1:50,p2:25,p3:10},enableRouting:!0};function E(s){return Object.hasOwn(q,s)?q[s]:[]}function en(s){q["cross-domain-workflow"]=s,q["protocol-execution"]=s}import{readFileSync as Ti,existsSync as vi}from"fs";import{join as Ci}from"path";import{parse as bi}from"yaml";De();import{randomUUID as yi}from"crypto";var z={RISK_WEIGHTS:2160*60*60*1e3,SFDIPOT_WEIGHTS:2160*60*60*1e3,FLAKY_PATTERNS:720*60*60*1e3,AC_QUALITY:1440*60*60*1e3};function G(s,e){let t=Date.now(),n=yi().split("-")[0];return`${e||s}-signal-${t}-${n}`}function j(s){return new Date(Date.now()+s).toISOString()}function w(s){return new Date(s.expiresAt)<new Date}var b={STRATEGIC:"qcsd/strategic",TACTICAL:"qcsd/tactical",OPERATIONAL:"qcsd/operational",QUALITY_CRITERIA:"qcsd/quality-criteria"},Je=class{memory;initialized=!1;constructor(e={}){this.memory=e.memoryManager||R()}async initialize(){this.initialized||(await this.memory.initialize(),this.initialized=!0,console.log("[CrossPhaseMemory] Initialized with UnifiedMemoryManager"))}async storeRiskSignal(e,t){await this.ensureInitialized();let n={id:G("strategic","risk"),timestamp:new Date().toISOString(),source:"production",target:"ideation",loopType:"strategic",version:"1.0.0",expiresAt:j(z.RISK_WEIGHTS),riskWeights:e,recommendations:t};return await this.store(b.STRATEGIC,n),n}async queryRiskSignals(){return await this.ensureInitialized(),(await this.queryByNamespace(b.STRATEGIC)).filter(t=>!w(t))}async storeSFDIPOTSignal(e,t,n){await this.ensureInitialized();let i={id:G("tactical","sfdipot"),timestamp:new Date().toISOString(),source:"production",target:"refinement",loopType:"tactical",version:"1.0.0",expiresAt:j(z.SFDIPOT_WEIGHTS),factorWeights:e,featureContext:t,recommendations:n};return await this.store(b.TACTICAL,i),i}async querySFDIPOTSignals(e){await this.ensureInitialized();let t=await this.queryByNamespace(b.TACTICAL);return t=t.filter(n=>!w(n)),e&&(t=t.filter(n=>n.featureContext.toLowerCase().includes(e.toLowerCase()))),t}async storeTestHealthSignal(e,t,n){await this.ensureInitialized();let i={id:G("operational","test-health"),timestamp:new Date().toISOString(),source:"cicd",target:"development",loopType:"operational",version:"1.0.0",expiresAt:j(z.FLAKY_PATTERNS),flakyPatterns:e,gateFailures:t,recommendations:n};return await this.store(b.OPERATIONAL,i),i}async queryTestHealthSignals(){return await this.ensureInitialized(),(await this.queryByNamespace(b.OPERATIONAL)).filter(t=>!w(t))}async storeACQualitySignal(e,t,n){await this.ensureInitialized();let i={id:G("quality-criteria","ac-quality"),timestamp:new Date().toISOString(),source:"development",target:"refinement",loopType:"quality-criteria",version:"1.0.0",expiresAt:j(z.AC_QUALITY),untestablePatterns:e,coverageGaps:t,recommendations:n};return await this.store(b.QUALITY_CRITERIA,i),i}async queryACQualitySignals(){return await this.ensureInitialized(),(await this.queryByNamespace(b.QUALITY_CRITERIA)).filter(t=>!w(t))}async store(e,t){let n=new Date(t.expiresAt).getTime(),i=Math.max(0,Math.floor((n-Date.now())/1e3));await this.memory.kvSet(t.id,t,e,i>0?i:void 0),console.log(`[CrossPhaseMemory] Stored signal: ${t.id} in ${e}`)}async queryByNamespace(e){let t=await this.memory.kvSearch("*",e,1e3),n=[];for(let i of t){let r=await this.memory.kvGet(i,e);r&&n.push(r)}return n.sort((i,r)=>new Date(r.timestamp).getTime()-new Date(i.timestamp).getTime())}async delete(e,t){let n=await this.memory.kvDelete(t,e);return n&&console.log(`[CrossPhaseMemory] Deleted signal: ${t}`),n}async cleanupExpired(){let e={deleted:0,namespaces:{}};for(let t of Object.values(b)){let n=await this.queryByNamespace(t),i=0;for(let r of n)w(r)&&(await this.delete(t,r.id),i++,e.deleted++);i>0&&(e.namespaces[t]=i)}return e.deleted>0&&console.log(`[CrossPhaseMemory] Cleanup: deleted ${e.deleted} expired signals`),e}async getStats(){await this.ensureInitialized();let e={totalSignals:0,byLoop:{strategic:0,tactical:0,operational:0,"quality-criteria":0},byNamespace:{},oldestSignal:null,newestSignal:null},t=null,n=null;for(let i of Object.values(b)){let a=(await this.queryByNamespace(i)).filter(o=>!w(o));e.byNamespace[i]=a.length,e.totalSignals+=a.length;for(let o of a){e.byLoop[o.loopType]++;let l=new Date(o.timestamp);(!t||l<t)&&(t=l,e.oldestSignal=o.timestamp),(!n||l>n)&&(n=l,e.newestSignal=o.timestamp)}}return e}async ensureInitialized(){this.initialized||await this.initialize()}},Xe=null;function tn(s){return Xe||(Xe=new Je(s)),Xe}function et(s){let e=Object.getOwnPropertyNames(s);for(let t of e){let n=s[t];n&&typeof n=="object"&&!Object.isFrozen(n)&&et(n)}return Object.freeze(s)}function tt(s){let e=structuredClone(s);return et(e)}function nt(s){return s===0?"success":s===2?"model_blocking":"user_error"}Dn();var rt=class{config=null;memory;configPath;listeners=new Map;constructor(e){this.configPath=e||Ci(process.cwd(),".claude/hooks/cross-phase-memory.yaml"),this.memory=tn()}async initialize(){if(process.env.AQE_HOOKS_DISABLED==="true")return console.log("[CrossPhaseHooks] All hooks disabled via AQE_HOOKS_DISABLED"),!1;if(!vi(this.configPath))return console.warn(`[CrossPhaseHooks] Config not found: ${this.configPath}`),!1;try{let e=Ti(this.configPath,"utf-8"),t=bi(e);return t.enabled?(this.config=tt(t),await this.memory.initialize(),console.log(`[CrossPhaseHooks] Initialized with ${Object.keys(this.config.hooks).length} hooks`),!0):(console.log("[CrossPhaseHooks] Hooks disabled in config"),!1)}catch(e){return console.error("[CrossPhaseHooks] Failed to load config:",e),!1}}async onAgentComplete(e,t){if(!this.config||process.env.AQE_HOOKS_DISABLED==="true")return;let n=this.filterManagedHooks(Object.entries(this.config.hooks).filter(([i,r])=>r.trigger.event==="agent-complete"&&r.trigger.agent===e));for(let[i,r]of n)this.checkConditions(r.trigger.conditions,t)&&(console.log(`[CrossPhaseHooks] Executing hook: ${i}`),await this.executeActions(r.actions,t))}async onPhaseStart(e,t={}){if(!this.config)return{};if(process.env.AQE_HOOKS_DISABLED==="true")return{};let n=pt(),i=this.filterManagedHooks(Object.entries(this.config.hooks).filter(([r,a])=>a.trigger.event==="phase-start"&&a.trigger.phase===e));for(let[r,a]of i){console.log(`[CrossPhaseHooks] Executing phase-start hook: ${r}`);for(let o of a.actions)if(o.type==="query-signals"&&o.injectInto){let l=await this.querySignalsForInjection(o.namespace,o.maxAge,o.filterBy?t[o.filterBy]:void 0);for(let c of o.injectInto)n[c]||(n[c]=[]),n[c].push(...l)}}return n}async onPhaseEnd(e,t){if(!this.config||process.env.AQE_HOOKS_DISABLED==="true")return;let n=this.filterManagedHooks(Object.entries(this.config.hooks).filter(([i,r])=>r.trigger.event==="phase-end"&&r.trigger.phase===e));for(let[i,r]of n)console.log(`[CrossPhaseHooks] Executing phase-end hook: ${i}`),await this.executeActions(r.actions,t)}async executeActions(e,t){for(let n of e)try{await this.executeAction(n,t)}catch(i){let r=i?.exitCode;if(typeof r=="number"){let a=nt(r);if(a==="model_blocking")throw console.error(`[CrossPhaseHooks] Model-blocking hook failure (exit ${r}):`,i),i;console.warn(`[CrossPhaseHooks] Hook ${a} (exit ${r}):`,i)}else console.error("[CrossPhaseHooks] Action failed:",i)}}async executeAction(e,t){switch(e.type){case"store-signal":await this.executeStoreSignal(e,t);break;case"query-signals":break;case"notify-agent":await this.executeNotifyAgent(e,t);break;case"invoke-agent":await this.executeInvokeAgent(e,t);break;case"conditional":e.condition&&e.action&&this.evaluateCondition(e.condition,t)&&await this.executeAction(e.action,t);break;case"delete-expired":await this.memory.cleanupExpired();break;default:console.warn(`[CrossPhaseHooks] Unknown action type: ${e.type}`)}}async executeStoreSignal(e,t){if(!e.loop||!e.namespace||!e.extract)return;let n=this.extractFromContext(e.extract,t);switch(e.loop){case"strategic":await this.memory.storeRiskSignal(n.riskWeights||[],n.recommendations||{forRiskAssessor:[],forQualityCriteria:[]});break;case"tactical":await this.memory.storeSFDIPOTSignal(n.factorWeights||[],n.featureContext||"unknown",n.recommendations||{forProductFactorsAssessor:[]});break;case"operational":await this.memory.storeTestHealthSignal(n.flakyPatterns||[],n.gateFailures||[],n.recommendations||{forTestArchitect:[],antiPatterns:[]});break;case"quality-criteria":await this.memory.storeACQualitySignal(n.untestablePatterns||[],n.coverageGaps||[],n.recommendations||{forRequirementsValidator:[],acTemplates:{}});break}this.emit("signal-stored",{loop:e.loop,namespace:e.namespace})}async executeNotifyAgent(e,t){!e.target||!e.message||await this.isBlockedUrl(e.target)||(console.log(`[CrossPhaseHooks] Notify ${e.target}: ${e.message}`),this.emit("agent-notification",{target:e.target,message:e.message,priority:e.priority||"normal",context:t}))}async executeInvokeAgent(e,t){e.target&&(await this.isBlockedUrl(e.target)||(console.log(`[CrossPhaseHooks] Invoke agent: ${e.target}`),this.emit("agent-invocation",{agent:e.target,input:{...t,...e.input||{}}})))}async querySignalsForInjection(e,t,n){let r=await this.memory.queryByNamespace(e);if(t){let a=this.parseMaxAge(t),o=Date.now()-a;r=r.filter(l=>new Date(l.timestamp).getTime()>o)}return r}formatSignalsForInjection(e){if(e.length===0)return"";let t=`## CROSS-PHASE LEARNING SIGNALS
|
|
164
|
+
`);return null}function F(s){let e=s.trim();return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function Zn(s){let e=Ut(s);if(!e)return null;let t=e.split(`
|
|
165
|
+
`),n=-1;for(let c=0;c<t.length;c++)if(/^dependencies:\s*$/.test(t[c])){n=c+1;break}if(n===-1)return null;let i=[];for(let c=n;c<t.length;c++){let u=t[c];if(u.trim()!==""){if(u.length>0&&u[0]!==" "&&u[0]!==" ")break;i.push(u)}}if(i.length===0)return null;let r={},a={section:"none",item:{},inList:!1},o=()=>{a.item.name&&(r.agents||(r.agents=[]),r.agents.push({name:a.item.name,type:a.item.type||"hard",reason:a.item.reason||""}),a.item={})},l=()=>{a.item.name&&(r.mcpServers||(r.mcpServers=[]),r.mcpServers.push({name:a.item.name,required:a.item.required==="true"}),a.item={})};for(let c of i){let u=c.trim();if(u==="")continue;let d=u.match(/^(agents|mcp_servers|models):\s*$/);if(d){a.section==="agents"&&a.inList&&o(),a.section==="mcp_servers"&&a.inList&&l(),a.inList=!1,a.section=d[1];continue}if(a.section==="agents"||a.section==="mcp_servers"){let m=u.match(/^-\s+(\w+):\s*(.*)$/);if(m){a.inList&&(a.section==="agents"?o():l()),a.inList=!0,a.item={[m[1]]:F(m[2])};continue}if(a.inList){let p=u.match(/^(\w+):\s*(.*)$/);if(p){a.item[p[1]]=F(p[2]);continue}}}if(a.section==="models"){r.models||(r.models={});let m=u.match(/^(\w+):\s*(.*)$/);if(m){let T=F(m[2]);if(m[1]==="minimum")r.models={...r.models,minimum:T};else if(m[1]==="capabilities"){let K=T.match(/^\[(.+)]$/);K&&(r.models={...r.models,capabilities:K[1].split(",").map(Cn=>F(Cn.trim()))})}}let p=u.match(/^-\s+(.+)$/);if(p&&r.models){let T=r.models.capabilities||[];r.models={...r.models,capabilities:[...T,F(p[1])]}}}}return a.section==="agents"&&a.inList&&o(),a.section==="mcp_servers"&&a.inList&&l(),!r.agents&&!r.mcpServers&&!r.models?null:r}function Xn(s){let e=Ut(s);if(!e)return null;for(let t of e.split(`
|
|
166
|
+
`)){let n=t.match(/^name:\s*(.+)$/);if(n)return F(n[1])}return null}function qt(s){let e=new Map,t=[];if(!jn(s))return t.push(`Agents directory not found: ${s}`),{nodes:e,spawnOrder:[],cycles:[],warnings:t};let n=Vn(s).filter(a=>a.startsWith("qe-")&&a.endsWith(".md"));for(let a of n){let o;try{o=Wn(Kn(s,a),"utf-8")}catch{t.push(`Failed to read agent file: ${a}`);continue}let l=Xn(o)||Yn(a,".md"),c=Zn(o),u=[],d=[],m=[];if(c?.agents)for(let p of c.agents)p.type==="hard"?u.push(p.name):p.type==="soft"?d.push(p.name):p.type==="peer"&&m.push(p.name);e.set(l,{agentName:l,hardDeps:u,softDeps:d,peerDeps:m,dependencies:c||{}})}let i=new Set(e.keys());for(let[a,o]of e)for(let l of o.hardDeps)i.has(l)||t.push(`Agent "${a}" declares hard dependency on "${l}" which is not in the agent directory`);let r=Jn(e);for(let a of r)t.push(`Dependency cycle detected: ${a.join(" -> ")}`);return{nodes:e,spawnOrder:ei(e,r),cycles:r,warnings:t}}function Jn(s){let e=[],t=new Set,n=new Set,i=[];function r(a){t.add(a),n.add(a),i.push(a);let o=s.get(a);if(o){for(let l of o.hardDeps)if(!t.has(l)&&s.has(l))r(l);else if(n.has(l)){let c=i.indexOf(l);c!==-1&&e.push([...i.slice(c),l])}}i.pop(),n.delete(a)}for(let a of s.keys())t.has(a)||r(a);return e}function ei(s,e){let t=new Set(e.flat()),n=[],i=new Set,r=new Set;function a(o){if(i.has(o)||t.has(o)||r.has(o))return;r.add(o);let l=s.get(o);if(l)for(let c of l.hardDeps)s.has(c)&&a(c);r.delete(o),i.add(o),n.push(o)}for(let o of s.keys())a(o);for(let o of t)n.includes(o)||n.push(o);return n}function zt(s,e){let t=new Set(s),n=[],i=[];for(let l of s){let c=e.nodes.get(l);if(!c)continue;let u=c.hardDeps.filter(d=>!t.has(d));u.length>0&&(i.push({agent:l,missing:u}),n.push(`Advisory: "${l}" has unsatisfied hard dependencies: ${u.join(", ")}. Proceeding anyway.`))}let r=[],a=new Set,o=new Set(s);for(;o.size>0;){let l=[];for(let c of o){let u=e.nodes.get(c);if(!u){l.push(c);continue}u.hardDeps.filter(m=>t.has(m)).every(m=>a.has(m))&&l.push(c)}if(l.length===0){n.push(`Could not resolve dependency ordering for: ${[...o].join(", ")}. Placing in final phase.`),r.push([...o]);break}r.push(l);for(let c of l)a.add(c),o.delete(c);o=new Set([...o])}return{phases:r,unsatisfiedHardDeps:i,warnings:n}}var Le={defaultTtlMs:0,cleanupIntervalMs:6e4,maxMailboxSize:1e3};var Q=class{mailboxes=new Map;messageHandlers=new Map;broadcastHandlers=new Map;domainAgents=new Map;cognitiveRouter=null;cognitiveRouterInitialized=!1;compressedMessages=new Map;createMailbox(e,t){let n=this.mailboxes.get(e);if(n)return this.toSnapshot(n);let i={agentId:e,domain:t,messages:[],unreadCount:0,lastRead:Date.now()};this.mailboxes.set(e,i);let r=this.domainAgents.get(t);return r||(r=new Set,this.domainAgents.set(t,r)),r.add(e),this.toSnapshot(i)}getMailbox(e){let t=this.mailboxes.get(e);if(t)return this.toSnapshot(t)}deleteMailbox(e){let t=this.mailboxes.get(e);if(!t)return!1;let n=this.domainAgents.get(t.domain);n&&(n.delete(e),n.size===0&&this.domainAgents.delete(t.domain));for(let i of t.messages)this.compressedMessages.delete(i.id);return this.messageHandlers.delete(e),this.mailboxes.delete(e),!0}send(e){if(e.to==="broadcast"){this.broadcast(e.domain,e);return}let t=this.mailboxes.get(e.to);if(!t)throw new Error(`No mailbox found for agent '${e.to}'. Create a mailbox first with createMailbox().`);let n=this.compressViaCognitive(e);t.messages.push(n),t.unreadCount++;let i=this.messageHandlers.get(e.to);if(i)for(let r of i)try{r(e)}catch{}}broadcast(e,t){let n=this.domainAgents.get(e);if(!n)return;for(let r of n){if(r===t.from)continue;let a=this.mailboxes.get(r);if(a){a.messages.push(t),a.unreadCount++;let o=this.messageHandlers.get(r);if(o)for(let l of o)try{l(t)}catch{}}}let i=this.broadcastHandlers.get(e);if(i)for(let r of i)try{r(e,t)}catch{}}receive(e,t){let n=this.mailboxes.get(e);if(!n||n.unreadCount===0)return[];let i=Date.now(),r=n.messages.length-n.unreadCount,a=n.messages.slice(r);return a=a.filter(o=>!this.isExpired(o,i)),t?.type&&(a=a.filter(o=>o.type===t.type)),t?.since!==void 0&&(a=a.filter(o=>o.timestamp>=t.since)),t?.limit!==void 0&&t.limit>0&&(a=a.slice(0,t.limit)),n.unreadCount=0,n.lastRead=i,this.decompressMessages(a)}peek(e){let t=this.mailboxes.get(e);if(!t)return 0;let n=Date.now(),i=t.messages.length-t.unreadCount,r=0;for(let a=i;a<t.messages.length;a++)this.isExpired(t.messages[a],n)||r++;return r}cleanup(e){let t=Date.now(),n=t-e,i=0;for(let r of this.mailboxes.values()){let a=r.messages.length,o=r.messages.length-r.unreadCount;r.messages=r.messages.filter((c,u)=>c.timestamp<n?(this.compressedMessages.delete(c.id),!1):this.isExpired(c,t)?(this.compressedMessages.delete(c.id),!1):!0);let l=a-r.messages.length;i+=l,l>0&&(r.unreadCount=r.messages.filter(c=>c.timestamp>r.lastRead).length)}return i}onMessage(e,t){let n=this.messageHandlers.get(e);return n||(n=[],this.messageHandlers.set(e,n)),n.push(t),()=>{let i=this.messageHandlers.get(e);if(i){let r=i.indexOf(t);r>=0&&i.splice(r,1)}}}onBroadcast(e,t){let n=this.broadcastHandlers.get(e);return n||(n=[],this.broadcastHandlers.set(e,n)),n.push(t),()=>{let i=this.broadcastHandlers.get(e);if(i){let r=i.indexOf(t);r>=0&&i.splice(r,1)}}}getAgentsInDomain(e){let t=this.domainAgents.get(e);return t?Array.from(t):[]}getDomains(){return Array.from(this.domainAgents.keys())}get size(){return this.mailboxes.size}clear(){this.mailboxes.clear(),this.messageHandlers.clear(),this.broadcastHandlers.clear(),this.domainAgents.clear(),this.compressedMessages.clear(),this.cognitiveRouter=null,this.cognitiveRouterInitialized=!1}isExpired(e,t){return!e.ttl||e.ttl<=0?!1:t>e.timestamp+e.ttl}toSnapshot(e){return{agentId:e.agentId,domain:e.domain,messages:[...e.messages],unreadCount:e.unreadCount,lastRead:e.lastRead}}ensureCognitiveRouter(){if(this.cognitiveRouterInitialized)return this.cognitiveRouter;if(this.cognitiveRouterInitialized=!0,!bt())return null;try{this.cognitiveRouter=Ct()??null}catch{this.cognitiveRouter=null}return this.cognitiveRouter}compressViaCognitive(e){try{let t=this.ensureCognitiveRouter();if(!t)return e;let n=`${e.from}->${e.to}`,i=t.send(n,e.from,e.to,e.payload);return i.compressed&&i.compressedSize<i.originalSize?(this.compressedMessages.set(e.id,i),{...e,payload:i.payload}):e}catch{return e}}decompressMessages(e){let t=this.cognitiveRouter;return!t||this.compressedMessages.size===0?e:e.map(n=>{try{let i=this.compressedMessages.get(n.id);if(!i)return n;let r=t.receive(i);return this.compressedMessages.delete(n.id),{...n,payload:r}}catch{return n}})}getCognitiveRoutingStats(){return this.cognitiveRouter?this.cognitiveRouter.getStats():null}};import{randomUUID as Gt}from"node:crypto";pt();import{randomUUID as te}from"node:crypto";var ne=class{spans=new Map;traceIndex=new Map;maxSpans;constructor(e=1e4){this.maxSpans=e}startTrace(e){let t=te(),n=te(),i={traceId:t,spanId:n},r=this.createSpan(i,e);return{context:i,span:r}}startSpan(e){let t=e.parentContext,n=t?.traceId??te(),i=te(),r={traceId:n,spanId:i,parentSpanId:t?.spanId,baggage:t?.baggage},a=this.createSpan(r,e);return{context:r,span:a}}completeSpan(e){let t=this.spans.get(e);t&&(t.endTime=Date.now(),t.status="completed")}failSpan(e,t){let n=this.spans.get(e);n&&(n.endTime=Date.now(),n.status="error",n.errorMessage=t)}getTrace(e){let t=this.traceIndex.get(e);return t?Array.from(t).map(n=>this.spans.get(n)).filter(n=>n!==void 0).sort((n,i)=>n.startTime-i.startTime):[]}getSpan(e){return this.spans.get(e)}getActiveSpans(){return Array.from(this.spans.values()).filter(e=>e.status==="active")}getStats(){let e=new Set,t=new Set;for(let[n,i]of this.traceIndex)Array.from(i).map(a=>this.spans.get(a)).filter(a=>a!==void 0).some(a=>a.status==="active")?e.add(n):t.add(n);return{totalSpans:this.spans.size,activeTraces:e.size,completedTraces:t.size}}purge(e){let t=Date.now()-e,n=0;for(let[i,r]of this.traceIndex){let a=Array.from(r).map(c=>this.spans.get(c)).filter(c=>c!==void 0),o=a.every(c=>c.status!=="active"),l=a.every(c=>(c.endTime??c.startTime)<t);if(o&&l){for(let c of r)this.spans.delete(c),n++;this.traceIndex.delete(i)}}return n}dispose(){this.spans.clear(),this.traceIndex.clear()}createSpan(e,t){this.spans.size>=this.maxSpans&&this.purge(6e4);let n={traceId:e.traceId,spanId:e.spanId,parentSpanId:e.parentSpanId,operationName:t.operationName,agentId:t.agentId,domain:t.domain,startTime:Date.now(),tags:t.tags??{},status:"active"};this.spans.set(e.spanId,n);let i=this.traceIndex.get(e.traceId);return i||(i=new Set,this.traceIndex.set(e.traceId,i)),i.add(e.spanId),n}},ti="trace:";function ie(s){return`${ti}${JSON.stringify({traceId:s.traceId,spanId:s.spanId,parentSpanId:s.parentSpanId})}`}function Qe(s){return new ne(s)}var re=class{mailbox;config;teams=new Map;registeredAgents=new Set;agentDomains=new Map;subscriptions=new Map;cleanupTimer=null;initialized=!1;constructor(e,t){this.mailbox=e??new Q,this.config={...Le,...t}}initialize(e){this.initialized||(e&&Object.assign(this.config,e),this.config.cleanupIntervalMs>0&&(this.cleanupTimer=setInterval(()=>{this.performCleanup()},this.config.cleanupIntervalMs)),this.initialized=!0)}shutdown(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null),this.mailbox.clear(),this.teams.clear(),this.registeredAgents.clear(),this.agentDomains.clear(),this.subscriptions.clear(),this.initialized=!1}createTeam(e){if(this.teams.has(e.domain))throw new Error(`Team already exists for domain '${e.domain}'. Use getTeamStatus() to inspect the existing team.`);let t={domain:e.domain,leadAgentId:e.leadAgentId,maxTeammates:e.maxTeammates,teammateIds:[...e.teammateIds],autoAssignEnabled:e.autoAssignEnabled};this.teams.set(e.domain,t),this.registerAgent(e.leadAgentId,e.domain);for(let n of e.teammateIds)this.registerAgent(n,e.domain)}getTeamStatus(e){let t=this.teams.get(e);if(!t)return;let n=[t.leadAgentId,...t.teammateIds],i=n.filter(a=>this.mailbox.peek(a)===0),r=0;for(let a of n)r+=this.mailbox.peek(a);return{domain:t.domain,leadAgentId:t.leadAgentId,teammateIds:[...t.teammateIds],activeAgentCount:n.filter(a=>this.registeredAgents.has(a)).length,idleAgentIds:i,totalUnreadMessages:r}}registerAgent(e,t){if(this.registeredAgents.has(e))return;this.registeredAgents.add(e),this.agentDomains.set(e,t),this.mailbox.createMailbox(e,t);let n=this.teams.get(t);n&&n.autoAssignEnabled&&e!==n.leadAgentId&&!n.teammateIds.includes(e)&&n.teammateIds.length<n.maxTeammates&&n.teammateIds.push(e)}unregisterAgent(e){if(!this.registeredAgents.has(e))return!1;let t=this.agentDomains.get(e);if(t){let n=this.teams.get(t);if(n){let i=n.teammateIds.indexOf(e);i>=0&&n.teammateIds.splice(i,1)}}return this.mailbox.deleteMailbox(e),this.subscriptions.delete(e),this.registeredAgents.delete(e),this.agentDomains.delete(e),!0}sendMessage(e,t,n,i,r){this.validateAgent(e,"sender"),this.validateAgent(t,"recipient");let a=this.agentDomains.get(e),o=r?.traceContext?ie(r.traceContext):r?.correlationId,l={id:Gt(),from:e,to:t,domain:r?.domain??a,type:n,payload:i,timestamp:Date.now(),correlationId:o,replyTo:r?.replyTo,ttl:r?.ttl??(this.config.defaultTtlMs>0?this.config.defaultTtlMs:void 0)};return this.mailbox.send(l),this.notifySubscribers(t,l),l}broadcast(e,t,n,i){let r=i?.from??"__system__";r!=="__system__"&&this.validateAgent(r,"broadcast sender");let a=i?.traceContext?ie(i.traceContext):i?.correlationId,o={id:Gt(),from:r,to:"broadcast",domain:e,type:t,payload:n,timestamp:Date.now(),correlationId:a,ttl:i?.ttl??(this.config.defaultTtlMs>0?this.config.defaultTtlMs:void 0)};this.mailbox.broadcast(e,o);let l=this.mailbox.getAgentsInDomain(e);for(let c of l)c!==r&&this.notifySubscribers(c,o);return o}onMessage(e,t){this.validateAgent(e,"subscription target");let n=this.subscriptions.get(e);return n||(n=[],this.subscriptions.set(e,n)),n.push(t),()=>{let i=this.subscriptions.get(e);if(i){let r=i.indexOf(t);r>=0&&i.splice(r,1)}}}getIdleAgents(e){let t=[],n=e?this.mailbox.getAgentsInDomain(e):Array.from(this.registeredAgents);for(let i of n)this.mailbox.peek(i)===0&&t.push(i);return t}isRegistered(e){return this.registeredAgents.has(e)}getAgentDomain(e){return this.agentDomains.get(e)}getRegisteredAgents(){return Array.from(this.registeredAgents)}getUnreadCount(e){return this.mailbox.peek(e)}receiveMessages(e){return this.mailbox.receive(e)}getMailboxService(){return this.mailbox}validateAgent(e,t){if(!this.registeredAgents.has(e))throw new Error(`Unknown ${t} '${e}'. Register the agent first with registerAgent() or createTeam().`)}notifySubscribers(e,t){let n=this.subscriptions.get(e);if(!(!n||n.length===0))for(let i of n)try{i(t)}catch{}}performCleanup(){let e=this.config.defaultTtlMs>0?this.config.defaultTtlMs*10:this.config.cleanupIntervalMs*60;this.mailbox.cleanup(e)}};function Be(s){return new re(void 0,s)}var Wt={maxActiveTeams:13,defaultTeamSize:3,autoScaleEnabled:!1,scaleUpThreshold:10,scaleDownIdleMs:6e4},se=class s{static SYSTEM_AGENT_ID="__dtm_system__";static SYSTEM_DOMAIN="__system__";adapter;config;teams=new Map;systemAgentRegistered=!1;constructor(e,t){this.adapter=e,this.config={...Wt,...t}}createDomainTeam(e,t,n){if(this.teams.has(e))throw new Error(`Domain team already exists for '${e}'. Use getDomainTeam() to inspect the existing team.`);if(this.teams.size>=this.config.maxActiveTeams)throw new Error(`Maximum active teams (${this.config.maxActiveTeams}) reached. Remove an existing team before creating a new one.`);let i=n?[...n]:[],r=this.getMaxTeamSize(e);i.length+1>r&&(i.length=r-1);let a=Date.now(),o={domain:e,leadAgentId:t,teammateIds:i,createdAt:a,taskCount:0,completedCount:0,lastActivity:new Map};o.lastActivity.set(t,a);for(let c of i)o.lastActivity.set(c,a);this.teams.set(e,o);let l={domain:e,leadAgentId:t,maxTeammates:r-1,teammateIds:i,autoAssignEnabled:!1};return this.adapter.createTeam(l),this.toSnapshot(o)}removeDomainTeam(e){let t=this.teams.get(e);if(!t)return!1;for(let n of[t.leadAgentId,...t.teammateIds])this.adapter.unregisterAgent(n);return this.teams.delete(e),!0}getDomainTeam(e){let t=this.teams.get(e);return t?this.toSnapshot(t):void 0}addTeammate(e,t){let n=this.teams.get(e);if(!n||t===n.leadAgentId||n.teammateIds.includes(t))return!1;let i=this.getMaxTeamSize(e);return 1+n.teammateIds.length>=i?!1:(n.teammateIds.push(t),n.lastActivity.set(t,Date.now()),this.adapter.registerAgent(t,e),!0)}listDomainTeams(){return Array.from(this.teams.values(),e=>this.toSnapshot(e))}assignTaskToTeam(e,t,n){let i=this.teams.get(e);return i?(this.ensureSystemAgent(),this.adapter.sendMessage(s.SYSTEM_AGENT_ID,i.leadAgentId,"task-assignment",{taskId:t,payload:n},{domain:e}),i.taskCount++,i.lastActivity.set(i.leadAgentId,Date.now()),!0):!1}broadcastToDomain(e,t,n){let i=this.teams.get(e);if(!i)throw new Error(`No domain team found for '${e}'. Create a team first with createDomainTeam().`);this.adapter.broadcast(e,t,n,{from:"__system__"});let r=Date.now();i.lastActivity.set(i.leadAgentId,r);for(let a of i.teammateIds)i.lastActivity.set(a,r)}getTeamHealth(e){let t=this.teams.get(e);if(!t)return;let n=[t.leadAgentId,...t.teammateIds],i=n.length,r=0,a=0,o=0;for(let c of n)if(this.adapter.isRegistered(c)){r++;let u=this.adapter.getUnreadCount(c);o+=u,u===0&&a++}let l=t.taskCount-t.completedCount;return{domain:e,teamSize:i,activeAgents:r,idleAgents:a,pendingMessages:o,tasksPending:l,tasksCompleted:t.completedCount,healthy:r>0&&r===i&&l<this.config.scaleUpThreshold*2}}scaleTeam(e,t){let n=this.teams.get(e);if(!n)throw new Error(`No domain team found for '${e}'. Create a team first with createDomainTeam().`);let i=Math.max(this.getMaxTeamSize(e),t,this.config.maxActiveTeams),r=Math.max(1,Math.min(t,i)),a=1+n.teammateIds.length,o=[],l=[];if(r>a){let c=r-a;for(let u=0;u<c;u++){let d=`${e}-teammate-${Date.now()}-${u}`;n.teammateIds.push(d),n.lastActivity.set(d,Date.now()),this.adapter.registerAgent(d,e),o.push(d)}}else if(r<a){let c=a-r;for(let u=0;u<c;u++){let d=n.teammateIds.pop();d&&(n.lastActivity.delete(d),this.adapter.unregisterAgent(d),l.push(d))}}return{domain:e,previousSize:a,newSize:1+n.teammateIds.length,addedAgents:o,removedAgents:l}}getIdleTeammates(e){if(e){let n=this.teams.get(e);return n?this.getIdleAgentsForTeam(n):[]}let t=[];for(let n of this.teams.values())t.push(...this.getIdleAgentsForTeam(n));return t}rebalance(){let e=[],t=new Set,n=Array.from(this.teams.values(),a=>{let o=this.getTargetTeamSize(a.domain),l=1+a.teammateIds.length,c=this.getIdleAgentsForTeam(a).filter(u=>u!==a.leadAgentId);return{domain:a.domain,team:a,currentSize:l,targetSize:o,idleTeammates:c}}),i=n.filter(a=>a.currentSize>a.targetSize&&a.idleTeammates.length>0).sort((a,o)=>o.currentSize-o.targetSize-(a.currentSize-a.targetSize)),r=n.filter(a=>a.currentSize<a.targetSize).sort((a,o)=>a.currentSize-a.targetSize-(o.currentSize-o.targetSize));for(let a of i)for(let o of r){if(o.currentSize>=o.targetSize)continue;if(a.idleTeammates.length===0)break;if(o.currentSize>=this.getMaxTeamSize(o.domain))continue;let l=a.idleTeammates.shift(),c=a.team.teammateIds.indexOf(l);c>=0&&a.team.teammateIds.splice(c,1),a.team.lastActivity.delete(l),a.currentSize--,this.adapter.unregisterAgent(l),this.adapter.registerAgent(l,o.domain),o.team.teammateIds.push(l),o.team.lastActivity.set(l,Date.now()),o.currentSize++,e.push({agentId:l,fromDomain:a.domain,toDomain:o.domain}),t.add(a.domain),t.add(o.domain)}return{moves:e,teamsAffected:t.size}}dispose(){for(let e of this.teams.values())for(let t of[e.leadAgentId,...e.teammateIds])this.adapter.unregisterAgent(t);this.teams.clear(),this.systemAgentRegistered&&(this.adapter.unregisterAgent(s.SYSTEM_AGENT_ID),this.systemAgentRegistered=!1)}markTaskCompleted(e){let t=this.teams.get(e);return t?(t.completedCount<t.taskCount&&t.completedCount++,!0):!1}ensureSystemAgent(){this.systemAgentRegistered||(this.adapter.registerAgent(s.SYSTEM_AGENT_ID,s.SYSTEM_DOMAIN),this.systemAgentRegistered=!0)}getMaxTeamSize(e){return this.config.domainTeamSizes&&e in this.config.domainTeamSizes?this.config.domainTeamSizes[e]:this.config.defaultTeamSize}getTargetTeamSize(e){return this.getMaxTeamSize(e)}getIdleAgentsForTeam(e){let t=[];for(let n of[e.leadAgentId,...e.teammateIds])this.adapter.isRegistered(n)&&this.adapter.getUnreadCount(n)===0&&t.push(n);return t}toSnapshot(e){return{domain:e.domain,leadAgentId:e.leadAgentId,teammateIds:[...e.teammateIds],createdAt:e.createdAt,taskCount:e.taskCount,completedCount:e.completedCount}}};function $e(s,e){return new se(s,e)}k();var oe={failureThreshold:3,resetTimeoutMs:6e4,halfOpenSuccessThreshold:2,failureWindowMs:12e4,cascadeEnabled:!1,cascadeTargets:void 0},ae=class extends Error{domain;retryAfterMs;constructor(e,t){let n=t!=null?` (retry after ${t}ms)`:"";super(`Circuit breaker is open for domain '${e}'${n}`),this.name="DomainCircuitOpenError",this.domain=e,this.retryAfterMs=t}},A=class{state="closed";failures=[];totalRequests=0;totalSuccesses=0;totalFailures=0;rejectedCount=0;lastFailureTime;lastSuccessTime;openedAt;halfOpenSuccesses=0;config;stateChangeHandlers=new Set;domain;constructor(e,t){this.domain=e,this.config={...oe,...t}}canExecute(){let e=this.getState();return e==="closed"?!0:e!=="open"}async execute(e){if(this.totalRequests++,this.getState()==="open")throw this.rejectedCount++,this.emitEvent({type:"request-rejected",domain:this.domain,timestamp:Date.now(),metadata:{retryAfterMs:this.getTimeUntilTransition()}}),new ae(this.domain,this.getTimeUntilTransition());try{let n=await e();return this.recordSuccess(),n}catch(n){throw this.recordFailure(Z(n)),n}}recordSuccess(){this.totalSuccesses++,this.lastSuccessTime=Date.now(),this.getState()==="half-open"&&(this.halfOpenSuccesses++,console.log(`[DomainCircuitBreaker:${this.domain}] Half-open success ${this.halfOpenSuccesses}/${this.config.halfOpenSuccessThreshold}`),this.halfOpenSuccesses>=this.config.halfOpenSuccessThreshold&&this.transitionTo("closed"))}recordFailure(e){this.totalFailures++,this.lastFailureTime=Date.now(),this.failures.push({timestamp:Date.now(),message:e.message}),this.cleanOldFailures();let t=this.getState();if(t==="half-open"){console.log(`[DomainCircuitBreaker:${this.domain}] Failure in half-open state, re-opening`),this.transitionTo("open");return}t==="closed"&&this.failures.length>=this.config.failureThreshold&&(console.log(`[DomainCircuitBreaker:${this.domain}] Failure threshold reached (${this.failures.length}/${this.config.failureThreshold}), opening circuit`),this.transitionTo("open"))}getState(){return this.state==="open"&&this.openedAt!=null&&Date.now()-this.openedAt>=this.config.resetTimeoutMs&&this.transitionTo("half-open"),this.state}getStats(){let e=this.getState();return{domain:this.domain,state:e,totalRequests:this.totalRequests,successCount:this.totalSuccesses,failureCount:this.totalFailures,rejectedCount:this.rejectedCount,lastFailureTime:this.lastFailureTime,lastSuccessTime:this.lastSuccessTime,openedAt:this.openedAt,timeUntilHalfOpen:e==="open"?this.getTimeUntilTransition():void 0,consecutiveSuccesses:this.halfOpenSuccesses}}reset(){let e=this.state;this.state="closed",this.failures=[],this.halfOpenSuccesses=0,this.openedAt=void 0,e!=="closed"&&(console.log(`[DomainCircuitBreaker:${this.domain}] Manually reset from '${e}' to 'closed'`),this.emitEvent({type:"state-change",domain:this.domain,previousState:e,newState:"closed",timestamp:Date.now(),metadata:{trigger:"manual-reset"}}))}forceOpen(){console.log(`[DomainCircuitBreaker:${this.domain}] Force-opening circuit`),this.transitionTo("open")}getRecentFailures(e=5){return this.failures.slice(-e).map(t=>`[${new Date(t.timestamp).toISOString()}] ${t.message}`)}onStateChange(e){return this.stateChangeHandlers.add(e),()=>{this.stateChangeHandlers.delete(e)}}getConfig(){return this.config}transitionTo(e){let t=this.state;if(t!==e){switch(this.state=e,e){case"open":this.openedAt=Date.now(),this.halfOpenSuccesses=0;break;case"half-open":this.halfOpenSuccesses=0,console.log(`[DomainCircuitBreaker:${this.domain}] Transitioning to half-open, allowing probe requests`);break;case"closed":this.failures=[],this.openedAt=void 0,this.halfOpenSuccesses=0,console.log(`[DomainCircuitBreaker:${this.domain}] Circuit closed, domain is healthy`);break}this.emitEvent({type:"state-change",domain:this.domain,previousState:t,newState:e,timestamp:Date.now()})}}cleanOldFailures(){let e=Date.now()-this.config.failureWindowMs;this.failures=this.failures.filter(t=>t.timestamp>e)}getTimeUntilTransition(){if(this.state==="open"&&this.openedAt!=null){let e=Date.now()-this.openedAt,t=this.config.resetTimeoutMs-e;return Math.max(0,t)}}emitEvent(e){for(let t of this.stateChangeHandlers)try{t(e)}catch(n){console.log(`[DomainCircuitBreaker:${this.domain}] State change handler error: ${h(n)}`)}}};k();var Ue={critical:{failureThreshold:2,resetTimeoutMs:3e4,halfOpenSuccessThreshold:2,failureWindowMs:6e4,cascadeEnabled:!1,cascadeTargets:void 0},standard:{failureThreshold:3,resetTimeoutMs:6e4,halfOpenSuccessThreshold:2,failureWindowMs:12e4,cascadeEnabled:!1,cascadeTargets:void 0},lenient:{failureThreshold:5,resetTimeoutMs:12e4,halfOpenSuccessThreshold:3,failureWindowMs:3e5,cascadeEnabled:!1,cascadeTargets:void 0}},jt={"test-generation":"critical","test-execution":"critical","coverage-analysis":"critical","quality-assessment":"critical","security-compliance":"critical","defect-intelligence":"standard","requirements-validation":"standard","code-intelligence":"standard","contract-testing":"standard","visual-accessibility":"lenient","chaos-resilience":"lenient","learning-optimization":"lenient","enterprise-integration":"standard"},B=class{breakers=new Map;defaultConfig;globalHandlers=new Set;constructor(e){this.defaultConfig={...oe,...e}}getBreaker(e){let t=this.breakers.get(e);if(!t){let n=jt[e],i=n?{...this.defaultConfig,...Ue[n]}:this.defaultConfig;t=new A(e,i),this.breakers.set(e,t),t.onStateChange(r=>this.handleBreakerEvent(r)),console.log(`[DomainBreakerRegistry] Created breaker for '${e}' (criticality: ${n??"default"})`)}return t}configureBreaker(e,t){let n={...this.defaultConfig,...t},i=new A(e,n);i.onStateChange(r=>this.handleBreakerEvent(r)),this.breakers.set(e,i),console.log(`[DomainBreakerRegistry] Reconfigured breaker for '${e}'`)}configureCriticality(e,t){let n=Ue[t];this.configureBreaker(e,n),console.log(`[DomainBreakerRegistry] Set '${e}' criticality to '${t}'`)}canExecuteInDomain(e){return this.getBreaker(e).canExecute()}async executeInDomain(e,t){return this.getBreaker(e).execute(t)}getAllStats(){let e=new Map;for(let[t,n]of this.breakers)e.set(t,n.getStats());return e}getOpenDomains(){let e=[];for(let[t,n]of this.breakers)n.getState()==="open"&&e.push(t);return e}getHealthyDomains(){let e=[];for(let[t,n]of this.breakers)n.getState()==="closed"&&e.push(t);return e}getDegradedDomains(){let e=[];for(let[t,n]of this.breakers)n.getState()==="half-open"&&e.push(t);return e}getHealthSummary(){let e=0,t=0,n=0;for(let i of this.breakers.values())switch(i.getState()){case"closed":e++;break;case"half-open":t++;break;case"open":n++;break}return{healthy:e,degraded:t,open:n,total:this.breakers.size}}resetAll(){for(let e of this.breakers.values())e.reset();console.log(`[DomainBreakerRegistry] Reset all ${this.breakers.size} breakers`)}reset(e){let t=this.breakers.get(e);t&&t.reset()}onAnyStateChange(e){return this.globalHandlers.add(e),()=>{this.globalHandlers.delete(e)}}handleBreakerEvent(e){for(let t of this.globalHandlers)try{t(e)}catch(n){console.log(`[DomainBreakerRegistry] Global handler error: ${h(n)}`)}e.type==="state-change"&&e.newState==="open"&&this.propagateCascade(e.domain)}propagateCascade(e){let t=this.breakers.get(e);if(!t)return;let n=t.getConfig();if(!(!n.cascadeEnabled||!n.cascadeTargets?.length))for(let i of n.cascadeTargets){if(i===e)continue;let r=this.getBreaker(i);if(r.getState()!=="open"){console.log(`[DomainBreakerRegistry] Cascading open from '${e}' to '${i}'`),r.forceOpen();let o={type:"cascade-triggered",domain:i,timestamp:Date.now(),metadata:{sourceDomain:e,cascadedFrom:e}};for(let l of this.globalHandlers)try{l(o)}catch(c){console.log(`[DomainBreakerRegistry] Cascade event handler error: ${h(c)}`)}}}}};function Vt(s){return new B(s)}var x=["smoke","standard","deep","crisis"];var $=["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","requirements-validation","code-intelligence","security-compliance","contract-testing","visual-accessibility","chaos-resilience","learning-optimization","enterprise-integration"],ce=["test-generation","coverage-analysis","quality-assessment"],qe={"test-generation":["generator","specialist"],"test-execution":["tester","coordinator"],"coverage-analysis":["analyzer","specialist"],"quality-assessment":["analyzer","validator"],"defect-intelligence":["analyzer","specialist"],"requirements-validation":["validator","reviewer"],"code-intelligence":["analyzer","specialist"],"security-compliance":["analyzer","validator"],"contract-testing":["tester","validator"],"visual-accessibility":["tester","validator"],"chaos-resilience":["tester","specialist"],"learning-optimization":["optimizer","specialist"],"enterprise-integration":["coordinator","validator"]},ni={tier:"smoke",maxAgents:3,agentTeamsEnabled:!1,domains:["test-execution","quality-assessment"],estimatedCost:"minimal",description:"Lightweight smoke test on every commit. Runs core test execution and quality assessment with minimal agent count to catch obvious regressions quickly.",triggers:[{type:"commit"},{type:"schedule",conditions:{interval:"hourly"}}]},ii={tier:"standard",maxAgents:7,agentTeamsEnabled:!1,domains:["test-generation","test-execution","coverage-analysis","quality-assessment","security-compliance"],estimatedCost:"moderate",description:"Standard validation for pull requests. Covers test generation, execution, coverage, quality, and security across up to 7 agents. Agent teams are optional.",triggers:[{type:"pr"},{type:"manual"}]},ri={tier:"deep",maxAgents:15,agentTeamsEnabled:!0,domains:[...$],estimatedCost:"high",description:"Deep validation for pre-release and critical path changes. Activates all 13 domains with up to 15 agents and full agent team collaboration.",triggers:[{type:"release"},{type:"pr",conditions:{criticalPath:!0}},{type:"manual",conditions:{requestedTier:"deep"}}]},si={tier:"crisis",maxAgents:15,agentTeamsEnabled:!0,domains:[...$],estimatedCost:"unlimited",description:"Crisis response for production incidents. All domains active with competing hypotheses enabled. Unlimited cost budget to resolve incidents as fast as possible.",triggers:[{type:"incident"},{type:"manual",conditions:{requestedTier:"crisis"}}]},ze={smoke:ni,standard:ii,deep:ri,crisis:si};var ai=["password","secret","token","crypto","auth","credential","jwt","oauth"],oi=["async","await","Promise","setTimeout","setInterval","Worker","mutex","lock"],ci={securityKeywords:ai,concurrencyKeywords:oi,enableDimensionOverrides:!1};function li(s,e){let t=s+e;return t<=8?"trivial":t<=20?"simple":t<=40?"moderate":t<=70?"complex":"critical"}var U=class{config;constructor(e){this.config={...ci,...e}}analyzeExtendedDimensions(e){let t=e.split(`
|
|
167
|
+
`),n=Math.max(t.length,1),i=this.countKeywordLines(t,this.config.securityKeywords),r=le(i/n,0,1),a=this.countKeywordLines(t,this.config.concurrencyKeywords),o=le(a/n,0,1),l=this.countPatternMatches(e,/\.(map|filter|reduce|flatMap|forEach)\s*\(/g),c=le(l/n,0,1),u=this.countPatternMatches(e,/^export\s/gm),d=Math.max(this.countPatternMatches(e,/^(export\s+)?(const|let|var|function|class|interface|type|enum)\s/gm),1),m=le(u/d,0,1);return{securitySurface:r,concurrency:o,dataFlow:c,apiSurface:m}}compose(e,t,n){let i=li(e.cyclomatic,e.cognitive),r=this.analyzeExtendedDimensions(n),a=[],o=[],l;switch(i){case"trivial":case"simple":a.push({agentType:"qe-test-generator",priority:1,reason:`${i} complexity \u2014 basic test generation sufficient`}),o.push("unit"),l="haiku";break;case"moderate":a.push({agentType:"qe-test-generator",priority:1,reason:"Moderate complexity requires thorough test generation"},{agentType:"qe-code-intelligence",priority:2,reason:"Moderate complexity benefits from code intelligence analysis"}),o.push("unit","integration"),l="sonnet";break;case"complex":a.push({agentType:"qe-test-generator",priority:1,reason:"Complex code needs comprehensive test generation"},{agentType:"qe-security-scanner",priority:2,reason:"High complexity warrants security analysis"},{agentType:"qe-code-intelligence",priority:2,reason:"Complex code requires deep code intelligence"}),o.push("unit","integration","security"),l="sonnet";break;case"critical":a.push({agentType:"qe-test-generator",priority:1,reason:"Critical complexity demands full test generation"},{agentType:"qe-security-scanner",priority:1,reason:"Critical complexity mandates security scanning"},{agentType:"qe-code-intelligence",priority:1,reason:"Critical complexity requires deep analysis"},{agentType:"qe-chaos-resilience",priority:2,reason:"Critical systems need chaos/resilience testing"},{agentType:"qe-performance",priority:2,reason:"Critical complexity warrants performance analysis"}),o.push("unit","integration","security","chaos","performance"),l="opus";break}return r.securitySurface>.3&&(a.some(c=>c.agentType==="qe-security-scanner")||a.push({agentType:"qe-security-scanner",priority:2,reason:`High security surface (${(r.securitySurface*100).toFixed(0)}%) \u2014 security scanning recommended`}),o.includes("security")||o.push("security")),r.concurrency>.3&&(a.some(c=>c.agentType==="qe-chaos-resilience")||a.push({agentType:"qe-chaos-resilience",priority:2,reason:`High concurrency (${(r.concurrency*100).toFixed(0)}%) \u2014 chaos/resilience testing recommended`}),o.includes("chaos")||o.push("chaos")),r.apiSurface>.5&&(o.includes("integration")||o.push("integration")),a.sort((c,u)=>c.priority-u.priority),{agents:a,testTypes:o,recommendedTier:l,complexityCategory:i}}countKeywordLines(e,t){let n=0;for(let i of e)for(let r of t)if(i.includes(r)){n++;break}return n}countPatternMatches(e,t){let n=e.match(t);return n?n.length:0}};function le(s,e,t){return Math.max(e,Math.min(t,s))}var Kt=200,Yt=10,Zt=3,ue=class{configs;history=[];escalationCount=0;deescalationCount=0;constructor(e){this.configs={...ze,...e}}selectTier(e){let t,n;if(e.manualOverride)return t=e.manualOverride,n=`Manual override to "${t}" tier`,this.buildResult(t,n,e);if(e.trigger==="incident"||e.isHotfix)return t="crisis",n=e.isHotfix?"Hotfix deployment triggers crisis-level validation":"Production incident triggers crisis-level response",this.buildResult(t,n,e);if(e.trigger==="release")return t="deep",n="Pre-release validation requires deep tier across all domains",this.buildResult(t,n,e);if(e.trigger==="pr"){let i=e.changedFiles!==void 0&&e.changedFiles>Yt,r=e.affectedDomains!==void 0&&e.affectedDomains.length>Zt;if(i||r){t="deep";let a=[];return i&&a.push(`>${Yt} changed files (${e.changedFiles})`),r&&a.push(`>${Zt} affected domains (${e.affectedDomains.length})`),n=`PR escalated to deep tier: ${a.join(" and ")}`,this.buildResult(t,n,e)}return t="standard",n="Pull request triggers standard tier validation",this.buildResult(t,n,e)}return t="smoke",n=e.trigger==="commit"?"Commit triggers lightweight smoke validation":`Trigger "${e.trigger}" defaults to smoke tier`,this.buildResult(t,n,e)}allocateAgents(e,t){let n=this.resolveTargetDomains(e,t);if(n.length===0)return[];let i=e.maxAgents;return n.length>=i?this.allocateWithPriority(n,i):this.allocateWithSurplus(n,i)}escalate(e,t){let n=x.indexOf(e),i=Math.min(n+1,x.length-1),r=x[i],a=e!==r,o=a?`Escalated from "${e}" to "${r}": ${t}`:`Already at maximum tier "${e}", cannot escalate further`;return a&&this.escalationCount++,this.buildResult(r,o,{trigger:"manual"})}deescalate(e){let t=x.indexOf(e),n=Math.max(t-1,0),i=x[n],r=e!==i,a=r?`De-escalated from "${e}" to "${i}"`:`Already at minimum tier "${e}", cannot de-escalate further`;return r&&this.deescalationCount++,this.buildResult(i,a,{trigger:"manual"})}getStats(){let e={smoke:0,standard:0,deep:0,crisis:0};for(let t of this.history)e[t.tier]++;return{totalSelections:this.history.length,selectionsByTier:e,escalationCount:this.escalationCount,deescalationCount:this.deescalationCount,recentSelections:[...this.history].slice(-20)}}_teamComposer;setTeamComposer(e){this._teamComposer=e}selectTierWithComposition(e,t,n){let i=this.selectTier(e);if(!t||!n)return{...i,composition:void 0};let a=(this._teamComposer??new U).compose(t,i.selectedTier,n);return{...i,composition:a}}buildResult(e,t,n){let i=this.configs[e],r=this.allocateAgents(i,n.affectedDomains),a={tier:e,reason:t,timestamp:Date.now(),trigger:n.trigger};return this.history.push(a),this.history.length>Kt&&this.history.splice(0,this.history.length-Kt),{selectedTier:e,config:i,reason:t,agentAllocation:r}}resolveTargetDomains(e,t){let n=e.domains.includes("all")?$:e.domains;if(!t||t.length===0)return[...n];let i=new Set(n),r=t.filter(a=>i.has(a));return r.length>0?r:[...n]}allocateWithPriority(e,t){let n=new Set(ce),i=[],r=t,a=e.filter(l=>n.has(l)),o=e.filter(l=>!n.has(l));for(let l of a){if(r<=0)break;i.push(this.createAllocation(l,1)),r--}for(let l of o){if(r<=0)break;i.push(this.createAllocation(l,1)),r--}return i}allocateWithSurplus(e,t){let n=new Set(ce),i=new Map;for(let u of e)i.set(u,1);let r=t-e.length,a=e.filter(u=>n.has(u)),o=e.filter(u=>!n.has(u)),l=0;for(;r>0&&a.length>0;){let u=a[l%a.length];if(i.set(u,(i.get(u)??0)+1),r--,l++,l>=a.length*2)break}let c=0;for(;r>0&&o.length>0;){let u=o[c%o.length];i.set(u,(i.get(u)??0)+1),r--,c++}for(;r>0&&a.length>0;){let u=a[l%a.length];i.set(u,(i.get(u)??0)+1),r--,l++}return e.map(u=>this.createAllocation(u,i.get(u)??1))}createAllocation(e,t){let n=qe[e]??["specialist"];return{domain:e,agentCount:t,agentTypes:[...n]}}};function Ge(s){return new ue(s)}k();var me={enabled:!0,minQualityScore:.6,rejectOnFailure:!0,gates:[{name:"test-pass-rate",type:"test-pass-rate",threshold:.8,weight:.35,required:!0},{name:"coverage",type:"coverage",threshold:0,weight:.25,required:!1},{name:"security",type:"security",threshold:0,weight:.25,required:!0},{name:"performance",type:"performance",threshold:3e4,weight:.15,required:!1}]},de=class{config;constructor(e={}){this.config={...me,...e},e.gates&&(this.config={...this.config,gates:e.gates})}evaluate(e){if(!this.config.enabled)return console.log("[QualityGateEnforcer] Gates disabled, auto-passing"),{passed:!0,score:1,exitCode:0,gates:[],reason:"Quality gates disabled"};if(e.status==="failed")return console.log(`[QualityGateEnforcer] Task ${e.taskId} has failed status`),{passed:!1,score:0,exitCode:this.config.rejectOnFailure?2:0,gates:[],reason:"Task reported failed status"};let t=[],n=[];for(let d of this.config.gates){let m=this.checkGate(d,e);t.push(m),!m.passed&&d.required&&n.push(d.name)}let i=this.config.gates.reduce((d,m)=>d+m.weight,0),r=i>0?t.reduce((d,m)=>{let p=this.config.gates.find(K=>K.name===m.gate);if(!p)return d;let T=m.passed?1:this.computePartialScore(m);return d+T*(p.weight/i)},0):1,a=n.length>0,o=r<this.config.minQualityScore,l=!a&&!o,c;if(!l){let d=[];a&&d.push(`Required gates failed: ${n.join(", ")}`),o&&d.push(`Score ${r.toFixed(3)} below minimum ${this.config.minQualityScore}`),c=d.join("; ")}let u=!l&&this.config.rejectOnFailure?2:0;return console.log(`[QualityGateEnforcer] Task ${e.taskId}: ${l?"PASSED":"FAILED"} (score=${r.toFixed(3)}, gates=${t.filter(d=>d.passed).length}/${t.length})`),{passed:l,score:r,exitCode:u,gates:t,reason:c}}getConfig(){return{...this.config}}checkGate(e,t){let n=this.extractMetricForGate(e,t),i=this.meetsThreshold(e,n);return{gate:e.name,passed:i,actual:n,threshold:e.threshold,weight:e.weight}}extractMetricForGate(e,t){let n=t.metrics;switch(e.type){case"coverage":return n.coverageChange??0;case"test-pass-rate":{let i=n.testsPassed??0,r=n.testsFailed??0,a=i+r;return a>0?i/a:1}case"security":return n.securityIssues??0;case"performance":return n.performanceMs??t.duration;case"custom":{let i=t.output[e.name];return typeof i=="number"?i:0}default:return 0}}meetsThreshold(e,t){switch(e.type){case"security":return t<=e.threshold;case"performance":return t<=e.threshold;default:return t>=e.threshold}}computePartialScore(e){let t=this.config.gates.find(n=>n.name===e.gate);if(!t)return 0;switch(t.type){case"security":case"performance":{if(t.threshold===0)return 0;let n=t.threshold/e.actual;return Math.max(0,Math.min(1,n))}default:{if(t.threshold===0)return 1;let n=e.actual/t.threshold;return Math.max(0,Math.min(1,n))}}}};var ui={trainPatterns:!0,qualityGate:me,patternDomains:["test-generation","coverage-analysis","security-compliance","quality-assessment","defect-intelligence","contract-testing"],emitEvents:!0,maxPatternsPerTask:5},di={"test-generation":{types:["test-template","assertion-pattern","mock-pattern"],contentKeys:["testCode","template","assertions","mocks"],baseConfidence:.6},"coverage-analysis":{types:["coverage-strategy","mutation-strategy"],contentKeys:["coverageReport","gaps","strategy","recommendations"],baseConfidence:.55},"security-compliance":{types:["security-pattern","vulnerability-fix"],contentKeys:["findings","fixes","recommendations","rules"],baseConfidence:.5},"quality-assessment":{types:["quality-rule","threshold-pattern"],contentKeys:["rules","thresholds","assessments"],baseConfidence:.5},"defect-intelligence":{types:["defect-pattern","root-cause"],contentKeys:["rootCause","pattern","prediction","analysis"],baseConfidence:.45},"contract-testing":{types:["api-contract","schema-pattern"],contentKeys:["contract","schema","endpoints","violations"],baseConfidence:.55},"test-execution":{types:["flaky-fix","retry-strategy"],contentKeys:["flakyTests","retryPolicy","stabilization"],baseConfidence:.5},"visual-accessibility":{types:["visual-baseline","a11y-check"],contentKeys:["baseline","violations","wcagResults"],baseConfidence:.5},"chaos-resilience":{types:["perf-benchmark","resilience-pattern"],contentKeys:["benchmark","faultInjection","recoveryTime"],baseConfidence:.45}},ge=class{config;gateEnforcer;patternStore;completionHandlers=new Set;stats={totalProcessed:0,accepted:0,rejected:0,patternsExtracted:0};constructor(e={},t){this.config={...ui,...e},e.qualityGate&&(this.config={...this.config,qualityGate:{...me,...e.qualityGate}}),this.gateEnforcer=new de(this.config.qualityGate),this.patternStore=t??null}async onTaskCompleted(e){this.stats.totalProcessed++,console.log(`[TaskCompletedHook] Processing task ${e.taskId} (agent=${e.agentId}, domain=${e.domain}, status=${e.status})`);let t=this.gateEnforcer.evaluate(e);if(!t.passed&&this.config.qualityGate.rejectOnFailure){this.stats.rejected++;let r={action:"reject",exitCode:2,reason:t.reason||"Quality gate check failed",gateResult:t};return console.log(`[TaskCompletedHook] Task ${e.taskId} REJECTED: ${r.reason}`),this.emitCompletion(e.taskId,r),r}let n=0;if(this.config.trainPatterns&&this.patternStore){let r=this.extractPatterns(e);n=await this.storePatterns(r,e),this.stats.patternsExtracted+=n}this.stats.accepted++;let i={action:"accept",patternsExtracted:n};return console.log(`[TaskCompletedHook] Task ${e.taskId} ACCEPTED (score=${t.score.toFixed(3)}, patterns=${n})`),this.emitCompletion(e.taskId,i),i}extractPatterns(e){let t=[],n=e.domain;if(!this.config.patternDomains.includes(n))return t;let i=di[n];if(!i)return this.extractGenericPatterns(e);let r=this.computeConfidenceBoost(e.metrics);for(let a of i.types){if(t.length>=this.config.maxPatternsPerTask)break;for(let o of i.contentKeys){if(t.length>=this.config.maxPatternsPerTask)break;let l=e.output[o];if(l==null)continue;let c=typeof l=="string"?l:JSON.stringify(l);if(c.length<10)continue;let u=Math.min(1,i.baseConfidence+r);t.push({domain:n,type:a,content:c,confidence:u,metadata:{sourceTaskId:e.taskId,sourceAgent:e.agentId,taskType:e.type,duration:e.duration,extractedFrom:o,timestamp:e.timestamp}})}}return t}onCompletion(e){this.completionHandlers.add(e)}offCompletion(e){this.completionHandlers.delete(e)}getStats(){return{...this.stats}}resetStats(){this.stats={totalProcessed:0,accepted:0,rejected:0,patternsExtracted:0}}async storePatterns(e,t){if(!this.patternStore||e.length===0)return 0;let n=0;for(let i of e)try{let r=await this.patternStore.store(i),a=t.status==="completed";await this.patternStore.recordOutcome(r,a),n++}catch(r){console.error(`[TaskCompletedHook] Failed to store pattern: ${h(r)}`)}return n>0&&console.log(`[TaskCompletedHook] Stored ${n}/${e.length} patterns from task ${t.taskId}`),n}extractGenericPatterns(e){let t=[];for(let[n,i]of Object.entries(e.output)){if(t.length>=this.config.maxPatternsPerTask)break;if(i==null)continue;let r=typeof i=="string"?i:JSON.stringify(i);r.length<10||t.push({domain:e.domain,type:"generic",content:r,confidence:.3+this.computeConfidenceBoost(e.metrics),metadata:{sourceTaskId:e.taskId,sourceAgent:e.agentId,taskType:e.type,extractedFrom:n,timestamp:e.timestamp}})}return t}computeConfidenceBoost(e){let t=0,n=e.testsPassed??0,i=e.testsFailed??0,r=n+i;return r>0&&(t+=n/r*.15),e.coverageChange!==void 0&&e.coverageChange>0&&(t+=Math.min(.1,e.coverageChange*.5)),e.securityIssues!==void 0&&e.securityIssues===0&&(t+=.1),e.performanceMs!==void 0&&e.performanceMs<5e3&&(t+=.05),Math.min(.4,t)}emitCompletion(e,t){if(this.config.emitEvents)for(let n of this.completionHandlers)try{n(e,t)}catch(i){console.error(`[TaskCompletedHook] Completion handler error: ${h(i)}`)}}};k();var mi={"test-template":"test-template","assertion-pattern":"assertion-pattern","mock-pattern":"mock-pattern","coverage-strategy":"coverage-strategy","mutation-strategy":"mutation-strategy","security-pattern":"error-handling","vulnerability-fix":"error-handling","quality-rule":"test-template","threshold-pattern":"test-template","defect-pattern":"error-handling","root-cause":"error-handling","api-contract":"api-contract","schema-pattern":"api-contract","flaky-fix":"flaky-fix","retry-strategy":"flaky-fix","visual-baseline":"visual-baseline","a11y-check":"a11y-check","perf-benchmark":"perf-benchmark","resilience-pattern":"perf-benchmark",generic:"test-template"};function gi(s){return mi[s]??"test-template"}function pi(s){let e=xe(s.domain);if(e)return e;let t=xe(s.content);return t||"test-generation"}function hi(s){let e=0;for(let t=0;t<s.length;t++){let n=s.charCodeAt(t);e=(e<<5)-e+n,e=e&e}return Math.abs(e).toString(36).slice(0,8)}var pe=class{constructor(e){this.reasoningBank=e}reasoningBank;async store(e){let t=pi(e),n=gi(e.type),i=hi(e.content),r=`${t}-${e.type}-${i}`,a=[t,e.type,...e.metadata.sourceTaskId?[`task:${e.metadata.sourceTaskId}`]:[]],o={patternType:n,name:r,description:`Auto-extracted ${e.type} pattern from ${e.domain} domain`,template:{type:"prompt",content:e.content,variables:[]},context:{tags:a},confidence:e.confidence};try{let l=await this.reasoningBank.storePattern(o);if(l.success)return l.value.id;throw console.error(`[ReasoningBankPatternStore] Failed to store pattern: ${l.error.message}`),l.error}catch(l){throw console.error(`[ReasoningBankPatternStore] Store error: ${h(l)}`),l}}async recordOutcome(e,t){let n={patternId:e,success:t};try{let i=await this.reasoningBank.recordOutcome(n);i.success||console.error(`[ReasoningBankPatternStore] Failed to record outcome: ${i.error.message}`)}catch(i){console.error(`[ReasoningBankPatternStore] recordOutcome error: ${h(i)}`)}}};Dn();var We={maxHypothesesPerInvestigation:5,convergenceThreshold:.2,investigationTimeoutMs:3e5,minEvidenceForConvergence:3,autoRejectThreshold:.15};import{randomUUID as je}from"node:crypto";var he=class{investigations=new Map;config;constructor(e){this.config={...We,...e}}createInvestigation(e,t,n){let i=`inv-${je().slice(0,8)}`,r=Date.now(),a={id:i,taskId:e,domain:t,description:n,hypotheses:[],status:"open",maxHypotheses:this.config.maxHypothesesPerInvestigation,convergenceThreshold:this.config.convergenceThreshold,createdAt:r,updatedAt:r};return this.investigations.set(i,a),this.toSnapshot(a)}addHypothesis(e,t,n,i){let r=this.getInvestigationMutable(e);if(r.hypotheses.length>=r.maxHypotheses)throw new Error(`Investigation ${e} already has ${r.maxHypotheses} hypotheses (max)`);let a={id:`hyp-${je().slice(0,8)}`,description:t,investigatorAgentId:i,strategy:n,status:"pending",evidence:[],confidenceScore:.5,createdAt:Date.now(),updatedAt:Date.now()};return r.hypotheses.push(a),r.updatedAt=Date.now(),r.status==="open"&&(r.status="investigating"),a}startHypothesis(e,t){let n=this.getInvestigationMutable(e),i=this.findHypothesis(n,t);if(i.status!=="pending")throw new Error(`Hypothesis ${t} cannot be started (current status: ${i.status})`);i.status="investigating",i.updatedAt=Date.now(),n.updatedAt=Date.now()}completeHypothesis(e,t){let n=this.getInvestigationMutable(e),i=this.findHypothesis(n,t);i.status="completed",i.updatedAt=Date.now(),n.updatedAt=Date.now()}submitEvidence(e,t,n){let i=this.getInvestigationMutable(e),r=this.findHypothesis(i,t),a={...n,id:`evi-${je().slice(0,8)}`,hypothesisId:t,timestamp:Date.now()};return r.evidence.push(a),r.confidenceScore=this.calculateConfidence(r),r.updatedAt=Date.now(),i.updatedAt=Date.now(),r.confidenceScore<this.config.autoRejectThreshold&&r.evidence.length>=2&&(r.status="rejected"),a}converge(e){let t=this.getInvestigationMutable(e),n=t.hypotheses.reduce((c,u)=>c+u.evidence.length,0);if(n<this.config.minEvidenceForConvergence){t.status="inconclusive";let c={winningHypothesisId:null,confidence:0,evidenceSummary:`Insufficient evidence (${n}/${this.config.minEvidenceForConvergence} required)`,rejectedHypotheses:t.hypotheses.filter(u=>u.status==="rejected").map(u=>u.id),method:"evidence-scoring"};return t.convergenceResult=c,t.updatedAt=Date.now(),c}let i=[...t.hypotheses].filter(c=>c.status!=="rejected").sort((c,u)=>u.confidenceScore-c.confidenceScore),r="evidence-scoring",a=null,o=0;i.length===0?t.status="inconclusive":i.length===1?(a=i[0].id,o=i[0].confidenceScore,r="unanimous",t.status="converged"):i[0].confidenceScore-i[1].confidenceScore>=t.convergenceThreshold?(a=i[0].id,o=i[0].confidenceScore,t.status="converged"):t.status="inconclusive";let l={winningHypothesisId:a,confidence:o,evidenceSummary:this.buildEvidenceSummary(t),rejectedHypotheses:t.hypotheses.filter(c=>c.status==="rejected").map(c=>c.id),method:r};return t.convergenceResult=l,t.updatedAt=Date.now(),l}getInvestigation(e){let t=this.investigations.get(e);return t?this.toSnapshot(t):void 0}listInvestigations(){return Array.from(this.investigations.values()).map(e=>this.toSnapshot(e))}getConfig(){return this.config}dispose(){this.investigations.clear()}getInvestigationMutable(e){let t=this.investigations.get(e);if(!t)throw new Error(`Investigation ${e} not found`);return t}findHypothesis(e,t){let n=e.hypotheses.find(i=>i.id===t);if(!n)throw new Error(`Hypothesis ${t} not found in investigation ${e.id}`);return n}calculateConfidence(e){if(e.evidence.length===0)return .5;let t=0,n=0;for(let r of e.evidence)r.supports?t+=r.weight:n+=r.weight;let i=t+n;return i===0?.5:Math.min(1,Math.max(0,t/i))}buildEvidenceSummary(e){let t=[];for(let n of e.hypotheses){let i=n.evidence.filter(a=>a.supports).length,r=n.evidence.filter(a=>!a.supports).length;t.push(`${n.id}: ${i} supporting, ${r} refuting (confidence: ${n.confidenceScore.toFixed(2)})`)}return t.join("; ")}toSnapshot(e){return{...e,hypotheses:e.hypotheses.map(t=>({...t,evidence:[...t.evidence]}))}}};function Ve(s){return new he(s)}import{randomUUID as fi}from"node:crypto";var Ke={localFleetId:"local",heartbeatIntervalMs:3e4,serviceTimeoutMs:9e4,maxPendingMessages:5e3,maxRoutes:100};var ye=class{config;services=new Map;routes=[];outbox=[];inbox=[];handlers=[];messagesSent=0;messagesReceived=0;constructor(e){this.config={...Ke,...e}}registerService(e,t,n,i){if(this.services.has(e))throw new Error(`Service '${e}' already registered`);let r=Date.now(),a={fleetId:e,name:t,domains:[...n],status:"active",registeredAt:r,lastHeartbeat:r,metadata:i};return this.services.set(e,a),fe(a)}deregisterService(e){let t=this.services.get(e);if(!t)return!1;t.status="deregistered";for(let n=this.routes.length-1;n>=0;n--)this.routes[n].targetFleetId===e&&this.routes.splice(n,1);return this.services.delete(e),!0}heartbeat(e){let t=this.services.get(e);return t?(t.lastHeartbeat=Date.now(),(t.status==="degraded"||t.status==="unreachable")&&(t.status="active"),!0):!1}addRoute(e,t,n,i=0){if(this.routes.length>=this.config.maxRoutes)throw new Error(`Maximum routes (${this.config.maxRoutes}) reached`);let r={sourceDomain:e,targetDomain:t,targetFleetId:n,priority:i,active:!0};return this.routes.push(r),this.routes.sort((a,o)=>o.priority-a.priority),Xt(r)}removeRoute(e,t){let n=this.routes.findIndex(i=>i.sourceDomain===e&&i.targetFleetId===t);return n<0?!1:(this.routes.splice(n,1),!0)}send(e,t,n,i,r,a){let o=e==="any"?this.resolveRoute(t,n):e;if(!o)throw new Error(`No route found for ${t} -> ${n}`);let l={id:fi(),sourceFleetId:this.config.localFleetId,targetFleetId:o,sourceDomain:t,targetDomain:n,type:i,payload:r,timestamp:Date.now(),ttl:a?.ttl,correlationId:a?.correlationId};return this.outbox.length>=this.config.maxPendingMessages&&this.outbox.shift(),this.outbox.push(l),this.messagesSent++,l}receive(e){this.inbox.length>=this.config.maxPendingMessages&&this.inbox.shift(),this.inbox.push(e),this.messagesReceived++;for(let t of this.handlers)try{t(e)}catch{}}onMessage(e){return this.handlers.push(e),()=>{let t=this.handlers.indexOf(e);t>=0&&this.handlers.splice(t,1)}}drainOutbox(){let e=[...this.outbox];return this.outbox.length=0,e}drainInbox(){let e=[...this.inbox];return this.inbox.length=0,e}findServicesByDomain(e){return Array.from(this.services.values()).filter(t=>t.status==="active"&&t.domains.includes(e)).map(fe)}getService(e){let t=this.services.get(e);return t?fe(t):void 0}listServices(){return Array.from(this.services.values()).map(fe)}listRoutes(){return this.routes.map(Xt)}checkHealth(){let e=Date.now();for(let t of this.services.values()){if(t.status==="deregistered")continue;let n=e-t.lastHeartbeat;n>this.config.serviceTimeoutMs?t.status="unreachable":n>this.config.serviceTimeoutMs*.6&&(t.status="degraded")}}getHealth(){return{localFleetId:this.config.localFleetId,connectedServices:Array.from(this.services.values()).filter(e=>e.status==="active").length,activeRoutes:this.routes.filter(e=>e.active).length,pendingMessages:this.outbox.length+this.inbox.length,messagesSent:this.messagesSent,messagesReceived:this.messagesReceived}}dispose(){this.services.clear(),this.routes.length=0,this.outbox.length=0,this.inbox.length=0,this.handlers.length=0}resolveRoute(e,t){for(let i of this.routes)if(i.active&&i.sourceDomain===e&&i.targetDomain===t){let r=this.services.get(i.targetFleetId);if(r&&r.status==="active")return i.targetFleetId}let n=this.findServicesByDomain(t);return n.length>0?n[0].fleetId:void 0}};function fe(s){return{fleetId:s.fleetId,name:s.name,domains:[...s.domains],status:s.status,registeredAt:s.registeredAt,lastHeartbeat:s.lastHeartbeat,metadata:s.metadata,endpoint:void 0}}function Xt(s){return{sourceDomain:s.sourceDomain,targetDomain:s.targetDomain,targetFleetId:s.targetFleetId,priority:s.priority,active:s.active}}function Ye(s){return new ye(s)}var Jt={name:"default",scaleUpQueueRatio:3,scaleDownIdleRatio:.5,errorRateScaleUpThreshold:.3,minAgents:2,maxAgents:15,cooldownMs:3e4,sampleWindowSize:5},Ze={defaultPolicy:Jt,metricsHistorySize:100,decisionHistorySize:50};import{randomUUID as yi}from"node:crypto";Ae();k();var Te=class s{config;policy;metricsHistory=[];events=[];lastScaleTime=0;scaleUpCount=0;scaleDownCount=0;totalDecisions=0;currentAgents;lastDecision;db=null;persistCount=0;static KV_NAMESPACE="scaling-metrics";static KV_KEY="dynamic-scaler-snapshot";static PERSIST_INTERVAL=10;static KV_TTL=7200;constructor(e=2,t){this.config={...Ze,...t},this.policy=this.config.defaultPolicy,this.currentAgents=e}recordMetrics(e){this.metricsHistory.push(e),this.metricsHistory.length>this.config.metricsHistorySize&&this.metricsHistory.shift(),this.persistCount++,this.persistCount%s.PERSIST_INTERVAL===0&&this.persistSnapshot().catch(()=>{})}evaluate(){let e=this.getAverageMetrics(),t=Date.now();if(this.totalDecisions++,t-this.lastScaleTime<this.policy.cooldownMs){let o={action:"maintain",currentAgents:this.currentAgents,targetAgents:this.currentAgents,reason:"Cooldown period active",metrics:e,timestamp:t};return this.lastDecision=o,o}let n="maintain",i=this.currentAgents,r="Workload within acceptable range";if(e.errorRate>this.policy.errorRateScaleUpThreshold)n="scale-up",i=Math.min(this.currentAgents+2,this.policy.maxAgents),r=`High error rate (${(e.errorRate*100).toFixed(1)}% > ${(this.policy.errorRateScaleUpThreshold*100).toFixed(1)}% threshold)`;else if(this.currentAgents>0&&e.queueDepth/Math.max(1,this.currentAgents)>this.policy.scaleUpQueueRatio){n="scale-up";let o=Math.ceil(e.queueDepth/this.policy.scaleUpQueueRatio);i=Math.min(o,this.policy.maxAgents),r=`Queue depth ratio ${(e.queueDepth/Math.max(1,this.currentAgents)).toFixed(1)} > ${this.policy.scaleUpQueueRatio} threshold`}if(n==="maintain"&&this.currentAgents>this.policy.minAgents){let o=this.currentAgents>0?e.idleAgents/this.currentAgents:0;if(o>this.policy.scaleDownIdleRatio){n="scale-down";let l=Math.floor(e.idleAgents*.5);i=Math.max(this.currentAgents-l,this.policy.minAgents),r=`Idle ratio ${(o*100).toFixed(1)}% > ${(this.policy.scaleDownIdleRatio*100).toFixed(1)}% threshold`}}i=Math.max(this.policy.minAgents,Math.min(this.policy.maxAgents,i)),i===this.currentAgents&&(n="maintain");let a={action:n,currentAgents:this.currentAgents,targetAgents:i,reason:r,metrics:e,timestamp:t};return this.lastDecision=a,a}async execute(e,t){let n={id:`scale-${yi().slice(0,8)}`,decision:e,executedAt:Date.now(),success:!0};if(e.action==="maintain")return this.recordEvent(n),n;try{if(t&&!await t(e.currentAgents,e.targetAgents)){let r={...n,success:!1,error:"Executor returned false"};return this.recordEvent(r),r}return this.currentAgents=e.targetAgents,this.lastScaleTime=Date.now(),e.action==="scale-up"&&this.scaleUpCount++,e.action==="scale-down"&&this.scaleDownCount++,this.recordEvent(n),n}catch(i){let r={...n,success:!1,error:h(i)};return this.recordEvent(r),r}}setPolicy(e){this.policy=e}getPolicy(){return{...this.policy}}getCurrentAgents(){return this.currentAgents}getStats(){return{scaleUpCount:this.scaleUpCount,scaleDownCount:this.scaleDownCount,totalDecisions:this.totalDecisions,currentAgents:this.currentAgents,policyName:this.policy.name,lastDecision:this.lastDecision,recentEvents:[...this.events].slice(-10)}}getMetricsHistory(){return[...this.metricsHistory]}async initialize(){try{this.db=R(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(e){console.warn("[DynamicScaler] DB init failed, using memory-only:",h(e)),this.db=null}}dispose(){this.metricsHistory.length=0,this.events.length=0}getAverageMetrics(){let e=this.metricsHistory.slice(-this.policy.sampleWindowSize);if(e.length===0)return{queueDepth:0,activeAgents:this.currentAgents,idleAgents:0,avgTaskDurationMs:0,errorRate:0,throughput:0,timestamp:Date.now()};let t=n=>e.reduce((i,r)=>i+n(r),0)/e.length;return{queueDepth:Math.round(t(n=>n.queueDepth)),activeAgents:Math.round(t(n=>n.activeAgents)),idleAgents:Math.round(t(n=>n.idleAgents)),avgTaskDurationMs:Math.round(t(n=>n.avgTaskDurationMs)),errorRate:t(n=>n.errorRate),throughput:t(n=>n.throughput),timestamp:Date.now()}}recordEvent(e){this.events.push(e),this.events.length>this.config.decisionHistorySize&&this.events.shift(),this.persistCount++,this.persistCount%s.PERSIST_INTERVAL===0&&this.persistSnapshot().catch(()=>{})}async loadFromKv(){if(this.db)try{let e=await this.db.kvGet(s.KV_KEY,s.KV_NAMESPACE);if(e){if(Array.isArray(e.metricsHistory))for(let t of e.metricsHistory)this.metricsHistory.push(t);if(Array.isArray(e.events))for(let t of e.events)this.events.push(t)}}catch(e){console.warn("[DynamicScaler] Failed to load KV snapshot:",h(e))}}async persistSnapshot(){if(this.db)try{let e={metricsHistory:this.metricsHistory.slice(-50),events:this.events.slice(-50)};await this.db.kvSet(s.KV_KEY,e,s.KV_NAMESPACE,s.KV_TTL)}catch(e){console.warn("[DynamicScaler] Failed to persist KV snapshot:",h(e))}}};function Xe(s,e){return new Te(s,e)}var Ti=[{name:"Core Testing",domains:["test-generation","test-execution","coverage-analysis","quality-assessment"],priority:"p0",description:"Core testing workflow domains"},{name:"Intelligence",domains:["defect-intelligence","code-intelligence","requirements-validation","security-compliance"],priority:"p0",description:"Intelligence and analysis domains"},{name:"Specialized",domains:["contract-testing","visual-accessibility","chaos-resilience","learning-optimization"],priority:"p1",description:"Specialized testing domains"}],q={"generate-tests":["test-generation"],"execute-tests":["test-execution"],"analyze-coverage":["coverage-analysis"],"assess-quality":["quality-assessment"],"predict-defects":["defect-intelligence"],"validate-requirements":["requirements-validation"],"index-code":["code-intelligence"],"scan-security":["security-compliance"],"validate-contracts":["contract-testing"],"test-accessibility":["visual-accessibility"],"run-chaos":["chaos-resilience"],"optimize-learning":["learning-optimization"],"cross-domain-workflow":[],"protocol-execution":[],"ideation-assessment":["requirements-validation","coverage-analysis","security-compliance"]},en={maxConcurrentTasks:50,defaultTaskTimeout:3e5,taskRetryLimit:3,workStealing:{enabled:!0,idleThreshold:5e3,loadThreshold:10,stealBatchSize:3,checkInterval:1e4},enableMetrics:!0,metricsInterval:6e4,priorityWeights:{p0:100,p1:50,p2:25,p3:10},enableRouting:!0};function E(s){return Object.hasOwn(q,s)?q[s]:[]}function tn(s){q["cross-domain-workflow"]=s,q["protocol-execution"]=s}import{readFileSync as Ci,existsSync as bi}from"fs";import{join as ki}from"path";import{parse as Si}from"yaml";Ae();import{randomUUID as vi}from"crypto";var z={RISK_WEIGHTS:2160*60*60*1e3,SFDIPOT_WEIGHTS:2160*60*60*1e3,FLAKY_PATTERNS:720*60*60*1e3,AC_QUALITY:1440*60*60*1e3};function G(s,e){let t=Date.now(),n=vi().split("-")[0];return`${e||s}-signal-${t}-${n}`}function W(s){return new Date(Date.now()+s).toISOString()}function w(s){return new Date(s.expiresAt)<new Date}var b={STRATEGIC:"qcsd/strategic",TACTICAL:"qcsd/tactical",OPERATIONAL:"qcsd/operational",QUALITY_CRITERIA:"qcsd/quality-criteria"},et=class{memory;initialized=!1;constructor(e={}){this.memory=e.memoryManager||R()}async initialize(){this.initialized||(await this.memory.initialize(),this.initialized=!0,console.log("[CrossPhaseMemory] Initialized with UnifiedMemoryManager"))}async storeRiskSignal(e,t){await this.ensureInitialized();let n={id:G("strategic","risk"),timestamp:new Date().toISOString(),source:"production",target:"ideation",loopType:"strategic",version:"1.0.0",expiresAt:W(z.RISK_WEIGHTS),riskWeights:e,recommendations:t};return await this.store(b.STRATEGIC,n),n}async queryRiskSignals(){return await this.ensureInitialized(),(await this.queryByNamespace(b.STRATEGIC)).filter(t=>!w(t))}async storeSFDIPOTSignal(e,t,n){await this.ensureInitialized();let i={id:G("tactical","sfdipot"),timestamp:new Date().toISOString(),source:"production",target:"refinement",loopType:"tactical",version:"1.0.0",expiresAt:W(z.SFDIPOT_WEIGHTS),factorWeights:e,featureContext:t,recommendations:n};return await this.store(b.TACTICAL,i),i}async querySFDIPOTSignals(e){await this.ensureInitialized();let t=await this.queryByNamespace(b.TACTICAL);return t=t.filter(n=>!w(n)),e&&(t=t.filter(n=>n.featureContext.toLowerCase().includes(e.toLowerCase()))),t}async storeTestHealthSignal(e,t,n){await this.ensureInitialized();let i={id:G("operational","test-health"),timestamp:new Date().toISOString(),source:"cicd",target:"development",loopType:"operational",version:"1.0.0",expiresAt:W(z.FLAKY_PATTERNS),flakyPatterns:e,gateFailures:t,recommendations:n};return await this.store(b.OPERATIONAL,i),i}async queryTestHealthSignals(){return await this.ensureInitialized(),(await this.queryByNamespace(b.OPERATIONAL)).filter(t=>!w(t))}async storeACQualitySignal(e,t,n){await this.ensureInitialized();let i={id:G("quality-criteria","ac-quality"),timestamp:new Date().toISOString(),source:"development",target:"refinement",loopType:"quality-criteria",version:"1.0.0",expiresAt:W(z.AC_QUALITY),untestablePatterns:e,coverageGaps:t,recommendations:n};return await this.store(b.QUALITY_CRITERIA,i),i}async queryACQualitySignals(){return await this.ensureInitialized(),(await this.queryByNamespace(b.QUALITY_CRITERIA)).filter(t=>!w(t))}async store(e,t){let n=new Date(t.expiresAt).getTime(),i=Math.max(0,Math.floor((n-Date.now())/1e3));await this.memory.kvSet(t.id,t,e,i>0?i:void 0),console.log(`[CrossPhaseMemory] Stored signal: ${t.id} in ${e}`)}async queryByNamespace(e){let t=await this.memory.kvSearch("*",e,1e3),n=[];for(let i of t){let r=await this.memory.kvGet(i,e);r&&n.push(r)}return n.sort((i,r)=>new Date(r.timestamp).getTime()-new Date(i.timestamp).getTime())}async delete(e,t){let n=await this.memory.kvDelete(t,e);return n&&console.log(`[CrossPhaseMemory] Deleted signal: ${t}`),n}async cleanupExpired(){let e={deleted:0,namespaces:{}};for(let t of Object.values(b)){let n=await this.queryByNamespace(t),i=0;for(let r of n)w(r)&&(await this.delete(t,r.id),i++,e.deleted++);i>0&&(e.namespaces[t]=i)}return e.deleted>0&&console.log(`[CrossPhaseMemory] Cleanup: deleted ${e.deleted} expired signals`),e}async getStats(){await this.ensureInitialized();let e={totalSignals:0,byLoop:{strategic:0,tactical:0,operational:0,"quality-criteria":0},byNamespace:{},oldestSignal:null,newestSignal:null},t=null,n=null;for(let i of Object.values(b)){let a=(await this.queryByNamespace(i)).filter(o=>!w(o));e.byNamespace[i]=a.length,e.totalSignals+=a.length;for(let o of a){e.byLoop[o.loopType]++;let l=new Date(o.timestamp);(!t||l<t)&&(t=l,e.oldestSignal=o.timestamp),(!n||l>n)&&(n=l,e.newestSignal=o.timestamp)}}return e}async ensureInitialized(){this.initialized||await this.initialize()}},Je=null;function nn(s){return Je||(Je=new et(s)),Je}function tt(s){let e=Object.getOwnPropertyNames(s);for(let t of e){let n=s[t];n&&typeof n=="object"&&!Object.isFrozen(n)&&tt(n)}return Object.freeze(s)}function nt(s){let e=structuredClone(s);return tt(e)}function it(s){return s===0?"success":s===2?"model_blocking":"user_error"}xn();var st=class{config=null;memory;configPath;listeners=new Map;constructor(e){this.configPath=e||ki(process.cwd(),".claude/hooks/cross-phase-memory.yaml"),this.memory=nn()}async initialize(){if(process.env.AQE_HOOKS_DISABLED==="true")return console.log("[CrossPhaseHooks] All hooks disabled via AQE_HOOKS_DISABLED"),!1;if(!bi(this.configPath))return console.warn(`[CrossPhaseHooks] Config not found: ${this.configPath}`),!1;try{let e=Ci(this.configPath,"utf-8"),t=Si(e);return t.enabled?(this.config=nt(t),await this.memory.initialize(),console.log(`[CrossPhaseHooks] Initialized with ${Object.keys(this.config.hooks).length} hooks`),!0):(console.log("[CrossPhaseHooks] Hooks disabled in config"),!1)}catch(e){return console.error("[CrossPhaseHooks] Failed to load config:",e),!1}}async onAgentComplete(e,t){if(!this.config||process.env.AQE_HOOKS_DISABLED==="true")return;let n=this.filterManagedHooks(Object.entries(this.config.hooks).filter(([i,r])=>r.trigger.event==="agent-complete"&&r.trigger.agent===e));for(let[i,r]of n)this.checkConditions(r.trigger.conditions,t)&&(console.log(`[CrossPhaseHooks] Executing hook: ${i}`),await this.executeActions(r.actions,t))}async onPhaseStart(e,t={}){if(!this.config)return{};if(process.env.AQE_HOOKS_DISABLED==="true")return{};let n=ht(),i=this.filterManagedHooks(Object.entries(this.config.hooks).filter(([r,a])=>a.trigger.event==="phase-start"&&a.trigger.phase===e));for(let[r,a]of i){console.log(`[CrossPhaseHooks] Executing phase-start hook: ${r}`);for(let o of a.actions)if(o.type==="query-signals"&&o.injectInto){let l=await this.querySignalsForInjection(o.namespace,o.maxAge,o.filterBy?t[o.filterBy]:void 0);for(let c of o.injectInto)n[c]||(n[c]=[]),n[c].push(...l)}}return n}async onPhaseEnd(e,t){if(!this.config||process.env.AQE_HOOKS_DISABLED==="true")return;let n=this.filterManagedHooks(Object.entries(this.config.hooks).filter(([i,r])=>r.trigger.event==="phase-end"&&r.trigger.phase===e));for(let[i,r]of n)console.log(`[CrossPhaseHooks] Executing phase-end hook: ${i}`),await this.executeActions(r.actions,t)}async executeActions(e,t){for(let n of e)try{await this.executeAction(n,t)}catch(i){let r=i?.exitCode;if(typeof r=="number"){let a=it(r);if(a==="model_blocking")throw console.error(`[CrossPhaseHooks] Model-blocking hook failure (exit ${r}):`,i),i;console.warn(`[CrossPhaseHooks] Hook ${a} (exit ${r}):`,i)}else console.error("[CrossPhaseHooks] Action failed:",i)}}async executeAction(e,t){switch(e.type){case"store-signal":await this.executeStoreSignal(e,t);break;case"query-signals":break;case"notify-agent":await this.executeNotifyAgent(e,t);break;case"invoke-agent":await this.executeInvokeAgent(e,t);break;case"conditional":e.condition&&e.action&&this.evaluateCondition(e.condition,t)&&await this.executeAction(e.action,t);break;case"delete-expired":await this.memory.cleanupExpired();break;default:console.warn(`[CrossPhaseHooks] Unknown action type: ${e.type}`)}}async executeStoreSignal(e,t){if(!e.loop||!e.namespace||!e.extract)return;let n=this.extractFromContext(e.extract,t);switch(e.loop){case"strategic":await this.memory.storeRiskSignal(n.riskWeights||[],n.recommendations||{forRiskAssessor:[],forQualityCriteria:[]});break;case"tactical":await this.memory.storeSFDIPOTSignal(n.factorWeights||[],n.featureContext||"unknown",n.recommendations||{forProductFactorsAssessor:[]});break;case"operational":await this.memory.storeTestHealthSignal(n.flakyPatterns||[],n.gateFailures||[],n.recommendations||{forTestArchitect:[],antiPatterns:[]});break;case"quality-criteria":await this.memory.storeACQualitySignal(n.untestablePatterns||[],n.coverageGaps||[],n.recommendations||{forRequirementsValidator:[],acTemplates:{}});break}this.emit("signal-stored",{loop:e.loop,namespace:e.namespace})}async executeNotifyAgent(e,t){!e.target||!e.message||await this.isBlockedUrl(e.target)||(console.log(`[CrossPhaseHooks] Notify ${e.target}: ${e.message}`),this.emit("agent-notification",{target:e.target,message:e.message,priority:e.priority||"normal",context:t}))}async executeInvokeAgent(e,t){e.target&&(await this.isBlockedUrl(e.target)||(console.log(`[CrossPhaseHooks] Invoke agent: ${e.target}`),this.emit("agent-invocation",{agent:e.target,input:{...t,...e.input||{}}})))}async querySignalsForInjection(e,t,n){let r=await this.memory.queryByNamespace(e);if(t){let a=this.parseMaxAge(t),o=Date.now()-a;r=r.filter(l=>new Date(l.timestamp).getTime()>o)}return r}formatSignalsForInjection(e){if(e.length===0)return"";let t=`## CROSS-PHASE LEARNING SIGNALS
|
|
168
168
|
|
|
169
169
|
`;t+=`The following signals have been automatically injected from previous phases.
|
|
170
170
|
`,t+=`Apply these learnings to your analysis.
|
|
@@ -177,4 +177,4 @@ import{b as Ee}from"./chunk-XSPMLJCQ.js";import{a as St}from"./chunk-6P4Q4RTC.js
|
|
|
177
177
|
`;let i=this.getRecommendations(n);if(i.length>0){t+=`**Recommendations:**
|
|
178
178
|
`;for(let r of i)t+=`- ${r}
|
|
179
179
|
`;t+=`
|
|
180
|
-
`}}return t}getRecommendations(e){switch(e.loopType){case"strategic":return[...e.recommendations.forRiskAssessor,...e.recommendations.forQualityCriteria];case"tactical":return e.recommendations.forProductFactorsAssessor;case"operational":return[...e.recommendations.forTestArchitect,...e.recommendations.antiPatterns];case"quality-criteria":return e.recommendations.forRequirementsValidator;default:return[]}}filterManagedHooks(e){if(process.env.AQE_HOOKS_MANAGED_ONLY!=="true")return e;let t=e.filter(([n])=>n.startsWith("managed:"));return t.length<e.length&&console.log(`[CrossPhaseHooks] AQE_HOOKS_MANAGED_ONLY: filtered ${e.length-t.length} non-managed hooks`),t}async isBlockedUrl(e){if(!e.includes("://"))return!1;let t=await Ee(e);return t.safe?!1:(console.warn(`[CrossPhaseHooks] SSRF blocked: ${t.reason}`),!0)}checkConditions(e,t){return!e||e.length===0?!0:e.every(n=>this.evaluateCondition(n,t))}evaluateCondition(e,t){try{let n=e.split(/\s*(>|<|>=|<=|==|!=)\s*/);if(n.length!==3)return!1;let[i,r,a]=n,o=this.getValueFromPath(t,i),l=isNaN(Number(a))?a:Number(a),c=typeof o=="number"?o:Number(o),u=typeof l=="number"?l:Number(l);switch(r){case">":return c>u;case"<":return c<u;case">=":return c>=u;case"<=":return c<=u;case"==":return o==l;case"!=":return o!=l;default:return!1}}catch{return!1}}getValueFromPath(e,t){return t.split(".").reduce((n,i)=>{if(n&&typeof n=="object"&&Object.hasOwn(n,i))return n[i]},e)}extractFromContext(e,t){let n={};for(let[i,r]of Object.entries(e))n[i]=this.getValueFromPath(t,r);return n}parseMaxAge(e){let t=e.match(/^(\d+)(d|h|m|s)$/);if(!t)return 0;let[,n,i]=t,r=parseInt(n,10);switch(i){case"d":return r*24*60*60*1e3;case"h":return r*60*60*1e3;case"m":return r*60*1e3;case"s":return r*1e3;default:return 0}}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t)}off(e,t){this.listeners.get(e)?.delete(t)}emit(e,t){this.listeners.get(e)?.forEach(n=>n(t))}async runCleanup(){if(!this.config?.cleanup.enabled)return;console.log("[CrossPhaseHooks] Running cleanup...");let e=await this.memory.cleanupExpired();console.log(`[CrossPhaseHooks] Cleanup complete: ${e.deleted} signals deleted`)}},it=null;function nn(s){return it||(it=new rt(s)),it}function H(s,e){let t=s.get(e);return t?.status!=="cancelled"?{ignored:!1,settledNow:!1}:t.cancellationResultPending?(s.set(e,{...t,cancellationResultPending:!1}),{ignored:!0,settledNow:!0}):{ignored:!0,settledNow:!1}}function rn(s,e){let t=[];for(let a of e){let o=s.router.subscribeToDoamin(a,async l=>{await ki(s,l)});t.push(o)}let n=s.router.subscribeToEventType("TaskCompleted",async a=>{await Si(s,a)});t.push(n);let i=s.router.subscribeToEventType("TaskFailed",async a=>{await Di(s,a)});t.push(i);let r=s.router.subscribeToEventType("AgentStatusChanged",async a=>{await Ai(s,a)});return t.push(r),t}async function ki(s,e){s.domainLastActivity.set(e.source,new Date),await s.processQueue()}async function sn(s,e){for(let t of e.assignedAgents)await s.agentCoordinator.stop(t)}async function Si(s,e){let{taskId:t,result:n}=e.payload,i=H(s.tasks,t);if(i.ignored){i.settledNow&&(s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),await s.processQueue());return}let r=s.tasks.get(t);if(r){await sn(s,r),(r.status==="running"||r.status==="assigned")&&(s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1));let a=r.startedAt?Date.now()-r.startedAt.getTime():0;s.tasks.set(t,{...r,status:"completed",completedAt:new Date,result:n}),s.tasksCompleted++,s.taskDurations.push(a),s.auditLogger.logComplete(t,r.assignedAgents[0]);try{let o=nn(),l=r.assignedAgents[0];l&&await o.onAgentComplete(l,{taskId:t,taskType:r.task.type,domain:r.assignedDomain,result:n,duration:a})}catch(o){console.warn("[QueenCoordinator] Cross-phase hook error:",o)}try{await _.afterTaskExecution({taskId:t,taskType:r.task.type,agentId:r.assignedAgents[0]||"unknown",domain:r.assignedDomain||"test-generation",priority:r.task.priority},!0,0,0)}catch(o){console.warn("[QueenCoordinator] Governance tracking error:",o)}if(s.domainBreakerRegistry&&r.assignedDomain&&s.domainBreakerRegistry.getBreaker(r.assignedDomain).recordSuccess(),s.traceCollector){let o=s.taskTraceContexts.get(t);o&&(s.traceCollector.completeSpan(o.spanId),s.taskTraceContexts.delete(t))}if(s.taskCompletedHook)try{let o=typeof n=="object"&&n!==null?n:null;if(o===null)console.error(`[QueenCoordinator] Pattern training skipped for task ${t}: result is not an object (got ${typeof n})`);else{let l=xi(o,t);if(l){let c={taskId:t,agentId:r.assignedAgents[0]||"unknown",domain:r.assignedDomain||"test-generation",type:r.task.type,status:"completed",output:o,metrics:l,duration:a,timestamp:Date.now()};s.taskCompletedHook.onTaskCompleted(c).catch(u=>{console.warn("[QueenCoordinator] Pattern training error:",u)})}}}catch(o){console.warn("[QueenCoordinator] Pattern training setup error:",o)}}await s.processQueue()}async function Di(s,e){let{taskId:t,error:n,callerError:i}=e.payload,r=H(s.tasks,t);if(r.ignored){r.settledNow&&(s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),await s.processQueue());return}let a=s.tasks.get(t);if(a){if(await sn(s,a),(a.status==="running"||a.status==="assigned")&&(s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1)),s.domainBreakerRegistry&&a.assignedDomain&&!i&&s.domainBreakerRegistry.getBreaker(a.assignedDomain).recordFailure(new Error(n||"Task failed")),s.traceCollector){let l=s.taskTraceContexts.get(t);l&&(s.traceCollector.failSpan(l.spanId,n||"Task failed"),s.taskTraceContexts.delete(t))}let o=a.task.executionOwner==="caller";if(!i&&!o&&a.retryCount<s.config.taskRetryLimit){s.auditLogger.logFail(t,a.assignedAgents[0],n);let l={...a,status:"queued",retryCount:a.retryCount+1,error:n};s.tasks.set(t,l),s.enqueueTask(a.task)}else{s.tasks.set(t,{...a,status:"failed",completedAt:new Date,error:n}),s.tasksFailed++,s.auditLogger.logFail(t,a.assignedAgents[0],n);try{await _.afterTaskExecution({taskId:t,taskType:a.task.type,agentId:a.assignedAgents[0]||"unknown",domain:a.assignedDomain||"test-generation",priority:a.task.priority},!1,0,0)}catch(l){console.warn("[QueenCoordinator] Governance tracking error:",l)}if(!i&&s.hypothesisManager&&(a.task.priority==="p0"||a.task.priority==="p1"))try{let l=a.assignedDomain||"test-generation",c=s.hypothesisManager.createInvestigation(t,l,`Root cause analysis for ${a.task.type} failure: ${n}`);s.hypothesisManager.addHypothesis(c.id,`Infrastructure failure in domain '${l}' caused task ${t} to fail`,"log-analysis",`${l}-lead`),s.hypothesisManager.addHypothesis(c.id,`Logic/configuration error in task payload caused ${a.task.type} to fail: ${n}`,"code-analysis",a.assignedAgents[0]||"unknown"),console.log(`[QueenCoordinator] Competing hypotheses investigation created: ${c.id}`)}catch(l){console.warn("[QueenCoordinator] Hypothesis creation error:",l)}}}await s.processQueue()}async function Ai(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 xi(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 an(s,e,t){let n=s.listAgents({domain:e}),i=n.filter(l=>l.status==="running").length,r=n.filter(l=>l.status==="idle").length,a=n.filter(l=>l.status==="failed").length,o;return a>0&&a>=n.length/2?o="unhealthy":a>0?o="degraded":i>0?o="healthy":o="idle",{status:o,agents:{total:n.length,active:i,idle:r,failed:a},lastActivity:t,errors:[]}}function W(s,e,t){let n=[];for(let i of t){let r=s.get(i);if(!r)n.push(`${i} (domain not loaded)`);else if(!r.executeTask||!r.canHandleTask?.(e)){let a=r.getSupportedTaskTypes?.()??[];n.push(a.length>0?`${i} (supported: ${a.join(", ")})`:i)}}return n}function Ei(s,e){let t=[];for(let[n,i]of s)i.executeTask&&i.canHandleTask?.(e)&&t.push(n);return t}function st(s,e,t){if(e.length>0)return e;let n=E(s);return n.length>0||!t?n:Ei(t,s)}function ve(s,e){return`No handler for task type '${s}' in domain ${e.join("; ")}`}k();k();var cn=kt();function at(s,e,t){let n=s.get(t.priority);n&&bt(n,t,cn);for(let i of t.targetDomains){let r=e.get(i);r&&r.push(t)}}function N(s,e,t){let n=s.get(t.priority);if(n){let i=n.findIndex(r=>r.id===t.id);i!==-1&&n.splice(i,1)}for(let i of t.targetDomains){let r=e.get(i);if(r){let a=r.findIndex(o=>o.id===t.id);a!==-1&&r.splice(a,1)}}}function be(s,e){let t=0;for(let n of["p0","p1","p2","p3"]){let i=s.get(n);if(i){if(n===e.priority){t+=i.findIndex(r=>r.id===e.id);break}t+=i.length}}return t}async function M(s){if(!(s.runningTaskCounter>=s.config.maxConcurrentTasks)){O.set(s.tasks,(O.get(s.tasks)??0)+1);try{do{Ce.delete(s.tasks);for(let e of["p0","p1","p2","p3"]){let t=s.taskQueue.get(e);if(!t||t.length===0)continue;let n=on(s,t);for(;n;){N(s.taskQueue,s.domainQueues,n),s.runningTaskCounter++;let i;try{i=await Se(s,n)}catch(r){throw s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),r}if(!i.success&&(s.tasks.get(n.id)?.status??"queued")==="queued"&&await ke(s,n,void 0,i.error.message),s.runningTaskCounter>=s.config.maxConcurrentTasks)return;n=on(s,t)}}}while(Ce.has(s.tasks)&&s.runningTaskCounter<s.config.maxConcurrentTasks)}finally{let e=(O.get(s.tasks)??1)-1;e>0?O.set(s.tasks,e):(O.delete(s.tasks),Ce.delete(s.tasks))}}}var O=new WeakMap,Ce=new WeakSet;async function V(s){if(s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),O.has(s.tasks)){Ce.add(s.tasks);return}M(s).catch(e=>{console.warn("[Queen] Queue drain after a released slot failed:",h(e))})}function on(s,e){let t=e.shift();for(;t;){let n=s.tasks.get(t.id)?.status;if(n===void 0||n==="queued")return t;N(s.taskQueue,s.domainQueues,t),t=e.shift()}}async function ke(s,e,t,n){s.tasks.set(e.id,{taskId:e.id,task:e,status:"failed",assignedDomain:t,assignedAgents:[],retryCount:s.tasks.get(e.id)?.retryCount??0,error:n,completedAt:new Date}),s.tasksFailed++,s.auditLogger.logFail(e.id,void 0,n),await s.publishEvent("TaskFailed",{taskId:e.id,domain:t,error:n}),await V(s)}function ln(s,e){let t=Array.from(s.values());return e&&(e.status&&(t=t.filter(n=>n.status===e.status)),e.domain&&(t=t.filter(n=>n.assignedDomain===e.domain)),e.priority&&(t=t.filter(n=>n.task.priority===e.priority)),e.type&&(t=t.filter(n=>n.task.type===e.type)),e.fromDate&&(t=t.filter(n=>n.task.createdAt>=e.fromDate)),e.toDate&&(t=t.filter(n=>n.task.createdAt<=e.toDate))),t}async function Se(s,e){let t=e.targetDomains.length>0?e.targetDomains:E(e.type);if(t.length===0)return f(new Error(`No domains configured for task type: ${e.type}`));let n,i=1/0;for(let r of t){let a=s.getDomainLoad(r);s.getDomainHealth(r)?.status!=="unhealthy"&&a<i&&(i=a,n=r)}return n?un(s,e,n):f(new Error("No healthy domain available for task"))}async function un(s,e,t){if(e.executionOwner!=="caller"&&s.domainPlugins){let c=W(s.domainPlugins,e.type,[t]);if(c.length>0)return wi(s,e,t,ve(e.type,c))}let n;if(s.tinyDancerRouter){let c={p0:"critical",p1:"high",p2:"normal",p3:"low"},u={description:`${e.type}: ${JSON.stringify(e.payload).slice(0,200)}`,type:e.type,domain:t,priority:Object.hasOwn(c,e.priority)?c[e.priority]:"normal"};n=await s.tinyDancerRouter.route(u),s.config.enableMetrics&&console.log(`[Queen] TinyDancer routing: ${e.type} \u2192 tier=${n.tier}, model=${n.model}, cost=$${n.estimatedCost.toFixed(4)}`)}if(s.domainBreakerRegistry&&!s.domainBreakerRegistry.canExecuteInDomain(t))return f(new Error(`Domain '${t}' circuit breaker is open \u2014 too many recent failures`));if(s.domainTeamManager)try{if(!s.domainTeamManager.getDomainTeam(t)){let u=`${t}-lead`;s.domainTeamManager.createDomainTeam(t,u)}}catch(c){console.warn(`[Queen] Domain team setup for '${t}' failed (continuing):`,c)}let i=n?.tier||"task-worker",r=["task-execution",e.type,...n?[`model:${n.model}`]:[],...n?.triggerMultiModel?["advisor:triggerMultiModel"]:[]],a=await s.requestAgentSpawn(t,i,r,e.id);if(s.tasks.get(e.id)?.status==="cancelled")return a.success&&await s.agentCoordinator.stop(a.value),await V(s),y(e.id);let o=[];a.success&&o.push(a.value);let l={taskId:e.id,task:e,status:"running",assignedDomain:t,assignedAgents:o,startedAt:new Date,retryCount:0};s.tasks.set(e.id,l),s.domainLastActivity.set(t,new Date);for(let c of o)s.auditLogger.logAssign(e.id,c,t);if(await s.publishEvent("TaskAssigned",{taskId:e.id,domain:t,agentIds:o}),e.executionOwner==="caller")return y(e.id);if(s.domainPlugins){let c=s.domainPlugins.get(t);if(c?.executeTask&&c.canHandleTask?.(e.type)){let u={taskId:e.id,taskType:e.type,payload:e.payload,priority:e.priority,timeout:e.timeout,correlationId:e.correlationId},d;try{d=await c.executeTask(u,g=>Mi(s,g))}catch(g){d=f(Z(g))}if(!d.success){let g=H(s.tasks,e.id);return g.ignored?(g.settledNow&&await V(s),y(e.id)):s.tasks.get(e.id)?.status!=="running"?f(d.error):(s.tasks.set(e.id,{...l,status:"failed",error:d.error.message,completedAt:new Date}),s.tasksFailed++,s.auditLogger.logFail(e.id,o[0],d.error.message),await s.publishEvent("TaskFailed",{taskId:e.id,domain:t,error:d.error.message}),await V(s),f(d.error))}return y(e.id)}}return y(e.id)}async function wi(s,e,t,n){let i=s.taskTraceContexts.get(e.id);return s.traceCollector&&i&&(s.traceCollector.failSpan(i.spanId,n),s.taskTraceContexts.delete(e.id)),await ke(s,e,t,n),y(e.id)}async function dn(s,e,t){let n=s.tasks.get(e.id)?.status;if(n!==void 0&&n!=="queued")return!1;s.runningTaskCounter++;let i;try{i=await un(s,e,t)}catch(a){throw s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),a}!i.success&&(s.tasks.get(e.id)?.status??"queued")==="queued"&&await ke(s,e,t,i.error.message);let r=s.tasks.get(e.id);return r?.assignedDomain===t&&(r.status==="running"||r.status==="completed")}async function Mi(s,e){let t=s.tasks.get(e.taskId);if(!t){console.warn(`[Queen] Received completion for unknown task: ${e.taskId}`);return}let n=H(s.tasks,e.taskId);if(n.ignored){n.settledNow&&(s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),await M(s));return}let i={...t,status:e.success?"completed":"failed",completedAt:new Date,result:e.data,error:e.error};if(s.tasks.set(e.taskId,i),e.success?(s.tasksCompleted++,s.taskDurations.push(e.duration),s.auditLogger.logComplete(e.taskId,t.assignedAgents[0])):(s.tasksFailed++,s.auditLogger.logFail(e.taskId,t.assignedAgents[0],e.error||"Unknown error")),s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),s.coExecutionRepo&&t.assignedAgents.length>=2)try{s.coExecutionRepo.recordSwarmCoExecution(t.assignedAgents,t.assignedDomain||"unknown",e.success,t.task.type)}catch{}for(let r of t.assignedAgents)await s.agentCoordinator.stop(r);await s.publishEvent(e.success?"TaskCompleted":"TaskFailed",{taskId:e.taskId,domain:t.assignedDomain,result:e.data,error:e.error,duration:e.duration}),await M(s)}function Ii(s,e){return E(e.type).includes(s)}function gn(s,e,t){return Ii(e,t)?t.executionOwner==="caller"||!s?!0:W(s,t.type,[e]).length===0:!1}k();async function mn(s){let e=0,t=s.getIdleDomains(),n=s.getBusyDomains();if(t.length===0||n.length===0)return 0;n.sort((i,r)=>s.getDomainLoad(r)-s.getDomainLoad(i));for(let i of n){if(t.length===0)break;let r=s.domainQueues.get(i)||[],a=Math.min(r.length,s.config.workStealing.stealBatchSize);for(let o=0;o<a&&t.length>0&&s.availableSlots()>0;o++){let l=r.find(c=>s.canExecuteInDomain(t[0],c));if(l){let c=t.shift();if(s.removeFromQueues(l),!await s.assignTaskToDomain(l,c))continue;s.auditLogger.logSteal(l.id,i,c),e++,s.tasksStolen++,await s.publishEvent("TaskStolen",{taskId:l.id,fromDomain:i,toDomain:c})}}}return e}function ot(s,e){let t=0,n=10,i=setInterval(async()=>{try{await e(),t=0}catch(r){t++;let a=Math.min(1e3*Math.pow(2,t),3e4);if(console.warn(`[QueenCoordinator] Work-stealing failed (attempt ${t}), backing off ${a}ms`,h(r)),t>n){console.error(`[QueenCoordinator] Work-stealing exceeded ${n} consecutive failures, stopping interval`),clearInterval(i);return}await new Promise(o=>setTimeout(o,a))}},s.workStealing.checkInterval);return i}function ct(s){return typeof s.setMinCutBridge=="function"}function pn(s,e){for(let[t,n]of s)ct(n)&&(n.setMinCutBridge(e),console.log(`[QueenCoordinator] MinCut bridge injected into ${t}`))}async function hn(s,e,t){try{let n=await s.get("queen:state");if(n){for(let[i,r]of n.tasks)if(r.status==="queued"){if(r.task.executionOwner==="caller"){e.set(i,{...r,status:"failed",error:"Caller-owned task was interrupted before completion; submit a new request.",completedAt:new Date});continue}e.set(i,r),t(r.task)}}}catch(n){console.debug("[QueenCoordinator] State loading failed:",n instanceof Error?n.message:n)}}async function fn(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 yn(s){return setInterval(async()=>{let e=s.getMetrics();if(await s.publishEvent("MetricsCollected",{metrics:e}),await s.memory.set(`queen:metrics:${Date.now()}`,e,{ttl:86400,namespace:"queen-coordinator"}),s.dynamicScaler)try{let t=s.getAverageTaskDuration(),n={queueDepth:s.getQueuedTaskCount(),activeAgents:s.getActiveAgentCount(),idleAgents:s.getIdleAgentCount(),avgTaskDurationMs:t,errorRate:s.getTasksReceived()>0?s.getTasksFailed()/s.getTasksReceived():0,throughput:e.uptime>0?s.getTasksCompleted()/(e.uptime/1e3):0,timestamp:Date.now()};s.dynamicScaler.recordMetrics(n);let i=s.dynamicScaler.evaluate();i&&i.action!=="maintain"&&(console.log(`[QueenCoordinator] Dynamic scaler: ${i.action} to ${i.targetAgents} agents \u2014 ${i.reason}`),s.dynamicScaler.execute(i).catch(r=>{console.warn("[QueenCoordinator] Dynamic scaling execution error:",r)}))}catch(t){console.warn("[QueenCoordinator] Dynamic scaler metrics error:",t)}},s.config.metricsInterval)}function lt(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 Tn(s,e){return s&&s.size>0?Array.from(s.keys()):[...e]}var m=gt.create("QueenCoordinator");en(v);var ut=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=we({enableConsoleLog:this.config.enableMetrics,maxEntries:1e3,logPrefix:"[QUEEN]"}),["p0","p1","p2","p3"].forEach(c=>{this.taskQueue.set(c,[])}),this.config.enableRouting!==!1&&(this.tinyDancerRouter=new ee(this.config.routing)),v.forEach(c=>{this.domainQueues.set(c,[]),this.domainLastActivity.set(c,new Date)})}eventBus;agentCoordinator;memory;router;protocolExecutor;workflowExecutor;domainPlugins;config;tasks=new Map;taskQueue=new Map;domainQueues=new Map;domainLastActivity=new Map;initialized=!1;workStealingTimer=null;metricsTimer=null;cleanupTimer=null;startTime=new Date;eventSubscriptionIds=[];runningTaskCounter=0;tasksReceived=0;tasksCompleted=0;tasksFailed=0;tasksStolen=0;taskDurations=new ht(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=ot(this.config,()=>this.triggerWorkStealing().then(()=>{}))),this.config.enableMetrics&&(this.metricsTimer=yn(this.createMetricsContext())),this.cleanupTimer=setInterval(()=>{lt(this.tasks,this.taskTraceContexts,36e5)},3e5),this.cleanupTimer.unref(),await hn(this.memory,this.tasks,e=>this.enqueueTaskInternal(e)),this.minCutBridge=xt(this.eventBus,this.agentCoordinator,{autoUpdateFromEvents:!0,persistData:!0,includeInQueenHealth:!0,sharedGraph:Tt()}),await this.minCutBridge.initialize(),this.domainPlugins&&pn(this.domainPlugins,this.minCutBridge);try{await _.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=Ut(t),this.availableMcpServers=St(process.cwd());let{getUnifiedMemory:n}=await import("./unified-memory-QARWQKJ2.js"),i=n();await i.initialize(),this.coExecutionRepo=Bt(),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:v}),this.initialized=!0}}async dispose(){this.workStealingTimer&&(clearInterval(this.workStealingTimer),this.workStealingTimer=null),this.metricsTimer&&(clearInterval(this.metricsTimer),this.metricsTimer=null),this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null),this.minCutBridge&&(await this.minCutBridge.dispose(),this.minCutBridge=null),this.domainTeamManager&&(this.domainTeamManager.dispose(),this.domainTeamManager=null),this.agentTeamsAdapter&&(this.agentTeamsAdapter.shutdown(),this.agentTeamsAdapter=null),this.domainBreakerRegistry=null,this.tierSelector=null,this.traceCollector&&(this.traceCollector.dispose(),this.traceCollector=null),this.hypothesisManager&&(this.hypothesisManager.dispose(),this.hypothesisManager=null),this.federationMailbox&&(this.federationMailbox.dispose(),this.federationMailbox=null),this.dynamicScaler&&(this.dynamicScaler.dispose(),this.dynamicScaler=null),await fn(this.memory,this.tasks);for(let[e,t]of this.tasks)(t.status==="queued"||t.status==="running")&&await this.cancelTask(e);await this.publishEvent("QueenShutdown",{timestamp:new Date,metrics:this.getMetrics()});for(let e of this.eventSubscriptionIds)this.router.unsubscribe(e);this.eventSubscriptionIds=[],await this.router.dispose(),this.initialized=!1}validateTaskExecutable(e,t=[]){let n=st(e,t,this.domainPlugins);if(n.length===0)return f(new Error(`Unknown task type '${e}': no domain is configured for it and no loaded domain handles it. Pass a target domain.`));if(!this.domainPlugins)return y(void 0);let i=W(this.domainPlugins,e,n);return i.length===0?y(void 0):f(new Error(ve(e,i)))}async submitTask(e){if(!this.initialized)return f(new Error("Queen Coordinator not initialized"));let t=`task_${C()}`,n={...e,targetDomains:E(e.type).length>0?e.targetDomains:[...st(e.type,e.targetDomains,this.domainPlugins)],id:t,createdAt:new Date,timeout:e.timeout||this.config.defaultTaskTimeout},i={taskId:n.id,taskType:n.type,agentId:n.requester||`queen-task:${n.id}`,domain:n.targetDomains[0]||"test-generation",priority:n.priority,payload:n.payload};try{let r=await _.beforeTaskExecution(i);if(!r.allowed)return this.auditLogger.logFail(t,"governance",r.reason||"Governance check failed"),await this.publishEvent("TaskRejected",{taskId:t,reason:r.reason,escalate:r.escalate}),f(new Error(`Task blocked by governance: ${r.reason}`))}catch(r){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 Se(this.createTaskContext(),n);return r.success?(this.tasksReceived++,await this.publishEvent("TaskSubmitted",{taskId:t,task:n}),y(t)):(this.tasks.has(t)||(this.runningTaskCounter=Math.max(0,this.runningTaskCounter-1)),r)}catch(r){throw this.runningTaskCounter=Math.max(0,this.runningTaskCounter-1),r}}async cancelTask(e){let t=this.tasks.get(e);if(!t)return f(new Error(`Task not found: ${e}`));if(t.status==="cancelled")return y(void 0);if(t.status==="completed"||t.status==="failed")return f(new Error(`Task already finished: ${e}`));let n=t.status==="running"||t.status==="assigned";this.tasks.set(e,{...t,status:"cancelled",completedAt:new Date,cancellationResultPending:n}),N(this.taskQueue,this.domainQueues,t.task);for(let i of t.assignedAgents)await this.agentCoordinator.stop(i);return this.auditLogger.logCancel(e),await this.publishEvent("TaskCancelled",{taskId:e}),y(void 0)}getTaskStatus(e){return this.tasks.get(e)}listTasks(e){return ln(this.tasks,e)}getDomainHealth(e){if(this.domainPlugins){let t=this.domainPlugins.get(e);if(t)return t.getHealth()}return an(this.agentCoordinator,e,this.domainLastActivity.get(e))}getDomainLoad(e){let t=this.domainQueues.get(e)||[],n=Array.from(this.tasks.values()).filter(i=>i.assignedDomain===e&&i.status==="running");return t.length+n.length}getIdleDomains(){let e=Date.now(),t=this.config.workStealing.idleThreshold;return v.filter(n=>{let i=this.domainLastActivity.get(n);return this.getDomainLoad(n)===0&&i&&e-i.getTime()>t})}getBusyDomains(){return v.filter(e=>this.getDomainLoad(e)>this.config.workStealing.loadThreshold)}getSpawnPlan(e){return this.dependencyGraph?qt(e,this.dependencyGraph):{phases:[e],warnings:[],unsatisfiedHardDeps:[]}}getDependencyGraph(){return this.dependencyGraph}enableWorkStealing(){this.workStealingTimer||(this.workStealingTimer=ot(this.config,()=>this.triggerWorkStealing().then(()=>{})))}disableWorkStealing(){this.workStealingTimer&&(clearInterval(this.workStealingTimer),this.workStealingTimer=null)}async triggerWorkStealing(){return mn(this.createWorkStealingContext())}listAllAgents(){return this.agentCoordinator.listAgents()}getAgentsByDomain(e){return this.agentCoordinator.listAgents({domain:e})}async requestAgentSpawn(e,t,n,i){if(!this.agentCoordinator.canSpawn())return f(new Error("Maximum concurrent agents reached (15)"));if(this.dependencyGraph&&this.availableMcpServers.length>0)try{for(let[,a]of this.dependencyGraph.nodes){let o=a.dependencies.mcpServers;if(!o||o.length===0)continue;let l=o.filter(c=>c.required&&!this.availableMcpServers.includes(c.name));if(l.length>0){m.warn(`Pre-spawn MCP advisory: ${a.agentName} needs ${l.map(c=>c.name).join(", ")}`,{agent:a.agentName,domain:e,missing:l.map(c=>c.name)});break}}}catch{}let r=await this.agentCoordinator.spawn({name:`${e}-${t}-${Date.now()}`,domain:e,type:t,capabilities:n});if(r.success){if(this.domainLastActivity.set(e,new Date),this.domainTeamManager&&typeof this.domainTeamManager.getDomainTeam=="function")try{if(this.domainTeamManager.getDomainTeam(e))this.domainTeamManager.addTeammate(e,r.value)||m.warn(`Agent ${r.value} could not join ${e} team (full)`);else try{this.domainTeamManager.createDomainTeam(e,r.value)}catch{this.domainTeamManager.addTeammate(e,r.value)||m.warn(`Agent ${r.value} could not join ${e} team (full or max teams reached)`)}}catch(a){m.warn(`Auto-team-wiring failed for ${r.value}`,{error:a})}await this.publishEvent("AgentSpawned",{agentId:r.value,domain:e,type:t,capabilities:n,...i?{taskId:i}:{}})}return r}getHealth(){let e=new Map,t=[],n=0,i=0,r=Tn(this.domainPlugins,v);for(let u of r){let d=this.getDomainHealth(u);d&&(e.set(u,d),d.status==="unhealthy"?(n++,t.push({domain:u,severity:"high",message:`Domain ${u} is unhealthy`,timestamp:new Date})):d.status==="degraded"&&(i++,t.push({domain:u,severity:"medium",message:`Domain ${u} is degraded`,timestamp:new Date})))}let a=this.agentCoordinator.listAgents(),o=a.filter(u=>u.status==="running").length,l="healthy";n>0?l="unhealthy":i>r.length/2&&(l="degraded");let c={status:l,domainHealth:e,totalAgents:a.length,activeAgents:o,pendingTasks:this.getQueuedTaskCount(),runningTasks:this.getRunningTaskCount(),workStealingActive:this.workStealingTimer!==null,lastHealthCheck:new Date,issues:t};return this.minCutBridge?this.minCutBridge.extendQueenHealth(c):c}getMetrics(){let e=new Map;for(let o of v){let l=this.getDomainLoad(o);e.set(o,l)}let t=this.agentCoordinator.listAgents(),n=t.filter(o=>o.status==="running").length,i=t.length>0?n/t.length:0,r=this.taskDurations.average(),a={tasksReceived:this.tasksReceived,tasksCompleted:this.tasksCompleted,tasksFailed:this.tasksFailed,tasksStolen:this.tasksStolen,averageTaskDuration:r,domainUtilization:e,agentUtilization:i,protocolsExecuted:this.protocolsExecuted,workflowsExecuted:this.workflowsExecuted,uptime:Date.now()-this.startTime.getTime()};return this.minCutBridge?this.minCutBridge.extendQueenMetrics(a):a}getMinCutBridge(){return this.minCutBridge}injectMinCutBridgeIntoDomain(e){if(!this.minCutBridge)return 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?ct(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 pe(e);this.taskCompletedHook=new me({},t),m.info("ReasoningBank connected for pattern training")}async executeProtocol(e,t){if(!this.protocolExecutor)return f(new Error("Protocol executor not configured"));let n=await this.protocolExecutor.execute(e,t);return n.success?(this.protocolsExecuted++,await this.publishEvent("ProtocolExecuted",{protocolId:e,executionId:n.value.executionId}),y(n.value.executionId)):n}async executeWorkflow(e,t){if(!this.workflowExecutor)return f(new Error("Workflow executor not configured"));let n=await this.workflowExecutor.execute(e,t);return n.success?(this.workflowsExecuted++,await this.publishEvent("WorkflowExecuted",{workflowId:e,executionId:n.value.executionId}),y(n.value.executionId)):n}cleanupCompletedTasks(e=36e5){return lt(this.tasks,this.taskTraceContexts,e)}subscribeToEvents(){this.eventSubscriptionIds=rn(this.createEventHandlerContext(),v)}enqueueTaskInternal(e){at(this.taskQueue,this.domainQueues,e)}async publishEvent(e,t){await this.eventBus.publish({id:C(),type:`Queen${e}`,timestamp:new Date,source:"queen-coordinator",payload:t})}queueTask(e){this.enqueueTaskInternal(e);let t={taskId:e.id,task:e,status:"queued",assignedAgents:[],retryCount:0};return this.tasks.set(e.id,t),this.tasksReceived++,this.auditLogger.logSubmit(e.id,{type:e.type,priority:e.priority}),this.auditLogger.logQueue(e.id,be(this.taskQueue,e)),this.publishEvent("TaskQueued",{taskId:e.id,task:e,position:be(this.taskQueue,e)}),y(e.id)}selectFleetTier(e){if(this.tierSelector)try{let t={trigger:e.payload?.trigger??"manual",changedFiles:e.payload?.changedFiles,affectedDomains:e.targetDomains,severity:e.priority==="p0"?"critical":e.priority==="p1"?"high":void 0,isHotfix:e.payload?.isHotfix},n=this.tierSelector.selectTier(t);return 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=Wt(),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=Qe(),this.agentTeamsAdapter.initialize(),this.domainTeamManager=Be(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=ze(),m.info("Fleet tier selector initialized")}catch(e){m.warn("Tier selector initialization failed (continuing)",{error:e})}try{this.traceCollector=Le(),m.info("Trace collector initialized")}catch(e){m.warn("Trace collector initialization failed (continuing)",{error:e})}try{this.hypothesisManager=We(),this.federationMailbox=Ke(),this.dynamicScaler=Ze(),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:()=>M(e.createTaskContext()),enqueueTask:t=>e.enqueueTaskInternal(t)}}createTaskContext(){let e=this;return{config:e.config,tasks:e.tasks,taskQueue:e.taskQueue,domainQueues:e.domainQueues,domainLastActivity:e.domainLastActivity,auditLogger:e.auditLogger,agentCoordinator:e.agentCoordinator,domainPlugins:e.domainPlugins,get runningTaskCounter(){return e.runningTaskCounter},set runningTaskCounter(t){e.runningTaskCounter=t},get tasksReceived(){return e.tasksReceived},set tasksReceived(t){e.tasksReceived=t},get tasksCompleted(){return e.tasksCompleted},set tasksCompleted(t){e.tasksCompleted=t},get tasksFailed(){return e.tasksFailed},set tasksFailed(t){e.tasksFailed=t},taskDurations:e.taskDurations,get tinyDancerRouter(){return e.tinyDancerRouter},get domainBreakerRegistry(){return e.domainBreakerRegistry},get domainTeamManager(){return e.domainTeamManager},get tierSelector(){return e.tierSelector},get traceCollector(){return e.traceCollector},taskTraceContexts:e.taskTraceContexts,get coExecutionRepo(){return e.coExecutionRepo},requestAgentSpawn:(t,n,i,r)=>e.requestAgentSpawn(t,n,i,r),publishEvent:(t,n)=>e.publishEvent(t,n),getDomainLoad:t=>e.getDomainLoad(t),getDomainHealth:t=>e.getDomainHealth(t)}}createWorkStealingContext(){let e=this;return{config:e.config,domainQueues:e.domainQueues,auditLogger:e.auditLogger,get tasksStolen(){return e.tasksStolen},set tasksStolen(t){e.tasksStolen=t},getIdleDomains:()=>e.getIdleDomains(),getBusyDomains:()=>e.getBusyDomains(),getDomainLoad:t=>e.getDomainLoad(t),availableSlots:()=>e.config.maxConcurrentTasks-e.runningTaskCounter,canExecuteInDomain:(t,n)=>(e.tasks.get(n.id)?.status??"queued")==="queued"&&gn(e.domainPlugins,t,n),removeFromQueues:t=>N(e.taskQueue,e.domainQueues,t),assignTaskToDomain:(t,n)=>dn(e.createTaskContext(),t,n),publishEvent:(t,n)=>e.publishEvent(t,n)}}createMetricsContext(){let e=this;return{config:e.config,memory:e.memory,get dynamicScaler(){return e.dynamicScaler},getMetrics:()=>e.getMetrics(),publishEvent:(t,n)=>e.publishEvent(t,n),getQueuedTaskCount:()=>e.getQueuedTaskCount(),getActiveAgentCount:()=>e.agentCoordinator.listAgents().filter(t=>t.status==="running").length,getIdleAgentCount:()=>e.agentCoordinator.listAgents().filter(t=>t.status==="idle").length,getAverageTaskDuration:()=>e.taskDurations.average(),getTasksReceived:()=>e.tasksReceived,getTasksFailed:()=>e.tasksFailed,getTasksCompleted:()=>e.tasksCompleted}}};function Uo(s,e,t,n,i,r){return new ut(s.eventBus,s.coordinator,s.memory,e,t,n,i,r)}export{fi as a,q as b,ut as c,Uo as d};
|
|
180
|
+
`}}return t}getRecommendations(e){switch(e.loopType){case"strategic":return[...e.recommendations.forRiskAssessor,...e.recommendations.forQualityCriteria];case"tactical":return e.recommendations.forProductFactorsAssessor;case"operational":return[...e.recommendations.forTestArchitect,...e.recommendations.antiPatterns];case"quality-criteria":return e.recommendations.forRequirementsValidator;default:return[]}}filterManagedHooks(e){if(process.env.AQE_HOOKS_MANAGED_ONLY!=="true")return e;let t=e.filter(([n])=>n.startsWith("managed:"));return t.length<e.length&&console.log(`[CrossPhaseHooks] AQE_HOOKS_MANAGED_ONLY: filtered ${e.length-t.length} non-managed hooks`),t}async isBlockedUrl(e){if(!e.includes("://"))return!1;let t=await we(e);return t.safe?!1:(console.warn(`[CrossPhaseHooks] SSRF blocked: ${t.reason}`),!0)}checkConditions(e,t){return!e||e.length===0?!0:e.every(n=>this.evaluateCondition(n,t))}evaluateCondition(e,t){try{let n=e.split(/\s*(>|<|>=|<=|==|!=)\s*/);if(n.length!==3)return!1;let[i,r,a]=n,o=this.getValueFromPath(t,i),l=isNaN(Number(a))?a:Number(a),c=typeof o=="number"?o:Number(o),u=typeof l=="number"?l:Number(l);switch(r){case">":return c>u;case"<":return c<u;case">=":return c>=u;case"<=":return c<=u;case"==":return o==l;case"!=":return o!=l;default:return!1}}catch{return!1}}getValueFromPath(e,t){return t.split(".").reduce((n,i)=>{if(n&&typeof n=="object"&&Object.hasOwn(n,i))return n[i]},e)}extractFromContext(e,t){let n={};for(let[i,r]of Object.entries(e))n[i]=this.getValueFromPath(t,r);return n}parseMaxAge(e){let t=e.match(/^(\d+)(d|h|m|s)$/);if(!t)return 0;let[,n,i]=t,r=parseInt(n,10);switch(i){case"d":return r*24*60*60*1e3;case"h":return r*60*60*1e3;case"m":return r*60*1e3;case"s":return r*1e3;default:return 0}}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t)}off(e,t){this.listeners.get(e)?.delete(t)}emit(e,t){this.listeners.get(e)?.forEach(n=>n(t))}async runCleanup(){if(!this.config?.cleanup.enabled)return;console.log("[CrossPhaseHooks] Running cleanup...");let e=await this.memory.cleanupExpired();console.log(`[CrossPhaseHooks] Cleanup complete: ${e.deleted} signals deleted`)}},rt=null;function rn(s){return rt||(rt=new st(s)),rt}function H(s,e){let t=s.get(e);return t?.status!=="cancelled"?{ignored:!1,settledNow:!1}:t.cancellationResultPending?(s.set(e,{...t,cancellationResultPending:!1}),{ignored:!0,settledNow:!0}):{ignored:!0,settledNow:!1}}function sn(s,e){let t=[];for(let a of e){let o=s.router.subscribeToDoamin(a,async l=>{await Di(s,l)});t.push(o)}let n=s.router.subscribeToEventType("TaskCompleted",async a=>{await Ai(s,a)});t.push(n);let i=s.router.subscribeToEventType("TaskFailed",async a=>{await xi(s,a)});t.push(i);let r=s.router.subscribeToEventType("AgentStatusChanged",async a=>{await Ei(s,a)});return t.push(r),t}async function Di(s,e){s.domainLastActivity.set(e.source,new Date),await s.processQueue()}async function an(s,e){for(let t of e.assignedAgents)await s.agentCoordinator.stop(t)}async function Ai(s,e){let{taskId:t,result:n}=e.payload,i=H(s.tasks,t);if(i.ignored){i.settledNow&&(s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),await s.processQueue());return}let r=s.tasks.get(t);if(r){await an(s,r),(r.status==="running"||r.status==="assigned")&&(s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1));let a=r.startedAt?Date.now()-r.startedAt.getTime():0;s.tasks.set(t,{...r,status:"completed",completedAt:new Date,result:n}),s.tasksCompleted++,s.taskDurations.push(a),s.auditLogger.logComplete(t,r.assignedAgents[0]);try{let o=rn(),l=r.assignedAgents[0];l&&await o.onAgentComplete(l,{taskId:t,taskType:r.task.type,domain:r.assignedDomain,result:n,duration:a})}catch(o){console.warn("[QueenCoordinator] Cross-phase hook error:",o)}try{await _.afterTaskExecution({taskId:t,taskType:r.task.type,agentId:r.assignedAgents[0]||"unknown",domain:r.assignedDomain||"test-generation",priority:r.task.priority},!0,0,0)}catch(o){console.warn("[QueenCoordinator] Governance tracking error:",o)}if(s.domainBreakerRegistry&&r.assignedDomain&&s.domainBreakerRegistry.getBreaker(r.assignedDomain).recordSuccess(),s.traceCollector){let o=s.taskTraceContexts.get(t);o&&(s.traceCollector.completeSpan(o.spanId),s.taskTraceContexts.delete(t))}if(s.taskCompletedHook)try{let o=typeof n=="object"&&n!==null?n:null;if(o===null)console.error(`[QueenCoordinator] Pattern training skipped for task ${t}: result is not an object (got ${typeof n})`);else{let l=wi(o,t);if(l){let c={taskId:t,agentId:r.assignedAgents[0]||"unknown",domain:r.assignedDomain||"test-generation",type:r.task.type,status:"completed",output:o,metrics:l,duration:a,timestamp:Date.now()};s.taskCompletedHook.onTaskCompleted(c).catch(u=>{console.warn("[QueenCoordinator] Pattern training error:",u)})}}}catch(o){console.warn("[QueenCoordinator] Pattern training setup error:",o)}}await s.processQueue()}async function xi(s,e){let{taskId:t,error:n,callerError:i}=e.payload,r=H(s.tasks,t);if(r.ignored){r.settledNow&&(s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),await s.processQueue());return}let a=s.tasks.get(t);if(a){if(await an(s,a),(a.status==="running"||a.status==="assigned")&&(s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1)),s.domainBreakerRegistry&&a.assignedDomain&&!i&&s.domainBreakerRegistry.getBreaker(a.assignedDomain).recordFailure(new Error(n||"Task failed")),s.traceCollector){let l=s.taskTraceContexts.get(t);l&&(s.traceCollector.failSpan(l.spanId,n||"Task failed"),s.taskTraceContexts.delete(t))}let o=a.task.executionOwner==="caller";if(!i&&!o&&a.retryCount<s.config.taskRetryLimit){s.auditLogger.logFail(t,a.assignedAgents[0],n);let l={...a,status:"queued",retryCount:a.retryCount+1,error:n};s.tasks.set(t,l),s.enqueueTask(a.task)}else{s.tasks.set(t,{...a,status:"failed",completedAt:new Date,error:n}),s.tasksFailed++,s.auditLogger.logFail(t,a.assignedAgents[0],n);try{await _.afterTaskExecution({taskId:t,taskType:a.task.type,agentId:a.assignedAgents[0]||"unknown",domain:a.assignedDomain||"test-generation",priority:a.task.priority},!1,0,0)}catch(l){console.warn("[QueenCoordinator] Governance tracking error:",l)}if(!i&&s.hypothesisManager&&(a.task.priority==="p0"||a.task.priority==="p1"))try{let l=a.assignedDomain||"test-generation",c=s.hypothesisManager.createInvestigation(t,l,`Root cause analysis for ${a.task.type} failure: ${n}`);s.hypothesisManager.addHypothesis(c.id,`Infrastructure failure in domain '${l}' caused task ${t} to fail`,"log-analysis",`${l}-lead`),s.hypothesisManager.addHypothesis(c.id,`Logic/configuration error in task payload caused ${a.task.type} to fail: ${n}`,"code-analysis",a.assignedAgents[0]||"unknown"),console.log(`[QueenCoordinator] Competing hypotheses investigation created: ${c.id}`)}catch(l){console.warn("[QueenCoordinator] Hypothesis creation error:",l)}}}await s.processQueue()}async function Ei(s,e){let{agentId:t,status:n,domain:i}=e.payload;s.domainLastActivity.set(i,new Date),(n==="completed"||n==="failed")&&await s.processQueue()}function wi(s,e){if("metrics"in s&&typeof s.metrics=="object"&&s.metrics!==null){let t=s.metrics;return{testsPassed:typeof t.testsPassed=="number"?t.testsPassed:void 0,testsFailed:typeof t.testsFailed=="number"?t.testsFailed:void 0,coverageChange:typeof t.coverageChange=="number"?t.coverageChange:void 0,securityIssues:typeof t.securityIssues=="number"?t.securityIssues:void 0,performanceMs:typeof t.performanceMs=="number"?t.performanceMs:void 0,linesChanged:typeof t.linesChanged=="number"?t.linesChanged:void 0}}return"testsPassed"in s||"testsFailed"in s?{testsPassed:typeof s.testsPassed=="number"?s.testsPassed:void 0,testsFailed:typeof s.testsFailed=="number"?s.testsFailed:void 0,coverageChange:typeof s.coverageChange=="number"?s.coverageChange:void 0,securityIssues:typeof s.securityIssues=="number"?s.securityIssues:void 0,performanceMs:typeof s.performanceMs=="number"?s.performanceMs:void 0,linesChanged:typeof s.linesChanged=="number"?s.linesChanged:void 0}:(console.error(`[QueenCoordinator] Pattern training skipped for task ${e}: result object has no recognizable metrics shape (keys: ${Object.keys(s).join(", ")})`),null)}function on(s,e,t){let n=s.listAgents({domain:e}),i=n.filter(l=>l.status==="running").length,r=n.filter(l=>l.status==="idle").length,a=n.filter(l=>l.status==="failed").length,o;return a>0&&a>=n.length/2?o="unhealthy":a>0?o="degraded":i>0?o="healthy":o="idle",{status:o,agents:{total:n.length,active:i,idle:r,failed:a},lastActivity:t,errors:[]}}function j(s,e,t){let n=[];for(let i of t){let r=s.get(i);if(!r)n.push(`${i} (domain not loaded)`);else if(!r.executeTask||!r.canHandleTask?.(e)){let a=r.getSupportedTaskTypes?.()??[];n.push(a.length>0?`${i} (supported: ${a.join(", ")})`:i)}}return n}function Mi(s,e){let t=[];for(let[n,i]of s)i.executeTask&&i.canHandleTask?.(e)&&t.push(n);return t}function at(s,e,t){if(e.length>0)return e;let n=E(s);return n.length>0||!t?n:Mi(t,s)}function ve(s,e){return`No handler for task type '${s}' in domain ${e.join("; ")}`}k();k();var ln=St();function ot(s,e,t){let n=s.get(t.priority);n&&kt(n,t,ln);for(let i of t.targetDomains){let r=e.get(i);r&&r.push(t)}}function N(s,e,t){let n=s.get(t.priority);if(n){let i=n.findIndex(r=>r.id===t.id);i!==-1&&n.splice(i,1)}for(let i of t.targetDomains){let r=e.get(i);if(r){let a=r.findIndex(o=>o.id===t.id);a!==-1&&r.splice(a,1)}}}function be(s,e){let t=0;for(let n of["p0","p1","p2","p3"]){let i=s.get(n);if(i){if(n===e.priority){t+=i.findIndex(r=>r.id===e.id);break}t+=i.length}}return t}async function M(s){if(!(s.runningTaskCounter>=s.config.maxConcurrentTasks)){O.set(s.tasks,(O.get(s.tasks)??0)+1);try{do{Ce.delete(s.tasks);for(let e of["p0","p1","p2","p3"]){let t=s.taskQueue.get(e);if(!t||t.length===0)continue;let n=cn(s,t);for(;n;){N(s.taskQueue,s.domainQueues,n),s.runningTaskCounter++;let i;try{i=await Se(s,n)}catch(r){throw s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),r}if(!i.success&&(s.tasks.get(n.id)?.status??"queued")==="queued"&&await ke(s,n,void 0,i.error.message),s.runningTaskCounter>=s.config.maxConcurrentTasks)return;n=cn(s,t)}}}while(Ce.has(s.tasks)&&s.runningTaskCounter<s.config.maxConcurrentTasks)}finally{let e=(O.get(s.tasks)??1)-1;e>0?O.set(s.tasks,e):(O.delete(s.tasks),Ce.delete(s.tasks))}}}var O=new WeakMap,Ce=new WeakSet;async function V(s){if(s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),O.has(s.tasks)){Ce.add(s.tasks);return}M(s).catch(e=>{console.warn("[Queen] Queue drain after a released slot failed:",h(e))})}function cn(s,e){let t=e.shift();for(;t;){let n=s.tasks.get(t.id)?.status;if(n===void 0||n==="queued")return t;N(s.taskQueue,s.domainQueues,t),t=e.shift()}}async function ke(s,e,t,n){s.tasks.set(e.id,{taskId:e.id,task:e,status:"failed",assignedDomain:t,assignedAgents:[],retryCount:s.tasks.get(e.id)?.retryCount??0,error:n,completedAt:new Date}),s.tasksFailed++,s.auditLogger.logFail(e.id,void 0,n),await s.publishEvent("TaskFailed",{taskId:e.id,domain:t,error:n}),await V(s)}function un(s,e){let t=Array.from(s.values());return e&&(e.status&&(t=t.filter(n=>n.status===e.status)),e.domain&&(t=t.filter(n=>n.assignedDomain===e.domain)),e.priority&&(t=t.filter(n=>n.task.priority===e.priority)),e.type&&(t=t.filter(n=>n.task.type===e.type)),e.fromDate&&(t=t.filter(n=>n.task.createdAt>=e.fromDate)),e.toDate&&(t=t.filter(n=>n.task.createdAt<=e.toDate))),t}async function Se(s,e){let t=e.targetDomains.length>0?e.targetDomains:E(e.type);if(t.length===0)return f(new Error(`No domains configured for task type: ${e.type}`));let n,i=1/0;for(let r of t){let a=s.getDomainLoad(r);s.getDomainHealth(r)?.status!=="unhealthy"&&a<i&&(i=a,n=r)}return n?dn(s,e,n):f(new Error("No healthy domain available for task"))}async function dn(s,e,t){if(e.executionOwner!=="caller"&&s.domainPlugins){let c=j(s.domainPlugins,e.type,[t]);if(c.length>0)return Ii(s,e,t,ve(e.type,c))}let n;if(s.tinyDancerRouter){let c={p0:"critical",p1:"high",p2:"normal",p3:"low"},u={description:`${e.type}: ${JSON.stringify(e.payload).slice(0,200)}`,type:e.type,domain:t,priority:Object.hasOwn(c,e.priority)?c[e.priority]:"normal"};n=await s.tinyDancerRouter.route(u),s.config.enableMetrics&&console.log(`[Queen] TinyDancer routing: ${e.type} \u2192 tier=${n.tier}, model=${n.model}, cost=$${n.estimatedCost.toFixed(4)}`)}if(s.domainBreakerRegistry&&!s.domainBreakerRegistry.canExecuteInDomain(t))return f(new Error(`Domain '${t}' circuit breaker is open \u2014 too many recent failures`));if(s.domainTeamManager)try{if(!s.domainTeamManager.getDomainTeam(t)){let u=`${t}-lead`;s.domainTeamManager.createDomainTeam(t,u)}}catch(c){console.warn(`[Queen] Domain team setup for '${t}' failed (continuing):`,c)}let i=n?.tier||"task-worker",r=["task-execution",e.type,...n?[`model:${n.model}`]:[],...n?.triggerMultiModel?["advisor:triggerMultiModel"]:[]],a=await s.requestAgentSpawn(t,i,r,e.id);if(s.tasks.get(e.id)?.status==="cancelled")return a.success&&await s.agentCoordinator.stop(a.value),await V(s),y(e.id);let o=[];a.success&&o.push(a.value);let l={taskId:e.id,task:e,status:"running",assignedDomain:t,assignedAgents:o,startedAt:new Date,retryCount:0};s.tasks.set(e.id,l),s.domainLastActivity.set(t,new Date);for(let c of o)s.auditLogger.logAssign(e.id,c,t);if(await s.publishEvent("TaskAssigned",{taskId:e.id,domain:t,agentIds:o}),e.executionOwner==="caller")return y(e.id);if(s.domainPlugins){let c=s.domainPlugins.get(t);if(c?.executeTask&&c.canHandleTask?.(e.type)){let u={taskId:e.id,taskType:e.type,payload:e.payload,priority:e.priority,timeout:e.timeout,correlationId:e.correlationId},d;try{d=await c.executeTask(u,m=>Ri(s,m))}catch(m){d=f(Z(m))}if(!d.success){let m=H(s.tasks,e.id);return m.ignored?(m.settledNow&&await V(s),y(e.id)):s.tasks.get(e.id)?.status!=="running"?f(d.error):(s.tasks.set(e.id,{...l,status:"failed",error:d.error.message,completedAt:new Date}),s.tasksFailed++,s.auditLogger.logFail(e.id,o[0],d.error.message),await s.publishEvent("TaskFailed",{taskId:e.id,domain:t,error:d.error.message}),await V(s),f(d.error))}return y(e.id)}}return y(e.id)}async function Ii(s,e,t,n){let i=s.taskTraceContexts.get(e.id);return s.traceCollector&&i&&(s.traceCollector.failSpan(i.spanId,n),s.taskTraceContexts.delete(e.id)),await ke(s,e,t,n),y(e.id)}async function mn(s,e,t){let n=s.tasks.get(e.id)?.status;if(n!==void 0&&n!=="queued")return!1;s.runningTaskCounter++;let i;try{i=await dn(s,e,t)}catch(a){throw s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),a}!i.success&&(s.tasks.get(e.id)?.status??"queued")==="queued"&&await ke(s,e,t,i.error.message);let r=s.tasks.get(e.id);return r?.assignedDomain===t&&(r.status==="running"||r.status==="completed")}async function Ri(s,e){let t=s.tasks.get(e.taskId);if(!t){console.warn(`[Queen] Received completion for unknown task: ${e.taskId}`);return}let n=H(s.tasks,e.taskId);if(n.ignored){n.settledNow&&(s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),await M(s));return}let i={...t,status:e.success?"completed":"failed",completedAt:new Date,result:e.data,error:e.error};if(s.tasks.set(e.taskId,i),e.success?(s.tasksCompleted++,s.taskDurations.push(e.duration),s.auditLogger.logComplete(e.taskId,t.assignedAgents[0])):(s.tasksFailed++,s.auditLogger.logFail(e.taskId,t.assignedAgents[0],e.error||"Unknown error")),s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),s.coExecutionRepo&&t.assignedAgents.length>=2)try{s.coExecutionRepo.recordSwarmCoExecution(t.assignedAgents,t.assignedDomain||"unknown",e.success,t.task.type)}catch{}for(let r of t.assignedAgents)await s.agentCoordinator.stop(r);await s.publishEvent(e.success?"TaskCompleted":"TaskFailed",{taskId:e.taskId,domain:t.assignedDomain,result:e.data,error:e.error,duration:e.duration}),await M(s)}function _i(s,e){return E(e.type).includes(s)}function gn(s,e,t){return _i(e,t)?t.executionOwner==="caller"||!s?!0:j(s,t.type,[e]).length===0:!1}k();async function pn(s){let e=0,t=s.getIdleDomains(),n=s.getBusyDomains();if(t.length===0||n.length===0)return 0;n.sort((i,r)=>s.getDomainLoad(r)-s.getDomainLoad(i));for(let i of n){if(t.length===0)break;let r=s.domainQueues.get(i)||[],a=Math.min(r.length,s.config.workStealing.stealBatchSize);for(let o=0;o<a&&t.length>0&&s.availableSlots()>0;o++){let l=r.find(c=>s.canExecuteInDomain(t[0],c));if(l){let c=t.shift();if(s.removeFromQueues(l),!await s.assignTaskToDomain(l,c))continue;s.auditLogger.logSteal(l.id,i,c),e++,s.tasksStolen++,await s.publishEvent("TaskStolen",{taskId:l.id,fromDomain:i,toDomain:c})}}}return e}function ct(s,e){let t=0,n=10,i=setInterval(async()=>{try{await e(),t=0}catch(r){t++;let a=Math.min(1e3*Math.pow(2,t),3e4);if(console.warn(`[QueenCoordinator] Work-stealing failed (attempt ${t}), backing off ${a}ms`,h(r)),t>n){console.error(`[QueenCoordinator] Work-stealing exceeded ${n} consecutive failures, stopping interval`),clearInterval(i);return}await new Promise(o=>setTimeout(o,a))}},s.workStealing.checkInterval);return i}function lt(s){return typeof s.setMinCutBridge=="function"}function hn(s,e){for(let[t,n]of s)lt(n)&&(n.setMinCutBridge(e),console.log(`[QueenCoordinator] MinCut bridge injected into ${t}`))}async function fn(s,e,t){try{let n=await s.get("queen:state");if(n){for(let[i,r]of n.tasks)if(r.status==="queued"){if(r.task.executionOwner==="caller"){e.set(i,{...r,status:"failed",error:"Caller-owned task was interrupted before completion; submit a new request.",completedAt:new Date});continue}e.set(i,r),t(r.task)}}}catch(n){console.debug("[QueenCoordinator] State loading failed:",n instanceof Error?n.message:n)}}async function yn(s,e){let t=Array.from(e.entries()).filter(([,n])=>n.status==="queued");await s.set("queen:state",{tasks:t},{namespace:"queen-coordinator",persist:!0})}function Tn(s){return setInterval(async()=>{let e=s.getMetrics();if(await s.publishEvent("MetricsCollected",{metrics:e}),await s.memory.set(`queen:metrics:${Date.now()}`,e,{ttl:86400,namespace:"queen-coordinator"}),s.dynamicScaler)try{let t=s.getAverageTaskDuration(),n={queueDepth:s.getQueuedTaskCount(),activeAgents:s.getActiveAgentCount(),idleAgents:s.getIdleAgentCount(),avgTaskDurationMs:t,errorRate:s.getTasksReceived()>0?s.getTasksFailed()/s.getTasksReceived():0,throughput:e.uptime>0?s.getTasksCompleted()/(e.uptime/1e3):0,timestamp:Date.now()};s.dynamicScaler.recordMetrics(n);let i=s.dynamicScaler.evaluate();i&&i.action!=="maintain"&&(console.log(`[QueenCoordinator] Dynamic scaler: ${i.action} to ${i.targetAgents} agents \u2014 ${i.reason}`),s.dynamicScaler.execute(i).catch(r=>{console.warn("[QueenCoordinator] Dynamic scaling execution error:",r)}))}catch(t){console.warn("[QueenCoordinator] Dynamic scaler metrics error:",t)}},s.config.metricsInterval)}function ut(s,e,t=36e5){let n=Date.now(),i=0;for(let[a,o]of s)if(o.status==="completed"||o.status==="failed"||o.status==="cancelled"){let l=o.completedAt?.getTime()||o.startedAt?.getTime()||0;l>0&&n-l>t&&(s.delete(a),e.delete(a),i++)}let r=1e4;if(e.size>r){let a=e.size-r,o=e.keys();for(let l=0;l<a;l++){let c=o.next().value;c!==void 0&&e.delete(c)}console.log(`[QueenCoordinator] Evicted ${a} oldest trace contexts (max: ${r})`)}return i>0&&console.log(`[QueenCoordinator] Cleaned up ${i} old tasks (retention: ${t}ms)`),i}function vn(s,e){return s&&s.size>0?Array.from(s.keys()):[...e]}var g=gt.create("QueenCoordinator");tn(v);var dt=class{constructor(e,t,n,i,r,a,o,l={}){this.eventBus=e;this.agentCoordinator=t;this.memory=n;this.router=i;this.protocolExecutor=r;this.workflowExecutor=a;this.domainPlugins=o;this.config={...en,...l},this.auditLogger=Me({enableConsoleLog:this.config.enableMetrics,maxEntries:1e3,logPrefix:"[QUEEN]"}),["p0","p1","p2","p3"].forEach(c=>{this.taskQueue.set(c,[])}),this.config.enableRouting!==!1&&(this.tinyDancerRouter=new ee(this.config.routing)),v.forEach(c=>{this.domainQueues.set(c,[]),this.domainLastActivity.set(c,new Date)})}eventBus;agentCoordinator;memory;router;protocolExecutor;workflowExecutor;domainPlugins;config;tasks=new Map;taskQueue=new Map;domainQueues=new Map;domainLastActivity=new Map;initialized=!1;workStealingTimer=null;metricsTimer=null;cleanupTimer=null;startTime=new Date;eventSubscriptionIds=[];runningTaskCounter=0;tasksReceived=0;tasksCompleted=0;tasksFailed=0;tasksStolen=0;taskDurations=new ft(1e3);protocolsExecuted=0;workflowsExecuted=0;auditLogger;minCutBridge=null;tinyDancerRouter=null;domainBreakerRegistry=null;domainTeamManager=null;agentTeamsAdapter=null;tierSelector=null;taskCompletedHook=null;traceCollector=null;taskTraceContexts=new Map;hypothesisManager=null;federationMailbox=null;dynamicScaler=null;coExecutionRepo=null;dependencyGraph=null;availableMcpServers=[];async initialize(){if(!this.initialized){this.startTime=new Date,await this.router.initialize(),this.subscribeToEvents(),this.config.workStealing.enabled&&(this.workStealingTimer=ct(this.config,()=>this.triggerWorkStealing().then(()=>{}))),this.config.enableMetrics&&(this.metricsTimer=Tn(this.createMetricsContext())),this.cleanupTimer=setInterval(()=>{ut(this.tasks,this.taskTraceContexts,36e5)},3e5),this.cleanupTimer.unref(),await fn(this.memory,this.tasks,e=>this.enqueueTaskInternal(e)),this.minCutBridge=Et(this.eventBus,this.agentCoordinator,{autoUpdateFromEvents:!0,persistData:!0,includeInQueenHealth:!0,sharedGraph:vt()}),await this.minCutBridge.initialize(),this.domainPlugins&&hn(this.domainPlugins,this.minCutBridge);try{await _.initialize(),g.info("Governance adapter initialized")}catch(e){g.warn("Governance initialization failed (continuing)",{error:e})}this.initializeSubsystems();try{let{join:e}=await import("path"),t=e(process.cwd(),".claude","agents","v3");this.dependencyGraph=qt(t),this.availableMcpServers=Dt(process.cwd());let{getUnifiedMemory:n}=await import("./unified-memory-GI76TXFV.js"),i=n();await i.initialize(),this.coExecutionRepo=$t(),this.coExecutionRepo.initialize(i.getDatabase()),this.dependencyGraph.warnings.length>0&&g.warn(`Dependency graph: ${this.dependencyGraph.warnings.length} warning(s)`,{warnings:this.dependencyGraph.warnings.slice(0,5)}),g.info("Dependency intelligence initialized",{agents:this.dependencyGraph.nodes.size,mcpServers:this.availableMcpServers.length})}catch(e){g.warn("Dependency intelligence initialization failed (continuing)",{error:e})}await this.publishEvent("QueenInitialized",{timestamp:new Date,config:this.config,domains:v}),this.initialized=!0}}async dispose(){this.workStealingTimer&&(clearInterval(this.workStealingTimer),this.workStealingTimer=null),this.metricsTimer&&(clearInterval(this.metricsTimer),this.metricsTimer=null),this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null),this.minCutBridge&&(await this.minCutBridge.dispose(),this.minCutBridge=null),this.domainTeamManager&&(this.domainTeamManager.dispose(),this.domainTeamManager=null),this.agentTeamsAdapter&&(this.agentTeamsAdapter.shutdown(),this.agentTeamsAdapter=null),this.domainBreakerRegistry=null,this.tierSelector=null,this.traceCollector&&(this.traceCollector.dispose(),this.traceCollector=null),this.hypothesisManager&&(this.hypothesisManager.dispose(),this.hypothesisManager=null),this.federationMailbox&&(this.federationMailbox.dispose(),this.federationMailbox=null),this.dynamicScaler&&(this.dynamicScaler.dispose(),this.dynamicScaler=null),await yn(this.memory,this.tasks);for(let[e,t]of this.tasks)(t.status==="queued"||t.status==="running")&&await this.cancelTask(e);await this.publishEvent("QueenShutdown",{timestamp:new Date,metrics:this.getMetrics()});for(let e of this.eventSubscriptionIds)this.router.unsubscribe(e);this.eventSubscriptionIds=[],await this.router.dispose(),this.initialized=!1}validateTaskExecutable(e,t=[]){let n=at(e,t,this.domainPlugins);if(n.length===0)return f(new Error(`Unknown task type '${e}': no domain is configured for it and no loaded domain handles it. Pass a target domain.`));if(!this.domainPlugins)return y(void 0);let i=j(this.domainPlugins,e,n);return i.length===0?y(void 0):f(new Error(ve(e,i)))}async submitTask(e){if(!this.initialized)return f(new Error("Queen Coordinator not initialized"));let t=`task_${C()}`,n={...e,targetDomains:E(e.type).length>0?e.targetDomains:[...at(e.type,e.targetDomains,this.domainPlugins)],id:t,createdAt:new Date,timeout:e.timeout||this.config.defaultTaskTimeout},i={taskId:n.id,taskType:n.type,agentId:n.requester||`queen-task:${n.id}`,domain:n.targetDomains[0]||"test-generation",priority:n.priority,payload:n.payload};try{let r=await _.beforeTaskExecution(i);if(!r.allowed)return this.auditLogger.logFail(t,"governance",r.reason||"Governance check failed"),await this.publishEvent("TaskRejected",{taskId:t,reason:r.reason,escalate:r.escalate}),f(new Error(`Task blocked by governance: ${r.reason}`))}catch(r){g.warn("Governance check error (continuing)",{error:r})}this.runningTaskCounter++;try{if(this.runningTaskCounter>this.config.maxConcurrentTasks)return this.runningTaskCounter--,this.queueTask(n);this.auditLogger.logSubmit(t,{type:n.type,priority:n.priority}),this.selectFleetTier(n),this.startTaskTrace(n,t);let r=await Se(this.createTaskContext(),n);return r.success?(this.tasksReceived++,await this.publishEvent("TaskSubmitted",{taskId:t,task:n}),y(t)):(this.tasks.has(t)||(this.runningTaskCounter=Math.max(0,this.runningTaskCounter-1)),r)}catch(r){throw this.runningTaskCounter=Math.max(0,this.runningTaskCounter-1),r}}async cancelTask(e){let t=this.tasks.get(e);if(!t)return f(new Error(`Task not found: ${e}`));if(t.status==="cancelled")return y(void 0);if(t.status==="completed"||t.status==="failed")return f(new Error(`Task already finished: ${e}`));let n=t.status==="running"||t.status==="assigned";this.tasks.set(e,{...t,status:"cancelled",completedAt:new Date,cancellationResultPending:n}),N(this.taskQueue,this.domainQueues,t.task);for(let i of t.assignedAgents)await this.agentCoordinator.stop(i);return this.auditLogger.logCancel(e),await this.publishEvent("TaskCancelled",{taskId:e}),y(void 0)}getTaskStatus(e){return this.tasks.get(e)}listTasks(e){return un(this.tasks,e)}getDomainHealth(e){if(this.domainPlugins){let t=this.domainPlugins.get(e);if(t)return t.getHealth()}return on(this.agentCoordinator,e,this.domainLastActivity.get(e))}getDomainLoad(e){let t=this.domainQueues.get(e)||[],n=Array.from(this.tasks.values()).filter(i=>i.assignedDomain===e&&i.status==="running");return t.length+n.length}getIdleDomains(){let e=Date.now(),t=this.config.workStealing.idleThreshold;return v.filter(n=>{let i=this.domainLastActivity.get(n);return this.getDomainLoad(n)===0&&i&&e-i.getTime()>t})}getBusyDomains(){return v.filter(e=>this.getDomainLoad(e)>this.config.workStealing.loadThreshold)}getSpawnPlan(e){return this.dependencyGraph?zt(e,this.dependencyGraph):{phases:[e],warnings:[],unsatisfiedHardDeps:[]}}getDependencyGraph(){return this.dependencyGraph}enableWorkStealing(){this.workStealingTimer||(this.workStealingTimer=ct(this.config,()=>this.triggerWorkStealing().then(()=>{})))}disableWorkStealing(){this.workStealingTimer&&(clearInterval(this.workStealingTimer),this.workStealingTimer=null)}async triggerWorkStealing(){return pn(this.createWorkStealingContext())}listAllAgents(){return this.agentCoordinator.listAgents()}getAgentsByDomain(e){return this.agentCoordinator.listAgents({domain:e})}async requestAgentSpawn(e,t,n,i){if(!this.agentCoordinator.canSpawn())return f(new Error("Maximum concurrent agents reached (15)"));if(this.dependencyGraph&&this.availableMcpServers.length>0)try{for(let[,a]of this.dependencyGraph.nodes){let o=a.dependencies.mcpServers;if(!o||o.length===0)continue;let l=o.filter(c=>c.required&&!this.availableMcpServers.includes(c.name));if(l.length>0){g.warn(`Pre-spawn MCP advisory: ${a.agentName} needs ${l.map(c=>c.name).join(", ")}`,{agent:a.agentName,domain:e,missing:l.map(c=>c.name)});break}}}catch{}let r=await this.agentCoordinator.spawn({name:`${e}-${t}-${Date.now()}`,domain:e,type:t,capabilities:n});if(r.success){if(this.domainLastActivity.set(e,new Date),this.domainTeamManager&&typeof this.domainTeamManager.getDomainTeam=="function")try{if(this.domainTeamManager.getDomainTeam(e))this.domainTeamManager.addTeammate(e,r.value)||g.warn(`Agent ${r.value} could not join ${e} team (full)`);else try{this.domainTeamManager.createDomainTeam(e,r.value)}catch{this.domainTeamManager.addTeammate(e,r.value)||g.warn(`Agent ${r.value} could not join ${e} team (full or max teams reached)`)}}catch(a){g.warn(`Auto-team-wiring failed for ${r.value}`,{error:a})}await this.publishEvent("AgentSpawned",{agentId:r.value,domain:e,type:t,capabilities:n,...i?{taskId:i}:{}})}return r}getHealth(){let e=new Map,t=[],n=0,i=0,r=vn(this.domainPlugins,v);for(let u of r){let d=this.getDomainHealth(u);d&&(e.set(u,d),d.status==="unhealthy"?(n++,t.push({domain:u,severity:"high",message:`Domain ${u} is unhealthy`,timestamp:new Date})):d.status==="degraded"&&(i++,t.push({domain:u,severity:"medium",message:`Domain ${u} is degraded`,timestamp:new Date})))}let a=this.agentCoordinator.listAgents(),o=a.filter(u=>u.status==="running").length,l="healthy";n>0?l="unhealthy":i>r.length/2&&(l="degraded");let c={status:l,domainHealth:e,totalAgents:a.length,activeAgents:o,pendingTasks:this.getQueuedTaskCount(),runningTasks:this.getRunningTaskCount(),workStealingActive:this.workStealingTimer!==null,lastHealthCheck:new Date,issues:t};return this.minCutBridge?this.minCutBridge.extendQueenHealth(c):c}getMetrics(){let e=new Map;for(let o of v){let l=this.getDomainLoad(o);e.set(o,l)}let t=this.agentCoordinator.listAgents(),n=t.filter(o=>o.status==="running").length,i=t.length>0?n/t.length:0,r=this.taskDurations.average(),a={tasksReceived:this.tasksReceived,tasksCompleted:this.tasksCompleted,tasksFailed:this.tasksFailed,tasksStolen:this.tasksStolen,averageTaskDuration:r,domainUtilization:e,agentUtilization:i,protocolsExecuted:this.protocolsExecuted,workflowsExecuted:this.workflowsExecuted,uptime:Date.now()-this.startTime.getTime()};return this.minCutBridge?this.minCutBridge.extendQueenMetrics(a):a}getMinCutBridge(){return this.minCutBridge}injectMinCutBridgeIntoDomain(e){if(!this.minCutBridge)return g.warn("Cannot inject MinCut bridge: bridge not initialized"),!1;if(!this.domainPlugins)return g.warn("Cannot inject MinCut bridge: no domain plugins registered"),!1;let t=this.domainPlugins.get(e);return t?lt(t)?(t.setMinCutBridge(this.minCutBridge),g.info(`MinCut bridge injected into ${e} (late binding)`),!0):(g.warn(`Domain ${e} does not support MinCut integration`),!1):(g.warn(`Cannot inject MinCut bridge: domain ${e} not found`),!1)}getTinyDancerRouter(){return this.tinyDancerRouter}getDomainBreakerRegistry(){return this.domainBreakerRegistry}getDomainTeamManager(){return this.domainTeamManager}getAgentTeamsAdapter(){return this.agentTeamsAdapter}getTierSelector(){return this.tierSelector}getTraceCollector(){return this.traceCollector}getHypothesisManager(){return this.hypothesisManager}getFederationMailbox(){return this.federationMailbox}getDynamicScaler(){return this.dynamicScaler}connectReasoningBank(e){let t=new pe(e);this.taskCompletedHook=new ge({},t),g.info("ReasoningBank connected for pattern training")}async executeProtocol(e,t){if(!this.protocolExecutor)return f(new Error("Protocol executor not configured"));let n=await this.protocolExecutor.execute(e,t);return n.success?(this.protocolsExecuted++,await this.publishEvent("ProtocolExecuted",{protocolId:e,executionId:n.value.executionId}),y(n.value.executionId)):n}async executeWorkflow(e,t){if(!this.workflowExecutor)return f(new Error("Workflow executor not configured"));let n=await this.workflowExecutor.execute(e,t);return n.success?(this.workflowsExecuted++,await this.publishEvent("WorkflowExecuted",{workflowId:e,executionId:n.value.executionId}),y(n.value.executionId)):n}cleanupCompletedTasks(e=36e5){return ut(this.tasks,this.taskTraceContexts,e)}subscribeToEvents(){this.eventSubscriptionIds=sn(this.createEventHandlerContext(),v)}enqueueTaskInternal(e){ot(this.taskQueue,this.domainQueues,e)}async publishEvent(e,t){await this.eventBus.publish({id:C(),type:`Queen${e}`,timestamp:new Date,source:"queen-coordinator",payload:t})}queueTask(e){this.enqueueTaskInternal(e);let t={taskId:e.id,task:e,status:"queued",assignedAgents:[],retryCount:0};return this.tasks.set(e.id,t),this.tasksReceived++,this.auditLogger.logSubmit(e.id,{type:e.type,priority:e.priority}),this.auditLogger.logQueue(e.id,be(this.taskQueue,e)),this.publishEvent("TaskQueued",{taskId:e.id,task:e,position:be(this.taskQueue,e)}),y(e.id)}selectFleetTier(e){if(this.tierSelector)try{let t={trigger:e.payload?.trigger??"manual",changedFiles:e.payload?.changedFiles,affectedDomains:e.targetDomains,severity:e.priority==="p0"?"critical":e.priority==="p1"?"high":void 0,isHotfix:e.payload?.isHotfix},n=this.tierSelector.selectTier(t);return g.info(`Fleet tier: ${n.selectedTier} (${n.reason})`),n.selectedTier}catch(t){g.warn("Tier selection error (continuing)",{error:t});return}}startTaskTrace(e,t){if(this.traceCollector)try{let{context:n}=this.traceCollector.startTrace({operationName:e.type,agentId:e.requester||"queen",domain:e.targetDomains[0]||"test-generation",tags:{taskId:t,priority:e.priority}});if(this.taskTraceContexts.size>=1e4){let r=this.taskTraceContexts.keys().next().value;r!==void 0&&this.taskTraceContexts.delete(r)}this.taskTraceContexts.set(t,n)}catch(n){g.warn("Trace start error (continuing)",{error:n})}}getRunningTaskCount(){return Array.from(this.tasks.values()).filter(e=>e.status==="running"||e.status==="assigned").length}getQueuedTaskCount(){return Array.from(this.tasks.values()).filter(e=>e.status==="queued").length}initializeSubsystems(){if(this.config.enableCircuitBreakers!==!1)try{this.domainBreakerRegistry=Vt(),g.info("Domain circuit breaker registry initialized")}catch(e){g.warn("Circuit breaker initialization failed (continuing)",{error:e})}if(this.config.enableDomainTeams!==!1)try{this.agentTeamsAdapter=Be(),this.agentTeamsAdapter.initialize(),this.domainTeamManager=$e(this.agentTeamsAdapter),g.info("Domain team manager initialized")}catch(e){g.warn("Domain team manager initialization failed (continuing)",{error:e})}if(this.config.enableFleetTiers!==!1)try{this.tierSelector=Ge(),g.info("Fleet tier selector initialized")}catch(e){g.warn("Tier selector initialization failed (continuing)",{error:e})}try{this.traceCollector=Qe(),g.info("Trace collector initialized")}catch(e){g.warn("Trace collector initialization failed (continuing)",{error:e})}try{this.hypothesisManager=Ve(),this.federationMailbox=Ye(),this.dynamicScaler=Xe(),g.info("Phase 4 modules initialized (hypotheses, federation, scaling)")}catch(e){g.warn("Phase 4 initialization failed (continuing)",{error:e})}}createEventHandlerContext(){let e=this;return{config:e.config,tasks:e.tasks,domainLastActivity:e.domainLastActivity,auditLogger:e.auditLogger,router:e.router,agentCoordinator:e.agentCoordinator,get runningTaskCounter(){return e.runningTaskCounter},set runningTaskCounter(t){e.runningTaskCounter=t},get tasksCompleted(){return e.tasksCompleted},set tasksCompleted(t){e.tasksCompleted=t},get tasksFailed(){return e.tasksFailed},set tasksFailed(t){e.tasksFailed=t},taskDurations:e.taskDurations,get domainBreakerRegistry(){return e.domainBreakerRegistry},get traceCollector(){return e.traceCollector},taskTraceContexts:e.taskTraceContexts,get taskCompletedHook(){return e.taskCompletedHook},get hypothesisManager(){return e.hypothesisManager},processQueue:()=>M(e.createTaskContext()),enqueueTask:t=>e.enqueueTaskInternal(t)}}createTaskContext(){let e=this;return{config:e.config,tasks:e.tasks,taskQueue:e.taskQueue,domainQueues:e.domainQueues,domainLastActivity:e.domainLastActivity,auditLogger:e.auditLogger,agentCoordinator:e.agentCoordinator,domainPlugins:e.domainPlugins,get runningTaskCounter(){return e.runningTaskCounter},set runningTaskCounter(t){e.runningTaskCounter=t},get tasksReceived(){return e.tasksReceived},set tasksReceived(t){e.tasksReceived=t},get tasksCompleted(){return e.tasksCompleted},set tasksCompleted(t){e.tasksCompleted=t},get tasksFailed(){return e.tasksFailed},set tasksFailed(t){e.tasksFailed=t},taskDurations:e.taskDurations,get tinyDancerRouter(){return e.tinyDancerRouter},get domainBreakerRegistry(){return e.domainBreakerRegistry},get domainTeamManager(){return e.domainTeamManager},get tierSelector(){return e.tierSelector},get traceCollector(){return e.traceCollector},taskTraceContexts:e.taskTraceContexts,get coExecutionRepo(){return e.coExecutionRepo},requestAgentSpawn:(t,n,i,r)=>e.requestAgentSpawn(t,n,i,r),publishEvent:(t,n)=>e.publishEvent(t,n),getDomainLoad:t=>e.getDomainLoad(t),getDomainHealth:t=>e.getDomainHealth(t)}}createWorkStealingContext(){let e=this;return{config:e.config,domainQueues:e.domainQueues,auditLogger:e.auditLogger,get tasksStolen(){return e.tasksStolen},set tasksStolen(t){e.tasksStolen=t},getIdleDomains:()=>e.getIdleDomains(),getBusyDomains:()=>e.getBusyDomains(),getDomainLoad:t=>e.getDomainLoad(t),availableSlots:()=>e.config.maxConcurrentTasks-e.runningTaskCounter,canExecuteInDomain:(t,n)=>(e.tasks.get(n.id)?.status??"queued")==="queued"&&gn(e.domainPlugins,t,n),removeFromQueues:t=>N(e.taskQueue,e.domainQueues,t),assignTaskToDomain:(t,n)=>mn(e.createTaskContext(),t,n),publishEvent:(t,n)=>e.publishEvent(t,n)}}createMetricsContext(){let e=this;return{config:e.config,memory:e.memory,get dynamicScaler(){return e.dynamicScaler},getMetrics:()=>e.getMetrics(),publishEvent:(t,n)=>e.publishEvent(t,n),getQueuedTaskCount:()=>e.getQueuedTaskCount(),getActiveAgentCount:()=>e.agentCoordinator.listAgents().filter(t=>t.status==="running").length,getIdleAgentCount:()=>e.agentCoordinator.listAgents().filter(t=>t.status==="idle").length,getAverageTaskDuration:()=>e.taskDurations.average(),getTasksReceived:()=>e.tasksReceived,getTasksFailed:()=>e.tasksFailed,getTasksCompleted:()=>e.tasksCompleted}}};function Go(s,e,t,n,i,r){return new dt(s.eventBus,s.coordinator,s.memory,e,t,n,i,r)}export{Ti as a,q as b,dt as c,Go as d};
|