agentic-qe 3.15.12 → 3.15.13
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/skills/skills-manifest.json +1 -1
- package/CHANGELOG.md +118 -0
- package/assets/skills/skills-manifest.json +1 -1
- package/dist/cli/bundle.js +6 -6
- package/dist/cli/chunks/adapter-KCQDVYY2.js +2 -0
- package/dist/cli/chunks/{agent-booster-wasm-5VZCKTIJ.js → agent-booster-wasm-6RRQWMNE.js} +2 -2
- package/dist/cli/chunks/{agent-handler-K3C6CQCD.js → agent-handler-AOH6TV7W.js} +2 -2
- package/dist/cli/chunks/{agent-memory-branch-NVFQ25WS.js → agent-memory-branch-2P54SF5N.js} +2 -2
- package/dist/cli/chunks/aqe-learning-engine-SAQOHSGN.js +2 -0
- package/dist/cli/chunks/{arena-QGWIJADQ.js → arena-NSVFCAF5.js} +2 -2
- package/dist/cli/chunks/{arena-TSZVDSXS.js → arena-X6MOGQHA.js} +4 -4
- package/dist/cli/chunks/{audit-KIEE2SHJ.js → audit-27DJLQNM.js} +3 -3
- package/dist/cli/chunks/base-WCACU3FN.js +2 -0
- package/dist/cli/chunks/{better-sqlite3-BNB32NW3.js → better-sqlite3-BU5GXILS.js} +2 -2
- package/dist/cli/chunks/{brain-handler-MPC5SPYI.js → brain-handler-GTQNHHZS.js} +3 -3
- package/dist/cli/chunks/{branch-enumerator-LZ7UXKAY.js → branch-enumerator-5CLULOCU.js} +2 -2
- package/dist/cli/chunks/{browser-VDHAW4RK.js → browser-R4DMU3LN.js} +2 -2
- package/dist/cli/chunks/browser-workflow-G6IASEAP.js +2 -0
- package/dist/cli/chunks/{chunk-QUJJYTJH.js → chunk-2G7TVT6W.js} +2 -2
- package/dist/cli/chunks/{chunk-FAGKBOX2.js → chunk-32ZMWEP3.js} +2 -2
- package/dist/cli/chunks/{chunk-FNUFTWEO.js → chunk-3AN5TNGD.js} +3 -3
- package/dist/cli/chunks/{chunk-JOWUS2X5.js → chunk-3LJ7LQMV.js} +1 -1
- package/dist/cli/chunks/{chunk-O4QJMANM.js → chunk-3QZEGE67.js} +1 -1
- package/dist/cli/chunks/{chunk-ICKUINKD.js → chunk-3RZV5DGO.js} +2 -2
- package/dist/cli/chunks/{chunk-W4II6SIH.js → chunk-3Y2ROSCL.js} +2 -2
- package/dist/cli/chunks/{chunk-L7NGKANW.js → chunk-3Y7TJFHU.js} +2 -2
- package/dist/cli/chunks/{chunk-UUZZXHUF.js → chunk-3YNLWPBF.js} +2 -2
- package/dist/cli/chunks/{chunk-JR6CUKAI.js → chunk-42J34YG4.js} +2 -2
- package/dist/cli/chunks/{chunk-65TH6RPD.js → chunk-4OVC4RIL.js} +1 -1
- package/dist/cli/chunks/{chunk-DRCBRUGN.js → chunk-526QYFJU.js} +2 -2
- package/dist/cli/chunks/{chunk-MCPXNUDK.js → chunk-5FKWCZNF.js} +2 -2
- package/dist/cli/chunks/{chunk-NX4BCSOZ.js → chunk-5K26BEYB.js} +2 -2
- package/dist/cli/chunks/{chunk-MCPEC6OO.js → chunk-5MDERQH3.js} +1 -1
- package/dist/cli/chunks/{chunk-7JFDLL2F.js → chunk-5VMAV6T6.js} +1 -1
- package/dist/cli/chunks/{chunk-5TAEW5OV.js → chunk-5ZGM3RMH.js} +1 -1
- package/dist/cli/chunks/{chunk-SG2TX72G.js → chunk-6KATY3KS.js} +2 -2
- package/dist/cli/chunks/{chunk-KA5SHLMW.js → chunk-6Z7PRBSG.js} +2 -2
- package/dist/cli/chunks/{chunk-LFBA735S.js → chunk-72ASBE35.js} +3 -3
- package/dist/cli/chunks/{chunk-TOWOJGEI.js → chunk-756CGMEH.js} +1 -1
- package/dist/cli/chunks/{chunk-IVTQF55W.js → chunk-75RDHBAX.js} +3 -3
- package/dist/cli/chunks/{chunk-66PXR3NI.js → chunk-7CMTY45A.js} +2 -2
- package/dist/cli/chunks/{chunk-WLRU6ESI.js → chunk-7JUC2MVZ.js} +2 -2
- package/dist/cli/chunks/{chunk-SBHM5X2S.js → chunk-7NA7JXNB.js} +2 -2
- package/dist/cli/chunks/{chunk-HZBXJFGN.js → chunk-7PLIEBY7.js} +2 -2
- package/dist/cli/chunks/{chunk-2ASQRBK2.js → chunk-7YTGHGK4.js} +2 -2
- package/dist/cli/chunks/{chunk-SQVZ3TRU.js → chunk-A64JFBWI.js} +2 -2
- package/dist/cli/chunks/{chunk-2PPSS4JD.js → chunk-AL6FBH3E.js} +2 -2
- package/dist/cli/chunks/{chunk-3IU4LDZR.js → chunk-AQSVJNEH.js} +2 -2
- package/dist/cli/chunks/{chunk-C74M4WUI.js → chunk-ARJW4I2O.js} +2 -2
- package/dist/cli/chunks/{chunk-VF7FTD64.js → chunk-ASQYASNV.js} +1 -1
- package/dist/cli/chunks/{chunk-HLGFHHWV.js → chunk-BEGR4D6N.js} +2 -2
- package/dist/cli/chunks/{chunk-EN7GRVEQ.js → chunk-BK577VL7.js} +2 -2
- package/dist/cli/chunks/{chunk-KGA7VAI4.js → chunk-BLSLEVDI.js} +2 -2
- package/dist/cli/chunks/{chunk-HM3LSFTY.js → chunk-BTVEYBW2.js} +2 -2
- package/dist/cli/chunks/{chunk-J7Y7ZBIT.js → chunk-C6JTLKG7.js} +5 -5
- package/dist/cli/chunks/{chunk-PTBOLBM4.js → chunk-C7JM7CD3.js} +2 -2
- package/dist/cli/chunks/{chunk-IL7GQNNE.js → chunk-CCMKSHAT.js} +2 -2
- package/dist/cli/chunks/{chunk-23PQF7NN.js → chunk-CE7B5LU7.js} +1 -1
- package/dist/cli/chunks/{chunk-BMG2JLSQ.js → chunk-CM4LSLKR.js} +2 -2
- package/dist/cli/chunks/chunk-CRWPZT74.js +62 -0
- package/dist/cli/chunks/{chunk-4HWUECVD.js → chunk-CT6SAVXQ.js} +2 -2
- package/dist/cli/chunks/chunk-CV77DMDQ.js +2 -0
- package/dist/cli/chunks/{chunk-CU36D7TN.js → chunk-DFUASIKA.js} +2 -2
- package/dist/cli/chunks/{chunk-T4EN5VVK.js → chunk-DLD7RUZ4.js} +2 -2
- package/dist/cli/chunks/{chunk-IA55PFLG.js → chunk-DNDL7SOS.js} +2 -2
- package/dist/cli/chunks/{chunk-6QRI3JVE.js → chunk-DVGRPK7A.js} +2 -2
- package/dist/cli/chunks/{chunk-UREDS662.js → chunk-E56B6IDX.js} +2 -2
- package/dist/cli/chunks/{chunk-ZGROHCOW.js → chunk-E7CLYGS7.js} +1 -1
- package/dist/cli/chunks/{chunk-YNVEDFPQ.js → chunk-EXGMJFAT.js} +1 -1
- package/dist/cli/chunks/{chunk-JRYWLOBD.js → chunk-F3YS57NF.js} +2 -2
- package/dist/cli/chunks/{chunk-ZYOYR3UR.js → chunk-FZ76G4QJ.js} +1 -1
- package/dist/cli/chunks/{chunk-UIKQPO4Y.js → chunk-G2Q66Z23.js} +2 -2
- package/dist/cli/chunks/{chunk-5S4UIDFK.js → chunk-G6WDYBLQ.js} +1 -1
- package/dist/cli/chunks/{chunk-4SA7M34P.js → chunk-G77ERMUD.js} +1 -1
- package/dist/cli/chunks/{chunk-ADUAJIAU.js → chunk-GB6HBNH2.js} +2 -2
- package/dist/cli/chunks/{chunk-IETBWYHW.js → chunk-GHM6MQNK.js} +2 -2
- package/dist/cli/chunks/{chunk-QWG3SILX.js → chunk-GHY6Z6KO.js} +5 -5
- package/dist/cli/chunks/{chunk-AJEXPFAB.js → chunk-GII6UM3F.js} +1 -1
- package/dist/cli/chunks/{chunk-SDRJJUPO.js → chunk-GU5HNCWI.js} +1 -1
- package/dist/cli/chunks/{chunk-ULCW6IVQ.js → chunk-H4GG2NLO.js} +2 -2
- package/dist/cli/chunks/{chunk-7TA5MUPW.js → chunk-H4H2YSFH.js} +1 -1
- package/dist/cli/chunks/{chunk-5A66EGEW.js → chunk-HD7YIFOI.js} +2 -2
- package/dist/cli/chunks/{chunk-CDA5Z74H.js → chunk-HOAJUIBQ.js} +2 -2
- package/dist/cli/chunks/{chunk-4KUOYDY2.js → chunk-HQZGPJYG.js} +2 -2
- package/dist/cli/chunks/{chunk-G3AABG4Q.js → chunk-HZ5NXFXH.js} +2 -2
- package/dist/cli/chunks/{chunk-U6IXYQO4.js → chunk-I3C7JOXC.js} +2 -2
- package/dist/cli/chunks/{chunk-MAJXZYGK.js → chunk-IC3TQEOA.js} +1 -1
- package/dist/cli/chunks/{chunk-RYHG3I7J.js → chunk-IJUHSJ2U.js} +2 -2
- package/dist/cli/chunks/{chunk-DZGPUGUG.js → chunk-J2ZIFFM6.js} +2 -2
- package/dist/cli/chunks/{chunk-NA3F6FEO.js → chunk-JGZ722G3.js} +2 -2
- package/dist/cli/chunks/{chunk-PX5OPXY6.js → chunk-JQGMW45H.js} +1 -1
- package/dist/cli/chunks/{chunk-WGTEZT7G.js → chunk-JRRXCODW.js} +2 -2
- package/dist/cli/chunks/{chunk-4Y6OEBJZ.js → chunk-K3TLLJMX.js} +1 -1
- package/dist/cli/chunks/{chunk-RCOLPF3B.js → chunk-K4CZA77U.js} +2 -2
- package/dist/cli/chunks/{chunk-YIDAXOUX.js → chunk-K65CGKLD.js} +2 -2
- package/dist/cli/chunks/{chunk-5ADXFUMO.js → chunk-KADFXPPN.js} +2 -2
- package/dist/cli/chunks/{chunk-P5E26N2X.js → chunk-KB56CPU4.js} +2 -2
- package/dist/cli/chunks/{chunk-YLKIXEPP.js → chunk-KCW47QR5.js} +1 -1
- package/dist/cli/chunks/{chunk-SPC4RBLF.js → chunk-KDNJ4F3P.js} +2 -2
- package/dist/cli/chunks/{chunk-P7UFJ6DO.js → chunk-KDVZND5Q.js} +1 -1
- package/dist/cli/chunks/{chunk-TLRHAMX5.js → chunk-KUAKV3IW.js} +1 -1
- package/dist/cli/chunks/{chunk-ZROAMFX2.js → chunk-KV4T4MXK.js} +2 -2
- package/dist/cli/chunks/{chunk-UZED4YZ5.js → chunk-KWYH3FI4.js} +1 -1
- package/dist/cli/chunks/{chunk-33I2ZP6E.js → chunk-LFJALJOA.js} +2 -2
- package/dist/cli/chunks/{chunk-TXEUVUMO.js → chunk-LL7LDPXS.js} +1 -1
- package/dist/cli/chunks/{chunk-W5HQIYQU.js → chunk-LUZNKJE6.js} +3 -3
- package/dist/cli/chunks/{chunk-GKFV6CUD.js → chunk-LWR3FV3Y.js} +2 -2
- package/dist/cli/chunks/{chunk-TVA5GRIU.js → chunk-LZYQHVD4.js} +2 -2
- package/dist/cli/chunks/{chunk-2JYUA27M.js → chunk-M6AAGIG7.js} +1 -1
- package/dist/cli/chunks/{chunk-PT2NXS43.js → chunk-MAMQA43L.js} +1 -1
- package/dist/cli/chunks/chunk-MB46UBGY.js +3 -0
- package/dist/cli/chunks/{chunk-ZPVGX4DI.js → chunk-MFW5HSG4.js} +2 -2
- package/dist/cli/chunks/{chunk-47RMGDG4.js → chunk-MGZ5FJUW.js} +2 -2
- package/dist/cli/chunks/{chunk-G24SWTAX.js → chunk-MVVB7C2E.js} +410 -410
- package/dist/cli/chunks/{chunk-XZOYKB22.js → chunk-N4CYAKOX.js} +2 -2
- package/dist/cli/chunks/{chunk-QCPVUNN3.js → chunk-NT4DBXSX.js} +2 -2
- package/dist/cli/chunks/{chunk-3EWQN37E.js → chunk-NU3W5WFT.js} +2 -2
- package/dist/cli/chunks/{chunk-VZBC6DP7.js → chunk-NURIILUB.js} +1 -1
- package/dist/cli/chunks/{chunk-6E6HB4N4.js → chunk-NW7IBHJA.js} +4 -4
- package/dist/cli/chunks/{chunk-K3A3NWT3.js → chunk-NZ3GUMB2.js} +2 -2
- package/dist/cli/chunks/{chunk-GJKZ7UQO.js → chunk-NZD4DPSU.js} +2 -2
- package/dist/cli/chunks/{chunk-7QEUHNKO.js → chunk-O6FGXMHD.js} +1 -1
- package/dist/cli/chunks/{chunk-YVJEUX3I.js → chunk-OCAEXYFA.js} +2 -2
- package/dist/cli/chunks/{chunk-BOSMELJX.js → chunk-OFACHK5O.js} +2 -2
- package/dist/cli/chunks/{chunk-PGSJBXTD.js → chunk-P7A4NKTZ.js} +2 -2
- package/dist/cli/chunks/{chunk-HSA5IGGW.js → chunk-PB6J6HAA.js} +2 -2
- package/dist/cli/chunks/{chunk-TGMXUZZC.js → chunk-PHP5UBT4.js} +2 -2
- package/dist/cli/chunks/{chunk-NV74SICL.js → chunk-PIDQVU3L.js} +2 -2
- package/dist/cli/chunks/{chunk-TSOQ2QLT.js → chunk-PSFSPGUD.js} +2 -2
- package/dist/cli/chunks/{chunk-4A76VPU4.js → chunk-PT4FMJPQ.js} +2 -2
- package/dist/cli/chunks/{chunk-U7ZHDGXG.js → chunk-Q3UDLV5Z.js} +1 -1
- package/dist/cli/chunks/{chunk-BYRCB5JT.js → chunk-QDEJ4CI2.js} +2 -2
- package/dist/cli/chunks/{chunk-CA5UNWQF.js → chunk-QPNG5ZN2.js} +2 -2
- package/dist/cli/chunks/{chunk-W7H55PY4.js → chunk-R7SYRCRP.js} +1 -1
- package/dist/cli/chunks/{chunk-4LWMAAWK.js → chunk-RF7HWBHN.js} +2 -2
- package/dist/cli/chunks/{chunk-MMEALJ4D.js → chunk-RFNW2LGD.js} +2 -2
- package/dist/cli/chunks/{chunk-UCSK2RMI.js → chunk-S5AZCIZS.js} +2 -2
- package/dist/cli/chunks/{chunk-JW5PDJ5O.js → chunk-SE4VNN4I.js} +3 -3
- package/dist/cli/chunks/{chunk-URSTP3WI.js → chunk-SG3NX7QE.js} +2 -2
- package/dist/cli/chunks/{chunk-N7O3PF6Y.js → chunk-SSU73QAX.js} +2 -2
- package/dist/cli/chunks/{chunk-7DNR4KKR.js → chunk-SVLQRAMF.js} +1 -1
- package/dist/cli/chunks/{chunk-BC4T6SCV.js → chunk-SYV2V3PL.js} +4 -4
- package/dist/cli/chunks/{chunk-4CB3QPZM.js → chunk-T3PGQFDI.js} +2 -2
- package/dist/cli/chunks/{chunk-OHVYINGM.js → chunk-TCBBNUBP.js} +3 -3
- package/dist/cli/chunks/{chunk-YWWMNTBF.js → chunk-TOQWL2ZF.js} +2 -2
- package/dist/cli/chunks/{chunk-SITL5YZV.js → chunk-TSQC2KKZ.js} +2 -2
- package/dist/cli/chunks/{chunk-YUA6ZKKY.js → chunk-TWDW32W2.js} +2 -2
- package/dist/cli/chunks/{chunk-SUX5XB2Z.js → chunk-TWJTK4CC.js} +2 -2
- package/dist/cli/chunks/{chunk-32UTHIY5.js → chunk-U2FUXDDJ.js} +3 -3
- package/dist/cli/chunks/{chunk-ENGL7FIJ.js → chunk-UDQSYWVF.js} +1 -1
- package/dist/cli/chunks/{chunk-7OEFBWAG.js → chunk-UOC3O6RP.js} +2 -2
- package/dist/cli/chunks/chunk-UT2VZ33P.js +2 -0
- package/dist/cli/chunks/{chunk-MYF5CNGV.js → chunk-UTRV7T2N.js} +2 -2
- package/dist/cli/chunks/{chunk-KJDI5CHX.js → chunk-UXZSUMEA.js} +2 -2
- package/dist/cli/chunks/{chunk-DAUEK66C.js → chunk-VRHRBAEM.js} +1 -1
- package/dist/cli/chunks/{chunk-FZJCBSN4.js → chunk-VRVMIPTM.js} +2 -2
- package/dist/cli/chunks/{chunk-26672ISV.js → chunk-VTDFVFST.js} +2 -2
- package/dist/cli/chunks/{chunk-WTAUF6O4.js → chunk-VTOBUZL6.js} +2 -2
- package/dist/cli/chunks/{chunk-4PU5GTZW.js → chunk-VU5TBX2V.js} +2 -2
- package/dist/cli/chunks/{chunk-C3YOVASQ.js → chunk-W26B7ERY.js} +1 -1
- package/dist/cli/chunks/{chunk-CPIBIR3X.js → chunk-W2QWSQVE.js} +2 -2
- package/dist/cli/chunks/{chunk-L3PV7VXK.js → chunk-W3INMZZ6.js} +1 -1
- package/dist/cli/chunks/{chunk-5Z23ZMXZ.js → chunk-W3PPFHI5.js} +54 -54
- package/dist/cli/chunks/{chunk-NVRYELCY.js → chunk-WKGTGOYS.js} +3 -3
- package/dist/cli/chunks/{chunk-35NW676P.js → chunk-WNQS4WTS.js} +2 -2
- package/dist/cli/chunks/{chunk-O3IM4WRZ.js → chunk-WO274FRI.js} +2 -2
- package/dist/cli/chunks/{chunk-35MIUSXQ.js → chunk-WOCGL4QP.js} +2 -2
- package/dist/cli/chunks/{chunk-EF6OERRR.js → chunk-WQL7WCIZ.js} +1 -1
- package/dist/cli/chunks/{chunk-INZARYUD.js → chunk-X2Z7F4EU.js} +2 -2
- package/dist/cli/chunks/{chunk-2E2QO44T.js → chunk-X7N2JF2X.js} +2 -2
- package/dist/cli/chunks/{chunk-2IVE5AR3.js → chunk-XEAEYC6Y.js} +1 -1
- package/dist/cli/chunks/{chunk-IPA7K556.js → chunk-XNBOGCF3.js} +2 -2
- package/dist/cli/chunks/{chunk-A2JCRXTK.js → chunk-XPRVF4YE.js} +2 -2
- package/dist/cli/chunks/{chunk-VUR5THML.js → chunk-YBQH2VOP.js} +2 -2
- package/dist/cli/chunks/{chunk-A5Y7DAVQ.js → chunk-YQFLQE53.js} +2 -2
- package/dist/cli/chunks/{chunk-JGIJPDGD.js → chunk-YSZ5OE3Z.js} +2 -2
- package/dist/cli/chunks/{chunk-JNXK47OL.js → chunk-YXRASAPI.js} +2 -2
- package/dist/cli/chunks/{chunk-MYUMJ2ZI.js → chunk-YZEXYO4W.js} +1 -1
- package/dist/cli/chunks/{chunk-NNBQZR73.js → chunk-YZWBNBTW.js} +2 -2
- package/dist/cli/chunks/{chunk-WDEXOLK2.js → chunk-ZAKQLAHT.js} +1 -1
- package/dist/cli/chunks/{ci-BZNWW3I3.js → ci-ENOASTYB.js} +2 -2
- package/dist/cli/chunks/{ci-config-LOHNXOKV.js → ci-config-B26OXHQM.js} +2 -2
- package/dist/cli/chunks/{ci-output-LCOQBSJL.js → ci-output-JTCLLNOQ.js} +2 -2
- package/dist/cli/chunks/{circuit-breaker-7LRXTLFE.js → circuit-breaker-23JMFNM5.js} +2 -2
- package/dist/cli/chunks/{claude-flow-setup-HBU4VWC3.js → claude-flow-setup-ON6L462G.js} +2 -2
- package/dist/cli/chunks/client-TV3V2YZ5.js +2 -0
- package/dist/cli/chunks/{cline-installer-CO6MLH6X.js → cline-installer-OWQ4D2FQ.js} +2 -2
- package/dist/cli/chunks/{code-SIXBS6JM.js → code-2ZRL7SEU.js} +19 -18
- package/dist/cli/chunks/{code-index-extractor-GWJKZ2IQ.js → code-index-extractor-JXSQVM67.js} +2 -2
- package/dist/cli/chunks/{codex-installer-6NINVWXJ.js → codex-installer-7LXZYBSQ.js} +2 -2
- package/dist/cli/chunks/{completions-7VIX3GML.js → completions-C2LR623C.js} +2 -2
- package/dist/cli/chunks/{complexity-analyzer-FBQR6ZP2.js → complexity-analyzer-TGQLHCYJ.js} +2 -2
- package/dist/cli/chunks/{continuedev-installer-VA7RIXW5.js → continuedev-installer-RUGD24D2.js} +2 -2
- package/dist/cli/chunks/{copilot-installer-4QEBC4MU.js → copilot-installer-ZLFVLEJP.js} +2 -2
- package/dist/cli/chunks/core-handlers-PZT4OLWR.js +2 -0
- package/dist/cli/chunks/{cost-tracker-GRYKHPWL.js → cost-tracker-RT4QL745.js} +2 -2
- package/dist/cli/chunks/{coverage-USPMNKOU.js → coverage-NV3C4IMM.js} +3 -3
- package/dist/cli/chunks/cross-domain-router-QOFCZ7G4.js +2 -0
- package/dist/cli/chunks/{cursor-installer-ZXIPSZVH.js → cursor-installer-LJKLNFF6.js} +2 -2
- package/dist/cli/chunks/{daemon-D7F3RGI5.js → daemon-BMDXCQT5.js} +3 -3
- package/dist/cli/chunks/{daemon-N2VRHPSJ.js → daemon-FBH3IRYN.js} +4 -4
- package/dist/cli/chunks/{dag-attention-scheduler-NL6BA7BY.js → dag-attention-scheduler-JGDED55I.js} +2 -2
- package/dist/cli/chunks/{detect-XC2HCIIT.js → detect-SZIHIVCJ.js} +2 -2
- package/dist/cli/chunks/{dist-node-A3Y26MEI.js → dist-node-FV3KWXQ6.js} +2 -2
- package/dist/cli/chunks/{domain-handler-WV6SFXRB.js → domain-handler-GI5JWQOV.js} +2 -2
- package/dist/cli/chunks/{domain-plugins-KJIF6Z2B.js → domain-plugins-BUWY36TL.js} +2 -2
- package/dist/cli/chunks/domain-transfer-GCY7W5DA.js +2 -0
- package/dist/cli/chunks/dream-TRFBGDSQ.js +2 -0
- package/dist/cli/chunks/{embed-and-insert-pattern-PA3Y4KGO.js → embed-and-insert-pattern-GPRR3ZGD.js} +2 -2
- package/dist/cli/chunks/{eval-YGEZNUVE.js → eval-XPB3IGAP.js} +2 -2
- package/dist/cli/chunks/{experience-capture-middleware-D4T7NW6B.js → experience-capture-middleware-2E554UB3.js} +3 -3
- package/dist/cli/chunks/{fast-paths-6JYK7RYQ.js → fast-paths-ZSMWZPUC.js} +2 -2
- package/dist/cli/chunks/{feature-flags-RBH2GDSR.js → feature-flags-GIWVDVVC.js} +2 -2
- package/dist/cli/chunks/{feature-flags-DKXMDVPE.js → feature-flags-N7EOGE5P.js} +2 -2
- package/dist/cli/chunks/file-discovery-WCKGMSPZ.js +2 -0
- package/dist/cli/chunks/fleet-HCHDOUCX.js +44 -0
- package/dist/cli/chunks/{gnn-wrapper-MV54UC4C.js → gnn-wrapper-CZNCNXXZ.js} +2 -2
- package/dist/cli/chunks/{heartbeat-handler-7DKMVQQH.js → heartbeat-handler-6YUIF2YQ.js} +4 -4
- package/dist/cli/chunks/heartbeat-scheduler-P44A2OX3.js +2 -0
- package/dist/cli/chunks/hnsw-adapter-ZJQIQJKC.js +2 -0
- package/dist/cli/chunks/hnsw-index-HMG2GH3Z.js +2 -0
- package/dist/cli/chunks/{hnsw-legacy-bridge-6IWREDQC.js → hnsw-legacy-bridge-J3M3IK24.js} +2 -2
- package/dist/cli/chunks/{hnswlib-node-5BIESSCK.js → hnswlib-node-ULGTGDZW.js} +2 -2
- package/dist/cli/chunks/{hooks-3EETRM62.js → hooks-C4BUGYUQ.js} +10 -10
- package/dist/cli/chunks/hybrid-backend-B7M74PZG.js +2 -0
- package/dist/cli/chunks/{hypergraph-engine-RSWCB2D3.js → hypergraph-engine-WINGVMPG.js} +2 -2
- package/dist/cli/chunks/{hypergraph-handler-552LXKL3.js → hypergraph-handler-GADMWKAU.js} +3 -3
- package/dist/cli/chunks/impact-analyzer-PZYOVKQO.js +2 -0
- package/dist/cli/chunks/{init-guard-OTDBJ5HD.js → init-guard-K2T4QWAO.js} +2 -2
- package/dist/cli/chunks/{init-handler-3FK3TKEA.js → init-handler-PCZTDZYI.js} +6 -6
- package/dist/cli/chunks/init-wizard-TZDJQK3U.js +2 -0
- package/dist/cli/chunks/kernel-Y6RRIOKW.js +2 -0
- package/dist/cli/chunks/{kilocode-installer-KZ2O4LF3.js → kilocode-installer-XENXNEIU.js} +2 -2
- package/dist/cli/chunks/{kiro-installer-MLCCXRF7.js → kiro-installer-3PG2TJ67.js} +2 -2
- package/dist/cli/chunks/knowledge-graph-BVD5Z66M.js +2 -0
- package/dist/cli/chunks/{learning-QUCMBD77.js → learning-6KDH7FK4.js} +3 -3
- package/dist/cli/chunks/{llm-router-PDEV3UP2.js → llm-router-RKVDEWU2.js} +4 -4
- package/dist/cli/chunks/llm-router-service-KHCAMSUU.js +2 -0
- package/dist/cli/chunks/{load-XFVVLO7E.js → load-ITHC564X.js} +2 -2
- package/dist/cli/chunks/load-test-RUF7DZA5.js +2 -0
- package/dist/cli/chunks/{mcp-74G3CL2S.js → mcp-TCL5UW3N.js} +2 -2
- package/dist/cli/chunks/{memory-XIFM6JNX.js → memory-BKDAY2N2.js} +5 -5
- package/dist/cli/chunks/memory-backend-7ZLFOVGG.js +2 -0
- package/dist/cli/chunks/{memory-handlers-ZCKURV6S.js → memory-handlers-WN4FXFOA.js} +2 -2
- package/dist/cli/chunks/{multi-model-executor-7L4W3O2Q.js → multi-model-executor-VHAT7ZPF.js} +2 -2
- package/dist/cli/chunks/{opencode-installer-BPG422LF.js → opencode-installer-E3VM3EEY.js} +2 -2
- package/dist/cli/chunks/{orchestrator-OEAFLAEV.js → orchestrator-BMQ6X762.js} +5 -5
- package/dist/cli/chunks/pattern-null-store-RY6CVYHP.js +2 -0
- package/dist/cli/chunks/{pattern-usage-recorder-LOPNCULT.js → pattern-usage-recorder-GOOR2BV5.js} +2 -2
- package/dist/cli/chunks/{pipeline-VWTYUZB7.js → pipeline-5NSFQQIX.js} +2 -2
- package/dist/cli/chunks/{platform-WFJJ3X2E.js → platform-SQM34J5G.js} +2 -2
- package/dist/cli/chunks/{plugin-744TPUSG.js → plugin-UQJZRMZG.js} +2 -2
- package/dist/cli/chunks/{prime-radiant-advanced-wasm-BD5BLNDR.js → prime-radiant-advanced-wasm-WMDJOL4S.js} +2 -2
- package/dist/cli/chunks/project-root-IO5KRNGL.js +2 -0
- package/dist/cli/chunks/protocol-executor-U2CUDWDE.js +2 -0
- package/dist/cli/chunks/{protocol-handler-JIBILI74.js → protocol-handler-OBDCVY6X.js} +2 -2
- package/dist/cli/chunks/{prove-MNOL5FYW.js → prove-XDC7I4XT.js} +2 -2
- package/dist/cli/chunks/qe-reasoning-bank-DQSSX2IP.js +2 -0
- package/dist/cli/chunks/{quality-JEGBDGGX.js → quality-L4GQ6WX4.js} +2 -2
- package/dist/cli/chunks/{quality-gate-SYJ6ROMI.js → quality-gate-MJG66LKN.js} +3 -3
- package/dist/cli/chunks/queen-coordinator-6FN4BZIX.js +2 -0
- package/dist/cli/chunks/{real-embeddings-ZWXS5ZFV.js → real-embeddings-HW4G2LWL.js} +2 -2
- package/dist/cli/chunks/{ref-validation-RRHUFW2N.js → ref-validation-FC7JOJ2C.js} +2 -2
- package/dist/cli/chunks/{roocode-installer-XFO6JSVN.js → roocode-installer-KWS4CEIC.js} +2 -2
- package/dist/cli/chunks/router-YUO3I7RU.js +2 -0
- package/dist/cli/chunks/routing-feedback-36SLQGJE.js +2 -0
- package/dist/cli/chunks/{routing-handler-L2K3JASE.js → routing-handler-QF4WVB2S.js} +2 -2
- package/dist/cli/chunks/{ruvector-commands-A6CINHGM.js → ruvector-commands-2MTCOUK6.js} +2 -2
- package/dist/cli/chunks/rvf-dual-writer-FRYZH3WZ.js +2 -0
- package/dist/cli/chunks/rvf-migration-adapter-XXNITL5I.js +2 -0
- package/dist/cli/chunks/{rvf-migration-coordinator-T4RY7L53.js → rvf-migration-coordinator-BREJCXWN.js} +2 -2
- package/dist/cli/chunks/rvf-native-adapter-D2WWKJIV.js +2 -0
- package/dist/cli/chunks/{rvf-store-integrity-IR33TGQS.js → rvf-store-integrity-KKC6HOJD.js} +2 -2
- package/dist/cli/chunks/safe-db-4RRIGRXD.js +2 -0
- package/dist/cli/chunks/schedule-25RTO4DQ.js +2 -0
- package/dist/cli/chunks/scheduler-BPIOJZ5P.js +2 -0
- package/dist/cli/chunks/{security-Z5GDE2IH.js → security-OSAE7VAP.js} +3 -3
- package/dist/cli/chunks/{shared-rvf-adapter-SIZMEHPM.js → shared-rvf-adapter-COUOS665.js} +2 -2
- package/dist/cli/chunks/{shared-rvf-dual-writer-HLM65RDS.js → shared-rvf-dual-writer-YXMPZKQE.js} +2 -2
- package/dist/cli/chunks/sqlite-persistence-EDF47DDX.js +2 -0
- package/dist/cli/chunks/{standalone-memory-SKSZG7P5.js → standalone-memory-E6JBMOIL.js} +2 -2
- package/dist/cli/chunks/{status-handler-766YOOMJ.js → status-handler-AFTCIYIX.js} +2 -2
- package/dist/cli/chunks/{structural-health-M45FNOLT.js → structural-health-2FROCEI4.js} +2 -2
- package/dist/cli/chunks/{sync-B2U366I3.js → sync-VAYTOWDC.js} +2 -2
- package/dist/cli/chunks/{sync-6CJ24B5T.js → sync-YIQYOFGW.js} +2 -2
- package/dist/cli/chunks/task-handler-KVQHDEX3.js +62 -0
- package/dist/cli/chunks/task-handlers-MVVECQA6.js +9 -0
- package/dist/cli/chunks/{test-TODH7KRF.js → test-5JSVTOMY.js} +4 -4
- package/dist/cli/chunks/test-runner-process-LEPF2OSS.js +2 -0
- package/dist/cli/chunks/{test-scheduling-VMVMVRHT.js → test-scheduling-HBOHVLI3.js} +3 -3
- package/dist/cli/chunks/{token-bootstrap-XQW7BMCK.js → token-bootstrap-5VEPTPFA.js} +2 -2
- package/dist/cli/chunks/{token-usage-JCZEIRKO.js → token-usage-TBJHDLY6.js} +2 -2
- package/dist/cli/chunks/{transformers-U2ML3OHE.js → transformers-VAWYMHMZ.js} +2 -2
- package/dist/cli/chunks/tree-sitter-wasm-parser-TSZTCMFV.js +2 -0
- package/dist/cli/chunks/{types-GGEPCHP6.js → types-R5SDZU2E.js} +2 -2
- package/dist/cli/chunks/unified-memory-TLGSSLMI.js +2 -0
- package/dist/cli/chunks/unified-memory-hnsw-MSUR7ZOO.js +2 -0
- package/dist/cli/chunks/unified-persistence-VFFOTWK7.js +2 -0
- package/dist/cli/chunks/{upgrade-T5GRM7HS.js → upgrade-K5PIHXRB.js} +2 -2
- package/dist/cli/chunks/{validate-XMUJPLP3.js → validate-RPTS7RYJ.js} +2 -2
- package/dist/cli/chunks/{validate-swarm-KJLF7JEH.js → validate-swarm-B2ZL556X.js} +2 -2
- package/dist/cli/chunks/visual-security-6Q44XNLB.js +2 -0
- package/dist/cli/chunks/{web-tree-sitter-LOHVZ7G5.js → web-tree-sitter-K4DUJC32.js} +2 -2
- package/dist/cli/chunks/{windsurf-installer-33FBTXJU.js → windsurf-installer-OK2AJN35.js} +2 -2
- package/dist/cli/chunks/witness-chain-KDOMXDQX.js +2 -0
- package/dist/cli/chunks/witness-chain-N3OY2RMH.js +2 -0
- package/dist/cli/chunks/{witness-chain-repair-VWBO4NXE.js → witness-chain-repair-L6Y5RFXR.js} +2 -2
- package/dist/cli/chunks/{witness-chain-verifier-BHJ3ZAEK.js → witness-chain-verifier-N4CW7FZX.js} +2 -2
- package/dist/cli/chunks/{witness-key-manager-WNVPH2Z3.js → witness-key-manager-TDNPS3WD.js} +2 -2
- package/dist/cli/chunks/{workflow-6QR5MQTO.js → workflow-XRZA3YCY.js} +4 -4
- package/dist/cli/chunks/workflow-orchestrator-CVNNT2RJ.js +2 -0
- package/dist/cli/chunks/{wrappers-EHOL62TS.js → wrappers-5JIFWKN6.js} +2 -2
- package/dist/cli/commands/code.js +6 -0
- package/dist/cli/commands/fleet-run.d.ts +12 -0
- package/dist/cli/commands/fleet-run.js +175 -0
- package/dist/cli/commands/fleet.js +2 -117
- package/dist/cli/handlers/task-handler.d.ts +5 -0
- package/dist/cli/handlers/task-handler.js +20 -0
- package/dist/cli/utils/fleet-operation.d.ts +5 -2
- package/dist/cli/utils/fleet-operation.js +13 -2
- package/dist/cli/utils/fleet-result.d.ts +16 -2
- package/dist/cli/utils/fleet-result.js +26 -21
- package/dist/cli/utils/fleet-shard.d.ts +36 -0
- package/dist/cli/utils/fleet-shard.js +110 -0
- package/dist/coordination/handlers/code-intelligence-handlers.js +21 -1
- package/dist/coordination/handlers/handler-types.d.ts +2 -2
- package/dist/coordination/handlers/handler-utils.d.ts +6 -0
- package/dist/coordination/handlers/handler-utils.js +14 -4
- package/dist/coordination/handlers/misc-handlers.js +5 -2
- package/dist/coordination/handlers/quality-handlers.js +2 -2
- package/dist/coordination/handlers/security-handlers.js +12 -2
- package/dist/coordination/protocols/security-audit.js +11 -1
- package/dist/coordination/task-executor.js +7 -2
- package/dist/domains/code-intelligence/coordinator-gnn.d.ts +2 -16
- package/dist/domains/code-intelligence/coordinator-gnn.js +1 -62
- package/dist/domains/code-intelligence/coordinator.d.ts +12 -6
- package/dist/domains/code-intelligence/coordinator.js +24 -27
- package/dist/domains/code-intelligence/interfaces.d.ts +9 -0
- package/dist/domains/code-intelligence/services/semantic-analyzer.d.ts +43 -5
- package/dist/domains/code-intelligence/services/semantic-analyzer.js +134 -71
- package/dist/domains/coverage-analysis/collected-metrics.d.ts +10 -0
- package/dist/domains/coverage-analysis/collected-metrics.js +29 -0
- package/dist/domains/coverage-analysis/services/coverage-analyzer.js +11 -3
- package/dist/domains/coverage-analysis/services/coverage-parser.d.ts +2 -0
- package/dist/domains/coverage-analysis/services/coverage-parser.js +18 -2
- package/dist/domains/quality-assessment/coherence/gate-controller.js +16 -4
- package/dist/domains/quality-assessment/coherence/lambda-calculator.d.ts +8 -0
- package/dist/domains/quality-assessment/coherence/lambda-calculator.js +57 -14
- package/dist/domains/quality-assessment/coherence/types.d.ts +12 -7
- package/dist/domains/quality-assessment/coordinator-gate-evaluation.js +3 -1
- package/dist/domains/quality-assessment/coordinator-reports.d.ts +30 -10
- package/dist/domains/quality-assessment/coordinator-reports.js +93 -57
- package/dist/domains/quality-assessment/coordinator.d.ts +14 -40
- package/dist/domains/quality-assessment/coordinator.js +10 -4
- package/dist/domains/quality-assessment/interfaces.d.ts +2 -0
- package/dist/domains/quality-assessment/services/coherence-gate.js +15 -2
- package/dist/domains/quality-assessment/services/quality-gate.js +6 -4
- package/dist/domains/security-compliance/index.d.ts +1 -1
- package/dist/domains/security-compliance/interfaces.d.ts +46 -5
- package/dist/domains/security-compliance/services/scanners/dast-auth-testing.d.ts +3 -3
- package/dist/domains/security-compliance/services/scanners/dast-auth-testing.js +15 -14
- package/dist/domains/security-compliance/services/scanners/dast-helpers.d.ts +8 -9
- package/dist/domains/security-compliance/services/scanners/dast-helpers.js +19 -44
- package/dist/domains/security-compliance/services/scanners/dast-injection-testing.d.ts +3 -3
- package/dist/domains/security-compliance/services/scanners/dast-injection-testing.js +13 -9
- package/dist/domains/security-compliance/services/scanners/dast-requests.d.ts +54 -0
- package/dist/domains/security-compliance/services/scanners/dast-requests.js +125 -0
- package/dist/domains/security-compliance/services/scanners/dast-scanner.d.ts +5 -1
- package/dist/domains/security-compliance/services/scanners/dast-scanner.js +125 -155
- package/dist/domains/security-compliance/services/scanners/index.d.ts +1 -1
- package/dist/domains/security-compliance/services/scanners/index.js +1 -1
- package/dist/domains/security-compliance/services/scanners/scanner-types.d.ts +2 -2
- package/dist/domains/security-compliance/services/security-auditor-dast.js +183 -212
- package/dist/domains/security-compliance/services/security-auditor-reports.js +5 -1
- package/dist/domains/security-compliance/services/security-auditor.d.ts +11 -3
- package/dist/domains/security-compliance/services/security-auditor.js +106 -65
- package/dist/domains/test-execution/coordinator.d.ts +2 -1
- package/dist/domains/test-execution/coordinator.js +33 -27
- package/dist/domains/test-execution/interfaces.d.ts +5 -0
- package/dist/domains/test-execution/services/test-executor.d.ts +6 -0
- package/dist/domains/test-execution/services/test-executor.js +16 -4
- package/dist/domains/visual-accessibility/coordinator.js +34 -9
- package/dist/domains/visual-accessibility/interfaces.d.ts +27 -0
- package/dist/domains/visual-accessibility/plugin.js +5 -0
- package/dist/domains/visual-accessibility/services/accessibility-tester-heuristics.d.ts +13 -21
- package/dist/domains/visual-accessibility/services/accessibility-tester-heuristics.js +13 -297
- package/dist/domains/visual-accessibility/services/accessibility-tester.d.ts +13 -5
- package/dist/domains/visual-accessibility/services/accessibility-tester.js +96 -73
- package/dist/integrations/embeddings/index/HNSWIndex.js +8 -4
- package/dist/integrations/ruvector/transfer-coherence-stub.js +5 -10
- package/dist/mcp/bundle.js +480 -480
- package/dist/mcp/handlers/domain-handler-configs.d.ts +8 -0
- package/dist/mcp/handlers/domain-handler-configs.js +9 -2
- package/dist/mcp/handlers/handler-factory.js +3 -0
- package/dist/mcp/handlers/model-route-handlers.d.ts +107 -0
- package/dist/mcp/handlers/model-route-handlers.js +139 -0
- package/dist/mcp/handlers/orchestrate-routes.js +41 -3
- package/dist/mcp/handlers/task-handlers.d.ts +3 -251
- package/dist/mcp/handlers/task-handlers.js +6 -828
- package/dist/mcp/handlers/task-inference.d.ts +26 -0
- package/dist/mcp/handlers/task-inference.js +156 -0
- package/dist/mcp/handlers/task-learning-handlers.d.ts +92 -0
- package/dist/mcp/handlers/task-learning-handlers.js +230 -0
- package/dist/mcp/handlers/task-orchestrate-handler.d.ts +73 -0
- package/dist/mcp/handlers/task-orchestrate-handler.js +361 -0
- package/dist/mcp/protocol-server.js +12 -2
- package/dist/mcp/tools/code-intelligence/analyze.js +3 -6
- package/dist/mcp/tools/coverage-analysis/index.d.ts +4 -0
- package/dist/mcp/tools/coverage-analysis/index.js +8 -2
- package/dist/mcp/tools/visual-accessibility/index.d.ts +7 -0
- package/dist/mcp/tools/visual-accessibility/index.js +29 -13
- package/dist/shared/events/domain-events.d.ts +2 -0
- package/dist/shared/metrics/code-metrics.js +21 -3
- package/dist/shared/parsers/typescript-parser.d.ts +6 -0
- package/dist/shared/parsers/typescript-parser.js +13 -1
- package/package.json +1 -1
- package/dist/cli/chunks/adapter-HL7MOCQN.js +0 -2
- package/dist/cli/chunks/aqe-learning-engine-OZ2DXB4G.js +0 -2
- package/dist/cli/chunks/base-WIM7G3HC.js +0 -2
- package/dist/cli/chunks/browser-workflow-QRKCFVR3.js +0 -2
- package/dist/cli/chunks/chunk-QSGEBCDB.js +0 -62
- package/dist/cli/chunks/chunk-UJNGGFGX.js +0 -2
- package/dist/cli/chunks/chunk-VXVTFKRA.js +0 -2
- package/dist/cli/chunks/chunk-XCNSGSKV.js +0 -3
- package/dist/cli/chunks/client-4PNYDFYS.js +0 -2
- package/dist/cli/chunks/core-handlers-ODO6LUWQ.js +0 -2
- package/dist/cli/chunks/cross-domain-router-DT4MHJKK.js +0 -2
- package/dist/cli/chunks/domain-transfer-L3F6AES2.js +0 -2
- package/dist/cli/chunks/dream-QOB3JCOM.js +0 -2
- package/dist/cli/chunks/file-discovery-BN76S2PR.js +0 -2
- package/dist/cli/chunks/fleet-43YMXACN.js +0 -46
- package/dist/cli/chunks/heartbeat-scheduler-3NNP4WCP.js +0 -2
- package/dist/cli/chunks/hnsw-adapter-MZR7Y4WF.js +0 -2
- package/dist/cli/chunks/hnsw-index-HE4AX22U.js +0 -2
- package/dist/cli/chunks/hybrid-backend-IHUHB3Y2.js +0 -2
- package/dist/cli/chunks/impact-analyzer-FI6GI6PD.js +0 -2
- package/dist/cli/chunks/init-wizard-WLQKH5Y5.js +0 -2
- package/dist/cli/chunks/kernel-2WZOQEZS.js +0 -2
- package/dist/cli/chunks/knowledge-graph-G3LVKK6P.js +0 -2
- package/dist/cli/chunks/llm-router-service-MM75HKWJ.js +0 -2
- package/dist/cli/chunks/load-test-BEWEE44J.js +0 -2
- package/dist/cli/chunks/memory-backend-NYKBBKZR.js +0 -2
- package/dist/cli/chunks/pattern-null-store-QGPUIV6M.js +0 -2
- package/dist/cli/chunks/project-root-C7ELXZRK.js +0 -2
- package/dist/cli/chunks/protocol-executor-SUVE33BM.js +0 -2
- package/dist/cli/chunks/qe-reasoning-bank-YWZMMGJB.js +0 -2
- package/dist/cli/chunks/queen-coordinator-ZFAKXRN7.js +0 -2
- package/dist/cli/chunks/router-4FTAVYLJ.js +0 -2
- package/dist/cli/chunks/routing-feedback-IO2KOWMJ.js +0 -2
- package/dist/cli/chunks/rvf-dual-writer-KCIRNE7C.js +0 -2
- package/dist/cli/chunks/rvf-migration-adapter-MFC5WTJU.js +0 -2
- package/dist/cli/chunks/rvf-native-adapter-I3KWHE7X.js +0 -2
- package/dist/cli/chunks/safe-db-QXDZ6QY3.js +0 -2
- package/dist/cli/chunks/schedule-CZKD6RIY.js +0 -2
- package/dist/cli/chunks/scheduler-BLA3Q4CH.js +0 -2
- package/dist/cli/chunks/sqlite-persistence-XIUYDJC4.js +0 -2
- package/dist/cli/chunks/task-handler-P6IFLCKP.js +0 -62
- package/dist/cli/chunks/task-handlers-DPWMUKFC.js +0 -9
- package/dist/cli/chunks/test-runner-process-46IPK3GH.js +0 -2
- package/dist/cli/chunks/tree-sitter-wasm-parser-MOI2WWNJ.js +0 -2
- package/dist/cli/chunks/unified-memory-FL26RTV3.js +0 -2
- package/dist/cli/chunks/unified-memory-hnsw-E2BPTH3U.js +0 -2
- package/dist/cli/chunks/unified-persistence-5ZOUPKHF.js +0 -2
- package/dist/cli/chunks/visual-security-IJVPO5FA.js +0 -2
- package/dist/cli/chunks/witness-chain-5FAFCQKP.js +0 -2
- package/dist/cli/chunks/witness-chain-V2M32W5D.js +0 -2
- package/dist/cli/chunks/workflow-orchestrator-3JLF3IX7.js +0 -2
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{a as l,d as b}from"./chunk-
|
|
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.13");process.exit(0)}
|
|
2
|
+
import{a as l,d as b}from"./chunk-KV4T4MXK.js";import{a as d,b as g}from"./chunk-AQSVJNEH.js";import{a as f}from"./chunk-UT2VZ33P.js";import{c as p}from"./chunk-GB6HBNH2.js";f();g();b();var v={dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine",namespace:"coverage-hnsw",maxElements:1e5},S=p.create("coverage-analysis/hnsw-index"),u=class{constructor(e,t={}){this.memory=e;this.config={...v,...t},this.stats={vectorCount:0,searchOperations:0,insertOperations:0}}memory;config;stats;searchLatencies=[];backendType="ruvector-gnn";adapter=null;initialized=!1;metadataStore=new Map;async initialize(){if(this.initialized)return;let e=this.config.metric==="cosine"?"cosine":"euclidean",t=`coverage-${this.config.namespace}`;d.close(t),this.adapter=d.create(t,{dimensions:this.config.dimensions,M:this.config.M,efConstruction:this.config.efConstruction,efSearch:this.config.efSearch,metric:e}),S.info(`HnswAdapter initialized: dimension=${this.config.dimensions}, metric=${this.config.metric}, M=${this.config.M} (unified backend via ADR-071)`),this.initialized=!0}isNativeAvailable(){return this.initialized&&this.adapter!==null}getBackendType(){return this.backendType}isRuvectorAvailable(){return this.initialized&&this.adapter!==null&&this.adapter.isRuvectorAvailable()}async insert(e,t,a){this.initialized||await this.initialize(),t=this.validateVector(t),this.adapter.addByStringId(e,t),a&&this.metadataStore.set(e,a),this.stats.insertOperations++,this.stats.vectorCount=this.adapter.size()}async search(e,t){this.initialized||await this.initialize(),e=this.validateVector(e);let a=performance.now(),n=[];this.adapter.size()>0&&(n=this.adapter.searchByArray(e,t).map(({id:i,score:o})=>({key:i,score:o,distance:1-o,metadata:this.metadataStore.get(i)})));let s=performance.now()-a;return this.recordSearchLatency(s),this.stats.searchOperations++,n}async batchInsert(e){this.initialized||await this.initialize();let t=100;for(let a=0;a<e.length;a+=t){let n=e.slice(a,a+t);await Promise.all(n.map(r=>this.insert(r.key,r.vector,r.metadata)))}}async delete(e){if(!this.adapter)return!1;let t=this.adapter.removeByStringId(e);if(t){this.metadataStore.delete(e);let a=this.buildKey(e);await this.memory.delete(a),this.stats.vectorCount=this.adapter.size()}return t}async getStats(){return{nativeHNSW:this.initialized&&this.adapter!==null,backendType:this.backendType,vectorCount:this.stats.vectorCount,indexSizeBytes:this.stats.vectorCount*this.config.dimensions*4,avgSearchLatencyMs:this.calculateAvgLatency(),p95SearchLatencyMs:this.calculatePercentileLatency(95),p99SearchLatencyMs:this.calculatePercentileLatency(99),searchOperations:this.stats.searchOperations,insertOperations:this.stats.insertOperations}}async clear(){this.metadataStore.clear(),this.adapter&&this.adapter.clear(),this.stats.vectorCount=0,this.searchLatencies=[]}validateVector(e){if(e.length!==this.config.dimensions)return this.resizeVector(e,this.config.dimensions);for(let t=0;t<e.length;t++)if(!Number.isFinite(e[t]))throw new Error(`Invalid vector value at index ${t}: ${e[t]}`);return e}resizeVector(e,t){if(e.length===t)return e;if(e.length>t){let n=new Array(t).fill(0),r=e.length/t;for(let s=0;s<t;s++){let h=Math.floor(s*r),i=Math.floor((s+1)*r),o=0;for(let m=h;m<i;m++)o+=e[m];n[s]=o/(i-h)}return n}let a=new Array(t).fill(0);for(let n=0;n<e.length;n++)a[n]=e[n];return a}buildKey(e){return`${this.config.namespace}:${e}`}recordSearchLatency(e){this.searchLatencies.push(e);let t=1e3;this.searchLatencies.length>t&&(this.searchLatencies=this.searchLatencies.slice(-t))}calculateAvgLatency(){return this.searchLatencies.length===0?0:this.searchLatencies.reduce((t,a)=>t+a,0)/this.searchLatencies.length}calculatePercentileLatency(e){if(this.searchLatencies.length===0)return 0;let t=[...this.searchLatencies].sort((n,r)=>n-r),a=Math.ceil(e/100*t.length)-1;return t[Math.max(0,a)]}setEfSearch(e){this.config.efSearch=e}};function C(c,e){return new u(c,e)}async function H(c,e=1e4,t=1e3){let n=performance.now();for(let i=0;i<e;i++){let o=Array.from({length:384},()=>l());await c.insert(`bench-${i}`,o)}let r=performance.now()-n,s=performance.now();for(let i=0;i<t;i++){let o=Array.from({length:384},()=>l());await c.search(o,10)}let h=performance.now()-s;return{insertTimeMs:r,searchTimeMs:h,avgSearchLatencyMs:h/t,isNative:c.isNativeAvailable(),backendType:c.getBackendType()}}export{v as a,u as b,C as c,H as d};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{a as p}from"./chunk-
|
|
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.13");process.exit(0)}
|
|
2
|
+
import{a as p}from"./chunk-EXGMJFAT.js";import{j as m,n as E}from"./chunk-P7A4NKTZ.js";import{v as T}from"./chunk-3Y7TJFHU.js";import{c as y}from"./chunk-J2ZIFFM6.js";import k from"node:path";async function V(e){if(e.checklist.requirements.length===0)throw new Error("RequirementChecklist must have a non-empty, constant denominator (ADR-117).");if(!(e.oracle!=null&&e.oracle.baselinePassed===!0&&e.oracle.passed===!0)){let s=e.oracle==null?"oracle did not run":e.oracle.baselinePassed!==!0?"tests did not execute against the reference implementation":"mutation score below threshold";return{verdict:"fail",mechanical:"fail",specCoverage:null,unmet:[],attempts:0,reason:`mechanical gate failed: ${s}`}}if(!await e.judge.preflight())return{verdict:"inconclusive",mechanical:"pass",specCoverage:null,unmet:[],attempts:0,reason:"judge preflight failed: judge tooling did not run \u2014 refusing to report success"};let r=[],n=null,a=[],o=0;for(let s=0;s<2;s++){o++;let u=await e.judge.grade(e.artifact,e.checklist);if(u.ran&&(r.push(u),(n==null||u.coverage>n)&&(n=u.coverage,a=u.unmet),u.coverage>=1))return{verdict:"pass",mechanical:"pass",specCoverage:u.coverage,unmet:[],attempts:o,reason:`spec gate passed at coverage ${u.coverage.toFixed(3)} on attempt ${o}`}}return r.length>=2?{verdict:"fail",mechanical:"pass",specCoverage:n,unmet:a,attempts:o,reason:`spec gate failed: ${r.length} real opinions, best coverage ${(n??0).toFixed(3)} < 1 (${a.length} unmet)`}:{verdict:"inconclusive",mechanical:"pass",specCoverage:n,unmet:a,attempts:o,reason:`spec gate inconclusive: only ${r.length} real opinion(s) obtainable (need 2 to fail) \u2014 retry later, record neither pass nor fail`}}T();import{createHash as R}from"node:crypto";function I(e){let{manifestHash:t,...i}=e;return`sha256:${R("sha256").update(h(i)).digest("hex")}`}function b(e){return`sha256:${R("sha256").update(e).digest("hex")}`}function x(e,t={}){q(e);let i=I(e);if(e.manifestHash!==i)throw new Error(`Verification reach manifestHash mismatch: expected ${i}`);let r=t.now??new Date,n=r.toISOString(),a=e.expiresAt!=null&&r.getTime()>l(e.expiresAt,"expiresAt"),o=e.risks.map(s=>O(s,e,a,r.getTime()));return{manifestId:e.id,manifestHash:e.manifestHash,systemUnderTest:e.systemUnderTest,artifact:structuredClone(e.artifact),coverageVerdict:P(o.map(s=>s.verdict)),risks:o,evaluatedAt:n}}function O(e,t,i,r){let n=new Set,a=new Set,o=new Set,s=new Set,u=new Set;for(let c of e.checks){for(let v of c.limitations)u.add(v);if(S(c,t,i,r)){if(c.reach==="partial"){a.add(c.checkId);continue}if(c.reach==="direct"&&e.requiredObservations.includes(c.channel)&&c.oracleRef===e.requiredOracle){if(c.executionStatus==="failed"){o.add(c.checkId);continue}c.executionStatus==="passed"&&(n.add(c.checkId),s.add(c.channel))}}}let d=e.requiredObservations.filter(c=>!s.has(c)),f=o.size>0?"fail":d.length===0?"pass":e.dispositionWhenUncovered;return{riskId:e.riskId,failureMode:e.failureMode,severity:e.severity,verdict:f,directCheckIds:[...n],partialCheckIds:[...a],failedCheckIds:[...o],uncoveredObservations:d,limitations:[...u],reason:j(f,o,d,i)}}function S(e,t,i,r){if(i||!$(e.target,t.artifact)||e.evidenceClass!=="EXECUTED"||e.executionStatus==="not-run"||e.executionStatus==="unavailable"||!e.observedAt)return!1;let n=l(e.observedAt,`check ${e.checkId} observedAt`),a=l(t.generatedAt,"generatedAt");return!(n<a||n>r||t.expiresAt&&n>l(t.expiresAt,"expiresAt"))}function $(e,t){return e.revision===t.revision&&e.digest===t.digest&&e.environment===t.environment}function P(e){return e.some(t=>t==="fail")?"fail":e.some(t=>t==="human-review")?"human-review":e.some(t=>t==="inconclusive")?"inconclusive":"pass"}function j(e,t,i,r){return r?`verification manifest expired; uncovered: ${i.join(", ")}`:t.size>0?`direct check failed: ${[...t].join(", ")}`:e==="pass"?"all required observation channels have direct executed reach":`required reach is uncovered (${i.join(", ")}); disposition: ${e}`}function q(e){if(!e.id||!e.systemUnderTest)throw new Error("Verification reach manifest requires id and systemUnderTest");if(!e.artifact.revision||!e.artifact.digest||!e.artifact.environment)throw new Error("Verification reach manifest artifact requires revision, digest, and environment");if(l(e.generatedAt,"generatedAt"),e.expiresAt&&l(e.expiresAt,"expiresAt"),e.risks.length===0)throw new Error("Verification reach manifest requires at least one failure mode");let t=new Set;for(let i of e.risks){if(t.has(i.riskId))throw new Error(`Duplicate riskId: ${i.riskId}`);if(t.add(i.riskId),!i.riskId||!i.failureMode||!i.requiredOracle)throw new Error("Each failure mode requires riskId, failureMode, and requiredOracle");if(i.requiredObservations.length===0)throw new Error(`Failure mode ${i.riskId} requires at least one observation channel`)}}function l(e,t){let i=Date.parse(e);if(!Number.isFinite(i))throw new Error(`Invalid ${t} timestamp: ${e}`);return i}function h(e){return Array.isArray(e)?`[${e.map(h).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).filter(([,i])=>i!==void 0).sort(([i],[r])=>i<r?-1:i>r?1:0).map(([i,r])=>`${JSON.stringify(i)}:${h(r)}`).join(",")}}`:JSON.stringify(e)}var U="verification/anchors/qe-anchor-v1.json";async function te(e){let t=J(e.checklistId,e.anchorPath,e.anchor);if(e.verificationManifest&&e.verificationManifest.artifact.digest!==b(e.artifact))throw new Error("Verification reach manifest artifact digest does not match the judged artifact");let i=e.verificationManifest?{kind:"verified",...x(e.verificationManifest)}:{kind:"legacy-unknown",coverageVerdict:"inconclusive",reason:"legacy quality-gate request has no verification reach manifest"},r=i.coverageVerdict,n=await V({oracle:e.oracleResult,artifact:e.artifact,checklist:t,judge:e.judge});return{...n,qualityVerdict:n.verdict,coverageVerdict:r,verdict:F(n.verdict,r),verification:i}}function F(e,t){return e==="fail"||t==="fail"?"fail":e==="pass"&&t==="pass"?"pass":"inconclusive"}function J(e,t,i){let r=C(t),n=i??p(r),a=n.items.find(o=>o.id===e);if(!a){let o=n.items.map(s=>s.id).join(", ");throw new Error(`Unknown checklist id "${e}" in anchor ${r}. Available: ${o}`)}return{id:a.id,requirements:a.requirements}}function ie(e){return p(C(e)).items.map(i=>i.id)}function C(e){if(e&&k.isAbsolute(e))return e;let t=y();return k.resolve(t,e??U)}E();var D=6e4,Q=15e3;function N(e){let t=e.timeoutMs??D,i=e.logger??(()=>{}),r=e.model??"frontier",n=e.ping??(async()=>{let a=await w(e.complete("Reply with exactly: OK"),Math.min(Q,t),"judge preflight ping");return typeof a=="string"&&a.trim().length>0});return{async preflight(){try{let a=await n();return a||i(`frontier-judge preflight: provider (${r}) returned empty \u2014 not ready`),a}catch(a){return i(`frontier-judge preflight failed (${r}): ${A(a)}`),!1}},async grade(a,o){let s=o.requirements.length;try{let u=H(a,o),d=await w(e.complete(u),t,"judge grade"),f=G(d,s);if(f==null)return i(`frontier-judge grade: could not parse response for ${o.id}`),{ran:!1,coverage:0,unmet:[]};let c=[...f].sort((g,M)=>g-M).map(g=>o.requirements[g]);return{ran:!0,coverage:(s-c.length)/s,unmet:c}}catch(u){return i(`frontier-judge grade failed for ${o.id} (${r}): ${A(u)}`),{ran:!1,coverage:0,unmet:[]}}}}}function _(e,t={}){let i=t.model??m;return async r=>(await e.chat({messages:[{role:"user",content:r}],model:i,strictModel:!0,preferredProvider:t.preferredProvider,temperature:t.temperature??0,maxTokens:t.maxTokens??1024,timeoutMs:t.timeoutMs,skipCache:!0})).content??""}function ae(e,t={}){let i=t.model??m;return N({complete:_(e,{...t,model:i}),model:i,timeoutMs:t.timeoutMs,logger:t.logger})}function oe(e){return{preflight:()=>!1,grade:()=>({ran:!1,coverage:0,unmet:[]})}}function H(e,t){let i=t.requirements.map((r,n)=>`${n+1}. ${r}`).join(`
|
|
3
3
|
`);return["You are a rigorous, frontier-tier quality oracle grading a software artifact","against a FIXED requirement checklist. Judge only what the artifact actually","verifies \u2014 do not give credit for requirements it merely mentions or leaves",'implicit. A requirement is "met" only if the artifact demonstrably covers it.',"",`Checklist id: ${t.id}`,"Requirements (the denominator is fixed \u2014 grade ALL of them):",i,"","--- ARTIFACT UNDER JUDGEMENT ---",e,"--- END ARTIFACT ---","","Return ONLY a single JSON object, no prose, no markdown fences, of the form:",'{"unmet": [<numbers of requirements NOT met>]}','Use the requirement numbers above. If every requirement is met, return {"unmet": []}.'].join(`
|
|
4
4
|
`)}function G(e,t){let i=L(e);if(i==null||!Array.isArray(i.unmet))return null;let r=i.unmet,n=new Set;for(let a of r){let o=typeof a=="number"?a:typeof a=="string"?Number(a.trim()):NaN;if(!Number.isInteger(o))continue;let s=o-1;s>=0&&s<t&&n.add(s)}return r.length>0&&n.size===0?null:n}function L(e){if(typeof e!="string")return null;let t=e.indexOf("{");if(t===-1)return null;let i=0,r=!1,n=!1;for(let a=t;a<e.length;a++){let o=e[a];if(r){n?n=!1:o==="\\"?n=!0:o==='"'&&(r=!1);continue}if(o==='"')r=!0;else if(o==="{")i++;else if(o==="}"&&(i--,i===0))try{return JSON.parse(e.slice(t,a+1))}catch{return null}}return null}function w(e,t,i){return new Promise((r,n)=>{let a=setTimeout(()=>n(new Error(`${i} timed out after ${t}ms`)),t);e.then(o=>{clearTimeout(a),r(o)},o=>{clearTimeout(a),n(o)})})}function A(e){return e instanceof Error?e.message:String(e)}export{te as a,ie as b,ae as c,oe as d};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{a as h,b as y}from"./chunk-
|
|
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.13");process.exit(0)}
|
|
2
|
+
import{a as h,b as y}from"./chunk-LFJALJOA.js";import{b as p}from"./chunk-6Z7PRBSG.js";import{f as g,k as v,l as f,m as b,o as c}from"./chunk-K65CGKLD.js";import k from"chalk";var C=3,D="instrumented-report",R="static-estimation";async function T(e,r=a=>console.log(a)){let a=await v(e);if(a.status==="target-missing")return{kind:"no-data",reason:"target-missing",message:c("target-missing",e,null)};if(a.status==="evaluated"){let{evaluation:n,projectRoot:t}=a;if(n.status==="measured"){let{files:l,evidence:o}=n;return{kind:"data",data:{files:l,summary:h(l),instrumented:!0,...o.unmeasuredFiles.length>0?{unmeasuredFiles:o.unmeasuredFiles}:{}},projectRoot:t,evidence:o}}return{kind:"no-data",reason:n.reason,message:c(n.reason,e,t)}}let s=p(a.target,{includeTests:!1});return s.length===0?{kind:"no-sources"}:(r(k.gray(` Analyzing ${s.length} files...
|
|
3
3
|
`)),{kind:"data",data:y(s,a.projectRoot),projectRoot:a.projectRoot})}function x(e){return{branch:e.files.some(r=>r.branches.total>0),function:e.files.some(r=>r.functions.total>0),statement:e.files.some(r=>r.statements.total>0)}}var N=e=>e==="target-missing"||e==="unreadable-report";function w(){return"UNMEASURED: no coverage report exists for this project, so these figures are a STATIC ESTIMATE derived from source shape \u2014 not measured coverage. No threshold verdict is given and nothing is stored as evidence. Run your tests with coverage first (e.g. `npm test -- --coverage`) and re-run."}async function M(e,r,a,s){let n=await T(r,s);if(n.kind==="no-sources")return n;if(n.kind==="no-data")return N(n.reason)?{kind:"error",reason:n.reason,message:n.message}:{kind:"unmeasured",reason:n.reason,message:n.message};let t=n.data,l=t.instrumented,o=await e.analyze({coverageData:t,threshold:a,includeFileDetails:!0,measured:l,...n.projectRoot?{projectRoot:n.projectRoot}:{}});if(!o.success||!o.value)return{kind:"analysis-failed",message:o.error?.message||"Coverage analysis failed"};let i=o.value;if(!l)return{kind:"estimate",data:t,summary:{...i.summary},message:w()};let u=x(t),m=f(i.summary,a,u),d=g(n.evidence,n.projectRoot??r),E={...m,meetsThreshold:m.meetsThreshold&&d.length===0};return{kind:"measured",data:t,collected:u,verdict:E,insufficientEvidence:d,...n.evidence?{evidence:n.evidence}:{},summary:{...i.summary,branch:u.branch?i.summary.branch:null,function:u.function?i.summary.function:null,statement:u.statement?i.summary.statement:null},recommendations:b(i.recommendations??[],m,a,u)}}function z(e,r){switch(e.kind){case"measured":{if(e.insufficientEvidence.length>0)return C;let{overall:a,meetsThreshold:s}=e.verdict;return s?a<r+5?2:0:1}case"estimate":case"unmeasured":return C;case"no-sources":return 0;default:return 1}}function O(e,r,a){let s={line:null,branch:null,function:null,statement:null};switch(e.kind){case"measured":return{summary:e.summary,meetsThreshold:e.verdict.meetsThreshold,threshold:r,recommendations:e.recommendations,measured:!0,estimated:!1,coverageMethod:D,branchDataCollected:e.collected.branch,functionDataCollected:e.collected.function,statementDataCollected:e.collected.statement,...e.data.unmeasuredFiles?.length?{unmeasuredFiles:e.data.unmeasuredFiles}:{},...e.evidence?{evidenceStatus:e.evidence.status}:{},...e.evidence?.stale?{staleReport:e.evidence.stale}:{},...e.insufficientEvidence.length>0?{warning:`INSUFFICIENT EVIDENCE: ${e.insufficientEvidence.join("; ")}`}:{}};case"estimate":return{summary:e.summary,meetsThreshold:null,threshold:r,measured:!1,estimated:!0,unmeasured:!0,coverageMethod:R,reason:"no-coverage-report",target:a,warning:e.message};case"unmeasured":case"error":return{summary:s,meetsThreshold:null,threshold:r,measured:!1,unmeasured:e.kind==="unmeasured",reason:e.reason,target:a,warning:e.message};case"analysis-failed":return{summary:s,meetsThreshold:null,threshold:r,measured:!1,target:a,error:e.message};case"no-sources":return{summary:s,meetsThreshold:null,threshold:r,measured:!1,target:a,warning:"No source files found"}}}export{C as a,T as b,M as c,z as d,O as e};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
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.13");process.exit(0)}
|
|
2
2
|
var i=["qe-pentest-validator","qe-security-auditor","qe-security-scanner","qe-security-reviewer"],s="claude-sonnet-4-6",a=`anthropic/${s.replace("4-6","4.6")}`,u=s,p=new Set(["opus","fable"]),l=/claude-(opus|fable)-(\d+)(?:[-.](\d{1,2})(?!\d))?/,o={major:4,minor:7};function E(e){let r=e.trim().toLowerCase();if(p.has(r))return!0;let n=l.exec(r);if(!n)return!1;let t=Number(n[2]),c=n[3]===void 0?0:Number(n[3]);return t>o.major||t===o.major&&c>=o.minor}function _(e,r=process.env){return r.AQE_CYBER_VERIFIED==="true"?!1:i.includes(e)}function d(e,r,n,t=process.env){return!_(e,t)||!E(r)?r:n}function f(e){switch(e){case"openrouter":return a;case"bedrock":return"anthropic.claude-sonnet-4-6-v1:0";default:return u}}export{a,u as b,E as c,_ as d,d as e,f};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{b as c,d as p}from"./chunk-
|
|
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.13");process.exit(0)}
|
|
2
|
+
import{b as c,d as p}from"./chunk-VTOBUZL6.js";import{a as f}from"./chunk-ZAKQLAHT.js";p();import{existsSync as l,readFileSync as i}from"node:fs";import{join as a}from"node:path";import{execSync as m}from"node:child_process";var s=null,d=0,g=6e4;function S(){s=null,d=0}function b(e){if(s&&Date.now()-d<g)return s;let n=w(e);return s=n,d=Date.now(),n}function w(e){let n=h(e);if(n)return n;let r=v(e);if(r)return r;let t=k(e);return t||{available:!1}}function h(e){let n=a(e,".mcp.json");if(l(n))try{let o=c(i(n,"utf-8"));if(o.mcpServers?.ruflo||o.mcpServers?.["claude-flow"])return{available:!0,method:"mcp-config"}}catch{}let r=a(e,".claude","mcp.json");if(l(r))try{let o=c(i(r,"utf-8"));if(o.mcpServers?.ruflo||o.mcpServers?.["claude-flow"])return{available:!0,method:"mcp-config"}}catch{}let t=a(e,".claude","settings.json");if(l(t))try{let o=c(i(t,"utf-8")),u=o.mcpServers||o.mcp?.servers||{};if(u.ruflo||u["claude-flow"]||u["@anthropic/claude-flow"])return{available:!0,method:"mcp-config"}}catch{}return null}function v(e){let n=a(e,"package.json");if(!l(n))return null;try{let r=c(i(n,"utf-8")),t={...r.dependencies,...r.devDependencies};if(t.ruflo||t["@claude-flow/cli"]||t["claude-flow"])return{available:!0,method:"npm-dependency"}}catch{}return null}function k(e){for(let n of["ruflo","@claude-flow/cli"])try{return{available:!0,method:"npx-cached",version:m(`npx --no-install ${n} --version`,{encoding:"utf-8",timeout:5e3,cwd:e,stdio:["pipe","pipe","pipe"]}).trim().match(/\d+\.\d+\.\d+[\w.-]*/)?.[0]}}catch{}return null}function x(){for(let e of["ruflo","@claude-flow/cli"])try{return f.resolve(`${e}/package.json`),e}catch{}return"ruflo"}function P(){return[" Claude Flow not found \u2014 running in standalone mode.",""," Claude Flow adds optional features:"," - SONA trajectory tracking (reinforcement learning)"," - 3-tier model routing (haiku / sonnet / opus)"," - Codebase pretrain analysis",""," To install later:"," npm install -g ruflo"," claude mcp add ruflo -- npx -y ruflo@3.5.18"," aqe init --auto --with-claude-flow"].join(`
|
|
3
3
|
`)}export{S as a,b,x as c,P as d};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{b as s}from"./chunk-
|
|
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.13");process.exit(0)}
|
|
2
|
+
import{b as s}from"./chunk-ZAKQLAHT.js";function A(r=l,o=process.env){let t=o.AQE_OLLAMA_URL??o.OLLAMA_URL??r,e=t.length;for(;e>0&&t.charCodeAt(e-1)===47;)e-=1;return t.slice(0,e)}var l,n=s(()=>{"use strict";l="http://localhost:11434"});export{A as a,n as b};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
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.13");process.exit(0)}
|
|
2
2
|
var l=["var-to-const","add-types","remove-console","promise-to-async","cjs-to-esm","func-to-arrow"],p={"var-to-const":{type:"var-to-const",name:"Var to Const/Let",description:"Convert var declarations to const (if not reassigned) or let (if reassigned)",complexity:"simple",wasmAvailable:!0,typicalLatencyMs:1},"add-types":{type:"add-types",name:"Add TypeScript Types",description:"Add TypeScript type annotations to function parameters and return types",complexity:"moderate",wasmAvailable:!0,typicalLatencyMs:5},"remove-console":{type:"remove-console",name:"Remove Console Statements",description:"Remove all console.log, console.warn, console.error, etc. statements",complexity:"simple",wasmAvailable:!0,typicalLatencyMs:1},"promise-to-async":{type:"promise-to-async",name:"Promise to Async/Await",description:"Convert Promise .then()/.catch() chains to async/await syntax",complexity:"complex",wasmAvailable:!0,typicalLatencyMs:10},"cjs-to-esm":{type:"cjs-to-esm",name:"CommonJS to ES Modules",description:"Convert require() calls to import statements and module.exports to export",complexity:"moderate",wasmAvailable:!0,typicalLatencyMs:5},"func-to-arrow":{type:"func-to-arrow",name:"Function to Arrow",description:"Convert function declarations and expressions to arrow functions",complexity:"moderate",wasmAvailable:!0,typicalLatencyMs:3}},u={enabled:!0,fallbackToLLM:!0,confidenceThreshold:.7,transforms:[],maxFileSizeBytes:1024*1024,timeoutMs:5e3,cacheEnabled:!0,cacheTtlMs:300*1e3},t=class extends Error{constructor(e,s,o){super(e);this.code=s;this.cause=o;this.name="AgentBoosterError"}code;cause},a=class extends t{constructor(e,s,o){super(e,"TRANSFORM_ERROR",o);this.transformType=s;this.name="TransformError"}transformType},i=class extends t{constructor(r="WASM module is not available",e){super(r,"WASM_UNAVAILABLE",e),this.name="WasmUnavailableError"}},c=class extends t{constructor(e,s,o){super(e,"TRANSFORM_TIMEOUT");this.transformType=s;this.timeoutMs=o;this.name="TransformTimeoutError"}transformType;timeoutMs},m=class extends t{constructor(e,s,o){super(`File ${e} is too large (${s} bytes, max ${o} bytes)`,"FILE_TOO_LARGE");this.filePath=e;this.sizeBytes=s;this.maxSizeBytes=o;this.name="FileTooLargeError"}filePath;sizeBytes;maxSizeBytes};export{l as a,p as b,u as c,a as d,i as e,c as f,m as g};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{b as S}from"./chunk-
|
|
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.13");process.exit(0)}
|
|
2
|
+
import{b as S}from"./chunk-ZAKQLAHT.js";import{createHash as C}from"crypto";import*as a from"fs";import*as c from"os";import*as n from"path";function P(t){try{return a.realpathSync.native(t)}catch{return t}}function i(){let t="",r="";try{t=c.tmpdir()}catch{}try{r=c.homedir()}catch{}return{platform:process.platform,tmpdir:t,homedir:r,env:process.env,realpath:P}}function m(t){return t==="win32"?n.win32:n.posix}function l(t,r=i()){let e=m(r.platform),o=e.resolve(r.realpath(e.resolve(t))),s=e.parse(o).root.length;for(;o.length>s&&/[\\/]$/.test(o);)o=o.slice(0,-1);return r.platform==="win32"?o.toLowerCase():o}function w(t,r=i()){let e=m(r.platform),o=l(t,r);if(r.tmpdir&&o===l(r.tmpdir,r))return!0;if(r.platform==="win32")return o===e.parse(o).root.toLowerCase();let s=e.resolve(t);return y.some(p=>p===s||l(p,r)===o)}function b(t,r=i()){if(r.platform==="win32")return!1;try{return(a.statSync(t).mode&514)===514}catch{return!1}}function k(t,r=i()){return w(t,r)||b(t,r)}function A(t=i()){let r=m(t.platform),e;if(t.platform==="win32")e=t.env.LOCALAPPDATA||r.join(t.homedir,"AppData","Local");else if(t.platform==="darwin")e=r.join(t.homedir,"Library","Caches");else{let o=t.env.XDG_CACHE_HOME;e=o&&r.isAbsolute(o)?o:r.join(t.homedir,".cache")}return r.join(e,"agentic-qe","scratch")}function E(t,r=i()){let e=C("sha256").update(l(t,r)).digest("hex").slice(0,16);return m(r.platform).join(A(r),e)}function u(t){a.mkdirSync(t,{recursive:!0,mode:448}),process.platform!=="win32"&&a.chmodSync(t,448)}function R(t,r=i()){let e=E(t,r);try{return u(e),d(e,t),e}catch(o){let s=typeof process.getuid=="function"?String(process.getuid()):"user",p=n.join(r.tmpdir||c.tmpdir(),`agentic-qe-scratch-${s}`),f=n.join(p,n.basename(e));try{return u(p),u(f),d(f,t),f}catch(v){let g=h=>h instanceof Error?h.message:String(h);throw new Error(`Cannot create a private AQE scratch root for "${t}". User cache "${e}" failed: ${g(o)}. Temporary fallback "${f}" failed: ${g(v)}. Set AQE_PROJECT_ROOT to a project directory or make the user cache writable.`)}}}function d(t,r){let e=n.join(t,"SCRATCH_ROOT_FOR");try{a.existsSync(e)||a.writeFileSync(e,`${n.resolve(r)}
|
|
3
3
|
`,{mode:384})}catch{}}var y,O=S(()=>{"use strict";y=["/","/tmp","/var/tmp","/usr/tmp","/dev/shm","/run/shm","/private","/private/tmp","/private/var","/private/var/tmp","/var","/usr","/etc","/opt","/srv","/mnt","/media","/run","/home","/Users","/Volumes"]});export{w as a,b,k as c,E as d,R as e,O as f};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{a as v}from"./chunk-FAGKBOX2.js";import{h as U}from"./chunk-ZPVGX4DI.js";import{c as D,d as R,e as h,g as x}from"./chunk-2ASQRBK2.js";var f=class{config;trackers;globalCostTodayUsd=0;lastGlobalReset=new Date;constructor(e){this.config=e,this.trackers=new Map;for(let t of[0,1,2,3,4])this.trackers.set(t,{tier:t,costSpentTodayUsd:0,requestsThisHour:0,requestsToday:0,lastHourlyReset:new Date,lastDailyReset:new Date,requestHistory:[]})}async checkBudget(e,t){if(!this.config.enabled)return this.createAllowedDecision(e,e,t,!1,[]);this.autoReset();let r=this.config.tierBudgets[e];if(!r||!r.enabled)return this.createAllowedDecision(e,e,t,!1,["Tier budget not configured or disabled"]);let s=this.getUsage(e),i=[],c=this.config.maxDailyCostUsd-this.globalCostTodayUsd;if(this.globalCostTodayUsd+t>this.config.maxDailyCostUsd)return this.handleBudgetExceeded(e,t,s,"Global daily budget would be exceeded");if(this.globalCostTodayUsd+t>=this.config.maxDailyCostUsd*this.config.warningThreshold&&(i.push(`Approaching global daily budget limit: $${this.globalCostTodayUsd.toFixed(2)}/$${this.config.maxDailyCostUsd.toFixed(2)}`),this.config.onBudgetWarning==="downgrade"))return this.downgradeTier(e,t,s,i);let a=[{exceeded:s.costSpentTodayUsd+t>r.maxDailyCostUsd,message:`Tier ${e} daily cost limit would be exceeded: $${s.costSpentTodayUsd.toFixed(2)}/$${r.maxDailyCostUsd.toFixed(2)}`},{exceeded:s.requestsThisHour>=r.maxRequestsPerHour,message:`Tier ${e} hourly request limit reached: ${s.requestsThisHour}/${r.maxRequestsPerHour}`},{exceeded:s.requestsToday>=r.maxRequestsPerDay,message:`Tier ${e} daily request limit reached: ${s.requestsToday}/${r.maxRequestsPerDay}`},{exceeded:t>r.maxCostPerRequest,message:`Tier ${e} per-request cost limit would be exceeded: $${t.toFixed(4)}/$${r.maxCostPerRequest.toFixed(4)}`}];for(let n of a)if(n.exceeded)return this.handleBudgetExceeded(e,t,s,n.message);return s.budgetUtilization>=this.config.warningThreshold&&(i.push(`Tier ${e} at ${(s.budgetUtilization*100).toFixed(1)}% of daily budget`),this.config.onBudgetWarning==="downgrade")?this.downgradeTier(e,t,s,i):this.createAllowedDecision(e,e,t,!1,i)}async recordCost(e,t){if(!this.config.enabled)return;let r=this.trackers.get(e);r&&(this.autoReset(),r.costSpentTodayUsd+=t,r.requestsThisHour++,r.requestsToday++,this.globalCostTodayUsd+=t,r.requestHistory.push({timestamp:new Date,costUsd:t}),r.requestHistory.length>1e3&&(r.requestHistory=r.requestHistory.slice(-1e3)))}getUsage(e){this.autoReset();let t=this.trackers.get(e);if(!t)return this.createEmptyUsage(e);let r=this.config.tierBudgets[e];if(!r)return this.createEmptyUsage(e);let s=r.maxDailyCostUsd>0?t.costSpentTodayUsd/r.maxDailyCostUsd:0,i=t.costSpentTodayUsd>=r.maxDailyCostUsd||t.requestsThisHour>=r.maxRequestsPerHour||t.requestsToday>=r.maxRequestsPerDay,c=s>=this.config.warningThreshold,a=new Date,n=new Date(a);return n.setUTCHours(24,0,0,0),{tier:e,costSpentTodayUsd:t.costSpentTodayUsd,requestsThisHour:t.requestsThisHour,requestsToday:t.requestsToday,budgetUtilization:s,isExceeded:i,isNearLimit:c,resetTime:n,remainingBudgetUsd:Math.max(0,r.maxDailyCostUsd-t.costSpentTodayUsd),remainingRequestsThisHour:Math.max(0,r.maxRequestsPerHour-t.requestsThisHour),remainingRequestsToday:Math.max(0,r.maxRequestsPerDay-t.requestsToday)}}getAllUsage(){let e={};for(let t of[0,1,2,3,4])e[t]=this.getUsage(t);return e}reset(){let e=new Date;for(let t of this.trackers.values())t.costSpentTodayUsd=0,t.requestsThisHour=0,t.requestsToday=0,t.lastHourlyReset=e,t.lastDailyReset=e,t.requestHistory=[];this.globalCostTodayUsd=0,this.lastGlobalReset=e}handleBudgetExceeded(e,t,r,s){switch(this.config.onBudgetExceeded){case"error":throw new h(`Budget exceeded: ${s}`,e,r);case"downgrade":return this.downgradeTier(e,t,r,[s]);case"queue":throw new h(`Budget exceeded (queueing not yet implemented): ${s}`,e,r);default:throw new h(`Budget exceeded: ${s}`,e,r)}}downgradeTier(e,t,r,s){for(let i=e-1;i>=0;i--){let c=this.config.tierBudgets[i];if(!c||!c.enabled)continue;let a=this.getUsage(i);if(!a.isExceeded){let n=t*.5;if(a.costSpentTodayUsd+n<=c.maxDailyCostUsd)return this.createAllowedDecision(e,i,n,!0,[...s,`Downgraded from Tier ${e} to Tier ${i} due to budget constraints`])}}throw new h(`Budget exceeded and no lower tier available: ${s.join("; ")}`,e,r)}createAllowedDecision(e,t,r,s,i){let c=this.getUsage(t);return{allowed:!0,reason:s?`Budget enforced: downgraded to Tier ${t}`:"Budget check passed",requestedTier:e,approvedTier:t,wasDowngraded:s,estimatedCostUsd:r,currentUsage:c,warnings:i}}createEmptyUsage(e){let t=new Date,r=new Date(t);return r.setUTCHours(24,0,0,0),{tier:e,costSpentTodayUsd:0,requestsThisHour:0,requestsToday:0,budgetUtilization:0,isExceeded:!1,isNearLimit:!1,resetTime:r,remainingBudgetUsd:0,remainingRequestsThisHour:0,remainingRequestsToday:0}}autoReset(){let e=new Date;this.shouldResetDaily(this.lastGlobalReset,e)&&(this.globalCostTodayUsd=0,this.lastGlobalReset=e);for(let t of this.trackers.values())this.shouldResetHourly(t.lastHourlyReset,e)&&(t.requestsThisHour=0,t.lastHourlyReset=e),this.shouldResetDaily(t.lastDailyReset,e)&&(t.costSpentTodayUsd=0,t.requestsToday=0,t.requestHistory=[],t.lastDailyReset=e)}shouldResetHourly(e,t){return(t.getTime()-e.getTime())/36e5>=1}shouldResetDaily(e,t){return t.getUTCDate()!==e.getUTCDate()||t.getUTCMonth()!==e.getUTCMonth()||t.getUTCFullYear()!==e.getUTCFullYear()}getSessionCostSummary(){this.autoReset();let e=this.config.maxDailyCostUsd,t=0,r={},s={0:"AgentBooster",1:"Haiku",2:"Sonnet",3:"SonnetExtended",4:"Opus"};for(let[c,a]of this.trackers.entries()){let n=this.config.tierBudgets[c],o=s[c]??`Tier${c}`;t+=a.costSpentTodayUsd,r[o]={spent:a.costSpentTodayUsd,limit:n?.maxDailyCostUsd??0,requests:a.requestsToday}}let i=e>0?Math.round(t/e*100):0;return{totalSpentUsd:t,dailyLimitUsd:e,utilizationPercent:i,byTier:r}}};var w=class{cache=new Map;maxSize;ttlMs;enabled;constructor(e,t,r){this.enabled=e,this.maxSize=t,this.ttlMs=r}generateKey(e){return`${e.agentType||"unknown"}:${e.domain||"unknown"}:${e.task.slice(0,100)}`}get(e){if(!this.enabled)return null;let t=this.generateKey(e),r=this.cache.get(t);return r?Date.now()>r.expiresAt?(this.cache.delete(t),null):{...r.decision,metadata:{...r.decision.metadata,fromCache:!0,decisionTimeMs:0}}:null}set(e,t){if(!this.enabled)return;let r=this.generateKey(e);if(this.cache.size>=this.maxSize){let s=this.cache.keys().next().value;s&&this.cache.delete(s)}this.cache.set(r,{decision:t,expiresAt:Date.now()+this.ttlMs})}clear(){this.cache.clear()}getStats(){return{size:this.cache.size,hitRate:0}}},M=class{events=[];enabled;maxEvents=1e4;constructor(e){this.enabled=e}record(e){this.enabled&&(this.events.push(e),this.events.length>this.maxEvents&&(this.events=this.events.slice(-this.maxEvents)))}getMetrics(){if(this.events.length===0)return this.createEmptyMetrics();let e=new Date,t={};for(let o of[0,1,2,3,4]){let d=this.events.filter(l=>l.tier===o);if(d.length===0)continue;let T=d.filter(l=>l.success),m=d.filter(l=>!l.wasManualOverride),b=d.filter(l=>l.wasDowngraded),y=d.map(l=>l.latencyMs).sort((l,g)=>l-g),B=Math.floor(y.length*.95);t[o]={tier:o,selectionCount:d.length,autoRouteCount:m.length,manualOverrideCount:d.length-m.length,budgetDowngradeCount:b.length,successRate:T.length/d.length,avgComplexity:d.reduce((l,g)=>l+g.complexity,0)/d.length,totalCostUsd:d.reduce((l,g)=>l+g.costUsd,0),avgLatencyMs:d.reduce((l,g)=>l+g.latencyMs,0)/d.length,p95LatencyMs:y[B]||0,budgetUtilization:0}}let r=this.events.map(o=>o.latencyMs).sort((o,d)=>o-d),s=Math.floor(r.length*.95),i=Math.floor(r.length*.99),c=this.events.filter(o=>o.agentBoosterEligible).length,a=this.events.filter(o=>o.tier===0).length,n=this.events.filter(o=>o.tier===0&&o.success).length;return{byTier:t,totalDecisions:this.events.length,avgDecisionTimeMs:this.events.reduce((o,d)=>o+d.latencyMs,0)/this.events.length,p95DecisionTimeMs:r[s]||0,p99DecisionTimeMs:r[i]||0,fallbackRate:this.events.filter(o=>o.wasDowngraded).length/this.events.length,ruleMatchRate:this.events.filter(o=>!o.wasManualOverride).length/this.events.length,estimatedCostSavings:0,agentBoosterStats:{eligible:c,used:a,fallbackToLLM:Math.max(0,c-a),successRate:a>0?n/a:0},budgetStats:{totalSpentUsd:this.events.reduce((o,d)=>o+d.costUsd,0),budgetUtilization:0,downgradeCount:this.events.filter(o=>o.wasDowngraded).length,overrideCount:this.events.filter(o=>o.wasManualOverride).length},period:{start:this.events[0]?.timestamp||e,end:this.events[this.events.length-1]?.timestamp||e}}}reset(){this.events=[]}createEmptyMetrics(){let e=new Date;return{byTier:{},totalDecisions:0,avgDecisionTimeMs:0,p95DecisionTimeMs:0,p99DecisionTimeMs:0,fallbackRate:0,ruleMatchRate:0,estimatedCostSavings:0,agentBoosterStats:{eligible:0,used:0,fallbackToLLM:0,successRate:0},budgetStats:{totalSpentUsd:0,budgetUtilization:0,downgradeCount:0,overrideCount:0},period:{start:e,end:e}}}},p=class{config;complexityAnalyzer;budgetEnforcer;agentBoosterAdapter;cache;metrics;persistentMetricsTracker;patternsLoaded=!1;tierHierarchyFromPatterns=null;constructor(e={},t,r){this.config={...D,...e},this.agentBoosterAdapter=t,this.persistentMetricsTracker=r,this.complexityAnalyzer=U(this.config,t),this.budgetEnforcer=new f(this.config.budgetConfig),this.cache=new w(this.config.enableDecisionCache,1e3,this.config.decisionCacheTtlMs),this.metrics=new M(this.config.enableMetrics)}setPersistentMetricsTracker(e){this.persistentMetricsTracker=e}async loadPatternsFromLoader(){try{let t=await v().getTierHierarchy();if(t){this.tierHierarchyFromPatterns=t,this.patternsLoaded=!0,console.info("[ModelRouter] Loaded tier hierarchy from PatternLoader",{tiers:Object.keys(t)});return}console.debug("[ModelRouter] PatternLoader returned no tier hierarchy, using defaults")}catch(e){console.warn("[ModelRouter] Failed to load patterns from PatternLoader, using defaults",{error:e instanceof Error?e.message:"Unknown error"})}this.patternsLoaded=!1}getPatternsLoaded(){return this.patternsLoaded}getTierHierarchyFromPatterns(){return this.tierHierarchyFromPatterns}async route(e){let t=Date.now(),r=e.metadata?.correlationId;try{let s=this.cache.get(e);if(s)return s;let i=await Promise.race([this.routeInternal(e,t,r),new Promise((c,a)=>setTimeout(()=>a(new x("Routing decision timed out",this.config.maxDecisionTimeMs)),this.config.maxDecisionTimeMs))]);return this.cache.set(e,i),this.recordMetrics(i,!0),i}catch(s){let i=await this.createFallbackDecision(e,t,r,s instanceof Error?s:new Error("Unknown error"));return this.recordMetrics(i,!1),i}}getMetrics(){return this.metrics.getMetrics()}async getAgentBoosterHealth(){if(!this.agentBoosterAdapter)throw new R("Agent Booster adapter not available","AGENT_BOOSTER_UNAVAILABLE");return this.agentBoosterAdapter.getHealth()}resetMetrics(){this.metrics.reset()}async dispose(){this.cache.clear(),this.metrics.reset(),this.agentBoosterAdapter&&await this.agentBoosterAdapter.dispose()}async routeInternal(e,t,r){let s=[];if(e.manualTier!==void 0&&this.config.allowManualOverrides)return this.handleManualOverride(e,e.manualTier,t,r);let i=await this.complexityAnalyzer.analyze(e),c=i.recommendedTier,a=this.estimateCost(c,e.task.length),n=await this.budgetEnforcer.checkBudget(c,a),o=n.approvedTier;s.push(...n.warnings);let d=o===0&&i.signals.isMechanicalTransform,T=this.getModelIdForTier(o),m=this.buildRationale(i,n,o),b=this.buildAlternatives(i,o),y=Date.now()-t;return{tier:o,modelId:T,complexityAnalysis:i,budgetDecision:n,confidence:i.confidence,rationale:m,agentBoosterEligible:d,agentBoosterTransform:d?i.signals.detectedTransformType:void 0,alternativeTiers:b,metadata:{timestamp:new Date,decisionTimeMs:y,fromCache:!1,correlationId:r},warnings:s}}async handleManualOverride(e,t,r,s){let i=await this.complexityAnalyzer.analyze(e),c=this.estimateCost(t,e.task.length),a=await this.budgetEnforcer.checkBudget(t,c);!a.allowed&&e.isCritical&&this.config.budgetConfig.allowCriticalOverrides&&(a={...a,allowed:!0,reason:"Critical task override",warnings:[...a.warnings,"Budget exceeded but allowed due to critical task override"]});let n=a.approvedTier,o=this.getModelIdForTier(n),d=Date.now()-r;return{tier:n,modelId:o,complexityAnalysis:i,budgetDecision:a,confidence:1,rationale:`Manual override to Tier ${n}${a.wasDowngraded?" (downgraded due to budget)":""}`,agentBoosterEligible:n===0,alternativeTiers:[],metadata:{timestamp:new Date,decisionTimeMs:d,fromCache:!1,correlationId:s},warnings:a.warnings}}async createFallbackDecision(e,t,r,s){let i=this.config.fallbackTier,c=this.getModelIdForTier(i),a={overall:50,codeComplexity:50,reasoningComplexity:50,scopeComplexity:50,confidence:.3,signals:{hasArchitectureScope:!1,hasSecurityScope:!1,requiresMultiStepReasoning:!1,requiresCrossDomainCoordination:!1,isMechanicalTransform:!1,requiresCreativity:!1,keywordMatches:{simple:[],moderate:[],complex:[],critical:[]}},recommendedTier:i,alternateTiers:[],explanation:`Fallback to Tier ${i} due to routing error`},n={allowed:!0,reason:"Fallback routing",requestedTier:i,approvedTier:i,wasDowngraded:!1,estimatedCostUsd:0,currentUsage:this.budgetEnforcer.getUsage(i),warnings:[]},o=Date.now()-t;return{tier:i,modelId:c,complexityAnalysis:a,budgetDecision:n,confidence:.3,rationale:`Fallback to Tier ${i} due to error: ${s.message}`,agentBoosterEligible:!1,alternativeTiers:[],metadata:{timestamp:new Date,decisionTimeMs:o,fromCache:!1,correlationId:r},warnings:[`Routing error: ${s.message}`,"Using fallback tier"]}}estimateCost(e,t){let r=[0,.001,.01,.05,.2],s=Math.max(1,t/1e3);return r[e]*s}getModelIdForTier(e){return this.config.tierModels[e]||`tier-${e}-default`}buildRationale(e,t,r){let s=[];return s.push(`Complexity: ${e.overall}/100`),s.push(`Tier ${r} selected`),t.wasDowngraded&&s.push(`Downgraded due to budget: ${t.reason}`),s.push(e.explanation),s.join(". ")}buildAlternatives(e,t){return e.alternateTiers.filter(r=>r!==t).map(r=>({tier:r,modelId:this.getModelIdForTier(r),reason:`Alternative tier ${r}`}))}recordMetrics(e,t){this.metrics.record({timestamp:e.metadata.timestamp,tier:e.tier,complexity:e.complexityAnalysis.overall,costUsd:e.budgetDecision.estimatedCostUsd,latencyMs:e.metadata.decisionTimeMs,wasDowngraded:e.budgetDecision.wasDowngraded,wasManualOverride:!1,agentBoosterEligible:e.agentBoosterEligible,success:t}),this.recordPersistentMetrics(e,t).catch(console.error)}async recordPersistentMetrics(e,t){if(this.persistentMetricsTracker)try{let r=`router-tier${e.tier}-${Date.now()}`;await this.persistentMetricsTracker.recordOutcome("router",r,t,e.metadata.decisionTimeMs,{subType:`tier-${e.tier}`,confidence:e.confidence,usedFallback:e.budgetDecision.wasDowngraded})}catch(r){console.warn("[ModelRouter] Failed to record persistent metrics:",r)}}};function H(u={},e,t){return new p(u,e,t)}async function $(u={},e){let{createAgentBoosterAdapter:t}=await import("./adapter-HL7MOCQN.js"),r=await t({enabled:!0}),s=new p(u,r,e);return await s.loadPatternsFromLoader(),s}export{p as a,H as b,$ as c};
|
|
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.13");process.exit(0)}
|
|
2
|
+
import{a as v}from"./chunk-32ZMWEP3.js";import{h as U}from"./chunk-MFW5HSG4.js";import{c as D,d as R,e as h,g as x}from"./chunk-7YTGHGK4.js";var f=class{config;trackers;globalCostTodayUsd=0;lastGlobalReset=new Date;constructor(e){this.config=e,this.trackers=new Map;for(let t of[0,1,2,3,4])this.trackers.set(t,{tier:t,costSpentTodayUsd:0,requestsThisHour:0,requestsToday:0,lastHourlyReset:new Date,lastDailyReset:new Date,requestHistory:[]})}async checkBudget(e,t){if(!this.config.enabled)return this.createAllowedDecision(e,e,t,!1,[]);this.autoReset();let r=this.config.tierBudgets[e];if(!r||!r.enabled)return this.createAllowedDecision(e,e,t,!1,["Tier budget not configured or disabled"]);let s=this.getUsage(e),i=[],c=this.config.maxDailyCostUsd-this.globalCostTodayUsd;if(this.globalCostTodayUsd+t>this.config.maxDailyCostUsd)return this.handleBudgetExceeded(e,t,s,"Global daily budget would be exceeded");if(this.globalCostTodayUsd+t>=this.config.maxDailyCostUsd*this.config.warningThreshold&&(i.push(`Approaching global daily budget limit: $${this.globalCostTodayUsd.toFixed(2)}/$${this.config.maxDailyCostUsd.toFixed(2)}`),this.config.onBudgetWarning==="downgrade"))return this.downgradeTier(e,t,s,i);let a=[{exceeded:s.costSpentTodayUsd+t>r.maxDailyCostUsd,message:`Tier ${e} daily cost limit would be exceeded: $${s.costSpentTodayUsd.toFixed(2)}/$${r.maxDailyCostUsd.toFixed(2)}`},{exceeded:s.requestsThisHour>=r.maxRequestsPerHour,message:`Tier ${e} hourly request limit reached: ${s.requestsThisHour}/${r.maxRequestsPerHour}`},{exceeded:s.requestsToday>=r.maxRequestsPerDay,message:`Tier ${e} daily request limit reached: ${s.requestsToday}/${r.maxRequestsPerDay}`},{exceeded:t>r.maxCostPerRequest,message:`Tier ${e} per-request cost limit would be exceeded: $${t.toFixed(4)}/$${r.maxCostPerRequest.toFixed(4)}`}];for(let n of a)if(n.exceeded)return this.handleBudgetExceeded(e,t,s,n.message);return s.budgetUtilization>=this.config.warningThreshold&&(i.push(`Tier ${e} at ${(s.budgetUtilization*100).toFixed(1)}% of daily budget`),this.config.onBudgetWarning==="downgrade")?this.downgradeTier(e,t,s,i):this.createAllowedDecision(e,e,t,!1,i)}async recordCost(e,t){if(!this.config.enabled)return;let r=this.trackers.get(e);r&&(this.autoReset(),r.costSpentTodayUsd+=t,r.requestsThisHour++,r.requestsToday++,this.globalCostTodayUsd+=t,r.requestHistory.push({timestamp:new Date,costUsd:t}),r.requestHistory.length>1e3&&(r.requestHistory=r.requestHistory.slice(-1e3)))}getUsage(e){this.autoReset();let t=this.trackers.get(e);if(!t)return this.createEmptyUsage(e);let r=this.config.tierBudgets[e];if(!r)return this.createEmptyUsage(e);let s=r.maxDailyCostUsd>0?t.costSpentTodayUsd/r.maxDailyCostUsd:0,i=t.costSpentTodayUsd>=r.maxDailyCostUsd||t.requestsThisHour>=r.maxRequestsPerHour||t.requestsToday>=r.maxRequestsPerDay,c=s>=this.config.warningThreshold,a=new Date,n=new Date(a);return n.setUTCHours(24,0,0,0),{tier:e,costSpentTodayUsd:t.costSpentTodayUsd,requestsThisHour:t.requestsThisHour,requestsToday:t.requestsToday,budgetUtilization:s,isExceeded:i,isNearLimit:c,resetTime:n,remainingBudgetUsd:Math.max(0,r.maxDailyCostUsd-t.costSpentTodayUsd),remainingRequestsThisHour:Math.max(0,r.maxRequestsPerHour-t.requestsThisHour),remainingRequestsToday:Math.max(0,r.maxRequestsPerDay-t.requestsToday)}}getAllUsage(){let e={};for(let t of[0,1,2,3,4])e[t]=this.getUsage(t);return e}reset(){let e=new Date;for(let t of this.trackers.values())t.costSpentTodayUsd=0,t.requestsThisHour=0,t.requestsToday=0,t.lastHourlyReset=e,t.lastDailyReset=e,t.requestHistory=[];this.globalCostTodayUsd=0,this.lastGlobalReset=e}handleBudgetExceeded(e,t,r,s){switch(this.config.onBudgetExceeded){case"error":throw new h(`Budget exceeded: ${s}`,e,r);case"downgrade":return this.downgradeTier(e,t,r,[s]);case"queue":throw new h(`Budget exceeded (queueing not yet implemented): ${s}`,e,r);default:throw new h(`Budget exceeded: ${s}`,e,r)}}downgradeTier(e,t,r,s){for(let i=e-1;i>=0;i--){let c=this.config.tierBudgets[i];if(!c||!c.enabled)continue;let a=this.getUsage(i);if(!a.isExceeded){let n=t*.5;if(a.costSpentTodayUsd+n<=c.maxDailyCostUsd)return this.createAllowedDecision(e,i,n,!0,[...s,`Downgraded from Tier ${e} to Tier ${i} due to budget constraints`])}}throw new h(`Budget exceeded and no lower tier available: ${s.join("; ")}`,e,r)}createAllowedDecision(e,t,r,s,i){let c=this.getUsage(t);return{allowed:!0,reason:s?`Budget enforced: downgraded to Tier ${t}`:"Budget check passed",requestedTier:e,approvedTier:t,wasDowngraded:s,estimatedCostUsd:r,currentUsage:c,warnings:i}}createEmptyUsage(e){let t=new Date,r=new Date(t);return r.setUTCHours(24,0,0,0),{tier:e,costSpentTodayUsd:0,requestsThisHour:0,requestsToday:0,budgetUtilization:0,isExceeded:!1,isNearLimit:!1,resetTime:r,remainingBudgetUsd:0,remainingRequestsThisHour:0,remainingRequestsToday:0}}autoReset(){let e=new Date;this.shouldResetDaily(this.lastGlobalReset,e)&&(this.globalCostTodayUsd=0,this.lastGlobalReset=e);for(let t of this.trackers.values())this.shouldResetHourly(t.lastHourlyReset,e)&&(t.requestsThisHour=0,t.lastHourlyReset=e),this.shouldResetDaily(t.lastDailyReset,e)&&(t.costSpentTodayUsd=0,t.requestsToday=0,t.requestHistory=[],t.lastDailyReset=e)}shouldResetHourly(e,t){return(t.getTime()-e.getTime())/36e5>=1}shouldResetDaily(e,t){return t.getUTCDate()!==e.getUTCDate()||t.getUTCMonth()!==e.getUTCMonth()||t.getUTCFullYear()!==e.getUTCFullYear()}getSessionCostSummary(){this.autoReset();let e=this.config.maxDailyCostUsd,t=0,r={},s={0:"AgentBooster",1:"Haiku",2:"Sonnet",3:"SonnetExtended",4:"Opus"};for(let[c,a]of this.trackers.entries()){let n=this.config.tierBudgets[c],o=s[c]??`Tier${c}`;t+=a.costSpentTodayUsd,r[o]={spent:a.costSpentTodayUsd,limit:n?.maxDailyCostUsd??0,requests:a.requestsToday}}let i=e>0?Math.round(t/e*100):0;return{totalSpentUsd:t,dailyLimitUsd:e,utilizationPercent:i,byTier:r}}};var w=class{cache=new Map;maxSize;ttlMs;enabled;constructor(e,t,r){this.enabled=e,this.maxSize=t,this.ttlMs=r}generateKey(e){return`${e.agentType||"unknown"}:${e.domain||"unknown"}:${e.task.slice(0,100)}`}get(e){if(!this.enabled)return null;let t=this.generateKey(e),r=this.cache.get(t);return r?Date.now()>r.expiresAt?(this.cache.delete(t),null):{...r.decision,metadata:{...r.decision.metadata,fromCache:!0,decisionTimeMs:0}}:null}set(e,t){if(!this.enabled)return;let r=this.generateKey(e);if(this.cache.size>=this.maxSize){let s=this.cache.keys().next().value;s&&this.cache.delete(s)}this.cache.set(r,{decision:t,expiresAt:Date.now()+this.ttlMs})}clear(){this.cache.clear()}getStats(){return{size:this.cache.size,hitRate:0}}},M=class{events=[];enabled;maxEvents=1e4;constructor(e){this.enabled=e}record(e){this.enabled&&(this.events.push(e),this.events.length>this.maxEvents&&(this.events=this.events.slice(-this.maxEvents)))}getMetrics(){if(this.events.length===0)return this.createEmptyMetrics();let e=new Date,t={};for(let o of[0,1,2,3,4]){let d=this.events.filter(l=>l.tier===o);if(d.length===0)continue;let T=d.filter(l=>l.success),m=d.filter(l=>!l.wasManualOverride),b=d.filter(l=>l.wasDowngraded),y=d.map(l=>l.latencyMs).sort((l,g)=>l-g),B=Math.floor(y.length*.95);t[o]={tier:o,selectionCount:d.length,autoRouteCount:m.length,manualOverrideCount:d.length-m.length,budgetDowngradeCount:b.length,successRate:T.length/d.length,avgComplexity:d.reduce((l,g)=>l+g.complexity,0)/d.length,totalCostUsd:d.reduce((l,g)=>l+g.costUsd,0),avgLatencyMs:d.reduce((l,g)=>l+g.latencyMs,0)/d.length,p95LatencyMs:y[B]||0,budgetUtilization:0}}let r=this.events.map(o=>o.latencyMs).sort((o,d)=>o-d),s=Math.floor(r.length*.95),i=Math.floor(r.length*.99),c=this.events.filter(o=>o.agentBoosterEligible).length,a=this.events.filter(o=>o.tier===0).length,n=this.events.filter(o=>o.tier===0&&o.success).length;return{byTier:t,totalDecisions:this.events.length,avgDecisionTimeMs:this.events.reduce((o,d)=>o+d.latencyMs,0)/this.events.length,p95DecisionTimeMs:r[s]||0,p99DecisionTimeMs:r[i]||0,fallbackRate:this.events.filter(o=>o.wasDowngraded).length/this.events.length,ruleMatchRate:this.events.filter(o=>!o.wasManualOverride).length/this.events.length,estimatedCostSavings:0,agentBoosterStats:{eligible:c,used:a,fallbackToLLM:Math.max(0,c-a),successRate:a>0?n/a:0},budgetStats:{totalSpentUsd:this.events.reduce((o,d)=>o+d.costUsd,0),budgetUtilization:0,downgradeCount:this.events.filter(o=>o.wasDowngraded).length,overrideCount:this.events.filter(o=>o.wasManualOverride).length},period:{start:this.events[0]?.timestamp||e,end:this.events[this.events.length-1]?.timestamp||e}}}reset(){this.events=[]}createEmptyMetrics(){let e=new Date;return{byTier:{},totalDecisions:0,avgDecisionTimeMs:0,p95DecisionTimeMs:0,p99DecisionTimeMs:0,fallbackRate:0,ruleMatchRate:0,estimatedCostSavings:0,agentBoosterStats:{eligible:0,used:0,fallbackToLLM:0,successRate:0},budgetStats:{totalSpentUsd:0,budgetUtilization:0,downgradeCount:0,overrideCount:0},period:{start:e,end:e}}}},p=class{config;complexityAnalyzer;budgetEnforcer;agentBoosterAdapter;cache;metrics;persistentMetricsTracker;patternsLoaded=!1;tierHierarchyFromPatterns=null;constructor(e={},t,r){this.config={...D,...e},this.agentBoosterAdapter=t,this.persistentMetricsTracker=r,this.complexityAnalyzer=U(this.config,t),this.budgetEnforcer=new f(this.config.budgetConfig),this.cache=new w(this.config.enableDecisionCache,1e3,this.config.decisionCacheTtlMs),this.metrics=new M(this.config.enableMetrics)}setPersistentMetricsTracker(e){this.persistentMetricsTracker=e}async loadPatternsFromLoader(){try{let t=await v().getTierHierarchy();if(t){this.tierHierarchyFromPatterns=t,this.patternsLoaded=!0,console.info("[ModelRouter] Loaded tier hierarchy from PatternLoader",{tiers:Object.keys(t)});return}console.debug("[ModelRouter] PatternLoader returned no tier hierarchy, using defaults")}catch(e){console.warn("[ModelRouter] Failed to load patterns from PatternLoader, using defaults",{error:e instanceof Error?e.message:"Unknown error"})}this.patternsLoaded=!1}getPatternsLoaded(){return this.patternsLoaded}getTierHierarchyFromPatterns(){return this.tierHierarchyFromPatterns}async route(e){let t=Date.now(),r=e.metadata?.correlationId;try{let s=this.cache.get(e);if(s)return s;let i=await Promise.race([this.routeInternal(e,t,r),new Promise((c,a)=>setTimeout(()=>a(new x("Routing decision timed out",this.config.maxDecisionTimeMs)),this.config.maxDecisionTimeMs))]);return this.cache.set(e,i),this.recordMetrics(i,!0),i}catch(s){let i=await this.createFallbackDecision(e,t,r,s instanceof Error?s:new Error("Unknown error"));return this.recordMetrics(i,!1),i}}getMetrics(){return this.metrics.getMetrics()}async getAgentBoosterHealth(){if(!this.agentBoosterAdapter)throw new R("Agent Booster adapter not available","AGENT_BOOSTER_UNAVAILABLE");return this.agentBoosterAdapter.getHealth()}resetMetrics(){this.metrics.reset()}async dispose(){this.cache.clear(),this.metrics.reset(),this.agentBoosterAdapter&&await this.agentBoosterAdapter.dispose()}async routeInternal(e,t,r){let s=[];if(e.manualTier!==void 0&&this.config.allowManualOverrides)return this.handleManualOverride(e,e.manualTier,t,r);let i=await this.complexityAnalyzer.analyze(e),c=i.recommendedTier,a=this.estimateCost(c,e.task.length),n=await this.budgetEnforcer.checkBudget(c,a),o=n.approvedTier;s.push(...n.warnings);let d=o===0&&i.signals.isMechanicalTransform,T=this.getModelIdForTier(o),m=this.buildRationale(i,n,o),b=this.buildAlternatives(i,o),y=Date.now()-t;return{tier:o,modelId:T,complexityAnalysis:i,budgetDecision:n,confidence:i.confidence,rationale:m,agentBoosterEligible:d,agentBoosterTransform:d?i.signals.detectedTransformType:void 0,alternativeTiers:b,metadata:{timestamp:new Date,decisionTimeMs:y,fromCache:!1,correlationId:r},warnings:s}}async handleManualOverride(e,t,r,s){let i=await this.complexityAnalyzer.analyze(e),c=this.estimateCost(t,e.task.length),a=await this.budgetEnforcer.checkBudget(t,c);!a.allowed&&e.isCritical&&this.config.budgetConfig.allowCriticalOverrides&&(a={...a,allowed:!0,reason:"Critical task override",warnings:[...a.warnings,"Budget exceeded but allowed due to critical task override"]});let n=a.approvedTier,o=this.getModelIdForTier(n),d=Date.now()-r;return{tier:n,modelId:o,complexityAnalysis:i,budgetDecision:a,confidence:1,rationale:`Manual override to Tier ${n}${a.wasDowngraded?" (downgraded due to budget)":""}`,agentBoosterEligible:n===0,alternativeTiers:[],metadata:{timestamp:new Date,decisionTimeMs:d,fromCache:!1,correlationId:s},warnings:a.warnings}}async createFallbackDecision(e,t,r,s){let i=this.config.fallbackTier,c=this.getModelIdForTier(i),a={overall:50,codeComplexity:50,reasoningComplexity:50,scopeComplexity:50,confidence:.3,signals:{hasArchitectureScope:!1,hasSecurityScope:!1,requiresMultiStepReasoning:!1,requiresCrossDomainCoordination:!1,isMechanicalTransform:!1,requiresCreativity:!1,keywordMatches:{simple:[],moderate:[],complex:[],critical:[]}},recommendedTier:i,alternateTiers:[],explanation:`Fallback to Tier ${i} due to routing error`},n={allowed:!0,reason:"Fallback routing",requestedTier:i,approvedTier:i,wasDowngraded:!1,estimatedCostUsd:0,currentUsage:this.budgetEnforcer.getUsage(i),warnings:[]},o=Date.now()-t;return{tier:i,modelId:c,complexityAnalysis:a,budgetDecision:n,confidence:.3,rationale:`Fallback to Tier ${i} due to error: ${s.message}`,agentBoosterEligible:!1,alternativeTiers:[],metadata:{timestamp:new Date,decisionTimeMs:o,fromCache:!1,correlationId:r},warnings:[`Routing error: ${s.message}`,"Using fallback tier"]}}estimateCost(e,t){let r=[0,.001,.01,.05,.2],s=Math.max(1,t/1e3);return r[e]*s}getModelIdForTier(e){return this.config.tierModels[e]||`tier-${e}-default`}buildRationale(e,t,r){let s=[];return s.push(`Complexity: ${e.overall}/100`),s.push(`Tier ${r} selected`),t.wasDowngraded&&s.push(`Downgraded due to budget: ${t.reason}`),s.push(e.explanation),s.join(". ")}buildAlternatives(e,t){return e.alternateTiers.filter(r=>r!==t).map(r=>({tier:r,modelId:this.getModelIdForTier(r),reason:`Alternative tier ${r}`}))}recordMetrics(e,t){this.metrics.record({timestamp:e.metadata.timestamp,tier:e.tier,complexity:e.complexityAnalysis.overall,costUsd:e.budgetDecision.estimatedCostUsd,latencyMs:e.metadata.decisionTimeMs,wasDowngraded:e.budgetDecision.wasDowngraded,wasManualOverride:!1,agentBoosterEligible:e.agentBoosterEligible,success:t}),this.recordPersistentMetrics(e,t).catch(console.error)}async recordPersistentMetrics(e,t){if(this.persistentMetricsTracker)try{let r=`router-tier${e.tier}-${Date.now()}`;await this.persistentMetricsTracker.recordOutcome("router",r,t,e.metadata.decisionTimeMs,{subType:`tier-${e.tier}`,confidence:e.confidence,usedFallback:e.budgetDecision.wasDowngraded})}catch(r){console.warn("[ModelRouter] Failed to record persistent metrics:",r)}}};function H(u={},e,t){return new p(u,e,t)}async function $(u={},e){let{createAgentBoosterAdapter:t}=await import("./adapter-KCQDVYY2.js"),r=await t({enabled:!0}),s=new p(u,r,e);return await s.loadPatternsFromLoader(),s}export{p as a,H as b,$ as c};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{d as l,e as o}from"./chunk-
|
|
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.13");process.exit(0)}
|
|
2
|
+
import{d as l,e as o}from"./chunk-A64JFBWI.js";var t=n=>typeof n=="number"&&Number.isFinite(n)&&n>=0&&n<=100,i=n=>n===null||t(n);function a(n){if(!n||typeof n!="object")return null;let e=n;if(e.measured!==!0||!t(e.line)||!i(e.statement)||!i(e.branch)||!i(e.function))return null;let r=typeof e.files=="number"&&Number.isInteger(e.files)&&e.files>=0?e.files:null;return r===null?null:{line:e.line,branch:e.branch,function:e.function,statement:e.statement,files:r,measured:!0,...e.runStatus==="passed"||e.runStatus==="failed"?{runStatus:e.runStatus}:{}}}function m(n){if(!n||typeof n!="object")return null;let e=n;if(e.measured!==!0||!t(e.line))return null;let r=s=>t(s)?s:null;return{line:e.line,branch:r(e.branch),function:r(e.function),statement:r(e.statement),measured:!0}}o();var u=class extends Error{constructor(e,r){super(`git ${e.join(" ")} timed out after ${Math.max(0,r)}ms`),this.name="GitTimeoutError"}};async function b(n,e){if(e.timeout<=0)throw new u(n,e.timeout);try{return await l("git",n,{cwd:e.cwd,timeout:e.timeout,maxBuffer:e.maxBuffer,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}})}catch(r){throw r.code==="ETIMEDOUT"?new u(n,e.timeout):r}}export{a,m as b,u as c,b as d};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{b as Ee}from"./chunk-TLRHAMX5.js";import{a as St}from"./chunk-5TAEW5OV.js";import{a as bt,b as kt}from"./chunk-JR6CUKAI.js";import{a as vt,b as Ct}from"./chunk-UIKQPO4Y.js";import{j as _}from"./chunk-4HWUECVD.js";import{a as ht}from"./chunk-ENGL7FIJ.js";import{a as yt,b as xe,c as Tt}from"./chunk-GJKZ7UQO.js";import{a as Ae}from"./chunk-ZGROHCOW.js";import{b as ft}from"./chunk-SDRJJUPO.js";import{r as R,v as De}from"./chunk-L7NGKANW.js";import{b as I,d as mt}from"./chunk-WTAUF6O4.js";import{a as pt,e as Dn}from"./chunk-SPC4RBLF.js";import{i as C}from"./chunk-7TA5MUPW.js";import{a as v,c as y,d as f}from"./chunk-VZBC6DP7.js";import{a as Sn}from"./chunk-UJNGGFGX.js";import{c as gt}from"./chunk-ADUAJIAU.js";import{R as bn,S as kn}from"./chunk-35MIUSXQ.js";import{a as h,b as Z,e as k}from"./chunk-W4II6SIH.js";import{b as Y,d as Cn,f as dt}from"./chunk-WDEXOLK2.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.13");process.exit(0)}
|
|
2
|
+
import{b as Ee}from"./chunk-KUAKV3IW.js";import{a as St}from"./chunk-5ZGM3RMH.js";import{a as bt,b as kt}from"./chunk-42J34YG4.js";import{a as vt,b as Ct}from"./chunk-G2Q66Z23.js";import{j as _}from"./chunk-CT6SAVXQ.js";import{a as ht}from"./chunk-UDQSYWVF.js";import{a as yt,b as xe,c as Tt}from"./chunk-NZD4DPSU.js";import{a as Ae}from"./chunk-E7CLYGS7.js";import{b as ft}from"./chunk-GU5HNCWI.js";import{r as R,v as De}from"./chunk-3Y7TJFHU.js";import{b as I,d as mt}from"./chunk-VTOBUZL6.js";import{a as pt,e as Dn}from"./chunk-KDNJ4F3P.js";import{i as C}from"./chunk-H4H2YSFH.js";import{a as v,c as y,d as f}from"./chunk-NURIILUB.js";import{a as Sn}from"./chunk-UT2VZ33P.js";import{c as gt}from"./chunk-GB6HBNH2.js";import{R as bn,S as kn}from"./chunk-WOCGL4QP.js";import{a as h,b as Z,e as k}from"./chunk-3Y2ROSCL.js";import{b as Y,d as Cn,f as dt}from"./chunk-ZAKQLAHT.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(`
|
|
3
3
|
INSERT INTO mincut_snapshots (
|
|
4
4
|
id, timestamp, vertex_count, edge_count, total_weight,
|
|
5
5
|
is_connected, component_count, vertices_json, edges_json
|
|
@@ -177,4 +177,4 @@ import{b as Ee}from"./chunk-TLRHAMX5.js";import{a as St}from"./chunk-5TAEW5OV.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-FL26RTV3.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 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-TLGSSLMI.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};
|