agentic-qe 3.10.2 → 3.10.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/.claude/skills/release/SKILL.md +10 -10
- package/.claude/skills/skills-manifest.json +1 -1
- package/CHANGELOG.md +88 -0
- package/assets/grammars/tree-sitter-c_sharp.wasm +0 -0
- package/assets/grammars/tree-sitter-java.wasm +0 -0
- package/assets/grammars/tree-sitter-javascript.wasm +0 -0
- package/assets/grammars/tree-sitter-python.wasm +0 -0
- package/assets/grammars/tree-sitter-rust.wasm +0 -0
- package/assets/grammars/tree-sitter-swift.wasm +0 -0
- package/assets/grammars/tree-sitter-tsx.wasm +0 -0
- package/assets/grammars/tree-sitter-typescript.wasm +0 -0
- package/assets/skills/skills-manifest.json +1 -1
- package/dist/agents/claim-verifier/claim-verifier-service.js +4 -2
- package/dist/agents/claim-verifier/verifiers/test-verifier.js +31 -23
- package/dist/agents/devils-advocate/agent.js +1 -1
- package/dist/cli/bundle.js +5 -5
- package/dist/cli/chunks/adapter-A62ETL5C.js +2 -0
- package/dist/cli/chunks/{agent-booster-wasm-DHSIPFTH.js → agent-booster-wasm-EJPDSWON.js} +2 -2
- package/dist/cli/chunks/{agent-handler-FPQVHGGT.js → agent-handler-2DZB7LGI.js} +2 -2
- package/dist/cli/chunks/{agent-memory-branch-OLOF5ZHV.js → agent-memory-branch-SSFYAVIK.js} +2 -2
- package/dist/cli/chunks/aqe-learning-engine-MTCRAV6N.js +2 -0
- package/dist/cli/chunks/audit-42XG5JFB.js +3 -0
- package/dist/cli/chunks/base-KKEBUHZC.js +2 -0
- package/dist/cli/chunks/{hnswlib-node-ZGSUMHDC.js → better-sqlite3-PX5JM3DG.js} +2 -2
- package/dist/cli/chunks/{brain-handler-ROZUHCOT.js → brain-handler-LFHX2TYP.js} +3 -3
- package/dist/cli/chunks/{branch-enumerator-VK7G4NKJ.js → branch-enumerator-AX7DKGV7.js} +2 -2
- package/dist/cli/chunks/{browser-Q2S75M2F.js → browser-4NYLZ7FA.js} +2 -2
- package/dist/cli/chunks/browser-workflow-XHYAJUB6.js +2 -0
- package/dist/cli/chunks/{chunk-XPCNUX2U.js → chunk-2B6ETC7C.js} +2 -2
- package/dist/cli/chunks/{chunk-YI6GNRQM.js → chunk-2G2PVVQG.js} +2 -2
- package/dist/cli/chunks/{chunk-2244IFZA.js → chunk-2L5VFVCG.js} +1 -1
- package/dist/cli/chunks/{chunk-EVCOCGVJ.js → chunk-2TYO4VZH.js} +4 -4
- package/dist/cli/chunks/{chunk-U3EUH6LX.js → chunk-3ISX5B77.js} +2 -2
- package/dist/cli/chunks/{chunk-WZJUMJ2S.js → chunk-3UGUX34A.js} +1 -1
- package/dist/cli/chunks/{chunk-6ZFHIKQG.js → chunk-4BX72XG4.js} +3 -3
- package/dist/cli/chunks/{chunk-UUFOHMUG.js → chunk-4FTLYIMW.js} +2 -2
- package/dist/cli/chunks/{chunk-XDU624HU.js → chunk-5FNNCVXR.js} +1 -1
- package/dist/cli/chunks/{chunk-7Z46RDDV.js → chunk-5Q3L4QEE.js} +3 -3
- package/dist/cli/chunks/{chunk-AH7FXNFE.js → chunk-5T2HDET6.js} +3 -3
- package/dist/cli/chunks/{chunk-24LUQICS.js → chunk-5T4J3IPG.js} +2 -2
- package/dist/cli/chunks/{chunk-HHCYSAH3.js → chunk-6OLHPWSN.js} +2 -2
- package/dist/cli/chunks/{chunk-5PRFFHFV.js → chunk-6SCIX2W2.js} +2 -2
- package/dist/cli/chunks/{chunk-2JDLQWSV.js → chunk-6WF2MOQB.js} +2 -2
- package/dist/cli/chunks/{chunk-YNNOY3XN.js → chunk-7BQXEYRV.js} +2 -2
- package/dist/cli/chunks/{chunk-MMIQ5DMA.js → chunk-7VO5IEJ2.js} +2 -2
- package/dist/cli/chunks/{chunk-XDSA7YUQ.js → chunk-AIBE3J4A.js} +1 -1
- package/dist/cli/chunks/{chunk-AV7KYE5P.js → chunk-AMW27FSS.js} +5 -5
- package/dist/cli/chunks/{chunk-22D6VBPD.js → chunk-AZJYDM2K.js} +2 -2
- package/dist/cli/chunks/{chunk-PYIHZXCI.js → chunk-B6CT4ILU.js} +4 -4
- package/dist/cli/chunks/{chunk-ZK2BH23O.js → chunk-BEFRQOLH.js} +2 -2
- package/dist/cli/chunks/{chunk-CIRPP7RQ.js → chunk-C2446H7G.js} +2 -2
- package/dist/cli/chunks/{chunk-ON4D4TJ4.js → chunk-D7IWGQTW.js} +2 -2
- package/dist/cli/chunks/{chunk-6KSCXPPL.js → chunk-D7PI4CYZ.js} +2 -2
- package/dist/cli/chunks/{chunk-BQCSCAUC.js → chunk-DAIM72HV.js} +2 -2
- package/dist/cli/chunks/{chunk-XMJTTF5N.js → chunk-DPKECIKN.js} +3 -3
- package/dist/cli/chunks/{chunk-DZZEHPSJ.js → chunk-E6CGBOZY.js} +3 -3
- package/dist/cli/chunks/{chunk-OIRZJCZY.js → chunk-EGTOSQZK.js} +2 -2
- package/dist/cli/chunks/{chunk-WDMPJ2M2.js → chunk-EMZ3DXMG.js} +2 -2
- package/dist/cli/chunks/{chunk-QBRHKTFT.js → chunk-EWI37TJA.js} +1 -1
- package/dist/cli/chunks/{chunk-A5RMQG4N.js → chunk-F34OO2Q7.js} +3 -3
- package/dist/cli/chunks/{chunk-7SWD3D6Y.js → chunk-F6QPAVWS.js} +2 -2
- package/dist/cli/chunks/chunk-F77X5DAF.js +2 -0
- package/dist/cli/chunks/{chunk-Y63MBMOV.js → chunk-FDFJJFQT.js} +2 -2
- package/dist/cli/chunks/{chunk-YWZHMXTO.js → chunk-FQ7I4JBQ.js} +2 -2
- package/dist/cli/chunks/{chunk-S3ZO7JXS.js → chunk-G5FPWH5O.js} +4 -4
- package/dist/cli/chunks/{chunk-QSE67XJO.js → chunk-GDMH7NPV.js} +2 -2
- package/dist/cli/chunks/{chunk-MEY43PIQ.js → chunk-GILL32E2.js} +2 -2
- package/dist/cli/chunks/{chunk-LQTWPSYL.js → chunk-GLMDRGJD.js} +1 -1
- package/dist/cli/chunks/{chunk-MNV3E5KY.js → chunk-GS33ZRJH.js} +4 -4
- package/dist/cli/chunks/chunk-HPYGMKZF.js +2 -0
- package/dist/cli/chunks/{chunk-EQBEGDTG.js → chunk-HTLAPMTK.js} +1 -1
- package/dist/cli/chunks/{chunk-C2M74HCN.js → chunk-IAK76TIZ.js} +1 -1
- package/dist/cli/chunks/{chunk-2EDWGHDA.js → chunk-ICF5RPQU.js} +2 -2
- package/dist/cli/chunks/{chunk-ZXTO4C7R.js → chunk-IPAQ4HVX.js} +2 -2
- package/dist/cli/chunks/{chunk-RLXTBL3H.js → chunk-ISRTT4I7.js} +22 -22
- package/dist/cli/chunks/{chunk-SW4OKUTC.js → chunk-IYFMDIYZ.js} +2 -2
- package/dist/cli/chunks/{chunk-7IZ2OPC2.js → chunk-JRBGHWAM.js} +2 -2
- package/dist/cli/chunks/{chunk-QJ2EHLJ2.js → chunk-JYR3X4OC.js} +1 -1
- package/dist/cli/chunks/{chunk-5QHSLWLP.js → chunk-K72J52JO.js} +2 -2
- package/dist/cli/chunks/{chunk-PIZYRPMT.js → chunk-K7CW2X6U.js} +2 -2
- package/dist/cli/chunks/{chunk-3Z4FHA2E.js → chunk-K7K4TFJM.js} +4 -4
- package/dist/cli/chunks/{chunk-5HB54RUS.js → chunk-KCXE2LZU.js} +2 -2
- package/dist/cli/chunks/{chunk-THRTUW4Z.js → chunk-KGPAWNNR.js} +1 -1
- package/dist/cli/chunks/{chunk-MYWQTCS4.js → chunk-KJ56OXH4.js} +1 -1
- package/dist/cli/chunks/{chunk-ZDHMZPSL.js → chunk-KUFC4DBX.js} +1 -1
- package/dist/cli/chunks/{chunk-CV2SBMBW.js → chunk-KWZEBHAP.js} +2 -2
- package/dist/cli/chunks/{chunk-X2VAOIUY.js → chunk-L6VNEEN6.js} +1 -1
- package/dist/cli/chunks/{chunk-S3OZ7XSY.js → chunk-LHPR7ROV.js} +1 -1
- package/dist/cli/chunks/{chunk-HO37VP4O.js → chunk-LKK3NIHC.js} +1 -1
- package/dist/cli/chunks/{chunk-XRJECWZE.js → chunk-LOFA3U4X.js} +1 -1
- package/dist/cli/chunks/{chunk-AWFIEGR3.js → chunk-LYKSIOOT.js} +2 -2
- package/dist/cli/chunks/chunk-M2PSXKTG.js +2 -0
- package/dist/cli/chunks/{chunk-CMACGG4Z.js → chunk-M3MKP5VN.js} +1 -1
- package/dist/cli/chunks/{chunk-UYYBPWU3.js → chunk-M4ARHDY4.js} +1 -1
- package/dist/cli/chunks/chunk-M5DBKHM4.js +2 -0
- package/dist/cli/chunks/{chunk-7IVQ6OVR.js → chunk-MDWJXSBA.js} +2 -2
- package/dist/cli/chunks/{chunk-IICTTDAA.js → chunk-MFWWPRBV.js} +2 -2
- package/dist/cli/chunks/{chunk-4BXGVM2C.js → chunk-MHWYQHGN.js} +1 -1
- package/dist/cli/chunks/{chunk-HJME6G5M.js → chunk-MIQBRVK2.js} +1 -1
- package/dist/cli/chunks/{chunk-FY3CUPNN.js → chunk-MKZQBBCU.js} +2 -2
- package/dist/cli/chunks/{chunk-MCOFJHSJ.js → chunk-MQ5WMWUK.js} +5 -5
- package/dist/cli/chunks/chunk-MQIAN57O.js +2 -0
- package/dist/cli/chunks/{chunk-6NZHEM4V.js → chunk-MU4P4P4E.js} +3 -3
- package/dist/cli/chunks/{chunk-ETN5563K.js → chunk-MWV4KPOB.js} +2 -2
- package/dist/cli/chunks/{chunk-XTCUN36Z.js → chunk-N244P4MM.js} +2 -2
- package/dist/cli/chunks/{chunk-DRWGK3YO.js → chunk-N3MM4Z33.js} +2 -2
- package/dist/cli/chunks/{chunk-QQNCSEZG.js → chunk-N4CXUGXE.js} +2 -2
- package/dist/cli/chunks/{chunk-PEK6NGVJ.js → chunk-ND6YSW5N.js} +1 -1
- package/dist/cli/chunks/{chunk-7V5UHLNY.js → chunk-NJYI7HX7.js} +3 -3
- package/dist/cli/chunks/{chunk-YACT5WFC.js → chunk-NSRDP7RD.js} +2 -2
- package/dist/cli/chunks/{chunk-L7VIX22Y.js → chunk-NZGLDOU4.js} +15 -15
- package/dist/cli/chunks/{chunk-MNUTRAUV.js → chunk-O3SG32PS.js} +1 -1
- package/dist/cli/chunks/{chunk-ZGNZJJFF.js → chunk-OIFJH7TF.js} +1 -1
- package/dist/cli/chunks/{chunk-LZCBSFAU.js → chunk-OKKTDHHF.js} +6 -6
- package/dist/cli/chunks/{chunk-3RHHKYUR.js → chunk-OO7KJ34Y.js} +2 -2
- package/dist/cli/chunks/{chunk-STEGWLH5.js → chunk-OV4BLIKJ.js} +2 -2
- package/dist/cli/chunks/{chunk-AOI67HA3.js → chunk-PISW5HUX.js} +1 -1
- package/dist/cli/chunks/{chunk-SJH3HYNC.js → chunk-PLD4IGDL.js} +2 -2
- package/dist/cli/chunks/{chunk-2OH3ALYB.js → chunk-PMWWWYUM.js} +1 -1
- package/dist/cli/chunks/{chunk-EA7ZSN3V.js → chunk-PWJZZCHJ.js} +1 -1
- package/dist/cli/chunks/{chunk-HA63NBFK.js → chunk-PZ4PRZXN.js} +37 -37
- package/dist/cli/chunks/chunk-PZCSJZVJ.js +2 -0
- package/dist/cli/chunks/{chunk-CTDLI2ON.js → chunk-Q53M4LI7.js} +1 -1
- package/dist/cli/chunks/{chunk-WSVUSIAZ.js → chunk-QPMAXDJ2.js} +2 -2
- package/dist/cli/chunks/{chunk-MCZHKXB4.js → chunk-RJKYPWFD.js} +2 -2
- package/dist/cli/chunks/{chunk-7QRMARM7.js → chunk-RUC3FCRK.js} +2 -2
- package/dist/cli/chunks/{chunk-5PL7WTCU.js → chunk-SC6UFGJ6.js} +2 -2
- package/dist/cli/chunks/{chunk-FO43SQXP.js → chunk-SJC7OKF3.js} +2 -2
- package/dist/cli/chunks/{chunk-R2O6OKT2.js → chunk-STMMZXS6.js} +1 -1
- package/dist/cli/chunks/{chunk-ORF2UKQH.js → chunk-SVILIQQQ.js} +1 -1
- package/dist/cli/chunks/{chunk-UVU7XLJY.js → chunk-SXMGNMFL.js} +5 -5
- package/dist/cli/chunks/{chunk-OIEQF7PG.js → chunk-SZKFT6CD.js} +2 -2
- package/dist/cli/chunks/{chunk-G5U6Q42D.js → chunk-TBJ566KV.js} +2 -2
- package/dist/cli/chunks/{chunk-SVYTN2GT.js → chunk-TCV5DASI.js} +2 -2
- package/dist/cli/chunks/chunk-TWAWEP4X.js +59 -0
- package/dist/cli/chunks/chunk-U27GVYXA.js +2 -0
- package/dist/cli/chunks/{chunk-FPAW77XV.js → chunk-UFKVKNAA.js} +1 -1
- package/dist/cli/chunks/{chunk-HJORBNXW.js → chunk-USB7GCIC.js} +1 -1
- package/dist/cli/chunks/{chunk-4GTDW2XL.js → chunk-UW3ZSFFB.js} +2 -2
- package/dist/cli/chunks/{chunk-OXCEUR5F.js → chunk-UWAUYDW4.js} +2 -2
- package/dist/cli/chunks/{chunk-4F3ZTXHP.js → chunk-UXJVR323.js} +2 -2
- package/dist/cli/chunks/{chunk-AIUSZC6K.js → chunk-V5G3SMAJ.js} +2 -2
- package/dist/cli/chunks/{chunk-DMQPO43S.js → chunk-VDKMBOUK.js} +1 -1
- package/dist/cli/chunks/{chunk-5WJ3FWL4.js → chunk-VJ2D6FST.js} +24 -24
- package/dist/cli/chunks/chunk-VJOPNK2L.js +2 -0
- package/dist/cli/chunks/{chunk-JF53LRBL.js → chunk-VRE2EBFI.js} +2 -2
- package/dist/cli/chunks/{chunk-WNR2KAUH.js → chunk-WI5WXYIS.js} +2 -2
- package/dist/cli/chunks/{chunk-OWQ6HEYI.js → chunk-WIYWDON4.js} +2 -2
- package/dist/cli/chunks/{chunk-KB5L5TTF.js → chunk-WYMQ6FZR.js} +5 -5
- package/dist/cli/chunks/{chunk-TJKDATEU.js → chunk-XBFEHVBO.js} +2 -2
- package/dist/cli/chunks/{chunk-7SJX4CFK.js → chunk-XDZXLEJK.js} +1 -1
- package/dist/cli/chunks/{chunk-QEPFXY6G.js → chunk-XJXCSCCP.js} +1 -1
- package/dist/cli/chunks/{chunk-OPFN5LFT.js → chunk-XVA56PXZ.js} +4 -4
- package/dist/cli/chunks/{chunk-PXTDEO65.js → chunk-Y2EDDV5U.js} +2 -2
- package/dist/cli/chunks/{chunk-VSUTI4G6.js → chunk-YSLE6NNG.js} +2 -2
- package/dist/cli/chunks/{chunk-XGBAHAGC.js → chunk-Z4BTPQLG.js} +4 -4
- package/dist/cli/chunks/{chunk-NZO4WUSO.js → chunk-ZM4QGYGK.js} +3 -3
- package/dist/cli/chunks/{ci-PYCRCL7G.js → ci-2BLMQNX3.js} +6 -6
- package/dist/cli/chunks/{ci-output-EKQQFE2D.js → ci-output-XK4PPSN7.js} +2 -2
- package/dist/cli/chunks/{circuit-breaker-RH3Q2MJO.js → circuit-breaker-W7X4NPFE.js} +2 -2
- package/dist/cli/chunks/{claude-flow-setup-DUDXB4VV.js → claude-flow-setup-GLBLSYNJ.js} +2 -2
- package/dist/cli/chunks/client-C6CJOCRN.js +2 -0
- package/dist/cli/chunks/{cline-installer-3Q4WIWUG.js → cline-installer-7WX7DBGI.js} +2 -2
- package/dist/cli/chunks/{code-E4Q6DGOO.js → code-SP3HAQWG.js} +20 -19
- package/dist/cli/chunks/{code-index-extractor-2PCISUOW.js → code-index-extractor-44HH36UG.js} +2 -2
- package/dist/cli/chunks/{codex-installer-YNNNOLJ6.js → codex-installer-LMXRWLPU.js} +2 -2
- package/dist/cli/chunks/{completions-2F7TUFBD.js → completions-GL5FTZAN.js} +2 -2
- package/dist/cli/chunks/{complexity-analyzer-2B6MHO7W.js → complexity-analyzer-CQMYGETL.js} +2 -2
- package/dist/cli/chunks/{continuedev-installer-ENOKRU5M.js → continuedev-installer-CYVYS5B7.js} +2 -2
- package/dist/cli/chunks/{copilot-installer-6YD2KM5F.js → copilot-installer-M7XVII2A.js} +2 -2
- package/dist/cli/chunks/{cost-tracker-FCH4QOEA.js → cost-tracker-S4ET4FH3.js} +2 -2
- package/dist/cli/chunks/{coverage-JTOXZE3T.js → coverage-DFVSSQ4A.js} +3 -3
- package/dist/cli/chunks/cross-domain-router-I3GEA5G6.js +2 -0
- package/dist/cli/chunks/{cursor-installer-QZFBUGLQ.js → cursor-installer-KWDSQPQC.js} +2 -2
- package/dist/cli/chunks/{daemon-K4QFB5FQ.js → daemon-2HD54QVO.js} +3 -3
- package/dist/cli/chunks/daemon-CRX46BBO.js +10 -0
- package/dist/cli/chunks/{dag-attention-scheduler-BXAAW33V.js → dag-attention-scheduler-SCP6WPZB.js} +2 -2
- package/dist/cli/chunks/{detect-UGSWIOAD.js → detect-XS2GDCEX.js} +2 -2
- package/dist/cli/chunks/{dist-node-FN3HX3OK.js → dist-node-U43MVQ3F.js} +2 -2
- package/dist/cli/chunks/{domain-handler-7PP7VYA7.js → domain-handler-HITMDULH.js} +2 -2
- package/dist/cli/chunks/{domain-transfer-XZM44W7I.js → domain-transfer-TJF7DNI4.js} +2 -2
- package/dist/cli/chunks/dream-JCQMG2RL.js +2 -0
- package/dist/cli/chunks/{embed-and-insert-pattern-JZVERJ5L.js → embed-and-insert-pattern-JKG33YZK.js} +2 -2
- package/dist/cli/chunks/{eval-466NFF2D.js → eval-NF5Y4W37.js} +3 -3
- package/dist/cli/chunks/{experience-capture-middleware-I7IQCC7V.js → experience-capture-middleware-VMMFYJ4D.js} +3 -3
- package/dist/cli/chunks/{fast-paths-34OICNZA.js → fast-paths-W2Q53IR2.js} +2 -2
- package/dist/cli/chunks/{feature-flags-6UBIVTAD.js → feature-flags-B4PBMQJO.js} +2 -2
- package/dist/cli/chunks/{feature-flags-X5WBBWSO.js → feature-flags-PVI7A4RE.js} +2 -2
- package/dist/cli/chunks/{file-discovery-NLMDBWXX.js → file-discovery-E4L3I33I.js} +2 -2
- package/dist/cli/chunks/{fleet-W7CYCHDI.js → fleet-LE5SHVLK.js} +3 -3
- package/dist/cli/chunks/{gnn-wrapper-K4VTAG5X.js → gnn-wrapper-MWWJBLOH.js} +2 -2
- package/dist/cli/chunks/{heartbeat-handler-ZGKF2Z6T.js → heartbeat-handler-XOUVNPQK.js} +4 -4
- package/dist/cli/chunks/heartbeat-scheduler-FBHE4ZWH.js +2 -0
- package/dist/cli/chunks/hnsw-adapter-EOOA4WXD.js +2 -0
- package/dist/cli/chunks/hnsw-index-TD3KRPND.js +2 -0
- package/dist/cli/chunks/{hnsw-legacy-bridge-ELDRLKK5.js → hnsw-legacy-bridge-W3T5ZDDP.js} +2 -2
- package/dist/cli/chunks/{better-sqlite3-5BT5FO64.js → hnswlib-node-3TZFES5I.js} +2 -2
- package/dist/cli/chunks/hooks-RUPQVIUM.js +250 -0
- package/dist/cli/chunks/hybrid-router-64O6PXZ2.js +2 -0
- package/dist/cli/chunks/{hypergraph-engine-UWFW3XP5.js → hypergraph-engine-VDFK3JYH.js} +2 -2
- package/dist/cli/chunks/{hypergraph-handler-PK2BI46K.js → hypergraph-handler-EUDGEF25.js} +3 -3
- package/dist/cli/chunks/impact-analyzer-ITQHXGTM.js +2 -0
- package/dist/cli/chunks/{init-handler-HNG6KJOU.js → init-handler-MZEAJOZK.js} +6 -6
- package/dist/cli/chunks/init-wizard-DZ4IKGQI.js +2 -0
- package/dist/cli/chunks/kernel-HSVY4ZYK.js +2 -0
- package/dist/cli/chunks/{kilocode-installer-25V7FEJ4.js → kilocode-installer-ECBYWT6M.js} +2 -2
- package/dist/cli/chunks/{kiro-installer-7RMTTCQB.js → kiro-installer-KYFCSYTG.js} +2 -2
- package/dist/cli/chunks/knowledge-graph-H32TXXX4.js +2 -0
- package/dist/cli/chunks/{learning-XQC2MG2R.js → learning-4RAFMDSB.js} +3 -3
- package/dist/cli/chunks/{llm-router-6KTTONH4.js → llm-router-JHBNLYP3.js} +12 -12
- package/dist/cli/chunks/llm-router-service-3FKESBUX.js +2 -0
- package/dist/cli/chunks/{load-BV64P3AL.js → load-4DVQML7P.js} +2 -2
- package/dist/cli/chunks/load-test-LKHURZGZ.js +2 -0
- package/dist/cli/chunks/{mcp-U5ZN77TA.js → mcp-LCWMU4GZ.js} +2 -2
- package/dist/cli/chunks/{memory-WB5BNBK7.js → memory-3DTJAURT.js} +5 -5
- package/dist/cli/chunks/memory-backend-XRJRZ6CK.js +2 -0
- package/dist/cli/chunks/memory-handlers-BL6E3XAK.js +2 -0
- package/dist/cli/chunks/{multi-model-executor-3X3W3UTY.js → multi-model-executor-AVR5SZOO.js} +2 -2
- package/dist/cli/chunks/{opencode-installer-TTTMG7ZZ.js → opencode-installer-DW2426QM.js} +3 -3
- package/dist/cli/chunks/{orchestrator-BLCGSHMZ.js → orchestrator-AHF4W5GS.js} +8 -8
- package/dist/cli/chunks/{pipeline-DZPGMRG7.js → pipeline-N6THEWYE.js} +2 -2
- package/dist/cli/chunks/{platform-EVMZAUNV.js → platform-MRCFQF7X.js} +2 -2
- package/dist/cli/chunks/{plugin-OR55K4HT.js → plugin-6YKUN5QM.js} +2 -2
- package/dist/cli/chunks/{prime-radiant-advanced-wasm-4ODV27HD.js → prime-radiant-advanced-wasm-2YPAHSVS.js} +2 -2
- package/dist/cli/chunks/protocol-executor-KABPB6PQ.js +2 -0
- package/dist/cli/chunks/{protocol-handler-ZOTI5PID.js → protocol-handler-Y2NMUKWQ.js} +2 -2
- package/dist/cli/chunks/{prove-DIMBYJ7V.js → prove-DZUNWBFD.js} +2 -2
- package/dist/cli/chunks/provider-manager-U7EBM3FA.js +2 -0
- package/dist/cli/chunks/qe-reasoning-bank-64O2OQIW.js +2 -0
- package/dist/cli/chunks/{quality-7MX4VL6M.js → quality-AIFQMGUV.js} +2 -2
- package/dist/cli/chunks/queen-coordinator-SV3COGIL.js +2 -0
- package/dist/cli/chunks/{real-embeddings-YPUHWRN2.js → real-embeddings-5XL4LOG2.js} +2 -2
- package/dist/cli/chunks/{roocode-installer-WG5AU4QM.js → roocode-installer-LV3WONT5.js} +2 -2
- package/dist/cli/chunks/router-QARRPMED.js +2 -0
- package/dist/cli/chunks/routing-feedback-KD2JFTPK.js +2 -0
- package/dist/cli/chunks/{routing-handler-LZB4MN2K.js → routing-handler-WSMUILGD.js} +2 -2
- package/dist/cli/chunks/{ruvector-commands-YE4ADBMC.js → ruvector-commands-BCEIDTW3.js} +2 -2
- package/dist/cli/chunks/{rvf-dual-writer-QS5ATW4C.js → rvf-dual-writer-LRSPC6H3.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-adapter-YIGKSBD3.js → rvf-migration-adapter-QHNX6353.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-coordinator-2NDCWP7F.js → rvf-migration-coordinator-SLNB3XPW.js} +2 -2
- package/dist/cli/chunks/rvf-native-adapter-4LLGF5AY.js +2 -0
- package/dist/cli/chunks/safe-db-RAX3H2P7.js +2 -0
- package/dist/cli/chunks/schedule-RQZGLLUY.js +2 -0
- package/dist/cli/chunks/scheduler-ACWTN4LN.js +2 -0
- package/dist/cli/chunks/{security-HT4SUT24.js → security-CYY6TECQ.js} +3 -3
- package/dist/cli/chunks/shared-rvf-adapter-U6JE4O6A.js +2 -0
- package/dist/cli/chunks/{shared-rvf-dual-writer-ZKFO7CBY.js → shared-rvf-dual-writer-PJBSNBRV.js} +2 -2
- package/dist/cli/chunks/sqlite-persistence-SWNBO257.js +2 -0
- package/dist/cli/chunks/{status-handler-AMEMKBI4.js → status-handler-W723LXX5.js} +2 -2
- package/dist/cli/chunks/{structural-health-RBADRLC3.js → structural-health-WZUPZBB5.js} +2 -2
- package/dist/cli/chunks/{sync-PCB23M4K.js → sync-UA22CKUS.js} +2 -2
- package/dist/cli/chunks/sync-ZLMF53TB.js +2 -0
- package/dist/cli/chunks/{task-handler-J26FSCH5.js → task-handler-SENTEEXZ.js} +2 -2
- package/dist/cli/chunks/{task-handlers-AQRLR6BL.js → task-handlers-FGVUZOCC.js} +3 -3
- package/dist/cli/chunks/{test-YXWSIOSB.js → test-Q37C3WI2.js} +4 -4
- package/dist/cli/chunks/{test-scheduling-XY532GI4.js → test-scheduling-E6SPIBTH.js} +4 -4
- package/dist/cli/chunks/token-bootstrap-HQFFMZUF.js +2 -0
- package/dist/cli/chunks/{token-usage-2MJVE4DT.js → token-usage-JHNWTZ7L.js} +3 -3
- package/dist/cli/chunks/{transformers-QSNTOD2Z.js → transformers-TEXDUVNI.js} +2 -2
- package/dist/cli/chunks/tree-sitter-wasm-parser-MWSS52H6.js +2 -0
- package/dist/cli/chunks/{types-RNKRSYMO.js → types-YQRKHYH3.js} +2 -2
- package/dist/cli/chunks/unified-memory-QG3FDRKR.js +2 -0
- package/dist/cli/chunks/unified-memory-hnsw-KOR4EOIG.js +2 -0
- package/dist/cli/chunks/unified-persistence-J6NIRYKM.js +2 -0
- package/dist/cli/chunks/{upgrade-EKJHIFWP.js → upgrade-JKMEDURI.js} +2 -2
- package/dist/cli/chunks/{validate-KS4T7LWC.js → validate-URO7G6OE.js} +4 -4
- package/dist/cli/chunks/validate-swarm-VZVJ56Z5.js +14 -0
- package/dist/cli/chunks/{vibium-FLUQO4IF.js → vibium-G5WZILL6.js} +2 -2
- package/dist/cli/chunks/visual-security-RAWV6YLN.js +2 -0
- package/dist/cli/chunks/{web-tree-sitter-UMC63DWD.js → web-tree-sitter-LECH5T6H.js} +2 -2
- package/dist/cli/chunks/{windsurf-installer-V3FQGJIQ.js → windsurf-installer-2NPLC2YW.js} +2 -2
- package/dist/cli/chunks/{witness-chain-GE74TLSO.js → witness-chain-X347C36A.js} +2 -2
- package/dist/cli/chunks/witness-chain-ZO7FIM35.js +2 -0
- package/dist/cli/chunks/{workflow-4YZ2RPWA.js → workflow-V4ALYZ73.js} +4 -4
- package/dist/cli/chunks/workflow-orchestrator-7SKITNIJ.js +2 -0
- package/dist/cli/chunks/wrappers-QXOPRPR4.js +2 -0
- package/dist/cli/commands/code.js +6 -0
- package/dist/cli/commands/hooks-handlers/task-hooks.js +50 -0
- package/dist/cli/commands/learning.js +5 -5
- package/dist/cli/commands/llm-router.js +1 -1
- package/dist/cli/commands/workflow.js +1 -0
- package/dist/coordination/consensus/providers/native-learning-provider.d.ts +1 -1
- package/dist/coordination/consensus/providers/ollama-provider.d.ts +1 -1
- package/dist/coordination/consensus/providers/openrouter-provider.d.ts +1 -1
- package/dist/coordination/handlers/code-intelligence-handlers.js +6 -0
- package/dist/coordination/mincut/neural-goap.js +24 -20
- package/dist/coordination/protocols/code-intelligence-index.js +31 -25
- package/dist/coordination/queen-coordinator.js +4 -0
- package/dist/coordination/queen-work-stealing.js +1 -2
- package/dist/domains/chaos-resilience/coordinator.js +19 -15
- package/dist/domains/chaos-resilience/services/chaos-engineer.js +5 -2
- package/dist/domains/chaos-resilience/services/load-tester.js +15 -11
- package/dist/domains/code-intelligence/interfaces.d.ts +5 -0
- package/dist/domains/code-intelligence/services/c4-model/index.js +12 -6
- package/dist/domains/code-intelligence/services/impact-analyzer.js +6 -2
- package/dist/domains/code-intelligence/services/knowledge-graph.d.ts +42 -0
- package/dist/domains/code-intelligence/services/knowledge-graph.js +278 -93
- package/dist/domains/code-intelligence/services/semantic-analyzer.js +8 -2
- package/dist/domains/contract-testing/coordinator.js +1 -1
- package/dist/domains/coverage-analysis/coordinator.js +4 -2
- package/dist/domains/learning-optimization/coordinator.js +1 -0
- package/dist/domains/quality-assessment/coherence/gate-controller.js +32 -26
- package/dist/domains/requirements-validation/coordinator.js +1 -0
- package/dist/domains/test-execution/services/e2e/wait-condition-handler.js +1 -1
- package/dist/domains/test-execution/services/retry-handler.js +18 -12
- package/dist/domains/test-generation/coordinator.js +1 -1
- package/dist/domains/test-generation/services/pattern-matcher.js +7 -5
- package/dist/domains/test-generation/services/test-generator.js +3 -2
- package/dist/domains/visual-accessibility/coordinator.js +24 -20
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/init/phases/12-verification.js +3 -3
- package/dist/integrations/agentic-flow/model-router/router.js +1 -1
- package/dist/integrations/embeddings/base/EmbeddingGenerator.js +11 -7
- package/dist/integrations/ruvector/hypergraph-engine.js +2 -2
- package/dist/integrations/ruvector/shared-rvf-adapter.js +12 -1
- package/dist/integrations/ruvector/shared-rvf-dual-writer.js +6 -2
- package/dist/integrations/ruvector/spectral-math.js +2 -2
- package/dist/integrations/ruvector/spectral-sparsifier.js +1 -1
- package/dist/kernel/kernel.js +1 -1
- package/dist/kernel/project-root.d.ts +33 -0
- package/dist/kernel/project-root.js +86 -0
- package/dist/kernel/unified-memory-hnsw.js +1 -0
- package/dist/kernel/unified-memory.d.ts +2 -19
- package/dist/kernel/unified-memory.js +8 -64
- package/dist/learning/experience-capture.js +1 -1
- package/dist/learning/local-judge-client.d.ts +55 -0
- package/dist/learning/local-judge-client.js +127 -0
- package/dist/learning/nagual-client.d.ts +73 -0
- package/dist/learning/nagual-client.js +150 -0
- package/dist/learning/pattern-store.js +10 -3
- package/dist/learning/qe-reasoning-bank.js +9 -1
- package/dist/learning/qe-unified-memory.js +8 -6
- package/dist/mcp/bundle.js +405 -403
- package/dist/mcp/entry.js +44 -33
- package/dist/mcp/handlers/core-handlers.js +2 -2
- package/dist/mcp/handlers/cross-phase-handlers.js +5 -3
- package/dist/mcp/handlers/handler-factory.d.ts +5 -0
- package/dist/mcp/handlers/handler-factory.js +44 -4
- package/dist/mcp/http-server.js +1 -0
- package/dist/mcp/protocol-server.js +2 -2
- package/dist/mcp/tools/code-intelligence/analyze.js +1 -1
- package/dist/mcp/tools/learning-optimization/optimize.js +1 -1
- package/dist/mcp/tools/qx-analysis/heuristics-engine.js +195 -173
- package/dist/mcp/tools/visual-accessibility/index.js +1 -1
- package/dist/mcp/transport/stdio.d.ts +7 -0
- package/dist/mcp/transport/stdio.js +39 -2
- package/dist/mcp/transport/websocket/websocket-transport.js +1 -0
- package/dist/optimization/auto-tuner.js +1 -1
- package/dist/planning/goap-planner.js +1 -0
- package/dist/routing/agent-dependency-graph.js +4 -1
- package/dist/shared/llm/router/config-store.js +1 -1
- package/dist/shared/metrics/system-metrics.js +6 -4
- package/dist/shared/parsers/tree-sitter-wasm-parser.d.ts +12 -0
- package/dist/shared/parsers/tree-sitter-wasm-parser.js +35 -0
- package/dist/shared/parsers/treesitter-ts-extractor.d.ts +39 -0
- package/dist/shared/parsers/treesitter-ts-extractor.js +196 -0
- package/dist/shared/utils/safe-expression-evaluator.js +8 -5
- package/dist/sync/cloud/postgres-writer.js +2 -0
- package/dist/sync/readers/json-reader.js +1 -1
- package/dist/test-scheduling/git-aware/test-selector.js +1 -1
- package/dist/workers/daemon.js +2 -0
- package/dist/workers/quality-daemon/git-watcher.js +2 -0
- package/dist/workers/quality-daemon/index.js +28 -24
- package/dist/workers/worker-manager.js +4 -0
- package/package.json +5 -4
- package/dist/cli/chunks/adapter-CR6J5C76.js +0 -2
- package/dist/cli/chunks/aqe-learning-engine-2MNTHMB6.js +0 -2
- package/dist/cli/chunks/audit-ALRYPHGP.js +0 -3
- package/dist/cli/chunks/base-AOQNGMTL.js +0 -2
- package/dist/cli/chunks/browser-workflow-UJ4A2ZXO.js +0 -2
- package/dist/cli/chunks/chunk-7DKYCVJI.js +0 -2
- package/dist/cli/chunks/chunk-FO73PZVU.js +0 -2
- package/dist/cli/chunks/chunk-I677W5BT.js +0 -59
- package/dist/cli/chunks/chunk-IAZEDWRX.js +0 -2
- package/dist/cli/chunks/chunk-RNREAOY4.js +0 -2
- package/dist/cli/chunks/chunk-UWXH2UQK.js +0 -2
- package/dist/cli/chunks/chunk-ZQUXNG5X.js +0 -2
- package/dist/cli/chunks/client-RDPWGOSA.js +0 -2
- package/dist/cli/chunks/cross-domain-router-4K5ZVZEZ.js +0 -2
- package/dist/cli/chunks/daemon-M422U3ZA.js +0 -10
- package/dist/cli/chunks/dream-RPNWM7VS.js +0 -2
- package/dist/cli/chunks/heartbeat-scheduler-JBCXMMZO.js +0 -2
- package/dist/cli/chunks/hnsw-adapter-3SC2HZIG.js +0 -2
- package/dist/cli/chunks/hnsw-index-FQORAR6K.js +0 -2
- package/dist/cli/chunks/hooks-T4CBINAV.js +0 -248
- package/dist/cli/chunks/hybrid-router-6CBFDXPR.js +0 -2
- package/dist/cli/chunks/impact-analyzer-SOEFVZWG.js +0 -2
- package/dist/cli/chunks/init-wizard-3E4IU5M4.js +0 -2
- package/dist/cli/chunks/kernel-GFZP4G5J.js +0 -2
- package/dist/cli/chunks/knowledge-graph-BKRKBU26.js +0 -2
- package/dist/cli/chunks/llm-router-service-KE4IGZPP.js +0 -2
- package/dist/cli/chunks/load-test-VSYJV2AO.js +0 -2
- package/dist/cli/chunks/memory-backend-B72RGHRF.js +0 -2
- package/dist/cli/chunks/memory-handlers-NWCH7AUO.js +0 -2
- package/dist/cli/chunks/protocol-executor-V3F37FPO.js +0 -2
- package/dist/cli/chunks/provider-manager-2PN72TT6.js +0 -2
- package/dist/cli/chunks/qe-reasoning-bank-P665QNIR.js +0 -2
- package/dist/cli/chunks/queen-coordinator-XD4F7BGB.js +0 -2
- package/dist/cli/chunks/router-4SSNWDJC.js +0 -2
- package/dist/cli/chunks/routing-feedback-O2JSIBW6.js +0 -2
- package/dist/cli/chunks/rvf-native-adapter-WIUHYXRB.js +0 -2
- package/dist/cli/chunks/safe-db-WL5Y7ZNS.js +0 -2
- package/dist/cli/chunks/schedule-U7QDGU5A.js +0 -2
- package/dist/cli/chunks/scheduler-LXKGQYXA.js +0 -2
- package/dist/cli/chunks/shared-rvf-adapter-4IZOJL33.js +0 -2
- package/dist/cli/chunks/sqlite-persistence-4KFO3SEB.js +0 -2
- package/dist/cli/chunks/sync-ARDDLQBS.js +0 -2
- package/dist/cli/chunks/token-bootstrap-KL2QIQ36.js +0 -2
- package/dist/cli/chunks/tree-sitter-wasm-parser-QJOKHOIW.js +0 -2
- package/dist/cli/chunks/unified-memory-7AS4LIEF.js +0 -2
- package/dist/cli/chunks/unified-memory-hnsw-GREESNJX.js +0 -2
- package/dist/cli/chunks/unified-persistence-BPJOMZOA.js +0 -2
- package/dist/cli/chunks/validate-swarm-SKKWRP2H.js +0 -14
- package/dist/cli/chunks/visual-security-BW662FHQ.js +0 -2
- package/dist/cli/chunks/witness-chain-OXVDLNVT.js +0 -2
- package/dist/cli/chunks/workflow-orchestrator-KKNR46XV.js +0 -2
- package/dist/cli/chunks/wrappers-37NLMKPE.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.10.
|
|
2
|
-
import{b as bl,c as wl}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.10.4");process.exit(0)}
|
|
2
|
+
import{b as bl,c as wl}from"./chunk-3UGUX34A.js";import{a as Ce,b as un,c as it,d as qr}from"./chunk-LKK3NIHC.js";import{a as xl}from"./chunk-SXMGNMFL.js";import{a as kl}from"./chunk-AZJYDM2K.js";import{a as za,b as an,c as Ba,d as Vr,e as qa,f as Ga,g as _r,h as Ha,i as on}from"./chunk-Z4BTPQLG.js";import{a as ae}from"./chunk-PMWWWYUM.js";import{a as hl}from"./chunk-MIQBRVK2.js";import{a as Dl,b as Il,e as Ml}from"./chunk-F34OO2Q7.js";import{e as dn,l as mn,q as Zm}from"./chunk-4FTLYIMW.js";import{a as Na,c as Al,d as El,s as tn}from"./chunk-XVA56PXZ.js";import{d as Fl}from"./chunk-4BX72XG4.js";import{a as I,b as Or,c as Pe,d as rn,e as nn,f as sn,g as rt,h as _a,i as He}from"./chunk-GDMH7NPV.js";import{a as Pl,j as Me}from"./chunk-N4CXUGXE.js";import{b as ja,d as cn}from"./chunk-C2446H7G.js";import{a as Br}from"./chunk-M5DBKHM4.js";import{a as x,b as Nr,c as At,d as Et,e as zr,f as Fe,g as xt}from"./chunk-TWAWEP4X.js";import{c as ln}from"./chunk-6WF2MOQB.js";import{a as Tl}from"./chunk-JRBGHWAM.js";import{a as yl}from"./chunk-TBJ566KV.js";import{b as Va}from"./chunk-FDFJJFQT.js";import{a as Sl,c as Rl}from"./chunk-VDKMBOUK.js";import{g as Cl}from"./chunk-YSLE6NNG.js";import{c as en,d as vl}from"./chunk-M2PSXKTG.js";import{i as Rt,m as Tt}from"./chunk-NZGLDOU4.js";import{b as fl}from"./chunk-U27GVYXA.js";import{b as E,d as H}from"./chunk-IYFMDIYZ.js";import{f as Xm}from"./chunk-KWZEBHAP.js";import{c as $r}from"./chunk-K7CW2X6U.js";import{a as M}from"./chunk-HPYGMKZF.js";import{c as R}from"./chunk-VRE2EBFI.js";import{a as we,b as f,c as p}from"./chunk-UFKVKNAA.js";import{a as T,b as y,c as A}from"./chunk-2B6ETC7C.js";import{i as v}from"./chunk-PISW5HUX.js";import{a as Oa}from"./chunk-KCXE2LZU.js";import{a as L,b as ue,d as se}from"./chunk-N3MM4Z33.js";import{a as gl,c as Lr,d as La,e as $a}from"./chunk-6OLHPWSN.js";import{a as tt,b as wt,c as Xi,d as Zi}from"./chunk-WI5WXYIS.js";import{S as Ge,b as Ct,n as St}from"./chunk-D7IWGQTW.js";import{a as Fa,c as qe,e as Yt,g as Xt}from"./chunk-SVILIQQQ.js";var _l={};Yt(_l,{ALL_SUPPORTED_LANGUAGES:()=>pp,ALL_TEST_FRAMEWORKS:()=>bn,DEFAULT_FRAMEWORKS:()=>Ja,FRAMEWORK_ALIASES:()=>Nl,FRAMEWORK_TO_LANGUAGE:()=>mp,LANGUAGE_FILE_EXTENSIONS:()=>Vl,getLanguageFromExtension:()=>nt,resolveFrameworkAlias:()=>wn});function wn(u){let t=u.toLowerCase().trim();return bn.includes(t)?t:Nl[t]}function nt(u){return Vl[u.startsWith(".")?u:`.${u}`]}var Ja,Nl,mp,Vl,bn,pp,er=qe(()=>{"use strict";Ja={typescript:"vitest",javascript:"jest",python:"pytest",java:"junit5",csharp:"xunit",go:"go-test",rust:"rust-test",swift:"swift-testing",kotlin:"kotlin-junit",dart:"flutter-test"},Nl={junit:"junit5","junit-5":"junit5","junit-4":"junit5",nunit:"nunit","x-unit":"xunit",xunit:"xunit",gotest:"go-test",go_test:"go-test",rusttest:"rust-test",rust_test:"rust-test",swift_testing:"swift-testing",swifttesting:"swift-testing",kotlin_junit:"kotlin-junit",kotlinjunit:"kotlin-junit",flutter_test:"flutter-test",fluttertest:"flutter-test",jest_rn:"jest-rn","jest-react-native":"jest-rn","react-native":"jest-rn"},mp={jest:"javascript",vitest:"typescript",mocha:"javascript",pytest:"python","node-test":"javascript",junit5:"java",testng:"java",xunit:"csharp",nunit:"csharp","go-test":"go","rust-test":"rust","swift-testing":"swift",xctest:"swift","kotlin-junit":"kotlin","flutter-test":"dart","jest-rn":"javascript",playwright:"typescript",cypress:"javascript"},Vl={".ts":"typescript",".tsx":"typescript",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".py":"python",".java":"java",".cs":"csharp",".go":"go",".rs":"rust",".swift":"swift",".kt":"kotlin",".kts":"kotlin",".dart":"dart"},bn=["jest","vitest","mocha","pytest","node-test","junit5","testng","xunit","nunit","go-test","rust-test","swift-testing","xctest","kotlin-junit","flutter-test","jest-rn","playwright","cypress"],pp=["typescript","javascript","python","java","csharp","go","rust","swift","kotlin","dart"]});function no(u,t={}){let{additionalContext:e,sourceCode:r,includeEvidence:i=!0,includeRemediation:n=!0,maxLength:s=8e3}=t,a=[];a.push(`# Security Finding Verification Request
|
|
3
3
|
|
|
4
4
|
You are a security expert tasked with verifying whether the following security finding is valid or a false positive.
|
|
5
5
|
|
|
@@ -114,7 +114,7 @@ Always explain your reasoning clearly.
|
|
|
114
114
|
Format your response with: verdict (confirmed/rejected/uncertain), confidence (0-100), and reasoning.`}}});import{randomUUID as Qm}from"crypto";$a();var Wa={LOOP_WARNING:"loop.warning",LOOP_DETECTED:"loop.detected"},pn=class{subscriptions=new Map;subscriptionsByEventType=new Map;subscriptionsByChannel=new Map;wildcardSubscriptions=new Set;eventHistory;maxHistorySize=La.MAX_HISTORY_SIZE;subscriptionCounter=0;middlewares=[];constructor(t=La.MAX_HISTORY_SIZE){this.maxHistorySize=t,this.eventHistory=new hl(t)}registerMiddleware(t){this.middlewares.push(t),this.middlewares.sort((e,r)=>e.priority-r.priority)}removeMiddleware(t){let e=this.middlewares.findIndex(r=>r.name===t);return e>=0?(this.middlewares.splice(e,1),!0):!1}getMiddlewares(){return this.middlewares}async publish(t){let e=t;for(let o of this.middlewares)if(o.onEmit&&e&&(e=await o.onEmit(e),!e))return;this.eventHistory.push(e);let r=new Set,i=this.subscriptionsByEventType.get(e.type);if(i)for(let o of i)r.add(o);let n=this.subscriptionsByChannel.get(e.source);if(n)for(let o of n)r.add(o);for(let o of this.wildcardSubscriptions)r.add(o);let s=[];for(let o of r){let c=this.subscriptions.get(o);!c||!c.active||c.channel&&c.channel!==e.source||c.eventType!=="*"&&c.eventType!==e.type||s.push(c)}let a=e;for(let o of this.middlewares)if(o.onReceive&&a&&(a=await o.onReceive(a),!a))return;await Promise.allSettled(s.map(o=>o.handler(a)))}subscribe(t,e){let r=`sub_${++this.subscriptionCounter}`,i={id:r,eventType:t,handler:e,active:!0};return this.subscriptions.set(r,i),t==="*"?this.wildcardSubscriptions.add(r):(this.subscriptionsByEventType.has(t)||this.subscriptionsByEventType.set(t,new Set),this.subscriptionsByEventType.get(t).add(r)),{unsubscribe:()=>{i.active=!1,this.subscriptions.delete(r),t==="*"?this.wildcardSubscriptions.delete(r):this.subscriptionsByEventType.get(t)?.delete(r)},get active(){return i.active}}}subscribeToChannel(t,e){let r=`sub_${++this.subscriptionCounter}`,i={id:r,eventType:"*",channel:t,handler:e,active:!0};return this.subscriptions.set(r,i),this.subscriptionsByChannel.has(t)||this.subscriptionsByChannel.set(t,new Set),this.subscriptionsByChannel.get(t).add(r),{unsubscribe:()=>{i.active=!1,this.subscriptions.delete(r),this.subscriptionsByChannel.get(t)?.delete(r)},get active(){return i.active}}}async getHistory(t){let e=this.eventHistory.toArray();return t&&(t.eventTypes?.length&&(e=e.filter(r=>t.eventTypes.includes(r.type))),t.sources?.length&&(e=e.filter(r=>t.sources.includes(r.source))),t.fromTimestamp&&(e=e.filter(r=>r.timestamp>=t.fromTimestamp)),t.toTimestamp&&(e=e.filter(r=>r.timestamp<=t.toTimestamp)),t.correlationId&&(e=e.filter(r=>r.correlationId===t.correlationId)),t.limit&&(e=e.slice(-t.limit))),e}async dispose(){this.subscriptions.clear(),this.subscriptionsByEventType.clear(),this.subscriptionsByChannel.clear(),this.wildcardSubscriptions.clear(),this.eventHistory.clear(),this.middlewares=[]}};$a();var hn=class{agents=new Map;maxAgents;memoryBranch=null;constructor(t=Lr.MAX_CONCURRENT_AGENTS){this.maxAgents=t}setMemoryBranch(t){this.memoryBranch=t}async spawn(t){if(!this.canSpawn())return p(new Error(`Cannot spawn agent: maximum concurrent agents (${this.maxAgents}) reached. Active: ${this.getActiveCount()}`));let e=t.config??{};if(t.progressiveContext?.strategy==="predictive"||process.env.AQE_PROGRESSIVE_CONTEXT_ENABLED==="true")try{let s=e.taskDescription||t.name||"",a=e.availableFiles||[];if(s&&a.length>0){let c=new Ua(t.progressiveContext).predictFilesForTask(s,a);e={...e,availableFiles:c,contextFiles:c,initialFiles:c,progressiveContextApplied:!0}}}catch{}let i=v(),n={id:i,name:t.name,domain:t.domain,type:t.type,status:"running",capabilities:t.capabilities,config:e,startedAt:new Date};if(this.agents.set(i,n),this.memoryBranch)try{let s=this.memoryBranch.createBranch(i);n.config={...n.config,_memoryBranchPath:s.childPath,_memoryBranchRecordIngest:a=>{this.memoryBranch?.recordIngest(i,a)}}}catch(s){console.warn(`[AgentCoordinator] Memory branch creation failed for ${i}:`,s)}return f(i)}getStatus(t){return this.agents.get(t)?.status}listAgents(t){let e=Array.from(this.agents.values());return t&&(t.domain&&(e=e.filter(r=>r.domain===t.domain)),t.status&&(e=e.filter(r=>r.status===t.status)),t.type&&(e=e.filter(r=>r.type===t.type))),e.map(r=>({id:r.id,name:r.name,domain:r.domain,type:r.type,status:r.status,startedAt:r.startedAt}))}async stop(t){let e=this.agents.get(t);return e?e.status!=="running"?p(new Error(`Agent ${t} is not running (status: ${e.status})`)):(e.status="completed",e.completedAt=new Date,f(void 0)):p(new Error(`Agent not found: ${t}`))}getActiveCount(){return Array.from(this.agents.values()).filter(t=>t.status==="running"||t.status==="queued").length}canSpawn(){return this.getActiveCount()<this.maxAgents}async dispose(){let t=Array.from(this.agents.values()).filter(e=>e.status==="running");await Promise.all(t.map(e=>this.stop(e.id))),this.agents.clear()}markCompleted(t){let e=this.agents.get(t);e&&e.status==="running"&&(e.status="completed",e.completedAt=new Date,this.handleBranchOnComplete(t,"merge"))}markFailed(t){let e=this.agents.get(t);e&&e.status==="running"&&(e.status="failed",e.completedAt=new Date,this.handleBranchOnComplete(t,"discard"))}handleBranchOnComplete(t,e){if(!this.memoryBranch)return;let r=this.memoryBranch.getBranch(t);if(r)try{e==="merge"?this.memoryBranch.mergeBranch(r).catch(i=>{console.warn(`[AgentCoordinator] Branch merge failed for ${t}:`,i)}):this.memoryBranch.discardBranch(r)}catch(i){console.warn(`[AgentCoordinator] Branch ${e} failed for ${t}:`,i)}}cleanup(t=Lr.DEFAULT_AGENT_TTL_MS){let e=Date.now(),r=0;for(let[i,n]of this.agents.entries())(n.status==="completed"||n.status==="failed")&&n.completedAt&&e-n.completedAt.getTime()>t&&(this.agents.delete(i),r++);return r}},ep={strategy:"full",maxInitialFiles:10,predictionThreshold:.7,trackFileRequests:!0},Ua=class{config;fileRequests=[];preloadedFiles=new Set;constructor(t){this.config={...ep,...t}}isEnabled(){return process.env.AQE_PROGRESSIVE_CONTEXT_ENABLED==="true"}predictFilesForTask(t,e){if(!this.isEnabled()||this.config.strategy==="full")return[...e];if(!t||t.trim().length===0)return e.slice(0,this.config.maxInitialFiles);if(e.length===0)return[];let r=this.extractKeywords(t);if(r.length===0)return e.slice(0,this.config.maxInitialFiles);let i=e.map(s=>({filePath:s,score:this.scoreFile(s,r)}));i.sort((s,a)=>a.score-s.score);let n=i.slice(0,this.config.maxInitialFiles).map(s=>s.filePath);return this.preloadedFiles=new Set(n),n}recordFileRequest(t){this.config.trackFileRequests&&this.fileRequests.push(t)}getPredictionAccuracy(){let t=this.preloadedFiles.size,e=this.fileRequests.filter(s=>s.wasPreloaded).length,r=new Set(this.fileRequests.map(s=>s.filePath)),i=[...r].filter(s=>this.preloadedFiles.has(s)).length,n=r.size>0?i/r.size:0;return{predicted:t,actuallyUsed:e,hitRate:n}}getFileRequestHistory(t){return t?this.fileRequests.filter(e=>e.agentId===t):[...this.fileRequests]}extractKeywords(t){let e=new Set(["the","a","an","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","could","should","may","might","shall","can","to","of","in","for","on","with","at","by","from","as","into","through","during","before","after","and","but","or","nor","not","so","yet","both","either","neither","each","every","all","any","few","more","most","other","some","such","no","only","same","than","too","very","just","because","if","when","while","that","this","these","those","it","its","they","them","their","we","our","you","your","he","she","his","her","i","me","my"]),r=t.toLowerCase().split(/[\s\-_./\\,;:!?()[\]{}'"]+/).filter(i=>i.length>1&&!e.has(i));return[...new Set(r)]}scoreFile(t,e){let r=t.toLowerCase(),i=r.split(/[\\/.]/).filter(s=>s.length>0),n=0;for(let s of e)if(i.includes(s))n+=2;else if(r.includes(s))n+=1;else for(let a of i)if(a.startsWith(s)||s.startsWith(a)){n+=.5;break}return e.length>0?n/(e.length*2):0}};M();var tp=R.create("plugin-loader"),Gr=class{constructor(t,e,r=!0){this.eventBus=t;this.memory=e}eventBus;memory;plugins=new Map;factories=new Map;loading=new Map;registerFactory(t,e){this.factories.set(t,e)}async load(t){let e=this.plugins.get(t);if(e)return e;let r=this.loading.get(t);if(r)return r;let i=this.factories.get(t);if(!i){let s=Array.from(this.factories.keys());throw new Error(`No factory registered for domain: ${t}
|
|
115
115
|
This usually means the domain is not enabled in your config.
|
|
116
116
|
Registered domains: ${s.join(", ")}
|
|
117
|
-
Fix: Add '${t}' to domains.enabled in .agentic-qe/config.yaml, or run 'aqe init --auto-migrate' to enable all domains.`)}let n=this.loadPlugin(t,i);this.loading.set(t,n);try{let s=await n;return this.plugins.set(t,s),s}finally{this.loading.delete(t)}}async loadPlugin(t,e){let r=await e(this.eventBus,this.memory);for(let i of r.dependencies)this.isLoaded(i)||await this.load(i);return await r.initialize(),r}async unload(t){let e=this.plugins.get(t);if(e){for(let[r,i]of this.plugins.entries())if(i.dependencies.includes(t))throw new Error(`Cannot unload ${t}: domain ${r} depends on it`);await e.dispose(),this.plugins.delete(t)}}isLoaded(t){return this.plugins.has(t)}getLoaded(){return Array.from(this.plugins.keys())}async loadAll(){let t=Array.from(this.factories.keys()),e=this.topologicalSort(t);for(let r of e)await this.load(r)}topologicalSort(t){let e=[],r=new Set,i=new Set,n=s=>{if(r.has(s))return;if(i.has(s))throw new Error(`Circular dependency detected involving: ${s}`);i.add(s);let o=this.plugins.get(s)?.dependencies??[];for(let c of o)t.includes(c)&&n(c);i.delete(s),r.add(s),e.push(s)};for(let s of t)n(s);return e}getPlugin(t){return this.plugins.get(t)}async disposeAll(){let t=[...this.getLoaded()].reverse();for(let e of t)try{await this.unload(e)}catch(r){tp.debug("Plugin unload failed, force removing",{domain:e,error:r instanceof Error?r.message:String(r)}),this.plugins.delete(e)}}};Zi();M();var Qa=R.create("anti-drift-middleware"),rp={maxIdenticalCalls:3,windowMs:3e4,steeringMessage:"Loop detected: the same tool call has been repeated multiple times. Consider an alternative approach or different parameters.",enableFleetLearning:!1};function Ll(u){let t=2166136261;for(let e=0;e<u.length;e++)t^=u.charCodeAt(e),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}var gn=class{config;callHistory=new Map;totalCallsTracked=0;loopsDetected=0;constructor(t){this.config={...rp,...t}}trackCall(t,e,r){if(process.env.AQE_LOOP_DETECTION_ENABLED==="false")return{isLoop:!1,callCount:1,signature:this.createSignature(e,r),action:"allow"};let i=this.createSignature(e,r);this.totalCallsTracked++,this.callHistory.has(t)||this.callHistory.set(t,[]);let n=this.callHistory.get(t);n.push(i);let s=Date.now()-this.config.windowMs,a=n.findIndex(c=>c.timestamp>=s);a>0?n.splice(0,a):a===-1&&(n.length=0,n.push(i));let o=n.filter(c=>c.hash===i.hash).length;return o>=this.config.maxIdenticalCalls?(this.loopsDetected++,{isLoop:!0,callCount:o,signature:i,action:"steer",steeringMessage:this.config.steeringMessage}):o===this.config.maxIdenticalCalls-1?{isLoop:!1,callCount:o,signature:i,action:"warn"}:{isLoop:!1,callCount:o,signature:i,action:"allow"}}getMetrics(){return{totalCallsTracked:this.totalCallsTracked,loopsDetected:this.loopsDetected}}clear(){this.callHistory.clear(),this.totalCallsTracked=0,this.loopsDetected=0}createSignature(t,e){let r=JSON.stringify(e??""),i=Ll(r),n=`${t}:${r}`;return{hash:Ll(n),toolName:t,argsFingerprint:i,timestamp:Date.now()}}},Ol={"quality-gate":.05,coverage:.1,"test-generation":.15,learning:.2,default:.12},ip={thresholds:Ol,agentId:"unknown",maxHistorySize:200,fallbackDimension:64};function np(u,t){let e=new Float64Array(t),r=2166136261,i=16777619;for(let a=0;a<u.length;a++){let o=u.charCodeAt(a);r^=o,r=Math.imul(r,16777619),i^=o,i=Math.imul(i,2166136261);let c=(r>>>0)%t;e[c]+=(i>>>0)/4294967295*2-1}let n=0;for(let a=0;a<t;a++)n+=e[a]*e[a];n=Math.sqrt(n);let s=new Array(t);for(let a=0;a<t;a++)s[a]=n===0?0:e[a]/n;return s}var $l=!1,Zt=!1,fn=null;async function sp(){if($l)return Zt;$l=!0;try{let u=await import("./real-embeddings-
|
|
117
|
+
Fix: Add '${t}' to domains.enabled in .agentic-qe/config.yaml, or run 'aqe init --auto-migrate' to enable all domains.`)}let n=this.loadPlugin(t,i);this.loading.set(t,n);try{let s=await n;return this.plugins.set(t,s),s}finally{this.loading.delete(t)}}async loadPlugin(t,e){let r=await e(this.eventBus,this.memory);for(let i of r.dependencies)this.isLoaded(i)||await this.load(i);return await r.initialize(),r}async unload(t){let e=this.plugins.get(t);if(e){for(let[r,i]of this.plugins.entries())if(i.dependencies.includes(t))throw new Error(`Cannot unload ${t}: domain ${r} depends on it`);await e.dispose(),this.plugins.delete(t)}}isLoaded(t){return this.plugins.has(t)}getLoaded(){return Array.from(this.plugins.keys())}async loadAll(){let t=Array.from(this.factories.keys()),e=this.topologicalSort(t);for(let r of e)await this.load(r)}topologicalSort(t){let e=[],r=new Set,i=new Set,n=s=>{if(r.has(s))return;if(i.has(s))throw new Error(`Circular dependency detected involving: ${s}`);i.add(s);let o=this.plugins.get(s)?.dependencies??[];for(let c of o)t.includes(c)&&n(c);i.delete(s),r.add(s),e.push(s)};for(let s of t)n(s);return e}getPlugin(t){return this.plugins.get(t)}async disposeAll(){let t=[...this.getLoaded()].reverse();for(let e of t)try{await this.unload(e)}catch(r){tp.debug("Plugin unload failed, force removing",{domain:e,error:r instanceof Error?r.message:String(r)}),this.plugins.delete(e)}}};Zi();M();var Qa=R.create("anti-drift-middleware"),rp={maxIdenticalCalls:3,windowMs:3e4,steeringMessage:"Loop detected: the same tool call has been repeated multiple times. Consider an alternative approach or different parameters.",enableFleetLearning:!1};function Ll(u){let t=2166136261;for(let e=0;e<u.length;e++)t^=u.charCodeAt(e),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}var gn=class{config;callHistory=new Map;totalCallsTracked=0;loopsDetected=0;constructor(t){this.config={...rp,...t}}trackCall(t,e,r){if(process.env.AQE_LOOP_DETECTION_ENABLED==="false")return{isLoop:!1,callCount:1,signature:this.createSignature(e,r),action:"allow"};let i=this.createSignature(e,r);this.totalCallsTracked++,this.callHistory.has(t)||this.callHistory.set(t,[]);let n=this.callHistory.get(t);n.push(i);let s=Date.now()-this.config.windowMs,a=n.findIndex(c=>c.timestamp>=s);a>0?n.splice(0,a):a===-1&&(n.length=0,n.push(i));let o=n.filter(c=>c.hash===i.hash).length;return o>=this.config.maxIdenticalCalls?(this.loopsDetected++,{isLoop:!0,callCount:o,signature:i,action:"steer",steeringMessage:this.config.steeringMessage}):o===this.config.maxIdenticalCalls-1?{isLoop:!1,callCount:o,signature:i,action:"warn"}:{isLoop:!1,callCount:o,signature:i,action:"allow"}}getMetrics(){return{totalCallsTracked:this.totalCallsTracked,loopsDetected:this.loopsDetected}}clear(){this.callHistory.clear(),this.totalCallsTracked=0,this.loopsDetected=0}createSignature(t,e){let r=JSON.stringify(e??""),i=Ll(r),n=`${t}:${r}`;return{hash:Ll(n),toolName:t,argsFingerprint:i,timestamp:Date.now()}}},Ol={"quality-gate":.05,coverage:.1,"test-generation":.15,learning:.2,default:.12},ip={thresholds:Ol,agentId:"unknown",maxHistorySize:200,fallbackDimension:64};function np(u,t){let e=new Float64Array(t),r=2166136261,i=16777619;for(let a=0;a<u.length;a++){let o=u.charCodeAt(a);r^=o,r=Math.imul(r,16777619),i^=o,i=Math.imul(i,2166136261);let c=(r>>>0)%t;e[c]+=(i>>>0)/4294967295*2-1}let n=0;for(let a=0;a<t;a++)n+=e[a]*e[a];n=Math.sqrt(n);let s=new Array(t);for(let a=0;a<t;a++)s[a]=n===0?0:e[a]/n;return s}var $l=!1,Zt=!1,fn=null;async function sp(){if($l)return Zt;$l=!0;try{let u=await import("./real-embeddings-5XL4LOG2.js");if(typeof u.isTransformerAvailable=="function"&&u.isTransformerAvailable())fn=u.computeRealEmbedding,Zt=!0;else try{await u.computeRealEmbedding("probe"),fn=u.computeRealEmbedding,Zt=!0}catch(t){Qa.debug("Transformer probe embedding failed",{error:t instanceof Error?t.message:String(t)}),Zt=!1}}catch(u){Qa.debug("Transformer module import failed",{error:u instanceof Error?u.message:String(u)}),Zt=!1}return Zt}var yn=class{name="semantic-anti-drift";priority=10;config;history=[];totalChecked=0;driftCount=0;similaritySum=0;constructor(t){this.config={...ip,...t,thresholds:{...Ol,...t?.thresholds}}}async onEmit(t){let e=JSON.stringify(t.payload),r=await this.embed(e),i=this.resolveCategory(t.type),n=this.config.thresholds[i]??this.config.thresholds.default,s={embedding:r,driftThreshold:n,sourceAgentId:this.config.agentId,hopCount:0,emittedAt:Date.now()};return{...t,semanticFingerprint:s}}async onReceive(t){let e=t.semanticFingerprint;if(!e)return t;let r=JSON.stringify(t.payload),i=await this.embed(r),n=tt(i,e.embedding),a=1-n>e.driftThreshold;this.totalChecked++,this.similaritySum+=n;let o={drifted:a,cosineSimilarity:n,threshold:e.driftThreshold,eventType:t.type,hopCount:e.hopCount+1,checkedAt:Date.now()};if(this.history.push(o),this.history.length>this.config.maxHistorySize&&this.history.shift(),a)return this.driftCount++,await this.emitDriftEvent(t,o),null;let c={...e,hopCount:e.hopCount+1};return{...t,semanticFingerprint:c}}getDriftHistory(){return this.history}getStats(){return{totalChecked:this.totalChecked,driftCount:this.driftCount,averageSimilarity:this.totalChecked>0?this.similaritySum/this.totalChecked:0}}validateConfig(){for(let[t,e]of Object.entries(this.config.thresholds))if(typeof e!="number"||e<0||e>1)return p(new Error(`Invalid threshold for "${t}": must be between 0 and 1, got ${e}`));return this.config.maxHistorySize<=0?p(new Error("maxHistorySize must be positive")):this.config.fallbackDimension<=0?p(new Error("fallbackDimension must be positive")):f(void 0)}async embed(t){return await sp()&&fn?fn(t):np(t,this.config.fallbackDimension)}resolveCategory(t){let e=t.toLowerCase();for(let r of Object.keys(this.config.thresholds))if(r!=="default"&&e.includes(r))return r;return"default"}async emitDriftEvent(t,e){if(!this.config.onDriftDetected)return;let r={id:`drift-${t.id}-${Date.now()}`,type:"SemanticDriftDetected",timestamp:new Date,source:t.source,correlationId:t.correlationId,payload:{originalEventId:t.id,originalEventType:t.type,cosineSimilarity:e.cosineSimilarity,threshold:e.threshold,hopCount:e.hopCount,agentId:this.config.agentId}};try{await this.config.onDriftDetected(r)}catch(i){Qa.debug("onDriftDetected callback failed",{error:i instanceof Error?i.message:String(i)})}}};$a();Tt();import*as Jt from"path";import*as Ma from"fs";Tt();import{randomUUID as ap}from"crypto";var Ka="aqe/bridge/captured-experiences/cursor",op=5e3,cp=100,vn=class{constructor(t,e,r={}){this.eventBus=t;this.memory=e;this.intervalMs=r.intervalMs??op,this.batchSize=r.batchSize??cp}eventBus;memory;cursor=0;intervalId;draining=!1;intervalMs;batchSize;async start(){if(this.intervalId)return;let t=await this.memory.get(Ka);this.cursor=typeof t=="number"?t:0,await this.drainSafe(),this.intervalId=setInterval(()=>{this.drainSafe()},this.intervalMs),this.intervalId.unref?.()}async stop(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=void 0)}async drainOnce(){return this.drainSafe()}async drainSafe(){if(this.draining)return 0;this.draining=!0;try{let t=await this.drain();return await Na(this.memory,"bridge",{success:!0}),t}catch(t){return console.warn("[CapturedExperienceBridge] drain failed:",t instanceof Error?t.message:t),await Na(this.memory,"bridge",{success:!1,error:t instanceof Error?t:String(t)}),0}finally{this.draining=!1}}async drain(){let t=Rt();if(!t.isInitialized())return 0;let e=t.getDatabase();if(!e.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='captured_experiences'").get())return 0;let i=e.prepare(`SELECT rowid, id, task, agent, domain, success, quality,
|
|
118
118
|
duration_ms, source, completed_at
|
|
119
119
|
FROM captured_experiences
|
|
120
120
|
WHERE rowid > ?
|
|
@@ -1936,7 +1936,7 @@ ${o},
|
|
|
1936
1936
|
`,e+=` });
|
|
1937
1937
|
`)}return e+=` });
|
|
1938
1938
|
|
|
1939
|
-
`,e}static convertParsedFile(t){return{functions:t.functions.map(e=>({name:e.name,parameters:e.parameters.map(r=>({name:r.name,type:r.type,optional:r.isOptional,defaultValue:r.defaultValue})),returnType:e.returnType,isAsync:e.isAsync,isExported:e.isPublic,complexity:e.complexity,startLine:e.startLine,endLine:e.endLine,body:e.body})),classes:t.classes.map(e=>({name:e.name,methods:e.methods.map(r=>({name:r.name,parameters:r.parameters.map(i=>({name:i.name,type:i.type,optional:i.isOptional,defaultValue:i.defaultValue})),returnType:r.returnType,isAsync:r.isAsync,isExported:r.isPublic,complexity:r.complexity,startLine:r.startLine,endLine:r.endLine,body:r.body})),properties:e.properties.map(r=>({name:r.name,type:r.type,isPrivate:!r.isPublic,isReadonly:r.isReadonly})),isExported:e.isPublic,hasConstructor:e.methods.some(r=>r.name==="constructor"),constructorParams:e.methods.find(r=>r.name==="constructor")?.parameters.map(r=>({name:r.name,type:r.type,optional:r.isOptional,defaultValue:r.defaultValue}))}))}}};var fp=bn,yp="vitest",ti=class{cache=new Map;create(t){let e=wn(t)??t,r=this.cache.get(e);if(r)return r;let i=this.createGenerator(e);return this.cache.set(e,i),i}supports(t){return wn(t)!==void 0}getDefault(){return yp}getSupportedFrameworks(){return[...fp]}createGenerator(t){switch(t){case"jest":return new tr("jest");case"vitest":return new tr("vitest");case"mocha":return new jr;case"pytest":return new at;case"node-test":return new Wr;case"junit5":case"testng":return new Ur;case"xunit":case"nunit":return new Kr;case"go-test":return new Qr;case"rust-test":return new Jr;case"swift-testing":case"xctest":return new Yr;case"kotlin-junit":return new Xr;case"flutter-test":return new Zr;case"jest-rn":return new ei;case"playwright":case"cypress":throw new Error(`Generator for '${t}' not yet implemented`);default:throw new Error(`Unsupported test framework: ${t}`)}}clearCache(){this.cache.clear()}},
|
|
1939
|
+
`,e}static convertParsedFile(t){return{functions:t.functions.map(e=>({name:e.name,parameters:e.parameters.map(r=>({name:r.name,type:r.type,optional:r.isOptional,defaultValue:r.defaultValue})),returnType:e.returnType,isAsync:e.isAsync,isExported:e.isPublic,complexity:e.complexity,startLine:e.startLine,endLine:e.endLine,body:e.body})),classes:t.classes.map(e=>({name:e.name,methods:e.methods.map(r=>({name:r.name,parameters:r.parameters.map(i=>({name:i.name,type:i.type,optional:i.isOptional,defaultValue:i.defaultValue})),returnType:r.returnType,isAsync:r.isAsync,isExported:r.isPublic,complexity:r.complexity,startLine:r.startLine,endLine:r.endLine,body:r.body})),properties:e.properties.map(r=>({name:r.name,type:r.type,isPrivate:!r.isPublic,isReadonly:r.isReadonly})),isExported:e.isPublic,hasConstructor:e.methods.some(r=>r.name==="constructor"),constructorParams:e.methods.find(r=>r.name==="constructor")?.parameters.map(r=>({name:r.name,type:r.type,optional:r.isOptional,defaultValue:r.defaultValue}))}))}}};var fp=bn,yp="vitest",ti=class{cache=new Map;create(t){let e=wn(t)??t,r=this.cache.get(e);if(r)return r;let i=this.createGenerator(e);return this.cache.set(e,i),i}supports(t){return wn(t)!==void 0}getDefault(){return yp}getSupportedFrameworks(){return[...fp]}createGenerator(t){switch(t){case"jest":return new tr("jest");case"vitest":return new tr("vitest");case"mocha":return new jr;case"pytest":return new at;case"node-test":return new Wr;case"junit5":case"testng":return new Ur;case"xunit":case"nunit":return new Kr;case"go-test":return new Qr;case"rust-test":return new Jr;case"swift-testing":case"xctest":return new Yr;case"kotlin-junit":return new Xr;case"flutter-test":return new Zr;case"jest-rn":return new ei;case"playwright":case"cypress":throw new Error(`Generator for '${t}' not yet implemented`);default:throw new Error(`Unsupported test framework: ${t}`)}}clearCache(){this.cache.clear()}},Gw=new ti;var Rn=class{async generateTDDTests(t){let{feature:e,behavior:r,framework:i,phase:n}=t;switch(n){case"red":return this.generateRedPhaseTest(e,r,i);case"green":return this.generateGreenPhaseCode(e,r,i);case"refactor":return this.generateRefactoringSuggestions(e,r);default:throw new Error(`Unknown TDD phase: ${n}`)}}generateRedPhaseTest(t,e,r){let i=this.camelCase(t),n=this.generateAssertionsFromBehavior(e,i);return{phase:"red",testCode:`describe('${t}', () => {
|
|
1940
1940
|
it('${e}', () => {
|
|
1941
1941
|
// Red phase: This test should fail initially
|
|
1942
1942
|
${n}
|
|
@@ -2057,7 +2057,7 @@ ${t}
|
|
|
2057
2057
|
Return a JSON array of test suggestions, each with: { "name": "test name", "description": "what to test", "type": "unit|integration|edge" }`},{role:"user",content:`Analyze this ${r} code and suggest test cases:
|
|
2058
2058
|
\`\`\`${this.getCodeFenceLanguage(r)}
|
|
2059
2059
|
${t}
|
|
2060
|
-
\`\`\``}],model:i,maxTokens:1024,temperature:.5});if(n.content)try{let s=n.content.match(/\[[\s\S]*\]/);if(s)return E(s[0]).map(o=>o.name)}catch{}return[]}catch{return Za.warn("LLM suggestion generation failed:"),[]}}async generateTests(t){try{let e=Ul({sourceFiles:t.sourceFiles,language:t.language,framework:t.framework,projectRoot:t.projectRoot}),r=t.framework||e?.framework||"vitest",i=t.language||e?.language,{sourceFiles:n,testType:s,coverageTarget:a=this.config.coverageTargetDefault,patterns:o=[]}=t;if(n.length===0)return p(new Error("No source files provided"));let c=[],l=[];for(let m of n){let h=await this.generateTestsForFile(m,s,r,o,i,t);h.success&&(c.push(...h.value.tests),l.push(...h.value.patternsUsed))}if(process.env.AQE_HOLDOUT_TESTING_ENABLED==="true")for(let m of c)Lp(m.id)&&(m.holdout=!0);let d=this.estimateCoverage(c,a);return await this.storeGenerationMetadata(c,l),f({tests:c,coverageEstimate:d,patternsUsed:Array.from(new Set(l))})}catch(e){return p(y(e))}}async generateForCoverageGap(t,e,r){try{if(e.length===0)return f([]);let i=[],n=this.groupConsecutiveLines(e),s=this.generatorFactory.supports(r)?r:this.config.defaultFramework;for(let a of n){let o=await this.generateTestForLines(t,a,s);o&&i.push(o)}return f(i)}catch(i){return p(y(i))}}async generateTDDTests(t){try{let e=await this.tddGenerator.generateTDDTests(t);return f(e)}catch(e){return p(y(e))}}async generatePropertyTests(t){try{let e=await this.propertyTestGenerator.generatePropertyTests(t);return f(e)}catch(e){return p(y(e))}}async generateTestData(t){try{let e=await this.testDataGenerator.generateTestData(t);return f(e)}catch(e){return p(y(e))}}async generateTestsForFile(t,e,r,i,n,s){let a=this.getTestFilePath(t,r),o=[],c=await this.findApplicablePatterns(t,i);o.push(...c.map(P=>P.name));let l=null,d="";try{d=Xl.readFileSync(t,"utf-8"),l=await this.analyzeSourceCode(d,t)}catch{}let m,h;this.memory&&d&&await this.hasKGVectors()&&(m=await this.queryKGDependencies(t,d),h=await this.queryKGSimilarCode(d));let g=this.generatorFactory.create(r),b=this.extractModuleName(t),w=s?.importPathOverrides?.[t]??this.getImportPath(t),C={moduleName:b,importPath:w,testType:e,patterns:c,analysis:l??void 0,dependencies:m,similarCode:h},S=g.generateTests(C);this.isLLMEnhancementAvailable()&&d&&(S=await this.enhanceTestWithLLM(S,d,l,C));let k={id:v(),name:`${b} tests`,sourceFile:t,testFile:a,testCode:S,type:e,assertions:this.countAssertions(S),language:n,framework:r,llmEnhanced:this.isLLMEnhancementAvailable()};if(s?.compileValidation&&n)try{let P=await Kl.validate(S,n,s.projectRoot);k.compilationValidated=P.compiles,P.compiles||(k.compilationErrors=P.errors.map(O=>O.message))}catch{}return this.qualityGate&&(k.qualityGateResult=this.qualityGate.validate(S,t,d||void 0)),f({tests:[k],patternsUsed:o})}async generateTestForLines(t,e,r){if(e.length===0)return null;let i=v(),n=this.getTestFilePath(t,r),s=this.extractModuleName(t),a=this.getImportPath(t),c=this.generatorFactory.create(r).generateCoverageTests(s,a,e);return{id:i,name:`Coverage test for lines ${e[0]}-${e[e.length-1]}`,sourceFile:t,testFile:n,testCode:c,type:"unit",assertions:this.countAssertions(c)}}async analyzeSourceCode(t,e){let r=ni.extname(e),i=nt(r);if(i&&i!=="typescript"&&i!=="javascript"){let c=await Nr.parseFile(t,e,i);if(c)return at.convertParsedFile(c)}let n=x.createSourceFile(ni.basename(e),t,x.ScriptTarget.Latest,!0,x.ScriptKind.TS),s=[],a=[],o=c=>{if(x.isFunctionDeclaration(c)&&c.name)s.push(this.extractFunctionInfo(c,n));else if(x.isVariableStatement(c)){for(let l of c.declarationList.declarations)if(x.isVariableDeclaration(l)&&l.initializer&&(x.isArrowFunction(l.initializer)||x.isFunctionExpression(l.initializer))){let d=l.name.getText(n);s.push(this.extractArrowFunctionInfo(d,l.initializer,n,c))}}else x.isClassDeclaration(c)&&c.name&&a.push(this.extractClassInfo(c,n));x.forEachChild(c,o)};return x.forEachChild(n,o),{functions:s,classes:a}}extractFunctionInfo(t,e){let r=t.name?.getText(e)||"anonymous",i=this.extractParameters(t.parameters,e),n=t.type?.getText(e),s=t.modifiers?.some(l=>l.kind===x.SyntaxKind.AsyncKeyword)??!1,a=t.modifiers?.some(l=>l.kind===x.SyntaxKind.ExportKeyword)??!1,{line:o}=e.getLineAndCharacterOfPosition(t.getStart(e)),{line:c}=e.getLineAndCharacterOfPosition(t.getEnd());return{name:r,parameters:i,returnType:n,isAsync:s,isExported:a,complexity:this.calculateComplexity(t),startLine:o+1,endLine:c+1,body:t.body?.getText(e)}}extractArrowFunctionInfo(t,e,r,i){let n=this.extractParameters(e.parameters,r),s=e.type?.getText(r),a=e.modifiers?.some(d=>d.kind===x.SyntaxKind.AsyncKeyword)??!1,o=x.isVariableStatement(i)&&(i.modifiers?.some(d=>d.kind===x.SyntaxKind.ExportKeyword)??!1),{line:c}=r.getLineAndCharacterOfPosition(e.getStart(r)),{line:l}=r.getLineAndCharacterOfPosition(e.getEnd());return{name:t,parameters:n,returnType:s,isAsync:a,isExported:o,complexity:this.calculateComplexity(e),startLine:c+1,endLine:l+1,body:e.body?.getText(r)}}extractClassInfo(t,e){let r=t.name?.getText(e)||"AnonymousClass",i=[],n=[],s=!1,a,o=t.modifiers?.some(c=>c.kind===x.SyntaxKind.ExportKeyword)??!1;for(let c of t.members)if(x.isMethodDeclaration(c)){let l=c.name.getText(e),d=this.extractParameters(c.parameters,e),m=c.type?.getText(e),h=c.modifiers?.some(w=>w.kind===x.SyntaxKind.AsyncKeyword)??!1,{line:g}=e.getLineAndCharacterOfPosition(c.getStart(e)),{line:b}=e.getLineAndCharacterOfPosition(c.getEnd());i.push({name:l,parameters:d,returnType:m,isAsync:h,isExported:!1,complexity:this.calculateComplexity(c),startLine:g+1,endLine:b+1,body:c.body?.getText(e)})}else if(x.isConstructorDeclaration(c))s=!0,a=this.extractParameters(c.parameters,e);else if(x.isPropertyDeclaration(c)){let l=c.name.getText(e),d=c.type?.getText(e),m=c.modifiers?.some(g=>g.kind===x.SyntaxKind.PrivateKeyword)??!1,h=c.modifiers?.some(g=>g.kind===x.SyntaxKind.ReadonlyKeyword)??!1;n.push({name:l,type:d,isPrivate:m,isReadonly:h})}return{name:r,methods:i,properties:n,isExported:o,hasConstructor:s,constructorParams:a}}extractParameters(t,e){let r=0,i=0;return t.map(n=>{let s=n.name.getText(e),a=n.type?.getText(e);return x.isObjectBindingPattern(n.name)?(r++,s=r>1?`options${r}`:"options",a||(a=`{ ${n.name.elements.map(c=>`${c.name.getText(e)}: unknown`).join(", ")} }`)):x.isArrayBindingPattern(n.name)&&(i++,s=i>1?`items${i}`:"items",a||(a="unknown[]")),{name:s,type:a,optional:n.questionToken!==void 0,defaultValue:n.initializer?.getText(e)}})}calculateComplexity(t){let e=1,r=i=>{switch(i.kind){case x.SyntaxKind.IfStatement:case x.SyntaxKind.ForStatement:case x.SyntaxKind.ForInStatement:case x.SyntaxKind.ForOfStatement:case x.SyntaxKind.WhileStatement:case x.SyntaxKind.DoStatement:case x.SyntaxKind.CaseClause:case x.SyntaxKind.CatchClause:case x.SyntaxKind.ConditionalExpression:e++;break;case x.SyntaxKind.BinaryExpression:{let n=i;(n.operatorToken.kind===x.SyntaxKind.AmpersandAmpersandToken||n.operatorToken.kind===x.SyntaxKind.BarBarToken)&&e++;break}}x.forEachChild(i,r)};return x.forEachChild(t,r),e}async hasKGVectors(){try{let t=new Array(384).fill(0);return t[0]=1,(await this.memory.vectorSearch(t,1)).length>0}catch{return!1}}async queryKGDependencies(t,e){try{let r=[],i=[],n=[],s=[],a=e.matchAll(/(?:import|from)\s+['"]([^'"]+)['"]/g);for(let m of a)r.push(m[1]);if(t.endsWith(".py")){let m=e.matchAll(/(?:^|\n)\s*(?:from\s+(\S+)\s+import|import\s+(\S+))/g);for(let h of m){let g=h[1]||h[2];g&&/^[a-zA-Z_][\w.]*$/.test(g)&&r.push(g)}}let l=t.replace(/\\/g,"/").split("/").pop()?.replace(/\.(ts|js|tsx|jsx|py)$/,"")||"",d=await this.memory.search(`code-intelligence:kg:node:*${l}*`,50);for(let m of d){if(!m.includes(l))continue;let h=m.split(":"),g=h[h.length-2],b=h[h.length-1];g==="function"&&n.push(b)}return r.length===0&&i.length===0&&n.length===0&&s.length===0?void 0:{imports:r,importedBy:i,callees:n,callers:s}}catch{return}}async queryKGSimilarCode(t){try{let e=this.generatePseudoEmbedding(t),r=await this.memory.vectorSearch(e,5);if(r.length===0)return;let i=[];for(let n of r){if(n.score<.1)continue;let s=n.metadata,a=s?.file||n.key,o=s?.name||s?.type||n.key.split(":").pop()||"";i.push({file:a,snippet:o,score:n.score})}return i.length>0?{snippets:i}:void 0}catch{return}}generatePseudoEmbedding(t){let r=new Array(384).fill(0),i=t.split(/[^a-zA-Z0-9_$]+/).filter(s=>s.length>1);for(let s=0;s<i.length;s++){let a=i[s];for(let o=0;o<a.length&&o<r.length;o++)r[(s+o)%384]+=a.charCodeAt(o)/1e3}let n=Math.sqrt(r.reduce((s,a)=>s+a*a,0));if(n>0)for(let s=0;s<384;s++)r[s]/=n;return r}getCodeFenceLanguage(t){try{let{FRAMEWORK_TO_LANGUAGE:e}=(er(),Xt(_l)),r=e?.[t];if(r){let i=Yl(r);if(i)return i.codeFenceLanguage}}catch{}return"typescript"}convertParsedToCodeAnalysis(t){return at.convertParsedFile(t)}async findApplicablePatterns(t,e){let r=[];try{let{getUnifiedMemory:i}=await import("./unified-memory-
|
|
2060
|
+
\`\`\``}],model:i,maxTokens:1024,temperature:.5});if(n.content)try{let s=n.content.match(/\[[\s\S]*\]/);if(s)return E(s[0]).map(o=>o.name)}catch{}return[]}catch{return Za.warn("LLM suggestion generation failed:"),[]}}async generateTests(t){try{let e=Ul({sourceFiles:t.sourceFiles,language:t.language,framework:t.framework,projectRoot:t.projectRoot}),r=t.framework||e?.framework||"vitest",i=t.language||e?.language,{sourceFiles:n,testType:s,coverageTarget:a=this.config.coverageTargetDefault,patterns:o=[]}=t;if(n.length===0)return p(new Error("No source files provided"));let c=[],l=[];for(let m of n){let h=await this.generateTestsForFile(m,s,r,o,i,t);h.success&&(c.push(...h.value.tests),l.push(...h.value.patternsUsed))}if(process.env.AQE_HOLDOUT_TESTING_ENABLED==="true")for(let m of c)Lp(m.id)&&(m.holdout=!0);let d=this.estimateCoverage(c,a);return await this.storeGenerationMetadata(c,l),f({tests:c,coverageEstimate:d,patternsUsed:Array.from(new Set(l))})}catch(e){return p(y(e))}}async generateForCoverageGap(t,e,r){try{if(e.length===0)return f([]);let i=[],n=this.groupConsecutiveLines(e),s=this.generatorFactory.supports(r)?r:this.config.defaultFramework;for(let a of n){let o=await this.generateTestForLines(t,a,s);o&&i.push(o)}return f(i)}catch(i){return p(y(i))}}async generateTDDTests(t){try{let e=await this.tddGenerator.generateTDDTests(t);return f(e)}catch(e){return p(y(e))}}async generatePropertyTests(t){try{let e=await this.propertyTestGenerator.generatePropertyTests(t);return f(e)}catch(e){return p(y(e))}}async generateTestData(t){try{let e=await this.testDataGenerator.generateTestData(t);return f(e)}catch(e){return p(y(e))}}async generateTestsForFile(t,e,r,i,n,s){let a=this.getTestFilePath(t,r),o=[],c=await this.findApplicablePatterns(t,i);o.push(...c.map(P=>P.name));let l=null,d="";try{d=Xl.readFileSync(t,"utf-8"),l=await this.analyzeSourceCode(d,t)}catch{}let m,h;this.memory&&d&&await this.hasKGVectors()&&(m=await this.queryKGDependencies(t,d),h=await this.queryKGSimilarCode(d));let g=this.generatorFactory.create(r),b=this.extractModuleName(t),w=s?.importPathOverrides?.[t]??this.getImportPath(t),C={moduleName:b,importPath:w,testType:e,patterns:c,analysis:l??void 0,dependencies:m,similarCode:h},S=g.generateTests(C);this.isLLMEnhancementAvailable()&&d&&(S=await this.enhanceTestWithLLM(S,d,l,C));let k={id:v(),name:`${b} tests`,sourceFile:t,testFile:a,testCode:S,type:e,assertions:this.countAssertions(S),language:n,framework:r,llmEnhanced:this.isLLMEnhancementAvailable()};if(s?.compileValidation&&n)try{let P=await Kl.validate(S,n,s.projectRoot);k.compilationValidated=P.compiles,P.compiles||(k.compilationErrors=P.errors.map(O=>O.message))}catch{}return this.qualityGate&&(k.qualityGateResult=this.qualityGate.validate(S,t,d||void 0)),f({tests:[k],patternsUsed:o})}async generateTestForLines(t,e,r){if(e.length===0)return null;let i=v(),n=this.getTestFilePath(t,r),s=this.extractModuleName(t),a=this.getImportPath(t),c=this.generatorFactory.create(r).generateCoverageTests(s,a,e);return{id:i,name:`Coverage test for lines ${e[0]}-${e[e.length-1]}`,sourceFile:t,testFile:n,testCode:c,type:"unit",assertions:this.countAssertions(c)}}async analyzeSourceCode(t,e){let r=ni.extname(e),i=nt(r);if(i&&i!=="typescript"&&i!=="javascript"){let c=await Nr.parseFile(t,e,i);if(c)return at.convertParsedFile(c)}let n=x.createSourceFile(ni.basename(e),t,x.ScriptTarget.Latest,!0,x.ScriptKind.TS),s=[],a=[],o=c=>{if(x.isFunctionDeclaration(c)&&c.name)s.push(this.extractFunctionInfo(c,n));else if(x.isVariableStatement(c)){for(let l of c.declarationList.declarations)if(x.isVariableDeclaration(l)&&l.initializer&&(x.isArrowFunction(l.initializer)||x.isFunctionExpression(l.initializer))){let d=l.name.getText(n);s.push(this.extractArrowFunctionInfo(d,l.initializer,n,c))}}else x.isClassDeclaration(c)&&c.name&&a.push(this.extractClassInfo(c,n));x.forEachChild(c,o)};return x.forEachChild(n,o),{functions:s,classes:a}}extractFunctionInfo(t,e){let r=t.name?.getText(e)||"anonymous",i=this.extractParameters(t.parameters,e),n=t.type?.getText(e),s=t.modifiers?.some(l=>l.kind===x.SyntaxKind.AsyncKeyword)??!1,a=t.modifiers?.some(l=>l.kind===x.SyntaxKind.ExportKeyword)??!1,{line:o}=e.getLineAndCharacterOfPosition(t.getStart(e)),{line:c}=e.getLineAndCharacterOfPosition(t.getEnd());return{name:r,parameters:i,returnType:n,isAsync:s,isExported:a,complexity:this.calculateComplexity(t),startLine:o+1,endLine:c+1,body:t.body?.getText(e)}}extractArrowFunctionInfo(t,e,r,i){let n=this.extractParameters(e.parameters,r),s=e.type?.getText(r),a=e.modifiers?.some(d=>d.kind===x.SyntaxKind.AsyncKeyword)??!1,o=x.isVariableStatement(i)&&(i.modifiers?.some(d=>d.kind===x.SyntaxKind.ExportKeyword)??!1),{line:c}=r.getLineAndCharacterOfPosition(e.getStart(r)),{line:l}=r.getLineAndCharacterOfPosition(e.getEnd());return{name:t,parameters:n,returnType:s,isAsync:a,isExported:o,complexity:this.calculateComplexity(e),startLine:c+1,endLine:l+1,body:e.body?.getText(r)}}extractClassInfo(t,e){let r=t.name?.getText(e)||"AnonymousClass",i=[],n=[],s=!1,a,o=t.modifiers?.some(c=>c.kind===x.SyntaxKind.ExportKeyword)??!1;for(let c of t.members)if(x.isMethodDeclaration(c)){let l=c.name.getText(e),d=this.extractParameters(c.parameters,e),m=c.type?.getText(e),h=c.modifiers?.some(w=>w.kind===x.SyntaxKind.AsyncKeyword)??!1,{line:g}=e.getLineAndCharacterOfPosition(c.getStart(e)),{line:b}=e.getLineAndCharacterOfPosition(c.getEnd());i.push({name:l,parameters:d,returnType:m,isAsync:h,isExported:!1,complexity:this.calculateComplexity(c),startLine:g+1,endLine:b+1,body:c.body?.getText(e)})}else if(x.isConstructorDeclaration(c))s=!0,a=this.extractParameters(c.parameters,e);else if(x.isPropertyDeclaration(c)){let l=c.name.getText(e),d=c.type?.getText(e),m=c.modifiers?.some(g=>g.kind===x.SyntaxKind.PrivateKeyword)??!1,h=c.modifiers?.some(g=>g.kind===x.SyntaxKind.ReadonlyKeyword)??!1;n.push({name:l,type:d,isPrivate:m,isReadonly:h})}return{name:r,methods:i,properties:n,isExported:o,hasConstructor:s,constructorParams:a}}extractParameters(t,e){let r=0,i=0;return t.map(n=>{let s=n.name.getText(e),a=n.type?.getText(e);return x.isObjectBindingPattern(n.name)?(r++,s=r>1?`options${r}`:"options",a||(a=`{ ${n.name.elements.map(c=>`${c.name.getText(e)}: unknown`).join(", ")} }`)):x.isArrayBindingPattern(n.name)&&(i++,s=i>1?`items${i}`:"items",a||(a="unknown[]")),{name:s,type:a,optional:n.questionToken!==void 0,defaultValue:n.initializer?.getText(e)}})}calculateComplexity(t){let e=1,r=i=>{switch(i.kind){case x.SyntaxKind.IfStatement:case x.SyntaxKind.ForStatement:case x.SyntaxKind.ForInStatement:case x.SyntaxKind.ForOfStatement:case x.SyntaxKind.WhileStatement:case x.SyntaxKind.DoStatement:case x.SyntaxKind.CaseClause:case x.SyntaxKind.CatchClause:case x.SyntaxKind.ConditionalExpression:e++;break;case x.SyntaxKind.BinaryExpression:{let n=i;(n.operatorToken.kind===x.SyntaxKind.AmpersandAmpersandToken||n.operatorToken.kind===x.SyntaxKind.BarBarToken)&&e++;break}}x.forEachChild(i,r)};return x.forEachChild(t,r),e}async hasKGVectors(){try{let t=new Array(384).fill(0);return t[0]=1,(await this.memory.vectorSearch(t,1)).length>0}catch{return!1}}async queryKGDependencies(t,e){try{let r=[],i=[],n=[],s=[],a=e.matchAll(/(?:import|from)\s+['"]([^'"]+)['"]/g);for(let m of a)r.push(m[1]);if(t.endsWith(".py")){let m=e.matchAll(/(?:^|\n)\s*(?:from\s+(\S+)\s+import|import\s+(\S+))/g);for(let h of m){let g=h[1]||h[2];g&&/^[a-zA-Z_][\w.]*$/.test(g)&&r.push(g)}}let l=t.replace(/\\/g,"/").split("/").pop()?.replace(/\.(ts|js|tsx|jsx|py)$/,"")||"",d=await this.memory.search(`code-intelligence:kg:node:*${l}*`,50,{namespace:"code-intelligence:kg"});for(let m of d){if(!m.includes(l))continue;let h=m.split(":"),g=h[h.length-2],b=h[h.length-1];g==="function"&&n.push(b)}return r.length===0&&i.length===0&&n.length===0&&s.length===0?void 0:{imports:r,importedBy:i,callees:n,callers:s}}catch{return}}async queryKGSimilarCode(t){try{let e=this.generatePseudoEmbedding(t),r=await this.memory.vectorSearch(e,5);if(r.length===0)return;let i=[];for(let n of r){if(n.score<.1)continue;let s=n.metadata,a=s?.file||n.key,o=s?.name||s?.type||n.key.split(":").pop()||"";i.push({file:a,snippet:o,score:n.score})}return i.length>0?{snippets:i}:void 0}catch{return}}generatePseudoEmbedding(t){let r=new Array(384).fill(0),i=t.split(/[^a-zA-Z0-9_$]+/).filter(s=>s.length>1);for(let s=0;s<i.length;s++){let a=i[s];for(let o=0;o<a.length&&o<r.length;o++)r[(s+o)%384]+=a.charCodeAt(o)/1e3}let n=Math.sqrt(r.reduce((s,a)=>s+a*a,0));if(n>0)for(let s=0;s<384;s++)r[s]/=n;return r}getCodeFenceLanguage(t){try{let{FRAMEWORK_TO_LANGUAGE:e}=(er(),Xt(_l)),r=e?.[t];if(r){let i=Yl(r);if(i)return i.codeFenceLanguage}}catch{}return"typescript"}convertParsedToCodeAnalysis(t){return at.convertParsedFile(t)}async findApplicablePatterns(t,e){let r=[];try{let{getUnifiedMemory:i}=await import("./unified-memory-QG3FDRKR.js"),n=i().getDatabase();for(let o of e){let c=n.prepare(`SELECT id, name, description, pattern_type, usage_count, quality_score
|
|
2061
2061
|
FROM qe_patterns WHERE id = ? OR name = ? LIMIT 1`).get(o,o);c&&r.push({id:c.id,name:c.name,structure:c.pattern_type,examples:c.usage_count,applicability:c.quality_score})}let s=t.split(".").pop()||"",a=n.prepare(`SELECT id, name, description, pattern_type, usage_count, quality_score
|
|
2062
2062
|
FROM qe_patterns
|
|
2063
2063
|
WHERE qe_domain = 'test-generation'
|
|
@@ -2095,7 +2095,7 @@ ${t}
|
|
|
2095
2095
|
}));`,examples:1,applicability:.7}),/jest\.fn\(/.test(t)&&e.push({id:v(),name:"Jest function mock pattern",structure:"const {{mockName}} = jest.fn().mockReturnValue({{returnValue}});",examples:1,applicability:.7}),/vi\.mock\(/.test(t)&&e.push({id:v(),name:"Vitest module mock pattern",structure:`vi.mock('{{modulePath}}', () => ({
|
|
2096
2096
|
{{mockImplementation}}
|
|
2097
2097
|
}));`,examples:1,applicability:.7}),/vi\.fn\(/.test(t)&&e.push({id:v(),name:"Vitest function mock pattern",structure:"const {{mockName}} = vi.fn().mockReturnValue({{returnValue}});",examples:1,applicability:.7}),/(?:jest|vi)\.spyOn\(/.test(t)&&e.push({id:v(),name:"SpyOn pattern",structure:"const spy = {{framework}}.spyOn({{object}}, '{{method}}').mockImplementation({{impl}});",examples:1,applicability:.6}),e}extractBlockContent(t,e){let r=0,i=e,n=!1;for(let s=e;s<t.length;s++){let a=t[s];if(a==="{")r++,n=!0;else if(a==="}"&&(r--,n&&r===0)){i=s;break}}return i>e?t.substring(e,i+1):null}deduplicatePatterns(t){let e=new Map;for(let r of t){let i=this.hashStructure(r.structure);if(!e.has(i))e.set(i,r);else{let n=e.get(i);n.examples+=r.examples}}return Array.from(e.values())}hashStructure(t){let e=t.replace(/\s+/g," ").trim(),r=0;for(let i=0;i<e.length;i++){let n=e.charCodeAt(i);r=(r<<5)-r+n,r=r&r}return r.toString(16)}calculateLearningConfidence(t){if(t.length===0)return 0;let e=t.reduce((n,s)=>n+s.examples,0)/t.length,r=Math.min(1,t.length/10),i=Math.min(1,e/5);return r*.5+i*.5}async generatePatternEmbedding(t){let e=this.formatPatternForEmbedding(t);return this.embedder.embed(e)}async generateQueryEmbedding(t){return this.embedder.embed(t)}formatPatternForEmbedding(t){return[`Pattern: ${t.name}`,t.description?`Description: ${t.description}`:"",`Structure: ${t.structure}`,t.tags?.length?`Tags: ${t.tags.join(", ")}`:"",t.testType?`Test type: ${t.testType}`:"",t.framework?`Framework: ${t.framework}`:""].filter(Boolean).join(`
|
|
2098
|
-
`)}},oi=class{sourceFile=null;sourceCode="";parseFile(t,e){return e?this.sourceCode=e:this.sourceCode=xn.readFileSync(t,"utf-8"),this.sourceFile=x.createSourceFile(Pn.basename(t),this.sourceCode,x.ScriptTarget.Latest,!0,x.ScriptKind.TS),this.sourceFile}parseSource(t,e="module.ts"){return this.sourceCode=t,this.sourceFile=x.createSourceFile(e,t,x.ScriptTarget.Latest,!0,x.ScriptKind.TS),this.sourceFile}extractFunctions(t){let e=[],r=i=>{if(x.isFunctionDeclaration(i)&&i.name)e.push(this.extractFunctionInfo(i,t));else if(x.isVariableStatement(i)){for(let n of i.declarationList.declarations)if(x.isVariableDeclaration(n)&&n.initializer&&(x.isArrowFunction(n.initializer)||x.isFunctionExpression(n.initializer))){let s=n.name.getText(t);e.push(this.extractArrowFunctionInfo(s,n.initializer,t,i))}}x.forEachChild(i,r)};return x.forEachChild(t,r),e}extractClasses(t){let e=[],r=i=>{x.isClassDeclaration(i)&&i.name&&e.push(this.extractClassInfo(i,t)),x.forEachChild(i,r)};return x.forEachChild(t,r),e}extractFunctionInfo(t,e){let r=t.name?.getText(e)||"anonymous",i=this.extractParameters(t.parameters,e),n=t.type?.getText(e),s=t.modifiers?.some(d=>d.kind===x.SyntaxKind.AsyncKeyword)??!1,a=t.modifiers?.some(d=>d.kind===x.SyntaxKind.ExportKeyword)??!1,{line:o}=e.getLineAndCharacterOfPosition(t.getStart(e)),{line:c}=e.getLineAndCharacterOfPosition(t.getEnd()),l=this.calculateCyclomaticComplexity(t);return{name:r,parameters:i,returnType:n,isAsync:s,isExported:a,complexity:l,startLine:o+1,endLine:c+1,body:t.body?.getText(e)}}extractArrowFunctionInfo(t,e,r,i){let n=this.extractParameters(e.parameters,r),s=e.type?.getText(r),a=e.modifiers?.some(m=>m.kind===x.SyntaxKind.AsyncKeyword)??!1,o=x.isVariableStatement(i)&&(i.modifiers?.some(m=>m.kind===x.SyntaxKind.ExportKeyword)??!1),{line:c}=r.getLineAndCharacterOfPosition(e.getStart(r)),{line:l}=r.getLineAndCharacterOfPosition(e.getEnd()),d=this.calculateCyclomaticComplexity(e);return{name:t,parameters:n,returnType:s,isAsync:a,isExported:o,complexity:d,startLine:c+1,endLine:l+1,body:e.body?.getText(r)}}extractClassInfo(t,e){let r=t.name?.getText(e)||"AnonymousClass",i=[],n=[],s=!1,a=t.modifiers?.some(l=>l.kind===x.SyntaxKind.ExportKeyword)??!1;for(let l of t.members)if(x.isMethodDeclaration(l)){let d=l.name.getText(e),m=this.extractParameters(l.parameters,e),h=l.type?.getText(e),g=l.modifiers?.some(C=>C.kind===x.SyntaxKind.AsyncKeyword)??!1,{line:b}=e.getLineAndCharacterOfPosition(l.getStart(e)),{line:w}=e.getLineAndCharacterOfPosition(l.getEnd());i.push({name:d,parameters:m,returnType:h,isAsync:g,isExported:!1,complexity:this.calculateCyclomaticComplexity(l),startLine:b+1,endLine:w+1,body:l.body?.getText(e)})}else if(x.isConstructorDeclaration(l))s=!0;else if(x.isPropertyDeclaration(l)){let d=l.name.getText(e),m=l.type?.getText(e),h=l.modifiers?.some(b=>b.kind===x.SyntaxKind.PrivateKeyword)??!1,g=l.modifiers?.some(b=>b.kind===x.SyntaxKind.ReadonlyKeyword)??!1;n.push({name:d,type:m,isPrivate:h,isReadonly:g})}let{line:o}=e.getLineAndCharacterOfPosition(t.getStart(e)),{line:c}=e.getLineAndCharacterOfPosition(t.getEnd());return{name:r,methods:i,properties:n,isExported:a,hasConstructor:s,startLine:o+1,endLine:c+1}}extractParameters(t,e){let r=0,i=0;return t.map(n=>{let s=n.name.getText(e),a=n.type?.getText(e);return x.isObjectBindingPattern(n.name)?(r++,s=r>1?`options${r}`:"options",a||(a=`{ ${n.name.elements.map(c=>`${c.name.getText(e)}: unknown`).join(", ")} }`)):x.isArrayBindingPattern(n.name)&&(i++,s=i>1?`items${i}`:"items",a||(a="unknown[]")),{name:s,type:a,optional:n.questionToken!==void 0,defaultValue:n.initializer?.getText(e)}})}calculateCyclomaticComplexity(t){let e=1,r=i=>{switch(i.kind){case x.SyntaxKind.IfStatement:case x.SyntaxKind.ForStatement:case x.SyntaxKind.ForInStatement:case x.SyntaxKind.ForOfStatement:case x.SyntaxKind.WhileStatement:case x.SyntaxKind.DoStatement:case x.SyntaxKind.CaseClause:case x.SyntaxKind.CatchClause:case x.SyntaxKind.ConditionalExpression:case x.SyntaxKind.QuestionQuestionToken:e++;break;case x.SyntaxKind.BinaryExpression:let n=i;(n.operatorToken.kind===x.SyntaxKind.AmpersandAmpersandToken||n.operatorToken.kind===x.SyntaxKind.BarBarToken)&&e++;break}x.forEachChild(i,r)};return x.forEachChild(t,r),e}};M();var Np={enableMinCutAwareness:!0,topologyHealthThreshold:.7,pauseOnCriticalTopology:!1,monitoredDomains:[]},to=100,ro=class{bridge=null;config;domainName;healthListeners=new Set;lastHealthStatus=null;healthCheckInterval=null;constructor(t,e={}){this.domainName=t,this.config={...Np,...e}}setMinCutBridge(t){this.bridge&&this.stopHealthMonitoring(),this.bridge=t,this.config.enableMinCutAwareness&&this.healthListeners.size>0&&this.startHealthMonitoring()}getMinCutBridge(){return this.bridge}hasBridge(){return this.bridge!==null}getDomainName(){return this.domainName}getConfig(){return{...this.config}}updateConfig(t){Object.assign(this.config,t),"enableMinCutAwareness"in t&&(t.enableMinCutAwareness&&this.bridge&&this.healthListeners.size>0?this.startHealthMonitoring():this.stopHealthMonitoring())}dispose(){this.stopHealthMonitoring(),this.healthListeners.clear(),this.bridge=null,this.lastHealthStatus=null}isTopologyHealthy(){return!this.config.enableMinCutAwareness||!this.bridge?!0:this.bridge.getMinCutHealth().status!=="critical"}getDomainWeakVertices(){return this.bridge?this.bridge.getWeakVertices().filter(e=>e.vertex.domain===this.domainName):[]}isDomainWeakPoint(){return this.getDomainWeakVertices().length>0}getTopologyBasedRouting(t){if(!this.config.enableMinCutAwareness||!this.bridge)return t;let e=this.bridge.getWeakVertices(),r=new Set;for(let i of e)i.vertex.domain&&r.add(i.vertex.domain);return t.filter(i=>!r.has(i))}onTopologyHealthChange(t){if(this.healthListeners.size>=to)throw console.error(`[MinCutAwareDomain] Max health listeners (${to}) reached for ${this.domainName}. Ensure listeners are properly unsubscribed.`),new Error(`Max health listeners (${to}) exceeded`);return this.healthListeners.add(t),this.healthListeners.size===1&&this.bridge&&this.config.enableMinCutAwareness&&this.startHealthMonitoring(),()=>{this.healthListeners.delete(t),this.healthListeners.size===0&&this.stopHealthMonitoring()}}getCurrentHealth(){return this.bridge?this.bridge.getMinCutHealth():null}getMinCutValue(){return this.bridge?this.bridge.getMinCutValue():null}shouldPauseOperations(){return this.config.pauseOnCriticalTopology?!this.isTopologyHealthy():!1}getHealthyRoutingDomains(){let t=this.config.monitoredDomains.length>0?this.config.monitoredDomains:this.getAllDomains();return this.getTopologyBasedRouting(t)}getNormalizedHealthScore(){if(!this.bridge)return 1;let t=this.bridge.getMinCutHealth();return t.healthyThreshold<=0?t.minCutValue>0?1:0:Math.min(1,t.minCutValue/t.healthyThreshold)}meetsHealthThreshold(){return this.getNormalizedHealthScore()>=this.config.topologyHealthThreshold}startHealthMonitoring(){this.healthCheckInterval||(this.healthCheckInterval=setInterval(()=>{this.checkAndNotifyHealthChange()},5e3),this.checkAndNotifyHealthChange())}stopHealthMonitoring(){this.healthCheckInterval&&(clearInterval(this.healthCheckInterval),this.healthCheckInterval=null)}checkAndNotifyHealthChange(){if(!this.bridge)return;let t=this.bridge.getMinCutHealth();if(t.status!==this.lastHealthStatus){this.lastHealthStatus=t.status;for(let e of this.healthListeners)try{e(t)}catch(r){console.error("Error in health change listener:",r)}}}getAllDomains(){return["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","requirements-validation","code-intelligence","security-compliance","contract-testing","visual-accessibility","chaos-resilience","learning-optimization","coordination"]}};function Zl(u,t){return new ro(u,t)}var kt={defaultThreshold:2/3,minModels:2,maxModels:3,defaultModelTimeout:3e4,defaultRetries:2,verifySeverities:["critical","high"],enableCache:!0,cacheTtlMs:36e5,enableCostTracking:!0,maxCostPerVerification:.5,humanReviewThreshold:.6,enableSycophancyCheck:!0};Le();Le();co();mo();ho();vo();To();Le();A();function Fn(u={}){let t=li(),e=u.enableLogging||!1;if(u.claude)try{let{createClaudeProvider:r}=(co(),Xt(ru)),i=r({...u.claude,enableLogging:u.claude.enableLogging??e});t.register(i)}catch(r){e&&console.warn(`[Providers] Failed to register Claude provider: ${r}`)}if(u.openai)try{let{createOpenAIProvider:r}=(mo(),Xt(nu)),i=r({...u.openai,enableLogging:u.openai.enableLogging??e});t.register(i)}catch(r){e&&console.warn(`[Providers] Failed to register OpenAI provider: ${r}`)}if(u.gemini)try{let{createGeminiProvider:r}=(ho(),Xt(su)),i=r({...u.gemini,enableLogging:u.gemini.enableLogging??e});t.register(i)}catch(r){e&&console.warn(`[Providers] Failed to register Gemini provider: ${r}`)}if(u.openrouter)try{let{createOpenRouterProvider:r,createMultiModelProviders:i}=(vo(),Xt(au));if(u.openrouter.multiModel&&u.openrouter.models){let n=i(u.openrouter.models);for(let s of n)t.register(s)}else{let n=r({apiKey:u.openrouter.apiKey,defaultModel:u.openrouter.defaultModel,enableLogging:u.openrouter.enableLogging??e});t.register(n)}}catch(r){e&&console.warn(`[Providers] Failed to register OpenRouter provider: ${r}`)}if(u.ollama)try{let{createOllamaProvider:r}=(To(),Xt(ou)),i=r({baseUrl:u.ollama.baseUrl,defaultModel:u.ollama.defaultModel,enableLogging:u.ollama.enableLogging??e});t.register(i)}catch(r){e&&console.warn(`[Providers] Failed to register Ollama provider: ${r}`)}return t}function Mt(u=!1){let t={enableLogging:u};return process.env.ANTHROPIC_API_KEY&&(t.claude={apiKey:process.env.ANTHROPIC_API_KEY}),process.env.OPENAI_API_KEY&&(t.openai={apiKey:process.env.OPENAI_API_KEY,organization:process.env.OPENAI_ORGANIZATION}),process.env.GOOGLE_API_KEY&&(t.gemini={apiKey:process.env.GOOGLE_API_KEY}),process.env.OPENROUTER_API_KEY&&(t.openrouter={apiKey:process.env.OPENROUTER_API_KEY}),process.env.OLLAMA_HOST&&(t.ollama={baseUrl:process.env.OLLAMA_HOST}),Fn(t)}var ui=class{config;constructor(t={}){this.config={minVotes:t.minVotes??2,humanReviewThreshold:t.humanReviewThreshold??.6,agreementThreshold:t.agreementThreshold??.5}}apply(t){if(t.length<this.config.minVotes)return{verdict:"insufficient",confidence:0,agreementRatio:0,reasoning:`Insufficient votes: ${t.length} received, ${this.config.minVotes} required`,requiresHumanReview:!0};let e=t.filter(l=>!l.error);if(e.length===0)return{verdict:"error",confidence:0,agreementRatio:0,reasoning:"All model votes resulted in errors",requiresHumanReview:!0};let r=e.filter(l=>l.agrees).length,i=e.length,n=r/i,s=e.reduce((l,d)=>l+d.confidence,0)/i,a;n>this.config.agreementThreshold?a="verified":n<1-this.config.agreementThreshold?a="rejected":a="disputed";let o=this.synthesizeReasoning(e,r,i),c=s<this.config.humanReviewThreshold||a==="disputed";return{verdict:a,confidence:s,agreementRatio:n,reasoning:o,requiresHumanReview:c}}synthesizeReasoning(t,e,r){let i=[];i.push(`Majority consensus reached: ${e}/${r} models agree.`);let n=t.filter(a=>a.agrees).map(a=>`- ${a.modelId}: ${a.reasoning}`),s=t.filter(a=>!a.agrees).map(a=>`- ${a.modelId}: ${a.reasoning}`);return n.length>0&&(i.push(`
|
|
2098
|
+
`)}},oi=class{sourceFile=null;sourceCode="";parseFile(t,e){return e?this.sourceCode=e:this.sourceCode=xn.readFileSync(t,"utf-8"),this.sourceFile=x.createSourceFile(Pn.basename(t),this.sourceCode,x.ScriptTarget.Latest,!0,x.ScriptKind.TS),this.sourceFile}parseSource(t,e="module.ts"){return this.sourceCode=t,this.sourceFile=x.createSourceFile(e,t,x.ScriptTarget.Latest,!0,x.ScriptKind.TS),this.sourceFile}extractFunctions(t){let e=[],r=i=>{if(x.isFunctionDeclaration(i)&&i.name)e.push(this.extractFunctionInfo(i,t));else if(x.isVariableStatement(i)){for(let n of i.declarationList.declarations)if(x.isVariableDeclaration(n)&&n.initializer&&(x.isArrowFunction(n.initializer)||x.isFunctionExpression(n.initializer))){let s=n.name.getText(t);e.push(this.extractArrowFunctionInfo(s,n.initializer,t,i))}}x.forEachChild(i,r)};return x.forEachChild(t,r),e}extractClasses(t){let e=[],r=i=>{x.isClassDeclaration(i)&&i.name&&e.push(this.extractClassInfo(i,t)),x.forEachChild(i,r)};return x.forEachChild(t,r),e}extractFunctionInfo(t,e){let r=t.name?.getText(e)||"anonymous",i=this.extractParameters(t.parameters,e),n=t.type?.getText(e),s=t.modifiers?.some(d=>d.kind===x.SyntaxKind.AsyncKeyword)??!1,a=t.modifiers?.some(d=>d.kind===x.SyntaxKind.ExportKeyword)??!1,{line:o}=e.getLineAndCharacterOfPosition(t.getStart(e)),{line:c}=e.getLineAndCharacterOfPosition(t.getEnd()),l=this.calculateCyclomaticComplexity(t);return{name:r,parameters:i,returnType:n,isAsync:s,isExported:a,complexity:l,startLine:o+1,endLine:c+1,body:t.body?.getText(e)}}extractArrowFunctionInfo(t,e,r,i){let n=this.extractParameters(e.parameters,r),s=e.type?.getText(r),a=e.modifiers?.some(m=>m.kind===x.SyntaxKind.AsyncKeyword)??!1,o=x.isVariableStatement(i)&&(i.modifiers?.some(m=>m.kind===x.SyntaxKind.ExportKeyword)??!1),{line:c}=r.getLineAndCharacterOfPosition(e.getStart(r)),{line:l}=r.getLineAndCharacterOfPosition(e.getEnd()),d=this.calculateCyclomaticComplexity(e);return{name:t,parameters:n,returnType:s,isAsync:a,isExported:o,complexity:d,startLine:c+1,endLine:l+1,body:e.body?.getText(r)}}extractClassInfo(t,e){let r=t.name?.getText(e)||"AnonymousClass",i=[],n=[],s=!1,a=t.modifiers?.some(l=>l.kind===x.SyntaxKind.ExportKeyword)??!1;for(let l of t.members)if(x.isMethodDeclaration(l)){let d=l.name.getText(e),m=this.extractParameters(l.parameters,e),h=l.type?.getText(e),g=l.modifiers?.some(C=>C.kind===x.SyntaxKind.AsyncKeyword)??!1,{line:b}=e.getLineAndCharacterOfPosition(l.getStart(e)),{line:w}=e.getLineAndCharacterOfPosition(l.getEnd());i.push({name:d,parameters:m,returnType:h,isAsync:g,isExported:!1,complexity:this.calculateCyclomaticComplexity(l),startLine:b+1,endLine:w+1,body:l.body?.getText(e)})}else if(x.isConstructorDeclaration(l))s=!0;else if(x.isPropertyDeclaration(l)){let d=l.name.getText(e),m=l.type?.getText(e),h=l.modifiers?.some(b=>b.kind===x.SyntaxKind.PrivateKeyword)??!1,g=l.modifiers?.some(b=>b.kind===x.SyntaxKind.ReadonlyKeyword)??!1;n.push({name:d,type:m,isPrivate:h,isReadonly:g})}let{line:o}=e.getLineAndCharacterOfPosition(t.getStart(e)),{line:c}=e.getLineAndCharacterOfPosition(t.getEnd());return{name:r,methods:i,properties:n,isExported:a,hasConstructor:s,startLine:o+1,endLine:c+1}}extractParameters(t,e){let r=0,i=0;return t.map(n=>{let s=n.name.getText(e),a=n.type?.getText(e);return x.isObjectBindingPattern(n.name)?(r++,s=r>1?`options${r}`:"options",a||(a=`{ ${n.name.elements.map(c=>`${c.name.getText(e)}: unknown`).join(", ")} }`)):x.isArrayBindingPattern(n.name)&&(i++,s=i>1?`items${i}`:"items",a||(a="unknown[]")),{name:s,type:a,optional:n.questionToken!==void 0,defaultValue:n.initializer?.getText(e)}})}calculateCyclomaticComplexity(t){let e=1,r=i=>{switch(i.kind){case x.SyntaxKind.IfStatement:case x.SyntaxKind.ForStatement:case x.SyntaxKind.ForInStatement:case x.SyntaxKind.ForOfStatement:case x.SyntaxKind.WhileStatement:case x.SyntaxKind.DoStatement:case x.SyntaxKind.CaseClause:case x.SyntaxKind.CatchClause:case x.SyntaxKind.ConditionalExpression:case x.SyntaxKind.QuestionQuestionToken:e++;break;case x.SyntaxKind.BinaryExpression:{let n=i;(n.operatorToken.kind===x.SyntaxKind.AmpersandAmpersandToken||n.operatorToken.kind===x.SyntaxKind.BarBarToken)&&e++;break}}x.forEachChild(i,r)};return x.forEachChild(t,r),e}};M();var Np={enableMinCutAwareness:!0,topologyHealthThreshold:.7,pauseOnCriticalTopology:!1,monitoredDomains:[]},to=100,ro=class{bridge=null;config;domainName;healthListeners=new Set;lastHealthStatus=null;healthCheckInterval=null;constructor(t,e={}){this.domainName=t,this.config={...Np,...e}}setMinCutBridge(t){this.bridge&&this.stopHealthMonitoring(),this.bridge=t,this.config.enableMinCutAwareness&&this.healthListeners.size>0&&this.startHealthMonitoring()}getMinCutBridge(){return this.bridge}hasBridge(){return this.bridge!==null}getDomainName(){return this.domainName}getConfig(){return{...this.config}}updateConfig(t){Object.assign(this.config,t),"enableMinCutAwareness"in t&&(t.enableMinCutAwareness&&this.bridge&&this.healthListeners.size>0?this.startHealthMonitoring():this.stopHealthMonitoring())}dispose(){this.stopHealthMonitoring(),this.healthListeners.clear(),this.bridge=null,this.lastHealthStatus=null}isTopologyHealthy(){return!this.config.enableMinCutAwareness||!this.bridge?!0:this.bridge.getMinCutHealth().status!=="critical"}getDomainWeakVertices(){return this.bridge?this.bridge.getWeakVertices().filter(e=>e.vertex.domain===this.domainName):[]}isDomainWeakPoint(){return this.getDomainWeakVertices().length>0}getTopologyBasedRouting(t){if(!this.config.enableMinCutAwareness||!this.bridge)return t;let e=this.bridge.getWeakVertices(),r=new Set;for(let i of e)i.vertex.domain&&r.add(i.vertex.domain);return t.filter(i=>!r.has(i))}onTopologyHealthChange(t){if(this.healthListeners.size>=to)throw console.error(`[MinCutAwareDomain] Max health listeners (${to}) reached for ${this.domainName}. Ensure listeners are properly unsubscribed.`),new Error(`Max health listeners (${to}) exceeded`);return this.healthListeners.add(t),this.healthListeners.size===1&&this.bridge&&this.config.enableMinCutAwareness&&this.startHealthMonitoring(),()=>{this.healthListeners.delete(t),this.healthListeners.size===0&&this.stopHealthMonitoring()}}getCurrentHealth(){return this.bridge?this.bridge.getMinCutHealth():null}getMinCutValue(){return this.bridge?this.bridge.getMinCutValue():null}shouldPauseOperations(){return this.config.pauseOnCriticalTopology?!this.isTopologyHealthy():!1}getHealthyRoutingDomains(){let t=this.config.monitoredDomains.length>0?this.config.monitoredDomains:this.getAllDomains();return this.getTopologyBasedRouting(t)}getNormalizedHealthScore(){if(!this.bridge)return 1;let t=this.bridge.getMinCutHealth();return t.healthyThreshold<=0?t.minCutValue>0?1:0:Math.min(1,t.minCutValue/t.healthyThreshold)}meetsHealthThreshold(){return this.getNormalizedHealthScore()>=this.config.topologyHealthThreshold}startHealthMonitoring(){this.healthCheckInterval||(this.healthCheckInterval=setInterval(()=>{this.checkAndNotifyHealthChange()},5e3),this.checkAndNotifyHealthChange())}stopHealthMonitoring(){this.healthCheckInterval&&(clearInterval(this.healthCheckInterval),this.healthCheckInterval=null)}checkAndNotifyHealthChange(){if(!this.bridge)return;let t=this.bridge.getMinCutHealth();if(t.status!==this.lastHealthStatus){this.lastHealthStatus=t.status;for(let e of this.healthListeners)try{e(t)}catch(r){console.error("Error in health change listener:",r)}}}getAllDomains(){return["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","requirements-validation","code-intelligence","security-compliance","contract-testing","visual-accessibility","chaos-resilience","learning-optimization","coordination"]}};function Zl(u,t){return new ro(u,t)}var kt={defaultThreshold:2/3,minModels:2,maxModels:3,defaultModelTimeout:3e4,defaultRetries:2,verifySeverities:["critical","high"],enableCache:!0,cacheTtlMs:36e5,enableCostTracking:!0,maxCostPerVerification:.5,humanReviewThreshold:.6,enableSycophancyCheck:!0};Le();Le();co();mo();ho();vo();To();Le();A();function Fn(u={}){let t=li(),e=u.enableLogging||!1;if(u.claude)try{let{createClaudeProvider:r}=(co(),Xt(ru)),i=r({...u.claude,enableLogging:u.claude.enableLogging??e});t.register(i)}catch(r){e&&console.warn(`[Providers] Failed to register Claude provider: ${r}`)}if(u.openai)try{let{createOpenAIProvider:r}=(mo(),Xt(nu)),i=r({...u.openai,enableLogging:u.openai.enableLogging??e});t.register(i)}catch(r){e&&console.warn(`[Providers] Failed to register OpenAI provider: ${r}`)}if(u.gemini)try{let{createGeminiProvider:r}=(ho(),Xt(su)),i=r({...u.gemini,enableLogging:u.gemini.enableLogging??e});t.register(i)}catch(r){e&&console.warn(`[Providers] Failed to register Gemini provider: ${r}`)}if(u.openrouter)try{let{createOpenRouterProvider:r,createMultiModelProviders:i}=(vo(),Xt(au));if(u.openrouter.multiModel&&u.openrouter.models){let n=i(u.openrouter.models);for(let s of n)t.register(s)}else{let n=r({apiKey:u.openrouter.apiKey,defaultModel:u.openrouter.defaultModel,enableLogging:u.openrouter.enableLogging??e});t.register(n)}}catch(r){e&&console.warn(`[Providers] Failed to register OpenRouter provider: ${r}`)}if(u.ollama)try{let{createOllamaProvider:r}=(To(),Xt(ou)),i=r({baseUrl:u.ollama.baseUrl,defaultModel:u.ollama.defaultModel,enableLogging:u.ollama.enableLogging??e});t.register(i)}catch(r){e&&console.warn(`[Providers] Failed to register Ollama provider: ${r}`)}return t}function Mt(u=!1){let t={enableLogging:u};return process.env.ANTHROPIC_API_KEY&&(t.claude={apiKey:process.env.ANTHROPIC_API_KEY}),process.env.OPENAI_API_KEY&&(t.openai={apiKey:process.env.OPENAI_API_KEY,organization:process.env.OPENAI_ORGANIZATION}),process.env.GOOGLE_API_KEY&&(t.gemini={apiKey:process.env.GOOGLE_API_KEY}),process.env.OPENROUTER_API_KEY&&(t.openrouter={apiKey:process.env.OPENROUTER_API_KEY}),process.env.OLLAMA_HOST&&(t.ollama={baseUrl:process.env.OLLAMA_HOST}),Fn(t)}var ui=class{config;constructor(t={}){this.config={minVotes:t.minVotes??2,humanReviewThreshold:t.humanReviewThreshold??.6,agreementThreshold:t.agreementThreshold??.5}}apply(t){if(t.length<this.config.minVotes)return{verdict:"insufficient",confidence:0,agreementRatio:0,reasoning:`Insufficient votes: ${t.length} received, ${this.config.minVotes} required`,requiresHumanReview:!0};let e=t.filter(l=>!l.error);if(e.length===0)return{verdict:"error",confidence:0,agreementRatio:0,reasoning:"All model votes resulted in errors",requiresHumanReview:!0};let r=e.filter(l=>l.agrees).length,i=e.length,n=r/i,s=e.reduce((l,d)=>l+d.confidence,0)/i,a;n>this.config.agreementThreshold?a="verified":n<1-this.config.agreementThreshold?a="rejected":a="disputed";let o=this.synthesizeReasoning(e,r,i),c=s<this.config.humanReviewThreshold||a==="disputed";return{verdict:a,confidence:s,agreementRatio:n,reasoning:o,requiresHumanReview:c}}synthesizeReasoning(t,e,r){let i=[];i.push(`Majority consensus reached: ${e}/${r} models agree.`);let n=t.filter(a=>a.agrees).map(a=>`- ${a.modelId}: ${a.reasoning}`),s=t.filter(a=>!a.agrees).map(a=>`- ${a.modelId}: ${a.reasoning}`);return n.length>0&&(i.push(`
|
|
2099
2099
|
Supporting votes:`),i.push(n.join(`
|
|
2100
2100
|
`))),s.length>0&&(i.push(`
|
|
2101
2101
|
Opposing votes:`),i.push(s.join(`
|
|
@@ -2147,7 +2147,7 @@ Individual assessments:`),t.forEach(s=>{let a=this.countsAsAgreement(s)?"\u2713
|
|
|
2147
2147
|
created_at TEXT DEFAULT (datetime('now')),
|
|
2148
2148
|
updated_at TEXT DEFAULT (datetime('now'))
|
|
2149
2149
|
);
|
|
2150
|
-
`,Io={loadOnInit:!0,autoSaveInterval:0,maxPatternsToLoad:1e4,enableCrossProcessSharing:!0},On=class{baseEngine;config;persistence=null;db=null;prepared=new Map;initialized=!1;initPromise=null;pendingSaves=new Map;saveTimer=null;serverClient=null;constructor(t){this.config={...Io,...t},this.baseEngine=new Pl(t),this.serverClient=t.serverClient??null}async initialize(){if(!this.initialized)return this.initPromise||(this.initPromise=this._doInitialize()),this.initPromise}async _doInitialize(){if(!this.initialized)try{this.persistence=en(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase(),this.ensureSchema(),this.prepareStatements(),this.config.loadOnInit&&await this.loadPatterns();let{isSONAThreeLoopEnabled:t}=await import("./feature-flags-
|
|
2150
|
+
`,Io={loadOnInit:!0,autoSaveInterval:0,maxPatternsToLoad:1e4,enableCrossProcessSharing:!0},On=class{baseEngine;config;persistence=null;db=null;prepared=new Map;initialized=!1;initPromise=null;pendingSaves=new Map;saveTimer=null;serverClient=null;constructor(t){this.config={...Io,...t},this.baseEngine=new Pl(t),this.serverClient=t.serverClient??null}async initialize(){if(!this.initialized)return this.initPromise||(this.initPromise=this._doInitialize()),this.initPromise}async _doInitialize(){if(!this.initialized)try{this.persistence=en(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase(),this.ensureSchema(),this.prepareStatements(),this.config.loadOnInit&&await this.loadPatterns();let{isSONAThreeLoopEnabled:t}=await import("./feature-flags-PVI7A4RE.js");if(t()){this.baseEngine.initThreeLoopEngine(),this.baseEngine.setFisherPersistence((r,i,n,s,a)=>{this.saveFisherMatrix(r,i,n,s,a)},this.config.domain);let e=this._loadFisherMatrixUnsafe(this.config.domain);if(e){let r=this.baseEngine.getThreeLoopEngine();r&&(r.restoreFisher({fisherDiagonal:e.fisherDiagonal,optimalParams:e.optimalParams,baseWeights:e.baseWeights,requestCount:e.requestCount}),$n.info("Three-loop engine restored Fisher state from SQLite",{domain:this.config.domain,requestCount:e.requestCount,taskBoundaries:e.taskBoundaries}))}$n.info("Three-loop engine initialized with Fisher persistence",{domain:this.config.domain})}this.initialized=!0,console.log(`[PersistentSONAEngine] Initialized: domain=${this.config.domain}`)}catch(t){throw this.initPromise=null,new Error(`Failed to initialize PersistentSONAEngine: ${T(t)}`)}}ensureSchema(){if(!this.db)throw new Error("Database not initialized");this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='sona_patterns'").get()||(console.log("[PersistentSONAEngine] Creating sona_patterns table"),this.db.exec(hu)),this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='sona_fisher_matrices'").get()||(console.log("[PersistentSONAEngine] Creating sona_fisher_matrices table"),this.db.exec(gu))}prepareStatements(){if(!this.db)throw new Error("Database not initialized");this.prepared.set("getById",this.db.prepare("SELECT * FROM sona_patterns WHERE id = ?")),this.prepared.set("getByDomain",this.db.prepare(`
|
|
2151
2151
|
SELECT * FROM sona_patterns
|
|
2152
2152
|
WHERE domain = ?
|
|
2153
2153
|
ORDER BY confidence DESC, updated_at DESC
|
|
@@ -2272,7 +2272,7 @@ Individual assessments:`),t.forEach(s=>{let a=this.countsAsAgreement(s)?"\u2713
|
|
|
2272
2272
|
MIN(created_at) as oldest_entry,
|
|
2273
2273
|
MAX(created_at) as newest_entry
|
|
2274
2274
|
FROM rl_q_values
|
|
2275
|
-
`))}async getQValue(t,e,r,i){this.ensureInitialized();let n=this.prepared.get("getQValue");if(!n)throw new Error("Statement not prepared");let s=i??this.config.defaultAlgorithm;return n.get(t,e,r,s)?.q_value??0}async setQValue(t,e,r,i,n,s){this.ensureInitialized();let a=this.prepared.get("upsertQValue");if(!a)throw new Error("Statement not prepared");let o=v(),c=s?.algorithm??this.config.defaultAlgorithm;a.run(o,c,t,e,r,i,n??null,s?.domain??null)}async incrementVisits(t,e,r,i){this.ensureInitialized();let n=this.prepared.get("incrementVisits");if(!n)throw new Error("Statement not prepared");let s=i??this.config.defaultAlgorithm;n.run(t,e,r,s)}async getTopActions(t,e,r=10,i){this.ensureInitialized();let n=this.prepared.get("getTopActions");if(!n)throw new Error("Statement not prepared");let s=i??this.config.defaultAlgorithm;return n.all(t,e,s,r).map(o=>this.rowToEntry(o))}async exportForAgent(t,e){this.ensureInitialized();let r=this.prepared.get("getAllForAgent");if(!r)throw new Error("Statement not prepared");let i=e??this.config.defaultAlgorithm,n=r.all(t,i),s=new Map;for(let a of n){let o=a.state_key,c=a.action_key,l=a.q_value;s.has(o)||s.set(o,new Map),s.get(o).set(c,l)}return s}async importFromMap(t,e,r){if(this.ensureInitialized(),!this.db)throw new Error("Database not initialized");let i=this.prepared.get("upsertQValue");if(!i)throw new Error("Statement not prepared");let n=r?.algorithm??this.config.defaultAlgorithm;this.db.transaction(()=>{for(let[a,o]of e)for(let[c,l]of o){let d=v();i.run(d,n,t,a,c,l,null,r?.domain??null)}})()}async pruneOldEntries(t){this.ensureInitialized();let e=this.prepared.get("pruneOld");if(!e)throw new Error("Statement not prepared");return e.run(t).changes}async getStats(){this.ensureInitialized();let t=this.prepared.get("getStats"),e=this.prepared.get("countByAlgorithm"),r=this.prepared.get("countByDomain");if(!t||!e||!r)throw new Error("Statements not prepared");let i=t.get(),n=e.all(),s=r.all(),a={};for(let c of n)a[c.algorithm]=c.count;let o={};for(let c of s)c.domain&&(o[c.domain]=c.count);return{totalEntries:i.total_entries,uniqueAgents:i.unique_agents,uniqueStates:i.unique_states,byAlgorithm:a,byDomain:o,averageVisits:i.avg_visits??0,averageQValue:i.avg_q_value??0,oldestEntry:i.oldest_entry?new Date(i.oldest_entry):null,newestEntry:i.newest_entry?new Date(i.newest_entry):null}}async close(){this.prepared.clear(),this.db=null,this.persistence=null,this.initialized=!1}async getEntry(t,e,r,i){this.ensureInitialized();let n=this.prepared.get("getEntry");if(!n)throw new Error("Statement not prepared");let s=i??this.config.defaultAlgorithm,a=n.get(t,e,r,s);return a?this.rowToEntry(a):null}async deleteEntry(t,e,r,i){this.ensureInitialized();let n=this.prepared.get("deleteEntry");if(!n)throw new Error("Statement not prepared");let s=i??this.config.defaultAlgorithm;return n.run(t,e,r,s).changes>0}isInitialized(){return this.initialized}getDbPath(){return this.persistence?.getDbPath()??""}ensureInitialized(){if(!this.initialized)throw new Error("QValueStore not initialized. Call initialize() first.")}rowToEntry(t){return{id:t.id,algorithm:t.algorithm,agentId:t.agent_id,stateKey:t.state_key,actionKey:t.action_key,qValue:t.q_value,visits:t.visits,lastReward:t.last_reward,domain:t.domain,createdAt:new Date(t.created_at),updatedAt:new Date(t.updated_at)}}};H();M();var vu=R.create("rl-base-algorithm"),bu={learningRate:.001,discountFactor:.99,episodes:1e3,maxSteps:1e3,batchSize:32,replayBufferSize:1e4,targetUpdateFrequency:100,explorationRate:.3,explorationDecay:.995,minExplorationRate:.01},ih={enabled:!1,autoSaveInterval:10},oe=class{constructor(t,e,r={},i=[],n={}){this.type=t;this.category=e;this.config={...bu,...r},this.rewardSignals=i,this.persistenceConfig={...ih,...n},this.stats=this.createInitialStats()}type;category;config;stats;replayBuffer=[];episodeCount=0;totalReward=0;rewardHistory=[];initialized=!1;rewardSignals=[];persistenceConfig;qValueStore=null;lastSaveEpisode=0;enablePersistence(t,e){this.persistenceConfig.enabled=!0,this.persistenceConfig.agentId=t,e&&(this.persistenceConfig.dbPath=e)}isPersistenceEnabled(){return this.persistenceConfig.enabled&&!!this.persistenceConfig.agentId}getPersistenceAgentId(){return this.persistenceConfig.agentId}async train(t){if(this.addToReplayBuffer(t),this.replayBuffer.length>=this.config.batchSize){let e=this.sampleBatch();return this.trainBatch(e)}return this.getStats()}async trainBatch(t){this.initialized||await this.initialize();let e=Date.now();try{this.episodeCount++;let r=t.reduce((n,s)=>n+s.reward,0);this.totalReward+=r,this.rewardHistory.push(r),this.rewardHistory.length>1e3&&this.rewardHistory.shift();let i=await this.trainCore(t);return this.stats={...i,episode:this.episodeCount,totalReward:this.totalReward,averageReward:this.rewardHistory.reduce((n,s)=>n+s,0)/this.rewardHistory.length,trainingTimeMs:Date.now()-e,timestamp:new Date},this.config.explorationRate=Math.max(this.config.minExplorationRate,this.config.explorationRate*this.config.explorationDecay),this.stats.explorationRate=this.config.explorationRate,await this.autoSaveToPersistence(),this.stats}catch(r){throw new Vn(`Training failed for ${this.type}: ${r.message}`,this.type,r)}}async autoSaveToPersistence(){if(!this.isPersistenceEnabled()||this.persistenceConfig.autoSaveInterval<=0)return;if(this.episodeCount-this.lastSaveEpisode>=this.persistenceConfig.autoSaveInterval)try{await this.saveToStore(this.persistenceConfig.agentId,this.qValueStore??void 0),this.lastSaveEpisode=this.episodeCount}catch(e){console.warn(`[${this.type}] Auto-save failed:`,e.message)}}async update(t){let e={...this.config};if(this.config={...this.config,...t},this.config.learningRate<=0||this.config.learningRate>1)throw new ct(`Invalid learning rate: ${this.config.learningRate}`,this.type);if(this.config.discountFactor<0||this.config.discountFactor>1)throw new ct(`Invalid discount factor: ${this.config.discountFactor}`,this.type);if(this.config.explorationRate<0||this.config.explorationRate>1)throw new ct(`Invalid exploration rate: ${this.config.explorationRate}`,this.type);await this.handleConfigUpdate(e,this.config)}getStats(){return{...this.stats}}async reset(){this.isPersistenceEnabled()&&this.episodeCount>0&&await this.saveToStore(this.persistenceConfig.agentId,this.qValueStore??void 0),this.replayBuffer=[],this.episodeCount=0,this.totalReward=0,this.rewardHistory=[],this.lastSaveEpisode=0,this.config.explorationRate=bu.explorationRate,this.stats=this.createInitialStats(),await this.resetAlgorithm()}async close(){this.isPersistenceEnabled()&&this.episodeCount>this.lastSaveEpisode&&await this.saveToStore(this.persistenceConfig.agentId,this.qValueStore??void 0),this.qValueStore&&(await this.qValueStore.close(),this.qValueStore=null)}async exportModel(){return{type:this.type,category:this.category,version:this.getVersion(),config:this.config,stats:this.stats,replayBufferSize:this.replayBuffer.length,exportedAt:new Date().toISOString(),customData:await this.exportCustomData()}}async importModel(t){if(t.type!==this.type)throw new ct(`Model type mismatch: expected ${this.type}, got ${t.type}`,this.type);if(t.category!==this.category)throw new ct(`Algorithm category mismatch: expected ${this.category}, got ${t.category}`,this.type);t.config&&(this.config={...this.config,...t.config}),t.stats&&(this.stats={...this.stats,...t.stats}),t.customData&&await this.importCustomData(t.customData),this.initialized=!0}getInfo(){let t=this.getAlgorithmInfo();return{...t,stats:this.stats,hyperparameters:{...t.hyperparameters,learningRate:this.config.learningRate,discountFactor:this.config.discountFactor,explorationRate:this.config.explorationRate,batchSize:this.config.batchSize}}}async saveToStore(t,e){let r=e??new lt;await r.initialize();let i=await this.exportModel();await r.setQValue(t,"__model_state__","__weights__",0,void 0,{algorithm:this.type,domain:JSON.stringify(i)})}async loadFromStore(t,e){let r=e??new lt;await r.initialize();try{let i=await r.getQValue(t,"__model_state__","__weights__",this.type),n=await r.getEntry(t,"__model_state__","__weights__",this.type);if(!n?.domain)return!1;let s=E(n.domain);return await this.importModel(s),!0}catch(i){return vu.debug("Model load from store failed",{algorithm:this.type,error:i instanceof Error?i.message:String(i)}),!1}}async storeQValue(t,e,r,i,n,s){let a=s??new lt;await a.initialize(),await a.setQValue(t,e,r,i,n,{algorithm:this.type})}async retrieveQValue(t,e,r,i){let n=i??new lt;await n.initialize();try{return await n.getQValue(t,e,r,this.type)}catch(s){return vu.debug("Q-value retrieval failed",{agentId:t,stateKey:e,actionKey:r,error:s instanceof Error?s.message:String(s)}),null}}calculateReward(t){let e={},r=0,i=[];for(let n of this.rewardSignals){let s=n.calculate(t);e[n.name]=s,r+=s,s!==0&&i.push(`${n.name}: ${s.toFixed(3)} (${n.description})`)}return{totalReward:Math.max(-1,Math.min(1,r)),components:e,reasoning:i.join("; ")||"No reward signals triggered",timestamp:new Date}}addToReplayBuffer(t){this.replayBuffer.push(t),this.replayBuffer.length>this.config.replayBufferSize&&this.replayBuffer.shift()}sampleBatch(t){let e=t||this.config.batchSize,r=this.replayBuffer;if(r.length===0)return[];if(r.length<=e)return[...r];let i=new Set;for(;i.size<Math.min(e,r.length);)i.add(ue(0,r.length));return Array.from(i).map(n=>r[n])}epsilonGreedy(t,e){return L()<this.config.explorationRate?t():e()}normalizeFeatures(t){if(t.length===0)return[];let e=Math.max(...t.map(Math.abs));return e===0?t:t.map(r=>r/e)}stateToKey(t){let e=t.features.map((r,i)=>`${i}:${Math.round(r*100)/100}`).join(",");return`${t.id}|${e}`}async initialize(){this.isPersistenceEnabled()&&(await this.initializePersistence(),await this.loadFromStore(this.persistenceConfig.agentId)&&console.log(`[${this.type}] Loaded persisted state for agent: ${this.persistenceConfig.agentId}`)),this.initialized=!0}async initializePersistence(){this.qValueStore||(this.qValueStore=new lt,await this.qValueStore.initialize())}async resetAlgorithm(){}async handleConfigUpdate(t,e){}async exportCustomData(){return{}}async importCustomData(t){}getVersion(){return"1.0.0"}createInitialStats(){return{episode:0,totalReward:0,averageReward:0,explorationRate:this.config.explorationRate,trainingTimeMs:0,timestamp:new Date}}};Zi();var nh={contextLength:10,embeddingDim:384,numHeads:4,numLayers:3,feedForwardDim:256,maxReturn:100},ar=class extends oe{trajectories=[];dtConfig;stateEmbeddings=new Map;actionEmbeddings=new Map;constructor(t={}){super("decision-transformer","offline-rl"),this.dtConfig={...nh,...t}}async predict(t){this.initialized||await this.initialize();let e=this.retrieveContext(t),r=this.calculateReturnToGo(e),i=this.generateAction(t,e,r),n=this.calculateConfidence(e,r);return{action:i,confidence:n,value:r,reasoning:this.generateReasoning(t,i,e,r)}}async trainCore(t){let e=this.groupIntoTrajectories(t);for(let i of e)this.calculateReturns(i);this.trajectories.push(...e),this.trajectories.length>1e3&&(this.trajectories=this.trajectories.slice(-1e3)),this.updateEmbeddings(e);let r=e.reduce((i,n)=>i+n.returns[n.returns.length-1],0)/e.length;return{episode:this.episodeCount,totalReward:this.totalReward,averageReward:this.rewardHistory.reduce((i,n)=>i+n,0)/this.rewardHistory.length,loss:Math.abs(r-this.targetReturn()),explorationRate:0,trainingTimeMs:0,timestamp:new Date}}getAlgorithmInfo(){return{type:this.type,category:this.category,version:"1.0.0",description:"Decision Transformer for Test Case Prioritization",capabilities:["Offline RL from historical data","Attention-based sequence modeling","Return-to-go conditioning","Context-aware decisions"],hyperparameters:{contextLength:this.dtConfig.contextLength,embeddingDim:this.dtConfig.embeddingDim,numHeads:this.dtConfig.numHeads,numLayers:this.dtConfig.numLayers},stats:this.stats}}retrieveContext(t){let e=this.trajectories.map(r=>{let i=this.calculateSimilarity(t,r);return{traj:r,similarity:i}});return e.sort((r,i)=>i.similarity-r.similarity),e.slice(0,this.dtConfig.contextLength).map(r=>r.traj)}calculateSimilarity(t,e){for(let r of e.states)if(this.statesMatch(t,r))return 1;if(e.states.length>0){let r=e.states[e.states.length-1];return tt(t.features,r.features)}return 0}statesMatch(t,e){return t.id===e.id||Math.abs(t.features[0]-e.features[0])<.1}calculateReturnToGo(t){if(t.length===0)return 0;let e=t.flatMap(r=>r.returns);return e.reduce((r,i)=>r+i,0)/e.length}calculateReturns(t){let e=[],r=0;for(let i=t.rewards.length-1;i>=0;i--)r=t.rewards[i]+this.config.discountFactor*r,e.unshift(r);t.returns=e}targetReturn(){return this.dtConfig.maxReturn*.8}generateAction(t,e,r){for(let i of e)for(let n=0;n<i.states.length;n++)if(this.statesMatch(t,i.states[n])&&i.returns[n]>r*.8)return{...i.actions[n]};return this.getHeuristicAction(t)}getHeuristicAction(t){return{type:"prioritize",value:t.features[0]>.7?"high":"standard",metadata:{heuristic:!0}}}updateEmbeddings(t){for(let e of t){for(let r of e.states)this.stateEmbeddings.has(r.id)||this.stateEmbeddings.set(r.id,this.hashEmbedding(r.id));for(let r of e.actions){let i=this.actionToKey(r);this.actionEmbeddings.has(i)||this.actionEmbeddings.set(i,this.hashEmbedding(i))}}}hashEmbedding(t){let e=[],r=this.dtConfig.embeddingDim;for(let i=0;i<r;i++){let n=this.simpleHash(t+i);e.push((n%200-100)/100)}return e}simpleHash(t){let e=0;for(let r=0;r<t.length;r++){let i=t.charCodeAt(r);e=(e<<5)-e+i,e=e&e}return Math.abs(e)}actionToKey(t){return`${t.type}:${JSON.stringify(t.value)}`}groupIntoTrajectories(t){let e=[],r=null;for(let i of t)i.done||!r?(r&&e.push(r),r={states:[i.state],actions:[i.action],rewards:[i.reward],returns:[]}):(r.states.push(i.state),r.actions.push(i.action),r.rewards.push(i.reward));return r&&e.push(r),e}calculateConfidence(t,e){if(t.length===0)return .3;let r=Math.min(1,t.length/this.dtConfig.contextLength),i=Math.min(1,e/this.targetReturn());return .3+r*.4+i*.3}generateReasoning(t,e,r,i){if(r.length===0)return"Decision Transformer: No similar historical contexts, using heuristic";let n=r.reduce((s,a)=>s+a.returns[a.returns.length-1]||0,0)/r.length;return`Decision Transformer: Found ${r.length} similar contexts (avg return: ${n.toFixed(2)}), selecting ${e.type} action with return-to-go ${i.toFixed(2)}`}async exportCustomData(){return{trajectories:this.trajectories,stateEmbeddings:Object.fromEntries(this.stateEmbeddings),actionEmbeddings:Object.fromEntries(this.actionEmbeddings),dtConfig:this.dtConfig}}async importCustomData(t){t.trajectories&&(this.trajectories=t.trajectories),t.stateEmbeddings&&(this.stateEmbeddings=new Map(Object.entries(t.stateEmbeddings))),t.actionEmbeddings&&(this.actionEmbeddings=new Map(Object.entries(t.actionEmbeddings))),t.dtConfig&&(this.dtConfig={...this.dtConfig,...t.dtConfig})}async resetAlgorithm(){this.trajectories=[],this.stateEmbeddings.clear(),this.actionEmbeddings.clear()}};Ge();M();var wu={enabled:!0,coherenceThreshold:.1,blockOnHumanLane:!0,enrichOnRetrievalLane:!0,embeddingDimension:384},sh=R.create("test-generation/coherence-gate"),_n=class extends Error{constructor(e,r,i){super(e);this.contradictions=r;this.lane=i;this.name="CoherenceError"}contradictions;lane},Mo=class{constructor(t=384){this.dimension=t}dimension;async embed(t){let e=new Array(this.dimension).fill(0),r=t.toLowerCase().trim();for(let n=0;n<r.length;n++){let s=r.charCodeAt(n),a=n%this.dimension;e[a]+=Math.sin(s*(n+1)*.1),e[(a+1)%this.dimension]+=Math.cos(s*(n+1)*.1)}let i=Math.sqrt(e.reduce((n,s)=>n+s*s,0));if(i>0)for(let n=0;n<e.length;n++)e[n]/=i;return e}},zn=class{constructor(t,e,r={}){this.coherenceService=t;this.config={...wu,...r},this.embeddingService=e||new Mo(this.config.embeddingDimension)}coherenceService;config;embeddingService;async checkRequirementCoherence(t){let e=Date.now();if(!this.config.enabled||!this.coherenceService)return this.createPassingResult(e,!0);if(t.length===0)return this.createPassingResult(e,!1);if(t.length===1)return this.createPassingResult(e,!1);try{let r=await this.requirementsToNodes(t),i=await this.coherenceService.checkCoherence(r);return this.transformCoherenceResult(i,t,Date.now()-e)}catch(r){return sh.error("Coherence check failed:",r instanceof Error?r:void 0),{isCoherent:!0,energy:0,lane:"reflex",contradictions:[],recommendations:[{type:"add-context",requirementId:"",description:"Coherence check failed. Manual review recommended.",suggestedResolution:"Review requirements manually before proceeding."}],durationMs:Date.now()-e,usedFallback:!0}}}async enrichSpecification(t,e){if(e.length===0)return t;let r={...t,requirements:[...t.requirements],context:{...t.context}},i=new Map;for(let n of e)switch(n.type){case"clarify":this.addClarificationNote(i,n);break;case"add-context":r.context={...r.context,coherenceRecommendations:[...r.context?.coherenceRecommendations||[],n.description]};break;case"resolve-ambiguity":this.addDisambiguationNote(i,n);break;case"split-requirement":r.context={...r.context,requirementsSuggestedForSplit:[...r.context?.requirementsSuggestedForSplit||[],n.requirementId]};break}return r.requirements=r.requirements.map(n=>{let s=i.get(n.id);return s?{...n,metadata:{...n.metadata,...s.metadata}}:n}),r.context={...r.context,enrichedAt:new Date().toISOString(),enrichmentCount:e.length},r}async validateAndEnrich(t){let e=await this.checkRequirementCoherence(t.requirements);if(this.config.blockOnHumanLane&&e.lane==="human")return p(new _n("Requirements contain unresolvable contradictions that require human review",e.contradictions,e.lane));if(this.config.enrichOnRetrievalLane&&e.lane==="retrieval"){let r=await this.enrichSpecification(t,e.recommendations);return f(r)}return f(t)}isAvailable(){return this.coherenceService?.isInitialized()??!1}async requirementsToNodes(t){let e=[];for(let r of t){let i=await this.embeddingService.embed(r.description);e.push({id:r.id,embedding:i,weight:this.priorityToWeight(r.priority),metadata:{description:r.description,source:r.source,...r.metadata}})}return e}transformCoherenceResult(t,e,r){let i=new Map(e.map(a=>[a.id,a])),n=t.contradictions.map(a=>({requirementId1:a.nodeIds[0],requirementId2:a.nodeIds[1],severity:this.mapSeverity(a.severity),description:a.description,confidence:a.confidence,suggestedResolution:a.resolution||this.generateResolutionSuggestion(i.get(a.nodeIds[0]),i.get(a.nodeIds[1]),a.severity)})),s=this.generateRecommendations(t,n,e);return{isCoherent:t.isCoherent,energy:t.energy,lane:t.lane,contradictions:n,recommendations:s,durationMs:r,usedFallback:t.usedFallback}}generateRecommendations(t,e,r){let i=[];for(let s of t.recommendations)i.push({type:"add-context",requirementId:"",description:s});for(let s of e)s.severity==="critical"||s.severity==="high"?i.push({type:"resolve-ambiguity",requirementId:s.requirementId1,description:`Potential conflict with requirement ${s.requirementId2}: ${s.description}`,suggestedResolution:s.suggestedResolution}):i.push({type:"clarify",requirementId:s.requirementId1,description:`Minor tension with requirement ${s.requirementId2}: ${s.description}`});let n=r.filter(s=>s.description.length>200||s.description.includes(" and ")&&s.description.includes(" or "));for(let s of n)i.push({type:"split-requirement",requirementId:s.id,description:"Complex requirement may benefit from splitting into smaller, focused requirements"});return i}generateResolutionSuggestion(t,e,r){return!t||!e?"Review and reconcile conflicting requirements.":r==="critical"?`Requirements "${t.id}" and "${e.id}" appear to be mutually exclusive. Consider removing one or explicitly documenting the conditions under which each applies.`:r==="high"?`Requirements "${t.id}" and "${e.id}" may conflict. Add clarification about their relationship and precedence.`:`Minor tension between "${t.id}" and "${e.id}". Consider adding context to clarify their relationship.`}createPassingResult(t,e){return{isCoherent:!0,energy:0,lane:"reflex",contradictions:[],recommendations:[],durationMs:Date.now()-t,usedFallback:e}}priorityToWeight(t){switch(t){case"high":return 1;case"medium":return .7;case"low":return .4;default:return .5}}mapSeverity(t){switch(t){case"critical":return"critical";case"high":return"high";case"medium":return"medium";default:return"low"}}addClarificationNote(t,e){let r=t.get(e.requirementId)||{metadata:{}},i=r.metadata?.clarificationNotes||[];i.push(e.description),t.set(e.requirementId,{...r,metadata:{...r.metadata,clarificationNotes:i,needsClarification:!0}})}addDisambiguationNote(t,e){let r=t.get(e.requirementId)||{metadata:{}},i=r.metadata?.disambiguationNotes||[];i.push(e.description),t.set(e.requirementId,{...r,metadata:{...r.metadata,disambiguationNotes:i,needsDisambiguation:!0,suggestedResolution:e.suggestedResolution}})}};function Fo(u,t,e){return new zn(u,t,e)}var ah={maxConcurrentWorkflows:5,defaultTimeout:6e4,enablePatternLearning:!0,publishEvents:!0,enableQESONA:!0,enableFlashAttention:!0,enableDecisionTransformer:!0,sonaPatternType:"test-generation",flashAttentionWorkload:"test-similarity",enableCoherenceGate:!0,blockOnIncoherentRequirements:!0,enrichOnRetrievalLane:!0,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},U=R.create("test-generation"),yi=class extends Q{constructor(e,r,i,n={},s,a,o){let c={...ah,...n};super(e,"test-generation",c,{verifyFindingTypes:["test-pattern-selection","mock-strategy","edge-case-generation","assertion-strategy"],...c.consensusConfig});this.memory=r;this.agentCoordinator=i;this.coherenceService=a;this.hookRegistry=o;this.testGenerator=ai({memory:r,llmRouter:s}),this.patternMatcher=new Pt(r),this.config.enableCoherenceGate&&a&&(this.coherenceGate=Fo(a,void 0,{enabled:!0,blockOnHumanLane:this.config.blockOnIncoherentRequirements,enrichOnRetrievalLane:this.config.enrichOnRetrievalLane}))}memory;agentCoordinator;coherenceService;hookRegistry;testGenerator;patternMatcher;qesona=null;flashAttention=null;decisionTransformer=null;testEmbeddings=new Map;recentDreamInsights=[];coherenceGate=null;async onInitialize(){if(this.config.enableQESONA)try{this.qesona=await pe({domain:"test-generation",loadOnInit:!0,autoSaveInterval:6e4,patternClusters:50,minConfidence:.5}),U.info("PersistentSONAEngine initialized for test-generation domain")}catch(e){U.error("Failed to initialize PersistentSONAEngine:",e instanceof Error?e:void 0),U.warn("Continuing without SONA pattern persistence"),this.qesona=null}if(this.config.enableFlashAttention)try{this.flashAttention=await Me(this.config.flashAttentionWorkload,{dim:384,strategy:"flash",blockSize:64}),U.info("QEFlashAttention initialized for test-similarity")}catch{U.warn("QEFlashAttention unavailable (optional native module), continuing without it"),this.flashAttention=null}if(this.config.enableDecisionTransformer)try{this.decisionTransformer=new ar({contextLength:10,embeddingDim:384}),U.info("DecisionTransformer created for test case selection")}catch{U.warn("DecisionTransformer unavailable (optional native module), continuing without it"),this.decisionTransformer=null}this.subscribeToEvents(),await this.loadWorkflowState()}async onDispose(){await this.saveWorkflowState(),this.flashAttention&&(this.flashAttention.dispose(),this.flashAttention=null),this.decisionTransformer&&(await this.decisionTransformer.reset(),this.decisionTransformer=null),this.qesona&&(await this.qesona.close(),this.qesona=null),this.testEmbeddings.clear()}getActiveWorkflows(){return super.getActiveWorkflows()}async generateTests(e){let r=v();try{if(this.startWorkflow(r,"generate"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&U.warn("Topology degraded, using conservative strategy"),this.minCutMixin.shouldPauseOperations())return p(new Error("Test generation paused: topology is in critical state"));let i=[];if(this.hookRegistry)try{let c=e.sourceFiles?.[0]||"",l=await this.hookRegistry.emit(xl.PreTestGeneration,{targetFile:c,testType:e.testType,framework:e.framework,language:c.split(".").pop()||"typescript"});for(let d of l)d.success&&d.data?.patterns&&i.push(...d.data.patterns),d.guidance&&U.info(`Hook guidance: ${d.guidance.join("; ")}`)}catch{U.debug("PreTestGeneration hook failed:")}if(!this.agentCoordinator.canSpawn())return p(new Error("Agent limit reached, cannot spawn test generation agents"));let n=await this.spawnTestGeneratorAgent(r,e);if(!n.success)return this.failWorkflow(r,n.error.message),p(n.error);this.addAgentToWorkflow(r,n.value);let s=[...e.patterns||[],...i];if(this.config.enableQESONA&&this.qesona){let c=await this.adaptTestGenerationPatterns(e);c.length>0&&(s=c,U.info(`Adapted ${c.length} patterns using QESONA`))}let a=s;if(this.config.enablePatternLearning&&a.length===0){let c=await this.patternMatcher.findMatchingPatterns({testType:e.testType,framework:e.framework});c.success&&c.value.length>0&&(a=c.value.map(l=>l.pattern.id))}let o=await this.testGenerator.generateTests({...e,patterns:a});if(o.success){if(this.completeWorkflow(r),this.config.enableFlashAttention&&this.flashAttention){let c=await this.findSimilarTests(o.value.tests);c.length>0&&U.info(`Found ${c.length} similar tests using Flash Attention`)}if(this.config.enableDecisionTransformer&&this.decisionTransformer){let c=await this.prioritizeTestCases(o.value.tests,e);U.info(`Prioritized ${c.length} tests using DecisionTransformer`)}if(this.config.publishEvents){await this.publishTestSuiteCreated(o.value,e);for(let c of o.value.tests)await this.publishTestGenerated(c,e.framework??"vitest")}if(St()&&this.qesona?.isThreeLoopEnabled()){let c=o.value;this.qesona.instantAdapt([c.tests.length/20,c.coverageEstimate/100,c.patternsUsed.length/10,e.sourceFiles.length/20,(e.coverageTarget??80)/100,c.tests.filter(l=>l.type==="unit").length/20]);try{if(this.qesona.recordOutcome(1),this.qesona.shouldConsolidate())try{this.qesona.backgroundConsolidate()}catch{}}catch{}}this.config.enableQESONA&&this.qesona&&await this.storeTestGenerationPattern(o.value,e),this.config.enablePatternLearning&&await this.learnFromGeneration(o.value)}else this.failWorkflow(r,o.error.message),this.config.publishEvents&&await this.publishGenerationFailed(o.error,"generateTests");return await this.agentCoordinator.stop(n.value),o}catch(i){let n=y(i);return this.failWorkflow(r,n.message),this.config.publishEvents&&await this.publishGenerationFailed(n,"generateTests"),{success:!1,error:n}}}async generateTDDTests(e){let r=v();try{this.startWorkflow(r,"tdd");let i=await this.spawnTDDAgent(r,e);if(!i.success)return this.failWorkflow(r,i.error.message),p(i.error);this.addAgentToWorkflow(r,i.value);let n=await this.testGenerator.generateTDDTests(e);return n.success?(this.completeWorkflow(r),this.updateWorkflowProgress(r,this.getTDDProgress(e.phase))):this.failWorkflow(r,n.error.message),await this.agentCoordinator.stop(i.value),n}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async generatePropertyTests(e){let r=v();try{this.startWorkflow(r,"property");let i=await this.spawnPropertyTestAgent(r,e);if(!i.success)return this.failWorkflow(r,i.error.message),p(i.error);this.addAgentToWorkflow(r,i.value);let n=await this.testGenerator.generatePropertyTests(e);return n.success?this.completeWorkflow(r):this.failWorkflow(r,n.error.message),await this.agentCoordinator.stop(i.value),n}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async generateTestData(e){let r=v();try{this.startWorkflow(r,"data");let i=await this.testGenerator.generateTestData(e);return i.success?this.completeWorkflow(r):this.failWorkflow(r,i.error.message),i}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async learnPatterns(e){let r=v();try{this.startWorkflow(r,"learn");let i=await this.patternMatcher.learnPatterns(e);return i.success?(this.completeWorkflow(r),this.config.publishEvents&&await this.publishPatternLearned(i.value)):this.failWorkflow(r,i.error.message),i}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async spawnTestGeneratorAgent(e,r){let i={name:`test-generator-${e.slice(0,8)}`,domain:"test-generation",type:"generator",capabilities:["test-generation",r.testType,r.framework??"vitest"],config:{workflowId:e,sourceFiles:r.sourceFiles,coverageTarget:r.coverageTarget}};return this.agentCoordinator.spawn(i)}async spawnTDDAgent(e,r){let i={name:`tdd-agent-${e.slice(0,8)}`,domain:"test-generation",type:"generator",capabilities:["tdd",r.framework,r.phase],config:{workflowId:e,feature:r.feature,behavior:r.behavior}};return this.agentCoordinator.spawn(i)}async spawnPropertyTestAgent(e,r){let i={name:`property-test-agent-${e.slice(0,8)}`,domain:"test-generation",type:"generator",capabilities:["property-testing","fast-check"],config:{workflowId:e,function:r.function,properties:r.properties}};return this.agentCoordinator.spawn(i)}async publishTestGenerated(e,r){let i={testId:e.id,testFile:e.testFile,framework:r,sourceFile:e.sourceFile,testType:e.type},n=I(Or.TestGenerated,"test-generation",i);await this.eventBus.publish(n)}async publishTestSuiteCreated(e,r){let i={suiteId:v(),testCount:e.tests.length,sourceFiles:r.sourceFiles,coverageEstimate:e.coverageEstimate},n=I(Or.TestSuiteCreated,"test-generation",i);await this.eventBus.publish(n)}async publishPatternLearned(e){let r=I(Or.PatternLearned,"test-generation",{patternCount:e.patterns.length,confidence:e.confidence,patternIds:e.patterns.map(i=>i.id)});await this.eventBus.publish(r)}async publishGenerationFailed(e,r){let i=I(Or.GenerationFailed,"test-generation",{error:e.message,context:r,timestamp:new Date().toISOString()});await this.eventBus.publish(i)}getTDDProgress(e){switch(e){case"red":return 33;case"green":return 66;case"refactor":return 100;default:return 0}}subscribeToEvents(){this.eventBus.subscribe("coverage-analysis.CoverageGapDetected",this.handleCoverageGapDetected.bind(this)),this.eventBus.subscribe("test-execution.TestRunCompleted",this.handleTestRunCompleted.bind(this)),this.subscribeToDreamEvents()}subscribeToDreamEvents(){this.eventBus.subscribe(He.DreamCycleCompleted,this.handleDreamCycleCompleted.bind(this))}async handleDreamCycleCompleted(e){let{insights:r,cycleId:i}=e.payload;if(!r||r.length===0)return;let n=r.filter(s=>{let a=s.suggestedAction?.toLowerCase().includes(this.domainName)||s.suggestedAction?.toLowerCase().includes("test")||s.suggestedAction?.toLowerCase().includes("coverage"),o=s.sourceConcepts.some(l=>l.toLowerCase().includes("test")||l.toLowerCase().includes(this.domainName)||l.toLowerCase().includes("coverage")||l.toLowerCase().includes("edge-case")),c=s.type==="optimization"||s.type==="gap_detection"||s.type==="novel_association";return a||o||c&&s.actionable});if(n.length!==0){U.info(`[${this.domainName}] Received ${n.length} relevant dream insights from cycle ${i}`);for(let s of n)s.confidenceScore>.7&&s.actionable&&await this.applyDreamInsight(s,i),this.recentDreamInsights.push({...s,receivedAt:new Date});this.recentDreamInsights.length>50&&(this.recentDreamInsights=this.recentDreamInsights.slice(-50))}}async applyDreamInsight(e,r){if(U.info(`[${this.domainName}] Applying dream insight: ${e.description.slice(0,100)}...`),this.qesona)try{let i={id:`dream-insight-${e.id}`,features:this.encodeInsightAsFeatures(e),metadata:{insightType:e.type,cycleId:r,sourceConcepts:e.sourceConcepts}},n={type:"dream-insight",value:e.suggestedAction||e.description},s=this.qesona.createPattern(i,n,{reward:e.confidenceScore,success:!0,quality:e.noveltyScore},"dream-derived",this.domainName,{insightId:e.id,cycleId:r,description:e.description,suggestedAction:e.suggestedAction});U.info(`[${this.domainName}] Created SONA pattern ${s.id} from dream insight`)}catch(i){U.error(`[${this.domainName}] Failed to store dream insight pattern`,i instanceof Error?i:void 0)}await this.memory.set(`${this.domainName}:dream-insight:${e.id}`,{insight:e,cycleId:r,appliedAt:new Date().toISOString()},{namespace:this.domainName,ttl:86400*7})}getRecentDreamInsights(e){let r=Date.now()-864e5;return this.recentDreamInsights.filter(i=>{let n=i.receivedAt.getTime()>r,s=!e||i.type===e;return n&&s})}async enhanceWithDreamInsights(e){let r=[],n=this.getRecentDreamInsights().filter(s=>(s.type==="novel_association"||s.type==="gap_detection")&&s.actionable&&s.confidenceScore>.6);for(let s of n)s.suggestedAction&&(e.sourceFiles.some(o=>s.sourceConcepts.some(c=>o.toLowerCase().includes(c.toLowerCase())))||s.suggestedAction.toLowerCase().includes(e.testType))&&r.push(s.suggestedAction);return r.slice(0,5)}encodeInsightAsFeatures(e){let r=[],i={pattern_merge:.2,novel_association:.4,optimization:.6,gap_detection:.8};for(r.push(i[e.type]||.5),r.push(e.confidenceScore),r.push(e.noveltyScore),r.push(e.actionable?1:0),r.push(Math.min(1,e.sourceConcepts.length/10));r.length<384;)r.push(0);return r.slice(0,384)}async handleCoverageGapDetected(e){let r=e.payload,i=await this.testGenerator.generateForCoverageGap(r.file,r.uncoveredLines,"jest");if(i.success&&i.value.length>0)for(let n of i.value)await this.publishTestGenerated(n,"jest")}async handleTestRunCompleted(e){}async learnFromGeneration(e){for(let r of e.patternsUsed){let i=await this.patternMatcher.getPattern(r)}}async adaptTestGenerationPatterns(e){if(!this.qesona)return[];try{let r={id:`test-gen-${Date.now()}`,features:this.encodeRequestAsFeatures(e),metadata:{testType:e.testType,framework:e.framework,sourceFileCount:e.sourceFiles.length}},i=await this.qesona.adaptPattern(r,this.config.sonaPatternType,"test-generation");return i.success&&i.pattern?(U.info(`QESONA adapted pattern with ${i.similarity.toFixed(3)} similarity in ${i.adaptationTimeMs.toFixed(2)}ms`),[i.pattern.id]):[]}catch(r){return U.error("QESONA pattern adaptation failed:",r instanceof Error?r:void 0),[]}}async storeTestGenerationPattern(e,r){if(this.qesona)try{let i={id:`test-gen-${Date.now()}`,features:this.encodeRequestAsFeatures(r),metadata:{testCount:e.tests.length,coverageEstimate:e.coverageEstimate,success:!0}},n={type:"generate-tests",value:{testType:r.testType,framework:r.framework,patternsUsed:e.patternsUsed}},s=this.qesona.createPattern(i,n,{reward:e.coverageEstimate/100,success:!0,quality:e.coverageEstimate/100},this.config.sonaPatternType,"test-generation",{testCount:e.tests.length,framework:r.framework,testType:r.testType});U.info(`Stored test generation pattern ${s.id} in QESONA`)}catch(i){U.error("Failed to store pattern in QESONA:",i instanceof Error?i:void 0)}}async findSimilarTests(e){if(!this.flashAttention)return[];let r=[];try{for(let n of e){let s=this.generateTestEmbedding(n);this.testEmbeddings.set(n.id,s)}let i=await this.loadExistingTestEmbeddings();if(i.length===0)return[];for(let n of e){let s=this.testEmbeddings.get(n.id);if(!s)continue;let o=(await this.flashAttention.computeTestSimilarity(s,i.map(c=>c.embedding),5)).filter(c=>c.similarity>.7).map(c=>({testId:i[c.index].testId,similarity:c.similarity}));o.length>0&&r.push({test:n,similarTests:o})}return r}catch(i){return U.error("Flash Attention similarity detection failed:",i instanceof Error?i:void 0),[]}}async prioritizeTestCases(e,r){if(!this.decisionTransformer)return e;try{let i={id:`prioritize-${Date.now()}`,features:[e.length/100,(r.coverageTarget||80)/100,r.testType==="unit"?.2:r.testType==="integration"?.5:.8,r.framework==="jest"?.3:r.framework==="vitest"?.4:.5],metadata:{testCount:e.length,framework:r.framework,testType:r.testType}},n=await this.decisionTransformer.predict(i);return U.info(`DecisionTransformer prediction: ${n.reasoning}`),n.confidence>.7?e.sort((s,a)=>a.assertions-s.assertions):e}catch(i){return U.error("DecisionTransformer prioritization failed:",i instanceof Error?i:void 0),e}}getQESONAStats(){return this.qesona?this.qesona.getStats():null}getFlashAttentionMetrics(){return this.flashAttention?this.flashAttention.getMetrics():null}async checkRequirementCoherence(e){return this.coherenceGate?this.coherenceGate.checkRequirementCoherence(e):{isCoherent:!0,energy:0,lane:"reflex",contradictions:[],recommendations:[],durationMs:0,usedFallback:!0}}isCoherenceGateAvailable(){return this.coherenceGate?.isAvailable()??!1}async verifyAndEnrichSpec(e){if(!this.coherenceGate||!this.config.enableCoherenceGate)return e;let r=await this.coherenceGate.validateAndEnrich(e);if(r.success)return r.value;throw r.error}async verifyTestPatternSelection(e,r){let i=V({id:v(),type:"test-pattern-selection",confidence:r,description:`Verify test pattern: ${e.name} (${e.type})`,payload:e,detectedBy:"test-generation-coordinator",severity:r>.9?"high":"medium"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(U.info(`Test pattern '${e.name}' verified by consensus`),!0):(U.warn(`Test pattern '${e.name}' NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}async verifyMockStrategy(e,r){let i=V({id:v(),type:"mock-strategy",confidence:r,description:`Verify mock strategy for ${e.target}: ${e.mockType}`,payload:e,detectedBy:"test-generation-coordinator",severity:r>.85?"high":"medium"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(U.info(`Mock strategy for '${e.target}' verified by consensus`),!0):(U.warn(`Mock strategy for '${e.target}' NOT verified`),!1)}return!0}async verifyEdgeCaseGeneration(e,r){let i=V({id:v(),type:"edge-case-generation",confidence:r,description:`Verify edge case: ${e.description}`,payload:e,detectedBy:"test-generation-coordinator",severity:"high"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(U.info(`Edge case '${e.description.slice(0,50)}...' verified by consensus`),!0):(U.warn(`Edge case NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}encodeRequestAsFeatures(e){let r=[];for(r.push(e.testType==="unit"?.2:e.testType==="integration"?.5:.8),r.push(e.framework==="jest"?.25:e.framework==="vitest"?.5:e.framework==="mocha"?.75:.9),r.push(Math.min(1,e.sourceFiles.length/50)),r.push((e.coverageTarget||80)/100);r.length<384;)r.push(0);return r.slice(0,384)}generateTestEmbedding(e){let r=[],i=this.simpleHash(e.name);for(let n=0;n<64;n++)r.push((i>>n%32&1)*2-1);for(r.push(e.type==="unit"?.2:e.type==="integration"?.5:.8),r.push(Math.min(1,e.assertions/20));r.length<384;)r.push(0);return new Float32Array(r.slice(0,384))}async loadExistingTestEmbeddings(){try{let e=await this.memory.search("test-embedding:*",1e3),r=[];for(let i of e){let n=await this.memory.get(i);n&&r.push({testId:n.testId,embedding:new Float32Array(n.embedding)})}return r}catch{return[]}}simpleHash(e){let r=0;for(let i=0;i<e.length;i++){let n=e.charCodeAt(i);r=(r<<5)-r+n,r=r|0}return Math.abs(r)}async loadWorkflowState(){let e=await this.memory.get("test-generation:coordinator:workflows");if(e)for(let r of e)r.status==="running"&&(r.status="failed",r.error="Coordinator restarted",r.completedAt=new Date),this.workflows.set(r.id,r)}async saveWorkflowState(){let e=Array.from(this.workflows.values());await this.memory.set("test-generation:coordinator:workflows",e,{namespace:"test-generation",persist:!0})}};A();var Bn=class extends j{constructor(e,r,i,n={},s){super(e,r);this.agentCoordinator=i;this.llmRouter=s;this.pluginConfig=n}agentCoordinator;llmRouter;coordinator=null;testGenerator=null;patternMatcher=null;pluginConfig;get name(){return"test-generation"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{generateTests:this.generateTests.bind(this),generateTDDTests:this.generateTDDTests.bind(this),generatePropertyTests:this.generatePropertyTests.bind(this),generateTestData:this.generateTestData.bind(this),learnPatterns:this.learnPatterns.bind(this),getCoordinator:()=>this.coordinator,getTestGenerator:()=>this.testGenerator,getPatternMatcher:()=>this.patternMatcher}}getTaskHandlers(){return new Map([["generate-tests",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.sourceFiles,i=e.testType,n=e.framework;if(!r||r.length===0)return p(new Error("Invalid generate-tests payload: missing sourceFiles"));let s={sourceFiles:r,testType:i??"unit",framework:n??"vitest",coverageTarget:e.coverageTarget,patterns:e.patterns};return this.coordinator.generateTests(s)}],["generate-tdd-tests",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.feature,i=e.behavior,n=e.framework,s=e.phase;return!r||!i?p(new Error("Invalid generate-tdd-tests payload: missing feature or behavior")):this.coordinator.generateTDDTests({feature:r,behavior:i,framework:n??"vitest",phase:s??"red"})}],["generate-property-tests",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.function,i=e.properties;return!r||!i||i.length===0?p(new Error("Invalid generate-property-tests payload: missing function or properties")):this.coordinator.generatePropertyTests({function:r,properties:i,constraints:e.constraints})}],["generate-test-data",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.schema,i=e.count;return r?this.coordinator.generateTestData({schema:r,count:i??10,locale:e.locale,preserveRelationships:e.preserveRelationships}):p(new Error("Invalid generate-test-data payload: missing schema"))}]])}async onInitialize(){this.testGenerator=ai({memory:this.memory,llmRouter:this.llmRouter},this.pluginConfig.testGenerator),this.patternMatcher=new Pt(this.memory,this.pluginConfig.patternMatcher),this.coordinator=new yi(this.eventBus,this.memory,this.agentCoordinator,this.pluginConfig.coordinator,this.llmRouter),await this.coordinator.initialize(),this.updateHealth({status:"idle",agents:{total:0,active:0,idle:0,failed:0},lastActivity:new Date,errors:[]})}async onDispose(){this.coordinator&&await this.coordinator.dispose(),this.coordinator=null,this.testGenerator=null,this.patternMatcher=null}subscribeToEvents(){this.eventBus.subscribe("coverage-analysis.CoverageGapDetected",this.handleCoverageGap.bind(this)),this.eventBus.subscribe("code-intelligence.ImpactAnalysisCompleted",this.handleImpactAnalysis.bind(this)),this.eventBus.subscribe("learning-optimization.PatternConsolidated",this.handlePatternConsolidation.bind(this))}async onEvent(e){switch(this.updateHealth({lastActivity:new Date}),e.type){case"coverage-analysis.CoverageGapDetected":await this.handleCoverageGap(e);break;case"code-intelligence.ImpactAnalysisCompleted":await this.handleImpactAnalysis(e);break;default:break}}async generateTests(e){this.ensureInitialized();try{let r=await this.coordinator.generateTests(e);return r.success?this.trackSuccessfulGeneration(r.value):this.trackFailedGeneration(r.error),r}catch(r){return this.handleError(r)}}async generateTDDTests(e){this.ensureInitialized();try{return await this.coordinator.generateTDDTests(e)}catch(r){return this.handleError(r)}}async generatePropertyTests(e){this.ensureInitialized();try{return await this.coordinator.generatePropertyTests(e)}catch(r){return this.handleError(r)}}async generateTestData(e){this.ensureInitialized();try{return await this.coordinator.generateTestData(e)}catch(r){return this.handleError(r)}}async learnPatterns(e){this.ensureInitialized();try{return await this.coordinator.learnPatterns(e)}catch(r){return this.handleError(r)}}async handleCoverageGap(e){let r=e.payload;r.riskScore>=.7&&await this.memory.set(`test-generation:pending-gaps:${r.gapId}`,r,{namespace:"test-generation",ttl:86400})}async handleImpactAnalysis(e){let r=e.payload;await this.memory.set(`test-generation:impact:${r.analysisId}`,r,{namespace:"test-generation",ttl:3600})}async handlePatternConsolidation(e){e.payload.domains.includes("test-generation")}ensureInitialized(){if(!this._initialized)throw new Error("TestGenerationPlugin is not initialized");if(!this.coordinator||!this.testGenerator||!this.patternMatcher)throw new Error("TestGenerationPlugin services are not available")}handleError(e){let r=y(e),i=this.getHealth();return this.updateHealth({errors:[...i.errors.slice(-9),r.message],status:i.errors.length>=5?"degraded":i.status}),{success:!1,error:r}}trackSuccessfulGeneration(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,total:r.agents.total+1,idle:r.agents.idle+1},lastActivity:new Date})}trackFailedGeneration(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,failed:r.agents.failed+1},errors:[...r.errors.slice(-9),e.message]})}};function Lo(u,t,e,r,i){return new Bn(u,t,e,r,i)}M();M();import{spawn as oh}from"node:child_process";import{existsSync as Cu,readFileSync as ch}from"node:fs";import{join as Su}from"node:path";var Ue={DEFAULT_TEST_TIMEOUT_MS:6e4,DEFAULT_FILE_TIMEOUT_MS:3e4,DEFAULT_VIEWPORT_WIDTH:1280,DEFAULT_VIEWPORT_HEIGHT:720,MAX_RESULTS:1e3,RESULT_RETENTION_MS:864e5,MAX_TESTS_TRACKED:1e4,MAX_EXECUTION_HISTORY:100,ANALYSIS_CACHE_TTL_MS:36e5,MAX_RETRY_HISTORY:50,MAX_ACTIONS_PER_RECORDING:1e3,MAX_RECORDING_DURATION_MS:18e5,MAX_WORKERS:32},qn={DEFAULT_STEP_TIMEOUT_MS:3e4,RETRY_DELAY_MS:1e3,DEFAULT_MAX_RETRIES:3,POLLING_INTERVAL_MS:100,ELEMENT_DETECTION_TIMEOUT_MS:1e3,POST_INTERACTION_DELAY_MS:500,DEFAULT_WAIT_MS:1e3,ACCESSIBILITY_TIMEOUT_MS:6e4,SCREENSHOT_QUALITY:80,TYPE_DEBOUNCE_MS:300},or={BASE_DELAY_MS:1e3,MAX_DELAY_MS:3e4,DEFAULT_FLAKY_RATE:.3,DEFAULT_FLAKY_PASS_RATE:.7,RETRY_PASS_RATE_VARIATION:.1,SIGKILL_GRACE_PERIOD_MS:1e3},Gn={DEFAULT_TIMEOUT_MS:6e4,QUICK_TIMEOUT_MS:1e4,MAX_CACHED_VALIDATIONS:1e3,CACHE_TTL_MS:36e5,CONTRACT_TTL_SECONDS:86400,MIGRATION_TTL_SECONDS:86400*90,MAX_RECURSION_DEPTH:10,MAX_SCHEMA_DEPTH:20,MAX_MIGRATION_STEPS:50,DEFAULT_SEARCH_LIMIT:100,HIGH_IMPACT_THRESHOLD:5,BREAKING_CHANGE_THRESHOLD:10,DEFAULT_PROVIDER_LOAD:50,HIGH_PROVIDER_LOAD_THRESHOLD:80},wT={PASSING_RATE_WARNING_THRESHOLD:95,PASSING_RATE_CRITICAL_THRESHOLD:80,MIN_COVERAGE_FOR_DEPLOY:80,PERFECT_PASSING_RATE:100,METRIC_TTL_SECONDS:86400*7,STANDARD_METRIC_TTL_SECONDS:86400,MAX_HIGH_VULN_IMPACT:.3,MEDIUM_VULN_IMPACT:.1,MAX_DUPLICATION_PERCENT:20};var CT={CHUNK_SIZE_BYTES:1024*1024,SPIKE_INTERVAL_MS:3e4,SPIKE_DURATION_MS:5e3};var ST={MAX_DURATION_MS:6e4,MAX_AGE_MS:10080*60*1e3,DAYS_IN_YEAR:365,MAX_DEPENDENCY_COUNT:10},Hn={MAX_TOKENS:2048,ERROR_TRUNCATION_LENGTH:200,OUTPUT_TRUNCATION_LENGTH:500,DETAILED_OUTPUT_TRUNCATION_LENGTH:1e3,MODEL_TIERS:{1:"claude-haiku-4-5",2:"claude-sonnet-4-6",3:"claude-sonnet-4-6",4:"claude-opus-4-7"}};A();H();se();var lh={simulateForTesting:!1,simulatedTestsPerFile:5,simulatedFailureRate:.2,simulatedSkipRate:.1,enableLLMAnalysis:!0,llmModelTier:2,llmMaxTokens:Hn.MAX_TOKENS},uh=R.create("test-execution/test-executor"),jn=class{runResults=new Map;runStats=new Map;config;memory;llmRouter;MAX_RESULTS=Ue.MAX_RESULTS;RESULT_RETENTION_MS=Ue.RESULT_RETENTION_MS;constructor(t,e={}){this.memory=t.memory,this.llmRouter=t.llmRouter,this.config={...lh,...e}}async execute(t){let e=v(),r=new Date;try{let i=this.validateRequest(t);if(i.success===!1)return p(i.error);let n=await this.runTests(t),s=new Date,a=s.getTime()-r.getTime(),o={runId:e,status:n.failed>0?"failed":"passed",total:n.total,passed:n.passed,failed:n.failed,skipped:n.skipped,duration:a,failedTests:n.failedTests,coverage:n.coverage,fileCoverages:n.fileCoverages};this.runResults.set(e,o),await this.storeResults(e,o);let c={runId:e,startTime:r,endTime:s,duration:a,testsPerSecond:n.total/(a/1e3),workers:1,memoryUsage:process.memoryUsage?.().heapUsed??0};return this.runStats.set(e,c),f(o)}catch(i){return p(y(i))}}async executeParallel(t){let e=v(),r=new Date;try{let i=this.validateParallelRequest(t);if(i.success===!1)return p(i.error);let{workers:n,sharding:s="file",isolation:a="process"}=t,o=this.shardTests(t.testFiles,n,s),c=await Promise.all(o.map((b,w)=>this.executeWorker(b,w,a,t))),l=this.aggregateResults(c),d=new Date,m=d.getTime()-r.getTime(),h={runId:e,status:l.failed>0?"failed":"passed",total:l.total,passed:l.passed,failed:l.failed,skipped:l.skipped,duration:m,failedTests:l.failedTests,coverage:l.coverage,fileCoverages:l.fileCoverages};this.runResults.set(e,h),await this.storeResults(e,h);let g={runId:e,startTime:r,endTime:d,duration:m,testsPerSecond:l.total/(m/1e3),workers:n,memoryUsage:process.memoryUsage?.().heapUsed??0};return this.runStats.set(e,g),f(h)}catch(i){return p(y(i))}}async getResults(t){let e=this.runResults.get(t);if(e)return f(e);try{let r=await this.memory.get(`test-run:${t}`);if(r)return this.runResults.set(t,r),f(r)}catch{}return p(new Error(`Test run not found: ${t}`))}async getStats(t){let e=this.runStats.get(t);if(e)return f(e);try{let r=await this.memory.get(`test-stats:${t}`);if(r)return this.runStats.set(t,r),f(r)}catch{}return p(new Error(`Test stats not found: ${t}`))}cleanupOldResults(){let t=Date.now(),e=0;for(let[r,i]of this.runResults){let n=i.duration?t-i.duration:t;t-n>this.RESULT_RETENTION_MS&&(this.runResults.delete(r),this.runStats.delete(r),e++)}if(this.runResults.size>this.MAX_RESULTS){let r=this.runResults.size-this.MAX_RESULTS,i=Array.from(this.runResults.entries());for(let n=0;n<r&&n<i.length;n++)this.runResults.delete(i[n][0]),this.runStats.delete(i[n][0]),e++}return e}destroy(){this.runResults.clear(),this.runStats.clear()}isLLMAnalysisAvailable(){return this.config.enableLLMAnalysis&&this.llmRouter!==void 0}getModelForTier(t){let e={1:"claude-haiku-4-5",2:"claude-sonnet-4-6",3:"claude-sonnet-4-6",4:"claude-opus-4-7"};return e[t]||e[2]}async analyzeFailuresWithLLM(t){if(!this.isLLMAnalysisAvailable()||t.length===0)return null;try{let e=t.slice(0,5).map(i=>`- ${i.testName}: ${i.error?.substring(0,200)||"Unknown error"}`).join(`
|
|
2275
|
+
`))}async getQValue(t,e,r,i){this.ensureInitialized();let n=this.prepared.get("getQValue");if(!n)throw new Error("Statement not prepared");let s=i??this.config.defaultAlgorithm;return n.get(t,e,r,s)?.q_value??0}async setQValue(t,e,r,i,n,s){this.ensureInitialized();let a=this.prepared.get("upsertQValue");if(!a)throw new Error("Statement not prepared");let o=v(),c=s?.algorithm??this.config.defaultAlgorithm;a.run(o,c,t,e,r,i,n??null,s?.domain??null)}async incrementVisits(t,e,r,i){this.ensureInitialized();let n=this.prepared.get("incrementVisits");if(!n)throw new Error("Statement not prepared");let s=i??this.config.defaultAlgorithm;n.run(t,e,r,s)}async getTopActions(t,e,r=10,i){this.ensureInitialized();let n=this.prepared.get("getTopActions");if(!n)throw new Error("Statement not prepared");let s=i??this.config.defaultAlgorithm;return n.all(t,e,s,r).map(o=>this.rowToEntry(o))}async exportForAgent(t,e){this.ensureInitialized();let r=this.prepared.get("getAllForAgent");if(!r)throw new Error("Statement not prepared");let i=e??this.config.defaultAlgorithm,n=r.all(t,i),s=new Map;for(let a of n){let o=a.state_key,c=a.action_key,l=a.q_value;s.has(o)||s.set(o,new Map),s.get(o).set(c,l)}return s}async importFromMap(t,e,r){if(this.ensureInitialized(),!this.db)throw new Error("Database not initialized");let i=this.prepared.get("upsertQValue");if(!i)throw new Error("Statement not prepared");let n=r?.algorithm??this.config.defaultAlgorithm;this.db.transaction(()=>{for(let[a,o]of e)for(let[c,l]of o){let d=v();i.run(d,n,t,a,c,l,null,r?.domain??null)}})()}async pruneOldEntries(t){this.ensureInitialized();let e=this.prepared.get("pruneOld");if(!e)throw new Error("Statement not prepared");return e.run(t).changes}async getStats(){this.ensureInitialized();let t=this.prepared.get("getStats"),e=this.prepared.get("countByAlgorithm"),r=this.prepared.get("countByDomain");if(!t||!e||!r)throw new Error("Statements not prepared");let i=t.get(),n=e.all(),s=r.all(),a={};for(let c of n)a[c.algorithm]=c.count;let o={};for(let c of s)c.domain&&(o[c.domain]=c.count);return{totalEntries:i.total_entries,uniqueAgents:i.unique_agents,uniqueStates:i.unique_states,byAlgorithm:a,byDomain:o,averageVisits:i.avg_visits??0,averageQValue:i.avg_q_value??0,oldestEntry:i.oldest_entry?new Date(i.oldest_entry):null,newestEntry:i.newest_entry?new Date(i.newest_entry):null}}async close(){this.prepared.clear(),this.db=null,this.persistence=null,this.initialized=!1}async getEntry(t,e,r,i){this.ensureInitialized();let n=this.prepared.get("getEntry");if(!n)throw new Error("Statement not prepared");let s=i??this.config.defaultAlgorithm,a=n.get(t,e,r,s);return a?this.rowToEntry(a):null}async deleteEntry(t,e,r,i){this.ensureInitialized();let n=this.prepared.get("deleteEntry");if(!n)throw new Error("Statement not prepared");let s=i??this.config.defaultAlgorithm;return n.run(t,e,r,s).changes>0}isInitialized(){return this.initialized}getDbPath(){return this.persistence?.getDbPath()??""}ensureInitialized(){if(!this.initialized)throw new Error("QValueStore not initialized. Call initialize() first.")}rowToEntry(t){return{id:t.id,algorithm:t.algorithm,agentId:t.agent_id,stateKey:t.state_key,actionKey:t.action_key,qValue:t.q_value,visits:t.visits,lastReward:t.last_reward,domain:t.domain,createdAt:new Date(t.created_at),updatedAt:new Date(t.updated_at)}}};H();M();var vu=R.create("rl-base-algorithm"),bu={learningRate:.001,discountFactor:.99,episodes:1e3,maxSteps:1e3,batchSize:32,replayBufferSize:1e4,targetUpdateFrequency:100,explorationRate:.3,explorationDecay:.995,minExplorationRate:.01},ih={enabled:!1,autoSaveInterval:10},oe=class{constructor(t,e,r={},i=[],n={}){this.type=t;this.category=e;this.config={...bu,...r},this.rewardSignals=i,this.persistenceConfig={...ih,...n},this.stats=this.createInitialStats()}type;category;config;stats;replayBuffer=[];episodeCount=0;totalReward=0;rewardHistory=[];initialized=!1;rewardSignals=[];persistenceConfig;qValueStore=null;lastSaveEpisode=0;enablePersistence(t,e){this.persistenceConfig.enabled=!0,this.persistenceConfig.agentId=t,e&&(this.persistenceConfig.dbPath=e)}isPersistenceEnabled(){return this.persistenceConfig.enabled&&!!this.persistenceConfig.agentId}getPersistenceAgentId(){return this.persistenceConfig.agentId}async train(t){if(this.addToReplayBuffer(t),this.replayBuffer.length>=this.config.batchSize){let e=this.sampleBatch();return this.trainBatch(e)}return this.getStats()}async trainBatch(t){this.initialized||await this.initialize();let e=Date.now();try{this.episodeCount++;let r=t.reduce((n,s)=>n+s.reward,0);this.totalReward+=r,this.rewardHistory.push(r),this.rewardHistory.length>1e3&&this.rewardHistory.shift();let i=await this.trainCore(t);return this.stats={...i,episode:this.episodeCount,totalReward:this.totalReward,averageReward:this.rewardHistory.reduce((n,s)=>n+s,0)/this.rewardHistory.length,trainingTimeMs:Date.now()-e,timestamp:new Date},this.config.explorationRate=Math.max(this.config.minExplorationRate,this.config.explorationRate*this.config.explorationDecay),this.stats.explorationRate=this.config.explorationRate,await this.autoSaveToPersistence(),this.stats}catch(r){throw new Vn(`Training failed for ${this.type}: ${r.message}`,this.type,r)}}async autoSaveToPersistence(){if(!this.isPersistenceEnabled()||this.persistenceConfig.autoSaveInterval<=0)return;if(this.episodeCount-this.lastSaveEpisode>=this.persistenceConfig.autoSaveInterval)try{await this.saveToStore(this.persistenceConfig.agentId,this.qValueStore??void 0),this.lastSaveEpisode=this.episodeCount}catch(e){console.warn(`[${this.type}] Auto-save failed:`,e.message)}}async update(t){let e={...this.config};if(this.config={...this.config,...t},this.config.learningRate<=0||this.config.learningRate>1)throw new ct(`Invalid learning rate: ${this.config.learningRate}`,this.type);if(this.config.discountFactor<0||this.config.discountFactor>1)throw new ct(`Invalid discount factor: ${this.config.discountFactor}`,this.type);if(this.config.explorationRate<0||this.config.explorationRate>1)throw new ct(`Invalid exploration rate: ${this.config.explorationRate}`,this.type);await this.handleConfigUpdate(e,this.config)}getStats(){return{...this.stats}}async reset(){this.isPersistenceEnabled()&&this.episodeCount>0&&await this.saveToStore(this.persistenceConfig.agentId,this.qValueStore??void 0),this.replayBuffer=[],this.episodeCount=0,this.totalReward=0,this.rewardHistory=[],this.lastSaveEpisode=0,this.config.explorationRate=bu.explorationRate,this.stats=this.createInitialStats(),await this.resetAlgorithm()}async close(){this.isPersistenceEnabled()&&this.episodeCount>this.lastSaveEpisode&&await this.saveToStore(this.persistenceConfig.agentId,this.qValueStore??void 0),this.qValueStore&&(await this.qValueStore.close(),this.qValueStore=null)}async exportModel(){return{type:this.type,category:this.category,version:this.getVersion(),config:this.config,stats:this.stats,replayBufferSize:this.replayBuffer.length,exportedAt:new Date().toISOString(),customData:await this.exportCustomData()}}async importModel(t){if(t.type!==this.type)throw new ct(`Model type mismatch: expected ${this.type}, got ${t.type}`,this.type);if(t.category!==this.category)throw new ct(`Algorithm category mismatch: expected ${this.category}, got ${t.category}`,this.type);t.config&&(this.config={...this.config,...t.config}),t.stats&&(this.stats={...this.stats,...t.stats}),t.customData&&await this.importCustomData(t.customData),this.initialized=!0}getInfo(){let t=this.getAlgorithmInfo();return{...t,stats:this.stats,hyperparameters:{...t.hyperparameters,learningRate:this.config.learningRate,discountFactor:this.config.discountFactor,explorationRate:this.config.explorationRate,batchSize:this.config.batchSize}}}async saveToStore(t,e){let r=e??new lt;await r.initialize();let i=await this.exportModel();await r.setQValue(t,"__model_state__","__weights__",0,void 0,{algorithm:this.type,domain:JSON.stringify(i)})}async loadFromStore(t,e){let r=e??new lt;await r.initialize();try{let i=await r.getQValue(t,"__model_state__","__weights__",this.type),n=await r.getEntry(t,"__model_state__","__weights__",this.type);if(!n?.domain)return!1;let s=E(n.domain);return await this.importModel(s),!0}catch(i){return vu.debug("Model load from store failed",{algorithm:this.type,error:i instanceof Error?i.message:String(i)}),!1}}async storeQValue(t,e,r,i,n,s){let a=s??new lt;await a.initialize(),await a.setQValue(t,e,r,i,n,{algorithm:this.type})}async retrieveQValue(t,e,r,i){let n=i??new lt;await n.initialize();try{return await n.getQValue(t,e,r,this.type)}catch(s){return vu.debug("Q-value retrieval failed",{agentId:t,stateKey:e,actionKey:r,error:s instanceof Error?s.message:String(s)}),null}}calculateReward(t){let e={},r=0,i=[];for(let n of this.rewardSignals){let s=n.calculate(t);e[n.name]=s,r+=s,s!==0&&i.push(`${n.name}: ${s.toFixed(3)} (${n.description})`)}return{totalReward:Math.max(-1,Math.min(1,r)),components:e,reasoning:i.join("; ")||"No reward signals triggered",timestamp:new Date}}addToReplayBuffer(t){this.replayBuffer.push(t),this.replayBuffer.length>this.config.replayBufferSize&&this.replayBuffer.shift()}sampleBatch(t){let e=t||this.config.batchSize,r=this.replayBuffer;if(r.length===0)return[];if(r.length<=e)return[...r];let i=new Set;for(;i.size<Math.min(e,r.length);)i.add(ue(0,r.length));return Array.from(i).map(n=>r[n])}epsilonGreedy(t,e){return L()<this.config.explorationRate?t():e()}normalizeFeatures(t){if(t.length===0)return[];let e=Math.max(...t.map(Math.abs));return e===0?t:t.map(r=>r/e)}stateToKey(t){let e=t.features.map((r,i)=>`${i}:${Math.round(r*100)/100}`).join(",");return`${t.id}|${e}`}async initialize(){this.isPersistenceEnabled()&&(await this.initializePersistence(),await this.loadFromStore(this.persistenceConfig.agentId)&&console.log(`[${this.type}] Loaded persisted state for agent: ${this.persistenceConfig.agentId}`)),this.initialized=!0}async initializePersistence(){this.qValueStore||(this.qValueStore=new lt,await this.qValueStore.initialize())}async resetAlgorithm(){}async handleConfigUpdate(t,e){}async exportCustomData(){return{}}async importCustomData(t){}getVersion(){return"1.0.0"}createInitialStats(){return{episode:0,totalReward:0,averageReward:0,explorationRate:this.config.explorationRate,trainingTimeMs:0,timestamp:new Date}}};Zi();var nh={contextLength:10,embeddingDim:384,numHeads:4,numLayers:3,feedForwardDim:256,maxReturn:100},ar=class extends oe{trajectories=[];dtConfig;stateEmbeddings=new Map;actionEmbeddings=new Map;constructor(t={}){super("decision-transformer","offline-rl"),this.dtConfig={...nh,...t}}async predict(t){this.initialized||await this.initialize();let e=this.retrieveContext(t),r=this.calculateReturnToGo(e),i=this.generateAction(t,e,r),n=this.calculateConfidence(e,r);return{action:i,confidence:n,value:r,reasoning:this.generateReasoning(t,i,e,r)}}async trainCore(t){let e=this.groupIntoTrajectories(t);for(let i of e)this.calculateReturns(i);this.trajectories.push(...e),this.trajectories.length>1e3&&(this.trajectories=this.trajectories.slice(-1e3)),this.updateEmbeddings(e);let r=e.reduce((i,n)=>i+n.returns[n.returns.length-1],0)/e.length;return{episode:this.episodeCount,totalReward:this.totalReward,averageReward:this.rewardHistory.reduce((i,n)=>i+n,0)/this.rewardHistory.length,loss:Math.abs(r-this.targetReturn()),explorationRate:0,trainingTimeMs:0,timestamp:new Date}}getAlgorithmInfo(){return{type:this.type,category:this.category,version:"1.0.0",description:"Decision Transformer for Test Case Prioritization",capabilities:["Offline RL from historical data","Attention-based sequence modeling","Return-to-go conditioning","Context-aware decisions"],hyperparameters:{contextLength:this.dtConfig.contextLength,embeddingDim:this.dtConfig.embeddingDim,numHeads:this.dtConfig.numHeads,numLayers:this.dtConfig.numLayers},stats:this.stats}}retrieveContext(t){let e=this.trajectories.map(r=>{let i=this.calculateSimilarity(t,r);return{traj:r,similarity:i}});return e.sort((r,i)=>i.similarity-r.similarity),e.slice(0,this.dtConfig.contextLength).map(r=>r.traj)}calculateSimilarity(t,e){for(let r of e.states)if(this.statesMatch(t,r))return 1;if(e.states.length>0){let r=e.states[e.states.length-1];return tt(t.features,r.features)}return 0}statesMatch(t,e){return t.id===e.id||Math.abs(t.features[0]-e.features[0])<.1}calculateReturnToGo(t){if(t.length===0)return 0;let e=t.flatMap(r=>r.returns);return e.reduce((r,i)=>r+i,0)/e.length}calculateReturns(t){let e=[],r=0;for(let i=t.rewards.length-1;i>=0;i--)r=t.rewards[i]+this.config.discountFactor*r,e.unshift(r);t.returns=e}targetReturn(){return this.dtConfig.maxReturn*.8}generateAction(t,e,r){for(let i of e)for(let n=0;n<i.states.length;n++)if(this.statesMatch(t,i.states[n])&&i.returns[n]>r*.8)return{...i.actions[n]};return this.getHeuristicAction(t)}getHeuristicAction(t){return{type:"prioritize",value:t.features[0]>.7?"high":"standard",metadata:{heuristic:!0}}}updateEmbeddings(t){for(let e of t){for(let r of e.states)this.stateEmbeddings.has(r.id)||this.stateEmbeddings.set(r.id,this.hashEmbedding(r.id));for(let r of e.actions){let i=this.actionToKey(r);this.actionEmbeddings.has(i)||this.actionEmbeddings.set(i,this.hashEmbedding(i))}}}hashEmbedding(t){let e=[],r=this.dtConfig.embeddingDim;for(let i=0;i<r;i++){let n=this.simpleHash(t+i);e.push((n%200-100)/100)}return e}simpleHash(t){let e=0;for(let r=0;r<t.length;r++){let i=t.charCodeAt(r);e=(e<<5)-e+i,e=e&e}return Math.abs(e)}actionToKey(t){return`${t.type}:${JSON.stringify(t.value)}`}groupIntoTrajectories(t){let e=[],r=null;for(let i of t)i.done||!r?(r&&e.push(r),r={states:[i.state],actions:[i.action],rewards:[i.reward],returns:[]}):(r.states.push(i.state),r.actions.push(i.action),r.rewards.push(i.reward));return r&&e.push(r),e}calculateConfidence(t,e){if(t.length===0)return .3;let r=Math.min(1,t.length/this.dtConfig.contextLength),i=Math.min(1,e/this.targetReturn());return .3+r*.4+i*.3}generateReasoning(t,e,r,i){if(r.length===0)return"Decision Transformer: No similar historical contexts, using heuristic";let n=r.reduce((s,a)=>s+a.returns[a.returns.length-1]||0,0)/r.length;return`Decision Transformer: Found ${r.length} similar contexts (avg return: ${n.toFixed(2)}), selecting ${e.type} action with return-to-go ${i.toFixed(2)}`}async exportCustomData(){return{trajectories:this.trajectories,stateEmbeddings:Object.fromEntries(this.stateEmbeddings),actionEmbeddings:Object.fromEntries(this.actionEmbeddings),dtConfig:this.dtConfig}}async importCustomData(t){t.trajectories&&(this.trajectories=t.trajectories),t.stateEmbeddings&&(this.stateEmbeddings=new Map(Object.entries(t.stateEmbeddings))),t.actionEmbeddings&&(this.actionEmbeddings=new Map(Object.entries(t.actionEmbeddings))),t.dtConfig&&(this.dtConfig={...this.dtConfig,...t.dtConfig})}async resetAlgorithm(){this.trajectories=[],this.stateEmbeddings.clear(),this.actionEmbeddings.clear()}};Ge();M();var wu={enabled:!0,coherenceThreshold:.1,blockOnHumanLane:!0,enrichOnRetrievalLane:!0,embeddingDimension:384},sh=R.create("test-generation/coherence-gate"),_n=class extends Error{constructor(e,r,i){super(e);this.contradictions=r;this.lane=i;this.name="CoherenceError"}contradictions;lane},Mo=class{constructor(t=384){this.dimension=t}dimension;async embed(t){let e=new Array(this.dimension).fill(0),r=t.toLowerCase().trim();for(let n=0;n<r.length;n++){let s=r.charCodeAt(n),a=n%this.dimension;e[a]+=Math.sin(s*(n+1)*.1),e[(a+1)%this.dimension]+=Math.cos(s*(n+1)*.1)}let i=Math.sqrt(e.reduce((n,s)=>n+s*s,0));if(i>0)for(let n=0;n<e.length;n++)e[n]/=i;return e}},zn=class{constructor(t,e,r={}){this.coherenceService=t;this.config={...wu,...r},this.embeddingService=e||new Mo(this.config.embeddingDimension)}coherenceService;config;embeddingService;async checkRequirementCoherence(t){let e=Date.now();if(!this.config.enabled||!this.coherenceService)return this.createPassingResult(e,!0);if(t.length===0)return this.createPassingResult(e,!1);if(t.length===1)return this.createPassingResult(e,!1);try{let r=await this.requirementsToNodes(t),i=await this.coherenceService.checkCoherence(r);return this.transformCoherenceResult(i,t,Date.now()-e)}catch(r){return sh.error("Coherence check failed:",r instanceof Error?r:void 0),{isCoherent:!0,energy:0,lane:"reflex",contradictions:[],recommendations:[{type:"add-context",requirementId:"",description:"Coherence check failed. Manual review recommended.",suggestedResolution:"Review requirements manually before proceeding."}],durationMs:Date.now()-e,usedFallback:!0}}}async enrichSpecification(t,e){if(e.length===0)return t;let r={...t,requirements:[...t.requirements],context:{...t.context}},i=new Map;for(let n of e)switch(n.type){case"clarify":this.addClarificationNote(i,n);break;case"add-context":r.context={...r.context,coherenceRecommendations:[...r.context?.coherenceRecommendations||[],n.description]};break;case"resolve-ambiguity":this.addDisambiguationNote(i,n);break;case"split-requirement":r.context={...r.context,requirementsSuggestedForSplit:[...r.context?.requirementsSuggestedForSplit||[],n.requirementId]};break}return r.requirements=r.requirements.map(n=>{let s=i.get(n.id);return s?{...n,metadata:{...n.metadata,...s.metadata}}:n}),r.context={...r.context,enrichedAt:new Date().toISOString(),enrichmentCount:e.length},r}async validateAndEnrich(t){let e=await this.checkRequirementCoherence(t.requirements);if(this.config.blockOnHumanLane&&e.lane==="human")return p(new _n("Requirements contain unresolvable contradictions that require human review",e.contradictions,e.lane));if(this.config.enrichOnRetrievalLane&&e.lane==="retrieval"){let r=await this.enrichSpecification(t,e.recommendations);return f(r)}return f(t)}isAvailable(){return this.coherenceService?.isInitialized()??!1}async requirementsToNodes(t){let e=[];for(let r of t){let i=await this.embeddingService.embed(r.description);e.push({id:r.id,embedding:i,weight:this.priorityToWeight(r.priority),metadata:{description:r.description,source:r.source,...r.metadata}})}return e}transformCoherenceResult(t,e,r){let i=new Map(e.map(a=>[a.id,a])),n=t.contradictions.map(a=>({requirementId1:a.nodeIds[0],requirementId2:a.nodeIds[1],severity:this.mapSeverity(a.severity),description:a.description,confidence:a.confidence,suggestedResolution:a.resolution||this.generateResolutionSuggestion(i.get(a.nodeIds[0]),i.get(a.nodeIds[1]),a.severity)})),s=this.generateRecommendations(t,n,e);return{isCoherent:t.isCoherent,energy:t.energy,lane:t.lane,contradictions:n,recommendations:s,durationMs:r,usedFallback:t.usedFallback}}generateRecommendations(t,e,r){let i=[];for(let s of t.recommendations)i.push({type:"add-context",requirementId:"",description:s});for(let s of e)s.severity==="critical"||s.severity==="high"?i.push({type:"resolve-ambiguity",requirementId:s.requirementId1,description:`Potential conflict with requirement ${s.requirementId2}: ${s.description}`,suggestedResolution:s.suggestedResolution}):i.push({type:"clarify",requirementId:s.requirementId1,description:`Minor tension with requirement ${s.requirementId2}: ${s.description}`});let n=r.filter(s=>s.description.length>200||s.description.includes(" and ")&&s.description.includes(" or "));for(let s of n)i.push({type:"split-requirement",requirementId:s.id,description:"Complex requirement may benefit from splitting into smaller, focused requirements"});return i}generateResolutionSuggestion(t,e,r){return!t||!e?"Review and reconcile conflicting requirements.":r==="critical"?`Requirements "${t.id}" and "${e.id}" appear to be mutually exclusive. Consider removing one or explicitly documenting the conditions under which each applies.`:r==="high"?`Requirements "${t.id}" and "${e.id}" may conflict. Add clarification about their relationship and precedence.`:`Minor tension between "${t.id}" and "${e.id}". Consider adding context to clarify their relationship.`}createPassingResult(t,e){return{isCoherent:!0,energy:0,lane:"reflex",contradictions:[],recommendations:[],durationMs:Date.now()-t,usedFallback:e}}priorityToWeight(t){switch(t){case"high":return 1;case"medium":return .7;case"low":return .4;default:return .5}}mapSeverity(t){switch(t){case"critical":return"critical";case"high":return"high";case"medium":return"medium";default:return"low"}}addClarificationNote(t,e){let r=t.get(e.requirementId)||{metadata:{}},i=r.metadata?.clarificationNotes||[];i.push(e.description),t.set(e.requirementId,{...r,metadata:{...r.metadata,clarificationNotes:i,needsClarification:!0}})}addDisambiguationNote(t,e){let r=t.get(e.requirementId)||{metadata:{}},i=r.metadata?.disambiguationNotes||[];i.push(e.description),t.set(e.requirementId,{...r,metadata:{...r.metadata,disambiguationNotes:i,needsDisambiguation:!0,suggestedResolution:e.suggestedResolution}})}};function Fo(u,t,e){return new zn(u,t,e)}var ah={maxConcurrentWorkflows:5,defaultTimeout:6e4,enablePatternLearning:!0,publishEvents:!0,enableQESONA:!0,enableFlashAttention:!0,enableDecisionTransformer:!0,sonaPatternType:"test-generation",flashAttentionWorkload:"test-similarity",enableCoherenceGate:!0,blockOnIncoherentRequirements:!0,enrichOnRetrievalLane:!0,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},U=R.create("test-generation"),yi=class extends Q{constructor(e,r,i,n={},s,a,o){let c={...ah,...n};super(e,"test-generation",c,{verifyFindingTypes:["test-pattern-selection","mock-strategy","edge-case-generation","assertion-strategy"],...c.consensusConfig});this.memory=r;this.agentCoordinator=i;this.coherenceService=a;this.hookRegistry=o;this.testGenerator=ai({memory:r,llmRouter:s}),this.patternMatcher=new Pt(r),this.config.enableCoherenceGate&&a&&(this.coherenceGate=Fo(a,void 0,{enabled:!0,blockOnHumanLane:this.config.blockOnIncoherentRequirements,enrichOnRetrievalLane:this.config.enrichOnRetrievalLane}))}memory;agentCoordinator;coherenceService;hookRegistry;testGenerator;patternMatcher;qesona=null;flashAttention=null;decisionTransformer=null;testEmbeddings=new Map;recentDreamInsights=[];coherenceGate=null;async onInitialize(){if(this.config.enableQESONA)try{this.qesona=await pe({domain:"test-generation",loadOnInit:!0,autoSaveInterval:6e4,patternClusters:50,minConfidence:.5}),U.info("PersistentSONAEngine initialized for test-generation domain")}catch(e){U.error("Failed to initialize PersistentSONAEngine:",e instanceof Error?e:void 0),U.warn("Continuing without SONA pattern persistence"),this.qesona=null}if(this.config.enableFlashAttention)try{this.flashAttention=await Me(this.config.flashAttentionWorkload,{dim:384,strategy:"flash",blockSize:64}),U.info("QEFlashAttention initialized for test-similarity")}catch{U.warn("QEFlashAttention unavailable (optional native module), continuing without it"),this.flashAttention=null}if(this.config.enableDecisionTransformer)try{this.decisionTransformer=new ar({contextLength:10,embeddingDim:384}),U.info("DecisionTransformer created for test case selection")}catch{U.warn("DecisionTransformer unavailable (optional native module), continuing without it"),this.decisionTransformer=null}this.subscribeToEvents(),await this.loadWorkflowState()}async onDispose(){await this.saveWorkflowState(),this.flashAttention&&(this.flashAttention.dispose(),this.flashAttention=null),this.decisionTransformer&&(await this.decisionTransformer.reset(),this.decisionTransformer=null),this.qesona&&(await this.qesona.close(),this.qesona=null),this.testEmbeddings.clear()}getActiveWorkflows(){return super.getActiveWorkflows()}async generateTests(e){let r=v();try{if(this.startWorkflow(r,"generate"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&U.warn("Topology degraded, using conservative strategy"),this.minCutMixin.shouldPauseOperations())return p(new Error("Test generation paused: topology is in critical state"));let i=[];if(this.hookRegistry)try{let c=e.sourceFiles?.[0]||"",l=await this.hookRegistry.emit(xl.PreTestGeneration,{targetFile:c,testType:e.testType,framework:e.framework,language:c.split(".").pop()||"typescript"});for(let d of l)d.success&&d.data?.patterns&&i.push(...d.data.patterns),d.guidance&&U.info(`Hook guidance: ${d.guidance.join("; ")}`)}catch{U.debug("PreTestGeneration hook failed:")}if(!this.agentCoordinator.canSpawn())return p(new Error("Agent limit reached, cannot spawn test generation agents"));let n=await this.spawnTestGeneratorAgent(r,e);if(!n.success)return this.failWorkflow(r,n.error.message),p(n.error);this.addAgentToWorkflow(r,n.value);let s=[...e.patterns||[],...i];if(this.config.enableQESONA&&this.qesona){let c=await this.adaptTestGenerationPatterns(e);c.length>0&&(s=c,U.info(`Adapted ${c.length} patterns using QESONA`))}let a=s;if(this.config.enablePatternLearning&&a.length===0){let c=await this.patternMatcher.findMatchingPatterns({testType:e.testType,framework:e.framework});c.success&&c.value.length>0&&(a=c.value.map(l=>l.pattern.id))}let o=await this.testGenerator.generateTests({...e,patterns:a});if(o.success){if(this.completeWorkflow(r),this.config.enableFlashAttention&&this.flashAttention){let c=await this.findSimilarTests(o.value.tests);c.length>0&&U.info(`Found ${c.length} similar tests using Flash Attention`)}if(this.config.enableDecisionTransformer&&this.decisionTransformer){let c=await this.prioritizeTestCases(o.value.tests,e);U.info(`Prioritized ${c.length} tests using DecisionTransformer`)}if(this.config.publishEvents){await this.publishTestSuiteCreated(o.value,e);for(let c of o.value.tests)await this.publishTestGenerated(c,e.framework??"vitest")}if(St()&&this.qesona?.isThreeLoopEnabled()){let c=o.value;this.qesona.instantAdapt([c.tests.length/20,c.coverageEstimate/100,c.patternsUsed.length/10,e.sourceFiles.length/20,(e.coverageTarget??80)/100,c.tests.filter(l=>l.type==="unit").length/20]);try{if(this.qesona.recordOutcome(1),this.qesona.shouldConsolidate())try{this.qesona.backgroundConsolidate()}catch{}}catch{}}this.config.enableQESONA&&this.qesona&&await this.storeTestGenerationPattern(o.value,e),this.config.enablePatternLearning&&await this.learnFromGeneration(o.value)}else this.failWorkflow(r,o.error.message),this.config.publishEvents&&await this.publishGenerationFailed(o.error,"generateTests");return await this.agentCoordinator.stop(n.value),o}catch(i){let n=y(i);return this.failWorkflow(r,n.message),this.config.publishEvents&&await this.publishGenerationFailed(n,"generateTests"),{success:!1,error:n}}}async generateTDDTests(e){let r=v();try{this.startWorkflow(r,"tdd");let i=await this.spawnTDDAgent(r,e);if(!i.success)return this.failWorkflow(r,i.error.message),p(i.error);this.addAgentToWorkflow(r,i.value);let n=await this.testGenerator.generateTDDTests(e);return n.success?(this.completeWorkflow(r),this.updateWorkflowProgress(r,this.getTDDProgress(e.phase))):this.failWorkflow(r,n.error.message),await this.agentCoordinator.stop(i.value),n}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async generatePropertyTests(e){let r=v();try{this.startWorkflow(r,"property");let i=await this.spawnPropertyTestAgent(r,e);if(!i.success)return this.failWorkflow(r,i.error.message),p(i.error);this.addAgentToWorkflow(r,i.value);let n=await this.testGenerator.generatePropertyTests(e);return n.success?this.completeWorkflow(r):this.failWorkflow(r,n.error.message),await this.agentCoordinator.stop(i.value),n}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async generateTestData(e){let r=v();try{this.startWorkflow(r,"data");let i=await this.testGenerator.generateTestData(e);return i.success?this.completeWorkflow(r):this.failWorkflow(r,i.error.message),i}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async learnPatterns(e){let r=v();try{this.startWorkflow(r,"learn");let i=await this.patternMatcher.learnPatterns(e);return i.success?(this.completeWorkflow(r),this.config.publishEvents&&await this.publishPatternLearned(i.value)):this.failWorkflow(r,i.error.message),i}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async spawnTestGeneratorAgent(e,r){let i={name:`test-generator-${e.slice(0,8)}`,domain:"test-generation",type:"generator",capabilities:["test-generation",r.testType,r.framework??"vitest"],config:{workflowId:e,sourceFiles:r.sourceFiles,coverageTarget:r.coverageTarget}};return this.agentCoordinator.spawn(i)}async spawnTDDAgent(e,r){let i={name:`tdd-agent-${e.slice(0,8)}`,domain:"test-generation",type:"generator",capabilities:["tdd",r.framework,r.phase],config:{workflowId:e,feature:r.feature,behavior:r.behavior}};return this.agentCoordinator.spawn(i)}async spawnPropertyTestAgent(e,r){let i={name:`property-test-agent-${e.slice(0,8)}`,domain:"test-generation",type:"generator",capabilities:["property-testing","fast-check"],config:{workflowId:e,function:r.function,properties:r.properties}};return this.agentCoordinator.spawn(i)}async publishTestGenerated(e,r){let i={testId:e.id,testFile:e.testFile,framework:r,sourceFile:e.sourceFile,testType:e.type},n=I(Or.TestGenerated,"test-generation",i);await this.eventBus.publish(n)}async publishTestSuiteCreated(e,r){let i={suiteId:v(),testCount:e.tests.length,sourceFiles:r.sourceFiles,coverageEstimate:e.coverageEstimate},n=I(Or.TestSuiteCreated,"test-generation",i);await this.eventBus.publish(n)}async publishPatternLearned(e){let r=I(Or.PatternLearned,"test-generation",{patternCount:e.patterns.length,confidence:e.confidence,patternIds:e.patterns.map(i=>i.id)});await this.eventBus.publish(r)}async publishGenerationFailed(e,r){let i=I(Or.GenerationFailed,"test-generation",{error:e.message,context:r,timestamp:new Date().toISOString()});await this.eventBus.publish(i)}getTDDProgress(e){switch(e){case"red":return 33;case"green":return 66;case"refactor":return 100;default:return 0}}subscribeToEvents(){this.eventBus.subscribe("coverage-analysis.CoverageGapDetected",this.handleCoverageGapDetected.bind(this)),this.eventBus.subscribe("test-execution.TestRunCompleted",this.handleTestRunCompleted.bind(this)),this.subscribeToDreamEvents()}subscribeToDreamEvents(){this.eventBus.subscribe(He.DreamCycleCompleted,this.handleDreamCycleCompleted.bind(this))}async handleDreamCycleCompleted(e){let{insights:r,cycleId:i}=e.payload;if(!r||r.length===0)return;let n=r.filter(s=>{let a=s.suggestedAction?.toLowerCase().includes(this.domainName)||s.suggestedAction?.toLowerCase().includes("test")||s.suggestedAction?.toLowerCase().includes("coverage"),o=s.sourceConcepts.some(l=>l.toLowerCase().includes("test")||l.toLowerCase().includes(this.domainName)||l.toLowerCase().includes("coverage")||l.toLowerCase().includes("edge-case")),c=s.type==="optimization"||s.type==="gap_detection"||s.type==="novel_association";return a||o||c&&s.actionable});if(n.length!==0){U.info(`[${this.domainName}] Received ${n.length} relevant dream insights from cycle ${i}`);for(let s of n)s.confidenceScore>.7&&s.actionable&&await this.applyDreamInsight(s,i),this.recentDreamInsights.push({...s,receivedAt:new Date});this.recentDreamInsights.length>50&&(this.recentDreamInsights=this.recentDreamInsights.slice(-50))}}async applyDreamInsight(e,r){if(U.info(`[${this.domainName}] Applying dream insight: ${e.description.slice(0,100)}...`),this.qesona)try{let i={id:`dream-insight-${e.id}`,features:this.encodeInsightAsFeatures(e),metadata:{insightType:e.type,cycleId:r,sourceConcepts:e.sourceConcepts}},n={type:"dream-insight",value:e.suggestedAction||e.description},s=this.qesona.createPattern(i,n,{reward:e.confidenceScore,success:!0,quality:e.noveltyScore},"dream-derived",this.domainName,{insightId:e.id,cycleId:r,description:e.description,suggestedAction:e.suggestedAction});U.info(`[${this.domainName}] Created SONA pattern ${s.id} from dream insight`)}catch(i){U.error(`[${this.domainName}] Failed to store dream insight pattern`,i instanceof Error?i:void 0)}await this.memory.set(`${this.domainName}:dream-insight:${e.id}`,{insight:e,cycleId:r,appliedAt:new Date().toISOString()},{namespace:this.domainName,ttl:86400*7})}getRecentDreamInsights(e){let r=Date.now()-864e5;return this.recentDreamInsights.filter(i=>{let n=i.receivedAt.getTime()>r,s=!e||i.type===e;return n&&s})}async enhanceWithDreamInsights(e){let r=[],n=this.getRecentDreamInsights().filter(s=>(s.type==="novel_association"||s.type==="gap_detection")&&s.actionable&&s.confidenceScore>.6);for(let s of n)s.suggestedAction&&(e.sourceFiles.some(o=>s.sourceConcepts.some(c=>o.toLowerCase().includes(c.toLowerCase())))||s.suggestedAction.toLowerCase().includes(e.testType))&&r.push(s.suggestedAction);return r.slice(0,5)}encodeInsightAsFeatures(e){let r=[],i={pattern_merge:.2,novel_association:.4,optimization:.6,gap_detection:.8};for(r.push(i[e.type]||.5),r.push(e.confidenceScore),r.push(e.noveltyScore),r.push(e.actionable?1:0),r.push(Math.min(1,e.sourceConcepts.length/10));r.length<384;)r.push(0);return r.slice(0,384)}async handleCoverageGapDetected(e){let r=e.payload,i=await this.testGenerator.generateForCoverageGap(r.file,r.uncoveredLines,"jest");if(i.success&&i.value.length>0)for(let n of i.value)await this.publishTestGenerated(n,"jest")}async handleTestRunCompleted(e){}async learnFromGeneration(e){for(let r of e.patternsUsed){let i=await this.patternMatcher.getPattern(r)}}async adaptTestGenerationPatterns(e){if(!this.qesona)return[];try{let r={id:`test-gen-${Date.now()}`,features:this.encodeRequestAsFeatures(e),metadata:{testType:e.testType,framework:e.framework,sourceFileCount:e.sourceFiles.length}},i=await this.qesona.adaptPattern(r,this.config.sonaPatternType,"test-generation");return i.success&&i.pattern?(U.info(`QESONA adapted pattern with ${i.similarity.toFixed(3)} similarity in ${i.adaptationTimeMs.toFixed(2)}ms`),[i.pattern.id]):[]}catch(r){return U.error("QESONA pattern adaptation failed:",r instanceof Error?r:void 0),[]}}async storeTestGenerationPattern(e,r){if(this.qesona)try{let i={id:`test-gen-${Date.now()}`,features:this.encodeRequestAsFeatures(r),metadata:{testCount:e.tests.length,coverageEstimate:e.coverageEstimate,success:!0}},n={type:"generate-tests",value:{testType:r.testType,framework:r.framework,patternsUsed:e.patternsUsed}},s=this.qesona.createPattern(i,n,{reward:e.coverageEstimate/100,success:!0,quality:e.coverageEstimate/100},this.config.sonaPatternType,"test-generation",{testCount:e.tests.length,framework:r.framework,testType:r.testType});U.info(`Stored test generation pattern ${s.id} in QESONA`)}catch(i){U.error("Failed to store pattern in QESONA:",i instanceof Error?i:void 0)}}async findSimilarTests(e){if(!this.flashAttention)return[];let r=[];try{for(let n of e){let s=this.generateTestEmbedding(n);this.testEmbeddings.set(n.id,s)}let i=await this.loadExistingTestEmbeddings();if(i.length===0)return[];for(let n of e){let s=this.testEmbeddings.get(n.id);if(!s)continue;let o=(await this.flashAttention.computeTestSimilarity(s,i.map(c=>c.embedding),5)).filter(c=>c.similarity>.7).map(c=>({testId:i[c.index].testId,similarity:c.similarity}));o.length>0&&r.push({test:n,similarTests:o})}return r}catch(i){return U.error("Flash Attention similarity detection failed:",i instanceof Error?i:void 0),[]}}async prioritizeTestCases(e,r){if(!this.decisionTransformer)return e;try{let i={id:`prioritize-${Date.now()}`,features:[e.length/100,(r.coverageTarget||80)/100,r.testType==="unit"?.2:r.testType==="integration"?.5:.8,r.framework==="jest"?.3:r.framework==="vitest"?.4:.5],metadata:{testCount:e.length,framework:r.framework,testType:r.testType}},n=await this.decisionTransformer.predict(i);return U.info(`DecisionTransformer prediction: ${n.reasoning}`),n.confidence>.7?e.sort((s,a)=>a.assertions-s.assertions):e}catch(i){return U.error("DecisionTransformer prioritization failed:",i instanceof Error?i:void 0),e}}getQESONAStats(){return this.qesona?this.qesona.getStats():null}getFlashAttentionMetrics(){return this.flashAttention?this.flashAttention.getMetrics():null}async checkRequirementCoherence(e){return this.coherenceGate?this.coherenceGate.checkRequirementCoherence(e):{isCoherent:!0,energy:0,lane:"reflex",contradictions:[],recommendations:[],durationMs:0,usedFallback:!0}}isCoherenceGateAvailable(){return this.coherenceGate?.isAvailable()??!1}async verifyAndEnrichSpec(e){if(!this.coherenceGate||!this.config.enableCoherenceGate)return e;let r=await this.coherenceGate.validateAndEnrich(e);if(r.success)return r.value;throw r.error}async verifyTestPatternSelection(e,r){let i=V({id:v(),type:"test-pattern-selection",confidence:r,description:`Verify test pattern: ${e.name} (${e.type})`,payload:e,detectedBy:"test-generation-coordinator",severity:r>.9?"high":"medium"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(U.info(`Test pattern '${e.name}' verified by consensus`),!0):(U.warn(`Test pattern '${e.name}' NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}async verifyMockStrategy(e,r){let i=V({id:v(),type:"mock-strategy",confidence:r,description:`Verify mock strategy for ${e.target}: ${e.mockType}`,payload:e,detectedBy:"test-generation-coordinator",severity:r>.85?"high":"medium"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(U.info(`Mock strategy for '${e.target}' verified by consensus`),!0):(U.warn(`Mock strategy for '${e.target}' NOT verified`),!1)}return!0}async verifyEdgeCaseGeneration(e,r){let i=V({id:v(),type:"edge-case-generation",confidence:r,description:`Verify edge case: ${e.description}`,payload:e,detectedBy:"test-generation-coordinator",severity:"high"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(U.info(`Edge case '${e.description.slice(0,50)}...' verified by consensus`),!0):(U.warn(`Edge case NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}encodeRequestAsFeatures(e){let r=[];for(r.push(e.testType==="unit"?.2:e.testType==="integration"?.5:.8),r.push(e.framework==="jest"?.25:e.framework==="vitest"?.5:e.framework==="mocha"?.75:.9),r.push(Math.min(1,e.sourceFiles.length/50)),r.push((e.coverageTarget||80)/100);r.length<384;)r.push(0);return r.slice(0,384)}generateTestEmbedding(e){let r=[],i=this.simpleHash(e.name);for(let n=0;n<64;n++)r.push((i>>n%32&1)*2-1);for(r.push(e.type==="unit"?.2:e.type==="integration"?.5:.8),r.push(Math.min(1,e.assertions/20));r.length<384;)r.push(0);return new Float32Array(r.slice(0,384))}async loadExistingTestEmbeddings(){try{let e=await this.memory.search("test-embedding:*",1e3),r=[];for(let i of e){let n=await this.memory.get(i);n&&r.push({testId:n.testId,embedding:new Float32Array(n.embedding)})}return r}catch{return[]}}simpleHash(e){let r=0;for(let i=0;i<e.length;i++){let n=e.charCodeAt(i);r=(r<<5)-r+n,r=r|0}return Math.abs(r)}async loadWorkflowState(){let e=await this.memory.get("test-generation:coordinator:workflows");if(e)for(let r of e)r.status==="running"&&(r.status="failed",r.error="Coordinator restarted",r.completedAt=new Date),this.workflows.set(r.id,r)}async saveWorkflowState(){let e=Array.from(this.workflows.values());await this.memory.set("test-generation:coordinator:workflows",e,{namespace:"test-generation",persist:!0})}};A();var Bn=class extends j{constructor(e,r,i,n={},s){super(e,r);this.agentCoordinator=i;this.llmRouter=s;this.pluginConfig=n}agentCoordinator;llmRouter;coordinator=null;testGenerator=null;patternMatcher=null;pluginConfig;get name(){return"test-generation"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{generateTests:this.generateTests.bind(this),generateTDDTests:this.generateTDDTests.bind(this),generatePropertyTests:this.generatePropertyTests.bind(this),generateTestData:this.generateTestData.bind(this),learnPatterns:this.learnPatterns.bind(this),getCoordinator:()=>this.coordinator,getTestGenerator:()=>this.testGenerator,getPatternMatcher:()=>this.patternMatcher}}getTaskHandlers(){return new Map([["generate-tests",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.sourceFiles,i=e.testType,n=e.framework;if(!r||r.length===0)return p(new Error("Invalid generate-tests payload: missing sourceFiles"));let s={sourceFiles:r,testType:i??"unit",framework:n??"vitest",coverageTarget:e.coverageTarget,patterns:e.patterns};return this.coordinator.generateTests(s)}],["generate-tdd-tests",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.feature,i=e.behavior,n=e.framework,s=e.phase;return!r||!i?p(new Error("Invalid generate-tdd-tests payload: missing feature or behavior")):this.coordinator.generateTDDTests({feature:r,behavior:i,framework:n??"vitest",phase:s??"red"})}],["generate-property-tests",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.function,i=e.properties;return!r||!i||i.length===0?p(new Error("Invalid generate-property-tests payload: missing function or properties")):this.coordinator.generatePropertyTests({function:r,properties:i,constraints:e.constraints})}],["generate-test-data",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.schema,i=e.count;return r?this.coordinator.generateTestData({schema:r,count:i??10,locale:e.locale,preserveRelationships:e.preserveRelationships}):p(new Error("Invalid generate-test-data payload: missing schema"))}]])}async onInitialize(){this.testGenerator=ai({memory:this.memory,llmRouter:this.llmRouter},this.pluginConfig.testGenerator),this.patternMatcher=new Pt(this.memory,this.pluginConfig.patternMatcher),this.coordinator=new yi(this.eventBus,this.memory,this.agentCoordinator,this.pluginConfig.coordinator,this.llmRouter),await this.coordinator.initialize(),this.updateHealth({status:"idle",agents:{total:0,active:0,idle:0,failed:0},lastActivity:new Date,errors:[]})}async onDispose(){this.coordinator&&await this.coordinator.dispose(),this.coordinator=null,this.testGenerator=null,this.patternMatcher=null}subscribeToEvents(){this.eventBus.subscribe("coverage-analysis.CoverageGapDetected",this.handleCoverageGap.bind(this)),this.eventBus.subscribe("code-intelligence.ImpactAnalysisCompleted",this.handleImpactAnalysis.bind(this)),this.eventBus.subscribe("learning-optimization.PatternConsolidated",this.handlePatternConsolidation.bind(this))}async onEvent(e){switch(this.updateHealth({lastActivity:new Date}),e.type){case"coverage-analysis.CoverageGapDetected":await this.handleCoverageGap(e);break;case"code-intelligence.ImpactAnalysisCompleted":await this.handleImpactAnalysis(e);break;default:break}}async generateTests(e){this.ensureInitialized();try{let r=await this.coordinator.generateTests(e);return r.success?this.trackSuccessfulGeneration(r.value):this.trackFailedGeneration(r.error),r}catch(r){return this.handleError(r)}}async generateTDDTests(e){this.ensureInitialized();try{return await this.coordinator.generateTDDTests(e)}catch(r){return this.handleError(r)}}async generatePropertyTests(e){this.ensureInitialized();try{return await this.coordinator.generatePropertyTests(e)}catch(r){return this.handleError(r)}}async generateTestData(e){this.ensureInitialized();try{return await this.coordinator.generateTestData(e)}catch(r){return this.handleError(r)}}async learnPatterns(e){this.ensureInitialized();try{return await this.coordinator.learnPatterns(e)}catch(r){return this.handleError(r)}}async handleCoverageGap(e){let r=e.payload;r.riskScore>=.7&&await this.memory.set(`test-generation:pending-gaps:${r.gapId}`,r,{namespace:"test-generation",ttl:86400})}async handleImpactAnalysis(e){let r=e.payload;await this.memory.set(`test-generation:impact:${r.analysisId}`,r,{namespace:"test-generation",ttl:3600})}async handlePatternConsolidation(e){e.payload.domains.includes("test-generation")}ensureInitialized(){if(!this._initialized)throw new Error("TestGenerationPlugin is not initialized");if(!this.coordinator||!this.testGenerator||!this.patternMatcher)throw new Error("TestGenerationPlugin services are not available")}handleError(e){let r=y(e),i=this.getHealth();return this.updateHealth({errors:[...i.errors.slice(-9),r.message],status:i.errors.length>=5?"degraded":i.status}),{success:!1,error:r}}trackSuccessfulGeneration(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,total:r.agents.total+1,idle:r.agents.idle+1},lastActivity:new Date})}trackFailedGeneration(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,failed:r.agents.failed+1},errors:[...r.errors.slice(-9),e.message]})}};function Lo(u,t,e,r,i){return new Bn(u,t,e,r,i)}M();M();import{spawn as oh}from"node:child_process";import{existsSync as Cu,readFileSync as ch}from"node:fs";import{join as Su}from"node:path";var Ue={DEFAULT_TEST_TIMEOUT_MS:6e4,DEFAULT_FILE_TIMEOUT_MS:3e4,DEFAULT_VIEWPORT_WIDTH:1280,DEFAULT_VIEWPORT_HEIGHT:720,MAX_RESULTS:1e3,RESULT_RETENTION_MS:864e5,MAX_TESTS_TRACKED:1e4,MAX_EXECUTION_HISTORY:100,ANALYSIS_CACHE_TTL_MS:36e5,MAX_RETRY_HISTORY:50,MAX_ACTIONS_PER_RECORDING:1e3,MAX_RECORDING_DURATION_MS:18e5,MAX_WORKERS:32},qn={DEFAULT_STEP_TIMEOUT_MS:3e4,RETRY_DELAY_MS:1e3,DEFAULT_MAX_RETRIES:3,POLLING_INTERVAL_MS:100,ELEMENT_DETECTION_TIMEOUT_MS:1e3,POST_INTERACTION_DELAY_MS:500,DEFAULT_WAIT_MS:1e3,ACCESSIBILITY_TIMEOUT_MS:6e4,SCREENSHOT_QUALITY:80,TYPE_DEBOUNCE_MS:300},or={BASE_DELAY_MS:1e3,MAX_DELAY_MS:3e4,DEFAULT_FLAKY_RATE:.3,DEFAULT_FLAKY_PASS_RATE:.7,RETRY_PASS_RATE_VARIATION:.1,SIGKILL_GRACE_PERIOD_MS:1e3},Gn={DEFAULT_TIMEOUT_MS:6e4,QUICK_TIMEOUT_MS:1e4,MAX_CACHED_VALIDATIONS:1e3,CACHE_TTL_MS:36e5,CONTRACT_TTL_SECONDS:86400,MIGRATION_TTL_SECONDS:86400*90,MAX_RECURSION_DEPTH:10,MAX_SCHEMA_DEPTH:20,MAX_MIGRATION_STEPS:50,DEFAULT_SEARCH_LIMIT:100,HIGH_IMPACT_THRESHOLD:5,BREAKING_CHANGE_THRESHOLD:10,DEFAULT_PROVIDER_LOAD:50,HIGH_PROVIDER_LOAD_THRESHOLD:80},cT={PASSING_RATE_WARNING_THRESHOLD:95,PASSING_RATE_CRITICAL_THRESHOLD:80,MIN_COVERAGE_FOR_DEPLOY:80,PERFECT_PASSING_RATE:100,METRIC_TTL_SECONDS:86400*7,STANDARD_METRIC_TTL_SECONDS:86400,MAX_HIGH_VULN_IMPACT:.3,MEDIUM_VULN_IMPACT:.1,MAX_DUPLICATION_PERCENT:20};var lT={CHUNK_SIZE_BYTES:1024*1024,SPIKE_INTERVAL_MS:3e4,SPIKE_DURATION_MS:5e3};var uT={MAX_DURATION_MS:6e4,MAX_AGE_MS:10080*60*1e3,DAYS_IN_YEAR:365,MAX_DEPENDENCY_COUNT:10},Hn={MAX_TOKENS:2048,ERROR_TRUNCATION_LENGTH:200,OUTPUT_TRUNCATION_LENGTH:500,DETAILED_OUTPUT_TRUNCATION_LENGTH:1e3,MODEL_TIERS:{1:"claude-haiku-4-5",2:"claude-sonnet-4-6",3:"claude-sonnet-4-6",4:"claude-opus-4-7"}};A();H();se();var lh={simulateForTesting:!1,simulatedTestsPerFile:5,simulatedFailureRate:.2,simulatedSkipRate:.1,enableLLMAnalysis:!0,llmModelTier:2,llmMaxTokens:Hn.MAX_TOKENS},uh=R.create("test-execution/test-executor"),jn=class{runResults=new Map;runStats=new Map;config;memory;llmRouter;MAX_RESULTS=Ue.MAX_RESULTS;RESULT_RETENTION_MS=Ue.RESULT_RETENTION_MS;constructor(t,e={}){this.memory=t.memory,this.llmRouter=t.llmRouter,this.config={...lh,...e}}async execute(t){let e=v(),r=new Date;try{let i=this.validateRequest(t);if(i.success===!1)return p(i.error);let n=await this.runTests(t),s=new Date,a=s.getTime()-r.getTime(),o={runId:e,status:n.failed>0?"failed":"passed",total:n.total,passed:n.passed,failed:n.failed,skipped:n.skipped,duration:a,failedTests:n.failedTests,coverage:n.coverage,fileCoverages:n.fileCoverages};this.runResults.set(e,o),await this.storeResults(e,o);let c={runId:e,startTime:r,endTime:s,duration:a,testsPerSecond:n.total/(a/1e3),workers:1,memoryUsage:process.memoryUsage?.().heapUsed??0};return this.runStats.set(e,c),f(o)}catch(i){return p(y(i))}}async executeParallel(t){let e=v(),r=new Date;try{let i=this.validateParallelRequest(t);if(i.success===!1)return p(i.error);let{workers:n,sharding:s="file",isolation:a="process"}=t,o=this.shardTests(t.testFiles,n,s),c=await Promise.all(o.map((b,w)=>this.executeWorker(b,w,a,t))),l=this.aggregateResults(c),d=new Date,m=d.getTime()-r.getTime(),h={runId:e,status:l.failed>0?"failed":"passed",total:l.total,passed:l.passed,failed:l.failed,skipped:l.skipped,duration:m,failedTests:l.failedTests,coverage:l.coverage,fileCoverages:l.fileCoverages};this.runResults.set(e,h),await this.storeResults(e,h);let g={runId:e,startTime:r,endTime:d,duration:m,testsPerSecond:l.total/(m/1e3),workers:n,memoryUsage:process.memoryUsage?.().heapUsed??0};return this.runStats.set(e,g),f(h)}catch(i){return p(y(i))}}async getResults(t){let e=this.runResults.get(t);if(e)return f(e);try{let r=await this.memory.get(`test-run:${t}`);if(r)return this.runResults.set(t,r),f(r)}catch{}return p(new Error(`Test run not found: ${t}`))}async getStats(t){let e=this.runStats.get(t);if(e)return f(e);try{let r=await this.memory.get(`test-stats:${t}`);if(r)return this.runStats.set(t,r),f(r)}catch{}return p(new Error(`Test stats not found: ${t}`))}cleanupOldResults(){let t=Date.now(),e=0;for(let[r,i]of this.runResults){let n=i.duration?t-i.duration:t;t-n>this.RESULT_RETENTION_MS&&(this.runResults.delete(r),this.runStats.delete(r),e++)}if(this.runResults.size>this.MAX_RESULTS){let r=this.runResults.size-this.MAX_RESULTS,i=Array.from(this.runResults.entries());for(let n=0;n<r&&n<i.length;n++)this.runResults.delete(i[n][0]),this.runStats.delete(i[n][0]),e++}return e}destroy(){this.runResults.clear(),this.runStats.clear()}isLLMAnalysisAvailable(){return this.config.enableLLMAnalysis&&this.llmRouter!==void 0}getModelForTier(t){let e={1:"claude-haiku-4-5",2:"claude-sonnet-4-6",3:"claude-sonnet-4-6",4:"claude-opus-4-7"};return e[t]||e[2]}async analyzeFailuresWithLLM(t){if(!this.isLLMAnalysisAvailable()||t.length===0)return null;try{let e=t.slice(0,5).map(i=>`- ${i.testName}: ${i.error?.substring(0,200)||"Unknown error"}`).join(`
|
|
2276
2276
|
`);return(await this.llmRouter.chat({model:this.getModelForTier(this.config.llmModelTier),messages:[{role:"user",content:`Analyze these test failures and provide insights:
|
|
2277
2277
|
${e}
|
|
2278
2278
|
|
|
@@ -2301,11 +2301,11 @@ expect(result).toBeDefined();`,effort:"medium"}),e.push({action:"Add error bound
|
|
|
2301
2301
|
}`,effort:"medium"});break;case"resource":e.push({action:"Mock external dependencies",description:"Use mocks for external services in unit tests",codeSnippet:"jest.mock('./externalService');",effort:"medium"}),e.push({action:"Implement retry logic",description:"Add retries for transient failures",codeSnippet:"const result = await retry(() => fetchData(), { retries: 3 });",effort:"low"});break;case"ordering":e.push({action:"Isolate test state",description:"Reset shared state in beforeEach/afterEach",codeSnippet:`beforeEach(() => {
|
|
2302
2302
|
resetDatabase();
|
|
2303
2303
|
clearCache();
|
|
2304
|
-
});`,effort:"medium"}),e.push({action:"Remove inter-test dependencies",description:"Each test should set up its own required state",effort:"high"});break;case"unknown":e.push({action:"Add detailed logging",description:"Log test state at key points to identify patterns",effort:"low"}),e.push({action:"Run in isolation",description:"Execute test alone to determine if it is a test interaction issue",effort:"low"});break}return e}determinePriority(t){return t.confidence>.8&&t.pattern!=="unknown"?"high":t.confidence>.5?"medium":"low"}hasDurationSpikes(t){let e=t.map(n=>n.duration),r=this.average(e),i=this.standardDeviation(e);return e.some(n=>n>r+2*i)}average(t){return t.length===0?0:t.reduce((e,r)=>e+r,0)/t.length}standardDeviation(t){let e=this.average(t),r=t.map(i=>(i-e)**2);return Math.sqrt(this.average(r))}async storeReport(t){let e=v();await this.memory.set(`flaky-report:${e}`,t,{namespace:"test-execution",persist:!0})}};M();import{spawn as ph}from"node:child_process";import{existsSync as Un,readFileSync as hh}from"node:fs";A();H();se();var gh={simulateForTesting:!1,simulatedRetrySuccessRate:or.DEFAULT_FLAKY_PASS_RATE,enableJitter:!1,maxJitterPercent:or.RETRY_PASS_RATE_VARIATION,testRunner:"auto",testTimeout:Ue.DEFAULT_TEST_TIMEOUT_MS,npxPath:"npx"},fh=R.create("test-execution/retry-handler"),Qn=class{constructor(t,e={}){this.memory=t;this.config={...gh,...e}}memory;retryHistory=new Map;retryPolicies=new Map;runStats=new Map;config;defaultPolicy={maxRetries:3,backoff:"exponential",baseDelay:1e3,maxDelay:3e4,retryOn:[],noRetryOn:[{type:"error_pattern",pattern:"SyntaxError"},{type:"error_pattern",pattern:"TypeError"}]};async shouldRetry(t,e,r){let i=await this.getRetryPolicy(t);if(e>=i.maxRetries)return!1;for(let n of i.noRetryOn)if(this.matchesCondition(n,r))return!1;return i.retryOn.length>0?i.retryOn.some(s=>this.matchesCondition(s,r)):!0}async executeWithRetry(t){let{runId:e,failedTests:r,maxRetries:i,backoff:n,baseDelay:s=1e3,maxDelay:a=3e4,onRetry:o}=t;try{let c={runId:e,totalRetries:0,successful:0,failed:0,flakyDetected:[],startTime:Date.now()},l=[],d=[],m=[];for(let g of r){let b=await this.retryTest(g,i,n,s,a,o);c.totalRetries+=b.attempts,b.passed?(l.push(g.testId),c.successful++,b.attempts>0&&m.push(g.testId)):(d.push(g.testId),c.failed++),await this.recordRetry(g.testId,b)}c.flakyDetected=m,c.endTime=Date.now(),this.runStats.set(e,c),await this.memory.set(`retry-stats:${e}`,c,{namespace:"test-execution",persist:!0});let h={originalFailed:r.length,retried:c.totalRetries,nowPassing:l.length,stillFailing:d.length,flakyDetected:m};return f(h)}catch(c){return p(y(c))}}async getRetryStats(t){try{if(t){let r=this.runStats.get(t);if(!r){let i=await this.memory.get(`retry-stats:${t}`);return i?f(this.convertToRetryStatistics([i])):p(new Error(`No retry stats found for run: ${t}`))}return f(this.convertToRetryStatistics([r]))}let e=Array.from(this.runStats.values());return f(this.convertToRetryStatistics(e))}catch(e){return p(y(e))}}async setRetryPolicy(t,e){this.retryPolicies.set(t,e),await this.memory.set(`retry-policy:${t}`,e,{namespace:"test-execution",persist:!0})}async getRetryPolicy(t){let e=this.retryPolicies.get(t);if(e)return e;let r=await this.memory.get(`retry-policy:${t}`);return r?(this.retryPolicies.set(t,r),r):this.defaultPolicy}matchesCondition(t,e){switch(t.type){case"error_pattern":return e.includes(t.pattern)||new RegExp(t.pattern,"i").test(e);case"exit_code":return e.includes(`exit code ${t.code}`);case"flakiness_score":return!1;case"custom":return!1;default:return!1}}async retryTest(t,e,r,i,n,s){let a=0,o=t.error;for(;a<e&&await this.shouldRetry(t.testId,a,o);){let l=this.calculateDelay(a,r,i,n);await this.sleep(l),s&&s(t.testId,a+1),a++;let d=await this.executeTest(t);if(d.passed)return{testId:t.testId,passed:!0,attempts:a,finalError:void 0};o=d.error??o}return{testId:t.testId,passed:!1,attempts:a,finalError:o}}async executeTest(t){if(this.config.simulateForTesting){let e=L()<this.config.simulatedRetrySuccessRate;return{passed:e,error:e?void 0:t.error}}return this.executeRealTest(t)}async executeRealTest(t){let e=t.file,r=t.testName,i=this.config.cwd??process.cwd();if(!Un(e))throw new Error(`Test file not found: ${e}. Cannot retry non-existent test file.`);let n=await this.detectTestRunner(i);if(!n)throw new Error(`No test runner detected or configured. Install vitest, jest, or mocha, or configure testRunner in RetryHandlerConfig. Cannot execute retry for: ${e}`);let{command:s,args:a}=this.buildTestCommand(n,e,r);return this.spawnTestProcess(s,a,i)}async detectTestRunner(t){if(this.config.testRunner!=="auto")return this.config.testRunner;let e=["vitest.config.ts","vitest.config.js","vitest.config.mts","vitest.config.mjs","vite.config.ts","vite.config.js"];for(let i of e)if(Un(`${t}/${i}`))return"vitest";let r=["jest.config.ts","jest.config.js","jest.config.json","jest.config.mjs"];for(let i of r)if(Un(`${t}/${i}`))return"jest";try{let i=`${t}/package.json`;if(Un(i)){let n=hh(i,"utf-8"),s=E(n),a=s?.scripts?.test??"";if(a.includes("vitest"))return"vitest";if(a.includes("jest"))return"jest";if(a.includes("mocha"))return"mocha";let o=s?.devDependencies??{};if("vitest"in o)return"vitest";if("jest"in o)return"jest";if("mocha"in o)return"mocha"}}catch{fh.debug("package.json read failed:")}return null}buildTestCommand(t,e,r){let i=this.config.npxPath;switch(t){case"vitest":let n=["vitest","run","--reporter=json",e];return r&&n.push("-t",r),{command:i,args:n}
|
|
2304
|
+
});`,effort:"medium"}),e.push({action:"Remove inter-test dependencies",description:"Each test should set up its own required state",effort:"high"});break;case"unknown":e.push({action:"Add detailed logging",description:"Log test state at key points to identify patterns",effort:"low"}),e.push({action:"Run in isolation",description:"Execute test alone to determine if it is a test interaction issue",effort:"low"});break}return e}determinePriority(t){return t.confidence>.8&&t.pattern!=="unknown"?"high":t.confidence>.5?"medium":"low"}hasDurationSpikes(t){let e=t.map(n=>n.duration),r=this.average(e),i=this.standardDeviation(e);return e.some(n=>n>r+2*i)}average(t){return t.length===0?0:t.reduce((e,r)=>e+r,0)/t.length}standardDeviation(t){let e=this.average(t),r=t.map(i=>(i-e)**2);return Math.sqrt(this.average(r))}async storeReport(t){let e=v();await this.memory.set(`flaky-report:${e}`,t,{namespace:"test-execution",persist:!0})}};M();import{spawn as ph}from"node:child_process";import{existsSync as Un,readFileSync as hh}from"node:fs";A();H();se();var gh={simulateForTesting:!1,simulatedRetrySuccessRate:or.DEFAULT_FLAKY_PASS_RATE,enableJitter:!1,maxJitterPercent:or.RETRY_PASS_RATE_VARIATION,testRunner:"auto",testTimeout:Ue.DEFAULT_TEST_TIMEOUT_MS,npxPath:"npx"},fh=R.create("test-execution/retry-handler"),Qn=class{constructor(t,e={}){this.memory=t;this.config={...gh,...e}}memory;retryHistory=new Map;retryPolicies=new Map;runStats=new Map;config;defaultPolicy={maxRetries:3,backoff:"exponential",baseDelay:1e3,maxDelay:3e4,retryOn:[],noRetryOn:[{type:"error_pattern",pattern:"SyntaxError"},{type:"error_pattern",pattern:"TypeError"}]};async shouldRetry(t,e,r){let i=await this.getRetryPolicy(t);if(e>=i.maxRetries)return!1;for(let n of i.noRetryOn)if(this.matchesCondition(n,r))return!1;return i.retryOn.length>0?i.retryOn.some(s=>this.matchesCondition(s,r)):!0}async executeWithRetry(t){let{runId:e,failedTests:r,maxRetries:i,backoff:n,baseDelay:s=1e3,maxDelay:a=3e4,onRetry:o}=t;try{let c={runId:e,totalRetries:0,successful:0,failed:0,flakyDetected:[],startTime:Date.now()},l=[],d=[],m=[];for(let g of r){let b=await this.retryTest(g,i,n,s,a,o);c.totalRetries+=b.attempts,b.passed?(l.push(g.testId),c.successful++,b.attempts>0&&m.push(g.testId)):(d.push(g.testId),c.failed++),await this.recordRetry(g.testId,b)}c.flakyDetected=m,c.endTime=Date.now(),this.runStats.set(e,c),await this.memory.set(`retry-stats:${e}`,c,{namespace:"test-execution",persist:!0});let h={originalFailed:r.length,retried:c.totalRetries,nowPassing:l.length,stillFailing:d.length,flakyDetected:m};return f(h)}catch(c){return p(y(c))}}async getRetryStats(t){try{if(t){let r=this.runStats.get(t);if(!r){let i=await this.memory.get(`retry-stats:${t}`);return i?f(this.convertToRetryStatistics([i])):p(new Error(`No retry stats found for run: ${t}`))}return f(this.convertToRetryStatistics([r]))}let e=Array.from(this.runStats.values());return f(this.convertToRetryStatistics(e))}catch(e){return p(y(e))}}async setRetryPolicy(t,e){this.retryPolicies.set(t,e),await this.memory.set(`retry-policy:${t}`,e,{namespace:"test-execution",persist:!0})}async getRetryPolicy(t){let e=this.retryPolicies.get(t);if(e)return e;let r=await this.memory.get(`retry-policy:${t}`);return r?(this.retryPolicies.set(t,r),r):this.defaultPolicy}matchesCondition(t,e){switch(t.type){case"error_pattern":return e.includes(t.pattern)||new RegExp(t.pattern,"i").test(e);case"exit_code":return e.includes(`exit code ${t.code}`);case"flakiness_score":return!1;case"custom":return!1;default:return!1}}async retryTest(t,e,r,i,n,s){let a=0,o=t.error;for(;a<e&&await this.shouldRetry(t.testId,a,o);){let l=this.calculateDelay(a,r,i,n);await this.sleep(l),s&&s(t.testId,a+1),a++;let d=await this.executeTest(t);if(d.passed)return{testId:t.testId,passed:!0,attempts:a,finalError:void 0};o=d.error??o}return{testId:t.testId,passed:!1,attempts:a,finalError:o}}async executeTest(t){if(this.config.simulateForTesting){let e=L()<this.config.simulatedRetrySuccessRate;return{passed:e,error:e?void 0:t.error}}return this.executeRealTest(t)}async executeRealTest(t){let e=t.file,r=t.testName,i=this.config.cwd??process.cwd();if(!Un(e))throw new Error(`Test file not found: ${e}. Cannot retry non-existent test file.`);let n=await this.detectTestRunner(i);if(!n)throw new Error(`No test runner detected or configured. Install vitest, jest, or mocha, or configure testRunner in RetryHandlerConfig. Cannot execute retry for: ${e}`);let{command:s,args:a}=this.buildTestCommand(n,e,r);return this.spawnTestProcess(s,a,i)}async detectTestRunner(t){if(this.config.testRunner!=="auto")return this.config.testRunner;let e=["vitest.config.ts","vitest.config.js","vitest.config.mts","vitest.config.mjs","vite.config.ts","vite.config.js"];for(let i of e)if(Un(`${t}/${i}`))return"vitest";let r=["jest.config.ts","jest.config.js","jest.config.json","jest.config.mjs"];for(let i of r)if(Un(`${t}/${i}`))return"jest";try{let i=`${t}/package.json`;if(Un(i)){let n=hh(i,"utf-8"),s=E(n),a=s?.scripts?.test??"";if(a.includes("vitest"))return"vitest";if(a.includes("jest"))return"jest";if(a.includes("mocha"))return"mocha";let o=s?.devDependencies??{};if("vitest"in o)return"vitest";if("jest"in o)return"jest";if("mocha"in o)return"mocha"}}catch{fh.debug("package.json read failed:")}return null}buildTestCommand(t,e,r){let i=this.config.npxPath;switch(t){case"vitest":{let n=["vitest","run","--reporter=json",e];return r&&n.push("-t",r),{command:i,args:n}}case"jest":{let n=["jest","--json","--testPathPattern",e];return r&&n.push("-t",r),{command:i,args:n}}case"mocha":{let n=["mocha","--reporter","json",e];return r&&n.push("--grep",r),{command:i,args:n}}default:throw new Error(`Unsupported test runner: ${t}`)}}spawnTestProcess(t,e,r){return new Promise((i,n)=>{let s=this.config.testTimeout,a="",o="",c=!1,l=ph(t,e,{cwd:r,env:{...process.env,FORCE_COLOR:"0",CI:"true"}}),d=setTimeout(()=>{c=!0,l.kill("SIGTERM"),setTimeout(()=>l.kill("SIGKILL"),1e3)},s);l.stdout?.on("data",m=>{a+=m.toString()}),l.stderr?.on("data",m=>{o+=m.toString()}),l.on("close",m=>{if(clearTimeout(d),c){n(new Error(`Test execution timed out after ${s}ms for command: ${t} ${e.join(" ")}`));return}let h=this.parseTestResult(m,a,o);i(h)}),l.on("error",m=>{clearTimeout(d),n(new Error(`Failed to spawn test process: ${m.message}. Command: ${t} ${e.join(" ")}. Ensure the test runner is installed and accessible.`))})})}parseTestResult(t,e,r){if(t===0)return{passed:!0};try{let n=e.match(/\{[\s\S]*"testResults"[\s\S]*\}/);if(n){let o=E(n[0]);return o.success===!0||o.numFailedTests===0?{passed:!0}:{passed:!1,error:o.testResults?.[0]?.assertionResults?.find(l=>l.status==="failed")?.failureMessages?.join(`
|
|
2305
2305
|
`)??`Test failed with exit code ${t}`}}let s=e.match(/\{[\s\S]*"numFailedTests"[\s\S]*\}/);if(s){let o=E(s[0]);return o.success===!0||o.numFailedTests===0?{passed:!0}:{passed:!1,error:o.testResults?.[0]?.assertionResults?.find(l=>l.status==="failed")?.failureMessages?.join(`
|
|
2306
2306
|
`)??`Test failed with exit code ${t}`}}let a=e.match(/\{[\s\S]*"stats"[\s\S]*"failures"[\s\S]*\}/);if(a){let o=E(a[0]);return o.stats?.failures===0?{passed:!0}:{passed:!1,error:o.failures?.[0]?.err?.message??`Test failed with exit code ${t}`}}}catch{}return{passed:!1,error:(r||e||`Test failed with exit code ${t}`).substring(0,1e3)}}calculateDelay(t,e,r,i){let n;switch(e){case"constant":n=r;break;case"linear":n=r*(t+1);break;case"exponential":n=r*Math.pow(2,t);break;default:n=r}if(this.config.enableJitter){let s=n*this.config.maxJitterPercent*L();n+=s}return Math.min(n,i)}sleep(t){return new Promise(e=>setTimeout(e,t))}async recordRetry(t,e){let r=this.retryHistory.get(t)??[];r.push({testId:e.testId,attempts:e.attempts,passed:e.passed,error:e.finalError,timestamp:new Date}),r.length>50&&r.shift(),this.retryHistory.set(t,r),await this.memory.set(`retry-history:${t}`,r,{namespace:"test-execution",persist:!0})}convertToRetryStatistics(t){let e=new Map,r=0,i=0,n=0,s=0,a=0;for(let d of t)r+=d.totalRetries,i+=d.successful,n+=d.failed,s+=d.totalRetries,d.successful>0&&(a+=d.successful);let o=i+n,c=o>0?r/o:0,l=a>0?s/a:0;return{totalRetries:r,successfulRetries:i,failedRetries:n,averageAttemptsToPass:l,retryRate:c,testStats:e}}};A();var Ft={NAVIGATE:"navigate",CLICK:"click",TYPE:"type",WAIT:"wait",ASSERT:"assert",SCREENSHOT:"screenshot",A11Y_CHECK:"a11y-check"};function Kn(u){return u.type===Ft.NAVIGATE}function Jn(u){return u.type===Ft.CLICK}function Yn(u){return u.type===Ft.TYPE}function Xn(u){return u.type===Ft.WAIT}function Zn(u){return u.type===Ft.ASSERT}function es(u){return u.type===Ft.SCREENSHOT}function ts(u){return u.type===Ft.A11Y_CHECK}function rs(u){let t=Math.min(1,u.failureRate??0),e=Math.min(1,u.flakinessScore??0),r=u.complexity??.5,i=1-(u.coverage??0)/100,n=u.businessCriticality??.5,a=Math.max(0,1-(u.estimatedDuration??0)/6e4),o=10080*60*1e3,c=Math.max(0,1-(u.timeSinceModification??0)/o),l=Math.min(1,(u.dependencyCount??0)/10);return{failureProbability:t,flakiness:e,complexity:r,coverageGap:i,criticality:n,speed:a,age:c,dependencyComplexity:l}}function Au(u){return[u.failureProbability,u.flakiness,u.complexity,u.coverageGap,u.criticality,u.speed,u.age,u.dependencyComplexity]}function Oo(u){return{critical:100,high:75,standard:50,low:25,defer:0}[u]}function No(u){return{critical:"p0",high:"p1",standard:"p2",low:"p3",defer:"p3"}[u]}function Vo(u,t){let e=t.failedEarly?.5:0,r=u.availableTime>0?Math.max(0,1-t.executionTime/u.availableTime)*.3:0,i=t.coverageImproved?.2:0,n=t.flakyDetected?.1:0,s=e+r+i+n;return{earlyDetection:e,timeEfficiency:r,coverageGain:i,flakinessReduction:n,total:s}}function is(u,t){let e=rs(t);return{id:u,features:Au(e),testId:u,testType:t.testType??"unit",priority:t.priority??t.assignedPriority??"p2",complexity:t.complexity??.5,domain:t.domain??"test-execution",dependencies:t.dependencies??[],estimatedDuration:t.estimatedDuration??5e3,coverage:t.coverage??0,failureHistory:t.failureHistory??[],filePath:t.filePath,testName:t.testName,failureRate:t.failureRate??0,flakinessScore:t.flakinessScore??0,executionCount:t.executionCount??0,timeSinceModification:t.timeSinceModification??0,businessCriticality:t.businessCriticality??.5,dependencyCount:t.dependencyCount??0,assignedPriority:t.assignedPriority??t.priority??"p2",timestamp:new Date,metadata:{...t,features:e}}}var Oh={enableDT:!0,minTrajectoriesForDT:5,enableHeuristicFallback:!0,minConfidence:.4,enableAutoTraining:!0,trainingInterval:10,contextLength:10,embeddingDim:384},ns=class{constructor(t,e={}){this.memory=t;this.config={...Oh,...e},this.decisionTransformer=new ar({contextLength:this.config.contextLength,embeddingDim:this.config.embeddingDim})}memory;decisionTransformer;config;executionHistory=new Map;executionsSinceLastTraining=0;async initialize(){await this.loadHistory(),await this.loadModel()}async prioritize(t,e){try{let r=t.map(d=>is(d.testId,d)),i=await Promise.all(r.map(d=>this.getPrediction(d))),n=t.map((d,m)=>{let h=i[m],g=h.action.value??"standard";return{testId:d.testId,filePath:d.filePath,testName:d.testName,priority:g,score:Oo(g),confidence:h.confidence,reasoning:h.reasoning??"No reasoning provided"}});n.sort((d,m)=>m.score-d.score);let s=this.decisionTransformer.getInfo(),a={trained:s.stats.episode>0,trajectoryCount:this.countTrajectories(),averageReturn:s.stats.averageReward},o=a.trained&&a.trajectoryCount>=this.config.minTrajectoriesForDT?"dt-prediction":this.config.enableHeuristicFallback?"heuristic":"dt-prediction",c=n.reduce((d,m)=>d+m.score,0),l=n.reduce((d,m)=>d+m.confidence,0)/n.length;return f({tests:n,totalScore:c,averageConfidence:l,method:o,learningStatus:a})}catch(r){return p(y(r))}}async recordExecution(t,e,r){let i={testId:t,timestamp:new Date,passed:e.passed,duration:e.duration,priority:No(e.priority),failureReason:e.passed?void 0:"Test failed"},n=this.executionHistory.get(t)??[];n.push(i),n.length>100&&n.shift(),this.executionHistory.set(t,n),await this.persistHistory();let s=this.createExperience(t,e,r);await this.decisionTransformer.train(s),this.executionsSinceLastTraining++,this.config.enableAutoTraining&&this.executionsSinceLastTraining>=this.config.trainingInterval&&(await this.trainBatch(),this.executionsSinceLastTraining=0)}getStats(){let t=this.executionHistory.size,e=Array.from(this.executionHistory.values()).reduce((r,i)=>r+i.length,0);return{totalTests:t,totalExecutions:e,trajectoryCount:this.countTrajectories(),dtStats:this.decisionTransformer.getStats()}}async exportModel(){return this.decisionTransformer.exportModel()}async importModel(t){await this.decisionTransformer.importModel(t)}async getPrediction(t){try{let e=await this.decisionTransformer.predict(t);return this.config.enableHeuristicFallback&&e.confidence<this.config.minConfidence?this.getHeuristicPrediction(t):{action:e.action,confidence:e.confidence,reasoning:e.reasoning}}catch{return this.getHeuristicPrediction(t)}}getHeuristicPrediction(t){let e=rs(t),r=0;r+=e.failureProbability*30,r+=e.flakiness*15,r+=e.complexity*10,r+=e.coverageGap*20,r+=e.criticality*15,r+=e.speed*5,r+=e.age*5;let i;return r>60?i="critical":r>45?i="high":r>30?i="standard":r>15?i="low":i="defer",{action:{type:"prioritize",value:i},confidence:.6,reasoning:`Heuristic: score ${r.toFixed(1)} (failure: ${e.failureProbability.toFixed(2)}, flaky: ${e.flakiness.toFixed(2)}, coverage gap: ${e.coverageGap.toFixed(2)})`}}createExperience(t,e,r){let i=this.executionHistory.get(t)??[],n=i[i.length-1],s=is(t,{filePath:"",testName:t,failureHistory:i.map(l=>l.passed?1:0),executionCount:i.length,flakinessScore:this.calculateFlakinessScore(i),estimatedDuration:e.duration}),a={type:"prioritize",value:e.priority},o=Vo(r,{failedEarly:e.failedEarly??!e.passed,executionTime:e.duration,coverageImproved:e.coverageImproved??!1,flakyDetected:e.flakyDetected??!1}),c={...s};return{state:s,action:a,reward:o.total,nextState:c,done:!0,timestamp:new Date}}calculateFlakinessScore(t){if(t.length<3)return 0;let e=t.slice(-10),r=e.filter(a=>!a.passed).length,i=0;for(let a=1;a<e.length;a++)e[a].passed!==e[a-1].passed&&i++;let n=r/e.length,s=i/Math.max(1,e.length-1);return n*.5+s*.5}async trainBatch(){let t=[];for(let[e,r]of this.executionHistory.entries())for(let i of r){let n={runId:`historical-${e}-${i.timestamp.getTime()}`,totalTests:1,availableTime:6e4,workers:1,mode:"sequential",phase:"regression"},s=this.createExperience(e,{passed:i.passed,duration:i.duration,priority:this.priorityFromEnum(i.priority),failedEarly:!i.passed},n);t.push(s)}t.length>0&&(await this.decisionTransformer.trainBatch(t),await this.saveModel())}priorityFromEnum(t){return{p0:"critical",p1:"high",p2:"standard",p3:"low",p4:"defer"}[t]??"standard"}countTrajectories(){return this.decisionTransformer.getStats().episode}async loadHistory(){try{let t=await this.memory.get("test-prioritizer:history");t&&(this.executionHistory=new Map(Object.entries(t)))}catch{}}async persistHistory(){let t=Object.fromEntries(this.executionHistory);await this.memory.set("test-prioritizer:history",t,{namespace:"test-execution",persist:!0})}async loadModel(){try{let t=await this.memory.get("test-prioritizer:model");t&&await this.decisionTransformer.importModel(t)}catch{}}async saveModel(){let t=await this.decisionTransformer.exportModel();await this.memory.set("test-prioritizer:model",t,{namespace:"test-execution",persist:!0})}};var _o={defaultStepTimeout:qn.DEFAULT_STEP_TIMEOUT_MS,defaultRetries:2,retryDelay:qn.RETRY_DELAY_MS,screenshotOnFailure:!0,stopOnFirstFailure:!1,pollingInterval:qn.POLLING_INTERVAL_MS,maxParallelWorkers:4,verbose:!1,preferAgentBrowser:!0,browserClientType:"auto"},ke=class extends Error{constructor(e,r,i,n){super(e);this.code=r;this.stepId=i;this.cause=n;this.name="E2ERunnerError"}code;stepId;cause},Lt=class extends ke{constructor(t,e,r){super(`Step "${t}" timed out after ${e}ms`,"STEP_TIMEOUT",t,r),this.name="StepTimeoutError"}},Qe=class extends ke{constructor(e,r,i,n,s){super(e,"ASSERTION_FAILED",r,s);this.expected=i;this.actual=n;this.name="AssertionError"}expected;actual};M();var F=class u extends Error{constructor(e,r,i,n){super(e);this.code=r;this.tool=i;this.cause=n;this.name="BrowserError",Object.setPrototypeOf(this,u.prototype)}code;tool;cause},te=class u extends F{constructor(t,e,r){super(e||"Browser tool is unavailable","BROWSER_UNAVAILABLE",t,r),this.name="BrowserUnavailableError",Object.setPrototypeOf(this,u.prototype)}},ut=class u extends F{constructor(t,e,r){super(`${e} timed out`,"BROWSER_TIMEOUT",t,r),this.name="BrowserTimeoutError",Object.setPrototypeOf(this,u.prototype)}},$t=class u extends F{constructor(t,e,r){let i=typeof e=="string"?e:JSON.stringify(e);super(`Element not found: ${i}`,"ELEMENT_NOT_FOUND",t,r),this.name="BrowserElementNotFoundError",Object.setPrototypeOf(this,u.prototype)}};H();A();import{spawnSync as zo,spawn as Nh}from"child_process";var dt=class{config;browserLaunched=!1;constructor(t={}){let e=t.sessionName??"default";if(!/^[a-zA-Z0-9_-]+$/.test(e))throw new Error(`Invalid sessionName "${e}": must match /^[a-zA-Z0-9_-]+$/`);this.config={sessionName:e,timeout:t.timeout??3e4,headed:t.headed??!1,debug:t.debug??!1}}execute(t,e=[]){let i=["agent-browser",...this.buildArgs(t,e)];this.config.debug&&console.log(`[agent-browser] Executing: npx ${i.join(" ")}`);try{let n=zo("npx",i,{encoding:"utf-8",timeout:this.config.timeout,maxBuffer:10485760,shell:!1});if(n.error)return{success:!1,error:n.error.message};if(n.status!==0)return{success:!1,error:n.stderr?.trim()||`Exit code: ${n.status}`};let s=n.stdout?.trim()??"";try{return{success:!0,data:E(s)}}catch{return{success:!0,data:s}}}catch(n){return{success:!1,error:T(n)}}}async executeAsync(t,e=[]){return new Promise(r=>{let i=this.buildArgs(t,e);this.config.debug&&console.log(`[agent-browser] Executing async: npx agent-browser ${i.join(" ")}`);let n=Nh("npx",["agent-browser",...i],{timeout:this.config.timeout}),s="",a="";n.stdout?.on("data",o=>{s+=o.toString()}),n.stderr?.on("data",o=>{a+=o.toString()}),n.on("close",o=>{if(o===0)try{let c=E(s.trim());r({success:!0,data:c})}catch{r({success:!0,data:s.trim()})}else r({success:!1,error:a||`Exit code: ${o}`})}),n.on("error",o=>{r({success:!1,error:o.message})})})}open(t){let e=[t];this.config.headed&&e.push("--headed");let r=this.execute("open",e);return r.success&&(this.browserLaunched=!0),r}close(){let t=this.execute("close");return t.success&&(this.browserLaunched=!1),t}terminateDaemon(){try{this.close();let t=this.config.sessionName;try{zo("pkill",["-f",`agent-browser.*--session[= ]${t}`],{timeout:5e3,stdio:"ignore",shell:!1})}catch(e){console.debug("[CommandExecutor] pkill error:",e instanceof Error?e.message:e)}return this.browserLaunched=!1,{success:!0}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Failed to terminate daemon"}}}snapshot(t){let e=["--json"];return t?.interactive&&e.push("-i"),t?.compact&&e.push("-c"),t?.depth&&e.push("-d",String(t.depth)),this.execute("snapshot",e)}click(t){return this.execute("click",[t])}fill(t,e){return this.execute("fill",[t,e])}type(t,e){return this.execute("type",[t,e])}getText(t){return this.execute("get",["text",t,"--json"])}isVisible(t){let e=this.execute("is",["visible",t,"--json"]);return e.success&&e.data?{success:!0,data:e.data.success}:{success:!1,error:e.error}}screenshot(t,e){let r=[];return t&&r.push(t),e&&r.push("--full"),t||r.push("--json"),this.execute("screenshot",r)}waitForElement(t,e){let r=[t];return e?this.execute("wait",r):this.execute("wait",r)}waitForText(t){return this.execute("wait",["--text",t])}waitForUrl(t){let e=t.includes("*")?t:`**${t}**`;return this.execute("wait",["--url",e])}waitForNetworkIdle(){return this.execute("wait",["--load","networkidle"])}setDevice(t){return this.execute("set",["device",t])}setViewport(t,e){return this.execute("set",["viewport",String(t),String(e)])}mockRoute(t,e){let r=JSON.stringify(e);return this.execute("network",["route",t,"--body",r])}abortRoute(t){return this.execute("network",["route",t,"--abort"])}clearRoutes(){return this.execute("network",["unroute"])}saveState(t){return this.execute("state",["save",t])}loadState(t){return this.execute("state",["load",t])}startTrace(){return this.execute("trace",["start"])}stopTrace(t){let e=this.execute("trace",["stop",t]);return e.success?{success:!0,data:t}:{success:!1,error:e.error}}eval(t){return this.execute("eval",[t,"--json"])}getSessionName(){return this.config.sessionName}isBrowserLaunched(){return this.browserLaunched}buildArgs(t,e){let r=[];return this.config.sessionName!=="default"&&r.push("--session",this.config.sessionName),r.push(t,...e),r}};function Eu(){try{let u=zo("npx",["agent-browser"],{encoding:"utf-8",timeout:1e4,shell:!1}),t=(u.stdout??"")+(u.stderr??"");return t.includes("agent-browser")&&t.includes("Usage:")}catch{return!1}}H();var xu=new Set(["button","link","textbox","checkbox","radio","combobox","listbox","menuitem","menuitemcheckbox","menuitemradio","option","searchbox","slider","spinbutton","switch","tab","treeitem"]);var qo=class{parse(t){let e=t.split(`
|
|
2307
2307
|
`),r=[],i=new Map,n=0;for(let a of e){let o=this.parseLine(a);o&&(r.push(o),i.set(o.ref,o),o.depth>n&&(n=o.depth))}this.buildRelationships(r);let s=r.filter(a=>xu.has(a.role.toLowerCase()));return{rawTree:t,elements:r,interactiveElements:s,refMap:i,stats:{totalElements:r.length,interactiveCount:s.length,maxDepth:n},parsedAt:new Date}}parseJson(t){let e=typeof t=="string"?E(t):t;if(e.success&&e.data){let r=e.data.snapshot||e.data,i=e.data.refs||{};return this.parseWithRefs(r,i)}if(typeof e=="string")return this.parse(e);throw new Error("Invalid snapshot JSON format")}parseWithRefs(t,e){let r=[],i=new Map,n=0;for(let[o,c]of Object.entries(e)){let l={ref:o,refWithAt:`@${o}`,role:c.role,name:c.name,attributes:{},depth:0,children:[]};r.push(l),i.set(o,l)}let s=this.parse(t);for(let o of s.elements){let c=i.get(o.ref);c&&(c.text=o.text,c.depth=o.depth,c.level=o.level,o.depth>n&&(n=o.depth))}let a=r.filter(o=>xu.has(o.role.toLowerCase()));return{rawTree:t,elements:r,interactiveElements:a,refMap:i,stats:{totalElements:r.length,interactiveCount:a.length,maxDepth:n},parsedAt:new Date}}parseLine(t){if(!t.trim())return null;let e=this.getIndentLevel(t),r=t.match(/^(\s*-\s*)(\w+)(?:\s+"([^"]*)")?(.*)$/);if(!r)return null;let[,,i,n,s]=r,a=s?.match(/\[ref=(\w+)\]/);if(!a)return null;let o=a[1],c=s?.match(/\[level=(\d+)\]/),l=c?parseInt(c[1],10):void 0,d=s?.match(/\[nth=(\d+)\]/),m=d?parseInt(d[1],10):void 0,h=t.match(/:\s*(.+)$/),g=h?h[1].trim():void 0,b={};return l&&(b.level=String(l)),m!==void 0&&(b.nth=String(m)),{ref:o,refWithAt:`@${o}`,role:i.toLowerCase(),name:n,text:g,level:l,attributes:b,depth:e,children:[]}}getIndentLevel(t){let e=t.match(/^(\s*)/);return e?Math.floor(e[1].length/2):0}buildRelationships(t){let e=[];for(let r of t){for(;e.length>0&&e[e.length-1].depth>=r.depth;)e.pop();if(e.length>0){let i=e[e.length-1];r.parent=i.ref,i.children.push(r.ref)}e.push(r)}}findByRef(t,e){let r=e.startsWith("@")?e.slice(1):e;return t.refMap.get(r)||null}findByRole(t,e){return t.elements.filter(r=>r.role.toLowerCase()===e.toLowerCase())}findByName(t,e,r=!1){return t.elements.filter(i=>i.name?r?i.name===e:i.name.toLowerCase().includes(e.toLowerCase()):!1)}findByText(t,e,r=!1){return t.elements.filter(i=>{let n=i.text||i.name||"";return r?n===e:n.toLowerCase().includes(e.toLowerCase())})}findInteractive(t,e){for(let r of t.interactiveElements)if(!(e.role&&r.role.toLowerCase()!==e.role.toLowerCase())&&!(e.name&&r.name!==e.name)&&!(e.text&&!(r.text||r.name||"").toLowerCase().includes(e.text.toLowerCase())))return r;return null}refToCssSelector(t,e){let r=this.findByRef(t,e);if(!r)return null;let i=r.role,n=r.name;return{button:n?`button:has-text("${n}")`:"button",link:n?`a:has-text("${n}")`:"a",textbox:n?`input[placeholder="${n}"], input[aria-label="${n}"]`:'input[type="text"]',heading:n?`h1:has-text("${n}"), h2:has-text("${n}"), h3:has-text("${n}")`:"h1, h2, h3",checkbox:n?`input[type="checkbox"][aria-label="${n}"]`:'input[type="checkbox"]'}[i]||`[role="${i}"]`}},Bo=null;function Pu(){return Bo||(Bo=new qo),Bo}A();import{execSync as Vh}from"child_process";var ss=class{constructor(t){this.defaultConfig=t}defaultConfig;sessions=new Map;activeSession=null;sessionCounter=0;async createSession(t){let e=t?.name??this.generateSessionName();if(this.sessions.has(e))throw new Error(`Session "${e}" already exists`);let r=new dt({sessionName:e,headed:t?.headed??this.defaultConfig?.headed??!1,timeout:t?.timeout??this.defaultConfig?.timeout??3e4}),i={name:e,createdAt:new Date,lastActivity:new Date,status:"idle",executor:r};return this.sessions.set(e,i),t?.initialUrl&&r.open(t.initialUrl).success&&(i.currentUrl=t.initialUrl,i.status="active"),this.activeSession||(this.activeSession=e),i}async getOrCreateSession(t,e){let r=this.sessions.get(t);return r||this.createSession({...e,name:t})}getSession(t){return this.sessions.get(t)}getActiveSession(){if(this.activeSession)return this.sessions.get(this.activeSession)}switchSession(t){if(!this.sessions.has(t))throw new Error(`Session "${t}" not found`);this.activeSession=t}listSessions(){return Array.from(this.sessions.values())}listCliSessions(){try{let e=Vh("npx agent-browser session list",{encoding:"utf-8",timeout:5e3}).split(`
|
|
2308
|
-
`),r=[];for(let i of e){let n=i.match(/^\s*(?:->)?\s*(\w+)\s*$/);n&&r.push(n[1])}return r}catch{return[]}}async closeSession(t){let e=this.sessions.get(t);if(!e)return{success:!1,error:`Session "${t}" not found`};let r=e.executor.terminateDaemon();if(r.success&&(e.status="closed",this.sessions.delete(t),this.activeSession===t)){let i=Array.from(this.sessions.keys());this.activeSession=i.length>0?i[0]:null}return r}async closeAllSessions(){let t=Array.from(this.sessions.keys());for(let e of t)await this.closeSession(e);this.sessions.clear(),this.activeSession=null}async cleanupIdleSessions(t=300*1e3){let e=Date.now(),r=0;for(let[i,n]of this.sessions)n.status==="idle"&&e-n.lastActivity.getTime()>t&&(await this.closeSession(i),r++);return r}getExecutor(){let t=this.getActiveSession();if(!t)throw new Error("No active session. Create one first.");return t.executor}getSessionExecutor(t){let e=this.sessions.get(t);if(!e)throw new Error(`Session "${t}" not found`);return e.executor}touchSession(t){let e=this.sessions.get(t);e&&(e.lastActivity=new Date)}updateSessionUrl(t,e){let r=this.sessions.get(t);r&&(r.currentUrl=e,r.lastActivity=new Date,r.status="active")}generateSessionName(){return`session-${++this.sessionCounter}-${Date.now().toString(36)}`}getStats(){let t=0,e=0,r=0;for(let i of this.sessions.values())switch(i.status){case"active":t++;break;case"idle":e++;break;case"closed":r++;break}return{totalSessions:this.sessions.size,activeSessions:t,idleSessions:e,closedSessions:r,activeSessionName:this.activeSession}}};H();function vi(u){if(typeof u=="string")return/^@?e\d+$/.test(u)?u.startsWith("@")?u:`@${u}`:u;switch(u.type){case"ref":return u.value.startsWith("@")?u.value:`@${u.value}`;case"css":return u.value;case"xpath":return`xpath=${u.value}`;case"text":return`text=${u.value}`;default:return u.value}}function W(u){return{success:!0,value:u}}function $(u){return{success:!1,error:u}}function as(u){return{id:u.name,tool:"agent-browser",status:u.status,currentUrl:u.currentUrl,createdAt:u.createdAt}}function _h(u){let t=u.elements.map(i=>({ref:i.refWithAt,role:i.role,name:i.name,text:i.text,depth:i.depth})),e=u.interactiveElements.map(i=>({ref:i.refWithAt,role:i.role,name:i.name,text:i.text,depth:i.depth})),r=new Map;for(let i of t)r.set(i.ref,i);return{url:u.url??"",title:u.title??"",elements:t,interactiveElements:e,refMap:r,timestamp:u.parsedAt}}var cr=class{tool="agent-browser";executor;sessionManager;snapshotParser;config;isLaunched=!1;currentSessionId=null;constructor(t={}){this.config={headed:t.headed??!1,timeout:t.timeout??3e4,debug:t.debug??!1,sessionName:t.sessionName??"default"};let e={sessionName:this.config.sessionName,timeout:this.config.timeout,headed:this.config.headed,debug:this.config.debug};this.executor=new dt(e),this.sessionManager=new ss({headed:this.config.headed,timeout:this.config.timeout}),this.snapshotParser=Pu()}async launch(t){try{if(this.isLaunched&&this.currentSessionId){let n=this.sessionManager.getSession(this.currentSessionId);if(n)return t?.viewport&&await this.setViewport(t.viewport.width,t.viewport.height),W(as(n))}if(!await this.isAvailable())return $(new te("agent-browser","agent-browser CLI is not available"));let r=t?.sessionName??this.config.sessionName,i=await this.sessionManager.createSession({name:r,headed:t?.headless===!1||this.config.headed,timeout:this.config.timeout});return this.currentSessionId=i.name,this.isLaunched=!0,this.executor=new dt({sessionName:i.name,timeout:this.config.timeout,headed:t?.headless===!1||this.config.headed,debug:this.config.debug}),t?.viewport&&await this.setViewport(t.viewport.width,t.viewport.height),t?.deviceName&&await this.setDevice(t.deviceName),W(as(i))}catch(e){let r=new F(T(e),"LAUNCH_FAILED","agent-browser",e instanceof Error?e:void 0);return $(r)}}async quit(){try{if(this.currentSessionId){let t=await this.sessionManager.closeSession(this.currentSessionId);t.success||this.config.debug&&console.warn(`[agent-browser] Session close warning: ${t.error}`)}if(this.executor)try{this.executor.terminateDaemon()}catch(t){console.debug("[AgentBrowserClient] Daemon termination error:",t instanceof Error?t.message:t)}return this.isLaunched=!1,this.currentSessionId=null,W(void 0)}catch(t){return this.isLaunched=!1,this.currentSessionId=null,$(new F(T(t),"QUIT_FAILED","agent-browser",t instanceof Error?t:void 0))}}async isAvailable(){return Eu()}async dispose(){await this.sessionManager.closeAllSessions(),this.isLaunched=!1,this.currentSessionId=null}async navigate(t){let e=Date.now();try{let r=this.executor.open(t);if(!r.success)return $(new F(r.error??"Navigation failed","NAVIGATION_FAILED","agent-browser"));this.currentSessionId&&this.sessionManager.updateSessionUrl(this.currentSessionId,t);let i=this.executor.eval("JSON.stringify({ title: document.title, url: window.location.href })"),n=i.success&&i.data?typeof i.data=="string"?E(i.data):i.data:{title:"",url:t};return W({url:n.url||t,title:n.title||"",success:!0,durationMs:Date.now()-e})}catch(r){return $(new F(T(r),"NAVIGATION_FAILED","agent-browser",r instanceof Error?r:void 0))}}async reload(){try{let t=this.executor.eval("window.location.reload()");return t.success?W(void 0):$(new F(t.error??"Reload failed","RELOAD_FAILED","agent-browser"))}catch(t){return $(new F(T(t),"RELOAD_FAILED","agent-browser",t instanceof Error?t:void 0))}}async goBack(){try{let t=this.executor.eval("window.history.back()");return t.success?W(void 0):$(new F(t.error??"Go back failed","HISTORY_FAILED","agent-browser"))}catch(t){return $(new F(T(t),"HISTORY_FAILED","agent-browser",t instanceof Error?t:void 0))}}async goForward(){try{let t=this.executor.eval("window.history.forward()");return t.success?W(void 0):$(new F(t.error??"Go forward failed","HISTORY_FAILED","agent-browser"))}catch(t){return $(new F(T(t),"HISTORY_FAILED","agent-browser",t instanceof Error?t:void 0))}}async click(t){try{let e=vi(t),r=this.executor.click(e);return r.success?W(void 0):$(new $t("agent-browser",t,new Error(r.error)))}catch(e){return $(new F(T(e),"CLICK_FAILED","agent-browser",e instanceof Error?e:void 0))}}async fill(t,e){try{let r=vi(t),i=this.executor.fill(r,e);return i.success?W(void 0):$(new $t("agent-browser",t,new Error(i.error)))}catch(r){return $(new F(T(r),"FILL_FAILED","agent-browser",r instanceof Error?r:void 0))}}async getText(t){try{let e=vi(t),r=this.executor.getText(e);if(!r.success)return $(new $t("agent-browser",t,new Error(r.error)));let i=r.data;if(i&&typeof i=="object"){let n=i;if("text"in n)i=n.text;else if("data"in n&&typeof n.data=="object"){let s=n.data;"text"in s?i=s.text:"result"in s&&(i=s.result)}else"result"in n&&(i=n.result)}return W(String(i??""))}catch(e){return $(new F(T(e),"GET_TEXT_FAILED","agent-browser",e instanceof Error?e:void 0))}}async isVisible(t){try{let e=vi(t),r=this.executor.isVisible(e);return r.success?W(!!r.data):W(!1)}catch(e){return $(new F(T(e),"VISIBILITY_CHECK_FAILED","agent-browser",e instanceof Error?e:void 0))}}async screenshot(t){try{let e=this.executor.screenshot(t?.path,t?.fullPage);if(!e.success)return $(new F(e.error??"Screenshot failed","SCREENSHOT_FAILED","agent-browser"));let r=this.executor.eval("JSON.stringify({ width: window.innerWidth, height: window.innerHeight })"),i={width:1280,height:720};if(r.success&&r.data){let n=typeof r.data=="string"?E(r.data):r.data;i={width:n.width||1280,height:n.height||720}}return W({base64:t?.path?void 0:String(e.data??""),path:t?.path,format:"png",dimensions:i})}catch(e){return $(new F(T(e),"SCREENSHOT_FAILED","agent-browser",e instanceof Error?e:void 0))}}async evaluate(t){try{let e=this.executor.eval(t);if(!e.success)return $(new F(e.error??"Evaluation failed","EVAL_FAILED","agent-browser"));let r=e.data;if(r&&typeof r=="object"){let i=r;if("data"in i&&i.data&&typeof i.data=="object"){let n=i.data;"result"in n&&(r=n.result)}else"result"in i&&(r=i.result)}return W(r)}catch(e){return $(new F(T(e),"EVAL_FAILED","agent-browser",e instanceof Error?e:void 0))}}async getSnapshot(t){try{let e=this.executor.snapshot({interactive:t?.interactive,depth:t?.depth});if(!e.success)return $(new F(e.error??"Snapshot failed","SNAPSHOT_FAILED","agent-browser"));let r;try{r=this.snapshotParser.parseJson(e.data)}catch{r=this.snapshotParser.parse(String(e.data))}let i=this.executor.eval("window.location.href"),n=this.executor.eval("document.title");return i.success&&(r.url=String(i.data)),n.success&&(r.title=String(n.data)),W(_h(r))}catch(e){return $(new F(T(e),"SNAPSHOT_FAILED","agent-browser",e instanceof Error?e:void 0))}}async createSession(t){try{let e=await this.sessionManager.createSession({name:t});return W(as(e))}catch(e){return $(new F(T(e),"SESSION_CREATE_FAILED","agent-browser",e instanceof Error?e:void 0))}}async switchSession(t){try{return this.sessionManager.switchSession(t),this.currentSessionId=t,this.executor=new dt({sessionName:t,timeout:this.config.timeout,headed:this.config.headed,debug:this.config.debug}),W(void 0)}catch(e){return $(new F(T(e),"SESSION_SWITCH_FAILED","agent-browser",e instanceof Error?e:void 0))}}async listSessions(){try{let t=this.sessionManager.listSessions();return W(t.map(as))}catch(t){return $(new F(T(t),"SESSION_LIST_FAILED","agent-browser",t instanceof Error?t:void 0))}}async mockRoute(t,e){try{let r={status:e.status??200,body:e.body,headers:e.headers},i=this.executor.mockRoute(t,r);return i.success?W(void 0):$(new F(i.error??"Mock route failed","MOCK_ROUTE_FAILED","agent-browser"))}catch(r){return $(new F(T(r),"MOCK_ROUTE_FAILED","agent-browser",r instanceof Error?r:void 0))}}async abortRoute(t){try{let e=this.executor.abortRoute(t);return e.success?W(void 0):$(new F(e.error??"Abort route failed","ABORT_ROUTE_FAILED","agent-browser"))}catch(e){return $(new F(T(e),"ABORT_ROUTE_FAILED","agent-browser",e instanceof Error?e:void 0))}}async clearRoutes(){try{let t=this.executor.clearRoutes();return t.success?W(void 0):$(new F(t.error??"Clear routes failed","CLEAR_ROUTES_FAILED","agent-browser"))}catch(t){return $(new F(T(t),"CLEAR_ROUTES_FAILED","agent-browser",t instanceof Error?t:void 0))}}async setDevice(t){try{let e=this.executor.setDevice(t);return e.success?W(void 0):$(new F(e.error??"Set device failed","SET_DEVICE_FAILED","agent-browser"))}catch(e){return $(new F(T(e),"SET_DEVICE_FAILED","agent-browser",e instanceof Error?e:void 0))}}async setViewport(t,e){try{let r=this.executor.setViewport(t,e);return r.success?W(void 0):$(new F(r.error??"Set viewport failed","SET_VIEWPORT_FAILED","agent-browser"))}catch(r){return $(new F(T(r),"SET_VIEWPORT_FAILED","agent-browser",r instanceof Error?r:void 0))}}async saveState(t){try{let e=this.executor.saveState(t);return e.success?W(void 0):$(new F(e.error??"Save state failed","SAVE_STATE_FAILED","agent-browser"))}catch(e){return $(new F(T(e),"SAVE_STATE_FAILED","agent-browser",e instanceof Error?e:void 0))}}async loadState(t){try{let e=this.executor.loadState(t);return e.success?W(void 0):$(new F(e.error??"Load state failed","LOAD_STATE_FAILED","agent-browser"))}catch(e){return $(new F(T(e),"LOAD_STATE_FAILED","agent-browser",e instanceof Error?e:void 0))}}async waitForElement(t,e){try{let r=vi(t),i=this.executor.waitForElement(r,e);return i.success?W(void 0):$(new ut("agent-browser",`waitForElement(${r})`,new Error(i.error)))}catch(r){return $(new F(T(r),"WAIT_FAILED","agent-browser",r instanceof Error?r:void 0))}}async waitForText(t,e){try{let r=this.executor.waitForText(t);return r.success?W(void 0):$(new ut("agent-browser",`waitForText("${t}")`,new Error(r.error)))}catch(r){return $(new F(T(r),"WAIT_FAILED","agent-browser",r instanceof Error?r:void 0))}}async waitForUrl(t,e){try{let r=this.executor.waitForUrl(t);return r.success?W(void 0):$(new ut("agent-browser",`waitForUrl("${t}")`,new Error(r.error)))}catch(r){return $(new F(T(r),"WAIT_FAILED","agent-browser",r instanceof Error?r:void 0))}}async waitForNetworkIdle(t){try{let e=this.executor.waitForNetworkIdle();return e.success?W(void 0):$(new ut("agent-browser","waitForNetworkIdle",new Error(e.error)))}catch(e){return $(new F(T(e),"WAIT_FAILED","agent-browser",e instanceof Error?e:void 0))}}async startTrace(){try{let t=this.executor.startTrace();return t.success?W(void 0):$(new F(t.error??"Start trace failed","START_TRACE_FAILED","agent-browser"))}catch(t){return $(new F(T(t),"START_TRACE_FAILED","agent-browser",t instanceof Error?t:void 0))}}async stopTrace(t){try{let e=this.executor.stopTrace(t);return e.success?W(e.data??t):$(new F(e.error??"Stop trace failed","STOP_TRACE_FAILED","agent-browser"))}catch(e){return $(new F(T(e),"STOP_TRACE_FAILED","agent-browser",e instanceof Error?e:void 0))}}};import{randomUUID as Fu}from"crypto";var os={persistentContext:!0,cloudflareWaitSeconds:0,resourceBlocking:"functional"};var zh=new Set(["google-analytics.com","googletagmanager.com","analytics.google.com","hotjar.com","fullstory.com","segment.io","segment.com","mixpanel.com","heap.io","heapanalytics.com","amplitude.com","mouseflow.com","crazyegg.com","optimizely.com","newrelic.com","nr-data.net","sentry.io","bugsnag.com","logrocket.com","clarity.ms","facebook.net","connect.facebook.net"]),Bh=new Set(["doubleclick.net","googlesyndication.com","googleadservices.com","google-analytics.com","adservice.google.com","pagead2.googlesyndication.com","ads.twitter.com","ads-api.twitter.com","adsserver.com","adnxs.com","amazon-adsystem.com","criteo.com","moatads.com","outbrain.com","taboola.com","bidswitch.net","rubiconproject.com"]),qh={image:"image",font:"font",media:"media",stylesheet:"stylesheet",websocket:"websocket"},ku={functional:{enabled:!0,blockedCategories:["image","font","media","stylesheet","tracking","advertising"]},visual:{enabled:!1,blockedCategories:[]},performance:{enabled:!0,blockedCategories:["image","font","media","tracking","advertising"]}};function Go(u,t,e){if(!e.enabled)return!1;if(e.allowPatterns?.length){for(let i of e.allowPatterns)if(Iu(u,i))return!1}if(e.blockPatterns?.length){for(let i of e.blockPatterns)if(Iu(u,i))return!0}let r=qh[t];return!!(r&&e.blockedCategories.includes(r)||e.blockedCategories.includes("tracking")&&Mu(u,zh)||e.blockedCategories.includes("advertising")&&Mu(u,Bh))}function bi(u){if(typeof u=="object")return u;let t=ku[u];return t?{...t,blockedCategories:[...t.blockedCategories]}:ku.visual}var Du=new Map;function Iu(u,t){let e=Du.get(t);if(!e){let r=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");e=new RegExp(r,"i"),Du.set(t,e)}return e.test(u)}function Mu(u,t){try{let e=new URL(u).hostname;for(let r of t)if(e===r||e.endsWith(`.${r}`))return!0}catch{}return!1}var cs=null,Lu=!1;function $u(){if(Lu)return cs;Lu=!0;try{cs=Fa("patchright")}catch{cs=null}return cs}var mt=class{tool="stealth";stealthConfig;page=null;context=null;browser=null;sessionId=null;constructor(t){this.stealthConfig={...os,...t}}async isAvailable(){return $u()!==null}async launch(t){let e=$u();if(!e)return{success:!1,error:new te("stealth","Patchright is not installed. Install with: npm install patchright")};try{let r={headless:t?.headless??!0};if(t?.viewport&&(r.viewport=t.viewport),t?.args&&(r.args=t.args),this.stealthConfig.userAgent&&(r.userAgent=this.stealthConfig.userAgent),this.stealthConfig.proxy&&(r.proxy=this.stealthConfig.proxy),this.stealthConfig.persistentContext){let i=this.stealthConfig.userDataDir||`/tmp/stealth-browser-${Fu()}`;this.context=await e.chromium.launchPersistentContext(i,r);let n=this.context.pages();this.page=n.length>0?n[0]:await this.context.newPage()}else this.browser=await e.chromium.launch(r),this.page=await this.browser.newPage();return await this.applyResourceBlocking(),this.sessionId=Fu(),{success:!0,value:{id:this.sessionId,tool:"stealth",status:"active",createdAt:new Date}}}catch(r){return{success:!1,error:new F(`Failed to launch stealth browser: ${r instanceof Error?r.message:String(r)}`,"LAUNCH_FAILED","stealth",r instanceof Error?r:void 0)}}}async quit(){try{return this.context&&(await this.context.close(),this.context=null),this.browser&&(await this.browser.close(),this.browser=null),this.page=null,this.sessionId=null,{success:!0,value:void 0}}catch(t){return{success:!1,error:new F("Failed to quit stealth browser","QUIT_FAILED","stealth",t instanceof Error?t:void 0)}}}async navigate(t){if(!this.page)return this.notLaunched();try{let e=Date.now(),i=(await this.page.goto(t,{waitUntil:"domcontentloaded"}))?.status()??void 0;this.stealthConfig.cloudflareWaitSeconds>0&&await this.waitForCloudflare();let n=await this.page.title();return{success:!0,value:{url:this.page.url(),title:n,success:!0,durationMs:Date.now()-e,statusCode:i??void 0}}}catch(e){return this.wrapError("navigate",e)}}async reload(){if(!this.page)return this.notLaunched();try{return await this.page.reload(),{success:!0,value:void 0}}catch(t){return this.wrapError("reload",t)}}async goBack(){if(!this.page)return this.notLaunched();try{return await this.page.goBack(),{success:!0,value:void 0}}catch(t){return this.wrapError("goBack",t)}}async goForward(){if(!this.page)return this.notLaunched();try{return await this.page.goForward(),{success:!0,value:void 0}}catch(t){return this.wrapError("goForward",t)}}async click(t){if(!this.page)return this.notLaunched();try{let e=this.resolveSelector(t);return await this.page.click(e),{success:!0,value:void 0}}catch(e){return this.wrapError("click",e)}}async fill(t,e){if(!this.page)return this.notLaunched();try{let r=this.resolveSelector(t);return await this.page.fill(r,e),{success:!0,value:void 0}}catch(r){return this.wrapError("fill",r)}}async getText(t){if(!this.page)return this.notLaunched();try{let e=this.resolveSelector(t);return{success:!0,value:await this.page.textContent(e)??""}}catch(e){return this.wrapError("getText",e)}}async isVisible(t){if(!this.page)return this.notLaunched();try{let e=this.resolveSelector(t);return{success:!0,value:await this.page.isVisible(e)}}catch(e){return this.wrapError("isVisible",e)}}async screenshot(t){if(!this.page)return this.notLaunched();try{return{success:!0,value:{base64:(await this.page.screenshot({path:t?.path,fullPage:t?.fullPage,type:"png"})).toString("base64"),path:t?.path,format:"png",dimensions:{width:0,height:0}}}}catch(e){return this.wrapError("screenshot",e)}}async evaluate(t){if(!this.page)return this.notLaunched();try{return{success:!0,value:await this.page.evaluate(t)}}catch(e){return this.wrapError("evaluate",e)}}async dispose(){await this.quit()}resolveSelector(t){if(typeof t=="string")return t;switch(t.type){case"css":return t.value;case"xpath":return`xpath=${t.value}`;case"text":return`text=${t.value}`;case"ref":return t.value;default:return t.value}}async applyResourceBlocking(){if(!this.page||!this.stealthConfig.resourceBlocking)return;let t=typeof this.stealthConfig.resourceBlocking=="string"?bi(this.stealthConfig.resourceBlocking):this.stealthConfig.resourceBlocking;t.enabled&&await this.page.route("**/*",e=>{let r=e.request().url(),i=e.request().resourceType();Go(r,i,t)?e.abort().catch(()=>{}):e.continue().catch(()=>{})})}async waitForCloudflare(){if(!this.page||this.stealthConfig.cloudflareWaitSeconds<=0)return;let t=this.stealthConfig.cloudflareWaitSeconds*1e3,e=Date.now();for(;Date.now()-e<t;){try{let r=await this.page.title();if(!r.includes("Just a moment")&&!r.includes("Checking your browser"))return}catch{}await new Promise(r=>setTimeout(r,500))}}notLaunched(){return{success:!1,error:new F("Stealth browser not launched. Call launch() first.","NOT_LAUNCHED","stealth")}}wrapError(t,e){return{success:!1,error:new F(`Stealth ${t} failed: ${e instanceof Error?e.message:String(e)}`,"OPERATION_FAILED","stealth",e instanceof Error?e:void 0)}}};async function Ho(){return!1}async function Wo(){try{return await new cr().isAvailable()}catch{return!1}}var Gh=["e2e-testing","api-mocking","responsive-testing","auth-testing"],Hh=["stealth-testing"];function jh(u){return Gh.includes(u)}var ls=class{tool="vibium";async isAvailable(){return!1}async launch(){return{success:!1,error:new te("vibium","Vibium client not yet implemented")}}async quit(){return{success:!1,error:new te("vibium","Vibium client not yet implemented")}}async navigate(){return{success:!1,error:new te("vibium","Vibium client not yet implemented")}}async reload(){return{success:!1,error:new te("vibium","Vibium client not yet implemented")}}async goBack(){return{success:!1,error:new te("vibium","Vibium client not yet implemented")}}async goForward(){return{success:!1,error:new te("vibium","Vibium client not yet implemented")}}async click(){return{success:!1,error:new te("vibium","Vibium client not yet implemented")}}async fill(){return{success:!1,error:new te("vibium","Vibium client not yet implemented")}}async getText(){return{success:!1,error:new te("vibium","Vibium client not yet implemented")}}async isVisible(){return{success:!1,error:new te("vibium","Vibium client not yet implemented")}}async screenshot(){return{success:!1,error:new te("vibium","Vibium client not yet implemented")}}async evaluate(){return{success:!1,error:new te("vibium","Vibium client not yet implemented")}}async dispose(){}};async function Uo(u={}){let{preference:t="auto",useCase:e}=u;if(e&&Hh.includes(e)&&await jo())return new mt;if(e&&jh(e)||t==="agent-browser")return wi();if(t==="stealth"){if(await jo())return new mt;throw new te("stealth","Patchright is not installed")}if(t==="vibium"){if(await Ho())return new ls;throw new te("vibium","Vibium is not available")}return await Ho()?new ls:(await Wo(),wi())}async function wi(){return new cr}async function us(u){return Uo({useCase:u})}async function jo(){try{return await new mt().isAvailable()}catch{return!1}}import{exec as Uh,execSync as nE}from"child_process";import{promisify as Qh}from"util";A();H();var uE=Qh(Uh);A();var Ou={enabled:!0,similarityThreshold:.6,maxFingerprintsPerPage:200,namespace:"aqe/adaptive-locators",fallbackChain:["text","aria","fingerprint"]};function Kh(u){return`
|
|
2308
|
+
`),r=[];for(let i of e){let n=i.match(/^\s*(?:->)?\s*(\w+)\s*$/);n&&r.push(n[1])}return r}catch{return[]}}async closeSession(t){let e=this.sessions.get(t);if(!e)return{success:!1,error:`Session "${t}" not found`};let r=e.executor.terminateDaemon();if(r.success&&(e.status="closed",this.sessions.delete(t),this.activeSession===t)){let i=Array.from(this.sessions.keys());this.activeSession=i.length>0?i[0]:null}return r}async closeAllSessions(){let t=Array.from(this.sessions.keys());for(let e of t)await this.closeSession(e);this.sessions.clear(),this.activeSession=null}async cleanupIdleSessions(t=300*1e3){let e=Date.now(),r=0;for(let[i,n]of this.sessions)n.status==="idle"&&e-n.lastActivity.getTime()>t&&(await this.closeSession(i),r++);return r}getExecutor(){let t=this.getActiveSession();if(!t)throw new Error("No active session. Create one first.");return t.executor}getSessionExecutor(t){let e=this.sessions.get(t);if(!e)throw new Error(`Session "${t}" not found`);return e.executor}touchSession(t){let e=this.sessions.get(t);e&&(e.lastActivity=new Date)}updateSessionUrl(t,e){let r=this.sessions.get(t);r&&(r.currentUrl=e,r.lastActivity=new Date,r.status="active")}generateSessionName(){return`session-${++this.sessionCounter}-${Date.now().toString(36)}`}getStats(){let t=0,e=0,r=0;for(let i of this.sessions.values())switch(i.status){case"active":t++;break;case"idle":e++;break;case"closed":r++;break}return{totalSessions:this.sessions.size,activeSessions:t,idleSessions:e,closedSessions:r,activeSessionName:this.activeSession}}};H();function vi(u){if(typeof u=="string")return/^@?e\d+$/.test(u)?u.startsWith("@")?u:`@${u}`:u;switch(u.type){case"ref":return u.value.startsWith("@")?u.value:`@${u.value}`;case"css":return u.value;case"xpath":return`xpath=${u.value}`;case"text":return`text=${u.value}`;default:return u.value}}function W(u){return{success:!0,value:u}}function $(u){return{success:!1,error:u}}function as(u){return{id:u.name,tool:"agent-browser",status:u.status,currentUrl:u.currentUrl,createdAt:u.createdAt}}function _h(u){let t=u.elements.map(i=>({ref:i.refWithAt,role:i.role,name:i.name,text:i.text,depth:i.depth})),e=u.interactiveElements.map(i=>({ref:i.refWithAt,role:i.role,name:i.name,text:i.text,depth:i.depth})),r=new Map;for(let i of t)r.set(i.ref,i);return{url:u.url??"",title:u.title??"",elements:t,interactiveElements:e,refMap:r,timestamp:u.parsedAt}}var cr=class{tool="agent-browser";executor;sessionManager;snapshotParser;config;isLaunched=!1;currentSessionId=null;constructor(t={}){this.config={headed:t.headed??!1,timeout:t.timeout??3e4,debug:t.debug??!1,sessionName:t.sessionName??"default"};let e={sessionName:this.config.sessionName,timeout:this.config.timeout,headed:this.config.headed,debug:this.config.debug};this.executor=new dt(e),this.sessionManager=new ss({headed:this.config.headed,timeout:this.config.timeout}),this.snapshotParser=Pu()}async launch(t){try{if(this.isLaunched&&this.currentSessionId){let n=this.sessionManager.getSession(this.currentSessionId);if(n)return t?.viewport&&await this.setViewport(t.viewport.width,t.viewport.height),W(as(n))}if(!await this.isAvailable())return $(new te("agent-browser","agent-browser CLI is not available"));let r=t?.sessionName??this.config.sessionName,i=await this.sessionManager.createSession({name:r,headed:t?.headless===!1||this.config.headed,timeout:this.config.timeout});return this.currentSessionId=i.name,this.isLaunched=!0,this.executor=new dt({sessionName:i.name,timeout:this.config.timeout,headed:t?.headless===!1||this.config.headed,debug:this.config.debug}),t?.viewport&&await this.setViewport(t.viewport.width,t.viewport.height),t?.deviceName&&await this.setDevice(t.deviceName),W(as(i))}catch(e){let r=new F(T(e),"LAUNCH_FAILED","agent-browser",e instanceof Error?e:void 0);return $(r)}}async quit(){try{if(this.currentSessionId){let t=await this.sessionManager.closeSession(this.currentSessionId);t.success||this.config.debug&&console.warn(`[agent-browser] Session close warning: ${t.error}`)}if(this.executor)try{this.executor.terminateDaemon()}catch(t){console.debug("[AgentBrowserClient] Daemon termination error:",t instanceof Error?t.message:t)}return this.isLaunched=!1,this.currentSessionId=null,W(void 0)}catch(t){return this.isLaunched=!1,this.currentSessionId=null,$(new F(T(t),"QUIT_FAILED","agent-browser",t instanceof Error?t:void 0))}}async isAvailable(){return Eu()}async dispose(){await this.sessionManager.closeAllSessions(),this.isLaunched=!1,this.currentSessionId=null}async navigate(t){let e=Date.now();try{let r=this.executor.open(t);if(!r.success)return $(new F(r.error??"Navigation failed","NAVIGATION_FAILED","agent-browser"));this.currentSessionId&&this.sessionManager.updateSessionUrl(this.currentSessionId,t);let i=this.executor.eval("JSON.stringify({ title: document.title, url: window.location.href })"),n=i.success&&i.data?typeof i.data=="string"?E(i.data):i.data:{title:"",url:t};return W({url:n.url||t,title:n.title||"",success:!0,durationMs:Date.now()-e})}catch(r){return $(new F(T(r),"NAVIGATION_FAILED","agent-browser",r instanceof Error?r:void 0))}}async reload(){try{let t=this.executor.eval("window.location.reload()");return t.success?W(void 0):$(new F(t.error??"Reload failed","RELOAD_FAILED","agent-browser"))}catch(t){return $(new F(T(t),"RELOAD_FAILED","agent-browser",t instanceof Error?t:void 0))}}async goBack(){try{let t=this.executor.eval("window.history.back()");return t.success?W(void 0):$(new F(t.error??"Go back failed","HISTORY_FAILED","agent-browser"))}catch(t){return $(new F(T(t),"HISTORY_FAILED","agent-browser",t instanceof Error?t:void 0))}}async goForward(){try{let t=this.executor.eval("window.history.forward()");return t.success?W(void 0):$(new F(t.error??"Go forward failed","HISTORY_FAILED","agent-browser"))}catch(t){return $(new F(T(t),"HISTORY_FAILED","agent-browser",t instanceof Error?t:void 0))}}async click(t){try{let e=vi(t),r=this.executor.click(e);return r.success?W(void 0):$(new $t("agent-browser",t,new Error(r.error)))}catch(e){return $(new F(T(e),"CLICK_FAILED","agent-browser",e instanceof Error?e:void 0))}}async fill(t,e){try{let r=vi(t),i=this.executor.fill(r,e);return i.success?W(void 0):$(new $t("agent-browser",t,new Error(i.error)))}catch(r){return $(new F(T(r),"FILL_FAILED","agent-browser",r instanceof Error?r:void 0))}}async getText(t){try{let e=vi(t),r=this.executor.getText(e);if(!r.success)return $(new $t("agent-browser",t,new Error(r.error)));let i=r.data;if(i&&typeof i=="object"){let n=i;if("text"in n)i=n.text;else if("data"in n&&typeof n.data=="object"){let s=n.data;"text"in s?i=s.text:"result"in s&&(i=s.result)}else"result"in n&&(i=n.result)}return W(String(i??""))}catch(e){return $(new F(T(e),"GET_TEXT_FAILED","agent-browser",e instanceof Error?e:void 0))}}async isVisible(t){try{let e=vi(t),r=this.executor.isVisible(e);return r.success?W(!!r.data):W(!1)}catch(e){return $(new F(T(e),"VISIBILITY_CHECK_FAILED","agent-browser",e instanceof Error?e:void 0))}}async screenshot(t){try{let e=this.executor.screenshot(t?.path,t?.fullPage);if(!e.success)return $(new F(e.error??"Screenshot failed","SCREENSHOT_FAILED","agent-browser"));let r=this.executor.eval("JSON.stringify({ width: window.innerWidth, height: window.innerHeight })"),i={width:1280,height:720};if(r.success&&r.data){let n=typeof r.data=="string"?E(r.data):r.data;i={width:n.width||1280,height:n.height||720}}return W({base64:t?.path?void 0:String(e.data??""),path:t?.path,format:"png",dimensions:i})}catch(e){return $(new F(T(e),"SCREENSHOT_FAILED","agent-browser",e instanceof Error?e:void 0))}}async evaluate(t){try{let e=this.executor.eval(t);if(!e.success)return $(new F(e.error??"Evaluation failed","EVAL_FAILED","agent-browser"));let r=e.data;if(r&&typeof r=="object"){let i=r;if("data"in i&&i.data&&typeof i.data=="object"){let n=i.data;"result"in n&&(r=n.result)}else"result"in i&&(r=i.result)}return W(r)}catch(e){return $(new F(T(e),"EVAL_FAILED","agent-browser",e instanceof Error?e:void 0))}}async getSnapshot(t){try{let e=this.executor.snapshot({interactive:t?.interactive,depth:t?.depth});if(!e.success)return $(new F(e.error??"Snapshot failed","SNAPSHOT_FAILED","agent-browser"));let r;try{r=this.snapshotParser.parseJson(e.data)}catch{r=this.snapshotParser.parse(String(e.data))}let i=this.executor.eval("window.location.href"),n=this.executor.eval("document.title");return i.success&&(r.url=String(i.data)),n.success&&(r.title=String(n.data)),W(_h(r))}catch(e){return $(new F(T(e),"SNAPSHOT_FAILED","agent-browser",e instanceof Error?e:void 0))}}async createSession(t){try{let e=await this.sessionManager.createSession({name:t});return W(as(e))}catch(e){return $(new F(T(e),"SESSION_CREATE_FAILED","agent-browser",e instanceof Error?e:void 0))}}async switchSession(t){try{return this.sessionManager.switchSession(t),this.currentSessionId=t,this.executor=new dt({sessionName:t,timeout:this.config.timeout,headed:this.config.headed,debug:this.config.debug}),W(void 0)}catch(e){return $(new F(T(e),"SESSION_SWITCH_FAILED","agent-browser",e instanceof Error?e:void 0))}}async listSessions(){try{let t=this.sessionManager.listSessions();return W(t.map(as))}catch(t){return $(new F(T(t),"SESSION_LIST_FAILED","agent-browser",t instanceof Error?t:void 0))}}async mockRoute(t,e){try{let r={status:e.status??200,body:e.body,headers:e.headers},i=this.executor.mockRoute(t,r);return i.success?W(void 0):$(new F(i.error??"Mock route failed","MOCK_ROUTE_FAILED","agent-browser"))}catch(r){return $(new F(T(r),"MOCK_ROUTE_FAILED","agent-browser",r instanceof Error?r:void 0))}}async abortRoute(t){try{let e=this.executor.abortRoute(t);return e.success?W(void 0):$(new F(e.error??"Abort route failed","ABORT_ROUTE_FAILED","agent-browser"))}catch(e){return $(new F(T(e),"ABORT_ROUTE_FAILED","agent-browser",e instanceof Error?e:void 0))}}async clearRoutes(){try{let t=this.executor.clearRoutes();return t.success?W(void 0):$(new F(t.error??"Clear routes failed","CLEAR_ROUTES_FAILED","agent-browser"))}catch(t){return $(new F(T(t),"CLEAR_ROUTES_FAILED","agent-browser",t instanceof Error?t:void 0))}}async setDevice(t){try{let e=this.executor.setDevice(t);return e.success?W(void 0):$(new F(e.error??"Set device failed","SET_DEVICE_FAILED","agent-browser"))}catch(e){return $(new F(T(e),"SET_DEVICE_FAILED","agent-browser",e instanceof Error?e:void 0))}}async setViewport(t,e){try{let r=this.executor.setViewport(t,e);return r.success?W(void 0):$(new F(r.error??"Set viewport failed","SET_VIEWPORT_FAILED","agent-browser"))}catch(r){return $(new F(T(r),"SET_VIEWPORT_FAILED","agent-browser",r instanceof Error?r:void 0))}}async saveState(t){try{let e=this.executor.saveState(t);return e.success?W(void 0):$(new F(e.error??"Save state failed","SAVE_STATE_FAILED","agent-browser"))}catch(e){return $(new F(T(e),"SAVE_STATE_FAILED","agent-browser",e instanceof Error?e:void 0))}}async loadState(t){try{let e=this.executor.loadState(t);return e.success?W(void 0):$(new F(e.error??"Load state failed","LOAD_STATE_FAILED","agent-browser"))}catch(e){return $(new F(T(e),"LOAD_STATE_FAILED","agent-browser",e instanceof Error?e:void 0))}}async waitForElement(t,e){try{let r=vi(t),i=this.executor.waitForElement(r,e);return i.success?W(void 0):$(new ut("agent-browser",`waitForElement(${r})`,new Error(i.error)))}catch(r){return $(new F(T(r),"WAIT_FAILED","agent-browser",r instanceof Error?r:void 0))}}async waitForText(t,e){try{let r=this.executor.waitForText(t);return r.success?W(void 0):$(new ut("agent-browser",`waitForText("${t}")`,new Error(r.error)))}catch(r){return $(new F(T(r),"WAIT_FAILED","agent-browser",r instanceof Error?r:void 0))}}async waitForUrl(t,e){try{let r=this.executor.waitForUrl(t);return r.success?W(void 0):$(new ut("agent-browser",`waitForUrl("${t}")`,new Error(r.error)))}catch(r){return $(new F(T(r),"WAIT_FAILED","agent-browser",r instanceof Error?r:void 0))}}async waitForNetworkIdle(t){try{let e=this.executor.waitForNetworkIdle();return e.success?W(void 0):$(new ut("agent-browser","waitForNetworkIdle",new Error(e.error)))}catch(e){return $(new F(T(e),"WAIT_FAILED","agent-browser",e instanceof Error?e:void 0))}}async startTrace(){try{let t=this.executor.startTrace();return t.success?W(void 0):$(new F(t.error??"Start trace failed","START_TRACE_FAILED","agent-browser"))}catch(t){return $(new F(T(t),"START_TRACE_FAILED","agent-browser",t instanceof Error?t:void 0))}}async stopTrace(t){try{let e=this.executor.stopTrace(t);return e.success?W(e.data??t):$(new F(e.error??"Stop trace failed","STOP_TRACE_FAILED","agent-browser"))}catch(e){return $(new F(T(e),"STOP_TRACE_FAILED","agent-browser",e instanceof Error?e:void 0))}}};import{randomUUID as Fu}from"crypto";var os={persistentContext:!0,cloudflareWaitSeconds:0,resourceBlocking:"functional"};var zh=new Set(["google-analytics.com","googletagmanager.com","analytics.google.com","hotjar.com","fullstory.com","segment.io","segment.com","mixpanel.com","heap.io","heapanalytics.com","amplitude.com","mouseflow.com","crazyegg.com","optimizely.com","newrelic.com","nr-data.net","sentry.io","bugsnag.com","logrocket.com","clarity.ms","facebook.net","connect.facebook.net"]),Bh=new Set(["doubleclick.net","googlesyndication.com","googleadservices.com","google-analytics.com","adservice.google.com","pagead2.googlesyndication.com","ads.twitter.com","ads-api.twitter.com","adsserver.com","adnxs.com","amazon-adsystem.com","criteo.com","moatads.com","outbrain.com","taboola.com","bidswitch.net","rubiconproject.com"]),qh={image:"image",font:"font",media:"media",stylesheet:"stylesheet",websocket:"websocket"},ku={functional:{enabled:!0,blockedCategories:["image","font","media","stylesheet","tracking","advertising"]},visual:{enabled:!1,blockedCategories:[]},performance:{enabled:!0,blockedCategories:["image","font","media","tracking","advertising"]}};function Go(u,t,e){if(!e.enabled)return!1;if(e.allowPatterns?.length){for(let i of e.allowPatterns)if(Iu(u,i))return!1}if(e.blockPatterns?.length){for(let i of e.blockPatterns)if(Iu(u,i))return!0}let r=qh[t];return!!(r&&e.blockedCategories.includes(r)||e.blockedCategories.includes("tracking")&&Mu(u,zh)||e.blockedCategories.includes("advertising")&&Mu(u,Bh))}function bi(u){if(typeof u=="object")return u;let t=ku[u];return t?{...t,blockedCategories:[...t.blockedCategories]}:ku.visual}var Du=new Map;function Iu(u,t){let e=Du.get(t);if(!e){let r=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");e=new RegExp(r,"i"),Du.set(t,e)}return e.test(u)}function Mu(u,t){try{let e=new URL(u).hostname;for(let r of t)if(e===r||e.endsWith(`.${r}`))return!0}catch{}return!1}var cs=null,Lu=!1;function $u(){if(Lu)return cs;Lu=!0;try{cs=Fa("patchright")}catch{cs=null}return cs}var mt=class{tool="stealth";stealthConfig;page=null;context=null;browser=null;sessionId=null;constructor(t){this.stealthConfig={...os,...t}}async isAvailable(){return $u()!==null}async launch(t){let e=$u();if(!e)return{success:!1,error:new te("stealth","Patchright is not installed. Install with: npm install patchright")};try{let r={headless:t?.headless??!0};if(t?.viewport&&(r.viewport=t.viewport),t?.args&&(r.args=t.args),this.stealthConfig.userAgent&&(r.userAgent=this.stealthConfig.userAgent),this.stealthConfig.proxy&&(r.proxy=this.stealthConfig.proxy),this.stealthConfig.persistentContext){let i=this.stealthConfig.userDataDir||`/tmp/stealth-browser-${Fu()}`;this.context=await e.chromium.launchPersistentContext(i,r);let n=this.context.pages();this.page=n.length>0?n[0]:await this.context.newPage()}else this.browser=await e.chromium.launch(r),this.page=await this.browser.newPage();return await this.applyResourceBlocking(),this.sessionId=Fu(),{success:!0,value:{id:this.sessionId,tool:"stealth",status:"active",createdAt:new Date}}}catch(r){return{success:!1,error:new F(`Failed to launch stealth browser: ${r instanceof Error?r.message:String(r)}`,"LAUNCH_FAILED","stealth",r instanceof Error?r:void 0)}}}async quit(){try{return this.context&&(await this.context.close(),this.context=null),this.browser&&(await this.browser.close(),this.browser=null),this.page=null,this.sessionId=null,{success:!0,value:void 0}}catch(t){return{success:!1,error:new F("Failed to quit stealth browser","QUIT_FAILED","stealth",t instanceof Error?t:void 0)}}}async navigate(t){if(!this.page)return this.notLaunched();try{let e=Date.now(),i=(await this.page.goto(t,{waitUntil:"domcontentloaded"}))?.status()??void 0;this.stealthConfig.cloudflareWaitSeconds>0&&await this.waitForCloudflare();let n=await this.page.title();return{success:!0,value:{url:this.page.url(),title:n,success:!0,durationMs:Date.now()-e,statusCode:i??void 0}}}catch(e){return this.wrapError("navigate",e)}}async reload(){if(!this.page)return this.notLaunched();try{return await this.page.reload(),{success:!0,value:void 0}}catch(t){return this.wrapError("reload",t)}}async goBack(){if(!this.page)return this.notLaunched();try{return await this.page.goBack(),{success:!0,value:void 0}}catch(t){return this.wrapError("goBack",t)}}async goForward(){if(!this.page)return this.notLaunched();try{return await this.page.goForward(),{success:!0,value:void 0}}catch(t){return this.wrapError("goForward",t)}}async click(t){if(!this.page)return this.notLaunched();try{let e=this.resolveSelector(t);return await this.page.click(e),{success:!0,value:void 0}}catch(e){return this.wrapError("click",e)}}async fill(t,e){if(!this.page)return this.notLaunched();try{let r=this.resolveSelector(t);return await this.page.fill(r,e),{success:!0,value:void 0}}catch(r){return this.wrapError("fill",r)}}async getText(t){if(!this.page)return this.notLaunched();try{let e=this.resolveSelector(t);return{success:!0,value:await this.page.textContent(e)??""}}catch(e){return this.wrapError("getText",e)}}async isVisible(t){if(!this.page)return this.notLaunched();try{let e=this.resolveSelector(t);return{success:!0,value:await this.page.isVisible(e)}}catch(e){return this.wrapError("isVisible",e)}}async screenshot(t){if(!this.page)return this.notLaunched();try{return{success:!0,value:{base64:(await this.page.screenshot({path:t?.path,fullPage:t?.fullPage,type:"png"})).toString("base64"),path:t?.path,format:"png",dimensions:{width:0,height:0}}}}catch(e){return this.wrapError("screenshot",e)}}async evaluate(t){if(!this.page)return this.notLaunched();try{return{success:!0,value:await this.page.evaluate(t)}}catch(e){return this.wrapError("evaluate",e)}}async dispose(){await this.quit()}resolveSelector(t){if(typeof t=="string")return t;switch(t.type){case"css":return t.value;case"xpath":return`xpath=${t.value}`;case"text":return`text=${t.value}`;case"ref":return t.value;default:return t.value}}async applyResourceBlocking(){if(!this.page||!this.stealthConfig.resourceBlocking)return;let t=typeof this.stealthConfig.resourceBlocking=="string"?bi(this.stealthConfig.resourceBlocking):this.stealthConfig.resourceBlocking;t.enabled&&await this.page.route("**/*",e=>{let r=e.request().url(),i=e.request().resourceType();Go(r,i,t)?e.abort().catch(()=>{}):e.continue().catch(()=>{})})}async waitForCloudflare(){if(!this.page||this.stealthConfig.cloudflareWaitSeconds<=0)return;let t=this.stealthConfig.cloudflareWaitSeconds*1e3,e=Date.now();for(;Date.now()-e<t;){try{let r=await this.page.title();if(!r.includes("Just a moment")&&!r.includes("Checking your browser"))return}catch{}await new Promise(r=>setTimeout(r,500))}}notLaunched(){return{success:!1,error:new F("Stealth browser not launched. Call launch() first.","NOT_LAUNCHED","stealth")}}wrapError(t,e){return{success:!1,error:new F(`Stealth ${t} failed: ${e instanceof Error?e.message:String(e)}`,"OPERATION_FAILED","stealth",e instanceof Error?e:void 0)}}};async function Ho(){return!1}async function Wo(){try{return await new cr().isAvailable()}catch{return!1}}var Gh=["e2e-testing","api-mocking","responsive-testing","auth-testing"],Hh=["stealth-testing"];function jh(u){return Gh.includes(u)}var ls=class{tool="vibium";async isAvailable(){return!1}async launch(){return{success:!1,error:new te("vibium","Vibium client not yet implemented")}}async quit(){return{success:!1,error:new te("vibium","Vibium client not yet implemented")}}async navigate(){return{success:!1,error:new te("vibium","Vibium client not yet implemented")}}async reload(){return{success:!1,error:new te("vibium","Vibium client not yet implemented")}}async goBack(){return{success:!1,error:new te("vibium","Vibium client not yet implemented")}}async goForward(){return{success:!1,error:new te("vibium","Vibium client not yet implemented")}}async click(){return{success:!1,error:new te("vibium","Vibium client not yet implemented")}}async fill(){return{success:!1,error:new te("vibium","Vibium client not yet implemented")}}async getText(){return{success:!1,error:new te("vibium","Vibium client not yet implemented")}}async isVisible(){return{success:!1,error:new te("vibium","Vibium client not yet implemented")}}async screenshot(){return{success:!1,error:new te("vibium","Vibium client not yet implemented")}}async evaluate(){return{success:!1,error:new te("vibium","Vibium client not yet implemented")}}async dispose(){}};async function Uo(u={}){let{preference:t="auto",useCase:e}=u;if(e&&Hh.includes(e)&&await jo())return new mt;if(e&&jh(e)||t==="agent-browser")return wi();if(t==="stealth"){if(await jo())return new mt;throw new te("stealth","Patchright is not installed")}if(t==="vibium"){if(await Ho())return new ls;throw new te("vibium","Vibium is not available")}return await Ho()?new ls:(await Wo(),wi())}async function wi(){return new cr}async function us(u){return Uo({useCase:u})}async function jo(){try{return await new mt().isAvailable()}catch{return!1}}import{exec as Uh,execSync as jA}from"child_process";import{promisify as Qh}from"util";A();H();var JA=Qh(Uh);A();var Ou={enabled:!0,similarityThreshold:.6,maxFingerprintsPerPage:200,namespace:"aqe/adaptive-locators",fallbackChain:["text","aria","fingerprint"]};function Kh(u){return`
|
|
2309
2309
|
(() => {
|
|
2310
2310
|
const el = document.querySelector(${JSON.stringify(u)});
|
|
2311
2311
|
if (!el) return null;
|
|
@@ -2611,7 +2611,7 @@ describe('${e} Integration', () => {
|
|
|
2611
2611
|
.rejects.toThrow('Unrecoverable');
|
|
2612
2612
|
});
|
|
2613
2613
|
});
|
|
2614
|
-
});`}};A();var ag=[{name:"uncovered-lines",weight:.25},{name:"complexity",weight:.2},{name:"defect-history",weight:.2},{name:"change-frequency",weight:.15},{name:"code-age",weight:.1},{name:"dependency-count",weight:.1}],ur=class u{constructor(t){this.memory=t}memory;static HISTORY_KEY_PREFIX="risk-history";static MAX_TREND_POINTS=30;async calculateRisk(t){try{let{file:e,uncoveredLines:r,factors:i=ag}=t,n=this.normalizeFactorWeights(i),s=await this.calculateFactorScores(e,r,n),a=s.reduce((l,d)=>l+d.score*d.contribution,0),o=this.riskScoreToSeverity(a),c=this.generateRiskRecommendations(e,a,o,s);return await this.storeRiskSnapshot(e,a,s),f({file:e,overallRisk:a,riskLevel:o,factors:s,recommendations:c})}catch(e){return p(y(e))}}async factorInHistory(t,e){try{let r=await this.getDefectHistory(t),i=Math.min(1,r.count/10)*.3,n=await this.getChangeFrequency(t),s=Math.min(1,n/20)*.2,a=await this.getRiskTrend(t),o=0;if(a.success){let l=a.value;l.trend==="increasing"?o=.15:l.trend==="decreasing"&&(o=-.1)}let c=e+i+s+o;return Math.min(1,Math.max(0,c))}catch{return e}}async getRiskTrend(t){try{let e=`${u.HISTORY_KEY_PREFIX}:${t}`,r=await this.memory.get(e);if(!r||r.length===0)return f({file:t,dataPoints:[],trend:"stable",forecast:.5});let i=r.slice(-u.MAX_TREND_POINTS).map(a=>({date:new Date(a.timestamp),riskScore:a.riskScore,factors:a.topFactors})),n=this.analyzeTrend(i),s=this.forecastRisk(i);return f({file:t,dataPoints:i,trend:n,forecast:s})}catch(e){return p(y(e))}}normalizeFactorWeights(t){let e=t.reduce((r,i)=>r+i.weight,0);return e===0?t:t.map(r=>({...r,weight:r.weight/e}))}async calculateFactorScores(t,e,r){let i=[];for(let n of r){let s=await this.calculateSingleFactorScore(n.name,t,e);i.push({name:n.name,score:s,contribution:n.weight})}return i}async calculateSingleFactorScore(t,e,r){switch(t){case"uncovered-lines":return this.calculateUncoveredLinesScore(r);case"complexity":return await this.calculateComplexityScore(e);case"defect-history":return await this.calculateDefectHistoryScore(e);case"change-frequency":return await this.calculateChangeFrequencyScore(e);case"code-age":return await this.calculateCodeAgeScore(e);case"dependency-count":return await this.calculateDependencyScore(e);default:return .5}}calculateUncoveredLinesScore(t){let e=t.length;return e===0?0:e<=5?.2:e<=15?.4:e<=30?.6:e<=50?.8:1}async calculateComplexityScore(t){try{let e=await this.memory.get(`complexity:${t}`);if(!e)return .5;let r=e.cyclomatic;return r<=5?.2:r<=10?.4:r<=20?.6:r<=30?.8:1}catch{return .5}}async calculateDefectHistoryScore(t){let r=(await this.getDefectHistory(t)).count;return r===0?.1:r<=2?.3:r<=5?.5:r<=10?.7:.9}async calculateChangeFrequencyScore(t){let e=await this.getChangeFrequency(t);return e<=2?.2:e<=5?.4:e<=10?.6:e<=20?.8:1}async calculateCodeAgeScore(t){try{let e=await this.memory.get(`file-metadata:${t}`);if(!e)return .5;let r=(Date.now()-new Date(e.createdAt).getTime())/(1e3*60*60*24);return r<=7?.8:r<=30?.5:r<=90?.3:r<=365?.4:.6}catch{return .5}}async calculateDependencyScore(t){try{let e=await this.memory.get(`dependencies:${t}`);if(!e)return .5;let r=e.count;return r<=3?.2:r<=7?.4:r<=15?.6:r<=25?.8:1}catch{return .5}}async getDefectHistory(t){try{return{count:(await this.memory.get(`defect-history:${t}`))?.defectCount??0}}catch{return{count:0}}}async getChangeFrequency(t){try{return(await this.memory.get(`change-frequency:${t}`))?.changesLast90Days??5}catch{return 5}}riskScoreToSeverity(t){return t>=.8?"critical":t>=.6?"high":t>=.3?"medium":t>=.1?"low":"info"}generateRiskRecommendations(t,e,r,i){let n=[],a=[...i].sort((o,c)=>c.score*c.contribution-o.score*o.contribution).slice(0,3);r==="critical"?n.push(`CRITICAL: ${t} has a risk score of ${(e*100).toFixed(1)}%. Immediate action required.`):r==="high"&&n.push(`HIGH RISK: ${t} should be prioritized for test coverage improvement.`);for(let o of a)o.score>=.6&&n.push(this.getFactorRecommendation(o.name,o.score));return e>=.5&&n.push("Consider breaking this file into smaller, more testable modules."),i.find(o=>o.name==="defect-history"&&o.score>=.5)&&n.push("This file has a history of defects. Add regression tests for known issues."),n}getFactorRecommendation(t,e){let r=e>=.8?"Critical":"High";switch(t){case"uncovered-lines":return`${r}: Many uncovered lines. Focus on adding unit tests for core logic.`;case"complexity":return`${r}: High complexity detected. Consider refactoring before adding tests.`;case"defect-history":return`${r}: Past defects in this area. Add regression tests to prevent recurrence.`;case"change-frequency":return`${r}: Frequently changed code. Ensure comprehensive test coverage.`;case"code-age":return`${r}: Code age indicates risk. Review and update tests accordingly.`;case"dependency-count":return`${r}: Many dependencies. Add integration tests to verify interactions.`;default:return`${r}: Factor "${t}" indicates elevated risk.`}}async storeRiskSnapshot(t,e,r){try{let i=`${u.HISTORY_KEY_PREFIX}:${t}`,n=await this.memory.get(i)??[],s={timestamp:Date.now(),riskScore:e,topFactors:r.filter(o=>o.score>=.5).map(o=>o.name)},a=[...n,s].slice(-u.MAX_TREND_POINTS);await this.memory.set(i,a,{persist:!0})}catch{}}analyzeTrend(t){if(t.length<3)return"stable";let e=t.length,r=0,i=0,n=0,s=0;for(let o=0;o<e;o++){let c=o,l=t[o].riskScore;r+=c,i+=l,n+=c*l,s+=c*c}let a=(e*n-r*i)/(e*s-r*r);return a>.01?"increasing":a<-.01?"decreasing":"stable"}forecastRisk(t){if(t.length===0)return .5;if(t.length===1)return t[0].riskScore;let e=.3,r=t[0].riskScore;for(let n=1;n<t.length;n++)r=e*t[n].riskScore+(1-e)*r;let i=this.analyzeTrend(t);return i==="increasing"?r=Math.min(1,r+.05):i==="decreasing"&&(r=Math.max(0,r-.05)),r}};var ac={dimensions:384,includePathFeatures:!0,includeTemporalFeatures:!0,normalization:"l2"},Ci=class{config;constructor(t={}){this.config={...ac,...t}}embedFileCoverage(t){let e=new Array(this.config.dimensions).fill(0),r=0;return r=this.encodeCoverageMetrics(e,t,r),r=this.encodeGapCharacteristics(e,t,r),r=this.encodeRiskFactors(e,t,r),r=this.encodeFileCharacteristics(e,t,r),this.encodeDerivedFeatures(e,t,r),{vector:this.normalize(e),metadata:this.createMetadata(t),confidence:this.calculateConfidence(t)}}embedCoverageGap(t){let e=new Array(this.config.dimensions).fill(0);e[0]=t.riskScore,e[1]=Math.min(1,t.lines.length/100),e[2]=Math.min(1,t.branches.length/20),e[3]=this.severityToNumber(t.severity)/4;let r=this.extractPathFeatures(t.file);if(e[4]=r.depth/10,e[5]=r.hashNormalized,t.lines.length>1){let n=t.lines[t.lines.length-1]-t.lines[0];e[6]=Math.min(1,n/500),e[7]=t.lines.length/(n+1)}for(let n=8;n<this.config.dimensions;n++){let s=t.riskScore*n+t.lines.length*.01;e[n]=Math.sin(s)*.5+.5}return{vector:this.normalize(e),metadata:{filePath:t.file,lineCoverage:0,branchCoverage:0,functionCoverage:0,statementCoverage:0,uncoveredLineCount:t.lines.length,uncoveredBranchCount:t.branches.length,riskScore:t.riskScore,lastUpdated:Date.now(),totalLines:t.lines.length>0?t.lines[t.lines.length-1]:0},confidence:.8}}embedQuery(t){let e=new Array(this.config.dimensions).fill(0);if(t.minLineCoverage!==void 0&&(e[0]=t.minLineCoverage/100),t.maxLineCoverage!==void 0&&(e[1]=t.maxLineCoverage/100),t.minBranchCoverage!==void 0&&(e[2]=t.minBranchCoverage/100),t.maxBranchCoverage!==void 0&&(e[3]=t.maxBranchCoverage/100),t.minRiskScore!==void 0&&(e[4]=t.minRiskScore),t.maxRiskScore!==void 0&&(e[5]=t.maxRiskScore),t.filePattern){let r=this.extractPathFeatures(t.filePattern);e[6]=r.depth/10,e[7]=r.hashNormalized}t.maxUncoveredLines!==void 0&&(e[8]=Math.min(1,t.maxUncoveredLines/100));for(let r=9;r<this.config.dimensions;r++)e[r]===0&&(e[r]=.5);return{vector:this.normalize(e),metadata:{filePath:t.filePattern||"",lineCoverage:t.minLineCoverage||0,branchCoverage:t.minBranchCoverage||0,functionCoverage:0,statementCoverage:0,uncoveredLineCount:t.maxUncoveredLines||0,uncoveredBranchCount:0,riskScore:t.minRiskScore||0,lastUpdated:Date.now(),totalLines:0},confidence:.7}}batchEmbed(t){return t.map(e=>this.embedFileCoverage(e))}encodeCoverageMetrics(t,e,r){return t[r++]=e.lines.total>0?e.lines.covered/e.lines.total:0,t[r++]=Math.min(1,e.lines.total/1e3),t[r++]=Math.min(1,e.lines.covered/500),t[r++]=e.lines.total>0?e.uncoveredLines.length/e.lines.total:0,t[r++]=e.branches.total>0?e.branches.covered/e.branches.total:1,t[r++]=Math.min(1,e.branches.total/200),t[r++]=Math.min(1,e.branches.covered/100),t[r++]=e.branches.total>0?e.uncoveredBranches.length/e.branches.total:0,t[r++]=e.functions.total>0?e.functions.covered/e.functions.total:1,t[r++]=Math.min(1,e.functions.total/50),t[r++]=Math.min(1,e.functions.covered/25),t[r++]=e.functions.total>0?1-e.functions.covered/e.functions.total:0,t[r++]=e.statements.total>0?e.statements.covered/e.statements.total:1,t[r++]=Math.min(1,e.statements.total/1e3),t[r++]=Math.min(1,e.statements.covered/500),t[r++]=e.statements.total>0?1-e.statements.covered/e.statements.total:0,r}encodeGapCharacteristics(t,e,r){let i=e.uncoveredLines,n=e.uncoveredBranches;if(t[r++]=Math.min(1,i.length/100),t[r++]=Math.min(1,n.length/50),t[r++]=Math.min(1,(i.length+n.length)/150),t[r++]=i.length>0?1:0,i.length>1){let s=[...i].sort((l,d)=>l-d),a=s[s.length-1]-s[0],o=i.length/(a+1);t[r++]=Math.min(1,a/500),t[r++]=Math.min(1,o);let c=this.countContiguousRegions(s);t[r++]=Math.min(1,c/10),t[r++]=c>0?i.length/c:0}else t[r++]=0,t[r++]=i.length>0?1:0,t[r++]=i.length>0?.1:0,t[r++]=i.length;if(i.length>0&&e.lines.total>0){let s=Math.min(...i),a=Math.max(...i);t[r++]=s/e.lines.total,t[r++]=a/e.lines.total,t[r++]=(a-s)/e.lines.total,t[r++]=i.filter(o=>o<=e.lines.total*.2).length/i.length}else r+=4;return r+=4,r}encodeRiskFactors(t,e,r){let i=this.calculateOverallCoverage(e);t[r++]=1-i,t[r++]=e.branches.total>0?1-e.branches.covered/e.branches.total:0,t[r++]=e.functions.total>0?1-e.functions.covered/e.functions.total:0,t[r++]=Math.min(1,e.uncoveredLines.length/50),t[r++]=Math.min(1,e.lines.total/500),t[r++]=Math.min(1,e.functions.total/30),t[r++]=Math.min(1,e.branches.total/100),t[r++]=e.lines.total>300?.8:e.lines.total/375;let n=this.calculateLargeGapRatio(e.uncoveredLines);return t[r++]=n,t[r++]=e.uncoveredBranches.length>10?1:e.uncoveredBranches.length/10,t[r++]=e.uncoveredLines.length>30?1:e.uncoveredLines.length/30,t[r++]=this.calculateGapConcentration(e),r+=4,r}encodeFileCharacteristics(t,e,r){let i=this.extractPathFeatures(e.path);return t[r++]=i.depth/10,t[r++]=i.hashNormalized,t[r++]=i.isTest?.1:.9,t[r++]=i.isConfig?.2:.8,t[r++]=i.extension==="ts"?1:0,t[r++]=i.extension==="js"?1:0,t[r++]=i.extension==="tsx"||i.extension==="jsx"?1:0,t[r++]=i.isIndex?.5:0,t[r++]=i.inSrc?1:0,t[r++]=i.inLib?.8:0,t[r++]=i.inDomains?1:0,t[r++]=i.inServices?.9:0,r+=4,r}encodeDerivedFeatures(t,e,r){let i=[e.lines.covered/(e.lines.total||1),e.branches.covered/(e.branches.total||1),e.functions.covered/(e.functions.total||1),e.statements.covered/(e.statements.total||1),e.uncoveredLines.length/(e.lines.total||1),e.uncoveredBranches.length/(e.branches.total||1)];for(let n=0;n<6;n++)for(let s=n+1;s<6&&r<this.config.dimensions;s++)t[r++]=(i[n]+i[s])/2,r<this.config.dimensions&&(t[r++]=Math.abs(i[n]-i[s]));for(;r<this.config.dimensions-6;){let n=(r-64)%i.length;t[r++]=i[n]*i[n],r<this.config.dimensions&&(t[r++]=Math.sqrt(i[n]))}for(;r<this.config.dimensions;){let n=(r-64)*.1,s=i[(r-64)%i.length];t[r++]=Math.sin(s*Math.PI+n)*.5+.5}}normalize(t){switch(this.config.normalization){case"l2":return this.l2Normalize(t);case"minmax":return this.minMaxNormalize(t);default:return t}}l2Normalize(t){let e=Math.sqrt(t.reduce((r,i)=>r+i*i,0));return e===0?t:t.map(r=>r/e)}minMaxNormalize(t){let e=Math.min(...t),i=Math.max(...t)-e;return i===0?t.map(()=>.5):t.map(n=>(n-e)/i)}createMetadata(t){return{filePath:t.path,lineCoverage:t.lines.total>0?t.lines.covered/t.lines.total*100:0,branchCoverage:t.branches.total>0?t.branches.covered/t.branches.total*100:0,functionCoverage:t.functions.total>0?t.functions.covered/t.functions.total*100:0,statementCoverage:t.statements.total>0?t.statements.covered/t.statements.total*100:0,uncoveredLineCount:t.uncoveredLines.length,uncoveredBranchCount:t.uncoveredBranches.length,riskScore:this.calculateRiskScore(t),lastUpdated:Date.now(),totalLines:t.lines.total}}calculateConfidence(t){let e=t.lines.total>0,r=t.branches.total>0,i=t.functions.total>0,n=t.statements.total>0,s=.5;return e&&(s+=.2),r&&(s+=.1),i&&(s+=.1),n&&(s+=.1),Math.min(1,s)}calculateOverallCoverage(t){let e=t.lines.total>0?t.lines.covered/t.lines.total:1,r=t.branches.total>0?t.branches.covered/t.branches.total:1,i=t.functions.total>0?t.functions.covered/t.functions.total:1,n=t.statements.total>0?t.statements.covered/t.statements.total:1;return(e+r+i+n)/4}calculateRiskScore(t){let e=t.lines.total>0?1-t.lines.covered/t.lines.total:0,r=t.branches.total>0?1-t.branches.covered/t.branches.total:0,i=t.functions.total>0?1-t.functions.covered/t.functions.total:0;return Math.min(1,e*.3+r*.4+i*.3)}countContiguousRegions(t){if(t.length===0)return 0;let e=1;for(let r=1;r<t.length;r++)t[r]-t[r-1]>3&&e++;return e}calculateLargeGapRatio(t){if(t.length===0)return 0;let e=[...t].sort((s,a)=>s-a),r=0,i=1;for(let s=1;s<e.length;s++)e[s]-e[s-1]<=3?i++:(i>10&&r++,i=1);i>10&&r++;let n=this.countContiguousRegions(e);return n>0?r/n:0}calculateGapConcentration(t){if(t.uncoveredLines.length===0||t.lines.total===0)return 0;let e=this.countContiguousRegions([...t.uncoveredLines].sort((i,n)=>i-n)),r=Math.ceil(t.uncoveredLines.length/5);return e>0?Math.min(1,r/e):0}extractPathFeatures(t){let e=t.split("/").filter(Boolean),r=t.split(".").pop()||"",i=e[e.length-1]||"";return{depth:e.length,extension:r,hashNormalized:this.hashString(t)/1e6,isTest:/\.(test|spec)\.(ts|js|tsx|jsx)$/.test(t)||e.includes("tests")||e.includes("__tests__"),isConfig:/\.(config|rc)\.(ts|js|json|yaml|yml)$/.test(t),isIndex:i.startsWith("index."),inSrc:e.includes("src"),inLib:e.includes("lib"),inDomains:e.includes("domains"),inServices:e.includes("services")}}hashString(t){let e=0;for(let r=0;r<t.length;r++){let i=t.charCodeAt(r);e=(e<<5)-e+i|0}return Math.abs(e)}severityToNumber(t){switch(t){case"critical":return 4;case"high":return 3;case"medium":return 2;case"low":return 1;default:return 0}}};function Si(u){return new Ci(u)}M();A();var HP=R.create("coverage-analysis/sublinear-analyzer");Zi();A();var Ri=["missing-error-handler","absent-boundary-validation","unprotected-state-transition","missing-integration-contract","absent-edge-case","missing-security-check"],og={dimensions:384,minConfidence:.3,maxGaps:50,riskWeight:.6,distanceWeight:.4,namespace:"ghost-surface",idealSurfaceDecay:.95},Ti=class u{config;hnswIndex;embedder;idealSurfacePatterns=[];cachedIdealSurface=null;cachedPhantomRatio=1;initialized=!1;constructor(t,e={}){this.config={...og,...e},this.hnswIndex=t.hnswIndex,this.embedder=t.embedder}async initialize(){try{return this.idealSurfacePatterns=this.buildBaselinePatterns(),this.cachedIdealSurface=this.aggregateIdealSurface(),this.initialized=!0,f(void 0)}catch(t){return p(y(t))}}async computePhantomSurface(t,e){try{this.ensureInitialized();let r=this.buildIdealSurface(e),i=new Map,n=[];for(let o of t.files){let c=this.embedder.embedFileCoverage(o).vector;n.push(c),i.set(o.path,this.computeGhostVector(c,r)),await this.hnswIndex.insert(`${this.config.namespace}:${o.path}`,i.get(o.path),{filePath:o.path,lineCoverage:this.ratio(o.lines.covered,o.lines.total)*100,branchCoverage:this.ratio(o.branches.covered,o.branches.total)*100,functionCoverage:this.ratio(o.functions.covered,o.functions.total)*100,statementCoverage:this.ratio(o.statements.covered,o.statements.total)*100,uncoveredLineCount:o.uncoveredLines.length,uncoveredBranchCount:o.uncoveredBranches.length,riskScore:this.fileRiskScore(o),lastUpdated:Date.now(),totalLines:o.lines.total})}let s=this.aggregateSurface(n),a=this.phantomRatioFromVectors(r,s);return this.cachedIdealSurface=r,this.cachedPhantomRatio=a,f({ghostVectors:i,idealSurface:r,actualSurface:s,phantomRatio:a,computedAt:Date.now(),filesAnalyzed:t.files.length})}catch(r){return p(y(r))}}async detectPhantomGaps(t,e){try{this.ensureInitialized();let r=e??this.config.minConfidence,i=[];for(let[n,s]of t.ghostVectors){if(Xi(s)<.01)continue;let a=await this.hnswIndex.search(s,5),o=this.getApplicableCategories(n);for(let c of this.classifyGhost(s,a)){if(c.confidence<r||!o.has(c.category))continue;let l=this.gapRiskScore(s,c.category),d=Math.min(1,Xi(s));i.push({id:this.gapId(n,c.category),file:n,category:c.category,ghostDistance:d,riskScore:l,severity:this.toSeverity(d,l),confidence:c.confidence,description:this.gapDescription(n,c.category,d),suggestedLines:c.suggestedLines})}}return i.sort((n,s)=>s.ghostDistance*s.riskScore-n.ghostDistance*n.riskScore),f(i.slice(0,this.config.maxGaps))}catch(r){return p(y(r))}}rankPhantomGaps(t){let{riskWeight:e,distanceWeight:r}=this.config;return[...t].sort((i,n)=>e*n.riskScore+r*n.ghostDistance-(e*i.riskScore+r*i.ghostDistance))}async updateIdealSurface(t){try{this.ensureInitialized();for(let e of this.idealSurfacePatterns)e.weight*=this.config.idealSurfaceDecay;for(let e of t){if(e.vector.length!==this.config.dimensions)continue;let r=this.idealSurfacePatterns.findIndex(i=>i.id===e.id);r>=0?this.idealSurfacePatterns[r]=e:this.idealSurfacePatterns.push(e)}return this.idealSurfacePatterns=this.idealSurfacePatterns.filter(e=>e.weight>.01),this.cachedIdealSurface=this.aggregateIdealSurface(),f(this.idealSurfacePatterns.length)}catch(e){return p(y(e))}}getPhantomRatio(){return this.cachedPhantomRatio}computeGhostVector(t,e){let r=Math.min(t.length,e.length),i=new Array(r);for(let n=0;n<r;n++)i[n]=Math.max(0,e[n]-t[n]);return wt(i)}buildBaselinePatterns(){let t=this.config.dimensions,e=Math.floor(t/Ri.length);return Ri.map((r,i)=>{let n=new Array(t).fill(0),s=i*e,a=Math.min(s+e,t);for(let o=s;o<a;o++)n[o]=Math.sin((o-s)/e*Math.PI)*.8+.2;return n[0]=.9,n[1]=.85,n[2]=.9,n[3]=.85,{id:`baseline-${r}`,category:r,vector:wt(n),weight:1,source:"baseline"}})}buildIdealSurface(t){let e=this.aggregateIdealSurface();if(t.riskAreas?.length)for(let r=32;r<48&&r<e.length;r++)e[r]*=1.2;if(t.defectHistory?.length){let r=Math.min(1.5,1+t.defectHistory.length*.05);for(let i=0;i<16&&i<e.length;i++)e[i]*=r}return wt(e)}aggregateIdealSurface(){let t=this.config.dimensions;if(this.idealSurfacePatterns.length===0)return wt(new Array(t).fill(1));let e=new Array(t).fill(0),r=0;for(let i of this.idealSurfacePatterns){for(let n=0;n<t;n++)e[n]+=i.vector[n]*i.weight;r+=i.weight}if(r>0)for(let i=0;i<t;i++)e[i]/=r;return wt(e)}aggregateSurface(t){let e=this.config.dimensions;if(t.length===0)return new Array(e).fill(0);let r=new Array(e).fill(0);for(let i of t)for(let n=0;n<e&&n<i.length;n++)r[n]+=i[n];for(let i=0;i<e;i++)r[i]/=t.length;return wt(r)}classifyGhost(t,e){let r=this.config.dimensions,i=Math.floor(r/Ri.length),n=[],s=0;for(let a of e)a.score>.7&&(s+=a.score*.1);for(let a=0;a<Ri.length;a++){let o=a*i,c=Math.min(o+i,r),l=0;for(let m=o;m<c&&m<t.length;m++)l+=t[m]**2;l=Math.sqrt(l/(c-o));let d=Math.min(1,l+s);d>.05&&n.push({category:Ri[a],confidence:d,suggestedLines:this.suggestLines(a,t)})}return n.sort((a,o)=>o.confidence-a.confidence)}suggestLines(t,e){let r=e[0]||0,i=e[2]||0;if(r<.1&&i<.1)return[];let n=t*20+1,s=Math.ceil(r*10),a=[];for(let o=0;o<s&&a.length<10;o++)a.push(n+o*5);return a}getApplicableCategories(t){let e=t.toLowerCase(),r=e.split("/").pop()||e,i=new Set(["missing-error-handler","absent-edge-case"]);return/\b(math|calc|util|helper|format|parse|convert|transform)\b/.test(r)?(i.add("absent-boundary-validation"),i):(i.add("absent-boundary-validation"),/\b(auth|security|token|credential|password|session|permission|rbac|acl|encrypt|crypto)\b/.test(e)&&i.add("missing-security-check"),/\b(service|controller|handler|router|middleware|api|endpoint|gateway|adapter)\b/.test(e)&&(i.add("missing-integration-contract"),i.add("unprotected-state-transition")),/\b(state|store|reducer|saga|machine|workflow|queue|scheduler)\b/.test(e)&&i.add("unprotected-state-transition"),i)}static CATEGORY_RISK={"missing-security-check":1.5,"missing-error-handler":1.3,"unprotected-state-transition":1.2,"missing-integration-contract":1.1,"absent-boundary-validation":1,"absent-edge-case":.8};gapRiskScore(t,e){return Math.min(1,Xi(t)*(u.CATEGORY_RISK[e]??1))}fileRiskScore(t){return Math.min(1,(1-this.ratio(t.lines.covered,t.lines.total))*.3+(1-this.ratio(t.branches.covered,t.branches.total))*.4+(1-this.ratio(t.functions.covered,t.functions.total))*.3)}phantomRatioFromVectors(t,e){return!t.length||!e.length?1:Math.max(0,Math.min(1,1-tt(t,e)))}toSeverity(t,e){let r=(t+e)/2;return r>=.8?"critical":r>=.6?"high":r>=.3?"medium":"low"}ensureInitialized(){if(!this.initialized)throw new Error("GhostCoverageAnalyzerService not initialized. Call initialize() first.")}ratio(t,e){return e>0?t/e:0}gapId(t,e){let r=`${t}:${e}`.split("").reduce((i,n)=>(i<<5)-i+n.charCodeAt(0)|0,0);return`phantom-${Math.abs(r).toString(16)}`}gapDescription(t,e,r){let i=t.split("/").pop()||t,n=r>.7?"significant":r>.4?"moderate":"minor";return{"missing-error-handler":`${i}: ${n} missing error handler tests. Cover error paths and failure recovery.`,"absent-boundary-validation":`${i}: ${n} missing boundary validation tests. Cover input bounds and null checks.`,"unprotected-state-transition":`${i}: ${n} missing state transition tests. Cover state changes and race conditions.`,"missing-integration-contract":`${i}: ${n} missing integration contract tests. Cover external API boundaries.`,"absent-edge-case":`${i}: ${n} missing edge case tests. Cover empty inputs, max values, and timeouts.`,"missing-security-check":`${i}: ${n} missing security check tests. Cover auth bypass and injection attacks.`}[e]}};se();var _=class{forward(t){return Math.max(0,t)}backward(t){return t>0?1:0}};var B=class{forward(t){return t}backward(t){return 1}},he=class u{static forward(t){let e=Math.max(...t),r=t.map(n=>Math.exp(n-e)),i=r.reduce((n,s)=>n+s,0);return new Float32Array(r.map(n=>n/i))}static backward(t,e){let r=u.forward(t),i=new Float32Array(t.length);for(let n=0;n<t.length;n++)i[n]=r[n]-e[n];return i}},fe=class{forward(t,e){let r=e instanceof Float32Array?e:new Float32Array(e),i=0;for(let n=0;n<t.length;n++){let s=t[n]-r[n];i+=s*s}return i/t.length}backward(t,e){let r=e instanceof Float32Array?e:new Float32Array(e),i=new Float32Array(t.length),n=t.length;for(let s=0;s<n;s++)i[s]=2*(t[s]-r[s])/n;return i}};var vs=class{weights;biases;weightGradients;biasGradients;activation;inputSize;outputSize;lastInput=null;lastPreActivation=null;lastOutput=null;constructor(t){this.inputSize=t.inputSize,this.outputSize=t.outputSize,this.activation=t.activation;let e=Math.sqrt(2/(this.inputSize+this.outputSize));this.weights=new Float32Array(this.inputSize*this.outputSize),this.biases=new Float32Array(this.outputSize),this.weightGradients=new Float32Array(this.inputSize*this.outputSize),this.biasGradients=new Float32Array(this.outputSize);for(let r=0;r<this.weights.length;r++)this.weights[r]=(L()*2-1)*e;for(let r=0;r<this.biases.length;r++)this.biases[r]=0}forward(t){this.lastInput=t;let e=new Float32Array(this.outputSize),r=new Float32Array(this.outputSize);for(let i=0;i<this.outputSize;i++){let n=this.biases[i];for(let s=0;s<this.inputSize;s++)n+=t[s]*this.weights[i*this.inputSize+s];r[i]=n,e[i]=this.activation.forward(n)}return this.lastPreActivation=r,this.lastOutput=e,e}backward(t){if(!this.lastInput||!this.lastPreActivation)throw new Error("Must call forward before backward");let e=new Float32Array(this.outputSize);for(let i=0;i<this.outputSize;i++)e[i]=this.activation.backward(this.lastPreActivation[i])*t[i];for(let i=0;i<this.outputSize;i++){for(let n=0;n<this.inputSize;n++)this.weightGradients[i*this.inputSize+n]+=e[i]*this.lastInput[n];this.biasGradients[i]+=e[i]}let r=new Float32Array(this.inputSize);for(let i=0;i<this.inputSize;i++)for(let n=0;n<this.outputSize;n++)r[i]+=e[n]*this.weights[n*this.inputSize+i];return r}update(t){for(let e=0;e<this.weights.length;e++)this.weights[e]-=t*this.weightGradients[e],this.weightGradients[e]=0;for(let e=0;e<this.biases.length;e++)this.biases[e]-=t*this.biasGradients[e],this.biasGradients[e]=0}getParameters(){return{weights:Array.from(this.weights),biases:Array.from(this.biases)}}setParameters(t){this.weights=new Float32Array(t.weights),this.biases=new Float32Array(t.biases),this.weightGradients=new Float32Array(this.weights.length),this.biasGradients=new Float32Array(this.biases.length)}},q=class u{layers=[];learningRate;constructor(t){this.learningRate=t.learningRate||.001;for(let e=0;e<t.layerSizes.length-1;e++){let r=new vs({inputSize:t.layerSizes[e],outputSize:t.layerSizes[e+1],activation:t.activations[e]||new _});this.layers.push(r)}}forward(t){let e=t instanceof Float32Array?t:new Float32Array(t);for(let r of this.layers)e=r.forward(e);return e}backward(t){let e=t;for(let r=this.layers.length-1;r>=0;r--)e=this.layers[r].backward(e)}train(t,e,r){let i=this.forward(t),n=e instanceof Float32Array?e:new Float32Array(e),s=r.forward(i,n),a=r.backward(i,n);this.backward(a);for(let o of this.layers)o.update(this.learningRate);return s}trainBatch(t,e,r){let i=0;for(let n of this.layers)n.weightGradients.fill(0),n.biasGradients.fill(0);for(let n=0;n<t.length;n++){let s=t[n]instanceof Float32Array?t[n]:new Float32Array(t[n]),a=e[n]instanceof Float32Array?e[n]:new Float32Array(e[n]),o=this.forward(s),c=r.forward(o,a);i+=c;let l=r.backward(o,a);this.backward(l)}for(let n of this.layers){for(let s=0;s<n.weightGradients.length;s++)n.weightGradients[s]/=t.length;for(let s=0;s<n.biasGradients.length;s++)n.biasGradients[s]/=t.length;n.update(this.learningRate)}return i/t.length}getParameters(){return{layers:this.layers.map(t=>t.getParameters())}}setParameters(t){for(let e=0;e<this.layers.length&&e<t.layers.length;e++)this.layers[e].setParameters(t.layers[e])}clone(){let t=new u({layerSizes:[this.layers[0].inputSize,...this.layers.map(e=>e.outputSize)],activations:this.layers.map(e=>e.activation),learningRate:this.learningRate});return t.setParameters(this.getParameters()),t}softUpdate(t,e){for(let r=0;r<this.layers.length;r++){let i=this.layers[r],n=t.layers[r];for(let s=0;s<i.weights.length;s++)i.weights[s]=e*n.weights[s]+(1-e)*i.weights[s];for(let s=0;s<i.biases.length;s++)i.biases[s]=e*n.biases[s]+(1-e)*i.biases[s]}}};se();var Je=class{buffer=[];maxSize;priorities=null;usePrioritized;alpha=.6;beta=.4;betaIncrement=.001;epsilon=1e-6;constructor(t,e=!1){this.maxSize=t,this.usePrioritized=e,e&&(this.priorities=new Float32Array(t),this.priorities.fill(1))}add(t){this.buffer.length>=this.maxSize&&(this.buffer.shift(),this.priorities&&(this.priorities.set(this.priorities.slice(1)),this.priorities[this.maxSize-1]=1)),this.buffer.push(t)}addBatch(t){for(let e of t)this.add(e)}sample(t){if(this.buffer.length===0)return[];if(this.usePrioritized&&this.priorities)return this.samplePrioritized(t);let e=[],r=new Set;for(;r.size<Math.min(t,this.buffer.length);)r.add(ue(0,this.buffer.length));for(let i of r)e.push(this.buffer[i]);return e}samplePrioritized(t){let e=this.getPriorities(),r=[],i=[];for(let n=0;n<Math.min(t,this.buffer.length);n++){let s=L()*e.reduce((o,c)=>o+c,0),a=0;for(let o=0;o<e.length;o++)if(a+=e[o],s<=a){r.push(o);break}}for(let n of r)n<this.buffer.length&&i.push(this.buffer[n]);return this.beta=Math.min(1,this.beta+this.betaIncrement),i}getPriorities(){if(!this.priorities)return[];let t=[],e=this.priorities.reduce((r,i)=>r+Math.pow(i,this.alpha),0);for(let r=0;r<this.buffer.length;r++)t.push(Math.pow(this.priorities[r],this.alpha)/e);return t}updatePriorities(t,e){if(!(!this.priorities||!this.usePrioritized))for(let r=0;r<t.length;r++){let i=t[r],n=e[r];i<this.priorities.length&&(this.priorities[i]=Math.abs(n)+this.epsilon)}}getImportanceWeights(t){if(!this.usePrioritized||!this.priorities)return new Array(t.length).fill(1);let e=[],r=this.getPriorities(),i=this.getMaxImportanceWeight();for(let n of t)if(n<r.length&&r[n]>0){let s=Math.pow(this.buffer.length*r[n],-this.beta);e.push(s/i)}else e.push(1);return e}getMaxImportanceWeight(){if(!this.usePrioritized||!this.priorities)return 1;let t=this.getPriorities(),e=0;for(let r of t)if(r>0){let i=Math.pow(this.buffer.length*r,-this.beta);e=Math.max(e,i)}return e}size(){return this.buffer.length}isReady(t){return this.buffer.length>=t}clear(){this.buffer=[],this.priorities&&this.priorities.fill(1)}getAll(){return[...this.buffer]}getStats(){return{size:this.buffer.length,maxSize:this.maxSize,utilization:this.buffer.length/this.maxSize,usePrioritized:this.usePrioritized}}};var pg={stateSize:10,actionSize:4,hiddenLayers:[128,128],targetUpdateFreq:100,minReplaySize:100,doubleDQN:!0,maxGradNorm:1},bs=class extends oe{qNetwork;targetNetwork;replayBufferClass;qConfig;updateCount=0;actions=[];constructor(t={},e=fu){super("q-learning","value-based",{},e),this.qConfig={...pg,...t},this.qNetwork=new q({layerSizes:[this.qConfig.stateSize,...this.qConfig.hiddenLayers,this.qConfig.actionSize],activations:Array(this.qConfig.hiddenLayers.length).fill(new _).concat([new B]),learningRate:this.config.learningRate}),this.targetNetwork=this.qNetwork.clone(),this.replayBufferClass=new Je(this.config.replayBufferSize,!1),this.initializeActions()}async predict(t){this.initialized||await this.initialize();let e=this.prepareState(t),r=this.targetNetwork.forward(e),i=this.argmax(r),n=this.actions[i],s=r[i],a=this.calculateConfidence(r);return{action:n,confidence:a,value:s,reasoning:this.generateReasoning(t,n,s,a)}}async trainCore(t){for(let i of t)this.replayBufferClass.add(i);if(!this.replayBufferClass.isReady(this.qConfig.minReplaySize))return this.getStats();let e=this.replayBufferClass.sample(this.config.batchSize);if(e.length===0)return this.getStats();let r=0;for(let i of e){let n=this.prepareState(i.state),s=this.prepareState(i.nextState),a,o=this.qNetwork.forward(n),c=this.actionToIndex(i.action);if(this.qConfig.doubleDQN&&!i.done){let m=this.qNetwork.forward(s),h=this.argmax(m),b=this.targetNetwork.forward(s)[h];a=i.reward+this.config.discountFactor*b}else{let m=this.targetNetwork.forward(s),h=Math.max(...m);a=i.reward+this.config.discountFactor*h*(i.done?0:1)}let l=new Float32Array(o.length);for(let m=0;m<l.length;m++)l[m]=m===c?a:o[m];let d=this.qNetwork.train(n,l,new fe);r+=Math.abs(d)}return this.updateCount++,this.updateCount%this.qConfig.targetUpdateFreq===0&&this.updateTargetNetwork(),{episode:this.episodeCount,totalReward:this.totalReward,averageReward:this.rewardHistory.reduce((i,n)=>i+n,0)/this.rewardHistory.length,loss:r/e.length,explorationRate:this.config.explorationRate,trainingTimeMs:0,timestamp:new Date}}getAlgorithmInfo(){return{type:this.type,category:this.category,version:"2.0.0",description:"Neural Q-Learning (DQN) for Coverage Path Optimization",capabilities:["Deep Q-Network for function approximation","Experience replay for stable learning","Target network for consistent targets","Double DQN for reduced overestimation","Coverage-aware test prioritization"],hyperparameters:{stateSize:this.qConfig.stateSize,actionSize:this.qConfig.actionSize,hiddenLayers:this.qConfig.hiddenLayers.join(","),targetUpdateFreq:this.qConfig.targetUpdateFreq,doubleDQN:String(this.qConfig.doubleDQN)},stats:this.stats}}updateTargetNetwork(){this.targetNetwork=this.qNetwork.clone()}prepareState(t){let e=t.features.slice(0,this.qConfig.stateSize);for(;e.length<this.qConfig.stateSize;)e.push(0);let r=Math.max(...e.map(Math.abs));if(r>0)for(let i=0;i<e.length;i++)e[i]=e[i]/r;return new Float32Array(e)}initializeActions(){this.actions=[{type:"generate-unit",value:"standard"},{type:"generate-integration",value:"standard"},{type:"prioritize",value:"high"},{type:"skip",value:0}],this.qConfig.actionSize=this.actions.length,this.qNetwork=new q({layerSizes:[this.qConfig.stateSize,...this.qConfig.hiddenLayers,this.qConfig.actionSize],activations:Array(this.qConfig.hiddenLayers.length).fill(new _).concat([new B]),learningRate:this.config.learningRate}),this.targetNetwork=this.qNetwork.clone()}actionToIndex(t){let e=this.actionToKey(t);for(let r=0;r<this.actions.length;r++)if(this.actionToKey(this.actions[r])===e)return r;return 0}indexToAction(t){return this.actions[Math.min(t,this.actions.length-1)]}argmax(t){let e=0,r=t[0];for(let i=1;i<t.length;i++)t[i]>r&&(r=t[i],e=i);return e}actionToKey(t){return`${t.type}:${JSON.stringify(t.value)}`}calculateConfidence(t){let e=Math.max(...t),r=Math.min(...t);if(e===r)return .5;let i=e-r;return Math.min(1,.3+i*2)}generateReasoning(t,e,r,i){return this.episodeCount<10?`Neural Q-Learning exploration phase (episode ${this.episodeCount}): ${e.type} action`:i>.8?`High-confidence Neural Q-Learning decision (${i.toFixed(2)}): ${e.type} with Q-value ${r.toFixed(3)} based on ${this.updateCount} network updates`:r>.5?`Positive Q-value (${r.toFixed(3)}) suggests ${e.type} is effective for current coverage state`:`Exploratory Neural Q-Learning action: ${e.type} with confidence ${i.toFixed(2)}`}async exportCustomData(){return{qNetwork:this.qNetwork.getParameters(),targetNetwork:this.targetNetwork.getParameters(),qConfig:this.qConfig,updateCount:this.updateCount,replayBufferSize:this.replayBufferClass.size()}}async importCustomData(t){t.qNetwork&&this.qNetwork.setParameters(t.qNetwork),t.targetNetwork&&this.targetNetwork.setParameters(t.targetNetwork),t.qConfig&&(this.qConfig={...this.qConfig,...t.qConfig}),typeof t.updateCount=="number"&&(this.updateCount=t.updateCount),this.initialized=!0}async resetAlgorithm(){this.qNetwork=new q({layerSizes:[this.qConfig.stateSize,...this.qConfig.hiddenLayers,this.qConfig.actionSize],activations:Array(this.qConfig.hiddenLayers.length).fill(new _).concat([new B]),learningRate:this.config.learningRate}),this.targetNetwork=this.qNetwork.clone(),this.replayBufferClass.clear(),this.updateCount=0}};var hg={maxConcurrentWorkflows:5,defaultTimeout:6e4,publishEvents:!0,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},$e=R.create("coverage-analysis"),Ai=class extends Q{constructor(e,r,i={},n){let s={...hg,...i};super(e,"coverage-analysis",s,{verifyFindingTypes:["coverage-gap","risk-zone","quality-regression"],...s.consensusConfig});this.memory=r;this.coverageAnalyzer=new ht({memory:r,llmRouter:n}),this.gapDetector=new lr({memory:r,llmRouter:n}),this.riskScorer=new ur(r),this.qLearning=new bs(this.qlConfig,yu)}memory;coverageAnalyzer;gapDetector;riskScorer;ghostAnalyzer=null;qLearning;qlConfig={stateSize:12,actionSize:4,hiddenLayers:[128,64],targetUpdateFreq:50,minReplaySize:50,doubleDQN:!0};async onInitialize(){}async onDispose(){}subscribeToEvents(){}async getQLRecommendations(e,r=10){try{let i=[];for(let a of e.slice(0,r)){let o=await this.predictQL(a),c=this.actionToTestType(o.action),l=this.estimateCoverageGain(a,o.action),d=this.estimateTestDuration(a,c);i.push({filePath:a.file,testType:c,priority:o.value,estimatedCoverageGain:l,estimatedDuration:d,action:o.action,confidence:o.confidence})}i.sort((a,o)=>o.priority-a.priority);let n=i.reduce((a,o)=>a+o.estimatedCoverageGain,0),s=i.reduce((a,o)=>a+o.estimatedDuration,0);return f({tests:i,totalEstimatedCoverageGain:n,totalEstimatedDuration:s,reasoning:`Q-Learning prioritized ${i.length} tests based on coverage optimization potential`})}catch(i){return p(y(i))}}async predictQL(e){try{let r=this.gapToQLState(e),i=await this.qLearning.predict(r),n=this.estimateCoverageGain(e,i.action),s=this.actionToTestCount(i.action);return{action:i.action,confidence:i.confidence,value:i.value||0,reasoning:i.reasoning||"",estimatedCoverageGain:n,estimatedTestCount:s}}catch(r){return{action:{type:"generate-unit",value:"standard"},confidence:.3,value:0,reasoning:`Fallback prediction due to error: ${r.message}`,estimatedCoverageGain:.1,estimatedTestCount:1}}}async trainQL(e){try{await this.qLearning.trainBatch([e]);let r=this.qLearning.getStats();r.episode%10===0&&await this.memory.set("coverage:ql:model:latest",{stats:r,exportedAt:new Date().toISOString()})}catch(r){$e.error("Failed to train Q-Learning model",r instanceof Error?r:void 0)}}gapToQLState(e){let r=[e.riskScore/10,Math.min(1,e.lines.length/50),Math.min(1,e.branches.length/10),this.severityToNumber(e.severity)/4,this.complexityFromPath(e.file),this.changeFrequencyFromPath(e.file),this.businessCriticalityFromPath(e.file),e.lines.length/Math.max(1,e.branches.length),this.calculateCoveragePotential(e),this.calculateFileComplexityScore(e),this.calculateTestComplexity(e),this.calculateExecutionCost(e)];return{id:e.id,features:r,metadata:{filePath:e.file,lines:e.lines,branches:e.branches,riskScore:e.riskScore,severity:e.severity},timestamp:new Date}}estimateCoverageGain(e,r){let i=(e.lines.length+e.branches.length*2)/1e3;switch(r.type){case"generate-unit":return i*.3;case"generate-integration":return i*.5;case"prioritize":return i*.7;case"skip":return 0;default:return i*.2}}estimateTestDuration(e,r){let i=e.lines.length*.5;switch(r){case"unit":return i;case"integration":return i*2;case"e2e":return i*5;default:return i}}actionToTestType(e){switch(e.type){case"generate-unit":return"unit";case"generate-integration":return"integration";case"prioritize":return"integration";default:return"unit"}}actionToTestCount(e){switch(e.type){case"generate-unit":return 3;case"generate-integration":return 2;case"prioritize":return 5;case"skip":return 0;default:return 1}}calculateCoveragePotential(e){let r=Math.min(1,e.lines.length/50),i=Math.min(1,e.branches.length/10),n=e.riskScore/10;return(r+i+n)/3}calculateFileComplexityScore(e){let i=e.file.split("/").length,n=/service|controller|provider|manager/i.test(e.file);return Math.min(1,(i+(n?2:0))/10)}calculateTestComplexity(e){let r=e.branches.length*.6,i=e.lines.length*.1;return Math.min(1,(r+i)/20)}calculateExecutionCost(e){let r=Math.min(1,e.lines.length/100),i=e.riskScore/10;return(r+i)/2}complexityFromPath(e){return["service","controller","provider","manager","handler"].some(n=>e.toLowerCase().includes(n))?.7:.3}changeFrequencyFromPath(e){return["src","lib","services","controllers"].some(n=>e.includes(n))?.6:.2}businessCriticalityFromPath(e){return["auth","payment","user","core","api"].some(n=>e.toLowerCase().includes(n))?.8:.4}isReady(){return this.initialized}async analyze(e){try{if(this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&$e.warn("Topology degraded, using conservative analysis mode"),this.minCutMixin.shouldPauseOperations())return p(new Error("Coverage analysis paused: topology is in critical state"));let r=await this.coverageAnalyzer.analyze(e);return r.success&&await this.publishCoverageReport(r.value),r}catch(r){return p(y(r))}}async detectGaps(e){try{if(this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&$e.warn("Topology degraded, using conservative gap detection"),this.minCutMixin.shouldPauseOperations())return p(new Error("Gap detection paused: topology is in critical state"));let r=await this.gapDetector.detectGaps(e);if(r.success){let i=[];for(let n of r.value.gaps){if(this.config.enableConsensus&&(n.severity==="critical"||n.severity==="high")){let s=Math.min(.95,n.riskScore/10+.3);if(!await this.verifyCoverageGap(n,s)){$e.info(`Coverage gap in '${n.file}' not verified, skipping publication`);continue}}i.push(n)}return await this.publishGapEvents(i),f({...r.value,gaps:i})}return r}catch(r){return p(y(r))}}async calculateRisk(e){try{if(this.minCutMixin.shouldPauseOperations())return p(new Error("Risk calculation paused: topology is in critical state"));let r=await this.riskScorer.calculateRisk(e);if(r.success){if(this.config.enableConsensus&&(r.value.riskLevel==="critical"||r.value.riskLevel==="high")&&!await this.verifyRiskZone({file:r.value.file,riskScore:r.value.overallRisk,factors:r.value.factors.map(n=>({name:n.name,weight:n.contribution}))},Math.min(.95,r.value.overallRisk/10+.5)))return $e.warn(`Risk zone '${r.value.file}' not verified, downgrading severity`),f({...r.value,riskLevel:r.value.riskLevel==="critical"?"high":"medium"});r.value.riskLevel==="critical"&&await this.publishRiskZoneEvent(r.value)}return r}catch(r){return p(y(r))}}async getTrend(e){try{let{timeRange:r,granularity:i}=e,n=await this.memory.search("coverage:history:*",100);if(n.length===0)return f({dataPoints:[],trend:"stable",forecast:0});let s=[];for(let l of n){let d=parseInt(l.split(":").pop()||"0",10),m=new Date(d);if(m>=r.start&&m<=r.end){let h=await this.memory.get(l);h&&s.push({date:m,coverage:h})}}s.sort((l,d)=>l.date.getTime()-d.date.getTime());let a=this.aggregateByGranularity(s,i),o=this.analyzeCoverageTrend(a),c=this.forecastCoverage(a);return f({dataPoints:a,trend:o,forecast:c})}catch(r){return p(y(r))}}async findSimilar(e){try{let{pattern:r,k:i}=e,n=Date.now(),s=this.createGapEmbedding(r),a=await this.memory.vectorSearch(s,i),o=[];for(let l of a){let d=l.metadata;d&&o.push({gap:{id:l.key,file:d.file||"unknown",lines:[],branches:[],riskScore:d.riskScore||0,severity:d.severity||"low",recommendation:"Similar pattern found in codebase"},similarity:l.score})}let c=Date.now()-n;return f({patterns:o,searchTime:c})}catch(r){return p(y(r))}}async analyzeGhostCoverage(e,r){try{if(!this.ghostAnalyzer){let d={hnswIndex:$r(this.memory),embedder:Si()};this.ghostAnalyzer=new Ti(d),await this.ghostAnalyzer.initialize()}let i={files:e.map(d=>({path:d,lines:{covered:0,total:100},branches:{covered:0,total:10},functions:{covered:0,total:5},statements:{covered:0,total:100},uncoveredLines:[],uncoveredBranches:[]})),summary:{line:0,branch:0,function:0,statement:0,files:e.length}},n={name:r,sourcePatterns:e},s=await this.ghostAnalyzer.computePhantomSurface(i,n);if(!s.success)return p(s.error);let a=s.value,o=await this.ghostAnalyzer.detectPhantomGaps(a),l={gaps:(o.success?o.value:[]).map(d=>({id:d.id,category:d.category,description:d.description,confidence:d.confidence,severity:d.severity,suggestedTest:d.suggestedLines.length>0?`Add test covering lines ${d.suggestedLines.join(", ")} in ${d.file}`:`Add ${d.category} test for ${d.file}`})),totalGhostScore:a.phantomRatio,coverageCompleteness:1-a.phantomRatio,computedAt:new Date(a.computedAt)};return f(l)}catch(i){return p(y(i))}}async publishCoverageReport(e){let r={reportId:crypto.randomUUID(),line:e.summary.line,branch:e.summary.branch,function:e.summary.function,statement:e.summary.statement,files:e.summary.files},i=I(rn.CoverageReportCreated,"coverage-analysis",r);await this.eventBus.publish(i)}async publishGapEvents(e){let r=e.filter(i=>i.severity==="critical"||i.severity==="high");for(let i of r){let n={gapId:i.id,file:i.file,uncoveredLines:i.lines,uncoveredBranches:i.branches,riskScore:i.riskScore},s=I(rn.CoverageGapDetected,"coverage-analysis",n);await this.eventBus.publish(s)}}async publishRiskZoneEvent(e){let r=I(rn.RiskZoneIdentified,"coverage-analysis",{file:e.file,overallRisk:e.overallRisk,riskLevel:e.riskLevel,topFactors:e.factors.slice(0,3).map(i=>i.name),recommendations:e.recommendations});await this.eventBus.publish(r)}aggregateByGranularity(e,r){if(e.length===0)return[];let i=new Map;for(let s of e){let a=this.getBucketKey(s.date,r),o=i.get(a)||[];o.push(s),i.set(a,o)}let n=[];for(let[,s]of i)if(s.length>0){let a={line:s.reduce((o,c)=>o+c.coverage.line,0)/s.length,branch:s.reduce((o,c)=>o+c.coverage.branch,0)/s.length,function:s.reduce((o,c)=>o+c.coverage.function,0)/s.length,statement:s.reduce((o,c)=>o+c.coverage.statement,0)/s.length,files:Math.round(s.reduce((o,c)=>o+c.coverage.files,0)/s.length)};n.push({date:s[0].date,coverage:a})}return n.sort((s,a)=>s.date.getTime()-a.date.getTime())}getBucketKey(e,r){let i=e.getFullYear(),n=e.getMonth(),s=e.getDate();switch(r){case"daily":return`${i}-${n}-${s}`;case"weekly":let a=Math.floor(s/7);return`${i}-${n}-W${a}`;case"monthly":return`${i}-${n}`}}analyzeCoverageTrend(e){if(e.length<2)return"stable";let r=e.map(l=>{let d=l.coverage;return(d.line+d.branch+d.function+d.statement)/4}),i=r.length,n=0,s=0,a=0,o=0;for(let l=0;l<i;l++)n+=l,s+=r[l],a+=l*r[l],o+=l*l;let c=(i*a-n*s)/(i*o-n*n);return c>.5?"improving":c<-.5?"declining":"stable"}forecastCoverage(e){if(e.length===0)return 0;let r=e.map(a=>{let o=a.coverage;return(o.line+o.branch+o.function+o.statement)/4});if(r.length===1)return r[0];let i=.3,n=r[0];for(let a=1;a<r.length;a++)n=i*r[a]+(1-i)*n;let s=this.analyzeCoverageTrend(e);return s==="improving"?n=Math.min(100,n+2):s==="declining"&&(n=Math.max(0,n-2)),n}createGapEmbedding(e){let i=new Array(384).fill(0);i[0]=e.riskScore,i[1]=Math.min(1,e.lines.length/100),i[2]=Math.min(1,e.branches.length/20),i[3]=this.severityToNumber(e.severity)/4;let n=e.file.split("").reduce((s,a)=>s+a.charCodeAt(0),0);i[4]=n%1e3/1e3;for(let s=5;s<384;s++)i[s]=Math.sin(s*e.riskScore)*.5+.5;return i}severityToNumber(e){switch(e){case"critical":return 4;case"high":return 3;case"medium":return 2;case"low":return 1;default:return 0}}async verifyCoverageGap(e,r){let i=V({id:v(),type:"coverage-gap",confidence:r,description:`Verify coverage gap in ${e.file}: ${e.lines.length} uncovered lines, ${e.branches.length} uncovered branches`,payload:e,detectedBy:"coverage-analysis-coordinator",severity:e.severity});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?($e.info(`Coverage gap in '${e.file}' verified by consensus`),!0):($e.warn(`Coverage gap in '${e.file}' NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}async verifyRiskZone(e,r){let i=V({id:v(),type:"risk-zone",confidence:r,description:`Verify risk zone: ${e.file} with risk score ${e.riskScore.toFixed(2)}`,payload:e,detectedBy:"coverage-analysis-coordinator",severity:e.riskScore>=.8?"critical":e.riskScore>=.5?"high":"medium"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?($e.info(`Risk zone '${e.file}' classification verified by consensus`),!0):($e.warn(`Risk zone '${e.file}' classification NOT verified`),!1)}return!0}async verifyQualityRegression(e,r){let i=V({id:v(),type:"quality-regression",confidence:r,description:`Verify quality regression: ${e.metric} dropped from ${e.previousValue.toFixed(1)}% to ${e.currentValue.toFixed(1)}% (threshold: ${e.threshold}%)`,payload:e,detectedBy:"coverage-analysis-coordinator",severity:"critical"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?($e.info("Quality regression verified by consensus"),!0):($e.warn(`Quality regression NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}};var ws=class u extends j{static VERSION="1.0.0";coordinator;_activeAnalyses=0;constructor(t,e,r){super(t,e),this.coordinator=new Ai(t,e,{},r)}get name(){return"coverage-analysis"}get version(){return u.VERSION}get dependencies(){return["test-execution"]}getAPI(){return this.coordinator}getCoverageAPI(){return this.coordinator}getTaskHandlers(){return new Map([["analyze-coverage",async t=>{let e=t.coverageData;if(!e)return p(new Error("Invalid analyze-coverage payload: missing coverageData"));this._activeAnalyses++,this.updateAgentMetrics();try{return await this.coordinator.analyze({coverageData:e,threshold:t.threshold,includeFileDetails:t.includeFileDetails})}finally{this._activeAnalyses--,this.updateAgentMetrics()}}],["detect-gaps",async t=>{let e=t.coverageData;if(!e)return p(new Error("Invalid detect-gaps payload: missing coverageData"));this._activeAnalyses++,this.updateAgentMetrics();try{return await this.coordinator.detectGaps({coverageData:e,minCoverage:t.minCoverage,prioritize:t.prioritize})}finally{this._activeAnalyses--,this.updateAgentMetrics()}}],["calculate-risk",async t=>{let e=t.file,r=t.uncoveredLines;if(!e||!r)return p(new Error("Invalid calculate-risk payload: missing file or uncoveredLines"));this._activeAnalyses++,this.updateAgentMetrics();try{return await this.coordinator.calculateRisk({file:e,uncoveredLines:r,factors:t.factors})}finally{this._activeAnalyses--,this.updateAgentMetrics()}}],["analyze-ghost-coverage",async t=>{let e=t.existingTests,r=t.codeContext;if(!e||!r)return p(new Error("Invalid analyze-ghost-coverage payload: missing existingTests or codeContext"));this._activeAnalyses++,this.updateAgentMetrics();try{return await this.coordinator.analyzeGhostCoverage(e,r)}finally{this._activeAnalyses--,this.updateAgentMetrics()}}]])}async onInitialize(){await this.coordinator.initialize(),this.updateHealth({status:"idle",lastActivity:new Date})}async onDispose(){await this.coordinator.dispose(),this.updateHealth({status:"unhealthy",agents:{total:0,active:0,idle:0,failed:0}})}subscribeToEvents(){this.eventBus.subscribe(Pe.TestRunCompleted,this.handleTestRunCompleted.bind(this))}async onEvent(t){t.type===Pe.TestRunCompleted&&await this.handleTestRunCompleted(t)}async handleTestRunCompleted(t){let e=t.payload;if(e.coverageData){this._activeAnalyses++,this.updateAgentMetrics();try{await this.coordinator.analyze({coverageData:e.coverageData,includeFileDetails:!0})}finally{this._activeAnalyses--,this.updateAgentMetrics()}}}updateAgentMetrics(){let t={status:(this._activeAnalyses>0,"healthy"),agents:{total:3,active:this._activeAnalyses>0?1:0,idle:this._activeAnalyses>0?2:3,failed:0},lastActivity:new Date,errors:[]};this.updateHealth(t)}getHealth(){return{...this._health,agents:{total:3,active:this._activeAnalyses>0?1:0,idle:this._activeAnalyses>0?2:3,failed:0},lastActivity:new Date}}};function oc(u,t,e){return new ws(u,t,e)}M();A();A();var gg={strictMode:!1,enableWarnings:!0,defaultSeverities:{coverage:"high",testsPassing:"critical",criticalBugs:"critical",codeSmells:"medium",securityVulnerabilities:"critical",technicalDebt:"medium",duplications:"low"}},fg={strict:{coverage:{min:90},testsPassing:{min:100},criticalBugs:{max:0},codeSmells:{max:10},securityVulnerabilities:{max:0},technicalDebt:{max:2},duplications:{max:3}},standard:{coverage:{min:80},testsPassing:{min:95},criticalBugs:{max:0},codeSmells:{max:20},securityVulnerabilities:{max:0},technicalDebt:{max:5},duplications:{max:5}},relaxed:{coverage:{min:60},testsPassing:{min:90},criticalBugs:{max:2},codeSmells:{max:50},securityVulnerabilities:{max:1},technicalDebt:{max:10},duplications:{max:10}}},gt=class{constructor(t,e={}){this.memory=t;this.config={...gg,...e};for(let[r,i]of Object.entries(fg))this.presets.set(r,i)}memory;config;presets=new Map;async evaluateGate(t){try{let{gateName:e,metrics:r,thresholds:i}=t;if(!r)return p(new Error("No metrics provided for gate evaluation"));let n=[],s=[];n.push(...this.evaluateMinThresholds(r,i)),n.push(...this.evaluateMaxThresholds(r,i));for(let l of n)l.passed||s.push(l.name);let a=this.calculateOverallScore(n),o=this.determineGateStatus(n),c={gateName:e,passed:o,checks:n,overallScore:a,failedChecks:s};return await this.storeEvaluationResult(c),f(c)}catch(e){return p(y(e))}}async createGatePreset(t,e){try{let r=`preset-${t}-${v().slice(0,8)}`;return this.presets.set(t,e),await this.memory.set(`quality-gate:preset:${t}`,{id:r,name:t,thresholds:e,createdAt:new Date().toISOString()},{namespace:"quality-assessment",persist:!0}),f(r)}catch(r){return p(y(r))}}async getGatePreset(t){if(this.presets.has(t))return this.presets.get(t);let e=await this.memory.get(`quality-gate:preset:${t}`);if(e)return this.presets.set(t,e.thresholds),e.thresholds}async listGatePresets(){let t=await this.memory.search("quality-gate:preset:*",100),e=new Set(Array.from(this.presets.keys()));for(let r of t){let i=r.replace("quality-gate:preset:","");e.add(i)}return Array.from(e)}evaluateMinThresholds(t,e){let r=[];return e.coverage?.min!==void 0&&r.push(this.createCheck("coverage",t.coverage,e.coverage.min,"min",this.config.defaultSeverities.coverage)),e.testsPassing?.min!==void 0&&r.push(this.createCheck("testsPassing",t.testsPassing,e.testsPassing.min,"min",this.config.defaultSeverities.testsPassing)),r}evaluateMaxThresholds(t,e){let r=[];return e.criticalBugs?.max!==void 0&&r.push(this.createCheck("criticalBugs",t.criticalBugs,e.criticalBugs.max,"max",this.config.defaultSeverities.criticalBugs)),e.codeSmells?.max!==void 0&&r.push(this.createCheck("codeSmells",t.codeSmells,e.codeSmells.max,"max",this.config.defaultSeverities.codeSmells)),e.securityVulnerabilities?.max!==void 0&&r.push(this.createCheck("securityVulnerabilities",t.securityVulnerabilities,e.securityVulnerabilities.max,"max",this.config.defaultSeverities.securityVulnerabilities)),e.technicalDebt?.max!==void 0&&r.push(this.createCheck("technicalDebt",t.technicalDebt,e.technicalDebt.max,"max",this.config.defaultSeverities.technicalDebt)),e.duplications?.max!==void 0&&r.push(this.createCheck("duplications",t.duplications,e.duplications.max,"max",this.config.defaultSeverities.duplications)),r}createCheck(t,e,r,i,n){let s=i==="min"?e>=r:e<=r;return{name:t,passed:s,value:e,threshold:r,severity:n}}calculateOverallScore(t){if(t.length===0)return 100;let e={critical:3,high:2,medium:1.5,low:1,info:.5},r=0,i=0;for(let n of t){let s=e[n.severity];r+=s,n.passed&&(i+=s)}return r>0?Math.round(i/r*100):100}determineGateStatus(t){return this.config.strictMode?t.every(e=>e.passed):t.filter(e=>e.severity==="critical"||e.severity==="high").every(e=>e.passed)}async storeEvaluationResult(t){let e=`quality-gate:evaluation:${t.gateName}:${Date.now()}`;await this.memory.set(e,{...t,evaluatedAt:new Date().toISOString()},{namespace:"quality-assessment",ttl:86400*30})}};M();er();var Cs=class{parser;fileReader;constructor(){this.parser=new zr,this.fileReader=new Fe}async analyzeFile(t){let e=await this.fileReader.readFile(t);if(!e.success)return null;let r=e.value,i=r.split(`
|
|
2614
|
+
});`}};A();var ag=[{name:"uncovered-lines",weight:.25},{name:"complexity",weight:.2},{name:"defect-history",weight:.2},{name:"change-frequency",weight:.15},{name:"code-age",weight:.1},{name:"dependency-count",weight:.1}],ur=class u{constructor(t){this.memory=t}memory;static HISTORY_KEY_PREFIX="risk-history";static MAX_TREND_POINTS=30;async calculateRisk(t){try{let{file:e,uncoveredLines:r,factors:i=ag}=t,n=this.normalizeFactorWeights(i),s=await this.calculateFactorScores(e,r,n),a=s.reduce((l,d)=>l+d.score*d.contribution,0),o=this.riskScoreToSeverity(a),c=this.generateRiskRecommendations(e,a,o,s);return await this.storeRiskSnapshot(e,a,s),f({file:e,overallRisk:a,riskLevel:o,factors:s,recommendations:c})}catch(e){return p(y(e))}}async factorInHistory(t,e){try{let r=await this.getDefectHistory(t),i=Math.min(1,r.count/10)*.3,n=await this.getChangeFrequency(t),s=Math.min(1,n/20)*.2,a=await this.getRiskTrend(t),o=0;if(a.success){let l=a.value;l.trend==="increasing"?o=.15:l.trend==="decreasing"&&(o=-.1)}let c=e+i+s+o;return Math.min(1,Math.max(0,c))}catch{return e}}async getRiskTrend(t){try{let e=`${u.HISTORY_KEY_PREFIX}:${t}`,r=await this.memory.get(e);if(!r||r.length===0)return f({file:t,dataPoints:[],trend:"stable",forecast:.5});let i=r.slice(-u.MAX_TREND_POINTS).map(a=>({date:new Date(a.timestamp),riskScore:a.riskScore,factors:a.topFactors})),n=this.analyzeTrend(i),s=this.forecastRisk(i);return f({file:t,dataPoints:i,trend:n,forecast:s})}catch(e){return p(y(e))}}normalizeFactorWeights(t){let e=t.reduce((r,i)=>r+i.weight,0);return e===0?t:t.map(r=>({...r,weight:r.weight/e}))}async calculateFactorScores(t,e,r){let i=[];for(let n of r){let s=await this.calculateSingleFactorScore(n.name,t,e);i.push({name:n.name,score:s,contribution:n.weight})}return i}async calculateSingleFactorScore(t,e,r){switch(t){case"uncovered-lines":return this.calculateUncoveredLinesScore(r);case"complexity":return await this.calculateComplexityScore(e);case"defect-history":return await this.calculateDefectHistoryScore(e);case"change-frequency":return await this.calculateChangeFrequencyScore(e);case"code-age":return await this.calculateCodeAgeScore(e);case"dependency-count":return await this.calculateDependencyScore(e);default:return .5}}calculateUncoveredLinesScore(t){let e=t.length;return e===0?0:e<=5?.2:e<=15?.4:e<=30?.6:e<=50?.8:1}async calculateComplexityScore(t){try{let e=await this.memory.get(`complexity:${t}`);if(!e)return .5;let r=e.cyclomatic;return r<=5?.2:r<=10?.4:r<=20?.6:r<=30?.8:1}catch{return .5}}async calculateDefectHistoryScore(t){let r=(await this.getDefectHistory(t)).count;return r===0?.1:r<=2?.3:r<=5?.5:r<=10?.7:.9}async calculateChangeFrequencyScore(t){let e=await this.getChangeFrequency(t);return e<=2?.2:e<=5?.4:e<=10?.6:e<=20?.8:1}async calculateCodeAgeScore(t){try{let e=await this.memory.get(`file-metadata:${t}`);if(!e)return .5;let r=(Date.now()-new Date(e.createdAt).getTime())/(1e3*60*60*24);return r<=7?.8:r<=30?.5:r<=90?.3:r<=365?.4:.6}catch{return .5}}async calculateDependencyScore(t){try{let e=await this.memory.get(`dependencies:${t}`);if(!e)return .5;let r=e.count;return r<=3?.2:r<=7?.4:r<=15?.6:r<=25?.8:1}catch{return .5}}async getDefectHistory(t){try{return{count:(await this.memory.get(`defect-history:${t}`))?.defectCount??0}}catch{return{count:0}}}async getChangeFrequency(t){try{return(await this.memory.get(`change-frequency:${t}`))?.changesLast90Days??5}catch{return 5}}riskScoreToSeverity(t){return t>=.8?"critical":t>=.6?"high":t>=.3?"medium":t>=.1?"low":"info"}generateRiskRecommendations(t,e,r,i){let n=[],a=[...i].sort((o,c)=>c.score*c.contribution-o.score*o.contribution).slice(0,3);r==="critical"?n.push(`CRITICAL: ${t} has a risk score of ${(e*100).toFixed(1)}%. Immediate action required.`):r==="high"&&n.push(`HIGH RISK: ${t} should be prioritized for test coverage improvement.`);for(let o of a)o.score>=.6&&n.push(this.getFactorRecommendation(o.name,o.score));return e>=.5&&n.push("Consider breaking this file into smaller, more testable modules."),i.find(o=>o.name==="defect-history"&&o.score>=.5)&&n.push("This file has a history of defects. Add regression tests for known issues."),n}getFactorRecommendation(t,e){let r=e>=.8?"Critical":"High";switch(t){case"uncovered-lines":return`${r}: Many uncovered lines. Focus on adding unit tests for core logic.`;case"complexity":return`${r}: High complexity detected. Consider refactoring before adding tests.`;case"defect-history":return`${r}: Past defects in this area. Add regression tests to prevent recurrence.`;case"change-frequency":return`${r}: Frequently changed code. Ensure comprehensive test coverage.`;case"code-age":return`${r}: Code age indicates risk. Review and update tests accordingly.`;case"dependency-count":return`${r}: Many dependencies. Add integration tests to verify interactions.`;default:return`${r}: Factor "${t}" indicates elevated risk.`}}async storeRiskSnapshot(t,e,r){try{let i=`${u.HISTORY_KEY_PREFIX}:${t}`,n=await this.memory.get(i)??[],s={timestamp:Date.now(),riskScore:e,topFactors:r.filter(o=>o.score>=.5).map(o=>o.name)},a=[...n,s].slice(-u.MAX_TREND_POINTS);await this.memory.set(i,a,{persist:!0})}catch{}}analyzeTrend(t){if(t.length<3)return"stable";let e=t.length,r=0,i=0,n=0,s=0;for(let o=0;o<e;o++){let c=o,l=t[o].riskScore;r+=c,i+=l,n+=c*l,s+=c*c}let a=(e*n-r*i)/(e*s-r*r);return a>.01?"increasing":a<-.01?"decreasing":"stable"}forecastRisk(t){if(t.length===0)return .5;if(t.length===1)return t[0].riskScore;let e=.3,r=t[0].riskScore;for(let n=1;n<t.length;n++)r=e*t[n].riskScore+(1-e)*r;let i=this.analyzeTrend(t);return i==="increasing"?r=Math.min(1,r+.05):i==="decreasing"&&(r=Math.max(0,r-.05)),r}};var ac={dimensions:384,includePathFeatures:!0,includeTemporalFeatures:!0,normalization:"l2"},Ci=class{config;constructor(t={}){this.config={...ac,...t}}embedFileCoverage(t){let e=new Array(this.config.dimensions).fill(0),r=0;return r=this.encodeCoverageMetrics(e,t,r),r=this.encodeGapCharacteristics(e,t,r),r=this.encodeRiskFactors(e,t,r),r=this.encodeFileCharacteristics(e,t,r),this.encodeDerivedFeatures(e,t,r),{vector:this.normalize(e),metadata:this.createMetadata(t),confidence:this.calculateConfidence(t)}}embedCoverageGap(t){let e=new Array(this.config.dimensions).fill(0);e[0]=t.riskScore,e[1]=Math.min(1,t.lines.length/100),e[2]=Math.min(1,t.branches.length/20),e[3]=this.severityToNumber(t.severity)/4;let r=this.extractPathFeatures(t.file);if(e[4]=r.depth/10,e[5]=r.hashNormalized,t.lines.length>1){let n=t.lines[t.lines.length-1]-t.lines[0];e[6]=Math.min(1,n/500),e[7]=t.lines.length/(n+1)}for(let n=8;n<this.config.dimensions;n++){let s=t.riskScore*n+t.lines.length*.01;e[n]=Math.sin(s)*.5+.5}return{vector:this.normalize(e),metadata:{filePath:t.file,lineCoverage:0,branchCoverage:0,functionCoverage:0,statementCoverage:0,uncoveredLineCount:t.lines.length,uncoveredBranchCount:t.branches.length,riskScore:t.riskScore,lastUpdated:Date.now(),totalLines:t.lines.length>0?t.lines[t.lines.length-1]:0},confidence:.8}}embedQuery(t){let e=new Array(this.config.dimensions).fill(0);if(t.minLineCoverage!==void 0&&(e[0]=t.minLineCoverage/100),t.maxLineCoverage!==void 0&&(e[1]=t.maxLineCoverage/100),t.minBranchCoverage!==void 0&&(e[2]=t.minBranchCoverage/100),t.maxBranchCoverage!==void 0&&(e[3]=t.maxBranchCoverage/100),t.minRiskScore!==void 0&&(e[4]=t.minRiskScore),t.maxRiskScore!==void 0&&(e[5]=t.maxRiskScore),t.filePattern){let r=this.extractPathFeatures(t.filePattern);e[6]=r.depth/10,e[7]=r.hashNormalized}t.maxUncoveredLines!==void 0&&(e[8]=Math.min(1,t.maxUncoveredLines/100));for(let r=9;r<this.config.dimensions;r++)e[r]===0&&(e[r]=.5);return{vector:this.normalize(e),metadata:{filePath:t.filePattern||"",lineCoverage:t.minLineCoverage||0,branchCoverage:t.minBranchCoverage||0,functionCoverage:0,statementCoverage:0,uncoveredLineCount:t.maxUncoveredLines||0,uncoveredBranchCount:0,riskScore:t.minRiskScore||0,lastUpdated:Date.now(),totalLines:0},confidence:.7}}batchEmbed(t){return t.map(e=>this.embedFileCoverage(e))}encodeCoverageMetrics(t,e,r){return t[r++]=e.lines.total>0?e.lines.covered/e.lines.total:0,t[r++]=Math.min(1,e.lines.total/1e3),t[r++]=Math.min(1,e.lines.covered/500),t[r++]=e.lines.total>0?e.uncoveredLines.length/e.lines.total:0,t[r++]=e.branches.total>0?e.branches.covered/e.branches.total:1,t[r++]=Math.min(1,e.branches.total/200),t[r++]=Math.min(1,e.branches.covered/100),t[r++]=e.branches.total>0?e.uncoveredBranches.length/e.branches.total:0,t[r++]=e.functions.total>0?e.functions.covered/e.functions.total:1,t[r++]=Math.min(1,e.functions.total/50),t[r++]=Math.min(1,e.functions.covered/25),t[r++]=e.functions.total>0?1-e.functions.covered/e.functions.total:0,t[r++]=e.statements.total>0?e.statements.covered/e.statements.total:1,t[r++]=Math.min(1,e.statements.total/1e3),t[r++]=Math.min(1,e.statements.covered/500),t[r++]=e.statements.total>0?1-e.statements.covered/e.statements.total:0,r}encodeGapCharacteristics(t,e,r){let i=e.uncoveredLines,n=e.uncoveredBranches;if(t[r++]=Math.min(1,i.length/100),t[r++]=Math.min(1,n.length/50),t[r++]=Math.min(1,(i.length+n.length)/150),t[r++]=i.length>0?1:0,i.length>1){let s=[...i].sort((l,d)=>l-d),a=s[s.length-1]-s[0],o=i.length/(a+1);t[r++]=Math.min(1,a/500),t[r++]=Math.min(1,o);let c=this.countContiguousRegions(s);t[r++]=Math.min(1,c/10),t[r++]=c>0?i.length/c:0}else t[r++]=0,t[r++]=i.length>0?1:0,t[r++]=i.length>0?.1:0,t[r++]=i.length;if(i.length>0&&e.lines.total>0){let s=Math.min(...i),a=Math.max(...i);t[r++]=s/e.lines.total,t[r++]=a/e.lines.total,t[r++]=(a-s)/e.lines.total,t[r++]=i.filter(o=>o<=e.lines.total*.2).length/i.length}else r+=4;return r+=4,r}encodeRiskFactors(t,e,r){let i=this.calculateOverallCoverage(e);t[r++]=1-i,t[r++]=e.branches.total>0?1-e.branches.covered/e.branches.total:0,t[r++]=e.functions.total>0?1-e.functions.covered/e.functions.total:0,t[r++]=Math.min(1,e.uncoveredLines.length/50),t[r++]=Math.min(1,e.lines.total/500),t[r++]=Math.min(1,e.functions.total/30),t[r++]=Math.min(1,e.branches.total/100),t[r++]=e.lines.total>300?.8:e.lines.total/375;let n=this.calculateLargeGapRatio(e.uncoveredLines);return t[r++]=n,t[r++]=e.uncoveredBranches.length>10?1:e.uncoveredBranches.length/10,t[r++]=e.uncoveredLines.length>30?1:e.uncoveredLines.length/30,t[r++]=this.calculateGapConcentration(e),r+=4,r}encodeFileCharacteristics(t,e,r){let i=this.extractPathFeatures(e.path);return t[r++]=i.depth/10,t[r++]=i.hashNormalized,t[r++]=i.isTest?.1:.9,t[r++]=i.isConfig?.2:.8,t[r++]=i.extension==="ts"?1:0,t[r++]=i.extension==="js"?1:0,t[r++]=i.extension==="tsx"||i.extension==="jsx"?1:0,t[r++]=i.isIndex?.5:0,t[r++]=i.inSrc?1:0,t[r++]=i.inLib?.8:0,t[r++]=i.inDomains?1:0,t[r++]=i.inServices?.9:0,r+=4,r}encodeDerivedFeatures(t,e,r){let i=[e.lines.covered/(e.lines.total||1),e.branches.covered/(e.branches.total||1),e.functions.covered/(e.functions.total||1),e.statements.covered/(e.statements.total||1),e.uncoveredLines.length/(e.lines.total||1),e.uncoveredBranches.length/(e.branches.total||1)];for(let n=0;n<6;n++)for(let s=n+1;s<6&&r<this.config.dimensions;s++)t[r++]=(i[n]+i[s])/2,r<this.config.dimensions&&(t[r++]=Math.abs(i[n]-i[s]));for(;r<this.config.dimensions-6;){let n=(r-64)%i.length;t[r++]=i[n]*i[n],r<this.config.dimensions&&(t[r++]=Math.sqrt(i[n]))}for(;r<this.config.dimensions;){let n=(r-64)*.1,s=i[(r-64)%i.length];t[r++]=Math.sin(s*Math.PI+n)*.5+.5}}normalize(t){switch(this.config.normalization){case"l2":return this.l2Normalize(t);case"minmax":return this.minMaxNormalize(t);default:return t}}l2Normalize(t){let e=Math.sqrt(t.reduce((r,i)=>r+i*i,0));return e===0?t:t.map(r=>r/e)}minMaxNormalize(t){let e=Math.min(...t),i=Math.max(...t)-e;return i===0?t.map(()=>.5):t.map(n=>(n-e)/i)}createMetadata(t){return{filePath:t.path,lineCoverage:t.lines.total>0?t.lines.covered/t.lines.total*100:0,branchCoverage:t.branches.total>0?t.branches.covered/t.branches.total*100:0,functionCoverage:t.functions.total>0?t.functions.covered/t.functions.total*100:0,statementCoverage:t.statements.total>0?t.statements.covered/t.statements.total*100:0,uncoveredLineCount:t.uncoveredLines.length,uncoveredBranchCount:t.uncoveredBranches.length,riskScore:this.calculateRiskScore(t),lastUpdated:Date.now(),totalLines:t.lines.total}}calculateConfidence(t){let e=t.lines.total>0,r=t.branches.total>0,i=t.functions.total>0,n=t.statements.total>0,s=.5;return e&&(s+=.2),r&&(s+=.1),i&&(s+=.1),n&&(s+=.1),Math.min(1,s)}calculateOverallCoverage(t){let e=t.lines.total>0?t.lines.covered/t.lines.total:1,r=t.branches.total>0?t.branches.covered/t.branches.total:1,i=t.functions.total>0?t.functions.covered/t.functions.total:1,n=t.statements.total>0?t.statements.covered/t.statements.total:1;return(e+r+i+n)/4}calculateRiskScore(t){let e=t.lines.total>0?1-t.lines.covered/t.lines.total:0,r=t.branches.total>0?1-t.branches.covered/t.branches.total:0,i=t.functions.total>0?1-t.functions.covered/t.functions.total:0;return Math.min(1,e*.3+r*.4+i*.3)}countContiguousRegions(t){if(t.length===0)return 0;let e=1;for(let r=1;r<t.length;r++)t[r]-t[r-1]>3&&e++;return e}calculateLargeGapRatio(t){if(t.length===0)return 0;let e=[...t].sort((s,a)=>s-a),r=0,i=1;for(let s=1;s<e.length;s++)e[s]-e[s-1]<=3?i++:(i>10&&r++,i=1);i>10&&r++;let n=this.countContiguousRegions(e);return n>0?r/n:0}calculateGapConcentration(t){if(t.uncoveredLines.length===0||t.lines.total===0)return 0;let e=this.countContiguousRegions([...t.uncoveredLines].sort((i,n)=>i-n)),r=Math.ceil(t.uncoveredLines.length/5);return e>0?Math.min(1,r/e):0}extractPathFeatures(t){let e=t.split("/").filter(Boolean),r=t.split(".").pop()||"",i=e[e.length-1]||"";return{depth:e.length,extension:r,hashNormalized:this.hashString(t)/1e6,isTest:/\.(test|spec)\.(ts|js|tsx|jsx)$/.test(t)||e.includes("tests")||e.includes("__tests__"),isConfig:/\.(config|rc)\.(ts|js|json|yaml|yml)$/.test(t),isIndex:i.startsWith("index."),inSrc:e.includes("src"),inLib:e.includes("lib"),inDomains:e.includes("domains"),inServices:e.includes("services")}}hashString(t){let e=0;for(let r=0;r<t.length;r++){let i=t.charCodeAt(r);e=(e<<5)-e+i|0}return Math.abs(e)}severityToNumber(t){switch(t){case"critical":return 4;case"high":return 3;case"medium":return 2;case"low":return 1;default:return 0}}};function Si(u){return new Ci(u)}M();A();var AP=R.create("coverage-analysis/sublinear-analyzer");Zi();A();var Ri=["missing-error-handler","absent-boundary-validation","unprotected-state-transition","missing-integration-contract","absent-edge-case","missing-security-check"],og={dimensions:384,minConfidence:.3,maxGaps:50,riskWeight:.6,distanceWeight:.4,namespace:"ghost-surface",idealSurfaceDecay:.95},Ti=class u{config;hnswIndex;embedder;idealSurfacePatterns=[];cachedIdealSurface=null;cachedPhantomRatio=1;initialized=!1;constructor(t,e={}){this.config={...og,...e},this.hnswIndex=t.hnswIndex,this.embedder=t.embedder}async initialize(){try{return this.idealSurfacePatterns=this.buildBaselinePatterns(),this.cachedIdealSurface=this.aggregateIdealSurface(),this.initialized=!0,f(void 0)}catch(t){return p(y(t))}}async computePhantomSurface(t,e){try{this.ensureInitialized();let r=this.buildIdealSurface(e),i=new Map,n=[];for(let o of t.files){let c=this.embedder.embedFileCoverage(o).vector;n.push(c),i.set(o.path,this.computeGhostVector(c,r)),await this.hnswIndex.insert(`${this.config.namespace}:${o.path}`,i.get(o.path),{filePath:o.path,lineCoverage:this.ratio(o.lines.covered,o.lines.total)*100,branchCoverage:this.ratio(o.branches.covered,o.branches.total)*100,functionCoverage:this.ratio(o.functions.covered,o.functions.total)*100,statementCoverage:this.ratio(o.statements.covered,o.statements.total)*100,uncoveredLineCount:o.uncoveredLines.length,uncoveredBranchCount:o.uncoveredBranches.length,riskScore:this.fileRiskScore(o),lastUpdated:Date.now(),totalLines:o.lines.total})}let s=this.aggregateSurface(n),a=this.phantomRatioFromVectors(r,s);return this.cachedIdealSurface=r,this.cachedPhantomRatio=a,f({ghostVectors:i,idealSurface:r,actualSurface:s,phantomRatio:a,computedAt:Date.now(),filesAnalyzed:t.files.length})}catch(r){return p(y(r))}}async detectPhantomGaps(t,e){try{this.ensureInitialized();let r=e??this.config.minConfidence,i=[];for(let[n,s]of t.ghostVectors){if(Xi(s)<.01)continue;let a=await this.hnswIndex.search(s,5),o=this.getApplicableCategories(n);for(let c of this.classifyGhost(s,a)){if(c.confidence<r||!o.has(c.category))continue;let l=this.gapRiskScore(s,c.category),d=Math.min(1,Xi(s));i.push({id:this.gapId(n,c.category),file:n,category:c.category,ghostDistance:d,riskScore:l,severity:this.toSeverity(d,l),confidence:c.confidence,description:this.gapDescription(n,c.category,d),suggestedLines:c.suggestedLines})}}return i.sort((n,s)=>s.ghostDistance*s.riskScore-n.ghostDistance*n.riskScore),f(i.slice(0,this.config.maxGaps))}catch(r){return p(y(r))}}rankPhantomGaps(t){let{riskWeight:e,distanceWeight:r}=this.config;return[...t].sort((i,n)=>e*n.riskScore+r*n.ghostDistance-(e*i.riskScore+r*i.ghostDistance))}async updateIdealSurface(t){try{this.ensureInitialized();for(let e of this.idealSurfacePatterns)e.weight*=this.config.idealSurfaceDecay;for(let e of t){if(e.vector.length!==this.config.dimensions)continue;let r=this.idealSurfacePatterns.findIndex(i=>i.id===e.id);r>=0?this.idealSurfacePatterns[r]=e:this.idealSurfacePatterns.push(e)}return this.idealSurfacePatterns=this.idealSurfacePatterns.filter(e=>e.weight>.01),this.cachedIdealSurface=this.aggregateIdealSurface(),f(this.idealSurfacePatterns.length)}catch(e){return p(y(e))}}getPhantomRatio(){return this.cachedPhantomRatio}computeGhostVector(t,e){let r=Math.min(t.length,e.length),i=new Array(r);for(let n=0;n<r;n++)i[n]=Math.max(0,e[n]-t[n]);return wt(i)}buildBaselinePatterns(){let t=this.config.dimensions,e=Math.floor(t/Ri.length);return Ri.map((r,i)=>{let n=new Array(t).fill(0),s=i*e,a=Math.min(s+e,t);for(let o=s;o<a;o++)n[o]=Math.sin((o-s)/e*Math.PI)*.8+.2;return n[0]=.9,n[1]=.85,n[2]=.9,n[3]=.85,{id:`baseline-${r}`,category:r,vector:wt(n),weight:1,source:"baseline"}})}buildIdealSurface(t){let e=this.aggregateIdealSurface();if(t.riskAreas?.length)for(let r=32;r<48&&r<e.length;r++)e[r]*=1.2;if(t.defectHistory?.length){let r=Math.min(1.5,1+t.defectHistory.length*.05);for(let i=0;i<16&&i<e.length;i++)e[i]*=r}return wt(e)}aggregateIdealSurface(){let t=this.config.dimensions;if(this.idealSurfacePatterns.length===0)return wt(new Array(t).fill(1));let e=new Array(t).fill(0),r=0;for(let i of this.idealSurfacePatterns){for(let n=0;n<t;n++)e[n]+=i.vector[n]*i.weight;r+=i.weight}if(r>0)for(let i=0;i<t;i++)e[i]/=r;return wt(e)}aggregateSurface(t){let e=this.config.dimensions;if(t.length===0)return new Array(e).fill(0);let r=new Array(e).fill(0);for(let i of t)for(let n=0;n<e&&n<i.length;n++)r[n]+=i[n];for(let i=0;i<e;i++)r[i]/=t.length;return wt(r)}classifyGhost(t,e){let r=this.config.dimensions,i=Math.floor(r/Ri.length),n=[],s=0;for(let a of e)a.score>.7&&(s+=a.score*.1);for(let a=0;a<Ri.length;a++){let o=a*i,c=Math.min(o+i,r),l=0;for(let m=o;m<c&&m<t.length;m++)l+=t[m]**2;l=Math.sqrt(l/(c-o));let d=Math.min(1,l+s);d>.05&&n.push({category:Ri[a],confidence:d,suggestedLines:this.suggestLines(a,t)})}return n.sort((a,o)=>o.confidence-a.confidence)}suggestLines(t,e){let r=e[0]||0,i=e[2]||0;if(r<.1&&i<.1)return[];let n=t*20+1,s=Math.ceil(r*10),a=[];for(let o=0;o<s&&a.length<10;o++)a.push(n+o*5);return a}getApplicableCategories(t){let e=t.toLowerCase(),r=e.split("/").pop()||e,i=new Set(["missing-error-handler","absent-edge-case"]);return/\b(math|calc|util|helper|format|parse|convert|transform)\b/.test(r)?(i.add("absent-boundary-validation"),i):(i.add("absent-boundary-validation"),/\b(auth|security|token|credential|password|session|permission|rbac|acl|encrypt|crypto)\b/.test(e)&&i.add("missing-security-check"),/\b(service|controller|handler|router|middleware|api|endpoint|gateway|adapter)\b/.test(e)&&(i.add("missing-integration-contract"),i.add("unprotected-state-transition")),/\b(state|store|reducer|saga|machine|workflow|queue|scheduler)\b/.test(e)&&i.add("unprotected-state-transition"),i)}static CATEGORY_RISK={"missing-security-check":1.5,"missing-error-handler":1.3,"unprotected-state-transition":1.2,"missing-integration-contract":1.1,"absent-boundary-validation":1,"absent-edge-case":.8};gapRiskScore(t,e){return Math.min(1,Xi(t)*(u.CATEGORY_RISK[e]??1))}fileRiskScore(t){return Math.min(1,(1-this.ratio(t.lines.covered,t.lines.total))*.3+(1-this.ratio(t.branches.covered,t.branches.total))*.4+(1-this.ratio(t.functions.covered,t.functions.total))*.3)}phantomRatioFromVectors(t,e){return!t.length||!e.length?1:Math.max(0,Math.min(1,1-tt(t,e)))}toSeverity(t,e){let r=(t+e)/2;return r>=.8?"critical":r>=.6?"high":r>=.3?"medium":"low"}ensureInitialized(){if(!this.initialized)throw new Error("GhostCoverageAnalyzerService not initialized. Call initialize() first.")}ratio(t,e){return e>0?t/e:0}gapId(t,e){let r=`${t}:${e}`.split("").reduce((i,n)=>(i<<5)-i+n.charCodeAt(0)|0,0);return`phantom-${Math.abs(r).toString(16)}`}gapDescription(t,e,r){let i=t.split("/").pop()||t,n=r>.7?"significant":r>.4?"moderate":"minor";return{"missing-error-handler":`${i}: ${n} missing error handler tests. Cover error paths and failure recovery.`,"absent-boundary-validation":`${i}: ${n} missing boundary validation tests. Cover input bounds and null checks.`,"unprotected-state-transition":`${i}: ${n} missing state transition tests. Cover state changes and race conditions.`,"missing-integration-contract":`${i}: ${n} missing integration contract tests. Cover external API boundaries.`,"absent-edge-case":`${i}: ${n} missing edge case tests. Cover empty inputs, max values, and timeouts.`,"missing-security-check":`${i}: ${n} missing security check tests. Cover auth bypass and injection attacks.`}[e]}};se();var _=class{forward(t){return Math.max(0,t)}backward(t){return t>0?1:0}};var B=class{forward(t){return t}backward(t){return 1}},he=class u{static forward(t){let e=Math.max(...t),r=t.map(n=>Math.exp(n-e)),i=r.reduce((n,s)=>n+s,0);return new Float32Array(r.map(n=>n/i))}static backward(t,e){let r=u.forward(t),i=new Float32Array(t.length);for(let n=0;n<t.length;n++)i[n]=r[n]-e[n];return i}},fe=class{forward(t,e){let r=e instanceof Float32Array?e:new Float32Array(e),i=0;for(let n=0;n<t.length;n++){let s=t[n]-r[n];i+=s*s}return i/t.length}backward(t,e){let r=e instanceof Float32Array?e:new Float32Array(e),i=new Float32Array(t.length),n=t.length;for(let s=0;s<n;s++)i[s]=2*(t[s]-r[s])/n;return i}};var vs=class{weights;biases;weightGradients;biasGradients;activation;inputSize;outputSize;lastInput=null;lastPreActivation=null;lastOutput=null;constructor(t){this.inputSize=t.inputSize,this.outputSize=t.outputSize,this.activation=t.activation;let e=Math.sqrt(2/(this.inputSize+this.outputSize));this.weights=new Float32Array(this.inputSize*this.outputSize),this.biases=new Float32Array(this.outputSize),this.weightGradients=new Float32Array(this.inputSize*this.outputSize),this.biasGradients=new Float32Array(this.outputSize);for(let r=0;r<this.weights.length;r++)this.weights[r]=(L()*2-1)*e;for(let r=0;r<this.biases.length;r++)this.biases[r]=0}forward(t){this.lastInput=t;let e=new Float32Array(this.outputSize),r=new Float32Array(this.outputSize);for(let i=0;i<this.outputSize;i++){let n=this.biases[i];for(let s=0;s<this.inputSize;s++)n+=t[s]*this.weights[i*this.inputSize+s];r[i]=n,e[i]=this.activation.forward(n)}return this.lastPreActivation=r,this.lastOutput=e,e}backward(t){if(!this.lastInput||!this.lastPreActivation)throw new Error("Must call forward before backward");let e=new Float32Array(this.outputSize);for(let i=0;i<this.outputSize;i++)e[i]=this.activation.backward(this.lastPreActivation[i])*t[i];for(let i=0;i<this.outputSize;i++){for(let n=0;n<this.inputSize;n++)this.weightGradients[i*this.inputSize+n]+=e[i]*this.lastInput[n];this.biasGradients[i]+=e[i]}let r=new Float32Array(this.inputSize);for(let i=0;i<this.inputSize;i++)for(let n=0;n<this.outputSize;n++)r[i]+=e[n]*this.weights[n*this.inputSize+i];return r}update(t){for(let e=0;e<this.weights.length;e++)this.weights[e]-=t*this.weightGradients[e],this.weightGradients[e]=0;for(let e=0;e<this.biases.length;e++)this.biases[e]-=t*this.biasGradients[e],this.biasGradients[e]=0}getParameters(){return{weights:Array.from(this.weights),biases:Array.from(this.biases)}}setParameters(t){this.weights=new Float32Array(t.weights),this.biases=new Float32Array(t.biases),this.weightGradients=new Float32Array(this.weights.length),this.biasGradients=new Float32Array(this.biases.length)}},q=class u{layers=[];learningRate;constructor(t){this.learningRate=t.learningRate||.001;for(let e=0;e<t.layerSizes.length-1;e++){let r=new vs({inputSize:t.layerSizes[e],outputSize:t.layerSizes[e+1],activation:t.activations[e]||new _});this.layers.push(r)}}forward(t){let e=t instanceof Float32Array?t:new Float32Array(t);for(let r of this.layers)e=r.forward(e);return e}backward(t){let e=t;for(let r=this.layers.length-1;r>=0;r--)e=this.layers[r].backward(e)}train(t,e,r){let i=this.forward(t),n=e instanceof Float32Array?e:new Float32Array(e),s=r.forward(i,n),a=r.backward(i,n);this.backward(a);for(let o of this.layers)o.update(this.learningRate);return s}trainBatch(t,e,r){let i=0;for(let n of this.layers)n.weightGradients.fill(0),n.biasGradients.fill(0);for(let n=0;n<t.length;n++){let s=t[n]instanceof Float32Array?t[n]:new Float32Array(t[n]),a=e[n]instanceof Float32Array?e[n]:new Float32Array(e[n]),o=this.forward(s),c=r.forward(o,a);i+=c;let l=r.backward(o,a);this.backward(l)}for(let n of this.layers){for(let s=0;s<n.weightGradients.length;s++)n.weightGradients[s]/=t.length;for(let s=0;s<n.biasGradients.length;s++)n.biasGradients[s]/=t.length;n.update(this.learningRate)}return i/t.length}getParameters(){return{layers:this.layers.map(t=>t.getParameters())}}setParameters(t){for(let e=0;e<this.layers.length&&e<t.layers.length;e++)this.layers[e].setParameters(t.layers[e])}clone(){let t=new u({layerSizes:[this.layers[0].inputSize,...this.layers.map(e=>e.outputSize)],activations:this.layers.map(e=>e.activation),learningRate:this.learningRate});return t.setParameters(this.getParameters()),t}softUpdate(t,e){for(let r=0;r<this.layers.length;r++){let i=this.layers[r],n=t.layers[r];for(let s=0;s<i.weights.length;s++)i.weights[s]=e*n.weights[s]+(1-e)*i.weights[s];for(let s=0;s<i.biases.length;s++)i.biases[s]=e*n.biases[s]+(1-e)*i.biases[s]}}};se();var Je=class{buffer=[];maxSize;priorities=null;usePrioritized;alpha=.6;beta=.4;betaIncrement=.001;epsilon=1e-6;constructor(t,e=!1){this.maxSize=t,this.usePrioritized=e,e&&(this.priorities=new Float32Array(t),this.priorities.fill(1))}add(t){this.buffer.length>=this.maxSize&&(this.buffer.shift(),this.priorities&&(this.priorities.set(this.priorities.slice(1)),this.priorities[this.maxSize-1]=1)),this.buffer.push(t)}addBatch(t){for(let e of t)this.add(e)}sample(t){if(this.buffer.length===0)return[];if(this.usePrioritized&&this.priorities)return this.samplePrioritized(t);let e=[],r=new Set;for(;r.size<Math.min(t,this.buffer.length);)r.add(ue(0,this.buffer.length));for(let i of r)e.push(this.buffer[i]);return e}samplePrioritized(t){let e=this.getPriorities(),r=[],i=[];for(let n=0;n<Math.min(t,this.buffer.length);n++){let s=L()*e.reduce((o,c)=>o+c,0),a=0;for(let o=0;o<e.length;o++)if(a+=e[o],s<=a){r.push(o);break}}for(let n of r)n<this.buffer.length&&i.push(this.buffer[n]);return this.beta=Math.min(1,this.beta+this.betaIncrement),i}getPriorities(){if(!this.priorities)return[];let t=[],e=this.priorities.reduce((r,i)=>r+Math.pow(i,this.alpha),0);for(let r=0;r<this.buffer.length;r++)t.push(Math.pow(this.priorities[r],this.alpha)/e);return t}updatePriorities(t,e){if(!(!this.priorities||!this.usePrioritized))for(let r=0;r<t.length;r++){let i=t[r],n=e[r];i<this.priorities.length&&(this.priorities[i]=Math.abs(n)+this.epsilon)}}getImportanceWeights(t){if(!this.usePrioritized||!this.priorities)return new Array(t.length).fill(1);let e=[],r=this.getPriorities(),i=this.getMaxImportanceWeight();for(let n of t)if(n<r.length&&r[n]>0){let s=Math.pow(this.buffer.length*r[n],-this.beta);e.push(s/i)}else e.push(1);return e}getMaxImportanceWeight(){if(!this.usePrioritized||!this.priorities)return 1;let t=this.getPriorities(),e=0;for(let r of t)if(r>0){let i=Math.pow(this.buffer.length*r,-this.beta);e=Math.max(e,i)}return e}size(){return this.buffer.length}isReady(t){return this.buffer.length>=t}clear(){this.buffer=[],this.priorities&&this.priorities.fill(1)}getAll(){return[...this.buffer]}getStats(){return{size:this.buffer.length,maxSize:this.maxSize,utilization:this.buffer.length/this.maxSize,usePrioritized:this.usePrioritized}}};var pg={stateSize:10,actionSize:4,hiddenLayers:[128,128],targetUpdateFreq:100,minReplaySize:100,doubleDQN:!0,maxGradNorm:1},bs=class extends oe{qNetwork;targetNetwork;replayBufferClass;qConfig;updateCount=0;actions=[];constructor(t={},e=fu){super("q-learning","value-based",{},e),this.qConfig={...pg,...t},this.qNetwork=new q({layerSizes:[this.qConfig.stateSize,...this.qConfig.hiddenLayers,this.qConfig.actionSize],activations:Array(this.qConfig.hiddenLayers.length).fill(new _).concat([new B]),learningRate:this.config.learningRate}),this.targetNetwork=this.qNetwork.clone(),this.replayBufferClass=new Je(this.config.replayBufferSize,!1),this.initializeActions()}async predict(t){this.initialized||await this.initialize();let e=this.prepareState(t),r=this.targetNetwork.forward(e),i=this.argmax(r),n=this.actions[i],s=r[i],a=this.calculateConfidence(r);return{action:n,confidence:a,value:s,reasoning:this.generateReasoning(t,n,s,a)}}async trainCore(t){for(let i of t)this.replayBufferClass.add(i);if(!this.replayBufferClass.isReady(this.qConfig.minReplaySize))return this.getStats();let e=this.replayBufferClass.sample(this.config.batchSize);if(e.length===0)return this.getStats();let r=0;for(let i of e){let n=this.prepareState(i.state),s=this.prepareState(i.nextState),a,o=this.qNetwork.forward(n),c=this.actionToIndex(i.action);if(this.qConfig.doubleDQN&&!i.done){let m=this.qNetwork.forward(s),h=this.argmax(m),b=this.targetNetwork.forward(s)[h];a=i.reward+this.config.discountFactor*b}else{let m=this.targetNetwork.forward(s),h=Math.max(...m);a=i.reward+this.config.discountFactor*h*(i.done?0:1)}let l=new Float32Array(o.length);for(let m=0;m<l.length;m++)l[m]=m===c?a:o[m];let d=this.qNetwork.train(n,l,new fe);r+=Math.abs(d)}return this.updateCount++,this.updateCount%this.qConfig.targetUpdateFreq===0&&this.updateTargetNetwork(),{episode:this.episodeCount,totalReward:this.totalReward,averageReward:this.rewardHistory.reduce((i,n)=>i+n,0)/this.rewardHistory.length,loss:r/e.length,explorationRate:this.config.explorationRate,trainingTimeMs:0,timestamp:new Date}}getAlgorithmInfo(){return{type:this.type,category:this.category,version:"2.0.0",description:"Neural Q-Learning (DQN) for Coverage Path Optimization",capabilities:["Deep Q-Network for function approximation","Experience replay for stable learning","Target network for consistent targets","Double DQN for reduced overestimation","Coverage-aware test prioritization"],hyperparameters:{stateSize:this.qConfig.stateSize,actionSize:this.qConfig.actionSize,hiddenLayers:this.qConfig.hiddenLayers.join(","),targetUpdateFreq:this.qConfig.targetUpdateFreq,doubleDQN:String(this.qConfig.doubleDQN)},stats:this.stats}}updateTargetNetwork(){this.targetNetwork=this.qNetwork.clone()}prepareState(t){let e=t.features.slice(0,this.qConfig.stateSize);for(;e.length<this.qConfig.stateSize;)e.push(0);let r=Math.max(...e.map(Math.abs));if(r>0)for(let i=0;i<e.length;i++)e[i]=e[i]/r;return new Float32Array(e)}initializeActions(){this.actions=[{type:"generate-unit",value:"standard"},{type:"generate-integration",value:"standard"},{type:"prioritize",value:"high"},{type:"skip",value:0}],this.qConfig.actionSize=this.actions.length,this.qNetwork=new q({layerSizes:[this.qConfig.stateSize,...this.qConfig.hiddenLayers,this.qConfig.actionSize],activations:Array(this.qConfig.hiddenLayers.length).fill(new _).concat([new B]),learningRate:this.config.learningRate}),this.targetNetwork=this.qNetwork.clone()}actionToIndex(t){let e=this.actionToKey(t);for(let r=0;r<this.actions.length;r++)if(this.actionToKey(this.actions[r])===e)return r;return 0}indexToAction(t){return this.actions[Math.min(t,this.actions.length-1)]}argmax(t){let e=0,r=t[0];for(let i=1;i<t.length;i++)t[i]>r&&(r=t[i],e=i);return e}actionToKey(t){return`${t.type}:${JSON.stringify(t.value)}`}calculateConfidence(t){let e=Math.max(...t),r=Math.min(...t);if(e===r)return .5;let i=e-r;return Math.min(1,.3+i*2)}generateReasoning(t,e,r,i){return this.episodeCount<10?`Neural Q-Learning exploration phase (episode ${this.episodeCount}): ${e.type} action`:i>.8?`High-confidence Neural Q-Learning decision (${i.toFixed(2)}): ${e.type} with Q-value ${r.toFixed(3)} based on ${this.updateCount} network updates`:r>.5?`Positive Q-value (${r.toFixed(3)}) suggests ${e.type} is effective for current coverage state`:`Exploratory Neural Q-Learning action: ${e.type} with confidence ${i.toFixed(2)}`}async exportCustomData(){return{qNetwork:this.qNetwork.getParameters(),targetNetwork:this.targetNetwork.getParameters(),qConfig:this.qConfig,updateCount:this.updateCount,replayBufferSize:this.replayBufferClass.size()}}async importCustomData(t){t.qNetwork&&this.qNetwork.setParameters(t.qNetwork),t.targetNetwork&&this.targetNetwork.setParameters(t.targetNetwork),t.qConfig&&(this.qConfig={...this.qConfig,...t.qConfig}),typeof t.updateCount=="number"&&(this.updateCount=t.updateCount),this.initialized=!0}async resetAlgorithm(){this.qNetwork=new q({layerSizes:[this.qConfig.stateSize,...this.qConfig.hiddenLayers,this.qConfig.actionSize],activations:Array(this.qConfig.hiddenLayers.length).fill(new _).concat([new B]),learningRate:this.config.learningRate}),this.targetNetwork=this.qNetwork.clone(),this.replayBufferClass.clear(),this.updateCount=0}};var hg={maxConcurrentWorkflows:5,defaultTimeout:6e4,publishEvents:!0,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},$e=R.create("coverage-analysis"),Ai=class extends Q{constructor(e,r,i={},n){let s={...hg,...i};super(e,"coverage-analysis",s,{verifyFindingTypes:["coverage-gap","risk-zone","quality-regression"],...s.consensusConfig});this.memory=r;this.coverageAnalyzer=new ht({memory:r,llmRouter:n}),this.gapDetector=new lr({memory:r,llmRouter:n}),this.riskScorer=new ur(r),this.qLearning=new bs(this.qlConfig,yu)}memory;coverageAnalyzer;gapDetector;riskScorer;ghostAnalyzer=null;qLearning;qlConfig={stateSize:12,actionSize:4,hiddenLayers:[128,64],targetUpdateFreq:50,minReplaySize:50,doubleDQN:!0};async onInitialize(){}async onDispose(){}subscribeToEvents(){}async getQLRecommendations(e,r=10){try{let i=[];for(let a of e.slice(0,r)){let o=await this.predictQL(a),c=this.actionToTestType(o.action),l=this.estimateCoverageGain(a,o.action),d=this.estimateTestDuration(a,c);i.push({filePath:a.file,testType:c,priority:o.value,estimatedCoverageGain:l,estimatedDuration:d,action:o.action,confidence:o.confidence})}i.sort((a,o)=>o.priority-a.priority);let n=i.reduce((a,o)=>a+o.estimatedCoverageGain,0),s=i.reduce((a,o)=>a+o.estimatedDuration,0);return f({tests:i,totalEstimatedCoverageGain:n,totalEstimatedDuration:s,reasoning:`Q-Learning prioritized ${i.length} tests based on coverage optimization potential`})}catch(i){return p(y(i))}}async predictQL(e){try{let r=this.gapToQLState(e),i=await this.qLearning.predict(r),n=this.estimateCoverageGain(e,i.action),s=this.actionToTestCount(i.action);return{action:i.action,confidence:i.confidence,value:i.value||0,reasoning:i.reasoning||"",estimatedCoverageGain:n,estimatedTestCount:s}}catch(r){return{action:{type:"generate-unit",value:"standard"},confidence:.3,value:0,reasoning:`Fallback prediction due to error: ${r.message}`,estimatedCoverageGain:.1,estimatedTestCount:1}}}async trainQL(e){try{await this.qLearning.trainBatch([e]);let r=this.qLearning.getStats();r.episode%10===0&&await this.memory.set("coverage:ql:model:latest",{stats:r,exportedAt:new Date().toISOString()})}catch(r){$e.error("Failed to train Q-Learning model",r instanceof Error?r:void 0)}}gapToQLState(e){let r=[e.riskScore/10,Math.min(1,e.lines.length/50),Math.min(1,e.branches.length/10),this.severityToNumber(e.severity)/4,this.complexityFromPath(e.file),this.changeFrequencyFromPath(e.file),this.businessCriticalityFromPath(e.file),e.lines.length/Math.max(1,e.branches.length),this.calculateCoveragePotential(e),this.calculateFileComplexityScore(e),this.calculateTestComplexity(e),this.calculateExecutionCost(e)];return{id:e.id,features:r,metadata:{filePath:e.file,lines:e.lines,branches:e.branches,riskScore:e.riskScore,severity:e.severity},timestamp:new Date}}estimateCoverageGain(e,r){let i=(e.lines.length+e.branches.length*2)/1e3;switch(r.type){case"generate-unit":return i*.3;case"generate-integration":return i*.5;case"prioritize":return i*.7;case"skip":return 0;default:return i*.2}}estimateTestDuration(e,r){let i=e.lines.length*.5;switch(r){case"unit":return i;case"integration":return i*2;case"e2e":return i*5;default:return i}}actionToTestType(e){switch(e.type){case"generate-unit":return"unit";case"generate-integration":return"integration";case"prioritize":return"integration";default:return"unit"}}actionToTestCount(e){switch(e.type){case"generate-unit":return 3;case"generate-integration":return 2;case"prioritize":return 5;case"skip":return 0;default:return 1}}calculateCoveragePotential(e){let r=Math.min(1,e.lines.length/50),i=Math.min(1,e.branches.length/10),n=e.riskScore/10;return(r+i+n)/3}calculateFileComplexityScore(e){let i=e.file.split("/").length,n=/service|controller|provider|manager/i.test(e.file);return Math.min(1,(i+(n?2:0))/10)}calculateTestComplexity(e){let r=e.branches.length*.6,i=e.lines.length*.1;return Math.min(1,(r+i)/20)}calculateExecutionCost(e){let r=Math.min(1,e.lines.length/100),i=e.riskScore/10;return(r+i)/2}complexityFromPath(e){return["service","controller","provider","manager","handler"].some(n=>e.toLowerCase().includes(n))?.7:.3}changeFrequencyFromPath(e){return["src","lib","services","controllers"].some(n=>e.includes(n))?.6:.2}businessCriticalityFromPath(e){return["auth","payment","user","core","api"].some(n=>e.toLowerCase().includes(n))?.8:.4}isReady(){return this.initialized}async analyze(e){try{if(this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&$e.warn("Topology degraded, using conservative analysis mode"),this.minCutMixin.shouldPauseOperations())return p(new Error("Coverage analysis paused: topology is in critical state"));let r=await this.coverageAnalyzer.analyze(e);return r.success&&await this.publishCoverageReport(r.value),r}catch(r){return p(y(r))}}async detectGaps(e){try{if(this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&$e.warn("Topology degraded, using conservative gap detection"),this.minCutMixin.shouldPauseOperations())return p(new Error("Gap detection paused: topology is in critical state"));let r=await this.gapDetector.detectGaps(e);if(r.success){let i=[];for(let n of r.value.gaps){if(this.config.enableConsensus&&(n.severity==="critical"||n.severity==="high")){let s=Math.min(.95,n.riskScore/10+.3);if(!await this.verifyCoverageGap(n,s)){$e.info(`Coverage gap in '${n.file}' not verified, skipping publication`);continue}}i.push(n)}return await this.publishGapEvents(i),f({...r.value,gaps:i})}return r}catch(r){return p(y(r))}}async calculateRisk(e){try{if(this.minCutMixin.shouldPauseOperations())return p(new Error("Risk calculation paused: topology is in critical state"));let r=await this.riskScorer.calculateRisk(e);if(r.success){if(this.config.enableConsensus&&(r.value.riskLevel==="critical"||r.value.riskLevel==="high")&&!await this.verifyRiskZone({file:r.value.file,riskScore:r.value.overallRisk,factors:r.value.factors.map(n=>({name:n.name,weight:n.contribution}))},Math.min(.95,r.value.overallRisk/10+.5)))return $e.warn(`Risk zone '${r.value.file}' not verified, downgrading severity`),f({...r.value,riskLevel:r.value.riskLevel==="critical"?"high":"medium"});r.value.riskLevel==="critical"&&await this.publishRiskZoneEvent(r.value)}return r}catch(r){return p(y(r))}}async getTrend(e){try{let{timeRange:r,granularity:i}=e,n=await this.memory.search("coverage:history:*",100);if(n.length===0)return f({dataPoints:[],trend:"stable",forecast:0});let s=[];for(let l of n){let d=parseInt(l.split(":").pop()||"0",10),m=new Date(d);if(m>=r.start&&m<=r.end){let h=await this.memory.get(l);h&&s.push({date:m,coverage:h})}}s.sort((l,d)=>l.date.getTime()-d.date.getTime());let a=this.aggregateByGranularity(s,i),o=this.analyzeCoverageTrend(a),c=this.forecastCoverage(a);return f({dataPoints:a,trend:o,forecast:c})}catch(r){return p(y(r))}}async findSimilar(e){try{let{pattern:r,k:i}=e,n=Date.now(),s=this.createGapEmbedding(r),a=await this.memory.vectorSearch(s,i),o=[];for(let l of a){let d=l.metadata;d&&o.push({gap:{id:l.key,file:d.file||"unknown",lines:[],branches:[],riskScore:d.riskScore||0,severity:d.severity||"low",recommendation:"Similar pattern found in codebase"},similarity:l.score})}let c=Date.now()-n;return f({patterns:o,searchTime:c})}catch(r){return p(y(r))}}async analyzeGhostCoverage(e,r){try{if(!this.ghostAnalyzer){let d={hnswIndex:$r(this.memory),embedder:Si()};this.ghostAnalyzer=new Ti(d),await this.ghostAnalyzer.initialize()}let i={files:e.map(d=>({path:d,lines:{covered:0,total:100},branches:{covered:0,total:10},functions:{covered:0,total:5},statements:{covered:0,total:100},uncoveredLines:[],uncoveredBranches:[]})),summary:{line:0,branch:0,function:0,statement:0,files:e.length}},n={name:r,sourcePatterns:e},s=await this.ghostAnalyzer.computePhantomSurface(i,n);if(!s.success)return p(s.error);let a=s.value,o=await this.ghostAnalyzer.detectPhantomGaps(a),l={gaps:(o.success?o.value:[]).map(d=>({id:d.id,category:d.category,description:d.description,confidence:d.confidence,severity:d.severity,suggestedTest:d.suggestedLines.length>0?`Add test covering lines ${d.suggestedLines.join(", ")} in ${d.file}`:`Add ${d.category} test for ${d.file}`})),totalGhostScore:a.phantomRatio,coverageCompleteness:1-a.phantomRatio,computedAt:new Date(a.computedAt)};return f(l)}catch(i){return p(y(i))}}async publishCoverageReport(e){let r={reportId:crypto.randomUUID(),line:e.summary.line,branch:e.summary.branch,function:e.summary.function,statement:e.summary.statement,files:e.summary.files},i=I(rn.CoverageReportCreated,"coverage-analysis",r);await this.eventBus.publish(i)}async publishGapEvents(e){let r=e.filter(i=>i.severity==="critical"||i.severity==="high");for(let i of r){let n={gapId:i.id,file:i.file,uncoveredLines:i.lines,uncoveredBranches:i.branches,riskScore:i.riskScore},s=I(rn.CoverageGapDetected,"coverage-analysis",n);await this.eventBus.publish(s)}}async publishRiskZoneEvent(e){let r=I(rn.RiskZoneIdentified,"coverage-analysis",{file:e.file,overallRisk:e.overallRisk,riskLevel:e.riskLevel,topFactors:e.factors.slice(0,3).map(i=>i.name),recommendations:e.recommendations});await this.eventBus.publish(r)}aggregateByGranularity(e,r){if(e.length===0)return[];let i=new Map;for(let s of e){let a=this.getBucketKey(s.date,r),o=i.get(a)||[];o.push(s),i.set(a,o)}let n=[];for(let[,s]of i)if(s.length>0){let a={line:s.reduce((o,c)=>o+c.coverage.line,0)/s.length,branch:s.reduce((o,c)=>o+c.coverage.branch,0)/s.length,function:s.reduce((o,c)=>o+c.coverage.function,0)/s.length,statement:s.reduce((o,c)=>o+c.coverage.statement,0)/s.length,files:Math.round(s.reduce((o,c)=>o+c.coverage.files,0)/s.length)};n.push({date:s[0].date,coverage:a})}return n.sort((s,a)=>s.date.getTime()-a.date.getTime())}getBucketKey(e,r){let i=e.getFullYear(),n=e.getMonth(),s=e.getDate();switch(r){case"daily":return`${i}-${n}-${s}`;case"weekly":{let a=Math.floor(s/7);return`${i}-${n}-W${a}`}case"monthly":return`${i}-${n}`}}analyzeCoverageTrend(e){if(e.length<2)return"stable";let r=e.map(l=>{let d=l.coverage;return(d.line+d.branch+d.function+d.statement)/4}),i=r.length,n=0,s=0,a=0,o=0;for(let l=0;l<i;l++)n+=l,s+=r[l],a+=l*r[l],o+=l*l;let c=(i*a-n*s)/(i*o-n*n);return c>.5?"improving":c<-.5?"declining":"stable"}forecastCoverage(e){if(e.length===0)return 0;let r=e.map(a=>{let o=a.coverage;return(o.line+o.branch+o.function+o.statement)/4});if(r.length===1)return r[0];let i=.3,n=r[0];for(let a=1;a<r.length;a++)n=i*r[a]+(1-i)*n;let s=this.analyzeCoverageTrend(e);return s==="improving"?n=Math.min(100,n+2):s==="declining"&&(n=Math.max(0,n-2)),n}createGapEmbedding(e){let i=new Array(384).fill(0);i[0]=e.riskScore,i[1]=Math.min(1,e.lines.length/100),i[2]=Math.min(1,e.branches.length/20),i[3]=this.severityToNumber(e.severity)/4;let n=e.file.split("").reduce((s,a)=>s+a.charCodeAt(0),0);i[4]=n%1e3/1e3;for(let s=5;s<384;s++)i[s]=Math.sin(s*e.riskScore)*.5+.5;return i}severityToNumber(e){switch(e){case"critical":return 4;case"high":return 3;case"medium":return 2;case"low":return 1;default:return 0}}async verifyCoverageGap(e,r){let i=V({id:v(),type:"coverage-gap",confidence:r,description:`Verify coverage gap in ${e.file}: ${e.lines.length} uncovered lines, ${e.branches.length} uncovered branches`,payload:e,detectedBy:"coverage-analysis-coordinator",severity:e.severity});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?($e.info(`Coverage gap in '${e.file}' verified by consensus`),!0):($e.warn(`Coverage gap in '${e.file}' NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}async verifyRiskZone(e,r){let i=V({id:v(),type:"risk-zone",confidence:r,description:`Verify risk zone: ${e.file} with risk score ${e.riskScore.toFixed(2)}`,payload:e,detectedBy:"coverage-analysis-coordinator",severity:e.riskScore>=.8?"critical":e.riskScore>=.5?"high":"medium"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?($e.info(`Risk zone '${e.file}' classification verified by consensus`),!0):($e.warn(`Risk zone '${e.file}' classification NOT verified`),!1)}return!0}async verifyQualityRegression(e,r){let i=V({id:v(),type:"quality-regression",confidence:r,description:`Verify quality regression: ${e.metric} dropped from ${e.previousValue.toFixed(1)}% to ${e.currentValue.toFixed(1)}% (threshold: ${e.threshold}%)`,payload:e,detectedBy:"coverage-analysis-coordinator",severity:"critical"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?($e.info("Quality regression verified by consensus"),!0):($e.warn(`Quality regression NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}};var ws=class u extends j{static VERSION="1.0.0";coordinator;_activeAnalyses=0;constructor(t,e,r){super(t,e),this.coordinator=new Ai(t,e,{},r)}get name(){return"coverage-analysis"}get version(){return u.VERSION}get dependencies(){return["test-execution"]}getAPI(){return this.coordinator}getCoverageAPI(){return this.coordinator}getTaskHandlers(){return new Map([["analyze-coverage",async t=>{let e=t.coverageData;if(!e)return p(new Error("Invalid analyze-coverage payload: missing coverageData"));this._activeAnalyses++,this.updateAgentMetrics();try{return await this.coordinator.analyze({coverageData:e,threshold:t.threshold,includeFileDetails:t.includeFileDetails})}finally{this._activeAnalyses--,this.updateAgentMetrics()}}],["detect-gaps",async t=>{let e=t.coverageData;if(!e)return p(new Error("Invalid detect-gaps payload: missing coverageData"));this._activeAnalyses++,this.updateAgentMetrics();try{return await this.coordinator.detectGaps({coverageData:e,minCoverage:t.minCoverage,prioritize:t.prioritize})}finally{this._activeAnalyses--,this.updateAgentMetrics()}}],["calculate-risk",async t=>{let e=t.file,r=t.uncoveredLines;if(!e||!r)return p(new Error("Invalid calculate-risk payload: missing file or uncoveredLines"));this._activeAnalyses++,this.updateAgentMetrics();try{return await this.coordinator.calculateRisk({file:e,uncoveredLines:r,factors:t.factors})}finally{this._activeAnalyses--,this.updateAgentMetrics()}}],["analyze-ghost-coverage",async t=>{let e=t.existingTests,r=t.codeContext;if(!e||!r)return p(new Error("Invalid analyze-ghost-coverage payload: missing existingTests or codeContext"));this._activeAnalyses++,this.updateAgentMetrics();try{return await this.coordinator.analyzeGhostCoverage(e,r)}finally{this._activeAnalyses--,this.updateAgentMetrics()}}]])}async onInitialize(){await this.coordinator.initialize(),this.updateHealth({status:"idle",lastActivity:new Date})}async onDispose(){await this.coordinator.dispose(),this.updateHealth({status:"unhealthy",agents:{total:0,active:0,idle:0,failed:0}})}subscribeToEvents(){this.eventBus.subscribe(Pe.TestRunCompleted,this.handleTestRunCompleted.bind(this))}async onEvent(t){t.type===Pe.TestRunCompleted&&await this.handleTestRunCompleted(t)}async handleTestRunCompleted(t){let e=t.payload;if(e.coverageData){this._activeAnalyses++,this.updateAgentMetrics();try{await this.coordinator.analyze({coverageData:e.coverageData,includeFileDetails:!0})}finally{this._activeAnalyses--,this.updateAgentMetrics()}}}updateAgentMetrics(){let t={status:(this._activeAnalyses>0,"healthy"),agents:{total:3,active:this._activeAnalyses>0?1:0,idle:this._activeAnalyses>0?2:3,failed:0},lastActivity:new Date,errors:[]};this.updateHealth(t)}getHealth(){return{...this._health,agents:{total:3,active:this._activeAnalyses>0?1:0,idle:this._activeAnalyses>0?2:3,failed:0},lastActivity:new Date}}};function oc(u,t,e){return new ws(u,t,e)}M();A();A();var gg={strictMode:!1,enableWarnings:!0,defaultSeverities:{coverage:"high",testsPassing:"critical",criticalBugs:"critical",codeSmells:"medium",securityVulnerabilities:"critical",technicalDebt:"medium",duplications:"low"}},fg={strict:{coverage:{min:90},testsPassing:{min:100},criticalBugs:{max:0},codeSmells:{max:10},securityVulnerabilities:{max:0},technicalDebt:{max:2},duplications:{max:3}},standard:{coverage:{min:80},testsPassing:{min:95},criticalBugs:{max:0},codeSmells:{max:20},securityVulnerabilities:{max:0},technicalDebt:{max:5},duplications:{max:5}},relaxed:{coverage:{min:60},testsPassing:{min:90},criticalBugs:{max:2},codeSmells:{max:50},securityVulnerabilities:{max:1},technicalDebt:{max:10},duplications:{max:10}}},gt=class{constructor(t,e={}){this.memory=t;this.config={...gg,...e};for(let[r,i]of Object.entries(fg))this.presets.set(r,i)}memory;config;presets=new Map;async evaluateGate(t){try{let{gateName:e,metrics:r,thresholds:i}=t;if(!r)return p(new Error("No metrics provided for gate evaluation"));let n=[],s=[];n.push(...this.evaluateMinThresholds(r,i)),n.push(...this.evaluateMaxThresholds(r,i));for(let l of n)l.passed||s.push(l.name);let a=this.calculateOverallScore(n),o=this.determineGateStatus(n),c={gateName:e,passed:o,checks:n,overallScore:a,failedChecks:s};return await this.storeEvaluationResult(c),f(c)}catch(e){return p(y(e))}}async createGatePreset(t,e){try{let r=`preset-${t}-${v().slice(0,8)}`;return this.presets.set(t,e),await this.memory.set(`quality-gate:preset:${t}`,{id:r,name:t,thresholds:e,createdAt:new Date().toISOString()},{namespace:"quality-assessment",persist:!0}),f(r)}catch(r){return p(y(r))}}async getGatePreset(t){if(this.presets.has(t))return this.presets.get(t);let e=await this.memory.get(`quality-gate:preset:${t}`);if(e)return this.presets.set(t,e.thresholds),e.thresholds}async listGatePresets(){let t=await this.memory.search("quality-gate:preset:*",100),e=new Set(Array.from(this.presets.keys()));for(let r of t){let i=r.replace("quality-gate:preset:","");e.add(i)}return Array.from(e)}evaluateMinThresholds(t,e){let r=[];return e.coverage?.min!==void 0&&r.push(this.createCheck("coverage",t.coverage,e.coverage.min,"min",this.config.defaultSeverities.coverage)),e.testsPassing?.min!==void 0&&r.push(this.createCheck("testsPassing",t.testsPassing,e.testsPassing.min,"min",this.config.defaultSeverities.testsPassing)),r}evaluateMaxThresholds(t,e){let r=[];return e.criticalBugs?.max!==void 0&&r.push(this.createCheck("criticalBugs",t.criticalBugs,e.criticalBugs.max,"max",this.config.defaultSeverities.criticalBugs)),e.codeSmells?.max!==void 0&&r.push(this.createCheck("codeSmells",t.codeSmells,e.codeSmells.max,"max",this.config.defaultSeverities.codeSmells)),e.securityVulnerabilities?.max!==void 0&&r.push(this.createCheck("securityVulnerabilities",t.securityVulnerabilities,e.securityVulnerabilities.max,"max",this.config.defaultSeverities.securityVulnerabilities)),e.technicalDebt?.max!==void 0&&r.push(this.createCheck("technicalDebt",t.technicalDebt,e.technicalDebt.max,"max",this.config.defaultSeverities.technicalDebt)),e.duplications?.max!==void 0&&r.push(this.createCheck("duplications",t.duplications,e.duplications.max,"max",this.config.defaultSeverities.duplications)),r}createCheck(t,e,r,i,n){let s=i==="min"?e>=r:e<=r;return{name:t,passed:s,value:e,threshold:r,severity:n}}calculateOverallScore(t){if(t.length===0)return 100;let e={critical:3,high:2,medium:1.5,low:1,info:.5},r=0,i=0;for(let n of t){let s=e[n.severity];r+=s,n.passed&&(i+=s)}return r>0?Math.round(i/r*100):100}determineGateStatus(t){return this.config.strictMode?t.every(e=>e.passed):t.filter(e=>e.severity==="critical"||e.severity==="high").every(e=>e.passed)}async storeEvaluationResult(t){let e=`quality-gate:evaluation:${t.gateName}:${Date.now()}`;await this.memory.set(e,{...t,evaluatedAt:new Date().toISOString()},{namespace:"quality-assessment",ttl:86400*30})}};M();er();var Cs=class{parser;fileReader;constructor(){this.parser=new zr,this.fileReader=new Fe}async analyzeFile(t){let e=await this.fileReader.readFile(t);if(!e.success)return null;let r=e.value,i=r.split(`
|
|
2615
2615
|
`),{codeLines:n,commentLines:s,blankLines:a}=this.countLines(i),o=t.split("/").pop()||t,c=o.split(".").pop()||"",l=1,d=0,m=0,h=0,g=0;if(["ts","tsx","js","jsx"].includes(c))try{let C=this.parser.parseFile(o,r),S=this.parser.extractFunctions(C);h=S.length;for(let P of S){let O=this.analyzeFunctionComplexity(r,P);l+=O.cyclomaticComplexity-1,d+=O.cognitiveComplexity,m=Math.max(m,this.calculateNestingDepth(r,P))}let k=this.parser.extractClasses(C);g=k.length;for(let P of k)for(let O of P.methods){let z=this.analyzeFunctionComplexity(r,O);l+=z.cyclomaticComplexity-1,d+=z.cognitiveComplexity}}catch{l=this.estimateCyclomaticComplexity(r),d=this.estimateCognitiveComplexity(r)}else{l=this.estimateCyclomaticComplexity(r),d=this.estimateCognitiveComplexity(r);let C=nt(c);if(C&&C!=="typescript"&&C!=="javascript"&&Nr.supportsLanguage(C))try{let S=await Nr.parseFile(r,t,C);S&&(h=S.functions.length,g=S.classes.length)}catch{h=(r.match(/function\s|def\s|func\s|fn\s/g)||[]).length,g=(r.match(/class\s|struct\s|interface\s/g)||[]).length}else h=(r.match(/function\s|def\s|func\s|fn\s/g)||[]).length,g=(r.match(/class\s|struct\s|interface\s/g)||[]).length}let b=this.calculateHalsteadMetrics(r),w=this.calculateMaintainabilityIndex(b.volume,l,n);return{path:t,linesOfCode:n,linesOfComments:s,blankLines:a,cyclomaticComplexity:l,cognitiveComplexity:d,maintainabilityIndex:w,halsteadMetrics:b,functionCount:h,classCount:g,maxNestingDepth:m}}analyzeFunctionComplexity(t,e){let r=t.split(`
|
|
2616
2616
|
`),i=e.startLine,n=e.endLine,s=r.slice(i-1,n).join(`
|
|
2617
2617
|
`);return{name:e.name,startLine:i,endLine:n,cyclomaticComplexity:this.calculateCyclomaticComplexity(s),cognitiveComplexity:this.calculateCognitiveComplexity(s),parameterCount:"parameters"in e?e.parameters.length:0,linesOfCode:n-i+1}}async detectDuplication(t,e=5){let r=new Map,i=0,n=0;for(let c of t){let l=await this.fileReader.readFile(c);if(l.success){let d=l.value.split(`
|
|
@@ -2619,7 +2619,7 @@ describe('${e} Integration', () => {
|
|
|
2619
2619
|
`);if(m.length<20)continue;let h=this.hashString(m),g=s.get(h)||[];g.push({file:c,line:d+1}),s.set(h,g)}for(let[,c]of s.entries())c.length>1&&(n+=e*(c.length-1),a.push({lines:e,occurrences:c.length,locations:c.map(l=>({file:l.file,startLine:l.line,endLine:l.line+e-1}))}));let o=a.sort((c,l)=>l.occurrences-c.occurrences).slice(0,20);return{percentage:i>0?Math.round(n/i*100*10)/10:0,duplicates:o}}countLines(t){let e=0,r=0,i=0,n=!1;for(let s of t){let a=s.trim();if(a===""){i++;continue}if(n){r++,a.includes("*/")&&(n=!1);continue}a.startsWith("//")?r++:a.startsWith("/*")?(r++,a.includes("*/")||(n=!0)):(e++,(a.includes("//")||a.includes("/*"))&&r++)}return{codeLines:e,commentLines:r,blankLines:i}}calculateCyclomaticComplexity(t){let e=[/\bif\s*\(/g,/\belse\s+if\s*\(/g,/\bfor\s*\(/g,/\bwhile\s*\(/g,/\bcase\s+/g,/\bcatch\s*\(/g,/\?\s*[^:]/g,/&&/g,/\|\|/g,/\?\?/g],r=1;for(let i of e){let n=t.match(i);n&&(r+=n.length)}return r}calculateCognitiveComplexity(t){let e=0,r=0,i=t.split(`
|
|
2620
2620
|
`);for(let n of i){let s=n.trim();/\bif\s*\(/.test(s)&&(e+=1+r,r++),/\belse\s+if\s*\(/.test(s)&&(e+=1+r),/\belse\s*{/.test(s)&&(e+=1),/\bfor\s*\(/.test(s)&&(e+=1+r,r++),/\bwhile\s*\(/.test(s)&&(e+=1+r,r++),/\bswitch\s*\(/.test(s)&&(e+=1+r,r++),/\bcatch\s*\(/.test(s)&&(e+=1+r,r++),/\?\s*[^:]/.test(s)&&(e+=1+r),/&&|\|\|/.test(s)&&(e+=1);let a=(s.match(/{/g)||[]).length,o=(s.match(/}/g)||[]).length;r=Math.max(0,r+a-o)}return e}estimateCyclomaticComplexity(t){return this.calculateCyclomaticComplexity(t)}estimateCognitiveComplexity(t){return this.calculateCognitiveComplexity(t)}calculateNestingDepth(t,e){let i=t.split(`
|
|
2621
2621
|
`).slice(e.startLine-1,e.endLine).join(`
|
|
2622
|
-
`),n=0,s=0;for(let a of i)a==="{"?(s++,n=Math.max(n,s)):a==="}"&&(s=Math.max(0,s-1));return n}calculateHalsteadMetrics(t){let e=new Set,r=new Set,i=0,n=0,s=[/[+\-*/%]=?/g,/[<>]=?/g,/[!=]=?=?/g,/&&|\|\|/g,/\+\+|--/g,/\./g,/,/g,/:/g,/\?/g,/=>/g];for(let k of s){let P=t.match(k);if(P)for(let O of P)e.add(O),i++}let a=/\b[a-zA-Z_][a-zA-Z0-9_]*\b/g,o=new Set(["if","else","for","while","do","switch","case","break","continue","return","function","class","const","let","var","new","this","true","false","null","undefined","typeof","import","export","default","from","async","await","try","catch","finally","throw","interface","type","extends"]),c=t.match(a);if(c)for(let k of c)o.has(k)||(r.add(k),n++);let l=e.size,d=r.size,m=i,h=n,g=l+d,b=m+h,w=b>0&&g>0?b*Math.log2(g):0,C=d>0?l/2*(h/d):0,S=w*C;return{vocabulary:g,length:b,volume:Math.round(w*100)/100,difficulty:Math.round(C*100)/100,effort:Math.round(S*100)/100}}calculateMaintainabilityIndex(t,e,r){if(r<=0||t<=0)return 100;let i=Math.log(t),n=Math.log(r),s=171-5.2*i-.23*e-16.2*n,a=Math.max(0,Math.min(100,s*100/171));return Math.round(a*100)/100}hashString(t){let e=0;for(let r=0;r<t.length;r++){let i=t.charCodeAt(r);e=(e<<5)-e+i,e=e&e}return e.toString(16)}},cc=null;function lc(){return cc||(cc=new Cs),cc}import*as Ye from"os";var Ss=class{lastCpuUsage=null;lastCpuTime=0;metricHistory=new Map;maxHistorySize;constructor(t=1e3){this.maxHistorySize=t}collectSystemMetrics(){let t=this.collectCpuMetrics(),e=this.collectMemoryMetrics(),r=this.collectProcessMetrics(),i={timestamp:new Date,cpu:t,memory:e,process:r};return this.recordMetric("cpu_usage",t.usage),this.recordMetric("memory_usage",e.usage),this.recordMetric("process_cpu_usage",r.cpuUsage),this.recordMetric("process_memory_usage",r.memoryUsage),i}collectCpuMetrics(){let t=Ye.cpus(),e=Ye.loadavg(),r=0,i=0;for(let s of t){for(let a of Object.keys(s.times))i+=s.times[a];r+=s.times.idle}let n=i>0?(i-r)/i*100:0;return{usage:Math.round(n*100)/100,loadAverage:e,cores:t.length}}collectMemoryMetrics(){let t=Ye.totalmem(),e=Ye.freemem(),r=t-e,i=r/t*100;return{usage:Math.round(i*100)/100,total:t,free:e,used:r}}collectProcessMetrics(){let t=process.memoryUsage(),e=process.cpuUsage(this.lastCpuUsage??void 0),r=Date.now(),n=(this.lastCpuTime>0?r-this.lastCpuTime:1e3)*1e3,a=(e.user+e.system)/n*100;this.lastCpuUsage=e,this.lastCpuTime=r;let o=Ye.totalmem(),c=t.rss/o*100;return{cpuUsage:Math.min(100,Math.round(a*100)/100),memoryUsage:Math.round(c*100)/100,heapUsed:t.heapUsed,heapTotal:t.heapTotal,rss:t.rss,uptime:process.uptime()}}getMetricValue(t){let e=this.collectSystemMetrics();switch(t){case"cpu_usage":return e.cpu.usage;case"memory_usage":return e.memory.usage;case"process_cpu_usage":return e.process.cpuUsage;case"process_memory_usage":return e.process.memoryUsage;case"heap_used":return e.process.heapUsed;case"heap_total":return e.process.heapTotal;case"rss":return e.process.rss;case"load_average_1m":return e.cpu.loadAverage[0];case"load_average_5m":return e.cpu.loadAverage[1];case"load_average_15m":return e.cpu.loadAverage[2];default:let r=this.metricHistory.get(t);return r&&r.length>0?r[r.length-1].value:0}}getChaosMetricValue(t){let r={response_time_ms:()=>this.getResponseTimeEstimate(),error_rate:()=>this.getErrorRateEstimate(),throughput:()=>this.getThroughputEstimate(),cpu_usage:()=>this.collectSystemMetrics().cpu.usage,memory_usage:()=>this.collectSystemMetrics().memory.usage,latency_p50:()=>this.getLatencyPercentile(50),latency_p95:()=>this.getLatencyPercentile(95),latency_p99:()=>this.getLatencyPercentile(99)}[t];return r?r():this.getMetricValue(t)}recordMetric(t,e,r){let i={name:t,value:e,timestamp:new Date,labels:r},n=this.metricHistory.get(t)||[];n.push(i),n.length>this.maxHistorySize&&n.shift(),this.metricHistory.set(t,n)}recordHttpMetrics(t){this.recordMetric("response_time_ms",t.responseTimeMs),this.recordMetric("http_status",t.statusCode),this.recordMetric("http_success",t.success?1:0)}getMetricHistory(t,e){let r=this.metricHistory.get(t)||[];return e&&r.length>e?r.slice(-e):[...r]}getMetricAverage(t,e=10){let r=this.getMetricHistory(t,e);return r.length===0?0:r.reduce((n,s)=>n+s.value,0)/r.length}getResponseTimeEstimate(){let t=this.collectSystemMetrics().cpu,e=50,r=1+t.usage/100;return Math.round(e*r)}getErrorRateEstimate(){let t=this.getMetricHistory("http_success",100);return t.length===0?0:t.filter(r=>r.value===0).length/t.length}getThroughputEstimate(){let t=this.getMetricHistory("response_time_ms",100);if(t.length<2)return 1e3;let e=t[0].timestamp.getTime(),i=(t[t.length-1].timestamp.getTime()-e)/1e3;return i<=0?1e3:Math.round(t.length/i)}getLatencyPercentile(t){let e=this.getMetricHistory("response_time_ms",1e3);if(e.length===0)return 50;let r=e.map(n=>n.value).sort((n,s)=>n-s),i=Math.floor(t/100*r.length);return r[Math.min(i,r.length-1)]}clearHistory(){this.metricHistory.clear()}},uc=null;function dc(){return uc||(uc=new Ss),uc}A();H();var yg={enableTrendAnalysis:!0,trendDataPointsMin:3,complexityThresholds:{cyclomatic:{warning:10,critical:20},cognitive:{warning:15,critical:30},maintainability:{warning:50,critical:30}},enableLLMInsights:!0,llmModelTier:2,llmMaxTokens:2048},Rs={A:90,B:80,C:70,D:50,E:0},ju=R.create("quality-assessment/quality-analyzer"),Xe=class{config;metricsAnalyzer;memory;llmRouter;constructor(t,e={}){this.config={...yg,...e},this.metricsAnalyzer=lc(),"memory"in t?(this.memory=t.memory,this.llmRouter=t.llmRouter):(this.memory=t,this.llmRouter=void 0)}isLLMInsightsAvailable(){return this.config.enableLLMInsights===!0&&this.llmRouter!==void 0}getModelForTier(t){switch(t){case 1:return"claude-haiku-4-5-20251001";case 2:return"claude-sonnet-4-6";case 3:return"claude-sonnet-4-6";case 4:return"claude-opus-4-7";default:return"claude-sonnet-4-6"}}async generateQualityInsightsWithLLM(t,e,r){if(!this.llmRouter)return null;try{let i=this.buildQualityInsightsPrompt(t,e,r),n=this.getModelForTier(this.config.llmModelTier??2),s=await this.llmRouter.chat({messages:[{role:"system",content:`You are an expert software quality engineer. Analyze quality metrics and provide actionable insights.
|
|
2622
|
+
`),n=0,s=0;for(let a of i)a==="{"?(s++,n=Math.max(n,s)):a==="}"&&(s=Math.max(0,s-1));return n}calculateHalsteadMetrics(t){let e=new Set,r=new Set,i=0,n=0,s=[/[+\-*/%]=?/g,/[<>]=?/g,/[!=]=?=?/g,/&&|\|\|/g,/\+\+|--/g,/\./g,/,/g,/:/g,/\?/g,/=>/g];for(let k of s){let P=t.match(k);if(P)for(let O of P)e.add(O),i++}let a=/\b[a-zA-Z_][a-zA-Z0-9_]*\b/g,o=new Set(["if","else","for","while","do","switch","case","break","continue","return","function","class","const","let","var","new","this","true","false","null","undefined","typeof","import","export","default","from","async","await","try","catch","finally","throw","interface","type","extends"]),c=t.match(a);if(c)for(let k of c)o.has(k)||(r.add(k),n++);let l=e.size,d=r.size,m=i,h=n,g=l+d,b=m+h,w=b>0&&g>0?b*Math.log2(g):0,C=d>0?l/2*(h/d):0,S=w*C;return{vocabulary:g,length:b,volume:Math.round(w*100)/100,difficulty:Math.round(C*100)/100,effort:Math.round(S*100)/100}}calculateMaintainabilityIndex(t,e,r){if(r<=0||t<=0)return 100;let i=Math.log(t),n=Math.log(r),s=171-5.2*i-.23*e-16.2*n,a=Math.max(0,Math.min(100,s*100/171));return Math.round(a*100)/100}hashString(t){let e=0;for(let r=0;r<t.length;r++){let i=t.charCodeAt(r);e=(e<<5)-e+i,e=e&e}return e.toString(16)}},cc=null;function lc(){return cc||(cc=new Cs),cc}import*as Ye from"os";var Ss=class{lastCpuUsage=null;lastCpuTime=0;metricHistory=new Map;maxHistorySize;constructor(t=1e3){this.maxHistorySize=t}collectSystemMetrics(){let t=this.collectCpuMetrics(),e=this.collectMemoryMetrics(),r=this.collectProcessMetrics(),i={timestamp:new Date,cpu:t,memory:e,process:r};return this.recordMetric("cpu_usage",t.usage),this.recordMetric("memory_usage",e.usage),this.recordMetric("process_cpu_usage",r.cpuUsage),this.recordMetric("process_memory_usage",r.memoryUsage),i}collectCpuMetrics(){let t=Ye.cpus(),e=Ye.loadavg(),r=0,i=0;for(let s of t){for(let a of Object.keys(s.times))i+=s.times[a];r+=s.times.idle}let n=i>0?(i-r)/i*100:0;return{usage:Math.round(n*100)/100,loadAverage:e,cores:t.length}}collectMemoryMetrics(){let t=Ye.totalmem(),e=Ye.freemem(),r=t-e,i=r/t*100;return{usage:Math.round(i*100)/100,total:t,free:e,used:r}}collectProcessMetrics(){let t=process.memoryUsage(),e=process.cpuUsage(this.lastCpuUsage??void 0),r=Date.now(),n=(this.lastCpuTime>0?r-this.lastCpuTime:1e3)*1e3,a=(e.user+e.system)/n*100;this.lastCpuUsage=e,this.lastCpuTime=r;let o=Ye.totalmem(),c=t.rss/o*100;return{cpuUsage:Math.min(100,Math.round(a*100)/100),memoryUsage:Math.round(c*100)/100,heapUsed:t.heapUsed,heapTotal:t.heapTotal,rss:t.rss,uptime:process.uptime()}}getMetricValue(t){let e=this.collectSystemMetrics();switch(t){case"cpu_usage":return e.cpu.usage;case"memory_usage":return e.memory.usage;case"process_cpu_usage":return e.process.cpuUsage;case"process_memory_usage":return e.process.memoryUsage;case"heap_used":return e.process.heapUsed;case"heap_total":return e.process.heapTotal;case"rss":return e.process.rss;case"load_average_1m":return e.cpu.loadAverage[0];case"load_average_5m":return e.cpu.loadAverage[1];case"load_average_15m":return e.cpu.loadAverage[2];default:{let r=this.metricHistory.get(t);return r&&r.length>0?r[r.length-1].value:0}}}getChaosMetricValue(t){let r={response_time_ms:()=>this.getResponseTimeEstimate(),error_rate:()=>this.getErrorRateEstimate(),throughput:()=>this.getThroughputEstimate(),cpu_usage:()=>this.collectSystemMetrics().cpu.usage,memory_usage:()=>this.collectSystemMetrics().memory.usage,latency_p50:()=>this.getLatencyPercentile(50),latency_p95:()=>this.getLatencyPercentile(95),latency_p99:()=>this.getLatencyPercentile(99)}[t];return r?r():this.getMetricValue(t)}recordMetric(t,e,r){let i={name:t,value:e,timestamp:new Date,labels:r},n=this.metricHistory.get(t)||[];n.push(i),n.length>this.maxHistorySize&&n.shift(),this.metricHistory.set(t,n)}recordHttpMetrics(t){this.recordMetric("response_time_ms",t.responseTimeMs),this.recordMetric("http_status",t.statusCode),this.recordMetric("http_success",t.success?1:0)}getMetricHistory(t,e){let r=this.metricHistory.get(t)||[];return e&&r.length>e?r.slice(-e):[...r]}getMetricAverage(t,e=10){let r=this.getMetricHistory(t,e);return r.length===0?0:r.reduce((n,s)=>n+s.value,0)/r.length}getResponseTimeEstimate(){let t=this.collectSystemMetrics().cpu,e=50,r=1+t.usage/100;return Math.round(e*r)}getErrorRateEstimate(){let t=this.getMetricHistory("http_success",100);return t.length===0?0:t.filter(r=>r.value===0).length/t.length}getThroughputEstimate(){let t=this.getMetricHistory("response_time_ms",100);if(t.length<2)return 1e3;let e=t[0].timestamp.getTime(),i=(t[t.length-1].timestamp.getTime()-e)/1e3;return i<=0?1e3:Math.round(t.length/i)}getLatencyPercentile(t){let e=this.getMetricHistory("response_time_ms",1e3);if(e.length===0)return 50;let r=e.map(n=>n.value).sort((n,s)=>n-s),i=Math.floor(t/100*r.length);return r[Math.min(i,r.length-1)]}clearHistory(){this.metricHistory.clear()}},uc=null;function dc(){return uc||(uc=new Ss),uc}A();H();var yg={enableTrendAnalysis:!0,trendDataPointsMin:3,complexityThresholds:{cyclomatic:{warning:10,critical:20},cognitive:{warning:15,critical:30},maintainability:{warning:50,critical:30}},enableLLMInsights:!0,llmModelTier:2,llmMaxTokens:2048},Rs={A:90,B:80,C:70,D:50,E:0},ju=R.create("quality-assessment/quality-analyzer"),Xe=class{config;metricsAnalyzer;memory;llmRouter;constructor(t,e={}){this.config={...yg,...e},this.metricsAnalyzer=lc(),"memory"in t?(this.memory=t.memory,this.llmRouter=t.llmRouter):(this.memory=t,this.llmRouter=void 0)}isLLMInsightsAvailable(){return this.config.enableLLMInsights===!0&&this.llmRouter!==void 0}getModelForTier(t){switch(t){case 1:return"claude-haiku-4-5-20251001";case 2:return"claude-sonnet-4-6";case 3:return"claude-sonnet-4-6";case 4:return"claude-opus-4-7";default:return"claude-sonnet-4-6"}}async generateQualityInsightsWithLLM(t,e,r){if(!this.llmRouter)return null;try{let i=this.buildQualityInsightsPrompt(t,e,r),n=this.getModelForTier(this.config.llmModelTier??2),s=await this.llmRouter.chat({messages:[{role:"system",content:`You are an expert software quality engineer. Analyze quality metrics and provide actionable insights.
|
|
2623
2623
|
|
|
2624
2624
|
Your response MUST be valid JSON with this exact structure:
|
|
2625
2625
|
{
|
|
@@ -2716,9 +2716,9 @@ Estimated Rollback Time: ${t.rollbackPlan.estimatedTime}`),a.length>0&&(s=a.join
|
|
|
2716
2716
|
\`\`\`json
|
|
2717
2717
|
${JSON.stringify(u,null,2)}
|
|
2718
2718
|
\`\`\``}M();A();se();var Tg={stateSize:10,actionSize:4,actorHiddenLayers:[64,64],criticHiddenLayers:[64,64],actorLR:1e-4,criticLR:.001,entropyCoeff:.01},Ts=class extends oe{actor;critic;acConfig;actions=[];constructor(t={}){super("actor-critic","policy-based"),this.acConfig={...Tg,...t},this.initializeActions(),this.actor=new q({layerSizes:[this.acConfig.stateSize,...this.acConfig.actorHiddenLayers,this.acConfig.actionSize],activations:Array(this.acConfig.actorHiddenLayers.length).fill(new _).concat([new B]),learningRate:this.acConfig.actorLR}),this.critic=new q({layerSizes:[this.acConfig.stateSize,...this.acConfig.criticHiddenLayers,1],activations:Array(this.acConfig.criticHiddenLayers.length).fill(new _).concat([new B]),learningRate:this.acConfig.criticLR})}async predict(t){this.initialized||await this.initialize();let e=this.prepareState(t),r=he.forward(this.actor.forward(e)),i=this.sampleAction(r),n=this.actions[i],s=this.critic.forward(e)[0],a=Math.max(.3,Math.min(1,r[i]+.3));return{action:n,confidence:a,value:s,reasoning:this.generateReasoning(t,n,s,r[i])}}async trainCore(t){let e=0,r=0;for(let i of t){let n=this.prepareState(i.state),s=this.prepareState(i.nextState),a=this.actionToIndex(i.action),o=this.actor.forward(n),c=he.forward(o),l=Math.log(c[a]+1e-10),d=this.critic.forward(n)[0],m=i.done?0:this.critic.forward(s)[0],h=i.reward+this.config.discountFactor*m-d,g=new Float32Array([i.reward+this.config.discountFactor*m]),b=this.critic.train(n,g,new fe),w=-l*h,C=this.calculateEntropy(c),S=this.acConfig.entropyCoeff*C,k=w-S,P=new Float32Array(c.length);for(let O=0;O<P.length;O++){let z=Math.log(c[O]+1e-10),K=O===a?-h:0;P[O]=K-this.acConfig.entropyCoeff*(c[O]*Math.log(c[O]+1e-10))}this.actor.backward(P);for(let O of this.actor.layers)O.update(this.acConfig.actorLR);e+=Math.abs(k),r+=Math.abs(b)}return{episode:this.episodeCount,totalReward:this.totalReward,averageReward:this.rewardHistory.reduce((i,n)=>i+n,0)/this.rewardHistory.length,loss:(e+r)/t.length,explorationRate:this.config.explorationRate,trainingTimeMs:0,timestamp:new Date}}getAlgorithmInfo(){return{type:this.type,category:this.category,version:"2.0.0",description:"Neural Actor-Critic for Quality Gate Threshold Tuning",capabilities:["Neural Actor learns optimal threshold policy","Neural Critic provides value estimates","Lower variance than REINFORCE","Online learning with bootstrapping"],hyperparameters:{stateSize:this.acConfig.stateSize,actionSize:this.acConfig.actionSize,actorLR:this.acConfig.actorLR,criticLR:this.acConfig.criticLR,entropyCoeff:this.acConfig.entropyCoeff},stats:this.stats}}sampleAction(t){if(L()<this.config.explorationRate)return ue(0,this.actions.length);let e=L(),r=0;for(let i=0;i<t.length;i++)if(r+=t[i],e<=r)return i;return this.argmax(t)}calculateEntropy(t){let e=0;for(let r=0;r<t.length;r++)t[r]>0&&(e-=t[r]*Math.log(t[r]));return e}prepareState(t){let e=t.features.slice(0,this.acConfig.stateSize);for(;e.length<this.acConfig.stateSize;)e.push(0);let r=Math.max(...e.map(Math.abs));if(r>0)for(let i=0;i<e.length;i++)e[i]=e[i]/r;return new Float32Array(e)}initializeActions(){this.actions=[{type:"adjust-threshold",value:.1},{type:"adjust-threshold",value:-.1},{type:"approve",value:1},{type:"reject",value:0}],this.acConfig.actionSize=this.actions.length,this.actor=new q({layerSizes:[this.acConfig.stateSize,...this.acConfig.actorHiddenLayers,this.acConfig.actionSize],activations:Array(this.acConfig.actorHiddenLayers.length).fill(new _).concat([new B]),learningRate:this.acConfig.actorLR})}actionToIndex(t){let e=this.actionToKey(t);for(let r=0;r<this.actions.length;r++)if(this.actionToKey(this.actions[r])===e)return r;return 0}actionToKey(t){return`${t.type}:${JSON.stringify(t.value)}`}argmax(t){let e=0,r=t[0];for(let i=1;i<t.length;i++)t[i]>r&&(r=t[i],e=i);return e}generateReasoning(t,e,r,i){return this.episodeCount<10?`Neural Actor-Critic learning (episode ${this.episodeCount}): exploring actions`:`Neural Actor-Critic: ${e.type} (prob: ${i.toFixed(3)}, state value: ${r.toFixed(3)})`}async exportCustomData(){return{actor:this.actor.getParameters(),critic:this.critic.getParameters(),acConfig:this.acConfig}}async importCustomData(t){t.actor&&this.actor.setParameters(t.actor),t.critic&&this.critic.setParameters(t.critic),t.acConfig&&(this.acConfig={...this.acConfig,...t.acConfig}),this.initialized=!0}async resetAlgorithm(){this.actor=new q({layerSizes:[this.acConfig.stateSize,...this.acConfig.actorHiddenLayers,this.acConfig.actionSize],activations:Array(this.acConfig.actorHiddenLayers.length).fill(new _).concat([new B]),learningRate:this.acConfig.actorLR}),this.critic=new q({layerSizes:[this.acConfig.stateSize,...this.acConfig.criticHiddenLayers,1],activations:Array(this.acConfig.criticHiddenLayers.length).fill(new _).concat([new B]),learningRate:this.acConfig.criticLR})}};var ft=R.create("quality-assessment/rl-integration");async function Zu(){try{return new Ts({stateSize:10,actionSize:4,actorHiddenLayers:[64,64],criticHiddenLayers:[64,64],actorLR:1e-4,criticLR:.001,entropyCoeff:.01})}catch(u){throw new Error(`Failed to initialize Actor-Critic RL: ${T(u)}`)}}async function ed(){try{let u=await pe({domain:"quality-assessment",loadOnInit:!0,autoSaveInterval:6e4,hiddenDim:256,embeddingDim:384,microLoraRank:1,baseLoraRank:8,minConfidence:.5,maxPatterns:5e3});return ft.info("PersistentSONAEngine initialized successfully"),u}catch(u){ft.error("Failed to initialize PersistentSONAEngine:",u instanceof Error?u:void 0),ft.warn("Continuing without SONA pattern persistence");return}}async function td(){try{return await Me("pattern-adaptation",{dim:384,strategy:"flash",blockSize:32})}catch(u){throw new Error(`Failed to initialize QEFlashAttention: ${T(u)}`)}}async function rd(u,t){try{let e={id:`quality-state-${Date.now()}`,features:[t.coverage/100,t.testsPassing/100,t.criticalBugs/10,t.codeSmells/50,t.securityVulnerabilities/10,t.technicalDebt/20,t.duplications/20]},r=await u.predict(e);return{thresholds:Ag({coverage:{min:80},testsPassing:{min:95},criticalBugs:{max:0},codeSmells:{max:20},securityVulnerabilities:{max:0},technicalDebt:{max:5},duplications:{max:5}},r.action),confidence:r.confidence,reasoning:r.reasoning??""}}catch(e){return ft.error("RL threshold tuning failed:",e instanceof Error?e:void 0),null}}function Ag(u,t){let e={...u};if(t.type==="adjust-threshold"&&typeof t.value=="number"){let r=t.value*5;e.coverage?.min!==void 0&&(e.coverage.min=Math.max(50,Math.min(100,e.coverage.min+r))),e.codeSmells?.max!==void 0&&(e.codeSmells.max=Math.max(0,Math.min(100,e.codeSmells.max-r)))}return e}async function id(u,t,e){try{let r={id:`quality-state-${Date.now()}`,features:[t.metrics.coverage/100,t.metrics.testsPassing/100,t.metrics.criticalBugs/10,t.metrics.codeSmells/50,t.metrics.securityVulnerabilities/10,t.metrics.technicalDebt/20,t.metrics.duplications/20]},i={type:"evaluate-gate",value:e.overallScore},n={...r},s=0;if(e.passed)s+=e.overallScore/100,e.overallScore>=90&&(s+=.5),e.overallScore>=95&&(s+=.5);else{s-=.5;let o=e.checks.filter(c=>!c.passed&&c.severity==="critical").length;s-=o*.2}let a={state:r,action:i,nextState:n,reward:Math.max(-1,Math.min(1,s)),done:!0};await u.train(a)}catch(r){ft.error("Actor-Critic training failed:",r instanceof Error?r:void 0)}}async function nd(u,t,e,r){try{let i={id:`quality-state-${Date.now()}`,features:[t.metrics.coverage,t.metrics.testsPassing,t.metrics.criticalBugs,t.metrics.codeSmells,t.metrics.securityVulnerabilities,t.metrics.technicalDebt,t.metrics.duplications]},n={type:"quality-gate-evaluation",value:e.passed?1:0};u.createPattern(i,n,{reward:e.passed?e.overallScore/100:-.5,success:e.passed,quality:e.overallScore/100},"quality-assessment",r,{gateName:t.gateName,overallScore:e.overallScore,failedChecks:e.failedChecks})}catch(i){ft.error("Failed to store quality pattern in SONA:",i instanceof Error?i:void 0)}}async function sd(u,t,e,r){try{let i={id:`quality-analysis-${Date.now()}`,features:[e.score.overall,e.score.coverage,e.score.complexity,e.score.maintainability,e.metrics.length,t.sourceFiles.length]},n={type:"quality-analysis",value:e.score.overall};u.createPattern(i,n,{reward:e.score.overall/100,success:e.score.overall>=70,quality:e.score.overall/100},"quality-assessment",r,{sourceFileCount:t.sourceFiles.length,recommendationCount:e.recommendations.length})}catch(i){ft.error("Failed to store quality analysis pattern in SONA:",i instanceof Error?i:void 0)}}async function ad(u,t,e,r){try{let i={id:`similarity-search-${Date.now()}`,features:[u.score.overall,u.score.coverage,u.score.complexity,u.score.maintainability]},n=await e.adaptPattern(i,"quality-assessment",r);if(!n.success||!n.pattern)return null;let s=[];if(n.pattern.metadata){let a=n.pattern.metadata;a.similarIssues&&a.similarIssues.length>0&&s.push({type:"improvement",title:"Similar Quality Patterns Found",description:`Found ${n.similarity.toFixed(0)}% similar historical patterns: ${a.similarIssues.slice(0,3).join(", ")}`,impact:"medium",effort:"low"})}return{...u,recommendations:[...u.recommendations,...s]}}catch(i){return ft.error("Failed to enhance with similarity patterns:",i instanceof Error?i:void 0),null}}function od(u){let t=[],e={pattern_merge:.2,novel_association:.4,optimization:.6,gap_detection:.8};for(t.push(e[u.type]||.5),t.push(u.confidenceScore),t.push(u.noveltyScore),t.push(u.actionable?1:0),t.push(Math.min(1,u.sourceConcepts.length/10));t.length<384;)t.push(0);return t.slice(0,384)}M();A();function As(u,t,e){let r=new Error(t);return r.code=u,r.claimId=e?.claimId,r.details=e?.details,r.retryable=e?.retryable??!1,r}var mc={defaultConfidenceThreshold:.8,defaultTimeout:3e4,reportQualityThreshold:.85,enableMultiModel:!0,maxParallelVerifications:5,enableStatistics:!0,statisticsPersistInterval:6e4},Es={"security-implementation":"code-trace","security-vulnerability":"code-trace","metric-count":"execution","pattern-implementation":"cross-file","coverage-claim":"execution"},xs=["security-implementation","security-vulnerability"];import{readFile as xg,stat as pc}from"node:fs/promises";import{join as cd}from"node:path";import Pg from"fast-glob";var xi=class{config;constructor(t){this.config={rootDir:t.rootDir,maxFileSize:t.maxFileSize??10*1024*1024,encoding:t.encoding??"utf-8",excludePatterns:t.excludePatterns??["node_modules/**",".git/**","dist/**"]}}async verify(t,e){let r=Date.now(),i=e?.checkAllInstances??!0;try{let n=this.extractFilePatterns(t),s=this.extractSearchPatterns(t),a=[],o=!1,c="",l=0,d=0;if(n.length>0){let g=await this.verifyFileExistence(n);a.push(...g.evidence),l+=g.total,d+=g.passed,g.passed===g.total?(o=!0,c=`All ${g.total} referenced files exist`):(o=!1,c=`${g.total-g.passed} of ${g.total} files not found`)}if(s.length>0){let g=await this.verifyContentPatterns(s,i,e?.maxInstances);a.push(...g.evidence),l+=g.total,d+=g.passed,g.passed>0?(o=!0,c=i?`Pattern found in all ${g.passed} instances`:`Pattern found in ${g.passed} of ${g.total} checked files`):(o=!1,c=`Pattern not found in any of ${g.total} checked files`)}if(n.length===0&&s.length===0){let g=await this.verifyExistingEvidence(t.evidence);a=g.evidence,o=g.verified,c=g.reasoning,l=g.total,d=g.passed}let m=Date.now()-r,h=this.calculateConfidence(d,l,o);return{claimId:t.id,verified:o,confidence:h,method:"cross-file",reasoning:c,allInstancesChecked:i,instancesChecked:l,instancesPassed:d,verificationTimeMs:m,verifiedAt:new Date,requiresHumanReview:h<.7,counterEvidence:o?void 0:a.filter(g=>!g.verified)}}catch(n){let s=Date.now()-r,a=n instanceof Error?n.message:"Unknown error";return{claimId:t.id,verified:!1,confidence:0,method:"cross-file",reasoning:`Verification failed: ${a}`,allInstancesChecked:!1,instancesChecked:0,instancesPassed:0,verificationTimeMs:s,verifiedAt:new Date,requiresHumanReview:!0}}}extractFilePatterns(t){let e=[];for(let n of t.evidence)if(n.type==="file-reference"||n.type==="code-snippet"){let s=n.location.split(":")[0];s&&!e.includes(s)&&e.push(s)}let r=/(?:src\/|tests\/|lib\/|app\/)[\w\-/.]+\.[\w]+/g,i=t.statement.match(r);return i&&e.push(...i.filter(n=>!e.includes(n))),e}extractSearchPatterns(t){let e=[],r=["parameterized queries","prepared statements","input validation","sanitization","csrf token","xss prevention"];for(let i of r)t.statement.toLowerCase().includes(i)&&e.push({pattern:i});return e}async verifyFileExistence(t){let e=[],r=0;for(let i of t){let n=cd(this.config.rootDir,i);try{let s=await pc(n),a=s.isFile();e.push({type:"file-reference",location:i,content:a?`File exists (${s.size} bytes)`:"File not found",verified:a,timestamp:new Date}),a&&r++}catch(s){e.push({type:"file-reference",location:i,content:`File not accessible: ${s instanceof Error?s.message:"Unknown error"}`,verified:!1,timestamp:new Date})}}return{evidence:e,total:t.length,passed:r}}async verifyContentPatterns(t,e,r){let i=[],n=0,s=0;for(let{pattern:a,fileGlob:o}of t){let l=await Pg(o??"**/*.{ts,js,tsx,jsx}",{cwd:this.config.rootDir,ignore:this.config.excludePatterns,absolute:!0}),d=r&&!e?l.slice(0,r):l;n+=d.length;for(let m of d){let h=await this.searchFileForPattern(m,a);if(h.matches.length>0){s++;for(let g of h.matches)i.push({type:"code-snippet",location:`${h.filePath}:${g.line}`,content:g.content,verified:!0,timestamp:new Date,contentHash:Pi(g.content)})}}}return{evidence:i,total:n,passed:s}}async searchFileForPattern(t,e){try{if((await pc(t)).size>this.config.maxFileSize)return{filePath:t,matches:[]};let n=(await xg(t,this.config.encoding)).split(`
|
|
2719
|
-
`),s=[],a=e.toLowerCase();for(let o=0;o<n.length;o++)n[o].toLowerCase().includes(a)&&s.push({line:o+1,content:n[o].trim()});return{filePath:t,matches:s}}catch{return{filePath:t,matches:[]}}}async verifyExistingEvidence(t){let e=[],r=0;for(let s of t)if(s.type==="file-reference"||s.type==="code-snippet"){let a=s.location.split(":")[0],o=cd(this.config.rootDir,a);try{let l=(await pc(o)).isFile();e.push({...s,verified:l,timestamp:new Date}),l&&r++}catch{e.push({...s,verified:!1,timestamp:new Date})}}else e.push(s);let i=r===t.length&&r>0,n=i?`All ${r} evidence items verified`:`${r} of ${t.length} evidence items verified`;return{evidence:e,verified:i,reasoning:n,total:t.length,passed:r}}calculateConfidence(t,e,r){if(e===0)return 0;let i=t/e;return r&&i===1?1:i>=.9?.9:i>=.75?.75:i>=.5?.6:.3}};H();import{execFile as kg}from"node:child_process";import{promisify as Dg}from"node:util";import{readFile as Ig}from"node:fs/promises";import{join as Mg}from"node:path";var Fg=Dg(kg),ld=new Map([["npm test",{bin:"npm",args:["test"]}],["npm run test",{bin:"npm",args:["run","test"]}],["npm run test:unit",{bin:"npm",args:["run","test:unit"]}],["npm run test:unit:fast",{bin:"npm",args:["run","test:unit:fast"]}],["npm run test:ci",{bin:"npm",args:["run","test:ci"]}],["npm run test:coverage",{bin:"npm",args:["run","test:coverage"]}],["npm run test:e2e",{bin:"npm",args:["run","test:e2e"]}],["npm run test:safe",{bin:"npm",args:["run","test:safe"]}]]),ki=class{config;constructor(t){this.config={rootDir:t.rootDir,testCommand:t.testCommand??"npm test",coverageCommand:t.coverageCommand??"npm run test:coverage",coverageReportPath:t.coverageReportPath??"coverage/coverage-summary.json",timeout:t.timeout??6e4}}async verify(t,e){let r=Date.now();try{let i=this.classifyTestClaim(t),n=[],s=!1,a="",o=0;switch(i){case"test-count":let l=await this.verifyTestCount(t);n=l.evidence,s=l.verified,a=l.reasoning,o=l.confidence;break;case"test-results":let d=await this.verifyTestExecution(t);n=d.evidence,s=d.verified,a=d.reasoning,o=d.confidence;break;case"coverage":let m=await this.verifyCoverage(t);n=m.evidence,s=m.verified,a=m.reasoning,o=m.confidence;break;default:let h=await this.verifyExistingEvidence(t.evidence);n=h.evidence,s=h.verified,a=h.reasoning,o=h.confidence}let c=Date.now()-r;return{claimId:t.id,verified:s,confidence:o,method:"execution",reasoning:a,allInstancesChecked:!0,instancesChecked:1,instancesPassed:s?1:0,verificationTimeMs:c,verifiedAt:new Date,requiresHumanReview:o<.8}}catch(i){let n=Date.now()-r,s=i instanceof Error?i.message:"Unknown error";return{claimId:t.id,verified:!1,confidence:0,method:"execution",reasoning:`Verification failed: ${s}`,allInstancesChecked:!1,instancesChecked:0,instancesPassed:0,verificationTimeMs:n,verifiedAt:new Date,requiresHumanReview:!0}}}classifyTestClaim(t){let e=t.statement.toLowerCase();return e.includes("coverage")||e.includes("%")||e.includes("percent")?"coverage":e.includes("test")&&(e.includes("pass")||e.includes("fail"))?"test-results":e.includes("test")&&/\d+/.test(e)?"test-count":"unknown"}async verifyTestCount(t){try{let e=await this.runTests(),r=this.extractNumber(t.statement),i=[{type:"test-result",location:"test-execution",content:`Total tests: ${e.total}, Passed: ${e.passed}, Failed: ${e.failed}`,verified:!0,timestamp:new Date,context:{total:e.total,passed:e.passed,failed:e.failed,skipped:e.skipped}},{type:"command-output",location:this.config.testCommand,content:e.rawOutput,verified:!0,timestamp:new Date}],n=r!==null&&e.total>=r,s=n?`Claimed ${r} tests, found ${e.total} tests`:r===null?"Could not extract test count from claim":`Claimed ${r} tests, but only ${e.total} exist`;return{evidence:i,verified:n,reasoning:s,confidence:n?.95:.3}}catch(e){let r=e instanceof Error?e.message:"Unknown error";return{evidence:[{type:"command-output",location:this.config.testCommand,content:`Test execution failed: ${r}`,verified:!1,timestamp:new Date}],verified:!1,reasoning:`Failed to run tests: ${r}`,confidence:0}}}async verifyTestExecution(t){try{let e=await this.runTests(),r=[{type:"test-result",location:"test-execution",content:`Tests passed: ${e.passed}/${e.total}`,verified:e.failed===0,timestamp:new Date,context:{total:e.total,passed:e.passed,failed:e.failed}},{type:"command-output",location:this.config.testCommand,content:e.rawOutput,verified:!0,timestamp:new Date}],i=e.failed===0&&e.total>0,n=t.statement.toLowerCase().includes("pass")?i:!i,s=i?`All ${e.total} tests passed`:`${e.failed} of ${e.total} tests failed`,a=e.total>0?.95:.3;return{evidence:r,verified:n,reasoning:s,confidence:a}}catch(e){let r=e instanceof Error?e.message:"Unknown error";return{evidence:[{type:"command-output",location:this.config.testCommand,content:`Test execution failed: ${r}`,verified:!1,timestamp:new Date}],verified:!1,reasoning:`Failed to run tests: ${r}`,confidence:0}}}async verifyCoverage(t){try{let e=await this.getCoverageData(),r=this.extractPercentage(t.statement),i=[{type:"coverage-data",location:this.config.coverageReportPath,content:`Lines: ${e.lines}%, Statements: ${e.statements}%, Functions: ${e.functions}%, Branches: ${e.branches}%`,verified:!0,timestamp:new Date,context:e.rawData}],n=e.lines,s=r!==null&&n>=r,a=s?`Claimed ${r}% coverage, actual coverage is ${n}%`:r===null?"Could not extract coverage percentage from claim":`Claimed ${r}% coverage, but actual is only ${n}%`;return{evidence:i,verified:s,reasoning:a,confidence:s?.95:.3}}catch(e){let r=e instanceof Error?e.message:"Unknown error";return{evidence:[{type:"coverage-data",location:this.config.coverageReportPath,content:`Coverage data unavailable: ${r}`,verified:!1,timestamp:new Date}],verified:!1,reasoning:`Failed to get coverage data: ${r}`,confidence:0}}}async runTests(){let t=ld.get(this.config.testCommand);if(!t)throw new Error(`Test command not in allowlist: "${this.config.testCommand}". Allowed: ${[...ld.keys()].join(", ")}`);let{stdout:e,stderr:r}=await Fg(t.bin,[...t.args],{cwd:this.config.rootDir,timeout:this.config.timeout}),i=e+r;return{...this.parseTestOutput(i),rawOutput:i}}parseTestOutput(t){let e=t.match(/(\d+) passed(?:\s+\|\s+(\d+) failed)?/);if(e){let r=parseInt(e[1],10),i=e[2]?parseInt(e[2],10):0;return{total:r+i,passed:r,failed:i}}return e=t.match(/Tests:\s+(\d+) failed.*?(\d+) passed.*?(\d+) total/),e?{total:parseInt(e[3],10),passed:parseInt(e[2],10),failed:parseInt(e[1],10)}:{total:0,passed:0,failed:0}}async getCoverageData(){let t=Mg(this.config.rootDir,this.config.coverageReportPath),e=await Ig(t,"utf-8"),r=E(e),i=r.total||r;return{lines:i.lines?.pct??0,statements:i.statements?.pct??0,functions:i.functions?.pct??0,branches:i.branches?.pct??0,rawData:r}}async verifyExistingEvidence(t){let e=t.filter(i=>i.type==="test-result"||i.type==="coverage-data");if(e.length===0)return{evidence:[],verified:!1,reasoning:"No test or coverage evidence provided",confidence:0};let r=e.every(i=>i.verified);return{evidence:e,verified:r,reasoning:r?`All ${e.length} evidence items verified`:"Some evidence items failed verification",confidence:r?.8:.3}}extractNumber(t){let e=t.match(/\d+/);return e?parseInt(e[0],10):null}extractPercentage(t){let e=t.match(/(\d+)%/);return e?parseInt(e[1],10):null}};import{execFile as Lg}from"node:child_process";import{promisify as $g}from"node:util";var Og=$g(Lg),ud=new Map([["npm run build",{bin:"npm",args:["run","build"]}],["npm run lint",{bin:"npm",args:["run","lint"]}],["npm test",{bin:"npm",args:["test"]}],["npm run typecheck",{bin:"npm",args:["run","typecheck"]}],["npm run test:unit",{bin:"npm",args:["run","test:unit"]}],["npm run test:ci",{bin:"npm",args:["run","test:ci"]}]]),Di=class{config;patterns={build:[{pattern:/build successful/i,type:"success",location:"stdout"},{pattern:/compiled successfully/i,type:"success",location:"stdout"},{pattern:/done in/i,type:"success",location:"stdout"},{pattern:/error/i,type:"error",location:"stderr"},{pattern:/failed/i,type:"error",location:"both"},{pattern:/warning/i,type:"warning",location:"both"}],lint:[{pattern:/no problems found/i,type:"success",location:"stdout"},{pattern:/✔.*\d+ problems?/i,type:"success",location:"stdout"},{pattern:/✖.*\d+ problems?/i,type:"error",location:"stdout"},{pattern:/error/i,type:"error",location:"both"}]};constructor(t){this.config={rootDir:t.rootDir,timeout:t.timeout??6e4,maxOutputSize:t.maxOutputSize??1024*1024,env:t.env??{}}}async verify(t,e){let r=Date.now();try{let i=this.extractCommand(t);if(!i){let c=await this.verifyExistingEvidence(t.evidence),l=Date.now()-r;return{claimId:t.id,verified:c.verified,confidence:c.confidence,method:"execution",reasoning:c.reasoning,allInstancesChecked:!0,instancesChecked:c.evidence.length,instancesPassed:c.verified?c.evidence.length:0,verificationTimeMs:l,verifiedAt:new Date,requiresHumanReview:c.confidence<.7}}let n=await this.executeCommand(i),s=this.createEvidence(i,n),a=this.analyzeOutput(t,n),o=Date.now()-r;return{claimId:t.id,verified:a.verified,confidence:a.confidence,method:"execution",reasoning:a.reasoning,allInstancesChecked:!0,instancesChecked:1,instancesPassed:a.verified?1:0,verificationTimeMs:o,verifiedAt:new Date,requiresHumanReview:a.confidence<.8,counterEvidence:a.verified?void 0:s}}catch(i){let n=Date.now()-r,s=i instanceof Error?i.message:"Unknown error";return{claimId:t.id,verified:!1,confidence:0,method:"execution",reasoning:`Verification failed: ${s}`,allInstancesChecked:!1,instancesChecked:0,instancesPassed:0,verificationTimeMs:n,verifiedAt:new Date,requiresHumanReview:!0}}}extractCommand(t){for(let i of t.evidence)if(i.type==="command-output"&&i.location)return i.location;let e=t.statement.toLowerCase();if(e.includes("build"))return"npm run build";if(e.includes("lint"))return"npm run lint";if(e.includes("test"))return"npm test";if(e.includes("typecheck")||e.includes("type check"))return"npm run typecheck";let r=e.match(/`([^`]+)`|"([^"]+)"/);return r?r[1]||r[2]:null}async executeCommand(t){let e=Date.now(),r=ud.get(t);if(!r)throw new Error(`Command not in allowlist: "${t}". Allowed: ${[...ud.keys()].join(", ")}`);try{let{stdout:i,stderr:n}=await Og(r.bin,[...r.args],{cwd:this.config.rootDir,timeout:this.config.timeout,maxBuffer:this.config.maxOutputSize,env:{...process.env,...this.config.env}}),s=Date.now()-e;return{stdout:this.truncateOutput(i),stderr:this.truncateOutput(n),exitCode:0,duration:s,success:!0}}catch(i){let n=Date.now()-e;if(i&&typeof i=="object"&&"stdout"in i&&"stderr"in i){let s=i;return{stdout:this.truncateOutput(s.stdout||""),stderr:this.truncateOutput(s.stderr||""),exitCode:s.code??1,duration:n,success:!1}}throw i}}createEvidence(t,e){let r=[];return e.stdout&&r.push({type:"command-output",location:t,content:e.stdout,verified:e.success,timestamp:new Date,contentHash:Pi(e.stdout),context:{stream:"stdout",exitCode:e.exitCode,duration:e.duration}}),e.stderr&&r.push({type:"command-output",location:t,content:e.stderr,verified:e.success,timestamp:new Date,contentHash:Pi(e.stderr),context:{stream:"stderr",exitCode:e.exitCode,duration:e.duration}}),r}analyzeOutput(t,e){let r=t.statement.toLowerCase(),i=this.inferCommandType(r),n=i?this.patterns[i]:[],s=!1,a=!1,o=!1;for(let g of n){let b=g.location==="both"?e.stdout+e.stderr:g.location==="stdout"?e.stdout:e.stderr;(typeof g.pattern=="string"?new RegExp(g.pattern,"i"):g.pattern).test(b)&&(g.type==="success"&&(s=!0),g.type==="error"&&(a=!0),g.type==="warning"&&(o=!0))}let c=r.includes("success")||r.includes("pass")||r.includes("complete"),l=r.includes("fail")||r.includes("error"),d,m,h;return c?(d=e.success&&s&&!a,m=d?.95:o?.7:.3,h=d?"Command executed successfully with expected output":e.success?"Command succeeded but output patterns do not match":"Command failed with exit code "+e.exitCode):l?(d=!e.success||a,m=d?.95:.3,h=d?"Command failed as claimed":"Command succeeded, contradicting the claim"):(d=e.exitCode===0,m=.8,h=d?"Command completed successfully":"Command exited with error code "+e.exitCode),{verified:d,confidence:m,reasoning:h}}inferCommandType(t){return t.includes("build")?"build":t.includes("lint")?"lint":null}async verifyExistingEvidence(t){let e=t.filter(o=>o.type==="command-output");if(e.length===0)return{evidence:[],verified:!1,reasoning:"No command output evidence provided",confidence:0};let r=e.some(o=>/error|failed/i.test(o.content)),n=e.some(o=>/success|passed|done/i.test(o.content))&&!r,s=n?.8:.3,a=n?`Found ${e.length} evidence items indicating success`:r?"Evidence contains error indicators":"Evidence does not indicate success";return{evidence:e,verified:n,reasoning:a,confidence:s}}truncateOutput(t){return t.length<=this.config.maxOutputSize?t:t.substring(0,this.config.maxOutputSize)+`
|
|
2719
|
+
`),s=[],a=e.toLowerCase();for(let o=0;o<n.length;o++)n[o].toLowerCase().includes(a)&&s.push({line:o+1,content:n[o].trim()});return{filePath:t,matches:s}}catch{return{filePath:t,matches:[]}}}async verifyExistingEvidence(t){let e=[],r=0;for(let s of t)if(s.type==="file-reference"||s.type==="code-snippet"){let a=s.location.split(":")[0],o=cd(this.config.rootDir,a);try{let l=(await pc(o)).isFile();e.push({...s,verified:l,timestamp:new Date}),l&&r++}catch{e.push({...s,verified:!1,timestamp:new Date})}}else e.push(s);let i=r===t.length&&r>0,n=i?`All ${r} evidence items verified`:`${r} of ${t.length} evidence items verified`;return{evidence:e,verified:i,reasoning:n,total:t.length,passed:r}}calculateConfidence(t,e,r){if(e===0)return 0;let i=t/e;return r&&i===1?1:i>=.9?.9:i>=.75?.75:i>=.5?.6:.3}};H();import{execFile as kg}from"node:child_process";import{promisify as Dg}from"node:util";import{readFile as Ig}from"node:fs/promises";import{join as Mg}from"node:path";var Fg=Dg(kg),ld=new Map([["npm test",{bin:"npm",args:["test"]}],["npm run test",{bin:"npm",args:["run","test"]}],["npm run test:unit",{bin:"npm",args:["run","test:unit"]}],["npm run test:unit:fast",{bin:"npm",args:["run","test:unit:fast"]}],["npm run test:ci",{bin:"npm",args:["run","test:ci"]}],["npm run test:coverage",{bin:"npm",args:["run","test:coverage"]}],["npm run test:e2e",{bin:"npm",args:["run","test:e2e"]}],["npm run test:safe",{bin:"npm",args:["run","test:safe"]}]]),ki=class{config;constructor(t){this.config={rootDir:t.rootDir,testCommand:t.testCommand??"npm test",coverageCommand:t.coverageCommand??"npm run test:coverage",coverageReportPath:t.coverageReportPath??"coverage/coverage-summary.json",timeout:t.timeout??6e4}}async verify(t,e){let r=Date.now();try{let i=this.classifyTestClaim(t),n=[],s=!1,a="",o=0;switch(i){case"test-count":{let l=await this.verifyTestCount(t);n=l.evidence,s=l.verified,a=l.reasoning,o=l.confidence;break}case"test-results":{let l=await this.verifyTestExecution(t);n=l.evidence,s=l.verified,a=l.reasoning,o=l.confidence;break}case"coverage":{let l=await this.verifyCoverage(t);n=l.evidence,s=l.verified,a=l.reasoning,o=l.confidence;break}default:{let l=await this.verifyExistingEvidence(t.evidence);n=l.evidence,s=l.verified,a=l.reasoning,o=l.confidence}}let c=Date.now()-r;return{claimId:t.id,verified:s,confidence:o,method:"execution",reasoning:a,allInstancesChecked:!0,instancesChecked:1,instancesPassed:s?1:0,verificationTimeMs:c,verifiedAt:new Date,requiresHumanReview:o<.8}}catch(i){let n=Date.now()-r,s=i instanceof Error?i.message:"Unknown error";return{claimId:t.id,verified:!1,confidence:0,method:"execution",reasoning:`Verification failed: ${s}`,allInstancesChecked:!1,instancesChecked:0,instancesPassed:0,verificationTimeMs:n,verifiedAt:new Date,requiresHumanReview:!0}}}classifyTestClaim(t){let e=t.statement.toLowerCase();return e.includes("coverage")||e.includes("%")||e.includes("percent")?"coverage":e.includes("test")&&(e.includes("pass")||e.includes("fail"))?"test-results":e.includes("test")&&/\d+/.test(e)?"test-count":"unknown"}async verifyTestCount(t){try{let e=await this.runTests(),r=this.extractNumber(t.statement),i=[{type:"test-result",location:"test-execution",content:`Total tests: ${e.total}, Passed: ${e.passed}, Failed: ${e.failed}`,verified:!0,timestamp:new Date,context:{total:e.total,passed:e.passed,failed:e.failed,skipped:e.skipped}},{type:"command-output",location:this.config.testCommand,content:e.rawOutput,verified:!0,timestamp:new Date}],n=r!==null&&e.total>=r,s=n?`Claimed ${r} tests, found ${e.total} tests`:r===null?"Could not extract test count from claim":`Claimed ${r} tests, but only ${e.total} exist`;return{evidence:i,verified:n,reasoning:s,confidence:n?.95:.3}}catch(e){let r=e instanceof Error?e.message:"Unknown error";return{evidence:[{type:"command-output",location:this.config.testCommand,content:`Test execution failed: ${r}`,verified:!1,timestamp:new Date}],verified:!1,reasoning:`Failed to run tests: ${r}`,confidence:0}}}async verifyTestExecution(t){try{let e=await this.runTests(),r=[{type:"test-result",location:"test-execution",content:`Tests passed: ${e.passed}/${e.total}`,verified:e.failed===0,timestamp:new Date,context:{total:e.total,passed:e.passed,failed:e.failed}},{type:"command-output",location:this.config.testCommand,content:e.rawOutput,verified:!0,timestamp:new Date}],i=e.failed===0&&e.total>0,n=t.statement.toLowerCase().includes("pass")?i:!i,s=i?`All ${e.total} tests passed`:`${e.failed} of ${e.total} tests failed`,a=e.total>0?.95:.3;return{evidence:r,verified:n,reasoning:s,confidence:a}}catch(e){let r=e instanceof Error?e.message:"Unknown error";return{evidence:[{type:"command-output",location:this.config.testCommand,content:`Test execution failed: ${r}`,verified:!1,timestamp:new Date}],verified:!1,reasoning:`Failed to run tests: ${r}`,confidence:0}}}async verifyCoverage(t){try{let e=await this.getCoverageData(),r=this.extractPercentage(t.statement),i=[{type:"coverage-data",location:this.config.coverageReportPath,content:`Lines: ${e.lines}%, Statements: ${e.statements}%, Functions: ${e.functions}%, Branches: ${e.branches}%`,verified:!0,timestamp:new Date,context:e.rawData}],n=e.lines,s=r!==null&&n>=r,a=s?`Claimed ${r}% coverage, actual coverage is ${n}%`:r===null?"Could not extract coverage percentage from claim":`Claimed ${r}% coverage, but actual is only ${n}%`;return{evidence:i,verified:s,reasoning:a,confidence:s?.95:.3}}catch(e){let r=e instanceof Error?e.message:"Unknown error";return{evidence:[{type:"coverage-data",location:this.config.coverageReportPath,content:`Coverage data unavailable: ${r}`,verified:!1,timestamp:new Date}],verified:!1,reasoning:`Failed to get coverage data: ${r}`,confidence:0}}}async runTests(){let t=ld.get(this.config.testCommand);if(!t)throw new Error(`Test command not in allowlist: "${this.config.testCommand}". Allowed: ${[...ld.keys()].join(", ")}`);let{stdout:e,stderr:r}=await Fg(t.bin,[...t.args],{cwd:this.config.rootDir,timeout:this.config.timeout}),i=e+r;return{...this.parseTestOutput(i),rawOutput:i}}parseTestOutput(t){let e=t.match(/(\d+) passed(?:\s+\|\s+(\d+) failed)?/);if(e){let r=parseInt(e[1],10),i=e[2]?parseInt(e[2],10):0;return{total:r+i,passed:r,failed:i}}return e=t.match(/Tests:\s+(\d+) failed.*?(\d+) passed.*?(\d+) total/),e?{total:parseInt(e[3],10),passed:parseInt(e[2],10),failed:parseInt(e[1],10)}:{total:0,passed:0,failed:0}}async getCoverageData(){let t=Mg(this.config.rootDir,this.config.coverageReportPath),e=await Ig(t,"utf-8"),r=E(e),i=r.total||r;return{lines:i.lines?.pct??0,statements:i.statements?.pct??0,functions:i.functions?.pct??0,branches:i.branches?.pct??0,rawData:r}}async verifyExistingEvidence(t){let e=t.filter(i=>i.type==="test-result"||i.type==="coverage-data");if(e.length===0)return{evidence:[],verified:!1,reasoning:"No test or coverage evidence provided",confidence:0};let r=e.every(i=>i.verified);return{evidence:e,verified:r,reasoning:r?`All ${e.length} evidence items verified`:"Some evidence items failed verification",confidence:r?.8:.3}}extractNumber(t){let e=t.match(/\d+/);return e?parseInt(e[0],10):null}extractPercentage(t){let e=t.match(/(\d+)%/);return e?parseInt(e[1],10):null}};import{execFile as Lg}from"node:child_process";import{promisify as $g}from"node:util";var Og=$g(Lg),ud=new Map([["npm run build",{bin:"npm",args:["run","build"]}],["npm run lint",{bin:"npm",args:["run","lint"]}],["npm test",{bin:"npm",args:["test"]}],["npm run typecheck",{bin:"npm",args:["run","typecheck"]}],["npm run test:unit",{bin:"npm",args:["run","test:unit"]}],["npm run test:ci",{bin:"npm",args:["run","test:ci"]}]]),Di=class{config;patterns={build:[{pattern:/build successful/i,type:"success",location:"stdout"},{pattern:/compiled successfully/i,type:"success",location:"stdout"},{pattern:/done in/i,type:"success",location:"stdout"},{pattern:/error/i,type:"error",location:"stderr"},{pattern:/failed/i,type:"error",location:"both"},{pattern:/warning/i,type:"warning",location:"both"}],lint:[{pattern:/no problems found/i,type:"success",location:"stdout"},{pattern:/✔.*\d+ problems?/i,type:"success",location:"stdout"},{pattern:/✖.*\d+ problems?/i,type:"error",location:"stdout"},{pattern:/error/i,type:"error",location:"both"}]};constructor(t){this.config={rootDir:t.rootDir,timeout:t.timeout??6e4,maxOutputSize:t.maxOutputSize??1024*1024,env:t.env??{}}}async verify(t,e){let r=Date.now();try{let i=this.extractCommand(t);if(!i){let c=await this.verifyExistingEvidence(t.evidence),l=Date.now()-r;return{claimId:t.id,verified:c.verified,confidence:c.confidence,method:"execution",reasoning:c.reasoning,allInstancesChecked:!0,instancesChecked:c.evidence.length,instancesPassed:c.verified?c.evidence.length:0,verificationTimeMs:l,verifiedAt:new Date,requiresHumanReview:c.confidence<.7}}let n=await this.executeCommand(i),s=this.createEvidence(i,n),a=this.analyzeOutput(t,n),o=Date.now()-r;return{claimId:t.id,verified:a.verified,confidence:a.confidence,method:"execution",reasoning:a.reasoning,allInstancesChecked:!0,instancesChecked:1,instancesPassed:a.verified?1:0,verificationTimeMs:o,verifiedAt:new Date,requiresHumanReview:a.confidence<.8,counterEvidence:a.verified?void 0:s}}catch(i){let n=Date.now()-r,s=i instanceof Error?i.message:"Unknown error";return{claimId:t.id,verified:!1,confidence:0,method:"execution",reasoning:`Verification failed: ${s}`,allInstancesChecked:!1,instancesChecked:0,instancesPassed:0,verificationTimeMs:n,verifiedAt:new Date,requiresHumanReview:!0}}}extractCommand(t){for(let i of t.evidence)if(i.type==="command-output"&&i.location)return i.location;let e=t.statement.toLowerCase();if(e.includes("build"))return"npm run build";if(e.includes("lint"))return"npm run lint";if(e.includes("test"))return"npm test";if(e.includes("typecheck")||e.includes("type check"))return"npm run typecheck";let r=e.match(/`([^`]+)`|"([^"]+)"/);return r?r[1]||r[2]:null}async executeCommand(t){let e=Date.now(),r=ud.get(t);if(!r)throw new Error(`Command not in allowlist: "${t}". Allowed: ${[...ud.keys()].join(", ")}`);try{let{stdout:i,stderr:n}=await Og(r.bin,[...r.args],{cwd:this.config.rootDir,timeout:this.config.timeout,maxBuffer:this.config.maxOutputSize,env:{...process.env,...this.config.env}}),s=Date.now()-e;return{stdout:this.truncateOutput(i),stderr:this.truncateOutput(n),exitCode:0,duration:s,success:!0}}catch(i){let n=Date.now()-e;if(i&&typeof i=="object"&&"stdout"in i&&"stderr"in i){let s=i;return{stdout:this.truncateOutput(s.stdout||""),stderr:this.truncateOutput(s.stderr||""),exitCode:s.code??1,duration:n,success:!1}}throw i}}createEvidence(t,e){let r=[];return e.stdout&&r.push({type:"command-output",location:t,content:e.stdout,verified:e.success,timestamp:new Date,contentHash:Pi(e.stdout),context:{stream:"stdout",exitCode:e.exitCode,duration:e.duration}}),e.stderr&&r.push({type:"command-output",location:t,content:e.stderr,verified:e.success,timestamp:new Date,contentHash:Pi(e.stderr),context:{stream:"stderr",exitCode:e.exitCode,duration:e.duration}}),r}analyzeOutput(t,e){let r=t.statement.toLowerCase(),i=this.inferCommandType(r),n=i?this.patterns[i]:[],s=!1,a=!1,o=!1;for(let g of n){let b=g.location==="both"?e.stdout+e.stderr:g.location==="stdout"?e.stdout:e.stderr;(typeof g.pattern=="string"?new RegExp(g.pattern,"i"):g.pattern).test(b)&&(g.type==="success"&&(s=!0),g.type==="error"&&(a=!0),g.type==="warning"&&(o=!0))}let c=r.includes("success")||r.includes("pass")||r.includes("complete"),l=r.includes("fail")||r.includes("error"),d,m,h;return c?(d=e.success&&s&&!a,m=d?.95:o?.7:.3,h=d?"Command executed successfully with expected output":e.success?"Command succeeded but output patterns do not match":"Command failed with exit code "+e.exitCode):l?(d=!e.success||a,m=d?.95:.3,h=d?"Command failed as claimed":"Command succeeded, contradicting the claim"):(d=e.exitCode===0,m=.8,h=d?"Command completed successfully":"Command exited with error code "+e.exitCode),{verified:d,confidence:m,reasoning:h}}inferCommandType(t){return t.includes("build")?"build":t.includes("lint")?"lint":null}async verifyExistingEvidence(t){let e=t.filter(o=>o.type==="command-output");if(e.length===0)return{evidence:[],verified:!1,reasoning:"No command output evidence provided",confidence:0};let r=e.some(o=>/error|failed/i.test(o.content)),n=e.some(o=>/success|passed|done/i.test(o.content))&&!r,s=n?.8:.3,a=n?`Found ${e.length} evidence items indicating success`:r?"Evidence contains error indicators":"Evidence does not indicate success";return{evidence:e,verified:n,reasoning:a,confidence:s}}truncateOutput(t){return t.length<=this.config.maxOutputSize?t:t.substring(0,this.config.maxOutputSize)+`
|
|
2720
2720
|
|
|
2721
|
-
... [output truncated]`}};var Ps=class{config;fileVerifier;testVerifier;outputVerifier;history=[];constructor(t){this.config={...mc,...t.verifier},this.fileVerifier=new xi({rootDir:t.rootDir,...t.fileVerifier}),this.testVerifier=new ki({rootDir:t.rootDir,...t.testVerifier}),this.outputVerifier=new Di({rootDir:t.rootDir,...t.outputVerifier})}async verify(t,e){try{let r={confidenceThreshold:this.config.defaultConfidenceThreshold,timeout:this.config.defaultTimeout,checkAllInstances:this.requiresStrictVerification(t.type),collectCounterEvidence:!0,useMultiModel:this.config.enableMultiModel&&this.isSecurityClaim(t.type),...e},i=this.selectVerificationMethod(t,r),n=await this.executeVerification(t,i,r);return this.config.enableStatistics&&this.recordVerification(t,n),{success:!0,value:n}}catch(r){return{success:!1,error:this.handleError(r,t.id)}}}async verifyReport(t,e){try{let r={confidenceThreshold:this.config.defaultConfidenceThreshold,qualityThreshold:this.config.reportQualityThreshold,timeout:this.config.defaultTimeout,parallelLimit:this.config.maxParallelVerifications,failFast:!1,verificationOrder:"severity",...e},i=this.sortClaimsByPriority(t.claims,r.verificationOrder),n=[],s=[];for(let d=0;d<i.length;d+=r.parallelLimit){let m=i.slice(d,d+r.parallelLimit),h=await Promise.all(m.map(g=>this.verify(g,r)));for(let g of h){if(!g.success){if(r.failFast)throw g.error;continue}n.push(g.value);let b=this.checkIfFlagged(m.find(w=>w.id===g.value.claimId),g.value,r);b&&s.push(b)}}let a=this.calculateSummary(n),o=a.averageConfidence,c=o>=r.qualityThreshold&&s.filter(d=>d.priority==="urgent").length===0;return{success:!0,value:{reportId:t.id,report:t,claims:t.claims,results:n,overallConfidence:o,flaggedClaims:s,summary:a,verifiedAt:new Date,passed:c,qualityThreshold:r.qualityThreshold}}}catch(r){return{success:!1,error:this.handleError(r,t.id)}}}async verifyBatch(t,e){try{let r=await Promise.all(t.map(s=>this.verify(s,e))),i=r.filter(s=>s.success).map(s=>s.value),n=r.filter(s=>!s.success);return n.length>0?{success:!1,error:n[0].error}:{success:!0,value:i}}catch(r){return{success:!1,error:this.handleError(r)}}}getStats(){let t=new Date;return{totalClaims:this.history.length,verified:this.history.filter(r=>r.result.verified).length,rejected:this.history.filter(r=>!r.result.verified).length,disputed:this.history.filter(r=>r.result.confidence<.5).length,avgConfidence:this.calculateAverageConfidence(this.history),byType:this.calculateTypeStats(),byMethod:this.calculateMethodStats(),bySourceAgent:this.calculateAgentStats(),lastUpdated:t,timeWindow:{start:this.history[0]?.timestamp??t,end:t}}}resetStats(){this.history.length=0}requiresStrictVerification(t){return xs.includes(t)}getRecommendedMethod(t){return Es[t]}selectVerificationMethod(t,e){return e.preferredMethods&&e.preferredMethods.length>0?e.preferredMethods[0]:this.getRecommendedMethod(t.type)}async executeVerification(t,e,r){switch(e){case"cross-file":return this.fileVerifier.verify(t,r);case"execution":return t.type==="coverage-claim"||t.statement.toLowerCase().includes("test")?this.testVerifier.verify(t,r):this.outputVerifier.verify(t,r);case"code-trace":return this.fileVerifier.verify(t,r);case"static-analysis":return this.fileVerifier.verify(t,r);case"multi-model":let i=this.getRecommendedMethod(t.type);return this.executeVerification(t,i,r);default:throw As("METHOD_NOT_AVAILABLE",`Verification method '${e}' is not available`,{retryable:!1})}}isSecurityClaim(t){return t==="security-implementation"||t==="security-vulnerability"}sortClaimsByPriority(t,e="severity"){return e==="sequential"?[...t]:[...t].sort((r,i)=>{if(e==="severity"){let s=["critical","high","medium","low"];return s.indexOf(r.severity)-s.indexOf(i.severity)}let n=["security-vulnerability","security-implementation","coverage-claim","pattern-implementation","metric-count"];return n.indexOf(r.type)-n.indexOf(i.type)})}checkIfFlagged(t,e,r){if(e.verified&&e.confidence>=r.confidenceThreshold)return null;let i;e.verified?e.confidence<r.confidenceThreshold?i="low-confidence":!e.allInstancesChecked&&this.requiresStrictVerification(t.type)?i="partial-verification":i="verification-failed":i="verification-failed";let n;e.verified?e.confidence<.5?n="human-review-required":e.confidence<r.confidenceThreshold?n="add-disclaimer":n="re-verify":n="remove-from-report";let s;return this.isSecurityClaim(t.type)&&!e.verified?s="urgent":t.severity==="critical"?s="high":t.severity==="high"?s="medium":s="low",{claim:t,result:e,reason:i,recommendedAction:n,priority:s}}calculateSummary(t){let e={"security-implementation":{total:0,verified:0,rejected:0,avgConfidence:0},"security-vulnerability":{total:0,verified:0,rejected:0,avgConfidence:0},"metric-count":{total:0,verified:0,rejected:0,avgConfidence:0},"pattern-implementation":{total:0,verified:0,rejected:0,avgConfidence:0},"coverage-claim":{total:0,verified:0,rejected:0,avgConfidence:0}},r={"code-trace":0,execution:0,"cross-file":0,"multi-model":0,"static-analysis":0},i=0,n=0;for(let s of t)r[s.method]++,i+=s.verificationTimeMs??0,n+=s.confidence;return{totalClaims:t.length,verified:t.filter(s=>s.verified).length,rejected:t.filter(s=>!s.verified).length,disputed:t.filter(s=>s.confidence<.5).length,requiresReview:t.filter(s=>s.requiresHumanReview).length,averageConfidence:t.length>0?n/t.length:0,totalTimeMs:i,byType:e,byMethod:r}}recordVerification(t,e){this.history.push({claimId:t.id,claimType:t.type,method:e.method,result:e,timestamp:new Date})}calculateAverageConfidence(t){return t.length===0?0:t.reduce((r,i)=>r+i.result.confidence,0)/t.length}calculateTypeStats(){let t={"security-implementation":this.createEmptyTypeStats(),"security-vulnerability":this.createEmptyTypeStats(),"metric-count":this.createEmptyTypeStats(),"pattern-implementation":this.createEmptyTypeStats(),"coverage-claim":this.createEmptyTypeStats()};for(let e of this.history){let r=t[e.claimType];r.total++,e.result.verified?r.verified++:r.rejected++}for(let e of Object.keys(t)){let r=this.history.filter(i=>i.claimType===e);t[e].avgConfidence=this.calculateAverageConfidence(r),t[e].avgVerificationTimeMs=r.length>0?r.reduce((i,n)=>i+(n.result.verificationTimeMs??0),0)/r.length:0}return t}calculateMethodStats(){let t={"code-trace":this.createEmptyMethodStats(),execution:this.createEmptyMethodStats(),"cross-file":this.createEmptyMethodStats(),"multi-model":this.createEmptyMethodStats(),"static-analysis":this.createEmptyMethodStats()};for(let e of this.history){let r=t[e.method];r.timesUsed++}for(let e of Object.keys(t)){let r=this.history.filter(i=>i.method===e);r.length>0&&(t[e].successRate=r.filter(i=>i.result.verified).length/r.length,t[e].avgConfidence=this.calculateAverageConfidence(r),t[e].avgTimeMs=r.reduce((i,n)=>i+(n.result.verificationTimeMs??0),0)/r.length)}return t}calculateAgentStats(){let t={};for(let e of this.history){let r=e.claimId.split("-")[0];t[r]||(t[r]={claimsSubmitted:0,claimsVerified:0,claimsRejected:0,verificationRate:0,avgConfidence:0}),t[r].claimsSubmitted++,e.result.verified?t[r].claimsVerified++:t[r].claimsRejected++}for(let e of Object.keys(t)){let r=this.history.filter(i=>i.claimId.startsWith(e));t[e].verificationRate=t[e].claimsVerified/t[e].claimsSubmitted,t[e].avgConfidence=this.calculateAverageConfidence(r)}return t}createEmptyTypeStats(){return{total:0,verified:0,rejected:0,disputed:0,avgConfidence:0,avgVerificationTimeMs:0}}createEmptyMethodStats(){return{timesUsed:0,successRate:0,avgConfidence:0,avgTimeMs:0}}handleError(t,e){if(t&&typeof t=="object"&&"code"in t)return t;let r=t instanceof Error?t.message:"Unknown verification error";return As("INTERNAL_ERROR",r,{claimId:e,retryable:!1})}};function hc(u){return new Ps(u)}function Pi(u){let t=0;for(let e=0;e<u.length;e++){let r=u.charCodeAt(e);t=(t<<5)-t+r,t=t&t}return Math.abs(t).toString(16).padStart(8,"0")}var ks=R.create("quality-assessment/claim-verifier");async function dd(u){try{let t=u||process.cwd();return hc({rootDir:t,verifier:{enableStatistics:!0,enableMultiModel:!1,defaultConfidenceThreshold:.7}})}catch(t){throw new Error(`Failed to initialize ClaimVerifier: ${T(t)}`)}}async function md(u,t){try{let e=Ng(u,"quality-analysis");if(e.claims.length===0)return u;let r=await t.verifyReport(e);return r.success?{...u,claimVerification:{verified:r.value.passed,confidence:r.value.overallConfidence,unverifiedClaims:r.value.flaggedClaims.length}}:(ks.warn("Claim verification failed:"),u)}catch(e){return ks.error("Failed to verify report claims:",e instanceof Error?e:void 0),u}}async function pd(u,t){try{let e=Vg(u);if(e.claims.length===0)return u;let r=await t.verifyReport(e);return r.success?{...u,claimVerification:{verified:r.value.passed,confidence:r.value.overallConfidence,unverifiedClaims:r.value.flaggedClaims.length}}:(ks.warn("Gate claim verification failed:"),u)}catch(e){return ks.error("Failed to verify gate claims:",e instanceof Error?e:void 0),u}}function Ng(u,t){let e=[];for(let r of u.metrics)e.push({id:`metric-${r.name}-${Date.now()}`,type:"metric-count",statement:`Metric ${r.name} = ${r.value}`,evidence:[],sourceAgent:"quality-analyzer",sourceAgentType:"analyzer",severity:r.value<50?"high":r.value<70?"medium":"low",timestamp:new Date,metadata:{name:r.name,value:r.value}});return u.score.coverage<80&&e.push({id:`coverage-${Date.now()}`,type:"coverage-claim",statement:`Code coverage is ${u.score.coverage}%`,evidence:[],sourceAgent:"quality-analyzer",sourceAgentType:"analyzer",severity:u.score.coverage<50?"critical":"high",timestamp:new Date,metadata:{coverage:u.score.coverage}}),{id:`quality-report-${Date.now()}`,type:t,claims:e,generatedAt:new Date,sourceAgent:"quality-assessment-coordinator"}}function Vg(u){let t=[];for(let e of u.checks)t.push({id:`gate-check-${e.name}-${Date.now()}`,type:"metric-count",statement:`Gate check '${e.name}': ${e.value} (threshold: ${e.threshold})`,evidence:[],sourceAgent:"quality-gate",sourceAgentType:"validator",severity:e.passed?"low":e.severity||"medium",timestamp:new Date,metadata:{checkName:e.name,value:e.value,threshold:e.threshold,passed:e.passed}});return{id:`gate-result-${Date.now()}`,type:"gate-evaluation",claims:t,generatedAt:new Date,sourceAgent:"quality-assessment-coordinator"}}M();var Nt=R.create("quality-assessment/gate-evaluation");function hd(u,t,e,r){let i=r,n=[{metricKey:"coverage",thresholdKey:"coverage",isMin:!0},{metricKey:"testsPassing",thresholdKey:"testsPassing",isMin:!0},{metricKey:"criticalBugs",thresholdKey:"criticalBugs",isMin:!1},{metricKey:"codeSmells",thresholdKey:"codeSmells",isMin:!1},{metricKey:"securityVulnerabilities",thresholdKey:"securityVulnerabilities",isMin:!1},{metricKey:"technicalDebt",thresholdKey:"technicalDebt",isMin:!1},{metricKey:"duplications",thresholdKey:"duplications",isMin:!1}];for(let{metricKey:s,thresholdKey:a,isMin:o}of n){let c=u[s],l=t[a];if(l===void 0)continue;let d=o?l.min:l.max;if(d===void 0||d===0)continue;let m=Math.abs(c-d)/d;if(m<i)return Nt.info(`Borderline detected: ${s}=${c} (threshold=${d}, distance=${(m*100).toFixed(1)}%)`),!0}return!1}async function gd(u,t,e){let r=V({id:`gate-verdict-${v()}`,type:"gate-verdict",confidence:t.overallScore/100,description:`Quality gate '${u.gateName}' verdict: ${t.passed?"PASSED":"FAILED"} (borderline case)`,payload:{metrics:u.metrics,thresholds:u.thresholds,initialResult:t},detectedBy:"quality-assessment-coordinator",severity:t.passed?"medium":"high"});if(!e.requiresConsensus(r))return null;try{let i=await e.verifyFinding(r);if(!i.success)return Nt.warn("Consensus verification failed:"),null;let n=i.value;return Nt.info(`[quality-assessment] Consensus for gate '${u.gateName}': verdict=${n.verdict}, confidence=${(n.confidence*100).toFixed(1)}%`),{...t,consensusVerified:!0,consensusConfidence:n.confidence,consensusVerdict:n.verdict}}catch(i){return Nt.error("Consensus verification error:",i instanceof Error?i:void 0),null}}function fd(u,t){return t.decision==="blocked"||t.decision==="warning"&&u.riskTolerance==="low"||t.riskScore>.7}async function yd(u,t,e){let r=V({id:`release-readiness-${v()}`,type:"release-readiness",confidence:t.confidence,description:`Release readiness for '${u.releaseCandidate}': ${t.decision} (risk: ${(t.riskScore*100).toFixed(0)}%)`,payload:{request:u,initialAdvice:t},detectedBy:"quality-assessment-coordinator",severity:t.decision==="blocked"?"critical":"high"});if(!e.requiresConsensus(r))return null;try{let i=await e.verifyFinding(r);if(!i.success)return Nt.warn("Consensus verification for deployment failed:"),null;let n=i.value;return Nt.info(`[quality-assessment] Consensus for deployment '${u.releaseCandidate}': verdict=${n.verdict}, confidence=${(n.confidence*100).toFixed(1)}%`),{...t,consensusVerified:!0,consensusConfidence:n.confidence,consensusVerdict:n.verdict}}catch(i){return Nt.error("Consensus verification error:",i instanceof Error?i:void 0),null}}var gc={enabled:!1,consecutivePassesRequired:5,ratchetIncrementPercent:2,maxThreshold:95,monotonic:!0,cooldownMs:10080*60*1e3};function fc(u,t,e,r=Date.now()){if(process.env.AQE_GATE_RATCHETING_ENABLED!=="true"||!t.enabled)return e;let i={currentThreshold:e.currentThreshold,consecutivePasses:e.consecutivePasses,lastRatchetTime:e.lastRatchetTime,history:[...e.history]};if(!u)return i.consecutivePasses=0,i;i.consecutivePasses=i.consecutivePasses+1;let n=i.consecutivePasses>=t.consecutivePassesRequired,s=r-i.lastRatchetTime>=t.cooldownMs;if(n&&s){let a=i.currentThreshold+t.ratchetIncrementPercent,o=Math.min(a,t.maxThreshold),c=Math.max(o,i.currentThreshold);c>i.currentThreshold&&(i.currentThreshold=c,i.lastRatchetTime=r,i.history.push({threshold:c,ratchetedAt:r})),i.consecutivePasses=0}return i}Ge();var Bg={maxConcurrentWorkflows:5,defaultTimeout:6e4,publishEvents:!0,enableAutoGating:!1,enableRLThresholdTuning:!0,enableSONAPatternLearning:!0,enableFlashAttention:!0,enableClaimVerification:!0,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2,borderlineMargin:.05},de=R.create("quality-assessment"),Ii=class extends Q{constructor(e,r,i,n={},s){let a={...Bg,...n};super(e,"quality-assessment",a,{verifyFindingTypes:["gate-verdict","tech-debt-classification","release-readiness","risk-scoring"]});this.memory=r;this.agentCoordinator=i;this.qualityGate=new gt(r),this.qualityAnalyzer=new Xe({memory:r,llmRouter:s}),this.deploymentAdvisor=new Ot({memory:r,llmRouter:s})}memory;agentCoordinator;qualityGate;qualityAnalyzer;deploymentAdvisor;actorCritic;qesona;flashAttention;claimVerifier;domain="quality-assessment";recentDreamInsights=[];ratchetState={currentThreshold:70,consecutivePasses:0,lastRatchetTime:0,history:[]};async onInitialize(){try{this.subscribeToEvents(),await this.loadWorkflowState(),await this.loadRatchetState(),this.config.enableRLThresholdTuning&&await this.initializeActorCritic(),this.config.enableSONAPatternLearning&&await this.initializeQESONA(),this.config.enableFlashAttention&&await this.initializeFlashAttention(),this.config.enableClaimVerification&&await this.initializeClaimVerifier()}catch(e){let r=`Failed to initialize quality-assessment coordinator: ${T(e)}`;throw new Error(r)}}async onDispose(){await this.saveWorkflowState(),this.flashAttention?.dispose(),this.qesona&&(await this.qesona.close(),this.qesona=void 0)}getActiveWorkflows(){return super.getActiveWorkflows()}getHealthyRoutingDomains(){return this.minCutMixin.getHealthyRoutingDomains()}async evaluateGate(e){let r=v();try{if(this.startWorkflow(r,"gate-evaluation"),this.minCutMixin.shouldPauseOperations())return de.warn("Quality gate evaluation paused: topology is in critical state"),this.failWorkflow(r,"Topology is in critical state"),p(new Error("Quality gate evaluation paused: topology is in critical state"));this.isTopologyHealthy()||de.warn("Topology degraded - applying stricter thresholds for quality gate");let i=await this.spawnQualityGateAgent(r,e);i.success&&this.addAgentToWorkflow(r,i.value);let n=e;if(this.config.enableRLThresholdTuning&&this.actorCritic){let c=await this.tuneThresholdsWithRL(e.metrics);c&&(n={...e,thresholds:c.thresholds})}let s=await this.qualityGate.evaluateGate(n);if(i.success&&await this.agentCoordinator.stop(i.value),!s.success)return this.failWorkflow(r,"Evaluation failed"),s;let a=s.value;if(this.config.enableConsensus&&this.isBorderlineGateResult(e.metrics,e.thresholds,s.value)){let c=await this.verifyGateVerdictWithConsensus(n,s.value);c&&(a=c)}if(this.completeWorkflow(r),St()&&this.qesona?.isThreeLoopEnabled()){let c=n.metrics;this.qesona.instantAdapt([c.coverage/100,c.testsPassing/100,c.criticalBugs/10,c.codeSmells/100,c.securityVulnerabilities/10,c.technicalDebt/100,c.duplications/100,a.overallScore/100]);try{if(this.qesona.recordOutcome(a.overallScore/100),this.qesona.shouldConsolidate())try{this.qesona.backgroundConsolidate()}catch{}}catch{}}this.config.enableSONAPatternLearning&&this.qesona&&await this.storeQualityPattern(n,a),this.config.enableRLThresholdTuning&&this.actorCritic&&await this.trainActorCritic(n,a);try{(await Cl()).append(a.passed?"QUALITY_GATE_PASS":"QUALITY_GATE_FAIL",{gateName:e.gateName,passed:a.passed,score:a.overallScore,failedChecks:a.failedChecks},"quality-gate")}catch{}if(process.env.AQE_GATE_RATCHETING_ENABLED==="true")try{let c=this.ratchetState.currentThreshold;this.ratchetState=fc(a.passed,gc,this.ratchetState),this.ratchetState.currentThreshold>c&&(de.info(`Gate threshold ratcheted: ${c} -> ${this.ratchetState.currentThreshold}`),await this.saveRatchetState())}catch(c){de.warn("Gate ratcheting failed (non-critical)",{error:c instanceof Error?c.message:String(c)})}this.config.publishEvents&&await this.publishQualityGateEvaluated(a);let o=await this.verifyGateResultClaims(a);return f(o)}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}isBorderlineGateResult(e,r,i){return hd(e,r,i,this.config.borderlineMargin)}async verifyGateVerdictWithConsensus(e,r){return gd(e,r,this.consensusMixin)}async analyzeQuality(e){let r=v();try{if(this.startWorkflow(r,"quality-analysis"),this.minCutMixin.shouldPauseOperations())return de.warn("Quality analysis paused: topology is in critical state"),this.failWorkflow(r,"Topology is in critical state"),p(new Error("Quality analysis paused: topology is in critical state"));this.isTopologyHealthy()||de.warn("Topology degraded during quality analysis");let n=await this.spawnQualityAnalyzerAgent(r,e);n.success&&this.addAgentToWorkflow(r,n.value);let s=await this.qualityAnalyzer.analyzeQuality(e);if(n.success&&await this.agentCoordinator.stop(n.value),!s.success)return this.failWorkflow(r,"Evaluation failed"),s;if(this.completeWorkflow(r),this.config.enableFlashAttention&&this.flashAttention&&s.value.metrics.length>0){let o=await this.enhanceWithSimilarityPatterns(s.value);o&&(s.value=o)}if(St()&&this.qesona?.isThreeLoopEnabled()){let o=s.value.score;this.qesona.instantAdapt([o.overall/100,s.value.metrics.length/20,s.value.trends.length/10,s.value.recommendations.length/10]);try{if(this.qesona.recordOutcome(o.overall/100),this.qesona.shouldConsolidate())try{this.qesona.backgroundConsolidate()}catch{}}catch{}}this.config.enableSONAPatternLearning&&this.qesona&&await this.storeQualityAnalysisPattern(e,s.value),this.config.enableAutoGating&&s.value.score.overall<70&&await this.memory.set(`quality-assessment:auto-gate:${r}`,{score:s.value.score,recommendations:s.value.recommendations},{namespace:"quality-assessment",ttl:3600});let a=await this.verifyQualityReportClaims(s.value);return f(a)}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async getDeploymentAdvice(e){let r=v();try{if(this.startWorkflow(r,"deployment-advice"),this.minCutMixin.shouldPauseOperations())return de.warn("Deployment advice paused: topology is in critical state"),this.failWorkflow(r,"Topology is in critical state"),p(new Error("Deployment advice paused: topology is in critical state"));this.isTopologyHealthy()||de.warn("Topology degraded during deployment advice generation");let i=await this.spawnDeploymentAdvisorAgent(r,e);i.success&&this.addAgentToWorkflow(r,i.value);let n=await this.deploymentAdvisor.getDeploymentAdvice(e);if(i.success&&await this.agentCoordinator.stop(i.value),!n.success)return this.failWorkflow(r,"Evaluation failed"),n;let s=n.value;if(this.config.enableConsensus&&this.isHighRiskDeployment(e,n.value)){let a=await this.verifyDeploymentAdviceWithConsensus(e,n.value);a&&(s=a)}return this.completeWorkflow(r),this.config.publishEvents&&await this.publishDeploymentDecision(s,e.releaseCandidate),f(s)}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}isHighRiskDeployment(e,r){return fd(e,r)}async verifyDeploymentAdviceWithConsensus(e,r){return yd(e,r,this.consensusMixin)}async analyzeComplexity(e){let r=v();try{if(this.startWorkflow(r,"complexity-analysis"),this.minCutMixin.shouldPauseOperations())return de.warn("Complexity analysis paused: topology is in critical state"),this.failWorkflow(r,"Topology is in critical state"),p(new Error("Complexity analysis paused: topology is in critical state"));this.isTopologyHealthy()||de.warn("Topology degraded during complexity analysis");let i=await this.spawnComplexityAnalyzerAgent(r,e);i.success&&this.addAgentToWorkflow(r,i.value);let n=await this.qualityAnalyzer.analyzeComplexity(e);return i.success&&await this.agentCoordinator.stop(i.value),n.success?(this.completeWorkflow(r),n):(this.failWorkflow(r,"Evaluation failed"),n)}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async generateReport(e){return Uu(this.memory,e)}async getQualityDashboard(){return Qu(this.memory)}async analyzeRisks(e){return Ku(this.memory,e)}async evaluateQualityGate(e){let r=Ju(e),i=await this.evaluateGate(r);return i.success?f({passed:i.value.passed,score:i.value.overallScore,violations:i.value.failedChecks}):p(i.error)}async assessDeploymentReadiness(e){return Yu(this.memory,e)}async analyzeTechnicalDebt(e){return Xu(this.memory,e)}async spawnQualityGateAgent(e,r){if(!this.agentCoordinator.canSpawn())return p(new Error("Agent limit reached"));let i={name:`quality-gate-${e.slice(0,8)}`,domain:"quality-assessment",type:"validator",capabilities:["quality-gate","threshold-evaluation"],config:{workflowId:e,gateName:r.gateName}};return this.agentCoordinator.spawn(i)}async spawnQualityAnalyzerAgent(e,r){if(!this.agentCoordinator.canSpawn())return p(new Error("Agent limit reached"));let i={name:`quality-analyzer-${e.slice(0,8)}`,domain:"quality-assessment",type:"analyzer",capabilities:["quality-analysis","metrics-collection","trend-analysis"],config:{workflowId:e,sourceFiles:r.sourceFiles,includeMetrics:r.includeMetrics}};return this.agentCoordinator.spawn(i)}async spawnDeploymentAdvisorAgent(e,r){if(!this.agentCoordinator.canSpawn())return p(new Error("Agent limit reached"));let i={name:`deployment-advisor-${e.slice(0,8)}`,domain:"quality-assessment",type:"analyzer",capabilities:["deployment-advice","risk-scoring","ml-prediction"],config:{workflowId:e,releaseCandidate:r.releaseCandidate,riskTolerance:r.riskTolerance}};return this.agentCoordinator.spawn(i)}async spawnComplexityAnalyzerAgent(e,r){if(!this.agentCoordinator.canSpawn())return p(new Error("Agent limit reached"));let i={name:`complexity-analyzer-${e.slice(0,8)}`,domain:"quality-assessment",type:"analyzer",capabilities:["complexity-analysis","cyclomatic","cognitive","maintainability"],config:{workflowId:e,sourceFiles:r.sourceFiles,metrics:r.metrics}};return this.agentCoordinator.spawn(i)}async publishQualityGateEvaluated(e){let r=I(nn.QualityGateEvaluated,"quality-assessment",{gateId:v(),passed:e.passed,checks:e.checks.map(i=>({name:i.name,passed:i.passed,value:i.value,threshold:i.threshold}))});await this.eventBus.publish(r)}async publishDeploymentDecision(e,r){let i=e.decision==="approved"?nn.DeploymentApproved:nn.DeploymentBlocked,n=I(i,"quality-assessment",{decision:e.decision,reason:e.reasons.join("; "),riskScore:e.riskScore,recommendations:e.conditions||[],releaseCandidate:r});await this.eventBus.publish(n)}subscribeToEvents(){this.eventBus.subscribe("test-execution.TestRunCompleted",this.handleTestRunCompleted.bind(this)),this.eventBus.subscribe("coverage-analysis.CoverageReportCreated",this.handleCoverageReportCreated.bind(this)),this.eventBus.subscribe("security-compliance.SecurityAuditCompleted",this.handleSecurityAuditCompleted.bind(this)),this.subscribeToDreamEvents()}subscribeToDreamEvents(){this.eventBus.subscribe(He.DreamCycleCompleted,this.handleDreamCycleCompleted.bind(this))}async handleDreamCycleCompleted(e){let{insights:r,cycleId:i}=e.payload;if(!r||r.length===0)return;let n=r.filter(s=>{let a=s.suggestedAction?.toLowerCase().includes(this.domain)||s.suggestedAction?.toLowerCase().includes("quality")||s.suggestedAction?.toLowerCase().includes("gate")||s.suggestedAction?.toLowerCase().includes("threshold"),o=s.sourceConcepts.some(l=>l.toLowerCase().includes("quality")||l.toLowerCase().includes(this.domain)||l.toLowerCase().includes("metric")||l.toLowerCase().includes("gate")),c=s.type==="optimization"||s.type==="pattern_merge";return a||o||c&&s.actionable});if(n.length!==0){de.info(`[${this.domain}] Received ${n.length} relevant dream insights from cycle ${i}`);for(let s of n)s.confidenceScore>.7&&s.actionable&&await this.applyDreamInsight(s,i),this.recentDreamInsights.push({...s,receivedAt:new Date});this.recentDreamInsights.length>50&&(this.recentDreamInsights=this.recentDreamInsights.slice(-50))}}async applyDreamInsight(e,r){if(de.info(`[${this.domain}] Applying dream insight: ${e.description.slice(0,100)}...`),this.qesona)try{let i={id:`dream-insight-${e.id}`,features:this.encodeInsightAsFeatures(e),metadata:{insightType:e.type,cycleId:r,sourceConcepts:e.sourceConcepts}},n={type:"dream-insight",value:e.suggestedAction||e.description};this.qesona.createPattern(i,n,{reward:e.confidenceScore,success:!0,quality:e.noveltyScore},"quality-assessment",this.domain,{insightId:e.id,cycleId:r,description:e.description,suggestedAction:e.suggestedAction,dreamDerived:!0}),de.info(`[${this.domain}] Created SONA pattern from dream insight ${e.id}`)}catch(i){de.error(`[${this.domain}] Failed to store dream insight pattern`,i instanceof Error?i:void 0)}await this.memory.set(`${this.domain}:dream-insight:${e.id}`,{insight:e,cycleId:r,appliedAt:new Date().toISOString()},{namespace:this.domain,ttl:86400*7})}encodeInsightAsFeatures(e){return od(e)}async handleTestRunCompleted(e){if(!this.config.enableAutoGating)return;let r=e.payload;await this.memory.set(`quality-assessment:test-results:${r.runId}`,r,{namespace:"quality-assessment",ttl:3600})}async handleCoverageReportCreated(e){let r=e.payload;await this.memory.set("coverage:latest",{line:r.line,branch:r.branch,function:0,statement:0,files:0},{persist:!0})}async handleSecurityAuditCompleted(e){let r=e.payload;await this.memory.set(`quality-assessment:security:${r.auditId}`,r,{namespace:"quality-assessment",ttl:86400})}async loadWorkflowState(){let e=await this.memory.get("quality-assessment:coordinator:workflows");if(e)for(let r of e)r.status==="running"&&(r.status="failed",r.error="Coordinator restarted",r.completedAt=new Date),this.workflows.set(r.id,r)}async saveWorkflowState(){let e=Array.from(this.workflows.values());await this.memory.set("quality-assessment:coordinator:workflows",e,{namespace:"quality-assessment",persist:!0})}async loadRatchetState(){try{let e=await this.memory.get("quality-assessment:ratchet-state");e&&(this.ratchetState=e,de.info(`Restored ratchet state (threshold=${e.currentThreshold}, passes=${e.consecutivePasses})`))}catch(e){de.warn("Failed to load ratchet state (using default)",{error:e instanceof Error?e.message:String(e)})}}async saveRatchetState(){try{await this.memory.set("quality-assessment:ratchet-state",this.ratchetState,{namespace:"quality-assessment",persist:!0})}catch(e){de.warn("Failed to persist ratchet state",{error:e instanceof Error?e.message:String(e)})}}async initializeActorCritic(){this.actorCritic=await Zu()}async initializeQESONA(){this.qesona=await ed()}async initializeFlashAttention(){this.flashAttention=await td()}async tuneThresholdsWithRL(e){return!this.actorCritic||!e?null:rd(this.actorCritic,e)}async trainActorCritic(e,r){this.actorCritic&&await id(this.actorCritic,e,r)}async storeQualityPattern(e,r){this.qesona&&await nd(this.qesona,e,r,this.domain)}async storeQualityAnalysisPattern(e,r){this.qesona&&await sd(this.qesona,e,r,this.domain)}async enhanceWithSimilarityPatterns(e){return!this.flashAttention||!this.qesona?null:ad(e,this.flashAttention,this.qesona,this.domain)}async initializeClaimVerifier(){this.claimVerifier=await dd(this.config.claimVerifierRootDir)}async verifyQualityReportClaims(e){return!this.config.enableClaimVerification||!this.claimVerifier?e:md(e,this.claimVerifier)}async verifyGateResultClaims(e){return!this.config.enableClaimVerification||!this.claimVerifier?e:pd(e,this.claimVerifier)}getClaimVerifierStats(){return this.claimVerifier?.getStats()??null}};A();var Is=class extends j{constructor(e,r,i,n={},s){super(e,r);this.agentCoordinator=i;this.llmRouter=s;this.pluginConfig=n}agentCoordinator;llmRouter;coordinator=null;qualityGate=null;qualityAnalyzer=null;deploymentAdvisor=null;pluginConfig;get name(){return"quality-assessment"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{evaluateGate:this.evaluateGate.bind(this),analyzeQuality:this.analyzeQuality.bind(this),getDeploymentAdvice:this.getDeploymentAdvice.bind(this),analyzeComplexity:this.analyzeComplexity.bind(this),getCoordinator:()=>this.coordinator,getQualityGate:()=>this.qualityGate,getQualityAnalyzer:()=>this.qualityAnalyzer,getDeploymentAdvisor:()=>this.deploymentAdvisor}}getTaskHandlers(){return new Map([["evaluate-gate",async e=>{let r=e.gateName,i=e.metrics,n=e.thresholds;if(!r||!i||!n)return p(new Error("Invalid evaluate-gate payload: missing gateName, metrics, or thresholds"));let s={gateName:r,metrics:i,thresholds:n};return this.evaluateGate(s)}],["analyze-quality",async e=>{let r=e.sourceFiles;if(!r||r.length===0)return p(new Error("Invalid analyze-quality payload: missing sourceFiles"));let i={sourceFiles:r,includeMetrics:e.includeMetrics??["coverage","complexity","maintainability"],compareBaseline:e.compareBaseline};return this.analyzeQuality(i)}],["deployment-advice",async e=>{let r=e.releaseCandidate,i=e.metrics,n=e.riskTolerance;if(!r||!i)return p(new Error("Invalid deployment-advice payload: missing releaseCandidate or metrics"));let s={releaseCandidate:r,metrics:i,riskTolerance:n??"medium"};return this.getDeploymentAdvice(s)}],["analyze-complexity",async e=>{let r=e.sourceFiles;if(!r||r.length===0)return p(new Error("Invalid analyze-complexity payload: missing sourceFiles"));let i={sourceFiles:r,metrics:e.metrics??["cyclomatic","cognitive"]};return this.analyzeComplexity(i)}]])}async onInitialize(){this.qualityGate=new gt(this.memory,this.pluginConfig.qualityGate),this.qualityAnalyzer=new Xe({memory:this.memory,llmRouter:this.llmRouter},this.pluginConfig.qualityAnalyzer),this.deploymentAdvisor=new Ot({memory:this.memory,llmRouter:this.llmRouter},this.pluginConfig.deploymentAdvisor),this.coordinator=new Ii(this.eventBus,this.memory,this.agentCoordinator,this.pluginConfig.coordinator,this.llmRouter),await this.coordinator.initialize(),this.updateHealth({status:"idle",agents:{total:0,active:0,idle:0,failed:0},lastActivity:new Date,errors:[]})}async onDispose(){this.coordinator&&await this.coordinator.dispose(),this.coordinator=null,this.qualityGate=null,this.qualityAnalyzer=null,this.deploymentAdvisor=null}subscribeToEvents(){this.eventBus.subscribe("test-execution.TestRunCompleted",this.handleTestRunCompleted.bind(this)),this.eventBus.subscribe("coverage-analysis.CoverageReportCreated",this.handleCoverageReport.bind(this)),this.eventBus.subscribe("defect-intelligence.DefectPredicted",this.handleDefectPrediction.bind(this)),this.eventBus.subscribe("security-compliance.VulnerabilityDetected",this.handleVulnerabilityDetected.bind(this))}async onEvent(e){switch(this.updateHealth({lastActivity:new Date}),e.type){case"test-execution.TestRunCompleted":await this.handleTestRunCompleted(e);break;case"coverage-analysis.CoverageReportCreated":await this.handleCoverageReport(e);break;case"defect-intelligence.DefectPredicted":await this.handleDefectPrediction(e);break;case"security-compliance.VulnerabilityDetected":await this.handleVulnerabilityDetected(e);break;default:break}}async evaluateGate(e){this.ensureInitialized();try{let r=await this.coordinator.evaluateGate(e);return r.success?this.trackSuccessfulOperation("gate-evaluation"):this.trackFailedOperation(r.error),r}catch(r){return this.handleError(r)}}async analyzeQuality(e){this.ensureInitialized();try{let r=await this.coordinator.analyzeQuality(e);return r.success?this.trackSuccessfulOperation("quality-analysis"):this.trackFailedOperation(r.error),r}catch(r){return this.handleError(r)}}async getDeploymentAdvice(e){this.ensureInitialized();try{let r=await this.coordinator.getDeploymentAdvice(e);return r.success?this.trackSuccessfulOperation("deployment-advice"):this.trackFailedOperation(r.error),r}catch(r){return this.handleError(r)}}async analyzeComplexity(e){this.ensureInitialized();try{let r=await this.coordinator.analyzeComplexity(e);return r.success?this.trackSuccessfulOperation("complexity-analysis"):this.trackFailedOperation(r.error),r}catch(r){return this.handleError(r)}}async handleTestRunCompleted(e){let r=e.payload;if(await this.memory.set(`quality-assessment:test-results:${r.runId}`,{...r,receivedAt:new Date().toISOString()},{namespace:"quality-assessment",ttl:86400}),r.failed>0){let i=r.passed+r.failed+r.skipped,n=r.passed/i*100;n<95&&await this.memory.set(`quality-assessment:concerns:test-failures:${r.runId}`,{type:"test-failures",passingRate:n,failedCount:r.failed,severity:n<80?"high":"medium"},{namespace:"quality-assessment",ttl:86400*7})}}async handleCoverageReport(e){let r=e.payload;await this.memory.set("coverage:latest",{line:r.line,branch:r.branch,function:r.function,statement:r.statement,files:0},{persist:!0})}async handleDefectPrediction(e){let r=e.payload;r.probability>=.7&&await this.memory.set(`quality-assessment:defect-risks:${r.predictionId}`,{...r,severity:r.probability>=.9?"critical":"high"},{namespace:"quality-assessment",ttl:86400*7})}async handleVulnerabilityDetected(e){let r=e.payload;await this.memory.set(`quality-assessment:vulnerabilities:${r.vulnId}`,{...r,receivedAt:new Date().toISOString()},{namespace:"quality-assessment",persist:!0})}ensureInitialized(){if(!this._initialized)throw new Error("QualityAssessmentPlugin is not initialized");if(!this.coordinator||!this.qualityGate||!this.qualityAnalyzer||!this.deploymentAdvisor)throw new Error("QualityAssessmentPlugin services are not available")}handleError(e){let r=y(e),i=this.getHealth();return this.updateHealth({errors:[...i.errors.slice(-9),r.message],status:i.errors.length>=5?"degraded":i.status}),{success:!1,error:r}}trackSuccessfulOperation(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,total:r.agents.total+1,idle:r.agents.idle+1},lastActivity:new Date}),this.memory.set(`quality-assessment:metrics:${e}:${Date.now()}`,{type:e,success:!0,timestamp:new Date().toISOString()},{namespace:"quality-assessment",ttl:86400}).catch(()=>{})}trackFailedOperation(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,failed:r.agents.failed+1},errors:[...r.errors.slice(-9),e.message]})}};function yc(u,t,e,r,i){return new Is(u,t,e,r,i)}M();A();M();import{execFileSync as ye}from"child_process";import*as Ms from"path";function yt(u){return u.replace(/[;&|`$(){}[\]<>\\'"!\n\r]/g,"")}var qg={repoRoot:process.cwd(),maxCommits:100,bugKeywords:["fix","bug","patch","issue","error","defect","problem"],enableCache:!0,cacheTtl:300*1e3},dr=class{config;cache=new Map;isGitRepo=null;constructor(t={}){this.config={...qg,...t}}async isGitRepository(){if(this.isGitRepo!==null)return this.isGitRepo;try{ye("git",["rev-parse","--is-inside-work-tree"],{cwd:this.config.repoRoot,stdio:["pipe","pipe","pipe"]}),this.isGitRepo=!0}catch{this.isGitRepo=!1}return this.isGitRepo}async getChangeFrequency(t){let e=`freq:${t}`,r=this.getFromCache(e);if(r!==void 0)return r;if(!await this.isGitRepository())return .4;try{let i=yt(this.getRelativePath(t)),n=ye("git",["log","--oneline","--since=90 days ago","--",i],{cwd:this.config.repoRoot,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),s=n?n.split(`
|
|
2721
|
+
... [output truncated]`}};var Ps=class{config;fileVerifier;testVerifier;outputVerifier;history=[];constructor(t){this.config={...mc,...t.verifier},this.fileVerifier=new xi({rootDir:t.rootDir,...t.fileVerifier}),this.testVerifier=new ki({rootDir:t.rootDir,...t.testVerifier}),this.outputVerifier=new Di({rootDir:t.rootDir,...t.outputVerifier})}async verify(t,e){try{let r={confidenceThreshold:this.config.defaultConfidenceThreshold,timeout:this.config.defaultTimeout,checkAllInstances:this.requiresStrictVerification(t.type),collectCounterEvidence:!0,useMultiModel:this.config.enableMultiModel&&this.isSecurityClaim(t.type),...e},i=this.selectVerificationMethod(t,r),n=await this.executeVerification(t,i,r);return this.config.enableStatistics&&this.recordVerification(t,n),{success:!0,value:n}}catch(r){return{success:!1,error:this.handleError(r,t.id)}}}async verifyReport(t,e){try{let r={confidenceThreshold:this.config.defaultConfidenceThreshold,qualityThreshold:this.config.reportQualityThreshold,timeout:this.config.defaultTimeout,parallelLimit:this.config.maxParallelVerifications,failFast:!1,verificationOrder:"severity",...e},i=this.sortClaimsByPriority(t.claims,r.verificationOrder),n=[],s=[];for(let d=0;d<i.length;d+=r.parallelLimit){let m=i.slice(d,d+r.parallelLimit),h=await Promise.all(m.map(g=>this.verify(g,r)));for(let g of h){if(!g.success){if(r.failFast)throw g.error;continue}n.push(g.value);let b=this.checkIfFlagged(m.find(w=>w.id===g.value.claimId),g.value,r);b&&s.push(b)}}let a=this.calculateSummary(n),o=a.averageConfidence,c=o>=r.qualityThreshold&&s.filter(d=>d.priority==="urgent").length===0;return{success:!0,value:{reportId:t.id,report:t,claims:t.claims,results:n,overallConfidence:o,flaggedClaims:s,summary:a,verifiedAt:new Date,passed:c,qualityThreshold:r.qualityThreshold}}}catch(r){return{success:!1,error:this.handleError(r,t.id)}}}async verifyBatch(t,e){try{let r=await Promise.all(t.map(s=>this.verify(s,e))),i=r.filter(s=>s.success).map(s=>s.value),n=r.filter(s=>!s.success);return n.length>0?{success:!1,error:n[0].error}:{success:!0,value:i}}catch(r){return{success:!1,error:this.handleError(r)}}}getStats(){let t=new Date;return{totalClaims:this.history.length,verified:this.history.filter(r=>r.result.verified).length,rejected:this.history.filter(r=>!r.result.verified).length,disputed:this.history.filter(r=>r.result.confidence<.5).length,avgConfidence:this.calculateAverageConfidence(this.history),byType:this.calculateTypeStats(),byMethod:this.calculateMethodStats(),bySourceAgent:this.calculateAgentStats(),lastUpdated:t,timeWindow:{start:this.history[0]?.timestamp??t,end:t}}}resetStats(){this.history.length=0}requiresStrictVerification(t){return xs.includes(t)}getRecommendedMethod(t){return Es[t]}selectVerificationMethod(t,e){return e.preferredMethods&&e.preferredMethods.length>0?e.preferredMethods[0]:this.getRecommendedMethod(t.type)}async executeVerification(t,e,r){switch(e){case"cross-file":return this.fileVerifier.verify(t,r);case"execution":return t.type==="coverage-claim"||t.statement.toLowerCase().includes("test")?this.testVerifier.verify(t,r):this.outputVerifier.verify(t,r);case"code-trace":return this.fileVerifier.verify(t,r);case"static-analysis":return this.fileVerifier.verify(t,r);case"multi-model":{let i=this.getRecommendedMethod(t.type);return this.executeVerification(t,i,r)}default:throw As("METHOD_NOT_AVAILABLE",`Verification method '${e}' is not available`,{retryable:!1})}}isSecurityClaim(t){return t==="security-implementation"||t==="security-vulnerability"}sortClaimsByPriority(t,e="severity"){return e==="sequential"?[...t]:[...t].sort((r,i)=>{if(e==="severity"){let s=["critical","high","medium","low"];return s.indexOf(r.severity)-s.indexOf(i.severity)}let n=["security-vulnerability","security-implementation","coverage-claim","pattern-implementation","metric-count"];return n.indexOf(r.type)-n.indexOf(i.type)})}checkIfFlagged(t,e,r){if(e.verified&&e.confidence>=r.confidenceThreshold)return null;let i;e.verified?e.confidence<r.confidenceThreshold?i="low-confidence":!e.allInstancesChecked&&this.requiresStrictVerification(t.type)?i="partial-verification":i="verification-failed":i="verification-failed";let n;e.verified?e.confidence<.5?n="human-review-required":e.confidence<r.confidenceThreshold?n="add-disclaimer":n="re-verify":n="remove-from-report";let s;return this.isSecurityClaim(t.type)&&!e.verified?s="urgent":t.severity==="critical"?s="high":t.severity==="high"?s="medium":s="low",{claim:t,result:e,reason:i,recommendedAction:n,priority:s}}calculateSummary(t){let e={"security-implementation":{total:0,verified:0,rejected:0,avgConfidence:0},"security-vulnerability":{total:0,verified:0,rejected:0,avgConfidence:0},"metric-count":{total:0,verified:0,rejected:0,avgConfidence:0},"pattern-implementation":{total:0,verified:0,rejected:0,avgConfidence:0},"coverage-claim":{total:0,verified:0,rejected:0,avgConfidence:0}},r={"code-trace":0,execution:0,"cross-file":0,"multi-model":0,"static-analysis":0},i=0,n=0;for(let s of t)r[s.method]++,i+=s.verificationTimeMs??0,n+=s.confidence;return{totalClaims:t.length,verified:t.filter(s=>s.verified).length,rejected:t.filter(s=>!s.verified).length,disputed:t.filter(s=>s.confidence<.5).length,requiresReview:t.filter(s=>s.requiresHumanReview).length,averageConfidence:t.length>0?n/t.length:0,totalTimeMs:i,byType:e,byMethod:r}}recordVerification(t,e){this.history.push({claimId:t.id,claimType:t.type,method:e.method,result:e,timestamp:new Date})}calculateAverageConfidence(t){return t.length===0?0:t.reduce((r,i)=>r+i.result.confidence,0)/t.length}calculateTypeStats(){let t={"security-implementation":this.createEmptyTypeStats(),"security-vulnerability":this.createEmptyTypeStats(),"metric-count":this.createEmptyTypeStats(),"pattern-implementation":this.createEmptyTypeStats(),"coverage-claim":this.createEmptyTypeStats()};for(let e of this.history){let r=t[e.claimType];r.total++,e.result.verified?r.verified++:r.rejected++}for(let e of Object.keys(t)){let r=this.history.filter(i=>i.claimType===e);t[e].avgConfidence=this.calculateAverageConfidence(r),t[e].avgVerificationTimeMs=r.length>0?r.reduce((i,n)=>i+(n.result.verificationTimeMs??0),0)/r.length:0}return t}calculateMethodStats(){let t={"code-trace":this.createEmptyMethodStats(),execution:this.createEmptyMethodStats(),"cross-file":this.createEmptyMethodStats(),"multi-model":this.createEmptyMethodStats(),"static-analysis":this.createEmptyMethodStats()};for(let e of this.history){let r=t[e.method];r.timesUsed++}for(let e of Object.keys(t)){let r=this.history.filter(i=>i.method===e);r.length>0&&(t[e].successRate=r.filter(i=>i.result.verified).length/r.length,t[e].avgConfidence=this.calculateAverageConfidence(r),t[e].avgTimeMs=r.reduce((i,n)=>i+(n.result.verificationTimeMs??0),0)/r.length)}return t}calculateAgentStats(){let t={};for(let e of this.history){let r=e.claimId.split("-")[0];t[r]||(t[r]={claimsSubmitted:0,claimsVerified:0,claimsRejected:0,verificationRate:0,avgConfidence:0}),t[r].claimsSubmitted++,e.result.verified?t[r].claimsVerified++:t[r].claimsRejected++}for(let e of Object.keys(t)){let r=this.history.filter(i=>i.claimId.startsWith(e));t[e].verificationRate=t[e].claimsVerified/t[e].claimsSubmitted,t[e].avgConfidence=this.calculateAverageConfidence(r)}return t}createEmptyTypeStats(){return{total:0,verified:0,rejected:0,disputed:0,avgConfidence:0,avgVerificationTimeMs:0}}createEmptyMethodStats(){return{timesUsed:0,successRate:0,avgConfidence:0,avgTimeMs:0}}handleError(t,e){if(t&&typeof t=="object"&&"code"in t)return t;let r=t instanceof Error?t.message:"Unknown verification error";return As("INTERNAL_ERROR",r,{claimId:e,retryable:!1})}};function hc(u){return new Ps(u)}function Pi(u){let t=0;for(let e=0;e<u.length;e++){let r=u.charCodeAt(e);t=(t<<5)-t+r,t=t&t}return Math.abs(t).toString(16).padStart(8,"0")}var ks=R.create("quality-assessment/claim-verifier");async function dd(u){try{let t=u||process.cwd();return hc({rootDir:t,verifier:{enableStatistics:!0,enableMultiModel:!1,defaultConfidenceThreshold:.7}})}catch(t){throw new Error(`Failed to initialize ClaimVerifier: ${T(t)}`)}}async function md(u,t){try{let e=Ng(u,"quality-analysis");if(e.claims.length===0)return u;let r=await t.verifyReport(e);return r.success?{...u,claimVerification:{verified:r.value.passed,confidence:r.value.overallConfidence,unverifiedClaims:r.value.flaggedClaims.length}}:(ks.warn("Claim verification failed:"),u)}catch(e){return ks.error("Failed to verify report claims:",e instanceof Error?e:void 0),u}}async function pd(u,t){try{let e=Vg(u);if(e.claims.length===0)return u;let r=await t.verifyReport(e);return r.success?{...u,claimVerification:{verified:r.value.passed,confidence:r.value.overallConfidence,unverifiedClaims:r.value.flaggedClaims.length}}:(ks.warn("Gate claim verification failed:"),u)}catch(e){return ks.error("Failed to verify gate claims:",e instanceof Error?e:void 0),u}}function Ng(u,t){let e=[];for(let r of u.metrics)e.push({id:`metric-${r.name}-${Date.now()}`,type:"metric-count",statement:`Metric ${r.name} = ${r.value}`,evidence:[],sourceAgent:"quality-analyzer",sourceAgentType:"analyzer",severity:r.value<50?"high":r.value<70?"medium":"low",timestamp:new Date,metadata:{name:r.name,value:r.value}});return u.score.coverage<80&&e.push({id:`coverage-${Date.now()}`,type:"coverage-claim",statement:`Code coverage is ${u.score.coverage}%`,evidence:[],sourceAgent:"quality-analyzer",sourceAgentType:"analyzer",severity:u.score.coverage<50?"critical":"high",timestamp:new Date,metadata:{coverage:u.score.coverage}}),{id:`quality-report-${Date.now()}`,type:t,claims:e,generatedAt:new Date,sourceAgent:"quality-assessment-coordinator"}}function Vg(u){let t=[];for(let e of u.checks)t.push({id:`gate-check-${e.name}-${Date.now()}`,type:"metric-count",statement:`Gate check '${e.name}': ${e.value} (threshold: ${e.threshold})`,evidence:[],sourceAgent:"quality-gate",sourceAgentType:"validator",severity:e.passed?"low":e.severity||"medium",timestamp:new Date,metadata:{checkName:e.name,value:e.value,threshold:e.threshold,passed:e.passed}});return{id:`gate-result-${Date.now()}`,type:"gate-evaluation",claims:t,generatedAt:new Date,sourceAgent:"quality-assessment-coordinator"}}M();var Nt=R.create("quality-assessment/gate-evaluation");function hd(u,t,e,r){let i=r,n=[{metricKey:"coverage",thresholdKey:"coverage",isMin:!0},{metricKey:"testsPassing",thresholdKey:"testsPassing",isMin:!0},{metricKey:"criticalBugs",thresholdKey:"criticalBugs",isMin:!1},{metricKey:"codeSmells",thresholdKey:"codeSmells",isMin:!1},{metricKey:"securityVulnerabilities",thresholdKey:"securityVulnerabilities",isMin:!1},{metricKey:"technicalDebt",thresholdKey:"technicalDebt",isMin:!1},{metricKey:"duplications",thresholdKey:"duplications",isMin:!1}];for(let{metricKey:s,thresholdKey:a,isMin:o}of n){let c=u[s],l=t[a];if(l===void 0)continue;let d=o?l.min:l.max;if(d===void 0||d===0)continue;let m=Math.abs(c-d)/d;if(m<i)return Nt.info(`Borderline detected: ${s}=${c} (threshold=${d}, distance=${(m*100).toFixed(1)}%)`),!0}return!1}async function gd(u,t,e){let r=V({id:`gate-verdict-${v()}`,type:"gate-verdict",confidence:t.overallScore/100,description:`Quality gate '${u.gateName}' verdict: ${t.passed?"PASSED":"FAILED"} (borderline case)`,payload:{metrics:u.metrics,thresholds:u.thresholds,initialResult:t},detectedBy:"quality-assessment-coordinator",severity:t.passed?"medium":"high"});if(!e.requiresConsensus(r))return null;try{let i=await e.verifyFinding(r);if(!i.success)return Nt.warn("Consensus verification failed:"),null;let n=i.value;return Nt.info(`[quality-assessment] Consensus for gate '${u.gateName}': verdict=${n.verdict}, confidence=${(n.confidence*100).toFixed(1)}%`),{...t,consensusVerified:!0,consensusConfidence:n.confidence,consensusVerdict:n.verdict}}catch(i){return Nt.error("Consensus verification error:",i instanceof Error?i:void 0),null}}function fd(u,t){return t.decision==="blocked"||t.decision==="warning"&&u.riskTolerance==="low"||t.riskScore>.7}async function yd(u,t,e){let r=V({id:`release-readiness-${v()}`,type:"release-readiness",confidence:t.confidence,description:`Release readiness for '${u.releaseCandidate}': ${t.decision} (risk: ${(t.riskScore*100).toFixed(0)}%)`,payload:{request:u,initialAdvice:t},detectedBy:"quality-assessment-coordinator",severity:t.decision==="blocked"?"critical":"high"});if(!e.requiresConsensus(r))return null;try{let i=await e.verifyFinding(r);if(!i.success)return Nt.warn("Consensus verification for deployment failed:"),null;let n=i.value;return Nt.info(`[quality-assessment] Consensus for deployment '${u.releaseCandidate}': verdict=${n.verdict}, confidence=${(n.confidence*100).toFixed(1)}%`),{...t,consensusVerified:!0,consensusConfidence:n.confidence,consensusVerdict:n.verdict}}catch(i){return Nt.error("Consensus verification error:",i instanceof Error?i:void 0),null}}var gc={enabled:!1,consecutivePassesRequired:5,ratchetIncrementPercent:2,maxThreshold:95,monotonic:!0,cooldownMs:10080*60*1e3};function fc(u,t,e,r=Date.now()){if(process.env.AQE_GATE_RATCHETING_ENABLED!=="true"||!t.enabled)return e;let i={currentThreshold:e.currentThreshold,consecutivePasses:e.consecutivePasses,lastRatchetTime:e.lastRatchetTime,history:[...e.history]};if(!u)return i.consecutivePasses=0,i;i.consecutivePasses=i.consecutivePasses+1;let n=i.consecutivePasses>=t.consecutivePassesRequired,s=r-i.lastRatchetTime>=t.cooldownMs;if(n&&s){let a=i.currentThreshold+t.ratchetIncrementPercent,o=Math.min(a,t.maxThreshold),c=Math.max(o,i.currentThreshold);c>i.currentThreshold&&(i.currentThreshold=c,i.lastRatchetTime=r,i.history.push({threshold:c,ratchetedAt:r})),i.consecutivePasses=0}return i}Ge();var Bg={maxConcurrentWorkflows:5,defaultTimeout:6e4,publishEvents:!0,enableAutoGating:!1,enableRLThresholdTuning:!0,enableSONAPatternLearning:!0,enableFlashAttention:!0,enableClaimVerification:!0,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2,borderlineMargin:.05},de=R.create("quality-assessment"),Ii=class extends Q{constructor(e,r,i,n={},s){let a={...Bg,...n};super(e,"quality-assessment",a,{verifyFindingTypes:["gate-verdict","tech-debt-classification","release-readiness","risk-scoring"]});this.memory=r;this.agentCoordinator=i;this.qualityGate=new gt(r),this.qualityAnalyzer=new Xe({memory:r,llmRouter:s}),this.deploymentAdvisor=new Ot({memory:r,llmRouter:s})}memory;agentCoordinator;qualityGate;qualityAnalyzer;deploymentAdvisor;actorCritic;qesona;flashAttention;claimVerifier;domain="quality-assessment";recentDreamInsights=[];ratchetState={currentThreshold:70,consecutivePasses:0,lastRatchetTime:0,history:[]};async onInitialize(){try{this.subscribeToEvents(),await this.loadWorkflowState(),await this.loadRatchetState(),this.config.enableRLThresholdTuning&&await this.initializeActorCritic(),this.config.enableSONAPatternLearning&&await this.initializeQESONA(),this.config.enableFlashAttention&&await this.initializeFlashAttention(),this.config.enableClaimVerification&&await this.initializeClaimVerifier()}catch(e){let r=`Failed to initialize quality-assessment coordinator: ${T(e)}`;throw new Error(r)}}async onDispose(){await this.saveWorkflowState(),this.flashAttention?.dispose(),this.qesona&&(await this.qesona.close(),this.qesona=void 0)}getActiveWorkflows(){return super.getActiveWorkflows()}getHealthyRoutingDomains(){return this.minCutMixin.getHealthyRoutingDomains()}async evaluateGate(e){let r=v();try{if(this.startWorkflow(r,"gate-evaluation"),this.minCutMixin.shouldPauseOperations())return de.warn("Quality gate evaluation paused: topology is in critical state"),this.failWorkflow(r,"Topology is in critical state"),p(new Error("Quality gate evaluation paused: topology is in critical state"));this.isTopologyHealthy()||de.warn("Topology degraded - applying stricter thresholds for quality gate");let i=await this.spawnQualityGateAgent(r,e);i.success&&this.addAgentToWorkflow(r,i.value);let n=e;if(this.config.enableRLThresholdTuning&&this.actorCritic){let c=await this.tuneThresholdsWithRL(e.metrics);c&&(n={...e,thresholds:c.thresholds})}let s=await this.qualityGate.evaluateGate(n);if(i.success&&await this.agentCoordinator.stop(i.value),!s.success)return this.failWorkflow(r,"Evaluation failed"),s;let a=s.value;if(this.config.enableConsensus&&this.isBorderlineGateResult(e.metrics,e.thresholds,s.value)){let c=await this.verifyGateVerdictWithConsensus(n,s.value);c&&(a=c)}if(this.completeWorkflow(r),St()&&this.qesona?.isThreeLoopEnabled()){let c=n.metrics;this.qesona.instantAdapt([c.coverage/100,c.testsPassing/100,c.criticalBugs/10,c.codeSmells/100,c.securityVulnerabilities/10,c.technicalDebt/100,c.duplications/100,a.overallScore/100]);try{if(this.qesona.recordOutcome(a.overallScore/100),this.qesona.shouldConsolidate())try{this.qesona.backgroundConsolidate()}catch{}}catch{}}this.config.enableSONAPatternLearning&&this.qesona&&await this.storeQualityPattern(n,a),this.config.enableRLThresholdTuning&&this.actorCritic&&await this.trainActorCritic(n,a);try{(await Cl()).append(a.passed?"QUALITY_GATE_PASS":"QUALITY_GATE_FAIL",{gateName:e.gateName,passed:a.passed,score:a.overallScore,failedChecks:a.failedChecks},"quality-gate")}catch{}if(process.env.AQE_GATE_RATCHETING_ENABLED==="true")try{let c=this.ratchetState.currentThreshold;this.ratchetState=fc(a.passed,gc,this.ratchetState),this.ratchetState.currentThreshold>c&&(de.info(`Gate threshold ratcheted: ${c} -> ${this.ratchetState.currentThreshold}`),await this.saveRatchetState())}catch(c){de.warn("Gate ratcheting failed (non-critical)",{error:c instanceof Error?c.message:String(c)})}this.config.publishEvents&&await this.publishQualityGateEvaluated(a);let o=await this.verifyGateResultClaims(a);return f(o)}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}isBorderlineGateResult(e,r,i){return hd(e,r,i,this.config.borderlineMargin)}async verifyGateVerdictWithConsensus(e,r){return gd(e,r,this.consensusMixin)}async analyzeQuality(e){let r=v();try{if(this.startWorkflow(r,"quality-analysis"),this.minCutMixin.shouldPauseOperations())return de.warn("Quality analysis paused: topology is in critical state"),this.failWorkflow(r,"Topology is in critical state"),p(new Error("Quality analysis paused: topology is in critical state"));this.isTopologyHealthy()||de.warn("Topology degraded during quality analysis");let n=await this.spawnQualityAnalyzerAgent(r,e);n.success&&this.addAgentToWorkflow(r,n.value);let s=await this.qualityAnalyzer.analyzeQuality(e);if(n.success&&await this.agentCoordinator.stop(n.value),!s.success)return this.failWorkflow(r,"Evaluation failed"),s;if(this.completeWorkflow(r),this.config.enableFlashAttention&&this.flashAttention&&s.value.metrics.length>0){let o=await this.enhanceWithSimilarityPatterns(s.value);o&&(s.value=o)}if(St()&&this.qesona?.isThreeLoopEnabled()){let o=s.value.score;this.qesona.instantAdapt([o.overall/100,s.value.metrics.length/20,s.value.trends.length/10,s.value.recommendations.length/10]);try{if(this.qesona.recordOutcome(o.overall/100),this.qesona.shouldConsolidate())try{this.qesona.backgroundConsolidate()}catch{}}catch{}}this.config.enableSONAPatternLearning&&this.qesona&&await this.storeQualityAnalysisPattern(e,s.value),this.config.enableAutoGating&&s.value.score.overall<70&&await this.memory.set(`quality-assessment:auto-gate:${r}`,{score:s.value.score,recommendations:s.value.recommendations},{namespace:"quality-assessment",ttl:3600});let a=await this.verifyQualityReportClaims(s.value);return f(a)}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async getDeploymentAdvice(e){let r=v();try{if(this.startWorkflow(r,"deployment-advice"),this.minCutMixin.shouldPauseOperations())return de.warn("Deployment advice paused: topology is in critical state"),this.failWorkflow(r,"Topology is in critical state"),p(new Error("Deployment advice paused: topology is in critical state"));this.isTopologyHealthy()||de.warn("Topology degraded during deployment advice generation");let i=await this.spawnDeploymentAdvisorAgent(r,e);i.success&&this.addAgentToWorkflow(r,i.value);let n=await this.deploymentAdvisor.getDeploymentAdvice(e);if(i.success&&await this.agentCoordinator.stop(i.value),!n.success)return this.failWorkflow(r,"Evaluation failed"),n;let s=n.value;if(this.config.enableConsensus&&this.isHighRiskDeployment(e,n.value)){let a=await this.verifyDeploymentAdviceWithConsensus(e,n.value);a&&(s=a)}return this.completeWorkflow(r),this.config.publishEvents&&await this.publishDeploymentDecision(s,e.releaseCandidate),f(s)}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}isHighRiskDeployment(e,r){return fd(e,r)}async verifyDeploymentAdviceWithConsensus(e,r){return yd(e,r,this.consensusMixin)}async analyzeComplexity(e){let r=v();try{if(this.startWorkflow(r,"complexity-analysis"),this.minCutMixin.shouldPauseOperations())return de.warn("Complexity analysis paused: topology is in critical state"),this.failWorkflow(r,"Topology is in critical state"),p(new Error("Complexity analysis paused: topology is in critical state"));this.isTopologyHealthy()||de.warn("Topology degraded during complexity analysis");let i=await this.spawnComplexityAnalyzerAgent(r,e);i.success&&this.addAgentToWorkflow(r,i.value);let n=await this.qualityAnalyzer.analyzeComplexity(e);return i.success&&await this.agentCoordinator.stop(i.value),n.success?(this.completeWorkflow(r),n):(this.failWorkflow(r,"Evaluation failed"),n)}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async generateReport(e){return Uu(this.memory,e)}async getQualityDashboard(){return Qu(this.memory)}async analyzeRisks(e){return Ku(this.memory,e)}async evaluateQualityGate(e){let r=Ju(e),i=await this.evaluateGate(r);return i.success?f({passed:i.value.passed,score:i.value.overallScore,violations:i.value.failedChecks}):p(i.error)}async assessDeploymentReadiness(e){return Yu(this.memory,e)}async analyzeTechnicalDebt(e){return Xu(this.memory,e)}async spawnQualityGateAgent(e,r){if(!this.agentCoordinator.canSpawn())return p(new Error("Agent limit reached"));let i={name:`quality-gate-${e.slice(0,8)}`,domain:"quality-assessment",type:"validator",capabilities:["quality-gate","threshold-evaluation"],config:{workflowId:e,gateName:r.gateName}};return this.agentCoordinator.spawn(i)}async spawnQualityAnalyzerAgent(e,r){if(!this.agentCoordinator.canSpawn())return p(new Error("Agent limit reached"));let i={name:`quality-analyzer-${e.slice(0,8)}`,domain:"quality-assessment",type:"analyzer",capabilities:["quality-analysis","metrics-collection","trend-analysis"],config:{workflowId:e,sourceFiles:r.sourceFiles,includeMetrics:r.includeMetrics}};return this.agentCoordinator.spawn(i)}async spawnDeploymentAdvisorAgent(e,r){if(!this.agentCoordinator.canSpawn())return p(new Error("Agent limit reached"));let i={name:`deployment-advisor-${e.slice(0,8)}`,domain:"quality-assessment",type:"analyzer",capabilities:["deployment-advice","risk-scoring","ml-prediction"],config:{workflowId:e,releaseCandidate:r.releaseCandidate,riskTolerance:r.riskTolerance}};return this.agentCoordinator.spawn(i)}async spawnComplexityAnalyzerAgent(e,r){if(!this.agentCoordinator.canSpawn())return p(new Error("Agent limit reached"));let i={name:`complexity-analyzer-${e.slice(0,8)}`,domain:"quality-assessment",type:"analyzer",capabilities:["complexity-analysis","cyclomatic","cognitive","maintainability"],config:{workflowId:e,sourceFiles:r.sourceFiles,metrics:r.metrics}};return this.agentCoordinator.spawn(i)}async publishQualityGateEvaluated(e){let r=I(nn.QualityGateEvaluated,"quality-assessment",{gateId:v(),passed:e.passed,checks:e.checks.map(i=>({name:i.name,passed:i.passed,value:i.value,threshold:i.threshold}))});await this.eventBus.publish(r)}async publishDeploymentDecision(e,r){let i=e.decision==="approved"?nn.DeploymentApproved:nn.DeploymentBlocked,n=I(i,"quality-assessment",{decision:e.decision,reason:e.reasons.join("; "),riskScore:e.riskScore,recommendations:e.conditions||[],releaseCandidate:r});await this.eventBus.publish(n)}subscribeToEvents(){this.eventBus.subscribe("test-execution.TestRunCompleted",this.handleTestRunCompleted.bind(this)),this.eventBus.subscribe("coverage-analysis.CoverageReportCreated",this.handleCoverageReportCreated.bind(this)),this.eventBus.subscribe("security-compliance.SecurityAuditCompleted",this.handleSecurityAuditCompleted.bind(this)),this.subscribeToDreamEvents()}subscribeToDreamEvents(){this.eventBus.subscribe(He.DreamCycleCompleted,this.handleDreamCycleCompleted.bind(this))}async handleDreamCycleCompleted(e){let{insights:r,cycleId:i}=e.payload;if(!r||r.length===0)return;let n=r.filter(s=>{let a=s.suggestedAction?.toLowerCase().includes(this.domain)||s.suggestedAction?.toLowerCase().includes("quality")||s.suggestedAction?.toLowerCase().includes("gate")||s.suggestedAction?.toLowerCase().includes("threshold"),o=s.sourceConcepts.some(l=>l.toLowerCase().includes("quality")||l.toLowerCase().includes(this.domain)||l.toLowerCase().includes("metric")||l.toLowerCase().includes("gate")),c=s.type==="optimization"||s.type==="pattern_merge";return a||o||c&&s.actionable});if(n.length!==0){de.info(`[${this.domain}] Received ${n.length} relevant dream insights from cycle ${i}`);for(let s of n)s.confidenceScore>.7&&s.actionable&&await this.applyDreamInsight(s,i),this.recentDreamInsights.push({...s,receivedAt:new Date});this.recentDreamInsights.length>50&&(this.recentDreamInsights=this.recentDreamInsights.slice(-50))}}async applyDreamInsight(e,r){if(de.info(`[${this.domain}] Applying dream insight: ${e.description.slice(0,100)}...`),this.qesona)try{let i={id:`dream-insight-${e.id}`,features:this.encodeInsightAsFeatures(e),metadata:{insightType:e.type,cycleId:r,sourceConcepts:e.sourceConcepts}},n={type:"dream-insight",value:e.suggestedAction||e.description};this.qesona.createPattern(i,n,{reward:e.confidenceScore,success:!0,quality:e.noveltyScore},"quality-assessment",this.domain,{insightId:e.id,cycleId:r,description:e.description,suggestedAction:e.suggestedAction,dreamDerived:!0}),de.info(`[${this.domain}] Created SONA pattern from dream insight ${e.id}`)}catch(i){de.error(`[${this.domain}] Failed to store dream insight pattern`,i instanceof Error?i:void 0)}await this.memory.set(`${this.domain}:dream-insight:${e.id}`,{insight:e,cycleId:r,appliedAt:new Date().toISOString()},{namespace:this.domain,ttl:86400*7})}encodeInsightAsFeatures(e){return od(e)}async handleTestRunCompleted(e){if(!this.config.enableAutoGating)return;let r=e.payload;await this.memory.set(`quality-assessment:test-results:${r.runId}`,r,{namespace:"quality-assessment",ttl:3600})}async handleCoverageReportCreated(e){let r=e.payload;await this.memory.set("coverage:latest",{line:r.line,branch:r.branch,function:0,statement:0,files:0},{persist:!0})}async handleSecurityAuditCompleted(e){let r=e.payload;await this.memory.set(`quality-assessment:security:${r.auditId}`,r,{namespace:"quality-assessment",ttl:86400})}async loadWorkflowState(){let e=await this.memory.get("quality-assessment:coordinator:workflows");if(e)for(let r of e)r.status==="running"&&(r.status="failed",r.error="Coordinator restarted",r.completedAt=new Date),this.workflows.set(r.id,r)}async saveWorkflowState(){let e=Array.from(this.workflows.values());await this.memory.set("quality-assessment:coordinator:workflows",e,{namespace:"quality-assessment",persist:!0})}async loadRatchetState(){try{let e=await this.memory.get("quality-assessment:ratchet-state");e&&(this.ratchetState=e,de.info(`Restored ratchet state (threshold=${e.currentThreshold}, passes=${e.consecutivePasses})`))}catch(e){de.warn("Failed to load ratchet state (using default)",{error:e instanceof Error?e.message:String(e)})}}async saveRatchetState(){try{await this.memory.set("quality-assessment:ratchet-state",this.ratchetState,{namespace:"quality-assessment",persist:!0})}catch(e){de.warn("Failed to persist ratchet state",{error:e instanceof Error?e.message:String(e)})}}async initializeActorCritic(){this.actorCritic=await Zu()}async initializeQESONA(){this.qesona=await ed()}async initializeFlashAttention(){this.flashAttention=await td()}async tuneThresholdsWithRL(e){return!this.actorCritic||!e?null:rd(this.actorCritic,e)}async trainActorCritic(e,r){this.actorCritic&&await id(this.actorCritic,e,r)}async storeQualityPattern(e,r){this.qesona&&await nd(this.qesona,e,r,this.domain)}async storeQualityAnalysisPattern(e,r){this.qesona&&await sd(this.qesona,e,r,this.domain)}async enhanceWithSimilarityPatterns(e){return!this.flashAttention||!this.qesona?null:ad(e,this.flashAttention,this.qesona,this.domain)}async initializeClaimVerifier(){this.claimVerifier=await dd(this.config.claimVerifierRootDir)}async verifyQualityReportClaims(e){return!this.config.enableClaimVerification||!this.claimVerifier?e:md(e,this.claimVerifier)}async verifyGateResultClaims(e){return!this.config.enableClaimVerification||!this.claimVerifier?e:pd(e,this.claimVerifier)}getClaimVerifierStats(){return this.claimVerifier?.getStats()??null}};A();var Is=class extends j{constructor(e,r,i,n={},s){super(e,r);this.agentCoordinator=i;this.llmRouter=s;this.pluginConfig=n}agentCoordinator;llmRouter;coordinator=null;qualityGate=null;qualityAnalyzer=null;deploymentAdvisor=null;pluginConfig;get name(){return"quality-assessment"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{evaluateGate:this.evaluateGate.bind(this),analyzeQuality:this.analyzeQuality.bind(this),getDeploymentAdvice:this.getDeploymentAdvice.bind(this),analyzeComplexity:this.analyzeComplexity.bind(this),getCoordinator:()=>this.coordinator,getQualityGate:()=>this.qualityGate,getQualityAnalyzer:()=>this.qualityAnalyzer,getDeploymentAdvisor:()=>this.deploymentAdvisor}}getTaskHandlers(){return new Map([["evaluate-gate",async e=>{let r=e.gateName,i=e.metrics,n=e.thresholds;if(!r||!i||!n)return p(new Error("Invalid evaluate-gate payload: missing gateName, metrics, or thresholds"));let s={gateName:r,metrics:i,thresholds:n};return this.evaluateGate(s)}],["analyze-quality",async e=>{let r=e.sourceFiles;if(!r||r.length===0)return p(new Error("Invalid analyze-quality payload: missing sourceFiles"));let i={sourceFiles:r,includeMetrics:e.includeMetrics??["coverage","complexity","maintainability"],compareBaseline:e.compareBaseline};return this.analyzeQuality(i)}],["deployment-advice",async e=>{let r=e.releaseCandidate,i=e.metrics,n=e.riskTolerance;if(!r||!i)return p(new Error("Invalid deployment-advice payload: missing releaseCandidate or metrics"));let s={releaseCandidate:r,metrics:i,riskTolerance:n??"medium"};return this.getDeploymentAdvice(s)}],["analyze-complexity",async e=>{let r=e.sourceFiles;if(!r||r.length===0)return p(new Error("Invalid analyze-complexity payload: missing sourceFiles"));let i={sourceFiles:r,metrics:e.metrics??["cyclomatic","cognitive"]};return this.analyzeComplexity(i)}]])}async onInitialize(){this.qualityGate=new gt(this.memory,this.pluginConfig.qualityGate),this.qualityAnalyzer=new Xe({memory:this.memory,llmRouter:this.llmRouter},this.pluginConfig.qualityAnalyzer),this.deploymentAdvisor=new Ot({memory:this.memory,llmRouter:this.llmRouter},this.pluginConfig.deploymentAdvisor),this.coordinator=new Ii(this.eventBus,this.memory,this.agentCoordinator,this.pluginConfig.coordinator,this.llmRouter),await this.coordinator.initialize(),this.updateHealth({status:"idle",agents:{total:0,active:0,idle:0,failed:0},lastActivity:new Date,errors:[]})}async onDispose(){this.coordinator&&await this.coordinator.dispose(),this.coordinator=null,this.qualityGate=null,this.qualityAnalyzer=null,this.deploymentAdvisor=null}subscribeToEvents(){this.eventBus.subscribe("test-execution.TestRunCompleted",this.handleTestRunCompleted.bind(this)),this.eventBus.subscribe("coverage-analysis.CoverageReportCreated",this.handleCoverageReport.bind(this)),this.eventBus.subscribe("defect-intelligence.DefectPredicted",this.handleDefectPrediction.bind(this)),this.eventBus.subscribe("security-compliance.VulnerabilityDetected",this.handleVulnerabilityDetected.bind(this))}async onEvent(e){switch(this.updateHealth({lastActivity:new Date}),e.type){case"test-execution.TestRunCompleted":await this.handleTestRunCompleted(e);break;case"coverage-analysis.CoverageReportCreated":await this.handleCoverageReport(e);break;case"defect-intelligence.DefectPredicted":await this.handleDefectPrediction(e);break;case"security-compliance.VulnerabilityDetected":await this.handleVulnerabilityDetected(e);break;default:break}}async evaluateGate(e){this.ensureInitialized();try{let r=await this.coordinator.evaluateGate(e);return r.success?this.trackSuccessfulOperation("gate-evaluation"):this.trackFailedOperation(r.error),r}catch(r){return this.handleError(r)}}async analyzeQuality(e){this.ensureInitialized();try{let r=await this.coordinator.analyzeQuality(e);return r.success?this.trackSuccessfulOperation("quality-analysis"):this.trackFailedOperation(r.error),r}catch(r){return this.handleError(r)}}async getDeploymentAdvice(e){this.ensureInitialized();try{let r=await this.coordinator.getDeploymentAdvice(e);return r.success?this.trackSuccessfulOperation("deployment-advice"):this.trackFailedOperation(r.error),r}catch(r){return this.handleError(r)}}async analyzeComplexity(e){this.ensureInitialized();try{let r=await this.coordinator.analyzeComplexity(e);return r.success?this.trackSuccessfulOperation("complexity-analysis"):this.trackFailedOperation(r.error),r}catch(r){return this.handleError(r)}}async handleTestRunCompleted(e){let r=e.payload;if(await this.memory.set(`quality-assessment:test-results:${r.runId}`,{...r,receivedAt:new Date().toISOString()},{namespace:"quality-assessment",ttl:86400}),r.failed>0){let i=r.passed+r.failed+r.skipped,n=r.passed/i*100;n<95&&await this.memory.set(`quality-assessment:concerns:test-failures:${r.runId}`,{type:"test-failures",passingRate:n,failedCount:r.failed,severity:n<80?"high":"medium"},{namespace:"quality-assessment",ttl:86400*7})}}async handleCoverageReport(e){let r=e.payload;await this.memory.set("coverage:latest",{line:r.line,branch:r.branch,function:r.function,statement:r.statement,files:0},{persist:!0})}async handleDefectPrediction(e){let r=e.payload;r.probability>=.7&&await this.memory.set(`quality-assessment:defect-risks:${r.predictionId}`,{...r,severity:r.probability>=.9?"critical":"high"},{namespace:"quality-assessment",ttl:86400*7})}async handleVulnerabilityDetected(e){let r=e.payload;await this.memory.set(`quality-assessment:vulnerabilities:${r.vulnId}`,{...r,receivedAt:new Date().toISOString()},{namespace:"quality-assessment",persist:!0})}ensureInitialized(){if(!this._initialized)throw new Error("QualityAssessmentPlugin is not initialized");if(!this.coordinator||!this.qualityGate||!this.qualityAnalyzer||!this.deploymentAdvisor)throw new Error("QualityAssessmentPlugin services are not available")}handleError(e){let r=y(e),i=this.getHealth();return this.updateHealth({errors:[...i.errors.slice(-9),r.message],status:i.errors.length>=5?"degraded":i.status}),{success:!1,error:r}}trackSuccessfulOperation(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,total:r.agents.total+1,idle:r.agents.idle+1},lastActivity:new Date}),this.memory.set(`quality-assessment:metrics:${e}:${Date.now()}`,{type:e,success:!0,timestamp:new Date().toISOString()},{namespace:"quality-assessment",ttl:86400}).catch(()=>{})}trackFailedOperation(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,failed:r.agents.failed+1},errors:[...r.errors.slice(-9),e.message]})}};function yc(u,t,e,r,i){return new Is(u,t,e,r,i)}M();A();M();import{execFileSync as ye}from"child_process";import*as Ms from"path";function yt(u){return u.replace(/[;&|`$(){}[\]<>\\'"!\n\r]/g,"")}var qg={repoRoot:process.cwd(),maxCommits:100,bugKeywords:["fix","bug","patch","issue","error","defect","problem"],enableCache:!0,cacheTtl:300*1e3},dr=class{config;cache=new Map;isGitRepo=null;constructor(t={}){this.config={...qg,...t}}async isGitRepository(){if(this.isGitRepo!==null)return this.isGitRepo;try{ye("git",["rev-parse","--is-inside-work-tree"],{cwd:this.config.repoRoot,stdio:["pipe","pipe","pipe"]}),this.isGitRepo=!0}catch{this.isGitRepo=!1}return this.isGitRepo}async getChangeFrequency(t){let e=`freq:${t}`,r=this.getFromCache(e);if(r!==void 0)return r;if(!await this.isGitRepository())return .4;try{let i=yt(this.getRelativePath(t)),n=ye("git",["log","--oneline","--since=90 days ago","--",i],{cwd:this.config.repoRoot,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),s=n?n.split(`
|
|
2722
2722
|
`).length:0,a=Math.min(1,s/30);return this.setCache(e,a),a}catch{return .4}}async getDeveloperExperience(t){let e=`exp:${t}`,r=this.getFromCache(e);if(r!==void 0)return r;if(!await this.isGitRepository())return .5;try{let i=yt(this.getRelativePath(t)),n=ye("git",["blame","--line-porcelain","--",i],{cwd:this.config.repoRoot,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),s=new Map,a=n.split(`
|
|
2723
2723
|
`);for(let d of a)if(d.startsWith("author ")){let m=d.substring(7).trim();s.set(m,(s.get(m)||0)+1)}let o=Array.from(s.values()).reduce((d,m)=>d+m,0),c=s.size;if(o===0)return .5;let l=Math.min(1,c/10);return this.setCache(e,l),l}catch{return .5}}async getCodeAge(t){let e=`age:${t}`,r=this.getFromCache(e);if(r!==void 0)return r;if(!await this.isGitRepository())return .4;try{let i=yt(this.getRelativePath(t)),n=NaN;try{let m=ye("git",["log","--format=%at","--follow","--diff-filter=A","--",i],{cwd:this.config.repoRoot,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(`
|
|
2724
2724
|
`).filter(Boolean);m.length>0&&(n=parseInt(m[m.length-1],10))}catch{}let s=NaN;try{let d=ye("git",["log","-1","--format=%at","--",i],{cwd:this.config.repoRoot,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();s=parseInt(d,10)}catch{}let a=Date.now()/1e3;if(isNaN(s))return .4;let o=(a-s)/(3600*24),c=isNaN(n)?o:(a-n)/(3600*24),l;return o<7?l=.7:c>365&&o>90?l=.3:l=.4,this.setCache(e,l),l}catch{return .4}}async getBugHistory(t){let e=`bugs:${t}`,r=this.getFromCache(e);if(r!==void 0)return r;if(!await this.isGitRepository())return .2;try{let i=yt(this.getRelativePath(t)),n=0,s=new Set;for(let o of this.config.bugKeywords){let c=yt(o);try{let l=ye("git",["log","--oneline","--grep",c,"-i","--",i],{cwd:this.config.repoRoot,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(l){let d=l.split(`
|
|
@@ -2763,7 +2763,7 @@ ${t.slice(0,4e3)}
|
|
|
2763
2763
|
// File: ${l}
|
|
2764
2764
|
${m.value.slice(0,2e3)}
|
|
2765
2765
|
`)}}let o=this.calculateModelConfidence(n),c=null;if(this.isLLMPredictionAvailable()&&a.length>0){let l=await this.getHistoricalDefectPatterns(e);if(c=await this.analyzeDefectRiskWithLLM(a,n,l),c){for(let d of n)d.recommendations=this.mergeRecommendationsWithLLM(d.recommendations,c);c.confidenceLevel>.7&&(o=Math.min(1,o*1.1))}}return await this.storePrediction(n),this.modelMetrics.totalPredictions+=n.length,this.modelMetrics.lastUpdated=new Date,f({predictions:n,modelConfidence:o,factors:Array.from(s),llmAnalysis:c??void 0})}catch(e){return p(y(e))}}async getHistoricalDefectPatterns(t){let e=[];for(let i of t.slice(0,5)){let n=await this.memory.get(`${this.config.modelNamespace}:defect-patterns:${i}`);n?.patterns&&e.push(...n.patterns)}let r=await this.memory.get(`${this.config.modelNamespace}:common-defect-patterns`);return r&&e.push(...r),[...new Set(e)].slice(0,10)}async analyzeRegressionRisk(t){try{let{changeset:e,baseline:r,depth:i="shallow"}=t;if(e.length===0)return p(new Error("No files in changeset"));let n=[],s=0;for(let d of e){let m=await this.analyzeFileImpact(d,i);n.push(...m.areas),s+=m.risk}if(r&&this.config.enableHistoricalAnalysis){let d=await this.getBaselineRisk(r);s=(s+d)/2}let a=Math.min(1,s/e.length),o=this.riskToSeverity(a),c=this.generateTestRecommendations(n);return f({overallRisk:a,riskLevel:o,impactedAreas:n,recommendedTests:c,confidence:i==="deep"?.85:.7})}catch(e){return p(y(e))}}async updateModel(t){try{let e=`${this.config.modelNamespace}:feedback:${t.predictionId}`;return await this.memory.set(e,t,{namespace:"defect-intelligence",persist:!0}),await this.recalculateMetrics(t),f(void 0)}catch(e){return p(y(e))}}async getModelMetrics(){let t=await this.memory.get(`${this.config.modelNamespace}:metrics`);return t&&(this.modelMetrics={...t,lastUpdated:new Date(t.lastUpdated)}),{...this.modelMetrics}}async predictForFile(t,e,r){let i=await this.extractFileMetrics(t),n=[],s=0;for(let c of e){let d=(i[c.name]??0)*c.weight;s+=d,n.push({name:c.name,contribution:Math.round(d*100)/100})}s=Math.max(0,Math.min(1,s));let a=this.probabilityToRisk(s,r),o=this.generateRecommendations(n,s);return{file:t,probability:s,riskLevel:a,factors:n.filter(c=>c.contribution>.05),recommendations:o}}async extractFileMetrics(t){let e=await this.memory.get(`${this.config.modelNamespace}:file-metrics:${t}`);if(e)return e;let r={codeComplexity:await this.calculateComplexity(t),changeFrequency:await this.getChangeFrequency(t),developerExperience:await this.getDeveloperExperience(t),testCoverage:await this.getTestCoverage(t),codeAge:await this.getCodeAge(t),bugHistory:await this.getBugHistory(t)};return await this.memory.set(`${this.config.modelNamespace}:file-metrics:${t}`,r,{namespace:"defect-intelligence",ttl:3600}),r}async calculateComplexity(t){let e=t.split(".").pop()?.toLowerCase();if(e&&["ts","tsx","js","jsx"].includes(e)){let r=await this.fileReader.readFile(t);if(r.success)try{let i=t.split("/").pop()||t,n=this.tsParser.parseFile(i,r.value),s=this.tsParser.extractFunctions(n),a=this.tsParser.extractClasses(n),o=r.value.split(`
|
|
2766
|
-
`).length,c=s.length,l=a.length,d=a.reduce((Y,G)=>Y+G.methods.length,0),m=s.filter(Y=>Y.isAsync).length,h=r.value,g=(h.match(/\bif\s*\(/g)||[]).length,b=(h.match(/\b(for|while|do)\s*[\(\{]/g)||[]).length,w=(h.match(/\bswitch\s*\(/g)||[]).length,C=(h.match(/\bcatch\s*\(/g)||[]).length,S=(h.match(/\?[^?:]+:/g)||[]).length,k=g+b*2+w*2+C+S,P=Math.min(1,o/500),O=Math.min(1,(c+d)/30),z=Math.min(1,k/50),K=m>0?.1:0,Re=P*.2+O*.25+z*.4+K+(l>3?.05:0);return Math.max(0,Math.min(1,Re))}catch(i){vc.debug(`AST parse failed: ${i instanceof Error?i.message:i}`)}}return this.estimateComplexityFromPath(t)}estimateComplexityFromPath(t){let e=t.split("/"),r=e[e.length-1],i=.3;return(t.includes("controller")||t.includes("service"))&&(i+=.2),(t.includes("coordinator")||t.includes("orchestrator"))&&(i+=.15),(t.includes("utils")||t.includes("helper"))&&(i-=.1),(t.includes("types")||t.includes("interfaces"))&&(i-=.15),r.length>30&&(i+=.1),Math.max(0,Math.min(1,i))}async getChangeFrequency(t){let e=await this.gitAnalyzer.getChangeFrequency(t);if(e!==.4)return await this.memory.set(`${this.config.modelNamespace}:history:${t}`,{changes:Math.round(e*30)},{ttl:3600}),e;let r=`${this.config.modelNamespace}:history:${t}`,i=await this.memory.get(r);return i?Math.min(1,i.changes/50):.4}async getDeveloperExperience(t){let e=await this.gitAnalyzer.getDeveloperExperience(t);if(e!==.5)return await this.memory.set(`${this.config.modelNamespace}:developer-exp:${t}`,{score:e},{ttl:3600}),e;let r=`${this.config.modelNamespace}:developer-exp:${t}`,i=await this.memory.get(r);return i?i.score:.5}async getTestCoverage(t){try{let e=await this.memory.get(`coverage:file:${t}`);if(e&&typeof e.line=="number")return 1-e.line/100;let r=await this.memory.get("coverage:latest");if(r&&typeof r.line=="number")return 1-r.line/100}catch{}return .4}async getCodeAge(t){let e=await this.gitAnalyzer.getCodeAge(t);if(e!==.4)return e;let r=`${this.config.modelNamespace}:age:${t}`,i=await this.memory.get(r);return i?i.days<7?.7:i.days>365?.3:.4:.4}async getBugHistory(t){let e=await this.gitAnalyzer.getBugHistory(t);if(e!==.2)return await this.memory.set(`${this.config.modelNamespace}:bugs:${t}`,{count:Math.round(e*10)},{ttl:3600}),e;let r=`${this.config.modelNamespace}:bugs:${t}`,i=await this.memory.get(r);return i?Math.min(1,i.count/10):.2}probabilityToRisk(t,e){return t>=e+.3?"critical":t>=e+.15?"high":t>=e?"medium":t>=e-.2?"low":"info"}riskToSeverity(t){return t>=.8?"critical":t>=.6?"high":t>=.4?"medium":t>=.2?"low":"info"}generateRecommendations(t,e){let r=[],i=[...t].sort((n,s)=>s.contribution-n.contribution);for(let n of i.slice(0,3))switch(n.name){case"codeComplexity":n.contribution>.1&&(r.push("Consider refactoring to reduce cyclomatic complexity"),r.push("Break down large functions into smaller, testable units"));break;case"changeFrequency":n.contribution>.1&&(r.push("High churn area - add comprehensive regression tests"),r.push("Consider stabilizing the interface before further changes"));break;case"testCoverage":n.contribution>.1&&(r.push("Increase test coverage to reduce defect risk"),r.push("Add unit tests for critical paths"));break;case"bugHistory":n.contribution>.1&&(r.push("Review past bug fixes for patterns"),r.push("Add regression tests for previously fixed issues"));break;case"codeAge":n.contribution>.1&&r.push("New code requires thorough review and testing");break;case"developerExperience":n.contribution>.1&&r.push("Request code review from senior developer");break}return e>.7&&r.push("CRITICAL: Schedule immediate code review"),r}async analyzeFileImpact(t,e){let r=[],i=0,n=this.categorizeFile(t),s=(await this.extractFileMetrics(t)).codeComplexity;if(r.push({area:n,files:[t],risk:s,reason:`Modified file in ${n} area`}),i+=s,e==="deep"){let a=await this.analyzeDependencies(t);for(let o of a){let c=(await this.extractFileMetrics(o)).codeComplexity*.5;r.push({area:this.categorizeFile(o),files:[o],risk:c,reason:`Dependency of ${t}`}),i+=c}}return{areas:r,risk:i}}categorizeFile(t){return t.includes("controller")?"API Layer":t.includes("service")?"Business Logic":t.includes("repository")||t.includes("dao")?"Data Access":t.includes("model")||t.includes("entity")?"Domain Model":t.includes("util")||t.includes("helper")?"Utilities":t.includes("test")?"Tests":t.includes("config")?"Configuration":"General"}async analyzeDependencies(t){let e=`code-intelligence:dependencies:${t}`,r=await this.memory.get(e);if(r&&r.length>0)return r;let i=[];try{let n=await this.fileReader.readFile(t);if(!n.success)return[];let s=t.split("/").pop()||t,a=this.tsParser.parseFile(s,n.value),o=this.tsParser.extractImports(a);for(let c of o)if(c.module.startsWith(".")){let l=this.resolveRelativeImport(t,c.module);i.push(l)}else c.module.startsWith("node:")||i.push(c.module);i.length>0&&await this.memory.set(e,i,{namespace:"code-intelligence",ttl:3600})}catch(n){vc.error(`Failed to analyze dependencies for ${t}`,n instanceof Error?n:void 0)}return i}resolveRelativeImport(t,e){let i=t.substring(0,t.lastIndexOf("/")).split("/"),n=e.split("/");for(let a of n)a!=="."&&(a===".."?i.pop():i.push(a));let s=i.join("/");return!s.endsWith(".ts")&&!s.endsWith(".tsx")&&!s.endsWith(".js")&&(s=s+".ts"),s}async getBaselineRisk(t){let e=`${this.config.modelNamespace}:baseline:${t}`;return(await this.memory.get(e))?.risk??.3}generateTestRecommendations(t){let e=[],r=new Set(t.map(n=>n.area));for(let n of r)switch(n){case"API Layer":e.push("Run API integration tests"),e.push("Verify endpoint response contracts");break;case"Business Logic":e.push("Run unit tests for business rules"),e.push("Execute scenario-based tests");break;case"Data Access":e.push("Run database integration tests"),e.push("Verify data integrity constraints");break;case"Domain Model":e.push("Run entity validation tests"),e.push("Check serialization/deserialization");break}return t.filter(n=>n.risk>.6).length>0&&(e.push("Run full regression test suite"),e.push("Consider exploratory testing for edge cases")),[...new Set(e)]}calculateModelConfidence(t){let e=this.modelMetrics.accuracy,r=t.map(n=>n.probability);return this.calculateVariance(r)>.2&&(e*=.9),t.length>10&&(e*=1.05),Math.min(1,Math.max(0,e))}calculateVariance(t){if(t.length===0)return 0;let e=t.reduce((i,n)=>i+n,0)/t.length;return t.map(i=>Math.pow(i-e,2)).reduce((i,n)=>i+n,0)/t.length}async storePrediction(t){let e=v();await this.memory.set(`${this.config.modelNamespace}:prediction:${e}`,{id:e,predictions:t,timestamp:new Date().toISOString()},{namespace:"defect-intelligence",ttl:86400*7})}async recalculateMetrics(t){let e=t.predictedProbability>=this.config.defaultThreshold,r=e===t.actualDefect,i=.01;this.modelMetrics.accuracy=this.modelMetrics.accuracy*(1-i)+(r?1:0)*i,e&&t.actualDefect?(this.modelMetrics.precision=this.modelMetrics.precision*(1-i)+1*i,this.modelMetrics.recall=this.modelMetrics.recall*(1-i)+1*i):e&&!t.actualDefect?this.modelMetrics.precision=this.modelMetrics.precision*(1-i)+0*i:!e&&t.actualDefect&&(this.modelMetrics.recall=this.modelMetrics.recall*(1-i)+0*i),this.modelMetrics.f1Score=2*this.modelMetrics.precision*this.modelMetrics.recall/(this.modelMetrics.precision+this.modelMetrics.recall||1),this.modelMetrics.lastUpdated=new Date,await this.memory.set(`${this.config.modelNamespace}:metrics`,this.modelMetrics,{namespace:"defect-intelligence",persist:!0})}};M();A();var jg={minPatternFrequency:2,maxPatterns:50,clusterThreshold:.7,embeddingDimension:At.DIMENSIONS,patternNamespace:"defect-intelligence:patterns",enableSemanticClustering:!0,enableFlashAttention:!0},Fs={"null-pointer":{indicators:["null","undefined","NullPointerException","TypeError: Cannot read"],prevention:"Use null-safe operators and defensive programming"},"race-condition":{indicators:["concurrent","async","race","timing","intermittent"],prevention:"Implement proper synchronization and use atomic operations"},"memory-leak":{indicators:["memory","leak","OutOfMemory","heap","gc"],prevention:"Ensure proper resource cleanup and avoid circular references"},"off-by-one":{indicators:["index","boundary","array","loop","range"],prevention:"Validate array bounds and use inclusive/exclusive ranges consistently"},"input-validation":{indicators:["validation","sanitize","input","injection","XSS"],prevention:"Implement strict input validation and sanitization"},"resource-exhaustion":{indicators:["timeout","resource","exhausted","limit","quota"],prevention:"Implement rate limiting and resource pooling"},"state-corruption":{indicators:["state","inconsistent","corrupt","invalid state"],prevention:"Use immutable state patterns and proper state machines"},"encoding-issue":{indicators:["encoding","charset","UTF","unicode","character"],prevention:"Use consistent encoding throughout the application"}},Wg=R.create("defect-intelligence/pattern-learner"),pr=class{constructor(t,e={}){this.memory=t;this.config={...jg,...e},this.embedder=e.embedder??new Et({enableFallback:!0}),this.config.enableFlashAttention&&this.initializeFlashAttention()}memory;config;patternCache=new Map;embedder;flashAttention=null;flashAttentionAvailable=!1;MAX_CACHED_PATTERNS=5e3;async initializeFlashAttention(){let{createQEFlashAttention:t}=await import("./wrappers-37NLMKPE.js");this.flashAttention=await t("defect-matching",this.config.flashAttentionConfig),this.flashAttentionAvailable=!0,Wg.info("Flash Attention initialized for defect matching")}async ensureFlashAttentionInitialized(){this.config.enableFlashAttention&&!this.flashAttention&&await this.initializeFlashAttention()}async learnPatterns(t){try{let{defects:e,includeResolutions:r=!1}=t;if(e.length===0)return p(new Error("No defects provided for learning"));let i=[],n=!1,s=await this.extractPatterns(e),a=this.mergeWithKnownPatterns(s);for(let c of a)c.frequency>=this.config.minPatternFrequency&&(i.push(c),await this.storePattern(c),n=!0);let o=this.calculateImprovementEstimate(e.length,i);return r&&await this.learnResolutions(e,i),f({patterns:i.slice(0,this.config.maxPatterns),modelUpdated:n,improvementEstimate:o})}catch(e){return p(y(e))}}async clusterDefects(t){try{let{defects:e,method:r,minClusterSize:i=2}=t;if(e.length===0)return p(new Error("No defects provided for clustering"));let n;switch(r){case"semantic":n=await this.clusterBySemantic(e,i);break;case"behavioral":n=await this.clusterByBehavior(e,i);break;case"temporal":n=await this.clusterByTemporal(e,i);break;default:return p(new Error(`Unknown clustering method: ${r}`))}let s=new Set(n.flatMap(c=>c.defects)),a=e.filter(c=>!s.has(c.id)).map(c=>c.id),o=this.calculateClusteringMetrics(n,e.length);return f({clusters:n,outliers:a,clusteringMetrics:o})}catch(e){return p(y(e))}}async findSimilarDefects(t,e=5){try{let r=await this.generateDefectEmbedding(t),i=await this.memory.vectorSearch(r,e+1),n=[];for(let s of i)if(s.score>=this.config.clusterThreshold){let a=await this.memory.get(s.key);a&&a.id!==t.id&&n.push(a)}return f(n.slice(0,e))}catch(r){return p(y(r))}}async getPatternById(t){if(this.patternCache.has(t))return this.patternCache.get(t);let e=`${this.config.patternNamespace}:${t}`,r=await this.memory.get(e);if(r)return this.cachePattern(r),r}async listPatterns(t=this.config.maxPatterns){let e=[],r=await this.memory.search(`${this.config.patternNamespace}:*`,t*2);for(let i of r){let n=await this.memory.get(i);if(n&&(e.push(n),e.length>=t))break}return e.sort((i,n)=>n.frequency-i.frequency)}getFlashAttentionStatus(){let t=0,e=null,r=null;return this.flashAttention&&(t=this.flashAttention.getMetrics().length,e=this.flashAttention.getAverageSpeedup(),r=this.flashAttention.getWorkload()),{enabled:this.config.enableFlashAttention??!1,available:this.flashAttentionAvailable,workload:r,metricsCount:t,averageSpeedup:e}}async extractPatterns(t){let e=new Map;for(let i of t){let n=`${i.title} ${i.description}`.toLowerCase();for(let[s,a]of Object.entries(Fs)){let o=a.indicators.filter(c=>n.includes(c.toLowerCase()));if(o.length>0){let c=e.get(s);c?(c.defects.push(i.id),c.indicators.push(...o.filter(l=>!c.indicators.includes(l)))):e.set(s,{indicators:o,defects:[i.id]})}}if(i.tags)for(let s of i.tags){let a=`tag-${s}`,o=e.get(a);o?o.defects.push(i.id):e.set(a,{indicators:[s],defects:[i.id]})}}let r=[];for(let[i,n]of e){let s=Fs[i];r.push({id:v(),name:this.formatPatternName(i),indicators:[...new Set(n.indicators)],frequency:n.defects.length,prevention:s?.prevention||`Address ${i} issues proactively`})}return r}mergeWithKnownPatterns(t){let e=[...t];for(let[r,i]of Object.entries(Fs))e.some(s=>s.name.toLowerCase().includes(r.replace("-"," ")))||e.push({id:v(),name:this.formatPatternName(r),indicators:i.indicators,frequency:0,prevention:i.prevention});return e}formatPatternName(t){return t.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}async storePattern(t){let e=`${this.config.patternNamespace}:${t.id}`;if(await this.memory.set(e,t,{namespace:"defect-intelligence",persist:!0}),this.config.enableSemanticClustering){let r=await this.generatePatternEmbedding(t);await this.memory.storeVector(e,r,{patternId:t.id,name:t.name})}this.cachePattern(t)}async learnResolutions(t,e){for(let r of e){let i=t.filter(n=>{let s=`${n.title} ${n.description}`.toLowerCase();return r.indicators.some(a=>s.includes(a.toLowerCase()))});i.length>0&&await this.memory.set(`${this.config.patternNamespace}:resolutions:${r.id}`,{patternId:r.id,defectIds:i.map(n=>n.id),learnedAt:new Date().toISOString()},{namespace:"defect-intelligence",persist:!0})}}calculateImprovementEstimate(t,e){if(t===0)return 0;let r=e.reduce((s,a)=>s+a.frequency,0),i=Math.min(1,r/t),n=e.length>0?e.reduce((s,a)=>s+(a.prevention?.1:0),0)/e.length:0;return i*.7+n*.3}async clusterBySemantic(t,e){let r=new Map;await this.ensureFlashAttentionInitialized();let i=[];for(let s of t){let a=await this.generateDefectEmbedding(s);i.push({defect:s,embedding:a}),await this.memory.storeVector(`${this.config.patternNamespace}:defect:${s.id}`,a,{defectId:s.id})}let n=new Set;for(let{defect:s,embedding:a}of i){if(n.has(s.id))continue;let o=[s.id];n.add(s.id);for(let c of i){if(c.defect.id===s.id||n.has(c.defect.id))continue;await this.computeSimilarity(a,c.embedding)>=this.config.clusterThreshold&&(o.push(c.defect.id),n.add(c.defect.id))}if(o.length>=e){let c=v(),l=this.findCommonFactors(t.filter(d=>o.includes(d.id)));r.set(c,{id:c,label:this.generateClusterLabel(t.filter(d=>o.includes(d.id))),defects:o,commonFactors:l,suggestedFix:this.suggestFix(l)})}}return Array.from(r.values())}async computeSimilarity(t,e){if(!this.flashAttention)throw new Error("[PatternLearnerService] Flash Attention not initialized. Call ensureFlashAttentionInitialized() first.");return this.computeFlashAttentionSimilarity(t,e)}async computeFlashAttentionSimilarity(t,e){let r=t.length,i=new Float32Array(r),n=new Float32Array(r),s=new Float32Array(r);for(let c=0;c<r;c++)i[c]=t[c],n[c]=e[c],s[c]=e[c];let a=await this.flashAttention.computeFlashAttention(i,n,s,1,r),o=0;for(let c=0;c<r;c++)o+=a[c]*t[c];return Math.max(0,Math.min(1,(o+1)/2))}async batchComputeSimilarities(t,e){if(await this.ensureFlashAttentionInitialized(),!this.flashAttention)throw new Error("[PatternLearnerService] Flash Attention not initialized. Ensure @ruvector/attention is installed as a dependency.");let r=new Float32Array(t),i=e.map(a=>new Float32Array(a)),n=await this.flashAttention.matchDefectPattern(r,i),s=new Array(e.length).fill(0);for(let a of n)a.pattern<s.length&&(s[a.pattern]=Math.max(0,Math.min(1,(a.score+1)/2)));return s}async clusterByBehavior(t,e){let r=new Map,i=new Map;for(let n of t){let s=n.tags?.sort().join("|")||n.file||"unknown",a=i.get(s)||[];a.push(n),i.set(s,a)}for(let[n,s]of i)if(s.length>=e){let a=v(),o=this.findCommonFactors(s);r.set(a,{id:a,label:`Behavioral: ${n.replace(/\|/g,", ")}`,defects:s.map(c=>c.id),commonFactors:o,suggestedFix:this.suggestFix(o)})}return Array.from(r.values())}async clusterByTemporal(t,e){let r=new Map,i=new Map;for(let n of t){let s=n.title.toLowerCase().split(/\s+/).slice(0,2).join(" "),a=i.get(s)||[];a.push(n),i.set(s,a)}for(let[n,s]of i)if(s.length>=2){let a=v(),o=this.findCommonFactors(s);r.set(a,{id:a,label:`Temporal: ${n}`,defects:s.map(c=>c.id),commonFactors:o,suggestedFix:this.suggestFix(o)})}return Array.from(r.values())}findCommonFactors(t){let e=[];if(t.every(n=>n.tags)){let n=t.map(a=>new Set(a.tags)),s=[...n[0]].filter(a=>n.every(o=>o.has(a)));e.push(...s)}if(t.every(n=>n.file)){let n=t.map(a=>a.file.split("/")),s=Math.min(...n.map(a=>a.length));for(let a=0;a<s;a++)n.every(o=>o[a]===n[0][a])&&e.push(`Path: ${n[0][a]}`)}let r=t.map(n=>new Set(n.title.toLowerCase().split(/\s+/))),i=[...r[0]].filter(n=>n.length>3&&r.every(s=>s.has(n)));return e.push(...i.map(n=>`Keyword: ${n}`)),[...new Set(e)]}generateClusterLabel(t){let r=t.map(s=>s.title.toLowerCase()).flatMap(s=>s.split(/\s+/)),i=new Map;for(let s of r)s.length>3&&i.set(s,(i.get(s)||0)+1);return[...i.entries()].sort((s,a)=>a[1]-s[1]).slice(0,2).map(([s])=>s).join(" ")||"Unnamed Cluster"}suggestFix(t){for(let e of t)for(let[r,i]of Object.entries(Fs))if(e.toLowerCase().includes(r)||i.indicators.some(n=>e.toLowerCase().includes(n.toLowerCase())))return i.prevention;return"Review common factors and implement targeted fixes"}calculateClusteringMetrics(t,e){if(t.length===0||e===0)return{silhouette:0,cohesion:0};let r=t.reduce((c,l)=>c+l.defects.length,0),i=r/t.length,n=r/e,s=t.map(c=>c.defects.length),a=s.reduce((c,l)=>c+Math.pow(l-i,2),0)/s.length,o=Math.max(0,1-a/(i*i||1));return{silhouette:Math.round(o*100)/100,cohesion:Math.round(n*100)/100}}async generateDefectEmbedding(t){let e=this.formatDefectForEmbedding(t);return this.embedder.embed(e)}async generatePatternEmbedding(t){let e=this.formatPatternForEmbedding(t);return this.embedder.embed(e)}formatDefectForEmbedding(t){return[`Title: ${t.title}`,t.description?`Description: ${t.description}`:"",t.tags?.length?`Tags: ${t.tags.join(", ")}`:"",t.file?`File: ${t.file}`:""].filter(Boolean).join(`
|
|
2766
|
+
`).length,c=s.length,l=a.length,d=a.reduce((Y,G)=>Y+G.methods.length,0),m=s.filter(Y=>Y.isAsync).length,h=r.value,g=(h.match(/\bif\s*\(/g)||[]).length,b=(h.match(/\b(for|while|do)\s*[\(\{]/g)||[]).length,w=(h.match(/\bswitch\s*\(/g)||[]).length,C=(h.match(/\bcatch\s*\(/g)||[]).length,S=(h.match(/\?[^?:]+:/g)||[]).length,k=g+b*2+w*2+C+S,P=Math.min(1,o/500),O=Math.min(1,(c+d)/30),z=Math.min(1,k/50),K=m>0?.1:0,Re=P*.2+O*.25+z*.4+K+(l>3?.05:0);return Math.max(0,Math.min(1,Re))}catch(i){vc.debug(`AST parse failed: ${i instanceof Error?i.message:i}`)}}return this.estimateComplexityFromPath(t)}estimateComplexityFromPath(t){let e=t.split("/"),r=e[e.length-1],i=.3;return(t.includes("controller")||t.includes("service"))&&(i+=.2),(t.includes("coordinator")||t.includes("orchestrator"))&&(i+=.15),(t.includes("utils")||t.includes("helper"))&&(i-=.1),(t.includes("types")||t.includes("interfaces"))&&(i-=.15),r.length>30&&(i+=.1),Math.max(0,Math.min(1,i))}async getChangeFrequency(t){let e=await this.gitAnalyzer.getChangeFrequency(t);if(e!==.4)return await this.memory.set(`${this.config.modelNamespace}:history:${t}`,{changes:Math.round(e*30)},{ttl:3600}),e;let r=`${this.config.modelNamespace}:history:${t}`,i=await this.memory.get(r);return i?Math.min(1,i.changes/50):.4}async getDeveloperExperience(t){let e=await this.gitAnalyzer.getDeveloperExperience(t);if(e!==.5)return await this.memory.set(`${this.config.modelNamespace}:developer-exp:${t}`,{score:e},{ttl:3600}),e;let r=`${this.config.modelNamespace}:developer-exp:${t}`,i=await this.memory.get(r);return i?i.score:.5}async getTestCoverage(t){try{let e=await this.memory.get(`coverage:file:${t}`);if(e&&typeof e.line=="number")return 1-e.line/100;let r=await this.memory.get("coverage:latest");if(r&&typeof r.line=="number")return 1-r.line/100}catch{}return .4}async getCodeAge(t){let e=await this.gitAnalyzer.getCodeAge(t);if(e!==.4)return e;let r=`${this.config.modelNamespace}:age:${t}`,i=await this.memory.get(r);return i?i.days<7?.7:i.days>365?.3:.4:.4}async getBugHistory(t){let e=await this.gitAnalyzer.getBugHistory(t);if(e!==.2)return await this.memory.set(`${this.config.modelNamespace}:bugs:${t}`,{count:Math.round(e*10)},{ttl:3600}),e;let r=`${this.config.modelNamespace}:bugs:${t}`,i=await this.memory.get(r);return i?Math.min(1,i.count/10):.2}probabilityToRisk(t,e){return t>=e+.3?"critical":t>=e+.15?"high":t>=e?"medium":t>=e-.2?"low":"info"}riskToSeverity(t){return t>=.8?"critical":t>=.6?"high":t>=.4?"medium":t>=.2?"low":"info"}generateRecommendations(t,e){let r=[],i=[...t].sort((n,s)=>s.contribution-n.contribution);for(let n of i.slice(0,3))switch(n.name){case"codeComplexity":n.contribution>.1&&(r.push("Consider refactoring to reduce cyclomatic complexity"),r.push("Break down large functions into smaller, testable units"));break;case"changeFrequency":n.contribution>.1&&(r.push("High churn area - add comprehensive regression tests"),r.push("Consider stabilizing the interface before further changes"));break;case"testCoverage":n.contribution>.1&&(r.push("Increase test coverage to reduce defect risk"),r.push("Add unit tests for critical paths"));break;case"bugHistory":n.contribution>.1&&(r.push("Review past bug fixes for patterns"),r.push("Add regression tests for previously fixed issues"));break;case"codeAge":n.contribution>.1&&r.push("New code requires thorough review and testing");break;case"developerExperience":n.contribution>.1&&r.push("Request code review from senior developer");break}return e>.7&&r.push("CRITICAL: Schedule immediate code review"),r}async analyzeFileImpact(t,e){let r=[],i=0,n=this.categorizeFile(t),s=(await this.extractFileMetrics(t)).codeComplexity;if(r.push({area:n,files:[t],risk:s,reason:`Modified file in ${n} area`}),i+=s,e==="deep"){let a=await this.analyzeDependencies(t);for(let o of a){let c=(await this.extractFileMetrics(o)).codeComplexity*.5;r.push({area:this.categorizeFile(o),files:[o],risk:c,reason:`Dependency of ${t}`}),i+=c}}return{areas:r,risk:i}}categorizeFile(t){return t.includes("controller")?"API Layer":t.includes("service")?"Business Logic":t.includes("repository")||t.includes("dao")?"Data Access":t.includes("model")||t.includes("entity")?"Domain Model":t.includes("util")||t.includes("helper")?"Utilities":t.includes("test")?"Tests":t.includes("config")?"Configuration":"General"}async analyzeDependencies(t){let e=`code-intelligence:dependencies:${t}`,r=await this.memory.get(e);if(r&&r.length>0)return r;let i=[];try{let n=await this.fileReader.readFile(t);if(!n.success)return[];let s=t.split("/").pop()||t,a=this.tsParser.parseFile(s,n.value),o=this.tsParser.extractImports(a);for(let c of o)if(c.module.startsWith(".")){let l=this.resolveRelativeImport(t,c.module);i.push(l)}else c.module.startsWith("node:")||i.push(c.module);i.length>0&&await this.memory.set(e,i,{namespace:"code-intelligence",ttl:3600})}catch(n){vc.error(`Failed to analyze dependencies for ${t}`,n instanceof Error?n:void 0)}return i}resolveRelativeImport(t,e){let i=t.substring(0,t.lastIndexOf("/")).split("/"),n=e.split("/");for(let a of n)a!=="."&&(a===".."?i.pop():i.push(a));let s=i.join("/");return!s.endsWith(".ts")&&!s.endsWith(".tsx")&&!s.endsWith(".js")&&(s=s+".ts"),s}async getBaselineRisk(t){let e=`${this.config.modelNamespace}:baseline:${t}`;return(await this.memory.get(e))?.risk??.3}generateTestRecommendations(t){let e=[],r=new Set(t.map(n=>n.area));for(let n of r)switch(n){case"API Layer":e.push("Run API integration tests"),e.push("Verify endpoint response contracts");break;case"Business Logic":e.push("Run unit tests for business rules"),e.push("Execute scenario-based tests");break;case"Data Access":e.push("Run database integration tests"),e.push("Verify data integrity constraints");break;case"Domain Model":e.push("Run entity validation tests"),e.push("Check serialization/deserialization");break}return t.filter(n=>n.risk>.6).length>0&&(e.push("Run full regression test suite"),e.push("Consider exploratory testing for edge cases")),[...new Set(e)]}calculateModelConfidence(t){let e=this.modelMetrics.accuracy,r=t.map(n=>n.probability);return this.calculateVariance(r)>.2&&(e*=.9),t.length>10&&(e*=1.05),Math.min(1,Math.max(0,e))}calculateVariance(t){if(t.length===0)return 0;let e=t.reduce((i,n)=>i+n,0)/t.length;return t.map(i=>Math.pow(i-e,2)).reduce((i,n)=>i+n,0)/t.length}async storePrediction(t){let e=v();await this.memory.set(`${this.config.modelNamespace}:prediction:${e}`,{id:e,predictions:t,timestamp:new Date().toISOString()},{namespace:"defect-intelligence",ttl:86400*7})}async recalculateMetrics(t){let e=t.predictedProbability>=this.config.defaultThreshold,r=e===t.actualDefect,i=.01;this.modelMetrics.accuracy=this.modelMetrics.accuracy*(1-i)+(r?1:0)*i,e&&t.actualDefect?(this.modelMetrics.precision=this.modelMetrics.precision*(1-i)+1*i,this.modelMetrics.recall=this.modelMetrics.recall*(1-i)+1*i):e&&!t.actualDefect?this.modelMetrics.precision=this.modelMetrics.precision*(1-i)+0*i:!e&&t.actualDefect&&(this.modelMetrics.recall=this.modelMetrics.recall*(1-i)+0*i),this.modelMetrics.f1Score=2*this.modelMetrics.precision*this.modelMetrics.recall/(this.modelMetrics.precision+this.modelMetrics.recall||1),this.modelMetrics.lastUpdated=new Date,await this.memory.set(`${this.config.modelNamespace}:metrics`,this.modelMetrics,{namespace:"defect-intelligence",persist:!0})}};M();A();var jg={minPatternFrequency:2,maxPatterns:50,clusterThreshold:.7,embeddingDimension:At.DIMENSIONS,patternNamespace:"defect-intelligence:patterns",enableSemanticClustering:!0,enableFlashAttention:!0},Fs={"null-pointer":{indicators:["null","undefined","NullPointerException","TypeError: Cannot read"],prevention:"Use null-safe operators and defensive programming"},"race-condition":{indicators:["concurrent","async","race","timing","intermittent"],prevention:"Implement proper synchronization and use atomic operations"},"memory-leak":{indicators:["memory","leak","OutOfMemory","heap","gc"],prevention:"Ensure proper resource cleanup and avoid circular references"},"off-by-one":{indicators:["index","boundary","array","loop","range"],prevention:"Validate array bounds and use inclusive/exclusive ranges consistently"},"input-validation":{indicators:["validation","sanitize","input","injection","XSS"],prevention:"Implement strict input validation and sanitization"},"resource-exhaustion":{indicators:["timeout","resource","exhausted","limit","quota"],prevention:"Implement rate limiting and resource pooling"},"state-corruption":{indicators:["state","inconsistent","corrupt","invalid state"],prevention:"Use immutable state patterns and proper state machines"},"encoding-issue":{indicators:["encoding","charset","UTF","unicode","character"],prevention:"Use consistent encoding throughout the application"}},Wg=R.create("defect-intelligence/pattern-learner"),pr=class{constructor(t,e={}){this.memory=t;this.config={...jg,...e},this.embedder=e.embedder??new Et({enableFallback:!0}),this.config.enableFlashAttention&&this.initializeFlashAttention()}memory;config;patternCache=new Map;embedder;flashAttention=null;flashAttentionAvailable=!1;MAX_CACHED_PATTERNS=5e3;async initializeFlashAttention(){let{createQEFlashAttention:t}=await import("./wrappers-QXOPRPR4.js");this.flashAttention=await t("defect-matching",this.config.flashAttentionConfig),this.flashAttentionAvailable=!0,Wg.info("Flash Attention initialized for defect matching")}async ensureFlashAttentionInitialized(){this.config.enableFlashAttention&&!this.flashAttention&&await this.initializeFlashAttention()}async learnPatterns(t){try{let{defects:e,includeResolutions:r=!1}=t;if(e.length===0)return p(new Error("No defects provided for learning"));let i=[],n=!1,s=await this.extractPatterns(e),a=this.mergeWithKnownPatterns(s);for(let c of a)c.frequency>=this.config.minPatternFrequency&&(i.push(c),await this.storePattern(c),n=!0);let o=this.calculateImprovementEstimate(e.length,i);return r&&await this.learnResolutions(e,i),f({patterns:i.slice(0,this.config.maxPatterns),modelUpdated:n,improvementEstimate:o})}catch(e){return p(y(e))}}async clusterDefects(t){try{let{defects:e,method:r,minClusterSize:i=2}=t;if(e.length===0)return p(new Error("No defects provided for clustering"));let n;switch(r){case"semantic":n=await this.clusterBySemantic(e,i);break;case"behavioral":n=await this.clusterByBehavior(e,i);break;case"temporal":n=await this.clusterByTemporal(e,i);break;default:return p(new Error(`Unknown clustering method: ${r}`))}let s=new Set(n.flatMap(c=>c.defects)),a=e.filter(c=>!s.has(c.id)).map(c=>c.id),o=this.calculateClusteringMetrics(n,e.length);return f({clusters:n,outliers:a,clusteringMetrics:o})}catch(e){return p(y(e))}}async findSimilarDefects(t,e=5){try{let r=await this.generateDefectEmbedding(t),i=await this.memory.vectorSearch(r,e+1),n=[];for(let s of i)if(s.score>=this.config.clusterThreshold){let a=await this.memory.get(s.key);a&&a.id!==t.id&&n.push(a)}return f(n.slice(0,e))}catch(r){return p(y(r))}}async getPatternById(t){if(this.patternCache.has(t))return this.patternCache.get(t);let e=`${this.config.patternNamespace}:${t}`,r=await this.memory.get(e);if(r)return this.cachePattern(r),r}async listPatterns(t=this.config.maxPatterns){let e=[],r=await this.memory.search(`${this.config.patternNamespace}:*`,t*2);for(let i of r){let n=await this.memory.get(i);if(n&&(e.push(n),e.length>=t))break}return e.sort((i,n)=>n.frequency-i.frequency)}getFlashAttentionStatus(){let t=0,e=null,r=null;return this.flashAttention&&(t=this.flashAttention.getMetrics().length,e=this.flashAttention.getAverageSpeedup(),r=this.flashAttention.getWorkload()),{enabled:this.config.enableFlashAttention??!1,available:this.flashAttentionAvailable,workload:r,metricsCount:t,averageSpeedup:e}}async extractPatterns(t){let e=new Map;for(let i of t){let n=`${i.title} ${i.description}`.toLowerCase();for(let[s,a]of Object.entries(Fs)){let o=a.indicators.filter(c=>n.includes(c.toLowerCase()));if(o.length>0){let c=e.get(s);c?(c.defects.push(i.id),c.indicators.push(...o.filter(l=>!c.indicators.includes(l)))):e.set(s,{indicators:o,defects:[i.id]})}}if(i.tags)for(let s of i.tags){let a=`tag-${s}`,o=e.get(a);o?o.defects.push(i.id):e.set(a,{indicators:[s],defects:[i.id]})}}let r=[];for(let[i,n]of e){let s=Fs[i];r.push({id:v(),name:this.formatPatternName(i),indicators:[...new Set(n.indicators)],frequency:n.defects.length,prevention:s?.prevention||`Address ${i} issues proactively`})}return r}mergeWithKnownPatterns(t){let e=[...t];for(let[r,i]of Object.entries(Fs))e.some(s=>s.name.toLowerCase().includes(r.replace("-"," ")))||e.push({id:v(),name:this.formatPatternName(r),indicators:i.indicators,frequency:0,prevention:i.prevention});return e}formatPatternName(t){return t.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}async storePattern(t){let e=`${this.config.patternNamespace}:${t.id}`;if(await this.memory.set(e,t,{namespace:"defect-intelligence",persist:!0}),this.config.enableSemanticClustering){let r=await this.generatePatternEmbedding(t);await this.memory.storeVector(e,r,{patternId:t.id,name:t.name})}this.cachePattern(t)}async learnResolutions(t,e){for(let r of e){let i=t.filter(n=>{let s=`${n.title} ${n.description}`.toLowerCase();return r.indicators.some(a=>s.includes(a.toLowerCase()))});i.length>0&&await this.memory.set(`${this.config.patternNamespace}:resolutions:${r.id}`,{patternId:r.id,defectIds:i.map(n=>n.id),learnedAt:new Date().toISOString()},{namespace:"defect-intelligence",persist:!0})}}calculateImprovementEstimate(t,e){if(t===0)return 0;let r=e.reduce((s,a)=>s+a.frequency,0),i=Math.min(1,r/t),n=e.length>0?e.reduce((s,a)=>s+(a.prevention?.1:0),0)/e.length:0;return i*.7+n*.3}async clusterBySemantic(t,e){let r=new Map;await this.ensureFlashAttentionInitialized();let i=[];for(let s of t){let a=await this.generateDefectEmbedding(s);i.push({defect:s,embedding:a}),await this.memory.storeVector(`${this.config.patternNamespace}:defect:${s.id}`,a,{defectId:s.id})}let n=new Set;for(let{defect:s,embedding:a}of i){if(n.has(s.id))continue;let o=[s.id];n.add(s.id);for(let c of i){if(c.defect.id===s.id||n.has(c.defect.id))continue;await this.computeSimilarity(a,c.embedding)>=this.config.clusterThreshold&&(o.push(c.defect.id),n.add(c.defect.id))}if(o.length>=e){let c=v(),l=this.findCommonFactors(t.filter(d=>o.includes(d.id)));r.set(c,{id:c,label:this.generateClusterLabel(t.filter(d=>o.includes(d.id))),defects:o,commonFactors:l,suggestedFix:this.suggestFix(l)})}}return Array.from(r.values())}async computeSimilarity(t,e){if(!this.flashAttention)throw new Error("[PatternLearnerService] Flash Attention not initialized. Call ensureFlashAttentionInitialized() first.");return this.computeFlashAttentionSimilarity(t,e)}async computeFlashAttentionSimilarity(t,e){let r=t.length,i=new Float32Array(r),n=new Float32Array(r),s=new Float32Array(r);for(let c=0;c<r;c++)i[c]=t[c],n[c]=e[c],s[c]=e[c];let a=await this.flashAttention.computeFlashAttention(i,n,s,1,r),o=0;for(let c=0;c<r;c++)o+=a[c]*t[c];return Math.max(0,Math.min(1,(o+1)/2))}async batchComputeSimilarities(t,e){if(await this.ensureFlashAttentionInitialized(),!this.flashAttention)throw new Error("[PatternLearnerService] Flash Attention not initialized. Ensure @ruvector/attention is installed as a dependency.");let r=new Float32Array(t),i=e.map(a=>new Float32Array(a)),n=await this.flashAttention.matchDefectPattern(r,i),s=new Array(e.length).fill(0);for(let a of n)a.pattern<s.length&&(s[a.pattern]=Math.max(0,Math.min(1,(a.score+1)/2)));return s}async clusterByBehavior(t,e){let r=new Map,i=new Map;for(let n of t){let s=n.tags?.sort().join("|")||n.file||"unknown",a=i.get(s)||[];a.push(n),i.set(s,a)}for(let[n,s]of i)if(s.length>=e){let a=v(),o=this.findCommonFactors(s);r.set(a,{id:a,label:`Behavioral: ${n.replace(/\|/g,", ")}`,defects:s.map(c=>c.id),commonFactors:o,suggestedFix:this.suggestFix(o)})}return Array.from(r.values())}async clusterByTemporal(t,e){let r=new Map,i=new Map;for(let n of t){let s=n.title.toLowerCase().split(/\s+/).slice(0,2).join(" "),a=i.get(s)||[];a.push(n),i.set(s,a)}for(let[n,s]of i)if(s.length>=2){let a=v(),o=this.findCommonFactors(s);r.set(a,{id:a,label:`Temporal: ${n}`,defects:s.map(c=>c.id),commonFactors:o,suggestedFix:this.suggestFix(o)})}return Array.from(r.values())}findCommonFactors(t){let e=[];if(t.every(n=>n.tags)){let n=t.map(a=>new Set(a.tags)),s=[...n[0]].filter(a=>n.every(o=>o.has(a)));e.push(...s)}if(t.every(n=>n.file)){let n=t.map(a=>a.file.split("/")),s=Math.min(...n.map(a=>a.length));for(let a=0;a<s;a++)n.every(o=>o[a]===n[0][a])&&e.push(`Path: ${n[0][a]}`)}let r=t.map(n=>new Set(n.title.toLowerCase().split(/\s+/))),i=[...r[0]].filter(n=>n.length>3&&r.every(s=>s.has(n)));return e.push(...i.map(n=>`Keyword: ${n}`)),[...new Set(e)]}generateClusterLabel(t){let r=t.map(s=>s.title.toLowerCase()).flatMap(s=>s.split(/\s+/)),i=new Map;for(let s of r)s.length>3&&i.set(s,(i.get(s)||0)+1);return[...i.entries()].sort((s,a)=>a[1]-s[1]).slice(0,2).map(([s])=>s).join(" ")||"Unnamed Cluster"}suggestFix(t){for(let e of t)for(let[r,i]of Object.entries(Fs))if(e.toLowerCase().includes(r)||i.indicators.some(n=>e.toLowerCase().includes(n.toLowerCase())))return i.prevention;return"Review common factors and implement targeted fixes"}calculateClusteringMetrics(t,e){if(t.length===0||e===0)return{silhouette:0,cohesion:0};let r=t.reduce((c,l)=>c+l.defects.length,0),i=r/t.length,n=r/e,s=t.map(c=>c.defects.length),a=s.reduce((c,l)=>c+Math.pow(l-i,2),0)/s.length,o=Math.max(0,1-a/(i*i||1));return{silhouette:Math.round(o*100)/100,cohesion:Math.round(n*100)/100}}async generateDefectEmbedding(t){let e=this.formatDefectForEmbedding(t);return this.embedder.embed(e)}async generatePatternEmbedding(t){let e=this.formatPatternForEmbedding(t);return this.embedder.embed(e)}formatDefectForEmbedding(t){return[`Title: ${t.title}`,t.description?`Description: ${t.description}`:"",t.tags?.length?`Tags: ${t.tags.join(", ")}`:"",t.file?`File: ${t.file}`:""].filter(Boolean).join(`
|
|
2767
2767
|
`)}formatPatternForEmbedding(t){return[`Pattern: ${t.name}`,`Indicators: ${t.indicators.join(", ")}`,`Prevention: ${t.prevention}`,`Frequency: ${t.frequency}`].filter(Boolean).join(`
|
|
2768
2768
|
`)}cachePattern(t){if(this.patternCache.size>=this.MAX_CACHED_PATTERNS){let e=this.patternCache.keys().next().value;e&&this.patternCache.delete(e)}this.patternCache.set(t.id,t)}destroy(){this.patternCache.clear(),this.flashAttention=null,this.flashAttentionAvailable=!1}};M();A();H();var Ug={maxTimelineEvents:20,maxRelatedFiles:10,minConfidenceThreshold:.3,analyzerNamespace:"defect-intelligence:root-cause",enableDeepAnalysis:!0,enableLLMAnalysis:!0,llmModelTier:2,llmMaxTokens:2048},Ls={"logic-error":{symptoms:["wrong result","incorrect output","unexpected behavior","calculation"],causes:["Incorrect algorithm implementation","Missing edge case handling","Wrong operator usage","Off-by-one error"],impact:"high",remediation:["Review algorithm logic step by step","Add comprehensive unit tests","Use property-based testing for edge cases"]},"null-reference":{symptoms:["null","undefined","cannot read property","NullPointerException"],causes:["Missing null check","Uninitialized variable","Race condition in initialization","API returning null unexpectedly"],impact:"high",remediation:["Add defensive null checks","Use Optional/Maybe pattern","Initialize variables at declaration"]},concurrency:{symptoms:["race","deadlock","intermittent","timing","thread"],causes:["Missing synchronization","Shared mutable state","Lock ordering issue","Async operation not awaited"],impact:"high",remediation:["Use immutable data structures","Implement proper locking strategy","Add synchronization primitives"]},"resource-management":{symptoms:["memory","leak","connection","file handle","exhausted"],causes:["Resource not properly released","Missing cleanup in error path","Connection pool misconfiguration","Circular reference preventing GC"],impact:"medium",remediation:["Use try-finally or using blocks","Implement IDisposable pattern","Configure resource pools properly"]},configuration:{symptoms:["config","environment","setting","property","parameter"],causes:["Wrong configuration value","Missing required setting","Environment mismatch","Hardcoded values"],impact:"medium",remediation:["Validate configuration at startup","Use configuration schema validation","Document all required settings"]},integration:{symptoms:["api","service","external","timeout","connection"],causes:["External service change","API contract violation","Network configuration issue","Missing retry logic"],impact:"high",remediation:["Implement circuit breaker pattern","Add contract tests","Use retry with exponential backoff"]},"data-integrity":{symptoms:["corrupt","invalid","constraint","duplicate","data"],causes:["Missing validation","Database constraint violated","Race condition in data update","Inconsistent state transitions"],impact:"high",remediation:["Add input validation at all layers","Use database transactions properly","Implement optimistic locking"]},security:{symptoms:["injection","auth","permission","access","security"],causes:["Missing input sanitization","Broken authentication","Insufficient authorization checks","Sensitive data exposure"],impact:"high",remediation:["Sanitize all user inputs","Implement proper authentication","Follow principle of least privilege"]}},Qg=R.create("defect-intelligence/root-cause-analyzer"),hr=class{config;memory;llmRouter;constructor(t,e={}){this.config={...Ug,...e},this.isMemoryBackend(t)?(this.memory=t,this.llmRouter=void 0):(this.memory=t.memory,this.llmRouter=t.llmRouter)}isMemoryBackend(t){return typeof t.get=="function"&&typeof t.set=="function"&&!("memory"in t)}isLLMAnalysisAvailable(){return this.config.enableLLMAnalysis===!0&&this.llmRouter!==void 0}getModelForTier(t){switch(t){case 1:return"claude-haiku-4-5-20251001";case 2:return"claude-sonnet-4-6";case 3:return"claude-sonnet-4-6";case 4:return"claude-opus-4-7";default:return"claude-sonnet-4-6"}}async analyzeRootCauseWithLLM(t,e,r){if(!this.llmRouter)return null;try{let i=this.buildLLMAnalysisPrompt(t,e,r),n=this.getModelForTier(this.config.llmModelTier??2),s=await this.llmRouter.chat({messages:[{role:"system",content:`You are an expert software engineer specialized in debugging and root cause analysis.
|
|
2769
2769
|
Analyze the provided defect information and provide:
|
|
@@ -2882,7 +2882,7 @@ Please analyze these requirements for:
|
|
|
2882
2882
|
`;return i}generateDependencyGraph(t,e){let r=`graph TD
|
|
2883
2883
|
`;for(let i of t)r+=` ${i.id}["${i.name}"]
|
|
2884
2884
|
`;for(let i of e){let n=i.type==="depends_on"?"-->|depends|":"-->";r+=` ${i.sourceId} ${n} ${i.targetId}
|
|
2885
|
-
`}return r}async getProjectMetadata(t){try{let e=Ze.join(t,"package.json"),r=await _e.readFile(e,"utf-8"),i=E(r);return{name:i.name||"Project",description:i.description||"Application system"}}catch{return{name:"Project",description:"Application system"}}}async detectExternalSystems(t){let e=[];try{let r=Ze.join(t,"package.json");try{await _e.access(r)}catch{return e}let i=await _e.readFile(r,"utf-8"),n=E(i),s={...n.dependencies,...n.devDependencies};for(let[a]of Object.entries(s)){let o=lf[a];o&&e.push({id:zs(a),name:o.technology,type:o.type,technology:o.technology,detectedFrom:"package.json",relationship:this.inferRelationship(o.type)})}}catch(r){Vt.error("External system detection failed",r instanceof Error?r:void 0)}return e}inferRelationship(t){switch(t){case"database":return"stores_data_in";case"auth":return"authenticates_with";case"queue":return"sends";default:return"uses"}}async analyzeComponents(t){let e=[],r=[];try{let i=Ze.join(t,"src"),n=t;try{await _e.access(i),n=i}catch{}let s=await _e.readdir(n,{withFileTypes:!0});for(let a of s)if(a.isDirectory()&&!this.shouldExclude(a.name)){let o=Ze.join(n,a.name),c=await this.getFilesInDirectory(o,t);c.length>0&&e.push({id:zs(a.name),name:this.formatComponentName(a.name),type:Dd(a.name),boundary:this.inferBoundary(a.name),technology:"TypeScript",files:c,responsibilities:[this.inferResponsibility(a.name)]})}for(let a=0;a<e.length;a++)for(let o=a+1;o<e.length;o++){let c=e[a],l=e[o];this.likelyHasRelationship(c.id,l.id)&&r.push({sourceId:c.id,targetId:l.id,type:"uses",weight:1})}}catch(i){Vt.error("Component analysis failed:",i instanceof Error?i:void 0)}return{components:e,relationships:r}}shouldExclude(t){return["node_modules",".git","dist","build","coverage","__tests__","__mocks__"].includes(t)||t.startsWith(".")}async getFilesInDirectory(t,e,r=3){let i=[],n=async(s,a)=>{if(!(a>r))try{let o=await _e.readdir(s,{withFileTypes:!0});for(let c of o){if(this.shouldExclude(c.name))continue;let l=Ze.join(s,c.name),d=Ze.relative(e,l);c.isDirectory()?await n(l,a+1):c.isFile()&&this.isSourceFile(c.name)&&i.push(d)}}catch{Vt.debug("Directory scan error:")}};return await n(t,0),i}isSourceFile(t){return[".ts",".tsx",".js",".jsx",".vue",".svelte"].some(r=>t.endsWith(r))&&!t.endsWith(".d.ts")}formatComponentName(t){return t.split(/[-_]/).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}inferBoundary(t){let e=t.toLowerCase();return e.includes("api")||e.includes("controller")?"API Layer":e.includes("service")?"Service Layer":e.includes("domain")?"Domain Layer":e.includes("infra")||e.includes("database")?"Infrastructure Layer":e.includes("ui")||e.includes("component")?"Presentation Layer":"Core"}inferResponsibility(t){let e=t.toLowerCase();return e.includes("auth")?"Authentication and authorization":e.includes("user")?"User management":e.includes("api")?"API endpoint handling":e.includes("service")?"Business logic processing":e.includes("model")?"Data modeling and validation":e.includes("util")?"Utility functions":e.includes("config")?"Configuration management":`${this.formatComponentName(t)} functionality`}likelyHasRelationship(t,e){let r=[["service","model"],["service","repository"],["controller","service"],["api","service"],["domain","infra"]],i=t.toLowerCase(),n=e.toLowerCase();return r.some(([s,a])=>i.includes(s)&&n.includes(a)||i.includes(a)&&n.includes(s))}analyzeCoupling(t,e){let r=[];try{if(t.length<2)return r;let i=new Set;for(let n of e)if(e.some(a=>a.sourceId===n.targetId&&a.targetId===n.sourceId)){let a=[n.sourceId,n.targetId].sort().join("::");i.add(a)}for(let n=0;n<t.length;n++)for(let s=n+1;s<t.length;s++){let a=t[n],o=t[s],c=e.filter(l=>l.sourceId===a.id&&l.targetId===o.id||l.sourceId===o.id&&l.targetId===a.id);if(c.length>0){let l=c.reduce((g,b)=>g+(b.weight||1),0),d=Math.min(1,l/10),m=[a.id,o.id].sort().join("::"),h=i.has(m);r.push({moduleA:a.name,moduleB:o.name,couplingStrength:d,isCircular:h,recommendation:this.getCouplingRecommendation(d,h)})}}}catch(i){Vt.error("Coupling analysis failed:",i instanceof Error?i:void 0)}return r}getCouplingRecommendation(t,e){return e?"CRITICAL: Circular dependency detected. Consider extracting shared interface.":t>.8?"HIGH: Tightly coupled. Consider interface segregation or facade pattern.":t>.5?"MEDIUM: Moderate coupling. Monitor for growth.":"LOW: Acceptable coupling level."}async getCachedDiagrams(t){let e=this.getCacheKey(t),r=await this.memory.get(e);return r&&kd(r)?r.result:null}async invalidateCache(t){let e=this.getCacheKey(t);await this.memory.delete(e)}async cacheResult(t,e){let r=this.getCacheKey(t),i=await this.computeProjectHash(t),n={result:e,cachedAt:new Date,ttlMs:this.config.cacheTtlMs,projectHash:i};await this.memory.set(r,n,{namespace:"code-intelligence",ttl:this.config.cacheTtlMs})}getCacheKey(t){return`c4-diagrams:${zs(t)}`}async computeProjectHash(t){try{let e=Ze.join(t,"package.json"),r=await _e.readFile(e,"utf-8");return this.hashString(r)}catch{return this.hashString(t+Date.now())}}hashString(t){let e=0;for(let r=0;r<t.length;r++)e=(e<<5)-e+t.charCodeAt(r),e=e|0;return Math.abs(e).toString(16)}async getExternalSystems(t){try{let e=await this.getCachedDiagrams(t);if(e)return f(e.externalSystems);let r=await this.detectExternalSystems(t);return f(r)}catch(e){let r=y(e);return p(r)}}async getComponents(t){try{let e=await this.getCachedDiagrams(t);if(e)return f(e.components);let{components:r}=await this.analyzeComponents(t);return f(r)}catch(e){let r=y(e);return p(r)}}async publishC4DiagramsGenerated(t,e,r,i){let n={requestId:t,projectPath:e,componentsDetected:r.components.length,externalSystemsDetected:r.externalSystems.length,relationshipsDetected:r.relationships.length,analysisTimeMs:i,hasContextDiagram:!!r.diagrams.context,hasContainerDiagram:!!r.diagrams.container,hasComponentDiagram:!!r.diagrams.component},s=I(rt.C4DiagramsGenerated,"code-intelligence",n);await this.eventBus.publish(s)}};A();var uf={embeddingDimension:At.DIMENSIONS,minScore:.5,maxResults:100,namespace:"code-intelligence:semantic",enableCaching:!0,cacheSize:1e3,useNomicEmbeddings:!0},_t=class{constructor(t,e={}){this.memory=t;this.config={...uf,...e},e.embeddingProvider&&(this.embedder=e.embeddingProvider,this.embedderInitialized=!0)}memory;config;embeddingCache=new Map;analysisCache=new Map;embedder=null;embedderInitialized=!1;async initializeEmbedder(){if(!this.embedderInitialized){if(this.config.useNomicEmbeddings){let t=new Et({enableFallback:!0,...this.config.nomicConfig});await t.healthCheck()&&(this.embedder=t,this.config.embeddingDimension=At.DIMENSIONS)}this.embedderInitialized=!0}}async search(t){let e=Date.now();try{let{query:r,type:i,scope:n,limit:s=this.config.maxResults,filters:a}=t,o;switch(i){case"semantic":o=await this.semanticSearch(r,s,n,a);break;case"exact":o=await this.exactSearch(r,s,n,a);break;case"fuzzy":o=await this.fuzzySearch(r,s,n,a);break;default:return p(new Error(`Unknown search type: ${i}`))}let c=Date.now()-e;return f({results:o,total:o.length,searchTime:c})}catch(r){return p(y(r))}}async indexCode(t,e){try{let r=await this.getEmbedding(e),i=this.extractCodeMetadata(t,e),n=`${this.config.namespace}:code:${this.fileToKey(t)}`;return await this.memory.storeVector(n,r,{file:t,...i,indexedAt:new Date().toISOString()}),await this.memory.set(`${this.config.namespace}:content:${this.fileToKey(t)}`,{file:t,content:e,metadata:i},{namespace:this.config.namespace}),f(void 0)}catch(r){return p(y(r))}}async findSimilar(t,e=10){try{let r=await this.getEmbedding(t),i=await this.memory.vectorSearch(r,e),n=[];for(let s of i){if(s.score<this.config.minScore)continue;let a=s.metadata;if(!a?.file)continue;let o=`${this.config.namespace}:content:${this.fileToKey(a.file)}`,c=await this.memory.get(o);c&&n.push({file:c.file,snippet:this.extractSnippet(c.content,200),score:s.score,highlights:this.findHighlights(c.content,t),metadata:c.metadata})}return f(n)}catch(r){return p(y(r))}}async analyze(t){try{let e=this.hashCode(t);if(this.config.enableCaching&&this.analysisCache.has(e))return f(this.analysisCache.get(e));let r=this.extractConcepts(t),i=this.detectPatterns(t),n=this.calculateComplexity(t),s=this.extractDependencies(t),a=this.generateSuggestions(t,n,i),o={concepts:r,patterns:i,complexity:n,dependencies:s,suggestions:a};return this.config.enableCaching&&this.cacheAnalysis(e,o),f(o)}catch(e){return p(y(e))}}async getEmbedding(t){let e=this.hashCode(t);if(this.config.enableCaching&&this.embeddingCache.has(e))return this.embeddingCache.get(e);await this.initializeEmbedder();let r;return this.embedder?r=await this.embedder.embed(t):r=this.generateCodeEmbedding(t),this.config.enableCaching&&this.cacheEmbedding(e,r),r}isUsingNomicEmbeddings(){return this.embedder!==null&&this.embedder instanceof Et}async semanticSearch(t,e,r,i){let n=await this.getEmbedding(t),s=await this.memory.vectorSearch(n,e*2),a=[];for(let o of s){if(o.score<this.config.minScore)continue;let c=o.metadata;if(!c?.file||r&&r.length>0&&!r.some(h=>c.file.includes(h)))continue;let l=`${this.config.namespace}:content:${this.fileToKey(c.file)}`,d=await this.memory.get(l);if(d){if(i&&!this.matchesFilters(d.metadata,i))continue;if(a.push({file:d.file,snippet:this.extractSnippet(d.content,200),score:o.score,highlights:this.findSemanticHighlights(d.content,t),metadata:d.metadata}),a.length>=e)break}}return a}async exactSearch(t,e,r,i){let n=[],s=`${this.config.namespace}:content:*`,a=await this.memory.search(s,e*3);for(let o of a){let c=await this.memory.get(o);if(!c||r&&r.length>0&&!r.some(m=>c.file.includes(m))||i&&!this.matchesFilters(c.metadata,i))continue;let l=c.content.indexOf(t);if(l>=0){let d=this.getLineNumber(c.content,l);if(n.push({file:c.file,line:d,snippet:this.extractSnippetAround(c.content,l,100),score:1,highlights:[t],metadata:c.metadata}),n.length>=e)break}}return n}async fuzzySearch(t,e,r,i){let n=[],s=`${this.config.namespace}:content:*`,a=await this.memory.search(s,e*5),o=this.tokenize(t.toLowerCase());for(let c of a){let l=await this.memory.get(c);if(!l||r&&r.length>0&&!r.some(g=>l.file.includes(g))||i&&!this.matchesFilters(l.metadata,i))continue;let d=this.tokenize(l.content.toLowerCase()),m=this.calculateFuzzyScore(o,d);if(m>=this.config.minScore){let h=o.filter(g=>d.some(b=>b.includes(g)||g.includes(b)));n.push({file:l.file,snippet:this.extractSnippet(l.content,200),score:m,highlights:h,metadata:l.metadata})}}return n.sort((c,l)=>l.score-c.score).slice(0,e)}extractConcepts(t){let e=[];return/class\s+\w+/.test(t)&&e.push("object-oriented"),/async\s+|await\s+|Promise/.test(t)&&e.push("asynchronous"),/\([^)]*\)\s*=>/.test(t)&&e.push("functional"),/interface\s+\w+/.test(t)&&e.push("type-safe"),/export\s+(default\s+)?/.test(t)&&e.push("modular"),/import\s+.*from/.test(t)&&e.push("dependency-injection"),/try\s*{[\s\S]*catch/.test(t)&&e.push("error-handling"),/\.map\(|\.filter\(|\.reduce\(/.test(t)&&e.push("collection-processing"),/new\s+Map\(|new\s+Set\(/.test(t)&&e.push("data-structures"),/describe\(|it\(|test\(|expect\(/.test(t)&&e.push("testing"),Array.from(new Set(e))}detectPatterns(t){let e=[];return/private\s+static\s+instance|getInstance\(\)/.test(t)&&e.push("singleton"),/factory|create\w+\(\)/.test(t)&&e.push("factory"),/constructor\(.*private.*\)/.test(t)&&e.push("dependency-injection"),/extends\s+\w+.*implements\s+\w+/.test(t)&&e.push("decorator"),/subscribe\(|on\w+\(|emit\(|publish\(/.test(t)&&e.push("observer"),/strategy|Strategy/.test(t)&&e.push("strategy"),/Repository|DAO/.test(t)&&e.push("repository"),/Builder|\.with\w+\(/.test(t)&&e.push("builder"),e}calculateComplexity(t){let e=[/\bif\b/g,/\belse\b/g,/\bfor\b/g,/\bwhile\b/g,/\bcase\b/g,/\bcatch\b/g,/\?\s*:/g,/&&/g,/\|\|/g],r=1;for(let P of e){let O=t.match(P);r+=O?O.length:0}let i=0,n=t.split(`
|
|
2885
|
+
`}return r}async getProjectMetadata(t){try{let e=Ze.join(t,"package.json"),r=await _e.readFile(e,"utf-8"),i=E(r);return{name:i.name||"Project",description:i.description||"Application system"}}catch{return{name:"Project",description:"Application system"}}}async detectExternalSystems(t){let e=[];try{let r=Ze.join(t,"package.json");try{await _e.access(r)}catch{return e}let i=await _e.readFile(r,"utf-8"),n=E(i),s={...n.dependencies,...n.devDependencies};for(let[a]of Object.entries(s)){let o=lf[a];o&&e.push({id:zs(a),name:o.technology,type:o.type,technology:o.technology,detectedFrom:"package.json",relationship:this.inferRelationship(o.type)})}}catch(r){Vt.error("External system detection failed",r instanceof Error?r:void 0)}return e}inferRelationship(t){switch(t){case"database":return"stores_data_in";case"auth":return"authenticates_with";case"queue":return"sends";default:return"uses"}}async analyzeComponents(t){let e=[],r=[];try{let i=Ze.join(t,"src"),n=t;try{await _e.access(i),n=i}catch{}let s=await _e.readdir(n,{withFileTypes:!0});for(let a of s)if(a.isDirectory()&&!this.shouldExclude(a.name)){let o=Ze.join(n,a.name),c=await this.getFilesInDirectory(o,t);c.length>0&&e.push({id:zs(a.name),name:this.formatComponentName(a.name),type:Dd(a.name),boundary:this.inferBoundary(a.name),technology:"TypeScript",files:c,responsibilities:[this.inferResponsibility(a.name)]})}for(let a=0;a<e.length;a++)for(let o=a+1;o<e.length;o++){let c=e[a],l=e[o];this.likelyHasRelationship(c.id,l.id)&&r.push({sourceId:c.id,targetId:l.id,type:"uses",weight:1})}}catch(i){Vt.error("Component analysis failed:",i instanceof Error?i:void 0)}return{components:e,relationships:r}}shouldExclude(t){return["node_modules",".git","dist","build","coverage","__tests__","__mocks__"].includes(t)||t.startsWith(".")}async getFilesInDirectory(t,e,r=3){let i=[],n=async(s,a)=>{if(!(a>r))try{let o=await _e.readdir(s,{withFileTypes:!0});for(let c of o){if(this.shouldExclude(c.name))continue;let l=Ze.join(s,c.name),d=Ze.relative(e,l);c.isDirectory()?await n(l,a+1):c.isFile()&&this.isSourceFile(c.name)&&i.push(d)}}catch{Vt.debug("Directory scan error:")}};return await n(t,0),i}isSourceFile(t){return[".ts",".tsx",".js",".jsx",".vue",".svelte"].some(r=>t.endsWith(r))&&!t.endsWith(".d.ts")}formatComponentName(t){return t.split(/[-_]/).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}inferBoundary(t){let e=t.toLowerCase();return e.includes("api")||e.includes("controller")?"API Layer":e.includes("service")?"Service Layer":e.includes("domain")?"Domain Layer":e.includes("infra")||e.includes("database")?"Infrastructure Layer":e.includes("ui")||e.includes("component")?"Presentation Layer":"Core"}inferResponsibility(t){let e=t.toLowerCase();return e.includes("auth")?"Authentication and authorization":e.includes("user")?"User management":e.includes("api")?"API endpoint handling":e.includes("service")?"Business logic processing":e.includes("model")?"Data modeling and validation":e.includes("util")?"Utility functions":e.includes("config")?"Configuration management":`${this.formatComponentName(t)} functionality`}likelyHasRelationship(t,e){let r=[["service","model"],["service","repository"],["controller","service"],["api","service"],["domain","infra"]],i=t.toLowerCase(),n=e.toLowerCase();return r.some(([s,a])=>i.includes(s)&&n.includes(a)||i.includes(a)&&n.includes(s))}analyzeCoupling(t,e){let r=[];try{if(t.length<2)return r;let i=new Set;for(let n of e)if(e.some(a=>a.sourceId===n.targetId&&a.targetId===n.sourceId)){let a=[n.sourceId,n.targetId].sort().join("::");i.add(a)}for(let n=0;n<t.length;n++)for(let s=n+1;s<t.length;s++){let a=t[n],o=t[s],c=e.filter(l=>l.sourceId===a.id&&l.targetId===o.id||l.sourceId===o.id&&l.targetId===a.id);if(c.length>0){let l=c.reduce((g,b)=>g+(b.weight||1),0),d=Math.min(1,l/10),m=[a.id,o.id].sort().join("::"),h=i.has(m);r.push({moduleA:a.name,moduleB:o.name,couplingStrength:d,isCircular:h,recommendation:this.getCouplingRecommendation(d,h)})}}}catch(i){Vt.error("Coupling analysis failed:",i instanceof Error?i:void 0)}return r}getCouplingRecommendation(t,e){return e?"CRITICAL: Circular dependency detected. Consider extracting shared interface.":t>.8?"HIGH: Tightly coupled. Consider interface segregation or facade pattern.":t>.5?"MEDIUM: Moderate coupling. Monitor for growth.":"LOW: Acceptable coupling level."}async getCachedDiagrams(t){let e=this.getCacheKey(t),r=await this.memory.get(e);return r&&kd(r)?r.result:null}async invalidateCache(t){let e=this.getCacheKey(t);await this.memory.delete(e)}async cacheResult(t,e){let r=this.getCacheKey(t),i=await this.computeProjectHash(t),n={result:e,cachedAt:new Date,ttlMs:this.config.cacheTtlMs,projectHash:i};await this.memory.set(r,n,{namespace:"code-intelligence",ttl:this.config.cacheTtlMs})}getCacheKey(t){return`c4-diagrams:${zs(t)}`}async computeProjectHash(t){try{let e=Ze.join(t,"package.json"),r=await _e.readFile(e,"utf-8");return this.hashString(r)}catch{return this.hashString(t+Date.now())}}hashString(t){let e=0;for(let r=0;r<t.length;r++)e=(e<<5)-e+t.charCodeAt(r),e=e|0;return Math.abs(e).toString(16)}async getExternalSystems(t){try{let e=await this.getCachedDiagrams(t);if(e)return f(e.externalSystems);let r=await this.detectExternalSystems(t);return f(r)}catch(e){let r=y(e);return p(r)}}async getComponents(t){try{let e=await this.getCachedDiagrams(t);if(e)return f(e.components);let{components:r}=await this.analyzeComponents(t);return f(r)}catch(e){let r=y(e);return p(r)}}async publishC4DiagramsGenerated(t,e,r,i){let n={requestId:t,projectPath:e,componentsDetected:r.components.length,externalSystemsDetected:r.externalSystems.length,relationshipsDetected:r.relationships.length,analysisTimeMs:i,hasContextDiagram:!!r.diagrams.context,hasContainerDiagram:!!r.diagrams.container,hasComponentDiagram:!!r.diagrams.component},s=I(rt.C4DiagramsGenerated,"code-intelligence",n);await this.eventBus.publish(s)}};A();var uf={embeddingDimension:At.DIMENSIONS,minScore:.5,maxResults:100,namespace:"code-intelligence:semantic",enableCaching:!0,cacheSize:1e3,useNomicEmbeddings:!0},_t=class{constructor(t,e={}){this.memory=t;this.config={...uf,...e},e.embeddingProvider&&(this.embedder=e.embeddingProvider,this.embedderInitialized=!0)}memory;config;embeddingCache=new Map;analysisCache=new Map;embedder=null;embedderInitialized=!1;async initializeEmbedder(){if(!this.embedderInitialized){if(this.config.useNomicEmbeddings){let t=new Et({enableFallback:!0,...this.config.nomicConfig});await t.healthCheck()&&(this.embedder=t,this.config.embeddingDimension=At.DIMENSIONS)}this.embedderInitialized=!0}}async search(t){let e=Date.now();try{let{query:r,type:i,scope:n,limit:s=this.config.maxResults,filters:a}=t,o;switch(i){case"semantic":o=await this.semanticSearch(r,s,n,a);break;case"exact":o=await this.exactSearch(r,s,n,a);break;case"fuzzy":o=await this.fuzzySearch(r,s,n,a);break;default:return p(new Error(`Unknown search type: ${i}`))}let c=Date.now()-e;return f({results:o,total:o.length,searchTime:c})}catch(r){return p(y(r))}}async indexCode(t,e){try{let r=await this.getEmbedding(e),i=this.extractCodeMetadata(t,e),n=`${this.config.namespace}:code:${this.fileToKey(t)}`;return await this.memory.storeVector(n,r,{file:t,...i,indexedAt:new Date().toISOString()}),await this.memory.set(`${this.config.namespace}:content:${this.fileToKey(t)}`,{file:t,content:e,metadata:i}),f(void 0)}catch(r){return p(y(r))}}async findSimilar(t,e=10){try{let r=await this.getEmbedding(t),i=await this.memory.vectorSearch(r,e),n=[];for(let s of i){if(s.score<this.config.minScore)continue;let a=s.metadata;if(!a?.file)continue;let o=`${this.config.namespace}:content:${this.fileToKey(a.file)}`,c=await this.memory.get(o);c&&n.push({file:c.file,snippet:this.extractSnippet(c.content,200),score:s.score,highlights:this.findHighlights(c.content,t),metadata:c.metadata})}return f(n)}catch(r){return p(y(r))}}async analyze(t){try{let e=this.hashCode(t);if(this.config.enableCaching&&this.analysisCache.has(e))return f(this.analysisCache.get(e));let r=this.extractConcepts(t),i=this.detectPatterns(t),n=this.calculateComplexity(t),s=this.extractDependencies(t),a=this.generateSuggestions(t,n,i),o={concepts:r,patterns:i,complexity:n,dependencies:s,suggestions:a};return this.config.enableCaching&&this.cacheAnalysis(e,o),f(o)}catch(e){return p(y(e))}}async getEmbedding(t){let e=this.hashCode(t);if(this.config.enableCaching&&this.embeddingCache.has(e))return this.embeddingCache.get(e);await this.initializeEmbedder();let r;return this.embedder?r=await this.embedder.embed(t):r=this.generateCodeEmbedding(t),this.config.enableCaching&&this.cacheEmbedding(e,r),r}isUsingNomicEmbeddings(){return this.embedder!==null&&this.embedder instanceof Et}async semanticSearch(t,e,r,i){let n=await this.getEmbedding(t),s=await this.memory.vectorSearch(n,e*2),a=[];for(let o of s){if(o.score<this.config.minScore)continue;let c=o.metadata;if(!c?.file||r&&r.length>0&&!r.some(h=>c.file.includes(h)))continue;let l=`${this.config.namespace}:content:${this.fileToKey(c.file)}`,d=await this.memory.get(l);if(d){if(i&&!this.matchesFilters(d.metadata,i))continue;if(a.push({file:d.file,snippet:this.extractSnippet(d.content,200),score:o.score,highlights:this.findSemanticHighlights(d.content,t),metadata:d.metadata}),a.length>=e)break}}return a}async exactSearch(t,e,r,i){let n=[],s=`${this.config.namespace}:content:*`,a=await this.memory.search(s,e*3);for(let o of a){let c=await this.memory.get(o);if(!c||r&&r.length>0&&!r.some(m=>c.file.includes(m))||i&&!this.matchesFilters(c.metadata,i))continue;let l=c.content.indexOf(t);if(l>=0){let d=this.getLineNumber(c.content,l);if(n.push({file:c.file,line:d,snippet:this.extractSnippetAround(c.content,l,100),score:1,highlights:[t],metadata:c.metadata}),n.length>=e)break}}return n}async fuzzySearch(t,e,r,i){let n=[],s=`${this.config.namespace}:content:*`,a=await this.memory.search(s,e*5),o=this.tokenize(t.toLowerCase());for(let c of a){let l=await this.memory.get(c);if(!l||r&&r.length>0&&!r.some(g=>l.file.includes(g))||i&&!this.matchesFilters(l.metadata,i))continue;let d=this.tokenize(l.content.toLowerCase()),m=this.calculateFuzzyScore(o,d);if(m>=this.config.minScore){let h=o.filter(g=>d.some(b=>b.includes(g)||g.includes(b)));n.push({file:l.file,snippet:this.extractSnippet(l.content,200),score:m,highlights:h,metadata:l.metadata})}}return n.sort((c,l)=>l.score-c.score).slice(0,e)}extractConcepts(t){let e=[];return/class\s+\w+/.test(t)&&e.push("object-oriented"),/async\s+|await\s+|Promise/.test(t)&&e.push("asynchronous"),/\([^)]*\)\s*=>/.test(t)&&e.push("functional"),/interface\s+\w+/.test(t)&&e.push("type-safe"),/export\s+(default\s+)?/.test(t)&&e.push("modular"),/import\s+.*from/.test(t)&&e.push("dependency-injection"),/try\s*{[\s\S]*catch/.test(t)&&e.push("error-handling"),/\.map\(|\.filter\(|\.reduce\(/.test(t)&&e.push("collection-processing"),/new\s+Map\(|new\s+Set\(/.test(t)&&e.push("data-structures"),/describe\(|it\(|test\(|expect\(/.test(t)&&e.push("testing"),Array.from(new Set(e))}detectPatterns(t){let e=[];return/private\s+static\s+instance|getInstance\(\)/.test(t)&&e.push("singleton"),/factory|create\w+\(\)/.test(t)&&e.push("factory"),/constructor\(.*private.*\)/.test(t)&&e.push("dependency-injection"),/extends\s+\w+.*implements\s+\w+/.test(t)&&e.push("decorator"),/subscribe\(|on\w+\(|emit\(|publish\(/.test(t)&&e.push("observer"),/strategy|Strategy/.test(t)&&e.push("strategy"),/Repository|DAO/.test(t)&&e.push("repository"),/Builder|\.with\w+\(/.test(t)&&e.push("builder"),e}calculateComplexity(t){let e=[/\bif\b/g,/\belse\b/g,/\bfor\b/g,/\bwhile\b/g,/\bcase\b/g,/\bcatch\b/g,/\?\s*:/g,/&&/g,/\|\|/g],r=1;for(let P of e){let O=t.match(P);r+=O?O.length:0}let i=0,n=t.split(`
|
|
2886
2886
|
`),s=0;for(let P of n)/{/.test(P)&&s++,/}/.test(P)&&(s=Math.max(0,s-1)),/\bif\b|\bfor\b|\bwhile\b/.test(P)&&(i+=1+s);let a=t.match(/[+\-*/%=<>!&|^~?:;,.()\[\]{}]+|function|return|if|else|for|while|switch|case|break|continue|throw|try|catch|finally|new|delete|typeof|instanceof|void|in|of/g)||[],o=t.match(/\b[a-zA-Z_]\w*\b|\b\d+\b|'[^']*'|"[^"]*"|`[^`]*`/g)||[],c=new Set(a).size,l=new Set(o).size,d=a.length,m=o.length,h=c+l,g=d+m,b=l>0?c/2*(m/l):0,w=g>0?g*Math.log2(h||1):0,C=b*w,S=C/18,k=w/3e3;return{cyclomatic:r,cognitive:i,halstead:{vocabulary:h,length:g,difficulty:Math.round(b*100)/100,effort:Math.round(C),time:Math.round(S),bugs:Math.round(k*1e3)/1e3}}}extractDependencies(t){let e=[],r=/import\s+(?:\{[^}]+\}|\*\s+as\s+\w+|\w+)\s+from\s+['"]([^'"]+)['"]/g,i;for(;(i=r.exec(t))!==null;)e.push(i[1]);let n=/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,s;for(;(s=n.exec(t))!==null;)e.push(s[1]);return Array.from(new Set(e))}generateSuggestions(t,e,r){let i=[];return e.cyclomatic>10&&i.push("Consider breaking down complex functions into smaller units"),e.cognitive>15&&i.push("Reduce nesting depth to improve readability"),e.halstead.bugs>.5&&i.push("High estimated bug density - add comprehensive tests"),!r.includes("error-handling")&&/async|Promise/.test(t)&&i.push("Add error handling for async operations"),!r.includes("testing")&&t.length>500&&i.push("Consider adding unit tests for this code"),t.split(`
|
|
2887
2887
|
`).length>200&&i.push("Consider splitting this file into smaller modules"),t.split(`
|
|
2888
2888
|
`).filter(s=>s.length>120).length>5&&i.push("Some lines exceed 120 characters - consider reformatting"),i}generateCodeEmbedding(t){let e=new Array(this.config.embeddingDimension).fill(0),r=this.tokenize(t),i=this.extractConcepts(t);for(let a=0;a<r.length;a++){let o=r[a];for(let c=0;c<o.length&&c<e.length;c++)e[(a+c)%e.length]+=o.charCodeAt(c)/1e3}let n=new Map([["object-oriented",0],["asynchronous",1],["functional",2],["type-safe",3],["modular",4]]);for(let a of i){let o=n.get(a);o!==void 0&&(e[o]+=.5)}let s=Math.sqrt(e.reduce((a,o)=>a+o*o,0))||1;return e.map(a=>a/s)}extractCodeMetadata(t,e){return{language:this.detectLanguage(t),lines:e.split(`
|
|
@@ -2894,7 +2894,7 @@ Please analyze these requirements for:
|
|
|
2894
2894
|
`).map(i=>i.trim()).filter(i=>i.length>0&&ge(i));if(r.length>0){let i=0;for(let n of r)i+=Fd(n);return Gs(i,"jest",u)}return Oi(u,t)}catch{return Oi(u,t)}}function If(u,t){try{let r=Ni("cargo test --list",{cwd:u,encoding:"utf-8",timeout:t.timeout}).split(`
|
|
2895
2895
|
`).filter(o=>o.endsWith(": test")),i=r.length,n=r.filter(o=>!o.includes("integration")&&!o.includes("e2e")).length,s=r.filter(o=>o.includes("integration")).length,a=r.filter(o=>o.includes("e2e")).length;return{total:i,unit:n,integration:s,e2e:a,source:"cargo"}}catch{return{total:0,unit:0,integration:0,e2e:0,source:"cargo"}}}function Mf(u,t){try{let r=Ni("pytest --collect-only -q",{cwd:u,encoding:"utf-8",timeout:t.timeout}).split(`
|
|
2896
2896
|
`).filter(o=>o.includes("::test_")||o.includes("::Test")),i=r.length,n=r.filter(o=>o.includes("unit")||!o.includes("integration")&&!o.includes("e2e")).length,s=r.filter(o=>o.includes("integration")||o.includes("_integration")).length,a=r.filter(o=>o.includes("e2e")||o.includes("end_to_end")).length;return{total:i,unit:n-s-a,integration:s,e2e:a,source:"pytest"}}catch{return{total:0,unit:0,integration:0,e2e:0,source:"pytest"}}}function Ff(u,t){try{let r=Ni('go test -list ".*" ./...',{cwd:u,encoding:"utf-8",timeout:t.timeout}).split(`
|
|
2897
|
-
`).filter(o=>o.startsWith("Test")||o.startsWith("Example")||o.startsWith("Benchmark")),i=r.filter(o=>o.startsWith("Test")).length,n=r.filter(o=>o.startsWith("Test")&&!o.includes("Integration")&&!o.includes("E2E")).length,s=r.filter(o=>o.includes("Integration")).length,a=r.filter(o=>o.includes("E2E")).length;return{total:i,unit:n,integration:s,e2e:a,source:"go"}}catch{return{total:0,unit:0,integration:0,e2e:0,source:"go"}}}function Oi(u,t){let e=0,r=0,i=0,n=0;function s(a){if(!ge(a))return;let o=xf(a,{withFileTypes:!0});for(let c of o){let l=ve(a,c.name);if(c.isDirectory()){if(t.excludeDirs.includes(c.name))continue;s(l)}else if(c.isFile()&&Lf(c.name)){let d=Pf(c.name).toLowerCase(),m=0;[".ts",".tsx",".js",".jsx",".mjs"].includes(d)?m=Fd(l):d===".py"?m=$f(l):d===".rs"?m=Of(l):d===".go"&&(m=Nf(l)),e+=m;let h=l.toLowerCase();h.includes("e2e")||h.includes("end-to-end")?n+=m:h.includes("integration")?i+=m:r+=m}}}return s(u),{total:e,unit:r,integration:i,e2e:n,source:"fallback"}}function Lf(u){let t=u.toLowerCase();return t.includes(".test.")||t.includes(".spec.")||t.includes("_test.")||t.startsWith("test_")||t.endsWith("_test.ts")||t.endsWith("_test.js")||t.endsWith("_test.py")||t.endsWith("_test.go")||t.endsWith("_test.rs")}function Fd(u){try{let t=Vi(u,"utf-8"),e=t.match(/\bit\s*\(/g)||[],r=t.match(/\btest\s*\(/g)||[];return e.length+r.length}catch{return 0}}function $f(u){try{let t=Vi(u,"utf-8"),e=t.match(/\bdef\s+test_\w+\s*\(/g)||[],r=t.match(/\basync\s+def\s+test_\w+\s*\(/g)||[];return e.length+r.length}catch{return 0}}function Of(u){try{let t=Vi(u,"utf-8"),e=t.match(/#\[test\]/g)||[],r=t.match(/#\[tokio::test\]/g)||[],i=t.match(/#\[async_std::test\]/g)||[];return e.length+r.length+i.length}catch{return 0}}function Nf(u){try{return(Vi(u,"utf-8").match(/\bfunc\s+Test\w+\s*\(/g)||[]).length}catch{return 0}}function Gs(u,t,e){let r=u,i=0,n=0;return(ge(ve(e,"tests","integration"))||ge(ve(e,"test","integration"))||ge(ve(e,"__tests__","integration")))&&(i=Math.floor(u*.2),r-=i),(ge(ve(e,"tests","e2e"))||ge(ve(e,"test","e2e"))||ge(ve(e,"e2e"))||ge(ve(e,"cypress")))&&(n=Math.floor(u*.1),r-=n),{total:u,unit:Math.max(0,r),integration:i,e2e:n,source:t}}var kc=class{config;cache=new Map;cacheHits=0;cacheMisses=0;constructor(t={}){this.config={...zt,...t}}async collectAll(t){let e=`all:${t}`;if(this.config.enableCache){let l=this.getFromCache(e);if(l)return l}let[r,i,n]=await Promise.all([this.countLOC(t),this.countTests(t),this.countPatterns(t,this.detectLanguage(t))]),s=[];r.source!=="fallback"&&s.push(r.source),i.source!=="fallback"&&s.push(i.source);let a=r.source==="fallback"?"approximate":"accurate",o=i.source==="fallback"?"approximate":"accurate",c={loc:r,tests:i,patterns:n,collectedAt:new Date,toolsUsed:s,accuracy:{loc:a,tests:o,overall:a==="accurate"&&o==="accurate"?"accurate":"approximate"}};return this.config.enableCache&&this.setInCache(e,c),c}async countLOC(t){let e=`loc:${t}`;if(this.config.enableCache){let i=this.getFromCache(e);if(i)return i}let r=await Tc(t,this.config);return this.config.enableCache&&this.setInCache(e,r),r}async countTests(t){let e=`tests:${t}`;if(this.config.enableCache){let i=this.getFromCache(e);if(i)return i}let r=await xc(t,this.config);return this.config.enableCache&&this.setInCache(e,r),r}async countPatterns(t,e){let r=`patterns:${t}:${e}`;if(this.config.enableCache){let n=this.getFromCache(r);if(n)return n}let i=this.countPatternsInternal(t,e);return this.config.enableCache&&this.setInCache(r,i),i}checkTools(){let t=Ac(),e=Pc(process.cwd());return[...t,...e]}clearCache(){this.cache.clear(),this.cacheHits=0,this.cacheMisses=0}getCacheStats(){return{hits:this.cacheHits,misses:this.cacheMisses,size:this.cache.size}}getFromCache(t){let e=this.cache.get(t);return e&&Date.now()-e.timestamp<this.config.cacheTTL?(this.cacheHits++,e.data):(this.cacheMisses++,null)}setInCache(t,e){this.cache.set(t,{data:e,timestamp:Date.now()})}detectLanguage(t){return Bt(qt(t,"Cargo.toml"))?"rust":Bt(qt(t,"go.mod"))?"go":Bt(qt(t,"pyproject.toml"))||Bt(qt(t,"requirements.txt"))?"python":Bt(qt(t,"package.json"))?Bt(qt(t,"tsconfig.json"))?"typescript":"javascript":"unknown"}countPatternsInternal(t,e){let r={},i=0,n=0,s=0,a=0,o=this.getPatternsForLanguage(e);function c(l){if(!Bt(l))return;let d=_f(l,{withFileTypes:!0});for(let m of d){let h=qt(l,m.name);if(m.isDirectory()){if(["node_modules","dist","coverage","build",".git","vendor","target"].includes(m.name))continue;c(h)}else if(m.isFile()){let g=zf(m.name).toLowerCase();if(Bf(g,e)){let b=qf(h,o);(b.unwraps>0||b.unsafeBlocks>0||b.todoComments>0||b.consoleStatements>0)&&(r[h]=b,i+=b.unwraps,n+=b.unsafeBlocks,s+=b.todoComments,a+=b.consoleStatements)}}}}return c(t),{unwraps:i,unsafeBlocks:n,todoComments:s,consoleStatements:a,byFile:r}}getPatternsForLanguage(t){switch(t){case"rust":return{unwrap:/\.unwrap\s*\(/g,unsafe:/\bunsafe\s*\{/g,todo:/\/\/\s*(TODO|FIXME|HACK|XXX)[\s:]/gi,console:/\b(println!|print!|eprintln!|eprint!|dbg!)\s*\(/g};case"python":return{unwrap:null,unsafe:null,todo:/#\s*(TODO|FIXME|HACK|XXX)[\s:]/gi,console:/\b(print)\s*\(/g};case"go":return{unwrap:null,unsafe:/\bunsafe\./g,todo:/\/\/\s*(TODO|FIXME|HACK|XXX)[\s:]/gi,console:/\b(fmt\.Print|fmt\.Printf|fmt\.Println|log\.Print|log\.Printf|log\.Println)\s*\(/g};default:return{unwrap:null,unsafe:null,todo:/\/\/\s*(TODO|FIXME|HACK|XXX)[\s:]/gi,console:/\bconsole\.(log|debug|info|warn|error)\s*\(/g}}}};function Bf(u,t){switch(t){case"rust":return u===".rs";case"python":return[".py",".pyw"].includes(u);case"go":return u===".go";case"typescript":return[".ts",".tsx"].includes(u);case"javascript":return[".js",".jsx",".mjs",".cjs"].includes(u);default:return[".ts",".tsx",".js",".jsx",".py",".rs",".go"].includes(u)}}function qf(u,t){try{let e=Vf(u,"utf-8");return{unwraps:t.unwrap?(e.match(t.unwrap)||[]).length:0,unsafeBlocks:t.unsafe?(e.match(t.unsafe)||[]).length:0,todoComments:(e.match(t.todo)||[]).length,consoleStatements:(e.match(t.console)||[]).length}}catch{return{unwraps:0,unsafeBlocks:0,todoComments:0,consoleStatements:0}}}function Ld(u={}){return new kc(u)}M();A();se();Tt();A();Tt();A();Tt();A();Tt();A();se();Tt();A();var n1=300*1e3;Ge();Ge();M();Ge();var v1=R.create("temporal-compression");A();M();var S1=R.create("ruvector-server-client");Xm();import{Buffer as ty}from"buffer";var k1=ty.from("COGCNTNR","ascii");Ge();Ge();var iy={capacity:1e4,minCoherenceThreshold:.3,highTierThreshold:.8,mediumTierThreshold:.5,highTierWeight:3,mediumTierWeight:1.5,lowTierWeight:1},Dc=class{config;cusumDetector;buffer;totalSeen=0;totalAdmitted=0;totalRejected=0;totalEvicted=0;totalSampled=0;constructor(t){this.config={...iy,...t},this.cusumDetector=new Va({threshold:this.config.cusumConfig?.threshold??5,slack:this.config.cusumConfig?.slack??.5,resetOnAlarm:!1,warmupSamples:20}),this.buffer=[]}admit(t,e,r){this.totalSeen++;let i=this.getEffectiveThreshold();if(r<i)return this.totalRejected++,!1;let n=this.classifyTier(r),s={id:t,data:e,coherenceScore:r,tier:n,admittedAt:Date.now(),replayCount:0};if(this.buffer.length<this.config.capacity)return this.buffer.push(s),this.totalAdmitted++,!0;let a=Math.floor(Math.random()*this.totalAdmitted),o=this.getTierWeight(n),c=Math.floor(a/o);if(c<this.config.capacity){let l=this.selectEvictionTarget(c);return this.buffer[l]=s,this.totalEvicted++,this.totalAdmitted++,!0}return this.totalRejected++,!1}sample(t,e){if(this.buffer.length===0)return[];let r=e!==void 0?this.buffer.filter(a=>a.coherenceScore>=e):this.buffer;if(r.length===0)return[];if(t>=r.length){let a=[...r];for(let o of a)o.replayCount++;return this.totalSampled+=a.length,a}let i=r.map(a=>this.getTierWeight(a.tier)),n=[],s=new Set;for(;n.length<t&&s.size<r.length;){let a=0;for(let l=0;l<r.length;l++)s.has(l)||(a+=i[l]);if(a<=0)break;let o=Math.random()*a,c=-1;for(let l=0;l<r.length;l++)if(!s.has(l)&&(o-=i[l],o<=0)){c=l;break}if(c===-1){for(let l=0;l<r.length;l++)if(!s.has(l)){c=l;break}}c>=0&&(s.add(c),r[c].replayCount++,n.push(r[c]))}return this.totalSampled+=n.length,n}size(){return this.buffer.length}getStats(){let t={high:0,medium:0,low:0};for(let e of this.buffer)t[e.tier]++;return{size:this.buffer.length,capacity:this.config.capacity,totalAdmitted:this.totalAdmitted,totalRejected:this.totalRejected,totalEvicted:this.totalEvicted,tierCounts:t,totalSampled:this.totalSampled}}getByTier(t){return this.buffer.filter(e=>e.tier===t)}clear(){this.buffer.length=0,this.totalSeen=0,this.totalAdmitted=0,this.totalRejected=0,this.totalEvicted=0,this.totalSampled=0,this.cusumDetector.reset()}getCusumState(t){return this.cusumDetector.getState(t)}observeCoherence(t,e){return this.cusumDetector.update(t,e)}classifyTier(t){return t>=this.config.highTierThreshold?"high":t>=this.config.mediumTierThreshold?"medium":"low"}getTierWeight(t){switch(t){case"high":return this.config.highTierWeight;case"medium":return this.config.mediumTierWeight;case"low":return this.config.lowTierWeight}}getEffectiveThreshold(){let t=["retrieve","write","learn","act"],e=!1;for(let r of t)if(this.cusumDetector.getState(r).driftDetected){e=!0;break}return e?Math.min(this.config.minCoherenceThreshold*1.5,.9):this.config.minCoherenceThreshold}selectEvictionTarget(t){let e=Math.min(10,this.buffer.length),r=Math.max(0,t-Math.floor(e/2)),i=Math.min(this.buffer.length,r+e),n=t,s=this.buffer[t].coherenceScore;for(let a=r;a<i;a++)this.buffer[a].coherenceScore<s&&(s=this.buffer[a].coherenceScore,n=a);return n}};se();var vr=R.create("code-intelligence/gnn");async function $d(u,t,e){try{for(let r of e)try{let i=await t.readFile(r);if(i.success&&i.value){let s={vector:await Ic(r,i.value),dimension:384,namespace:"code",text:i.value.slice(0,1e3),timestamp:Date.now(),quantization:"none",metadata:{path:r}};u.addEmbedding(s)}}catch(i){vr.error(`Failed to index ${r}:`,i instanceof Error?i:void 0)}vr.info(`Indexed ${e.length} code embeddings`)}catch(r){vr.error("Failed to index code embeddings:",r instanceof Error?r:void 0)}}async function Ic(u,t){let e=[],r=u.split(".").pop(),i=Hs(r||"");e.push(i%1e3/1e3),e.push(Math.min(1,t.length/1e4));let n=t.match(/function\s+\w+/g)||[],s=t.match(/class\s+\w+/g)||[];e.push(Math.min(1,(n.length+s.length)/50));let a=t.match(/import\s+.*from|require\s*\(/g)||[];e.push(Math.min(1,a.length/20));let o=t.match(/for\s*\(|while\s*\(/g)||[],c=t.match(/if\s*\(/g)||[];e.push(Math.min(1,(o.length+c.length)/30));let l=t.match(/\/\/.*|\/\*[\s\S]*?\*\//g)||[];e.push(Math.min(1,l.length/50));let d=Hs(t.slice(0,500));for(let m=e.length;m<384;m++)e.push(d*(m+1)%1e4/1e4);return e.slice(0,384)}async function Od(u,t){try{let r={vector:await Ic("query",t),dimension:384,namespace:"code",text:t,timestamp:Date.now(),quantization:"none"};return u.search(r,{limit:10,namespace:"code"}).map(n=>({file:n.metadata?.path??`file-${n.id}`,similarity:1-n.distance}))}catch(e){return vr.error("Failed to search with GNN:",e instanceof Error?e:void 0),[]}}async function Nd(u,t,e){try{for(let r of e.changedFiles){let i=await t.readFile(r);if(i.success&&i.value){let s={vector:await Ic(r,i.value),dimension:384,namespace:"code",text:i.value.slice(0,1e3),timestamp:Date.now(),quantization:"none",metadata:{path:r}},a=u.search(s,{limit:5,namespace:"code"});vr.info(`Found ${a.length} semantically similar files to ${r}`)}}}catch(r){vr.error("Failed to enhance impact analysis:",r instanceof Error?r:void 0)}}function Vd(u,t){let e=new Map,r=new Map;for(let i of u)e.set(i.file,i.score),r.set(i.file,i);for(let i of t){let n=e.get(i.file);n!==void 0?e.set(i.file,(n+i.similarity)/2):(e.set(i.file,i.similarity*.8),r.set(i.file,{file:i.file,snippet:"",score:i.similarity*.8,highlights:[]}))}return Array.from(r.values()).map(i=>({...i,score:e.get(i.file)??i.score})).sort((i,n)=>n.score-i.score).slice(0,20)}function Hs(u){let t=0;for(let e=0;e<u.length;e++)t=(t<<5)-t+u.charCodeAt(e),t=t|0;return Math.abs(t)}M();A();var ze=R.create("code-intelligence/hypergraph");async function _d(u,t,e){try{let r=await u.findUntestedFunctions();if(ze.info(`[CodeIntelligence] Found ${r.length} untested functions via hypergraph`),e){let i=I("code-intelligence.UntestedFunctionsFound","code-intelligence",{count:r.length,functions:r.slice(0,10).map(n=>({name:n.name,file:n.filePath,complexity:n.complexity}))});await t.publish(i)}return{success:!0,value:r}}catch(r){let i=y(r);return ze.error("Failed to find untested functions:"),p(i)}}async function zd(u,t,e,r){if(t.length===0)return{success:!0,value:[]};try{let i=await u.findImpactedTests(t);if(ze.info(`[CodeIntelligence] Found ${i.length} impacted tests for ${t.length} changed files via hypergraph`),r){let n=I("code-intelligence.ImpactedTestsFound","code-intelligence",{changedFiles:t,testCount:i.length,tests:i.slice(0,10).map(s=>({name:s.name,file:s.filePath}))});await e.publish(n)}return{success:!0,value:i}}catch(i){let n=y(i);return ze.error("Failed to find impacted tests:"),p(n)}}async function Bd(u,t,e,r){try{let i=await u.findCoverageGaps(t);if(ze.info(`[CodeIntelligence] Found ${i.length} coverage gaps (functions with <=${t}% coverage) via hypergraph`),r){let n=I("code-intelligence.CoverageGapsFound","code-intelligence",{maxCoverage:t,gapCount:i.length,gaps:i.slice(0,10).map(s=>({name:s.name,file:s.filePath,coverage:s.coverage,complexity:s.complexity}))});await e.publish(n)}return{success:!0,value:i}}catch(i){let n=y(i);return ze.error("Failed to find coverage gaps:"),p(n)}}async function qd(u,t,e,r,i){try{ze.info(`[CodeIntelligence] Building hypergraph from ${t.files.length} indexed files`);let n=await u.buildFromIndexResult(t);if(ze.info(`[CodeIntelligence] Hypergraph built: ${n.nodesCreated} nodes created, ${n.nodesUpdated} nodes updated, ${n.edgesCreated} edges created (${n.durationMs}ms)`),await e.set("hypergraph:build:latest",{timestamp:new Date().toISOString(),...n},{namespace:"code-intelligence",persist:!0}),i){let s=I("code-intelligence.HypergraphBuilt","code-intelligence",{nodesCreated:n.nodesCreated,nodesUpdated:n.nodesUpdated,edgesCreated:n.edgesCreated,durationMs:n.durationMs,errorCount:n.errors.length});await r.publish(s)}return{success:!0,value:n}}catch(n){let s=y(n);return ze.error("Failed to build hypergraph:"),p(s)}}async function Gd(u,t,e){try{let r=await u.findImpactedTests(t.changedFiles),i=new Set([...e.impactedTests,...r.map(a=>a.filePath||a.name)]),n=e.riskLevel;if(r.length>e.impactedTests.length){let a=e.directImpact.length+e.transitiveImpact.length;a>10&&i.size>20?n="critical":a>5&&i.size>10&&(n="high")}let s=[...e.recommendations];return r.length>0&&s.push(`Hypergraph analysis found ${r.length} additional test(s) to run`),{...e,impactedTests:Array.from(i),riskLevel:n,recommendations:s}}catch(r){return ze.error("Failed to enhance impact with hypergraph:",r instanceof Error?r:void 0),e}}M();var br=R.create("code-intelligence/consensus");async function Hd(u,t,e,r){let i=V({id:v(),type:"code-pattern-detection",confidence:t,description:`Verify code pattern: ${u.name} (${u.type}) at ${u.location}`,payload:u,detectedBy:"code-intelligence-coordinator",severity:t>.9?"high":"medium"});if(e.requiresConsensus(i)){let n=await e.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(br.info(`Code pattern '${u.name}' verified by consensus`),!0):(br.warn(`Code pattern '${u.name}' NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}async function jd(u,t,e,r){let i=V({id:v(),type:"impact-analysis",confidence:t,description:`Verify impact analysis: ${u.changedFiles.length} files, risk=${u.riskLevel}, ${u.impactedTests.length} tests`,payload:u,detectedBy:"code-intelligence-coordinator",severity:u.riskLevel==="critical"||u.riskLevel==="high"?"high":"medium"});if(e.requiresConsensus(i)){let n=await e.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(br.info(`Impact analysis verified by consensus (risk=${u.riskLevel})`),!0):(br.warn(`Impact analysis NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}async function Wd(u,t,e,r){let i=V({id:v(),type:"dependency-mapping",confidence:t,description:`Verify dependency: ${u.source} -> ${u.targets.length} targets (${u.type})`,payload:u,detectedBy:"code-intelligence-coordinator",severity:t>.85?"high":"medium"});if(e.requiresConsensus(i)){let n=await e.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(br.info("Dependency mapping verified by consensus"),!0):(br.warn(`Dependency mapping NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}var wy={maxConcurrentWorkflows:5,defaultTimeout:12e4,publishEvents:!0,enableIncrementalIndex:!0,enableGNN:!0,enableSONA:!0,enableMetricCollector:!0,enableHypergraph:!0,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},Z=R.create("code-intelligence"),zi=class extends Q{constructor(e,r,i,n={},s){let a={...wy,...n};super(e,"code-intelligence",a,{verifyFindingTypes:["code-pattern-detection","impact-analysis","dependency-mapping"]});this.memory=r;this.agentCoordinator=i;this.knowledgeGraph=new xt({memory:r,llmRouter:s}),this.semanticAnalyzer=new _t(r),this.impactAnalyzer=new Br(r,this.knowledgeGraph),this.fileReader=new Fe,this.productFactorsBridge=new Bs(e,r,{publishEvents:this.config.publishEvents})}memory;agentCoordinator;knowledgeGraph;semanticAnalyzer;impactAnalyzer;fileReader;gnnIndex;sonaEngine;rlInitialized=!1;metricCollector;hypergraph;hypergraphDb;productFactorsBridge;async onInitialize(){this.subscribeToEvents(),await this.loadWorkflowState(),(this.config.enableGNN||this.config.enableSONA)&&await this.initializeRLIntegrations(),this.config.enableMetricCollector&&(this.metricCollector=Ld({enableCache:!0,cacheTTL:3e5}),Z.info("MetricCollector initialized for real code metrics")),this.config.enableHypergraph&&await this.initializeHypergraph(),await this.productFactorsBridge.initialize()}async initializeHypergraph(){try{let{openDatabase:e}=await import("./safe-db-WL5Y7ZNS.js"),r=await import("fs"),i=await import("path"),{findProjectRoot:n}=await import("./unified-memory-7AS4LIEF.js"),s=n(),a=this.config.hypergraphDbPath||i.join(s,".agentic-qe","memory.db"),o=i.dirname(a);r.existsSync(o)||r.mkdirSync(o,{recursive:!0}),this.hypergraphDb=e(a),this.hypergraph=await ln({db:this.hypergraphDb,maxTraversalDepth:10,maxQueryResults:1e3,enableVectorSearch:this.config.enableGNN}),Z.info(`Hypergraph Engine initialized at ${a}`)}catch(e){let r=e instanceof Error?e.message:String(e);if(Z.warn(`Hypergraph Engine initialization failed (feature degraded): ${r}`),this.hypergraph=void 0,this.hypergraphDb=void 0,this.config.publishEvents){let i=I("code-intelligence.HypergraphDegraded","code-intelligence",{reason:r});this.eventBus.publish(i).catch(()=>{})}}}async initializeRLIntegrations(){try{if(this.config.enableGNN&&(ja(),this.gnnIndex=cn.getInstance("code-intelligence",{M:16,efConstruction:200,efSearch:50,dimension:384,metric:"cosine"}),this.gnnIndex.initializeIndex("code"),this.gnnIndex.initializeIndex("test")),this.config.enableSONA)try{this.sonaEngine=await pe({domain:"code-intelligence",loadOnInit:!0,autoSaveInterval:6e4,maxPatterns:1e4,minConfidence:.6}),Z.info("PersistentSONAEngine initialized for code pattern learning")}catch(e){Z.error("Failed to initialize PersistentSONAEngine:",e instanceof Error?e:void 0),this.sonaEngine=void 0}this.rlInitialized=!0}catch(e){throw Z.error("Failed to initialize RL integrations:",e instanceof Error?e:void 0),e}}async onDispose(){if(await this.saveWorkflowState(),this.gnnIndex&&cn.closeInstance("code-intelligence"),this.sonaEngine)try{await this.sonaEngine.close(),this.sonaEngine=void 0}catch(e){Z.error("Error closing SONA engine:",e instanceof Error?e:void 0)}if(this.hypergraphDb){try{this.hypergraphDb.close()}catch(e){Z.error("Error closing hypergraph database:",e instanceof Error?e:void 0)}this.hypergraphDb=void 0}this.hypergraph=void 0,await this.productFactorsBridge.dispose()}getActiveWorkflows(){return super.getActiveWorkflows()}async index(e){let r=v();try{if(this.startWorkflow(r,"index"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Z.warn("Topology degraded, using conservative strategy"),this.minCutMixin.shouldPauseOperations())return p(new Error("Indexing paused: topology is in critical state"));if(!this.agentCoordinator.canSpawn())return p(new Error("Agent limit reached, cannot spawn indexing agents"));let i=await this.spawnIndexerAgent(r,e);if(!i.success)return this.failWorkflow(r,i.error.message),p(i.error);this.addAgentToWorkflow(r,i.value),this.updateWorkflowProgress(r,10);let n=await this.knowledgeGraph.index(e);if(n.success){if(this.updateWorkflowProgress(r,40),this.config.enableGNN&&this.gnnIndex&&e.paths.length>0&&await this.indexCodeEmbeddings(e.paths),this.updateWorkflowProgress(r,60),this.config.enableMetricCollector&&this.metricCollector&&e.paths.length>0){let s=this.getProjectRootFromPaths(e.paths);s&&await this.collectProjectMetrics(s)}if(this.updateWorkflowProgress(r,70),e.paths.length>0&&await this.indexForSemanticSearch(e.paths),this.updateWorkflowProgress(r,85),this.config.enableHypergraph&&this.hypergraph&&e.paths.length>0)try{let s=await this.buildCodeIndexResultFromPaths(e.paths);if(s.files.length>0){await this.hypergraph.buildFromIndexResult(s),Z.info(`Hypergraph rebuilt from ${s.files.length} indexed files`);try{let a=await this.hypergraph.synthesizeTestCoverage();(a.testsTagged>0||a.coversCreated>0)&&Z.info(`Test coverage synthesized: tests_tagged=${a.testsTagged} covers_created=${a.coversCreated}`)}catch(a){Z.warn(`Test coverage synthesis skipped: ${a instanceof Error?a.message:a}`)}}}catch(s){Z.warn(`Hypergraph rebuild skipped: ${s instanceof Error?s.message:s}`)}this.updateWorkflowProgress(r,100),this.completeWorkflow(r),this.config.publishEvents&&await this.publishKnowledgeGraphUpdated(n.value)}else this.failWorkflow(r,n.error.message);return await this.agentCoordinator.stop(i.value),n}catch(i){let n=y(i);return this.failWorkflow(r,n.message),p(n)}}async search(e){let r=v();try{this.startWorkflow(r,"search");let i=await this.spawnSearchAgent(r,e);if(i.success&&this.addAgentToWorkflow(r,i.value),this.config.enableSONA&&this.sonaEngine){let a=await this.adaptSearchPattern(e);a.success&&a.pattern&&Z.info(`Adapted search pattern with ${a.similarity.toFixed(3)} similarity`)}let n=[];this.config.enableGNN&&this.gnnIndex&&(n=await this.searchCodeWithGNN(e));let s=await this.semanticAnalyzer.search(e);return s.success?(n.length>0&&(s.value.results=this.mergeSearchResults(s.value.results,n)),this.completeWorkflow(r),this.config.publishEvents&&await this.publishSemanticSearchCompleted(e,s.value)):this.failWorkflow(r,s.error.message),i.success&&await this.agentCoordinator.stop(i.value),s}catch(i){let n=y(i);return this.failWorkflow(r,n.message),p(n)}}async analyzeImpact(e){let r=v();try{if(this.startWorkflow(r,"impact"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Z.warn("Topology degraded, using conservative impact analysis"),this.minCutMixin.shouldPauseOperations())return p(new Error("Impact analysis paused: topology is in critical state"));let i=await this.spawnImpactAnalyzerAgent(r,e);if(!i.success)return this.failWorkflow(r,i.error.message),p(i.error);this.addAgentToWorkflow(r,i.value),this.updateWorkflowProgress(r,20),this.config.enableGNN&&this.gnnIndex&&await this.enhanceImpactAnalysisWithGNN(e);let n=await this.impactAnalyzer.analyzeImpact(e);if(n.success){this.updateWorkflowProgress(r,80);let s=n.value;return this.config.enableHypergraph&&this.hypergraph&&(s=await this.enhanceImpactWithHypergraph(e,n.value)),this.updateWorkflowProgress(r,100),this.completeWorkflow(r),this.config.enableSONA&&this.sonaEngine&&await this.storeImpactPattern(e,s),this.config.publishEvents&&await this.publishImpactAnalysisCompleted(e,s),{success:!0,value:s}}else this.failWorkflow(r,n.error.message);return await this.agentCoordinator.stop(i.value),n}catch(i){let n=y(i);return this.failWorkflow(r,n.message),p(n)}}async mapDependencies(e){let r=v();try{this.startWorkflow(r,"dependency");let i=await this.knowledgeGraph.mapDependencies(e);return i.success?this.completeWorkflow(r):this.failWorkflow(r,i.error.message),i}catch(i){let n=y(i);return this.failWorkflow(r,n.message),p(n)}}async queryKG(e){let r=v();try{this.startWorkflow(r,"query");let i=await this.knowledgeGraph.query(e);return i.success?this.completeWorkflow(r):this.failWorkflow(r,i.error.message),i}catch(i){let n=y(i);return this.failWorkflow(r,n.message),p(n)}}async indexCodeEmbeddings(e){!this.gnnIndex||!this.rlInitialized||await $d(this.gnnIndex,this.fileReader,e)}async searchCodeWithGNN(e){return!this.gnnIndex||!this.rlInitialized?[]:Od(this.gnnIndex,e.query)}async enhanceImpactAnalysisWithGNN(e){!this.gnnIndex||!this.rlInitialized||await Nd(this.gnnIndex,this.fileReader,e)}async adaptSearchPattern(e){if(!this.sonaEngine||!this.rlInitialized)return{success:!1,pattern:null,similarity:0};try{let r=Array.isArray(e.filters)?e.filters.find(s=>s.field==="language")?.value:void 0,i={id:`search-${e.type}`,features:[e.query.length,e.type==="semantic"?1:0,e.type==="exact"?1:0,r==="typescript"?1:0,r==="javascript"?1:0]},n=await this.sonaEngine.adaptPattern(i,"coverage-optimization","code-intelligence");return{success:n.success,pattern:n.pattern,similarity:n.similarity}}catch(r){return Z.error("Failed to adapt search pattern:",r instanceof Error?r:void 0),{success:!1,pattern:null,similarity:0}}}async storeImpactPattern(e,r){if(!(!this.sonaEngine||!this.rlInitialized))try{let i={id:`impact-${e.changedFiles.join(",")}`,features:[e.changedFiles.length,e.depth||1,r.directImpact.length,r.transitiveImpact.length,r.impactedTests.length,r.riskLevel==="high"?1:r.riskLevel==="medium"?.5:0]},n={type:"analyze-impact",value:r.riskLevel},s={reward:r.riskLevel==="high"?.8:r.riskLevel==="medium"?.5:.3,success:r.impactedTests.length>0,quality:(r.directImpact.length+r.transitiveImpact.length)/100},a=this.sonaEngine.createPattern(i,n,s,"coverage-optimization","code-intelligence",{changedFiles:e.changedFiles,impactCount:r.directImpact.length+r.transitiveImpact.length,testImpactCount:r.impactedTests.length});Z.info(`Stored impact pattern ${a.id}`)}catch(i){Z.error("Failed to store impact pattern:",i instanceof Error?i:void 0)}}mergeSearchResults(e,r){return Vd(e,r)}hashCode(e){return Hs(e)}async spawnIndexerAgent(e,r){let i={name:`kg-indexer-${e.slice(0,8)}`,domain:"code-intelligence",type:"analyzer",capabilities:["indexing","ast-parsing","graph-building"],config:{workflowId:e,paths:r.paths,incremental:r.incremental}};return this.agentCoordinator.spawn(i)}async spawnSearchAgent(e,r){let i={name:`semantic-search-${e.slice(0,8)}`,domain:"code-intelligence",type:"analyzer",capabilities:["semantic-search","vector-similarity",r.type],config:{workflowId:e,query:r.query,type:r.type}};return this.agentCoordinator.spawn(i)}async spawnImpactAnalyzerAgent(e,r){let i={name:`impact-analyzer-${e.slice(0,8)}`,domain:"code-intelligence",type:"analyzer",capabilities:["impact-analysis","dependency-traversal","risk-assessment"],config:{workflowId:e,changedFiles:r.changedFiles,depth:r.depth}};return this.agentCoordinator.spawn(i)}async publishKnowledgeGraphUpdated(e){let r={nodes:e.nodesCreated,edges:e.edgesCreated,filesIndexed:e.filesIndexed,duration:e.duration},i=I(rt.KnowledgeGraphUpdated,"code-intelligence",r);await this.eventBus.publish(i)}async publishImpactAnalysisCompleted(e,r){let i={analysisId:v(),changedFiles:e.changedFiles,impactedFiles:[...r.directImpact.map(s=>s.file),...r.transitiveImpact.map(s=>s.file)],impactedTests:r.impactedTests,riskLevel:r.riskLevel},n=I(rt.ImpactAnalysisCompleted,"code-intelligence",i);await this.eventBus.publish(n)}async publishSemanticSearchCompleted(e,r){let i=I(rt.SemanticSearchCompleted,"code-intelligence",{query:e.query,type:e.type,resultCount:r.total,searchTime:r.searchTime});await this.eventBus.publish(i)}subscribeToEvents(){this.eventBus.subscribe("test-execution.TestRunCompleted",this.handleTestRunCompleted.bind(this)),this.eventBus.subscribe("source-control.FilesChanged",this.handleFilesChanged.bind(this))}async handleTestRunCompleted(e){let r=e.payload;await this.memory.set(`code-intelligence:test-correlation:${r.runId}`,r,{namespace:"code-intelligence",ttl:86400})}async handleFilesChanged(e){if(!this.config.enableIncrementalIndex)return;let r=e.payload;r.files&&r.files.length>0&&await this.memory.set(`code-intelligence:pending-index:${Date.now()}`,{files:r.files,timestamp:new Date().toISOString()},{namespace:"code-intelligence",ttl:3600})}async indexForSemanticSearch(e){let r=e.slice(0,100);for(let i of r)try{let n=await this.fileReader.readFile(i);n.success&&n.value&&await this.semanticAnalyzer.indexCode(i,n.value)}catch{}}async loadWorkflowState(){let e=await this.memory.get("code-intelligence:coordinator:workflows");if(e)for(let r of e)r.status==="running"&&(r.status="failed",r.error="Coordinator restarted",r.completedAt=new Date),this.workflows.set(r.id,r)}async saveWorkflowState(){let e=Array.from(this.workflows.values());await this.memory.set("code-intelligence:coordinator:workflows",e,{namespace:"code-intelligence",persist:!0})}async generateC4Diagrams(e,r){let i=v();try{this.startWorkflow(i,"query");let n={projectPath:e,detectExternalSystems:r?.detectExternalSystems??!0,analyzeComponents:r?.analyzeComponents??!0,analyzeCoupling:r?.analyzeCoupling??!0,includeContext:r?.includeContext??!0,includeContainer:r?.includeContainer??!0,includeComponent:r?.includeComponent??!0,includeDependency:r?.includeDependency??!1,excludePatterns:r?.excludePatterns};this.updateWorkflowProgress(i,20);let s=await this.productFactorsBridge.requestC4Diagrams(n);return s.success?(this.updateWorkflowProgress(i,80),await this.storeC4DiagramsInMemory(e,s.value),this.updateWorkflowProgress(i,100),this.completeWorkflow(i),Z.info(`[CodeIntelligenceCoordinator] C4 diagrams generated for ${e}: ${s.value.components.length} components, ${s.value.externalSystems.length} external systems`)):this.failWorkflow(i,s.error.message),s}catch(n){let s=y(n);return this.failWorkflow(i,s.message),p(s)}}getProductFactorsBridge(){return this.productFactorsBridge}async storeC4DiagramsInMemory(e,r){let i=`c4-diagrams:latest:${this.hashCode(e)}`;await this.memory.set(i,r,{namespace:"code-intelligence",persist:!0,ttl:36e5}),await this.memory.set(`c4-components:${this.hashCode(e)}`,r.components,{namespace:"code-intelligence",ttl:36e5}),await this.memory.set(`c4-external-systems:${this.hashCode(e)}`,r.externalSystems,{namespace:"code-intelligence",ttl:36e5})}async collectProjectMetrics(e){if(!this.config.enableMetricCollector||!this.metricCollector)return p(new Error("MetricCollector is not enabled"));try{Z.info(`Collecting real metrics for ${e}`);let r=await this.metricCollector.collectAll(e),i=r.toolsUsed.length>0?r.toolsUsed.join(", "):r.loc.source==="node-native"?"node-native":"fallback";if(Z.info(`[CodeIntelligence] Real metrics collected: ${r.loc.total} LOC, ${r.tests.total} tests, tools: ${i}`),r.loc.source==="node-native"&&Z.info("[CodeIntelligence] Using Node.js-native line counter (no cloc/tokei needed)"),await this.storeProjectMetricsInMemory(e,r),this.config.publishEvents){let n=I("code-intelligence.MetricsCollected","code-intelligence",{projectPath:e,loc:r.loc.total,tests:r.tests.total,toolsUsed:r.toolsUsed});await this.eventBus.publish(n)}return{success:!0,value:r}}catch(r){let i=y(r);return Z.error("Failed to collect metrics:"),p(i)}}async storeProjectMetricsInMemory(e,r){let i=`project-metrics:latest:${this.hashCode(e)}`;await this.memory.set(i,r,{namespace:"code-intelligence",persist:!0,ttl:3e5}),await this.memory.set(`loc-metrics:${this.hashCode(e)}`,r.loc,{namespace:"code-intelligence",ttl:3e5}),await this.memory.set(`test-metrics:${this.hashCode(e)}`,r.tests,{namespace:"code-intelligence",ttl:3e5})}getMetricCollector(){return this.metricCollector}getProjectRootFromPaths(e){if(e.length===0)return null;let r=e[0],i=r.split("/"),n="";for(let a of i){n=n?`${n}/${a}`:a;let o=["package.json","Cargo.toml","go.mod","pyproject.toml",".git"];for(let c of o)try{let l=`${n}/${c}`;if(Fa("fs").existsSync(l))return n}catch{}}let s=r.lastIndexOf("/");return s>0?r.substring(0,s):r}isHypergraphEnabled(){return this.config.enableHypergraph&&this.hypergraph!==void 0}async findUntestedFunctions(){return this.hypergraph?_d(this.hypergraph,this.eventBus,this.config.publishEvents):p(new Error("Hypergraph is not enabled or not initialized"))}async findImpactedTestsFromHypergraph(e){return this.hypergraph?zd(this.hypergraph,e,this.eventBus,this.config.publishEvents):p(new Error("Hypergraph is not enabled or not initialized"))}async findCoverageGapsFromHypergraph(e=50){return this.hypergraph?Bd(this.hypergraph,e,this.eventBus,this.config.publishEvents):p(new Error("Hypergraph is not enabled or not initialized"))}async buildHypergraphFromIndex(e){return this.hypergraph?qd(this.hypergraph,e,this.memory,this.eventBus,this.config.publishEvents):p(new Error("Hypergraph is not enabled or not initialized"))}getHypergraph(){return this.hypergraph}async enhanceImpactWithHypergraph(e,r){return this.hypergraph?Gd(this.hypergraph,e,r):r}async buildCodeIndexResultFromPaths(e){let{extractCodeIndex:r}=await import("./code-index-extractor-2PCISUOW.js");return r(e)}async verifyCodePatternDetection(e,r){return Hd(e,r,this.consensusMixin,this.domainName)}async verifyImpactAnalysis(e,r){return jd(e,r,this.consensusMixin,this.domainName)}async verifyDependencyMapping(e,r){return Wd(e,r,this.consensusMixin,this.domainName)}};A();var js=class extends j{constructor(e,r,i,n={},s){super(e,r);this.agentCoordinator=i;this.llmRouter=s;this.pluginConfig=n}agentCoordinator;llmRouter;coordinator=null;knowledgeGraph=null;semanticAnalyzer=null;impactAnalyzer=null;pluginConfig;get name(){return"code-intelligence"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{index:this.index.bind(this),search:this.search.bind(this),analyzeImpact:this.analyzeImpact.bind(this),mapDependencies:this.mapDependencies.bind(this),getDependencies:this.mapDependencies.bind(this),queryKG:this.queryKG.bind(this),getMetrics:this.getMetrics.bind(this),getCoordinator:()=>this.coordinator,getKnowledgeGraph:()=>this.knowledgeGraph,getSemanticAnalyzer:()=>this.semanticAnalyzer,getImpactAnalyzer:()=>this.impactAnalyzer}}getTaskHandlers(){return new Map([["index",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.paths;if(!r||r.length===0)return p(new Error("Invalid index payload: missing paths"));let i=e.language?[e.language]:e.languages;return this.coordinator.index({paths:r,languages:i})}],["search",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.query;return r?this.coordinator.search({query:r,type:e.type??"semantic",limit:e.limit}):p(new Error("Invalid search payload: missing query"))}],["analyze-impact",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.changedFiles;return!r||r.length===0?p(new Error("Invalid analyze-impact payload: missing changedFiles")):this.coordinator.analyzeImpact({changedFiles:r})}],["query-dependencies",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.file,n=e.files??(r?[r]:void 0);return!n||n.length===0?p(new Error("Invalid query-dependencies payload: missing file or files")):this.coordinator.mapDependencies({files:n,direction:e.direction??"both",depth:e.depth})}]])}async onInitialize(){this.knowledgeGraph=new xt({memory:this.memory,llmRouter:this.llmRouter},this.pluginConfig.knowledgeGraph),this.semanticAnalyzer=new _t(this.memory,this.pluginConfig.semanticAnalyzer),this.impactAnalyzer=new Br(this.memory,this.knowledgeGraph,this.pluginConfig.impactAnalyzer),this.coordinator=new zi(this.eventBus,this.memory,this.agentCoordinator,this.pluginConfig.coordinator,this.llmRouter),await this.coordinator.initialize(),this.updateHealth({status:"idle",agents:{total:0,active:0,idle:0,failed:0},lastActivity:new Date,errors:[]})}async onDispose(){this.coordinator&&await this.coordinator.dispose(),this.coordinator=null,this.knowledgeGraph=null,this.semanticAnalyzer=null,this.impactAnalyzer=null}subscribeToEvents(){this.eventBus.subscribe("test-generation.TestGenerated",this.handleTestGenerated.bind(this)),this.eventBus.subscribe("coverage-analysis.CoverageGapDetected",this.handleCoverageGap.bind(this)),this.eventBus.subscribe("defect-intelligence.DefectPredicted",this.handleDefectPredicted.bind(this))}async onEvent(e){switch(this.updateHealth({lastActivity:new Date}),e.type){case"test-generation.TestGenerated":await this.handleTestGenerated(e);break;case"coverage-analysis.CoverageGapDetected":await this.handleCoverageGap(e);break;case"defect-intelligence.DefectPredicted":await this.handleDefectPredicted(e);break;default:break}}async index(e){this.ensureInitialized();try{let r=await this.coordinator.index(e);return r.success?this.trackSuccessfulOperation("index",r.value):this.trackFailedOperation("index",r.error),r}catch(r){return this.handleError(r)}}async search(e){this.ensureInitialized();try{let r=await this.coordinator.search(e);return r.success?this.trackSuccessfulOperation("search",r.value):this.trackFailedOperation("search",r.error),r}catch(r){return this.handleError(r)}}async analyzeImpact(e){this.ensureInitialized();try{let r=await this.coordinator.analyzeImpact(e);return r.success?this.trackSuccessfulOperation("impact",r.value):this.trackFailedOperation("impact",r.error),r}catch(r){return this.handleError(r)}}async mapDependencies(e){this.ensureInitialized();try{let r=await this.coordinator.mapDependencies(e);return r.success?this.trackSuccessfulOperation("dependency",r.value):this.trackFailedOperation("dependency",r.error),r}catch(r){return this.handleError(r)}}async queryKG(e){this.ensureInitialized();try{let r=await this.coordinator.queryKG(e);return r.success?this.trackSuccessfulOperation("query",r.value):this.trackFailedOperation("query",r.error),r}catch(r){return this.handleError(r)}}async getMetrics(){this.ensureInitialized();try{let e=this.getHealth();return{success:!0,value:{indexed:e.agents.total,queries:e.agents.idle,impacts:e.agents.active}}}catch(e){return this.handleError(e)}}async handleTestGenerated(e){let r=e.payload;await this.memory.set(`code-intelligence:test-mapping:${r.testId}`,{testFile:r.testFile,sourceFile:r.sourceFile,generatedAt:new Date().toISOString()},{namespace:"code-intelligence",ttl:86400*30})}async handleCoverageGap(e){let r=e.payload;await this.memory.set(`code-intelligence:coverage-gap:${r.gapId}`,r,{namespace:"code-intelligence",ttl:86400*7})}async handleDefectPredicted(e){let r=e.payload;await this.memory.set(`code-intelligence:defect-prediction:${r.predictionId}`,r,{namespace:"code-intelligence",ttl:86400*7})}ensureInitialized(){if(!this._initialized)throw new Error("CodeIntelligencePlugin is not initialized");if(!this.coordinator||!this.knowledgeGraph||!this.semanticAnalyzer||!this.impactAnalyzer)throw new Error("CodeIntelligencePlugin services are not available")}handleError(e){let r=y(e),i=this.getHealth();return this.updateHealth({errors:[...i.errors.slice(-9),r.message],status:i.errors.length>=5?"degraded":i.status}),{success:!1,error:r}}trackSuccessfulOperation(e,r){let i=this.getHealth();this.updateHealth({agents:{...i.agents,total:i.agents.total+1,idle:i.agents.idle+1},lastActivity:new Date})}trackFailedOperation(e,r){let i=this.getHealth();this.updateHealth({agents:{...i.agents,failed:i.agents.failed+1},errors:[...i.errors.slice(-9),r.message]})}};function Mc(u,t,e,r,i){return new js(u,t,e,r,i)}M();A();var Ws={defaultRuleSets:["owasp-top-10","cwe-sans-25"],maxConcurrentScans:4,timeout:3e5,enableFalsePositiveDetection:!0,dastMaxDepth:5,dastActiveScanning:!1,enableLLMAnalysis:!0,llmModelTier:4,enableSemgrep:!0};M();var Fc=[{id:"sqli-string-concat",pattern:/query\s*\(\s*['"`].*\+.*['"`]\s*\)/g,category:"injection",severity:"critical",title:"SQL Injection via String Concatenation",description:"SQL query constructed using string concatenation with potentially untrusted input",owaspId:"A03:2021",cweId:"CWE-89",remediation:"Use parameterized queries or prepared statements instead of string concatenation",fixExample:'db.query("SELECT * FROM users WHERE id = $1", [userId])'},{id:"sqli-template-literal",pattern:/execute\s*\(\s*`[^`]*\$\{[^}]+\}[^`]*`\s*\)/g,category:"injection",severity:"critical",title:"SQL Injection via Template Literal",description:"SQL query constructed using template literals with embedded expressions",owaspId:"A03:2021",cweId:"CWE-89",remediation:"Use parameterized queries instead of template literals for SQL",fixExample:'db.execute("DELETE FROM users WHERE id = ?", [userId])'},{id:"sqli-raw-query",pattern:/\.raw\s*\(\s*['"`].*\+|\.raw\s*\(\s*`[^`]*\$\{/g,category:"injection",severity:"high",title:"SQL Injection via Raw Query",description:"Raw SQL query with potential user input interpolation",owaspId:"A03:2021",cweId:"CWE-89",remediation:"Avoid raw queries with user input; use ORM methods or parameterized queries"},{id:"sqli-exec",pattern:/exec(?:ute)?(?:Sql|Query)?\s*\([^)]*\+[^)]*\)/gi,category:"injection",severity:"critical",title:"SQL Injection via Dynamic Execution",description:"Dynamic SQL execution with string concatenation detected",owaspId:"A03:2021",cweId:"CWE-89",remediation:"Never concatenate user input into SQL queries"}],Lc=[{id:"xss-innerhtml",pattern:/\.innerHTML\s*=\s*[^'"`;\n]+/g,category:"xss",severity:"high",title:"XSS via innerHTML Assignment",description:"Direct innerHTML assignment with potentially unsanitized content",owaspId:"A03:2021",cweId:"CWE-79",remediation:"Use textContent for text, or sanitize HTML with DOMPurify before innerHTML assignment",fixExample:"element.textContent = userInput; // or DOMPurify.sanitize(userInput)"},{id:"xss-document-write",pattern:/document\.write\s*\([^)]+\)/g,category:"xss",severity:"high",title:"XSS via document.write",description:"document.write() can execute scripts from untrusted data",owaspId:"A03:2021",cweId:"CWE-79",remediation:"Avoid document.write(); use DOM manipulation methods instead",fixExample:"document.body.appendChild(document.createTextNode(text))"},{id:"xss-dangerously-set",pattern:/dangerouslySetInnerHTML\s*=\s*\{/g,category:"xss",severity:"medium",title:"React dangerouslySetInnerHTML Usage",description:"dangerouslySetInnerHTML bypasses React XSS protections",owaspId:"A03:2021",cweId:"CWE-79",remediation:"Sanitize HTML content with DOMPurify before using dangerouslySetInnerHTML",fixExample:"dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(content) }}"},{id:"xss-eval",pattern:/eval\s*\([^)]+\)/g,category:"xss",severity:"critical",title:"Code Injection via eval()",description:"eval() executes arbitrary code and is a major security risk",owaspId:"A03:2021",cweId:"CWE-95",remediation:"Never use eval(); use JSON.parse() for JSON data or safer alternatives",fixExample:"JSON.parse(jsonString) // instead of eval(jsonString)"},{id:"xss-new-function",pattern:/new\s+Function\s*\([^)]+\)/g,category:"xss",severity:"critical",title:"Code Injection via Function Constructor",description:"Function constructor can execute arbitrary code like eval()",owaspId:"A03:2021",cweId:"CWE-95",remediation:"Avoid the Function constructor; use predefined functions instead"},{id:"xss-outerhtml",pattern:/\.outerHTML\s*=\s*[^'"`;\n]+/g,category:"xss",severity:"high",title:"XSS via outerHTML Assignment",description:"Direct outerHTML assignment with potentially unsanitized content",owaspId:"A03:2021",cweId:"CWE-79",remediation:"Sanitize content before outerHTML assignment"}],$c=[{id:"secret-aws-access-key",pattern:/['"`]AKIA[0-9A-Z]{16}['"`]/g,category:"sensitive-data",severity:"critical",title:"AWS Access Key Detected",description:"Hardcoded AWS Access Key ID found in source code",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Use environment variables or AWS Secrets Manager for credentials",fixExample:"const accessKey = process.env.AWS_ACCESS_KEY_ID"},{id:"secret-aws-secret-key",pattern:/['"`][A-Za-z0-9/+=]{40}['"`]/g,category:"sensitive-data",severity:"critical",title:"Potential AWS Secret Key Detected",description:"Potential hardcoded AWS Secret Access Key found",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Store secrets in environment variables or secrets manager"},{id:"secret-openai-key",pattern:/['"`]sk-[a-zA-Z0-9]{48,}['"`]/g,category:"sensitive-data",severity:"critical",title:"OpenAI API Key Detected",description:"Hardcoded OpenAI API key found in source code",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Use environment variables for API keys",fixExample:"const apiKey = process.env.OPENAI_API_KEY"},{id:"secret-generic-password",pattern:/password\s*[:=]\s*['"`][^'"`]{4,}['"`]/gi,category:"sensitive-data",severity:"high",title:"Hardcoded Password Detected",description:"Hardcoded password found in source code",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Never hardcode passwords; use environment variables or secrets manager",fixExample:"const password = process.env.DB_PASSWORD"},{id:"secret-api-key",pattern:/api[_-]?key\s*[:=]\s*['"`][a-zA-Z0-9_\-]{16,}['"`]/gi,category:"sensitive-data",severity:"high",title:"Hardcoded API Key Detected",description:"Hardcoded API key found in source code",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Use environment variables for API keys",fixExample:"const apiKey = process.env.API_KEY"},{id:"secret-jwt",pattern:/['"`]eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+['"`]/g,category:"sensitive-data",severity:"high",title:"Hardcoded JWT Token Detected",description:"Hardcoded JWT token found in source code",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Generate JWT tokens dynamically; never hardcode them"},{id:"secret-private-key",pattern:/-----BEGIN\s+(RSA|EC|OPENSSH|DSA)?\s*PRIVATE\s+KEY-----/g,category:"sensitive-data",severity:"critical",title:"Private Key Detected",description:"Private key found in source code",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Store private keys in secure key management systems, not in code"},{id:"secret-github-token",pattern:/['"`]ghp_[a-zA-Z0-9]{36}['"`]|['"`]github_pat_[a-zA-Z0-9]{22}_[a-zA-Z0-9]{59}['"`]/g,category:"sensitive-data",severity:"critical",title:"GitHub Token Detected",description:"Hardcoded GitHub personal access token found",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Use environment variables or GitHub Actions secrets"},{id:"secret-slack-token",pattern:/['"`]xox[baprs]-[0-9]{10,13}-[0-9]{10,13}[a-zA-Z0-9-]*['"`]/g,category:"sensitive-data",severity:"high",title:"Slack Token Detected",description:"Hardcoded Slack token found in source code",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Use environment variables for Slack tokens"},{id:"secret-generic-assignment",pattern:/\b\w*(?:SECRET|secret)(?:_KEY|_key|Key)?\s*[:=]\s*['"`][^'"`]{4,}['"`]/g,category:"sensitive-data",severity:"high",title:"Generic Secret Assignment Detected",description:"Hardcoded secret assignment (SECRET_KEY, JWT_SECRET, APP_SECRET, etc.) found in source code",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Use environment variables or a secrets manager instead of hardcoding secrets",fixExample:"const secretKey = process.env.SECRET_KEY"}],Oc=[{id:"path-traversal-readfile",pattern:/(?:readFile|readFileSync)\s*\([^)]*\+/g,category:"access-control",severity:"high",title:"Path Traversal via File Read",description:"File read operation with concatenated path may allow directory traversal",owaspId:"A01:2021",cweId:"CWE-22",remediation:"Validate and sanitize file paths; use path.resolve() and check against base directory",fixExample:"const safePath = path.resolve(baseDir, path.basename(userInput))"},{id:"path-traversal-pattern",pattern:/\.\.\/.*\.\.\//g,category:"access-control",severity:"medium",title:"Path Traversal Pattern Detected",description:"Suspicious path traversal pattern (../) found in code",owaspId:"A01:2021",cweId:"CWE-22",remediation:"Validate paths and ensure they resolve within expected directories"},{id:"path-traversal-writefile",pattern:/(?:writeFile|writeFileSync)\s*\([^)]*\+/g,category:"access-control",severity:"high",title:"Path Traversal via File Write",description:"File write operation with concatenated path may allow directory traversal",owaspId:"A01:2021",cweId:"CWE-22",remediation:"Validate file paths before writing; ensure path is within allowed directory"},{id:"path-traversal-createstream",pattern:/createReadStream\s*\([^)]*\+/g,category:"access-control",severity:"high",title:"Path Traversal via Stream",description:"Stream creation with concatenated path may allow directory traversal",owaspId:"A01:2021",cweId:"CWE-22",remediation:"Validate and sanitize file paths before creating streams"}],Nc=[{id:"cmd-injection-exec",pattern:/exec\s*\([^)]*\+[^)]*\)|exec\s*\(\s*`[^`]*\$\{/g,category:"injection",severity:"critical",title:"Command Injection via exec()",description:"Shell command execution with unsanitized input",owaspId:"A03:2021",cweId:"CWE-78",remediation:"Use execFile() with argument array instead of exec() with string concatenation",fixExample:'execFile("command", [arg1, arg2], callback)'},{id:"cmd-injection-spawn",pattern:/spawn\s*\(\s*[^,]+\+|spawn\s*\(\s*`[^`]*\$\{/g,category:"injection",severity:"critical",title:"Command Injection via spawn()",description:"Process spawn with potentially unsanitized command",owaspId:"A03:2021",cweId:"CWE-78",remediation:"Use spawn with command and args array; validate inputs",fixExample:'spawn("command", [sanitizedArg1, sanitizedArg2])'},{id:"cmd-injection-shell-true",pattern:/spawn\s*\([^)]+,\s*\{[^}]*shell\s*:\s*true/g,category:"injection",severity:"high",title:"Dangerous Shell Option in spawn()",description:"spawn() with shell: true can enable command injection",owaspId:"A03:2021",cweId:"CWE-78",remediation:"Avoid shell: true option; use direct command execution"}],Vc=[{id:"misc-cors-wildcard",pattern:/cors\s*\(\s*\{[^}]*origin\s*:\s*['"]\*['"]/gi,category:"security-misconfiguration",severity:"medium",title:"Permissive CORS Configuration",description:"CORS allows all origins (*) which may expose sensitive data",owaspId:"A05:2021",cweId:"CWE-942",remediation:"Restrict CORS to specific trusted origins",fixExample:'cors({ origin: ["https://trusted-domain.com"] })'},{id:"misc-debug-enabled",pattern:/debug\s*[:=]\s*true|DEBUG\s*[:=]\s*['"]?true['"]?/gi,category:"security-misconfiguration",severity:"low",title:"Debug Mode Enabled",description:"Debug mode may expose sensitive information in production",owaspId:"A05:2021",cweId:"CWE-489",remediation:"Disable debug mode in production environments"},{id:"misc-ssl-disabled",pattern:/rejectUnauthorized\s*:\s*false|NODE_TLS_REJECT_UNAUTHORIZED\s*=\s*['"]?0['"]?/g,category:"security-misconfiguration",severity:"high",title:"TLS Certificate Validation Disabled",description:"Disabling TLS certificate validation exposes to MITM attacks",owaspId:"A05:2021",cweId:"CWE-295",remediation:"Always enable TLS certificate validation in production"},{id:"misc-helmet-missing",pattern:/app\.use\s*\(\s*express\s*\(\s*\)\s*\)/g,category:"security-misconfiguration",severity:"low",title:"Express App Without Security Headers",description:"Express app initialized without helmet or security headers",owaspId:"A05:2021",cweId:"CWE-693",remediation:"Use helmet middleware for security headers",fixExample:"app.use(helmet())"}],_c=[{id:"deser-yaml-load",pattern:/yaml\.load\s*\([^)]+\)/g,category:"insecure-deserialization",severity:"high",title:"Unsafe YAML Deserialization",description:"yaml.load() can execute arbitrary code from untrusted YAML",owaspId:"A08:2021",cweId:"CWE-502",remediation:"Use yaml.safeLoad() or schema-constrained loading",fixExample:"yaml.load(content, { schema: yaml.SAFE_SCHEMA })"},{id:"deser-serialize-js",pattern:/serialize\s*\([^)]+\)|unserialize\s*\([^)]+\)/g,category:"insecure-deserialization",severity:"high",title:"Unsafe Serialization Function",description:"Node serialize/unserialize functions can execute arbitrary code",owaspId:"A08:2021",cweId:"CWE-502",remediation:"Use JSON.parse/stringify for serialization"}],zc=[{id:"auth-weak-jwt-secret",pattern:/jwt\.sign\s*\([^)]+,\s*['"][a-zA-Z0-9]{1,16}['"]/g,category:"broken-auth",severity:"high",title:"Weak JWT Secret",description:"JWT signed with a weak or short secret key",owaspId:"A07:2021",cweId:"CWE-327",remediation:"Use a strong, randomly generated secret of at least 256 bits"},{id:"auth-no-algorithm",pattern:/jwt\.verify\s*\([^)]+\)\s*(?!.*algorithm)/g,category:"broken-auth",severity:"medium",title:"JWT Without Algorithm Specification",description:"JWT verification without explicit algorithm can be exploited",owaspId:"A07:2021",cweId:"CWE-347",remediation:"Always specify the expected algorithm in JWT verification",fixExample:'jwt.verify(token, secret, { algorithms: ["HS256"] })'}],Us=[...Fc,...Lc,...$c,...Oc,...Nc,...Vc,..._c,...zc],Bi=[{id:"owasp-top-10",name:"OWASP Top 10",description:"OWASP Top 10 most critical security risks",ruleCount:45,categories:["injection","broken-auth","sensitive-data","xxe","access-control","security-misconfiguration","xss","insecure-deserialization","vulnerable-components","insufficient-logging"]},{id:"cwe-sans-25",name:"CWE/SANS Top 25",description:"Most dangerous software errors",ruleCount:38,categories:["injection","xss","access-control","sensitive-data","broken-auth"]},{id:"nodejs-security",name:"Node.js Security",description:"Node.js specific security rules",ruleCount:25,categories:["injection","xss","sensitive-data","security-misconfiguration"]},{id:"typescript-security",name:"TypeScript Security",description:"TypeScript specific security rules",ruleCount:20,categories:["injection","xss","sensitive-data"]}];A();H();A();H();import{execFile as Cy}from"child_process";import{promisify as Sy}from"util";import*as Kd from"path";var Bc=Sy(Cy);async function qi(){try{return await Bc("semgrep",["--version"],{timeout:5e3}),!0}catch{return!1}}async function Ud(){try{let{stdout:u}=await Bc("semgrep",["--version"],{timeout:5e3});return u.trim()}catch{return null}}async function Ry(u){let t={target:u.target||".",config:u.config||"auto",exclude:u.exclude||["node_modules",".git","dist","build","coverage"],maxFileSize:u.maxFileSize||5e6,timeout:u.timeout||300,verbose:u.verbose||!1};if(!await qi())return{success:!1,findings:[],errors:["Semgrep is not installed. Install with: pip install semgrep"]};try{let r=["scan",`--config=${t.config}`,"--json",t.verbose?"--verbose":"--quiet",`--max-target-bytes=${t.maxFileSize}`];for(let o of t.exclude)r.push(`--exclude=${o}`);r.push(t.target);let i=(t.timeout??300)*1e3,{stdout:n,stderr:s}=await Bc("semgrep",r,{timeout:i,maxBuffer:50*1024*1024,cwd:Kd.isAbsolute(t.target)?void 0:process.cwd()}),a=Qd(n);return s&&t.verbose&&a.errors.push(s),a.version=await Ud()||void 0,a}catch(r){let i=r;if(i.stdout)try{let n=Qd(i.stdout);return n.version=await Ud()||void 0,n}catch{}return{success:!1,findings:[],errors:[i.message??String(r)]}}}function Qd(u){try{let t=E(u),e=t.results||t.findings||[],r=t.errors?.map(i=>i.message||String(i))||[];return{success:!0,findings:e.map(i=>({check_id:i.check_id||i.rule_id||"unknown",path:i.path,start:{line:i.start?.line||1,col:i.start?.col||1},end:{line:i.end?.line||i.start?.line||1,col:i.end?.col||1},extra:{message:i.extra?.message||i.message||"Security issue detected",severity:i.extra?.severity||i.severity||"WARNING",lines:i.extra?.lines||"",metadata:{cwe:i.extra?.metadata?.cwe||i.metadata?.cwe,owasp:i.extra?.metadata?.owasp||i.metadata?.owasp,category:i.extra?.metadata?.category||i.metadata?.category,description:i.extra?.metadata?.description||i.metadata?.description,fix:i.extra?.metadata?.fix||i.extra?.fix,references:i.extra?.metadata?.references||i.metadata?.references,confidence:i.extra?.metadata?.confidence||i.metadata?.confidence}}})),errors:r}}catch(t){return{success:!1,findings:[],errors:[`Failed to parse semgrep output: ${T(t)}`]}}}async function Qs(u,t,e){let r={"owasp-top-10":"p/owasp-top-ten","cwe-sans-25":"p/cwe-top-25","nodejs-security":"p/nodejs","typescript-security":"p/typescript","javascript-security":"p/javascript","react-security":"p/react","express-security":"p/express",secrets:"p/secrets","sql-injection":"p/sql-injection",xss:"p/xss","command-injection":"p/command-injection","path-traversal":"p/path-traversal"},i=t.map(n=>r[n]||`p/${n}`).join(",");return Ry({...e,target:u,config:i||"auto"})}function Ty(u){return{ERROR:"high",WARNING:"medium",INFO:"low"}[u]||"medium"}function Ks(u){return u.map(t=>({id:t.check_id,title:t.check_id.split(".").pop()||t.check_id,description:t.extra.message,severity:Ty(t.extra.severity),file:t.path,line:t.start.line,column:t.start.col,snippet:t.extra.lines,cweId:t.extra.metadata?.cwe?.[0],owaspCategory:t.extra.metadata?.owasp?.[0],remediation:t.extra.metadata?.fix||"Review and fix the identified security issue",references:t.extra.metadata?.references||[]}))}var Ay=R.create("security-compliance/sast-scanner"),wr=class{config;memory;llmRouter;activeScans;constructor(t,e,r,i){this.config=t,this.memory=e,this.llmRouter=r,this.activeScans=i||new Map}async scanFiles(t){return this.scanWithRules(t,this.config.defaultRuleSets)}async scanWithRules(t,e){let r=v();try{if(t.length===0)return p(new Error("No files provided for scanning"));this.activeScans.set(r,"running");let i=Date.now(),n=Bi.filter(g=>e.includes(g.id));if(n.length===0)return p(new Error(`No valid rule sets found: ${e.join(", ")}`));let[s,a]=await Promise.all([this.runPatternScanning(t,n),this.runSemgrepScanning(t,e)]),o=this.mergeVulnerabilities(s.vulnerabilities,a),c=s.linesScanned,l=Date.now()-i,d=this.calculateSummary(o,t.length,l),m=n.reduce((g,b)=>g+b.ruleCount,0),h={filesScanned:t.length,linesScanned:c,rulesApplied:m+(a.length>0?a.length:0)};return await this.storeScanResults(r,"sast",o,d),this.activeScans.set(r,"completed"),f({scanId:r,vulnerabilities:o,summary:d,coverage:h})}catch(i){return this.activeScans.set(r,"failed"),p(y(i))}}async runPatternScanning(t,e){let r=[],i=0;for(let n of t){let s=await this.analyzeFile(n,e);r.push(...s.vulnerabilities),i+=s.linesScanned}return{vulnerabilities:r,linesScanned:i}}async runSemgrepScanning(t,e){if(!this.config.enableSemgrep)return[];try{if(!await qi())return[];let i=this.resolveTargetDirectory(t),n=await Qs(i,e);return!n.success||n.findings.length===0?[]:Ks(n.findings).map(a=>({id:v(),cveId:void 0,title:a.title,description:`[semgrep] ${a.description}`,severity:a.severity,category:this.mapSemgrepCategory(a.owaspCategory),location:{file:a.file,line:a.line,column:a.column,snippet:a.snippet},remediation:{description:a.remediation,estimatedEffort:"moderate",automatable:!1},references:a.references}))}catch{return[]}}resolveTargetDirectory(t){if(t.length===0)return".";if(t.length===1)return t[0].directory||".";let e=t.map(a=>a.directory||"."),r=e[0],i=r.length;for(let a=1;a<e.length;a++){let o=e[a],c=Math.min(i,o.length),l=0;for(;l<c&&r[l]===o[l];)l++;i=l}let n=r.substring(0,i),s=n.lastIndexOf("/");return s>0?n.substring(0,s):n||"."}mapSemgrepCategory(t){if(!t)return"injection";let e={A01:"access-control",A02:"sensitive-data",A03:"injection",A04:"insecure-deserialization",A05:"security-misconfiguration",A06:"vulnerable-components",A07:"broken-auth",A08:"insecure-deserialization",A09:"insufficient-logging",A10:"xxe"};for(let[r,i]of Object.entries(e))if(t.startsWith(r))return i;return"injection"}mergeVulnerabilities(t,e){if(e.length===0)return t;if(t.length===0)return e;let r=new Set(t.map(n=>`${n.location.file}:${n.location.line??0}:${n.category}`)),i=e.filter(n=>!r.has(`${n.location.file}:${n.location.line??0}:${n.category}`));return[...t,...i]}async getAvailableRuleSets(){let t=await this.memory.get("security:custom-rule-sets");return[...Bi,...t||[]]}async checkFalsePositive(t){try{if(!this.config.enableFalsePositiveDetection)return f({isFalsePositive:!1,confidence:0,reason:"False positive detection is disabled"});let e=await this.analyzeFalsePositive(t);return await this.memory.set(`security:fp-check:${t.id}`,{vulnerability:t,analysis:e},{namespace:"security-compliance",ttl:86400*30}),f(e)}catch(e){return p(y(e))}}async analyzeFile(t,e){let r=[],i=t.value,n=t.extension,s,a;try{s=await(await import("fs/promises")).readFile(i,"utf-8"),a=s.split(`
|
|
2897
|
+
`).filter(o=>o.startsWith("Test")||o.startsWith("Example")||o.startsWith("Benchmark")),i=r.filter(o=>o.startsWith("Test")).length,n=r.filter(o=>o.startsWith("Test")&&!o.includes("Integration")&&!o.includes("E2E")).length,s=r.filter(o=>o.includes("Integration")).length,a=r.filter(o=>o.includes("E2E")).length;return{total:i,unit:n,integration:s,e2e:a,source:"go"}}catch{return{total:0,unit:0,integration:0,e2e:0,source:"go"}}}function Oi(u,t){let e=0,r=0,i=0,n=0;function s(a){if(!ge(a))return;let o=xf(a,{withFileTypes:!0});for(let c of o){let l=ve(a,c.name);if(c.isDirectory()){if(t.excludeDirs.includes(c.name))continue;s(l)}else if(c.isFile()&&Lf(c.name)){let d=Pf(c.name).toLowerCase(),m=0;[".ts",".tsx",".js",".jsx",".mjs"].includes(d)?m=Fd(l):d===".py"?m=$f(l):d===".rs"?m=Of(l):d===".go"&&(m=Nf(l)),e+=m;let h=l.toLowerCase();h.includes("e2e")||h.includes("end-to-end")?n+=m:h.includes("integration")?i+=m:r+=m}}}return s(u),{total:e,unit:r,integration:i,e2e:n,source:"fallback"}}function Lf(u){let t=u.toLowerCase();return t.includes(".test.")||t.includes(".spec.")||t.includes("_test.")||t.startsWith("test_")||t.endsWith("_test.ts")||t.endsWith("_test.js")||t.endsWith("_test.py")||t.endsWith("_test.go")||t.endsWith("_test.rs")}function Fd(u){try{let t=Vi(u,"utf-8"),e=t.match(/\bit\s*\(/g)||[],r=t.match(/\btest\s*\(/g)||[];return e.length+r.length}catch{return 0}}function $f(u){try{let t=Vi(u,"utf-8"),e=t.match(/\bdef\s+test_\w+\s*\(/g)||[],r=t.match(/\basync\s+def\s+test_\w+\s*\(/g)||[];return e.length+r.length}catch{return 0}}function Of(u){try{let t=Vi(u,"utf-8"),e=t.match(/#\[test\]/g)||[],r=t.match(/#\[tokio::test\]/g)||[],i=t.match(/#\[async_std::test\]/g)||[];return e.length+r.length+i.length}catch{return 0}}function Nf(u){try{return(Vi(u,"utf-8").match(/\bfunc\s+Test\w+\s*\(/g)||[]).length}catch{return 0}}function Gs(u,t,e){let r=u,i=0,n=0;return(ge(ve(e,"tests","integration"))||ge(ve(e,"test","integration"))||ge(ve(e,"__tests__","integration")))&&(i=Math.floor(u*.2),r-=i),(ge(ve(e,"tests","e2e"))||ge(ve(e,"test","e2e"))||ge(ve(e,"e2e"))||ge(ve(e,"cypress")))&&(n=Math.floor(u*.1),r-=n),{total:u,unit:Math.max(0,r),integration:i,e2e:n,source:t}}var kc=class{config;cache=new Map;cacheHits=0;cacheMisses=0;constructor(t={}){this.config={...zt,...t}}async collectAll(t){let e=`all:${t}`;if(this.config.enableCache){let l=this.getFromCache(e);if(l)return l}let[r,i,n]=await Promise.all([this.countLOC(t),this.countTests(t),this.countPatterns(t,this.detectLanguage(t))]),s=[];r.source!=="fallback"&&s.push(r.source),i.source!=="fallback"&&s.push(i.source);let a=r.source==="fallback"?"approximate":"accurate",o=i.source==="fallback"?"approximate":"accurate",c={loc:r,tests:i,patterns:n,collectedAt:new Date,toolsUsed:s,accuracy:{loc:a,tests:o,overall:a==="accurate"&&o==="accurate"?"accurate":"approximate"}};return this.config.enableCache&&this.setInCache(e,c),c}async countLOC(t){let e=`loc:${t}`;if(this.config.enableCache){let i=this.getFromCache(e);if(i)return i}let r=await Tc(t,this.config);return this.config.enableCache&&this.setInCache(e,r),r}async countTests(t){let e=`tests:${t}`;if(this.config.enableCache){let i=this.getFromCache(e);if(i)return i}let r=await xc(t,this.config);return this.config.enableCache&&this.setInCache(e,r),r}async countPatterns(t,e){let r=`patterns:${t}:${e}`;if(this.config.enableCache){let n=this.getFromCache(r);if(n)return n}let i=this.countPatternsInternal(t,e);return this.config.enableCache&&this.setInCache(r,i),i}checkTools(){let t=Ac(),e=Pc(process.cwd());return[...t,...e]}clearCache(){this.cache.clear(),this.cacheHits=0,this.cacheMisses=0}getCacheStats(){return{hits:this.cacheHits,misses:this.cacheMisses,size:this.cache.size}}getFromCache(t){let e=this.cache.get(t);return e&&Date.now()-e.timestamp<this.config.cacheTTL?(this.cacheHits++,e.data):(this.cacheMisses++,null)}setInCache(t,e){this.cache.set(t,{data:e,timestamp:Date.now()})}detectLanguage(t){return Bt(qt(t,"Cargo.toml"))?"rust":Bt(qt(t,"go.mod"))?"go":Bt(qt(t,"pyproject.toml"))||Bt(qt(t,"requirements.txt"))?"python":Bt(qt(t,"package.json"))?Bt(qt(t,"tsconfig.json"))?"typescript":"javascript":"unknown"}countPatternsInternal(t,e){let r={},i=0,n=0,s=0,a=0,o=this.getPatternsForLanguage(e);function c(l){if(!Bt(l))return;let d=_f(l,{withFileTypes:!0});for(let m of d){let h=qt(l,m.name);if(m.isDirectory()){if(["node_modules","dist","coverage","build",".git","vendor","target"].includes(m.name))continue;c(h)}else if(m.isFile()){let g=zf(m.name).toLowerCase();if(Bf(g,e)){let b=qf(h,o);(b.unwraps>0||b.unsafeBlocks>0||b.todoComments>0||b.consoleStatements>0)&&(r[h]=b,i+=b.unwraps,n+=b.unsafeBlocks,s+=b.todoComments,a+=b.consoleStatements)}}}}return c(t),{unwraps:i,unsafeBlocks:n,todoComments:s,consoleStatements:a,byFile:r}}getPatternsForLanguage(t){switch(t){case"rust":return{unwrap:/\.unwrap\s*\(/g,unsafe:/\bunsafe\s*\{/g,todo:/\/\/\s*(TODO|FIXME|HACK|XXX)[\s:]/gi,console:/\b(println!|print!|eprintln!|eprint!|dbg!)\s*\(/g};case"python":return{unwrap:null,unsafe:null,todo:/#\s*(TODO|FIXME|HACK|XXX)[\s:]/gi,console:/\b(print)\s*\(/g};case"go":return{unwrap:null,unsafe:/\bunsafe\./g,todo:/\/\/\s*(TODO|FIXME|HACK|XXX)[\s:]/gi,console:/\b(fmt\.Print|fmt\.Printf|fmt\.Println|log\.Print|log\.Printf|log\.Println)\s*\(/g};default:return{unwrap:null,unsafe:null,todo:/\/\/\s*(TODO|FIXME|HACK|XXX)[\s:]/gi,console:/\bconsole\.(log|debug|info|warn|error)\s*\(/g}}}};function Bf(u,t){switch(t){case"rust":return u===".rs";case"python":return[".py",".pyw"].includes(u);case"go":return u===".go";case"typescript":return[".ts",".tsx"].includes(u);case"javascript":return[".js",".jsx",".mjs",".cjs"].includes(u);default:return[".ts",".tsx",".js",".jsx",".py",".rs",".go"].includes(u)}}function qf(u,t){try{let e=Vf(u,"utf-8");return{unwraps:t.unwrap?(e.match(t.unwrap)||[]).length:0,unsafeBlocks:t.unsafe?(e.match(t.unsafe)||[]).length:0,todoComments:(e.match(t.todo)||[]).length,consoleStatements:(e.match(t.console)||[]).length}}catch{return{unwraps:0,unsafeBlocks:0,todoComments:0,consoleStatements:0}}}function Ld(u={}){return new kc(u)}M();A();se();Tt();A();Tt();A();Tt();A();Tt();A();se();Tt();A();var kO=300*1e3;Ge();Ge();M();Ge();var qO=R.create("temporal-compression");A();M();var WO=R.create("ruvector-server-client");Xm();import{Buffer as ty}from"buffer";var ZO=ty.from("COGCNTNR","ascii");Ge();Ge();var iy={capacity:1e4,minCoherenceThreshold:.3,highTierThreshold:.8,mediumTierThreshold:.5,highTierWeight:3,mediumTierWeight:1.5,lowTierWeight:1},Dc=class{config;cusumDetector;buffer;totalSeen=0;totalAdmitted=0;totalRejected=0;totalEvicted=0;totalSampled=0;constructor(t){this.config={...iy,...t},this.cusumDetector=new Va({threshold:this.config.cusumConfig?.threshold??5,slack:this.config.cusumConfig?.slack??.5,resetOnAlarm:!1,warmupSamples:20}),this.buffer=[]}admit(t,e,r){this.totalSeen++;let i=this.getEffectiveThreshold();if(r<i)return this.totalRejected++,!1;let n=this.classifyTier(r),s={id:t,data:e,coherenceScore:r,tier:n,admittedAt:Date.now(),replayCount:0};if(this.buffer.length<this.config.capacity)return this.buffer.push(s),this.totalAdmitted++,!0;let a=Math.floor(Math.random()*this.totalAdmitted),o=this.getTierWeight(n),c=Math.floor(a/o);if(c<this.config.capacity){let l=this.selectEvictionTarget(c);return this.buffer[l]=s,this.totalEvicted++,this.totalAdmitted++,!0}return this.totalRejected++,!1}sample(t,e){if(this.buffer.length===0)return[];let r=e!==void 0?this.buffer.filter(a=>a.coherenceScore>=e):this.buffer;if(r.length===0)return[];if(t>=r.length){let a=[...r];for(let o of a)o.replayCount++;return this.totalSampled+=a.length,a}let i=r.map(a=>this.getTierWeight(a.tier)),n=[],s=new Set;for(;n.length<t&&s.size<r.length;){let a=0;for(let l=0;l<r.length;l++)s.has(l)||(a+=i[l]);if(a<=0)break;let o=Math.random()*a,c=-1;for(let l=0;l<r.length;l++)if(!s.has(l)&&(o-=i[l],o<=0)){c=l;break}if(c===-1){for(let l=0;l<r.length;l++)if(!s.has(l)){c=l;break}}c>=0&&(s.add(c),r[c].replayCount++,n.push(r[c]))}return this.totalSampled+=n.length,n}size(){return this.buffer.length}getStats(){let t={high:0,medium:0,low:0};for(let e of this.buffer)t[e.tier]++;return{size:this.buffer.length,capacity:this.config.capacity,totalAdmitted:this.totalAdmitted,totalRejected:this.totalRejected,totalEvicted:this.totalEvicted,tierCounts:t,totalSampled:this.totalSampled}}getByTier(t){return this.buffer.filter(e=>e.tier===t)}clear(){this.buffer.length=0,this.totalSeen=0,this.totalAdmitted=0,this.totalRejected=0,this.totalEvicted=0,this.totalSampled=0,this.cusumDetector.reset()}getCusumState(t){return this.cusumDetector.getState(t)}observeCoherence(t,e){return this.cusumDetector.update(t,e)}classifyTier(t){return t>=this.config.highTierThreshold?"high":t>=this.config.mediumTierThreshold?"medium":"low"}getTierWeight(t){switch(t){case"high":return this.config.highTierWeight;case"medium":return this.config.mediumTierWeight;case"low":return this.config.lowTierWeight}}getEffectiveThreshold(){let t=["retrieve","write","learn","act"],e=!1;for(let r of t)if(this.cusumDetector.getState(r).driftDetected){e=!0;break}return e?Math.min(this.config.minCoherenceThreshold*1.5,.9):this.config.minCoherenceThreshold}selectEvictionTarget(t){let e=Math.min(10,this.buffer.length),r=Math.max(0,t-Math.floor(e/2)),i=Math.min(this.buffer.length,r+e),n=t,s=this.buffer[t].coherenceScore;for(let a=r;a<i;a++)this.buffer[a].coherenceScore<s&&(s=this.buffer[a].coherenceScore,n=a);return n}};se();var vr=R.create("code-intelligence/gnn");async function $d(u,t,e){try{for(let r of e)try{let i=await t.readFile(r);if(i.success&&i.value){let s={vector:await Ic(r,i.value),dimension:384,namespace:"code",text:i.value.slice(0,1e3),timestamp:Date.now(),quantization:"none",metadata:{path:r}};u.addEmbedding(s)}}catch(i){vr.error(`Failed to index ${r}:`,i instanceof Error?i:void 0)}vr.info(`Indexed ${e.length} code embeddings`)}catch(r){vr.error("Failed to index code embeddings:",r instanceof Error?r:void 0)}}async function Ic(u,t){let e=[],r=u.split(".").pop(),i=Hs(r||"");e.push(i%1e3/1e3),e.push(Math.min(1,t.length/1e4));let n=t.match(/function\s+\w+/g)||[],s=t.match(/class\s+\w+/g)||[];e.push(Math.min(1,(n.length+s.length)/50));let a=t.match(/import\s+.*from|require\s*\(/g)||[];e.push(Math.min(1,a.length/20));let o=t.match(/for\s*\(|while\s*\(/g)||[],c=t.match(/if\s*\(/g)||[];e.push(Math.min(1,(o.length+c.length)/30));let l=t.match(/\/\/.*|\/\*[\s\S]*?\*\//g)||[];e.push(Math.min(1,l.length/50));let d=Hs(t.slice(0,500));for(let m=e.length;m<384;m++)e.push(d*(m+1)%1e4/1e4);return e.slice(0,384)}async function Od(u,t){try{let r={vector:await Ic("query",t),dimension:384,namespace:"code",text:t,timestamp:Date.now(),quantization:"none"};return u.search(r,{limit:10,namespace:"code"}).map(n=>({file:n.metadata?.path??`file-${n.id}`,similarity:1-n.distance}))}catch(e){return vr.error("Failed to search with GNN:",e instanceof Error?e:void 0),[]}}async function Nd(u,t,e){try{for(let r of e.changedFiles){let i=await t.readFile(r);if(i.success&&i.value){let s={vector:await Ic(r,i.value),dimension:384,namespace:"code",text:i.value.slice(0,1e3),timestamp:Date.now(),quantization:"none",metadata:{path:r}},a=u.search(s,{limit:5,namespace:"code"});vr.info(`Found ${a.length} semantically similar files to ${r}`)}}}catch(r){vr.error("Failed to enhance impact analysis:",r instanceof Error?r:void 0)}}function Vd(u,t){let e=new Map,r=new Map;for(let i of u)e.set(i.file,i.score),r.set(i.file,i);for(let i of t){let n=e.get(i.file);n!==void 0?e.set(i.file,(n+i.similarity)/2):(e.set(i.file,i.similarity*.8),r.set(i.file,{file:i.file,snippet:"",score:i.similarity*.8,highlights:[]}))}return Array.from(r.values()).map(i=>({...i,score:e.get(i.file)??i.score})).sort((i,n)=>n.score-i.score).slice(0,20)}function Hs(u){let t=0;for(let e=0;e<u.length;e++)t=(t<<5)-t+u.charCodeAt(e),t=t|0;return Math.abs(t)}M();A();var ze=R.create("code-intelligence/hypergraph");async function _d(u,t,e){try{let r=await u.findUntestedFunctions();if(ze.info(`[CodeIntelligence] Found ${r.length} untested functions via hypergraph`),e){let i=I("code-intelligence.UntestedFunctionsFound","code-intelligence",{count:r.length,functions:r.slice(0,10).map(n=>({name:n.name,file:n.filePath,complexity:n.complexity}))});await t.publish(i)}return{success:!0,value:r}}catch(r){let i=y(r);return ze.error("Failed to find untested functions:"),p(i)}}async function zd(u,t,e,r){if(t.length===0)return{success:!0,value:[]};try{let i=await u.findImpactedTests(t);if(ze.info(`[CodeIntelligence] Found ${i.length} impacted tests for ${t.length} changed files via hypergraph`),r){let n=I("code-intelligence.ImpactedTestsFound","code-intelligence",{changedFiles:t,testCount:i.length,tests:i.slice(0,10).map(s=>({name:s.name,file:s.filePath}))});await e.publish(n)}return{success:!0,value:i}}catch(i){let n=y(i);return ze.error("Failed to find impacted tests:"),p(n)}}async function Bd(u,t,e,r){try{let i=await u.findCoverageGaps(t);if(ze.info(`[CodeIntelligence] Found ${i.length} coverage gaps (functions with <=${t}% coverage) via hypergraph`),r){let n=I("code-intelligence.CoverageGapsFound","code-intelligence",{maxCoverage:t,gapCount:i.length,gaps:i.slice(0,10).map(s=>({name:s.name,file:s.filePath,coverage:s.coverage,complexity:s.complexity}))});await e.publish(n)}return{success:!0,value:i}}catch(i){let n=y(i);return ze.error("Failed to find coverage gaps:"),p(n)}}async function qd(u,t,e,r,i){try{ze.info(`[CodeIntelligence] Building hypergraph from ${t.files.length} indexed files`);let n=await u.buildFromIndexResult(t);if(ze.info(`[CodeIntelligence] Hypergraph built: ${n.nodesCreated} nodes created, ${n.nodesUpdated} nodes updated, ${n.edgesCreated} edges created (${n.durationMs}ms)`),await e.set("hypergraph:build:latest",{timestamp:new Date().toISOString(),...n},{namespace:"code-intelligence",persist:!0}),i){let s=I("code-intelligence.HypergraphBuilt","code-intelligence",{nodesCreated:n.nodesCreated,nodesUpdated:n.nodesUpdated,edgesCreated:n.edgesCreated,durationMs:n.durationMs,errorCount:n.errors.length});await r.publish(s)}return{success:!0,value:n}}catch(n){let s=y(n);return ze.error("Failed to build hypergraph:"),p(s)}}async function Gd(u,t,e){try{let r=await u.findImpactedTests(t.changedFiles),i=new Set([...e.impactedTests,...r.map(a=>a.filePath||a.name)]),n=e.riskLevel;if(r.length>e.impactedTests.length){let a=e.directImpact.length+e.transitiveImpact.length;a>10&&i.size>20?n="critical":a>5&&i.size>10&&(n="high")}let s=[...e.recommendations];return r.length>0&&s.push(`Hypergraph analysis found ${r.length} additional test(s) to run`),{...e,impactedTests:Array.from(i),riskLevel:n,recommendations:s}}catch(r){return ze.error("Failed to enhance impact with hypergraph:",r instanceof Error?r:void 0),e}}M();var br=R.create("code-intelligence/consensus");async function Hd(u,t,e,r){let i=V({id:v(),type:"code-pattern-detection",confidence:t,description:`Verify code pattern: ${u.name} (${u.type}) at ${u.location}`,payload:u,detectedBy:"code-intelligence-coordinator",severity:t>.9?"high":"medium"});if(e.requiresConsensus(i)){let n=await e.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(br.info(`Code pattern '${u.name}' verified by consensus`),!0):(br.warn(`Code pattern '${u.name}' NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}async function jd(u,t,e,r){let i=V({id:v(),type:"impact-analysis",confidence:t,description:`Verify impact analysis: ${u.changedFiles.length} files, risk=${u.riskLevel}, ${u.impactedTests.length} tests`,payload:u,detectedBy:"code-intelligence-coordinator",severity:u.riskLevel==="critical"||u.riskLevel==="high"?"high":"medium"});if(e.requiresConsensus(i)){let n=await e.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(br.info(`Impact analysis verified by consensus (risk=${u.riskLevel})`),!0):(br.warn(`Impact analysis NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}async function Wd(u,t,e,r){let i=V({id:v(),type:"dependency-mapping",confidence:t,description:`Verify dependency: ${u.source} -> ${u.targets.length} targets (${u.type})`,payload:u,detectedBy:"code-intelligence-coordinator",severity:t>.85?"high":"medium"});if(e.requiresConsensus(i)){let n=await e.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(br.info("Dependency mapping verified by consensus"),!0):(br.warn(`Dependency mapping NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}var wy={maxConcurrentWorkflows:5,defaultTimeout:12e4,publishEvents:!0,enableIncrementalIndex:!0,enableGNN:!0,enableSONA:!0,enableMetricCollector:!0,enableHypergraph:!0,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},Z=R.create("code-intelligence"),zi=class extends Q{constructor(e,r,i,n={},s){let a={...wy,...n};super(e,"code-intelligence",a,{verifyFindingTypes:["code-pattern-detection","impact-analysis","dependency-mapping"]});this.memory=r;this.agentCoordinator=i;this.knowledgeGraph=new xt({memory:r,llmRouter:s}),this.semanticAnalyzer=new _t(r),this.impactAnalyzer=new Br(r,this.knowledgeGraph),this.fileReader=new Fe,this.productFactorsBridge=new Bs(e,r,{publishEvents:this.config.publishEvents})}memory;agentCoordinator;knowledgeGraph;semanticAnalyzer;impactAnalyzer;fileReader;gnnIndex;sonaEngine;rlInitialized=!1;metricCollector;hypergraph;hypergraphDb;productFactorsBridge;async onInitialize(){this.subscribeToEvents(),await this.loadWorkflowState(),(this.config.enableGNN||this.config.enableSONA)&&await this.initializeRLIntegrations(),this.config.enableMetricCollector&&(this.metricCollector=Ld({enableCache:!0,cacheTTL:3e5}),Z.info("MetricCollector initialized for real code metrics")),this.config.enableHypergraph&&await this.initializeHypergraph(),await this.productFactorsBridge.initialize()}async initializeHypergraph(){try{let{openDatabase:e}=await import("./safe-db-RAX3H2P7.js"),r=await import("fs"),i=await import("path"),{findProjectRoot:n}=await import("./unified-memory-QG3FDRKR.js"),s=n(),a=this.config.hypergraphDbPath||i.join(s,".agentic-qe","memory.db"),o=i.dirname(a);r.existsSync(o)||r.mkdirSync(o,{recursive:!0}),this.hypergraphDb=e(a),this.hypergraph=await ln({db:this.hypergraphDb,maxTraversalDepth:10,maxQueryResults:1e3,enableVectorSearch:this.config.enableGNN}),Z.info(`Hypergraph Engine initialized at ${a}`)}catch(e){let r=e instanceof Error?e.message:String(e);if(Z.warn(`Hypergraph Engine initialization failed (feature degraded): ${r}`),this.hypergraph=void 0,this.hypergraphDb=void 0,this.config.publishEvents){let i=I("code-intelligence.HypergraphDegraded","code-intelligence",{reason:r});this.eventBus.publish(i).catch(()=>{})}}}async initializeRLIntegrations(){try{if(this.config.enableGNN&&(ja(),this.gnnIndex=cn.getInstance("code-intelligence",{M:16,efConstruction:200,efSearch:50,dimension:384,metric:"cosine"}),this.gnnIndex.initializeIndex("code"),this.gnnIndex.initializeIndex("test")),this.config.enableSONA)try{this.sonaEngine=await pe({domain:"code-intelligence",loadOnInit:!0,autoSaveInterval:6e4,maxPatterns:1e4,minConfidence:.6}),Z.info("PersistentSONAEngine initialized for code pattern learning")}catch(e){Z.error("Failed to initialize PersistentSONAEngine:",e instanceof Error?e:void 0),this.sonaEngine=void 0}this.rlInitialized=!0}catch(e){throw Z.error("Failed to initialize RL integrations:",e instanceof Error?e:void 0),e}}async onDispose(){if(await this.saveWorkflowState(),this.gnnIndex&&cn.closeInstance("code-intelligence"),this.sonaEngine)try{await this.sonaEngine.close(),this.sonaEngine=void 0}catch(e){Z.error("Error closing SONA engine:",e instanceof Error?e:void 0)}if(this.hypergraphDb){try{this.hypergraphDb.close()}catch(e){Z.error("Error closing hypergraph database:",e instanceof Error?e:void 0)}this.hypergraphDb=void 0}this.hypergraph=void 0,await this.productFactorsBridge.dispose()}getActiveWorkflows(){return super.getActiveWorkflows()}async index(e){let r=v();try{if(this.startWorkflow(r,"index"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Z.warn("Topology degraded, using conservative strategy"),this.minCutMixin.shouldPauseOperations())return p(new Error("Indexing paused: topology is in critical state"));if(!this.agentCoordinator.canSpawn())return p(new Error("Agent limit reached, cannot spawn indexing agents"));let i=await this.spawnIndexerAgent(r,e);if(!i.success)return this.failWorkflow(r,i.error.message),p(i.error);this.addAgentToWorkflow(r,i.value),this.updateWorkflowProgress(r,10);let n=await this.knowledgeGraph.index(e);if(n.success){if(this.updateWorkflowProgress(r,40),this.config.enableGNN&&this.gnnIndex&&e.paths.length>0&&await this.indexCodeEmbeddings(e.paths),this.updateWorkflowProgress(r,60),this.config.enableMetricCollector&&this.metricCollector&&e.paths.length>0){let s=this.getProjectRootFromPaths(e.paths);s&&await this.collectProjectMetrics(s)}if(this.updateWorkflowProgress(r,70),e.paths.length>0&&await this.indexForSemanticSearch(e.paths),this.updateWorkflowProgress(r,85),this.config.enableHypergraph&&this.hypergraph&&e.paths.length>0)try{let s=await this.buildCodeIndexResultFromPaths(e.paths);if(s.files.length>0){await this.hypergraph.buildFromIndexResult(s),Z.info(`Hypergraph rebuilt from ${s.files.length} indexed files`);try{let a=await this.hypergraph.synthesizeTestCoverage();(a.testsTagged>0||a.coversCreated>0)&&Z.info(`Test coverage synthesized: tests_tagged=${a.testsTagged} covers_created=${a.coversCreated}`)}catch(a){Z.warn(`Test coverage synthesis skipped: ${a instanceof Error?a.message:a}`)}}}catch(s){Z.warn(`Hypergraph rebuild skipped: ${s instanceof Error?s.message:s}`)}this.updateWorkflowProgress(r,100),this.completeWorkflow(r),this.config.publishEvents&&await this.publishKnowledgeGraphUpdated(n.value)}else this.failWorkflow(r,n.error.message);return await this.agentCoordinator.stop(i.value),n}catch(i){let n=y(i);return this.failWorkflow(r,n.message),p(n)}}async search(e){let r=v();try{this.startWorkflow(r,"search");let i=await this.spawnSearchAgent(r,e);if(i.success&&this.addAgentToWorkflow(r,i.value),this.config.enableSONA&&this.sonaEngine){let a=await this.adaptSearchPattern(e);a.success&&a.pattern&&Z.info(`Adapted search pattern with ${a.similarity.toFixed(3)} similarity`)}let n=[];this.config.enableGNN&&this.gnnIndex&&(n=await this.searchCodeWithGNN(e));let s=await this.semanticAnalyzer.search(e);return s.success?(n.length>0&&(s.value.results=this.mergeSearchResults(s.value.results,n)),this.completeWorkflow(r),this.config.publishEvents&&await this.publishSemanticSearchCompleted(e,s.value)):this.failWorkflow(r,s.error.message),i.success&&await this.agentCoordinator.stop(i.value),s}catch(i){let n=y(i);return this.failWorkflow(r,n.message),p(n)}}async analyzeImpact(e){let r=v();try{if(this.startWorkflow(r,"impact"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Z.warn("Topology degraded, using conservative impact analysis"),this.minCutMixin.shouldPauseOperations())return p(new Error("Impact analysis paused: topology is in critical state"));let i=await this.spawnImpactAnalyzerAgent(r,e);if(!i.success)return this.failWorkflow(r,i.error.message),p(i.error);this.addAgentToWorkflow(r,i.value),this.updateWorkflowProgress(r,20),this.config.enableGNN&&this.gnnIndex&&await this.enhanceImpactAnalysisWithGNN(e);let n=await this.impactAnalyzer.analyzeImpact(e);if(n.success){this.updateWorkflowProgress(r,80);let s=n.value;return this.config.enableHypergraph&&this.hypergraph&&(s=await this.enhanceImpactWithHypergraph(e,n.value)),this.updateWorkflowProgress(r,100),this.completeWorkflow(r),this.config.enableSONA&&this.sonaEngine&&await this.storeImpactPattern(e,s),this.config.publishEvents&&await this.publishImpactAnalysisCompleted(e,s),{success:!0,value:s}}else this.failWorkflow(r,n.error.message);return await this.agentCoordinator.stop(i.value),n}catch(i){let n=y(i);return this.failWorkflow(r,n.message),p(n)}}async mapDependencies(e){let r=v();try{this.startWorkflow(r,"dependency");let i=await this.knowledgeGraph.mapDependencies(e);return i.success?this.completeWorkflow(r):this.failWorkflow(r,i.error.message),i}catch(i){let n=y(i);return this.failWorkflow(r,n.message),p(n)}}async queryKG(e){let r=v();try{this.startWorkflow(r,"query");let i=await this.knowledgeGraph.query(e);return i.success?this.completeWorkflow(r):this.failWorkflow(r,i.error.message),i}catch(i){let n=y(i);return this.failWorkflow(r,n.message),p(n)}}async indexCodeEmbeddings(e){!this.gnnIndex||!this.rlInitialized||await $d(this.gnnIndex,this.fileReader,e)}async searchCodeWithGNN(e){return!this.gnnIndex||!this.rlInitialized?[]:Od(this.gnnIndex,e.query)}async enhanceImpactAnalysisWithGNN(e){!this.gnnIndex||!this.rlInitialized||await Nd(this.gnnIndex,this.fileReader,e)}async adaptSearchPattern(e){if(!this.sonaEngine||!this.rlInitialized)return{success:!1,pattern:null,similarity:0};try{let r=Array.isArray(e.filters)?e.filters.find(s=>s.field==="language")?.value:void 0,i={id:`search-${e.type}`,features:[e.query.length,e.type==="semantic"?1:0,e.type==="exact"?1:0,r==="typescript"?1:0,r==="javascript"?1:0]},n=await this.sonaEngine.adaptPattern(i,"coverage-optimization","code-intelligence");return{success:n.success,pattern:n.pattern,similarity:n.similarity}}catch(r){return Z.error("Failed to adapt search pattern:",r instanceof Error?r:void 0),{success:!1,pattern:null,similarity:0}}}async storeImpactPattern(e,r){if(!(!this.sonaEngine||!this.rlInitialized))try{let i={id:`impact-${e.changedFiles.join(",")}`,features:[e.changedFiles.length,e.depth||1,r.directImpact.length,r.transitiveImpact.length,r.impactedTests.length,r.riskLevel==="high"?1:r.riskLevel==="medium"?.5:0]},n={type:"analyze-impact",value:r.riskLevel},s={reward:r.riskLevel==="high"?.8:r.riskLevel==="medium"?.5:.3,success:r.impactedTests.length>0,quality:(r.directImpact.length+r.transitiveImpact.length)/100},a=this.sonaEngine.createPattern(i,n,s,"coverage-optimization","code-intelligence",{changedFiles:e.changedFiles,impactCount:r.directImpact.length+r.transitiveImpact.length,testImpactCount:r.impactedTests.length});Z.info(`Stored impact pattern ${a.id}`)}catch(i){Z.error("Failed to store impact pattern:",i instanceof Error?i:void 0)}}mergeSearchResults(e,r){return Vd(e,r)}hashCode(e){return Hs(e)}async spawnIndexerAgent(e,r){let i={name:`kg-indexer-${e.slice(0,8)}`,domain:"code-intelligence",type:"analyzer",capabilities:["indexing","ast-parsing","graph-building"],config:{workflowId:e,paths:r.paths,incremental:r.incremental}};return this.agentCoordinator.spawn(i)}async spawnSearchAgent(e,r){let i={name:`semantic-search-${e.slice(0,8)}`,domain:"code-intelligence",type:"analyzer",capabilities:["semantic-search","vector-similarity",r.type],config:{workflowId:e,query:r.query,type:r.type}};return this.agentCoordinator.spawn(i)}async spawnImpactAnalyzerAgent(e,r){let i={name:`impact-analyzer-${e.slice(0,8)}`,domain:"code-intelligence",type:"analyzer",capabilities:["impact-analysis","dependency-traversal","risk-assessment"],config:{workflowId:e,changedFiles:r.changedFiles,depth:r.depth}};return this.agentCoordinator.spawn(i)}async publishKnowledgeGraphUpdated(e){let r={nodes:e.nodesCreated,edges:e.edgesCreated,filesIndexed:e.filesIndexed,duration:e.duration},i=I(rt.KnowledgeGraphUpdated,"code-intelligence",r);await this.eventBus.publish(i)}async publishImpactAnalysisCompleted(e,r){let i={analysisId:v(),changedFiles:e.changedFiles,impactedFiles:[...r.directImpact.map(s=>s.file),...r.transitiveImpact.map(s=>s.file)],impactedTests:r.impactedTests,riskLevel:r.riskLevel},n=I(rt.ImpactAnalysisCompleted,"code-intelligence",i);await this.eventBus.publish(n)}async publishSemanticSearchCompleted(e,r){let i=I(rt.SemanticSearchCompleted,"code-intelligence",{query:e.query,type:e.type,resultCount:r.total,searchTime:r.searchTime});await this.eventBus.publish(i)}subscribeToEvents(){this.eventBus.subscribe("test-execution.TestRunCompleted",this.handleTestRunCompleted.bind(this)),this.eventBus.subscribe("source-control.FilesChanged",this.handleFilesChanged.bind(this))}async handleTestRunCompleted(e){let r=e.payload;await this.memory.set(`code-intelligence:test-correlation:${r.runId}`,r,{namespace:"code-intelligence",ttl:86400})}async handleFilesChanged(e){if(!this.config.enableIncrementalIndex)return;let r=e.payload;r.files&&r.files.length>0&&await this.memory.set(`code-intelligence:pending-index:${Date.now()}`,{files:r.files,timestamp:new Date().toISOString()},{namespace:"code-intelligence",ttl:3600})}async indexForSemanticSearch(e){let r=e.slice(0,100);for(let i of r)try{let n=await this.fileReader.readFile(i);n.success&&n.value&&await this.semanticAnalyzer.indexCode(i,n.value)}catch{}}async loadWorkflowState(){let e=await this.memory.get("code-intelligence:coordinator:workflows");if(e)for(let r of e)r.status==="running"&&(r.status="failed",r.error="Coordinator restarted",r.completedAt=new Date),this.workflows.set(r.id,r)}async saveWorkflowState(){let e=Array.from(this.workflows.values());await this.memory.set("code-intelligence:coordinator:workflows",e,{namespace:"code-intelligence",persist:!0})}async generateC4Diagrams(e,r){let i=v();try{this.startWorkflow(i,"query");let n={projectPath:e,detectExternalSystems:r?.detectExternalSystems??!0,analyzeComponents:r?.analyzeComponents??!0,analyzeCoupling:r?.analyzeCoupling??!0,includeContext:r?.includeContext??!0,includeContainer:r?.includeContainer??!0,includeComponent:r?.includeComponent??!0,includeDependency:r?.includeDependency??!1,excludePatterns:r?.excludePatterns};this.updateWorkflowProgress(i,20);let s=await this.productFactorsBridge.requestC4Diagrams(n);return s.success?(this.updateWorkflowProgress(i,80),await this.storeC4DiagramsInMemory(e,s.value),this.updateWorkflowProgress(i,100),this.completeWorkflow(i),Z.info(`[CodeIntelligenceCoordinator] C4 diagrams generated for ${e}: ${s.value.components.length} components, ${s.value.externalSystems.length} external systems`)):this.failWorkflow(i,s.error.message),s}catch(n){let s=y(n);return this.failWorkflow(i,s.message),p(s)}}getProductFactorsBridge(){return this.productFactorsBridge}async storeC4DiagramsInMemory(e,r){let i=`c4-diagrams:latest:${this.hashCode(e)}`;await this.memory.set(i,r,{namespace:"code-intelligence",persist:!0,ttl:36e5}),await this.memory.set(`c4-components:${this.hashCode(e)}`,r.components,{namespace:"code-intelligence",ttl:36e5}),await this.memory.set(`c4-external-systems:${this.hashCode(e)}`,r.externalSystems,{namespace:"code-intelligence",ttl:36e5})}async collectProjectMetrics(e){if(!this.config.enableMetricCollector||!this.metricCollector)return p(new Error("MetricCollector is not enabled"));try{Z.info(`Collecting real metrics for ${e}`);let r=await this.metricCollector.collectAll(e),i=r.toolsUsed.length>0?r.toolsUsed.join(", "):r.loc.source==="node-native"?"node-native":"fallback";if(Z.info(`[CodeIntelligence] Real metrics collected: ${r.loc.total} LOC, ${r.tests.total} tests, tools: ${i}`),r.loc.source==="node-native"&&Z.info("[CodeIntelligence] Using Node.js-native line counter (no cloc/tokei needed)"),await this.storeProjectMetricsInMemory(e,r),this.config.publishEvents){let n=I("code-intelligence.MetricsCollected","code-intelligence",{projectPath:e,loc:r.loc.total,tests:r.tests.total,toolsUsed:r.toolsUsed});await this.eventBus.publish(n)}return{success:!0,value:r}}catch(r){let i=y(r);return Z.error("Failed to collect metrics:"),p(i)}}async storeProjectMetricsInMemory(e,r){let i=`project-metrics:latest:${this.hashCode(e)}`;await this.memory.set(i,r,{namespace:"code-intelligence",persist:!0,ttl:3e5}),await this.memory.set(`loc-metrics:${this.hashCode(e)}`,r.loc,{namespace:"code-intelligence",ttl:3e5}),await this.memory.set(`test-metrics:${this.hashCode(e)}`,r.tests,{namespace:"code-intelligence",ttl:3e5})}getMetricCollector(){return this.metricCollector}getProjectRootFromPaths(e){if(e.length===0)return null;let r=e[0],i=r.split("/"),n="";for(let a of i){n=n?`${n}/${a}`:a;let o=["package.json","Cargo.toml","go.mod","pyproject.toml",".git"];for(let c of o)try{let l=`${n}/${c}`;if(Fa("fs").existsSync(l))return n}catch{}}let s=r.lastIndexOf("/");return s>0?r.substring(0,s):r}isHypergraphEnabled(){return this.config.enableHypergraph&&this.hypergraph!==void 0}async findUntestedFunctions(){return this.hypergraph?_d(this.hypergraph,this.eventBus,this.config.publishEvents):p(new Error("Hypergraph is not enabled or not initialized"))}async findImpactedTestsFromHypergraph(e){return this.hypergraph?zd(this.hypergraph,e,this.eventBus,this.config.publishEvents):p(new Error("Hypergraph is not enabled or not initialized"))}async findCoverageGapsFromHypergraph(e=50){return this.hypergraph?Bd(this.hypergraph,e,this.eventBus,this.config.publishEvents):p(new Error("Hypergraph is not enabled or not initialized"))}async buildHypergraphFromIndex(e){return this.hypergraph?qd(this.hypergraph,e,this.memory,this.eventBus,this.config.publishEvents):p(new Error("Hypergraph is not enabled or not initialized"))}getHypergraph(){return this.hypergraph}async enhanceImpactWithHypergraph(e,r){return this.hypergraph?Gd(this.hypergraph,e,r):r}async buildCodeIndexResultFromPaths(e){let{extractCodeIndex:r}=await import("./code-index-extractor-44HH36UG.js");return r(e)}async verifyCodePatternDetection(e,r){return Hd(e,r,this.consensusMixin,this.domainName)}async verifyImpactAnalysis(e,r){return jd(e,r,this.consensusMixin,this.domainName)}async verifyDependencyMapping(e,r){return Wd(e,r,this.consensusMixin,this.domainName)}};A();var js=class extends j{constructor(e,r,i,n={},s){super(e,r);this.agentCoordinator=i;this.llmRouter=s;this.pluginConfig=n}agentCoordinator;llmRouter;coordinator=null;knowledgeGraph=null;semanticAnalyzer=null;impactAnalyzer=null;pluginConfig;get name(){return"code-intelligence"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{index:this.index.bind(this),search:this.search.bind(this),analyzeImpact:this.analyzeImpact.bind(this),mapDependencies:this.mapDependencies.bind(this),getDependencies:this.mapDependencies.bind(this),queryKG:this.queryKG.bind(this),getMetrics:this.getMetrics.bind(this),getCoordinator:()=>this.coordinator,getKnowledgeGraph:()=>this.knowledgeGraph,getSemanticAnalyzer:()=>this.semanticAnalyzer,getImpactAnalyzer:()=>this.impactAnalyzer}}getTaskHandlers(){return new Map([["index",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.paths;if(!r||r.length===0)return p(new Error("Invalid index payload: missing paths"));let i=e.language?[e.language]:e.languages;return this.coordinator.index({paths:r,languages:i})}],["search",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.query;return r?this.coordinator.search({query:r,type:e.type??"semantic",limit:e.limit}):p(new Error("Invalid search payload: missing query"))}],["analyze-impact",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.changedFiles;return!r||r.length===0?p(new Error("Invalid analyze-impact payload: missing changedFiles")):this.coordinator.analyzeImpact({changedFiles:r})}],["query-dependencies",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.file,n=e.files??(r?[r]:void 0);return!n||n.length===0?p(new Error("Invalid query-dependencies payload: missing file or files")):this.coordinator.mapDependencies({files:n,direction:e.direction??"both",depth:e.depth})}]])}async onInitialize(){this.knowledgeGraph=new xt({memory:this.memory,llmRouter:this.llmRouter},this.pluginConfig.knowledgeGraph),this.semanticAnalyzer=new _t(this.memory,this.pluginConfig.semanticAnalyzer),this.impactAnalyzer=new Br(this.memory,this.knowledgeGraph,this.pluginConfig.impactAnalyzer),this.coordinator=new zi(this.eventBus,this.memory,this.agentCoordinator,this.pluginConfig.coordinator,this.llmRouter),await this.coordinator.initialize(),this.updateHealth({status:"idle",agents:{total:0,active:0,idle:0,failed:0},lastActivity:new Date,errors:[]})}async onDispose(){this.coordinator&&await this.coordinator.dispose(),this.coordinator=null,this.knowledgeGraph=null,this.semanticAnalyzer=null,this.impactAnalyzer=null}subscribeToEvents(){this.eventBus.subscribe("test-generation.TestGenerated",this.handleTestGenerated.bind(this)),this.eventBus.subscribe("coverage-analysis.CoverageGapDetected",this.handleCoverageGap.bind(this)),this.eventBus.subscribe("defect-intelligence.DefectPredicted",this.handleDefectPredicted.bind(this))}async onEvent(e){switch(this.updateHealth({lastActivity:new Date}),e.type){case"test-generation.TestGenerated":await this.handleTestGenerated(e);break;case"coverage-analysis.CoverageGapDetected":await this.handleCoverageGap(e);break;case"defect-intelligence.DefectPredicted":await this.handleDefectPredicted(e);break;default:break}}async index(e){this.ensureInitialized();try{let r=await this.coordinator.index(e);return r.success?this.trackSuccessfulOperation("index",r.value):this.trackFailedOperation("index",r.error),r}catch(r){return this.handleError(r)}}async search(e){this.ensureInitialized();try{let r=await this.coordinator.search(e);return r.success?this.trackSuccessfulOperation("search",r.value):this.trackFailedOperation("search",r.error),r}catch(r){return this.handleError(r)}}async analyzeImpact(e){this.ensureInitialized();try{let r=await this.coordinator.analyzeImpact(e);return r.success?this.trackSuccessfulOperation("impact",r.value):this.trackFailedOperation("impact",r.error),r}catch(r){return this.handleError(r)}}async mapDependencies(e){this.ensureInitialized();try{let r=await this.coordinator.mapDependencies(e);return r.success?this.trackSuccessfulOperation("dependency",r.value):this.trackFailedOperation("dependency",r.error),r}catch(r){return this.handleError(r)}}async queryKG(e){this.ensureInitialized();try{let r=await this.coordinator.queryKG(e);return r.success?this.trackSuccessfulOperation("query",r.value):this.trackFailedOperation("query",r.error),r}catch(r){return this.handleError(r)}}async getMetrics(){this.ensureInitialized();try{let e=this.getHealth();return{success:!0,value:{indexed:e.agents.total,queries:e.agents.idle,impacts:e.agents.active}}}catch(e){return this.handleError(e)}}async handleTestGenerated(e){let r=e.payload;await this.memory.set(`code-intelligence:test-mapping:${r.testId}`,{testFile:r.testFile,sourceFile:r.sourceFile,generatedAt:new Date().toISOString()},{namespace:"code-intelligence",ttl:86400*30})}async handleCoverageGap(e){let r=e.payload;await this.memory.set(`code-intelligence:coverage-gap:${r.gapId}`,r,{namespace:"code-intelligence",ttl:86400*7})}async handleDefectPredicted(e){let r=e.payload;await this.memory.set(`code-intelligence:defect-prediction:${r.predictionId}`,r,{namespace:"code-intelligence",ttl:86400*7})}ensureInitialized(){if(!this._initialized)throw new Error("CodeIntelligencePlugin is not initialized");if(!this.coordinator||!this.knowledgeGraph||!this.semanticAnalyzer||!this.impactAnalyzer)throw new Error("CodeIntelligencePlugin services are not available")}handleError(e){let r=y(e),i=this.getHealth();return this.updateHealth({errors:[...i.errors.slice(-9),r.message],status:i.errors.length>=5?"degraded":i.status}),{success:!1,error:r}}trackSuccessfulOperation(e,r){let i=this.getHealth();this.updateHealth({agents:{...i.agents,total:i.agents.total+1,idle:i.agents.idle+1},lastActivity:new Date})}trackFailedOperation(e,r){let i=this.getHealth();this.updateHealth({agents:{...i.agents,failed:i.agents.failed+1},errors:[...i.errors.slice(-9),r.message]})}};function Mc(u,t,e,r,i){return new js(u,t,e,r,i)}M();A();var Ws={defaultRuleSets:["owasp-top-10","cwe-sans-25"],maxConcurrentScans:4,timeout:3e5,enableFalsePositiveDetection:!0,dastMaxDepth:5,dastActiveScanning:!1,enableLLMAnalysis:!0,llmModelTier:4,enableSemgrep:!0};M();var Fc=[{id:"sqli-string-concat",pattern:/query\s*\(\s*['"`].*\+.*['"`]\s*\)/g,category:"injection",severity:"critical",title:"SQL Injection via String Concatenation",description:"SQL query constructed using string concatenation with potentially untrusted input",owaspId:"A03:2021",cweId:"CWE-89",remediation:"Use parameterized queries or prepared statements instead of string concatenation",fixExample:'db.query("SELECT * FROM users WHERE id = $1", [userId])'},{id:"sqli-template-literal",pattern:/execute\s*\(\s*`[^`]*\$\{[^}]+\}[^`]*`\s*\)/g,category:"injection",severity:"critical",title:"SQL Injection via Template Literal",description:"SQL query constructed using template literals with embedded expressions",owaspId:"A03:2021",cweId:"CWE-89",remediation:"Use parameterized queries instead of template literals for SQL",fixExample:'db.execute("DELETE FROM users WHERE id = ?", [userId])'},{id:"sqli-raw-query",pattern:/\.raw\s*\(\s*['"`].*\+|\.raw\s*\(\s*`[^`]*\$\{/g,category:"injection",severity:"high",title:"SQL Injection via Raw Query",description:"Raw SQL query with potential user input interpolation",owaspId:"A03:2021",cweId:"CWE-89",remediation:"Avoid raw queries with user input; use ORM methods or parameterized queries"},{id:"sqli-exec",pattern:/exec(?:ute)?(?:Sql|Query)?\s*\([^)]*\+[^)]*\)/gi,category:"injection",severity:"critical",title:"SQL Injection via Dynamic Execution",description:"Dynamic SQL execution with string concatenation detected",owaspId:"A03:2021",cweId:"CWE-89",remediation:"Never concatenate user input into SQL queries"}],Lc=[{id:"xss-innerhtml",pattern:/\.innerHTML\s*=\s*[^'"`;\n]+/g,category:"xss",severity:"high",title:"XSS via innerHTML Assignment",description:"Direct innerHTML assignment with potentially unsanitized content",owaspId:"A03:2021",cweId:"CWE-79",remediation:"Use textContent for text, or sanitize HTML with DOMPurify before innerHTML assignment",fixExample:"element.textContent = userInput; // or DOMPurify.sanitize(userInput)"},{id:"xss-document-write",pattern:/document\.write\s*\([^)]+\)/g,category:"xss",severity:"high",title:"XSS via document.write",description:"document.write() can execute scripts from untrusted data",owaspId:"A03:2021",cweId:"CWE-79",remediation:"Avoid document.write(); use DOM manipulation methods instead",fixExample:"document.body.appendChild(document.createTextNode(text))"},{id:"xss-dangerously-set",pattern:/dangerouslySetInnerHTML\s*=\s*\{/g,category:"xss",severity:"medium",title:"React dangerouslySetInnerHTML Usage",description:"dangerouslySetInnerHTML bypasses React XSS protections",owaspId:"A03:2021",cweId:"CWE-79",remediation:"Sanitize HTML content with DOMPurify before using dangerouslySetInnerHTML",fixExample:"dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(content) }}"},{id:"xss-eval",pattern:/eval\s*\([^)]+\)/g,category:"xss",severity:"critical",title:"Code Injection via eval()",description:"eval() executes arbitrary code and is a major security risk",owaspId:"A03:2021",cweId:"CWE-95",remediation:"Never use eval(); use JSON.parse() for JSON data or safer alternatives",fixExample:"JSON.parse(jsonString) // instead of eval(jsonString)"},{id:"xss-new-function",pattern:/new\s+Function\s*\([^)]+\)/g,category:"xss",severity:"critical",title:"Code Injection via Function Constructor",description:"Function constructor can execute arbitrary code like eval()",owaspId:"A03:2021",cweId:"CWE-95",remediation:"Avoid the Function constructor; use predefined functions instead"},{id:"xss-outerhtml",pattern:/\.outerHTML\s*=\s*[^'"`;\n]+/g,category:"xss",severity:"high",title:"XSS via outerHTML Assignment",description:"Direct outerHTML assignment with potentially unsanitized content",owaspId:"A03:2021",cweId:"CWE-79",remediation:"Sanitize content before outerHTML assignment"}],$c=[{id:"secret-aws-access-key",pattern:/['"`]AKIA[0-9A-Z]{16}['"`]/g,category:"sensitive-data",severity:"critical",title:"AWS Access Key Detected",description:"Hardcoded AWS Access Key ID found in source code",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Use environment variables or AWS Secrets Manager for credentials",fixExample:"const accessKey = process.env.AWS_ACCESS_KEY_ID"},{id:"secret-aws-secret-key",pattern:/['"`][A-Za-z0-9/+=]{40}['"`]/g,category:"sensitive-data",severity:"critical",title:"Potential AWS Secret Key Detected",description:"Potential hardcoded AWS Secret Access Key found",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Store secrets in environment variables or secrets manager"},{id:"secret-openai-key",pattern:/['"`]sk-[a-zA-Z0-9]{48,}['"`]/g,category:"sensitive-data",severity:"critical",title:"OpenAI API Key Detected",description:"Hardcoded OpenAI API key found in source code",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Use environment variables for API keys",fixExample:"const apiKey = process.env.OPENAI_API_KEY"},{id:"secret-generic-password",pattern:/password\s*[:=]\s*['"`][^'"`]{4,}['"`]/gi,category:"sensitive-data",severity:"high",title:"Hardcoded Password Detected",description:"Hardcoded password found in source code",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Never hardcode passwords; use environment variables or secrets manager",fixExample:"const password = process.env.DB_PASSWORD"},{id:"secret-api-key",pattern:/api[_-]?key\s*[:=]\s*['"`][a-zA-Z0-9_\-]{16,}['"`]/gi,category:"sensitive-data",severity:"high",title:"Hardcoded API Key Detected",description:"Hardcoded API key found in source code",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Use environment variables for API keys",fixExample:"const apiKey = process.env.API_KEY"},{id:"secret-jwt",pattern:/['"`]eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+['"`]/g,category:"sensitive-data",severity:"high",title:"Hardcoded JWT Token Detected",description:"Hardcoded JWT token found in source code",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Generate JWT tokens dynamically; never hardcode them"},{id:"secret-private-key",pattern:/-----BEGIN\s+(RSA|EC|OPENSSH|DSA)?\s*PRIVATE\s+KEY-----/g,category:"sensitive-data",severity:"critical",title:"Private Key Detected",description:"Private key found in source code",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Store private keys in secure key management systems, not in code"},{id:"secret-github-token",pattern:/['"`]ghp_[a-zA-Z0-9]{36}['"`]|['"`]github_pat_[a-zA-Z0-9]{22}_[a-zA-Z0-9]{59}['"`]/g,category:"sensitive-data",severity:"critical",title:"GitHub Token Detected",description:"Hardcoded GitHub personal access token found",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Use environment variables or GitHub Actions secrets"},{id:"secret-slack-token",pattern:/['"`]xox[baprs]-[0-9]{10,13}-[0-9]{10,13}[a-zA-Z0-9-]*['"`]/g,category:"sensitive-data",severity:"high",title:"Slack Token Detected",description:"Hardcoded Slack token found in source code",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Use environment variables for Slack tokens"},{id:"secret-generic-assignment",pattern:/\b\w*(?:SECRET|secret)(?:_KEY|_key|Key)?\s*[:=]\s*['"`][^'"`]{4,}['"`]/g,category:"sensitive-data",severity:"high",title:"Generic Secret Assignment Detected",description:"Hardcoded secret assignment (SECRET_KEY, JWT_SECRET, APP_SECRET, etc.) found in source code",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Use environment variables or a secrets manager instead of hardcoding secrets",fixExample:"const secretKey = process.env.SECRET_KEY"}],Oc=[{id:"path-traversal-readfile",pattern:/(?:readFile|readFileSync)\s*\([^)]*\+/g,category:"access-control",severity:"high",title:"Path Traversal via File Read",description:"File read operation with concatenated path may allow directory traversal",owaspId:"A01:2021",cweId:"CWE-22",remediation:"Validate and sanitize file paths; use path.resolve() and check against base directory",fixExample:"const safePath = path.resolve(baseDir, path.basename(userInput))"},{id:"path-traversal-pattern",pattern:/\.\.\/.*\.\.\//g,category:"access-control",severity:"medium",title:"Path Traversal Pattern Detected",description:"Suspicious path traversal pattern (../) found in code",owaspId:"A01:2021",cweId:"CWE-22",remediation:"Validate paths and ensure they resolve within expected directories"},{id:"path-traversal-writefile",pattern:/(?:writeFile|writeFileSync)\s*\([^)]*\+/g,category:"access-control",severity:"high",title:"Path Traversal via File Write",description:"File write operation with concatenated path may allow directory traversal",owaspId:"A01:2021",cweId:"CWE-22",remediation:"Validate file paths before writing; ensure path is within allowed directory"},{id:"path-traversal-createstream",pattern:/createReadStream\s*\([^)]*\+/g,category:"access-control",severity:"high",title:"Path Traversal via Stream",description:"Stream creation with concatenated path may allow directory traversal",owaspId:"A01:2021",cweId:"CWE-22",remediation:"Validate and sanitize file paths before creating streams"}],Nc=[{id:"cmd-injection-exec",pattern:/exec\s*\([^)]*\+[^)]*\)|exec\s*\(\s*`[^`]*\$\{/g,category:"injection",severity:"critical",title:"Command Injection via exec()",description:"Shell command execution with unsanitized input",owaspId:"A03:2021",cweId:"CWE-78",remediation:"Use execFile() with argument array instead of exec() with string concatenation",fixExample:'execFile("command", [arg1, arg2], callback)'},{id:"cmd-injection-spawn",pattern:/spawn\s*\(\s*[^,]+\+|spawn\s*\(\s*`[^`]*\$\{/g,category:"injection",severity:"critical",title:"Command Injection via spawn()",description:"Process spawn with potentially unsanitized command",owaspId:"A03:2021",cweId:"CWE-78",remediation:"Use spawn with command and args array; validate inputs",fixExample:'spawn("command", [sanitizedArg1, sanitizedArg2])'},{id:"cmd-injection-shell-true",pattern:/spawn\s*\([^)]+,\s*\{[^}]*shell\s*:\s*true/g,category:"injection",severity:"high",title:"Dangerous Shell Option in spawn()",description:"spawn() with shell: true can enable command injection",owaspId:"A03:2021",cweId:"CWE-78",remediation:"Avoid shell: true option; use direct command execution"}],Vc=[{id:"misc-cors-wildcard",pattern:/cors\s*\(\s*\{[^}]*origin\s*:\s*['"]\*['"]/gi,category:"security-misconfiguration",severity:"medium",title:"Permissive CORS Configuration",description:"CORS allows all origins (*) which may expose sensitive data",owaspId:"A05:2021",cweId:"CWE-942",remediation:"Restrict CORS to specific trusted origins",fixExample:'cors({ origin: ["https://trusted-domain.com"] })'},{id:"misc-debug-enabled",pattern:/debug\s*[:=]\s*true|DEBUG\s*[:=]\s*['"]?true['"]?/gi,category:"security-misconfiguration",severity:"low",title:"Debug Mode Enabled",description:"Debug mode may expose sensitive information in production",owaspId:"A05:2021",cweId:"CWE-489",remediation:"Disable debug mode in production environments"},{id:"misc-ssl-disabled",pattern:/rejectUnauthorized\s*:\s*false|NODE_TLS_REJECT_UNAUTHORIZED\s*=\s*['"]?0['"]?/g,category:"security-misconfiguration",severity:"high",title:"TLS Certificate Validation Disabled",description:"Disabling TLS certificate validation exposes to MITM attacks",owaspId:"A05:2021",cweId:"CWE-295",remediation:"Always enable TLS certificate validation in production"},{id:"misc-helmet-missing",pattern:/app\.use\s*\(\s*express\s*\(\s*\)\s*\)/g,category:"security-misconfiguration",severity:"low",title:"Express App Without Security Headers",description:"Express app initialized without helmet or security headers",owaspId:"A05:2021",cweId:"CWE-693",remediation:"Use helmet middleware for security headers",fixExample:"app.use(helmet())"}],_c=[{id:"deser-yaml-load",pattern:/yaml\.load\s*\([^)]+\)/g,category:"insecure-deserialization",severity:"high",title:"Unsafe YAML Deserialization",description:"yaml.load() can execute arbitrary code from untrusted YAML",owaspId:"A08:2021",cweId:"CWE-502",remediation:"Use yaml.safeLoad() or schema-constrained loading",fixExample:"yaml.load(content, { schema: yaml.SAFE_SCHEMA })"},{id:"deser-serialize-js",pattern:/serialize\s*\([^)]+\)|unserialize\s*\([^)]+\)/g,category:"insecure-deserialization",severity:"high",title:"Unsafe Serialization Function",description:"Node serialize/unserialize functions can execute arbitrary code",owaspId:"A08:2021",cweId:"CWE-502",remediation:"Use JSON.parse/stringify for serialization"}],zc=[{id:"auth-weak-jwt-secret",pattern:/jwt\.sign\s*\([^)]+,\s*['"][a-zA-Z0-9]{1,16}['"]/g,category:"broken-auth",severity:"high",title:"Weak JWT Secret",description:"JWT signed with a weak or short secret key",owaspId:"A07:2021",cweId:"CWE-327",remediation:"Use a strong, randomly generated secret of at least 256 bits"},{id:"auth-no-algorithm",pattern:/jwt\.verify\s*\([^)]+\)\s*(?!.*algorithm)/g,category:"broken-auth",severity:"medium",title:"JWT Without Algorithm Specification",description:"JWT verification without explicit algorithm can be exploited",owaspId:"A07:2021",cweId:"CWE-347",remediation:"Always specify the expected algorithm in JWT verification",fixExample:'jwt.verify(token, secret, { algorithms: ["HS256"] })'}],Us=[...Fc,...Lc,...$c,...Oc,...Nc,...Vc,..._c,...zc],Bi=[{id:"owasp-top-10",name:"OWASP Top 10",description:"OWASP Top 10 most critical security risks",ruleCount:45,categories:["injection","broken-auth","sensitive-data","xxe","access-control","security-misconfiguration","xss","insecure-deserialization","vulnerable-components","insufficient-logging"]},{id:"cwe-sans-25",name:"CWE/SANS Top 25",description:"Most dangerous software errors",ruleCount:38,categories:["injection","xss","access-control","sensitive-data","broken-auth"]},{id:"nodejs-security",name:"Node.js Security",description:"Node.js specific security rules",ruleCount:25,categories:["injection","xss","sensitive-data","security-misconfiguration"]},{id:"typescript-security",name:"TypeScript Security",description:"TypeScript specific security rules",ruleCount:20,categories:["injection","xss","sensitive-data"]}];A();H();A();H();import{execFile as Cy}from"child_process";import{promisify as Sy}from"util";import*as Kd from"path";var Bc=Sy(Cy);async function qi(){try{return await Bc("semgrep",["--version"],{timeout:5e3}),!0}catch{return!1}}async function Ud(){try{let{stdout:u}=await Bc("semgrep",["--version"],{timeout:5e3});return u.trim()}catch{return null}}async function Ry(u){let t={target:u.target||".",config:u.config||"auto",exclude:u.exclude||["node_modules",".git","dist","build","coverage"],maxFileSize:u.maxFileSize||5e6,timeout:u.timeout||300,verbose:u.verbose||!1};if(!await qi())return{success:!1,findings:[],errors:["Semgrep is not installed. Install with: pip install semgrep"]};try{let r=["scan",`--config=${t.config}`,"--json",t.verbose?"--verbose":"--quiet",`--max-target-bytes=${t.maxFileSize}`];for(let o of t.exclude)r.push(`--exclude=${o}`);r.push(t.target);let i=(t.timeout??300)*1e3,{stdout:n,stderr:s}=await Bc("semgrep",r,{timeout:i,maxBuffer:50*1024*1024,cwd:Kd.isAbsolute(t.target)?void 0:process.cwd()}),a=Qd(n);return s&&t.verbose&&a.errors.push(s),a.version=await Ud()||void 0,a}catch(r){let i=r;if(i.stdout)try{let n=Qd(i.stdout);return n.version=await Ud()||void 0,n}catch{}return{success:!1,findings:[],errors:[i.message??String(r)]}}}function Qd(u){try{let t=E(u),e=t.results||t.findings||[],r=t.errors?.map(i=>i.message||String(i))||[];return{success:!0,findings:e.map(i=>({check_id:i.check_id||i.rule_id||"unknown",path:i.path,start:{line:i.start?.line||1,col:i.start?.col||1},end:{line:i.end?.line||i.start?.line||1,col:i.end?.col||1},extra:{message:i.extra?.message||i.message||"Security issue detected",severity:i.extra?.severity||i.severity||"WARNING",lines:i.extra?.lines||"",metadata:{cwe:i.extra?.metadata?.cwe||i.metadata?.cwe,owasp:i.extra?.metadata?.owasp||i.metadata?.owasp,category:i.extra?.metadata?.category||i.metadata?.category,description:i.extra?.metadata?.description||i.metadata?.description,fix:i.extra?.metadata?.fix||i.extra?.fix,references:i.extra?.metadata?.references||i.metadata?.references,confidence:i.extra?.metadata?.confidence||i.metadata?.confidence}}})),errors:r}}catch(t){return{success:!1,findings:[],errors:[`Failed to parse semgrep output: ${T(t)}`]}}}async function Qs(u,t,e){let r={"owasp-top-10":"p/owasp-top-ten","cwe-sans-25":"p/cwe-top-25","nodejs-security":"p/nodejs","typescript-security":"p/typescript","javascript-security":"p/javascript","react-security":"p/react","express-security":"p/express",secrets:"p/secrets","sql-injection":"p/sql-injection",xss:"p/xss","command-injection":"p/command-injection","path-traversal":"p/path-traversal"},i=t.map(n=>r[n]||`p/${n}`).join(",");return Ry({...e,target:u,config:i||"auto"})}function Ty(u){return{ERROR:"high",WARNING:"medium",INFO:"low"}[u]||"medium"}function Ks(u){return u.map(t=>({id:t.check_id,title:t.check_id.split(".").pop()||t.check_id,description:t.extra.message,severity:Ty(t.extra.severity),file:t.path,line:t.start.line,column:t.start.col,snippet:t.extra.lines,cweId:t.extra.metadata?.cwe?.[0],owaspCategory:t.extra.metadata?.owasp?.[0],remediation:t.extra.metadata?.fix||"Review and fix the identified security issue",references:t.extra.metadata?.references||[]}))}var Ay=R.create("security-compliance/sast-scanner"),wr=class{config;memory;llmRouter;activeScans;constructor(t,e,r,i){this.config=t,this.memory=e,this.llmRouter=r,this.activeScans=i||new Map}async scanFiles(t){return this.scanWithRules(t,this.config.defaultRuleSets)}async scanWithRules(t,e){let r=v();try{if(t.length===0)return p(new Error("No files provided for scanning"));this.activeScans.set(r,"running");let i=Date.now(),n=Bi.filter(g=>e.includes(g.id));if(n.length===0)return p(new Error(`No valid rule sets found: ${e.join(", ")}`));let[s,a]=await Promise.all([this.runPatternScanning(t,n),this.runSemgrepScanning(t,e)]),o=this.mergeVulnerabilities(s.vulnerabilities,a),c=s.linesScanned,l=Date.now()-i,d=this.calculateSummary(o,t.length,l),m=n.reduce((g,b)=>g+b.ruleCount,0),h={filesScanned:t.length,linesScanned:c,rulesApplied:m+(a.length>0?a.length:0)};return await this.storeScanResults(r,"sast",o,d),this.activeScans.set(r,"completed"),f({scanId:r,vulnerabilities:o,summary:d,coverage:h})}catch(i){return this.activeScans.set(r,"failed"),p(y(i))}}async runPatternScanning(t,e){let r=[],i=0;for(let n of t){let s=await this.analyzeFile(n,e);r.push(...s.vulnerabilities),i+=s.linesScanned}return{vulnerabilities:r,linesScanned:i}}async runSemgrepScanning(t,e){if(!this.config.enableSemgrep)return[];try{if(!await qi())return[];let i=this.resolveTargetDirectory(t),n=await Qs(i,e);return!n.success||n.findings.length===0?[]:Ks(n.findings).map(a=>({id:v(),cveId:void 0,title:a.title,description:`[semgrep] ${a.description}`,severity:a.severity,category:this.mapSemgrepCategory(a.owaspCategory),location:{file:a.file,line:a.line,column:a.column,snippet:a.snippet},remediation:{description:a.remediation,estimatedEffort:"moderate",automatable:!1},references:a.references}))}catch{return[]}}resolveTargetDirectory(t){if(t.length===0)return".";if(t.length===1)return t[0].directory||".";let e=t.map(a=>a.directory||"."),r=e[0],i=r.length;for(let a=1;a<e.length;a++){let o=e[a],c=Math.min(i,o.length),l=0;for(;l<c&&r[l]===o[l];)l++;i=l}let n=r.substring(0,i),s=n.lastIndexOf("/");return s>0?n.substring(0,s):n||"."}mapSemgrepCategory(t){if(!t)return"injection";let e={A01:"access-control",A02:"sensitive-data",A03:"injection",A04:"insecure-deserialization",A05:"security-misconfiguration",A06:"vulnerable-components",A07:"broken-auth",A08:"insecure-deserialization",A09:"insufficient-logging",A10:"xxe"};for(let[r,i]of Object.entries(e))if(t.startsWith(r))return i;return"injection"}mergeVulnerabilities(t,e){if(e.length===0)return t;if(t.length===0)return e;let r=new Set(t.map(n=>`${n.location.file}:${n.location.line??0}:${n.category}`)),i=e.filter(n=>!r.has(`${n.location.file}:${n.location.line??0}:${n.category}`));return[...t,...i]}async getAvailableRuleSets(){let t=await this.memory.get("security:custom-rule-sets");return[...Bi,...t||[]]}async checkFalsePositive(t){try{if(!this.config.enableFalsePositiveDetection)return f({isFalsePositive:!1,confidence:0,reason:"False positive detection is disabled"});let e=await this.analyzeFalsePositive(t);return await this.memory.set(`security:fp-check:${t.id}`,{vulnerability:t,analysis:e},{namespace:"security-compliance",ttl:86400*30}),f(e)}catch(e){return p(y(e))}}async analyzeFile(t,e){let r=[],i=t.value,n=t.extension,s,a;try{s=await(await import("fs/promises")).readFile(i,"utf-8"),a=s.split(`
|
|
2898
2898
|
`)}catch{return{vulnerabilities:[],linesScanned:0}}let o=a.length;if(!["ts","tsx","js","jsx","mjs","cjs"].includes(n))return{vulnerabilities:[],linesScanned:o};let l=new Set(e.flatMap(m=>m.categories)),d=Us.filter(m=>l.has(m.category));for(let m of d){let h=this.findPatternMatches(s,a,m);for(let g of h)this.isInComment(s,g.index)||this.isInDocumentation(g.snippet)||this.hasNosecAnnotation(a,g.line)||r.push(this.createVulnerabilityFromPattern(m,i,g))}return{vulnerabilities:r,linesScanned:o}}findPatternMatches(t,e,r){let i=[],n=new RegExp(r.pattern.source,r.pattern.flags),s;for(;(s=n.exec(t))!==null;){let a=s.index,{line:o,column:c}=this.getLineAndColumn(t,a),l=[],d=Math.max(0,o-2),m=Math.min(e.length-1,o+1);for(let g=d;g<=m;g++)l.push(e[g]);let h=l.join(`
|
|
2899
2899
|
`);i.push({index:a,line:o+1,column:c+1,snippet:h})}return i}getLineAndColumn(t,e){let i=t.substring(0,e).split(`
|
|
2900
2900
|
`),n=i.length-1,s=i[i.length-1].length;return{line:n,column:s}}isInComment(t,e){let r=t.substring(0,e),i=r.lastIndexOf(`
|
|
@@ -2921,7 +2921,7 @@ Provide detailed remediation advice specific to this code.`}],model:r,maxTokens:
|
|
|
2921
2921
|
`);ca.generalLog.some(w=>w.test(g))||e.push({file:n,line:c+1,snippet:l.trim().substring(0,100),pattern:"missing-audit-log",severity:"warning"})}for(let d of ca.sensitiveInLogs)d.test(l)&&r.push({file:n,line:c+1,snippet:l.trim().substring(0,100),pattern:"sensitive-data-logged",severity:"critical"})}}return{hasAuditLogging:i,sensitiveOperationsWithoutLogging:e,sensitiveDataInLogs:r}}async analyzeDataProtection(t){let e=[],r=[],i=[];for(let n of t){let s=await this.fileReader.readFile(n);if(!s.success)continue;let a=s.value,o=a.split(`
|
|
2922
2922
|
`),c=la.validation.some(d=>d.test(a)),l=la.masking.some(d=>d.test(a));for(let d=0;d<o.length;d++){let m=o[d];for(let h of la.piiFields)if(h.test(m)){e.push({file:n,line:d+1,snippet:m.trim().substring(0,100),pattern:"pii-field",severity:"info"});let g=o.slice(Math.max(0,d-2),d+3).join(`
|
|
2923
2923
|
`);!la.masking.some(w=>w.test(g))&&!l&&r.push({file:n,line:d+1,snippet:m.trim().substring(0,100),pattern:"unmasked-pii",severity:"warning"})}}e.length>0&&!c&&i.push({file:n,line:1,snippet:"File contains PII fields without input validation",pattern:"missing-validation",severity:"warning"})}return{piiFields:e,unmaskedPii:r,missingValidation:i}}async analyzeSecurityControls(t){let e=[],r=[],i=!1,n=!1,s=!1,a=!1;for(let o of t){let c=await this.fileReader.readFile(o);if(!c.success)continue;let l=c.value;ua.rateLimiting.some(d=>d.test(l))&&(i=!0),ua.csrf.some(d=>d.test(l))&&(n=!0),ua.cors.some(d=>d.test(l))&&(s=!0),ua.sanitization.some(d=>d.test(l))&&(a=!0)}return i||r.push("Rate Limiting"),n||r.push("CSRF Protection"),s||r.push("CORS Configuration"),a||r.push("Input Validation/Sanitization"),{hasRateLimiting:i,hasCsrfProtection:n,hasCors:s,hasInputValidation:a,missingControls:r,vulnerabilities:e}}async scanForDataTypes(t,e){let r=new Map,i={pii:[/email|phone|ssn|social_security|address|date_of_birth|dob/i,/firstName|lastName|fullName/i,/passport|driverLicense|nationalId/i],phi:[/medical|diagnosis|prescription|patient|health/i,/insurance|provider|treatment/i,/blood_type|allergy|medication/i],financial:[/creditCard|cardNumber|cvv|expiry|account_number/i,/bank|routing|swift|iban/i,/transaction|payment|billing/i],credentials:[/password|secret|apikey|api_key|token|auth/i,/private_key|certificate|credential/i],biometric:[/fingerprint|faceId|retina|voice_print/i,/biometric|facial_recognition/i]};for(let n of e)r.set(n,[]);for(let n of t){let s=await this.fileReader.readFile(n);if(!s.success)continue;let a=s.value.split(`
|
|
2924
|
-
`);for(let o=0;o<a.length;o++){let c=a[o];for(let l of e){let d=i[l]||[];for(let m of d)if(m.test(c)){let h=r.get(l)||[];h.push({file:n,line:o+1,snippet:c.trim().substring(0,100),pattern:l,severity:"info"}),r.set(l,h);break}}}}return r}},Qc=null;function Kc(){return Qc||(Qc=new da),Qc}var Xd=["ls","cat","echo","grep","find","head","tail","wc","npm","node","yarn","pnpm","git","jest","vitest","playwright"],Zd=[/;/,/&&/,/\|\|/,/\|/,/`[^`]*`/,/\$\([^)]*\)/,/>\s*\/dev\/sd/i,/>\s*\/etc\//i],My=/[|;&$`<>{}[\]!#*?~]/g,Wi=class{name="command-injection";defaultAllowedCommands;constructor(t=Xd){this.defaultAllowedCommands=t}getRiskLevel(){return"critical"}validate(t,e={}){let r=e.allowedCommands??this.defaultAllowedCommands;return this.validateCommand(t,r)}validateCommand(t,e=this.defaultAllowedCommands){let r=[];for(let a of Zd)a.test(t)&&r.push(a.source);if(r.length>0)return{valid:!1,error:"Command contains blocked patterns",blockedPatterns:r,riskLevel:"critical"};let i=t.trim().split(/\s+/),n=i[0].split("/").pop()||"";return e.includes(n)?{valid:!0,sanitizedCommand:i.map((a,o)=>o===0?a:a.replace(My,"")).join(" "),blockedPatterns:[],riskLevel:"none"}:{valid:!1,error:`Command '${n}' is not in the allowed list`,blockedPatterns:[],riskLevel:"high"}}escapeShellArg(t){return`'${t.replace(/'/g,"'\\''")}'`}},Yd=new Wi,ma=(u,t)=>t?Yd.validateCommand(u,t):Yd.validate(u);var em={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/","`":"`","=":"="},tm=[/('|")\s*;\s*--/i,/'\s*OR\s+'1'\s*=\s*'1/i,/"\s*OR\s+"1"\s*=\s*"1/i,/UNION\s+SELECT/i,/INSERT\s+INTO/i,/DROP\s+TABLE/i,/DELETE\s+FROM/i,/UPDATE\s+[^\s.!]+(?:\.[^\s.!]+)*\s+SET/i,/EXEC(\s+|\()sp_/i,/xp_cmdshell/i],rm=/[|;&$`<>{}[\]!#*?~]/g,im=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,pa=class{name="input-sanitization";getRiskLevel(){return"high"}sanitize(t,e={}){let{maxLength:r=1e4,allowedChars:i,stripHtml:n=!0,stripSql:s=!0,escapeShell:a=!0,trim:o=!0,stripControlChars:c=!0}=e,l=t;if(c&&(l=l.replace(im,"")),o&&(l=l.trim()),l.length>r&&(l=l.substring(0,r)),n&&(l=this.stripHtmlTags(l)),s)for(let d of tm)l=l.replace(d,"");return a&&(l=l.replace(rm,"")),i&&(l=l.split("").filter(d=>i.test(d)).join("")),l}escapeHtml(t){return t.replace(/[&<>"'`=/]/g,e=>em[e]||e)}stripHtmlTags(t){t.length>1e5&&(t=t.slice(0,1e5));let r=t,i;do{i=r.length;let n="",s=!1;for(let a=0;a<r.length;a++){let o=r[a];o==="<"?s=!0:o===">"&&s?s=!1:s||(n+=o)}r=n}while(r.length<i&&r.length>0);return r=r.replace(/</g,"<").replace(/>/g,">"),r}},Kq=new pa;import{createHash as nm,timingSafeEqual as Fy,randomBytes as Ly}from"crypto";var ha=class{name="crypto-security";getRiskLevel(){return"critical"}timingSafeCompare(t,e){let r=Math.max(t.length,e.length),i=t.padEnd(r,"\0"),n=e.padEnd(r,"\0");try{return Fy(Buffer.from(i),Buffer.from(n))}catch{return!1}}timingSafeHashCompare(t,e){let r=nm("sha256").update(t).digest("hex");return this.timingSafeCompare(r,e)}generateSecureToken(t=32){return Ly(t).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}secureHash(t,e){let r=e?`${e}:${t}`:t;return nm("sha256").update(r).digest("hex")}},Xq=new ha;A();H();var Sr=class{config;memory;osvClient;activeScans;constructor(t,e,r){this.config=t,this.memory=e,this.osvClient=new Hi({enableCache:!0}),this.activeScans=r||new Map}async scanDependencies(t){let e=v(),r=Date.now();try{if(Object.keys(t).length===0)return p(new Error("No dependencies provided for scanning"));this.activeScans.set(e,"running");let i=await this.osvClient.scanNpmDependencies(t),n=this.convertOSVVulnerabilities(i),s=Date.now()-r,a=new Set(i.map(c=>c.affectedPackage)),o=this.calculateSummary(n,Object.keys(t).length,s);return await this.storeScanResults(e,"dependency",n,o),this.activeScans.set(e,"completed"),f({scanId:e,vulnerabilities:n,packagesScanned:Object.keys(t).length,vulnerablePackages:a.size,summary:o,scanDurationMs:s})}catch(i){return this.activeScans.set(e,"failed"),p(y(i))}}async scanPackageJson(t){try{let r=await(await import("fs/promises")).readFile(t,"utf-8"),i=E(r),n={...i.dependencies||{},...i.devDependencies||{},...i.peerDependencies||{},...i.optionalDependencies||{}};return Object.keys(n).length===0?p(new Error("No dependencies found in package.json")):this.scanDependencies(n)}catch(e){return e instanceof SyntaxError?p(new Error(`Invalid JSON in package.json: ${e.message}`)):p(y(e))}}async getScanStatus(t){return this.activeScans.get(t)??"pending"}convertOSVVulnerabilities(t){return t.map(e=>{let r={file:"package.json",line:1,column:1,snippet:`"${e.affectedPackage}": "..."`},i={description:e.fixedVersions.length>0?`Update to version ${e.fixedVersions[0]} or later`:"No fixed version available; consider alternative packages",fixExample:e.fixedVersions.length>0?`npm install ${e.affectedPackage}@${e.fixedVersions[0]}`:void 0,estimatedEffort:"minor",automatable:!0};return{id:v(),cveId:e.cveIds[0],title:`${e.affectedPackage}: ${e.summary.substring(0,80)}`,description:e.details||e.summary,severity:this.mapOSVSeverity(e.severity),category:"vulnerable-components",location:r,remediation:i,references:e.references.slice(0,5)}})}mapOSVSeverity(t){return{critical:"critical",high:"high",medium:"medium",low:"low",unknown:"medium"}[t]}calculateSummary(t,e,r){let i={critical:0,high:0,medium:0,low:0,informational:0,totalFiles:e,scanDurationMs:r};for(let n of t)i[n.severity]++;return i}async storeScanResults(t,e,r,i){await this.memory.set(`security:scan:${t}`,{scanId:t,scanType:e,vulnerabilities:r,summary:i,timestamp:new Date().toISOString()},{namespace:"security-compliance",ttl:86400*7})}};A();var Ne=class{config;memory;llmRouter;activeScans=new Map;sastScanner;dastScanner;dependencyScanner;constructor(t,e={}){this.config={...Ws,...e},"memory"in t?(this.memory=t.memory,this.llmRouter=t.llmRouter):this.memory=t,this.sastScanner=new wr(this.config,this.memory,this.llmRouter,this.activeScans),this.dastScanner=new Cr(this.config,this.memory,this.activeScans),this.dependencyScanner=new Sr(this.config,this.memory,this.activeScans)}async scanFiles(t){return this.sastScanner.scanFiles(t)}async scanWithRules(t,e){return this.sastScanner.scanWithRules(t,e)}async getAvailableRuleSets(){return this.sastScanner.getAvailableRuleSets()}async checkFalsePositive(t){return this.sastScanner.checkFalsePositive(t)}async scanUrl(t,e){return this.dastScanner.scanUrl(t,e)}async scanAuthenticated(t,e,r){return this.dastScanner.scanAuthenticated(t,e,r)}async getScanStatus(t){return this.activeScans.get(t)??"pending"}async scanDependencies(t){return this.dependencyScanner.scanDependencies(t)}async scanPackageJson(t){return this.dependencyScanner.scanPackageJson(t)}async runFullScan(t,e,r){try{let i=await this.scanWithRules(t,this.config.defaultRuleSets);if(i.success===!1)return p(i.error);let n;if(e){let a=await this.scanUrl(e,r);a.success&&(n=a.value)}let s=this.combineSummaries(i.value.summary,n?.summary);return f({sastResult:i.value,dastResult:n,combinedSummary:s})}catch(i){return p(y(i))}}isLLMAnalysisAvailable(){return this.sastScanner.isLLMAnalysisAvailable()}getModelForTier(t){return this.sastScanner.getModelForTier(t)}async analyzeVulnerabilityWithLLM(t,e){return this.sastScanner.analyzeVulnerabilityWithLLM(t,e)}combineSummaries(t,e){return e?{critical:t.critical+e.critical,high:t.high+e.high,medium:t.medium+e.medium,low:t.low+e.low,informational:t.informational+e.informational,totalFiles:t.totalFiles+e.totalFiles,scanDurationMs:t.scanDurationMs+e.scanDurationMs}:t}};M();import*as Qi from"fs/promises";import*as Ki from"path";A();H();async function Jc(u,t){let e=await fetch(u,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),r=await e.json();return{ok:e.ok,status:e.status,data:r}}async function Ui(u){let t=await fetch(u,{method:"GET",headers:{Accept:"application/json"}}),e=await t.json();return{ok:t.ok,status:t.status,data:e}}var Yc={secretPatterns:[/(?:api[_-]?key|apikey)['":\s]*['"=]?\s*['"]?([a-zA-Z0-9_\-]{20,})['"]?/gi,/(?:password|passwd|pwd)['":\s]*['"=]?\s*['"]?([^\s'"]{8,})['"]?/gi,/(?:secret|token)['":\s]*['"=]?\s*['"]?([a-zA-Z0-9_\-]{16,})['"]?/gi,/(?:aws[_-]?access[_-]?key|aws[_-]?secret)['":\s]*['"=]?\s*['"]?([A-Z0-9]{20,})['"]?/gi,/-----BEGIN\s+(?:RSA\s+)?PRIVATE\s+KEY-----/gi,/ghp_[a-zA-Z0-9]{36}/g,/gho_[a-zA-Z0-9]{36}/g,/sk-[a-zA-Z0-9]{48}/g],excludePatterns:["node_modules","dist","build",".git","*.test.*","*.spec.*"],maxFileSizeKb:1024,enableHistoricalAnalysis:!0,riskThreshold:.7};M();import*as sm from"fs/promises";import*as am from"path";var Ny=R.create("security-compliance/security-auditor-sast");function Vy(){return[{id:"sqli-concat",pattern:/(?:query|execute|exec|run)\s*\(\s*(?:['"`].*?\s*\+|`[^`]*\$\{)/gi,title:"SQL Injection via String Concatenation",description:"SQL query constructed using string concatenation with potentially untrusted input",severity:"critical",category:"injection",remediation:"Use parameterized queries or prepared statements",fixExample:'db.query("SELECT * FROM users WHERE id = $1", [userId])',cweId:"CWE-89"},{id:"xss-innerhtml",pattern:/\.innerHTML\s*=\s*(?!['"`])/g,title:"XSS via innerHTML Assignment",description:"Direct innerHTML assignment with potentially unsanitized content",severity:"high",category:"xss",remediation:"Use textContent for text, or sanitize HTML with DOMPurify",fixExample:"element.textContent = userInput;",cweId:"CWE-79"},{id:"xss-document-write",pattern:/document\.write\s*\([^)]+\)/g,title:"XSS via document.write",description:"document.write() can execute scripts from untrusted data",severity:"high",category:"xss",remediation:"Avoid document.write(); use DOM manipulation methods",cweId:"CWE-79"},{id:"xss-eval",pattern:/(?<!\.)\beval\s*\([^)]+\)/g,title:"Code Injection via eval()",description:"eval() executes arbitrary code and is a major security risk",severity:"critical",category:"xss",remediation:"Never use eval(); use JSON.parse() for JSON data",fixExample:"JSON.parse(jsonString)",cweId:"CWE-95"},{id:"xss-dangerous-react",pattern:/dangerouslySetInnerHTML\s*=\s*\{/g,title:"React dangerouslySetInnerHTML Usage",description:"dangerouslySetInnerHTML bypasses React XSS protections",severity:"medium",category:"xss",remediation:"Sanitize HTML content with DOMPurify before use",fixExample:"dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(content) }}",cweId:"CWE-79"},{id:"cmd-injection-exec",pattern:/(?:child_process\.)?exec\s*\(\s*(?:[^,)]*\s*\+|`[^`]*\$\{)/g,title:"Command Injection via exec()",description:"Shell command execution with unsanitized input",severity:"critical",category:"injection",remediation:"Use execFile() with argument array instead of exec()",fixExample:'execFile("command", [arg1, arg2], callback)',cweId:"CWE-78"},{id:"cmd-injection-spawn-shell",pattern:/spawn\s*\([^)]+,\s*\{[^}]*shell\s*:\s*true/g,title:"Dangerous Shell Option in spawn()",description:"spawn() with shell: true can enable command injection",severity:"high",category:"injection",remediation:"Avoid shell: true option; use direct command execution",cweId:"CWE-78"},{id:"path-traversal-readfile",pattern:/(?:readFile|readFileSync)\s*\([^)]*\+/g,title:"Path Traversal via File Read",description:"File read operation with concatenated path may allow directory traversal",severity:"high",category:"access-control",remediation:"Validate and sanitize file paths; use path.resolve() and check against base directory",fixExample:"const safePath = path.resolve(baseDir, path.basename(userInput))",cweId:"CWE-22"},{id:"path-traversal-writefile",pattern:/(?:writeFile|writeFileSync)\s*\([^)]*\+/g,title:"Path Traversal via File Write",description:"File write operation with concatenated path may allow directory traversal",severity:"high",category:"access-control",remediation:"Validate file paths before writing; ensure path is within allowed directory",cweId:"CWE-22"},{id:"secret-private-key",pattern:/-----BEGIN\s+(?:RSA\s+)?PRIVATE\s+KEY-----/g,title:"Private Key Detected in Source",description:"Private key found in source code",severity:"critical",category:"sensitive-data",remediation:"Store private keys in secure key management systems, not in code",cweId:"CWE-798"},{id:"config-tls-disabled",pattern:/rejectUnauthorized\s*:\s*false/g,title:"TLS Certificate Validation Disabled",description:"Disabling TLS certificate validation exposes to MITM attacks",severity:"high",category:"security-misconfiguration",remediation:"Always enable TLS certificate validation in production",cweId:"CWE-295"},{id:"config-cors-wildcard",pattern:/cors\s*\(\s*\{[^}]*origin\s*:\s*['"]\*['"]/gi,title:"Permissive CORS Configuration",description:"CORS allows all origins (*) which may expose sensitive data",severity:"medium",category:"security-misconfiguration",remediation:"Restrict CORS to specific trusted origins",fixExample:'cors({ origin: ["https://trusted-domain.com"] })',cweId:"CWE-942"}]}async function om(u,t){let e=v(),r=Date.now(),i=[],n=0,s=0;try{let h=await u(process.cwd()),g=Vy();for(let b of h){if(t(b))continue;let w=am.extname(b).toLowerCase();if([".ts",".tsx",".js",".jsx",".mjs",".cjs"].includes(w))try{let C=await sm.readFile(b,"utf-8"),S=C.split(`
|
|
2924
|
+
`);for(let o=0;o<a.length;o++){let c=a[o];for(let l of e){let d=i[l]||[];for(let m of d)if(m.test(c)){let h=r.get(l)||[];h.push({file:n,line:o+1,snippet:c.trim().substring(0,100),pattern:l,severity:"info"}),r.set(l,h);break}}}}return r}},Qc=null;function Kc(){return Qc||(Qc=new da),Qc}var Xd=["ls","cat","echo","grep","find","head","tail","wc","npm","node","yarn","pnpm","git","jest","vitest","playwright"],Zd=[/;/,/&&/,/\|\|/,/\|/,/`[^`]*`/,/\$\([^)]*\)/,/>\s*\/dev\/sd/i,/>\s*\/etc\//i],My=/[|;&$`<>{}[\]!#*?~]/g,Wi=class{name="command-injection";defaultAllowedCommands;constructor(t=Xd){this.defaultAllowedCommands=t}getRiskLevel(){return"critical"}validate(t,e={}){let r=e.allowedCommands??this.defaultAllowedCommands;return this.validateCommand(t,r)}validateCommand(t,e=this.defaultAllowedCommands){let r=[];for(let a of Zd)a.test(t)&&r.push(a.source);if(r.length>0)return{valid:!1,error:"Command contains blocked patterns",blockedPatterns:r,riskLevel:"critical"};let i=t.trim().split(/\s+/),n=i[0].split("/").pop()||"";return e.includes(n)?{valid:!0,sanitizedCommand:i.map((a,o)=>o===0?a:a.replace(My,"")).join(" "),blockedPatterns:[],riskLevel:"none"}:{valid:!1,error:`Command '${n}' is not in the allowed list`,blockedPatterns:[],riskLevel:"high"}}escapeShellArg(t){return`'${t.replace(/'/g,"'\\''")}'`}},Yd=new Wi,ma=(u,t)=>t?Yd.validateCommand(u,t):Yd.validate(u);var em={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/","`":"`","=":"="},tm=[/('|")\s*;\s*--/i,/'\s*OR\s+'1'\s*=\s*'1/i,/"\s*OR\s+"1"\s*=\s*"1/i,/UNION\s+SELECT/i,/INSERT\s+INTO/i,/DROP\s+TABLE/i,/DELETE\s+FROM/i,/UPDATE\s+[^\s.!]+(?:\.[^\s.!]+)*\s+SET/i,/EXEC(\s+|\()sp_/i,/xp_cmdshell/i],rm=/[|;&$`<>{}[\]!#*?~]/g,im=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,pa=class{name="input-sanitization";getRiskLevel(){return"high"}sanitize(t,e={}){let{maxLength:r=1e4,allowedChars:i,stripHtml:n=!0,stripSql:s=!0,escapeShell:a=!0,trim:o=!0,stripControlChars:c=!0}=e,l=t;if(c&&(l=l.replace(im,"")),o&&(l=l.trim()),l.length>r&&(l=l.substring(0,r)),n&&(l=this.stripHtmlTags(l)),s)for(let d of tm)l=l.replace(d,"");return a&&(l=l.replace(rm,"")),i&&(l=l.split("").filter(d=>i.test(d)).join("")),l}escapeHtml(t){return t.replace(/[&<>"'`=/]/g,e=>em[e]||e)}stripHtmlTags(t){t.length>1e5&&(t=t.slice(0,1e5));let r=t,i;do{i=r.length;let n="",s=!1;for(let a=0;a<r.length;a++){let o=r[a];o==="<"?s=!0:o===">"&&s?s=!1:s||(n+=o)}r=n}while(r.length<i&&r.length>0);return r=r.replace(/</g,"<").replace(/>/g,">"),r}},gq=new pa;import{createHash as nm,timingSafeEqual as Fy,randomBytes as Ly}from"crypto";var ha=class{name="crypto-security";getRiskLevel(){return"critical"}timingSafeCompare(t,e){let r=Math.max(t.length,e.length),i=t.padEnd(r,"\0"),n=e.padEnd(r,"\0");try{return Fy(Buffer.from(i),Buffer.from(n))}catch{return!1}}timingSafeHashCompare(t,e){let r=nm("sha256").update(t).digest("hex");return this.timingSafeCompare(r,e)}generateSecureToken(t=32){return Ly(t).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}secureHash(t,e){let r=e?`${e}:${t}`:t;return nm("sha256").update(r).digest("hex")}},vq=new ha;A();H();var Sr=class{config;memory;osvClient;activeScans;constructor(t,e,r){this.config=t,this.memory=e,this.osvClient=new Hi({enableCache:!0}),this.activeScans=r||new Map}async scanDependencies(t){let e=v(),r=Date.now();try{if(Object.keys(t).length===0)return p(new Error("No dependencies provided for scanning"));this.activeScans.set(e,"running");let i=await this.osvClient.scanNpmDependencies(t),n=this.convertOSVVulnerabilities(i),s=Date.now()-r,a=new Set(i.map(c=>c.affectedPackage)),o=this.calculateSummary(n,Object.keys(t).length,s);return await this.storeScanResults(e,"dependency",n,o),this.activeScans.set(e,"completed"),f({scanId:e,vulnerabilities:n,packagesScanned:Object.keys(t).length,vulnerablePackages:a.size,summary:o,scanDurationMs:s})}catch(i){return this.activeScans.set(e,"failed"),p(y(i))}}async scanPackageJson(t){try{let r=await(await import("fs/promises")).readFile(t,"utf-8"),i=E(r),n={...i.dependencies||{},...i.devDependencies||{},...i.peerDependencies||{},...i.optionalDependencies||{}};return Object.keys(n).length===0?p(new Error("No dependencies found in package.json")):this.scanDependencies(n)}catch(e){return e instanceof SyntaxError?p(new Error(`Invalid JSON in package.json: ${e.message}`)):p(y(e))}}async getScanStatus(t){return this.activeScans.get(t)??"pending"}convertOSVVulnerabilities(t){return t.map(e=>{let r={file:"package.json",line:1,column:1,snippet:`"${e.affectedPackage}": "..."`},i={description:e.fixedVersions.length>0?`Update to version ${e.fixedVersions[0]} or later`:"No fixed version available; consider alternative packages",fixExample:e.fixedVersions.length>0?`npm install ${e.affectedPackage}@${e.fixedVersions[0]}`:void 0,estimatedEffort:"minor",automatable:!0};return{id:v(),cveId:e.cveIds[0],title:`${e.affectedPackage}: ${e.summary.substring(0,80)}`,description:e.details||e.summary,severity:this.mapOSVSeverity(e.severity),category:"vulnerable-components",location:r,remediation:i,references:e.references.slice(0,5)}})}mapOSVSeverity(t){return{critical:"critical",high:"high",medium:"medium",low:"low",unknown:"medium"}[t]}calculateSummary(t,e,r){let i={critical:0,high:0,medium:0,low:0,informational:0,totalFiles:e,scanDurationMs:r};for(let n of t)i[n.severity]++;return i}async storeScanResults(t,e,r,i){await this.memory.set(`security:scan:${t}`,{scanId:t,scanType:e,vulnerabilities:r,summary:i,timestamp:new Date().toISOString()},{namespace:"security-compliance",ttl:86400*7})}};A();var Ne=class{config;memory;llmRouter;activeScans=new Map;sastScanner;dastScanner;dependencyScanner;constructor(t,e={}){this.config={...Ws,...e},"memory"in t?(this.memory=t.memory,this.llmRouter=t.llmRouter):this.memory=t,this.sastScanner=new wr(this.config,this.memory,this.llmRouter,this.activeScans),this.dastScanner=new Cr(this.config,this.memory,this.activeScans),this.dependencyScanner=new Sr(this.config,this.memory,this.activeScans)}async scanFiles(t){return this.sastScanner.scanFiles(t)}async scanWithRules(t,e){return this.sastScanner.scanWithRules(t,e)}async getAvailableRuleSets(){return this.sastScanner.getAvailableRuleSets()}async checkFalsePositive(t){return this.sastScanner.checkFalsePositive(t)}async scanUrl(t,e){return this.dastScanner.scanUrl(t,e)}async scanAuthenticated(t,e,r){return this.dastScanner.scanAuthenticated(t,e,r)}async getScanStatus(t){return this.activeScans.get(t)??"pending"}async scanDependencies(t){return this.dependencyScanner.scanDependencies(t)}async scanPackageJson(t){return this.dependencyScanner.scanPackageJson(t)}async runFullScan(t,e,r){try{let i=await this.scanWithRules(t,this.config.defaultRuleSets);if(i.success===!1)return p(i.error);let n;if(e){let a=await this.scanUrl(e,r);a.success&&(n=a.value)}let s=this.combineSummaries(i.value.summary,n?.summary);return f({sastResult:i.value,dastResult:n,combinedSummary:s})}catch(i){return p(y(i))}}isLLMAnalysisAvailable(){return this.sastScanner.isLLMAnalysisAvailable()}getModelForTier(t){return this.sastScanner.getModelForTier(t)}async analyzeVulnerabilityWithLLM(t,e){return this.sastScanner.analyzeVulnerabilityWithLLM(t,e)}combineSummaries(t,e){return e?{critical:t.critical+e.critical,high:t.high+e.high,medium:t.medium+e.medium,low:t.low+e.low,informational:t.informational+e.informational,totalFiles:t.totalFiles+e.totalFiles,scanDurationMs:t.scanDurationMs+e.scanDurationMs}:t}};M();import*as Qi from"fs/promises";import*as Ki from"path";A();H();async function Jc(u,t){let e=await fetch(u,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),r=await e.json();return{ok:e.ok,status:e.status,data:r}}async function Ui(u){let t=await fetch(u,{method:"GET",headers:{Accept:"application/json"}}),e=await t.json();return{ok:t.ok,status:t.status,data:e}}var Yc={secretPatterns:[/(?:api[_-]?key|apikey)['":\s]*['"=]?\s*['"]?([a-zA-Z0-9_\-]{20,})['"]?/gi,/(?:password|passwd|pwd)['":\s]*['"=]?\s*['"]?([^\s'"]{8,})['"]?/gi,/(?:secret|token)['":\s]*['"=]?\s*['"]?([a-zA-Z0-9_\-]{16,})['"]?/gi,/(?:aws[_-]?access[_-]?key|aws[_-]?secret)['":\s]*['"=]?\s*['"]?([A-Z0-9]{20,})['"]?/gi,/-----BEGIN\s+(?:RSA\s+)?PRIVATE\s+KEY-----/gi,/ghp_[a-zA-Z0-9]{36}/g,/gho_[a-zA-Z0-9]{36}/g,/sk-[a-zA-Z0-9]{48}/g],excludePatterns:["node_modules","dist","build",".git","*.test.*","*.spec.*"],maxFileSizeKb:1024,enableHistoricalAnalysis:!0,riskThreshold:.7};M();import*as sm from"fs/promises";import*as am from"path";var Ny=R.create("security-compliance/security-auditor-sast");function Vy(){return[{id:"sqli-concat",pattern:/(?:query|execute|exec|run)\s*\(\s*(?:['"`].*?\s*\+|`[^`]*\$\{)/gi,title:"SQL Injection via String Concatenation",description:"SQL query constructed using string concatenation with potentially untrusted input",severity:"critical",category:"injection",remediation:"Use parameterized queries or prepared statements",fixExample:'db.query("SELECT * FROM users WHERE id = $1", [userId])',cweId:"CWE-89"},{id:"xss-innerhtml",pattern:/\.innerHTML\s*=\s*(?!['"`])/g,title:"XSS via innerHTML Assignment",description:"Direct innerHTML assignment with potentially unsanitized content",severity:"high",category:"xss",remediation:"Use textContent for text, or sanitize HTML with DOMPurify",fixExample:"element.textContent = userInput;",cweId:"CWE-79"},{id:"xss-document-write",pattern:/document\.write\s*\([^)]+\)/g,title:"XSS via document.write",description:"document.write() can execute scripts from untrusted data",severity:"high",category:"xss",remediation:"Avoid document.write(); use DOM manipulation methods",cweId:"CWE-79"},{id:"xss-eval",pattern:/(?<!\.)\beval\s*\([^)]+\)/g,title:"Code Injection via eval()",description:"eval() executes arbitrary code and is a major security risk",severity:"critical",category:"xss",remediation:"Never use eval(); use JSON.parse() for JSON data",fixExample:"JSON.parse(jsonString)",cweId:"CWE-95"},{id:"xss-dangerous-react",pattern:/dangerouslySetInnerHTML\s*=\s*\{/g,title:"React dangerouslySetInnerHTML Usage",description:"dangerouslySetInnerHTML bypasses React XSS protections",severity:"medium",category:"xss",remediation:"Sanitize HTML content with DOMPurify before use",fixExample:"dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(content) }}",cweId:"CWE-79"},{id:"cmd-injection-exec",pattern:/(?:child_process\.)?exec\s*\(\s*(?:[^,)]*\s*\+|`[^`]*\$\{)/g,title:"Command Injection via exec()",description:"Shell command execution with unsanitized input",severity:"critical",category:"injection",remediation:"Use execFile() with argument array instead of exec()",fixExample:'execFile("command", [arg1, arg2], callback)',cweId:"CWE-78"},{id:"cmd-injection-spawn-shell",pattern:/spawn\s*\([^)]+,\s*\{[^}]*shell\s*:\s*true/g,title:"Dangerous Shell Option in spawn()",description:"spawn() with shell: true can enable command injection",severity:"high",category:"injection",remediation:"Avoid shell: true option; use direct command execution",cweId:"CWE-78"},{id:"path-traversal-readfile",pattern:/(?:readFile|readFileSync)\s*\([^)]*\+/g,title:"Path Traversal via File Read",description:"File read operation with concatenated path may allow directory traversal",severity:"high",category:"access-control",remediation:"Validate and sanitize file paths; use path.resolve() and check against base directory",fixExample:"const safePath = path.resolve(baseDir, path.basename(userInput))",cweId:"CWE-22"},{id:"path-traversal-writefile",pattern:/(?:writeFile|writeFileSync)\s*\([^)]*\+/g,title:"Path Traversal via File Write",description:"File write operation with concatenated path may allow directory traversal",severity:"high",category:"access-control",remediation:"Validate file paths before writing; ensure path is within allowed directory",cweId:"CWE-22"},{id:"secret-private-key",pattern:/-----BEGIN\s+(?:RSA\s+)?PRIVATE\s+KEY-----/g,title:"Private Key Detected in Source",description:"Private key found in source code",severity:"critical",category:"sensitive-data",remediation:"Store private keys in secure key management systems, not in code",cweId:"CWE-798"},{id:"config-tls-disabled",pattern:/rejectUnauthorized\s*:\s*false/g,title:"TLS Certificate Validation Disabled",description:"Disabling TLS certificate validation exposes to MITM attacks",severity:"high",category:"security-misconfiguration",remediation:"Always enable TLS certificate validation in production",cweId:"CWE-295"},{id:"config-cors-wildcard",pattern:/cors\s*\(\s*\{[^}]*origin\s*:\s*['"]\*['"]/gi,title:"Permissive CORS Configuration",description:"CORS allows all origins (*) which may expose sensitive data",severity:"medium",category:"security-misconfiguration",remediation:"Restrict CORS to specific trusted origins",fixExample:'cors({ origin: ["https://trusted-domain.com"] })',cweId:"CWE-942"}]}async function om(u,t){let e=v(),r=Date.now(),i=[],n=0,s=0;try{let h=await u(process.cwd()),g=Vy();for(let b of h){if(t(b))continue;let w=am.extname(b).toLowerCase();if([".ts",".tsx",".js",".jsx",".mjs",".cjs"].includes(w))try{let C=await sm.readFile(b,"utf-8"),S=C.split(`
|
|
2925
2925
|
`);n++,s+=S.length;for(let k of g){k.pattern.lastIndex=0;let P;for(;(P=k.pattern.exec(C))!==null;){let z=C.substring(0,P.index).split(`
|
|
2926
2926
|
`),K=z.length,Re=z[z.length-1].length+1,Y=S[K-1]||"";if(Y.trimStart().startsWith("//")||Y.trimStart().startsWith("*")||Y.includes("// nosec")||Y.includes("// security-ignore"))continue;let G=Math.max(0,K-2),ne=Math.min(S.length,K+1),X=S.slice(G,ne).join(`
|
|
2927
2927
|
`),Jm={file:b,line:K,column:Re,snippet:X},Ym={description:k.remediation,fixExample:k.fixExample,estimatedEffort:k.severity==="critical"?"moderate":"minor",automatable:k.severity==="low"||k.severity==="medium"};i.push({id:v(),cveId:void 0,title:k.title,description:`${k.description} [${k.cweId}]`,severity:k.severity,category:k.category,location:Jm,remediation:Ym,references:[`https://cwe.mitre.org/data/definitions/${k.cweId.replace("CWE-","")}.html`]})}}}catch{}}}catch(h){Ny.error("SAST scan failed:",h instanceof Error?h:void 0)}let a=Date.now()-r,o=0,c=0,l=0,d=0,m=0;for(let h of i)switch(h.severity){case"critical":o++;break;case"high":c++;break;case"medium":l++;break;case"low":d++;break;case"informational":m++;break}return{scanId:e,vulnerabilities:i,summary:{critical:o,high:c,medium:l,low:d,informational:m,totalFiles:n,scanDurationMs:a},coverage:{filesScanned:n,linesScanned:s,rulesApplied:12}}}M();A();var _y=R.create("security-compliance/security-auditor-dast");async function cm(u){let t=v(),e=Date.now(),r=[],i=0;try{let d;try{d=new URL(u)}catch{return{scanId:t,targetUrl:u,vulnerabilities:[{id:v(),title:"Invalid Target URL",description:"The provided target URL is not valid",severity:"informational",category:"security-misconfiguration",location:{file:u},remediation:{description:"Provide a valid URL",estimatedEffort:"trivial",automatable:!1},references:[]}],summary:{critical:0,high:0,medium:0,low:0,informational:1,totalFiles:0,scanDurationMs:Date.now()-e},crawledUrls:0}}let m=new AbortController,h=setTimeout(()=>m.abort(),3e4);try{let g=await fetch(u,{method:"GET",headers:{"User-Agent":"AgenticQE-SecurityScanner/3.0",Accept:"text/html,application/json,*/*"},signal:m.signal,redirect:"follow"});clearTimeout(h),i=1;let b=g.headers,w=[{header:"strict-transport-security",title:"Missing HTTP Strict Transport Security (HSTS)",description:"HSTS header is missing, allowing downgrade attacks",severity:"medium",remediation:"Add Strict-Transport-Security header with appropriate max-age"},{header:"x-content-type-options",title:"Missing X-Content-Type-Options Header",description:"X-Content-Type-Options header is missing, allowing MIME sniffing attacks",severity:"low",remediation:"Add X-Content-Type-Options: nosniff header"},{header:"x-frame-options",title:"Missing X-Frame-Options Header",description:"X-Frame-Options header is missing, allowing clickjacking attacks",severity:"medium",remediation:"Add X-Frame-Options: DENY or SAMEORIGIN header"},{header:"content-security-policy",title:"Missing Content Security Policy",description:"CSP header is missing, increasing XSS attack surface",severity:"medium",remediation:"Implement a Content-Security-Policy header"},{header:"x-xss-protection",title:"Missing X-XSS-Protection Header",description:"X-XSS-Protection header is missing (legacy XSS filter)",severity:"low",remediation:"Add X-XSS-Protection: 1; mode=block header"}];for(let P of w)b.get(P.header)||r.push({id:v(),title:P.title,description:P.description,severity:P.severity,category:"security-misconfiguration",location:{file:u,snippet:`Response Headers: ${P.header} not present`},remediation:{description:P.remediation,estimatedEffort:"minor",automatable:!0},references:["https://owasp.org/www-project-secure-headers/"]});let C=b.get("set-cookie");C&&(C.toLowerCase().includes("secure")||r.push({id:v(),title:"Cookie Without Secure Flag",description:"Session cookie is set without the Secure flag",severity:"medium",category:"sensitive-data",location:{file:u,snippet:`Set-Cookie: ${C.substring(0,50)}...`},remediation:{description:"Add Secure flag to cookies",estimatedEffort:"trivial",automatable:!0},references:["https://owasp.org/www-community/controls/SecureCookieAttribute"]}),C.toLowerCase().includes("httponly")||r.push({id:v(),title:"Cookie Without HttpOnly Flag",description:"Session cookie is set without the HttpOnly flag, making it accessible to JavaScript",severity:"medium",category:"sensitive-data",location:{file:u,snippet:`Set-Cookie: ${C.substring(0,50)}...`},remediation:{description:"Add HttpOnly flag to session cookies",estimatedEffort:"trivial",automatable:!0},references:["https://owasp.org/www-community/HttpOnly"]}),C.toLowerCase().includes("samesite")||r.push({id:v(),title:"Cookie Without SameSite Attribute",description:"Cookie is set without the SameSite attribute, potentially vulnerable to CSRF",severity:"low",category:"broken-auth",location:{file:u,snippet:`Set-Cookie: ${C.substring(0,50)}...`},remediation:{description:"Add SameSite=Strict or SameSite=Lax to cookies",estimatedEffort:"trivial",automatable:!0},references:["https://owasp.org/www-community/SameSite"]}));let S=b.get("server");S&&/[0-9]+\.[0-9]+/.test(S)&&r.push({id:v(),title:"Server Version Disclosure",description:`Server header reveals version information: ${S}`,severity:"low",category:"security-misconfiguration",location:{file:u,snippet:`Server: ${S}`},remediation:{description:"Remove or obfuscate server version information",estimatedEffort:"trivial",automatable:!0},references:["https://owasp.org/www-project-web-security-testing-guide/"]}),d.protocol==="http:"&&r.push({id:v(),title:"Insecure HTTP Protocol",description:"Target is using HTTP instead of HTTPS, exposing data in transit",severity:"high",category:"sensitive-data",location:{file:u},remediation:{description:"Use HTTPS with valid TLS certificate",estimatedEffort:"moderate",automatable:!1},references:["https://owasp.org/www-project-web-security-testing-guide/"]});let k=[{path:"/.git/config",vuln:"Git Repository Exposed",severity:"high"},{path:"/.env",vuln:"Environment File Exposed",severity:"critical"},{path:"/phpinfo.php",vuln:"PHP Info Exposed",severity:"medium"},{path:"/wp-config.php.bak",vuln:"WordPress Config Backup Exposed",severity:"critical"}];for(let P of k)try{let O=new URL(P.path,d.origin).toString(),z=await fetch(O,{method:"GET",signal:AbortSignal.timeout(5e3)});if(z.ok&&z.status===200){let K=await z.text();K.length>10&&!K.toLowerCase().includes("not found")&&(i++,r.push({id:v(),title:P.vuln,description:`Sensitive file found at ${P.path}`,severity:P.severity,category:"sensitive-data",location:{file:O},remediation:{description:"Remove or restrict access to sensitive files",estimatedEffort:"trivial",automatable:!0},references:["https://owasp.org/www-project-web-security-testing-guide/"]}))}}catch{}}catch(g){clearTimeout(h);let b=T(g);(b.includes("certificate")||b.includes("SSL")||b.includes("TLS"))&&r.push({id:v(),title:"TLS/SSL Certificate Issue",description:`Certificate error: ${b}`,severity:"high",category:"security-misconfiguration",location:{file:u},remediation:{description:"Fix TLS certificate configuration",estimatedEffort:"moderate",automatable:!1},references:["https://owasp.org/www-project-web-security-testing-guide/"]})}}catch(d){_y.error("DAST scan failed:",d instanceof Error?d:void 0)}let n=Date.now()-e,s=0,a=0,o=0,c=0,l=0;for(let d of r)switch(d.severity){case"critical":s++;break;case"high":a++;break;case"medium":o++;break;case"low":c++;break;case"informational":l++;break}return{scanId:t,targetUrl:u,vulnerabilities:r,summary:{critical:s,high:a,medium:o,low:c,informational:l,totalFiles:1,scanDurationMs:n},crawledUrls:i}}M();import*as lm from"fs/promises";var zy=R.create("security-compliance/security-auditor-secrets");function By(){return[{name:"AWS Access Key ID",type:"api-key",regex:/AKIA[0-9A-Z]{16}/g},{name:"AWS Secret Access Key",type:"api-key",regex:/(?:aws[_-]?secret[_-]?access[_-]?key|AWS_SECRET_ACCESS_KEY)['"]?\s*[:=]\s*['"]?([A-Za-z0-9/+=]{40})['"]?/gi,entropyThreshold:4},{name:"GitHub Personal Access Token",type:"token",regex:/ghp_[A-Za-z0-9]{36}/g},{name:"GitHub OAuth Access Token",type:"token",regex:/gho_[A-Za-z0-9]{36}/g},{name:"GitHub App Token",type:"token",regex:/(?:ghu|ghs)_[A-Za-z0-9]{36}/g},{name:"Generic API Key",type:"api-key",regex:/(?:api[_-]?key|apikey|api_secret)['"]?\s*[:=]\s*['"]([A-Za-z0-9_\-]{20,})['"]?/gi,entropyThreshold:3.5},{name:"OpenAI API Key",type:"api-key",regex:/sk-[A-Za-z0-9]{48}/g},{name:"Stripe Secret Key",type:"api-key",regex:/sk_live_[A-Za-z0-9]{24,}/g},{name:"Stripe Publishable Key",type:"api-key",regex:/pk_live_[A-Za-z0-9]{24,}/g},{name:"RSA Private Key",type:"private-key",regex:/-----BEGIN\s+(?:RSA\s+)?PRIVATE\s+KEY-----/gi},{name:"PGP Private Key",type:"private-key",regex:/-----BEGIN\s+PGP\s+PRIVATE\s+KEY\s+BLOCK-----/gi},{name:"SSH Private Key",type:"private-key",regex:/-----BEGIN\s+(?:OPENSSH|DSA|EC)?\s*PRIVATE\s+KEY-----/gi},{name:"Password Assignment",type:"password",regex:/(?:password|passwd|pwd|secret)['"]?\s*[:=]\s*['"]([^'"\s]{8,})['"]?/gi,entropyThreshold:3},{name:"Database Connection String",type:"password",regex:/(?:mongodb|postgres|mysql|redis):\/\/[^:]+:[^@]+@[^\s'"]+/gi},{name:"JWT Token",type:"token",regex:/eyJ[A-Za-z0-9_-]*\.eyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]*/g,entropyThreshold:4},{name:"Slack Token",type:"token",regex:/xox[baprs]-[A-Za-z0-9-]{10,}/g},{name:"Google API Key",type:"api-key",regex:/AIza[A-Za-z0-9_-]{35}/g},{name:"Twilio API Key",type:"api-key",regex:/SK[A-Za-z0-9]{32}/g},{name:"SendGrid API Key",type:"api-key",regex:/SG\.[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43}/g},{name:"X.509 Certificate",type:"certificate",regex:/-----BEGIN\s+CERTIFICATE-----/gi}]}function qy(u){if(!u||u.length===0)return 0;let t={};for(let i of u)t[i]=(t[i]||0)+1;let e=0,r=u.length;for(let i in t){let n=t[i]/r;e-=n*Math.log2(n)}return e}function Gy(u,t,e){let n=Math.max(0,t-20),s=Math.min(u.length,t+e+10),a=u.substring(n,s),o=t-n,c=a.substring(o,o+e);if(c.length>8){let l=c.substring(0,4)+"..."+c.substring(c.length-4);a=a.substring(0,o)+l+a.substring(o+e)}return n>0&&(a="..."+a),s<u.length&&(a=a+"..."),a}function Hy(u,t){switch(u){case"api-key":return t.length>=20&&/[a-z]/.test(t)&&/[A-Z0-9]/.test(t);case"token":return t.length>=20;case"password":return!["password","secret","changeme","12345678","qwerty"].includes(t.toLowerCase());case"private-key":return!0;case"certificate":return!0;default:return!0}}async function Xc(u){let t=[];try{let r=(await lm.readFile(u.value,"utf-8")).split(`
|
|
@@ -3003,7 +3003,7 @@ Provide:
|
|
|
3003
3003
|
});
|
|
3004
3004
|
})();
|
|
3005
3005
|
`,s=await u.evaluate(n);if(!s.success)return p(new Error(`Failed to run axe-core: ${s.error?.message??"Unknown error"}`));try{let a=E(s.value);return f(a)}catch(a){return p(new Error(`Failed to parse axe-core results: ${a}`))}}function fv(u,t){let e=[];for(let r of u){let i=r.match(/^wcag(\d)(\d)(\d)(\d)?$/);if(i){let n=i[4]?`${i[1]}.${i[2]}.${i[3]}${i[4]}`:`${i[1]}.${i[2]}.${i[3]}`,s=Er[n];s?e.push(s):e.push({id:n,level:t,title:`WCAG ${n}`})}}return e}function yv(u,t,e){let r=t.violations.map(l=>({id:l.id,impact:wm(l.impact??"moderate"),wcagCriteria:fv(l.tags??[],e),description:l.description,help:l.help,helpUrl:l.helpUrl??`https://dequeuniversity.com/rules/axe/4.8/${l.id}`,nodes:l.nodes.map(d=>({selector:d.selector,html:d.html,target:d.target,failureSummary:d.failureSummary??""}))})),i=t.passes.map(l=>({id:l,description:`Rule ${l} passed`,nodes:0})),n=t.incomplete.map(l=>({id:l,description:`Rule ${l} requires manual review`,reason:"Could not automatically determine compliance",nodes:[]})),s=r.length+i.length+n.length,a=r.reduce((l,d)=>l+{critical:4,serious:3,moderate:2,minor:1}[d.impact],0),o=s*4,c=s>0?Math.round((o-a)/o*100):100;return{url:u,timestamp:new Date,violations:r,passes:i,incomplete:n,score:Math.max(0,Math.min(100,c)),wcagLevel:e}}function Cm(u,t,e){let r=t.violations.map(l=>({id:l.id,impact:wm(l.impact),wcagCriteria:l.wcagCriterion?[{id:l.wcagCriterion,level:e,title:l.rule}]:[],description:l.description,help:l.help,helpUrl:l.helpUrl??"https://www.w3.org/WAI/WCAG22/Understanding/",nodes:l.nodes.map(d=>({selector:d.selector,html:d.html,target:d.target,failureSummary:d.failureSummary}))})),i=t.passedRules.map(l=>({id:l,description:`Rule ${l} passed`,nodes:0})),n=t.incompleteRules.map(l=>({id:l,description:`Rule ${l} requires manual review`,reason:"Could not automatically determine compliance",nodes:[]})),s=r.length+i.length+n.length,a=r.reduce((l,d)=>l+{critical:4,serious:3,moderate:2,minor:1}[d.impact],0),o=s*4,c=s>0?Math.round((o-a)/o*100):100;return{url:u,timestamp:new Date,violations:r,passes:i,incomplete:n,score:Math.max(0,Math.min(100,c)),wcagLevel:e}}function vv(u,t){let e=[];for(let r of u.violations)if(r.rule.includes("contrast")||r.id.includes("contrast"))for(let i of r.nodes){let n=i.failureSummary.match(/foreground:?\s*([#\w\d]+).*?background:?\s*([#\w\d]+)/i),s=i.failureSummary.match(/ratio\s*[:\s]*(\d+\.?\d*)/i);e.push({element:i.selector,foreground:n?.[1]||"#000000",background:n?.[2]||"#ffffff",ratio:s?parseFloat(s[1]):1,requiredRatio:t==="AAA"?7:4.5,passes:!1,wcagLevel:t})}if(e.length===0&&u.passedRules.some(r=>r.includes("contrast"))){let r=["h1","p","a","button"];for(let i of r)e.push({element:i,foreground:"#333333",background:"#ffffff",ratio:12.63,requiredRatio:t==="AAA"?7:4.5,passes:!0,wcagLevel:t})}return e}async function Sm(u,t,e,r,i){try{let n=await u.launch({headless:r.headless});if(!n.success)return p(new Error(`Failed to launch browser: ${n.error?.message??"Unknown error"}`));try{let s=await u.navigate(t);if(!s.success)return p(new Error(`Failed to navigate to ${t}: ${s.error?.message??"Unknown error"}`));if(pv(u)){let c=await u.getSnapshot({interactive:!0});if(c.success){let l=c.value.interactiveElements.length;mv.debug(`Found ${l} interactive elements`)}}let a=await gv(u,e,i);if(!a.success)return p(a.error);let o=yv(t,a.value,e);return f(o)}finally{await u.quit()}}catch(n){return p(y(n))}}async function Rm(u,t,e,r,i){try{let n=await u.launch({headless:r.headless});if(!n.success)return p(new Error(`Failed to launch browser: ${le(n)}`));try{let s=await u.navigate({url:t,waitUntil:"networkidle",timeout:r.timeout});if(!s.success)return p(new Error(`Failed to navigate to ${t}: ${le(s)}`));let a=await u.checkAccessibility({wcagLevel:e,selector:i?.excludeSelectors?.[0]});if(!a.success)return p(new Error(`Accessibility check failed: ${le(a)}`));let o=Cm(t,a.value,e);return f(o)}finally{await u.quit()}}catch(n){return p(y(n))}}async function Tm(u,t,e,r,i){try{let n=await u.launch({headless:i.headless});if(!n.success)return p(new Error(`Failed to launch browser: ${le(n)}`));try{let s=await u.navigate({url:t,waitUntil:"networkidle",timeout:i.timeout});if(!s.success)return p(new Error(`Failed to navigate to ${t}: ${le(s)}`));let a=await u.checkAccessibility({wcagLevel:r,selector:e});if(!a.success)return p(new Error(`Element accessibility check failed: ${le(a)}`));let o=Cm(t,a.value,r);return f(o)}finally{await u.quit()}}catch(n){return p(y(n))}}async function Am(u,t,e,r){try{let i=await u.launch({headless:r.headless});if(!i.success)return p(new Error(`Failed to launch browser: ${le(i)}`));try{let n=await u.navigate({url:t,waitUntil:"networkidle",timeout:r.timeout});if(!n.success)return p(new Error(`Failed to navigate to ${t}: ${le(n)}`));let s=await u.checkAccessibility({wcagLevel:e,rules:{include:["color-contrast"]}});if(!s.success)return p(new Error(`Contrast check failed: ${le(s)}`));let a=vv(s.value,e);return f(a)}finally{await u.quit()}}catch(i){return p(y(i))}}async function Em(u,t,e,r){try{let i=await u.launch({headless:r.headless});if(!i.success)return p(new Error(`Failed to launch browser: ${le(i)}`));try{let n=await u.navigate({url:t,waitUntil:"networkidle",timeout:r.timeout});if(!n.success)return p(new Error(`Failed to navigate to ${t}: ${le(n)}`));let a=await u.findElements({selector:'a[href], button, input, select, textarea, [tabindex]:not([tabindex="-1"])',visible:!0});if(!a.success)return p(new Error(`Failed to find focusable elements: ${le(a)}`));let o=a.value.map((h,g)=>({index:g,selector:h.selector,elementType:bv(h.tagName),hasVisibleFocus:!0})),c=await u.checkAccessibility({wcagLevel:e,rules:{include:["keyboard","focus-order","focus-trap","bypass-blocks"]}}),l=[],d=[];if(c.success){for(let h of c.value.violations)if(h.rule.includes("focus")||h.rule.includes("keyboard"))for(let g of h.nodes)h.rule.includes("trap")?d.push({selector:g.selector,description:g.failureSummary,escapePath:"Ensure Escape key or Tab can exit this element"}):l.push({type:wv(h.rule),selector:g.selector,description:g.failureSummary})}let m={url:t,focusableElements:o.length,tabOrder:o,issues:l,traps:d};return f(m)}finally{await u.quit()}}catch(i){return p(y(i))}}function bv(u){return{a:"link",button:"button",input:"input",select:"input",textarea:"input"}[u.toLowerCase()]||"other"}function wv(u){return u.includes("focus-indicator")||u.includes("visible")?"no-focus-indicator":u.includes("skip")||u.includes("bypass")?"skip-link-missing":u.includes("order")||u.includes("sequence")?"incorrect-tab-order":"non-interactive-focusable"}function Pm(){return[{id:"image-alt",description:"Images must have alternate text",wcagCriteria:["1.1.1"],impact:"critical",simulationFailureRate:.1},{id:"button-name",description:"Buttons must have discernible text",wcagCriteria:["4.1.2"],impact:"critical",simulationFailureRate:.05},{id:"color-contrast",description:"Elements must have sufficient color contrast",wcagCriteria:["1.4.3"],impact:"serious",simulationFailureRate:.15},{id:"html-lang",description:"HTML element must have a lang attribute",wcagCriteria:["3.1.1"],impact:"serious",simulationFailureRate:.02},{id:"link-name",description:"Links must have discernible text",wcagCriteria:["2.4.4","4.1.2"],impact:"serious",simulationFailureRate:.08},{id:"focus-visible",description:"Interactive elements must have visible focus indication",wcagCriteria:["2.4.7"],impact:"serious",simulationFailureRate:.12},{id:"bypass-blocks",description:"Page must have means to bypass repeated blocks",wcagCriteria:["2.4.1"],impact:"moderate",simulationFailureRate:.1},{id:"label",description:"Form elements must have labels",wcagCriteria:["1.3.1","4.1.2"],impact:"critical",simulationFailureRate:.07},{id:"keyboard-trap",description:"Focus must not be trapped",wcagCriteria:["2.1.2"],impact:"critical",simulationFailureRate:.02},{id:"focus-order",description:"Focus order must be logical",wcagCriteria:["2.4.3"],impact:"moderate",simulationFailureRate:.05}]}function nl(u,t){let e={A:1,AA:2,AAA:3},r=e[t];return u.filter(i=>i.wcagCriteria.some(n=>{let s=Er[n];return s&&e[s.level]<=r}))}function km(u,t,e,r){if(e){let s=_v(u,t),a=xm(u,t);return{nodes:s,passed:s.length===0,checkedNodes:a}}let i=Cv(u,t,r),n=xm(u,t);return{nodes:i,passed:i.length===0,checkedNodes:n}}function Cv(u,t,e){let r=[],i=t.url.toLowerCase();switch(u.id){case"image-alt":Sv(i)&&r.push(...Iv());break;case"button-name":Rv(i)&&r.push(...Mv());break;case"color-contrast":e&&r.push(...Fv());break;case"html-lang":Tv(i)&&r.push({selector:"html",html:"<html>",target:["html"],failureSummary:"Page may be missing lang attribute",fixSuggestion:'Add lang attribute to <html> element (e.g., <html lang="en">)'});break;case"link-name":Av(i)&&r.push(...Lv());break;case"focus-visible":Ev(i)&&r.push(...$v());break;case"bypass-blocks":xv(i)||r.push({selector:"body",html:"<body>",target:["body"],failureSummary:"Page may lack skip navigation mechanism",fixSuggestion:"Add a skip link at the beginning of the page to bypass repeated content"});break;case"label":Pv(i)&&r.push(...Ov());break;case"keyboard-trap":kv(i)&&r.push(...Nv());break;case"focus-order":Dv(i)&&r.push(...Vv());break}return r}function Sv(u){return u.includes("gallery")||u.includes("photo")||u.includes("image")||u.includes("product")||u.includes("portfolio")||u.includes("media")}function Rv(u){return u.includes("app")||u.includes("dashboard")||u.includes("editor")||u.includes("tool")||u.includes("builder")||u.includes("widget")}function Tv(u){return u.includes("cdn")||u.includes("static")||u.includes(".html")||u.includes("file://")}function Av(u){return u.includes("nav")||u.includes("menu")||u.includes("header")||u.includes("sidebar")||u.includes("footer")}function Ev(u){return u.includes("app")||u.includes("dashboard")||u.includes("#/")||u.includes("react")||u.includes("angular")||u.includes("vue")}function xv(u){return u.includes("gov")||u.includes("edu")||u.includes("a11y")||u.includes("accessible")}function Pv(u){return u.includes("form")||u.includes("contact")||u.includes("register")||u.includes("signup")||u.includes("login")||u.includes("checkout")||u.includes("submit")||u.includes("search")}function kv(u){return u.includes("modal")||u.includes("dialog")||u.includes("popup")||u.includes("overlay")||u.includes("lightbox")}function Dv(u){return u.includes("dashboard")||u.includes("admin")||u.includes("grid")||u.includes("layout")||u.includes("multi")}function Iv(){return[{selector:"img",html:'<img src="...">',target:["img"],failureSummary:"Images should have descriptive alt text",fixSuggestion:"Add alt attribute with meaningful description to all <img> elements"}]}function Mv(){return[{selector:"button:not([aria-label])",html:"<button>",target:["button"],failureSummary:"Buttons should have accessible names",fixSuggestion:"Ensure buttons have visible text or aria-label attribute"}]}function Fv(){return[{selector:".text-content",html:'<div class="text-content">',target:[".text-content"],failureSummary:"Text elements should meet WCAG 2.2 AA contrast ratio (4.5:1)",fixSuggestion:"Verify text color has sufficient contrast against background"}]}function Lv(){return[{selector:"a:not([aria-label])",html:'<a href="#">',target:["a"],failureSummary:"Links should have descriptive text",fixSuggestion:"Add meaningful link text or aria-label attribute"}]}function $v(){return[{selector:":focus",html:"<element>:focus",target:[":focus"],failureSummary:"Interactive elements should have visible focus indicators",fixSuggestion:"Do not remove outline on :focus; use :focus-visible for styling"}]}function Ov(){return[{selector:"input:not([aria-label]):not([id])",html:'<input type="text">',target:["input"],failureSummary:"Form inputs should have associated labels",fixSuggestion:'Add <label for="id"> or aria-label to form inputs'}]}function Nv(){return[{selector:'[role="dialog"]',html:'<div role="dialog">',target:['[role="dialog"]'],failureSummary:"Modal dialogs should not trap keyboard focus",fixSuggestion:"Ensure Escape key closes modal and Tab cycles within dialog"}]}function Vv(){return[{selector:"[tabindex]",html:'<div tabindex="...">',target:["[tabindex]"],failureSummary:"Focus order should follow logical reading sequence",fixSuggestion:'Avoid positive tabindex values; use tabindex="0" or "-1"'}]}function _v(u,t){let e=[],r=vt(t.url),i=parseInt(r,36),n=u.id.split("").reduce((a,o)=>a+o.charCodeAt(0),0),s=1+(i+n)%10;for(let a=0;a<s;a++)if((i+n+a*100)%100/100<u.simulationFailureRate){let c=zv(u.id,a);e.push({selector:c,html:`<element class="${u.id}-element-${a}">Content</element>`,target:[c],failureSummary:"Element does not meet accessibility requirements",fixSuggestion:"Review and update the element to meet WCAG guidelines"})}return e}function zv(u,t){let r={"image-alt":["img"],"button-name":["button"],"color-contrast":["div","p","span"],"html-lang":["html"],"link-name":["a"],"focus-visible":["button","a","input"],"bypass-blocks":["main","nav"],label:["input","select","textarea"],"keyboard-trap":["div","dialog"],"focus-order":["button","a","input"]}[u]||["div"],i=r[t%r.length],n=["content","widget","component","item","element"],s=n[t%n.length];return`${i}.${s}`}function xm(u,t){let e=u.id.toLowerCase();return e.includes("image")||e.includes("alt")?5+t.url.length%10:e.includes("form")||e.includes("label")||e.includes("input")?8+t.url.length%12:e.includes("link")||e.includes("anchor")?15+t.url.length%20:e.includes("color")||e.includes("contrast")?20+t.url.length%15:e.includes("heading")||e.includes("h1")||e.includes("h2")?6+t.url.length%8:e.includes("aria")||e.includes("role")?12+t.url.length%18:10+t.url.length%10}function Dm(u,t){let r={"1.1.1":.12,"1.3.1":.08,"1.4.1":.05,"1.4.3":.15,"1.4.6":.25,"2.1.1":.1,"2.1.2":.03,"2.4.1":.08,"2.4.3":.06,"2.4.4":.1,"2.4.7":.12,"3.1.1":.04,"4.1.1":.02,"4.1.2":.09}[u.id]??.1,i=u.id.charCodeAt(0)*100,s=(t+i)%100/100>=r;return{passed:s,reason:s?void 0:`Criterion ${u.id} (${u.title}) not fully satisfied`}}function sl(u){let t=["h1","p","a","button",".card-text",".nav-link"],e=[],r=vt(u),i=parseInt(r,36);for(let n=0;n<t.length;n++){let s=t[n],a=4.5+(i+n*1e3)%100/10,o=Math.round(a*100)/100,l=s==="h1"||s==="button"?3:4.5,d=o>=l,m=20+(i+n*50)%30,h=200+(i+n*30)%55,g=m.toString(16).padStart(2,"0"),b=h.toString(16).padStart(2,"0");e.push({element:s,foreground:`#${g}${g}${g}`,background:`#${b}${b}${b}`,ratio:o,requiredRatio:l,passes:d,wcagLevel:"AA"})}return e}function al(u){let t=vt(u),e=Bv(u,t),r=qv(e),i=Gv(u,t);return{url:u,focusableElements:e.length,tabOrder:e,issues:r,traps:i}}function Bv(u,t){let e=[],r=parseInt(t,36);return[{selector:"#skip-link",type:"link"},{selector:"header nav a.logo",type:"link"},{selector:"header nav a.menu-item",type:"link"},{selector:"#search-input",type:"input"},{selector:"#search-button",type:"button"},{selector:"main a",type:"link"},{selector:"main button",type:"button"},{selector:"form input",type:"input"},{selector:"form select",type:"input"},{selector:'form button[type="submit"]',type:"button"},{selector:"footer a",type:"link"}].forEach((n,s)=>{let o=(r+s*17)%100>=12;e.push({index:s,selector:n.selector,elementType:n.type,hasVisibleFocus:o})}),e}function qv(u){let t=[];for(let r of u)r.hasVisibleFocus||t.push({type:"no-focus-indicator",selector:r.selector,description:`Element ${r.selector} does not have a visible focus indicator`});return u.some(r=>r.selector.includes("skip"))||t.push({type:"skip-link-missing",selector:"body",description:"Page is missing a skip navigation link"}),u.every((r,i)=>{if(i===0)return!0;let n=r.selector.includes("nav")||r.selector.includes("header"),s=u[i-1].selector.includes("main");return!(n&&s)})||t.push({type:"incorrect-tab-order",selector:"body",description:"Focus order does not follow logical reading sequence"}),t}function Gv(u,t){let e=[],r=parseInt(t,36),i=u.includes("modal")||u.includes("dialog")||u.includes("popup"),n=u.includes("form")||u.includes("checkout")||u.includes("register");return i&&r%100<8&&e.push({selector:'.modal, [role="dialog"]',description:"Modal dialog may trap focus without escape mechanism",escapePath:"Ensure Escape key closes modal and focus returns to trigger element"}),n&&r%100<5&&e.push({selector:"form .autocomplete, form .datepicker",description:"Form widget may trap keyboard focus",escapePath:"Add keyboard navigation (Tab/Escape) to exit widget"}),e}function vt(u){let t=0;for(let e=0;e<u.length;e++){let r=u.charCodeAt(e);t=(t<<5)-t+r,t=t&t}return Math.abs(t).toString(36)}var Hv={defaultWCAGLevel:"AA",includeWarnings:!0,auditTimeout:3e4,enableColorContrastCheck:!0,enableKeyboardCheck:!0,simulationMode:!1,useBrowserMode:!0,browserConfig:{headless:!0,timeout:3e4},browserClient:void 0,preferAgentBrowser:!0},xr=R.create("visual-accessibility/accessibility-tester"),Pr=class{constructor(t,e={},r){this.memory=t;this.config={...Hv,...e},this.rules=Pm(),this.vibiumClient=r??null,this.browserClient=e.browserClient??null,this.euComplianceService=new Ra(t)}memory;config;rules;vibiumClient;browserClient;managedBrowserClient=null;euComplianceService;shouldUseBrowserMode(){return this.config.useBrowserMode?this.browserClient||this.config.preferAgentBrowser?!0:!(!dn()||!mn()||!this.vibiumClient):!1}async getBrowserClient(){if(this.browserClient)return this.browserClient;if(this.managedBrowserClient)return this.managedBrowserClient;if(this.config.preferAgentBrowser)try{let t=await us("accessibility");if(await t.isAvailable())return this.managedBrowserClient=t,t}catch{xr.debug("Browser client error:")}return null}async audit(t,e){try{let r=e?.wcagLevel||this.config.defaultWCAGLevel;if(this.shouldUseBrowserMode()){let i=await this.getBrowserClient();if(i){let n=await Sm(i,t,r,this.config.browserConfig,e);if(n.success)return await this.storeReport(n.value),n;let s=le(n);xr.warn(`Browser client audit failed: ${s}`)}if(this.vibiumClient&&dn()&&mn()){let n=await Rm(this.vibiumClient,t,r,this.config.browserConfig,e);if(n.success)return await this.storeReport(n.value),n;let s=le(n);xr.warn(`Vibium audit failed, falling back to heuristic mode: ${s}`)}}return this.auditWithHeuristics(t,r,e)}catch(r){return p(y(r))}}async auditElement(t,e){if(this.shouldUseBrowserMode()&&this.vibiumClient){let r=await Tm(this.vibiumClient,t,e,this.config.defaultWCAGLevel,this.config.browserConfig);if(r.success)return await this.storeReport(r.value),r;let i=le(r);xr.warn(`Browser mode element audit failed, falling back to heuristic mode: ${i}`)}return this.audit(t,{excludeSelectors:[],wcagLevel:this.config.defaultWCAGLevel})}async auditWithHeuristics(t,e,r){try{let n=r?.includeWarnings??this.config.includeWarnings?nl(this.rules,e):nl(this.rules,e).filter(h=>h.impact!=="minor"),s=[],a=[],o=[];for(let h of n){let g=km(h,{url:t},this.config.simulationMode,this.config.enableColorContrastCheck);g.nodes.length>0?s.push({id:h.id,impact:h.impact,wcagCriteria:h.wcagCriteria.map(b=>Er[b]).filter(Boolean),description:h.description,help:`Fix ${h.description.toLowerCase()}`,helpUrl:`https://www.w3.org/WAI/WCAG22/Understanding/${h.wcagCriteria[0]}`,nodes:g.nodes}):g.passed?a.push({id:h.id,description:h.description,nodes:g.checkedNodes}):o.push({id:h.id,description:h.description,reason:"Could not determine compliance",nodes:g.nodes})}let c=n.length,l=s.length,d=Math.round((c-l)/c*100),m={url:t,timestamp:new Date,violations:s,passes:a,incomplete:o,score:d,wcagLevel:e};return await this.storeReport(m),f(m)}catch(i){return p(y(i))}}async checkContrast(t){try{let e=`visual-accessibility:contrast:${vt(t)}`,r=await this.memory.get(e);if(r)return f(r);let i;if(this.shouldUseBrowserMode()&&this.vibiumClient){let n=await Am(this.vibiumClient,t,this.config.defaultWCAGLevel,this.config.browserConfig);if(n.success)i=n.value;else{let s=le(n);xr.warn(`Browser mode contrast check failed, falling back to heuristic mode: ${s}`),i=sl(t)}}else i=sl(t);return await this.memory.set(e,i,{namespace:"visual-accessibility",ttl:3600}),f(i)}catch(e){return p(y(e))}}async validateWCAGLevel(t,e){try{let r={A:1,AA:2,AAA:3},i=r[e],n=Object.values(Er).filter(m=>r[m.level]<=i),s=[],a=[],o=vt(t),c=parseInt(o,36);for(let m of n)Dm(m,c).passed?a.push(m):s.push(m);let l=s.length===0,d=Math.round(a.length/n.length*100);return f({level:e,passed:l,failedCriteria:s,passedCriteria:a,score:d})}catch(r){return p(y(r))}}async checkKeyboardNavigation(t){try{let e=`visual-accessibility:keyboard:${vt(t)}`,r=await this.memory.get(e);if(r)return f(r);let i;if(this.shouldUseBrowserMode()&&this.config.enableKeyboardCheck&&this.vibiumClient){let n=await Em(this.vibiumClient,t,this.config.defaultWCAGLevel,this.config.browserConfig);if(n.success)i=n.value;else{let s=le(n);xr.warn(`Browser mode keyboard check failed, falling back to heuristic mode: ${s}`),i=al(t)}}else i=al(t);return await this.memory.set(e,i,{namespace:"visual-accessibility",ttl:3600}),f(i)}catch(e){return p(y(e))}}async storeReport(t){let e=v();await this.memory.set(`visual-accessibility:report:${e}`,t,{namespace:"visual-accessibility",persist:!0}),await this.memory.set(`visual-accessibility:latest:${vt(t.url)}`,t,{namespace:"visual-accessibility",persist:!0})}async validateEUCompliance(t,e){try{let r=await this.audit(t,{wcagLevel:"AA",includeWarnings:!0});return r.success?await this.euComplianceService.validateCompliance(r.value,e):p(new Error(`WCAG audit failed: ${r.error.message}`))}catch(r){return p(y(r))}}getEN301549Clauses(){return this.euComplianceService.getEN301549Clauses()}getEAARequirements(){return this.euComplianceService.getEAARequirements()}getWCAGtoEN301549Mapping(){return this.euComplianceService.getWCAGMapping()}async dispose(){this.managedBrowserClient&&(await this.managedBrowserClient.dispose(),this.managedBrowserClient=null)}};A();var Ta={"iphone-se":{width:375,height:667,deviceScaleFactor:2,isMobile:!0,hasTouch:!0},"iphone-14":{width:390,height:844,deviceScaleFactor:3,isMobile:!0,hasTouch:!0},"iphone-14-pro-max":{width:430,height:932,deviceScaleFactor:3,isMobile:!0,hasTouch:!0},"ipad-mini":{width:768,height:1024,deviceScaleFactor:2,isMobile:!0,hasTouch:!0},"ipad-pro":{width:1024,height:1366,deviceScaleFactor:2,isMobile:!0,hasTouch:!0},"pixel-7":{width:412,height:915,deviceScaleFactor:2.625,isMobile:!0,hasTouch:!0},"galaxy-s21":{width:360,height:800,deviceScaleFactor:3,isMobile:!0,hasTouch:!0},"desktop-hd":{width:1920,height:1080,deviceScaleFactor:1,isMobile:!1,hasTouch:!1},"desktop-2k":{width:2560,height:1440,deviceScaleFactor:1,isMobile:!1,hasTouch:!1},laptop:{width:1366,height:768,deviceScaleFactor:1,isMobile:!1,hasTouch:!1}},jv={viewports:[Ta["iphone-14"],Ta["ipad-mini"],Ta.laptop,Ta["desktop-hd"]],breakpoints:[320,480,768,1024,1280,1920],checkTouchTargets:!0,minFontSize:12,minTouchTargetSize:44,simulationMode:!1},kr=class{constructor(t,e={}){this.memory=t;this.config={...jv,...e}}memory;config;async testResponsiveness(t,e){try{let r={...this.config,...e},i=[],n=[];for(let l of r.viewports){let d=await this.testViewport(t,l,r);i.push(d),n.push(...d.layoutIssues)}let s=this.detectBreakpointIssues(t,i,r),a=this.calculateLayoutScore(i,n),o=this.generateRecommendations(n,s),c={url:t,timestamp:new Date,viewports:i,breakpointIssues:s,layoutScore:a,recommendations:o};return await this.storeResult(c),f(c)}catch(r){return p(y(r))}}async compareViewports(t,e,r){try{let i=this.createScreenshot(t,e),n=this.createScreenshot(t,r),s=this.calculateStructuralDiff(i,n);return f(s)}catch(i){return p(y(i))}}async testBreakpoint(t,e){try{let r={width:e,height:800,deviceScaleFactor:1,isMobile:e<768,hasTouch:e<1024},i=await this.testViewport(t,r,this.config);return f(i)}catch(r){return p(y(r))}}async analyzeBreakpoints(t){try{let e=this.findContentBreaks(t),r=this.config.breakpoints,i=this.suggestBreakpoints(e),n=this.calculateBreakpointCoverage(r,e);return f({currentBreakpoints:r,suggestedBreakpoints:i,contentBreaks:e,coverageScore:n})}catch(e){return p(y(e))}}async testViewport(t,e,r){let i=this.createScreenshot(t,e),n=this.detectLayoutIssues(t,e,r),s=this.hashUrl(t),o=200+(parseInt(s,36)+e.width)%1e3,c=n.filter(l=>l.severity==="critical").length===0;return{viewport:e,screenshot:i,layoutIssues:n,renderTime:o,passed:c}}createScreenshot(t,e){let r=this.hashUrl(t),n=500+(parseInt(r,36)+e.width+e.height)%2e3;return{id:v(),url:t,viewport:e,timestamp:new Date,path:Ce.create(`.visual-tests/responsive/${e.width}x${e.height}.png`),metadata:{browser:"chromium",os:process.platform,fullPage:!1,loadTime:n}}}detectLayoutIssues(t,e,r){return r.simulationMode?this.detectLayoutIssuesSimulation(t,e,r):this.detectLayoutIssuesHeuristic(t,e,r)}detectLayoutIssuesHeuristic(t,e,r){let i=[],n=t.toLowerCase(),s=this.hasResponsivePatterns(n);e.width<768&&(this.hasWideContentPatterns(n)&&i.push({type:"horizontal-overflow",severity:"critical",element:".wide-content, table, pre",description:"Wide content elements may cause horizontal overflow on mobile",viewport:e}),s||i.push({type:"horizontal-overflow",severity:"warning",element:".container",description:"Page may lack responsive CSS breakpoints for mobile",viewport:e})),e.width<=320&&i.push({type:"text-overflow",severity:"warning",element:"body",description:"Verify viewport meta tag is set correctly for very small screens",viewport:e}),r.checkTouchTargets&&e.hasTouch&&(this.hasInteractiveElements(n)&&i.push({type:"touch-target-size",severity:"warning",element:"button, a, input",description:`Touch targets should be at least ${r.minTouchTargetSize}px for accessibility`,viewport:e}),e.isMobile&&this.hasNavigationElements(n)&&i.push({type:"touch-target-size",severity:"info",element:"nav a",description:"Navigation links may be too small for touch on mobile devices",viewport:e})),e.isMobile&&r.minFontSize>0&&this.hasDataDensePatterns(n)&&i.push({type:"font-size-too-small",severity:"warning",element:".data, .table, .form-label",description:`Font size may be below ${r.minFontSize}px on mobile`,viewport:e}),this.hasImagePatterns(n)&&(e.deviceScaleFactor>1&&i.push({type:"image-not-responsive",severity:"info",element:"img",description:"Verify images use srcset for high-DPI displays",viewport:e}),e.width<480&&i.push({type:"image-not-responsive",severity:"info",element:"img",description:"Verify images are resized for mobile to reduce bandwidth",viewport:e}));let a=this.findNearestBreakpoint(e.width,r.breakpoints);return a.gap>200&&i.push({type:"hidden-content",severity:"info",element:"body",description:`Viewport ${e.width}px is ${a.gap}px from nearest breakpoint (${a.value}px)`,viewport:e}),this.hasOverlapRiskPatterns(n)&&e.width<1024&&i.push({type:"overlapping-elements",severity:"warning",element:".positioned, .absolute, .fixed",description:"Positioned elements may overlap on smaller screens",viewport:e}),i}hasResponsivePatterns(t){return t.includes("mobile")||t.includes("responsive")||t.includes("bootstrap")||t.includes("tailwind")||t.includes("material")||t.includes("foundation")}hasWideContentPatterns(t){return t.includes("table")||t.includes("data")||t.includes("report")||t.includes("code")||t.includes("pre")||t.includes("spreadsheet")}hasInteractiveElements(t){return t.includes("form")||t.includes("button")||t.includes("input")||t.includes("select")||t.includes("click")||t.includes("action")}hasNavigationElements(t){return t.includes("nav")||t.includes("menu")||t.includes("header")||t.includes("sidebar")||t.includes("footer")||t.includes("breadcrumb")}hasDataDensePatterns(t){return t.includes("dashboard")||t.includes("analytics")||t.includes("report")||t.includes("table")||t.includes("stats")||t.includes("metrics")}hasImagePatterns(t){return t.includes("gallery")||t.includes("photo")||t.includes("image")||t.includes("media")||t.includes("portfolio")||t.includes("hero")}hasOverlapRiskPatterns(t){return t.includes("modal")||t.includes("overlay")||t.includes("tooltip")||t.includes("dropdown")||t.includes("popup")||t.includes("float")}findNearestBreakpoint(t,e){let r=e[0]||0,i=Math.abs(t-r);for(let n of e){let s=Math.abs(t-n);s<i&&(i=s,r=n)}return{value:r,gap:i}}detectLayoutIssuesSimulation(t,e,r){let i=[],n=this.hashUrl(t),s=parseInt(n,36),a=(s+e.width)%100/100;e.width<768&&a<.2&&i.push({type:"horizontal-overflow",severity:"critical",element:".container",description:"Content overflows horizontally causing horizontal scroll",viewport:e});let o=(s+e.width+100)%100/100;e.width<480&&o<.15&&i.push({type:"text-overflow",severity:"warning",element:".long-text",description:"Text content is truncated or overflows container",viewport:e});let c=(s+e.width+200)%100/100;r.checkTouchTargets&&e.isMobile&&c<.25&&i.push({type:"touch-target-size",severity:"warning",element:".small-button",description:`Touch target is smaller than ${r.minTouchTargetSize}px minimum`,viewport:e});let l=(s+e.width+300)%100/100;return e.isMobile&&l<.1&&i.push({type:"font-size-too-small",severity:"warning",element:".fine-print",description:`Font size is below ${r.minFontSize}px minimum for readability`,viewport:e}),(s+e.width+400)%100/100<.15&&i.push({type:"image-not-responsive",severity:"info",element:"img.hero-image",description:"Image does not scale properly for viewport width",viewport:e}),i}detectBreakpointIssues(t,e,r){if(!r.simulationMode)return[];let i=[],n=this.hashUrl(t),s=parseInt(n,36),a=[...e].sort((o,c)=>o.viewport.width-c.viewport.width);for(let o=0;o<a.length-1;o++){let c=a[o],l=a[o+1],d=r.breakpoints.find(m=>m>c.viewport.width&&m<l.viewport.width);d&&(s+d+o*100)%100/100<.2&&i.push({breakpoint:d,description:"Layout shifts abruptly at this breakpoint",affectedElements:[".navigation",".sidebar"],suggestion:"Consider adding intermediate styles or adjusting breakpoint"})}return i}calculateLayoutScore(t,e){let i=e.filter(o=>o.severity==="critical").length*15,n=e.filter(o=>o.severity==="warning").length*5,s=e.filter(o=>o.severity==="info").length*1,a=t.every(o=>o.passed)?5:0;return Math.max(0,100-i-n-s+a)}generateRecommendations(t,e){let r=[],i=new Map;for(let n of t){let s=i.get(n.type)||[];i.set(n.type,[...s,n])}return i.has("horizontal-overflow")&&r.push("Use CSS overflow-x: hidden or adjust element widths to prevent horizontal scrolling"),i.has("touch-target-size")&&r.push("Increase touch target sizes to at least 44x44 pixels for better mobile usability"),i.has("font-size-too-small")&&r.push("Use relative font units (rem/em) and ensure minimum 16px base font size on mobile"),i.has("image-not-responsive")&&r.push("Use srcset and sizes attributes for responsive images, or CSS max-width: 100%"),e.length>0&&r.push("Review CSS media queries to ensure smooth transitions between breakpoints"),r}calculateStructuralDiff(t,e){let r=Math.abs(t.viewport.width-e.viewport.width),i=Math.abs(t.viewport.height-e.viewport.height),n=Math.min(50,(r+i)/20);return{baselineId:t.id,comparisonId:e.id,diffPercentage:n,diffPixels:Math.floor(n*1e3),regions:[],status:n<10?"acceptable":"changed"}}findContentBreaks(t){let e=[],r=this.hashUrl(t),i=parseInt(r.substring(0,6),36),n=[375,540,768,992,1200,1400],s=t.includes("shop")||t.includes("product")||t.includes("cart"),a=t.includes("dashboard")||t.includes("admin")||t.includes("panel"),o=t.includes("blog")||t.includes("article")||t.includes("news");for(let c=0;c<n.length;c++){let l=n[c],d=(i+c*100+l)%100,m,h,g;if(s?(m=40,h=[".product-grid",".cart-items",".checkout-form",".filters"],g="Product grid layout adjusts for viewport"):a?(m=50,h=[".sidebar",".dashboard-cards",".data-table",".nav-menu"],g="Dashboard layout reorganizes for smaller screens"):o?(m=60,h=[".article-content",".sidebar-widgets",".comments"],g="Content width and sidebar visibility changes"):(m=55,h=[".container",".grid",".navigation",".footer"],g="Content layout changes significantly"),d<m){let b=Math.min(h.length,1+Math.floor((i+l)%h.length)),w=h.slice(0,b);e.push({width:l,reason:g,affectedElements:w})}}return e}hashUrl(t){let e=0;for(let r=0;r<t.length;r++){let i=t.charCodeAt(r);e=(e<<5)-e+i,e=e&e}return Math.abs(e).toString(36)}suggestBreakpoints(t){let e=new Set;for(let i of t){let n=Math.round(i.width/100)*100;e.add(n)}let r=[576,768,992,1200,1400];for(let i of r)Array.from(e).some(n=>Math.abs(n-i)<50)||e.add(i);return Array.from(e).sort((i,n)=>i-n)}calculateBreakpointCoverage(t,e){if(e.length===0)return 100;let r=0;for(let i of e)t.some(n=>Math.abs(n-i.width)<50)&&r++;return Math.round(r/e.length*100)}async storeResult(t){let e=v();await this.memory.set(`visual-accessibility:responsive:${e}`,t,{namespace:"visual-accessibility",persist:!0})}};se();var Wv={stateSize:10,actionSize:5,actorHiddenLayers:[64,64],criticHiddenLayers:[64,64],numWorkers:4,nSteps:5,entropyCoeff:.01,valueLossCoeff:.5},Aa=class extends oe{actor;critic;a2cConfig;actions=[];constructor(t={}){super("a2c","actor-critic"),this.a2cConfig={...Wv,...t},this.initializeActions(),this.actor=new q({layerSizes:[this.a2cConfig.stateSize,...this.a2cConfig.actorHiddenLayers,this.a2cConfig.actionSize],activations:Array(this.a2cConfig.actorHiddenLayers.length).fill(new _).concat([new B]),learningRate:this.config.learningRate}),this.critic=new q({layerSizes:[this.a2cConfig.stateSize,...this.a2cConfig.criticHiddenLayers,1],activations:Array(this.a2cConfig.criticHiddenLayers.length).fill(new _).concat([new B]),learningRate:this.config.learningRate})}async predict(t){this.initialized||await this.initialize();let e=this.prepareState(t),r=this.actor.forward(e),i=he.forward(r),n=this.sampleAction(i),s=this.actions[n],a=this.critic.forward(e)[0],o=Math.max(.3,Math.min(1,i[n]+.4));return{action:s,confidence:o,value:a,reasoning:`A2C (${this.a2cConfig.numWorkers} workers): ${s.type}`}}async trainCore(t){let e=this.distributeToWorkers(t),r=0,i=0;for(let[n,s]of Object.entries(e)){if(s.length===0)continue;let a=this.calculateReturns(s),o=this.calculateAdvantages(s,a);for(let c=0;c<s.length;c++){let l=s[c],d=this.prepareState(l.state),m=this.actionToIndex(l.action),h=o[c],g=this.actor.forward(d),b=he.forward(g),C=-Math.log(b[m]+1e-10)*h,S=this.calculateEntropy(b),k=this.a2cConfig.entropyCoeff*S,P=new Float32Array(b.length);for(let Y=0;Y<P.length;Y++)Y===m?P[Y]=-h*(1-b[Y]):P[Y]=h*b[Y];this.actor.backward(P);for(let Y of this.actor.layers)Y.update(this.config.learningRate*.1);let O=this.critic.forward(d)[0],z=a[c],K=(O-z)**2,Re=new Float32Array([z]);this.critic.train(d,Re,new fe),r+=Math.abs(C-k),i+=K}}return{episode:this.episodeCount,totalReward:this.totalReward,averageReward:this.rewardHistory.reduce((n,s)=>n+s,0)/this.rewardHistory.length,loss:(r+i)/t.length,explorationRate:this.config.explorationRate,trainingTimeMs:0,timestamp:new Date}}getAlgorithmInfo(){return{type:this.type,category:this.category,version:"2.0.0",description:"Neural A2C for Fleet Coordination",capabilities:["Multi-worker parallel training","Advantage estimation","Combined policy and value learning"],hyperparameters:{stateSize:this.a2cConfig.stateSize,actionSize:this.a2cConfig.actionSize,numWorkers:this.a2cConfig.numWorkers,entropyCoeff:this.a2cConfig.entropyCoeff},stats:this.stats}}distributeToWorkers(t){let e={};for(let r=0;r<this.a2cConfig.numWorkers;r++)e[r]=[];return t.forEach((r,i)=>{let n=i%this.a2cConfig.numWorkers;e[n].push(r)}),e}calculateReturns(t){let e=[],r=0;for(let i=t.length-1;i>=0;i--)r=t[i].reward+this.config.discountFactor*r,e.unshift(r);return e}calculateAdvantages(t,e){return t.map((r,i)=>{let n=this.prepareState(r.state),s=this.critic.forward(n)[0];return e[i]-s})}prepareState(t){let e=t.features.slice(0,this.a2cConfig.stateSize);for(;e.length<this.a2cConfig.stateSize;)e.push(0);let r=Math.max(...e.map(Math.abs));if(r>0)for(let i=0;i<e.length;i++)e[i]/=r;return new Float32Array(e)}initializeActions(){this.actions=[{type:"coordinate",value:"parallel"},{type:"coordinate",value:"sequential"},{type:"coordinate",value:"distributed"},{type:"allocate",value:{agents:2}},{type:"rebalance",value:1}],this.a2cConfig.actionSize=this.actions.length,this.actor=new q({layerSizes:[this.a2cConfig.stateSize,...this.a2cConfig.actorHiddenLayers,this.a2cConfig.actionSize],activations:Array(this.a2cConfig.actorHiddenLayers.length).fill(new _).concat([new B]),learningRate:this.config.learningRate}),this.critic=new q({layerSizes:[this.a2cConfig.stateSize,...this.a2cConfig.criticHiddenLayers,1],activations:Array(this.a2cConfig.criticHiddenLayers.length).fill(new _).concat([new B]),learningRate:this.config.learningRate})}actionToIndex(t){let e=`${t.type}:${JSON.stringify(t.value)}`;for(let r=0;r<this.actions.length;r++)if(`${this.actions[r].type}:${JSON.stringify(this.actions[r].value)}`===e)return r;return 0}sampleAction(t){if(L()<this.config.explorationRate)return ue(0,this.actions.length);let e=L(),r=0;for(let i=0;i<t.length;i++)if(r+=t[i],e<=r)return i;return this.argmax(t)}argmax(t){let e=0,r=t[0];for(let i=1;i<t.length;i++)t[i]>r&&(r=t[i],e=i);return e}calculateEntropy(t){let e=0;for(let r=0;r<t.length;r++)t[r]>0&&(e-=t[r]*Math.log(t[r]));return e}async exportCustomData(){return{actor:this.actor.getParameters(),critic:this.critic.getParameters(),a2cConfig:this.a2cConfig}}async importCustomData(t){t.actor&&this.actor.setParameters(t.actor),t.critic&&this.critic.setParameters(t.critic),t.a2cConfig&&(this.a2cConfig={...this.a2cConfig,...t.a2cConfig}),this.initialized=!0}async resetAlgorithm(){this.actor=new q({layerSizes:[this.a2cConfig.stateSize,...this.a2cConfig.actorHiddenLayers,this.a2cConfig.actionSize],activations:Array(this.a2cConfig.actorHiddenLayers.length).fill(new _).concat([new B]),learningRate:this.config.learningRate}),this.critic=new q({layerSizes:[this.a2cConfig.stateSize,...this.a2cConfig.criticHiddenLayers,1],activations:Array(this.a2cConfig.criticHiddenLayers.length).fill(new _).concat([new B]),learningRate:this.config.learningRate})}};var Uv={maxConcurrentWorkflows:5,defaultTimeout:12e4,publishEvents:!0,enableParallelViewportTesting:!0,enableA2C:!0,enableFlashAttention:!0,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},Ie=R.create("visual-accessibility"),Ea=class extends Q{constructor(e,r,i,n={},s={},a={},o={},c){let l={...Uv,...n};super(e,"visual-accessibility",l,{verifyFindingTypes:["accessibility-violation","visual-regression","wcag-non-compliance"]});this.memory=r;this.agentCoordinator=i;this.visualTester=Ca({memory:r,llmRouter:c},s),this.accessibilityTester=new Pr(r,a),this.responsiveTester=new kr(r,o)}memory;agentCoordinator;visualTester;accessibilityTester;responsiveTester;a2cAlgorithm;flashAttention;async onInitialize(){if(this.config.enableA2C)try{this.a2cAlgorithm=new Aa({stateSize:10,actionSize:5,actorHiddenLayers:[64,64],criticHiddenLayers:[64,64],numWorkers:4}),Ie.info("A2C algorithm created successfully")}catch(e){throw Ie.error("Failed to create A2C:",e instanceof Error?e:void 0),new Error(`A2C creation failed: ${T(e)}`)}if(this.config.enableFlashAttention)try{this.flashAttention=await Me("test-similarity"),Ie.info("QEFlashAttention initialized successfully")}catch(e){throw Ie.error("Failed to initialize Flash Attention:",e instanceof Error?e:void 0),new Error(`Flash Attention initialization failed: ${T(e)}`)}this.subscribeToEvents(),await this.loadWorkflowState()}async onDispose(){await this.saveWorkflowState(),this.flashAttention&&(this.flashAttention.dispose(),this.flashAttention=void 0),this.a2cAlgorithm=void 0}getActiveWorkflows(){return super.getActiveWorkflows()}async runVisualTests(e,r){let i=v();try{if(this.startWorkflow(i,"visual"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Ie.warn("Topology degraded, using conservative strategy"),this.minCutMixin.shouldPauseOperations())return p(new Error("Operation paused: topology is in critical state"));if(!this.agentCoordinator.canSpawn())return p(new Error("Agent limit reached, cannot spawn visual testing agents"));let n=await this.spawnVisualTestingAgent(i);if(!n.success)return this.failWorkflow(i,n.error.message),p(n.error);this.addAgentToWorkflow(i,n.value);let s=[],a=0,o=0,c=0,l=[];for(let w of e)for(let C of r)l.push({url:w,viewport:C});if(this.config.enableA2C&&l.length>1){let w={urgency:5,availableResources:80,historicalFailureRate:.1},C=await this.prioritizeVisualTests(l.map(S=>({...S,priority:5})),w);C.success&&(l=C.value.orderedTests.map(S=>({url:S.url,viewport:S.viewport})),Ie.info(`[visual-accessibility] Using ${C.value.strategy} strategy for visual test order (confidence: ${C.value.confidence.toFixed(2)})`))}let d=l.length,m=0;for(let{url:w,viewport:C}of l){let S=await this.visualTester.captureScreenshot(w,{viewport:C});if(!S.success){o++,s.push({url:w,viewport:C,status:"failed",screenshot:{id:"",url:w,viewport:C,timestamp:new Date,path:Ce.create("error-placeholder.png"),metadata:{browser:"",os:"",fullPage:!1,loadTime:0}}});continue}let k=S.value,P=await this.visualTester.getBaseline(w,C);if(!P)await this.visualTester.setBaseline(k),c++,s.push({url:w,viewport:C,status:"new",screenshot:k});else{let O=await this.visualTester.compare(k,P.id);if(O.success){let z=O.value,K=z.status==="identical"||z.status==="acceptable"?"passed":"failed";K==="passed"?a++:o++,s.push({url:w,viewport:C,status:K,diff:z,screenshot:k}),K==="failed"&&this.config.publishEvents&&await this.publishVisualRegressionEvent(w,C,z)}else o++,s.push({url:w,viewport:C,status:"failed",screenshot:k})}m++,this.updateWorkflowProgress(i,m/d*100)}let h=this.workflows.get(i)?.startedAt.getTime()??Date.now(),g=Date.now()-h,b={totalTests:s.length,passed:a,failed:o,newBaselines:c,results:s,duration:g};return this.completeWorkflow(i),await this.agentCoordinator.stop(n.value),f(b)}catch(n){let s=y(n);return this.failWorkflow(i,s.message),{success:!1,error:s}}}async runAccessibilityAudit(e,r){let i=v();try{if(this.startWorkflow(i,"accessibility"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Ie.warn("Topology degraded, using conservative strategy"),this.minCutMixin.shouldPauseOperations())return p(new Error("Operation paused: topology is in critical state"));let n=await this.spawnAccessibilityTestingAgent(i,r);if(!n.success)return this.failWorkflow(i,n.error.message),p(n.error);this.addAgentToWorkflow(i,n.value);let s=[],a=0,o=0,c=0;for(let h=0;h<e.length;h++){let g=e[h],b=await this.accessibilityTester.audit(g,{wcagLevel:r});if(b.success){let w=b.value;s.push(w),a+=w.violations.length,o+=w.violations.filter(C=>C.impact==="critical").length,w.violations.length===0&&c++,this.config.publishEvents&&await this.publishAccessibilityAuditEvent(w)}this.updateWorkflowProgress(i,(h+1)/e.length*100)}let l=s.length>0?Math.round(s.reduce((h,g)=>h+g.score,0)/s.length):0,d=this.identifyTopIssues(s),m={totalUrls:e.length,passingUrls:c,totalViolations:a,criticalViolations:o,averageScore:l,reports:s,topIssues:d};return this.completeWorkflow(i),await this.agentCoordinator.stop(n.value),f(m)}catch(n){let s=y(n);return this.failWorkflow(i,s.message),{success:!1,error:s}}}async approveVisualChanges(e,r){try{for(let i of e){let n=await this.memory.get(`visual-accessibility:diff:${i}`);if(!n)continue;let s=await this.memory.get(`visual-accessibility:screenshot:${n.comparisonId}`);s&&(await this.visualTester.setBaseline(s),this.config.publishEvents&&await this.publishBaselineUpdatedEvent(s,r))}return f(void 0)}catch(i){return p(y(i))}}async generateRemediationPlan(e){try{let r=[];for(let a of e){let o=this.createRemediation(a);r.push(o)}let i={trivial:0,minor:1,moderate:2,major:3};r.sort((a,o)=>i[a.effort]-i[o.effort]);let n=this.calculateTotalEffort(r),s={violations:r,totalEffort:n,prioritizedOrder:r.map(a=>a.violationId)};return f(s)}catch(r){return p(y(r))}}async getVisualTestingStatus(){try{let e=await this.memory.search("visual-accessibility:baseline:*",1e3),r=e.length,i=await this.memory.search("visual-accessibility:diff:*",1e3),n=0;for(let h of i){let g=await this.memory.get(h);g&&(g.status==="changed"||g.status==="failed")&&n++}let a=Array.from(this.workflows.values()).filter(h=>h.type==="visual"&&h.status==="completed").sort((h,g)=>(g.completedAt?.getTime()??0)-(h.completedAt?.getTime()??0))[0]?.completedAt??new Date,o=Array.from(this.workflows.values()).filter(h=>h.type==="visual").length,c=Array.from(this.workflows.values()).filter(h=>h.type==="visual"&&h.status==="failed").length,l=o>0?c/o:0,d=await this.calculateViewportCoverage(e);return f({baselineCount:r,pendingReviews:n,lastTestRun:a,failureRate:l,coverageByViewport:d})}catch(e){return p(y(e))}}async runVisualRegression(e){let r=v();try{if(this.startWorkflow(r,"visual"),!this.agentCoordinator.canSpawn())return this.failWorkflow(r,"Agent limit reached"),p(new Error("Agent limit reached, cannot spawn visual testing agents"));let i=await this.spawnVisualTestingAgent(r);if(!i.success)return this.failWorkflow(r,i.error.message),p(i.error);this.addAgentToWorkflow(r,i.value);let n=[],s={width:1280,height:720,deviceScaleFactor:1,isMobile:!1,hasTouch:!1},a=e.viewports??[s];for(let o of e.pages)for(let c of a){let l=await this.visualTester.captureScreenshot(`${e.baselineUrl}${o}`,{viewport:c}),d=await this.visualTester.captureScreenshot(`${e.compareUrl}${o}`,{viewport:c});if(l.success&&d.success){let m=await this.visualTester.compare(d.value,l.value.id);m.success?n.push({page:o,diffPercentage:m.value.diffPercentage,passed:m.value.status==="identical"||m.value.status==="acceptable"}):n.push({page:o,diffPercentage:100,passed:!1})}else n.push({page:o,diffPercentage:100,passed:!1})}return this.completeWorkflow(r),await this.agentCoordinator.stop(i.value),f({differences:n})}catch(i){let n=y(i);return this.failWorkflow(r,n.message),{success:!1,error:n}}}async runAccessibilityAuditSingle(e){let r=await this.runAccessibilityAudit([e.url],e.wcagLevel);if(!r.success)return p(r.error);let i=r.value.reports[0];return i?f({violations:i.violations,wcagLevel:i.wcagLevel,score:i.score}):f({violations:[],wcagLevel:e.wcagLevel,score:100})}async compareScreenshots(e){try{let r=await this.memory.get(`visual-accessibility:screenshot:${e.baseline}`),i=await this.memory.get(`visual-accessibility:screenshot:${e.current}`);if(r&&i){let n=await this.visualTester.compare(i,r.id);if(n.success){let s=e.threshold??.1;return f({diffPercentage:n.value.diffPercentage,passed:n.value.diffPercentage<=s*100,diffImagePath:n.value.diffImagePath?.value})}}return f({diffPercentage:0,passed:!0})}catch(r){return p(y(r))}}async analyzeColorContrast(e){try{let r=e.wcagLevel??"AA",i=await this.accessibilityTester.audit(e.url,{wcagLevel:r});if(!i.success)return p(i.error);let s=i.value.violations.filter(a=>a.id.includes("color-contrast")||a.id.includes("contrast")).flatMap(a=>a.nodes.map(o=>({element:o.target.join(" "),foreground:"#000000",background:"#ffffff",ratio:1,required:r==="AAA"?7:4.5})));return f({issues:s})}catch(r){return p(y(r))}}async testResponsiveDesign(e){try{let r=[];for(let i of e.viewports){let n={width:i.width,height:i.height,deviceScaleFactor:1,isMobile:i.width<768,hasTouch:i.width<1024},s=await this.visualTester.captureScreenshot(e.url,{viewport:n}),a=i.name??`${i.width}x${i.height}`,o=[];s.success||o.push(`Failed to capture screenshot: ${s.error.message}`),r.push({viewport:a,passed:o.length===0,issues:o})}return f({viewportResults:r})}catch(r){return p(y(r))}}async spawnVisualTestingAgent(e){let r={name:`visual-tester-${e.slice(0,8)}`,domain:"visual-accessibility",type:"tester",capabilities:["visual-testing","screenshot-capture","image-diff"],config:{workflowId:e}};return this.agentCoordinator.spawn(r)}async spawnAccessibilityTestingAgent(e,r){let i={name:`a11y-tester-${e.slice(0,8)}`,domain:"visual-accessibility",type:"analyzer",capabilities:["accessibility-audit","wcag-validation",r],config:{workflowId:e,wcagLevel:r}};return this.agentCoordinator.spawn(i)}async calculateViewportCoverage(e){let r=new Map([["mobile",0],["tablet",0],["desktop",0]]),i=new Set;for(let a of e){let o=a.match(/baseline:([^_]+)_(\d+)x(\d+)_/);if(o){let[,c,l]=o,d=parseInt(l,10);i.add(c);let m=this.categorizeViewport(d);r.set(m,(r.get(m)||0)+1)}}let n=i.size||1,s=new Map;for(let[a,o]of r){let c=Math.min(100,Math.round(o/n*100));s.set(a,c)}return e.length===0?new Map([["mobile",0],["tablet",0],["desktop",0]]):s}categorizeViewport(e){return e<=480?"mobile":e<=1024?"tablet":"desktop"}async publishVisualRegressionEvent(e,r,i){let n={id:v(),type:"visual-accessibility.VisualRegressionDetected",timestamp:new Date,source:"visual-accessibility",payload:{url:e,viewport:r,diffPercentage:i.diffPercentage,diffImagePath:i.diffImagePath?.value}};await this.eventBus.publish(n)}async publishAccessibilityAuditEvent(e){let r={id:v(),type:"visual-accessibility.AccessibilityAuditCompleted",timestamp:new Date,source:"visual-accessibility",payload:{url:e.url,violations:e.violations.length,score:e.score,wcagLevel:e.wcagLevel}};await this.eventBus.publish(r)}async publishBaselineUpdatedEvent(e,r){let i={id:v(),type:"visual-accessibility.BaselineUpdated",timestamp:new Date,source:"visual-accessibility",payload:{screenshotId:e.id,url:e.url,viewport:e.viewport,reason:r}};await this.eventBus.publish(i)}identifyTopIssues(e){let r=new Map;for(let i of e)for(let n of i.violations){let s=r.get(n.id);s?(s.occurrences++,s.affectedUrls.includes(i.url)||s.affectedUrls.push(i.url)):r.set(n.id,{ruleId:n.id,description:n.description,occurrences:1,impact:n.impact,affectedUrls:[i.url]})}return Array.from(r.values()).sort((i,n)=>n.occurrences-i.occurrences).slice(0,10)}createRemediation(e){let r=this.estimateEffort(e);return{violationId:e.id,description:e.description,fix:e.help,codeExample:this.generateCodeExample(e),effort:r,wcagReference:e.wcagCriteria[0]?.id??""}}estimateEffort(e){let r=e.nodes.length;return e.impact==="minor"&&r<=3?"trivial":e.impact==="minor"||r<=5?"minor":e.impact==="serious"&&r<=10?"moderate":"major"}generateCodeExample(e){return e.id.includes("alt")?'<img src="..." alt="Descriptive text for the image">':e.id.includes("label")?`<label for="input-id">Label text</label>
|
|
3006
|
-
<input id="input-id" type="text">`:e.id.includes("button")?'<button aria-label="Descriptive action">Icon</button>':"<!-- See WCAG guidelines for specific implementation -->"}calculateTotalEffort(e){let r={trivial:1,minor:2,moderate:4,major:8},i=e.reduce((n,s)=>n+r[s.effort],0);return i<=5?"trivial":i<=15?"minor":i<=40?"moderate":"major"}async prioritizeVisualTests(e,r){if(!this.a2cAlgorithm||!this.config.enableA2C)return f({orderedTests:e.map(i=>({...i,priority:i.priority??5,reason:"default"})),strategy:"default",confidence:1});if(e.length===0)return f({orderedTests:[],strategy:"empty",confidence:1});try{let i={id:`visual-priority-${Date.now()}`,features:[r.urgency/10,r.availableResources/100,r.historicalFailureRate,e.length/100,e.filter(l=>l.viewport.width<=480).length/Math.max(1,e.length),e.filter(l=>l.viewport.width>1024).length/Math.max(1,e.length),e.filter(l=>(l.priority??5)>7).length/Math.max(1,e.length),e.filter(l=>l.url.includes("dashboard")).length/Math.max(1,e.length),e.filter(l=>l.url.includes("checkout")).length/Math.max(1,e.length),e.filter(l=>l.url.includes("login")).length/Math.max(1,e.length)]},n=await this.a2cAlgorithm.predict(i),s=e.map(l=>({...l,priority:l.priority??5,reason:"default"})),a="default";switch(n.action.type){case"coordinate":if(n.action.value==="parallel")s.sort((h,g)=>h.viewport.width-g.viewport.width),s=s.map(h=>({...h,priority:10-Math.floor(h.viewport.width/200),reason:"parallel-viewport-order"})),a="parallel-viewport-order";else if(n.action.value==="sequential"){let h=["checkout","payment","login"];s.sort((g,b)=>{let w=h.some(S=>g.url.includes(S))?1:0;return(h.some(S=>b.url.includes(S))?1:0)-w}),s=s.map(g=>({...g,priority:h.some(b=>g.url.includes(b))?9:5,reason:"sequential-critical-url"})),a="sequential-critical-url"}break;case"allocate":let l=typeof n.action.value=="object"?n.action.value.agents??2:2,d=Math.ceil(s.length/l);s=s.map((h,g)=>({...h,priority:10-Math.floor(g/d),reason:`allocate-agent-${Math.floor(g/d)}`})),a="allocate-by-agent";break;case"rebalance":let m=new Map;for(let h of s)m.set(h.viewport.width,(m.get(h.viewport.width)||0)+1);s.sort((h,g)=>(m.get(h.viewport.width)||0)-(m.get(g.viewport.width)||0)),s=s.map(h=>({...h,priority:10-(m.get(h.viewport.width)||0),reason:"rebalance-viewport-coverage"})),a="rebalance-viewport-coverage";break;default:break}let o=await this.calculatePrioritizationReward(s,r),c=n.action;return await this.a2cAlgorithm.train({state:i,action:c,reward:o,nextState:i,done:!0}),Ie.info(`[visual-accessibility] A2C prioritized ${e.length} visual tests using ${a} strategy (confidence: ${n.confidence.toFixed(2)})`),f({orderedTests:s,strategy:a,confidence:n.confidence})}catch(i){return Ie.error("A2C prioritization failed:",i instanceof Error?i:void 0),f({orderedTests:e.map(n=>({...n,priority:n.priority??5,reason:"fallback"})),strategy:"fallback",confidence:.5})}}async calculatePrioritizationReward(e,r){let i=.5,n=e.slice(0,Math.ceil(e.length/4)),s=n.filter(o=>["checkout","payment","login","dashboard"].some(c=>o.url.includes(c))).length;i+=Math.min(.3,s/n.length);let a=new Set(e.map(o=>`${o.viewport.width}x${o.viewport.height}`));return i+=Math.min(.2,a.size/10),r.availableResources<30&&e.length>50&&(i-=.1),Math.max(0,Math.min(1,i))}async findSimilarImages(e,r,i=5){if(!this.flashAttention||!this.config.enableFlashAttention)return this.cosineSimilarityFallback(e,r,i);try{return(await this.flashAttention.computeTestSimilarity(e,r,i)).map(s=>({index:s.index,similarity:s.similarity,imagePath:`image-${s.index}.png`}))}catch(n){return Ie.error("Flash Attention similarity search failed:",n instanceof Error?n:void 0),this.cosineSimilarityFallback(e,r,i)}}cosineSimilarityFallback(e,r,i){let n=[];for(let s=0;s<r.length;s++){let o=(tt(e,r[s])+1)/2;n.push({index:s,similarity:o,imagePath:`image-${s}.png`})}return n.sort((s,a)=>a.similarity-s.similarity),n.slice(0,i)}async storeVisualPattern(e,r,i,n){if(!(!this.flashAttention||!this.config.enableFlashAttention))try{let s=this.createVisualEmbedding(e,r,i,n);await this.memory.set(`visual-accessibility:embedding:${e}:${r.width}x${r.height}`,{embedding:s,url:e,viewport:r,diffScore:i,passed:n,timestamp:new Date},{namespace:"visual-accessibility",persist:!0}),Ie.info(`Stored visual pattern for ${e} at ${r.width}x${r.height}`)}catch(s){Ie.error("Failed to store visual pattern:",s instanceof Error?s:void 0)}}createVisualEmbedding(e,r,i,n){let s=[],a=this.hashString(e);for(let l=0;l<100;l++)s.push((a>>l%32&1)===1?1:0);s.push(r.width/2e3),s.push(r.height/2e3),s.push(r.deviceScaleFactor/3),s.push(r.isMobile?1:0),s.push(r.hasTouch?1:0),s.push(r.width<=480?1:0),s.push(r.width<=1024&&r.width>480?1:0),s.push(r.width>1024?1:0);let o=r.height>r.width;s.push(o?1:0),s.push(o?0:1),s.push(i/100),s.push(n?1:0),s.push(i>10?1:0),s.push(i>50?1:0);let c=this.extractPathFeatures(e);return s.push(...c.slice(0,270)),new Float32Array(s.slice(0,384))}hashString(e){let r=0;for(let i=0;i<e.length;i++)r=(r<<5)-r+e.charCodeAt(i),r=r|0;return Math.abs(r)}extractPathFeatures(e){let r=[],i=new URL(e).pathname,n=["dashboard","checkout","login","profile","settings","api","admin","search"];for(let a of n)r.push(i.includes(a)?1:0);let s=i.split("/").filter(Boolean).length;for(r.push(s/10),r.push(e.includes("?")?1:0),r.push(e.startsWith("https://")?1:0);r.length<270;)r.push(0);return r}subscribeToEvents(){this.eventBus.subscribe("code-intelligence.FileChanged",this.handleFileChanged.bind(this)),this.eventBus.subscribe("ci-cd.DeploymentCompleted",this.handleDeploymentCompleted.bind(this))}async handleFileChanged(e){}async handleDeploymentCompleted(e){}async loadWorkflowState(){let e=await this.memory.get("visual-accessibility:coordinator:workflows");if(e)for(let r of e)r.status==="running"&&(r.status="failed",r.error="Coordinator restarted",r.completedAt=new Date),this.workflows.set(r.id,r)}async saveWorkflowState(){let e=Array.from(this.workflows.values());await this.memory.set("visual-accessibility:coordinator:workflows",e,{namespace:"visual-accessibility",persist:!0})}requiresConsensus(e){return this.consensusMixin.requiresConsensus(e)}async verifyFinding(e){return this.consensusMixin.verifyFinding(e)}async verifyAccessibilityViolation(e,r){let i=V({id:v(),type:"accessibility-violation",confidence:r,description:`Accessibility violation: ${e.description} (${e.impact} impact)`,payload:e,detectedBy:"visual-accessibility-coordinator",severity:e.impact==="critical"?"critical":e.impact==="serious"?"high":e.impact==="moderate"?"medium":"low"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return!!(n.success&&n.value.verdict==="verified")}return!0}async verifyVisualRegression(e,r){let i=V({id:v(),type:"visual-regression",confidence:r,description:`Visual regression detected at ${e.url} (${e.viewport.width}x${e.viewport.height}): ${e.diffPercentage.toFixed(2)}% difference`,payload:e,detectedBy:"visual-accessibility-coordinator",severity:e.diffPercentage>20?"critical":e.diffPercentage>10?"high":e.diffPercentage>5?"medium":"low"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return!!(n.success&&n.value.verdict==="verified")}return!0}onTopologyHealthChange(e){return this.minCutMixin.onTopologyHealthChange(e)}};A();var ol=class extends j{constructor(e,r,i,n={},s){super(e,r);this.agentCoordinator=i;this.llmRouter=s;this.pluginConfig=n}agentCoordinator;llmRouter;coordinator=null;visualTester=null;accessibilityTester=null;responsiveTester=null;pluginConfig;get name(){return"visual-accessibility"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{runVisualTests:this.runVisualTests.bind(this),runAccessibilityAudit:this.runAccessibilityAudit.bind(this),approveVisualChanges:this.approveVisualChanges.bind(this),generateRemediationPlan:this.generateRemediationPlan.bind(this),getVisualTestingStatus:this.getVisualTestingStatus.bind(this),captureScreenshot:this.captureScreenshot.bind(this),captureElement:this.captureElement.bind(this),auditAccessibility:this.auditAccessibility.bind(this),checkContrast:this.checkContrast.bind(this),validateWCAGLevel:this.validateWCAGLevel.bind(this),checkKeyboardNavigation:this.checkKeyboardNavigation.bind(this),testResponsiveness:this.testResponsiveness.bind(this),analyzeBreakpoints:this.analyzeBreakpoints.bind(this),registerWorkflowActions:this.registerWorkflowActions.bind(this),getCoordinator:()=>this.coordinator,getVisualTester:()=>this.visualTester,getAccessibilityTester:()=>this.accessibilityTester,getResponsiveTester:()=>this.responsiveTester}}getTaskHandlers(){return new Map([["run-visual-tests",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.urls,i=e.viewports;return!r||r.length===0?p(new Error("Invalid run-visual-tests payload: missing urls")):this.coordinator.runVisualTests(r,i||[{width:1920,height:1080,deviceScaleFactor:1,isMobile:!1,hasTouch:!1}])}],["run-accessibility-audit",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.urls,i=e.level||"AA";return!r||r.length===0?p(new Error("Invalid run-accessibility-audit payload: missing urls")):this.coordinator.runAccessibilityAudit(r,i)}],["capture-screenshot",async e=>{if(!this.visualTester)return p(new Error("Visual tester not initialized"));let r=e.url;return r?this.visualTester.captureScreenshot(r,e.options):p(new Error("Invalid capture-screenshot payload: missing url"))}],["test-responsiveness",async e=>{if(!this.responsiveTester)return p(new Error("Responsive tester not initialized"));let r=e.url;return r?this.responsiveTester.testResponsiveness(r,e.options):p(new Error("Invalid test-responsiveness payload: missing url"))}],["validate-wcag",async e=>{if(!this.accessibilityTester)return p(new Error("Accessibility tester not initialized"));let r=e.url;if(!r)return p(new Error("Invalid validate-wcag payload: missing url"));let i=e.level||"AA";return this.accessibilityTester.validateWCAGLevel(r,i)}]])}async onInitialize(){this.visualTester=Ca({memory:this.memory,llmRouter:this.llmRouter},this.pluginConfig.visualTester),this.accessibilityTester=new Pr(this.memory,this.pluginConfig.accessibilityTester),this.responsiveTester=new kr(this.memory,this.pluginConfig.responsiveTester),this.coordinator=new Ea(this.eventBus,this.memory,this.agentCoordinator,this.pluginConfig.coordinator,this.pluginConfig.visualTester,this.pluginConfig.accessibilityTester,this.pluginConfig.responsiveTester,this.llmRouter),await this.coordinator.initialize(),this.updateHealth({status:"idle",agents:{total:0,active:0,idle:0,failed:0},lastActivity:new Date,errors:[]})}async onDispose(){this.coordinator&&await this.coordinator.dispose(),this.coordinator=null,this.visualTester=null,this.accessibilityTester=null,this.responsiveTester=null}subscribeToEvents(){this.eventBus.subscribe("ci-cd.DeploymentCompleted",this.handleDeploymentCompleted.bind(this)),this.eventBus.subscribe("code-intelligence.FileChanged",this.handleFileChanged.bind(this)),this.eventBus.subscribe("quality-assessment.QualityGateTriggered",this.handleQualityGateTriggered.bind(this))}async onEvent(e){switch(this.updateHealth({lastActivity:new Date}),e.type){case"ci-cd.DeploymentCompleted":await this.handleDeploymentCompleted(e);break;case"code-intelligence.FileChanged":await this.handleFileChanged(e);break;case"quality-assessment.QualityGateTriggered":await this.handleQualityGateTriggered(e);break;default:break}}async runVisualTests(e,r){this.ensureInitialized();try{let i=await this.coordinator.runVisualTests(e,r);return i.success?this.trackSuccessfulTest("visual",i.value.totalTests):this.trackFailedTest(i.error),i}catch(i){return this.handleError(i)}}async runAccessibilityAudit(e,r){this.ensureInitialized();try{let i=await this.coordinator.runAccessibilityAudit(e,r);return i.success?this.trackSuccessfulTest("accessibility",i.value.totalUrls):this.trackFailedTest(i.error),i}catch(i){return this.handleError(i)}}async approveVisualChanges(e,r){this.ensureInitialized();try{return await this.coordinator.approveVisualChanges(e,r)}catch(i){return this.handleError(i)}}async generateRemediationPlan(e){this.ensureInitialized();try{return await this.coordinator.generateRemediationPlan(e)}catch(r){return this.handleError(r)}}async getVisualTestingStatus(){this.ensureInitialized();try{return await this.coordinator.getVisualTestingStatus()}catch(e){return this.handleError(e)}}async captureScreenshot(e,r){this.ensureInitialized();try{return await this.visualTester.captureScreenshot(e,r)}catch(i){return this.handleError(i)}}async captureElement(e,r,i){this.ensureInitialized();try{return await this.visualTester.captureElement(e,r,i)}catch(n){return this.handleError(n)}}async auditAccessibility(e,r){this.ensureInitialized();try{return await this.accessibilityTester.audit(e,r)}catch(i){return this.handleError(i)}}async checkContrast(e){this.ensureInitialized();try{return await this.accessibilityTester.checkContrast(e)}catch(r){return this.handleError(r)}}async validateWCAGLevel(e,r){this.ensureInitialized();try{return await this.accessibilityTester.validateWCAGLevel(e,r)}catch(i){return this.handleError(i)}}async checkKeyboardNavigation(e){this.ensureInitialized();try{return await this.accessibilityTester.checkKeyboardNavigation(e)}catch(r){return this.handleError(r)}}async testResponsiveness(e,r){this.ensureInitialized();try{return await this.responsiveTester.testResponsiveness(e,r)}catch(i){return this.handleError(i)}}async analyzeBreakpoints(e){this.ensureInitialized();try{return await this.responsiveTester.analyzeBreakpoints(e)}catch(r){return this.handleError(r)}}async handleDeploymentCompleted(e){let r=e.payload;await this.memory.set(`visual-accessibility:deployment:${Date.now()}`,r,{namespace:"visual-accessibility",ttl:3600})}async handleFileChanged(e){let r=e.payload;(r.file.endsWith(".css")||r.file.endsWith(".scss"))&&await this.memory.set(`visual-accessibility:style-change:${Date.now()}`,r,{namespace:"visual-accessibility",ttl:3600})}async handleQualityGateTriggered(e){let r=e.payload;r.checks.includes("accessibility")&&await this.memory.set(`visual-accessibility:quality-gate:${r.gateId}`,{pending:!0,timestamp:Date.now()},{namespace:"visual-accessibility",ttl:3600})}ensureInitialized(){if(!this._initialized)throw new Error("VisualAccessibilityPlugin is not initialized");if(!this.coordinator||!this.visualTester||!this.accessibilityTester||!this.responsiveTester)throw new Error("VisualAccessibilityPlugin services are not available")}handleError(e){let r=y(e),i=this.getHealth();return this.updateHealth({errors:[...i.errors.slice(-9),r.message],status:i.errors.length>=5?"degraded":i.status}),{success:!1,error:r}}trackSuccessfulTest(e,r){let i=this.getHealth();this.updateHealth({agents:{...i.agents,total:i.agents.total+1,idle:i.agents.idle+1},lastActivity:new Date})}trackFailedTest(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,failed:r.agents.failed+1},errors:[...r.errors.slice(-9),e.message]})}registerWorkflowActions(e){if(!this._initialized)throw new Error("VisualAccessibilityPlugin must be initialized before registering workflow actions");e.registerAction("visual-accessibility","runVisualTest",async(r,i)=>{try{this.ensureInitialized();let n=this.extractUrls(r);if(n.length===0)return p(new Error('No URLs provided for visual test. Provide "url" or "urls" parameter.'));let s=this.extractViewports(r),a=await this.coordinator.runVisualTests(n,s);return a.success?f({passed:a.value.passed,failed:a.value.failed,totalTests:a.value.totalTests,newBaselines:a.value.newBaselines,duration:a.value.duration,results:a.value.results.map(o=>({url:o.url,viewport:`${o.viewport.width}x${o.viewport.height}`,status:o.status,diffPercentage:o.diff?.diffPercentage}))}):p(a.error)}catch(n){return p(y(n))}}),e.registerAction("visual-accessibility","runAccessibilityTest",async(r,i)=>{try{this.ensureInitialized();let n=this.extractUrls(r);if(n.length===0)return p(new Error('No URLs provided for accessibility test. Provide "url" or "urls" parameter.'));let s=this.extractWcagLevel(r),a=await this.coordinator.runAccessibilityAudit(n,s);return a.success?f({totalUrls:a.value.totalUrls,passingUrls:a.value.passingUrls,totalViolations:a.value.totalViolations,criticalViolations:a.value.criticalViolations,averageScore:a.value.averageScore,topIssues:a.value.topIssues.map(o=>({ruleId:o.ruleId,description:o.description,occurrences:o.occurrences,impact:o.impact}))}):p(a.error)}catch(n){return p(y(n))}})}extractUrls(e){return typeof e.url=="string"?[e.url]:Array.isArray(e.urls)?e.urls.filter(r=>typeof r=="string"):typeof e.target=="string"?[e.target]:[]}extractViewports(e){let r=[{width:1920,height:1080,deviceScaleFactor:1,isMobile:!1,hasTouch:!1},{width:1280,height:720,deviceScaleFactor:1,isMobile:!1,hasTouch:!1},{width:768,height:1024,deviceScaleFactor:2,isMobile:!0,hasTouch:!0},{width:375,height:812,deviceScaleFactor:3,isMobile:!0,hasTouch:!0}];if(Array.isArray(e.viewports))return e.viewports.filter(i=>typeof i=="object"&&i!==null).map(i=>({width:typeof i.width=="number"?i.width:1920,height:typeof i.height=="number"?i.height:1080,deviceScaleFactor:typeof i.deviceScaleFactor=="number"?i.deviceScaleFactor:1,isMobile:typeof i.isMobile=="boolean"?i.isMobile:!1,hasTouch:typeof i.hasTouch=="boolean"?i.hasTouch:!1}));if(typeof e.viewport=="object"&&e.viewport!==null){let i=e.viewport;return[{width:typeof i.width=="number"?i.width:1920,height:typeof i.height=="number"?i.height:1080,deviceScaleFactor:typeof i.deviceScaleFactor=="number"?i.deviceScaleFactor:1,isMobile:typeof i.isMobile=="boolean"?i.isMobile:!1,hasTouch:typeof i.hasTouch=="boolean"?i.hasTouch:!1}]}return r}extractWcagLevel(e){let i=(e.level??e.wcagLevel??"AA").toUpperCase();return i==="A"||i==="AA"||i==="AAA"?i:"AA"}};function Im(u,t,e,r,i){return new ol(u,t,e,r,i)}M();A();M();import*as Fm from"net";import{execFile as Mm}from"child_process";A();H();se();var Qv={defaultTimeout:6e4,maxConcurrentFaults:3,enableDryRun:!0,safetyCheckInterval:5e3,autoRollbackOnFailure:!0,enableLLMAnalysis:!0,llmModelTier:2,llmMaxTokens:2048},N=R.create("chaos-resilience/chaos-engineer"),Dr=class u{config;activeExperiments=new Map;activeFaults=new Map;httpClient;metricsCollector;stressWorkers=new Map;memory;llmRouter;constructor(t,e={}){this.memory=t.memory,this.llmRouter=t.llmRouter,this.config={...Qv,...e},this.httpClient=new Be,this.metricsCollector=dc()}async createExperiment(t){try{let e=this.validateExperiment(t);if(!e.success)return p(e.error);let r=await this.analyzeExperimentWithLLM(t);return r&&N.info(`LLM Analysis:
|
|
3006
|
+
<input id="input-id" type="text">`:e.id.includes("button")?'<button aria-label="Descriptive action">Icon</button>':"<!-- See WCAG guidelines for specific implementation -->"}calculateTotalEffort(e){let r={trivial:1,minor:2,moderate:4,major:8},i=e.reduce((n,s)=>n+r[s.effort],0);return i<=5?"trivial":i<=15?"minor":i<=40?"moderate":"major"}async prioritizeVisualTests(e,r){if(!this.a2cAlgorithm||!this.config.enableA2C)return f({orderedTests:e.map(i=>({...i,priority:i.priority??5,reason:"default"})),strategy:"default",confidence:1});if(e.length===0)return f({orderedTests:[],strategy:"empty",confidence:1});try{let i={id:`visual-priority-${Date.now()}`,features:[r.urgency/10,r.availableResources/100,r.historicalFailureRate,e.length/100,e.filter(l=>l.viewport.width<=480).length/Math.max(1,e.length),e.filter(l=>l.viewport.width>1024).length/Math.max(1,e.length),e.filter(l=>(l.priority??5)>7).length/Math.max(1,e.length),e.filter(l=>l.url.includes("dashboard")).length/Math.max(1,e.length),e.filter(l=>l.url.includes("checkout")).length/Math.max(1,e.length),e.filter(l=>l.url.includes("login")).length/Math.max(1,e.length)]},n=await this.a2cAlgorithm.predict(i),s=e.map(l=>({...l,priority:l.priority??5,reason:"default"})),a="default";switch(n.action.type){case"coordinate":if(n.action.value==="parallel")s.sort((l,d)=>l.viewport.width-d.viewport.width),s=s.map(l=>({...l,priority:10-Math.floor(l.viewport.width/200),reason:"parallel-viewport-order"})),a="parallel-viewport-order";else if(n.action.value==="sequential"){let l=["checkout","payment","login"];s.sort((d,m)=>{let h=l.some(b=>d.url.includes(b))?1:0;return(l.some(b=>m.url.includes(b))?1:0)-h}),s=s.map(d=>({...d,priority:l.some(m=>d.url.includes(m))?9:5,reason:"sequential-critical-url"})),a="sequential-critical-url"}break;case"allocate":{let l=typeof n.action.value=="object"?n.action.value.agents??2:2,d=Math.ceil(s.length/l);s=s.map((m,h)=>({...m,priority:10-Math.floor(h/d),reason:`allocate-agent-${Math.floor(h/d)}`})),a="allocate-by-agent";break}case"rebalance":{let l=new Map;for(let d of s)l.set(d.viewport.width,(l.get(d.viewport.width)||0)+1);s.sort((d,m)=>(l.get(d.viewport.width)||0)-(l.get(m.viewport.width)||0)),s=s.map(d=>({...d,priority:10-(l.get(d.viewport.width)||0),reason:"rebalance-viewport-coverage"})),a="rebalance-viewport-coverage";break}default:break}let o=await this.calculatePrioritizationReward(s,r),c=n.action;return await this.a2cAlgorithm.train({state:i,action:c,reward:o,nextState:i,done:!0}),Ie.info(`[visual-accessibility] A2C prioritized ${e.length} visual tests using ${a} strategy (confidence: ${n.confidence.toFixed(2)})`),f({orderedTests:s,strategy:a,confidence:n.confidence})}catch(i){return Ie.error("A2C prioritization failed:",i instanceof Error?i:void 0),f({orderedTests:e.map(n=>({...n,priority:n.priority??5,reason:"fallback"})),strategy:"fallback",confidence:.5})}}async calculatePrioritizationReward(e,r){let i=.5,n=e.slice(0,Math.ceil(e.length/4)),s=n.filter(o=>["checkout","payment","login","dashboard"].some(c=>o.url.includes(c))).length;i+=Math.min(.3,s/n.length);let a=new Set(e.map(o=>`${o.viewport.width}x${o.viewport.height}`));return i+=Math.min(.2,a.size/10),r.availableResources<30&&e.length>50&&(i-=.1),Math.max(0,Math.min(1,i))}async findSimilarImages(e,r,i=5){if(!this.flashAttention||!this.config.enableFlashAttention)return this.cosineSimilarityFallback(e,r,i);try{return(await this.flashAttention.computeTestSimilarity(e,r,i)).map(s=>({index:s.index,similarity:s.similarity,imagePath:`image-${s.index}.png`}))}catch(n){return Ie.error("Flash Attention similarity search failed:",n instanceof Error?n:void 0),this.cosineSimilarityFallback(e,r,i)}}cosineSimilarityFallback(e,r,i){let n=[];for(let s=0;s<r.length;s++){let o=(tt(e,r[s])+1)/2;n.push({index:s,similarity:o,imagePath:`image-${s}.png`})}return n.sort((s,a)=>a.similarity-s.similarity),n.slice(0,i)}async storeVisualPattern(e,r,i,n){if(!(!this.flashAttention||!this.config.enableFlashAttention))try{let s=this.createVisualEmbedding(e,r,i,n);await this.memory.set(`visual-accessibility:embedding:${e}:${r.width}x${r.height}`,{embedding:s,url:e,viewport:r,diffScore:i,passed:n,timestamp:new Date},{namespace:"visual-accessibility",persist:!0}),Ie.info(`Stored visual pattern for ${e} at ${r.width}x${r.height}`)}catch(s){Ie.error("Failed to store visual pattern:",s instanceof Error?s:void 0)}}createVisualEmbedding(e,r,i,n){let s=[],a=this.hashString(e);for(let l=0;l<100;l++)s.push((a>>l%32&1)===1?1:0);s.push(r.width/2e3),s.push(r.height/2e3),s.push(r.deviceScaleFactor/3),s.push(r.isMobile?1:0),s.push(r.hasTouch?1:0),s.push(r.width<=480?1:0),s.push(r.width<=1024&&r.width>480?1:0),s.push(r.width>1024?1:0);let o=r.height>r.width;s.push(o?1:0),s.push(o?0:1),s.push(i/100),s.push(n?1:0),s.push(i>10?1:0),s.push(i>50?1:0);let c=this.extractPathFeatures(e);return s.push(...c.slice(0,270)),new Float32Array(s.slice(0,384))}hashString(e){let r=0;for(let i=0;i<e.length;i++)r=(r<<5)-r+e.charCodeAt(i),r=r|0;return Math.abs(r)}extractPathFeatures(e){let r=[],i=new URL(e).pathname,n=["dashboard","checkout","login","profile","settings","api","admin","search"];for(let a of n)r.push(i.includes(a)?1:0);let s=i.split("/").filter(Boolean).length;for(r.push(s/10),r.push(e.includes("?")?1:0),r.push(e.startsWith("https://")?1:0);r.length<270;)r.push(0);return r}subscribeToEvents(){this.eventBus.subscribe("code-intelligence.FileChanged",this.handleFileChanged.bind(this)),this.eventBus.subscribe("ci-cd.DeploymentCompleted",this.handleDeploymentCompleted.bind(this))}async handleFileChanged(e){}async handleDeploymentCompleted(e){}async loadWorkflowState(){let e=await this.memory.get("visual-accessibility:coordinator:workflows");if(e)for(let r of e)r.status==="running"&&(r.status="failed",r.error="Coordinator restarted",r.completedAt=new Date),this.workflows.set(r.id,r)}async saveWorkflowState(){let e=Array.from(this.workflows.values());await this.memory.set("visual-accessibility:coordinator:workflows",e,{namespace:"visual-accessibility",persist:!0})}requiresConsensus(e){return this.consensusMixin.requiresConsensus(e)}async verifyFinding(e){return this.consensusMixin.verifyFinding(e)}async verifyAccessibilityViolation(e,r){let i=V({id:v(),type:"accessibility-violation",confidence:r,description:`Accessibility violation: ${e.description} (${e.impact} impact)`,payload:e,detectedBy:"visual-accessibility-coordinator",severity:e.impact==="critical"?"critical":e.impact==="serious"?"high":e.impact==="moderate"?"medium":"low"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return!!(n.success&&n.value.verdict==="verified")}return!0}async verifyVisualRegression(e,r){let i=V({id:v(),type:"visual-regression",confidence:r,description:`Visual regression detected at ${e.url} (${e.viewport.width}x${e.viewport.height}): ${e.diffPercentage.toFixed(2)}% difference`,payload:e,detectedBy:"visual-accessibility-coordinator",severity:e.diffPercentage>20?"critical":e.diffPercentage>10?"high":e.diffPercentage>5?"medium":"low"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return!!(n.success&&n.value.verdict==="verified")}return!0}onTopologyHealthChange(e){return this.minCutMixin.onTopologyHealthChange(e)}};A();var ol=class extends j{constructor(e,r,i,n={},s){super(e,r);this.agentCoordinator=i;this.llmRouter=s;this.pluginConfig=n}agentCoordinator;llmRouter;coordinator=null;visualTester=null;accessibilityTester=null;responsiveTester=null;pluginConfig;get name(){return"visual-accessibility"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{runVisualTests:this.runVisualTests.bind(this),runAccessibilityAudit:this.runAccessibilityAudit.bind(this),approveVisualChanges:this.approveVisualChanges.bind(this),generateRemediationPlan:this.generateRemediationPlan.bind(this),getVisualTestingStatus:this.getVisualTestingStatus.bind(this),captureScreenshot:this.captureScreenshot.bind(this),captureElement:this.captureElement.bind(this),auditAccessibility:this.auditAccessibility.bind(this),checkContrast:this.checkContrast.bind(this),validateWCAGLevel:this.validateWCAGLevel.bind(this),checkKeyboardNavigation:this.checkKeyboardNavigation.bind(this),testResponsiveness:this.testResponsiveness.bind(this),analyzeBreakpoints:this.analyzeBreakpoints.bind(this),registerWorkflowActions:this.registerWorkflowActions.bind(this),getCoordinator:()=>this.coordinator,getVisualTester:()=>this.visualTester,getAccessibilityTester:()=>this.accessibilityTester,getResponsiveTester:()=>this.responsiveTester}}getTaskHandlers(){return new Map([["run-visual-tests",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.urls,i=e.viewports;return!r||r.length===0?p(new Error("Invalid run-visual-tests payload: missing urls")):this.coordinator.runVisualTests(r,i||[{width:1920,height:1080,deviceScaleFactor:1,isMobile:!1,hasTouch:!1}])}],["run-accessibility-audit",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.urls,i=e.level||"AA";return!r||r.length===0?p(new Error("Invalid run-accessibility-audit payload: missing urls")):this.coordinator.runAccessibilityAudit(r,i)}],["capture-screenshot",async e=>{if(!this.visualTester)return p(new Error("Visual tester not initialized"));let r=e.url;return r?this.visualTester.captureScreenshot(r,e.options):p(new Error("Invalid capture-screenshot payload: missing url"))}],["test-responsiveness",async e=>{if(!this.responsiveTester)return p(new Error("Responsive tester not initialized"));let r=e.url;return r?this.responsiveTester.testResponsiveness(r,e.options):p(new Error("Invalid test-responsiveness payload: missing url"))}],["validate-wcag",async e=>{if(!this.accessibilityTester)return p(new Error("Accessibility tester not initialized"));let r=e.url;if(!r)return p(new Error("Invalid validate-wcag payload: missing url"));let i=e.level||"AA";return this.accessibilityTester.validateWCAGLevel(r,i)}]])}async onInitialize(){this.visualTester=Ca({memory:this.memory,llmRouter:this.llmRouter},this.pluginConfig.visualTester),this.accessibilityTester=new Pr(this.memory,this.pluginConfig.accessibilityTester),this.responsiveTester=new kr(this.memory,this.pluginConfig.responsiveTester),this.coordinator=new Ea(this.eventBus,this.memory,this.agentCoordinator,this.pluginConfig.coordinator,this.pluginConfig.visualTester,this.pluginConfig.accessibilityTester,this.pluginConfig.responsiveTester,this.llmRouter),await this.coordinator.initialize(),this.updateHealth({status:"idle",agents:{total:0,active:0,idle:0,failed:0},lastActivity:new Date,errors:[]})}async onDispose(){this.coordinator&&await this.coordinator.dispose(),this.coordinator=null,this.visualTester=null,this.accessibilityTester=null,this.responsiveTester=null}subscribeToEvents(){this.eventBus.subscribe("ci-cd.DeploymentCompleted",this.handleDeploymentCompleted.bind(this)),this.eventBus.subscribe("code-intelligence.FileChanged",this.handleFileChanged.bind(this)),this.eventBus.subscribe("quality-assessment.QualityGateTriggered",this.handleQualityGateTriggered.bind(this))}async onEvent(e){switch(this.updateHealth({lastActivity:new Date}),e.type){case"ci-cd.DeploymentCompleted":await this.handleDeploymentCompleted(e);break;case"code-intelligence.FileChanged":await this.handleFileChanged(e);break;case"quality-assessment.QualityGateTriggered":await this.handleQualityGateTriggered(e);break;default:break}}async runVisualTests(e,r){this.ensureInitialized();try{let i=await this.coordinator.runVisualTests(e,r);return i.success?this.trackSuccessfulTest("visual",i.value.totalTests):this.trackFailedTest(i.error),i}catch(i){return this.handleError(i)}}async runAccessibilityAudit(e,r){this.ensureInitialized();try{let i=await this.coordinator.runAccessibilityAudit(e,r);return i.success?this.trackSuccessfulTest("accessibility",i.value.totalUrls):this.trackFailedTest(i.error),i}catch(i){return this.handleError(i)}}async approveVisualChanges(e,r){this.ensureInitialized();try{return await this.coordinator.approveVisualChanges(e,r)}catch(i){return this.handleError(i)}}async generateRemediationPlan(e){this.ensureInitialized();try{return await this.coordinator.generateRemediationPlan(e)}catch(r){return this.handleError(r)}}async getVisualTestingStatus(){this.ensureInitialized();try{return await this.coordinator.getVisualTestingStatus()}catch(e){return this.handleError(e)}}async captureScreenshot(e,r){this.ensureInitialized();try{return await this.visualTester.captureScreenshot(e,r)}catch(i){return this.handleError(i)}}async captureElement(e,r,i){this.ensureInitialized();try{return await this.visualTester.captureElement(e,r,i)}catch(n){return this.handleError(n)}}async auditAccessibility(e,r){this.ensureInitialized();try{return await this.accessibilityTester.audit(e,r)}catch(i){return this.handleError(i)}}async checkContrast(e){this.ensureInitialized();try{return await this.accessibilityTester.checkContrast(e)}catch(r){return this.handleError(r)}}async validateWCAGLevel(e,r){this.ensureInitialized();try{return await this.accessibilityTester.validateWCAGLevel(e,r)}catch(i){return this.handleError(i)}}async checkKeyboardNavigation(e){this.ensureInitialized();try{return await this.accessibilityTester.checkKeyboardNavigation(e)}catch(r){return this.handleError(r)}}async testResponsiveness(e,r){this.ensureInitialized();try{return await this.responsiveTester.testResponsiveness(e,r)}catch(i){return this.handleError(i)}}async analyzeBreakpoints(e){this.ensureInitialized();try{return await this.responsiveTester.analyzeBreakpoints(e)}catch(r){return this.handleError(r)}}async handleDeploymentCompleted(e){let r=e.payload;await this.memory.set(`visual-accessibility:deployment:${Date.now()}`,r,{namespace:"visual-accessibility",ttl:3600})}async handleFileChanged(e){let r=e.payload;(r.file.endsWith(".css")||r.file.endsWith(".scss"))&&await this.memory.set(`visual-accessibility:style-change:${Date.now()}`,r,{namespace:"visual-accessibility",ttl:3600})}async handleQualityGateTriggered(e){let r=e.payload;r.checks.includes("accessibility")&&await this.memory.set(`visual-accessibility:quality-gate:${r.gateId}`,{pending:!0,timestamp:Date.now()},{namespace:"visual-accessibility",ttl:3600})}ensureInitialized(){if(!this._initialized)throw new Error("VisualAccessibilityPlugin is not initialized");if(!this.coordinator||!this.visualTester||!this.accessibilityTester||!this.responsiveTester)throw new Error("VisualAccessibilityPlugin services are not available")}handleError(e){let r=y(e),i=this.getHealth();return this.updateHealth({errors:[...i.errors.slice(-9),r.message],status:i.errors.length>=5?"degraded":i.status}),{success:!1,error:r}}trackSuccessfulTest(e,r){let i=this.getHealth();this.updateHealth({agents:{...i.agents,total:i.agents.total+1,idle:i.agents.idle+1},lastActivity:new Date})}trackFailedTest(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,failed:r.agents.failed+1},errors:[...r.errors.slice(-9),e.message]})}registerWorkflowActions(e){if(!this._initialized)throw new Error("VisualAccessibilityPlugin must be initialized before registering workflow actions");e.registerAction("visual-accessibility","runVisualTest",async(r,i)=>{try{this.ensureInitialized();let n=this.extractUrls(r);if(n.length===0)return p(new Error('No URLs provided for visual test. Provide "url" or "urls" parameter.'));let s=this.extractViewports(r),a=await this.coordinator.runVisualTests(n,s);return a.success?f({passed:a.value.passed,failed:a.value.failed,totalTests:a.value.totalTests,newBaselines:a.value.newBaselines,duration:a.value.duration,results:a.value.results.map(o=>({url:o.url,viewport:`${o.viewport.width}x${o.viewport.height}`,status:o.status,diffPercentage:o.diff?.diffPercentage}))}):p(a.error)}catch(n){return p(y(n))}}),e.registerAction("visual-accessibility","runAccessibilityTest",async(r,i)=>{try{this.ensureInitialized();let n=this.extractUrls(r);if(n.length===0)return p(new Error('No URLs provided for accessibility test. Provide "url" or "urls" parameter.'));let s=this.extractWcagLevel(r),a=await this.coordinator.runAccessibilityAudit(n,s);return a.success?f({totalUrls:a.value.totalUrls,passingUrls:a.value.passingUrls,totalViolations:a.value.totalViolations,criticalViolations:a.value.criticalViolations,averageScore:a.value.averageScore,topIssues:a.value.topIssues.map(o=>({ruleId:o.ruleId,description:o.description,occurrences:o.occurrences,impact:o.impact}))}):p(a.error)}catch(n){return p(y(n))}})}extractUrls(e){return typeof e.url=="string"?[e.url]:Array.isArray(e.urls)?e.urls.filter(r=>typeof r=="string"):typeof e.target=="string"?[e.target]:[]}extractViewports(e){let r=[{width:1920,height:1080,deviceScaleFactor:1,isMobile:!1,hasTouch:!1},{width:1280,height:720,deviceScaleFactor:1,isMobile:!1,hasTouch:!1},{width:768,height:1024,deviceScaleFactor:2,isMobile:!0,hasTouch:!0},{width:375,height:812,deviceScaleFactor:3,isMobile:!0,hasTouch:!0}];if(Array.isArray(e.viewports))return e.viewports.filter(i=>typeof i=="object"&&i!==null).map(i=>({width:typeof i.width=="number"?i.width:1920,height:typeof i.height=="number"?i.height:1080,deviceScaleFactor:typeof i.deviceScaleFactor=="number"?i.deviceScaleFactor:1,isMobile:typeof i.isMobile=="boolean"?i.isMobile:!1,hasTouch:typeof i.hasTouch=="boolean"?i.hasTouch:!1}));if(typeof e.viewport=="object"&&e.viewport!==null){let i=e.viewport;return[{width:typeof i.width=="number"?i.width:1920,height:typeof i.height=="number"?i.height:1080,deviceScaleFactor:typeof i.deviceScaleFactor=="number"?i.deviceScaleFactor:1,isMobile:typeof i.isMobile=="boolean"?i.isMobile:!1,hasTouch:typeof i.hasTouch=="boolean"?i.hasTouch:!1}]}return r}extractWcagLevel(e){let i=(e.level??e.wcagLevel??"AA").toUpperCase();return i==="A"||i==="AA"||i==="AAA"?i:"AA"}};function Im(u,t,e,r,i){return new ol(u,t,e,r,i)}M();A();M();import*as Fm from"net";import{execFile as Mm}from"child_process";A();H();se();var Qv={defaultTimeout:6e4,maxConcurrentFaults:3,enableDryRun:!0,safetyCheckInterval:5e3,autoRollbackOnFailure:!0,enableLLMAnalysis:!0,llmModelTier:2,llmMaxTokens:2048},N=R.create("chaos-resilience/chaos-engineer"),Dr=class u{config;activeExperiments=new Map;activeFaults=new Map;httpClient;metricsCollector;stressWorkers=new Map;memory;llmRouter;constructor(t,e={}){this.memory=t.memory,this.llmRouter=t.llmRouter,this.config={...Qv,...e},this.httpClient=new Be,this.metricsCollector=dc()}async createExperiment(t){try{let e=this.validateExperiment(t);if(!e.success)return p(e.error);let r=await this.analyzeExperimentWithLLM(t);return r&&N.info(`LLM Analysis:
|
|
3007
3007
|
${r}`),await this.memory.set(`chaos:experiments:${t.id}`,t,{namespace:"chaos-resilience",persist:!0}),f(t.id)}catch(e){return p(y(e))}}async runExperiment(t){try{let e=await this.memory.get(`chaos:experiments:${t}`);if(!e)return p(new Error(`Experiment not found: ${t}`));if(this.activeExperiments.has(t))return p(new Error(`Experiment ${t} is already running`));let r=this.createExecution(e);this.activeExperiments.set(t,r);try{let i=await this.verifySteadyState(e.steadyState);if(!i.success||!i.value)return r.result.steadyStateVerified=!1,r.result.status="failed",r.result.incidents.push({type:"error",severity:"high",message:"Initial steady state verification failed",timestamp:new Date,resolved:!1}),f(this.finalizeExecution(r));r.result.steadyStateVerified=!0;for(let a of e.faults){let o=await this.injectFault(a);o.success?r.result.faultResults.push(o.value):r.result.faultResults.push({faultId:a.id,injected:!1,duration:0,affectedTargets:0,errors:[o.error.message]})}await this.collectMetricsDuringExperiment(r,e);let n=await this.verifySteadyState(e.steadyState),s=n.success?n.value:!1;r.result.hypothesisValidated=this.validateHypothesis(e.hypothesis,r.result.metrics),r.result.status=this.determineExperimentStatus(r,s);for(let a of e.faults)await this.removeFault(a.id);return f(this.finalizeExecution(r))}catch(i){return r.result.status="failed",r.result.incidents.push({type:"error",severity:"critical",message:T(i),timestamp:new Date,resolved:!1}),this.config.autoRollbackOnFailure&&(await this.rollbackExperiment(e),r.result.status="rolled-back"),f(this.finalizeExecution(r))}finally{this.activeExperiments.delete(t)}}catch(e){return p(y(e))}}async abortExperiment(t,e){try{let r=this.activeExperiments.get(t);if(!r)return p(new Error(`No active experiment found: ${t}`));r.result.status="aborted",r.result.incidents.push({type:"alert",severity:"medium",message:`Experiment aborted: ${e}`,timestamp:new Date,resolved:!0});let i=await this.memory.get(`chaos:experiments:${t}`);if(i)for(let n of i.faults)await this.removeFault(n.id);return f(void 0)}catch(r){return p(y(r))}}async verifySteadyState(t){try{let e=[];for(let i of t.probes){let n=await this.executeProbe(i);e.push(n)}let r=e.every(i=>i);return f(r)}catch(e){return p(y(e))}}async injectFault(t){try{if(this.activeFaults.size>=this.config.maxConcurrentFaults)return p(new Error(`Maximum concurrent faults (${this.config.maxConcurrentFaults}) reached`));let e=this.validateFault(t);if(!e.success)return p(e.error);let r=Date.now();if(t.probability!==void 0&&L()>t.probability)return f({faultId:t.id,injected:!1,duration:0,affectedTargets:0,errors:["Skipped due to probability check"]});let i=await this.performFaultInjection(t);return i.success?(this.activeFaults.set(t.id,t),t.duration>0&&setTimeout(()=>{this.removeFault(t.id)},t.duration),f({faultId:t.id,injected:!0,duration:Date.now()-r,affectedTargets:i.value,errors:[]})):f({faultId:t.id,injected:!1,duration:Date.now()-r,affectedTargets:0,errors:[i.error.message]})}catch(e){return p(y(e))}}async removeFault(t){try{let e=this.activeFaults.get(t);return e?(await this.performFaultRemoval(e),this.activeFaults.delete(t),f(void 0)):f(void 0)}catch(e){return p(y(e))}}isLLMAnalysisAvailable(){return this.config.enableLLMAnalysis&&this.llmRouter!==void 0}getModelForTier(t){let e={1:"claude-haiku-4-5",2:"claude-sonnet-4-6",3:"claude-sonnet-4-6",4:"claude-opus-4-7"};return e[t]||e[2]}async analyzeExperimentWithLLM(t){if(!this.isLLMAnalysisAvailable())return null;try{return(await this.llmRouter.chat({model:this.getModelForTier(this.config.llmModelTier),messages:[{role:"user",content:`Analyze this chaos experiment hypothesis and provide recommendations:
|
|
3008
3008
|
Experiment: ${t.name}
|
|
3009
3009
|
Hypothesis: ${t.hypothesis.statement}
|
|
@@ -3013,8 +3013,8 @@ Fault Types: ${t.faults.map(r=>`${r.type} targeting ${r.target.type}:${r.target.
|
|
|
3013
3013
|
Provide:
|
|
3014
3014
|
1. Hypothesis validation likelihood
|
|
3015
3015
|
2. Potential risks
|
|
3016
|
-
3. Recommended safety measures`}],maxTokens:this.config.llmMaxTokens})).content}catch{return N.warn("LLM analysis failed:"),null}}validateExperiment(t){return t.id?t.name?t.hypothesis?!t.steadyState||t.steadyState.probes.length===0?p(new Error("At least one steady state probe is required")):!t.faults||t.faults.length===0?p(new Error("At least one fault injection is required")):t.rollbackPlan?t.blastRadius.excludeProduction===!1&&!t.rollbackPlan.automatic?p(new Error("Production experiments require automatic rollback")):f(void 0):p(new Error("Rollback plan is required")):p(new Error("Experiment hypothesis is required")):p(new Error("Experiment name is required")):p(new Error("Experiment ID is required"))}validateFault(t){return t.id?t.type?t.target?t.duration<0?p(new Error("Fault duration must be non-negative")):t.probability!==void 0&&(t.probability<0||t.probability>1)?p(new Error("Fault probability must be between 0 and 1")):f(void 0):p(new Error("Fault target is required")):p(new Error("Fault type is required")):p(new Error("Fault ID is required"))}createExecution(t){return{experimentId:t.id,startTime:new Date,result:{experimentId:t.id,status:"running",startTime:new Date,hypothesisValidated:!1,steadyStateVerified:!1,faultResults:[],metrics:[],incidents:[]}}}finalizeExecution(t){t.result.endTime=new Date;let e={experimentId:t.result.experimentId,status:t.result.status,startTime:t.result.startTime,endTime:t.result.endTime,hypothesisValidated:t.result.hypothesisValidated,steadyStateVerified:t.result.steadyStateVerified,faultResults:t.result.faultResults,metrics:t.result.metrics,incidents:t.result.incidents};return this.memory.set(`chaos:results:${t.experimentId}:${Date.now()}`,e,{namespace:"chaos-resilience",persist:!0}),e}async executeProbe(t){try{switch(t.type){case"http":return await this.executeHttpProbe(t);case"tcp":return await this.executeTcpProbe(t);case"command":return await this.executeCommandProbe(t);case"metric":return await this.executeMetricProbe(t);default:return!1}}catch{return!1}}async executeHttpProbe(t){try{let e=await this.httpClient.get(t.target,{timeout:t.timeout??5e3,retries:1,circuitBreaker:!1});if(!e.success)return N.info(`HTTP probe failed: ${t.name} -> ${e.error.message}`),!1;let r=e.value;if(t.expectedStatus!==void 0){let i=r.status===t.expectedStatus;return i||N.info(`HTTP probe ${t.name}: expected status ${t.expectedStatus}, got ${r.status}`),i}return r.ok}catch(e){return N.info(`HTTP probe error: ${t.name} -> ${T(e)}`),!1}}async executeTcpProbe(t){return new Promise(e=>{try{let[r,i]=t.target.split(":"),n=parseInt(i,10);if(!r||isNaN(n)){N.info(`TCP probe invalid target: ${t.target} (expected host:port)`),e(!1);return}let s=t.timeout??5e3,a=new Fm.Socket,o=setTimeout(()=>{a.destroy(),N.info(`TCP probe timeout: ${t.name} -> ${t.target}`),e(!1)},s);a.connect(n,r,()=>{clearTimeout(o),a.destroy(),e(!0)}),a.on("error",c=>{clearTimeout(o),a.destroy(),N.info(`TCP probe error: ${t.name} -> ${c.message}`),e(!1)})}catch(r){N.info(`TCP probe exception: ${t.name} -> ${T(r)}`),e(!1)}})}static ALLOWED_PROBE_COMMANDS=["curl","wget","nc","netcat","ping","nslookup","dig","ps","pgrep","cat","head","tail","ls","stat","echo","test","[","node","npm"];async executeCommandProbe(t){return new Promise(e=>{let r=t.timeout??1e4,i=ma(t.target,u.ALLOWED_PROBE_COMMANDS);if(!i.valid){N.info(`Command probe ${t.name} blocked: ${i.error}`),N.info(`Blocked patterns: ${i.blockedPatterns?.join(", ")||"none"}`),e(!1);return}let s=(i.sanitizedCommand||t.target).trim().split(/\s+/),a=s[0],o=s.slice(1);Mm(a,o,{timeout:r},(c,l,d)=>{if(c){N.info(`Command probe failed: ${t.name} -> ${c.message}`),e(!1);return}if(t.expectedOutput!==void 0){let m=l.trim().includes(t.expectedOutput);m||N.info(`Command probe ${t.name}: output did not contain expected value`),e(m);return}e(!0)})})}async executeMetricProbe(t){try{let e=await this.httpClient.get(t.target,{timeout:t.timeout??5e3,retries:1,circuitBreaker:!1});if(!e.success)return N.info(`Metric probe failed: ${t.name} -> ${e.error.message}`),!1;let r=e.value;if(!r.ok)return N.info(`Metric probe HTTP error: ${t.name} -> ${r.status}`),!1;let i=await r.text(),n;try{let s=E(i);n=typeof s.value=="number"?s.value:parseFloat(s.value)}catch{n=parseFloat(i)}if(isNaN(n))return N.info(`Metric probe ${t.name}: could not parse metric value from response`),!1;if(t.threshold!==void 0){let{operator:s,value:a}=t.threshold;switch(s){case"lt":return n<a;case"gt":return n>a;case"lte":return n<=a;case"gte":return n>=a;case"eq":return n===a;default:return!0}}return!0}catch(e){return N.info(`Metric probe error: ${t.name} -> ${T(e)}`),!1}}async performFaultInjection(t){let r={latency:async()=>this.injectLatency(t),error:async()=>this.injectError(t),timeout:async()=>this.injectTimeout(t),"packet-loss":async()=>this.injectPacketLoss(t),"cpu-stress":async()=>this.injectCpuStress(t),"memory-stress":async()=>this.injectMemoryStress(t),"disk-stress":async()=>this.injectDiskStress(t),"network-partition":async()=>this.injectNetworkPartition(t),"dns-failure":async()=>this.injectDnsFailure(t),"process-kill":async()=>this.injectProcessKill(t)}[t.type];return r?r():p(new Error(`Unknown fault type: ${t.type}`))}async injectLatency(t){let e=t.parameters.latencyMs??100;return N.info(`Latency injection configured: ${e}ms for ${t.target.selector}`),N.info("Note: Actual latency injection requires network proxy (e.g., Toxiproxy, tc)"),f(1)}async injectError(t){let e=t.parameters.errorCode??500;return N.info(`Error injection configured: ${e} for ${t.target.selector}`),N.info("Note: Actual error injection requires service mesh (e.g., Istio, Linkerd)"),f(1)}async injectTimeout(t){return N.info(`Timeout injection configured for ${t.target.selector}`),N.info("Note: Actual timeout injection requires network proxy configuration"),f(1)}async injectPacketLoss(t){let e=t.parameters.packetLossPercent??10;return N.info(`Packet loss configured: ${e}% for ${t.target.selector}`),N.info("Note: Actual packet loss requires tc/iptables (Linux) or similar"),f(1)}async injectCpuStress(t){let e=t.parameters.cpuPercent??80,r=t.parameters.cores??1,i=t.duration;N.info(`Injecting CPU stress: ${e}% on ${r} core(s) for ${i}ms`);let n=Date.now(),s=setInterval(()=>{if(Date.now()-n>=i){clearInterval(s);return}let a=10*(e/100),o=Date.now();for(;Date.now()-o<a;)L()*L()},10);return this.stressWorkers.set(t.id,s),f(r)}async injectMemoryStress(t){let e=t.parameters.memoryBytes??104857600,r=Math.round(e/(1024*1024));N.info(`Injecting memory stress: ${r}MB allocation`);try{let n=Math.ceil(e/1048576),s=[];for(let a=0;a<n;a++){let o=Math.min(1048576,e-a*1048576),c=new Array(o).fill(L());s.push(c)}return this.stressWorkers.set(t.id,s),N.info(`Memory stress active: ${s.length} chunks allocated`),f(1)}catch(i){return p(new Error(`Failed to allocate memory: ${T(i)}`))}}async injectDiskStress(t){return N.info(`Disk stress configured for ${t.target.selector}`),N.info("Note: Actual disk stress requires file system write permissions"),f(1)}async injectNetworkPartition(t){return N.info(`Network partition configured for ${t.target.selector}`),N.info("Note: Actual network partition requires iptables/firewall rules"),f(1)}async injectDnsFailure(t){return N.info(`DNS failure configured for ${t.target.selector}`),N.info("Note: Actual DNS failure requires DNS server or /etc/hosts modification"),f(1)}async injectProcessKill(t){let e=t.target.selector;return N.info(`Process kill configured for pattern: ${e}`),N.info("Note: Actual process kill requires appropriate permissions"),this.config.enableDryRun?(N.info(`Would kill processes matching: ${e}`),f(0)):f(1)}async performFaultRemoval(t){N.info(`Removing fault: ${t.id} (${t.type})`);let e=this.stressWorkers.get(t.id);e&&(typeof e=="object"&&"unref"in e&&clearInterval(e),this.stressWorkers.delete(t.id))}async collectMetricsDuringExperiment(t,e){let r=e.hypothesis.metrics.map(s=>s.metric),i=Date.now(),n=Math.max(...e.faults.map(s=>s.duration),this.config.defaultTimeout);for(;Date.now()-i<Math.min(n,5e3);){for(let s of r){let a={timestamp:new Date,name:s,value:this.collectRealMetricValue(s),labels:{experiment:e.id}};t.result.metrics.push(a)}await this.sleep(this.config.safetyCheckInterval)}}collectRealMetricValue(t){return this.metricsCollector.getChaosMetricValue(t)}validateHypothesis(t,e){for(let r of t.metrics){let i=e.filter(s=>s.name===r.metric);if(i.length===0)return!1;let n=i.reduce((s,a)=>s+a.value,0)/i.length;if(!this.checkMetricExpectation(n,r))return!1}for(let r of t.tolerances){let i=e.filter(o=>o.name===r.metric);if(i.length===0)continue;let n=i.map(o=>o.value),s=this.calculateDeviation(n);if((r.unit==="percent"?s/n[0]*100:s)>r.maxDeviation)return!1}return!0}checkMetricExpectation(t,e){let{operator:r,value:i}=e;switch(r){case"eq":return t===i;case"lt":return t<i;case"gt":return t>i;case"lte":return t<=i;case"gte":return t>=i;case"between":let[n,s]=i;return t>=n&&t<=s;default:return!1}}calculateDeviation(t){if(t.length===0)return 0;let e=t.reduce((i,n)=>i+n,0)/t.length,r=t.map(i=>Math.pow(i-e,2));return Math.sqrt(r.reduce((i,n)=>i+n,0)/t.length)}determineExperimentStatus(t,e){return!t.result.steadyStateVerified||!e?"failed":t.result.hypothesisValidated?"completed":t.result.faultResults.filter(i=>!i.injected).length>0?"failed":"completed"}async rollbackExperiment(t){for(let e of t.rollbackPlan.steps.sort((r,i)=>r.order-i.order)){N.info(`Executing rollback step ${e.order}: ${e.action}`);try{await this.executeRollbackAction(e.action,e.target,e.timeout)}catch(r){N.error(`Rollback step ${e.order} failed: ${T(r)}`)}}for(let e of t.faults)await this.removeFault(e.id)}async executeRollbackAction(t,e,r=3e4){t.startsWith("http://")||t.startsWith("https://")?await this.executeHttpRollback(t,r):t.startsWith("cmd:")?await this.executeCommandRollback(t.slice(4),r):e&&(e.startsWith("http://")||e.startsWith("https://"))?await this.executeHttpRollback(`${e}/_chaos/${t}`,r):await this.executeBuiltInRollback(t,e,r)}async executeHttpRollback(t,e){let r=await this.httpClient.post(t,{},{timeout:e,retries:1});if(!r.success)throw new Error(`HTTP rollback failed: ${r.error.message}`)}static ALLOWED_ROLLBACK_COMMANDS=["kill","pkill","rm","rmdir","mv","cp","systemctl","service","docker","kubectl","iptables","tc","echo","true"];executeCommandRollback(t,e){return new Promise((r,i)=>{let n=ma(t,u.ALLOWED_ROLLBACK_COMMANDS);if(!n.valid){i(new Error(`Rollback command blocked: ${n.error}`));return}let a=(n.sanitizedCommand||t).trim().split(/\s+/),o=a[0],c=a.slice(1);Mm(o,c,{timeout:e},(l,d,m)=>{l?i(new Error(`Command rollback failed: ${l.message}. ${m}`)):r()})})}async executeBuiltInRollback(t,e,r){let i=t.toLowerCase();i.includes("remove")||i.includes("clear")?e&&N.info(`Clearing state for target: ${e}`):i.includes("restart")?N.info(`Restart requested for: ${e||"service"}`):i.includes("restore")?N.info(`Restore requested for: ${e||"system"}`):N.info(`Rollback action logged: ${t}`),await this.sleep(100)}sleep(t){return new Promise(e=>setTimeout(e,t))}};A();se();var Kv={defaultTimeout:3e5,maxVirtualUsers:1e3,reportingInterval:1e3,enableDetailedMetrics:!0,connectionPoolSize:100},Ir=class{constructor(t,e={}){this.memory=t;this.config={...Kv,...e},this.httpClient=new Be}memory;config;activeTests=new Map;httpClient;async createTest(t){try{let e=this.validateTest(t);return e.success?(await this.memory.set(`loadtest:tests:${t.id}`,t,{namespace:"chaos-resilience",persist:!0}),f(t.id)):p(e.error)}catch(e){return p(y(e))}}async runTest(t){try{let e=await this.memory.get(`loadtest:tests:${t}`);if(!e)return p(new Error(`Load test not found: ${t}`));if(this.activeTests.has(t))return p(new Error(`Load test ${t} is already running`));if(e.profile.virtualUsers.max>this.config.maxVirtualUsers)return p(new Error(`Virtual users (${e.profile.virtualUsers.max}) exceeds maximum (${this.config.maxVirtualUsers})`));let r=this.createExecution(e);this.activeTests.set(t,r);try{return await this.executeLoadTest(r,e),r.result.assertionResults=this.evaluateAssertions(e.assertions,r.result.summary),r.result.status=this.determineTestStatus(r.result),f(this.finalizeExecution(r))}catch(i){return r.result.status="failed",r.result.errors.push({type:"execution_error",message:T(i),count:1,firstOccurrence:new Date,lastOccurrence:new Date}),f(this.finalizeExecution(r))}finally{this.activeTests.delete(t)}}catch(e){return p(y(e))}}async stopTest(t){try{let e=this.activeTests.get(t);return e?(e.aborted=!0,e.result.status="aborted",f(this.finalizeExecution(e))):p(new Error(`No active load test found: ${t}`))}catch(e){return p(y(e))}}async getRealtimeMetrics(t){try{let e=this.activeTests.get(t);if(!e)return p(new Error(`No active load test found: ${t}`));let r=e.result.timeline[e.result.timeline.length-1];return r?f(r):p(new Error("No metrics available yet"))}catch(e){return p(y(e))}}async generateFromTraffic(t,e){try{if(t.requests.length===0)return p(new Error("Traffic sample contains no requests"));if(e<=0)return p(new Error("Multiplier must be positive"));let r=t.requests.reduce((h,g)=>h+g.frequency,0),i=t.requests.reduce((h,g)=>h+g.avgResponseTime*g.frequency,0)/r,n=t.requests.map(h=>({name:`${h.method} ${h.url}`,weight:h.frequency/r,steps:[{type:"request",target:{url:h.url,method:h.method}},{type:"think",duration:Math.max(100,i*.5)}]})),a=r/t.duration*e,o=Math.ceil(a*(i/1e3)),c={virtualUsers:{start:Math.ceil(o*.1),max:Math.min(o,this.config.maxVirtualUsers),pattern:"ramp"},duration:Math.max(6e4,t.duration*e),rampUp:3e4,rampDown:15e3},l=[{metric:"p95",operator:"lt",value:i*2},{metric:"error-rate",operator:"lt",value:5},{metric:"throughput",operator:"gte",value:a*.9}],d=e>5?"stress":"load",m={id:v(),name:`Generated from ${t.source} (${e}x)`,type:d,target:{url:t.requests[0].url,method:t.requests[0].method},profile:c,scenarios:n,assertions:l};return f(m)}catch(r){return p(y(r))}}validateTest(t){return t.id?t.name?!t.target||!t.target.url?p(new Error("Test target URL is required")):t.profile?t.profile.virtualUsers.max<=0?p(new Error("Maximum virtual users must be positive")):t.profile.duration<=0?p(new Error("Test duration must be positive")):f(void 0):p(new Error("Test profile is required")):p(new Error("Test name is required")):p(new Error("Test ID is required"))}createExecution(t){return{testId:t.id,startTime:new Date,aborted:!1,result:{testId:t.id,status:"completed",duration:0,summary:this.createEmptySummary(),timeline:[],errors:[],assertionResults:[]}}}createEmptySummary(){return{totalRequests:0,successfulRequests:0,failedRequests:0,requestsPerSecond:0,avgResponseTime:0,p50ResponseTime:0,p95ResponseTime:0,p99ResponseTime:0,maxResponseTime:0,errorRate:0}}async executeLoadTest(t,e){let r=Date.now(),i=e.profile.duration,n=[],s=new Map,a=this.getExecutionStrategy(e.type);for(;Date.now()-r<i&&!t.aborted;){let o=Date.now()-r,c=this.calculateCurrentVirtualUsers(e.profile,o,i),l=await this.executeBatch(e,c,a);n.push(...l.responseTimes);for(let m of l.errors){let h=s.get(m);h?(h.count++,h.lastOccurrence=new Date):s.set(m,{type:"request_error",message:m,count:1,firstOccurrence:new Date,lastOccurrence:new Date})}t.result.summary.totalRequests+=l.totalRequests,t.result.summary.successfulRequests+=l.successfulRequests,t.result.summary.failedRequests+=l.failedRequests;let d={timestamp:new Date,virtualUsers:c,requestsPerSecond:l.totalRequests,avgResponseTime:l.responseTimes.length>0?l.responseTimes.reduce((m,h)=>m+h,0)/l.responseTimes.length:0,errorRate:l.totalRequests>0?l.failedRequests/l.totalRequests*100:0};t.result.timeline.push(d),await this.sleep(this.config.reportingInterval)}if(t.result.duration=Date.now()-r,t.result.errors=Array.from(s.values()),n.length>0){let o=n.sort((c,l)=>c-l);t.result.summary.avgResponseTime=o.reduce((c,l)=>c+l,0)/o.length,t.result.summary.p50ResponseTime=this.percentile(o,50),t.result.summary.p95ResponseTime=this.percentile(o,95),t.result.summary.p99ResponseTime=this.percentile(o,99),t.result.summary.maxResponseTime=o[o.length-1]}t.result.summary.requestsPerSecond=t.result.summary.totalRequests/(t.result.duration/1e3),t.result.summary.errorRate=t.result.summary.totalRequests>0?t.result.summary.failedRequests/t.result.summary.totalRequests*100:0}getExecutionStrategy(t){switch(t){case"load":return{requestMultiplier:1,errorInjectionRate:0};case"stress":return{requestMultiplier:1.5,errorInjectionRate:.01};case"spike":return{requestMultiplier:3,errorInjectionRate:.02};case"soak":return{requestMultiplier:.8,errorInjectionRate:0};case"breakpoint":return{requestMultiplier:2,errorInjectionRate:.05};default:return{requestMultiplier:1,errorInjectionRate:0}}}calculateCurrentVirtualUsers(t,e,r){let{virtualUsers:i,rampUp:n=0,rampDown:s=0}=t,{start:a,max:o,pattern:c}=i;switch(c){case"constant":return o;case"ramp":if(e<n)return Math.round(a+(o-a)*(e/n));if(e>r-s){let C=(r-e)/s;return Math.round(a+(o-a)*C)}return o;case"step":let l=5,d=r/l,m=Math.floor(e/d),h=(o-a)/l;return Math.round(a+h*m);case"spike":return e%3e4<5e3?o:a;default:return o}}async executeBatch(t,e,r){let i=Math.round(e*r.requestMultiplier),n=Math.min(i,this.config.connectionPoolSize),s=this.createBatches(i,n),a=[];for(let l of s){let d=Date.now(),m=await Promise.all(l.map(()=>this.executeRequest(t,r)));a.push(...m);let h=Date.now()-d,g=1e3/Math.max(e,1)*l.length;h<g&&await this.sleep(g-h)}let o=a.filter(l=>l.success).map(l=>l.latency),c=a.filter(l=>!l.success).map(l=>l.error||"Unknown error");return{totalRequests:a.length,successfulRequests:a.filter(l=>l.success).length,failedRequests:a.filter(l=>!l.success).length,responseTimes:o,errors:c}}async executeRequest(t,e){let r=Date.now(),i=r;if(e.errorInjectionRate>0&&L()<e.errorInjectionRate)return{status:0,latency:Date.now()-r,success:!1,error:"Simulated error injection",timestamp:i};try{let{url:n,method:s="GET",headers:a,body:o}=t.target,c={headers:a,timeout:this.config.defaultTimeout,retries:0,circuitBreaker:!1},l;switch(s.toUpperCase()){case"POST":l=await this.httpClient.post(n,o,c);break;case"PUT":l=await this.httpClient.put(n,o,c);break;case"DELETE":l=await this.httpClient.delete(n,c);break;default:l=await this.httpClient.get(n,c);break}if(l.success){let d=l.value;return{status:d.status,latency:Date.now()-r,success:d.ok,error:d.ok?void 0:`HTTP ${d.status}: ${d.statusText}`,timestamp:i}}else return{status:l.error.status??0,latency:Date.now()-r,success:!1,error:l.error.message,timestamp:i}}catch(n){return{status:0,latency:Date.now()-r,success:!1,error:T(n),timestamp:i}}}createBatches(t,e){let r=[],i=t;for(;i>0;){let n=Math.min(i,e);r.push(Array.from({length:n},(s,a)=>a)),i-=n}return r}percentile(t,e){if(t.length===0)return 0;let r=Math.ceil(e/100*t.length)-1;return t[Math.max(0,Math.min(r,t.length-1))]}evaluateAssertions(t,e){return t.map(r=>{let i=this.getMetricValue(r.metric,e),n=this.checkAssertion(r,i);return{assertion:r,passed:n,actualValue:i}})}getMetricValue(t,e){switch(t){case"response-time":return e.avgResponseTime;case"throughput":return e.requestsPerSecond;case"error-rate":return e.errorRate;case"p95":return e.p95ResponseTime;case"p99":return e.p99ResponseTime;default:return 0}}checkAssertion(t,e){switch(t.operator){case"lt":return e<t.value;case"gt":return e>t.value;case"lte":return e<=t.value;case"gte":return e>=t.value;default:return!1}}determineTestStatus(t){return t.status==="aborted"?"aborted":t.assertionResults.filter(r=>!r.passed).length>0||t.summary.errorRate>10?"failed":"completed"}finalizeExecution(t){let e={testId:t.result.testId,status:t.result.status,duration:t.result.duration,summary:t.result.summary,timeline:t.result.timeline,errors:t.result.errors,assertionResults:t.result.assertionResults};return this.memory.set(`loadtest:results:${t.testId}:${Date.now()}`,e,{namespace:"chaos-resilience",persist:!0}),e}sleep(t){return new Promise(e=>setTimeout(e,t))}};M();A();se();H();var Jv={defaultTimeout:6e4,healthCheckInterval:1e3,maxRetries:3,recoveryCheckDelay:500,simulateRandomFailures:!1},bt=R.create("chaos-resilience/performance-profiler"),Mr=class{constructor(t,e={}){this.memory=t;this.config={...Jv,...e},this.httpClient=Gi()}memory;config;httpClient;async testRecovery(t,e,r){let i=v();try{let n=[],s=await this.checkServiceHealth(t);if(n.push({timestamp:new Date,event:"Initial health check",status:s?"healthy":"unhealthy"}),!s)return f({service:t,faultType:e,recoveryTime:0,expectedRecoveryTime:r,passed:!1,timeline:n});n.push({timestamp:new Date,event:`Injecting fault: ${e}`,status:"degraded"}),await this.injectFault(t,e);let a=await this.checkServiceHealth(t);n.push({timestamp:new Date,event:"Post-fault health check",status:a?"healthy":"unhealthy"}),n.push({timestamp:new Date,event:"Removing fault",status:"degraded"}),await this.removeFault(t,e);let o=Date.now(),c=0,l=!1,d=r*2;for(;Date.now()-o<d;){if(await this.checkServiceHealth(t)){c=Date.now()-o,l=!0,n.push({timestamp:new Date,event:"Service recovered",status:"healthy"});break}n.push({timestamp:new Date,event:"Recovery check - still degraded",status:"degraded"}),await this.sleep(this.config.recoveryCheckDelay)}l||n.push({timestamp:new Date,event:"Recovery timeout exceeded",status:"unhealthy"});let m={service:t,faultType:e,recoveryTime:c,expectedRecoveryTime:r,passed:l&&c<=r,timeline:n};return await this.storeTestResult("recovery",i,m),f(m)}catch(n){return p(y(n))}}async testFailover(t,e){let r=v();try{let i=[],n=1,[s,a]=await Promise.all([this.checkServiceHealth(t),this.checkServiceHealth(e)]);if(i.push({order:n++,action:"Verify primary service health",duration:0,success:s}),i.push({order:n++,action:"Verify secondary service health",duration:0,success:a}),!s||!a)return f({primaryService:t,secondaryService:e,failoverTime:0,dataLoss:!0,passed:!1,steps:i});let o=await this.captureServiceState(t);i.push({order:n++,action:"Capture primary service state",duration:0,success:!0});let c=Date.now();await this.injectFault(t,"process-kill"),i.push({order:n++,action:"Trigger primary service failure",duration:Date.now()-c,success:!0});let l=Date.now(),d=!1,m=0;for(;Date.now()-l<this.config.defaultTimeout;){if(await this.checkServiceIsActive(e)){m=Date.now()-c,d=!0;break}await this.sleep(this.config.healthCheckInterval)}i.push({order:n++,action:"Detect failover completion",duration:m,success:d});let h=await this.captureServiceState(e),g=!this.compareServiceStates(o,h);i.push({order:n++,action:"Verify data integrity on secondary",duration:0,success:!g}),await this.removeFault(t,"process-kill"),i.push({order:n++,action:"Restore primary service",duration:0,success:!0});let b={primaryService:t,secondaryService:e,failoverTime:m,dataLoss:g,passed:d&&!g,steps:i};return await this.storeTestResult("failover",r,b),f(b)}catch(i){return p(y(i))}}async testCircuitBreaker(t,e){let r=v();try{let i=e?.errorThreshold??5,n=e?.timeout??this.config.defaultTimeout,s=e?.halfOpenRequests??3;await this.getCircuitState(t)!=="closed"&&await this.resetCircuit(t);let o=0,c=!1;for(let w=0;w<i*2;w++)if(await this.generateError(t),o++,await this.getCircuitState(t)==="open"){c=!0;break}let l=!1,d=Date.now();for(;Date.now()-d<n;){if(await this.getCircuitState(t)==="half-open"){l=!0;break}await this.sleep(this.config.healthCheckInterval)}let m="correct";if(l){let w=0;for(let S=0;S<s;S++)await this.sendSuccessfulRequest(t)&&w++;await this.getCircuitState(t)!=="closed"&&w===s&&(m="incorrect")}let h=!1,g=Date.now();for(;Date.now()-g<n;){if(await this.getCircuitState(t)==="closed"){h=!0;break}await this.sendSuccessfulRequest(t),await this.sleep(this.config.healthCheckInterval)}let b={service:t,opened:c,openedAfterErrors:o,closedAfterRecovery:h,halfOpenBehavior:m,passed:c&&h&&m==="correct"};return await this.storeTestResult("circuit-breaker",r,b),f(b)}catch(i){return p(y(i))}}async testRateLimiting(t,e){let r=v();try{let i=0,n={statusCode:429,retryAfter:void 0,body:void 0},s=[1,5,10,25,50,100,200],a=0,o=!1;for(let m of s){if(o)break;let h=await this.sendRequestBatch(t,m);a+=m;for(let g of h)if(g.statusCode===429){o=!0,i=a-(m-h.indexOf(g)),n=g;break}}o||(i=a);let c=e*.2,l=Math.abs(i-e)<=c||!o,d={service:t,expectedLimit:e,actualLimit:i,passed:o&&l,responseWhenLimited:n};return await this.storeTestResult("rate-limit",r,d),f(d)}catch(i){return p(y(i))}}async checkServiceHealth(t){if(!this.isRealServiceUrl(t))return this.simulateHealthCheck();try{return await this.httpClient.healthCheck(t)}catch{return this.simulateHealthCheck()}}isRealServiceUrl(t){return t.startsWith("http://")||t.startsWith("https://")}simulateHealthCheck(){return this.config.simulateRandomFailures?L()>.05:!0}async checkServiceIsActive(t){if(!this.isRealServiceUrl(t))return this.simulateServiceActive();try{let e=await this.httpClient.get(t,{timeout:5e3,retries:1});return e.success&&e.value.ok}catch{return this.simulateServiceActive()}}simulateServiceActive(){return this.config.simulateRandomFailures?L()>.1:!0}async injectFault(t,e){if(this.isRealServiceUrl(t))try{let r=`${t}/_chaos/inject`;await this.httpClient.post(r,{faultType:e},{timeout:5e3,retries:0});return}catch{bt.debug("Fault injection API failed:")}bt.info(`Injecting fault ${e} into service: ${t}`),await this.sleep(100)}async removeFault(t,e){if(this.isRealServiceUrl(t))try{let r=`${t}/_chaos/remove`;await this.httpClient.post(r,{faultType:e},{timeout:5e3,retries:0});return}catch{bt.debug("Fault removal API failed:")}bt.info(`Removing fault ${e} from service: ${t}`),await this.sleep(50)}async captureServiceState(t){if(this.isRealServiceUrl(t))try{let r=`${t}/_state`,i=await this.httpClient.get(r,{timeout:5e3,retries:1});if(i.success&&i.value.ok){let n=await i.value.text(),s=this.calculateChecksum(n),a=this.parseRecordCount(n);return{checksum:s,timestamp:new Date,records:a}}}catch{bt.debug("State capture API failed:")}return await this.captureMemoryState(t)}calculateChecksum(t){let e=0;for(let r=0;r<t.length;r++){let i=t.charCodeAt(r);e=(e<<5)-e+i,e=e&e}return`chk_${Math.abs(e).toString(16)}`}parseRecordCount(t){try{let e=E(t);return e.records??e.count??e.total??e.length??0}catch{return t.split(`
|
|
3017
|
-
`).filter(e=>e.trim()).length}}async captureMemoryState(t){let e=`resilience:state:${this.hashServiceName(t)}`,r=await this.memory.get(e);if(r)return r;let i={checksum:`init_${v().slice(0,8)}`,timestamp:new Date,records:0};return await this.memory.set(e,i,{namespace:"chaos-resilience"}),i}hashServiceName(t){let e=0;for(let r of t)e=(e<<5)-e+r.charCodeAt(0),e=e&e;return Math.abs(e).toString(16)}compareServiceStates(t,e){let r=t.checksum===e.checksum,i=t.records===e.records;return r||i}async getCircuitState(t){try{return this.httpClient.getCircuitState(t).state}catch{return"closed"}}async resetCircuit(t){try{this.httpClient.resetCircuit(t)}catch{bt.info(`Resetting circuit breaker for: ${t}`)}}async generateError(t){if(this.isRealServiceUrl(t))try{let e=`${t}/_chaos/error`;await this.httpClient.post(e,{},{timeout:5e3,retries:0});return}catch{bt.debug("Error generation API failed:")}bt.info(`Generating error for: ${t}`)}async sendSuccessfulRequest(t){if(!this.isRealServiceUrl(t))return!0;try{let e=await this.httpClient.get(t,{timeout:5e3,retries:1});return e.success&&e.value.ok}catch{return!0}}async sendRequestBatch(t,e){let r=[];if(!this.isRealServiceUrl(t))return this.simulateRequestBatch(e);for(let i=0;i<e;i++)try{let n=await this.httpClient.get(t,{timeout:2e3,retries:0,circuitBreaker:!1});if(n.success){let s=n.value,a=s.headers.get("Retry-After");r.push({statusCode:s.status,retryAfter:a?parseInt(a,10):void 0})}else r.push({statusCode:500,body:{error:n.error.message}})}catch{return[...r,...this.simulateRequestBatch(e-i)]}return r}simulateRequestBatch(t){let e=[];for(let i=0;i<t;i++)i>=75?e.push({statusCode:429,retryAfter:60,body:{error:"Rate limit exceeded"}}):e.push({statusCode:200});return e}async storeTestResult(t,e,r){await this.memory.set(`resilience:${t}:${e}`,r,{namespace:"chaos-resilience",persist:!0})}sleep(t){return new Promise(e=>setTimeout(e,t))}};se();var Yv={stateSize:10,actionSize:5,hiddenLayers:[64,64],learningRatePG:.01,gammaPG:.99,entropyCoeff:.01},xa=class extends oe{policy;pgConfig;actions=[];episodeLog=[];constructor(t={}){super("policy-gradient","policy-based"),this.pgConfig={...Yv,...t},this.initializeActions(),this.policy=new q({layerSizes:[this.pgConfig.stateSize,...this.pgConfig.hiddenLayers,this.pgConfig.actionSize],activations:Array(this.pgConfig.hiddenLayers.length).fill(new _).concat([new B]),learningRate:this.pgConfig.learningRatePG})}async predict(t){this.initialized||await this.initialize();let e=this.prepareState(t),r=this.policy.forward(e),i=he.forward(r),n=this.sampleAction(i),s=this.actions[n],a=i[n],o=Math.max(.3,Math.min(1,a+.4));return this.episodeLog.push({state:t,action:s,reward:0}),{action:s,confidence:o,reasoning:this.generateReasoning(t,s,a)}}async trainCore(t){let e=this.groupIntoEpisodes(t),r=0;for(let i of e){let n=this.calculateReturns(i);for(let s=0;s<i.length;s++){let{state:a,action:o}=i[s],c=n[s],l=this.prepareState(a),d=this.policy.forward(l),m=he.forward(d),h=this.actionToIndex(o),b=-Math.log(m[h]+1e-10)*c;r+=Math.abs(b);let w=new Float32Array(m.length);for(let C=0;C<w.length;C++)C===h?w[C]=-c*(1-m[C]):w[C]=c*m[C];this.policy.backward(w);for(let C of this.policy.layers)C.update(this.pgConfig.learningRatePG)}}return this.episodeLog=[],{episode:this.episodeCount,totalReward:this.totalReward,averageReward:this.rewardHistory.reduce((i,n)=>i+n,0)/this.rewardHistory.length,loss:r/t.length,explorationRate:this.config.explorationRate,trainingTimeMs:0,timestamp:new Date}}getAlgorithmInfo(){return{type:this.type,category:this.category,version:"2.0.0",description:"Neural Policy Gradient (REINFORCE) for Resource Allocation",capabilities:["Neural policy optimization","Monte Carlo return estimation","Entropy regularization"],hyperparameters:{stateSize:this.pgConfig.stateSize,actionSize:this.pgConfig.actionSize,learningRatePG:this.pgConfig.learningRatePG,gammaPG:this.pgConfig.gammaPG},stats:this.stats}}prepareState(t){let e=t.features.slice(0,this.pgConfig.stateSize);for(;e.length<this.pgConfig.stateSize;)e.push(0);let r=Math.max(...e.map(Math.abs));if(r>0)for(let i=0;i<e.length;i++)e[i]=e[i]/r;return new Float32Array(e)}initializeActions(){this.actions=[{type:"allocate",value:{agentType:"tester",count:1}},{type:"allocate",value:{agentType:"analyzer",count:1}},{type:"reallocate",value:{domain:"test-execution"}},{type:"scale-up",value:1},{type:"scale-down",value:1}],this.pgConfig.actionSize=this.actions.length,this.policy=new q({layerSizes:[this.pgConfig.stateSize,...this.pgConfig.hiddenLayers,this.pgConfig.actionSize],activations:Array(this.pgConfig.hiddenLayers.length).fill(new _).concat([new B]),learningRate:this.pgConfig.learningRatePG})}actionToIndex(t){let e=this.actionToKey(t);for(let r=0;r<this.actions.length;r++)if(this.actionToKey(this.actions[r])===e)return r;return 0}actionToKey(t){return`${t.type}:${JSON.stringify(t.value)}`}sampleAction(t){if(L()<this.config.explorationRate)return ue(0,this.actions.length);let e=L(),r=0;for(let i=0;i<t.length;i++)if(r+=t[i],e<=r)return i;return this.argmax(t)}argmax(t){let e=0,r=t[0];for(let i=1;i<t.length;i++)t[i]>r&&(r=t[i],e=i);return e}calculateReturns(t){let e=[],r=0;for(let i=t.length-1;i>=0;i--)r=t[i].reward+this.pgConfig.gammaPG*r,e.unshift(r);return e}groupIntoEpisodes(t){let e=[],r=[];for(let i of t)r.push(i),i.done&&(e.push(r),r=[]);return r.length>0&&e.push(r),e}generateReasoning(t,e,r){return`Neural Policy Gradient: ${e.type} (probability: ${r.toFixed(3)})`}async exportCustomData(){return{policy:this.policy.getParameters(),pgConfig:this.pgConfig}}async importCustomData(t){t.policy&&this.policy.setParameters(t.policy),t.pgConfig&&(this.pgConfig={...this.pgConfig,...t.pgConfig}),this.initialized=!0}async resetAlgorithm(){this.policy=new q({layerSizes:[this.pgConfig.stateSize,...this.pgConfig.hiddenLayers,this.pgConfig.actionSize],activations:Array(this.pgConfig.hiddenLayers.length).fill(new _).concat([new B]),learningRate:this.pgConfig.learningRatePG}),this.episodeLog=[]}};var Xv={maxConcurrentWorkflows:3,defaultTimeout:3e5,enableAutomatedExperiments:!1,publishEvents:!0,enablePolicyGradient:!0,enableQESONA:!0,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},ie=R.create("chaos-resilience"),Pa=class extends Q{constructor(e,r,i,n={},s){let a={...Xv,...n};super(e,"chaos-resilience",a,{verifyFindingTypes:["chaos-experiment","resilience-assessment","failure-injection"],...a.consensusConfig});this.memory=r;this.agentCoordinator=i;this.chaosGovernanceMixin=pu(this.domainName),this.chaosEngineer=new Dr({memory:r,llmRouter:s}),this.loadTester=new Ir(r),this.performanceProfiler=new Mr(r)}memory;agentCoordinator;chaosEngineer;loadTester;performanceProfiler;policyGradient;qesona;chaosGovernanceMixin;async onInitialize(){if(this.config.enablePolicyGradient)try{this.policyGradient=new xa({stateSize:10,actionSize:5,hiddenLayers:[64,64]}),ie.info("PolicyGradient algorithm created successfully")}catch(e){throw ie.error("Failed to create PolicyGradient:",e instanceof Error?e:void 0),new Error(`PolicyGradient creation failed: ${T(e)}`)}if(this.config.enableQESONA)try{this.qesona=await pe({domain:"chaos-resilience",loadOnInit:!0,autoSaveInterval:6e4,maxPatterns:5e3,minConfidence:.6}),ie.info("PersistentSONAEngine initialized successfully")}catch(e){ie.error("Failed to initialize PersistentSONAEngine:",e instanceof Error?e:void 0),ie.warn("Continuing without SONA pattern persistence"),this.qesona=void 0}this.subscribeToEvents(),await this.loadWorkflowState()}async onDispose(){await this.saveWorkflowState(),this.qesona&&(await this.qesona.close(),this.qesona=void 0),this.policyGradient=void 0}getActiveWorkflows(){return super.getActiveWorkflows()}async runChaosSuite(e){let r=v();try{if(this.startWorkflow(r,"chaos-suite"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&ie.warn("Topology degraded, using conservative chaos strategy"),this.minCutMixin.shouldPauseOperations())return p(new Error("Chaos suite paused: topology is in critical state"));if(!this.agentCoordinator.canSpawn())return p(new Error("Agent limit reached, cannot spawn chaos agents"));let i=await this.spawnChaosAgent(r,"coordinator");if(!i.success)return this.failWorkflow(r,i.error.message),p(i.error);this.addAgentToWorkflow(r,i.value);let n=[],s=[],a=0,o=0;for(let l=0;l<e.length;l++){let d=e[l];this.updateWorkflowProgress(r,Math.round((l+1)/e.length*100));let m=await this.chaosEngineer.runExperiment(d);if(m.success){if(n.push(m.value),m.value.hypothesisValidated)a++;else{o++;let h=this.generateRecommendationsFromExperiment(m.value);s.push(...h)}this.config.publishEvents&&await this.publishExperimentCompleted(m.value)}else o++,s.push({priority:"high",category:"experiment-failure",recommendation:`Failed to run experiment ${d}: ${m.error.message}`,effort:"moderate"})}await this.agentCoordinator.stop(i.value),this.completeWorkflow(r);let c={totalExperiments:e.length,passed:a,failed:o,results:n,recommendations:s};return await this.storeReport("chaos-suite",r,c),f(c)}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async runLoadTestSuite(e){let r=v();try{if(this.startWorkflow(r,"load-suite"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&ie.warn("Topology degraded, using conservative load test parameters"),this.minCutMixin.shouldPauseOperations())return p(new Error("Load test suite paused: topology is in critical state"));let i=await this.spawnLoadTestAgent(r,"orchestrator");if(!i.success)return this.failWorkflow(r,i.error.message),p(i.error);this.addAgentToWorkflow(r,i.value);let n=[],s=[],a=0,o=0;for(let l=0;l<e.length;l++){let d=e[l];this.updateWorkflowProgress(r,Math.round((l+1)/e.length*100));let m=await this.loadTester.runTest(d);if(m.success){n.push(m.value),m.value.status==="completed"?a++:o++;let h=this.detectBottlenecks(m.value);s.push(...h),this.config.publishEvents&&await this.publishLoadTestCompleted(m.value)}else o++}await this.agentCoordinator.stop(i.value),this.completeWorkflow(r);let c={totalTests:e.length,passed:a,failed:o,results:n,bottlenecks:s};return await this.storeReport("load-suite",r,c),f(c)}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async assessResilience(e){let r=v();try{if(this.startWorkflow(r,"assessment"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&ie.warn("Topology degraded, assessment may be limited"),this.minCutMixin.shouldPauseOperations())return p(new Error("Resilience assessment paused: topology is in critical state"));let i=new Map,n=[],s=[],a=[],o=await this.spawnAssessmentAgent(r);if(!o.success)return this.failWorkflow(r,o.error.message),p(o.error);this.addAgentToWorkflow(r,o.value);for(let d=0;d<e.length;d++){let m=e[d];this.updateWorkflowProgress(r,Math.round((d+1)/e.length*100));let h=await this.performanceProfiler.testRecovery(m,"latency",5e3),g=await this.performanceProfiler.testCircuitBreaker(m),b=await this.performanceProfiler.testRateLimiting(m,100),w=0;if(h.success&&h.value.passed)w+=33.3,n.push(`${m}: Fast recovery (${h.value.recoveryTime}ms)`);else{let C=h.success?h.value.recoveryTime:"unknown";s.push({service:m,type:"recovery",description:"Slow or failed recovery after fault",risk:un.create(.7)}),a.push({priority:"high",category:"recovery",recommendation:`Improve ${m} recovery time - currently ${C}ms`,effort:"moderate"})}g.success&&g.value.passed?(w+=33.3,n.push(`${m}: Circuit breaker functioning correctly`)):(s.push({service:m,type:"circuit-breaker",description:"Circuit breaker not functioning as expected",risk:un.create(.6)}),a.push({priority:"medium",category:"circuit-breaker",recommendation:`Review ${m} circuit breaker configuration`,effort:"minor"})),b.success&&b.value.passed?(w+=33.4,n.push(`${m}: Rate limiting effective`)):(s.push({service:m,type:"rate-limiting",description:"Rate limiting not properly configured",risk:un.create(.5)}),a.push({priority:"medium",category:"rate-limiting",recommendation:`Configure rate limiting for ${m}`,effort:"minor"})),i.set(m,w)}let c=e.length>0?Array.from(i.values()).reduce((d,m)=>d+m,0)/e.length:0;await this.agentCoordinator.stop(o.value),this.completeWorkflow(r);let l={overallScore:c,serviceScores:i,strengths:n,weaknesses:s,recommendations:a};return await this.storeReport("assessment",r,l),f(l)}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async generateExperiments(e){let r=v();try{this.startWorkflow(r,"experiment-generation");let i=[];for(let n of e.services){let s=this.generateServiceExperiments(n,e.dependencies);i.push(...s)}for(let n of e.criticalPaths){let s=this.generateCriticalPathExperiment(n,e);i.push(s)}for(let n of i)await this.chaosEngineer.createExperiment(n);return this.completeWorkflow(r),f(i)}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async runStrategicChaosSuite(e,r){let i=v();try{if(this.startWorkflow(i,"chaos-suite"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&ie.warn("Topology degraded, adjusting strategic chaos parameters"),this.minCutMixin.shouldPauseOperations())return p(new Error("Strategic chaos suite paused: topology is in critical state"));if(!this.agentCoordinator.canSpawn())return p(new Error("Agent limit reached, cannot spawn chaos agents"));let n=await this.selectChaosStrategy(e,r);if(!n.success)return this.failWorkflow(i,n.error.message),p(n.error);let s=n.value.selectedExperiments;if(ie.info(`[chaos-resilience] Using ${n.value.strategy} strategy with ${s.length} experiments (confidence: ${n.value.confidence.toFixed(2)})`),s.length===0)return this.completeWorkflow(i),f({totalExperiments:0,passed:0,failed:0,results:[],recommendations:[{priority:"low",category:"strategy",recommendation:"No experiments selected - consider adjusting strategy context",effort:"trivial"}]});let a=await this.spawnChaosAgent(i,"coordinator");if(!a.success)return this.failWorkflow(i,a.error.message),p(a.error);this.addAgentToWorkflow(i,a.value);let o=[],c=[],l=0,d=0;for(let h of s)await this.chaosEngineer.createExperiment(h);for(let h=0;h<s.length;h++){let g=s[h];this.updateWorkflowProgress(i,Math.round((h+1)/s.length*100));let b=await this.chaosEngineer.runExperiment(g.id);if(b.success){if(o.push(b.value),b.value.hypothesisValidated)l++;else{d++;let C=this.generateRecommendationsFromExperiment(b.value);c.push(...C)}let w=b.value.hypothesisValidated?.8:.2;await this.storeResiliencePattern(g,b.value,w),this.config.publishEvents&&await this.publishExperimentCompleted(b.value)}else d++,c.push({priority:"high",category:"experiment-failure",recommendation:`Failed to run experiment ${g.name}: ${b.error.message}`,effort:"moderate"})}await this.agentCoordinator.stop(a.value),this.completeWorkflow(i);let m={totalExperiments:s.length,passed:l,failed:d,results:o,recommendations:c};return await this.storeReport("strategic-chaos-suite",i,m),f(m)}catch(n){return this.failWorkflow(i,String(n)),p(y(n))}}async getResilienceDashboard(){try{let e=await this.memory.search("chaos:results:*",10),r=await this.memory.search("loadtest:results:*",10),i,n,s=0,a=0,o=0,c=0,l=0;for(let b of e){let w=await this.memory.get(b);w&&((!i||w.startTime>i)&&(i=w.startTime),s+=w.incidents.filter(C=>!C.resolved).length)}for(let b of r){let w=await this.memory.get(b);if(w&&w.timeline.length>0){let C=w.timeline[0].timestamp;(!n||C>n)&&(n=C),l++,w.status==="failed"&&c++}}let d=o>0?a/o:0,m=l>0?c/l*100:0,h="healthy";return s>5||m>25?h="unhealthy":(s>0||m>10)&&(h="degraded"),f({overallHealth:h,lastExperimentDate:i,lastLoadTestDate:n,activeIncidents:s,uptime:99.9,mttr:d,changeFailureRate:m})}catch(e){return p(y(e))}}async spawnChaosAgent(e,r){let i={name:`chaos-${r}-${e.slice(0,8)}`,domain:"chaos-resilience",type:"specialist",capabilities:["chaos-engineering","fault-injection",r],config:{workflowId:e}};return this.agentCoordinator.spawn(i)}async spawnLoadTestAgent(e,r){let i={name:`loadtest-${r}-${e.slice(0,8)}`,domain:"chaos-resilience",type:"specialist",capabilities:["load-testing","performance",r],config:{workflowId:e}};return this.agentCoordinator.spawn(i)}async spawnAssessmentAgent(e){let r={name:`assessment-${e.slice(0,8)}`,domain:"chaos-resilience",type:"analyzer",capabilities:["resilience-assessment","analysis"],config:{workflowId:e}};return this.agentCoordinator.spawn(r)}async publishExperimentCompleted(e){let r={id:v(),type:"chaos-resilience.ExperimentCompleted",timestamp:new Date,source:"chaos-resilience",payload:{experimentId:e.experimentId,status:e.status,hypothesisValidated:e.hypothesisValidated,incidentCount:e.incidents.length}};await this.eventBus.publish(r)}async publishLoadTestCompleted(e){let r={id:v(),type:"chaos-resilience.LoadTestCompleted",timestamp:new Date,source:"chaos-resilience",payload:{testId:e.testId,status:e.status,summary:e.summary,assertionsPassed:e.assertionResults.filter(i=>i.passed).length,assertionsFailed:e.assertionResults.filter(i=>!i.passed).length}};await this.eventBus.publish(r)}generateRecommendationsFromExperiment(e){let r=[];e.hypothesisValidated||r.push({priority:"high",category:"hypothesis-failure",recommendation:`Experiment ${e.experimentId} hypothesis was not validated - review system behavior under fault conditions`,effort:"moderate"}),e.steadyStateVerified||r.push({priority:"critical",category:"steady-state",recommendation:"System did not maintain steady state - investigate stability issues",effort:"major"});for(let i of e.incidents)(i.severity==="critical"||i.severity==="high")&&r.push({priority:i.severity,category:"incident",recommendation:`Address ${i.type}: ${i.message}`,effort:"moderate"});return r}detectBottlenecks(e){let r=[];return e.summary.p95ResponseTime>1e3&&r.push({location:"api",type:"network",description:`P95 response time is ${e.summary.p95ResponseTime}ms (>1000ms)`,impact:e.summary.p95ResponseTime>2e3?"high":"medium",recommendation:"Investigate API response time, consider caching or query optimization"}),e.summary.errorRate>5&&r.push({location:"service",type:"cpu",description:`Error rate is ${e.summary.errorRate.toFixed(2)}% (>5%)`,impact:e.summary.errorRate>10?"high":"medium",recommendation:"Investigate error causes, scale resources if under load"}),e.summary.requestsPerSecond<10&&r.push({location:"backend",type:"io",description:`Low throughput: ${e.summary.requestsPerSecond.toFixed(2)} RPS`,impact:"medium",recommendation:"Review I/O operations, database queries, and connection pooling"}),r}generateServiceExperiments(e,r){let i=[];i.push(this.createExperiment(`${e.name}-latency`,`Test ${e.name} behavior under latency`,"latency",e.name)),i.push(this.createExperiment(`${e.name}-error`,`Test ${e.name} error handling`,"error",e.name)),i.push(this.createExperiment(`${e.name}-cpu-stress`,`Test ${e.name} under CPU stress`,"cpu-stress",e.name));let n=r.filter(s=>s.from===e.name);for(let s of n)s.criticality==="critical"&&i.push(this.createExperiment(`${e.name}-${s.to}-failure`,`Test ${e.name} when ${s.to} fails`,"error",s.to));return i}generateCriticalPathExperiment(e,r){let i=e.join("-");return{id:v(),name:`critical-path-${i}`,description:`Test critical path: ${e.join(" -> ")}`,hypothesis:{statement:"System should handle partial path failure gracefully",metrics:[{metric:"error_rate",operator:"lt",value:10},{metric:"response_time_ms",operator:"lt",value:2e3}],tolerances:[{metric:"error_rate",maxDeviation:5,unit:"percent"}]},steadyState:{description:"All services in path are healthy",probes:e.map(n=>({name:`${n}-health`,type:"http",target:`http://${n}/health`,expected:{status:200},timeout:5e3}))},faults:e.slice(0,-1).map(n=>({id:v(),type:"latency",target:{type:"service",selector:n},parameters:{latencyMs:500},duration:3e4})),blastRadius:{scope:"subset",percentage:50,excludeProduction:!0},rollbackPlan:{automatic:!0,triggerConditions:[{type:"error-rate",condition:"error_rate > 20"},{type:"timeout",condition:"duration > 60000"}],steps:[{order:1,action:"Remove all faults",timeout:5e3},{order:2,action:"Verify service health"}]}}}createExperiment(e,r,i,n){return{id:v(),name:e,description:r,hypothesis:{statement:`${n} should recover within 5 seconds from ${i}`,metrics:[{metric:"response_time_ms",operator:"lt",value:1e3},{metric:"error_rate",operator:"lt",value:5}],tolerances:[{metric:"response_time_ms",maxDeviation:50,unit:"percent"}]},steadyState:{description:`${n} is healthy and responsive`,probes:[{name:`${n}-health`,type:"http",target:`http://${n}/health`,expected:{status:200},timeout:5e3}]},faults:[{id:v(),type:i,target:{type:"service",selector:n},parameters:this.getDefaultFaultParameters(i),duration:3e4}],blastRadius:{scope:"single",excludeProduction:!0},rollbackPlan:{automatic:!0,triggerConditions:[{type:"error-rate",condition:"error_rate > 50"}],steps:[{order:1,action:`Remove ${i} fault`},{order:2,action:"Verify recovery"}]}}}getDefaultFaultParameters(e){return{latency:{latencyMs:500},error:{errorCode:500},timeout:{timeoutMs:3e4},"packet-loss":{packetLossPercent:10},"cpu-stress":{cpuPercent:80},"memory-stress":{memoryBytes:268435456},"disk-stress":{},"network-partition":{},"dns-failure":{},"process-kill":{}}[e]||{}}async storeReport(e,r,i){await this.memory.set(`chaos-resilience:reports:${e}:${r}`,i,{namespace:"chaos-resilience",persist:!0})}async selectChaosStrategy(e,r){if(!this.policyGradient||!this.config.enablePolicyGradient)return f({strategy:"default",selectedExperiments:this.getDefaultExperiments(e.slice(0,3)),confidence:1,reasoning:"Default strategy (PolicyGradient disabled)"});if(e.length===0)return f({strategy:"empty",selectedExperiments:[],confidence:1,reasoning:"No services provided"});try{let i={id:`chaos-strategy-${Date.now()}`,features:[r.riskTolerance,r.availableCapacity/100,e.length/50,e.filter(l=>!l.hasFailover).length/Math.max(1,e.length),e.filter(l=>l.type==="database").length/Math.max(1,e.length),r.environment==="production"?0:1,r.environment==="staging"?1:0,e.filter(l=>l.type==="cache").length/Math.max(1,e.length),e.filter(l=>l.type==="queue").length/Math.max(1,e.length),e.reduce((l,d)=>l+d.replicas,0)/Math.max(1,e.length*5)]},n=await this.policyGradient.predict(i),s=[],a="default";switch(n.action.type){case"allocate":let l=typeof n.action.value=="object"?n.action.value:null;if(l&&"agentType"in l&&l.agentType==="tester"){let m=e.filter(h=>!h.hasFailover||h.type==="database").slice(0,3);s=this.generateExperimentsForServices(m,["latency","error"]),a="allocate-critical"}break;case"reallocate":let d=typeof n.action.value=="object"?n.action.value:null;d&&"domain"in d&&d.domain==="test-execution"&&(s=this.generateExperimentsForServices(e.slice(0,5),["cpu-stress","memory-stress"]),a="reallocate-resource-stress");break;case"scale-up":s=this.generateExperimentsForServices(e,["latency","error","timeout"]),a="scale-up-comprehensive";break;case"scale-down":s=this.generateExperimentsForServices(e.slice(0,2),["latency"]),a="scale-down-minimal";break;default:s=this.getDefaultExperiments(e.slice(0,3)),a="default";break}let o=await this.calculateStrategyReward(s,r),c=n.action;return await this.policyGradient.train({state:i,action:c,reward:o,nextState:i,done:!0}),ie.info(`[chaos-resilience] PolicyGradient selected ${a} strategy for ${e.length} services (confidence: ${n.confidence.toFixed(2)})`),f({strategy:a,selectedExperiments:s,confidence:n.confidence,reasoning:n.reasoning||`PolicyGradient selected: ${a}`})}catch(i){return ie.error("PolicyGradient strategy selection failed:",i instanceof Error?i:void 0),f({strategy:"fallback",selectedExperiments:this.getDefaultExperiments(e.slice(0,3)),confidence:.5,reasoning:"Fallback to default (PolicyGradient error)"})}}generateExperimentsForServices(e,r){let i=[];for(let n of e)for(let s of r)i.push(this.createExperiment(`${n.name}-${s}-${Date.now()}`,`Test ${n.name} with ${s} fault`,s,n.name));return i}getDefaultExperiments(e){return this.generateExperimentsForServices(e,["latency","error"])}async calculateStrategyReward(e,r){let i=.5,n=e.length;(r.riskTolerance>.7&&n>5||r.riskTolerance<.3&&n<=3)&&(i+=.2),(r.availableCapacity>70&&n>5||r.availableCapacity<30&&n<=3)&&(i+=.1);let s=new Set(e.map(a=>a.faults[0]?.type));return i+=Math.min(.1,s.size/5),Math.max(0,Math.min(1,i))}async storeResiliencePattern(e,r,i){if(!(!this.qesona||!this.config.enableQESONA))try{let n={id:`chaos-${e.id}`,features:[e.faults.length/10,e.faults[0]?.duration?e.faults[0].duration/6e4:0,e.steadyState.probes.length/20,e.blastRadius.excludeProduction?1:0,(e.blastRadius.percentage??0)/100,r.hypothesisValidated?1:0,r.steadyStateVerified?1:0,r.incidents.length/10,r.incidents.filter(a=>a.severity==="critical").length/5,i]},s={type:r.hypothesisValidated?"validate":"reject",value:i};this.qesona.createPattern(n,s,{reward:r.hypothesisValidated?i:-i,success:r.hypothesisValidated,quality:i},"defect-prediction","chaos-resilience",{experimentId:e.id,experimentName:e.name,faultType:e.faults[0]?.type,hypothesisValidated:r.hypothesisValidated}),ie.info(`Stored resilience pattern for ${e.id} (validated: ${r.hypothesisValidated}, quality: ${i.toFixed(2)})`)}catch(n){ie.error("Failed to store resilience pattern:",n instanceof Error?n:void 0)}}async adaptStrategies(e,r){if(!this.qesona||!this.config.enableQESONA)return{shouldRunChaos:r.environment!=="production",recommendedFaults:["latency","error"],confidence:.5};try{let i={id:`chaos-adapt-${e.name}-${Date.now()}`,features:[e.hasFailover?0:1,r.riskTolerance,e.type==="api"?1:0,e.type==="database"?1:0,e.type==="cache"?1:0,r.environment==="production"?1:0,r.environment==="staging"?1:0,e.replicas/10,e.type==="worker"?1:0,e.type==="queue"?1:0]},n=await this.qesona.adaptPattern(i,"defect-prediction","chaos-resilience");if(n.success&&n.pattern){let s=n.pattern.outcome.success,a=this.getRecommendedFaults(n.pattern.action.type);return ie.info(`[chaos-resilience] QESONA adapted strategy for ${e.name}: shouldRun=${s}, faults=${a.join(",")}, confidence=${n.similarity.toFixed(2)}`),{shouldRunChaos:s,recommendedFaults:a,confidence:n.similarity}}return{shouldRunChaos:r.environment!=="production",recommendedFaults:["latency","error"],confidence:.5}}catch(i){return ie.error("QESONA strategy adaptation failed:",i instanceof Error?i:void 0),{shouldRunChaos:r.environment!=="production",recommendedFaults:["latency","error"],confidence:.5}}}getRecommendedFaults(e){switch(e){case"validate":return["latency","error","timeout"];case"reject":return["latency"];case"allocate":return["latency","cpu-stress"];case"scale-up":return["latency","error","timeout","packet-loss"];case"scale-down":return["latency"];default:return["latency","error"]}}subscribeToEvents(){this.eventBus.subscribe("quality-assessment.DeploymentApproved",this.handleDeploymentApproved.bind(this)),this.eventBus.subscribe("quality-assessment.QualityGateEvaluated",this.handleQualityGateEvaluated.bind(this))}async handleDeploymentApproved(e){if(!this.config.enableAutomatedExperiments)return;let r=e.payload;r.services&&await this.memory.set(`chaos-resilience:pending-assessment:${e.id}`,r.services,{namespace:"chaos-resilience",ttl:3600})}async handleQualityGateEvaluated(e){let r=e.payload;r.passed||await this.memory.set(`chaos-resilience:quality-gate-failures:${e.id}`,r,{namespace:"chaos-resilience",ttl:86400})}async loadWorkflowState(){let e=await this.memory.get("chaos-resilience:coordinator:workflows");if(e)for(let r of e)r.status==="running"&&(r.status="failed",r.error="Coordinator restarted",r.completedAt=new Date),this.workflows.set(r.id,r)}async saveWorkflowState(){let e=Array.from(this.workflows.values());await this.memory.set("chaos-resilience:coordinator:workflows",e,{namespace:"chaos-resilience",persist:!0})}async verifyChaosExperiment(e,r){let i=V({id:v(),type:"chaos-experiment",confidence:r,description:`Verify chaos experiment safety: ${e.name} (${e.faultType}) on ${e.target}`,payload:e,detectedBy:"chaos-resilience-coordinator",severity:e.blastRadius==="full"?"critical":r>.9?"high":"medium"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(ie.info(`Chaos experiment '${e.name}' verified safe by consensus`),!0):(ie.warn(`Chaos experiment '${e.name}' NOT verified safe: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}async verifyResilienceAssessment(e,r){let i=V({id:v(),type:"resilience-assessment",confidence:r,description:`Verify resilience assessment for ${e.service}: score ${e.overallScore}, ${e.weaknessCount} weaknesses`,payload:e,detectedBy:"chaos-resilience-coordinator",severity:e.overallScore<50?"critical":e.overallScore<70?"high":"medium"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(ie.info(`Resilience assessment for '${e.service}' verified by consensus`),!0):(ie.warn(`Resilience assessment for '${e.service}' NOT verified`),!1)}return!0}async verifyFailureInjection(e,r){let i=V({id:v(),type:"failure-injection",confidence:r,description:`Verify failure injection: ${e.faultType} on ${e.target} for ${e.duration}ms`,payload:e,detectedBy:"chaos-resilience-coordinator",severity:"critical"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(ie.info(`Failure injection '${e.faultType}' on '${e.target}' verified safe by consensus`),!0):(ie.warn(`Failure injection '${e.faultType}' NOT verified safe: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}};A();var cl=class extends j{constructor(e,r,i,n={},s){super(e,r);this.agentCoordinator=i;this.llmRouter=s;this.pluginConfig=n}agentCoordinator;llmRouter;coordinator=null;chaosEngineer=null;loadTester=null;performanceProfiler=null;pluginConfig;get name(){return"chaos-resilience"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{runChaosSuite:this.runChaosSuite.bind(this),runLoadTestSuite:this.runLoadTestSuite.bind(this),assessResilience:this.assessResilience.bind(this),generateExperiments:this.generateExperiments.bind(this),getResilienceDashboard:this.getResilienceDashboard.bind(this),createExperiment:this.createExperiment.bind(this),runExperiment:this.runExperiment.bind(this),abortExperiment:this.abortExperiment.bind(this),verifySteadyState:this.verifySteadyState.bind(this),injectFault:this.injectFault.bind(this),removeFault:this.removeFault.bind(this),createTest:this.createTest.bind(this),runTest:this.runTest.bind(this),runLoadTest:this.runTest.bind(this),stopTest:this.stopTest.bind(this),getRealtimeMetrics:this.getRealtimeMetrics.bind(this),generateFromTraffic:this.generateFromTraffic.bind(this),getExperimentHistory:this.getExperimentHistory.bind(this),testRecovery:this.testRecovery.bind(this),testFailover:this.testFailover.bind(this),testCircuitBreaker:this.testCircuitBreaker.bind(this),testRateLimiting:this.testRateLimiting.bind(this),selectChaosStrategy:this.coordinator.selectChaosStrategy.bind(this.coordinator),runStrategicChaosSuite:this.coordinator.runStrategicChaosSuite.bind(this.coordinator),getCoordinator:()=>this.coordinator,getChaosEngineer:()=>this.chaosEngineer,getChaosEngine:()=>this.chaosEngineer,getLoadTester:()=>this.loadTester,getPerformanceProfiler:()=>this.performanceProfiler,getResilienceAssessor:()=>this.performanceProfiler}}getTaskHandlers(){return new Map([["run-experiment",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.experimentId;return r?this.coordinator.runChaosSuite([r]):p(new Error("Invalid run-experiment payload: missing experimentId"))}],["run-load-test",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.testId;return r?this.coordinator.runLoadTestSuite([r]):p(new Error("Invalid run-load-test payload: missing testId"))}],["assess-resilience",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.services;return!r||r.length===0?p(new Error("Invalid assess-resilience payload: missing services")):this.coordinator.assessResilience(r)}],["inject-fault",async e=>{if(!this.chaosEngineer)return p(new Error("Chaos engineer not initialized"));let r=e.faultType,i=e.target;if(!r||!i)return p(new Error("Invalid inject-fault payload: missing faultType or target"));let n={id:`fault-${Date.now()}`,type:r,target:{type:"service",selector:i},parameters:e.parameters??{},duration:e.duration??3e4,probability:e.probability};return this.chaosEngineer.injectFault(n)}]])}async onInitialize(){this.chaosEngineer=new Dr({memory:this.memory,llmRouter:this.llmRouter},this.pluginConfig.chaosEngineer),this.loadTester=new Ir(this.memory,this.pluginConfig.loadTester),this.performanceProfiler=new Mr(this.memory,this.pluginConfig.performanceProfiler),this.coordinator=new Pa(this.eventBus,this.memory,this.agentCoordinator,this.pluginConfig.coordinator,this.llmRouter),await this.coordinator.initialize(),this.updateHealth({status:"idle",agents:{total:0,active:0,idle:0,failed:0},lastActivity:new Date,errors:[]})}async onDispose(){this.coordinator&&await this.coordinator.dispose(),this.coordinator=null,this.chaosEngineer=null,this.loadTester=null,this.performanceProfiler=null}subscribeToEvents(){this.eventBus.subscribe("quality-assessment.DeploymentApproved",this.handleDeploymentApproved.bind(this)),this.eventBus.subscribe("test-execution.TestRunCompleted",this.handleTestRunCompleted.bind(this)),this.eventBus.subscribe("security-compliance.VulnerabilityDetected",this.handleVulnerabilityDetected.bind(this))}async onEvent(e){switch(this.updateHealth({lastActivity:new Date}),e.type){case"quality-assessment.DeploymentApproved":await this.handleDeploymentApproved(e);break;case"test-execution.TestRunCompleted":await this.handleTestRunCompleted(e);break;case"security-compliance.VulnerabilityDetected":await this.handleVulnerabilityDetected(e);break;case"quality-assessment.QualityGateEvaluated":await this.handleQualityGateEvaluated(e);break;default:break}}async runChaosSuite(e){this.ensureInitialized();try{let r=await this.coordinator.runChaosSuite(e);return r.success?this.trackSuccessfulOperation("chaos-suite"):this.trackFailedOperation(r.error),r}catch(r){return this.handleError(r)}}async runLoadTestSuite(e){this.ensureInitialized();try{let r=await this.coordinator.runLoadTestSuite(e);return r.success?this.trackSuccessfulOperation("load-suite"):this.trackFailedOperation(r.error),r}catch(r){return this.handleError(r)}}async assessResilience(e){this.ensureInitialized();try{return await this.coordinator.assessResilience(e)}catch(r){return this.handleError(r)}}async generateExperiments(e){this.ensureInitialized();try{return await this.coordinator.generateExperiments(e)}catch(r){return this.handleError(r)}}async getResilienceDashboard(){this.ensureInitialized();try{return await this.coordinator.getResilienceDashboard()}catch(e){return this.handleError(e)}}async createExperiment(e){this.ensureInitialized();try{return await this.chaosEngineer.createExperiment(e)}catch(r){return this.handleError(r)}}async runExperiment(e){this.ensureInitialized();try{let r=await this.chaosEngineer.runExperiment(e);return r.success&&await this.publishExperimentEvent(r.value),r}catch(r){return this.handleError(r)}}async abortExperiment(e,r){this.ensureInitialized();try{return await this.chaosEngineer.abortExperiment(e,r)}catch(i){return this.handleError(i)}}async verifySteadyState(e){this.ensureInitialized();try{return await this.chaosEngineer.verifySteadyState(e)}catch(r){return this.handleError(r)}}async injectFault(e){this.ensureInitialized();try{return await this.chaosEngineer.injectFault(e)}catch(r){return this.handleError(r)}}async removeFault(e){this.ensureInitialized();try{return await this.chaosEngineer.removeFault(e)}catch(r){return this.handleError(r)}}async getExperimentHistory(){this.ensureInitialized();try{return{success:!0,value:await this.memory.get("chaos-resilience:experiment-history")??[]}}catch(e){return this.handleError(e)}}async createTest(e){this.ensureInitialized();try{return await this.loadTester.createTest(e)}catch(r){return this.handleError(r)}}async runTest(e){this.ensureInitialized();try{let r=await this.loadTester.runTest(e);return r.success&&await this.publishLoadTestEvent(r.value),r}catch(r){return this.handleError(r)}}async stopTest(e){this.ensureInitialized();try{return await this.loadTester.stopTest(e)}catch(r){return this.handleError(r)}}async getRealtimeMetrics(e){this.ensureInitialized();try{return await this.loadTester.getRealtimeMetrics(e)}catch(r){return this.handleError(r)}}async generateFromTraffic(e,r){this.ensureInitialized();try{return await this.loadTester.generateFromTraffic(e,r)}catch(i){return this.handleError(i)}}async testRecovery(e,r,i){this.ensureInitialized();try{return await this.performanceProfiler.testRecovery(e,r,i)}catch(n){return this.handleError(n)}}async testFailover(e,r){this.ensureInitialized();try{return await this.performanceProfiler.testFailover(e,r)}catch(i){return this.handleError(i)}}async testCircuitBreaker(e,r){this.ensureInitialized();try{return await this.performanceProfiler.testCircuitBreaker(e,r)}catch(i){return this.handleError(i)}}async testRateLimiting(e,r){this.ensureInitialized();try{return await this.performanceProfiler.testRateLimiting(e,r)}catch(i){return this.handleError(i)}}async handleDeploymentApproved(e){let r=e.payload;r.services&&r.services.length>0&&await this.memory.set(`chaos-resilience:pending-assessment:${e.id}`,{services:r.services,triggeredAt:new Date,source:"deployment-approved"},{namespace:"chaos-resilience",ttl:3600})}async handleTestRunCompleted(e){let r=e.payload;await this.memory.set(`chaos-resilience:test-baseline:${r.runId}`,{duration:r.duration,successRate:r.passed/(r.passed+r.failed),timestamp:new Date},{namespace:"chaos-resilience",ttl:86400})}async handleVulnerabilityDetected(e){let r=e.payload;(r.severity==="critical"||r.severity==="high")&&await this.memory.set(`chaos-resilience:security-tests:${r.vulnId}`,{vulnerabilityId:r.vulnId,severity:r.severity,file:r.file,triggeredAt:new Date},{namespace:"chaos-resilience",ttl:86400})}async handleQualityGateEvaluated(e){let r=e.payload;r.checks?.some(n=>n.name==="resilience")&&await this.memory.set(`chaos-resilience:gate-context:${r.gateId}`,{gateId:r.gateId,passed:r.passed,checks:r.checks,timestamp:Date.now()},{namespace:"chaos-resilience",ttl:3600})}async publishExperimentEvent(e){await this.publishEvent("chaos-resilience.ExperimentCompleted",{experimentId:e.experimentId,status:e.status,hypothesisValidated:e.hypothesisValidated,steadyStateVerified:e.steadyStateVerified,faultCount:e.faultResults.length,incidentCount:e.incidents.length,duration:e.endTime?e.endTime.getTime()-e.startTime.getTime():0})}async publishLoadTestEvent(e){await this.publishEvent("chaos-resilience.LoadTestCompleted",{testId:e.testId,status:e.status,duration:e.duration,totalRequests:e.summary.totalRequests,successRate:e.summary.totalRequests>0?e.summary.successfulRequests/e.summary.totalRequests*100:0,p95ResponseTime:e.summary.p95ResponseTime,errorRate:e.summary.errorRate,assertionsPassed:e.assertionResults.filter(r=>r.passed).length,assertionsFailed:e.assertionResults.filter(r=>!r.passed).length})}ensureInitialized(){if(!this._initialized)throw new Error("ChaosResiliencePlugin is not initialized");if(!this.coordinator||!this.chaosEngineer||!this.loadTester||!this.performanceProfiler)throw new Error("ChaosResiliencePlugin services are not available")}handleError(e){let r=y(e),i=this.getHealth();return this.updateHealth({errors:[...i.errors.slice(-9),r.message],status:i.errors.length>=5?"degraded":i.status}),{success:!1,error:r}}trackSuccessfulOperation(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,total:r.agents.total+1,idle:r.agents.idle+1},lastActivity:new Date})}trackFailedOperation(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,failed:r.agents.failed+1},errors:[...r.errors.slice(-9),e.message]})}};function Lm(u,t,e,r,i){return new cl(u,t,e,r,i)}M();A();M();A();var Zv={minExperiencesForPattern:5,patternConfidenceThreshold:.7,maxPatternsPerDomain:100,anomalyDeviationThreshold:2,clusterSimilarityThreshold:.8,enableLLMSynthesis:!0,llmModelTier:2,llmMaxTokens:2048},$m=R.create("learning-optimization/learning-coordinator"),be={namespace:"learning-optimization"},jt=class{config;memory;llmRouter;flashAttention=null;constructor(t,e={}){this.memory=t.memory,this.llmRouter=t.llmRouter,this.config={...Zv,...e}}async initializeFlashAttention(t){return this.flashAttention=await Me("pattern-adaptation",t),$m.info("FlashAttention initialized for pattern adaptation"),this.flashAttention}injectFlashAttention(t){this.flashAttention=t}isFlashAttentionAvailable(){return this.flashAttention!==null}getFlashAttentionMetrics(){return this.flashAttention?this.flashAttention.getMetrics():[]}async computeSimilarityWithFlashAttention(t,e){if(!this.flashAttention)throw new Error("[LearningCoordinatorService] FlashAttention not initialized. Call initializeFlashAttention() first.");let r=Math.min(t.length,e.length),i=new Float32Array(r),n=new Float32Array(r),s=new Float32Array(r);for(let c=0;c<r;c++)i[c]=t[c],n[c]=e[c],s[c]=1;let a=await this.flashAttention.computeFlashAttention(i,n,s,1,r),o=Math.abs(a[0]);return Math.min(1,o)}async batchComputeSimilarities(t,e,r=5){if(!this.flashAttention)throw new Error("[LearningCoordinatorService] FlashAttention not initialized. Call initializeFlashAttention() first.");let i=new Float32Array(t),n=e.map(s=>new Float32Array(s));return this.flashAttention.computeTestSimilarity(i,n,r)}disposeFlashAttention(){this.flashAttention&&(this.flashAttention.dispose(),this.flashAttention=null)}isLLMSynthesisAvailable(){return this.config.enableLLMSynthesis&&this.llmRouter!==void 0}getModelForTier(t){let e={1:"claude-haiku-4-5",2:"claude-sonnet-4-6",3:"claude-sonnet-4-6",4:"claude-opus-4-7"};return e[t]||e[2]}async synthesizePatternsWithLLM(t){if(!this.isLLMSynthesisAvailable())return null;try{let e=t.slice(0,10).map(i=>`- ${i.name}: ${i.type} (confidence: ${i.confidence.toFixed(2)})`).join(`
|
|
3016
|
+
3. Recommended safety measures`}],maxTokens:this.config.llmMaxTokens})).content}catch{return N.warn("LLM analysis failed:"),null}}validateExperiment(t){return t.id?t.name?t.hypothesis?!t.steadyState||t.steadyState.probes.length===0?p(new Error("At least one steady state probe is required")):!t.faults||t.faults.length===0?p(new Error("At least one fault injection is required")):t.rollbackPlan?t.blastRadius.excludeProduction===!1&&!t.rollbackPlan.automatic?p(new Error("Production experiments require automatic rollback")):f(void 0):p(new Error("Rollback plan is required")):p(new Error("Experiment hypothesis is required")):p(new Error("Experiment name is required")):p(new Error("Experiment ID is required"))}validateFault(t){return t.id?t.type?t.target?t.duration<0?p(new Error("Fault duration must be non-negative")):t.probability!==void 0&&(t.probability<0||t.probability>1)?p(new Error("Fault probability must be between 0 and 1")):f(void 0):p(new Error("Fault target is required")):p(new Error("Fault type is required")):p(new Error("Fault ID is required"))}createExecution(t){return{experimentId:t.id,startTime:new Date,result:{experimentId:t.id,status:"running",startTime:new Date,hypothesisValidated:!1,steadyStateVerified:!1,faultResults:[],metrics:[],incidents:[]}}}finalizeExecution(t){t.result.endTime=new Date;let e={experimentId:t.result.experimentId,status:t.result.status,startTime:t.result.startTime,endTime:t.result.endTime,hypothesisValidated:t.result.hypothesisValidated,steadyStateVerified:t.result.steadyStateVerified,faultResults:t.result.faultResults,metrics:t.result.metrics,incidents:t.result.incidents};return this.memory.set(`chaos:results:${t.experimentId}:${Date.now()}`,e,{namespace:"chaos-resilience",persist:!0}),e}async executeProbe(t){try{switch(t.type){case"http":return await this.executeHttpProbe(t);case"tcp":return await this.executeTcpProbe(t);case"command":return await this.executeCommandProbe(t);case"metric":return await this.executeMetricProbe(t);default:return!1}}catch{return!1}}async executeHttpProbe(t){try{let e=await this.httpClient.get(t.target,{timeout:t.timeout??5e3,retries:1,circuitBreaker:!1});if(!e.success)return N.info(`HTTP probe failed: ${t.name} -> ${e.error.message}`),!1;let r=e.value;if(t.expectedStatus!==void 0){let i=r.status===t.expectedStatus;return i||N.info(`HTTP probe ${t.name}: expected status ${t.expectedStatus}, got ${r.status}`),i}return r.ok}catch(e){return N.info(`HTTP probe error: ${t.name} -> ${T(e)}`),!1}}async executeTcpProbe(t){return new Promise(e=>{try{let[r,i]=t.target.split(":"),n=parseInt(i,10);if(!r||isNaN(n)){N.info(`TCP probe invalid target: ${t.target} (expected host:port)`),e(!1);return}let s=t.timeout??5e3,a=new Fm.Socket,o=setTimeout(()=>{a.destroy(),N.info(`TCP probe timeout: ${t.name} -> ${t.target}`),e(!1)},s);a.connect(n,r,()=>{clearTimeout(o),a.destroy(),e(!0)}),a.on("error",c=>{clearTimeout(o),a.destroy(),N.info(`TCP probe error: ${t.name} -> ${c.message}`),e(!1)})}catch(r){N.info(`TCP probe exception: ${t.name} -> ${T(r)}`),e(!1)}})}static ALLOWED_PROBE_COMMANDS=["curl","wget","nc","netcat","ping","nslookup","dig","ps","pgrep","cat","head","tail","ls","stat","echo","test","[","node","npm"];async executeCommandProbe(t){return new Promise(e=>{let r=t.timeout??1e4,i=ma(t.target,u.ALLOWED_PROBE_COMMANDS);if(!i.valid){N.info(`Command probe ${t.name} blocked: ${i.error}`),N.info(`Blocked patterns: ${i.blockedPatterns?.join(", ")||"none"}`),e(!1);return}let s=(i.sanitizedCommand||t.target).trim().split(/\s+/),a=s[0],o=s.slice(1);Mm(a,o,{timeout:r},(c,l,d)=>{if(c){N.info(`Command probe failed: ${t.name} -> ${c.message}`),e(!1);return}if(t.expectedOutput!==void 0){let m=l.trim().includes(t.expectedOutput);m||N.info(`Command probe ${t.name}: output did not contain expected value`),e(m);return}e(!0)})})}async executeMetricProbe(t){try{let e=await this.httpClient.get(t.target,{timeout:t.timeout??5e3,retries:1,circuitBreaker:!1});if(!e.success)return N.info(`Metric probe failed: ${t.name} -> ${e.error.message}`),!1;let r=e.value;if(!r.ok)return N.info(`Metric probe HTTP error: ${t.name} -> ${r.status}`),!1;let i=await r.text(),n;try{let s=E(i);n=typeof s.value=="number"?s.value:parseFloat(s.value)}catch{n=parseFloat(i)}if(isNaN(n))return N.info(`Metric probe ${t.name}: could not parse metric value from response`),!1;if(t.threshold!==void 0){let{operator:s,value:a}=t.threshold;switch(s){case"lt":return n<a;case"gt":return n>a;case"lte":return n<=a;case"gte":return n>=a;case"eq":return n===a;default:return!0}}return!0}catch(e){return N.info(`Metric probe error: ${t.name} -> ${T(e)}`),!1}}async performFaultInjection(t){let r={latency:async()=>this.injectLatency(t),error:async()=>this.injectError(t),timeout:async()=>this.injectTimeout(t),"packet-loss":async()=>this.injectPacketLoss(t),"cpu-stress":async()=>this.injectCpuStress(t),"memory-stress":async()=>this.injectMemoryStress(t),"disk-stress":async()=>this.injectDiskStress(t),"network-partition":async()=>this.injectNetworkPartition(t),"dns-failure":async()=>this.injectDnsFailure(t),"process-kill":async()=>this.injectProcessKill(t)}[t.type];return r?r():p(new Error(`Unknown fault type: ${t.type}`))}async injectLatency(t){let e=t.parameters.latencyMs??100;return N.info(`Latency injection configured: ${e}ms for ${t.target.selector}`),N.info("Note: Actual latency injection requires network proxy (e.g., Toxiproxy, tc)"),f(1)}async injectError(t){let e=t.parameters.errorCode??500;return N.info(`Error injection configured: ${e} for ${t.target.selector}`),N.info("Note: Actual error injection requires service mesh (e.g., Istio, Linkerd)"),f(1)}async injectTimeout(t){return N.info(`Timeout injection configured for ${t.target.selector}`),N.info("Note: Actual timeout injection requires network proxy configuration"),f(1)}async injectPacketLoss(t){let e=t.parameters.packetLossPercent??10;return N.info(`Packet loss configured: ${e}% for ${t.target.selector}`),N.info("Note: Actual packet loss requires tc/iptables (Linux) or similar"),f(1)}async injectCpuStress(t){let e=t.parameters.cpuPercent??80,r=t.parameters.cores??1,i=t.duration;N.info(`Injecting CPU stress: ${e}% on ${r} core(s) for ${i}ms`);let n=Date.now(),s=setInterval(()=>{if(Date.now()-n>=i){clearInterval(s);return}let a=10*(e/100),o=Date.now();for(;Date.now()-o<a;)L()*L()},10);return this.stressWorkers.set(t.id,s),f(r)}async injectMemoryStress(t){let e=t.parameters.memoryBytes??104857600,r=Math.round(e/(1024*1024));N.info(`Injecting memory stress: ${r}MB allocation`);try{let n=Math.ceil(e/1048576),s=[];for(let a=0;a<n;a++){let o=Math.min(1048576,e-a*1048576),c=new Array(o).fill(L());s.push(c)}return this.stressWorkers.set(t.id,s),N.info(`Memory stress active: ${s.length} chunks allocated`),f(1)}catch(i){return p(new Error(`Failed to allocate memory: ${T(i)}`))}}async injectDiskStress(t){return N.info(`Disk stress configured for ${t.target.selector}`),N.info("Note: Actual disk stress requires file system write permissions"),f(1)}async injectNetworkPartition(t){return N.info(`Network partition configured for ${t.target.selector}`),N.info("Note: Actual network partition requires iptables/firewall rules"),f(1)}async injectDnsFailure(t){return N.info(`DNS failure configured for ${t.target.selector}`),N.info("Note: Actual DNS failure requires DNS server or /etc/hosts modification"),f(1)}async injectProcessKill(t){let e=t.target.selector;return N.info(`Process kill configured for pattern: ${e}`),N.info("Note: Actual process kill requires appropriate permissions"),this.config.enableDryRun?(N.info(`Would kill processes matching: ${e}`),f(0)):f(1)}async performFaultRemoval(t){N.info(`Removing fault: ${t.id} (${t.type})`);let e=this.stressWorkers.get(t.id);e&&(typeof e=="object"&&"unref"in e&&clearInterval(e),this.stressWorkers.delete(t.id))}async collectMetricsDuringExperiment(t,e){let r=e.hypothesis.metrics.map(s=>s.metric),i=Date.now(),n=Math.max(...e.faults.map(s=>s.duration),this.config.defaultTimeout);for(;Date.now()-i<Math.min(n,5e3);){for(let s of r){let a={timestamp:new Date,name:s,value:this.collectRealMetricValue(s),labels:{experiment:e.id}};t.result.metrics.push(a)}await this.sleep(this.config.safetyCheckInterval)}}collectRealMetricValue(t){return this.metricsCollector.getChaosMetricValue(t)}validateHypothesis(t,e){for(let r of t.metrics){let i=e.filter(s=>s.name===r.metric);if(i.length===0)return!1;let n=i.reduce((s,a)=>s+a.value,0)/i.length;if(!this.checkMetricExpectation(n,r))return!1}for(let r of t.tolerances){let i=e.filter(o=>o.name===r.metric);if(i.length===0)continue;let n=i.map(o=>o.value),s=this.calculateDeviation(n);if((r.unit==="percent"?s/n[0]*100:s)>r.maxDeviation)return!1}return!0}checkMetricExpectation(t,e){let{operator:r,value:i}=e;switch(r){case"eq":return t===i;case"lt":return t<i;case"gt":return t>i;case"lte":return t<=i;case"gte":return t>=i;case"between":{let[n,s]=i;return t>=n&&t<=s}default:return!1}}calculateDeviation(t){if(t.length===0)return 0;let e=t.reduce((i,n)=>i+n,0)/t.length,r=t.map(i=>Math.pow(i-e,2));return Math.sqrt(r.reduce((i,n)=>i+n,0)/t.length)}determineExperimentStatus(t,e){return!t.result.steadyStateVerified||!e?"failed":t.result.hypothesisValidated?"completed":t.result.faultResults.filter(i=>!i.injected).length>0?"failed":"completed"}async rollbackExperiment(t){for(let e of t.rollbackPlan.steps.sort((r,i)=>r.order-i.order)){N.info(`Executing rollback step ${e.order}: ${e.action}`);try{await this.executeRollbackAction(e.action,e.target,e.timeout)}catch(r){N.error(`Rollback step ${e.order} failed: ${T(r)}`)}}for(let e of t.faults)await this.removeFault(e.id)}async executeRollbackAction(t,e,r=3e4){t.startsWith("http://")||t.startsWith("https://")?await this.executeHttpRollback(t,r):t.startsWith("cmd:")?await this.executeCommandRollback(t.slice(4),r):e&&(e.startsWith("http://")||e.startsWith("https://"))?await this.executeHttpRollback(`${e}/_chaos/${t}`,r):await this.executeBuiltInRollback(t,e,r)}async executeHttpRollback(t,e){let r=await this.httpClient.post(t,{},{timeout:e,retries:1});if(!r.success)throw new Error(`HTTP rollback failed: ${r.error.message}`)}static ALLOWED_ROLLBACK_COMMANDS=["kill","pkill","rm","rmdir","mv","cp","systemctl","service","docker","kubectl","iptables","tc","echo","true"];executeCommandRollback(t,e){return new Promise((r,i)=>{let n=ma(t,u.ALLOWED_ROLLBACK_COMMANDS);if(!n.valid){i(new Error(`Rollback command blocked: ${n.error}`));return}let a=(n.sanitizedCommand||t).trim().split(/\s+/),o=a[0],c=a.slice(1);Mm(o,c,{timeout:e},(l,d,m)=>{l?i(new Error(`Command rollback failed: ${l.message}. ${m}`)):r()})})}async executeBuiltInRollback(t,e,r){let i=t.toLowerCase();i.includes("remove")||i.includes("clear")?e&&N.info(`Clearing state for target: ${e}`):i.includes("restart")?N.info(`Restart requested for: ${e||"service"}`):i.includes("restore")?N.info(`Restore requested for: ${e||"system"}`):N.info(`Rollback action logged: ${t}`),await this.sleep(100)}sleep(t){return new Promise(e=>setTimeout(e,t))}};A();se();var Kv={defaultTimeout:3e5,maxVirtualUsers:1e3,reportingInterval:1e3,enableDetailedMetrics:!0,connectionPoolSize:100},Ir=class{constructor(t,e={}){this.memory=t;this.config={...Kv,...e},this.httpClient=new Be}memory;config;activeTests=new Map;httpClient;async createTest(t){try{let e=this.validateTest(t);return e.success?(await this.memory.set(`loadtest:tests:${t.id}`,t,{namespace:"chaos-resilience",persist:!0}),f(t.id)):p(e.error)}catch(e){return p(y(e))}}async runTest(t){try{let e=await this.memory.get(`loadtest:tests:${t}`);if(!e)return p(new Error(`Load test not found: ${t}`));if(this.activeTests.has(t))return p(new Error(`Load test ${t} is already running`));if(e.profile.virtualUsers.max>this.config.maxVirtualUsers)return p(new Error(`Virtual users (${e.profile.virtualUsers.max}) exceeds maximum (${this.config.maxVirtualUsers})`));let r=this.createExecution(e);this.activeTests.set(t,r);try{return await this.executeLoadTest(r,e),r.result.assertionResults=this.evaluateAssertions(e.assertions,r.result.summary),r.result.status=this.determineTestStatus(r.result),f(this.finalizeExecution(r))}catch(i){return r.result.status="failed",r.result.errors.push({type:"execution_error",message:T(i),count:1,firstOccurrence:new Date,lastOccurrence:new Date}),f(this.finalizeExecution(r))}finally{this.activeTests.delete(t)}}catch(e){return p(y(e))}}async stopTest(t){try{let e=this.activeTests.get(t);return e?(e.aborted=!0,e.result.status="aborted",f(this.finalizeExecution(e))):p(new Error(`No active load test found: ${t}`))}catch(e){return p(y(e))}}async getRealtimeMetrics(t){try{let e=this.activeTests.get(t);if(!e)return p(new Error(`No active load test found: ${t}`));let r=e.result.timeline[e.result.timeline.length-1];return r?f(r):p(new Error("No metrics available yet"))}catch(e){return p(y(e))}}async generateFromTraffic(t,e){try{if(t.requests.length===0)return p(new Error("Traffic sample contains no requests"));if(e<=0)return p(new Error("Multiplier must be positive"));let r=t.requests.reduce((h,g)=>h+g.frequency,0),i=t.requests.reduce((h,g)=>h+g.avgResponseTime*g.frequency,0)/r,n=t.requests.map(h=>({name:`${h.method} ${h.url}`,weight:h.frequency/r,steps:[{type:"request",target:{url:h.url,method:h.method}},{type:"think",duration:Math.max(100,i*.5)}]})),a=r/t.duration*e,o=Math.ceil(a*(i/1e3)),c={virtualUsers:{start:Math.ceil(o*.1),max:Math.min(o,this.config.maxVirtualUsers),pattern:"ramp"},duration:Math.max(6e4,t.duration*e),rampUp:3e4,rampDown:15e3},l=[{metric:"p95",operator:"lt",value:i*2},{metric:"error-rate",operator:"lt",value:5},{metric:"throughput",operator:"gte",value:a*.9}],d=e>5?"stress":"load",m={id:v(),name:`Generated from ${t.source} (${e}x)`,type:d,target:{url:t.requests[0].url,method:t.requests[0].method},profile:c,scenarios:n,assertions:l};return f(m)}catch(r){return p(y(r))}}validateTest(t){return t.id?t.name?!t.target||!t.target.url?p(new Error("Test target URL is required")):t.profile?t.profile.virtualUsers.max<=0?p(new Error("Maximum virtual users must be positive")):t.profile.duration<=0?p(new Error("Test duration must be positive")):f(void 0):p(new Error("Test profile is required")):p(new Error("Test name is required")):p(new Error("Test ID is required"))}createExecution(t){return{testId:t.id,startTime:new Date,aborted:!1,result:{testId:t.id,status:"completed",duration:0,summary:this.createEmptySummary(),timeline:[],errors:[],assertionResults:[]}}}createEmptySummary(){return{totalRequests:0,successfulRequests:0,failedRequests:0,requestsPerSecond:0,avgResponseTime:0,p50ResponseTime:0,p95ResponseTime:0,p99ResponseTime:0,maxResponseTime:0,errorRate:0}}async executeLoadTest(t,e){let r=Date.now(),i=e.profile.duration,n=[],s=new Map,a=this.getExecutionStrategy(e.type);for(;Date.now()-r<i&&!t.aborted;){let o=Date.now()-r,c=this.calculateCurrentVirtualUsers(e.profile,o,i),l=await this.executeBatch(e,c,a);n.push(...l.responseTimes);for(let m of l.errors){let h=s.get(m);h?(h.count++,h.lastOccurrence=new Date):s.set(m,{type:"request_error",message:m,count:1,firstOccurrence:new Date,lastOccurrence:new Date})}t.result.summary.totalRequests+=l.totalRequests,t.result.summary.successfulRequests+=l.successfulRequests,t.result.summary.failedRequests+=l.failedRequests;let d={timestamp:new Date,virtualUsers:c,requestsPerSecond:l.totalRequests,avgResponseTime:l.responseTimes.length>0?l.responseTimes.reduce((m,h)=>m+h,0)/l.responseTimes.length:0,errorRate:l.totalRequests>0?l.failedRequests/l.totalRequests*100:0};t.result.timeline.push(d),await this.sleep(this.config.reportingInterval)}if(t.result.duration=Date.now()-r,t.result.errors=Array.from(s.values()),n.length>0){let o=n.sort((c,l)=>c-l);t.result.summary.avgResponseTime=o.reduce((c,l)=>c+l,0)/o.length,t.result.summary.p50ResponseTime=this.percentile(o,50),t.result.summary.p95ResponseTime=this.percentile(o,95),t.result.summary.p99ResponseTime=this.percentile(o,99),t.result.summary.maxResponseTime=o[o.length-1]}t.result.summary.requestsPerSecond=t.result.summary.totalRequests/(t.result.duration/1e3),t.result.summary.errorRate=t.result.summary.totalRequests>0?t.result.summary.failedRequests/t.result.summary.totalRequests*100:0}getExecutionStrategy(t){switch(t){case"load":return{requestMultiplier:1,errorInjectionRate:0};case"stress":return{requestMultiplier:1.5,errorInjectionRate:.01};case"spike":return{requestMultiplier:3,errorInjectionRate:.02};case"soak":return{requestMultiplier:.8,errorInjectionRate:0};case"breakpoint":return{requestMultiplier:2,errorInjectionRate:.05};default:return{requestMultiplier:1,errorInjectionRate:0}}}calculateCurrentVirtualUsers(t,e,r){let{virtualUsers:i,rampUp:n=0,rampDown:s=0}=t,{start:a,max:o,pattern:c}=i;switch(c){case"constant":return o;case"ramp":if(e<n)return Math.round(a+(o-a)*(e/n));if(e>r-s){let l=(r-e)/s;return Math.round(a+(o-a)*l)}return o;case"step":{let d=r/5,m=Math.floor(e/d),h=(o-a)/5;return Math.round(a+h*m)}case"spike":return e%3e4<5e3?o:a;default:return o}}async executeBatch(t,e,r){let i=Math.round(e*r.requestMultiplier),n=Math.min(i,this.config.connectionPoolSize),s=this.createBatches(i,n),a=[];for(let l of s){let d=Date.now(),m=await Promise.all(l.map(()=>this.executeRequest(t,r)));a.push(...m);let h=Date.now()-d,g=1e3/Math.max(e,1)*l.length;h<g&&await this.sleep(g-h)}let o=a.filter(l=>l.success).map(l=>l.latency),c=a.filter(l=>!l.success).map(l=>l.error||"Unknown error");return{totalRequests:a.length,successfulRequests:a.filter(l=>l.success).length,failedRequests:a.filter(l=>!l.success).length,responseTimes:o,errors:c}}async executeRequest(t,e){let r=Date.now(),i=r;if(e.errorInjectionRate>0&&L()<e.errorInjectionRate)return{status:0,latency:Date.now()-r,success:!1,error:"Simulated error injection",timestamp:i};try{let{url:n,method:s="GET",headers:a,body:o}=t.target,c={headers:a,timeout:this.config.defaultTimeout,retries:0,circuitBreaker:!1},l;switch(s.toUpperCase()){case"POST":l=await this.httpClient.post(n,o,c);break;case"PUT":l=await this.httpClient.put(n,o,c);break;case"DELETE":l=await this.httpClient.delete(n,c);break;default:l=await this.httpClient.get(n,c);break}if(l.success){let d=l.value;return{status:d.status,latency:Date.now()-r,success:d.ok,error:d.ok?void 0:`HTTP ${d.status}: ${d.statusText}`,timestamp:i}}else return{status:l.error.status??0,latency:Date.now()-r,success:!1,error:l.error.message,timestamp:i}}catch(n){return{status:0,latency:Date.now()-r,success:!1,error:T(n),timestamp:i}}}createBatches(t,e){let r=[],i=t;for(;i>0;){let n=Math.min(i,e);r.push(Array.from({length:n},(s,a)=>a)),i-=n}return r}percentile(t,e){if(t.length===0)return 0;let r=Math.ceil(e/100*t.length)-1;return t[Math.max(0,Math.min(r,t.length-1))]}evaluateAssertions(t,e){return t.map(r=>{let i=this.getMetricValue(r.metric,e),n=this.checkAssertion(r,i);return{assertion:r,passed:n,actualValue:i}})}getMetricValue(t,e){switch(t){case"response-time":return e.avgResponseTime;case"throughput":return e.requestsPerSecond;case"error-rate":return e.errorRate;case"p95":return e.p95ResponseTime;case"p99":return e.p99ResponseTime;default:return 0}}checkAssertion(t,e){switch(t.operator){case"lt":return e<t.value;case"gt":return e>t.value;case"lte":return e<=t.value;case"gte":return e>=t.value;default:return!1}}determineTestStatus(t){return t.status==="aborted"?"aborted":t.assertionResults.filter(r=>!r.passed).length>0||t.summary.errorRate>10?"failed":"completed"}finalizeExecution(t){let e={testId:t.result.testId,status:t.result.status,duration:t.result.duration,summary:t.result.summary,timeline:t.result.timeline,errors:t.result.errors,assertionResults:t.result.assertionResults};return this.memory.set(`loadtest:results:${t.testId}:${Date.now()}`,e,{namespace:"chaos-resilience",persist:!0}),e}sleep(t){return new Promise(e=>setTimeout(e,t))}};M();A();se();H();var Jv={defaultTimeout:6e4,healthCheckInterval:1e3,maxRetries:3,recoveryCheckDelay:500,simulateRandomFailures:!1},bt=R.create("chaos-resilience/performance-profiler"),Mr=class{constructor(t,e={}){this.memory=t;this.config={...Jv,...e},this.httpClient=Gi()}memory;config;httpClient;async testRecovery(t,e,r){let i=v();try{let n=[],s=await this.checkServiceHealth(t);if(n.push({timestamp:new Date,event:"Initial health check",status:s?"healthy":"unhealthy"}),!s)return f({service:t,faultType:e,recoveryTime:0,expectedRecoveryTime:r,passed:!1,timeline:n});n.push({timestamp:new Date,event:`Injecting fault: ${e}`,status:"degraded"}),await this.injectFault(t,e);let a=await this.checkServiceHealth(t);n.push({timestamp:new Date,event:"Post-fault health check",status:a?"healthy":"unhealthy"}),n.push({timestamp:new Date,event:"Removing fault",status:"degraded"}),await this.removeFault(t,e);let o=Date.now(),c=0,l=!1,d=r*2;for(;Date.now()-o<d;){if(await this.checkServiceHealth(t)){c=Date.now()-o,l=!0,n.push({timestamp:new Date,event:"Service recovered",status:"healthy"});break}n.push({timestamp:new Date,event:"Recovery check - still degraded",status:"degraded"}),await this.sleep(this.config.recoveryCheckDelay)}l||n.push({timestamp:new Date,event:"Recovery timeout exceeded",status:"unhealthy"});let m={service:t,faultType:e,recoveryTime:c,expectedRecoveryTime:r,passed:l&&c<=r,timeline:n};return await this.storeTestResult("recovery",i,m),f(m)}catch(n){return p(y(n))}}async testFailover(t,e){let r=v();try{let i=[],n=1,[s,a]=await Promise.all([this.checkServiceHealth(t),this.checkServiceHealth(e)]);if(i.push({order:n++,action:"Verify primary service health",duration:0,success:s}),i.push({order:n++,action:"Verify secondary service health",duration:0,success:a}),!s||!a)return f({primaryService:t,secondaryService:e,failoverTime:0,dataLoss:!0,passed:!1,steps:i});let o=await this.captureServiceState(t);i.push({order:n++,action:"Capture primary service state",duration:0,success:!0});let c=Date.now();await this.injectFault(t,"process-kill"),i.push({order:n++,action:"Trigger primary service failure",duration:Date.now()-c,success:!0});let l=Date.now(),d=!1,m=0;for(;Date.now()-l<this.config.defaultTimeout;){if(await this.checkServiceIsActive(e)){m=Date.now()-c,d=!0;break}await this.sleep(this.config.healthCheckInterval)}i.push({order:n++,action:"Detect failover completion",duration:m,success:d});let h=await this.captureServiceState(e),g=!this.compareServiceStates(o,h);i.push({order:n++,action:"Verify data integrity on secondary",duration:0,success:!g}),await this.removeFault(t,"process-kill"),i.push({order:n++,action:"Restore primary service",duration:0,success:!0});let b={primaryService:t,secondaryService:e,failoverTime:m,dataLoss:g,passed:d&&!g,steps:i};return await this.storeTestResult("failover",r,b),f(b)}catch(i){return p(y(i))}}async testCircuitBreaker(t,e){let r=v();try{let i=e?.errorThreshold??5,n=e?.timeout??this.config.defaultTimeout,s=e?.halfOpenRequests??3;await this.getCircuitState(t)!=="closed"&&await this.resetCircuit(t);let o=0,c=!1;for(let w=0;w<i*2;w++)if(await this.generateError(t),o++,await this.getCircuitState(t)==="open"){c=!0;break}let l=!1,d=Date.now();for(;Date.now()-d<n;){if(await this.getCircuitState(t)==="half-open"){l=!0;break}await this.sleep(this.config.healthCheckInterval)}let m="correct";if(l){let w=0;for(let S=0;S<s;S++)await this.sendSuccessfulRequest(t)&&w++;await this.getCircuitState(t)!=="closed"&&w===s&&(m="incorrect")}let h=!1,g=Date.now();for(;Date.now()-g<n;){if(await this.getCircuitState(t)==="closed"){h=!0;break}await this.sendSuccessfulRequest(t),await this.sleep(this.config.healthCheckInterval)}let b={service:t,opened:c,openedAfterErrors:o,closedAfterRecovery:h,halfOpenBehavior:m,passed:c&&h&&m==="correct"};return await this.storeTestResult("circuit-breaker",r,b),f(b)}catch(i){return p(y(i))}}async testRateLimiting(t,e){let r=v();try{let i=0,n={statusCode:429,retryAfter:void 0,body:void 0},s=[1,5,10,25,50,100,200],a=0,o=!1;for(let m of s){if(o)break;let h=await this.sendRequestBatch(t,m);a+=m;for(let g of h)if(g.statusCode===429){o=!0,i=a-(m-h.indexOf(g)),n=g;break}}o||(i=a);let c=e*.2,l=Math.abs(i-e)<=c||!o,d={service:t,expectedLimit:e,actualLimit:i,passed:o&&l,responseWhenLimited:n};return await this.storeTestResult("rate-limit",r,d),f(d)}catch(i){return p(y(i))}}async checkServiceHealth(t){if(!this.isRealServiceUrl(t))return this.simulateHealthCheck();try{return await this.httpClient.healthCheck(t)}catch{return this.simulateHealthCheck()}}isRealServiceUrl(t){return t.startsWith("http://")||t.startsWith("https://")}simulateHealthCheck(){return this.config.simulateRandomFailures?L()>.05:!0}async checkServiceIsActive(t){if(!this.isRealServiceUrl(t))return this.simulateServiceActive();try{let e=await this.httpClient.get(t,{timeout:5e3,retries:1});return e.success&&e.value.ok}catch{return this.simulateServiceActive()}}simulateServiceActive(){return this.config.simulateRandomFailures?L()>.1:!0}async injectFault(t,e){if(this.isRealServiceUrl(t))try{let r=`${t}/_chaos/inject`;await this.httpClient.post(r,{faultType:e},{timeout:5e3,retries:0});return}catch{bt.debug("Fault injection API failed:")}bt.info(`Injecting fault ${e} into service: ${t}`),await this.sleep(100)}async removeFault(t,e){if(this.isRealServiceUrl(t))try{let r=`${t}/_chaos/remove`;await this.httpClient.post(r,{faultType:e},{timeout:5e3,retries:0});return}catch{bt.debug("Fault removal API failed:")}bt.info(`Removing fault ${e} from service: ${t}`),await this.sleep(50)}async captureServiceState(t){if(this.isRealServiceUrl(t))try{let r=`${t}/_state`,i=await this.httpClient.get(r,{timeout:5e3,retries:1});if(i.success&&i.value.ok){let n=await i.value.text(),s=this.calculateChecksum(n),a=this.parseRecordCount(n);return{checksum:s,timestamp:new Date,records:a}}}catch{bt.debug("State capture API failed:")}return await this.captureMemoryState(t)}calculateChecksum(t){let e=0;for(let r=0;r<t.length;r++){let i=t.charCodeAt(r);e=(e<<5)-e+i,e=e&e}return`chk_${Math.abs(e).toString(16)}`}parseRecordCount(t){try{let e=E(t);return e.records??e.count??e.total??e.length??0}catch{return t.split(`
|
|
3017
|
+
`).filter(e=>e.trim()).length}}async captureMemoryState(t){let e=`resilience:state:${this.hashServiceName(t)}`,r=await this.memory.get(e);if(r)return r;let i={checksum:`init_${v().slice(0,8)}`,timestamp:new Date,records:0};return await this.memory.set(e,i,{namespace:"chaos-resilience"}),i}hashServiceName(t){let e=0;for(let r of t)e=(e<<5)-e+r.charCodeAt(0),e=e&e;return Math.abs(e).toString(16)}compareServiceStates(t,e){let r=t.checksum===e.checksum,i=t.records===e.records;return r||i}async getCircuitState(t){try{return this.httpClient.getCircuitState(t).state}catch{return"closed"}}async resetCircuit(t){try{this.httpClient.resetCircuit(t)}catch{bt.info(`Resetting circuit breaker for: ${t}`)}}async generateError(t){if(this.isRealServiceUrl(t))try{let e=`${t}/_chaos/error`;await this.httpClient.post(e,{},{timeout:5e3,retries:0});return}catch{bt.debug("Error generation API failed:")}bt.info(`Generating error for: ${t}`)}async sendSuccessfulRequest(t){if(!this.isRealServiceUrl(t))return!0;try{let e=await this.httpClient.get(t,{timeout:5e3,retries:1});return e.success&&e.value.ok}catch{return!0}}async sendRequestBatch(t,e){let r=[];if(!this.isRealServiceUrl(t))return this.simulateRequestBatch(e);for(let i=0;i<e;i++)try{let n=await this.httpClient.get(t,{timeout:2e3,retries:0,circuitBreaker:!1});if(n.success){let s=n.value,a=s.headers.get("Retry-After");r.push({statusCode:s.status,retryAfter:a?parseInt(a,10):void 0})}else r.push({statusCode:500,body:{error:n.error.message}})}catch{return[...r,...this.simulateRequestBatch(e-i)]}return r}simulateRequestBatch(t){let e=[];for(let i=0;i<t;i++)i>=75?e.push({statusCode:429,retryAfter:60,body:{error:"Rate limit exceeded"}}):e.push({statusCode:200});return e}async storeTestResult(t,e,r){await this.memory.set(`resilience:${t}:${e}`,r,{namespace:"chaos-resilience",persist:!0})}sleep(t){return new Promise(e=>setTimeout(e,t))}};se();var Yv={stateSize:10,actionSize:5,hiddenLayers:[64,64],learningRatePG:.01,gammaPG:.99,entropyCoeff:.01},xa=class extends oe{policy;pgConfig;actions=[];episodeLog=[];constructor(t={}){super("policy-gradient","policy-based"),this.pgConfig={...Yv,...t},this.initializeActions(),this.policy=new q({layerSizes:[this.pgConfig.stateSize,...this.pgConfig.hiddenLayers,this.pgConfig.actionSize],activations:Array(this.pgConfig.hiddenLayers.length).fill(new _).concat([new B]),learningRate:this.pgConfig.learningRatePG})}async predict(t){this.initialized||await this.initialize();let e=this.prepareState(t),r=this.policy.forward(e),i=he.forward(r),n=this.sampleAction(i),s=this.actions[n],a=i[n],o=Math.max(.3,Math.min(1,a+.4));return this.episodeLog.push({state:t,action:s,reward:0}),{action:s,confidence:o,reasoning:this.generateReasoning(t,s,a)}}async trainCore(t){let e=this.groupIntoEpisodes(t),r=0;for(let i of e){let n=this.calculateReturns(i);for(let s=0;s<i.length;s++){let{state:a,action:o}=i[s],c=n[s],l=this.prepareState(a),d=this.policy.forward(l),m=he.forward(d),h=this.actionToIndex(o),b=-Math.log(m[h]+1e-10)*c;r+=Math.abs(b);let w=new Float32Array(m.length);for(let C=0;C<w.length;C++)C===h?w[C]=-c*(1-m[C]):w[C]=c*m[C];this.policy.backward(w);for(let C of this.policy.layers)C.update(this.pgConfig.learningRatePG)}}return this.episodeLog=[],{episode:this.episodeCount,totalReward:this.totalReward,averageReward:this.rewardHistory.reduce((i,n)=>i+n,0)/this.rewardHistory.length,loss:r/t.length,explorationRate:this.config.explorationRate,trainingTimeMs:0,timestamp:new Date}}getAlgorithmInfo(){return{type:this.type,category:this.category,version:"2.0.0",description:"Neural Policy Gradient (REINFORCE) for Resource Allocation",capabilities:["Neural policy optimization","Monte Carlo return estimation","Entropy regularization"],hyperparameters:{stateSize:this.pgConfig.stateSize,actionSize:this.pgConfig.actionSize,learningRatePG:this.pgConfig.learningRatePG,gammaPG:this.pgConfig.gammaPG},stats:this.stats}}prepareState(t){let e=t.features.slice(0,this.pgConfig.stateSize);for(;e.length<this.pgConfig.stateSize;)e.push(0);let r=Math.max(...e.map(Math.abs));if(r>0)for(let i=0;i<e.length;i++)e[i]=e[i]/r;return new Float32Array(e)}initializeActions(){this.actions=[{type:"allocate",value:{agentType:"tester",count:1}},{type:"allocate",value:{agentType:"analyzer",count:1}},{type:"reallocate",value:{domain:"test-execution"}},{type:"scale-up",value:1},{type:"scale-down",value:1}],this.pgConfig.actionSize=this.actions.length,this.policy=new q({layerSizes:[this.pgConfig.stateSize,...this.pgConfig.hiddenLayers,this.pgConfig.actionSize],activations:Array(this.pgConfig.hiddenLayers.length).fill(new _).concat([new B]),learningRate:this.pgConfig.learningRatePG})}actionToIndex(t){let e=this.actionToKey(t);for(let r=0;r<this.actions.length;r++)if(this.actionToKey(this.actions[r])===e)return r;return 0}actionToKey(t){return`${t.type}:${JSON.stringify(t.value)}`}sampleAction(t){if(L()<this.config.explorationRate)return ue(0,this.actions.length);let e=L(),r=0;for(let i=0;i<t.length;i++)if(r+=t[i],e<=r)return i;return this.argmax(t)}argmax(t){let e=0,r=t[0];for(let i=1;i<t.length;i++)t[i]>r&&(r=t[i],e=i);return e}calculateReturns(t){let e=[],r=0;for(let i=t.length-1;i>=0;i--)r=t[i].reward+this.pgConfig.gammaPG*r,e.unshift(r);return e}groupIntoEpisodes(t){let e=[],r=[];for(let i of t)r.push(i),i.done&&(e.push(r),r=[]);return r.length>0&&e.push(r),e}generateReasoning(t,e,r){return`Neural Policy Gradient: ${e.type} (probability: ${r.toFixed(3)})`}async exportCustomData(){return{policy:this.policy.getParameters(),pgConfig:this.pgConfig}}async importCustomData(t){t.policy&&this.policy.setParameters(t.policy),t.pgConfig&&(this.pgConfig={...this.pgConfig,...t.pgConfig}),this.initialized=!0}async resetAlgorithm(){this.policy=new q({layerSizes:[this.pgConfig.stateSize,...this.pgConfig.hiddenLayers,this.pgConfig.actionSize],activations:Array(this.pgConfig.hiddenLayers.length).fill(new _).concat([new B]),learningRate:this.pgConfig.learningRatePG}),this.episodeLog=[]}};var Xv={maxConcurrentWorkflows:3,defaultTimeout:3e5,enableAutomatedExperiments:!1,publishEvents:!0,enablePolicyGradient:!0,enableQESONA:!0,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},ie=R.create("chaos-resilience"),Pa=class extends Q{constructor(e,r,i,n={},s){let a={...Xv,...n};super(e,"chaos-resilience",a,{verifyFindingTypes:["chaos-experiment","resilience-assessment","failure-injection"],...a.consensusConfig});this.memory=r;this.agentCoordinator=i;this.chaosGovernanceMixin=pu(this.domainName),this.chaosEngineer=new Dr({memory:r,llmRouter:s}),this.loadTester=new Ir(r),this.performanceProfiler=new Mr(r)}memory;agentCoordinator;chaosEngineer;loadTester;performanceProfiler;policyGradient;qesona;chaosGovernanceMixin;async onInitialize(){if(this.config.enablePolicyGradient)try{this.policyGradient=new xa({stateSize:10,actionSize:5,hiddenLayers:[64,64]}),ie.info("PolicyGradient algorithm created successfully")}catch(e){throw ie.error("Failed to create PolicyGradient:",e instanceof Error?e:void 0),new Error(`PolicyGradient creation failed: ${T(e)}`)}if(this.config.enableQESONA)try{this.qesona=await pe({domain:"chaos-resilience",loadOnInit:!0,autoSaveInterval:6e4,maxPatterns:5e3,minConfidence:.6}),ie.info("PersistentSONAEngine initialized successfully")}catch(e){ie.error("Failed to initialize PersistentSONAEngine:",e instanceof Error?e:void 0),ie.warn("Continuing without SONA pattern persistence"),this.qesona=void 0}this.subscribeToEvents(),await this.loadWorkflowState()}async onDispose(){await this.saveWorkflowState(),this.qesona&&(await this.qesona.close(),this.qesona=void 0),this.policyGradient=void 0}getActiveWorkflows(){return super.getActiveWorkflows()}async runChaosSuite(e){let r=v();try{if(this.startWorkflow(r,"chaos-suite"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&ie.warn("Topology degraded, using conservative chaos strategy"),this.minCutMixin.shouldPauseOperations())return p(new Error("Chaos suite paused: topology is in critical state"));if(!this.agentCoordinator.canSpawn())return p(new Error("Agent limit reached, cannot spawn chaos agents"));let i=await this.spawnChaosAgent(r,"coordinator");if(!i.success)return this.failWorkflow(r,i.error.message),p(i.error);this.addAgentToWorkflow(r,i.value);let n=[],s=[],a=0,o=0;for(let l=0;l<e.length;l++){let d=e[l];this.updateWorkflowProgress(r,Math.round((l+1)/e.length*100));let m=await this.chaosEngineer.runExperiment(d);if(m.success){if(n.push(m.value),m.value.hypothesisValidated)a++;else{o++;let h=this.generateRecommendationsFromExperiment(m.value);s.push(...h)}this.config.publishEvents&&await this.publishExperimentCompleted(m.value)}else o++,s.push({priority:"high",category:"experiment-failure",recommendation:`Failed to run experiment ${d}: ${m.error.message}`,effort:"moderate"})}await this.agentCoordinator.stop(i.value),this.completeWorkflow(r);let c={totalExperiments:e.length,passed:a,failed:o,results:n,recommendations:s};return await this.storeReport("chaos-suite",r,c),f(c)}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async runLoadTestSuite(e){let r=v();try{if(this.startWorkflow(r,"load-suite"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&ie.warn("Topology degraded, using conservative load test parameters"),this.minCutMixin.shouldPauseOperations())return p(new Error("Load test suite paused: topology is in critical state"));let i=await this.spawnLoadTestAgent(r,"orchestrator");if(!i.success)return this.failWorkflow(r,i.error.message),p(i.error);this.addAgentToWorkflow(r,i.value);let n=[],s=[],a=0,o=0;for(let l=0;l<e.length;l++){let d=e[l];this.updateWorkflowProgress(r,Math.round((l+1)/e.length*100));let m=await this.loadTester.runTest(d);if(m.success){n.push(m.value),m.value.status==="completed"?a++:o++;let h=this.detectBottlenecks(m.value);s.push(...h),this.config.publishEvents&&await this.publishLoadTestCompleted(m.value)}else o++}await this.agentCoordinator.stop(i.value),this.completeWorkflow(r);let c={totalTests:e.length,passed:a,failed:o,results:n,bottlenecks:s};return await this.storeReport("load-suite",r,c),f(c)}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async assessResilience(e){let r=v();try{if(this.startWorkflow(r,"assessment"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&ie.warn("Topology degraded, assessment may be limited"),this.minCutMixin.shouldPauseOperations())return p(new Error("Resilience assessment paused: topology is in critical state"));let i=new Map,n=[],s=[],a=[],o=await this.spawnAssessmentAgent(r);if(!o.success)return this.failWorkflow(r,o.error.message),p(o.error);this.addAgentToWorkflow(r,o.value);for(let d=0;d<e.length;d++){let m=e[d];this.updateWorkflowProgress(r,Math.round((d+1)/e.length*100));let h=await this.performanceProfiler.testRecovery(m,"latency",5e3),g=await this.performanceProfiler.testCircuitBreaker(m),b=await this.performanceProfiler.testRateLimiting(m,100),w=0;if(h.success&&h.value.passed)w+=33.3,n.push(`${m}: Fast recovery (${h.value.recoveryTime}ms)`);else{let C=h.success?h.value.recoveryTime:"unknown";s.push({service:m,type:"recovery",description:"Slow or failed recovery after fault",risk:un.create(.7)}),a.push({priority:"high",category:"recovery",recommendation:`Improve ${m} recovery time - currently ${C}ms`,effort:"moderate"})}g.success&&g.value.passed?(w+=33.3,n.push(`${m}: Circuit breaker functioning correctly`)):(s.push({service:m,type:"circuit-breaker",description:"Circuit breaker not functioning as expected",risk:un.create(.6)}),a.push({priority:"medium",category:"circuit-breaker",recommendation:`Review ${m} circuit breaker configuration`,effort:"minor"})),b.success&&b.value.passed?(w+=33.4,n.push(`${m}: Rate limiting effective`)):(s.push({service:m,type:"rate-limiting",description:"Rate limiting not properly configured",risk:un.create(.5)}),a.push({priority:"medium",category:"rate-limiting",recommendation:`Configure rate limiting for ${m}`,effort:"minor"})),i.set(m,w)}let c=e.length>0?Array.from(i.values()).reduce((d,m)=>d+m,0)/e.length:0;await this.agentCoordinator.stop(o.value),this.completeWorkflow(r);let l={overallScore:c,serviceScores:i,strengths:n,weaknesses:s,recommendations:a};return await this.storeReport("assessment",r,l),f(l)}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async generateExperiments(e){let r=v();try{this.startWorkflow(r,"experiment-generation");let i=[];for(let n of e.services){let s=this.generateServiceExperiments(n,e.dependencies);i.push(...s)}for(let n of e.criticalPaths){let s=this.generateCriticalPathExperiment(n,e);i.push(s)}for(let n of i)await this.chaosEngineer.createExperiment(n);return this.completeWorkflow(r),f(i)}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async runStrategicChaosSuite(e,r){let i=v();try{if(this.startWorkflow(i,"chaos-suite"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&ie.warn("Topology degraded, adjusting strategic chaos parameters"),this.minCutMixin.shouldPauseOperations())return p(new Error("Strategic chaos suite paused: topology is in critical state"));if(!this.agentCoordinator.canSpawn())return p(new Error("Agent limit reached, cannot spawn chaos agents"));let n=await this.selectChaosStrategy(e,r);if(!n.success)return this.failWorkflow(i,n.error.message),p(n.error);let s=n.value.selectedExperiments;if(ie.info(`[chaos-resilience] Using ${n.value.strategy} strategy with ${s.length} experiments (confidence: ${n.value.confidence.toFixed(2)})`),s.length===0)return this.completeWorkflow(i),f({totalExperiments:0,passed:0,failed:0,results:[],recommendations:[{priority:"low",category:"strategy",recommendation:"No experiments selected - consider adjusting strategy context",effort:"trivial"}]});let a=await this.spawnChaosAgent(i,"coordinator");if(!a.success)return this.failWorkflow(i,a.error.message),p(a.error);this.addAgentToWorkflow(i,a.value);let o=[],c=[],l=0,d=0;for(let h of s)await this.chaosEngineer.createExperiment(h);for(let h=0;h<s.length;h++){let g=s[h];this.updateWorkflowProgress(i,Math.round((h+1)/s.length*100));let b=await this.chaosEngineer.runExperiment(g.id);if(b.success){if(o.push(b.value),b.value.hypothesisValidated)l++;else{d++;let C=this.generateRecommendationsFromExperiment(b.value);c.push(...C)}let w=b.value.hypothesisValidated?.8:.2;await this.storeResiliencePattern(g,b.value,w),this.config.publishEvents&&await this.publishExperimentCompleted(b.value)}else d++,c.push({priority:"high",category:"experiment-failure",recommendation:`Failed to run experiment ${g.name}: ${b.error.message}`,effort:"moderate"})}await this.agentCoordinator.stop(a.value),this.completeWorkflow(i);let m={totalExperiments:s.length,passed:l,failed:d,results:o,recommendations:c};return await this.storeReport("strategic-chaos-suite",i,m),f(m)}catch(n){return this.failWorkflow(i,String(n)),p(y(n))}}async getResilienceDashboard(){try{let e=await this.memory.search("chaos:results:*",10),r=await this.memory.search("loadtest:results:*",10),i,n,s=0,a=0,o=0,c=0,l=0;for(let b of e){let w=await this.memory.get(b);w&&((!i||w.startTime>i)&&(i=w.startTime),s+=w.incidents.filter(C=>!C.resolved).length)}for(let b of r){let w=await this.memory.get(b);if(w&&w.timeline.length>0){let C=w.timeline[0].timestamp;(!n||C>n)&&(n=C),l++,w.status==="failed"&&c++}}let d=o>0?a/o:0,m=l>0?c/l*100:0,h="healthy";return s>5||m>25?h="unhealthy":(s>0||m>10)&&(h="degraded"),f({overallHealth:h,lastExperimentDate:i,lastLoadTestDate:n,activeIncidents:s,uptime:99.9,mttr:d,changeFailureRate:m})}catch(e){return p(y(e))}}async spawnChaosAgent(e,r){let i={name:`chaos-${r}-${e.slice(0,8)}`,domain:"chaos-resilience",type:"specialist",capabilities:["chaos-engineering","fault-injection",r],config:{workflowId:e}};return this.agentCoordinator.spawn(i)}async spawnLoadTestAgent(e,r){let i={name:`loadtest-${r}-${e.slice(0,8)}`,domain:"chaos-resilience",type:"specialist",capabilities:["load-testing","performance",r],config:{workflowId:e}};return this.agentCoordinator.spawn(i)}async spawnAssessmentAgent(e){let r={name:`assessment-${e.slice(0,8)}`,domain:"chaos-resilience",type:"analyzer",capabilities:["resilience-assessment","analysis"],config:{workflowId:e}};return this.agentCoordinator.spawn(r)}async publishExperimentCompleted(e){let r={id:v(),type:"chaos-resilience.ExperimentCompleted",timestamp:new Date,source:"chaos-resilience",payload:{experimentId:e.experimentId,status:e.status,hypothesisValidated:e.hypothesisValidated,incidentCount:e.incidents.length}};await this.eventBus.publish(r)}async publishLoadTestCompleted(e){let r={id:v(),type:"chaos-resilience.LoadTestCompleted",timestamp:new Date,source:"chaos-resilience",payload:{testId:e.testId,status:e.status,summary:e.summary,assertionsPassed:e.assertionResults.filter(i=>i.passed).length,assertionsFailed:e.assertionResults.filter(i=>!i.passed).length}};await this.eventBus.publish(r)}generateRecommendationsFromExperiment(e){let r=[];e.hypothesisValidated||r.push({priority:"high",category:"hypothesis-failure",recommendation:`Experiment ${e.experimentId} hypothesis was not validated - review system behavior under fault conditions`,effort:"moderate"}),e.steadyStateVerified||r.push({priority:"critical",category:"steady-state",recommendation:"System did not maintain steady state - investigate stability issues",effort:"major"});for(let i of e.incidents)(i.severity==="critical"||i.severity==="high")&&r.push({priority:i.severity,category:"incident",recommendation:`Address ${i.type}: ${i.message}`,effort:"moderate"});return r}detectBottlenecks(e){let r=[];return e.summary.p95ResponseTime>1e3&&r.push({location:"api",type:"network",description:`P95 response time is ${e.summary.p95ResponseTime}ms (>1000ms)`,impact:e.summary.p95ResponseTime>2e3?"high":"medium",recommendation:"Investigate API response time, consider caching or query optimization"}),e.summary.errorRate>5&&r.push({location:"service",type:"cpu",description:`Error rate is ${e.summary.errorRate.toFixed(2)}% (>5%)`,impact:e.summary.errorRate>10?"high":"medium",recommendation:"Investigate error causes, scale resources if under load"}),e.summary.requestsPerSecond<10&&r.push({location:"backend",type:"io",description:`Low throughput: ${e.summary.requestsPerSecond.toFixed(2)} RPS`,impact:"medium",recommendation:"Review I/O operations, database queries, and connection pooling"}),r}generateServiceExperiments(e,r){let i=[];i.push(this.createExperiment(`${e.name}-latency`,`Test ${e.name} behavior under latency`,"latency",e.name)),i.push(this.createExperiment(`${e.name}-error`,`Test ${e.name} error handling`,"error",e.name)),i.push(this.createExperiment(`${e.name}-cpu-stress`,`Test ${e.name} under CPU stress`,"cpu-stress",e.name));let n=r.filter(s=>s.from===e.name);for(let s of n)s.criticality==="critical"&&i.push(this.createExperiment(`${e.name}-${s.to}-failure`,`Test ${e.name} when ${s.to} fails`,"error",s.to));return i}generateCriticalPathExperiment(e,r){let i=e.join("-");return{id:v(),name:`critical-path-${i}`,description:`Test critical path: ${e.join(" -> ")}`,hypothesis:{statement:"System should handle partial path failure gracefully",metrics:[{metric:"error_rate",operator:"lt",value:10},{metric:"response_time_ms",operator:"lt",value:2e3}],tolerances:[{metric:"error_rate",maxDeviation:5,unit:"percent"}]},steadyState:{description:"All services in path are healthy",probes:e.map(n=>({name:`${n}-health`,type:"http",target:`http://${n}/health`,expected:{status:200},timeout:5e3}))},faults:e.slice(0,-1).map(n=>({id:v(),type:"latency",target:{type:"service",selector:n},parameters:{latencyMs:500},duration:3e4})),blastRadius:{scope:"subset",percentage:50,excludeProduction:!0},rollbackPlan:{automatic:!0,triggerConditions:[{type:"error-rate",condition:"error_rate > 20"},{type:"timeout",condition:"duration > 60000"}],steps:[{order:1,action:"Remove all faults",timeout:5e3},{order:2,action:"Verify service health"}]}}}createExperiment(e,r,i,n){return{id:v(),name:e,description:r,hypothesis:{statement:`${n} should recover within 5 seconds from ${i}`,metrics:[{metric:"response_time_ms",operator:"lt",value:1e3},{metric:"error_rate",operator:"lt",value:5}],tolerances:[{metric:"response_time_ms",maxDeviation:50,unit:"percent"}]},steadyState:{description:`${n} is healthy and responsive`,probes:[{name:`${n}-health`,type:"http",target:`http://${n}/health`,expected:{status:200},timeout:5e3}]},faults:[{id:v(),type:i,target:{type:"service",selector:n},parameters:this.getDefaultFaultParameters(i),duration:3e4}],blastRadius:{scope:"single",excludeProduction:!0},rollbackPlan:{automatic:!0,triggerConditions:[{type:"error-rate",condition:"error_rate > 50"}],steps:[{order:1,action:`Remove ${i} fault`},{order:2,action:"Verify recovery"}]}}}getDefaultFaultParameters(e){return{latency:{latencyMs:500},error:{errorCode:500},timeout:{timeoutMs:3e4},"packet-loss":{packetLossPercent:10},"cpu-stress":{cpuPercent:80},"memory-stress":{memoryBytes:268435456},"disk-stress":{},"network-partition":{},"dns-failure":{},"process-kill":{}}[e]||{}}async storeReport(e,r,i){await this.memory.set(`chaos-resilience:reports:${e}:${r}`,i,{namespace:"chaos-resilience",persist:!0})}async selectChaosStrategy(e,r){if(!this.policyGradient||!this.config.enablePolicyGradient)return f({strategy:"default",selectedExperiments:this.getDefaultExperiments(e.slice(0,3)),confidence:1,reasoning:"Default strategy (PolicyGradient disabled)"});if(e.length===0)return f({strategy:"empty",selectedExperiments:[],confidence:1,reasoning:"No services provided"});try{let i={id:`chaos-strategy-${Date.now()}`,features:[r.riskTolerance,r.availableCapacity/100,e.length/50,e.filter(l=>!l.hasFailover).length/Math.max(1,e.length),e.filter(l=>l.type==="database").length/Math.max(1,e.length),r.environment==="production"?0:1,r.environment==="staging"?1:0,e.filter(l=>l.type==="cache").length/Math.max(1,e.length),e.filter(l=>l.type==="queue").length/Math.max(1,e.length),e.reduce((l,d)=>l+d.replicas,0)/Math.max(1,e.length*5)]},n=await this.policyGradient.predict(i),s=[],a="default";switch(n.action.type){case"allocate":{let l=typeof n.action.value=="object"?n.action.value:null;if(l&&"agentType"in l&&l.agentType==="tester"){let d=e.filter(m=>!m.hasFailover||m.type==="database").slice(0,3);s=this.generateExperimentsForServices(d,["latency","error"]),a="allocate-critical"}break}case"reallocate":{let l=typeof n.action.value=="object"?n.action.value:null;l&&"domain"in l&&l.domain==="test-execution"&&(s=this.generateExperimentsForServices(e.slice(0,5),["cpu-stress","memory-stress"]),a="reallocate-resource-stress");break}case"scale-up":s=this.generateExperimentsForServices(e,["latency","error","timeout"]),a="scale-up-comprehensive";break;case"scale-down":s=this.generateExperimentsForServices(e.slice(0,2),["latency"]),a="scale-down-minimal";break;default:s=this.getDefaultExperiments(e.slice(0,3)),a="default";break}let o=await this.calculateStrategyReward(s,r),c=n.action;return await this.policyGradient.train({state:i,action:c,reward:o,nextState:i,done:!0}),ie.info(`[chaos-resilience] PolicyGradient selected ${a} strategy for ${e.length} services (confidence: ${n.confidence.toFixed(2)})`),f({strategy:a,selectedExperiments:s,confidence:n.confidence,reasoning:n.reasoning||`PolicyGradient selected: ${a}`})}catch(i){return ie.error("PolicyGradient strategy selection failed:",i instanceof Error?i:void 0),f({strategy:"fallback",selectedExperiments:this.getDefaultExperiments(e.slice(0,3)),confidence:.5,reasoning:"Fallback to default (PolicyGradient error)"})}}generateExperimentsForServices(e,r){let i=[];for(let n of e)for(let s of r)i.push(this.createExperiment(`${n.name}-${s}-${Date.now()}`,`Test ${n.name} with ${s} fault`,s,n.name));return i}getDefaultExperiments(e){return this.generateExperimentsForServices(e,["latency","error"])}async calculateStrategyReward(e,r){let i=.5,n=e.length;(r.riskTolerance>.7&&n>5||r.riskTolerance<.3&&n<=3)&&(i+=.2),(r.availableCapacity>70&&n>5||r.availableCapacity<30&&n<=3)&&(i+=.1);let s=new Set(e.map(a=>a.faults[0]?.type));return i+=Math.min(.1,s.size/5),Math.max(0,Math.min(1,i))}async storeResiliencePattern(e,r,i){if(!(!this.qesona||!this.config.enableQESONA))try{let n={id:`chaos-${e.id}`,features:[e.faults.length/10,e.faults[0]?.duration?e.faults[0].duration/6e4:0,e.steadyState.probes.length/20,e.blastRadius.excludeProduction?1:0,(e.blastRadius.percentage??0)/100,r.hypothesisValidated?1:0,r.steadyStateVerified?1:0,r.incidents.length/10,r.incidents.filter(a=>a.severity==="critical").length/5,i]},s={type:r.hypothesisValidated?"validate":"reject",value:i};this.qesona.createPattern(n,s,{reward:r.hypothesisValidated?i:-i,success:r.hypothesisValidated,quality:i},"defect-prediction","chaos-resilience",{experimentId:e.id,experimentName:e.name,faultType:e.faults[0]?.type,hypothesisValidated:r.hypothesisValidated}),ie.info(`Stored resilience pattern for ${e.id} (validated: ${r.hypothesisValidated}, quality: ${i.toFixed(2)})`)}catch(n){ie.error("Failed to store resilience pattern:",n instanceof Error?n:void 0)}}async adaptStrategies(e,r){if(!this.qesona||!this.config.enableQESONA)return{shouldRunChaos:r.environment!=="production",recommendedFaults:["latency","error"],confidence:.5};try{let i={id:`chaos-adapt-${e.name}-${Date.now()}`,features:[e.hasFailover?0:1,r.riskTolerance,e.type==="api"?1:0,e.type==="database"?1:0,e.type==="cache"?1:0,r.environment==="production"?1:0,r.environment==="staging"?1:0,e.replicas/10,e.type==="worker"?1:0,e.type==="queue"?1:0]},n=await this.qesona.adaptPattern(i,"defect-prediction","chaos-resilience");if(n.success&&n.pattern){let s=n.pattern.outcome.success,a=this.getRecommendedFaults(n.pattern.action.type);return ie.info(`[chaos-resilience] QESONA adapted strategy for ${e.name}: shouldRun=${s}, faults=${a.join(",")}, confidence=${n.similarity.toFixed(2)}`),{shouldRunChaos:s,recommendedFaults:a,confidence:n.similarity}}return{shouldRunChaos:r.environment!=="production",recommendedFaults:["latency","error"],confidence:.5}}catch(i){return ie.error("QESONA strategy adaptation failed:",i instanceof Error?i:void 0),{shouldRunChaos:r.environment!=="production",recommendedFaults:["latency","error"],confidence:.5}}}getRecommendedFaults(e){switch(e){case"validate":return["latency","error","timeout"];case"reject":return["latency"];case"allocate":return["latency","cpu-stress"];case"scale-up":return["latency","error","timeout","packet-loss"];case"scale-down":return["latency"];default:return["latency","error"]}}subscribeToEvents(){this.eventBus.subscribe("quality-assessment.DeploymentApproved",this.handleDeploymentApproved.bind(this)),this.eventBus.subscribe("quality-assessment.QualityGateEvaluated",this.handleQualityGateEvaluated.bind(this))}async handleDeploymentApproved(e){if(!this.config.enableAutomatedExperiments)return;let r=e.payload;r.services&&await this.memory.set(`chaos-resilience:pending-assessment:${e.id}`,r.services,{namespace:"chaos-resilience",ttl:3600})}async handleQualityGateEvaluated(e){let r=e.payload;r.passed||await this.memory.set(`chaos-resilience:quality-gate-failures:${e.id}`,r,{namespace:"chaos-resilience",ttl:86400})}async loadWorkflowState(){let e=await this.memory.get("chaos-resilience:coordinator:workflows");if(e)for(let r of e)r.status==="running"&&(r.status="failed",r.error="Coordinator restarted",r.completedAt=new Date),this.workflows.set(r.id,r)}async saveWorkflowState(){let e=Array.from(this.workflows.values());await this.memory.set("chaos-resilience:coordinator:workflows",e,{namespace:"chaos-resilience",persist:!0})}async verifyChaosExperiment(e,r){let i=V({id:v(),type:"chaos-experiment",confidence:r,description:`Verify chaos experiment safety: ${e.name} (${e.faultType}) on ${e.target}`,payload:e,detectedBy:"chaos-resilience-coordinator",severity:e.blastRadius==="full"?"critical":r>.9?"high":"medium"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(ie.info(`Chaos experiment '${e.name}' verified safe by consensus`),!0):(ie.warn(`Chaos experiment '${e.name}' NOT verified safe: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}async verifyResilienceAssessment(e,r){let i=V({id:v(),type:"resilience-assessment",confidence:r,description:`Verify resilience assessment for ${e.service}: score ${e.overallScore}, ${e.weaknessCount} weaknesses`,payload:e,detectedBy:"chaos-resilience-coordinator",severity:e.overallScore<50?"critical":e.overallScore<70?"high":"medium"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(ie.info(`Resilience assessment for '${e.service}' verified by consensus`),!0):(ie.warn(`Resilience assessment for '${e.service}' NOT verified`),!1)}return!0}async verifyFailureInjection(e,r){let i=V({id:v(),type:"failure-injection",confidence:r,description:`Verify failure injection: ${e.faultType} on ${e.target} for ${e.duration}ms`,payload:e,detectedBy:"chaos-resilience-coordinator",severity:"critical"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(ie.info(`Failure injection '${e.faultType}' on '${e.target}' verified safe by consensus`),!0):(ie.warn(`Failure injection '${e.faultType}' NOT verified safe: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}};A();var cl=class extends j{constructor(e,r,i,n={},s){super(e,r);this.agentCoordinator=i;this.llmRouter=s;this.pluginConfig=n}agentCoordinator;llmRouter;coordinator=null;chaosEngineer=null;loadTester=null;performanceProfiler=null;pluginConfig;get name(){return"chaos-resilience"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{runChaosSuite:this.runChaosSuite.bind(this),runLoadTestSuite:this.runLoadTestSuite.bind(this),assessResilience:this.assessResilience.bind(this),generateExperiments:this.generateExperiments.bind(this),getResilienceDashboard:this.getResilienceDashboard.bind(this),createExperiment:this.createExperiment.bind(this),runExperiment:this.runExperiment.bind(this),abortExperiment:this.abortExperiment.bind(this),verifySteadyState:this.verifySteadyState.bind(this),injectFault:this.injectFault.bind(this),removeFault:this.removeFault.bind(this),createTest:this.createTest.bind(this),runTest:this.runTest.bind(this),runLoadTest:this.runTest.bind(this),stopTest:this.stopTest.bind(this),getRealtimeMetrics:this.getRealtimeMetrics.bind(this),generateFromTraffic:this.generateFromTraffic.bind(this),getExperimentHistory:this.getExperimentHistory.bind(this),testRecovery:this.testRecovery.bind(this),testFailover:this.testFailover.bind(this),testCircuitBreaker:this.testCircuitBreaker.bind(this),testRateLimiting:this.testRateLimiting.bind(this),selectChaosStrategy:this.coordinator.selectChaosStrategy.bind(this.coordinator),runStrategicChaosSuite:this.coordinator.runStrategicChaosSuite.bind(this.coordinator),getCoordinator:()=>this.coordinator,getChaosEngineer:()=>this.chaosEngineer,getChaosEngine:()=>this.chaosEngineer,getLoadTester:()=>this.loadTester,getPerformanceProfiler:()=>this.performanceProfiler,getResilienceAssessor:()=>this.performanceProfiler}}getTaskHandlers(){return new Map([["run-experiment",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.experimentId;return r?this.coordinator.runChaosSuite([r]):p(new Error("Invalid run-experiment payload: missing experimentId"))}],["run-load-test",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.testId;return r?this.coordinator.runLoadTestSuite([r]):p(new Error("Invalid run-load-test payload: missing testId"))}],["assess-resilience",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.services;return!r||r.length===0?p(new Error("Invalid assess-resilience payload: missing services")):this.coordinator.assessResilience(r)}],["inject-fault",async e=>{if(!this.chaosEngineer)return p(new Error("Chaos engineer not initialized"));let r=e.faultType,i=e.target;if(!r||!i)return p(new Error("Invalid inject-fault payload: missing faultType or target"));let n={id:`fault-${Date.now()}`,type:r,target:{type:"service",selector:i},parameters:e.parameters??{},duration:e.duration??3e4,probability:e.probability};return this.chaosEngineer.injectFault(n)}]])}async onInitialize(){this.chaosEngineer=new Dr({memory:this.memory,llmRouter:this.llmRouter},this.pluginConfig.chaosEngineer),this.loadTester=new Ir(this.memory,this.pluginConfig.loadTester),this.performanceProfiler=new Mr(this.memory,this.pluginConfig.performanceProfiler),this.coordinator=new Pa(this.eventBus,this.memory,this.agentCoordinator,this.pluginConfig.coordinator,this.llmRouter),await this.coordinator.initialize(),this.updateHealth({status:"idle",agents:{total:0,active:0,idle:0,failed:0},lastActivity:new Date,errors:[]})}async onDispose(){this.coordinator&&await this.coordinator.dispose(),this.coordinator=null,this.chaosEngineer=null,this.loadTester=null,this.performanceProfiler=null}subscribeToEvents(){this.eventBus.subscribe("quality-assessment.DeploymentApproved",this.handleDeploymentApproved.bind(this)),this.eventBus.subscribe("test-execution.TestRunCompleted",this.handleTestRunCompleted.bind(this)),this.eventBus.subscribe("security-compliance.VulnerabilityDetected",this.handleVulnerabilityDetected.bind(this))}async onEvent(e){switch(this.updateHealth({lastActivity:new Date}),e.type){case"quality-assessment.DeploymentApproved":await this.handleDeploymentApproved(e);break;case"test-execution.TestRunCompleted":await this.handleTestRunCompleted(e);break;case"security-compliance.VulnerabilityDetected":await this.handleVulnerabilityDetected(e);break;case"quality-assessment.QualityGateEvaluated":await this.handleQualityGateEvaluated(e);break;default:break}}async runChaosSuite(e){this.ensureInitialized();try{let r=await this.coordinator.runChaosSuite(e);return r.success?this.trackSuccessfulOperation("chaos-suite"):this.trackFailedOperation(r.error),r}catch(r){return this.handleError(r)}}async runLoadTestSuite(e){this.ensureInitialized();try{let r=await this.coordinator.runLoadTestSuite(e);return r.success?this.trackSuccessfulOperation("load-suite"):this.trackFailedOperation(r.error),r}catch(r){return this.handleError(r)}}async assessResilience(e){this.ensureInitialized();try{return await this.coordinator.assessResilience(e)}catch(r){return this.handleError(r)}}async generateExperiments(e){this.ensureInitialized();try{return await this.coordinator.generateExperiments(e)}catch(r){return this.handleError(r)}}async getResilienceDashboard(){this.ensureInitialized();try{return await this.coordinator.getResilienceDashboard()}catch(e){return this.handleError(e)}}async createExperiment(e){this.ensureInitialized();try{return await this.chaosEngineer.createExperiment(e)}catch(r){return this.handleError(r)}}async runExperiment(e){this.ensureInitialized();try{let r=await this.chaosEngineer.runExperiment(e);return r.success&&await this.publishExperimentEvent(r.value),r}catch(r){return this.handleError(r)}}async abortExperiment(e,r){this.ensureInitialized();try{return await this.chaosEngineer.abortExperiment(e,r)}catch(i){return this.handleError(i)}}async verifySteadyState(e){this.ensureInitialized();try{return await this.chaosEngineer.verifySteadyState(e)}catch(r){return this.handleError(r)}}async injectFault(e){this.ensureInitialized();try{return await this.chaosEngineer.injectFault(e)}catch(r){return this.handleError(r)}}async removeFault(e){this.ensureInitialized();try{return await this.chaosEngineer.removeFault(e)}catch(r){return this.handleError(r)}}async getExperimentHistory(){this.ensureInitialized();try{return{success:!0,value:await this.memory.get("chaos-resilience:experiment-history")??[]}}catch(e){return this.handleError(e)}}async createTest(e){this.ensureInitialized();try{return await this.loadTester.createTest(e)}catch(r){return this.handleError(r)}}async runTest(e){this.ensureInitialized();try{let r=await this.loadTester.runTest(e);return r.success&&await this.publishLoadTestEvent(r.value),r}catch(r){return this.handleError(r)}}async stopTest(e){this.ensureInitialized();try{return await this.loadTester.stopTest(e)}catch(r){return this.handleError(r)}}async getRealtimeMetrics(e){this.ensureInitialized();try{return await this.loadTester.getRealtimeMetrics(e)}catch(r){return this.handleError(r)}}async generateFromTraffic(e,r){this.ensureInitialized();try{return await this.loadTester.generateFromTraffic(e,r)}catch(i){return this.handleError(i)}}async testRecovery(e,r,i){this.ensureInitialized();try{return await this.performanceProfiler.testRecovery(e,r,i)}catch(n){return this.handleError(n)}}async testFailover(e,r){this.ensureInitialized();try{return await this.performanceProfiler.testFailover(e,r)}catch(i){return this.handleError(i)}}async testCircuitBreaker(e,r){this.ensureInitialized();try{return await this.performanceProfiler.testCircuitBreaker(e,r)}catch(i){return this.handleError(i)}}async testRateLimiting(e,r){this.ensureInitialized();try{return await this.performanceProfiler.testRateLimiting(e,r)}catch(i){return this.handleError(i)}}async handleDeploymentApproved(e){let r=e.payload;r.services&&r.services.length>0&&await this.memory.set(`chaos-resilience:pending-assessment:${e.id}`,{services:r.services,triggeredAt:new Date,source:"deployment-approved"},{namespace:"chaos-resilience",ttl:3600})}async handleTestRunCompleted(e){let r=e.payload;await this.memory.set(`chaos-resilience:test-baseline:${r.runId}`,{duration:r.duration,successRate:r.passed/(r.passed+r.failed),timestamp:new Date},{namespace:"chaos-resilience",ttl:86400})}async handleVulnerabilityDetected(e){let r=e.payload;(r.severity==="critical"||r.severity==="high")&&await this.memory.set(`chaos-resilience:security-tests:${r.vulnId}`,{vulnerabilityId:r.vulnId,severity:r.severity,file:r.file,triggeredAt:new Date},{namespace:"chaos-resilience",ttl:86400})}async handleQualityGateEvaluated(e){let r=e.payload;r.checks?.some(n=>n.name==="resilience")&&await this.memory.set(`chaos-resilience:gate-context:${r.gateId}`,{gateId:r.gateId,passed:r.passed,checks:r.checks,timestamp:Date.now()},{namespace:"chaos-resilience",ttl:3600})}async publishExperimentEvent(e){await this.publishEvent("chaos-resilience.ExperimentCompleted",{experimentId:e.experimentId,status:e.status,hypothesisValidated:e.hypothesisValidated,steadyStateVerified:e.steadyStateVerified,faultCount:e.faultResults.length,incidentCount:e.incidents.length,duration:e.endTime?e.endTime.getTime()-e.startTime.getTime():0})}async publishLoadTestEvent(e){await this.publishEvent("chaos-resilience.LoadTestCompleted",{testId:e.testId,status:e.status,duration:e.duration,totalRequests:e.summary.totalRequests,successRate:e.summary.totalRequests>0?e.summary.successfulRequests/e.summary.totalRequests*100:0,p95ResponseTime:e.summary.p95ResponseTime,errorRate:e.summary.errorRate,assertionsPassed:e.assertionResults.filter(r=>r.passed).length,assertionsFailed:e.assertionResults.filter(r=>!r.passed).length})}ensureInitialized(){if(!this._initialized)throw new Error("ChaosResiliencePlugin is not initialized");if(!this.coordinator||!this.chaosEngineer||!this.loadTester||!this.performanceProfiler)throw new Error("ChaosResiliencePlugin services are not available")}handleError(e){let r=y(e),i=this.getHealth();return this.updateHealth({errors:[...i.errors.slice(-9),r.message],status:i.errors.length>=5?"degraded":i.status}),{success:!1,error:r}}trackSuccessfulOperation(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,total:r.agents.total+1,idle:r.agents.idle+1},lastActivity:new Date})}trackFailedOperation(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,failed:r.agents.failed+1},errors:[...r.errors.slice(-9),e.message]})}};function Lm(u,t,e,r,i){return new cl(u,t,e,r,i)}M();A();M();A();var Zv={minExperiencesForPattern:5,patternConfidenceThreshold:.7,maxPatternsPerDomain:100,anomalyDeviationThreshold:2,clusterSimilarityThreshold:.8,enableLLMSynthesis:!0,llmModelTier:2,llmMaxTokens:2048},$m=R.create("learning-optimization/learning-coordinator"),be={namespace:"learning-optimization"},jt=class{config;memory;llmRouter;flashAttention=null;constructor(t,e={}){this.memory=t.memory,this.llmRouter=t.llmRouter,this.config={...Zv,...e}}async initializeFlashAttention(t){return this.flashAttention=await Me("pattern-adaptation",t),$m.info("FlashAttention initialized for pattern adaptation"),this.flashAttention}injectFlashAttention(t){this.flashAttention=t}isFlashAttentionAvailable(){return this.flashAttention!==null}getFlashAttentionMetrics(){return this.flashAttention?this.flashAttention.getMetrics():[]}async computeSimilarityWithFlashAttention(t,e){if(!this.flashAttention)throw new Error("[LearningCoordinatorService] FlashAttention not initialized. Call initializeFlashAttention() first.");let r=Math.min(t.length,e.length),i=new Float32Array(r),n=new Float32Array(r),s=new Float32Array(r);for(let c=0;c<r;c++)i[c]=t[c],n[c]=e[c],s[c]=1;let a=await this.flashAttention.computeFlashAttention(i,n,s,1,r),o=Math.abs(a[0]);return Math.min(1,o)}async batchComputeSimilarities(t,e,r=5){if(!this.flashAttention)throw new Error("[LearningCoordinatorService] FlashAttention not initialized. Call initializeFlashAttention() first.");let i=new Float32Array(t),n=e.map(s=>new Float32Array(s));return this.flashAttention.computeTestSimilarity(i,n,r)}disposeFlashAttention(){this.flashAttention&&(this.flashAttention.dispose(),this.flashAttention=null)}isLLMSynthesisAvailable(){return this.config.enableLLMSynthesis&&this.llmRouter!==void 0}getModelForTier(t){let e={1:"claude-haiku-4-5",2:"claude-sonnet-4-6",3:"claude-sonnet-4-6",4:"claude-opus-4-7"};return e[t]||e[2]}async synthesizePatternsWithLLM(t){if(!this.isLLMSynthesisAvailable())return null;try{let e=t.slice(0,10).map(i=>`- ${i.name}: ${i.type} (confidence: ${i.confidence.toFixed(2)})`).join(`
|
|
3018
3018
|
`);return(await this.llmRouter.chat({model:this.getModelForTier(this.config.llmModelTier),messages:[{role:"user",content:`Analyze these learned QE patterns and synthesize insights:
|
|
3019
3019
|
${e}
|
|
3020
3020
|
|
|
@@ -3024,4 +3024,4 @@ Provide:
|
|
|
3024
3024
|
3. Recommendations for pattern application`}],maxTokens:this.config.llmMaxTokens})).content}catch{return $m.warn("LLM synthesis failed:"),null}}async learnPattern(t){try{if(t.length<this.config.minExperiencesForPattern)return p(new Error(`Need at least ${this.config.minExperiencesForPattern} experiences to learn a pattern`));let e=this.extractCommonActions(t),r=this.calculateSuccessRate(t);if(r<this.config.patternConfidenceThreshold)return p(new Error(`Success rate ${r} below threshold ${this.config.patternConfidenceThreshold}`));let i=this.inferPatternType(t),n=t[0].domain,s=this.generatePatternTemplate(t,e),a=this.extractPatternContext(t),o={id:v(),type:i,domain:n,name:`${i}-${n}-${Date.now()}`,description:`Learned pattern from ${t.length} experiences with ${r*100}% success rate`,confidence:r,usageCount:0,successRate:r,context:a,template:s,createdAt:new Date,lastUsedAt:new Date};return await this.storePattern(o),await this.recordPatternCreation(o,t),f(o)}catch(e){return p(y(e))}}async findMatchingPatterns(t,e=10){try{let r=[],i=await this.memory.search("learning:pattern:*",100,be);for(let n of i){let s=await this.memory.get(n,be);s&&this.matchesContext(s,t)&&r.push(s)}return r.sort((n,s)=>{let a=n.confidence*.6+n.successRate*.4;return s.confidence*.6+s.successRate*.4-a}),f(r.slice(0,e))}catch(r){return p(y(r))}}async applyPattern(t,e){try{let r=t.template.content;for(let i of t.template.variables){let n=e[i.name]??i.defaultValue;if(i.required&&n===void 0)return p(new Error(`Required variable ${i.name} not provided`));r=r.replace(new RegExp(`\\{\\{${i.name}\\}\\}`,"g"),String(n??""))}return await this.updatePatternUsage(t.id),f(r)}catch(r){return p(y(r))}}async updatePatternFeedback(t,e){try{let r=`learning:pattern:${t}`,i=await this.memory.get(r,be);if(!i)return p(new Error(`Pattern ${t} not found`));let n=.1,s=n*(e?1:0)+(1-n)*i.successRate,a=Math.min(i.usageCount/100,1),o=s*.7+a*.3,c={...i,successRate:s,confidence:o,usageCount:i.usageCount+1,lastUsedAt:new Date};return await this.memory.set(r,c,{namespace:"learning-optimization",persist:!0}),f(void 0)}catch(r){return p(y(r))}}async consolidatePatterns(t){try{if(t.length<2)return p(new Error("Need at least 2 patterns to consolidate"));let e=[];for(let s of t){let a=await this.memory.get(`learning:pattern:${s}`,be);a&&e.push(a)}if(e.length<2)return p(new Error("Not enough valid patterns found"));let r=e.reduce((s,a)=>a.successRate>s.successRate?a:s),i={language:r.context.language,framework:r.context.framework,testType:r.context.testType,codeContext:r.context.codeContext,tags:[...new Set(e.flatMap(s=>s.context.tags))]},n={id:v(),type:r.type,domain:r.domain,name:`consolidated-${r.name}`,description:`Consolidated from ${e.length} patterns`,confidence:this.calculateConsolidatedConfidence(e),usageCount:e.reduce((s,a)=>s+a.usageCount,0),successRate:this.calculateWeightedSuccessRate(e),context:i,template:r.template,createdAt:new Date,lastUsedAt:new Date};await this.storePattern(n);for(let s of e)await this.archivePattern(s.id);return f(n)}catch(e){return p(y(e))}}async getPatternStats(t){try{let e=await this.memory.search("learning:pattern:*",500,be),r=[];for(let c of e){let l=await this.memory.get(c,be);l&&(!t||l.domain===t)&&r.push(l)}let i={"test-pattern":0,"fix-pattern":0,"optimization-pattern":0,"detection-pattern":0,"workflow-pattern":0,"failure-pattern":0},n={"test-generation":0,"test-execution":0,"coverage-analysis":0,"quality-assessment":0,"defect-intelligence":0,"requirements-validation":0,"code-intelligence":0,"security-compliance":0,"contract-testing":0,"visual-accessibility":0,"chaos-resilience":0,"learning-optimization":0,"enterprise-integration":0,coordination:0},s=0,a=0;for(let c of r)i[c.type]++,n[c.domain]++,s+=c.confidence,a+=c.successRate;let o=r.sort((c,l)=>l.successRate-c.successRate).slice(0,10);return f({totalPatterns:r.length,byType:i,byDomain:n,avgConfidence:r.length>0?s/r.length:0,avgSuccessRate:r.length>0?a/r.length:0,topPatterns:o})}catch(e){return p(y(e))}}async recordExperience(t){try{let e=v(),r={...t,id:e,timestamp:new Date};return await this.memory.set(`learning:experience:${e}`,r,{namespace:"learning-optimization",ttl:86400*30}),await this.indexExperience(r),f(e)}catch(e){return p(y(e))}}async mineExperiences(t,e){try{let r=await this.getExperiencesByDomainAndTime(t,e);if(r.length===0)return f({experienceCount:0,successRate:0,avgReward:0,patterns:[],anomalies:[],recommendations:["No experiences found in the given time range"]});let i=this.calculateSuccessRate(r),n=this.calculateAverageReward(r),s=await this.extractPatternsFromExperiences(r),a=this.detectAnomalies(r),o=this.generateRecommendations(r,i,a);return f({experienceCount:r.length,successRate:i,avgReward:n,patterns:s,anomalies:a,recommendations:o})}catch(r){return p(y(r))}}calculateReward(t,e){let r=t.outcome[e.metric]??0,i;e.direction==="maximize"?i=Math.min(r/100,1):i=Math.max(1-r/100,0);let n=0;for(let o of e.constraints){let c=t.outcome[o.metric]??0;this.isConstraintViolated(o,c)&&(n+=.2)}let s=t.success?.5:0,a=Math.max(0,i+s-n);return Math.min(1,a)}async getReplayBuffer(t,e=100){try{let r=await this.memory.search(`learning:experience:index:agent:${t.value}:*`,e,be),i=[];for(let n of r){let s=await this.memory.get(n,be);if(s){let a=ae(await this.memory.get(`learning:experience:${s}`,be),["timestamp"]);a&&i.push(a)}}return i.sort((n,s)=>s.timestamp.getTime()-n.timestamp.getTime()),f(i.slice(0,e))}catch(r){return p(y(r))}}async clusterExperiences(t){try{if(t.length===0)return f([]);let e=new Map;for(let n of t){let s=!1;for(let[a,o]of e)if(this.actionsSimilar(n.action,a)){o.push(n),s=!0;break}s||e.set(n.action,[n])}let r=[],i=0;for(let[n,s]of e)if(s.length>=2){let a=this.calculateCentroid(s),o=this.extractCommonActions(s),c=this.calculateAverageReward(s);r.push({id:`cluster-${i++}`,centroid:a,experiences:s,commonActions:o,avgReward:c})}return f(r)}catch(e){return p(y(e))}}async storePattern(t){await this.memory.set(`learning:pattern:${t.id}`,t,{namespace:"learning-optimization",persist:!0})}async archivePattern(t){let e=`learning:pattern:${t}`,r=await this.memory.get(e,be);r&&(await this.memory.set(`learning:pattern:archived:${t}`,r,{namespace:"learning-optimization",persist:!0}),await this.memory.delete(e,be))}async updatePatternUsage(t){let e=`learning:pattern:${t}`,r=await this.memory.get(e,be);if(r){let i={...r,usageCount:r.usageCount+1,lastUsedAt:new Date};await this.memory.set(e,i,{namespace:"learning-optimization",persist:!0})}}async recordPatternCreation(t,e){await this.memory.set(`learning:pattern:creation:${t.id}`,{patternId:t.id,experienceIds:e.map(r=>r.id),createdAt:new Date},{namespace:"learning-optimization",persist:!0})}async indexExperience(t){await this.memory.set(`learning:experience:index:agent:${t.agentId.value}:${t.id}`,t.id,{namespace:"learning-optimization",ttl:86400*30}),await this.memory.set(`learning:experience:index:domain:${t.domain}:${t.id}`,t.id,{namespace:"learning-optimization",ttl:86400*30})}async getExperiencesByDomainAndTime(t,e){let r=await this.memory.search(`learning:experience:index:domain:${t}:*`,1e3,be),i=[];for(let n of r){let s=await this.memory.get(n,be);if(s){let a=await this.memory.get(`learning:experience:${s}`,be);if(a){let o=a.timestamp instanceof Date?a.timestamp:new Date(a.timestamp);e.contains(o)&&i.push({...a,timestamp:o})}}}return i}async extractPatternsFromExperiences(t){let e=t.filter(n=>n.result.success),r=new Map;for(let n of e){let s=r.get(n.action)||[];s.push(n),r.set(n.action,s)}let i=[];for(let[n,s]of r)if(s.length>=this.config.minExperiencesForPattern){let a=await this.learnPattern(s);a.success&&i.push(a.value)}return i}matchesContext(t,e){return!(e.language&&t.context.language!==e.language||e.framework&&t.context.framework!==e.framework||e.testType&&t.context.testType!==e.testType||e.tags.length>0&&!e.tags.some(i=>t.context.tags.includes(i)))}extractCommonActions(t){let e=new Map;for(let r of t){let i=e.get(r.action)||0;e.set(r.action,i+1)}return Array.from(e.entries()).filter(([r,i])=>i>=t.length*.3).map(([r])=>r)}calculateAverageReward(t){return t.length===0?0:t.reduce((r,i)=>r+i.reward,0)/t.length}calculateSuccessRate(t){return t.length===0?0:t.filter(r=>r.result.success).length/t.length}inferPatternType(t){let e=t.map(r=>r.action.toLowerCase());return e.some(r=>r.includes("test")||r.includes("generate"))?"test-pattern":e.some(r=>r.includes("fix")||r.includes("repair"))?"fix-pattern":e.some(r=>r.includes("optimize")||r.includes("improve"))?"optimization-pattern":e.some(r=>r.includes("detect")||r.includes("find"))?"detection-pattern":e.some(r=>r.includes("workflow")||r.includes("process"))?"workflow-pattern":e.some(r=>r.includes("fail")||r.includes("error"))?"failure-pattern":"workflow-pattern"}generatePatternTemplate(t,e){let r=[{name:"domain",type:"string",required:!0,description:"Target domain for the pattern"},{name:"action",type:"string",required:!0,defaultValue:e[0],description:"Primary action to execute"}];return{type:"workflow",content:`// Pattern learned from ${t.length} experiences
|
|
3025
3025
|
// Common actions: ${e.join(", ")}
|
|
3026
3026
|
// Apply to domain: {{domain}}
|
|
3027
|
-
// Execute action: {{action}}`,variables:r}}extractPatternContext(t){let e=new Set,r,i;for(let n of t){let s=n.state.context;if(s.language&&(r=s.language),s.framework&&(i=s.framework),s.tags&&Array.isArray(s.tags))for(let a of s.tags)e.add(a)}return{language:r,framework:i,tags:Array.from(e)}}calculateConsolidatedConfidence(t){let e=t.reduce((i,n)=>i+n.usageCount,0),r=0;for(let i of t){let n=e>0?i.usageCount/e:1/t.length;r+=i.confidence*n}return r}calculateWeightedSuccessRate(t){let e=t.reduce((i,n)=>i+n.usageCount,0),r=0;for(let i of t){let n=e>0?i.usageCount/e:1/t.length;r+=i.successRate*n}return r}detectAnomalies(t){let e=[],r=this.calculateAverageReward(t),i=this.calculateStdDev(t.map(n=>n.reward));for(let n of t){let s=Math.abs(n.reward-r)/(i||1);if(s>this.config.anomalyDeviationThreshold){let a="outlier-reward";n.result.success&&n.reward<r?a="unexpected-success":!n.result.success&&n.reward>r&&(a="unexpected-failure"),e.push({experienceId:n.id,type:a,description:`Reward ${n.reward.toFixed(2)} deviates ${s.toFixed(2)} std from mean ${r.toFixed(2)}`,deviation:s})}}return e}calculateStdDev(t){if(t.length===0)return 0;let e=t.reduce((i,n)=>i+n,0)/t.length,r=t.map(i=>Math.pow(i-e,2));return Math.sqrt(r.reduce((i,n)=>i+n,0)/t.length)}generateRecommendations(t,e,r){let i=[];return e<.5&&i.push("Low success rate detected. Consider reviewing the approach or gathering more training data."),r.length>t.length*.1&&i.push("High anomaly rate detected. Investigate unexpected outcomes for potential improvements."),t.reduce((s,a)=>s+a.result.duration,0)/t.length>6e4&&i.push("Average operation duration is high. Consider optimizing performance."),t.length<10&&i.push("Limited experience data. Collect more data points for better insights."),i.length===0&&i.push("Performance metrics are within acceptable ranges. Continue monitoring."),i}actionsSimilar(t,e){let r=s=>s.toLowerCase().replace(/[^a-z]/g,""),i=r(t),n=r(e);return!!(i===n||i.includes(n)||n.includes(i))}calculateCentroid(t){let e={},r={};for(let i of t)for(let[n,s]of Object.entries(i.state.metrics))e[n]=(e[n]||0)+s,r[n]=(r[n]||0)+1;for(let i of Object.keys(e))e[i]/=r[i];return{context:{},metrics:e}}isConstraintViolated(t,e){switch(t.operator){case"lt":return e>=t.value;case"gt":return e<=t.value;case"lte":return e>t.value;case"gte":return e<t.value;case"eq":return e!==t.value;default:return!1}}};A();var eb={maxKnowledgeItems:1e3,relevanceThreshold:.5,transferDecayFactor:.1,crossDomainBoost:.2},Wt=class{constructor(t,e={}){this.memory=t;this.config={...eb,...e}}memory;config;async shareKnowledge(t,e){try{await this.memory.set(`learning:knowledge:shared:${t.id}`,t,{namespace:"learning-optimization",persist:!0});for(let r of e)await this.memory.set(`learning:knowledge:access:${r.value}:${t.id}`,{knowledgeId:t.id,agentId:r.value,sharedAt:new Date,accessed:!1},{namespace:"learning-optimization",ttl:86400*7});return await this.recordSharingEvent(t,e),f(void 0)}catch(r){return p(y(r))}}async queryKnowledge(t){try{let e=[],r;t.domain?r=await this.memory.search(`learning:knowledge:*:${t.domain}:*`,t.limit||100):r=await this.memory.search("learning:knowledge:shared:*",t.limit||100);for(let i of r){let n=ae(await this.memory.get(i),["createdAt","expiresAt"]);n&&this.matchesQuery(n,t)&&e.push(n)}if(e.sort((i,n)=>n.relevanceScore-i.relevanceScore),t.embedding&&t.embedding.length>0){let i=await this.memory.vectorSearch(t.embedding,t.limit||10);for(let n of i){let s=ae(await this.memory.get(n.key),["createdAt","expiresAt"]);s&&!e.some(a=>a.id===s.id)&&this.matchesQuery(s,t)&&e.push(s)}}return f(e.slice(0,t.limit||100))}catch(e){return p(y(e))}}async synthesizeKnowledge(t){try{if(t.length<2)return p(new Error("Need at least 2 knowledge items to synthesize"));let e=[];for(let c of t){let l=await this.getKnowledgeById(c);l&&e.push(l)}if(e.length<2)return p(new Error("Not enough valid knowledge items found"));let r=this.determineSynthesizedType(e),i=this.determineSynthesizedDomain(e),n=this.mergeKnowledgeContent(e),s=e.reduce((c,l)=>c+l.relevanceScore,0)/e.length,a=Math.min(1,s+this.config.crossDomainBoost),o={id:v(),type:r,domain:i,content:n,sourceAgentId:e[0].sourceAgentId,targetDomains:this.mergeTargetDomains(e),relevanceScore:a,version:1,createdAt:new Date};return await this.storeKnowledge(o),await this.recordSynthesisEvent(o,t),f(o)}catch(e){return p(y(e))}}async transferKnowledge(t,e){try{if(t.domain===e)return p(new Error("Cannot transfer knowledge to the same domain"));let r=this.calculateTransferredRelevance(t,e);if(r<this.config.relevanceThreshold)return p(new Error(`Transferred relevance ${r} below threshold ${this.config.relevanceThreshold}`));let i=await this.adaptContentForDomain(t.content,t.domain,e),n={id:v(),type:t.type,domain:e,content:i,sourceAgentId:t.sourceAgentId,targetDomains:[e],relevanceScore:r,version:t.version+1,createdAt:new Date};return await this.storeKnowledge(n),await this.recordTransferEvent(t,n),f(n)}catch(r){return p(y(r))}}async validateRelevance(t,e){try{let r=t.relevanceScore;if(e.language&&t.content.metadata?.language===e.language&&(r+=.1),e.framework&&t.content.metadata?.framework===e.framework&&(r+=.1),e.tags.length>0&&t.content.metadata?.tags){let a=t.content.metadata.tags,o=e.tags.filter(c=>a.includes(c));r+=o.length/e.tags.length*.2}let n=(Date.now()-t.createdAt.getTime())/(1e3*60*60*24),s=Math.exp(-this.config.transferDecayFactor*n/30);return r*=s,t.expiresAt&&new Date>t.expiresAt&&(r*=.5),f(Math.min(1,Math.max(0,r)))}catch(r){return p(y(r))}}async createKnowledge(t,e,r,i,n=[],s){try{let a={id:v(),type:t,domain:e,content:{format:this.inferContentFormat(r),data:r,metadata:s},sourceAgentId:i,targetDomains:n,relevanceScore:1,version:1,createdAt:new Date};return await this.storeKnowledge(a),t==="embedding"&&Array.isArray(r)&&await this.memory.storeVector(`learning:knowledge:vector:${a.id}`,r,{knowledgeId:a.id}),f(a)}catch(a){return p(y(a))}}async getKnowledgeById(t){return ae(await this.memory.get(`learning:knowledge:shared:${t}`),["createdAt","expiresAt"])||null}async bulkTransfer(t,e,r){try{let i=await this.memory.search(`learning:knowledge:project:${t}:*`,500),n=[];for(let s of i){let a=ae(await this.memory.get(s),["createdAt","expiresAt"]);if(!a||r?.types&&!r.types.includes(a.type)||r?.minRelevance&&a.relevanceScore<r.minRelevance)continue;let o=await this.adaptContentForProject(a.content,t,e),c={...a,id:v(),content:o,relevanceScore:a.relevanceScore*(1-this.config.transferDecayFactor),version:a.version+1,createdAt:new Date};await this.memory.set(`learning:knowledge:project:${e}:${c.id}`,c,{namespace:"learning-optimization",persist:!0}),n.push({knowledgeId:c.id,sourceDomain:a.domain,targetDomain:a.domain,originalRelevance:a.relevanceScore,transferredRelevance:c.relevanceScore,adaptations:["project-context-adapted"]})}return f(n)}catch(i){return p(y(i))}}async storeKnowledge(t){await this.memory.set(`learning:knowledge:shared:${t.id}`,t,{namespace:"learning-optimization",persist:!0}),await this.memory.set(`learning:knowledge:domain:${t.domain}:${t.id}`,t.id,{namespace:"learning-optimization",persist:!0}),await this.memory.set(`learning:knowledge:type:${t.type}:${t.id}`,t.id,{namespace:"learning-optimization",persist:!0})}matchesQuery(t,e){if(e.type&&t.type!==e.type||e.domain&&t.domain!==e.domain||e.minRelevance!==void 0&&t.relevanceScore<e.minRelevance)return!1;if(e.tags&&e.tags.length>0){let r=t.content.metadata?.tags||[];if(!e.tags.some(n=>r.includes(n)))return!1}return!0}determineSynthesizedType(t){let e=new Map;for(let n of t)e.set(n.type,(e.get(n.type)||0)+1);let r=t[0].type,i=0;for(let[n,s]of e)s>i&&(i=s,r=n);return r}determineSynthesizedDomain(t){let e=new Map;for(let n of t)e.set(n.domain,(e.get(n.domain)||0)+1);let r=t[0].domain,i=0;for(let[n,s]of e)s>i&&(i=s,r=n);return r}mergeKnowledgeContent(t){let e={},r=[];for(let i of t)if(r.push(i.content.data),i.content.metadata)for(let[n,s]of Object.entries(i.content.metadata))if(Array.isArray(s)){let a=e[n]||[];e[n]=[...new Set([...a,...s])]}else e[n]=s;return{format:"json",data:{synthesized:!0,sources:r},metadata:{...e,synthesizedFrom:t.map(i=>i.id),synthesizedAt:new Date().toISOString()}}}mergeTargetDomains(t){let e=new Set;for(let r of t){e.add(r.domain);for(let i of r.targetDomains)e.add(i)}return Array.from(e)}calculateTransferredRelevance(t,e){let r=t.relevanceScore;r*=1-this.config.transferDecayFactor;let i=this.getDomainCompatibility(t.domain,e);return r*=i,t.targetDomains.includes(e)&&(r+=this.config.crossDomainBoost),Math.min(1,Math.max(0,r))}getDomainCompatibility(t,e){let r={"test-generation":["test-execution","coverage-analysis"],"test-execution":["test-generation","coverage-analysis","quality-assessment"],"coverage-analysis":["test-generation","test-execution","quality-assessment"],"quality-assessment":["test-execution","coverage-analysis","defect-intelligence"],"defect-intelligence":["quality-assessment","code-intelligence"],"requirements-validation":["test-generation","quality-assessment"],"code-intelligence":["defect-intelligence","security-compliance"],"security-compliance":["code-intelligence","quality-assessment"],"contract-testing":["test-generation","test-execution"],"visual-accessibility":["quality-assessment"],"chaos-resilience":["test-execution","quality-assessment"],"learning-optimization":["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence"],"enterprise-integration":["contract-testing","security-compliance","quality-assessment"],coordination:we.filter(i=>i!=="coordination")};return t===e?1:r[t]?.includes(e)?.8:.5}async adaptContentForDomain(t,e,r){return{...t,metadata:{...t.metadata||{},adaptedFrom:e,adaptedTo:r,adaptedAt:new Date().toISOString()}}}async adaptContentForProject(t,e,r){return{...t,metadata:{...t.metadata||{},sourceProject:e,targetProject:r,transferredAt:new Date().toISOString()}}}inferContentFormat(t){return typeof t=="string"?"text":Array.isArray(t)&&t.every(e=>typeof e=="number")?"embedding":"json"}async recordSharingEvent(t,e){await this.memory.set(`learning:knowledge:events:share:${t.id}:${Date.now()}`,{type:"share",knowledgeId:t.id,targetAgents:e.map(r=>r.value),timestamp:new Date},{namespace:"learning-optimization",ttl:86400*30})}async recordSynthesisEvent(t,e){await this.memory.set(`learning:knowledge:events:synthesis:${t.id}`,{type:"synthesis",synthesizedId:t.id,sourceIds:e,timestamp:new Date},{namespace:"learning-optimization",ttl:86400*30})}async recordTransferEvent(t,e){await this.memory.set(`learning:knowledge:events:transfer:${e.id}`,{type:"transfer",originalId:t.id,transferredId:e.id,originalDomain:t.domain,targetDomain:e.domain,timestamp:new Date},{namespace:"learning-optimization",ttl:86400*30})}};A();se();var tb={defaultConfidenceLevel:.95,minSamplesForOptimization:20,maxOptimizationIterations:100,improvementThreshold:.05,explorationRate:.1},rb=["__proto__","constructor","prototype"];function Yi(u){return!rb.includes(u)}var Ut=class{constructor(t,e={}){this.memory=t;this.config={...tb,...e}}memory;config;async optimizeStrategy(t,e,r){try{if(r.length<this.config.minSamplesForOptimization)return p(new Error(`Need at least ${this.config.minSamplesForOptimization} experiences for optimization`));let i=this.evaluateStrategyPerformance(t,r,e),n=await this.optimizeParameters(t.parameters,r,e),s={name:`${t.name}-optimized`,parameters:n,expectedOutcome:this.predictOutcome(n,r)},a=await this.validateOptimization(t,s,r.slice(-10)),o=this.evaluateStrategyPerformance(s,r,e),c=this.calculateImprovement(i,o,e),l=this.calculateOptimizationConfidence(r.length,c,a),d=this.inferDomainFromExperiences(r),m={id:v(),domain:d,objective:e,currentStrategy:t,optimizedStrategy:s,improvement:c,confidence:l,validationResults:a};return await this.storeOptimizationResult(m),f(m)}catch(i){return p(y(i))}}async runABTest(t,e,r){try{let i=await this.collectStrategyMetrics(t,r.metric,r.minSamples),n=await this.collectStrategyMetrics(e,r.metric,r.minSamples),s=this.calculateMean(i),a=this.calculateMean(n),o=this.calculateStdDev(i),c=this.calculateStdDev(n),l=this.calculatePValue(i,n),d;l<1-r.confidenceLevel?d=s>a?"A":"B":d="inconclusive";let m={winner:d,strategyAMetrics:{[r.metric]:s,stdDev:o,samples:i.length},strategyBMetrics:{[r.metric]:a,stdDev:c,samples:n.length},pValue:l,sampleSizeA:i.length,sampleSizeB:n.length};return await this.storeABTestResult(t,e,m),f(m)}catch(i){return p(y(i))}}async recommendStrategy(t){try{let e=await this.memory.search("learning:strategy:optimized:*",100),r=[];for(let i of e){let n=await this.memory.get(i);if(n&&n.confidence>.6){let s=this.scoreContextMatch(n,t),a=n.improvement*n.confidence;r.push({strategy:n.optimizedStrategy,score:s*.4+a*.6})}}return r.length===0?f({name:"default-strategy",parameters:this.getDefaultParameters(t),expectedOutcome:{success_rate:.7}}):(r.sort((i,n)=>n.score-i.score),f(r[0].strategy))}catch(e){return p(y(e))}}async evaluateStrategy(t,e){try{let r={},i=this.calculateSuccessRate(e),n=this.calculateAverageDuration(e),s=this.calculateAverageReward(e);r.success_rate=i,r.avg_duration_ms=n,r.avg_reward=s;let a=[];i>.8&&a.push("High success rate"),n<5e3&&a.push("Fast execution"),s>.7&&a.push("Consistently good rewards");let o=[];i<.5&&o.push("Low success rate needs investigation"),n>3e4&&o.push("Slow execution time"),s<.3&&o.push("Low reward values");let c=this.identifyImprovementAreas(t,r,e),l={strategy:t,metrics:r,strengths:a,weaknesses:o,improvementAreas:c};return await this.storeStrategyEvaluation(l),f(l)}catch(r){return p(y(r))}}async trackMetrics(t,e){try{let r={strategyId:t,metrics:e,timestamp:new Date,samples:1},i=`learning:metrics:history:${t}:${Date.now()}`;return await this.memory.set(i,r,{namespace:"learning-optimization",ttl:86400*30}),await this.updateAggregatedMetrics(t,e),f(void 0)}catch(r){return p(y(r))}}async getMetricsHistory(t,e=100){try{let r=await this.memory.search(`learning:metrics:history:${t}:*`,e),i=[];for(let n of r){let s=ae(await this.memory.get(n),["timestamp"]);s&&i.push(s)}return i.sort((n,s)=>n.timestamp.getTime()-s.timestamp.getTime()),f(i)}catch(r){return p(y(r))}}async gridSearchOptimize(t,e,r){try{let i=this.generateParameterCombinations(t),n={},s=e.direction==="maximize"?-1/0:1/0;for(let a of i){let o=this.scoreParameters(a,r,e);(e.direction==="maximize"?o>s:o<s)&&(s=o,n=a)}return f(n)}catch(i){return p(y(i))}}evaluateStrategyPerformance(t,e,r){let i=0,n=0;for(let s of e){let a=s.result.outcome[r.metric]??0;i+=a,n++}return n>0?i/n:0}async optimizeParameters(t,e,r){let i={...t};for(let[n,s]of Object.entries(t))if(Yi(n)&&typeof s=="number"){let a=[-.1,-.05,0,.05,.1],o=0,c=this.scoreParameters(i,e,r);for(let l of a){let d={...i,[n]:s*(1+l)},m=this.scoreParameters(d,e,r);(r.direction==="maximize"?m>c:m<c)&&(c=m,o=l)}i[n]=s*(1+o)}return i}scoreParameters(t,e,r){let i=0,n=0;for(let s of e){let a=s.result.success?1:.5,o=this.calculateParamSimilarity(t,s.state.context),c=s.result.outcome[r.metric]??0;i+=o*c*a,n+=a}return n>0?i/n:0}calculateParamSimilarity(t,e){let r=0,i=0;for(let[n,s]of Object.entries(t))if(e[n]!==void 0)if(i++,typeof s=="number"&&typeof e[n]=="number"){let a=Math.abs(s-e[n]),o=Math.max(Math.abs(s),Math.abs(e[n]),1);r+=1-a/o}else s===e[n]&&r++;return i>0?r/i:.5}predictOutcome(t,e){let r={},i={},n={};for(let s of e)if(s.result.success)for(let[a,o]of Object.entries(s.result.outcome))Yi(a)&&typeof o=="number"&&(i[a]=(i[a]||0)+o,n[a]=(n[a]||0)+1);for(let[s,a]of Object.entries(i))Yi(s)&&(r[s]=a/n[s]);return r}async validateOptimization(t,e,r){let i=[];for(let n of r){let s=e.expectedOutcome,a=Object.entries(s).every(([o,c])=>{let l=n.result.outcome[o]??0;return Math.abs(l-c)/Math.max(c,1)<.2});i.push({testId:n.id,passed:a,metrics:n.state.metrics})}return i}calculateImprovement(t,e,r){if(t===0)return e>0?1:0;let i=e-t,n=r.direction==="maximize"?i/t:-i/t;return Math.max(-1,Math.min(1,n))}calculateOptimizationConfidence(t,e,r){let i=Math.min(1,t/(this.config.minSamplesForOptimization*2)),n=r.filter(a=>a.passed).length/Math.max(r.length,1),s=Math.abs(e)>this.config.improvementThreshold?1:.5;return i*.3+n*.5+s*.2}inferDomainFromExperiences(t){let e=new Map;for(let n of t)e.set(n.domain,(e.get(n.domain)||0)+1);let r="learning-optimization",i=0;for(let[n,s]of e)s>i&&(i=s,r=n);return r}async collectStrategyMetrics(t,e,r){let i=await this.memory.search("learning:metrics:history:*:*",r*2),n=[];for(let s of i){let a=await this.memory.get(s);a&&a.metrics[e]!==void 0&&n.push(a.metrics[e])}for(;n.length<r;){let s=t.expectedOutcome[e]||.5,a=(L()-.5)*.2;n.push(s+a)}return n}calculateMean(t){return t.length===0?0:t.reduce((e,r)=>e+r,0)/t.length}calculateStdDev(t){if(t.length===0)return 0;let e=this.calculateMean(t),r=t.map(i=>Math.pow(i-e,2));return Math.sqrt(r.reduce((i,n)=>i+n,0)/t.length)}calculatePValue(t,e){let r=this.calculateMean(t),i=this.calculateMean(e),n=Math.pow(this.calculateStdDev(t),2),s=Math.pow(this.calculateStdDev(e),2),a=t.length,o=e.length,c=Math.sqrt(n/a+s/o);if(c===0)return .5;let l=Math.abs(r-i)/c,d=2*(1-this.normalCDF(l));return Math.max(0,Math.min(1,d))}normalCDF(t){let e=.254829592,r=-.284496736,i=1.421413741,n=-1.453152027,s=1.061405429,a=.3275911,o=t<0?-1:1;t=Math.abs(t)/Math.sqrt(2);let c=1/(1+a*t),l=1-((((s*c+n)*c+i)*c+r)*c+e)*c*Math.exp(-t*t);return .5*(1+o*l)}scoreContextMatch(t,e){let r=0,i=0;return e.tags.some(n=>n===t.objective.metric)&&(r+=1),i+=1,e.tags.some(n=>n===t.domain)&&(r+=1),i+=1,i>0?r/i:.5}getDefaultParameters(t){let e={timeout:3e4,retryCount:3,concurrency:4};return t.framework&&(e.framework=t.framework),t.language&&(e.language=t.language),e}calculateSuccessRate(t){return t.length===0?0:t.filter(e=>e.result.success).length/t.length}calculateAverageDuration(t){return t.length===0?0:t.reduce((e,r)=>e+r.result.duration,0)/t.length}calculateAverageReward(t){return t.length===0?0:t.reduce((e,r)=>e+r.reward,0)/t.length}identifyImprovementAreas(t,e,r){let i=[];e.success_rate<.8&&i.push("Increase success rate by tuning parameters"),e.avg_duration_ms>1e4&&i.push("Optimize for faster execution"),e.avg_reward<.5&&i.push("Improve reward through better strategy selection");let n=t.parameters;return n.retryCount<2&&i.push("Consider increasing retry count for resilience"),n.concurrency>8&&i.push("High concurrency may cause resource contention"),i}generateParameterCombinations(t){let e=Object.keys(t);if(e.length===0)return[{}];let r=[];function i(n,s){if(n===e.length){r.push({...s});return}let a=e[n];if(!Yi(a)){i(n+1,s);return}for(let o of t[a])s[a]=o,i(n+1,s)}return i(0,{}),r}async updateAggregatedMetrics(t,e){let r=`learning:metrics:aggregated:${t}`,n=(await this.memory.get(r))?.metrics||{};for(let[s,a]of Object.entries(e))Yi(s)&&(n[s]||(n[s]={sum:0,count:0}),n[s].sum+=a,n[s].count+=1);await this.memory.set(r,{metrics:n,updatedAt:new Date},{namespace:"learning-optimization",persist:!0})}async storeOptimizationResult(t){await this.memory.set(`learning:strategy:optimized:${t.id}`,t,{namespace:"learning-optimization",persist:!0}),await this.memory.set(`learning:strategy:domain:${t.domain}:${t.id}`,t.id,{namespace:"learning-optimization",persist:!0})}async storeABTestResult(t,e,r){let i=v();await this.memory.set(`learning:abtest:${i}`,{testId:i,strategyA:t.name,strategyB:e.name,result:r,timestamp:new Date},{namespace:"learning-optimization",persist:!0})}async storeStrategyEvaluation(t){let e=v();await this.memory.set(`learning:evaluation:${e}`,{...t,evaluatedAt:new Date},{namespace:"learning-optimization",ttl:86400*7})}};A();var ib={metricsRetentionDays:90,anomalyThreshold:2.5,trendWindowSize:7,alertThresholds:{error_rate:.05,latency_p99:5e3,memory_usage:.9,cpu_usage:.8}},Qt=class{constructor(t,e={}){this.memory=t;this.config={...ib,...e}}memory;config;async recordMetric(t,e,r,i,n=[]){try{let s={id:v(),name:t,value:e,unit:r,domain:i,tags:n,timestamp:new Date};return await this.memory.set(`production:metric:${s.id}`,s,{namespace:"learning-optimization",ttl:this.config.metricsRetentionDays*86400}),await this.indexMetric(s),await this.checkForAnomalies(s),f(s.id)}catch(s){return p(y(s))}}async recordMetricsBatch(t){try{let e=[];for(let r of t){let i=await this.recordMetric(r.name,r.value,r.unit,r.domain,r.tags);i.success&&e.push(i.value)}return f(e)}catch(e){return p(y(e))}}async getMetricsHistory(t,e,r){try{let i=r?`production:metric:index:${t}:${r}:*`:`production:metric:index:${t}:*`,n=await this.memory.search(i,1e3),s=[];for(let a of n){let o=await this.memory.get(a);if(o){let c=ae(await this.memory.get(`production:metric:${o}`),["timestamp"]);c&&e.contains(c.timestamp)&&s.push(c)}}return s.sort((a,o)=>a.timestamp.getTime()-o.timestamp.getTime()),f(s)}catch(i){return p(y(i))}}async recordIncident(t,e,r,i,n){try{let s={id:v(),severity:t,title:e,description:r,domain:i,metrics:n,startedAt:new Date};return await this.memory.set(`production:incident:${s.id}`,s,{namespace:"learning-optimization",persist:!0}),await this.indexIncident(s),await this.createExperienceFromIncident(s),f(s)}catch(s){return p(y(s))}}async resolveIncident(t,e,r){try{let i=ae(await this.memory.get(`production:incident:${t}`),["startedAt","resolvedAt"]);if(!i)return p(new Error(`Incident ${t} not found`));let n={...i,rootCause:e,resolution:r,resolvedAt:new Date};return await this.memory.set(`production:incident:${t}`,n,{namespace:"learning-optimization",persist:!0}),await this.updateExperienceWithResolution(n),f(n)}catch(i){return p(y(i))}}async getRecentIncidents(t=10,e){try{let r=e?`production:incident:index:domain:${e}:*`:"production:incident:*",i=await this.memory.search(r,t*2),n=[];for(let a of i)if(a.includes(":index:")){let o=await this.memory.get(a);if(o){let c=ae(await this.memory.get(`production:incident:${o}`),["startedAt","resolvedAt"]);c&&n.push(c)}}else{let o=ae(await this.memory.get(a),["startedAt","resolvedAt"]);o&&n.push(o)}n.sort((a,o)=>o.startedAt.getTime()-a.startedAt.getTime());let s=Array.from(new Map(n.map(a=>[a.id,a])).values());return f(s.slice(0,t))}catch(r){return p(y(r))}}async getProductionHealth(){try{let t=["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","code-intelligence","security-compliance","learning-optimization"],e={},r={},i="healthy",n=0,s=0;for(let d of t){let m=await this.getDomainHealth(d);e[d]=m,m.status==="degraded"&&n++,m.status==="unhealthy"&&s++;for(let[h,g]of Object.entries(m.metrics))r[`${d}_${h}`]=g}s>0?i="unhealthy":n>t.length/3&&(i="degraded");let a=await this.calculateTrends(),o=await this.getRecentIncidents(5),c=o.success?o.value:[],l=this.generateHealthRecommendations(e,r,c);return f({overall:i,domains:e,metrics:r,trends:a,recentIncidents:c,recommendations:l})}catch(t){return p(y(t))}}async getDomainHealth(t){let e=it.lastNDays(1),r=await this.getMetricsHistory("*",e,t),i={};if(r.success)for(let o of r.value)i[o.name],i[o.name]=o.value;let n=await this.getRecentIncidents(100,t),s=n.success?n.value.filter(o=>!o.resolvedAt).length:0,a="healthy";return s>2?a="unhealthy":s>0&&(a="degraded"),i.error_rate>this.config.alertThresholds.error_rate?a="unhealthy":i.latency_p99>this.config.alertThresholds.latency_p99&&(a="degraded"),{status:a,metrics:i,activeIncidents:s}}async calculateTrends(){let t=[],e=["error_rate","latency_p99","success_rate"],r=this.config.trendWindowSize;for(let i of e)for(let n=0;n<r;n++){let s=new Date;s.setDate(s.getDate()-n),s.setHours(0,0,0,0);let a=new Date(s);a.setHours(23,59,59,999);let o=it.create(s,a),c=await this.getMetricsHistory(i,o);if(c.success&&c.value.length>0){let l=c.value.reduce((d,m)=>d+m.value,0)/c.value.length;t.push({timestamp:s,metric:i,value:l})}}return t}generateHealthRecommendations(t,e,r){let i=[];for(let[a,o]of Object.entries(t))o.status==="unhealthy"?i.push(`Domain ${a} is unhealthy. Review active incidents and metrics.`):o.status==="degraded"&&i.push(`Domain ${a} is degraded. Monitor closely.`);for(let[a,o]of Object.entries(e)){let c=a.split("_").slice(-2).join("_"),l=this.config.alertThresholds[c];l&&o>l&&i.push(`Metric ${a} (${o.toFixed(2)}) exceeds threshold (${l})`)}let n=r.filter(a=>!a.resolvedAt);return n.length>3&&i.push(`${n.length} unresolved incidents require attention`),r.reduce((a,o)=>(a[o.severity]=(a[o.severity]||0)+1,a),{}).critical>2&&i.push("Multiple critical incidents detected. Consider system-wide review."),i.length===0&&i.push("All systems operating within normal parameters."),i}async extractInsights(t,e){try{let r=await this.getMetricsHistory("*",t,e),i=r.success?r.value:[],n=await this.getRecentIncidents(50,e),s=n.success?n.value:[],a=i.length,o=s.filter(h=>h.resolvedAt),c=s.length>0?o.length/s.length:1,l=this.calculateRewardFromIncidents(s),d=this.generateInsightRecommendations(i,s),m=this.detectMetricAnomalies(i);return f({experienceCount:a,successRate:c,avgReward:l,patterns:[],anomalies:m,recommendations:d})}catch(r){return p(y(r))}}async recordMilestone(t,e,r){try{let i={name:t,achievedAt:new Date,domain:e};return await this.memory.set(`production:milestone:${v()}`,{...i,metrics:r},{namespace:"learning-optimization",persist:!0}),f(i)}catch(i){return p(y(i))}}async getRecentMilestones(t=10){try{let e=await this.memory.search("production:milestone:*",t),r=[];for(let i of e){let n=ae(await this.memory.get(i),["achievedAt"]);n&&r.push(n)}return r.sort((i,n)=>n.achievedAt.getTime()-i.achievedAt.getTime()),f(r.slice(0,t))}catch(e){return p(y(e))}}async indexMetric(t){await this.memory.set(`production:metric:index:${t.name}:${t.domain}:${t.id}`,t.id,{namespace:"learning-optimization",ttl:this.config.metricsRetentionDays*86400})}async indexIncident(t){await this.memory.set(`production:incident:index:domain:${t.domain}:${t.id}`,t.id,{namespace:"learning-optimization",persist:!0}),await this.memory.set(`production:incident:index:severity:${t.severity}:${t.id}`,t.id,{namespace:"learning-optimization",persist:!0})}async checkForAnomalies(t){let e=it.lastNDays(7),r=await this.getMetricsHistory(t.name,e,t.domain);if(!r.success||r.value.length<10)return;let i=r.value.map(o=>o.value),n=i.reduce((o,c)=>o+c,0)/i.length,s=Math.sqrt(i.reduce((o,c)=>o+Math.pow(c-n,2),0)/i.length),a=Math.abs(t.value-n)/(s||1);a>this.config.anomalyThreshold&&await this.memory.set(`production:anomaly:${v()}`,{metricId:t.id,metricName:t.name,value:t.value,mean:n,stdDev:s,deviation:a,timestamp:new Date},{namespace:"learning-optimization",ttl:86400*7})}async createExperienceFromIncident(t){let e={context:{incidentId:t.id,severity:t.severity,domain:t.domain},metrics:t.metrics},r={success:!1,outcome:t.metrics,duration:0},i={id:v(),agentId:{value:"production-intel",domain:"learning-optimization",type:"analyzer"},domain:t.domain,action:`incident-${t.severity}`,state:e,result:r,reward:this.calculateIncidentReward(t),timestamp:t.startedAt};await this.memory.set(`learning:experience:${i.id}`,i,{namespace:"learning-optimization",ttl:86400*30})}async updateExperienceWithResolution(t){if(!t.resolvedAt)return;let e={context:{incidentId:t.id,rootCause:t.rootCause,resolution:t.resolution},metrics:t.metrics},r=t.resolvedAt.getTime()-t.startedAt.getTime(),i={success:!0,outcome:{...t.metrics,resolution_time_ms:r},duration:r},n={id:v(),agentId:{value:"production-intel",domain:"learning-optimization",type:"analyzer"},domain:t.domain,action:`resolution-${t.severity}`,state:e,result:i,reward:1-this.calculateIncidentReward(t),timestamp:t.resolvedAt};await this.memory.set(`learning:experience:${n.id}`,n,{namespace:"learning-optimization",ttl:86400*30})}calculateIncidentReward(t){return-({critical:.9,high:.7,medium:.4,low:.2}[t.severity]||.5)}calculateRewardFromIncidents(t){if(t.length===0)return .8;let e={critical:.1,high:.3,medium:.6,low:.8},r=0,i=0;for(let n of t){let s=e[n.severity]||.5,a=n.resolvedAt?.2:0;r+=s+a,i++}return i>0?r/i:.8}generateInsightRecommendations(t,e){let r=[],i=new Map;for(let n of t){let s=i.get(n.name)||[];s.push(n.value),i.set(n.name,s)}for(let[n,s]of i){let a=this.calculateTrendDirection(s);a==="increasing"&&n.includes("error")?r.push(`${n} is trending upward. Investigate root causes.`):a==="decreasing"&&n.includes("success")&&r.push(`${n} is declining. Review recent changes.`)}if(e.length>0){let n=new Map;for(let s of e)n.set(s.domain,(n.get(s.domain)||0)+1);for(let[s,a]of n)a>3&&r.push(`Domain ${s} has ${a} incidents. Consider preventive measures.`)}return r}detectMetricAnomalies(t){let e=[],r=new Map;for(let i of t){let n=r.get(i.name)||[];n.push(i),r.set(i.name,n)}for(let[i,n]of r){if(n.length<5)continue;let s=n.map(c=>c.value),a=s.reduce((c,l)=>c+l,0)/s.length,o=Math.sqrt(s.reduce((c,l)=>c+Math.pow(l-a,2),0)/s.length);for(let c of n){let l=Math.abs(c.value-a)/(o||1);l>this.config.anomalyThreshold&&e.push({experienceId:c.id,type:"outlier-reward",description:`${i} value ${c.value.toFixed(2)} is ${l.toFixed(1)} std deviations from mean`,deviation:l})}}return e}calculateTrendDirection(t){if(t.length<3)return"stable";let e=t.slice(0,Math.floor(t.length/2)),r=t.slice(Math.floor(t.length/2)),i=e.reduce((a,o)=>a+o,0)/e.length,s=(r.reduce((a,o)=>a+o,0)/r.length-i)/(i||1);return s>.1?"increasing":s<-.1?"decreasing":"stable"}};async function Om(u,t,e){await u.set(`learning:strategy:current:${t}`,e,{namespace:"learning-optimization",persist:!0})}function Nm(u,t){let e=u.map(r=>r.result.outcome[t]??0).filter(r=>!isNaN(r));return e.length===0?0:e.reduce((r,i)=>r+i,0)/e.length}function Vm(u){return{"test-generation":["test-execution","coverage-analysis"],"test-execution":["test-generation","coverage-analysis","quality-assessment"],"coverage-analysis":["test-generation","test-execution","quality-assessment"],"quality-assessment":["test-execution","coverage-analysis","defect-intelligence"],"defect-intelligence":["quality-assessment","code-intelligence"],"requirements-validation":["test-generation","quality-assessment"],"code-intelligence":["defect-intelligence","security-compliance"],"security-compliance":["code-intelligence","quality-assessment"],"contract-testing":["test-generation","test-execution"],"visual-accessibility":["quality-assessment"],"chaos-resilience":["test-execution","quality-assessment"],"learning-optimization":we.filter(e=>e!=="learning-optimization"),"enterprise-integration":["contract-testing","security-compliance","quality-assessment"],coordination:we.filter(e=>e!=="coordination")}[u]||[]}function _m(u){let t=[],e=new Set;for(let r of u){if(e.has(r.id))continue;let i=[r];e.add(r.id);for(let n of u)e.has(n.id)||r.type===n.type&&r.domain===n.domain&&nb(r.context,n.context)&&(i.push(n),e.add(n.id));i.length>=2&&t.push(i)}return t}function nb(u,t){return u.tags.some(e=>t.tags.includes(e))}function zm(u,t,e){let r=JSON.stringify({patternCount:u.length,knowledgeCount:t.length,strategyCount:e.length,patternIds:u.map(n=>n.id).sort(),knowledgeIds:t.map(n=>n.id).sort(),strategyIds:e.map(n=>n.id).sort()}),i=0;for(let n=0;n<r.length;n++){let s=r.charCodeAt(n);i=(i<<5)-i+s,i=i&i}return Math.abs(i).toString(16)}M();var Fr=R.create("learning-optimization/consensus");async function Bm(u,t,e,r){let i=V({id:v(),type:"pattern-recommendation",confidence:t,description:`Verify pattern recommendation: ${u.name} (${u.type}) for domain ${u.domain}`,payload:u,detectedBy:"learning-optimization-coordinator",severity:t>.9?"high":"medium"});if(e.requiresConsensus(i)){let n=await e.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(Fr.info(`Pattern recommendation '${u.name}' verified by consensus`),!0):(Fr.warn(`Pattern recommendation '${u.name}' NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}async function qm(u,t,e,r){let i=V({id:v(),type:"optimization-suggestion",confidence:t,description:`Verify optimization: ${u.metric} from ${u.currentValue} to ${u.targetValue} via ${u.strategy}`,payload:u,detectedBy:"learning-optimization-coordinator",severity:t>.85?"high":"medium"});if(e.requiresConsensus(i)){let n=await e.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(Fr.info(`Optimization suggestion for '${u.metric}' verified by consensus`),!0):(Fr.warn(`Optimization suggestion for '${u.metric}' NOT verified`),!1)}return!0}async function Gm(u,t,e,r){let i=V({id:v(),type:"cross-domain-insight",confidence:t,description:`Verify cross-domain insight: ${u.description}`,payload:u,detectedBy:"learning-optimization-coordinator",severity:"high"});if(e.requiresConsensus(i)){let n=await e.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(Fr.info(`Cross-domain insight verified by consensus for ${u.targetDomains.length} target domains`),!0):(Fr.warn(`Cross-domain insight NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}var ob={maxConcurrentWorkflows:3,defaultTimeout:12e4,enableAutoOptimization:!0,publishEvents:!0,learningCycleIntervalMs:36e5,enableDreamScheduler:!0,dreamCycleIntervalMs:36e5,enableExperienceTrigger:!0,experienceThreshold:50,enableQualityGateFailureTrigger:!0,autoApplyHighConfidenceInsights:!1,autoApplyConfidenceThreshold:.8,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},Ae=R.create("learning-optimization"),ka=class extends Q{constructor(e,r,i,n={},s){let a={...ob,...n};super(e,"learning-optimization",a,{verifyFindingTypes:["pattern-recommendation","optimization-suggestion","cross-domain-insight"]});this.memory=r;this.agentCoordinator=i;this.learningService=new jt({memory:r,llmRouter:s}),this.transferService=new Wt(r),this.optimizerService=new Ut(r),this.productionIntel=new Qt(r)}memory;agentCoordinator;learningService;transferService;optimizerService;productionIntel;sona=null;dreamScheduler=null;async onInitialize(){try{this.sona=await pe({domain:"learning-optimization",loadOnInit:!0,autoSaveInterval:6e4,maxPatterns:1e4,minConfidence:.5}),Ae.info("PersistentSONAEngine initialized for pattern learning")}catch(e){Ae.error("Failed to initialize PersistentSONAEngine:",e instanceof Error?e:void 0),Ae.warn("Continuing without SONA pattern persistence"),this.sona=null}if(this.config.enableDreamScheduler)try{let e=await tn();await e.initialize(),this.dreamScheduler=El({dreamEngine:e,eventBus:this.eventBus,memoryBackend:this.memory},{autoScheduleIntervalMs:this.config.dreamCycleIntervalMs,enableExperienceTrigger:this.config.enableExperienceTrigger,experienceThreshold:this.config.experienceThreshold,enableQualityGateFailureTrigger:this.config.enableQualityGateFailureTrigger,autoApplyHighConfidenceInsights:this.config.autoApplyHighConfidenceInsights,insightConfidenceThreshold:this.config.autoApplyConfidenceThreshold}),await this.dreamScheduler.initialize(),this.dreamScheduler.start(),Ae.info("DreamScheduler initialized and started")}catch{Ae.warn("Failed to initialize DreamScheduler:")}this.subscribeToEvents(),await this.loadWorkflowState()}async onDispose(){if(await this.saveWorkflowState(),this.dreamScheduler){try{await this.dreamScheduler.dispose(),Ae.info("DreamScheduler disposed")}catch(e){Ae.error("Error disposing DreamScheduler:",e instanceof Error?e:void 0)}this.dreamScheduler=null}if(this.initialized&&this.sona)try{await this.sona.close()}catch(e){Ae.error("Error closing SONA engine:",e instanceof Error?e:void 0)}}getActiveWorkflows(){return super.getActiveWorkflows()}async runLearningCycle(e){let r=v();try{if(this.startWorkflow(r,"learning-cycle"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Ae.warn("Topology degraded, using conservative strategy for learning cycle"),this.minCutMixin.shouldPauseOperations())return p(new Error("Learning cycle paused: topology is in critical state"));let i=await this.spawnLearningAgent(r,e);if(!i.success)return this.failWorkflow(r,i.error.message),p(i.error);this.addAgentToWorkflow(r,i.value);let n=it.lastNDays(1),s=await this.getExperiencesForDomain(e,n),a=s.success?s.value:[];this.updateWorkflowProgress(r,20);let o=await this.learningService.mineExperiences(e,n),c=o.success?o.value.patterns.length:0;this.updateWorkflowProgress(r,50);let l=0,d=[];if(a.length>=10){let g={metric:"success_rate",direction:"maximize",constraints:[]},b=await this.getCurrentStrategy(e),w=await this.optimizerService.optimizeStrategy(b,g,a);w.success&&(l=1,d.push({metric:g.metric,before:this.calculateMetricValue(a,g.metric),after:w.value.optimizedStrategy.expectedOutcome[g.metric]||0,percentChange:w.value.improvement*100}))}this.updateWorkflowProgress(r,80);let m=0;o.success&&o.value.recommendations.length>0&&(await this.transferService.createKnowledge("heuristic",e,o.value.recommendations,{value:`learning-agent-${r.slice(0,8)}`,domain:"learning-optimization",type:"analyzer"},[e])).success&&(m=1),this.completeWorkflow(r),await this.agentCoordinator.stop(i.value);let h={domain:e,experiencesProcessed:a.length,patternsLearned:c,strategiesOptimized:l,knowledgeGenerated:m,improvements:d};return this.config.publishEvents&&c>0&&await this.publishPatternConsolidated(c,[e]),f(h)}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async optimizeAllStrategies(){let e=v();try{if(this.startWorkflow(e,"optimization"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Ae.warn("Topology degraded, using conservative optimization strategy"),this.minCutMixin.shouldPauseOperations())return p(new Error("Optimization paused: topology is in critical state"));let r={},i=0,n=0,s=0,a=we.filter(c=>c!=="learning-optimization");for(let c=0;c<a.length;c++){let l=a[c];this.updateWorkflowProgress(e,Math.round(c/a.length*100));let d=it.lastNDays(7),m=await this.getExperiencesForDomain(l,d);if(!m.success||m.value.length<10)continue;let h=m.value,g={metric:"success_rate",direction:"maximize",constraints:[]},b=await this.getCurrentStrategy(l),w=await this.optimizerService.optimizeStrategy(b,g,h);w.success&&(i++,n+=w.value.improvement,s++,r[l]={strategiesOptimized:1,avgImprovement:w.value.improvement,bestStrategy:w.value.optimizedStrategy},await this.storeStrategy(l,w.value.optimizedStrategy))}this.completeWorkflow(e);let o={domainsOptimized:s,totalStrategies:i,avgImprovement:i>0?n/i:0,byDomain:r};return this.config.publishEvents&&i>0&&await this.publishOptimizationApplied(o),f(o)}catch(r){return this.failWorkflow(e,String(r)),p(y(r))}}async shareCrossDomainLearnings(){let e=v();try{if(this.startWorkflow(e,"transfer"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Ae.warn("Topology degraded, limiting cross-domain transfer scope"),this.minCutMixin.shouldPauseOperations())return p(new Error("Cross-domain sharing paused: topology is in critical state"));let r=0,i=[],n=0,s=0,a=0,o=await this.transferService.queryKnowledge({minRelevance:.7,limit:100});if(!o.success)return this.failWorkflow(e,o.error.message),p(o.error);let c=o.value;for(let m of c){let h=this.getRelatedDomains(m.domain);for(let g of h){if(g===m.domain)continue;s++,(await this.transferService.transferKnowledge(m,g)).success&&(a++,r++,i.includes(g)||i.push(g))}this.updateWorkflowProgress(e,Math.round(r/(c.length*2)*100))}let l=await this.learningService.getPatternStats();if(l.success){let m=l.value.topPatterns;if(m.length>=2){let h=this.findSimilarPatterns(m);for(let g of h)g.length>=2&&(await this.learningService.consolidatePatterns(g.map(w=>w.id))).success&&n++}}this.completeWorkflow(e);let d={knowledgeShared:r,domainsUpdated:i,transferSuccessRate:s>0?a/s:1,newPatternsCreated:n};return this.config.publishEvents&&r>0&&await this.publishTransferCompleted(d),f(d)}catch(r){return this.failWorkflow(e,String(r)),p(y(r))}}async getLearningDashboard(){try{let e=await this.learningService.getPatternStats(),r=e.success?e.value:null,i=await this.transferService.queryKnowledge({limit:1e3}),n=i.success?i.value.length:0,s=it.lastNDays(1),a=0;for(let b of we){let w=await this.getExperiencesForDomain(b,s);w.success&&(a+=w.value.length)}let o=await this.productionIntel.getProductionHealth(),c=o.success?o.value.trends:[],l=await this.productionIntel.getRecentMilestones(5),d=l.success?l.value:[],m=r?r.avgSuccessRate*.6+r.avgConfidence*.4:.5,h=[];if(r){let b=Object.entries(r.byDomain).filter(([w,C])=>C>0).map(([w,C])=>({domain:w,score:C})).sort((w,C)=>C.score-w.score);h.push(...b.slice(0,3).map(w=>w.domain))}let g={overallLearningRate:m,totalPatterns:r?.totalPatterns||0,totalKnowledge:n,experiencesLast24h:a,topPerformingDomains:h,learningTrend:c,recentMilestones:d};return f(g)}catch(e){return p(y(e))}}learnPattern(e,r,i,n,s,a){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.createPattern(e,r,i,n,s,a)}ensureInitialized(){if(!this.initialized)throw new Error("[LearningOptimizationCoordinator] Not initialized. Call initialize() first.")}ensureSONAAvailable(){if(!this.sona)throw new Error("[LearningOptimizationCoordinator] SONA engine is not available. Pattern persistence failed during initialization.")}async adaptPattern(e,r,i){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.adaptPattern(e,r,i)}getSONAStats(){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.getStats()}getSONAPatterns(){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.getAllPatterns()}getSONAPatternsByType(e){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.getPatternsByType(e)}getSONAPatternsByDomain(e){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.getPatternsByDomain(e)}updateSONAPattern(e,r,i){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.updatePattern(e,r,i)}forceSONALearning(){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.forceLearn()}isSONAAvailable(){return this.initialized&&this.sona!==null}exportSONAPatterns(){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.exportPatterns()}importSONAPatterns(e){this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.importPatterns(e)}async verifySONAPerformance(e=100){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.verifyPerformance(e)}async triggerDreamCycle(e){if(!this.dreamScheduler)throw new Error("[LearningOptimizationCoordinator] DreamScheduler not initialized");let r=await this.dreamScheduler.triggerDream(e);return this.config.publishEvents&&await this.publishDreamCycleCompleted(r.cycle.id,r.cycle.durationMs??0,r.cycle.conceptsProcessed,r.insights.map(i=>({id:i.id,type:i.type,description:i.description,noveltyScore:i.noveltyScore,confidenceScore:i.confidenceScore,actionable:i.actionable,suggestedAction:i.suggestedAction,sourceConcepts:i.sourceConcepts})),r.patternsCreated),r}getDreamStatus(){return this.dreamScheduler?.getStatus()??null}isDreamSchedulerAvailable(){return this.dreamScheduler!==null}getLastDreamResult(){return this.dreamScheduler?.getLastDreamResult()??null}async triggerQuickDream(){if(!this.dreamScheduler)throw new Error("[LearningOptimizationCoordinator] DreamScheduler not initialized");return this.dreamScheduler.triggerQuickDream()}async triggerFullDream(){if(!this.dreamScheduler)throw new Error("[LearningOptimizationCoordinator] DreamScheduler not initialized");return this.dreamScheduler.triggerFullDream()}async exportModels(e){let r=v();try{this.startWorkflow(r,"export");let i=e||we,n=[],s=[],a=[];for(let m of i){let h=await this.memory.search("learning:pattern:*",500);for(let g of h){let b=await this.memory.get(g);b&&i.includes(b.domain)&&n.push(b)}this.updateWorkflowProgress(r,Math.round(n.length/100*30))}let o=await this.transferService.queryKnowledge({limit:1e3});if(o.success)for(let m of o.value)i.includes(m.domain)&&s.push(m);this.updateWorkflowProgress(r,60);let c=await this.memory.search("learning:strategy:optimized:*",200);for(let m of c){let h=await this.memory.get(m);h&&i.includes(h.domain)&&a.push(h)}this.updateWorkflowProgress(r,90);let l=this.calculateChecksum(n,s,a);return this.completeWorkflow(r),f({version:"1.0.0",exportedAt:new Date,patterns:n,knowledge:s,strategies:a,checksum:l})}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async importModels(e){let r=v();try{if(this.startWorkflow(r,"import"),this.calculateChecksum(e.patterns,e.knowledge,e.strategies)!==e.checksum)return this.failWorkflow(r,"Checksum mismatch"),p(new Error("Import failed: checksum mismatch"));let n=0,s=0,a=0,o=[];for(let l of e.patterns){let d=await this.memory.get(`learning:pattern:${l.id}`);d?d.confidence<l.confidence?(await this.memory.set(`learning:pattern:${l.id}`,l,{namespace:"learning-optimization",persist:!0}),n++,o.push({type:"pattern",id:l.id,reason:"Existing pattern had lower confidence",resolution:"overwrite"})):o.push({type:"pattern",id:l.id,reason:"Existing pattern has higher confidence",resolution:"skip"}):(await this.memory.set(`learning:pattern:${l.id}`,l,{namespace:"learning-optimization",persist:!0}),n++),this.updateWorkflowProgress(r,Math.round(n/e.patterns.length*30))}for(let l of e.knowledge){let d=await this.memory.get(`learning:knowledge:shared:${l.id}`);d?l.version>d.version?(await this.memory.set(`learning:knowledge:shared:${l.id}`,l,{namespace:"learning-optimization",persist:!0}),s++,o.push({type:"knowledge",id:l.id,reason:"Import has newer version",resolution:"overwrite"})):o.push({type:"knowledge",id:l.id,reason:"Existing knowledge is same or newer version",resolution:"skip"}):(await this.memory.set(`learning:knowledge:shared:${l.id}`,l,{namespace:"learning-optimization",persist:!0}),s++),this.updateWorkflowProgress(r,30+Math.round(s/e.knowledge.length*30))}for(let l of e.strategies){let d=await this.memory.get(`learning:strategy:optimized:${l.id}`);d?l.confidence>d.confidence?(await this.memory.set(`learning:strategy:optimized:${l.id}`,l,{namespace:"learning-optimization",persist:!0}),a++,o.push({type:"strategy",id:l.id,reason:"Import has higher confidence",resolution:"overwrite"})):o.push({type:"strategy",id:l.id,reason:"Existing strategy has higher confidence",resolution:"skip"}):(await this.memory.set(`learning:strategy:optimized:${l.id}`,l,{namespace:"learning-optimization",persist:!0}),a++),this.updateWorkflowProgress(r,60+Math.round(a/e.strategies.length*40))}return this.completeWorkflow(r),f({patternsImported:n,knowledgeImported:s,strategiesImported:a,conflicts:o,resolved:!0})}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}subscribeToEvents(){this.eventBus.subscribe("test-execution.TestRunCompleted",this.handleTestRunCompleted.bind(this)),this.eventBus.subscribe("coverage-analysis.CoverageGapDetected",this.handleCoverageGap.bind(this)),this.eventBus.subscribe("quality-assessment.QualityGateEvaluated",this.handleQualityGate.bind(this)),this.eventBus.subscribe("learning.ExperienceCaptured",this.handleExperienceCaptured.bind(this))}async handleTestRunCompleted(e){let{runId:r,passed:i,failed:n,duration:s}=e.payload,a=i+n>0?i/(i+n):0;await this.learningService.recordExperience({agentId:{value:"test-execution",domain:"test-execution",type:"tester"},domain:"test-execution",action:"test-run",state:{context:{runId:r},metrics:{passed:i,failed:n,duration:s}},result:{success:a>.8,outcome:{success_rate:a,passed:i,failed:n},duration:s},reward:a})}async handleCoverageGap(e){let{gapId:r,file:i,riskScore:n}=e.payload;await this.learningService.recordExperience({agentId:{value:"coverage-analysis",domain:"coverage-analysis",type:"analyzer"},domain:"coverage-analysis",action:"gap-detection",state:{context:{gapId:r,file:i},metrics:{riskScore:n}},result:{success:!0,outcome:{risk_score:n},duration:0},reward:1-n})}async handleQualityGate(e){let{gateId:r,passed:i}=e.payload;await this.learningService.recordExperience({agentId:{value:"quality-assessment",domain:"quality-assessment",type:"validator"},domain:"quality-assessment",action:"gate-evaluation",state:{context:{gateId:r},metrics:{passed:i?1:0}},result:{success:i,outcome:{gate_passed:i?1:0},duration:0},reward:i?1:0})}async handleExperienceCaptured(e){let{experience:r}=e.payload;if(!r.success||r.quality<.7)return;let i=r.domain||"learning-optimization";if(await this.learningService.recordExperience({agentId:{value:r.agent||"unknown",domain:i,type:"specialist"},domain:i,action:r.task,state:{context:{experienceId:r.id,trajectoryId:r.trajectoryId,model:r.model},metrics:{durationMs:r.durationMs,stepCount:r.steps.length,quality:r.quality}},result:{success:r.success,outcome:{quality:r.quality,patterns_extracted:r.patterns?.length||0},duration:r.durationMs},reward:r.quality}),r.patterns&&r.patterns.length>0&&r.domain){let n=this.getRelatedDomains(r.domain);for(let s of n)s!==r.domain&&await this.transferService.transferKnowledge({id:`exp-${r.id}`,domain:r.domain,type:"workflow",content:{format:"json",data:{task:r.task,steps:r.steps,quality:r.quality,patterns:r.patterns}},sourceAgentId:{value:r.agent||"experience-capture",domain:r.domain,type:"specialist"},targetDomains:[s],relevanceScore:r.quality,version:1,createdAt:new Date(r.startedAt)},s);Ae.info(`[LearningOptimizationCoordinator] Experience ${r.id} transferred to ${n.length} related domains`)}this.dreamScheduler&&this.dreamScheduler.recordExperience({id:r.id,agentType:r.agent||"unknown",domain:i,taskType:r.task,success:r.success,duration:r.durationMs,context:{quality:r.quality,steps:r.steps.length,patterns:r.patterns?.length||0},timestamp:new Date(r.startedAt)})}async publishPatternConsolidated(e,r){let i={patternCount:e,domains:r,improvements:0},n=I(He.PatternConsolidated,"learning-optimization",i);await this.eventBus.publish(n)}async publishTransferCompleted(e){let r={sourceProject:"current",targetProject:"current",patternsTransferred:e.knowledgeShared,successRate:e.transferSuccessRate},i=I(He.TransferCompleted,"learning-optimization",r);await this.eventBus.publish(i)}async publishOptimizationApplied(e){let r=I(He.OptimizationApplied,"learning-optimization",{domainsOptimized:e.domainsOptimized,avgImprovement:e.avgImprovement});await this.eventBus.publish(r)}async publishDreamCycleCompleted(e,r,i,n,s){if(!this.config.publishEvents)return;let a={cycleId:e,durationMs:r,conceptsProcessed:i,insights:n,patternsCreated:s},o=I(He.DreamCycleCompleted,"learning-optimization",a);await this.eventBus.publish(o),Ae.info(`[LearningOptimizationCoordinator] Published dream cycle completion: ${n.length} insights for ${i} concepts`)}async spawnLearningAgent(e,r){if(!this.agentCoordinator.canSpawn())return p(new Error("Agent limit reached"));let i={name:`learning-agent-${e.slice(0,8)}`,domain:"learning-optimization",type:"optimizer",capabilities:["pattern-learning","experience-mining",r],config:{workflowId:e,targetDomain:r}};return this.agentCoordinator.spawn(i)}async loadWorkflowState(){let e=await this.memory.get("learning-optimization:coordinator:workflows");if(e)for(let r of e)r.status==="running"&&(r.status="failed",r.error="Coordinator restarted",r.completedAt=new Date),this.workflows.set(r.id,r)}async saveWorkflowState(){let e=Array.from(this.workflows.values());await this.memory.set("learning-optimization:coordinator:workflows",e,{namespace:"learning-optimization",persist:!0})}async getExperiencesForDomain(e,r){let i=await this.memory.search(`learning:experience:index:domain:${e}:*`,500),n=[];for(let s of i){let a=await this.memory.get(s);if(a){let o=ae(await this.memory.get(`learning:experience:${a}`),["timestamp"]);o&&r.contains(o.timestamp)&&n.push(o)}}return f(n)}async getCurrentStrategy(e){let r=`learning:strategy:current:${e}`,i=await this.memory.get(r);return i||{name:`default-${e}`,parameters:{timeout:3e4,retryCount:3,concurrency:4},expectedOutcome:{success_rate:.8}}}async storeStrategy(e,r){await Om(this.memory,e,r)}calculateMetricValue(e,r){return Nm(e,r)}getRelatedDomains(e){return Vm(e)}findSimilarPatterns(e){return _m(e)}calculateChecksum(e,r,i){return zm(e,r,i)}async verifyPatternRecommendation(e,r){return Bm(e,r,this.consensusMixin,this.domainName)}async verifyOptimizationSuggestion(e,r){return qm(e,r,this.consensusMixin,this.domainName)}async verifyCrossDomainInsight(e,r){return Gm(e,r,this.consensusMixin,this.domainName)}};A();var ll=class extends j{constructor(e,r,i,n={},s){super(e,r);this.agentCoordinator=i;this.llmRouter=s;this.pluginConfig=n}agentCoordinator;llmRouter;coordinator=null;learningService=null;transferService=null;optimizerService=null;productionIntel=null;pluginConfig;get name(){return"learning-optimization"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{isSONAAvailable:()=>this.coordinator?.isSONAAvailable()??!1,runLearningCycle:this.runLearningCycle.bind(this),optimizeAllStrategies:this.optimizeAllStrategies.bind(this),shareCrossDomainLearnings:this.shareCrossDomainLearnings.bind(this),getLearningDashboard:this.getLearningDashboard.bind(this),exportModels:this.exportModels.bind(this),importModels:this.importModels.bind(this),learnPattern:this.learnPattern.bind(this),findMatchingPatterns:this.findMatchingPatterns.bind(this),applyPattern:this.applyPattern.bind(this),updatePatternFeedback:this.updatePatternFeedback.bind(this),getPatternStats:this.getPatternStats.bind(this),queryKnowledge:this.queryKnowledge.bind(this),transferKnowledge:this.transferKnowledge.bind(this),optimizeStrategy:this.optimizeStrategy.bind(this),runABTest:this.runABTest.bind(this),recommendStrategy:this.recommendStrategy.bind(this),evaluateStrategy:this.evaluateStrategy.bind(this),getCoordinator:()=>this.coordinator,getActiveWorkflows:()=>this.coordinator?.getActiveWorkflows()||[],getLearningService:()=>this.learningService,getTransferService:()=>this.transferService,getOptimizerService:()=>this.optimizerService,getProductionIntelService:()=>this.productionIntel}}getTaskHandlers(){return new Map([["run-learning-cycle",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.domain;return r?this.coordinator.runLearningCycle(r):p(new Error("Invalid run-learning-cycle payload: missing domain"))}],["optimize-strategies",async e=>this.coordinator?this.coordinator.optimizeAllStrategies():p(new Error("Coordinator not initialized"))],["share-learnings",async e=>this.coordinator?this.coordinator.shareCrossDomainLearnings():p(new Error("Coordinator not initialized"))],["learn-pattern",async e=>{if(!this.learningService)return p(new Error("Learning service not initialized"));let r=e.experiences;return!r||r.length===0?p(new Error("Invalid learn-pattern payload: missing experiences")):this.learningService.learnPattern(r)}],["query-knowledge",async e=>{if(!this.transferService)return p(new Error("Transfer service not initialized"));let r=e.query;return r?this.transferService.queryKnowledge(r):p(new Error("Invalid query-knowledge payload: missing query"))}]])}async onInitialize(){this.learningService=new jt({memory:this.memory,llmRouter:this.llmRouter},this.pluginConfig.learningService),this.transferService=new Wt(this.memory,this.pluginConfig.transferService),this.optimizerService=new Ut(this.memory,this.pluginConfig.optimizerService),this.productionIntel=new Qt(this.memory,this.pluginConfig.productionIntel),this.coordinator=new ka(this.eventBus,this.memory,this.agentCoordinator,this.pluginConfig.coordinator,this.llmRouter),await this.coordinator.initialize(),this.updateHealth({status:"idle",agents:{total:0,active:0,idle:0,failed:0},lastActivity:new Date,errors:[]})}async onDispose(){this.coordinator&&await this.coordinator.dispose(),this.coordinator=null,this.learningService=null,this.transferService=null,this.optimizerService=null,this.productionIntel=null}subscribeToEvents(){this.eventBus.subscribe("test-generation.TestGenerated",this.handleTestGenerated.bind(this)),this.eventBus.subscribe("test-execution.TestRunCompleted",this.handleTestRunCompleted.bind(this)),this.eventBus.subscribe("coverage-analysis.CoverageGapDetected",this.handleCoverageGap.bind(this)),this.eventBus.subscribe("quality-assessment.QualityGateEvaluated",this.handleQualityGate.bind(this)),this.eventBus.subscribe("defect-intelligence.DefectPredicted",this.handleDefectPredicted.bind(this)),this.eventBus.subscribe("code-intelligence.ImpactAnalysisCompleted",this.handleImpactAnalysis.bind(this))}async onEvent(e){switch(this.updateHealth({lastActivity:new Date}),e.type){case"test-generation.TestGenerated":await this.handleTestGenerated(e);break;case"test-execution.TestRunCompleted":await this.handleTestRunCompleted(e);break;case"coverage-analysis.CoverageGapDetected":await this.handleCoverageGap(e);break;default:break}}async runLearningCycle(e){this.ensureInitialized();try{let r=await this.coordinator.runLearningCycle(e);return r.success?this.trackSuccessfulOperation("learning-cycle"):this.trackFailedOperation("learning-cycle",r.error),r}catch(r){return this.handleError(r)}}async optimizeAllStrategies(){this.ensureInitialized();try{let e=await this.coordinator.optimizeAllStrategies();return e.success?this.trackSuccessfulOperation("optimization"):this.trackFailedOperation("optimization",e.error),e}catch(e){return this.handleError(e)}}async shareCrossDomainLearnings(){this.ensureInitialized();try{return await this.coordinator.shareCrossDomainLearnings()}catch(e){return this.handleError(e)}}async getLearningDashboard(){this.ensureInitialized();try{return await this.coordinator.getLearningDashboard()}catch(e){return this.handleError(e)}}async exportModels(e){this.ensureInitialized();try{return await this.coordinator.exportModels(e)}catch(r){return this.handleError(r)}}async importModels(e){this.ensureInitialized();try{return await this.coordinator.importModels(e)}catch(r){return this.handleError(r)}}async learnPattern(e){this.ensureInitialized();try{return await this.learningService.learnPattern(e)}catch(r){return this.handleError(r)}}async findMatchingPatterns(e,r){this.ensureInitialized();try{return await this.learningService.findMatchingPatterns(e,r)}catch(i){return this.handleError(i)}}async applyPattern(e,r){this.ensureInitialized();try{return await this.learningService.applyPattern(e,r)}catch(i){return this.handleError(i)}}async updatePatternFeedback(e,r){this.ensureInitialized();try{return await this.learningService.updatePatternFeedback(e,r)}catch(i){return this.handleError(i)}}async getPatternStats(e){this.ensureInitialized();try{return await this.learningService.getPatternStats(e)}catch(r){return this.handleError(r)}}async queryKnowledge(e){this.ensureInitialized();try{return await this.transferService.queryKnowledge(e)}catch(r){return this.handleError(r)}}async transferKnowledge(e,r){this.ensureInitialized();try{return await this.transferService.transferKnowledge(e,r)}catch(i){return this.handleError(i)}}async optimizeStrategy(e,r,i){this.ensureInitialized();try{return await this.optimizerService.optimizeStrategy(e,r,i)}catch(n){return this.handleError(n)}}async runABTest(e,r,i){this.ensureInitialized();try{return await this.optimizerService.runABTest(e,r,i)}catch(n){return this.handleError(n)}}async recommendStrategy(e){this.ensureInitialized();try{return await this.optimizerService.recommendStrategy(e)}catch(r){return this.handleError(r)}}async evaluateStrategy(e,r){this.ensureInitialized();try{return await this.optimizerService.evaluateStrategy(e,r)}catch(i){return this.handleError(i)}}async handleTestGenerated(e){let r=e.payload;await this.learningService.recordExperience({agentId:{value:"test-generation",domain:"test-generation",type:"generator"},domain:"test-generation",action:"test-generated",state:{context:{testId:r.testId,testType:r.testType},metrics:{}},result:{success:!0,outcome:{generated:1},duration:0},reward:.8})}async handleTestRunCompleted(e){let r=e.payload,i=r.passed+r.failed>0?r.passed/(r.passed+r.failed):0;await this.learningService.recordExperience({agentId:{value:"test-execution",domain:"test-execution",type:"tester"},domain:"test-execution",action:"test-run",state:{context:{runId:r.runId},metrics:{passed:r.passed,failed:r.failed,duration:r.duration}},result:{success:i>.8,outcome:{success_rate:i,passed:r.passed,failed:r.failed},duration:r.duration},reward:i}),await this.productionIntel.recordMetric("test_success_rate",i,"ratio","test-execution",["automated"])}async handleCoverageGap(e){let r=e.payload;await this.learningService.recordExperience({agentId:{value:"coverage-analysis",domain:"coverage-analysis",type:"analyzer"},domain:"coverage-analysis",action:"gap-detection",state:{context:{gapId:r.gapId,file:r.file},metrics:{riskScore:r.riskScore}},result:{success:!0,outcome:{risk_score:r.riskScore},duration:0},reward:1-r.riskScore})}async handleQualityGate(e){let r=e.payload;await this.learningService.recordExperience({agentId:{value:"quality-assessment",domain:"quality-assessment",type:"validator"},domain:"quality-assessment",action:"gate-evaluation",state:{context:{gateId:r.gateId},metrics:{passed:r.passed?1:0}},result:{success:r.passed,outcome:{gate_passed:r.passed?1:0},duration:0},reward:r.passed?1:0})}async handleDefectPredicted(e){let r=e.payload;await this.learningService.recordExperience({agentId:{value:"defect-intelligence",domain:"defect-intelligence",type:"analyzer"},domain:"defect-intelligence",action:"defect-prediction",state:{context:{predictionId:r.predictionId},metrics:{probability:r.probability}},result:{success:!0,outcome:{probability:r.probability},duration:0},reward:.7})}async handleImpactAnalysis(e){let r=e.payload;await this.learningService.recordExperience({agentId:{value:"code-intelligence",domain:"code-intelligence",type:"analyzer"},domain:"code-intelligence",action:"impact-analysis",state:{context:{analysisId:r.analysisId},metrics:{changedFiles:r.changedFiles.length,impactedFiles:r.impactedFiles.length}},result:{success:!0,outcome:{changed_count:r.changedFiles.length,impacted_count:r.impactedFiles.length},duration:0},reward:.8})}ensureInitialized(){if(!this._initialized)throw new Error("LearningOptimizationPlugin is not initialized");if(!this.coordinator||!this.learningService||!this.transferService||!this.optimizerService||!this.productionIntel)throw new Error("LearningOptimizationPlugin services are not available")}handleError(e){let r=y(e),i=this.getHealth();return this.updateHealth({errors:[...i.errors.slice(-9),r.message],status:i.errors.length>=5?"degraded":i.status}),p(r)}trackSuccessfulOperation(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,total:r.agents.total+1,idle:r.agents.idle+1},lastActivity:new Date})}trackFailedOperation(e,r){let i=this.getHealth();this.updateHealth({agents:{...i.agents,failed:i.agents.failed+1},errors:[...i.errors.slice(-9),r.message]})}};function Hm(u,t,e,r,i){return new ll(u,t,e,r,i)}var ul=class extends j{constructor(e,r,i,n={}){super(e,r);this.agentCoordinator=i;this.pluginConfig=n}agentCoordinator;workflowOrchestrator=null;pluginConfig;get name(){return"coordination"}get version(){return"1.0.0"}get dependencies(){return we.filter(e=>e!=="coordination")}getAPI(){return{listWorkflows:async()=>{if(!this.workflowOrchestrator)throw new Error("Workflow orchestrator not initialized");return this.workflowOrchestrator.listWorkflows()}}}async onInitialize(){this.workflowOrchestrator=Fl(this.eventBus,this.memory,this.agentCoordinator,this.pluginConfig.workflowConfig),await this.workflowOrchestrator.initialize(),this.updateHealth({status:"healthy",agents:{total:0,active:0,idle:0,failed:0}})}async onDispose(){this.workflowOrchestrator&&(await this.workflowOrchestrator.dispose(),this.workflowOrchestrator=null)}async onEvent(e){e.type.startsWith("coordination.")&&await this.handleCoordinationEvent(e)}subscribeToEvents(){this.eventBus.subscribe("coordination.workflow.execute",async e=>{await this.handleEvent(e)})}async handleCoordinationEvent(e){e.type.split(".")[1]==="workflow"&&await this.handleWorkflowEvent(e)}async handleWorkflowEvent(e){this.workflowOrchestrator}};function jm(u,t,e,r){return new ul(u,t,e,r)}var Ee={CoverageAnalyzerService:"coverage-analysis.CoverageAnalyzerService",SecurityScannerService:"security-compliance.SecurityScannerService",isSemgrepAvailable:"security-compliance.isSemgrepAvailable",runSemgrepWithRules:"security-compliance.runSemgrepWithRules",convertSemgrepFindings:"security-compliance.convertSemgrepFindings",createTestGeneratorService:"test-generation.createTestGeneratorService",KnowledgeGraphService:"code-intelligence.KnowledgeGraphService",QualityAnalyzerService:"quality-assessment.QualityAnalyzerService"},dl=class{factories=new Map;register(t,e){this.factories.set(t,e)}resolve(t){let e=this.factories.get(t);if(!e)throw new Error(`DomainServiceRegistry: service '${t}' not registered. Ensure the domain module is initialized before coordination.`);return e}has(t){return this.factories.has(t)}clear(){this.factories.clear()}keys(){return Array.from(this.factories.keys())}},xe=new dl;xe.register(Ee.createTestGeneratorService,u=>eo(u));xe.register(Ee.CoverageAnalyzerService,u=>new ht(u));xe.register(Ee.SecurityScannerService,u=>new Ne(u));xe.register(Ee.isSemgrepAvailable,qi);xe.register(Ee.runSemgrepWithRules,Qs);xe.register(Ee.convertSemgrepFindings,Ks);xe.register(Ee.KnowledgeGraphService,u=>new xt(u));A();xe.register(Ee.QualityAnalyzerService,u=>new Xe(u));A();M();A();var Kt={SoapOperationTested:"enterprise-integration.SoapOperationTested",MessageFlowTested:"enterprise-integration.MessageFlowTested",BapiTested:"enterprise-integration.BapiTested",IDocValidated:"enterprise-integration.IDocValidated",ODataTested:"enterprise-integration.ODataTested",SodAnalyzed:"enterprise-integration.SodAnalyzed",MiddlewareFlowTested:"enterprise-integration.MiddlewareFlowTested",IntegrationValidationFailed:"enterprise-integration.IntegrationValidationFailed"},db={maxConcurrentWorkflows:8,defaultTimeout:12e4,publishEvents:!0,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},Da=R.create("enterprise-integration"),Ia=class extends Q{constructor(e,r,i,n={}){let s={...db,...n};super(e,"enterprise-integration",s,{verifyFindingTypes:["soap-fault","message-ordering-violation","rfc-compatibility-break","idoc-validation-failure","odata-contract-break","sod-conflict"],modelTimeout:12e4});this.memory=r;this.agentCoordinator=i}memory;agentCoordinator;async onInitialize(){this.subscribeToEvents(),Da.info("Enterprise Integration Coordinator initialized")}async onDispose(){}subscribeToEvents(){this.eventBus.subscribe("contract-testing.ContractVerified",this.handleContractVerified.bind(this)),this.eventBus.subscribe("chaos-resilience.FaultInjected",this.handleFaultInjected.bind(this))}getActiveWorkflows(){return super.getActiveWorkflows()}async validateWsdl(e){let r=v();try{if(this.startWorkflow(r,"soap"),this.minCutMixin.shouldPauseOperations())return p(new Error("WSDL validation paused: topology is in critical state"));let i=await this.spawnAgent(r,"qe-soap-tester",{task:"validate-wsdl",url:e});if(!i.success)return this.failWorkflow(r,i.error.message),i;let n={url:e,version:"1.1",services:[],schemas:[]};return await this.memory.set(`enterprise-integration:wsdl:${encodeURIComponent(e)}`,n,{namespace:"enterprise-integration",persist:!0}),this.completeWorkflow(r),f(n)}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async testSoapOperation(e,r,i){let n=v();try{this.startWorkflow(n,"soap");let s=await this.spawnAgent(n,"qe-soap-tester",{task:"test-operation",wsdl:e,operation:r,input:i});if(!s.success)return this.failWorkflow(n,s.error.message),p(s.error);let a={operation:r,passed:!0,request:JSON.stringify(i),response:"",validationErrors:[],duration:0};return this.config.publishEvents&&await this.eventBus.publish(I(Kt.SoapOperationTested,this.domainName,{operation:r,wsdlUrl:e.url,passed:a.passed,errors:a.validationErrors.length})),this.completeWorkflow(n),f(a)}catch(s){return this.failWorkflow(n,String(s)),p(y(s))}}async testMessageFlow(e,r){let i=v();try{this.startWorkflow(i,"messaging");let n=await this.spawnAgent(i,"qe-message-broker-tester",{task:"test-message-flow",brokerConfig:e,testCase:r});if(!n.success)return this.failWorkflow(i,n.error.message),p(n.error);let s={testCaseId:r.id,passed:!0,sentAt:new Date,receivedAt:new Date,latency:0,actualOutcome:r.expectedOutcome,errors:[]};return this.config.publishEvents&&await this.eventBus.publish(I(Kt.MessageFlowTested,this.domainName,{protocol:e.protocol,queue:r.queue,passed:s.passed,latency:s.latency})),this.completeWorkflow(i),f(s)}catch(n){return this.failWorkflow(i,String(n)),p(y(n))}}async testDlqHandling(e,r){let i=v();try{this.startWorkflow(i,"messaging");let n=await this.spawnAgent(i,"qe-message-broker-tester",{task:"test-dlq",brokerConfig:e,queue:r});if(!n.success)return this.failWorkflow(i,n.error.message),p(n.error);let s={queue:r,messageCount:0,poisonMessages:0,reprocessable:0,errors:[]};return this.completeWorkflow(i),f(s)}catch(n){return this.failWorkflow(i,String(n)),p(y(n))}}async testBapiCall(e,r){let i=v();try{if(this.startWorkflow(i,"rfc"),this.minCutMixin.shouldPauseOperations())return p(new Error("BAPI testing paused: topology is in critical state"));let n=await this.spawnAgent(i,"qe-sap-rfc-tester",{task:"test-bapi",connection:e,bapi:r});if(!n.success)return this.failWorkflow(i,n.error.message),p(n.error);let s={bapiName:r.name,passed:!0,returnMessages:[],exportValues:{},tableData:{},duration:0,transactionCommitted:!1};return this.config.publishEvents&&await this.eventBus.publish(I(Kt.BapiTested,this.domainName,{bapiName:r.name,passed:s.passed,returnType:s.returnMessages.length>0?s.returnMessages[0].type:"S"})),await this.memory.set(`enterprise-integration:bapi:${r.name}:${Date.now()}`,{bapiName:r.name,importParams:Object.keys(r.importParams),passed:s.passed,timestamp:new Date().toISOString()},{namespace:"enterprise-integration",persist:!0}),this.completeWorkflow(i),f(s)}catch(n){return this.failWorkflow(i,String(n)),p(y(n))}}async validateIdoc(e,r){let i=v();try{this.startWorkflow(i,"idoc");let n=await this.spawnAgent(i,"qe-sap-idoc-tester",{task:"validate-idoc",definition:e,content:r});if(!n.success)return this.failWorkflow(i,n.error.message),p(n.error);let s={idocType:e.type,direction:"inbound",passed:!0,statusCode:3,statusMessage:"IDoc validated successfully",segmentValidation:[],processingTime:0};return this.config.publishEvents&&await this.eventBus.publish(I(Kt.IDocValidated,this.domainName,{idocType:e.type,direction:s.direction,passed:s.passed,statusCode:s.statusCode})),this.completeWorkflow(i),f(s)}catch(n){return this.failWorkflow(i,String(n)),p(y(n))}}async validateODataMetadata(e){let r=v();try{this.startWorkflow(r,"odata");let i=await this.spawnAgent(r,"qe-odata-contract-tester",{task:"validate-metadata",serviceUrl:e});if(!i.success)return this.failWorkflow(r,i.error.message),p(i.error);let n={version:"v4",serviceUrl:e,entitySets:[],functionImports:[],actions:[]};return await this.memory.set(`enterprise-integration:odata:${encodeURIComponent(e)}`,n,{namespace:"enterprise-integration",persist:!0}),this.completeWorkflow(r),f(n)}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async testODataEntitySet(e,r){let i=v();try{this.startWorkflow(i,"odata");let n=await this.spawnAgent(i,"qe-odata-contract-tester",{task:"test-entity-set",metadata:e,entitySet:r});if(!n.success)return this.failWorkflow(i,n.error.message),p(n.error);let s={entitySet:r,operation:"CRUD",passed:!0,statusCode:200,validationErrors:[],duration:0};return this.config.publishEvents&&await this.eventBus.publish(I(Kt.ODataTested,this.domainName,{entitySet:r,operation:s.operation,passed:s.passed,version:e.version})),this.completeWorkflow(i),f(s)}catch(n){return this.failWorkflow(i,String(n)),p(y(n))}}async validateMessageFlow(e,r){let i=v();try{this.startWorkflow(i,"middleware");let n=await this.spawnAgent(i,"qe-middleware-validator",{task:"validate-flow",flow:e,input:r});if(!n.success)return this.failWorkflow(i,n.error.message),p(n.error);let s={flowName:e.name,passed:!0,routingCorrect:!0,transformationCorrect:!0,errorHandlingCorrect:!0,validationErrors:[],duration:0};return this.config.publishEvents&&await this.eventBus.publish(I(Kt.MiddlewareFlowTested,this.domainName,{flowName:e.name,passed:s.passed,routingCorrect:s.routingCorrect,transformationCorrect:s.transformationCorrect})),this.completeWorkflow(i),f(s)}catch(n){return this.failWorkflow(i,String(n)),p(y(n))}}async validateTransformation(e,r,i){let n=v();try{this.startWorkflow(n,"middleware");let s=await this.spawnAgent(n,"qe-middleware-validator",{task:"validate-transformation",spec:e,input:r,expectedOutput:i});return s.success?(this.completeWorkflow(n),f(!0)):(this.failWorkflow(n,s.error.message),p(s.error))}catch(s){return this.failWorkflow(n,String(s)),p(y(s))}}async analyzeSod(e,r){let i=v();try{this.startWorkflow(i,"sod");let n=await this.spawnAgent(i,"qe-sod-analyzer",{task:"analyze-sod",userId:e,ruleset:r});if(!n.success)return this.failWorkflow(i,n.error.message),p(n.error);let s={userId:e,conflicts:[],riskScore:0,compliant:!0,recommendations:[]};return this.config.publishEvents&&await this.eventBus.publish(I(Kt.SodAnalyzed,this.domainName,{userId:e,conflicts:s.conflicts.length,compliant:s.compliant,riskScore:s.riskScore})),await this.memory.set(`enterprise-integration:sod:${e}:${Date.now()}`,{userId:e,ruleset:r.name,conflicts:s.conflicts.length,compliant:s.compliant,riskScore:s.riskScore,timestamp:new Date().toISOString()},{namespace:"enterprise-integration",persist:!0}),this.completeWorkflow(i),f(s)}catch(n){return this.failWorkflow(i,String(n)),p(y(n))}}async spawnAgent(e,r,i){let n={name:`${r}-${e.slice(0,8)}`,domain:"enterprise-integration",type:r,capabilities:[r],config:{workflowId:e,...i}},s=await this.agentCoordinator.spawn(n);return s.success&&this.addAgentToWorkflow(e,s.value),s}async verifyCriticalFinding(e,r){let i=V({id:v(),type:e.type,confidence:r,description:e.description,payload:e.payload,detectedBy:"enterprise-integration-coordinator",severity:r>.9?"critical":"high"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(Da.info(`Finding verified by consensus: ${e.type}`),!0):(Da.warn(`Finding NOT verified: ${e.type}`),!1)}return!0}async handleContractVerified(e){let r=e.payload;(r?.contractType==="soap"||r?.contractType==="odata")&&await this.memory.set(`enterprise-integration:contract-event:${Date.now()}`,{contractId:r.contractId,type:r.contractType,passed:r.passed,timestamp:new Date().toISOString()},{namespace:"enterprise-integration",ttl:86400})}async handleFaultInjected(e){let r=e.payload;(r?.targetService?.includes("middleware")||r?.targetService?.includes("esb"))&&Da.info(`Middleware fault injection detected: ${r.targetService}`)}};var ml=class extends j{constructor(e,r,i,n={}){super(e,r);this.agentCoordinator=i;this.pluginConfig=n}agentCoordinator;coordinator=null;pluginConfig;get name(){return"enterprise-integration"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{validateWsdl:this.validateWsdl.bind(this),testSoapOperation:this.testSoapOperation.bind(this),testMessageFlow:this.testMessageFlow.bind(this),testDlqHandling:this.testDlqHandling.bind(this),testBapiCall:this.testBapiCall.bind(this),validateIdoc:this.validateIdoc.bind(this),validateODataMetadata:this.validateODataMetadata.bind(this),testODataEntitySet:this.testODataEntitySet.bind(this),validateMessageFlow:this.validateMessageFlow.bind(this),validateTransformation:this.validateTransformation.bind(this),analyzeSod:this.analyzeSod.bind(this),getCoordinator:()=>this.coordinator,getActiveWorkflows:()=>this.coordinator?.getActiveWorkflows()||[]}}getTaskHandlers(){return new Map([["enterprise-integration:soap-test",async e=>{if(!this.coordinator)return p(new Error("Enterprise integration coordinator not initialized"));let r=e.wsdl,i=e.operation,n=e.input;return e.url&&!r?this.coordinator.validateWsdl(e.url):!r||!i?p(new Error("Invalid soap-test payload: missing wsdl or operation")):this.coordinator.testSoapOperation(r,i,n)}],["enterprise-integration:message-broker-test",async e=>{if(!this.coordinator)return p(new Error("Enterprise integration coordinator not initialized"));let r=e.brokerConfig,i=e.testCase,n=e.queue;return r?n&&!i?this.coordinator.testDlqHandling(r,n):i?this.coordinator.testMessageFlow(r,i):p(new Error("Invalid message-broker-test payload: missing testCase")):p(new Error("Invalid message-broker-test payload: missing brokerConfig"))}],["enterprise-integration:sap-rfc-test",async e=>{if(!this.coordinator)return p(new Error("Enterprise integration coordinator not initialized"));let r=e.connection,i=e.bapi;return!r||!i?p(new Error("Invalid sap-rfc-test payload: missing connection or bapi")):this.coordinator.testBapiCall(r,i)}],["enterprise-integration:sap-idoc-validate",async e=>{if(!this.coordinator)return p(new Error("Enterprise integration coordinator not initialized"));let r=e.definition,i=e.content;return!r||!i?p(new Error("Invalid sap-idoc-validate payload: missing definition or content")):this.coordinator.validateIdoc(r,i)}],["enterprise-integration:odata-test",async e=>{if(!this.coordinator)return p(new Error("Enterprise integration coordinator not initialized"));let r=e.serviceUrl,i=e.metadata,n=e.entitySet;return r&&!i?this.coordinator.validateODataMetadata(r):!i||!n?p(new Error("Invalid odata-test payload: missing metadata or entitySet")):this.coordinator.testODataEntitySet(i,n)}],["enterprise-integration:esb-flow-test",async e=>{if(!this.coordinator)return p(new Error("Enterprise integration coordinator not initialized"));let r=e.flow,i=e.input,n=e.spec;if(n){let s=e.transformInput,a=e.expectedOutput;return!s||!a?p(new Error("Invalid esb-flow-test payload: missing transformInput or expectedOutput for transformation")):this.coordinator.validateTransformation(n,s,a)}return!r||!i?p(new Error("Invalid esb-flow-test payload: missing flow or input")):this.coordinator.validateMessageFlow(r,i)}],["enterprise-integration:sod-analyze",async e=>{if(!this.coordinator)return p(new Error("Enterprise integration coordinator not initialized"));let r=e.userId,i=e.ruleset;return!r||!i?p(new Error("Invalid sod-analyze payload: missing userId or ruleset")):this.coordinator.analyzeSod(r,i)}]])}async onInitialize(){this.coordinator=new Ia(this.eventBus,this.memory,this.agentCoordinator,this.pluginConfig.coordinator),await this.coordinator.initialize(),this.updateHealth({status:"idle",agents:{total:0,active:0,idle:0,failed:0},lastActivity:new Date,errors:[]})}async onDispose(){this.coordinator&&await this.coordinator.dispose(),this.coordinator=null}subscribeToEvents(){this.eventBus.subscribe("contract-testing.ContractVerified",this.handleContractVerified.bind(this)),this.eventBus.subscribe("quality-assessment.QualityGateEvaluated",this.handleQualityGate.bind(this)),this.eventBus.subscribe("chaos-resilience.FaultInjected",this.handleFaultInjected.bind(this))}async onEvent(e){switch(this.updateHealth({lastActivity:new Date}),e.type){case"contract-testing.ContractVerified":await this.handleContractVerified(e);break;case"quality-assessment.QualityGateEvaluated":await this.handleQualityGate(e);break;case"chaos-resilience.FaultInjected":await this.handleFaultInjected(e);break;default:break}}async validateWsdl(e){this.ensureInitialized();try{let r=await this.coordinator.validateWsdl(e);return r.success?this.trackSuccessfulOperation("validateWsdl"):this.trackFailedOperation(new Error(r.error.message)),r}catch(r){return this.handleError(r)}}async testSoapOperation(e,r,i){this.ensureInitialized();try{let n=await this.coordinator.testSoapOperation(e,r,i);return n.success?this.trackSuccessfulOperation("testSoapOperation"):this.trackFailedOperation(new Error(n.error.message)),n}catch(n){return this.handleError(n)}}async testMessageFlow(e,r){this.ensureInitialized();try{let i=await this.coordinator.testMessageFlow(e,r);return i.success?this.trackSuccessfulOperation("testMessageFlow"):this.trackFailedOperation(new Error(i.error.message)),i}catch(i){return this.handleError(i)}}async testDlqHandling(e,r){this.ensureInitialized();try{let i=await this.coordinator.testDlqHandling(e,r);return i.success?this.trackSuccessfulOperation("testDlqHandling"):this.trackFailedOperation(new Error(i.error.message)),i}catch(i){return this.handleError(i)}}async testBapiCall(e,r){this.ensureInitialized();try{let i=await this.coordinator.testBapiCall(e,r);return i.success?this.trackSuccessfulOperation("testBapiCall"):this.trackFailedOperation(new Error(i.error.message)),i}catch(i){return this.handleError(i)}}async validateIdoc(e,r){this.ensureInitialized();try{let i=await this.coordinator.validateIdoc(e,r);return i.success?this.trackSuccessfulOperation("validateIdoc"):this.trackFailedOperation(new Error(i.error.message)),i}catch(i){return this.handleError(i)}}async validateODataMetadata(e){this.ensureInitialized();try{let r=await this.coordinator.validateODataMetadata(e);return r.success?this.trackSuccessfulOperation("validateODataMetadata"):this.trackFailedOperation(new Error(r.error.message)),r}catch(r){return this.handleError(r)}}async testODataEntitySet(e,r){this.ensureInitialized();try{let i=await this.coordinator.testODataEntitySet(e,r);return i.success?this.trackSuccessfulOperation("testODataEntitySet"):this.trackFailedOperation(new Error(i.error.message)),i}catch(i){return this.handleError(i)}}async validateMessageFlow(e,r){this.ensureInitialized();try{let i=await this.coordinator.validateMessageFlow(e,r);return i.success?this.trackSuccessfulOperation("validateMessageFlow"):this.trackFailedOperation(new Error(i.error.message)),i}catch(i){return this.handleError(i)}}async validateTransformation(e,r,i){this.ensureInitialized();try{let n=await this.coordinator.validateTransformation(e,r,i);return n.success?this.trackSuccessfulOperation("validateTransformation"):this.trackFailedOperation(new Error(n.error.message)),n}catch(n){return this.handleError(n)}}async analyzeSod(e,r){this.ensureInitialized();try{let i=await this.coordinator.analyzeSod(e,r);return i.success?this.trackSuccessfulOperation("analyzeSod"):this.trackFailedOperation(new Error(i.error.message)),i}catch(i){return this.handleError(i)}}async handleContractVerified(e){let r=e.payload;(r.contractType==="soap"||r.contractType==="odata")&&await this.memory.set(`enterprise-integration:contract-verified:${r.contractId}`,{contractId:r.contractId,type:r.contractType,passed:r.passed,timestamp:new Date().toISOString()},{namespace:"enterprise-integration",ttl:86400})}async handleQualityGate(e){let r=e.payload;r.checks.find(n=>n.name==="enterprise-integration")||await this.memory.set(`enterprise-integration:quality-gate-warning:${r.gateId}`,{warning:"Enterprise integration testing not included in quality gate",timestamp:new Date().toISOString()},{namespace:"enterprise-integration",ttl:86400})}async handleFaultInjected(e){let r=e.payload;(r.targetService?.includes("middleware")||r.targetService?.includes("esb")||r.targetService?.includes("broker")||r.targetService?.includes("mq"))&&await this.memory.set(`enterprise-integration:fault-correlation:${r.faultId||Date.now()}`,{targetService:r.targetService,faultType:r.faultType,timestamp:new Date().toISOString()},{namespace:"enterprise-integration",ttl:3600})}ensureInitialized(){if(!this._initialized)throw new Error("EnterpriseIntegrationPlugin is not initialized");if(!this.coordinator)throw new Error("EnterpriseIntegrationPlugin coordinator is not available")}handleError(e){let r=y(e),i=this.getHealth();return this.updateHealth({errors:[...i.errors.slice(-9),r.message],status:i.errors.length>=5?"degraded":i.status}),{success:!1,error:r}}trackSuccessfulOperation(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,total:r.agents.total+1,idle:r.agents.idle+1},lastActivity:new Date})}trackFailedOperation(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,failed:r.agents.failed+1},errors:[...r.errors.slice(-9),e.message]})}};function Um(u,t,e,r){return new ml(u,t,e,r)}var Km={"test-generation":(u,t,e,r)=>Lo(u,t,e,void 0,r),"test-execution":(u,t,e,r)=>qu(u,t,r),"coverage-analysis":(u,t,e,r)=>oc(u,t,r),"quality-assessment":(u,t,e,r)=>yc(u,t,e,void 0,r),"defect-intelligence":(u,t,e,r)=>Td(u,t,e,void 0,r),"requirements-validation":(u,t,e,r)=>Pd(u,t,e,void 0,r),"code-intelligence":(u,t,e,r)=>Mc(u,t,e,void 0,r),"security-compliance":(u,t,e,r)=>tl(u,t,e,void 0,r),"contract-testing":(u,t,e,r)=>fm(u,t,e,void 0,r),"visual-accessibility":(u,t,e,r)=>Im(u,t,e,void 0,r),"chaos-resilience":(u,t,e,r)=>Lm(u,t,e,void 0,r),"learning-optimization":(u,t,e,r)=>Hm(u,t,e,void 0,r),"enterprise-integration":(u,t,e,r)=>Um(u,t,e),coordination:(u,t,e,r)=>jm(u,t,e)},mb={maxConcurrentAgents:Lr.MAX_CONCURRENT_AGENTS,memoryBackend:"hybrid",hnswEnabled:!0,lazyLoading:!0,enabledDomains:[...we],dataDir:void 0,enableExperienceBridge:!0,enableDreamScheduler:!0},pl=class{_eventBus;_coordinator;_plugins;_memory;_config;_startTime;_initialized=!1;_loopTracker;_experienceBridge;_dreamScheduler;_llmRouter;_llmRouterBuild;constructor(t={}){this._config={...mb,...t},this._startTime=new Date,this._memory=new Oa,this._eventBus=new pn,this._coordinator=new hn(this._config.maxConcurrentAgents),this._plugins=new Gr(this._eventBus,this._memory,this._config.lazyLoading),this._loopTracker=new gn}get eventBus(){return this._eventBus}get coordinator(){return this._coordinator}get plugins(){return this._plugins}get memory(){return this._memory}get llmRouter(){return this._llmRouter}async initialize(){if(this._initialized)return;let t=fl(),e=this._config.dataDir||Jt.join(t,".agentic-qe");if(Ma.existsSync(e)||Ma.mkdirSync(e,{recursive:!0}),this._config.memoryBackend==="memory"){let i=Jt.join(Fa("os").tmpdir(),`aqe-test-${Date.now()}-${Qm().slice(0,12)}.db`);await vl({dbPath:i})}else this._memory=new yl({sqlite:{path:Jt.join(e,"memory.db"),walMode:!0,poolSize:3,busyTimeout:gl.BUSY_TIMEOUT_MS},enableFallback:!0,defaultNamespace:"qe-kernel"}),this._plugins=new Gr(this._eventBus,this._memory,this._config.lazyLoading);await this._initializeLLMRouter(t);for(let i of this._config.enabledDomains){let n=Km[i];n&&this._plugins.registerFactory(i,async(s,a)=>Promise.resolve(n(s,a,this._coordinator,this._llmRouter)))}await this._memory.initialize();let r=new yn({agentId:"qe-kernel"});this._eventBus.registerMiddleware(r);try{let i=Jt.join(e,"plugins"),n=new bl({cacheDir:i}),a=new wl({cache:n}).resolveLoadOrder();for(let o of a.ordered){let c=o.manifest,l=n.get(c.name,c.version);if(!l)continue;let d=Jt.join(l.path,c.entryPoint);for(let m of c.domains){let h=m;if(Km[h])continue;this._plugins.registerFactory(h,async(b,w)=>{let C=await import(d),S=C.default??C.createPlugin;if(typeof S!="function")throw new Error(`Plugin "${c.name}" entry point must export a default function or "createPlugin" function`);return S(b,w,this._coordinator,this._llmRouter)})}}}catch{}this._config.lazyLoading||await this._plugins.loadAll();try{let{isAgentMemoryBranchingEnabled:i,isRVFPatternStoreEnabled:n}=await import("./feature-flags-X5WBBWSO.js");if(i()&&n()){let{getSharedRvfAdapter:s}=await import("./shared-rvf-adapter-4IZOJL33.js"),{AgentMemoryBranch:a}=await import("./agent-memory-branch-OLOF5ZHV.js"),o=s(e,384);if(o){let c=new a(o,{branchDir:Jt.join(e,"branches")});this._coordinator.setMemoryBranch(c)}}}catch{}try{let{getRvfMigrationStage:i}=await import("./feature-flags-X5WBBWSO.js"),n=i();if(n>=2){let{RvfMigrationCoordinator:s}=await import("./rvf-migration-coordinator-2NDCWP7F.js");await s.getInstance({stage:n}).initialize()}}catch{}if(this._config.enableExperienceBridge!==!1){try{await this._plugins.loadAll()}catch(i){console.warn("[QEKernel] domain plugin pre-load (for bridge subscribers) failed:",i instanceof Error?i.message:i)}try{this._experienceBridge=new vn(this._eventBus,this._memory),await this._experienceBridge.start()}catch(i){console.warn("[QEKernel] CapturedExperienceBridge failed to start:",i instanceof Error?i.message:i),this._experienceBridge=void 0}}if(this._config.enableDreamScheduler!==!1)try{let i=tn({maxDurationMs:1e4,minConceptsRequired:3});await i.initialize(),this._dreamScheduler=new Al({dreamEngine:i,eventBus:this._eventBus,memoryBackend:this._memory}),await this._dreamScheduler.initialize(),this._dreamScheduler.start()}catch(i){if(console.warn("[QEKernel] DreamScheduler failed to start:",i instanceof Error?i.message:i),this._dreamScheduler)try{await this._dreamScheduler.dispose()}catch{}this._dreamScheduler=void 0}this._initialized=!0}async _initializeLLMRouter(t){let e=(process.env.AQE_LLM_ROUTER_DISABLED??"").trim().toLowerCase();if(e&&e!=="false"&&e!=="0"&&e!=="no"&&e!=="off"){this._llmRouter=void 0;return}let r=this._config.llmRouter??{},i=r.enabled??"auto";if(i===!1){this._llmRouter=void 0;return}try{let n=await Tl({projectRoot:t,override:r.configOverride,providerManager:r.providerManager});if(!n){i===!0&&(console.warn("[QEKernel] llmRouter.enabled=true but no provider available \u2014 continuing without LLM router (domain services will skip LLM enhancement)"),await this._publishLLMRouterEvent("init-no-provider",{reason:"no provider available in env or disk config"})),this._llmRouter=void 0;return}this._llmRouterBuild=n,this._llmRouter=n.router;try{let{setSharedLLMRouter:s}=await import("./base-AOQNGMTL.js");s(n.router)}catch{}}catch(n){let s=n instanceof Error?n.message:String(n);console.warn("[QEKernel] LLM router init failed; continuing without LLM enhancement:",s),await this._publishLLMRouterEvent("init-failed",{error:s,stack:n instanceof Error?n.stack:void 0}),this._llmRouter=void 0}}async _publishLLMRouterEvent(t,e){try{await this._eventBus.publish({id:Qm(),type:`kernel.llm-router.${t}`,timestamp:new Date,source:"qe-kernel",payload:e})}catch{}}async dispose(){if(this._dreamScheduler){try{await this._dreamScheduler.dispose()}catch(t){console.warn("[QEKernel] DreamScheduler dispose failed:",t instanceof Error?t.message:t)}this._dreamScheduler=void 0}if(this._experienceBridge&&(await this._experienceBridge.stop(),this._experienceBridge=void 0),await this._plugins.disposeAll(),await this._coordinator.dispose(),await this._eventBus.dispose(),await this._memory.dispose(),this._llmRouter){try{let{resetSharedLLMRouter:t}=await import("./base-AOQNGMTL.js");t()}catch{}this._llmRouter=void 0,this._llmRouterBuild=void 0}this._initialized=!1}getDomainAPI(t){return this._plugins.getPlugin(t)?.getAPI()}async getDomainAPIAsync(t){let e=this._plugins.getPlugin(t);if(!e&&this._config.lazyLoading&&this._config.enabledDomains.includes(t))try{e=await this._plugins.load(t)}catch(r){console.error(`[QEKernel] Failed to lazy load domain ${t}:`,r);return}return e?.getAPI()}async ensureDomainLoaded(t){if(this._plugins.isLoaded(t))return!0;if(!this._config.enabledDomains.includes(t))return console.warn(`[QEKernel] Domain ${t} is not enabled`),!1;try{return await this._plugins.load(t),!0}catch(e){return console.error(`[QEKernel] Failed to load domain ${t}:`,e),!1}}isDomainLoaded(t){return this._plugins.isLoaded(t)}getLoadedDomains(){return this._plugins.getLoaded()}getPendingDomains(){let t=new Set(this._plugins.getLoaded());return this._config.enabledDomains.filter(e=>!t.has(e))}getHealth(){let t=this._coordinator.listAgents(),e={};for(let c of this._plugins.getLoaded()){let l=this._plugins.getPlugin(c);l&&(e[c]=l.getHealth())}for(let c of we)if(!e[c]){let l=this._config.enabledDomains.includes(c),d=this._config.lazyLoading&&l;e[c]={status:d?"healthy":l?"degraded":"healthy",agents:{total:0,active:0,idle:0,failed:0},errors:d?[]:l?["Domain not yet loaded"]:[],loaded:!1,lazyLoadable:d}}let r=this._coordinator.getActiveCount(),i=0,n=Number.MAX_SAFE_INTEGER;if(this._memory instanceof Oa){let c=this._memory.getStats();i=c.entries+c.vectors}else i=0;let a=this._eventBus.getMiddlewares().find(c=>c.name==="semantic-anti-drift"),o=a?a.getStats():void 0;return{status:this.determineOverallStatus(e),uptime:Date.now()-this._startTime.getTime(),domains:e,agents:{total:t.length,active:r,maxAllowed:this._config.maxConcurrentAgents},memory:{used:i,available:n},...o?{antiDrift:o}:{}}}determineOverallStatus(t){let e=Object.values(t).map(r=>r.status);return e.some(r=>r==="unhealthy")?"unhealthy":e.some(r=>r==="degraded")?"degraded":"healthy"}getConfig(){return{...this._config}}checkToolCall(t,e,r){if(process.env.AQE_LOOP_DETECTION_ENABLED==="false")return this._loopTracker.trackCall(t,e,r);let i=this._loopTracker.trackCall(t,e,r);if(i.action==="warn"){let n={id:`loop-warn-${t}-${Date.now()}`,type:Wa.LOOP_WARNING,timestamp:new Date,source:"coordination",correlationId:t,payload:{agentId:t,toolName:e,callCount:i.callCount,signature:i.signature}};this._eventBus.publish(n)}else if(i.action==="steer"){let n={id:`loop-detected-${t}-${Date.now()}`,type:Wa.LOOP_DETECTED,timestamp:new Date,source:"coordination",correlationId:t,payload:{agentId:t,toolName:e,callCount:i.callCount,signature:i.signature,steeringMessage:i.steeringMessage}};this._eventBus.publish(n)}return i}get loopTracker(){return this._loopTracker}};function L6(u){return new pl(u)}export{Ja as a,mp as b,er as c,ai as d,ht as e,lr as f,mr as g,_t as h,Dc as i,$c as j,Us as k,Tr as l,Ar as m,Ca as n,Pr as o,Dr as p,jt as q,Wt as r,Ut as s,Ee as t,xe as u,pl as v,L6 as w};
|
|
3027
|
+
// Execute action: {{action}}`,variables:r}}extractPatternContext(t){let e=new Set,r,i;for(let n of t){let s=n.state.context;if(s.language&&(r=s.language),s.framework&&(i=s.framework),s.tags&&Array.isArray(s.tags))for(let a of s.tags)e.add(a)}return{language:r,framework:i,tags:Array.from(e)}}calculateConsolidatedConfidence(t){let e=t.reduce((i,n)=>i+n.usageCount,0),r=0;for(let i of t){let n=e>0?i.usageCount/e:1/t.length;r+=i.confidence*n}return r}calculateWeightedSuccessRate(t){let e=t.reduce((i,n)=>i+n.usageCount,0),r=0;for(let i of t){let n=e>0?i.usageCount/e:1/t.length;r+=i.successRate*n}return r}detectAnomalies(t){let e=[],r=this.calculateAverageReward(t),i=this.calculateStdDev(t.map(n=>n.reward));for(let n of t){let s=Math.abs(n.reward-r)/(i||1);if(s>this.config.anomalyDeviationThreshold){let a="outlier-reward";n.result.success&&n.reward<r?a="unexpected-success":!n.result.success&&n.reward>r&&(a="unexpected-failure"),e.push({experienceId:n.id,type:a,description:`Reward ${n.reward.toFixed(2)} deviates ${s.toFixed(2)} std from mean ${r.toFixed(2)}`,deviation:s})}}return e}calculateStdDev(t){if(t.length===0)return 0;let e=t.reduce((i,n)=>i+n,0)/t.length,r=t.map(i=>Math.pow(i-e,2));return Math.sqrt(r.reduce((i,n)=>i+n,0)/t.length)}generateRecommendations(t,e,r){let i=[];return e<.5&&i.push("Low success rate detected. Consider reviewing the approach or gathering more training data."),r.length>t.length*.1&&i.push("High anomaly rate detected. Investigate unexpected outcomes for potential improvements."),t.reduce((s,a)=>s+a.result.duration,0)/t.length>6e4&&i.push("Average operation duration is high. Consider optimizing performance."),t.length<10&&i.push("Limited experience data. Collect more data points for better insights."),i.length===0&&i.push("Performance metrics are within acceptable ranges. Continue monitoring."),i}actionsSimilar(t,e){let r=s=>s.toLowerCase().replace(/[^a-z]/g,""),i=r(t),n=r(e);return!!(i===n||i.includes(n)||n.includes(i))}calculateCentroid(t){let e={},r={};for(let i of t)for(let[n,s]of Object.entries(i.state.metrics))e[n]=(e[n]||0)+s,r[n]=(r[n]||0)+1;for(let i of Object.keys(e))e[i]/=r[i];return{context:{},metrics:e}}isConstraintViolated(t,e){switch(t.operator){case"lt":return e>=t.value;case"gt":return e<=t.value;case"lte":return e>t.value;case"gte":return e<t.value;case"eq":return e!==t.value;default:return!1}}};A();var eb={maxKnowledgeItems:1e3,relevanceThreshold:.5,transferDecayFactor:.1,crossDomainBoost:.2},Wt=class{constructor(t,e={}){this.memory=t;this.config={...eb,...e}}memory;config;async shareKnowledge(t,e){try{await this.memory.set(`learning:knowledge:shared:${t.id}`,t,{namespace:"learning-optimization",persist:!0});for(let r of e)await this.memory.set(`learning:knowledge:access:${r.value}:${t.id}`,{knowledgeId:t.id,agentId:r.value,sharedAt:new Date,accessed:!1},{namespace:"learning-optimization",ttl:86400*7});return await this.recordSharingEvent(t,e),f(void 0)}catch(r){return p(y(r))}}async queryKnowledge(t){try{let e=[],r;t.domain?r=await this.memory.search(`learning:knowledge:*:${t.domain}:*`,t.limit||100):r=await this.memory.search("learning:knowledge:shared:*",t.limit||100);for(let i of r){let n=ae(await this.memory.get(i),["createdAt","expiresAt"]);n&&this.matchesQuery(n,t)&&e.push(n)}if(e.sort((i,n)=>n.relevanceScore-i.relevanceScore),t.embedding&&t.embedding.length>0){let i=await this.memory.vectorSearch(t.embedding,t.limit||10);for(let n of i){let s=ae(await this.memory.get(n.key),["createdAt","expiresAt"]);s&&!e.some(a=>a.id===s.id)&&this.matchesQuery(s,t)&&e.push(s)}}return f(e.slice(0,t.limit||100))}catch(e){return p(y(e))}}async synthesizeKnowledge(t){try{if(t.length<2)return p(new Error("Need at least 2 knowledge items to synthesize"));let e=[];for(let c of t){let l=await this.getKnowledgeById(c);l&&e.push(l)}if(e.length<2)return p(new Error("Not enough valid knowledge items found"));let r=this.determineSynthesizedType(e),i=this.determineSynthesizedDomain(e),n=this.mergeKnowledgeContent(e),s=e.reduce((c,l)=>c+l.relevanceScore,0)/e.length,a=Math.min(1,s+this.config.crossDomainBoost),o={id:v(),type:r,domain:i,content:n,sourceAgentId:e[0].sourceAgentId,targetDomains:this.mergeTargetDomains(e),relevanceScore:a,version:1,createdAt:new Date};return await this.storeKnowledge(o),await this.recordSynthesisEvent(o,t),f(o)}catch(e){return p(y(e))}}async transferKnowledge(t,e){try{if(t.domain===e)return p(new Error("Cannot transfer knowledge to the same domain"));let r=this.calculateTransferredRelevance(t,e);if(r<this.config.relevanceThreshold)return p(new Error(`Transferred relevance ${r} below threshold ${this.config.relevanceThreshold}`));let i=await this.adaptContentForDomain(t.content,t.domain,e),n={id:v(),type:t.type,domain:e,content:i,sourceAgentId:t.sourceAgentId,targetDomains:[e],relevanceScore:r,version:t.version+1,createdAt:new Date};return await this.storeKnowledge(n),await this.recordTransferEvent(t,n),f(n)}catch(r){return p(y(r))}}async validateRelevance(t,e){try{let r=t.relevanceScore;if(e.language&&t.content.metadata?.language===e.language&&(r+=.1),e.framework&&t.content.metadata?.framework===e.framework&&(r+=.1),e.tags.length>0&&t.content.metadata?.tags){let a=t.content.metadata.tags,o=e.tags.filter(c=>a.includes(c));r+=o.length/e.tags.length*.2}let n=(Date.now()-t.createdAt.getTime())/(1e3*60*60*24),s=Math.exp(-this.config.transferDecayFactor*n/30);return r*=s,t.expiresAt&&new Date>t.expiresAt&&(r*=.5),f(Math.min(1,Math.max(0,r)))}catch(r){return p(y(r))}}async createKnowledge(t,e,r,i,n=[],s){try{let a={id:v(),type:t,domain:e,content:{format:this.inferContentFormat(r),data:r,metadata:s},sourceAgentId:i,targetDomains:n,relevanceScore:1,version:1,createdAt:new Date};return await this.storeKnowledge(a),t==="embedding"&&Array.isArray(r)&&await this.memory.storeVector(`learning:knowledge:vector:${a.id}`,r,{knowledgeId:a.id}),f(a)}catch(a){return p(y(a))}}async getKnowledgeById(t){return ae(await this.memory.get(`learning:knowledge:shared:${t}`),["createdAt","expiresAt"])||null}async bulkTransfer(t,e,r){try{let i=await this.memory.search(`learning:knowledge:project:${t}:*`,500),n=[];for(let s of i){let a=ae(await this.memory.get(s),["createdAt","expiresAt"]);if(!a||r?.types&&!r.types.includes(a.type)||r?.minRelevance&&a.relevanceScore<r.minRelevance)continue;let o=await this.adaptContentForProject(a.content,t,e),c={...a,id:v(),content:o,relevanceScore:a.relevanceScore*(1-this.config.transferDecayFactor),version:a.version+1,createdAt:new Date};await this.memory.set(`learning:knowledge:project:${e}:${c.id}`,c,{namespace:"learning-optimization",persist:!0}),n.push({knowledgeId:c.id,sourceDomain:a.domain,targetDomain:a.domain,originalRelevance:a.relevanceScore,transferredRelevance:c.relevanceScore,adaptations:["project-context-adapted"]})}return f(n)}catch(i){return p(y(i))}}async storeKnowledge(t){await this.memory.set(`learning:knowledge:shared:${t.id}`,t,{namespace:"learning-optimization",persist:!0}),await this.memory.set(`learning:knowledge:domain:${t.domain}:${t.id}`,t.id,{namespace:"learning-optimization",persist:!0}),await this.memory.set(`learning:knowledge:type:${t.type}:${t.id}`,t.id,{namespace:"learning-optimization",persist:!0})}matchesQuery(t,e){if(e.type&&t.type!==e.type||e.domain&&t.domain!==e.domain||e.minRelevance!==void 0&&t.relevanceScore<e.minRelevance)return!1;if(e.tags&&e.tags.length>0){let r=t.content.metadata?.tags||[];if(!e.tags.some(n=>r.includes(n)))return!1}return!0}determineSynthesizedType(t){let e=new Map;for(let n of t)e.set(n.type,(e.get(n.type)||0)+1);let r=t[0].type,i=0;for(let[n,s]of e)s>i&&(i=s,r=n);return r}determineSynthesizedDomain(t){let e=new Map;for(let n of t)e.set(n.domain,(e.get(n.domain)||0)+1);let r=t[0].domain,i=0;for(let[n,s]of e)s>i&&(i=s,r=n);return r}mergeKnowledgeContent(t){let e={},r=[];for(let i of t)if(r.push(i.content.data),i.content.metadata)for(let[n,s]of Object.entries(i.content.metadata))if(Array.isArray(s)){let a=e[n]||[];e[n]=[...new Set([...a,...s])]}else e[n]=s;return{format:"json",data:{synthesized:!0,sources:r},metadata:{...e,synthesizedFrom:t.map(i=>i.id),synthesizedAt:new Date().toISOString()}}}mergeTargetDomains(t){let e=new Set;for(let r of t){e.add(r.domain);for(let i of r.targetDomains)e.add(i)}return Array.from(e)}calculateTransferredRelevance(t,e){let r=t.relevanceScore;r*=1-this.config.transferDecayFactor;let i=this.getDomainCompatibility(t.domain,e);return r*=i,t.targetDomains.includes(e)&&(r+=this.config.crossDomainBoost),Math.min(1,Math.max(0,r))}getDomainCompatibility(t,e){let r={"test-generation":["test-execution","coverage-analysis"],"test-execution":["test-generation","coverage-analysis","quality-assessment"],"coverage-analysis":["test-generation","test-execution","quality-assessment"],"quality-assessment":["test-execution","coverage-analysis","defect-intelligence"],"defect-intelligence":["quality-assessment","code-intelligence"],"requirements-validation":["test-generation","quality-assessment"],"code-intelligence":["defect-intelligence","security-compliance"],"security-compliance":["code-intelligence","quality-assessment"],"contract-testing":["test-generation","test-execution"],"visual-accessibility":["quality-assessment"],"chaos-resilience":["test-execution","quality-assessment"],"learning-optimization":["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence"],"enterprise-integration":["contract-testing","security-compliance","quality-assessment"],coordination:we.filter(i=>i!=="coordination")};return t===e?1:r[t]?.includes(e)?.8:.5}async adaptContentForDomain(t,e,r){return{...t,metadata:{...t.metadata||{},adaptedFrom:e,adaptedTo:r,adaptedAt:new Date().toISOString()}}}async adaptContentForProject(t,e,r){return{...t,metadata:{...t.metadata||{},sourceProject:e,targetProject:r,transferredAt:new Date().toISOString()}}}inferContentFormat(t){return typeof t=="string"?"text":Array.isArray(t)&&t.every(e=>typeof e=="number")?"embedding":"json"}async recordSharingEvent(t,e){await this.memory.set(`learning:knowledge:events:share:${t.id}:${Date.now()}`,{type:"share",knowledgeId:t.id,targetAgents:e.map(r=>r.value),timestamp:new Date},{namespace:"learning-optimization",ttl:86400*30})}async recordSynthesisEvent(t,e){await this.memory.set(`learning:knowledge:events:synthesis:${t.id}`,{type:"synthesis",synthesizedId:t.id,sourceIds:e,timestamp:new Date},{namespace:"learning-optimization",ttl:86400*30})}async recordTransferEvent(t,e){await this.memory.set(`learning:knowledge:events:transfer:${e.id}`,{type:"transfer",originalId:t.id,transferredId:e.id,originalDomain:t.domain,targetDomain:e.domain,timestamp:new Date},{namespace:"learning-optimization",ttl:86400*30})}};A();se();var tb={defaultConfidenceLevel:.95,minSamplesForOptimization:20,maxOptimizationIterations:100,improvementThreshold:.05,explorationRate:.1},rb=["__proto__","constructor","prototype"];function Yi(u){return!rb.includes(u)}var Ut=class{constructor(t,e={}){this.memory=t;this.config={...tb,...e}}memory;config;async optimizeStrategy(t,e,r){try{if(r.length<this.config.minSamplesForOptimization)return p(new Error(`Need at least ${this.config.minSamplesForOptimization} experiences for optimization`));let i=this.evaluateStrategyPerformance(t,r,e),n=await this.optimizeParameters(t.parameters,r,e),s={name:`${t.name}-optimized`,parameters:n,expectedOutcome:this.predictOutcome(n,r)},a=await this.validateOptimization(t,s,r.slice(-10)),o=this.evaluateStrategyPerformance(s,r,e),c=this.calculateImprovement(i,o,e),l=this.calculateOptimizationConfidence(r.length,c,a),d=this.inferDomainFromExperiences(r),m={id:v(),domain:d,objective:e,currentStrategy:t,optimizedStrategy:s,improvement:c,confidence:l,validationResults:a};return await this.storeOptimizationResult(m),f(m)}catch(i){return p(y(i))}}async runABTest(t,e,r){try{let i=await this.collectStrategyMetrics(t,r.metric,r.minSamples),n=await this.collectStrategyMetrics(e,r.metric,r.minSamples),s=this.calculateMean(i),a=this.calculateMean(n),o=this.calculateStdDev(i),c=this.calculateStdDev(n),l=this.calculatePValue(i,n),d;l<1-r.confidenceLevel?d=s>a?"A":"B":d="inconclusive";let m={winner:d,strategyAMetrics:{[r.metric]:s,stdDev:o,samples:i.length},strategyBMetrics:{[r.metric]:a,stdDev:c,samples:n.length},pValue:l,sampleSizeA:i.length,sampleSizeB:n.length};return await this.storeABTestResult(t,e,m),f(m)}catch(i){return p(y(i))}}async recommendStrategy(t){try{let e=await this.memory.search("learning:strategy:optimized:*",100),r=[];for(let i of e){let n=await this.memory.get(i);if(n&&n.confidence>.6){let s=this.scoreContextMatch(n,t),a=n.improvement*n.confidence;r.push({strategy:n.optimizedStrategy,score:s*.4+a*.6})}}return r.length===0?f({name:"default-strategy",parameters:this.getDefaultParameters(t),expectedOutcome:{success_rate:.7}}):(r.sort((i,n)=>n.score-i.score),f(r[0].strategy))}catch(e){return p(y(e))}}async evaluateStrategy(t,e){try{let r={},i=this.calculateSuccessRate(e),n=this.calculateAverageDuration(e),s=this.calculateAverageReward(e);r.success_rate=i,r.avg_duration_ms=n,r.avg_reward=s;let a=[];i>.8&&a.push("High success rate"),n<5e3&&a.push("Fast execution"),s>.7&&a.push("Consistently good rewards");let o=[];i<.5&&o.push("Low success rate needs investigation"),n>3e4&&o.push("Slow execution time"),s<.3&&o.push("Low reward values");let c=this.identifyImprovementAreas(t,r,e),l={strategy:t,metrics:r,strengths:a,weaknesses:o,improvementAreas:c};return await this.storeStrategyEvaluation(l),f(l)}catch(r){return p(y(r))}}async trackMetrics(t,e){try{let r={strategyId:t,metrics:e,timestamp:new Date,samples:1},i=`learning:metrics:history:${t}:${Date.now()}`;return await this.memory.set(i,r,{namespace:"learning-optimization",ttl:86400*30}),await this.updateAggregatedMetrics(t,e),f(void 0)}catch(r){return p(y(r))}}async getMetricsHistory(t,e=100){try{let r=await this.memory.search(`learning:metrics:history:${t}:*`,e),i=[];for(let n of r){let s=ae(await this.memory.get(n),["timestamp"]);s&&i.push(s)}return i.sort((n,s)=>n.timestamp.getTime()-s.timestamp.getTime()),f(i)}catch(r){return p(y(r))}}async gridSearchOptimize(t,e,r){try{let i=this.generateParameterCombinations(t),n={},s=e.direction==="maximize"?-1/0:1/0;for(let a of i){let o=this.scoreParameters(a,r,e);(e.direction==="maximize"?o>s:o<s)&&(s=o,n=a)}return f(n)}catch(i){return p(y(i))}}evaluateStrategyPerformance(t,e,r){let i=0,n=0;for(let s of e){let a=s.result.outcome[r.metric]??0;i+=a,n++}return n>0?i/n:0}async optimizeParameters(t,e,r){let i={...t};for(let[n,s]of Object.entries(t))if(Yi(n)&&typeof s=="number"){let a=[-.1,-.05,0,.05,.1],o=0,c=this.scoreParameters(i,e,r);for(let l of a){let d={...i,[n]:s*(1+l)},m=this.scoreParameters(d,e,r);(r.direction==="maximize"?m>c:m<c)&&(c=m,o=l)}i[n]=s*(1+o)}return i}scoreParameters(t,e,r){let i=0,n=0;for(let s of e){let a=s.result.success?1:.5,o=this.calculateParamSimilarity(t,s.state.context),c=s.result.outcome[r.metric]??0;i+=o*c*a,n+=a}return n>0?i/n:0}calculateParamSimilarity(t,e){let r=0,i=0;for(let[n,s]of Object.entries(t))if(e[n]!==void 0)if(i++,typeof s=="number"&&typeof e[n]=="number"){let a=Math.abs(s-e[n]),o=Math.max(Math.abs(s),Math.abs(e[n]),1);r+=1-a/o}else s===e[n]&&r++;return i>0?r/i:.5}predictOutcome(t,e){let r={},i={},n={};for(let s of e)if(s.result.success)for(let[a,o]of Object.entries(s.result.outcome))Yi(a)&&typeof o=="number"&&(i[a]=(i[a]||0)+o,n[a]=(n[a]||0)+1);for(let[s,a]of Object.entries(i))Yi(s)&&(r[s]=a/n[s]);return r}async validateOptimization(t,e,r){let i=[];for(let n of r){let s=e.expectedOutcome,a=Object.entries(s).every(([o,c])=>{let l=n.result.outcome[o]??0;return Math.abs(l-c)/Math.max(c,1)<.2});i.push({testId:n.id,passed:a,metrics:n.state.metrics})}return i}calculateImprovement(t,e,r){if(t===0)return e>0?1:0;let i=e-t,n=r.direction==="maximize"?i/t:-i/t;return Math.max(-1,Math.min(1,n))}calculateOptimizationConfidence(t,e,r){let i=Math.min(1,t/(this.config.minSamplesForOptimization*2)),n=r.filter(a=>a.passed).length/Math.max(r.length,1),s=Math.abs(e)>this.config.improvementThreshold?1:.5;return i*.3+n*.5+s*.2}inferDomainFromExperiences(t){let e=new Map;for(let n of t)e.set(n.domain,(e.get(n.domain)||0)+1);let r="learning-optimization",i=0;for(let[n,s]of e)s>i&&(i=s,r=n);return r}async collectStrategyMetrics(t,e,r){let i=await this.memory.search("learning:metrics:history:*:*",r*2),n=[];for(let s of i){let a=await this.memory.get(s);a&&a.metrics[e]!==void 0&&n.push(a.metrics[e])}for(;n.length<r;){let s=t.expectedOutcome[e]||.5,a=(L()-.5)*.2;n.push(s+a)}return n}calculateMean(t){return t.length===0?0:t.reduce((e,r)=>e+r,0)/t.length}calculateStdDev(t){if(t.length===0)return 0;let e=this.calculateMean(t),r=t.map(i=>Math.pow(i-e,2));return Math.sqrt(r.reduce((i,n)=>i+n,0)/t.length)}calculatePValue(t,e){let r=this.calculateMean(t),i=this.calculateMean(e),n=Math.pow(this.calculateStdDev(t),2),s=Math.pow(this.calculateStdDev(e),2),a=t.length,o=e.length,c=Math.sqrt(n/a+s/o);if(c===0)return .5;let l=Math.abs(r-i)/c,d=2*(1-this.normalCDF(l));return Math.max(0,Math.min(1,d))}normalCDF(t){let e=.254829592,r=-.284496736,i=1.421413741,n=-1.453152027,s=1.061405429,a=.3275911,o=t<0?-1:1;t=Math.abs(t)/Math.sqrt(2);let c=1/(1+a*t),l=1-((((s*c+n)*c+i)*c+r)*c+e)*c*Math.exp(-t*t);return .5*(1+o*l)}scoreContextMatch(t,e){let r=0,i=0;return e.tags.some(n=>n===t.objective.metric)&&(r+=1),i+=1,e.tags.some(n=>n===t.domain)&&(r+=1),i+=1,i>0?r/i:.5}getDefaultParameters(t){let e={timeout:3e4,retryCount:3,concurrency:4};return t.framework&&(e.framework=t.framework),t.language&&(e.language=t.language),e}calculateSuccessRate(t){return t.length===0?0:t.filter(e=>e.result.success).length/t.length}calculateAverageDuration(t){return t.length===0?0:t.reduce((e,r)=>e+r.result.duration,0)/t.length}calculateAverageReward(t){return t.length===0?0:t.reduce((e,r)=>e+r.reward,0)/t.length}identifyImprovementAreas(t,e,r){let i=[];e.success_rate<.8&&i.push("Increase success rate by tuning parameters"),e.avg_duration_ms>1e4&&i.push("Optimize for faster execution"),e.avg_reward<.5&&i.push("Improve reward through better strategy selection");let n=t.parameters;return n.retryCount<2&&i.push("Consider increasing retry count for resilience"),n.concurrency>8&&i.push("High concurrency may cause resource contention"),i}generateParameterCombinations(t){let e=Object.keys(t);if(e.length===0)return[{}];let r=[];function i(n,s){if(n===e.length){r.push({...s});return}let a=e[n];if(!Yi(a)){i(n+1,s);return}for(let o of t[a])s[a]=o,i(n+1,s)}return i(0,{}),r}async updateAggregatedMetrics(t,e){let r=`learning:metrics:aggregated:${t}`,n=(await this.memory.get(r))?.metrics||{};for(let[s,a]of Object.entries(e))Yi(s)&&(n[s]||(n[s]={sum:0,count:0}),n[s].sum+=a,n[s].count+=1);await this.memory.set(r,{metrics:n,updatedAt:new Date},{namespace:"learning-optimization",persist:!0})}async storeOptimizationResult(t){await this.memory.set(`learning:strategy:optimized:${t.id}`,t,{namespace:"learning-optimization",persist:!0}),await this.memory.set(`learning:strategy:domain:${t.domain}:${t.id}`,t.id,{namespace:"learning-optimization",persist:!0})}async storeABTestResult(t,e,r){let i=v();await this.memory.set(`learning:abtest:${i}`,{testId:i,strategyA:t.name,strategyB:e.name,result:r,timestamp:new Date},{namespace:"learning-optimization",persist:!0})}async storeStrategyEvaluation(t){let e=v();await this.memory.set(`learning:evaluation:${e}`,{...t,evaluatedAt:new Date},{namespace:"learning-optimization",ttl:86400*7})}};A();var ib={metricsRetentionDays:90,anomalyThreshold:2.5,trendWindowSize:7,alertThresholds:{error_rate:.05,latency_p99:5e3,memory_usage:.9,cpu_usage:.8}},Qt=class{constructor(t,e={}){this.memory=t;this.config={...ib,...e}}memory;config;async recordMetric(t,e,r,i,n=[]){try{let s={id:v(),name:t,value:e,unit:r,domain:i,tags:n,timestamp:new Date};return await this.memory.set(`production:metric:${s.id}`,s,{namespace:"learning-optimization",ttl:this.config.metricsRetentionDays*86400}),await this.indexMetric(s),await this.checkForAnomalies(s),f(s.id)}catch(s){return p(y(s))}}async recordMetricsBatch(t){try{let e=[];for(let r of t){let i=await this.recordMetric(r.name,r.value,r.unit,r.domain,r.tags);i.success&&e.push(i.value)}return f(e)}catch(e){return p(y(e))}}async getMetricsHistory(t,e,r){try{let i=r?`production:metric:index:${t}:${r}:*`:`production:metric:index:${t}:*`,n=await this.memory.search(i,1e3),s=[];for(let a of n){let o=await this.memory.get(a);if(o){let c=ae(await this.memory.get(`production:metric:${o}`),["timestamp"]);c&&e.contains(c.timestamp)&&s.push(c)}}return s.sort((a,o)=>a.timestamp.getTime()-o.timestamp.getTime()),f(s)}catch(i){return p(y(i))}}async recordIncident(t,e,r,i,n){try{let s={id:v(),severity:t,title:e,description:r,domain:i,metrics:n,startedAt:new Date};return await this.memory.set(`production:incident:${s.id}`,s,{namespace:"learning-optimization",persist:!0}),await this.indexIncident(s),await this.createExperienceFromIncident(s),f(s)}catch(s){return p(y(s))}}async resolveIncident(t,e,r){try{let i=ae(await this.memory.get(`production:incident:${t}`),["startedAt","resolvedAt"]);if(!i)return p(new Error(`Incident ${t} not found`));let n={...i,rootCause:e,resolution:r,resolvedAt:new Date};return await this.memory.set(`production:incident:${t}`,n,{namespace:"learning-optimization",persist:!0}),await this.updateExperienceWithResolution(n),f(n)}catch(i){return p(y(i))}}async getRecentIncidents(t=10,e){try{let r=e?`production:incident:index:domain:${e}:*`:"production:incident:*",i=await this.memory.search(r,t*2),n=[];for(let a of i)if(a.includes(":index:")){let o=await this.memory.get(a);if(o){let c=ae(await this.memory.get(`production:incident:${o}`),["startedAt","resolvedAt"]);c&&n.push(c)}}else{let o=ae(await this.memory.get(a),["startedAt","resolvedAt"]);o&&n.push(o)}n.sort((a,o)=>o.startedAt.getTime()-a.startedAt.getTime());let s=Array.from(new Map(n.map(a=>[a.id,a])).values());return f(s.slice(0,t))}catch(r){return p(y(r))}}async getProductionHealth(){try{let t=["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","code-intelligence","security-compliance","learning-optimization"],e={},r={},i="healthy",n=0,s=0;for(let d of t){let m=await this.getDomainHealth(d);e[d]=m,m.status==="degraded"&&n++,m.status==="unhealthy"&&s++;for(let[h,g]of Object.entries(m.metrics))r[`${d}_${h}`]=g}s>0?i="unhealthy":n>t.length/3&&(i="degraded");let a=await this.calculateTrends(),o=await this.getRecentIncidents(5),c=o.success?o.value:[],l=this.generateHealthRecommendations(e,r,c);return f({overall:i,domains:e,metrics:r,trends:a,recentIncidents:c,recommendations:l})}catch(t){return p(y(t))}}async getDomainHealth(t){let e=it.lastNDays(1),r=await this.getMetricsHistory("*",e,t),i={};if(r.success)for(let o of r.value)i[o.name],i[o.name]=o.value;let n=await this.getRecentIncidents(100,t),s=n.success?n.value.filter(o=>!o.resolvedAt).length:0,a="healthy";return s>2?a="unhealthy":s>0&&(a="degraded"),i.error_rate>this.config.alertThresholds.error_rate?a="unhealthy":i.latency_p99>this.config.alertThresholds.latency_p99&&(a="degraded"),{status:a,metrics:i,activeIncidents:s}}async calculateTrends(){let t=[],e=["error_rate","latency_p99","success_rate"],r=this.config.trendWindowSize;for(let i of e)for(let n=0;n<r;n++){let s=new Date;s.setDate(s.getDate()-n),s.setHours(0,0,0,0);let a=new Date(s);a.setHours(23,59,59,999);let o=it.create(s,a),c=await this.getMetricsHistory(i,o);if(c.success&&c.value.length>0){let l=c.value.reduce((d,m)=>d+m.value,0)/c.value.length;t.push({timestamp:s,metric:i,value:l})}}return t}generateHealthRecommendations(t,e,r){let i=[];for(let[a,o]of Object.entries(t))o.status==="unhealthy"?i.push(`Domain ${a} is unhealthy. Review active incidents and metrics.`):o.status==="degraded"&&i.push(`Domain ${a} is degraded. Monitor closely.`);for(let[a,o]of Object.entries(e)){let c=a.split("_").slice(-2).join("_"),l=this.config.alertThresholds[c];l&&o>l&&i.push(`Metric ${a} (${o.toFixed(2)}) exceeds threshold (${l})`)}let n=r.filter(a=>!a.resolvedAt);return n.length>3&&i.push(`${n.length} unresolved incidents require attention`),r.reduce((a,o)=>(a[o.severity]=(a[o.severity]||0)+1,a),{}).critical>2&&i.push("Multiple critical incidents detected. Consider system-wide review."),i.length===0&&i.push("All systems operating within normal parameters."),i}async extractInsights(t,e){try{let r=await this.getMetricsHistory("*",t,e),i=r.success?r.value:[],n=await this.getRecentIncidents(50,e),s=n.success?n.value:[],a=i.length,o=s.filter(h=>h.resolvedAt),c=s.length>0?o.length/s.length:1,l=this.calculateRewardFromIncidents(s),d=this.generateInsightRecommendations(i,s),m=this.detectMetricAnomalies(i);return f({experienceCount:a,successRate:c,avgReward:l,patterns:[],anomalies:m,recommendations:d})}catch(r){return p(y(r))}}async recordMilestone(t,e,r){try{let i={name:t,achievedAt:new Date,domain:e};return await this.memory.set(`production:milestone:${v()}`,{...i,metrics:r},{namespace:"learning-optimization",persist:!0}),f(i)}catch(i){return p(y(i))}}async getRecentMilestones(t=10){try{let e=await this.memory.search("production:milestone:*",t),r=[];for(let i of e){let n=ae(await this.memory.get(i),["achievedAt"]);n&&r.push(n)}return r.sort((i,n)=>n.achievedAt.getTime()-i.achievedAt.getTime()),f(r.slice(0,t))}catch(e){return p(y(e))}}async indexMetric(t){await this.memory.set(`production:metric:index:${t.name}:${t.domain}:${t.id}`,t.id,{namespace:"learning-optimization",ttl:this.config.metricsRetentionDays*86400})}async indexIncident(t){await this.memory.set(`production:incident:index:domain:${t.domain}:${t.id}`,t.id,{namespace:"learning-optimization",persist:!0}),await this.memory.set(`production:incident:index:severity:${t.severity}:${t.id}`,t.id,{namespace:"learning-optimization",persist:!0})}async checkForAnomalies(t){let e=it.lastNDays(7),r=await this.getMetricsHistory(t.name,e,t.domain);if(!r.success||r.value.length<10)return;let i=r.value.map(o=>o.value),n=i.reduce((o,c)=>o+c,0)/i.length,s=Math.sqrt(i.reduce((o,c)=>o+Math.pow(c-n,2),0)/i.length),a=Math.abs(t.value-n)/(s||1);a>this.config.anomalyThreshold&&await this.memory.set(`production:anomaly:${v()}`,{metricId:t.id,metricName:t.name,value:t.value,mean:n,stdDev:s,deviation:a,timestamp:new Date},{namespace:"learning-optimization",ttl:86400*7})}async createExperienceFromIncident(t){let e={context:{incidentId:t.id,severity:t.severity,domain:t.domain},metrics:t.metrics},r={success:!1,outcome:t.metrics,duration:0},i={id:v(),agentId:{value:"production-intel",domain:"learning-optimization",type:"analyzer"},domain:t.domain,action:`incident-${t.severity}`,state:e,result:r,reward:this.calculateIncidentReward(t),timestamp:t.startedAt};await this.memory.set(`learning:experience:${i.id}`,i,{namespace:"learning-optimization",ttl:86400*30})}async updateExperienceWithResolution(t){if(!t.resolvedAt)return;let e={context:{incidentId:t.id,rootCause:t.rootCause,resolution:t.resolution},metrics:t.metrics},r=t.resolvedAt.getTime()-t.startedAt.getTime(),i={success:!0,outcome:{...t.metrics,resolution_time_ms:r},duration:r},n={id:v(),agentId:{value:"production-intel",domain:"learning-optimization",type:"analyzer"},domain:t.domain,action:`resolution-${t.severity}`,state:e,result:i,reward:1-this.calculateIncidentReward(t),timestamp:t.resolvedAt};await this.memory.set(`learning:experience:${n.id}`,n,{namespace:"learning-optimization",ttl:86400*30})}calculateIncidentReward(t){return-({critical:.9,high:.7,medium:.4,low:.2}[t.severity]||.5)}calculateRewardFromIncidents(t){if(t.length===0)return .8;let e={critical:.1,high:.3,medium:.6,low:.8},r=0,i=0;for(let n of t){let s=e[n.severity]||.5,a=n.resolvedAt?.2:0;r+=s+a,i++}return i>0?r/i:.8}generateInsightRecommendations(t,e){let r=[],i=new Map;for(let n of t){let s=i.get(n.name)||[];s.push(n.value),i.set(n.name,s)}for(let[n,s]of i){let a=this.calculateTrendDirection(s);a==="increasing"&&n.includes("error")?r.push(`${n} is trending upward. Investigate root causes.`):a==="decreasing"&&n.includes("success")&&r.push(`${n} is declining. Review recent changes.`)}if(e.length>0){let n=new Map;for(let s of e)n.set(s.domain,(n.get(s.domain)||0)+1);for(let[s,a]of n)a>3&&r.push(`Domain ${s} has ${a} incidents. Consider preventive measures.`)}return r}detectMetricAnomalies(t){let e=[],r=new Map;for(let i of t){let n=r.get(i.name)||[];n.push(i),r.set(i.name,n)}for(let[i,n]of r){if(n.length<5)continue;let s=n.map(c=>c.value),a=s.reduce((c,l)=>c+l,0)/s.length,o=Math.sqrt(s.reduce((c,l)=>c+Math.pow(l-a,2),0)/s.length);for(let c of n){let l=Math.abs(c.value-a)/(o||1);l>this.config.anomalyThreshold&&e.push({experienceId:c.id,type:"outlier-reward",description:`${i} value ${c.value.toFixed(2)} is ${l.toFixed(1)} std deviations from mean`,deviation:l})}}return e}calculateTrendDirection(t){if(t.length<3)return"stable";let e=t.slice(0,Math.floor(t.length/2)),r=t.slice(Math.floor(t.length/2)),i=e.reduce((a,o)=>a+o,0)/e.length,s=(r.reduce((a,o)=>a+o,0)/r.length-i)/(i||1);return s>.1?"increasing":s<-.1?"decreasing":"stable"}};async function Om(u,t,e){await u.set(`learning:strategy:current:${t}`,e,{namespace:"learning-optimization",persist:!0})}function Nm(u,t){let e=u.map(r=>r.result.outcome[t]??0).filter(r=>!isNaN(r));return e.length===0?0:e.reduce((r,i)=>r+i,0)/e.length}function Vm(u){return{"test-generation":["test-execution","coverage-analysis"],"test-execution":["test-generation","coverage-analysis","quality-assessment"],"coverage-analysis":["test-generation","test-execution","quality-assessment"],"quality-assessment":["test-execution","coverage-analysis","defect-intelligence"],"defect-intelligence":["quality-assessment","code-intelligence"],"requirements-validation":["test-generation","quality-assessment"],"code-intelligence":["defect-intelligence","security-compliance"],"security-compliance":["code-intelligence","quality-assessment"],"contract-testing":["test-generation","test-execution"],"visual-accessibility":["quality-assessment"],"chaos-resilience":["test-execution","quality-assessment"],"learning-optimization":we.filter(e=>e!=="learning-optimization"),"enterprise-integration":["contract-testing","security-compliance","quality-assessment"],coordination:we.filter(e=>e!=="coordination")}[u]||[]}function _m(u){let t=[],e=new Set;for(let r of u){if(e.has(r.id))continue;let i=[r];e.add(r.id);for(let n of u)e.has(n.id)||r.type===n.type&&r.domain===n.domain&&nb(r.context,n.context)&&(i.push(n),e.add(n.id));i.length>=2&&t.push(i)}return t}function nb(u,t){return u.tags.some(e=>t.tags.includes(e))}function zm(u,t,e){let r=JSON.stringify({patternCount:u.length,knowledgeCount:t.length,strategyCount:e.length,patternIds:u.map(n=>n.id).sort(),knowledgeIds:t.map(n=>n.id).sort(),strategyIds:e.map(n=>n.id).sort()}),i=0;for(let n=0;n<r.length;n++){let s=r.charCodeAt(n);i=(i<<5)-i+s,i=i&i}return Math.abs(i).toString(16)}M();var Fr=R.create("learning-optimization/consensus");async function Bm(u,t,e,r){let i=V({id:v(),type:"pattern-recommendation",confidence:t,description:`Verify pattern recommendation: ${u.name} (${u.type}) for domain ${u.domain}`,payload:u,detectedBy:"learning-optimization-coordinator",severity:t>.9?"high":"medium"});if(e.requiresConsensus(i)){let n=await e.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(Fr.info(`Pattern recommendation '${u.name}' verified by consensus`),!0):(Fr.warn(`Pattern recommendation '${u.name}' NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}async function qm(u,t,e,r){let i=V({id:v(),type:"optimization-suggestion",confidence:t,description:`Verify optimization: ${u.metric} from ${u.currentValue} to ${u.targetValue} via ${u.strategy}`,payload:u,detectedBy:"learning-optimization-coordinator",severity:t>.85?"high":"medium"});if(e.requiresConsensus(i)){let n=await e.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(Fr.info(`Optimization suggestion for '${u.metric}' verified by consensus`),!0):(Fr.warn(`Optimization suggestion for '${u.metric}' NOT verified`),!1)}return!0}async function Gm(u,t,e,r){let i=V({id:v(),type:"cross-domain-insight",confidence:t,description:`Verify cross-domain insight: ${u.description}`,payload:u,detectedBy:"learning-optimization-coordinator",severity:"high"});if(e.requiresConsensus(i)){let n=await e.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(Fr.info(`Cross-domain insight verified by consensus for ${u.targetDomains.length} target domains`),!0):(Fr.warn(`Cross-domain insight NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}var ob={maxConcurrentWorkflows:3,defaultTimeout:12e4,enableAutoOptimization:!0,publishEvents:!0,learningCycleIntervalMs:36e5,enableDreamScheduler:!0,dreamCycleIntervalMs:36e5,enableExperienceTrigger:!0,experienceThreshold:50,enableQualityGateFailureTrigger:!0,autoApplyHighConfidenceInsights:!1,autoApplyConfidenceThreshold:.8,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},Ae=R.create("learning-optimization"),ka=class extends Q{constructor(e,r,i,n={},s){let a={...ob,...n};super(e,"learning-optimization",a,{verifyFindingTypes:["pattern-recommendation","optimization-suggestion","cross-domain-insight"]});this.memory=r;this.agentCoordinator=i;this.learningService=new jt({memory:r,llmRouter:s}),this.transferService=new Wt(r),this.optimizerService=new Ut(r),this.productionIntel=new Qt(r)}memory;agentCoordinator;learningService;transferService;optimizerService;productionIntel;sona=null;dreamScheduler=null;async onInitialize(){try{this.sona=await pe({domain:"learning-optimization",loadOnInit:!0,autoSaveInterval:6e4,maxPatterns:1e4,minConfidence:.5}),Ae.info("PersistentSONAEngine initialized for pattern learning")}catch(e){Ae.error("Failed to initialize PersistentSONAEngine:",e instanceof Error?e:void 0),Ae.warn("Continuing without SONA pattern persistence"),this.sona=null}if(this.config.enableDreamScheduler)try{let e=await tn();await e.initialize(),this.dreamScheduler=El({dreamEngine:e,eventBus:this.eventBus,memoryBackend:this.memory},{autoScheduleIntervalMs:this.config.dreamCycleIntervalMs,enableExperienceTrigger:this.config.enableExperienceTrigger,experienceThreshold:this.config.experienceThreshold,enableQualityGateFailureTrigger:this.config.enableQualityGateFailureTrigger,autoApplyHighConfidenceInsights:this.config.autoApplyHighConfidenceInsights,insightConfidenceThreshold:this.config.autoApplyConfidenceThreshold}),await this.dreamScheduler.initialize(),this.dreamScheduler.start(),Ae.info("DreamScheduler initialized and started")}catch{Ae.warn("Failed to initialize DreamScheduler:")}this.subscribeToEvents(),await this.loadWorkflowState()}async onDispose(){if(await this.saveWorkflowState(),this.dreamScheduler){try{await this.dreamScheduler.dispose(),Ae.info("DreamScheduler disposed")}catch(e){Ae.error("Error disposing DreamScheduler:",e instanceof Error?e:void 0)}this.dreamScheduler=null}if(this.initialized&&this.sona)try{await this.sona.close()}catch(e){Ae.error("Error closing SONA engine:",e instanceof Error?e:void 0)}}getActiveWorkflows(){return super.getActiveWorkflows()}async runLearningCycle(e){let r=v();try{if(this.startWorkflow(r,"learning-cycle"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Ae.warn("Topology degraded, using conservative strategy for learning cycle"),this.minCutMixin.shouldPauseOperations())return p(new Error("Learning cycle paused: topology is in critical state"));let i=await this.spawnLearningAgent(r,e);if(!i.success)return this.failWorkflow(r,i.error.message),p(i.error);this.addAgentToWorkflow(r,i.value);let n=it.lastNDays(1),s=await this.getExperiencesForDomain(e,n),a=s.success?s.value:[];this.updateWorkflowProgress(r,20);let o=await this.learningService.mineExperiences(e,n),c=o.success?o.value.patterns.length:0;this.updateWorkflowProgress(r,50);let l=0,d=[];if(a.length>=10){let g={metric:"success_rate",direction:"maximize",constraints:[]},b=await this.getCurrentStrategy(e),w=await this.optimizerService.optimizeStrategy(b,g,a);w.success&&(l=1,d.push({metric:g.metric,before:this.calculateMetricValue(a,g.metric),after:w.value.optimizedStrategy.expectedOutcome[g.metric]||0,percentChange:w.value.improvement*100}))}this.updateWorkflowProgress(r,80);let m=0;o.success&&o.value.recommendations.length>0&&(await this.transferService.createKnowledge("heuristic",e,o.value.recommendations,{value:`learning-agent-${r.slice(0,8)}`,domain:"learning-optimization",type:"analyzer"},[e])).success&&(m=1),this.completeWorkflow(r),await this.agentCoordinator.stop(i.value);let h={domain:e,experiencesProcessed:a.length,patternsLearned:c,strategiesOptimized:l,knowledgeGenerated:m,improvements:d};return this.config.publishEvents&&c>0&&await this.publishPatternConsolidated(c,[e]),f(h)}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async optimizeAllStrategies(){let e=v();try{if(this.startWorkflow(e,"optimization"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Ae.warn("Topology degraded, using conservative optimization strategy"),this.minCutMixin.shouldPauseOperations())return p(new Error("Optimization paused: topology is in critical state"));let r={},i=0,n=0,s=0,a=we.filter(c=>c!=="learning-optimization");for(let c=0;c<a.length;c++){let l=a[c];this.updateWorkflowProgress(e,Math.round(c/a.length*100));let d=it.lastNDays(7),m=await this.getExperiencesForDomain(l,d);if(!m.success||m.value.length<10)continue;let h=m.value,g={metric:"success_rate",direction:"maximize",constraints:[]},b=await this.getCurrentStrategy(l),w=await this.optimizerService.optimizeStrategy(b,g,h);w.success&&(i++,n+=w.value.improvement,s++,r[l]={strategiesOptimized:1,avgImprovement:w.value.improvement,bestStrategy:w.value.optimizedStrategy},await this.storeStrategy(l,w.value.optimizedStrategy))}this.completeWorkflow(e);let o={domainsOptimized:s,totalStrategies:i,avgImprovement:i>0?n/i:0,byDomain:r};return this.config.publishEvents&&i>0&&await this.publishOptimizationApplied(o),f(o)}catch(r){return this.failWorkflow(e,String(r)),p(y(r))}}async shareCrossDomainLearnings(){let e=v();try{if(this.startWorkflow(e,"transfer"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Ae.warn("Topology degraded, limiting cross-domain transfer scope"),this.minCutMixin.shouldPauseOperations())return p(new Error("Cross-domain sharing paused: topology is in critical state"));let r=0,i=[],n=0,s=0,a=0,o=await this.transferService.queryKnowledge({minRelevance:.7,limit:100});if(!o.success)return this.failWorkflow(e,o.error.message),p(o.error);let c=o.value;for(let m of c){let h=this.getRelatedDomains(m.domain);for(let g of h){if(g===m.domain)continue;s++,(await this.transferService.transferKnowledge(m,g)).success&&(a++,r++,i.includes(g)||i.push(g))}this.updateWorkflowProgress(e,Math.round(r/(c.length*2)*100))}let l=await this.learningService.getPatternStats();if(l.success){let m=l.value.topPatterns;if(m.length>=2){let h=this.findSimilarPatterns(m);for(let g of h)g.length>=2&&(await this.learningService.consolidatePatterns(g.map(w=>w.id))).success&&n++}}this.completeWorkflow(e);let d={knowledgeShared:r,domainsUpdated:i,transferSuccessRate:s>0?a/s:1,newPatternsCreated:n};return this.config.publishEvents&&r>0&&await this.publishTransferCompleted(d),f(d)}catch(r){return this.failWorkflow(e,String(r)),p(y(r))}}async getLearningDashboard(){try{let e=await this.learningService.getPatternStats(),r=e.success?e.value:null,i=await this.transferService.queryKnowledge({limit:1e3}),n=i.success?i.value.length:0,s=it.lastNDays(1),a=0;for(let b of we){let w=await this.getExperiencesForDomain(b,s);w.success&&(a+=w.value.length)}let o=await this.productionIntel.getProductionHealth(),c=o.success?o.value.trends:[],l=await this.productionIntel.getRecentMilestones(5),d=l.success?l.value:[],m=r?r.avgSuccessRate*.6+r.avgConfidence*.4:.5,h=[];if(r){let b=Object.entries(r.byDomain).filter(([w,C])=>C>0).map(([w,C])=>({domain:w,score:C})).sort((w,C)=>C.score-w.score);h.push(...b.slice(0,3).map(w=>w.domain))}let g={overallLearningRate:m,totalPatterns:r?.totalPatterns||0,totalKnowledge:n,experiencesLast24h:a,topPerformingDomains:h,learningTrend:c,recentMilestones:d};return f(g)}catch(e){return p(y(e))}}learnPattern(e,r,i,n,s,a){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.createPattern(e,r,i,n,s,a)}ensureInitialized(){if(!this.initialized)throw new Error("[LearningOptimizationCoordinator] Not initialized. Call initialize() first.")}ensureSONAAvailable(){if(!this.sona)throw new Error("[LearningOptimizationCoordinator] SONA engine is not available. Pattern persistence failed during initialization.")}async adaptPattern(e,r,i){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.adaptPattern(e,r,i)}getSONAStats(){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.getStats()}getSONAPatterns(){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.getAllPatterns()}getSONAPatternsByType(e){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.getPatternsByType(e)}getSONAPatternsByDomain(e){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.getPatternsByDomain(e)}updateSONAPattern(e,r,i){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.updatePattern(e,r,i)}forceSONALearning(){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.forceLearn()}isSONAAvailable(){return this.initialized&&this.sona!==null}exportSONAPatterns(){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.exportPatterns()}importSONAPatterns(e){this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.importPatterns(e)}async verifySONAPerformance(e=100){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.verifyPerformance(e)}async triggerDreamCycle(e){if(!this.dreamScheduler)throw new Error("[LearningOptimizationCoordinator] DreamScheduler not initialized");let r=await this.dreamScheduler.triggerDream(e);return this.config.publishEvents&&await this.publishDreamCycleCompleted(r.cycle.id,r.cycle.durationMs??0,r.cycle.conceptsProcessed,r.insights.map(i=>({id:i.id,type:i.type,description:i.description,noveltyScore:i.noveltyScore,confidenceScore:i.confidenceScore,actionable:i.actionable,suggestedAction:i.suggestedAction,sourceConcepts:i.sourceConcepts})),r.patternsCreated),r}getDreamStatus(){return this.dreamScheduler?.getStatus()??null}isDreamSchedulerAvailable(){return this.dreamScheduler!==null}getLastDreamResult(){return this.dreamScheduler?.getLastDreamResult()??null}async triggerQuickDream(){if(!this.dreamScheduler)throw new Error("[LearningOptimizationCoordinator] DreamScheduler not initialized");return this.dreamScheduler.triggerQuickDream()}async triggerFullDream(){if(!this.dreamScheduler)throw new Error("[LearningOptimizationCoordinator] DreamScheduler not initialized");return this.dreamScheduler.triggerFullDream()}async exportModels(e){let r=v();try{this.startWorkflow(r,"export");let i=e||we,n=[],s=[],a=[];for(let m of i){let h=await this.memory.search("learning:pattern:*",500);for(let g of h){let b=await this.memory.get(g);b&&i.includes(b.domain)&&n.push(b)}this.updateWorkflowProgress(r,Math.round(n.length/100*30))}let o=await this.transferService.queryKnowledge({limit:1e3});if(o.success)for(let m of o.value)i.includes(m.domain)&&s.push(m);this.updateWorkflowProgress(r,60);let c=await this.memory.search("learning:strategy:optimized:*",200);for(let m of c){let h=await this.memory.get(m);h&&i.includes(h.domain)&&a.push(h)}this.updateWorkflowProgress(r,90);let l=this.calculateChecksum(n,s,a);return this.completeWorkflow(r),f({version:"1.0.0",exportedAt:new Date,patterns:n,knowledge:s,strategies:a,checksum:l})}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async importModels(e){let r=v();try{if(this.startWorkflow(r,"import"),this.calculateChecksum(e.patterns,e.knowledge,e.strategies)!==e.checksum)return this.failWorkflow(r,"Checksum mismatch"),p(new Error("Import failed: checksum mismatch"));let n=0,s=0,a=0,o=[];for(let l of e.patterns){let d=await this.memory.get(`learning:pattern:${l.id}`);d?d.confidence<l.confidence?(await this.memory.set(`learning:pattern:${l.id}`,l,{namespace:"learning-optimization",persist:!0}),n++,o.push({type:"pattern",id:l.id,reason:"Existing pattern had lower confidence",resolution:"overwrite"})):o.push({type:"pattern",id:l.id,reason:"Existing pattern has higher confidence",resolution:"skip"}):(await this.memory.set(`learning:pattern:${l.id}`,l,{namespace:"learning-optimization",persist:!0}),n++),this.updateWorkflowProgress(r,Math.round(n/e.patterns.length*30))}for(let l of e.knowledge){let d=await this.memory.get(`learning:knowledge:shared:${l.id}`);d?l.version>d.version?(await this.memory.set(`learning:knowledge:shared:${l.id}`,l,{namespace:"learning-optimization",persist:!0}),s++,o.push({type:"knowledge",id:l.id,reason:"Import has newer version",resolution:"overwrite"})):o.push({type:"knowledge",id:l.id,reason:"Existing knowledge is same or newer version",resolution:"skip"}):(await this.memory.set(`learning:knowledge:shared:${l.id}`,l,{namespace:"learning-optimization",persist:!0}),s++),this.updateWorkflowProgress(r,30+Math.round(s/e.knowledge.length*30))}for(let l of e.strategies){let d=await this.memory.get(`learning:strategy:optimized:${l.id}`);d?l.confidence>d.confidence?(await this.memory.set(`learning:strategy:optimized:${l.id}`,l,{namespace:"learning-optimization",persist:!0}),a++,o.push({type:"strategy",id:l.id,reason:"Import has higher confidence",resolution:"overwrite"})):o.push({type:"strategy",id:l.id,reason:"Existing strategy has higher confidence",resolution:"skip"}):(await this.memory.set(`learning:strategy:optimized:${l.id}`,l,{namespace:"learning-optimization",persist:!0}),a++),this.updateWorkflowProgress(r,60+Math.round(a/e.strategies.length*40))}return this.completeWorkflow(r),f({patternsImported:n,knowledgeImported:s,strategiesImported:a,conflicts:o,resolved:!0})}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}subscribeToEvents(){this.eventBus.subscribe("test-execution.TestRunCompleted",this.handleTestRunCompleted.bind(this)),this.eventBus.subscribe("coverage-analysis.CoverageGapDetected",this.handleCoverageGap.bind(this)),this.eventBus.subscribe("quality-assessment.QualityGateEvaluated",this.handleQualityGate.bind(this)),this.eventBus.subscribe("learning.ExperienceCaptured",this.handleExperienceCaptured.bind(this))}async handleTestRunCompleted(e){let{runId:r,passed:i,failed:n,duration:s}=e.payload,a=i+n>0?i/(i+n):0;await this.learningService.recordExperience({agentId:{value:"test-execution",domain:"test-execution",type:"tester"},domain:"test-execution",action:"test-run",state:{context:{runId:r},metrics:{passed:i,failed:n,duration:s}},result:{success:a>.8,outcome:{success_rate:a,passed:i,failed:n},duration:s},reward:a})}async handleCoverageGap(e){let{gapId:r,file:i,riskScore:n}=e.payload;await this.learningService.recordExperience({agentId:{value:"coverage-analysis",domain:"coverage-analysis",type:"analyzer"},domain:"coverage-analysis",action:"gap-detection",state:{context:{gapId:r,file:i},metrics:{riskScore:n}},result:{success:!0,outcome:{risk_score:n},duration:0},reward:1-n})}async handleQualityGate(e){let{gateId:r,passed:i}=e.payload;await this.learningService.recordExperience({agentId:{value:"quality-assessment",domain:"quality-assessment",type:"validator"},domain:"quality-assessment",action:"gate-evaluation",state:{context:{gateId:r},metrics:{passed:i?1:0}},result:{success:i,outcome:{gate_passed:i?1:0},duration:0},reward:i?1:0})}async handleExperienceCaptured(e){let{experience:r}=e.payload;if(!r.success||r.quality<.7)return;let i=r.domain||"learning-optimization";if(await this.learningService.recordExperience({agentId:{value:r.agent||"unknown",domain:i,type:"specialist"},domain:i,action:r.task,state:{context:{experienceId:r.id,trajectoryId:r.trajectoryId,model:r.model},metrics:{durationMs:r.durationMs,stepCount:r.steps.length,quality:r.quality}},result:{success:r.success,outcome:{quality:r.quality,patterns_extracted:r.patterns?.length||0},duration:r.durationMs},reward:r.quality}),r.patterns&&r.patterns.length>0&&r.domain){let n=this.getRelatedDomains(r.domain);for(let s of n)s!==r.domain&&await this.transferService.transferKnowledge({id:`exp-${r.id}`,domain:r.domain,type:"workflow",content:{format:"json",data:{task:r.task,steps:r.steps,quality:r.quality,patterns:r.patterns}},sourceAgentId:{value:r.agent||"experience-capture",domain:r.domain,type:"specialist"},targetDomains:[s],relevanceScore:r.quality,version:1,createdAt:new Date(r.startedAt)},s);Ae.info(`[LearningOptimizationCoordinator] Experience ${r.id} transferred to ${n.length} related domains`)}this.dreamScheduler&&this.dreamScheduler.recordExperience({id:r.id,agentType:r.agent||"unknown",domain:i,taskType:r.task,success:r.success,duration:r.durationMs,context:{quality:r.quality,steps:r.steps.length,patterns:r.patterns?.length||0},timestamp:new Date(r.startedAt)})}async publishPatternConsolidated(e,r){let i={patternCount:e,domains:r,improvements:0},n=I(He.PatternConsolidated,"learning-optimization",i);await this.eventBus.publish(n)}async publishTransferCompleted(e){let r={sourceProject:"current",targetProject:"current",patternsTransferred:e.knowledgeShared,successRate:e.transferSuccessRate},i=I(He.TransferCompleted,"learning-optimization",r);await this.eventBus.publish(i)}async publishOptimizationApplied(e){let r=I(He.OptimizationApplied,"learning-optimization",{domainsOptimized:e.domainsOptimized,avgImprovement:e.avgImprovement});await this.eventBus.publish(r)}async publishDreamCycleCompleted(e,r,i,n,s){if(!this.config.publishEvents)return;let a={cycleId:e,durationMs:r,conceptsProcessed:i,insights:n,patternsCreated:s},o=I(He.DreamCycleCompleted,"learning-optimization",a);await this.eventBus.publish(o),Ae.info(`[LearningOptimizationCoordinator] Published dream cycle completion: ${n.length} insights for ${i} concepts`)}async spawnLearningAgent(e,r){if(!this.agentCoordinator.canSpawn())return p(new Error("Agent limit reached"));let i={name:`learning-agent-${e.slice(0,8)}`,domain:"learning-optimization",type:"optimizer",capabilities:["pattern-learning","experience-mining",r],config:{workflowId:e,targetDomain:r}};return this.agentCoordinator.spawn(i)}async loadWorkflowState(){let e=await this.memory.get("learning-optimization:coordinator:workflows");if(e)for(let r of e)r.status==="running"&&(r.status="failed",r.error="Coordinator restarted",r.completedAt=new Date),this.workflows.set(r.id,r)}async saveWorkflowState(){let e=Array.from(this.workflows.values());await this.memory.set("learning-optimization:coordinator:workflows",e,{namespace:"learning-optimization",persist:!0})}async getExperiencesForDomain(e,r){let i=await this.memory.search(`learning:experience:index:domain:${e}:*`,500),n=[];for(let s of i){let a=await this.memory.get(s);if(a){let o=ae(await this.memory.get(`learning:experience:${a}`),["timestamp"]);o&&r.contains(o.timestamp)&&n.push(o)}}return f(n)}async getCurrentStrategy(e){let r=`learning:strategy:current:${e}`,i=await this.memory.get(r);return i||{name:`default-${e}`,parameters:{timeout:3e4,retryCount:3,concurrency:4},expectedOutcome:{success_rate:.8}}}async storeStrategy(e,r){await Om(this.memory,e,r)}calculateMetricValue(e,r){return Nm(e,r)}getRelatedDomains(e){return Vm(e)}findSimilarPatterns(e){return _m(e)}calculateChecksum(e,r,i){return zm(e,r,i)}async verifyPatternRecommendation(e,r){return Bm(e,r,this.consensusMixin,this.domainName)}async verifyOptimizationSuggestion(e,r){return qm(e,r,this.consensusMixin,this.domainName)}async verifyCrossDomainInsight(e,r){return Gm(e,r,this.consensusMixin,this.domainName)}};A();var ll=class extends j{constructor(e,r,i,n={},s){super(e,r);this.agentCoordinator=i;this.llmRouter=s;this.pluginConfig=n}agentCoordinator;llmRouter;coordinator=null;learningService=null;transferService=null;optimizerService=null;productionIntel=null;pluginConfig;get name(){return"learning-optimization"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{isSONAAvailable:()=>this.coordinator?.isSONAAvailable()??!1,runLearningCycle:this.runLearningCycle.bind(this),optimizeAllStrategies:this.optimizeAllStrategies.bind(this),shareCrossDomainLearnings:this.shareCrossDomainLearnings.bind(this),getLearningDashboard:this.getLearningDashboard.bind(this),exportModels:this.exportModels.bind(this),importModels:this.importModels.bind(this),learnPattern:this.learnPattern.bind(this),findMatchingPatterns:this.findMatchingPatterns.bind(this),applyPattern:this.applyPattern.bind(this),updatePatternFeedback:this.updatePatternFeedback.bind(this),getPatternStats:this.getPatternStats.bind(this),queryKnowledge:this.queryKnowledge.bind(this),transferKnowledge:this.transferKnowledge.bind(this),optimizeStrategy:this.optimizeStrategy.bind(this),runABTest:this.runABTest.bind(this),recommendStrategy:this.recommendStrategy.bind(this),evaluateStrategy:this.evaluateStrategy.bind(this),getCoordinator:()=>this.coordinator,getActiveWorkflows:()=>this.coordinator?.getActiveWorkflows()||[],getLearningService:()=>this.learningService,getTransferService:()=>this.transferService,getOptimizerService:()=>this.optimizerService,getProductionIntelService:()=>this.productionIntel}}getTaskHandlers(){return new Map([["run-learning-cycle",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.domain;return r?this.coordinator.runLearningCycle(r):p(new Error("Invalid run-learning-cycle payload: missing domain"))}],["optimize-strategies",async e=>this.coordinator?this.coordinator.optimizeAllStrategies():p(new Error("Coordinator not initialized"))],["share-learnings",async e=>this.coordinator?this.coordinator.shareCrossDomainLearnings():p(new Error("Coordinator not initialized"))],["learn-pattern",async e=>{if(!this.learningService)return p(new Error("Learning service not initialized"));let r=e.experiences;return!r||r.length===0?p(new Error("Invalid learn-pattern payload: missing experiences")):this.learningService.learnPattern(r)}],["query-knowledge",async e=>{if(!this.transferService)return p(new Error("Transfer service not initialized"));let r=e.query;return r?this.transferService.queryKnowledge(r):p(new Error("Invalid query-knowledge payload: missing query"))}]])}async onInitialize(){this.learningService=new jt({memory:this.memory,llmRouter:this.llmRouter},this.pluginConfig.learningService),this.transferService=new Wt(this.memory,this.pluginConfig.transferService),this.optimizerService=new Ut(this.memory,this.pluginConfig.optimizerService),this.productionIntel=new Qt(this.memory,this.pluginConfig.productionIntel),this.coordinator=new ka(this.eventBus,this.memory,this.agentCoordinator,this.pluginConfig.coordinator,this.llmRouter),await this.coordinator.initialize(),this.updateHealth({status:"idle",agents:{total:0,active:0,idle:0,failed:0},lastActivity:new Date,errors:[]})}async onDispose(){this.coordinator&&await this.coordinator.dispose(),this.coordinator=null,this.learningService=null,this.transferService=null,this.optimizerService=null,this.productionIntel=null}subscribeToEvents(){this.eventBus.subscribe("test-generation.TestGenerated",this.handleTestGenerated.bind(this)),this.eventBus.subscribe("test-execution.TestRunCompleted",this.handleTestRunCompleted.bind(this)),this.eventBus.subscribe("coverage-analysis.CoverageGapDetected",this.handleCoverageGap.bind(this)),this.eventBus.subscribe("quality-assessment.QualityGateEvaluated",this.handleQualityGate.bind(this)),this.eventBus.subscribe("defect-intelligence.DefectPredicted",this.handleDefectPredicted.bind(this)),this.eventBus.subscribe("code-intelligence.ImpactAnalysisCompleted",this.handleImpactAnalysis.bind(this))}async onEvent(e){switch(this.updateHealth({lastActivity:new Date}),e.type){case"test-generation.TestGenerated":await this.handleTestGenerated(e);break;case"test-execution.TestRunCompleted":await this.handleTestRunCompleted(e);break;case"coverage-analysis.CoverageGapDetected":await this.handleCoverageGap(e);break;default:break}}async runLearningCycle(e){this.ensureInitialized();try{let r=await this.coordinator.runLearningCycle(e);return r.success?this.trackSuccessfulOperation("learning-cycle"):this.trackFailedOperation("learning-cycle",r.error),r}catch(r){return this.handleError(r)}}async optimizeAllStrategies(){this.ensureInitialized();try{let e=await this.coordinator.optimizeAllStrategies();return e.success?this.trackSuccessfulOperation("optimization"):this.trackFailedOperation("optimization",e.error),e}catch(e){return this.handleError(e)}}async shareCrossDomainLearnings(){this.ensureInitialized();try{return await this.coordinator.shareCrossDomainLearnings()}catch(e){return this.handleError(e)}}async getLearningDashboard(){this.ensureInitialized();try{return await this.coordinator.getLearningDashboard()}catch(e){return this.handleError(e)}}async exportModels(e){this.ensureInitialized();try{return await this.coordinator.exportModels(e)}catch(r){return this.handleError(r)}}async importModels(e){this.ensureInitialized();try{return await this.coordinator.importModels(e)}catch(r){return this.handleError(r)}}async learnPattern(e){this.ensureInitialized();try{return await this.learningService.learnPattern(e)}catch(r){return this.handleError(r)}}async findMatchingPatterns(e,r){this.ensureInitialized();try{return await this.learningService.findMatchingPatterns(e,r)}catch(i){return this.handleError(i)}}async applyPattern(e,r){this.ensureInitialized();try{return await this.learningService.applyPattern(e,r)}catch(i){return this.handleError(i)}}async updatePatternFeedback(e,r){this.ensureInitialized();try{return await this.learningService.updatePatternFeedback(e,r)}catch(i){return this.handleError(i)}}async getPatternStats(e){this.ensureInitialized();try{return await this.learningService.getPatternStats(e)}catch(r){return this.handleError(r)}}async queryKnowledge(e){this.ensureInitialized();try{return await this.transferService.queryKnowledge(e)}catch(r){return this.handleError(r)}}async transferKnowledge(e,r){this.ensureInitialized();try{return await this.transferService.transferKnowledge(e,r)}catch(i){return this.handleError(i)}}async optimizeStrategy(e,r,i){this.ensureInitialized();try{return await this.optimizerService.optimizeStrategy(e,r,i)}catch(n){return this.handleError(n)}}async runABTest(e,r,i){this.ensureInitialized();try{return await this.optimizerService.runABTest(e,r,i)}catch(n){return this.handleError(n)}}async recommendStrategy(e){this.ensureInitialized();try{return await this.optimizerService.recommendStrategy(e)}catch(r){return this.handleError(r)}}async evaluateStrategy(e,r){this.ensureInitialized();try{return await this.optimizerService.evaluateStrategy(e,r)}catch(i){return this.handleError(i)}}async handleTestGenerated(e){let r=e.payload;await this.learningService.recordExperience({agentId:{value:"test-generation",domain:"test-generation",type:"generator"},domain:"test-generation",action:"test-generated",state:{context:{testId:r.testId,testType:r.testType},metrics:{}},result:{success:!0,outcome:{generated:1},duration:0},reward:.8})}async handleTestRunCompleted(e){let r=e.payload,i=r.passed+r.failed>0?r.passed/(r.passed+r.failed):0;await this.learningService.recordExperience({agentId:{value:"test-execution",domain:"test-execution",type:"tester"},domain:"test-execution",action:"test-run",state:{context:{runId:r.runId},metrics:{passed:r.passed,failed:r.failed,duration:r.duration}},result:{success:i>.8,outcome:{success_rate:i,passed:r.passed,failed:r.failed},duration:r.duration},reward:i}),await this.productionIntel.recordMetric("test_success_rate",i,"ratio","test-execution",["automated"])}async handleCoverageGap(e){let r=e.payload;await this.learningService.recordExperience({agentId:{value:"coverage-analysis",domain:"coverage-analysis",type:"analyzer"},domain:"coverage-analysis",action:"gap-detection",state:{context:{gapId:r.gapId,file:r.file},metrics:{riskScore:r.riskScore}},result:{success:!0,outcome:{risk_score:r.riskScore},duration:0},reward:1-r.riskScore})}async handleQualityGate(e){let r=e.payload;await this.learningService.recordExperience({agentId:{value:"quality-assessment",domain:"quality-assessment",type:"validator"},domain:"quality-assessment",action:"gate-evaluation",state:{context:{gateId:r.gateId},metrics:{passed:r.passed?1:0}},result:{success:r.passed,outcome:{gate_passed:r.passed?1:0},duration:0},reward:r.passed?1:0})}async handleDefectPredicted(e){let r=e.payload;await this.learningService.recordExperience({agentId:{value:"defect-intelligence",domain:"defect-intelligence",type:"analyzer"},domain:"defect-intelligence",action:"defect-prediction",state:{context:{predictionId:r.predictionId},metrics:{probability:r.probability}},result:{success:!0,outcome:{probability:r.probability},duration:0},reward:.7})}async handleImpactAnalysis(e){let r=e.payload;await this.learningService.recordExperience({agentId:{value:"code-intelligence",domain:"code-intelligence",type:"analyzer"},domain:"code-intelligence",action:"impact-analysis",state:{context:{analysisId:r.analysisId},metrics:{changedFiles:r.changedFiles.length,impactedFiles:r.impactedFiles.length}},result:{success:!0,outcome:{changed_count:r.changedFiles.length,impacted_count:r.impactedFiles.length},duration:0},reward:.8})}ensureInitialized(){if(!this._initialized)throw new Error("LearningOptimizationPlugin is not initialized");if(!this.coordinator||!this.learningService||!this.transferService||!this.optimizerService||!this.productionIntel)throw new Error("LearningOptimizationPlugin services are not available")}handleError(e){let r=y(e),i=this.getHealth();return this.updateHealth({errors:[...i.errors.slice(-9),r.message],status:i.errors.length>=5?"degraded":i.status}),p(r)}trackSuccessfulOperation(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,total:r.agents.total+1,idle:r.agents.idle+1},lastActivity:new Date})}trackFailedOperation(e,r){let i=this.getHealth();this.updateHealth({agents:{...i.agents,failed:i.agents.failed+1},errors:[...i.errors.slice(-9),r.message]})}};function Hm(u,t,e,r,i){return new ll(u,t,e,r,i)}var ul=class extends j{constructor(e,r,i,n={}){super(e,r);this.agentCoordinator=i;this.pluginConfig=n}agentCoordinator;workflowOrchestrator=null;pluginConfig;get name(){return"coordination"}get version(){return"1.0.0"}get dependencies(){return we.filter(e=>e!=="coordination")}getAPI(){return{listWorkflows:async()=>{if(!this.workflowOrchestrator)throw new Error("Workflow orchestrator not initialized");return this.workflowOrchestrator.listWorkflows()}}}async onInitialize(){this.workflowOrchestrator=Fl(this.eventBus,this.memory,this.agentCoordinator,this.pluginConfig.workflowConfig),await this.workflowOrchestrator.initialize(),this.updateHealth({status:"healthy",agents:{total:0,active:0,idle:0,failed:0}})}async onDispose(){this.workflowOrchestrator&&(await this.workflowOrchestrator.dispose(),this.workflowOrchestrator=null)}async onEvent(e){e.type.startsWith("coordination.")&&await this.handleCoordinationEvent(e)}subscribeToEvents(){this.eventBus.subscribe("coordination.workflow.execute",async e=>{await this.handleEvent(e)})}async handleCoordinationEvent(e){e.type.split(".")[1]==="workflow"&&await this.handleWorkflowEvent(e)}async handleWorkflowEvent(e){this.workflowOrchestrator}};function jm(u,t,e,r){return new ul(u,t,e,r)}var Ee={CoverageAnalyzerService:"coverage-analysis.CoverageAnalyzerService",SecurityScannerService:"security-compliance.SecurityScannerService",isSemgrepAvailable:"security-compliance.isSemgrepAvailable",runSemgrepWithRules:"security-compliance.runSemgrepWithRules",convertSemgrepFindings:"security-compliance.convertSemgrepFindings",createTestGeneratorService:"test-generation.createTestGeneratorService",KnowledgeGraphService:"code-intelligence.KnowledgeGraphService",QualityAnalyzerService:"quality-assessment.QualityAnalyzerService"},dl=class{factories=new Map;register(t,e){this.factories.set(t,e)}resolve(t){let e=this.factories.get(t);if(!e)throw new Error(`DomainServiceRegistry: service '${t}' not registered. Ensure the domain module is initialized before coordination.`);return e}has(t){return this.factories.has(t)}clear(){this.factories.clear()}keys(){return Array.from(this.factories.keys())}},xe=new dl;xe.register(Ee.createTestGeneratorService,u=>eo(u));xe.register(Ee.CoverageAnalyzerService,u=>new ht(u));xe.register(Ee.SecurityScannerService,u=>new Ne(u));xe.register(Ee.isSemgrepAvailable,qi);xe.register(Ee.runSemgrepWithRules,Qs);xe.register(Ee.convertSemgrepFindings,Ks);xe.register(Ee.KnowledgeGraphService,u=>new xt(u));A();xe.register(Ee.QualityAnalyzerService,u=>new Xe(u));A();M();A();var Kt={SoapOperationTested:"enterprise-integration.SoapOperationTested",MessageFlowTested:"enterprise-integration.MessageFlowTested",BapiTested:"enterprise-integration.BapiTested",IDocValidated:"enterprise-integration.IDocValidated",ODataTested:"enterprise-integration.ODataTested",SodAnalyzed:"enterprise-integration.SodAnalyzed",MiddlewareFlowTested:"enterprise-integration.MiddlewareFlowTested",IntegrationValidationFailed:"enterprise-integration.IntegrationValidationFailed"},db={maxConcurrentWorkflows:8,defaultTimeout:12e4,publishEvents:!0,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},Da=R.create("enterprise-integration"),Ia=class extends Q{constructor(e,r,i,n={}){let s={...db,...n};super(e,"enterprise-integration",s,{verifyFindingTypes:["soap-fault","message-ordering-violation","rfc-compatibility-break","idoc-validation-failure","odata-contract-break","sod-conflict"],modelTimeout:12e4});this.memory=r;this.agentCoordinator=i}memory;agentCoordinator;async onInitialize(){this.subscribeToEvents(),Da.info("Enterprise Integration Coordinator initialized")}async onDispose(){}subscribeToEvents(){this.eventBus.subscribe("contract-testing.ContractVerified",this.handleContractVerified.bind(this)),this.eventBus.subscribe("chaos-resilience.FaultInjected",this.handleFaultInjected.bind(this))}getActiveWorkflows(){return super.getActiveWorkflows()}async validateWsdl(e){let r=v();try{if(this.startWorkflow(r,"soap"),this.minCutMixin.shouldPauseOperations())return p(new Error("WSDL validation paused: topology is in critical state"));let i=await this.spawnAgent(r,"qe-soap-tester",{task:"validate-wsdl",url:e});if(!i.success)return this.failWorkflow(r,i.error.message),i;let n={url:e,version:"1.1",services:[],schemas:[]};return await this.memory.set(`enterprise-integration:wsdl:${encodeURIComponent(e)}`,n,{namespace:"enterprise-integration",persist:!0}),this.completeWorkflow(r),f(n)}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async testSoapOperation(e,r,i){let n=v();try{this.startWorkflow(n,"soap");let s=await this.spawnAgent(n,"qe-soap-tester",{task:"test-operation",wsdl:e,operation:r,input:i});if(!s.success)return this.failWorkflow(n,s.error.message),p(s.error);let a={operation:r,passed:!0,request:JSON.stringify(i),response:"",validationErrors:[],duration:0};return this.config.publishEvents&&await this.eventBus.publish(I(Kt.SoapOperationTested,this.domainName,{operation:r,wsdlUrl:e.url,passed:a.passed,errors:a.validationErrors.length})),this.completeWorkflow(n),f(a)}catch(s){return this.failWorkflow(n,String(s)),p(y(s))}}async testMessageFlow(e,r){let i=v();try{this.startWorkflow(i,"messaging");let n=await this.spawnAgent(i,"qe-message-broker-tester",{task:"test-message-flow",brokerConfig:e,testCase:r});if(!n.success)return this.failWorkflow(i,n.error.message),p(n.error);let s={testCaseId:r.id,passed:!0,sentAt:new Date,receivedAt:new Date,latency:0,actualOutcome:r.expectedOutcome,errors:[]};return this.config.publishEvents&&await this.eventBus.publish(I(Kt.MessageFlowTested,this.domainName,{protocol:e.protocol,queue:r.queue,passed:s.passed,latency:s.latency})),this.completeWorkflow(i),f(s)}catch(n){return this.failWorkflow(i,String(n)),p(y(n))}}async testDlqHandling(e,r){let i=v();try{this.startWorkflow(i,"messaging");let n=await this.spawnAgent(i,"qe-message-broker-tester",{task:"test-dlq",brokerConfig:e,queue:r});if(!n.success)return this.failWorkflow(i,n.error.message),p(n.error);let s={queue:r,messageCount:0,poisonMessages:0,reprocessable:0,errors:[]};return this.completeWorkflow(i),f(s)}catch(n){return this.failWorkflow(i,String(n)),p(y(n))}}async testBapiCall(e,r){let i=v();try{if(this.startWorkflow(i,"rfc"),this.minCutMixin.shouldPauseOperations())return p(new Error("BAPI testing paused: topology is in critical state"));let n=await this.spawnAgent(i,"qe-sap-rfc-tester",{task:"test-bapi",connection:e,bapi:r});if(!n.success)return this.failWorkflow(i,n.error.message),p(n.error);let s={bapiName:r.name,passed:!0,returnMessages:[],exportValues:{},tableData:{},duration:0,transactionCommitted:!1};return this.config.publishEvents&&await this.eventBus.publish(I(Kt.BapiTested,this.domainName,{bapiName:r.name,passed:s.passed,returnType:s.returnMessages.length>0?s.returnMessages[0].type:"S"})),await this.memory.set(`enterprise-integration:bapi:${r.name}:${Date.now()}`,{bapiName:r.name,importParams:Object.keys(r.importParams),passed:s.passed,timestamp:new Date().toISOString()},{namespace:"enterprise-integration",persist:!0}),this.completeWorkflow(i),f(s)}catch(n){return this.failWorkflow(i,String(n)),p(y(n))}}async validateIdoc(e,r){let i=v();try{this.startWorkflow(i,"idoc");let n=await this.spawnAgent(i,"qe-sap-idoc-tester",{task:"validate-idoc",definition:e,content:r});if(!n.success)return this.failWorkflow(i,n.error.message),p(n.error);let s={idocType:e.type,direction:"inbound",passed:!0,statusCode:3,statusMessage:"IDoc validated successfully",segmentValidation:[],processingTime:0};return this.config.publishEvents&&await this.eventBus.publish(I(Kt.IDocValidated,this.domainName,{idocType:e.type,direction:s.direction,passed:s.passed,statusCode:s.statusCode})),this.completeWorkflow(i),f(s)}catch(n){return this.failWorkflow(i,String(n)),p(y(n))}}async validateODataMetadata(e){let r=v();try{this.startWorkflow(r,"odata");let i=await this.spawnAgent(r,"qe-odata-contract-tester",{task:"validate-metadata",serviceUrl:e});if(!i.success)return this.failWorkflow(r,i.error.message),p(i.error);let n={version:"v4",serviceUrl:e,entitySets:[],functionImports:[],actions:[]};return await this.memory.set(`enterprise-integration:odata:${encodeURIComponent(e)}`,n,{namespace:"enterprise-integration",persist:!0}),this.completeWorkflow(r),f(n)}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async testODataEntitySet(e,r){let i=v();try{this.startWorkflow(i,"odata");let n=await this.spawnAgent(i,"qe-odata-contract-tester",{task:"test-entity-set",metadata:e,entitySet:r});if(!n.success)return this.failWorkflow(i,n.error.message),p(n.error);let s={entitySet:r,operation:"CRUD",passed:!0,statusCode:200,validationErrors:[],duration:0};return this.config.publishEvents&&await this.eventBus.publish(I(Kt.ODataTested,this.domainName,{entitySet:r,operation:s.operation,passed:s.passed,version:e.version})),this.completeWorkflow(i),f(s)}catch(n){return this.failWorkflow(i,String(n)),p(y(n))}}async validateMessageFlow(e,r){let i=v();try{this.startWorkflow(i,"middleware");let n=await this.spawnAgent(i,"qe-middleware-validator",{task:"validate-flow",flow:e,input:r});if(!n.success)return this.failWorkflow(i,n.error.message),p(n.error);let s={flowName:e.name,passed:!0,routingCorrect:!0,transformationCorrect:!0,errorHandlingCorrect:!0,validationErrors:[],duration:0};return this.config.publishEvents&&await this.eventBus.publish(I(Kt.MiddlewareFlowTested,this.domainName,{flowName:e.name,passed:s.passed,routingCorrect:s.routingCorrect,transformationCorrect:s.transformationCorrect})),this.completeWorkflow(i),f(s)}catch(n){return this.failWorkflow(i,String(n)),p(y(n))}}async validateTransformation(e,r,i){let n=v();try{this.startWorkflow(n,"middleware");let s=await this.spawnAgent(n,"qe-middleware-validator",{task:"validate-transformation",spec:e,input:r,expectedOutput:i});return s.success?(this.completeWorkflow(n),f(!0)):(this.failWorkflow(n,s.error.message),p(s.error))}catch(s){return this.failWorkflow(n,String(s)),p(y(s))}}async analyzeSod(e,r){let i=v();try{this.startWorkflow(i,"sod");let n=await this.spawnAgent(i,"qe-sod-analyzer",{task:"analyze-sod",userId:e,ruleset:r});if(!n.success)return this.failWorkflow(i,n.error.message),p(n.error);let s={userId:e,conflicts:[],riskScore:0,compliant:!0,recommendations:[]};return this.config.publishEvents&&await this.eventBus.publish(I(Kt.SodAnalyzed,this.domainName,{userId:e,conflicts:s.conflicts.length,compliant:s.compliant,riskScore:s.riskScore})),await this.memory.set(`enterprise-integration:sod:${e}:${Date.now()}`,{userId:e,ruleset:r.name,conflicts:s.conflicts.length,compliant:s.compliant,riskScore:s.riskScore,timestamp:new Date().toISOString()},{namespace:"enterprise-integration",persist:!0}),this.completeWorkflow(i),f(s)}catch(n){return this.failWorkflow(i,String(n)),p(y(n))}}async spawnAgent(e,r,i){let n={name:`${r}-${e.slice(0,8)}`,domain:"enterprise-integration",type:r,capabilities:[r],config:{workflowId:e,...i}},s=await this.agentCoordinator.spawn(n);return s.success&&this.addAgentToWorkflow(e,s.value),s}async verifyCriticalFinding(e,r){let i=V({id:v(),type:e.type,confidence:r,description:e.description,payload:e.payload,detectedBy:"enterprise-integration-coordinator",severity:r>.9?"critical":"high"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(Da.info(`Finding verified by consensus: ${e.type}`),!0):(Da.warn(`Finding NOT verified: ${e.type}`),!1)}return!0}async handleContractVerified(e){let r=e.payload;(r?.contractType==="soap"||r?.contractType==="odata")&&await this.memory.set(`enterprise-integration:contract-event:${Date.now()}`,{contractId:r.contractId,type:r.contractType,passed:r.passed,timestamp:new Date().toISOString()},{namespace:"enterprise-integration",ttl:86400})}async handleFaultInjected(e){let r=e.payload;(r?.targetService?.includes("middleware")||r?.targetService?.includes("esb"))&&Da.info(`Middleware fault injection detected: ${r.targetService}`)}};var ml=class extends j{constructor(e,r,i,n={}){super(e,r);this.agentCoordinator=i;this.pluginConfig=n}agentCoordinator;coordinator=null;pluginConfig;get name(){return"enterprise-integration"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{validateWsdl:this.validateWsdl.bind(this),testSoapOperation:this.testSoapOperation.bind(this),testMessageFlow:this.testMessageFlow.bind(this),testDlqHandling:this.testDlqHandling.bind(this),testBapiCall:this.testBapiCall.bind(this),validateIdoc:this.validateIdoc.bind(this),validateODataMetadata:this.validateODataMetadata.bind(this),testODataEntitySet:this.testODataEntitySet.bind(this),validateMessageFlow:this.validateMessageFlow.bind(this),validateTransformation:this.validateTransformation.bind(this),analyzeSod:this.analyzeSod.bind(this),getCoordinator:()=>this.coordinator,getActiveWorkflows:()=>this.coordinator?.getActiveWorkflows()||[]}}getTaskHandlers(){return new Map([["enterprise-integration:soap-test",async e=>{if(!this.coordinator)return p(new Error("Enterprise integration coordinator not initialized"));let r=e.wsdl,i=e.operation,n=e.input;return e.url&&!r?this.coordinator.validateWsdl(e.url):!r||!i?p(new Error("Invalid soap-test payload: missing wsdl or operation")):this.coordinator.testSoapOperation(r,i,n)}],["enterprise-integration:message-broker-test",async e=>{if(!this.coordinator)return p(new Error("Enterprise integration coordinator not initialized"));let r=e.brokerConfig,i=e.testCase,n=e.queue;return r?n&&!i?this.coordinator.testDlqHandling(r,n):i?this.coordinator.testMessageFlow(r,i):p(new Error("Invalid message-broker-test payload: missing testCase")):p(new Error("Invalid message-broker-test payload: missing brokerConfig"))}],["enterprise-integration:sap-rfc-test",async e=>{if(!this.coordinator)return p(new Error("Enterprise integration coordinator not initialized"));let r=e.connection,i=e.bapi;return!r||!i?p(new Error("Invalid sap-rfc-test payload: missing connection or bapi")):this.coordinator.testBapiCall(r,i)}],["enterprise-integration:sap-idoc-validate",async e=>{if(!this.coordinator)return p(new Error("Enterprise integration coordinator not initialized"));let r=e.definition,i=e.content;return!r||!i?p(new Error("Invalid sap-idoc-validate payload: missing definition or content")):this.coordinator.validateIdoc(r,i)}],["enterprise-integration:odata-test",async e=>{if(!this.coordinator)return p(new Error("Enterprise integration coordinator not initialized"));let r=e.serviceUrl,i=e.metadata,n=e.entitySet;return r&&!i?this.coordinator.validateODataMetadata(r):!i||!n?p(new Error("Invalid odata-test payload: missing metadata or entitySet")):this.coordinator.testODataEntitySet(i,n)}],["enterprise-integration:esb-flow-test",async e=>{if(!this.coordinator)return p(new Error("Enterprise integration coordinator not initialized"));let r=e.flow,i=e.input,n=e.spec;if(n){let s=e.transformInput,a=e.expectedOutput;return!s||!a?p(new Error("Invalid esb-flow-test payload: missing transformInput or expectedOutput for transformation")):this.coordinator.validateTransformation(n,s,a)}return!r||!i?p(new Error("Invalid esb-flow-test payload: missing flow or input")):this.coordinator.validateMessageFlow(r,i)}],["enterprise-integration:sod-analyze",async e=>{if(!this.coordinator)return p(new Error("Enterprise integration coordinator not initialized"));let r=e.userId,i=e.ruleset;return!r||!i?p(new Error("Invalid sod-analyze payload: missing userId or ruleset")):this.coordinator.analyzeSod(r,i)}]])}async onInitialize(){this.coordinator=new Ia(this.eventBus,this.memory,this.agentCoordinator,this.pluginConfig.coordinator),await this.coordinator.initialize(),this.updateHealth({status:"idle",agents:{total:0,active:0,idle:0,failed:0},lastActivity:new Date,errors:[]})}async onDispose(){this.coordinator&&await this.coordinator.dispose(),this.coordinator=null}subscribeToEvents(){this.eventBus.subscribe("contract-testing.ContractVerified",this.handleContractVerified.bind(this)),this.eventBus.subscribe("quality-assessment.QualityGateEvaluated",this.handleQualityGate.bind(this)),this.eventBus.subscribe("chaos-resilience.FaultInjected",this.handleFaultInjected.bind(this))}async onEvent(e){switch(this.updateHealth({lastActivity:new Date}),e.type){case"contract-testing.ContractVerified":await this.handleContractVerified(e);break;case"quality-assessment.QualityGateEvaluated":await this.handleQualityGate(e);break;case"chaos-resilience.FaultInjected":await this.handleFaultInjected(e);break;default:break}}async validateWsdl(e){this.ensureInitialized();try{let r=await this.coordinator.validateWsdl(e);return r.success?this.trackSuccessfulOperation("validateWsdl"):this.trackFailedOperation(new Error(r.error.message)),r}catch(r){return this.handleError(r)}}async testSoapOperation(e,r,i){this.ensureInitialized();try{let n=await this.coordinator.testSoapOperation(e,r,i);return n.success?this.trackSuccessfulOperation("testSoapOperation"):this.trackFailedOperation(new Error(n.error.message)),n}catch(n){return this.handleError(n)}}async testMessageFlow(e,r){this.ensureInitialized();try{let i=await this.coordinator.testMessageFlow(e,r);return i.success?this.trackSuccessfulOperation("testMessageFlow"):this.trackFailedOperation(new Error(i.error.message)),i}catch(i){return this.handleError(i)}}async testDlqHandling(e,r){this.ensureInitialized();try{let i=await this.coordinator.testDlqHandling(e,r);return i.success?this.trackSuccessfulOperation("testDlqHandling"):this.trackFailedOperation(new Error(i.error.message)),i}catch(i){return this.handleError(i)}}async testBapiCall(e,r){this.ensureInitialized();try{let i=await this.coordinator.testBapiCall(e,r);return i.success?this.trackSuccessfulOperation("testBapiCall"):this.trackFailedOperation(new Error(i.error.message)),i}catch(i){return this.handleError(i)}}async validateIdoc(e,r){this.ensureInitialized();try{let i=await this.coordinator.validateIdoc(e,r);return i.success?this.trackSuccessfulOperation("validateIdoc"):this.trackFailedOperation(new Error(i.error.message)),i}catch(i){return this.handleError(i)}}async validateODataMetadata(e){this.ensureInitialized();try{let r=await this.coordinator.validateODataMetadata(e);return r.success?this.trackSuccessfulOperation("validateODataMetadata"):this.trackFailedOperation(new Error(r.error.message)),r}catch(r){return this.handleError(r)}}async testODataEntitySet(e,r){this.ensureInitialized();try{let i=await this.coordinator.testODataEntitySet(e,r);return i.success?this.trackSuccessfulOperation("testODataEntitySet"):this.trackFailedOperation(new Error(i.error.message)),i}catch(i){return this.handleError(i)}}async validateMessageFlow(e,r){this.ensureInitialized();try{let i=await this.coordinator.validateMessageFlow(e,r);return i.success?this.trackSuccessfulOperation("validateMessageFlow"):this.trackFailedOperation(new Error(i.error.message)),i}catch(i){return this.handleError(i)}}async validateTransformation(e,r,i){this.ensureInitialized();try{let n=await this.coordinator.validateTransformation(e,r,i);return n.success?this.trackSuccessfulOperation("validateTransformation"):this.trackFailedOperation(new Error(n.error.message)),n}catch(n){return this.handleError(n)}}async analyzeSod(e,r){this.ensureInitialized();try{let i=await this.coordinator.analyzeSod(e,r);return i.success?this.trackSuccessfulOperation("analyzeSod"):this.trackFailedOperation(new Error(i.error.message)),i}catch(i){return this.handleError(i)}}async handleContractVerified(e){let r=e.payload;(r.contractType==="soap"||r.contractType==="odata")&&await this.memory.set(`enterprise-integration:contract-verified:${r.contractId}`,{contractId:r.contractId,type:r.contractType,passed:r.passed,timestamp:new Date().toISOString()},{namespace:"enterprise-integration",ttl:86400})}async handleQualityGate(e){let r=e.payload;r.checks.find(n=>n.name==="enterprise-integration")||await this.memory.set(`enterprise-integration:quality-gate-warning:${r.gateId}`,{warning:"Enterprise integration testing not included in quality gate",timestamp:new Date().toISOString()},{namespace:"enterprise-integration",ttl:86400})}async handleFaultInjected(e){let r=e.payload;(r.targetService?.includes("middleware")||r.targetService?.includes("esb")||r.targetService?.includes("broker")||r.targetService?.includes("mq"))&&await this.memory.set(`enterprise-integration:fault-correlation:${r.faultId||Date.now()}`,{targetService:r.targetService,faultType:r.faultType,timestamp:new Date().toISOString()},{namespace:"enterprise-integration",ttl:3600})}ensureInitialized(){if(!this._initialized)throw new Error("EnterpriseIntegrationPlugin is not initialized");if(!this.coordinator)throw new Error("EnterpriseIntegrationPlugin coordinator is not available")}handleError(e){let r=y(e),i=this.getHealth();return this.updateHealth({errors:[...i.errors.slice(-9),r.message],status:i.errors.length>=5?"degraded":i.status}),{success:!1,error:r}}trackSuccessfulOperation(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,total:r.agents.total+1,idle:r.agents.idle+1},lastActivity:new Date})}trackFailedOperation(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,failed:r.agents.failed+1},errors:[...r.errors.slice(-9),e.message]})}};function Um(u,t,e,r){return new ml(u,t,e,r)}var Km={"test-generation":(u,t,e,r)=>Lo(u,t,e,void 0,r),"test-execution":(u,t,e,r)=>qu(u,t,r),"coverage-analysis":(u,t,e,r)=>oc(u,t,r),"quality-assessment":(u,t,e,r)=>yc(u,t,e,void 0,r),"defect-intelligence":(u,t,e,r)=>Td(u,t,e,void 0,r),"requirements-validation":(u,t,e,r)=>Pd(u,t,e,void 0,r),"code-intelligence":(u,t,e,r)=>Mc(u,t,e,void 0,r),"security-compliance":(u,t,e,r)=>tl(u,t,e,void 0,r),"contract-testing":(u,t,e,r)=>fm(u,t,e,void 0,r),"visual-accessibility":(u,t,e,r)=>Im(u,t,e,void 0,r),"chaos-resilience":(u,t,e,r)=>Lm(u,t,e,void 0,r),"learning-optimization":(u,t,e,r)=>Hm(u,t,e,void 0,r),"enterprise-integration":(u,t,e,r)=>Um(u,t,e),coordination:(u,t,e,r)=>jm(u,t,e)},mb={maxConcurrentAgents:Lr.MAX_CONCURRENT_AGENTS,memoryBackend:"hybrid",hnswEnabled:!0,lazyLoading:!0,enabledDomains:[...we],dataDir:void 0,enableExperienceBridge:!0,enableDreamScheduler:!0},pl=class{_eventBus;_coordinator;_plugins;_memory;_config;_startTime;_initialized=!1;_loopTracker;_experienceBridge;_dreamScheduler;_llmRouter;_llmRouterBuild;constructor(t={}){this._config={...mb,...t},this._startTime=new Date,this._memory=new Oa,this._eventBus=new pn,this._coordinator=new hn(this._config.maxConcurrentAgents),this._plugins=new Gr(this._eventBus,this._memory,this._config.lazyLoading),this._loopTracker=new gn}get eventBus(){return this._eventBus}get coordinator(){return this._coordinator}get plugins(){return this._plugins}get memory(){return this._memory}get llmRouter(){return this._llmRouter}async initialize(){if(this._initialized)return;let t=fl(),e=this._config.dataDir||Jt.join(t,".agentic-qe");if(Ma.existsSync(e)||Ma.mkdirSync(e,{recursive:!0}),this._config.memoryBackend==="memory"){let i=Jt.join(Fa("os").tmpdir(),`aqe-test-${Date.now()}-${Qm().slice(0,12)}.db`);await vl({dbPath:i})}else this._memory=new yl({sqlite:{path:Jt.join(e,"memory.db"),walMode:!0,poolSize:3,busyTimeout:gl.BUSY_TIMEOUT_MS},enableFallback:!0,defaultNamespace:"qe-kernel"}),this._plugins=new Gr(this._eventBus,this._memory,this._config.lazyLoading);await this._initializeLLMRouter(t);for(let i of this._config.enabledDomains){let n=Km[i];n&&this._plugins.registerFactory(i,async(s,a)=>Promise.resolve(n(s,a,this._coordinator,this._llmRouter)))}await this._memory.initialize();let r=new yn({agentId:"qe-kernel"});this._eventBus.registerMiddleware(r);try{let i=Jt.join(e,"plugins"),n=new bl({cacheDir:i}),a=new wl({cache:n}).resolveLoadOrder();for(let o of a.ordered){let c=o.manifest,l=n.get(c.name,c.version);if(!l)continue;let d=Jt.join(l.path,c.entryPoint);for(let m of c.domains){let h=m;if(Km[h])continue;this._plugins.registerFactory(h,async(b,w)=>{let C=await import(d),S=C.default??C.createPlugin;if(typeof S!="function")throw new Error(`Plugin "${c.name}" entry point must export a default function or "createPlugin" function`);return S(b,w,this._coordinator,this._llmRouter)})}}}catch{}this._config.lazyLoading||await this._plugins.loadAll();try{let{isAgentMemoryBranchingEnabled:i,isRVFPatternStoreEnabled:n}=await import("./feature-flags-PVI7A4RE.js");if(i()&&n()){let{getSharedRvfAdapter:s}=await import("./shared-rvf-adapter-U6JE4O6A.js"),{AgentMemoryBranch:a}=await import("./agent-memory-branch-SSFYAVIK.js"),o=s(e,384);if(o){let c=new a(o,{branchDir:Jt.join(e,"branches")});this._coordinator.setMemoryBranch(c)}}}catch{}try{let{getRvfMigrationStage:i}=await import("./feature-flags-PVI7A4RE.js"),n=i();if(n>=2){let{RvfMigrationCoordinator:s}=await import("./rvf-migration-coordinator-SLNB3XPW.js");await s.getInstance({stage:n}).initialize()}}catch{}if(this._config.enableExperienceBridge!==!1){try{await this._plugins.loadAll()}catch(i){console.warn("[QEKernel] domain plugin pre-load (for bridge subscribers) failed:",i instanceof Error?i.message:i)}try{this._experienceBridge=new vn(this._eventBus,this._memory),await this._experienceBridge.start()}catch(i){console.warn("[QEKernel] CapturedExperienceBridge failed to start:",i instanceof Error?i.message:i),this._experienceBridge=void 0}}if(this._config.enableDreamScheduler!==!1)try{let i=tn({maxDurationMs:1e4,minConceptsRequired:3});await i.initialize(),this._dreamScheduler=new Al({dreamEngine:i,eventBus:this._eventBus,memoryBackend:this._memory}),await this._dreamScheduler.initialize(),this._dreamScheduler.start()}catch(i){if(console.warn("[QEKernel] DreamScheduler failed to start:",i instanceof Error?i.message:i),this._dreamScheduler)try{await this._dreamScheduler.dispose()}catch{}this._dreamScheduler=void 0}this._initialized=!0}async _initializeLLMRouter(t){let e=(process.env.AQE_LLM_ROUTER_DISABLED??"").trim().toLowerCase();if(e&&e!=="false"&&e!=="0"&&e!=="no"&&e!=="off"){this._llmRouter=void 0;return}let r=this._config.llmRouter??{},i=r.enabled??"auto";if(i===!1){this._llmRouter=void 0;return}try{let n=await Tl({projectRoot:t,override:r.configOverride,providerManager:r.providerManager});if(!n){i===!0&&(console.warn("[QEKernel] llmRouter.enabled=true but no provider available \u2014 continuing without LLM router (domain services will skip LLM enhancement)"),await this._publishLLMRouterEvent("init-no-provider",{reason:"no provider available in env or disk config"})),this._llmRouter=void 0;return}this._llmRouterBuild=n,this._llmRouter=n.router;try{let{setSharedLLMRouter:s}=await import("./base-KKEBUHZC.js");s(n.router)}catch{}}catch(n){let s=n instanceof Error?n.message:String(n);console.warn("[QEKernel] LLM router init failed; continuing without LLM enhancement:",s),await this._publishLLMRouterEvent("init-failed",{error:s,stack:n instanceof Error?n.stack:void 0}),this._llmRouter=void 0}}async _publishLLMRouterEvent(t,e){try{await this._eventBus.publish({id:Qm(),type:`kernel.llm-router.${t}`,timestamp:new Date,source:"qe-kernel",payload:e})}catch{}}async dispose(){if(this._dreamScheduler){try{await this._dreamScheduler.dispose()}catch(t){console.warn("[QEKernel] DreamScheduler dispose failed:",t instanceof Error?t.message:t)}this._dreamScheduler=void 0}if(this._experienceBridge&&(await this._experienceBridge.stop(),this._experienceBridge=void 0),await this._plugins.disposeAll(),await this._coordinator.dispose(),await this._eventBus.dispose(),await this._memory.dispose(),this._llmRouter){try{let{resetSharedLLMRouter:t}=await import("./base-KKEBUHZC.js");t()}catch{}this._llmRouter=void 0,this._llmRouterBuild=void 0}this._initialized=!1}getDomainAPI(t){return this._plugins.getPlugin(t)?.getAPI()}async getDomainAPIAsync(t){let e=this._plugins.getPlugin(t);if(!e&&this._config.lazyLoading&&this._config.enabledDomains.includes(t))try{e=await this._plugins.load(t)}catch(r){console.error(`[QEKernel] Failed to lazy load domain ${t}:`,r);return}return e?.getAPI()}async ensureDomainLoaded(t){if(this._plugins.isLoaded(t))return!0;if(!this._config.enabledDomains.includes(t))return console.warn(`[QEKernel] Domain ${t} is not enabled`),!1;try{return await this._plugins.load(t),!0}catch(e){return console.error(`[QEKernel] Failed to load domain ${t}:`,e),!1}}isDomainLoaded(t){return this._plugins.isLoaded(t)}getLoadedDomains(){return this._plugins.getLoaded()}getPendingDomains(){let t=new Set(this._plugins.getLoaded());return this._config.enabledDomains.filter(e=>!t.has(e))}getHealth(){let t=this._coordinator.listAgents(),e={};for(let c of this._plugins.getLoaded()){let l=this._plugins.getPlugin(c);l&&(e[c]=l.getHealth())}for(let c of we)if(!e[c]){let l=this._config.enabledDomains.includes(c),d=this._config.lazyLoading&&l;e[c]={status:d?"healthy":l?"degraded":"healthy",agents:{total:0,active:0,idle:0,failed:0},errors:d?[]:l?["Domain not yet loaded"]:[],loaded:!1,lazyLoadable:d}}let r=this._coordinator.getActiveCount(),i=0,n=Number.MAX_SAFE_INTEGER;if(this._memory instanceof Oa){let c=this._memory.getStats();i=c.entries+c.vectors}else i=0;let a=this._eventBus.getMiddlewares().find(c=>c.name==="semantic-anti-drift"),o=a?a.getStats():void 0;return{status:this.determineOverallStatus(e),uptime:Date.now()-this._startTime.getTime(),domains:e,agents:{total:t.length,active:r,maxAllowed:this._config.maxConcurrentAgents},memory:{used:i,available:n},...o?{antiDrift:o}:{}}}determineOverallStatus(t){let e=Object.values(t).map(r=>r.status);return e.some(r=>r==="unhealthy")?"unhealthy":e.some(r=>r==="degraded")?"degraded":"healthy"}getConfig(){return{...this._config}}checkToolCall(t,e,r){if(process.env.AQE_LOOP_DETECTION_ENABLED==="false")return this._loopTracker.trackCall(t,e,r);let i=this._loopTracker.trackCall(t,e,r);if(i.action==="warn"){let n={id:`loop-warn-${t}-${Date.now()}`,type:Wa.LOOP_WARNING,timestamp:new Date,source:"coordination",correlationId:t,payload:{agentId:t,toolName:e,callCount:i.callCount,signature:i.signature}};this._eventBus.publish(n)}else if(i.action==="steer"){let n={id:`loop-detected-${t}-${Date.now()}`,type:Wa.LOOP_DETECTED,timestamp:new Date,source:"coordination",correlationId:t,payload:{agentId:t,toolName:e,callCount:i.callCount,signature:i.signature,steeringMessage:i.steeringMessage}};this._eventBus.publish(n)}return i}get loopTracker(){return this._loopTracker}};function YK(u){return new pl(u)}export{Ja as a,mp as b,er as c,ai as d,ht as e,lr as f,mr as g,_t as h,Dc as i,$c as j,Us as k,Tr as l,Ar as m,Ca as n,Pr as o,Dr as p,jt as q,Wt as r,Ut as s,Ee as t,xe as u,pl as v,YK as w};
|