agentic-qe 3.15.5 → 3.15.6
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/qe-court/evals/fixtures/seeded-mutant-delivery/README.md +9 -2
- package/.claude/skills/qe-court/evals/qe-court.yaml +3 -2
- package/.claude/skills/qe-quality-assessment/schemas/output.json +12 -2
- package/.claude/skills/skills-manifest.json +1 -1
- package/CHANGELOG.md +121 -0
- package/assets/skills/qe-court/evals/fixtures/seeded-mutant-delivery/README.md +9 -2
- package/assets/skills/qe-court/evals/qe-court.yaml +3 -2
- package/assets/skills/qe-quality-assessment/schemas/output.json +12 -2
- package/assets/skills/skills-manifest.json +1 -1
- package/dist/cli/bundle.js +5 -5
- package/dist/cli/chunks/adapter-PP3XIXDV.js +2 -0
- package/dist/cli/chunks/{agent-booster-wasm-CCTTGCQS.js → agent-booster-wasm-SY7UCLBL.js} +2 -2
- package/dist/cli/chunks/{agent-handler-DHYUF3NX.js → agent-handler-KAMYBU3S.js} +2 -2
- package/dist/cli/chunks/{agent-memory-branch-642W7CYX.js → agent-memory-branch-2CAW3KUM.js} +2 -2
- package/dist/cli/chunks/aqe-learning-engine-VDUQJKKY.js +2 -0
- package/dist/cli/chunks/{arena-NW2JVAFY.js → arena-4OFLJ3R2.js} +2 -2
- package/dist/cli/chunks/{arena-MUCC7UUN.js → arena-QCCVIOAH.js} +4 -4
- package/dist/cli/chunks/{audit-VKQTZJAA.js → audit-RBDQJQJB.js} +3 -3
- package/dist/cli/chunks/base-QSYWWPCE.js +2 -0
- package/dist/cli/chunks/{better-sqlite3-7ZUFVWLQ.js → better-sqlite3-5JRACCDQ.js} +2 -2
- package/dist/cli/chunks/{brain-handler-7LKAWSBI.js → brain-handler-W4QIIRT4.js} +3 -3
- package/dist/cli/chunks/{branch-enumerator-HUNXJKM4.js → branch-enumerator-IBNGI572.js} +2 -2
- package/dist/cli/chunks/{browser-ZSZEYUDP.js → browser-GMSCVAOI.js} +2 -2
- package/dist/cli/chunks/browser-workflow-WXXPBSCM.js +2 -0
- package/dist/cli/chunks/{chunk-RUSLEOMC.js → chunk-22OZIJAD.js} +2 -2
- package/dist/cli/chunks/{chunk-WR64BKUE.js → chunk-24ZSGYC6.js} +1 -1
- package/dist/cli/chunks/{chunk-CR2JUANW.js → chunk-2CIDFR2H.js} +3 -3
- package/dist/cli/chunks/{chunk-SDWMLT7B.js → chunk-2IWPJUVV.js} +5 -5
- package/dist/cli/chunks/{chunk-VYDNLQJN.js → chunk-2ZTWPMTK.js} +2 -2
- package/dist/cli/chunks/{chunk-WN55MNZ2.js → chunk-34MDMFET.js} +2 -2
- package/dist/cli/chunks/{chunk-D3G2NN7F.js → chunk-3DJNKNBR.js} +66 -65
- package/dist/cli/chunks/{chunk-XQRE2HWM.js → chunk-3NJ7O3OH.js} +2 -2
- package/dist/cli/chunks/chunk-45MVRQG4.js +2 -0
- package/dist/cli/chunks/chunk-46HBVDMU.js +2 -0
- package/dist/cli/chunks/{chunk-MNQ36MAF.js → chunk-47Q7JL3V.js} +2 -2
- package/dist/cli/chunks/chunk-4CLDYT36.js +2 -0
- package/dist/cli/chunks/{chunk-ORTBRO7F.js → chunk-4KOVHQXK.js} +2 -2
- package/dist/cli/chunks/{chunk-B2UHTA4Q.js → chunk-4POOJYXA.js} +1 -1
- package/dist/cli/chunks/{chunk-QXY3IRBW.js → chunk-5DH5QI7G.js} +26 -26
- package/dist/cli/chunks/{chunk-7BIYJRQJ.js → chunk-5GIJU2ZY.js} +2 -2
- package/dist/cli/chunks/{chunk-6LG5UEQE.js → chunk-5HAPS6VD.js} +2 -2
- package/dist/cli/chunks/{chunk-OU4ZAWCC.js → chunk-5LST62QR.js} +2 -2
- package/dist/cli/chunks/{chunk-Y2E3IJ53.js → chunk-5MT7DMD7.js} +2 -2
- package/dist/cli/chunks/{chunk-6UYN5PHA.js → chunk-5NC7QEJ6.js} +4 -4
- package/dist/cli/chunks/{chunk-3DTEQHFB.js → chunk-5UPIL62W.js} +3 -3
- package/dist/cli/chunks/{chunk-YINFES3E.js → chunk-5VUIXDY2.js} +2 -2
- package/dist/cli/chunks/chunk-5VZVMO7B.js +3 -0
- package/dist/cli/chunks/{chunk-JCC7QEKZ.js → chunk-624QRKQX.js} +1 -1
- package/dist/cli/chunks/{chunk-HIUNCO2W.js → chunk-66NW3ZB4.js} +2 -2
- package/dist/cli/chunks/{chunk-4AZP7ZCW.js → chunk-6HWARQWV.js} +2 -2
- package/dist/cli/chunks/{chunk-LNO5IWGH.js → chunk-6MXAJBEA.js} +1 -1
- package/dist/cli/chunks/{chunk-XNEEYXR2.js → chunk-6R3FBFCJ.js} +2 -2
- package/dist/cli/chunks/{chunk-ZT3GUYM5.js → chunk-6RDVY26I.js} +2 -2
- package/dist/cli/chunks/{chunk-W3ZGNNDV.js → chunk-6T6AHVLF.js} +1 -1
- package/dist/cli/chunks/{chunk-JANLATHN.js → chunk-6WOZUSSN.js} +2 -2
- package/dist/cli/chunks/chunk-72MQCZSM.js +2 -0
- package/dist/cli/chunks/chunk-7QVPMH25.js +3 -0
- package/dist/cli/chunks/{chunk-HLFDC4SF.js → chunk-7SAMMQVS.js} +1 -1
- package/dist/cli/chunks/{chunk-644DFAGS.js → chunk-7TJZDRDU.js} +1 -1
- package/dist/cli/chunks/{chunk-BYXNHGQC.js → chunk-7TVIX4WL.js} +2 -2
- package/dist/cli/chunks/{chunk-FBEXG4HD.js → chunk-7VTKR44N.js} +2 -2
- package/dist/cli/chunks/{chunk-UE22ODHN.js → chunk-7XTANLTN.js} +1 -1
- package/dist/cli/chunks/chunk-7XUB7U6Z.js +4 -0
- package/dist/cli/chunks/{chunk-HPLMX62I.js → chunk-A74J23QB.js} +2 -2
- package/dist/cli/chunks/{chunk-VRJPH3LG.js → chunk-A7ANPS4E.js} +2 -2
- package/dist/cli/chunks/{chunk-IHFUEPZH.js → chunk-AJT3XDRD.js} +2 -2
- package/dist/cli/chunks/{chunk-EUEHBERE.js → chunk-ALCIUWFC.js} +1 -1
- package/dist/cli/chunks/{chunk-NMJVG22Z.js → chunk-AUN4FG7V.js} +1 -1
- package/dist/cli/chunks/{chunk-DWZI3IVB.js → chunk-AUOSHM63.js} +2 -2
- package/dist/cli/chunks/{chunk-7EZLOC4K.js → chunk-AX26QJ6T.js} +2 -2
- package/dist/cli/chunks/{chunk-PDPEMBFV.js → chunk-B7RHBKHL.js} +2 -2
- package/dist/cli/chunks/{chunk-DEGWCUMY.js → chunk-BAYGQRNP.js} +2 -2
- package/dist/cli/chunks/{chunk-ONCH5AXU.js → chunk-BIXRTOH3.js} +18 -18
- package/dist/cli/chunks/{chunk-U4TV75AC.js → chunk-BO7UFNYV.js} +2 -2
- package/dist/cli/chunks/{chunk-FNAYDITO.js → chunk-BUTGIVKW.js} +1 -1
- package/dist/cli/chunks/{chunk-HBYQYGXP.js → chunk-BXATKI5S.js} +2 -2
- package/dist/cli/chunks/{chunk-BO4PKNYP.js → chunk-CCL436IU.js} +32 -27
- package/dist/cli/chunks/{chunk-XIE7OHML.js → chunk-CEXNW5TR.js} +1 -1
- package/dist/cli/chunks/{chunk-663ZFPUL.js → chunk-CLAMMGY3.js} +2 -2
- package/dist/cli/chunks/{chunk-PVAE65B4.js → chunk-CR66HNAE.js} +1 -1
- package/dist/cli/chunks/{chunk-LRASYSGV.js → chunk-CZBIREL5.js} +2 -2
- package/dist/cli/chunks/{chunk-WLIYWBQR.js → chunk-D5N2O5EH.js} +2 -2
- package/dist/cli/chunks/{chunk-A337MD3C.js → chunk-DA7DGDTI.js} +2 -2
- package/dist/cli/chunks/{chunk-WC47GICZ.js → chunk-DLSFT6PO.js} +2 -2
- package/dist/cli/chunks/{chunk-KHCALIFP.js → chunk-DQNUPEY5.js} +2 -2
- package/dist/cli/chunks/{chunk-GTSOFCMQ.js → chunk-EECF4CMA.js} +1 -1
- package/dist/cli/chunks/{chunk-5BOZCMXZ.js → chunk-EF5UHDCG.js} +1 -1
- package/dist/cli/chunks/{chunk-L6SVCNXK.js → chunk-EJ4KZFZN.js} +1 -1
- package/dist/cli/chunks/{chunk-CFPR24YK.js → chunk-ELI4GDQO.js} +2 -2
- package/dist/cli/chunks/{chunk-KJ3KBP24.js → chunk-F3KS3TAB.js} +2 -2
- package/dist/cli/chunks/{chunk-RMJ7PJOS.js → chunk-F7A2UBZO.js} +2 -2
- package/dist/cli/chunks/{chunk-U6OVPMQX.js → chunk-FOJRPEIP.js} +2 -2
- package/dist/cli/chunks/{chunk-JYY7AYGA.js → chunk-FQ5N666N.js} +1 -1
- package/dist/cli/chunks/{chunk-4XSCZVON.js → chunk-FU7LNUD7.js} +2 -2
- package/dist/cli/chunks/{chunk-OW42F2TX.js → chunk-GFB6BZWU.js} +2 -2
- package/dist/cli/chunks/{chunk-JI77KJP7.js → chunk-GI5HWS4H.js} +1 -1
- package/dist/cli/chunks/{chunk-4UXPDV7E.js → chunk-GNYOHZVV.js} +1 -1
- package/dist/cli/chunks/{chunk-VCKDVOPD.js → chunk-GVRFSXY6.js} +2 -2
- package/dist/cli/chunks/{chunk-PURHGLEC.js → chunk-GWM4M5NF.js} +1 -1
- package/dist/cli/chunks/{chunk-BY646JOM.js → chunk-HAN4MS5T.js} +2 -2
- package/dist/cli/chunks/{chunk-OGYWWZU7.js → chunk-HEGGV2PT.js} +2 -2
- package/dist/cli/chunks/{chunk-FHUJCVT3.js → chunk-HOEWMEF2.js} +2 -2
- package/dist/cli/chunks/{chunk-CXOXUBYU.js → chunk-HZFK2Z2Z.js} +1 -1
- package/dist/cli/chunks/chunk-I7WAW7TM.js +2 -0
- package/dist/cli/chunks/{chunk-E4VIVMDL.js → chunk-IEPWO4XP.js} +2 -2
- package/dist/cli/chunks/{chunk-DTJODGCE.js → chunk-ITIJ23K2.js} +2 -2
- package/dist/cli/chunks/{chunk-AQN5EDBM.js → chunk-IVJIHZSM.js} +1 -1
- package/dist/cli/chunks/{chunk-PHP4UJYP.js → chunk-JAPBSSFY.js} +1 -1
- package/dist/cli/chunks/{chunk-A2WOQO2N.js → chunk-JCE76MPP.js} +2 -2
- package/dist/cli/chunks/{chunk-A5J4XJS6.js → chunk-JPJEAK4G.js} +1 -1
- package/dist/cli/chunks/{chunk-3OAQPN2N.js → chunk-JYKQVYX2.js} +2 -2
- package/dist/cli/chunks/{chunk-MQGEZA2A.js → chunk-K55EAWZ5.js} +2 -2
- package/dist/cli/chunks/chunk-KCB6P463.js +3 -0
- package/dist/cli/chunks/{chunk-L375O3CZ.js → chunk-KIDOBLUO.js} +2 -2
- package/dist/cli/chunks/{chunk-NLDFNAOS.js → chunk-KYVIOC3C.js} +2 -2
- package/dist/cli/chunks/{chunk-CQMHDAJS.js → chunk-L2TDHJR3.js} +2 -2
- package/dist/cli/chunks/{chunk-FE3AIZI6.js → chunk-L4D3TPFP.js} +1 -1
- package/dist/cli/chunks/{chunk-VLOIEVER.js → chunk-LAY7NCQK.js} +3 -3
- package/dist/cli/chunks/{chunk-WT3JC4A6.js → chunk-LCCTJ2PC.js} +2 -2
- package/dist/cli/chunks/{chunk-VML4SG3X.js → chunk-LJCEDTUM.js} +3 -3
- package/dist/cli/chunks/{chunk-NF6AFIAX.js → chunk-LMAEMVPA.js} +1 -1
- package/dist/cli/chunks/{chunk-2XYTS2WY.js → chunk-LZWJ5BMP.js} +2 -2
- package/dist/cli/chunks/{chunk-PHAQWAEV.js → chunk-MP3FSUNB.js} +2 -2
- package/dist/cli/chunks/{chunk-IJ2EXSMO.js → chunk-MQCTLTGE.js} +2 -2
- package/dist/cli/chunks/{chunk-GRIPCYW5.js → chunk-MQTA6KIO.js} +1 -1
- package/dist/cli/chunks/{chunk-GGDKOJVF.js → chunk-NBUXM5X6.js} +10 -6
- package/dist/cli/chunks/{chunk-DPYDUKVZ.js → chunk-NHRF3V4B.js} +2 -2
- package/dist/cli/chunks/chunk-NMY4KTWA.js +16 -0
- package/dist/cli/chunks/chunk-NYS2GUNO.js +2 -0
- package/dist/cli/chunks/{chunk-AUZXRFOX.js → chunk-ONPPBLRB.js} +2 -2
- package/dist/cli/chunks/{chunk-HGBJ2QQ4.js → chunk-OPDZBRIL.js} +2 -2
- package/dist/cli/chunks/{chunk-DXVZBJE4.js → chunk-OQ4S6B7P.js} +1 -1
- package/dist/cli/chunks/{chunk-Y2WMPEUP.js → chunk-ORBODZSO.js} +2 -2
- package/dist/cli/chunks/{chunk-IJOFZBXD.js → chunk-ORFL3YXB.js} +2 -2
- package/dist/cli/chunks/{chunk-BMWAWZAN.js → chunk-P7DXVL2S.js} +2 -2
- package/dist/cli/chunks/chunk-PEMSXSP2.js +4 -0
- package/dist/cli/chunks/chunk-PS6WFCA4.js +6 -0
- package/dist/cli/chunks/{chunk-DPV33C77.js → chunk-Q2RBOC7V.js} +2 -2
- package/dist/cli/chunks/{chunk-3AYYGR6W.js → chunk-QLKUCMZC.js} +1 -1
- package/dist/cli/chunks/{chunk-EVCFUYYK.js → chunk-QLYO3H7E.js} +9 -9
- package/dist/cli/chunks/{chunk-3SH23PS3.js → chunk-QS5KZYUZ.js} +2 -2
- package/dist/cli/chunks/{chunk-3YNP33GB.js → chunk-R363XXGH.js} +2 -2
- package/dist/cli/chunks/chunk-RD5BYLN7.js +2 -0
- package/dist/cli/chunks/{chunk-MS3Z2CP5.js → chunk-RFDFET3O.js} +2 -2
- package/dist/cli/chunks/{chunk-ZLBBX24Q.js → chunk-RHIQ6QO5.js} +357 -351
- package/dist/cli/chunks/chunk-RLB7K7QP.js +2 -0
- package/dist/cli/chunks/{chunk-3YASZPLO.js → chunk-RUTO67PT.js} +2 -2
- package/dist/cli/chunks/{chunk-V7GNUVYI.js → chunk-RV6HSMKJ.js} +1 -1
- package/dist/cli/chunks/{chunk-4PT5KNXL.js → chunk-SOSJWM3E.js} +4 -4
- package/dist/cli/chunks/{chunk-6ZIDZ4TJ.js → chunk-SV5BUYHH.js} +2 -2
- package/dist/cli/chunks/{chunk-ZTC5FBL6.js → chunk-TL5GV3PR.js} +8 -8
- package/dist/cli/chunks/{chunk-GKPRECLL.js → chunk-TLUIO37P.js} +2 -2
- package/dist/cli/chunks/{chunk-FWYJ6UDX.js → chunk-TUDENMAE.js} +2 -2
- package/dist/cli/chunks/chunk-TVLOED6O.js +2 -0
- package/dist/cli/chunks/{chunk-3QD7U3FY.js → chunk-UB6DQGWM.js} +2 -2
- package/dist/cli/chunks/{chunk-SAPIRK2G.js → chunk-UHHMAKPE.js} +1 -1
- package/dist/cli/chunks/{chunk-35MDATQE.js → chunk-ULCHPPW2.js} +1 -1
- package/dist/cli/chunks/chunk-V3OLS2NG.js +2 -0
- package/dist/cli/chunks/{chunk-UXZEVIFX.js → chunk-VAYZ5QIE.js} +1 -1
- package/dist/cli/chunks/{chunk-VH3EB6ZG.js → chunk-VCONCVSY.js} +3 -3
- package/dist/cli/chunks/{chunk-QPV3OKX2.js → chunk-VVF337SV.js} +2 -2
- package/dist/cli/chunks/{chunk-XNHB6TLC.js → chunk-WKDWRRDT.js} +2 -2
- package/dist/cli/chunks/{chunk-RUJLVJDE.js → chunk-X2DR27AY.js} +2 -2
- package/dist/cli/chunks/{chunk-47GEI2LT.js → chunk-X33F7NXH.js} +3 -3
- package/dist/cli/chunks/{chunk-MB4VFAJC.js → chunk-XBEI2JBA.js} +2 -2
- package/dist/cli/chunks/{chunk-OQDC7GCM.js → chunk-XBFQJZWX.js} +2 -2
- package/dist/cli/chunks/{chunk-EAYQCBXL.js → chunk-XFPQIWEH.js} +3 -3
- package/dist/cli/chunks/{chunk-2KWI3MT3.js → chunk-XPB5BVU6.js} +2 -2
- package/dist/cli/chunks/{chunk-DL5JENWD.js → chunk-XQ53PZEF.js} +3 -3
- package/dist/cli/chunks/{chunk-BZFT4QDQ.js → chunk-XZ46CI35.js} +2 -2
- package/dist/cli/chunks/chunk-YLNYPQDR.js +2 -0
- package/dist/cli/chunks/{chunk-EOR3RECZ.js → chunk-YNG7E26C.js} +2 -2
- package/dist/cli/chunks/{chunk-6JFGB2JB.js → chunk-YXU35GGD.js} +1 -1
- package/dist/cli/chunks/{chunk-JNMUVBAJ.js → chunk-ZCP4P6O2.js} +2 -2
- package/dist/cli/chunks/{chunk-Y7GPLOXB.js → chunk-ZL5LJT7D.js} +2 -2
- package/dist/cli/chunks/{chunk-PCCIZFD7.js → chunk-ZOUEQ6DL.js} +1 -1
- package/dist/cli/chunks/{chunk-FQKEZVN6.js → chunk-ZSBD4FUX.js} +2 -2
- package/dist/cli/chunks/chunk-ZTB32K5N.js +5 -0
- package/dist/cli/chunks/{chunk-X52TMBHU.js → chunk-ZUTFHGEO.js} +1 -1
- package/dist/cli/chunks/ci-GEJCXMBK.js +81 -0
- package/dist/cli/chunks/{ci-config-XDDZOOEI.js → ci-config-2ZVV4OXL.js} +2 -2
- package/dist/cli/chunks/{ci-output-7ZUQI4U6.js → ci-output-E45OGVPR.js} +2 -2
- package/dist/cli/chunks/{circuit-breaker-ALXKCFAL.js → circuit-breaker-X73ITYZC.js} +2 -2
- package/dist/cli/chunks/{claude-flow-setup-RL7K2NI2.js → claude-flow-setup-W4PPH46C.js} +2 -2
- package/dist/cli/chunks/client-6XKSQ4JT.js +2 -0
- package/dist/cli/chunks/{cline-installer-2Z2QQKC3.js → cline-installer-NUEPMWDE.js} +2 -2
- package/dist/cli/chunks/{code-QSZTDINQ.js → code-6WQHBS7G.js} +3 -3
- package/dist/cli/chunks/{code-index-extractor-5CGR5D3Y.js → code-index-extractor-BXQIFIFT.js} +2 -2
- package/dist/cli/chunks/{codex-installer-7JLSEDE5.js → codex-installer-Z337R2KH.js} +2 -2
- package/dist/cli/chunks/{completions-U4NBSXEB.js → completions-F5DMYFHV.js} +2 -2
- package/dist/cli/chunks/{complexity-analyzer-WYZD2YSY.js → complexity-analyzer-W2SYPZDI.js} +2 -2
- package/dist/cli/chunks/{continuedev-installer-UPXINJFT.js → continuedev-installer-ZCHUIFTN.js} +2 -2
- package/dist/cli/chunks/{copilot-installer-WIVYQRIF.js → copilot-installer-M5JNODXF.js} +2 -2
- package/dist/cli/chunks/core-handlers-OJYW4Y6M.js +2 -0
- package/dist/cli/chunks/{cost-tracker-RIN4JDDM.js → cost-tracker-LSYTHBHV.js} +2 -2
- package/dist/cli/chunks/coverage-PGMRS5SS.js +49 -0
- package/dist/cli/chunks/cross-domain-router-QVUPQ2SC.js +2 -0
- package/dist/cli/chunks/{cursor-installer-POM7NGCC.js → cursor-installer-XPUA73UW.js} +2 -2
- package/dist/cli/chunks/{daemon-HFGKQ6LB.js → daemon-ITKDIYMW.js} +5 -5
- package/dist/cli/chunks/daemon-QBYTCIMH.js +10 -0
- package/dist/cli/chunks/{dag-attention-scheduler-HJXM7Q5P.js → dag-attention-scheduler-T55AXLD6.js} +2 -2
- package/dist/cli/chunks/{detect-XKQGLZYN.js → detect-DR7J6K4O.js} +2 -2
- package/dist/cli/chunks/{dist-node-SSKB53QL.js → dist-node-LAJJBOUT.js} +2 -2
- package/dist/cli/chunks/{domain-handler-6BNDHATU.js → domain-handler-OMSHCRMK.js} +2 -2
- package/dist/cli/chunks/{domain-plugins-DOX54YE3.js → domain-plugins-EQXSKC5K.js} +2 -2
- package/dist/cli/chunks/{domain-transfer-FW4ZX3Z7.js → domain-transfer-FKRAGVSW.js} +2 -2
- package/dist/cli/chunks/dream-3UABDRZJ.js +2 -0
- package/dist/cli/chunks/embed-and-insert-pattern-JZFPCNL3.js +3 -0
- package/dist/cli/chunks/{eval-K7E4XXBS.js → eval-JSNNASBW.js} +2 -2
- package/dist/cli/chunks/experience-capture-middleware-UPD3IZBK.js +40 -0
- package/dist/cli/chunks/{fast-paths-5JXXTYAG.js → fast-paths-YNMIBS2E.js} +2 -2
- package/dist/cli/chunks/{feature-flags-2CR3CO23.js → feature-flags-SRLXDKBI.js} +2 -2
- package/dist/cli/chunks/{feature-flags-RB72LHOJ.js → feature-flags-VIR7O4L7.js} +2 -2
- package/dist/cli/chunks/file-discovery-ZFGZTKZ4.js +2 -0
- package/dist/cli/chunks/{fleet-SDU7QEOA.js → fleet-K2ED46EL.js} +3 -3
- package/dist/cli/chunks/{gnn-wrapper-AWCFODUV.js → gnn-wrapper-QCU4ZRYW.js} +2 -2
- package/dist/cli/chunks/{heartbeat-handler-A4PJ3NFP.js → heartbeat-handler-YYQI4WZM.js} +4 -4
- package/dist/cli/chunks/heartbeat-scheduler-MJ6MTPDF.js +2 -0
- package/dist/cli/chunks/hnsw-adapter-FQWJCFVW.js +2 -0
- package/dist/cli/chunks/hnsw-index-NJYKJUHC.js +2 -0
- package/dist/cli/chunks/{hnsw-legacy-bridge-KRS7SSFM.js → hnsw-legacy-bridge-C5TJSWTZ.js} +2 -2
- package/dist/cli/chunks/{hnswlib-node-OGGCPKPO.js → hnswlib-node-SE3MJJYS.js} +2 -2
- package/dist/cli/chunks/{hooks-XNRNMUBW.js → hooks-C572SRDH.js} +43 -43
- package/dist/cli/chunks/hybrid-backend-SL7RFID7.js +2 -0
- package/dist/cli/chunks/{hypergraph-engine-X35LTXYT.js → hypergraph-engine-35A6G3M5.js} +2 -2
- package/dist/cli/chunks/{hypergraph-handler-M6THKAG6.js → hypergraph-handler-U2756CWI.js} +3 -3
- package/dist/cli/chunks/impact-analyzer-5ZJTXPVC.js +2 -0
- package/dist/cli/chunks/init-handler-PCLYQUSB.js +88 -0
- package/dist/cli/chunks/init-wizard-MQMDSIOF.js +2 -0
- package/dist/cli/chunks/kernel-MEJ5GMRH.js +2 -0
- package/dist/cli/chunks/{kilocode-installer-TEPR2ZJD.js → kilocode-installer-32PX5YH7.js} +2 -2
- package/dist/cli/chunks/{kiro-installer-RUKHGDEE.js → kiro-installer-C4ROMMUS.js} +2 -2
- package/dist/cli/chunks/knowledge-graph-XUBZSEZE.js +2 -0
- package/dist/cli/chunks/learning-GEPVZGJQ.js +122 -0
- package/dist/cli/chunks/{llm-router-7GECMDCP.js → llm-router-XRKTTJTX.js} +4 -4
- package/dist/cli/chunks/llm-router-service-QZAPAEPX.js +2 -0
- package/dist/cli/chunks/{load-NTJ4Y4ZR.js → load-XVH6HW7E.js} +2 -2
- package/dist/cli/chunks/load-test-OVXIQ3AF.js +2 -0
- package/dist/cli/chunks/{mcp-4335GTTG.js → mcp-IULSTM4Z.js} +2 -2
- package/dist/cli/chunks/{memory-HYC4M4XS.js → memory-6K7IAU4T.js} +5 -5
- package/dist/cli/chunks/memory-backend-TRPOMPK4.js +2 -0
- package/dist/cli/chunks/memory-handlers-CG6DRLAW.js +2 -0
- package/dist/cli/chunks/{multi-model-executor-T7FYKM6T.js → multi-model-executor-VZDUYPLX.js} +2 -2
- package/dist/cli/chunks/{opencode-installer-3USXVT5M.js → opencode-installer-QUTXKNH4.js} +2 -2
- package/dist/cli/chunks/orchestrator-PCKKUWOP.js +452 -0
- package/dist/cli/chunks/pattern-null-store-JWYBRBZG.js +2 -0
- package/dist/cli/chunks/{pattern-usage-recorder-CMZLPX2K.js → pattern-usage-recorder-PX5HQVRL.js} +2 -2
- package/dist/cli/chunks/{pipeline-BTRZOVSL.js → pipeline-O562GTOG.js} +2 -2
- package/dist/cli/chunks/{platform-2MCRKC25.js → platform-PM7Q2AZS.js} +2 -2
- package/dist/cli/chunks/plugin-OTYTFGPY.js +27 -0
- package/dist/cli/chunks/{prime-radiant-advanced-wasm-TXFEMBP6.js → prime-radiant-advanced-wasm-6CFXTHC2.js} +2 -2
- package/dist/cli/chunks/project-root-VVSTHIP4.js +2 -0
- package/dist/cli/chunks/protocol-executor-PXZCLZD3.js +2 -0
- package/dist/cli/chunks/{protocol-handler-DZ26OYVZ.js → protocol-handler-PPGNSAOS.js} +2 -2
- package/dist/cli/chunks/{prove-QWONEJWX.js → prove-WQ3BKRZG.js} +2 -2
- package/dist/cli/chunks/qe-reasoning-bank-42FRS5V3.js +2 -0
- package/dist/cli/chunks/{quality-WFH54FY7.js → quality-C5WUU3AA.js} +2 -2
- package/dist/cli/chunks/{quality-gate-ONJB7XU7.js → quality-gate-WSSRKD5U.js} +3 -3
- package/dist/cli/chunks/queen-coordinator-UI3B7DI6.js +2 -0
- package/dist/cli/chunks/real-embeddings-CFQE7IRQ.js +2 -0
- package/dist/cli/chunks/{ref-validation-HW5Y55ZC.js → ref-validation-DHKHXVZT.js} +2 -2
- package/dist/cli/chunks/{roocode-installer-5OABDNZT.js → roocode-installer-3PPODABV.js} +2 -2
- package/dist/cli/chunks/router-HYRPWLAY.js +2 -0
- package/dist/cli/chunks/routing-feedback-BPZ5R6F3.js +2 -0
- package/dist/cli/chunks/{routing-handler-CVHVOQTC.js → routing-handler-JNXTGT6T.js} +2 -2
- package/dist/cli/chunks/{ruvector-commands-KKDKFGIQ.js → ruvector-commands-6YLROPVP.js} +2 -2
- package/dist/cli/chunks/rvf-dual-writer-DEKDQ6KO.js +2 -0
- package/dist/cli/chunks/rvf-migration-adapter-L53VBS7I.js +2 -0
- package/dist/cli/chunks/rvf-migration-coordinator-4DWB4WRK.js +2 -0
- package/dist/cli/chunks/rvf-native-adapter-I6RUGD2D.js +2 -0
- package/dist/cli/chunks/{rvf-store-integrity-UGUXKIFX.js → rvf-store-integrity-YKR2ZNBF.js} +2 -2
- package/dist/cli/chunks/safe-db-KS65XDCP.js +2 -0
- package/dist/cli/chunks/schedule-KD2VN6GB.js +2 -0
- package/dist/cli/chunks/scheduler-ZH3RMUHY.js +2 -0
- package/dist/cli/chunks/{security-7723AZZ4.js → security-PWQTGDRU.js} +3 -3
- package/dist/cli/chunks/shared-rvf-adapter-LNRLFP5I.js +2 -0
- package/dist/cli/chunks/{shared-rvf-dual-writer-ZSHYG5IA.js → shared-rvf-dual-writer-GWU6YQNS.js} +2 -2
- package/dist/cli/chunks/sqlite-persistence-6DTVME5D.js +2 -0
- package/dist/cli/chunks/{standalone-memory-MHZEEYMK.js → standalone-memory-46KKBSSV.js} +2 -2
- package/dist/cli/chunks/{status-handler-JKXPJ22K.js → status-handler-35T5FTDQ.js} +2 -2
- package/dist/cli/chunks/{structural-health-J4RKCYWF.js → structural-health-P7QPQWLO.js} +2 -2
- package/dist/cli/chunks/{sync-PDPORHVN.js → sync-W6Z4R4PL.js} +2 -2
- package/dist/cli/chunks/sync-Y43EWBSY.js +2 -0
- package/dist/cli/chunks/{task-handler-VERADM44.js → task-handler-5CX3ZYT7.js} +2 -2
- package/dist/cli/chunks/{task-handlers-4RUCWUR2.js → task-handlers-DQZGOJNE.js} +3 -3
- package/dist/cli/chunks/{test-DMBJFQNL.js → test-TPP53VVV.js} +12 -12
- package/dist/cli/chunks/{test-scheduling-LUPTVGCD.js → test-scheduling-WBV4UMQH.js} +3 -3
- package/dist/cli/chunks/token-bootstrap-GIIDXHLC.js +2 -0
- package/dist/cli/chunks/{token-usage-VOA34IKM.js → token-usage-AKK37RB7.js} +2 -2
- package/dist/cli/chunks/{transformers-GU4TYAN5.js → transformers-7MASPELS.js} +2 -2
- package/dist/cli/chunks/{tree-sitter-wasm-parser-MZPXAH7C.js → tree-sitter-wasm-parser-YZKD6UGB.js} +2 -2
- package/dist/cli/chunks/{types-K4FLXR2K.js → types-AZ3BTXDP.js} +2 -2
- package/dist/cli/chunks/unified-memory-FCX7NLFZ.js +2 -0
- package/dist/cli/chunks/unified-memory-hnsw-VU5QJK37.js +2 -0
- package/dist/cli/chunks/unified-persistence-FM376LGE.js +2 -0
- package/dist/cli/chunks/{upgrade-M3ATDRMK.js → upgrade-L7OTDKEK.js} +2 -2
- package/dist/cli/chunks/{validate-AAP773B3.js → validate-O3QVFIGP.js} +2 -2
- package/dist/cli/chunks/{validate-swarm-7RGAZX5F.js → validate-swarm-2UGBGLTX.js} +2 -2
- package/dist/cli/chunks/visual-security-EU7Y3X46.js +2 -0
- package/dist/cli/chunks/{web-tree-sitter-GQMRHGGI.js → web-tree-sitter-J75IYPRO.js} +2 -2
- package/dist/cli/chunks/{windsurf-installer-HG6HF2GF.js → windsurf-installer-FQ5DBFCG.js} +2 -2
- package/dist/cli/chunks/witness-chain-CSEBT52D.js +2 -0
- package/dist/cli/chunks/{witness-chain-WKU3ZIBQ.js → witness-chain-I7TN4MXZ.js} +2 -2
- package/dist/cli/chunks/witness-chain-repair-D3NE3NQK.js +2 -0
- package/dist/cli/chunks/{witness-chain-verifier-Q2KW3QEQ.js → witness-chain-verifier-RU2WOP5M.js} +2 -2
- package/dist/cli/chunks/witness-key-manager-IHQB2FR5.js +2 -0
- package/dist/cli/chunks/{workflow-CX6SHFBW.js → workflow-6BWTNVV6.js} +28 -28
- package/dist/cli/chunks/workflow-orchestrator-ALNKOM3N.js +2 -0
- package/dist/cli/chunks/wrappers-URVP25VU.js +2 -0
- package/dist/cli/commands/ci.js +47 -25
- package/dist/cli/commands/coverage.d.ts +1 -28
- package/dist/cli/commands/coverage.js +63 -134
- package/dist/cli/commands/daemon.js +7 -1
- package/dist/cli/commands/hooks-handlers/stats-hooks.d.ts +15 -0
- package/dist/cli/commands/hooks-handlers/stats-hooks.js +54 -2
- package/dist/cli/commands/learning.js +47 -7
- package/dist/cli/commands/test.js +6 -7
- package/dist/cli/commands/workflow.js +9 -5
- package/dist/cli/handlers/init-guard.d.ts +13 -0
- package/dist/cli/handlers/init-guard.js +23 -0
- package/dist/cli/handlers/init-handler.d.ts +3 -0
- package/dist/cli/handlers/init-handler.js +9 -0
- package/dist/cli/handlers/interfaces.js +5 -1
- package/dist/cli/scheduler/persistent-scheduler.d.ts +6 -2
- package/dist/cli/scheduler/persistent-scheduler.js +107 -41
- package/dist/cli/utils/ci-output.d.ts +8 -1
- package/dist/cli/utils/ci-output.js +13 -2
- package/dist/cli/utils/coverage-data.d.ts +3 -0
- package/dist/cli/utils/coverage-data.js +14 -39
- package/dist/cli/utils/coverage-verdict.d.ts +130 -0
- package/dist/cli/utils/coverage-verdict.js +193 -0
- package/dist/cli/utils/file-discovery.js +5 -0
- package/dist/coordination/deterministic-actions.js +24 -13
- package/dist/coordination/handlers/code-intelligence-handlers.d.ts +8 -0
- package/dist/coordination/handlers/code-intelligence-handlers.js +39 -0
- package/dist/coordination/handlers/coverage-handlers.js +34 -6
- package/dist/coordination/handlers/coverage-runner.d.ts +22 -0
- package/dist/coordination/handlers/coverage-runner.js +105 -10
- package/dist/coordination/handlers/coverage-target.d.ts +1 -0
- package/dist/coordination/handlers/coverage-target.js +4 -1
- package/dist/coordination/handlers/handler-types.d.ts +9 -0
- package/dist/coordination/handlers/handler-utils.d.ts +14 -1
- package/dist/coordination/handlers/handler-utils.js +46 -22
- package/dist/coordination/handlers/quality-handlers.js +108 -18
- package/dist/coordination/handlers/test-execution-handlers.js +4 -1
- package/dist/coordination/protocols/defect-investigation.d.ts +2 -1
- package/dist/coordination/protocols/defect-investigation.js +6 -3
- package/dist/coordination/protocols/quality-gate.js +10 -6
- package/dist/coordination/result-saver.d.ts +22 -0
- package/dist/coordination/result-saver.js +113 -43
- package/dist/coordination/task-executor.d.ts +7 -0
- package/dist/coordination/task-executor.js +32 -3
- package/dist/domains/code-intelligence/plugin.js +4 -0
- package/dist/domains/code-intelligence/services/metric-collector/index.js +9 -2
- package/dist/domains/code-intelligence/services/metric-collector/interfaces.d.ts +21 -0
- package/dist/domains/code-intelligence/services/metric-collector/interfaces.js +25 -0
- package/dist/domains/code-intelligence/services/metric-collector/loc-counter.d.ts +12 -0
- package/dist/domains/code-intelligence/services/metric-collector/loc-counter.js +69 -3
- package/dist/domains/code-intelligence/services/metric-collector/test-counter.js +4 -1
- package/dist/domains/coverage-analysis/collected-metrics.d.ts +33 -0
- package/dist/domains/coverage-analysis/collected-metrics.js +36 -0
- package/dist/domains/coverage-analysis/coordinator.js +18 -6
- package/dist/domains/coverage-analysis/interfaces.d.ts +44 -0
- package/dist/domains/coverage-analysis/interfaces.js +6 -1
- package/dist/domains/coverage-analysis/services/coverage-analyzer.js +61 -34
- package/dist/domains/coverage-analysis/services/gap-detector.js +7 -2
- package/dist/domains/defect-intelligence/plugin.js +4 -0
- package/dist/domains/defect-intelligence/services/defect-predictor.js +6 -4
- package/dist/domains/learning-optimization/coordinator.js +4 -0
- package/dist/domains/learning-optimization/plugin.js +4 -0
- package/dist/domains/quality-assessment/coordinator-rl-integration.d.ts +14 -0
- package/dist/domains/quality-assessment/coordinator-rl-integration.js +54 -16
- package/dist/domains/quality-assessment/coordinator.js +10 -6
- package/dist/domains/quality-assessment/coverage-report-event.d.ts +32 -8
- package/dist/domains/quality-assessment/coverage-report-event.js +28 -6
- package/dist/domains/quality-assessment/index.d.ts +1 -1
- package/dist/domains/quality-assessment/interfaces.d.ts +46 -0
- package/dist/domains/quality-assessment/quality-evidence.d.ts +48 -2
- package/dist/domains/quality-assessment/quality-evidence.js +62 -0
- package/dist/domains/quality-assessment/services/quality-analyzer.d.ts +23 -2
- package/dist/domains/quality-assessment/services/quality-analyzer.js +192 -109
- package/dist/domains/security-compliance/services/scanners/dast-scanner.js +22 -16
- package/dist/domains/test-execution/interfaces.d.ts +10 -6
- package/dist/domains/test-execution/plugin.js +4 -0
- package/dist/domains/test-execution/services/test-executor.js +152 -102
- package/dist/domains/test-generation/coordinator.js +4 -0
- package/dist/domains/test-generation/plugin.js +4 -0
- package/dist/feedback/coverage-learner.js +4 -1
- package/dist/feedback/coverage-session-provenance.d.ts +29 -0
- package/dist/feedback/coverage-session-provenance.js +39 -0
- package/dist/init/orchestrator.js +2 -0
- package/dist/init/phases/09-assets.d.ts +4 -0
- package/dist/init/phases/09-assets.js +35 -0
- package/dist/init/retired-assets.d.ts +86 -0
- package/dist/init/retired-assets.js +230 -0
- package/dist/init/skills-installer.d.ts +2 -0
- package/dist/init/skills-installer.js +4 -0
- package/dist/init/types.d.ts +3 -0
- package/dist/integrations/ruvector/rvf-native-adapter.d.ts +2 -0
- package/dist/integrations/ruvector/rvf-native-adapter.js +5 -0
- package/dist/integrations/ruvector/server-client.js +4 -12
- package/dist/kernel/project-root.d.ts +17 -0
- package/dist/kernel/project-root.js +54 -2
- package/dist/kernel/shared-dirs.d.ts +66 -0
- package/dist/kernel/shared-dirs.js +168 -0
- package/dist/learning/daily-log.js +2 -1
- package/dist/learning/experience-capture-middleware.d.ts +22 -0
- package/dist/learning/experience-capture-middleware.js +35 -0
- package/dist/learning/learnable-result.d.ts +16 -0
- package/dist/learning/learnable-result.js +24 -0
- package/dist/learning/pattern-mutation-error.d.ts +8 -0
- package/dist/learning/pattern-mutation-error.js +12 -0
- package/dist/learning/qe-reasoning-bank.d.ts +10 -0
- package/dist/learning/qe-reasoning-bank.js +50 -1
- package/dist/learning/rvf-reconcile.d.ts +39 -0
- package/dist/learning/rvf-reconcile.js +40 -0
- package/dist/learning/sqlite-persistence.d.ts +14 -0
- package/dist/learning/sqlite-persistence.js +36 -0
- package/dist/mcp/bundle.js +516 -504
- package/dist/mcp/handlers/domain-handler-configs.d.ts +31 -1
- package/dist/mcp/handlers/domain-handler-configs.js +37 -3
- package/dist/mcp/handlers/handler-factory.js +40 -14
- package/dist/mcp/protocol-server.js +27 -2
- package/dist/mcp/tool-cache-scope.d.ts +31 -0
- package/dist/mcp/tool-cache-scope.js +71 -0
- package/dist/mcp/tools/code-intelligence/analyze.js +5 -3
- package/dist/mcp/types.d.ts +4 -0
- package/dist/optimization/session-cache.d.ts +19 -1
- package/dist/optimization/session-cache.js +36 -2
- package/dist/plugins/cache.js +2 -1
- package/dist/plugins/sources/github.js +2 -1
- package/dist/plugins/sources/npm.js +2 -1
- package/dist/shared/aqe-managed-dirs.d.ts +24 -0
- package/dist/shared/aqe-managed-dirs.js +56 -0
- package/dist/shared/events/domain-events.d.ts +18 -3
- package/dist/shared/events/domain-events.js +4 -0
- package/dist/shared/http/http-client.d.ts +6 -0
- package/dist/shared/http/http-client.js +13 -15
- package/dist/shared/io/file-reader.d.ts +26 -0
- package/dist/shared/io/file-reader.js +111 -17
- package/dist/shared/llm/providers/response-deadline.d.ts +7 -2
- package/dist/shared/llm/providers/response-deadline.js +17 -5
- package/dist/shared/metrics/code-metrics.d.ts +24 -0
- package/dist/shared/metrics/code-metrics.js +93 -6
- package/dist/shared/metrics/index.d.ts +1 -1
- package/dist/workers/interfaces.d.ts +9 -1
- package/dist/workers/quality-daemon/coverage-delta.d.ts +4 -3
- package/dist/workers/quality-daemon/coverage-delta.js +13 -6
- package/dist/workers/quality-daemon/index.js +6 -5
- package/dist/workers/quality-daemon/notification-service.js +3 -3
- package/dist/workers/quality-daemon/persistent-memory.d.ts +2 -2
- package/dist/workers/quality-daemon/persistent-memory.js +2 -2
- package/dist/workers/worker-manager.js +5 -1
- package/dist/workers/workers/coverage-tracker.js +69 -33
- package/dist/workers/workers/regression-monitor.d.ts +18 -1
- package/dist/workers/workers/regression-monitor.js +276 -117
- package/package.json +1 -1
- package/dist/cli/chunks/adapter-EGIPTX5H.js +0 -2
- package/dist/cli/chunks/aqe-learning-engine-WP4GCBDT.js +0 -2
- package/dist/cli/chunks/base-6ORFD62I.js +0 -2
- package/dist/cli/chunks/browser-workflow-PIXGERWP.js +0 -2
- package/dist/cli/chunks/chunk-2WFTZSRT.js +0 -2
- package/dist/cli/chunks/chunk-7YB2KELI.js +0 -5
- package/dist/cli/chunks/chunk-BBL6YXD3.js +0 -2
- package/dist/cli/chunks/chunk-BJ5P4IV2.js +0 -2
- package/dist/cli/chunks/chunk-DFPL5N3Q.js +0 -16
- package/dist/cli/chunks/chunk-DLY4YEN3.js +0 -2
- package/dist/cli/chunks/chunk-ERGWWI4Y.js +0 -3
- package/dist/cli/chunks/chunk-KZVJW2SD.js +0 -2
- package/dist/cli/chunks/chunk-L336HFFE.js +0 -2
- package/dist/cli/chunks/chunk-N2TJNIHA.js +0 -2
- package/dist/cli/chunks/chunk-RCXMUEZN.js +0 -3
- package/dist/cli/chunks/chunk-SEZLYRCS.js +0 -2
- package/dist/cli/chunks/chunk-TDLKXLJC.js +0 -4
- package/dist/cli/chunks/chunk-WOZIXXY5.js +0 -7
- package/dist/cli/chunks/ci-KP4GZKJ7.js +0 -81
- package/dist/cli/chunks/client-C3KHVRM6.js +0 -2
- package/dist/cli/chunks/core-handlers-KSQM6Q6S.js +0 -2
- package/dist/cli/chunks/coverage-SPFVHRRU.js +0 -43
- package/dist/cli/chunks/coverage-target-GSRBNHXE.js +0 -2
- package/dist/cli/chunks/cross-domain-router-CTGNOVCF.js +0 -2
- package/dist/cli/chunks/daemon-M5TD5Y6T.js +0 -10
- package/dist/cli/chunks/dream-MIK2E4UL.js +0 -2
- package/dist/cli/chunks/embed-and-insert-pattern-QST77T2B.js +0 -3
- package/dist/cli/chunks/experience-capture-middleware-X66IYSRV.js +0 -40
- package/dist/cli/chunks/file-discovery-3NHRUQQB.js +0 -2
- package/dist/cli/chunks/heartbeat-scheduler-OCKRACUW.js +0 -2
- package/dist/cli/chunks/hnsw-adapter-X67XG73C.js +0 -2
- package/dist/cli/chunks/hnsw-index-I7KCQBQR.js +0 -2
- package/dist/cli/chunks/hybrid-backend-FOUHTKAK.js +0 -2
- package/dist/cli/chunks/impact-analyzer-GXYVX46O.js +0 -2
- package/dist/cli/chunks/init-handler-2AXMXHYF.js +0 -86
- package/dist/cli/chunks/init-wizard-C2MRX2QG.js +0 -2
- package/dist/cli/chunks/kernel-Q2IUDIDC.js +0 -2
- package/dist/cli/chunks/knowledge-graph-E2Z6K5EE.js +0 -2
- package/dist/cli/chunks/learning-BEA26RNA.js +0 -122
- package/dist/cli/chunks/llm-router-service-YATYFEDD.js +0 -2
- package/dist/cli/chunks/load-test-LV77JXWA.js +0 -2
- package/dist/cli/chunks/memory-backend-XME3X3QX.js +0 -2
- package/dist/cli/chunks/memory-handlers-VG47X5DX.js +0 -2
- package/dist/cli/chunks/orchestrator-VHUXUYIM.js +0 -452
- package/dist/cli/chunks/pattern-null-store-TAXMLENP.js +0 -2
- package/dist/cli/chunks/plugin-2VAYWAO3.js +0 -27
- package/dist/cli/chunks/project-root-CFFPBGPX.js +0 -2
- package/dist/cli/chunks/protocol-executor-ML76QAVQ.js +0 -2
- package/dist/cli/chunks/qe-reasoning-bank-LUZH6RYV.js +0 -2
- package/dist/cli/chunks/queen-coordinator-EWXNIXB6.js +0 -2
- package/dist/cli/chunks/real-embeddings-GZV4VKK4.js +0 -2
- package/dist/cli/chunks/router-MXOBVEBF.js +0 -2
- package/dist/cli/chunks/routing-feedback-T6CCRUEK.js +0 -2
- package/dist/cli/chunks/rvf-dual-writer-WHXVT3V3.js +0 -2
- package/dist/cli/chunks/rvf-migration-adapter-JFPWIRCG.js +0 -2
- package/dist/cli/chunks/rvf-migration-coordinator-D4KUBNRZ.js +0 -2
- package/dist/cli/chunks/rvf-native-adapter-KOXR7TJL.js +0 -2
- package/dist/cli/chunks/safe-db-CI6IPSIN.js +0 -2
- package/dist/cli/chunks/schedule-X4HW6TVJ.js +0 -2
- package/dist/cli/chunks/scheduler-KCNJ2ON3.js +0 -2
- package/dist/cli/chunks/shared-rvf-adapter-KEQ5CLNI.js +0 -2
- package/dist/cli/chunks/sqlite-persistence-PGHU6VUR.js +0 -2
- package/dist/cli/chunks/sync-EFWXMA2H.js +0 -2
- package/dist/cli/chunks/token-bootstrap-S346YBVO.js +0 -2
- package/dist/cli/chunks/unified-memory-6CK3TUNQ.js +0 -2
- package/dist/cli/chunks/unified-memory-hnsw-A7BWBGYN.js +0 -2
- package/dist/cli/chunks/unified-persistence-GEPMDBQZ.js +0 -2
- package/dist/cli/chunks/visual-security-L4J7LQWT.js +0 -2
- package/dist/cli/chunks/witness-chain-CDUMX623.js +0 -2
- package/dist/cli/chunks/witness-chain-repair-WNYH6O4L.js +0 -2
- package/dist/cli/chunks/witness-key-manager-NQ5DAAC4.js +0 -2
- package/dist/cli/chunks/workflow-orchestrator-USJDWVDR.js +0 -2
- package/dist/cli/chunks/wrappers-CZDI6Z3X.js +0 -2
- /package/.claude/skills/qe-court/evals/fixtures/seeded-mutant-delivery/{budget.test.ts → budget-tests.ts.fixture} +0 -0
- /package/.claude/skills/qe-court/evals/fixtures/seeded-mutant-delivery/{budget.ts → budget.ts.fixture} +0 -0
- /package/.claude/skills/testability-scoring/resources/templates/{testability-scoring.spec.template.js → testability-scoring-spec.template.js} +0 -0
- /package/assets/skills/qe-court/evals/fixtures/seeded-mutant-delivery/{budget.test.ts → budget-tests.ts.fixture} +0 -0
- /package/assets/skills/qe-court/evals/fixtures/seeded-mutant-delivery/{budget.ts → budget.ts.fixture} +0 -0
- /package/assets/skills/testability-scoring/resources/templates/{testability-scoring.spec.template.js → testability-scoring-spec.template.js} +0 -0
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{b as o}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.6");process.exit(0)}
|
|
2
|
+
import{b as o}from"./chunk-7SAMMQVS.js";function s(n){return n instanceof Error?n.message:String(n)}function u(n){return n instanceof Error?n:new Error(String(n))}function a(n){return n instanceof r||typeof n=="object"&&n!==null&&n.callerError===!0}var r,e=o(()=>{"use strict";r=class extends Error{callerError=!0;constructor(t){super(t),this.name="CallerInputError"}}});export{s as a,u as b,r as c,a as d,e};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{l as c,o as d,q as f,s as h}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.6");process.exit(0)}
|
|
2
|
+
import{l as c,o as d,q as f,s as h}from"./chunk-YNG7E26C.js";import{a as r,e as u}from"./chunk-5LST62QR.js";import{a as s,c as o,d as g}from"./chunk-HEGGV2PT.js";import{a,e as m}from"./chunk-KYVIOC3C.js";m();h();u();g();var P={dbPath:c.dbPath,walMode:!0,mmapSize:r.MMAP_SIZE_BYTES,cacheSize:r.CACHE_SIZE_KB,busyTimeout:r.BUSY_TIMEOUT_MS},t=class e{static instance=null;static instancePromise=null;unifiedMemory=null;config;initialized=!1;initPromise=null;constructor(i){this.config={...P,...i}}static getInstance(i){return e.instance||(e.instance=new e(i)),e.instance}static async getInstanceAsync(i){return e.instance?.initialized?e.instance:(e.instancePromise||(e.instancePromise=(async()=>{let n=e.getInstance(i);return await n.initialize(),n})()),e.instancePromise)}static resetInstance(){e.instance&&(e.instance.close(),e.instance=null),e.instancePromise=null,f()}async initialize(){if(!this.initialized)return this.initPromise||(this.initPromise=this._doInitialize()),this.initPromise}async _doInitialize(){if(!this.initialized)try{let i={dbPath:this.config.dbPath,walMode:this.config.walMode,busyTimeout:this.config.busyTimeout,mmapSize:this.config.mmapSize,cacheSize:this.config.cacheSize};this.unifiedMemory=d(i),await this.unifiedMemory.initialize(),this.initialized=!0,console.log(`[UnifiedPersistence] Initialized via UnifiedMemoryManager: ${this.config.dbPath}`)}catch(i){throw this.initPromise=null,new Error(`Failed to initialize UnifiedPersistenceManager: ${a(i)}`)}}getDatabase(){if(!this.unifiedMemory||!this.initialized)throw new Error("UnifiedPersistenceManager not initialized");return this.unifiedMemory.getDatabase()}isInitialized(){return this.initialized}getDbPath(){return this.config.dbPath}prepare(i,n){if(!this.unifiedMemory)throw new Error("Database not initialized");return this.unifiedMemory.prepare(i,n)}transaction(i){if(!this.unifiedMemory)throw new Error("Database not initialized");return this.unifiedMemory.transaction(i)}getStats(){if(!this.unifiedMemory)throw new Error("Database not initialized");let i=this.unifiedMemory.getStats();return{tables:i.tables,fileSize:i.fileSize,walSize:i.walSize}}vacuum(){this.getDatabase().exec("VACUUM")}checkpoint(){this.getDatabase().pragma("wal_checkpoint(TRUNCATE)")}close(){this.initialized=!1,console.log("[UnifiedPersistence] Facade closed")}};function p(e){return t.getInstance(e)}async function E(e){let i=p(e);return await i.initialize(),i}function I(){t.resetInstance()}var l=!1;function M(){if(l)return;l=!0;let e=()=>{try{let n=t.instance;n&&n.close()}catch(n){console.debug("[UnifiedPersistence] Cleanup error:",n instanceof Error?n.message:n)}};process.on("beforeExit",e),s(e);let i=n=>{o(n)||(e(),process.exit(0))};process.on("SIGINT",i),process.on("SIGTERM",i)}M();export{P as a,t as b,p as c,E as d,I as e};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.6");process.exit(0)}
|
|
2
2
|
var l=[{name:"aqe-plan-quality",default:!0},{name:"aqe-plan-work",default:!0},{name:"aqe-research",default:!0},{name:"aqe-review-quality",default:!0},{name:"aqe-test-change",default:!0},{name:"aqe-ruflo",default:!1,files:["SKILL.md"]}];function t(a={}){return l.filter(e=>e.default||e.name==="aqe-ruflo"&&a.includeRuflo===!0)}export{t as a};
|
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{a as v}from"./chunk-
|
|
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.6");process.exit(0)}
|
|
2
|
+
import{a as v}from"./chunk-BUTGIVKW.js";import{a as h}from"./chunk-45MVRQG4.js";import{e as E}from"./chunk-IEPWO4XP.js";import{a as y,e as k}from"./chunk-KYVIOC3C.js";k();h();var l=E.create("qe-hooks"),u={PreTestGeneration:"qe:pre-test-generation",PostTestGeneration:"qe:post-test-generation",TestExecutionResult:"qe:test-execution-result",PreCoverageAnalysis:"qe:pre-coverage-analysis",PostCoverageAnalysis:"qe:post-coverage-analysis",CoverageGapIdentified:"qe:coverage-gap-identified",QEAgentRouting:"qe:agent-routing",QEAgentCompletion:"qe:agent-completion",QualityScoreCalculated:"qe:quality-score",RiskAssessmentComplete:"qe:risk-assessment",PatternLearned:"qe:pattern-learned",PatternApplied:"qe:pattern-applied",PatternPromoted:"qe:pattern-promoted",PreCompaction:"qe:pre-compaction"};function Q(i){return{[u.PreTestGeneration]:async t=>{let{targetFile:s,testType:a,framework:e,language:r}=t.data,n=await i.routeTask({task:`Generate ${a} tests for ${s}`,taskType:"test-generation",context:{framework:e,language:r,testType:a}});if(!n.success)return{success:!1,error:n.error.message};let o=[];try{let{getUnifiedMemory:c}=await import("./unified-memory-FCX7NLFZ.js");o=c().getDatabase().prepare(`
|
|
3
3
|
SELECT u.pattern_id, u.success, u.feedback
|
|
4
4
|
FROM qe_pattern_usage u
|
|
5
5
|
JOIN qe_patterns p ON u.pattern_id = p.id
|
|
6
6
|
WHERE p.qe_domain = 'test-generation'
|
|
7
7
|
ORDER BY u.created_at DESC
|
|
8
8
|
LIMIT 10
|
|
9
|
-
`).all()}catch{}return{success:!0,routing:n.value,guidance:n.value.guidance,data:{recommendedAgent:n.value.recommendedAgent,patterns:n.value.patterns.map(c=>c.id),recentExperiences:o}}},[u.PostTestGeneration]:async t=>{let{targetFile:s,generatedTests:a,testCount:e,framework:r,language:n,success:o,patternId:c}=t.data,d=0;if(c&&await i.recordOutcome({patternId:c,success:o,metrics:{testsPassed:0,testsFailed:0}}),o&&a&&e>0)try{(await i.storePattern({patternType:"test-template",name:`Generated tests for ${s.split("/").pop()}`,description:`Test template extracted from successful test generation for ${s}`,template:{type:"code",content:a,variables:[]},context:{framework:r,language:n,testType:"unit",tags:["generated","test-template",r,n]}})).success&&(d=1)}catch(p){l.debug("Pattern learning failed",{error:p instanceof Error?p.message:String(p)})}return{success:!0,patternsLearned:d,data:{learned:d>0}}},[u.TestExecutionResult]:async t=>{let{runId:s,patternId:a,passed:e,failed:r,duration:n,flaky:o}=t.data;if(a){let c=e+r>0?e/(e+r):0;await i.recordOutcome({patternId:a,success:c>.8&&!o,metrics:{testsPassed:e,testsFailed:r,executionTimeMs:n}})}return{success:!0,data:{runId:s,successRate:e+r>0?e/(e+r):0}}},[u.PreCoverageAnalysis]:async t=>{let{targetPath:s,currentCoverage:a}=t.data,e=await i.routeTask({task:`Analyze coverage gaps for ${s} (current: ${a}%)`,taskType:"analysis",domain:"coverage-analysis"});if(!e.success)return{success:!1,error:e.error.message};let r=[];try{let{getUnifiedMemory:n}=await import("./unified-memory-
|
|
9
|
+
`).all()}catch{}return{success:!0,routing:n.value,guidance:n.value.guidance,data:{recommendedAgent:n.value.recommendedAgent,patterns:n.value.patterns.map(c=>c.id),recentExperiences:o}}},[u.PostTestGeneration]:async t=>{let{targetFile:s,generatedTests:a,testCount:e,framework:r,language:n,success:o,patternId:c}=t.data,d=0;if(c&&await i.recordOutcome({patternId:c,success:o,metrics:{testsPassed:0,testsFailed:0}}),o&&a&&e>0)try{(await i.storePattern({patternType:"test-template",name:`Generated tests for ${s.split("/").pop()}`,description:`Test template extracted from successful test generation for ${s}`,template:{type:"code",content:a,variables:[]},context:{framework:r,language:n,testType:"unit",tags:["generated","test-template",r,n]}})).success&&(d=1)}catch(p){l.debug("Pattern learning failed",{error:p instanceof Error?p.message:String(p)})}return{success:!0,patternsLearned:d,data:{learned:d>0}}},[u.TestExecutionResult]:async t=>{let{runId:s,patternId:a,passed:e,failed:r,duration:n,flaky:o}=t.data;if(a){let c=e+r>0?e/(e+r):0;await i.recordOutcome({patternId:a,success:c>.8&&!o,metrics:{testsPassed:e,testsFailed:r,executionTimeMs:n}})}return{success:!0,data:{runId:s,successRate:e+r>0?e/(e+r):0}}},[u.PreCoverageAnalysis]:async t=>{let{targetPath:s,currentCoverage:a}=t.data,e=await i.routeTask({task:`Analyze coverage gaps for ${s} (current: ${a}%)`,taskType:"analysis",domain:"coverage-analysis"});if(!e.success)return{success:!1,error:e.error.message};let r=[];try{let{getUnifiedMemory:n}=await import("./unified-memory-FCX7NLFZ.js");r=n().getDatabase().prepare(`
|
|
10
10
|
SELECT u.pattern_id, u.success, u.feedback
|
|
11
11
|
FROM qe_pattern_usage u
|
|
12
12
|
JOIN qe_patterns p ON u.pattern_id = p.id
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{o as f,s as P}from"./chunk-EOR3RECZ.js";import{b as h,d as U}from"./chunk-RUSLEOMC.js";import{f as p,g as y}from"./chunk-E4VIVMDL.js";import{a as T,e as C}from"./chunk-NLDFNAOS.js";P();C();U();y();import{randomUUID as v}from"crypto";var M=p("TokenTracker"),S={costPerInputToken:.003/1e3,costPerOutputToken:.015/1e3},I={filePath:".agentic-qe/token-metrics.json",autoSaveIntervalMs:6e4,maxMetricsInMemory:1e4},m=class u{taskMetrics=[];agentMetrics=new Map;domainMetrics=new Map;sessionId;sessionStartTime;costConfig;cacheHits=0;earlyExits=0;totalTokensSaved=0;totalPatternsReused=0;initialized=!1;persistenceConfig=I;autoSaveTimer=null;isDirty=!1;db=null;kvPersistCount=0;static KV_NAMESPACE="token-usage-metrics";static KV_KEY="token-tracker-snapshot";static KV_TTL=604800;static KV_PERSIST_INTERVAL=10;constructor(){this.sessionId=`session-${Date.now()}-${v().substring(0,8)}`,this.sessionStartTime=Date.now(),this.costConfig=S}initialize(t){this.initialized||(this.initialized=!0,t&&(this.costConfig={...S,...t}),this.initializeDb().catch(e=>{M.warn("DB initialization failed",{error:e instanceof Error?e.message:String(e)})}),this.startAutoSave())}setCostConfig(t){this.costConfig={...this.costConfig,...t}}recordTokenUsage(t,e,n,a,s,r){this.ensureInitialized();let c,d,i,o,l,k;typeof e=="object"?(c="default",d="unknown",i="unknown",o=e,l=!1,k=0):(c=e,d=n??"unknown",i=a??"unknown",o=s,l=r?.patternReused??!1,k=r?.tokensSaved??0),o.estimatedCostUsd===void 0&&(o.estimatedCostUsd=this.calculateCost(o));let g={taskId:t,agentId:c,domain:d,operation:i,timestamp:Date.now(),usage:o,patternReused:l,tokensSaved:k};this.taskMetrics.push(g),this.updateAgentMetrics(c,o,l,k),this.updateDomainMetrics(d,o),l&&this.totalPatternsReused++,k>0&&(this.totalTokensSaved+=k),this.isDirty=!0,this.maybePersistToKv()}recordPatternReuse(t,e){this.ensureInitialized(),this.totalPatternsReused++,this.totalTokensSaved+=e;let n={taskId:t,agentId:"pattern-cache",domain:"optimization",operation:"pattern-reuse",timestamp:Date.now(),usage:{inputTokens:0,outputTokens:0,totalTokens:0,estimatedCostUsd:0},patternReused:!0,tokensSaved:e};this.taskMetrics.push(n),this.isDirty=!0}recordCacheHit(t){this.cacheHits++,this.totalTokensSaved+=t,this.isDirty=!0}recordEarlyExit(t){this.earlyExits++,this.totalTokensSaved+=t,this.isDirty=!0}getSessionSummary(t){this.ensureInitialized();let e=this.filterByTimeframe(this.taskMetrics,t),n=this.aggregateTokenUsage(e),a=new Map;for(let i of e){let o=a.get(i.agentId);o?(o.totalInputTokens+=i.usage.inputTokens,o.totalOutputTokens+=i.usage.outputTokens,o.totalTokens+=i.usage.totalTokens,o.totalCost+=i.usage.estimatedCostUsd||0,o.tasksExecuted++,i.patternReused&&o.patternsReused++,o.estimatedTokensSaved+=i.tokensSaved||0):a.set(i.agentId,{agentId:i.agentId,totalInputTokens:i.usage.inputTokens,totalOutputTokens:i.usage.outputTokens,totalTokens:i.usage.totalTokens,totalCost:i.usage.estimatedCostUsd||0,tasksExecuted:1,patternsReused:i.patternReused?1:0,estimatedTokensSaved:i.tokensSaved||0})}let s=new Map;for(let i of e){let o=s.get(i.domain);o?(o.inputTokens+=i.usage.inputTokens,o.outputTokens+=i.usage.outputTokens,o.totalTokens+=i.usage.totalTokens,o.estimatedCostUsd=(o.estimatedCostUsd||0)+(i.usage.estimatedCostUsd||0)):s.set(i.domain,{...i.usage})}let r=n.totalTokens,c=this.totalTokensSaved,d=r+c>0?c/(r+c)*100:0;return{sessionId:this.sessionId,startTime:this.sessionStartTime,endTime:Date.now(),byAgent:a,byDomain:s,totalUsage:n,optimizationStats:{patternsReused:this.totalPatternsReused,cacheHits:this.cacheHits,earlyExits:this.earlyExits,tokensSaved:this.totalTokensSaved,savingsPercentage:Math.round(d*100)/100}}}getAgentMetrics(t,e){this.ensureInitialized();let n=this.filterByTimeframe(this.taskMetrics,e);if(t){let s=n.filter(r=>r.agentId===t);return this.aggregateAgentMetrics(t,s)}let a=new Map;for(let s of n){let r=a.get(s.agentId)||[];r.push(s),a.set(s.agentId,r)}return Array.from(a.entries()).map(([s,r])=>this.aggregateAgentMetrics(s,r))}getDomainMetrics(t,e){this.ensureInitialized();let n=this.filterByTimeframe(this.taskMetrics,e);if(t){let s=n.filter(r=>r.domain===t);return this.aggregateTokenUsage(s)}let a=new Map;for(let s of n){let r=a.get(s.domain);r?(r.inputTokens+=s.usage.inputTokens,r.outputTokens+=s.usage.outputTokens,r.totalTokens+=s.usage.totalTokens,r.estimatedCostUsd=(r.estimatedCostUsd||0)+(s.usage.estimatedCostUsd||0)):a.set(s.domain,{...s.usage})}return a}getTaskMetrics(t){return this.ensureInitialized(),this.filterByTimeframe(this.taskMetrics,t)}getEfficiencyReport(t){return this.getTokenEfficiency(t)}getTokenEfficiency(t){this.ensureInitialized();let e=this.filterByTimeframe(this.taskMetrics,t),a=this.aggregateTokenUsage(e).totalTokens,s=this.totalTokensSaved,r=a+s>0?s/(a+s)*100:0,c=e.length,d=c>0?e.filter(l=>l.patternReused).length/c:0,i=c>0?a/c:0,o=this.generateRecommendations(e);return{totalTokensUsed:a,totalTokensSaved:s,savingsPercentage:Math.round(r*100)/100,patternReuseRate:Math.round(d*100)/100,averageTokensPerTask:Math.round(i),recommendations:o}}reset(){this.stopAutoSave(),this.taskMetrics=[],this.agentMetrics.clear(),this.domainMetrics.clear(),this.sessionId=`session-${Date.now()}-${v().substring(0,8)}`,this.sessionStartTime=Date.now(),this.cacheHits=0,this.earlyExits=0,this.totalTokensSaved=0,this.totalPatternsReused=0,this.isDirty=!1}configurePersistence(t){this.persistenceConfig={...this.persistenceConfig,...t},t.autoSaveIntervalMs!==void 0&&(this.stopAutoSave(),t.autoSaveIntervalMs>0&&this.startAutoSave())}startAutoSave(){this.autoSaveTimer||this.persistenceConfig.autoSaveIntervalMs>0&&(this.autoSaveTimer=setInterval(()=>{this.isDirty&&this.save().catch(t=>{console.warn("[TokenMetricsCollector] Auto-save failed:",t)})},this.persistenceConfig.autoSaveIntervalMs))}stopAutoSave(){this.autoSaveTimer&&(clearInterval(this.autoSaveTimer),this.autoSaveTimer=null)}async save(){let t=await import("fs"),e=await import("path"),n={version:"1.0.0",sessionId:this.sessionId,sessionStartTime:this.sessionStartTime,taskMetrics:this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory),optimizationStats:{cacheHits:this.cacheHits,earlyExits:this.earlyExits,totalTokensSaved:this.totalTokensSaved,totalPatternsReused:this.totalPatternsReused},lastSavedAt:Date.now()},a=e.resolve(this.persistenceConfig.filePath),s=e.dirname(a);t.existsSync(s)||t.mkdirSync(s,{recursive:!0}),t.writeFileSync(a,JSON.stringify(n,null,2)),this.isDirty=!1}async load(){let t=await import("fs"),n=(await import("path")).resolve(this.persistenceConfig.filePath);if(!t.existsSync(n))return!1;try{let a=t.readFileSync(n,"utf-8"),s=h(a);if(!s.version||!s.version.startsWith("1."))return console.warn("[TokenMetricsCollector] Incompatible data version, skipping load"),!1;let r=s.taskMetrics||[];this.taskMetrics=[...r,...this.taskMetrics],this.cacheHits+=s.optimizationStats?.cacheHits||0,this.earlyExits+=s.optimizationStats?.earlyExits||0,this.totalTokensSaved+=s.optimizationStats?.totalTokensSaved||0,this.totalPatternsReused+=s.optimizationStats?.totalPatternsReused||0;for(let c of r)this.updateAgentMetrics(c.agentId,c.usage,c.patternReused,c.tokensSaved||0),this.updateDomainMetrics(c.domain,c.usage);return this.taskMetrics.length>this.persistenceConfig.maxMetricsInMemory&&(this.taskMetrics=this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory)),!0}catch(a){return console.warn("[TokenMetricsCollector] Failed to load persisted data:",a),!1}}getPersistenceFilePath(){return this.persistenceConfig.filePath}hasUnsavedChanges(){return this.isDirty}async initializeDb(){try{this.db=f(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(t){console.warn("[TokenMetricsCollector] DB init failed, using memory-only:",T(t)),this.db=null}}async persistToKv(){if(!this.db)return;let t={version:"1.0.0",sessionId:this.sessionId,sessionStartTime:this.sessionStartTime,taskMetrics:this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory),optimizationStats:{cacheHits:this.cacheHits,earlyExits:this.earlyExits,totalTokensSaved:this.totalTokensSaved,totalPatternsReused:this.totalPatternsReused},lastSavedAt:Date.now()};await this.db.kvSet(u.KV_KEY,t,u.KV_NAMESPACE,u.KV_TTL)}async loadFromKv(){if(!this.db)return!1;let t=await this.db.kvGet(u.KV_KEY,u.KV_NAMESPACE);if(!t)return!1;if(!t.version||!t.version.startsWith("1."))return console.warn("[TokenMetricsCollector] Incompatible kv_store data version, skipping load"),!1;let e=t.taskMetrics||[];this.taskMetrics=[...e,...this.taskMetrics],this.cacheHits+=t.optimizationStats?.cacheHits||0,this.earlyExits+=t.optimizationStats?.earlyExits||0,this.totalTokensSaved+=t.optimizationStats?.totalTokensSaved||0,this.totalPatternsReused+=t.optimizationStats?.totalPatternsReused||0;for(let n of e)this.updateAgentMetrics(n.agentId,n.usage,n.patternReused,n.tokensSaved||0),this.updateDomainMetrics(n.domain,n.usage);return this.taskMetrics.length>this.persistenceConfig.maxMetricsInMemory&&(this.taskMetrics=this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory)),!0}maybePersistToKv(){this.kvPersistCount++,this.kvPersistCount>=u.KV_PERSIST_INTERVAL&&(this.kvPersistCount=0,this.persistToKv().catch(t=>{M.warn("KV persist failed",{error:t instanceof Error?t.message:String(t)})}))}ensureInitialized(){this.initialized||this.initialize()}calculateCost(t){let e=t.inputTokens*this.costConfig.costPerInputToken,n=t.outputTokens*this.costConfig.costPerOutputToken;return Math.round((e+n)*1e5)/1e5}filterByTimeframe(t,e){if(!e)return t;let n=Date.now(),a;switch(e){case"1h":a=n-3600*1e3;break;case"24h":a=n-1440*60*1e3;break;case"7d":a=n-10080*60*1e3;break;case"30d":a=n-720*60*60*1e3;break;default:return t}return t.filter(s=>s.timestamp>=a)}aggregateTokenUsage(t){let e=0,n=0,a=0,s=0;for(let r of t)e+=r.usage.inputTokens,n+=r.usage.outputTokens,a+=r.usage.totalTokens,s+=r.usage.estimatedCostUsd||0;return{inputTokens:e,outputTokens:n,totalTokens:a,estimatedCostUsd:Math.round(s*1e5)/1e5}}aggregateAgentMetrics(t,e){let n=0,a=0,s=0,r=0,c=0,d=0;for(let i of e)n+=i.usage.inputTokens,a+=i.usage.outputTokens,s+=i.usage.totalTokens,r+=i.usage.estimatedCostUsd||0,i.patternReused&&c++,d+=i.tokensSaved||0;return{agentId:t,totalInputTokens:n,totalOutputTokens:a,totalTokens:s,totalCost:Math.round(r*1e5)/1e5,tasksExecuted:e.length,patternsReused:c,estimatedTokensSaved:d}}updateAgentMetrics(t,e,n,a){let s=this.agentMetrics.get(t);s?(s.totalInputTokens+=e.inputTokens,s.totalOutputTokens+=e.outputTokens,s.totalTokens+=e.totalTokens,s.totalCost+=e.estimatedCostUsd||0,s.tasksExecuted++,n&&s.patternsReused++,s.estimatedTokensSaved+=a):this.agentMetrics.set(t,{agentId:t,totalInputTokens:e.inputTokens,totalOutputTokens:e.outputTokens,totalTokens:e.totalTokens,totalCost:e.estimatedCostUsd||0,tasksExecuted:1,patternsReused:n?1:0,estimatedTokensSaved:a})}updateDomainMetrics(t,e){let n=this.domainMetrics.get(t);n?(n.inputTokens+=e.inputTokens,n.outputTokens+=e.outputTokens,n.totalTokens+=e.totalTokens,n.estimatedCostUsd=(n.estimatedCostUsd||0)+(e.estimatedCostUsd||0)):this.domainMetrics.set(t,{...e})}generateRecommendations(t){let e=[];if(t.length===0)return["No token usage data available yet. Start executing tasks to track consumption."];let n=t.filter(i=>i.patternReused).length/t.length;n<.2?e.push("Low pattern reuse rate detected. Consider enabling pattern caching for similar tasks."):n>.5&&e.push("Good pattern reuse rate. Continue leveraging cached patterns for token savings.");let a=new Map;for(let i of t){let o=a.get(i.domain)||0;a.set(i.domain,o+i.usage.totalTokens)}let s=Array.from(a.entries()).sort((i,o)=>o[1]-i[1]);if(s.length>0){let i=s[0];e.push(`Highest token consumer: ${i[0]} (${i[1].toLocaleString()} tokens). Consider optimizing prompts or increasing caching.`)}let r=t.reduce((i,o)=>i+o.usage.inputTokens,0);return t.reduce((i,o)=>i+o.usage.outputTokens,0)/(r||1)>2&&e.push("High output-to-input token ratio. Consider requesting more concise responses."),this.cacheHits===0&&t.length>10&&e.push("No cache hits detected. Enable response caching to reduce duplicate API calls."),this.earlyExits===0&&t.length>20&&e.push("Early exit optimization not utilized. Enable high-confidence pattern matching to skip unnecessary LLM calls."),e}};function b(u){return u.toLocaleString("en-US")}function z(u){if(process.env.AQE_TOKEN_DASHBOARD_ENABLED==="false")return"Token dashboard disabled (AQE_TOKEN_DASHBOARD_ENABLED=false)";if(!u){let d=E.getSessionSummary(),i=d.totalUsage.totalTokens,o=d.totalUsage.estimatedCostUsd??0,l=d.optimizationStats.tokensSaved,k=i>0?o/i:0,g=l*k;u={totalTokens:i,totalCostUsd:o,savedTokens:l,savedCostUsd:g}}let t=u.totalTokens??0,e=u.totalCostUsd??0,n=u.savedTokens??0,a=u.savedCostUsd??0,s=u.budgetLimitUsd;if(t===0&&n===0)return"Token Dashboard: No data available";let r=`Token Usage: ${b(t)} tokens ($${e.toFixed(2)})`;n>0&&(r+=` | Saved: ${b(n)} tokens ($${a.toFixed(2)}) via pattern reuse`);let c=[];if(s!==void 0&&s>0){let d=Math.round(e/s*100);c.push(`Budget: $${e.toFixed(2)} / $${s.toFixed(2)} (${d}%)`)}if(u.tierSplit&&Object.keys(u.tierSplit).length>0){let d=Object.entries(u.tierSplit).sort((i,o)=>o[1]-i[1]).map(([i,o])=>`${i} ${o}%`);c.push(`Tier split: ${d.join(" | ")}`)}return c.length===0?r:`${r}
|
|
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.6");process.exit(0)}
|
|
2
|
+
import{o as f,s as P}from"./chunk-YNG7E26C.js";import{b as h,d as U}from"./chunk-22OZIJAD.js";import{f as p,g as y}from"./chunk-IEPWO4XP.js";import{a as T,e as C}from"./chunk-KYVIOC3C.js";P();C();U();y();import{randomUUID as v}from"crypto";var M=p("TokenTracker"),S={costPerInputToken:.003/1e3,costPerOutputToken:.015/1e3},I={filePath:".agentic-qe/token-metrics.json",autoSaveIntervalMs:6e4,maxMetricsInMemory:1e4},m=class u{taskMetrics=[];agentMetrics=new Map;domainMetrics=new Map;sessionId;sessionStartTime;costConfig;cacheHits=0;earlyExits=0;totalTokensSaved=0;totalPatternsReused=0;initialized=!1;persistenceConfig=I;autoSaveTimer=null;isDirty=!1;db=null;kvPersistCount=0;static KV_NAMESPACE="token-usage-metrics";static KV_KEY="token-tracker-snapshot";static KV_TTL=604800;static KV_PERSIST_INTERVAL=10;constructor(){this.sessionId=`session-${Date.now()}-${v().substring(0,8)}`,this.sessionStartTime=Date.now(),this.costConfig=S}initialize(t){this.initialized||(this.initialized=!0,t&&(this.costConfig={...S,...t}),this.initializeDb().catch(e=>{M.warn("DB initialization failed",{error:e instanceof Error?e.message:String(e)})}),this.startAutoSave())}setCostConfig(t){this.costConfig={...this.costConfig,...t}}recordTokenUsage(t,e,n,a,s,r){this.ensureInitialized();let c,d,i,o,l,k;typeof e=="object"?(c="default",d="unknown",i="unknown",o=e,l=!1,k=0):(c=e,d=n??"unknown",i=a??"unknown",o=s,l=r?.patternReused??!1,k=r?.tokensSaved??0),o.estimatedCostUsd===void 0&&(o.estimatedCostUsd=this.calculateCost(o));let g={taskId:t,agentId:c,domain:d,operation:i,timestamp:Date.now(),usage:o,patternReused:l,tokensSaved:k};this.taskMetrics.push(g),this.updateAgentMetrics(c,o,l,k),this.updateDomainMetrics(d,o),l&&this.totalPatternsReused++,k>0&&(this.totalTokensSaved+=k),this.isDirty=!0,this.maybePersistToKv()}recordPatternReuse(t,e){this.ensureInitialized(),this.totalPatternsReused++,this.totalTokensSaved+=e;let n={taskId:t,agentId:"pattern-cache",domain:"optimization",operation:"pattern-reuse",timestamp:Date.now(),usage:{inputTokens:0,outputTokens:0,totalTokens:0,estimatedCostUsd:0},patternReused:!0,tokensSaved:e};this.taskMetrics.push(n),this.isDirty=!0}recordCacheHit(t){this.cacheHits++,this.totalTokensSaved+=t,this.isDirty=!0}recordEarlyExit(t){this.earlyExits++,this.totalTokensSaved+=t,this.isDirty=!0}getSessionSummary(t){this.ensureInitialized();let e=this.filterByTimeframe(this.taskMetrics,t),n=this.aggregateTokenUsage(e),a=new Map;for(let i of e){let o=a.get(i.agentId);o?(o.totalInputTokens+=i.usage.inputTokens,o.totalOutputTokens+=i.usage.outputTokens,o.totalTokens+=i.usage.totalTokens,o.totalCost+=i.usage.estimatedCostUsd||0,o.tasksExecuted++,i.patternReused&&o.patternsReused++,o.estimatedTokensSaved+=i.tokensSaved||0):a.set(i.agentId,{agentId:i.agentId,totalInputTokens:i.usage.inputTokens,totalOutputTokens:i.usage.outputTokens,totalTokens:i.usage.totalTokens,totalCost:i.usage.estimatedCostUsd||0,tasksExecuted:1,patternsReused:i.patternReused?1:0,estimatedTokensSaved:i.tokensSaved||0})}let s=new Map;for(let i of e){let o=s.get(i.domain);o?(o.inputTokens+=i.usage.inputTokens,o.outputTokens+=i.usage.outputTokens,o.totalTokens+=i.usage.totalTokens,o.estimatedCostUsd=(o.estimatedCostUsd||0)+(i.usage.estimatedCostUsd||0)):s.set(i.domain,{...i.usage})}let r=n.totalTokens,c=this.totalTokensSaved,d=r+c>0?c/(r+c)*100:0;return{sessionId:this.sessionId,startTime:this.sessionStartTime,endTime:Date.now(),byAgent:a,byDomain:s,totalUsage:n,optimizationStats:{patternsReused:this.totalPatternsReused,cacheHits:this.cacheHits,earlyExits:this.earlyExits,tokensSaved:this.totalTokensSaved,savingsPercentage:Math.round(d*100)/100}}}getAgentMetrics(t,e){this.ensureInitialized();let n=this.filterByTimeframe(this.taskMetrics,e);if(t){let s=n.filter(r=>r.agentId===t);return this.aggregateAgentMetrics(t,s)}let a=new Map;for(let s of n){let r=a.get(s.agentId)||[];r.push(s),a.set(s.agentId,r)}return Array.from(a.entries()).map(([s,r])=>this.aggregateAgentMetrics(s,r))}getDomainMetrics(t,e){this.ensureInitialized();let n=this.filterByTimeframe(this.taskMetrics,e);if(t){let s=n.filter(r=>r.domain===t);return this.aggregateTokenUsage(s)}let a=new Map;for(let s of n){let r=a.get(s.domain);r?(r.inputTokens+=s.usage.inputTokens,r.outputTokens+=s.usage.outputTokens,r.totalTokens+=s.usage.totalTokens,r.estimatedCostUsd=(r.estimatedCostUsd||0)+(s.usage.estimatedCostUsd||0)):a.set(s.domain,{...s.usage})}return a}getTaskMetrics(t){return this.ensureInitialized(),this.filterByTimeframe(this.taskMetrics,t)}getEfficiencyReport(t){return this.getTokenEfficiency(t)}getTokenEfficiency(t){this.ensureInitialized();let e=this.filterByTimeframe(this.taskMetrics,t),a=this.aggregateTokenUsage(e).totalTokens,s=this.totalTokensSaved,r=a+s>0?s/(a+s)*100:0,c=e.length,d=c>0?e.filter(l=>l.patternReused).length/c:0,i=c>0?a/c:0,o=this.generateRecommendations(e);return{totalTokensUsed:a,totalTokensSaved:s,savingsPercentage:Math.round(r*100)/100,patternReuseRate:Math.round(d*100)/100,averageTokensPerTask:Math.round(i),recommendations:o}}reset(){this.stopAutoSave(),this.taskMetrics=[],this.agentMetrics.clear(),this.domainMetrics.clear(),this.sessionId=`session-${Date.now()}-${v().substring(0,8)}`,this.sessionStartTime=Date.now(),this.cacheHits=0,this.earlyExits=0,this.totalTokensSaved=0,this.totalPatternsReused=0,this.isDirty=!1}configurePersistence(t){this.persistenceConfig={...this.persistenceConfig,...t},t.autoSaveIntervalMs!==void 0&&(this.stopAutoSave(),t.autoSaveIntervalMs>0&&this.startAutoSave())}startAutoSave(){this.autoSaveTimer||this.persistenceConfig.autoSaveIntervalMs>0&&(this.autoSaveTimer=setInterval(()=>{this.isDirty&&this.save().catch(t=>{console.warn("[TokenMetricsCollector] Auto-save failed:",t)})},this.persistenceConfig.autoSaveIntervalMs))}stopAutoSave(){this.autoSaveTimer&&(clearInterval(this.autoSaveTimer),this.autoSaveTimer=null)}async save(){let t=await import("fs"),e=await import("path"),n={version:"1.0.0",sessionId:this.sessionId,sessionStartTime:this.sessionStartTime,taskMetrics:this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory),optimizationStats:{cacheHits:this.cacheHits,earlyExits:this.earlyExits,totalTokensSaved:this.totalTokensSaved,totalPatternsReused:this.totalPatternsReused},lastSavedAt:Date.now()},a=e.resolve(this.persistenceConfig.filePath),s=e.dirname(a);t.existsSync(s)||t.mkdirSync(s,{recursive:!0}),t.writeFileSync(a,JSON.stringify(n,null,2)),this.isDirty=!1}async load(){let t=await import("fs"),n=(await import("path")).resolve(this.persistenceConfig.filePath);if(!t.existsSync(n))return!1;try{let a=t.readFileSync(n,"utf-8"),s=h(a);if(!s.version||!s.version.startsWith("1."))return console.warn("[TokenMetricsCollector] Incompatible data version, skipping load"),!1;let r=s.taskMetrics||[];this.taskMetrics=[...r,...this.taskMetrics],this.cacheHits+=s.optimizationStats?.cacheHits||0,this.earlyExits+=s.optimizationStats?.earlyExits||0,this.totalTokensSaved+=s.optimizationStats?.totalTokensSaved||0,this.totalPatternsReused+=s.optimizationStats?.totalPatternsReused||0;for(let c of r)this.updateAgentMetrics(c.agentId,c.usage,c.patternReused,c.tokensSaved||0),this.updateDomainMetrics(c.domain,c.usage);return this.taskMetrics.length>this.persistenceConfig.maxMetricsInMemory&&(this.taskMetrics=this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory)),!0}catch(a){return console.warn("[TokenMetricsCollector] Failed to load persisted data:",a),!1}}getPersistenceFilePath(){return this.persistenceConfig.filePath}hasUnsavedChanges(){return this.isDirty}async initializeDb(){try{this.db=f(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(t){console.warn("[TokenMetricsCollector] DB init failed, using memory-only:",T(t)),this.db=null}}async persistToKv(){if(!this.db)return;let t={version:"1.0.0",sessionId:this.sessionId,sessionStartTime:this.sessionStartTime,taskMetrics:this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory),optimizationStats:{cacheHits:this.cacheHits,earlyExits:this.earlyExits,totalTokensSaved:this.totalTokensSaved,totalPatternsReused:this.totalPatternsReused},lastSavedAt:Date.now()};await this.db.kvSet(u.KV_KEY,t,u.KV_NAMESPACE,u.KV_TTL)}async loadFromKv(){if(!this.db)return!1;let t=await this.db.kvGet(u.KV_KEY,u.KV_NAMESPACE);if(!t)return!1;if(!t.version||!t.version.startsWith("1."))return console.warn("[TokenMetricsCollector] Incompatible kv_store data version, skipping load"),!1;let e=t.taskMetrics||[];this.taskMetrics=[...e,...this.taskMetrics],this.cacheHits+=t.optimizationStats?.cacheHits||0,this.earlyExits+=t.optimizationStats?.earlyExits||0,this.totalTokensSaved+=t.optimizationStats?.totalTokensSaved||0,this.totalPatternsReused+=t.optimizationStats?.totalPatternsReused||0;for(let n of e)this.updateAgentMetrics(n.agentId,n.usage,n.patternReused,n.tokensSaved||0),this.updateDomainMetrics(n.domain,n.usage);return this.taskMetrics.length>this.persistenceConfig.maxMetricsInMemory&&(this.taskMetrics=this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory)),!0}maybePersistToKv(){this.kvPersistCount++,this.kvPersistCount>=u.KV_PERSIST_INTERVAL&&(this.kvPersistCount=0,this.persistToKv().catch(t=>{M.warn("KV persist failed",{error:t instanceof Error?t.message:String(t)})}))}ensureInitialized(){this.initialized||this.initialize()}calculateCost(t){let e=t.inputTokens*this.costConfig.costPerInputToken,n=t.outputTokens*this.costConfig.costPerOutputToken;return Math.round((e+n)*1e5)/1e5}filterByTimeframe(t,e){if(!e)return t;let n=Date.now(),a;switch(e){case"1h":a=n-3600*1e3;break;case"24h":a=n-1440*60*1e3;break;case"7d":a=n-10080*60*1e3;break;case"30d":a=n-720*60*60*1e3;break;default:return t}return t.filter(s=>s.timestamp>=a)}aggregateTokenUsage(t){let e=0,n=0,a=0,s=0;for(let r of t)e+=r.usage.inputTokens,n+=r.usage.outputTokens,a+=r.usage.totalTokens,s+=r.usage.estimatedCostUsd||0;return{inputTokens:e,outputTokens:n,totalTokens:a,estimatedCostUsd:Math.round(s*1e5)/1e5}}aggregateAgentMetrics(t,e){let n=0,a=0,s=0,r=0,c=0,d=0;for(let i of e)n+=i.usage.inputTokens,a+=i.usage.outputTokens,s+=i.usage.totalTokens,r+=i.usage.estimatedCostUsd||0,i.patternReused&&c++,d+=i.tokensSaved||0;return{agentId:t,totalInputTokens:n,totalOutputTokens:a,totalTokens:s,totalCost:Math.round(r*1e5)/1e5,tasksExecuted:e.length,patternsReused:c,estimatedTokensSaved:d}}updateAgentMetrics(t,e,n,a){let s=this.agentMetrics.get(t);s?(s.totalInputTokens+=e.inputTokens,s.totalOutputTokens+=e.outputTokens,s.totalTokens+=e.totalTokens,s.totalCost+=e.estimatedCostUsd||0,s.tasksExecuted++,n&&s.patternsReused++,s.estimatedTokensSaved+=a):this.agentMetrics.set(t,{agentId:t,totalInputTokens:e.inputTokens,totalOutputTokens:e.outputTokens,totalTokens:e.totalTokens,totalCost:e.estimatedCostUsd||0,tasksExecuted:1,patternsReused:n?1:0,estimatedTokensSaved:a})}updateDomainMetrics(t,e){let n=this.domainMetrics.get(t);n?(n.inputTokens+=e.inputTokens,n.outputTokens+=e.outputTokens,n.totalTokens+=e.totalTokens,n.estimatedCostUsd=(n.estimatedCostUsd||0)+(e.estimatedCostUsd||0)):this.domainMetrics.set(t,{...e})}generateRecommendations(t){let e=[];if(t.length===0)return["No token usage data available yet. Start executing tasks to track consumption."];let n=t.filter(i=>i.patternReused).length/t.length;n<.2?e.push("Low pattern reuse rate detected. Consider enabling pattern caching for similar tasks."):n>.5&&e.push("Good pattern reuse rate. Continue leveraging cached patterns for token savings.");let a=new Map;for(let i of t){let o=a.get(i.domain)||0;a.set(i.domain,o+i.usage.totalTokens)}let s=Array.from(a.entries()).sort((i,o)=>o[1]-i[1]);if(s.length>0){let i=s[0];e.push(`Highest token consumer: ${i[0]} (${i[1].toLocaleString()} tokens). Consider optimizing prompts or increasing caching.`)}let r=t.reduce((i,o)=>i+o.usage.inputTokens,0);return t.reduce((i,o)=>i+o.usage.outputTokens,0)/(r||1)>2&&e.push("High output-to-input token ratio. Consider requesting more concise responses."),this.cacheHits===0&&t.length>10&&e.push("No cache hits detected. Enable response caching to reduce duplicate API calls."),this.earlyExits===0&&t.length>20&&e.push("Early exit optimization not utilized. Enable high-confidence pattern matching to skip unnecessary LLM calls."),e}};function b(u){return u.toLocaleString("en-US")}function z(u){if(process.env.AQE_TOKEN_DASHBOARD_ENABLED==="false")return"Token dashboard disabled (AQE_TOKEN_DASHBOARD_ENABLED=false)";if(!u){let d=E.getSessionSummary(),i=d.totalUsage.totalTokens,o=d.totalUsage.estimatedCostUsd??0,l=d.optimizationStats.tokensSaved,k=i>0?o/i:0,g=l*k;u={totalTokens:i,totalCostUsd:o,savedTokens:l,savedCostUsd:g}}let t=u.totalTokens??0,e=u.totalCostUsd??0,n=u.savedTokens??0,a=u.savedCostUsd??0,s=u.budgetLimitUsd;if(t===0&&n===0)return"Token Dashboard: No data available";let r=`Token Usage: ${b(t)} tokens ($${e.toFixed(2)})`;n>0&&(r+=` | Saved: ${b(n)} tokens ($${a.toFixed(2)}) via pattern reuse`);let c=[];if(s!==void 0&&s>0){let d=Math.round(e/s*100);c.push(`Budget: $${e.toFixed(2)} / $${s.toFixed(2)} (${d}%)`)}if(u.tierSplit&&Object.keys(u.tierSplit).length>0){let d=Object.entries(u.tierSplit).sort((i,o)=>o[1]-i[1]).map(([i,o])=>`${i} ${o}%`);c.push(`Tier split: ${d.join(" | ")}`)}return c.length===0?r:`${r}
|
|
3
3
|
${c.join(" | ")}`}var E=new m;function $(u){return`$${u.toFixed(2)}`}export{z as a,E as b,$ as c};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{a as F}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.6");process.exit(0)}
|
|
2
|
+
import{a as F}from"./chunk-F3KS3TAB.js";import{a as b,b as E,c as z,d as M,e as C,f as P,g as B}from"./chunk-MQTA6KIO.js";function W(s,e){let n=s.slice(0,e).split(`
|
|
3
3
|
`),r=n.length,o=(n[n.length-1]||"").length;return{line:r,column:o,offset:e}}function p(s,e,n,r,o){return{start:W(s,e),end:W(s,n),oldText:s.slice(e,n),newText:r,description:o}}function _(s,e){let n=[...e].sort((o,t)=>t.start.offset-o.start.offset),r=s;for(let o of n)r=r.slice(0,o.start.offset)+o.newText+r.slice(o.end.offset);return r}function U(s,e){if(s.length===0)return 1;let n=s.reduce((t,a)=>t+Math.abs(a.newText.length-a.oldText.length),0)/s.length,r=Math.max(.5,1-n/1e3),o=Math.max(.7,1-s.length/100);return Math.min(1,e*r*o)}function T(s,e,n,r,o=.9){let t=_(s,n),a=Date.now()-r;return{success:!0,transformType:e,originalCode:s,transformedCode:t,edits:n,changeCount:n.length,confidence:U(n,o),durationMs:a,implementationUsed:"typescript",usedFallback:!1,warnings:[]}}function w(s,e,n,r){return{success:!1,transformType:e,originalCode:s,transformedCode:s,edits:[],changeCount:0,confidence:0,durationMs:Date.now()-r,implementationUsed:"typescript",usedFallback:!1,error:n,warnings:[]}}function Z(s,e={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}}){let n=Date.now(),r=[],o=[];try{let t=/\bvar\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g,a=/([a-zA-Z_$][a-zA-Z0-9_$]*)\s*(?:\+\+|--|[+\-*/%&|^]=|\?\?=|&&=|\|\|=|=(?!=))/g,i=[],l;for(;(l=t.exec(s))!==null;)i.push({name:l[1],offset:l.index});let m=new Set;for(;(l=a.exec(s))!==null;)m.add(l[1]);let u=/\bfor\s*\(\s*var\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g,c=new Set;for(;(l=u.exec(s))!==null;)c.add(l[1]);for(let g of i){let d=c.has(g.name)||m.has(g.name)?"let":"const";r.push(p(s,g.offset,g.offset+3,d,`Convert var ${g.name} to ${d}`))}e.debug("var-to-const transform completed",{declarations:i.length,reassigned:m.size,loopVars:c.size});let f=T(s,"var-to-const",r,n,.95);return f.warnings=o,f}catch(t){return e.error("var-to-const transform failed",t),w(s,"var-to-const",t instanceof Error?t.message:"Unknown error",n)}}function O(s,e={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}}){let n=Date.now(),r=[],o=[];try{let t=/function\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*\(([^)]*)\)/g,a=/(?:const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*\(([^)]*)\)\s*=>/g,i=/([a-zA-Z_$][a-zA-Z0-9_$]*)\s*\(([^)]*)\)\s*(?::\s*[^{]+)?\s*\{/g,l;for(;(l=t.exec(s))!==null;){let u=l[2].trim();if(u&&!u.includes(":")){let c=u.split(",").map(d=>{let h=d.trim().replace(/\s*=.*$/,"");return h&&!h.includes(":")?`${h}: unknown`:d.trim()}).join(", "),f=l.index+l[0].indexOf("(")+1,g=f+l[2].length;r.push(p(s,f,g,c,`Add types to function ${l[1]} parameters`))}}for(;(l=a.exec(s))!==null;){let u=l[2].trim();if(u&&!u.includes(":")){let c=u.split(",").map(d=>{let h=d.trim().replace(/\s*=.*$/,"");return h&&!h.includes(":")?`${h}: unknown`:d.trim()}).join(", "),f=l.index+l[0].indexOf("(")+1,g=f+l[2].length;r.push(p(s,f,g,c,`Add types to arrow function ${l[1]} parameters`))}}e.debug("add-types transform completed",{edits:r.length});let m=T(s,"add-types",r,n,.7);return m.warnings=o,r.length>0&&m.warnings.push('Type annotations use "unknown" - manual review recommended'),m}catch(t){return e.error("add-types transform failed",t),w(s,"add-types",t instanceof Error?t.message:"Unknown error",n)}}function I(s,e={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}}){let n=Date.now(),r=[],o=[];try{let t=/^\s*console\.(log|warn|error|info|debug|trace|dir|table|time|timeEnd|group|groupEnd|assert)\s*\([^)]*\);?\s*$/gm,a=/console\.(log|warn|error|info|debug|trace|dir|table|time|timeEnd|group|groupEnd|assert)\s*\([^)]*\)/g,i,l=new Set;for(;(i=t.exec(s))!==null;)l.has(i.index)||(l.add(i.index),r.push(p(s,i.index,i.index+i[0].length,"",`Remove console.${i[1]}() statement`)));for(;(i=a.exec(s))!==null;){if(l.has(i.index))continue;let u=s.lastIndexOf(`
|
|
4
4
|
`,i.index)+1,c=s.indexOf(`
|
|
5
5
|
`,i.index),f=s.slice(u,c===-1?void 0:c);/^\s*console\./.test(f)||(l.add(i.index),o.push(`Inline console.${i[1]}() at offset ${i.index} - consider manual review`))}e.debug("remove-console transform completed",{removed:r.length,warnings:o.length});let m=T(s,"remove-console",r,n,.95);return m.warnings=o,m}catch(t){return e.error("remove-console transform failed",t),w(s,"remove-console",t instanceof Error?t.message:"Unknown error",n)}}function j(s,e={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}}){let n=Date.now(),r=[],o=[];try{let t=/([a-zA-Z_$][a-zA-Z0-9_$]*(?:\([^)]*\))?)\s*\.then\s*\(\s*(?:async\s*)?\(?\s*([a-zA-Z_$][a-zA-Z0-9_$]*)\s*\)?\s*=>\s*([^)]+)\)/g,a;for(;(a=t.exec(s))!==null;){let[l,m,u,c]=a;if(c.includes(".then")||c.includes(".catch")){o.push(`Complex promise chain at offset ${a.index} - manual review recommended`);continue}let f=`const ${u} = await ${m};
|
|
6
|
-
${c.trim()}`;r.push(p(s,a.index,a.index+l.length,f,"Convert .then() to await"))}e.debug("promise-to-async transform completed",{converted:r.length,warnings:o.length});let i=T(s,"promise-to-async",r,n,.65);return i.warnings=o,r.length>0&&i.warnings.push("Promise chains converted to await - ensure containing function is async"),i}catch(t){return e.error("promise-to-async transform failed",t),w(s,"promise-to-async",t instanceof Error?t.message:"Unknown error",n)}}function N(s,e={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}}){let n=Date.now(),r=[],o=[];try{let t,a=/(?:const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*require\s*\(\s*(['"`][^'"`]+['"`])\s*\)\s*;?/g;for(;(t=a.exec(s))!==null;){let[c,f,g]=t,d=`import ${f} from ${g};`;r.push(p(s,t.index,t.index+c.length,d,"Convert require to import"))}let i=/(?:const|let|var)\s+\{\s*([^}]+)\s*\}\s*=\s*require\s*\(\s*(['"`][^'"`]+['"`])\s*\)\s*;?/g;for(;(t=i.exec(s))!==null;){let[c,f,g]=t,d=`import { ${f.trim()} } from ${g};`;r.push(p(s,t.index,t.index+c.length,d,"Convert destructured require to import"))}let l=/module\.exports\s*=\s*([^;]+);?/g;for(;(t=l.exec(s))!==null;){let[c,f]=t,g=`export default ${f.trim()};`;r.push(p(s,t.index,t.index+c.length,g,"Convert module.exports to export default"))}let m=/exports\.([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*([^;]+);?/g;for(;(t=m.exec(s))!==null;){let[c,f,g]=t,d=g.trim(),h;d.startsWith("function")||d.startsWith("class")?h=`export ${d}`:d.startsWith("async function")?h=`export ${d}`:h=`export const ${f} = ${d};`,r.push(p(s,t.index,t.index+c.length,h,`Convert exports.${f} to named export`))}e.debug("cjs-to-esm transform completed",{edits:r.length});let u=T(s,"cjs-to-esm",r,n,.85);return u.warnings=o,u}catch(t){return e.error("cjs-to-esm transform failed",t),w(s,"cjs-to-esm",t instanceof Error?t.message:"Unknown error",n)}}function H(s,e={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}}){let n=Date.now(),r=[],o=[];try{let t=/(const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*function\s*\(([^)]*)\)\s*\{/g,a;for(;(a=t.exec(s))!==null;){let[m,u,c,f]=a,g=a.index,d=1,h=g+m.length;for(;d>0&&h<s.length;)s[h]==="{"&&d++,s[h]==="}"&&d--,h++;let S=s.slice(g,h);if(/\bthis\b/.test(S)){o.push(`Function ${c} uses 'this' - skipping arrow conversion (would change binding)`);continue}if(/\barguments\b/.test(S)){o.push(`Function ${c} uses 'arguments' - skipping arrow conversion (not available in arrow functions)`);continue}let D=`${u} ${c} = (${f}) => {`;r.push(p(s,a.index,a.index+m.length,D,`Convert function ${c} to arrow function`))}let i=/function\s*\(([^)]*)\)\s*\{\s*return\s+([^;]+);\s*\}/g;for(;(a=i.exec(s))!==null;){let[m,u,c]=a;if(/\b(this|arguments)\b/.test(m))continue;let f=u.includes(",")||u.trim()===""?`(${u}) => ${c}`:`${u.trim()} => ${c}`;r.push(p(s,a.index,a.index+m.length,f,"Convert callback to arrow function"))}e.debug("func-to-arrow transform completed",{converted:r.length,warnings:o.length});let l=T(s,"func-to-arrow",r,n,.85);return l.warnings=o,l}catch(t){return e.error("func-to-arrow transform failed",t),w(s,"func-to-arrow",t instanceof Error?t.message:"Unknown error",n)}}var V={"var-to-const":Z,"add-types":O,"remove-console":I,"promise-to-async":j,"cjs-to-esm":N,"func-to-arrow":H};function $(s,e,n){let r=V[e];return r?r(s,n):{success:!1,transformType:e,originalCode:s,transformedCode:s,edits:[],changeCount:0,confidence:0,durationMs:0,implementationUsed:"typescript",usedFallback:!1,error:`Unknown transform type: ${e}`,warnings:[]}}var q={JavaScript:0,TypeScript:1,Python:2,Rust:3,Go:4,Java:5,C:6,Cpp:7},y=null,A=null,x=null,k=!1,R=null;async function G(){if(k)return R===null;if(R)return!1;try{let s=await import("./agent-booster-wasm-CCTTGCQS.js");return y=s.transform,A=s.warmup,x=s.isWasmAvailable,k=!0,!0}catch(s){return R=s,k=!0,!1}}function K(s){return q.TypeScript}var L=class{cache=new Map;ttlMs;enabled;constructor(e,n){this.enabled=e,this.ttlMs=n}generateKey(e,n){let r=0;for(let o=0;o<e.length;o++){let t=e.charCodeAt(o);r=(r<<5)-r+t,r=r&r}return`${n}:${r}:${e.length}`}get(e,n){if(!this.enabled)return null;let r=this.generateKey(e,n),o=this.cache.get(r);return o?Date.now()>o.expiresAt?(this.cache.delete(r),null):o.result:null}set(e,n,r){if(!this.enabled)return;let o=this.generateKey(e,n);this.cache.set(o,{result:r,expiresAt:Date.now()+this.ttlMs})}clear(){this.cache.clear()}getStats(){return{size:this.cache.size,hitRate:0}}},v=class{config;logger;cache;enabledTransforms;metricsTracker;initialized=!1;wasmAvailable=!1;wasmModule=null;patternsLoaded=!1;totalTransforms=0;successfulTransforms=0;totalDurationMs=0;cacheHits=0;cacheMisses=0;constructor(e={},n,r){this.config={...z,...e},this.logger=n||{debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},this.metricsTracker=r,this.cache=new L(this.config.cacheEnabled,this.config.cacheTtlMs),this.config.transforms.length===0?this.enabledTransforms=new Set(b):this.enabledTransforms=new Set(this.config.transforms)}setMetricsTracker(e){this.metricsTracker=e}async initialize(){this.initialized||(this.logger.info("Initializing Agent Booster adapter",{enabled:this.config.enabled,transforms:Array.from(this.enabledTransforms)}),this.config.transforms.length===0&&await this.loadEligibleTransformsFromPatterns(),this.config.enabled&&await this.tryLoadWasm(),this.initialized=!0,this.logger.info("Agent Booster adapter initialized",{wasmAvailable:this.wasmAvailable,enabledTransforms:Array.from(this.enabledTransforms),patternsLoaded:this.patternsLoaded}))}async loadEligibleTransformsFromPatterns(){try{let n=await F().getEligibleBoosterTransforms();if(n.length>0){let r=n.filter(o=>b.includes(o));if(r.length>0){this.enabledTransforms=new Set(r),this.patternsLoaded=!0,this.logger.info("Loaded eligible transforms from PatternLoader",{fromPatterns:r,invalidIgnored:n.length-r.length});return}}this.logger.debug("PatternLoader returned empty transforms, using defaults")}catch(e){this.logger.warn("Failed to load transforms from PatternLoader, using defaults",{error:e instanceof Error?e.message:"Unknown error"})}this.enabledTransforms=new Set(b),this.patternsLoaded=!1}async tryLoadWasm(){try{if(this.logger.debug("Loading WASM module"),!await G()||!x){this.logger.debug("WASM module could not be loaded, using TypeScript fallback"),this.wasmAvailable=!1;return}this.logger.debug("Checking WASM availability from local module"),await x()&&y&&A?(this.logger.debug("Warming up WASM module"),await A(),this.wasmModule={transform:y,warmup:A,isAvailable:x},this.wasmAvailable=!0,this.logger.info("WASM Agent Booster loaded and warmed up successfully",{source:"local-module"})):(this.logger.debug("WASM not available from local module, using TypeScript fallback"),this.wasmAvailable=!1)}catch(e){this.logger.warn("Failed to load WASM module",{error:e instanceof Error?e.message:"Unknown error"}),this.wasmAvailable=!1}}async dispose(){this.cache.clear(),this.wasmModule=null,this.wasmAvailable=!1,this.initialized=!1,this.logger.info("Agent Booster adapter disposed")}async transform(e,n){this.ensureInitialized(),this.ensureEnabled();let r=Date.now();if(this.totalTransforms++,!this.enabledTransforms.has(n))return this.createErrorResult(e,n,`Transform type '${n}' is not enabled`,r);let o=this.cache.get(e,n);if(o)return this.cacheHits++,this.logger.debug("Cache hit for transform",{type:n}),{...o,durationMs:Date.now()-r};this.cacheMisses++;let t;try{t=await this.executeWithFallback(e,n,r)}catch(a){return this.createErrorResult(e,n,a instanceof Error?a.message:"Unknown error",r)}return t.success&&(this.successfulTransforms++,this.cache.set(e,n,t)),this.totalDurationMs+=t.durationMs,await this.recordMetrics(t,n),t}async recordMetrics(e,n){if(this.metricsTracker)try{let r=`booster-${n}-${Date.now()}`;await this.metricsTracker.recordOutcome("booster",r,e.success,e.durationMs,{subType:n,confidence:e.confidence,usedFallback:e.usedFallback,implementationUsed:e.implementationUsed,itemCount:e.changeCount,errorMessage:e.error})}catch(r){this.logger.warn("Failed to record metrics",{error:r instanceof Error?r.message:"Unknown error"})}}async executeWithFallback(e,n,r){if(this.wasmAvailable)try{let t=await this.executeWasmTransform(e,n,r);if(t.success&&t.confidence>=this.config.confidenceThreshold)return t;this.logger.debug("WASM transform low confidence, trying TypeScript",{confidence:t.confidence,threshold:this.config.confidenceThreshold})}catch(t){this.logger.warn("WASM transform failed, falling back to TypeScript",{error:t instanceof Error?t.message:"Unknown error"})}let o=$(e,n,this.logger);return o.durationMs=Date.now()-r,this.config.fallbackToLLM&&o.confidence<this.config.confidenceThreshold&&(this.logger.debug("TypeScript transform low confidence, LLM fallback available",{confidence:o.confidence,threshold:this.config.confidenceThreshold}),o.warnings.push(`Confidence ${o.confidence.toFixed(2)} is below threshold ${this.config.confidenceThreshold}. LLM fallback recommended for review.`),o.usedFallback=!0),o}async executeWasmTransform(e,n,r){if(!this.wasmAvailable)throw new C;let o=K(n),t=$(e,n,this.logger);if(t.changeCount===0)return{...t,durationMs:Date.now()-r,implementationUsed:"wasm"};if(!y)throw new C("WASM transform function not loaded");let a=await Promise.race([y(e,t.transformedCode,o,{confidenceThreshold:this.config.confidenceThreshold,allowFallback:!0}),new Promise((m,u)=>setTimeout(()=>u(new P("WASM transform timed out",n,this.config.timeoutMs)),this.config.timeoutMs))]),i=Date.now()-r,l=a.success&&a.mergedCode!==e?t.changeCount:0;return{success:a.success,transformType:n,originalCode:e,transformedCode:a.mergedCode,edits:t.edits,changeCount:l,confidence:a.confidence,durationMs:i,implementationUsed:a.source==="wasm"?"wasm":"typescript",usedFallback:a.source!=="wasm",error:a.error,warnings:a.syntaxValid?[]:["WASM reported syntax may be invalid"]}}async batchTransform(e,n){this.ensureInitialized(),this.ensureEnabled();let r=Date.now(),o=[],t=[],a=0,i=0,l=0,m=0;for(let u of e){if(u.content.length>this.config.maxFileSizeBytes){let c=new B(u.path,u.content.length,this.config.maxFileSizeBytes);t.push({path:u.path,error:c.message}),i++;continue}try{let c=await this.transform(u.content,n);o.push({path:u.path,result:c}),c.success?c.changeCount>0?(a++,m+=c.changeCount):l++:(i++,c.error&&t.push({path:u.path,error:c.error}))}catch(c){i++,t.push({path:u.path,error:c instanceof Error?c.message:"Unknown error"})}}return{success:i===0,transformType:n,files:o,totalFiles:e.length,successCount:a,failureCount:i,noChangeCount:l,totalChanges:m,durationMs:Date.now()-r,errors:t}}async detectTransformOpportunities(e){this.ensureInitialized(),this.ensureEnabled();let n=Date.now(),r=[],o={},t=[];for(let a of b)o[a]=0;for(let a of Array.from(this.enabledTransforms))try{let i=await this.transform(e,a);if(i.changeCount>0)for(let l of i.edits){let m={type:a,confidence:i.confidence,location:l.start,codeSnippet:l.oldText.slice(0,100)+(l.oldText.length>100?"...":""),suggestedCode:l.newText.slice(0,100)+(l.newText.length>100?"...":""),reason:l.description,risk:this.confidenceToRisk(i.confidence),estimatedDurationMs:E[a].typicalLatencyMs};r.push(m),o[a]++}}catch(i){t.push(`Failed to analyze for ${a}: ${i instanceof Error?i.message:"Unknown error"}`)}return r.sort((a,i)=>i.confidence-a.confidence),{opportunities:r,totalCount:r.length,byType:o,durationMs:Date.now()-n,complete:t.length===0,warnings:t}}isTransformAvailable(e){return this.enabledTransforms.has(e)}getTransformMetadata(e){return E[e]}getAvailableTransforms(){return Array.from(this.enabledTransforms)}isWasmAvailable(){return this.wasmAvailable}getHealth(){let e=this.totalTransforms>0?this.totalDurationMs/this.totalTransforms:0,n=this.cacheHits+this.cacheMisses>0?this.cacheHits/(this.cacheHits+this.cacheMisses):0,r=[];return this.initialized||r.push("Adapter not initialized"),this.config.enabled||r.push("Adapter is disabled"),this.wasmAvailable||r.push("WASM module not loaded (using TypeScript fallback)"),this.patternsLoaded||r.push("Patterns not loaded from PatternLoader (using defaults)"),{ready:this.initialized&&this.config.enabled,wasmAvailable:this.wasmAvailable,patternsLoaded:this.patternsLoaded,availableTransforms:Array.from(this.enabledTransforms),lastChecked:new Date,issues:r,metrics:{totalTransforms:this.totalTransforms,successfulTransforms:this.successfulTransforms,averageDurationMs:e,cacheHitRate:n}}}ensureInitialized(){if(!this.initialized)throw new M("AgentBoosterAdapter not initialized. Call initialize() first.","var-to-const")}ensureEnabled(){if(!this.config.enabled)throw new M("AgentBoosterAdapter is disabled. Set enabled: true in config.","var-to-const")}createErrorResult(e,n,r,o){return{success:!1,transformType:n,originalCode:e,transformedCode:e,edits:[],changeCount:0,confidence:0,durationMs:Date.now()-o,implementationUsed:"typescript",usedFallback:!1,error:r,warnings:[]}}confidenceToRisk(e){return e>=.95?"info":e>=.85?"low":e>=.7?"medium":e>=.5?"high":"critical"}};async function ee(s={},e,n){let r=new v(s,e,n);return await r.initialize(),r}function re(s={},e,n){return new v(s,e,n)}export{v as a,ee as b,re as c};
|
|
6
|
+
${c.trim()}`;r.push(p(s,a.index,a.index+l.length,f,"Convert .then() to await"))}e.debug("promise-to-async transform completed",{converted:r.length,warnings:o.length});let i=T(s,"promise-to-async",r,n,.65);return i.warnings=o,r.length>0&&i.warnings.push("Promise chains converted to await - ensure containing function is async"),i}catch(t){return e.error("promise-to-async transform failed",t),w(s,"promise-to-async",t instanceof Error?t.message:"Unknown error",n)}}function N(s,e={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}}){let n=Date.now(),r=[],o=[];try{let t,a=/(?:const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*require\s*\(\s*(['"`][^'"`]+['"`])\s*\)\s*;?/g;for(;(t=a.exec(s))!==null;){let[c,f,g]=t,d=`import ${f} from ${g};`;r.push(p(s,t.index,t.index+c.length,d,"Convert require to import"))}let i=/(?:const|let|var)\s+\{\s*([^}]+)\s*\}\s*=\s*require\s*\(\s*(['"`][^'"`]+['"`])\s*\)\s*;?/g;for(;(t=i.exec(s))!==null;){let[c,f,g]=t,d=`import { ${f.trim()} } from ${g};`;r.push(p(s,t.index,t.index+c.length,d,"Convert destructured require to import"))}let l=/module\.exports\s*=\s*([^;]+);?/g;for(;(t=l.exec(s))!==null;){let[c,f]=t,g=`export default ${f.trim()};`;r.push(p(s,t.index,t.index+c.length,g,"Convert module.exports to export default"))}let m=/exports\.([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*([^;]+);?/g;for(;(t=m.exec(s))!==null;){let[c,f,g]=t,d=g.trim(),h;d.startsWith("function")||d.startsWith("class")?h=`export ${d}`:d.startsWith("async function")?h=`export ${d}`:h=`export const ${f} = ${d};`,r.push(p(s,t.index,t.index+c.length,h,`Convert exports.${f} to named export`))}e.debug("cjs-to-esm transform completed",{edits:r.length});let u=T(s,"cjs-to-esm",r,n,.85);return u.warnings=o,u}catch(t){return e.error("cjs-to-esm transform failed",t),w(s,"cjs-to-esm",t instanceof Error?t.message:"Unknown error",n)}}function H(s,e={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}}){let n=Date.now(),r=[],o=[];try{let t=/(const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*function\s*\(([^)]*)\)\s*\{/g,a;for(;(a=t.exec(s))!==null;){let[m,u,c,f]=a,g=a.index,d=1,h=g+m.length;for(;d>0&&h<s.length;)s[h]==="{"&&d++,s[h]==="}"&&d--,h++;let S=s.slice(g,h);if(/\bthis\b/.test(S)){o.push(`Function ${c} uses 'this' - skipping arrow conversion (would change binding)`);continue}if(/\barguments\b/.test(S)){o.push(`Function ${c} uses 'arguments' - skipping arrow conversion (not available in arrow functions)`);continue}let D=`${u} ${c} = (${f}) => {`;r.push(p(s,a.index,a.index+m.length,D,`Convert function ${c} to arrow function`))}let i=/function\s*\(([^)]*)\)\s*\{\s*return\s+([^;]+);\s*\}/g;for(;(a=i.exec(s))!==null;){let[m,u,c]=a;if(/\b(this|arguments)\b/.test(m))continue;let f=u.includes(",")||u.trim()===""?`(${u}) => ${c}`:`${u.trim()} => ${c}`;r.push(p(s,a.index,a.index+m.length,f,"Convert callback to arrow function"))}e.debug("func-to-arrow transform completed",{converted:r.length,warnings:o.length});let l=T(s,"func-to-arrow",r,n,.85);return l.warnings=o,l}catch(t){return e.error("func-to-arrow transform failed",t),w(s,"func-to-arrow",t instanceof Error?t.message:"Unknown error",n)}}var V={"var-to-const":Z,"add-types":O,"remove-console":I,"promise-to-async":j,"cjs-to-esm":N,"func-to-arrow":H};function $(s,e,n){let r=V[e];return r?r(s,n):{success:!1,transformType:e,originalCode:s,transformedCode:s,edits:[],changeCount:0,confidence:0,durationMs:0,implementationUsed:"typescript",usedFallback:!1,error:`Unknown transform type: ${e}`,warnings:[]}}var q={JavaScript:0,TypeScript:1,Python:2,Rust:3,Go:4,Java:5,C:6,Cpp:7},y=null,A=null,x=null,k=!1,R=null;async function G(){if(k)return R===null;if(R)return!1;try{let s=await import("./agent-booster-wasm-SY7UCLBL.js");return y=s.transform,A=s.warmup,x=s.isWasmAvailable,k=!0,!0}catch(s){return R=s,k=!0,!1}}function K(s){return q.TypeScript}var L=class{cache=new Map;ttlMs;enabled;constructor(e,n){this.enabled=e,this.ttlMs=n}generateKey(e,n){let r=0;for(let o=0;o<e.length;o++){let t=e.charCodeAt(o);r=(r<<5)-r+t,r=r&r}return`${n}:${r}:${e.length}`}get(e,n){if(!this.enabled)return null;let r=this.generateKey(e,n),o=this.cache.get(r);return o?Date.now()>o.expiresAt?(this.cache.delete(r),null):o.result:null}set(e,n,r){if(!this.enabled)return;let o=this.generateKey(e,n);this.cache.set(o,{result:r,expiresAt:Date.now()+this.ttlMs})}clear(){this.cache.clear()}getStats(){return{size:this.cache.size,hitRate:0}}},v=class{config;logger;cache;enabledTransforms;metricsTracker;initialized=!1;wasmAvailable=!1;wasmModule=null;patternsLoaded=!1;totalTransforms=0;successfulTransforms=0;totalDurationMs=0;cacheHits=0;cacheMisses=0;constructor(e={},n,r){this.config={...z,...e},this.logger=n||{debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},this.metricsTracker=r,this.cache=new L(this.config.cacheEnabled,this.config.cacheTtlMs),this.config.transforms.length===0?this.enabledTransforms=new Set(b):this.enabledTransforms=new Set(this.config.transforms)}setMetricsTracker(e){this.metricsTracker=e}async initialize(){this.initialized||(this.logger.info("Initializing Agent Booster adapter",{enabled:this.config.enabled,transforms:Array.from(this.enabledTransforms)}),this.config.transforms.length===0&&await this.loadEligibleTransformsFromPatterns(),this.config.enabled&&await this.tryLoadWasm(),this.initialized=!0,this.logger.info("Agent Booster adapter initialized",{wasmAvailable:this.wasmAvailable,enabledTransforms:Array.from(this.enabledTransforms),patternsLoaded:this.patternsLoaded}))}async loadEligibleTransformsFromPatterns(){try{let n=await F().getEligibleBoosterTransforms();if(n.length>0){let r=n.filter(o=>b.includes(o));if(r.length>0){this.enabledTransforms=new Set(r),this.patternsLoaded=!0,this.logger.info("Loaded eligible transforms from PatternLoader",{fromPatterns:r,invalidIgnored:n.length-r.length});return}}this.logger.debug("PatternLoader returned empty transforms, using defaults")}catch(e){this.logger.warn("Failed to load transforms from PatternLoader, using defaults",{error:e instanceof Error?e.message:"Unknown error"})}this.enabledTransforms=new Set(b),this.patternsLoaded=!1}async tryLoadWasm(){try{if(this.logger.debug("Loading WASM module"),!await G()||!x){this.logger.debug("WASM module could not be loaded, using TypeScript fallback"),this.wasmAvailable=!1;return}this.logger.debug("Checking WASM availability from local module"),await x()&&y&&A?(this.logger.debug("Warming up WASM module"),await A(),this.wasmModule={transform:y,warmup:A,isAvailable:x},this.wasmAvailable=!0,this.logger.info("WASM Agent Booster loaded and warmed up successfully",{source:"local-module"})):(this.logger.debug("WASM not available from local module, using TypeScript fallback"),this.wasmAvailable=!1)}catch(e){this.logger.warn("Failed to load WASM module",{error:e instanceof Error?e.message:"Unknown error"}),this.wasmAvailable=!1}}async dispose(){this.cache.clear(),this.wasmModule=null,this.wasmAvailable=!1,this.initialized=!1,this.logger.info("Agent Booster adapter disposed")}async transform(e,n){this.ensureInitialized(),this.ensureEnabled();let r=Date.now();if(this.totalTransforms++,!this.enabledTransforms.has(n))return this.createErrorResult(e,n,`Transform type '${n}' is not enabled`,r);let o=this.cache.get(e,n);if(o)return this.cacheHits++,this.logger.debug("Cache hit for transform",{type:n}),{...o,durationMs:Date.now()-r};this.cacheMisses++;let t;try{t=await this.executeWithFallback(e,n,r)}catch(a){return this.createErrorResult(e,n,a instanceof Error?a.message:"Unknown error",r)}return t.success&&(this.successfulTransforms++,this.cache.set(e,n,t)),this.totalDurationMs+=t.durationMs,await this.recordMetrics(t,n),t}async recordMetrics(e,n){if(this.metricsTracker)try{let r=`booster-${n}-${Date.now()}`;await this.metricsTracker.recordOutcome("booster",r,e.success,e.durationMs,{subType:n,confidence:e.confidence,usedFallback:e.usedFallback,implementationUsed:e.implementationUsed,itemCount:e.changeCount,errorMessage:e.error})}catch(r){this.logger.warn("Failed to record metrics",{error:r instanceof Error?r.message:"Unknown error"})}}async executeWithFallback(e,n,r){if(this.wasmAvailable)try{let t=await this.executeWasmTransform(e,n,r);if(t.success&&t.confidence>=this.config.confidenceThreshold)return t;this.logger.debug("WASM transform low confidence, trying TypeScript",{confidence:t.confidence,threshold:this.config.confidenceThreshold})}catch(t){this.logger.warn("WASM transform failed, falling back to TypeScript",{error:t instanceof Error?t.message:"Unknown error"})}let o=$(e,n,this.logger);return o.durationMs=Date.now()-r,this.config.fallbackToLLM&&o.confidence<this.config.confidenceThreshold&&(this.logger.debug("TypeScript transform low confidence, LLM fallback available",{confidence:o.confidence,threshold:this.config.confidenceThreshold}),o.warnings.push(`Confidence ${o.confidence.toFixed(2)} is below threshold ${this.config.confidenceThreshold}. LLM fallback recommended for review.`),o.usedFallback=!0),o}async executeWasmTransform(e,n,r){if(!this.wasmAvailable)throw new C;let o=K(n),t=$(e,n,this.logger);if(t.changeCount===0)return{...t,durationMs:Date.now()-r,implementationUsed:"wasm"};if(!y)throw new C("WASM transform function not loaded");let a=await Promise.race([y(e,t.transformedCode,o,{confidenceThreshold:this.config.confidenceThreshold,allowFallback:!0}),new Promise((m,u)=>setTimeout(()=>u(new P("WASM transform timed out",n,this.config.timeoutMs)),this.config.timeoutMs))]),i=Date.now()-r,l=a.success&&a.mergedCode!==e?t.changeCount:0;return{success:a.success,transformType:n,originalCode:e,transformedCode:a.mergedCode,edits:t.edits,changeCount:l,confidence:a.confidence,durationMs:i,implementationUsed:a.source==="wasm"?"wasm":"typescript",usedFallback:a.source!=="wasm",error:a.error,warnings:a.syntaxValid?[]:["WASM reported syntax may be invalid"]}}async batchTransform(e,n){this.ensureInitialized(),this.ensureEnabled();let r=Date.now(),o=[],t=[],a=0,i=0,l=0,m=0;for(let u of e){if(u.content.length>this.config.maxFileSizeBytes){let c=new B(u.path,u.content.length,this.config.maxFileSizeBytes);t.push({path:u.path,error:c.message}),i++;continue}try{let c=await this.transform(u.content,n);o.push({path:u.path,result:c}),c.success?c.changeCount>0?(a++,m+=c.changeCount):l++:(i++,c.error&&t.push({path:u.path,error:c.error}))}catch(c){i++,t.push({path:u.path,error:c instanceof Error?c.message:"Unknown error"})}}return{success:i===0,transformType:n,files:o,totalFiles:e.length,successCount:a,failureCount:i,noChangeCount:l,totalChanges:m,durationMs:Date.now()-r,errors:t}}async detectTransformOpportunities(e){this.ensureInitialized(),this.ensureEnabled();let n=Date.now(),r=[],o={},t=[];for(let a of b)o[a]=0;for(let a of Array.from(this.enabledTransforms))try{let i=await this.transform(e,a);if(i.changeCount>0)for(let l of i.edits){let m={type:a,confidence:i.confidence,location:l.start,codeSnippet:l.oldText.slice(0,100)+(l.oldText.length>100?"...":""),suggestedCode:l.newText.slice(0,100)+(l.newText.length>100?"...":""),reason:l.description,risk:this.confidenceToRisk(i.confidence),estimatedDurationMs:E[a].typicalLatencyMs};r.push(m),o[a]++}}catch(i){t.push(`Failed to analyze for ${a}: ${i instanceof Error?i.message:"Unknown error"}`)}return r.sort((a,i)=>i.confidence-a.confidence),{opportunities:r,totalCount:r.length,byType:o,durationMs:Date.now()-n,complete:t.length===0,warnings:t}}isTransformAvailable(e){return this.enabledTransforms.has(e)}getTransformMetadata(e){return E[e]}getAvailableTransforms(){return Array.from(this.enabledTransforms)}isWasmAvailable(){return this.wasmAvailable}getHealth(){let e=this.totalTransforms>0?this.totalDurationMs/this.totalTransforms:0,n=this.cacheHits+this.cacheMisses>0?this.cacheHits/(this.cacheHits+this.cacheMisses):0,r=[];return this.initialized||r.push("Adapter not initialized"),this.config.enabled||r.push("Adapter is disabled"),this.wasmAvailable||r.push("WASM module not loaded (using TypeScript fallback)"),this.patternsLoaded||r.push("Patterns not loaded from PatternLoader (using defaults)"),{ready:this.initialized&&this.config.enabled,wasmAvailable:this.wasmAvailable,patternsLoaded:this.patternsLoaded,availableTransforms:Array.from(this.enabledTransforms),lastChecked:new Date,issues:r,metrics:{totalTransforms:this.totalTransforms,successfulTransforms:this.successfulTransforms,averageDurationMs:e,cacheHitRate:n}}}ensureInitialized(){if(!this.initialized)throw new M("AgentBoosterAdapter not initialized. Call initialize() first.","var-to-const")}ensureEnabled(){if(!this.config.enabled)throw new M("AgentBoosterAdapter is disabled. Set enabled: true in config.","var-to-const")}createErrorResult(e,n,r,o){return{success:!1,transformType:n,originalCode:e,transformedCode:e,edits:[],changeCount:0,confidence:0,durationMs:Date.now()-o,implementationUsed:"typescript",usedFallback:!1,error:r,warnings:[]}}confidenceToRisk(e){return e>=.95?"info":e>=.85?"low":e>=.7?"medium":e>=.5?"high":"critical"}};async function ee(s={},e,n){let r=new v(s,e,n);return await r.initialize(),r}function re(s={},e,n){return new v(s,e,n)}export{v as a,ee as b,re as c};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
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.6");process.exit(0)}
|
|
2
2
|
var i=class r{constructor(e){this._value=e;if(!e||e.trim()==="")throw new Error("FilePath cannot be empty")}_value;get value(){return this._value}get extension(){let e=this._value.split(".");return e.length>1?e[e.length-1]:""}get directory(){let e=this._value.lastIndexOf("/");return e>0?this._value.substring(0,e):""}get filename(){let e=this._value.lastIndexOf("/");return e>=0?this._value.substring(e+1):this._value}equals(e){return this._value===e._value}static create(e){return new r(e)}};var s=class r{constructor(e){this._value=e;if(e<0||e>1)throw new Error("RiskScore must be between 0 and 1")}_value;get value(){return this._value}get percentage(){return this._value*100}get level(){return this._value>=.8?"critical":this._value>=.6?"high":this._value>=.3?"medium":"low"}isHigherThan(e){return this._value>e._value}equals(e){return this._value===e._value}static create(e){return new r(e)}static fromPercentage(e){return new r(e/100)}},u=class r{constructor(e,t){this._start=e;this._end=t;if(e>t)throw new Error("Start date cannot be after end date")}_start;_end;get start(){return this._start}get end(){return this._end}get durationMs(){return this._end.getTime()-this._start.getTime()}get durationSeconds(){return this.durationMs/1e3}contains(e){return e>=this._start&&e<=this._end}overlaps(e){return this._start<=e._end&&e._start<=this._end}equals(e){return this._start.getTime()===e._start.getTime()&&this._end.getTime()===e._end.getTime()}static create(e,t){return new r(e,t)}static lastNDays(e){let t=new Date,n=new Date(t.getTime()-e*24*60*60*1e3);return new r(n,t)}},o=class r{constructor(e,t,n,a){this._major=e;this._minor=t;this._patch=n;this._prerelease=a}_major;_minor;_patch;_prerelease;get major(){return this._major}get minor(){return this._minor}get patch(){return this._patch}get prerelease(){return this._prerelease}toString(){let e=`${this._major}.${this._minor}.${this._patch}`;return this._prerelease?`${e}-${this._prerelease}`:e}isNewerThan(e){return this._major!==e._major?this._major>e._major:this._minor!==e._minor?this._minor>e._minor:this._patch>e._patch}equals(e){return this._major===e._major&&this._minor===e._minor&&this._patch===e._patch&&this._prerelease===e._prerelease}static create(e,t,n,a){return new r(e,t,n,a)}static parse(e){let t=e.match(/^(\d+)\.(\d+)\.(\d+)(?:-(.+))?$/);if(!t)throw new Error(`Invalid version format: ${e}`);return new r(parseInt(t[1]),parseInt(t[2]),parseInt(t[3]),t[4])}};export{i as a,s as b,u as c,o as d};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{b as e}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.6");process.exit(0)}
|
|
2
|
+
import{b as e}from"./chunk-7SAMMQVS.js";function r(t){t.exec(n)}var n,a=e(()=>{"use strict";n=`
|
|
3
3
|
-- Negative pattern records (ADR-110 kept nulls)
|
|
4
4
|
CREATE TABLE IF NOT EXISTS qe_pattern_nulls (
|
|
5
5
|
id TEXT PRIMARY KEY,
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
var e=null,f=null,t=null,u=!1;async function W(){return u&&!t?e:t||(t=(async()=>{try{if(process.env.AQE_RVF_MODE==="sqlite-only"||process.env.AQE_MEMORY_BACKEND==="memory")return null;let{isRvfNativeAvailable:d}=await import("./rvf-native-adapter-
|
|
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.6");process.exit(0)}
|
|
2
|
+
var e=null,f=null,t=null,u=!1;async function W(){return u&&!t?e:t||(t=(async()=>{try{if(process.env.AQE_RVF_MODE==="sqlite-only"||process.env.AQE_MEMORY_BACKEND==="memory")return null;let{isRvfNativeAvailable:d}=await import("./rvf-native-adapter-I6RUGD2D.js");if(!d())return null;let{getUnifiedMemory:v,findProjectRoot:p}=await import("./unified-memory-FCX7NLFZ.js"),o=v().getDatabase();if(!o)return null;let{join:m}=await import("node:path"),g=m(process.env.AQE_PROJECT_ROOT??p(),".agentic-qe","brain.rvf"),{RvfDualWriter:R}=await import("./rvf-dual-writer-DEKDQ6KO.js"),l=new R(o,{rvfPath:g,mode:"dual-write",dimensions:384});await l.initialize(),e=l;try{let{getRvfMigrationStage:y}=await import("./feature-flags-SRLXDKBI.js"),a=y();if(a>=2){let{RvfMigrationAdapter:A}=await import("./rvf-migration-adapter-L53VBS7I.js"),s=new A({stage:a});s.setSqliteDb(o);let{getSharedRvfAdapter:D}=await import("./shared-rvf-adapter-LNRLFP5I.js"),i=D();if(i){let h={ingest:n=>i.ingest(n),search:(n,M)=>i.search(n,M).map(c=>({id:c.id,score:c.score})),delete:n=>i.delete(n),status:()=>i.status(),close:()=>{}};s.setRvfStore(h)}f=s,console.log(`[RVF] Migration adapter active at stage ${a} (${["sqlite-only","hybrid","dual-sqlite","dual-rvf","rvf-primary"][a]})`)}}catch{}return l}catch(r){return(process.env.DEBUG||process.env.AQE_VERBOSE)&&console.debug("[RVF] Dual-writer init failed, degrading to sqlite-only:",r instanceof Error?r.message:r),null}finally{u=!0,t=null,import("./base-QSYWWPCE.js").then(({registerRvfResetFn:r})=>r(w)).catch(()=>{})}})(),t)}function S(){return e}function b(){return f}function w(){if(e){try{e.close()}catch{}e=null}f=null,t=null,u=!1}export{W as a,S as b,b as c,w as d};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{p as g}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.6");process.exit(0)}
|
|
2
|
+
import{p as g}from"./chunk-XFPQIWEH.js";var m={0:"sqlite-only",1:"hybrid",2:"dual-write-sqlite-primary",3:"dual-write-rvf-primary",4:"rvf-primary"},b=class{config;db=null;rvfStore=null;totalWrites=0;totalReads=0;rvfWriteFailures=0;rvfReadFailures=0;fallbacksUsed=0;sqliteLatencies=[];rvfLatencies=[];sqliteWriteLatencies=[];rvfWriteLatencies=[];constructor(e){this.config={rvfPath:".agentic-qe/patterns.rvf",dimensions:384,enableFallback:!0,...e}}setSqliteDb(e){this.db=e}setRvfStore(e){this.rvfStore=e}get stage(){return this.config.stage}setStage(e){this.config={...this.config,stage:e}}write(e,t){this.totalWrites++;let r={sqliteSuccess:!1,rvfSuccess:!1,stage:this.config.stage,fallbackUsed:!1},n=this.db?this.db.prepare("PRAGMA table_info('qe_pattern_embeddings')").all().some(s=>s.name==="space_id"):!1,c=g()?.spaceId??this.config.embeddingSpaceId;if(!n||!c)return r;let o=this.config.stage<4,i=this.config.stage>=2;if(o&&this.db){let s=performance.now();try{let a=Buffer.from(t instanceof Float32Array?t.buffer:new Float32Array(t).buffer);n?this.db.prepare(`
|
|
3
3
|
INSERT INTO qe_pattern_embeddings (pattern_id, embedding, dimension, model, space_id, created_at)
|
|
4
4
|
VALUES (?, ?, ?, 'all-MiniLM-L6-v2', ?, datetime('now'))
|
|
5
5
|
ON CONFLICT(pattern_id) DO UPDATE SET
|
|
@@ -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.6");process.exit(0)}
|
|
2
2
|
var l=["var-to-const","add-types","remove-console","promise-to-async","cjs-to-esm","func-to-arrow"],p={"var-to-const":{type:"var-to-const",name:"Var to Const/Let",description:"Convert var declarations to const (if not reassigned) or let (if reassigned)",complexity:"simple",wasmAvailable:!0,typicalLatencyMs:1},"add-types":{type:"add-types",name:"Add TypeScript Types",description:"Add TypeScript type annotations to function parameters and return types",complexity:"moderate",wasmAvailable:!0,typicalLatencyMs:5},"remove-console":{type:"remove-console",name:"Remove Console Statements",description:"Remove all console.log, console.warn, console.error, etc. statements",complexity:"simple",wasmAvailable:!0,typicalLatencyMs:1},"promise-to-async":{type:"promise-to-async",name:"Promise to Async/Await",description:"Convert Promise .then()/.catch() chains to async/await syntax",complexity:"complex",wasmAvailable:!0,typicalLatencyMs:10},"cjs-to-esm":{type:"cjs-to-esm",name:"CommonJS to ES Modules",description:"Convert require() calls to import statements and module.exports to export",complexity:"moderate",wasmAvailable:!0,typicalLatencyMs:5},"func-to-arrow":{type:"func-to-arrow",name:"Function to Arrow",description:"Convert function declarations and expressions to arrow functions",complexity:"moderate",wasmAvailable:!0,typicalLatencyMs:3}},u={enabled:!0,fallbackToLLM:!0,confidenceThreshold:.7,transforms:[],maxFileSizeBytes:1024*1024,timeoutMs:5e3,cacheEnabled:!0,cacheTtlMs:300*1e3},t=class extends Error{constructor(e,s,o){super(e);this.code=s;this.cause=o;this.name="AgentBoosterError"}code;cause},a=class extends t{constructor(e,s,o){super(e,"TRANSFORM_ERROR",o);this.transformType=s;this.name="TransformError"}transformType},i=class extends t{constructor(r="WASM module is not available",e){super(r,"WASM_UNAVAILABLE",e),this.name="WasmUnavailableError"}},c=class extends t{constructor(e,s,o){super(e,"TRANSFORM_TIMEOUT");this.transformType=s;this.timeoutMs=o;this.name="TransformTimeoutError"}transformType;timeoutMs},m=class extends t{constructor(e,s,o){super(`File ${e} is too large (${s} bytes, max ${o} bytes)`,"FILE_TOO_LARGE");this.filePath=e;this.sizeBytes=s;this.maxSizeBytes=o;this.name="FileTooLargeError"}filePath;sizeBytes;maxSizeBytes};export{l as a,p as b,u as c,a as d,i as e,c as f,m as g};
|
|
@@ -1,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{a as q}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.6");process.exit(0)}
|
|
2
|
+
import{a as q}from"./chunk-EJ4KZFZN.js";import{g as O,h as X,i as L,j as k,o as I,s as B}from"./chunk-YNG7E26C.js";import{b as h,d as x}from"./chunk-22OZIJAD.js";import{a as y,b as A,h as f,l as C,n as D,p as g}from"./chunk-XFPQIWEH.js";import{i as w}from"./chunk-IVJIHZSM.js";import{a as _,e as U}from"./chunk-KYVIOC3C.js";import{a as N,b as v}from"./chunk-AJT3XDRD.js";v();x();U();B();X();k();var H={dbPath:".agentic-qe/memory.db",walMode:!0,mmapSize:256*1024*1024,cacheSize:-64e3,foreignKeys:!0,useUnified:!0};function ee(l,e=384){let t=new Array(e).fill(0),n=l.toLowerCase().trim();for(let a=0;a<3;a++)for(let s=0;s<n.length;s++){let i=n.charCodeAt(s),o=i*(s+1)*(a+1)%e;t[o]+=Math.sin(i*(a+1))/(s+1)}let r=Math.sqrt(t.reduce((a,s)=>a+s*s,0));if(r>0)for(let a=0;a<e;a++)t[a]/=r;return t}function P(l){return l.normalize("NFKD").replace(/\p{M}+/gu,"").toLowerCase().match(/[\p{L}\p{N}]+/gu)??[]}var S=class{db=null;config;prepared=new Map;initialized=!1;unifiedMemory=null;constructor(e={}){this.config={...H,...e}}getDatabase(){return this.db}async initialize(){if(!this.initialized)try{if(this.config.useUnified)this.unifiedMemory=I(),await this.unifiedMemory.initialize(),this.db=this.unifiedMemory.getDatabase(),console.log(`[SQLitePatternStore] Using unified storage: ${this.unifiedMemory.getDbPath()}`);else{let e=await import("path"),t=await import("fs"),n=e.dirname(this.config.dbPath);t.existsSync(n)||t.mkdirSync(n,{recursive:!0}),this.db=N(this.config.dbPath),this.db.pragma(`mmap_size = ${this.config.mmapSize}`),this.db.pragma(`cache_size = ${this.config.cacheSize}`),this.config.foreignKeys&&this.db.pragma("foreign_keys = ON"),L(this.db,{logPrefix:"[SQLitePatternStore]"}),this.createSchema(),console.log(`[SQLitePatternStore] Initialized (legacy): ${this.config.dbPath}`)}this.deduplicatePatterns(),this.ensureEmbeddingSpaceSchema(),this.prepareStatements(),this.initialized=!0}catch(e){throw new Error(`Failed to initialize SQLite: ${_(e)}`)}}createSchema(){if(!this.db)throw new Error("Database not initialized");this.db.exec(`
|
|
3
3
|
-- QE Patterns table
|
|
4
4
|
CREATE TABLE IF NOT EXISTS qe_patterns (
|
|
5
5
|
id TEXT PRIMARY KEY,
|
|
@@ -175,14 +175,14 @@ import{a as q}from"./chunk-L6SVCNXK.js";import{g as O,h as X,i as L,j as k,o as
|
|
|
175
175
|
SELECT COUNT(*) as count FROM qe_patterns
|
|
176
176
|
`)),this.prepared.set("countByDomain",this.db.prepare(`
|
|
177
177
|
SELECT qe_domain, COUNT(*) as count FROM qe_patterns GROUP BY qe_domain
|
|
178
|
-
`))}storePattern(e,t,n){if(!this.db)throw new Error("Database not initialized");let r=e.id||w(),a=this.prepared.get("insertPattern"),s=this.prepared.get("insertEmbedding");if(!a||!s)throw new Error("Prepared statements not ready");let i=r;return this.db.transaction(()=>{a.run(r,e.patternType,e.qeDomain,e.domain,e.name,e.description||"",e.confidence,e.tier||"short-term",JSON.stringify(e.template),JSON.stringify(e.context));let p=this.db.prepare("SELECT id FROM qe_patterns WHERE name = ? AND qe_domain = ? AND pattern_type = ?").get(e.name,e.qeDomain??"",e.patternType??"");if(i=p?p.id:r,t){let d=n??g()?.spaceId;if(!d)throw new Error("VECTOR_SPACE_UNVERIFIED: refusing to persist an embedding without runtime provenance");let
|
|
178
|
+
`))}storePattern(e,t,n){if(!this.db)throw new Error("Database not initialized");let r=e.id||w(),a=this.prepared.get("insertPattern"),s=this.prepared.get("insertEmbedding");if(!a||!s)throw new Error("Prepared statements not ready");let i=r;return this.db.transaction(()=>{a.run(r,e.patternType,e.qeDomain,e.domain,e.name,e.description||"",e.confidence,e.tier||"short-term",JSON.stringify(e.template),JSON.stringify(e.context));let p=this.db.prepare("SELECT id FROM qe_patterns WHERE name = ? AND qe_domain = ? AND pattern_type = ?").get(e.name,e.qeDomain??"",e.patternType??"");if(i=p?p.id:r,t){let d=n??g()?.spaceId;if(!d)throw new Error("VECTOR_SPACE_UNVERIFIED: refusing to persist an embedding without runtime provenance");let E=Buffer.from(new Float32Array(t).buffer);s.run(i,E,t.length,"all-MiniLM-L6-v2",d)}})(),i}getPattern(e){if(!this.db)throw new Error("Database not initialized");let t=this.prepared.get("getPatternWithEmbedding");if(!t)throw new Error("Prepared statement not ready");let n=t.get(e);return n?this.rowToPattern(n):null}getPatterns(e={}){if(!this.db)throw new Error("Database not initialized");let t=e.limit||1e3,n,r;return e.domain?(n=this.prepared.get("getPatternsByDomain"),r=n.all(e.domain,t)):(n=this.prepared.get("getAllPatterns"),r=n.all(t)),r.map(a=>this.rowToPattern(a))}searchFTS(e,t=20){if(!this.db)throw new Error("Database not initialized");if(!e.trim())return[];let n=[...new Set(P(e))].filter(s=>s.length>=2).slice(0,32);if(n.length===0)return[];let r=n.map(s=>`"${s}"`).join(" OR "),a=performance.now();try{let s=this.db.prepare(`
|
|
179
179
|
SELECT p.id, rank AS fts_score, p.name, p.description, p.pattern_type, p.qe_domain
|
|
180
180
|
FROM qe_patterns_fts fts
|
|
181
181
|
JOIN qe_patterns p ON p.rowid = fts.rowid
|
|
182
182
|
WHERE qe_patterns_fts MATCH ?
|
|
183
183
|
ORDER BY rank
|
|
184
184
|
LIMIT ?
|
|
185
|
-
`).all(r,t),i=performance.now()-a;i>50&&console.warn(`[FTS5] searchFTS took ${i.toFixed(1)}ms (results=${s.length})`),this._lastFtsLatencyMs=i;let o=Math.max(...s.map(d=>Math.abs(d.fts_score)),1),p=s.length>0?this.searchFTSPhraseIds(e,t):new Set;return s.map(d=>{let
|
|
185
|
+
`).all(r,t),i=performance.now()-a;i>50&&console.warn(`[FTS5] searchFTS took ${i.toFixed(1)}ms (results=${s.length})`),this._lastFtsLatencyMs=i;let o=Math.max(...s.map(d=>Math.abs(d.fts_score)),1),p=s.length>0?this.searchFTSPhraseIds(e,t):new Set;return s.map(d=>{let E=new Set(P([d.name,d.description,d.pattern_type,d.qe_domain].filter(Boolean).join(" "))),T=n.filter(u=>E.has(u)).length;return{id:d.id,ftsScore:Math.abs(d.fts_score)/o,phrase:p.has(d.id),coverage:T/n.length}})}catch{return[]}}searchFTSPhraseIds(e,t){let n='"'+e.replace(/"/g,'""')+'"';try{let r=this.db.prepare(`
|
|
186
186
|
SELECT p.id FROM qe_patterns_fts fts
|
|
187
187
|
JOIN qe_patterns p ON p.rowid = fts.rowid
|
|
188
188
|
WHERE qe_patterns_fts MATCH ?
|
|
@@ -196,7 +196,11 @@ import{a as q}from"./chunk-L6SVCNXK.js";import{g as O,h as X,i as L,j as k,o as
|
|
|
196
196
|
WHERE p.id NOT LIKE 'bench-%'
|
|
197
197
|
AND p.id NOT IN (SELECT pattern_id FROM qe_pattern_embeddings)
|
|
198
198
|
LIMIT 10
|
|
199
|
-
`).all();return{total:e,withoutEmbeddings:t,sampleGhostIds:n.map(r=>r.id)}}getAllEmbeddings(){if(!this.db)throw new Error("Database not initialized");let e=this.prepared.get("getAllEmbeddings");if(!e)throw new Error("Prepared statement not ready");return e.all().map(n=>({patternId:n.pattern_id,embedding:Array.from(new Float32Array(n.embedding.buffer,n.embedding.byteOffset,n.dimension)),spaceId:n.space_id}))}
|
|
199
|
+
`).all();return{total:e,withoutEmbeddings:t,sampleGhostIds:n.map(r=>r.id)}}getAllEmbeddings(){if(!this.db)throw new Error("Database not initialized");let e=this.prepared.get("getAllEmbeddings");if(!e)throw new Error("Prepared statement not ready");return e.all().map(n=>({patternId:n.pattern_id,embedding:Array.from(new Float32Array(n.embedding.buffer,n.embedding.byteOffset,n.dimension)),spaceId:n.space_id}))}getEmbeddingIdsInSpace(e,t={}){if(!this.db)throw new Error("Database not initialized");let n=t.ordered?`SELECT e.pattern_id
|
|
200
|
+
FROM qe_pattern_embeddings e
|
|
201
|
+
LEFT JOIN qe_patterns p ON p.id = e.pattern_id
|
|
202
|
+
WHERE e.space_id = ?
|
|
203
|
+
ORDER BY COALESCE(p.last_used_at, p.created_at, e.created_at) DESC`:"SELECT pattern_id FROM qe_pattern_embeddings WHERE space_id = ?";return this.db.prepare(n).all(e).map(a=>a.pattern_id)}getEmbeddingsByIds(e){if(!this.db)throw new Error("Database not initialized");let t=[],n=this.db.prepare("SELECT pattern_id, embedding, dimension, space_id FROM qe_pattern_embeddings WHERE pattern_id = ?");for(let r of e){let a=n.get(r);a&&t.push({patternId:a.pattern_id,embedding:Array.from(new Float32Array(a.embedding.buffer,a.embedding.byteOffset,a.dimension))})}return t}getRecentEmbeddings(e){if(!this.db)throw new Error("Database not initialized");let t=Number.isFinite(e)&&e>0?Math.floor(e):1e3,n=this.prepared.get("getRecentEmbeddings");if(!n)throw new Error("Prepared statement not ready");return n.all(t).map(a=>({patternId:a.pattern_id,embedding:Array.from(new Float32Array(a.embedding.buffer,a.embedding.byteOffset,a.dimension)),spaceId:a.space_id}))}getEmbeddingSpaceDiagnostics(e=g()?.spaceId??null){if(!this.db)throw new Error("Database not initialized");let t=this.db.prepare("SELECT space_id AS spaceId FROM qe_pattern_embeddings").all();return A(t,e)}recordUsage(e,t,n,r){if(!this.db)throw new Error("Database not initialized");if(!q(this.db,{patternId:e,success:t,metrics:n,feedback:r}).updated)throw new Error(`Pattern not found: ${e}`)}deletePattern(e){if(!this.db)throw new Error("Database not initialized");this.db.transaction(()=>{this.db.prepare("DELETE FROM qe_pattern_embeddings WHERE pattern_id = ?").run(e),this.db.prepare("DELETE FROM qe_pattern_usage WHERE pattern_id = ?").run(e),this.db.prepare("DELETE FROM qe_patterns WHERE id = ?").run(e)})()}promotePattern(e){if(!this.db)throw new Error("Database not initialized");let t=this.prepared.get("promotePattern");if(!t)throw new Error("Prepared statement not ready");t.run(e)}getStats(){if(!this.db)throw new Error("Database not initialized");let e=this.prepared.get("countPatterns"),t=this.prepared.get("countByDomain");if(!e||!t)throw new Error("Prepared statements not ready");let n=e.get().count,r=t.all(),a={};for(let o of r)a[o.qe_domain]=o.count;let s=this.db.prepare(`
|
|
200
204
|
SELECT tier, COUNT(*) as count FROM qe_patterns GROUP BY tier
|
|
201
205
|
`).all(),i={};for(let o of s)i[o.tier]=o.count;return{totalPatterns:n,byDomain:a,byTier:i}}getAggregateOutcomeStats(){let e={routingRequests:0,avgRoutingConfidence:0,successfulRoutings:0,learningOutcomes:0,successfulOutcomes:0,avgPatternSuccessRate:0};if(!this.db)return e;let t=s=>{try{return this.db.prepare(s).get()}catch{return}},n=t(`
|
|
202
206
|
SELECT
|
|
@@ -260,4 +264,4 @@ import{a as q}from"./chunk-L6SVCNXK.js";import{g as O,h as X,i as L,j as k,o as
|
|
|
260
264
|
ORDER BY p.quality_score DESC
|
|
261
265
|
`).all(n),a=this.db.prepare(`
|
|
262
266
|
SELECT COUNT(*) as c FROM qe_pattern_embeddings
|
|
263
|
-
`).get();if(r.length===0)return console.log(`[SQLitePatternStore] Backfill: all patterns already have embeddings (${a.c} total)`),{processed:0,skipped:0,errors:0,alreadyHad:a.c,method:"transformer"};console.log(`[SQLitePatternStore] Backfill: ${r.length} patterns need embeddings (${a.c} already have)`);let s=this.prepared.get("insertEmbedding");if(!s)throw new Error("Prepared statements not ready");let i=0,o=0,p=0,d="transformer";for(let
|
|
267
|
+
`).get();if(r.length===0)return console.log(`[SQLitePatternStore] Backfill: all patterns already have embeddings (${a.c} total)`),{processed:0,skipped:0,errors:0,alreadyHad:a.c,method:"transformer"};console.log(`[SQLitePatternStore] Backfill: ${r.length} patterns need embeddings (${a.c} already have)`);let s=this.prepared.get("insertEmbedding");if(!s)throw new Error("Prepared statements not ready");let i=0,o=0,p=0,d="transformer";for(let E=0;E<r.length;E+=e){let T=r.slice(E,E+e),u=[];for(let c of T){let m=[c.name,c.description,c.pattern_type,c.qe_domain].filter(Boolean).join(" ");if(!m.trim()){o++;continue}u.push({id:c.id,text:m})}if(u.length===0)continue;let R;try{R=await f(u.map(c=>c.text))}catch(c){throw D()?new Error(`[SQLitePatternStore] external embedder endpoint failed during backfill; aborting to protect HNSW index. Original error: ${_(c)}`):new Error(`[SQLitePatternStore] semantic embedding unavailable; refusing to write hash proxies. Install @huggingface/transformers or configure AQE_EMBEDDER_ENDPOINT. Original error: ${_(c)}`)}let F=d==="transformer"?"transformer-backfill":"hash-backfill";this.db.transaction(()=>{for(let c=0;c<u.length;c++)try{let m=R[c];if(!m||m.length!==t){p++;continue}let M=Buffer.from(new Float32Array(m).buffer);s.run(u[c].id,M,t,F,n),i++}catch(m){p++,p<=3&&console.warn(`[SQLitePatternStore] Backfill error for ${u[c].id}:`,_(m))}})();let b=Math.min(E+e,r.length);(b%100===0||b>=r.length)&&console.log(`[SQLitePatternStore] Backfill progress: ${b}/${r.length}`)}return console.log(`[SQLitePatternStore] Backfill complete (${d}): ${i} processed, ${o} skipped, ${p} errors`),{processed:i,skipped:o,errors:p,alreadyHad:a.c,method:d}}close(){this.db&&(this.unifiedMemory?console.log("[SQLitePatternStore] Detached from unified storage (not closing shared connection)"):(this.db.close(),console.log("[SQLitePatternStore] Database closed")),this.db=null,this.unifiedMemory=null,this.initialized=!1,this.prepared.clear())}exec(e){if(!this.db)throw new Error("Database not initialized");this.db.exec(e)}getDb(){if(!this.db)throw new Error("Database not initialized");return this.db}};function te(l={}){return new S(l)}export{H as a,ee as b,S as c,te as d};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{b as C,d as P}from"./chunk-RUSLEOMC.js";import{a as w,d as M}from"./chunk-MQGEZA2A.js";import{a as T}from"./chunk-L336HFFE.js";import{e as S}from"./chunk-E4VIVMDL.js";import{a as b,e as $}from"./chunk-NLDFNAOS.js";$();M();import{randomUUID as A}from"crypto";var x={topology:"hierarchical",maxConcurrentSkills:10,maxConcurrentModels:3,timeout:3e5,continueOnFailure:!0,retry:{maxRetries:2,retryDelayMs:1e3}},R=class{config;learner;skillValidator=null;workers=new Map;taskQueue=[];isRunning=!1;constructor(e,t){this.config={...x,...e},this.learner=t}setSkillValidator(e){this.skillValidator=e}async validateSkillsParallel(e,t,i){let s=Date.now(),a=i?.trustTier??3,n=i?.validationLevel??"eval",c=this.determineTopology(e.length,t.length),r=this.createValidationTasks(e,t,a,n),o=await this.executeTasksParallel(r,c),l=new Map;for(let u of o){let p=l.get(u.skill)||[];p.push(u),l.set(u.skill,p)}return await this.recordOutcomesToLearner(o,a,n),l}async validateSkillCrossModel(e,t,i){return(await this.validateSkillsParallel([e],t,i)).get(e)||[]}getSummary(e){let t=[],i=new Map,s=new Map;for(let[c,r]of e){i.set(c,r);for(let o of r){t.push(o);let l=s.get(o.model)||[];l.push(o),s.set(o.model,l)}}let a=t.filter(c=>c.errors.length===0&&c.evalPassRate>=.9).length,n=t.reduce((c,r)=>c+r.durationMs,0);return{totalSkills:i.size,totalModels:s.size,successCount:a,failureCount:t.length-a,overallPassRate:t.length>0?a/t.length:0,totalDurationMs:n,avgDurationMs:t.length>0?n/t.length:0,topology:this.config.topology,bySkill:i,byModel:s,results:t}}determineTopology(e,t){if(this.config.topology){let i=e*t;return i>20&&this.config.topology==="mesh"&&console.warn(`[SwarmSkillValidator] Large workload (${i} tasks) may be more efficient with hierarchical topology`),this.config.topology}return e>5||e>t*2?"hierarchical":t>5&&e<=3?"mesh":"hierarchical"}createValidationTasks(e,t,i,s){let a=[];for(let n of e)for(let c of t)a.push({id:`${n}-${c}-${Date.now()}-${A().slice(0,8)}`,skill:n,model:c,trustTier:i,validationLevel:s,timeout:this.config.timeout,retryCount:0});return a}async executeTasksParallel(e,t){this.isRunning=!0,this.taskQueue=[...e];let i=[],s=t==="hierarchical"?this.config.maxConcurrentSkills:Math.min(this.config.maxConcurrentSkills*this.config.maxConcurrentModels,e.length),a=[];for(let n=0;n<Math.min(s,e.length);n++){let c=`worker-${n}`;this.workers.set(c,{id:c,task:null,status:"idle"}),a.push(this.runWorker(c,i))}return await Promise.all(a),this.isRunning=!1,this.workers.clear(),i}async runWorker(e,t){let i=this.workers.get(e);if(i){for(;this.taskQueue.length>0&&this.isRunning;){let s=this.taskQueue.shift();if(!s)break;i.task=s,i.status="running",i.startTime=Date.now();try{let a=await this.executeValidationTask(s);t.push(a),i.result=a,i.status="completed"}catch(a){let n=this.createErrorResult(s,a);this.config.retry&&s.retryCount<this.config.retry.maxRetries&&this.config.continueOnFailure?(s.retryCount++,this.taskQueue.push(s),await this.delay(this.config.retry.retryDelayMs)):(t.push(n),i.result=n,i.status="failed")}}i.task=null,i.status="idle"}}async executeValidationTask(e){let t=Date.now();if(!this.skillValidator)return this.createSimulatedResult(e,t);let i=new Promise((n,c)=>{setTimeout(()=>c(new Error(`Validation timeout after ${e.timeout}ms`)),e.timeout)}),s=await Promise.race([this.skillValidator(e.skill,e.model,{trustTier:e.trustTier,validationLevel:e.validationLevel,timeout:e.timeout}),i]),a=Date.now()-t;return this.outcomeToResult(s,e,a)}outcomeToResult(e,t,i){let s=e.testCaseResults.filter(c=>c.passed).length,a=e.testCaseResults.length,n=a>0?s/a:e.score;return{skill:t.skill,model:t.model,schemaValid:e.validationLevel!=="schema"||e.passed,validatorPassed:e.validationLevel!=="validator"||e.passed,evalPassRate:n,durationMs:i,errors:e.passed?[]:["Validation failed"],trustTier:t.trustTier,validationLevel:t.validationLevel,retryCount:t.retryCount,timestamp:new Date}}createSimulatedResult(e,t){let i=Date.now()-t+w()*100,s=.85+w()*.15;return{skill:e.skill,model:e.model,schemaValid:!0,validatorPassed:s>.8,evalPassRate:s,durationMs:i,errors:s>.8?[]:["Simulated validation failure"],trustTier:e.trustTier,validationLevel:e.validationLevel,retryCount:e.retryCount,timestamp:new Date}}createErrorResult(e,t){let i=b(t);return{skill:e.skill,model:e.model,schemaValid:!1,validatorPassed:!1,evalPassRate:0,durationMs:0,errors:[i],trustTier:e.trustTier,validationLevel:e.validationLevel,retryCount:e.retryCount,timestamp:new Date}}async recordOutcomesToLearner(e,t,i){for(let s of e){let a={skillName:s.skill,trustTier:s.trustTier||t,validationLevel:s.validationLevel||i,model:s.model,passed:s.errors.length===0&&s.evalPassRate>=.9,score:s.evalPassRate,testCaseResults:this.createTestCaseResults(s),timestamp:s.timestamp,runId:`swarm-${Date.now()}`,metadata:{duration:s.durationMs,retryCount:s.retryCount}};await this.learner.recordValidationOutcome(a)}}createTestCaseResults(e){return[{testId:`${e.skill}-${e.model}-aggregate`,passed:e.errors.length===0,expectedPatterns:["valid-output"],actualPatterns:e.errors.length===0?["valid-output"]:[],reasoningQuality:e.evalPassRate,executionTimeMs:e.durationMs,category:"swarm-validation",priority:"high",error:e.errors.length>0?e.errors.join("; "):void 0}]}delay(e){return new Promise(t=>setTimeout(t,e))}getConfig(){return{...this.config}}isValidationRunning(){return this.isRunning}getWorkerStatus(){return Array.from(this.workers.values())}cancel(){this.isRunning=!1,this.taskQueue=[]}};function D(y,e){return new R(y,e)}var F=["security-testing","accessibility-testing","api-testing","performance-testing","visual-regression-testing","mutation-testing","contract-testing","chaos-testing","compliance-testing","penetration-testing"],I=["claude-sonnet","claude-haiku","claude-opus"];P();import{readFileSync as E,writeFileSync as L,existsSync as N}from"fs";var O={varianceThreshold:.04,regressionThreshold:.1,minSamples:3,autoUpdateManifest:!1},k=class{constructor(e,t,i={}){this.learner=e;this.manifestPath=t;this.config={...O,...i}}learner;manifestPath;config;async aggregateResults(e){let t=`agg-${Date.now()}`,i=new Date,s=this.buildSkillResultsMap(e),a=this.calculateSummary(s,e),n=await this.detectCrossModelAnomalies(e),c=await this.detectRegressions(e,this.config.regressionThreshold),r=this.generateRecommendations(s,n,c),o={timestamp:i,runId:t,summary:a,skillResults:s,crossModelAnalysis:n,regressions:c,recommendations:r,metadata:{version:"1.0.0",environment:e[0]?.metadata?.environment,generatedBy:"ValidationResultAggregator",inputs:{runIds:e.map(l=>l.runId),models:[...new Set(e.map(l=>l.model))]}}};return this.config.autoUpdateManifest&&await this.updateManifest(o),o}buildSkillResultsMap(e){let t=new Map;for(let i of e)for(let s of i.outcomes){let a=s.skillName;t.has(a)||t.set(a,{skill:a,trustTier:s.trustTier,passRateByModel:new Map,avgPassRate:0,schemaValid:!0,validatorPassed:!0,evalPassed:!0,issues:[],executionTimeMs:0,testCount:0,passedTests:0,failedTests:0});let n=t.get(a),c=s.testCaseResults.filter(r=>r.passed).length/(s.testCaseResults.length||1);n.passRateByModel.set(i.model,c),n.testCount+=s.testCaseResults.length,n.passedTests+=s.testCaseResults.filter(r=>r.passed).length,n.failedTests+=s.testCaseResults.filter(r=>!r.passed).length,n.executionTimeMs+=s.metadata?.duration||0,s.validationLevel==="schema"&&!s.passed&&(n.schemaValid=!1),s.validationLevel==="validator"&&!s.passed&&(n.validatorPassed=!1),s.validationLevel==="eval"&&!s.passed&&(n.evalPassed=!1);for(let r of s.testCaseResults)!r.passed&&r.error&&n.issues.push({skill:a,model:i.model,severity:r.priority==="critical"?"critical":r.priority==="high"?"high":r.priority==="medium"?"medium":"low",type:this.categorizeIssueType(s.validationLevel,r.error),message:r.error,testId:r.testId})}for(let i of t.values()){let s=Array.from(i.passRateByModel.values());i.avgPassRate=s.length>0?s.reduce((a,n)=>a+n,0)/s.length:0}return t}categorizeIssueType(e,t){return t.toLowerCase().includes("timeout")?"timeout":e==="schema"?"schema_failure":e==="validator"?"validator_failure":e==="eval"?"eval_failure":"error"}calculateSummary(e,t){let i=Array.from(e.values()),s=i.filter(n=>n.avgPassRate>=.9).length,a=i.length>0?i.reduce((n,c)=>n+c.avgPassRate,0)/i.length:0;return{totalSkills:i.length,passedSkills:s,failedSkills:i.length-s,avgPassRate:a,totalDurationMs:t.reduce((n,c)=>n+c.durationMs,0),totalTests:i.reduce((n,c)=>n+c.testCount,0),passedTests:i.reduce((n,c)=>n+c.passedTests,0),failedTests:i.reduce((n,c)=>n+c.failedTests,0),modelsUsed:[...new Set(t.map(n=>n.model))]}}async detectCrossModelAnomalies(e){let t=new Map,i=new Map,s=new Map;for(let d of e){t.has(d.model)||(t.set(d.model,[]),i.set(d.model,{totalTests:0,passedTests:0,skillCount:0}));for(let g of d.outcomes){let h=g.testCaseResults.filter(m=>m.passed).length/(g.testCaseResults.length||1);t.get(d.model).push(h);let f=i.get(d.model);f.totalTests+=g.testCaseResults.length,f.passedTests+=g.testCaseResults.filter(m=>m.passed).length,f.skillCount++,s.has(g.skillName)||s.set(g.skillName,{passRates:[],models:[]}),s.get(g.skillName).passRates.push(h),s.get(g.skillName).models.push(d.model)}}let a=[];for(let d of t.values())a.push(...d);let n=a.length>0?a.reduce((d,g)=>d+g,0)/a.length:0,c=a.length>1?a.reduce((d,g)=>d+Math.pow(g-n,2),0)/a.length:0,r=Math.sqrt(c),o=[],l=new Map;for(let[d,g]of t.entries()){let h=g.reduce((v,V)=>v+V,0)/g.length,f=h-n,m=i.get(d);l.set(d,{avgPassRate:h,skillCount:m.skillCount,totalTests:m.totalTests}),Math.abs(f)>this.config.varianceThreshold*2&&o.push({model:d,type:f<0?"low_performance":"high_variance",description:`Model ${d} has ${(f*100).toFixed(1)}% difference from average`,passRate:h,avgPassRate:n,deviation:Math.abs(f)})}let u=[],p=[];for(let[d,g]of s.entries()){if(g.passRates.length<2)continue;let h=g.passRates.reduce((m,v)=>m+v,0)/g.passRates.length;g.passRates.reduce((m,v)=>m+Math.pow(v-h,2),0)/g.passRates.length<this.config.varianceThreshold?u.push(d):p.push(d)}return{variance:c,stdDeviation:r,anomalies:o,consistentSkills:u,inconsistentSkills:p,modelPerformance:l}}async detectRegressions(e,t){let i=[],s=new Set;for(let a of e)for(let n of a.outcomes){let c=`${n.skillName}-${a.model}`;if(s.has(c))continue;s.add(c);let r=await this.learner.getValidationTrends(n.skillName);if(!r)continue;let o=n.testCaseResults.filter(p=>p.passed).length/(n.testCaseResults.length||1),l=r.recentPassRate,u=l-o;u>=t&&i.push({skill:n.skillName,model:a.model,previousPassRate:l,currentPassRate:o,regressionAmount:u,trend:r.overall,possibleCauses:this.analyzePossibleCauses(n,u),severity:this.categorizeRegressionSeverity(u)})}return i.sort((a,n)=>{let c={critical:0,high:1,medium:2,low:3},r=c[a.severity]-c[n.severity];return r!==0?r:n.regressionAmount-a.regressionAmount})}analyzePossibleCauses(e,t){let i=[],s=e.testCaseResults.filter(c=>!c.passed);if(s.length>0){let c=[...new Set(s.map(r=>r.category).filter(Boolean))];c.length>0&&i.push(`Failures in categories: ${c.join(", ")}`)}let a=s.filter(c=>c.priority==="critical");a.length>0&&i.push(`${a.length} critical test(s) failing`);let n=e.testCaseResults.reduce((c,r)=>c+r.reasoningQuality,0)/(e.testCaseResults.length||1);return n<.7&&i.push(`Low reasoning quality score: ${(n*100).toFixed(1)}%`),t>.3&&i.push("Possible model behavior change or prompt drift"),i.length===0&&i.push("No specific cause identified - review test details"),i}categorizeRegressionSeverity(e){return e>=.5?"critical":e>=.3?"high":e>=.15?"medium":"low"}generateRecommendations(e,t,i){let s=[];if(t.inconsistentSkills.length>0&&s.push(`Review ${t.inconsistentSkills.length} skills with inconsistent cross-model behavior: `+t.inconsistentSkills.slice(0,3).join(", ")+(t.inconsistentSkills.length>3?` and ${t.inconsistentSkills.length-3} more`:"")),t.anomalies.some(r=>r.type==="low_performance")){let r=t.anomalies.filter(o=>o.type==="low_performance").map(o=>o.model);s.push(`Investigate low performance on model(s): ${r.join(", ")}`)}let a=i.filter(r=>r.severity==="critical");a.length>0&&s.push(`URGENT: ${a.length} critical regression(s) detected - immediate review required`);let n=Array.from(e.values()).filter(r=>r.avgPassRate<.9);if(n.length>0){let r=n.filter(l=>!l.schemaValid),o=n.filter(l=>!l.validatorPassed);r.length>0&&s.push(`Fix schema validation for: ${r.map(l=>l.skill).slice(0,3).join(", ")}`),o.length>0&&s.push(`Review validator scripts for: ${o.map(l=>l.skill).slice(0,3).join(", ")}`)}return Array.from(e.values()).reduce((r,o)=>r+o.avgPassRate,0)/e.size<.8&&s.push("Overall pass rate below 80% - consider reviewing skill definitions and test expectations"),s.length===0&&s.push("All validations passing - no immediate action required"),s}async updateManifest(e){if(!N(this.manifestPath))throw new Error(`Manifest file not found: ${this.manifestPath}`);let t=C(E(this.manifestPath,"utf-8"));for(let[s,a]of e.skillResults.entries())if(t.skills&&t.skills[s]){let n=t.skills[s];n.validation||(n.validation={}),n.validation.passRate=a.avgPassRate,n.validation.lastValidated=e.timestamp.toISOString(),n.validation.status=a.avgPassRate>=.9?"passing":"failing",n.validation.passRateByModel=Object.fromEntries(a.passRateByModel)}let i=Array.from(e.skillResults.values());t.validationStatus={passing:i.filter(s=>s.avgPassRate>=.9).length,failing:i.filter(s=>s.avgPassRate<.9).length,unknown:0,skipped:t.summary?.tier0||0},t.generatedAt=new Date().toISOString(),t.lastValidationRun={runId:e.runId,timestamp:e.timestamp.toISOString(),avgPassRate:e.summary.avgPassRate,modelsUsed:e.summary.modelsUsed},L(this.manifestPath,JSON.stringify(t,null,2))}generateMarkdownReport(e){let{summary:t,crossModelAnalysis:i,regressions:s,recommendations:a,skillResults:n}=e,c=(t.avgPassRate>=.9||t.avgPassRate>=.7,"`"),r=[];if(r.push(`# Validation Report
|
|
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.6");process.exit(0)}
|
|
2
|
+
import{b as C,d as P}from"./chunk-22OZIJAD.js";import{a as w,d as M}from"./chunk-K55EAWZ5.js";import{a as T}from"./chunk-45MVRQG4.js";import{e as S}from"./chunk-IEPWO4XP.js";import{a as b,e as $}from"./chunk-KYVIOC3C.js";$();M();import{randomUUID as A}from"crypto";var x={topology:"hierarchical",maxConcurrentSkills:10,maxConcurrentModels:3,timeout:3e5,continueOnFailure:!0,retry:{maxRetries:2,retryDelayMs:1e3}},R=class{config;learner;skillValidator=null;workers=new Map;taskQueue=[];isRunning=!1;constructor(e,t){this.config={...x,...e},this.learner=t}setSkillValidator(e){this.skillValidator=e}async validateSkillsParallel(e,t,i){let s=Date.now(),a=i?.trustTier??3,n=i?.validationLevel??"eval",c=this.determineTopology(e.length,t.length),r=this.createValidationTasks(e,t,a,n),o=await this.executeTasksParallel(r,c),l=new Map;for(let u of o){let p=l.get(u.skill)||[];p.push(u),l.set(u.skill,p)}return await this.recordOutcomesToLearner(o,a,n),l}async validateSkillCrossModel(e,t,i){return(await this.validateSkillsParallel([e],t,i)).get(e)||[]}getSummary(e){let t=[],i=new Map,s=new Map;for(let[c,r]of e){i.set(c,r);for(let o of r){t.push(o);let l=s.get(o.model)||[];l.push(o),s.set(o.model,l)}}let a=t.filter(c=>c.errors.length===0&&c.evalPassRate>=.9).length,n=t.reduce((c,r)=>c+r.durationMs,0);return{totalSkills:i.size,totalModels:s.size,successCount:a,failureCount:t.length-a,overallPassRate:t.length>0?a/t.length:0,totalDurationMs:n,avgDurationMs:t.length>0?n/t.length:0,topology:this.config.topology,bySkill:i,byModel:s,results:t}}determineTopology(e,t){if(this.config.topology){let i=e*t;return i>20&&this.config.topology==="mesh"&&console.warn(`[SwarmSkillValidator] Large workload (${i} tasks) may be more efficient with hierarchical topology`),this.config.topology}return e>5||e>t*2?"hierarchical":t>5&&e<=3?"mesh":"hierarchical"}createValidationTasks(e,t,i,s){let a=[];for(let n of e)for(let c of t)a.push({id:`${n}-${c}-${Date.now()}-${A().slice(0,8)}`,skill:n,model:c,trustTier:i,validationLevel:s,timeout:this.config.timeout,retryCount:0});return a}async executeTasksParallel(e,t){this.isRunning=!0,this.taskQueue=[...e];let i=[],s=t==="hierarchical"?this.config.maxConcurrentSkills:Math.min(this.config.maxConcurrentSkills*this.config.maxConcurrentModels,e.length),a=[];for(let n=0;n<Math.min(s,e.length);n++){let c=`worker-${n}`;this.workers.set(c,{id:c,task:null,status:"idle"}),a.push(this.runWorker(c,i))}return await Promise.all(a),this.isRunning=!1,this.workers.clear(),i}async runWorker(e,t){let i=this.workers.get(e);if(i){for(;this.taskQueue.length>0&&this.isRunning;){let s=this.taskQueue.shift();if(!s)break;i.task=s,i.status="running",i.startTime=Date.now();try{let a=await this.executeValidationTask(s);t.push(a),i.result=a,i.status="completed"}catch(a){let n=this.createErrorResult(s,a);this.config.retry&&s.retryCount<this.config.retry.maxRetries&&this.config.continueOnFailure?(s.retryCount++,this.taskQueue.push(s),await this.delay(this.config.retry.retryDelayMs)):(t.push(n),i.result=n,i.status="failed")}}i.task=null,i.status="idle"}}async executeValidationTask(e){let t=Date.now();if(!this.skillValidator)return this.createSimulatedResult(e,t);let i=new Promise((n,c)=>{setTimeout(()=>c(new Error(`Validation timeout after ${e.timeout}ms`)),e.timeout)}),s=await Promise.race([this.skillValidator(e.skill,e.model,{trustTier:e.trustTier,validationLevel:e.validationLevel,timeout:e.timeout}),i]),a=Date.now()-t;return this.outcomeToResult(s,e,a)}outcomeToResult(e,t,i){let s=e.testCaseResults.filter(c=>c.passed).length,a=e.testCaseResults.length,n=a>0?s/a:e.score;return{skill:t.skill,model:t.model,schemaValid:e.validationLevel!=="schema"||e.passed,validatorPassed:e.validationLevel!=="validator"||e.passed,evalPassRate:n,durationMs:i,errors:e.passed?[]:["Validation failed"],trustTier:t.trustTier,validationLevel:t.validationLevel,retryCount:t.retryCount,timestamp:new Date}}createSimulatedResult(e,t){let i=Date.now()-t+w()*100,s=.85+w()*.15;return{skill:e.skill,model:e.model,schemaValid:!0,validatorPassed:s>.8,evalPassRate:s,durationMs:i,errors:s>.8?[]:["Simulated validation failure"],trustTier:e.trustTier,validationLevel:e.validationLevel,retryCount:e.retryCount,timestamp:new Date}}createErrorResult(e,t){let i=b(t);return{skill:e.skill,model:e.model,schemaValid:!1,validatorPassed:!1,evalPassRate:0,durationMs:0,errors:[i],trustTier:e.trustTier,validationLevel:e.validationLevel,retryCount:e.retryCount,timestamp:new Date}}async recordOutcomesToLearner(e,t,i){for(let s of e){let a={skillName:s.skill,trustTier:s.trustTier||t,validationLevel:s.validationLevel||i,model:s.model,passed:s.errors.length===0&&s.evalPassRate>=.9,score:s.evalPassRate,testCaseResults:this.createTestCaseResults(s),timestamp:s.timestamp,runId:`swarm-${Date.now()}`,metadata:{duration:s.durationMs,retryCount:s.retryCount}};await this.learner.recordValidationOutcome(a)}}createTestCaseResults(e){return[{testId:`${e.skill}-${e.model}-aggregate`,passed:e.errors.length===0,expectedPatterns:["valid-output"],actualPatterns:e.errors.length===0?["valid-output"]:[],reasoningQuality:e.evalPassRate,executionTimeMs:e.durationMs,category:"swarm-validation",priority:"high",error:e.errors.length>0?e.errors.join("; "):void 0}]}delay(e){return new Promise(t=>setTimeout(t,e))}getConfig(){return{...this.config}}isValidationRunning(){return this.isRunning}getWorkerStatus(){return Array.from(this.workers.values())}cancel(){this.isRunning=!1,this.taskQueue=[]}};function D(y,e){return new R(y,e)}var F=["security-testing","accessibility-testing","api-testing","performance-testing","visual-regression-testing","mutation-testing","contract-testing","chaos-testing","compliance-testing","penetration-testing"],I=["claude-sonnet","claude-haiku","claude-opus"];P();import{readFileSync as E,writeFileSync as L,existsSync as N}from"fs";var O={varianceThreshold:.04,regressionThreshold:.1,minSamples:3,autoUpdateManifest:!1},k=class{constructor(e,t,i={}){this.learner=e;this.manifestPath=t;this.config={...O,...i}}learner;manifestPath;config;async aggregateResults(e){let t=`agg-${Date.now()}`,i=new Date,s=this.buildSkillResultsMap(e),a=this.calculateSummary(s,e),n=await this.detectCrossModelAnomalies(e),c=await this.detectRegressions(e,this.config.regressionThreshold),r=this.generateRecommendations(s,n,c),o={timestamp:i,runId:t,summary:a,skillResults:s,crossModelAnalysis:n,regressions:c,recommendations:r,metadata:{version:"1.0.0",environment:e[0]?.metadata?.environment,generatedBy:"ValidationResultAggregator",inputs:{runIds:e.map(l=>l.runId),models:[...new Set(e.map(l=>l.model))]}}};return this.config.autoUpdateManifest&&await this.updateManifest(o),o}buildSkillResultsMap(e){let t=new Map;for(let i of e)for(let s of i.outcomes){let a=s.skillName;t.has(a)||t.set(a,{skill:a,trustTier:s.trustTier,passRateByModel:new Map,avgPassRate:0,schemaValid:!0,validatorPassed:!0,evalPassed:!0,issues:[],executionTimeMs:0,testCount:0,passedTests:0,failedTests:0});let n=t.get(a),c=s.testCaseResults.filter(r=>r.passed).length/(s.testCaseResults.length||1);n.passRateByModel.set(i.model,c),n.testCount+=s.testCaseResults.length,n.passedTests+=s.testCaseResults.filter(r=>r.passed).length,n.failedTests+=s.testCaseResults.filter(r=>!r.passed).length,n.executionTimeMs+=s.metadata?.duration||0,s.validationLevel==="schema"&&!s.passed&&(n.schemaValid=!1),s.validationLevel==="validator"&&!s.passed&&(n.validatorPassed=!1),s.validationLevel==="eval"&&!s.passed&&(n.evalPassed=!1);for(let r of s.testCaseResults)!r.passed&&r.error&&n.issues.push({skill:a,model:i.model,severity:r.priority==="critical"?"critical":r.priority==="high"?"high":r.priority==="medium"?"medium":"low",type:this.categorizeIssueType(s.validationLevel,r.error),message:r.error,testId:r.testId})}for(let i of t.values()){let s=Array.from(i.passRateByModel.values());i.avgPassRate=s.length>0?s.reduce((a,n)=>a+n,0)/s.length:0}return t}categorizeIssueType(e,t){return t.toLowerCase().includes("timeout")?"timeout":e==="schema"?"schema_failure":e==="validator"?"validator_failure":e==="eval"?"eval_failure":"error"}calculateSummary(e,t){let i=Array.from(e.values()),s=i.filter(n=>n.avgPassRate>=.9).length,a=i.length>0?i.reduce((n,c)=>n+c.avgPassRate,0)/i.length:0;return{totalSkills:i.length,passedSkills:s,failedSkills:i.length-s,avgPassRate:a,totalDurationMs:t.reduce((n,c)=>n+c.durationMs,0),totalTests:i.reduce((n,c)=>n+c.testCount,0),passedTests:i.reduce((n,c)=>n+c.passedTests,0),failedTests:i.reduce((n,c)=>n+c.failedTests,0),modelsUsed:[...new Set(t.map(n=>n.model))]}}async detectCrossModelAnomalies(e){let t=new Map,i=new Map,s=new Map;for(let d of e){t.has(d.model)||(t.set(d.model,[]),i.set(d.model,{totalTests:0,passedTests:0,skillCount:0}));for(let g of d.outcomes){let h=g.testCaseResults.filter(m=>m.passed).length/(g.testCaseResults.length||1);t.get(d.model).push(h);let f=i.get(d.model);f.totalTests+=g.testCaseResults.length,f.passedTests+=g.testCaseResults.filter(m=>m.passed).length,f.skillCount++,s.has(g.skillName)||s.set(g.skillName,{passRates:[],models:[]}),s.get(g.skillName).passRates.push(h),s.get(g.skillName).models.push(d.model)}}let a=[];for(let d of t.values())a.push(...d);let n=a.length>0?a.reduce((d,g)=>d+g,0)/a.length:0,c=a.length>1?a.reduce((d,g)=>d+Math.pow(g-n,2),0)/a.length:0,r=Math.sqrt(c),o=[],l=new Map;for(let[d,g]of t.entries()){let h=g.reduce((v,V)=>v+V,0)/g.length,f=h-n,m=i.get(d);l.set(d,{avgPassRate:h,skillCount:m.skillCount,totalTests:m.totalTests}),Math.abs(f)>this.config.varianceThreshold*2&&o.push({model:d,type:f<0?"low_performance":"high_variance",description:`Model ${d} has ${(f*100).toFixed(1)}% difference from average`,passRate:h,avgPassRate:n,deviation:Math.abs(f)})}let u=[],p=[];for(let[d,g]of s.entries()){if(g.passRates.length<2)continue;let h=g.passRates.reduce((m,v)=>m+v,0)/g.passRates.length;g.passRates.reduce((m,v)=>m+Math.pow(v-h,2),0)/g.passRates.length<this.config.varianceThreshold?u.push(d):p.push(d)}return{variance:c,stdDeviation:r,anomalies:o,consistentSkills:u,inconsistentSkills:p,modelPerformance:l}}async detectRegressions(e,t){let i=[],s=new Set;for(let a of e)for(let n of a.outcomes){let c=`${n.skillName}-${a.model}`;if(s.has(c))continue;s.add(c);let r=await this.learner.getValidationTrends(n.skillName);if(!r)continue;let o=n.testCaseResults.filter(p=>p.passed).length/(n.testCaseResults.length||1),l=r.recentPassRate,u=l-o;u>=t&&i.push({skill:n.skillName,model:a.model,previousPassRate:l,currentPassRate:o,regressionAmount:u,trend:r.overall,possibleCauses:this.analyzePossibleCauses(n,u),severity:this.categorizeRegressionSeverity(u)})}return i.sort((a,n)=>{let c={critical:0,high:1,medium:2,low:3},r=c[a.severity]-c[n.severity];return r!==0?r:n.regressionAmount-a.regressionAmount})}analyzePossibleCauses(e,t){let i=[],s=e.testCaseResults.filter(c=>!c.passed);if(s.length>0){let c=[...new Set(s.map(r=>r.category).filter(Boolean))];c.length>0&&i.push(`Failures in categories: ${c.join(", ")}`)}let a=s.filter(c=>c.priority==="critical");a.length>0&&i.push(`${a.length} critical test(s) failing`);let n=e.testCaseResults.reduce((c,r)=>c+r.reasoningQuality,0)/(e.testCaseResults.length||1);return n<.7&&i.push(`Low reasoning quality score: ${(n*100).toFixed(1)}%`),t>.3&&i.push("Possible model behavior change or prompt drift"),i.length===0&&i.push("No specific cause identified - review test details"),i}categorizeRegressionSeverity(e){return e>=.5?"critical":e>=.3?"high":e>=.15?"medium":"low"}generateRecommendations(e,t,i){let s=[];if(t.inconsistentSkills.length>0&&s.push(`Review ${t.inconsistentSkills.length} skills with inconsistent cross-model behavior: `+t.inconsistentSkills.slice(0,3).join(", ")+(t.inconsistentSkills.length>3?` and ${t.inconsistentSkills.length-3} more`:"")),t.anomalies.some(r=>r.type==="low_performance")){let r=t.anomalies.filter(o=>o.type==="low_performance").map(o=>o.model);s.push(`Investigate low performance on model(s): ${r.join(", ")}`)}let a=i.filter(r=>r.severity==="critical");a.length>0&&s.push(`URGENT: ${a.length} critical regression(s) detected - immediate review required`);let n=Array.from(e.values()).filter(r=>r.avgPassRate<.9);if(n.length>0){let r=n.filter(l=>!l.schemaValid),o=n.filter(l=>!l.validatorPassed);r.length>0&&s.push(`Fix schema validation for: ${r.map(l=>l.skill).slice(0,3).join(", ")}`),o.length>0&&s.push(`Review validator scripts for: ${o.map(l=>l.skill).slice(0,3).join(", ")}`)}return Array.from(e.values()).reduce((r,o)=>r+o.avgPassRate,0)/e.size<.8&&s.push("Overall pass rate below 80% - consider reviewing skill definitions and test expectations"),s.length===0&&s.push("All validations passing - no immediate action required"),s}async updateManifest(e){if(!N(this.manifestPath))throw new Error(`Manifest file not found: ${this.manifestPath}`);let t=C(E(this.manifestPath,"utf-8"));for(let[s,a]of e.skillResults.entries())if(t.skills&&t.skills[s]){let n=t.skills[s];n.validation||(n.validation={}),n.validation.passRate=a.avgPassRate,n.validation.lastValidated=e.timestamp.toISOString(),n.validation.status=a.avgPassRate>=.9?"passing":"failing",n.validation.passRateByModel=Object.fromEntries(a.passRateByModel)}let i=Array.from(e.skillResults.values());t.validationStatus={passing:i.filter(s=>s.avgPassRate>=.9).length,failing:i.filter(s=>s.avgPassRate<.9).length,unknown:0,skipped:t.summary?.tier0||0},t.generatedAt=new Date().toISOString(),t.lastValidationRun={runId:e.runId,timestamp:e.timestamp.toISOString(),avgPassRate:e.summary.avgPassRate,modelsUsed:e.summary.modelsUsed},L(this.manifestPath,JSON.stringify(t,null,2))}generateMarkdownReport(e){let{summary:t,crossModelAnalysis:i,regressions:s,recommendations:a,skillResults:n}=e,c=(t.avgPassRate>=.9||t.avgPassRate>=.7,"`"),r=[];if(r.push(`# Validation Report
|
|
3
3
|
|
|
4
4
|
> ${c} Generated: ${e.timestamp.toISOString()}
|
|
5
5
|
> Run ID: ${e.runId}
|
|
@@ -0,0 +1,16 @@
|
|
|
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.6");process.exit(0)}
|
|
2
|
+
import{a as $}from"./chunk-4CLDYT36.js";import{r as V,s as K}from"./chunk-YNG7E26C.js";import{i as q}from"./chunk-IVJIHZSM.js";import{a as N,c as k,d}from"./chunk-QLKUCMZC.js";import{a as y,b as M,e as Q}from"./chunk-KYVIOC3C.js";import{f as H}from"./chunk-7SAMMQVS.js";Q();var v={WorkflowStarted:"workflow.WorkflowStarted",WorkflowCompleted:"workflow.WorkflowCompleted",WorkflowFailed:"workflow.WorkflowFailed",WorkflowCancelled:"workflow.WorkflowCancelled",StepStarted:"workflow.StepStarted",StepCompleted:"workflow.StepCompleted",StepFailed:"workflow.StepFailed",StepSkipped:"workflow.StepSkipped",StepAwaitingApproval:"workflow.StepAwaitingApproval",StepApproved:"workflow.StepApproved",StepRejected:"workflow.StepRejected"},T={maxConcurrentWorkflows:10,defaultStepTimeout:6e4,defaultWorkflowTimeout:6e5,enableEventTriggers:!0,persistExecutions:!0};import{createHash as J}from"node:crypto";function R(s){if(["__proto__","constructor","prototype"].includes(s.id))throw new Error(`parallel_output_invalid_path: unsafe step ID ${s.id}`);let e=[{stepId:s.id,path:s.id,segments:[s.id]}];for(let t of Object.values(s.outputMapping??{}).sort()){let i=t.split(".");if(i.some(r=>!r||["__proto__","constructor","prototype"].includes(r)))throw new Error(`parallel_output_invalid_path: ${s.id} maps to ${t}`);e.push({stepId:s.id,path:t,segments:i})}return e}function j(s){let e=s.flatMap(R),t=[];for(let i=0;i<e.length;i++)for(let r=i+1;r<e.length;r++){let o=e[i],a=e[r];if(o.stepId===a.stepId)continue;let n=Math.min(o.segments.length,a.segments.length);o.segments.slice(0,n).every((c,l)=>c===a.segments[l])&&t.push({pathA:o.path,stepA:o.stepId,pathB:a.path,stepB:a.stepId,kind:o.segments.length===a.segments.length?"exact":"ancestor-descendant"})}return t}function L(s){let e=[];for(let t of s){let i=[...Object.values(t.inputMapping??{}),t.condition?.path,t.skipCondition?.path].filter(r=>typeof r=="string");for(let r of i)for(let o of s){if(o.id===t.id)continue;if(r==="results"){e.push({stepId:t.id,sourcePath:r,otherStepId:o.id});continue}if(!r.startsWith("results."))continue;let a=r.slice(8).split(".");R(o).some(c=>{let l=Math.min(a.length,c.segments.length);return c.segments.slice(0,l).every((f,S)=>f===a[S])})&&e.push({stepId:t.id,sourcePath:r,otherStepId:o.id})}}return e}function x(s,e){if(s===null||typeof s=="string"||typeof s=="boolean")return s;if(typeof s=="number")return["number",String(s)];if(typeof s=="bigint")return["bigint",String(s)];if(s===void 0)return["undefined"];if(typeof s!="object")throw new Error("parallel_output_unhashable");if(e.has(s))throw new Error("parallel_output_cyclic");e.add(s);try{if(s instanceof Date)return["date",s.toISOString()];if(s instanceof ArrayBuffer)return["bytes",Buffer.from(s).toString("base64")];if(ArrayBuffer.isView(s))return["bytes",s.constructor.name,Buffer.from(s.buffer,s.byteOffset,s.byteLength).toString("base64")];if(Array.isArray(s))return["array",s.map(i=>x(i,e))];if(s instanceof Set)return["set",[...s].map(r=>x(r,e)).sort((r,o)=>JSON.stringify(r).localeCompare(JSON.stringify(o)))];if(s instanceof Map)return["map",[...s].map(([r,o])=>[x(r,e),x(o,e)]).sort((r,o)=>JSON.stringify(r).localeCompare(JSON.stringify(o)))];let t=s;return["object",Object.keys(t).sort().map(i=>[i,x(t[i],e)])]}finally{e.delete(s)}}function I(s){let e=JSON.stringify(x(s,new Set));return J("sha256").update(e).digest("hex")}var X="qe-coverage-analysis",O=`(agent_id != '${X}' OR (CASE WHEN json_valid(context_json) THEN json_extract(context_json, '$.measured') END) = 1)`;function P(){try{let{getUnifiedMemory:s}=(K(),H(V)),e=s();return e.isInitialized()?e.getDatabase():null}catch{return null}}var Y={id:"quality-gate-check",domain:"quality-assessment",action:"gate-check",async execute(s){let e=typeof s.coverageMin=="number"?s.coverageMin:80,t=typeof s.testsPassingMin=="number"?s.testsPassingMin:90,i=typeof s.maxBugs=="number"?s.maxBugs:5,r=typeof s.currentCoverage=="number"?s.currentCoverage:null,o=typeof s.currentTestsPassingRate=="number"?s.currentTestsPassingRate:null,a=typeof s.currentBugs=="number"?s.currentBugs:null;if(r===null||o===null||a===null){let b=P();if(b)try{if(r===null){let h=b.prepare(`SELECT after_lines FROM coverage_sessions WHERE ${O} ORDER BY created_at DESC LIMIT 1`).get();r=typeof h?.after_lines=="number"?h.after_lines:null}if(o===null){let h=b.prepare(`SELECT COUNT(*) as total,
|
|
3
|
+
SUM(CASE WHEN passed = 1 THEN 1 ELSE 0 END) as passed
|
|
4
|
+
FROM test_outcomes
|
|
5
|
+
WHERE created_at > datetime('now', '-7 days')`).get();o=h&&h.total>0?h.passed/h.total*100:0}a===null&&(a=b.prepare(`SELECT COUNT(*) as bugs FROM test_outcomes
|
|
6
|
+
WHERE passed = 0 AND flaky = 0
|
|
7
|
+
AND created_at > datetime('now', '-7 days')`).get()?.bugs??0)}catch{}}let n=r!==null;o=o??0,a=a??0;let c=r!==null&&r>=e,l=o>=t,f=a<=i,S=c&&l&&f,A=r===null?0:Math.min(r/e,1),u=Math.min(o/t,1),w=i>0?Math.max(0,1-a/i):a===0?1:0,m=(A+u+w)/3;return k({passed:S,score:Math.round(m*100)/100,source:typeof s.currentCoverage=="number"?"input":"database",details:{coverage:{current:r,threshold:e,passed:c,...n?{}:{unmeasured:!0}},testsPassing:{current:o,threshold:t,passed:l},bugs:{current:a,threshold:i,passed:f}}})}},Z={id:"coverage-threshold",domain:"coverage-analysis",action:"threshold-check",async execute(s){let e=typeof s.minCoverage=="number"?s.minCoverage:80,t=typeof s.currentCoverage=="number"?s.currentCoverage:null,i="input";if(t===null){i="database";let a=P();if(a)try{let n=a.prepare(`SELECT after_lines FROM coverage_sessions WHERE ${O} ORDER BY created_at DESC LIMIT 1`).get();t=typeof n?.after_lines=="number"?n.after_lines:null}catch{t=null}else t=null}let r=t!==null&&t>=e,o=t===null?null:r?0:Math.round((e-t)*100)/100;return k({currentCoverage:t,passed:r,gap:o,minCoverage:e,source:i,...t===null?{unmeasured:!0}:{}})}},ee={id:"pattern-health",domain:"learning-optimization",action:"health-check",async execute(s){let e=typeof s.totalPatterns=="number"?s.totalPatterns:null,t=typeof s.activePatterns=="number"?s.activePatterns:null,i=typeof s.avgConfidence=="number"?s.avgConfidence:null,r="input";if(e===null||t===null||i===null){r="database";let c=P();if(c)try{let l=c.prepare(`
|
|
8
|
+
SELECT COUNT(*) as total,
|
|
9
|
+
SUM(CASE WHEN deprecated_at IS NULL AND confidence >= 0.3 THEN 1 ELSE 0 END) as active,
|
|
10
|
+
AVG(confidence) as avg_conf
|
|
11
|
+
FROM qe_patterns
|
|
12
|
+
`).get();e=e??l?.total??0,t=t??l?.active??0,i=i??l?.avg_conf??0}catch{}}e=e??0,t=t??0,i=i??0;let o=Math.min(e/100,1),a=e>0?t/e:0,n=Math.round((o*.3+a*.3+i*.4)*100)/100;return k({totalPatterns:e,activePatterns:t,avgConfidence:i,healthScore:n,source:r})}},te={id:"routing-accuracy",domain:"learning-optimization",action:"routing-check",async execute(s){let e=typeof s.totalOutcomes=="number"?s.totalOutcomes:null,t=typeof s.successfulOutcomes=="number"?s.successfulOutcomes:null,i=typeof s.confidenceCorrelation=="number"?s.confidenceCorrelation:null,r="input";if(e===null||t===null){r="database";let a=P();if(a)try{let n=a.prepare(`
|
|
13
|
+
SELECT COUNT(*) as total,
|
|
14
|
+
SUM(CASE WHEN success = 1 THEN 1 ELSE 0 END) as successful
|
|
15
|
+
FROM routing_outcomes
|
|
16
|
+
`).get();e=e??n?.total??0,t=t??n?.successful??0}catch{}}e=e??0,t=t??0,i=i??0;let o=e>0?Math.round(t/e*1e4)/100:0;return k({successRate:o,totalOutcomes:e,successfulOutcomes:t,confidenceCorrelation:i,source:r})}},re=[Y,Z,ee,te];function B(s,e){return re.find(t=>t.domain===s&&t.action===e)}function z(){return[ie(),ne(),oe(),se(),ae(),le()]}var G=["comprehensive-testing","defect-prevention","pre-release","continuous-learning","morning-sync","qcsd-ideation-swarm"];function ie(){return{id:"comprehensive-testing",name:"Comprehensive Testing Workflow",description:"test-generation -> test-execution -> coverage-analysis -> quality-assessment",version:"1.0.0",tags:["testing","quality"],steps:[{id:"generate-tests",name:"Generate Tests",domain:"test-generation",action:"generateTests",inputMapping:{sourceFiles:"input.sourceFiles",framework:"input.framework"},outputMapping:{testFiles:"generatedTests.files",testCount:"generatedTests.count"},timeout:12e4,retry:{maxAttempts:2,backoffMs:1e3}},{id:"execute-tests",name:"Execute Tests",domain:"test-execution",action:"execute",dependsOn:["generate-tests"],inputMapping:{testFiles:"results.generatedTests.files"},outputMapping:{runId:"execution.runId",passed:"execution.passed",failed:"execution.failed"},timeout:3e5},{id:"analyze-coverage",name:"Analyze Coverage",domain:"coverage-analysis",action:"analyze",dependsOn:["execute-tests"],inputMapping:{runId:"results.execution.runId"},outputMapping:{line:"coverage.line",branch:"coverage.branch",overall:"coverage.overall"}},{id:"assess-quality",name:"Assess Quality",domain:"quality-assessment",action:"evaluateGate",dependsOn:["analyze-coverage"],inputMapping:{coverage:"results.coverage",testResults:"results.execution"},outputMapping:{passed:"quality.gatePassed",score:"quality.score"}},{id:"generate-more-tests",name:"Generate Additional Tests",domain:"test-generation",action:"generateTests",dependsOn:["analyze-coverage"],condition:{path:"results.coverage.overall",operator:"lt",value:80},inputMapping:{sourceFiles:"input.sourceFiles",targetCoverage:"input.targetCoverage"},continueOnFailure:!0}]}}function ne(){return{id:"defect-prevention",name:"Defect Prevention Workflow",description:"code-intelligence (impact) -> defect-intelligence (predict) -> test-generation (for risky areas)",version:"1.0.0",tags:["defect","prevention","ai"],steps:[{id:"analyze-impact",name:"Analyze Code Impact",domain:"code-intelligence",action:"analyzeImpact",inputMapping:{changedFiles:"input.changedFiles"},outputMapping:{impactedFiles:"impact.files",impactedTests:"impact.tests",riskLevel:"impact.riskLevel"},timeout:6e4},{id:"predict-defects",name:"Predict Defects",domain:"defect-intelligence",action:"predictDefects",dependsOn:["analyze-impact"],inputMapping:{files:"results.impact.files"},outputMapping:{predictions:"defects.predictions",highRiskFiles:"defects.highRiskFiles"}},{id:"generate-targeted-tests",name:"Generate Targeted Tests",domain:"test-generation",action:"generateTests",dependsOn:["predict-defects"],condition:{path:"results.defects.highRiskFiles",operator:"exists",value:!0},inputMapping:{sourceFiles:"results.defects.highRiskFiles",priority:"input.priority"}}],triggers:[{eventType:"code-intelligence.ImpactAnalysisCompleted",inputMapping:{changedFiles:"event.changedFiles"}}]}}function oe(){return{id:"pre-release",name:"Pre-Release Workflow",description:"security-audit -> quality-gate -> deployment-advisor",version:"1.0.0",tags:["release","security","deployment"],steps:[{id:"security-audit",name:"Security Audit",domain:"security-compliance",action:"runAudit",inputMapping:{targetFiles:"input.targetFiles",includeDependencies:"input.includeDependencies"},outputMapping:{vulnerabilities:"security.vulnerabilities",riskScore:"security.riskScore",passed:"security.passed"},timeout:18e4},{id:"quality-gate",name:"Quality Gate Evaluation",domain:"quality-assessment",action:"evaluateGate",dependsOn:["security-audit"],inputMapping:{securityResults:"results.security",releaseCandidate:"input.releaseCandidate"},outputMapping:{passed:"quality.gatePassed",checks:"quality.checks"}},{id:"deployment-advice",name:"Get Deployment Advice",domain:"quality-assessment",action:"getDeploymentAdvice",dependsOn:["quality-gate"],inputMapping:{releaseCandidate:"input.releaseCandidate",qualityResults:"results.quality",securityResults:"results.security"},outputMapping:{decision:"deployment.decision",recommendations:"deployment.recommendations",riskScore:"deployment.riskScore"}}],triggers:[{eventType:"quality-assessment.QualityGateEvaluated",condition:{path:"event.passed",operator:"eq",value:!0}}]}}function se(){return{id:"continuous-learning",name:"Continuous Learning Workflow",description:"Collect patterns -> consolidate -> transfer -> optimize",version:"1.0.0",tags:["learning","optimization","ai"],steps:[{id:"collect-patterns",name:"Collect Patterns",domain:"learning-optimization",action:"runLearningCycle",inputMapping:{domain:"input.targetDomain"},outputMapping:{patternsLearned:"learning.patterns",experiencesProcessed:"learning.experiences"}},{id:"consolidate-patterns",name:"Consolidate Patterns",domain:"learning-optimization",action:"shareCrossDomainLearnings",dependsOn:["collect-patterns"],condition:{path:"results.learning.patterns",operator:"gt",value:0},outputMapping:{knowledgeShared:"consolidation.shared",domainsUpdated:"consolidation.domains"}},{id:"transfer-knowledge",name:"Transfer Knowledge",domain:"learning-optimization",action:"shareCrossDomainLearnings",dependsOn:["consolidate-patterns"],outputMapping:{transferSuccessRate:"transfer.successRate",newPatternsCreated:"transfer.newPatterns"}},{id:"optimize-strategies",name:"Optimize Strategies",domain:"learning-optimization",action:"optimizeAllStrategies",dependsOn:["transfer-knowledge"],outputMapping:{domainsOptimized:"optimization.domains",avgImprovement:"optimization.improvement"}}]}}function ae(){return{id:"morning-sync",name:"Morning Sync Protocol",description:"Daily quality synchronization across all domains",version:"1.0.0",tags:["protocol","daily","sync"],steps:[{id:"collect-metrics",name:"Collect Quality Metrics",domain:"quality-assessment",action:"analyzeQuality",inputMapping:{sourceFiles:"input.sourceFiles"},outputMapping:{score:"metrics.qualityScore"}},{id:"analyze-trends",name:"Analyze Coverage Trends",domain:"coverage-analysis",action:"getTrend",inputMapping:{timeRange:"input.timeRange",granularity:"input.granularity"},outputMapping:{trend:"trends.coverage",forecast:"trends.forecast"}},{id:"check-security",name:"Check Security Posture",domain:"security-compliance",action:"getSecurityPosture",outputMapping:{overallScore:"security.score",criticalIssues:"security.critical",recommendations:"security.recommendations"}},{id:"get-defect-predictions",name:"Get Defect Predictions",domain:"defect-intelligence",action:"predictDefects",inputMapping:{files:"input.changedFiles"},outputMapping:{predictions:"defects.predictions"}},{id:"generate-learning-report",name:"Generate Learning Dashboard",domain:"learning-optimization",action:"getLearningDashboard",dependsOn:["collect-metrics","analyze-trends","check-security","get-defect-predictions"],outputMapping:{learningRate:"learning.rate",topDomains:"learning.topDomains"}}]}}function le(){return{id:"qcsd-ideation-swarm",name:"QCSD Ideation Swarm",description:"Quality Conscious Software Delivery ideation phase: [url-extraction] -> [flag-detection] -> quality-criteria (HTSM) -> [testability, risk, requirements, security*, accessibility*, qx*] in parallel -> aggregated report. Supports live website URLs with conditional agent spawning based on HAS_UI, HAS_SECURITY, HAS_UX flags.",version:"3.0.0",tags:["qcsd","ideation","quality-criteria","htsm","shift-left","url-analysis"],steps:[{id:"website-content-extraction",name:"Website Content Extraction",domain:"requirements-validation",action:"extractWebsiteContent",inputMapping:{url:"input.url"},outputMapping:{extractedDescription:"extraction.description",extractedFeatures:"extraction.features",extractedAcceptanceCriteria:"extraction.acceptanceCriteria",detectedFlags:"extraction.flags",isWebsite:"extraction.isWebsite"},timeout:6e4,continueOnFailure:!0},{id:"quality-criteria-analysis",name:"HTSM Quality Criteria Analysis",domain:"requirements-validation",action:"analyzeQualityCriteria",dependsOn:["website-content-extraction"],inputMapping:{targetId:"input.targetId",targetType:"input.targetType",description:"results.website-content-extraction.extractedDescription || input.description",acceptanceCriteria:"results.website-content-extraction.extractedAcceptanceCriteria || input.acceptanceCriteria"},outputMapping:{qualityCriteria:"qualityCriteria.criteria",qualityScore:"qualityCriteria.score"},timeout:18e4,retry:{maxAttempts:2,backoffMs:2e3}},{id:"testability-assessment",name:"Testability Scoring (10 Principles)",domain:"requirements-validation",action:"assessTestability",dependsOn:["quality-criteria-analysis"],inputMapping:{targetId:"input.targetId",description:"results.website-content-extraction.extractedDescription || input.description",acceptanceCriteria:"results.website-content-extraction.extractedAcceptanceCriteria || input.acceptanceCriteria"},outputMapping:{overallScore:"testability.overallScore",principles:"testability.principles",blockers:"testability.blockers",recommendations:"testability.recommendations"},timeout:12e4,continueOnFailure:!0},{id:"risk-assessment",name:"Quality Risk Assessment",domain:"requirements-validation",action:"assessRisks",dependsOn:["quality-criteria-analysis"],inputMapping:{targetId:"input.targetId",targetType:"input.targetType",description:"results.website-content-extraction.extractedDescription || input.description"},outputMapping:{overallRisk:"risks.overallRisk",riskScore:"risks.riskScore",factors:"risks.factors",mitigations:"risks.mitigations"},timeout:9e4,continueOnFailure:!0},{id:"requirements-validation",name:"Requirements & Acceptance Criteria Validation",domain:"requirements-validation",action:"validateRequirements",dependsOn:["quality-criteria-analysis"],inputMapping:{targetId:"input.targetId",description:"results.website-content-extraction.extractedDescription || input.description",acceptanceCriteria:"results.website-content-extraction.extractedAcceptanceCriteria || input.acceptanceCriteria"},outputMapping:{valid:"requirements.valid",issues:"requirements.issues",suggestions:"requirements.suggestions"},timeout:9e4,continueOnFailure:!0},{id:"security-threat-modeling",name:"Early Security Threat Modeling (STRIDE)",domain:"security-compliance",action:"modelSecurityThreats",dependsOn:["quality-criteria-analysis"],condition:{path:"results.website-content-extraction.detectedFlags.hasSecurity || input.securityCritical",operator:"eq",value:!0},inputMapping:{targetId:"input.targetId",description:"results.website-content-extraction.extractedDescription || input.description",securityCritical:"results.website-content-extraction.detectedFlags.hasSecurity || input.securityCritical"},outputMapping:{threats:"security.threats",overallRisk:"security.overallRisk",recommendations:"security.recommendations"},timeout:12e4,continueOnFailure:!0},{id:"accessibility-audit",name:"Accessibility Audit (WCAG 2.2)",domain:"visual-accessibility",action:"auditAccessibility",dependsOn:["quality-criteria-analysis"],condition:{path:"results.website-content-extraction.detectedFlags.hasUI || input.hasUI",operator:"eq",value:!0},inputMapping:{targetId:"input.targetId",url:"input.url",description:"results.website-content-extraction.extractedDescription || input.description",features:"results.website-content-extraction.extractedFeatures"},outputMapping:{wcagLevel:"accessibility.wcagLevel",violations:"accessibility.violations",recommendations:"accessibility.recommendations"},timeout:18e4,continueOnFailure:!0},{id:"quality-experience-analysis",name:"Quality Experience Analysis (QX Partner)",domain:"coordination",action:"analyzeQualityExperience",dependsOn:["quality-criteria-analysis"],condition:{path:"results.website-content-extraction.detectedFlags.hasUX || input.hasUX",operator:"eq",value:!0},inputMapping:{targetId:"input.targetId",url:"input.url",description:"results.website-content-extraction.extractedDescription || input.description",features:"results.website-content-extraction.extractedFeatures"},outputMapping:{journeys:"qx.journeys",frictionPoints:"qx.frictionPoints",recommendations:"qx.recommendations"},timeout:15e4,continueOnFailure:!0},{id:"aggregate-ideation-report",name:"Generate Ideation Report",domain:"requirements-validation",action:"generateIdeationReport",dependsOn:["quality-criteria-analysis","testability-assessment","risk-assessment","requirements-validation","security-threat-modeling","accessibility-audit","quality-experience-analysis"],inputMapping:{targetId:"input.targetId",targetType:"input.targetType"},outputMapping:{report:"ideation.report",readyForDevelopment:"ideation.readyForDevelopment",blockers:"ideation.blockers",recommendations:"ideation.recommendations",testStrategy:"ideation.testStrategy"},timeout:6e4},{id:"store-ideation-learnings",name:"Store Ideation Learnings",domain:"learning-optimization",action:"storeIdeationLearnings",dependsOn:["aggregate-ideation-report"],inputMapping:{targetId:"input.targetId",report:"results.ideation.report"},outputMapping:{stored:"learning.stored",patternId:"learning.patternId"},continueOnFailure:!0}],triggers:[{eventType:"requirements-validation.EpicCreated",inputMapping:{targetId:"event.epicId",targetType:"event.type",description:"event.description",acceptanceCriteria:"event.acceptanceCriteria"}},{eventType:"requirements-validation.SprintPlanningStarted",inputMapping:{targetId:"event.sprintId",targetType:"event.type",description:"event.description",acceptanceCriteria:"event.acceptanceCriteria"}}]}}var _=class{constructor(e,t,i,r={}){this.eventBus=e;this.memory=t;this.agentCoordinator=i;this.config={...T,...r}}eventBus;memory;agentCoordinator;config;workflows=new Map;executions=new Map;actionRegistry={};eventSubscriptions=[];approvalGates=new Map;initialized=!1;async initialize(){this.initialized||(this.registerBuiltInWorkflows(),this.config.enableEventTriggers&&this.setupEventTriggers(),await this.loadPersistedWorkflows(),this.initialized=!0)}async dispose(){for(let e of this.executions.values())e.status==="running"&&await this.cancelWorkflow(e.executionId);for(let e of this.eventSubscriptions)e.unsubscribe();await this.persistWorkflows(),this.initialized=!1}registerWorkflow(e){try{let t=this.validateWorkflowDefinition(e);return t.success?(this.workflows.set(e.id,e),this.config.enableEventTriggers&&e.triggers&&this.registerWorkflowTriggers(e),k(void 0)):t}catch(t){return d(M(t))}}unregisterWorkflow(e){if(!this.workflows.has(e))return d(new Error(`Workflow not found: ${e}`));let t=Array.from(this.executions.values()).filter(i=>i.workflowId===e&&i.status==="running");return t.length>0?d(new Error(`Cannot unregister workflow with ${t.length} active execution(s)`)):(this.workflows.delete(e),k(void 0))}async executeWorkflow(e,t={},i){let r=this.workflows.get(e);if(!r)return d(new Error(`Workflow not found: ${e}`));if(Array.from(this.executions.values()).filter(f=>f.status==="running").length>=this.config.maxConcurrentWorkflows)return d(new Error(`Maximum concurrent workflows (${this.config.maxConcurrentWorkflows}) reached`));let a=q(),n=new Date,c={input:t,results:{},metadata:{executionId:a,workflowId:e,correlationId:i||a,startedAt:n}},l={executionId:a,workflowId:e,workflowName:r.name,status:"running",startedAt:n,progress:0,currentSteps:[],completedSteps:[],failedSteps:[],skippedSteps:[],context:c,stepResults:new Map,parallelCompositionReceipts:[]};return this.executions.set(a,l),await this.publishWorkflowStarted(l,r),this.runWorkflow(r,l).catch(async f=>{l.status="failed",l.error=y(f),l.completedAt=new Date,l.duration=l.completedAt.getTime()-n.getTime(),await this.publishWorkflowFailed(l,"unknown",String(f))}),k(a)}getWorkflowStatus(e){return this.executions.get(e)}async cancelWorkflow(e){let t=this.executions.get(e);return t?t.status!=="running"&&t.status!=="paused"?d(new Error(`Cannot cancel workflow in status: ${t.status}`)):(t.status="cancelled",t.completedAt=new Date,t.duration=t.completedAt.getTime()-t.startedAt.getTime(),this.closeApprovalGates(e,"Workflow cancelled"),await this.publishEvent(v.WorkflowCancelled,{executionId:e,workflowId:t.workflowId,workflowName:t.workflowName},t.context.metadata.correlationId),k(void 0)):d(new Error(`Execution not found: ${e}`))}async pauseWorkflow(e){let t=this.executions.get(e);return t?t.status!=="running"?d(new Error(`Cannot pause workflow in status: ${t.status}`)):(t.status="paused",k(void 0)):d(new Error(`Execution not found: ${e}`))}async resumeWorkflow(e){let t=this.executions.get(e);if(!t)return d(new Error(`Execution not found: ${e}`));if(t.status!=="paused")return d(new Error(`Cannot resume workflow in status: ${t.status}`));let i=this.workflows.get(t.workflowId);return i?(t.status="running",this.runWorkflow(i,t).catch(async r=>{t.status="failed",t.error=y(r)}),k(void 0)):d(new Error(`Workflow definition not found: ${t.workflowId}`))}listWorkflows(){return Array.from(this.workflows.values()).map(e=>({id:e.id,name:e.name,description:e.description,version:e.version,stepCount:e.steps.length,tags:e.tags,triggers:e.triggers?.map(t=>t.eventType)}))}getActiveExecutions(){return Array.from(this.executions.values()).filter(e=>e.status==="running"||e.status==="paused")}getWorkflow(e){return this.workflows.get(e)}approveStep(e,t){let i=`${e}:${t}`,r=this.approvalGates.get(i);return r?(r.resolve({approved:!0}),this.approvalGates.delete(i),!0):!1}rejectStep(e,t,i){let r=`${e}:${t}`,o=this.approvalGates.get(r);return o?(o.resolve({approved:!1,reason:i}),this.approvalGates.delete(r),!0):!1}isActionRegistered(e,t){return!!this.actionRegistry[e]?.[t]}getRegisteredActions(e){return Object.keys(this.actionRegistry[e]||{})}getDomainsWithActions(){return Object.keys(this.actionRegistry)}async spawnWorkflowAgent(e,t,i){return this.agentCoordinator.canSpawn()?this.agentCoordinator.spawn({name:`workflow-agent-${e.slice(0,8)}-${t}`,domain:i,type:"coordinator",capabilities:["workflow-execution",t],config:{workflowId:e,stepId:t}}):d(new Error("Agent limit reached"))}async stopWorkflowAgent(e){return this.agentCoordinator.stop(e)}getAvailableAgentCapacity(){return this.agentCoordinator.canSpawn()?this.config.maxConcurrentWorkflows-this.getActiveExecutions().length:0}registerAction(e,t,i){let r=["__proto__","constructor","prototype"];if(r.includes(e)||r.includes(t))throw new Error("Invalid domain or action name: contains dangerous prototype key");this.actionRegistry[e]||(this.actionRegistry[e]={}),this.actionRegistry[e][t]=i}async executeFromBehaviorTree(e){let t=new Date;try{let i=await e.tick(),r=new Date,o=r.getTime()-t.getTime();return{status:i==="SUCCESS"?"completed":i==="RUNNING"?"running":"failed",startedAt:t,completedAt:r,duration:o,treeStatus:i,treeName:e.name}}catch(i){let r=new Date,o=r.getTime()-t.getTime();return{status:"failed",startedAt:t,completedAt:r,duration:o,treeStatus:"FAILURE",treeName:e.name,error:y(i)}}}async runWorkflow(e,t){let i=e.timeout||this.config.defaultWorkflowTimeout,r,o=new Promise((a,n)=>{r=setTimeout(()=>n(new Error(`Workflow timeout after ${i}ms`)),i)});try{await Promise.race([this.executeSteps(e,t),o]),t.status==="running"&&(t.status="completed",t.completedAt=new Date,t.duration=t.completedAt.getTime()-t.startedAt.getTime(),t.progress=100,await this.publishWorkflowCompleted(t))}catch(a){if(t.status==="running"){t.status="failed",t.error=y(a),this.closeApprovalGates(t.executionId,"Workflow failed"),t.completedAt=new Date,t.duration=t.completedAt.getTime()-t.startedAt.getTime();let n=t.currentSteps[0]||"unknown";t.currentSteps=[],await this.publishWorkflowFailed(t,n,y(a))}}finally{r&&clearTimeout(r)}this.config.persistExecutions&&await this.persistExecution(t)}async executeSteps(e,t){let i=e.steps,r=new Set(t.completedSteps),o=new Set(t.skippedSteps),a=new Set(t.failedSteps),n=i.filter(c=>!r.has(c.id)&&!o.has(c.id)&&!a.has(c.id));for(;n.length>0&&t.status==="running";){let c=n.filter(u=>(u.dependsOn||[]).every(m=>r.has(m)||o.has(m)));if(c.length===0)break;let l=c.filter(u=>!u.dependsOn?.length),f=c.filter(u=>u.dependsOn?.length);if(l.length===1&&f.unshift(l[0]),l.length>1){t.currentSteps=l.map(p=>p.id);let u={version:1,workflowId:e.id,workflowRevision:`${e.version}:${I(e)}`,executionId:t.executionId,groupId:l.map(p=>p.id).join("|"),steps:[],conflicts:[],strategy:"rejected",disposition:"invalid"};t.parallelCompositionReceipts??=[],t.parallelCompositionReceipts.push(u);try{u.steps=l.map(p=>({stepId:p.id,disposition:"not_started",writes:R(p).map(g=>g.path)})),u.conflicts=j(l)}catch(p){throw new Error(`parallel_output_invalid_path: ${y(p)}`)}if(u.conflicts.length>0)throw u.disposition="conflict",new Error(`parallel_output_conflict: ${u.conflicts.map(p=>`${p.stepA}.${p.pathA} \u2194 ${p.stepB}.${p.pathB}`).join(", ")}`);let w=L(l);if(w.length>0)throw new Error(`parallel_dependency_error: ${w.map(p=>`${p.stepId} reads ${p.sourcePath} from concurrent step ${p.otherStepId}`).join(", ")}`);let m,b,h;try{m=structuredClone(t.context),h=I(m.results),b=l.map(()=>structuredClone(m))}catch(p){throw new Error(`parallel_context_uncloneable: ${y(p)}`)}let F=await Promise.allSettled(l.map((p,g)=>this.executeStep(p,t,e,b[g],!0))),D;for(let p=0;p<l.length;p++){let g=l[p],W=F[p];if(W.status==="fulfilled"){let C=W.value;if(t.stepResults.set(g.id,C),C.status==="completed"){r.add(g.id),t.completedSteps.push(g.id),u.steps[p].disposition="succeeded";try{u.steps[p].outputHash=I(C.output)}catch(U){throw new Error(`parallel_output_unhashable: ${y(U)}`)}}else C.status==="skipped"?(o.add(g.id),t.skippedSteps.push(g.id),u.steps[p].disposition="skipped"):C.status==="failed"&&(a.add(g.id),t.failedSteps.push(g.id),u.steps[p].disposition="failed",g.continueOnFailure||(D??=C.error??"Unknown error"))}else a.add(g.id),t.failedSteps.push(g.id),u.steps[p].disposition="failed",g.continueOnFailure||(D??=y(W.reason));let E=n.indexOf(g);E!==-1&&n.splice(E,1)}if(t.status!=="running"||D!==void 0){if(u.disposition="partial",D!==void 0)throw new Error(D);if(t.status!=="running")return}else try{let p={...m,results:structuredClone(m.results)};for(let W=0;W<l.length;W++){let E=F[W];E.status==="fulfilled"&&E.value.status==="completed"&&this.mapStepOutput(l[W],E.value.output,p)}let g=I(p.results);if(t.status!=="running"){u.disposition="partial";return}if(I(t.context.results)!==h)throw new Error("parallel_context_changed: shared results changed before composition");t.context.results=p.results,u.combinedStateHash=g,u.strategy="disjoint",u.disposition="composed"}catch(p){throw u.disposition="invalid",new Error(`parallel_output_invalid: ${y(p)}`)}}for(let u of f){if(t.status!=="running")break;t.currentSteps=[u.id];let w=await this.executeStep(u,t,e);if(w.status==="completed")r.add(u.id),t.completedSteps.push(u.id);else if(w.status==="skipped")o.add(u.id),t.skippedSteps.push(u.id);else if(w.status==="failed"&&(a.add(u.id),t.failedSteps.push(u.id),!u.continueOnFailure)){t.status="failed",t.error=w.error;return}let m=n.indexOf(u);m!==-1&&n.splice(m,1)}let S=i.length,A=r.size+o.size+a.size;t.progress=Math.round(A/S*100)}t.currentSteps=[]}async executeStep(e,t,i,r=t.context,o=!1){let a=new Date,n={stepId:e.id,status:"pending",startedAt:a};try{if(e.skipCondition&&this.evaluateCondition(e.skipCondition,r))return n.status="skipped",n.completedAt=new Date,n.duration=n.completedAt.getTime()-a.getTime(),o||t.stepResults.set(e.id,n),await this.publishStepSkipped(t,e),n;if(e.condition&&!this.evaluateCondition(e.condition,r))return n.status="skipped",n.completedAt=new Date,n.duration=n.completedAt.getTime()-a.getTime(),o||t.stepResults.set(e.id,n),await this.publishStepSkipped(t,e),n;n.status="running",await this.publishStepStarted(t,e);let c=this.buildStepInput(e,r);if(e.approval){n.status="awaiting_approval",t.stepResults.set(e.id,n);let u=await this.waitForApproval(e,t);if(!u.approved||t.status!=="running")return n.status="failed",n.error=u.reason||"Step rejected at approval gate",n.completedAt=new Date,n.duration=n.completedAt.getTime()-a.getTime(),await this.publishStepFailed(t,e,n.error),n;n.status="running"}let l,f=e.retry?.maxAttempts||1,S=e.retry?.backoffMs||1e3,A=e.retry?.backoffMultiplier||2;for(let u=1;u<=f;u++){n.retryCount=u-1;try{let w=e.timeout||this.config.defaultStepTimeout,m=await this.executeStepAction(e,c,r,w);o||this.mapStepOutput(e,m,r);let b;try{b=o?structuredClone(m):m}catch(h){throw new Error(`parallel_output_uncloneable: ${y(h)}`)}return n.status="completed",n.output=b,n.completedAt=new Date,n.duration=n.completedAt.getTime()-a.getTime(),o||t.stepResults.set(e.id,n),await this.publishStepCompleted(t,e,n),n}catch(w){if(l=M(w),l.message.startsWith("parallel_output_uncloneable:"))break;u<f&&(await this.delay(S),S*=A)}}return n.status="failed",n.error=l?.message||"Unknown error",n.completedAt=new Date,n.duration=n.completedAt.getTime()-a.getTime(),o||t.stepResults.set(e.id,n),e.rollback&&await this.executeRollback(e.rollback,r),await this.publishStepFailed(t,e,n.error),n}catch(c){return n.status="failed",n.error=y(c),n.completedAt=new Date,n.duration=n.completedAt.getTime()-a.getTime(),o||t.stepResults.set(e.id,n),await this.publishStepFailed(t,e,n.error),n}}async executeStepAction(e,t,i,r){let o=new Promise((c,l)=>{setTimeout(()=>l(new Error(`Step timeout after ${r}ms`)),r)}),a=B(e.domain,e.action);if(a){let c=await Promise.race([a.execute(t,i),o]);if(!c.success)throw c.error;return c.value}let n=this.actionRegistry[e.domain];if(n?.[e.action]){let c=await Promise.race([n[e.action](t,i),o]);if(!c.success)throw c.error;return c.value}throw new Error(`Action '${e.action}' not registered for domain '${e.domain}'. Register it using orchestrator.registerAction('${e.domain}', '${e.action}', handler)`)}async executeRollback(e,t){try{let i=this.actionRegistry[e.domain];if(!i?.[e.action]){console.warn(`Rollback action '${e.action}' not registered for domain '${e.domain}'. Skipping rollback.`);return}let r=await i[e.action](e.input||{},t);r.success||console.error(`Rollback failed for ${e.domain}.${e.action}:`,r.error)}catch(i){console.error(`Rollback failed for ${e.domain}.${e.action}:`,i)}}buildStepInput(e,t){let i={};if(e.inputMapping)for(let[r,o]of Object.entries(e.inputMapping)){let a=this.getValueByPath(t,o);a!==void 0&&(i[r]=a)}return i}mapStepOutput(e,t,i){if(Object.defineProperty(i.results,e.id,{value:t,writable:!0,enumerable:!0,configurable:!0}),e.outputMapping&&typeof t=="object"&&t!==null)for(let[r,o]of Object.entries(e.outputMapping)){let a=this.getValueByPath(t,r);a!==void 0&&this.setValueByPath(i.results,o,a)}}getValueByPath(e,t){let i=t.split("."),r=e;for(let o of i){if(r==null)return;if(typeof r=="object")r=r[o];else return}return r}setValueByPath(e,t,i){let r=t.split("."),o=new Set(["__proto__","constructor","prototype"]);for(let c of r)if(o.has(c))throw new Error("Invalid path: contains dangerous prototype key");let a=e;for(let c=0;c<r.length-1;c++){let l=r[c];Object.hasOwn(a,l)||Object.defineProperty(a,l,{value:Object.create(null),writable:!0,enumerable:!0,configurable:!0}),a=a[l]}let n=r[r.length-1];Object.defineProperty(a,n,{value:i,writable:!0,enumerable:!0,configurable:!0})}evaluateCondition(e,t){let i=this.getValueByPath(t,e.path);switch(e.operator){case"eq":return i===e.value;case"neq":return i!==e.value;case"gt":return typeof i=="number"&&i>e.value;case"gte":return typeof i=="number"&&i>=e.value;case"lt":return typeof i=="number"&&i<e.value;case"lte":return typeof i=="number"&&i<=e.value;case"contains":return Array.isArray(i)?i.includes(e.value):typeof i=="string"?i.includes(String(e.value)):!1;case"exists":return i!=null;default:return!1}}async publishEvent(e,t,i){let r=$(e,"learning-optimization",t,i);await this.eventBus.publish(r)}async publishWorkflowStarted(e,t){await this.publishEvent(v.WorkflowStarted,{executionId:e.executionId,workflowId:e.workflowId,workflowName:e.workflowName,stepCount:t.steps.length},e.context.metadata.correlationId)}async publishWorkflowCompleted(e){await this.publishEvent(v.WorkflowCompleted,{executionId:e.executionId,workflowId:e.workflowId,workflowName:e.workflowName,duration:e.duration||0,completedSteps:e.completedSteps.length,skippedSteps:e.skippedSteps.length},e.context.metadata.correlationId)}async publishWorkflowFailed(e,t,i){await this.publishEvent(v.WorkflowFailed,{executionId:e.executionId,workflowId:e.workflowId,workflowName:e.workflowName,failedStep:t,error:i},e.context.metadata.correlationId)}async publishStepStarted(e,t){await this.publishEvent(v.StepStarted,{executionId:e.executionId,workflowId:e.workflowId,stepId:t.id,stepName:t.name,domain:t.domain},e.context.metadata.correlationId)}async publishStepCompleted(e,t,i){await this.publishEvent(v.StepCompleted,{executionId:e.executionId,workflowId:e.workflowId,stepId:t.id,stepName:t.name,domain:t.domain,duration:i.duration},e.context.metadata.correlationId)}async publishStepFailed(e,t,i){await this.publishEvent(v.StepFailed,{executionId:e.executionId,workflowId:e.workflowId,stepId:t.id,stepName:t.name,domain:t.domain,error:i},e.context.metadata.correlationId)}async publishStepSkipped(e,t){await this.publishEvent(v.StepSkipped,{executionId:e.executionId,workflowId:e.workflowId,stepId:t.id,stepName:t.name,domain:t.domain},e.context.metadata.correlationId)}validateWorkflowDefinition(e){if(!e.id)return d(new Error("Workflow ID is required"));if(!e.name)return d(new Error("Workflow name is required"));if(!e.steps||e.steps.length===0)return d(new Error("Workflow must have at least one step"));let t=new Set;for(let r of e.steps){if(!r.id)return d(new Error("Step ID is required"));if(t.has(r.id))return d(new Error(`Duplicate step ID: ${r.id}`));if(t.add(r.id),!r.domain)return d(new Error(`Step ${r.id} must have a domain`));if(!N.includes(r.domain))return d(new Error(`Invalid domain for step ${r.id}: ${r.domain}`));if(!r.action)return d(new Error(`Step ${r.id} must have an action`));if(r.approval&&typeof r.approval=="object"){let{expiresAfter:o,autoApproveAfter:a}=r.approval;if(o!==void 0&&a!==void 0)return d(new Error(`Step ${r.id} sets both approval expiry fields`));let n=o??a;if(n!==void 0&&(!Number.isSafeInteger(n)||n<0||n>2147483647))return d(new Error(`Step ${r.id} has an invalid approval expiry`))}if(r.dependsOn){for(let o of r.dependsOn)if(!e.steps.some(a=>a.id===o))return d(new Error(`Step ${r.id} depends on unknown step: ${o}`))}}let i=this.detectCircularDependencies(e.steps);return i?d(new Error(`Circular dependency detected: ${i}`)):k(void 0)}detectCircularDependencies(e){let t=new Set,i=new Set,r=(o,a)=>{if(i.has(o))return[...a,o].join(" -> ");if(t.has(o))return null;t.add(o),i.add(o);let n=e.find(c=>c.id===o);if(n?.dependsOn)for(let c of n.dependsOn){let l=r(c,[...a,o]);if(l)return l}return i.delete(o),null};for(let o of e){let a=r(o.id,[]);if(a)return a}return null}setupEventTriggers(){let e=this.eventBus.subscribe("*",async t=>{await this.handleEventForTriggers(t)});this.eventSubscriptions.push(e)}registerWorkflowTriggers(e){}async handleEventForTriggers(e){for(let t of this.workflows.values())if(t.triggers)for(let i of t.triggers){if(i.eventType!==e.type||i.sourceDomain&&i.sourceDomain!==e.source)continue;if(i.condition){let o={input:{event:e.payload},results:{},metadata:{executionId:"",workflowId:t.id,startedAt:new Date}};if(!this.evaluateCondition(i.condition,o))continue}let r={};if(i.inputMapping)for(let[o,a]of Object.entries(i.inputMapping)){let n=this.getValueByPath({event:e.payload},a);n!==void 0&&(r[o]=n)}else r.triggerEvent=e.payload;await this.executeWorkflow(t.id,r,e.correlationId)}}registerBuiltInWorkflows(){let e=z();for(let t of e)this.registerWorkflow(t)}async loadPersistedWorkflows(){try{let e=await this.memory.search("workflow:definition:*",100);for(let t of e){let i=await this.memory.get(t);i&&!this.workflows.has(i.id)&&this.workflows.set(i.id,i)}}catch(e){console.error("Failed to load persisted workflows:",e)}}async persistWorkflows(){try{for(let e of this.workflows.values())G.includes(e.id)||await this.memory.set(`workflow:definition:${e.id}`,e,{namespace:"coordination",persist:!0})}catch(e){console.error("Failed to persist workflows:",e)}}async persistExecution(e){try{let t={...e,stepResults:Object.fromEntries(e.stepResults)};await this.memory.set(`workflow:execution:${e.executionId}`,t,{namespace:"coordination",ttl:86400*7})}catch(t){console.error("Failed to persist execution:",t)}}closeApprovalGates(e,t){for(let[i,r]of this.approvalGates.entries())i.startsWith(`${e}:`)&&r.resolve({approved:!1,reason:t})}async waitForApproval(e,t){if(t.status!=="running")return{approved:!1,reason:`Workflow is ${t.status}`};let i=typeof e.approval=="object"?e.approval:{},r=i.expiresAfter??i.autoApproveAfter??3e5,o=i.message??`Awaiting approval for step: ${e.name}`;if(!Number.isSafeInteger(r)||r<0||r>2147483647)return{approved:!1,reason:"Invalid approval expiry"};let a=`${t.executionId}:${e.id}`,n,c=new Promise(l=>{let f={resolve:S=>{this.approvalGates.get(a)===f&&(this.approvalGates.delete(a),n&&clearTimeout(n),l(S))}};this.approvalGates.set(a,f),r>0&&(n=setTimeout(()=>{f.resolve({approved:!1,reason:"Approval expired"})},r))});try{await this.publishEvent(v.StepAwaitingApproval,{executionId:t.executionId,workflowId:t.workflowId,stepId:e.id,stepName:e.name,domain:e.domain,message:o,expiresAfter:r>0?r:void 0},t.context.metadata.correlationId)}catch(l){throw this.approvalGates.get(a)?.resolve({approved:!1,reason:"Approval event failed"}),l}return c}delay(e){return new Promise(t=>setTimeout(t,e))}};function Re(s,e,t,i){return new _(s,e,t,i)}export{v as a,T as b,O as c,_ as d,Re as e};
|