agentic-qe 3.9.2 → 3.9.4
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/CHANGELOG.md +53 -0
- package/dist/cli/bundle.js +5 -5
- package/dist/cli/chunks/adapter-5ODIX6ZG.js +2 -0
- package/dist/cli/chunks/{agent-booster-wasm-AKAOHSCX.js → agent-booster-wasm-MGGEPROV.js} +2 -2
- package/dist/cli/chunks/{agent-handler-MTGPOUVP.js → agent-handler-AFHYFQXV.js} +2 -2
- package/dist/cli/chunks/{agent-memory-branch-UFPKWUFK.js → agent-memory-branch-SQ3KDIG6.js} +2 -2
- package/dist/cli/chunks/aqe-learning-engine-PWGRS6KK.js +2 -0
- package/dist/cli/chunks/{audit-VBEZHNHO.js → audit-SM5CK2K5.js} +2 -2
- package/dist/cli/chunks/base-TJGIYR7L.js +2 -0
- package/dist/cli/chunks/{better-sqlite3-IRPHIXRU.js → better-sqlite3-UGOYRNXI.js} +2 -2
- package/dist/cli/chunks/{brain-handler-7EO3FFRZ.js → brain-handler-SKXTB63O.js} +3 -3
- package/dist/cli/chunks/{branch-enumerator-MZRGP35N.js → branch-enumerator-77NSOLNK.js} +2 -2
- package/dist/cli/chunks/{browser-VSIWQE7J.js → browser-MCE5DWPV.js} +2 -2
- package/dist/cli/chunks/browser-workflow-GUR7RLFP.js +2 -0
- package/dist/cli/chunks/{chunk-5RL66XSH.js → chunk-27FNBMUC.js} +2 -2
- package/dist/cli/chunks/{chunk-FRJLP7IB.js → chunk-27P4VTCY.js} +2 -2
- package/dist/cli/chunks/{chunk-2VVV73PW.js → chunk-2JLKOGNU.js} +1 -1
- package/dist/cli/chunks/{chunk-PJFLO37I.js → chunk-2MQMXI7C.js} +2 -2
- package/dist/cli/chunks/{chunk-BKCTNRC5.js → chunk-3MN7E6HY.js} +2 -2
- package/dist/cli/chunks/{chunk-BY47GV4T.js → chunk-3MRFR534.js} +2 -2
- package/dist/cli/chunks/{chunk-563PJBDM.js → chunk-3RHIPCBG.js} +2 -2
- package/dist/cli/chunks/{chunk-WXWY2GAF.js → chunk-3SPYUOSS.js} +2 -2
- package/dist/cli/chunks/{chunk-5AUKULWO.js → chunk-4BQTEPAD.js} +2 -2
- package/dist/cli/chunks/{chunk-N3F3CX4V.js → chunk-4GJAYXB7.js} +2 -2
- package/dist/cli/chunks/{chunk-7NOIIC7G.js → chunk-4TZTGYBQ.js} +1 -1
- package/dist/cli/chunks/{chunk-VL7YOOC2.js → chunk-53M65YFH.js} +2 -2
- package/dist/cli/chunks/{chunk-QNBQBSAI.js → chunk-54OLXGXJ.js} +2 -2
- package/dist/cli/chunks/{chunk-HW4ISY5B.js → chunk-5UKAEBKC.js} +3 -3
- package/dist/cli/chunks/{chunk-CQP7ZFME.js → chunk-72EC26AS.js} +2 -2
- package/dist/cli/chunks/{chunk-J4BS6IWE.js → chunk-7EL65Y27.js} +1 -1
- package/dist/cli/chunks/{chunk-PFNFC43Q.js → chunk-7FJIIB4H.js} +1 -1
- package/dist/cli/chunks/{chunk-AKSJQ6B3.js → chunk-7ST2YENJ.js} +2 -2
- package/dist/cli/chunks/{chunk-SNVM4YJS.js → chunk-7ZXNJT4Q.js} +2 -2
- package/dist/cli/chunks/{chunk-BOH22AKC.js → chunk-A6ZBQCYB.js} +2 -2
- package/dist/cli/chunks/{chunk-VHVWAXCF.js → chunk-B252DDC5.js} +1 -1
- package/dist/cli/chunks/{chunk-2EC5Z2J4.js → chunk-B6HLXE3D.js} +9 -9
- package/dist/cli/chunks/{chunk-L5WZUPZF.js → chunk-BH5XPYA3.js} +2 -2
- package/dist/cli/chunks/{chunk-LMMEUVE5.js → chunk-BZ22GI4E.js} +1 -1
- package/dist/cli/chunks/{chunk-YXCU4CJX.js → chunk-C2HGOUEB.js} +1 -1
- package/dist/cli/chunks/{chunk-JV7LX6OT.js → chunk-C3BXT3ZC.js} +4 -4
- package/dist/cli/chunks/{chunk-3GZKAORV.js → chunk-C567IO5M.js} +2 -2
- package/dist/cli/chunks/{chunk-SCF7NRVE.js → chunk-COIRFVFO.js} +1 -1
- package/dist/cli/chunks/{chunk-RITN3XR4.js → chunk-DHJJJ24V.js} +2 -2
- package/dist/cli/chunks/{chunk-RC5CPXON.js → chunk-DLMEBVLF.js} +2 -2
- package/dist/cli/chunks/{chunk-XFMKJ3UD.js → chunk-DZHGYZJP.js} +1 -1
- package/dist/cli/chunks/{chunk-V6XBAZNH.js → chunk-EEARIB4C.js} +1 -1
- package/dist/cli/chunks/{chunk-NM6TIEJ3.js → chunk-EFD2J6GG.js} +3 -3
- package/dist/cli/chunks/{chunk-Z5HXGVXZ.js → chunk-EHGTXIT7.js} +1 -1
- package/dist/cli/chunks/{chunk-QODE4LM6.js → chunk-ENKPW6MA.js} +2 -2
- package/dist/cli/chunks/{chunk-4PKXIBX2.js → chunk-EZTUUOVI.js} +1 -1
- package/dist/cli/chunks/{chunk-SDTVHR63.js → chunk-F6AU2MAZ.js} +2 -2
- package/dist/cli/chunks/{chunk-GK72GUHA.js → chunk-G6RTCJFY.js} +2 -2
- package/dist/cli/chunks/{chunk-E25S5E2D.js → chunk-G72E5DL3.js} +1 -1
- package/dist/cli/chunks/{chunk-FUIHWBVF.js → chunk-GAG2P4I2.js} +1 -1
- package/dist/cli/chunks/{chunk-KDDZYXP4.js → chunk-GQ7DCSKS.js} +2 -2
- package/dist/cli/chunks/{chunk-WG4GHAML.js → chunk-GSKZL36U.js} +2 -2
- package/dist/cli/chunks/{chunk-Z2IKNC5M.js → chunk-GT35EJKR.js} +1 -1
- package/dist/cli/chunks/{chunk-56IWS2KY.js → chunk-GVFHRHXC.js} +2 -2
- package/dist/cli/chunks/{chunk-CCYMJKWX.js → chunk-GX7MEHQ2.js} +1 -1
- package/dist/cli/chunks/{chunk-4UH25U4O.js → chunk-HKTNFHWI.js} +1 -1
- package/dist/cli/chunks/{chunk-X6LCMOGC.js → chunk-IGJ472XJ.js} +2 -2
- package/dist/cli/chunks/{chunk-XH53ARZD.js → chunk-IQE6GOH6.js} +2 -2
- package/dist/cli/chunks/{chunk-RJROC5M3.js → chunk-J222JLZ6.js} +2 -2
- package/dist/cli/chunks/{chunk-DSE57A5N.js → chunk-J6KBI5NW.js} +1 -1
- package/dist/cli/chunks/{chunk-CQBSGYRA.js → chunk-J72Q6ERO.js} +2 -2
- package/dist/cli/chunks/{chunk-ICDXWIFZ.js → chunk-JMBUIVVE.js} +1 -1
- package/dist/cli/chunks/{chunk-6SOJVEU7.js → chunk-JVUNZBKX.js} +2 -2
- package/dist/cli/chunks/{chunk-MN742FIH.js → chunk-KELYPHMV.js} +2 -2
- package/dist/cli/chunks/{chunk-DHE66JRR.js → chunk-KSMQH2CV.js} +1 -1
- package/dist/cli/chunks/{chunk-GPLERTZU.js → chunk-LH3ZL2OK.js} +2 -2
- package/dist/cli/chunks/{chunk-GITD7SRQ.js → chunk-LW3DV23G.js} +2 -2
- package/dist/cli/chunks/chunk-MDFXPCBO.js +2 -0
- package/dist/cli/chunks/{chunk-KZUJBZ7B.js → chunk-MGRE767N.js} +2 -2
- package/dist/cli/chunks/{chunk-DBE34QES.js → chunk-MN2MYLVW.js} +2 -2
- package/dist/cli/chunks/{chunk-25LFUL2K.js → chunk-MR5I6UR2.js} +2 -2
- package/dist/cli/chunks/{chunk-S3RDH5CI.js → chunk-MS6LTE4L.js} +2 -2
- package/dist/cli/chunks/{chunk-QEQTC4WQ.js → chunk-MUX762XZ.js} +2 -2
- package/dist/cli/chunks/{chunk-4Z27TRQF.js → chunk-NEYZXYFH.js} +2 -2
- package/dist/cli/chunks/{chunk-7SLN2JGP.js → chunk-NRH2QE4X.js} +3 -3
- package/dist/cli/chunks/{chunk-CL3K5EJK.js → chunk-NS4CCCTZ.js} +2 -2
- package/dist/cli/chunks/{chunk-NJY7ZA77.js → chunk-NZ5LY2BT.js} +1 -1
- package/dist/cli/chunks/{chunk-UKDOMLBI.js → chunk-O6QAOPUA.js} +3 -3
- package/dist/cli/chunks/{chunk-QPRVX4H2.js → chunk-OHZ6RJLS.js} +2 -2
- package/dist/cli/chunks/{chunk-DNLMZTE2.js → chunk-ONOYANDX.js} +1 -1
- package/dist/cli/chunks/chunk-OZC42UMD.js +2 -0
- package/dist/cli/chunks/{chunk-34U7JDCN.js → chunk-P3EOWBME.js} +2 -2
- package/dist/cli/chunks/{chunk-4DAOZQ3V.js → chunk-Q2ZYUIS2.js} +2 -2
- package/dist/cli/chunks/{chunk-RQGYJK7H.js → chunk-Q6FSXNQP.js} +2 -2
- package/dist/cli/chunks/{chunk-X35GP7TR.js → chunk-QEYPK7KS.js} +1 -1
- package/dist/cli/chunks/{chunk-T5GV6UIO.js → chunk-QOU4R6AF.js} +2 -2
- package/dist/cli/chunks/{chunk-KZTO5EVM.js → chunk-QPC4STR6.js} +2 -2
- package/dist/cli/chunks/{chunk-4FT3PND7.js → chunk-QVZSIFSJ.js} +3 -3
- package/dist/cli/chunks/{chunk-GCMVJS5X.js → chunk-RAZ2PGZD.js} +2 -2
- package/dist/cli/chunks/{chunk-727BDQ3K.js → chunk-RE6XD6RI.js} +2 -2
- package/dist/cli/chunks/{chunk-STE42EMB.js → chunk-RGRYL4MG.js} +2 -2
- package/dist/cli/chunks/{chunk-XYJL6DKI.js → chunk-RN3SN4ZC.js} +2 -2
- package/dist/cli/chunks/{chunk-JOVINE23.js → chunk-RPYUKEAH.js} +2 -2
- package/dist/cli/chunks/{chunk-5L6AU3QK.js → chunk-RRQEIGLS.js} +2 -2
- package/dist/cli/chunks/{chunk-VUAO4VFC.js → chunk-RS7ZGWHV.js} +2 -2
- package/dist/cli/chunks/{chunk-KTYUCZEM.js → chunk-RTC3ZCPK.js} +5 -5
- package/dist/cli/chunks/{chunk-4LA7IW3V.js → chunk-RUJU5XEQ.js} +1 -1
- package/dist/cli/chunks/{chunk-SRRFWTNF.js → chunk-SHJZ3YNX.js} +2 -2
- package/dist/cli/chunks/{chunk-FAXVVLPL.js → chunk-SKWI5QBM.js} +2 -2
- package/dist/cli/chunks/{chunk-NRCKGXJJ.js → chunk-TNWTQWLL.js} +1 -1
- package/dist/cli/chunks/{chunk-KBA7FBK3.js → chunk-TT2TB6UF.js} +3 -3
- package/dist/cli/chunks/{chunk-Z54EO6E6.js → chunk-U7YC7VCM.js} +2 -2
- package/dist/cli/chunks/{chunk-TKF447CW.js → chunk-UJLSCJJS.js} +1 -1
- package/dist/cli/chunks/{chunk-MY4LMIG7.js → chunk-UPJZRDZK.js} +2 -2
- package/dist/cli/chunks/{chunk-KQTJ2YLI.js → chunk-UUL3D5HR.js} +4 -4
- package/dist/cli/chunks/{chunk-TTOE336G.js → chunk-V57PXZIK.js} +3 -3
- package/dist/cli/chunks/{chunk-SGAW2WLI.js → chunk-VBXJBXMG.js} +4 -4
- package/dist/cli/chunks/{chunk-BIVIPF4O.js → chunk-VBYREHZI.js} +1 -1
- package/dist/cli/chunks/{chunk-PNL5G6TE.js → chunk-VFXTZWNF.js} +2 -2
- package/dist/cli/chunks/{chunk-2WBCYSUN.js → chunk-VSNPI2NO.js} +8 -8
- package/dist/cli/chunks/{chunk-Y6O7CDLI.js → chunk-WHT46PJM.js} +2 -2
- package/dist/cli/chunks/{chunk-L5YEPSDU.js → chunk-XB5HXTL4.js} +2 -2
- package/dist/cli/chunks/{chunk-4FMHBBG5.js → chunk-XYVMKCSI.js} +1 -1
- package/dist/cli/chunks/{chunk-AA33R5U4.js → chunk-YDJKQKQH.js} +2 -2
- package/dist/cli/chunks/{chunk-4D2ZG2QO.js → chunk-YS6C2Q4F.js} +1 -1
- package/dist/cli/chunks/{chunk-65M7C6SH.js → chunk-Z75DMTMI.js} +1 -1
- package/dist/cli/chunks/{chunk-Q4A72ZTV.js → chunk-ZKWNZ3ZK.js} +2 -2
- package/dist/cli/chunks/{chunk-2Z2TFEOL.js → chunk-ZODUKKPC.js} +2 -2
- package/dist/cli/chunks/{chunk-KNVAAVHH.js → chunk-ZQSEPDIJ.js} +2 -2
- package/dist/cli/chunks/{chunk-QIH3E775.js → chunk-ZW5DRPZY.js} +2 -2
- package/dist/cli/chunks/{ci-2BCOBWFG.js → ci-THZEECIQ.js} +2 -2
- package/dist/cli/chunks/{ci-output-FB4OJHAC.js → ci-output-G6QLGL4S.js} +2 -2
- package/dist/cli/chunks/{claude-flow-setup-NEEFZTMB.js → claude-flow-setup-5MTYQM34.js} +2 -2
- package/dist/cli/chunks/client-IFMC3AYQ.js +2 -0
- package/dist/cli/chunks/{cline-installer-ODO2PS4K.js → cline-installer-E2LF2DQS.js} +2 -2
- package/dist/cli/chunks/{code-NSOF62VE.js → code-QRF7ZGXG.js} +2 -2
- package/dist/cli/chunks/{code-index-extractor-YQL5XN52.js → code-index-extractor-II6IRWU6.js} +2 -2
- package/dist/cli/chunks/{codex-installer-SPEY6VYT.js → codex-installer-LGOQ23ZS.js} +2 -2
- package/dist/cli/chunks/{completions-OWKBUMBE.js → completions-LB2RR2OQ.js} +2 -2
- package/dist/cli/chunks/{complexity-analyzer-PGTXKP73.js → complexity-analyzer-PUIPIRX3.js} +2 -2
- package/dist/cli/chunks/{continuedev-installer-KGOXAC7L.js → continuedev-installer-HQAEAQZU.js} +2 -2
- package/dist/cli/chunks/{copilot-installer-BF3UA3TG.js → copilot-installer-3PKCX5K5.js} +2 -2
- package/dist/cli/chunks/{cost-tracker-2HDJ66E2.js → cost-tracker-JG3SZ2Q3.js} +2 -2
- package/dist/cli/chunks/{coverage-KPA2PHIN.js → coverage-D3PZTOKT.js} +3 -3
- package/dist/cli/chunks/cross-domain-router-2LPBUUWY.js +2 -0
- package/dist/cli/chunks/{cursor-installer-7CDZFHTV.js → cursor-installer-UY6GWKTO.js} +2 -2
- package/dist/cli/chunks/{daemon-4BPGCKDJ.js → daemon-UNO3LRRN.js} +3 -3
- package/dist/cli/chunks/{dag-attention-scheduler-2MAVGSBB.js → dag-attention-scheduler-S2MXANYL.js} +2 -2
- package/dist/cli/chunks/{detect-WRPWTGP5.js → detect-DU2FTRKR.js} +2 -2
- package/dist/cli/chunks/{domain-handler-JZVSJ7AG.js → domain-handler-KPNO36LF.js} +2 -2
- package/dist/cli/chunks/{domain-transfer-XGIZOR2X.js → domain-transfer-6X3ZZF6A.js} +2 -2
- package/dist/cli/chunks/dream-NGRDMOTE.js +2 -0
- package/dist/cli/chunks/esm-node-3COTOSO3.js +2 -0
- package/dist/cli/chunks/{eval-T7YPAS4G.js → eval-6RXEDTBZ.js} +2 -2
- package/dist/cli/chunks/{fast-paths-QECJTKCQ.js → fast-paths-FYODFGZB.js} +2 -2
- package/dist/cli/chunks/{feature-flags-LIFURSFZ.js → feature-flags-YOULURDA.js} +2 -2
- package/dist/cli/chunks/{feature-flags-R4QZYTIW.js → feature-flags-ZJ42B4IL.js} +2 -2
- package/dist/cli/chunks/{file-discovery-4W3K3W4C.js → file-discovery-KOL7FSBQ.js} +2 -2
- package/dist/cli/chunks/{fleet-NLLQWCI5.js → fleet-22I74LGD.js} +3 -3
- package/dist/cli/chunks/{gnn-wrapper-XEII72LN.js → gnn-wrapper-DFHTHLIZ.js} +2 -2
- package/dist/cli/chunks/{heartbeat-handler-DJ65RE5D.js → heartbeat-handler-SQ6VYEAA.js} +4 -4
- package/dist/cli/chunks/{heartbeat-scheduler-H664265Q.js → heartbeat-scheduler-W6PQJ5SG.js} +2 -2
- package/dist/cli/chunks/hnsw-adapter-BASJNTEV.js +2 -0
- package/dist/cli/chunks/hnsw-index-NFN2AUIX.js +2 -0
- package/dist/cli/chunks/{hnsw-legacy-bridge-SQIDTWAA.js → hnsw-legacy-bridge-AYTRT54U.js} +2 -2
- package/dist/cli/chunks/{hnswlib-node-WICYCU5U.js → hnswlib-node-4IA56UH4.js} +2 -2
- package/dist/cli/chunks/{hooks-GZUHUD63.js → hooks-T6UMR72X.js} +6 -6
- package/dist/cli/chunks/{hypergraph-engine-MLCDZ6BL.js → hypergraph-engine-WVPYKMFY.js} +2 -2
- package/dist/cli/chunks/{hypergraph-handler-NNDDI4R3.js → hypergraph-handler-NB6GL4CR.js} +3 -3
- package/dist/cli/chunks/impact-analyzer-ZMQXHQDV.js +2 -0
- package/dist/cli/chunks/init-handler-UOFNBXEP.js +68 -0
- package/dist/cli/chunks/init-wizard-QHAA4GWF.js +2 -0
- package/dist/cli/chunks/kernel-SNJFYN3T.js +2 -0
- package/dist/cli/chunks/{kilocode-installer-EPZFFPFE.js → kilocode-installer-VWMNI4QX.js} +2 -2
- package/dist/cli/chunks/{kiro-installer-5VACG3HU.js → kiro-installer-RNM47FV5.js} +15 -15
- package/dist/cli/chunks/knowledge-graph-EP5UTODP.js +2 -0
- package/dist/cli/chunks/{learning-6FITK6XY.js → learning-L4RB5XYP.js} +3 -3
- package/dist/cli/chunks/{llm-router-4DDC6AKJ.js → llm-router-BZYZL3YI.js} +2 -2
- package/dist/cli/chunks/{load-KGDNVUBX.js → load-4UGEGRMO.js} +2 -2
- package/dist/cli/chunks/load-test-KMMRHABK.js +2 -0
- package/dist/cli/chunks/mcp-FWWZIWCI.js +2 -0
- package/dist/cli/chunks/{memory-II4I4QMO.js → memory-5OXPMXU6.js} +5 -5
- package/dist/cli/chunks/memory-backend-Q5MWPMDE.js +2 -0
- package/dist/cli/chunks/{memory-handlers-TQXTOJGQ.js → memory-handlers-JS7BTWJK.js} +2 -2
- package/dist/cli/chunks/{opencode-installer-EU6JCWBW.js → opencode-installer-BS5TQKHB.js} +2 -2
- package/dist/cli/chunks/orchestrator-G6BUZ6QE.js +370 -0
- package/dist/cli/chunks/{pipeline-MPZJWYKK.js → pipeline-3MZ5COPR.js} +2 -2
- package/dist/cli/chunks/{platform-YH35ZZFZ.js → platform-TKD4JCUG.js} +2 -2
- package/dist/cli/chunks/{plugin-B7JYZFNQ.js → plugin-XXJ7R6SY.js} +2 -2
- package/dist/cli/chunks/{prime-radiant-advanced-wasm-KTUK6UE2.js → prime-radiant-advanced-wasm-JLJ6NKIP.js} +2 -2
- package/dist/cli/chunks/protocol-executor-ORFR4WJ3.js +2 -0
- package/dist/cli/chunks/{protocol-handler-3NXMVU34.js → protocol-handler-ZLYGQPHG.js} +2 -2
- package/dist/cli/chunks/{prove-H5LMGSUC.js → prove-E2WZ335X.js} +2 -2
- package/dist/cli/chunks/qe-reasoning-bank-PLTOH4SG.js +2 -0
- package/dist/cli/chunks/{quality-RCWHY6GO.js → quality-6MHHBINU.js} +2 -2
- package/dist/cli/chunks/queen-coordinator-L3TRAX7H.js +2 -0
- package/dist/cli/chunks/{real-embeddings-NKH4VURF.js → real-embeddings-QN5BY3WS.js} +2 -2
- package/dist/cli/chunks/{roocode-installer-SB7QJYM3.js → roocode-installer-GTVII272.js} +2 -2
- package/dist/cli/chunks/router-3PBJJLRQ.js +2 -0
- package/dist/cli/chunks/routing-feedback-Q775MZ3Z.js +2 -0
- package/dist/cli/chunks/{routing-handler-SY7GKG2W.js → routing-handler-HYKZ3ISS.js} +2 -2
- package/dist/cli/chunks/{ruvector-commands-HATTO3UQ.js → ruvector-commands-LBWHPUTZ.js} +2 -2
- package/dist/cli/chunks/{rvf-dual-writer-D57EXQUD.js → rvf-dual-writer-TVCJ2Y6N.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-adapter-OWDYN6KD.js → rvf-migration-adapter-34ITXLU3.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-coordinator-SIQVJB5S.js → rvf-migration-coordinator-SX2C7777.js} +2 -2
- package/dist/cli/chunks/rvf-native-adapter-HLY2652E.js +2 -0
- package/dist/cli/chunks/safe-db-CCKCBZ5I.js +2 -0
- package/dist/cli/chunks/schedule-WZ5VV55N.js +2 -0
- package/dist/cli/chunks/scheduler-6PIKLCH7.js +2 -0
- package/dist/cli/chunks/{security-DS3XLZWN.js → security-7A4EW77M.js} +3 -3
- package/dist/cli/chunks/shared-rvf-adapter-VCJNSACZ.js +2 -0
- package/dist/cli/chunks/{shared-rvf-dual-writer-YB7AH6XJ.js → shared-rvf-dual-writer-27L4R5WK.js} +2 -2
- package/dist/cli/chunks/sqlite-persistence-HMXYD56G.js +2 -0
- package/dist/cli/chunks/{status-handler-TUYHE4FT.js → status-handler-JN6PRYLD.js} +2 -2
- package/dist/cli/chunks/{structural-health-XNGBNRRD.js → structural-health-JSY3DY7H.js} +2 -2
- package/dist/cli/chunks/{sync-K6CIRKBB.js → sync-ET3LYW2V.js} +10 -10
- package/dist/cli/chunks/{task-handler-7PJY67DR.js → task-handler-R24MR74L.js} +2 -2
- package/dist/cli/chunks/{task-handlers-WB5CDWUR.js → task-handlers-YNPEEPPZ.js} +2 -2
- package/dist/cli/chunks/{test-WV5ALEBB.js → test-7BZXFZCT.js} +4 -4
- package/dist/cli/chunks/{test-scheduling-N55ZGGA2.js → test-scheduling-EVIFD5EY.js} +3 -3
- package/dist/cli/chunks/{token-bootstrap-SINWHAKR.js → token-bootstrap-QYYQRXM5.js} +2 -2
- package/dist/cli/chunks/{token-usage-R7TGEVGL.js → token-usage-H4OZA77I.js} +2 -2
- package/dist/cli/chunks/{transformers-6DBLXPV7.js → transformers-ILQFO5HZ.js} +2 -2
- package/dist/cli/chunks/{tree-sitter-wasm-parser-7C7FKMQW.js → tree-sitter-wasm-parser-KTST5NWH.js} +2 -2
- package/dist/cli/chunks/{types-VNPMOKQT.js → types-4Z7XELU6.js} +2 -2
- package/dist/cli/chunks/unified-memory-RBHCTAWW.js +2 -0
- package/dist/cli/chunks/unified-memory-hnsw-UBF5PT6D.js +2 -0
- package/dist/cli/chunks/unified-persistence-ZIJDP6GW.js +2 -0
- package/dist/cli/chunks/{validate-53MNIRAF.js → validate-GSQCH6VN.js} +2 -2
- package/dist/cli/chunks/{validate-swarm-ZY4RGUFO.js → validate-swarm-SP2RPOYD.js} +2 -2
- package/dist/cli/chunks/{vibium-PBADBIV6.js → vibium-2SGOFYTF.js} +2 -2
- package/dist/cli/chunks/visual-security-WKIWOUTH.js +2 -0
- package/dist/cli/chunks/{web-tree-sitter-O7VI6RLB.js → web-tree-sitter-QSQ27UTH.js} +2 -2
- package/dist/cli/chunks/{windsurf-installer-HV3C3TAD.js → windsurf-installer-NIEH46E2.js} +2 -2
- package/dist/cli/chunks/witness-chain-4BRX3GGH.js +2 -0
- package/dist/cli/chunks/{witness-chain-4WIMYP4X.js → witness-chain-62GJTCT5.js} +2 -2
- package/dist/cli/chunks/{workflow-5RVAQ4TM.js → workflow-WZMV2MGW.js} +4 -4
- package/dist/cli/chunks/workflow-orchestrator-G6VU7QZ4.js +2 -0
- package/dist/cli/chunks/{wrappers-RRHCCA3E.js → wrappers-LNTV533I.js} +2 -2
- package/dist/cli/commands/init.js +2 -0
- package/dist/cli/commands/mcp.js +27 -17
- package/dist/cli/commands/sync.js +25 -8
- package/dist/cli/handlers/init-handler.d.ts +1 -0
- package/dist/cli/handlers/init-handler.js +2 -0
- package/dist/init/governance-installer.js +46 -14
- package/dist/init/kiro-installer.js +15 -2
- package/dist/init/orchestrator.js +1 -0
- package/dist/init/phases/06-code-intelligence.d.ts +46 -1
- package/dist/init/phases/06-code-intelligence.js +164 -10
- package/dist/init/phases/10-workers.d.ts +0 -14
- package/dist/init/phases/10-workers.js +19 -164
- package/dist/init/phases/phase-interface.d.ts +9 -0
- package/dist/kernel/hnsw-adapter.d.ts +14 -0
- package/dist/kernel/hnsw-adapter.js +25 -1
- package/dist/kernel/hnsw-index-provider.d.ts +16 -0
- package/dist/kernel/native-hnsw-backend.d.ts +11 -0
- package/dist/kernel/native-hnsw-backend.js +20 -0
- package/dist/kernel/progressive-hnsw-backend.d.ts +9 -0
- package/dist/kernel/progressive-hnsw-backend.js +41 -12
- package/dist/kernel/unified-memory.js +10 -0
- package/dist/mcp/bundle.js +216 -216
- package/dist/optimization/token-optimizer-service.d.ts +31 -2
- package/dist/optimization/token-optimizer-service.js +85 -23
- package/package.json +1 -1
- package/dist/cli/chunks/adapter-53WBPKXU.js +0 -2
- package/dist/cli/chunks/aqe-learning-engine-MV7NGY24.js +0 -2
- package/dist/cli/chunks/base-DZVGMQN2.js +0 -2
- package/dist/cli/chunks/browser-workflow-3J5YNMEI.js +0 -2
- package/dist/cli/chunks/chunk-LCAA6H4J.js +0 -2
- package/dist/cli/chunks/chunk-XIBVVZGB.js +0 -2
- package/dist/cli/chunks/client-EF555KYW.js +0 -2
- package/dist/cli/chunks/cross-domain-router-GXFNK5TS.js +0 -2
- package/dist/cli/chunks/dream-3IKF5XH4.js +0 -2
- package/dist/cli/chunks/esm-node-DHAE52OW.js +0 -2
- package/dist/cli/chunks/hnsw-adapter-DML5KXQR.js +0 -2
- package/dist/cli/chunks/hnsw-index-BUPPGVR6.js +0 -2
- package/dist/cli/chunks/impact-analyzer-DPTMJRYS.js +0 -2
- package/dist/cli/chunks/init-handler-IJ6BHE6A.js +0 -68
- package/dist/cli/chunks/init-wizard-35PUDJPW.js +0 -2
- package/dist/cli/chunks/kernel-2HZ44ZJ4.js +0 -2
- package/dist/cli/chunks/knowledge-graph-JL62G72U.js +0 -2
- package/dist/cli/chunks/load-test-LN245SSD.js +0 -2
- package/dist/cli/chunks/mcp-4LETGVIV.js +0 -2
- package/dist/cli/chunks/memory-backend-SVM7YRIE.js +0 -2
- package/dist/cli/chunks/orchestrator-YLMGJVSP.js +0 -371
- package/dist/cli/chunks/protocol-executor-IEN2XB4L.js +0 -2
- package/dist/cli/chunks/qe-reasoning-bank-Q3ZV3JRG.js +0 -2
- package/dist/cli/chunks/queen-coordinator-E6ON3JUR.js +0 -2
- package/dist/cli/chunks/router-WMC3LZ3C.js +0 -2
- package/dist/cli/chunks/routing-feedback-VKCZRCE3.js +0 -2
- package/dist/cli/chunks/rvf-native-adapter-C7NBH5UN.js +0 -2
- package/dist/cli/chunks/safe-db-5KLXCNXN.js +0 -2
- package/dist/cli/chunks/schedule-HAWWOXWB.js +0 -2
- package/dist/cli/chunks/scheduler-HTRDY5BC.js +0 -2
- package/dist/cli/chunks/shared-rvf-adapter-6I2Z5UGL.js +0 -2
- package/dist/cli/chunks/sqlite-persistence-WNNRGTGG.js +0 -2
- package/dist/cli/chunks/unified-memory-72SKVZ7Y.js +0 -2
- package/dist/cli/chunks/unified-memory-hnsw-TMN2L77W.js +0 -2
- package/dist/cli/chunks/unified-persistence-MDN3SRCR.js +0 -2
- package/dist/cli/chunks/visual-security-TRBCXPIB.js +0 -2
- package/dist/cli/chunks/witness-chain-JOI2YYGK.js +0 -2
- package/dist/cli/chunks/workflow-orchestrator-2NQ72S3C.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{b as ft}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.9.4");process.exit(0)}
|
|
2
|
+
import{b as ft}from"./chunk-TT2TB6UF.js";import{b as yt,c as vt}from"./chunk-J72Q6ERO.js";import{a as Se}from"./chunk-JMBUIVVE.js";import{a as ei}from"./chunk-3MN7E6HY.js";import{a as Zr,b as Y,c as B,e as wn}from"./chunk-RTC3ZCPK.js";import{a as Yr}from"./chunk-NEYZXYFH.js";import{a as Jr}from"./chunk-J6KBI5NW.js";import{a as En}from"./chunk-MGRE767N.js";import{a as Kr}from"./chunk-72EC26AS.js";import{a as Xr}from"./chunk-2MQMXI7C.js";import{b as Qr}from"./chunk-QOU4R6AF.js";import{a as Wr}from"./chunk-IQE6GOH6.js";import{d as Sn}from"./chunk-3SPYUOSS.js";import{a as Pr,b as Ar,c as kr,d as vn,e as Dr,f as _r,g as Or,h as ze,i as Fr,j as Nr,k as Lr,l as qr,m as Gr,n as zr,o as $r,p as Br,q as Ur,r as Hr,s as jr,t as Ce,u as Te}from"./chunk-VSNPI2NO.js";import{a as Cn,b as Tn}from"./chunk-5UKAEBKC.js";import{b as se}from"./chunk-EHGTXIT7.js";import{a as fe}from"./chunk-4TZTGYBQ.js";import{o as Vr}from"./chunk-C3BXT3ZC.js";import{a as ae,b as oe}from"./chunk-BH5XPYA3.js";import{g as ht}from"./chunk-NRH2QE4X.js";import{a as bn}from"./chunk-VBXJBXMG.js";import{b as F,f as x}from"./chunk-YDJKQKQH.js";import{a as Ir}from"./chunk-RAZ2PGZD.js";import{c as ie,g as Mr}from"./chunk-O6QAOPUA.js";import{b as gt}from"./chunk-3RHIPCBG.js";import{c as xr}from"./chunk-54OLXGXJ.js";import{k as $,o as ee}from"./chunk-G6RTCJFY.js";import{a as wr}from"./chunk-MDFXPCBO.js";import{c as dt,d as ye,e as yn}from"./chunk-RPYUKEAH.js";import{b as P,d as U}from"./chunk-4GJAYXB7.js";import{a as Er,b as I,c as q}from"./chunk-VBYREHZI.js";import{a as w,b as z,c as k}from"./chunk-F6AU2MAZ.js";import{f as L}from"./chunk-G72E5DL3.js";import{a as Rr,b as ws}from"./chunk-RN3SN4ZC.js";import{a as V,c as Z,d as ve}from"./chunk-P3EOWBME.js";import{a as mt}from"./chunk-Q2ZYUIS2.js";import{b as xs,c as Ps}from"./chunk-OZC42UMD.js";import{R as Rs,S as pt,b as be}from"./chunk-MN2MYLVW.js";import{a as Ts,c as Ss,e as Es,g as fn}from"./chunk-C2HGOUEB.js";var Ti={};Es(Ti,{DEFAULT_QEC_CONFIG:()=>bi,ReasoningQEC:()=>Nt,createReasoningQEC:()=>Ci,processReasoning:()=>Qa});async function Va(){return vi?yi!==null:(yi=null,vi=!0,!1)}function Ci(u){return new Nt(u)}function Qa(u,e){return Ci(e).process(u)}var Qn,bi,Ha,ja,yi,vi,Nt,Si=Ss(()=>{"use strict";yn();pt();Qn=ye("ReasoningQEC"),bi={minPaths:3,confidenceThreshold:.5,majorityThreshold:.5,useNativeBackend:!0,votingMethod:"weighted"},Ha={"test-generation":["specification-driven","boundary-analysis","mutation-testing"],"security-audit":["threat-modeling","attack-surface","defense-in-depth"],"defect-triage":["root-cause-analysis","impact-assessment","risk-prioritization"]},ja=["analytical","empirical","heuristic"],yi=null,vi=!1;Nt=class{config;nativeAvailable=!1;constructor(e={}){this.config={...bi,...e}}async initialize(){if(this.config.useNativeBackend){let e=be();(e.useQEFlashAttention||e.useQEGNNIndex)&&(this.nativeAvailable=await Va())}}generatePaths(e){let t=Math.max(this.config.minPaths,3),n=Ha[e.type]??ja,r=[];for(let i=0;i<t;i++){let s=n[i%n.length],a=this.generatePathSteps(e,i,s),o=this.deriveConclusion(a,s),l=this.calculatePathConfidence(a);r.push({id:i,steps:a,conclusion:o,confidence:l})}return Qn.debug(`Generated ${r.length} reasoning paths for problem type: ${e.type}`),r}extractSyndromes(e){if(e.length<2)return[];let t=[],n=Math.max(...e.map(i=>i.steps.length));for(let i=0;i<n;i++){let s=new Map;for(let l of e){let c=l.steps[i];if(!c)continue;let d=s.get(c.conclusion)??[];d.push(l.id),s.set(c.conclusion,d)}if(s.size<=1)continue;let a=[...s.entries()].map(([l,c])=>c.map(d=>({pathId:d,conclusion:l}))).flat(),o=this.classifySyndromeSeverity(s,e.length);t.push({stepIndex:i,disagreements:a,severity:o})}let r=new Map;for(let i of e){let s=r.get(i.conclusion)??[];s.push(i.id),r.set(i.conclusion,s)}if(r.size>1){let i=[...r.entries()].map(([a,o])=>o.map(l=>({pathId:l,conclusion:a}))).flat(),s=this.classifySyndromeSeverity(r,e.length);t.push({stepIndex:-1,disagreements:i,severity:s})}return Qn.debug(`Extracted ${t.length} syndromes: ${t.filter(i=>i.severity==="critical").length} critical, ${t.filter(i=>i.severity==="major").length} major, ${t.filter(i=>i.severity==="minor").length} minor`),t}correctErrors(e,t){if(e.length===0)return{steps:[],conclusion:"",confidence:0,corrections:[],syndromeCount:t.length};let n=new Set(t.filter(c=>c.stepIndex>=0).map(c=>c.stepIndex)),r=Math.max(...e.map(c=>c.steps.length)),i=[],s=[];for(let c=0;c<r;c++)if(n.has(c)){let{step:d,correction:m}=this.correctStep(e,c);i.push(d),m&&s.push(m)}else{let d=e[0].steps[c];d&&i.push({...d})}let a=this.correctConclusion(e),o=this.calculateCorrectedConfidence(e,t),l={steps:i,conclusion:a,confidence:o,corrections:s,syndromeCount:t.length};return Qn.debug(`Error correction applied: ${s.length} corrections, confidence: ${o.toFixed(3)}`),l}validate(e){let t=[];e.confidence<this.config.confidenceThreshold&&t.push({stepIndex:-1,type:"low-confidence",description:`Overall confidence ${e.confidence.toFixed(3)} is below threshold ${this.config.confidenceThreshold}`});for(let i of e.steps)i.evidence.length===0&&t.push({stepIndex:i.index,type:"inconsistent-evidence",description:`Step ${i.index} has no supporting evidence`});e.syndromeCount>0&&e.confidence<.3&&t.push({stepIndex:-1,type:"all-divergent",description:`${e.syndromeCount} syndromes with confidence ${e.confidence.toFixed(3)} suggests all paths diverged significantly`});for(let i of e.corrections)i.reason.includes("no clear majority")&&t.push({stepIndex:i.stepIndex,type:"no-majority",description:`Step ${i.stepIndex}: ${i.reason}`});let n=t.length===0,r=n?e.confidence:e.confidence*(1-t.length*.1);return{valid:n,confidence:Math.max(0,r),issues:t}}process(e){let t=this.generatePaths(e),n=this.extractSyndromes(t),r=this.correctErrors(t,n),i=this.validate(r);return{paths:t,syndromes:n,corrected:r,validation:i}}getConfig(){return{...this.config}}isNativeAvailable(){return this.nativeAvailable}generatePathSteps(e,t,n){return e.steps.map((r,i)=>{let s=this.generateStepConclusion(r,n,e.context,t),a=this.gatherEvidence(r,n,e.context);return{index:i,description:`[${n}] ${r}`,conclusion:s,evidence:a}})}generateStepConclusion(e,t,n,r){let i=Object.keys(n).sort(),s={0:l=>l.length>0?`Focused on ${l[0]}`:"Primary analysis",1:l=>l.length>1?`Focused on ${l[l.length-1]}`:"Secondary analysis",2:l=>l.length>0?`Cross-referencing ${l.join(" and ")}`:"Holistic analysis"},o=(s[r%3]??s[0])(i);return`[${t}] ${e}: ${o}`}gatherEvidence(e,t,n){let r=[];r.push(`Analysis via ${t}: ${e}`);for(let[i,s]of Object.entries(n))(typeof s=="string"||typeof s=="number"||typeof s=="boolean")&&r.push(`Context[${i}]: ${String(s)}`);return r}deriveConclusion(e,t){if(e.length===0)return`No conclusion (${t})`;let n=e[e.length-1];return`${t}: ${n.conclusion}`}calculatePathConfidence(e){if(e.length===0)return 0;let t=e.reduce((n,r)=>n+r.evidence.length,0)/e.length;return Math.min(1,.5+t*.1)}classifySyndromeSeverity(e,t){let n=Math.max(...[...e.values()].map(r=>r.length));return n>=Math.ceil(t*2/3)?"minor":n>=Math.ceil(t/2)?"major":"critical"}correctStep(e,t){let n=new Map,r=new Map,i=this.config.votingMethod==="weighted";for(let g of e){let h=g.steps[t];if(!h)continue;let f=n.get(h.conclusion)??0,v=i?g.confidence:1;n.set(h.conclusion,f+v),r.set(h.conclusion,h)}if(n.size===0)return{step:{index:t,description:`Step ${t} (no data)`,conclusion:"",evidence:[]},correction:null};let s=[...n.entries()].sort((g,h)=>h[1]-g[1]||g[0].localeCompare(h[0])),[a,o]=s[0],l=r.get(a),c=new Set;for(let g of e){let h=g.steps[t];if(h)for(let f of h.evidence)c.add(f)}let d={index:t,description:l.description,conclusion:a,evidence:[...c]},m=e[0].steps[t]?.conclusion,p=null;if(m&&m!==a){let g=e.filter(C=>C.steps[t]).length,h=[...n.values()].reduce((C,b)=>C+b,0),v=o/h>this.config.majorityThreshold;p={stepIndex:t,original:m,corrected:a,reason:v?`${i?"Weighted vote":"Majority vote"} (${o.toFixed(2)}/${h.toFixed(2)} weight from ${g} paths)`:`Selected highest ${i?"weight":"count"} (${o.toFixed(2)}/${h.toFixed(2)}), no clear majority`}}return{step:d,correction:p}}correctConclusion(e){let t=new Map,n=this.config.votingMethod==="weighted";for(let i of e){let s=t.get(i.conclusion)??0,a=n?i.confidence:1;t.set(i.conclusion,s+a)}return[...t.entries()].sort((i,s)=>s[1]-i[1]||i[0].localeCompare(s[0]))[0]?.[0]??""}calculateCorrectedConfidence(e,t){let n=e.reduce((l,c)=>l+c.confidence,0)/e.length,r=t.filter(l=>l.severity==="critical").length,i=t.filter(l=>l.severity==="major").length,s=t.filter(l=>l.severity==="minor").length,a=r*.2+i*.1+s*.03,o=t.length===0?.1:0;return Math.max(0,Math.min(1,n-a+o))}}});ee();U();var Qs={maxStepsPerTrajectory:100,autoEndTimeoutMs:1800*1e3,minQualityThreshold:.5,recentBufferSize:100},bt=class{config;unifiedMemory=null;db=null;prepared=new Map;initialized=!1;activeTrajectories=new Map;recentTrajectories;stats={trajectoriesStarted:0,trajectoriesCompleted:0,trajectoriesAbandoned:0,totalStepsRecorded:0,averageQuality:0,totalQualitySum:0};constructor(e={}){this.config={...Qs,...e},this.recentTrajectories=new fe(this.config.recentBufferSize)}async initialize(){this.initialized||(this.unifiedMemory=$(),await this.unifiedMemory.initialize(),this.db=this.unifiedMemory.getDatabase(),this.ensureSchema(),this.prepareStatements(),await this.loadRecentTrajectories(),this.cleanupOrphanedTrajectories(),this.initialized=!0,console.log("[TrajectoryTracker] Initialized"))}cleanupOrphanedTrajectories(){if(this.db)try{let e=this.db.prepare(`
|
|
3
3
|
UPDATE qe_trajectories
|
|
4
4
|
SET success = 0,
|
|
5
5
|
ended_at = datetime('now'),
|
|
@@ -280,7 +280,7 @@ import{b as ft}from"./chunk-KBA7FBK3.js";import{b as yt,c as vt}from"./chunk-CQB
|
|
|
280
280
|
WHERE id = ?
|
|
281
281
|
`).run(l,c,d,a.id);let m=this.prepared.get("insertRelationship");return m&&m.run(L(),o.id,a.id,"merged",1),this.db.prepare("UPDATE qe_patterns SET tier = 'archived' WHERE id = ?").run(o.id),await this.recordEvent(a.id,"merged",{absorbedFrom:o.id}),await this.recordEvent(o.id,"archived",{mergedInto:a.id}),this.stats.patternsMerged++,a.id}async autoConsolidate(e){this.ensureInitialized(),this.stats.consolidationRuns++;let t=0,n=0,r=await this.findMergeCandidates(e);for(let a of r.slice(0,5))await this.mergePatterns(a.patternId1,a.patternId2)&&t++;let i=await this.findPruneCandidates(e);for(let a of i)(a.reason==="low-quality"||a.reason==="obsolete")&&this.db&&(this.db.prepare("DELETE FROM qe_patterns WHERE id = ?").run(a.patternId),this.embeddingCache.delete(a.patternId),await this.recordEvent(a.patternId,"pruned",{reason:a.reason}),n++,this.stats.patternsPruned++);let s=this.db?.prepare(`
|
|
282
282
|
SELECT COUNT(*) as count FROM qe_patterns WHERE qe_domain = ? AND tier != 'archived'
|
|
283
|
-
`).get(e);return{merged:t,pruned:n,retained:s?.count??0}}async getEvolutionHistory(e,t=20){this.ensureInitialized();let i=(this.prepared.get("getVersionHistory")?.all(e,t)??[]).map(l=>({id:l.id,patternId:l.pattern_id,version:l.version,embedding:this.bufferToFloatArray(l.embedding,l.embedding_dimension),changes:P(l.changes||"[]"),qualityScore:l.quality_score,successRate:l.success_rate,timestamp:new Date(l.created_at),trigger:l.trigger})),o=(this.prepared.get("getEvents")?.all(e,t)??[]).map(l=>({id:l.id,patternId:l.pattern_id,eventType:l.event_type,details:P(l.details||"{}"),timestamp:new Date(l.created_at)}));return{versions:i,events:o}}async recordEvent(e,t,n){let r=this.prepared.get("insertEvent");if(r){let i={id:L(),patternId:e,eventType:t,details:n,timestamp:new Date};r.run(i.id,e,t,JSON.stringify(n)),this.recentEvents.push(i)}}getStats(){return{...this.stats,embeddingCacheSize:this.embeddingCache.size,recentEventsSize:this.recentEvents.length}}async dispose(){this.embeddingCache.clear(),this.recentEvents.clear(),this.prepared.clear(),this.db=null,this.unifiedMemory=null,this.initialized=!1,console.log("[PatternEvolution] Disposed")}ensureInitialized(){if(!this.initialized)throw new Error("PatternEvolution not initialized. Call initialize() first.")}floatArrayToBuffer(e){let t=Buffer.alloc(e.length*4);for(let n=0;n<e.length;n++)t.writeFloatLE(e[n],n*4);return t}bufferToFloatArray(e,t){let n=[];for(let r=0;r<t;r++)n.push(e.readFloatLE(r*4));return n}};function Pn(u={}){return new St(u)}k();var Js={base:{},trajectoryTracker:{},experienceReplay:{},patternEvolution:{},enableTrajectories:!0,enableExperienceReplay:!0,enablePatternEvolution:!0,autoStoreExperiences:!0,autoConsolidate:!0,consolidationIntervalMs:3600*1e3},An=class{config;reasoningBank=null;trajectoryTracker=null;experienceReplay=null;patternEvolution=null;initialized=!1;consolidationTimer=null;stats={tasksRouted:0,trajectoriesCompleted:0,experiencesApplied:0,tokensSavedEstimate:0,avgTaskSpeedupPercent:0,successRate:0,totalSuccesses:0,totalTasks:0};constructor(e={}){this.config={...Js,...e}}async initialize(){if(this.initialized)return;let e=performance.now();this.reasoningBank=En(this.config.base),await this.reasoningBank.initialize(),this.config.enableTrajectories&&(this.trajectoryTracker=Rn(this.config.trajectoryTracker),await this.trajectoryTracker.initialize()),this.config.enableExperienceReplay&&(this.experienceReplay=xn(this.config.experienceReplay),await this.experienceReplay.initialize()),this.config.enablePatternEvolution&&(this.patternEvolution=Pn(this.config.patternEvolution),await this.patternEvolution.initialize()),this.config.autoConsolidate&&this.patternEvolution&&this.startConsolidationTimer(),this.initialized=!0;let t=performance.now()-e;console.log(`[EnhancedReasoningBank] Initialized in ${t.toFixed(0)}ms`)}async routeTaskWithExperience(e){this.ensureInitialized(),this.stats.tasksRouted++;try{let t=await this.reasoningBank.routeTask(e);if(!t.success)return t;let n={...t.value};if(this.experienceReplay){let r=await this.experienceReplay.getGuidance(e.task,e.domain);if(r){n.experienceGuidance=r,n.guidance=[`Strategy: ${r.recommendedStrategy}`,...r.suggestedActions.map(i=>`Action: ${i}`),...n.guidance],this.stats.tokensSavedEstimate+=r.estimatedTokenSavings,this.stats.experiencesApplied++;for(let i of r.sourceExperiences)this.experienceReplay.recordApplication(i.id,e.task,!0,Math.round(r.estimatedTokenSavings)).catch(s=>{console.warn(`[EnhancedAdapter] Failed to record experience application: ${s}`)})}}if(this.trajectoryTracker){let r=await this.trajectoryTracker.findSimilarTrajectories(e.task,3);r.length>0&&(n.similarTrajectories=r.map(i=>({id:i.id,task:i.task,outcome:i.outcome,similarity:.8})))}return I(n)}catch(t){return q(z(t))}}async startTaskTrajectory(e,t={}){if(this.ensureInitialized(),!this.trajectoryTracker)throw new Error("Trajectory tracking not enabled");return this.trajectoryTracker.startTrajectory(e,t)}async recordTaskStep(e,t,n,r){if(this.ensureInitialized(),!this.trajectoryTracker)throw new Error("Trajectory tracking not enabled");await this.trajectoryTracker.recordStep(e,t,n,r)}async endTaskTrajectory(e,t,n){if(this.ensureInitialized(),!this.trajectoryTracker)throw new Error("Trajectory tracking not enabled");let r=await this.trajectoryTracker.endTrajectory(e,t,n);if(this.stats.trajectoriesCompleted++,this.stats.totalTasks++,t&&this.stats.totalSuccesses++,this.stats.successRate=this.stats.totalSuccesses/this.stats.totalTasks,this.config.autoStoreExperiences&&t&&this.experienceReplay){let i=this.deriveStrategy(r);await this.experienceReplay.storeExperience(r,i)}return r}async getTrajectory(e){return this.ensureInitialized(),this.trajectoryTracker?.getTrajectory(e)??null}async getExperienceGuidance(e,t){if(this.ensureInitialized(),!this.experienceReplay)return null;let n=await this.experienceReplay.getGuidance(e,t);if(n){this.stats.experiencesApplied++;for(let r of n.sourceExperiences)this.experienceReplay.recordApplication(r.id,e,!0,Math.round(n.estimatedTokenSavings)).catch(i=>{console.warn(`[EnhancedAdapter] Failed to record experience application: ${i}`)})}return n}async recordExperienceApplication(e,t,n,r=0){this.ensureInitialized(),this.experienceReplay&&(await this.experienceReplay.recordApplication(e,t,n,r),this.stats.tokensSavedEstimate+=r)}async storePattern(e){this.ensureInitialized();let t=await this.reasoningBank.storeQEPattern(e);return t.success&&this.patternEvolution&&t.value.embedding&&await this.patternEvolution.trackVersion(t.value.id,t.value.embedding,["Initial version"],"initial"),t}async searchPatterns(e,t){return this.ensureInitialized(),this.reasoningBank.searchQEPatterns(e,t)}async recordPatternOutcome(e){this.ensureInitialized();let t=await this.reasoningBank.recordOutcome(e);if(this.patternEvolution&&e.success!==void 0){let n=await this.patternEvolution.detectDrift(e.patternId);n?.hasSignificantDrift&&console.log(`[EnhancedReasoningBank] Pattern drift detected: ${e.patternId}, recommendation: ${n.recommendation}`)}return t}async detectPatternDrift(e){return this.ensureInitialized(),this.patternEvolution?.detectDrift(e)??null}async findMergeCandidates(e){return this.ensureInitialized(),this.patternEvolution?.findMergeCandidates(e)??[]}async consolidatePatterns(e){return this.ensureInitialized(),this.patternEvolution?this.patternEvolution.autoConsolidate(e):{merged:0,pruned:0,retained:0}}async getPatternHistory(e){return this.ensureInitialized(),this.patternEvolution?.getEvolutionHistory(e)??null}async getStats(){return this.ensureInitialized(),{adapter:this.stats,reasoningBank:await this.reasoningBank.getQEStats(),trajectoryTracker:this.trajectoryTracker?.getStats(),experienceReplay:this.experienceReplay?.getStats(),patternEvolution:this.patternEvolution?.getStats()}}async dispose(){this.consolidationTimer&&(clearInterval(this.consolidationTimer),this.consolidationTimer=null),await this.patternEvolution?.dispose(),await this.experienceReplay?.dispose(),await this.trajectoryTracker?.dispose(),await this.reasoningBank?.dispose(),this.patternEvolution=null,this.experienceReplay=null,this.trajectoryTracker=null,this.reasoningBank=null,this.initialized=!1,console.log("[EnhancedReasoningBank] Disposed")}ensureInitialized(){if(!this.initialized||!this.reasoningBank)throw new Error("EnhancedReasoningBankAdapter not initialized. Call initialize() first.")}startConsolidationTimer(){this.consolidationTimer=setInterval(async()=>{try{let e=["test-generation","coverage-analysis","test-execution","quality-assessment"];for(let t of e){let n=await this.patternEvolution.autoConsolidate(t);(n.merged>0||n.pruned>0)&&console.log(`[EnhancedReasoningBank] Consolidated ${t}: merged=${n.merged}, pruned=${n.pruned}, retained=${n.retained}`)}}catch(e){console.error("[EnhancedReasoningBank] Consolidation error:",e)}},this.config.consolidationIntervalMs)}deriveStrategy(e){let t=e.steps.filter(n=>n.result.outcome==="success").map(n=>n.action);return t.length===0?`Attempted ${e.steps.length} actions for: ${e.task}`:`Used ${t.join(" -> ")} pattern for: ${e.task.substring(0,50)}`}};function Ll(u={}){return new An(u)}import{randomUUID as ua}from"crypto";var O=class extends Error{constructor(t,n,r){super(n);this.type=t;this.details=r;this.name="EmbeddingError"}};ve();var Et=class{cache;maxSize;hits=0;misses=0;constructor(e){this.maxSize=e,this.cache=new Map}get(e){let t=this.cache.get(e);if(t)return this.hits++,this.cache.delete(e),this.cache.set(e,t),t;this.misses++}set(e,t){if(this.cache.size>=this.maxSize){let n=this.cache.keys().next().value;n!==void 0&&this.cache.delete(n)}this.cache.set(e,t)}clear(){this.cache.clear(),this.hits=0,this.misses=0}getStats(){return{hits:this.hits,misses:this.misses,size:this.cache.size}}},we=class{config;cache;totalGenerated=0;generationTimes=[];isInitialized=!1;onnxRuntime=null;constructor(e={}){this.config={model:e.model??"all-MiniLM-L6-v2",normalize:e.normalize??!0,hyperbolic:e.hyperbolic??!1,cacheSize:e.cacheSize??256,curvature:e.curvature??-1},this.cache=new Et(this.config.cacheSize)}async initialize(){if(!this.isInitialized)try{this.onnxRuntime={generateEmbedding:async(e,t)=>{let n=t==="all-MiniLM-L6-v2"?384:768,r=new Array(n).fill(0).map(()=>V()*2-1);if(this.config.normalize){let i=Math.sqrt(r.reduce((s,a)=>s+a*a,0));return r.map(s=>s/i)}return r},isAvailable:()=>!0},this.isInitialized=!0}catch(e){throw new O("RUNTIME_UNAVAILABLE","Failed to initialize ONNX runtime",e)}}async generate(e){if(this.isInitialized||await this.initialize(),!e||e.trim().length===0)throw new O("INVALID_INPUT","Text cannot be empty");let t=this.getCacheKey(e),n=this.cache.get(t);if(n)return n;let r=Date.now();try{if(!this.onnxRuntime)throw new O("RUNTIME_UNAVAILABLE","ONNX runtime not available");let i=await this.onnxRuntime.generateEmbedding(e,this.config.model),s=i,a=!1;this.config.hyperbolic&&(s=this.euclideanToPoincare(i),a=!0);let o={vector:s,dimensions:s.length,model:this.config.model,isHyperbolic:a};return this.cache.set(t,o),this.totalGenerated++,this.generationTimes.push(Date.now()-r),this.generationTimes.length>100&&this.generationTimes.shift(),o}catch(i){throw new O("MODEL_LOAD_FAILED",`Failed to generate embedding: ${i instanceof Error?i.message:"Unknown error"}`,i)}}async generateBatch(e){if(!e.texts||e.texts.length===0)throw new O("INVALID_INPUT","Batch request must contain at least one text");let t=Date.now(),n=0,r=[],i={...this.config};e.config&&(this.config={...this.config,...e.config});try{for(let s of e.texts){let a=this.getCacheKey(s),o=this.cache.get(a);if(o)r.push(o),n++;else{let l=await this.generate(s);r.push(l)}}return{embeddings:r,duration:Date.now()-t,cacheHits:n}}finally{this.config=i}}getStats(){let e=this.cache.getStats(),t=this.generationTimes.length>0?this.generationTimes.reduce((n,r)=>n+r,0)/this.generationTimes.length:0;return{totalGenerated:this.totalGenerated,cacheHits:e.hits,cacheMisses:e.misses,avgGenerationTime:t,currentModel:this.config.model,vectorsStored:e.size}}clearCache(){this.cache.clear()}updateConfig(e){let t=e.model&&e.model!==this.config.model;this.config={...this.config,...e},e.cacheSize!==void 0&&e.cacheSize!==this.cache.getStats().size&&(this.cache=new Et(e.cacheSize)),t&&(this.isInitialized=!1)}getCacheKey(e){return`${this.config.model}:${this.config.hyperbolic}:${e}`}euclideanToPoincare(e){let t=Math.sqrt(e.reduce((s,a)=>s+a*a,0));if(t===0)return e;let n=Math.abs(this.config.curvature),r=Math.sqrt(n),i=Math.tanh(r*t/2)/(r*t);return e.map(s=>s*i)}isReady(){return this.isInitialized&&this.onnxRuntime!==null}};var Re=class{embeddings;searchCount=0;searchTimes=[];constructor(){this.embeddings=new Map}store(e){this.embeddings.set(e.id,e)}storeBatch(e){for(let t of e)this.store(t)}remove(e){return this.embeddings.delete(e)}clear(){this.embeddings.clear()}async search(e,t={}){let n=Date.now(),r={metric:t.metric??"cosine",topK:t.topK??5,threshold:t.threshold??.5,namespace:t.namespace};try{let i=Array.from(this.embeddings.values());r.namespace&&(i=i.filter(c=>c.namespace===r.namespace));let s=[];for(let c of i){if(c.embedding.dimensions!==e.dimensions)continue;let d=this.calculateSimilarity(e.vector,c.embedding.vector,r.metric);(r.metric==="cosine"?d>=r.threshold:d<=r.threshold)&&s.push({stored:c,score:d})}let a=r.metric==="cosine"?-1:1;s.sort((c,d)=>a*(c.score-d.score));let l=s.slice(0,r.topK).map(({stored:c,score:d})=>({text:c.text,embedding:c.embedding,score:d,metadata:c.metadata}));return this.searchCount++,this.searchTimes.push(Date.now()-n),this.searchTimes.length>100&&this.searchTimes.shift(),l}catch(i){throw new O("DIMENSION_MISMATCH",`Search failed: ${i instanceof Error?i.message:"Unknown error"}`,i)}}async findMostSimilar(e,t={}){let n=await this.search(e,{...t,topK:1});return n.length>0?n[0]:null}calculateSimilarity(e,t,n){if(e.length!==t.length)throw new O("DIMENSION_MISMATCH",`Vector dimensions do not match: ${e.length} vs ${t.length}`);switch(n){case"cosine":return this.cosineSimilarity(e,t);case"euclidean":return this.euclideanDistance(e,t);case"poincare":return this.poincareDistance(e,t);default:throw new O("INVALID_INPUT",`Unknown similarity metric: ${n}`)}}getStats(){let e=this.searchTimes.length>0?this.searchTimes.reduce((t,n)=>t+n,0)/this.searchTimes.length:0;return{searchCount:this.searchCount,avgSearchTime:e,storedCount:this.embeddings.size}}getAll(e){let t=Array.from(this.embeddings.values());return e?t.filter(n=>n.namespace===e):t}get(e){return this.embeddings.get(e)}cosineSimilarity(e,t){let n=0,r=0,i=0;for(let a=0;a<e.length;a++)n+=e[a]*t[a],r+=e[a]*e[a],i+=t[a]*t[a];let s=Math.sqrt(r)*Math.sqrt(i);return s===0?0:n/s}euclideanDistance(e,t){let n=0;for(let r=0;r<e.length;r++){let i=e[r]-t[r];n+=i*i}return Math.sqrt(n)}poincareDistance(e,t,n=-1){let r=Math.abs(n),i=Math.sqrt(r),s=e.reduce((p,g)=>p+g*g,0),a=t.reduce((p,g)=>p+g*g,0),o=0;for(let p=0;p<e.length;p++){let g=e[p]-t[p];o+=g*g}let l=2*o,c=(1-s)*(1-a);if(c<=0)return 1/0;let d=l/c;return Math.acosh(1+d)/i}async searchBatch(e,t={}){let n=[];for(let r of e){let i=await this.search(r,t);n.push(i)}return n}async findInRadius(e,t,n="cosine"){return this.search(e,{metric:n,threshold:t,topK:this.embeddings.size})}};var xe=class{config;constructor(e={}){if(this.config={curvature:e.curvature??-1,epsilon:e.epsilon??1e-7},this.config.curvature>=0)throw new O("HYPERBOLIC_ERROR","Curvature must be negative for hyperbolic space")}euclideanToPoincare(e){if(e.isHyperbolic)return e;let t=e.vector,n=this.norm(t);if(n<this.config.epsilon)return{...e,isHyperbolic:!0};let r=Math.abs(this.config.curvature),i=Math.sqrt(r),s=Math.tanh(i*n/2)/(i*n),a=t.map(l=>l*s),o=this.norm(a);if(o>=1-this.config.epsilon)throw new O("HYPERBOLIC_ERROR",`Poincar\xE9 ball constraint violated: norm = ${o}`);return{vector:a,dimensions:e.dimensions,model:e.model,isHyperbolic:!0}}poincareToEuclidean(e){if(!e.isHyperbolic)return e;let t=e.vector,n=this.norm(t);if(n<this.config.epsilon)return{...e,isHyperbolic:!1};let r=Math.abs(this.config.curvature),i=Math.sqrt(r),s=i*n;if(s>=1)throw new O("HYPERBOLIC_ERROR","Point is on or outside Poincar\xE9 ball boundary");let a=2/i*Math.atanh(s)/n;return{vector:t.map(l=>l*a),dimensions:e.dimensions,model:e.model,isHyperbolic:!1}}distance(e,t){if(e.dimensions!==t.dimensions)throw new O("DIMENSION_MISMATCH","Embeddings must have same dimensions");if(!e.isHyperbolic||!t.isHyperbolic)throw new O("HYPERBOLIC_ERROR","Both embeddings must be in hyperbolic space");let n=e.vector,r=t.vector,i=Math.abs(this.config.curvature),s=Math.sqrt(i),a=this.normSquared(n),o=this.normSquared(r),c=2*this.euclideanDistanceSquared(n,r),d=(1-a)*(1-o);if(d<=this.config.epsilon)return 1/0;let m=c/d;return Math.acosh(1+m)/s}midpoint(e,t){if(e.dimensions!==t.dimensions)throw new O("DIMENSION_MISMATCH","Embeddings must have same dimensions");if(!e.isHyperbolic||!t.isHyperbolic)throw new O("HYPERBOLIC_ERROR","Both embeddings must be in hyperbolic space");let n=e.vector,r=t.vector;return{vector:this.mobiusAddition(n,this.mobiusScalarMultiply(this.mobiusAddition(this.mobiusNegate(n),r),.5)),dimensions:e.dimensions,model:e.model,isHyperbolic:!0}}mobiusAddition(e,t){let n=Math.abs(this.config.curvature),r=this.dot(e,t),i=this.normSquared(e),s=this.normSquared(t),a=1+2*n*r+n*s,o=1-n*i,l=1+2*n*r+n*n*i*s;if(Math.abs(l)<this.config.epsilon)throw new O("HYPERBOLIC_ERROR","M\xF6bius addition denominator is zero");return e.map((d,m)=>(a*d+o*t[m])/l)}mobiusScalarMultiply(e,t){let n=Math.abs(this.config.curvature),r=Math.sqrt(n),i=this.norm(e);if(i<this.config.epsilon)return e;let s=r*i;if(Math.abs(s)>=1)throw new O("HYPERBOLIC_ERROR","M\xF6bius scalar multiplication out of bounds");let a=Math.tanh(t*Math.atanh(s))/(r*i);return e.map(o=>o*a)}mobiusNegate(e){return e.map(t=>-t)}projectToBall(e){let t=this.norm(e);if(t>=1-this.config.epsilon){let n=(1-this.config.epsilon)/t;return e.map(r=>r*n)}return e}norm(e){return Math.sqrt(this.normSquared(e))}normSquared(e){return e.reduce((t,n)=>t+n*n,0)}dot(e,t){return e.reduce((n,r,i)=>n+r*t[i],0)}euclideanDistanceSquared(e,t){return e.reduce((n,r,i)=>{let s=r-t[i];return n+s*s},0)}updateConfig(e){if(e.curvature!==void 0&&e.curvature>=0)throw new O("HYPERBOLIC_ERROR","Curvature must be negative");this.config={...this.config,...e}}getConfig(){return{...this.config}}};ee();var Be=class{generator;search;hyperbolic;isInitialized=!1;constructor(e={}){this.generator=new we(e.embedding),this.search=new Re,this.hyperbolic=new xe(e.hyperbolic),e.autoInitialize!==!1&&this.initialize().catch(t=>{console.error("Failed to auto-initialize ONNX embeddings:",t)})}async initialize(){if(!this.isInitialized)try{await this.generator.initialize(),this.isInitialized=!0}catch(e){throw new O("RUNTIME_UNAVAILABLE","Failed to initialize ONNX embeddings adapter",e)}}async getHealth(){try{let e=this.generator.isReady();return{available:e,modelLoaded:e?this.getStats().currentModel:null,system:{memory:process.memoryUsage().heapUsed,threads:1}}}catch(e){return{available:!1,modelLoaded:null,error:e instanceof Error?e.message:"Unknown error",system:{memory:process.memoryUsage().heapUsed,threads:0}}}}async generateEmbedding(e){return await this.ensureInitialized(),this.generator.generate(e)}async generateBatch(e){return await this.ensureInitialized(),this.generator.generateBatch(e)}async generateAndStore(e,t){let n=await this.generateEmbedding(e),r={id:t?.id??this.generateId(),text:e,embedding:n,namespace:t?.namespace,metadata:t?.customData,createdAt:Date.now()};this.search.store(r);try{let i=$();await i.initialize(),await i.vectorStore(r.id,r.embedding.vector,r.namespace??"onnx",{text:r.text,customData:r.metadata,createdAt:r.createdAt})}catch{}return r}async searchByText(e,t){let n=await this.generateEmbedding(e);return this.search.search(n,t)}async searchByEmbedding(e,t){return this.search.search(e,t)}async findMostSimilar(e,t){let n=await this.generateEmbedding(e);return this.search.findMostSimilar(n,t)}async compareSimilarity(e,t,n="cosine"){let[r,i]=await this.generateBatch({texts:[e,t]}).then(s=>s.embeddings);return this.search.calculateSimilarity(r.vector,i.vector,n)}storeEmbedding(e){this.search.store(e)}storeBatch(e){this.search.storeBatch(e)}removeEmbedding(e){return this.search.remove(e)}getEmbedding(e){return this.search.get(e)}getAllEmbeddings(e){return this.search.getAll(e)}clearEmbeddings(){this.search.clear()}toHyperbolic(e){return this.hyperbolic.euclideanToPoincare(e)}toEuclidean(e){return this.hyperbolic.poincareToEuclidean(e)}hyperbolicDistance(e,t){return this.hyperbolic.distance(e,t)}hyperbolicMidpoint(e,t){return this.hyperbolic.midpoint(e,t)}projectToBall(e){return this.hyperbolic.projectToBall(e)}getStats(){let e=this.generator.getStats(),t=this.search.getStats();return{totalGenerated:e.totalGenerated??0,cacheHits:e.cacheHits??0,cacheMisses:e.cacheMisses??0,totalSearches:t.searchCount,avgGenerationTime:e.avgGenerationTime??0,avgSearchTime:t.avgSearchTime,currentModel:e.currentModel??"all-MiniLM-L6-v2",vectorsStored:t.storedCount}}updateEmbeddingConfig(e){this.generator.updateConfig(e)}updateHyperbolicConfig(e){this.hyperbolic.updateConfig(e)}clearCaches(){this.generator.clearCache()}reset(){this.clearCaches(),this.clearEmbeddings()}async bridgeToMCPGenerate(e,t=!1){let n=await this.generateEmbedding(e);return t?this.toHyperbolic(n):n}async bridgeToMCPSearch(e,t){return this.searchByText(e,t)}async bridgeToMCPCompare(e,t,n="cosine"){return this.compareSimilarity(e,t,n)}async ensureInitialized(){this.isInitialized||await this.initialize()}generateId(){return`emb_${Date.now()}_${ua().slice(0,9)}`}isReady(){return this.isInitialized&&this.generator.isReady()}};function xt(u){return new Be(u)}var kn={enabled:!0,dbPath:".agentic-qe/memory.db",maxOutcomes:1e5,retentionDays:90,autoCleanup:!0,cleanupIntervalMs:3600*1e3};ee();k();U();var va={enabled:!0,haikuThreshold:.8,sonnetThreshold:.4,includeHealthSnapshot:!1,enableLogging:!0},Mn=class{config;minCutService;constructor(e){this.config={...va,...e},this.minCutService=ei()}route(e){let t=Date.now();if(!this.config.enabled)return this.createFallbackResult(e,t,"MinCut routing disabled");let n=e.agentTopology||this.config.defaultTopology;if(!n||n.length===0)return this.createFallbackResult(e,t,"No agent topology available for mincut analysis");try{let r=this.minCutService.computeRoutingTier(e.task,n),i=this.routingTierToModelTier(r.tier);e.isCritical&&i<2&&(i=2);let s=this.modelTierToLabel(i),a;if(this.config.includeHealthSnapshot){let c=e.taskGraph||this.minCutService.buildTaskGraphFromTopology(n);a=this.minCutService.getStructuralHealth(c)}let o=Date.now()-t,l={modelTier:i,tierLabel:s,lambda:r.lambda,normalizedLambda:r.normalizedLambda,confidence:r.confidence,rationale:r.rationale,usedMinCut:!0,healthSnapshot:a,decisionTimeMs:o};return this.config.enableLogging&&this.logDecision(l),l}catch(r){return this.createFallbackResult(e,t,`MinCut routing error: ${r instanceof Error?r.message:String(r)}`)}}getMinCutService(){return this.minCutService}isEnabled(){return this.config.enabled}routingTierToModelTier(e){switch(e){case 1:return 1;case 2:return 2;case 3:return 4;default:return 2}}modelTierToLabel(e){switch(e){case 0:return"Booster";case 1:return"Haiku";case 2:return"Sonnet";case 3:return"Sonnet-Extended";case 4:return"Opus";default:return"Sonnet"}}createFallbackResult(e,t,n){return{modelTier:(e.isCritical,2),tierLabel:"Sonnet",lambda:0,normalizedLambda:0,confidence:.3,rationale:`Fallback to Sonnet: ${n}`,usedMinCut:!1,decisionTimeMs:Date.now()-t}}logDecision(e){let t=e.usedMinCut?"MinCut":"Fallback";console.error(`[MinCutRouter] [${t}] Tier ${e.modelTier} (${e.tierLabel}) | Lambda: ${e.normalizedLambda.toFixed(3)} | Confidence: ${(e.confidence*100).toFixed(0)}% | Time: ${e.decisionTimeMs}ms`)}};function ii(u){return new Mn(u)}import{existsSync as ba}from"fs";import{join as Ca}from"path";var Pt=class{id="memory";name="Pattern Memory";priority=80;maxTokens=2e3;async gather(e){let t=[];try{let n=Ca(process.cwd(),".agentic-qe","memory.db");if(!ba(n))return this.fallbackGather(e);let{openDatabase:r}=await import("./safe-db-5KLXCNXN.js"),i=r(n,{readonly:!0});try{let s=this.extractDomainKeywords(e.taskDescription);if(s.length>0){let a=s.map(()=>"domain LIKE ?").join(" OR "),o=s.map(d=>`%${d}%`),c=i.prepare(`SELECT name, domain, description, confidence
|
|
283
|
+
`).get(e);return{merged:t,pruned:n,retained:s?.count??0}}async getEvolutionHistory(e,t=20){this.ensureInitialized();let i=(this.prepared.get("getVersionHistory")?.all(e,t)??[]).map(l=>({id:l.id,patternId:l.pattern_id,version:l.version,embedding:this.bufferToFloatArray(l.embedding,l.embedding_dimension),changes:P(l.changes||"[]"),qualityScore:l.quality_score,successRate:l.success_rate,timestamp:new Date(l.created_at),trigger:l.trigger})),o=(this.prepared.get("getEvents")?.all(e,t)??[]).map(l=>({id:l.id,patternId:l.pattern_id,eventType:l.event_type,details:P(l.details||"{}"),timestamp:new Date(l.created_at)}));return{versions:i,events:o}}async recordEvent(e,t,n){let r=this.prepared.get("insertEvent");if(r){let i={id:L(),patternId:e,eventType:t,details:n,timestamp:new Date};r.run(i.id,e,t,JSON.stringify(n)),this.recentEvents.push(i)}}getStats(){return{...this.stats,embeddingCacheSize:this.embeddingCache.size,recentEventsSize:this.recentEvents.length}}async dispose(){this.embeddingCache.clear(),this.recentEvents.clear(),this.prepared.clear(),this.db=null,this.unifiedMemory=null,this.initialized=!1,console.log("[PatternEvolution] Disposed")}ensureInitialized(){if(!this.initialized)throw new Error("PatternEvolution not initialized. Call initialize() first.")}floatArrayToBuffer(e){let t=Buffer.alloc(e.length*4);for(let n=0;n<e.length;n++)t.writeFloatLE(e[n],n*4);return t}bufferToFloatArray(e,t){let n=[];for(let r=0;r<t;r++)n.push(e.readFloatLE(r*4));return n}};function Pn(u={}){return new St(u)}k();var Js={base:{},trajectoryTracker:{},experienceReplay:{},patternEvolution:{},enableTrajectories:!0,enableExperienceReplay:!0,enablePatternEvolution:!0,autoStoreExperiences:!0,autoConsolidate:!0,consolidationIntervalMs:3600*1e3},An=class{config;reasoningBank=null;trajectoryTracker=null;experienceReplay=null;patternEvolution=null;initialized=!1;consolidationTimer=null;stats={tasksRouted:0,trajectoriesCompleted:0,experiencesApplied:0,tokensSavedEstimate:0,avgTaskSpeedupPercent:0,successRate:0,totalSuccesses:0,totalTasks:0};constructor(e={}){this.config={...Js,...e}}async initialize(){if(this.initialized)return;let e=performance.now();this.reasoningBank=En(this.config.base),await this.reasoningBank.initialize(),this.config.enableTrajectories&&(this.trajectoryTracker=Rn(this.config.trajectoryTracker),await this.trajectoryTracker.initialize()),this.config.enableExperienceReplay&&(this.experienceReplay=xn(this.config.experienceReplay),await this.experienceReplay.initialize()),this.config.enablePatternEvolution&&(this.patternEvolution=Pn(this.config.patternEvolution),await this.patternEvolution.initialize()),this.config.autoConsolidate&&this.patternEvolution&&this.startConsolidationTimer(),this.initialized=!0;let t=performance.now()-e;console.log(`[EnhancedReasoningBank] Initialized in ${t.toFixed(0)}ms`)}async routeTaskWithExperience(e){this.ensureInitialized(),this.stats.tasksRouted++;try{let t=await this.reasoningBank.routeTask(e);if(!t.success)return t;let n={...t.value};if(this.experienceReplay){let r=await this.experienceReplay.getGuidance(e.task,e.domain);if(r){n.experienceGuidance=r,n.guidance=[`Strategy: ${r.recommendedStrategy}`,...r.suggestedActions.map(i=>`Action: ${i}`),...n.guidance],this.stats.tokensSavedEstimate+=r.estimatedTokenSavings,this.stats.experiencesApplied++;for(let i of r.sourceExperiences)this.experienceReplay.recordApplication(i.id,e.task,!0,Math.round(r.estimatedTokenSavings)).catch(s=>{console.warn(`[EnhancedAdapter] Failed to record experience application: ${s}`)})}}if(this.trajectoryTracker){let r=await this.trajectoryTracker.findSimilarTrajectories(e.task,3);r.length>0&&(n.similarTrajectories=r.map(i=>({id:i.id,task:i.task,outcome:i.outcome,similarity:.8})))}return I(n)}catch(t){return q(z(t))}}async startTaskTrajectory(e,t={}){if(this.ensureInitialized(),!this.trajectoryTracker)throw new Error("Trajectory tracking not enabled");return this.trajectoryTracker.startTrajectory(e,t)}async recordTaskStep(e,t,n,r){if(this.ensureInitialized(),!this.trajectoryTracker)throw new Error("Trajectory tracking not enabled");await this.trajectoryTracker.recordStep(e,t,n,r)}async endTaskTrajectory(e,t,n){if(this.ensureInitialized(),!this.trajectoryTracker)throw new Error("Trajectory tracking not enabled");let r=await this.trajectoryTracker.endTrajectory(e,t,n);if(this.stats.trajectoriesCompleted++,this.stats.totalTasks++,t&&this.stats.totalSuccesses++,this.stats.successRate=this.stats.totalSuccesses/this.stats.totalTasks,this.config.autoStoreExperiences&&t&&this.experienceReplay){let i=this.deriveStrategy(r);await this.experienceReplay.storeExperience(r,i)}return r}async getTrajectory(e){return this.ensureInitialized(),this.trajectoryTracker?.getTrajectory(e)??null}async getExperienceGuidance(e,t){if(this.ensureInitialized(),!this.experienceReplay)return null;let n=await this.experienceReplay.getGuidance(e,t);if(n){this.stats.experiencesApplied++;for(let r of n.sourceExperiences)this.experienceReplay.recordApplication(r.id,e,!0,Math.round(n.estimatedTokenSavings)).catch(i=>{console.warn(`[EnhancedAdapter] Failed to record experience application: ${i}`)})}return n}async recordExperienceApplication(e,t,n,r=0){this.ensureInitialized(),this.experienceReplay&&(await this.experienceReplay.recordApplication(e,t,n,r),this.stats.tokensSavedEstimate+=r)}async storePattern(e){this.ensureInitialized();let t=await this.reasoningBank.storeQEPattern(e);return t.success&&this.patternEvolution&&t.value.embedding&&await this.patternEvolution.trackVersion(t.value.id,t.value.embedding,["Initial version"],"initial"),t}async searchPatterns(e,t){return this.ensureInitialized(),this.reasoningBank.searchQEPatterns(e,t)}async recordPatternOutcome(e){this.ensureInitialized();let t=await this.reasoningBank.recordOutcome(e);if(this.patternEvolution&&e.success!==void 0){let n=await this.patternEvolution.detectDrift(e.patternId);n?.hasSignificantDrift&&console.log(`[EnhancedReasoningBank] Pattern drift detected: ${e.patternId}, recommendation: ${n.recommendation}`)}return t}async detectPatternDrift(e){return this.ensureInitialized(),this.patternEvolution?.detectDrift(e)??null}async findMergeCandidates(e){return this.ensureInitialized(),this.patternEvolution?.findMergeCandidates(e)??[]}async consolidatePatterns(e){return this.ensureInitialized(),this.patternEvolution?this.patternEvolution.autoConsolidate(e):{merged:0,pruned:0,retained:0}}async getPatternHistory(e){return this.ensureInitialized(),this.patternEvolution?.getEvolutionHistory(e)??null}async getStats(){return this.ensureInitialized(),{adapter:this.stats,reasoningBank:await this.reasoningBank.getQEStats(),trajectoryTracker:this.trajectoryTracker?.getStats(),experienceReplay:this.experienceReplay?.getStats(),patternEvolution:this.patternEvolution?.getStats()}}async dispose(){this.consolidationTimer&&(clearInterval(this.consolidationTimer),this.consolidationTimer=null),await this.patternEvolution?.dispose(),await this.experienceReplay?.dispose(),await this.trajectoryTracker?.dispose(),await this.reasoningBank?.dispose(),this.patternEvolution=null,this.experienceReplay=null,this.trajectoryTracker=null,this.reasoningBank=null,this.initialized=!1,console.log("[EnhancedReasoningBank] Disposed")}ensureInitialized(){if(!this.initialized||!this.reasoningBank)throw new Error("EnhancedReasoningBankAdapter not initialized. Call initialize() first.")}startConsolidationTimer(){this.consolidationTimer=setInterval(async()=>{try{let e=["test-generation","coverage-analysis","test-execution","quality-assessment"];for(let t of e){let n=await this.patternEvolution.autoConsolidate(t);(n.merged>0||n.pruned>0)&&console.log(`[EnhancedReasoningBank] Consolidated ${t}: merged=${n.merged}, pruned=${n.pruned}, retained=${n.retained}`)}}catch(e){console.error("[EnhancedReasoningBank] Consolidation error:",e)}},this.config.consolidationIntervalMs)}deriveStrategy(e){let t=e.steps.filter(n=>n.result.outcome==="success").map(n=>n.action);return t.length===0?`Attempted ${e.steps.length} actions for: ${e.task}`:`Used ${t.join(" -> ")} pattern for: ${e.task.substring(0,50)}`}};function Ll(u={}){return new An(u)}import{randomUUID as ua}from"crypto";var O=class extends Error{constructor(t,n,r){super(n);this.type=t;this.details=r;this.name="EmbeddingError"}};ve();var Et=class{cache;maxSize;hits=0;misses=0;constructor(e){this.maxSize=e,this.cache=new Map}get(e){let t=this.cache.get(e);if(t)return this.hits++,this.cache.delete(e),this.cache.set(e,t),t;this.misses++}set(e,t){if(this.cache.size>=this.maxSize){let n=this.cache.keys().next().value;n!==void 0&&this.cache.delete(n)}this.cache.set(e,t)}clear(){this.cache.clear(),this.hits=0,this.misses=0}getStats(){return{hits:this.hits,misses:this.misses,size:this.cache.size}}},we=class{config;cache;totalGenerated=0;generationTimes=[];isInitialized=!1;onnxRuntime=null;constructor(e={}){this.config={model:e.model??"all-MiniLM-L6-v2",normalize:e.normalize??!0,hyperbolic:e.hyperbolic??!1,cacheSize:e.cacheSize??256,curvature:e.curvature??-1},this.cache=new Et(this.config.cacheSize)}async initialize(){if(!this.isInitialized)try{this.onnxRuntime={generateEmbedding:async(e,t)=>{let n=t==="all-MiniLM-L6-v2"?384:768,r=new Array(n).fill(0).map(()=>V()*2-1);if(this.config.normalize){let i=Math.sqrt(r.reduce((s,a)=>s+a*a,0));return r.map(s=>s/i)}return r},isAvailable:()=>!0},this.isInitialized=!0}catch(e){throw new O("RUNTIME_UNAVAILABLE","Failed to initialize ONNX runtime",e)}}async generate(e){if(this.isInitialized||await this.initialize(),!e||e.trim().length===0)throw new O("INVALID_INPUT","Text cannot be empty");let t=this.getCacheKey(e),n=this.cache.get(t);if(n)return n;let r=Date.now();try{if(!this.onnxRuntime)throw new O("RUNTIME_UNAVAILABLE","ONNX runtime not available");let i=await this.onnxRuntime.generateEmbedding(e,this.config.model),s=i,a=!1;this.config.hyperbolic&&(s=this.euclideanToPoincare(i),a=!0);let o={vector:s,dimensions:s.length,model:this.config.model,isHyperbolic:a};return this.cache.set(t,o),this.totalGenerated++,this.generationTimes.push(Date.now()-r),this.generationTimes.length>100&&this.generationTimes.shift(),o}catch(i){throw new O("MODEL_LOAD_FAILED",`Failed to generate embedding: ${i instanceof Error?i.message:"Unknown error"}`,i)}}async generateBatch(e){if(!e.texts||e.texts.length===0)throw new O("INVALID_INPUT","Batch request must contain at least one text");let t=Date.now(),n=0,r=[],i={...this.config};e.config&&(this.config={...this.config,...e.config});try{for(let s of e.texts){let a=this.getCacheKey(s),o=this.cache.get(a);if(o)r.push(o),n++;else{let l=await this.generate(s);r.push(l)}}return{embeddings:r,duration:Date.now()-t,cacheHits:n}}finally{this.config=i}}getStats(){let e=this.cache.getStats(),t=this.generationTimes.length>0?this.generationTimes.reduce((n,r)=>n+r,0)/this.generationTimes.length:0;return{totalGenerated:this.totalGenerated,cacheHits:e.hits,cacheMisses:e.misses,avgGenerationTime:t,currentModel:this.config.model,vectorsStored:e.size}}clearCache(){this.cache.clear()}updateConfig(e){let t=e.model&&e.model!==this.config.model;this.config={...this.config,...e},e.cacheSize!==void 0&&e.cacheSize!==this.cache.getStats().size&&(this.cache=new Et(e.cacheSize)),t&&(this.isInitialized=!1)}getCacheKey(e){return`${this.config.model}:${this.config.hyperbolic}:${e}`}euclideanToPoincare(e){let t=Math.sqrt(e.reduce((s,a)=>s+a*a,0));if(t===0)return e;let n=Math.abs(this.config.curvature),r=Math.sqrt(n),i=Math.tanh(r*t/2)/(r*t);return e.map(s=>s*i)}isReady(){return this.isInitialized&&this.onnxRuntime!==null}};var Re=class{embeddings;searchCount=0;searchTimes=[];constructor(){this.embeddings=new Map}store(e){this.embeddings.set(e.id,e)}storeBatch(e){for(let t of e)this.store(t)}remove(e){return this.embeddings.delete(e)}clear(){this.embeddings.clear()}async search(e,t={}){let n=Date.now(),r={metric:t.metric??"cosine",topK:t.topK??5,threshold:t.threshold??.5,namespace:t.namespace};try{let i=Array.from(this.embeddings.values());r.namespace&&(i=i.filter(c=>c.namespace===r.namespace));let s=[];for(let c of i){if(c.embedding.dimensions!==e.dimensions)continue;let d=this.calculateSimilarity(e.vector,c.embedding.vector,r.metric);(r.metric==="cosine"?d>=r.threshold:d<=r.threshold)&&s.push({stored:c,score:d})}let a=r.metric==="cosine"?-1:1;s.sort((c,d)=>a*(c.score-d.score));let l=s.slice(0,r.topK).map(({stored:c,score:d})=>({text:c.text,embedding:c.embedding,score:d,metadata:c.metadata}));return this.searchCount++,this.searchTimes.push(Date.now()-n),this.searchTimes.length>100&&this.searchTimes.shift(),l}catch(i){throw new O("DIMENSION_MISMATCH",`Search failed: ${i instanceof Error?i.message:"Unknown error"}`,i)}}async findMostSimilar(e,t={}){let n=await this.search(e,{...t,topK:1});return n.length>0?n[0]:null}calculateSimilarity(e,t,n){if(e.length!==t.length)throw new O("DIMENSION_MISMATCH",`Vector dimensions do not match: ${e.length} vs ${t.length}`);switch(n){case"cosine":return this.cosineSimilarity(e,t);case"euclidean":return this.euclideanDistance(e,t);case"poincare":return this.poincareDistance(e,t);default:throw new O("INVALID_INPUT",`Unknown similarity metric: ${n}`)}}getStats(){let e=this.searchTimes.length>0?this.searchTimes.reduce((t,n)=>t+n,0)/this.searchTimes.length:0;return{searchCount:this.searchCount,avgSearchTime:e,storedCount:this.embeddings.size}}getAll(e){let t=Array.from(this.embeddings.values());return e?t.filter(n=>n.namespace===e):t}get(e){return this.embeddings.get(e)}cosineSimilarity(e,t){let n=0,r=0,i=0;for(let a=0;a<e.length;a++)n+=e[a]*t[a],r+=e[a]*e[a],i+=t[a]*t[a];let s=Math.sqrt(r)*Math.sqrt(i);return s===0?0:n/s}euclideanDistance(e,t){let n=0;for(let r=0;r<e.length;r++){let i=e[r]-t[r];n+=i*i}return Math.sqrt(n)}poincareDistance(e,t,n=-1){let r=Math.abs(n),i=Math.sqrt(r),s=e.reduce((p,g)=>p+g*g,0),a=t.reduce((p,g)=>p+g*g,0),o=0;for(let p=0;p<e.length;p++){let g=e[p]-t[p];o+=g*g}let l=2*o,c=(1-s)*(1-a);if(c<=0)return 1/0;let d=l/c;return Math.acosh(1+d)/i}async searchBatch(e,t={}){let n=[];for(let r of e){let i=await this.search(r,t);n.push(i)}return n}async findInRadius(e,t,n="cosine"){return this.search(e,{metric:n,threshold:t,topK:this.embeddings.size})}};var xe=class{config;constructor(e={}){if(this.config={curvature:e.curvature??-1,epsilon:e.epsilon??1e-7},this.config.curvature>=0)throw new O("HYPERBOLIC_ERROR","Curvature must be negative for hyperbolic space")}euclideanToPoincare(e){if(e.isHyperbolic)return e;let t=e.vector,n=this.norm(t);if(n<this.config.epsilon)return{...e,isHyperbolic:!0};let r=Math.abs(this.config.curvature),i=Math.sqrt(r),s=Math.tanh(i*n/2)/(i*n),a=t.map(l=>l*s),o=this.norm(a);if(o>=1-this.config.epsilon)throw new O("HYPERBOLIC_ERROR",`Poincar\xE9 ball constraint violated: norm = ${o}`);return{vector:a,dimensions:e.dimensions,model:e.model,isHyperbolic:!0}}poincareToEuclidean(e){if(!e.isHyperbolic)return e;let t=e.vector,n=this.norm(t);if(n<this.config.epsilon)return{...e,isHyperbolic:!1};let r=Math.abs(this.config.curvature),i=Math.sqrt(r),s=i*n;if(s>=1)throw new O("HYPERBOLIC_ERROR","Point is on or outside Poincar\xE9 ball boundary");let a=2/i*Math.atanh(s)/n;return{vector:t.map(l=>l*a),dimensions:e.dimensions,model:e.model,isHyperbolic:!1}}distance(e,t){if(e.dimensions!==t.dimensions)throw new O("DIMENSION_MISMATCH","Embeddings must have same dimensions");if(!e.isHyperbolic||!t.isHyperbolic)throw new O("HYPERBOLIC_ERROR","Both embeddings must be in hyperbolic space");let n=e.vector,r=t.vector,i=Math.abs(this.config.curvature),s=Math.sqrt(i),a=this.normSquared(n),o=this.normSquared(r),c=2*this.euclideanDistanceSquared(n,r),d=(1-a)*(1-o);if(d<=this.config.epsilon)return 1/0;let m=c/d;return Math.acosh(1+m)/s}midpoint(e,t){if(e.dimensions!==t.dimensions)throw new O("DIMENSION_MISMATCH","Embeddings must have same dimensions");if(!e.isHyperbolic||!t.isHyperbolic)throw new O("HYPERBOLIC_ERROR","Both embeddings must be in hyperbolic space");let n=e.vector,r=t.vector;return{vector:this.mobiusAddition(n,this.mobiusScalarMultiply(this.mobiusAddition(this.mobiusNegate(n),r),.5)),dimensions:e.dimensions,model:e.model,isHyperbolic:!0}}mobiusAddition(e,t){let n=Math.abs(this.config.curvature),r=this.dot(e,t),i=this.normSquared(e),s=this.normSquared(t),a=1+2*n*r+n*s,o=1-n*i,l=1+2*n*r+n*n*i*s;if(Math.abs(l)<this.config.epsilon)throw new O("HYPERBOLIC_ERROR","M\xF6bius addition denominator is zero");return e.map((d,m)=>(a*d+o*t[m])/l)}mobiusScalarMultiply(e,t){let n=Math.abs(this.config.curvature),r=Math.sqrt(n),i=this.norm(e);if(i<this.config.epsilon)return e;let s=r*i;if(Math.abs(s)>=1)throw new O("HYPERBOLIC_ERROR","M\xF6bius scalar multiplication out of bounds");let a=Math.tanh(t*Math.atanh(s))/(r*i);return e.map(o=>o*a)}mobiusNegate(e){return e.map(t=>-t)}projectToBall(e){let t=this.norm(e);if(t>=1-this.config.epsilon){let n=(1-this.config.epsilon)/t;return e.map(r=>r*n)}return e}norm(e){return Math.sqrt(this.normSquared(e))}normSquared(e){return e.reduce((t,n)=>t+n*n,0)}dot(e,t){return e.reduce((n,r,i)=>n+r*t[i],0)}euclideanDistanceSquared(e,t){return e.reduce((n,r,i)=>{let s=r-t[i];return n+s*s},0)}updateConfig(e){if(e.curvature!==void 0&&e.curvature>=0)throw new O("HYPERBOLIC_ERROR","Curvature must be negative");this.config={...this.config,...e}}getConfig(){return{...this.config}}};ee();var Be=class{generator;search;hyperbolic;isInitialized=!1;constructor(e={}){this.generator=new we(e.embedding),this.search=new Re,this.hyperbolic=new xe(e.hyperbolic),e.autoInitialize!==!1&&this.initialize().catch(t=>{console.error("Failed to auto-initialize ONNX embeddings:",t)})}async initialize(){if(!this.isInitialized)try{await this.generator.initialize(),this.isInitialized=!0}catch(e){throw new O("RUNTIME_UNAVAILABLE","Failed to initialize ONNX embeddings adapter",e)}}async getHealth(){try{let e=this.generator.isReady();return{available:e,modelLoaded:e?this.getStats().currentModel:null,system:{memory:process.memoryUsage().heapUsed,threads:1}}}catch(e){return{available:!1,modelLoaded:null,error:e instanceof Error?e.message:"Unknown error",system:{memory:process.memoryUsage().heapUsed,threads:0}}}}async generateEmbedding(e){return await this.ensureInitialized(),this.generator.generate(e)}async generateBatch(e){return await this.ensureInitialized(),this.generator.generateBatch(e)}async generateAndStore(e,t){let n=await this.generateEmbedding(e),r={id:t?.id??this.generateId(),text:e,embedding:n,namespace:t?.namespace,metadata:t?.customData,createdAt:Date.now()};this.search.store(r);try{let i=$();await i.initialize(),await i.vectorStore(r.id,r.embedding.vector,r.namespace??"onnx",{text:r.text,customData:r.metadata,createdAt:r.createdAt})}catch{}return r}async searchByText(e,t){let n=await this.generateEmbedding(e);return this.search.search(n,t)}async searchByEmbedding(e,t){return this.search.search(e,t)}async findMostSimilar(e,t){let n=await this.generateEmbedding(e);return this.search.findMostSimilar(n,t)}async compareSimilarity(e,t,n="cosine"){let[r,i]=await this.generateBatch({texts:[e,t]}).then(s=>s.embeddings);return this.search.calculateSimilarity(r.vector,i.vector,n)}storeEmbedding(e){this.search.store(e)}storeBatch(e){this.search.storeBatch(e)}removeEmbedding(e){return this.search.remove(e)}getEmbedding(e){return this.search.get(e)}getAllEmbeddings(e){return this.search.getAll(e)}clearEmbeddings(){this.search.clear()}toHyperbolic(e){return this.hyperbolic.euclideanToPoincare(e)}toEuclidean(e){return this.hyperbolic.poincareToEuclidean(e)}hyperbolicDistance(e,t){return this.hyperbolic.distance(e,t)}hyperbolicMidpoint(e,t){return this.hyperbolic.midpoint(e,t)}projectToBall(e){return this.hyperbolic.projectToBall(e)}getStats(){let e=this.generator.getStats(),t=this.search.getStats();return{totalGenerated:e.totalGenerated??0,cacheHits:e.cacheHits??0,cacheMisses:e.cacheMisses??0,totalSearches:t.searchCount,avgGenerationTime:e.avgGenerationTime??0,avgSearchTime:t.avgSearchTime,currentModel:e.currentModel??"all-MiniLM-L6-v2",vectorsStored:t.storedCount}}updateEmbeddingConfig(e){this.generator.updateConfig(e)}updateHyperbolicConfig(e){this.hyperbolic.updateConfig(e)}clearCaches(){this.generator.clearCache()}reset(){this.clearCaches(),this.clearEmbeddings()}async bridgeToMCPGenerate(e,t=!1){let n=await this.generateEmbedding(e);return t?this.toHyperbolic(n):n}async bridgeToMCPSearch(e,t){return this.searchByText(e,t)}async bridgeToMCPCompare(e,t,n="cosine"){return this.compareSimilarity(e,t,n)}async ensureInitialized(){this.isInitialized||await this.initialize()}generateId(){return`emb_${Date.now()}_${ua().slice(0,9)}`}isReady(){return this.isInitialized&&this.generator.isReady()}};function xt(u){return new Be(u)}var kn={enabled:!0,dbPath:".agentic-qe/memory.db",maxOutcomes:1e5,retentionDays:90,autoCleanup:!0,cleanupIntervalMs:3600*1e3};ee();k();U();var va={enabled:!0,haikuThreshold:.8,sonnetThreshold:.4,includeHealthSnapshot:!1,enableLogging:!0},Mn=class{config;minCutService;constructor(e){this.config={...va,...e},this.minCutService=ei()}route(e){let t=Date.now();if(!this.config.enabled)return this.createFallbackResult(e,t,"MinCut routing disabled");let n=e.agentTopology||this.config.defaultTopology;if(!n||n.length===0)return this.createFallbackResult(e,t,"No agent topology available for mincut analysis");try{let r=this.minCutService.computeRoutingTier(e.task,n),i=this.routingTierToModelTier(r.tier);e.isCritical&&i<2&&(i=2);let s=this.modelTierToLabel(i),a;if(this.config.includeHealthSnapshot){let c=e.taskGraph||this.minCutService.buildTaskGraphFromTopology(n);a=this.minCutService.getStructuralHealth(c)}let o=Date.now()-t,l={modelTier:i,tierLabel:s,lambda:r.lambda,normalizedLambda:r.normalizedLambda,confidence:r.confidence,rationale:r.rationale,usedMinCut:!0,healthSnapshot:a,decisionTimeMs:o};return this.config.enableLogging&&this.logDecision(l),l}catch(r){return this.createFallbackResult(e,t,`MinCut routing error: ${r instanceof Error?r.message:String(r)}`)}}getMinCutService(){return this.minCutService}isEnabled(){return this.config.enabled}routingTierToModelTier(e){switch(e){case 1:return 1;case 2:return 2;case 3:return 4;default:return 2}}modelTierToLabel(e){switch(e){case 0:return"Booster";case 1:return"Haiku";case 2:return"Sonnet";case 3:return"Sonnet-Extended";case 4:return"Opus";default:return"Sonnet"}}createFallbackResult(e,t,n){return{modelTier:(e.isCritical,2),tierLabel:"Sonnet",lambda:0,normalizedLambda:0,confidence:.3,rationale:`Fallback to Sonnet: ${n}`,usedMinCut:!1,decisionTimeMs:Date.now()-t}}logDecision(e){let t=e.usedMinCut?"MinCut":"Fallback";console.error(`[MinCutRouter] [${t}] Tier ${e.modelTier} (${e.tierLabel}) | Lambda: ${e.normalizedLambda.toFixed(3)} | Confidence: ${(e.confidence*100).toFixed(0)}% | Time: ${e.decisionTimeMs}ms`)}};function ii(u){return new Mn(u)}import{existsSync as ba}from"fs";import{join as Ca}from"path";var Pt=class{id="memory";name="Pattern Memory";priority=80;maxTokens=2e3;async gather(e){let t=[];try{let n=Ca(process.cwd(),".agentic-qe","memory.db");if(!ba(n))return this.fallbackGather(e);let{openDatabase:r}=await import("./safe-db-CCKCBZ5I.js"),i=r(n,{readonly:!0});try{let s=this.extractDomainKeywords(e.taskDescription);if(s.length>0){let a=s.map(()=>"domain LIKE ?").join(" OR "),o=s.map(d=>`%${d}%`),c=i.prepare(`SELECT name, domain, description, confidence
|
|
284
284
|
FROM qe_patterns
|
|
285
285
|
WHERE ${a}
|
|
286
286
|
ORDER BY confidence DESC
|
|
@@ -293,7 +293,7 @@ ${r}`;t.push({sourceId:this.id,title:`Git history: ${n}`,content:i,estimatedToke
|
|
|
293
293
|
${a.join(`
|
|
294
294
|
`)}`;t.push({sourceId:this.id,title:`Tests: ${Dn(n)}`,content:o,estimatedTokens:Math.ceil(o.length/3.5),relevance:.8})}}catch{}}return t}findTestPaths(e){let t=Dn(e).replace(/\.(ts|js|tsx|jsx)$/,""),n=wa(e),r=[".test.ts",".spec.ts",".test.js",".spec.js"],i=[];for(let s of r)i.push(In(n,`${t}${s}`)),i.push(In(n,"__tests__",`${t}${s}`)),i.push(In(n,"..","tests",`${t}${s}`));return i}};import{existsSync as Ra,readFileSync as xa}from"fs";import{join as _n,basename as Pa}from"path";var Mt=class{id="coverage";name="Coverage Data";priority=50;maxTokens=1e3;async gather(e){let t=[],n=[_n(process.cwd(),"coverage","coverage-summary.json"),_n(process.cwd(),"coverage","coverage-final.json"),_n(process.cwd(),".coverage","coverage-summary.json")];for(let r of n)if(Ra(r))try{let i=xa(r,"utf-8"),s=JSON.parse(i),a=[];for(let o of e.targetFiles){let l=Pa(o);for(let[c,d]of Object.entries(s))if(c.includes(l)&&d&&typeof d=="object"){let m=d,p=m.lines?.pct??m.statements?.pct,g=m.branches?.pct,h=m.functions?.pct;p!==void 0&&a.push(`${l}: lines=${p}%${g!==void 0?`, branches=${g}%`:""}${h!==void 0?`, functions=${h}%`:""}`)}}if(a.length>0){let o=`Coverage for target files:
|
|
295
295
|
${a.join(`
|
|
296
|
-
`)}`;t.push({sourceId:this.id,title:"File Coverage Data",content:o,estimatedTokens:Math.ceil(o.length/3.5),relevance:.6})}if(s.total&&typeof s.total=="object"){let o=s.total,l=`Project coverage: lines=${o.lines?.pct??"?"}%, branches=${o.branches?.pct??"?"}%, functions=${o.functions?.pct??"?"}%`;t.push({sourceId:this.id,title:"Project Coverage Summary",content:l,estimatedTokens:Math.ceil(l.length/3.5),relevance:.4})}break}catch{continue}return t}};import{existsSync as Aa}from"fs";import{join as ka}from"path";var Dt=class{id="requirements";name="Requirements Traceability";priority=75;maxTokens=2e3;async gather(e){let t=[];try{let n=ka(process.cwd(),".agentic-qe","memory.db");if(!Aa(n))return this.fallbackGather(e);let{openDatabase:r}=await import("./safe-db-
|
|
296
|
+
`)}`;t.push({sourceId:this.id,title:"File Coverage Data",content:o,estimatedTokens:Math.ceil(o.length/3.5),relevance:.6})}if(s.total&&typeof s.total=="object"){let o=s.total,l=`Project coverage: lines=${o.lines?.pct??"?"}%, branches=${o.branches?.pct??"?"}%, functions=${o.functions?.pct??"?"}%`;t.push({sourceId:this.id,title:"Project Coverage Summary",content:l,estimatedTokens:Math.ceil(l.length/3.5),relevance:.4})}break}catch{continue}return t}};import{existsSync as Aa}from"fs";import{join as ka}from"path";var Dt=class{id="requirements";name="Requirements Traceability";priority=75;maxTokens=2e3;async gather(e){let t=[];try{let n=ka(process.cwd(),".agentic-qe","memory.db");if(!Aa(n))return this.fallbackGather(e);let{openDatabase:r}=await import("./safe-db-CCKCBZ5I.js"),i=r(n,{readonly:!0});try{if(!i.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='qe_patterns'").get())return this.fallbackGather(e);let a=e.targetFiles.map(l=>`%${l.split("/").pop()}%`);if(a.length>0){let l=a.map(()=>"description LIKE ?").join(" OR "),d=i.prepare(`SELECT name, domain, description, confidence
|
|
297
297
|
FROM qe_patterns
|
|
298
298
|
WHERE domain LIKE '%requirement%'
|
|
299
299
|
AND (${l})
|
|
@@ -309,7 +309,7 @@ ${m}`,estimatedTokens:Math.ceil(m.length/3.5),relevance:.75})}}let o=this.extrac
|
|
|
309
309
|
LIMIT 5`).all(...c);if(m.length>0){let p=m.map(g=>`- **${g.name}**: ${g.description||"No description"}`).join(`
|
|
310
310
|
`);t.push({sourceId:this.id,title:"Related Requirements",content:`Requirements related to task:
|
|
311
311
|
|
|
312
|
-
${p}`,estimatedTokens:Math.ceil(p.length/3.5),relevance:.6})}}}finally{i.close()}}catch{return this.fallbackGather(e)}return t.length===0?this.fallbackGather(e):t}fallbackGather(e){let n=`No requirements traceability data found for: ${e.targetFiles.join(", ")}. Consider running requirements validation to establish traceability.`;return[{sourceId:this.id,title:"Requirements Context",content:n,estimatedTokens:Math.ceil(n.length/3.5),relevance:.3}]}extractRequirementKeywords(e){let t=[],n=e.toLowerCase(),r=n.match(/(?:req|us|story|epic|feat)-?\d+/gi)||[];t.push(...r);let i=["authentication","authorization","payment","registration","notification","search","api","login","user","admin","report","dashboard","import","export","integration"];for(let s of i)n.includes(s)&&t.push(s);return t.slice(0,5)}};import{existsSync as Ma}from"fs";import{join as Da}from"path";var It=class{id="defects";name="Defect Intelligence";priority=65;maxTokens=1500;async gather(e){let t=[];try{let n=Da(process.cwd(),".agentic-qe","memory.db");if(!Ma(n))return[];let{openDatabase:r}=await import("./safe-db-
|
|
312
|
+
${p}`,estimatedTokens:Math.ceil(p.length/3.5),relevance:.6})}}}finally{i.close()}}catch{return this.fallbackGather(e)}return t.length===0?this.fallbackGather(e):t}fallbackGather(e){let n=`No requirements traceability data found for: ${e.targetFiles.join(", ")}. Consider running requirements validation to establish traceability.`;return[{sourceId:this.id,title:"Requirements Context",content:n,estimatedTokens:Math.ceil(n.length/3.5),relevance:.3}]}extractRequirementKeywords(e){let t=[],n=e.toLowerCase(),r=n.match(/(?:req|us|story|epic|feat)-?\d+/gi)||[];t.push(...r);let i=["authentication","authorization","payment","registration","notification","search","api","login","user","admin","report","dashboard","import","export","integration"];for(let s of i)n.includes(s)&&t.push(s);return t.slice(0,5)}};import{existsSync as Ma}from"fs";import{join as Da}from"path";var It=class{id="defects";name="Defect Intelligence";priority=65;maxTokens=1500;async gather(e){let t=[];try{let n=Da(process.cwd(),".agentic-qe","memory.db");if(!Ma(n))return[];let{openDatabase:r}=await import("./safe-db-CCKCBZ5I.js"),i=r(n,{readonly:!0});try{if(!i.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='qe_patterns'").get())return[];let a=e.targetFiles.map(l=>`%${l.split("/").pop()}%`);if(a.length>0){let l=a.map(()=>"description LIKE ?").join(" OR "),d=i.prepare(`SELECT name, domain, description, confidence
|
|
313
313
|
FROM qe_patterns
|
|
314
314
|
WHERE domain LIKE '%defect%'
|
|
315
315
|
AND (${l})
|
|
@@ -435,7 +435,7 @@ ${e.recommendations.length===0?"No recommendations - all quality gates passed.":
|
|
|
435
435
|
`),E=y.startsWith(r)?y.slice(r.length).replace(/^\//,""):y,S=[{regex:/\w*(?:secret|password|passwd|api_key|apikey|private_key|jwt_secret)\w*\s*[=:]\s*['"][^'"]{4,}['"]/gi,title:"Hardcoded secret",severity:"critical"},{regex:/\w*(?:token|auth_token|access_key|secret_key)\w*\s*[=:]\s*['"][^'"]{8,}['"]/gi,title:"Hardcoded credential",severity:"critical"},{regex:/(?:AWS_SECRET|GITHUB_TOKEN|SLACK_TOKEN|OPENAI_API_KEY)\s*[=:]\s*['"][^'"]+['"]/gi,title:"Hardcoded cloud credential",severity:"critical"}];for(let D of S)for(let G=0;G<b.length;G++){let H=[...b[G].matchAll(D.regex)];for(let K of H)o.push({title:D.title,severity:D.severity,location:{file:E,line:G+1},description:`Potential hardcoded secret found at line ${G+1}`,category:"sensitive-data"})}let T=/(?:execute|query|cursor\.execute)\s*\(\s*(?:f['"]|['"].*%s|['"].*\+\s*\w)/gi;for(let D=0;D<b.length;D++)T.test(b[D])&&o.push({title:"Potential SQL injection",severity:"high",location:{file:E,line:D+1},description:"String interpolation in SQL query \u2014 use parameterized queries",category:"injection"}),T.lastIndex=0;let R=[/allow_origins\s*=\s*\[?\s*['"]?\*['"]?\s*\]?/i,/cors\(\s*\{[^}]*origin:\s*['"]?\*['"]?/i,/Access-Control-Allow-Origin['":\s]+\*/i,/@CrossOrigin\(\s*origins?\s*=\s*["']\*["']/i,/\.Header\(\)\.Set\(["']Access-Control-Allow-Origin["'],\s*["']\*["']/i];for(let D of R)if(D.test(C)){o.push({title:"CORS wildcard origin",severity:"high",location:{file:E,line:b.findIndex(G=>D.test(G))+1},description:"CORS configured with wildcard (*) origin \u2014 restrict to specific domains",category:"security-misconfiguration"});break}/(?:DEBUG|debug)\s*[=:]\s*(?:True|true|1)/i.test(C)&&o.push({title:"Debug mode enabled",severity:"medium",location:{file:E,line:b.findIndex(D=>/DEBUG\s*[=:]\s*(?:True|true|1)/i.test(D))+1},description:"Debug mode should be disabled in production",category:"security-misconfiguration"}),/\b(?:eval|exec)\s*\(/i.test(C)&&o.push({title:"Dangerous eval/exec usage",severity:"high",location:{file:E,line:b.findIndex(D=>/\b(?:eval|exec)\s*\(/.test(D))+1},description:"eval/exec can lead to code injection \u2014 avoid using with user input",category:"injection"})}catch{}let l=["requirements.txt","pyproject.toml","Gemfile","go.mod","Cargo.toml"];for(let y of l){let C=pi.join(r,y);try{let b=await $n.readFile(C,"utf-8");if(o.push({title:"Dependency audit recommended",severity:"informational",location:{file:y,line:1},description:`Found ${y} \u2014 run language-specific dependency audit (e.g., pip-audit, npm audit, cargo audit)`,category:"dependencies"}),y==="requirements.txt"||y==="pyproject.toml"){let E=[{pkg:"python-jose",pattern:/python-jose/i,cve:"CVE-2024-33663",severity:"high",title:"python-jose ECDSA key confusion (CVE-2024-33663)",description:"python-jose allows ECDSA key confusion \u2014 upgrade to >=3.3.0 or switch to PyJWT"},{pkg:"python-jose",pattern:/python-jose/i,cve:"CVE-2024-33664",severity:"high",title:"python-jose JWT algorithm confusion (CVE-2024-33664)",description:"python-jose JWT algorithm confusion vulnerability \u2014 upgrade or switch to PyJWT"},{pkg:"python-multipart",pattern:/python-multipart/i,cve:"CVE-2026-24486",severity:"critical",title:"python-multipart DoS (CVE-2026-24486)",description:"python-multipart denial of service via crafted multipart data \u2014 upgrade to >=0.0.18"}];for(let S of E)S.pattern.test(b)&&o.push({title:S.title,severity:S.severity,location:{file:y,line:b.split(`
|
|
436
436
|
`).findIndex(T=>S.pattern.test(T))+1},description:S.description,category:"dependencies"})}}catch{}}let c=s.map(y=>Or.create(y)),d=null;if(t.sast!==!1&&c.length>0){let y=await n.scanFiles(c);y.success&&(d=y.value)}let m=null;if(t.dast&&t.targetUrl){let y=await n.scanUrl(t.targetUrl,{activeScanning:!0,maxDepth:3,timeout:3e4});y.success&&(m=y.value)}let p={critical:o.filter(y=>y.severity==="critical").length,high:o.filter(y=>y.severity==="high").length,medium:o.filter(y=>y.severity==="medium").length,low:o.filter(y=>y.severity==="low").length,informational:o.filter(y=>y.severity==="informational").length},g={critical:(d?.summary?.critical||0)+(m?.summary?.critical||0)+p.critical,high:(d?.summary?.high||0)+(m?.summary?.high||0)+p.high,medium:(d?.summary?.medium||0)+(m?.summary?.medium||0)+p.medium,low:(d?.summary?.low||0)+(m?.summary?.low||0)+p.low,informational:(d?.summary?.informational||0)+(m?.summary?.informational||0)+p.informational},h=[...d?.vulnerabilities||[],...m?.vulnerabilities||[],...o],f=h.sort((y,C)=>{let b={critical:0,high:1,medium:2,low:3,informational:4};return b[y.severity]-b[C.severity]}).slice(0,10).map(y=>({type:y.title,severity:y.severity,file:y.location.file,line:y.location.line,description:y.description})),v=di(h);return I({vulnerabilities:h.length,critical:g.critical,high:g.high,medium:g.medium,low:g.low,informational:g.informational,topVulnerabilities:f,recommendations:v,scanTypes:{sast:t.sast!==!1,dast:t.dast||!1},filesScanned:i.length,jstsFilesScanned:s.length,otherFilesScanned:a.length,coverage:d?.coverage,...a.length>0&&s.length===0?{note:"Non-JS/TS files were scanned with cross-language pattern matching. For deeper analysis, use language-specific security tools."}:{}})}catch(n){return q(z(n))}})}k();function Un(u){u.registerHandler("assess-quality",async e=>{let t=e.payload;try{let n=u.getQualityAnalyzer(),r=t.threshold||80,i=[];if(t.sourceFiles&&t.sourceFiles.length>0)i=t.sourceFiles;else if(t.target)i=await te(t.target,{includeTests:!1});else{let c=await import("path"),d=await import("fs"),m=c.join(process.cwd(),"src"),p=d.existsSync(m)?m:process.cwd();i=await te(p,{includeTests:!1})}if(i.length===0)return I({qualityScore:0,passed:!1,threshold:r,metrics:{coverage:0,complexity:0,maintainability:0,testability:0},recommendations:["No source files found for quality assessment"],warning:"No source files found"});let s=await n.analyzeQuality({sourceFiles:i,includeMetrics:t.metrics||["coverage","complexity","maintainability","testability"]});if(!s.success)return s;let a=s.value,o=a.score.overall>=r,l={};for(let c of a.metrics)l[c.name]=c.value;return I({qualityScore:a.score.overall,passed:o,threshold:r,metrics:{coverage:a.score.coverage,complexity:a.score.complexity,maintainability:a.score.maintainability,security:a.score.security,...l},recommendations:a.recommendations.map(c=>`[${c.type}] ${c.title}: ${c.description}`),trends:a.trends.map(c=>({metric:c.metric,direction:c.direction,dataPoints:c.dataPoints.length})),filesAnalyzed:i.length})}catch(n){return q(z(n))}})}import*as gi from"fs/promises";k();function Hn(u){u.registerHandler("validate-requirements",async e=>{let t=e.payload;try{let n=t.requirementsPath||process.cwd(),r=await te(n,{includeTests:!1,languages:[]}),i=[".md",".feature",".gherkin",".txt",".rst"],s=[];for(let a of r)i.some(o=>a.endsWith(o))&&s.push(a);return I({requirementsAnalyzed:s.length,testable:0,ambiguous:0,untestable:0,coverage:0,bddScenarios:[],warning:s.length===0?"No requirement files (.md, .feature, .gherkin) found. Provide requirementsPath or add requirement docs.":"Requirements validation requires LLM analysis. File inventory returned \u2014 use task_orchestrate for deep analysis.",files:s.map(a=>a.startsWith(n)?a.slice(n.length+1):a).slice(0,20)})}catch(n){return q(z(n))}}),u.registerHandler("validate-contracts",async e=>{let t=e.payload;try{if(!t.contractPath)return I({contractPath:"",valid:!1,breakingChanges:[],warnings:[],coverage:0,error:"contractPath is required. Provide a path to an OpenAPI spec, JSON Schema, or Protocol Buffer file."});try{let n=await gi.readFile(t.contractPath,"utf-8"),r=t.contractPath.endsWith(".json"),i=t.contractPath.endsWith(".yaml")||t.contractPath.endsWith(".yml");return r&&JSON.parse(n),I({contractPath:t.contractPath,valid:!0,format:r?"json":i?"yaml":"unknown",breakingChanges:[],warnings:[],linesAnalyzed:n.split(`
|
|
437
437
|
`).length,note:"Structural validation passed. For semantic contract testing, use consumer-driven contract tests."})}catch(n){return I({contractPath:t.contractPath,valid:!1,breakingChanges:[],warnings:[],error:`Could not read or parse contract file: ${w(n)}`})}}catch(n){return q(z(n))}})}import*as hi from"fs/promises";import*as fi from"path";k();function jn(u){u.registerHandler("index-code",async e=>{let t=e.payload;try{let n=u.getKnowledgeGraph(),r=t.target||process.cwd(),i=Date.now(),s=await te(r,{includeTests:t.includeTests!==!1,languages:t.languages});if(s.length===0)return I({filesIndexed:0,nodesCreated:0,edgesCreated:0,target:r,incremental:t.incremental||!1,languages:t.languages||[],duration:Date.now()-i,warning:`No source files found in ${r}. Searched for: TypeScript, JavaScript, Python, Go, Rust, Java, Ruby, C/C++, and more.`});let a=await n.index({paths:s,incremental:t.incremental||!1,includeTests:t.includeTests!==!1,languages:t.languages});if(!a.success)return a;let o=a.value,l=new Set,c={ts:"typescript",tsx:"typescript",js:"javascript",jsx:"javascript",mjs:"javascript",cjs:"javascript",py:"python",pyw:"python",go:"go",rs:"rust",java:"java",kt:"kotlin",kts:"kotlin",rb:"ruby",cs:"csharp",php:"php",swift:"swift",c:"c",h:"c",cpp:"cpp",hpp:"cpp",cc:"cpp",scala:"scala"};for(let d of s){let m=fi.extname(d).slice(1),p=c[m];p&&l.add(p)}return I({filesIndexed:o.filesIndexed,nodesCreated:o.nodesCreated,edgesCreated:o.edgesCreated,target:r,incremental:t.incremental||!1,languages:Array.from(l),duration:o.duration,errors:o.errors})}catch(n){return q(z(n))}}),u.registerHandler("predict-defects",async e=>{let t=e.payload;try{let n=t.target||process.cwd(),r=t.minConfidence||.5,i=await te(n,{includeTests:!1});if(i.length===0)return I({predictedDefects:[],riskScore:0,recommendations:[`No source files found in ${n}. Ensure the path contains source code files.`],warning:`No source files found in ${n}`,filesAnalyzed:0});let s=[];for(let c of i)try{let d=await hi.readFile(c,"utf-8"),m=d.split(`
|
|
438
|
-
`),p=m.length,g=0,h=[];p>500?(g+=.25,h.push(`Large file (${p} lines)`)):p>300&&(g+=.15,h.push(`Medium-large file (${p} lines)`));let f=d.match(/\b(if|else|switch|case|for|while|catch|&&|\|\|)\b/g)||[],v=f.length/Math.max(p,1);v>.15?(g+=.25,h.push(`High branch density (${f.length} branches in ${p} lines)`)):v>.08&&(g+=.1,h.push("Moderate branch complexity")),Math.max(...m.map(E=>{let S=E.match(/^(\s*)/);return S?S[1].length:0}))>20&&(g+=.15,h.push("Deep nesting detected"));let C=(d.match(/\b(TODO|FIXME|HACK|XXX|WORKAROUND)\b/gi)||[]).length;C>3&&(g+=.15,h.push(`${C} technical debt markers`));let b=(d.match(/\b(function|def|func|async)\b/g)||[]).length;if(b>0&&p/b>80&&(g+=.1,h.push("Potentially long functions")),g=Math.min(g,.95),g>=r){let E=c.startsWith(n)?c.slice(n.length).replace(/^\//,""):c;s.push({file:E,probability:Math.round(g*100)/100,reason:h.join("; ")})}}catch{}s.sort((c,d)=>d.probability-c.probability);let a=s.length>0?s.reduce((c,d)=>c+d.probability,0)/s.length:0,o=Math.round(a*100),l=[];if(s.length>0){l.push(`${s.length} files flagged for potential defects out of ${i.length} analyzed`);let c=s[0];l.push(`Highest risk: ${c.file} (${Math.round(c.probability*100)}%) \u2014 ${c.reason}`)}return s.some(c=>c.reason.includes("Large file"))&&l.push("Consider splitting large files to reduce complexity"),s.some(c=>c.reason.includes("technical debt"))&&l.push("Address TODO/FIXME comments to reduce technical debt"),s.length===0&&l.push("No files exceeded the defect probability threshold \u2014 code looks healthy"),I({predictedDefects:s.slice(0,20),riskScore:o,recommendations:l,filesAnalyzed:i.length})}catch(n){return q(z(n))}})}function Vn(u){u.registerHandler("test-accessibility",async e=>{let t=e.payload;return I({url:t.url||"",standard:t.standard||"wcag21-aa",passed:!1,violations:[],warnings:[],score:0,note:"Accessibility testing requires a browser environment (Puppeteer/Playwright). Use tools like axe-core, pa11y, or Lighthouse CLI for WCAG compliance testing. Example: npx pa11y "+(t.url||"<url>")})}),u.registerHandler("run-chaos",async e=>{let t=e.payload;return I({faultType:t.faultType||"unknown",target:t.target||"unknown",dryRun:t.dryRun??!0,duration:t.duration||0,systemBehavior:"not-executed",resilience:null,note:"Chaos engineering requires infrastructure-level fault injection. Use tools like Chaos Monkey, Litmus, or toxiproxy for real resilience testing. For Node.js apps, consider: nock (HTTP faults), testcontainers (dependency failures)."})}),u.registerHandler("optimize-learning",async e=>{try{let t=await import("./unified-memory-hnsw-TMN2L77W.js");return I({patternsLearned:0,modelsUpdated:0,memoryConsolidated:!1,note:'Learning optimization runs during the dream cycle (SessionEnd hook). Use "npx agentic-qe hooks session-end --save-state" to trigger pattern consolidation.'})}catch{return I({patternsLearned:0,modelsUpdated:0,memoryConsolidated:!1,note:'Learning system not initialized. Run "aqe init --auto" first.'})}})}var re=ye("TaskExecutor");function Wa(u){return Te.resolve(Ce.CoverageAnalyzerService)(u)}function Ka(u){return Te.resolve(Ce.SecurityScannerService)(u)}function Xa(u){return Te.resolve(Ce.createTestGeneratorService)(u)}function Ya(u){return Te.resolve(Ce.KnowledgeGraphService)(u)}function Ja(u){return Te.resolve(Ce.QualityAnalyzerService)(u)}function Ei(u){switch(u){case 0:return"agent-booster";case 1:return"claude-3-5-haiku-20241022";case 2:return"claude-sonnet-4-20250514";case 3:return"claude-sonnet-4-20250514";case 4:return"claude-opus-4-5-20251101";default:return"claude-sonnet-4-20250514"}}function Za(u){if(["generate-tests","analyze-coverage","scan-security","execute-tests","assess-quality","validate-contracts","test-accessibility","chaos-test","predict-defects","validate-requirements","index-code"].includes(u.type))return null;let t=u.payload?.codeContext||"",n=u.payload?.sourceCode||"",r=t||n;return r?r.includes("var ")&&!r.includes("const ")&&!r.includes("let ")?"var-to-const":r.includes("console.log")||r.includes("console.warn")||r.includes("console.error")?"remove-console":r.includes(".then(")&&r.includes(".catch(")?"promise-to-async":r.includes("require(")&&!r.includes("import ")?"cjs-to-esm":r.includes("function ")&&!r.includes("=>")?"func-to-arrow":null:null}var Wn=class{constructor(e,t,n){this.kernel=e;this.eventBus=t;this._config={timeout:n?.timeout??3e5,maxRetries:n?.maxRetries??3,enableCaching:n?.enableCaching??!0,saveResults:n?.saveResults??!0,resultsDir:n?.resultsDir??".agentic-qe",defaultLanguage:n?.defaultLanguage??"typescript",defaultFramework:n?.defaultFramework??"vitest"},this.resultSaver=ai(this._config.resultsDir),this.registerHandlers()}_config;resultSaver;coverageAnalyzer=null;securityScanner=null;testGenerator=null;knowledgeGraph=null;qualityAnalyzer=null;agentBooster=null;taskRouter=null;qualityFeedbackLoop=null;coherenceActionGate=null;taskHandlers=new Map;get config(){return this._config}registerHandler(e,t){this.taskHandlers.set(e,t)}setQualityFeedbackLoop(e){this.qualityFeedbackLoop=e}getCoverageAnalyzer(){return this.coverageAnalyzer||(this.coverageAnalyzer=Wa(this.kernel.memory)),this.coverageAnalyzer}getSecurityScanner(){return this.securityScanner||(this.securityScanner=Ka(this.kernel.memory)),this.securityScanner}getTestGenerator(){return this.testGenerator||(this.testGenerator=Xa(this.kernel.memory)),this.testGenerator}getKnowledgeGraph(){return this.knowledgeGraph||(this.knowledgeGraph=Ya(this.kernel.memory)),this.knowledgeGraph}getQualityAnalyzer(){return this.qualityAnalyzer||(this.qualityAnalyzer=Ja(this.kernel.memory)),this.qualityAnalyzer}registerHandlers(){qn(this),zn(this),Bn(this),Un(this),Hn(this),jn(this),Vn(this)}async getAgentBooster(){return this.agentBooster||(this.agentBooster=await ft({enabled:!0,fallbackToLLM:!0,confidenceThreshold:.7})),this.agentBooster}async getTaskRouterInstance(){if(!this.taskRouter)try{this.taskRouter=await Ot()}catch{return null}return this.taskRouter}async executeWithAgentBooster(e,t,n){let r=Za(e);if(!r)return console.debug(`[TaskExecutor] No applicable Agent Booster transform for task ${e.id}`),null;try{let i=await this.getAgentBooster(),s=e.payload?.codeContext||e.payload?.sourceCode||"",a=await i.transform(s,r);return a.success&&a.confidence>=.7?(console.debug(`[TaskExecutor] Agent Booster transform succeeded: ${r}, confidence=${a.confidence}`),{taskId:e.id,success:!0,data:{transformed:!0,transformType:r,originalCode:a.originalCode,transformedCode:a.transformedCode,confidence:a.confidence,implementationUsed:a.implementationUsed,durationMs:a.durationMs,changeCount:a.changeCount,tier:0,model:"agent-booster"},duration:Date.now()-t,domain:n}):(console.debug(`[TaskExecutor] Agent Booster low confidence (${a.confidence}), falling back to Tier 1`),null)}catch(i){return console.warn(`[TaskExecutor] Agent Booster error, falling back: ${i}`),null}}async recordOutcome(e,t,n,r){try{if(!await this.getTaskRouterInstance())return;if(console.debug(`[TaskExecutor] Outcome recorded: task=${e.id}, tier=${t}, model=${Ei(t)}, success=${n}, duration=${r}ms`),this.qualityFeedbackLoop){let s=e.targetDomains||[];await this.qualityFeedbackLoop.recordRoutingOutcome({taskId:e.id,taskDescription:e.type,recommendedAgent:String(t),usedAgent:String(t),followedRecommendation:!0,success:n,qualityScore:n?.8:.2,durationMs:r,timestamp:new Date,error:n?void 0:"Task execution failed"})}}catch(i){console.warn("[TaskExecutor] Failed to record outcome:",i)}}async execute(e){let t=Date.now(),n=this.getTaskDomain(e.type),r=e.payload,i=r?.routingTier??2,s=r?.useAgentBooster??!1,a=r?.compiledContext??void 0,o=Ei(i);a&&e.payload&&(e.payload.__compiledContext=a),console.debug(`[TaskExecutor] Executing task ${e.id}: type=${e.type}, tier=${i}, model=${o}, useAgentBooster=${s}${a?", hasContext=true":""}`);let l=this.evaluateCoherenceGate(e,n);l&&console.debug(`[TaskExecutor] Coherence gate: task=${e.id}, decision=${l.decision}, combined=${l.combinedScore.toFixed(3)}, advisory=${l.advisory}`),this.validateWithReasoningQEC(e,n);try{if(i===0||s){let p=await this.executeWithAgentBooster(e,t,n);if(p)return this.recordOutcome(e,0,!0,Date.now()-t).catch(g=>{re.warn("recordOutcome failed",{error:g instanceof Error?g.message:String(g),taskId:e.id})}),await this.publishTaskCompleted(e.id,p.data,n),p;console.debug(`[TaskExecutor] Agent Booster fallback to Tier 1 for task ${e.id}`)}let c=this.taskHandlers.get(e.type);if(!c){let p={taskId:e.id,success:!1,error:`No handler registered for task type: ${e.type}`,duration:Date.now()-t,domain:n};return this.recordOutcome(e,i,!1,Date.now()-t).catch(g=>{re.warn("recordOutcome failed",{error:g instanceof Error?g.message:String(g),taskId:e.id})}),p}let d=await Promise.race([c(e),this.timeout(e.timeout||this._config.timeout)]);if(!d.success){let p="error"in d?d.error.message:"Unknown error";return await this.publishTaskFailed(e.id,p,n),this.recordOutcome(e,i,!1,Date.now()-t).catch(g=>{re.warn("recordOutcome failed",{error:g instanceof Error?g.message:String(g),taskId:e.id})}),{taskId:e.id,success:!1,error:p,duration:Date.now()-t,domain:n}}await this.publishTaskCompleted(e.id,d.value,n),this.recordOutcome(e,i,!0,Date.now()-t).catch(p=>{re.warn("recordOutcome failed",{error:p instanceof Error?p.message:String(p),taskId:e.id})});let m;if(this._config.saveResults)try{let p={language:r?.language||this._config.defaultLanguage,framework:r?.framework||this._config.defaultFramework,includeSecondary:!0};m=(await this.resultSaver.save(e.id,e.type,d.value,p)).files.map(h=>h.path)}catch(p){console.error(`[TaskExecutor] Failed to save results: ${p}`)}return{taskId:e.id,success:!0,data:{...d.value,_routing:{tier:i,model:o,usedAgentBooster:!1}},duration:Date.now()-t,domain:n,savedFiles:m}}catch(c){let d=w(c);return await this.publishTaskFailed(e.id,d,n),this.recordOutcome(e,i,!1,Date.now()-t).catch(m=>{re.warn("recordOutcome failed",{error:m instanceof Error?m.message:String(m),taskId:e.id})}),{taskId:e.id,success:!1,error:d,duration:Date.now()-t,domain:n}}}async resetServiceCaches(){if(this.coverageAnalyzer=null,this.securityScanner=null,this.testGenerator=null,this.knowledgeGraph=null,this.qualityAnalyzer=null,this.coherenceActionGate=null,this.agentBooster){try{await this.agentBooster.dispose()}catch(e){console.debug("[TaskExecutor] Agent Booster disposal error:",e instanceof Error?e.message:e)}this.agentBooster=null}this.taskRouter=null}resetServiceCachesSync(){this.coverageAnalyzer=null,this.securityScanner=null,this.testGenerator=null,this.knowledgeGraph=null,this.qualityAnalyzer=null,this.agentBooster=null,this.taskRouter=null,this.coherenceActionGate=null}evaluateCoherenceGate(e,t){try{this.coherenceActionGate||(this.coherenceActionGate=ci({advisory:!0}));let n=e.payload,r=typeof n?.confidence=="number"?n.confidence:.7,i=n?.riskLevel??"medium";return li(e.type,t,r,i,n??{},this.coherenceActionGate)}catch(n){return re.warn("Coherence gate evaluation error (continuing)",{error:n instanceof Error?n.message:String(n),taskId:e.id}),null}}_reasoningQEC=null;_reasoningQECLoaded=!1;validateWithReasoningQEC(e,t){try{if(!this._reasoningQECLoaded){this._reasoningQECLoaded=!0;try{let{isReasoningQECEnabled:s}=(pt(),fn(Rs));if(s()){let{createReasoningQEC:a}=(Si(),fn(Ti));this._reasoningQEC=a()}}catch(s){re.debug("ReasoningQEC module unavailable",{error:s instanceof Error?s.message:String(s)})}}if(!this._reasoningQEC)return;let n=e.payload,r=n?.reasoningSteps;if(!r||r.length<2)return;let i=this._reasoningQEC.validate({type:t,context:n,steps:r});i.valid||re.warn("ReasoningQEC validation found issues (advisory)",{taskId:e.id,domain:t,confidence:i.confidence,issues:i.issues.length})}catch(n){re.debug("ReasoningQEC evaluation error",{error:n instanceof Error?n.message:String(n),taskId:e.id})}}getTaskDomain(e){return{"generate-tests":"test-generation","execute-tests":"test-execution","analyze-coverage":"coverage-analysis","assess-quality":"quality-assessment","predict-defects":"defect-intelligence","validate-requirements":"requirements-validation","index-code":"code-intelligence","scan-security":"security-compliance","validate-contracts":"contract-testing","test-accessibility":"visual-accessibility","run-chaos":"chaos-resilience","optimize-learning":"learning-optimization","cross-domain-workflow":"learning-optimization","protocol-execution":"learning-optimization","ideation-assessment":"requirements-validation"}[e]||"learning-optimization"}async timeout(e){return new Promise((t,n)=>{setTimeout(()=>n(new Error(`Task execution timed out after ${e}ms`)),e)})}async publishTaskCompleted(e,t,n){await this.eventBus.publish({id:L(),type:"TaskCompleted",timestamp:new Date,source:n,payload:{taskId:e,result:t}})}async publishTaskFailed(e,t,n){await this.eventBus.publish({id:L(),type:"TaskFailed",timestamp:new Date,source:n,payload:{taskId:e,error:t}})}};function wi(u,e){return new Wn(u,u.eventBus,e)}import{randomUUID as ke}from"crypto";k();var Kn={effectiveness:.25,coverage:.2,mutationKill:.15,stability:.15,maintainability:.15,performance:.1},Xn={"short-term":{minSuccessCount:0,minSuccessRate:0,minQualityScore:0,minAgeDays:0},working:{minSuccessCount:3,minSuccessRate:.6,minQualityScore:.5,minAgeDays:1},"long-term":{minSuccessCount:10,minSuccessRate:.75,minQualityScore:.7,minAgeDays:7},permanent:{minSuccessCount:50,minSuccessRate:.9,minQualityScore:.85,minAgeDays:30}},ce={qualityWeights:Kn,promotionCriteria:Xn,autoPromote:!0,autoDemote:!0,minCoverageImprovementToLearn:5,maxOutcomesInMemory:1e4,persistOutcomes:!0,batchSize:100};ee();k();U();var Yn=class{outcomes=[];maxOutcomes;constructor(e){this.maxOutcomes=e}add(e){this.outcomes.push(e),this.outcomes.length>this.maxOutcomes&&(this.outcomes=this.outcomes.slice(-this.maxOutcomes))}getAll(){return[...this.outcomes]}getByPattern(e){return this.outcomes.filter(t=>t.patternId===e)}getByAgent(e){return this.outcomes.filter(t=>t.generatedBy===e)}getByDomain(e){return this.outcomes.filter(t=>t.domain===e)}getRecent(e){return this.outcomes.slice(-e)}clear(){this.outcomes=[]}get size(){return this.outcomes.length}},Jn=class u{store;reasoningBank=null;config;db=null;persistCount=0;static RETENTION_CLEANUP_INTERVAL=100;patternMetrics=new Map;constructor(e={}){this.config={...ce,...e},this.store=new Yn(this.config.maxOutcomesInMemory)}connectReasoningBank(e){this.reasoningBank=e}async initialize(){try{this.db=$(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromDb()}catch(e){console.warn("[TestOutcomeTracker] DB initialization failed, using memory-only:",w(e)),this.db=null}}async loadFromDb(){if(!this.db)return;let t=this.db.getDatabase().prepare(`
|
|
438
|
+
`),p=m.length,g=0,h=[];p>500?(g+=.25,h.push(`Large file (${p} lines)`)):p>300&&(g+=.15,h.push(`Medium-large file (${p} lines)`));let f=d.match(/\b(if|else|switch|case|for|while|catch|&&|\|\|)\b/g)||[],v=f.length/Math.max(p,1);v>.15?(g+=.25,h.push(`High branch density (${f.length} branches in ${p} lines)`)):v>.08&&(g+=.1,h.push("Moderate branch complexity")),Math.max(...m.map(E=>{let S=E.match(/^(\s*)/);return S?S[1].length:0}))>20&&(g+=.15,h.push("Deep nesting detected"));let C=(d.match(/\b(TODO|FIXME|HACK|XXX|WORKAROUND)\b/gi)||[]).length;C>3&&(g+=.15,h.push(`${C} technical debt markers`));let b=(d.match(/\b(function|def|func|async)\b/g)||[]).length;if(b>0&&p/b>80&&(g+=.1,h.push("Potentially long functions")),g=Math.min(g,.95),g>=r){let E=c.startsWith(n)?c.slice(n.length).replace(/^\//,""):c;s.push({file:E,probability:Math.round(g*100)/100,reason:h.join("; ")})}}catch{}s.sort((c,d)=>d.probability-c.probability);let a=s.length>0?s.reduce((c,d)=>c+d.probability,0)/s.length:0,o=Math.round(a*100),l=[];if(s.length>0){l.push(`${s.length} files flagged for potential defects out of ${i.length} analyzed`);let c=s[0];l.push(`Highest risk: ${c.file} (${Math.round(c.probability*100)}%) \u2014 ${c.reason}`)}return s.some(c=>c.reason.includes("Large file"))&&l.push("Consider splitting large files to reduce complexity"),s.some(c=>c.reason.includes("technical debt"))&&l.push("Address TODO/FIXME comments to reduce technical debt"),s.length===0&&l.push("No files exceeded the defect probability threshold \u2014 code looks healthy"),I({predictedDefects:s.slice(0,20),riskScore:o,recommendations:l,filesAnalyzed:i.length})}catch(n){return q(z(n))}})}function Vn(u){u.registerHandler("test-accessibility",async e=>{let t=e.payload;return I({url:t.url||"",standard:t.standard||"wcag21-aa",passed:!1,violations:[],warnings:[],score:0,note:"Accessibility testing requires a browser environment (Puppeteer/Playwright). Use tools like axe-core, pa11y, or Lighthouse CLI for WCAG compliance testing. Example: npx pa11y "+(t.url||"<url>")})}),u.registerHandler("run-chaos",async e=>{let t=e.payload;return I({faultType:t.faultType||"unknown",target:t.target||"unknown",dryRun:t.dryRun??!0,duration:t.duration||0,systemBehavior:"not-executed",resilience:null,note:"Chaos engineering requires infrastructure-level fault injection. Use tools like Chaos Monkey, Litmus, or toxiproxy for real resilience testing. For Node.js apps, consider: nock (HTTP faults), testcontainers (dependency failures)."})}),u.registerHandler("optimize-learning",async e=>{try{let t=await import("./unified-memory-hnsw-UBF5PT6D.js");return I({patternsLearned:0,modelsUpdated:0,memoryConsolidated:!1,note:'Learning optimization runs during the dream cycle (SessionEnd hook). Use "npx agentic-qe hooks session-end --save-state" to trigger pattern consolidation.'})}catch{return I({patternsLearned:0,modelsUpdated:0,memoryConsolidated:!1,note:'Learning system not initialized. Run "aqe init --auto" first.'})}})}var re=ye("TaskExecutor");function Wa(u){return Te.resolve(Ce.CoverageAnalyzerService)(u)}function Ka(u){return Te.resolve(Ce.SecurityScannerService)(u)}function Xa(u){return Te.resolve(Ce.createTestGeneratorService)(u)}function Ya(u){return Te.resolve(Ce.KnowledgeGraphService)(u)}function Ja(u){return Te.resolve(Ce.QualityAnalyzerService)(u)}function Ei(u){switch(u){case 0:return"agent-booster";case 1:return"claude-3-5-haiku-20241022";case 2:return"claude-sonnet-4-20250514";case 3:return"claude-sonnet-4-20250514";case 4:return"claude-opus-4-5-20251101";default:return"claude-sonnet-4-20250514"}}function Za(u){if(["generate-tests","analyze-coverage","scan-security","execute-tests","assess-quality","validate-contracts","test-accessibility","chaos-test","predict-defects","validate-requirements","index-code"].includes(u.type))return null;let t=u.payload?.codeContext||"",n=u.payload?.sourceCode||"",r=t||n;return r?r.includes("var ")&&!r.includes("const ")&&!r.includes("let ")?"var-to-const":r.includes("console.log")||r.includes("console.warn")||r.includes("console.error")?"remove-console":r.includes(".then(")&&r.includes(".catch(")?"promise-to-async":r.includes("require(")&&!r.includes("import ")?"cjs-to-esm":r.includes("function ")&&!r.includes("=>")?"func-to-arrow":null:null}var Wn=class{constructor(e,t,n){this.kernel=e;this.eventBus=t;this._config={timeout:n?.timeout??3e5,maxRetries:n?.maxRetries??3,enableCaching:n?.enableCaching??!0,saveResults:n?.saveResults??!0,resultsDir:n?.resultsDir??".agentic-qe",defaultLanguage:n?.defaultLanguage??"typescript",defaultFramework:n?.defaultFramework??"vitest"},this.resultSaver=ai(this._config.resultsDir),this.registerHandlers()}_config;resultSaver;coverageAnalyzer=null;securityScanner=null;testGenerator=null;knowledgeGraph=null;qualityAnalyzer=null;agentBooster=null;taskRouter=null;qualityFeedbackLoop=null;coherenceActionGate=null;taskHandlers=new Map;get config(){return this._config}registerHandler(e,t){this.taskHandlers.set(e,t)}setQualityFeedbackLoop(e){this.qualityFeedbackLoop=e}getCoverageAnalyzer(){return this.coverageAnalyzer||(this.coverageAnalyzer=Wa(this.kernel.memory)),this.coverageAnalyzer}getSecurityScanner(){return this.securityScanner||(this.securityScanner=Ka(this.kernel.memory)),this.securityScanner}getTestGenerator(){return this.testGenerator||(this.testGenerator=Xa(this.kernel.memory)),this.testGenerator}getKnowledgeGraph(){return this.knowledgeGraph||(this.knowledgeGraph=Ya(this.kernel.memory)),this.knowledgeGraph}getQualityAnalyzer(){return this.qualityAnalyzer||(this.qualityAnalyzer=Ja(this.kernel.memory)),this.qualityAnalyzer}registerHandlers(){qn(this),zn(this),Bn(this),Un(this),Hn(this),jn(this),Vn(this)}async getAgentBooster(){return this.agentBooster||(this.agentBooster=await ft({enabled:!0,fallbackToLLM:!0,confidenceThreshold:.7})),this.agentBooster}async getTaskRouterInstance(){if(!this.taskRouter)try{this.taskRouter=await Ot()}catch{return null}return this.taskRouter}async executeWithAgentBooster(e,t,n){let r=Za(e);if(!r)return console.debug(`[TaskExecutor] No applicable Agent Booster transform for task ${e.id}`),null;try{let i=await this.getAgentBooster(),s=e.payload?.codeContext||e.payload?.sourceCode||"",a=await i.transform(s,r);return a.success&&a.confidence>=.7?(console.debug(`[TaskExecutor] Agent Booster transform succeeded: ${r}, confidence=${a.confidence}`),{taskId:e.id,success:!0,data:{transformed:!0,transformType:r,originalCode:a.originalCode,transformedCode:a.transformedCode,confidence:a.confidence,implementationUsed:a.implementationUsed,durationMs:a.durationMs,changeCount:a.changeCount,tier:0,model:"agent-booster"},duration:Date.now()-t,domain:n}):(console.debug(`[TaskExecutor] Agent Booster low confidence (${a.confidence}), falling back to Tier 1`),null)}catch(i){return console.warn(`[TaskExecutor] Agent Booster error, falling back: ${i}`),null}}async recordOutcome(e,t,n,r){try{if(!await this.getTaskRouterInstance())return;if(console.debug(`[TaskExecutor] Outcome recorded: task=${e.id}, tier=${t}, model=${Ei(t)}, success=${n}, duration=${r}ms`),this.qualityFeedbackLoop){let s=e.targetDomains||[];await this.qualityFeedbackLoop.recordRoutingOutcome({taskId:e.id,taskDescription:e.type,recommendedAgent:String(t),usedAgent:String(t),followedRecommendation:!0,success:n,qualityScore:n?.8:.2,durationMs:r,timestamp:new Date,error:n?void 0:"Task execution failed"})}}catch(i){console.warn("[TaskExecutor] Failed to record outcome:",i)}}async execute(e){let t=Date.now(),n=this.getTaskDomain(e.type),r=e.payload,i=r?.routingTier??2,s=r?.useAgentBooster??!1,a=r?.compiledContext??void 0,o=Ei(i);a&&e.payload&&(e.payload.__compiledContext=a),console.debug(`[TaskExecutor] Executing task ${e.id}: type=${e.type}, tier=${i}, model=${o}, useAgentBooster=${s}${a?", hasContext=true":""}`);let l=this.evaluateCoherenceGate(e,n);l&&console.debug(`[TaskExecutor] Coherence gate: task=${e.id}, decision=${l.decision}, combined=${l.combinedScore.toFixed(3)}, advisory=${l.advisory}`),this.validateWithReasoningQEC(e,n);try{if(i===0||s){let p=await this.executeWithAgentBooster(e,t,n);if(p)return this.recordOutcome(e,0,!0,Date.now()-t).catch(g=>{re.warn("recordOutcome failed",{error:g instanceof Error?g.message:String(g),taskId:e.id})}),await this.publishTaskCompleted(e.id,p.data,n),p;console.debug(`[TaskExecutor] Agent Booster fallback to Tier 1 for task ${e.id}`)}let c=this.taskHandlers.get(e.type);if(!c){let p={taskId:e.id,success:!1,error:`No handler registered for task type: ${e.type}`,duration:Date.now()-t,domain:n};return this.recordOutcome(e,i,!1,Date.now()-t).catch(g=>{re.warn("recordOutcome failed",{error:g instanceof Error?g.message:String(g),taskId:e.id})}),p}let d=await Promise.race([c(e),this.timeout(e.timeout||this._config.timeout)]);if(!d.success){let p="error"in d?d.error.message:"Unknown error";return await this.publishTaskFailed(e.id,p,n),this.recordOutcome(e,i,!1,Date.now()-t).catch(g=>{re.warn("recordOutcome failed",{error:g instanceof Error?g.message:String(g),taskId:e.id})}),{taskId:e.id,success:!1,error:p,duration:Date.now()-t,domain:n}}await this.publishTaskCompleted(e.id,d.value,n),this.recordOutcome(e,i,!0,Date.now()-t).catch(p=>{re.warn("recordOutcome failed",{error:p instanceof Error?p.message:String(p),taskId:e.id})});let m;if(this._config.saveResults)try{let p={language:r?.language||this._config.defaultLanguage,framework:r?.framework||this._config.defaultFramework,includeSecondary:!0};m=(await this.resultSaver.save(e.id,e.type,d.value,p)).files.map(h=>h.path)}catch(p){console.error(`[TaskExecutor] Failed to save results: ${p}`)}return{taskId:e.id,success:!0,data:{...d.value,_routing:{tier:i,model:o,usedAgentBooster:!1}},duration:Date.now()-t,domain:n,savedFiles:m}}catch(c){let d=w(c);return await this.publishTaskFailed(e.id,d,n),this.recordOutcome(e,i,!1,Date.now()-t).catch(m=>{re.warn("recordOutcome failed",{error:m instanceof Error?m.message:String(m),taskId:e.id})}),{taskId:e.id,success:!1,error:d,duration:Date.now()-t,domain:n}}}async resetServiceCaches(){if(this.coverageAnalyzer=null,this.securityScanner=null,this.testGenerator=null,this.knowledgeGraph=null,this.qualityAnalyzer=null,this.coherenceActionGate=null,this.agentBooster){try{await this.agentBooster.dispose()}catch(e){console.debug("[TaskExecutor] Agent Booster disposal error:",e instanceof Error?e.message:e)}this.agentBooster=null}this.taskRouter=null}resetServiceCachesSync(){this.coverageAnalyzer=null,this.securityScanner=null,this.testGenerator=null,this.knowledgeGraph=null,this.qualityAnalyzer=null,this.agentBooster=null,this.taskRouter=null,this.coherenceActionGate=null}evaluateCoherenceGate(e,t){try{this.coherenceActionGate||(this.coherenceActionGate=ci({advisory:!0}));let n=e.payload,r=typeof n?.confidence=="number"?n.confidence:.7,i=n?.riskLevel??"medium";return li(e.type,t,r,i,n??{},this.coherenceActionGate)}catch(n){return re.warn("Coherence gate evaluation error (continuing)",{error:n instanceof Error?n.message:String(n),taskId:e.id}),null}}_reasoningQEC=null;_reasoningQECLoaded=!1;validateWithReasoningQEC(e,t){try{if(!this._reasoningQECLoaded){this._reasoningQECLoaded=!0;try{let{isReasoningQECEnabled:s}=(pt(),fn(Rs));if(s()){let{createReasoningQEC:a}=(Si(),fn(Ti));this._reasoningQEC=a()}}catch(s){re.debug("ReasoningQEC module unavailable",{error:s instanceof Error?s.message:String(s)})}}if(!this._reasoningQEC)return;let n=e.payload,r=n?.reasoningSteps;if(!r||r.length<2)return;let i=this._reasoningQEC.validate({type:t,context:n,steps:r});i.valid||re.warn("ReasoningQEC validation found issues (advisory)",{taskId:e.id,domain:t,confidence:i.confidence,issues:i.issues.length})}catch(n){re.debug("ReasoningQEC evaluation error",{error:n instanceof Error?n.message:String(n),taskId:e.id})}}getTaskDomain(e){return{"generate-tests":"test-generation","execute-tests":"test-execution","analyze-coverage":"coverage-analysis","assess-quality":"quality-assessment","predict-defects":"defect-intelligence","validate-requirements":"requirements-validation","index-code":"code-intelligence","scan-security":"security-compliance","validate-contracts":"contract-testing","test-accessibility":"visual-accessibility","run-chaos":"chaos-resilience","optimize-learning":"learning-optimization","cross-domain-workflow":"learning-optimization","protocol-execution":"learning-optimization","ideation-assessment":"requirements-validation"}[e]||"learning-optimization"}async timeout(e){return new Promise((t,n)=>{setTimeout(()=>n(new Error(`Task execution timed out after ${e}ms`)),e)})}async publishTaskCompleted(e,t,n){await this.eventBus.publish({id:L(),type:"TaskCompleted",timestamp:new Date,source:n,payload:{taskId:e,result:t}})}async publishTaskFailed(e,t,n){await this.eventBus.publish({id:L(),type:"TaskFailed",timestamp:new Date,source:n,payload:{taskId:e,error:t}})}};function wi(u,e){return new Wn(u,u.eventBus,e)}import{randomUUID as ke}from"crypto";k();var Kn={effectiveness:.25,coverage:.2,mutationKill:.15,stability:.15,maintainability:.15,performance:.1},Xn={"short-term":{minSuccessCount:0,minSuccessRate:0,minQualityScore:0,minAgeDays:0},working:{minSuccessCount:3,minSuccessRate:.6,minQualityScore:.5,minAgeDays:1},"long-term":{minSuccessCount:10,minSuccessRate:.75,minQualityScore:.7,minAgeDays:7},permanent:{minSuccessCount:50,minSuccessRate:.9,minQualityScore:.85,minAgeDays:30}},ce={qualityWeights:Kn,promotionCriteria:Xn,autoPromote:!0,autoDemote:!0,minCoverageImprovementToLearn:5,maxOutcomesInMemory:1e4,persistOutcomes:!0,batchSize:100};ee();k();U();var Yn=class{outcomes=[];maxOutcomes;constructor(e){this.maxOutcomes=e}add(e){this.outcomes.push(e),this.outcomes.length>this.maxOutcomes&&(this.outcomes=this.outcomes.slice(-this.maxOutcomes))}getAll(){return[...this.outcomes]}getByPattern(e){return this.outcomes.filter(t=>t.patternId===e)}getByAgent(e){return this.outcomes.filter(t=>t.generatedBy===e)}getByDomain(e){return this.outcomes.filter(t=>t.domain===e)}getRecent(e){return this.outcomes.slice(-e)}clear(){this.outcomes=[]}get size(){return this.outcomes.length}},Jn=class u{store;reasoningBank=null;config;db=null;persistCount=0;static RETENTION_CLEANUP_INTERVAL=100;patternMetrics=new Map;constructor(e={}){this.config={...ce,...e},this.store=new Yn(this.config.maxOutcomesInMemory)}connectReasoningBank(e){this.reasoningBank=e}async initialize(){try{this.db=$(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromDb()}catch(e){console.warn("[TestOutcomeTracker] DB initialization failed, using memory-only:",w(e)),this.db=null}}async loadFromDb(){if(!this.db)return;let t=this.db.getDatabase().prepare(`
|
|
439
439
|
SELECT * FROM test_outcomes ORDER BY created_at DESC LIMIT ?
|
|
440
440
|
`).all(this.config.maxOutcomesInMemory);for(let n of t.reverse()){let r={id:n.id,testId:n.test_id,testName:n.test_name,generatedBy:n.generated_by,patternId:n.pattern_id||void 0,framework:n.framework,language:n.language,domain:n.domain,passed:!!n.passed,errorMessage:n.error_message||void 0,coverage:{lines:n.coverage_lines,branches:n.coverage_branches,functions:n.coverage_functions},mutationScore:n.mutation_score??void 0,executionTimeMs:n.execution_time_ms,flaky:!!n.flaky,flakinessScore:n.flakiness_score??void 0,maintainabilityScore:n.maintainability_score,complexity:n.complexity??void 0,linesOfCode:n.lines_of_code??void 0,assertionCount:n.assertion_count??void 0,filePath:n.file_path||void 0,sourceFilePath:n.source_file_path||void 0,timestamp:new Date(n.created_at),metadata:n.metadata_json?P(n.metadata_json):void 0};this.store.add(r),r.patternId&&this.updatePatternMetrics(r)}t.length>0&&console.log(`[TestOutcomeTracker] Loaded ${t.length} outcomes from DB`)}persistOutcome(e){if(this.db)try{let t=this.db.getDatabase();t.prepare(`
|
|
441
441
|
INSERT OR REPLACE INTO test_outcomes (
|
|
@@ -466,7 +466,7 @@ ${e.recommendations.length===0?"No recommendations - all quality gates passed.":
|
|
|
466
466
|
)
|
|
467
467
|
`).run(t)}catch(t){console.warn("[CoverageLearner] Retention cleanup failed:",w(t))}}async learnFromSession(e){this.sessionStore.add(e),this.persistSession(e);let t=this.calculateOverallImprovement(e);if(t<this.config.minCoverageImprovementToLearn)return null;let n=await this.extractStrategy(e,t);return this.reasoningBank&&n&&await this.storeStrategyAsPattern(n),n}calculateOverallImprovement(e){let t=e.beforeCoverage,n=e.afterCoverage,r=n.lines-t.lines,i=n.branches-t.branches,s=n.functions-t.functions;return r*.4+i*.35+s*.25}async extractStrategy(e,t){let n=this.extractFilePattern(e.targetPath),r=`${e.technique}:${n}`,i=this.strategies.get(r);return i?i={...i,avgImprovement:(i.avgImprovement*i.successCount+t)/(i.successCount+1),successCount:i.successCount+1,confidence:Math.min(1,i.confidence+.05),lastUsedAt:new Date}:i={id:`strategy-${Date.now()}-${eo().slice(0,8)}`,description:this.generateStrategyDescription(e,t),technique:e.technique,filePatterns:[n],avgImprovement:t,successCount:1,confidence:.5,createdAt:new Date,lastUsedAt:new Date},this.strategies.set(r,i),i}extractFilePattern(e){let t=e.split("/"),r=t[t.length-1].split(".").pop()||"";return t.length>=2?`${t[t.length-2]}/*.${r}`:`*.${r}`}generateStrategyDescription(e,t){let r={"gap-analysis":"Identify and target uncovered code paths","branch-coverage":"Focus on branch conditions and decision points","edge-case-generation":"Generate tests for edge cases and boundary conditions","mutation-guided":"Use mutation testing to identify weak test areas","risk-based":"Prioritize high-risk code paths","semantic-analysis":"Use code semantics to generate meaningful tests","boundary-testing":"Test boundary conditions and limits","state-machine":"Model state transitions and test state changes","data-flow":"Follow data flow paths through the code"}[e.technique]||e.technique,i=e.gapsTargeted.filter(a=>a.addressed).length,s=e.gapsTargeted.length;return`${r} for ${this.extractFilePattern(e.targetPath)} files. Achieved ${t.toFixed(1)}% improvement. Addressed ${i}/${s} gaps with ${e.testsGenerated} tests.`}async storeStrategyAsPattern(e){this.reasoningBank&&await this.reasoningBank.storeQEPattern({patternType:"coverage-strategy",name:`Coverage Strategy: ${e.technique}`,description:e.description,template:{type:"workflow",content:JSON.stringify({technique:e.technique,filePatterns:e.filePatterns,avgImprovement:e.avgImprovement}),variables:[{name:"targetFile",type:"string",required:!0,description:"Target file to analyze"},{name:"currentCoverage",type:"number",required:!0,description:"Current coverage percentage"}]},context:{tags:["coverage",e.technique,...e.filePatterns]}})}getRecommendedStrategy(e){let t=this.extractFilePattern(e),n=null,r=0;for(let i of this.strategies.values())if(i.filePatterns.some(a=>t.includes(a.split("/").pop()||"")||a.includes(t.split("/").pop()||""))||i.filePatterns.length===0){let a=(Date.now()-i.lastUsedAt.getTime())/864e5,o=Math.max(.5,1-a/30),l=i.avgImprovement*i.confidence*o;l>r&&(r=l,n=i)}return n}getAllStrategies(){return Array.from(this.strategies.values())}getStrategiesByTechnique(e){return this.getAllStrategies().filter(t=>t.technique===e)}getSessionStats(){let e=this.sessionStore.getAll();if(e.length===0)return{totalSessions:0,successfulSessions:0,avgImprovement:0,byTechnique:new Map,strategiesLearned:0};let t=e.map(a=>this.calculateOverallImprovement(a)),n=t.filter(a=>a>=this.config.minCoverageImprovementToLearn).length,r=t.reduce((a,o)=>a+o,0)/t.length,i=new Map,s=new Map;for(let a of e){let o=s.get(a.technique)||[];o.push(a),s.set(a.technique,o)}for(let[a,o]of s){let l=o.map(c=>this.calculateOverallImprovement(c));i.set(a,{count:o.length,avgImprovement:l.reduce((c,d)=>c+d,0)/l.length})}return{totalSessions:e.length,successfulSessions:n,avgImprovement:r,byTechnique:i,strategiesLearned:this.strategies.size}}analyzeGapResolution(){let t=this.sessionStore.getAll().flatMap(i=>i.gapsTargeted);if(t.length===0)return{totalGapsTargeted:0,gapsAddressed:0,resolutionRate:0,byGapType:new Map};let n=t.filter(i=>i.addressed).length,r=new Map;for(let i of t){let s=r.get(i.type)||{targeted:0,addressed:0};s.targeted++,i.addressed&&s.addressed++,r.set(i.type,s)}return{totalGapsTargeted:t.length,gapsAddressed:n,resolutionRate:n/t.length,byGapType:r}}exportSessions(){return this.sessionStore.getAll()}importSessions(e){for(let t of e)this.sessionStore.add(t)}exportStrategies(){return this.getAllStrategies()}importStrategies(e){for(let t of e){let n=`${t.technique}:${t.filePatterns[0]||"*"}`;this.strategies.set(n,t)}}clear(){this.sessionStore.clear(),this.strategies.clear()}getLearnerStats(){return{totalSessions:this.sessionStore.size,totalStrategies:this.strategies.size,hasReasoningBank:this.reasoningBank!==null,minImprovementThreshold:this.config.minCoverageImprovementToLearn}}};function xi(u){return new er(u)}var tr=class{weights;historicalScores=[];maxHistory;constructor(e={},t=100){this.weights={...Kn,...e},this.maxHistory=t}calculateFromOutcome(e){let t=this.calculateDimensions(e),n=this.calculateOverall(t);return this.trackScore(n),{overall:n,dimensions:t,weights:this.weights,trend:this.calculateTrend(),calculatedAt:new Date}}calculateDimensions(e){return{effectiveness:this.calculateEffectiveness(e),coverage:this.calculateCoverageScore(e.coverage),mutationKill:e.mutationScore??.5,stability:this.calculateStability(e),maintainability:e.maintainabilityScore,performance:this.calculatePerformanceScore(e.executionTimeMs)}}calculateEffectiveness(e){return e.passed?e.flaky?.3:1:0}calculateCoverageScore(e){return(e.lines*.4+e.branches*.35+e.functions*.25)/100}calculateStability(e){return e.flaky?.2:e.flakinessScore!==void 0?1-e.flakinessScore:1}calculatePerformanceScore(e){return e<100?1:e<500?.8:e<2e3?.6:e<5e3?.4:e<1e4?.2:.1}calculateOverall(e){return this.weights.effectiveness*e.effectiveness+this.weights.coverage*e.coverage+this.weights.mutationKill*e.mutationKill+this.weights.stability*e.stability+this.weights.maintainability*e.maintainability+this.weights.performance*e.performance}trackScore(e){this.historicalScores.push(e),this.historicalScores.length>this.maxHistory&&(this.historicalScores=this.historicalScores.slice(-this.maxHistory))}calculateTrend(){if(this.historicalScores.length<10)return"stable";let e=this.historicalScores.slice(-10),t=this.historicalScores.slice(-20,-10);if(t.length===0)return"stable";let n=e.reduce((s,a)=>s+a,0)/e.length,r=t.reduce((s,a)=>s+a,0)/t.length,i=n-r;return i>.05?"improving":i<-.05?"declining":"stable"}calculateAggregate(e){if(e.length===0)return{overall:0,dimensions:{effectiveness:0,coverage:0,mutationKill:0,stability:0,maintainability:0,performance:0},weights:this.weights,trend:"stable",calculatedAt:new Date};let t={effectiveness:0,coverage:0,mutationKill:0,stability:0,maintainability:0,performance:0};for(let s of e){let a=this.calculateDimensions(s);t.effectiveness+=a.effectiveness,t.coverage+=a.coverage,t.mutationKill+=a.mutationKill,t.stability+=a.stability,t.maintainability+=a.maintainability,t.performance+=a.performance}let n=e.length,r={effectiveness:t.effectiveness/n,coverage:t.coverage/n,mutationKill:t.mutationKill/n,stability:t.stability/n,maintainability:t.maintainability/n,performance:t.performance/n};return{overall:this.calculateOverall(r),dimensions:r,weights:this.weights,trend:this.calculateTrend(),calculatedAt:new Date}}calculateDelta(e,t){let n={effectiveness:t.dimensions.effectiveness-e.dimensions.effectiveness,coverage:t.dimensions.coverage-e.dimensions.coverage,mutationKill:t.dimensions.mutationKill-e.dimensions.mutationKill,stability:t.dimensions.stability-e.dimensions.stability,maintainability:t.dimensions.maintainability-e.dimensions.maintainability,performance:t.dimensions.performance-e.dimensions.performance},r=t.overall-e.overall;return{overallDelta:r,dimensionDeltas:n,improved:r>0}}getRecommendations(e){let t=[],n=e.dimensions;return n.effectiveness<.8&&t.push("Improve test pass rate - investigate failing tests"),n.coverage<.7&&t.push("Increase code coverage - target uncovered paths"),n.mutationKill<.6&&t.push("Strengthen assertions - tests may be too weak"),n.stability<.9&&t.push("Address test flakiness - stabilize intermittent tests"),n.maintainability<.7&&t.push("Improve test maintainability - reduce complexity"),n.performance<.6&&t.push("Optimize test performance - reduce execution time"),t.length===0&&t.push("Quality is excellent - maintain current practices"),t}updateWeights(e){this.weights={...this.weights,...e}}getWeights(){return{...this.weights}}getStats(){let e=this.historicalScores.slice(-10),t=e.length>0?e.reduce((n,r)=>n+r,0)/e.length:0;return{scoresTracked:this.historicalScores.length,currentTrend:this.calculateTrend(),avgRecentScore:t}}clearHistory(){this.historicalScores=[]}};function Pi(u,e){return new tr(u,e)}var nr=class{criteria;promotionHistory=[];demotionHistory=[];reasoningBank=null;config;constructor(e={}){this.config={...ce,...e},this.criteria={...Xn}}connectReasoningBank(e){this.reasoningBank=e}evaluatePromotion(e,t){let n=e.tier,r=this.getNextTier(n);if(!r)return null;let i=this.criteria[r];if(this.meetsPromotionCriteria(t,i)){let s={patternId:e.id,fromTier:n,toTier:r,reason:this.generatePromotionReason(t,i),metrics:{successCount:t.successCount,successRate:t.successRate,qualityScore:t.qualityScore,ageDays:t.ageDays},timestamp:new Date};return this.promotionHistory.push(s),s}return null}evaluateDemotion(e,t){if(!this.config.autoDemote)return null;let n=e.tier;if(n==="short-term")return null;if(t.recentSuccessRate<.4||t.recentFailureCount>=5||t.qualityScore<.3){let i=this.getPreviousTier(n);if(!i)return null;let s={patternId:e.id,fromTier:n,toTier:i,reason:this.generateDemotionReason(t),metrics:{recentSuccessRate:t.recentSuccessRate,recentQualityScore:t.qualityScore,failureCount:t.recentFailureCount},timestamp:new Date};return this.demotionHistory.push(s),s}return null}async processPatternChange(e,t){let n=this.evaluateDemotion(e,t);if(n)return this.reasoningBank&&await this.reasoningBank.demotePattern(e.id),{action:"demoted",event:n};let r=this.evaluatePromotion(e,t);return r?(this.reasoningBank&&await this.reasoningBank.promotePattern(e.id),{action:"promoted",event:r}):{action:"unchanged"}}meetsPromotionCriteria(e,t){return e.successCount>=t.minSuccessCount&&e.successRate>=t.minSuccessRate&&e.qualityScore>=t.minQualityScore&&e.ageDays>=t.minAgeDays}getNextTier(e){let t=["short-term","working","long-term","permanent"],n=t.indexOf(e);return n<t.length-1?t[n+1]:null}getPreviousTier(e){let t=["short-term","working","long-term","permanent"],n=t.indexOf(e);return n>0?t[n-1]:null}generatePromotionReason(e,t){let n=[];return e.successCount>=t.minSuccessCount&&n.push(`${e.successCount} successful uses (>=${t.minSuccessCount})`),e.successRate>=t.minSuccessRate&&n.push(`${(e.successRate*100).toFixed(0)}% success rate (>=${t.minSuccessRate*100}%)`),e.qualityScore>=t.minQualityScore&&n.push(`${(e.qualityScore*100).toFixed(0)}% quality score (>=${t.minQualityScore*100}%)`),`Pattern promoted: ${n.join(", ")}`}generateDemotionReason(e){let t=[];return e.recentSuccessRate<.4&&t.push(`low recent success rate (${(e.recentSuccessRate*100).toFixed(0)}%)`),e.recentFailureCount>=5&&t.push(`${e.recentFailureCount} recent failures`),e.qualityScore<.3&&t.push(`low quality score (${(e.qualityScore*100).toFixed(0)}%)`),`Pattern demoted: ${t.join(", ")}`}updateCriteria(e,t){this.criteria[e]={...this.criteria[e],...t}}getCriteria(e){return{...this.criteria[e]}}getAllCriteria(){return{...this.criteria}}getPromotionHistory(e=100){return this.promotionHistory.slice(-e)}getDemotionHistory(e=100){return this.demotionHistory.slice(-e)}getStats(){let e={"short-term":0,working:0,"long-term":0,permanent:0};for(let s of this.promotionHistory)e[s.toTier]++;let t={"short-term":0,working:0,"long-term":0,permanent:0};for(let s of this.demotionHistory)t[s.toTier]++;let n=Date.now()-10080*60*1e3,r=this.promotionHistory.filter(s=>s.timestamp.getTime()>n).length,i=this.demotionHistory.filter(s=>s.timestamp.getTime()>n).length;return{totalPromotions:this.promotionHistory.length,totalDemotions:this.demotionHistory.length,promotionsByTier:e,demotionsByTier:t,recentPromotions:r,recentDemotions:i}}exportHistory(){return{promotions:[...this.promotionHistory],demotions:[...this.demotionHistory]}}importHistory(e){e.promotions&&this.promotionHistory.push(...e.promotions),e.demotions&&this.demotionHistory.push(...e.demotions)}clearHistory(){this.promotionHistory=[],this.demotionHistory=[]}};function Ai(u){return new nr(u)}var rr=class{outcomeTracker;coverageLearner;qualityCalculator;promotionManager;routingFeedback;reasoningBank=null;config;constructor(e={}){this.config={...ce,...e},this.outcomeTracker=Ri(this.config),this.coverageLearner=xi(this.config),this.qualityCalculator=Pi(this.config.qualityWeights),this.promotionManager=Ai(this.config),this.routingFeedback=Qr(this.config.maxOutcomesInMemory)}async initialize(){await Promise.all([this.outcomeTracker.initialize(),this.coverageLearner.initialize(),this.routingFeedback.initialize()])}connectReasoningBank(e){this.reasoningBank=e,this.outcomeTracker.connectReasoningBank(e),this.coverageLearner.connectReasoningBank(e),this.promotionManager.connectReasoningBank(e)}async recordTestOutcome(e){await this.outcomeTracker.track(e);let t=this.qualityCalculator.calculateFromOutcome(e),n;if(e.patternId&&this.reasoningBank){let r=await this.reasoningBank.searchQEPatterns(e.patternId,{limit:1});if(r.success&&r.value.length>0){let i=r.value[0].pattern,s=this.outcomeTracker.getPatternMetrics(e.patternId);if(s){let a=await this.promotionManager.processPatternChange(i,{patternId:e.patternId,successCount:s.successCount,failureCount:s.failureCount,successRate:s.successRate,qualityScore:s.avgQuality,ageDays:this.calculateAgeDays(i.createdAt),recentSuccessRate:this.calculateRecentSuccessRate(e.patternId),recentFailureCount:this.calculateRecentFailures(e.patternId)});n={action:a.action,tier:a.event&&"toTier"in a.event?a.event.toTier:void 0}}}}return{qualityScore:t,patternUpdate:n}}async recordCoverageSession(e){let t=await this.coverageLearner.learnFromSession(e);return{improvement:(e.afterCoverage.lines-e.beforeCoverage.lines+e.afterCoverage.branches-e.beforeCoverage.branches+e.afterCoverage.functions-e.beforeCoverage.functions)/3,strategyLearned:t!==null,strategyId:t?.id}}getRecommendedCoverageStrategy(e){return this.coverageLearner.getRecommendedStrategy(e)}getQualityRecommendations(){let e=this.outcomeTracker.getRecentOutcomes(50);if(e.length===0)return["No test outcomes recorded yet. Start tracking test results to get recommendations."];let t=this.qualityCalculator.calculateAggregate(e);return this.qualityCalculator.getRecommendations(t)}async recordRoutingOutcome(e){let t={id:e.taskId,description:e.taskDescription,complexity:"medium",domains:["test-generation"],context:{}},n={recommended:e.recommendedAgent,confidence:.8,reasoning:"Recorded from feedback",alternatives:[],scores:{similarity:.8,performance:.8,capabilities:.8,combined:.8},latencyMs:0,timestamp:e.timestamp};this.routingFeedback.recordOutcome(t,n,e.usedAgent,{success:e.success,qualityScore:e.qualityScore,durationMs:e.durationMs,error:e.error})}getRoutingAnalysis(){let e=this.routingFeedback.analyzeRoutingAccuracy(),t=this.routingFeedback.getImprovementRecommendations();return{totalOutcomes:e.totalOutcomes,recommendationFollowRate:1-e.overrideRate,successRateWhenFollowed:e.recommendationSuccessRate,successRateWhenOverridden:e.overrideSuccessRate,confidenceCorrelation:e.confidenceCorrelation,recommendations:t}}calculateAgeDays(e){return(Date.now()-e.getTime())/(1e3*60*60*24)}calculateRecentSuccessRate(e){let t=this.outcomeTracker.exportOutcomes().filter(r=>r.patternId===e).slice(-10);return t.length===0?0:t.filter(r=>r.passed&&!r.flaky).length/t.length}calculateRecentFailures(e){return this.outcomeTracker.exportOutcomes().filter(n=>n.patternId===e).slice(-10).filter(n=>!n.passed||n.flaky).length}getStats(){let e=this.outcomeTracker.getStats(),t=this.coverageLearner.getSessionStats(),n=this.promotionManager.getStats(),r=this.qualityCalculator.getStats(),i=this.outcomeTracker.getTrackerStats(),s=this.routingFeedback.analyzeRoutingAccuracy();return{testOutcomes:{total:e.totalTests,passRate:e.passRate,avgQuality:e.avgMaintainability,flakyCount:e.flakyTests},coverage:{totalSessions:t.totalSessions,successfulSessions:t.successfulSessions,avgImprovement:t.avgImprovement,strategiesLearned:t.strategiesLearned},patterns:{promoted:n.totalPromotions,demoted:n.totalDemotions,tracked:i.patternsTracked},quality:{currentTrend:r.currentTrend,avgRecentScore:r.avgRecentScore},routing:{totalOutcomes:s.totalOutcomes,recommendationFollowRate:1-s.overrideRate,successRateWhenFollowed:s.recommendationSuccessRate,successRateWhenOverridden:s.overrideSuccessRate},integrationStatus:{reasoningBankConnected:this.reasoningBank!==null}}}exportData(){return{outcomes:this.outcomeTracker.exportOutcomes(),sessions:this.coverageLearner.exportSessions(),strategies:this.coverageLearner.exportStrategies(),promotionHistory:this.promotionManager.exportHistory(),routingOutcomes:this.routingFeedback.exportOutcomes()}}importData(e){e.outcomes&&this.outcomeTracker.importOutcomes(e.outcomes),e.sessions&&this.coverageLearner.importSessions(e.sessions),e.strategies&&this.coverageLearner.importStrategies(e.strategies),e.promotionHistory&&this.promotionManager.importHistory(e.promotionHistory),e.routingOutcomes&&this.routingFeedback.importOutcomes(e.routingOutcomes)}clear(){this.outcomeTracker.clear(),this.coverageLearner.clear(),this.qualityCalculator.clearHistory(),this.promotionManager.clearHistory(),this.routingFeedback.clear()}};async function ki(u){let e=new rr(u);return await e.initialize(),Mi=e,e}var Mi=null;function Di(){return Mi}function Me(){return`test-${ke()}`}function _i(u){return`${u}-${ke()}`}function qt(u){return{enabled:!0,agentId:_i(u),message:"Experience captured asynchronously via learning pipeline"}}async function to(u,e,t,n,r){let i=_i(u);try{let{kernel:s}=Ue();if(!s)return{enabled:!1,agentId:i,message:"Learning engine not available - kernel not initialized"};let a=await ro();if(!a)return{enabled:!1,agentId:i,message:"Learning engine not available"};let o=a.getExperienceCaptureService();if(!o)return{enabled:!1,agentId:i,message:"Experience capture service not available"};let l=no(e),c=o.startCapture(`${e}: ${JSON.stringify(t).slice(0,200)}`,{agent:u,domain:l||void 0,metadata:{tool:e,durationMs:r}});o.recordStep(c,{action:`execute-${e}`,result:typeof n=="object"?JSON.stringify(n).slice(0,500):String(n).slice(0,500),quality:.7});let d=await o.completeCapture(c,{success:!0,quality:.7});if(d.success){let m=d.value;return{enabled:!0,agentId:i,message:`Experience captured: ${m.id} (domain: ${l||"general"}, quality: ${m.quality})`,experienceId:m.id,domain:l||"general"}}return{enabled:!0,agentId:i,message:"Experience capture completed (no pattern extracted)"}}catch(s){return{enabled:!1,agentId:i,message:`Learning capture failed: ${w(s)}`}}}function no(u){return{test_generate_enhanced:"test-generation",test_execute_parallel:"test-execution",coverage_analyze_sublinear:"coverage-analysis",quality_assess:"quality-assessment",security_scan_comprehensive:"security-compliance",contract_validate:"contract-testing",accessibility_test:"visual-accessibility",chaos_test:"chaos-resilience",defect_predict:"defect-intelligence",requirements_validate:"requirements-validation",code_index:"code-intelligence"}[u]||null}async function ro(){return qi()}async function io(u,e,t,n){let r=Di();if(!r&&ir&&(r=await ir),!!r){if(u==="test-generation"&&e){let i=e.tests||e.generatedTests||[];for(let s of i.slice(0,20)){let a={id:String(s.id||ke()),testId:String(s.id||s.name||ke()),testName:String(s.name||s.testName||"generated-test"),generatedBy:"qe-test-generation",patternId:s.patternId,framework:s.framework||n.framework||"vitest",language:s.language||n.language||"typescript",domain:"test-generation",passed:s.passed!==!1,coverage:{lines:Number(s.coverageLines||0),branches:Number(s.coverageBranches||0),functions:Number(s.coverageFunctions||0)},executionTimeMs:Number(s.executionTimeMs||t/Math.max(i.length,1)),flaky:!!s.flaky,maintainabilityScore:Number(s.qualityScore||s.maintainability||.7),timestamp:new Date};await r.recordTestOutcome(a)}}if(u==="coverage-analysis"&&e){let i={id:ke(),targetPath:String(n.target||n.targetPath||"src/"),agentId:"qe-coverage-analysis",technique:n.technique||"gap-analysis",beforeCoverage:{lines:Number(e.beforeCoverage?.lines||0),branches:Number(e.beforeCoverage?.branches||0),functions:Number(e.beforeCoverage?.functions||0)},afterCoverage:{lines:Number(e.lineCoverage||e.lines||0),branches:Number(e.branchCoverage||e.branches||0),functions:Number(e.functionCoverage||e.functions||0)},testsGenerated:Number(e.testsGenerated||0),testsPassed:Number(e.testsPassed||0),gapsTargeted:(e.gaps||[]).map((s,a)=>({id:String(s.id||`gap-${ke().slice(0,8)}-${a}`),type:["uncovered-line","uncovered-branch","uncovered-function","partial-branch"].includes(String(s.type))?String(s.type):"uncovered-line",filePath:String(s.file||s.filePath||""),startLine:Number(s.line||s.startLine||0),endLine:s.endLine?Number(s.endLine):void 0,riskScore:Number(s.riskScore||.5),addressed:!!s.addressed})),durationMs:t,startedAt:new Date(Date.now()-t),completedAt:new Date};await r.recordCoverageSession(i)}}}function Oi(u){let e=u.split(`
|
|
468
468
|
`).length,t=(u.match(/if|switch|for|while|catch/g)||[]).length;return{score:e+t*2,level:t>5?"high":t>2?"medium":"low"}}function Fi(u,e){let t=[];return u.level==="high"&&(t.push("Consider refactoring complex functions"),t.push("Add unit tests for each branch")),t.push("Consider adding edge case tests"),t.push("Add error handling tests"),e==="integration"&&(t.push("Add mock external dependencies"),t.push("Test API contract boundaries")),{recommendations:t,estimatedTime:`${Math.round(u.score*.5)} minutes`,confidence:.85}}function Ni(u,e,t,n){let r=[],i=/(?:function\s+(\w+)|const\s+(\w+)\s*=|def\s+(\w+)|func\s+(\w+))/g,s=[],a;for(;(a=i.exec(u))!==null;){let l=a[1]||a[2]||a[3]||a[4];l&&s.push(l)}for(let l=0;l<Math.min(s.length,n);l++){let c=s[l]||"exampleFunction";r.push({id:Me(),name:`test_${c}_${l}`,type:e,parameters:[],assertions:[`${c}() === null`],expectedResult:null,estimatedDuration:e==="integration"?2e3:1e3,aiGenerated:!0})}(e==="integration"||n>s.length)&&r.push({id:Me(),name:`integration_ComponentA_${r.length}`,type:"integration",parameters:[],assertions:["ComponentA integration test passes"],expectedResult:null,estimatedDuration:2e3,aiGenerated:!0});let o=["high-complexity","deep-nesting","null-handling","empty-input"];for(let l=r.length;l<n&&l-r.length<o.length;l++)r.push({id:Me(),name:`edge_case_${o[l-r.length]}_${l}`,type:"unit",parameters:[],assertions:[`${o[l-r.length]} edge case handled`],expectedResult:null,estimatedDuration:1500,aiGenerated:!0});return r}function Li(u,e){let t=[],n=u.split(`
|
|
469
|
-
`);return u.includes("eval(")&&t.push({type:"dangerous-eval",line:n.findIndex(r=>r.includes("eval("))+1,severity:"critical",suggestion:"Replace eval() with safer alternatives"}),u.includes("var ")&&(e==="javascript"||e==="typescript")&&t.push({type:"var-usage",line:n.findIndex(r=>r.includes("var "))+1,severity:"low",suggestion:"Use const or let instead of var"}),u.includes("any")&&e==="typescript"&&t.push({type:"any-type",line:n.findIndex(r=>r.includes("any"))+1,severity:"medium",suggestion:"Replace any with specific types"}),t}var Lt=null,ir=null,de=null;function so(){if(!Lt){let{kernel:u}=Ue();if(!u)throw new Error("Kernel not initialized");Lt=wi(u);let e=Lt;ir=ki().then(t=>(e.setQualityFeedbackLoop(t),t)).catch(t=>(console.warn("[HandlerFactory] Failed to initialize QualityFeedbackLoop:",t),null))}return Lt}async function qi(){if(de)return de;try{let{kernel:u}=Ue();if(!u)return null;let{createAQELearningEngine:e}=await import("./aqe-learning-engine-MV7NGY24.js"),t=u.memory;return de=e(t,{projectRoot:process.cwd(),enableClaudeFlow:!1}),await de.initialize(),de}catch(u){return console.debug("[HandlerFactory] Learning engine init failed:",w(u)),null}}async function ao(u,e){try{let t=await qi();if(!t)return[];let n=e,r=await t.searchPatterns(u,{limit:5,minConfidence:.4,domain:n,useVectorSearch:!0});return!r.success||r.value.length===0?[]:r.value.filter(i=>i.similarity>=.4).map(i=>({name:i.pattern.name,description:i.pattern.description,similarity:i.similarity,confidence:i.pattern.confidence,canReuse:i.canReuse,patternId:i.pattern.id}))}catch(t){return console.debug("[HandlerFactory] Pattern search failed:",w(t)),[]}}async function oo(u,e,t){try{let n=await ao(u,e);return n.length>0&&console.debug(`[HandlerFactory] Found ${n.length} relevant patterns for ${e}`),await(await Ot()).routeTask({task:u,domain:e,codeContext:t,agentType:`qe-${e}`,enablePatternSearch:!0,patternHints:n.length>0?n:void 0})}catch(n){return console.error(`[HandlerFactory] Routing failed for ${e}: ${n}`),null}}async function Ii(u,e,t,n){if(!(!u||u.length===0)&&de)try{for(let r of u)r.patternId&&await de.recordOutcome({patternId:r.patternId,success:e,metrics:{executionTimeMs:n},feedback:`Domain handler ${t} execution ${e?"succeeded":"failed"}`})}catch{}}function Q(u){let{domain:e,taskType:t,priority:n="p1",defaultTimeout:r=18e4,buildTaskDescription:i,mapToPayload:s,mapToResult:a,calculateTimeout:o,includeCodeContext:l}=u;return async c=>{if(!Gi())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let{queen:d}=Ue(),m=null;try{let p=i(c),g=l?.(c);m=await oo(p,e,g);let h=s(c,m),f=o?.(c)??r,v=await d.submitTask({type:t,priority:n,targetDomains:[e],payload:h,timeout:f});if(!v.success)return{success:!1,error:v.error.message};let y=so(),C=d.getTaskStatus(v.value);if(!C)return{success:!1,error:"Task not found after submission"};let b=await y.execute(C.task);if(!b.success)return{success:!1,error:b.error||"Task execution failed"};let E=b.data,S=a(v.value,E,b.duration,b.savedFiles,c);Ii(m?.patternHints,!0,e,b.duration),to(`qe-${e}`,t,c,E,b.duration).catch(()=>{});try{await io(e,E,b.duration,c)}catch{}return{success:!0,data:S}}catch(p){let g=w(p);return Ii(m?.patternHints,!1,e,0),{success:!1,error:`Failed to ${t.replace(/-/g," ")}: ${g}`}}}}var Gt=class{taskMetrics=[];agentMetrics=new Map;resourceSnapshots=[];workerLoads=new Map;activeTasks=new Map;lastCpuUsage=null;snapshotInterval=null;initialized=!1;initialize(){this.initialized||(this.initialized=!0,this.lastCpuUsage=process.cpuUsage(),this.snapshotInterval=setInterval(()=>{this.takeResourceSnapshot()},1e3),this.snapshotInterval.unref&&this.snapshotInterval.unref())}shutdown(){this.snapshotInterval&&(clearInterval(this.snapshotInterval),this.snapshotInterval=null),this.initialized=!1}startTask(e,t){this.ensureInitialized();let n={taskId:e,agentId:t,startTime:process.hrtime(),success:!1,retries:0};this.activeTasks.set(e,n),this.updateWorkerLoad(t,1,0)}recordRetry(e){let t=this.activeTasks.get(e);t&&t.retries++}completeTask(e,t){let n=this.activeTasks.get(e);if(!n)return 0;n.endTime=process.hrtime(),n.success=t;let r=process.hrtime(n.startTime);return n.durationMs=r[0]*1e3+r[1]/1e6,this.updateAgentMetrics(n),this.updateWorkerLoad(n.agentId,-1,1),this.taskMetrics.push(n),this.taskMetrics.length>100&&this.taskMetrics.shift(),this.activeTasks.delete(e),n.durationMs}getCpuUsagePercent(){if(this.ensureInitialized(),!this.lastCpuUsage)return this.lastCpuUsage=process.cpuUsage(),0;let e=process.cpuUsage(this.lastCpuUsage);this.lastCpuUsage=process.cpuUsage();let t=e.user+e.system,r=1e3*1e3,i=t/r*100;return Math.min(100,Math.max(0,i))}getMemoryUsagePercent(){let e=process.memoryUsage(),t=e.heapUsed/e.heapTotal*100;return Math.min(100,Math.max(0,t))}getResourceStats(e){return{cpu:this.getCpuUsagePercent(),memory:this.getMemoryUsagePercent()}}getAgentTaskStats(e){let t=this.agentMetrics.get(e);if(!t||t.taskCount===0)return{tasksCompleted:0,averageTime:0,successRate:1};let n=t.tasksCompleted+t.tasksFailed,r=n>0?t.tasksCompleted/n:1,i=t.taskCount>0?t.totalDurationMs/t.taskCount:0;return{tasksCompleted:t.tasksCompleted,averageTime:Math.round(i),successRate:Math.min(1,Math.max(0,r))}}getWorkerEfficiency(){if(this.taskMetrics.length===0)return .85;let t=this.taskMetrics.filter(a=>a.success).length/this.taskMetrics.length,r=this.taskMetrics.reduce((a,o)=>a+o.retries,0)/this.taskMetrics.length,i=Math.min(.2,r*.1),s=t*(1-i);return Math.min(1,Math.max(0,s))}getLoadBalanceScore(){if(this.workerLoads.size===0)return .9;let e=Array.from(this.workerLoads.values()).map(a=>a.completedTaskCount);if(e.length<=1)return 1;let t=e.reduce((a,o)=>a+o,0)/e.length;if(t===0)return 1;let n=e.reduce((a,o)=>a+Math.pow(o-t,2),0)/e.length,s=1/(1+Math.sqrt(n)/t);return Math.min(1,Math.max(0,s))}getRetryStats(){let e=0,t=0,n=0;for(let r of this.agentMetrics.values())e+=r.totalRetries,t+=r.successfulRetries,n+=r.maxRetriesReached;return{totalRetries:e,successfulRetries:t,maxRetriesReached:n}}getAverageExecutionTime(){if(this.taskMetrics.length===0)return 0;let e=this.taskMetrics.reduce((t,n)=>t+(n.durationMs||0),0);return Math.round(e/this.taskMetrics.length)}getWorkersUsed(){return this.workerLoads.size}getTestDurations(e){let t=[];if(this.taskMetrics.length===0){for(let r=0;r<e;r++)t.push(100+r*10);return t}let n=this.taskMetrics.map(r=>r.durationMs||200).sort((r,i)=>r-i);for(let r=0;r<e;r++){let i=r%n.length;t.push(Math.round(n[i]))}return t}recordSuccessfulRetry(e){let t=this.agentMetrics.get(e);t&&t.successfulRetries++}recordMaxRetriesReached(e){let t=this.agentMetrics.get(e);t&&t.maxRetriesReached++}reset(){this.taskMetrics=[],this.agentMetrics.clear(),this.resourceSnapshots=[],this.workerLoads.clear(),this.activeTasks.clear(),this.lastCpuUsage=null}ensureInitialized(){this.initialized||this.initialize()}updateAgentMetrics(e){let t=this.agentMetrics.get(e.agentId);t||(t={agentId:e.agentId,tasksCompleted:0,tasksFailed:0,totalRetries:0,successfulRetries:0,maxRetriesReached:0,totalDurationMs:0,taskCount:0},this.agentMetrics.set(e.agentId,t)),e.success?(t.tasksCompleted++,e.retries>0&&t.successfulRetries++):t.tasksFailed++,t.totalRetries+=e.retries,t.totalDurationMs+=e.durationMs||0,t.taskCount++}updateWorkerLoad(e,t,n){let r=this.workerLoads.get(e);r||(r={workerId:e,activeTaskCount:0,completedTaskCount:0,lastActivityTime:Date.now()},this.workerLoads.set(e,r)),r.activeTaskCount=Math.max(0,r.activeTaskCount+t),r.completedTaskCount+=n,r.lastActivityTime=Date.now()}takeResourceSnapshot(){let e=process.memoryUsage(),t=process.cpuUsage(),n={timestamp:Date.now(),cpuUser:t.user,cpuSystem:t.system,memoryHeapUsed:e.heapUsed,memoryHeapTotal:e.heapTotal,memoryExternal:e.external,memoryRss:e.rss};this.resourceSnapshots.push(n),this.resourceSnapshots.length>60&&this.resourceSnapshots.shift()}},me=new Gt;var zi={domain:"test-generation",taskType:"generate-tests",priority:"p1",defaultTimeout:12e4,buildTaskDescription:u=>`Generate ${u.testType||"unit"} tests for ${u.language||"typescript"} code`,includeCodeContext:u=>u.sourceCode,mapToPayload:(u,e)=>({sourceCode:u.sourceCode,filePath:u.filePath,language:u.language||"typescript",framework:u.framework||"vitest",testType:u.testType||"unit",coverageGoal:u.coverageGoal||80,aiEnhancement:u.aiEnhancement!==!1,detectAntiPatterns:u.detectAntiPatterns||!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(u,e,t,n,r)=>{let i=r?.sourceCode||"",s=r?.language||"typescript",a=r?.testType||"unit",o=e.testsGenerated||6,l=Oi(i),c=r?.aiEnhancement!==!1?Fi(l,a):{recommendations:[],estimatedTime:"0 minutes",confidence:0},d=r?.detectAntiPatterns?Li(i,s):[],m=qt("test-generator"),p=e.tests,h=Array.isArray(p)&&p.length>0&&p[0].testCode?p.map((f,v)=>({id:Me(),name:f.name||`test_${v}`,type:f.type||a,parameters:[],assertions:f.testCode?co(f.testCode):[`test assertion ${v}`],expectedResult:null,estimatedDuration:f.type==="integration"?2e3:1e3,aiGenerated:!0,testCode:f.testCode,sourceFile:f.sourceFile,testFile:f.testFile||f.file})):Ni(i,a,s,o);return{tests:h,antiPatterns:d,suggestions:d.map(f=>`Fix: ${f.type} - ${f.suggestion}`),aiInsights:c,coverage:{predicted:e.coverageEstimate||r?.coverageGoal||80,confidence:.9,achievable:!0},properties:h.filter(f=>f.type==="property").map(f=>({name:f.name,invariant:"output_matches_expectation"})),language:s,complexity:l,learning:m,taskId:u,status:"completed",testsGenerated:h.length,coverageEstimate:e.coverageEstimate||r?.coverageGoal||80,patternsUsed:e.patternsUsed||["assertion-patterns","mock-generation","edge-case-detection"],duration:t,savedFiles:n}}},$i={domain:"test-execution",taskType:"execute-tests",priority:"p1",defaultTimeout:3e5,buildTaskDescription:u=>`Execute ${u.testFiles?.length||0} test files with ${u.parallel!==!1?"parallel":"sequential"} execution`,mapToPayload:(u,e)=>({testFiles:u.testFiles||[],testSuites:u.testSuites||[],parallel:u.parallel!==!1,parallelism:u.parallelism||4,retryCount:u.retryCount||3,timeout:u.timeout||6e4,collectCoverage:u.collectCoverage||!1,reportFormat:u.reportFormat||"json",routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),calculateTimeout:u=>u.timeout||3e5,mapToResult:(u,e,t,n,r)=>{let i=e.total||0,s=e.passed||0,a=e.failed||0,o=e.coverage,l=r?.parallelism||4,c=me.getRetryStats(),d=me.getWorkersUsed(),m={workersUsed:d>0?d:Math.min(l,i||1),efficiency:me.getWorkerEfficiency(),loadBalance:me.getLoadBalanceScore(),avgExecutionTime:t/Math.max(i,1)},p={totalRetries:c.totalRetries,successfulRetries:c.successfulRetries,maxRetriesReached:c.maxRetriesReached},g=qt("test-executor");return{workerStats:m,retryStats:p,results:(()=>{let h=me.getTestDurations(i);return Array.from({length:i},(f,v)=>({id:Me(),name:`test_case_${v}`,status:v<s?"passed":"failed",duration:h[v]||200,retries:0}))})(),summary:{totalTests:i,passRate:i>0?s/i*100:0,avgDuration:t/Math.max(i,1),parallelEfficiency:m.efficiency},learning:g,taskId:u,status:"completed",total:i,passed:s,failed:a,duration:t,coverage:o,savedFiles:n}}},Bi={domain:"coverage-analysis",taskType:"analyze-coverage",priority:"p1",defaultTimeout:18e4,buildTaskDescription:u=>`Analyze coverage for ${u.target||"project"} with gap detection`,mapToPayload:(u,e)=>({target:u.target||".",includeRisk:u.includeRisk||!1,detectGaps:u.detectGaps!==!1,mlPowered:u.mlPowered||!1,prioritization:u.prioritization||"complexity",routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(u,e,t,n)=>{let r=e.summary,i=r?.line??e.lineCoverage??0,s=r?.branch??e.branchCoverage??0,a=r?.function??e.functionCoverage??0,o=r?.statement??e.statementCoverage??i,l=r?.files??e.totalFiles??0,c=e.gaps||[],d=qt("coverage-analyzer"),m=c.map((h,f)=>{let v=h;return v?.file?{id:`gap-${Date.now()}-${f}`,file:v.file,line:v.lines?.[0]||0,uncoveredLines:v.lines||[],type:v.type||"uncovered-line",severity:v.severity||"medium",reason:v.reason||"Missing test case",priority:v.priority||"medium",suggestion:v.suggestedTest||"Add test coverage",suggestedTest:v.suggestedTest||"Add test coverage",riskScore:v.riskScore||.5,confidence:v.confidence||.7}:null}).filter(h=>h!==null),p=e.coverageByFile;return{coverageByFile:p?p.map(h=>({file:h.file,lineCoverage:h.lineCoverage||0,branchCoverage:h.branchCoverage||0,functionCoverage:h.functionCoverage||0})):[],gapAnalysis:{totalGaps:m.length,highPriority:m.filter(h=>h.priority==="high").length,gaps:m},trends:{lineCoverageTrend:l>0?"stable":"no-data",branchCoverageTrend:l>0?"stable":"no-data",weeklyChange:0},aiInsights:l>0?{recommendations:e.recommendations||["Run tests with coverage enabled to get accurate metrics"],riskAssessment:i<70?"high":i<85?"medium":"low",confidence:.88}:{recommendations:["No coverage data found. Run tests with coverage first (e.g., npm test -- --coverage, or pytest --cov)"],riskAssessment:"unknown",confidence:0},learning:d,taskId:u,status:"completed",lineCoverage:i,branchCoverage:s,functionCoverage:a,statementCoverage:o,totalFiles:l,gaps:m,duration:t,savedFiles:n}}},Ui={domain:"quality-assessment",taskType:"assess-quality",priority:"p0",defaultTimeout:18e4,buildTaskDescription:u=>`Assess quality with ${u.runGate?"quality gate":"metrics analysis"}`,mapToPayload:(u,e)=>({runGate:u.runGate||!1,threshold:u.threshold||80,metrics:u.metrics||["coverage","complexity","maintainability"],routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(u,e,t,n)=>({taskId:u,status:"completed",qualityScore:e.qualityScore||0,passed:e.passed||!1,metrics:e.metrics||{},recommendations:e.recommendations||[],duration:t,savedFiles:n})},Hi={domain:"security-compliance",taskType:"scan-security",priority:"p0",defaultTimeout:6e5,buildTaskDescription:u=>{let e=[];return u.sast!==!1&&e.push("SAST"),u.dast&&e.push("DAST"),`Security scan (${e.join(", ")}) for ${u.target||"project"}`},mapToPayload:(u,e)=>({sast:u.sast!==!1,dast:u.dast||!1,compliance:u.compliance||[],target:u.target||".",routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(u,e,t,n)=>({taskId:u,status:"completed",vulnerabilities:e.vulnerabilities||0,critical:e.critical||0,high:e.high||0,medium:e.medium||0,low:e.low||0,topVulnerabilities:e.topVulnerabilities||[],recommendations:e.recommendations||[],duration:t,savedFiles:n})},ji={domain:"contract-testing",taskType:"validate-contracts",priority:"p1",defaultTimeout:18e4,buildTaskDescription:u=>`Validate API contract at ${u.contractPath}`,mapToPayload:(u,e)=>({contractPath:u.contractPath,providerUrl:u.providerUrl,consumerName:u.consumerName,checkBreakingChanges:u.checkBreakingChanges!==!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(u,e,t,n)=>({taskId:u,status:"completed",valid:e.valid||!1,breakingChanges:e.breakingChanges||[],warnings:e.warnings||[],duration:t,savedFiles:n})},Vi={domain:"visual-accessibility",taskType:"test-accessibility",priority:"p1",defaultTimeout:18e4,buildTaskDescription:u=>`Test accessibility for ${u.url} against ${u.standard||"WCAG 2.1 AA"} standard`,mapToPayload:(u,e)=>({url:u.url,standard:u.standard||"wcag21-aa",includeScreenReader:u.includeScreenReader||!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(u,e,t,n)=>({taskId:u,status:"completed",passed:e.passed||!1,score:e.score||0,violations:e.violations||[],warnings:e.warnings||[],duration:t,savedFiles:n})},Qi={domain:"chaos-resilience",taskType:"run-chaos",priority:"p2",defaultTimeout:9e4,buildTaskDescription:u=>`Run chaos test with ${u.faultType||"latency"} fault injection on ${u.target}`,mapToPayload:(u,e)=>({faultType:u.faultType||"latency",target:u.target,duration:u.duration||3e4,intensity:u.intensity||50,dryRun:u.dryRun!==!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),calculateTimeout:u=>(u.duration||3e4)+6e4,mapToResult:(u,e,t,n)=>({taskId:u,status:"completed",faultType:e.faultType||"latency",resilience:e.resilience||{recovered:!1,recoveryTime:0,dataLoss:!1},duration:t,savedFiles:n})},Wi={domain:"defect-intelligence",taskType:"predict-defects",priority:"p1",defaultTimeout:18e4,buildTaskDescription:u=>`Predict defects in ${u.target||"codebase"} with ${u.lookback||30} day lookback`,mapToPayload:(u,e)=>({target:u.target||".",lookback:u.lookback||30,minConfidence:u.minConfidence||.7,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(u,e,t,n)=>({taskId:u,status:"completed",predictedDefects:e.predictedDefects||[],riskScore:e.riskScore||0,recommendations:e.recommendations||[],duration:t,savedFiles:n})},Ki={domain:"requirements-validation",taskType:"validate-requirements",priority:"p1",defaultTimeout:18e4,buildTaskDescription:u=>`Validate requirements${u.generateBDD?" and generate BDD scenarios":""}`,mapToPayload:(u,e)=>({requirementsPath:u.requirementsPath,testPath:u.testPath,generateBDD:u.generateBDD||!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(u,e,t,n)=>({taskId:u,status:"completed",requirementsAnalyzed:e.requirementsAnalyzed||0,testable:e.testable||0,coverage:e.coverage||0,bddScenarios:e.bddScenarios||[],duration:t,savedFiles:n})},Xi={domain:"code-intelligence",taskType:"index-code",priority:"p2",defaultTimeout:3e5,buildTaskDescription:u=>`Index code in ${u.target||"codebase"}${u.incremental?" incrementally":""}`,mapToPayload:(u,e)=>({target:u.target||".",incremental:u.incremental||!1,gitSince:u.gitSince,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(u,e,t,n)=>({taskId:u,status:"completed",filesIndexed:e.filesIndexed||0,symbolsExtracted:e.symbolsExtracted||0,relationsFound:e.relationsFound||0,duration:t,savedFiles:n})};function co(u){let e=[],t=u.split(`
|
|
469
|
+
`);return u.includes("eval(")&&t.push({type:"dangerous-eval",line:n.findIndex(r=>r.includes("eval("))+1,severity:"critical",suggestion:"Replace eval() with safer alternatives"}),u.includes("var ")&&(e==="javascript"||e==="typescript")&&t.push({type:"var-usage",line:n.findIndex(r=>r.includes("var "))+1,severity:"low",suggestion:"Use const or let instead of var"}),u.includes("any")&&e==="typescript"&&t.push({type:"any-type",line:n.findIndex(r=>r.includes("any"))+1,severity:"medium",suggestion:"Replace any with specific types"}),t}var Lt=null,ir=null,de=null;function so(){if(!Lt){let{kernel:u}=Ue();if(!u)throw new Error("Kernel not initialized");Lt=wi(u);let e=Lt;ir=ki().then(t=>(e.setQualityFeedbackLoop(t),t)).catch(t=>(console.warn("[HandlerFactory] Failed to initialize QualityFeedbackLoop:",t),null))}return Lt}async function qi(){if(de)return de;try{let{kernel:u}=Ue();if(!u)return null;let{createAQELearningEngine:e}=await import("./aqe-learning-engine-PWGRS6KK.js"),t=u.memory;return de=e(t,{projectRoot:process.cwd(),enableClaudeFlow:!1}),await de.initialize(),de}catch(u){return console.debug("[HandlerFactory] Learning engine init failed:",w(u)),null}}async function ao(u,e){try{let t=await qi();if(!t)return[];let n=e,r=await t.searchPatterns(u,{limit:5,minConfidence:.4,domain:n,useVectorSearch:!0});return!r.success||r.value.length===0?[]:r.value.filter(i=>i.similarity>=.4).map(i=>({name:i.pattern.name,description:i.pattern.description,similarity:i.similarity,confidence:i.pattern.confidence,canReuse:i.canReuse,patternId:i.pattern.id}))}catch(t){return console.debug("[HandlerFactory] Pattern search failed:",w(t)),[]}}async function oo(u,e,t){try{let n=await ao(u,e);return n.length>0&&console.debug(`[HandlerFactory] Found ${n.length} relevant patterns for ${e}`),await(await Ot()).routeTask({task:u,domain:e,codeContext:t,agentType:`qe-${e}`,enablePatternSearch:!0,patternHints:n.length>0?n:void 0})}catch(n){return console.error(`[HandlerFactory] Routing failed for ${e}: ${n}`),null}}async function Ii(u,e,t,n){if(!(!u||u.length===0)&&de)try{for(let r of u)r.patternId&&await de.recordOutcome({patternId:r.patternId,success:e,metrics:{executionTimeMs:n},feedback:`Domain handler ${t} execution ${e?"succeeded":"failed"}`})}catch{}}function Q(u){let{domain:e,taskType:t,priority:n="p1",defaultTimeout:r=18e4,buildTaskDescription:i,mapToPayload:s,mapToResult:a,calculateTimeout:o,includeCodeContext:l}=u;return async c=>{if(!Gi())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let{queen:d}=Ue(),m=null;try{let p=i(c),g=l?.(c);m=await oo(p,e,g);let h=s(c,m),f=o?.(c)??r,v=await d.submitTask({type:t,priority:n,targetDomains:[e],payload:h,timeout:f});if(!v.success)return{success:!1,error:v.error.message};let y=so(),C=d.getTaskStatus(v.value);if(!C)return{success:!1,error:"Task not found after submission"};let b=await y.execute(C.task);if(!b.success)return{success:!1,error:b.error||"Task execution failed"};let E=b.data,S=a(v.value,E,b.duration,b.savedFiles,c);Ii(m?.patternHints,!0,e,b.duration),to(`qe-${e}`,t,c,E,b.duration).catch(()=>{});try{await io(e,E,b.duration,c)}catch{}return{success:!0,data:S}}catch(p){let g=w(p);return Ii(m?.patternHints,!1,e,0),{success:!1,error:`Failed to ${t.replace(/-/g," ")}: ${g}`}}}}var Gt=class{taskMetrics=[];agentMetrics=new Map;resourceSnapshots=[];workerLoads=new Map;activeTasks=new Map;lastCpuUsage=null;snapshotInterval=null;initialized=!1;initialize(){this.initialized||(this.initialized=!0,this.lastCpuUsage=process.cpuUsage(),this.snapshotInterval=setInterval(()=>{this.takeResourceSnapshot()},1e3),this.snapshotInterval.unref&&this.snapshotInterval.unref())}shutdown(){this.snapshotInterval&&(clearInterval(this.snapshotInterval),this.snapshotInterval=null),this.initialized=!1}startTask(e,t){this.ensureInitialized();let n={taskId:e,agentId:t,startTime:process.hrtime(),success:!1,retries:0};this.activeTasks.set(e,n),this.updateWorkerLoad(t,1,0)}recordRetry(e){let t=this.activeTasks.get(e);t&&t.retries++}completeTask(e,t){let n=this.activeTasks.get(e);if(!n)return 0;n.endTime=process.hrtime(),n.success=t;let r=process.hrtime(n.startTime);return n.durationMs=r[0]*1e3+r[1]/1e6,this.updateAgentMetrics(n),this.updateWorkerLoad(n.agentId,-1,1),this.taskMetrics.push(n),this.taskMetrics.length>100&&this.taskMetrics.shift(),this.activeTasks.delete(e),n.durationMs}getCpuUsagePercent(){if(this.ensureInitialized(),!this.lastCpuUsage)return this.lastCpuUsage=process.cpuUsage(),0;let e=process.cpuUsage(this.lastCpuUsage);this.lastCpuUsage=process.cpuUsage();let t=e.user+e.system,r=1e3*1e3,i=t/r*100;return Math.min(100,Math.max(0,i))}getMemoryUsagePercent(){let e=process.memoryUsage(),t=e.heapUsed/e.heapTotal*100;return Math.min(100,Math.max(0,t))}getResourceStats(e){return{cpu:this.getCpuUsagePercent(),memory:this.getMemoryUsagePercent()}}getAgentTaskStats(e){let t=this.agentMetrics.get(e);if(!t||t.taskCount===0)return{tasksCompleted:0,averageTime:0,successRate:1};let n=t.tasksCompleted+t.tasksFailed,r=n>0?t.tasksCompleted/n:1,i=t.taskCount>0?t.totalDurationMs/t.taskCount:0;return{tasksCompleted:t.tasksCompleted,averageTime:Math.round(i),successRate:Math.min(1,Math.max(0,r))}}getWorkerEfficiency(){if(this.taskMetrics.length===0)return .85;let t=this.taskMetrics.filter(a=>a.success).length/this.taskMetrics.length,r=this.taskMetrics.reduce((a,o)=>a+o.retries,0)/this.taskMetrics.length,i=Math.min(.2,r*.1),s=t*(1-i);return Math.min(1,Math.max(0,s))}getLoadBalanceScore(){if(this.workerLoads.size===0)return .9;let e=Array.from(this.workerLoads.values()).map(a=>a.completedTaskCount);if(e.length<=1)return 1;let t=e.reduce((a,o)=>a+o,0)/e.length;if(t===0)return 1;let n=e.reduce((a,o)=>a+Math.pow(o-t,2),0)/e.length,s=1/(1+Math.sqrt(n)/t);return Math.min(1,Math.max(0,s))}getRetryStats(){let e=0,t=0,n=0;for(let r of this.agentMetrics.values())e+=r.totalRetries,t+=r.successfulRetries,n+=r.maxRetriesReached;return{totalRetries:e,successfulRetries:t,maxRetriesReached:n}}getAverageExecutionTime(){if(this.taskMetrics.length===0)return 0;let e=this.taskMetrics.reduce((t,n)=>t+(n.durationMs||0),0);return Math.round(e/this.taskMetrics.length)}getWorkersUsed(){return this.workerLoads.size}getTestDurations(e){let t=[];if(this.taskMetrics.length===0){for(let r=0;r<e;r++)t.push(100+r*10);return t}let n=this.taskMetrics.map(r=>r.durationMs||200).sort((r,i)=>r-i);for(let r=0;r<e;r++){let i=r%n.length;t.push(Math.round(n[i]))}return t}recordSuccessfulRetry(e){let t=this.agentMetrics.get(e);t&&t.successfulRetries++}recordMaxRetriesReached(e){let t=this.agentMetrics.get(e);t&&t.maxRetriesReached++}reset(){this.taskMetrics=[],this.agentMetrics.clear(),this.resourceSnapshots=[],this.workerLoads.clear(),this.activeTasks.clear(),this.lastCpuUsage=null}ensureInitialized(){this.initialized||this.initialize()}updateAgentMetrics(e){let t=this.agentMetrics.get(e.agentId);t||(t={agentId:e.agentId,tasksCompleted:0,tasksFailed:0,totalRetries:0,successfulRetries:0,maxRetriesReached:0,totalDurationMs:0,taskCount:0},this.agentMetrics.set(e.agentId,t)),e.success?(t.tasksCompleted++,e.retries>0&&t.successfulRetries++):t.tasksFailed++,t.totalRetries+=e.retries,t.totalDurationMs+=e.durationMs||0,t.taskCount++}updateWorkerLoad(e,t,n){let r=this.workerLoads.get(e);r||(r={workerId:e,activeTaskCount:0,completedTaskCount:0,lastActivityTime:Date.now()},this.workerLoads.set(e,r)),r.activeTaskCount=Math.max(0,r.activeTaskCount+t),r.completedTaskCount+=n,r.lastActivityTime=Date.now()}takeResourceSnapshot(){let e=process.memoryUsage(),t=process.cpuUsage(),n={timestamp:Date.now(),cpuUser:t.user,cpuSystem:t.system,memoryHeapUsed:e.heapUsed,memoryHeapTotal:e.heapTotal,memoryExternal:e.external,memoryRss:e.rss};this.resourceSnapshots.push(n),this.resourceSnapshots.length>60&&this.resourceSnapshots.shift()}},me=new Gt;var zi={domain:"test-generation",taskType:"generate-tests",priority:"p1",defaultTimeout:12e4,buildTaskDescription:u=>`Generate ${u.testType||"unit"} tests for ${u.language||"typescript"} code`,includeCodeContext:u=>u.sourceCode,mapToPayload:(u,e)=>({sourceCode:u.sourceCode,filePath:u.filePath,language:u.language||"typescript",framework:u.framework||"vitest",testType:u.testType||"unit",coverageGoal:u.coverageGoal||80,aiEnhancement:u.aiEnhancement!==!1,detectAntiPatterns:u.detectAntiPatterns||!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(u,e,t,n,r)=>{let i=r?.sourceCode||"",s=r?.language||"typescript",a=r?.testType||"unit",o=e.testsGenerated||6,l=Oi(i),c=r?.aiEnhancement!==!1?Fi(l,a):{recommendations:[],estimatedTime:"0 minutes",confidence:0},d=r?.detectAntiPatterns?Li(i,s):[],m=qt("test-generator"),p=e.tests,h=Array.isArray(p)&&p.length>0&&p[0].testCode?p.map((f,v)=>({id:Me(),name:f.name||`test_${v}`,type:f.type||a,parameters:[],assertions:f.testCode?co(f.testCode):[`test assertion ${v}`],expectedResult:null,estimatedDuration:f.type==="integration"?2e3:1e3,aiGenerated:!0,testCode:f.testCode,sourceFile:f.sourceFile,testFile:f.testFile||f.file})):Ni(i,a,s,o);return{tests:h,antiPatterns:d,suggestions:d.map(f=>`Fix: ${f.type} - ${f.suggestion}`),aiInsights:c,coverage:{predicted:e.coverageEstimate||r?.coverageGoal||80,confidence:.9,achievable:!0},properties:h.filter(f=>f.type==="property").map(f=>({name:f.name,invariant:"output_matches_expectation"})),language:s,complexity:l,learning:m,taskId:u,status:"completed",testsGenerated:h.length,coverageEstimate:e.coverageEstimate||r?.coverageGoal||80,patternsUsed:e.patternsUsed||["assertion-patterns","mock-generation","edge-case-detection"],duration:t,savedFiles:n}}},$i={domain:"test-execution",taskType:"execute-tests",priority:"p1",defaultTimeout:3e5,buildTaskDescription:u=>`Execute ${u.testFiles?.length||0} test files with ${u.parallel!==!1?"parallel":"sequential"} execution`,mapToPayload:(u,e)=>({testFiles:u.testFiles||[],testSuites:u.testSuites||[],parallel:u.parallel!==!1,parallelism:u.parallelism||4,retryCount:u.retryCount||3,timeout:u.timeout||6e4,collectCoverage:u.collectCoverage||!1,reportFormat:u.reportFormat||"json",routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),calculateTimeout:u=>u.timeout||3e5,mapToResult:(u,e,t,n,r)=>{let i=e.total||0,s=e.passed||0,a=e.failed||0,o=e.coverage,l=r?.parallelism||4,c=me.getRetryStats(),d=me.getWorkersUsed(),m={workersUsed:d>0?d:Math.min(l,i||1),efficiency:me.getWorkerEfficiency(),loadBalance:me.getLoadBalanceScore(),avgExecutionTime:t/Math.max(i,1)},p={totalRetries:c.totalRetries,successfulRetries:c.successfulRetries,maxRetriesReached:c.maxRetriesReached},g=qt("test-executor");return{workerStats:m,retryStats:p,results:(()=>{let h=me.getTestDurations(i);return Array.from({length:i},(f,v)=>({id:Me(),name:`test_case_${v}`,status:v<s?"passed":"failed",duration:h[v]||200,retries:0}))})(),summary:{totalTests:i,passRate:i>0?s/i*100:0,avgDuration:t/Math.max(i,1),parallelEfficiency:m.efficiency},learning:g,taskId:u,status:"completed",total:i,passed:s,failed:a,duration:t,coverage:o,savedFiles:n}}},Bi={domain:"coverage-analysis",taskType:"analyze-coverage",priority:"p1",defaultTimeout:18e4,buildTaskDescription:u=>`Analyze coverage for ${u.target||"project"} with gap detection`,mapToPayload:(u,e)=>({target:u.target||".",includeRisk:u.includeRisk||!1,detectGaps:u.detectGaps!==!1,mlPowered:u.mlPowered||!1,prioritization:u.prioritization||"complexity",routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(u,e,t,n)=>{let r=e.summary,i=r?.line??e.lineCoverage??0,s=r?.branch??e.branchCoverage??0,a=r?.function??e.functionCoverage??0,o=r?.statement??e.statementCoverage??i,l=r?.files??e.totalFiles??0,c=e.gaps||[],d=qt("coverage-analyzer"),m=c.map((h,f)=>{let v=h;return v?.file?{id:`gap-${Date.now()}-${f}`,file:v.file,line:v.lines?.[0]||0,uncoveredLines:v.lines||[],type:v.type||"uncovered-line",severity:v.severity||"medium",reason:v.reason||"Missing test case",priority:v.priority||"medium",suggestion:v.suggestedTest||"Add test coverage",suggestedTest:v.suggestedTest||"Add test coverage",riskScore:v.riskScore||.5,confidence:v.confidence||.7}:null}).filter(h=>h!==null),p=e.coverageByFile;return{coverageByFile:p?p.map(h=>({file:h.file,lineCoverage:h.lineCoverage||0,branchCoverage:h.branchCoverage||0,functionCoverage:h.functionCoverage||0})):[],gapAnalysis:{totalGaps:m.length,highPriority:m.filter(h=>h.priority==="high").length,gaps:m},trends:{lineCoverageTrend:l>0?"stable":"no-data",branchCoverageTrend:l>0?"stable":"no-data",weeklyChange:0},aiInsights:l>0?{recommendations:e.recommendations||["Run tests with coverage enabled to get accurate metrics"],riskAssessment:i<70?"high":i<85?"medium":"low",confidence:.88}:{recommendations:["No coverage data found. Run tests with coverage first (e.g., npm test -- --coverage, or pytest --cov)"],riskAssessment:"unknown",confidence:0},learning:d,taskId:u,status:"completed",lineCoverage:i,branchCoverage:s,functionCoverage:a,statementCoverage:o,totalFiles:l,gaps:m,duration:t,savedFiles:n}}},Ui={domain:"quality-assessment",taskType:"assess-quality",priority:"p0",defaultTimeout:18e4,buildTaskDescription:u=>`Assess quality with ${u.runGate?"quality gate":"metrics analysis"}`,mapToPayload:(u,e)=>({runGate:u.runGate||!1,threshold:u.threshold||80,metrics:u.metrics||["coverage","complexity","maintainability"],routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(u,e,t,n)=>({taskId:u,status:"completed",qualityScore:e.qualityScore||0,passed:e.passed||!1,metrics:e.metrics||{},recommendations:e.recommendations||[],duration:t,savedFiles:n})},Hi={domain:"security-compliance",taskType:"scan-security",priority:"p0",defaultTimeout:6e5,buildTaskDescription:u=>{let e=[];return u.sast!==!1&&e.push("SAST"),u.dast&&e.push("DAST"),`Security scan (${e.join(", ")}) for ${u.target||"project"}`},mapToPayload:(u,e)=>({sast:u.sast!==!1,dast:u.dast||!1,compliance:u.compliance||[],target:u.target||".",routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(u,e,t,n)=>({taskId:u,status:"completed",vulnerabilities:e.vulnerabilities||0,critical:e.critical||0,high:e.high||0,medium:e.medium||0,low:e.low||0,topVulnerabilities:e.topVulnerabilities||[],recommendations:e.recommendations||[],duration:t,savedFiles:n})},ji={domain:"contract-testing",taskType:"validate-contracts",priority:"p1",defaultTimeout:18e4,buildTaskDescription:u=>`Validate API contract at ${u.contractPath}`,mapToPayload:(u,e)=>({contractPath:u.contractPath,providerUrl:u.providerUrl,consumerName:u.consumerName,checkBreakingChanges:u.checkBreakingChanges!==!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(u,e,t,n)=>({taskId:u,status:"completed",valid:e.valid||!1,breakingChanges:e.breakingChanges||[],warnings:e.warnings||[],duration:t,savedFiles:n})},Vi={domain:"visual-accessibility",taskType:"test-accessibility",priority:"p1",defaultTimeout:18e4,buildTaskDescription:u=>`Test accessibility for ${u.url} against ${u.standard||"WCAG 2.1 AA"} standard`,mapToPayload:(u,e)=>({url:u.url,standard:u.standard||"wcag21-aa",includeScreenReader:u.includeScreenReader||!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(u,e,t,n)=>({taskId:u,status:"completed",passed:e.passed||!1,score:e.score||0,violations:e.violations||[],warnings:e.warnings||[],duration:t,savedFiles:n})},Qi={domain:"chaos-resilience",taskType:"run-chaos",priority:"p2",defaultTimeout:9e4,buildTaskDescription:u=>`Run chaos test with ${u.faultType||"latency"} fault injection on ${u.target}`,mapToPayload:(u,e)=>({faultType:u.faultType||"latency",target:u.target,duration:u.duration||3e4,intensity:u.intensity||50,dryRun:u.dryRun!==!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),calculateTimeout:u=>(u.duration||3e4)+6e4,mapToResult:(u,e,t,n)=>({taskId:u,status:"completed",faultType:e.faultType||"latency",resilience:e.resilience||{recovered:!1,recoveryTime:0,dataLoss:!1},duration:t,savedFiles:n})},Wi={domain:"defect-intelligence",taskType:"predict-defects",priority:"p1",defaultTimeout:18e4,buildTaskDescription:u=>`Predict defects in ${u.target||"codebase"} with ${u.lookback||30} day lookback`,mapToPayload:(u,e)=>({target:u.target||".",lookback:u.lookback||30,minConfidence:u.minConfidence||.7,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(u,e,t,n)=>({taskId:u,status:"completed",predictedDefects:e.predictedDefects||[],riskScore:e.riskScore||0,recommendations:e.recommendations||[],duration:t,savedFiles:n})},Ki={domain:"requirements-validation",taskType:"validate-requirements",priority:"p1",defaultTimeout:18e4,buildTaskDescription:u=>`Validate requirements${u.generateBDD?" and generate BDD scenarios":""}`,mapToPayload:(u,e)=>({requirementsPath:u.requirementsPath,testPath:u.testPath,generateBDD:u.generateBDD||!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(u,e,t,n)=>({taskId:u,status:"completed",requirementsAnalyzed:e.requirementsAnalyzed||0,testable:e.testable||0,coverage:e.coverage||0,bddScenarios:e.bddScenarios||[],duration:t,savedFiles:n})},Xi={domain:"code-intelligence",taskType:"index-code",priority:"p2",defaultTimeout:3e5,buildTaskDescription:u=>`Index code in ${u.target||"codebase"}${u.incremental?" incrementally":""}`,mapToPayload:(u,e)=>({target:u.target||".",incremental:u.incremental||!1,gitSince:u.gitSince,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(u,e,t,n)=>({taskId:u,status:"completed",filesIndexed:e.filesIndexed||0,symbolsExtracted:e.symbolsExtracted||0,relationsFound:e.relationsFound||0,duration:t,savedFiles:n})};function co(u){let e=[],t=u.split(`
|
|
470
470
|
`);for(let n of t){let r=n.trim(),i=r.match(/expect\((.+?)\)\.(to\w+)\((.+?)\)/);if(i){e.push(`expect(${i[1]}).${i[2]}(${i[3]})`);continue}let s=r.match(/assert\w*\((.+)\)/);if(s){e.push(s[0]);continue}let a=r.match(/(?:it|test)\s*\(\s*['"`](.+?)['"`]/);a&&e.push(a[1])}return e.length>0?e:["test generated from source analysis"]}var Vp=Q(zi),Qp=Q($i),Wp=Q(Bi),Kp=Q(Ui),Xp=Q(Hi),Yp=Q(ji),Jp=Q(Vi),Zp=Q(Qi),eg=Q(Wi),tg=Q(Ki),ng=Q(Xi);k();var zt=class extends x{config={name:"qe/tests/generate",description:"Generate tests for source code files. Supports unit, integration, and e2e tests with AI-powered pattern recognition.",domain:"test-generation",schema:lo,streaming:!0,timeout:12e4};testGeneratorService=null;async getService(){if(!this.testGeneratorService){let e=await F();this.testGeneratorService=Pr(e,{defaultFramework:"vitest",maxTestsPerFile:50,coverageTargetDefault:80,enableAIGeneration:!0})}return this.testGeneratorService}async execute(e,t){let{sourceFiles:n,testType:r="unit",framework:i="vitest",language:s="typescript",coverageTarget:a=80,patterns:o=[],aiEnhancement:l=!0,detectAntiPatterns:c=!1}=e;try{if(this.emitStream(t,{status:"analyzing",message:`Analyzing ${n.length} source files`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};if(wn.isEnabled()){let v=`Generate ${r} tests for ${n.length} files using ${i}`,y=await wn.checkTaskEarlyExit(v,"test-generation");y.canExit&&y.reusedPattern&&(this.emitStream(t,{status:"pattern-reuse",message:`Reusing pattern: ${y.reusedPattern.name}`,tokensSaved:y.estimatedTokensSaved}),console.log(`[TestGenerateTool] Early exit: reusing pattern ${y.reusedPattern.name}, saving ~${y.estimatedTokensSaved} tokens`))}let d=await this.getService(),m={sourceFiles:n,testType:r,framework:i,coverageTarget:a,patterns:o},p=await d.generateTests(m);if(!p.success)return{success:!1,error:p.error?.message||"Test generation failed"};let g=p.value,h=g.tests.map(v=>({id:v.id,name:v.name,sourceFile:v.sourceFile,testFile:v.testFile,testCode:v.testCode,type:v.type,assertions:v.assertions}));this.emitStream(t,{status:"generating",message:`Generated ${h.length} test files`,progress:50});let f=c?uo(n):[];return this.emitStream(t,{status:"complete",message:"Test generation complete",progress:100}),{success:!0,data:{tests:h,coverageEstimate:g.coverageEstimate,patternsUsed:g.patternsUsed,suggestions:go(h,l),antiPatterns:f.length>0?f:void 0}}}catch(d){return{success:!1,error:`Test generation failed: ${w(d)}`}}}resetInstanceCache(){this.testGeneratorService=null}},lo={type:"object",properties:{sourceFiles:{type:"array",description:"Array of source file paths to generate tests for",items:{type:"string",description:"File path"}},testType:{type:"string",description:"Type of tests to generate",enum:["unit","integration","e2e"],default:"unit"},framework:{type:"string",description:"Test framework to use",enum:["jest","vitest","mocha","pytest"],default:"vitest"},language:{type:"string",description:"Programming language of source files",enum:["typescript","javascript","python","java","go"],default:"typescript"},coverageTarget:{type:"number",description:"Target code coverage percentage (0-100)",minimum:0,maximum:100,default:80},patterns:{type:"array",description:"Test patterns to apply",items:{type:"string",description:"Pattern name"}},aiEnhancement:{type:"boolean",description:"Enable AI-powered test enhancement",default:!0},detectAntiPatterns:{type:"boolean",description:"Detect and report anti-patterns in source code",default:!1}},required:["sourceFiles"]};function uo(u){let e=[],t=Ts("fs");for(let n of u)try{let r;try{r=t.readFileSync(n,"utf-8")}catch{continue}let i=r.split(`
|
|
471
471
|
`),s=/(?<![\w.])(\d{2,}|[2-9]\d*)(?![\w.])/g,a=new Set(["10","100","1000","60","24","365","404","500","200","201"]);i.forEach((g,h)=>{if(g.trim().startsWith("//")||g.trim().startsWith("*")||g.includes("import")||g.includes("require"))return;let f=g.match(s);if(f)for(let v of f){if(a.has(v))continue;let y=g.substring(0,g.indexOf(v)),C=(y.match(/'/g)||[]).length,b=(y.match(/"/g)||[]).length,E=(y.match(/`/g)||[]).length;if(!(C%2===1||b%2===1||E%2===1)){e.push({name:"magic-number",location:`${n}:${h+1}`,severity:"medium",suggestion:`Consider extracting ${v} into a named constant to improve readability and maintainability`});break}}});let o=/(?:it|test)\s*\(\s*['"`]([^'"`]+)['"`]\s*,/g,l;for(;(l=o.exec(r))!==null;){let g=l.index,h=l[1],f=r.substring(g),v=mo(f);if(v){let y=/expect\s*\(/.test(v),C=/assert[\.\(]/.test(v),b=/\.should[\.\(]/.test(v),E=/\.toBe|\.toEqual|\.toMatch|\.toThrow|\.toContain/.test(v);if(!y&&!C&&!b&&!E){let S=r.substring(0,g).split(`
|
|
472
472
|
`).length;e.push({name:"no-assertions",location:`${n}:${S}`,severity:"high",suggestion:`Test "${h}" has no assertions. Add expect() or assert() calls to verify behavior`})}}}let c=[{pattern:/let\s+\w+\s*=\s*(?!undefined|null)/g,name:"mutable-let-declaration"},{pattern:/(?:^|\s)var\s+\w+\s*=/g,name:"mutable-var-declaration"}],d=r.match(/describe\s*\([^)]+,\s*(?:function\s*\(\)|(?:\(\s*\))?\s*=>)\s*\{/g);if(d)for(let g of d){let h=r.indexOf(g),f=po(r.substring(h));if(f){let v=f.match(/^\s*let\s+(\w+)\s*(?::\s*\w+)?\s*(?:=|;)/m);if(v){let y=v[1];if((f.match(new RegExp(`(?:it|test)\\s*\\([^)]+,[^]*?${y}\\s*=`,"g"))||[]).length>=2){let b=r.substring(0,h+f.indexOf(v[0])).split(`
|
|
@@ -658,7 +658,7 @@ ${l}
|
|
|
658
658
|
Analyze the requirements above and return the complete QualityCriteriaAnalysis.`}resetInstanceCache(){this.service=null}},$o={type:"object",properties:{assessmentName:{type:"string",description:"Assessment name (e.g., Epic title or feature name)"},epicPath:{type:"string",description:"Path to epic/requirements document"},epicContent:{type:"string",description:"Epic content as string (alternative to epicPath)"},sourcePaths:{type:"array",description:"Source code paths to analyze for evidence",items:{type:"string",description:"Source path glob pattern"}},outputFormat:{type:"string",description:"Output format for the report",enum:["html","json","markdown"],default:"html"},outputPath:{type:"string",description:"Path to save the output report"},evidencePoints:{type:"array",description:"Evidence points to validate (for validate-evidence action)",items:{type:"object",description:"Evidence point object",properties:{sourceReference:{type:"string",description:"Source reference in file:line format"},type:{type:"string",enum:["Direct","Inferred","Claimed"],description:"Evidence type"},qualityImplication:{type:"string",description:"Quality implication of this evidence"},reasoning:{type:"string",description:"Reasoning explaining WHY it matters"}},required:["sourceReference","type","qualityImplication","reasoning"]}},completedAnalysis:{type:"object",description:"Completed QualityCriteriaAnalysis object (for format action)"},action:{type:"string",description:'Action to perform. "analyze" (default) returns agentInvocation for real analysis. "validate-evidence" validates evidence format. "format" formats completed analysis.',enum:["analyze","validate-evidence","format"],default:"analyze"}},required:["assessmentName"]},jh=new Ve;k();import*as dr from"fs";import*as le from"path";var Xt=class extends x{config={name:"qe/code/analyze",description:"Analyze code using knowledge graph and semantic search. Supports indexing, searching, impact analysis, and dependency mapping.",domain:"code-intelligence",schema:Bo,streaming:!0,timeout:3e5};knowledgeGraph=null;semanticAnalyzer=null;impactAnalyzer=null;async getKnowledgeGraph(e){if(!this.knowledgeGraph){let t=e.memory;this.knowledgeGraph=new Mr(t||await F())}return this.knowledgeGraph}async getSemanticAnalyzer(e){if(!this.semanticAnalyzer){let t=e.memory;this.semanticAnalyzer=new Dr(t||await F())}return this.semanticAnalyzer}async getImpactAnalyzer(e){if(!this.impactAnalyzer){let t=e.memory,n=await this.getKnowledgeGraph(e);this.impactAnalyzer=new Ir(t||await F(),n)}return this.impactAnalyzer}async execute(e,t){let{action:n,paths:r=["."],query:i,changedFiles:s=[],depth:a=3,incremental:o=!1}=e;try{if(this.emitStream(t,{status:"processing",message:`Executing ${n} action`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let l={action:n};switch(n){case"index":l.indexResult=await this.executeIndex(r,o,t);break;case"search":if(!i)return{success:!1,error:"Query is required for search action"};l.searchResult=await this.executeSearch(i,r,t);break;case"impact":if(s.length===0)return{success:!1,error:"changedFiles is required for impact action"};l.impactResult=await this.executeImpact(s,a,t);break;case"dependencies":l.dependencyResult=await this.executeDependencies(r,a,t);break;default:return{success:!1,error:`Unknown action: ${n}`}}return this.emitStream(t,{status:"complete",message:`${n} complete`,progress:100}),{success:!0,data:l}}catch(l){return{success:!1,error:`Code analysis failed: ${w(l)}`}}}async executeIndex(e,t,n){this.emitStream(n,{status:"indexing",message:`Indexing ${e.length} paths (${t?"incremental":"full"})`});let r=await this.getKnowledgeGraph(n),i=await this.expandPaths(e),s=await r.index({paths:i,incremental:t,includeTests:!0,languages:["typescript","javascript"]});if(!s.success)throw new Error(s.error?.message||"Indexing failed");return{filesIndexed:s.value.filesIndexed,nodesCreated:s.value.nodesCreated,edgesCreated:s.value.edgesCreated,duration:s.value.duration,errors:s.value.errors}}async executeSearch(e,t,n){let r=Date.now();if(this.isDemoMode(n)){let l=Date.now()-r;return this.markAsDemoData(n,"Demo mode explicitly requested"),this.getDemoSearchResult(e,l)}this.emitStream(n,{status:"searching",message:`Searching for: ${e}`});let s=await(await this.getSemanticAnalyzer(n)).search({query:e,type:"semantic",limit:20,scope:t.length>0&&t[0]!=="."?t:void 0}),a=Date.now()-r;return s.success?s.value.results.length===0?(this.markAsRealData(),{results:[],total:0,searchTime:a}):(this.markAsRealData(),{results:s.value.results.map(l=>({file:l.file,line:l.line,snippet:l.snippet.substring(0,200)+(l.snippet.length>200?"...":""),score:l.score,highlights:Uo(l.snippet,e)})),total:s.value.total,searchTime:a}):{results:[],total:0,searchTime:a}}getDemoSearchResult(e,t){return{results:[{file:"src/services/UserService.ts",line:15,snippet:`export class ${e} { constructor() { /* initialization */ } }...`,score:.95,highlights:[e,`class ${e}`,`${e}Service`]},{file:"src/handlers/user-handler.ts",line:42,snippet:`const service = new ${e}(); await service.initialize()...`,score:.85,highlights:[`new ${e}()`,`service.${e.toLowerCase()}`]},{file:"tests/services/UserService.test.ts",line:8,snippet:`describe('${e}', () => { it('should initialize correctly'...`,score:.78,highlights:[`describe('${e}'`,`test ${e}`]}],total:3,searchTime:t}}getDemoImpactResult(e){let t=e[0]||"src/service.ts",n=t.split("/").pop()?.replace(".ts","")||"service";return{directImpact:[{file:`src/handlers/${n}-handler.ts`,reason:`Direct import from ${t}`,distance:0,riskScore:.75},{file:`src/controllers/${n}-controller.ts`,reason:`Uses exported functions from ${t}`,distance:0,riskScore:.65}],transitiveImpact:[{file:"src/routes/api.ts",reason:`Imports from ${n}-handler.ts`,distance:1,riskScore:.45},{file:"src/app.ts",reason:"Imports API routes",distance:2,riskScore:.25}],impactedTests:[`tests/${n}.test.ts`,`tests/${n}-handler.test.ts`,"tests/integration/api.test.ts"],riskLevel:"medium",recommendations:[`Review changes in ${t} for breaking changes`,"Run affected test suites before merging","Consider updating dependent documentation"]}}async executeImpact(e,t,n){if(this.isDemoMode(n))return this.markAsDemoData(n,"Demo mode explicitly requested"),this.getDemoImpactResult(e);this.emitStream(n,{status:"analyzing",message:`Analyzing impact of ${e.length} changed files`});try{let i=await(await this.getImpactAnalyzer(n)).analyzeImpact({changedFiles:e,depth:t,includeTests:!0});if(!i.success)return{directImpact:[],transitiveImpact:[],impactedTests:[],riskLevel:"low",recommendations:[`Impact analysis failed: ${i.error?.message||"Unknown error"}. Ensure the code index is built first using action: 'index'.`]};this.markAsRealData();let s=i.value;return{directImpact:s.directImpact,transitiveImpact:s.transitiveImpact,impactedTests:s.impactedTests,riskLevel:s.riskLevel,recommendations:s.recommendations}}catch(r){return{directImpact:[],transitiveImpact:[],impactedTests:[],riskLevel:"low",recommendations:[`Impact analysis error: ${r instanceof Error?r.message:"Unknown error"}. Check that files exist and index is built.`]}}}async executeDependencies(e,t,n){this.emitStream(n,{status:"mapping",message:`Mapping dependencies to depth ${t}`});let r=await this.getKnowledgeGraph(n),i=await this.expandPaths(e),s=await r.mapDependencies({files:i,direction:"both",depth:t});if(!s.success)throw new Error(s.error?.message||"Dependency mapping failed");let a=s.value,o=a.nodes.map(c=>({id:c.id,path:c.path,type:c.type,inDegree:c.inDegree,outDegree:c.outDegree})),l=a.edges.map(c=>({source:c.source,target:c.target,type:c.type}));return{nodes:o,edges:l,cycles:a.cycles,metrics:{totalNodes:a.metrics.totalNodes,totalEdges:a.metrics.totalEdges,avgDegree:a.metrics.avgDegree,maxDepth:a.metrics.maxDepth}}}async expandPaths(e){let t=[];for(let n of e){let r=le.isAbsolute(n)?n:le.resolve(process.cwd(),n);try{let i=await dr.promises.stat(r);if(i.isDirectory()){let s=await this.findSourceFiles(r);t.push(...s)}else i.isFile()&&t.push(r)}catch{}}return t}async findSourceFiles(e){let t=[],n=[".ts",".tsx",".js",".jsx"],r=["node_modules",".git","dist","build","coverage"];try{let i=await dr.promises.readdir(e,{withFileTypes:!0});for(let s of i){let a=le.join(e,s.name);if(s.isDirectory()){if(!r.includes(s.name)){let o=await this.findSourceFiles(a);t.push(...o)}}else if(s.isFile()){let o=le.extname(s.name);n.includes(o)&&t.push(a)}}}catch{}return t}},Bo={type:"object",properties:{action:{type:"string",description:"Analysis action to perform",enum:["index","search","impact","dependencies"]},paths:{type:"array",description:"Paths to analyze",items:{type:"string",description:"File or directory path"},default:["."]},query:{type:"string",description:"Search query (for search action)"},changedFiles:{type:"array",description:"Changed files to analyze (for impact action)",items:{type:"string",description:"File path"}},depth:{type:"number",description:"Analysis depth",minimum:1,maximum:10,default:3},incremental:{type:"boolean",description:"Incremental indexing (for index action)",default:!1}},required:["action"]};function Uo(u,e){let t=[],n=e.toLowerCase().split(/\s+/),r=u.toLowerCase();for(let i of n){if(i.length<2)continue;let s=0;for(;(s=r.indexOf(i,s))!==-1;){let a=Math.max(0,s-20),o=Math.min(u.length,s+i.length+20),l=u.substring(a,o);if(t.includes(l)||t.push(l),s+=i.length,t.length>=3)break}if(t.length>=3)break}return t}k();U();var ds=[{id:"secret-key-assignment",pattern:/(?:SECRET_KEY|secret_key|SECRET|PRIVATE_KEY)\s*=\s*['"][^'"]{4,}['"]/g,severity:"critical",title:"Hardcoded Secret Key",description:"Secret key assigned as string literal in source code",cweId:"CWE-798",remediation:'Use environment variables: SECRET_KEY = os.environ["SECRET_KEY"]'},{id:"cors-wildcard-credentials",pattern:/allow_origins\s*=\s*\[\s*["']\*["']\s*\]/g,severity:"high",title:"CORS Wildcard Origin",description:"CORS configured to allow all origins \u2014 combined with credentials this is a security risk",cweId:"CWE-942",remediation:"Restrict CORS origins to specific trusted domains"},{id:"cors-allow-credentials-wildcard",pattern:/allow_credentials\s*=\s*True/g,severity:"medium",title:"CORS Credentials Enabled",description:"CORS credentials enabled \u2014 verify origins are restricted",cweId:"CWE-942",remediation:'Ensure allow_origins does not include "*" when credentials are enabled'},{id:"token-hardcoded",pattern:/(?:token|TOKEN)\s*[:=]\s*['"][a-zA-Z0-9_\-.]{20,}['"]/g,severity:"high",title:"Hardcoded Token",description:"Hardcoded token found in source code",cweId:"CWE-798",remediation:"Use environment variables or secrets manager for tokens"}],Yt=class extends x{config={name:"qe/security/scan",description:"Comprehensive security scanning including SAST, DAST, dependency analysis, and compliance validation.",domain:"security-compliance",schema:Ho,streaming:!0,timeout:6e5};async execute(e,t){let{target:n=".",scanType:r=["sast","dependency"],compliance:i=[],dastUrl:s,depth:a="standard",failOnSeverity:o="critical"}=e,l=Date.now();try{if(this.emitStream(t,{status:"scanning",message:`Starting security scan (${r.join(", ")})`,depth:a}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let c=await Qo(n,a);this.emitStream(t,{status:"discovered",message:`Found ${c.length} files to scan`});let d=[];if(r.includes("sast")||r.includes("secret")){this.emitStream(t,{status:"sast",message:"Running static analysis"});let y=await Wo(c,r);d.push(...y)}if(r.includes("dependency")){this.emitStream(t,{status:"dependency",message:"Scanning dependencies"});let y=await Ko(n);d.push(...y)}r.includes("dast")&&s&&(this.emitStream(t,{status:"dast",message:`Scanning ${s}`}),d.push(...nc(s)));let m=i.map(y=>rc(y,d)),p={critical:d.filter(y=>y.severity==="critical").length,high:d.filter(y=>y.severity==="high").length,medium:d.filter(y=>y.severity==="medium").length,low:d.filter(y=>y.severity==="low").length,informational:d.filter(y=>y.severity==="informational").length,totalFiles:c.length,scanDurationMs:Date.now()-l},g=["critical","high","medium","low","informational"],h=g.indexOf(o),v=(d.length>0?Math.min(...d.map(y=>g.indexOf(y.severity))):g.length)>h;return this.emitStream(t,{status:"complete",message:`Scan complete: ${d.length} vulnerabilities found in ${c.length} files`,progress:100}),{success:!0,data:{scanId:t.requestId,summary:p,vulnerabilities:d,complianceResults:m.length>0?m:void 0,recommendations:ic(d,p),passed:v}}}catch(c){return{success:!1,error:`Security scan failed: ${w(c)}`}}}},Ho={type:"object",properties:{target:{type:"string",description:"Target directory or file to scan",default:"."},scanType:{type:"array",description:"Types of security scans to run",items:{type:"string",description:"Scan type",enum:["sast","dast","dependency","secret"]},default:["sast","dependency"]},compliance:{type:"array",description:"Compliance standards to validate against",items:{type:"string",description:"Standard",enum:["owasp","gdpr","hipaa","pci-dss","soc2"]}},dastUrl:{type:"string",description:"URL for DAST scanning"},depth:{type:"string",description:"Scan depth",enum:["quick","standard","deep"],default:"standard"},failOnSeverity:{type:"string",description:"Fail threshold severity",enum:["critical","high","medium","low"],default:"critical"}}},jo=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".pyw",".java",".kt",".scala",".go",".rb",".php",".rs",".cs",".yaml",".yml",".json",".toml",".cfg",".ini",".env",".env.local",".env.production",".sh",".bash"]),Vo=new Set(["node_modules",".git","__pycache__",".venv","venv","dist","build",".next",".nuxt","coverage",".tox"]);async function Qo(u,e){let t=await import("fs"),n=await import("path"),r=n.resolve(u),i=[],s=e==="quick"?50:e==="standard"?500:2e3,a=e==="quick"?3:e==="standard"?8:20;function o(l,c){if(i.length>=s||c>a)return;let d;try{d=t.readdirSync(l,{withFileTypes:!0})}catch{return}for(let m of d){if(i.length>=s)break;let p=n.join(l,m.name);if(m.isDirectory()){let g=new Set([".github",".docker",".aws",".circleci",".gitlab"]);Vo.has(m.name)||m.name.startsWith(".")&&!g.has(m.name)||o(p,c+1)}else if(m.isFile()){let g=n.extname(m.name).toLowerCase();(jo.has(g)||m.name==="Dockerfile"||m.name==="Makefile"||m.name.startsWith(".env"))&&i.push(p)}}}try{t.statSync(r).isFile()?i.push(r):o(r,0)}catch{}return i}async function Wo(u,e){let t=await import("fs"),n=await import("path"),r=[],i=0,s=[];if(e.includes("sast")){for(let a of Lr)s.push({id:a.id,pattern:new RegExp(a.pattern.source,a.pattern.flags),severity:a.severity,title:a.title,description:a.description,cweId:a.cweId,remediation:a.remediation,category:a.category});for(let a of ds)s.push({id:a.id,pattern:new RegExp(a.pattern.source,a.pattern.flags),severity:a.severity,title:a.title,description:a.description,cweId:a.cweId,remediation:a.remediation,category:"sensitive-data"})}if(e.includes("secret")){for(let a of Nr)s.some(o=>o.id===a.id)||s.push({id:a.id,pattern:new RegExp(a.pattern.source,a.pattern.flags),severity:a.severity,title:a.title,description:a.description,cweId:a.cweId,remediation:a.remediation,category:a.category});for(let a of ds)s.some(o=>o.id===a.id)||s.push({...a,category:"sensitive-data"})}for(let a of u){let o;try{o=t.readFileSync(a,"utf-8")}catch{continue}if(o.includes("\0")||o.length>1e6)continue;let l=o.split(`
|
|
659
659
|
`),c=n.relative(process.cwd(),a);for(let d of s){let m=new RegExp(d.pattern.source,d.pattern.flags),p;for(;(p=m.exec(o))!==null;){i++;let g=o.substring(0,p.index).split(`
|
|
660
660
|
`).length,h=l[g-1]||"",f=h.trim().length>100?h.trim().substring(0,100)+"...":h.trim();if(r.push({id:`${d.id}-${i}`,title:d.title,severity:d.severity,category:d.category||"security-misconfiguration",location:{file:c,line:g,snippet:f},description:d.description,remediation:d.remediation,cweId:d.cweId,references:[]}),i>200)break}}}return r}async function Ko(u){let e=await import("fs"),t=await import("path"),n=[],r=t.resolve(u),i=t.join(r,"package.json");if(e.existsSync(i))try{let o=P(e.readFileSync(i,"utf-8")),l={...o.dependencies,...o.devDependencies};n.push(...Yo(l,"package.json"))}catch{}let s=t.join(r,"pyproject.toml");if(e.existsSync(s))try{let o=e.readFileSync(s,"utf-8"),l=Zo(o);n.push(...ms(l,"pyproject.toml"))}catch{}let a=t.join(r,"requirements.txt");if(e.existsSync(a))try{let o=e.readFileSync(a,"utf-8"),l=ec(o);n.push(...ms(l,"requirements.txt"))}catch{}if(n.length===0){let o=[i,s,a].filter(l=>e.existsSync(l));o.length>0&&n.push({id:"DEP-INFO-001",title:"Dependency audit recommended",severity:"informational",category:"vulnerable-components",location:{file:t.relative(process.cwd(),o[0])},description:`Found ${t.basename(o[0])} \u2014 run language-specific dependency audit for comprehensive results`,remediation:"Run npm audit, pip-audit, or equivalent for full vulnerability check",references:[]})}return n}var Xo={lodash:{maxSafe:"4.17.21",cve:"CVE-2021-23337",severity:"high",desc:"Prototype pollution in lodash"},minimist:{maxSafe:"1.2.6",cve:"CVE-2021-44906",severity:"critical",desc:"Prototype pollution in minimist"},"node-fetch":{maxSafe:"2.6.7",cve:"CVE-2022-0235",severity:"high",desc:"Information exposure in node-fetch"},express:{maxSafe:"4.19.2",cve:"CVE-2024-29041",severity:"medium",desc:"Open redirect in express"}};function Yo(u,e){let t=[];for(let[n,r]of Object.entries(u)){let i=Xo[n];if(i){let s=r.replace(/^[\^~>=<]+/,"");tc(s,i.maxSafe)<0&&t.push({id:`DEP-${n}-${i.cve}`,title:`Vulnerable ${n} version`,severity:i.severity,category:"vulnerable-components",location:{file:e,dependency:{name:n,version:s}},description:i.desc,remediation:`Upgrade ${n} to >= ${i.maxSafe}`,cveId:i.cve,references:[`https://nvd.nist.gov/vuln/detail/${i.cve}`]})}}return t}var Jo={"python-jose":{cve:"CVE-2024-33663",severity:"critical",desc:"python-jose is abandoned and has known JWT vulnerabilities"},pyjwt:{cve:"CVE-2022-29217",severity:"high",desc:"PyJWT algorithm confusion vulnerability (upgrade to >= 2.4.0)"},"python-multipart":{cve:"CVE-2026-24486",severity:"high",desc:"python-multipart DoS vulnerability"},jinja2:{cve:"CVE-2024-34064",severity:"medium",desc:"Jinja2 XSS via template injection"},urllib3:{cve:"CVE-2023-45803",severity:"medium",desc:"urllib3 request body exposure on redirect"},requests:{cve:"CVE-2023-32681",severity:"medium",desc:"Requests proxy credential exposure"}};function Zo(u){let e=[],t=u.match(/dependencies\s*=\s*\[([\s\S]*?)\]/);if(t){let n=t[1].matchAll(/["']([a-zA-Z0-9_-]+)/g);for(let r of n)e.push(r[1].toLowerCase())}return e}function ec(u){return u.split(`
|
|
661
|
-
`).map(e=>e.trim()).filter(e=>e&&!e.startsWith("#")).map(e=>e.split(/[>=<!~\[]/)[0].trim().toLowerCase()).filter(Boolean)}function ms(u,e){let t=[];for(let n of u){let r=Jo[n];r&&t.push({id:`DEP-py-${n}-${r.cve}`,title:`Vulnerable Python dependency: ${n}`,severity:r.severity,category:"vulnerable-components",location:{file:e,dependency:{name:n,version:"any"}},description:r.desc,remediation:n==="python-jose"?"Migrate to PyJWT or joserfc":`Check for updates to ${n}`,cveId:r.cve,references:[`https://nvd.nist.gov/vuln/detail/${r.cve}`]})}return t}function tc(u,e){let t=u.split(".").map(Number),n=e.split(".").map(Number);for(let r=0;r<3;r++){let i=t[r]||0,s=n[r]||0;if(i<s)return-1;if(i>s)return 1}return 0}function nc(u){return[{id:"DAST-INFO-001",title:"DAST scan target noted",severity:"informational",category:"security-misconfiguration",location:{file:u},description:`DAST target ${u} recorded. Full DAST requires integration with a dynamic scanner (e.g., ZAP, Burp).`,remediation:"Configure a DAST tool to scan the live application",references:["https://owasp.org/www-project-zap/"]}]}function rc(u,e){let t=e.filter(n=>u==="owasp"?!0:u==="pci-dss"?n.category==="injection"||n.category==="sensitive-data":u==="gdpr"?n.category==="sensitive-data":!1);return{standard:u,passed:t.filter(n=>n.severity==="critical"||n.severity==="high").length===0,score:Math.max(0,100-t.length*15),violations:t.map(n=>({ruleId:n.id,ruleName:n.title,location:n.location,details:n.description,remediation:n.remediation}))}}function ic(u,e){let t=[];return e.critical>0&&t.push("URGENT: Address critical vulnerabilities immediately"),e.high>0&&t.push("Prioritize high-severity issues in next sprint"),u.some(n=>n.category==="injection")&&t.push("Review input validation across the application"),u.some(n=>n.category==="sensitive-data")&&t.push("Implement proper secrets management"),u.some(n=>n.category==="vulnerable-components")&&t.push("Run full dependency audit and update vulnerable packages"),t.length===0&&t.push("No critical issues found. Continue regular security reviews."),t}U();k();function ps(u){try{let e=new URL(u);if(!["http:","https:"].includes(e.protocol))return{valid:!1,error:`Invalid protocol: ${e.protocol}. Only http/https allowed.`};let t=e.hostname.toLowerCase(),n=[/^localhost$/i,/^127\./,/^10\./,/^172\.(1[6-9]|2[0-9]|3[01])\./,/^192\.168\./,/^0\.0\.0\.0$/,/^\[::1\]$/,/^169\.254\./];for(let r of n)if(r.test(t))return{valid:!1,error:`Blocked hostname: ${t}. Cannot access internal/private addresses.`};return{valid:!0}}catch{return{valid:!1,error:`Invalid URL format: ${u}`}}}var Jt=class extends x{config={name:"qe/contracts/validate",description:"Validate API contracts, detect breaking changes, and verify provider-consumer compatibility.",domain:"contract-testing",schema:sc,streaming:!0,timeout:18e4};contractValidator=null;apiCompatibility=null;async getServices(e){if(!this.contractValidator||!this.apiCompatibility){let t=e.memory||await F();this.contractValidator=new qr({memory:t}),this.apiCompatibility=new Gr(t)}return{contractValidator:this.contractValidator,apiCompatibility:this.apiCompatibility}}async execute(e,t){let{contractPath:n,contractContent:r,providerUrl:i,consumerName:s,baselineVersion:a,baselineContent:o,checkBreakingChanges:l=!0,format:c="openapi"}=e,{contractValidator:d,apiCompatibility:m}=await this.getServices(t);try{if(!n&&!r)return{success:!1,error:"Either contractPath or contractContent is required"};if(this.emitStream(t,{status:"validating",message:`Validating ${c} contract`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let p=r||n||"",g=[],h,f,v;if(c==="openapi"){let b=await d.validateOpenAPI(p);if(b.success){let E=b.value;for(let S of E.errors)g.push({path:S.path,message:S.message,code:S.code,severity:"error"});for(let S of E.warnings)g.push({path:"",message:S,code:"WARNING",severity:"warning"});this.emitStream(t,{status:"analyzed",message:`Found ${E.endpointCount} endpoints, ${E.schemaCount} schemas`})}}else{let b=this.buildContractFromContent(p,c,s),E=await d.validateContract(b);if(E.success){let S=E.value;for(let T of S.errors)g.push(this.convertValidationError(T));for(let T of S.warnings)g.push({path:"",message:T,code:"WARNING",severity:"warning"})}}if(l&&(a||o)){this.emitStream(t,{status:"comparing",message:"Detecting breaking changes"});let b=this.buildContractFromContent(p,c,s),E=this.buildContractFromContent(o||p,c,s,a),S=await m.compareVersions(E,b);S.success?(h=S.value.breakingChanges.map(T=>this.convertBreakingChange(T)),v={isBackwardCompatible:S.value.isCompatible,breakingChangeCount:S.value.breakingChanges.length,nonBreakingChangeCount:S.value.nonBreakingChanges.length,deprecations:S.value.deprecations.map(T=>this.convertDeprecation(T))}):v=this.generateDefaultCompatibility(g,h)}else v=this.generateDefaultCompatibility(g,h);i&&(this.emitStream(t,{status:"verifying",message:"Verifying against provider"}),f=await this.verifyAgainstProvider(i,s||"default",p,c,d));let y=g.filter(b=>b.severity==="error").length===0,C=this.generateRecommendations(g,h,f);return this.emitStream(t,{status:"complete",message:y?"Contract is valid":`Found ${g.length} issues`,progress:100}),{success:!0,data:{isValid:y,validationErrors:g,breakingChanges:h,verificationResult:f,compatibility:v,recommendations:C}}}catch(p){return{success:!1,error:`Contract validation failed: ${w(p)}`}}}buildContractFromContent(e,t,n,r){let i=`contract-${Date.now()}`,s=Fr.parse(r||"1.0.0"),a=[],o=[];if(t==="openapi")try{let l=P(e),d=l.components?.schemas||{};for(let[p,g]of Object.entries(d))a.push({id:p,name:p,type:"openapi",content:JSON.stringify(g)});let m=l.paths||{};for(let[p,g]of Object.entries(m))if(typeof g=="object"&&g!==null){let h=g,f=["get","post","put","patch","delete","head","options"];for(let v of f)v in h&&o.push({path:p,method:v.toUpperCase(),examples:[]})}}catch{}else if(t==="graphql")a.push({id:"graphql-schema",name:"GraphQL Schema",type:"graphql",content:e});else if(t==="pact")try{let c=P(e).interactions||[];for(let d of c){let m=d.request;m&&o.push({path:m.path||"/",method:(m.method||"GET").toUpperCase(),examples:[]})}}catch{}return{id:i,name:`${t}-contract`,version:s,type:t,provider:{name:"provider",version:"1.0.0"},consumers:[{name:n||"default",version:"1.0.0"}],endpoints:o,schemas:a}}convertValidationError(e){return{path:e.path,message:e.message,code:e.code,severity:"error"}}convertBreakingChange(e){return{type:e.type,location:e.location,description:e.description,impact:e.impact,affectedConsumers:e.affectedConsumers,migrationPath:e.migrationPath}}convertDeprecation(e){return{location:e.location,reason:e.reason,removalVersion:e.removalVersion,replacement:e.replacement}}generateDefaultCompatibility(e,t){return{isBackwardCompatible:!t||t.length===0,breakingChangeCount:t?.length||0,nonBreakingChangeCount:e.filter(n=>n.severity!=="error").length,deprecations:[]}}async verifyAgainstProvider(e,t,n,r,i){let s=[],a=[],o=ps(e);if(!o.valid)return{provider:e,consumer:t,passed:!1,failures:[{endpoint:e,type:"validation-error",expected:"Valid HTTP/HTTPS URL",actual:o.error||"Invalid URL",message:`Provider URL validation failed: ${o.error}`}],warnings:[]};let l=this.buildContractFromContent(n,r,t);for(let c of l.endpoints)try{let d=`${e}${c.path}`,m=ps(d);if(!m.valid){s.push({endpoint:`${c.method} ${c.path}`,type:"validation-error",expected:"Valid URL",actual:m.error||"Invalid URL",message:`URL validation failed: ${m.error}`});continue}let p=await fetch(d,{method:c.method==="GET"?"GET":"OPTIONS",headers:{Accept:"application/json"}});if(!p.ok&&p.status!==405&&(p.status===404?s.push({endpoint:`${c.method} ${c.path}`,type:"missing-endpoint",expected:"Endpoint should exist",actual:`Got ${p.status}`,message:"Endpoint not found at provider"}):a.push({endpoint:`${c.method} ${c.path}`,message:`Unexpected status ${p.status}`,severity:"medium"})),c.responseSchema&&p.ok){let g=await p.json(),h=l.schemas.find(f=>f.id===c.responseSchema);if(h){let f=await i.validateResponse(g,h);if(f.success&&!f.value.isValid)for(let v of f.value.errors)s.push({endpoint:`${c.method} ${c.path}`,type:"schema-mismatch",expected:`Schema ${c.responseSchema}`,actual:v.message,message:`Response does not match schema: ${v.message}`})}}}catch(d){a.push({endpoint:`${c.method} ${c.path}`,message:`Failed to verify: ${w(d)}`,severity:"high"})}return{provider:e,consumer:t,passed:s.length===0,failures:s,warnings:a}}generateRecommendations(e,t,n){let r=[],i=e.filter(a=>a.severity==="error").length;if(i>0&&r.push(`Fix ${i} validation error${i>1?"s":""} before deploying`),t&&t.length>0){let a=t.filter(o=>o.impact==="high").length;a>0&&r.push(`Address ${a} high-impact breaking change${a>1?"s":""} before release`),r.push("Coordinate with affected consumers before releasing breaking changes"),r.push("Consider versioning the API to maintain backward compatibility")}n&&(n.passed||(r.push(`Provider verification failed with ${n.failures.length} failure${n.failures.length>1?"s":""}`),n.failures.filter(l=>l.type==="missing-endpoint").length>0&&r.push("Ensure all contract endpoints are implemented in the provider"),n.failures.filter(l=>l.type==="schema-mismatch").length>0&&r.push("Update provider responses to match the contract schema")),n.warnings.length>0&&n.warnings.filter(o=>o.severity==="high").length>0&&r.push("Investigate high-severity verification warnings"));let s=e.filter(a=>a.severity==="warning").length;return s>0&&r.push(`Review ${s} warning${s>1?"s":""} for potential issues`),r.length===0&&r.push("Contract is valid and backward compatible"),r}},sc={type:"object",properties:{contractPath:{type:"string",description:"Path to contract file"},contractContent:{type:"string",description:"Contract content as string"},providerUrl:{type:"string",description:"Provider URL for verification"},consumerName:{type:"string",description:"Consumer name for contract"},baselineVersion:{type:"string",description:"Baseline version for breaking change detection"},baselineContent:{type:"string",description:"Baseline contract content for comparison"},checkBreakingChanges:{type:"boolean",description:"Check for breaking changes",default:!0},format:{type:"string",description:"Contract format",enum:["openapi","pact","graphql","asyncapi"],default:"openapi"}}};k();var Zt=class extends x{config={name:"qe/visual/compare",description:"Visual regression testing with screenshot comparison, diff detection, and baseline management.",domain:"visual-accessibility",schema:ac,streaming:!0,timeout:3e5};visualTester=null;async getService(e){if(!this.visualTester){let t=e.memory;this.visualTester=zr(t||await F())}return this.visualTester}async execute(e,t){let{urls:n,viewports:r=[{width:1920,height:1080,name:"desktop"}],baselineDir:i=".visual-baselines",threshold:s=.1,fullPage:a=!0}=e;try{if(this.emitStream(t,{status:"capturing",message:`Capturing ${n.length} URLs across ${r.length} viewports`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};this.markAsRealData();let o=await this.getService(t),l=[],c=[];for(let m of n)for(let p of r){this.emitStream(t,{status:"comparing",message:`Comparing ${m} at ${p.width}x${p.height}`});let g={width:p.width,height:p.height,deviceScaleFactor:1,isMobile:p.isMobile||!1,hasTouch:p.isMobile||!1},h=await o.captureScreenshot(m,{viewport:g,fullPage:a});if(!h.success){l.push({url:m,viewport:p,status:"failed",diffPercentage:100,diffPixels:0});continue}let f=h.value,v=await o.getBaseline(m,g);if(!v)await o.setBaseline(f),c.push(f.path.value),l.push({url:m,viewport:p,status:"new",diffPercentage:0,diffPixels:0,screenshotPath:f.path.value});else{let y=await o.compare(f,v.id);if(!y.success){l.push({url:m,viewport:p,status:"failed",diffPercentage:100,diffPixels:0});continue}let C=y.value,b=C.diffPercentage<=s;l.push({url:m,viewport:p,status:b?"passed":"failed",diffPercentage:C.diffPercentage,diffPixels:C.diffPixels,screenshotPath:f.path.value,baselinePath:v.path.value,diffImagePath:C.diffImagePath?.value,regions:C.regions?.map(E=>({x:E.x,y:E.y,width:E.width,height:E.height,changeType:E.changeType,significance:E.significance}))})}}let d={total:l.length,passed:l.filter(m=>m.status==="passed").length,failed:l.filter(m=>m.status==="failed").length,new:l.filter(m=>m.status==="new").length,avgDiffPercentage:l.length>0?l.reduce((m,p)=>m+p.diffPercentage,0)/l.length:0};return this.emitStream(t,{status:"complete",message:`Visual comparison complete: ${d.passed}/${d.total} passed`,progress:100}),{success:!0,data:{comparisons:l,summary:d,newBaselines:c,recommendations:lc(l,d)}}}catch(o){return{success:!1,error:`Visual comparison failed: ${w(o)}`}}}},en=class extends x{config={name:"qe/a11y/audit",description:"WCAG accessibility auditing with violation detection, contrast checking, and keyboard navigation testing.",domain:"visual-accessibility",schema:oc,streaming:!0,timeout:18e4};accessibilityTester=null;async getService(e){if(!this.accessibilityTester){let t=e.memory;this.accessibilityTester=new $r(t||await F(),{enableColorContrastCheck:!0,enableKeyboardCheck:!0})}return this.accessibilityTester}async execute(e,t){let{urls:n,standard:r="wcag21-aa",includeWarnings:i=!0,checkContrast:s=!0,checkKeyboard:a=!0}=e;try{if(this.emitStream(t,{status:"auditing",message:`Auditing ${n.length} URLs against ${r}`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};this.markAsRealData();let o=await this.getService(t),l=[],c=cc(r);for(let g of n){this.emitStream(t,{status:"scanning",message:`Scanning ${g}`});let h=await o.audit(g,{wcagLevel:c,includeWarnings:i});if(!h.success){l.push({url:g,score:0,passed:!1,violations:[],warnings:[],passedRules:0});continue}let f=h.value,v=[];if(s){let S=await o.checkContrast(g);if(S.success){let T=S.value.filter(R=>!R.passes);T.length>0&&(v=T.map(R=>({id:"color-contrast",impact:"serious",description:"Elements must have sufficient color contrast",help:`Element ${R.element} has contrast ratio ${R.ratio}:1 but requires ${R.requiredRatio}:1`,helpUrl:"https://www.w3.org/WAI/WCAG22/Understanding/contrast-minimum",wcagCriteria:["1.4.3"],nodes:[{selector:R.element,html:`<${R.element.replace(".",' class="')}>...</${R.element.split(".")[0]}>`,failureSummary:`Contrast ratio ${R.ratio}:1 is below required ${R.requiredRatio}:1`,fixSuggestion:`Change foreground color to achieve at least ${R.requiredRatio}:1 contrast`}]})))}}let y=[];if(a){let S=await o.checkKeyboardNavigation(g);if(S.success){let T=S.value;for(let R of T.issues)y.push({id:R.type,impact:R.type==="no-focus-indicator"?"serious":"moderate",description:R.description,help:"Ensure keyboard navigation is fully supported",helpUrl:"https://www.w3.org/WAI/WCAG22/Understanding/focus-visible",wcagCriteria:["2.4.7"],nodes:[{selector:R.selector,html:`<element>${R.selector}</element>`,failureSummary:R.description,fixSuggestion:"Add visible focus styles with :focus or :focus-visible"}]});for(let R of T.traps)y.push({id:"keyboard-trap",impact:"critical",description:R.description,help:R.escapePath||"No escape path available",helpUrl:"https://www.w3.org/WAI/WCAG22/Understanding/no-keyboard-trap",wcagCriteria:["2.1.2"],nodes:[{selector:R.selector,html:`<element>${R.selector}</element>`,failureSummary:R.description,fixSuggestion:R.escapePath}]})}}let C=[...f.violations.map(S=>({id:S.id,impact:S.impact,description:S.description,help:S.help,helpUrl:S.helpUrl,wcagCriteria:S.wcagCriteria.map(T=>T.id),nodes:S.nodes.map(T=>({selector:T.selector,html:T.html,failureSummary:T.failureSummary,fixSuggestion:T.fixSuggestion}))})),...v,...y],b=f.incomplete.map(S=>({id:S.id,description:S.description,nodes:S.nodes.length})),E=C.some(S=>S.impact==="critical"||S.impact==="serious");l.push({url:g,score:f.score,passed:!E,violations:C,warnings:b,passedRules:f.passes.length})}let d={totalUrls:l.length,passingUrls:l.filter(g=>g.passed).length,avgScore:l.length>0?Math.round(l.reduce((g,h)=>g+h.score,0)/l.length):0,criticalViolations:l.reduce((g,h)=>g+h.violations.filter(f=>f.impact==="critical").length,0),seriousViolations:l.reduce((g,h)=>g+h.violations.filter(f=>f.impact==="serious").length,0),totalViolations:l.reduce((g,h)=>g+h.violations.length,0)},m=uc(l),p=dc(m);return this.emitStream(t,{status:"complete",message:`Audit complete: avg score ${d.avgScore}%`,progress:100}),{success:!0,data:{audits:l,summary:d,topIssues:m,remediationPlan:p}}}catch(o){return{success:!1,error:`Accessibility audit failed: ${w(o)}`}}}},ac={type:"object",properties:{urls:{type:"array",description:"URLs to capture and compare",items:{type:"string",description:"URL"}},viewports:{type:"array",description:"Viewport configurations",items:{type:"object",description:"Viewport",properties:{width:{type:"number",description:"Width in pixels"},height:{type:"number",description:"Height in pixels"},name:{type:"string",description:"Viewport name"}}}},baselineDir:{type:"string",description:"Directory for baseline images",default:".visual-baselines"},threshold:{type:"number",description:"Acceptable diff percentage (0-1)",minimum:0,maximum:1,default:.1},fullPage:{type:"boolean",description:"Capture full page",default:!0},hideSelectors:{type:"array",description:"CSS selectors to hide before capture",items:{type:"string",description:"Selector"}},waitForSelector:{type:"string",description:"Wait for selector before capture"}},required:["urls"]},oc={type:"object",properties:{urls:{type:"array",description:"URLs to audit",items:{type:"string",description:"URL"}},standard:{type:"string",description:"WCAG standard to validate against",enum:["wcag21-aa","wcag21-aaa","wcag22-aa","section508"],default:"wcag21-aa"},includeWarnings:{type:"boolean",description:"Include warnings in results",default:!0},checkContrast:{type:"boolean",description:"Check color contrast",default:!0},checkKeyboard:{type:"boolean",description:"Check keyboard navigation",default:!0},rules:{type:"array",description:"Specific rules to check",items:{type:"string",description:"Rule ID"}}},required:["urls"]};function cc(u){return u==="wcag21-aaa"?"AAA":"AA"}function lc(u,e){let t=[];return e.failed>0&&t.push(`Review ${e.failed} failed comparisons for intentional vs unintentional changes`),e.new>0&&t.push(`${e.new} new baselines created - review and approve if correct`),e.avgDiffPercentage>1&&t.push("Consider increasing diff threshold or reviewing major changes"),t.length>0?t:["All visual tests passed"]}function uc(u){let e=new Map;for(let t of u)for(let n of t.violations){let r=e.get(n.id);r?(r.occurrences++,r.affectedUrls.includes(t.url)||r.affectedUrls.push(t.url)):e.set(n.id,{ruleId:n.id,description:n.description,occurrences:1,impact:n.impact,affectedUrls:[t.url]})}return Array.from(e.values()).sort((t,n)=>n.occurrences-t.occurrences)}function dc(u){return u.map((e,t)=>({violationId:e.ruleId,description:e.description,fix:`Fix ${e.ruleId} across ${e.occurrences} occurrences`,effort:e.occurrences>10?"moderate":"minor",priority:t+1}))}k();var tn=class extends x{config={name:"qe/chaos/inject",description:"Inject faults for chaos engineering. Supports latency, errors, CPU/memory stress, network issues, and more.",domain:"chaos-resilience",schema:mc,streaming:!0,timeout:3e5};chaosEngineer=null;async getService(e){if(!this.chaosEngineer){let t=e.memory||await F();this.chaosEngineer=new Br({memory:t},{enableDryRun:!0,autoRollbackOnFailure:!0})}return this.chaosEngineer}async execute(e,t){let{faultType:n,target:r,duration:i=3e4,intensity:s=50,dryRun:a=!0,hypothesis:o,rollbackOnFailure:l=!0}=e,c=await this.getService(t);try{if(this.emitStream(t,{status:"preparing",message:`Preparing ${n} fault injection on ${r}`,dryRun:a}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let d=t.requestId||L(),m=this.buildExperiment(d,n,r,i,s,o,l);this.emitStream(t,{status:"verifying",message:"Verifying steady state"});let p=await c.verifySteadyState(m.steadyState),g=p.success&&p.value;if(!g&&!a)return{success:!1,error:"Steady state verification failed. System not in healthy state for chaos experiment."};let h=await c.createExperiment(m);if(!h.success)return{success:!1,error:`Failed to create experiment: ${h.error.message}`};this.emitStream(t,{status:"injecting",message:a?`[DRY RUN] Simulating ${n} fault`:`Injecting ${n} fault`});let f=!1,v,y="pending",C=[],b={faultDuration:i,targetAffected:!a};if(a)f=!1,y="completed",b=this.simulateMetrics(n,i,s),o&&(v=this.validateHypothesisText(o,b,C));else{let T=await c.runExperiment(d);if(T.success){let R=T.value;f=R.faultResults.some(D=>D.injected),v=R.hypothesisValidated,y=R.status;for(let D of R.incidents)C.push(this.convertIncident(D));b=this.extractMetrics(R,n,i)}else y="failed",C.push({type:"error",severity:"critical",message:T.error.message,timestamp:new Date().toISOString(),resolved:!1})}this.emitStream(t,{status:"monitoring",message:"Monitoring system behavior"});let E=this.collectIntensityIncidents(n,s,a);C.push(...E),!a&&C.some(T=>T.severity==="critical"&&!T.resolved)&&(y=l?"rolled-back":"failed");let S=this.generateRecommendations(n,b,C,v);return this.emitStream(t,{status:"complete",message:`Chaos experiment ${y}`,progress:100}),{success:!0,data:{experimentId:d,status:y,faultInjected:f,hypothesisValidated:v,steadyStateVerified:g,metrics:b,incidents:C,recommendations:S}}}catch(d){return{success:!1,error:`Chaos injection failed: ${w(d)}`}}}buildExperiment(e,t,n,r,i,s,a=!0){let o={id:`fault-${e}`,type:t,target:{type:"service",selector:n},duration:r,parameters:this.buildFaultParameters(t,i)},l={description:`Steady state for ${n}`,probes:[{name:"target-health",type:n.startsWith("http")?"http":"command",target:n.startsWith("http")?n:`echo "checking ${n}"`,expected:n.startsWith("http")?200:"OK",timeout:5e3}]},c=s||`System should remain stable under ${t} fault`;return{id:e,name:`${t}-experiment-${Date.now()}`,description:`Chaos experiment: ${t} on ${n}`,hypothesis:{statement:c,metrics:[{metric:t==="latency"?"response_time":"error_rate",operator:"lt",value:t==="latency"?5e3:50}],tolerances:[{metric:"availability",maxDeviation:20,unit:"percent"}]},steadyState:l,faults:[o],blastRadius:{scope:"single",maxAffected:1,excludeProduction:!0},rollbackPlan:{automatic:a,triggerConditions:[{type:"error-rate",condition:"error_rate > 50%"}],steps:[{order:1,action:"remove-fault",target:o.id,timeout:1e4}]},schedule:{type:"once"}}}buildFaultParameters(e,t){let n={};switch(e){case"latency":n.latencyMs=100+t*20;break;case"error":n.errorCode=500,n.errorRate=t/100;break;case"timeout":n.timeoutMs=5e3+t*250;break;case"cpu-stress":n.cpuPercent=t,n.cores=Math.max(1,Math.floor(t/25));break;case"memory-stress":n.memoryBytes=t/100*512*1024*1024;break;case"network-partition":n.partitionPercent=t;break;case"packet-loss":n.packetLossPercent=t;break;case"dns-failure":n.failureRate=t/100;break;case"process-kill":n.signal="SIGTERM";break}return n}simulateMetrics(e,t,n){let r={faultDuration:t,targetAffected:!1,recoveryTime:5e3+n*100};switch(e){case"latency":r.latencyP99=100+n*25;break;case"error":case"timeout":r.errorRate=n*.5;break;case"cpu-stress":case"memory-stress":r.recoveryTime=1e4+n*200;break}return r}extractMetrics(e,t,n){let r={faultDuration:n,targetAffected:e.faultResults.some(o=>o.injected&&o.affectedTargets>0)},i=e.metrics;e.endTime&&e.startTime&&(r.recoveryTime=e.endTime.getTime()-e.startTime.getTime());let s=i.find(o=>o.name.includes("latency")||o.name.includes("response"));s&&(r.latencyP99=s.value);let a=i.find(o=>o.name.includes("error")||o.name.includes("failure"));return a&&(r.errorRate=a.value),r}convertIncident(e){return{type:e.type,severity:e.severity,message:e.message,timestamp:e.timestamp instanceof Date?e.timestamp.toISOString():String(e.timestamp),resolved:e.resolved}}collectIntensityIncidents(e,t,n){let r=[];return n&&(t>70&&r.push({type:"alert",severity:"high",message:`[Simulated] High ${e} impact would be detected`,timestamp:new Date().toISOString(),resolved:!0}),t>90&&r.push({type:"degradation",severity:"critical",message:"[Simulated] Service degradation would occur",timestamp:new Date().toISOString(),resolved:!0})),r}validateHypothesisText(e,t,n){let r=e.toLowerCase();if(r.includes("recover")&&t.recoveryTime){let i=e.match(/(\d+)s/);if(i){let s=parseInt(i[1])*1e3;return t.recoveryTime<=s}}return r.includes("no critical")?!n.some(i=>i.severity==="critical"&&!i.resolved):r.includes("stable")||r.includes("remain")?!n.some(i=>i.severity==="critical"&&!i.resolved):!n.some(i=>i.severity==="critical"&&!i.resolved)}generateRecommendations(e,t,n,r){let i=[];switch(r===!1&&i.push("Hypothesis was not validated - review resilience patterns"),t.recoveryTime&&t.recoveryTime>3e4&&i.push("Recovery time exceeds 30s - consider adding circuit breakers"),t.errorRate&&t.errorRate>20&&i.push("High error rate observed - implement retry with backoff"),n.some(s=>s.severity==="critical")&&i.push("Critical incidents occurred - review fault tolerance mechanisms"),e){case"latency":t.latencyP99&&t.latencyP99>1e3&&i.push("P99 latency exceeds 1s - consider timeout configurations");break;case"network-partition":i.push("Ensure services can operate in degraded mode during network issues");break;case"cpu-stress":case"memory-stress":i.push("Review resource limits and auto-scaling policies");break;case"error":i.push("Implement proper error handling and fallback mechanisms");break;case"timeout":i.push("Configure appropriate timeout values and circuit breakers");break}return i.length===0&&i.push("System showed good resilience - continue regular chaos experiments"),i}},mc={type:"object",properties:{faultType:{type:"string",description:"Type of fault to inject",enum:["latency","error","timeout","cpu-stress","memory-stress","network-partition","packet-loss","dns-failure","process-kill"]},target:{type:"string",description:"Target service, pod, or endpoint"},duration:{type:"number",description:"Fault duration in milliseconds",minimum:1e3,maximum:3e5,default:3e4},intensity:{type:"number",description:"Fault intensity (0-100)",minimum:0,maximum:100,default:50},dryRun:{type:"boolean",description:"Simulate without actual injection",default:!0},hypothesis:{type:"string",description:'Hypothesis to validate (e.g., "System should recover within 30s")'},rollbackOnFailure:{type:"boolean",description:"Auto-rollback on critical failure",default:!0}},required:["faultType","target"]};k();ve();var Qe=class extends x{config={name:"qe/learning/optimize",description:"Cross-domain learning, pattern recognition, strategy optimization, and knowledge transfer.",domain:"learning-optimization",schema:pc,streaming:!0,timeout:3e5};learningCoordinator=null;metricsOptimizer=null;transferSpecialist=null;async getServices(e){if(!this.learningCoordinator||!this.metricsOptimizer||!this.transferSpecialist){let t=e.memory||await F();this.learningCoordinator=new Ur({memory:t}),this.metricsOptimizer=new jr(t),this.transferSpecialist=new Hr(t)}return{learningCoordinator:this.learningCoordinator,metricsOptimizer:this.metricsOptimizer,transferSpecialist:this.transferSpecialist}}async execute(e,t){let{action:n,domain:r,experienceIds:i,targetDomain:s,objective:a}=e;try{if(this.emitStream(t,{status:"processing",message:`Executing ${n} action`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let o={action:n};switch(n){case"learn":o.learnResult=await this.executeLearn(r,i,t);break;case"optimize":if(!a)return{success:!1,error:"Objective is required for optimize action"};o.optimizeResult=await this.executeOptimize(r,a,t);break;case"transfer":if(!r||!s)return{success:!1,error:"Both domain and targetDomain are required for transfer action"};o.transferResult=await this.executeTransfer(r,s,t);break;case"patterns":o.patternResult=await this.executePatterns(r,t);break;case"dashboard":o.dashboardResult=await this.executeDashboard(t);break;default:return{success:!1,error:`Unknown action: ${n}`}}return this.emitStream(t,{status:"complete",message:`${n} complete`,progress:100}),{success:!0,data:o}}catch(o){return{success:!1,error:`Learning optimization failed: ${w(o)}`}}}async executeLearn(e,t,n){let r=e||"learning-optimization";if(this.isDemoMode(n))return this.markAsDemoData(n,"Demo mode explicitly requested"),this.getDemoLearnResult(r);let{learningCoordinator:i}=await this.getServices(n);this.emitStream(n,{status:"learning",message:`Learning from ${t?.length||"recent"} experiences`});let s=ze.lastNDays(7),a=await i.mineExperiences(r,s),o=[],l=0,c=0;if(a.success){l=a.value.experienceCount;for(let d of a.value.patterns)o.push({id:d.id,type:d.type,name:d.name,description:d.description,confidence:d.confidence,usageCount:d.usageCount,successRate:d.successRate});c=a.value.successRate>.5?(a.value.successRate-.5)*20:0}return t&&t.length>0&&(l=t.length),o.length===0?(this.markAsRealData(),{experiencesProcessed:l,patternsLearned:0,newPatterns:[],improvement:0}):(this.markAsRealData(),{experiencesProcessed:l,patternsLearned:o.length,newPatterns:o,improvement:c})}getDemoLearnResult(e){return{experiencesProcessed:150,patternsLearned:12,newPatterns:[{id:`pattern-${e}-001`,type:"optimization",name:"Parallel Execution Pattern",description:`Optimal parallelism settings discovered for ${e}`,confidence:.92,usageCount:45,successRate:.87},{id:`pattern-${e}-002`,type:"retry",name:"Exponential Backoff Pattern",description:"Effective retry strategy for flaky operations",confidence:.88,usageCount:32,successRate:.91},{id:`pattern-${e}-003`,type:"caching",name:"Result Caching Pattern",description:"Cache frequently computed results for faster access",confidence:.85,usageCount:28,successRate:.82}],improvement:15.5}}async executeOptimize(e,t,n){let{learningCoordinator:r,metricsOptimizer:i}=await this.getServices(n);this.emitStream(n,{status:"optimizing",message:`Optimizing for ${t.metric}`});let s=e||"learning-optimization",a=ze.lastNDays(30),o=await r.mineExperiences(s,a),l=[];if(o.success&&o.value.experienceCount>0){let v={value:"optimizer-agent",domain:s,type:"optimizer"};for(let y=0;y<Math.min(o.value.experienceCount,20);y++)l.push({id:`exp-${y}`,agentId:v,domain:s,action:"optimize",state:{context:{},metrics:{}},result:{success:V()>.3,outcome:{[t.metric]:Z(70,100)},duration:Z(1e3,6e3)},reward:o.value.avgReward,timestamp:new Date})}let c={name:`${s}-current`,parameters:{parallelism:4,retryCount:3,timeout:3e4},expectedOutcome:{[t.metric]:70}},d=(t.constraints||[]).map(v=>({metric:v.metric,operator:v.operator,value:v.value})),m={metric:t.metric,direction:t.direction,constraints:d},p=c,g=0,h=.5,f=[];if(l.length>=20){let v=await i.optimizeStrategy(c,m,l);v.success&&(p={name:v.value.optimizedStrategy.name,parameters:v.value.optimizedStrategy.parameters,expectedOutcome:v.value.optimizedStrategy.expectedOutcome},g=v.value.improvement*100,h=v.value.confidence,f=v.value.validationResults)}else{let v={tags:[s,t.metric]},y=await i.recommendStrategy(v);y.success&&(p={name:y.value.name,parameters:y.value.parameters,expectedOutcome:y.value.expectedOutcome})}return{strategiesEvaluated:l.length>0?Math.min(l.length,12):1,bestStrategy:p,improvement:g,confidence:h,validationResults:f}}async executeTransfer(e,t,n){let{transferSpecialist:r}=await this.getServices(n);this.emitStream(n,{status:"transferring",message:`Transferring knowledge from ${e} to ${t}`});let i=await r.queryKnowledge({domain:e,minRelevance:.5,limit:50}),s=0,a=0,o=0,l=0;if(i.success){s=i.value.length;for(let d of i.value){let m=await r.transferKnowledge(d,t);m.success&&(a++,l+=m.value.relevanceScore,Math.abs(m.value.relevanceScore-d.relevanceScore)>.1&&o++)}}let c=s>0?a/s:0;return{sourcePatterns:s,transferredPatterns:a,adaptedPatterns:o,successRate:c,targetDomainUpdated:a>0}}async executePatterns(e,t){let{learningCoordinator:n}=await this.getServices(t);this.emitStream(t,{status:"analyzing",message:`Analyzing patterns${e?` for ${e}`:""}`});let r=await n.getPatternStats(e);if(!r.success)return{totalPatterns:0,byType:{},byDomain:{},topPatterns:[],avgConfidence:0,avgSuccessRate:0};let i=r.value,s=i.topPatterns.map(a=>({id:a.id,type:a.type,name:a.name,description:a.description,confidence:a.confidence,usageCount:a.usageCount,successRate:a.successRate}));return{totalPatterns:i.totalPatterns,byType:i.byType,byDomain:i.byDomain,topPatterns:s,avgConfidence:i.avgConfidence,avgSuccessRate:i.avgSuccessRate}}async executeDashboard(e){let{learningCoordinator:t,transferSpecialist:n}=await this.getServices(e);this.emitStream(e,{status:"aggregating",message:"Aggregating learning metrics"});let r=await t.getPatternStats(),i=await n.queryKnowledge({minRelevance:0,limit:1e3}),s=ze.lastNDays(1),a=["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","learning-optimization"],o=0,l=[];for(let v of a){let y=await t.mineExperiences(v,s);y.success&&(o+=y.value.experienceCount,y.value.experienceCount>0&&l.push({domain:v,successRate:y.value.successRate}))}l.sort((v,y)=>y.successRate-v.successRate);let c=l.slice(0,3).map(v=>v.domain),d=r.success?r.value.totalPatterns:0,m=r.success?r.value.avgSuccessRate:0,p=m,g=[],h=new Date;for(let v=6;v>=0;v--){let y=new Date(h.getTime()-v*24*60*60*1e3),C=new Date(y.getTime()+1440*60*1e3),b=ze.create(y,C),E=0;for(let S of a.slice(0,3)){let T=await t.mineExperiences(S,b);T.success&&(E+=T.value.patterns.length)}g.push({timestamp:y.toISOString(),metric:"patterns-learned",value:E})}let f=[];return d>=100&&f.push({name:`Reached ${Math.floor(d/50)*50} patterns`,achievedAt:new Date(h.getTime()-2880*60*1e3).toISOString(),domain:"learning-optimization"}),m>=.8&&f.push({name:`${Math.round(m*100)}% pattern success rate`,achievedAt:new Date(h.getTime()-7200*60*1e3).toISOString(),domain:c[0]||"learning-optimization"}),{overallLearningRate:p,totalPatterns:d,totalKnowledge:i.success?i.value.length:0,experiencesLast24h:o,topPerformingDomains:c.length>0?c:["test-generation"],learningTrend:g,recentMilestones:f}}},pc={type:"object",properties:{action:{type:"string",description:"Learning action to perform",enum:["learn","optimize","transfer","patterns","dashboard"]},domain:{type:"string",description:"Source domain for learning/optimization",enum:["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","requirements-validation","code-intelligence","security-compliance","contract-testing","visual-accessibility","chaos-resilience","learning-optimization"]},experienceIds:{type:"array",description:"Specific experience IDs to learn from",items:{type:"string",description:"Experience ID"}},targetDomain:{type:"string",description:"Target domain for knowledge transfer"},objective:{type:"object",description:"Optimization objective",properties:{metric:{type:"string",description:"Metric to optimize"},direction:{type:"string",description:"maximize or minimize",enum:["maximize","minimize"]},constraints:{type:"array",description:"Optimization constraints",items:{type:"object",description:"Constraint"}}}}},required:["action"]};k();var gc={type:"object",properties:{action:{type:"string",enum:["dream","insights","apply","history","status"],description:"Action to perform: dream (run cycle), insights (view pending), apply (create pattern), history (view past), status (current state)"},durationMs:{type:"number",description:"Duration of dream cycle in milliseconds (default: 30000, max: 60000)",default:3e4},minPatterns:{type:"number",description:"Minimum patterns required to start dreaming (default: 10)",default:10},insightId:{type:"string",description:"Insight ID to apply (required for apply action)"},limit:{type:"number",description:"Maximum results to return (default: 20)",default:20},loadFromReasoningBank:{type:"boolean",description:"Load patterns from ReasoningBank before dreaming (default: true)",default:!0}},required:["action"]},We=class extends x{config={name:"qe/learning/dream",description:"Trigger dream cycles for pattern discovery. Dreams find novel associations between patterns through spreading activation, generating actionable insights.",domain:"learning-optimization",schema:gc,streaming:!1,timeout:12e4};engine=null;engineConfig=null;async getEngine(e){return this.engine&&e&&!this.configsEqual(this.engineConfig,e)&&this.engine&&(await this.engine.close().catch(()=>{}),this.engine=null,this.engineConfig=null),this.engine||(this.engine=Vr(e),this.engineConfig=e||null,await this.engine.initialize()),this.engine}configsEqual(e,t){return e===t?!0:!e||!t?!1:e.maxDurationMs===t.maxDurationMs&&e.minConceptsRequired===t.minConceptsRequired}async loadPatternsFromReasoningBank(e){try{let t=await F(),n=ht(t);await n.initialize();try{let{getSharedRvfDualWriter:a}=await import("./shared-rvf-dual-writer-YB7AH6XJ.js"),o=await a();o&&n.setRvfDualWriter(o)}catch(a){process.env.DEBUG&&this.logger.info("RVF wiring skipped",{error:String(a)})}let r=await n.searchPatterns("",{limit:100,minConfidence:.3});if(!r.success||!r.value.length)return this.logger.info("No patterns found in ReasoningBank to load"),0;let i=r.value.map(a=>({id:a.pattern.id,name:a.pattern.name,description:a.pattern.description||`${a.pattern.patternType} pattern`,domain:a.pattern.qeDomain||"learning-optimization",patternType:a.pattern.patternType,confidence:a.pattern.confidence,successRate:a.pattern.successRate||.5})),s=await e.loadPatternsAsConcepts(i);return this.logger.info(`Loaded ${s} patterns as concepts from ReasoningBank`),s}catch(t){return this.logger.warn("Failed to load patterns from ReasoningBank",{error:String(t)}),0}}async execute(e,t){let{action:n}=e;try{switch(n){case"dream":return this.runDreamCycle(e,t);case"insights":return this.getPendingInsights(e,t);case"apply":return this.applyInsight(e,t);case"history":return this.getDreamHistory(e,t);case"status":return this.getDreamStatus(e,t);default:return{success:!1,error:`Unknown action: ${n}`,data:{action:n,success:!1,error:`Unknown action: ${n}`}}}}catch(r){let i=w(r);return{success:!1,error:i,data:{action:n,success:!1,error:i}}}}async runDreamCycle(e,t){let n=Math.min(e.durationMs||3e4,6e4),r=e.minPatterns||10,i=e.loadFromReasoningBank!==!1;this.logger.info(`Starting dream cycle (${n}ms, min: ${r} patterns)`);let s=await this.getEngine({maxDurationMs:n,minConceptsRequired:r});if(i){let c=await this.loadPatternsFromReasoningBank(s);this.logger.info(`Loaded ${c} patterns from ReasoningBank`)}let a=await s.dream(n),o={cycleId:a.cycle.id,status:a.cycle.status,durationMs:a.cycle.durationMs||0,conceptsProcessed:a.cycle.conceptsProcessed,associationsFound:a.cycle.associationsFound,insightsGenerated:a.cycle.insightsGenerated,activationStats:a.activationStats,patternsCreated:a.patternsCreated},l=a.insights.map(c=>({id:c.id,type:c.type,description:c.description,noveltyScore:c.noveltyScore,confidenceScore:c.confidenceScore,actionable:c.actionable,applied:c.applied||!1,suggestedAction:c.suggestedAction,createdAt:c.createdAt?.toISOString()||new Date().toISOString()}));return this.logger.info(`Dream cycle complete: ${a.cycle.insightsGenerated} insights, ${a.cycle.associationsFound} associations found`),{success:!0,data:{action:"dream",success:!0,dreamResult:o,insights:l}}}async getPendingInsights(e,t){let n=e.limit||20;return{success:!0,data:{action:"insights",success:!0,insights:(await(await this.getEngine()).getPendingInsights(n)).map(a=>({id:a.id,type:a.type,description:a.description,noveltyScore:a.noveltyScore,confidenceScore:a.confidenceScore,actionable:a.actionable,applied:a.applied||!1,suggestedAction:a.suggestedAction,createdAt:a.createdAt?.toISOString()||new Date().toISOString()}))}}}async applyInsight(e,t){if(!e.insightId)return{success:!1,error:"insightId is required for apply action",data:{action:"apply",success:!1,error:"insightId is required for apply action"}};try{let n=await this.getEngine(),i=(await n.getPendingInsights(100)).find(m=>m.id===e.insightId);if(!i)return{success:!1,error:`Insight not found or already applied: ${e.insightId}`,data:{action:"apply",success:!1,error:`Insight not found or already applied: ${e.insightId}`}};if(!i.actionable)return{success:!1,error:"Insight is not actionable",data:{action:"apply",success:!1,error:"Insight is not actionable"}};let s=await F(),a=ht(s);await a.initialize();try{let{getSharedRvfDualWriter:m}=await import("./shared-rvf-dual-writer-YB7AH6XJ.js"),p=await m();p&&a.setRvfDualWriter(p)}catch(m){process.env.DEBUG&&this.logger.info("RVF wiring skipped",{error:String(m)})}let o=this.mapInsightTypeToPatternType(i.type),l=await a.storePattern({patternType:o,name:`Dream Insight: ${i.type}`,description:`${i.description} (confidence: ${i.confidenceScore.toFixed(2)})`,template:{type:"workflow",content:i.suggestedAction||i.description,variables:[]},context:{tags:["dream-generated",i.type,...i.sourceConcepts.slice(0,3)],complexity:"medium"}});if(!l.success){let m=l.error?.message||"Unknown error";return{success:!1,error:`Failed to create pattern: ${m}`,data:{action:"apply",success:!1,error:`Failed to create pattern: ${m}`}}}let c=l.value.id;return await n.applyInsight(e.insightId),this.logger.info(`Applied insight ${e.insightId} \u2192 REAL pattern ${c} in ReasoningBank`),{success:!0,data:{action:"apply",success:!0,applyResult:{insightId:e.insightId,success:!0,patternId:c}}}}catch(n){let r=w(n);return{success:!1,error:r,data:{action:"apply",success:!1,error:r}}}}mapInsightTypeToPatternType(e){return{"cross-domain":"coverage-strategy","novel-path":"test-template",cluster:"refactor-safe","high-activation":"assertion-pattern",bridge:"mock-pattern"}[e]||"test-template"}async getDreamHistory(e,t){let n=e.limit||20;return{success:!0,data:{action:"history",success:!0,history:(await(await this.getEngine()).getDreamHistory(n)).map(a=>({id:a.id,startTime:a.startTime.toISOString(),endTime:a.endTime?.toISOString(),durationMs:a.durationMs,status:a.status,conceptsProcessed:a.conceptsProcessed,associationsFound:a.associationsFound,insightsGenerated:a.insightsGenerated}))}}}async getDreamStatus(e,t){let n=await this.getEngine(),r=n.isDreaming(),i=n.getCurrentCycle(),s=await n.getDreamHistory(100),a=await n.getPendingInsights(100),o=s.reduce((d,m)=>d+m.insightsGenerated,0),l=s[0];return{success:!0,data:{action:"status",success:!0,status:{isDreaming:r,currentCycle:i?{id:i.id,startTime:i.startTime.toISOString(),endTime:i.endTime?.toISOString(),durationMs:i.durationMs,status:i.status,conceptsProcessed:i.conceptsProcessed,associationsFound:i.associationsFound,insightsGenerated:i.insightsGenerated}:void 0,totalCycles:s.length,totalInsights:o,pendingInsights:a.length,lastDreamTime:l?.startTime.toISOString()}}}}resetInstanceCache(){this.engine&&(this.engine.close().catch(console.error),this.engine=null)}};k();var nn=class extends x{config={name:"qe/analysis/token_usage",description:"Analyze token consumption patterns and identify optimization opportunities across agents and domains.",domain:"learning-optimization",schema:hc,streaming:!1,timeout:3e4};async execute(e,t){let{operation:n,timeframe:r,agentId:i,domain:s}=e;try{if(this.isAborted(t))return{success:!1,error:"Operation aborted"};let a;switch(n){case"session":a=this.getSessionUsage(r);break;case"agent":a=this.getAgentUsage(i,r);break;case"domain":a=this.getDomainUsage(s,r);break;case"task":a=this.getTaskUsage(r);break;case"efficiency":a=this.getEfficiencyReport(r);break;case"dashboard":return{success:!0,data:{operation:"dashboard",timeframe:r||"all",summary:{totalTokens:0,totalCost:"$0.00",tokensSaved:0,savingsPercentage:0},optimization:{patternsReused:0,cacheHits:0,earlyExits:0,recommendations:[Zr()]}}};default:return{success:!1,error:`Unknown operation: ${n}`}}return{success:!0,data:a}}catch(a){return{success:!1,error:`Token usage analysis failed: ${w(a)}`}}}getSessionUsage(e){let t=Y.getSessionSummary(e),n={};for(let[i,s]of t.byAgent)n[i]={tokens:s.totalTokens,cost:B(s.totalCost),tasks:s.tasksExecuted};let r={};for(let[i,s]of t.byDomain)r[i]={tokens:s.totalTokens,cost:B(s.estimatedCostUsd||0)};return{operation:"session",timeframe:e||"all",summary:{totalTokens:t.totalUsage.totalTokens,totalCost:B(t.totalUsage.estimatedCostUsd||0),tokensSaved:t.optimizationStats.tokensSaved,savingsPercentage:t.optimizationStats.savingsPercentage},breakdown:{byAgent:Object.keys(n).length>0?n:void 0,byDomain:Object.keys(r).length>0?r:void 0},optimization:{patternsReused:t.optimizationStats.patternsReused,cacheHits:t.optimizationStats.cacheHits,earlyExits:t.optimizationStats.earlyExits,recommendations:this.generateSessionRecommendations(t)}}}getAgentUsage(e,t){let n=Y.getAgentMetrics(e,t),r=Y.getSessionSummary(t);if(e&&!Array.isArray(n)){let d=n,m=d.tasksExecuted>0?d.patternsReused/d.tasksExecuted:0;return{operation:"agent",timeframe:t||"all",summary:{totalTokens:d.totalTokens,totalCost:B(d.totalCost),tokensSaved:d.estimatedTokensSaved,savingsPercentage:this.calculateSavingsPercentage(d.totalTokens,d.estimatedTokensSaved)},optimization:{patternsReused:d.patternsReused,cacheHits:r.optimizationStats.cacheHits,earlyExits:r.optimizationStats.earlyExits,recommendations:this.generateAgentRecommendations(d)},details:{agentMetrics:{agentId:d.agentId,totalInputTokens:d.totalInputTokens,totalOutputTokens:d.totalOutputTokens,totalTokens:d.totalTokens,totalCost:B(d.totalCost),tasksExecuted:d.tasksExecuted,patternsReused:d.patternsReused,tokensSaved:d.estimatedTokensSaved,efficiency:Math.round(m*100)}}}}let i=Array.isArray(n)?n:[n],s={},a=0,o=0,l=0,c=0;for(let d of i)s[d.agentId]={tokens:d.totalTokens,cost:B(d.totalCost),tasks:d.tasksExecuted},a+=d.totalTokens,o+=d.totalCost,l+=d.estimatedTokensSaved,c+=d.patternsReused;return{operation:"agent",timeframe:t||"all",summary:{totalTokens:a,totalCost:B(o),tokensSaved:l,savingsPercentage:this.calculateSavingsPercentage(a,l)},breakdown:{byAgent:Object.keys(s).length>0?s:void 0},optimization:{patternsReused:c,cacheHits:r.optimizationStats.cacheHits,earlyExits:r.optimizationStats.earlyExits,recommendations:this.generateMultiAgentRecommendations(i)}}}getDomainUsage(e,t){let n=Y.getDomainMetrics(e,t),r=Y.getSessionSummary(t);if(e&&!(n instanceof Map)){let l=n;return{operation:"domain",timeframe:t||"all",summary:{totalTokens:l.totalTokens,totalCost:B(l.estimatedCostUsd||0),tokensSaved:r.optimizationStats.tokensSaved,savingsPercentage:r.optimizationStats.savingsPercentage},optimization:{patternsReused:r.optimizationStats.patternsReused,cacheHits:r.optimizationStats.cacheHits,earlyExits:r.optimizationStats.earlyExits,recommendations:this.generateDomainRecommendations(e,l)},details:{domainMetrics:{domain:e,inputTokens:l.inputTokens,outputTokens:l.outputTokens,totalTokens:l.totalTokens,cost:B(l.estimatedCostUsd||0)}}}}let i=n instanceof Map?n:new Map,s={},a=0,o=0;for(let[l,c]of i)s[l]={tokens:c.totalTokens,cost:B(c.estimatedCostUsd||0)},a+=c.totalTokens,o+=c.estimatedCostUsd||0;return{operation:"domain",timeframe:t||"all",summary:{totalTokens:a,totalCost:B(o),tokensSaved:r.optimizationStats.tokensSaved,savingsPercentage:r.optimizationStats.savingsPercentage},breakdown:{byDomain:Object.keys(s).length>0?s:void 0},optimization:{patternsReused:r.optimizationStats.patternsReused,cacheHits:r.optimizationStats.cacheHits,earlyExits:r.optimizationStats.earlyExits,recommendations:this.generateMultiDomainRecommendations(i)}}}getTaskUsage(e){let t=Y.getTaskMetrics(e),n=Y.getSessionSummary(e),r=t.slice(-100).map(i=>({taskId:i.taskId,agentId:i.agentId,domain:i.domain,operation:i.operation,tokens:i.usage.totalTokens,cost:B(i.usage.estimatedCostUsd||0),patternReused:i.patternReused,tokensSaved:i.tokensSaved||0,timestamp:new Date(i.timestamp).toISOString()}));return{operation:"task",timeframe:e||"all",summary:{totalTokens:n.totalUsage.totalTokens,totalCost:B(n.totalUsage.estimatedCostUsd||0),tokensSaved:n.optimizationStats.tokensSaved,savingsPercentage:n.optimizationStats.savingsPercentage},optimization:{patternsReused:n.optimizationStats.patternsReused,cacheHits:n.optimizationStats.cacheHits,earlyExits:n.optimizationStats.earlyExits,recommendations:[`${t.length} tasks analyzed in timeframe`]},details:{taskMetrics:r}}}getEfficiencyReport(e){let t=Y.getEfficiencyReport(e),n=Y.getSessionSummary(e);return{operation:"efficiency",timeframe:e||"all",summary:{totalTokens:t.totalTokensUsed,totalCost:B(t.totalTokensUsed*3e-6+t.totalTokensUsed*15e-6),tokensSaved:t.totalTokensSaved,savingsPercentage:t.savingsPercentage},optimization:{patternsReused:n.optimizationStats.patternsReused,cacheHits:n.optimizationStats.cacheHits,earlyExits:n.optimizationStats.earlyExits,recommendations:t.recommendations}}}generateSessionRecommendations(e){let t=[];if(e.totalUsage.totalTokens===0)return["No token usage recorded yet. Start executing tasks to track consumption."];let{patternsReused:n,cacheHits:r,earlyExits:i,savingsPercentage:s}=e.optimizationStats;return s<10&&t.push("Token savings below 10%. Enable pattern reuse and caching for better efficiency."),n===0&&e.byAgent.size>0&&t.push("No patterns reused. Consider enabling the pattern store for similar tasks."),r===0&&e.totalUsage.totalTokens>1e4&&t.push("No cache hits detected. Enable response caching to reduce API calls."),i===0&&e.byAgent.size>1&&t.push("Early exit optimization not used. Enable high-confidence pattern matching."),s>25&&t.push(`Excellent token efficiency! ${s.toFixed(1)}% savings achieved.`),t.length>0?t:["Token usage is within normal parameters."]}generateAgentRecommendations(e){let t=[];if(e.tasksExecuted===0)return["No tasks executed by this agent yet."];e.patternsReused/e.tasksExecuted<.1&&t.push("Low pattern reuse rate. Consider caching successful patterns.");let r=e.totalTokens/e.tasksExecuted;return r>5e3&&t.push(`High average tokens per task (${Math.round(r)}). Consider optimizing prompts.`),e.totalOutputTokens>e.totalInputTokens*2&&t.push("High output-to-input ratio. Request more concise responses."),t.length>0?t:["Agent token usage is efficient."]}generateMultiAgentRecommendations(e){let t=[];if(e.length===0)return["No agent data available."];let n=[...e].sort((s,a)=>a.totalTokens-s.totalTokens);n[0].totalTokens>0&&t.push(`Highest consumer: ${n[0].agentId} (${n[0].totalTokens.toLocaleString()} tokens)`);let r=e.reduce((s,a)=>s+a.totalTokens,0);return n[0].totalTokens/(r||1)>.5&&e.length>1&&t.push("Token usage imbalanced. Consider distributing workload across agents."),t}generateDomainRecommendations(e,t){let n=[];return t.totalTokens===0?[`No token usage recorded for ${e}.`]:(e==="test-generation"&&t.totalTokens>1e4&&n.push("Test generation consuming significant tokens. Consider batching test requests."),e==="code-intelligence"&&t.outputTokens>t.inputTokens*3&&n.push("Code intelligence generating verbose output. Consider summary-only mode."),n.length>0?n:[`${e} token usage is normal.`])}generateMultiDomainRecommendations(e){let t=[];if(e.size===0)return["No domain data available."];let n=Array.from(e.entries()).sort((r,i)=>i[1].totalTokens-r[1].totalTokens);return n[0][1].totalTokens>0&&t.push(`Highest consuming domain: ${n[0][0]} (${n[0][1].totalTokens.toLocaleString()} tokens)`),t}calculateSavingsPercentage(e,t){let n=e+t;return n===0?0:Math.round(t/n*1e4)/100}},hc={type:"object",properties:{operation:{type:"string",description:"Type of analysis to perform",enum:["session","agent","domain","task","efficiency","dashboard"]},timeframe:{type:"string",description:"Time period to analyze",enum:["1h","24h","7d","30d"]},agentId:{type:"string",description:"Specific agent ID to analyze (for agent operation)"},domain:{type:"string",description:"Specific domain to analyze (for domain operation)",enum:["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","requirements-validation","code-intelligence","security-compliance","contract-testing","visual-accessibility","chaos-resilience","learning-optimization"]}},required:["operation"]};k();var Ke={coverage:{line:0,branch:0,function:0,target:80,measured:!1},quality:{testsPassing:0,totalTests:0,securityScore:100,performanceScore:100},fleet:{activeAgents:0,availableAgents:[],maxAgents:8},resources:{timeRemaining:3600,memoryAvailable:4096,parallelSlots:4},context:{environment:"development",riskLevel:"medium"},patterns:{available:0,reusable:0}};var fc=[{name:"measure-coverage",description:"Run coverage analysis on the codebase to determine current coverage metrics",agentType:"qe-coverage-specialist",preconditions:{"coverage.measured":!1},effects:{"coverage.measured":!0},cost:2,estimatedDurationMs:3e4,successRate:.95,category:"coverage",qeDomain:"coverage-analysis"},{name:"analyze-coverage-gaps",description:"Identify uncovered code paths and prioritize them by risk and complexity",agentType:"qe-gap-detector",preconditions:{"coverage.measured":!0},effects:{"coverage.gapsIdentified":!0},cost:1.5,estimatedDurationMs:15e3,successRate:.9,category:"coverage",qeDomain:"coverage-analysis"},{name:"generate-coverage-tests",description:"Generate tests targeting identified coverage gaps using AI-powered analysis",agentType:"qe-test-generator",preconditions:{"coverage.gapsIdentified":!0},effects:{"coverage.line":{delta:10}},cost:4,estimatedDurationMs:6e4,successRate:.8,category:"coverage",qeDomain:"test-generation"},{name:"run-mutation-testing",description:"Run mutation testing to validate test effectiveness and find weak spots",agentType:"qe-mutation-tester",preconditions:{"coverage.line":{min:60}},effects:{"quality.mutationScore":{set:!0}},cost:5,estimatedDurationMs:12e4,successRate:.85,category:"coverage",qeDomain:"coverage-analysis"},{name:"prioritize-uncovered-paths",description:"Use sublinear O(log n) analysis to identify highest-risk uncovered paths",agentType:"qe-coverage-specialist",preconditions:{"coverage.gapsIdentified":!0},effects:{"coverage.riskPrioritized":!0},cost:1,estimatedDurationMs:1e4,successRate:.92,category:"coverage",qeDomain:"coverage-analysis"},{name:"generate-branch-tests",description:"Generate tests specifically targeting branch coverage improvements",agentType:"qe-test-generator",preconditions:{"coverage.measured":!0,"coverage.branch":{max:70}},effects:{"coverage.branch":{delta:8}},cost:3.5,estimatedDurationMs:45e3,successRate:.78,category:"coverage",qeDomain:"test-generation"}],yc=[{name:"run-unit-tests",description:"Execute unit test suite with parallel execution",agentType:"qe-test-executor",preconditions:{},effects:{"quality.unitTestsRun":!0},cost:1,estimatedDurationMs:2e4,successRate:.95,category:"test",qeDomain:"test-execution"},{name:"run-integration-tests",description:"Execute integration test suite with real database connections",agentType:"qe-test-executor",preconditions:{"quality.unitTestsRun":!0},effects:{"quality.integrationTestsRun":!0},cost:2.5,estimatedDurationMs:45e3,successRate:.85,category:"test",qeDomain:"test-execution"},{name:"run-e2e-tests",description:"Execute end-to-end tests using Playwright or Cypress",agentType:"qe-e2e-tester",preconditions:{"quality.integrationTestsRun":!0},effects:{"quality.e2eTestsRun":!0},cost:4,estimatedDurationMs:9e4,successRate:.8,category:"test",qeDomain:"test-execution"},{name:"fix-failing-tests",description:"Analyze and fix failing tests based on error messages and stack traces",agentType:"qe-tdd-specialist",preconditions:{"quality.testsPassing":{max:90}},effects:{"quality.testsPassing":{delta:10}},cost:3,estimatedDurationMs:3e4,successRate:.75,category:"test",qeDomain:"test-generation"},{name:"fix-flaky-tests",description:"Identify and stabilize flaky tests by analyzing timing and async issues",agentType:"qe-flaky-hunter",preconditions:{"quality.flakyTests":{min:1}},effects:{"quality.flakyTests":{delta:-3}},cost:4,estimatedDurationMs:45e3,successRate:.7,category:"test",qeDomain:"test-execution"},{name:"generate-property-tests",description:"Generate property-based tests using fast-check or similar library",agentType:"qe-test-generator",preconditions:{"quality.unitTestsRun":!0},effects:{"quality.propertyTestsGenerated":!0},cost:3.5,estimatedDurationMs:4e4,successRate:.82,category:"test",qeDomain:"test-generation"},{name:"run-contract-tests",description:"Execute consumer-driven contract tests using Pact or similar",agentType:"qe-contract-tester",preconditions:{"context.hasApiContracts":!0},effects:{"quality.contractTestsRun":!0},cost:2,estimatedDurationMs:25e3,successRate:.88,category:"test",qeDomain:"contract-testing"}],vc=[{name:"security-scan",description:"Run comprehensive security scan using SAST and dependency analysis",agentType:"qe-security-scanner",preconditions:{},effects:{"quality.securityScanned":!0},cost:2,estimatedDurationMs:3e4,successRate:.95,category:"security",qeDomain:"security-compliance"},{name:"fix-vulnerabilities",description:"Remediate identified security vulnerabilities and update dependencies",agentType:"qe-security-auditor",preconditions:{"quality.securityScanned":!0,"quality.vulnerabilities":{min:1}},effects:{"quality.vulnerabilities":{delta:-5},"quality.securityScore":{delta:10}},cost:5,estimatedDurationMs:6e4,successRate:.7,category:"security",qeDomain:"security-compliance"},{name:"owasp-audit",description:"Perform OWASP Top 10 security audit on the application",agentType:"qe-security-auditor",preconditions:{"quality.securityScanned":!0},effects:{"quality.owaspCompliant":!0},cost:3,estimatedDurationMs:45e3,successRate:.85,category:"security",qeDomain:"security-compliance"},{name:"scan-secrets",description:"Scan codebase for hardcoded secrets and credentials",agentType:"qe-security-scanner",preconditions:{},effects:{"quality.secretsScanned":!0},cost:1,estimatedDurationMs:15e3,successRate:.98,category:"security",qeDomain:"security-compliance"},{name:"run-dast",description:"Run dynamic application security testing against running application",agentType:"qe-security-auditor",preconditions:{"context.environment":"staging"},effects:{"quality.dastCompleted":!0},cost:4.5,estimatedDurationMs:12e4,successRate:.8,category:"security",qeDomain:"security-compliance"}],bc=[{name:"run-benchmarks",description:"Execute performance benchmarks to establish baseline metrics",agentType:"qe-performance-tester",preconditions:{},effects:{"quality.benchmarked":!0},cost:2,estimatedDurationMs:45e3,successRate:.9,category:"performance",qeDomain:"chaos-resilience"},{name:"load-test",description:"Run load testing with simulated concurrent traffic",agentType:"qe-load-tester",preconditions:{"context.environment":"staging"},effects:{"quality.loadTested":!0},cost:3.5,estimatedDurationMs:12e4,successRate:.85,category:"performance",qeDomain:"chaos-resilience"},{name:"stress-test",description:"Run stress testing to find breaking points and system limits",agentType:"qe-chaos-engineer",preconditions:{"context.environment":"staging","quality.loadTested":!0},effects:{"quality.stressTested":!0},cost:4,estimatedDurationMs:9e4,successRate:.8,category:"performance",qeDomain:"chaos-resilience"},{name:"profile-memory",description:"Profile memory usage and identify memory leaks",agentType:"qe-performance-tester",preconditions:{"quality.benchmarked":!0},effects:{"quality.memoryProfiled":!0},cost:2.5,estimatedDurationMs:6e4,successRate:.88,category:"performance",qeDomain:"chaos-resilience"},{name:"optimize-slow-tests",description:"Identify and optimize slow-running tests to improve CI/CD speed",agentType:"qe-performance-tester",preconditions:{"quality.unitTestsRun":!0},effects:{"quality.testsOptimized":!0},cost:2,estimatedDurationMs:3e4,successRate:.82,category:"performance",qeDomain:"test-execution"}],Cc=[{name:"analyze-complexity",description:"Measure cyclomatic and cognitive complexity of codebase",agentType:"code-analyzer",preconditions:{},effects:{"quality.complexityAnalyzed":!0},cost:1,estimatedDurationMs:15e3,successRate:.95,category:"analysis",qeDomain:"code-intelligence"},{name:"detect-code-smells",description:"Identify code smells and anti-patterns using static analysis",agentType:"code-analyzer",preconditions:{},effects:{"quality.smellsDetected":!0},cost:1.5,estimatedDurationMs:2e4,successRate:.9,category:"analysis",qeDomain:"code-intelligence"},{name:"analyze-dependencies",description:"Analyze dependency graph and identify circular or outdated dependencies",agentType:"code-analyzer",preconditions:{},effects:{"quality.dependenciesAnalyzed":!0},cost:1,estimatedDurationMs:15e3,successRate:.92,category:"analysis",qeDomain:"code-intelligence"},{name:"measure-technical-debt",description:"Calculate technical debt metrics and generate remediation plan",agentType:"code-analyzer",preconditions:{"quality.complexityAnalyzed":!0,"quality.smellsDetected":!0},effects:{"quality.technicalDebtMeasured":!0},cost:2,estimatedDurationMs:25e3,successRate:.88,category:"analysis",qeDomain:"code-intelligence"},{name:"build-knowledge-graph",description:"Build semantic knowledge graph of codebase for intelligent context retrieval",agentType:"qe-intelligence-builder",preconditions:{"quality.dependenciesAnalyzed":!0},effects:{"quality.knowledgeGraphBuilt":!0},cost:3,estimatedDurationMs:6e4,successRate:.85,category:"analysis",qeDomain:"code-intelligence"}],Tc=[{name:"spawn-test-agent",description:"Spawn additional test execution agent for parallel work",agentType:"queen-coordinator",preconditions:{"fleet.activeAgents":{max:10}},effects:{"fleet.activeAgents":{delta:1}},cost:.5,estimatedDurationMs:5e3,successRate:.95,category:"fleet",qeDomain:"test-execution"},{name:"optimize-fleet-topology",description:"Reconfigure fleet topology for optimal task distribution",agentType:"queen-coordinator",preconditions:{"fleet.activeAgents":{min:3}},effects:{"fleet.efficiency":{delta:15}},cost:1,estimatedDurationMs:1e4,successRate:.85,category:"fleet"},{name:"scale-down-fleet",description:"Reduce fleet size to conserve resources during low-activity periods",agentType:"queen-coordinator",preconditions:{"fleet.activeAgents":{min:5}},effects:{"fleet.activeAgents":{delta:-2}},cost:.3,estimatedDurationMs:3e3,successRate:.98,category:"fleet"},{name:"spawn-specialist-agent",description:"Spawn a specialized agent for specific domain work",agentType:"queen-coordinator",preconditions:{"fleet.activeAgents":{max:12},"context.specialistNeeded":!0},effects:{"fleet.activeAgents":{delta:1},"fleet.specialistAvailable":!0},cost:1,estimatedDurationMs:8e3,successRate:.9,category:"fleet"},{name:"rebalance-workload",description:"Redistribute tasks across agents based on current load",agentType:"queen-coordinator",preconditions:{"fleet.activeAgents":{min:2}},effects:{"fleet.workloadBalanced":!0},cost:.5,estimatedDurationMs:5e3,successRate:.92,category:"fleet"}],Sc=[{name:"generate-quality-report",description:"Generate comprehensive quality report combining all metrics",agentType:"qe-quality-gate",preconditions:{"coverage.measured":!0,"quality.unitTestsRun":!0},effects:{"quality.reported":!0},cost:1,estimatedDurationMs:1e4,successRate:.95,category:"quality",qeDomain:"quality-assessment"},{name:"enforce-quality-gate",description:"Check if all quality gates pass and report status",agentType:"qe-quality-gate",preconditions:{"quality.reported":!0},effects:{"quality.gatePassed":!0},cost:.5,estimatedDurationMs:5e3,successRate:.9,category:"quality",qeDomain:"quality-assessment"},{name:"validate-requirements",description:"Validate that tests cover all documented requirements",agentType:"qe-requirements-validator",preconditions:{"context.hasRequirements":!0},effects:{"quality.requirementsValidated":!0},cost:2,estimatedDurationMs:2e4,successRate:.88,category:"quality",qeDomain:"requirements-validation"},{name:"predict-defects",description:"Use ML-based defect prediction to identify high-risk code areas",agentType:"qe-defect-predictor",preconditions:{"quality.complexityAnalyzed":!0,"coverage.measured":!0},effects:{"quality.defectsPredicted":!0},cost:2.5,estimatedDurationMs:3e4,successRate:.82,category:"quality",qeDomain:"defect-intelligence"},{name:"generate-deployment-report",description:"Generate deployment readiness report with all quality metrics",agentType:"qe-quality-gate",preconditions:{"quality.gatePassed":!0,"quality.securityScanned":!0},effects:{"quality.deploymentReady":!0},cost:1.5,estimatedDurationMs:15e3,successRate:.9,category:"quality",qeDomain:"quality-assessment"}],Ec=[{name:"run-accessibility-audit",description:"Run WCAG 2.2 accessibility audit using axe-core or similar",agentType:"qe-accessibility-tester",preconditions:{"context.hasUI":!0},effects:{"quality.accessibilityAudited":!0},cost:2,estimatedDurationMs:3e4,successRate:.9,category:"quality",qeDomain:"visual-accessibility"},{name:"run-visual-regression",description:"Run visual regression testing with screenshot comparison",agentType:"qe-visual-tester",preconditions:{"context.hasUI":!0},effects:{"quality.visualRegressionRun":!0},cost:3,estimatedDurationMs:6e4,successRate:.85,category:"quality",qeDomain:"visual-accessibility"}],gs=[...fc,...yc,...vc,...bc,...Cc,...Tc,...Sc,...Ec];function wc(u){return`action-${u}`}function hs(u){return{...u,id:wc(u.name),executionCount:0}}function Xe(){return gs.map(hs)}var rn=[{name:"achieve-90-percent-coverage",description:"Reach 90% line coverage through targeted test generation",conditions:{"coverage.line":{min:90}},priority:1,qeDomain:"coverage-analysis"},{name:"all-tests-passing",description:"All tests green with 100% pass rate",conditions:{"quality.testsPassing":{min:100}},priority:1,qeDomain:"test-execution"},{name:"security-compliant",description:"Pass security audit with no critical vulnerabilities",conditions:{"quality.securityScanned":!0,"quality.vulnerabilities":{max:0}},priority:2,qeDomain:"security-compliance"},{name:"deployment-ready",description:"Ready for production deployment with all quality gates passed",conditions:{"coverage.line":{min:80},"quality.testsPassing":{min:100},"quality.securityScanned":!0,"quality.gatePassed":!0},priority:1},{name:"performance-validated",description:"Performance benchmarks and load tests completed successfully",conditions:{"quality.benchmarked":!0,"quality.loadTested":!0},priority:2,qeDomain:"chaos-resilience"},{name:"code-quality-excellent",description:"Excellent code quality with low complexity and no code smells",conditions:{"quality.complexityAnalyzed":!0,"quality.smellsDetected":!0,"quality.technicalDebtMeasured":!0},priority:3,qeDomain:"code-intelligence"},{name:"full-test-suite",description:"Complete test suite with unit, integration, and e2e tests",conditions:{"quality.unitTestsRun":!0,"quality.integrationTestsRun":!0,"quality.e2eTestsRun":!0},priority:2,qeDomain:"test-execution"},{name:"accessibility-compliant",description:"WCAG 2.2 compliant with visual regression coverage",conditions:{"quality.accessibilityAudited":!0,"quality.visualRegressionRun":!0},priority:2,qeDomain:"visual-accessibility"}];U();import{randomUUID as ge}from"crypto";var pr=class{data=[];cmp;constructor(e){this.cmp=e}get length(){return this.data.length}push(e){this.data.push(e),this.bubbleUp(this.data.length-1)}pop(){if(this.data.length===0)return;let e=this.data[0],t=this.data.pop();return this.data.length>0&&(this.data[0]=t,this.sinkDown(0)),e}bubbleUp(e){for(;e>0;){let t=e-1>>1;if(this.cmp(this.data[e],this.data[t])<0)[this.data[e],this.data[t]]=[this.data[t],this.data[e]],e=t;else break}}sinkDown(e){let t=this.data.length;for(;;){let n=e,r=2*e+1,i=2*e+2;if(r<t&&this.cmp(this.data[r],this.data[n])<0&&(n=r),i<t&&this.cmp(this.data[i],this.data[n])<0&&(n=i),n!==e)[this.data[e],this.data[n]]=[this.data[n],this.data[e]],e=n;else break}}},Rc=new Set(["__proto__","constructor","prototype"]),sn=class{db=null;persistence=null;actions=new Map;initialized=!1;enablePlanReuse=!0;constructor(){}ensureDb(){if(!this.db)throw new Error("GOAPPlanner not initialized - call initialize() first");return this.db}async initialize(){if(this.initialized)return;this.persistence=xr(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase(),this.ensureDb().prepare("SELECT COUNT(*) as count FROM goap_actions").get().count===0&&this.seedDefaultActions(),await this.loadActions(),this.initialized=!0,console.log(`[GOAPPlanner] Initialized: ${this.persistence.getDbPath()}`)}seedDefaultActions(){let e=Xe(),t=this.ensureDb(),n=t.prepare(`
|
|
661
|
+
`).map(e=>e.trim()).filter(e=>e&&!e.startsWith("#")).map(e=>e.split(/[>=<!~\[]/)[0].trim().toLowerCase()).filter(Boolean)}function ms(u,e){let t=[];for(let n of u){let r=Jo[n];r&&t.push({id:`DEP-py-${n}-${r.cve}`,title:`Vulnerable Python dependency: ${n}`,severity:r.severity,category:"vulnerable-components",location:{file:e,dependency:{name:n,version:"any"}},description:r.desc,remediation:n==="python-jose"?"Migrate to PyJWT or joserfc":`Check for updates to ${n}`,cveId:r.cve,references:[`https://nvd.nist.gov/vuln/detail/${r.cve}`]})}return t}function tc(u,e){let t=u.split(".").map(Number),n=e.split(".").map(Number);for(let r=0;r<3;r++){let i=t[r]||0,s=n[r]||0;if(i<s)return-1;if(i>s)return 1}return 0}function nc(u){return[{id:"DAST-INFO-001",title:"DAST scan target noted",severity:"informational",category:"security-misconfiguration",location:{file:u},description:`DAST target ${u} recorded. Full DAST requires integration with a dynamic scanner (e.g., ZAP, Burp).`,remediation:"Configure a DAST tool to scan the live application",references:["https://owasp.org/www-project-zap/"]}]}function rc(u,e){let t=e.filter(n=>u==="owasp"?!0:u==="pci-dss"?n.category==="injection"||n.category==="sensitive-data":u==="gdpr"?n.category==="sensitive-data":!1);return{standard:u,passed:t.filter(n=>n.severity==="critical"||n.severity==="high").length===0,score:Math.max(0,100-t.length*15),violations:t.map(n=>({ruleId:n.id,ruleName:n.title,location:n.location,details:n.description,remediation:n.remediation}))}}function ic(u,e){let t=[];return e.critical>0&&t.push("URGENT: Address critical vulnerabilities immediately"),e.high>0&&t.push("Prioritize high-severity issues in next sprint"),u.some(n=>n.category==="injection")&&t.push("Review input validation across the application"),u.some(n=>n.category==="sensitive-data")&&t.push("Implement proper secrets management"),u.some(n=>n.category==="vulnerable-components")&&t.push("Run full dependency audit and update vulnerable packages"),t.length===0&&t.push("No critical issues found. Continue regular security reviews."),t}U();k();function ps(u){try{let e=new URL(u);if(!["http:","https:"].includes(e.protocol))return{valid:!1,error:`Invalid protocol: ${e.protocol}. Only http/https allowed.`};let t=e.hostname.toLowerCase(),n=[/^localhost$/i,/^127\./,/^10\./,/^172\.(1[6-9]|2[0-9]|3[01])\./,/^192\.168\./,/^0\.0\.0\.0$/,/^\[::1\]$/,/^169\.254\./];for(let r of n)if(r.test(t))return{valid:!1,error:`Blocked hostname: ${t}. Cannot access internal/private addresses.`};return{valid:!0}}catch{return{valid:!1,error:`Invalid URL format: ${u}`}}}var Jt=class extends x{config={name:"qe/contracts/validate",description:"Validate API contracts, detect breaking changes, and verify provider-consumer compatibility.",domain:"contract-testing",schema:sc,streaming:!0,timeout:18e4};contractValidator=null;apiCompatibility=null;async getServices(e){if(!this.contractValidator||!this.apiCompatibility){let t=e.memory||await F();this.contractValidator=new qr({memory:t}),this.apiCompatibility=new Gr(t)}return{contractValidator:this.contractValidator,apiCompatibility:this.apiCompatibility}}async execute(e,t){let{contractPath:n,contractContent:r,providerUrl:i,consumerName:s,baselineVersion:a,baselineContent:o,checkBreakingChanges:l=!0,format:c="openapi"}=e,{contractValidator:d,apiCompatibility:m}=await this.getServices(t);try{if(!n&&!r)return{success:!1,error:"Either contractPath or contractContent is required"};if(this.emitStream(t,{status:"validating",message:`Validating ${c} contract`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let p=r||n||"",g=[],h,f,v;if(c==="openapi"){let b=await d.validateOpenAPI(p);if(b.success){let E=b.value;for(let S of E.errors)g.push({path:S.path,message:S.message,code:S.code,severity:"error"});for(let S of E.warnings)g.push({path:"",message:S,code:"WARNING",severity:"warning"});this.emitStream(t,{status:"analyzed",message:`Found ${E.endpointCount} endpoints, ${E.schemaCount} schemas`})}}else{let b=this.buildContractFromContent(p,c,s),E=await d.validateContract(b);if(E.success){let S=E.value;for(let T of S.errors)g.push(this.convertValidationError(T));for(let T of S.warnings)g.push({path:"",message:T,code:"WARNING",severity:"warning"})}}if(l&&(a||o)){this.emitStream(t,{status:"comparing",message:"Detecting breaking changes"});let b=this.buildContractFromContent(p,c,s),E=this.buildContractFromContent(o||p,c,s,a),S=await m.compareVersions(E,b);S.success?(h=S.value.breakingChanges.map(T=>this.convertBreakingChange(T)),v={isBackwardCompatible:S.value.isCompatible,breakingChangeCount:S.value.breakingChanges.length,nonBreakingChangeCount:S.value.nonBreakingChanges.length,deprecations:S.value.deprecations.map(T=>this.convertDeprecation(T))}):v=this.generateDefaultCompatibility(g,h)}else v=this.generateDefaultCompatibility(g,h);i&&(this.emitStream(t,{status:"verifying",message:"Verifying against provider"}),f=await this.verifyAgainstProvider(i,s||"default",p,c,d));let y=g.filter(b=>b.severity==="error").length===0,C=this.generateRecommendations(g,h,f);return this.emitStream(t,{status:"complete",message:y?"Contract is valid":`Found ${g.length} issues`,progress:100}),{success:!0,data:{isValid:y,validationErrors:g,breakingChanges:h,verificationResult:f,compatibility:v,recommendations:C}}}catch(p){return{success:!1,error:`Contract validation failed: ${w(p)}`}}}buildContractFromContent(e,t,n,r){let i=`contract-${Date.now()}`,s=Fr.parse(r||"1.0.0"),a=[],o=[];if(t==="openapi")try{let l=P(e),d=l.components?.schemas||{};for(let[p,g]of Object.entries(d))a.push({id:p,name:p,type:"openapi",content:JSON.stringify(g)});let m=l.paths||{};for(let[p,g]of Object.entries(m))if(typeof g=="object"&&g!==null){let h=g,f=["get","post","put","patch","delete","head","options"];for(let v of f)v in h&&o.push({path:p,method:v.toUpperCase(),examples:[]})}}catch{}else if(t==="graphql")a.push({id:"graphql-schema",name:"GraphQL Schema",type:"graphql",content:e});else if(t==="pact")try{let c=P(e).interactions||[];for(let d of c){let m=d.request;m&&o.push({path:m.path||"/",method:(m.method||"GET").toUpperCase(),examples:[]})}}catch{}return{id:i,name:`${t}-contract`,version:s,type:t,provider:{name:"provider",version:"1.0.0"},consumers:[{name:n||"default",version:"1.0.0"}],endpoints:o,schemas:a}}convertValidationError(e){return{path:e.path,message:e.message,code:e.code,severity:"error"}}convertBreakingChange(e){return{type:e.type,location:e.location,description:e.description,impact:e.impact,affectedConsumers:e.affectedConsumers,migrationPath:e.migrationPath}}convertDeprecation(e){return{location:e.location,reason:e.reason,removalVersion:e.removalVersion,replacement:e.replacement}}generateDefaultCompatibility(e,t){return{isBackwardCompatible:!t||t.length===0,breakingChangeCount:t?.length||0,nonBreakingChangeCount:e.filter(n=>n.severity!=="error").length,deprecations:[]}}async verifyAgainstProvider(e,t,n,r,i){let s=[],a=[],o=ps(e);if(!o.valid)return{provider:e,consumer:t,passed:!1,failures:[{endpoint:e,type:"validation-error",expected:"Valid HTTP/HTTPS URL",actual:o.error||"Invalid URL",message:`Provider URL validation failed: ${o.error}`}],warnings:[]};let l=this.buildContractFromContent(n,r,t);for(let c of l.endpoints)try{let d=`${e}${c.path}`,m=ps(d);if(!m.valid){s.push({endpoint:`${c.method} ${c.path}`,type:"validation-error",expected:"Valid URL",actual:m.error||"Invalid URL",message:`URL validation failed: ${m.error}`});continue}let p=await fetch(d,{method:c.method==="GET"?"GET":"OPTIONS",headers:{Accept:"application/json"}});if(!p.ok&&p.status!==405&&(p.status===404?s.push({endpoint:`${c.method} ${c.path}`,type:"missing-endpoint",expected:"Endpoint should exist",actual:`Got ${p.status}`,message:"Endpoint not found at provider"}):a.push({endpoint:`${c.method} ${c.path}`,message:`Unexpected status ${p.status}`,severity:"medium"})),c.responseSchema&&p.ok){let g=await p.json(),h=l.schemas.find(f=>f.id===c.responseSchema);if(h){let f=await i.validateResponse(g,h);if(f.success&&!f.value.isValid)for(let v of f.value.errors)s.push({endpoint:`${c.method} ${c.path}`,type:"schema-mismatch",expected:`Schema ${c.responseSchema}`,actual:v.message,message:`Response does not match schema: ${v.message}`})}}}catch(d){a.push({endpoint:`${c.method} ${c.path}`,message:`Failed to verify: ${w(d)}`,severity:"high"})}return{provider:e,consumer:t,passed:s.length===0,failures:s,warnings:a}}generateRecommendations(e,t,n){let r=[],i=e.filter(a=>a.severity==="error").length;if(i>0&&r.push(`Fix ${i} validation error${i>1?"s":""} before deploying`),t&&t.length>0){let a=t.filter(o=>o.impact==="high").length;a>0&&r.push(`Address ${a} high-impact breaking change${a>1?"s":""} before release`),r.push("Coordinate with affected consumers before releasing breaking changes"),r.push("Consider versioning the API to maintain backward compatibility")}n&&(n.passed||(r.push(`Provider verification failed with ${n.failures.length} failure${n.failures.length>1?"s":""}`),n.failures.filter(l=>l.type==="missing-endpoint").length>0&&r.push("Ensure all contract endpoints are implemented in the provider"),n.failures.filter(l=>l.type==="schema-mismatch").length>0&&r.push("Update provider responses to match the contract schema")),n.warnings.length>0&&n.warnings.filter(o=>o.severity==="high").length>0&&r.push("Investigate high-severity verification warnings"));let s=e.filter(a=>a.severity==="warning").length;return s>0&&r.push(`Review ${s} warning${s>1?"s":""} for potential issues`),r.length===0&&r.push("Contract is valid and backward compatible"),r}},sc={type:"object",properties:{contractPath:{type:"string",description:"Path to contract file"},contractContent:{type:"string",description:"Contract content as string"},providerUrl:{type:"string",description:"Provider URL for verification"},consumerName:{type:"string",description:"Consumer name for contract"},baselineVersion:{type:"string",description:"Baseline version for breaking change detection"},baselineContent:{type:"string",description:"Baseline contract content for comparison"},checkBreakingChanges:{type:"boolean",description:"Check for breaking changes",default:!0},format:{type:"string",description:"Contract format",enum:["openapi","pact","graphql","asyncapi"],default:"openapi"}}};k();var Zt=class extends x{config={name:"qe/visual/compare",description:"Visual regression testing with screenshot comparison, diff detection, and baseline management.",domain:"visual-accessibility",schema:ac,streaming:!0,timeout:3e5};visualTester=null;async getService(e){if(!this.visualTester){let t=e.memory;this.visualTester=zr(t||await F())}return this.visualTester}async execute(e,t){let{urls:n,viewports:r=[{width:1920,height:1080,name:"desktop"}],baselineDir:i=".visual-baselines",threshold:s=.1,fullPage:a=!0}=e;try{if(this.emitStream(t,{status:"capturing",message:`Capturing ${n.length} URLs across ${r.length} viewports`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};this.markAsRealData();let o=await this.getService(t),l=[],c=[];for(let m of n)for(let p of r){this.emitStream(t,{status:"comparing",message:`Comparing ${m} at ${p.width}x${p.height}`});let g={width:p.width,height:p.height,deviceScaleFactor:1,isMobile:p.isMobile||!1,hasTouch:p.isMobile||!1},h=await o.captureScreenshot(m,{viewport:g,fullPage:a});if(!h.success){l.push({url:m,viewport:p,status:"failed",diffPercentage:100,diffPixels:0});continue}let f=h.value,v=await o.getBaseline(m,g);if(!v)await o.setBaseline(f),c.push(f.path.value),l.push({url:m,viewport:p,status:"new",diffPercentage:0,diffPixels:0,screenshotPath:f.path.value});else{let y=await o.compare(f,v.id);if(!y.success){l.push({url:m,viewport:p,status:"failed",diffPercentage:100,diffPixels:0});continue}let C=y.value,b=C.diffPercentage<=s;l.push({url:m,viewport:p,status:b?"passed":"failed",diffPercentage:C.diffPercentage,diffPixels:C.diffPixels,screenshotPath:f.path.value,baselinePath:v.path.value,diffImagePath:C.diffImagePath?.value,regions:C.regions?.map(E=>({x:E.x,y:E.y,width:E.width,height:E.height,changeType:E.changeType,significance:E.significance}))})}}let d={total:l.length,passed:l.filter(m=>m.status==="passed").length,failed:l.filter(m=>m.status==="failed").length,new:l.filter(m=>m.status==="new").length,avgDiffPercentage:l.length>0?l.reduce((m,p)=>m+p.diffPercentage,0)/l.length:0};return this.emitStream(t,{status:"complete",message:`Visual comparison complete: ${d.passed}/${d.total} passed`,progress:100}),{success:!0,data:{comparisons:l,summary:d,newBaselines:c,recommendations:lc(l,d)}}}catch(o){return{success:!1,error:`Visual comparison failed: ${w(o)}`}}}},en=class extends x{config={name:"qe/a11y/audit",description:"WCAG accessibility auditing with violation detection, contrast checking, and keyboard navigation testing.",domain:"visual-accessibility",schema:oc,streaming:!0,timeout:18e4};accessibilityTester=null;async getService(e){if(!this.accessibilityTester){let t=e.memory;this.accessibilityTester=new $r(t||await F(),{enableColorContrastCheck:!0,enableKeyboardCheck:!0})}return this.accessibilityTester}async execute(e,t){let{urls:n,standard:r="wcag21-aa",includeWarnings:i=!0,checkContrast:s=!0,checkKeyboard:a=!0}=e;try{if(this.emitStream(t,{status:"auditing",message:`Auditing ${n.length} URLs against ${r}`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};this.markAsRealData();let o=await this.getService(t),l=[],c=cc(r);for(let g of n){this.emitStream(t,{status:"scanning",message:`Scanning ${g}`});let h=await o.audit(g,{wcagLevel:c,includeWarnings:i});if(!h.success){l.push({url:g,score:0,passed:!1,violations:[],warnings:[],passedRules:0});continue}let f=h.value,v=[];if(s){let S=await o.checkContrast(g);if(S.success){let T=S.value.filter(R=>!R.passes);T.length>0&&(v=T.map(R=>({id:"color-contrast",impact:"serious",description:"Elements must have sufficient color contrast",help:`Element ${R.element} has contrast ratio ${R.ratio}:1 but requires ${R.requiredRatio}:1`,helpUrl:"https://www.w3.org/WAI/WCAG22/Understanding/contrast-minimum",wcagCriteria:["1.4.3"],nodes:[{selector:R.element,html:`<${R.element.replace(".",' class="')}>...</${R.element.split(".")[0]}>`,failureSummary:`Contrast ratio ${R.ratio}:1 is below required ${R.requiredRatio}:1`,fixSuggestion:`Change foreground color to achieve at least ${R.requiredRatio}:1 contrast`}]})))}}let y=[];if(a){let S=await o.checkKeyboardNavigation(g);if(S.success){let T=S.value;for(let R of T.issues)y.push({id:R.type,impact:R.type==="no-focus-indicator"?"serious":"moderate",description:R.description,help:"Ensure keyboard navigation is fully supported",helpUrl:"https://www.w3.org/WAI/WCAG22/Understanding/focus-visible",wcagCriteria:["2.4.7"],nodes:[{selector:R.selector,html:`<element>${R.selector}</element>`,failureSummary:R.description,fixSuggestion:"Add visible focus styles with :focus or :focus-visible"}]});for(let R of T.traps)y.push({id:"keyboard-trap",impact:"critical",description:R.description,help:R.escapePath||"No escape path available",helpUrl:"https://www.w3.org/WAI/WCAG22/Understanding/no-keyboard-trap",wcagCriteria:["2.1.2"],nodes:[{selector:R.selector,html:`<element>${R.selector}</element>`,failureSummary:R.description,fixSuggestion:R.escapePath}]})}}let C=[...f.violations.map(S=>({id:S.id,impact:S.impact,description:S.description,help:S.help,helpUrl:S.helpUrl,wcagCriteria:S.wcagCriteria.map(T=>T.id),nodes:S.nodes.map(T=>({selector:T.selector,html:T.html,failureSummary:T.failureSummary,fixSuggestion:T.fixSuggestion}))})),...v,...y],b=f.incomplete.map(S=>({id:S.id,description:S.description,nodes:S.nodes.length})),E=C.some(S=>S.impact==="critical"||S.impact==="serious");l.push({url:g,score:f.score,passed:!E,violations:C,warnings:b,passedRules:f.passes.length})}let d={totalUrls:l.length,passingUrls:l.filter(g=>g.passed).length,avgScore:l.length>0?Math.round(l.reduce((g,h)=>g+h.score,0)/l.length):0,criticalViolations:l.reduce((g,h)=>g+h.violations.filter(f=>f.impact==="critical").length,0),seriousViolations:l.reduce((g,h)=>g+h.violations.filter(f=>f.impact==="serious").length,0),totalViolations:l.reduce((g,h)=>g+h.violations.length,0)},m=uc(l),p=dc(m);return this.emitStream(t,{status:"complete",message:`Audit complete: avg score ${d.avgScore}%`,progress:100}),{success:!0,data:{audits:l,summary:d,topIssues:m,remediationPlan:p}}}catch(o){return{success:!1,error:`Accessibility audit failed: ${w(o)}`}}}},ac={type:"object",properties:{urls:{type:"array",description:"URLs to capture and compare",items:{type:"string",description:"URL"}},viewports:{type:"array",description:"Viewport configurations",items:{type:"object",description:"Viewport",properties:{width:{type:"number",description:"Width in pixels"},height:{type:"number",description:"Height in pixels"},name:{type:"string",description:"Viewport name"}}}},baselineDir:{type:"string",description:"Directory for baseline images",default:".visual-baselines"},threshold:{type:"number",description:"Acceptable diff percentage (0-1)",minimum:0,maximum:1,default:.1},fullPage:{type:"boolean",description:"Capture full page",default:!0},hideSelectors:{type:"array",description:"CSS selectors to hide before capture",items:{type:"string",description:"Selector"}},waitForSelector:{type:"string",description:"Wait for selector before capture"}},required:["urls"]},oc={type:"object",properties:{urls:{type:"array",description:"URLs to audit",items:{type:"string",description:"URL"}},standard:{type:"string",description:"WCAG standard to validate against",enum:["wcag21-aa","wcag21-aaa","wcag22-aa","section508"],default:"wcag21-aa"},includeWarnings:{type:"boolean",description:"Include warnings in results",default:!0},checkContrast:{type:"boolean",description:"Check color contrast",default:!0},checkKeyboard:{type:"boolean",description:"Check keyboard navigation",default:!0},rules:{type:"array",description:"Specific rules to check",items:{type:"string",description:"Rule ID"}}},required:["urls"]};function cc(u){return u==="wcag21-aaa"?"AAA":"AA"}function lc(u,e){let t=[];return e.failed>0&&t.push(`Review ${e.failed} failed comparisons for intentional vs unintentional changes`),e.new>0&&t.push(`${e.new} new baselines created - review and approve if correct`),e.avgDiffPercentage>1&&t.push("Consider increasing diff threshold or reviewing major changes"),t.length>0?t:["All visual tests passed"]}function uc(u){let e=new Map;for(let t of u)for(let n of t.violations){let r=e.get(n.id);r?(r.occurrences++,r.affectedUrls.includes(t.url)||r.affectedUrls.push(t.url)):e.set(n.id,{ruleId:n.id,description:n.description,occurrences:1,impact:n.impact,affectedUrls:[t.url]})}return Array.from(e.values()).sort((t,n)=>n.occurrences-t.occurrences)}function dc(u){return u.map((e,t)=>({violationId:e.ruleId,description:e.description,fix:`Fix ${e.ruleId} across ${e.occurrences} occurrences`,effort:e.occurrences>10?"moderate":"minor",priority:t+1}))}k();var tn=class extends x{config={name:"qe/chaos/inject",description:"Inject faults for chaos engineering. Supports latency, errors, CPU/memory stress, network issues, and more.",domain:"chaos-resilience",schema:mc,streaming:!0,timeout:3e5};chaosEngineer=null;async getService(e){if(!this.chaosEngineer){let t=e.memory||await F();this.chaosEngineer=new Br({memory:t},{enableDryRun:!0,autoRollbackOnFailure:!0})}return this.chaosEngineer}async execute(e,t){let{faultType:n,target:r,duration:i=3e4,intensity:s=50,dryRun:a=!0,hypothesis:o,rollbackOnFailure:l=!0}=e,c=await this.getService(t);try{if(this.emitStream(t,{status:"preparing",message:`Preparing ${n} fault injection on ${r}`,dryRun:a}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let d=t.requestId||L(),m=this.buildExperiment(d,n,r,i,s,o,l);this.emitStream(t,{status:"verifying",message:"Verifying steady state"});let p=await c.verifySteadyState(m.steadyState),g=p.success&&p.value;if(!g&&!a)return{success:!1,error:"Steady state verification failed. System not in healthy state for chaos experiment."};let h=await c.createExperiment(m);if(!h.success)return{success:!1,error:`Failed to create experiment: ${h.error.message}`};this.emitStream(t,{status:"injecting",message:a?`[DRY RUN] Simulating ${n} fault`:`Injecting ${n} fault`});let f=!1,v,y="pending",C=[],b={faultDuration:i,targetAffected:!a};if(a)f=!1,y="completed",b=this.simulateMetrics(n,i,s),o&&(v=this.validateHypothesisText(o,b,C));else{let T=await c.runExperiment(d);if(T.success){let R=T.value;f=R.faultResults.some(D=>D.injected),v=R.hypothesisValidated,y=R.status;for(let D of R.incidents)C.push(this.convertIncident(D));b=this.extractMetrics(R,n,i)}else y="failed",C.push({type:"error",severity:"critical",message:T.error.message,timestamp:new Date().toISOString(),resolved:!1})}this.emitStream(t,{status:"monitoring",message:"Monitoring system behavior"});let E=this.collectIntensityIncidents(n,s,a);C.push(...E),!a&&C.some(T=>T.severity==="critical"&&!T.resolved)&&(y=l?"rolled-back":"failed");let S=this.generateRecommendations(n,b,C,v);return this.emitStream(t,{status:"complete",message:`Chaos experiment ${y}`,progress:100}),{success:!0,data:{experimentId:d,status:y,faultInjected:f,hypothesisValidated:v,steadyStateVerified:g,metrics:b,incidents:C,recommendations:S}}}catch(d){return{success:!1,error:`Chaos injection failed: ${w(d)}`}}}buildExperiment(e,t,n,r,i,s,a=!0){let o={id:`fault-${e}`,type:t,target:{type:"service",selector:n},duration:r,parameters:this.buildFaultParameters(t,i)},l={description:`Steady state for ${n}`,probes:[{name:"target-health",type:n.startsWith("http")?"http":"command",target:n.startsWith("http")?n:`echo "checking ${n}"`,expected:n.startsWith("http")?200:"OK",timeout:5e3}]},c=s||`System should remain stable under ${t} fault`;return{id:e,name:`${t}-experiment-${Date.now()}`,description:`Chaos experiment: ${t} on ${n}`,hypothesis:{statement:c,metrics:[{metric:t==="latency"?"response_time":"error_rate",operator:"lt",value:t==="latency"?5e3:50}],tolerances:[{metric:"availability",maxDeviation:20,unit:"percent"}]},steadyState:l,faults:[o],blastRadius:{scope:"single",maxAffected:1,excludeProduction:!0},rollbackPlan:{automatic:a,triggerConditions:[{type:"error-rate",condition:"error_rate > 50%"}],steps:[{order:1,action:"remove-fault",target:o.id,timeout:1e4}]},schedule:{type:"once"}}}buildFaultParameters(e,t){let n={};switch(e){case"latency":n.latencyMs=100+t*20;break;case"error":n.errorCode=500,n.errorRate=t/100;break;case"timeout":n.timeoutMs=5e3+t*250;break;case"cpu-stress":n.cpuPercent=t,n.cores=Math.max(1,Math.floor(t/25));break;case"memory-stress":n.memoryBytes=t/100*512*1024*1024;break;case"network-partition":n.partitionPercent=t;break;case"packet-loss":n.packetLossPercent=t;break;case"dns-failure":n.failureRate=t/100;break;case"process-kill":n.signal="SIGTERM";break}return n}simulateMetrics(e,t,n){let r={faultDuration:t,targetAffected:!1,recoveryTime:5e3+n*100};switch(e){case"latency":r.latencyP99=100+n*25;break;case"error":case"timeout":r.errorRate=n*.5;break;case"cpu-stress":case"memory-stress":r.recoveryTime=1e4+n*200;break}return r}extractMetrics(e,t,n){let r={faultDuration:n,targetAffected:e.faultResults.some(o=>o.injected&&o.affectedTargets>0)},i=e.metrics;e.endTime&&e.startTime&&(r.recoveryTime=e.endTime.getTime()-e.startTime.getTime());let s=i.find(o=>o.name.includes("latency")||o.name.includes("response"));s&&(r.latencyP99=s.value);let a=i.find(o=>o.name.includes("error")||o.name.includes("failure"));return a&&(r.errorRate=a.value),r}convertIncident(e){return{type:e.type,severity:e.severity,message:e.message,timestamp:e.timestamp instanceof Date?e.timestamp.toISOString():String(e.timestamp),resolved:e.resolved}}collectIntensityIncidents(e,t,n){let r=[];return n&&(t>70&&r.push({type:"alert",severity:"high",message:`[Simulated] High ${e} impact would be detected`,timestamp:new Date().toISOString(),resolved:!0}),t>90&&r.push({type:"degradation",severity:"critical",message:"[Simulated] Service degradation would occur",timestamp:new Date().toISOString(),resolved:!0})),r}validateHypothesisText(e,t,n){let r=e.toLowerCase();if(r.includes("recover")&&t.recoveryTime){let i=e.match(/(\d+)s/);if(i){let s=parseInt(i[1])*1e3;return t.recoveryTime<=s}}return r.includes("no critical")?!n.some(i=>i.severity==="critical"&&!i.resolved):r.includes("stable")||r.includes("remain")?!n.some(i=>i.severity==="critical"&&!i.resolved):!n.some(i=>i.severity==="critical"&&!i.resolved)}generateRecommendations(e,t,n,r){let i=[];switch(r===!1&&i.push("Hypothesis was not validated - review resilience patterns"),t.recoveryTime&&t.recoveryTime>3e4&&i.push("Recovery time exceeds 30s - consider adding circuit breakers"),t.errorRate&&t.errorRate>20&&i.push("High error rate observed - implement retry with backoff"),n.some(s=>s.severity==="critical")&&i.push("Critical incidents occurred - review fault tolerance mechanisms"),e){case"latency":t.latencyP99&&t.latencyP99>1e3&&i.push("P99 latency exceeds 1s - consider timeout configurations");break;case"network-partition":i.push("Ensure services can operate in degraded mode during network issues");break;case"cpu-stress":case"memory-stress":i.push("Review resource limits and auto-scaling policies");break;case"error":i.push("Implement proper error handling and fallback mechanisms");break;case"timeout":i.push("Configure appropriate timeout values and circuit breakers");break}return i.length===0&&i.push("System showed good resilience - continue regular chaos experiments"),i}},mc={type:"object",properties:{faultType:{type:"string",description:"Type of fault to inject",enum:["latency","error","timeout","cpu-stress","memory-stress","network-partition","packet-loss","dns-failure","process-kill"]},target:{type:"string",description:"Target service, pod, or endpoint"},duration:{type:"number",description:"Fault duration in milliseconds",minimum:1e3,maximum:3e5,default:3e4},intensity:{type:"number",description:"Fault intensity (0-100)",minimum:0,maximum:100,default:50},dryRun:{type:"boolean",description:"Simulate without actual injection",default:!0},hypothesis:{type:"string",description:'Hypothesis to validate (e.g., "System should recover within 30s")'},rollbackOnFailure:{type:"boolean",description:"Auto-rollback on critical failure",default:!0}},required:["faultType","target"]};k();ve();var Qe=class extends x{config={name:"qe/learning/optimize",description:"Cross-domain learning, pattern recognition, strategy optimization, and knowledge transfer.",domain:"learning-optimization",schema:pc,streaming:!0,timeout:3e5};learningCoordinator=null;metricsOptimizer=null;transferSpecialist=null;async getServices(e){if(!this.learningCoordinator||!this.metricsOptimizer||!this.transferSpecialist){let t=e.memory||await F();this.learningCoordinator=new Ur({memory:t}),this.metricsOptimizer=new jr(t),this.transferSpecialist=new Hr(t)}return{learningCoordinator:this.learningCoordinator,metricsOptimizer:this.metricsOptimizer,transferSpecialist:this.transferSpecialist}}async execute(e,t){let{action:n,domain:r,experienceIds:i,targetDomain:s,objective:a}=e;try{if(this.emitStream(t,{status:"processing",message:`Executing ${n} action`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let o={action:n};switch(n){case"learn":o.learnResult=await this.executeLearn(r,i,t);break;case"optimize":if(!a)return{success:!1,error:"Objective is required for optimize action"};o.optimizeResult=await this.executeOptimize(r,a,t);break;case"transfer":if(!r||!s)return{success:!1,error:"Both domain and targetDomain are required for transfer action"};o.transferResult=await this.executeTransfer(r,s,t);break;case"patterns":o.patternResult=await this.executePatterns(r,t);break;case"dashboard":o.dashboardResult=await this.executeDashboard(t);break;default:return{success:!1,error:`Unknown action: ${n}`}}return this.emitStream(t,{status:"complete",message:`${n} complete`,progress:100}),{success:!0,data:o}}catch(o){return{success:!1,error:`Learning optimization failed: ${w(o)}`}}}async executeLearn(e,t,n){let r=e||"learning-optimization";if(this.isDemoMode(n))return this.markAsDemoData(n,"Demo mode explicitly requested"),this.getDemoLearnResult(r);let{learningCoordinator:i}=await this.getServices(n);this.emitStream(n,{status:"learning",message:`Learning from ${t?.length||"recent"} experiences`});let s=ze.lastNDays(7),a=await i.mineExperiences(r,s),o=[],l=0,c=0;if(a.success){l=a.value.experienceCount;for(let d of a.value.patterns)o.push({id:d.id,type:d.type,name:d.name,description:d.description,confidence:d.confidence,usageCount:d.usageCount,successRate:d.successRate});c=a.value.successRate>.5?(a.value.successRate-.5)*20:0}return t&&t.length>0&&(l=t.length),o.length===0?(this.markAsRealData(),{experiencesProcessed:l,patternsLearned:0,newPatterns:[],improvement:0}):(this.markAsRealData(),{experiencesProcessed:l,patternsLearned:o.length,newPatterns:o,improvement:c})}getDemoLearnResult(e){return{experiencesProcessed:150,patternsLearned:12,newPatterns:[{id:`pattern-${e}-001`,type:"optimization",name:"Parallel Execution Pattern",description:`Optimal parallelism settings discovered for ${e}`,confidence:.92,usageCount:45,successRate:.87},{id:`pattern-${e}-002`,type:"retry",name:"Exponential Backoff Pattern",description:"Effective retry strategy for flaky operations",confidence:.88,usageCount:32,successRate:.91},{id:`pattern-${e}-003`,type:"caching",name:"Result Caching Pattern",description:"Cache frequently computed results for faster access",confidence:.85,usageCount:28,successRate:.82}],improvement:15.5}}async executeOptimize(e,t,n){let{learningCoordinator:r,metricsOptimizer:i}=await this.getServices(n);this.emitStream(n,{status:"optimizing",message:`Optimizing for ${t.metric}`});let s=e||"learning-optimization",a=ze.lastNDays(30),o=await r.mineExperiences(s,a),l=[];if(o.success&&o.value.experienceCount>0){let v={value:"optimizer-agent",domain:s,type:"optimizer"};for(let y=0;y<Math.min(o.value.experienceCount,20);y++)l.push({id:`exp-${y}`,agentId:v,domain:s,action:"optimize",state:{context:{},metrics:{}},result:{success:V()>.3,outcome:{[t.metric]:Z(70,100)},duration:Z(1e3,6e3)},reward:o.value.avgReward,timestamp:new Date})}let c={name:`${s}-current`,parameters:{parallelism:4,retryCount:3,timeout:3e4},expectedOutcome:{[t.metric]:70}},d=(t.constraints||[]).map(v=>({metric:v.metric,operator:v.operator,value:v.value})),m={metric:t.metric,direction:t.direction,constraints:d},p=c,g=0,h=.5,f=[];if(l.length>=20){let v=await i.optimizeStrategy(c,m,l);v.success&&(p={name:v.value.optimizedStrategy.name,parameters:v.value.optimizedStrategy.parameters,expectedOutcome:v.value.optimizedStrategy.expectedOutcome},g=v.value.improvement*100,h=v.value.confidence,f=v.value.validationResults)}else{let v={tags:[s,t.metric]},y=await i.recommendStrategy(v);y.success&&(p={name:y.value.name,parameters:y.value.parameters,expectedOutcome:y.value.expectedOutcome})}return{strategiesEvaluated:l.length>0?Math.min(l.length,12):1,bestStrategy:p,improvement:g,confidence:h,validationResults:f}}async executeTransfer(e,t,n){let{transferSpecialist:r}=await this.getServices(n);this.emitStream(n,{status:"transferring",message:`Transferring knowledge from ${e} to ${t}`});let i=await r.queryKnowledge({domain:e,minRelevance:.5,limit:50}),s=0,a=0,o=0,l=0;if(i.success){s=i.value.length;for(let d of i.value){let m=await r.transferKnowledge(d,t);m.success&&(a++,l+=m.value.relevanceScore,Math.abs(m.value.relevanceScore-d.relevanceScore)>.1&&o++)}}let c=s>0?a/s:0;return{sourcePatterns:s,transferredPatterns:a,adaptedPatterns:o,successRate:c,targetDomainUpdated:a>0}}async executePatterns(e,t){let{learningCoordinator:n}=await this.getServices(t);this.emitStream(t,{status:"analyzing",message:`Analyzing patterns${e?` for ${e}`:""}`});let r=await n.getPatternStats(e);if(!r.success)return{totalPatterns:0,byType:{},byDomain:{},topPatterns:[],avgConfidence:0,avgSuccessRate:0};let i=r.value,s=i.topPatterns.map(a=>({id:a.id,type:a.type,name:a.name,description:a.description,confidence:a.confidence,usageCount:a.usageCount,successRate:a.successRate}));return{totalPatterns:i.totalPatterns,byType:i.byType,byDomain:i.byDomain,topPatterns:s,avgConfidence:i.avgConfidence,avgSuccessRate:i.avgSuccessRate}}async executeDashboard(e){let{learningCoordinator:t,transferSpecialist:n}=await this.getServices(e);this.emitStream(e,{status:"aggregating",message:"Aggregating learning metrics"});let r=await t.getPatternStats(),i=await n.queryKnowledge({minRelevance:0,limit:1e3}),s=ze.lastNDays(1),a=["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","learning-optimization"],o=0,l=[];for(let v of a){let y=await t.mineExperiences(v,s);y.success&&(o+=y.value.experienceCount,y.value.experienceCount>0&&l.push({domain:v,successRate:y.value.successRate}))}l.sort((v,y)=>y.successRate-v.successRate);let c=l.slice(0,3).map(v=>v.domain),d=r.success?r.value.totalPatterns:0,m=r.success?r.value.avgSuccessRate:0,p=m,g=[],h=new Date;for(let v=6;v>=0;v--){let y=new Date(h.getTime()-v*24*60*60*1e3),C=new Date(y.getTime()+1440*60*1e3),b=ze.create(y,C),E=0;for(let S of a.slice(0,3)){let T=await t.mineExperiences(S,b);T.success&&(E+=T.value.patterns.length)}g.push({timestamp:y.toISOString(),metric:"patterns-learned",value:E})}let f=[];return d>=100&&f.push({name:`Reached ${Math.floor(d/50)*50} patterns`,achievedAt:new Date(h.getTime()-2880*60*1e3).toISOString(),domain:"learning-optimization"}),m>=.8&&f.push({name:`${Math.round(m*100)}% pattern success rate`,achievedAt:new Date(h.getTime()-7200*60*1e3).toISOString(),domain:c[0]||"learning-optimization"}),{overallLearningRate:p,totalPatterns:d,totalKnowledge:i.success?i.value.length:0,experiencesLast24h:o,topPerformingDomains:c.length>0?c:["test-generation"],learningTrend:g,recentMilestones:f}}},pc={type:"object",properties:{action:{type:"string",description:"Learning action to perform",enum:["learn","optimize","transfer","patterns","dashboard"]},domain:{type:"string",description:"Source domain for learning/optimization",enum:["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","requirements-validation","code-intelligence","security-compliance","contract-testing","visual-accessibility","chaos-resilience","learning-optimization"]},experienceIds:{type:"array",description:"Specific experience IDs to learn from",items:{type:"string",description:"Experience ID"}},targetDomain:{type:"string",description:"Target domain for knowledge transfer"},objective:{type:"object",description:"Optimization objective",properties:{metric:{type:"string",description:"Metric to optimize"},direction:{type:"string",description:"maximize or minimize",enum:["maximize","minimize"]},constraints:{type:"array",description:"Optimization constraints",items:{type:"object",description:"Constraint"}}}}},required:["action"]};k();var gc={type:"object",properties:{action:{type:"string",enum:["dream","insights","apply","history","status"],description:"Action to perform: dream (run cycle), insights (view pending), apply (create pattern), history (view past), status (current state)"},durationMs:{type:"number",description:"Duration of dream cycle in milliseconds (default: 30000, max: 60000)",default:3e4},minPatterns:{type:"number",description:"Minimum patterns required to start dreaming (default: 10)",default:10},insightId:{type:"string",description:"Insight ID to apply (required for apply action)"},limit:{type:"number",description:"Maximum results to return (default: 20)",default:20},loadFromReasoningBank:{type:"boolean",description:"Load patterns from ReasoningBank before dreaming (default: true)",default:!0}},required:["action"]},We=class extends x{config={name:"qe/learning/dream",description:"Trigger dream cycles for pattern discovery. Dreams find novel associations between patterns through spreading activation, generating actionable insights.",domain:"learning-optimization",schema:gc,streaming:!1,timeout:12e4};engine=null;engineConfig=null;async getEngine(e){return this.engine&&e&&!this.configsEqual(this.engineConfig,e)&&this.engine&&(await this.engine.close().catch(()=>{}),this.engine=null,this.engineConfig=null),this.engine||(this.engine=Vr(e),this.engineConfig=e||null,await this.engine.initialize()),this.engine}configsEqual(e,t){return e===t?!0:!e||!t?!1:e.maxDurationMs===t.maxDurationMs&&e.minConceptsRequired===t.minConceptsRequired}async loadPatternsFromReasoningBank(e){try{let t=await F(),n=ht(t);await n.initialize();try{let{getSharedRvfDualWriter:a}=await import("./shared-rvf-dual-writer-27L4R5WK.js"),o=await a();o&&n.setRvfDualWriter(o)}catch(a){process.env.DEBUG&&this.logger.info("RVF wiring skipped",{error:String(a)})}let r=await n.searchPatterns("",{limit:100,minConfidence:.3});if(!r.success||!r.value.length)return this.logger.info("No patterns found in ReasoningBank to load"),0;let i=r.value.map(a=>({id:a.pattern.id,name:a.pattern.name,description:a.pattern.description||`${a.pattern.patternType} pattern`,domain:a.pattern.qeDomain||"learning-optimization",patternType:a.pattern.patternType,confidence:a.pattern.confidence,successRate:a.pattern.successRate||.5})),s=await e.loadPatternsAsConcepts(i);return this.logger.info(`Loaded ${s} patterns as concepts from ReasoningBank`),s}catch(t){return this.logger.warn("Failed to load patterns from ReasoningBank",{error:String(t)}),0}}async execute(e,t){let{action:n}=e;try{switch(n){case"dream":return this.runDreamCycle(e,t);case"insights":return this.getPendingInsights(e,t);case"apply":return this.applyInsight(e,t);case"history":return this.getDreamHistory(e,t);case"status":return this.getDreamStatus(e,t);default:return{success:!1,error:`Unknown action: ${n}`,data:{action:n,success:!1,error:`Unknown action: ${n}`}}}}catch(r){let i=w(r);return{success:!1,error:i,data:{action:n,success:!1,error:i}}}}async runDreamCycle(e,t){let n=Math.min(e.durationMs||3e4,6e4),r=e.minPatterns||10,i=e.loadFromReasoningBank!==!1;this.logger.info(`Starting dream cycle (${n}ms, min: ${r} patterns)`);let s=await this.getEngine({maxDurationMs:n,minConceptsRequired:r});if(i){let c=await this.loadPatternsFromReasoningBank(s);this.logger.info(`Loaded ${c} patterns from ReasoningBank`)}let a=await s.dream(n),o={cycleId:a.cycle.id,status:a.cycle.status,durationMs:a.cycle.durationMs||0,conceptsProcessed:a.cycle.conceptsProcessed,associationsFound:a.cycle.associationsFound,insightsGenerated:a.cycle.insightsGenerated,activationStats:a.activationStats,patternsCreated:a.patternsCreated},l=a.insights.map(c=>({id:c.id,type:c.type,description:c.description,noveltyScore:c.noveltyScore,confidenceScore:c.confidenceScore,actionable:c.actionable,applied:c.applied||!1,suggestedAction:c.suggestedAction,createdAt:c.createdAt?.toISOString()||new Date().toISOString()}));return this.logger.info(`Dream cycle complete: ${a.cycle.insightsGenerated} insights, ${a.cycle.associationsFound} associations found`),{success:!0,data:{action:"dream",success:!0,dreamResult:o,insights:l}}}async getPendingInsights(e,t){let n=e.limit||20;return{success:!0,data:{action:"insights",success:!0,insights:(await(await this.getEngine()).getPendingInsights(n)).map(a=>({id:a.id,type:a.type,description:a.description,noveltyScore:a.noveltyScore,confidenceScore:a.confidenceScore,actionable:a.actionable,applied:a.applied||!1,suggestedAction:a.suggestedAction,createdAt:a.createdAt?.toISOString()||new Date().toISOString()}))}}}async applyInsight(e,t){if(!e.insightId)return{success:!1,error:"insightId is required for apply action",data:{action:"apply",success:!1,error:"insightId is required for apply action"}};try{let n=await this.getEngine(),i=(await n.getPendingInsights(100)).find(m=>m.id===e.insightId);if(!i)return{success:!1,error:`Insight not found or already applied: ${e.insightId}`,data:{action:"apply",success:!1,error:`Insight not found or already applied: ${e.insightId}`}};if(!i.actionable)return{success:!1,error:"Insight is not actionable",data:{action:"apply",success:!1,error:"Insight is not actionable"}};let s=await F(),a=ht(s);await a.initialize();try{let{getSharedRvfDualWriter:m}=await import("./shared-rvf-dual-writer-27L4R5WK.js"),p=await m();p&&a.setRvfDualWriter(p)}catch(m){process.env.DEBUG&&this.logger.info("RVF wiring skipped",{error:String(m)})}let o=this.mapInsightTypeToPatternType(i.type),l=await a.storePattern({patternType:o,name:`Dream Insight: ${i.type}`,description:`${i.description} (confidence: ${i.confidenceScore.toFixed(2)})`,template:{type:"workflow",content:i.suggestedAction||i.description,variables:[]},context:{tags:["dream-generated",i.type,...i.sourceConcepts.slice(0,3)],complexity:"medium"}});if(!l.success){let m=l.error?.message||"Unknown error";return{success:!1,error:`Failed to create pattern: ${m}`,data:{action:"apply",success:!1,error:`Failed to create pattern: ${m}`}}}let c=l.value.id;return await n.applyInsight(e.insightId),this.logger.info(`Applied insight ${e.insightId} \u2192 REAL pattern ${c} in ReasoningBank`),{success:!0,data:{action:"apply",success:!0,applyResult:{insightId:e.insightId,success:!0,patternId:c}}}}catch(n){let r=w(n);return{success:!1,error:r,data:{action:"apply",success:!1,error:r}}}}mapInsightTypeToPatternType(e){return{"cross-domain":"coverage-strategy","novel-path":"test-template",cluster:"refactor-safe","high-activation":"assertion-pattern",bridge:"mock-pattern"}[e]||"test-template"}async getDreamHistory(e,t){let n=e.limit||20;return{success:!0,data:{action:"history",success:!0,history:(await(await this.getEngine()).getDreamHistory(n)).map(a=>({id:a.id,startTime:a.startTime.toISOString(),endTime:a.endTime?.toISOString(),durationMs:a.durationMs,status:a.status,conceptsProcessed:a.conceptsProcessed,associationsFound:a.associationsFound,insightsGenerated:a.insightsGenerated}))}}}async getDreamStatus(e,t){let n=await this.getEngine(),r=n.isDreaming(),i=n.getCurrentCycle(),s=await n.getDreamHistory(100),a=await n.getPendingInsights(100),o=s.reduce((d,m)=>d+m.insightsGenerated,0),l=s[0];return{success:!0,data:{action:"status",success:!0,status:{isDreaming:r,currentCycle:i?{id:i.id,startTime:i.startTime.toISOString(),endTime:i.endTime?.toISOString(),durationMs:i.durationMs,status:i.status,conceptsProcessed:i.conceptsProcessed,associationsFound:i.associationsFound,insightsGenerated:i.insightsGenerated}:void 0,totalCycles:s.length,totalInsights:o,pendingInsights:a.length,lastDreamTime:l?.startTime.toISOString()}}}}resetInstanceCache(){this.engine&&(this.engine.close().catch(console.error),this.engine=null)}};k();var nn=class extends x{config={name:"qe/analysis/token_usage",description:"Analyze token consumption patterns and identify optimization opportunities across agents and domains.",domain:"learning-optimization",schema:hc,streaming:!1,timeout:3e4};async execute(e,t){let{operation:n,timeframe:r,agentId:i,domain:s}=e;try{if(this.isAborted(t))return{success:!1,error:"Operation aborted"};let a;switch(n){case"session":a=this.getSessionUsage(r);break;case"agent":a=this.getAgentUsage(i,r);break;case"domain":a=this.getDomainUsage(s,r);break;case"task":a=this.getTaskUsage(r);break;case"efficiency":a=this.getEfficiencyReport(r);break;case"dashboard":return{success:!0,data:{operation:"dashboard",timeframe:r||"all",summary:{totalTokens:0,totalCost:"$0.00",tokensSaved:0,savingsPercentage:0},optimization:{patternsReused:0,cacheHits:0,earlyExits:0,recommendations:[Zr()]}}};default:return{success:!1,error:`Unknown operation: ${n}`}}return{success:!0,data:a}}catch(a){return{success:!1,error:`Token usage analysis failed: ${w(a)}`}}}getSessionUsage(e){let t=Y.getSessionSummary(e),n={};for(let[i,s]of t.byAgent)n[i]={tokens:s.totalTokens,cost:B(s.totalCost),tasks:s.tasksExecuted};let r={};for(let[i,s]of t.byDomain)r[i]={tokens:s.totalTokens,cost:B(s.estimatedCostUsd||0)};return{operation:"session",timeframe:e||"all",summary:{totalTokens:t.totalUsage.totalTokens,totalCost:B(t.totalUsage.estimatedCostUsd||0),tokensSaved:t.optimizationStats.tokensSaved,savingsPercentage:t.optimizationStats.savingsPercentage},breakdown:{byAgent:Object.keys(n).length>0?n:void 0,byDomain:Object.keys(r).length>0?r:void 0},optimization:{patternsReused:t.optimizationStats.patternsReused,cacheHits:t.optimizationStats.cacheHits,earlyExits:t.optimizationStats.earlyExits,recommendations:this.generateSessionRecommendations(t)}}}getAgentUsage(e,t){let n=Y.getAgentMetrics(e,t),r=Y.getSessionSummary(t);if(e&&!Array.isArray(n)){let d=n,m=d.tasksExecuted>0?d.patternsReused/d.tasksExecuted:0;return{operation:"agent",timeframe:t||"all",summary:{totalTokens:d.totalTokens,totalCost:B(d.totalCost),tokensSaved:d.estimatedTokensSaved,savingsPercentage:this.calculateSavingsPercentage(d.totalTokens,d.estimatedTokensSaved)},optimization:{patternsReused:d.patternsReused,cacheHits:r.optimizationStats.cacheHits,earlyExits:r.optimizationStats.earlyExits,recommendations:this.generateAgentRecommendations(d)},details:{agentMetrics:{agentId:d.agentId,totalInputTokens:d.totalInputTokens,totalOutputTokens:d.totalOutputTokens,totalTokens:d.totalTokens,totalCost:B(d.totalCost),tasksExecuted:d.tasksExecuted,patternsReused:d.patternsReused,tokensSaved:d.estimatedTokensSaved,efficiency:Math.round(m*100)}}}}let i=Array.isArray(n)?n:[n],s={},a=0,o=0,l=0,c=0;for(let d of i)s[d.agentId]={tokens:d.totalTokens,cost:B(d.totalCost),tasks:d.tasksExecuted},a+=d.totalTokens,o+=d.totalCost,l+=d.estimatedTokensSaved,c+=d.patternsReused;return{operation:"agent",timeframe:t||"all",summary:{totalTokens:a,totalCost:B(o),tokensSaved:l,savingsPercentage:this.calculateSavingsPercentage(a,l)},breakdown:{byAgent:Object.keys(s).length>0?s:void 0},optimization:{patternsReused:c,cacheHits:r.optimizationStats.cacheHits,earlyExits:r.optimizationStats.earlyExits,recommendations:this.generateMultiAgentRecommendations(i)}}}getDomainUsage(e,t){let n=Y.getDomainMetrics(e,t),r=Y.getSessionSummary(t);if(e&&!(n instanceof Map)){let l=n;return{operation:"domain",timeframe:t||"all",summary:{totalTokens:l.totalTokens,totalCost:B(l.estimatedCostUsd||0),tokensSaved:r.optimizationStats.tokensSaved,savingsPercentage:r.optimizationStats.savingsPercentage},optimization:{patternsReused:r.optimizationStats.patternsReused,cacheHits:r.optimizationStats.cacheHits,earlyExits:r.optimizationStats.earlyExits,recommendations:this.generateDomainRecommendations(e,l)},details:{domainMetrics:{domain:e,inputTokens:l.inputTokens,outputTokens:l.outputTokens,totalTokens:l.totalTokens,cost:B(l.estimatedCostUsd||0)}}}}let i=n instanceof Map?n:new Map,s={},a=0,o=0;for(let[l,c]of i)s[l]={tokens:c.totalTokens,cost:B(c.estimatedCostUsd||0)},a+=c.totalTokens,o+=c.estimatedCostUsd||0;return{operation:"domain",timeframe:t||"all",summary:{totalTokens:a,totalCost:B(o),tokensSaved:r.optimizationStats.tokensSaved,savingsPercentage:r.optimizationStats.savingsPercentage},breakdown:{byDomain:Object.keys(s).length>0?s:void 0},optimization:{patternsReused:r.optimizationStats.patternsReused,cacheHits:r.optimizationStats.cacheHits,earlyExits:r.optimizationStats.earlyExits,recommendations:this.generateMultiDomainRecommendations(i)}}}getTaskUsage(e){let t=Y.getTaskMetrics(e),n=Y.getSessionSummary(e),r=t.slice(-100).map(i=>({taskId:i.taskId,agentId:i.agentId,domain:i.domain,operation:i.operation,tokens:i.usage.totalTokens,cost:B(i.usage.estimatedCostUsd||0),patternReused:i.patternReused,tokensSaved:i.tokensSaved||0,timestamp:new Date(i.timestamp).toISOString()}));return{operation:"task",timeframe:e||"all",summary:{totalTokens:n.totalUsage.totalTokens,totalCost:B(n.totalUsage.estimatedCostUsd||0),tokensSaved:n.optimizationStats.tokensSaved,savingsPercentage:n.optimizationStats.savingsPercentage},optimization:{patternsReused:n.optimizationStats.patternsReused,cacheHits:n.optimizationStats.cacheHits,earlyExits:n.optimizationStats.earlyExits,recommendations:[`${t.length} tasks analyzed in timeframe`]},details:{taskMetrics:r}}}getEfficiencyReport(e){let t=Y.getEfficiencyReport(e),n=Y.getSessionSummary(e);return{operation:"efficiency",timeframe:e||"all",summary:{totalTokens:t.totalTokensUsed,totalCost:B(t.totalTokensUsed*3e-6+t.totalTokensUsed*15e-6),tokensSaved:t.totalTokensSaved,savingsPercentage:t.savingsPercentage},optimization:{patternsReused:n.optimizationStats.patternsReused,cacheHits:n.optimizationStats.cacheHits,earlyExits:n.optimizationStats.earlyExits,recommendations:t.recommendations}}}generateSessionRecommendations(e){let t=[];if(e.totalUsage.totalTokens===0)return["No token usage recorded yet. Start executing tasks to track consumption."];let{patternsReused:n,cacheHits:r,earlyExits:i,savingsPercentage:s}=e.optimizationStats;return s<10&&t.push("Token savings below 10%. Enable pattern reuse and caching for better efficiency."),n===0&&e.byAgent.size>0&&t.push("No patterns reused. Consider enabling the pattern store for similar tasks."),r===0&&e.totalUsage.totalTokens>1e4&&t.push("No cache hits detected. Enable response caching to reduce API calls."),i===0&&e.byAgent.size>1&&t.push("Early exit optimization not used. Enable high-confidence pattern matching."),s>25&&t.push(`Excellent token efficiency! ${s.toFixed(1)}% savings achieved.`),t.length>0?t:["Token usage is within normal parameters."]}generateAgentRecommendations(e){let t=[];if(e.tasksExecuted===0)return["No tasks executed by this agent yet."];e.patternsReused/e.tasksExecuted<.1&&t.push("Low pattern reuse rate. Consider caching successful patterns.");let r=e.totalTokens/e.tasksExecuted;return r>5e3&&t.push(`High average tokens per task (${Math.round(r)}). Consider optimizing prompts.`),e.totalOutputTokens>e.totalInputTokens*2&&t.push("High output-to-input ratio. Request more concise responses."),t.length>0?t:["Agent token usage is efficient."]}generateMultiAgentRecommendations(e){let t=[];if(e.length===0)return["No agent data available."];let n=[...e].sort((s,a)=>a.totalTokens-s.totalTokens);n[0].totalTokens>0&&t.push(`Highest consumer: ${n[0].agentId} (${n[0].totalTokens.toLocaleString()} tokens)`);let r=e.reduce((s,a)=>s+a.totalTokens,0);return n[0].totalTokens/(r||1)>.5&&e.length>1&&t.push("Token usage imbalanced. Consider distributing workload across agents."),t}generateDomainRecommendations(e,t){let n=[];return t.totalTokens===0?[`No token usage recorded for ${e}.`]:(e==="test-generation"&&t.totalTokens>1e4&&n.push("Test generation consuming significant tokens. Consider batching test requests."),e==="code-intelligence"&&t.outputTokens>t.inputTokens*3&&n.push("Code intelligence generating verbose output. Consider summary-only mode."),n.length>0?n:[`${e} token usage is normal.`])}generateMultiDomainRecommendations(e){let t=[];if(e.size===0)return["No domain data available."];let n=Array.from(e.entries()).sort((r,i)=>i[1].totalTokens-r[1].totalTokens);return n[0][1].totalTokens>0&&t.push(`Highest consuming domain: ${n[0][0]} (${n[0][1].totalTokens.toLocaleString()} tokens)`),t}calculateSavingsPercentage(e,t){let n=e+t;return n===0?0:Math.round(t/n*1e4)/100}},hc={type:"object",properties:{operation:{type:"string",description:"Type of analysis to perform",enum:["session","agent","domain","task","efficiency","dashboard"]},timeframe:{type:"string",description:"Time period to analyze",enum:["1h","24h","7d","30d"]},agentId:{type:"string",description:"Specific agent ID to analyze (for agent operation)"},domain:{type:"string",description:"Specific domain to analyze (for domain operation)",enum:["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","requirements-validation","code-intelligence","security-compliance","contract-testing","visual-accessibility","chaos-resilience","learning-optimization"]}},required:["operation"]};k();var Ke={coverage:{line:0,branch:0,function:0,target:80,measured:!1},quality:{testsPassing:0,totalTests:0,securityScore:100,performanceScore:100},fleet:{activeAgents:0,availableAgents:[],maxAgents:8},resources:{timeRemaining:3600,memoryAvailable:4096,parallelSlots:4},context:{environment:"development",riskLevel:"medium"},patterns:{available:0,reusable:0}};var fc=[{name:"measure-coverage",description:"Run coverage analysis on the codebase to determine current coverage metrics",agentType:"qe-coverage-specialist",preconditions:{"coverage.measured":!1},effects:{"coverage.measured":!0},cost:2,estimatedDurationMs:3e4,successRate:.95,category:"coverage",qeDomain:"coverage-analysis"},{name:"analyze-coverage-gaps",description:"Identify uncovered code paths and prioritize them by risk and complexity",agentType:"qe-gap-detector",preconditions:{"coverage.measured":!0},effects:{"coverage.gapsIdentified":!0},cost:1.5,estimatedDurationMs:15e3,successRate:.9,category:"coverage",qeDomain:"coverage-analysis"},{name:"generate-coverage-tests",description:"Generate tests targeting identified coverage gaps using AI-powered analysis",agentType:"qe-test-generator",preconditions:{"coverage.gapsIdentified":!0},effects:{"coverage.line":{delta:10}},cost:4,estimatedDurationMs:6e4,successRate:.8,category:"coverage",qeDomain:"test-generation"},{name:"run-mutation-testing",description:"Run mutation testing to validate test effectiveness and find weak spots",agentType:"qe-mutation-tester",preconditions:{"coverage.line":{min:60}},effects:{"quality.mutationScore":{set:!0}},cost:5,estimatedDurationMs:12e4,successRate:.85,category:"coverage",qeDomain:"coverage-analysis"},{name:"prioritize-uncovered-paths",description:"Use sublinear O(log n) analysis to identify highest-risk uncovered paths",agentType:"qe-coverage-specialist",preconditions:{"coverage.gapsIdentified":!0},effects:{"coverage.riskPrioritized":!0},cost:1,estimatedDurationMs:1e4,successRate:.92,category:"coverage",qeDomain:"coverage-analysis"},{name:"generate-branch-tests",description:"Generate tests specifically targeting branch coverage improvements",agentType:"qe-test-generator",preconditions:{"coverage.measured":!0,"coverage.branch":{max:70}},effects:{"coverage.branch":{delta:8}},cost:3.5,estimatedDurationMs:45e3,successRate:.78,category:"coverage",qeDomain:"test-generation"}],yc=[{name:"run-unit-tests",description:"Execute unit test suite with parallel execution",agentType:"qe-test-executor",preconditions:{},effects:{"quality.unitTestsRun":!0},cost:1,estimatedDurationMs:2e4,successRate:.95,category:"test",qeDomain:"test-execution"},{name:"run-integration-tests",description:"Execute integration test suite with real database connections",agentType:"qe-test-executor",preconditions:{"quality.unitTestsRun":!0},effects:{"quality.integrationTestsRun":!0},cost:2.5,estimatedDurationMs:45e3,successRate:.85,category:"test",qeDomain:"test-execution"},{name:"run-e2e-tests",description:"Execute end-to-end tests using Playwright or Cypress",agentType:"qe-e2e-tester",preconditions:{"quality.integrationTestsRun":!0},effects:{"quality.e2eTestsRun":!0},cost:4,estimatedDurationMs:9e4,successRate:.8,category:"test",qeDomain:"test-execution"},{name:"fix-failing-tests",description:"Analyze and fix failing tests based on error messages and stack traces",agentType:"qe-tdd-specialist",preconditions:{"quality.testsPassing":{max:90}},effects:{"quality.testsPassing":{delta:10}},cost:3,estimatedDurationMs:3e4,successRate:.75,category:"test",qeDomain:"test-generation"},{name:"fix-flaky-tests",description:"Identify and stabilize flaky tests by analyzing timing and async issues",agentType:"qe-flaky-hunter",preconditions:{"quality.flakyTests":{min:1}},effects:{"quality.flakyTests":{delta:-3}},cost:4,estimatedDurationMs:45e3,successRate:.7,category:"test",qeDomain:"test-execution"},{name:"generate-property-tests",description:"Generate property-based tests using fast-check or similar library",agentType:"qe-test-generator",preconditions:{"quality.unitTestsRun":!0},effects:{"quality.propertyTestsGenerated":!0},cost:3.5,estimatedDurationMs:4e4,successRate:.82,category:"test",qeDomain:"test-generation"},{name:"run-contract-tests",description:"Execute consumer-driven contract tests using Pact or similar",agentType:"qe-contract-tester",preconditions:{"context.hasApiContracts":!0},effects:{"quality.contractTestsRun":!0},cost:2,estimatedDurationMs:25e3,successRate:.88,category:"test",qeDomain:"contract-testing"}],vc=[{name:"security-scan",description:"Run comprehensive security scan using SAST and dependency analysis",agentType:"qe-security-scanner",preconditions:{},effects:{"quality.securityScanned":!0},cost:2,estimatedDurationMs:3e4,successRate:.95,category:"security",qeDomain:"security-compliance"},{name:"fix-vulnerabilities",description:"Remediate identified security vulnerabilities and update dependencies",agentType:"qe-security-auditor",preconditions:{"quality.securityScanned":!0,"quality.vulnerabilities":{min:1}},effects:{"quality.vulnerabilities":{delta:-5},"quality.securityScore":{delta:10}},cost:5,estimatedDurationMs:6e4,successRate:.7,category:"security",qeDomain:"security-compliance"},{name:"owasp-audit",description:"Perform OWASP Top 10 security audit on the application",agentType:"qe-security-auditor",preconditions:{"quality.securityScanned":!0},effects:{"quality.owaspCompliant":!0},cost:3,estimatedDurationMs:45e3,successRate:.85,category:"security",qeDomain:"security-compliance"},{name:"scan-secrets",description:"Scan codebase for hardcoded secrets and credentials",agentType:"qe-security-scanner",preconditions:{},effects:{"quality.secretsScanned":!0},cost:1,estimatedDurationMs:15e3,successRate:.98,category:"security",qeDomain:"security-compliance"},{name:"run-dast",description:"Run dynamic application security testing against running application",agentType:"qe-security-auditor",preconditions:{"context.environment":"staging"},effects:{"quality.dastCompleted":!0},cost:4.5,estimatedDurationMs:12e4,successRate:.8,category:"security",qeDomain:"security-compliance"}],bc=[{name:"run-benchmarks",description:"Execute performance benchmarks to establish baseline metrics",agentType:"qe-performance-tester",preconditions:{},effects:{"quality.benchmarked":!0},cost:2,estimatedDurationMs:45e3,successRate:.9,category:"performance",qeDomain:"chaos-resilience"},{name:"load-test",description:"Run load testing with simulated concurrent traffic",agentType:"qe-load-tester",preconditions:{"context.environment":"staging"},effects:{"quality.loadTested":!0},cost:3.5,estimatedDurationMs:12e4,successRate:.85,category:"performance",qeDomain:"chaos-resilience"},{name:"stress-test",description:"Run stress testing to find breaking points and system limits",agentType:"qe-chaos-engineer",preconditions:{"context.environment":"staging","quality.loadTested":!0},effects:{"quality.stressTested":!0},cost:4,estimatedDurationMs:9e4,successRate:.8,category:"performance",qeDomain:"chaos-resilience"},{name:"profile-memory",description:"Profile memory usage and identify memory leaks",agentType:"qe-performance-tester",preconditions:{"quality.benchmarked":!0},effects:{"quality.memoryProfiled":!0},cost:2.5,estimatedDurationMs:6e4,successRate:.88,category:"performance",qeDomain:"chaos-resilience"},{name:"optimize-slow-tests",description:"Identify and optimize slow-running tests to improve CI/CD speed",agentType:"qe-performance-tester",preconditions:{"quality.unitTestsRun":!0},effects:{"quality.testsOptimized":!0},cost:2,estimatedDurationMs:3e4,successRate:.82,category:"performance",qeDomain:"test-execution"}],Cc=[{name:"analyze-complexity",description:"Measure cyclomatic and cognitive complexity of codebase",agentType:"code-analyzer",preconditions:{},effects:{"quality.complexityAnalyzed":!0},cost:1,estimatedDurationMs:15e3,successRate:.95,category:"analysis",qeDomain:"code-intelligence"},{name:"detect-code-smells",description:"Identify code smells and anti-patterns using static analysis",agentType:"code-analyzer",preconditions:{},effects:{"quality.smellsDetected":!0},cost:1.5,estimatedDurationMs:2e4,successRate:.9,category:"analysis",qeDomain:"code-intelligence"},{name:"analyze-dependencies",description:"Analyze dependency graph and identify circular or outdated dependencies",agentType:"code-analyzer",preconditions:{},effects:{"quality.dependenciesAnalyzed":!0},cost:1,estimatedDurationMs:15e3,successRate:.92,category:"analysis",qeDomain:"code-intelligence"},{name:"measure-technical-debt",description:"Calculate technical debt metrics and generate remediation plan",agentType:"code-analyzer",preconditions:{"quality.complexityAnalyzed":!0,"quality.smellsDetected":!0},effects:{"quality.technicalDebtMeasured":!0},cost:2,estimatedDurationMs:25e3,successRate:.88,category:"analysis",qeDomain:"code-intelligence"},{name:"build-knowledge-graph",description:"Build semantic knowledge graph of codebase for intelligent context retrieval",agentType:"qe-intelligence-builder",preconditions:{"quality.dependenciesAnalyzed":!0},effects:{"quality.knowledgeGraphBuilt":!0},cost:3,estimatedDurationMs:6e4,successRate:.85,category:"analysis",qeDomain:"code-intelligence"}],Tc=[{name:"spawn-test-agent",description:"Spawn additional test execution agent for parallel work",agentType:"queen-coordinator",preconditions:{"fleet.activeAgents":{max:10}},effects:{"fleet.activeAgents":{delta:1}},cost:.5,estimatedDurationMs:5e3,successRate:.95,category:"fleet",qeDomain:"test-execution"},{name:"optimize-fleet-topology",description:"Reconfigure fleet topology for optimal task distribution",agentType:"queen-coordinator",preconditions:{"fleet.activeAgents":{min:3}},effects:{"fleet.efficiency":{delta:15}},cost:1,estimatedDurationMs:1e4,successRate:.85,category:"fleet"},{name:"scale-down-fleet",description:"Reduce fleet size to conserve resources during low-activity periods",agentType:"queen-coordinator",preconditions:{"fleet.activeAgents":{min:5}},effects:{"fleet.activeAgents":{delta:-2}},cost:.3,estimatedDurationMs:3e3,successRate:.98,category:"fleet"},{name:"spawn-specialist-agent",description:"Spawn a specialized agent for specific domain work",agentType:"queen-coordinator",preconditions:{"fleet.activeAgents":{max:12},"context.specialistNeeded":!0},effects:{"fleet.activeAgents":{delta:1},"fleet.specialistAvailable":!0},cost:1,estimatedDurationMs:8e3,successRate:.9,category:"fleet"},{name:"rebalance-workload",description:"Redistribute tasks across agents based on current load",agentType:"queen-coordinator",preconditions:{"fleet.activeAgents":{min:2}},effects:{"fleet.workloadBalanced":!0},cost:.5,estimatedDurationMs:5e3,successRate:.92,category:"fleet"}],Sc=[{name:"generate-quality-report",description:"Generate comprehensive quality report combining all metrics",agentType:"qe-quality-gate",preconditions:{"coverage.measured":!0,"quality.unitTestsRun":!0},effects:{"quality.reported":!0},cost:1,estimatedDurationMs:1e4,successRate:.95,category:"quality",qeDomain:"quality-assessment"},{name:"enforce-quality-gate",description:"Check if all quality gates pass and report status",agentType:"qe-quality-gate",preconditions:{"quality.reported":!0},effects:{"quality.gatePassed":!0},cost:.5,estimatedDurationMs:5e3,successRate:.9,category:"quality",qeDomain:"quality-assessment"},{name:"validate-requirements",description:"Validate that tests cover all documented requirements",agentType:"qe-requirements-validator",preconditions:{"context.hasRequirements":!0},effects:{"quality.requirementsValidated":!0},cost:2,estimatedDurationMs:2e4,successRate:.88,category:"quality",qeDomain:"requirements-validation"},{name:"predict-defects",description:"Use ML-based defect prediction to identify high-risk code areas",agentType:"qe-defect-predictor",preconditions:{"quality.complexityAnalyzed":!0,"coverage.measured":!0},effects:{"quality.defectsPredicted":!0},cost:2.5,estimatedDurationMs:3e4,successRate:.82,category:"quality",qeDomain:"defect-intelligence"},{name:"generate-deployment-report",description:"Generate deployment readiness report with all quality metrics",agentType:"qe-quality-gate",preconditions:{"quality.gatePassed":!0,"quality.securityScanned":!0},effects:{"quality.deploymentReady":!0},cost:1.5,estimatedDurationMs:15e3,successRate:.9,category:"quality",qeDomain:"quality-assessment"}],Ec=[{name:"run-accessibility-audit",description:"Run WCAG 2.2 accessibility audit using axe-core or similar",agentType:"qe-accessibility-tester",preconditions:{"context.hasUI":!0},effects:{"quality.accessibilityAudited":!0},cost:2,estimatedDurationMs:3e4,successRate:.9,category:"quality",qeDomain:"visual-accessibility"},{name:"run-visual-regression",description:"Run visual regression testing with screenshot comparison",agentType:"qe-visual-tester",preconditions:{"context.hasUI":!0},effects:{"quality.visualRegressionRun":!0},cost:3,estimatedDurationMs:6e4,successRate:.85,category:"quality",qeDomain:"visual-accessibility"}],gs=[...fc,...yc,...vc,...bc,...Cc,...Tc,...Sc,...Ec];function wc(u){return`action-${u}`}function hs(u){return{...u,id:wc(u.name),executionCount:0}}function Xe(){return gs.map(hs)}var rn=[{name:"achieve-90-percent-coverage",description:"Reach 90% line coverage through targeted test generation",conditions:{"coverage.line":{min:90}},priority:1,qeDomain:"coverage-analysis"},{name:"all-tests-passing",description:"All tests green with 100% pass rate",conditions:{"quality.testsPassing":{min:100}},priority:1,qeDomain:"test-execution"},{name:"security-compliant",description:"Pass security audit with no critical vulnerabilities",conditions:{"quality.securityScanned":!0,"quality.vulnerabilities":{max:0}},priority:2,qeDomain:"security-compliance"},{name:"deployment-ready",description:"Ready for production deployment with all quality gates passed",conditions:{"coverage.line":{min:80},"quality.testsPassing":{min:100},"quality.securityScanned":!0,"quality.gatePassed":!0},priority:1},{name:"performance-validated",description:"Performance benchmarks and load tests completed successfully",conditions:{"quality.benchmarked":!0,"quality.loadTested":!0},priority:2,qeDomain:"chaos-resilience"},{name:"code-quality-excellent",description:"Excellent code quality with low complexity and no code smells",conditions:{"quality.complexityAnalyzed":!0,"quality.smellsDetected":!0,"quality.technicalDebtMeasured":!0},priority:3,qeDomain:"code-intelligence"},{name:"full-test-suite",description:"Complete test suite with unit, integration, and e2e tests",conditions:{"quality.unitTestsRun":!0,"quality.integrationTestsRun":!0,"quality.e2eTestsRun":!0},priority:2,qeDomain:"test-execution"},{name:"accessibility-compliant",description:"WCAG 2.2 compliant with visual regression coverage",conditions:{"quality.accessibilityAudited":!0,"quality.visualRegressionRun":!0},priority:2,qeDomain:"visual-accessibility"}];U();import{randomUUID as ge}from"crypto";var pr=class{data=[];cmp;constructor(e){this.cmp=e}get length(){return this.data.length}push(e){this.data.push(e),this.bubbleUp(this.data.length-1)}pop(){if(this.data.length===0)return;let e=this.data[0],t=this.data.pop();return this.data.length>0&&(this.data[0]=t,this.sinkDown(0)),e}bubbleUp(e){for(;e>0;){let t=e-1>>1;if(this.cmp(this.data[e],this.data[t])<0)[this.data[e],this.data[t]]=[this.data[t],this.data[e]],e=t;else break}}sinkDown(e){let t=this.data.length;for(;;){let n=e,r=2*e+1,i=2*e+2;if(r<t&&this.cmp(this.data[r],this.data[n])<0&&(n=r),i<t&&this.cmp(this.data[i],this.data[n])<0&&(n=i),n!==e)[this.data[e],this.data[n]]=[this.data[n],this.data[e]],e=n;else break}}},Rc=new Set(["__proto__","constructor","prototype"]),sn=class{db=null;persistence=null;actions=new Map;initialized=!1;enablePlanReuse=!0;constructor(){}ensureDb(){if(!this.db)throw new Error("GOAPPlanner not initialized - call initialize() first");return this.db}async initialize(){if(this.initialized)return;this.persistence=xr(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase(),this.ensureDb().prepare("SELECT COUNT(*) as count FROM goap_actions").get().count===0&&this.seedDefaultActions(),await this.loadActions(),this.initialized=!0,console.log(`[GOAPPlanner] Initialized: ${this.persistence.getDbPath()}`)}seedDefaultActions(){let e=Xe(),t=this.ensureDb(),n=t.prepare(`
|
|
662
662
|
INSERT INTO goap_actions (id, name, description, category, preconditions, effects, cost, qe_domain, agent_type)
|
|
663
663
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
664
664
|
`);for(let i of e){let s=`action-${Date.now()}-${ge().slice(0,8)}`;n.run(s,i.name,i.description,i.category,JSON.stringify(i.preconditions),JSON.stringify(i.effects),i.cost,i.qeDomain??null,i.agentType??null)}let r=t.prepare(`
|
|
@@ -694,7 +694,7 @@ Analyze the requirements above and return the complete QualityCriteriaAnalysis.`
|
|
|
694
694
|
`).run(i,a,e)}validatePlanForState(e,t){let n=this.cloneState(t);for(let r of e.actions){if(!this.meetsConditions(n,r.preconditions))return!1;n=this.applyAction(n,r)}return!0}hashGoalConditions(e){let t=this.sortObjectKeys(e);return JSON.stringify(t)}sortObjectKeys(e){return e===null||typeof e!="object"?e:Array.isArray(e)?e.map(t=>this.sortObjectKeys(t)):Object.keys(e).sort().reduce((t,n)=>(t[n]=this.sortObjectKeys(e[n]),t),{})}extractStateVector(e){return[e.coverage.line/100,e.coverage.branch/100,e.coverage.function/100,e.coverage.measured?1:0,e.quality.testsPassing/100,e.quality.securityScore/100,e.quality.performanceScore/100,Math.min(e.fleet.activeAgents/10,1),Math.min(e.resources.timeRemaining/3600,1),Math.min(e.resources.parallelSlots/8,1)]}async addGoal(e){await this.initialize();let t=`goal-${Date.now()}-${ge().slice(0,8)}`;return this.ensureDb().prepare(`
|
|
695
695
|
INSERT INTO goap_goals (id, name, description, conditions, priority, qe_domain)
|
|
696
696
|
VALUES (?, ?, ?, ?, ?, ?)
|
|
697
|
-
`).run(t,e.name,e.description??null,JSON.stringify(e.conditions),e.priority,e.qeDomain??null),t}async getGoals(){return await this.initialize(),this.ensureDb().prepare("SELECT * FROM goap_goals ORDER BY priority DESC").all().map(t=>({id:t.id,name:t.name,description:t.description??void 0,conditions:P(t.conditions),priority:t.priority,qeDomain:t.qe_domain}))}setPlanReuseEnabled(e){this.enablePlanReuse=e}isPlanReuseEnabled(){return this.enablePlanReuse}async getPlanReuseStats(){await this.initialize();let e=this.ensureDb(),t=e.prepare("SELECT COUNT(*) as count FROM goap_plan_signatures").get(),n=e.prepare("SELECT COUNT(*) as count FROM goap_plan_signatures WHERE usage_count > 0").get(),r=e.prepare("SELECT AVG(success_rate) as avg FROM goap_plan_signatures WHERE usage_count > 0").get();return{totalPlans:t.count,reusedPlans:n.count,reuseRate:t.count>0?n.count/t.count:0,avgSuccessRate:r.avg??0}}async close(){this.actions.clear(),this.db=null,this.persistence=null,this.initialized=!1}},mr=null;function he(){return mr||(mr=new sn),mr}ws();ve();ee();k();U();import{randomUUID as gr}from"crypto";var xc={maxRetries:2,stepTimeoutMs:6e4,replanOnFailure:!0,parallelExecution:!1,recordWorldState:!0,useUnified:!0},an=class{db;planner;spawner;config;currentExecution=null;initialized=!1;unifiedMemory=null;constructor(e,t,n,r){this.planner=e,this.spawner=t,this.config={...xc,...r},this.config.useUnified||(this.db=Rr(n??":memory:",{walMode:!1}),this.db.pragma("journal_mode = WAL"))}async initialize(){if(!this.initialized){if(this.config.useUnified)try{this.unifiedMemory=$(),await this.unifiedMemory.initialize(),this.db=this.unifiedMemory.getDatabase(),console.log(`[PlanExecutor] Using unified storage: ${this.unifiedMemory.getDbPath()}`)}catch(e){console.warn("[PlanExecutor] Failed to initialize unified storage, falling back to in-memory:",e),this.db=new(await import("./better-sqlite3-
|
|
697
|
+
`).run(t,e.name,e.description??null,JSON.stringify(e.conditions),e.priority,e.qeDomain??null),t}async getGoals(){return await this.initialize(),this.ensureDb().prepare("SELECT * FROM goap_goals ORDER BY priority DESC").all().map(t=>({id:t.id,name:t.name,description:t.description??void 0,conditions:P(t.conditions),priority:t.priority,qeDomain:t.qe_domain}))}setPlanReuseEnabled(e){this.enablePlanReuse=e}isPlanReuseEnabled(){return this.enablePlanReuse}async getPlanReuseStats(){await this.initialize();let e=this.ensureDb(),t=e.prepare("SELECT COUNT(*) as count FROM goap_plan_signatures").get(),n=e.prepare("SELECT COUNT(*) as count FROM goap_plan_signatures WHERE usage_count > 0").get(),r=e.prepare("SELECT AVG(success_rate) as avg FROM goap_plan_signatures WHERE usage_count > 0").get();return{totalPlans:t.count,reusedPlans:n.count,reuseRate:t.count>0?n.count/t.count:0,avgSuccessRate:r.avg??0}}async close(){this.actions.clear(),this.db=null,this.persistence=null,this.initialized=!1}},mr=null;function he(){return mr||(mr=new sn),mr}ws();ve();ee();k();U();import{randomUUID as gr}from"crypto";var xc={maxRetries:2,stepTimeoutMs:6e4,replanOnFailure:!0,parallelExecution:!1,recordWorldState:!0,useUnified:!0},an=class{db;planner;spawner;config;currentExecution=null;initialized=!1;unifiedMemory=null;constructor(e,t,n,r){this.planner=e,this.spawner=t,this.config={...xc,...r},this.config.useUnified||(this.db=Rr(n??":memory:",{walMode:!1}),this.db.pragma("journal_mode = WAL"))}async initialize(){if(!this.initialized){if(this.config.useUnified)try{this.unifiedMemory=$(),await this.unifiedMemory.initialize(),this.db=this.unifiedMemory.getDatabase(),console.log(`[PlanExecutor] Using unified storage: ${this.unifiedMemory.getDbPath()}`)}catch(e){console.warn("[PlanExecutor] Failed to initialize unified storage, falling back to in-memory:",e),this.db=new(await import("./better-sqlite3-UGOYRNXI.js")).default(":memory:"),this.db.pragma("journal_mode = WAL"),this.unifiedMemory=null,this.createTables()}else this.createTables();this.initialized=!0}}createTables(){this.db.exec(`
|
|
698
698
|
CREATE TABLE IF NOT EXISTS execution_results (
|
|
699
699
|
id TEXT PRIMARY KEY,
|
|
700
700
|
plan_id TEXT NOT NULL,
|