agentic-qe 3.15.0 → 3.15.1
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 +44 -0
- package/assets/skills/skills-manifest.json +1 -1
- package/dist/cli/bundle.js +5 -5
- package/dist/cli/chunks/adapter-Q6RPGMUE.js +2 -0
- package/dist/cli/chunks/{agent-booster-wasm-GDHJ6QUN.js → agent-booster-wasm-XUHRLKWP.js} +2 -2
- package/dist/cli/chunks/{agent-handler-MPYYQ2RZ.js → agent-handler-CL7MJP5W.js} +2 -2
- package/dist/cli/chunks/{agent-memory-branch-QBSHKLA2.js → agent-memory-branch-F7RV72FC.js} +2 -2
- package/dist/cli/chunks/aqe-learning-engine-JQPXIU7C.js +2 -0
- package/dist/cli/chunks/{arena-UJE2FROF.js → arena-GRRNK7IN.js} +4 -4
- package/dist/cli/chunks/{arena-WIGSL37B.js → arena-LHLVOQHW.js} +2 -2
- package/dist/cli/chunks/{audit-VT7Y2Z7V.js → audit-EOP2K34L.js} +3 -3
- package/dist/cli/chunks/base-5SK64NXB.js +2 -0
- package/dist/cli/chunks/{better-sqlite3-DSL7LFRK.js → better-sqlite3-YERQ5DOL.js} +2 -2
- package/dist/cli/chunks/{brain-handler-N3C2MDMK.js → brain-handler-FBXBM5XE.js} +3 -3
- package/dist/cli/chunks/{branch-enumerator-B6NSQ3PZ.js → branch-enumerator-NWO6LNHB.js} +2 -2
- package/dist/cli/chunks/{browser-KQ3YNRGW.js → browser-EDCG7TNF.js} +2 -2
- package/dist/cli/chunks/browser-workflow-WN7XNTCJ.js +2 -0
- package/dist/cli/chunks/{chunk-QRALXNNX.js → chunk-25IWHVMW.js} +2 -2
- package/dist/cli/chunks/{chunk-ROK5YQ5P.js → chunk-27S47AYK.js} +2 -2
- package/dist/cli/chunks/{chunk-H77AUJNW.js → chunk-2IPBCXTT.js} +2 -2
- package/dist/cli/chunks/chunk-2K3QFLX2.js +2 -0
- package/dist/cli/chunks/{chunk-XPUY3ZKD.js → chunk-35XRY6ZW.js} +2 -2
- package/dist/cli/chunks/{chunk-ILKMNDUM.js → chunk-3NOSMJS4.js} +2 -2
- package/dist/cli/chunks/{chunk-N5ZHIQAV.js → chunk-3TZRJ5QD.js} +3 -3
- package/dist/cli/chunks/{chunk-OBSX3I4Y.js → chunk-46DUU44C.js} +2 -2
- package/dist/cli/chunks/{chunk-32YSI6OT.js → chunk-4AEFJEZH.js} +1 -1
- package/dist/cli/chunks/{chunk-KUTMQBV4.js → chunk-4KHSWNFW.js} +4 -4
- package/dist/cli/chunks/{chunk-FCSETOWZ.js → chunk-4KSCJ462.js} +1 -1
- package/dist/cli/chunks/{chunk-WPSGMTI4.js → chunk-4P7CGSRL.js} +3 -3
- package/dist/cli/chunks/{chunk-AQZSF32Y.js → chunk-4THIRDBL.js} +2 -2
- package/dist/cli/chunks/{chunk-5KN4QL3G.js → chunk-4XEZ562Q.js} +2 -2
- package/dist/cli/chunks/{chunk-PPFW3H7E.js → chunk-53C7TGC4.js} +1 -1
- package/dist/cli/chunks/{chunk-7WUHVGGT.js → chunk-53HWWWFZ.js} +2 -2
- package/dist/cli/chunks/{chunk-EBK6CUBD.js → chunk-54JYUOSR.js} +1 -1
- package/dist/cli/chunks/{chunk-ZPH2YT3J.js → chunk-5B5TA3X4.js} +2 -2
- package/dist/cli/chunks/{chunk-ATXAMGVE.js → chunk-5C4UYXQL.js} +2 -2
- package/dist/cli/chunks/{chunk-LDJ5DZT5.js → chunk-5JJWVFUV.js} +1 -1
- package/dist/cli/chunks/{chunk-7JABIXP3.js → chunk-5QEXDXHQ.js} +2 -2
- package/dist/cli/chunks/{chunk-A37YYHUD.js → chunk-5TEDVUEB.js} +2 -2
- package/dist/cli/chunks/{chunk-KU4WLKDK.js → chunk-66HKJJFH.js} +2 -2
- package/dist/cli/chunks/{chunk-ZXIIB3QE.js → chunk-6AVVC7Y3.js} +1 -1
- package/dist/cli/chunks/{chunk-PJU5HVWV.js → chunk-6DF6X3SZ.js} +2 -2
- package/dist/cli/chunks/{chunk-AW5OWYQ4.js → chunk-6MGJMGAD.js} +2 -2
- package/dist/cli/chunks/{chunk-WQMXQO3O.js → chunk-6Q7PWKWV.js} +2 -2
- package/dist/cli/chunks/{chunk-W6H2SOIK.js → chunk-6U6JQS4Z.js} +2 -2
- package/dist/cli/chunks/{chunk-4EEY23JS.js → chunk-6WW6A6JM.js} +2 -2
- package/dist/cli/chunks/{chunk-62IEVKN3.js → chunk-7B3XVVYP.js} +2 -2
- package/dist/cli/chunks/{chunk-OYVDTD3A.js → chunk-7FGSX4UD.js} +2 -2
- package/dist/cli/chunks/{chunk-MEYSIVMP.js → chunk-A5LOELVV.js} +2 -2
- package/dist/cli/chunks/{chunk-HOPXHZA3.js → chunk-ADEYBXAS.js} +2 -2
- package/dist/cli/chunks/{chunk-L6PUBB6L.js → chunk-ALLABEUK.js} +2 -2
- package/dist/cli/chunks/{chunk-MM57SD2F.js → chunk-ARGMYSDY.js} +1 -1
- package/dist/cli/chunks/{chunk-X5RELRY7.js → chunk-ARWSPV2C.js} +2 -2
- package/dist/cli/chunks/{chunk-JSYNSJDQ.js → chunk-AVOYMVD6.js} +2 -2
- package/dist/cli/chunks/{chunk-MFGLRMO4.js → chunk-B3DWOR5R.js} +1 -1
- package/dist/cli/chunks/{chunk-O5AUOBGU.js → chunk-BW7S6LIJ.js} +2 -2
- package/dist/cli/chunks/{chunk-FPTZP7W5.js → chunk-C3BW3Q27.js} +1 -1
- package/dist/cli/chunks/{chunk-S644OORE.js → chunk-CFZJEOCD.js} +1 -1
- package/dist/cli/chunks/{chunk-KEZ4PXVF.js → chunk-CHX65QXY.js} +1 -1
- package/dist/cli/chunks/{chunk-AAQNRZKT.js → chunk-CTK7NMSJ.js} +2 -2
- package/dist/cli/chunks/{chunk-2ORTL5WG.js → chunk-CTLHNFPM.js} +1 -1
- package/dist/cli/chunks/{chunk-6GTIJNRO.js → chunk-D3LREV4P.js} +1 -1
- package/dist/cli/chunks/{chunk-F76SYOBT.js → chunk-DKWB4ERY.js} +1 -1
- package/dist/cli/chunks/{chunk-R6CZCMKD.js → chunk-DREYYJ7A.js} +2 -2
- package/dist/cli/chunks/{chunk-VY4557VF.js → chunk-DV7I6CRH.js} +2 -2
- package/dist/cli/chunks/{chunk-WPOYFV4X.js → chunk-EQ3BJS37.js} +1 -1
- package/dist/cli/chunks/{chunk-4YPL3OXS.js → chunk-FIIHSEXP.js} +2 -2
- package/dist/cli/chunks/{chunk-Z6CRROLU.js → chunk-FQYXPSWD.js} +2 -2
- package/dist/cli/chunks/{chunk-5DJGP4TA.js → chunk-FRGNM6SW.js} +2 -2
- package/dist/cli/chunks/{chunk-P7MNF2SK.js → chunk-FTHXV7N7.js} +2 -2
- package/dist/cli/chunks/{chunk-ISAMM7QA.js → chunk-GAKVCN3C.js} +1 -1
- package/dist/cli/chunks/{chunk-IRHBR56R.js → chunk-GDSYJHVB.js} +1 -1
- package/dist/cli/chunks/{chunk-AV3RX2L5.js → chunk-GUHJWBPN.js} +2 -2
- package/dist/cli/chunks/{chunk-XEABMIUH.js → chunk-GUKBN3BS.js} +2 -2
- package/dist/cli/chunks/{chunk-URUOTHPO.js → chunk-HU4QGCIJ.js} +2 -2
- package/dist/cli/chunks/{chunk-PN3FYSQ6.js → chunk-HVAYG54D.js} +2 -2
- package/dist/cli/chunks/{chunk-JYRBOSOF.js → chunk-IUGY6Z4Q.js} +2 -2
- package/dist/cli/chunks/{chunk-MRIZY6HB.js → chunk-J2WALRWR.js} +2 -2
- package/dist/cli/chunks/{chunk-WO7NPGUD.js → chunk-J4ULR4QR.js} +3 -3
- package/dist/cli/chunks/{chunk-FTS6NGBP.js → chunk-JEXPSOT2.js} +2 -2
- package/dist/cli/chunks/{chunk-LLS6JYPN.js → chunk-JHKMUY4W.js} +2 -2
- package/dist/cli/chunks/{chunk-Q4RCUCHD.js → chunk-JQVECGYL.js} +1 -1
- package/dist/cli/chunks/{chunk-EQ4SDE4L.js → chunk-JSHASVQ2.js} +3 -3
- package/dist/cli/chunks/{chunk-AGYPPPXR.js → chunk-JW2HNT3J.js} +2 -2
- package/dist/cli/chunks/{chunk-M5EKZA7Q.js → chunk-JY6HWYC4.js} +1 -1
- package/dist/cli/chunks/{chunk-YFRZVNE4.js → chunk-JYF3QF4C.js} +2 -2
- package/dist/cli/chunks/{chunk-QVX22EIM.js → chunk-K4NB3MYN.js} +2 -2
- package/dist/cli/chunks/{chunk-JIWMFLHV.js → chunk-KBK4GBJQ.js} +2 -2
- package/dist/cli/chunks/{chunk-JO2YLIZH.js → chunk-KHVWIUAF.js} +2 -2
- package/dist/cli/chunks/{chunk-P2PPJUGD.js → chunk-KP6LNSDO.js} +10 -10
- package/dist/cli/chunks/{chunk-J4XCBOPA.js → chunk-KTBA2HJC.js} +2 -2
- package/dist/cli/chunks/{chunk-VTGRGYY4.js → chunk-L5GEWKR3.js} +3 -3
- package/dist/cli/chunks/{chunk-7JC3LHA6.js → chunk-LDDIYDIP.js} +10 -10
- package/dist/cli/chunks/{chunk-J46XGXPS.js → chunk-LI7N45GM.js} +1 -1
- package/dist/cli/chunks/{chunk-MO3QXLF2.js → chunk-LQI5GVH7.js} +1 -1
- package/dist/cli/chunks/{chunk-HBIV7PQH.js → chunk-MEOAKMKF.js} +1 -1
- package/dist/cli/chunks/{chunk-S7QUHLXV.js → chunk-N4HQ6FE2.js} +1 -1
- package/dist/cli/chunks/{chunk-4DCDIKBX.js → chunk-N5OSH5JO.js} +2 -2
- package/dist/cli/chunks/{chunk-XZDPR6I2.js → chunk-NF6SLLE6.js} +2 -2
- package/dist/cli/chunks/{chunk-WR54SKKL.js → chunk-NGDRSF6Y.js} +2 -2
- package/dist/cli/chunks/{chunk-N2MDNEF7.js → chunk-NK2BR4QZ.js} +2 -2
- package/dist/cli/chunks/{chunk-2ZEV3O24.js → chunk-NS4RIZ4F.js} +1 -1
- package/dist/cli/chunks/{chunk-JLPNYHJJ.js → chunk-NTLWHLAY.js} +1 -1
- package/dist/cli/chunks/{chunk-LPCFIFZF.js → chunk-NWNZMXNO.js} +2 -2
- package/dist/cli/chunks/{chunk-NZ556KZN.js → chunk-OABFAREV.js} +2 -2
- package/dist/cli/chunks/{chunk-WDV6CBED.js → chunk-OH4SKOAM.js} +2 -2
- package/dist/cli/chunks/{chunk-XELFJC77.js → chunk-OKS25EGZ.js} +3 -3
- package/dist/cli/chunks/{chunk-4FOKHGP5.js → chunk-OPBPFNBO.js} +2 -2
- package/dist/cli/chunks/{chunk-6MN4L6BS.js → chunk-P24ZBDZY.js} +2 -2
- package/dist/cli/chunks/{chunk-5PNRUMRV.js → chunk-PBWR2SKH.js} +2 -2
- package/dist/cli/chunks/{chunk-S7CROKX4.js → chunk-PDLVO3ZR.js} +2 -2
- package/dist/cli/chunks/{chunk-I3BH3KIF.js → chunk-PGARKOE6.js} +1 -1
- package/dist/cli/chunks/{chunk-GX5RFGW2.js → chunk-PNK5KHSI.js} +1 -1
- package/dist/cli/chunks/{chunk-3Y24VTZ3.js → chunk-PZBYZV5M.js} +1 -1
- package/dist/cli/chunks/{chunk-BH2SQQ2N.js → chunk-PZDI7WQ3.js} +1 -1
- package/dist/cli/chunks/{chunk-VQVFGFYK.js → chunk-Q7ONRZBD.js} +1 -1
- package/dist/cli/chunks/{chunk-DGRE6ZAA.js → chunk-QMHWJBD3.js} +2 -2
- package/dist/cli/chunks/{chunk-Y63DADOR.js → chunk-QOOADAT7.js} +2 -2
- package/dist/cli/chunks/{chunk-GRN47ANK.js → chunk-QVTV47TM.js} +2 -2
- package/dist/cli/chunks/{chunk-F7JVDLOI.js → chunk-R2ICZKQA.js} +2 -2
- package/dist/cli/chunks/{chunk-GCHDMO5V.js → chunk-RDI3W4H6.js} +2 -2
- package/dist/cli/chunks/{chunk-S2GNFAOC.js → chunk-REGPCPEJ.js} +2 -2
- package/dist/cli/chunks/{chunk-DSGRXW6K.js → chunk-RXKOZ6VS.js} +3 -3
- package/dist/cli/chunks/{chunk-GV7P5JYF.js → chunk-SRXXPZVT.js} +2 -2
- package/dist/cli/chunks/{chunk-YIDZ3TEN.js → chunk-SUFXUM6W.js} +2 -2
- package/dist/cli/chunks/{chunk-FFE4XAQA.js → chunk-T5K6ZCA6.js} +1 -1
- package/dist/cli/chunks/{chunk-OLD2CIDI.js → chunk-TBCQWD5A.js} +1 -1
- package/dist/cli/chunks/{chunk-X7JEBPEW.js → chunk-TCJ65NPY.js} +1 -1
- package/dist/cli/chunks/{chunk-EZPWSS3B.js → chunk-TJCMG3QE.js} +2 -2
- package/dist/cli/chunks/{chunk-P4WE6VRR.js → chunk-TLUMENRZ.js} +2 -2
- package/dist/cli/chunks/{chunk-7D6NVIGP.js → chunk-TR37Q7A6.js} +2 -2
- package/dist/cli/chunks/{chunk-UGYXUPGN.js → chunk-UE33MZOC.js} +2 -2
- package/dist/cli/chunks/{chunk-5LN7FQZI.js → chunk-UGUZFUQG.js} +2 -2
- package/dist/cli/chunks/{chunk-CZWWC7GC.js → chunk-UOHZRR5C.js} +1 -1
- package/dist/cli/chunks/{chunk-VCYOFWMG.js → chunk-UTFNHITI.js} +2 -2
- package/dist/cli/chunks/{chunk-FTFIA4I5.js → chunk-V3ISBQ5Q.js} +2 -2
- package/dist/cli/chunks/{chunk-ISGFAMHZ.js → chunk-V5RP2SU3.js} +2 -2
- package/dist/cli/chunks/{chunk-ANUZGOLQ.js → chunk-VEKRK3R6.js} +2 -2
- package/dist/cli/chunks/{chunk-P4FRYNHL.js → chunk-VGYLV6VD.js} +1 -1
- package/dist/cli/chunks/{chunk-DZHIE5UW.js → chunk-VLL7ASGH.js} +2 -2
- package/dist/cli/chunks/{chunk-VT5SMBEM.js → chunk-W5HQQTVH.js} +1 -1
- package/dist/cli/chunks/{chunk-JJ7WAU4I.js → chunk-W5NHBYYS.js} +2 -2
- package/dist/cli/chunks/{chunk-URRPJ3M7.js → chunk-W6K77PQR.js} +1 -1
- package/dist/cli/chunks/{chunk-ZV7LJPSI.js → chunk-WFDDWRWY.js} +5 -5
- package/dist/cli/chunks/{chunk-OTJ22IO2.js → chunk-WHBDSJUE.js} +3 -3
- package/dist/cli/chunks/{chunk-VYERAOQL.js → chunk-WONHFDWF.js} +2 -2
- package/dist/cli/chunks/{chunk-WBR4VRQE.js → chunk-WPG6SW7C.js} +2 -2
- package/dist/cli/chunks/{chunk-B6QTNTCU.js → chunk-WQZR6DS6.js} +2 -2
- package/dist/cli/chunks/{chunk-4BWDCUZZ.js → chunk-WTFVYFRZ.js} +1 -1
- package/dist/cli/chunks/{chunk-DXA7RLYU.js → chunk-WYE3ICSL.js} +2 -2
- package/dist/cli/chunks/{chunk-KLGFEHEN.js → chunk-X4PGLEPQ.js} +2 -2
- package/dist/cli/chunks/{chunk-P725KXHX.js → chunk-X6W35QXO.js} +2 -2
- package/dist/cli/chunks/{chunk-BAPMEDWC.js → chunk-XCVD57GW.js} +1 -1
- package/dist/cli/chunks/{chunk-3DKYBHNA.js → chunk-XYZUBAR6.js} +4 -4
- package/dist/cli/chunks/{chunk-VWCFXCSV.js → chunk-XZGRHJGC.js} +2 -2
- package/dist/cli/chunks/{chunk-X4OESN7M.js → chunk-YDM2DPUU.js} +2 -2
- package/dist/cli/chunks/{chunk-4OQSAUKR.js → chunk-YDMPTCJ3.js} +2 -2
- package/dist/cli/chunks/{chunk-CMYZWIXS.js → chunk-YM3GAJMN.js} +2 -2
- package/dist/cli/chunks/{chunk-FZ3TQAPW.js → chunk-YTMWPGVR.js} +1 -1
- package/dist/cli/chunks/{chunk-D7NOHASX.js → chunk-YWX7KLNG.js} +3 -3
- package/dist/cli/chunks/{chunk-G35KP72N.js → chunk-ZE6WJDXM.js} +2 -2
- package/dist/cli/chunks/{chunk-C6M27NQE.js → chunk-ZX4I7IND.js} +2 -2
- package/dist/cli/chunks/{chunk-EPEKEUCF.js → chunk-ZZV6GR46.js} +1 -1
- package/dist/cli/chunks/{ci-63JINRNB.js → ci-K7DG4GSO.js} +3 -3
- package/dist/cli/chunks/{ci-output-CRFWLUAA.js → ci-output-EBSUG6HP.js} +2 -2
- package/dist/cli/chunks/{circuit-breaker-PJLG3WYL.js → circuit-breaker-P6N6YIRZ.js} +2 -2
- package/dist/cli/chunks/{claude-flow-setup-UKHSQMJU.js → claude-flow-setup-P6EZPQZT.js} +2 -2
- package/dist/cli/chunks/client-ZYH66YRI.js +2 -0
- package/dist/cli/chunks/{cline-installer-PYQ27AS3.js → cline-installer-EVZZ3EFY.js} +2 -2
- package/dist/cli/chunks/{code-K7VGLZ3W.js → code-3WLBG2XK.js} +3 -3
- package/dist/cli/chunks/{code-index-extractor-NNWAVWSL.js → code-index-extractor-ZP6D4WL2.js} +2 -2
- package/dist/cli/chunks/{codex-installer-U4VJIKRN.js → codex-installer-XAUI4SB7.js} +2 -2
- package/dist/cli/chunks/{completions-DOCI3P4W.js → completions-RHFNDDG3.js} +2 -2
- package/dist/cli/chunks/{complexity-analyzer-RFW2QRFR.js → complexity-analyzer-DCW7Q3OR.js} +2 -2
- package/dist/cli/chunks/{continuedev-installer-S5WXXOBU.js → continuedev-installer-53SQA5T6.js} +2 -2
- package/dist/cli/chunks/{copilot-installer-AAQ6YLVJ.js → copilot-installer-SXXMFB6T.js} +2 -2
- package/dist/cli/chunks/core-handlers-XKSPHEHE.js +2 -0
- package/dist/cli/chunks/{cost-tracker-R4VOHTWQ.js → cost-tracker-CKLDQ5AZ.js} +2 -2
- package/dist/cli/chunks/{coverage-P54HPCLV.js → coverage-AWCS2SP7.js} +3 -3
- package/dist/cli/chunks/cross-domain-router-6VYNFQZA.js +2 -0
- package/dist/cli/chunks/{cursor-installer-VHBWZE5A.js → cursor-installer-4TYF5V5J.js} +2 -2
- package/dist/cli/chunks/{daemon-JLH5TTWZ.js → daemon-CTZXGN5V.js} +4 -4
- package/dist/cli/chunks/{daemon-BTRSWNB4.js → daemon-OOY4H6RJ.js} +3 -3
- package/dist/cli/chunks/{dag-attention-scheduler-5Z6DCRFK.js → dag-attention-scheduler-3WG24Q33.js} +2 -2
- package/dist/cli/chunks/{detect-NWGASRJJ.js → detect-O7MUZ6NX.js} +2 -2
- package/dist/cli/chunks/{dist-node-XMNNSEFJ.js → dist-node-H4XI7BAF.js} +2 -2
- package/dist/cli/chunks/{domain-handler-BWVBZTNR.js → domain-handler-FU4WZ23B.js} +2 -2
- package/dist/cli/chunks/{domain-plugins-YAD4USA4.js → domain-plugins-XK26KYNJ.js} +2 -2
- package/dist/cli/chunks/{domain-transfer-Z3MRPZEZ.js → domain-transfer-6B5NOVH6.js} +2 -2
- package/dist/cli/chunks/dream-DRSSIHPP.js +2 -0
- package/dist/cli/chunks/{embed-and-insert-pattern-5CCO45WC.js → embed-and-insert-pattern-XNZXPZNL.js} +2 -2
- package/dist/cli/chunks/{eval-JEMLTGY4.js → eval-J3Q5TTI7.js} +2 -2
- package/dist/cli/chunks/{experience-capture-middleware-FKVYBBAN.js → experience-capture-middleware-COKIGMXW.js} +3 -3
- package/dist/cli/chunks/{fast-paths-TFL32H3C.js → fast-paths-IHWPJI6I.js} +2 -2
- package/dist/cli/chunks/{feature-flags-CNGAUUMT.js → feature-flags-G7ONDNTT.js} +2 -2
- package/dist/cli/chunks/{feature-flags-OHGD2NCW.js → feature-flags-WUXFWZLR.js} +2 -2
- package/dist/cli/chunks/{file-discovery-IHGDYW34.js → file-discovery-JN3YMBOJ.js} +2 -2
- package/dist/cli/chunks/{fleet-OGTSDGJ2.js → fleet-OUHUZJE4.js} +3 -3
- package/dist/cli/chunks/{gnn-wrapper-QYTTKNCE.js → gnn-wrapper-PRH55ZT6.js} +2 -2
- package/dist/cli/chunks/{heartbeat-handler-R5OD2SKN.js → heartbeat-handler-6YF35AQS.js} +4 -4
- package/dist/cli/chunks/heartbeat-scheduler-FMICCNWK.js +2 -0
- package/dist/cli/chunks/hnsw-adapter-4TGBNJEZ.js +2 -0
- package/dist/cli/chunks/hnsw-index-J4NSCPAZ.js +2 -0
- package/dist/cli/chunks/{hnsw-legacy-bridge-ULJWYXBQ.js → hnsw-legacy-bridge-7PAFSTJO.js} +2 -2
- package/dist/cli/chunks/{hnswlib-node-SYKJXGE2.js → hnswlib-node-UETDZNNN.js} +2 -2
- package/dist/cli/chunks/{hooks-XAJXPXTU.js → hooks-QQNUKQAS.js} +10 -10
- package/dist/cli/chunks/hybrid-backend-NKPA3QE7.js +2 -0
- package/dist/cli/chunks/{hypergraph-engine-GIBPGW4N.js → hypergraph-engine-5GDGE3ET.js} +2 -2
- package/dist/cli/chunks/{hypergraph-handler-ENFK6IDN.js → hypergraph-handler-C3F2OJYA.js} +3 -3
- package/dist/cli/chunks/impact-analyzer-MWX7XY7X.js +2 -0
- package/dist/cli/chunks/{init-handler-CSA62LGT.js → init-handler-C7ZBDAC5.js} +6 -6
- package/dist/cli/chunks/init-wizard-EX5N5Q7X.js +2 -0
- package/dist/cli/chunks/kernel-EQLZDHDD.js +2 -0
- package/dist/cli/chunks/{kilocode-installer-YXFIRTSA.js → kilocode-installer-VLJENC76.js} +2 -2
- package/dist/cli/chunks/{kiro-installer-JW3BG2MQ.js → kiro-installer-UYPYM6LA.js} +2 -2
- package/dist/cli/chunks/knowledge-graph-A3WSMQ6U.js +2 -0
- package/dist/cli/chunks/{learning-BDBZ7ZVG.js → learning-SFIWIG6Z.js} +3 -3
- package/dist/cli/chunks/{llm-router-CCX2DYTC.js → llm-router-V633KAS5.js} +4 -4
- package/dist/cli/chunks/llm-router-service-A6XYWTL6.js +2 -0
- package/dist/cli/chunks/{load-UJTTEOOK.js → load-UWZV4JRA.js} +2 -2
- package/dist/cli/chunks/load-test-WF2PCXLI.js +2 -0
- package/dist/cli/chunks/{mcp-2NAJYREC.js → mcp-XVFHUKCP.js} +2 -2
- package/dist/cli/chunks/{memory-C3UQSN5F.js → memory-BQ5652VK.js} +5 -5
- package/dist/cli/chunks/memory-backend-BKGLI2RF.js +2 -0
- package/dist/cli/chunks/{memory-handlers-ESFIJENU.js → memory-handlers-PWI3G4P4.js} +2 -2
- package/dist/cli/chunks/{multi-model-executor-SIHSHAD7.js → multi-model-executor-X6AQ7VVR.js} +2 -2
- package/dist/cli/chunks/{opencode-installer-KDYHUGPG.js → opencode-installer-N3V2Z4EF.js} +2 -2
- package/dist/cli/chunks/{orchestrator-MJHIQEHD.js → orchestrator-KNEKS4F7.js} +5 -5
- package/dist/cli/chunks/pattern-null-store-YTBLEH7D.js +2 -0
- package/dist/cli/chunks/{pattern-usage-recorder-OLBE4UIF.js → pattern-usage-recorder-MZIM6XWU.js} +2 -2
- package/dist/cli/chunks/{pipeline-IOK2CV3U.js → pipeline-LNLBKSXR.js} +2 -2
- package/dist/cli/chunks/{platform-53JQ7JXN.js → platform-OMUDXHD3.js} +2 -2
- package/dist/cli/chunks/{plugin-L5SDIWDI.js → plugin-HGY6KKZW.js} +2 -2
- package/dist/cli/chunks/{prime-radiant-advanced-wasm-2DS67JFS.js → prime-radiant-advanced-wasm-LZBHLQYN.js} +2 -2
- package/dist/cli/chunks/{project-root-LQMOFO2Z.js → project-root-VPSCDBMD.js} +2 -2
- package/dist/cli/chunks/protocol-executor-HFR2D54O.js +2 -0
- package/dist/cli/chunks/{protocol-handler-NXG2M43B.js → protocol-handler-LZXT3TXU.js} +2 -2
- package/dist/cli/chunks/{prove-7K7PFSSX.js → prove-I4VKQEYQ.js} +2 -2
- package/dist/cli/chunks/qe-reasoning-bank-MYFBQUYV.js +2 -0
- package/dist/cli/chunks/{quality-ATILUGMJ.js → quality-VVAWK2DD.js} +2 -2
- package/dist/cli/chunks/{quality-gate-MPZMDPIZ.js → quality-gate-RGXLWYT6.js} +3 -3
- package/dist/cli/chunks/queen-coordinator-CQQMOTIW.js +2 -0
- package/dist/cli/chunks/{real-embeddings-VZN3KIAI.js → real-embeddings-WM66PMQ6.js} +2 -2
- package/dist/cli/chunks/{ref-validation-EUATPVXX.js → ref-validation-ZIWJNI6M.js} +2 -2
- package/dist/cli/chunks/{roocode-installer-7M2GOUNZ.js → roocode-installer-QYSI3STC.js} +2 -2
- package/dist/cli/chunks/router-GKWLPA3N.js +2 -0
- package/dist/cli/chunks/routing-feedback-WA4D5JRF.js +2 -0
- package/dist/cli/chunks/{routing-handler-VWANE652.js → routing-handler-BID3EOLE.js} +2 -2
- package/dist/cli/chunks/{ruvector-commands-B2YIPGOV.js → ruvector-commands-DXIFMF4W.js} +2 -2
- package/dist/cli/chunks/rvf-dual-writer-H3ZXS5MA.js +2 -0
- package/dist/cli/chunks/rvf-migration-adapter-J7MTCOQA.js +2 -0
- package/dist/cli/chunks/{rvf-migration-coordinator-RQXOQJ5T.js → rvf-migration-coordinator-EV5E6SAO.js} +2 -2
- package/dist/cli/chunks/rvf-native-adapter-HXBY4VYI.js +2 -0
- package/dist/cli/chunks/{rvf-store-integrity-7P5YDXRH.js → rvf-store-integrity-IT6DCCJK.js} +2 -2
- package/dist/cli/chunks/safe-db-INVJ5LHR.js +2 -0
- package/dist/cli/chunks/schedule-XRIPPL52.js +2 -0
- package/dist/cli/chunks/scheduler-HBN3KPRW.js +2 -0
- package/dist/cli/chunks/{security-VJ7TVSQF.js → security-AAFAEATQ.js} +3 -3
- package/dist/cli/chunks/{shared-rvf-adapter-63NXQFBX.js → shared-rvf-adapter-QIHSYHAF.js} +2 -2
- package/dist/cli/chunks/{shared-rvf-dual-writer-JQRP7P5A.js → shared-rvf-dual-writer-V7OZ6TBR.js} +2 -2
- package/dist/cli/chunks/sqlite-persistence-6KNLT5Q2.js +2 -0
- package/dist/cli/chunks/{standalone-memory-WJ72PH5P.js → standalone-memory-ALZI6VPX.js} +2 -2
- package/dist/cli/chunks/{status-handler-G72ZSLAX.js → status-handler-DED5A3OW.js} +2 -2
- package/dist/cli/chunks/{structural-health-HYBGP4BD.js → structural-health-CB7L3NWH.js} +2 -2
- package/dist/cli/chunks/{sync-O5FQAHT7.js → sync-QNPGETIO.js} +2 -2
- package/dist/cli/chunks/{sync-5YMZZIF4.js → sync-S6Z2U46T.js} +2 -2
- package/dist/cli/chunks/{task-handler-E6IFNHZG.js → task-handler-CGHXYFIF.js} +2 -2
- package/dist/cli/chunks/{task-handlers-P3GC2L5L.js → task-handlers-A6BGQJIB.js} +3 -3
- package/dist/cli/chunks/{test-OU6ERW67.js → test-IISTF5W6.js} +4 -4
- package/dist/cli/chunks/{test-scheduling-3HY4I3HY.js → test-scheduling-FKYX4OLF.js} +3 -3
- package/dist/cli/chunks/{token-bootstrap-A5QA4CWK.js → token-bootstrap-OKO3JEKT.js} +2 -2
- package/dist/cli/chunks/{token-usage-MUNQVPFT.js → token-usage-25BRFKJ5.js} +2 -2
- package/dist/cli/chunks/{transformers-IEO25W5V.js → transformers-TBVVSZMF.js} +2 -2
- package/dist/cli/chunks/{tree-sitter-wasm-parser-T2EQHEAY.js → tree-sitter-wasm-parser-N7KCOQT4.js} +2 -2
- package/dist/cli/chunks/{types-ODCPGCID.js → types-TFHWJGRK.js} +2 -2
- package/dist/cli/chunks/unified-memory-WVELSL6T.js +2 -0
- package/dist/cli/chunks/unified-memory-hnsw-7P5MVKXD.js +2 -0
- package/dist/cli/chunks/unified-persistence-YLFCEWYY.js +2 -0
- package/dist/cli/chunks/{upgrade-4DN6EIW2.js → upgrade-4VWQU7RD.js} +2 -2
- package/dist/cli/chunks/{validate-TBNAPDE3.js → validate-FF7WVXMP.js} +2 -2
- package/dist/cli/chunks/{validate-swarm-ZN7XXUY4.js → validate-swarm-NRLH4EDC.js} +2 -2
- package/dist/cli/chunks/visual-security-T5OM742H.js +2 -0
- package/dist/cli/chunks/{web-tree-sitter-DWAWVD2X.js → web-tree-sitter-VVU3LULW.js} +2 -2
- package/dist/cli/chunks/{windsurf-installer-U6EROS5S.js → windsurf-installer-Q2ZNWG2D.js} +2 -2
- package/dist/cli/chunks/witness-chain-D6X4OZP5.js +2 -0
- package/dist/cli/chunks/{witness-chain-EQEJS2P4.js → witness-chain-FP3D4PQL.js} +2 -2
- package/dist/cli/chunks/{witness-chain-repair-KBXDRXS3.js → witness-chain-repair-3LG4BF7C.js} +2 -2
- package/dist/cli/chunks/{witness-chain-verifier-HSQGZ4R4.js → witness-chain-verifier-LACGL6BK.js} +2 -2
- package/dist/cli/chunks/{witness-key-manager-RAODG73T.js → witness-key-manager-GQZIB5ZE.js} +2 -2
- package/dist/cli/chunks/{workflow-KNFJNNKG.js → workflow-JPA5Y7L6.js} +4 -4
- package/dist/cli/chunks/workflow-orchestrator-OORDDKT3.js +2 -0
- package/dist/cli/chunks/{wrappers-NIJBA22T.js → wrappers-2B5NHICD.js} +2 -2
- package/dist/mcp/bundle.js +3 -3
- package/package.json +1 -1
- package/dist/cli/chunks/adapter-D7G5MIDQ.js +0 -2
- package/dist/cli/chunks/aqe-learning-engine-G6TUFGHC.js +0 -2
- package/dist/cli/chunks/base-B45BOC7E.js +0 -2
- package/dist/cli/chunks/browser-workflow-MIBU4XMV.js +0 -2
- package/dist/cli/chunks/chunk-AIE6OKCD.js +0 -2
- package/dist/cli/chunks/client-A4FTITK3.js +0 -2
- package/dist/cli/chunks/core-handlers-FO3QTNWI.js +0 -2
- package/dist/cli/chunks/cross-domain-router-LIV6SRWF.js +0 -2
- package/dist/cli/chunks/dream-DNLGHYXY.js +0 -2
- package/dist/cli/chunks/heartbeat-scheduler-DL4LXXJF.js +0 -2
- package/dist/cli/chunks/hnsw-adapter-Y64M43J4.js +0 -2
- package/dist/cli/chunks/hnsw-index-5V6DDMTA.js +0 -2
- package/dist/cli/chunks/hybrid-backend-JWT2V4FQ.js +0 -2
- package/dist/cli/chunks/impact-analyzer-XUZQSZZC.js +0 -2
- package/dist/cli/chunks/init-wizard-KDJKHEPN.js +0 -2
- package/dist/cli/chunks/kernel-MUDYPGFR.js +0 -2
- package/dist/cli/chunks/knowledge-graph-GR52N7PU.js +0 -2
- package/dist/cli/chunks/llm-router-service-QL6LVKZ4.js +0 -2
- package/dist/cli/chunks/load-test-76V75WZ5.js +0 -2
- package/dist/cli/chunks/memory-backend-SMQRS5QN.js +0 -2
- package/dist/cli/chunks/pattern-null-store-MWAJMOYU.js +0 -2
- package/dist/cli/chunks/protocol-executor-32X3GAJT.js +0 -2
- package/dist/cli/chunks/qe-reasoning-bank-KAFV3TGI.js +0 -2
- package/dist/cli/chunks/queen-coordinator-L3SODGRX.js +0 -2
- package/dist/cli/chunks/router-DDCSSXYQ.js +0 -2
- package/dist/cli/chunks/routing-feedback-RFASKYCD.js +0 -2
- package/dist/cli/chunks/rvf-dual-writer-HCIF2G56.js +0 -2
- package/dist/cli/chunks/rvf-migration-adapter-UVAHQ7SV.js +0 -2
- package/dist/cli/chunks/rvf-native-adapter-F2I5FFHK.js +0 -2
- package/dist/cli/chunks/safe-db-6ZAA4S23.js +0 -2
- package/dist/cli/chunks/schedule-SM5Q6UVP.js +0 -2
- package/dist/cli/chunks/scheduler-4EYP4EZ6.js +0 -2
- package/dist/cli/chunks/sqlite-persistence-KLN2K266.js +0 -2
- package/dist/cli/chunks/unified-memory-B5IA2KKQ.js +0 -2
- package/dist/cli/chunks/unified-memory-hnsw-YF74LL3Z.js +0 -2
- package/dist/cli/chunks/unified-persistence-VZMGNGWY.js +0 -2
- package/dist/cli/chunks/visual-security-ZV3BLLSH.js +0 -2
- package/dist/cli/chunks/witness-chain-OA24MQWX.js +0 -2
- package/dist/cli/chunks/workflow-orchestrator-IMX2LSVE.js +0 -2
package/dist/mcp/bundle.js
CHANGED
|
@@ -867,7 +867,7 @@ ${wM}
|
|
|
867
867
|
);
|
|
868
868
|
CREATE INDEX IF NOT EXISTS idx_kv_namespace ON kv_store(namespace);
|
|
869
869
|
`),sl=r,r}catch{return UM=!0,null}}function Pj(o){let e=kj();if(!e)return null;try{let t=e.prepare("SELECT value FROM kv_store WHERE namespace = ? AND key = ?").get(Aj,xj+o);if(!t)return null;let r=JSON.parse(t.value);return!r.fingerprint||typeof r.dim!="number"?null:{fingerprint:r.fingerprint,dim:r.dim,endpoint:r.endpoint}}catch{return null}}function Mj(o){let e=kj();if(!e)return;let t={fingerprint:o.fingerprint,dim:o.dim,endpoint:o.endpoint,updatedAt:Date.now()};e.prepare("INSERT OR REPLACE INTO kv_store (key, namespace, value) VALUES (?, ?, ?)").run(xj+o.endpoint,Aj,JSON.stringify(t))}function Ij(){if(sl)try{sl.close()}catch{}sl=null,UM=!1}var qge,Aj,xj,sl,UM,Dj=b(()=>{"use strict";Si();qge=$ge(import.meta.url);Aj="_system",xj="embedder_identity:",sl=null,UM=!1});import{createHash as _j}from"node:crypto";import{existsSync as Uge,readFileSync as zge,renameSync as Vge,writeFileSync as Gge}from"node:fs";function Hge(o){return JSON.stringify({provider:o.provider,model:o.model,dimensions:o.dimensions,pooling:o.pooling??null,normalized:o.normalized,preprocessingVersion:o.preprocessingVersion??null,implementation:o.implementation??null,runtimeFingerprint:o.runtimeFingerprint})}function Lj(o){let e=Buffer.alloc(o.length*2);for(let t=0;t<o.length;t++){let r=Math.max(-32768,Math.min(32767,Math.round(o[t]*32767)));e.writeInt16LE(r,t*2)}return _j("sha256").update(e).digest("hex").slice(0,16)}function zM(o){if(!o.runtimeFingerprint)throw new Error("Embedding space identity requires executable runtime evidence");let e=_j("sha256").update("aqe:embedding-space:v1\0").update(Hge(o)).digest("hex");return{...o,spaceId:e}}function Oj(o,e){let t=[...new Set(o.flatMap(a=>a.spaceId?[a.spaceId]:[]))].sort(),r=o.filter(a=>!a.spaceId).length,n=e?o.filter(a=>a.spaceId===e).length:0,i=e?o.filter(a=>a.spaceId!==null&&a.spaceId!==e).length:o.length-r;return{status:r>0||!e?"unverified":i>0||t.length>1?"vector_space_mismatch":"healthy",activeSpaceId:e,storedSpaceIds:t,verifiedVectors:n,mismatchedVectors:i,unverifiedVectors:r}}function Wge(o){return`${o}.space.json`}function Jb(o,e,t){if(!e)throw new Xa("VECTOR_SPACE_UNVERIFIED",`cannot open ANN index ${o} without runtime provenance`);let r=Wge(o);if(Uge(r)){let s;try{s=JSON.parse(zge(r,"utf8"))}catch{throw new Xa("VECTOR_SPACE_UNVERIFIED",`ANN index manifest ${r} is unreadable`)}if(s.version!==1||!s.spaceId)throw new Xa("VECTOR_SPACE_UNVERIFIED",`ANN index manifest ${r} has no verified space`);if(s.spaceId!==e)throw new Xa("VECTOR_SPACE_MISMATCH",`ANN index space ${s.spaceId} != active space ${e}`);return}if(t>0)throw new Xa("VECTOR_SPACE_UNVERIFIED",`populated ANN index ${o} has no embedding-space manifest; rebuild required`);let n={version:1,spaceId:e},i=`${r}.${process.pid}.tmp`;Gge(i,`${JSON.stringify(n)}
|
|
870
|
-
`,{encoding:"utf8",mode:384}),Vge(i,r)}var al,Xa,ol=b(()=>{"use strict";an();al="aqe embedding-space compatibility canary v1",Xa=class extends Error{constructor(t,r){super(`${t}: ${r}`);this.code=t;this.name="EmbeddingSpaceError"}code}});var Fj={};Q(Fj,{DotProductAttention:()=>nhe,FlashAttention:()=>rhe,HyperbolicAttention:()=>she,LinearAttention:()=>ahe,MoEAttention:()=>ohe,MultiHeadAttention:()=>ihe,RuvectorLayer:()=>Xge,SonaEngine:()=>che,TensorCompress:()=>Jge,default:()=>Kge,differentiableSearch:()=>Yge,getCompressionLevel:()=>ehe,hierarchicalForward:()=>Zge,init:()=>the,pipeline:()=>lhe});import{createRequire as jge}from"module";var Qge,Nj,Kge,Xge,Jge,Yge,Zge,ehe,the,rhe,nhe,ihe,she,ahe,ohe,che,lhe,$j=b(()=>{Qge=jge(import.meta.url),Nj=Qge("@huggingface/transformers"),Kge=Nj,{RuvectorLayer:Xge,TensorCompress:Jge,differentiableSearch:Yge,hierarchicalForward:Zge,getCompressionLevel:ehe,init:the,FlashAttention:rhe,DotProductAttention:nhe,MultiHeadAttention:ihe,HyperbolicAttention:she,LinearAttention:ahe,MoEAttention:ohe,SonaEngine:che,pipeline:lhe}=Nj||{}});var cl={};Q(cl,{DEFAULT_EMBEDDING_CONFIG:()=>Za,clearEmbeddingCache:()=>eC,computeBatchEmbeddings:()=>nm,computeRealEmbedding:()=>zt,cosineSimilarity:()=>nt,ensureEndpointEmbeddingSpaceIdentity:()=>eo,getActiveEmbeddingSpaceIdentity:()=>De,getCacheStats:()=>Uj,getEmbeddingDimension:()=>Ur,getEndpointIdentity:()=>dhe,isTransformerAvailable:()=>tC,isUsingEndpoint:()=>WM,resetInitialization:()=>zj});function GM(o){return tr?`endpoint:${tr.fingerprint}:${o}`:`inproc:${o}`}function Bj(o){let e=o.trim();return!!(e.startsWith("{")&&/["']metrics["']/.test(e)||e.startsWith("[")&&e.endsWith("]")&&e.length>50||(e.match(/[a-zA-Z]/g)||[]).length/Math.max(e.length,1)<.3&&e.length>20)}async function HM(o={}){if(Zb)throw new Error(`Transformer initialization previously failed: ${Yb}`);if(rm)return rm;let e={...Za,...o};return rm=(async()=>{try{if(e.endpoint){let c=Ej(e.endpoint);console.log(`[RealEmbeddings] Using external embedder endpoint: ${c}`),Ja=new Kb({endpoint:e.endpoint,token:e.endpointToken,model:e.modelName,expectedDim:Ur()}),tr=await Ja.probe(),Ya=zM({provider:"openai-compatible-endpoint",model:e.modelName,dimensions:tr.dim,pooling:"mean",normalized:!0,preprocessingVersion:"aqe-text-v1",implementation:tr.endpoint,runtimeFingerprint:tr.fingerprint}),console.log(`[RealEmbeddings] Endpoint identity: dim=${tr.dim} fingerprint=${tr.fingerprint}`);try{let l=Pj(tr.endpoint);l&&l.fingerprint!==tr.fingerprint&&console.warn(`[RealEmbeddings] WARNING: endpoint identity changed since last run. Previous fingerprint=${l.fingerprint} dim=${l.dim}, current fingerprint=${tr.fingerprint} dim=${tr.dim}. Vectors written before this change may no longer be comparable.`),Mj(tr)}catch(l){console.warn(`[RealEmbeddings] Could not persist endpoint identity: ${E(l)}`)}on=uhe(Ja);return}let t;try{t=await Promise.resolve().then(()=>($j(),Fj))}catch{throw new Error('In-process embeddings require the optional package "@huggingface/transformers", which is not installed. Configure an embedding endpoint (EmbeddingConfig.endpoint / AQE_EMBEDDER_ENDPOINT) so no local model is loaded. Installing @huggingface/transformers@4.2.0 is an explicit security opt-in: its compatible dependency chain currently has unresolved HIGH advisories GHSA-xcpc-8h2w-3j85 and GHSA-f88m-g3jw-g9cj.')}VM=t.pipeline,console.log(`[RealEmbeddings] Loading model: ${e.modelName}`);let r=performance.now();on=await VM("feature-extraction",e.modelName,{quantized:e.quantized});let n=on;if(!n)throw new Error("Transformer pipeline returned no embedding model");let i=await n(al,{pooling:"mean",normalize:!0}),s=Array.from(i.data);Ya=zM({provider:"huggingface-transformers",model:e.modelName,dimensions:s.length,pooling:"mean",normalized:!0,preprocessingVersion:"aqe-text-v1",implementation:`transformers:${e.quantized?"quantized":"full"}`,runtimeFingerprint:Lj(s)});let a=performance.now()-r;console.log(`[RealEmbeddings] Model loaded in ${a.toFixed(0)}ms`)}catch(t){throw Zb=!0,Yb=E(t),new Error(`Failed to initialize transformer model: ${Yb}`)}})(),rm}function uhe(o){return async e=>{let t=Array.isArray(e)?e:[e],r=await o.embed(t),n=r[0]?.length??Ur(),i=new Float32Array(t.length*n);for(let s=0;s<r.length;s++)i.set(r[s],s*n);return{data:i,dims:[t.length,n]}}}async function zt(o,e={}){let t={...Za,...e};if(Bj(o))return new Array(Ur()).fill(0);if(on||await HM(e),!on)throw new Error("Embedding model failed to initialize");let r=GM(o);if(t.enableCache){let c=Ar.get(r);if(c&&Date.now()-c.timestamp<qj)return c.embedding}let n=performance.now(),i=await on(o,{pooling:"mean",normalize:!0}),s=Array.from(i.data),a=performance.now()-n;if(a>500&&console.warn(`[RealEmbeddings] Slow embedding computation: ${a.toFixed(1)}ms for "${o.slice(0,50)}..."`),t.enableCache){if(Ar.size>=t.maxCacheSize){let c=Ar.keys().next().value;c&&Ar.delete(c)}Ar.set(r,{embedding:s,timestamp:Date.now()})}return s}async function nm(o,e={}){let t={...Za,...e},r=[],n=[],i=new Array(o.length).fill(null),s=[];for(let a=0;a<o.length;a++)Bj(o[a])?i[a]=new Array(Ur()).fill(0):s.push(a);if(s.length===0)return i;if(on||await HM(e),!on)throw new Error("Embedding model failed to initialize");if(t.enableCache)for(let a of s){let c=Ar.get(GM(o[a]));c&&Date.now()-c.timestamp<qj?i[a]=c.embedding:(r.push(o[a]),n.push(a))}else for(let a of s)r.push(o[a]),n.push(a);if(r.length>0){let a=performance.now(),c=32;for(let u=0;u<r.length;u+=c){let d=Math.min(u+c,r.length),p=r.slice(u,d),m=await on(p,{pooling:"mean",normalize:!0}),g=m.dims||[p.length,384],h=g[0],f=g[1];for(let v=0;v<h;v++){let C=v*f,S=Array.from(m.data.slice(C,C+f)),R=u+v,x=n[R];if(i[x]=S,t.enableCache){if(Ar.size>=t.maxCacheSize){let k=Ar.keys().next().value;k&&Ar.delete(k)}Ar.set(GM(r[R]),{embedding:S,timestamp:Date.now()})}}}let l=performance.now()-a;console.log(`[RealEmbeddings] Batch computed ${r.length} embeddings in ${l.toFixed(0)}ms`)}return i.filter(a=>a!==null)}function eC(){Ar.clear(),console.log("[RealEmbeddings] Cache cleared")}function Uj(){return{size:Ar.size,hitRate:0}}function tC(){return!Zb&&on!==null}function Ur(){return 384}function zj(){VM=null,on=null,rm=null,Zb=!1,Yb="",Ar.clear(),Ja&&Ja.close(),Ja=null,tr=null,Ya=null,Ij()}function WM(){return Ja!==null}function dhe(){return tr}function De(){return Ya}async function eo(){if(Ya)return Ya;let o=process.env.AQE_EMBEDDER_ENDPOINT;return o?(await HM({endpoint:o,endpointToken:process.env.AQE_EMBEDDER_TOKEN}),Ya):null}var VM,on,rm,Zb,Yb,Ja,tr,Ya,Za,Ar,qj,Tt=b(()=>{"use strict";an();M();wj();Dj();ol();VM=null,on=null,rm=null,Zb=!1,Yb="",Ja=null,tr=null,Ya=null,Za={modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0,enableCache:!0,maxCacheSize:1e4,endpoint:process.env.AQE_EMBEDDER_ENDPOINT,endpointToken:process.env.AQE_EMBEDDER_TOKEN},Ar=new Map,qj=36e5});function Vj(o){let e=2166136261;for(let t=0;t<o.length;t++)e^=o.charCodeAt(t),e=Math.imul(e,16777619);return(e>>>0).toString(16).padStart(8,"0")}function ghe(o,e){let t=new Float64Array(e),r=2166136261,n=16777619;for(let a=0;a<o.length;a++){let c=o.charCodeAt(a);r^=c,r=Math.imul(r,16777619),n^=c,n=Math.imul(n,2166136261);let l=(r>>>0)%e;t[l]+=(n>>>0)/4294967295*2-1}let i=0;for(let a=0;a<e;a++)i+=t[a]*t[a];i=Math.sqrt(i);let s=new Array(e);for(let a=0;a<e;a++)s[a]=i===0?0:t[a]/i;return s}async function hhe(){if(Gj)return ll;Gj=!0;try{let o=await Promise.resolve().then(()=>(Tt(),cl));if(typeof o.isTransformerAvailable=="function"&&o.isTransformerAvailable())rC=o.computeRealEmbedding,ll=!0;else try{await o.computeRealEmbedding("probe"),rC=o.computeRealEmbedding,ll=!0}catch(e){jM.debug("Transformer probe embedding failed",{error:e instanceof Error?e.message:String(e)}),ll=!1}}catch(o){jM.debug("Transformer module import failed",{error:o instanceof Error?o.message:String(o)}),ll=!1}return ll}var jM,phe,ul,Hj,mhe,Gj,ll,rC,nC,QM=b(()=>{"use strict";N();an();G();jM=_.create("anti-drift-middleware"),phe={maxIdenticalCalls:3,windowMs:3e4,steeringMessage:"Loop detected: the same tool call has been repeated multiple times. Consider an alternative approach or different parameters.",enableFleetLearning:!1};ul=class{config;callHistory=new Map;totalCallsTracked=0;loopsDetected=0;constructor(e){this.config={...phe,...e}}trackCall(e,t,r){if(process.env.AQE_LOOP_DETECTION_ENABLED==="false")return{isLoop:!1,callCount:1,signature:this.createSignature(t,r),action:"allow"};let n=this.createSignature(t,r);this.totalCallsTracked++,this.callHistory.has(e)||this.callHistory.set(e,[]);let i=this.callHistory.get(e);i.push(n);let s=Date.now()-this.config.windowMs,a=i.findIndex(l=>l.timestamp>=s);a>0?i.splice(0,a):a===-1&&(i.length=0,i.push(n));let c=i.filter(l=>l.hash===n.hash).length;return c>=this.config.maxIdenticalCalls?(this.loopsDetected++,{isLoop:!0,callCount:c,signature:n,action:"steer",steeringMessage:this.config.steeringMessage}):c===this.config.maxIdenticalCalls-1?{isLoop:!1,callCount:c,signature:n,action:"warn"}:{isLoop:!1,callCount:c,signature:n,action:"allow"}}getMetrics(){return{totalCallsTracked:this.totalCallsTracked,loopsDetected:this.loopsDetected}}clear(){this.callHistory.clear(),this.totalCallsTracked=0,this.loopsDetected=0}createSignature(e,t){let r=JSON.stringify(t??""),n=Vj(r),i=`${e}:${r}`;return{hash:Vj(i),toolName:e,argsFingerprint:n,timestamp:Date.now()}}},Hj={"quality-gate":.05,coverage:.1,"test-generation":.15,learning:.2,default:.12},mhe={thresholds:Hj,agentId:"unknown",maxHistorySize:200,fallbackDimension:64};Gj=!1,ll=!1,rC=null;nC=class{name="semantic-anti-drift";priority=10;config;history=[];totalChecked=0;driftCount=0;similaritySum=0;constructor(e){this.config={...mhe,...e,thresholds:{...Hj,...e?.thresholds}}}async onEmit(e){let t=JSON.stringify(e.payload),r=await this.embed(t),n=this.resolveCategory(e.type),i=this.config.thresholds[n]??this.config.thresholds.default,s={embedding:r,driftThreshold:i,sourceAgentId:this.config.agentId,hopCount:0,emittedAt:Date.now()};return{...e,semanticFingerprint:s}}async onReceive(e){let t=e.semanticFingerprint;if(!t)return e;let r=JSON.stringify(e.payload),n=await this.embed(r),i=nt(n,t.embedding),a=1-i>t.driftThreshold;this.totalChecked++,this.similaritySum+=i;let c={drifted:a,cosineSimilarity:i,threshold:t.driftThreshold,eventType:e.type,hopCount:t.hopCount+1,checkedAt:Date.now()};if(this.history.push(c),this.history.length>this.config.maxHistorySize&&this.history.shift(),a)return this.driftCount++,await this.emitDriftEvent(e,c),null;let l={...t,hopCount:t.hopCount+1};return{...e,semanticFingerprint:l}}getDriftHistory(){return this.history}getStats(){return{totalChecked:this.totalChecked,driftCount:this.driftCount,averageSimilarity:this.totalChecked>0?this.similaritySum/this.totalChecked:0}}validateConfig(){for(let[e,t]of Object.entries(this.config.thresholds))if(typeof t!="number"||t<0||t>1)return y(new Error(`Invalid threshold for "${e}": must be between 0 and 1, got ${t}`));return this.config.maxHistorySize<=0?y(new Error("maxHistorySize must be positive")):this.config.fallbackDimension<=0?y(new Error("fallbackDimension must be positive")):T(void 0)}async embed(e){return await hhe()&&rC?rC(e):ghe(e,this.config.fallbackDimension)}resolveCategory(e){let t=e.toLowerCase();for(let r of Object.keys(this.config.thresholds))if(r!=="default"&&t.includes(r))return r;return"default"}async emitDriftEvent(e,t){if(!this.config.onDriftDetected)return;let r={id:`drift-${e.id}-${Date.now()}`,type:"SemanticDriftDetected",timestamp:new Date,source:e.source,correlationId:e.correlationId,payload:{originalEventId:e.id,originalEventType:e.type,cosineSimilarity:t.cosineSimilarity,threshold:t.threshold,hopCount:t.hopCount,agentId:this.config.agentId}};try{await this.config.onDriftDetected(r)}catch(n){jM.debug("onDriftDetected callback failed",{error:n instanceof Error?n.message:String(n)})}}}});var iC={};Q(iC,{DEFAULT_UNIFIED_CONFIG:()=>jj,UnifiedPersistenceManager:()=>dl,getUnifiedPersistence:()=>zr,initializeUnifiedPersistence:()=>KM,resetUnifiedPersistence:()=>fhe});function zr(o){return dl.getInstance(o)}async function KM(o){let e=zr(o);return await e.initialize(),e}function fhe(){dl.resetInstance()}function yhe(){if(Wj)return;Wj=!0;let o=()=>{try{let t=dl.instance;t&&t.close()}catch(t){console.debug("[UnifiedPersistence] Cleanup error:",t instanceof Error?t.message:t)}};process.on("beforeExit",o),jb(o);let e=t=>{tl(t)||(o(),process.exit(0))};process.on("SIGINT",e),process.on("SIGTERM",e)}var jj,dl,Wj,Un=b(()=>{"use strict";M();te();Fn();Zp();jj={dbPath:nl.dbPath,walMode:!0,mmapSize:dt.MMAP_SIZE_BYTES,cacheSize:dt.CACHE_SIZE_KB,busyTimeout:dt.BUSY_TIMEOUT_MS},dl=class o{static instance=null;static instancePromise=null;unifiedMemory=null;config;initialized=!1;initPromise=null;constructor(e){this.config={...jj,...e}}static getInstance(e){return o.instance||(o.instance=new o(e)),o.instance}static async getInstanceAsync(e){return o.instance?.initialized?o.instance:(o.instancePromise||(o.instancePromise=(async()=>{let t=o.getInstance(e);return await t.initialize(),t})()),o.instancePromise)}static resetInstance(){o.instance&&(o.instance.close(),o.instance=null),o.instancePromise=null,qM()}async initialize(){if(!this.initialized)return this.initPromise||(this.initPromise=this._doInitialize()),this.initPromise}async _doInitialize(){if(!this.initialized)try{let e={dbPath:this.config.dbPath,walMode:this.config.walMode,busyTimeout:this.config.busyTimeout,mmapSize:this.config.mmapSize,cacheSize:this.config.cacheSize};this.unifiedMemory=j(e),await this.unifiedMemory.initialize(),this.initialized=!0,console.log(`[UnifiedPersistence] Initialized via UnifiedMemoryManager: ${this.config.dbPath}`)}catch(e){throw this.initPromise=null,new Error(`Failed to initialize UnifiedPersistenceManager: ${E(e)}`)}}getDatabase(){if(!this.unifiedMemory||!this.initialized)throw new Error("UnifiedPersistenceManager not initialized");return this.unifiedMemory.getDatabase()}isInitialized(){return this.initialized}getDbPath(){return this.config.dbPath}prepare(e,t){if(!this.unifiedMemory)throw new Error("Database not initialized");return this.unifiedMemory.prepare(e,t)}transaction(e){if(!this.unifiedMemory)throw new Error("Database not initialized");return this.unifiedMemory.transaction(e)}getStats(){if(!this.unifiedMemory)throw new Error("Database not initialized");let e=this.unifiedMemory.getStats();return{tables:e.tables,fileSize:e.fileSize,walSize:e.walSize}}vacuum(){this.getDatabase().exec("VACUUM")}checkpoint(){this.getDatabase().pragma("wal_checkpoint(TRUNCATE)")}close(){this.initialized=!1,console.log("[UnifiedPersistence] Facade closed")}};Wj=!1;yhe()});import{createRequire as vhe}from"node:module";var bhe,sC,Qj,Ai,im,XM,JM,aC,oC=b(()=>{"use strict";bhe=vhe(import.meta.url),sC=bhe("semver"),Qj="3.15.0",Ai=o=>typeof o=="string"&&sC.valid(o)===o.split("+")[0],im=o=>sC.validRange(o)!==null,XM=(o,e)=>sC.satisfies(o,e),JM=(o,e)=>sC.compare(o,e),aC=(o,e)=>JM(e,o)||o.localeCompare(e)});function YM(o){let e=[],t=[];if(!o||typeof o!="object")return{valid:!1,errors:["Manifest must be a non-null object"],warnings:[]};let r=o;if(!r.name||typeof r.name!="string"?e.push("name is required and must be a string"):She(r.name,e,t),!r.version||typeof r.version!="string"?e.push("version is required and must be a string"):Ai(r.version)||e.push(`version "${r.version}" is not valid semver (expected: major.minor.patch)`),!r.description||typeof r.description!="string"?e.push("description is required and must be a string"):r.description.length>Xj&&t.push(`description exceeds ${Xj} characters`),(!r.author||typeof r.author!="string")&&e.push("author is required and must be a string"),!Array.isArray(r.domains)||r.domains.length===0)e.push("domains is required and must be a non-empty array");else for(let n of r.domains)if(typeof n!="string"){e.push("Each domain must be a string");break}if(!r.entryPoint||typeof r.entryPoint!="string"?e.push("entryPoint is required and must be a string"):Ehe(r.entryPoint,e),r.dependencies!==void 0)if(typeof r.dependencies!="object"||r.dependencies===null||Array.isArray(r.dependencies))e.push("dependencies must be an object mapping plugin names to semver ranges");else for(let[n,i]of Object.entries(r.dependencies))typeof i!="string"?e.push(`Dependency "${n}" must have a string version range`):im(i)||e.push(`Dependency "${n}" has an invalid semver range`);if(r.hooks!==void 0)if(typeof r.hooks!="object"||r.hooks===null||Array.isArray(r.hooks))e.push("hooks must be an object mapping event names to handler paths");else for(let[,n]of Object.entries(r.hooks)){if(typeof n!="string"){e.push("Hook handler paths must be strings");break}n.includes("..")&&e.push(`Hook handler path "${n}" must not contain ".." (path traversal)`)}if(r.minAqeVersion!==void 0&&(typeof r.minAqeVersion!="string"||!Ai(r.minAqeVersion))&&e.push("minAqeVersion must be valid semver"),r.permissions!==void 0){if(!Array.isArray(r.permissions))e.push("permissions must be an array of strings");else for(let n of r.permissions)if(typeof n!="string"){e.push("Each permission must be a string");break}}return{valid:e.length===0,errors:e,warnings:t}}function Jj(o){let e=typeof o=="string"?JSON.parse(o):o,t=YM(e);if(!t.valid)throw new Error(`Invalid plugin manifest:
|
|
870
|
+
`,{encoding:"utf8",mode:384}),Vge(i,r)}var al,Xa,ol=b(()=>{"use strict";an();al="aqe embedding-space compatibility canary v1",Xa=class extends Error{constructor(t,r){super(`${t}: ${r}`);this.code=t;this.name="EmbeddingSpaceError"}code}});var Fj={};Q(Fj,{DotProductAttention:()=>nhe,FlashAttention:()=>rhe,HyperbolicAttention:()=>she,LinearAttention:()=>ahe,MoEAttention:()=>ohe,MultiHeadAttention:()=>ihe,RuvectorLayer:()=>Xge,SonaEngine:()=>che,TensorCompress:()=>Jge,default:()=>Kge,differentiableSearch:()=>Yge,getCompressionLevel:()=>ehe,hierarchicalForward:()=>Zge,init:()=>the,pipeline:()=>lhe});import{createRequire as jge}from"module";var Qge,Nj,Kge,Xge,Jge,Yge,Zge,ehe,the,rhe,nhe,ihe,she,ahe,ohe,che,lhe,$j=b(()=>{Qge=jge(import.meta.url),Nj=Qge("@huggingface/transformers"),Kge=Nj,{RuvectorLayer:Xge,TensorCompress:Jge,differentiableSearch:Yge,hierarchicalForward:Zge,getCompressionLevel:ehe,init:the,FlashAttention:rhe,DotProductAttention:nhe,MultiHeadAttention:ihe,HyperbolicAttention:she,LinearAttention:ahe,MoEAttention:ohe,SonaEngine:che,pipeline:lhe}=Nj||{}});var cl={};Q(cl,{DEFAULT_EMBEDDING_CONFIG:()=>Za,clearEmbeddingCache:()=>eC,computeBatchEmbeddings:()=>nm,computeRealEmbedding:()=>zt,cosineSimilarity:()=>nt,ensureEndpointEmbeddingSpaceIdentity:()=>eo,getActiveEmbeddingSpaceIdentity:()=>De,getCacheStats:()=>Uj,getEmbeddingDimension:()=>Ur,getEndpointIdentity:()=>dhe,isTransformerAvailable:()=>tC,isUsingEndpoint:()=>WM,resetInitialization:()=>zj});function GM(o){return tr?`endpoint:${tr.fingerprint}:${o}`:`inproc:${o}`}function Bj(o){let e=o.trim();return!!(e.startsWith("{")&&/["']metrics["']/.test(e)||e.startsWith("[")&&e.endsWith("]")&&e.length>50||(e.match(/[a-zA-Z]/g)||[]).length/Math.max(e.length,1)<.3&&e.length>20)}async function HM(o={}){if(Zb)throw new Error(`Transformer initialization previously failed: ${Yb}`);if(rm)return rm;let e={...Za,...o};return rm=(async()=>{try{if(e.endpoint){let c=Ej(e.endpoint);console.log(`[RealEmbeddings] Using external embedder endpoint: ${c}`),Ja=new Kb({endpoint:e.endpoint,token:e.endpointToken,model:e.modelName,expectedDim:Ur()}),tr=await Ja.probe(),Ya=zM({provider:"openai-compatible-endpoint",model:e.modelName,dimensions:tr.dim,pooling:"mean",normalized:!0,preprocessingVersion:"aqe-text-v1",implementation:tr.endpoint,runtimeFingerprint:tr.fingerprint}),console.log(`[RealEmbeddings] Endpoint identity: dim=${tr.dim} fingerprint=${tr.fingerprint}`);try{let l=Pj(tr.endpoint);l&&l.fingerprint!==tr.fingerprint&&console.warn(`[RealEmbeddings] WARNING: endpoint identity changed since last run. Previous fingerprint=${l.fingerprint} dim=${l.dim}, current fingerprint=${tr.fingerprint} dim=${tr.dim}. Vectors written before this change may no longer be comparable.`),Mj(tr)}catch(l){console.warn(`[RealEmbeddings] Could not persist endpoint identity: ${E(l)}`)}on=uhe(Ja);return}let t;try{t=await Promise.resolve().then(()=>($j(),Fj))}catch{throw new Error('In-process embeddings require the optional package "@huggingface/transformers", which is not installed. Configure an embedding endpoint (EmbeddingConfig.endpoint / AQE_EMBEDDER_ENDPOINT) so no local model is loaded. Installing @huggingface/transformers@4.2.0 is an explicit security opt-in: its compatible dependency chain currently has unresolved HIGH advisories GHSA-xcpc-8h2w-3j85 and GHSA-f88m-g3jw-g9cj.')}VM=t.pipeline,console.log(`[RealEmbeddings] Loading model: ${e.modelName}`);let r=performance.now();on=await VM("feature-extraction",e.modelName,{quantized:e.quantized});let n=on;if(!n)throw new Error("Transformer pipeline returned no embedding model");let i=await n(al,{pooling:"mean",normalize:!0}),s=Array.from(i.data);Ya=zM({provider:"huggingface-transformers",model:e.modelName,dimensions:s.length,pooling:"mean",normalized:!0,preprocessingVersion:"aqe-text-v1",implementation:`transformers:${e.quantized?"quantized":"full"}`,runtimeFingerprint:Lj(s)});let a=performance.now()-r;console.log(`[RealEmbeddings] Model loaded in ${a.toFixed(0)}ms`)}catch(t){throw Zb=!0,Yb=E(t),new Error(`Failed to initialize transformer model: ${Yb}`)}})(),rm}function uhe(o){return async e=>{let t=Array.isArray(e)?e:[e],r=await o.embed(t),n=r[0]?.length??Ur(),i=new Float32Array(t.length*n);for(let s=0;s<r.length;s++)i.set(r[s],s*n);return{data:i,dims:[t.length,n]}}}async function zt(o,e={}){let t={...Za,...e};if(Bj(o))return new Array(Ur()).fill(0);if(on||await HM(e),!on)throw new Error("Embedding model failed to initialize");let r=GM(o);if(t.enableCache){let c=Ar.get(r);if(c&&Date.now()-c.timestamp<qj)return c.embedding}let n=performance.now(),i=await on(o,{pooling:"mean",normalize:!0}),s=Array.from(i.data),a=performance.now()-n;if(a>500&&console.warn(`[RealEmbeddings] Slow embedding computation: ${a.toFixed(1)}ms for "${o.slice(0,50)}..."`),t.enableCache){if(Ar.size>=t.maxCacheSize){let c=Ar.keys().next().value;c&&Ar.delete(c)}Ar.set(r,{embedding:s,timestamp:Date.now()})}return s}async function nm(o,e={}){let t={...Za,...e},r=[],n=[],i=new Array(o.length).fill(null),s=[];for(let a=0;a<o.length;a++)Bj(o[a])?i[a]=new Array(Ur()).fill(0):s.push(a);if(s.length===0)return i;if(on||await HM(e),!on)throw new Error("Embedding model failed to initialize");if(t.enableCache)for(let a of s){let c=Ar.get(GM(o[a]));c&&Date.now()-c.timestamp<qj?i[a]=c.embedding:(r.push(o[a]),n.push(a))}else for(let a of s)r.push(o[a]),n.push(a);if(r.length>0){let a=performance.now(),c=32;for(let u=0;u<r.length;u+=c){let d=Math.min(u+c,r.length),p=r.slice(u,d),m=await on(p,{pooling:"mean",normalize:!0}),g=m.dims||[p.length,384],h=g[0],f=g[1];for(let v=0;v<h;v++){let C=v*f,S=Array.from(m.data.slice(C,C+f)),R=u+v,x=n[R];if(i[x]=S,t.enableCache){if(Ar.size>=t.maxCacheSize){let k=Ar.keys().next().value;k&&Ar.delete(k)}Ar.set(GM(r[R]),{embedding:S,timestamp:Date.now()})}}}let l=performance.now()-a;console.log(`[RealEmbeddings] Batch computed ${r.length} embeddings in ${l.toFixed(0)}ms`)}return i.filter(a=>a!==null)}function eC(){Ar.clear(),console.log("[RealEmbeddings] Cache cleared")}function Uj(){return{size:Ar.size,hitRate:0}}function tC(){return!Zb&&on!==null}function Ur(){return 384}function zj(){VM=null,on=null,rm=null,Zb=!1,Yb="",Ar.clear(),Ja&&Ja.close(),Ja=null,tr=null,Ya=null,Ij()}function WM(){return Ja!==null}function dhe(){return tr}function De(){return Ya}async function eo(){if(Ya)return Ya;let o=process.env.AQE_EMBEDDER_ENDPOINT;return o?(await HM({endpoint:o,endpointToken:process.env.AQE_EMBEDDER_TOKEN}),Ya):null}var VM,on,rm,Zb,Yb,Ja,tr,Ya,Za,Ar,qj,Tt=b(()=>{"use strict";an();M();wj();Dj();ol();VM=null,on=null,rm=null,Zb=!1,Yb="",Ja=null,tr=null,Ya=null,Za={modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0,enableCache:!0,maxCacheSize:1e4,endpoint:process.env.AQE_EMBEDDER_ENDPOINT,endpointToken:process.env.AQE_EMBEDDER_TOKEN},Ar=new Map,qj=36e5});function Vj(o){let e=2166136261;for(let t=0;t<o.length;t++)e^=o.charCodeAt(t),e=Math.imul(e,16777619);return(e>>>0).toString(16).padStart(8,"0")}function ghe(o,e){let t=new Float64Array(e),r=2166136261,n=16777619;for(let a=0;a<o.length;a++){let c=o.charCodeAt(a);r^=c,r=Math.imul(r,16777619),n^=c,n=Math.imul(n,2166136261);let l=(r>>>0)%e;t[l]+=(n>>>0)/4294967295*2-1}let i=0;for(let a=0;a<e;a++)i+=t[a]*t[a];i=Math.sqrt(i);let s=new Array(e);for(let a=0;a<e;a++)s[a]=i===0?0:t[a]/i;return s}async function hhe(){if(Gj)return ll;Gj=!0;try{let o=await Promise.resolve().then(()=>(Tt(),cl));if(typeof o.isTransformerAvailable=="function"&&o.isTransformerAvailable())rC=o.computeRealEmbedding,ll=!0;else try{await o.computeRealEmbedding("probe"),rC=o.computeRealEmbedding,ll=!0}catch(e){jM.debug("Transformer probe embedding failed",{error:e instanceof Error?e.message:String(e)}),ll=!1}}catch(o){jM.debug("Transformer module import failed",{error:o instanceof Error?o.message:String(o)}),ll=!1}return ll}var jM,phe,ul,Hj,mhe,Gj,ll,rC,nC,QM=b(()=>{"use strict";N();an();G();jM=_.create("anti-drift-middleware"),phe={maxIdenticalCalls:3,windowMs:3e4,steeringMessage:"Loop detected: the same tool call has been repeated multiple times. Consider an alternative approach or different parameters.",enableFleetLearning:!1};ul=class{config;callHistory=new Map;totalCallsTracked=0;loopsDetected=0;constructor(e){this.config={...phe,...e}}trackCall(e,t,r){if(process.env.AQE_LOOP_DETECTION_ENABLED==="false")return{isLoop:!1,callCount:1,signature:this.createSignature(t,r),action:"allow"};let n=this.createSignature(t,r);this.totalCallsTracked++,this.callHistory.has(e)||this.callHistory.set(e,[]);let i=this.callHistory.get(e);i.push(n);let s=Date.now()-this.config.windowMs,a=i.findIndex(l=>l.timestamp>=s);a>0?i.splice(0,a):a===-1&&(i.length=0,i.push(n));let c=i.filter(l=>l.hash===n.hash).length;return c>=this.config.maxIdenticalCalls?(this.loopsDetected++,{isLoop:!0,callCount:c,signature:n,action:"steer",steeringMessage:this.config.steeringMessage}):c===this.config.maxIdenticalCalls-1?{isLoop:!1,callCount:c,signature:n,action:"warn"}:{isLoop:!1,callCount:c,signature:n,action:"allow"}}getMetrics(){return{totalCallsTracked:this.totalCallsTracked,loopsDetected:this.loopsDetected}}clear(){this.callHistory.clear(),this.totalCallsTracked=0,this.loopsDetected=0}createSignature(e,t){let r=JSON.stringify(t??""),n=Vj(r),i=`${e}:${r}`;return{hash:Vj(i),toolName:e,argsFingerprint:n,timestamp:Date.now()}}},Hj={"quality-gate":.05,coverage:.1,"test-generation":.15,learning:.2,default:.12},mhe={thresholds:Hj,agentId:"unknown",maxHistorySize:200,fallbackDimension:64};Gj=!1,ll=!1,rC=null;nC=class{name="semantic-anti-drift";priority=10;config;history=[];totalChecked=0;driftCount=0;similaritySum=0;constructor(e){this.config={...mhe,...e,thresholds:{...Hj,...e?.thresholds}}}async onEmit(e){let t=JSON.stringify(e.payload),r=await this.embed(t),n=this.resolveCategory(e.type),i=this.config.thresholds[n]??this.config.thresholds.default,s={embedding:r,driftThreshold:i,sourceAgentId:this.config.agentId,hopCount:0,emittedAt:Date.now()};return{...e,semanticFingerprint:s}}async onReceive(e){let t=e.semanticFingerprint;if(!t)return e;let r=JSON.stringify(e.payload),n=await this.embed(r),i=nt(n,t.embedding),a=1-i>t.driftThreshold;this.totalChecked++,this.similaritySum+=i;let c={drifted:a,cosineSimilarity:i,threshold:t.driftThreshold,eventType:e.type,hopCount:t.hopCount+1,checkedAt:Date.now()};if(this.history.push(c),this.history.length>this.config.maxHistorySize&&this.history.shift(),a)return this.driftCount++,await this.emitDriftEvent(e,c),null;let l={...t,hopCount:t.hopCount+1};return{...e,semanticFingerprint:l}}getDriftHistory(){return this.history}getStats(){return{totalChecked:this.totalChecked,driftCount:this.driftCount,averageSimilarity:this.totalChecked>0?this.similaritySum/this.totalChecked:0}}validateConfig(){for(let[e,t]of Object.entries(this.config.thresholds))if(typeof t!="number"||t<0||t>1)return y(new Error(`Invalid threshold for "${e}": must be between 0 and 1, got ${t}`));return this.config.maxHistorySize<=0?y(new Error("maxHistorySize must be positive")):this.config.fallbackDimension<=0?y(new Error("fallbackDimension must be positive")):T(void 0)}async embed(e){return await hhe()&&rC?rC(e):ghe(e,this.config.fallbackDimension)}resolveCategory(e){let t=e.toLowerCase();for(let r of Object.keys(this.config.thresholds))if(r!=="default"&&t.includes(r))return r;return"default"}async emitDriftEvent(e,t){if(!this.config.onDriftDetected)return;let r={id:`drift-${e.id}-${Date.now()}`,type:"SemanticDriftDetected",timestamp:new Date,source:e.source,correlationId:e.correlationId,payload:{originalEventId:e.id,originalEventType:e.type,cosineSimilarity:t.cosineSimilarity,threshold:t.threshold,hopCount:t.hopCount,agentId:this.config.agentId}};try{await this.config.onDriftDetected(r)}catch(n){jM.debug("onDriftDetected callback failed",{error:n instanceof Error?n.message:String(n)})}}}});var iC={};Q(iC,{DEFAULT_UNIFIED_CONFIG:()=>jj,UnifiedPersistenceManager:()=>dl,getUnifiedPersistence:()=>zr,initializeUnifiedPersistence:()=>KM,resetUnifiedPersistence:()=>fhe});function zr(o){return dl.getInstance(o)}async function KM(o){let e=zr(o);return await e.initialize(),e}function fhe(){dl.resetInstance()}function yhe(){if(Wj)return;Wj=!0;let o=()=>{try{let t=dl.instance;t&&t.close()}catch(t){console.debug("[UnifiedPersistence] Cleanup error:",t instanceof Error?t.message:t)}};process.on("beforeExit",o),jb(o);let e=t=>{tl(t)||(o(),process.exit(0))};process.on("SIGINT",e),process.on("SIGTERM",e)}var jj,dl,Wj,Un=b(()=>{"use strict";M();te();Fn();Zp();jj={dbPath:nl.dbPath,walMode:!0,mmapSize:dt.MMAP_SIZE_BYTES,cacheSize:dt.CACHE_SIZE_KB,busyTimeout:dt.BUSY_TIMEOUT_MS},dl=class o{static instance=null;static instancePromise=null;unifiedMemory=null;config;initialized=!1;initPromise=null;constructor(e){this.config={...jj,...e}}static getInstance(e){return o.instance||(o.instance=new o(e)),o.instance}static async getInstanceAsync(e){return o.instance?.initialized?o.instance:(o.instancePromise||(o.instancePromise=(async()=>{let t=o.getInstance(e);return await t.initialize(),t})()),o.instancePromise)}static resetInstance(){o.instance&&(o.instance.close(),o.instance=null),o.instancePromise=null,qM()}async initialize(){if(!this.initialized)return this.initPromise||(this.initPromise=this._doInitialize()),this.initPromise}async _doInitialize(){if(!this.initialized)try{let e={dbPath:this.config.dbPath,walMode:this.config.walMode,busyTimeout:this.config.busyTimeout,mmapSize:this.config.mmapSize,cacheSize:this.config.cacheSize};this.unifiedMemory=j(e),await this.unifiedMemory.initialize(),this.initialized=!0,console.log(`[UnifiedPersistence] Initialized via UnifiedMemoryManager: ${this.config.dbPath}`)}catch(e){throw this.initPromise=null,new Error(`Failed to initialize UnifiedPersistenceManager: ${E(e)}`)}}getDatabase(){if(!this.unifiedMemory||!this.initialized)throw new Error("UnifiedPersistenceManager not initialized");return this.unifiedMemory.getDatabase()}isInitialized(){return this.initialized}getDbPath(){return this.config.dbPath}prepare(e,t){if(!this.unifiedMemory)throw new Error("Database not initialized");return this.unifiedMemory.prepare(e,t)}transaction(e){if(!this.unifiedMemory)throw new Error("Database not initialized");return this.unifiedMemory.transaction(e)}getStats(){if(!this.unifiedMemory)throw new Error("Database not initialized");let e=this.unifiedMemory.getStats();return{tables:e.tables,fileSize:e.fileSize,walSize:e.walSize}}vacuum(){this.getDatabase().exec("VACUUM")}checkpoint(){this.getDatabase().pragma("wal_checkpoint(TRUNCATE)")}close(){this.initialized=!1,console.log("[UnifiedPersistence] Facade closed")}};Wj=!1;yhe()});import{createRequire as vhe}from"node:module";var bhe,sC,Qj,Ai,im,XM,JM,aC,oC=b(()=>{"use strict";bhe=vhe(import.meta.url),sC=bhe("semver"),Qj="3.15.1",Ai=o=>typeof o=="string"&&sC.valid(o)===o.split("+")[0],im=o=>sC.validRange(o)!==null,XM=(o,e)=>sC.satisfies(o,e),JM=(o,e)=>sC.compare(o,e),aC=(o,e)=>JM(e,o)||o.localeCompare(e)});function YM(o){let e=[],t=[];if(!o||typeof o!="object")return{valid:!1,errors:["Manifest must be a non-null object"],warnings:[]};let r=o;if(!r.name||typeof r.name!="string"?e.push("name is required and must be a string"):She(r.name,e,t),!r.version||typeof r.version!="string"?e.push("version is required and must be a string"):Ai(r.version)||e.push(`version "${r.version}" is not valid semver (expected: major.minor.patch)`),!r.description||typeof r.description!="string"?e.push("description is required and must be a string"):r.description.length>Xj&&t.push(`description exceeds ${Xj} characters`),(!r.author||typeof r.author!="string")&&e.push("author is required and must be a string"),!Array.isArray(r.domains)||r.domains.length===0)e.push("domains is required and must be a non-empty array");else for(let n of r.domains)if(typeof n!="string"){e.push("Each domain must be a string");break}if(!r.entryPoint||typeof r.entryPoint!="string"?e.push("entryPoint is required and must be a string"):Ehe(r.entryPoint,e),r.dependencies!==void 0)if(typeof r.dependencies!="object"||r.dependencies===null||Array.isArray(r.dependencies))e.push("dependencies must be an object mapping plugin names to semver ranges");else for(let[n,i]of Object.entries(r.dependencies))typeof i!="string"?e.push(`Dependency "${n}" must have a string version range`):im(i)||e.push(`Dependency "${n}" has an invalid semver range`);if(r.hooks!==void 0)if(typeof r.hooks!="object"||r.hooks===null||Array.isArray(r.hooks))e.push("hooks must be an object mapping event names to handler paths");else for(let[,n]of Object.entries(r.hooks)){if(typeof n!="string"){e.push("Hook handler paths must be strings");break}n.includes("..")&&e.push(`Hook handler path "${n}" must not contain ".." (path traversal)`)}if(r.minAqeVersion!==void 0&&(typeof r.minAqeVersion!="string"||!Ai(r.minAqeVersion))&&e.push("minAqeVersion must be valid semver"),r.permissions!==void 0){if(!Array.isArray(r.permissions))e.push("permissions must be an array of strings");else for(let n of r.permissions)if(typeof n!="string"){e.push("Each permission must be a string");break}}return{valid:e.length===0,errors:e,warnings:t}}function Jj(o){let e=typeof o=="string"?JSON.parse(o):o,t=YM(e);if(!t.valid)throw new Error(`Invalid plugin manifest:
|
|
871
871
|
- ${t.errors.join(`
|
|
872
872
|
- `)}`);return e}function She(o,e,t){o.length>Kj&&e.push(`name must be ${Kj} characters or fewer`),Che.test(o)||e.push("name must be lowercase alphanumeric with hyphens, starting with a letter"),/[^\x00-\x7F]/.test(o)&&e.push("name must contain only ASCII characters");for(let r of The)o.startsWith(r)&&e.push(`name cannot start with reserved prefix "${r}"`);["plugin","test","tool"].includes(o)&&t.push(`name "${o}" is very generic \u2014 consider a more descriptive name`)}function Ehe(o,e){o.includes("..")&&e.push('entryPoint must not contain ".." (path traversal)'),(o.startsWith("/")||o.startsWith("\\"))&&e.push("entryPoint must be a relative path"),!o.endsWith(".js")&&!o.endsWith(".ts")&&!o.endsWith(".mjs")&&e.push("entryPoint must end in .js, .ts, or .mjs")}var Che,The,Kj,Xj,ZM=b(()=>{"use strict";oC();Che=/^[a-z][a-z0-9-]*$/,The=["aqe-core-","agentic-qe-core-"],Kj=64,Xj=500});import*as xe from"fs";import*as cn from"path";var pl,eI=b(()=>{"use strict";oC();pl=class{cacheDir;keepVersions;constructor(e={}){this.cacheDir=e.cacheDir??cn.join(process.cwd(),".agentic-qe","plugins"),this.keepVersions=e.keepVersions??2}has(e,t){let r=this.versionDir(e,t);return xe.existsSync(r)&&xe.existsSync(cn.join(r,"qe-plugin.json"))}get(e,t){if(!this.has(e,t))return;let r=this.versionDir(e,t),n=xe.readFileSync(cn.join(r,"qe-plugin.json"),"utf-8"),i=JSON.parse(n),s=xe.statSync(r);return{manifest:i,path:r,cachedAt:s.birthtime.toISOString()}}store(e,t){let r=this.versionDir(e.name,e.version);if(xe.existsSync(r))return r;xe.mkdirSync(r,{recursive:!0});try{this.copyDir(t,r),xe.writeFileSync(cn.join(r,"qe-plugin.json"),JSON.stringify(e,null,2))}catch(n){throw xe.rmSync(r,{recursive:!0,force:!0}),n}return this.pruneOldVersions(e.name),r}remove(e,t){let r=this.versionDir(e,t);return xe.existsSync(r)?(xe.rmSync(r,{recursive:!0,force:!0}),!0):!1}listVersions(e){let t=cn.join(this.cacheDir,e);if(!xe.existsSync(t))return[];let r=[],n=xe.readdirSync(t);for(let i of n){let s=cn.join(t,i),a=cn.join(s,"qe-plugin.json");if(xe.existsSync(a))try{let c=xe.readFileSync(a,"utf-8"),l=JSON.parse(c);if(!Ai(l.version)){console.warn(`[PluginCache] Skipping cached plugin ${e}@${i}: invalid version ${JSON.stringify(l.version)}`);continue}let u=xe.statSync(s);r.push({manifest:l,path:s,cachedAt:u.birthtime.toISOString()})}catch{}}return r}listAll(){if(!xe.existsSync(this.cacheDir))return[];let e=[],t=xe.readdirSync(this.cacheDir);for(let r of t){let n=this.listVersions(r);n.length>0&&(n.sort((i,s)=>aC(i.manifest.version,s.manifest.version)),e.push(n[0]))}return e}listCandidates(){return xe.existsSync(this.cacheDir)?xe.readdirSync(this.cacheDir).flatMap(e=>this.listVersions(e)):[]}versionDir(e,t){return cn.join(this.cacheDir,e,t)}pruneOldVersions(e){let t=this.listVersions(e);if(t.length<=this.keepVersions)return;t.sort((n,i)=>n.cachedAt.localeCompare(i.cachedAt));let r=t.slice(0,t.length-this.keepVersions);for(let n of r)xe.rmSync(n.path,{recursive:!0,force:!0})}copyDir(e,t){if(!xe.existsSync(e))return;let r=xe.readdirSync(e,{withFileTypes:!0});for(let n of r){let i=cn.join(e,n.name),s=cn.join(t,n.name);if(n.isDirectory()){if(n.name===".git"||n.name==="node_modules")continue;xe.mkdirSync(s,{recursive:!0}),this.copyDir(i,s)}else xe.copyFileSync(i,s)}}}});var cC,Yj=b(()=>{"use strict";oC();cC=class{constructor(e=Qj){this.aqeVersion=e}aqeVersion;resolve(e,t){let r=new Map,n=new Map;for(let x of e){let k=r.get(x.name)??[];r.set(x.name,k);let P=this.validateVersions(x);P?n.set(x.name,[...n.get(x.name)??[],P]):k.push(x)}for(let x of r.values())x.sort((k,P)=>aC(k.version,P.version));let i=new Map,s=[],a=x=>({ordered:x.map((k,P)=>({manifest:k,order:P})),missing:i,errors:s,selectedVersions:Object.fromEntries(x.map(k=>[k.name,k.version])),aqeVersion:this.aqeVersion}),c=[...t??r.keys()].sort(),l=new Set(c),u=new Map,d=0,p=!1,m=()=>{for(let x of u.values())for(let[k,P]of Object.entries(x.dependencies??{})){let L=u.get(k);if(!(L?[L]:r.get(k)??[]).some(q=>XM(q.version,P)))return!1}return!0},g,h=()=>{let x=new Set,k=new Set,P=(L,B)=>{if(k.has(L))return[...B.slice(B.indexOf(L)),L];if(!x.has(L)){k.add(L);for(let q of Object.keys(u.get(L)?.dependencies??{})){let Y=P(q,[...B,L]);if(Y)return Y}k.delete(L),x.add(L)}};for(let L of u.keys()){let B=P(L,[]);if(B)return B}},f=()=>{let x=new Set(c);for(let P of u.values())for(let L of Object.keys(P.dependencies??{}))x.add(L);let k=[...x].sort().find(P=>!u.has(P));if(!k){let P=h();return P?(g=P,!1):!0}l.add(k);for(let P of r.get(k)??[]){if(++d>1e4)return p=!0,!1;if(u.set(k,P),m()&&f())return!0;if(u.delete(k),p)return!1}return!1};if(!f()){if(g&&!p)throw new Error(`Dependency cycle detected: ${g.join(" -> ")}`);for(let x of l)r.get(x)?.length||s.push(...n.get(x)??[]);for(let[x,k]of r){let P=[...new Set(k.flatMap(L=>Object.keys(L.dependencies??{})))].filter(L=>!r.has(L));P.length&&i.set(x,P)}return s.push({code:p?"RESOLUTION_LIMIT":i.size?"MISSING_DEPENDENCY":"UNSATISFIED_DEPENDENCY_RANGE",plugin:c.join(", "),message:p?"Plugin dependency search exceeded 10000 candidates":"No cached plugin selection satisfies all dependency ranges"}),a([])}let v=[],C=new Set,S=new Set,R=(x,k)=>{if(C.has(x))return;if(S.has(x))throw new Error(`Dependency cycle detected: ${[...k.slice(k.indexOf(x)),x].join(" -> ")}`);S.add(x);let P=u.get(x);for(let L of Object.keys(P.dependencies??{}))R(L,[...k,x]);S.delete(x),C.add(x),v.push(P)};for(let x of[...u.keys()].sort())R(x,[]);return a(v)}resolveAvailable(e){let t=[],r=this.resolve(e,[]),n=[],i=new Map;for(let s of[...new Set(e.map(a=>a.name))].sort())try{let a=this.resolve(e,[...t,s]);if(a.errors.length){n.push(...a.errors.map(c=>({...c,plugin:s})));for(let[c,l]of a.missing)i.set(c,l);continue}t.push(s),r=a}catch(a){n.push({code:"DEPENDENCY_CYCLE",plugin:s,message:a instanceof Error?a.message:String(a)})}return{...r,errors:n,missing:i}}canLoad(e,t){let r=Object.entries(e.dependencies??{}).filter(([n,i])=>{let s=t instanceof Set?void 0:t.get(n);return!s||!im(i)||!XM(s,i)}).map(([n])=>n);return{canLoad:!this.validateVersions(e)&&r.length===0,missingDeps:r}}validateVersions(e){if(!Ai(e.version))return{code:"INVALID_PLUGIN_VERSION",plugin:e.name,message:"Invalid plugin version"};for(let t of Object.values(e.dependencies??{}))if(!im(t))return{code:"INVALID_DEPENDENCY_RANGE",plugin:e.name,message:"Invalid dependency range"};if(e.minAqeVersion&&(!Ai(e.minAqeVersion)||!Ai(this.aqeVersion)||JM(this.aqeVersion,e.minAqeVersion)<0))return{code:"AQE_VERSION_INCOMPATIBLE",plugin:e.name,message:`Requires AQE ${e.minAqeVersion}; running ${this.aqeVersion}`}}}});function eQ(o){let e=[];return Ahe(o.name,e),xhe(o.entryPoint,e),khe(o.hooks,e),Phe(o.permissions,e),{safe:e.length===0,violations:e}}function Ahe(o,e){/[^\x20-\x7E]/.test(o)&&e.push(`Plugin name "${o}" contains non-ASCII characters`),Zj.has(o.toLowerCase())&&e.push(`Plugin name "${o}" is a reserved name`);for(let r of whe)o.toLowerCase().startsWith(r)&&e.push(`Plugin name "${o}" uses reserved prefix "${r}"`);let t=o.toLowerCase().replace(/[0o]/g,"o").replace(/[1il]/g,"l").replace(/[-_]/g,"");Zj.has(t)&&e.push(`Plugin name "${o}" is visually similar to a reserved name`)}function xhe(o,e){tQ(o,"entryPoint",e),(o.startsWith("/")||o.startsWith("\\"))&&e.push("entryPoint must be a relative path, not absolute")}function khe(o,e){if(o)for(let[t,r]of Object.entries(o))tQ(r,`hook[${t}]`,e)}function tQ(o,e,t){for(let r of Rhe)o.includes(r)&&t.push(`${e} contains dangerous path pattern "${r}"`);o.includes("\0")&&t.push(`${e} contains null byte (path injection attempt)`)}function Phe(o,e){if(!o)return;let t=["fs:write-root","net:arbitrary","exec:shell"];for(let r of o)t.includes(r)&&e.push(`Plugin requests dangerous permission: ${r}`)}var whe,Zj,Rhe,rQ=b(()=>{"use strict";whe=["aqe-core-","agentic-qe-core-","agentic-qe-internal-"],Zj=new Set(["aqe","agentic-qe","ruflo","claude-flow"]),Rhe=["..","~","/etc/","/proc/","/dev/","node_modules/"]});import*as sm from"fs";import*as am from"path";var lC,nQ=b(()=>{"use strict";ZM();lC=class{type="local";async resolve(e){let t=am.resolve(e),r=am.join(t,"qe-plugin.json");if(!sm.existsSync(r))throw new Error(`No qe-plugin.json found at ${r}`);let n=sm.readFileSync(r,"utf-8");return Jj(n)}async getPluginPath(e){let t=am.resolve(e);if(!sm.existsSync(t))throw new Error(`Plugin directory does not exist: ${t}`);return t}}});var uC,iQ=b(()=>{"use strict";ZM();eI();Yj();rQ();nQ();uC=class{cache;resolver;sources=new Map;constructor(e={}){this.cache=e.cache??new pl,this.resolver=new cC;let t=new lC;if(this.sources.set("local",t),e.sources)for(let r of e.sources)this.sources.set(r.type,r)}async install(e,t="local"){if(process.env.AQE_PLUGINS_DISABLED==="true")return{success:!1,errors:["Plugin loading is disabled (AQE_PLUGINS_DISABLED=true)"],securityViolations:[]};let r=[],n=this.sources.get(t);if(!n)return{success:!1,errors:[`Unknown source type: ${t}. Available: ${[...this.sources.keys()].join(", ")}`],securityViolations:[]};let i;try{i=await n.resolve(e)}catch(u){return{success:!1,errors:[`Failed to resolve plugin: ${u instanceof Error?u.message:String(u)}`],securityViolations:[]}}let s=YM(i);if(!s.valid)return{success:!1,manifest:i,errors:s.errors,securityViolations:[]};let a=eQ(i);if(!a.safe)return{success:!1,manifest:i,errors:["Plugin failed security checks"],securityViolations:a.violations};try{let u=this.cache.listCandidates().map(p=>p.manifest).filter(p=>p.name!==i.name),d=this.resolver.resolve([...u,i],[i.name]);if(d.errors.length)return{success:!1,manifest:i,errors:d.errors.map(p=>`${p.code}: ${p.message}`),securityViolations:[]}}catch(u){return{success:!1,manifest:i,errors:[u instanceof Error?u.message:String(u)],securityViolations:[]}}if(this.cache.has(i.name,i.version)){let u=this.cache.get(i.name,i.version);return{success:!0,manifest:i,cachePath:u.path,errors:[],securityViolations:[]}}let c;try{c=await n.getPluginPath(e)}catch(u){return{success:!1,manifest:i,errors:[`Failed to get plugin path: ${u instanceof Error?u.message:String(u)}`],securityViolations:[]}}let l=this.cache.store(i,c);return{success:!0,manifest:i,cachePath:l,errors:r,securityViolations:[]}}remove(e,t){if(t)return this.cache.remove(e,t);let r=this.cache.listVersions(e),n=!1;for(let i of r)this.cache.remove(e,i.manifest.version)&&(n=!0);return n}list(){return this.cache.listAll().map(t=>({name:t.manifest.name,version:t.manifest.version,description:t.manifest.description,domains:t.manifest.domains,source:"cached",cachePath:t.path}))}resolveLoadOrder(){let e=this.cache.listCandidates();return this.resolver.resolveAvailable(e.map(t=>t.manifest))}registerSource(e){this.sources.set(e.type,e)}}});async function to(o,e,t){try{let r=new Date().toISOString(),n=await o.get(sQ)??{overallLastSuccess:"",bootedAt:r,components:{}},i=n.components[e]??{lastSuccessAt:"",ticksSinceBoot:0,successesSinceBoot:0};if(i.ticksSinceBoot+=1,t.success)i.lastSuccessAt=r,i.successesSinceBoot+=1,delete i.lastError;else if(t.error){let a=t.error instanceof Error?t.error.message:String(t.error);i.lastError={message:a,at:r}}n.components[e]=i;let s=Object.values(n.components).map(a=>a?.lastSuccessAt??"").filter(a=>a!=="");n.overallLastSuccess=s.length>0?s.sort().pop():"",await o.set(sQ,n)}catch{}}var sQ,dC=b(()=>{"use strict";sQ="learning:loop-health"});import{randomUUID as Mhe}from"crypto";function _he(o){let e=Ohe(o.completed_at),t=o.id,r=[],n=e.getTime(),i=n-(o.duration_ms||0),s=o.success===1?1:0,a={id:o.id,task:o.task??"",agent:o.agent??"",domain:o.domain??"",startedAt:i,completedAt:n,durationMs:o.duration_ms??0,steps:[],success:o.success===1,quality:o.quality,reward:s,metadata:{sourceHook:o.source??"",bridgedAt:Date.now()}};r.push(om({type:"learning.ExperienceCaptured",source:"learning-optimization",correlationId:t,timestamp:e,payload:{experience:a,reward:s}}));let c=Lhe(o,e,t);return c&&r.push(c),r}function Lhe(o,e,t){let r={experienceId:o.id,agent:o.agent??"",task:o.task??"",success:o.success===1,quality:o.quality,durationMs:o.duration_ms};switch(o.domain){case"test-generation":return om({type:"test-generation.TestGenerated",source:"test-generation",correlationId:t,timestamp:e,payload:r});case"test-execution":return om({type:"test-execution.TestRunCompleted",source:"test-execution",correlationId:t,timestamp:e,payload:r});case"coverage-analysis":return om({type:o.success===1?"coverage-analysis.CoverageReportCreated":"coverage-analysis.CoverageGapDetected",source:"coverage-analysis",correlationId:t,timestamp:e,payload:r});case"code-intelligence":return om({type:"code-intelligence.FileChanged",source:"code-intelligence",correlationId:t,timestamp:e,payload:r});default:return null}}function om(o){return{id:Mhe(),type:o.type,timestamp:o.timestamp,source:o.source,correlationId:o.correlationId,payload:o.payload}}function Ohe(o){let e=new Date(o);return Number.isNaN(e.getTime())?new Date:e}var tI,Ihe,Dhe,pC,aQ=b(()=>{"use strict";te();dC();tI="aqe/bridge/captured-experiences/cursor",Ihe=5e3,Dhe=100,pC=class{constructor(e,t,r={}){this.eventBus=e;this.memory=t;this.intervalMs=r.intervalMs??Ihe,this.batchSize=r.batchSize??Dhe}eventBus;memory;cursor=0;intervalId;draining=!1;intervalMs;batchSize;async start(){if(this.intervalId)return;let e=await this.memory.get(tI);this.cursor=typeof e=="number"?e:0,await this.drainSafe(),this.intervalId=setInterval(()=>{this.drainSafe()},this.intervalMs),this.intervalId.unref?.()}async stop(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=void 0)}async drainOnce(){return this.drainSafe()}async drainSafe(){if(this.draining)return 0;this.draining=!0;try{let e=await this.drain();return await to(this.memory,"bridge",{success:!0}),e}catch(e){return console.warn("[CapturedExperienceBridge] drain failed:",e instanceof Error?e.message:e),await to(this.memory,"bridge",{success:!1,error:e instanceof Error?e:String(e)}),0}finally{this.draining=!1}}async drain(){let e=j();if(!e.isInitialized())return 0;let t=e.getDatabase();if(!t.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='captured_experiences'").get())return 0;let n=t.prepare(`SELECT rowid, id, task, agent, domain, success, quality,
|
|
873
873
|
duration_ms, source, completed_at
|
|
@@ -5796,7 +5796,7 @@ ${d.slice(0,4e3)}`))}catch(r){return y(w(r))}})}var jee=b(()=>{"use strict";$();
|
|
|
5796
5796
|
`).run(t)}catch(t){console.warn("[CoverageLearner] Retention cleanup failed:",E(t))}}async learnFromSession(e){this.sessionStore.add(e),this.persistSession(e);let t=this.calculateOverallImprovement(e);if(t<this.config.minCoverageImprovementToLearn)return null;let r=await this.extractStrategy(e,t);return this.reasoningBank&&r&&await this.storeStrategyAsPattern(r),r}calculateOverallImprovement(e){let t=e.beforeCoverage,r=e.afterCoverage,n=r.lines-t.lines,i=r.branches-t.branches,s=r.functions-t.functions;return n*.4+i*.35+s*.25}async extractStrategy(e,t){let r=this.extractFilePattern(e.targetPath),n=`${e.technique}:${r}`,i=this.strategies.get(n);return i?i={...i,avgImprovement:(i.avgImprovement*i.successCount+t)/(i.successCount+1),successCount:i.successCount+1,confidence:Math.min(1,i.confidence+.05),lastUsedAt:new Date}:i={id:`strategy-${Date.now()}-${sIe().slice(0,8)}`,description:this.generateStrategyDescription(e,t),technique:e.technique,filePatterns:[r],avgImprovement:t,successCount:1,confidence:.5,createdAt:new Date,lastUsedAt:new Date},this.strategies.set(n,i),i}extractFilePattern(e){let t=e.split("/"),n=t[t.length-1].split(".").pop()||"";return t.length>=2?`${t[t.length-2]}/*.${n}`:`*.${n}`}generateStrategyDescription(e,t){let n={"gap-analysis":"Identify and target uncovered code paths","branch-coverage":"Focus on branch conditions and decision points","edge-case-generation":"Generate tests for edge cases and boundary conditions","mutation-guided":"Use mutation testing to identify weak test areas","risk-based":"Prioritize high-risk code paths","semantic-analysis":"Use code semantics to generate meaningful tests","boundary-testing":"Test boundary conditions and limits","state-machine":"Model state transitions and test state changes","data-flow":"Follow data flow paths through the code"}[e.technique]||e.technique,i=e.gapsTargeted.filter(a=>a.addressed).length,s=e.gapsTargeted.length;return`${n} for ${this.extractFilePattern(e.targetPath)} files. Achieved ${t.toFixed(1)}% improvement. Addressed ${i}/${s} gaps with ${e.testsGenerated} tests.`}async storeStrategyAsPattern(e){this.reasoningBank&&await this.reasoningBank.storeQEPattern({patternType:"coverage-strategy",name:`Coverage Strategy: ${e.technique}`,description:e.description,template:{type:"workflow",content:JSON.stringify({technique:e.technique,filePatterns:e.filePatterns,avgImprovement:e.avgImprovement}),variables:[{name:"targetFile",type:"string",required:!0,description:"Target file to analyze"},{name:"currentCoverage",type:"number",required:!0,description:"Current coverage percentage"}]},context:{tags:["coverage",e.technique,...e.filePatterns]}})}getRecommendedStrategy(e){let t=this.extractFilePattern(e),r=null,n=0;for(let i of this.strategies.values())if(i.filePatterns.some(a=>t.includes(a.split("/").pop()||"")||a.includes(t.split("/").pop()||""))||i.filePatterns.length===0){let a=(Date.now()-i.lastUsedAt.getTime())/864e5,c=Math.max(.5,1-a/30),l=i.avgImprovement*i.confidence*c;l>n&&(n=l,r=i)}return r}getAllStrategies(){return Array.from(this.strategies.values())}getStrategiesByTechnique(e){return this.getAllStrategies().filter(t=>t.technique===e)}getSessionStats(){let e=this.sessionStore.getAll();if(e.length===0)return{totalSessions:0,successfulSessions:0,avgImprovement:0,byTechnique:new Map,strategiesLearned:0};let t=e.map(a=>this.calculateOverallImprovement(a)),r=t.filter(a=>a>=this.config.minCoverageImprovementToLearn).length,n=t.reduce((a,c)=>a+c,0)/t.length,i=new Map,s=new Map;for(let a of e){let c=s.get(a.technique)||[];c.push(a),s.set(a.technique,c)}for(let[a,c]of s){let l=c.map(u=>this.calculateOverallImprovement(u));i.set(a,{count:c.length,avgImprovement:l.reduce((u,d)=>u+d,0)/l.length})}return{totalSessions:e.length,successfulSessions:r,avgImprovement:n,byTechnique:i,strategiesLearned:this.strategies.size}}analyzeGapResolution(){let t=this.sessionStore.getAll().flatMap(i=>i.gapsTargeted);if(t.length===0)return{totalGapsTargeted:0,gapsAddressed:0,resolutionRate:0,byGapType:new Map};let r=t.filter(i=>i.addressed).length,n=new Map;for(let i of t){let s=n.get(i.type)||{targeted:0,addressed:0};s.targeted++,i.addressed&&s.addressed++,n.set(i.type,s)}return{totalGapsTargeted:t.length,gapsAddressed:r,resolutionRate:r/t.length,byGapType:n}}exportSessions(){return this.sessionStore.getAll()}importSessions(e){for(let t of e)this.sessionStore.add(t)}exportStrategies(){return this.getAllStrategies()}importStrategies(e){for(let t of e){let r=`${t.technique}:${t.filePatterns[0]||"*"}`;this.strategies.set(r,t)}}clear(){this.sessionStore.clear(),this.strategies.clear()}getLearnerStats(){return{totalSessions:this.sessionStore.size,totalStrategies:this.strategies.size,hasReasoningBank:this.reasoningBank!==null,minImprovementThreshold:this.config.minCoverageImprovementToLearn}}}});function Nte(o,e){return new MB(o,e)}var MB,Fte=b(()=>{"use strict";Cd();MB=class{weights;historicalScores=[];maxHistory;constructor(e={},t=100){this.weights={...wB,...e},this.maxHistory=t}calculateFromOutcome(e){let t=this.calculateDimensions(e),r=this.calculateOverall(t);return this.trackScore(r),{overall:r,dimensions:t,weights:this.weights,trend:this.calculateTrend(),calculatedAt:new Date}}calculateDimensions(e){return{effectiveness:this.calculateEffectiveness(e),coverage:this.calculateCoverageScore(e.coverage),mutationKill:e.mutationScore??.5,stability:this.calculateStability(e),maintainability:e.maintainabilityScore,performance:this.calculatePerformanceScore(e.executionTimeMs)}}calculateEffectiveness(e){return e.passed?e.flaky?.3:1:0}calculateCoverageScore(e){return(e.lines*.4+e.branches*.35+e.functions*.25)/100}calculateStability(e){return e.flaky?.2:e.flakinessScore!==void 0?1-e.flakinessScore:1}calculatePerformanceScore(e){return e<100?1:e<500?.8:e<2e3?.6:e<5e3?.4:e<1e4?.2:.1}calculateOverall(e){return this.weights.effectiveness*e.effectiveness+this.weights.coverage*e.coverage+this.weights.mutationKill*e.mutationKill+this.weights.stability*e.stability+this.weights.maintainability*e.maintainability+this.weights.performance*e.performance}trackScore(e){this.historicalScores.push(e),this.historicalScores.length>this.maxHistory&&(this.historicalScores=this.historicalScores.slice(-this.maxHistory))}calculateTrend(){if(this.historicalScores.length<10)return"stable";let e=this.historicalScores.slice(-10),t=this.historicalScores.slice(-20,-10);if(t.length===0)return"stable";let r=e.reduce((s,a)=>s+a,0)/e.length,n=t.reduce((s,a)=>s+a,0)/t.length,i=r-n;return i>.05?"improving":i<-.05?"declining":"stable"}calculateAggregate(e){if(e.length===0)return{overall:0,dimensions:{effectiveness:0,coverage:0,mutationKill:0,stability:0,maintainability:0,performance:0},weights:this.weights,trend:"stable",calculatedAt:new Date};let t={effectiveness:0,coverage:0,mutationKill:0,stability:0,maintainability:0,performance:0};for(let s of e){let a=this.calculateDimensions(s);t.effectiveness+=a.effectiveness,t.coverage+=a.coverage,t.mutationKill+=a.mutationKill,t.stability+=a.stability,t.maintainability+=a.maintainability,t.performance+=a.performance}let r=e.length,n={effectiveness:t.effectiveness/r,coverage:t.coverage/r,mutationKill:t.mutationKill/r,stability:t.stability/r,maintainability:t.maintainability/r,performance:t.performance/r};return{overall:this.calculateOverall(n),dimensions:n,weights:this.weights,trend:this.calculateTrend(),calculatedAt:new Date}}calculateDelta(e,t){let r={effectiveness:t.dimensions.effectiveness-e.dimensions.effectiveness,coverage:t.dimensions.coverage-e.dimensions.coverage,mutationKill:t.dimensions.mutationKill-e.dimensions.mutationKill,stability:t.dimensions.stability-e.dimensions.stability,maintainability:t.dimensions.maintainability-e.dimensions.maintainability,performance:t.dimensions.performance-e.dimensions.performance},n=t.overall-e.overall;return{overallDelta:n,dimensionDeltas:r,improved:n>0}}getRecommendations(e){let t=[],r=e.dimensions;return r.effectiveness<.8&&t.push("Improve test pass rate - investigate failing tests"),r.coverage<.7&&t.push("Increase code coverage - target uncovered paths"),r.mutationKill<.6&&t.push("Strengthen assertions - tests may be too weak"),r.stability<.9&&t.push("Address test flakiness - stabilize intermittent tests"),r.maintainability<.7&&t.push("Improve test maintainability - reduce complexity"),r.performance<.6&&t.push("Optimize test performance - reduce execution time"),t.length===0&&t.push("Quality is excellent - maintain current practices"),t}updateWeights(e){this.weights={...this.weights,...e}}getWeights(){return{...this.weights}}getStats(){let e=this.historicalScores.slice(-10),t=e.length>0?e.reduce((r,n)=>r+n,0)/e.length:0;return{scoresTracked:this.historicalScores.length,currentTrend:this.calculateTrend(),avgRecentScore:t}}clearHistory(){this.historicalScores=[]}}});function $te(o){return new IB(o)}var IB,qte=b(()=>{"use strict";Cd();IB=class{criteria;promotionHistory=[];demotionHistory=[];reasoningBank=null;config;constructor(e={}){this.config={...xa,...e},this.criteria={...RB}}connectReasoningBank(e){this.reasoningBank=e}evaluatePromotion(e,t){let r=e.tier,n=this.getNextTier(r);if(!n)return null;let i=this.criteria[n];if(this.meetsPromotionCriteria(t,i)){let s={patternId:e.id,fromTier:r,toTier:n,reason:this.generatePromotionReason(t,i),metrics:{successCount:t.successCount,successRate:t.successRate,qualityScore:t.qualityScore,ageDays:t.ageDays},timestamp:new Date};return this.promotionHistory.push(s),s}return null}evaluateDemotion(e,t){if(!this.config.autoDemote)return null;let r=e.tier;if(r==="short-term")return null;if(t.recentSuccessRate<.4||t.recentFailureCount>=5||t.qualityScore<.3){let i=this.getPreviousTier(r);if(!i)return null;let s={patternId:e.id,fromTier:r,toTier:i,reason:this.generateDemotionReason(t),metrics:{recentSuccessRate:t.recentSuccessRate,recentQualityScore:t.qualityScore,failureCount:t.recentFailureCount},timestamp:new Date};return this.demotionHistory.push(s),s}return null}async processPatternChange(e,t){let r=this.evaluateDemotion(e,t);if(r)return this.reasoningBank&&await this.reasoningBank.demotePattern(e.id),{action:"demoted",event:r};let n=this.evaluatePromotion(e,t);return n?(this.reasoningBank&&await this.reasoningBank.promotePattern(e.id),{action:"promoted",event:n}):{action:"unchanged"}}meetsPromotionCriteria(e,t){return e.successCount>=t.minSuccessCount&&e.successRate>=t.minSuccessRate&&e.qualityScore>=t.minQualityScore&&e.ageDays>=t.minAgeDays}getNextTier(e){let t=["short-term","working","long-term","permanent"],r=t.indexOf(e);return r<t.length-1?t[r+1]:null}getPreviousTier(e){let t=["short-term","working","long-term","permanent"],r=t.indexOf(e);return r>0?t[r-1]:null}generatePromotionReason(e,t){let r=[];return e.successCount>=t.minSuccessCount&&r.push(`${e.successCount} successful uses (>=${t.minSuccessCount})`),e.successRate>=t.minSuccessRate&&r.push(`${(e.successRate*100).toFixed(0)}% success rate (>=${t.minSuccessRate*100}%)`),e.qualityScore>=t.minQualityScore&&r.push(`${(e.qualityScore*100).toFixed(0)}% quality score (>=${t.minQualityScore*100}%)`),`Pattern promoted: ${r.join(", ")}`}generateDemotionReason(e){let t=[];return e.recentSuccessRate<.4&&t.push(`low recent success rate (${(e.recentSuccessRate*100).toFixed(0)}%)`),e.recentFailureCount>=5&&t.push(`${e.recentFailureCount} recent failures`),e.qualityScore<.3&&t.push(`low quality score (${(e.qualityScore*100).toFixed(0)}%)`),`Pattern demoted: ${t.join(", ")}`}updateCriteria(e,t){this.criteria[e]={...this.criteria[e],...t}}getCriteria(e){return{...this.criteria[e]}}getAllCriteria(){return{...this.criteria}}getPromotionHistory(e=100){return this.promotionHistory.slice(-e)}getDemotionHistory(e=100){return this.demotionHistory.slice(-e)}getStats(){let e={"short-term":0,working:0,"long-term":0,permanent:0};for(let s of this.promotionHistory)e[s.toTier]++;let t={"short-term":0,working:0,"long-term":0,permanent:0};for(let s of this.demotionHistory)t[s.toTier]++;let r=Date.now()-10080*60*1e3,n=this.promotionHistory.filter(s=>s.timestamp.getTime()>r).length,i=this.demotionHistory.filter(s=>s.timestamp.getTime()>r).length;return{totalPromotions:this.promotionHistory.length,totalDemotions:this.demotionHistory.length,promotionsByTier:e,demotionsByTier:t,recentPromotions:n,recentDemotions:i}}exportHistory(){return{promotions:[...this.promotionHistory],demotions:[...this.demotionHistory]}}importHistory(e){e.promotions&&this.promotionHistory.push(...e.promotions),e.demotions&&this.demotionHistory.push(...e.demotions)}clearHistory(){this.promotionHistory=[],this.demotionHistory=[]}}});async function Bte(o){let e=new DB(o);return await e.initialize(),Ute=e,e}function zte(){return Ute}var DB,Ute,Vte=b(()=>{"use strict";Cd();_te();Ote();Fte();qte();yh();DB=class{outcomeTracker;coverageLearner;qualityCalculator;promotionManager;routingFeedback;reasoningBank=null;config;constructor(e={}){this.config={...xa,...e},this.outcomeTracker=Dte(this.config),this.coverageLearner=Lte(this.config),this.qualityCalculator=Nte(this.config.qualityWeights),this.promotionManager=$te(this.config),this.routingFeedback=WO(this.config.maxOutcomesInMemory)}async initialize(){await Promise.all([this.outcomeTracker.initialize(),this.coverageLearner.initialize(),this.routingFeedback.initialize()])}connectReasoningBank(e){this.reasoningBank=e,this.outcomeTracker.connectReasoningBank(e),this.coverageLearner.connectReasoningBank(e),this.promotionManager.connectReasoningBank(e)}async recordTestOutcome(e){await this.outcomeTracker.track(e);let t=this.qualityCalculator.calculateFromOutcome(e),r;if(e.patternId&&this.reasoningBank){let n=await this.reasoningBank.searchQEPatterns(e.patternId,{limit:1});if(n.success&&n.value.length>0){let i=n.value[0].pattern,s=this.outcomeTracker.getPatternMetrics(e.patternId);if(s){let a=await this.promotionManager.processPatternChange(i,{patternId:e.patternId,successCount:s.successCount,failureCount:s.failureCount,successRate:s.successRate,qualityScore:s.avgQuality,ageDays:this.calculateAgeDays(i.createdAt),recentSuccessRate:this.calculateRecentSuccessRate(e.patternId),recentFailureCount:this.calculateRecentFailures(e.patternId)});r={action:a.action,tier:a.event&&"toTier"in a.event?a.event.toTier:void 0}}}}return{qualityScore:t,patternUpdate:r}}async recordCoverageSession(e){let t=await this.coverageLearner.learnFromSession(e);return{improvement:(e.afterCoverage.lines-e.beforeCoverage.lines+e.afterCoverage.branches-e.beforeCoverage.branches+e.afterCoverage.functions-e.beforeCoverage.functions)/3,strategyLearned:t!==null,strategyId:t?.id}}getRecommendedCoverageStrategy(e){return this.coverageLearner.getRecommendedStrategy(e)}getQualityRecommendations(){let e=this.outcomeTracker.getRecentOutcomes(50);if(e.length===0)return["No test outcomes recorded yet. Start tracking test results to get recommendations."];let t=this.qualityCalculator.calculateAggregate(e);return this.qualityCalculator.getRecommendations(t)}async recordRoutingOutcome(e){let t={id:e.taskId,description:e.taskDescription,complexity:"medium",domains:["test-generation"],context:{}},r={recommended:e.recommendedAgent,confidence:.8,reasoning:"Recorded from feedback",alternatives:[],scores:{similarity:.8,performance:.8,capabilities:.8,combined:.8},latencyMs:0,timestamp:e.timestamp};this.routingFeedback.recordOutcome(t,r,e.usedAgent,{success:e.success,qualityScore:e.qualityScore,durationMs:e.durationMs,error:e.error})}getRoutingAnalysis(){let e=this.routingFeedback.analyzeRoutingAccuracy(),t=this.routingFeedback.getImprovementRecommendations();return{totalOutcomes:e.totalOutcomes,recommendationFollowRate:1-e.overrideRate,successRateWhenFollowed:e.recommendationSuccessRate,successRateWhenOverridden:e.overrideSuccessRate,confidenceCorrelation:e.confidenceCorrelation,recommendations:t}}calculateAgeDays(e){return(Date.now()-e.getTime())/(1e3*60*60*24)}calculateRecentSuccessRate(e){let t=this.outcomeTracker.exportOutcomes().filter(n=>n.patternId===e).slice(-10);return t.length===0?0:t.filter(n=>n.passed&&!n.flaky).length/t.length}calculateRecentFailures(e){return this.outcomeTracker.exportOutcomes().filter(r=>r.patternId===e).slice(-10).filter(r=>!r.passed||r.flaky).length}getStats(){let e=this.outcomeTracker.getStats(),t=this.coverageLearner.getSessionStats(),r=this.promotionManager.getStats(),n=this.qualityCalculator.getStats(),i=this.outcomeTracker.getTrackerStats(),s=this.routingFeedback.analyzeRoutingAccuracy();return{testOutcomes:{total:e.totalTests,passRate:e.passRate,avgQuality:e.avgMaintainability,flakyCount:e.flakyTests},coverage:{totalSessions:t.totalSessions,successfulSessions:t.successfulSessions,avgImprovement:t.avgImprovement,strategiesLearned:t.strategiesLearned},patterns:{promoted:r.totalPromotions,demoted:r.totalDemotions,tracked:i.patternsTracked},quality:{currentTrend:n.currentTrend,avgRecentScore:n.avgRecentScore},routing:{totalOutcomes:s.totalOutcomes,recommendationFollowRate:1-s.overrideRate,successRateWhenFollowed:s.recommendationSuccessRate,successRateWhenOverridden:s.overrideSuccessRate},integrationStatus:{reasoningBankConnected:this.reasoningBank!==null}}}exportData(){return{outcomes:this.outcomeTracker.exportOutcomes(),sessions:this.coverageLearner.exportSessions(),strategies:this.coverageLearner.exportStrategies(),promotionHistory:this.promotionManager.exportHistory(),routingOutcomes:this.routingFeedback.exportOutcomes()}}importData(e){e.outcomes&&this.outcomeTracker.importOutcomes(e.outcomes),e.sessions&&this.coverageLearner.importSessions(e.sessions),e.strategies&&this.coverageLearner.importStrategies(e.strategies),e.promotionHistory&&this.promotionManager.importHistory(e.promotionHistory),e.routingOutcomes&&this.routingFeedback.importOutcomes(e.routingOutcomes)}clear(){this.outcomeTracker.clear(),this.coverageLearner.clear(),this.qualityCalculator.clearHistory(),this.promotionManager.clearHistory(),this.routingFeedback.clear()}};Ute=null});import{randomUUID as Td}from"crypto";function Sd(){return`test-${Td()}`}function Hte(o){return`${o}-${Td()}`}function gA(o){return{enabled:!0,agentId:Hte(o),message:"Experience captured asynchronously via learning pipeline"}}async function aIe(o,e,t,r,n){let i=Hte(o);try{let{kernel:s}=ve();if(!s)return{enabled:!1,agentId:i,message:"Learning engine not available - kernel not initialized"};let a=await cIe();if(!a)return{enabled:!1,agentId:i,message:"Learning engine not available"};let c=a.getExperienceCaptureService();if(!c)return{enabled:!1,agentId:i,message:"Experience capture service not available"};let l=oIe(e),u=c.startCapture(`${e}: ${JSON.stringify(t).slice(0,200)}`,{agent:o,domain:l||void 0,metadata:{tool:e,durationMs:n}});c.recordStep(u,{action:`execute-${e}`,result:typeof r=="object"?JSON.stringify(r).slice(0,500):String(r).slice(0,500),quality:.7});let d=await c.completeCapture(u,{success:!0,quality:.7});if(d.success){let p=d.value;return{enabled:!0,agentId:i,message:`Experience captured: ${p.id} (domain: ${l||"general"}, quality: ${p.quality})`,experienceId:p.id,domain:l||"general"}}return{enabled:!0,agentId:i,message:"Experience capture completed (no pattern extracted)"}}catch(s){return{enabled:!1,agentId:i,message:`Learning capture failed: ${E(s)}`}}}function oIe(o){return{test_generate_enhanced:"test-generation",test_execute_parallel:"test-execution",coverage_analyze_sublinear:"coverage-analysis",quality_assess:"quality-assessment",security_scan_comprehensive:"security-compliance",contract_validate:"contract-testing",accessibility_test:"visual-accessibility",chaos_test:"chaos-resilience",defect_predict:"defect-intelligence",requirements_validate:"requirements-validation",code_index:"code-intelligence"}[o]||null}async function cIe(){return Jte()}async function lIe(o,e,t,r){let n=zte();if(!n&&_B&&(n=await _B),!!n){if(o==="test-generation"&&e){let i=e.tests||e.generatedTests||[];for(let s of i.slice(0,20)){let a={id:String(s.id||Td()),testId:String(s.id||s.name||Td()),testName:String(s.name||s.testName||"generated-test"),generatedBy:"qe-test-generation",patternId:s.patternId,framework:s.framework||r.framework||"vitest",language:s.language||r.language||"typescript",domain:"test-generation",passed:s.passed!==!1,coverage:{lines:Number(s.coverageLines||0),branches:Number(s.coverageBranches||0),functions:Number(s.coverageFunctions||0)},executionTimeMs:Number(s.executionTimeMs||t/Math.max(i.length,1)),flaky:!!s.flaky,maintainabilityScore:Number(s.qualityScore||s.maintainability||.7),timestamp:new Date};await n.recordTestOutcome(a)}}if(o==="coverage-analysis"&&e){let i={id:Td(),targetPath:String(r.target||r.targetPath||"src/"),agentId:"qe-coverage-analysis",technique:r.technique||"gap-analysis",beforeCoverage:{lines:Number(e.beforeCoverage?.lines||0),branches:Number(e.beforeCoverage?.branches||0),functions:Number(e.beforeCoverage?.functions||0)},afterCoverage:{lines:Number(e.lineCoverage||e.lines||0),branches:Number(e.branchCoverage||e.branches||0),functions:Number(e.functionCoverage||e.functions||0)},testsGenerated:Number(e.testsGenerated||0),testsPassed:Number(e.testsPassed||0),gapsTargeted:(e.gaps||[]).map((s,a)=>({id:String(s.id||`gap-${Td().slice(0,8)}-${a}`),type:["uncovered-line","uncovered-branch","uncovered-function","partial-branch"].includes(String(s.type))?String(s.type):"uncovered-line",filePath:String(s.file||s.filePath||""),startLine:Number(s.line||s.startLine||0),endLine:s.endLine?Number(s.endLine):void 0,riskScore:Number(s.riskScore||.5),addressed:!!s.addressed})),durationMs:t,startedAt:new Date(Date.now()-t),completedAt:new Date};await n.recordCoverageSession(i)}}}function Wte(o){let e=o.split(`
|
|
5797
5797
|
`).length,t=(o.match(/if|switch|for|while|catch/g)||[]).length;return{score:e+t*2,level:t>5?"high":t>2?"medium":"low"}}function jte(o,e){let t=[];return o.level==="high"&&(t.push("Consider refactoring complex functions"),t.push("Add unit tests for each branch")),t.push("Consider adding edge case tests"),t.push("Add error handling tests"),e==="integration"&&(t.push("Add mock external dependencies"),t.push("Test API contract boundaries")),{recommendations:t,estimatedTime:`${Math.round(o.score*.5)} minutes`,confidence:.85}}function Qte(o,e,t,r){let n=[],i=/(?:function\s+(\w+)|const\s+(\w+)\s*=|def\s+(\w+)|func\s+(\w+))/g,s=[],a;for(;(a=i.exec(o))!==null;){let l=a[1]||a[2]||a[3]||a[4];l&&s.push(l)}for(let l=0;l<Math.min(s.length,r);l++){let u=s[l]||"exampleFunction";n.push({id:Sd(),name:`test_${u}_${l}`,type:e,parameters:[],assertions:[`${u}() === null`],expectedResult:null,estimatedDuration:e==="integration"?2e3:1e3,aiGenerated:!0})}(e==="integration"||r>s.length)&&n.push({id:Sd(),name:`integration_ComponentA_${n.length}`,type:"integration",parameters:[],assertions:["ComponentA integration test passes"],expectedResult:null,estimatedDuration:2e3,aiGenerated:!0});let c=["high-complexity","deep-nesting","null-handling","empty-input"];for(let l=n.length;l<r&&l-n.length<c.length;l++)n.push({id:Sd(),name:`edge_case_${c[l-n.length]}_${l}`,type:"unit",parameters:[],assertions:[`${c[l-n.length]} edge case handled`],expectedResult:null,estimatedDuration:1500,aiGenerated:!0});return n}function Kte(o,e){let t=[],r=o.split(`
|
|
5798
5798
|
`);return o.includes("eval(")&&t.push({type:"dangerous-eval",line:r.findIndex(n=>n.includes("eval("))+1,severity:"critical",suggestion:"Replace eval() with safer alternatives"}),o.includes("var ")&&(e==="javascript"||e==="typescript")&&t.push({type:"var-usage",line:r.findIndex(n=>n.includes("var "))+1,severity:"low",suggestion:"Use const or let instead of var"}),o.includes("any")&&e==="typescript"&&t.push({type:"any-type",line:r.findIndex(n=>n.includes("any"))+1,severity:"medium",suggestion:"Replace any with specific types"}),t}function dIe(o,e,t){return new Promise(r=>{let n=!1,i=setTimeout(()=>{n||(n=!0,r(t))},e);typeof i.unref=="function"&&i.unref(),o.then(s=>{n||(n=!0,clearTimeout(i),r(s))},()=>{n||(n=!0,clearTimeout(i),r(t))})})}function pIe(){if(!ty){let{kernel:o}=ve();if(!o)throw new Error("Kernel not initialized");ty=Mte(o);let e=ty;_B=Bte().then(t=>(e.setQualityFeedbackLoop(t),t)).catch(t=>(console.warn("[HandlerFactory] Failed to initialize QualityFeedbackLoop:",t),null))}return ty}function Xte(){if(ty=null,os){let o=os;os=null,o.dispose().catch(()=>{})}}async function Jte(){if(os)return os;try{let{kernel:o}=ve();if(!o)return null;let{createAQELearningEngine:e}=await Promise.resolve().then(()=>(GT(),A4)),t=o.memory,r=e(t,{projectRoot:process.cwd(),enableClaudeFlow:!1});return await r.initialize(),os=r,os}catch(o){return console.debug("[HandlerFactory] Learning engine init failed:",E(o)),null}}async function mIe(o,e){try{let t=await Jte();if(!t)return[];let r=e,n=await t.searchPatterns(o,{limit:5,minConfidence:.4,domain:r,useVectorSearch:!0});return!n.success||n.value.length===0?[]:n.value.filter(i=>i.similarity>=.4).map(i=>({name:i.pattern.name,description:i.pattern.description,similarity:i.similarity,confidence:i.pattern.confidence,canReuse:i.canReuse,patternId:i.pattern.id}))}catch(t){return console.debug("[HandlerFactory] Pattern search failed:",E(t)),[]}}async function gIe(o,e,t){try{let r=await mIe(o,e);return r.length>0&&console.debug(`[HandlerFactory] Found ${r.length} relevant patterns for ${e}`),await(await wa()).routeTask({task:o,domain:e,codeContext:t,agentType:`qe-${e}`,enablePatternSearch:!0,patternHints:r.length>0?r:void 0})}catch(r){return console.error(`[HandlerFactory] Routing failed for ${e}: ${r}`),null}}async function Gte(o,e,t,r){if(!(!o||o.length===0)&&os)try{for(let n of o)n.patternId&&await os.recordOutcome({patternId:n.patternId,success:e,metrics:{executionTimeMs:r},feedback:`Domain handler ${t} execution ${e?"succeeded":"failed"}`})}catch{}}function Jr(o){let{domain:e,taskType:t,priority:r="p1",defaultTimeout:n=18e4,buildTaskDescription:i,mapToPayload:s,mapToResult:a,calculateTimeout:c,includeCodeContext:l}=o;return async u=>{if(!be())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let{queen:d}=ve(),p=null;try{let m=i(u),g=l?.(u);p=await dIe(gIe(m,e,g),uIe,null);let h=s(u,p),f=c?.(u)??n,v=await d.submitTask({type:t,priority:r,targetDomains:[e],payload:h,timeout:f});if(!v.success)return{success:!1,error:v.error.message};let C=pIe(),S=d.getTaskStatus(v.value);if(!S)return{success:!1,error:"Task not found after submission"};let R=await C.execute(S.task);if(!R.success)return{success:!1,error:R.error||"Task execution failed"};let x=R.data,k=a(v.value,x,R.duration,R.savedFiles,u);Gte(p?.patternHints,!0,e,R.duration),aIe(`qe-${e}`,t,u,x,R.duration).catch(()=>{});try{await lIe(e,x,R.duration,u)}catch{}return{success:!0,data:k}}catch(m){let g=E(m);return Gte(p?.patternHints,!1,e,0),{success:!1,error:`Failed to ${t.replace(/-/g," ")}: ${g}`}}}}var ty,_B,os,uIe,LB=b(()=>{"use strict";Kn();EB();sA();M();Vte();ty=null,_B=null,os=null,uIe=Number(process.env.AQE_ROUTE_TIMEOUT_MS)||5e3});var hA,li,Yte=b(()=>{"use strict";hA=class{taskMetrics=[];agentMetrics=new Map;resourceSnapshots=[];workerLoads=new Map;activeTasks=new Map;lastCpuUsage=null;snapshotInterval=null;initialized=!1;initialize(){this.initialized||(this.initialized=!0,this.lastCpuUsage=process.cpuUsage(),this.snapshotInterval=setInterval(()=>{this.takeResourceSnapshot()},1e3),this.snapshotInterval.unref&&this.snapshotInterval.unref())}shutdown(){this.snapshotInterval&&(clearInterval(this.snapshotInterval),this.snapshotInterval=null),this.initialized=!1}startTask(e,t){this.ensureInitialized();let r={taskId:e,agentId:t,startTime:process.hrtime(),success:!1,retries:0};this.activeTasks.set(e,r),this.updateWorkerLoad(t,1,0)}recordRetry(e){let t=this.activeTasks.get(e);t&&t.retries++}completeTask(e,t){let r=this.activeTasks.get(e);if(!r)return 0;r.endTime=process.hrtime(),r.success=t;let n=process.hrtime(r.startTime);return r.durationMs=n[0]*1e3+n[1]/1e6,this.updateAgentMetrics(r),this.updateWorkerLoad(r.agentId,-1,1),this.taskMetrics.push(r),this.taskMetrics.length>100&&this.taskMetrics.shift(),this.activeTasks.delete(e),r.durationMs}getCpuUsagePercent(){if(this.ensureInitialized(),!this.lastCpuUsage)return this.lastCpuUsage=process.cpuUsage(),0;let e=process.cpuUsage(this.lastCpuUsage);this.lastCpuUsage=process.cpuUsage();let t=e.user+e.system,n=1e3*1e3,i=t/n*100;return Math.min(100,Math.max(0,i))}getMemoryUsagePercent(){let e=process.memoryUsage(),t=e.heapUsed/e.heapTotal*100;return Math.min(100,Math.max(0,t))}getResourceStats(e){return{cpu:this.getCpuUsagePercent(),memory:this.getMemoryUsagePercent()}}getAgentTaskStats(e){let t=this.agentMetrics.get(e);if(!t||t.taskCount===0)return{tasksCompleted:0,averageTime:0,successRate:1};let r=t.tasksCompleted+t.tasksFailed,n=r>0?t.tasksCompleted/r:1,i=t.taskCount>0?t.totalDurationMs/t.taskCount:0;return{tasksCompleted:t.tasksCompleted,averageTime:Math.round(i),successRate:Math.min(1,Math.max(0,n))}}getWorkerEfficiency(){if(this.taskMetrics.length===0)return .85;let t=this.taskMetrics.filter(a=>a.success).length/this.taskMetrics.length,n=this.taskMetrics.reduce((a,c)=>a+c.retries,0)/this.taskMetrics.length,i=Math.min(.2,n*.1),s=t*(1-i);return Math.min(1,Math.max(0,s))}getLoadBalanceScore(){if(this.workerLoads.size===0)return .9;let e=Array.from(this.workerLoads.values()).map(a=>a.completedTaskCount);if(e.length<=1)return 1;let t=e.reduce((a,c)=>a+c,0)/e.length;if(t===0)return 1;let r=e.reduce((a,c)=>a+Math.pow(c-t,2),0)/e.length,s=1/(1+Math.sqrt(r)/t);return Math.min(1,Math.max(0,s))}getRetryStats(){let e=0,t=0,r=0;for(let n of this.agentMetrics.values())e+=n.totalRetries,t+=n.successfulRetries,r+=n.maxRetriesReached;return{totalRetries:e,successfulRetries:t,maxRetriesReached:r}}getAverageExecutionTime(){if(this.taskMetrics.length===0)return 0;let e=this.taskMetrics.reduce((t,r)=>t+(r.durationMs||0),0);return Math.round(e/this.taskMetrics.length)}getWorkersUsed(){return this.workerLoads.size}getTestDurations(e){let t=[];if(this.taskMetrics.length===0){for(let n=0;n<e;n++)t.push(100+n*10);return t}let r=this.taskMetrics.map(n=>n.durationMs||200).sort((n,i)=>n-i);for(let n=0;n<e;n++){let i=n%r.length;t.push(Math.round(r[i]))}return t}recordSuccessfulRetry(e){let t=this.agentMetrics.get(e);t&&t.successfulRetries++}recordMaxRetriesReached(e){let t=this.agentMetrics.get(e);t&&t.maxRetriesReached++}reset(){this.taskMetrics=[],this.agentMetrics.clear(),this.resourceSnapshots=[],this.workerLoads.clear(),this.activeTasks.clear(),this.lastCpuUsage=null}ensureInitialized(){this.initialized||this.initialize()}updateAgentMetrics(e){let t=this.agentMetrics.get(e.agentId);t||(t={agentId:e.agentId,tasksCompleted:0,tasksFailed:0,totalRetries:0,successfulRetries:0,maxRetriesReached:0,totalDurationMs:0,taskCount:0},this.agentMetrics.set(e.agentId,t)),e.success?(t.tasksCompleted++,e.retries>0&&t.successfulRetries++):t.tasksFailed++,t.totalRetries+=e.retries,t.totalDurationMs+=e.durationMs||0,t.taskCount++}updateWorkerLoad(e,t,r){let n=this.workerLoads.get(e);n||(n={workerId:e,activeTaskCount:0,completedTaskCount:0,lastActivityTime:Date.now()},this.workerLoads.set(e,n)),n.activeTaskCount=Math.max(0,n.activeTaskCount+t),n.completedTaskCount+=r,n.lastActivityTime=Date.now()}takeResourceSnapshot(){let e=process.memoryUsage(),t=process.cpuUsage(),r={timestamp:Date.now(),cpuUser:t.user,cpuSystem:t.system,memoryHeapUsed:e.heapUsed,memoryHeapTotal:e.heapTotal,memoryExternal:e.external,memoryRss:e.rss};this.resourceSnapshots.push(r),this.resourceSnapshots.length>60&&this.resourceSnapshots.shift()}},li=new hA});var OB=b(()=>{"use strict";Yte()});var NB,FB,$B,qB,BB,UB,IQt,DQt,_Qt,LQt,OQt,NQt,Zte=b(()=>{"use strict";NB="^(?:UNKNOWN|[A-Za-z0-9][A-Za-z0-9._:/@+-]{0,255})$",FB="(?:^|[._:/@+\\-])(?:(?:[sS][kK]|[rR][kK]|[gG][hH][pPoOuUsSrR]|[gG][iI][tT][hH][uU][bB]_[pP][aA][tT]|[xX][oO][xX][bBaApPrRsS]|[nN][pP][mM]|[gG][lL][pP][aA][tT]|[pP][aA][tT])(?:[-_][A-Za-z0-9_-]*|(?=$|[.:/@+\\-]))|(?:[aA][kK][iI][aA]|[aA][sS][iI][aA]|[aA][iI][zZ][aA])[A-Za-z0-9]*)",$B="(?:^|[^A-Za-z0-9_-])(?:eyJ[A-Za-z0-9_-]*|e30|ew[A-Za-z0-9_-]*)\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+(?:$|[^A-Za-z0-9_-])",qB="(?:^|[._:/@+\\-])[A-Za-z0-9]{32,}(?:$|[._:/@+\\-])",BB="(?:(?:^|[.:@\\-])[A-Za-z0-9+/]{32,}={0,2}(?:$|[.:@\\-])|(?:^|[.:/@+\\-])[A-Za-z0-9_-]{48,}(?:$|[.:/@+\\-]))",UB="^\\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\\d|3[01])T(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d{1,9})?Z$",IQt=new RegExp(NB),DQt=new RegExp(FB),_Qt=new RegExp($B),LQt=new RegExp(qB),OQt=new RegExp(BB),NQt=new RegExp(UB)});function hIe(o){return typeof o=="object"&&o!==null&&!Array.isArray(o)}function fIe(o){return Array.isArray(o)&&o.every(e=>typeof e=="string")}function yIe(o){return typeof o=="number"&&Number.isFinite(o)&&o>=0&&o<=1}function tre(o){let e=[];return hIe(o)?(o.contract!=="risk-decision@1"&&e.push('contract must be "risk-decision@1"'),["approve","block","escalate"].includes(o.decision)||e.push("decision must be approve|block|escalate"),fIe(o.riskFactors)||e.push("riskFactors must be string[]"),yIe(o.confidence)||e.push("confidence must be a number in [0,1]"),(typeof o.rationale!="string"||o.rationale.length===0)&&e.push("rationale must be a non-empty string"),{valid:e.length===0,errors:e}):{valid:!1,errors:["not an object"]}}function rre(o){let{passed:e,qualityScore:t,recommendations:r=[]}=o,n=e===!0?"approve":e===!1?"block":"escalate";return{contract:"risk-decision@1",decision:n,riskFactors:r.slice(0,10),confidence:n==="escalate"?.5:.9,rationale:n==="escalate"?"Quality gate outcome indeterminate \u2014 manual review required":`Quality gate ${e?"passed":"failed"}${typeof t=="number"?` with score ${t}`:""}`}}function Ed(o){return{type:"string",pattern:NB,allOf:[{not:{pattern:FB}},{not:{pattern:$B}},{not:{pattern:o==="provider"||o==="requestedModel"||o==="resolvedModel"?qB:BB}}]}}var vIe,ere,wd,Yr,UQt,nre=b(()=>{"use strict";Zte();vIe={type:"number",minimum:0,maximum:1},ere={type:"array",items:{type:"string"}};wd={type:"string",pattern:"^(?:UNKNOWN|sha256:[a-f0-9]{64})$"},Yr={type:"string",pattern:"^sha256:[a-f0-9]{64}$"},UQt={$schema:"http://json-schema.org/draft-07/schema#",$id:"https://agentic-qe.dev/schemas/finding-verdict.schema.json",title:"FindingVerdict",type:"object",required:["contract","id","title","severity","confidence","evidence","verdict","refutations"],additionalProperties:!0,properties:{contract:{const:"finding-verdict@1"},id:{type:"string",minLength:1},title:{type:"string",minLength:1},file:{type:"string"},severity:{enum:["critical","high","medium","low","info"]},confidence:vIe,evidence:ere,verdict:{enum:["upheld","refuted","uncertain"]},refutations:ere,measurementReceipts:{type:"array",items:{type:"object",required:["contract","provider","requestedModel","resolvedModel","endpointClass","snapshotIdentity","semantics","fingerprint","requestHash","promptHash","configHash","parserSchemaHash","outputHash","parsedVoteHash","temperature","topP","seed","deterministic","cacheStatus","retryCount","timestamp","windowId","latencyMs","requestId"],additionalProperties:!1,properties:{contract:{const:"judge-measurement@1"},provider:Ed("provider"),requestedModel:Ed("requestedModel"),resolvedModel:Ed("resolvedModel"),endpointClass:{enum:["shared","dedicated","local","UNKNOWN"]},snapshotIdentity:{enum:["L0_UNKNOWN","L1_NAMED","L2_CONTENT_BOUND"]},semantics:{enum:["verified","provider-asserted","UNKNOWN"]},fingerprint:Ed("fingerprint"),requestHash:wd,promptHash:wd,configHash:wd,parserSchemaHash:wd,outputHash:wd,parsedVoteHash:wd,temperature:{type:["number","null"],minimum:0},topP:{type:["number","null"],minimum:0,maximum:1},seed:{type:["integer","null"],minimum:Number.MIN_SAFE_INTEGER,maximum:Number.MAX_SAFE_INTEGER},deterministic:{type:["boolean","null"]},cacheStatus:{enum:["hit","miss","bypass","UNKNOWN"]},retryCount:{type:"integer",minimum:0,maximum:Number.MAX_SAFE_INTEGER},timestamp:{anyOf:[{const:"UNKNOWN"},{type:"string",pattern:UB,format:"date-time"}]},windowId:Ed("windowId"),latencyMs:{type:["number","null"],minimum:0},requestId:Ed("requestId")},allOf:[{if:{properties:{snapshotIdentity:{const:"L2_CONTENT_BOUND"}}},then:{properties:{fingerprint:{not:{const:"UNKNOWN"}},requestHash:Yr,promptHash:Yr,configHash:Yr,parserSchemaHash:Yr,outputHash:Yr,parsedVoteHash:Yr}}},{if:{properties:{snapshotIdentity:{const:"L1_NAMED"}}},then:{properties:{resolvedModel:{not:{const:"UNKNOWN"}}}}},{if:{properties:{semantics:{const:"verified"}}},then:{properties:{snapshotIdentity:{const:"L2_CONTENT_BOUND"},fingerprint:{not:{const:"UNKNOWN"}},requestHash:Yr,promptHash:Yr,configHash:Yr,parserSchemaHash:Yr,outputHash:Yr,parsedVoteHash:Yr}}},{if:{properties:{semantics:{enum:["verified","provider-asserted"]}}},then:{properties:{snapshotIdentity:{not:{const:"L0_UNKNOWN"}},fingerprint:{not:{const:"UNKNOWN"}}}}}]}}}}});function bIe(o){if(!o)return"typescript";let e=o.toLowerCase().trim(),t={ts:"typescript",js:"javascript",py:"python","c#":"csharp","c-sharp":"csharp",cs:"csharp",golang:"go",rs:"rust",kt:"kotlin"};return t[e]?t[e]:ire.includes(e)?e:null}function CIe(o){let e=[],t=o.split(`
|
|
5799
|
-
`);for(let r of t){let n=r.trim(),i=n.match(/expect\((.+?)\)\.(to\w+)\((.+?)\)/);if(i){e.push(`expect(${i[1]}).${i[2]}(${i[3]})`);continue}let s=n.match(/assert\w*\((.+)\)/);if(s){e.push(s[0]);continue}let a=n.match(/(?:it|test)\s*\(\s*['"`](.+?)['"`]/);a&&e.push(a[1])}return e.length>0?e:["test generated from source analysis"]}var ire,sre,are,ore,cre,lre,ure,dre,pre,mre,gre,hre,fre=b(()=>{"use strict";LB();OB();Ro();nre();nu();ire=Object.keys(wo);sre={domain:"test-generation",taskType:"generate-tests",priority:"p1",defaultTimeout:12e4,buildTaskDescription:o=>`Generate ${o.testType||"unit"} tests for ${o.language||"typescript"} code`,includeCodeContext:o=>o.sourceCode,mapToPayload:(o,e)=>{let t=bIe(o.language);if(t===null)throw new Error(`Unsupported language '${o.language}'. Supported languages: ${ire.join(", ")}. Open a feature request for additional language support.`);let r;if(o.framework){r=o.framework;let i=x_[r];if(i&&i!==t){let s=a=>a==="javascript"||a==="typescript";if(!(s(i)&&s(t)))throw new Error(`Framework '${r}' targets ${i}, but language was '${t}'. Either pick a matching framework or omit \`framework\` to use the default (${wo[t]}).`)}}else r=wo[t];let n=$s(o.behaviorExamples);return{sourceCode:o.sourceCode,behaviorExamples:n,filePath:o.filePath,language:t,framework:r,testType:o.testType||"unit",coverageGoal:o.coverageGoal||80,aiEnhancement:o.aiEnhancement!==!1,detectAntiPatterns:o.detectAntiPatterns||!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}},mapToResult:(o,e,t,r,n)=>{let i=n?.sourceCode||"",s=n?.language||"typescript",a=n?.testType||"unit",c=e.testsGenerated||6,l=Wte(i),u=n?.aiEnhancement!==!1?jte(l,a):{recommendations:[],estimatedTime:"0 minutes",confidence:0},d=n?.detectAntiPatterns?Kte(i,s):[],p=gA("test-generator"),m=e.tests,g=Array.isArray(m)&&m.length>0&&m[0].testCode,h=e.llmEnhanced===!0,f=g?m.map((v,C)=>({id:Sd(),name:v.name||`test_${C}`,type:v.type||a,parameters:[],assertions:v.testCode?CIe(v.testCode):[`test assertion ${C}`],expectedResult:null,estimatedDuration:v.type==="integration"?2e3:1e3,aiGenerated:h,testCode:v.testCode,generationMode:v.generationMode,generationLimits:v.generationLimits,sourceFile:v.sourceFile,testFile:v.testFile||v.file})):Qte(i,a,s,c);return{tests:f,antiPatterns:d,suggestions:d.map(v=>`Fix: ${v.type} - ${v.suggestion}`),aiInsights:u,coverage:{predicted:e.coverageEstimate??null,confidence:e.coverageEstimate==null?0:h?.9:0,achievable:e.coverageEstimate==null?null:!0},properties:f.filter(v=>v.type==="property").map(v=>({name:v.name,invariant:"output_matches_expectation"})),language:s,complexity:l,learning:p,taskId:o,status:"completed",testsGenerated:f.length,coverageEstimate:e.coverageEstimate??null,patternsUsed:e.patternsUsed||["assertion-patterns","mock-generation","edge-case-detection"],duration:t,savedFiles:r,llmEnhanced:h,...e.generationMode?{generationMode:e.generationMode}:{},...e.note?{note:e.note}:{}}}},are={domain:"test-execution",taskType:"execute-tests",priority:"p1",defaultTimeout:3e5,buildTaskDescription:o=>`Execute ${o.testFiles?.length||0} test files with ${o.parallel!==!1?"parallel":"sequential"} execution`,mapToPayload:(o,e)=>({testFiles:o.testFiles||[],testSuites:o.testSuites||[],parallel:o.parallel!==!1,parallelism:o.parallelism||4,retryCount:o.retryCount||3,timeout:o.timeout||6e4,collectCoverage:o.collectCoverage||!1,reportFormat:o.reportFormat||"json",routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),calculateTimeout:o=>o.timeout||3e5,mapToResult:(o,e,t,r,n)=>{let i=e.total||0,s=e.passed||0,a=e.failed||0,c=e.coverage,l=n?.parallelism||4,u=li.getRetryStats(),d=li.getWorkersUsed(),p={workersUsed:d>0?d:Math.min(l,i||1),efficiency:li.getWorkerEfficiency(),loadBalance:li.getLoadBalanceScore(),avgExecutionTime:t/Math.max(i,1)},m={totalRetries:u.totalRetries,successfulRetries:u.successfulRetries,maxRetriesReached:u.maxRetriesReached},g=gA("test-executor");return{workerStats:p,retryStats:m,results:(()=>{let h=li.getTestDurations(i);return Array.from({length:i},(f,v)=>({id:Sd(),name:`test_case_${v}`,status:v<s?"passed":"failed",duration:h[v]||200,retries:0}))})(),summary:{totalTests:i,passRate:i>0?s/i*100:0,avgDuration:t/Math.max(i,1),parallelEfficiency:p.efficiency},learning:g,taskId:o,status:"completed",total:i,passed:s,failed:a,duration:t,coverage:c,savedFiles:r}}},ore={domain:"coverage-analysis",taskType:"analyze-coverage",priority:"p1",defaultTimeout:18e4,buildTaskDescription:o=>`Analyze coverage for ${o.target||"project"} with gap detection`,mapToPayload:(o,e)=>({target:o.target||".",includeRisk:o.includeRisk||!1,detectGaps:o.detectGaps!==!1,mlPowered:o.mlPowered||!1,prioritization:o.prioritization||"complexity",routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,r)=>{let n=e.summary,i=n?.files??e.totalFiles??0,s=e.gaps||[],a=e.branchDataCollected===!0,c=e.functionDataCollected===!0,l=a?n?.branch??e.branchCoverage??null:null,u=c?n?.function??e.functionCoverage??null:null,d=e.estimated===!0,p=e.measured===!0,g=n?.line??e.lineCoverage??null,f=n?.statement??e.statementCoverage??g,v=gA("coverage-analyzer"),C=s.map((x,k)=>{let P=x;return P?.file?{id:`gap-${Date.now()}-${k}`,file:P.file,line:P.lines?.[0]||0,uncoveredLines:P.lines||[],type:P.type||"uncovered-line",severity:P.severity||"medium",reason:P.reason||"Missing test case",priority:P.priority||"medium",suggestion:P.suggestedTest||"Add test coverage",suggestedTest:P.suggestedTest||"Add test coverage",riskScore:P.riskScore||.5,confidence:P.confidence??(p?.7:.2),estimated:P.estimated===!0||d}:null}).filter(x=>x!==null),S=e.coverageByFile;return{coverageByFile:S?S.map(x=>({file:x.file,lineCoverage:x.lineCoverage||0,branchCoverage:x.branchCoverage??null,functionCoverage:x.functionCoverage??null})):[],gapAnalysis:{totalGaps:C.length,highPriority:C.filter(x=>x.priority==="high").length,gaps:C},trends:{lineCoverageTrend:i>0?"stable":"no-data",branchCoverageTrend:i>0?"stable":"no-data",weeklyChange:0},aiInsights:i>0?{recommendations:d?["ESTIMATED RESULT \u2014 no instrumentation ran. The figures below are a static guess from source shape, not measured coverage. Do not act on individual gaps without running real instrumentation first.",...e.recommendations||[]]:e.recommendations||["Run tests with coverage enabled to get accurate metrics"],riskAssessment:d||!p||g===null?"unknown":g<70?"high":g<85?"medium":"low",confidence:d?.2:p?.88:0}:{recommendations:["No coverage data found. Run tests with coverage first (e.g., npm test -- --coverage, or pytest --cov)"],riskAssessment:"unknown",confidence:0},learning:v,taskId:o,status:"completed",lineCoverage:g,branchCoverage:l,functionCoverage:u,statementCoverage:f,totalFiles:i,gaps:C,duration:t,savedFiles:r,estimated:d,measured:p,coverageMethod:e.coverageMethod??"unknown",branchDataCollected:a,functionDataCollected:c,...e.warning?{warning:e.warning}:{}}}},cre={domain:"quality-assessment",taskType:"assess-quality",priority:"p0",defaultTimeout:18e4,buildTaskDescription:o=>`Assess quality with ${o.runGate?"quality gate":"metrics analysis"}`,mapToPayload:(o,e)=>{if(o.runGate!==void 0&&typeof o.runGate!="boolean")throw new Error("runGate must be a boolean.");return{runGate:o.runGate??!1,threshold:o.threshold||80,metrics:o.metrics||["coverage","complexity","maintainability"],routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}},mapToResult:(o,e,t,r)=>{let n=rre({passed:typeof e.passed=="boolean"?e.passed:void 0,qualityScore:e.qualityScore,recommendations:e.recommendations||[]});return{taskId:o,status:"completed",...typeof e.qualityScore=="number"?{qualityScore:e.qualityScore}:{},...Array.isArray(e.checks)?{checks:e.checks}:{},passed:e.passed||!1,metrics:e.metrics||{},recommendations:e.recommendations||[],duration:t,savedFiles:r,...tre(n).valid?{riskDecision:n}:{}}}},lre={domain:"security-compliance",taskType:"scan-security",priority:"p0",defaultTimeout:6e5,buildTaskDescription:o=>{let e=[];return o.sast!==!1&&e.push("SAST"),o.dast&&e.push("DAST"),`Security scan (${e.join(", ")}) for ${o.target||"project"}`},mapToPayload:(o,e)=>{for(let t of["sast","dast"])if(o[t]!==void 0&&typeof o[t]!="boolean")throw new Error(`${t} must be a boolean`);return{sast:o.sast!==!1,dast:o.dast||!1,compliance:o.compliance||[],target:o.target||".",targetUrl:o.targetUrl,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}},mapToResult:(o,e,t,r)=>({taskId:o,status:e.evidence?.completeness==="complete"?"completed":e.evidence?.completeness==="partial"?"partial":e.evidence?"unavailable":"unverified",vulnerabilities:e.vulnerabilities||0,critical:e.critical||0,high:e.high||0,medium:e.medium||0,low:e.low||0,informational:e.informational||0,topVulnerabilities:e.topVulnerabilities||[],findings:e.findings,recommendations:e.recommendations||[],evidence:e.evidence,limitations:e.limitations||["Execution receipts unavailable; scan completeness is unverified."],...e.evidence?{filesScanned:e.filesScanned,jstsFilesScanned:e.jstsFilesScanned,otherFilesScanned:e.otherFilesScanned,coverage:e.coverage}:{},deepAnalysisPerformed:!!(e.evidence&&e.deepAnalysisPerformed===!0),analysisDepth:e.analysisDepth,scanTypes:e.scanTypes,note:e.note,duration:t,savedFiles:r})},ure={domain:"contract-testing",taskType:"validate-contracts",priority:"p1",defaultTimeout:18e4,buildTaskDescription:o=>`Validate API contract at ${o.contractPath}`,mapToPayload:(o,e)=>({contractPath:o.contractPath,providerUrl:o.providerUrl,consumerName:o.consumerName,checkBreakingChanges:o.checkBreakingChanges!==!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,r)=>({taskId:o,status:"completed",valid:e.valid||!1,breakingChanges:e.breakingChanges||[],warnings:e.warnings||[],duration:t,savedFiles:r})},dre={domain:"visual-accessibility",taskType:"test-accessibility",priority:"p1",defaultTimeout:18e4,buildTaskDescription:o=>`Test accessibility for ${o.url} against ${o.standard||"WCAG 2.1 AA"} standard`,mapToPayload:(o,e)=>({url:o.url,standard:o.standard||"wcag21-aa",includeScreenReader:o.includeScreenReader||!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,r)=>({taskId:o,status:"completed",passed:e.passed||!1,score:e.score||0,violations:e.violations||[],warnings:e.warnings||[],duration:t,savedFiles:r})},pre={domain:"chaos-resilience",taskType:"run-chaos",priority:"p2",defaultTimeout:9e4,buildTaskDescription:o=>`Run chaos test with ${o.faultType||"latency"} fault injection on ${o.target}`,mapToPayload:(o,e)=>({faultType:o.faultType||"latency",target:o.target,duration:o.duration||3e4,intensity:o.intensity||50,dryRun:o.dryRun!==!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),calculateTimeout:o=>(o.duration||3e4)+6e4,mapToResult:(o,e,t,r)=>({taskId:o,status:"completed",faultType:e.faultType||"latency",resilience:e.resilience||{recovered:!1,recoveryTime:0,dataLoss:!1},duration:t,savedFiles:r})},mre={domain:"defect-intelligence",taskType:"predict-defects",priority:"p1",defaultTimeout:18e4,buildTaskDescription:o=>`Predict defects in ${o.target||"codebase"} with ${o.lookback||30} day lookback`,mapToPayload:(o,e)=>({target:o.target||".",lookback:o.lookback||30,minConfidence:o.minConfidence||.7,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,r)=>({taskId:o,status:"completed",predictedDefects:e.predictedDefects||[],riskScore:e.riskScore||0,recommendations:e.recommendations||[],duration:t,savedFiles:r})},gre={domain:"requirements-validation",taskType:"validate-requirements",priority:"p1",defaultTimeout:18e4,buildTaskDescription:o=>`Validate requirements${o.generateBDD?" and generate BDD scenarios":""}`,mapToPayload:(o,e)=>({requirementsPath:o.requirementsPath,testPath:o.testPath,generateBDD:o.generateBDD||!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,r)=>({taskId:o,status:"completed",requirementsAnalyzed:e.requirementsAnalyzed||0,testable:e.testable||0,coverage:e.coverage||0,bddScenarios:e.bddScenarios||[],duration:t,savedFiles:r})},hre={domain:"code-intelligence",taskType:"index-code",priority:"p2",defaultTimeout:3e5,buildTaskDescription:o=>`Index code in ${o.target||"codebase"}${o.incremental?" incrementally":""}`,mapToPayload:(o,e)=>({target:o.target||".",incremental:o.incremental||!1,gitSince:o.gitSince,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,r)=>({taskId:o,status:"completed",filesIndexed:e.filesIndexed||0,symbolsExtracted:e.symbolsExtracted||0,relationsFound:e.relationsFound||0,duration:t,savedFiles:r})}});function fA(){Xte()}function zB(o){FN(o)}async function VB(o){let e=Vo();if(!e)return{success:!1,error:"Infrastructure healing not initialized"};let t=e.getStats(),r=e.getObserver(),n=[...r.getFailingServices()],i=e.getRerunManager(),s={ready:e.isReady(),stats:t,failingServices:n,pendingReruns:i.hasPendingReruns(),pendingRerunCount:i.getPendingRerunCount(),servicesWithPendingReruns:i.getServicesWithPendingReruns()};if(o.verbose){let a=r.getLastObservation();a&&(s.lastObservation={id:a.id,totalLinesParsed:a.totalLinesParsed,infraFailureCount:a.infraFailures.length,vulnerabilityCount:a.vulnerabilities.length,observedAt:a.observedAt,parsingDurationMs:a.parsingDurationMs})}return{success:!0,data:s}}async function GB(o){let e=Vo();if(!e)return{success:!1,error:"Infrastructure healing not initialized"};if(!o.output)return{success:!1,error:"Missing required parameter: output"};e.feedTestOutput(o.output);let t=e.getObserver(),r=t.getLastObservation();return{success:!0,data:{infraFailuresDetected:r?.infraFailures.length??0,failingServices:[...t.getFailingServices()],vulnerabilities:r?.vulnerabilities.map(n=>({type:n.type,severity:n.severity,affectedAgents:n.affectedAgents,description:n.description}))??[]}}}async function HB(o){let e=Vo();if(!e)return{success:!1,error:"Infrastructure healing not initialized"};let t=await e.runRecoveryCycle(),r=o.services?.length?t.filter(n=>o.services.includes(n.serviceName)):t;return{success:!0,data:{recoveryResults:r.map(n=>({serviceName:n.serviceName,recovered:n.recovered,totalAttempts:n.totalAttempts,totalDurationMs:n.totalDurationMs,escalated:n.escalated,affectedTestIds:n.affectedTestIds})),summary:{attempted:r.length,succeeded:r.filter(n=>n.recovered).length,failed:r.filter(n=>!n.recovered).length,testsToRerun:r.flatMap(n=>[...n.affectedTestIds])}}}}var yre,vre,bre,Cre,Tre,Sre,Ere,wre,Rre,Are,xre,yA=b(()=>{"use strict";LB();fre();UE();yre=Jr(sre),vre=Jr(are),bre=Jr(ore),Cre=Jr(cre),Tre=Jr(lre),Sre=Jr(ure),Ere=Jr(dre),wre=Jr(pre),Rre=Jr(mre),Are=Jr(gre),xre=Jr(hre)});var WB,g3t,h3t,vA,kre=b(()=>{"use strict";rr();M();WB={minConfidenceForExit:.85,minSuccessRate:.9,maxPatternAge:10080*60*1e3,minQualityScore:.7,minSuccessfulUses:2,maxSearchResults:5,similarityThreshold:.8,verbose:!1},g3t={minConfidenceForExit:.75,minSuccessRate:.8,maxPatternAge:336*60*60*1e3,minQualityScore:.6,minSuccessfulUses:1,maxSearchResults:10,similarityThreshold:.7,verbose:!1},h3t={minConfidenceForExit:.92,minSuccessRate:.95,maxPatternAge:4320*60*1e3,minQualityScore:.85,minSuccessfulUses:3,maxSearchResults:3,similarityThreshold:.9,verbose:!1},vA=class{patternStore;config;reuseHistory=[];attemptHistory=[];constructor(e,t){this.patternStore=e,this.config={...WB,...t}}async checkEarlyExit(e){let t=performance.now(),r=new Date;try{let n=e.domain??ln(e.description)??void 0,i={limit:this.config.maxSearchResults*2,useVectorSearch:!!e.embedding};n&&(i.domain=n),e.context&&(i.context={language:e.context.language,framework:e.context.framework,testType:e.context.testType});let s=e.embedding??e.description,a=await this.patternStore.search(s,i),c=performance.now()-t;if(!a.success){let p="error"in a?a.error.message:"Unknown error",m=this.createResult(!1,"search_error",`Pattern search failed: ${p}`,c);return this.recordAttempt("search_error",n),m}let l=a.value;if(l.length===0){let p=this.createResult(!1,"no_matching_pattern","No matching patterns found in store",c);return this.recordAttempt("no_matching_pattern",n),p}let u=null;for(let{pattern:p,score:m}of l){let g=this.evaluatePatternEligibility(p,m,r);if(g.eligible){let h=this.estimateTokensSaved(p),f={canExit:!0,reusedPattern:p,estimatedTokensSaved:h,confidence:p.confidence,similarityScore:m,reason:"pattern_reused",explanation:`Reusing pattern "${p.name}" with ${(p.confidence*100).toFixed(1)}% confidence`,searchLatencyMs:c};return this.recordReuse(p.id,h,p.confidence,m,c,n),this.config.verbose&&console.log(`[EarlyExitTokenOptimizer] Pattern reuse: ${p.name} (confidence: ${p.confidence.toFixed(2)}, similarity: ${m.toFixed(2)}, tokens saved: ${h})`),f}u===null&&(u={reason:g.reason,explanation:g.explanation})}if(u){let p=this.createResult(!1,u.reason,u.explanation,c);return this.recordAttempt(u.reason,n),p}let d=this.createResult(!1,"no_matching_pattern",`Found ${l.length} patterns but none met eligibility criteria`,c);return this.recordAttempt("no_matching_pattern",n),d}catch(n){let i=performance.now()-t,s=this.createResult(!1,"search_error",`Error during pattern search: ${E(n)}`,i);return this.recordAttempt("search_error"),s}}evaluatePatternEligibility(e,t,r){if(t<this.config.similarityThreshold)return{eligible:!1,reason:"similarity_too_low",explanation:`Similarity ${(t*100).toFixed(1)}% < threshold ${(this.config.similarityThreshold*100).toFixed(1)}%`};if(e.confidence<this.config.minConfidenceForExit)return{eligible:!1,reason:"confidence_too_low",explanation:`Confidence ${(e.confidence*100).toFixed(1)}% < threshold ${(this.config.minConfidenceForExit*100).toFixed(1)}%`};if(e.successRate<this.config.minSuccessRate)return{eligible:!1,reason:"success_rate_too_low",explanation:`Success rate ${(e.successRate*100).toFixed(1)}% < threshold ${(this.config.minSuccessRate*100).toFixed(1)}%`};let n=r.getTime()-e.lastUsedAt.getTime();if(n>this.config.maxPatternAge){let i=Math.floor(n/864e5),s=Math.floor(this.config.maxPatternAge/(1440*60*1e3));return{eligible:!1,reason:"pattern_too_old",explanation:`Pattern age ${i} days > max ${s} days`}}return e.qualityScore<this.config.minQualityScore?{eligible:!1,reason:"quality_score_too_low",explanation:`Quality score ${(e.qualityScore*100).toFixed(1)}% < threshold ${(this.config.minQualityScore*100).toFixed(1)}%`}:e.successfulUses<this.config.minSuccessfulUses?{eligible:!1,reason:"insufficient_uses",explanation:`Successful uses ${e.successfulUses} < minimum ${this.config.minSuccessfulUses}`}:{eligible:!0,reason:"pattern_reused",explanation:"Pattern meets all eligibility criteria"}}estimateTokensSaved(e){let t=100,r=Math.ceil(e.template.content.length/4);t+=r,t+=50;let s={"test-template":1.5,"assertion-pattern":1,"mock-pattern":1.2,"coverage-strategy":1.3,"api-contract":1.4,"visual-baseline":1.1,"perf-benchmark":1.4,"flaky-fix":1.3,"error-handling":1.2}[e.patternType]??1;return Math.ceil(t*s)}createResult(e,t,r,n){return{canExit:e,reason:t,explanation:r,searchLatencyMs:n}}recordReuse(e,t,r,n,i,s){this.reuseHistory.push({patternId:e,tokensSaved:t,confidence:r,similarity:n,latencyMs:i,domain:s,timestamp:new Date}),this.attemptHistory.push({reason:"pattern_reused",domain:s,timestamp:new Date}),this.reuseHistory.length>1e4&&(this.reuseHistory=this.reuseHistory.slice(-1e4))}recordAttempt(e,t){this.attemptHistory.push({reason:e,domain:t,timestamp:new Date}),this.attemptHistory.length>1e4&&(this.attemptHistory=this.attemptHistory.slice(-1e4))}recordSuccessfulReuse(e){this.patternStore.recordUsage(e,!0).catch(t=>{console.warn(`[EarlyExitTokenOptimizer] Failed to record successful reuse for ${e}:`,t)})}recordFailedReuse(e){this.patternStore.recordUsage(e,!1).catch(t=>{console.warn(`[EarlyExitTokenOptimizer] Failed to record failed reuse for ${e}:`,t)})}getReuseStats(){let e=this.reuseHistory.length,t=this.attemptHistory.length,r=0,n=0,i=0,s=0;for(let l of this.reuseHistory)r+=l.tokensSaved,n+=l.confidence,i+=l.similarity,s+=l.latencyMs;let a={pattern_reused:0,no_matching_pattern:0,confidence_too_low:0,success_rate_too_low:0,pattern_too_old:0,quality_score_too_low:0,insufficient_uses:0,similarity_too_low:0,search_error:0};for(let l of this.attemptHistory)a[l.reason]++;let c={};for(let l of this.reuseHistory){let u=l.domain??"unknown";c[u]||(c[u]={reuses:0,tokens:0}),c[u].reuses++,c[u].tokens+=l.tokensSaved}return{totalReuses:e,tokensSaved:r,avgConfidence:e>0?n/e:0,avgSimilarity:e>0?i/e:0,avgSearchLatencyMs:e>0?s/e:0,totalAttempts:t,exitRate:t>0?e/t:0,reasonBreakdown:a,domainBreakdown:c}}resetStats(){this.reuseHistory=[],this.attemptHistory=[]}getConfig(){return{...this.config}}updateConfig(e){Object.assign(this.config,e)}}});var ny={};Q(ny,{DEFAULT_SESSION_CACHE_CONFIG:()=>Pre,SessionOperationCache:()=>CA,getSessionCache:()=>ry,resetSessionCache:()=>wIe});import{createHash as TIe}from"crypto";function SIe(){let o="3.15.0",e=(process.env.AQE_SESSION_CACHE_SALT??"").trim();return e?`${o}+${e}`:o}function EIe(o){let e=JSON.parse(JSON.stringify(o));function t(r){if(r===null||typeof r!="object")return JSON.stringify(r);if(Array.isArray(r))return"["+r.map(t).join(",")+"]";let n=r;return"{"+Object.keys(n).sort().map(i=>JSON.stringify(i)+":"+t(n[i])).join(",")+"}"}return t(e)}function bA(){try{let{getUnifiedMemory:o}=(te(),Ye(Rr)),e=o();return e.isInitialized()?e.getDatabase():null}catch{return null}}function ry(o){return bc||(bc=new CA(o),bc.loadFromDb()),bc}function wIe(){bc&&bc.clear(),bc=null}var Pre,CA,bc,Rd=b(()=>{"use strict";Pre={enabled:!0,maxEntries:500,ttlMs:3600*1e3,persistToDb:!0};CA=class{cache=new Map;config;hits=0;misses=0;generation=0;constructor(e){this.config={...Pre,...e}}computeFingerprint(e,t,r){let n=EIe({action:t,build:SIe(),domain:e,input:r});return TIe("sha256").update(n).digest("hex").slice(0,16)}get(e){if(!this.config.enabled)return null;let t=this.cache.get(e);return t?Date.now()-t.cachedAt>this.config.ttlMs?(this.cache.delete(e),this.misses++,null):(t.hitCount++,t.lastHitAt=Date.now(),this.hits++,t):(this.misses++,null)}set(e,t,r,n,i){if(!this.config.enabled)return;!this.cache.has(e)&&this.cache.size>=this.config.maxEntries&&this.evictOldest();let s={fingerprint:e,domain:t,action:r,result:n,tokensSaved:i,cachedAt:Date.now(),hitCount:0,lastHitAt:0};this.cache.set(e,s),this.config.persistToDb&&this.persistEntry(s)}loadFromDb(){try{let e=bA();if(!e)return;let t=Date.now()-this.config.ttlMs,r=e.prepare(`SELECT key, value FROM kv_store
|
|
5799
|
+
`);for(let r of t){let n=r.trim(),i=n.match(/expect\((.+?)\)\.(to\w+)\((.+?)\)/);if(i){e.push(`expect(${i[1]}).${i[2]}(${i[3]})`);continue}let s=n.match(/assert\w*\((.+)\)/);if(s){e.push(s[0]);continue}let a=n.match(/(?:it|test)\s*\(\s*['"`](.+?)['"`]/);a&&e.push(a[1])}return e.length>0?e:["test generated from source analysis"]}var ire,sre,are,ore,cre,lre,ure,dre,pre,mre,gre,hre,fre=b(()=>{"use strict";LB();OB();Ro();nre();nu();ire=Object.keys(wo);sre={domain:"test-generation",taskType:"generate-tests",priority:"p1",defaultTimeout:12e4,buildTaskDescription:o=>`Generate ${o.testType||"unit"} tests for ${o.language||"typescript"} code`,includeCodeContext:o=>o.sourceCode,mapToPayload:(o,e)=>{let t=bIe(o.language);if(t===null)throw new Error(`Unsupported language '${o.language}'. Supported languages: ${ire.join(", ")}. Open a feature request for additional language support.`);let r;if(o.framework){r=o.framework;let i=x_[r];if(i&&i!==t){let s=a=>a==="javascript"||a==="typescript";if(!(s(i)&&s(t)))throw new Error(`Framework '${r}' targets ${i}, but language was '${t}'. Either pick a matching framework or omit \`framework\` to use the default (${wo[t]}).`)}}else r=wo[t];let n=$s(o.behaviorExamples);return{sourceCode:o.sourceCode,behaviorExamples:n,filePath:o.filePath,language:t,framework:r,testType:o.testType||"unit",coverageGoal:o.coverageGoal||80,aiEnhancement:o.aiEnhancement!==!1,detectAntiPatterns:o.detectAntiPatterns||!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}},mapToResult:(o,e,t,r,n)=>{let i=n?.sourceCode||"",s=n?.language||"typescript",a=n?.testType||"unit",c=e.testsGenerated||6,l=Wte(i),u=n?.aiEnhancement!==!1?jte(l,a):{recommendations:[],estimatedTime:"0 minutes",confidence:0},d=n?.detectAntiPatterns?Kte(i,s):[],p=gA("test-generator"),m=e.tests,g=Array.isArray(m)&&m.length>0&&m[0].testCode,h=e.llmEnhanced===!0,f=g?m.map((v,C)=>({id:Sd(),name:v.name||`test_${C}`,type:v.type||a,parameters:[],assertions:v.testCode?CIe(v.testCode):[`test assertion ${C}`],expectedResult:null,estimatedDuration:v.type==="integration"?2e3:1e3,aiGenerated:h,testCode:v.testCode,generationMode:v.generationMode,generationLimits:v.generationLimits,sourceFile:v.sourceFile,testFile:v.testFile||v.file})):Qte(i,a,s,c);return{tests:f,antiPatterns:d,suggestions:d.map(v=>`Fix: ${v.type} - ${v.suggestion}`),aiInsights:u,coverage:{predicted:e.coverageEstimate??null,confidence:e.coverageEstimate==null?0:h?.9:0,achievable:e.coverageEstimate==null?null:!0},properties:f.filter(v=>v.type==="property").map(v=>({name:v.name,invariant:"output_matches_expectation"})),language:s,complexity:l,learning:p,taskId:o,status:"completed",testsGenerated:f.length,coverageEstimate:e.coverageEstimate??null,patternsUsed:e.patternsUsed||["assertion-patterns","mock-generation","edge-case-detection"],duration:t,savedFiles:r,llmEnhanced:h,...e.generationMode?{generationMode:e.generationMode}:{},...e.note?{note:e.note}:{}}}},are={domain:"test-execution",taskType:"execute-tests",priority:"p1",defaultTimeout:3e5,buildTaskDescription:o=>`Execute ${o.testFiles?.length||0} test files with ${o.parallel!==!1?"parallel":"sequential"} execution`,mapToPayload:(o,e)=>({testFiles:o.testFiles||[],testSuites:o.testSuites||[],parallel:o.parallel!==!1,parallelism:o.parallelism||4,retryCount:o.retryCount||3,timeout:o.timeout||6e4,collectCoverage:o.collectCoverage||!1,reportFormat:o.reportFormat||"json",routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),calculateTimeout:o=>o.timeout||3e5,mapToResult:(o,e,t,r,n)=>{let i=e.total||0,s=e.passed||0,a=e.failed||0,c=e.coverage,l=n?.parallelism||4,u=li.getRetryStats(),d=li.getWorkersUsed(),p={workersUsed:d>0?d:Math.min(l,i||1),efficiency:li.getWorkerEfficiency(),loadBalance:li.getLoadBalanceScore(),avgExecutionTime:t/Math.max(i,1)},m={totalRetries:u.totalRetries,successfulRetries:u.successfulRetries,maxRetriesReached:u.maxRetriesReached},g=gA("test-executor");return{workerStats:p,retryStats:m,results:(()=>{let h=li.getTestDurations(i);return Array.from({length:i},(f,v)=>({id:Sd(),name:`test_case_${v}`,status:v<s?"passed":"failed",duration:h[v]||200,retries:0}))})(),summary:{totalTests:i,passRate:i>0?s/i*100:0,avgDuration:t/Math.max(i,1),parallelEfficiency:p.efficiency},learning:g,taskId:o,status:"completed",total:i,passed:s,failed:a,duration:t,coverage:c,savedFiles:r}}},ore={domain:"coverage-analysis",taskType:"analyze-coverage",priority:"p1",defaultTimeout:18e4,buildTaskDescription:o=>`Analyze coverage for ${o.target||"project"} with gap detection`,mapToPayload:(o,e)=>({target:o.target||".",includeRisk:o.includeRisk||!1,detectGaps:o.detectGaps!==!1,mlPowered:o.mlPowered||!1,prioritization:o.prioritization||"complexity",routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,r)=>{let n=e.summary,i=n?.files??e.totalFiles??0,s=e.gaps||[],a=e.branchDataCollected===!0,c=e.functionDataCollected===!0,l=a?n?.branch??e.branchCoverage??null:null,u=c?n?.function??e.functionCoverage??null:null,d=e.estimated===!0,p=e.measured===!0,g=n?.line??e.lineCoverage??null,f=n?.statement??e.statementCoverage??g,v=gA("coverage-analyzer"),C=s.map((x,k)=>{let P=x;return P?.file?{id:`gap-${Date.now()}-${k}`,file:P.file,line:P.lines?.[0]||0,uncoveredLines:P.lines||[],type:P.type||"uncovered-line",severity:P.severity||"medium",reason:P.reason||"Missing test case",priority:P.priority||"medium",suggestion:P.suggestedTest||"Add test coverage",suggestedTest:P.suggestedTest||"Add test coverage",riskScore:P.riskScore||.5,confidence:P.confidence??(p?.7:.2),estimated:P.estimated===!0||d}:null}).filter(x=>x!==null),S=e.coverageByFile;return{coverageByFile:S?S.map(x=>({file:x.file,lineCoverage:x.lineCoverage||0,branchCoverage:x.branchCoverage??null,functionCoverage:x.functionCoverage??null})):[],gapAnalysis:{totalGaps:C.length,highPriority:C.filter(x=>x.priority==="high").length,gaps:C},trends:{lineCoverageTrend:i>0?"stable":"no-data",branchCoverageTrend:i>0?"stable":"no-data",weeklyChange:0},aiInsights:i>0?{recommendations:d?["ESTIMATED RESULT \u2014 no instrumentation ran. The figures below are a static guess from source shape, not measured coverage. Do not act on individual gaps without running real instrumentation first.",...e.recommendations||[]]:e.recommendations||["Run tests with coverage enabled to get accurate metrics"],riskAssessment:d||!p||g===null?"unknown":g<70?"high":g<85?"medium":"low",confidence:d?.2:p?.88:0}:{recommendations:["No coverage data found. Run tests with coverage first (e.g., npm test -- --coverage, or pytest --cov)"],riskAssessment:"unknown",confidence:0},learning:v,taskId:o,status:"completed",lineCoverage:g,branchCoverage:l,functionCoverage:u,statementCoverage:f,totalFiles:i,gaps:C,duration:t,savedFiles:r,estimated:d,measured:p,coverageMethod:e.coverageMethod??"unknown",branchDataCollected:a,functionDataCollected:c,...e.warning?{warning:e.warning}:{}}}},cre={domain:"quality-assessment",taskType:"assess-quality",priority:"p0",defaultTimeout:18e4,buildTaskDescription:o=>`Assess quality with ${o.runGate?"quality gate":"metrics analysis"}`,mapToPayload:(o,e)=>{if(o.runGate!==void 0&&typeof o.runGate!="boolean")throw new Error("runGate must be a boolean.");return{runGate:o.runGate??!1,threshold:o.threshold||80,metrics:o.metrics||["coverage","complexity","maintainability"],routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}},mapToResult:(o,e,t,r)=>{let n=rre({passed:typeof e.passed=="boolean"?e.passed:void 0,qualityScore:e.qualityScore,recommendations:e.recommendations||[]});return{taskId:o,status:"completed",...typeof e.qualityScore=="number"?{qualityScore:e.qualityScore}:{},...Array.isArray(e.checks)?{checks:e.checks}:{},passed:e.passed||!1,metrics:e.metrics||{},recommendations:e.recommendations||[],duration:t,savedFiles:r,...tre(n).valid?{riskDecision:n}:{}}}},lre={domain:"security-compliance",taskType:"scan-security",priority:"p0",defaultTimeout:6e5,buildTaskDescription:o=>{let e=[];return o.sast!==!1&&e.push("SAST"),o.dast&&e.push("DAST"),`Security scan (${e.join(", ")}) for ${o.target||"project"}`},mapToPayload:(o,e)=>{for(let t of["sast","dast"])if(o[t]!==void 0&&typeof o[t]!="boolean")throw new Error(`${t} must be a boolean`);return{sast:o.sast!==!1,dast:o.dast||!1,compliance:o.compliance||[],target:o.target||".",targetUrl:o.targetUrl,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}},mapToResult:(o,e,t,r)=>({taskId:o,status:e.evidence?.completeness==="complete"?"completed":e.evidence?.completeness==="partial"?"partial":e.evidence?"unavailable":"unverified",vulnerabilities:e.vulnerabilities||0,critical:e.critical||0,high:e.high||0,medium:e.medium||0,low:e.low||0,informational:e.informational||0,topVulnerabilities:e.topVulnerabilities||[],findings:e.findings,recommendations:e.recommendations||[],evidence:e.evidence,limitations:e.limitations||["Execution receipts unavailable; scan completeness is unverified."],...e.evidence?{filesScanned:e.filesScanned,jstsFilesScanned:e.jstsFilesScanned,otherFilesScanned:e.otherFilesScanned,coverage:e.coverage}:{},deepAnalysisPerformed:!!(e.evidence&&e.deepAnalysisPerformed===!0),analysisDepth:e.analysisDepth,scanTypes:e.scanTypes,note:e.note,duration:t,savedFiles:r})},ure={domain:"contract-testing",taskType:"validate-contracts",priority:"p1",defaultTimeout:18e4,buildTaskDescription:o=>`Validate API contract at ${o.contractPath}`,mapToPayload:(o,e)=>({contractPath:o.contractPath,providerUrl:o.providerUrl,consumerName:o.consumerName,checkBreakingChanges:o.checkBreakingChanges!==!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,r)=>({taskId:o,status:"completed",valid:e.valid||!1,breakingChanges:e.breakingChanges||[],warnings:e.warnings||[],duration:t,savedFiles:r})},dre={domain:"visual-accessibility",taskType:"test-accessibility",priority:"p1",defaultTimeout:18e4,buildTaskDescription:o=>`Test accessibility for ${o.url} against ${o.standard||"WCAG 2.1 AA"} standard`,mapToPayload:(o,e)=>({url:o.url,standard:o.standard||"wcag21-aa",includeScreenReader:o.includeScreenReader||!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,r)=>({taskId:o,status:"completed",passed:e.passed||!1,score:e.score||0,violations:e.violations||[],warnings:e.warnings||[],duration:t,savedFiles:r})},pre={domain:"chaos-resilience",taskType:"run-chaos",priority:"p2",defaultTimeout:9e4,buildTaskDescription:o=>`Run chaos test with ${o.faultType||"latency"} fault injection on ${o.target}`,mapToPayload:(o,e)=>({faultType:o.faultType||"latency",target:o.target,duration:o.duration||3e4,intensity:o.intensity||50,dryRun:o.dryRun!==!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),calculateTimeout:o=>(o.duration||3e4)+6e4,mapToResult:(o,e,t,r)=>({taskId:o,status:"completed",faultType:e.faultType||"latency",resilience:e.resilience||{recovered:!1,recoveryTime:0,dataLoss:!1},duration:t,savedFiles:r})},mre={domain:"defect-intelligence",taskType:"predict-defects",priority:"p1",defaultTimeout:18e4,buildTaskDescription:o=>`Predict defects in ${o.target||"codebase"} with ${o.lookback||30} day lookback`,mapToPayload:(o,e)=>({target:o.target||".",lookback:o.lookback||30,minConfidence:o.minConfidence||.7,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,r)=>({taskId:o,status:"completed",predictedDefects:e.predictedDefects||[],riskScore:e.riskScore||0,recommendations:e.recommendations||[],duration:t,savedFiles:r})},gre={domain:"requirements-validation",taskType:"validate-requirements",priority:"p1",defaultTimeout:18e4,buildTaskDescription:o=>`Validate requirements${o.generateBDD?" and generate BDD scenarios":""}`,mapToPayload:(o,e)=>({requirementsPath:o.requirementsPath,testPath:o.testPath,generateBDD:o.generateBDD||!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,r)=>({taskId:o,status:"completed",requirementsAnalyzed:e.requirementsAnalyzed||0,testable:e.testable||0,coverage:e.coverage||0,bddScenarios:e.bddScenarios||[],duration:t,savedFiles:r})},hre={domain:"code-intelligence",taskType:"index-code",priority:"p2",defaultTimeout:3e5,buildTaskDescription:o=>`Index code in ${o.target||"codebase"}${o.incremental?" incrementally":""}`,mapToPayload:(o,e)=>({target:o.target||".",incremental:o.incremental||!1,gitSince:o.gitSince,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,r)=>({taskId:o,status:"completed",filesIndexed:e.filesIndexed||0,symbolsExtracted:e.symbolsExtracted||0,relationsFound:e.relationsFound||0,duration:t,savedFiles:r})}});function fA(){Xte()}function zB(o){FN(o)}async function VB(o){let e=Vo();if(!e)return{success:!1,error:"Infrastructure healing not initialized"};let t=e.getStats(),r=e.getObserver(),n=[...r.getFailingServices()],i=e.getRerunManager(),s={ready:e.isReady(),stats:t,failingServices:n,pendingReruns:i.hasPendingReruns(),pendingRerunCount:i.getPendingRerunCount(),servicesWithPendingReruns:i.getServicesWithPendingReruns()};if(o.verbose){let a=r.getLastObservation();a&&(s.lastObservation={id:a.id,totalLinesParsed:a.totalLinesParsed,infraFailureCount:a.infraFailures.length,vulnerabilityCount:a.vulnerabilities.length,observedAt:a.observedAt,parsingDurationMs:a.parsingDurationMs})}return{success:!0,data:s}}async function GB(o){let e=Vo();if(!e)return{success:!1,error:"Infrastructure healing not initialized"};if(!o.output)return{success:!1,error:"Missing required parameter: output"};e.feedTestOutput(o.output);let t=e.getObserver(),r=t.getLastObservation();return{success:!0,data:{infraFailuresDetected:r?.infraFailures.length??0,failingServices:[...t.getFailingServices()],vulnerabilities:r?.vulnerabilities.map(n=>({type:n.type,severity:n.severity,affectedAgents:n.affectedAgents,description:n.description}))??[]}}}async function HB(o){let e=Vo();if(!e)return{success:!1,error:"Infrastructure healing not initialized"};let t=await e.runRecoveryCycle(),r=o.services?.length?t.filter(n=>o.services.includes(n.serviceName)):t;return{success:!0,data:{recoveryResults:r.map(n=>({serviceName:n.serviceName,recovered:n.recovered,totalAttempts:n.totalAttempts,totalDurationMs:n.totalDurationMs,escalated:n.escalated,affectedTestIds:n.affectedTestIds})),summary:{attempted:r.length,succeeded:r.filter(n=>n.recovered).length,failed:r.filter(n=>!n.recovered).length,testsToRerun:r.flatMap(n=>[...n.affectedTestIds])}}}}var yre,vre,bre,Cre,Tre,Sre,Ere,wre,Rre,Are,xre,yA=b(()=>{"use strict";LB();fre();UE();yre=Jr(sre),vre=Jr(are),bre=Jr(ore),Cre=Jr(cre),Tre=Jr(lre),Sre=Jr(ure),Ere=Jr(dre),wre=Jr(pre),Rre=Jr(mre),Are=Jr(gre),xre=Jr(hre)});var WB,g3t,h3t,vA,kre=b(()=>{"use strict";rr();M();WB={minConfidenceForExit:.85,minSuccessRate:.9,maxPatternAge:10080*60*1e3,minQualityScore:.7,minSuccessfulUses:2,maxSearchResults:5,similarityThreshold:.8,verbose:!1},g3t={minConfidenceForExit:.75,minSuccessRate:.8,maxPatternAge:336*60*60*1e3,minQualityScore:.6,minSuccessfulUses:1,maxSearchResults:10,similarityThreshold:.7,verbose:!1},h3t={minConfidenceForExit:.92,minSuccessRate:.95,maxPatternAge:4320*60*1e3,minQualityScore:.85,minSuccessfulUses:3,maxSearchResults:3,similarityThreshold:.9,verbose:!1},vA=class{patternStore;config;reuseHistory=[];attemptHistory=[];constructor(e,t){this.patternStore=e,this.config={...WB,...t}}async checkEarlyExit(e){let t=performance.now(),r=new Date;try{let n=e.domain??ln(e.description)??void 0,i={limit:this.config.maxSearchResults*2,useVectorSearch:!!e.embedding};n&&(i.domain=n),e.context&&(i.context={language:e.context.language,framework:e.context.framework,testType:e.context.testType});let s=e.embedding??e.description,a=await this.patternStore.search(s,i),c=performance.now()-t;if(!a.success){let p="error"in a?a.error.message:"Unknown error",m=this.createResult(!1,"search_error",`Pattern search failed: ${p}`,c);return this.recordAttempt("search_error",n),m}let l=a.value;if(l.length===0){let p=this.createResult(!1,"no_matching_pattern","No matching patterns found in store",c);return this.recordAttempt("no_matching_pattern",n),p}let u=null;for(let{pattern:p,score:m}of l){let g=this.evaluatePatternEligibility(p,m,r);if(g.eligible){let h=this.estimateTokensSaved(p),f={canExit:!0,reusedPattern:p,estimatedTokensSaved:h,confidence:p.confidence,similarityScore:m,reason:"pattern_reused",explanation:`Reusing pattern "${p.name}" with ${(p.confidence*100).toFixed(1)}% confidence`,searchLatencyMs:c};return this.recordReuse(p.id,h,p.confidence,m,c,n),this.config.verbose&&console.log(`[EarlyExitTokenOptimizer] Pattern reuse: ${p.name} (confidence: ${p.confidence.toFixed(2)}, similarity: ${m.toFixed(2)}, tokens saved: ${h})`),f}u===null&&(u={reason:g.reason,explanation:g.explanation})}if(u){let p=this.createResult(!1,u.reason,u.explanation,c);return this.recordAttempt(u.reason,n),p}let d=this.createResult(!1,"no_matching_pattern",`Found ${l.length} patterns but none met eligibility criteria`,c);return this.recordAttempt("no_matching_pattern",n),d}catch(n){let i=performance.now()-t,s=this.createResult(!1,"search_error",`Error during pattern search: ${E(n)}`,i);return this.recordAttempt("search_error"),s}}evaluatePatternEligibility(e,t,r){if(t<this.config.similarityThreshold)return{eligible:!1,reason:"similarity_too_low",explanation:`Similarity ${(t*100).toFixed(1)}% < threshold ${(this.config.similarityThreshold*100).toFixed(1)}%`};if(e.confidence<this.config.minConfidenceForExit)return{eligible:!1,reason:"confidence_too_low",explanation:`Confidence ${(e.confidence*100).toFixed(1)}% < threshold ${(this.config.minConfidenceForExit*100).toFixed(1)}%`};if(e.successRate<this.config.minSuccessRate)return{eligible:!1,reason:"success_rate_too_low",explanation:`Success rate ${(e.successRate*100).toFixed(1)}% < threshold ${(this.config.minSuccessRate*100).toFixed(1)}%`};let n=r.getTime()-e.lastUsedAt.getTime();if(n>this.config.maxPatternAge){let i=Math.floor(n/864e5),s=Math.floor(this.config.maxPatternAge/(1440*60*1e3));return{eligible:!1,reason:"pattern_too_old",explanation:`Pattern age ${i} days > max ${s} days`}}return e.qualityScore<this.config.minQualityScore?{eligible:!1,reason:"quality_score_too_low",explanation:`Quality score ${(e.qualityScore*100).toFixed(1)}% < threshold ${(this.config.minQualityScore*100).toFixed(1)}%`}:e.successfulUses<this.config.minSuccessfulUses?{eligible:!1,reason:"insufficient_uses",explanation:`Successful uses ${e.successfulUses} < minimum ${this.config.minSuccessfulUses}`}:{eligible:!0,reason:"pattern_reused",explanation:"Pattern meets all eligibility criteria"}}estimateTokensSaved(e){let t=100,r=Math.ceil(e.template.content.length/4);t+=r,t+=50;let s={"test-template":1.5,"assertion-pattern":1,"mock-pattern":1.2,"coverage-strategy":1.3,"api-contract":1.4,"visual-baseline":1.1,"perf-benchmark":1.4,"flaky-fix":1.3,"error-handling":1.2}[e.patternType]??1;return Math.ceil(t*s)}createResult(e,t,r,n){return{canExit:e,reason:t,explanation:r,searchLatencyMs:n}}recordReuse(e,t,r,n,i,s){this.reuseHistory.push({patternId:e,tokensSaved:t,confidence:r,similarity:n,latencyMs:i,domain:s,timestamp:new Date}),this.attemptHistory.push({reason:"pattern_reused",domain:s,timestamp:new Date}),this.reuseHistory.length>1e4&&(this.reuseHistory=this.reuseHistory.slice(-1e4))}recordAttempt(e,t){this.attemptHistory.push({reason:e,domain:t,timestamp:new Date}),this.attemptHistory.length>1e4&&(this.attemptHistory=this.attemptHistory.slice(-1e4))}recordSuccessfulReuse(e){this.patternStore.recordUsage(e,!0).catch(t=>{console.warn(`[EarlyExitTokenOptimizer] Failed to record successful reuse for ${e}:`,t)})}recordFailedReuse(e){this.patternStore.recordUsage(e,!1).catch(t=>{console.warn(`[EarlyExitTokenOptimizer] Failed to record failed reuse for ${e}:`,t)})}getReuseStats(){let e=this.reuseHistory.length,t=this.attemptHistory.length,r=0,n=0,i=0,s=0;for(let l of this.reuseHistory)r+=l.tokensSaved,n+=l.confidence,i+=l.similarity,s+=l.latencyMs;let a={pattern_reused:0,no_matching_pattern:0,confidence_too_low:0,success_rate_too_low:0,pattern_too_old:0,quality_score_too_low:0,insufficient_uses:0,similarity_too_low:0,search_error:0};for(let l of this.attemptHistory)a[l.reason]++;let c={};for(let l of this.reuseHistory){let u=l.domain??"unknown";c[u]||(c[u]={reuses:0,tokens:0}),c[u].reuses++,c[u].tokens+=l.tokensSaved}return{totalReuses:e,tokensSaved:r,avgConfidence:e>0?n/e:0,avgSimilarity:e>0?i/e:0,avgSearchLatencyMs:e>0?s/e:0,totalAttempts:t,exitRate:t>0?e/t:0,reasonBreakdown:a,domainBreakdown:c}}resetStats(){this.reuseHistory=[],this.attemptHistory=[]}getConfig(){return{...this.config}}updateConfig(e){Object.assign(this.config,e)}}});var ny={};Q(ny,{DEFAULT_SESSION_CACHE_CONFIG:()=>Pre,SessionOperationCache:()=>CA,getSessionCache:()=>ry,resetSessionCache:()=>wIe});import{createHash as TIe}from"crypto";function SIe(){let o="3.15.1",e=(process.env.AQE_SESSION_CACHE_SALT??"").trim();return e?`${o}+${e}`:o}function EIe(o){let e=JSON.parse(JSON.stringify(o));function t(r){if(r===null||typeof r!="object")return JSON.stringify(r);if(Array.isArray(r))return"["+r.map(t).join(",")+"]";let n=r;return"{"+Object.keys(n).sort().map(i=>JSON.stringify(i)+":"+t(n[i])).join(",")+"}"}return t(e)}function bA(){try{let{getUnifiedMemory:o}=(te(),Ye(Rr)),e=o();return e.isInitialized()?e.getDatabase():null}catch{return null}}function ry(o){return bc||(bc=new CA(o),bc.loadFromDb()),bc}function wIe(){bc&&bc.clear(),bc=null}var Pre,CA,bc,Rd=b(()=>{"use strict";Pre={enabled:!0,maxEntries:500,ttlMs:3600*1e3,persistToDb:!0};CA=class{cache=new Map;config;hits=0;misses=0;generation=0;constructor(e){this.config={...Pre,...e}}computeFingerprint(e,t,r){let n=EIe({action:t,build:SIe(),domain:e,input:r});return TIe("sha256").update(n).digest("hex").slice(0,16)}get(e){if(!this.config.enabled)return null;let t=this.cache.get(e);return t?Date.now()-t.cachedAt>this.config.ttlMs?(this.cache.delete(e),this.misses++,null):(t.hitCount++,t.lastHitAt=Date.now(),this.hits++,t):(this.misses++,null)}set(e,t,r,n,i){if(!this.config.enabled)return;!this.cache.has(e)&&this.cache.size>=this.config.maxEntries&&this.evictOldest();let s={fingerprint:e,domain:t,action:r,result:n,tokensSaved:i,cachedAt:Date.now(),hitCount:0,lastHitAt:0};this.cache.set(e,s),this.config.persistToDb&&this.persistEntry(s)}loadFromDb(){try{let e=bA();if(!e)return;let t=Date.now()-this.config.ttlMs,r=e.prepare(`SELECT key, value FROM kv_store
|
|
5800
5800
|
WHERE namespace = 'session_cache'
|
|
5801
5801
|
AND created_at > ?
|
|
5802
5802
|
ORDER BY created_at DESC LIMIT ?`).all(t,this.config.maxEntries);for(let n of r)try{let i=JSON.parse(n.value);Date.now()-i.cachedAt<=this.config.ttlMs&&this.cache.set(i.fingerprint,i)}catch{}}catch{}}getStats(){let e=this.hits+this.misses,t=0;for(let r of this.cache.values())t+=r.tokensSaved*r.hitCount;return{size:this.cache.size,hits:this.hits,misses:this.misses,hitRate:e>0?this.hits/e:0,estimatedTokensSaved:t}}clear(){this.cache.clear(),this.hits=0,this.misses=0,this.generation++}getGeneration(){return this.generation}invalidateAll(){let e=this.cache.size;if(this.cache.clear(),this.generation++,this.config.persistToDb)try{bA()?.prepare("DELETE FROM kv_store WHERE namespace = 'session_cache'").run()}catch{}return e}invalidateDomain(e){this.generation++;let t=0;for(let[r,n]of this.cache)n.domain===e&&(this.cache.delete(r),this.deletePersisted(n.fingerprint),t++);return t}evictOldest(){let e=null,t=1/0;for(let[r,n]of this.cache)n.cachedAt<t&&(t=n.cachedAt,e=r);e&&this.cache.delete(e)}persistEntry(e){try{let t=bA();if(!t)return;t.prepare(`INSERT OR REPLACE INTO kv_store (key, namespace, value, created_at)
|
|
@@ -6279,7 +6279,7 @@ ${i.errors.join(`
|
|
|
6279
6279
|
ORDER BY ended_at DESC
|
|
6280
6280
|
LIMIT ?
|
|
6281
6281
|
`).all(dOe);if(i.length===0)return;let s=r.prepare("UPDATE qe_trajectories SET feedback = ? WHERE id = ?");for(let a of i)try{let c=await pOe(a,o,e);c&&s.run(JSON.stringify(c),a.id)}catch{}}async function pOe(o,e,t){let r=["You are a quality engineering judge scoring a completed task trajectory.","",`Task: ${o.task.slice(0,400)}`,`Agent: ${o.agent??"unknown"}`,`Domain: ${o.domain??"general"}`,`Outcome: ${o.success?"success":"failure"}`,"",'Respond ONLY with JSON: {"quality": 0..1, "reasoning": "\u2264120 chars", "improvement": "\u2264120 chars or omit"}.'].join(`
|
|
6282
|
-
`),n=await fetch(`${t}/v1/messages`,{method:"POST",headers:{"content-type":"application/json","x-api-key":e,"anthropic-version":"2023-06-01"},body:JSON.stringify({model:lOe,max_tokens:uOe,messages:[{role:"user",content:r}]})});if(!n.ok)return null;let s=(await n.json()).content?.[0]?.text;if(!s)return null;let a=s.match(/\{[\s\S]*\}/);if(!a)return null;try{let c=JSON.parse(a[0]);return typeof c.quality!="number"||typeof c.reasoning!="string"?null:{quality:Math.max(0,Math.min(1,c.quality)),reasoning:c.reasoning.slice(0,200),improvement:typeof c.improvement=="string"?c.improvement.slice(0,200):void 0}}catch{return null}}var lOe,uOe,dOe,jse=b(()=>{"use strict";te();lOe="claude-haiku-4-5-20251001",uOe=200,dOe=5});var xz={};Q(xz,{handleModelRoute:()=>Ix,handleReasoningBankStats:()=>yOe,handleRoutingEconomics:()=>_x,handleRoutingMetrics:()=>Dx,handleTaskCancel:()=>Px,handleTaskList:()=>xx,handleTaskOrchestrate:()=>Mx,handleTaskOutcomeRecord:()=>fOe,handleTaskStatus:()=>kx,handleTaskStatusWithLearning:()=>vOe,handleTaskSubmit:()=>Ax,subscribeTrajectoryEvents:()=>bOe,unsubscribeTrajectoryEvents:()=>Xse});async function Ax(o){if(!be())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let e=o.targetDomains??[];if(!Array.isArray(e)||!e.every(xP))return{success:!1,error:`Unknown domain: ${(Array.isArray(e)?e.filter(n=>!xP(n)).map(String):[String(e)]).join(", ")}. Valid domains: ${ne.join(", ")}`};let{queen:t}=ve();try{let r=await t.submitTask({type:o.type,priority:o.priority||"p1",targetDomains:e,payload:o.payload||{},timeout:o.timeout||3e5});if(!r.success)return{success:!1,error:r.error.message};let n=t.getTaskStatus(r.value);return n?{success:!0,data:{taskId:r.value,type:o.type,priority:o.priority||"p1",status:n.status,error:n.error,assignedDomain:n.assignedDomain}}:{success:!1,error:`Task ${r.value} was accepted but its execution status is unavailable.`}}catch(r){return{success:!1,error:`Failed to submit task: ${E(r)}`}}}async function xx(o){if(!be())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let{queen:e}=ve();try{let t=e.listTasks({status:o.status,priority:o.priority,domain:o.domain});return{success:!0,data:(typeof o.limit=="number"?t.slice(0,o.limit):t).map(i=>({taskId:i.taskId,type:i.task.type,status:i.status,cancellationResultPending:i.cancellationResultPending,priority:i.task.priority,assignedDomain:i.assignedDomain,assignedAgents:i.assignedAgents,result:i.result,error:i.error,createdAt:i.task.createdAt.toISOString(),startedAt:i.startedAt?.toISOString(),completedAt:i.completedAt?.toISOString(),duration:i.completedAt&&i.startedAt?i.completedAt.getTime()-i.startedAt.getTime():void 0}))}}catch(t){return{success:!1,error:`Failed to list tasks: ${E(t)}`}}}async function kx(o){if(!be())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let{queen:e}=ve();try{let t=e.getTaskStatus(o.taskId);return t?{success:!0,data:{taskId:t.taskId,type:t.task.type,status:t.status,cancellationResultPending:t.cancellationResultPending,priority:t.task.priority,assignedDomain:t.assignedDomain,assignedAgents:t.assignedAgents,result:o.detailed?t.result:void 0,error:t.error,createdAt:t.task.createdAt.toISOString(),startedAt:t.startedAt?.toISOString(),completedAt:t.completedAt?.toISOString(),duration:t.completedAt&&t.startedAt?t.completedAt.getTime()-t.startedAt.getTime():void 0}}:{success:!1,error:`Task not found: ${o.taskId}`}}catch(t){return{success:!1,error:`Failed to get task status: ${E(t)}`}}}async function Px(o){if(!be())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let{queen:e}=ve();try{let t=await e.cancelTask(o.taskId);return t.success?{success:!0,data:{taskId:o.taskId,cancelled:!0,cancellationResultPending:e.getTaskStatus(o.taskId)?.cancellationResultPending??!1}}:{success:!1,error:t.error.message}}catch(t){return{success:!1,error:`Failed to cancel task: ${E(t)}`}}}async function Mx(o){if(!be())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let{queen:e,workflowOrchestrator:t}=ve();try{let r=o.context?.project||Kse(o.task),n=o.priority==="critical"||/\b(security|vulnerability|cve|owasp|critical|production|exploit)\b/i.test(o.task),s=await(await wa()).routeTask({task:o.task,codeContext:o.codeContext,filePaths:o.filePaths,manualTier:o.manualTier,isCritical:n,agentType:`qe-${r}`,domain:r,metadata:{inferredDomain:r,hasCodeContext:!!o.codeContext,fileCount:o.filePaths?.length}}),a=await di(),c=await a.getExperienceGuidance(o.task,o.context?.project),l=await a.searchPatternMatches(o.task,{limit:5,domain:o.context?.project??r}).catch(()=>[]),u=gOe(o.task),d=hOe(o.priority||"medium"),p=mOe[u];if(p&&t){console.log(`[TaskOrchestrate] Task type '${u}' has workflow '${p}' - executing workflow`);let f=o.task.match(/https?:\/\/[^\s]+/i),v=f?f[0]:void 0;v&&console.log(`[TaskOrchestrate] Detected URL for analysis: ${v}`);let C={targetId:o.context?.project||v||`task-${Date.now()}`,targetType:v?"website":"epic",description:o.task,acceptanceCriteria:o.context?.requirements||[],url:v,routing:{tier:s.decision.tier,modelId:s.modelId,executionStrategy:s.executionStrategy,complexity:s.decision.complexityAnalysis.overall},patternHints:l.length>0?l.map(({pattern:R,similarity:x,score:k,matchType:P,canReuse:L})=>({patternId:R.id,name:R.name,description:R.description,confidence:R.confidence,similarity:x,score:k,matchType:P,canReuse:L})):void 0},S=await t.executeWorkflow(p,C);return S.success?{success:!0,data:{taskId:S.value,type:u,priority:d,strategy:o.strategy||"adaptive",status:"workflow-started",message:`Workflow '${p}' started for task: ${o.task}`,routing:{tier:s.decision.tier,tierName:s.tierInfo.name,modelId:s.modelId,executionStrategy:s.executionStrategy,complexity:s.decision.complexityAnalysis.overall,confidence:s.decision.confidence,useAgentBooster:s.useAgentBooster,rationale:s.decision.rationale,decisionTimeMs:s.decision.metadata.decisionTimeMs}}}:{success:!1,error:`Workflow execution failed: ${S.error.message}`}}let m={description:o.task,strategy:o.strategy||"adaptive",maxAgents:o.maxAgents,context:o.context};u==="generate-tests"&&(m.sourceFiles=o.filePaths||[],m.sourceCode=o.codeContext||"",m.language=m.language||"typescript",m.testType=m.testType||"unit");let g=await e.submitTask({type:u,priority:d,targetDomains:[],payload:{...m,routing:{tier:s.decision.tier,modelId:s.modelId,executionStrategy:s.executionStrategy,useAgentBooster:s.useAgentBooster,agentBoosterTransform:s.decision.agentBoosterTransform,complexity:s.decision.complexityAnalysis.overall,confidence:s.decision.confidence},experienceGuidance:c?{strategy:c.recommendedStrategy,actions:c.suggestedActions,confidence:c.confidence,tokenSavings:c.estimatedTokenSavings}:void 0,patternHints:l.length>0?l.map(({pattern:f,similarity:v,score:C,matchType:S,canReuse:R})=>({patternId:f.id,name:f.name,description:f.description,confidence:f.confidence,similarity:v,score:C,matchType:S,canReuse:R})):void 0},timeout:6e5});if(!g.success)return{success:!1,error:g.error.message};let h=g.value;return await wz(h,o.task,{agent:"queen-coordinator",domain:o.context?.project}),process.env.AQE_TRAJECTORY_JUDGE==="1"&&process.env.ANTHROPIC_API_KEY&&Wse().catch(f=>{console.warn("[TrajectoryJudge] failed:",f instanceof Error?f.message:f)}),{success:!0,data:{taskId:h,type:u,priority:d,strategy:o.strategy||"adaptive",status:"submitted",message:`Task orchestrated: ${o.task}${c?" (with experience guidance)":""}`,routing:{tier:s.decision.tier,tierName:s.tierInfo.name,modelId:s.modelId,executionStrategy:s.executionStrategy,complexity:s.decision.complexityAnalysis.overall,confidence:s.decision.confidence,useAgentBooster:s.useAgentBooster,rationale:s.decision.rationale,decisionTimeMs:s.decision.metadata.decisionTimeMs}}}}catch(r){return{success:!1,error:`Failed to orchestrate task: ${E(r)}`}}}async function Ix(o){try{let e=await wa(),t=o.domain||Kse(o.task),r=o.isCritical??/\b(security|vulnerability|cve|owasp|critical|production|exploit)\b/i.test(o.task),n=await e.routeTask({task:o.task,codeContext:o.codeContext,filePaths:o.filePaths,manualTier:o.manualTier,isCritical:r,agentType:o.agentType||`qe-${t}`,domain:t,metadata:{inferredDomain:t,hasCodeContext:!!o.codeContext,fileCount:o.filePaths?.length}});return{success:!0,data:{tier:n.decision.tier,tierName:n.tierInfo.name,modelId:n.modelId,executionStrategy:n.executionStrategy,useAgentBooster:n.useAgentBooster,agentBoosterTransform:n.decision.agentBoosterTransform,complexity:{overall:n.decision.complexityAnalysis.overall,code:n.decision.complexityAnalysis.codeComplexity,reasoning:n.decision.complexityAnalysis.reasoningComplexity,scope:n.decision.complexityAnalysis.scopeComplexity},confidence:n.decision.confidence,rationale:n.decision.rationale,warnings:n.decision.warnings,budget:{allowed:n.decision.budgetDecision.allowed,wasDowngraded:n.decision.budgetDecision.wasDowngraded,estimatedCostUsd:n.decision.budgetDecision.estimatedCostUsd},decisionTimeMs:n.decision.metadata.decisionTimeMs}}}catch(e){return{success:!1,error:`Failed to route task: ${E(e)}`}}}async function Dx(o){try{let e=await wa(),t=e.getRoutingStats(),r=e.getMetrics(),n={stats:t,modelRouterMetrics:{totalDecisions:r.totalDecisions,avgDecisionTimeMs:r.avgDecisionTimeMs,agentBoosterStats:r.agentBoosterStats,budgetStats:r.budgetStats}};return o.includeLog&&(n.log=e.getRoutingLog(o.logLimit||100)),{success:!0,data:n}}catch(e){return{success:!1,error:`Failed to get routing metrics: ${E(e)}`}}}async function _x(o){try{let{createRoutingFeedbackCollector:e}=await Promise.resolve().then(()=>(yh(),MX)),{getGlobalCostTracker:t}=await Promise.resolve().then(()=>(Vr(),Y3)),r=e(100);await r.initialize(),r.enableEconomicRouting({...o.taskComplexity!=null?{}:{}},t());let n=r.getEconomicReport();return n?{success:!0,data:{tierEfficiency:n.tierEfficiency.map(s=>({...s,qualityPerDollar:isFinite(s.qualityPerDollar)?s.qualityPerDollar:"Infinity"})),currentHourlyCostUsd:n.currentHourlyCostUsd,currentDailyCostUsd:n.currentDailyCostUsd,budgetRemaining:n.budgetRemaining,recommendation:n.recommendation,savingsOpportunity:n.savingsOpportunity}}:{success:!1,error:"Economic routing is not available"}}catch(e){return{success:!1,error:`Failed to get economic routing report: ${E(e)}`}}}function Kse(o){let e=o.toLowerCase();return/\b(security|vulnerabilit|cve|owasp|secret|credential|injection|xss|csrf)\b/.test(e)?"security-compliance":/\b(chaos|resilience|fault.?inject|disaster|failover)\b/.test(e)?"chaos-resilience":/\b(defect|bug.?predict|risk.?assess|mutation)\b/.test(e)?"defect-intelligence":/\b(coverage|uncovered|gap.?analy)\b/.test(e)?"coverage-analysis":/\b(quality|code.?review|maintain|tech.?debt)\b/.test(e)?"quality-assessment":/\b(contract|api.?compat|breaking.?change|pact)\b/.test(e)?"contract-testing":/\b(index|knowledge.?graph|semantic|code.?intel)\b/.test(e)?"code-intelligence":/\b(accessib|a11y|wcag|screen.?read)\b/.test(e)?"visual-accessibility":/\b(requirement|bdd|acceptance|user.?stor)\b/.test(e)?"requirements-validation":/\b(generat.*test|test.*generat|write.*test|create.*test)\b/.test(e)?"test-generation":/\b(run.*test|execut.*test)\b/.test(e)?"test-execution":"test-generation"}function gOe(o){let e=o.toLowerCase();return/run\s+(?:\w+\s+)*tests?/.test(e)||/execute\s+(?:\w+\s+)*tests?/.test(e)||e.includes("run tests")||e.includes("execute tests")?"execute-tests":e.includes("generate test")||e.includes("create test")||e.includes("write test")?"generate-tests":e.includes("coverage")||e.includes("uncovered")?"analyze-coverage":e.includes("quality")||e.includes("code quality")?"assess-quality":e.includes("defect")||e.includes("bug")||e.includes("predict")?"predict-defects":e.includes("requirement")||e.includes("bdd")||e.includes("acceptance")?"validate-requirements":e.includes("index")||e.includes("knowledge graph")||e.includes("semantic")?"index-code":e.includes("security")||e.includes("vulnerability")||e.includes("owasp")?"scan-security":e.includes("contract")||e.includes("api contract")||e.includes("pact")?"validate-contracts":e.includes("accessibility")||e.includes("a11y")||e.includes("wcag")?"test-accessibility":e.includes("chaos")||e.includes("resilience")||e.includes("fault")?"run-chaos":e.includes("learn")||e.includes("optimize")||e.includes("improve")?"optimize-learning":e.includes("ideation")||e.includes("quality criteria")||e.includes("htsm")||e.includes("qcsd")||e.includes("testability")||e.includes("pi planning")||e.includes("sprint planning")?"ideation-assessment":"generate-tests"}function hOe(o){switch(o){case"critical":return"p0";case"high":return"p1";case"medium":return"p2";case"low":return"p3";default:return"p1"}}async function fOe(o){try{let e=await di(),t={taskId:o.taskId,task:o.task,taskType:o.taskType,success:o.success,executionTimeMs:o.executionTimeMs,agentId:o.agentId,domain:o.domain,modelTier:o.modelTier,qualityScore:o.qualityScore,error:o.error,metrics:o.metrics};await e.recordTaskOutcome(t);let r=o.success&&(o.qualityScore||.5)>=.6;return{success:!0,data:{recorded:!0,patternStored:r,message:r?`Outcome recorded and pattern stored for task ${o.taskId}`:`Outcome recorded for task ${o.taskId}`}}}catch(e){return{success:!1,error:`Failed to record task outcome: ${E(e)}`}}}async function yOe(){try{let e=await(await di()).getStats();return{success:!0,data:{service:e.service,patterns:{totalPatterns:e.reasoningBank.totalPatterns,byDomain:e.reasoningBank.byDomain,byTier:e.reasoningBank.byTier,learningOutcomes:e.reasoningBank.learningOutcomes,patternSuccessRate:e.reasoningBank.patternSuccessRate},embeddings:{cacheSize:e.reasoningBank.embeddingCacheSize,dimension:e.reasoningBank.embeddingDimension,transformerAvailable:e.reasoningBank.transformerAvailable},performance:{avgRoutingLatencyMs:e.reasoningBank.avgRoutingLatencyMs,p95RoutingLatencyMs:e.reasoningBank.p95RoutingLatencyMs}}}}catch(o){return{success:!1,error:`Failed to get ReasoningBank stats: ${E(o)}`}}}async function vOe(o){if(!be())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let{queen:e}=ve();try{let t=e.getTaskStatus(o.taskId);if(!t)return{success:!1,error:`Task not found: ${o.taskId}`};let r={taskId:t.taskId,type:t.task.type,status:t.status,cancellationResultPending:t.cancellationResultPending,priority:t.task.priority,assignedDomain:t.assignedDomain,assignedAgents:t.assignedAgents,result:o.detailed?t.result:void 0,error:t.error,createdAt:t.task.createdAt.toISOString(),startedAt:t.startedAt?.toISOString(),completedAt:t.completedAt?.toISOString(),duration:t.completedAt&&t.startedAt?t.completedAt.getTime()-t.startedAt.getTime():void 0};if((t.status==="completed"||t.status==="failed")&&!Qse.has(o.taskId)){Qse.add(o.taskId);try{let n=await di(),i=r.duration||0,s=t.status==="completed",a=t.task.payload||{},c=typeof a.description=="string"?a.description:t.task.type,l=a.routing,u=await nv(o.taskId,s,t.error),d=u?.metrics.averageQuality??(s?.7:.3);await n.recordTaskOutcome({taskId:o.taskId,task:c,taskType:t.task.type,success:s,executionTimeMs:i,agentId:t.assignedAgents?.[0],domain:t.assignedDomain,modelTier:l?.tier,qualityScore:d,error:t.error,metrics:{testsGenerated:typeof t.result=="object"&&t.result?t.result.testsGenerated:void 0,testsPassed:typeof t.result=="object"&&t.result?t.result.testsPassed:void 0}}),console.error(`[TaskHandler] Recorded learning outcome: task=${o.taskId} success=${s} quality=${d.toFixed(2)} trajectorySteps=${u?.steps.length??0}`)}catch(n){console.error("[TaskHandler] Failed to record outcome:",n)}}return{success:!0,data:r}}catch(t){return{success:!1,error:`Failed to get task status: ${E(t)}`}}}function bOe(o){Xse(o);let e=o.subscribeToEventType("TaskCompleted",async r=>{let{taskId:n}=r.payload;n&&ve().queen?.getTaskStatus(n)?.status!=="cancelled"&&await nv(n,!0).catch(()=>{})}),t=o.subscribeToEventType("TaskFailed",async r=>{let{taskId:n,error:i}=r.payload;n&&ve().queen?.getTaskStatus(n)?.status!=="cancelled"&&await nv(n,!1,i).catch(()=>{})});Az=[e,t]}function Xse(o){for(let e of Az)o.unsubscribe(e);Az=[]}var mOe,Qse,Az,Lx=b(()=>{"use strict";Kn();sA();Rz();jse();M();N();mOe={"ideation-assessment":"qcsd-ideation-swarm"};Qse=new Set;Az=[]});var Yse={};Q(Yse,{DEFAULT_STRUCTURAL_HEALTH_CONFIG:()=>Jse,StructuralHealthMonitor:()=>Ox,createStructuralHealthMonitor:()=>COe});function COe(o){return new Ox(o)}var Jse,Ox,Zse=b(()=>{"use strict";Zq();Jse={healthyThreshold:.4,warningThreshold:.2,maxHistoryEntries:100,enableLogging:!1},Ox=class{config;minCutService;history=[];constructor(e){this.config={...Jse,...e},this.minCutService=J0()}computeFleetHealth(e){if(e.length===0)return this.emptyFleetResult();let t=this.minCutService.buildTaskGraphFromTopology(e);return this.computeFleetHealthFromGraph(t,e.length)}computeFleetHealthFromGraph(e,t){if(e.nodes.length===0)return this.emptyFleetResult();let r=this.minCutService.getStructuralHealth(e),n=this.determineStatus(r.normalizedLambda),i={lambda:r.lambda,healthy:r.healthy,weakPoints:r.weakPoints,normalizedLambda:r.normalizedLambda,riskScore:r.riskScore,status:n,suggestions:r.suggestions,measuredAt:new Date};return this.addHistoryEntry({lambda:r.lambda,healthy:r.healthy,weakPointCount:r.weakPoints.length,agentCount:t??e.nodes.length,timestamp:i.measuredAt}),this.config.enableLogging&&this.logHealth(i),i}getTrend(){if(this.history.length<2)return"stable";let e=Math.min(5,this.history.length),t=this.history.slice(-e),r=t[0].lambda,i=t[t.length-1].lambda-r;return Math.abs(i)<.05?"stable":i>0?"improving":"degrading"}getHistory(e){let t=[...this.history];return e!==void 0&&e<t.length?t.slice(-e):t}clearHistory(){this.history.length=0}getMinCutService(){return this.minCutService}determineStatus(e){return e>=this.config.healthyThreshold?"healthy":e>=this.config.warningThreshold?"warning":"critical"}addHistoryEntry(e){this.history.push(e),this.history.length>this.config.maxHistoryEntries&&this.history.splice(0,this.history.length-this.config.maxHistoryEntries)}emptyFleetResult(){return{lambda:0,healthy:!1,weakPoints:[],normalizedLambda:0,riskScore:1,status:"empty",suggestions:["No agents in fleet. Spawn agents to build a topology."],measuredAt:new Date}}logHealth(e){console.error(`[StructuralHealth] Status: ${e.status} | Lambda: ${e.normalizedLambda.toFixed(3)} | Weak points: ${e.weakPoints.length} | Risk: ${(e.riskScore*100).toFixed(0)}%`)}}});var QD={};Q(QD,{adoptExternalFleet:()=>SOe,assignAgentLevel:()=>kz,disposeFleet:()=>$x,getAgentLevel:()=>Pz,getAllAgentLevels:()=>wOe,getFleetState:()=>ve,getFleetTopology:()=>EOe,handleAQEHealth:()=>qx,handleFleetHealth:()=>Fx,handleFleetInit:()=>Wd,handleFleetStatus:()=>Nx,isFleetInitialized:()=>be});function ve(){return U}function be(){return U.initialized&&U.kernel!==null&&U.queen!==null}function SOe(o){return be()||(U.fleetId=`fleet-${A().slice(0,8)}`,U.kernel=o.kernel,U.queen=o.queen,U.router=o.router??null,U.workflowOrchestrator=o.workflowOrchestrator??null,U.initialized=!0,U.initTime=new Date,U.topology=o.topology??"hierarchical",U.agentLevels.clear()),U.fleetId}function EOe(){return U.topology}function kz(o,e){if(U.topology!=="hierarchical"){let i={agentId:o,domain:e,level:"worker",spawnedAt:new Date};return U.agentLevels.set(o,i),"worker"}let r=Array.from(U.agentLevels.values()).find(i=>i.domain===e&&i.level==="lead")?"worker":"lead",n={agentId:o,domain:e,level:r,spawnedAt:new Date};return U.agentLevels.set(o,n),r}function Pz(o){return U.agentLevels.get(o)}function wOe(){return U.agentLevels}async function Wd(o){try{if(U.initialized&&U.kernel&&U.queen){let l=U.kernel.getConfig();return{success:!0,data:{fleetId:U.fleetId,topology:U.topology,maxAgents:l.maxConcurrentAgents,enabledDomains:l.enabledDomains.filter(u=>u!=="coordination"),status:"ready"}}}U.fleetId=`fleet-${A().slice(0,8)}`;let e=o.enabledDomains||[...ne],t=e.filter(l=>l!=="coordination"),r=process.env.AQE_MEMORY_BACKEND==="memory"?"memory":o.memoryBackend||"hybrid";U.kernel=new jR({maxConcurrentAgents:o.maxAgents||15,memoryBackend:r,hnswEnabled:!0,lazyLoading:o.lazyLoading!==!1,enabledDomains:e}),await U.kernel.initialize(),U.router=new k0(U.kernel.eventBus),await U.router.initialize();let n=l=>U.kernel.getDomainAPI(l),i=new hx(U.kernel.eventBus,U.kernel.memory,n),s=U.kernel.plugins;await s.loadAll();let a=new Map;for(let l of s.getLoaded()){let u=s.getPlugin(l);u&&a.set(l,u)}try{let{getDaemon:l}=await Promise.resolve().then(()=>(wx(),Ex)),u=l().getWorkerManager();u.setKernel(U.kernel),u.setMemory(U.kernel.memory)}catch(l){console.warn(`[fleet_init] Daemon worker manager wiring skipped: ${E(l)}`)}U.queen=ree(U.kernel,U.router,i,void 0,a),await U.queen.initialize(),U.workflowOrchestrator=new xf(U.kernel.eventBus,U.kernel.memory,U.kernel.coordinator),await U.workflowOrchestrator.initialize(),ROe(U.kernel,U.workflowOrchestrator);let{subscribeTrajectoryEvents:c}=await Promise.resolve().then(()=>(Lx(),xz));return c(U.router),U.initialized=!0,U.initTime=new Date,U.topology=o.topology||"hierarchical",U.agentLevels.clear(),{success:!0,data:{fleetId:U.fleetId,topology:U.topology,maxAgents:o.maxAgents||15,enabledDomains:t,status:"initialized"}}}catch(e){return{success:!1,error:`Failed to initialize fleet: ${E(e)}`}}}async function Nx(o){if(!be())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};try{let e=U.queen.getHealth(),t=U.queen.getMetrics(),r={status:e.status,uptime:t.uptime,agents:{total:e.totalAgents,active:e.activeAgents,idle:e.totalAgents-e.activeAgents},tasks:{pending:e.pendingTasks,running:e.runningTasks,completed:t.tasksCompleted,failed:t.tasksFailed}};if(o.includeDomains){let i=[];for(let[s,a]of e.domainHealth)i.push({domain:s,status:a.status,agents:a.agents.total,load:U.queen.getDomainLoad(s)});r.domains=i}let n=U.queen.getDomainTeamManager?.();if(n){let i=n.listDomainTeams(),s=0,a=0;for(let c of i)s+=1+c.teammateIds.length,n.getTeamHealth(c.domain)?.healthy&&a++;r.teams={active:i.length,totalAgentsInTeams:s,healthyCount:a}}o.includeMetrics&&(r.metrics={tasksReceived:t.tasksReceived,tasksCompleted:t.tasksCompleted,tasksFailed:t.tasksFailed,agentUtilization:t.agentUtilization,averageTaskDuration:t.averageTaskDuration});try{let{getUnifiedMemory:i}=await Promise.resolve().then(()=>(te(),Rr)),s=i();if(s.isInitialized()){let a=l=>{try{return s.queryCount(l)}catch{return 0}},c=await s.vectorCount();r.learning={totalPatterns:a("qe_patterns"),totalExperiences:a("captured_experiences"),totalTrajectories:a("qe_trajectories"),vectorCount:c,experienceApplications:a("experience_applications"),dreamCycles:a("dream_cycles"),embeddingDimension:384}}}catch{}return{success:!0,data:r}}catch(e){return{success:!1,error:`Failed to get fleet status: ${E(e)}`}}}async function Fx(o){if(!be())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};try{if(o.domain){let r=U.queen.getDomainHealth(o.domain);return r?{success:!0,data:{domain:o.domain,status:r.status,agents:r.agents,errors:r.errors,lastActivity:r.lastActivity?.toISOString()}}:{success:!1,error:`Domain not found: ${o.domain}`}}let e=U.queen.getHealth(),t={status:e.status,totalAgents:e.totalAgents,activeAgents:e.activeAgents,pendingTasks:e.pendingTasks,runningTasks:e.runningTasks,workStealingActive:e.workStealingActive,lastHealthCheck:e.lastHealthCheck.toISOString()};if(o.detailed){let r={};for(let[n,i]of e.domainHealth)r[n]={status:i.status,agents:i.agents,errors:i.errors.length,lastActivity:i.lastActivity?.toISOString()};t.domains=r,t.issues=e.issues.map(n=>({severity:n.severity,message:n.message,domain:n.domain,timestamp:n.timestamp.toISOString()}))}try{let{StructuralHealthMonitor:r}=await Promise.resolve().then(()=>(Zse(),Yse)),n=new r,i=[];for(let[c]of e.domainHealth){let l=U.queen.getAgentsByDomain(c);for(let u of l)i.push({id:u.id,name:u.name,domain:u.domain})}let s=i.map(c=>({id:c.id,name:c.name,domain:c.domain,capabilities:[c.domain],dependsOn:[],weight:1})),a=n.computeFleetHealth(s);t.structuralHealth={lambda:a.lambda,healthy:a.healthy,normalizedLambda:a.normalizedLambda,riskScore:a.riskScore,status:a.status,weakPoints:a.weakPoints,suggestions:a.suggestions}}catch{}return{success:!0,data:t}}catch(e){return{success:!1,error:`Failed to get fleet health: ${E(e)}`}}}async function $x(){if(Ite(),fA(),fse(),U.workflowOrchestrator&&(await U.workflowOrchestrator.dispose(),U.workflowOrchestrator=null),U.queen&&(await U.queen.dispose(),U.queen=null),U.router){try{let{unsubscribeTrajectoryEvents:o}=await Promise.resolve().then(()=>(Lx(),xz));o(U.router)}catch{}await U.router.dispose(),U.router=null}U.kernel&&(await U.kernel.dispose(),U.kernel=null),U.initialized=!1,U.fleetId=null,U.initTime=null,U.topology="hierarchical",U.agentLevels.clear()}async function qx(){let o=performance.now();try{let e=be(),t=U.initTime?Date.now()-U.initTime.getTime():0,r={connected:!1,totalEntries:0,namespaces:0},n={enabled:!1,vectorCount:0},i=0;if(e&&U.kernel){let u=U.kernel.memory;try{r.connected=!0;let d=await u.count("default"),p=await u.count("learning"),m=await u.count("patterns");r.totalEntries=d+p+m;let g=0;for(let h of["default","learning","patterns","mcp-tools","coordination"])await u.count(h)>0&&g++;r.namespaces=g}catch{}try{let d=process.env.AQE_V3_HNSW_ENABLED==="true";n.enabled=d;let p=u;d&&typeof p.vectorCount=="function"&&(n.vectorCount=await p.vectorCount())}catch{}try{i=(await u.search("pattern:*",1e3)).length}catch{}}let s=e&&U.kernel?(U.kernel.getLoadedDomains?.()??TOe).length:0,a=null;try{let{getSharedRvfDualWriterSync:u}=await Promise.resolve().then(()=>(Ns(),Wl)),d=u();if(d){let p=d.status(),m=d.getDivergenceReport();a={mode:p.mode,vectorCount:p.rvf?.totalVectors??0,divergences:m.divergences,promotionSafe:d.isPromotionSafe()}}}catch{}let c=null;try{let{SQLitePatternStore:u}=await Promise.resolve().then(()=>(fl(),oI)),d=new u;await d.initialize(),c=d.getGhostPatternCount(),d.close()}catch{}return{success:!0,data:{status:e?"healthy":"unhealthy",version:"3.15.0",loadedDomains:s,memory:r,hnsw:n,rvf:a??void 0,ghostPatterns:c??void 0,loadedPatterns:i,uptimeMs:t,timestamp:new Date().toISOString()},metadata:{executionTime:performance.now()-o,timestamp:new Date().toISOString(),requestId:A(),toolName:"aqe_health"}}}catch(e){return{success:!1,error:E(e),metadata:{executionTime:performance.now()-o,timestamp:new Date().toISOString(),requestId:A(),toolName:"aqe_health"}}}}function ROe(o,e){let t=o.getDomainAPI("requirements-validation");t?.registerWorkflowActions&&(t.registerWorkflowActions(e),console.log("[Fleet] Registered requirements-validation workflow actions (includes QCSD Ideation)"));let r=o.getDomainAPI("visual-accessibility");r?.registerWorkflowActions&&(r.registerWorkflowActions(e),console.log("[Fleet] Registered visual-accessibility workflow actions"))}var TOe,U,Kn=b(()=>{"use strict";$();D7();N();nee();t$();iee();EB();yA();cz();yse();M();TOe=ne.filter(o=>o!=="coordination"),U={fleetId:null,kernel:null,queen:null,router:null,workflowOrchestrator:null,initialized:!1,initTime:null,topology:"hierarchical",agentLevels:new Map}});V();import*as VG from"readline";var rn={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,SERVER_ERROR:-32e3},La=class extends Error{constructor(t,r,n){super(r);this.code=t;this.data=n;this.name="McpError"}code;data};function Hk(o){return typeof o=="object"&&o!==null&&typeof o.code=="number"&&typeof o.message=="string"}var Gk=class{inputStream;outputStream;maxMessageSize;rl=null;requestHandler=null;notificationHandler=null;errorHandler=null;closeHandler=null;running=!1;metrics={messagesReceived:0,messagesSent:0,errors:0,bytesReceived:0,bytesSent:0};constructor(e={}){this.inputStream=e.inputStream??process.stdin,this.outputStream=e.outputStream??process.stdout,this.maxMessageSize=e.maxMessageSize??10*1024*1024}onRequest(e){this.requestHandler=e}onNotification(e){this.notificationHandler=e}start(){this.running||(this.running=!0,this.rl=VG.createInterface({input:this.inputStream,crlfDelay:1/0}),this.rl.on("line",e=>{this.handleLine(e).catch(t=>{this.metrics.errors++,console.error("[StdioTransport] Error handling line:",t)})}),this.rl.on("close",()=>{let e=this.running;if(this.running=!1,!e)return;if(this.inputStream.readableEnded===!0){this.closeHandler&&this.closeHandler();return}this.errorHandler&&this.errorHandler(new Error("Transport connection closed unexpectedly"))}),this.rl.on("error",e=>{this.metrics.errors++,console.error("[StdioTransport] Readline error:",e),this.errorHandler&&this.errorHandler(e)}))}stop(){this.running=!1,this.rl&&(this.rl.close(),this.rl=null)}async sendResponse(e){await this.write(JSON.stringify(e))}async sendNotification(e,t){let r={jsonrpc:"2.0",method:e,params:t};await this.write(JSON.stringify(r))}onError(e){this.errorHandler=e}onClose(e){this.closeHandler=e}reconnect(){if(this.inputStream.readableEnded===!0){this.running=!1,this.closeHandler&&this.closeHandler();return}this.rl&&(this.rl.close(),this.rl=null),this.running=!1,this.start()}getMetrics(){return{...this.metrics}}isRunning(){return this.running}async handleLine(e){if(!e.trim())return;if(this.metrics.bytesReceived+=Buffer.byteLength(e,"utf-8"),Buffer.byteLength(e,"utf-8")>this.maxMessageSize){this.metrics.errors++,await this.sendError(null,rn.INVALID_REQUEST,"Message too large");return}let t;try{t=I(e)}catch{this.metrics.errors++,await this.sendError(null,rn.PARSE_ERROR,"Parse error");return}if(t.jsonrpc!=="2.0"){this.metrics.errors++,await this.sendError(t.id??null,rn.INVALID_REQUEST,"Invalid JSON-RPC version");return}if(!t.method||typeof t.method!="string"){this.metrics.errors++,await this.sendError(t.id??null,rn.INVALID_REQUEST,"Missing or invalid method");return}this.metrics.messagesReceived++,t.id!==void 0?await this.handleRequest(t):await this.handleNotification(t)}async handleRequest(e){if(!this.requestHandler){await this.sendError(e.id,rn.INTERNAL_ERROR,"No request handler registered");return}try{let t=await this.requestHandler(e);await this.sendResponse({jsonrpc:"2.0",id:e.id,result:t})}catch(t){if(Hk(t))await this.sendError(e.id,t.code,t.message,t.data);else{let r=t;await this.sendError(e.id,rn.INTERNAL_ERROR,r.message||"Internal error")}}}async handleNotification(e){if(this.notificationHandler)try{await this.notificationHandler(e)}catch(t){this.metrics.errors++,console.error("[StdioTransport] Notification handler error:",t)}}async sendError(e,t,r,n){let i={jsonrpc:"2.0",id:e,error:{code:t,message:r,data:n}};await this.sendResponse(i)}async write(e){let r=[0,500,1e3];for(let n=0;n<3;n++)try{await this.writeOnce(e);return}catch(i){if(n<2)console.error(`[StdioTransport] Write attempt ${n+1} failed, retrying in ${r[n+1]}ms...`),await new Promise(s=>setTimeout(s,r[n+1]));else throw i}}async writeOnce(e){let t=e+`
|
|
6282
|
+
`),n=await fetch(`${t}/v1/messages`,{method:"POST",headers:{"content-type":"application/json","x-api-key":e,"anthropic-version":"2023-06-01"},body:JSON.stringify({model:lOe,max_tokens:uOe,messages:[{role:"user",content:r}]})});if(!n.ok)return null;let s=(await n.json()).content?.[0]?.text;if(!s)return null;let a=s.match(/\{[\s\S]*\}/);if(!a)return null;try{let c=JSON.parse(a[0]);return typeof c.quality!="number"||typeof c.reasoning!="string"?null:{quality:Math.max(0,Math.min(1,c.quality)),reasoning:c.reasoning.slice(0,200),improvement:typeof c.improvement=="string"?c.improvement.slice(0,200):void 0}}catch{return null}}var lOe,uOe,dOe,jse=b(()=>{"use strict";te();lOe="claude-haiku-4-5-20251001",uOe=200,dOe=5});var xz={};Q(xz,{handleModelRoute:()=>Ix,handleReasoningBankStats:()=>yOe,handleRoutingEconomics:()=>_x,handleRoutingMetrics:()=>Dx,handleTaskCancel:()=>Px,handleTaskList:()=>xx,handleTaskOrchestrate:()=>Mx,handleTaskOutcomeRecord:()=>fOe,handleTaskStatus:()=>kx,handleTaskStatusWithLearning:()=>vOe,handleTaskSubmit:()=>Ax,subscribeTrajectoryEvents:()=>bOe,unsubscribeTrajectoryEvents:()=>Xse});async function Ax(o){if(!be())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let e=o.targetDomains??[];if(!Array.isArray(e)||!e.every(xP))return{success:!1,error:`Unknown domain: ${(Array.isArray(e)?e.filter(n=>!xP(n)).map(String):[String(e)]).join(", ")}. Valid domains: ${ne.join(", ")}`};let{queen:t}=ve();try{let r=await t.submitTask({type:o.type,priority:o.priority||"p1",targetDomains:e,payload:o.payload||{},timeout:o.timeout||3e5});if(!r.success)return{success:!1,error:r.error.message};let n=t.getTaskStatus(r.value);return n?{success:!0,data:{taskId:r.value,type:o.type,priority:o.priority||"p1",status:n.status,error:n.error,assignedDomain:n.assignedDomain}}:{success:!1,error:`Task ${r.value} was accepted but its execution status is unavailable.`}}catch(r){return{success:!1,error:`Failed to submit task: ${E(r)}`}}}async function xx(o){if(!be())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let{queen:e}=ve();try{let t=e.listTasks({status:o.status,priority:o.priority,domain:o.domain});return{success:!0,data:(typeof o.limit=="number"?t.slice(0,o.limit):t).map(i=>({taskId:i.taskId,type:i.task.type,status:i.status,cancellationResultPending:i.cancellationResultPending,priority:i.task.priority,assignedDomain:i.assignedDomain,assignedAgents:i.assignedAgents,result:i.result,error:i.error,createdAt:i.task.createdAt.toISOString(),startedAt:i.startedAt?.toISOString(),completedAt:i.completedAt?.toISOString(),duration:i.completedAt&&i.startedAt?i.completedAt.getTime()-i.startedAt.getTime():void 0}))}}catch(t){return{success:!1,error:`Failed to list tasks: ${E(t)}`}}}async function kx(o){if(!be())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let{queen:e}=ve();try{let t=e.getTaskStatus(o.taskId);return t?{success:!0,data:{taskId:t.taskId,type:t.task.type,status:t.status,cancellationResultPending:t.cancellationResultPending,priority:t.task.priority,assignedDomain:t.assignedDomain,assignedAgents:t.assignedAgents,result:o.detailed?t.result:void 0,error:t.error,createdAt:t.task.createdAt.toISOString(),startedAt:t.startedAt?.toISOString(),completedAt:t.completedAt?.toISOString(),duration:t.completedAt&&t.startedAt?t.completedAt.getTime()-t.startedAt.getTime():void 0}}:{success:!1,error:`Task not found: ${o.taskId}`}}catch(t){return{success:!1,error:`Failed to get task status: ${E(t)}`}}}async function Px(o){if(!be())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let{queen:e}=ve();try{let t=await e.cancelTask(o.taskId);return t.success?{success:!0,data:{taskId:o.taskId,cancelled:!0,cancellationResultPending:e.getTaskStatus(o.taskId)?.cancellationResultPending??!1}}:{success:!1,error:t.error.message}}catch(t){return{success:!1,error:`Failed to cancel task: ${E(t)}`}}}async function Mx(o){if(!be())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let{queen:e,workflowOrchestrator:t}=ve();try{let r=o.context?.project||Kse(o.task),n=o.priority==="critical"||/\b(security|vulnerability|cve|owasp|critical|production|exploit)\b/i.test(o.task),s=await(await wa()).routeTask({task:o.task,codeContext:o.codeContext,filePaths:o.filePaths,manualTier:o.manualTier,isCritical:n,agentType:`qe-${r}`,domain:r,metadata:{inferredDomain:r,hasCodeContext:!!o.codeContext,fileCount:o.filePaths?.length}}),a=await di(),c=await a.getExperienceGuidance(o.task,o.context?.project),l=await a.searchPatternMatches(o.task,{limit:5,domain:o.context?.project??r}).catch(()=>[]),u=gOe(o.task),d=hOe(o.priority||"medium"),p=mOe[u];if(p&&t){console.log(`[TaskOrchestrate] Task type '${u}' has workflow '${p}' - executing workflow`);let f=o.task.match(/https?:\/\/[^\s]+/i),v=f?f[0]:void 0;v&&console.log(`[TaskOrchestrate] Detected URL for analysis: ${v}`);let C={targetId:o.context?.project||v||`task-${Date.now()}`,targetType:v?"website":"epic",description:o.task,acceptanceCriteria:o.context?.requirements||[],url:v,routing:{tier:s.decision.tier,modelId:s.modelId,executionStrategy:s.executionStrategy,complexity:s.decision.complexityAnalysis.overall},patternHints:l.length>0?l.map(({pattern:R,similarity:x,score:k,matchType:P,canReuse:L})=>({patternId:R.id,name:R.name,description:R.description,confidence:R.confidence,similarity:x,score:k,matchType:P,canReuse:L})):void 0},S=await t.executeWorkflow(p,C);return S.success?{success:!0,data:{taskId:S.value,type:u,priority:d,strategy:o.strategy||"adaptive",status:"workflow-started",message:`Workflow '${p}' started for task: ${o.task}`,routing:{tier:s.decision.tier,tierName:s.tierInfo.name,modelId:s.modelId,executionStrategy:s.executionStrategy,complexity:s.decision.complexityAnalysis.overall,confidence:s.decision.confidence,useAgentBooster:s.useAgentBooster,rationale:s.decision.rationale,decisionTimeMs:s.decision.metadata.decisionTimeMs}}}:{success:!1,error:`Workflow execution failed: ${S.error.message}`}}let m={description:o.task,strategy:o.strategy||"adaptive",maxAgents:o.maxAgents,context:o.context};u==="generate-tests"&&(m.sourceFiles=o.filePaths||[],m.sourceCode=o.codeContext||"",m.language=m.language||"typescript",m.testType=m.testType||"unit");let g=await e.submitTask({type:u,priority:d,targetDomains:[],payload:{...m,routing:{tier:s.decision.tier,modelId:s.modelId,executionStrategy:s.executionStrategy,useAgentBooster:s.useAgentBooster,agentBoosterTransform:s.decision.agentBoosterTransform,complexity:s.decision.complexityAnalysis.overall,confidence:s.decision.confidence},experienceGuidance:c?{strategy:c.recommendedStrategy,actions:c.suggestedActions,confidence:c.confidence,tokenSavings:c.estimatedTokenSavings}:void 0,patternHints:l.length>0?l.map(({pattern:f,similarity:v,score:C,matchType:S,canReuse:R})=>({patternId:f.id,name:f.name,description:f.description,confidence:f.confidence,similarity:v,score:C,matchType:S,canReuse:R})):void 0},timeout:6e5});if(!g.success)return{success:!1,error:g.error.message};let h=g.value;return await wz(h,o.task,{agent:"queen-coordinator",domain:o.context?.project}),process.env.AQE_TRAJECTORY_JUDGE==="1"&&process.env.ANTHROPIC_API_KEY&&Wse().catch(f=>{console.warn("[TrajectoryJudge] failed:",f instanceof Error?f.message:f)}),{success:!0,data:{taskId:h,type:u,priority:d,strategy:o.strategy||"adaptive",status:"submitted",message:`Task orchestrated: ${o.task}${c?" (with experience guidance)":""}`,routing:{tier:s.decision.tier,tierName:s.tierInfo.name,modelId:s.modelId,executionStrategy:s.executionStrategy,complexity:s.decision.complexityAnalysis.overall,confidence:s.decision.confidence,useAgentBooster:s.useAgentBooster,rationale:s.decision.rationale,decisionTimeMs:s.decision.metadata.decisionTimeMs}}}}catch(r){return{success:!1,error:`Failed to orchestrate task: ${E(r)}`}}}async function Ix(o){try{let e=await wa(),t=o.domain||Kse(o.task),r=o.isCritical??/\b(security|vulnerability|cve|owasp|critical|production|exploit)\b/i.test(o.task),n=await e.routeTask({task:o.task,codeContext:o.codeContext,filePaths:o.filePaths,manualTier:o.manualTier,isCritical:r,agentType:o.agentType||`qe-${t}`,domain:t,metadata:{inferredDomain:t,hasCodeContext:!!o.codeContext,fileCount:o.filePaths?.length}});return{success:!0,data:{tier:n.decision.tier,tierName:n.tierInfo.name,modelId:n.modelId,executionStrategy:n.executionStrategy,useAgentBooster:n.useAgentBooster,agentBoosterTransform:n.decision.agentBoosterTransform,complexity:{overall:n.decision.complexityAnalysis.overall,code:n.decision.complexityAnalysis.codeComplexity,reasoning:n.decision.complexityAnalysis.reasoningComplexity,scope:n.decision.complexityAnalysis.scopeComplexity},confidence:n.decision.confidence,rationale:n.decision.rationale,warnings:n.decision.warnings,budget:{allowed:n.decision.budgetDecision.allowed,wasDowngraded:n.decision.budgetDecision.wasDowngraded,estimatedCostUsd:n.decision.budgetDecision.estimatedCostUsd},decisionTimeMs:n.decision.metadata.decisionTimeMs}}}catch(e){return{success:!1,error:`Failed to route task: ${E(e)}`}}}async function Dx(o){try{let e=await wa(),t=e.getRoutingStats(),r=e.getMetrics(),n={stats:t,modelRouterMetrics:{totalDecisions:r.totalDecisions,avgDecisionTimeMs:r.avgDecisionTimeMs,agentBoosterStats:r.agentBoosterStats,budgetStats:r.budgetStats}};return o.includeLog&&(n.log=e.getRoutingLog(o.logLimit||100)),{success:!0,data:n}}catch(e){return{success:!1,error:`Failed to get routing metrics: ${E(e)}`}}}async function _x(o){try{let{createRoutingFeedbackCollector:e}=await Promise.resolve().then(()=>(yh(),MX)),{getGlobalCostTracker:t}=await Promise.resolve().then(()=>(Vr(),Y3)),r=e(100);await r.initialize(),r.enableEconomicRouting({...o.taskComplexity!=null?{}:{}},t());let n=r.getEconomicReport();return n?{success:!0,data:{tierEfficiency:n.tierEfficiency.map(s=>({...s,qualityPerDollar:isFinite(s.qualityPerDollar)?s.qualityPerDollar:"Infinity"})),currentHourlyCostUsd:n.currentHourlyCostUsd,currentDailyCostUsd:n.currentDailyCostUsd,budgetRemaining:n.budgetRemaining,recommendation:n.recommendation,savingsOpportunity:n.savingsOpportunity}}:{success:!1,error:"Economic routing is not available"}}catch(e){return{success:!1,error:`Failed to get economic routing report: ${E(e)}`}}}function Kse(o){let e=o.toLowerCase();return/\b(security|vulnerabilit|cve|owasp|secret|credential|injection|xss|csrf)\b/.test(e)?"security-compliance":/\b(chaos|resilience|fault.?inject|disaster|failover)\b/.test(e)?"chaos-resilience":/\b(defect|bug.?predict|risk.?assess|mutation)\b/.test(e)?"defect-intelligence":/\b(coverage|uncovered|gap.?analy)\b/.test(e)?"coverage-analysis":/\b(quality|code.?review|maintain|tech.?debt)\b/.test(e)?"quality-assessment":/\b(contract|api.?compat|breaking.?change|pact)\b/.test(e)?"contract-testing":/\b(index|knowledge.?graph|semantic|code.?intel)\b/.test(e)?"code-intelligence":/\b(accessib|a11y|wcag|screen.?read)\b/.test(e)?"visual-accessibility":/\b(requirement|bdd|acceptance|user.?stor)\b/.test(e)?"requirements-validation":/\b(generat.*test|test.*generat|write.*test|create.*test)\b/.test(e)?"test-generation":/\b(run.*test|execut.*test)\b/.test(e)?"test-execution":"test-generation"}function gOe(o){let e=o.toLowerCase();return/run\s+(?:\w+\s+)*tests?/.test(e)||/execute\s+(?:\w+\s+)*tests?/.test(e)||e.includes("run tests")||e.includes("execute tests")?"execute-tests":e.includes("generate test")||e.includes("create test")||e.includes("write test")?"generate-tests":e.includes("coverage")||e.includes("uncovered")?"analyze-coverage":e.includes("quality")||e.includes("code quality")?"assess-quality":e.includes("defect")||e.includes("bug")||e.includes("predict")?"predict-defects":e.includes("requirement")||e.includes("bdd")||e.includes("acceptance")?"validate-requirements":e.includes("index")||e.includes("knowledge graph")||e.includes("semantic")?"index-code":e.includes("security")||e.includes("vulnerability")||e.includes("owasp")?"scan-security":e.includes("contract")||e.includes("api contract")||e.includes("pact")?"validate-contracts":e.includes("accessibility")||e.includes("a11y")||e.includes("wcag")?"test-accessibility":e.includes("chaos")||e.includes("resilience")||e.includes("fault")?"run-chaos":e.includes("learn")||e.includes("optimize")||e.includes("improve")?"optimize-learning":e.includes("ideation")||e.includes("quality criteria")||e.includes("htsm")||e.includes("qcsd")||e.includes("testability")||e.includes("pi planning")||e.includes("sprint planning")?"ideation-assessment":"generate-tests"}function hOe(o){switch(o){case"critical":return"p0";case"high":return"p1";case"medium":return"p2";case"low":return"p3";default:return"p1"}}async function fOe(o){try{let e=await di(),t={taskId:o.taskId,task:o.task,taskType:o.taskType,success:o.success,executionTimeMs:o.executionTimeMs,agentId:o.agentId,domain:o.domain,modelTier:o.modelTier,qualityScore:o.qualityScore,error:o.error,metrics:o.metrics};await e.recordTaskOutcome(t);let r=o.success&&(o.qualityScore||.5)>=.6;return{success:!0,data:{recorded:!0,patternStored:r,message:r?`Outcome recorded and pattern stored for task ${o.taskId}`:`Outcome recorded for task ${o.taskId}`}}}catch(e){return{success:!1,error:`Failed to record task outcome: ${E(e)}`}}}async function yOe(){try{let e=await(await di()).getStats();return{success:!0,data:{service:e.service,patterns:{totalPatterns:e.reasoningBank.totalPatterns,byDomain:e.reasoningBank.byDomain,byTier:e.reasoningBank.byTier,learningOutcomes:e.reasoningBank.learningOutcomes,patternSuccessRate:e.reasoningBank.patternSuccessRate},embeddings:{cacheSize:e.reasoningBank.embeddingCacheSize,dimension:e.reasoningBank.embeddingDimension,transformerAvailable:e.reasoningBank.transformerAvailable},performance:{avgRoutingLatencyMs:e.reasoningBank.avgRoutingLatencyMs,p95RoutingLatencyMs:e.reasoningBank.p95RoutingLatencyMs}}}}catch(o){return{success:!1,error:`Failed to get ReasoningBank stats: ${E(o)}`}}}async function vOe(o){if(!be())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let{queen:e}=ve();try{let t=e.getTaskStatus(o.taskId);if(!t)return{success:!1,error:`Task not found: ${o.taskId}`};let r={taskId:t.taskId,type:t.task.type,status:t.status,cancellationResultPending:t.cancellationResultPending,priority:t.task.priority,assignedDomain:t.assignedDomain,assignedAgents:t.assignedAgents,result:o.detailed?t.result:void 0,error:t.error,createdAt:t.task.createdAt.toISOString(),startedAt:t.startedAt?.toISOString(),completedAt:t.completedAt?.toISOString(),duration:t.completedAt&&t.startedAt?t.completedAt.getTime()-t.startedAt.getTime():void 0};if((t.status==="completed"||t.status==="failed")&&!Qse.has(o.taskId)){Qse.add(o.taskId);try{let n=await di(),i=r.duration||0,s=t.status==="completed",a=t.task.payload||{},c=typeof a.description=="string"?a.description:t.task.type,l=a.routing,u=await nv(o.taskId,s,t.error),d=u?.metrics.averageQuality??(s?.7:.3);await n.recordTaskOutcome({taskId:o.taskId,task:c,taskType:t.task.type,success:s,executionTimeMs:i,agentId:t.assignedAgents?.[0],domain:t.assignedDomain,modelTier:l?.tier,qualityScore:d,error:t.error,metrics:{testsGenerated:typeof t.result=="object"&&t.result?t.result.testsGenerated:void 0,testsPassed:typeof t.result=="object"&&t.result?t.result.testsPassed:void 0}}),console.error(`[TaskHandler] Recorded learning outcome: task=${o.taskId} success=${s} quality=${d.toFixed(2)} trajectorySteps=${u?.steps.length??0}`)}catch(n){console.error("[TaskHandler] Failed to record outcome:",n)}}return{success:!0,data:r}}catch(t){return{success:!1,error:`Failed to get task status: ${E(t)}`}}}function bOe(o){Xse(o);let e=o.subscribeToEventType("TaskCompleted",async r=>{let{taskId:n}=r.payload;n&&ve().queen?.getTaskStatus(n)?.status!=="cancelled"&&await nv(n,!0).catch(()=>{})}),t=o.subscribeToEventType("TaskFailed",async r=>{let{taskId:n,error:i}=r.payload;n&&ve().queen?.getTaskStatus(n)?.status!=="cancelled"&&await nv(n,!1,i).catch(()=>{})});Az=[e,t]}function Xse(o){for(let e of Az)o.unsubscribe(e);Az=[]}var mOe,Qse,Az,Lx=b(()=>{"use strict";Kn();sA();Rz();jse();M();N();mOe={"ideation-assessment":"qcsd-ideation-swarm"};Qse=new Set;Az=[]});var Yse={};Q(Yse,{DEFAULT_STRUCTURAL_HEALTH_CONFIG:()=>Jse,StructuralHealthMonitor:()=>Ox,createStructuralHealthMonitor:()=>COe});function COe(o){return new Ox(o)}var Jse,Ox,Zse=b(()=>{"use strict";Zq();Jse={healthyThreshold:.4,warningThreshold:.2,maxHistoryEntries:100,enableLogging:!1},Ox=class{config;minCutService;history=[];constructor(e){this.config={...Jse,...e},this.minCutService=J0()}computeFleetHealth(e){if(e.length===0)return this.emptyFleetResult();let t=this.minCutService.buildTaskGraphFromTopology(e);return this.computeFleetHealthFromGraph(t,e.length)}computeFleetHealthFromGraph(e,t){if(e.nodes.length===0)return this.emptyFleetResult();let r=this.minCutService.getStructuralHealth(e),n=this.determineStatus(r.normalizedLambda),i={lambda:r.lambda,healthy:r.healthy,weakPoints:r.weakPoints,normalizedLambda:r.normalizedLambda,riskScore:r.riskScore,status:n,suggestions:r.suggestions,measuredAt:new Date};return this.addHistoryEntry({lambda:r.lambda,healthy:r.healthy,weakPointCount:r.weakPoints.length,agentCount:t??e.nodes.length,timestamp:i.measuredAt}),this.config.enableLogging&&this.logHealth(i),i}getTrend(){if(this.history.length<2)return"stable";let e=Math.min(5,this.history.length),t=this.history.slice(-e),r=t[0].lambda,i=t[t.length-1].lambda-r;return Math.abs(i)<.05?"stable":i>0?"improving":"degrading"}getHistory(e){let t=[...this.history];return e!==void 0&&e<t.length?t.slice(-e):t}clearHistory(){this.history.length=0}getMinCutService(){return this.minCutService}determineStatus(e){return e>=this.config.healthyThreshold?"healthy":e>=this.config.warningThreshold?"warning":"critical"}addHistoryEntry(e){this.history.push(e),this.history.length>this.config.maxHistoryEntries&&this.history.splice(0,this.history.length-this.config.maxHistoryEntries)}emptyFleetResult(){return{lambda:0,healthy:!1,weakPoints:[],normalizedLambda:0,riskScore:1,status:"empty",suggestions:["No agents in fleet. Spawn agents to build a topology."],measuredAt:new Date}}logHealth(e){console.error(`[StructuralHealth] Status: ${e.status} | Lambda: ${e.normalizedLambda.toFixed(3)} | Weak points: ${e.weakPoints.length} | Risk: ${(e.riskScore*100).toFixed(0)}%`)}}});var QD={};Q(QD,{adoptExternalFleet:()=>SOe,assignAgentLevel:()=>kz,disposeFleet:()=>$x,getAgentLevel:()=>Pz,getAllAgentLevels:()=>wOe,getFleetState:()=>ve,getFleetTopology:()=>EOe,handleAQEHealth:()=>qx,handleFleetHealth:()=>Fx,handleFleetInit:()=>Wd,handleFleetStatus:()=>Nx,isFleetInitialized:()=>be});function ve(){return U}function be(){return U.initialized&&U.kernel!==null&&U.queen!==null}function SOe(o){return be()||(U.fleetId=`fleet-${A().slice(0,8)}`,U.kernel=o.kernel,U.queen=o.queen,U.router=o.router??null,U.workflowOrchestrator=o.workflowOrchestrator??null,U.initialized=!0,U.initTime=new Date,U.topology=o.topology??"hierarchical",U.agentLevels.clear()),U.fleetId}function EOe(){return U.topology}function kz(o,e){if(U.topology!=="hierarchical"){let i={agentId:o,domain:e,level:"worker",spawnedAt:new Date};return U.agentLevels.set(o,i),"worker"}let r=Array.from(U.agentLevels.values()).find(i=>i.domain===e&&i.level==="lead")?"worker":"lead",n={agentId:o,domain:e,level:r,spawnedAt:new Date};return U.agentLevels.set(o,n),r}function Pz(o){return U.agentLevels.get(o)}function wOe(){return U.agentLevels}async function Wd(o){try{if(U.initialized&&U.kernel&&U.queen){let l=U.kernel.getConfig();return{success:!0,data:{fleetId:U.fleetId,topology:U.topology,maxAgents:l.maxConcurrentAgents,enabledDomains:l.enabledDomains.filter(u=>u!=="coordination"),status:"ready"}}}U.fleetId=`fleet-${A().slice(0,8)}`;let e=o.enabledDomains||[...ne],t=e.filter(l=>l!=="coordination"),r=process.env.AQE_MEMORY_BACKEND==="memory"?"memory":o.memoryBackend||"hybrid";U.kernel=new jR({maxConcurrentAgents:o.maxAgents||15,memoryBackend:r,hnswEnabled:!0,lazyLoading:o.lazyLoading!==!1,enabledDomains:e}),await U.kernel.initialize(),U.router=new k0(U.kernel.eventBus),await U.router.initialize();let n=l=>U.kernel.getDomainAPI(l),i=new hx(U.kernel.eventBus,U.kernel.memory,n),s=U.kernel.plugins;await s.loadAll();let a=new Map;for(let l of s.getLoaded()){let u=s.getPlugin(l);u&&a.set(l,u)}try{let{getDaemon:l}=await Promise.resolve().then(()=>(wx(),Ex)),u=l().getWorkerManager();u.setKernel(U.kernel),u.setMemory(U.kernel.memory)}catch(l){console.warn(`[fleet_init] Daemon worker manager wiring skipped: ${E(l)}`)}U.queen=ree(U.kernel,U.router,i,void 0,a),await U.queen.initialize(),U.workflowOrchestrator=new xf(U.kernel.eventBus,U.kernel.memory,U.kernel.coordinator),await U.workflowOrchestrator.initialize(),ROe(U.kernel,U.workflowOrchestrator);let{subscribeTrajectoryEvents:c}=await Promise.resolve().then(()=>(Lx(),xz));return c(U.router),U.initialized=!0,U.initTime=new Date,U.topology=o.topology||"hierarchical",U.agentLevels.clear(),{success:!0,data:{fleetId:U.fleetId,topology:U.topology,maxAgents:o.maxAgents||15,enabledDomains:t,status:"initialized"}}}catch(e){return{success:!1,error:`Failed to initialize fleet: ${E(e)}`}}}async function Nx(o){if(!be())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};try{let e=U.queen.getHealth(),t=U.queen.getMetrics(),r={status:e.status,uptime:t.uptime,agents:{total:e.totalAgents,active:e.activeAgents,idle:e.totalAgents-e.activeAgents},tasks:{pending:e.pendingTasks,running:e.runningTasks,completed:t.tasksCompleted,failed:t.tasksFailed}};if(o.includeDomains){let i=[];for(let[s,a]of e.domainHealth)i.push({domain:s,status:a.status,agents:a.agents.total,load:U.queen.getDomainLoad(s)});r.domains=i}let n=U.queen.getDomainTeamManager?.();if(n){let i=n.listDomainTeams(),s=0,a=0;for(let c of i)s+=1+c.teammateIds.length,n.getTeamHealth(c.domain)?.healthy&&a++;r.teams={active:i.length,totalAgentsInTeams:s,healthyCount:a}}o.includeMetrics&&(r.metrics={tasksReceived:t.tasksReceived,tasksCompleted:t.tasksCompleted,tasksFailed:t.tasksFailed,agentUtilization:t.agentUtilization,averageTaskDuration:t.averageTaskDuration});try{let{getUnifiedMemory:i}=await Promise.resolve().then(()=>(te(),Rr)),s=i();if(s.isInitialized()){let a=l=>{try{return s.queryCount(l)}catch{return 0}},c=await s.vectorCount();r.learning={totalPatterns:a("qe_patterns"),totalExperiences:a("captured_experiences"),totalTrajectories:a("qe_trajectories"),vectorCount:c,experienceApplications:a("experience_applications"),dreamCycles:a("dream_cycles"),embeddingDimension:384}}}catch{}return{success:!0,data:r}}catch(e){return{success:!1,error:`Failed to get fleet status: ${E(e)}`}}}async function Fx(o){if(!be())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};try{if(o.domain){let r=U.queen.getDomainHealth(o.domain);return r?{success:!0,data:{domain:o.domain,status:r.status,agents:r.agents,errors:r.errors,lastActivity:r.lastActivity?.toISOString()}}:{success:!1,error:`Domain not found: ${o.domain}`}}let e=U.queen.getHealth(),t={status:e.status,totalAgents:e.totalAgents,activeAgents:e.activeAgents,pendingTasks:e.pendingTasks,runningTasks:e.runningTasks,workStealingActive:e.workStealingActive,lastHealthCheck:e.lastHealthCheck.toISOString()};if(o.detailed){let r={};for(let[n,i]of e.domainHealth)r[n]={status:i.status,agents:i.agents,errors:i.errors.length,lastActivity:i.lastActivity?.toISOString()};t.domains=r,t.issues=e.issues.map(n=>({severity:n.severity,message:n.message,domain:n.domain,timestamp:n.timestamp.toISOString()}))}try{let{StructuralHealthMonitor:r}=await Promise.resolve().then(()=>(Zse(),Yse)),n=new r,i=[];for(let[c]of e.domainHealth){let l=U.queen.getAgentsByDomain(c);for(let u of l)i.push({id:u.id,name:u.name,domain:u.domain})}let s=i.map(c=>({id:c.id,name:c.name,domain:c.domain,capabilities:[c.domain],dependsOn:[],weight:1})),a=n.computeFleetHealth(s);t.structuralHealth={lambda:a.lambda,healthy:a.healthy,normalizedLambda:a.normalizedLambda,riskScore:a.riskScore,status:a.status,weakPoints:a.weakPoints,suggestions:a.suggestions}}catch{}return{success:!0,data:t}}catch(e){return{success:!1,error:`Failed to get fleet health: ${E(e)}`}}}async function $x(){if(Ite(),fA(),fse(),U.workflowOrchestrator&&(await U.workflowOrchestrator.dispose(),U.workflowOrchestrator=null),U.queen&&(await U.queen.dispose(),U.queen=null),U.router){try{let{unsubscribeTrajectoryEvents:o}=await Promise.resolve().then(()=>(Lx(),xz));o(U.router)}catch{}await U.router.dispose(),U.router=null}U.kernel&&(await U.kernel.dispose(),U.kernel=null),U.initialized=!1,U.fleetId=null,U.initTime=null,U.topology="hierarchical",U.agentLevels.clear()}async function qx(){let o=performance.now();try{let e=be(),t=U.initTime?Date.now()-U.initTime.getTime():0,r={connected:!1,totalEntries:0,namespaces:0},n={enabled:!1,vectorCount:0},i=0;if(e&&U.kernel){let u=U.kernel.memory;try{r.connected=!0;let d=await u.count("default"),p=await u.count("learning"),m=await u.count("patterns");r.totalEntries=d+p+m;let g=0;for(let h of["default","learning","patterns","mcp-tools","coordination"])await u.count(h)>0&&g++;r.namespaces=g}catch{}try{let d=process.env.AQE_V3_HNSW_ENABLED==="true";n.enabled=d;let p=u;d&&typeof p.vectorCount=="function"&&(n.vectorCount=await p.vectorCount())}catch{}try{i=(await u.search("pattern:*",1e3)).length}catch{}}let s=e&&U.kernel?(U.kernel.getLoadedDomains?.()??TOe).length:0,a=null;try{let{getSharedRvfDualWriterSync:u}=await Promise.resolve().then(()=>(Ns(),Wl)),d=u();if(d){let p=d.status(),m=d.getDivergenceReport();a={mode:p.mode,vectorCount:p.rvf?.totalVectors??0,divergences:m.divergences,promotionSafe:d.isPromotionSafe()}}}catch{}let c=null;try{let{SQLitePatternStore:u}=await Promise.resolve().then(()=>(fl(),oI)),d=new u;await d.initialize(),c=d.getGhostPatternCount(),d.close()}catch{}return{success:!0,data:{status:e?"healthy":"unhealthy",version:"3.15.1",loadedDomains:s,memory:r,hnsw:n,rvf:a??void 0,ghostPatterns:c??void 0,loadedPatterns:i,uptimeMs:t,timestamp:new Date().toISOString()},metadata:{executionTime:performance.now()-o,timestamp:new Date().toISOString(),requestId:A(),toolName:"aqe_health"}}}catch(e){return{success:!1,error:E(e),metadata:{executionTime:performance.now()-o,timestamp:new Date().toISOString(),requestId:A(),toolName:"aqe_health"}}}}function ROe(o,e){let t=o.getDomainAPI("requirements-validation");t?.registerWorkflowActions&&(t.registerWorkflowActions(e),console.log("[Fleet] Registered requirements-validation workflow actions (includes QCSD Ideation)"));let r=o.getDomainAPI("visual-accessibility");r?.registerWorkflowActions&&(r.registerWorkflowActions(e),console.log("[Fleet] Registered visual-accessibility workflow actions"))}var TOe,U,Kn=b(()=>{"use strict";$();D7();N();nee();t$();iee();EB();yA();cz();yse();M();TOe=ne.filter(o=>o!=="coordination"),U={fleetId:null,kernel:null,queen:null,router:null,workflowOrchestrator:null,initialized:!1,initTime:null,topology:"hierarchical",agentLevels:new Map}});V();import*as VG from"readline";var rn={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,SERVER_ERROR:-32e3},La=class extends Error{constructor(t,r,n){super(r);this.code=t;this.data=n;this.name="McpError"}code;data};function Hk(o){return typeof o=="object"&&o!==null&&typeof o.code=="number"&&typeof o.message=="string"}var Gk=class{inputStream;outputStream;maxMessageSize;rl=null;requestHandler=null;notificationHandler=null;errorHandler=null;closeHandler=null;running=!1;metrics={messagesReceived:0,messagesSent:0,errors:0,bytesReceived:0,bytesSent:0};constructor(e={}){this.inputStream=e.inputStream??process.stdin,this.outputStream=e.outputStream??process.stdout,this.maxMessageSize=e.maxMessageSize??10*1024*1024}onRequest(e){this.requestHandler=e}onNotification(e){this.notificationHandler=e}start(){this.running||(this.running=!0,this.rl=VG.createInterface({input:this.inputStream,crlfDelay:1/0}),this.rl.on("line",e=>{this.handleLine(e).catch(t=>{this.metrics.errors++,console.error("[StdioTransport] Error handling line:",t)})}),this.rl.on("close",()=>{let e=this.running;if(this.running=!1,!e)return;if(this.inputStream.readableEnded===!0){this.closeHandler&&this.closeHandler();return}this.errorHandler&&this.errorHandler(new Error("Transport connection closed unexpectedly"))}),this.rl.on("error",e=>{this.metrics.errors++,console.error("[StdioTransport] Readline error:",e),this.errorHandler&&this.errorHandler(e)}))}stop(){this.running=!1,this.rl&&(this.rl.close(),this.rl=null)}async sendResponse(e){await this.write(JSON.stringify(e))}async sendNotification(e,t){let r={jsonrpc:"2.0",method:e,params:t};await this.write(JSON.stringify(r))}onError(e){this.errorHandler=e}onClose(e){this.closeHandler=e}reconnect(){if(this.inputStream.readableEnded===!0){this.running=!1,this.closeHandler&&this.closeHandler();return}this.rl&&(this.rl.close(),this.rl=null),this.running=!1,this.start()}getMetrics(){return{...this.metrics}}isRunning(){return this.running}async handleLine(e){if(!e.trim())return;if(this.metrics.bytesReceived+=Buffer.byteLength(e,"utf-8"),Buffer.byteLength(e,"utf-8")>this.maxMessageSize){this.metrics.errors++,await this.sendError(null,rn.INVALID_REQUEST,"Message too large");return}let t;try{t=I(e)}catch{this.metrics.errors++,await this.sendError(null,rn.PARSE_ERROR,"Parse error");return}if(t.jsonrpc!=="2.0"){this.metrics.errors++,await this.sendError(t.id??null,rn.INVALID_REQUEST,"Invalid JSON-RPC version");return}if(!t.method||typeof t.method!="string"){this.metrics.errors++,await this.sendError(t.id??null,rn.INVALID_REQUEST,"Missing or invalid method");return}this.metrics.messagesReceived++,t.id!==void 0?await this.handleRequest(t):await this.handleNotification(t)}async handleRequest(e){if(!this.requestHandler){await this.sendError(e.id,rn.INTERNAL_ERROR,"No request handler registered");return}try{let t=await this.requestHandler(e);await this.sendResponse({jsonrpc:"2.0",id:e.id,result:t})}catch(t){if(Hk(t))await this.sendError(e.id,t.code,t.message,t.data);else{let r=t;await this.sendError(e.id,rn.INTERNAL_ERROR,r.message||"Internal error")}}}async handleNotification(e){if(this.notificationHandler)try{await this.notificationHandler(e)}catch(t){this.metrics.errors++,console.error("[StdioTransport] Notification handler error:",t)}}async sendError(e,t,r,n){let i={jsonrpc:"2.0",id:e,error:{code:t,message:r,data:n}};await this.sendResponse(i)}async write(e){let r=[0,500,1e3];for(let n=0;n<3;n++)try{await this.writeOnce(e);return}catch(i){if(n<2)console.error(`[StdioTransport] Write attempt ${n+1} failed, retrying in ${r[n+1]}ms...`),await new Promise(s=>setTimeout(s,r[n+1]));else throw i}}async writeOnce(e){let t=e+`
|
|
6283
6283
|
`;return this.outputStream.writableNeedDrain&&await new Promise((r,n)=>{let i=setTimeout(()=>{n(new Error("Transport drain timeout after 30 seconds"))},3e4);this.outputStream.once("drain",()=>{clearTimeout(i),r()})}),new Promise((r,n)=>{let i=setTimeout(()=>{this.metrics.errors++,n(new Error("Transport write timeout after 120 seconds"))},12e4);this.outputStream.write(t,"utf-8",s=>{clearTimeout(i),s?(this.metrics.errors++,n(s)):(this.metrics.messagesSent++,this.metrics.bytesSent+=Buffer.byteLength(t,"utf-8"),r())})})}};function Wk(o){return new Gk(o)}$();V();$();var due={keepAliveInterval:15e3,connectionTimeout:3e5,maxConnections:1e3,enableMetrics:!0},kv=class{config;connections=new Map;threadIndex=new Map;closedConnections=[];keepAliveTimers=new Map;timeoutTimers=new Map;disposed=!1;constructor(e={}){this.config={...due,...e}}createConnection(e,t,r){if(this.disposed)throw new Error("ConnectionManager has been disposed");if(this.connections.size>=this.config.maxConnections)throw new Error(`Maximum connections (${this.config.maxConnections}) exceeded`);let n=A(),i=Date.now(),s={id:n,threadId:e,runId:t,createdAt:i,lastActivity:i,response:r,abortController:new AbortController,state:"connecting",metrics:{eventsSent:0,bytesSent:0,keepAlivesSent:0,errors:0,startTime:i}};this.connections.set(n,s);let a=this.threadIndex.get(e);return a||(a=new Set,this.threadIndex.set(e,a)),a.add(n),this.startKeepAlive(n),this.startTimeout(n),s}getConnection(e){return this.connections.get(e)}getConnectionByThreadId(e){let t=this.threadIndex.get(e);if(t)for(let r of t){let n=this.connections.get(r);if(n)return n}}getActiveConnections(){return Array.from(this.connections.values()).filter(e=>e.state==="open"||e.state==="connecting")}updateState(e,t){let r=this.connections.get(e);r&&(r.state=t,r.lastActivity=Date.now(),t==="closed"&&(r.metrics.endTime=Date.now()))}recordEventSent(e,t){let r=this.connections.get(e);r&&(r.metrics.eventsSent++,r.metrics.bytesSent+=t,r.lastActivity=Date.now(),this.resetTimeout(e))}recordError(e){let t=this.connections.get(e);t&&t.metrics.errors++}closeConnection(e,t){let r=this.connections.get(e);if(!r)return;if(this.stopKeepAlive(e),this.stopTimeout(e),r.state="closing",r.metrics.endTime=Date.now(),r.abortController.abort(t||"Connection closed"),!r.response.writableEnded)try{r.response.end()}catch{}for(r.state="closed",this.closedConnections.push(r);this.closedConnections.length>1e3;)this.closedConnections.shift();let n=this.threadIndex.get(r.threadId);n&&(n.delete(e),n.size===0&&this.threadIndex.delete(r.threadId)),this.connections.delete(e)}closeThreadConnections(e,t){let r=this.threadIndex.get(e);if(!r)return;let n=Array.from(r);for(let i of n)this.closeConnection(i,t)}getMetrics(){let e=Array.from(this.connections.values()),t=[...e,...this.closedConnections],r=e.filter(s=>s.state==="open"||s.state==="connecting"),n=t.filter(s=>s.metrics.endTime).map(s=>(s.metrics.endTime??0)-s.metrics.startTime),i=n.length>0?n.reduce((s,a)=>s+a,0)/n.length:0;return{totalConnections:t.length,activeConnections:r.length,totalEventsSent:t.reduce((s,a)=>s+a.metrics.eventsSent,0),totalBytesSent:t.reduce((s,a)=>s+a.metrics.bytesSent,0),totalErrors:t.reduce((s,a)=>s+a.metrics.errors,0),averageConnectionDuration:i}}dispose(){if(this.disposed)return;this.disposed=!0;let e=Array.from(this.connections.keys());for(let n of e)this.closeConnection(n,"Manager disposed");let t=Array.from(this.keepAliveTimers.values());for(let n of t)clearInterval(n);this.keepAliveTimers.clear();let r=Array.from(this.timeoutTimers.values());for(let n of r)clearTimeout(n);this.timeoutTimers.clear()}startKeepAlive(e){let t=setInterval(()=>{this.sendKeepAlive(e)},this.config.keepAliveInterval);this.keepAliveTimers.set(e,t)}stopKeepAlive(e){let t=this.keepAliveTimers.get(e);t&&(clearInterval(t),this.keepAliveTimers.delete(e))}sendKeepAlive(e){let t=this.connections.get(e);if(!(!t||t.state!=="open"))try{t.response.write(`: keep-alive
|
|
6284
6284
|
|
|
6285
6285
|
`),t.metrics.keepAlivesSent++,t.lastActivity=Date.now();let n=t.response;n.flush&&typeof n.flush=="function"&&n.flush()}catch{this.closeConnection(e,"Keep-alive failed")}}startTimeout(e){let t=setTimeout(()=>{this.closeConnection(e,"Connection timeout")},this.config.connectionTimeout);this.timeoutTimers.set(e,t)}stopTimeout(e){let t=this.timeoutTimers.get(e);t&&(clearTimeout(t),this.timeoutTimers.delete(e))}resetTimeout(e){this.stopTimeout(e),this.startTimeout(e)}};function eP(o){return new kv(o)}var ct={RUN_STARTED:"RUN_STARTED",RUN_FINISHED:"RUN_FINISHED",RUN_ERROR:"RUN_ERROR",STEP_STARTED:"STEP_STARTED",STEP_FINISHED:"STEP_FINISHED",TEXT_MESSAGE_START:"TEXT_MESSAGE_START",TEXT_MESSAGE_CONTENT:"TEXT_MESSAGE_CONTENT",TEXT_MESSAGE_END:"TEXT_MESSAGE_END",TOOL_CALL_START:"TOOL_CALL_START",TOOL_CALL_ARGS:"TOOL_CALL_ARGS",TOOL_CALL_END:"TOOL_CALL_END",TOOL_CALL_RESULT:"TOOL_CALL_RESULT",STATE_SNAPSHOT:"STATE_SNAPSHOT",STATE_DELTA:"STATE_DELTA",MESSAGES_SNAPSHOT:"MESSAGES_SNAPSHOT",ACTIVITY_SNAPSHOT:"ACTIVITY_SNAPSHOT",ACTIVITY_DELTA:"ACTIVITY_DELTA",RAW:"RAW",CUSTOM:"CUSTOM"};var pue={keepAliveInterval:15e3,maxBufferSize:100,flushInterval:50,parseBody:!0,maxBodySize:1024*1024,connectionTimeout:3e5,customHeaders:{}},tP=class{buffer=[];flushTimer=null;flushInterval;maxSize;onFlush;constructor(e,t,r){this.flushInterval=e,this.maxSize=t,this.onFlush=r}add(e){if(this.buffer.push(e),this.buffer.length>=this.maxSize){this.flush();return}this.flushTimer||(this.flushTimer=setTimeout(()=>{this.flush()},this.flushInterval))}flush(){if(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.buffer.length>0){let e=this.buffer;this.buffer=[],this.onFlush(e)}}clear(){this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.buffer=[]}get size(){return this.buffer.length}},Pv=class{config;connectionManager;agentHandler=null;disposed=!1;constructor(e={}){this.config={...pue,...e},this.connectionManager=eP({keepAliveInterval:this.config.keepAliveInterval,connectionTimeout:this.config.connectionTimeout})}setAgentHandler(e){this.agentHandler=e}async handleRequest(e,t){if(this.disposed){this.sendError(t,503,"Service Unavailable","Transport disposed");return}if(e.method!=="POST"){this.sendError(t,405,"Method Not Allowed","Only POST is supported");return}let r;try{r=await this.parseRequestBody(e)}catch(c){let l=c instanceof Error?c.message:"Failed to parse request body";this.sendError(t,400,"Bad Request",l);return}if(!r.threadId){this.sendError(t,400,"Bad Request","Missing required field: threadId");return}let n=r.runId||A();this.setSSEHeaders(t);let i;try{i=this.connectionManager.createConnection(r.threadId,n,t)}catch(c){let l=c instanceof Error?c.message:"Failed to create connection";this.sendError(t,503,"Service Unavailable",l);return}this.connectionManager.updateState(i.id,"open");let s=new tP(this.config.flushInterval,this.config.maxBufferSize,c=>this.writeEvents(i,c)),a=c=>{i.state==="open"&&(c.timestamp||(c.timestamp=Date.now()),s.add(c))};e.on("close",()=>{s.clear(),this.connectionManager.closeConnection(i.id,"Client disconnected")}),e.on("error",()=>{s.clear(),this.connectionManager.recordError(i.id),this.connectionManager.closeConnection(i.id,"Request error")}),t.on("error",()=>{s.clear(),this.connectionManager.recordError(i.id),this.connectionManager.closeConnection(i.id,"Response error")}),a({type:ct.RUN_STARTED,threadId:r.threadId,runId:n}),s.flush();try{if(!this.agentHandler)throw new Error("No agent handler registered");await this.agentHandler(r,a,i.abortController.signal),s.flush(),i.state==="open"&&this.writeEvent(i,{type:ct.RUN_FINISHED,runId:n,outcome:"success",timestamp:Date.now()})}catch(c){s.flush();let l=c instanceof Error?c.message:"Unknown error";!(c instanceof Error&&c.name==="AbortError")&&i.state==="open"&&(this.writeEvent(i,{type:ct.RUN_ERROR,runId:n,message:l,code:"INTERNAL_ERROR",timestamp:Date.now()}),this.connectionManager.recordError(i.id))}finally{s.clear(),this.connectionManager.closeConnection(i.id,"Request complete")}}getMetrics(){return this.connectionManager.getMetrics()}getActiveConnectionsCount(){return this.connectionManager.getActiveConnections().length}closeAllConnections(e){let t=this.connectionManager.getActiveConnections();for(let r of t)this.connectionManager.closeConnection(r.id,e)}dispose(){this.disposed||(this.disposed=!0,this.connectionManager.dispose())}async parseRequestBody(e){if(e.body)return e.body;if(!this.config.parseBody)throw new Error("Request body parsing is disabled");return new Promise((t,r)=>{let n=[],i=0;e.on("data",s=>{if(i+=s.length,i>this.config.maxBodySize){r(new Error(`Request body exceeds maximum size of ${this.config.maxBodySize} bytes`));return}n.push(s)}),e.on("end",()=>{try{let s=Buffer.concat(n).toString("utf-8");if(!s){r(new Error("Empty request body"));return}let a=I(s);t(a)}catch{r(new Error("Invalid JSON in request body"))}}),e.on("error",s=>{r(s)})})}setSSEHeaders(e){e.setHeader("Content-Type","text/event-stream"),e.setHeader("Cache-Control","no-cache"),e.setHeader("Connection","keep-alive"),e.setHeader("X-Accel-Buffering","no");for(let[t,r]of Object.entries(this.config.customHeaders))e.setHeader(t,r);e.flushHeaders()}writeEvent(e,t){if(!(e.state!=="open"||e.response.writableEnded))try{let r=this.formatSSEEvent(t);e.response.write(r),this.connectionManager.recordEventSent(e.id,Buffer.byteLength(r,"utf-8"));let n=e.response;n.flush&&typeof n.flush=="function"&&n.flush()}catch{this.connectionManager.recordError(e.id)}}writeEvents(e,t){if(!(e.state!=="open"||e.response.writableEnded))try{let r=0,n=[];for(let a of t){let c=this.formatSSEEvent(a);n.push(c),r+=Buffer.byteLength(c,"utf-8")}let i=n.join("");e.response.write(i),this.connectionManager.recordEventSent(e.id,r);let s=e.response;s.flush&&typeof s.flush=="function"&&s.flush()}catch{this.connectionManager.recordError(e.id)}}formatSSEEvent(e){let t=e.type,r=JSON.stringify(e);return`event: ${t}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agentic-qe",
|
|
3
|
-
"version": "3.15.
|
|
3
|
+
"version": "3.15.1",
|
|
4
4
|
"description": "Agentic Quality Engineering V3 - Domain-Driven Design Architecture with 13 Bounded Contexts, O(log n) coverage analysis, ReasoningBank learning, 60 specialized QE agents, mathematical Coherence verification, deep Claude Flow integration",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.0");process.exit(0)}
|
|
2
|
-
import{a,b,c}from"./chunk-VTGRGYY4.js";import"./chunk-5KN4QL3G.js";import"./chunk-3Y24VTZ3.js";import"./chunk-ATXAMGVE.js";import"./chunk-X5RELRY7.js";import"./chunk-GX5RFGW2.js";export{a as AgentBoosterAdapter,b as createAgentBoosterAdapter,c as createAgentBoosterAdapterSync};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.0");process.exit(0)}
|
|
2
|
-
import{a,b,c,d,e,f}from"./chunk-N5ZHIQAV.js";import"./chunk-YIDZ3TEN.js";import"./chunk-XELFJC77.js";import"./chunk-KEZ4PXVF.js";import"./chunk-KUTMQBV4.js";import"./chunk-GCHDMO5V.js";import"./chunk-MFGLRMO4.js";import"./chunk-I3BH3KIF.js";import"./chunk-BAPMEDWC.js";import"./chunk-7JABIXP3.js";import"./chunk-4DCDIKBX.js";import"./chunk-WPOYFV4X.js";import"./chunk-PN3FYSQ6.js";import"./chunk-KU4WLKDK.js";import"./chunk-URRPJ3M7.js";import"./chunk-QVX22EIM.js";import"./chunk-XZDPR6I2.js";import"./chunk-ILKMNDUM.js";import"./chunk-ATXAMGVE.js";import"./chunk-JJ7WAU4I.js";import"./chunk-7WUHVGGT.js";import"./chunk-UGYXUPGN.js";import"./chunk-HOPXHZA3.js";import"./chunk-B6QTNTCU.js";import"./chunk-WBR4VRQE.js";import"./chunk-WPSGMTI4.js";import"./chunk-GV7P5JYF.js";import"./chunk-MO3QXLF2.js";import"./chunk-BH2SQQ2N.js";import"./chunk-5LN7FQZI.js";import"./chunk-AIE6OKCD.js";import"./chunk-OYVDTD3A.js";import"./chunk-OBSX3I4Y.js";import"./chunk-X5RELRY7.js";import"./chunk-URUOTHPO.js";import"./chunk-NZ556KZN.js";import"./chunk-QRALXNNX.js";import"./chunk-X7JEBPEW.js";import"./chunk-CMYZWIXS.js";import"./chunk-AGYPPPXR.js";import"./chunk-WDV6CBED.js";import"./chunk-GX5RFGW2.js";export{b as AQELearningEngine,a as DEFAULT_ENGINE_CONFIG,c as DEFAULT_META_LEARNING_CONFIG,d as MetaLearningEngine,e as createAQELearningEngine,f as createDefaultLearningEngine};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.0");process.exit(0)}
|
|
2
|
-
import{a,b,c,d,e,f,g,h,i,j,k,l}from"./chunk-5PNRUMRV.js";import"./chunk-WQMXQO3O.js";import"./chunk-R6CZCMKD.js";import"./chunk-XZDPR6I2.js";import"./chunk-ILKMNDUM.js";import"./chunk-ATXAMGVE.js";import"./chunk-JJ7WAU4I.js";import"./chunk-7WUHVGGT.js";import"./chunk-UGYXUPGN.js";import"./chunk-HOPXHZA3.js";import"./chunk-B6QTNTCU.js";import"./chunk-WBR4VRQE.js";import"./chunk-GV7P5JYF.js";import"./chunk-MO3QXLF2.js";import"./chunk-5LN7FQZI.js";import"./chunk-AIE6OKCD.js";import"./chunk-OYVDTD3A.js";import"./chunk-OBSX3I4Y.js";import"./chunk-X5RELRY7.js";import"./chunk-URUOTHPO.js";import"./chunk-QRALXNNX.js";import"./chunk-AGYPPPXR.js";import"./chunk-WDV6CBED.js";import"./chunk-GX5RFGW2.js";export{l as MCPToolBase,k as defaultToolLogger,j as getKernel,i as getLLMRouter,e as getMemoryBackend,g as getSharedLLMRouter,c as getSharedMemoryBackend,a as isMemoryOnlyMode,b as registerRvfResetFn,h as resetSharedLLMRouter,d as resetSharedMemoryBackend,f as setSharedLLMRouter};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.0");process.exit(0)}
|
|
2
|
-
import{a}from"./chunk-JO2YLIZH.js";import"./chunk-5PNRUMRV.js";import"./chunk-WQMXQO3O.js";import"./chunk-R6CZCMKD.js";import"./chunk-XZDPR6I2.js";import"./chunk-ILKMNDUM.js";import"./chunk-ATXAMGVE.js";import"./chunk-JJ7WAU4I.js";import"./chunk-7WUHVGGT.js";import"./chunk-UGYXUPGN.js";import"./chunk-HOPXHZA3.js";import"./chunk-B6QTNTCU.js";import"./chunk-WBR4VRQE.js";import"./chunk-GV7P5JYF.js";import"./chunk-MO3QXLF2.js";import"./chunk-5LN7FQZI.js";import"./chunk-AIE6OKCD.js";import"./chunk-OYVDTD3A.js";import"./chunk-OBSX3I4Y.js";import"./chunk-X5RELRY7.js";import"./chunk-URUOTHPO.js";import"./chunk-QRALXNNX.js";import"./chunk-AGYPPPXR.js";import"./chunk-WDV6CBED.js";import"./chunk-GX5RFGW2.js";export{a as BrowserWorkflowTool};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.0");process.exit(0)}
|
|
2
|
-
import{a as e,c as r,d as g,g as t}from"./chunk-OYVDTD3A.js";import{b as o}from"./chunk-GX5RFGW2.js";var L=o(()=>{"use strict";e();g();t();r()});export{L as a};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.0");process.exit(0)}
|
|
2
|
-
import{c as a,d as b,e as c}from"./chunk-MRIZY6HB.js";import"./chunk-S7CROKX4.js";import"./chunk-X5RELRY7.js";import"./chunk-GX5RFGW2.js";c();export{a as VibiumClientImpl,b as VibiumClientProvider};
|