agentic-qe 3.15.6 → 3.15.8
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 +263 -0
- package/README.md +2 -0
- package/assets/skills/skills-manifest.json +1 -1
- package/dist/cli/bundle.js +8 -6
- package/dist/cli/chunks/adapter-FC4EY447.js +2 -0
- package/dist/cli/chunks/{agent-booster-wasm-SY7UCLBL.js → agent-booster-wasm-W3V5P7LE.js} +2 -2
- package/dist/cli/chunks/{agent-handler-KAMYBU3S.js → agent-handler-2NQFHAWE.js} +2 -2
- package/dist/cli/chunks/{agent-memory-branch-2CAW3KUM.js → agent-memory-branch-457ECHHK.js} +2 -2
- package/dist/cli/chunks/aqe-learning-engine-AUAL6UBL.js +2 -0
- package/dist/cli/chunks/{arena-QCCVIOAH.js → arena-IYBQ3GPY.js} +4 -4
- package/dist/cli/chunks/{arena-4OFLJ3R2.js → arena-JV3WSEHU.js} +2 -2
- package/dist/cli/chunks/{audit-RBDQJQJB.js → audit-5OS3T3K6.js} +3 -3
- package/dist/cli/chunks/base-2XML4WH7.js +2 -0
- package/dist/cli/chunks/{better-sqlite3-5JRACCDQ.js → better-sqlite3-IQKBFVAO.js} +2 -2
- package/dist/cli/chunks/{brain-handler-W4QIIRT4.js → brain-handler-KA3SGAFM.js} +3 -3
- package/dist/cli/chunks/{branch-enumerator-IBNGI572.js → branch-enumerator-QZDU2VOQ.js} +2 -2
- package/dist/cli/chunks/{browser-GMSCVAOI.js → browser-ZL7OLKJQ.js} +2 -2
- package/dist/cli/chunks/browser-workflow-2IFEUAAK.js +2 -0
- package/dist/cli/chunks/{chunk-6HWARQWV.js → chunk-22DOS3PM.js} +2 -2
- package/dist/cli/chunks/{chunk-VCONCVSY.js → chunk-2DPHFCMW.js} +2 -2
- package/dist/cli/chunks/{chunk-ALCIUWFC.js → chunk-2GSAAUW3.js} +1 -1
- package/dist/cli/chunks/{chunk-AX26QJ6T.js → chunk-2JCLACCS.js} +2 -2
- package/dist/cli/chunks/{chunk-7XTANLTN.js → chunk-2QRGIEQV.js} +1 -1
- package/dist/cli/chunks/{chunk-MP3FSUNB.js → chunk-2UN4JOTN.js} +2 -2
- package/dist/cli/chunks/{chunk-CR66HNAE.js → chunk-2ZRNXEVI.js} +1 -1
- package/dist/cli/chunks/{chunk-WKDWRRDT.js → chunk-3LFLO2WK.js} +2 -2
- package/dist/cli/chunks/{chunk-QLYO3H7E.js → chunk-3N627QRU.js} +2 -2
- package/dist/cli/chunks/{chunk-VVF337SV.js → chunk-4C3RYBTT.js} +2 -2
- package/dist/cli/chunks/{chunk-MQCTLTGE.js → chunk-4C7KE2EL.js} +2 -2
- package/dist/cli/chunks/{chunk-AUN4FG7V.js → chunk-4GUVVGJX.js} +1 -1
- package/dist/cli/chunks/{chunk-ZOUEQ6DL.js → chunk-4GYFONJB.js} +1 -1
- package/dist/cli/chunks/{chunk-24ZSGYC6.js → chunk-4I35ARWW.js} +1 -1
- package/dist/cli/chunks/{chunk-6MXAJBEA.js → chunk-4NTLGGXO.js} +1 -1
- package/dist/cli/chunks/{chunk-EF5UHDCG.js → chunk-4TZLZRZ4.js} +1 -1
- package/dist/cli/chunks/{chunk-RD5BYLN7.js → chunk-4YUBWU3E.js} +1 -1
- package/dist/cli/chunks/{chunk-7TVIX4WL.js → chunk-52YRSWPS.js} +2 -2
- package/dist/cli/chunks/{chunk-LAY7NCQK.js → chunk-5DZDLOY6.js} +3 -3
- package/dist/cli/chunks/{chunk-34MDMFET.js → chunk-5MBNRTT5.js} +2 -2
- package/dist/cli/chunks/{chunk-VAYZ5QIE.js → chunk-5ONJ7AV6.js} +1 -1
- package/dist/cli/chunks/{chunk-RV6HSMKJ.js → chunk-5YOO5QSE.js} +1 -1
- package/dist/cli/chunks/{chunk-BUTGIVKW.js → chunk-62T7U25U.js} +1 -1
- package/dist/cli/chunks/{chunk-66NW3ZB4.js → chunk-6CKTLVYV.js} +2 -2
- package/dist/cli/chunks/{chunk-TUDENMAE.js → chunk-6E7EOHMN.js} +2 -2
- package/dist/cli/chunks/{chunk-GVRFSXY6.js → chunk-6GIC2263.js} +2 -2
- package/dist/cli/chunks/{chunk-KIDOBLUO.js → chunk-767SR7WH.js} +2 -2
- package/dist/cli/chunks/{chunk-NBUXM5X6.js → chunk-7C6FMLQR.js} +2 -2
- package/dist/cli/chunks/{chunk-4POOJYXA.js → chunk-7CVMT64N.js} +1 -1
- package/dist/cli/chunks/{chunk-R363XXGH.js → chunk-7DHSHD5B.js} +2 -2
- package/dist/cli/chunks/{chunk-IEPWO4XP.js → chunk-7H3GNRNA.js} +2 -2
- package/dist/cli/chunks/{chunk-DQNUPEY5.js → chunk-7SLEUVPZ.js} +2 -2
- package/dist/cli/chunks/{chunk-YNG7E26C.js → chunk-7XGM7Q2N.js} +2 -2
- package/dist/cli/chunks/{chunk-5MT7DMD7.js → chunk-A2UGPKCS.js} +2 -2
- package/dist/cli/chunks/{chunk-2CIDFR2H.js → chunk-A6GCO6ZU.js} +2 -2
- package/dist/cli/chunks/{chunk-XFPQIWEH.js → chunk-BEVWCF3Q.js} +3 -3
- package/dist/cli/chunks/{chunk-LCCTJ2PC.js → chunk-BLZEOGQE.js} +2 -2
- package/dist/cli/chunks/{chunk-6R3FBFCJ.js → chunk-BQUIZ5QT.js} +2 -2
- package/dist/cli/chunks/{chunk-ZUTFHGEO.js → chunk-BTMEOZYY.js} +1 -1
- package/dist/cli/chunks/{chunk-FU7LNUD7.js → chunk-CDLG3Q2O.js} +2 -2
- package/dist/cli/chunks/{chunk-NYS2GUNO.js → chunk-CQ3SBRDP.js} +2 -2
- package/dist/cli/chunks/chunk-CQ5G64EA.js +3 -0
- package/dist/cli/chunks/{chunk-JCE76MPP.js → chunk-CRUQ6RXU.js} +2 -2
- package/dist/cli/chunks/{chunk-XBFQJZWX.js → chunk-D4IBIMWI.js} +2 -2
- package/dist/cli/chunks/{chunk-LZWJ5BMP.js → chunk-D4O3TJI7.js} +2 -2
- package/dist/cli/chunks/{chunk-AUOSHM63.js → chunk-DAFMHM64.js} +2 -2
- package/dist/cli/chunks/{chunk-V3OLS2NG.js → chunk-DCYUHCPK.js} +2 -2
- package/dist/cli/chunks/{chunk-F7A2UBZO.js → chunk-DKFSCJEF.js} +2 -2
- package/dist/cli/chunks/{chunk-5LST62QR.js → chunk-DN3AKAPY.js} +2 -2
- package/dist/cli/chunks/{chunk-OQ4S6B7P.js → chunk-DY37YMMQ.js} +1 -1
- package/dist/cli/chunks/{chunk-XQ53PZEF.js → chunk-EUVSSIGR.js} +3 -3
- package/dist/cli/chunks/{chunk-6WOZUSSN.js → chunk-FAYXES7R.js} +2 -2
- package/dist/cli/chunks/{chunk-GNYOHZVV.js → chunk-FEN2DHFM.js} +1 -1
- package/dist/cli/chunks/{chunk-BAYGQRNP.js → chunk-FEPFXXI7.js} +2 -2
- package/dist/cli/chunks/{chunk-DLSFT6PO.js → chunk-FJAO4UX2.js} +2 -2
- package/dist/cli/chunks/{chunk-22OZIJAD.js → chunk-FWXNFPLS.js} +2 -2
- package/dist/cli/chunks/{chunk-X33F7NXH.js → chunk-G6CLO74Q.js} +3 -3
- package/dist/cli/chunks/{chunk-HAN4MS5T.js → chunk-G77Q22EN.js} +2 -2
- package/dist/cli/chunks/{chunk-5DH5QI7G.js → chunk-GENNJRNK.js} +3 -3
- package/dist/cli/chunks/{chunk-LMAEMVPA.js → chunk-GGSTLKY5.js} +1 -1
- package/dist/cli/chunks/{chunk-EJ4KZFZN.js → chunk-GSOK4M6V.js} +1 -1
- package/dist/cli/chunks/{chunk-DA7DGDTI.js → chunk-HI6OBDDY.js} +2 -2
- package/dist/cli/chunks/{chunk-XZ46CI35.js → chunk-HNGNRIZZ.js} +2 -2
- package/dist/cli/chunks/{chunk-CLAMMGY3.js → chunk-HXCGV5UJ.js} +2 -2
- package/dist/cli/chunks/{chunk-5UPIL62W.js → chunk-I4U7YCXG.js} +3 -3
- package/dist/cli/chunks/{chunk-RFDFET3O.js → chunk-I77D65X5.js} +2 -2
- package/dist/cli/chunks/{chunk-HEGGV2PT.js → chunk-IJSFZO7P.js} +2 -2
- package/dist/cli/chunks/{chunk-GWM4M5NF.js → chunk-IMSRWNWF.js} +1 -1
- package/dist/cli/chunks/{chunk-B7RHBKHL.js → chunk-J6LL25QJ.js} +2 -2
- package/dist/cli/chunks/{chunk-KYVIOC3C.js → chunk-J7FLNP5L.js} +2 -2
- package/dist/cli/chunks/{chunk-YLNYPQDR.js → chunk-J7RCI25Q.js} +1 -1
- package/dist/cli/chunks/{chunk-72MQCZSM.js → chunk-JFWQFB3S.js} +2 -2
- package/dist/cli/chunks/{chunk-SV5BUYHH.js → chunk-JLTGO5BB.js} +2 -2
- package/dist/cli/chunks/{chunk-CCL436IU.js → chunk-JWPYMRIX.js} +14 -6
- package/dist/cli/chunks/{chunk-ONPPBLRB.js → chunk-K4N2MBCE.js} +2 -2
- package/dist/cli/chunks/{chunk-7SAMMQVS.js → chunk-K5R3WUJP.js} +1 -1
- package/dist/cli/chunks/{chunk-GI5HWS4H.js → chunk-KITKQUBX.js} +1 -1
- package/dist/cli/chunks/{chunk-7TJZDRDU.js → chunk-KJNUETCB.js} +1 -1
- package/dist/cli/chunks/{chunk-JYKQVYX2.js → chunk-KMVFBYJO.js} +2 -2
- package/dist/cli/chunks/{chunk-ZSBD4FUX.js → chunk-KMZW2P3R.js} +2 -2
- package/dist/cli/chunks/{chunk-PEMSXSP2.js → chunk-KNHLOANK.js} +2 -2
- package/dist/cli/chunks/{chunk-47Q7JL3V.js → chunk-KNQUHGNY.js} +2 -2
- package/dist/cli/chunks/{chunk-A7ANPS4E.js → chunk-KVMKYUOE.js} +2 -2
- package/dist/cli/chunks/{chunk-XBEI2JBA.js → chunk-LHRVSK44.js} +2 -2
- package/dist/cli/chunks/{chunk-AJT3XDRD.js → chunk-LPSMVBB3.js} +2 -2
- package/dist/cli/chunks/{chunk-ORBODZSO.js → chunk-LVHZK7GW.js} +2 -2
- package/dist/cli/chunks/{chunk-ZTB32K5N.js → chunk-LZWBUVCK.js} +3 -3
- package/dist/cli/chunks/{chunk-OPDZBRIL.js → chunk-MMY52Y6R.js} +2 -2
- package/dist/cli/chunks/{chunk-MQTA6KIO.js → chunk-MUDBF2JC.js} +1 -1
- package/dist/cli/chunks/{chunk-GFB6BZWU.js → chunk-MV4S3TEC.js} +2 -2
- package/dist/cli/chunks/{chunk-UB6DQGWM.js → chunk-NF63NHJH.js} +2 -2
- package/dist/cli/chunks/{chunk-D5N2O5EH.js → chunk-NHOMVBCI.js} +2 -2
- package/dist/cli/chunks/{chunk-3NJ7O3OH.js → chunk-NLYUC63R.js} +2 -2
- package/dist/cli/chunks/{chunk-4CLDYT36.js → chunk-NQDYOF35.js} +2 -2
- package/dist/cli/chunks/{chunk-ORFL3YXB.js → chunk-NW7HTOSN.js} +2 -2
- package/dist/cli/chunks/{chunk-FQ5N666N.js → chunk-NWFBF3KT.js} +1 -1
- package/dist/cli/chunks/{chunk-P7DXVL2S.js → chunk-NZATJ2C6.js} +2 -2
- package/dist/cli/chunks/{chunk-HOEWMEF2.js → chunk-O4RRVTXN.js} +2 -2
- package/dist/cli/chunks/{chunk-4KOVHQXK.js → chunk-OCLAMZJG.js} +2 -2
- package/dist/cli/chunks/{chunk-TLUIO37P.js → chunk-OJWEZYLR.js} +2 -2
- package/dist/cli/chunks/{chunk-A74J23QB.js → chunk-OWBFVAEH.js} +2 -2
- package/dist/cli/chunks/{chunk-6T6AHVLF.js → chunk-P2EA62YS.js} +1 -1
- package/dist/cli/chunks/{chunk-TL5GV3PR.js → chunk-P4UT4LBE.js} +3 -3
- package/dist/cli/chunks/{chunk-IVJIHZSM.js → chunk-PICEGWGB.js} +1 -1
- package/dist/cli/chunks/{chunk-ITIJ23K2.js → chunk-PIEKGKW6.js} +2 -2
- package/dist/cli/chunks/{chunk-2ZTWPMTK.js → chunk-PJGQ2TKN.js} +2 -2
- package/dist/cli/chunks/{chunk-KCB6P463.js → chunk-PPIM7B5G.js} +2 -2
- package/dist/cli/chunks/{chunk-L2TDHJR3.js → chunk-PUYQ6EKC.js} +2 -2
- package/dist/cli/chunks/{chunk-2IWPJUVV.js → chunk-PWA6XBW4.js} +8 -8
- package/dist/cli/chunks/{chunk-XPB5BVU6.js → chunk-PZ7FJ4UG.js} +2 -2
- package/dist/cli/chunks/{chunk-SOSJWM3E.js → chunk-QFYUZYRA.js} +4 -4
- package/dist/cli/chunks/{chunk-RUTO67PT.js → chunk-R2NHGESM.js} +2 -2
- package/dist/cli/chunks/{chunk-K55EAWZ5.js → chunk-RG42LDOB.js} +2 -2
- package/dist/cli/chunks/{chunk-JAPBSSFY.js → chunk-RSMPJWQH.js} +1 -1
- package/dist/cli/chunks/{chunk-46HBVDMU.js → chunk-SFPGLUXS.js} +1 -1
- package/dist/cli/chunks/{chunk-TVLOED6O.js → chunk-SHEVM5PF.js} +2 -2
- package/dist/cli/chunks/{chunk-6RDVY26I.js → chunk-SJMZZMHP.js} +2 -2
- package/dist/cli/chunks/{chunk-3DJNKNBR.js → chunk-ST7ASEJO.js} +57 -57
- package/dist/cli/chunks/{chunk-QS5KZYUZ.js → chunk-SWY6KGMF.js} +2 -2
- package/dist/cli/chunks/{chunk-UHHMAKPE.js → chunk-T2TDTBFV.js} +1 -1
- package/dist/cli/chunks/{chunk-5HAPS6VD.js → chunk-TC52M542.js} +2 -2
- package/dist/cli/chunks/chunk-TMNEK7TP.js +2 -0
- package/dist/cli/chunks/{chunk-ELI4GDQO.js → chunk-U3BWBP6B.js} +2 -2
- package/dist/cli/chunks/{chunk-CZBIREL5.js → chunk-U7CIY3YR.js} +2 -2
- package/dist/cli/chunks/{chunk-X2DR27AY.js → chunk-UDCYQLTD.js} +2 -2
- package/dist/cli/chunks/{chunk-CEXNW5TR.js → chunk-UKKFZJME.js} +1 -1
- package/dist/cli/chunks/{chunk-5NC7QEJ6.js → chunk-UQLAN5TX.js} +4 -4
- package/dist/cli/chunks/{chunk-BIXRTOH3.js → chunk-UTFMMZ57.js} +3 -3
- package/dist/cli/chunks/{chunk-YXU35GGD.js → chunk-UTNKMPTC.js} +1 -1
- package/dist/cli/chunks/{chunk-HZFK2Z2Z.js → chunk-V4QJ3MMT.js} +1 -1
- package/dist/cli/chunks/{chunk-LJCEDTUM.js → chunk-V7VZSNDK.js} +3 -3
- package/dist/cli/chunks/{chunk-RLB7K7QP.js → chunk-VKFVJCIH.js} +1 -1
- package/dist/cli/chunks/{chunk-5GIJU2ZY.js → chunk-VQRBBR27.js} +2 -2
- package/dist/cli/chunks/{chunk-Q2RBOC7V.js → chunk-VVK4ECVJ.js} +2 -2
- package/dist/cli/chunks/{chunk-624QRKQX.js → chunk-VWRNG3UK.js} +1 -1
- package/dist/cli/chunks/{chunk-F3KS3TAB.js → chunk-VWSGWYRB.js} +2 -2
- package/dist/cli/chunks/{chunk-I7WAW7TM.js → chunk-W5A36V3Z.js} +2 -2
- package/dist/cli/chunks/chunk-WAWKAYPY.js +2 -0
- package/dist/cli/chunks/{chunk-NMY4KTWA.js → chunk-WLXGUQOZ.js} +2 -2
- package/dist/cli/chunks/{chunk-7VTKR44N.js → chunk-X3HM7SV4.js} +2 -2
- package/dist/cli/chunks/chunk-X6VYQVUM.js +2 -0
- package/dist/cli/chunks/{chunk-ZL5LJT7D.js → chunk-X7ZQIFES.js} +2 -2
- package/dist/cli/chunks/{chunk-5VUIXDY2.js → chunk-XOOBLZXR.js} +2 -2
- package/dist/cli/chunks/{chunk-L4D3TPFP.js → chunk-XZQVC3GD.js} +1 -1
- package/dist/cli/chunks/{chunk-BO7UFNYV.js → chunk-Y5ZBF7MA.js} +2 -2
- package/dist/cli/chunks/{chunk-ULCHPPW2.js → chunk-YNQPHRUZ.js} +1 -1
- package/dist/cli/chunks/{chunk-ZCP4P6O2.js → chunk-YRH7KMTU.js} +2 -2
- package/dist/cli/chunks/{chunk-QLKUCMZC.js → chunk-YTYS2XSY.js} +1 -1
- package/dist/cli/chunks/{chunk-JPJEAK4G.js → chunk-YUP3APSN.js} +1 -1
- package/dist/cli/chunks/{chunk-BXATKI5S.js → chunk-YVWMJZ6O.js} +2 -2
- package/dist/cli/chunks/{chunk-PS6WFCA4.js → chunk-Z3LDUPLQ.js} +2 -2
- package/dist/cli/chunks/{chunk-FOJRPEIP.js → chunk-ZBI7PJFX.js} +2 -2
- package/dist/cli/chunks/{chunk-NHRF3V4B.js → chunk-ZG7UKWBB.js} +2 -2
- package/dist/cli/chunks/{chunk-7XUB7U6Z.js → chunk-ZOHS32SI.js} +2 -2
- package/dist/cli/chunks/{chunk-RHIQ6QO5.js → chunk-ZOVAZTXE.js} +430 -430
- package/dist/cli/chunks/{chunk-7QVPMH25.js → chunk-ZWMFKZEQ.js} +2 -2
- package/dist/cli/chunks/{ci-GEJCXMBK.js → ci-7NUCRGWO.js} +2 -2
- package/dist/cli/chunks/{ci-config-2ZVV4OXL.js → ci-config-VQVECCFI.js} +2 -2
- package/dist/cli/chunks/{ci-output-E45OGVPR.js → ci-output-P7GQ6TKF.js} +2 -2
- package/dist/cli/chunks/{circuit-breaker-X73ITYZC.js → circuit-breaker-5YP6N6HE.js} +2 -2
- package/dist/cli/chunks/{claude-flow-setup-W4PPH46C.js → claude-flow-setup-W5H7CMU6.js} +2 -2
- package/dist/cli/chunks/client-RFUSQRUZ.js +2 -0
- package/dist/cli/chunks/{cline-installer-NUEPMWDE.js → cline-installer-OYANSZ54.js} +2 -2
- package/dist/cli/chunks/{code-6WQHBS7G.js → code-OMT4UEZI.js} +3 -3
- package/dist/cli/chunks/{code-index-extractor-BXQIFIFT.js → code-index-extractor-M2JEWKNF.js} +2 -2
- package/dist/cli/chunks/{codex-installer-Z337R2KH.js → codex-installer-YBS6N5O3.js} +2 -2
- package/dist/cli/chunks/{completions-F5DMYFHV.js → completions-U7GS5RG6.js} +2 -2
- package/dist/cli/chunks/{complexity-analyzer-W2SYPZDI.js → complexity-analyzer-QSXPIUIU.js} +2 -2
- package/dist/cli/chunks/{continuedev-installer-ZCHUIFTN.js → continuedev-installer-W5TTT743.js} +2 -2
- package/dist/cli/chunks/{copilot-installer-M5JNODXF.js → copilot-installer-KC2RT24C.js} +2 -2
- package/dist/cli/chunks/core-handlers-ZC7QB432.js +2 -0
- package/dist/cli/chunks/{cost-tracker-LSYTHBHV.js → cost-tracker-OQPVR6V4.js} +2 -2
- package/dist/cli/chunks/{coverage-PGMRS5SS.js → coverage-TCO2A2NX.js} +3 -3
- package/dist/cli/chunks/cross-domain-router-GRBK7YFZ.js +2 -0
- package/dist/cli/chunks/{cursor-installer-XPUA73UW.js → cursor-installer-MH7GWD4L.js} +2 -2
- package/dist/cli/chunks/daemon-JER6HE2J.js +12 -0
- package/dist/cli/chunks/{daemon-ITKDIYMW.js → daemon-UJEARJZ2.js} +3 -3
- package/dist/cli/chunks/{dag-attention-scheduler-T55AXLD6.js → dag-attention-scheduler-F3SUJU5O.js} +2 -2
- package/dist/cli/chunks/{detect-DR7J6K4O.js → detect-5QTCRB32.js} +2 -2
- package/dist/cli/chunks/{dist-node-LAJJBOUT.js → dist-node-XKZPHDBO.js} +2 -2
- package/dist/cli/chunks/{domain-handler-OMSHCRMK.js → domain-handler-V3UEADKW.js} +2 -2
- package/dist/cli/chunks/{domain-plugins-EQXSKC5K.js → domain-plugins-7PES4UHZ.js} +2 -2
- package/dist/cli/chunks/{domain-transfer-FKRAGVSW.js → domain-transfer-NF7UJW7B.js} +2 -2
- package/dist/cli/chunks/dream-VALD726W.js +2 -0
- package/dist/cli/chunks/{embed-and-insert-pattern-JZFPCNL3.js → embed-and-insert-pattern-D2HWORHF.js} +2 -2
- package/dist/cli/chunks/{eval-JSNNASBW.js → eval-UF2UBAUC.js} +2 -2
- package/dist/cli/chunks/{experience-capture-middleware-UPD3IZBK.js → experience-capture-middleware-2OUCEHHM.js} +3 -3
- package/dist/cli/chunks/{fast-paths-YNMIBS2E.js → fast-paths-KV5DKKHC.js} +2 -2
- package/dist/cli/chunks/{feature-flags-SRLXDKBI.js → feature-flags-6YWMTNO5.js} +2 -2
- package/dist/cli/chunks/{feature-flags-VIR7O4L7.js → feature-flags-MTW6NMR3.js} +2 -2
- package/dist/cli/chunks/file-discovery-VL73ASNI.js +2 -0
- package/dist/cli/chunks/{fleet-K2ED46EL.js → fleet-GJ66QFXK.js} +3 -3
- package/dist/cli/chunks/{gnn-wrapper-QCU4ZRYW.js → gnn-wrapper-52V6ANOY.js} +2 -2
- package/dist/cli/chunks/{heartbeat-handler-YYQI4WZM.js → heartbeat-handler-X7NHNRC7.js} +4 -4
- package/dist/cli/chunks/heartbeat-scheduler-FSX7A3ZA.js +2 -0
- package/dist/cli/chunks/hnsw-adapter-UX2QT6RL.js +2 -0
- package/dist/cli/chunks/hnsw-index-WRDDAMXH.js +2 -0
- package/dist/cli/chunks/{hnsw-legacy-bridge-C5TJSWTZ.js → hnsw-legacy-bridge-DZBE3KMK.js} +2 -2
- package/dist/cli/chunks/{hnswlib-node-SE3MJJYS.js → hnswlib-node-2AWWUJAZ.js} +2 -2
- package/dist/cli/chunks/{hooks-C572SRDH.js → hooks-XLPVROL3.js} +10 -10
- package/dist/cli/chunks/hybrid-backend-O67NGIB5.js +2 -0
- package/dist/cli/chunks/{hypergraph-engine-35A6G3M5.js → hypergraph-engine-6TI7YP6P.js} +2 -2
- package/dist/cli/chunks/{hypergraph-handler-U2756CWI.js → hypergraph-handler-DBIBBOXS.js} +3 -3
- package/dist/cli/chunks/impact-analyzer-6VXWWYWM.js +2 -0
- package/dist/cli/chunks/init-guard-OSO6MIDD.js +2 -0
- package/dist/cli/chunks/init-handler-7S7IHMUF.js +88 -0
- package/dist/cli/chunks/init-wizard-VH34J4TL.js +2 -0
- package/dist/cli/chunks/kernel-KJD24NO7.js +2 -0
- package/dist/cli/chunks/{kilocode-installer-32PX5YH7.js → kilocode-installer-2KBRFXMA.js} +2 -2
- package/dist/cli/chunks/{kiro-installer-C4ROMMUS.js → kiro-installer-5VFR4OQZ.js} +2 -2
- package/dist/cli/chunks/knowledge-graph-343O2HEZ.js +2 -0
- package/dist/cli/chunks/{learning-GEPVZGJQ.js → learning-G5NHL3DV.js} +20 -20
- package/dist/cli/chunks/{llm-router-XRKTTJTX.js → llm-router-4EAPPMHS.js} +4 -4
- package/dist/cli/chunks/llm-router-service-2M4BT2AO.js +2 -0
- package/dist/cli/chunks/{load-XVH6HW7E.js → load-UYMZPEY6.js} +2 -2
- package/dist/cli/chunks/load-test-OTQ2JQ5F.js +2 -0
- package/dist/cli/chunks/{mcp-IULSTM4Z.js → mcp-NOTDZBW5.js} +2 -2
- package/dist/cli/chunks/{memory-6K7IAU4T.js → memory-QL53YIHP.js} +5 -5
- package/dist/cli/chunks/memory-backend-4QSNRRV6.js +2 -0
- package/dist/cli/chunks/{memory-handlers-CG6DRLAW.js → memory-handlers-YFFYRSM6.js} +2 -2
- package/dist/cli/chunks/{multi-model-executor-VZDUYPLX.js → multi-model-executor-PDDDXF2B.js} +2 -2
- package/dist/cli/chunks/{opencode-installer-QUTXKNH4.js → opencode-installer-75D2SKOT.js} +2 -2
- package/dist/cli/chunks/{orchestrator-PCKKUWOP.js → orchestrator-3WIZBV4T.js} +5 -5
- package/dist/cli/chunks/pattern-null-store-5USH5MNR.js +2 -0
- package/dist/cli/chunks/{pattern-usage-recorder-PX5HQVRL.js → pattern-usage-recorder-TEX2JGHA.js} +2 -2
- package/dist/cli/chunks/{pipeline-O562GTOG.js → pipeline-7ATPA6LU.js} +2 -2
- package/dist/cli/chunks/{platform-PM7Q2AZS.js → platform-WPSKRJE7.js} +2 -2
- package/dist/cli/chunks/{plugin-OTYTFGPY.js → plugin-UUFOVVMU.js} +2 -2
- package/dist/cli/chunks/{prime-radiant-advanced-wasm-6CFXTHC2.js → prime-radiant-advanced-wasm-PDFSYWKZ.js} +2 -2
- package/dist/cli/chunks/project-root-SRTA6TBL.js +2 -0
- package/dist/cli/chunks/protocol-executor-4WYPCNBS.js +2 -0
- package/dist/cli/chunks/{protocol-handler-PPGNSAOS.js → protocol-handler-3VRYRIQB.js} +2 -2
- package/dist/cli/chunks/{prove-WQ3BKRZG.js → prove-2NAUROGF.js} +2 -2
- package/dist/cli/chunks/qe-reasoning-bank-I4D6SFS4.js +2 -0
- package/dist/cli/chunks/{quality-C5WUU3AA.js → quality-ZIEI2WGA.js} +2 -2
- package/dist/cli/chunks/{quality-gate-WSSRKD5U.js → quality-gate-KWJO4SWQ.js} +3 -3
- package/dist/cli/chunks/queen-coordinator-24UMTZTE.js +2 -0
- package/dist/cli/chunks/{real-embeddings-CFQE7IRQ.js → real-embeddings-TSZ4UIAE.js} +2 -2
- package/dist/cli/chunks/{ref-validation-DHKHXVZT.js → ref-validation-DWFFRETJ.js} +2 -2
- package/dist/cli/chunks/{roocode-installer-3PPODABV.js → roocode-installer-XTZHLUBO.js} +2 -2
- package/dist/cli/chunks/router-AUD4GATI.js +2 -0
- package/dist/cli/chunks/routing-feedback-2FE6SIKQ.js +2 -0
- package/dist/cli/chunks/{routing-handler-JNXTGT6T.js → routing-handler-GG525TDM.js} +2 -2
- package/dist/cli/chunks/{ruvector-commands-6YLROPVP.js → ruvector-commands-QKRJDM7Z.js} +2 -2
- package/dist/cli/chunks/rvf-dual-writer-P5LEUF25.js +2 -0
- package/dist/cli/chunks/rvf-migration-adapter-ZCYD5YJS.js +2 -0
- package/dist/cli/chunks/{rvf-migration-coordinator-4DWB4WRK.js → rvf-migration-coordinator-FF52OS6Q.js} +2 -2
- package/dist/cli/chunks/rvf-native-adapter-QGV6BW2W.js +2 -0
- package/dist/cli/chunks/{rvf-store-integrity-YKR2ZNBF.js → rvf-store-integrity-M6DXTAZ4.js} +2 -2
- package/dist/cli/chunks/safe-db-Q6JUKG2A.js +2 -0
- package/dist/cli/chunks/schedule-44OSMGE5.js +2 -0
- package/dist/cli/chunks/scheduler-V3HO2QQT.js +2 -0
- package/dist/cli/chunks/security-EHXSW22U.js +18 -0
- package/dist/cli/chunks/{shared-rvf-adapter-LNRLFP5I.js → shared-rvf-adapter-6EH7UVJL.js} +2 -2
- package/dist/cli/chunks/{shared-rvf-dual-writer-GWU6YQNS.js → shared-rvf-dual-writer-WML274E7.js} +2 -2
- package/dist/cli/chunks/sqlite-persistence-N5T7DWMR.js +2 -0
- package/dist/cli/chunks/{standalone-memory-46KKBSSV.js → standalone-memory-C7QKAXS4.js} +2 -2
- package/dist/cli/chunks/{status-handler-35T5FTDQ.js → status-handler-VLI7MRLM.js} +2 -2
- package/dist/cli/chunks/{structural-health-P7QPQWLO.js → structural-health-3LPG6MQN.js} +2 -2
- package/dist/cli/chunks/{sync-Y43EWBSY.js → sync-4IMMQEPT.js} +2 -2
- package/dist/cli/chunks/{sync-W6Z4R4PL.js → sync-JFJEJBVK.js} +2 -2
- package/dist/cli/chunks/{task-handler-5CX3ZYT7.js → task-handler-IED3K6E4.js} +2 -2
- package/dist/cli/chunks/{task-handlers-DQZGOJNE.js → task-handlers-FH6DNTHW.js} +3 -3
- package/dist/cli/chunks/{test-TPP53VVV.js → test-GPKT3CKZ.js} +4 -4
- package/dist/cli/chunks/{test-scheduling-WBV4UMQH.js → test-scheduling-Z42XXZP6.js} +3 -3
- package/dist/cli/chunks/{token-bootstrap-GIIDXHLC.js → token-bootstrap-HMM3AHXM.js} +2 -2
- package/dist/cli/chunks/{token-usage-AKK37RB7.js → token-usage-6Y2ERYIY.js} +2 -2
- package/dist/cli/chunks/{transformers-7MASPELS.js → transformers-MB63T2XO.js} +2 -2
- package/dist/cli/chunks/{tree-sitter-wasm-parser-YZKD6UGB.js → tree-sitter-wasm-parser-56GDQCMR.js} +2 -2
- package/dist/cli/chunks/{types-AZ3BTXDP.js → types-J4J6QV3I.js} +2 -2
- package/dist/cli/chunks/unified-memory-RQ3Q4CU3.js +2 -0
- package/dist/cli/chunks/unified-memory-hnsw-ZOP5FEYX.js +2 -0
- package/dist/cli/chunks/unified-persistence-72OCJJKK.js +2 -0
- package/dist/cli/chunks/{upgrade-L7OTDKEK.js → upgrade-U4XU7LFM.js} +2 -2
- package/dist/cli/chunks/{validate-O3QVFIGP.js → validate-B57HA4YK.js} +2 -2
- package/dist/cli/chunks/{validate-swarm-2UGBGLTX.js → validate-swarm-UPPA4M6T.js} +2 -2
- package/dist/cli/chunks/visual-security-7F5UV23J.js +2 -0
- package/dist/cli/chunks/{web-tree-sitter-J75IYPRO.js → web-tree-sitter-GDZMUKOZ.js} +2 -2
- package/dist/cli/chunks/{windsurf-installer-FQ5DBFCG.js → windsurf-installer-VJRWCHXP.js} +2 -2
- package/dist/cli/chunks/witness-chain-KZ57QUFE.js +2 -0
- package/dist/cli/chunks/{witness-chain-I7TN4MXZ.js → witness-chain-LFASSMZK.js} +2 -2
- package/dist/cli/chunks/{witness-chain-repair-D3NE3NQK.js → witness-chain-repair-TPHN4DXN.js} +2 -2
- package/dist/cli/chunks/{witness-chain-verifier-RU2WOP5M.js → witness-chain-verifier-Z23FVABW.js} +2 -2
- package/dist/cli/chunks/{witness-key-manager-IHQB2FR5.js → witness-key-manager-745MJ7WO.js} +2 -2
- package/dist/cli/chunks/{workflow-6BWTNVV6.js → workflow-T245QNQM.js} +4 -4
- package/dist/cli/chunks/workflow-orchestrator-ZNWEUYBN.js +2 -0
- package/dist/cli/chunks/{wrappers-URVP25VU.js → wrappers-WCAYIQUX.js} +2 -2
- package/dist/cli/commands/learning.js +3 -2
- package/dist/cli/commands/security.d.ts +16 -0
- package/dist/cli/commands/security.js +76 -9
- package/dist/cli/handlers/init-guard.d.ts +21 -1
- package/dist/cli/handlers/init-guard.js +51 -8
- package/dist/cli/handlers/init-handler.js +57 -56
- package/dist/cli/index.js +11 -0
- package/dist/cli/utils/ci-output.d.ts +5 -0
- package/dist/cli/utils/ci-output.js +8 -0
- package/dist/coordination/handlers/security-handlers.js +22 -6
- package/dist/coordination/protocols/defect-investigation.js +7 -1
- package/dist/coordination/protocols/learning-consolidation.js +6 -12
- package/dist/coordination/protocols/security-audit.js +11 -0
- package/dist/coordination/result-saver.d.ts +9 -0
- package/dist/coordination/result-saver.js +34 -4
- package/dist/domains/coverage-analysis/collected-metrics.d.ts +2 -0
- package/dist/domains/coverage-analysis/collected-metrics.js +8 -1
- package/dist/domains/defect-intelligence/services/defect-predictor.js +9 -6
- package/dist/domains/learning-optimization/active-patterns.d.ts +55 -0
- package/dist/domains/learning-optimization/active-patterns.js +77 -0
- package/dist/domains/learning-optimization/coordinator.js +12 -9
- package/dist/domains/learning-optimization/services/learning-coordinator.js +15 -17
- package/dist/domains/quality-assessment/interfaces.d.ts +4 -0
- package/dist/domains/quality-assessment/quality-evidence.d.ts +1 -1
- package/dist/domains/quality-assessment/services/quality-analyzer.js +7 -5
- package/dist/domains/quality-assessment/services/quality-gate.js +12 -3
- package/dist/domains/security-compliance/dependency-advisory-engine.d.ts +52 -0
- package/dist/domains/security-compliance/dependency-advisory-engine.js +113 -0
- package/dist/domains/security-compliance/interfaces.d.ts +30 -0
- package/dist/domains/security-compliance/plugin.d.ts +7 -1
- package/dist/domains/security-compliance/plugin.js +19 -0
- package/dist/domains/security-compliance/services/scanners/dependency-resolver.d.ts +71 -0
- package/dist/domains/security-compliance/services/scanners/dependency-resolver.js +232 -0
- package/dist/domains/security-compliance/services/scanners/dependency-scanner.d.ts +21 -6
- package/dist/domains/security-compliance/services/scanners/dependency-scanner.js +142 -64
- package/dist/domains/security-compliance/services/scanners/lockfile-versions.d.ts +43 -0
- package/dist/domains/security-compliance/services/scanners/lockfile-versions.js +248 -0
- package/dist/domains/security-compliance/services/scanners/scanner-types.d.ts +30 -2
- package/dist/domains/security-compliance/services/security-auditor.d.ts +19 -6
- package/dist/domains/security-compliance/services/security-auditor.js +133 -92
- package/dist/domains/test-execution/services/retry-handler.js +34 -7
- package/dist/domains/test-execution/services/test-executor.d.ts +1 -0
- package/dist/domains/test-execution/services/test-executor.js +87 -7
- package/dist/kernel/shared-dirs.js +17 -5
- package/dist/learning/dream/dream-engine.d.ts +27 -1
- package/dist/learning/dream/dream-engine.js +56 -2
- package/dist/learning/dream/rvcow-branch-manager.d.ts +8 -0
- package/dist/learning/dream/rvcow-branch-manager.js +8 -0
- package/dist/learning/dream/speculative-dreamer.d.ts +8 -0
- package/dist/learning/dream/speculative-dreamer.js +8 -0
- package/dist/mcp/background-workers.d.ts +15 -0
- package/dist/mcp/background-workers.js +71 -0
- package/dist/mcp/bundle.js +881 -878
- package/dist/mcp/entry.js +4 -49
- package/dist/mcp/handlers/domain-handler-configs.d.ts +4 -0
- package/dist/mcp/handlers/domain-handler-configs.js +5 -1
- package/dist/mcp/protocol-server.js +2 -1
- package/dist/mcp/types.d.ts +6 -0
- package/dist/shared/security/index.d.ts +2 -2
- package/dist/shared/security/index.js +1 -1
- package/dist/shared/security/osv-client.d.ts +79 -132
- package/dist/shared/security/osv-client.js +344 -167
- package/dist/shared/security/osv-lookup.d.ts +124 -0
- package/dist/shared/security/osv-lookup.js +246 -0
- package/dist/shared/security/osv-types.d.ts +119 -0
- package/dist/shared/security/osv-types.js +6 -0
- package/dist/workers/daemon.d.ts +5 -0
- package/dist/workers/daemon.js +16 -2
- package/dist/workers/interfaces.d.ts +6 -1
- package/dist/workers/namespaced-keys.d.ts +16 -0
- package/dist/workers/namespaced-keys.js +24 -0
- package/dist/workers/quality-daemon/persistent-memory.d.ts +1 -1
- package/dist/workers/quality-daemon/persistent-memory.js +2 -2
- package/dist/workers/worker-env.d.ts +45 -0
- package/dist/workers/worker-env.js +76 -0
- package/dist/workers/worker-manager.js +5 -2
- package/dist/workers/workers/defect-predictor.d.ts +25 -8
- package/dist/workers/workers/defect-predictor.js +223 -216
- package/dist/workers/workers/learning-consolidation.d.ts +20 -0
- package/dist/workers/workers/learning-consolidation.js +53 -22
- package/dist/workers/workers/performance-baseline.d.ts +24 -9
- package/dist/workers/workers/performance-baseline.js +187 -230
- package/dist/workers/workers/quality-gate.d.ts +11 -9
- package/dist/workers/workers/quality-gate.js +125 -267
- package/dist/workers/workers/security-scan-records.d.ts +111 -0
- package/dist/workers/workers/security-scan-records.js +128 -0
- package/dist/workers/workers/security-scan.d.ts +25 -7
- package/dist/workers/workers/security-scan.js +187 -164
- package/package.json +2 -2
- package/dist/cli/chunks/adapter-PP3XIXDV.js +0 -2
- package/dist/cli/chunks/aqe-learning-engine-VDUQJKKY.js +0 -2
- package/dist/cli/chunks/base-QSYWWPCE.js +0 -2
- package/dist/cli/chunks/browser-workflow-WXXPBSCM.js +0 -2
- package/dist/cli/chunks/chunk-45MVRQG4.js +0 -2
- package/dist/cli/chunks/chunk-5VZVMO7B.js +0 -3
- package/dist/cli/chunks/chunk-EECF4CMA.js +0 -2
- package/dist/cli/chunks/client-6XKSQ4JT.js +0 -2
- package/dist/cli/chunks/core-handlers-OJYW4Y6M.js +0 -2
- package/dist/cli/chunks/cross-domain-router-QVUPQ2SC.js +0 -2
- package/dist/cli/chunks/daemon-QBYTCIMH.js +0 -10
- package/dist/cli/chunks/dream-3UABDRZJ.js +0 -2
- package/dist/cli/chunks/file-discovery-ZFGZTKZ4.js +0 -2
- package/dist/cli/chunks/heartbeat-scheduler-MJ6MTPDF.js +0 -2
- package/dist/cli/chunks/hnsw-adapter-FQWJCFVW.js +0 -2
- package/dist/cli/chunks/hnsw-index-NJYKJUHC.js +0 -2
- package/dist/cli/chunks/hybrid-backend-SL7RFID7.js +0 -2
- package/dist/cli/chunks/impact-analyzer-5ZJTXPVC.js +0 -2
- package/dist/cli/chunks/init-handler-PCLYQUSB.js +0 -88
- package/dist/cli/chunks/init-wizard-MQMDSIOF.js +0 -2
- package/dist/cli/chunks/kernel-MEJ5GMRH.js +0 -2
- package/dist/cli/chunks/knowledge-graph-XUBZSEZE.js +0 -2
- package/dist/cli/chunks/llm-router-service-QZAPAEPX.js +0 -2
- package/dist/cli/chunks/load-test-OVXIQ3AF.js +0 -2
- package/dist/cli/chunks/memory-backend-TRPOMPK4.js +0 -2
- package/dist/cli/chunks/pattern-null-store-JWYBRBZG.js +0 -2
- package/dist/cli/chunks/project-root-VVSTHIP4.js +0 -2
- package/dist/cli/chunks/protocol-executor-PXZCLZD3.js +0 -2
- package/dist/cli/chunks/qe-reasoning-bank-42FRS5V3.js +0 -2
- package/dist/cli/chunks/queen-coordinator-UI3B7DI6.js +0 -2
- package/dist/cli/chunks/router-HYRPWLAY.js +0 -2
- package/dist/cli/chunks/routing-feedback-BPZ5R6F3.js +0 -2
- package/dist/cli/chunks/rvf-dual-writer-DEKDQ6KO.js +0 -2
- package/dist/cli/chunks/rvf-migration-adapter-L53VBS7I.js +0 -2
- package/dist/cli/chunks/rvf-native-adapter-I6RUGD2D.js +0 -2
- package/dist/cli/chunks/safe-db-KS65XDCP.js +0 -2
- package/dist/cli/chunks/schedule-KD2VN6GB.js +0 -2
- package/dist/cli/chunks/scheduler-ZH3RMUHY.js +0 -2
- package/dist/cli/chunks/security-PWQTGDRU.js +0 -13
- package/dist/cli/chunks/sqlite-persistence-6DTVME5D.js +0 -2
- package/dist/cli/chunks/unified-memory-FCX7NLFZ.js +0 -2
- package/dist/cli/chunks/unified-memory-hnsw-VU5QJK37.js +0 -2
- package/dist/cli/chunks/unified-persistence-FM376LGE.js +0 -2
- package/dist/cli/chunks/visual-security-EU7Y3X46.js +0 -2
- package/dist/cli/chunks/witness-chain-CSEBT52D.js +0 -2
- package/dist/cli/chunks/workflow-orchestrator-ALNKOM3N.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{o as V,s as ae}from"./chunk-YNG7E26C.js";import{b as j,d as Me}from"./chunk-22OZIJAD.js";import{a as D,e as qe}from"./chunk-DQNUPEY5.js";import{a as S,b as Le,e as W}from"./chunk-KYVIOC3C.js";var We={continueGate:{enabled:!0,maxConsecutiveRetries:3,reworkRatioThreshold:.5,idleTimeoutMs:9e5,throttleOnExceed:!0},memoryWriteGate:{enabled:!0,contradictionDetection:!0,temporalDecayDays:30,minUsesForRetention:3,domainNamespacing:!0},trustAccumulator:{enabled:!0,performanceWeight:.5,taskSimilarityWeight:.3,capabilityMatchWeight:.2,minTrustForCritical:.7,autoTierAdjustment:!0},proofEnvelope:{enabled:!0,hashChaining:!0,auditLogRetentionDays:90,requireProofForClaims:!0,chainPersistence:!1,maxChainLength:1e4,signAllEnvelopes:!0},budgetMeter:{enabled:!0,maxSessionCostUsd:50,maxTokensPerSession:1e6,warningThresholdPercent:80},deterministicGateway:{enabled:!0,deduplicationWindowMs:5e3,cacheResultsForIdempotent:!0,validateSchemas:!0},evolutionPipeline:{enabled:!0,autoPromoteThreshold:.9,autoDemoteThreshold:.3,minSamplesForDecision:20,learningRate:.1},shardRetriever:{enabled:!0,shardsPath:".claude/guidance/shards",cacheEnabled:!0,cacheTtlMs:3e5,maxShardsPerQuery:3,relevanceThreshold:.3},abBenchmarking:{enabled:!0,defaultConfidenceLevel:.95,defaultMinSampleSize:100,autoApplyWinners:!1,maxConcurrentBenchmarks:5},shardEmbeddings:{enabled:!0,embeddingDimensions:384,persistEmbeddings:!1,autoRebuildOnChange:!0,ngramMin:2,ngramMax:4,persistPath:".agentic-qe/shard-embeddings.json"},adversarialDefense:{enabled:!0,blockThreshold:.7,sanitizeInputs:!0,penalizeOnDetection:!0,logDetections:!0},complianceReporter:{enabled:!0,autoRecordViolations:!0,retentionDays:90,alertOnCritical:!0,generateDailyReport:!1},constitutionalEnforcer:{enabled:!0,strictEnforcement:!1,escalateViolations:!0,constitutionPath:".claude/guidance/constitution.md",logAllChecks:!0},global:{enableAllGates:!0,strictMode:!1,logViolations:!0,escalateToQueen:!0}};function je(){let c=process.env;return{continueGate:{enabled:c.GOVERNANCE_CONTINUE_GATE!=="false",maxConsecutiveRetries:parseInt(c.GOVERNANCE_MAX_RETRIES||"3",10),reworkRatioThreshold:parseFloat(c.GOVERNANCE_REWORK_THRESHOLD||"0.5"),idleTimeoutMs:parseInt(c.GOVERNANCE_IDLE_TIMEOUT||"900000",10),throttleOnExceed:c.GOVERNANCE_THROTTLE!=="false"},memoryWriteGate:{enabled:c.GOVERNANCE_MEMORY_GATE!=="false",contradictionDetection:c.GOVERNANCE_CONTRADICTION_CHECK!=="false",temporalDecayDays:parseInt(c.GOVERNANCE_DECAY_DAYS||"30",10),minUsesForRetention:parseInt(c.GOVERNANCE_MIN_USES||"3",10),domainNamespacing:c.GOVERNANCE_DOMAIN_NS!=="false"},trustAccumulator:{enabled:c.GOVERNANCE_TRUST!=="false",performanceWeight:parseFloat(c.GOVERNANCE_PERF_WEIGHT||"0.5"),taskSimilarityWeight:parseFloat(c.GOVERNANCE_SIMILARITY_WEIGHT||"0.3"),capabilityMatchWeight:parseFloat(c.GOVERNANCE_CAPABILITY_WEIGHT||"0.2"),minTrustForCritical:parseFloat(c.GOVERNANCE_MIN_TRUST||"0.7"),autoTierAdjustment:c.GOVERNANCE_AUTO_TIER!=="false"},proofEnvelope:{enabled:c.GOVERNANCE_PROOF!=="false",hashChaining:c.GOVERNANCE_HASH_CHAIN!=="false",auditLogRetentionDays:parseInt(c.GOVERNANCE_AUDIT_DAYS||"90",10),requireProofForClaims:c.GOVERNANCE_REQUIRE_PROOF!=="false",chainPersistence:c.GOVERNANCE_CHAIN_PERSIST==="true",maxChainLength:parseInt(c.GOVERNANCE_MAX_CHAIN_LENGTH||"10000",10),signAllEnvelopes:c.GOVERNANCE_SIGN_ALL!=="false"},budgetMeter:{enabled:c.GOVERNANCE_BUDGET!=="false",maxSessionCostUsd:parseFloat(c.GOVERNANCE_MAX_COST||"50"),maxTokensPerSession:parseInt(c.GOVERNANCE_MAX_TOKENS||"1000000",10),warningThresholdPercent:parseInt(c.GOVERNANCE_WARNING_PERCENT||"80",10)},deterministicGateway:{enabled:c.GOVERNANCE_DETERMINISTIC!=="false",deduplicationWindowMs:parseInt(c.GOVERNANCE_DEDUP_WINDOW||"5000",10),cacheResultsForIdempotent:c.GOVERNANCE_CACHE_IDEMPOTENT!=="false",validateSchemas:c.GOVERNANCE_VALIDATE_SCHEMAS!=="false"},evolutionPipeline:{enabled:c.GOVERNANCE_EVOLUTION!=="false",autoPromoteThreshold:parseFloat(c.GOVERNANCE_PROMOTE_THRESHOLD||"0.9"),autoDemoteThreshold:parseFloat(c.GOVERNANCE_DEMOTE_THRESHOLD||"0.3"),minSamplesForDecision:parseInt(c.GOVERNANCE_MIN_SAMPLES||"20",10),learningRate:parseFloat(c.GOVERNANCE_LEARNING_RATE||"0.1")},shardRetriever:{enabled:c.GOVERNANCE_SHARD_RETRIEVER!=="false",shardsPath:c.GOVERNANCE_SHARDS_PATH||".claude/guidance/shards",cacheEnabled:c.GOVERNANCE_SHARD_CACHE!=="false",cacheTtlMs:parseInt(c.GOVERNANCE_SHARD_CACHE_TTL||"300000",10),maxShardsPerQuery:parseInt(c.GOVERNANCE_MAX_SHARDS||"3",10),relevanceThreshold:parseFloat(c.GOVERNANCE_RELEVANCE_THRESHOLD||"0.3")},abBenchmarking:{enabled:c.GOVERNANCE_AB_BENCHMARKING!=="false",defaultConfidenceLevel:parseFloat(c.GOVERNANCE_AB_CONFIDENCE||"0.95"),defaultMinSampleSize:parseInt(c.GOVERNANCE_AB_MIN_SAMPLES||"100",10),autoApplyWinners:c.GOVERNANCE_AB_AUTO_APPLY==="true",maxConcurrentBenchmarks:parseInt(c.GOVERNANCE_AB_MAX_CONCURRENT||"5",10)},shardEmbeddings:{enabled:c.GOVERNANCE_SHARD_EMBEDDINGS!=="false",embeddingDimensions:parseInt(c.GOVERNANCE_EMBEDDING_DIMENSIONS||"384",10),persistEmbeddings:c.GOVERNANCE_PERSIST_EMBEDDINGS==="true",autoRebuildOnChange:c.GOVERNANCE_AUTO_REBUILD!=="false",ngramMin:parseInt(c.GOVERNANCE_NGRAM_MIN||"2",10),ngramMax:parseInt(c.GOVERNANCE_NGRAM_MAX||"4",10),persistPath:c.GOVERNANCE_EMBEDDINGS_PATH||".agentic-qe/shard-embeddings.json"},adversarialDefense:{enabled:c.GOVERNANCE_ADVERSARIAL_DEFENSE!=="false",blockThreshold:parseFloat(c.GOVERNANCE_BLOCK_THRESHOLD||"0.7"),sanitizeInputs:c.GOVERNANCE_SANITIZE_INPUTS!=="false",penalizeOnDetection:c.GOVERNANCE_PENALIZE_DETECTION!=="false",logDetections:c.GOVERNANCE_LOG_DETECTIONS!=="false"},complianceReporter:{enabled:c.GOVERNANCE_COMPLIANCE_REPORTER!=="false",autoRecordViolations:c.GOVERNANCE_AUTO_RECORD_VIOLATIONS!=="false",retentionDays:parseInt(c.GOVERNANCE_VIOLATION_RETENTION_DAYS||"90",10),alertOnCritical:c.GOVERNANCE_ALERT_ON_CRITICAL!=="false",generateDailyReport:c.GOVERNANCE_DAILY_REPORT==="true"},constitutionalEnforcer:{enabled:c.GOVERNANCE_CONSTITUTIONAL_ENFORCER!=="false",strictEnforcement:c.GOVERNANCE_CONSTITUTIONAL_STRICT==="true",escalateViolations:c.GOVERNANCE_CONSTITUTIONAL_ESCALATE!=="false",constitutionPath:c.GOVERNANCE_CONSTITUTION_PATH||".claude/guidance/constitution.md",logAllChecks:c.GOVERNANCE_CONSTITUTIONAL_LOG!=="false"},global:{enableAllGates:c.GOVERNANCE_ENABLED!=="false",strictMode:c.GOVERNANCE_STRICT==="true",logViolations:c.GOVERNANCE_LOG_VIOLATIONS!=="false",escalateToQueen:c.GOVERNANCE_ESCALATE!=="false"}}}function oe(c=We,e=je(),t={}){let n=(i,r)=>{let s={...i};for(let a in r)r[a]!==void 0&&(typeof r[a]=="object"&&!Array.isArray(r[a])?s[a]=n(i[a],r[a]):s[a]=r[a]);return s};return n(n(c,e),t)}var xe=class{flags;listeners=new Set;constructor(){this.flags=oe()}getFlags(){return this.flags}isGateEnabled(e){return this.flags.global.enableAllGates?this.flags[e].enabled:!1}updateFlags(e){this.flags=oe(this.flags,{},e),this.notifyListeners()}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}notifyListeners(){this.listeners.forEach(e=>e(this.flags))}reset(){this.flags=oe(),this.notifyListeners()}enableStrictMode(){this.updateFlags({global:{...this.flags.global,strictMode:!0}})}disableAllGates(){this.updateFlags({global:{...this.flags.global,enableAllGates:!1}})}},h=new xe,G=()=>h.isGateEnabled("continueGate"),U=()=>h.isGateEnabled("memoryWriteGate"),M=()=>h.isGateEnabled("trustAccumulator");var ce=()=>h.isGateEnabled("budgetMeter"),le=()=>h.isGateEnabled("deterministicGateway");var E=()=>h.isGateEnabled("adversarialDefense"),x=()=>h.isGateEnabled("complianceReporter"),K=()=>h.isGateEnabled("constitutionalEnforcer"),v=()=>h.getFlags().global.strictMode;var Ie=class{patternIndex=new Map;domainPatterns=new Map;guidanceMemoryGate=null;initialized=!1;async initialize(){if(!this.initialized){try{let t=await import("@claude-flow/guidance/memory-gate");t&&typeof t.createMemoryWriteGate=="function"&&(this.guidanceMemoryGate=t.createMemoryWriteGate({enableContradictionTracking:!0}),console.log("[MemoryWriteGateIntegration] Guidance MemoryWriteGate loaded"))}catch{this.guidanceMemoryGate=null}this.initialized=!0}}async evaluateWrite(e){if(!U())return{allowed:!0};await this.initialize();let t=h.getFlags().memoryWriteGate;e.timestamp=e.timestamp||Date.now(),e.useCount=e.useCount||0;let n=this.localEvaluation(e,t);if(this.guidanceMemoryGate&&n.allowed&&!n.reason)try{let i={agentId:e.agentId||"unknown",role:"worker",namespaces:[e.domain],maxWritesPerMinute:60,canDelete:!1,canOverwrite:!0,trustLevel:.7},r=this.guidanceMemoryGate.evaluateWrite(i,e.key,e.domain,e.value);if(!r.allowed)return this.mapGuidanceDecision(r)}catch{}return n}localEvaluation(e,t){if(t.domainNamespacing&&e.agentId){let n=this.getAllowedDomainsForAgent(e.agentId);if(!n.includes(e.domain)&&!n.includes("*"))return this.logViolation(e,"domain_violation",`Agent ${e.agentId} cannot write to domain ${e.domain}`),{allowed:!v(),reason:`Agent ${e.agentId} not authorized to write to domain ${e.domain}`,requiresManualReview:!0}}if(t.contradictionDetection){let n=this.findConflictingPatterns(e);if(n.length>0)return n.every(r=>e.supersedes?.includes(r.key))?{allowed:!0,conflictingPatterns:n,suggestedResolution:"supersede"}:(this.logViolation(e,"contradiction",`Conflicts with ${n.length} existing pattern(s)`),{allowed:!v(),reason:`Pattern conflicts with ${n.length} existing pattern(s)`,conflictingPatterns:n,suggestedResolution:this.suggestResolution(e,n),requiresManualReview:n.some(r=>(r.useCount||0)>5)})}return{allowed:!0}}findConflictingPatterns(e){let t=this.domainPatterns.get(e.domain);if(!t)return[];let n=[];for(let i of t){let r=this.patternIndex.get(i);!r||r.key===e.key||this.areContradictory(e,r)&&n.push(r)}return n}areContradictory(e,t){if(e.key===t.key)return!1;let n=JSON.stringify(e.value).toLowerCase(),i=JSON.stringify(t.value).toLowerCase(),r=[{positive:"should",negative:"should not"},{positive:"always",negative:"never"},{positive:"enabled",negative:"disabled"},{positive:"true",negative:"false"},{positive:"allow",negative:"deny"},{positive:"include",negative:"exclude"}];for(let s of r)if(n.includes(s.positive)&&i.includes(s.negative)||n.includes(s.negative)&&i.includes(s.positive)){let a=new Set(n.match(/\b\w{4,}\b/g)||[]),o=new Set(i.match(/\b\w{4,}\b/g)||[]);if([...a].filter(u=>o.has(u)).length>=2)return!0}return!!(e.tags&&t.tags&&e.tags.filter(a=>t.tags?.includes(a)).length>0&&e.value!==t.value)}suggestResolution(e,t){let n=e.timestamp||0,i=Math.min(...t.map(r=>r.timestamp||0));return n-i>10080*60*1e3?"supersede":t.some(r=>(r.useCount||0)>10)?"reject":"merge"}getAllowedDomainsForAgent(e){return{"qe-test-architect":["test-generation","learning-optimization"],"qe-coverage-specialist":["coverage-analysis","learning-optimization"],"qe-security-scanner":["security-compliance"],"qe-chaos-engineer":["chaos-resilience"],"qe-defect-predictor":["defect-intelligence","learning-optimization"],"qe-learning-coordinator":["*"],"qe-quality-gate":["quality-assessment"],"qe-parallel-executor":["test-execution"],"qe-contract-validator":["contract-testing"],"qe-accessibility-auditor":["visual-accessibility"],"qe-requirements-validator":["requirements-validation"],"qe-code-intelligence":["code-intelligence"]}[e]||[e.split("-").pop()||"unknown"]}getExistingPatterns(e){let t=this.domainPatterns.get(e);return t?[...t].map(n=>this.patternIndex.get(n)).filter(n=>n!==void 0):[]}mapGuidanceDecision(e){return{allowed:e.allowed,reason:e.reason,requiresManualReview:!e.authorityCheck.passed||e.contradictions.length>0,suggestedResolution:e.contradictions.length>0?"reject":void 0}}logViolation(e,t,n){h.getFlags().global.logViolations&&console.warn("[MemoryWriteGate] Violation detected:",{patternKey:e.key,domain:e.domain,violationType:t,details:n,timestamp:new Date().toISOString()})}registerPattern(e){this.patternIndex.set(e.key,e),this.domainPatterns.has(e.domain)||this.domainPatterns.set(e.domain,new Set),this.domainPatterns.get(e.domain).add(e.key)}unregisterPattern(e){let t=this.patternIndex.get(e);t&&(this.domainPatterns.get(t.domain)?.delete(e),this.patternIndex.delete(e))}incrementUseCount(e){let t=this.patternIndex.get(e);t&&(t.useCount=(t.useCount||0)+1)}async applyTemporalDecay(){let e=h.getFlags().memoryWriteGate,t=e.temporalDecayDays*24*60*60*1e3,n=Date.now(),i=[];for(let[r,s]of this.patternIndex){let a=n-(s.timestamp||0),o=s.useCount||0;a>t&&o<e.minUsesForRetention&&(i.push(r),this.unregisterPattern(r))}return i.length>0&&console.info(`[MemoryWriteGate] Archived ${i.length} patterns due to temporal decay`),i}getStats(){let e={};for(let[t,n]of this.domainPatterns)e[t]=n.size;return{totalPatterns:this.patternIndex.size,patternsByDomain:e}}reset(){this.patternIndex.clear(),this.domainPatterns.clear()}loadPatternsFromBank(e){for(let t of e)this.registerPattern(t)}},Q=new Ie;function Pe(c,e,t,n={}){return{key:c,value:e,domain:t,timestamp:Date.now(),useCount:0,...n}}import{randomUUID as Ke}from"node:crypto";Me();import{randomUUID as ut,createHash as dt}from"node:crypto";W();Me();import{createHash as ct,createHmac as lt}from"node:crypto";var De=class{kernel=null;initialized=!1;initError=null;metrics={backend:"js",avgHashTimeMs:0,totalOperations:0,totalTimeMs:0,operationCounts:{hash:0,hashChain:0,verify:0,hmac:0}};async initialize(){if(!this.initialized){try{let t=await import("@claude-flow/guidance/wasm-kernel");t&&typeof t.getKernel=="function"&&(this.kernel=t.getKernel(),this.metrics.backend=this.kernel?.available?"wasm":"js")}catch(e){this.initError=Le(e),this.kernel=null,this.metrics.backend="js"}this.initialized=!0}}isWasmAvailable(){return this.kernel?.available??!1}getVersion(){return this.kernel?.version??"js-fallback"}getInitError(){return this.initError}hash(e){let t=performance.now(),n;if(this.kernel?.available){let i=typeof e=="string"?e:Buffer.from(e).toString("utf-8");n=this.kernel.sha256(i)}else n=this.jsHash(e);return this.recordOperation("hash",performance.now()-t),n}hmac(e,t){let n=performance.now(),i;return this.kernel?.available?i=this.kernel.hmacSha256(e,t):i=lt("sha256",e).update(t).digest("hex"),this.recordOperation("hmac",performance.now()-n),i}hashChain(e){let t=performance.now();if(e.length===0)return this.recordOperation("hashChain",performance.now()-t),this.hash("");if(e.length===1)return this.recordOperation("hashChain",performance.now()-t),e[0];let n=e[0];for(let i=1;i<e.length;i++)n=this.hash(n+e[i]);return this.recordOperation("hashChain",performance.now()-t),n}verify(e,t){let n=performance.now(),r=this.hash(e)===t;return this.recordOperation("verify",performance.now()-n),r}contentHash(e){let t=performance.now(),n,i=typeof e=="string"?e:JSON.stringify(e);return this.kernel?.available?n=this.kernel.contentHash(i):n=this.jsContentHash(i),this.recordOperation("hash",performance.now()-t),n}signEnvelope(e,t){let n=JSON.stringify(t);return this.kernel?.available?this.kernel.signEnvelope(e,n):this.hmac(e,n)}getPerformanceMetrics(){return{...this.metrics}}resetMetrics(){this.metrics={backend:this.kernel?.available?"wasm":"js",avgHashTimeMs:0,totalOperations:0,totalTimeMs:0,operationCounts:{hash:0,hashChain:0,verify:0,hmac:0}}}reset(){this.kernel=null,this.initialized=!1,this.initError=null,this.resetMetrics()}jsHash(e){let t=ct("sha256");return typeof e=="string"?t.update(e):t.update(Buffer.from(e)),t.digest("hex")}jsContentHash(e){try{let t=j(e),n=this.sortKeys(t);return this.jsHash(JSON.stringify(n))}catch{return this.jsHash(e)}}sortKeys(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>this.sortKeys(n));let t={};for(let n of Object.keys(e).sort())t[n]=this.sortKeys(e[n]);return t}recordOperation(e,t){this.metrics.totalOperations++,this.metrics.totalTimeMs+=t,this.metrics.operationCounts[e]++,this.metrics.avgHashTimeMs=this.metrics.totalTimeMs/this.metrics.totalOperations}},Ue=new De;qe();var te="0".repeat(64),ue=class{kernel;chain=[];signingKey="";guidanceProofChain=null;initialized=!1;envelopeIndex=new Map;constructor(e){this.kernel=e??Ue}async initialize(e){if(!this.initialized){await this.kernel.initialize(),this.signingKey=e||dt("sha256").update(`aqe-proof-envelope:${process.cwd()}`).digest("hex");try{let n=await import("@claude-flow/guidance/proof");n&&typeof n.createProofChain=="function"&&(this.guidanceProofChain=n.createProofChain({signingKey:this.signingKey}),console.log("[ProofEnvelopeIntegration] Guidance ProofChain loaded"))}catch{this.guidanceProofChain=null}this.initialized=!0}}isInitialized(){return this.initialized}getFlags(){return h.getFlags().proofEnvelope}createEnvelope(e,t,n,i){let r=this.generateEnvelopeId(),s=Date.now(),a=this.chain.length>0?this.chain[this.chain.length-1].contentHash:te,o={id:r,timestamp:s,agentId:e,action:t,payload:n,metadata:i},l=this.kernel.contentHash(o);return{id:r,timestamp:s,agentId:e,action:t,payload:n,contentHash:l,previousHash:a,signature:"",metadata:i}}signEnvelope(e,t){let n=t??this.signingKey,i=`${e.contentHash}:${e.previousHash}`,r=this.kernel.hmac(n,i);return{...e,signature:r}}createSignedEnvelope(e,t,n,i){let r=this.createEnvelope(e,t,n,i);return this.signEnvelope(r)}appendToChain(e){let t=this.verifyEnvelope(e);if(!t.valid)throw new Error(`Cannot append invalid envelope: ${t.error}`);let n=this.chain.length>0?this.chain[this.chain.length-1].contentHash:te;if(e.previousHash!==n)throw new Error(`Envelope does not link to chain. Expected previous hash ${n}, got ${e.previousHash}`);let i=this.chain.length;if(this.chain.push(e),this.envelopeIndex.set(e.id,i),this.guidanceProofChain)try{let r={eventId:e.id,taskId:e.metadata?.taskId?String(e.metadata.taskId):e.id,guidanceHash:e.contentHash,retrievedRuleIds:[],toolsUsed:e.action?[e.action]:[],filesTouched:[],diffSummary:{linesAdded:0,linesRemoved:0,filesChanged:0},testResults:{passed:0,failed:0,skipped:0},metrics:{},timestamp:new Date(e.timestamp).toISOString()};this.guidanceProofChain.append(r,[],[],{agentId:e.agentId,sessionId:e.metadata?.sessionId?String(e.metadata.sessionId):"aqe"})}catch{}}getChain(){return[...this.chain]}getChainLength(){return this.chain.length}getLastEnvelope(){return this.chain.length===0?null:this.chain[this.chain.length-1]}clearChain(){this.chain=[],this.envelopeIndex.clear()}verifyEnvelope(e,t){let n=t??this.signingKey,i={contentHashValid:!1,signatureValid:!1,chainLinkValid:!0},r={id:e.id,timestamp:e.timestamp,agentId:e.agentId,action:e.action,payload:e.payload,metadata:e.metadata},s=this.kernel.contentHash(r);if(i.contentHashValid=e.contentHash===s,!i.contentHashValid)return{valid:!1,details:i,error:"Content hash does not match envelope content"};let a=`${e.contentHash}:${e.previousHash}`,o=this.kernel.hmac(n,a);if(i.signatureValid=e.signature===o,!i.signatureValid)return{valid:!1,details:i,error:"Signature verification failed"};let l=this.envelopeIndex.get(e.id);if(l!==void 0&&l>0){let u=this.chain[l-1];if(i.chainLinkValid=e.previousHash===u.contentHash,!i.chainLinkValid)return{valid:!1,details:i,error:"Chain link is broken - previous hash does not match"}}return{valid:!0,details:i}}verifyChain(e){let t=[],n=-1;for(let i=0;i<this.chain.length;i++){let r=this.chain[i],s=this.verifyEnvelope(r,e);s.valid||(t.push({index:i,envelopeId:r.id,error:s.error??"Unknown error"}),n===-1&&(n=i));let a=i>0?this.chain[i-1].contentHash:te;r.previousHash!==a&&(t.push({index:i,envelopeId:r.id,error:`Chain link broken at index ${i}`}),n===-1&&(n=i))}return{valid:t.length===0,envelopesVerified:this.chain.length,firstInvalidIndex:n,merkleRoot:this.computeMerkleRoot(),errors:t}}detectTampering(){let e=[],t=[];for(let n=0;n<this.chain.length;n++){let i=this.chain[n],r={id:i.id,timestamp:i.timestamp,agentId:i.agentId,action:i.action,payload:i.payload,metadata:i.metadata},s=this.kernel.contentHash(r);i.contentHash!==s&&(t.push(n),e.push({index:n,envelopeId:i.id,issue:"Content hash mismatch - envelope content was modified"}));let a=n>0?this.chain[n-1].contentHash:te;i.previousHash!==a&&(t.includes(n)||t.push(n),e.push({index:n,envelopeId:i.id,issue:"Chain link broken - previous hash does not match"}))}return{tampered:t.length>0,tamperedIndices:t,details:e}}getEnvelopeById(e){let t=this.envelopeIndex.get(e);return t===void 0?null:this.chain[t]}getEnvelopesByAgent(e){return this.chain.filter(t=>t.agentId===e)}getEnvelopesByAction(e){return this.chain.filter(t=>t.action===e)}getEnvelopesSince(e){return this.chain.filter(t=>t.timestamp>=e)}getEnvelopesInRange(e,t){return this.chain.filter(n=>n.timestamp>=e&&n.timestamp<=t)}exportChain(e){let t={version:1,exportedAt:Date.now(),chainLength:this.chain.length,merkleRoot:this.computeMerkleRoot(),envelopes:this.chain};if(e==="json")return JSON.stringify(t,null,2);let n=JSON.stringify(t);return new TextEncoder().encode(n)}importChain(e,t=!0){let n;typeof e=="string"?n=e:n=new TextDecoder().decode(e);let i=j(n);if(!i.envelopes||!Array.isArray(i.envelopes))throw new Error("Invalid chain data: missing envelopes array");this.clearChain();for(let r of i.envelopes){let s=this.chain.length;this.chain.push(r),this.envelopeIndex.set(r.id,s)}if(t){let r=this.verifyChain();if(!r.valid)throw this.clearChain(),new Error(`Imported chain failed verification: ${r.errors[0]?.error}`)}}getProofStats(){let e=D(),t=new Set;for(let i of this.chain)t.add(i.agentId),e[i.action]=(e[i.action]||0)+1;let n=this.chain.length===0||this.verifyChain().valid;return{chainLength:this.chain.length,firstTimestamp:this.chain.length>0?this.chain[0].timestamp:null,lastTimestamp:this.chain.length>0?this.chain[this.chain.length-1].timestamp:null,uniqueAgents:Array.from(t),actionCounts:e,merkleRoot:this.computeMerkleRoot(),chainValid:n}}computeMerkleRoot(){if(this.chain.length===0)return te;let e=this.chain.map(t=>t.contentHash);for(;e.length>1;){let t=[];for(let n=0;n<e.length;n+=2)n+1<e.length?t.push(this.kernel.hash(e[n]+e[n+1])):t.push(e[n]);e=t}return e[0]}getMerkleProof(e){let t=this.envelopeIndex.get(e);if(t===void 0)return null;let n=[],i=this.chain.map(s=>s.contentHash),r=t;for(;i.length>1;){let s=r%2===0?r+1:r-1;s<i.length&&n.push(i[s]);let a=[];for(let o=0;o<i.length;o+=2)o+1<i.length?a.push(this.kernel.hash(i[o]+i[o+1])):a.push(i[o]);i=a,r=Math.floor(r/2)}return n}verifyMerkleProof(e,t,n){let i=e,r=n;for(let s of t)r%2===0?i=this.kernel.hash(i+s):i=this.kernel.hash(s+i),r=Math.floor(r/2);return i===this.computeMerkleRoot()}generateEnvelopeId(){return`env_${ut()}`}reset(){this.chain=[],this.envelopeIndex.clear(),this.signingKey="",this.initialized=!1}},Ve=new ue;ae();W();qe();var Je={enabled:!0,autoRecordViolations:!0,retentionDays:90,alertOnCritical:!0,generateDailyReport:!1},mt={low:1,medium:3,high:7,critical:15},Qe=100,ht=.5,J=5,de=class c{violations=new Map;alertThresholds=new Map;proofIntegration;flags;initialized=!1;scoreHistory=[];alertListeners=new Set;db=null;persistCount=0;static NAMESPACE="compliance-audit";static TTL_SECONDS=2592e3;static PERSIST_INTERVAL=10;constructor(e,t){this.proofIntegration=e??Ve,this.flags={...Je,...t}}async initialize(){if(!this.initialized){try{this.db=V(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(e){console.warn("[ComplianceReporter] DB init failed, using memory-only:",S(e)),this.db=null}this.proofIntegration.isInitialized()||await this.proofIntegration.initialize(),this.alertThresholds.set("continueGate",70),this.alertThresholds.set("memoryWriteGate",70),this.alertThresholds.set("trustAccumulator",70),this.alertThresholds.set("budgetMeter",60),this.alertThresholds.set("adversarialDefense",80),this.initialized=!0}}isInitialized(){return this.initialized}getFlags(){return{...this.flags}}updateFlags(e){this.flags={...this.flags,...e}}recordViolation(e){let t=this.generateViolationId(),n=Date.now(),i={...e,id:t,timestamp:n,resolved:!1};if(this.violations.set(t,i),h.getFlags().proofEnvelope.enabled)try{let r=this.proofIntegration.createSignedEnvelope(e.agentId??"system","violation_recorded",{violationId:t,type:e.type,severity:e.severity,gate:e.gate,description:e.description});this.proofIntegration.appendToChain(r),i.proofEnvelopeId=r.id}catch{}return this.flags.alertOnCritical&&e.severity==="critical"&&this.triggerAlert(e.gate,"Critical violation detected","critical"),this.persistSnapshot(),this.cleanupOldViolations(),t}resolveViolation(e,t){let n=this.violations.get(e);if(!n)throw new Error(`Violation not found: ${e}`);if(n.resolved=!0,n.resolution=t,n.resolvedAt=Date.now(),h.getFlags().proofEnvelope.enabled)try{let i=this.proofIntegration.createSignedEnvelope(n.agentId??"system","violation_resolved",{violationId:e,resolution:t});this.proofIntegration.appendToChain(i)}catch{}}getViolation(e){return this.violations.get(e)??null}getViolations(e){let t=Array.from(this.violations.values());return e&&(e.type!==void 0&&(t=t.filter(n=>n.type===e.type)),e.severity!==void 0&&(t=t.filter(n=>n.severity===e.severity)),e.agentId!==void 0&&(t=t.filter(n=>n.agentId===e.agentId)),e.gate!==void 0&&(t=t.filter(n=>n.gate===e.gate)),e.resolved!==void 0&&(t=t.filter(n=>n.resolved===e.resolved)),e.startTime!==void 0&&(t=t.filter(n=>n.timestamp>=e.startTime)),e.endTime!==void 0&&(t=t.filter(n=>n.timestamp<=e.endTime)),e.limit!==void 0&&(t=t.slice(0,e.limit))),t.sort((n,i)=>i.timestamp-n.timestamp)}calculateScore(e){let t=Date.now(),n=e??{start:t-1440*60*1e3,end:t},i=this.getViolations({startTime:n.start,endTime:n.end}),r=this.calculateOverallScore(i),s=D(),a=this.groupBy(i,"gate");for(let[g,p]of Object.entries(a))s[g]=this.calculateOverallScore(p);let o=D(),l=this.groupBy(i,"agentId");for(let[g,p]of Object.entries(l))g!=="undefined"&&(o[g]=this.calculateOverallScore(p));let u=this.calculateTrend(n),d=i.filter(g=>g.resolved).length,m={overall:r,byGate:s,byAgent:o,trend:u,period:n,totalViolations:i.length,resolvedViolations:d};return this.scoreHistory.push(m),this.scoreHistory.length>100&&this.scoreHistory.shift(),m}getScoreHistory(e){return this.scoreHistory.slice(-e)}generateReport(e={}){let t=Date.now(),n=e.timeWindow??{start:t-1440*60*1e3,end:t},i=this.getViolations({startTime:n.start,endTime:n.end}),r=this.calculateScore(n),s={loop_detected:0,contradiction:0,trust_violation:0,budget_exceeded:0,adversarial_detected:0,invariant_violated:0,unauthorized_access:0,chain_tampered:0,schema_violation:0,rate_limit_exceeded:0};for(let g of i)s[g.type]++;let a={low:0,medium:0,high:0,critical:0};for(let g of i)a[g.severity]++;let o={},l=this.groupBy(i,"gate");for(let[g,p]of Object.entries(l))o[g]={score:this.calculateOverallScore(p),violations:p.length,trend:this.calculateGateTrend(g,n)};let u=i.filter(g=>g.resolved).length,d=i.length>0?u/i.length:1,m={generatedAt:t,timeWindow:n,summary:{overallScore:r.overall,totalViolations:i.length,criticalViolations:a.critical,highViolations:a.high,resolvedViolations:u,resolutionRate:d,trend:r.trend},gateScores:o,violationsByType:s,violationsBySeverity:a};if(e.includeAgentRankings){let g=this.groupBy(i,"agentId");m.agentRankings=Object.entries(g).filter(([p])=>p!=="undefined").map(([p,b])=>({agentId:p,score:this.calculateOverallScore(b),violations:b.length,trend:this.calculateAgentTrend(p,n)})).sort((p,b)=>b.score-p.score)}if(e.includeViolations){let g=e.maxViolations??50;m.violations=i.slice(0,g)}return e.includeRecommendations&&(m.recommendations=this.generateRecommendations(i,r)),e.includeTrendAnalysis&&(m.trendAnalysis=this.calculateTrendAnalysis(n)),m}exportReport(e,t){return t==="json"?JSON.stringify(e,null,2):this.generateMarkdownReport(e)}attachProof(e,t){let n=this.violations.get(e);if(!n)throw new Error(`Violation not found: ${e}`);if(!this.proofIntegration.getEnvelopeById(t))throw new Error(`Proof envelope not found: ${t}`);n.proofEnvelopeId=t}getViolationsWithProof(){return Array.from(this.violations.values()).filter(e=>e.proofEnvelopeId!==void 0)}getViolationProof(e){let t=this.violations.get(e);return t?.proofEnvelopeId?this.proofIntegration.getEnvelopeById(t.proofEnvelopeId):null}setAlertThreshold(e,t){if(t<0||t>100)throw new Error("Threshold must be between 0 and 100");this.alertThresholds.set(e,t)}getAlertThreshold(e){return this.alertThresholds.get(e)}checkAlerts(){let e=[],t=this.calculateScore();for(let[n,i]of this.alertThresholds){let r=t.byGate[n];if(r!==void 0&&r<i){let s={id:this.generateAlertId(),gate:n,message:`Compliance score for ${n} (${r.toFixed(1)}) dropped below threshold (${i})`,severity:r<i*.5?"critical":"high",timestamp:Date.now(),currentScore:r,threshold:i};e.push(s),this.notifyAlertListeners(s)}}return e}onAlert(e){return this.alertListeners.add(e),()=>this.alertListeners.delete(e)}getComplianceStats(){let e=Array.from(this.violations.values()),t=e.filter(d=>d.resolved),n={loop_detected:0,contradiction:0,trust_violation:0,budget_exceeded:0,adversarial_detected:0,invariant_violated:0,unauthorized_access:0,chain_tampered:0,schema_violation:0,rate_limit_exceeded:0};for(let d of e)n[d.type]++;let i={low:0,medium:0,high:0,critical:0};for(let d of e)i[d.severity]++;let r=D();for(let d of e)r[d.gate]=(r[d.gate]||0)+1;let s=D();for(let d of e)d.agentId&&(s[d.agentId]=(s[d.agentId]||0)+1);let a=0,o=0;for(let d of t)d.resolvedAt&&(a+=d.resolvedAt-d.timestamp,o++);let l=o>0?a/o:0,u=e.filter(d=>d.proofEnvelopeId).length;return{totalViolations:e.length,resolvedViolations:t.length,resolutionRate:e.length>0?t.length/e.length:1,byType:n,bySeverity:i,byGate:r,byAgent:s,avgResolutionTime:l,violationsWithProof:u,currentScore:this.calculateScore().overall}}clearViolations(){this.violations.clear(),this.scoreHistory=[]}reset(){this.violations.clear(),this.alertThresholds.clear(),this.scoreHistory=[],this.alertListeners.clear(),this.initialized=!1}async loadFromKv(){if(!this.db)return;let e=await this.db.kvGet("snapshot",c.NAMESPACE);if(e){if(e.violations)for(let[t,n]of Object.entries(e.violations))this.violations.set(t,n);e.scoreHistory&&(this.scoreHistory=e.scoreHistory)}}persistSnapshot(){if(this.db&&(this.persistCount++,this.persistCount%c.PERSIST_INTERVAL===0))try{let e=Array.from(this.violations.entries()).slice(-500),t={violations:Object.fromEntries(e),scoreHistory:this.scoreHistory.slice(-100)};this.db.kvSet("snapshot",t,c.NAMESPACE,c.TTL_SECONDS).catch(()=>{})}catch(e){console.warn("[ComplianceReporter] Persist failed:",S(e))}}generateViolationId(){return`viol_${Ke()}`}generateAlertId(){return`alert_${Ke()}`}calculateOverallScore(e){if(e.length===0)return Qe;let t=0;for(let i of e){let r=i.resolved?.5:1;t+=mt[i.severity]*r}let n=Qe*Math.exp(-ht*t/10);return Math.max(0,Math.min(100,Math.round(n*10)/10))}calculateTrend(e){let t=e.end-e.start,n={start:e.start-t,end:e.start},i=this.getViolations({startTime:n.start,endTime:n.end}),r=this.getViolations({startTime:e.start,endTime:e.end}),s=this.calculateOverallScore(i),o=this.calculateOverallScore(r)-s;return o>J?"improving":o<-J?"declining":"stable"}calculateGateTrend(e,t){let n=t.end-t.start,i={start:t.start-n,end:t.start},r=this.getViolations({gate:e,startTime:i.start,endTime:i.end}),s=this.getViolations({gate:e,startTime:t.start,endTime:t.end}),a=this.calculateOverallScore(r),l=this.calculateOverallScore(s)-a;return l>J?"improving":l<-J?"declining":"stable"}calculateAgentTrend(e,t){let n=t.end-t.start,i={start:t.start-n,end:t.start},r=this.getViolations({agentId:e,startTime:i.start,endTime:i.end}),s=this.getViolations({agentId:e,startTime:t.start,endTime:t.end}),a=this.calculateOverallScore(r),l=this.calculateOverallScore(s)-a;return l>J?"improving":l<-J?"declining":"stable"}calculateTrendAnalysis(e){let t=e.end-e.start,n={start:e.start-t,end:e.start},i=this.getViolations({startTime:e.start,endTime:e.end}),r=this.getViolations({startTime:n.start,endTime:n.end}),s=this.calculateOverallScore(i),a=this.calculateOverallScore(r),o=i.length-r.length,l;return o>2?l="increasing":o<-2?l="decreasing":l="stable",{currentPeriodScore:s,previousPeriodScore:a,change:s-a,violationTrend:l}}generateRecommendations(e,t){let n=[],i=e.filter(a=>a.severity==="critical").length;i>0&&n.push(`URGENT: ${i} critical violation(s) require immediate attention.`);let r=e.filter(a=>!a.resolved).length;r>5&&n.push(`${r} violations remain unresolved. Consider allocating resources for resolution.`);for(let[a,o]of Object.entries(t.byGate))o<70&&n.push(`${a} compliance score is ${o.toFixed(1)}. Review ${a} configuration and add monitoring.`);for(let[a,o]of Object.entries(t.byAgent))o<60&&n.push(`Agent ${a} has low compliance score (${o.toFixed(1)}). Consider retraining or restricting permissions.`);let s=new Map;for(let a of e)s.set(a.type,(s.get(a.type)||0)+1);for(let[a,o]of s)o>=5&&n.push(`${a} violations occurred ${o} times. Investigate root cause and add preventive measures.`);return t.trend==="declining"&&n.push("Overall compliance trend is declining. Schedule a governance review meeting."),n.length===0&&n.push("Compliance is within acceptable parameters. Continue monitoring."),n}generateMarkdownReport(e){let t=[],n=new Date(e.generatedAt).toISOString();t.push("# Compliance Report"),t.push(""),t.push(`**Generated:** ${n}`),t.push(`**Period:** ${new Date(e.timeWindow.start).toISOString()} to ${new Date(e.timeWindow.end).toISOString()}`),t.push(""),t.push("## Executive Summary"),t.push(""),t.push("| Metric | Value |"),t.push("|--------|-------|"),t.push(`| Overall Score | ${e.summary.overallScore.toFixed(1)} |`),t.push(`| Total Violations | ${e.summary.totalViolations} |`),t.push(`| Critical Violations | ${e.summary.criticalViolations} |`),t.push(`| High Violations | ${e.summary.highViolations} |`),t.push(`| Resolution Rate | ${(e.summary.resolutionRate*100).toFixed(1)}% |`),t.push(`| Trend | ${e.summary.trend} |`),t.push(""),t.push("## Gate Compliance Scores"),t.push(""),t.push("| Gate | Score | Violations | Trend |"),t.push("|------|-------|------------|-------|");for(let[i,r]of Object.entries(e.gateScores))t.push(`| ${i} | ${r.score.toFixed(1)} | ${r.violations} | ${r.trend} |`);t.push(""),t.push("## Violations by Type"),t.push(""),t.push("| Type | Count |"),t.push("|------|-------|");for(let[i,r]of Object.entries(e.violationsByType))r>0&&t.push(`| ${i} | ${r} |`);t.push(""),t.push("## Violations by Severity"),t.push(""),t.push("| Severity | Count |"),t.push("|----------|-------|");for(let[i,r]of Object.entries(e.violationsBySeverity))t.push(`| ${i} | ${r} |`);if(t.push(""),e.agentRankings&&e.agentRankings.length>0){t.push("## Agent Compliance Rankings"),t.push(""),t.push("| Agent | Score | Violations | Trend |"),t.push("|-------|-------|------------|-------|");for(let i of e.agentRankings)t.push(`| ${i.agentId} | ${i.score.toFixed(1)} | ${i.violations} | ${i.trend} |`);t.push("")}if(e.trendAnalysis&&(t.push("## Trend Analysis"),t.push(""),t.push(`- **Current Period Score:** ${e.trendAnalysis.currentPeriodScore.toFixed(1)}`),t.push(`- **Previous Period Score:** ${e.trendAnalysis.previousPeriodScore.toFixed(1)}`),t.push(`- **Change:** ${e.trendAnalysis.change>0?"+":""}${e.trendAnalysis.change.toFixed(1)}`),t.push(`- **Violation Trend:** ${e.trendAnalysis.violationTrend}`),t.push("")),e.recommendations&&e.recommendations.length>0){t.push("## Recommendations"),t.push("");for(let i of e.recommendations)t.push(`- ${i}`);t.push("")}if(e.violations&&e.violations.length>0){t.push("## Recent Violations"),t.push("");for(let i of e.violations.slice(0,10)){let r=i.resolved?"RESOLVED":"OPEN",s=new Date(i.timestamp).toISOString();t.push(`### ${i.id}`),t.push(""),t.push(`- **Type:** ${i.type}`),t.push(`- **Severity:** ${i.severity}`),t.push(`- **Gate:** ${i.gate}`),t.push(`- **Status:** ${r}`),t.push(`- **Time:** ${s}`),i.agentId&&t.push(`- **Agent:** ${i.agentId}`),t.push(`- **Description:** ${i.description}`),i.proofEnvelopeId&&t.push(`- **Proof:** ${i.proofEnvelopeId}`),t.push("")}}return t.push("---"),t.push("*Report generated by Agentic QE Compliance Reporter*"),t.join(`
|
|
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.8");process.exit(0)}
|
|
2
|
+
import{o as V,s as ae}from"./chunk-7XGM7Q2N.js";import{b as j,d as Me}from"./chunk-FWXNFPLS.js";import{a as D,e as qe}from"./chunk-7SLEUVPZ.js";import{a as S,b as Le,e as W}from"./chunk-J7FLNP5L.js";var We={continueGate:{enabled:!0,maxConsecutiveRetries:3,reworkRatioThreshold:.5,idleTimeoutMs:9e5,throttleOnExceed:!0},memoryWriteGate:{enabled:!0,contradictionDetection:!0,temporalDecayDays:30,minUsesForRetention:3,domainNamespacing:!0},trustAccumulator:{enabled:!0,performanceWeight:.5,taskSimilarityWeight:.3,capabilityMatchWeight:.2,minTrustForCritical:.7,autoTierAdjustment:!0},proofEnvelope:{enabled:!0,hashChaining:!0,auditLogRetentionDays:90,requireProofForClaims:!0,chainPersistence:!1,maxChainLength:1e4,signAllEnvelopes:!0},budgetMeter:{enabled:!0,maxSessionCostUsd:50,maxTokensPerSession:1e6,warningThresholdPercent:80},deterministicGateway:{enabled:!0,deduplicationWindowMs:5e3,cacheResultsForIdempotent:!0,validateSchemas:!0},evolutionPipeline:{enabled:!0,autoPromoteThreshold:.9,autoDemoteThreshold:.3,minSamplesForDecision:20,learningRate:.1},shardRetriever:{enabled:!0,shardsPath:".claude/guidance/shards",cacheEnabled:!0,cacheTtlMs:3e5,maxShardsPerQuery:3,relevanceThreshold:.3},abBenchmarking:{enabled:!0,defaultConfidenceLevel:.95,defaultMinSampleSize:100,autoApplyWinners:!1,maxConcurrentBenchmarks:5},shardEmbeddings:{enabled:!0,embeddingDimensions:384,persistEmbeddings:!1,autoRebuildOnChange:!0,ngramMin:2,ngramMax:4,persistPath:".agentic-qe/shard-embeddings.json"},adversarialDefense:{enabled:!0,blockThreshold:.7,sanitizeInputs:!0,penalizeOnDetection:!0,logDetections:!0},complianceReporter:{enabled:!0,autoRecordViolations:!0,retentionDays:90,alertOnCritical:!0,generateDailyReport:!1},constitutionalEnforcer:{enabled:!0,strictEnforcement:!1,escalateViolations:!0,constitutionPath:".claude/guidance/constitution.md",logAllChecks:!0},global:{enableAllGates:!0,strictMode:!1,logViolations:!0,escalateToQueen:!0}};function je(){let c=process.env;return{continueGate:{enabled:c.GOVERNANCE_CONTINUE_GATE!=="false",maxConsecutiveRetries:parseInt(c.GOVERNANCE_MAX_RETRIES||"3",10),reworkRatioThreshold:parseFloat(c.GOVERNANCE_REWORK_THRESHOLD||"0.5"),idleTimeoutMs:parseInt(c.GOVERNANCE_IDLE_TIMEOUT||"900000",10),throttleOnExceed:c.GOVERNANCE_THROTTLE!=="false"},memoryWriteGate:{enabled:c.GOVERNANCE_MEMORY_GATE!=="false",contradictionDetection:c.GOVERNANCE_CONTRADICTION_CHECK!=="false",temporalDecayDays:parseInt(c.GOVERNANCE_DECAY_DAYS||"30",10),minUsesForRetention:parseInt(c.GOVERNANCE_MIN_USES||"3",10),domainNamespacing:c.GOVERNANCE_DOMAIN_NS!=="false"},trustAccumulator:{enabled:c.GOVERNANCE_TRUST!=="false",performanceWeight:parseFloat(c.GOVERNANCE_PERF_WEIGHT||"0.5"),taskSimilarityWeight:parseFloat(c.GOVERNANCE_SIMILARITY_WEIGHT||"0.3"),capabilityMatchWeight:parseFloat(c.GOVERNANCE_CAPABILITY_WEIGHT||"0.2"),minTrustForCritical:parseFloat(c.GOVERNANCE_MIN_TRUST||"0.7"),autoTierAdjustment:c.GOVERNANCE_AUTO_TIER!=="false"},proofEnvelope:{enabled:c.GOVERNANCE_PROOF!=="false",hashChaining:c.GOVERNANCE_HASH_CHAIN!=="false",auditLogRetentionDays:parseInt(c.GOVERNANCE_AUDIT_DAYS||"90",10),requireProofForClaims:c.GOVERNANCE_REQUIRE_PROOF!=="false",chainPersistence:c.GOVERNANCE_CHAIN_PERSIST==="true",maxChainLength:parseInt(c.GOVERNANCE_MAX_CHAIN_LENGTH||"10000",10),signAllEnvelopes:c.GOVERNANCE_SIGN_ALL!=="false"},budgetMeter:{enabled:c.GOVERNANCE_BUDGET!=="false",maxSessionCostUsd:parseFloat(c.GOVERNANCE_MAX_COST||"50"),maxTokensPerSession:parseInt(c.GOVERNANCE_MAX_TOKENS||"1000000",10),warningThresholdPercent:parseInt(c.GOVERNANCE_WARNING_PERCENT||"80",10)},deterministicGateway:{enabled:c.GOVERNANCE_DETERMINISTIC!=="false",deduplicationWindowMs:parseInt(c.GOVERNANCE_DEDUP_WINDOW||"5000",10),cacheResultsForIdempotent:c.GOVERNANCE_CACHE_IDEMPOTENT!=="false",validateSchemas:c.GOVERNANCE_VALIDATE_SCHEMAS!=="false"},evolutionPipeline:{enabled:c.GOVERNANCE_EVOLUTION!=="false",autoPromoteThreshold:parseFloat(c.GOVERNANCE_PROMOTE_THRESHOLD||"0.9"),autoDemoteThreshold:parseFloat(c.GOVERNANCE_DEMOTE_THRESHOLD||"0.3"),minSamplesForDecision:parseInt(c.GOVERNANCE_MIN_SAMPLES||"20",10),learningRate:parseFloat(c.GOVERNANCE_LEARNING_RATE||"0.1")},shardRetriever:{enabled:c.GOVERNANCE_SHARD_RETRIEVER!=="false",shardsPath:c.GOVERNANCE_SHARDS_PATH||".claude/guidance/shards",cacheEnabled:c.GOVERNANCE_SHARD_CACHE!=="false",cacheTtlMs:parseInt(c.GOVERNANCE_SHARD_CACHE_TTL||"300000",10),maxShardsPerQuery:parseInt(c.GOVERNANCE_MAX_SHARDS||"3",10),relevanceThreshold:parseFloat(c.GOVERNANCE_RELEVANCE_THRESHOLD||"0.3")},abBenchmarking:{enabled:c.GOVERNANCE_AB_BENCHMARKING!=="false",defaultConfidenceLevel:parseFloat(c.GOVERNANCE_AB_CONFIDENCE||"0.95"),defaultMinSampleSize:parseInt(c.GOVERNANCE_AB_MIN_SAMPLES||"100",10),autoApplyWinners:c.GOVERNANCE_AB_AUTO_APPLY==="true",maxConcurrentBenchmarks:parseInt(c.GOVERNANCE_AB_MAX_CONCURRENT||"5",10)},shardEmbeddings:{enabled:c.GOVERNANCE_SHARD_EMBEDDINGS!=="false",embeddingDimensions:parseInt(c.GOVERNANCE_EMBEDDING_DIMENSIONS||"384",10),persistEmbeddings:c.GOVERNANCE_PERSIST_EMBEDDINGS==="true",autoRebuildOnChange:c.GOVERNANCE_AUTO_REBUILD!=="false",ngramMin:parseInt(c.GOVERNANCE_NGRAM_MIN||"2",10),ngramMax:parseInt(c.GOVERNANCE_NGRAM_MAX||"4",10),persistPath:c.GOVERNANCE_EMBEDDINGS_PATH||".agentic-qe/shard-embeddings.json"},adversarialDefense:{enabled:c.GOVERNANCE_ADVERSARIAL_DEFENSE!=="false",blockThreshold:parseFloat(c.GOVERNANCE_BLOCK_THRESHOLD||"0.7"),sanitizeInputs:c.GOVERNANCE_SANITIZE_INPUTS!=="false",penalizeOnDetection:c.GOVERNANCE_PENALIZE_DETECTION!=="false",logDetections:c.GOVERNANCE_LOG_DETECTIONS!=="false"},complianceReporter:{enabled:c.GOVERNANCE_COMPLIANCE_REPORTER!=="false",autoRecordViolations:c.GOVERNANCE_AUTO_RECORD_VIOLATIONS!=="false",retentionDays:parseInt(c.GOVERNANCE_VIOLATION_RETENTION_DAYS||"90",10),alertOnCritical:c.GOVERNANCE_ALERT_ON_CRITICAL!=="false",generateDailyReport:c.GOVERNANCE_DAILY_REPORT==="true"},constitutionalEnforcer:{enabled:c.GOVERNANCE_CONSTITUTIONAL_ENFORCER!=="false",strictEnforcement:c.GOVERNANCE_CONSTITUTIONAL_STRICT==="true",escalateViolations:c.GOVERNANCE_CONSTITUTIONAL_ESCALATE!=="false",constitutionPath:c.GOVERNANCE_CONSTITUTION_PATH||".claude/guidance/constitution.md",logAllChecks:c.GOVERNANCE_CONSTITUTIONAL_LOG!=="false"},global:{enableAllGates:c.GOVERNANCE_ENABLED!=="false",strictMode:c.GOVERNANCE_STRICT==="true",logViolations:c.GOVERNANCE_LOG_VIOLATIONS!=="false",escalateToQueen:c.GOVERNANCE_ESCALATE!=="false"}}}function oe(c=We,e=je(),t={}){let n=(i,r)=>{let s={...i};for(let a in r)r[a]!==void 0&&(typeof r[a]=="object"&&!Array.isArray(r[a])?s[a]=n(i[a],r[a]):s[a]=r[a]);return s};return n(n(c,e),t)}var xe=class{flags;listeners=new Set;constructor(){this.flags=oe()}getFlags(){return this.flags}isGateEnabled(e){return this.flags.global.enableAllGates?this.flags[e].enabled:!1}updateFlags(e){this.flags=oe(this.flags,{},e),this.notifyListeners()}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}notifyListeners(){this.listeners.forEach(e=>e(this.flags))}reset(){this.flags=oe(),this.notifyListeners()}enableStrictMode(){this.updateFlags({global:{...this.flags.global,strictMode:!0}})}disableAllGates(){this.updateFlags({global:{...this.flags.global,enableAllGates:!1}})}},h=new xe,G=()=>h.isGateEnabled("continueGate"),U=()=>h.isGateEnabled("memoryWriteGate"),M=()=>h.isGateEnabled("trustAccumulator");var ce=()=>h.isGateEnabled("budgetMeter"),le=()=>h.isGateEnabled("deterministicGateway");var E=()=>h.isGateEnabled("adversarialDefense"),x=()=>h.isGateEnabled("complianceReporter"),K=()=>h.isGateEnabled("constitutionalEnforcer"),v=()=>h.getFlags().global.strictMode;var Ie=class{patternIndex=new Map;domainPatterns=new Map;guidanceMemoryGate=null;initialized=!1;async initialize(){if(!this.initialized){try{let t=await import("@claude-flow/guidance/memory-gate");t&&typeof t.createMemoryWriteGate=="function"&&(this.guidanceMemoryGate=t.createMemoryWriteGate({enableContradictionTracking:!0}),console.log("[MemoryWriteGateIntegration] Guidance MemoryWriteGate loaded"))}catch{this.guidanceMemoryGate=null}this.initialized=!0}}async evaluateWrite(e){if(!U())return{allowed:!0};await this.initialize();let t=h.getFlags().memoryWriteGate;e.timestamp=e.timestamp||Date.now(),e.useCount=e.useCount||0;let n=this.localEvaluation(e,t);if(this.guidanceMemoryGate&&n.allowed&&!n.reason)try{let i={agentId:e.agentId||"unknown",role:"worker",namespaces:[e.domain],maxWritesPerMinute:60,canDelete:!1,canOverwrite:!0,trustLevel:.7},r=this.guidanceMemoryGate.evaluateWrite(i,e.key,e.domain,e.value);if(!r.allowed)return this.mapGuidanceDecision(r)}catch{}return n}localEvaluation(e,t){if(t.domainNamespacing&&e.agentId){let n=this.getAllowedDomainsForAgent(e.agentId);if(!n.includes(e.domain)&&!n.includes("*"))return this.logViolation(e,"domain_violation",`Agent ${e.agentId} cannot write to domain ${e.domain}`),{allowed:!v(),reason:`Agent ${e.agentId} not authorized to write to domain ${e.domain}`,requiresManualReview:!0}}if(t.contradictionDetection){let n=this.findConflictingPatterns(e);if(n.length>0)return n.every(r=>e.supersedes?.includes(r.key))?{allowed:!0,conflictingPatterns:n,suggestedResolution:"supersede"}:(this.logViolation(e,"contradiction",`Conflicts with ${n.length} existing pattern(s)`),{allowed:!v(),reason:`Pattern conflicts with ${n.length} existing pattern(s)`,conflictingPatterns:n,suggestedResolution:this.suggestResolution(e,n),requiresManualReview:n.some(r=>(r.useCount||0)>5)})}return{allowed:!0}}findConflictingPatterns(e){let t=this.domainPatterns.get(e.domain);if(!t)return[];let n=[];for(let i of t){let r=this.patternIndex.get(i);!r||r.key===e.key||this.areContradictory(e,r)&&n.push(r)}return n}areContradictory(e,t){if(e.key===t.key)return!1;let n=JSON.stringify(e.value).toLowerCase(),i=JSON.stringify(t.value).toLowerCase(),r=[{positive:"should",negative:"should not"},{positive:"always",negative:"never"},{positive:"enabled",negative:"disabled"},{positive:"true",negative:"false"},{positive:"allow",negative:"deny"},{positive:"include",negative:"exclude"}];for(let s of r)if(n.includes(s.positive)&&i.includes(s.negative)||n.includes(s.negative)&&i.includes(s.positive)){let a=new Set(n.match(/\b\w{4,}\b/g)||[]),o=new Set(i.match(/\b\w{4,}\b/g)||[]);if([...a].filter(u=>o.has(u)).length>=2)return!0}return!!(e.tags&&t.tags&&e.tags.filter(a=>t.tags?.includes(a)).length>0&&e.value!==t.value)}suggestResolution(e,t){let n=e.timestamp||0,i=Math.min(...t.map(r=>r.timestamp||0));return n-i>10080*60*1e3?"supersede":t.some(r=>(r.useCount||0)>10)?"reject":"merge"}getAllowedDomainsForAgent(e){return{"qe-test-architect":["test-generation","learning-optimization"],"qe-coverage-specialist":["coverage-analysis","learning-optimization"],"qe-security-scanner":["security-compliance"],"qe-chaos-engineer":["chaos-resilience"],"qe-defect-predictor":["defect-intelligence","learning-optimization"],"qe-learning-coordinator":["*"],"qe-quality-gate":["quality-assessment"],"qe-parallel-executor":["test-execution"],"qe-contract-validator":["contract-testing"],"qe-accessibility-auditor":["visual-accessibility"],"qe-requirements-validator":["requirements-validation"],"qe-code-intelligence":["code-intelligence"]}[e]||[e.split("-").pop()||"unknown"]}getExistingPatterns(e){let t=this.domainPatterns.get(e);return t?[...t].map(n=>this.patternIndex.get(n)).filter(n=>n!==void 0):[]}mapGuidanceDecision(e){return{allowed:e.allowed,reason:e.reason,requiresManualReview:!e.authorityCheck.passed||e.contradictions.length>0,suggestedResolution:e.contradictions.length>0?"reject":void 0}}logViolation(e,t,n){h.getFlags().global.logViolations&&console.warn("[MemoryWriteGate] Violation detected:",{patternKey:e.key,domain:e.domain,violationType:t,details:n,timestamp:new Date().toISOString()})}registerPattern(e){this.patternIndex.set(e.key,e),this.domainPatterns.has(e.domain)||this.domainPatterns.set(e.domain,new Set),this.domainPatterns.get(e.domain).add(e.key)}unregisterPattern(e){let t=this.patternIndex.get(e);t&&(this.domainPatterns.get(t.domain)?.delete(e),this.patternIndex.delete(e))}incrementUseCount(e){let t=this.patternIndex.get(e);t&&(t.useCount=(t.useCount||0)+1)}async applyTemporalDecay(){let e=h.getFlags().memoryWriteGate,t=e.temporalDecayDays*24*60*60*1e3,n=Date.now(),i=[];for(let[r,s]of this.patternIndex){let a=n-(s.timestamp||0),o=s.useCount||0;a>t&&o<e.minUsesForRetention&&(i.push(r),this.unregisterPattern(r))}return i.length>0&&console.info(`[MemoryWriteGate] Archived ${i.length} patterns due to temporal decay`),i}getStats(){let e={};for(let[t,n]of this.domainPatterns)e[t]=n.size;return{totalPatterns:this.patternIndex.size,patternsByDomain:e}}reset(){this.patternIndex.clear(),this.domainPatterns.clear()}loadPatternsFromBank(e){for(let t of e)this.registerPattern(t)}},Q=new Ie;function Pe(c,e,t,n={}){return{key:c,value:e,domain:t,timestamp:Date.now(),useCount:0,...n}}import{randomUUID as Ke}from"node:crypto";Me();import{randomUUID as ut,createHash as dt}from"node:crypto";W();Me();import{createHash as ct,createHmac as lt}from"node:crypto";var De=class{kernel=null;initialized=!1;initError=null;metrics={backend:"js",avgHashTimeMs:0,totalOperations:0,totalTimeMs:0,operationCounts:{hash:0,hashChain:0,verify:0,hmac:0}};async initialize(){if(!this.initialized){try{let t=await import("@claude-flow/guidance/wasm-kernel");t&&typeof t.getKernel=="function"&&(this.kernel=t.getKernel(),this.metrics.backend=this.kernel?.available?"wasm":"js")}catch(e){this.initError=Le(e),this.kernel=null,this.metrics.backend="js"}this.initialized=!0}}isWasmAvailable(){return this.kernel?.available??!1}getVersion(){return this.kernel?.version??"js-fallback"}getInitError(){return this.initError}hash(e){let t=performance.now(),n;if(this.kernel?.available){let i=typeof e=="string"?e:Buffer.from(e).toString("utf-8");n=this.kernel.sha256(i)}else n=this.jsHash(e);return this.recordOperation("hash",performance.now()-t),n}hmac(e,t){let n=performance.now(),i;return this.kernel?.available?i=this.kernel.hmacSha256(e,t):i=lt("sha256",e).update(t).digest("hex"),this.recordOperation("hmac",performance.now()-n),i}hashChain(e){let t=performance.now();if(e.length===0)return this.recordOperation("hashChain",performance.now()-t),this.hash("");if(e.length===1)return this.recordOperation("hashChain",performance.now()-t),e[0];let n=e[0];for(let i=1;i<e.length;i++)n=this.hash(n+e[i]);return this.recordOperation("hashChain",performance.now()-t),n}verify(e,t){let n=performance.now(),r=this.hash(e)===t;return this.recordOperation("verify",performance.now()-n),r}contentHash(e){let t=performance.now(),n,i=typeof e=="string"?e:JSON.stringify(e);return this.kernel?.available?n=this.kernel.contentHash(i):n=this.jsContentHash(i),this.recordOperation("hash",performance.now()-t),n}signEnvelope(e,t){let n=JSON.stringify(t);return this.kernel?.available?this.kernel.signEnvelope(e,n):this.hmac(e,n)}getPerformanceMetrics(){return{...this.metrics}}resetMetrics(){this.metrics={backend:this.kernel?.available?"wasm":"js",avgHashTimeMs:0,totalOperations:0,totalTimeMs:0,operationCounts:{hash:0,hashChain:0,verify:0,hmac:0}}}reset(){this.kernel=null,this.initialized=!1,this.initError=null,this.resetMetrics()}jsHash(e){let t=ct("sha256");return typeof e=="string"?t.update(e):t.update(Buffer.from(e)),t.digest("hex")}jsContentHash(e){try{let t=j(e),n=this.sortKeys(t);return this.jsHash(JSON.stringify(n))}catch{return this.jsHash(e)}}sortKeys(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>this.sortKeys(n));let t={};for(let n of Object.keys(e).sort())t[n]=this.sortKeys(e[n]);return t}recordOperation(e,t){this.metrics.totalOperations++,this.metrics.totalTimeMs+=t,this.metrics.operationCounts[e]++,this.metrics.avgHashTimeMs=this.metrics.totalTimeMs/this.metrics.totalOperations}},Ue=new De;qe();var te="0".repeat(64),ue=class{kernel;chain=[];signingKey="";guidanceProofChain=null;initialized=!1;envelopeIndex=new Map;constructor(e){this.kernel=e??Ue}async initialize(e){if(!this.initialized){await this.kernel.initialize(),this.signingKey=e||dt("sha256").update(`aqe-proof-envelope:${process.cwd()}`).digest("hex");try{let n=await import("@claude-flow/guidance/proof");n&&typeof n.createProofChain=="function"&&(this.guidanceProofChain=n.createProofChain({signingKey:this.signingKey}),console.log("[ProofEnvelopeIntegration] Guidance ProofChain loaded"))}catch{this.guidanceProofChain=null}this.initialized=!0}}isInitialized(){return this.initialized}getFlags(){return h.getFlags().proofEnvelope}createEnvelope(e,t,n,i){let r=this.generateEnvelopeId(),s=Date.now(),a=this.chain.length>0?this.chain[this.chain.length-1].contentHash:te,o={id:r,timestamp:s,agentId:e,action:t,payload:n,metadata:i},l=this.kernel.contentHash(o);return{id:r,timestamp:s,agentId:e,action:t,payload:n,contentHash:l,previousHash:a,signature:"",metadata:i}}signEnvelope(e,t){let n=t??this.signingKey,i=`${e.contentHash}:${e.previousHash}`,r=this.kernel.hmac(n,i);return{...e,signature:r}}createSignedEnvelope(e,t,n,i){let r=this.createEnvelope(e,t,n,i);return this.signEnvelope(r)}appendToChain(e){let t=this.verifyEnvelope(e);if(!t.valid)throw new Error(`Cannot append invalid envelope: ${t.error}`);let n=this.chain.length>0?this.chain[this.chain.length-1].contentHash:te;if(e.previousHash!==n)throw new Error(`Envelope does not link to chain. Expected previous hash ${n}, got ${e.previousHash}`);let i=this.chain.length;if(this.chain.push(e),this.envelopeIndex.set(e.id,i),this.guidanceProofChain)try{let r={eventId:e.id,taskId:e.metadata?.taskId?String(e.metadata.taskId):e.id,guidanceHash:e.contentHash,retrievedRuleIds:[],toolsUsed:e.action?[e.action]:[],filesTouched:[],diffSummary:{linesAdded:0,linesRemoved:0,filesChanged:0},testResults:{passed:0,failed:0,skipped:0},metrics:{},timestamp:new Date(e.timestamp).toISOString()};this.guidanceProofChain.append(r,[],[],{agentId:e.agentId,sessionId:e.metadata?.sessionId?String(e.metadata.sessionId):"aqe"})}catch{}}getChain(){return[...this.chain]}getChainLength(){return this.chain.length}getLastEnvelope(){return this.chain.length===0?null:this.chain[this.chain.length-1]}clearChain(){this.chain=[],this.envelopeIndex.clear()}verifyEnvelope(e,t){let n=t??this.signingKey,i={contentHashValid:!1,signatureValid:!1,chainLinkValid:!0},r={id:e.id,timestamp:e.timestamp,agentId:e.agentId,action:e.action,payload:e.payload,metadata:e.metadata},s=this.kernel.contentHash(r);if(i.contentHashValid=e.contentHash===s,!i.contentHashValid)return{valid:!1,details:i,error:"Content hash does not match envelope content"};let a=`${e.contentHash}:${e.previousHash}`,o=this.kernel.hmac(n,a);if(i.signatureValid=e.signature===o,!i.signatureValid)return{valid:!1,details:i,error:"Signature verification failed"};let l=this.envelopeIndex.get(e.id);if(l!==void 0&&l>0){let u=this.chain[l-1];if(i.chainLinkValid=e.previousHash===u.contentHash,!i.chainLinkValid)return{valid:!1,details:i,error:"Chain link is broken - previous hash does not match"}}return{valid:!0,details:i}}verifyChain(e){let t=[],n=-1;for(let i=0;i<this.chain.length;i++){let r=this.chain[i],s=this.verifyEnvelope(r,e);s.valid||(t.push({index:i,envelopeId:r.id,error:s.error??"Unknown error"}),n===-1&&(n=i));let a=i>0?this.chain[i-1].contentHash:te;r.previousHash!==a&&(t.push({index:i,envelopeId:r.id,error:`Chain link broken at index ${i}`}),n===-1&&(n=i))}return{valid:t.length===0,envelopesVerified:this.chain.length,firstInvalidIndex:n,merkleRoot:this.computeMerkleRoot(),errors:t}}detectTampering(){let e=[],t=[];for(let n=0;n<this.chain.length;n++){let i=this.chain[n],r={id:i.id,timestamp:i.timestamp,agentId:i.agentId,action:i.action,payload:i.payload,metadata:i.metadata},s=this.kernel.contentHash(r);i.contentHash!==s&&(t.push(n),e.push({index:n,envelopeId:i.id,issue:"Content hash mismatch - envelope content was modified"}));let a=n>0?this.chain[n-1].contentHash:te;i.previousHash!==a&&(t.includes(n)||t.push(n),e.push({index:n,envelopeId:i.id,issue:"Chain link broken - previous hash does not match"}))}return{tampered:t.length>0,tamperedIndices:t,details:e}}getEnvelopeById(e){let t=this.envelopeIndex.get(e);return t===void 0?null:this.chain[t]}getEnvelopesByAgent(e){return this.chain.filter(t=>t.agentId===e)}getEnvelopesByAction(e){return this.chain.filter(t=>t.action===e)}getEnvelopesSince(e){return this.chain.filter(t=>t.timestamp>=e)}getEnvelopesInRange(e,t){return this.chain.filter(n=>n.timestamp>=e&&n.timestamp<=t)}exportChain(e){let t={version:1,exportedAt:Date.now(),chainLength:this.chain.length,merkleRoot:this.computeMerkleRoot(),envelopes:this.chain};if(e==="json")return JSON.stringify(t,null,2);let n=JSON.stringify(t);return new TextEncoder().encode(n)}importChain(e,t=!0){let n;typeof e=="string"?n=e:n=new TextDecoder().decode(e);let i=j(n);if(!i.envelopes||!Array.isArray(i.envelopes))throw new Error("Invalid chain data: missing envelopes array");this.clearChain();for(let r of i.envelopes){let s=this.chain.length;this.chain.push(r),this.envelopeIndex.set(r.id,s)}if(t){let r=this.verifyChain();if(!r.valid)throw this.clearChain(),new Error(`Imported chain failed verification: ${r.errors[0]?.error}`)}}getProofStats(){let e=D(),t=new Set;for(let i of this.chain)t.add(i.agentId),e[i.action]=(e[i.action]||0)+1;let n=this.chain.length===0||this.verifyChain().valid;return{chainLength:this.chain.length,firstTimestamp:this.chain.length>0?this.chain[0].timestamp:null,lastTimestamp:this.chain.length>0?this.chain[this.chain.length-1].timestamp:null,uniqueAgents:Array.from(t),actionCounts:e,merkleRoot:this.computeMerkleRoot(),chainValid:n}}computeMerkleRoot(){if(this.chain.length===0)return te;let e=this.chain.map(t=>t.contentHash);for(;e.length>1;){let t=[];for(let n=0;n<e.length;n+=2)n+1<e.length?t.push(this.kernel.hash(e[n]+e[n+1])):t.push(e[n]);e=t}return e[0]}getMerkleProof(e){let t=this.envelopeIndex.get(e);if(t===void 0)return null;let n=[],i=this.chain.map(s=>s.contentHash),r=t;for(;i.length>1;){let s=r%2===0?r+1:r-1;s<i.length&&n.push(i[s]);let a=[];for(let o=0;o<i.length;o+=2)o+1<i.length?a.push(this.kernel.hash(i[o]+i[o+1])):a.push(i[o]);i=a,r=Math.floor(r/2)}return n}verifyMerkleProof(e,t,n){let i=e,r=n;for(let s of t)r%2===0?i=this.kernel.hash(i+s):i=this.kernel.hash(s+i),r=Math.floor(r/2);return i===this.computeMerkleRoot()}generateEnvelopeId(){return`env_${ut()}`}reset(){this.chain=[],this.envelopeIndex.clear(),this.signingKey="",this.initialized=!1}},Ve=new ue;ae();W();qe();var Je={enabled:!0,autoRecordViolations:!0,retentionDays:90,alertOnCritical:!0,generateDailyReport:!1},mt={low:1,medium:3,high:7,critical:15},Qe=100,ht=.5,J=5,de=class c{violations=new Map;alertThresholds=new Map;proofIntegration;flags;initialized=!1;scoreHistory=[];alertListeners=new Set;db=null;persistCount=0;static NAMESPACE="compliance-audit";static TTL_SECONDS=2592e3;static PERSIST_INTERVAL=10;constructor(e,t){this.proofIntegration=e??Ve,this.flags={...Je,...t}}async initialize(){if(!this.initialized){try{this.db=V(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(e){console.warn("[ComplianceReporter] DB init failed, using memory-only:",S(e)),this.db=null}this.proofIntegration.isInitialized()||await this.proofIntegration.initialize(),this.alertThresholds.set("continueGate",70),this.alertThresholds.set("memoryWriteGate",70),this.alertThresholds.set("trustAccumulator",70),this.alertThresholds.set("budgetMeter",60),this.alertThresholds.set("adversarialDefense",80),this.initialized=!0}}isInitialized(){return this.initialized}getFlags(){return{...this.flags}}updateFlags(e){this.flags={...this.flags,...e}}recordViolation(e){let t=this.generateViolationId(),n=Date.now(),i={...e,id:t,timestamp:n,resolved:!1};if(this.violations.set(t,i),h.getFlags().proofEnvelope.enabled)try{let r=this.proofIntegration.createSignedEnvelope(e.agentId??"system","violation_recorded",{violationId:t,type:e.type,severity:e.severity,gate:e.gate,description:e.description});this.proofIntegration.appendToChain(r),i.proofEnvelopeId=r.id}catch{}return this.flags.alertOnCritical&&e.severity==="critical"&&this.triggerAlert(e.gate,"Critical violation detected","critical"),this.persistSnapshot(),this.cleanupOldViolations(),t}resolveViolation(e,t){let n=this.violations.get(e);if(!n)throw new Error(`Violation not found: ${e}`);if(n.resolved=!0,n.resolution=t,n.resolvedAt=Date.now(),h.getFlags().proofEnvelope.enabled)try{let i=this.proofIntegration.createSignedEnvelope(n.agentId??"system","violation_resolved",{violationId:e,resolution:t});this.proofIntegration.appendToChain(i)}catch{}}getViolation(e){return this.violations.get(e)??null}getViolations(e){let t=Array.from(this.violations.values());return e&&(e.type!==void 0&&(t=t.filter(n=>n.type===e.type)),e.severity!==void 0&&(t=t.filter(n=>n.severity===e.severity)),e.agentId!==void 0&&(t=t.filter(n=>n.agentId===e.agentId)),e.gate!==void 0&&(t=t.filter(n=>n.gate===e.gate)),e.resolved!==void 0&&(t=t.filter(n=>n.resolved===e.resolved)),e.startTime!==void 0&&(t=t.filter(n=>n.timestamp>=e.startTime)),e.endTime!==void 0&&(t=t.filter(n=>n.timestamp<=e.endTime)),e.limit!==void 0&&(t=t.slice(0,e.limit))),t.sort((n,i)=>i.timestamp-n.timestamp)}calculateScore(e){let t=Date.now(),n=e??{start:t-1440*60*1e3,end:t},i=this.getViolations({startTime:n.start,endTime:n.end}),r=this.calculateOverallScore(i),s=D(),a=this.groupBy(i,"gate");for(let[g,p]of Object.entries(a))s[g]=this.calculateOverallScore(p);let o=D(),l=this.groupBy(i,"agentId");for(let[g,p]of Object.entries(l))g!=="undefined"&&(o[g]=this.calculateOverallScore(p));let u=this.calculateTrend(n),d=i.filter(g=>g.resolved).length,m={overall:r,byGate:s,byAgent:o,trend:u,period:n,totalViolations:i.length,resolvedViolations:d};return this.scoreHistory.push(m),this.scoreHistory.length>100&&this.scoreHistory.shift(),m}getScoreHistory(e){return this.scoreHistory.slice(-e)}generateReport(e={}){let t=Date.now(),n=e.timeWindow??{start:t-1440*60*1e3,end:t},i=this.getViolations({startTime:n.start,endTime:n.end}),r=this.calculateScore(n),s={loop_detected:0,contradiction:0,trust_violation:0,budget_exceeded:0,adversarial_detected:0,invariant_violated:0,unauthorized_access:0,chain_tampered:0,schema_violation:0,rate_limit_exceeded:0};for(let g of i)s[g.type]++;let a={low:0,medium:0,high:0,critical:0};for(let g of i)a[g.severity]++;let o={},l=this.groupBy(i,"gate");for(let[g,p]of Object.entries(l))o[g]={score:this.calculateOverallScore(p),violations:p.length,trend:this.calculateGateTrend(g,n)};let u=i.filter(g=>g.resolved).length,d=i.length>0?u/i.length:1,m={generatedAt:t,timeWindow:n,summary:{overallScore:r.overall,totalViolations:i.length,criticalViolations:a.critical,highViolations:a.high,resolvedViolations:u,resolutionRate:d,trend:r.trend},gateScores:o,violationsByType:s,violationsBySeverity:a};if(e.includeAgentRankings){let g=this.groupBy(i,"agentId");m.agentRankings=Object.entries(g).filter(([p])=>p!=="undefined").map(([p,b])=>({agentId:p,score:this.calculateOverallScore(b),violations:b.length,trend:this.calculateAgentTrend(p,n)})).sort((p,b)=>b.score-p.score)}if(e.includeViolations){let g=e.maxViolations??50;m.violations=i.slice(0,g)}return e.includeRecommendations&&(m.recommendations=this.generateRecommendations(i,r)),e.includeTrendAnalysis&&(m.trendAnalysis=this.calculateTrendAnalysis(n)),m}exportReport(e,t){return t==="json"?JSON.stringify(e,null,2):this.generateMarkdownReport(e)}attachProof(e,t){let n=this.violations.get(e);if(!n)throw new Error(`Violation not found: ${e}`);if(!this.proofIntegration.getEnvelopeById(t))throw new Error(`Proof envelope not found: ${t}`);n.proofEnvelopeId=t}getViolationsWithProof(){return Array.from(this.violations.values()).filter(e=>e.proofEnvelopeId!==void 0)}getViolationProof(e){let t=this.violations.get(e);return t?.proofEnvelopeId?this.proofIntegration.getEnvelopeById(t.proofEnvelopeId):null}setAlertThreshold(e,t){if(t<0||t>100)throw new Error("Threshold must be between 0 and 100");this.alertThresholds.set(e,t)}getAlertThreshold(e){return this.alertThresholds.get(e)}checkAlerts(){let e=[],t=this.calculateScore();for(let[n,i]of this.alertThresholds){let r=t.byGate[n];if(r!==void 0&&r<i){let s={id:this.generateAlertId(),gate:n,message:`Compliance score for ${n} (${r.toFixed(1)}) dropped below threshold (${i})`,severity:r<i*.5?"critical":"high",timestamp:Date.now(),currentScore:r,threshold:i};e.push(s),this.notifyAlertListeners(s)}}return e}onAlert(e){return this.alertListeners.add(e),()=>this.alertListeners.delete(e)}getComplianceStats(){let e=Array.from(this.violations.values()),t=e.filter(d=>d.resolved),n={loop_detected:0,contradiction:0,trust_violation:0,budget_exceeded:0,adversarial_detected:0,invariant_violated:0,unauthorized_access:0,chain_tampered:0,schema_violation:0,rate_limit_exceeded:0};for(let d of e)n[d.type]++;let i={low:0,medium:0,high:0,critical:0};for(let d of e)i[d.severity]++;let r=D();for(let d of e)r[d.gate]=(r[d.gate]||0)+1;let s=D();for(let d of e)d.agentId&&(s[d.agentId]=(s[d.agentId]||0)+1);let a=0,o=0;for(let d of t)d.resolvedAt&&(a+=d.resolvedAt-d.timestamp,o++);let l=o>0?a/o:0,u=e.filter(d=>d.proofEnvelopeId).length;return{totalViolations:e.length,resolvedViolations:t.length,resolutionRate:e.length>0?t.length/e.length:1,byType:n,bySeverity:i,byGate:r,byAgent:s,avgResolutionTime:l,violationsWithProof:u,currentScore:this.calculateScore().overall}}clearViolations(){this.violations.clear(),this.scoreHistory=[]}reset(){this.violations.clear(),this.alertThresholds.clear(),this.scoreHistory=[],this.alertListeners.clear(),this.initialized=!1}async loadFromKv(){if(!this.db)return;let e=await this.db.kvGet("snapshot",c.NAMESPACE);if(e){if(e.violations)for(let[t,n]of Object.entries(e.violations))this.violations.set(t,n);e.scoreHistory&&(this.scoreHistory=e.scoreHistory)}}persistSnapshot(){if(this.db&&(this.persistCount++,this.persistCount%c.PERSIST_INTERVAL===0))try{let e=Array.from(this.violations.entries()).slice(-500),t={violations:Object.fromEntries(e),scoreHistory:this.scoreHistory.slice(-100)};this.db.kvSet("snapshot",t,c.NAMESPACE,c.TTL_SECONDS).catch(()=>{})}catch(e){console.warn("[ComplianceReporter] Persist failed:",S(e))}}generateViolationId(){return`viol_${Ke()}`}generateAlertId(){return`alert_${Ke()}`}calculateOverallScore(e){if(e.length===0)return Qe;let t=0;for(let i of e){let r=i.resolved?.5:1;t+=mt[i.severity]*r}let n=Qe*Math.exp(-ht*t/10);return Math.max(0,Math.min(100,Math.round(n*10)/10))}calculateTrend(e){let t=e.end-e.start,n={start:e.start-t,end:e.start},i=this.getViolations({startTime:n.start,endTime:n.end}),r=this.getViolations({startTime:e.start,endTime:e.end}),s=this.calculateOverallScore(i),o=this.calculateOverallScore(r)-s;return o>J?"improving":o<-J?"declining":"stable"}calculateGateTrend(e,t){let n=t.end-t.start,i={start:t.start-n,end:t.start},r=this.getViolations({gate:e,startTime:i.start,endTime:i.end}),s=this.getViolations({gate:e,startTime:t.start,endTime:t.end}),a=this.calculateOverallScore(r),l=this.calculateOverallScore(s)-a;return l>J?"improving":l<-J?"declining":"stable"}calculateAgentTrend(e,t){let n=t.end-t.start,i={start:t.start-n,end:t.start},r=this.getViolations({agentId:e,startTime:i.start,endTime:i.end}),s=this.getViolations({agentId:e,startTime:t.start,endTime:t.end}),a=this.calculateOverallScore(r),l=this.calculateOverallScore(s)-a;return l>J?"improving":l<-J?"declining":"stable"}calculateTrendAnalysis(e){let t=e.end-e.start,n={start:e.start-t,end:e.start},i=this.getViolations({startTime:e.start,endTime:e.end}),r=this.getViolations({startTime:n.start,endTime:n.end}),s=this.calculateOverallScore(i),a=this.calculateOverallScore(r),o=i.length-r.length,l;return o>2?l="increasing":o<-2?l="decreasing":l="stable",{currentPeriodScore:s,previousPeriodScore:a,change:s-a,violationTrend:l}}generateRecommendations(e,t){let n=[],i=e.filter(a=>a.severity==="critical").length;i>0&&n.push(`URGENT: ${i} critical violation(s) require immediate attention.`);let r=e.filter(a=>!a.resolved).length;r>5&&n.push(`${r} violations remain unresolved. Consider allocating resources for resolution.`);for(let[a,o]of Object.entries(t.byGate))o<70&&n.push(`${a} compliance score is ${o.toFixed(1)}. Review ${a} configuration and add monitoring.`);for(let[a,o]of Object.entries(t.byAgent))o<60&&n.push(`Agent ${a} has low compliance score (${o.toFixed(1)}). Consider retraining or restricting permissions.`);let s=new Map;for(let a of e)s.set(a.type,(s.get(a.type)||0)+1);for(let[a,o]of s)o>=5&&n.push(`${a} violations occurred ${o} times. Investigate root cause and add preventive measures.`);return t.trend==="declining"&&n.push("Overall compliance trend is declining. Schedule a governance review meeting."),n.length===0&&n.push("Compliance is within acceptable parameters. Continue monitoring."),n}generateMarkdownReport(e){let t=[],n=new Date(e.generatedAt).toISOString();t.push("# Compliance Report"),t.push(""),t.push(`**Generated:** ${n}`),t.push(`**Period:** ${new Date(e.timeWindow.start).toISOString()} to ${new Date(e.timeWindow.end).toISOString()}`),t.push(""),t.push("## Executive Summary"),t.push(""),t.push("| Metric | Value |"),t.push("|--------|-------|"),t.push(`| Overall Score | ${e.summary.overallScore.toFixed(1)} |`),t.push(`| Total Violations | ${e.summary.totalViolations} |`),t.push(`| Critical Violations | ${e.summary.criticalViolations} |`),t.push(`| High Violations | ${e.summary.highViolations} |`),t.push(`| Resolution Rate | ${(e.summary.resolutionRate*100).toFixed(1)}% |`),t.push(`| Trend | ${e.summary.trend} |`),t.push(""),t.push("## Gate Compliance Scores"),t.push(""),t.push("| Gate | Score | Violations | Trend |"),t.push("|------|-------|------------|-------|");for(let[i,r]of Object.entries(e.gateScores))t.push(`| ${i} | ${r.score.toFixed(1)} | ${r.violations} | ${r.trend} |`);t.push(""),t.push("## Violations by Type"),t.push(""),t.push("| Type | Count |"),t.push("|------|-------|");for(let[i,r]of Object.entries(e.violationsByType))r>0&&t.push(`| ${i} | ${r} |`);t.push(""),t.push("## Violations by Severity"),t.push(""),t.push("| Severity | Count |"),t.push("|----------|-------|");for(let[i,r]of Object.entries(e.violationsBySeverity))t.push(`| ${i} | ${r} |`);if(t.push(""),e.agentRankings&&e.agentRankings.length>0){t.push("## Agent Compliance Rankings"),t.push(""),t.push("| Agent | Score | Violations | Trend |"),t.push("|-------|-------|------------|-------|");for(let i of e.agentRankings)t.push(`| ${i.agentId} | ${i.score.toFixed(1)} | ${i.violations} | ${i.trend} |`);t.push("")}if(e.trendAnalysis&&(t.push("## Trend Analysis"),t.push(""),t.push(`- **Current Period Score:** ${e.trendAnalysis.currentPeriodScore.toFixed(1)}`),t.push(`- **Previous Period Score:** ${e.trendAnalysis.previousPeriodScore.toFixed(1)}`),t.push(`- **Change:** ${e.trendAnalysis.change>0?"+":""}${e.trendAnalysis.change.toFixed(1)}`),t.push(`- **Violation Trend:** ${e.trendAnalysis.violationTrend}`),t.push("")),e.recommendations&&e.recommendations.length>0){t.push("## Recommendations"),t.push("");for(let i of e.recommendations)t.push(`- ${i}`);t.push("")}if(e.violations&&e.violations.length>0){t.push("## Recent Violations"),t.push("");for(let i of e.violations.slice(0,10)){let r=i.resolved?"RESOLVED":"OPEN",s=new Date(i.timestamp).toISOString();t.push(`### ${i.id}`),t.push(""),t.push(`- **Type:** ${i.type}`),t.push(`- **Severity:** ${i.severity}`),t.push(`- **Gate:** ${i.gate}`),t.push(`- **Status:** ${r}`),t.push(`- **Time:** ${s}`),i.agentId&&t.push(`- **Agent:** ${i.agentId}`),t.push(`- **Description:** ${i.description}`),i.proofEnvelopeId&&t.push(`- **Proof:** ${i.proofEnvelopeId}`),t.push("")}}return t.push("---"),t.push("*Report generated by Agentic QE Compliance Reporter*"),t.join(`
|
|
3
3
|
`)}groupBy(e,t){let n=D();for(let i of e){let r=String(i[t]);n[r]||(n[r]=[]),n[r].push(i)}return n}cleanupOldViolations(){let e=Date.now()-this.flags.retentionDays*24*60*60*1e3;for(let[t,n]of this.violations)n.timestamp<e&&this.violations.delete(t)}triggerAlert(e,t,n){let i={id:this.generateAlertId(),gate:e,message:t,severity:n,timestamp:Date.now(),currentScore:0,threshold:0};this.notifyAlertListeners(i)}notifyAlertListeners(e){for(let t of this.alertListeners)try{t(e)}catch{}}},R=new de;ae();W();var Ge=class c{actionHistory=new Map;throttledAgents=new Map;guidanceContinueGate=null;initialized=!1;db=null;persistCount=0;static KV_NAMESPACE="continue-gate-actions";static KV_KEY="snapshot";static PERSIST_INTERVAL=20;static KV_TTL=3600;async initialize(){if(!this.initialized){try{let t=await import("@claude-flow/guidance/continue-gate");if(t&&typeof t.createContinueGate=="function"){let n=h.getFlags().continueGate;this.guidanceContinueGate=t.createContinueGate({maxConsecutiveSteps:n.maxConsecutiveRetries*10,maxReworkRatio:n.reworkRatioThreshold,checkpointIntervalSteps:25}),console.log("[ContinueGateIntegration] Guidance ContinueGate loaded")}}catch{this.guidanceContinueGate=null}try{this.db=V(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(e){console.warn("[ContinueGateIntegration] DB init failed, using memory-only:",S(e)),this.db=null}this.initialized=!0}}async loadFromKv(){if(!this.db)return;let e=await this.db.kvGet(c.KV_KEY,c.KV_NAMESPACE);if(e){for(let[n,i]of e.actionHistory)this.actionHistory.set(n,i);let t=Date.now();for(let[n,i]of e.throttledAgents)i>t&&this.throttledAgents.set(n,i);console.log("[ContinueGateIntegration] Loaded state from DB")}}async persistSnapshot(){if(this.db)try{await this.db.kvSet(c.KV_KEY,{actionHistory:Array.from(this.actionHistory.entries()).map(([e,t])=>[e,t.slice(-50)]),throttledAgents:Array.from(this.throttledAgents.entries())},c.KV_NAMESPACE,c.KV_TTL)}catch(e){console.warn("[ContinueGateIntegration] Persist failed:",S(e))}}recordAction(e){if(!G())return;let t=this.actionHistory.get(e.agentId)||[];t.push(e),t.length>100&&t.shift(),this.actionHistory.set(e.agentId,t),this.persistCount++,this.persistCount%c.PERSIST_INTERVAL===0&&this.persistSnapshot().catch(()=>{})}async evaluate(e){if(!G())return{shouldContinue:!0};await this.initialize();let t=h.getFlags().continueGate,n=this.actionHistory.get(e)||[],i=this.throttledAgents.get(e);if(i&&Date.now()<i){let s=i-Date.now();return{shouldContinue:!v(),reason:`Agent throttled for ${Math.ceil(s/1e3)}s`,throttleMs:s,escalate:!1}}let r=this.localEvaluation(e,n,t);if(this.guidanceContinueGate&&r.shouldContinue&&!r.reason)try{let s=this.calculateReworkRatio(n.slice(-10)),a={stepNumber:n.length,totalToolCalls:n.length,reworkCount:n.filter(l=>!l.success).length,coherenceScore:1-s,uncertaintyScore:s,elapsedMs:n.length>0?Date.now()-n[0].timestamp:0,lastCheckpointStep:0,totalTokensUsed:0,budgetRemaining:{tokens:Number.MAX_SAFE_INTEGER,toolCalls:Math.max(0,t.maxConsecutiveRetries*10-n.length),timeMs:Math.max(0,t.idleTimeoutMs-(n.length>0?Date.now()-n[n.length-1].timestamp:0))},recentDecisions:[]},o=this.guidanceContinueGate.evaluateWithHistory(a);if(o.decision!=="continue")return this.mapGuidanceDecision(o,e)}catch{}return r}localEvaluation(e,t,n){if(t.length<2)return{shouldContinue:!0};let i=t.slice(-10),r=this.countConsecutiveIdentical(i);if(r>=n.maxConsecutiveRetries){let l=Math.min(r*1e3,3e4);return n.throttleOnExceed&&this.throttledAgents.set(e,Date.now()+l),this.logViolation(e,"consecutive_identical_actions",r),{shouldContinue:!v(),reason:`Agent exceeded max consecutive retries (${r}/${n.maxConsecutiveRetries})`,throttleMs:l,escalate:r>=n.maxConsecutiveRetries*2,consecutiveCount:r}}let s=this.calculateReworkRatio(i);if(s>n.reworkRatioThreshold)return n.throttleOnExceed&&this.throttledAgents.set(e,Date.now()+5e3),this.logViolation(e,"high_rework_ratio",s),{shouldContinue:!v(),reason:`Agent rework ratio too high (${(s*100).toFixed(1)}% > ${n.reworkRatioThreshold*100}%)`,throttleMs:5e3,escalate:s>.8,reworkRatio:s};let a=t[t.length-1],o=Date.now()-a.timestamp;return o>n.idleTimeoutMs?(this.logViolation(e,"idle_timeout",o),{shouldContinue:!v(),reason:`Agent idle for ${Math.ceil(o/1e3)}s (limit: ${n.idleTimeoutMs/1e3}s)`,escalate:!0}):{shouldContinue:!0}}countConsecutiveIdentical(e){if(e.length===0)return 0;let t=1,n=e[e.length-1].actionHash;for(let i=e.length-2;i>=0&&e[i].actionHash===n;i--)t++;return t}calculateReworkRatio(e){return e.length===0?0:e.filter(n=>!n.success).length/e.length}mapGuidanceDecision(e,t){let n=h.getFlags().continueGate,i=e.decision==="pause"||e.decision==="stop",r=!i,s=e.reasons.length>0?e.reasons.join("; "):void 0;if(i&&n.throttleOnExceed){let a=e.decision==="stop"?3e4:15e3;this.throttledAgents.set(t,Date.now()+a)}return{shouldContinue:r,reason:s,throttleMs:e.decision==="throttle"?5e3:e.decision==="pause"?15e3:e.decision==="stop"?3e4:void 0,escalate:i,reworkRatio:e.metrics.reworkRatio}}logViolation(e,t,n){h.getFlags().global.logViolations&&console.warn("[ContinueGate] Violation detected:",{agentId:e,violationType:t,value:n,timestamp:new Date().toISOString()})}clearThrottle(e){this.throttledAgents.delete(e)}clearHistory(e){this.actionHistory.delete(e),this.throttledAgents.delete(e)}getAgentStats(e){let t=this.actionHistory.get(e)||[],n=this.throttledAgents.get(e)||0,i=Date.now();return{actionCount:t.length,reworkRatio:this.calculateReworkRatio(t),isThrottled:n>i,throttleRemainingMs:Math.max(0,n-i)}}reset(){this.actionHistory.clear(),this.throttledAgents.clear()}},C=new Ge;function gt(c,e,t){let n=JSON.stringify({actionType:c,target:e,params:t}),i=0;for(let r=0;r<n.length;r++){let s=n.charCodeAt(r);i=(i<<5)-i+s,i=i&i}return i.toString(16)}function me(c,e,t,n,i){return{agentId:c,actionType:e,actionHash:gt(e,t,n),timestamp:Date.now(),success:i}}import{randomUUID as pt}from"node:crypto";var Ye={low:0,medium:.3,high:.5,critical:.7},he=class{agentMetrics=new Map;taskHistory=new Map;tierThresholds={...Ye};guidanceTrustSystem=null;initialized=!1;async initialize(){if(!this.initialized){try{let t=await import("@claude-flow/guidance/trust");t&&typeof t.createTrustSystem=="function"&&(this.guidanceTrustSystem=t.createTrustSystem({initialTrust:.7,allowDelta:.02,denyDelta:.05,warnDelta:.01,decayRate:.05,decayIntervalMs:3e5}),console.log("[TrustAccumulatorIntegration] Guidance TrustSystem loaded"))}catch{this.guidanceTrustSystem=null}this.initialized=!0}}recordTaskOutcome(e,t,n,i,r={}){if(!M())return;let s={taskId:`${e}-${Date.now()}`,taskType:t,success:n,durationMs:i,qualityScore:r.qualityScore,timestamp:Date.now(),errorType:r.errorType},a=this.taskHistory.get(e)||[];if(a.push(s),a.length>100&&a.shift(),this.taskHistory.set(e,a),this.updateAgentMetrics(e,s),this.guidanceTrustSystem)try{let l=n?"allow":"deny";this.guidanceTrustSystem.recordOutcome(e,l,`Task ${t}: ${n?"success":"failure"}`)}catch{}h.getFlags().trustAccumulator.autoTierAdjustment&&this.adjustTier(e)}getTrustScore(e){if(!M())return .7;let t=this.agentMetrics.get(e);return t?t.trustScore:.7}getTrustTier(e){if(!M())return"medium";let t=this.agentMetrics.get(e);return t?t.trustTier:"medium"}canHandleCriticalTask(e){if(!M())return!0;let t=h.getFlags().trustAccumulator;return this.getTrustScore(e)>=t.minTrustForCritical}getAgentMetrics(e){return M()&&this.agentMetrics.get(e)||null}selectBestAgent(e,t,n={}){if(!M()||t.length===0)return{selectedAgent:t[0]||null,confidence:.5,reason:"TrustAccumulator disabled or no agents available",alternatives:[]};let i=h.getFlags().trustAccumulator,r=n.requireCriticalTrust?i.minTrustForCritical:n.minTrustScore??0,s=t.map(l=>{let u=this.agentMetrics.get(l),d=this.calculateAgentScore(l,e,u);return{agentId:l,score:d,trustScore:u?.trustScore??.7,meetsMinTrust:(u?.trustScore??.7)>=r}}).filter(l=>l.meetsMinTrust).sort((l,u)=>u.score-l.score);if(s.length===0){if(v())return{selectedAgent:null,confidence:0,reason:`No agents meet minimum trust threshold (${r})`,alternatives:t.map(u=>({agentId:u,trustScore:this.getTrustScore(u),reason:"Trust score below threshold"}))};let l=t.map(u=>({agentId:u,score:this.calculateAgentScore(u,e,this.agentMetrics.get(u)),trustScore:this.getTrustScore(u)})).sort((u,d)=>d.score-u.score);return{selectedAgent:l[0]?.agentId||null,confidence:.3,reason:"No agents meet trust threshold, selected best available (non-strict mode)",alternatives:l.slice(1).map(u=>({agentId:u.agentId,trustScore:u.trustScore,reason:`Score: ${u.score.toFixed(3)}`}))}}let a=s[0],o=Math.min(1,a.score*1.2);return{selectedAgent:a.agentId,confidence:o,reason:`Selected based on combined score (trust: ${a.trustScore.toFixed(3)}, task fit: ${(a.score-a.trustScore*i.performanceWeight).toFixed(3)})`,alternatives:s.slice(1,4).map(l=>({agentId:l.agentId,trustScore:l.trustScore,reason:`Score: ${l.score.toFixed(3)}`}))}}adjustTier(e){if(!M())return;let t=this.agentMetrics.get(e);if(!t)return;let n=t.trustTier,i=this.calculateTier(t.trustScore);n!==i&&(t.trustTier=i,t.tierHistory.push({tier:i,timestamp:Date.now(),reason:`Trust score changed to ${t.trustScore.toFixed(3)}`}),t.tierHistory.length>20&&t.tierHistory.shift(),this.logTierChange(e,n,i,t.trustScore))}boostTrust(e,t,n){if(!M())return;let i=this.getOrCreateMetrics(e),r=i.trustScore;i.trustScore=Math.min(1,i.trustScore+t),i.lastUpdated=Date.now(),this.logTrustChange(e,r,i.trustScore,`Boost: ${n}`),h.getFlags().trustAccumulator.autoTierAdjustment&&this.adjustTier(e)}penalizeTrust(e,t,n){if(!M())return;let i=this.getOrCreateMetrics(e),r=i.trustScore;i.trustScore=Math.max(0,i.trustScore-t),i.lastUpdated=Date.now(),this.logTrustChange(e,r,i.trustScore,`Penalty: ${n}`),h.getFlags().trustAccumulator.autoTierAdjustment&&this.adjustTier(e)}getAllAgentMetrics(){return Array.from(this.agentMetrics.values())}getAgentsByTier(e){return Array.from(this.agentMetrics.entries()).filter(([t,n])=>n.trustTier===e).map(([t])=>t)}getTaskExperience(e){return this.agentMetrics.get(e)?.taskTypeExperience??new Map}setTierThresholds(e){this.tierThresholds={...this.tierThresholds,...e};for(let t of Array.from(this.agentMetrics.keys()))this.adjustTier(t)}reset(){this.agentMetrics.clear(),this.taskHistory.clear(),this.tierThresholds={...Ye}}resetAgent(e){this.agentMetrics.delete(e),this.taskHistory.delete(e)}updateAgentMetrics(e,t){let n=this.getOrCreateMetrics(e);n.totalTasks++,t.success&&n.successfulTasks++,n.successRate=n.successfulTasks/n.totalTasks;let i=.3,r=t.success?0:1,s=1-n.successRate;n.errorRate=i*r+(1-i)*s,n.totalTasks===1?n.avgDurationMs=t.durationMs:n.avgDurationMs=i*t.durationMs+(1-i)*n.avgDurationMs;let a=n.taskTypeExperience.get(t.taskType)||0;n.taskTypeExperience.set(t.taskType,a+1),this.recalculateTrustScore(n,t),n.lastUpdated=Date.now()}recalculateTrustScore(e,t){let n=h.getFlags().trustAccumulator,i=e.successRate,r=e.taskTypeExperience.get(t.taskType)||0,a=Math.min(1,r/20),o=t.qualityScore??(t.success?.7:.3),l=1-e.errorRate,u=(o+l)/2,d=n.performanceWeight*i+n.taskSimilarityWeight*a+n.capabilityMatchWeight*u;e.totalTasks===1?e.trustScore=d:e.trustScore=.2*d+(1-.2)*e.trustScore,e.trustScore=Math.max(0,Math.min(1,e.trustScore))}calculateAgentScore(e,t,n){let i=h.getFlags().trustAccumulator;if(!n)return .7*i.performanceWeight;let r=n.trustScore*i.performanceWeight,s=n.taskTypeExperience.get(t)||0,o=Math.min(.3,s*.03)*i.taskSimilarityWeight,l=(1-n.errorRate)*i.capabilityMatchWeight;return r+o+l}calculateTier(e){return e>=this.tierThresholds.critical?"critical":e>=this.tierThresholds.high?"high":e>=this.tierThresholds.medium?"medium":"low"}getOrCreateMetrics(e){let t=this.agentMetrics.get(e);return t||(t={agentId:e,trustScore:.7,trustTier:"high",totalTasks:0,successfulTasks:0,successRate:0,avgDurationMs:0,errorRate:0,taskTypeExperience:new Map,lastUpdated:Date.now(),tierHistory:[{tier:"high",timestamp:Date.now(),reason:"Initial tier assignment"}]},this.agentMetrics.set(e,t)),t}logTrustChange(e,t,n,i){h.getFlags().global.logViolations&&console.warn("[TrustAccumulator] Trust change:",{agentId:e,oldScore:t.toFixed(3),newScore:n.toFixed(3),change:(n-t).toFixed(3),reason:i,timestamp:new Date().toISOString()})}logTierChange(e,t,n,i){if(!h.getFlags().global.logViolations)return;let r=this.compareTiers(n,t)>0?"PROMOTED":"DEMOTED";console.warn(`[TrustAccumulator] Tier change (${r}):`,{agentId:e,oldTier:t,newTier:n,trustScore:i.toFixed(3),timestamp:new Date().toISOString()})}compareTiers(e,t){let n={low:0,medium:1,high:2,critical:3};return n[e]-n[t]}},Oe=new he;var ft=[{name:"ignore-instructions",category:"prompt-injection",pattern:/ignore\s+(all\s+)?(previous|prior|above|earlier)\s+(instructions?|rules?|guidelines?|prompts?)/i,severity:.9,description:"Attempts to override previous instructions",enabled:!0},{name:"system-prompt-override",category:"prompt-injection",pattern:/\[?(system|admin|root|sudo)\]?\s*[:>]\s*.{0,50}(override|bypass|ignore|forget|reset)/i,severity:.95,description:"Attempts to impersonate system prompt",enabled:!0},{name:"new-instructions",category:"prompt-injection",pattern:/your\s+(new|real|actual|true)\s+(instructions?|task|purpose|goal)\s+(are?|is)/i,severity:.85,description:"Attempts to redefine agent instructions",enabled:!0},{name:"disregard-previous",category:"prompt-injection",pattern:/(disregard|forget|omit|skip|delete)\s+(everything|all|anything)\s+(above|before|previous)/i,severity:.9,description:"Attempts to clear context",enabled:!0},{name:"prompt-leak",category:"prompt-injection",pattern:/(show|reveal|display|output|print|echo)\s+(your|the|my)?\s*(system\s*)?(prompt|instructions?|rules?|config)/i,severity:.8,description:"Attempts to extract system prompt",enabled:!0},{name:"dan-jailbreak",category:"jailbreak",pattern:/\b(DAN|do\s*anything\s*now|jailbreak|unrestricted|unfiltered)\b/i,severity:.95,description:"Known jailbreak attempt (DAN/unrestricted mode)",enabled:!0},{name:"developer-mode",category:"jailbreak",pattern:/(developer|debug|maintenance|test)\s*mode\s*(enabled?|on|active|activate)/i,severity:.9,description:"Attempts to enable developer/debug mode",enabled:!0},{name:"hypothetical-bypass",category:"jailbreak",pattern:/(hypothetically|in\s+theory|imagine\s+if|let's\s+say|what\s+if).{0,50}(no\s+rules?|no\s+restrictions?|anything|everything)/i,severity:.7,description:"Hypothetical scenario to bypass restrictions",enabled:!0},{name:"roleplay-bypass",category:"jailbreak",pattern:/(roleplay|role-play|pretend|act)\s*(as|like|that).{0,30}(no|without)\s*(restrictions?|limits?|rules?|ethics?)/i,severity:.85,description:"Roleplay scenario to bypass ethics",enabled:!0},{name:"pretend-you-are",category:"role-manipulation",pattern:/(pretend|imagine|act|behave)\s+(you\s+are|as\s+if\s+you're|like\s+you're|that\s+you're)/i,severity:.6,description:"Attempts to change agent identity",enabled:!0},{name:"you-are-now",category:"role-manipulation",pattern:/you\s+are\s+now\s+(a|an|the)?\s*[a-z]+/i,severity:.65,description:"Direct role reassignment attempt",enabled:!0},{name:"from-now-on",category:"role-manipulation",pattern:/from\s+now\s+on\s*(,\s*)?(you|your)\s+(will|are|should|must|have\s+to)/i,severity:.7,description:"Attempts to change future behavior",enabled:!0},{name:"persona-switch",category:"role-manipulation",pattern:/(switch|change|transform)\s*(to|into)\s*(a|an)?\s*(different|new|another)\s*(persona|character|role|identity)/i,severity:.75,description:"Attempts to switch persona",enabled:!0},{name:"api-key-request",category:"data-exfiltration",pattern:/(show|reveal|give|tell|output|display|print)\s*(me\s*)?(your|the|any)?\s*(api|access|secret)?\s*key/i,severity:.85,description:"Attempts to extract API keys",enabled:!0},{name:"credential-request",category:"data-exfiltration",pattern:/(show|reveal|give|tell|output)\s*(me\s*)?(the|your|any)?\s*(credentials?|passwords?|tokens?|secrets?)/i,severity:.9,description:"Attempts to extract credentials",enabled:!0},{name:"environment-dump",category:"data-exfiltration",pattern:/(dump|print|show|list|output)\s*(all\s*)?(environment|env)\s*(variables?)?/i,severity:.8,description:"Attempts to dump environment variables",enabled:!0},{name:"internal-state",category:"data-exfiltration",pattern:/(show|reveal|access|dump)\s*(your|the)?\s*(internal|hidden|private)\s*(state|data|memory|context)/i,severity:.75,description:"Attempts to access internal state",enabled:!0},{name:"shell-command",category:"command-injection",pattern:/[;\|\&`]\s*(rm|cat|wget|curl|nc|bash|sh|python|perl|ruby|eval|exec)\s+/i,severity:.95,description:"Shell command injection attempt",enabled:!0},{name:"sql-injection",category:"command-injection",pattern:/(['";]\s*(or|and|union|select|drop|delete|insert|update)\s+)/i,severity:.9,description:"SQL injection attempt",enabled:!0},{name:"path-traversal",category:"command-injection",pattern:/\.\.[\/\\]+/,severity:.7,description:"Path traversal attempt",enabled:!0},{name:"code-execution",category:"command-injection",pattern:/(eval|exec|system|popen|subprocess)\s*\(/i,severity:.85,description:"Code execution function call",enabled:!0},{name:"base64-encoded",category:"encoded-payload",pattern:/[A-Za-z0-9+\/]{50,}={0,2}/,severity:.5,description:"Potential base64 encoded payload",enabled:!0},{name:"unicode-escape",category:"encoded-payload",pattern:/(\\u[0-9a-fA-F]{4}){4,}/,severity:.6,description:"Unicode escape sequence (potential obfuscation)",enabled:!0},{name:"hex-encoded",category:"encoded-payload",pattern:/(\\x[0-9a-fA-F]{2}){8,}/,severity:.65,description:"Hex-encoded data (potential obfuscation)",enabled:!0},{name:"url-encoded",category:"encoded-payload",pattern:/(%[0-9a-fA-F]{2}){5,}/,severity:.55,description:"URL-encoded sequence (potential obfuscation)",enabled:!0}],ge=class{patterns=new Map;blocklist=new Map;stats=this.createEmptyStats();assessmentHistory=[];guidanceThreatDetector=null;guidanceCollusionDetector=null;initialized=!1;async initialize(){if(!this.initialized){for(let e of ft)this.patterns.set(e.name,e);this.initialized=!0;try{let t=await import("@claude-flow/guidance/adversarial");t&&typeof t.createThreatDetector=="function"&&(this.guidanceThreatDetector=t.createThreatDetector(),console.log("[AdversarialDefense] Guidance ThreatDetector loaded")),t&&typeof t.createCollusionDetector=="function"&&(this.guidanceCollusionDetector=t.createCollusionDetector(),console.log("[AdversarialDefense] Guidance CollusionDetector loaded"))}catch{this.guidanceThreatDetector=null,this.guidanceCollusionDetector=null}}}assessThreat(e,t){if(!E())return this.createSafeAssessment(e);let n=h.getFlags().adversarialDefense,i=this.detectInjectionPatterns(e),r=this.checkBlocklist(e);if(this.guidanceThreatDetector&&i.length===0)try{let d={agentId:t?.agentId||"",toolName:t?.taskType||""},m=this.guidanceThreatDetector.analyzeInput(e,d);if(m&&Array.isArray(m)&&m.length>0)for(let g of m)i.push({name:`guidance:${g.category||"unknown"}`,category:g.category||"custom",matched:g.description||"",position:0,severity:g.severity||.5,description:g.description||"Detected by guidance ThreatDetector"})}catch{}let s=0;if(i.length>0){let d=i.map(m=>m.severity).sort((m,g)=>g-m);s=d[0];for(let m=1;m<d.length;m++)s+=d[m]*Math.pow(.5,m);s=Math.min(1,s)}r.length>0&&(s=Math.min(1,s+.3));let a=this.shouldBlock({threatScore:s,detectedPatterns:i.map(d=>d.name),isBlocked:!1,recommendations:[],timestamp:Date.now(),assessmentId:""}),o=this.generateRecommendations(i,s,a),l;n.sanitizeInputs&&!a&&(l=this.sanitizeInput(e));let u={threatScore:s,detectedPatterns:i.map(d=>d.name),isBlocked:a,sanitizedInput:l,recommendations:o,timestamp:Date.now(),assessmentId:`assess-${pt()}`};return this.updateStats(u,i),this.assessmentHistory.push(u),this.assessmentHistory.length>1e3&&this.assessmentHistory.shift(),n.penalizeOnDetection&&t?.agentId&&i.length>0&&this.penalizeAgent(t.agentId,u),n.logDetections&&i.length>0&&this.logDetection(u,t),u}detectInjectionPatterns(e){if(!E())return[];let t=[],n=e.toLowerCase();for(let[i,r]of this.patterns){if(!r.enabled)continue;let s=r.pattern.exec(e)||r.pattern.exec(n);s&&(t.push({name:r.name,category:r.category,matched:s[0],position:s.index,severity:r.severity,description:r.description}),this.stats.patternMatchCounts[i]=(this.stats.patternMatchCounts[i]||0)+1)}return t}sanitizeInput(e){if(!E())return e;let t=e;for(let[i,r]of this.patterns)r.enabled&&r.severity>=.8&&(t=t.replace(r.pattern,"[REDACTED]"));t=t.replace(/[;\|\&`$]/g,""),t=t.replace(/\s{3,}/g," ");let n=1e4;return t.length>n&&(t=t.substring(0,n)+"...[TRUNCATED]"),this.stats.sanitizedInputs++,t}escapeSpecialCharacters(e){return e.replace(/[;&|`$]/g,t=>`\\${t}`).replace(/[']/g,"''").replace(/(?<!\\)\\/g,"\\\\")}shouldBlock(e){if(!E())return!1;let t=h.getFlags().adversarialDefense;return!!(e.threatScore>=t.blockThreshold||v()&&e.threatScore>=t.blockThreshold*.7)}addToBlocklist(e,t){E()&&this.blocklist.set(e.toLowerCase(),{pattern:e,reason:t,addedAt:Date.now(),matchCount:0})}removeFromBlocklist(e){this.blocklist.delete(e.toLowerCase())}checkBlocklist(e){let t=[],n=e.toLowerCase();for(let[i,r]of this.blocklist)n.includes(i)&&(r.matchCount++,t.push(r));return t}recordAgentInteraction(e,t,n){if(E()&&this.guidanceCollusionDetector)try{this.guidanceCollusionDetector.recordInteraction(e,t,n)}catch{}}detectCollusion(){if(!E())return null;if(this.guidanceCollusionDetector)try{return this.guidanceCollusionDetector.detectCollusion()}catch{}return null}penalizeAgent(e,t){if(!E())return;let i=.05+t.threatScore*.15;Oe.penalizeTrust(e,i,`Adversarial input detected: ${t.detectedPatterns.join(", ")} (score: ${t.threatScore.toFixed(2)})`),this.stats.agentPenalties++}addCustomPattern(e){let t={...e,category:e.category||"custom"};this.patterns.set(e.name,t)}removePattern(e){return this.patterns.delete(e)}setPatternEnabled(e,t){let n=this.patterns.get(e);return n?(n.enabled=t,!0):!1}getPattern(e){return this.patterns.get(e)}getAllPatterns(){return Array.from(this.patterns.values())}getPatternStats(){let e=Array.from(this.patterns.values()),t={"prompt-injection":0,jailbreak:0,"role-manipulation":0,"data-exfiltration":0,"command-injection":0,"encoded-payload":0,custom:0},n=0,i=0,r=0;for(let s of e)t[s.category]++,s.enabled?n++:i++,s.category==="custom"&&r++;return{totalPatterns:e.length,patternsByCategory:t,enabledPatterns:n,disabledPatterns:i,customPatterns:r}}getDefenseStats(){return{...this.stats}}getBlocklist(){return Array.from(this.blocklist.values())}getAssessmentHistory(e=100){return this.assessmentHistory.slice(-e)}reset(){this.patterns.clear(),this.blocklist.clear(),this.assessmentHistory=[],this.stats=this.createEmptyStats(),this.initialized=!1}resetStats(){this.stats=this.createEmptyStats()}createEmptyStats(){return{totalAssessments:0,blockedInputs:0,sanitizedInputs:0,averageThreatScore:0,patternMatchCounts:{},categoryBreakdown:{"prompt-injection":0,jailbreak:0,"role-manipulation":0,"data-exfiltration":0,"command-injection":0,"encoded-payload":0,custom:0},agentPenalties:0,lastAssessment:null}}createSafeAssessment(e){return{threatScore:0,detectedPatterns:[],isBlocked:!1,sanitizedInput:e,recommendations:[],timestamp:Date.now(),assessmentId:`safe-${Date.now()}`}}updateStats(e,t){this.stats.totalAssessments++,e.isBlocked&&this.stats.blockedInputs++;let n=this.stats.totalAssessments;this.stats.averageThreatScore=(this.stats.averageThreatScore*(n-1)+e.threatScore)/n;for(let i of t)this.stats.categoryBreakdown[i.category]++;this.stats.lastAssessment=e.timestamp}generateRecommendations(e,t,n){let i=[];if(n&&(i.push("Input blocked due to high threat score"),i.push("Review input source and sanitize before retry")),t>=.7&&(i.push("Consider additional input validation"),i.push("Log this attempt for security review")),e.length>0){let r=new Set(e.map(s=>s.category));r.has("prompt-injection")&&(i.push("Implement input boundary markers"),i.push("Use separate instruction and data channels")),r.has("jailbreak")&&(i.push("Monitor for repeated jailbreak attempts"),i.push("Consider rate limiting this user")),r.has("role-manipulation")&&(i.push("Validate agent identity constraints"),i.push("Prevent role switching via user input")),r.has("command-injection")&&(i.push("Never pass user input directly to command execution"),i.push("Use parameterized commands or allowlists")),r.has("data-exfiltration")&&(i.push("Audit access to sensitive data"),i.push("Implement principle of least privilege")),r.has("encoded-payload")&&(i.push("Decode and validate payloads before processing"),i.push("Consider rejecting deeply encoded inputs")),i.length===0&&i.push("Review input for potential security issues")}return i}logDetection(e,t){h.getFlags().global.logViolations&&console.warn("[AdversarialDefense] Threat detected:",{assessmentId:e.assessmentId,threatScore:e.threatScore.toFixed(3),patterns:e.detectedPatterns,isBlocked:e.isBlocked,agentId:t?.agentId,taskType:t?.taskType,source:t?.source,timestamp:new Date().toISOString()})}},O=new ge;O.initialize().catch(()=>{});function pe(c){return O.initialized||O.initialize(),O.assessThreat(c)}function Fe(c){return O.initialized||O.initialize(),O.sanitizeInput(c)}import*as ne from"fs";import*as Y from"path";var Xe={enabled:!0,strictEnforcement:!1,escalateViolations:!0,constitutionPath:".claude/guidance/constitution.md",logAllChecks:!0},fe=class{invariants=new Map;initialized=!1;constitutionLoaded=!1;flags;stats={totalChecks:0,passedChecks:0,failedChecks:0,blockedViolations:0,escalations:0,checksByInvariant:{},lastCheckTimestamp:null,passRate:1};escalationCallbacks=new Set;gateIntegrations=new Map;constructor(e){this.flags={...Xe,...e}}async initialize(){if(!this.initialized){this.loadDefaultInvariants();try{await this.loadConstitution()}catch{this.flags.logAllChecks&&console.warn("[ConstitutionalEnforcer] Could not load constitution file, using defaults")}this.initialized=!0}}isInitialized(){return this.initialized}loadDefaultInvariants(){let e=[{id:"test-execution-integrity",name:"Test Execution Integrity",description:"Claims of test success require execution proof",condition:"IF task.claims_tests_passed THEN EXISTS execution_proof",enforcement:"ContinueGate blocks claims without execution proof",enabled:!0},{id:"security-scan-required",name:"Security Scan Requirement",description:"Auth/security code changes require security scan",condition:"IF change.affects_auth_code THEN EXISTS security_scan WITH status=complete AND critical_vulnerabilities=0",enforcement:"Quality gates block deployment without security scan",enabled:!0},{id:"backup-before-delete",name:"Backup Before Delete",description:"Destructive operations require verified backup",condition:"IF operation.type=delete AND target IN protected_files THEN EXISTS backup.verified=true",enforcement:"MemoryWriteGate blocks destructive operations without backup",enabled:!0},{id:"loop-detection",name:"Loop Detection",description:"Agents must not exceed retry or rework limits",condition:"agent.consecutive_identical_actions < 3 AND agent.rework_ratio < 0.5",enforcement:"ContinueGate throttles or blocks agents exceeding limits",enabled:!0},{id:"budget-enforcement",name:"Budget Enforcement",description:"Sessions must not exceed budget limits",condition:"session.total_cost <= budget_limit AND session.token_usage <= token_limit",enforcement:"BudgetMeter blocks operations exceeding budget",enabled:!0},{id:"memory-consistency",name:"Memory Consistency",description:"No contradictory patterns without supersession",condition:"NOT EXISTS conflicting_pattern WHERE supersession_marker IS NULL",enforcement:"MemoryWriteGate blocks contradictory patterns",enabled:!0},{id:"verification-before-claim",name:"Verification Before Claim",description:"All success claims require verification proof",condition:"FOR ALL claim IN success_claims: EXISTS verification.result=passed",enforcement:"All success claims require proof of verification",enabled:!0}];for(let t of e)this.invariants.set(t.id,t),this.stats.checksByInvariant[t.id]={passed:0,failed:0}}async loadConstitution(e){let t=e||this.flags.constitutionPath,n=t;if(!Y.isAbsolute(t)){let r=[Y.join(process.cwd(),t),Y.join(process.cwd(),"..",t),Y.join(process.cwd(),"../..",t)];for(let s of r)if(ne.existsSync(s)){n=s;break}}if(!ne.existsSync(n))throw new Error(`Constitution file not found: ${n}`);let i=ne.readFileSync(n,"utf-8");this.parseConstitution(i),this.constitutionLoaded=!0}parseConstitution(e){let t=/### Invariant (\d+): ([^\n]+)\n+```\n([\s\S]*?)```\n+\*\*Enforcement\*\*: ([^\n]+)/g,n;for(;(n=t.exec(e))!==null;){let[,i,r,s,a]=n,o=this.generateInvariantId(r),l=this.invariants.get(o);l&&(l.condition=s.trim(),l.enforcement=a.trim())}}generateInvariantId(e){return e.toLowerCase().replace(/\s+/g,"-")}getInvariants(){return Array.from(this.invariants.values())}getInvariant(e){return this.invariants.get(e)||null}setInvariantEnabled(e,t){let n=this.invariants.get(e);n&&(n.enabled=t)}checkInvariant(e,t){let n=this.invariants.get(e);if(!n)return this.createCheck(e,!1,t,`Unknown invariant: ${e}`);if(!n.enabled)return this.createCheck(e,!0,t);switch(e){case"test-execution-integrity":return this.checkTestExecutionIntegrity(t.taskId,t.claimsTestsPassed,t.executionProof);case"security-scan-required":return this.checkSecurityScanRequirement(t.changeId,t.affectsAuthCode,t.securityScan);case"backup-before-delete":return this.checkBackupBeforeDelete(t.operation,t.backup);case"loop-detection":return this.checkLoopDetection(t.agentId,t.stats);case"budget-enforcement":return this.checkBudgetEnforcement(t.sessionCost,t.sessionTokens);case"memory-consistency":return this.checkMemoryConsistency(t.pattern,t.existingPatterns);case"verification-before-claim":return this.checkVerificationBeforeClaim(t.claimId,t.verification);default:return this.createCheck(e,!0,t)}}checkAllInvariants(e){let t=[];for(let n of this.invariants.values())if(n.enabled){let i=this.checkInvariant(n.id,e);t.push(i)}return t}checkTestExecutionIntegrity(e,t,n){let i={taskId:e,claimsTestsPassed:t,hasProof:!!n};return t?n?n.taskId!==e?this.createCheck("test-execution-integrity",!1,i,`Execution proof task_id (${n.taskId}) does not match claim task_id (${e})`,"Ensure execution proof is for the correct task"):n.allTestsExecuted?n.timestamp?this.createCheck("test-execution-integrity",!0,i):this.createCheck("test-execution-integrity",!1,i,"Execution proof missing timestamp","Include timestamp in execution proof"):this.createCheck("test-execution-integrity",!1,i,"Execution proof indicates not all tests were executed","Execute all tests before claiming success"):this.createCheck("test-execution-integrity",!1,i,"Test success claimed without execution proof","Provide ExecutionProof with task_id matching the claim and all_tests_executed=true"):this.createCheck("test-execution-integrity",!0,i)}checkSecurityScanRequirement(e,t,n){let i={changeId:e,affectsAuthCode:t,hasScan:!!n};return t?n?n.changeId!==e?this.createCheck("security-scan-required",!1,i,`Security scan change_id (${n.changeId}) does not match (${e})`,"Ensure security scan is for the correct change"):n.status!=="complete"?this.createCheck("security-scan-required",!1,i,`Security scan status is ${n.status}, not complete`,"Wait for security scan to complete"):n.criticalVulnerabilities>0?this.createCheck("security-scan-required",!1,i,`Security scan found ${n.criticalVulnerabilities} critical vulnerabilities`,"Fix all critical vulnerabilities before deploying"):this.createCheck("security-scan-required",!0,i):this.createCheck("security-scan-required",!1,i,"Auth/security code change without security scan","Run security scan before deploying auth-related changes"):this.createCheck("security-scan-required",!0,i)}checkBackupBeforeDelete(e,t){let n={operation:e,hasBackup:!!t};return!e||!e.target?this.createCheck("backup-before-delete",!0,n):["memory.db","coverage/",".db"].some(s=>e.target.includes(s))?t?t.source!==e.target?this.createCheck("backup-before-delete",!1,n,`Backup source (${t.source}) does not match delete target (${e.target})`,"Create backup for the correct target"):t.timestamp>=e.timestamp?this.createCheck("backup-before-delete",!1,n,"Backup timestamp is after operation timestamp","Create backup before starting delete operation"):t.verified?this.createCheck("backup-before-delete",!0,n):this.createCheck("backup-before-delete",!1,n,"Backup is not verified","Verify backup integrity before proceeding"):this.createCheck("backup-before-delete",!1,n,`Delete operation on protected target (${e.target}) without backup`,"Create and verify backup before deleting protected files"):this.createCheck("backup-before-delete",!0,n)}checkLoopDetection(e,t){let n={agentId:e,stats:t};if(!t)return this.createCheck("loop-detection",!0,n);let i=h.getFlags().continueGate.maxConsecutiveRetries,r=h.getFlags().continueGate.reworkRatioThreshold;return t.consecutiveIdenticalActions>=i?this.createCheck("loop-detection",!1,n,`Agent ${e} exceeded max consecutive retries (${t.consecutiveIdenticalActions}/${i})`,"Break the loop by trying a different approach or escalating"):t.reworkRatio>r?this.createCheck("loop-detection",!1,n,`Agent ${e} rework ratio too high (${(t.reworkRatio*100).toFixed(1)}% > ${r*100}%)`,"Review agent strategy or reassign task"):this.createCheck("loop-detection",!0,n)}checkBudgetEnforcement(e,t){let n={sessionCost:e,sessionTokens:t},i=h.getFlags().budgetMeter;return e>i.maxSessionCostUsd?this.createCheck("budget-enforcement",!1,n,`Session cost ($${e.toFixed(2)}) exceeds limit ($${i.maxSessionCostUsd})`,"Stop current operations or request budget increase"):t>i.maxTokensPerSession?this.createCheck("budget-enforcement",!1,n,`Session tokens (${t}) exceeds limit (${i.maxTokensPerSession})`,"Optimize token usage or request limit increase"):this.createCheck("budget-enforcement",!0,n)}checkMemoryConsistency(e,t){let n={patternKey:e?.key,domain:e?.domain};if(!e||!t)return this.createCheck("memory-consistency",!0,n);let i=t.filter(r=>r.domain===e.domain);for(let r of i)if(r.key===e.key&&!e.supersessionMarker&&JSON.stringify(r.value)!==JSON.stringify(e.value))return this.createCheck("memory-consistency",!1,{...n,conflictingPattern:r.key},`Pattern ${e.key} contradicts existing pattern without supersession marker`,"Add supersession marker to explicitly replace the old pattern");return this.createCheck("memory-consistency",!0,n)}checkVerificationBeforeClaim(e,t){let n={claimId:e,hasVerification:!!t};return t?t.claimId!==e?this.createCheck("verification-before-claim",!1,n,`Verification claim_id (${t.claimId}) does not match (${e})`,"Ensure verification is for the correct claim"):["test_execution","manual_review","automated_check"].includes(t.method)?t.result!=="passed"?this.createCheck("verification-before-claim",!1,n,`Verification result is ${t.result}, not passed`,"Cannot claim success with pending or failed verification"):this.createCheck("verification-before-claim",!0,n):this.createCheck("verification-before-claim",!1,n,`Invalid verification method: ${t.method}`,"Use one of: test_execution, manual_review, automated_check"):this.createCheck("verification-before-claim",!1,n,`Success claim ${e} made without verification`,"Provide verification through test_execution, manual_review, or automated_check")}enforceInvariant(e){let t={blocked:!1,escalated:!1};return e.passed||(this.shouldBlock(e)&&(t.blocked=!0,t.reason=e.violationDetails,this.stats.blockedViolations++,this.flags.logAllChecks&&console.warn(`[ConstitutionalEnforcer] BLOCKED: ${e.invariantId}`,{violation:e.violationDetails,context:e.context})),this.flags.escalateViolations&&(this.escalateViolation(e),t.escalated=!0,this.stats.escalations++)),t}shouldBlock(e){if(!e.passed&&(this.flags.strictEnforcement||v()))return!0;let t=["test-execution-integrity","security-scan-required","budget-enforcement"];return!!(!e.passed&&t.includes(e.invariantId))}escalateViolation(e){e.passed||(this.flags.logAllChecks&&console.warn(`[ConstitutionalEnforcer] ESCALATION: ${e.invariantId}`,{violation:e.violationDetails,recommendation:e.recommendation}),this.escalationCallbacks.forEach(t=>{try{t(e)}catch(n){console.error("[ConstitutionalEnforcer] Escalation callback error:",n)}}))}onEscalation(e){return this.escalationCallbacks.add(e),()=>this.escalationCallbacks.delete(e)}integrateWithGate(e,t){this.gateIntegrations.set(e,t)}runGateChecks(){let e=[];for(let[t,n]of this.gateIntegrations)try{let i=n();e.push(i)}catch(i){console.error(`[ConstitutionalEnforcer] Gate check error for ${t}:`,i)}return e}getEnforcementStats(){return{...this.stats,passRate:this.stats.totalChecks>0?this.stats.passedChecks/this.stats.totalChecks:1}}resetStats(){this.stats={totalChecks:0,passedChecks:0,failedChecks:0,blockedViolations:0,escalations:0,checksByInvariant:{},lastCheckTimestamp:null,passRate:1};for(let e of this.invariants.keys())this.stats.checksByInvariant[e]={passed:0,failed:0}}createCheck(e,t,n,i,r){let s={invariantId:e,passed:t,context:n,timestamp:Date.now(),violationDetails:i,recommendation:r};return this.stats.totalChecks++,this.stats.lastCheckTimestamp=s.timestamp,t?this.stats.passedChecks++:this.stats.failedChecks++,this.stats.checksByInvariant[e]||(this.stats.checksByInvariant[e]={passed:0,failed:0}),t?this.stats.checksByInvariant[e].passed++:this.stats.checksByInvariant[e].failed++,this.flags.logAllChecks&&!t&&console.warn(`[ConstitutionalEnforcer] Check failed: ${e}`,{violationDetails:i,recommendation:r}),s}getFlags(){return{...this.flags}}updateFlags(e){this.flags={...this.flags,...e}}reset(){this.invariants.clear(),this.gateIntegrations.clear(),this.escalationCallbacks.clear(),this.initialized=!1,this.constitutionLoaded=!1,this.resetStats()}},X=new fe;var _e=class{initialized=!1;sessionCost=0;sessionTokens=0;escalationCallbacks=new Set;async initialize(){this.initialized||(await C.initialize(),this.initialized=!0,console.log("[QueenGovernance] Initialized with flags:",{continueGate:G(),memoryWriteGate:U(),budgetMeter:ce(),strictMode:v()}))}async beforeTaskExecution(e){let t={allowed:!0};if(E()&&e.payload){let i=JSON.stringify(e.payload),r=pe(i);if(t.threatAssessment=r,r.isBlocked&&(x()&&R.recordViolation({type:"adversarial_detected",severity:r.threatScore>.7?"critical":"high",agentId:e.agentId,gate:"adversarialDefense",description:`Adversarial threat detected in task ${e.taskId}: ${r.detectedPatterns.join(", ")}`,context:{taskId:e.taskId,threatScore:r.threatScore,detectedPatterns:r.detectedPatterns,domain:e.domain}}),console.warn("[QueenGovernance] Adversarial threat detected:",{taskId:e.taskId,agentId:e.agentId,threatScore:r.threatScore,patterns:r.detectedPatterns}),v()))return{allowed:!1,reason:`Adversarial threat detected: ${r.detectedPatterns.join(", ")}`,threatAssessment:r}}if(!G())return t;C.recordAction(me(e.agentId,`task:${e.taskType}`,e.domain,{taskId:e.taskId,retryCount:e.retryCount||0},!0));let n=await C.evaluate(e.agentId);if(!n.shouldContinue)return x()&&R.recordViolation({type:"loop_detected",severity:"high",agentId:e.agentId,gate:"continueGate",description:`Agent ${e.agentId} loop detected in task ${e.taskId}: ${n.reason}`,context:{taskId:e.taskId,reason:n.reason,throttleMs:n.throttleMs}}),n.escalate&&h.getFlags().global.escalateToQueen&&this.triggerEscalation(e,n.reason||"Unknown"),{...t,allowed:!1,reason:n.reason,throttleMs:n.throttleMs,escalate:n.escalate,agentStats:C.getAgentStats(e.agentId)};if(ce()){let i=this.checkBudget();if(!i.allowed)return x()&&R.recordViolation({type:"budget_exceeded",severity:"high",agentId:e.agentId,gate:"budgetMeter",description:`Budget exceeded for task ${e.taskId}: ${i.reason}`,context:{taskId:e.taskId,reason:i.reason,sessionCost:this.sessionCost,sessionTokens:this.sessionTokens}}),{...t,allowed:!1,reason:i.reason}}return{...t,allowed:!0,agentStats:C.getAgentStats(e.agentId)}}async afterTaskExecution(e,t,n,i,r){if(C.recordAction(me(e.agentId,`task-result:${e.taskType}`,e.domain,{taskId:e.taskId,success:t},t)),n!==void 0&&(this.sessionCost+=n),i!==void 0&&(this.sessionTokens+=i),K()&&r){let s=r.passed>0&&r.failed===0,a=s?{taskId:e.taskId,allTestsExecuted:!0,timestamp:Date.now(),passed:r.passed,failed:r.failed,skipped:r.skipped}:void 0,o=X.checkTestExecutionIntegrity(e.taskId,s,a);o.passed||(console.warn("[QueenGovernance] Constitutional invariant violation:",{invariantId:o.invariantId,taskId:e.taskId,violation:o.violationDetails}),x()&&R.recordViolation({type:"invariant_violated",severity:"critical",agentId:e.agentId,gate:"constitutionalEnforcer",description:`Test execution integrity violation for task ${e.taskId}: ${o.violationDetails}`,context:{taskId:e.taskId,invariantId:o.invariantId,violationDetails:o.violationDetails,recommendation:o.recommendation}}))}if(K()&&t){let s={claimId:e.taskId,method:"automated_check",result:"passed",timestamp:Date.now(),evidence:`Task ${e.taskId} completed by agent ${e.agentId}`},a=X.checkVerificationBeforeClaim(e.taskId,s);a.passed||(console.warn("[QueenGovernance] Claim without verification:",{invariantId:a.invariantId,taskId:e.taskId,violation:a.violationDetails}),x()&&R.recordViolation({type:"invariant_violated",severity:"high",agentId:e.agentId,gate:"constitutionalEnforcer",description:`Verification-before-claim violation for task ${e.taskId}: ${a.violationDetails}`,context:{taskId:e.taskId,invariantId:a.invariantId,violationDetails:a.violationDetails}}))}!t&&(e.retryCount||0)>=2&&C.getAgentStats(e.agentId).reworkRatio>.5&&this.triggerEscalation(e,`High failure rate after ${e.retryCount} retries`)}async beforeMemoryWrite(e){if(!U())return{allowed:!0};let t=Pe(e.key,e.value,e.domain,{agentId:e.agentId,tags:e.tags,supersedes:e.supersedes});return Q.evaluateWrite(t)}registerPattern(e){let t=Pe(e.key,e.value,e.domain,{agentId:e.agentId,tags:e.tags});Q.registerPattern(t)}onAgentAction(e){G()&&C.recordAction(me(e.agentId,e.actionType,e.target,e.params,e.success))}validateUserInput(e,t){if(!E())return{safe:!0,sanitized:e};let n=pe(e),i=Fe(e);return n.isBlocked&&x()&&R.recordViolation({type:"adversarial_detected",severity:n.threatScore>.7?"critical":"high",agentId:t?.agentId||"unknown",gate:"adversarialDefense",description:`Adversarial input detected from ${t?.source||"user_input"}: ${n.detectedPatterns.join(", ")}`,context:{source:t?.source||"user_input",threatScore:n.threatScore,detectedPatterns:n.detectedPatterns}}),{safe:!n.isBlocked,sanitized:i,threatAssessment:n}}async checkSecurityScanRequired(e,t,n){if(!K())return{allowed:!0};let i=X.checkSecurityScanRequirement(e,t,n);return!i.passed&&(x()&&R.recordViolation({type:"invariant_violated",severity:"critical",gate:"constitutionalEnforcer",description:`Security scan required for change ${e}: ${i.violationDetails}`,context:{invariantId:i.invariantId,changeId:e,affectsAuthCode:t,violationDetails:i.violationDetails}}),v())?{allowed:!1,reason:i.violationDetails}:{allowed:!0}}async checkBackupRequired(e,t){if(!K())return{allowed:!0};let n={type:"delete",target:e,timestamp:Date.now()},i=X.checkBackupBeforeDelete(n,t);return!i.passed&&(x()&&R.recordViolation({type:"invariant_violated",severity:"high",gate:"constitutionalEnforcer",description:`Backup required before delete of ${e}: ${i.violationDetails}`,context:{invariantId:i.invariantId,targetPath:e,violationDetails:i.violationDetails}}),v())?{allowed:!1,reason:i.violationDetails}:{allowed:!0}}getComplianceReport(){if(!x())return null;let e=R.getComplianceStats(),t=R.getViolations(),n;return e.currentScore>=90?n="A":e.currentScore>=80?n="B":e.currentScore>=70?n="C":e.currentScore>=60?n="D":n="F",{score:e.currentScore,grade:n,violations:t}}isAgentThrottled(e){return C.getAgentStats(e).isThrottled}getThrottleRemaining(e){return C.getAgentStats(e).throttleRemainingMs}clearAgentThrottle(e){C.clearThrottle(e)}onEscalation(e){return this.escalationCallbacks.add(e),()=>this.escalationCallbacks.delete(e)}checkBudget(){let e=h.getFlags().budgetMeter;if(this.sessionCost>=e.maxSessionCostUsd)return{allowed:!v(),reason:`Session cost limit exceeded ($${this.sessionCost.toFixed(2)} >= $${e.maxSessionCostUsd})`};if(this.sessionTokens>=e.maxTokensPerSession)return{allowed:!v(),reason:`Session token limit exceeded (${this.sessionTokens} >= ${e.maxTokensPerSession})`};let t=this.sessionCost/e.maxSessionCostUsd*100,n=this.sessionTokens/e.maxTokensPerSession*100;return(t>=e.warningThresholdPercent||n>=e.warningThresholdPercent)&&console.warn(`[QueenGovernance] Budget warning: ${Math.max(t,n).toFixed(1)}% consumed`),{allowed:!0}}triggerEscalation(e,t){console.warn("[QueenGovernance] Escalation triggered:",{agentId:e.agentId,taskId:e.taskId,domain:e.domain,reason:t}),this.escalationCallbacks.forEach(n=>{try{n(e,t)}catch(i){console.error("[QueenGovernance] Escalation callback error:",i)}})}getStats(){let e=Q.getStats();return{sessionCost:this.sessionCost,sessionTokens:this.sessionTokens,memoryPatterns:e.totalPatterns,patternsByDomain:e.patternsByDomain}}async applyMemoryDecay(){return Q.applyTemporalDecay()}reset(){C.reset(),Q.reset(),this.sessionCost=0,this.sessionTokens=0}enableStrictMode(){h.enableStrictMode()}disableAllGates(){h.disableAllGates()}},bn=new _e;var yt=[/\(\.\*\)\+/,/\(\.\+\)\+/,/\([^)]*?\?\)\+/,/\([^)]*?\*\)\+/,/\([^)]*?\+\)\+/,/\(\[[^\]]*\]\+\)\+/,/\(\[[^\]]*\]\*\)\+/,/\(\[[^\]]*\]\?\)\+/,/\(\[[^\]]*\]\*\)\*/,/\.\*\.\*/,/\.\+\.\+/,/\(\.\|\.\)/],vt=3;function bt(c){let e=0,t=0,n=!1,i=!1;for(let r=0;r<c.length;r++){let s=c[r];if(i){i=!1;continue}if(s==="\\"){i=!0;continue}if(s==="("){n=!0;continue}if(s===")"){n=!1;let a=c[r+1];(a==="*"||a==="+"||a==="?"||a==="{")&&(t++,e=Math.max(e,t));continue}(s==="*"||s==="+"||s==="?")&&!n&&(t=1,e=Math.max(e,t))}return e}function St(c){return[/\(\[^\\]*\]\+\)\+/,/\(\[^\\]*\]\*\)\*/,/\([^)]+\|[^)]+\)\+/,/\(\.\*\)[*+]/,/\(\.\+\)[*+]/].some(t=>t.test(c))}var $e=class{name="regex-safety";maxComplexity;constructor(e=vt){this.maxComplexity=e}getRiskLevel(){return"high"}validate(e,t={}){let{maxLength:n=1e4,maxComplexity:i=this.maxComplexity}=t;if(e.length>n)return{valid:!1,error:`Pattern exceeds maximum length of ${n}`,riskLevel:"medium"};let r=this.isRegexSafe(e,i);return{valid:r.safe,error:r.error,riskLevel:r.safe?"none":"high"}}isRegexSafe(e,t=this.maxComplexity){let n=[];for(let r of yt)r.test(e)&&n.push(r.source);let i=bt(e);return i>t&&n.push(`Quantifier nesting depth: ${i} (max: ${t})`),St(e)&&n.push("Exponential backtracking potential detected"),{safe:n.length===0,pattern:e,escapedPattern:this.escapeRegex(e),riskyPatterns:n,error:n.length>0?"Pattern may cause ReDoS":void 0}}escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}createSafeRegex(e,t,n=1e4){if(!this.isRegexSafe(e).safe||e.length>n)return null;try{return new RegExp(e,t)}catch{return null}}},Tt=new $e;var Ze=(c,e,t)=>Tt.createSafeRegex(c,e,t);function ye(){return h.getFlags().deterministicGateway??{enabled:!1,deduplicationWindowMs:5e3,cacheResultsForIdempotent:!0,validateSchemas:!0}}var Ne=class{requestHistory=new Map;resultCache=new Map;toolSchemas=new Map;guidanceGateway=null;initialized=!1;async initialize(){if(!this.initialized){this.registerDefaultSchemas(),this.initialized=!0;try{let t=await import("@claude-flow/guidance/gateway");t&&typeof t.createToolGateway=="function"&&(this.guidanceGateway=t.createToolGateway(),console.log("[DeterministicGateway] Guidance ToolGateway loaded"))}catch{this.guidanceGateway=null}}}registerDefaultSchemas(){this.registerToolSchema({toolName:"memory_store",params:{key:{type:"string",required:!0,minLength:1},value:{type:"object",required:!0},namespace:{type:"string",required:!1}},isIdempotent:!0,cacheableDurationMs:6e4}),this.registerToolSchema({toolName:"memory_retrieve",params:{key:{type:"string",required:!0,minLength:1},namespace:{type:"string",required:!1}},isIdempotent:!0,cacheableDurationMs:3e4}),this.registerToolSchema({toolName:"test_execute",params:{testFiles:{type:"array",required:!0},parallel:{type:"boolean",required:!1}},isIdempotent:!1}),this.registerToolSchema({toolName:"coverage_analyze",params:{target:{type:"string",required:!0},detectGaps:{type:"boolean",required:!1}},isIdempotent:!0,cacheableDurationMs:12e4}),this.registerToolSchema({toolName:"quality_assess",params:{target:{type:"string",required:!0},metrics:{type:"array",required:!1}},isIdempotent:!0,cacheableDurationMs:6e4})}registerToolSchema(e){this.toolSchemas.set(e.toolName,e)}async beforeToolCall(e,t,n){if(!le())return{allowed:!0};await this.initialize();let i=ye(),r=n||this.generateIdempotencyKey(e,t);if(this.cleanupExpiredEntries(),this.isDuplicate(r)){let s=this.requestHistory.get(r);return s.completed&&i.cacheResultsForIdempotent?(this.logEvent(e,"duplicate_with_cache",r),{allowed:!1,reason:"Duplicate request - returning cached result",cachedResult:s.result,isDuplicate:!0,idempotencyKey:r}):(this.logEvent(e,"duplicate_in_flight",r),{allowed:!v(),reason:"Duplicate request in-flight",isDuplicate:!0,idempotencyKey:r})}if(this.requestHistory.set(r,{idempotencyKey:r,toolName:e,params:t,timestamp:Date.now(),completed:!1}),i.validateSchemas){let s=this.validateParams(e,t);if(s.length>0)return this.logEvent(e,"validation_failed",r,s),{allowed:!v(),reason:`Schema validation failed: ${s.map(a=>a.message).join(", ")}`,validationErrors:s,idempotencyKey:r}}if(i.cacheResultsForIdempotent){let s=this.getCachedResult(r);if(s!==null)return this.logEvent(e,"cache_hit",r),{allowed:!1,reason:"Returning cached result for idempotent operation",cachedResult:s,idempotencyKey:r}}if(this.guidanceGateway&&typeof t=="object"&&t!==null)try{let s=this.guidanceGateway.evaluate(e,t);if(!s.allowed)return this.logEvent(e,"guidance_denied",r),{allowed:!v(),reason:`Guidance gateway: ${s.reason}`,idempotencyKey:r}}catch{}return{allowed:!0,idempotencyKey:r}}async afterToolCall(e,t,n){if(!le())return;let i=ye(),r=this.requestHistory.get(n);if(r&&(r.completed=!0,r.result=t),i.cacheResultsForIdempotent){let s=this.toolSchemas.get(e);if(s?.isIdempotent){let a=s.cacheableDurationMs||6e4;this.resultCache.set(n,{result:t,timestamp:Date.now(),toolName:e,expiresAt:Date.now()+a})}}}generateIdempotencyKey(e,t){let n=JSON.stringify({toolName:e,params:t},this.sortKeys);return this.hashString(n)}isDuplicate(e){let t=ye(),n=this.requestHistory.get(e);return n?Date.now()-n.timestamp<t.deduplicationWindowMs:!1}getCachedResult(e){let t=this.resultCache.get(e);return t?Date.now()>t.expiresAt?(this.resultCache.delete(e),null):t.result:null}validateParams(e,t){let n=this.toolSchemas.get(e);if(!n)return[];let i=[],r=typeof t=="object"&&t!==null?t:{};for(let[s,a]of Object.entries(n.params)){let o=r[s],l=this.validateValue(o,a,s);i.push(...l)}return i}validateValue(e,t,n){let i=[];if(t.required&&e==null)return i.push({path:n,message:`${n} is required`,expected:t.type,received:"undefined"}),i;if(e==null)return i;let r=Array.isArray(e)?"array":typeof e;if(r!==t.type)return i.push({path:n,message:`${n} must be of type ${t.type}`,expected:t.type,received:r}),i;if(t.type==="string"&&typeof e=="string"){t.minLength!==void 0&&e.length<t.minLength&&i.push({path:n,message:`${n} must be at least ${t.minLength} characters`,expected:`minLength: ${t.minLength}`,received:`length: ${e.length}`}),t.maxLength!==void 0&&e.length>t.maxLength&&i.push({path:n,message:`${n} must be at most ${t.maxLength} characters`,expected:`maxLength: ${t.maxLength}`,received:`length: ${e.length}`});let s=t.pattern?Ze(t.pattern):null;s&&!s.test(e)&&i.push({path:n,message:`${n} must match pattern ${t.pattern}`,expected:`pattern: ${t.pattern}`,received:e})}if(t.type==="number"&&typeof e=="number"&&(t.min!==void 0&&e<t.min&&i.push({path:n,message:`${n} must be at least ${t.min}`,expected:`min: ${t.min}`,received:`${e}`}),t.max!==void 0&&e>t.max&&i.push({path:n,message:`${n} must be at most ${t.max}`,expected:`max: ${t.max}`,received:`${e}`})),t.enum&&!t.enum.includes(e)&&i.push({path:n,message:`${n} must be one of: ${t.enum.join(", ")}`,expected:`enum: [${t.enum.join(", ")}]`,received:String(e)}),t.type==="array"&&Array.isArray(e)&&t.items&&e.forEach((s,a)=>{let o=this.validateValue(s,t.items,`${n}[${a}]`);i.push(...o)}),t.type==="object"&&typeof e=="object"&&t.properties){let s=e;for(let[a,o]of Object.entries(t.properties)){let l=this.validateValue(s[a],o,`${n}.${a}`);i.push(...l)}}return i}cleanupExpiredEntries(){let e=Date.now(),t=ye();for(let[n,i]of this.requestHistory){let r=e-i.timestamp;!i.completed&&r>t.deduplicationWindowMs?this.requestHistory.delete(n):i.completed&&r>t.deduplicationWindowMs*10&&this.requestHistory.delete(n)}for(let[n,i]of this.resultCache)e>i.expiresAt&&this.resultCache.delete(n)}logEvent(e,t,n,i){h.getFlags().global.logViolations&&console.info(`[DeterministicGateway] ${t}:`,{toolName:e,idempotencyKey:n.substring(0,16)+"...",eventType:t,details:i,timestamp:new Date().toISOString()})}sortKeys=(e,t)=>{if(t&&typeof t=="object"&&!Array.isArray(t)){let n={};for(let i of Object.keys(t).sort())n[i]=t[i];return n}return t};hashString(e){let t=0;for(let i=0;i<e.length;i++){let r=e.charCodeAt(i);t=(t<<5)-t+r,t=t&t}return`idem_${Math.abs(t).toString(16).padStart(8,"0")}`}getStats(){return{pendingRequests:[...this.requestHistory.values()].filter(t=>!t.completed).length,cachedResults:this.resultCache.size,registeredSchemas:this.toolSchemas.size,duplicatesPrevented:[...this.requestHistory.values()].filter(t=>t.completed).length}}clearCache(e){this.resultCache.delete(e),this.requestHistory.delete(e)}clearAllCaches(){this.resultCache.clear(),this.requestHistory.clear()}reset(){this.requestHistory.clear(),this.resultCache.clear(),this.toolSchemas.clear(),this.initialized=!1}getToolSchema(e){return this.toolSchemas.get(e)}isToolIdempotent(e){return this.toolSchemas.get(e)?.isIdempotent??!1}},kn=new Ne;ae();W();function F(){let c=h.getFlags();return c.global.enableAllGates?c.evolutionPipeline?.enabled??!1:!1}function ie(){return h.getFlags().evolutionPipeline??{enabled:!1,autoPromoteThreshold:.9,autoDemoteThreshold:.3,minSamplesForDecision:20,learningRate:.1}}var ve=class c{rules=new Map;variantTests=new Map;taskOutcomes=new Map;guidanceEvolution=null;initialized=!1;db=null;persistCount=0;static NAMESPACE="rule-evolution";static TTL_SECONDS=604800;static PERSIST_INTERVAL=10;stats={autoPromotions:0,autoDemotions:0,learningOutcomes:0};TIME_WINDOWS={HOUR:3600*1e3,DAY:1440*60*1e3,WEEK:10080*60*1e3};async initialize(){if(!this.initialized){try{this.db=V(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(e){console.warn("[EvolutionPipeline] DB init failed, using memory-only:",S(e)),this.db=null}try{let t=await import("@claude-flow/guidance/evolution");t&&typeof t.createEvolutionPipeline=="function"&&(this.guidanceEvolution=t.createEvolutionPipeline(),console.log("[EvolutionPipeline] Guidance EvolutionPipeline loaded"))}catch{this.guidanceEvolution=null}this.initialized=!0,this.logEvent("initialize","Evolution Pipeline initialized")}}recordRuleApplication(e,t,n){if(!F())return;let i=this.getOrCreateRuleRecord(e),r={ruleId:e,context:t,success:n,timestamp:Date.now()};i.applications.push(r),this.pruneApplicationHistory(i),this.checkAutoPromotionDemotion(e),this.persistSnapshot(),this.logEvent("rule_application",`Rule ${e} applied: ${n?"success":"failure"}`)}getRuleEffectiveness(e){let t=this.rules.get(e);if(!t)return this.createEmptyEffectiveness(e);let n=Date.now(),i=t.applications,r=i.filter(f=>n-f.timestamp<this.TIME_WINDOWS.HOUR),s=i.filter(f=>n-f.timestamp<this.TIME_WINDOWS.DAY),a=i.filter(f=>n-f.timestamp<this.TIME_WINDOWS.WEEK),o=i.length,l=i.filter(f=>f.success).length,u=o>0?l/o:0,d=this.calculateWilsonConfidenceInterval(l,o,.95),m=new Map,g=this.groupBy(i,f=>f.context.domain||"unknown");for(let[f,y]of Object.entries(g)){let w=y.filter(A=>A.success).length;m.set(f,{domain:f,applications:y.length,successes:w,successRate:y.length>0?w/y.length:0})}let p=new Map,b=this.groupBy(i,f=>f.context.taskType||"unknown");for(let[f,y]of Object.entries(b)){let w=y.filter(A=>A.success).length;p.set(f,{taskType:f,applications:y.length,successes:w,successRate:y.length>0?w/y.length:0})}let I=ie(),T=o>=I.minSamplesForDecision;return{ruleId:e,totalApplications:o,successfulApplications:l,successRate:u,successRate1h:this.calculateSuccessRate(r),successRate24h:this.calculateSuccessRate(s),successRate7d:this.calculateSuccessRate(a),confidenceInterval:d,isStatisticallySignificant:T,byDomain:m,byTaskType:p,promotionStatus:t.promotionStatus,lastUpdated:n}}promoteRule(e,t){if(!F())return;let n=this.getOrCreateRuleRecord(e),i=n.promotionStatus,r;switch(i){case"candidate":case"demoted":r="promoted";break;case"deprecated":r="candidate";break;default:r=i}if(r!==i){if(n.promotionStatus=r,n.promotionHistory.push({status:r,timestamp:Date.now(),reason:t}),this.guidanceEvolution)try{this.guidanceEvolution.propose({kind:"rule-promote",title:`Promote rule ${e}`,description:t,author:"aqe-evolution-pipeline",targetPath:`rules/${e}`,diff:{before:i,after:r},rationale:t,riskAssessment:{level:"low",factors:["automated-promotion"]}})}catch{}this.logEvent("rule_promotion",`Rule ${e} promoted: ${i} -> ${r}. Reason: ${t}`)}}demoteRule(e,t){if(!F())return;let n=this.getOrCreateRuleRecord(e),i=n.promotionStatus,r;switch(i){case"promoted":case"candidate":r="demoted";break;case"demoted":r="deprecated";break;default:r=i}if(r!==i){if(n.promotionStatus=r,n.promotionHistory.push({status:r,timestamp:Date.now(),reason:t}),this.guidanceEvolution)try{this.guidanceEvolution.propose({kind:"rule-remove",title:`Demote rule ${e}`,description:t,author:"aqe-evolution-pipeline",targetPath:`rules/${e}`,diff:{before:i,after:r},rationale:t,riskAssessment:{level:r==="deprecated"?"medium":"low",factors:["automated-demotion"]}})}catch{}this.logEvent("rule_demotion",`Rule ${e} demoted: ${i} -> ${r}. Reason: ${t}`)}}createVariant(e,t){if(!F())return`${e}-variant-disabled`;let n=this.rules.get(e),i=`${e}-variant-${Date.now()}`,r={ruleId:i,name:t.name||`${n?.name||e} (Variant)`,createdAt:Date.now(),promotionStatus:"variant",baseRuleId:e,applications:[],promotionHistory:[{status:"variant",timestamp:Date.now(),reason:`Variant created: ${t.changeDescription}`}]};return this.rules.set(i,r),this.logEvent("variant_created",`Variant ${i} created from ${e}: ${t.changeDescription}`),i}learnFromOutcome(e,t){if(F()){if(this.taskOutcomes.set(e,t),this.stats.learningOutcomes++,t.appliedRules&&t.appliedRules.length>0){let n={taskType:t.taskType};for(let i of t.appliedRules)this.recordRuleApplication(i,n,t.success)}if(this.taskOutcomes.size>1e4){let n=Array.from(this.taskOutcomes.entries()).sort((i,r)=>i[1].timestamp-r[1].timestamp).slice(0,1e3);for(let[i]of n)this.taskOutcomes.delete(i)}this.logEvent("learning_outcome",`Learned from task ${e}: ${t.success?"success":"failure"}`)}}suggestRuleOptimizations(){if(!F())return[];let e=[],t=ie();for(let[n,i]of Array.from(this.rules.entries())){let r=this.getRuleEffectiveness(n);if(r.isStatisticallySignificant){if(r.successRate<t.autoDemoteThreshold){e.push({ruleId:n,optimizationType:"deprecation",current:r.successRate,suggested:null,reasoning:`Rule has ${(r.successRate*100).toFixed(1)}% success rate (below ${(t.autoDemoteThreshold*100).toFixed(1)}% threshold)`,estimatedImprovement:1-r.successRate,confidence:Math.min(1,r.totalApplications/100)});continue}for(let[s,a]of Array.from(r.byDomain.entries()))a.applications>=10&&a.successRate>r.successRate+.1&&e.push({ruleId:n,optimizationType:"context_restriction",current:{domain:"all"},suggested:{domain:s},reasoning:`Rule performs ${((a.successRate-r.successRate)*100).toFixed(1)}% better in ${s} domain`,estimatedImprovement:a.successRate-r.successRate,confidence:Math.min(1,a.applications/50)});for(let[s,a]of Array.from(r.byTaskType.entries()))a.applications>=10&&a.successRate>r.successRate+.1&&e.push({ruleId:n,optimizationType:"context_restriction",current:{taskType:"all"},suggested:{taskType:s},reasoning:`Rule performs ${((a.successRate-r.successRate)*100).toFixed(1)}% better for ${s} tasks`,estimatedImprovement:a.successRate-r.successRate,confidence:Math.min(1,a.applications/50)})}}return e.sort((n,i)=>i.estimatedImprovement-n.estimatedImprovement),e}registerVariantTest(e,t){if(!F())return;if(t.length<2)throw new Error("A/B test requires at least 2 variants");let n={testId:e,variants:t,startTime:Date.now(),endTime:null,results:new Map,status:"running",winner:null,significanceAchieved:!1};for(let i of t)n.results.set(i,{variantId:i,applications:0,successes:0,successRate:0,avgDurationMs:0});this.variantTests.set(e,n),this.logEvent("variant_test_registered",`A/B test ${e} registered with ${t.length} variants`)}recordVariantOutcome(e,t,n,i){if(!F())return;let r=this.variantTests.get(e);if(!r){this.logEvent("variant_test_error",`A/B test ${e} not found`);return}if(r.status!=="running"){this.logEvent("variant_test_error",`A/B test ${e} is not running (status: ${r.status})`);return}let s=r.results.get(t);if(!s){this.logEvent("variant_test_error",`Variant ${t} not found in test ${e}`);return}s.applications++,n&&s.successes++,s.successRate=s.applications>0?s.successes/s.applications:0,i!==void 0&&(s.avgDurationMs=(s.avgDurationMs*(s.applications-1)+i)/s.applications),this.checkVariantTestSignificance(r)}getWinningVariant(e){let t=this.variantTests.get(e);return t?t.winner?t.winner:t.significanceAchieved?this.determineWinner(t):null:null}getActiveTests(){return Array.from(this.variantTests.values()).filter(e=>e.status==="running")}completeVariantTest(e){let t=this.variantTests.get(e);return t?(t.status="completed",t.endTime=Date.now(),t.winner=this.determineWinner(t),t.winner&&t.significanceAchieved&&this.promoteRule(t.winner,`Won A/B test ${e}`),this.logEvent("variant_test_completed",`A/B test ${e} completed. Winner: ${t.winner||"none"}`),t):null}cancelVariantTest(e){let t=this.variantTests.get(e);t&&(t.status="cancelled",t.endTime=Date.now(),this.logEvent("variant_test_cancelled",`A/B test ${e} cancelled`))}getEvolutionStats(){let e=Array.from(this.rules.values()),t=ie(),n={candidate:0,promoted:0,demoted:0,deprecated:0,variant:0,control:0},i=0,r=0,s=0,a=0;for(let u of e){n[u.promotionStatus]++;let d=this.getRuleEffectiveness(u.ruleId);d.totalApplications>0&&(a++,i+=d.successRate,d.successRate>=t.autoPromoteThreshold?r++:d.successRate<=t.autoDemoteThreshold&&s++)}let o=Array.from(this.variantTests.values()).filter(u=>u.status==="running").length,l=Array.from(this.variantTests.values()).filter(u=>u.status==="completed").length;return{totalRules:e.length,byStatus:n,activeTests:o,completedTests:l,autoPromotions:this.stats.autoPromotions,autoDemotions:this.stats.autoDemotions,learningOutcomes:this.stats.learningOutcomes,avgSuccessRate:a>0?i/a:0,aboveThreshold:r,belowThreshold:s}}getAllRules(){return Array.from(this.rules.values())}getRulesByStatus(e){return Array.from(this.rules.entries()).filter(([t,n])=>n.promotionStatus===e).map(([t])=>t)}reset(){this.rules.clear(),this.variantTests.clear(),this.taskOutcomes.clear(),this.stats={autoPromotions:0,autoDemotions:0,learningOutcomes:0},this.initialized=!1}resetRule(e){this.rules.delete(e)}async loadFromKv(){if(!this.db)return;let e=await this.db.kvGet("snapshot",c.NAMESPACE);if(e)for(let[t,n]of Object.entries(e))this.rules.set(t,n)}persistSnapshot(){if(this.db&&(this.persistCount++,this.persistCount%c.PERSIST_INTERVAL===0))try{let e=Object.fromEntries(this.rules);this.db.kvSet("snapshot",e,c.NAMESPACE,c.TTL_SECONDS).catch(()=>{})}catch(e){console.warn("[EvolutionPipeline] Persist failed:",S(e))}}getOrCreateRuleRecord(e){let t=this.rules.get(e);return t||(t={ruleId:e,name:e,createdAt:Date.now(),promotionStatus:"candidate",applications:[],promotionHistory:[{status:"candidate",timestamp:Date.now(),reason:"Initial creation"}]},this.rules.set(e,t)),t}createEmptyEffectiveness(e){return{ruleId:e,totalApplications:0,successfulApplications:0,successRate:0,successRate1h:0,successRate24h:0,successRate7d:0,confidenceInterval:{lower:0,upper:1},isStatisticallySignificant:!1,byDomain:new Map,byTaskType:new Map,promotionStatus:"candidate",lastUpdated:Date.now()}}calculateSuccessRate(e){return e.length===0?0:e.filter(n=>n.success).length/e.length}calculateWilsonConfidenceInterval(e,t,n){if(t===0)return{lower:0,upper:1};let i=n===.95?1.96:n===.99?2.576:1.645,r=e/t,s=t,a=1+i*i/s,o=r+i*i/(2*s),l=i*Math.sqrt((r*(1-r)+i*i/(4*s))/s),u=Math.max(0,(o-l)/a),d=Math.min(1,(o+l)/a);return{lower:u,upper:d}}checkAutoPromotionDemotion(e){let t=ie(),n=this.getRuleEffectiveness(e);if(!n.isStatisticallySignificant)return;let i=this.rules.get(e);i&&(n.successRate>=t.autoPromoteThreshold&&i.promotionStatus!=="promoted"&&i.promotionStatus!=="variant"&&(this.promoteRule(e,`Auto-promoted: ${(n.successRate*100).toFixed(1)}% success rate >= ${(t.autoPromoteThreshold*100).toFixed(1)}% threshold`),this.stats.autoPromotions++),n.successRate<=t.autoDemoteThreshold&&i.promotionStatus!=="demoted"&&i.promotionStatus!=="deprecated"&&(this.demoteRule(e,`Auto-demoted: ${(n.successRate*100).toFixed(1)}% success rate <= ${(t.autoDemoteThreshold*100).toFixed(1)}% threshold`),this.stats.autoDemotions++))}pruneApplicationHistory(e){let i=Date.now();e.applications=e.applications.filter(r=>i-r.timestamp<2592e6),e.applications.length>1e3&&(e.applications=e.applications.slice(-1e3))}groupBy(e,t){let n={};for(let i of e){let r=t(i);n[r]||(n[r]=[]),n[r].push(i)}return n}checkVariantTestSignificance(e){let t=ie(),n=Array.from(e.results.values());if(!n.every(l=>l.applications>=t.minSamplesForDecision))return;let r=n.reduce((l,u)=>l+u.applications,0),s=n.reduce((l,u)=>l+u.successes,0)/r,a=0;for(let l of n){let u=l.applications*s;if(u>0){let d=l.successes-u;a+=d*d/u}}let o=n.length===2?3.841:n.length===3?5.991:7.815;e.significanceAchieved=a>=o,e.significanceAchieved&&(e.winner=this.determineWinner(e),this.logEvent("variant_test_significant",`A/B test ${e.testId} achieved significance. Winner: ${e.winner}`))}determineWinner(e){let t=Array.from(e.results.values());if(t.length===0)return null;let n=t[0];for(let i of t)i.successRate>n.successRate&&(n=i);return n.variantId}logEvent(e,t){h.getFlags().global.logViolations&&console.info(`[EvolutionPipeline] ${e}:`,{message:t,timestamp:new Date().toISOString()})}},_=new ve;import{promises as et}from"fs";import*as Z from"path";W();var tt={"test-generation":["test-generation","generate-tests","tdd","property-testing","test-creation","unit-test","integration-test"],"test-execution":["test-execution","run-tests","test-run","parallel-testing","flaky-detection","retry"],"coverage-analysis":["coverage-analysis","coverage","gap-detection","coverage-report","uncovered-code"],"quality-assessment":["quality-assessment","quality-gate","quality-check","deployment-decision","release-validation"],"defect-intelligence":["defect-intelligence","defect-prediction","root-cause","bug-prediction","regression-risk"],"requirements-validation":["requirements-validation","bdd","gherkin","acceptance-criteria","requirements-check"],"code-intelligence":["code-intelligence","code-analysis","complexity-analysis","dependency-analysis","code-structure"],"security-compliance":["security-compliance","security-scan","sast","dast","vulnerability","owasp","compliance"],"contract-testing":["contract-testing","api-contract","consumer-driven","pact","schema-validation"],"visual-accessibility":["visual-accessibility","accessibility","a11y","wcag","visual-regression","screenshot"],"chaos-resilience":["chaos-resilience","chaos-testing","fault-injection","resilience","load-testing","performance"],"learning-optimization":["learning-optimization","pattern-learning","knowledge-transfer","experience-learning","optimization"]},nt={test:["test-generation","test-execution"],coverage:["coverage-analysis"],quality:["quality-assessment"],security:["security-compliance"],defect:["defect-intelligence"],bug:["defect-intelligence"],requirements:["requirements-validation"],bdd:["requirements-validation"],code:["code-intelligence"],analysis:["code-intelligence","coverage-analysis"],contract:["contract-testing"],api:["contract-testing"],accessibility:["visual-accessibility"],a11y:["visual-accessibility"],chaos:["chaos-resilience"],performance:["chaos-resilience"],learning:["learning-optimization"],pattern:["learning-optimization"],compliance:["security-compliance"],vulnerability:["security-compliance"]};function $(){let c=h.getFlags();return c.global.enableAllGates?c.shardRetriever?.enabled??!1:!1}function N(){return h.getFlags().shardRetriever??it}var it={enabled:!0,shardsPath:".claude/guidance/shards",cacheEnabled:!0,cacheTtlMs:300*1e3,maxShardsPerQuery:3,relevanceThreshold:.3},ee=class{shardCache=new Map;cacheHits=0;cacheMisses=0;lastCacheCleanup=null;parseErrors=[];guidanceRetriever=null;initialized=!1;basePath;constructor(e){this.basePath=e??process.cwd()}async initialize(){if(!this.initialized){if(!$()){this.initialized=!0;return}try{let t=await import("@claude-flow/guidance/retriever");t&&typeof t.createRetriever=="function"&&(this.guidanceRetriever=t.createRetriever(),console.log("[ShardRetrieverIntegration] Guidance ShardRetriever loaded"))}catch{this.guidanceRetriever=null}await this.loadAllShards(),this.initialized=!0}}async loadAllShards(){let e=new Map;if(!$())return e;let t=N(),n=Z.resolve(this.basePath,t.shardsPath);try{let r=(await et.readdir(n)).filter(s=>s.endsWith(".shard.md"));for(let s of r){let a=s.replace(".shard.md","");try{let o=await this.loadShardFromFile(Z.join(n,s));o&&(e.set(a,o),this.cacheShardIfEnabled(a,o))}catch(o){let l=`Failed to load shard ${s}: ${S(o)}`;this.parseErrors.push(l),this.logError(l)}}}catch(i){let r=`Failed to read shards directory: ${S(i)}`;this.parseErrors.push(r),this.logError(r)}return e}async loadShard(e){if(!$())return null;let t=this.getCachedShard(e);if(t)return this.cacheHits++,t;this.cacheMisses++;let n=N(),i=Z.resolve(this.basePath,n.shardsPath),r=Z.join(i,`${e}.shard.md`);try{let s=await this.loadShardFromFile(r);return s&&this.cacheShardIfEnabled(e,s),s}catch(s){return this.logError(`Failed to load shard for domain ${e}: ${S(s)}`),null}}async retrieveForTask(e,t){if(!$())return[];await this.initialize();let n=N(),i=await this.getAllCachedOrLoadedShards(),r=new Set;if(this.guidanceRetriever)try{let o=await this.guidanceRetriever.retrieve({taskDescription:`${e}: ${t.intent||""} ${(t.keywords||[]).join(" ")}`,maxShards:n.maxShardsPerQuery});if(o&&o.shards){for(let l of o.shards)if(l.shard?.rule?.domains)for(let u of l.shard.rule.domains)r.add(u)}}catch{}let s=[];for(let o of i.values()){let l=this.calculateRelevance(o,{...t,taskType:e});r.has(o.domain)&&(l=Math.min(1,l+.1)),l>=n.relevanceThreshold&&s.push({shard:o,score:l})}return s.sort((o,l)=>l.score-o.score),s.slice(0,n.maxShardsPerQuery).map(o=>o.shard)}async retrieveByIntent(e){if(!$())return[];await this.initialize();let t=N(),n=e.toLowerCase(),i=new Set;for(let[s,a]of Object.entries(nt))n.includes(s)&&a.forEach(o=>i.add(o));for(let s of Object.keys(tt))n.includes(s)&&i.add(s);let r=[];for(let s of i){let a=await this.loadShard(s);a&&r.push(a)}return r.slice(0,t.maxShardsPerQuery)}async retrieveByDomain(e){return $()?this.loadShard(e):null}calculateRelevance(e,t){let n=0,i={domainMatch:.4,taskTypeMatch:.25,keywordMatch:.15,intentMatch:.1,agentMatch:.1};t.domain===e.domain&&(n+=i.domainMatch);let r=tt[e.domain]||[],s=t.taskType.toLowerCase();for(let a of r)if(s.includes(a)||a.includes(s)){n+=i.taskTypeMatch;break}if(t.keywords&&t.keywords.length>0){let a=e.rawContent.toLowerCase(),o=0;for(let l of t.keywords)a.includes(l.toLowerCase())&&o++;n+=o/t.keywords.length*i.keywordMatch}if(t.intent){let a=t.intent.toLowerCase();this.getDomainsForIntent(a).includes(e.domain)&&(n+=i.intentMatch)}return t.agentId&&[...e.agentConstraints.primary.map(o=>o.agentId),...e.agentConstraints.secondary.map(o=>o.agentId),...e.agentConstraints.support.map(o=>o.agentId)].includes(t.agentId)&&(n+=i.agentMatch),t.requiresSecurity&&e.domain==="security-compliance"&&(n+=.15),t.requiresCompliance&&e.domain==="security-compliance"&&(n+=.1),t.requiresCoverage&&e.domain==="coverage-analysis"&&(n+=.15),t.requiresLearning&&e.domain==="learning-optimization"&&(n+=.1),Math.min(1,n)}async getTopShards(e,t){if(!$())return[];await this.initialize();let n=await this.getAllCachedOrLoadedShards(),i=[];for(let r of n.values()){let s=this.calculateRelevance(r,e);i.push({shard:r,score:s})}return i.sort((r,s)=>s.score-r.score),i.slice(0,t).map(r=>r.shard)}async injectRulesForContext(e){let t={rules:[],thresholds:{},constraints:{primary:[],secondary:[],support:[],readonly:[],forbidden:[]},escalations:[],sourceDomains:[]};if(!$())return t;let n=await this.retrieveForTask(e.taskType,e);if(n.length===0)return t;let i=[],r={},s={primary:[],secondary:[],support:[],readonly:[],forbidden:[]},a=[],o=[];for(let l of n)l.rules.forEach(u=>{i.push(`[${l.domain}] ${u}`)}),Object.assign(r,l.thresholds),s.primary.push(...l.agentConstraints.primary),s.secondary.push(...l.agentConstraints.secondary),s.support.push(...l.agentConstraints.support),s.readonly.push(...l.agentConstraints.readonly),s.forbidden.push(...l.agentConstraints.forbidden),a.push(...l.escalationTriggers),o.push(l.domain);return s.primary=this.dedupeAgentRoles(s.primary),s.secondary=this.dedupeAgentRoles(s.secondary),s.support=this.dedupeAgentRoles(s.support),s.readonly=this.dedupeAgentRoles(s.readonly),s.forbidden=[...new Set(s.forbidden)],{rules:i,thresholds:r,constraints:s,escalations:a,sourceDomains:o}}getShardStats(){let e=this.shardCache,t=Array.from(e.keys());return{totalShards:12,loadedShards:e.size,domains:t,lastRefresh:e.size>0?Math.max(...Array.from(e.values()).map(n=>n.loadedAt)):null,parseErrors:[...this.parseErrors]}}getCacheStats(){let e=N(),t=this.cacheHits+this.cacheMisses;return{enabled:e.cacheEnabled,size:this.shardCache.size,hits:this.cacheHits,misses:this.cacheMisses,hitRate:t>0?this.cacheHits/t:0,lastCleanup:this.lastCacheCleanup}}clearCache(){this.shardCache.clear(),this.cacheHits=0,this.cacheMisses=0,this.lastCacheCleanup=Date.now()}reset(){this.shardCache.clear(),this.cacheHits=0,this.cacheMisses=0,this.lastCacheCleanup=null,this.parseErrors=[],this.initialized=!1}async loadShardFromFile(e){try{let t=await et.readFile(e,"utf-8");return t=t.replace(/\r\n/g,`
|
|
4
4
|
`).replace(/\r/g,`
|
|
5
5
|
`),this.parseShard(t)}catch(t){if(t.code==="ENOENT")return null;throw t}}parseShard(e){let t=e.split(`
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{b as t}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.8");process.exit(0)}
|
|
2
|
+
import{b as t}from"./chunk-K5R3WUJP.js";function o(e){try{return e.prepare(`
|
|
3
3
|
SELECT COUNT(*) as count FROM sqlite_master
|
|
4
4
|
WHERE type='table' AND name IN ('hypergraph_nodes', 'hypergraph_edges')
|
|
5
5
|
`).get().count===2}catch{return!1}}var r,a,E,n,p=t(()=>{"use strict";r=`
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.8");process.exit(0)}
|
|
2
2
|
import{existsSync as c,readFileSync as f}from"fs";import{join as p,dirname as i}from"path";import{fileURLToPath as s}from"url";function u(o,a=10){let t=i(s(o));for(let r=0;r<a;r++){let n=p(t,"package.json");if(c(n))try{if(JSON.parse(f(n,"utf-8")).name==="agentic-qe")return t}catch{}let e=i(t);if(e===t)break;t=e}return null}export{u as a};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{b as P,c as q,d as R,e as D,g as O,h as x,i as j,j as $,k as L,l as N,m as M,n as Q,o as U,p as z}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.8");process.exit(0)}
|
|
2
|
+
import{b as P,c as q,d as R,e as D,g as O,h as x,i as j,j as $,k as L,l as N,m as M,n as Q,o as U,p as z}from"./chunk-2DPHFCMW.js";import{b as v,d as T}from"./chunk-FWXNFPLS.js";import{a as f,e as A}from"./chunk-J7FLNP5L.js";import{a as _,b as ae}from"./chunk-LPSMVBB3.js";T();import{existsSync as y,mkdirSync as F,writeFileSync as b,readFileSync as C,copyFileSync as oe}from"fs";import{join as p,dirname as ie}from"path";async function W(t,e){if(!e.hooks.claudeCode)return!1;let r=p(t,".claude");y(r)||F(r,{recursive:!0});let n=p(r,"settings.json"),s={};if(y(n))try{let m=C(n,"utf-8");s=v(m)}catch{s={}}let o={PreToolUse:[{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" guard --file "$TOOL_INPUT_file_path" --json',timeout:3,continueOnError:!0}]},{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" pre-edit --file "$TOOL_INPUT_file_path" --json',timeout:5,continueOnError:!0}]},{matcher:"^Bash$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" pre-command --command "$TOOL_INPUT_command" --json',timeout:3,continueOnError:!0}]},{matcher:"^Task$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" pre-task --description "$TOOL_INPUT_prompt" --json',timeout:5,continueOnError:!0}]}],PostToolUse:[{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" post-edit --file "$TOOL_INPUT_file_path" --success --json',timeout:5,continueOnError:!0}]},{matcher:"^Bash$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" post-command --command "$TOOL_INPUT_command" --success true --json',timeout:5,continueOnError:!0}]},{matcher:"^Task$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" post-task --task-id "$TOOL_RESULT_agent_id" --agent "$TOOL_INPUT_subagent_type" --success true --description "$TOOL_INPUT_prompt" --json',timeout:5,continueOnError:!0}]}],UserPromptSubmit:[{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" route --json',timeout:5,continueOnError:!0}]}],SessionStart:[{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" session-start --session-id "$SESSION_ID" --json',timeout:10,continueOnError:!0}]}],Stop:[{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" session-end --save-state --json',timeout:5,continueOnError:!0}]},{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" post-route --success true --json',timeout:5,continueOnError:!0}]}]},u=s.hooks||{};s.hooks=O(u,o);let l=s.env;s.env=x(l,j(e));let d=L(e,t);$(s,d);let a=s.enabledMcpjsonServers||[];return a=a.filter(m=>m!=="aqe"),a.includes("agentic-qe")||a.push("agentic-qe"),s.enabledMcpjsonServers=a,D(n),b(n,JSON.stringify(s,null,2),"utf-8"),await le(t),!0}async function le(t){let e=p(t,".claude","hooks");y(e)||F(e,{recursive:!0});let r=p(e,"cross-phase-memory.yaml");if(y(r))return;let n=[p(ie(import.meta.url.replace("file://","")),"..","..","assets","hooks","cross-phase-memory.yaml"),p(process.cwd(),"assets","hooks","cross-phase-memory.yaml"),p(process.cwd(),"v3","assets","hooks","cross-phase-memory.yaml")];for(let o of n)try{if(y(o)){oe(o,r),console.log(" \u2713 Cross-phase memory hooks installed");return}}catch{}b(r,`# Cross-Phase Memory Hooks Configuration
|
|
3
3
|
# Generated by aqe init
|
|
4
4
|
# See: https://github.com/anthropics/agentic-qe/docs/cross-phase-memory.md
|
|
5
5
|
|
|
@@ -276,7 +276,7 @@ aqe init --auto
|
|
|
276
276
|
`).run("aqe_version",JSON.stringify(e),o),s.prepare(`
|
|
277
277
|
INSERT OR REPLACE INTO kv_store (key, namespace, value, created_at)
|
|
278
278
|
VALUES (?, '_system', ?, ?)
|
|
279
|
-
`).run("init_timestamp",JSON.stringify(new Date().toISOString()),o),s.close(),console.log(` \u2713 Version ${e} written to memory.db`),!0}catch(o){return s.close(),console.warn(` \u26A0 Could not write version: ${f(o)}`),!1}}catch(n){return console.warn(` \u26A0 Could not open memory.db: ${f(n)}`),!1}}async function B(t){let e=null;try{e=(await import("./better-sqlite3-
|
|
279
|
+
`).run("init_timestamp",JSON.stringify(new Date().toISOString()),o),s.close(),console.log(` \u2713 Version ${e} written to memory.db`),!0}catch(o){return s.close(),console.warn(` \u26A0 Could not write version: ${f(o)}`),!1}}catch(n){return console.warn(` \u26A0 Could not open memory.db: ${f(n)}`),!1}}async function B(t){let e=null;try{e=(await import("./better-sqlite3-IQKBFVAO.js")).default}catch{throw new Error(`SQLite persistence REQUIRED but better-sqlite3 is not installed.
|
|
280
280
|
Install it with: npm install better-sqlite3
|
|
281
281
|
If you see native compilation errors, ensure build tools are installed:
|
|
282
282
|
- macOS: xcode-select --install
|
|
@@ -302,7 +302,7 @@ Database path: ${n}
|
|
|
302
302
|
Ensure the directory is writable and has sufficient disk space.`)}}async function H(t){let e=i(t,".agentic-qe","memory.db");if(!h(e))return!1;try{let r=_(e),n=r.prepare(`
|
|
303
303
|
SELECT COUNT(*) as count FROM kv_store
|
|
304
304
|
WHERE namespace = 'code-intelligence:kg'
|
|
305
|
-
`).get();return r.close(),n.count>0}catch{return!1}}async function X(t){try{let{KnowledgeGraphService:e}=await import("./knowledge-graph-
|
|
305
|
+
`).get();return r.close(),n.count>0}catch{return!1}}async function X(t){try{let{KnowledgeGraphService:e}=await import("./knowledge-graph-343O2HEZ.js"),{InMemoryBackend:r}=await import("./memory-backend-4QSNRRV6.js"),n=new r;await n.initialize();let s=new e(n,{namespace:"code-intelligence:kg",enableVectorEmbeddings:!0}),{glob:o}=await import("tinyglobby"),u=await o(["**/*.ts","**/*.tsx","**/*.js","**/*.jsx","**/*.py"],{cwd:t,ignore:["node_modules/**","dist/**","coverage/**",".agentic-qe/**"],expandDirectories:!1}),l=await s.index({paths:u.map(d=>i(t,d)),incremental:!1,includeTests:!0});return s.destroy(),l.success?{status:"indexed",entries:l.value.nodesCreated+l.value.edgesCreated}:{status:"error",entries:0}}catch(e){return console.warn("Code intelligence scan warning:",f(e)),{status:"skipped",entries:0}}}async function K(t){let e=i(t,".agentic-qe","memory.db");try{let r=_(e),n=r.prepare(`
|
|
306
306
|
SELECT COUNT(*) as count FROM kv_store
|
|
307
307
|
WHERE namespace LIKE 'code-intelligence:kg%'
|
|
308
308
|
`).get();return r.close(),n.count}catch{return 0}}async function Y(t,e,r){if(!e.learning.enabled)return 0;let n=i(t,".agentic-qe","data");h(n)||k(n,{recursive:!0});let s=i(n,"hnsw");h(s)||k(s,{recursive:!0});let o=i(n,"learning-config.json"),u={embeddingModel:e.learning.embeddingModel,hnswConfig:e.learning.hnswConfig,qualityThreshold:e.learning.qualityThreshold,promotionThreshold:e.learning.promotionThreshold,databasePath:i(n,"memory.db"),hnswIndexPath:i(s,"index.bin"),initialized:new Date().toISOString()};E(o,JSON.stringify(u,null,2),"utf-8");let l=0;if(e.learning.pretrainedPatterns&&r){let d=r,a=new Map;for(let g of d.patterns){let c=g.domain||"general";a.has(c)||a.set(c,[]),a.get(c).push(g)}let m=i(n,"pretrained-index.json"),S={version:d.version,totalPatterns:d.statistics.totalPatterns,domains:Array.from(a.entries()).map(([g,c])=>({name:g,patternCount:c.length})),loadedAt:new Date().toISOString()};E(m,JSON.stringify(S,null,2),"utf-8");for(let[g,c]of a){let w=i(n,"patterns",g);h(w)||k(w,{recursive:!0});let se=i(w,"patterns.json");E(se,JSON.stringify(c,null,2),"utf-8"),l+=c.length}return l}return 0}async function Z(t,e){if(!e.workers.daemonAutoStart||e.workers.enabled.length===0)return 0;let r=i(t,".agentic-qe","workers");h(r)||k(r,{recursive:!0});let n={},s={"pattern-consolidator":6e4,"coverage-gap-scanner":3e5,"flaky-test-detector":6e5,"routing-accuracy-monitor":12e4};for(let a of e.workers.enabled)n[a]={name:a,enabled:!0,interval:e.workers.intervals[a]||s[a]||6e4,lastRun:null,status:"pending"};let o=i(r,"registry.json"),u={version:e.version,maxConcurrent:e.workers.maxConcurrent,workers:n,createdAt:new Date().toISOString(),daemonPid:null};E(o,JSON.stringify(u,null,2),"utf-8");for(let a of e.workers.enabled){let m=i(r,`${a}.json`),S={name:a,enabled:!0,interval:e.workers.intervals[a]||s[a]||6e4,projectRoot:t,dataDir:i(t,".agentic-qe","data"),createdAt:new Date().toISOString()};E(m,JSON.stringify(S,null,2),"utf-8")}let l=i(r,"start-daemon.cjs");return E(l,`#!/usr/bin/env node
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{b as T}from"./chunk-LCCTJ2PC.js";import{a as Ae,c as Me}from"./chunk-OPDZBRIL.js";import{b as a,g as we}from"./chunk-ONPPBLRB.js";import{a as me,b as $e}from"./chunk-JCE76MPP.js";import{b as Re,c as w,d as _e,f as x}from"./chunk-6WOZUSSN.js";import{e as z,h as Ce,i as de,n as H}from"./chunk-6RDVY26I.js";import{b as W,d as ke}from"./chunk-22OZIJAD.js";import{a as pe,e as Ge}from"./chunk-DQNUPEY5.js";import{b as Ee,d as Fe}from"./chunk-K55EAWZ5.js";import{b as _,e as O}from"./chunk-KYVIOC3C.js";import{b as $}from"./chunk-7SAMMQVS.js";async function A(g,t,e,r,o="absolute",s){let n=new AbortController,i=!1,l,d=()=>{i=!0;let u=r();l?.(u),n.abort(u)},h=setTimeout(d,e),c=s!==void 0&&s>0?setTimeout(d,s):void 0;c?.unref?.();let p=()=>{clearTimeout(h),c&&clearTimeout(c)},m=()=>{o==="idle"&&(clearTimeout(h),h=setTimeout(d,e),h.unref?.())};h.unref?.();try{let u=await fetch(g,{...t,signal:n.signal});if(!u.body)return p(),u;m();let f=u.body.getReader(),b=!1,y=()=>{b=!0,p()},E=new ReadableStream({start(R){l=C=>{b||(y(),R.error(C),f.cancel(C).catch(()=>{}).finally(()=>f.releaseLock()))}},async pull(R){try{let C=await f.read();if(b)return;C.done?(y(),f.releaseLock(),R.close()):(m(),R.enqueue(C.value))}catch(C){if(b)return;y(),f.releaseLock(),R.error(C)}},async cancel(R){if(!b){y();try{await f.cancel(R)}finally{f.releaseLock()}}}},{highWaterMark:0}),v=new Response(E,{status:u.status,statusText:u.statusText,headers:u.headers});for(let R of["url","redirected","type"])Object.defineProperty(v,R,{value:u[R]});return v}catch(u){throw p(),i||u instanceof Error&&u.name==="AbortError"?r():u}}var I=$(()=>{"use strict"});import{readFileSync as Ve}from"fs";import*as Ie from"path";function J(g){return typeof g=="string"&&Ye.includes(g)}function Xe(g){try{let e=Ve(g,"utf8").match(/^\s*effort_level\s*:\s*['"]?([a-z]+)['"]?\s*$/m);return e&&J(e[1])?e[1]:null}catch{return null}}function Se(g={}){if(g.override&&J(g.override))return g.override;if(g.agentEffort&&J(g.agentEffort))return g.agentEffort;let e=(g.env??process.env).QE_EFFORT_LEVEL;if(e&&J(e))return e;let r=g.fleetDefaultsPath??Ie.join(process.cwd(),"config","fleet-defaults.yaml");return Y===void 0&&(Y=Xe(r)),Y||Je}var Ye,Je,Y,xe=$(()=>{"use strict";Ye=["low","medium","high","xhigh","max"],Je="xhigh"});function Qe(g){try{let t=z(g);return{sendSampling:t.supportsSamplingParams!==!1,supportsEffort:t.supportsEffortXHigh===!0}}catch{return{sendSampling:!1,supportsEffort:!1}}}function X(g,t,e){let r=Qe(t);if(r.sendSampling&&e.temperature!==void 0&&(g.temperature=e.temperature),r.supportsEffort){let o=e.effort??(Ze(t)?Se():void 0);o!==void 0&&(g.output_config={effort:o})}return g}function Ze(g){return Ce(g)?.tier==="flagship"}var be=$(()=>{"use strict";H();xe()});function gt(g){try{let t=z(g);return{sendSampling:t.supportsSamplingParams!==!1,maxTokensField:t.usesMaxCompletionTokens===!0?"max_completion_tokens":"max_tokens"}}catch{return dt.test(g)?{...ht}:{...mt}}}function D(g,t,e){let r=gt(t),o=g;return e.maxTokens!==void 0&&(o[r.maxTokensField]=e.maxTokens),r.sendSampling&&e.temperature!==void 0&&(o.temperature=e.temperature),g}var dt,mt,ht,ve=$(()=>{"use strict";H();dt=/^(openai\/)?(gpt-5|gpt-6|o\d)/i,mt={sendSampling:!0,maxTokensField:"max_tokens"},ht={sendSampling:!1,maxTokensField:"max_completion_tokens"}});Fe();O();var Le={failureThreshold:5,resetTimeoutMs:3e4,halfOpenSuccessThreshold:2,failureWindowMs:6e4,includeTimeouts:!0},he=class{state="closed";failures=[];successCount=0;totalRequests=0;totalSuccesses=0;totalFailures=0;rejectedCount=0;lastFailureTime;lastSuccessTime;openedAt;halfOpenSuccesses=0;config;providerType;constructor(t,e={}){this.providerType=t,this.config={...Le,...e}}getState(){return this.state==="open"&&this.openedAt&&Date.now()-this.openedAt.getTime()>=this.config.resetTimeoutMs&&this.transitionTo("half-open"),this.state}canExecute(){let t=this.getState();return t==="closed"?!0:t!=="open"}async execute(t){if(this.totalRequests++,this.getState()==="open")throw this.rejectedCount++,a(`Circuit breaker is open for provider ${this.providerType}`,"CIRCUIT_OPEN",{provider:this.providerType,retryable:!0,retryAfterMs:this.getTimeUntilTransition()});try{let r=await t();return this.recordSuccess(),r}catch(r){throw this.recordFailure(_(r)),r}}recordSuccess(){this.successCount++,this.totalSuccesses++,this.lastSuccessTime=new Date,this.getState()==="half-open"&&(this.halfOpenSuccesses++,this.halfOpenSuccesses>=this.config.halfOpenSuccessThreshold&&this.transitionTo("closed"))}recordFailure(t){if(this.totalFailures++,this.lastFailureTime=new Date,(t.message.toLowerCase().includes("timeout")||t.name==="TimeoutError"||t.name==="AbortError")&&!this.config.includeTimeouts)return;this.failures.push({timestamp:new Date,error:t}),this.cleanOldFailures();let r=this.getState();if(r==="half-open"){this.transitionTo("open");return}r==="closed"&&this.failures.length>=this.config.failureThreshold&&this.transitionTo("open")}getStats(){return{state:this.getState(),totalRequests:this.totalRequests,successCount:this.totalSuccesses,failureCount:this.totalFailures,rejectedCount:this.rejectedCount,lastFailureTime:this.lastFailureTime,lastSuccessTime:this.lastSuccessTime,timeUntilTransitionMs:this.getTimeUntilTransition()}}reset(){this.state="closed",this.failures=[],this.successCount=0,this.halfOpenSuccesses=0,this.openedAt=void 0}forceOpen(){this.transitionTo("open")}forceHalfOpen(){this.transitionTo("half-open")}getRecentFailures(t=5){return this.failures.slice(-t).map(e=>`[${e.timestamp.toISOString()}] ${e.error.message}`)}transitionTo(t){if(this.state!==t)switch(this.state=t,t){case"open":this.openedAt=new Date,this.halfOpenSuccesses=0;break;case"half-open":this.halfOpenSuccesses=0;break;case"closed":this.failures=[],this.openedAt=void 0,this.halfOpenSuccesses=0;break}}cleanOldFailures(){let t=Date.now()-this.config.failureWindowMs;this.failures=this.failures.filter(e=>e.timestamp.getTime()>t)}getTimeUntilTransition(){if(this.state==="open"&&this.openedAt){let t=Date.now()-this.openedAt.getTime(),e=this.config.resetTimeoutMs-t;return Math.max(0,e)}}},j=class{breakers=new Map;defaultConfig;constructor(t={}){this.defaultConfig={...Le,...t}}getBreaker(t,e){let r=this.breakers.get(t);return r||(r=new he(t,{...this.defaultConfig,...e}),this.breakers.set(t,r)),r}getAllStats(){let t={};for(let[e,r]of this.breakers)t[e]=r.getStats();return t}getAvailableProviders(){let t=[];for(let[e,r]of this.breakers)r.canExecute()&&t.push(e);return t}resetAll(){for(let t of this.breakers.values())t.reset()}reset(t){let e=this.breakers.get(t);e&&e.reset()}};import{createHash as We}from"node:crypto";var Pe={maxSize:1e3,defaultTtlMs:36e5,enableLRU:!0,cacheGenerations:!0,cacheEmbeddings:!0,cacheCompletions:!0},L=class{cache=new Map;accessOrder=[];config;hits=0;misses=0;evictions=0;constructor(t={}){this.config={...Pe,...t}}static generateKey(t,e,r){let o=[t,r?.model??"default",String(r?.temperature??.7),String(r?.maxTokens??0),r?.systemPrompt??"",e],s=[r?.stopSequences,r?.effort,r?.preferredProvider];s.some(i=>i!==void 0)&&o.push(JSON.stringify(s));let n=We("sha256").update(JSON.stringify(o)).digest("hex");return`${t}:${n}`}get(t){let e=this.cache.get(t);if(!e){this.misses++;return}if(e.ttlMs>0&&Date.now()-e.createdAt.getTime()>e.ttlMs){this.delete(t),this.misses++;return}return this.hits++,e.lastAccessedAt=new Date,e.accessCount++,this.config.enableLRU&&this.updateAccessOrder(t),e.value}set(t,e,r){this.cache.size>=this.config.maxSize&&!this.cache.has(t)&&this.evictLRU();let o={value:e,createdAt:new Date,lastAccessedAt:new Date,accessCount:1,ttlMs:r??this.config.defaultTtlMs,keyHash:t};this.cache.set(t,o),this.config.enableLRU&&this.updateAccessOrder(t)}has(t){let e=this.cache.get(t);return e?e.ttlMs>0&&Date.now()-e.createdAt.getTime()>e.ttlMs?(this.delete(t),!1):!0:!1}delete(t){let e=this.cache.delete(t);if(e){let r=this.accessOrder.indexOf(t);r!==-1&&this.accessOrder.splice(r,1)}return e}clear(){this.cache.clear(),this.accessOrder=[],this.hits=0,this.misses=0,this.evictions=0}getStats(){let t=this.hits+this.misses,e=t>0?this.hits/t:0,r=0;for(let o of this.cache.values())r+=this.estimateSize(o.value);return{size:this.cache.size,maxSize:this.config.maxSize,hits:this.hits,misses:this.misses,hitRate:e,evictions:this.evictions,memoryUsageBytes:r}}keys(){return Array.from(this.cache.keys())}entries(){return Array.from(this.cache.entries())}import(t){for(let[e,r]of t)r.createdAt=new Date(r.createdAt),r.lastAccessedAt=new Date(r.lastAccessedAt),this.cache.set(e,r),this.config.enableLRU&&this.updateAccessOrder(e);for(;this.cache.size>this.config.maxSize;)this.evictLRU()}pruneExpired(){let t=Date.now(),e=0;for(let[r,o]of this.cache.entries())o.ttlMs>0&&t-o.createdAt.getTime()>o.ttlMs&&(this.delete(r),e++);return e}updateAccessOrder(t){let e=this.accessOrder.indexOf(t);e!==-1&&this.accessOrder.splice(e,1),this.accessOrder.push(t)}evictLRU(){if(this.accessOrder.length===0){let e=this.cache.keys().next().value;e!==void 0&&(this.cache.delete(e),this.evictions++);return}let t=this.accessOrder.shift();t!==void 0&&(this.cache.delete(t),this.evictions++)}estimateSize(t){return t==null?0:JSON.stringify(t).length*2}},V=class{generationCache;embeddingCache;completionCache;config;constructor(t={}){this.config={...Pe,...t},this.generationCache=new L(t),this.embeddingCache=new L(t),this.completionCache=new L(t)}getGeneration(t,e){if(!this.config.cacheGenerations)return;let r=L.generateKey("generation",t,e);return this.generationCache.get(r)}setGeneration(t,e,r,o){if(!this.config.cacheGenerations||e.finishReason==="content_filter")return;let s=L.generateKey("generation",t,r);this.generationCache.set(s,e,o)}getEmbedding(t,e){if(!this.config.cacheEmbeddings)return;let r=L.generateKey("embedding",t,e);return this.embeddingCache.get(r)}setEmbedding(t,e,r,o){if(!this.config.cacheEmbeddings)return;let s=L.generateKey("embedding",t,r);this.embeddingCache.set(s,e,o)}getCompletion(t,e){if(!this.config.cacheCompletions)return;let r=L.generateKey("completion",t,e);return this.completionCache.get(r)}setCompletion(t,e,r,o){if(!this.config.cacheCompletions)return;let s=L.generateKey("completion",t,r);this.completionCache.set(s,e,o)}getStats(){let t=this.generationCache.getStats(),e=this.embeddingCache.getStats(),r=this.completionCache.getStats(),o=t.hits+e.hits+r.hits,s=t.misses+e.misses+r.misses,n=o+s;return{generation:t,embedding:e,completion:r,total:{size:t.size+e.size+r.size,maxSize:this.config.maxSize*3,hits:o,misses:s,hitRate:n>0?o/n:0,evictions:t.evictions+e.evictions+r.evictions,memoryUsageBytes:t.memoryUsageBytes+e.memoryUsageBytes+r.memoryUsageBytes}}}clear(){this.generationCache.clear(),this.embeddingCache.clear(),this.completionCache.clear()}pruneExpired(){return this.generationCache.pruneExpired()+this.embeddingCache.pruneExpired()+this.completionCache.pruneExpired()}};x();Ge();var ge="(unattributed)",ze=`
|
|
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.8");process.exit(0)}
|
|
2
|
+
import{b as T}from"./chunk-BLZEOGQE.js";import{a as Ae,c as Me}from"./chunk-MMY52Y6R.js";import{b as a,g as we}from"./chunk-K4N2MBCE.js";import{a as me,b as $e}from"./chunk-CRUQ6RXU.js";import{b as Re,c as w,d as _e,f as x}from"./chunk-FAYXES7R.js";import{e as z,h as Ce,i as de,n as H}from"./chunk-SJMZZMHP.js";import{b as W,d as ke}from"./chunk-FWXNFPLS.js";import{a as pe,e as Ge}from"./chunk-7SLEUVPZ.js";import{b as Ee,d as Fe}from"./chunk-RG42LDOB.js";import{b as _,e as O}from"./chunk-J7FLNP5L.js";import{b as $}from"./chunk-K5R3WUJP.js";async function A(g,t,e,r,o="absolute",s){let n=new AbortController,i=!1,l,d=()=>{i=!0;let u=r();l?.(u),n.abort(u)},h=setTimeout(d,e),c=s!==void 0&&s>0?setTimeout(d,s):void 0;c?.unref?.();let p=()=>{clearTimeout(h),c&&clearTimeout(c)},m=()=>{o==="idle"&&(clearTimeout(h),h=setTimeout(d,e),h.unref?.())};h.unref?.();try{let u=await fetch(g,{...t,signal:n.signal});if(!u.body)return p(),u;m();let f=u.body.getReader(),b=!1,y=()=>{b=!0,p()},E=new ReadableStream({start(R){l=C=>{b||(y(),R.error(C),f.cancel(C).catch(()=>{}).finally(()=>f.releaseLock()))}},async pull(R){try{let C=await f.read();if(b)return;C.done?(y(),f.releaseLock(),R.close()):(m(),R.enqueue(C.value))}catch(C){if(b)return;y(),f.releaseLock(),R.error(C)}},async cancel(R){if(!b){y();try{await f.cancel(R)}finally{f.releaseLock()}}}},{highWaterMark:0}),v=new Response(E,{status:u.status,statusText:u.statusText,headers:u.headers});for(let R of["url","redirected","type"])Object.defineProperty(v,R,{value:u[R]});return v}catch(u){throw p(),i||u instanceof Error&&u.name==="AbortError"?r():u}}var I=$(()=>{"use strict"});import{readFileSync as Ve}from"fs";import*as Ie from"path";function J(g){return typeof g=="string"&&Ye.includes(g)}function Xe(g){try{let e=Ve(g,"utf8").match(/^\s*effort_level\s*:\s*['"]?([a-z]+)['"]?\s*$/m);return e&&J(e[1])?e[1]:null}catch{return null}}function Se(g={}){if(g.override&&J(g.override))return g.override;if(g.agentEffort&&J(g.agentEffort))return g.agentEffort;let e=(g.env??process.env).QE_EFFORT_LEVEL;if(e&&J(e))return e;let r=g.fleetDefaultsPath??Ie.join(process.cwd(),"config","fleet-defaults.yaml");return Y===void 0&&(Y=Xe(r)),Y||Je}var Ye,Je,Y,xe=$(()=>{"use strict";Ye=["low","medium","high","xhigh","max"],Je="xhigh"});function Qe(g){try{let t=z(g);return{sendSampling:t.supportsSamplingParams!==!1,supportsEffort:t.supportsEffortXHigh===!0}}catch{return{sendSampling:!1,supportsEffort:!1}}}function X(g,t,e){let r=Qe(t);if(r.sendSampling&&e.temperature!==void 0&&(g.temperature=e.temperature),r.supportsEffort){let o=e.effort??(Ze(t)?Se():void 0);o!==void 0&&(g.output_config={effort:o})}return g}function Ze(g){return Ce(g)?.tier==="flagship"}var be=$(()=>{"use strict";H();xe()});function gt(g){try{let t=z(g);return{sendSampling:t.supportsSamplingParams!==!1,maxTokensField:t.usesMaxCompletionTokens===!0?"max_completion_tokens":"max_tokens"}}catch{return dt.test(g)?{...ht}:{...mt}}}function D(g,t,e){let r=gt(t),o=g;return e.maxTokens!==void 0&&(o[r.maxTokensField]=e.maxTokens),r.sendSampling&&e.temperature!==void 0&&(o.temperature=e.temperature),g}var dt,mt,ht,ve=$(()=>{"use strict";H();dt=/^(openai\/)?(gpt-5|gpt-6|o\d)/i,mt={sendSampling:!0,maxTokensField:"max_tokens"},ht={sendSampling:!1,maxTokensField:"max_completion_tokens"}});Fe();O();var Le={failureThreshold:5,resetTimeoutMs:3e4,halfOpenSuccessThreshold:2,failureWindowMs:6e4,includeTimeouts:!0},he=class{state="closed";failures=[];successCount=0;totalRequests=0;totalSuccesses=0;totalFailures=0;rejectedCount=0;lastFailureTime;lastSuccessTime;openedAt;halfOpenSuccesses=0;config;providerType;constructor(t,e={}){this.providerType=t,this.config={...Le,...e}}getState(){return this.state==="open"&&this.openedAt&&Date.now()-this.openedAt.getTime()>=this.config.resetTimeoutMs&&this.transitionTo("half-open"),this.state}canExecute(){let t=this.getState();return t==="closed"?!0:t!=="open"}async execute(t){if(this.totalRequests++,this.getState()==="open")throw this.rejectedCount++,a(`Circuit breaker is open for provider ${this.providerType}`,"CIRCUIT_OPEN",{provider:this.providerType,retryable:!0,retryAfterMs:this.getTimeUntilTransition()});try{let r=await t();return this.recordSuccess(),r}catch(r){throw this.recordFailure(_(r)),r}}recordSuccess(){this.successCount++,this.totalSuccesses++,this.lastSuccessTime=new Date,this.getState()==="half-open"&&(this.halfOpenSuccesses++,this.halfOpenSuccesses>=this.config.halfOpenSuccessThreshold&&this.transitionTo("closed"))}recordFailure(t){if(this.totalFailures++,this.lastFailureTime=new Date,(t.message.toLowerCase().includes("timeout")||t.name==="TimeoutError"||t.name==="AbortError")&&!this.config.includeTimeouts)return;this.failures.push({timestamp:new Date,error:t}),this.cleanOldFailures();let r=this.getState();if(r==="half-open"){this.transitionTo("open");return}r==="closed"&&this.failures.length>=this.config.failureThreshold&&this.transitionTo("open")}getStats(){return{state:this.getState(),totalRequests:this.totalRequests,successCount:this.totalSuccesses,failureCount:this.totalFailures,rejectedCount:this.rejectedCount,lastFailureTime:this.lastFailureTime,lastSuccessTime:this.lastSuccessTime,timeUntilTransitionMs:this.getTimeUntilTransition()}}reset(){this.state="closed",this.failures=[],this.successCount=0,this.halfOpenSuccesses=0,this.openedAt=void 0}forceOpen(){this.transitionTo("open")}forceHalfOpen(){this.transitionTo("half-open")}getRecentFailures(t=5){return this.failures.slice(-t).map(e=>`[${e.timestamp.toISOString()}] ${e.error.message}`)}transitionTo(t){if(this.state!==t)switch(this.state=t,t){case"open":this.openedAt=new Date,this.halfOpenSuccesses=0;break;case"half-open":this.halfOpenSuccesses=0;break;case"closed":this.failures=[],this.openedAt=void 0,this.halfOpenSuccesses=0;break}}cleanOldFailures(){let t=Date.now()-this.config.failureWindowMs;this.failures=this.failures.filter(e=>e.timestamp.getTime()>t)}getTimeUntilTransition(){if(this.state==="open"&&this.openedAt){let t=Date.now()-this.openedAt.getTime(),e=this.config.resetTimeoutMs-t;return Math.max(0,e)}}},j=class{breakers=new Map;defaultConfig;constructor(t={}){this.defaultConfig={...Le,...t}}getBreaker(t,e){let r=this.breakers.get(t);return r||(r=new he(t,{...this.defaultConfig,...e}),this.breakers.set(t,r)),r}getAllStats(){let t={};for(let[e,r]of this.breakers)t[e]=r.getStats();return t}getAvailableProviders(){let t=[];for(let[e,r]of this.breakers)r.canExecute()&&t.push(e);return t}resetAll(){for(let t of this.breakers.values())t.reset()}reset(t){let e=this.breakers.get(t);e&&e.reset()}};import{createHash as We}from"node:crypto";var Pe={maxSize:1e3,defaultTtlMs:36e5,enableLRU:!0,cacheGenerations:!0,cacheEmbeddings:!0,cacheCompletions:!0},L=class{cache=new Map;accessOrder=[];config;hits=0;misses=0;evictions=0;constructor(t={}){this.config={...Pe,...t}}static generateKey(t,e,r){let o=[t,r?.model??"default",String(r?.temperature??.7),String(r?.maxTokens??0),r?.systemPrompt??"",e],s=[r?.stopSequences,r?.effort,r?.preferredProvider];s.some(i=>i!==void 0)&&o.push(JSON.stringify(s));let n=We("sha256").update(JSON.stringify(o)).digest("hex");return`${t}:${n}`}get(t){let e=this.cache.get(t);if(!e){this.misses++;return}if(e.ttlMs>0&&Date.now()-e.createdAt.getTime()>e.ttlMs){this.delete(t),this.misses++;return}return this.hits++,e.lastAccessedAt=new Date,e.accessCount++,this.config.enableLRU&&this.updateAccessOrder(t),e.value}set(t,e,r){this.cache.size>=this.config.maxSize&&!this.cache.has(t)&&this.evictLRU();let o={value:e,createdAt:new Date,lastAccessedAt:new Date,accessCount:1,ttlMs:r??this.config.defaultTtlMs,keyHash:t};this.cache.set(t,o),this.config.enableLRU&&this.updateAccessOrder(t)}has(t){let e=this.cache.get(t);return e?e.ttlMs>0&&Date.now()-e.createdAt.getTime()>e.ttlMs?(this.delete(t),!1):!0:!1}delete(t){let e=this.cache.delete(t);if(e){let r=this.accessOrder.indexOf(t);r!==-1&&this.accessOrder.splice(r,1)}return e}clear(){this.cache.clear(),this.accessOrder=[],this.hits=0,this.misses=0,this.evictions=0}getStats(){let t=this.hits+this.misses,e=t>0?this.hits/t:0,r=0;for(let o of this.cache.values())r+=this.estimateSize(o.value);return{size:this.cache.size,maxSize:this.config.maxSize,hits:this.hits,misses:this.misses,hitRate:e,evictions:this.evictions,memoryUsageBytes:r}}keys(){return Array.from(this.cache.keys())}entries(){return Array.from(this.cache.entries())}import(t){for(let[e,r]of t)r.createdAt=new Date(r.createdAt),r.lastAccessedAt=new Date(r.lastAccessedAt),this.cache.set(e,r),this.config.enableLRU&&this.updateAccessOrder(e);for(;this.cache.size>this.config.maxSize;)this.evictLRU()}pruneExpired(){let t=Date.now(),e=0;for(let[r,o]of this.cache.entries())o.ttlMs>0&&t-o.createdAt.getTime()>o.ttlMs&&(this.delete(r),e++);return e}updateAccessOrder(t){let e=this.accessOrder.indexOf(t);e!==-1&&this.accessOrder.splice(e,1),this.accessOrder.push(t)}evictLRU(){if(this.accessOrder.length===0){let e=this.cache.keys().next().value;e!==void 0&&(this.cache.delete(e),this.evictions++);return}let t=this.accessOrder.shift();t!==void 0&&(this.cache.delete(t),this.evictions++)}estimateSize(t){return t==null?0:JSON.stringify(t).length*2}},V=class{generationCache;embeddingCache;completionCache;config;constructor(t={}){this.config={...Pe,...t},this.generationCache=new L(t),this.embeddingCache=new L(t),this.completionCache=new L(t)}getGeneration(t,e){if(!this.config.cacheGenerations)return;let r=L.generateKey("generation",t,e);return this.generationCache.get(r)}setGeneration(t,e,r,o){if(!this.config.cacheGenerations||e.finishReason==="content_filter")return;let s=L.generateKey("generation",t,r);this.generationCache.set(s,e,o)}getEmbedding(t,e){if(!this.config.cacheEmbeddings)return;let r=L.generateKey("embedding",t,e);return this.embeddingCache.get(r)}setEmbedding(t,e,r,o){if(!this.config.cacheEmbeddings)return;let s=L.generateKey("embedding",t,r);this.embeddingCache.set(s,e,o)}getCompletion(t,e){if(!this.config.cacheCompletions)return;let r=L.generateKey("completion",t,e);return this.completionCache.get(r)}setCompletion(t,e,r,o){if(!this.config.cacheCompletions)return;let s=L.generateKey("completion",t,r);this.completionCache.set(s,e,o)}getStats(){let t=this.generationCache.getStats(),e=this.embeddingCache.getStats(),r=this.completionCache.getStats(),o=t.hits+e.hits+r.hits,s=t.misses+e.misses+r.misses,n=o+s;return{generation:t,embedding:e,completion:r,total:{size:t.size+e.size+r.size,maxSize:this.config.maxSize*3,hits:o,misses:s,hitRate:n>0?o/n:0,evictions:t.evictions+e.evictions+r.evictions,memoryUsageBytes:t.memoryUsageBytes+e.memoryUsageBytes+r.memoryUsageBytes}}}clear(){this.generationCache.clear(),this.embeddingCache.clear(),this.completionCache.clear()}pruneExpired(){return this.generationCache.pruneExpired()+this.embeddingCache.pruneExpired()+this.completionCache.pruneExpired()}};x();Ge();var ge="(unattributed)",ze=`
|
|
3
3
|
CREATE TABLE IF NOT EXISTS llm_spend (
|
|
4
4
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
5
5
|
ts INTEGER NOT NULL,
|
|
@@ -17,7 +17,7 @@ CREATE INDEX IF NOT EXISTS idx_llm_spend_ts ON llm_spend(ts);
|
|
|
17
17
|
VALUES (@ts, @provider, @model, @cost_usd, @cost_source, @prompt_tokens, @completion_tokens, @request_id, @agent_type)`).run({ts:Date.now(),provider:t.provider,model:t.model,cost_usd:t.costUsd,cost_source:t.costSource,prompt_tokens:t.promptTokens,completion_tokens:t.completionTokens,request_id:t.requestId,agent_type:t.agent??null}):this.db.prepare(`INSERT INTO llm_spend
|
|
18
18
|
(ts, provider, model, cost_usd, cost_source, prompt_tokens, completion_tokens, request_id)
|
|
19
19
|
VALUES (@ts, @provider, @model, @cost_usd, @cost_source, @prompt_tokens, @completion_tokens, @request_id)`).run({ts:Date.now(),provider:t.provider,model:t.model,cost_usd:t.costUsd,cost_source:t.costSource,prompt_tokens:t.promptTokens,completion_tokens:t.completionTokens,request_id:t.requestId})}catch{}}spentSince(t,e=Date.now()){try{return this.db.prepare("SELECT COALESCE(SUM(cost_usd), 0) AS total FROM llm_spend WHERE ts >= ?").get(e-t)?.total??0}catch{return 0}}spentByAgentSince(t,e=Date.now()){try{let r=this.db.prepare(`SELECT COALESCE(agent_type, ?) AS agent, COALESCE(SUM(cost_usd), 0) AS total
|
|
20
|
-
FROM llm_spend WHERE ts >= ? GROUP BY COALESCE(agent_type, ?)`).all(ge,e-t,ge),o=pe();for(let s of r)o[s.agent]=s.total;return o}catch{return{}}}},B=class{entries=[];record(t){this.entries.push({ts:Date.now(),costUsd:t.costUsd,agent:t.agent??ge})}spentSince(t,e=Date.now()){let r=e-t,o=0;for(let s of this.entries)s.ts>=r&&(o+=s.costUsd);return o}spentByAgentSince(t,e=Date.now()){let r=e-t,o=pe();for(let s of this.entries)s.ts>=r&&(o[s.agent]=(o[s.agent]??0)+s.costUsd);return o}};async function Oe(){try{let t=(await import("./unified-memory-
|
|
20
|
+
FROM llm_spend WHERE ts >= ? GROUP BY COALESCE(agent_type, ?)`).all(ge,e-t,ge),o=pe();for(let s of r)o[s.agent]=s.total;return o}catch{return{}}}},B=class{entries=[];record(t){this.entries.push({ts:Date.now(),costUsd:t.costUsd,agent:t.agent??ge})}spentSince(t,e=Date.now()){let r=e-t,o=0;for(let s of this.entries)s.ts>=r&&(o+=s.costUsd);return o}spentByAgentSince(t,e=Date.now()){let r=e-t,o=pe();for(let s of this.entries)s.ts>=r&&(o[s.agent]=(o[s.agent]??0)+s.costUsd);return o}};async function Oe(){try{let t=(await import("./unified-memory-RQ3Q4CU3.js")).getUnifiedMemory();return t.isInitialized()||await t.initialize(),new fe(t.getDatabase())}catch{return new B}}x();O();O();function ye(g,t,e,r){let o=Math.min(t*Math.pow(2,g),e),s=Math.random()*r*o;return o+s}var He=1e3,je=3e4;function k(g,t=He,e=je){return ye(g,t,e,0)}I();be();H();var et={model:de,maxTokens:4096,temperature:.7,timeoutMs:6e4,maxRetries:3,anthropicVersion:"2023-06-01",enableCache:!0,enableCircuitBreaker:!0},Q=class{type="claude";name="Anthropic Claude";config;requestId=0;constructor(t={}){this.config={...et,...t}}async isAvailable(){if(!this.getApiKey())return!1;try{return(await this.healthCheck()).healthy}catch{return!1}}async healthCheck(){if(!this.getApiKey())return{healthy:!1,error:"API key not configured. Set ANTHROPIC_API_KEY environment variable."};let e=Date.now();try{let r=await this.fetchWithTimeout(`${this.getBaseUrl()}/v1/messages`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({model:this.config.model,max_tokens:1,messages:[{role:"user",content:"Hi"}]})},5e3),o=Date.now()-e;if(!r.ok){let s=await r.text();return{healthy:!1,latencyMs:o,error:`API error: ${r.status} - ${s}`}}return{healthy:!0,latencyMs:o,models:this.getSupportedModels(),details:{apiVersion:this.config.anthropicVersion,defaultModel:this.config.model}}}catch(r){return{healthy:!1,error:r instanceof Error?r.message:"Unknown error"}}}async generate(t,e){if(!this.getApiKey())throw a("Anthropic API key not configured","API_KEY_MISSING",{provider:"claude",retryable:!1});let o=this.formatMessages(t),s=e?.model??this.config.model,n=e?.maxTokens??this.config.maxTokens??4096,i=e?.temperature??this.config.temperature??.7,l=`claude-${++this.requestId}-${Date.now()}`,d=Date.now(),h={model:s,max_tokens:n,messages:o};X(h,s,{temperature:i,effort:e?.effort}),e?.systemPrompt&&(h.system=this.config.enableCache!==!1?[{type:"text",text:e.systemPrompt,cache_control:{type:"ephemeral"}}]:e.systemPrompt),e?.stopSequences&&e.stopSequences.length>0&&(h.stop_sequences=e.stopSequences);try{let c=await this.fetchWithRetry(`${this.getBaseUrl()}/v1/messages`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify(h)},e?.timeoutMs??this.config.timeoutMs??6e4,this.config.maxRetries??3),p=Date.now()-d;if(!c.ok){let v=await c.json().catch(()=>({error:{message:"Unknown error"}}));throw this.handleApiError(c.status,v,s)}let m=await c.json(),u=m.usage.cache_creation_input_tokens??0,f=m.usage.cache_read_input_tokens??0,b={promptTokens:m.usage.input_tokens,completionTokens:m.usage.output_tokens,totalTokens:m.usage.input_tokens+u+f+m.usage.output_tokens,cacheCreationTokens:u,cacheReadTokens:f},y=w.calculateCost(s,b);return T.recordTokenUsage(l,"claude-provider","llm","generate",{inputTokens:m.usage.input_tokens,outputTokens:m.usage.output_tokens,totalTokens:m.usage.input_tokens+m.usage.output_tokens,estimatedCostUsd:y.totalCost}),{content:m.content.filter(v=>v.type==="text").map(v=>v.text).join(""),model:m.model,provider:"claude",usage:b,cost:y,latencyMs:p,finishReason:this.mapFinishReason(m.stop_reason),cached:!1,requestId:l}}catch(c){throw c instanceof Error&&"code"in c?c:a(c instanceof Error?c.message:"Request failed","NETWORK_ERROR",{provider:"claude",model:s,retryable:!0,cause:c})}}async embed(t,e){throw a("Claude does not support native embeddings. Use OpenAI or Ollama for embeddings.","MODEL_NOT_FOUND",{provider:"claude",retryable:!1})}async complete(t,e){let r=await this.generate(t,{model:e?.model,temperature:e?.temperature??.2,maxTokens:e?.maxTokens??256,stopSequences:e?.stopSequences??[`
|
|
21
21
|
|
|
22
22
|
`,"```"]});return{completion:r.content,model:r.model,provider:"claude",usage:r.usage,latencyMs:r.latencyMs,cached:r.cached}}getConfig(){return{...this.config}}getSupportedModels(){return["claude-opus-4-7","claude-sonnet-4-6","claude-haiku-4-5-20251001","claude-3-opus-20240229","claude-3-sonnet-20240229","claude-3-haiku-20240307"]}getCostPerToken(){return w.getCostPerToken(this.config.model)}async dispose(){}getApiKey(){return this.config.apiKey??process.env.ANTHROPIC_API_KEY}getBaseUrl(){return(this.config.baseUrl??process.env.ANTHROPIC_BASE_URL??"https://api.anthropic.com").replace(/\/$/,"")}getHeaders(){return{"Content-Type":"application/json","x-api-key":this.getApiKey(),"anthropic-version":this.config.anthropicVersion??"2023-06-01"}}formatMessages(t){return typeof t=="string"?[{role:"user",content:t}]:t.filter(e=>e.role!=="system").map(e=>({role:e.role,content:e.content}))}mapFinishReason(t){switch(t){case"end_turn":return"stop";case"max_tokens":return"length";case"stop_sequence":return"stop";default:return"stop"}}handleApiError(t,e,r){let o="error"in e?e.error?.message??"Unknown API error":"Unknown API error",s="error"in e&&"type"in e.error?e.error.type:"";switch(t){case 401:throw a(o,"API_KEY_INVALID",{provider:"claude",model:r,retryable:!1});case 429:throw a(o,"RATE_LIMITED",{provider:"claude",model:r,retryable:!0,retryAfterMs:6e4});case 400:throw s==="invalid_request_error"&&o.includes("context")?a(o,"CONTEXT_LENGTH_EXCEEDED",{provider:"claude",model:r,retryable:!1}):a(o,"UNKNOWN",{provider:"claude",model:r,retryable:!1});case 500:case 502:case 503:throw a(o,"PROVIDER_UNAVAILABLE",{provider:"claude",model:r,retryable:!0,retryAfterMs:5e3});default:throw a(o,"UNKNOWN",{provider:"claude",model:r,retryable:!1})}}async fetchWithTimeout(t,e,r){return A(t,e,r,()=>a("Request timed out","TIMEOUT",{provider:"claude",retryable:!0}))}async fetchWithRetry(t,e,r,o){let s;for(let n=0;n<o;n++)try{let i=await this.fetchWithTimeout(t,e,r);if(i.status>=400&&i.status<500&&i.status!==429)return i;if((i.status>=500||i.status===429)&&n<o-1){let l=k(n);await this.sleep(l);continue}return i}catch(i){if(s=_(i),n<o-1){let l=k(n);await this.sleep(l)}}throw s??new Error("Request failed after retries")}sleep(t){return new Promise(e=>setTimeout(e,t))}};import{spawn as tt}from"node:child_process";var rt=["ANTHROPIC_API_KEY","CLAUDE_API_KEY","ANTHROPIC_AUTH_TOKEN"],ot={model:"sonnet",maxTokens:4096,temperature:.7,timeoutMs:12e4,maxRetries:1,binaryPath:"claude",maxConcurrency:2,disallowedTools:["Bash","Edit","Write","NotebookEdit","WebFetch","WebSearch","Task"]},Z=class g{type="claude-code";name="Claude Code (subscription)";billingMode="subscription";config;requestId=0;availabilityCache;active=0;queue=[];constructor(t={}){this.config={...ot,...t};let e=Number.parseInt(process.env.AQE_CLAUDE_CODE_CONCURRENCY??"",10);Number.isFinite(e)&&e>0&&(this.config.maxConcurrency=e)}async isAvailable(){let t=Date.now();if(this.availabilityCache&&t-this.availabilityCache.at<6e4)return this.availabilityCache.available;let e=!1;try{let{code:r}=await this.runProcess(["--version"],void 0,5e3);e=r===0}catch{e=!1}return this.availabilityCache={at:t,available:e},e}async healthCheck(){let t=Date.now(),e=await this.isAvailable(),r=Date.now()-t;return e?{healthy:!0,latencyMs:r,models:this.getSupportedModels(),details:{binaryPath:this.config.binaryPath,billing:"subscription"}}:{healthy:!1,latencyMs:r,error:`Claude Code CLI ("${this.config.binaryPath}") not found or not runnable. Install Claude Code and log in with your Pro/Max account.`}}async generate(t,e){let r=this.toCliModel(e?.model??this.config.model),o=`claude-code-${++this.requestId}-${Date.now()}`,{prompt:s,systemPrompt:n}=this.flatten(t,e?.systemPrompt),i=["-p","--output-format","json","--model",r];n&&i.push("--append-system-prompt",n);let l=this.config.disallowedTools??[];l.length>0&&i.push("--disallowedTools",...l);let d=Date.now(),h=e?.timeoutMs??this.config.timeoutMs??12e4,{code:c,stdout:p,stderr:m}=await this.withConcurrency(()=>this.runProcess(i,s,h)),u=Date.now()-d;if(c!==0&&!p.trim())throw this.classifyError(m||`claude exited with code ${c}`,r);let f;try{f=JSON.parse(p)}catch{throw a(`Could not parse claude -p JSON output: ${p.slice(0,200)}`,"PROVIDER_UNAVAILABLE",{provider:"claude-code",model:r,retryable:!0})}if(f.is_error)throw this.classifyError(f.result??f.api_error_status??"claude error",r);let b=f.usage??{},y={promptTokens:b.input_tokens??0,completionTokens:b.output_tokens??0,totalTokens:(b.input_tokens??0)+(b.output_tokens??0),cacheCreationTokens:b.cache_creation_input_tokens??0,cacheReadTokens:b.cache_read_input_tokens??0},E=f.modelUsage&&Object.keys(f.modelUsage)[0]||r;return T.recordTokenUsage(o,"claude-code-provider","llm","generate",{inputTokens:y.promptTokens,outputTokens:y.completionTokens,totalTokens:y.totalTokens,estimatedCostUsd:0}),{content:f.result??"",model:E,provider:"claude-code",usage:y,cost:{inputCost:0,outputCost:0,totalCost:0,currency:"USD",source:"provider-receipt"},latencyMs:u,finishReason:this.mapFinishReason(f.stop_reason),cached:!1,requestId:o}}async embed(t,e){throw a("Claude Code provider does not support embeddings. Use openai, ollama, or cognitum.","MODEL_NOT_FOUND",{provider:"claude-code",retryable:!1})}async complete(t,e){let r=await this.generate(t,{model:e?.model,temperature:e?.temperature??.2,maxTokens:e?.maxTokens??256});return{completion:r.content,model:r.model,provider:"claude-code",usage:r.usage,latencyMs:r.latencyMs,cached:r.cached}}getConfig(){return{...this.config}}getSupportedModels(){return["opus","sonnet","haiku"]}getCostPerToken(){return{input:0,output:0}}async dispose(){}toCliModel(t){let e=t.toLowerCase();return e.includes("opus")?"opus":e.includes("haiku")?"haiku":e.includes("sonnet")?"sonnet":t}flatten(t,e){if(typeof t=="string")return{prompt:t,systemPrompt:e};let r=t.filter(s=>s.role==="system").map(s=>s.content);return e&&r.unshift(e),{prompt:t.filter(s=>s.role!=="system").map(s=>`${s.role==="assistant"?"Assistant":"User"}: ${s.content}`).join(`
|
|
23
23
|
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.8");process.exit(0)}
|
|
2
2
|
var n=class{constructor(t){this.capacity=t;this.buffer=new Array(t)}capacity;buffer;head=0;tail=0;count=0;push(t){this.buffer[this.tail]=t,this.tail=(this.tail+1)%this.capacity,this.count<this.capacity?this.count++:this.head=(this.head+1)%this.capacity}toArray(){let t=[];for(let e=0;e<this.count;e++){let i=(this.head+e)%this.capacity;t.push(this.buffer[i])}return t}get length(){return this.count}get size(){return this.count}clear(){this.buffer=new Array(this.capacity),this.head=0,this.tail=0,this.count=0}last(t){let e=[],i=Math.max(0,this.count-t);for(let s=i;s<this.count;s++){let r=(this.head+s)%this.capacity;e.push(this.buffer[r])}return e}percentile(t){if(this.count===0)return;let e=this.toArray().sort((s,r)=>Number(s)-Number(r)),i=Math.floor(t/100*(e.length-1));return e[i]}reduce(t,e){let i=e;for(let s=0;s<this.count;s++){let r=(this.head+s)%this.capacity;i=t(i,this.buffer[r])}return i}average(){return this.count===0?0:this.reduce((e,i)=>e+i,0)/this.count}};export{n as a};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.8");process.exit(0)}
|
|
2
2
|
var i=/[\s\x00-\x1f\x7f]/;function e(t,n="git ref"){if(typeof t!="string"||t.length===0)return`Invalid ${n}: must be a non-empty string`;if(t.length>256)return`Invalid ${n}: longer than 256 characters`;if(t.startsWith("-"))return`Invalid ${n} "${t}": must not start with "-"`;if(i.test(t))return`Invalid ${n}: must not contain whitespace or control characters`}function s(t,n="git ref"){let r=e(t,n);if(r)throw new Error(r)}export{e as a,s as b};
|