agentic-qe 3.9.13 → 3.9.15
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/accessibility-testing/SKILL.md +18 -0
- package/.claude/skills/enterprise-integration-testing/SKILL.md +1 -1
- package/.claude/skills/pentest-validation/SKILL.md +1 -1
- package/.claude/skills/qe-browser/evals/qe-browser.yaml +46 -63
- package/.claude/skills/qe-browser/scripts/smoke-test.sh +16 -4
- package/.claude/skills/skills-manifest.json +1 -1
- package/CHANGELOG.md +51 -0
- package/assets/skills/accessibility-testing/SKILL.md +18 -0
- package/assets/skills/qe-browser/evals/qe-browser.yaml +46 -63
- package/assets/skills/qe-browser/scripts/smoke-test.sh +16 -4
- package/assets/skills/skills-manifest.json +1 -1
- package/dist/cli/bundle.js +5 -5
- package/dist/cli/chunks/adapter-P2EPBJLF.js +2 -0
- package/dist/cli/chunks/{agent-booster-wasm-3RBPTJAU.js → agent-booster-wasm-NA2VN5U2.js} +2 -2
- package/dist/cli/chunks/{agent-handler-XV45GCWC.js → agent-handler-NRIF5IOC.js} +2 -2
- package/dist/cli/chunks/{agent-memory-branch-V6EXWWMY.js → agent-memory-branch-NW3UB2UW.js} +2 -2
- package/dist/cli/chunks/aqe-learning-engine-6UITO3NJ.js +2 -0
- package/dist/cli/chunks/{audit-WXFI4AC4.js → audit-5CSEDVJR.js} +2 -2
- package/dist/cli/chunks/base-JHBJXVGP.js +2 -0
- package/dist/cli/chunks/{better-sqlite3-23MIVVHF.js → better-sqlite3-FZ32SHZ6.js} +2 -2
- package/dist/cli/chunks/{brain-handler-LQUMAACV.js → brain-handler-ISVST4MR.js} +3 -3
- package/dist/cli/chunks/{branch-enumerator-HE37VX7G.js → branch-enumerator-IUHWHIMV.js} +2 -2
- package/dist/cli/chunks/{browser-3VG5M7WM.js → browser-D4F3327X.js} +2 -2
- package/dist/cli/chunks/browser-workflow-U4OON5DZ.js +2 -0
- package/dist/cli/chunks/{chunk-ZS5BM2EE.js → chunk-2BBKAX7X.js} +2 -2
- package/dist/cli/chunks/{chunk-6GYMFSPA.js → chunk-2CN2NPJQ.js} +2 -2
- package/dist/cli/chunks/{chunk-OGHIQCJU.js → chunk-2L5ZFBHP.js} +2 -2
- package/dist/cli/chunks/{chunk-VCJP7HQG.js → chunk-2XW36KDQ.js} +2 -2
- package/dist/cli/chunks/{chunk-AOTEEGQA.js → chunk-37ZSWRRP.js} +2 -2
- package/dist/cli/chunks/chunk-3BA2FGSA.js +2 -0
- package/dist/cli/chunks/{chunk-54A2LVKM.js → chunk-3FUKJT4S.js} +2 -2
- package/dist/cli/chunks/chunk-3NIHJIWP.js +2 -0
- package/dist/cli/chunks/{chunk-LHZLH6I4.js → chunk-3RSPEFU3.js} +2 -2
- package/dist/cli/chunks/{chunk-I6O4MVEY.js → chunk-3Y4YZDHJ.js} +4 -4
- package/dist/cli/chunks/{chunk-AEKTVLLF.js → chunk-4M7RBSW6.js} +2 -2
- package/dist/cli/chunks/{chunk-LRHJOYKY.js → chunk-4T36OQUK.js} +3 -3
- package/dist/cli/chunks/{chunk-XV42SKJD.js → chunk-56YHSI6R.js} +2 -2
- package/dist/cli/chunks/{chunk-OBDM6OJL.js → chunk-62MVVEGH.js} +1 -1
- package/dist/cli/chunks/chunk-65QA7MYW.js +2 -0
- package/dist/cli/chunks/{chunk-RYPUA6E2.js → chunk-6AMD4PZB.js} +2 -2
- package/dist/cli/chunks/{chunk-OUNZPHTA.js → chunk-6BHAGCZD.js} +1 -1
- package/dist/cli/chunks/{chunk-YBKSENTJ.js → chunk-6F3H2C5H.js} +5 -5
- package/dist/cli/chunks/{chunk-OM7A3YC3.js → chunk-6OEGZSRK.js} +2 -2
- package/dist/cli/chunks/{chunk-Q3MQYATA.js → chunk-6TOUMCSE.js} +2 -2
- package/dist/cli/chunks/chunk-6Z7LYE2B.js +2 -0
- package/dist/cli/chunks/{chunk-TRJRRJV3.js → chunk-7J5KWUC2.js} +1 -1
- package/dist/cli/chunks/{chunk-VWEGO7BY.js → chunk-7ZPNQ3T6.js} +1 -1
- package/dist/cli/chunks/{chunk-6LDRSG7C.js → chunk-AE65B2ZE.js} +3 -3
- package/dist/cli/chunks/{chunk-D22MEX2U.js → chunk-AVKUFN3C.js} +2 -2
- package/dist/cli/chunks/{chunk-4VETZICF.js → chunk-B4BOOOYM.js} +1 -1
- package/dist/cli/chunks/{chunk-Y7YSJD4I.js → chunk-BGUCXJEJ.js} +2 -2
- package/dist/cli/chunks/{chunk-JV7HKHQS.js → chunk-C5BRTU4V.js} +2 -2
- package/dist/cli/chunks/{chunk-FEGITTAE.js → chunk-CF3W34BA.js} +1 -1
- package/dist/cli/chunks/chunk-CSB2M7IX.js +2 -0
- package/dist/cli/chunks/{chunk-ERGY45RL.js → chunk-CUQBOVRP.js} +1 -1
- package/dist/cli/chunks/{chunk-W6LEOFA4.js → chunk-CWWUBZNX.js} +2 -2
- package/dist/cli/chunks/{chunk-GKRKCJ6D.js → chunk-D32YCVCA.js} +2 -2
- package/dist/cli/chunks/{chunk-E7P6GAD7.js → chunk-D3FV5NNA.js} +2 -2
- package/dist/cli/chunks/{chunk-YYQVSVBO.js → chunk-D3ZUSXFY.js} +2 -2
- package/dist/cli/chunks/{chunk-6HSHLSGU.js → chunk-DATFN5DG.js} +2 -2
- package/dist/cli/chunks/{chunk-UCCNB75R.js → chunk-DPEG44BS.js} +2 -2
- package/dist/cli/chunks/chunk-DYQ7HTEU.js +12 -0
- package/dist/cli/chunks/{chunk-SL66MHDM.js → chunk-E3EDVRB5.js} +1 -1
- package/dist/cli/chunks/chunk-ELLNKP3I.js +24 -0
- package/dist/cli/chunks/{chunk-3RM2VNYG.js → chunk-EORSYD66.js} +2 -2
- package/dist/cli/chunks/{chunk-OHG6SNIA.js → chunk-ESQSX37W.js} +2 -2
- package/dist/cli/chunks/{chunk-H53V7GI3.js → chunk-EY2DGYQX.js} +1 -1
- package/dist/cli/chunks/chunk-FEVTMHO6.js +2 -0
- package/dist/cli/chunks/{chunk-Q7TWE55T.js → chunk-FSOY2XB4.js} +4 -4
- package/dist/cli/chunks/{chunk-QIE76ERL.js → chunk-FW6QBTPE.js} +1 -1
- package/dist/cli/chunks/{chunk-5TDHUYYF.js → chunk-G3FUOFXA.js} +2 -2
- package/dist/cli/chunks/{chunk-BUIMIUJA.js → chunk-GHEO5YVA.js} +1 -1
- package/dist/cli/chunks/chunk-GLJ6CJNY.js +5 -0
- package/dist/cli/chunks/{chunk-V6UODTBP.js → chunk-GWUO3RY5.js} +1 -1
- package/dist/cli/chunks/{chunk-3IJ4NRJF.js → chunk-H6DAP4KS.js} +2 -2
- package/dist/cli/chunks/chunk-HJNFBJT5.js +3021 -0
- package/dist/cli/chunks/{chunk-KULWZMVC.js → chunk-HNAQNAGI.js} +4 -4
- package/dist/cli/chunks/{chunk-VU7ENCSU.js → chunk-HPY7HGVQ.js} +2 -2
- package/dist/cli/chunks/{chunk-4PCHU2X7.js → chunk-HWK27KJK.js} +1 -1
- package/dist/cli/chunks/chunk-ICXWXO5P.js +2 -0
- package/dist/cli/chunks/{chunk-OKCI6BNZ.js → chunk-IHDW4HW7.js} +2 -2
- package/dist/cli/chunks/chunk-II5KTTIS.js +65 -0
- package/dist/cli/chunks/{chunk-OP54A7C6.js → chunk-IMLH32AG.js} +2 -2
- package/dist/cli/chunks/{chunk-TNQBHQFH.js → chunk-IPTGPCEL.js} +2 -2
- package/dist/cli/chunks/{chunk-V2CV6J2A.js → chunk-IPVKVPAF.js} +2 -2
- package/dist/cli/chunks/{chunk-AV23XNRL.js → chunk-ISNXE6TP.js} +2 -2
- package/dist/cli/chunks/{chunk-CF5EJGOV.js → chunk-JAIIPEE6.js} +2 -2
- package/dist/cli/chunks/{chunk-3AOWTHLS.js → chunk-JJDHD7SC.js} +2 -2
- package/dist/cli/chunks/{chunk-HXLAXSEM.js → chunk-JQRR37YY.js} +2 -2
- package/dist/cli/chunks/chunk-KJTXY3DW.js +3 -0
- package/dist/cli/chunks/{chunk-XXQYSDLV.js → chunk-KKBSX43Q.js} +2 -2
- package/dist/cli/chunks/{chunk-EBQUXPIG.js → chunk-LLVS3UYZ.js} +2 -2
- package/dist/cli/chunks/{chunk-VJN7NQGI.js → chunk-LNUWNRRJ.js} +10 -10
- package/dist/cli/chunks/{chunk-IQGVQBVS.js → chunk-MBDX4OHD.js} +1 -1
- package/dist/cli/chunks/{chunk-ZXJNX5D2.js → chunk-MHL6CPGY.js} +1 -1
- package/dist/cli/chunks/{chunk-YCQ2GHFH.js → chunk-MO4Q5ZGE.js} +2 -2
- package/dist/cli/chunks/{chunk-AZPDX4KS.js → chunk-MS6T4VCU.js} +2 -2
- package/dist/cli/chunks/chunk-N2RPLPVG.js +18 -0
- package/dist/cli/chunks/chunk-NL2PQLRD.js +2 -0
- package/dist/cli/chunks/{chunk-GHAEDZDE.js → chunk-NWMYV7KG.js} +2 -2
- package/dist/cli/chunks/{chunk-ZUW3KVML.js → chunk-O6CHLZYT.js} +2 -2
- package/dist/cli/chunks/{chunk-EC2CI3ZC.js → chunk-O6J7MKRV.js} +2 -2
- package/dist/cli/chunks/{chunk-SSZMISGC.js → chunk-OBZMQFWG.js} +3 -3
- package/dist/cli/chunks/{chunk-TU3JIH3U.js → chunk-OHESV6I3.js} +4 -4
- package/dist/cli/chunks/{chunk-X3UVXJIK.js → chunk-OMTYOIOS.js} +2 -2
- package/dist/cli/chunks/{chunk-TPTKR5ZO.js → chunk-ORKGVVXK.js} +1 -1
- package/dist/cli/chunks/{chunk-QHCOAG7D.js → chunk-OUP2X3LT.js} +1 -1
- package/dist/cli/chunks/{chunk-DY5JRJXV.js → chunk-PSOIVDD2.js} +3 -3
- package/dist/cli/chunks/{chunk-UDIRBCZW.js → chunk-Q3E6Z2RQ.js} +1 -1
- package/dist/cli/chunks/{chunk-RMNZSGTE.js → chunk-Q3GDSFGA.js} +2 -2
- package/dist/cli/chunks/{chunk-FLML5IT7.js → chunk-QNLZKD7E.js} +2 -2
- package/dist/cli/chunks/{chunk-WVWB7K6H.js → chunk-R4G64UH3.js} +2 -2
- package/dist/cli/chunks/{chunk-ES6CEZG2.js → chunk-REUGPZIA.js} +1 -1
- package/dist/cli/chunks/{chunk-FS4TPAAA.js → chunk-RODJK6G6.js} +1 -1
- package/dist/cli/chunks/{chunk-4MZZMWF6.js → chunk-RPOW5LWO.js} +1 -1
- package/dist/cli/chunks/{chunk-BE2DYHUB.js → chunk-RSOOENGE.js} +2 -2
- package/dist/cli/chunks/{chunk-RURYOWWU.js → chunk-RTVD7SZQ.js} +1 -1
- package/dist/cli/chunks/{chunk-Z6F4GRXY.js → chunk-RWVFOXYM.js} +2 -2
- package/dist/cli/chunks/{chunk-2RTGP76Y.js → chunk-SSQ42GI7.js} +2 -2
- package/dist/cli/chunks/{chunk-AXDGBI4Y.js → chunk-SXUX6PTE.js} +1 -1
- package/dist/cli/chunks/{chunk-MXT7YUOZ.js → chunk-TJDAXI6E.js} +2 -2
- package/dist/cli/chunks/{chunk-ZN7KPIJW.js → chunk-TZWCVGG2.js} +1 -1
- package/dist/cli/chunks/{chunk-TWRGM5TY.js → chunk-U4WDJPRL.js} +2 -2
- package/dist/cli/chunks/chunk-UZOFXYNC.js +2 -0
- package/dist/cli/chunks/{chunk-TOS3PI5Q.js → chunk-V65DK6ZZ.js} +1 -1
- package/dist/cli/chunks/{chunk-7HX2PMBB.js → chunk-V6QARSVQ.js} +2 -2
- package/dist/cli/chunks/{chunk-VHSDZEYF.js → chunk-V775NJOM.js} +1 -1
- package/dist/cli/chunks/{chunk-QNUVC6OX.js → chunk-VBEVZUQW.js} +1 -1
- package/dist/cli/chunks/{chunk-OJGR56BP.js → chunk-VDDQSW4L.js} +2 -2
- package/dist/cli/chunks/{chunk-DHYJMGKC.js → chunk-W4PUKTBF.js} +1 -1
- package/dist/cli/chunks/{chunk-CPRYUCPC.js → chunk-WAQ3U4FC.js} +1 -1
- package/dist/cli/chunks/{chunk-HJHFGPGP.js → chunk-WCOJGDGO.js} +2 -2
- package/dist/cli/chunks/{chunk-77GZ7LXL.js → chunk-WI6UA5HV.js} +2 -2
- package/dist/cli/chunks/{chunk-HHRUXDLT.js → chunk-XALB3KRR.js} +2 -2
- package/dist/cli/chunks/{chunk-W2YCNX4O.js → chunk-XXRDI53H.js} +2 -2
- package/dist/cli/chunks/{chunk-JOCR5TWI.js → chunk-YCYFUYCE.js} +2 -2
- package/dist/cli/chunks/{chunk-WQIB5ERQ.js → chunk-ZHTCZGML.js} +2 -2
- package/dist/cli/chunks/{chunk-WQGP5ULD.js → chunk-ZOAPOVYW.js} +2 -2
- package/dist/cli/chunks/{chunk-VVVIRGO7.js → chunk-ZSC7NHK3.js} +2 -2
- package/dist/cli/chunks/{ci-FEEIAOQN.js → ci-BGUUHDUS.js} +2 -2
- package/dist/cli/chunks/{ci-output-2WMUTORB.js → ci-output-CDFRGBNU.js} +2 -2
- package/dist/cli/chunks/{circuit-breaker-MFEE23XA.js → circuit-breaker-S3NFX6RQ.js} +2 -2
- package/dist/cli/chunks/{claude-flow-setup-6D655INK.js → claude-flow-setup-AJIPJFMC.js} +2 -2
- package/dist/cli/chunks/client-UHHMKUPF.js +2 -0
- package/dist/cli/chunks/{cline-installer-5PIYMPAG.js → cline-installer-6O4KZ5UH.js} +2 -2
- package/dist/cli/chunks/{code-ACS453WG.js → code-IZALXUL5.js} +2 -2
- package/dist/cli/chunks/{code-index-extractor-5SERI6TM.js → code-index-extractor-N7VDH4XF.js} +2 -2
- package/dist/cli/chunks/{codex-installer-WCUUWHP5.js → codex-installer-35GTWCFJ.js} +2 -2
- package/dist/cli/chunks/{completions-6WFG3FPJ.js → completions-XPJFHGG2.js} +2 -2
- package/dist/cli/chunks/{complexity-analyzer-IFZEFCB6.js → complexity-analyzer-DNLCJGUJ.js} +2 -2
- package/dist/cli/chunks/{continuedev-installer-RW6FEEND.js → continuedev-installer-PXAIKNYO.js} +2 -2
- package/dist/cli/chunks/{copilot-installer-UZPE65RL.js → copilot-installer-2TQ5IZNY.js} +2 -2
- package/dist/cli/chunks/{cost-tracker-2R4FT6TY.js → cost-tracker-A5XH4W6S.js} +2 -2
- package/dist/cli/chunks/{coverage-ZUC5U47P.js → coverage-EPIMXTLW.js} +3 -3
- package/dist/cli/chunks/cross-domain-router-GEBXTPZW.js +2 -0
- package/dist/cli/chunks/{cursor-installer-7JBZT7JZ.js → cursor-installer-WMMRPW44.js} +2 -2
- package/dist/cli/chunks/daemon-55DSODOH.js +19 -0
- package/dist/cli/chunks/{dag-attention-scheduler-MS7D2NFM.js → dag-attention-scheduler-5DSWXMMK.js} +2 -2
- package/dist/cli/chunks/{detect-UHOSHYVB.js → detect-NOS46AWN.js} +2 -2
- package/dist/cli/chunks/{domain-handler-BVW4AX7O.js → domain-handler-BFRNU6S3.js} +2 -2
- package/dist/cli/chunks/{domain-transfer-PA2ENF3D.js → domain-transfer-BPSA4HFR.js} +2 -2
- package/dist/cli/chunks/dream-XBRGYPBC.js +2 -0
- package/dist/cli/chunks/esm-node-EV4HOHTZ.js +2 -0
- package/dist/cli/chunks/eval-YDLM23FB.js +15 -0
- package/dist/cli/chunks/{fast-paths-DYQ5NC4Y.js → fast-paths-GISZ7HBO.js} +2 -2
- package/dist/cli/chunks/{feature-flags-V34UZPHG.js → feature-flags-3FLJF6CQ.js} +2 -2
- package/dist/cli/chunks/{feature-flags-YMMGYWT3.js → feature-flags-5WGZLUPQ.js} +2 -2
- package/dist/cli/chunks/{file-discovery-75ZHSK4G.js → file-discovery-PPHUMFSI.js} +2 -2
- package/dist/cli/chunks/{fleet-DD2CFGJL.js → fleet-LHFZ53FS.js} +3 -3
- package/dist/cli/chunks/{gnn-wrapper-UXM3L5LV.js → gnn-wrapper-Z45DRWGI.js} +2 -2
- package/dist/cli/chunks/{heartbeat-handler-ANHRYXNS.js → heartbeat-handler-VMLJ5PDH.js} +4 -4
- package/dist/cli/chunks/heartbeat-scheduler-GUWYDHEY.js +2 -0
- package/dist/cli/chunks/hnsw-adapter-BG73YVXI.js +2 -0
- package/dist/cli/chunks/hnsw-index-K73ZTLJN.js +2 -0
- package/dist/cli/chunks/{hnsw-legacy-bridge-IFUEUOVF.js → hnsw-legacy-bridge-S7UZWDUP.js} +2 -2
- package/dist/cli/chunks/{hnswlib-node-GYVDPTWU.js → hnswlib-node-MIAAS7OI.js} +2 -2
- package/dist/cli/chunks/{hooks-R3DQNG2F.js → hooks-ZN4FV5XS.js} +6 -6
- package/dist/cli/chunks/{hybrid-router-MSCQ2XGU.js → hybrid-router-Y6LBFPL7.js} +2 -2
- package/dist/cli/chunks/{hypergraph-engine-3TKB5O7T.js → hypergraph-engine-KK73LZYZ.js} +2 -2
- package/dist/cli/chunks/{hypergraph-handler-4APYID2S.js → hypergraph-handler-OBGDPIWG.js} +3 -3
- package/dist/cli/chunks/impact-analyzer-GWIUYYCQ.js +2 -0
- package/dist/cli/chunks/{init-handler-E7B2GKH3.js → init-handler-JJJ7VHM4.js} +6 -6
- package/dist/cli/chunks/init-wizard-RIJJAKE3.js +2 -0
- package/dist/cli/chunks/kernel-SIPBCRGL.js +2 -0
- package/dist/cli/chunks/{kilocode-installer-WY6VTFSA.js → kilocode-installer-EF6DPX2D.js} +2 -2
- package/dist/cli/chunks/{kiro-installer-SCNF3JXD.js → kiro-installer-SG74CEVO.js} +2 -2
- package/dist/cli/chunks/knowledge-graph-NOYZXHIG.js +2 -0
- package/dist/cli/chunks/learning-LVWYMHF6.js +107 -0
- package/dist/cli/chunks/{llm-router-RBKYYHBJ.js → llm-router-QFK7MNPY.js} +4 -4
- package/dist/cli/chunks/{load-FY64UGHV.js → load-6XPV4WA2.js} +2 -2
- package/dist/cli/chunks/load-test-DIMUH75F.js +2 -0
- package/dist/cli/chunks/{mcp-6VMQOWMX.js → mcp-GZXOPYMH.js} +2 -2
- package/dist/cli/chunks/{memory-Y5RO4PGM.js → memory-QTE2Z5HU.js} +5 -5
- package/dist/cli/chunks/memory-backend-IWOGO4BV.js +2 -0
- package/dist/cli/chunks/{memory-handlers-CMMVHHPG.js → memory-handlers-PC4P4YEF.js} +2 -2
- package/dist/cli/chunks/{multi-model-executor-JO3MNMPZ.js → multi-model-executor-FZOPSUOT.js} +3 -3
- package/dist/cli/chunks/{opencode-installer-WQBTY6JT.js → opencode-installer-CITDTCUQ.js} +2 -2
- package/dist/cli/chunks/{orchestrator-4J7OSNSG.js → orchestrator-ZTG7MFHQ.js} +20 -20
- package/dist/cli/chunks/{pipeline-63T6HN72.js → pipeline-QXO4EJP4.js} +2 -2
- package/dist/cli/chunks/{platform-UJMD4EPZ.js → platform-JJEDYCAK.js} +2 -2
- package/dist/cli/chunks/{plugin-NDOZ63JW.js → plugin-ZEKRM6F7.js} +2 -2
- package/dist/cli/chunks/{prime-radiant-advanced-wasm-ELGHVIFI.js → prime-radiant-advanced-wasm-GRS4T6LR.js} +2 -2
- package/dist/cli/chunks/protocol-executor-NT4TILJW.js +2 -0
- package/dist/cli/chunks/{protocol-handler-KYERIMVF.js → protocol-handler-KWI2T6OR.js} +2 -2
- package/dist/cli/chunks/{prove-ATSSBP4Z.js → prove-7FJN2HEH.js} +2 -2
- package/dist/cli/chunks/{provider-manager-YYMIF23V.js → provider-manager-QYYZZLLO.js} +2 -2
- package/dist/cli/chunks/qe-reasoning-bank-VDROHXFS.js +2 -0
- package/dist/cli/chunks/{quality-2AGJSJW6.js → quality-4NHO2NY5.js} +2 -2
- package/dist/cli/chunks/queen-coordinator-7LO73IV3.js +2 -0
- package/dist/cli/chunks/{real-embeddings-H36GVXMI.js → real-embeddings-SIELAOWX.js} +2 -2
- package/dist/cli/chunks/{roocode-installer-PMRBAY7O.js → roocode-installer-ANYXH3NR.js} +2 -2
- package/dist/cli/chunks/router-SFVOLN2W.js +2 -0
- package/dist/cli/chunks/routing-feedback-MRFV7WUZ.js +2 -0
- package/dist/cli/chunks/{routing-handler-Z7VZSDXW.js → routing-handler-6QQHK4KV.js} +2 -2
- package/dist/cli/chunks/{ruvector-commands-N3FZ3ZEE.js → ruvector-commands-YEUA3MZB.js} +2 -2
- package/dist/cli/chunks/{rvf-dual-writer-L5DQHUF3.js → rvf-dual-writer-UJFRHPVE.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-adapter-NPGFA3SL.js → rvf-migration-adapter-CSDFG7UA.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-coordinator-MCJDNKXG.js → rvf-migration-coordinator-QO7OENQF.js} +2 -2
- package/dist/cli/chunks/rvf-native-adapter-6L7FZZC7.js +2 -0
- package/dist/cli/chunks/safe-db-PYWBVGOV.js +2 -0
- package/dist/cli/chunks/schedule-BUQU75HY.js +2 -0
- package/dist/cli/chunks/scheduler-XOSKWZO2.js +2 -0
- package/dist/cli/chunks/{security-TX7TXUGI.js → security-QCIUC5FX.js} +3 -3
- package/dist/cli/chunks/shared-rvf-adapter-OZ7S4ZQL.js +2 -0
- package/dist/cli/chunks/{shared-rvf-dual-writer-6K3ZAG7P.js → shared-rvf-dual-writer-LVJJS3PD.js} +2 -2
- package/dist/cli/chunks/sqlite-persistence-7UXQZ5Y6.js +2 -0
- package/dist/cli/chunks/{status-handler-MIRLQRNN.js → status-handler-O77A4JWM.js} +2 -2
- package/dist/cli/chunks/{structural-health-CIHASLUE.js → structural-health-WIIBIIQI.js} +2 -2
- package/dist/cli/chunks/{sync-FGLAP7EK.js → sync-UN6D6OF2.js} +2 -2
- package/dist/cli/chunks/{task-handler-7HMPRCHY.js → task-handler-RBOSMJCK.js} +2 -2
- package/dist/cli/chunks/{task-handlers-DQLQCLCT.js → task-handlers-VWMXQKAT.js} +2 -2
- package/dist/cli/chunks/{test-JKDO5ZHU.js → test-XK5M3PGT.js} +4 -4
- package/dist/cli/chunks/{test-scheduling-2YKZ7PVZ.js → test-scheduling-CTQ3JJ7G.js} +4 -4
- package/dist/cli/chunks/{token-bootstrap-C7UUPMQN.js → token-bootstrap-D5CQ3I5M.js} +2 -2
- package/dist/cli/chunks/{token-usage-2RVIPCY4.js → token-usage-L4QSLWQ5.js} +2 -2
- package/dist/cli/chunks/{transformers-UEMAGHQ5.js → transformers-SRPJDBKA.js} +2 -2
- package/dist/cli/chunks/{tree-sitter-wasm-parser-MELABICK.js → tree-sitter-wasm-parser-DOU5ITWB.js} +2 -2
- package/dist/cli/chunks/{types-5B4RD7ZV.js → types-LECYZUBN.js} +2 -2
- package/dist/cli/chunks/unified-memory-L6735TFM.js +2 -0
- package/dist/cli/chunks/unified-memory-hnsw-7TZNEDGY.js +2 -0
- package/dist/cli/chunks/unified-persistence-FNYZ3C2B.js +2 -0
- package/dist/cli/chunks/{validate-CHDG7SC3.js → validate-SIKNIS6B.js} +2 -2
- package/dist/cli/chunks/{validate-swarm-LB7GORKE.js → validate-swarm-EHAMMILJ.js} +2 -2
- package/dist/cli/chunks/{vibium-ZMC4G2YA.js → vibium-LJ4NYXMZ.js} +2 -2
- package/dist/cli/chunks/visual-security-SMPZPDY4.js +2 -0
- package/dist/cli/chunks/{web-tree-sitter-THNO6S2V.js → web-tree-sitter-DZQ3T4JD.js} +2 -2
- package/dist/cli/chunks/{windsurf-installer-LRB43BPX.js → windsurf-installer-U6Z73O6J.js} +2 -2
- package/dist/cli/chunks/witness-chain-FNCOTWFA.js +2 -0
- package/dist/cli/chunks/{witness-chain-JC5UBXPM.js → witness-chain-JE3QU4YP.js} +2 -2
- package/dist/cli/chunks/{workflow-Q4IYQ6F2.js → workflow-62QXGZQO.js} +4 -4
- package/dist/cli/chunks/workflow-orchestrator-RCR4N7OA.js +2 -0
- package/dist/cli/chunks/{wrappers-WSSLMFSE.js → wrappers-CAX5EZSH.js} +2 -2
- package/dist/cli/commands/eval.js +86 -0
- package/dist/cli/commands/learning.js +28 -8
- package/dist/domains/chaos-resilience/services/chaos-engineer.js +1 -1
- package/dist/domains/constants.d.ts +1 -1
- package/dist/domains/constants.js +1 -1
- package/dist/domains/contract-testing/services/contract-validator.js +1 -1
- package/dist/domains/learning-optimization/services/learning-coordinator.js +1 -1
- package/dist/domains/test-execution/services/test-executor.js +1 -1
- package/dist/domains/test-generation/services/test-data-generator.d.ts +1 -0
- package/dist/domains/test-generation/services/test-data-generator.js +17 -3
- package/dist/domains/visual-accessibility/services/visual-tester.js +1 -1
- package/dist/init/browser-engine-installer.d.ts +60 -1
- package/dist/init/browser-engine-installer.js +73 -3
- package/dist/init/phases/09-assets.js +9 -2
- package/dist/mcp/bundle.js +1782 -1790
- package/dist/mcp/protocol-server.js +20 -10
- package/dist/validation/command-eval-runner.d.ts +154 -0
- package/dist/validation/command-eval-runner.js +293 -0
- package/dist/validation/index.d.ts +2 -0
- package/dist/validation/index.js +4 -0
- package/package.json +7 -5
- package/dist/cli/chunks/adapter-VP3WBXE5.js +0 -2
- package/dist/cli/chunks/aqe-learning-engine-ASPPEOKQ.js +0 -2
- package/dist/cli/chunks/base-SIAOYPTD.js +0 -2
- package/dist/cli/chunks/browser-workflow-BG3M3RZU.js +0 -2
- package/dist/cli/chunks/chunk-3I6KWFJT.js +0 -2
- package/dist/cli/chunks/chunk-4WJ3BHCN.js +0 -24
- package/dist/cli/chunks/chunk-67TMNSO3.js +0 -3
- package/dist/cli/chunks/chunk-APQYMAKG.js +0 -65
- package/dist/cli/chunks/chunk-BSTCXDVH.js +0 -2
- package/dist/cli/chunks/chunk-F74IVEON.js +0 -2
- package/dist/cli/chunks/chunk-FHWDVN65.js +0 -18
- package/dist/cli/chunks/chunk-HEHGQM2H.js +0 -3029
- package/dist/cli/chunks/chunk-HRD7LL7Q.js +0 -2
- package/dist/cli/chunks/chunk-QKTB5FZP.js +0 -2
- package/dist/cli/chunks/chunk-R4B2B6MZ.js +0 -5
- package/dist/cli/chunks/chunk-SI7AQK7I.js +0 -2
- package/dist/cli/chunks/chunk-TVASP2E6.js +0 -2
- package/dist/cli/chunks/chunk-VLZBQ3XN.js +0 -2
- package/dist/cli/chunks/chunk-Y2ONHWXI.js +0 -2
- package/dist/cli/chunks/chunk-YCTGWMCP.js +0 -12
- package/dist/cli/chunks/client-LMOHUGOA.js +0 -2
- package/dist/cli/chunks/cross-domain-router-IZB5ZMXO.js +0 -2
- package/dist/cli/chunks/daemon-YNF54UYB.js +0 -19
- package/dist/cli/chunks/dream-SAPSS25B.js +0 -2
- package/dist/cli/chunks/esm-node-FTBUMV4L.js +0 -2
- package/dist/cli/chunks/eval-Y3ODM7JU.js +0 -15
- package/dist/cli/chunks/heartbeat-scheduler-HYVMXCXT.js +0 -2
- package/dist/cli/chunks/hnsw-adapter-CBDRZLXX.js +0 -2
- package/dist/cli/chunks/hnsw-index-EOJG4VF4.js +0 -2
- package/dist/cli/chunks/impact-analyzer-C2TXXYPC.js +0 -2
- package/dist/cli/chunks/init-wizard-IQV7SBMW.js +0 -2
- package/dist/cli/chunks/kernel-NJOPFGK7.js +0 -2
- package/dist/cli/chunks/knowledge-graph-EUMGCQPH.js +0 -2
- package/dist/cli/chunks/learning-Y4OZJFBV.js +0 -107
- package/dist/cli/chunks/load-test-LBYVVG35.js +0 -2
- package/dist/cli/chunks/memory-backend-NQMJKHCQ.js +0 -2
- package/dist/cli/chunks/protocol-executor-ZSWPG5SU.js +0 -2
- package/dist/cli/chunks/qe-reasoning-bank-4RLPRCGF.js +0 -2
- package/dist/cli/chunks/queen-coordinator-KQ673NYE.js +0 -2
- package/dist/cli/chunks/router-UBNV4H5S.js +0 -2
- package/dist/cli/chunks/routing-feedback-BMMGZ346.js +0 -2
- package/dist/cli/chunks/rvf-native-adapter-LXBCTTVF.js +0 -2
- package/dist/cli/chunks/safe-db-FFSPBUAK.js +0 -2
- package/dist/cli/chunks/schedule-2MOMNZ6B.js +0 -2
- package/dist/cli/chunks/scheduler-5VGVANFG.js +0 -2
- package/dist/cli/chunks/shared-rvf-adapter-6JWYF7WV.js +0 -2
- package/dist/cli/chunks/sqlite-persistence-LCOAORK7.js +0 -2
- package/dist/cli/chunks/unified-memory-CZCWZUFP.js +0 -2
- package/dist/cli/chunks/unified-memory-hnsw-QEOXVSOZ.js +0 -2
- package/dist/cli/chunks/unified-persistence-HGZAYZGP.js +0 -2
- package/dist/cli/chunks/visual-security-ITKF4E4Z.js +0 -2
- package/dist/cli/chunks/witness-chain-SYFYXQD3.js +0 -2
- package/dist/cli/chunks/workflow-orchestrator-GZS2O3KW.js +0 -2
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{c as t,e as o}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.15");process.exit(0)}
|
|
2
|
+
import{c as t,e as o}from"./chunk-CUQBOVRP.js";var L={};o(L,{DotProductAttention:()=>d,FlashAttention:()=>u,HyperbolicAttention:()=>f,LinearAttention:()=>h,MoEAttention:()=>_,MultiHeadAttention:()=>A,RuvectorLayer:()=>a,SonaEngine:()=>b,TensorCompress:()=>c,default:()=>n,differentiableSearch:()=>l,getCompressionLevel:()=>p,hierarchicalForward:()=>s,init:()=>m,pipeline:()=>q});import{createRequire as r}from"module";var i,e,n,a,c,l,s,p,m,u,d,A,f,h,_,b,q,g=t(()=>{i=r(import.meta.url),e=i("better-sqlite3"),n=e,{RuvectorLayer:a,TensorCompress:c,differentiableSearch:l,hierarchicalForward:s,getCompressionLevel:p,init:m,FlashAttention:u,DotProductAttention:d,MultiHeadAttention:A,HyperbolicAttention:f,LinearAttention:h,MoEAttention:_,SonaEngine:b,pipeline:q}=e||{}});export{n as a,a as b,c,l as d,s as e,p as f,m as g,u as h,d as i,A as j,f as k,h as l,_ as m,b as n,q as o,L as p,g as q};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{k as K,o as ot}from"./chunk-EBQUXPIG.js";import{a as rt}from"./chunk-Y2ONHWXI.js";import{c as U}from"./chunk-HHRUXDLT.js";import{a as j,c as et}from"./chunk-3AOWTHLS.js";import{a as G,d as at}from"./chunk-YYQVSVBO.js";import{a as nt,b as it}from"./chunk-JOCR5TWI.js";import{c as H,e as V,g as w}from"./chunk-ERGY45RL.js";var Z={};V(Z,{DotProductAttention:()=>yt,FlashAttention:()=>ft,HyperbolicAttention:()=>bt,LinearAttention:()=>vt,MoEAttention:()=>Et,MultiHeadAttention:()=>At,RuvectorLayer:()=>ut,SonaEngine:()=>P,TensorCompress:()=>mt,default:()=>ct,differentiableSearch:()=>ht,getCompressionLevel:()=>pt,hierarchicalForward:()=>dt,init:()=>gt,pipeline:()=>Ft});import{createRequire as st}from"module";var lt,$,ct,ut,mt,ht,dt,pt,gt,ft,yt,At,bt,vt,Et,P,Ft,k=H(()=>{lt=st(import.meta.url),$=lt("@ruvector/sona"),ct=$,{RuvectorLayer:ut,TensorCompress:mt,differentiableSearch:ht,hierarchicalForward:dt,getCompressionLevel:pt,init:gt,FlashAttention:ft,DotProductAttention:yt,MultiHeadAttention:At,HyperbolicAttention:bt,LinearAttention:vt,MoEAttention:Et,SonaEngine:P,pipeline:Ft}=$||{}});var N={};V(N,{DotProductAttention:()=>It,FlashAttention:()=>zt,HyperbolicAttention:()=>_t,LinearAttention:()=>Ht,MoEAttention:()=>Vt,MultiHeadAttention:()=>qt,RuvectorLayer:()=>Qt,SonaEngine:()=>jt,TensorCompress:()=>Nt,default:()=>xt,differentiableSearch:()=>Ot,getCompressionLevel:()=>Wt,hierarchicalForward:()=>Dt,init:()=>Bt,pipeline:()=>Ut});import{createRequire as kt}from"module";var Rt,X,xt,Qt,Nt,Ot,Dt,Wt,Bt,zt,It,qt,_t,Ht,Vt,jt,Ut,O=H(()=>{Rt=kt(import.meta.url),X=Rt("@ruvector/attention"),xt=X,{RuvectorLayer:Qt,TensorCompress:Nt,differentiableSearch:Ot,hierarchicalForward:Dt,getCompressionLevel:Wt,init:Bt,FlashAttention:zt,DotProductAttention:It,MultiHeadAttention:qt,HyperbolicAttention:_t,LinearAttention:Ht,MoEAttention:Vt,SonaEngine:jt,pipeline:Ut}=X||{}});k();at();import{randomUUID as Ct}from"crypto";rt();import{createRequire as wt}from"module";var f=U.create("sona-three-loop"),S=wt(import.meta.url),M=null,J=!1;function St(){if(J)return M;J=!0;try{let l=S("@ruvector/learning-wasm"),t=S("fs"),e=S("path"),r=e.join(e.dirname(S.resolve("@ruvector/learning-wasm")),"ruvector_learning_wasm_bg.wasm");l.initSync({module:t.readFileSync(r)}),M=l,f.info("WASM MicroLoRA loaded from @ruvector/learning-wasm (6.4x faster than TS)")}catch{M=null,f.debug("@ruvector/learning-wasm not available, using TypeScript MicroLoRA")}return M}var Mt={dimension:384,microLoraLr:.001,consolidationInterval:100,ewcLambda:1e3,taskBoundaryZScoreThreshold:2.5,fisherDecay:.9,fisherSampleSize:200,importanceThreshold:.01},R=class{adaptationVector;baseWeights;lr;adaptationCount=0;constructor(t,e=.001){this.adaptationVector=new Float32Array(t),this.baseWeights=new Float32Array(t),this.lr=e}adapt(t){let e=this.baseWeights.length,r=new Float32Array(e),a=Math.min(t.length,e);for(let n=0;n<e;n++){let o=n<a?t[n]:0;r[n]=this.baseWeights[n]+this.adaptationVector[n]+this.lr*o}for(let n=0;n<a;n++)this.adaptationVector[n]+=this.lr*t[n];return this.adaptationCount++,r}consolidate(){let t=this.adaptationCount,e=this.baseWeights.length;for(let r=0;r<e;r++)this.baseWeights[r]+=this.adaptationVector[r],this.adaptationVector[r]=0;return this.adaptationCount=0,t}getAdaptationCount(){return this.adaptationCount}getEffectiveWeights(){let t=this.baseWeights.length,e=new Float32Array(t);for(let r=0;r<t;r++)e[r]=this.baseWeights[r]+this.adaptationVector[r];return e}getAdaptationMagnitude(){let t=0;for(let e=0;e<this.adaptationVector.length;e++)t+=this.adaptationVector[e]*this.adaptationVector[e];return Math.sqrt(t)}resetAdaptation(){this.adaptationVector.fill(0),this.adaptationCount=0}},x=class{fisherMatrix;optimalParams;lambda;fisherDecay;zScoreThreshold;importanceThreshold;gradientHistory=[];gradientMean=0;gradientVariance=0;taskBoundaryCount=0;consolidationCount=0;constructor(t,e=1e3,r=.9,a=2.5,n=.01){this.fisherMatrix=new Float32Array(t),this.optimalParams=new Float32Array(t),this.lambda=e,this.fisherDecay=r,this.zScoreThreshold=a,this.importanceThreshold=n}detectTaskBoundary(t){let e=0;for(let i=0;i<t.length;i++)e+=t[i]*t[i];if(e=Math.sqrt(e),this.gradientHistory.length<5)return this.gradientHistory.push(e),this.updateGradientStats(),!1;let r=Math.sqrt(this.gradientVariance),a=0,n=Math.abs(e-this.gradientMean);return r>1e-10?a=n/r:n>1e-10&&this.gradientMean>1e-10&&(a=n/(this.gradientMean*.01+1e-10)),this.gradientHistory.push(e),this.gradientHistory.length>100&&this.gradientHistory.shift(),this.updateGradientStats(),a>this.zScoreThreshold?(this.taskBoundaryCount++,!0):!1}computeLoss(t){let e=0,r=Math.min(t.length,this.fisherMatrix.length,this.optimalParams.length);for(let a=0;a<r;a++){let n=t[a]-this.optimalParams[a];e+=this.fisherMatrix[a]*n*n}return this.lambda/2*e}updateFisher(t,e){if(t.length===0)return;let r=this.fisherMatrix.length,a=new Float32Array(r);for(let s of t){let u=Math.min(s.length,r);for(let c=0;c<u;c++)a[c]+=s[c]*s[c]}let n=t.length;for(let s=0;s<r;s++)a[s]/=n;let o=this.fisherDecay;for(let s=0;s<r;s++)this.fisherMatrix[s]=o*this.fisherMatrix[s]+(1-o)*a[s];let i=Math.min(e.length,r);for(let s=0;s<i;s++)this.optimalParams[s]=e[s];this.consolidationCount++}getMetrics(){let t=this.fisherMatrix.length,e=0,r=0,a=0;for(let n=0;n<t;n++)e+=this.fisherMatrix[n],this.fisherMatrix[n]>r&&(r=this.fisherMatrix[n]),this.fisherMatrix[n]>this.importanceThreshold&&a++;return{regularizationLoss:0,taskBoundariesDetected:this.taskBoundaryCount,fisherTrace:e,avgFisherImportance:t>0?e/t:0,maxFisherImportance:r,protectedParams:a,consolidationCycles:this.consolidationCount,lambda:this.lambda}}getTaskBoundaryCount(){return this.taskBoundaryCount}getFisherDiagonal(){return new Float32Array(this.fisherMatrix)}getOptimalParams(){return new Float32Array(this.optimalParams)}loadFisher(t,e){let r=this.fisherMatrix.length,a=Math.min(t.length,r),n=Math.min(e.length,r);for(let o=0;o<a;o++)this.fisherMatrix[o]=t[o];for(let o=0;o<n;o++)this.optimalParams[o]=e[o]}updateGradientStats(){let t=this.gradientHistory.length;if(t===0)return;let e=0;for(let a of this.gradientHistory)e+=a;e/=t;let r=0;for(let a of this.gradientHistory){let n=a-e;r+=n*n}r=t>1?r/(t-1):0,this.gradientMean=e,this.gradientVariance=r}},C=class{config;microLora;ewc;nativeEngine;wasmLora=null;requestCount=0;lastConsolidationRequest=0;peerStates=new Map;gradientBuffer=[];lastFeatures=null;constructor(t={},e){this.config={...Mt,...t},this.nativeEngine=e??null,this.microLora=new R(this.config.dimension,this.config.microLoraLr),this.ewc=new x(this.config.dimension,this.config.ewcLambda,this.config.fisherDecay,this.config.taskBoundaryZScoreThreshold,this.config.importanceThreshold);let r=St();if(r)try{this.wasmLora=new r.WasmMicroLoRA(this.config.dimension,1,this.config.microLoraLr),f.info("SONA Three-Loop using WASM MicroLoRA (0.07us/adapt)")}catch(a){f.debug("WASM MicroLoRA creation failed, falling back",{error:String(a)}),this.wasmLora=null}!this.wasmLora&&this.nativeEngine&&f.info("SONA Three-Loop using native @ruvector/sona engine for MicroLoRA delegation")}instantAdapt(t){let e=performance.now(),r;if(this.wasmLora)try{let o=new Float32Array(t),i=this.wasmLora.adapt(o);i&&i.length>0?(r=i,this.microLora.adapt(t)):r=this.microLora.adapt(t)}catch{r=this.microLora.adapt(t)}else if(this.nativeEngine)try{let o=this.nativeEngine.applyMicroLora(t);r=new Float32Array(o),this.microLora.adapt(t)}catch{r=this.microLora.adapt(t)}else r=this.microLora.adapt(t);let a=this.microLora.getAdaptationMagnitude();this.requestCount++,this.lastFeatures=[...t];let n=(performance.now()-e)*1e3;return{adaptedWeights:r,latencyUs:n,applied:!0,magnitude:a,requestIndex:this.requestCount}}recordOutcome(t,e){if(this.lastFeatures===null){f.warn("recordOutcome called without a preceding instantAdapt()");return}let r=this.lastFeatures.length,a=new Float32Array(r);for(let n=0;n<r;n++)a[n]=t*this.lastFeatures[n];this.gradientBuffer.push(a),this.gradientBuffer.length>this.config.fisherSampleSize&&this.gradientBuffer.shift(),this.lastFeatures=null}backgroundConsolidate(){let t=performance.now();if(this.nativeEngine)try{this.nativeEngine.forceLearn(),this.nativeEngine.tick()}catch(i){f.warn("Native SONA background learning failed, continuing with TypeScript",{error:String(i)})}let e=this.ewc.computeLoss(this.microLora.getEffectiveWeights()),r=!1;if(this.gradientBuffer.length>0){let i=this.gradientBuffer[this.gradientBuffer.length-1];r=this.ewc.detectTaskBoundary(i)}if(r&&this.gradientBuffer.length>0&&(this.ewc.updateFisher(this.gradientBuffer,this.microLora.getEffectiveWeights()),f.info("Task boundary detected, Fisher updated",{boundaries:this.ewc.getTaskBoundaryCount(),requestCount:this.requestCount})),this.gradientBuffer.length>1){let i=!1,s=this.gradientBuffer[0];for(let u=1;u<this.gradientBuffer.length&&!i;u++)for(let c=0;c<s.length;c++)if(Math.abs(this.gradientBuffer[u][c]-s[c])>1e-8){i=!0;break}i||f.warn("All gradient samples identical \u2014 Fisher estimate may be poor. Ensure recordOutcome() is called with diverse rewards.")}let a=this.microLora.consolidate();this.applyEWCRegularization();let n=this.ewc.computeLoss(this.microLora.getEffectiveWeights());this.lastConsolidationRequest=this.requestCount,this.gradientBuffer=[];let o=performance.now()-t;return{consolidated:a>0||r,adaptationsMerged:a,ewcLossBefore:e,ewcLossAfter:n,taskBoundaryDetected:r,durationMs:o}}shouldConsolidate(){return this.requestCount-this.lastConsolidationRequest>=this.config.consolidationInterval}syncWithPeers(t){if(t.length===0)return;for(let i of t)this.peerStates.set(i.peerId,i);let e=this.config.dimension,r=new Float32Array(e),a=new Float32Array(e),n=this.ewc.getFisherDiagonal(),o=this.microLora.adaptationVector;for(let i=0;i<e;i++){let s=n[i]+1e-10;r[i]+=s*o[i],a[i]+=s}for(let i of t){let s=Math.min(i.adaptationVector.length,e);for(let u=0;u<s;u++){let c=(u<i.fisherDiagonal.length?i.fisherDiagonal[u]:0)+1e-10;r[u]+=c*i.adaptationVector[u],a[u]+=c}}for(let i=0;i<e;i++)this.microLora.adaptationVector[i]=r[i]/a[i];f.debug("Synced with peers",{peerCount:t.length,peersStored:this.peerStates.size})}getLocalPeerState(t,e){return{peerId:t,domain:e,adaptationVector:new Float32Array(this.microLora.adaptationVector),fisherDiagonal:this.ewc.getFisherDiagonal(),requestCount:this.requestCount,lastUpdateMs:Date.now()}}getEWCMetrics(){let t=this.ewc.getMetrics();return t.regularizationLoss=this.ewc.computeLoss(this.microLora.getEffectiveWeights()),t}getFisherDiagonal(){return this.ewc.getFisherDiagonal()}getOptimalParams(){return this.ewc.getOptimalParams()}loadFisher(t,e){this.ewc.loadFisher(t,e)}getBaseWeights(){return new Float32Array(this.microLora.baseWeights)}setBaseWeights(t){let e=Math.min(t.length,this.microLora.baseWeights.length);for(let r=0;r<e;r++)this.microLora.baseWeights[r]=t[r]}getEffectiveWeights(){return this.microLora.getEffectiveWeights()}getRequestCount(){return this.requestCount}getConfig(){return{...this.config}}getPeerStates(){return new Map(this.peerStates)}getMicroLoRA(){return this.microLora}getEWC(){return this.ewc}applyEWCRegularization(){let t=this.config.dimension,e=this.ewc.fisherMatrix,r=this.ewc.optimalParams,a=this.microLora.baseWeights,n=.01;for(let o=0;o<t;o++)if(e[o]>this.config.importanceThreshold){let i=a[o]-r[o];a[o]-=n*e[o]*i}}persistFisher(t,e){let r=this.ewc.getMetrics();t(e,this.ewc.getFisherDiagonal(),this.ewc.getOptimalParams(),this.getBaseWeights(),{taskBoundaries:r.taskBoundariesDetected,consolidationCycles:r.consolidationCycles,requestCount:this.requestCount,ewcLambda:r.lambda}),f.info("Fisher matrix persisted to SQLite",{domain:e,requestCount:this.requestCount,taskBoundaries:r.taskBoundariesDetected})}restoreFisher(t){this.ewc.loadFisher(t.fisherDiagonal,t.optimalParams),t.baseWeights&&this.setBaseWeights(t.baseWeights),this.requestCount=t.requestCount,f.info("Fisher matrix restored from SQLite",{requestCount:t.requestCount,dimension:t.fisherDiagonal.length})}};var Lt={hiddenDim:256,embeddingDim:384,microLoraRank:1,baseLoraRank:8,microLoraLr:.001,baseLoraLr:1e-4,ewcLambda:1e3,patternClusters:50,trajectoryCapacity:1e4,backgroundIntervalMs:36e5,qualityThreshold:.5,enableSimd:!0,minConfidence:.5,maxPatterns:1e4},Q=class{patterns;trajectoryMap;maxPatterns;constructor(t=1e4){this.patterns=new Map,this.trajectoryMap=new Map,this.maxPatterns=t}register(t){if(this.patterns.size>=this.maxPatterns&&!this.patterns.has(t.id)){let e=Array.from(this.patterns.entries()).sort(([,r],[,a])=>(r.lastUsedAt?.getTime()??r.createdAt.getTime())-(a.lastUsedAt?.getTime()??a.createdAt.getTime()))[0];e&&this.patterns.delete(e[0])}this.patterns.set(t.id,t)}get(t){return this.patterns.get(t)}getByTrajectory(t){let e=this.trajectoryMap.get(t);return e?this.patterns.get(e):void 0}associateTrajectory(t,e){this.trajectoryMap.set(t,e)}update(t,e){let r=this.patterns.get(t);return r?(this.patterns.set(t,{...r,...e}),!0):!1}getAll(){return Array.from(this.patterns.values())}getByType(t){return Array.from(this.patterns.values()).filter(e=>e.type===t)}getByDomain(t){return Array.from(this.patterns.values()).filter(e=>e.domain===t)}clear(){this.patterns.clear(),this.trajectoryMap.clear()}size(){return this.patterns.size}},v=class{engine;registry;config;adaptationTimes=[];cacheHits=0;totalAdaptations=0;threeLoopEngine=null;fisherPersistFn=null;fisherDomain="default";constructor(t={}){this.config={...Lt,...t};let e={hiddenDim:this.config.hiddenDim,embeddingDim:this.config.embeddingDim,microLoraRank:this.config.microLoraRank,baseLoraRank:this.config.baseLoraRank,microLoraLr:this.config.microLoraLr,baseLoraLr:this.config.baseLoraLr,ewcLambda:this.config.ewcLambda,patternClusters:this.config.patternClusters,trajectoryCapacity:this.config.trajectoryCapacity,backgroundIntervalMs:this.config.backgroundIntervalMs,qualityThreshold:this.config.qualityThreshold,enableSimd:this.config.enableSimd};this.engine=P.withConfig(e),this.registry=new Q(this.config.maxPatterns??1e4)}async adaptPattern(t,e,r){let a=performance.now();try{let n=this.createStateEmbedding(t),o=this.engine.findPatterns(n,5),i=[];for(let m of o){let g=this.findByRawPattern(m);if(g||(g=this.createQEPatternFromRaw(m,e,r)),g.type===e&&g.domain===r&&g.confidence>=(this.config.minConfidence??.5)){let h=this.calculateSimilarity(n,m.centroid);i.push({pattern:g,similarity:h})}}if(i.length===0){let m=performance.now()-a;return this.recordAdaptation(m),{success:!1,pattern:null,adaptationTimeMs:m,similarity:0,reasoning:"No suitable pattern found"}}let s=i[0],u={...s.pattern,usageCount:s.pattern.usageCount+1,lastUsedAt:new Date};this.registry.update(u.id,u);let c=performance.now()-a;return this.recordAdaptation(c),{success:!0,pattern:u,adaptationTimeMs:c,similarity:s.similarity,reasoning:`Pattern adapted from @ruvector/sona with ${s.similarity.toFixed(3)} similarity`}}catch(n){let o=performance.now()-a;return this.recordAdaptation(o),{success:!1,pattern:null,adaptationTimeMs:o,similarity:0,reasoning:`Adaptation failed: ${n.message}`}}}recallPattern(t,e,r){let a=this.createStateEmbedding(t),n=this.engine.findPatterns(a,1);for(let o of n){let i=this.findByRawPattern(o);if(i&&i.type===e&&i.domain===r)return i}return null}storePattern(t){this.registry.register(t);let e=this.engine.beginTrajectory(t.stateEmbedding),r=this.createActionEmbedding(t.action),a=new Array(r.length).fill(1),n=t.outcome.success?t.outcome.quality:-t.outcome.quality;this.engine.addTrajectoryStep(e,r,a,n),this.engine.endTrajectory(e,t.outcome.quality),this.registry.associateTrajectory(e,t.id)}storePatternsBatch(t){for(let e of t)this.storePattern(e)}createPattern(t,e,r,a,n,o){let i={id:`qesona-${Date.now()}-${Ct().slice(0,7)}`,type:a,domain:n,stateEmbedding:this.createStateEmbedding(t),action:e,outcome:r,confidence:.5,usageCount:0,createdAt:new Date,metadata:o};return this.storePattern(i),i}updatePattern(t,e,r){let a=this.registry.get(t);if(!a)return!1;let n=e?r:-r,i=a.confidence+.1*(n-a.confidence),s={...a,confidence:Math.max(0,Math.min(1,i)),usageCount:a.usageCount+1,lastUsedAt:new Date};return this.registry.update(t,s)}applyMicroLora(t){return this.engine.applyMicroLora(t)}applyBaseLora(t,e){return this.engine.applyBaseLora(t,e)}forceLearn(){return this.engine.forceLearn()}tick(){return this.engine.tick()}getAllPatterns(){return this.registry.getAll()}getPatternsByType(t){return this.registry.getByType(t)}getPatternsByDomain(t){return this.registry.getByDomain(t)}getStats(){let t=this.registry.getAll(),e=this.engine.getStats(),r={"test-generation":0,"defect-prediction":0,"coverage-optimization":0,"quality-assessment":0,"resource-allocation":0};for(let a of t)r[a.type]++;return{totalPatterns:t.length,patternsByType:r,avgAdaptationTimeMs:this.avgAdaptationTime(),minAdaptationTimeMs:this.minAdaptationTime(),maxAdaptationTimeMs:this.maxAdaptationTime(),totalAdaptations:this.totalAdaptations,cacheHitRate:this.totalAdaptations>0?this.cacheHits/this.totalAdaptations:0,engineStats:e}}clear(){this.registry.clear(),this.adaptationTimes=[],this.cacheHits=0,this.totalAdaptations=0}exportPatterns(){return this.registry.getAll()}importPatterns(t){this.clear(),this.storePatternsBatch(t)}getConfig(){return{...this.config}}setEnabled(t){this.engine.setEnabled(t)}isEnabled(){return this.engine.isEnabled()}createStateEmbedding(t){let e=t.features;if(e.length===0)return new Array(this.config.embeddingDim??384).fill(0);let r=Math.max(...e.map(Math.abs));if(r===0)return[...e];let a=e.map(o=>o/r),n=this.config.embeddingDim??384;return a.length>=n?a.slice(0,n):[...a,...new Array(n-a.length).fill(0)]}createActionEmbedding(t){let e=[],r=this.hashCode(t.type);if(e.push(r%1e3/1e3),typeof t.value=="number")e.push(Math.min(1,Math.max(-1,t.value)));else if(typeof t.value=="string"){let n=this.hashCode(t.value);e.push(n%1e3/1e3)}else if(Array.isArray(t.value))for(let n of t.value.slice(0,10))typeof n=="number"&&e.push(Math.min(1,Math.max(-1,n)));let a=this.config.embeddingDim??384;for(;e.length<a;)e.push(0);return e.slice(0,a)}findByRawPattern(t){let e=this.registry.getAll();for(let r of e)if(r.rawPattern?.patternType===t.id)return r}createQEPatternFromRaw(t,e,r){let a={centroid:t.centroid,clusterSize:1,totalWeight:1,avgQuality:t.avgQuality,createdAt:new Date().toISOString(),lastAccessed:new Date().toISOString(),accessCount:0,patternType:t.patternType};return{id:`qesona-${t.id}`,type:e,domain:r,stateEmbedding:t.centroid,action:{type:"learned",value:t.patternType},outcome:{reward:t.avgQuality,success:t.avgQuality>.5,quality:t.avgQuality},confidence:t.avgQuality,usageCount:0,createdAt:new Date,rawPattern:a}}calculateSimilarity(t,e){let r=Math.min(t.length,e.length),a=0,n=0,o=0;for(let s=0;s<r;s++)a+=t[s]*e[s],n+=t[s]*t[s],o+=e[s]*e[s];return(a/(Math.sqrt(n)*Math.sqrt(o)+1e-10)+1)/2}hashCode(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)}recordAdaptation(t){this.adaptationTimes.push(t),this.totalAdaptations++,this.adaptationTimes.length>1e3&&this.adaptationTimes.shift()}avgAdaptationTime(){return this.adaptationTimes.length===0?0:this.adaptationTimes.reduce((e,r)=>e+r,0)/this.adaptationTimes.length}minAdaptationTime(){return this.adaptationTimes.length===0?0:Math.min(...this.adaptationTimes)}maxAdaptationTime(){return this.adaptationTimes.length===0?0:Math.max(...this.adaptationTimes)}initThreeLoopEngine(t){this.threeLoopEngine=new C({dimension:this.config.embeddingDim??384,microLoraLr:this.config.microLoraLr??.001,ewcLambda:this.config.ewcLambda??1e3,...t},this.engine)}getThreeLoopEngine(){return this.threeLoopEngine}instantAdapt(t){return this.threeLoopEngine?this.threeLoopEngine.instantAdapt(t):null}recordOutcome(t,e){this.threeLoopEngine&&this.threeLoopEngine.recordOutcome(t,e)}backgroundConsolidate(){if(!this.threeLoopEngine)return null;let t=this.threeLoopEngine.backgroundConsolidate();if(t&&(t.consolidated||t.taskBoundaryDetected)&&this.fisherPersistFn)try{this.threeLoopEngine.persistFisher(this.fisherPersistFn,this.fisherDomain)}catch(e){console.warn("[QESONA] Fisher persistence failed:",e instanceof Error?e.message:e)}return t}setFisherPersistence(t,e){this.fisherPersistFn=t,this.fisherDomain=e}syncWithPeers(t){this.threeLoopEngine&&this.threeLoopEngine.syncWithPeers(t)}getEWCMetrics(){return this.threeLoopEngine?this.threeLoopEngine.getEWCMetrics():null}shouldConsolidate(){return this.threeLoopEngine?this.threeLoopEngine.shouldConsolidate():!1}getLocalPeerState(t,e){return this.threeLoopEngine?this.threeLoopEngine.getLocalPeerState(t,e):null}isThreeLoopEnabled(){return this.threeLoopEngine!==null}async verifyPerformance(t=1e3){let e=[],r={id:"test-state",features:new Array(384).fill(0).map(()=>G())};for(let s=0;s<t;s++){let u=performance.now();await this.adaptPattern(r,"test-generation","test-generation");let c=performance.now();e.push({iteration:s,timeMs:c-u})}let a=e.map(s=>s.timeMs),n=a.reduce((s,u)=>s+u,0)/a.length,o=Math.min(...a),i=Math.max(...a);return{targetMet:n<.05,avgTimeMs:n,minTimeMs:o,maxTimeMs:i,details:e}}};function Tt(l){return new v(l)}function Pt(l,t){return new v({...t,maxPatterns:t?.maxPatterns||5e3})}ot();et();var F=null,D=null,W=null,B=null,z=null,I=null,q=!1;try{let l=(O(),w(N));F=l.FlashAttention,D=l.DotProductAttention,W=l.MultiHeadAttention,B=l.HyperbolicAttention,z=l.LinearAttention,I=l.MoEAttention,q=!0}catch{}function Gt(){return q}function A(){if(!q)throw new Error("@ruvector/attention native module is not available on this platform. Install the appropriate optional dependency for your platform, or use a platform where pre-built binaries are available.")}var T={"test-similarity":{dim:384,strategy:"flash",blockSize:64},"code-embedding":{dim:512,strategy:"flash",blockSize:128},"defect-matching":{dim:384,strategy:"flash",blockSize:64},"coverage-analysis":{dim:384,strategy:"flash",blockSize:256},"pattern-adaptation":{dim:256,strategy:"flash",blockSize:32}},Kt={"test-similarity":{enabled:!0,microLoRARank:4,targetAdaptationMs:.05,patternCacheSize:1e3},"code-embedding":{enabled:!0,microLoRARank:2,targetAdaptationMs:.03,patternCacheSize:5e3},"defect-matching":{enabled:!0,microLoRARank:8,targetAdaptationMs:.05,patternCacheSize:2e3},"coverage-analysis":{enabled:!1,microLoRARank:2,targetAdaptationMs:.01,patternCacheSize:100},"pattern-adaptation":{enabled:!0,microLoRARank:2,targetAdaptationMs:.05,patternCacheSize:1e4}},$t={"test-similarity":{latency:{before:50,after:15},memory:{before:200,after:80},throughput:{min:1e3}},"code-embedding":{latency:{before:50,after:15},memory:{before:200,after:80},throughput:{min:2e3}},"defect-matching":{latency:{before:20,after:5},memory:{before:150,after:50},throughput:{min:500}},"coverage-analysis":{latency:{before:100,after:1},memory:{before:100,after:30},throughput:{min:1e4}},"pattern-adaptation":{latency:{before:2,after:.05},memory:{before:50,after:20},throughput:{min:2e4}}};function Zt(l){return l<=128?{queryChunkSize:128,kvChunkSize:128}:l<=256?{queryChunkSize:256,kvChunkSize:256}:l<=512?{queryChunkSize:512,kvChunkSize:512}:l<=1024?{queryChunkSize:1024,kvChunkSize:1024}:{queryChunkSize:1024,kvChunkSize:2048}}var E=class{static create(t){switch(A(),t.strategy){case"flash":return new F(t.dim,t.blockSize);case"dot-product":return new D(t.dim);case"multi-head":return new W(t.dim,t.numHeads??8);case"hyperbolic":return new B(t.dim,t.curvature);case"linear":return new z(t.dim,t.features);case"moe":return I.simple(t.dim,t.moeConfig?.numExperts??8,t.moeConfig?.topK??2);default:return new F(t.dim,t.blockSize)}}},L=class l{attention;config;workload;metrics=[];db=null;persistCount=0;static KV_NAMESPACE="attention-metrics";static KV_TTL=3600;static PERSIST_INTERVAL=10;constructor(t,e){this.workload=t;let r=T[t];this.config={...r,...e},this.attention=E.create(this.config)}async initialize(){try{this.db=K(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(t){console.warn("[QEFlashAttention] DB init failed, using memory-only:",j(t)),this.db=null}}async computeFlashAttention(t,e,r,a,n){let o=performance.now(),i=process.memoryUsage().heapUsed/1024/1024,s=this.toFloat32Array(t,a,n),u=this.splitMatrix(e,a,n),c=this.splitMatrix(r,a,n),m,g=this.attention;typeof g.compute=="function"?m=g.compute(s,u,c):(A(),m=new F(this.config.dim).compute(s,u,c));let h=performance.now(),d=process.memoryUsage().heapUsed/1024/1024;return this.metrics.push({timeMs:h-o,memoryMB:d-i,speedup:1,throughput:a*a/((h-o)/1e3),peakMemoryMB:d}),this.maybePersistToKv(),m}async computeBaselineAttention(t,e,r,a,n){let o=performance.now(),i=process.memoryUsage().heapUsed/1024/1024,s=new Float32Array(a*a),u=1/Math.sqrt(n);for(let h=0;h<a;h++)for(let d=0;d<a;d++){let b=0;for(let p=0;p<n;p++)b+=t[h*n+p]*e[d*n+p];s[h*a+d]=b*u}for(let h=0;h<a;h++){let d=h*a,b=d+a,p=s.subarray(d,b),tt=Math.max(...p),_=0;for(let y=0;y<a;y++)p[y]=Math.exp(p[y]-tt),_+=p[y];for(let y=0;y<a;y++)p[y]/=_}let c=new Float32Array(a*n);for(let h=0;h<a;h++)for(let d=0;d<a;d++){let b=s[h*a+d];for(let p=0;p<n;p++)c[h*n+p]+=b*r[d*n+p]}let m=performance.now(),g=process.memoryUsage().heapUsed/1024/1024;return c}async computeTestSimilarity(t,e,r=5){let a=e.length,n=t.length,o=new Float32Array(a*n),i=new Float32Array(a*n);for(let m=0;m<a;m++)o.set(t,m*n),i.set(e[m],m*n);let s=new Float32Array(a*n),u=await this.computeFlashAttention(o,i,s,a,n),c=[];for(let m=0;m<a;m++)c.push({index:m,similarity:u[m*n]});return c.sort((m,g)=>g.similarity-m.similarity),c.slice(0,r)}async generateCodeEmbedding(t,e){let r=t.length/e.length,a=e.length;return await this.computeFlashAttention(t,e,t,r,a)}async matchDefectPattern(t,e){let r=e.length,a=t.length,n=new Float32Array(r*a),o=new Float32Array(r*a);for(let c=0;c<r;c++)n.set(t,c*a),o.set(e[c],c*a);let i=new Float32Array(r*a),s=await this.computeFlashAttention(n,o,i,r,a),u=[];for(let c=0;c<r;c++)u.push({pattern:c,score:s[c*a]});return u.sort((c,m)=>m.score-c.score),u}getMetrics(){return[...this.metrics]}getAverageSpeedup(){return this.metrics.length===0?1:this.metrics.reduce((t,e)=>t+e.speedup,0)/this.metrics.length}getConfig(){return{...this.config}}updateConfig(t){this.config={...this.config,...t},this.attention=E.create(this.config)}changeStrategy(t){this.config.strategy=t,this.attention=E.create(this.config)}resetMetrics(){this.metrics=[]}getWorkload(){return this.workload}dispose(){this.metrics=[]}async persistToKv(){if(!this.db)return;let t=`attention-metrics-${this.workload}`,e={workload:this.workload,metrics:this.metrics.slice(-50),savedAt:Date.now()};await this.db.kvSet(t,e,l.KV_NAMESPACE,l.KV_TTL)}async loadFromKv(){if(!this.db)return;let t=`attention-metrics-${this.workload}`,e=await this.db.kvGet(t,l.KV_NAMESPACE);e?.metrics?.length&&(this.metrics=e.metrics)}maybePersistToKv(){this.persistCount++,this.persistCount>=l.PERSIST_INTERVAL&&(this.persistCount=0,this.persistToKv().catch(()=>{}))}toFloat32Array(t,e,r){return t.slice(0,r)}splitMatrix(t,e,r){let a=[];for(let n=0;n<e;n++)a.push(t.slice(n*r,(n+1)*r));return a}};async function Y(l,t){let e=new L(l,t);return await e.initialize(),e}function Jt(l){return{...T[l]}}function Xt(){return Object.keys(T)}function Yt(){return A(),F}function te(){return A(),D}function ee(){return A(),W}function re(){return A(),B}function ae(){return A(),z}function ne(){return A(),I}function ie(l){return l instanceof Float32Array?l:new Float32Array(l)}function oe(l){return Array.from(l)}async function se(l,t,e,r){let a=await Y(l),n=[],o=t[0].length,i=e.length;for(let s of t){let u=new Float32Array(i*o),c=new Float32Array(i*o),m=new Float32Array(i*o);u.set(s,0);for(let h=0;h<i;h++)c.set(e[h],h*o),m.set(r[h],h*o);let g=await a.computeFlashAttention(u,c,m,i,o);n.push(g.slice(0,o))}return a.dispose(),n}function We(){return{"@ruvector/sona":"^0.1.5","@ruvector/attention":"^0.1.4","@ruvector/gnn":"^0.1.22"}}function Be(){let l={sona:!1,attention:!1,gnn:!1,all:!1};try{k(),l.sona=!0}catch{}try{O(),l.attention=!0}catch{}try{let t=(it(),w(nt));t.init();let e=new Float32Array([.1,.2,.3]),r=[new Float32Array([.1,.2,.3]),new Float32Array([.4,.5,.6])],a=t.differentiableSearch(e,r,1,1);a&&Array.isArray(a.indices)&&Array.isArray(a.weights)&&(l.gnn=!0)}catch{}return l.all=l.sona&&l.attention&&l.gnn,l}async function ze(){let{initGNN:l}=await import("./gnn-wrapper-UXM3L5LV.js");return[l(),"SONA: Ready (no initialization required)","Attention: Ready (no initialization required)"]}export{v as a,Tt as b,Pt as c,Gt as d,T as e,Kt as f,$t as g,Zt as h,L as i,Y as j,Jt as k,Xt as l,Yt as m,te as n,ee as o,re as p,ae as q,ne as r,ie as s,oe as t,se as u,We as v,Be as w,ze as x};
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.15");process.exit(0)}
|
|
2
|
+
import{k as K,o as ot}from"./chunk-LLVS3UYZ.js";import{a as rt}from"./chunk-FEVTMHO6.js";import{c as U}from"./chunk-XALB3KRR.js";import{a as j,c as et}from"./chunk-JJDHD7SC.js";import{a as G,d as at}from"./chunk-D3ZUSXFY.js";import{a as nt,b as it}from"./chunk-YCYFUYCE.js";import{c as H,e as V,g as w}from"./chunk-CUQBOVRP.js";var Z={};V(Z,{DotProductAttention:()=>yt,FlashAttention:()=>ft,HyperbolicAttention:()=>bt,LinearAttention:()=>vt,MoEAttention:()=>Et,MultiHeadAttention:()=>At,RuvectorLayer:()=>ut,SonaEngine:()=>P,TensorCompress:()=>mt,default:()=>ct,differentiableSearch:()=>ht,getCompressionLevel:()=>pt,hierarchicalForward:()=>dt,init:()=>gt,pipeline:()=>Ft});import{createRequire as st}from"module";var lt,$,ct,ut,mt,ht,dt,pt,gt,ft,yt,At,bt,vt,Et,P,Ft,k=H(()=>{lt=st(import.meta.url),$=lt("@ruvector/sona"),ct=$,{RuvectorLayer:ut,TensorCompress:mt,differentiableSearch:ht,hierarchicalForward:dt,getCompressionLevel:pt,init:gt,FlashAttention:ft,DotProductAttention:yt,MultiHeadAttention:At,HyperbolicAttention:bt,LinearAttention:vt,MoEAttention:Et,SonaEngine:P,pipeline:Ft}=$||{}});var N={};V(N,{DotProductAttention:()=>It,FlashAttention:()=>zt,HyperbolicAttention:()=>_t,LinearAttention:()=>Ht,MoEAttention:()=>Vt,MultiHeadAttention:()=>qt,RuvectorLayer:()=>Qt,SonaEngine:()=>jt,TensorCompress:()=>Nt,default:()=>xt,differentiableSearch:()=>Ot,getCompressionLevel:()=>Wt,hierarchicalForward:()=>Dt,init:()=>Bt,pipeline:()=>Ut});import{createRequire as kt}from"module";var Rt,X,xt,Qt,Nt,Ot,Dt,Wt,Bt,zt,It,qt,_t,Ht,Vt,jt,Ut,O=H(()=>{Rt=kt(import.meta.url),X=Rt("@ruvector/attention"),xt=X,{RuvectorLayer:Qt,TensorCompress:Nt,differentiableSearch:Ot,hierarchicalForward:Dt,getCompressionLevel:Wt,init:Bt,FlashAttention:zt,DotProductAttention:It,MultiHeadAttention:qt,HyperbolicAttention:_t,LinearAttention:Ht,MoEAttention:Vt,SonaEngine:jt,pipeline:Ut}=X||{}});k();at();import{randomUUID as Ct}from"crypto";rt();import{createRequire as wt}from"module";var f=U.create("sona-three-loop"),S=wt(import.meta.url),M=null,J=!1;function St(){if(J)return M;J=!0;try{let l=S("@ruvector/learning-wasm"),t=S("fs"),e=S("path"),r=e.join(e.dirname(S.resolve("@ruvector/learning-wasm")),"ruvector_learning_wasm_bg.wasm");l.initSync({module:t.readFileSync(r)}),M=l,f.info("WASM MicroLoRA loaded from @ruvector/learning-wasm (6.4x faster than TS)")}catch{M=null,f.debug("@ruvector/learning-wasm not available, using TypeScript MicroLoRA")}return M}var Mt={dimension:384,microLoraLr:.001,consolidationInterval:100,ewcLambda:1e3,taskBoundaryZScoreThreshold:2.5,fisherDecay:.9,fisherSampleSize:200,importanceThreshold:.01},R=class{adaptationVector;baseWeights;lr;adaptationCount=0;constructor(t,e=.001){this.adaptationVector=new Float32Array(t),this.baseWeights=new Float32Array(t),this.lr=e}adapt(t){let e=this.baseWeights.length,r=new Float32Array(e),a=Math.min(t.length,e);for(let n=0;n<e;n++){let o=n<a?t[n]:0;r[n]=this.baseWeights[n]+this.adaptationVector[n]+this.lr*o}for(let n=0;n<a;n++)this.adaptationVector[n]+=this.lr*t[n];return this.adaptationCount++,r}consolidate(){let t=this.adaptationCount,e=this.baseWeights.length;for(let r=0;r<e;r++)this.baseWeights[r]+=this.adaptationVector[r],this.adaptationVector[r]=0;return this.adaptationCount=0,t}getAdaptationCount(){return this.adaptationCount}getEffectiveWeights(){let t=this.baseWeights.length,e=new Float32Array(t);for(let r=0;r<t;r++)e[r]=this.baseWeights[r]+this.adaptationVector[r];return e}getAdaptationMagnitude(){let t=0;for(let e=0;e<this.adaptationVector.length;e++)t+=this.adaptationVector[e]*this.adaptationVector[e];return Math.sqrt(t)}resetAdaptation(){this.adaptationVector.fill(0),this.adaptationCount=0}},x=class{fisherMatrix;optimalParams;lambda;fisherDecay;zScoreThreshold;importanceThreshold;gradientHistory=[];gradientMean=0;gradientVariance=0;taskBoundaryCount=0;consolidationCount=0;constructor(t,e=1e3,r=.9,a=2.5,n=.01){this.fisherMatrix=new Float32Array(t),this.optimalParams=new Float32Array(t),this.lambda=e,this.fisherDecay=r,this.zScoreThreshold=a,this.importanceThreshold=n}detectTaskBoundary(t){let e=0;for(let i=0;i<t.length;i++)e+=t[i]*t[i];if(e=Math.sqrt(e),this.gradientHistory.length<5)return this.gradientHistory.push(e),this.updateGradientStats(),!1;let r=Math.sqrt(this.gradientVariance),a=0,n=Math.abs(e-this.gradientMean);return r>1e-10?a=n/r:n>1e-10&&this.gradientMean>1e-10&&(a=n/(this.gradientMean*.01+1e-10)),this.gradientHistory.push(e),this.gradientHistory.length>100&&this.gradientHistory.shift(),this.updateGradientStats(),a>this.zScoreThreshold?(this.taskBoundaryCount++,!0):!1}computeLoss(t){let e=0,r=Math.min(t.length,this.fisherMatrix.length,this.optimalParams.length);for(let a=0;a<r;a++){let n=t[a]-this.optimalParams[a];e+=this.fisherMatrix[a]*n*n}return this.lambda/2*e}updateFisher(t,e){if(t.length===0)return;let r=this.fisherMatrix.length,a=new Float32Array(r);for(let s of t){let u=Math.min(s.length,r);for(let c=0;c<u;c++)a[c]+=s[c]*s[c]}let n=t.length;for(let s=0;s<r;s++)a[s]/=n;let o=this.fisherDecay;for(let s=0;s<r;s++)this.fisherMatrix[s]=o*this.fisherMatrix[s]+(1-o)*a[s];let i=Math.min(e.length,r);for(let s=0;s<i;s++)this.optimalParams[s]=e[s];this.consolidationCount++}getMetrics(){let t=this.fisherMatrix.length,e=0,r=0,a=0;for(let n=0;n<t;n++)e+=this.fisherMatrix[n],this.fisherMatrix[n]>r&&(r=this.fisherMatrix[n]),this.fisherMatrix[n]>this.importanceThreshold&&a++;return{regularizationLoss:0,taskBoundariesDetected:this.taskBoundaryCount,fisherTrace:e,avgFisherImportance:t>0?e/t:0,maxFisherImportance:r,protectedParams:a,consolidationCycles:this.consolidationCount,lambda:this.lambda}}getTaskBoundaryCount(){return this.taskBoundaryCount}getFisherDiagonal(){return new Float32Array(this.fisherMatrix)}getOptimalParams(){return new Float32Array(this.optimalParams)}loadFisher(t,e){let r=this.fisherMatrix.length,a=Math.min(t.length,r),n=Math.min(e.length,r);for(let o=0;o<a;o++)this.fisherMatrix[o]=t[o];for(let o=0;o<n;o++)this.optimalParams[o]=e[o]}updateGradientStats(){let t=this.gradientHistory.length;if(t===0)return;let e=0;for(let a of this.gradientHistory)e+=a;e/=t;let r=0;for(let a of this.gradientHistory){let n=a-e;r+=n*n}r=t>1?r/(t-1):0,this.gradientMean=e,this.gradientVariance=r}},C=class{config;microLora;ewc;nativeEngine;wasmLora=null;requestCount=0;lastConsolidationRequest=0;peerStates=new Map;gradientBuffer=[];lastFeatures=null;constructor(t={},e){this.config={...Mt,...t},this.nativeEngine=e??null,this.microLora=new R(this.config.dimension,this.config.microLoraLr),this.ewc=new x(this.config.dimension,this.config.ewcLambda,this.config.fisherDecay,this.config.taskBoundaryZScoreThreshold,this.config.importanceThreshold);let r=St();if(r)try{this.wasmLora=new r.WasmMicroLoRA(this.config.dimension,1,this.config.microLoraLr),f.info("SONA Three-Loop using WASM MicroLoRA (0.07us/adapt)")}catch(a){f.debug("WASM MicroLoRA creation failed, falling back",{error:String(a)}),this.wasmLora=null}!this.wasmLora&&this.nativeEngine&&f.info("SONA Three-Loop using native @ruvector/sona engine for MicroLoRA delegation")}instantAdapt(t){let e=performance.now(),r;if(this.wasmLora)try{let o=new Float32Array(t),i=this.wasmLora.adapt(o);i&&i.length>0?(r=i,this.microLora.adapt(t)):r=this.microLora.adapt(t)}catch{r=this.microLora.adapt(t)}else if(this.nativeEngine)try{let o=this.nativeEngine.applyMicroLora(t);r=new Float32Array(o),this.microLora.adapt(t)}catch{r=this.microLora.adapt(t)}else r=this.microLora.adapt(t);let a=this.microLora.getAdaptationMagnitude();this.requestCount++,this.lastFeatures=[...t];let n=(performance.now()-e)*1e3;return{adaptedWeights:r,latencyUs:n,applied:!0,magnitude:a,requestIndex:this.requestCount}}recordOutcome(t,e){if(this.lastFeatures===null){f.warn("recordOutcome called without a preceding instantAdapt()");return}let r=this.lastFeatures.length,a=new Float32Array(r);for(let n=0;n<r;n++)a[n]=t*this.lastFeatures[n];this.gradientBuffer.push(a),this.gradientBuffer.length>this.config.fisherSampleSize&&this.gradientBuffer.shift(),this.lastFeatures=null}backgroundConsolidate(){let t=performance.now();if(this.nativeEngine)try{this.nativeEngine.forceLearn(),this.nativeEngine.tick()}catch(i){f.warn("Native SONA background learning failed, continuing with TypeScript",{error:String(i)})}let e=this.ewc.computeLoss(this.microLora.getEffectiveWeights()),r=!1;if(this.gradientBuffer.length>0){let i=this.gradientBuffer[this.gradientBuffer.length-1];r=this.ewc.detectTaskBoundary(i)}if(r&&this.gradientBuffer.length>0&&(this.ewc.updateFisher(this.gradientBuffer,this.microLora.getEffectiveWeights()),f.info("Task boundary detected, Fisher updated",{boundaries:this.ewc.getTaskBoundaryCount(),requestCount:this.requestCount})),this.gradientBuffer.length>1){let i=!1,s=this.gradientBuffer[0];for(let u=1;u<this.gradientBuffer.length&&!i;u++)for(let c=0;c<s.length;c++)if(Math.abs(this.gradientBuffer[u][c]-s[c])>1e-8){i=!0;break}i||f.warn("All gradient samples identical \u2014 Fisher estimate may be poor. Ensure recordOutcome() is called with diverse rewards.")}let a=this.microLora.consolidate();this.applyEWCRegularization();let n=this.ewc.computeLoss(this.microLora.getEffectiveWeights());this.lastConsolidationRequest=this.requestCount,this.gradientBuffer=[];let o=performance.now()-t;return{consolidated:a>0||r,adaptationsMerged:a,ewcLossBefore:e,ewcLossAfter:n,taskBoundaryDetected:r,durationMs:o}}shouldConsolidate(){return this.requestCount-this.lastConsolidationRequest>=this.config.consolidationInterval}syncWithPeers(t){if(t.length===0)return;for(let i of t)this.peerStates.set(i.peerId,i);let e=this.config.dimension,r=new Float32Array(e),a=new Float32Array(e),n=this.ewc.getFisherDiagonal(),o=this.microLora.adaptationVector;for(let i=0;i<e;i++){let s=n[i]+1e-10;r[i]+=s*o[i],a[i]+=s}for(let i of t){let s=Math.min(i.adaptationVector.length,e);for(let u=0;u<s;u++){let c=(u<i.fisherDiagonal.length?i.fisherDiagonal[u]:0)+1e-10;r[u]+=c*i.adaptationVector[u],a[u]+=c}}for(let i=0;i<e;i++)this.microLora.adaptationVector[i]=r[i]/a[i];f.debug("Synced with peers",{peerCount:t.length,peersStored:this.peerStates.size})}getLocalPeerState(t,e){return{peerId:t,domain:e,adaptationVector:new Float32Array(this.microLora.adaptationVector),fisherDiagonal:this.ewc.getFisherDiagonal(),requestCount:this.requestCount,lastUpdateMs:Date.now()}}getEWCMetrics(){let t=this.ewc.getMetrics();return t.regularizationLoss=this.ewc.computeLoss(this.microLora.getEffectiveWeights()),t}getFisherDiagonal(){return this.ewc.getFisherDiagonal()}getOptimalParams(){return this.ewc.getOptimalParams()}loadFisher(t,e){this.ewc.loadFisher(t,e)}getBaseWeights(){return new Float32Array(this.microLora.baseWeights)}setBaseWeights(t){let e=Math.min(t.length,this.microLora.baseWeights.length);for(let r=0;r<e;r++)this.microLora.baseWeights[r]=t[r]}getEffectiveWeights(){return this.microLora.getEffectiveWeights()}getRequestCount(){return this.requestCount}getConfig(){return{...this.config}}getPeerStates(){return new Map(this.peerStates)}getMicroLoRA(){return this.microLora}getEWC(){return this.ewc}applyEWCRegularization(){let t=this.config.dimension,e=this.ewc.fisherMatrix,r=this.ewc.optimalParams,a=this.microLora.baseWeights,n=.01;for(let o=0;o<t;o++)if(e[o]>this.config.importanceThreshold){let i=a[o]-r[o];a[o]-=n*e[o]*i}}persistFisher(t,e){let r=this.ewc.getMetrics();t(e,this.ewc.getFisherDiagonal(),this.ewc.getOptimalParams(),this.getBaseWeights(),{taskBoundaries:r.taskBoundariesDetected,consolidationCycles:r.consolidationCycles,requestCount:this.requestCount,ewcLambda:r.lambda}),f.info("Fisher matrix persisted to SQLite",{domain:e,requestCount:this.requestCount,taskBoundaries:r.taskBoundariesDetected})}restoreFisher(t){this.ewc.loadFisher(t.fisherDiagonal,t.optimalParams),t.baseWeights&&this.setBaseWeights(t.baseWeights),this.requestCount=t.requestCount,f.info("Fisher matrix restored from SQLite",{requestCount:t.requestCount,dimension:t.fisherDiagonal.length})}};var Lt={hiddenDim:256,embeddingDim:384,microLoraRank:1,baseLoraRank:8,microLoraLr:.001,baseLoraLr:1e-4,ewcLambda:1e3,patternClusters:50,trajectoryCapacity:1e4,backgroundIntervalMs:36e5,qualityThreshold:.5,enableSimd:!0,minConfidence:.5,maxPatterns:1e4},Q=class{patterns;trajectoryMap;maxPatterns;constructor(t=1e4){this.patterns=new Map,this.trajectoryMap=new Map,this.maxPatterns=t}register(t){if(this.patterns.size>=this.maxPatterns&&!this.patterns.has(t.id)){let e=Array.from(this.patterns.entries()).sort(([,r],[,a])=>(r.lastUsedAt?.getTime()??r.createdAt.getTime())-(a.lastUsedAt?.getTime()??a.createdAt.getTime()))[0];e&&this.patterns.delete(e[0])}this.patterns.set(t.id,t)}get(t){return this.patterns.get(t)}getByTrajectory(t){let e=this.trajectoryMap.get(t);return e?this.patterns.get(e):void 0}associateTrajectory(t,e){this.trajectoryMap.set(t,e)}update(t,e){let r=this.patterns.get(t);return r?(this.patterns.set(t,{...r,...e}),!0):!1}getAll(){return Array.from(this.patterns.values())}getByType(t){return Array.from(this.patterns.values()).filter(e=>e.type===t)}getByDomain(t){return Array.from(this.patterns.values()).filter(e=>e.domain===t)}clear(){this.patterns.clear(),this.trajectoryMap.clear()}size(){return this.patterns.size}},v=class{engine;registry;config;adaptationTimes=[];cacheHits=0;totalAdaptations=0;threeLoopEngine=null;fisherPersistFn=null;fisherDomain="default";constructor(t={}){this.config={...Lt,...t};let e={hiddenDim:this.config.hiddenDim,embeddingDim:this.config.embeddingDim,microLoraRank:this.config.microLoraRank,baseLoraRank:this.config.baseLoraRank,microLoraLr:this.config.microLoraLr,baseLoraLr:this.config.baseLoraLr,ewcLambda:this.config.ewcLambda,patternClusters:this.config.patternClusters,trajectoryCapacity:this.config.trajectoryCapacity,backgroundIntervalMs:this.config.backgroundIntervalMs,qualityThreshold:this.config.qualityThreshold,enableSimd:this.config.enableSimd};this.engine=P.withConfig(e),this.registry=new Q(this.config.maxPatterns??1e4)}async adaptPattern(t,e,r){let a=performance.now();try{let n=this.createStateEmbedding(t),o=this.engine.findPatterns(n,5),i=[];for(let m of o){let g=this.findByRawPattern(m);if(g||(g=this.createQEPatternFromRaw(m,e,r)),g.type===e&&g.domain===r&&g.confidence>=(this.config.minConfidence??.5)){let h=this.calculateSimilarity(n,m.centroid);i.push({pattern:g,similarity:h})}}if(i.length===0){let m=performance.now()-a;return this.recordAdaptation(m),{success:!1,pattern:null,adaptationTimeMs:m,similarity:0,reasoning:"No suitable pattern found"}}let s=i[0],u={...s.pattern,usageCount:s.pattern.usageCount+1,lastUsedAt:new Date};this.registry.update(u.id,u);let c=performance.now()-a;return this.recordAdaptation(c),{success:!0,pattern:u,adaptationTimeMs:c,similarity:s.similarity,reasoning:`Pattern adapted from @ruvector/sona with ${s.similarity.toFixed(3)} similarity`}}catch(n){let o=performance.now()-a;return this.recordAdaptation(o),{success:!1,pattern:null,adaptationTimeMs:o,similarity:0,reasoning:`Adaptation failed: ${n.message}`}}}recallPattern(t,e,r){let a=this.createStateEmbedding(t),n=this.engine.findPatterns(a,1);for(let o of n){let i=this.findByRawPattern(o);if(i&&i.type===e&&i.domain===r)return i}return null}storePattern(t){this.registry.register(t);let e=this.engine.beginTrajectory(t.stateEmbedding),r=this.createActionEmbedding(t.action),a=new Array(r.length).fill(1),n=t.outcome.success?t.outcome.quality:-t.outcome.quality;this.engine.addTrajectoryStep(e,r,a,n),this.engine.endTrajectory(e,t.outcome.quality),this.registry.associateTrajectory(e,t.id)}storePatternsBatch(t){for(let e of t)this.storePattern(e)}createPattern(t,e,r,a,n,o){let i={id:`qesona-${Date.now()}-${Ct().slice(0,7)}`,type:a,domain:n,stateEmbedding:this.createStateEmbedding(t),action:e,outcome:r,confidence:.5,usageCount:0,createdAt:new Date,metadata:o};return this.storePattern(i),i}updatePattern(t,e,r){let a=this.registry.get(t);if(!a)return!1;let n=e?r:-r,i=a.confidence+.1*(n-a.confidence),s={...a,confidence:Math.max(0,Math.min(1,i)),usageCount:a.usageCount+1,lastUsedAt:new Date};return this.registry.update(t,s)}applyMicroLora(t){return this.engine.applyMicroLora(t)}applyBaseLora(t,e){return this.engine.applyBaseLora(t,e)}forceLearn(){return this.engine.forceLearn()}tick(){return this.engine.tick()}getAllPatterns(){return this.registry.getAll()}getPatternsByType(t){return this.registry.getByType(t)}getPatternsByDomain(t){return this.registry.getByDomain(t)}getStats(){let t=this.registry.getAll(),e=this.engine.getStats(),r={"test-generation":0,"defect-prediction":0,"coverage-optimization":0,"quality-assessment":0,"resource-allocation":0};for(let a of t)r[a.type]++;return{totalPatterns:t.length,patternsByType:r,avgAdaptationTimeMs:this.avgAdaptationTime(),minAdaptationTimeMs:this.minAdaptationTime(),maxAdaptationTimeMs:this.maxAdaptationTime(),totalAdaptations:this.totalAdaptations,cacheHitRate:this.totalAdaptations>0?this.cacheHits/this.totalAdaptations:0,engineStats:e}}clear(){this.registry.clear(),this.adaptationTimes=[],this.cacheHits=0,this.totalAdaptations=0}exportPatterns(){return this.registry.getAll()}importPatterns(t){this.clear(),this.storePatternsBatch(t)}getConfig(){return{...this.config}}setEnabled(t){this.engine.setEnabled(t)}isEnabled(){return this.engine.isEnabled()}createStateEmbedding(t){let e=t.features;if(e.length===0)return new Array(this.config.embeddingDim??384).fill(0);let r=Math.max(...e.map(Math.abs));if(r===0)return[...e];let a=e.map(o=>o/r),n=this.config.embeddingDim??384;return a.length>=n?a.slice(0,n):[...a,...new Array(n-a.length).fill(0)]}createActionEmbedding(t){let e=[],r=this.hashCode(t.type);if(e.push(r%1e3/1e3),typeof t.value=="number")e.push(Math.min(1,Math.max(-1,t.value)));else if(typeof t.value=="string"){let n=this.hashCode(t.value);e.push(n%1e3/1e3)}else if(Array.isArray(t.value))for(let n of t.value.slice(0,10))typeof n=="number"&&e.push(Math.min(1,Math.max(-1,n)));let a=this.config.embeddingDim??384;for(;e.length<a;)e.push(0);return e.slice(0,a)}findByRawPattern(t){let e=this.registry.getAll();for(let r of e)if(r.rawPattern?.patternType===t.id)return r}createQEPatternFromRaw(t,e,r){let a={centroid:t.centroid,clusterSize:1,totalWeight:1,avgQuality:t.avgQuality,createdAt:new Date().toISOString(),lastAccessed:new Date().toISOString(),accessCount:0,patternType:t.patternType};return{id:`qesona-${t.id}`,type:e,domain:r,stateEmbedding:t.centroid,action:{type:"learned",value:t.patternType},outcome:{reward:t.avgQuality,success:t.avgQuality>.5,quality:t.avgQuality},confidence:t.avgQuality,usageCount:0,createdAt:new Date,rawPattern:a}}calculateSimilarity(t,e){let r=Math.min(t.length,e.length),a=0,n=0,o=0;for(let s=0;s<r;s++)a+=t[s]*e[s],n+=t[s]*t[s],o+=e[s]*e[s];return(a/(Math.sqrt(n)*Math.sqrt(o)+1e-10)+1)/2}hashCode(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)}recordAdaptation(t){this.adaptationTimes.push(t),this.totalAdaptations++,this.adaptationTimes.length>1e3&&this.adaptationTimes.shift()}avgAdaptationTime(){return this.adaptationTimes.length===0?0:this.adaptationTimes.reduce((e,r)=>e+r,0)/this.adaptationTimes.length}minAdaptationTime(){return this.adaptationTimes.length===0?0:Math.min(...this.adaptationTimes)}maxAdaptationTime(){return this.adaptationTimes.length===0?0:Math.max(...this.adaptationTimes)}initThreeLoopEngine(t){this.threeLoopEngine=new C({dimension:this.config.embeddingDim??384,microLoraLr:this.config.microLoraLr??.001,ewcLambda:this.config.ewcLambda??1e3,...t},this.engine)}getThreeLoopEngine(){return this.threeLoopEngine}instantAdapt(t){return this.threeLoopEngine?this.threeLoopEngine.instantAdapt(t):null}recordOutcome(t,e){this.threeLoopEngine&&this.threeLoopEngine.recordOutcome(t,e)}backgroundConsolidate(){if(!this.threeLoopEngine)return null;let t=this.threeLoopEngine.backgroundConsolidate();if(t&&(t.consolidated||t.taskBoundaryDetected)&&this.fisherPersistFn)try{this.threeLoopEngine.persistFisher(this.fisherPersistFn,this.fisherDomain)}catch(e){console.warn("[QESONA] Fisher persistence failed:",e instanceof Error?e.message:e)}return t}setFisherPersistence(t,e){this.fisherPersistFn=t,this.fisherDomain=e}syncWithPeers(t){this.threeLoopEngine&&this.threeLoopEngine.syncWithPeers(t)}getEWCMetrics(){return this.threeLoopEngine?this.threeLoopEngine.getEWCMetrics():null}shouldConsolidate(){return this.threeLoopEngine?this.threeLoopEngine.shouldConsolidate():!1}getLocalPeerState(t,e){return this.threeLoopEngine?this.threeLoopEngine.getLocalPeerState(t,e):null}isThreeLoopEnabled(){return this.threeLoopEngine!==null}async verifyPerformance(t=1e3){let e=[],r={id:"test-state",features:new Array(384).fill(0).map(()=>G())};for(let s=0;s<t;s++){let u=performance.now();await this.adaptPattern(r,"test-generation","test-generation");let c=performance.now();e.push({iteration:s,timeMs:c-u})}let a=e.map(s=>s.timeMs),n=a.reduce((s,u)=>s+u,0)/a.length,o=Math.min(...a),i=Math.max(...a);return{targetMet:n<.05,avgTimeMs:n,minTimeMs:o,maxTimeMs:i,details:e}}};function Tt(l){return new v(l)}function Pt(l,t){return new v({...t,maxPatterns:t?.maxPatterns||5e3})}ot();et();var F=null,D=null,W=null,B=null,z=null,I=null,q=!1;try{let l=(O(),w(N));F=l.FlashAttention,D=l.DotProductAttention,W=l.MultiHeadAttention,B=l.HyperbolicAttention,z=l.LinearAttention,I=l.MoEAttention,q=!0}catch{}function Gt(){return q}function A(){if(!q)throw new Error("@ruvector/attention native module is not available on this platform. Install the appropriate optional dependency for your platform, or use a platform where pre-built binaries are available.")}var T={"test-similarity":{dim:384,strategy:"flash",blockSize:64},"code-embedding":{dim:512,strategy:"flash",blockSize:128},"defect-matching":{dim:384,strategy:"flash",blockSize:64},"coverage-analysis":{dim:384,strategy:"flash",blockSize:256},"pattern-adaptation":{dim:256,strategy:"flash",blockSize:32}},Kt={"test-similarity":{enabled:!0,microLoRARank:4,targetAdaptationMs:.05,patternCacheSize:1e3},"code-embedding":{enabled:!0,microLoRARank:2,targetAdaptationMs:.03,patternCacheSize:5e3},"defect-matching":{enabled:!0,microLoRARank:8,targetAdaptationMs:.05,patternCacheSize:2e3},"coverage-analysis":{enabled:!1,microLoRARank:2,targetAdaptationMs:.01,patternCacheSize:100},"pattern-adaptation":{enabled:!0,microLoRARank:2,targetAdaptationMs:.05,patternCacheSize:1e4}},$t={"test-similarity":{latency:{before:50,after:15},memory:{before:200,after:80},throughput:{min:1e3}},"code-embedding":{latency:{before:50,after:15},memory:{before:200,after:80},throughput:{min:2e3}},"defect-matching":{latency:{before:20,after:5},memory:{before:150,after:50},throughput:{min:500}},"coverage-analysis":{latency:{before:100,after:1},memory:{before:100,after:30},throughput:{min:1e4}},"pattern-adaptation":{latency:{before:2,after:.05},memory:{before:50,after:20},throughput:{min:2e4}}};function Zt(l){return l<=128?{queryChunkSize:128,kvChunkSize:128}:l<=256?{queryChunkSize:256,kvChunkSize:256}:l<=512?{queryChunkSize:512,kvChunkSize:512}:l<=1024?{queryChunkSize:1024,kvChunkSize:1024}:{queryChunkSize:1024,kvChunkSize:2048}}var E=class{static create(t){switch(A(),t.strategy){case"flash":return new F(t.dim,t.blockSize);case"dot-product":return new D(t.dim);case"multi-head":return new W(t.dim,t.numHeads??8);case"hyperbolic":return new B(t.dim,t.curvature);case"linear":return new z(t.dim,t.features);case"moe":return I.simple(t.dim,t.moeConfig?.numExperts??8,t.moeConfig?.topK??2);default:return new F(t.dim,t.blockSize)}}},L=class l{attention;config;workload;metrics=[];db=null;persistCount=0;static KV_NAMESPACE="attention-metrics";static KV_TTL=3600;static PERSIST_INTERVAL=10;constructor(t,e){this.workload=t;let r=T[t];this.config={...r,...e},this.attention=E.create(this.config)}async initialize(){try{this.db=K(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(t){console.warn("[QEFlashAttention] DB init failed, using memory-only:",j(t)),this.db=null}}async computeFlashAttention(t,e,r,a,n){let o=performance.now(),i=process.memoryUsage().heapUsed/1024/1024,s=this.toFloat32Array(t,a,n),u=this.splitMatrix(e,a,n),c=this.splitMatrix(r,a,n),m,g=this.attention;typeof g.compute=="function"?m=g.compute(s,u,c):(A(),m=new F(this.config.dim).compute(s,u,c));let h=performance.now(),d=process.memoryUsage().heapUsed/1024/1024;return this.metrics.push({timeMs:h-o,memoryMB:d-i,speedup:1,throughput:a*a/((h-o)/1e3),peakMemoryMB:d}),this.maybePersistToKv(),m}async computeBaselineAttention(t,e,r,a,n){let o=performance.now(),i=process.memoryUsage().heapUsed/1024/1024,s=new Float32Array(a*a),u=1/Math.sqrt(n);for(let h=0;h<a;h++)for(let d=0;d<a;d++){let b=0;for(let p=0;p<n;p++)b+=t[h*n+p]*e[d*n+p];s[h*a+d]=b*u}for(let h=0;h<a;h++){let d=h*a,b=d+a,p=s.subarray(d,b),tt=Math.max(...p),_=0;for(let y=0;y<a;y++)p[y]=Math.exp(p[y]-tt),_+=p[y];for(let y=0;y<a;y++)p[y]/=_}let c=new Float32Array(a*n);for(let h=0;h<a;h++)for(let d=0;d<a;d++){let b=s[h*a+d];for(let p=0;p<n;p++)c[h*n+p]+=b*r[d*n+p]}let m=performance.now(),g=process.memoryUsage().heapUsed/1024/1024;return c}async computeTestSimilarity(t,e,r=5){let a=e.length,n=t.length,o=new Float32Array(a*n),i=new Float32Array(a*n);for(let m=0;m<a;m++)o.set(t,m*n),i.set(e[m],m*n);let s=new Float32Array(a*n),u=await this.computeFlashAttention(o,i,s,a,n),c=[];for(let m=0;m<a;m++)c.push({index:m,similarity:u[m*n]});return c.sort((m,g)=>g.similarity-m.similarity),c.slice(0,r)}async generateCodeEmbedding(t,e){let r=t.length/e.length,a=e.length;return await this.computeFlashAttention(t,e,t,r,a)}async matchDefectPattern(t,e){let r=e.length,a=t.length,n=new Float32Array(r*a),o=new Float32Array(r*a);for(let c=0;c<r;c++)n.set(t,c*a),o.set(e[c],c*a);let i=new Float32Array(r*a),s=await this.computeFlashAttention(n,o,i,r,a),u=[];for(let c=0;c<r;c++)u.push({pattern:c,score:s[c*a]});return u.sort((c,m)=>m.score-c.score),u}getMetrics(){return[...this.metrics]}getAverageSpeedup(){return this.metrics.length===0?1:this.metrics.reduce((t,e)=>t+e.speedup,0)/this.metrics.length}getConfig(){return{...this.config}}updateConfig(t){this.config={...this.config,...t},this.attention=E.create(this.config)}changeStrategy(t){this.config.strategy=t,this.attention=E.create(this.config)}resetMetrics(){this.metrics=[]}getWorkload(){return this.workload}dispose(){this.metrics=[]}async persistToKv(){if(!this.db)return;let t=`attention-metrics-${this.workload}`,e={workload:this.workload,metrics:this.metrics.slice(-50),savedAt:Date.now()};await this.db.kvSet(t,e,l.KV_NAMESPACE,l.KV_TTL)}async loadFromKv(){if(!this.db)return;let t=`attention-metrics-${this.workload}`,e=await this.db.kvGet(t,l.KV_NAMESPACE);e?.metrics?.length&&(this.metrics=e.metrics)}maybePersistToKv(){this.persistCount++,this.persistCount>=l.PERSIST_INTERVAL&&(this.persistCount=0,this.persistToKv().catch(()=>{}))}toFloat32Array(t,e,r){return t.slice(0,r)}splitMatrix(t,e,r){let a=[];for(let n=0;n<e;n++)a.push(t.slice(n*r,(n+1)*r));return a}};async function Y(l,t){let e=new L(l,t);return await e.initialize(),e}function Jt(l){return{...T[l]}}function Xt(){return Object.keys(T)}function Yt(){return A(),F}function te(){return A(),D}function ee(){return A(),W}function re(){return A(),B}function ae(){return A(),z}function ne(){return A(),I}function ie(l){return l instanceof Float32Array?l:new Float32Array(l)}function oe(l){return Array.from(l)}async function se(l,t,e,r){let a=await Y(l),n=[],o=t[0].length,i=e.length;for(let s of t){let u=new Float32Array(i*o),c=new Float32Array(i*o),m=new Float32Array(i*o);u.set(s,0);for(let h=0;h<i;h++)c.set(e[h],h*o),m.set(r[h],h*o);let g=await a.computeFlashAttention(u,c,m,i,o);n.push(g.slice(0,o))}return a.dispose(),n}function We(){return{"@ruvector/sona":"^0.1.5","@ruvector/attention":"^0.1.4","@ruvector/gnn":"^0.1.22"}}function Be(){let l={sona:!1,attention:!1,gnn:!1,all:!1};try{k(),l.sona=!0}catch{}try{O(),l.attention=!0}catch{}try{let t=(it(),w(nt));t.init();let e=new Float32Array([.1,.2,.3]),r=[new Float32Array([.1,.2,.3]),new Float32Array([.4,.5,.6])],a=t.differentiableSearch(e,r,1,1);a&&Array.isArray(a.indices)&&Array.isArray(a.weights)&&(l.gnn=!0)}catch{}return l.all=l.sona&&l.attention&&l.gnn,l}async function ze(){let{initGNN:l}=await import("./gnn-wrapper-Z45DRWGI.js");return[l(),"SONA: Ready (no initialization required)","Attention: Ready (no initialization required)"]}export{v as a,Tt as b,Pt as c,Gt as d,T as e,Kt as f,$t as g,Zt as h,L as i,Y as j,Jt as k,Xt as l,Yt as m,te as n,ee as o,re as p,ae as q,ne as r,ie as s,oe as t,se as u,We as v,Be as w,ze as x};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.15");process.exit(0)}
|
|
2
|
+
import{a as l}from"./chunk-ICXWXO5P.js";import{a as m}from"./chunk-FW6QBTPE.js";import{f as a}from"./chunk-MBDX4OHD.js";var u=class{constructor(t,e){this.eventBus=t;this.maxHistorySize=e?.maxHistorySize??1e4,this.eventHistory=new l(this.maxHistorySize),this.correlationTimeout=e?.correlationTimeout??6e4,this.maxEventsPerCorrelation=e?.maxEventsPerCorrelation??100}eventBus;subscriptions=new Map;correlations=new Map;eventHistory;routes=[];domainSubscriptions=new Map;maxHistorySize;correlationTimeout;maxEventsPerCorrelation;initialized=!1;async initialize(){if(!this.initialized){for(let t of m){let e=this.eventBus.subscribeToChannel(t,async i=>{await this.handleIncomingEvent(i)});this.domainSubscriptions.set(t,e)}this.eventBus.subscribe("*",async t=>{m.includes(t.source)||await this.handleIncomingEvent(t)}),this.initialized=!0}}subscribeToDoamin(t,e){let i=`sub_domain_${a()}`;return this.subscriptions.set(i,{id:i,type:"domain",filter:t,handler:e,active:!0}),i}subscribeToEventType(t,e){let i=`sub_type_${a()}`;return this.subscriptions.set(i,{id:i,type:"eventType",filter:t,handler:e,active:!0}),i}unsubscribe(t){let e=this.subscriptions.get(t);return e?(e.active=!1,this.subscriptions.delete(t),!0):!1}async route(t){this.addToHistory(t),t.correlationId&&this.trackCorrelation(t);let i=this.findMatchingSubscriptions(t).map(async o=>{try{await o.handler(t)}catch(n){console.error(`Error in subscription handler ${o.id}:`,n instanceof Error?n.message:n)}}),r=await this.applyRoutes(t);await Promise.allSettled([...i,...r])}getCorrelation(t){let e=this.correlations.get(t);if(e)return{correlationId:e.correlationId,events:[...e.events],domains:new Set(e.domains),startedAt:e.startedAt,lastEventAt:e.lastEventAt,complete:e.complete}}trackCorrelation(t){if(!t.correlationId)return;let e=this.correlations.get(t.correlationId);e||(e={correlationId:t.correlationId,events:[],domains:new Set,startedAt:t.timestamp,lastEventAt:t.timestamp,complete:!1,timeout:null},this.correlations.set(t.correlationId,e)),e.events.length<this.maxEventsPerCorrelation&&(e.events.push(t),e.domains.add(t.source),e.lastEventAt=t.timestamp),e.timeout&&clearTimeout(e.timeout),e.timeout=setTimeout(()=>{e.complete=!0,e.timeout=null},this.correlationTimeout)}aggregate(t,e){let i=this.eventHistory.toArray().filter(s=>s.timestamp>=t&&s.timestamp<=e),r=new Map,o=new Map;for(let s of i)r.set(s.type,(r.get(s.type)??0)+1),o.set(s.source,(o.get(s.source)??0)+1);let n={totalEvents:i.length,uniqueEventTypes:r.size,uniqueDomains:o.size,eventsPerSecond:i.length>0?i.length/((e.getTime()-t.getTime())/1e3):0};return{id:a(),windowStart:t,windowEnd:e,events:i,countByType:r,countByDomain:o,metrics:n}}getHistory(t){let e=this.eventHistory.toArray();return t&&(t.eventTypes?.length&&(e=e.filter(i=>t.eventTypes.includes(i.type))),t.domains?.length&&(e=e.filter(i=>t.domains.includes(i.source))),t.fromTimestamp&&(e=e.filter(i=>i.timestamp>=t.fromTimestamp)),t.toTimestamp&&(e=e.filter(i=>i.timestamp<=t.toTimestamp)),t.limit&&(e=e.slice(-t.limit))),e}addRoute(t){let e=t.priority??0,i=this.routes.findIndex(r=>(r.priority??0)<e);i===-1?this.routes.push(t):this.routes.splice(i,0,t)}removeRoute(t,e){let i=this.routes.findIndex(r=>r.eventPattern===t&&(e===void 0||r.source===e));return i!==-1?(this.routes.splice(i,1),!0):!1}async dispose(){this.subscriptions.clear();for(let t of this.domainSubscriptions.values())t.unsubscribe();this.domainSubscriptions.clear();for(let t of this.correlations.values())t.timeout&&clearTimeout(t.timeout);this.correlations.clear(),this.eventHistory.clear(),this.initialized=!1}async handleIncomingEvent(t){await this.route(t)}findMatchingSubscriptions(t){let e=[];for(let i of this.subscriptions.values())i.active&&(i.type==="domain"&&i.filter===t.source||i.type==="eventType"&&this.matchEventType(t.type,i.filter))&&e.push(i);return e}matchEventType(t,e){if(e==="*")return!0;let i=e.replace(/\\/g,"\\\\").replace(/\./g,"\\.").replace(/\*/g,".*");return new RegExp(`^${i}$`).test(t)}async applyRoutes(t){let e=[];for(let i of this.routes){if(!(i.source==="*"||i.source===t.source||Array.isArray(i.source)&&i.source.includes(t.source))||!this.matchEventType(t.type,i.eventPattern)||i.filter&&!i.filter(t))continue;let o=i.transform?i.transform(t):t;for(let n of i.targets)n!==t.source&&e.push(this.eventBus.publish({...o,id:a(),correlationId:t.correlationId??t.id}))}return e}addToHistory(t){this.eventHistory.push(t)}};function y(c,t){return new u(c,t)}export{u as a,y as b};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.15");process.exit(0)}
|
|
2
2
|
var i={domain:"test-generation",bestPractices:["Follow Arrange-Act-Assert (AAA) pattern for clear test structure","One logical assertion per test - test one behavior at a time","Use descriptive test names: should_returnValue_when_condition","Mock external dependencies to isolate unit under test","Test edge cases and boundary conditions, not just happy paths","Keep tests deterministic - avoid time-dependent assertions","Use test data builders or factories for complex objects","Prefer integration tests for workflows, unit tests for logic","Maintain test independence - no shared mutable state between tests","Write failing test first (TDD Red) before implementation"],antiPatterns:[{name:"God Test",description:"A single test that verifies too many behaviors",reason:"Hard to diagnose failures, brittle, slow to run",alternative:"Split into focused tests, each verifying one behavior",detection:"expect.*expect.*expect.*expect.*expect"},{name:"Mystery Guest",description:"Test relies on external data files or state not visible in test",reason:"Tests are hard to understand and maintain",alternative:"Make test data explicit within the test or use fixtures"},{name:"Eager Test",description:"Test that verifies more than needed for the current behavior",reason:"Creates unnecessary coupling, breaks easily",alternative:"Only assert what is necessary for this specific test case"},{name:"Flaky Assertion",description:"Assertions that depend on timing, order, or external state",reason:"Creates unreliable test suite, erodes trust",alternative:"Use deterministic assertions, mock time/random",detection:"setTimeout|Date\\.now|Math\\.random"},{name:"Test Code Duplication",description:"Same setup or assertion code repeated across tests",reason:"Maintenance burden, inconsistency risk",alternative:"Extract to beforeEach, helpers, or fixtures"}],frameworkGuidance:{jest:["Use describe blocks to group related tests","Prefer toEqual for deep equality, toBe for primitives","Use jest.mock() at module level for consistent mocking","Use jest.spyOn for partial mocking of objects","Enable --coverage to track test coverage"],vitest:["Use vi.mock() for module mocking","Prefer vi.fn() over jest.fn() syntax","Use vitest/ui for interactive test debugging","Enable browser mode for component tests","Use inline snapshots for small expected values"],mocha:["Use beforeEach/afterEach for setup/teardown","Combine with chai for assertions","Use sinon for spies, stubs, and mocks","Set appropriate timeouts for async tests"],pytest:["Use fixtures for reusable test setup","Use parametrize for data-driven tests","Use conftest.py for shared fixtures","Use pytest.raises for exception testing","Use pytest-cov for coverage reporting"],junit:["Use @BeforeEach and @AfterEach for setup/teardown","Use @DisplayName for readable test names","Use @ParameterizedTest for data-driven tests","Use Mockito for mocking dependencies"],testng:["Use @BeforeMethod and @AfterMethod appropriately","Use @DataProvider for parameterized tests","Configure test groups for selective execution"],playwright:["Use page.locator() for resilient element selection","Use expect(locator) for auto-waiting assertions","Use page.waitForLoadState for navigation","Use test.describe for grouping tests","Use fixtures for reusable browser contexts"],cypress:["Use cy.intercept() for API mocking","Avoid conditional testing - use deterministic state","Use data-cy attributes for stable selectors","Use cy.within() for scoped queries","Prefer cy.contains() for text-based selection"],selenium:["Use explicit waits over implicit waits","Use Page Object Model for maintainability","Handle stale element references with retry logic","Clean up browser state between tests"]},languageGuidance:{typescript:["Use type assertions in tests for better IDE support","Create typed test fixtures and builders","Use satisfies operator for test data validation","Mock types with ts-mockito or typed mocking libs"],javascript:["Use JSDoc comments for test documentation","Consider TypeScript for larger test suites","Use ESLint with testing plugins"],python:["Use type hints in test functions","Use dataclasses for test data","Follow PEP 8 naming: test_should_do_something"],java:["Use AssertJ for fluent assertions","Use Lombok for test data classes","Follow naming: shouldDoSomething_whenCondition"],go:["Use table-driven tests for multiple cases","Use testify for assertions and mocking","Place tests in _test.go files"],rust:["Use #[test] attribute for test functions","Use assert!, assert_eq!, assert_ne! macros","Place unit tests in same file with #[cfg(test)]"],csharp:["Use xUnit or NUnit for testing","Use FluentAssertions for readable assertions","Use Moq for mocking interfaces"],kotlin:["Use kotest for BDD-style testing","Use MockK for Kotlin-first mocking","Use data classes for test fixtures"]},examples:[{title:"Unit Test Template (TypeScript + Vitest)",description:"Standard AAA pattern for unit tests",content:`describe('UserService', () => {
|
|
3
3
|
describe('createUser', () => {
|
|
4
4
|
it('should create user with valid data', async () => {
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.15");process.exit(0)}
|
|
2
2
|
function c(r,e,o){let n=new Error(r);return n.name="LLMError",n.code=e,n.provider=o?.provider,n.model=o?.model,n.retryable=o?.retryable??!1,n.retryAfterMs=o?.retryAfterMs,n.cause=o?.cause,n}function p(r){return r instanceof Error&&"code"in r&&typeof r.code=="string"}var a={"claude-sonnet-4-5":{canonical:"Claude Sonnet 4.5",family:"claude",tier:"standard",providers:{anthropic:"claude-sonnet-4-5-20250929",openrouter:"anthropic/claude-sonnet-4.5",bedrock:"anthropic.claude-sonnet-4-5-v2:0"}},"claude-opus-4":{canonical:"Claude Opus 4",family:"claude",tier:"flagship",providers:{anthropic:"claude-opus-4-20250514",openrouter:"anthropic/claude-opus-4",bedrock:"anthropic.claude-opus-4-v1:0"}},"claude-opus-4-5":{canonical:"Claude Opus 4.5",family:"claude",tier:"flagship",providers:{anthropic:"claude-opus-4-5-20251101",openrouter:"anthropic/claude-opus-4.5",bedrock:"anthropic.claude-opus-4-5-v1:0"}},"claude-haiku-3-5":{canonical:"Claude Haiku 3.5",family:"claude",tier:"economy",providers:{anthropic:"claude-3-5-haiku-20241022",openrouter:"anthropic/claude-3.5-haiku",bedrock:"anthropic.claude-3-5-haiku-v1:0"}},"claude-sonnet-4":{canonical:"Claude Sonnet 4",family:"claude",tier:"standard",providers:{anthropic:"claude-sonnet-4-20250514",openrouter:"anthropic/claude-sonnet-4",bedrock:"anthropic.claude-sonnet-4-v1:0"}},"claude-opus-4-7":{canonical:"Claude Opus 4.7",family:"claude",tier:"flagship",providers:{anthropic:"claude-opus-4-7",openrouter:"anthropic/claude-opus-4.7",bedrock:"anthropic.claude-opus-4-7-v1:0"}},"claude-sonnet-4-6":{canonical:"Claude Sonnet 4.6",family:"claude",tier:"standard",providers:{anthropic:"claude-sonnet-4-6",openrouter:"anthropic/claude-sonnet-4.6",bedrock:"anthropic.claude-sonnet-4-6-v1:0"}},"claude-haiku-4-5":{canonical:"Claude Haiku 4.5",family:"claude",tier:"economy",providers:{anthropic:"claude-haiku-4-5-20251001",openrouter:"anthropic/claude-haiku-4.5",bedrock:"anthropic.claude-haiku-4-5-v1:0"}},"gpt-4o":{canonical:"GPT-4o",family:"gpt",tier:"standard",providers:{openai:"gpt-4o",azure:"gpt-4o",openrouter:"openai/gpt-4o"}},"gpt-4o-mini":{canonical:"GPT-4o Mini",family:"gpt",tier:"economy",providers:{openai:"gpt-4o-mini",azure:"gpt-4o-mini",openrouter:"openai/gpt-4o-mini"}},"gpt-4-turbo":{canonical:"GPT-4 Turbo",family:"gpt",tier:"premium",providers:{openai:"gpt-4-turbo",azure:"gpt-4-turbo",openrouter:"openai/gpt-4-turbo"}},"gpt-4":{canonical:"GPT-4",family:"gpt",tier:"premium",providers:{openai:"gpt-4",azure:"gpt-4",openrouter:"openai/gpt-4"}},o1:{canonical:"OpenAI o1",family:"gpt",tier:"flagship",providers:{openai:"o1",azure:"o1",openrouter:"openai/o1"}},"o1-mini":{canonical:"OpenAI o1 Mini",family:"gpt",tier:"standard",providers:{openai:"o1-mini",azure:"o1-mini",openrouter:"openai/o1-mini"}},"gemini-pro":{canonical:"Gemini Pro",family:"gemini",tier:"standard",providers:{gemini:"gemini-pro",openrouter:"google/gemini-pro"}},"gemini-pro-1.5":{canonical:"Gemini Pro 1.5",family:"gemini",tier:"standard",providers:{gemini:"gemini-1.5-pro",openrouter:"google/gemini-pro-1.5"}},"gemini-flash-1.5":{canonical:"Gemini Flash 1.5",family:"gemini",tier:"economy",providers:{gemini:"gemini-1.5-flash",openrouter:"google/gemini-flash-1.5"}},"gemini-ultra":{canonical:"Gemini Ultra",family:"gemini",tier:"flagship",providers:{gemini:"gemini-ultra",openrouter:"google/gemini-ultra"}},llama3:{canonical:"Llama 3",family:"llama",tier:"economy",providers:{ollama:"llama3",openrouter:"meta-llama/llama-3-8b-instruct"}},"llama3.1":{canonical:"Llama 3.1",family:"llama",tier:"economy",providers:{ollama:"llama3.1",openrouter:"meta-llama/llama-3.1-8b-instruct"}},codellama:{canonical:"CodeLlama",family:"llama",tier:"economy",providers:{ollama:"codellama",openrouter:"meta-llama/codellama-34b-instruct"}},mistral:{canonical:"Mistral",family:"mistral",tier:"economy",providers:{ollama:"mistral",openrouter:"mistralai/mistral-7b-instruct"}},mixtral:{canonical:"Mixtral",family:"mistral",tier:"standard",providers:{ollama:"mixtral",openrouter:"mistralai/mixtral-8x7b-instruct"}},phi3:{canonical:"Phi-3",family:"phi",tier:"economy",providers:{ollama:"phi3",azure:"phi-3-mini-128k-instruct"}},qwen2:{canonical:"Qwen 2",family:"qwen",tier:"economy",providers:{ollama:"qwen2",openrouter:"qwen/qwen-2-7b-instruct"}}};function l(){let r=new Map;for(let[e,o]of Object.entries(a)){r.set(e,e),r.set(e.toLowerCase(),e);for(let[n,t]of Object.entries(o.providers))t&&(r.set(t,e),r.set(t.toLowerCase(),e),r.set(`${n}/${t}`,e),r.set(`${n}/${t}`.toLowerCase(),e))}return r}var i=l();function m(r,e){let o=s(r),n=a[o];if(!n)throw new Error(`Unknown model: ${r}`);let t=n.providers[e];if(!t)throw new Error(`Model '${o}' (${n.canonical}) is not available on provider '${e}'`);return t}function s(r){let e=i.get(r);if(e||(e=i.get(r.toLowerCase()),e))return e;let o=[/^anthropic\//i,/^openai\//i,/^google\//i,/^meta-llama\//i,/^mistralai\//i,/^qwen\//i];for(let n of o){let t=r.replace(n,"");if(e=i.get(t),e||(e=i.get(t.toLowerCase()),e))return e}throw new Error(`Unknown model ID: ${r}`)}function d(r){try{let e=s(r);return a[e]}catch{return}}export{c as a,p as b,m as c,s as d,d as e};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{a as I}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.15");process.exit(0)}
|
|
2
|
+
import{a as I}from"./chunk-ZOAPOVYW.js";import{n as F,o as q}from"./chunk-LLVS3UYZ.js";import{a as A,b as m,c as d}from"./chunk-FW6QBTPE.js";import{a as b,b as W,c as O}from"./chunk-JJDHD7SC.js";import{f as D}from"./chunk-MBDX4OHD.js";import{g as T}from"./chunk-CUQBOVRP.js";O();var w={WorkflowStarted:"workflow.WorkflowStarted",WorkflowCompleted:"workflow.WorkflowCompleted",WorkflowFailed:"workflow.WorkflowFailed",WorkflowCancelled:"workflow.WorkflowCancelled",StepStarted:"workflow.StepStarted",StepCompleted:"workflow.StepCompleted",StepFailed:"workflow.StepFailed",StepSkipped:"workflow.StepSkipped",StepAwaitingApproval:"workflow.StepAwaitingApproval",StepApproved:"workflow.StepApproved",StepRejected:"workflow.StepRejected"},E={maxConcurrentWorkflows:10,defaultStepTimeout:6e4,defaultWorkflowTimeout:6e5,enableEventTriggers:!0,persistExecutions:!0};function S(){try{let{getUnifiedMemory:s}=(q(),T(F)),e=s();return e.isInitialized()?e.getDatabase():null}catch{return null}}var N={id:"quality-gate-check",domain:"quality-assessment",action:"gate-check",async execute(s){let e=typeof s.coverageMin=="number"?s.coverageMin:80,t=typeof s.testsPassingMin=="number"?s.testsPassingMin:90,i=typeof s.maxBugs=="number"?s.maxBugs:5,r=typeof s.currentCoverage=="number"?s.currentCoverage:null,n=typeof s.currentTestsPassingRate=="number"?s.currentTestsPassingRate:null,o=typeof s.currentBugs=="number"?s.currentBugs:null;if(r===null||n===null||o===null){let p=S();if(p)try{if(r===null&&(r=p.prepare("SELECT after_lines FROM coverage_sessions ORDER BY created_at DESC LIMIT 1").get()?.after_lines??0),n===null){let y=p.prepare(`SELECT COUNT(*) as total,
|
|
3
3
|
SUM(CASE WHEN passed = 1 THEN 1 ELSE 0 END) as passed
|
|
4
4
|
FROM test_outcomes
|
|
5
5
|
WHERE created_at > datetime('now', '-7 days')`).get();n=y&&y.total>0?y.passed/y.total*100:0}o===null&&(o=p.prepare(`SELECT COUNT(*) as bugs FROM test_outcomes
|
|
@@ -13,4 +13,4 @@ import{a as I}from"./chunk-WQGP5ULD.js";import{n as F,o as q}from"./chunk-EBQUXP
|
|
|
13
13
|
SELECT COUNT(*) as total,
|
|
14
14
|
SUM(CASE WHEN success = 1 THEN 1 ELSE 0 END) as successful
|
|
15
15
|
FROM routing_outcomes
|
|
16
|
-
`).get();e=e??c?.total??0,t=t??c?.successful??0}catch{}}e=e??0,t=t??0,i=i??0;let n=e>0?Math.round(t/e*1e4)/100:0;return m({successRate:n,totalOutcomes:e,successfulOutcomes:t,confidenceCorrelation:i,source:r})}},$=[N,_,L,z];function R(s,e){return $.find(t=>t.domain===s&&t.action===e)}function M(){return[B(),U(),G(),j(),H(),Q()]}var P=["comprehensive-testing","defect-prevention","pre-release","continuous-learning","morning-sync","qcsd-ideation-swarm"];function B(){return{id:"comprehensive-testing",name:"Comprehensive Testing Workflow",description:"test-generation -> test-execution -> coverage-analysis -> quality-assessment",version:"1.0.0",tags:["testing","quality"],steps:[{id:"generate-tests",name:"Generate Tests",domain:"test-generation",action:"generateTests",inputMapping:{sourceFiles:"input.sourceFiles",framework:"input.framework"},outputMapping:{testFiles:"generatedTests.files",testCount:"generatedTests.count"},timeout:12e4,retry:{maxAttempts:2,backoffMs:1e3}},{id:"execute-tests",name:"Execute Tests",domain:"test-execution",action:"execute",dependsOn:["generate-tests"],inputMapping:{testFiles:"results.generatedTests.files"},outputMapping:{runId:"execution.runId",passed:"execution.passed",failed:"execution.failed"},timeout:3e5},{id:"analyze-coverage",name:"Analyze Coverage",domain:"coverage-analysis",action:"analyze",dependsOn:["execute-tests"],inputMapping:{runId:"results.execution.runId"},outputMapping:{line:"coverage.line",branch:"coverage.branch",overall:"coverage.overall"}},{id:"assess-quality",name:"Assess Quality",domain:"quality-assessment",action:"evaluateGate",dependsOn:["analyze-coverage"],inputMapping:{coverage:"results.coverage",testResults:"results.execution"},outputMapping:{passed:"quality.gatePassed",score:"quality.score"}},{id:"generate-more-tests",name:"Generate Additional Tests",domain:"test-generation",action:"generateTests",dependsOn:["analyze-coverage"],condition:{path:"results.coverage.overall",operator:"lt",value:80},inputMapping:{sourceFiles:"input.sourceFiles",targetCoverage:"input.targetCoverage"},continueOnFailure:!0}]}}function U(){return{id:"defect-prevention",name:"Defect Prevention Workflow",description:"code-intelligence (impact) -> defect-intelligence (predict) -> test-generation (for risky areas)",version:"1.0.0",tags:["defect","prevention","ai"],steps:[{id:"analyze-impact",name:"Analyze Code Impact",domain:"code-intelligence",action:"analyzeImpact",inputMapping:{changedFiles:"input.changedFiles"},outputMapping:{impactedFiles:"impact.files",impactedTests:"impact.tests",riskLevel:"impact.riskLevel"},timeout:6e4},{id:"predict-defects",name:"Predict Defects",domain:"defect-intelligence",action:"predictDefects",dependsOn:["analyze-impact"],inputMapping:{files:"results.impact.files"},outputMapping:{predictions:"defects.predictions",highRiskFiles:"defects.highRiskFiles"}},{id:"generate-targeted-tests",name:"Generate Targeted Tests",domain:"test-generation",action:"generateTests",dependsOn:["predict-defects"],condition:{path:"results.defects.highRiskFiles",operator:"exists",value:!0},inputMapping:{sourceFiles:"results.defects.highRiskFiles",priority:"input.priority"}}],triggers:[{eventType:"code-intelligence.ImpactAnalysisCompleted",inputMapping:{changedFiles:"event.changedFiles"}}]}}function G(){return{id:"pre-release",name:"Pre-Release Workflow",description:"security-audit -> quality-gate -> deployment-advisor",version:"1.0.0",tags:["release","security","deployment"],steps:[{id:"security-audit",name:"Security Audit",domain:"security-compliance",action:"runAudit",inputMapping:{targetFiles:"input.targetFiles",includeDependencies:"input.includeDependencies"},outputMapping:{vulnerabilities:"security.vulnerabilities",riskScore:"security.riskScore",passed:"security.passed"},timeout:18e4},{id:"quality-gate",name:"Quality Gate Evaluation",domain:"quality-assessment",action:"evaluateGate",dependsOn:["security-audit"],inputMapping:{securityResults:"results.security",releaseCandidate:"input.releaseCandidate"},outputMapping:{passed:"quality.gatePassed",checks:"quality.checks"}},{id:"deployment-advice",name:"Get Deployment Advice",domain:"quality-assessment",action:"getDeploymentAdvice",dependsOn:["quality-gate"],inputMapping:{releaseCandidate:"input.releaseCandidate",qualityResults:"results.quality",securityResults:"results.security"},outputMapping:{decision:"deployment.decision",recommendations:"deployment.recommendations",riskScore:"deployment.riskScore"}}],triggers:[{eventType:"quality-assessment.QualityGateEvaluated",condition:{path:"event.passed",operator:"eq",value:!0}}]}}function j(){return{id:"continuous-learning",name:"Continuous Learning Workflow",description:"Collect patterns -> consolidate -> transfer -> optimize",version:"1.0.0",tags:["learning","optimization","ai"],steps:[{id:"collect-patterns",name:"Collect Patterns",domain:"learning-optimization",action:"runLearningCycle",inputMapping:{domain:"input.targetDomain"},outputMapping:{patternsLearned:"learning.patterns",experiencesProcessed:"learning.experiences"}},{id:"consolidate-patterns",name:"Consolidate Patterns",domain:"learning-optimization",action:"shareCrossDomainLearnings",dependsOn:["collect-patterns"],condition:{path:"results.learning.patterns",operator:"gt",value:0},outputMapping:{knowledgeShared:"consolidation.shared",domainsUpdated:"consolidation.domains"}},{id:"transfer-knowledge",name:"Transfer Knowledge",domain:"learning-optimization",action:"shareCrossDomainLearnings",dependsOn:["consolidate-patterns"],outputMapping:{transferSuccessRate:"transfer.successRate",newPatternsCreated:"transfer.newPatterns"}},{id:"optimize-strategies",name:"Optimize Strategies",domain:"learning-optimization",action:"optimizeAllStrategies",dependsOn:["transfer-knowledge"],outputMapping:{domainsOptimized:"optimization.domains",avgImprovement:"optimization.improvement"}}]}}function H(){return{id:"morning-sync",name:"Morning Sync Protocol",description:"Daily quality synchronization across all domains",version:"1.0.0",tags:["protocol","daily","sync"],steps:[{id:"collect-metrics",name:"Collect Quality Metrics",domain:"quality-assessment",action:"analyzeQuality",inputMapping:{sourceFiles:"input.sourceFiles"},outputMapping:{score:"metrics.qualityScore"}},{id:"analyze-trends",name:"Analyze Coverage Trends",domain:"coverage-analysis",action:"getTrend",inputMapping:{timeRange:"input.timeRange",granularity:"input.granularity"},outputMapping:{trend:"trends.coverage",forecast:"trends.forecast"}},{id:"check-security",name:"Check Security Posture",domain:"security-compliance",action:"getSecurityPosture",outputMapping:{overallScore:"security.score",criticalIssues:"security.critical",recommendations:"security.recommendations"}},{id:"get-defect-predictions",name:"Get Defect Predictions",domain:"defect-intelligence",action:"predictDefects",inputMapping:{files:"input.changedFiles"},outputMapping:{predictions:"defects.predictions"}},{id:"generate-learning-report",name:"Generate Learning Dashboard",domain:"learning-optimization",action:"getLearningDashboard",dependsOn:["collect-metrics","analyze-trends","check-security","get-defect-predictions"],outputMapping:{learningRate:"learning.rate",topDomains:"learning.topDomains"}}]}}function Q(){return{id:"qcsd-ideation-swarm",name:"QCSD Ideation Swarm",description:"Quality Conscious Software Delivery ideation phase: [url-extraction] -> [flag-detection] -> quality-criteria (HTSM) -> [testability, risk, requirements, security*, accessibility*, qx*] in parallel -> aggregated report. Supports live website URLs with conditional agent spawning based on HAS_UI, HAS_SECURITY, HAS_UX flags.",version:"3.0.0",tags:["qcsd","ideation","quality-criteria","htsm","shift-left","url-analysis"],steps:[{id:"website-content-extraction",name:"Website Content Extraction",domain:"requirements-validation",action:"extractWebsiteContent",inputMapping:{url:"input.url"},outputMapping:{extractedDescription:"extraction.description",extractedFeatures:"extraction.features",extractedAcceptanceCriteria:"extraction.acceptanceCriteria",detectedFlags:"extraction.flags",isWebsite:"extraction.isWebsite"},timeout:6e4,continueOnFailure:!0},{id:"quality-criteria-analysis",name:"HTSM Quality Criteria Analysis",domain:"requirements-validation",action:"analyzeQualityCriteria",dependsOn:["website-content-extraction"],inputMapping:{targetId:"input.targetId",targetType:"input.targetType",description:"results.website-content-extraction.extractedDescription || input.description",acceptanceCriteria:"results.website-content-extraction.extractedAcceptanceCriteria || input.acceptanceCriteria"},outputMapping:{qualityCriteria:"qualityCriteria.criteria",qualityScore:"qualityCriteria.score"},timeout:18e4,retry:{maxAttempts:2,backoffMs:2e3}},{id:"testability-assessment",name:"Testability Scoring (10 Principles)",domain:"requirements-validation",action:"assessTestability",dependsOn:["quality-criteria-analysis"],inputMapping:{targetId:"input.targetId",description:"results.website-content-extraction.extractedDescription || input.description",acceptanceCriteria:"results.website-content-extraction.extractedAcceptanceCriteria || input.acceptanceCriteria"},outputMapping:{overallScore:"testability.overallScore",principles:"testability.principles",blockers:"testability.blockers",recommendations:"testability.recommendations"},timeout:12e4,continueOnFailure:!0},{id:"risk-assessment",name:"Quality Risk Assessment",domain:"requirements-validation",action:"assessRisks",dependsOn:["quality-criteria-analysis"],inputMapping:{targetId:"input.targetId",targetType:"input.targetType",description:"results.website-content-extraction.extractedDescription || input.description"},outputMapping:{overallRisk:"risks.overallRisk",riskScore:"risks.riskScore",factors:"risks.factors",mitigations:"risks.mitigations"},timeout:9e4,continueOnFailure:!0},{id:"requirements-validation",name:"Requirements & Acceptance Criteria Validation",domain:"requirements-validation",action:"validateRequirements",dependsOn:["quality-criteria-analysis"],inputMapping:{targetId:"input.targetId",description:"results.website-content-extraction.extractedDescription || input.description",acceptanceCriteria:"results.website-content-extraction.extractedAcceptanceCriteria || input.acceptanceCriteria"},outputMapping:{valid:"requirements.valid",issues:"requirements.issues",suggestions:"requirements.suggestions"},timeout:9e4,continueOnFailure:!0},{id:"security-threat-modeling",name:"Early Security Threat Modeling (STRIDE)",domain:"security-compliance",action:"modelSecurityThreats",dependsOn:["quality-criteria-analysis"],condition:{path:"results.website-content-extraction.detectedFlags.hasSecurity || input.securityCritical",operator:"eq",value:!0},inputMapping:{targetId:"input.targetId",description:"results.website-content-extraction.extractedDescription || input.description",securityCritical:"results.website-content-extraction.detectedFlags.hasSecurity || input.securityCritical"},outputMapping:{threats:"security.threats",overallRisk:"security.overallRisk",recommendations:"security.recommendations"},timeout:12e4,continueOnFailure:!0},{id:"accessibility-audit",name:"Accessibility Audit (WCAG 2.2)",domain:"visual-accessibility",action:"auditAccessibility",dependsOn:["quality-criteria-analysis"],condition:{path:"results.website-content-extraction.detectedFlags.hasUI || input.hasUI",operator:"eq",value:!0},inputMapping:{targetId:"input.targetId",url:"input.url",description:"results.website-content-extraction.extractedDescription || input.description",features:"results.website-content-extraction.extractedFeatures"},outputMapping:{wcagLevel:"accessibility.wcagLevel",violations:"accessibility.violations",recommendations:"accessibility.recommendations"},timeout:18e4,continueOnFailure:!0},{id:"quality-experience-analysis",name:"Quality Experience Analysis (QX Partner)",domain:"coordination",action:"analyzeQualityExperience",dependsOn:["quality-criteria-analysis"],condition:{path:"results.website-content-extraction.detectedFlags.hasUX || input.hasUX",operator:"eq",value:!0},inputMapping:{targetId:"input.targetId",url:"input.url",description:"results.website-content-extraction.extractedDescription || input.description",features:"results.website-content-extraction.extractedFeatures"},outputMapping:{journeys:"qx.journeys",frictionPoints:"qx.frictionPoints",recommendations:"qx.recommendations"},timeout:15e4,continueOnFailure:!0},{id:"aggregate-ideation-report",name:"Generate Ideation Report",domain:"requirements-validation",action:"generateIdeationReport",dependsOn:["quality-criteria-analysis","testability-assessment","risk-assessment","requirements-validation","security-threat-modeling","accessibility-audit","quality-experience-analysis"],inputMapping:{targetId:"input.targetId",targetType:"input.targetType"},outputMapping:{report:"ideation.report",readyForDevelopment:"ideation.readyForDevelopment",blockers:"ideation.blockers",recommendations:"ideation.recommendations",testStrategy:"ideation.testStrategy"},timeout:6e4},{id:"store-ideation-learnings",name:"Store Ideation Learnings",domain:"learning-optimization",action:"storeIdeationLearnings",dependsOn:["aggregate-ideation-report"],inputMapping:{targetId:"input.targetId",report:"results.ideation.report"},outputMapping:{stored:"learning.stored",patternId:"learning.patternId"},continueOnFailure:!0}],triggers:[{eventType:"requirements-validation.EpicCreated",inputMapping:{targetId:"event.epicId",targetType:"event.type",description:"event.description",acceptanceCriteria:"event.acceptanceCriteria"}},{eventType:"requirements-validation.SprintPlanningStarted",inputMapping:{targetId:"event.sprintId",targetType:"event.type",description:"event.description",acceptanceCriteria:"event.acceptanceCriteria"}}]}}var C=class{constructor(e,t,i,r={}){this.eventBus=e;this.memory=t;this.agentCoordinator=i;this.config={...E,...r}}config;workflows=new Map;executions=new Map;actionRegistry={};eventSubscriptions=[];approvalGates=new Map;initialized=!1;async initialize(){this.initialized||(this.registerBuiltInWorkflows(),this.config.enableEventTriggers&&this.setupEventTriggers(),await this.loadPersistedWorkflows(),this.initialized=!0)}async dispose(){for(let e of this.executions.values())e.status==="running"&&await this.cancelWorkflow(e.executionId);for(let e of this.eventSubscriptions)e.unsubscribe();await this.persistWorkflows(),this.initialized=!1}registerWorkflow(e){try{let t=this.validateWorkflowDefinition(e);return t.success?(this.workflows.set(e.id,e),this.config.enableEventTriggers&&e.triggers&&this.registerWorkflowTriggers(e),m(void 0)):t}catch(t){return d(W(t))}}unregisterWorkflow(e){if(!this.workflows.has(e))return d(new Error(`Workflow not found: ${e}`));let t=Array.from(this.executions.values()).filter(i=>i.workflowId===e&&i.status==="running");return t.length>0?d(new Error(`Cannot unregister workflow with ${t.length} active execution(s)`)):(this.workflows.delete(e),m(void 0))}async executeWorkflow(e,t={},i){let r=this.workflows.get(e);if(!r)return d(new Error(`Workflow not found: ${e}`));if(Array.from(this.executions.values()).filter(g=>g.status==="running").length>=this.config.maxConcurrentWorkflows)return d(new Error(`Maximum concurrent workflows (${this.config.maxConcurrentWorkflows}) reached`));let o=D(),c=new Date,a={input:t,results:{},metadata:{executionId:o,workflowId:e,correlationId:i||o,startedAt:c}},l={executionId:o,workflowId:e,workflowName:r.name,status:"running",startedAt:c,progress:0,currentSteps:[],completedSteps:[],failedSteps:[],skippedSteps:[],context:a,stepResults:new Map};return this.executions.set(o,l),await this.publishWorkflowStarted(l,r),this.runWorkflow(r,l).catch(async g=>{l.status="failed",l.error=String(g),l.completedAt=new Date,l.duration=l.completedAt.getTime()-c.getTime(),await this.publishWorkflowFailed(l,"unknown",String(g))}),m(o)}getWorkflowStatus(e){return this.executions.get(e)}async cancelWorkflow(e){let t=this.executions.get(e);if(!t)return d(new Error(`Execution not found: ${e}`));if(t.status!=="running"&&t.status!=="paused")return d(new Error(`Cannot cancel workflow in status: ${t.status}`));t.status="cancelled",t.completedAt=new Date,t.duration=t.completedAt.getTime()-t.startedAt.getTime();for(let[i,r]of this.approvalGates.entries())i.startsWith(`${e}:`)&&(r.resolve({approved:!1,reason:"Workflow cancelled"}),this.approvalGates.delete(i));return await this.publishEvent(w.WorkflowCancelled,{executionId:e,workflowId:t.workflowId,workflowName:t.workflowName},t.context.metadata.correlationId),m(void 0)}async pauseWorkflow(e){let t=this.executions.get(e);return t?t.status!=="running"?d(new Error(`Cannot pause workflow in status: ${t.status}`)):(t.status="paused",m(void 0)):d(new Error(`Execution not found: ${e}`))}async resumeWorkflow(e){let t=this.executions.get(e);if(!t)return d(new Error(`Execution not found: ${e}`));if(t.status!=="paused")return d(new Error(`Cannot resume workflow in status: ${t.status}`));let i=this.workflows.get(t.workflowId);return i?(t.status="running",this.runWorkflow(i,t).catch(async r=>{t.status="failed",t.error=String(r)}),m(void 0)):d(new Error(`Workflow definition not found: ${t.workflowId}`))}listWorkflows(){return Array.from(this.workflows.values()).map(e=>({id:e.id,name:e.name,description:e.description,version:e.version,stepCount:e.steps.length,tags:e.tags,triggers:e.triggers?.map(t=>t.eventType)}))}getActiveExecutions(){return Array.from(this.executions.values()).filter(e=>e.status==="running"||e.status==="paused")}getWorkflow(e){return this.workflows.get(e)}approveStep(e,t){let i=`${e}:${t}`,r=this.approvalGates.get(i);return r?(r.resolve({approved:!0}),this.approvalGates.delete(i),!0):!1}rejectStep(e,t,i){let r=`${e}:${t}`,n=this.approvalGates.get(r);return n?(n.resolve({approved:!1,reason:i}),this.approvalGates.delete(r),!0):!1}isActionRegistered(e,t){return!!this.actionRegistry[e]?.[t]}getRegisteredActions(e){return Object.keys(this.actionRegistry[e]||{})}getDomainsWithActions(){return Object.keys(this.actionRegistry)}async spawnWorkflowAgent(e,t,i){return this.agentCoordinator.canSpawn()?this.agentCoordinator.spawn({name:`workflow-agent-${e.slice(0,8)}-${t}`,domain:i,type:"coordinator",capabilities:["workflow-execution",t],config:{workflowId:e,stepId:t}}):d(new Error("Agent limit reached"))}async stopWorkflowAgent(e){return this.agentCoordinator.stop(e)}getAvailableAgentCapacity(){return this.agentCoordinator.canSpawn()?this.config.maxConcurrentWorkflows-this.getActiveExecutions().length:0}registerAction(e,t,i){let r=["__proto__","constructor","prototype"];if(r.includes(e)||r.includes(t))throw new Error("Invalid domain or action name: contains dangerous prototype key");this.actionRegistry[e]||(this.actionRegistry[e]={}),this.actionRegistry[e][t]=i}async executeFromBehaviorTree(e){let t=new Date;try{let i=await e.tick(),r=new Date,n=r.getTime()-t.getTime();return{status:i==="SUCCESS"?"completed":i==="RUNNING"?"running":"failed",startedAt:t,completedAt:r,duration:n,treeStatus:i,treeName:e.name}}catch(i){let r=new Date,n=r.getTime()-t.getTime();return{status:"failed",startedAt:t,completedAt:r,duration:n,treeStatus:"FAILURE",treeName:e.name,error:b(i)}}}async runWorkflow(e,t){let i=e.timeout||this.config.defaultWorkflowTimeout,r=new Promise((n,o)=>{setTimeout(()=>o(new Error(`Workflow timeout after ${i}ms`)),i)});try{await Promise.race([this.executeSteps(e,t),r]),t.status==="running"&&(t.status="completed",t.completedAt=new Date,t.duration=t.completedAt.getTime()-t.startedAt.getTime(),t.progress=100,await this.publishWorkflowCompleted(t))}catch(n){if(t.status==="running"){t.status="failed",t.error=String(n),t.completedAt=new Date,t.duration=t.completedAt.getTime()-t.startedAt.getTime();let o=t.currentSteps[0]||"unknown";await this.publishWorkflowFailed(t,o,String(n))}}this.config.persistExecutions&&await this.persistExecution(t)}async executeSteps(e,t){let i=e.steps,r=new Set(t.completedSteps),n=new Set(t.skippedSteps),o=new Set(t.failedSteps),c=i.filter(a=>!r.has(a.id)&&!n.has(a.id)&&!o.has(a.id));for(;c.length>0&&t.status==="running";){let a=c.filter(u=>(u.dependsOn||[]).every(p=>r.has(p)||n.has(p)));if(a.length===0)break;let l=a.filter(u=>!u.dependsOn?.length),g=a.filter(u=>u.dependsOn?.length);if(l.length>0){t.currentSteps=l.map(f=>f.id);let u=await Promise.allSettled(l.map(f=>this.executeStep(f,t,e)));for(let f=0;f<l.length;f++){let p=l[f],y=u[f];if(y.status==="fulfilled"){let h=y.value;if(h.status==="completed")r.add(p.id),t.completedSteps.push(p.id);else if(h.status==="skipped")n.add(p.id),t.skippedSteps.push(p.id);else if(h.status==="failed"&&(o.add(p.id),t.failedSteps.push(p.id),!p.continueOnFailure)){t.status="failed",t.error=h.error;return}}else if(o.add(p.id),t.failedSteps.push(p.id),!p.continueOnFailure){t.status="failed",t.error=y.reason?.message||"Unknown error";return}let x=c.indexOf(p);x!==-1&&c.splice(x,1)}}for(let u of g){if(t.status!=="running")break;t.currentSteps=[u.id];let f=await this.executeStep(u,t,e);if(f.status==="completed")r.add(u.id),t.completedSteps.push(u.id);else if(f.status==="skipped")n.add(u.id),t.skippedSteps.push(u.id);else if(f.status==="failed"&&(o.add(u.id),t.failedSteps.push(u.id),!u.continueOnFailure)){t.status="failed",t.error=f.error;return}let p=c.indexOf(u);p!==-1&&c.splice(p,1)}let k=i.length,v=r.size+n.size+o.size;t.progress=Math.round(v/k*100)}t.currentSteps=[]}async executeStep(e,t,i){let r=new Date,n={stepId:e.id,status:"pending",startedAt:r};try{if(e.skipCondition&&this.evaluateCondition(e.skipCondition,t.context))return n.status="skipped",n.completedAt=new Date,n.duration=n.completedAt.getTime()-r.getTime(),t.stepResults.set(e.id,n),await this.publishStepSkipped(t,e),n;if(e.condition&&!this.evaluateCondition(e.condition,t.context))return n.status="skipped",n.completedAt=new Date,n.duration=n.completedAt.getTime()-r.getTime(),t.stepResults.set(e.id,n),await this.publishStepSkipped(t,e),n;n.status="running",await this.publishStepStarted(t,e);let o=this.buildStepInput(e,t.context),c,a=e.retry?.maxAttempts||1,l=e.retry?.backoffMs||1e3,g=e.retry?.backoffMultiplier||2;for(let k=1;k<=a;k++){n.retryCount=k-1;try{let v=e.timeout||this.config.defaultStepTimeout,u=await this.executeStepAction(e,o,t.context,v);if(this.mapStepOutput(e,u,t.context),e.approval){let f=await this.waitForApproval(e,t);if(!f.approved)return n.status="failed",n.error=f.reason||"Step rejected at approval gate",n.output=u,n.completedAt=new Date,n.duration=n.completedAt.getTime()-r.getTime(),t.stepResults.set(e.id,n),await this.publishStepFailed(t,e,n.error),n}return n.status="completed",n.output=u,n.completedAt=new Date,n.duration=n.completedAt.getTime()-r.getTime(),t.stepResults.set(e.id,n),await this.publishStepCompleted(t,e,n),n}catch(v){c=W(v),k<a&&(await this.delay(l),l*=g)}}return n.status="failed",n.error=c?.message||"Unknown error",n.completedAt=new Date,n.duration=n.completedAt.getTime()-r.getTime(),t.stepResults.set(e.id,n),e.rollback&&await this.executeRollback(e.rollback,t.context),await this.publishStepFailed(t,e,n.error),n}catch(o){return n.status="failed",n.error=b(o),n.completedAt=new Date,n.duration=n.completedAt.getTime()-r.getTime(),t.stepResults.set(e.id,n),await this.publishStepFailed(t,e,n.error),n}}async executeStepAction(e,t,i,r){let n=new Promise((a,l)=>{setTimeout(()=>l(new Error(`Step timeout after ${r}ms`)),r)}),o=R(e.domain,e.action);if(o){let a=await Promise.race([o.execute(t,i),n]);if(!a.success)throw a.error;return a.value}let c=this.actionRegistry[e.domain];if(c?.[e.action]){let a=await Promise.race([c[e.action](t,i),n]);if(!a.success)throw a.error;return a.value}throw new Error(`Action '${e.action}' not registered for domain '${e.domain}'. Register it using orchestrator.registerAction('${e.domain}', '${e.action}', handler)`)}async executeRollback(e,t){try{let i=this.actionRegistry[e.domain];if(!i?.[e.action]){console.warn(`Rollback action '${e.action}' not registered for domain '${e.domain}'. Skipping rollback.`);return}let r=await i[e.action](e.input||{},t);r.success||console.error(`Rollback failed for ${e.domain}.${e.action}:`,r.error)}catch(i){console.error(`Rollback failed for ${e.domain}.${e.action}:`,i)}}buildStepInput(e,t){let i={};if(e.inputMapping)for(let[r,n]of Object.entries(e.inputMapping)){let o=this.getValueByPath(t,n);o!==void 0&&(i[r]=o)}return i}mapStepOutput(e,t,i){if(i.results[e.id]=t,e.outputMapping&&typeof t=="object"&&t!==null)for(let[r,n]of Object.entries(e.outputMapping)){let o=this.getValueByPath(t,r);o!==void 0&&this.setValueByPath(i.results,n,o)}}getValueByPath(e,t){let i=t.split("."),r=e;for(let n of i){if(r==null)return;if(typeof r=="object")r=r[n];else return}return r}setValueByPath(e,t,i){let r=t.split("."),n=new Set(["__proto__","constructor","prototype"]);for(let a of r)if(n.has(a))throw new Error("Invalid path: contains dangerous prototype key");let o=e;for(let a=0;a<r.length-1;a++){let l=r[a];Object.hasOwn(o,l)||Object.defineProperty(o,l,{value:Object.create(null),writable:!0,enumerable:!0,configurable:!0}),o=o[l]}let c=r[r.length-1];Object.defineProperty(o,c,{value:i,writable:!0,enumerable:!0,configurable:!0})}evaluateCondition(e,t){let i=this.getValueByPath(t,e.path);switch(e.operator){case"eq":return i===e.value;case"neq":return i!==e.value;case"gt":return typeof i=="number"&&i>e.value;case"gte":return typeof i=="number"&&i>=e.value;case"lt":return typeof i=="number"&&i<e.value;case"lte":return typeof i=="number"&&i<=e.value;case"contains":return Array.isArray(i)?i.includes(e.value):typeof i=="string"?i.includes(String(e.value)):!1;case"exists":return i!=null;default:return!1}}async publishEvent(e,t,i){let r=I(e,"learning-optimization",t,i);await this.eventBus.publish(r)}async publishWorkflowStarted(e,t){await this.publishEvent(w.WorkflowStarted,{executionId:e.executionId,workflowId:e.workflowId,workflowName:e.workflowName,stepCount:t.steps.length},e.context.metadata.correlationId)}async publishWorkflowCompleted(e){await this.publishEvent(w.WorkflowCompleted,{executionId:e.executionId,workflowId:e.workflowId,workflowName:e.workflowName,duration:e.duration||0,completedSteps:e.completedSteps.length,skippedSteps:e.skippedSteps.length},e.context.metadata.correlationId)}async publishWorkflowFailed(e,t,i){await this.publishEvent(w.WorkflowFailed,{executionId:e.executionId,workflowId:e.workflowId,workflowName:e.workflowName,failedStep:t,error:i},e.context.metadata.correlationId)}async publishStepStarted(e,t){await this.publishEvent(w.StepStarted,{executionId:e.executionId,workflowId:e.workflowId,stepId:t.id,stepName:t.name,domain:t.domain},e.context.metadata.correlationId)}async publishStepCompleted(e,t,i){await this.publishEvent(w.StepCompleted,{executionId:e.executionId,workflowId:e.workflowId,stepId:t.id,stepName:t.name,domain:t.domain,duration:i.duration},e.context.metadata.correlationId)}async publishStepFailed(e,t,i){await this.publishEvent(w.StepFailed,{executionId:e.executionId,workflowId:e.workflowId,stepId:t.id,stepName:t.name,domain:t.domain,error:i},e.context.metadata.correlationId)}async publishStepSkipped(e,t){await this.publishEvent(w.StepSkipped,{executionId:e.executionId,workflowId:e.workflowId,stepId:t.id,stepName:t.name,domain:t.domain},e.context.metadata.correlationId)}validateWorkflowDefinition(e){if(!e.id)return d(new Error("Workflow ID is required"));if(!e.name)return d(new Error("Workflow name is required"));if(!e.steps||e.steps.length===0)return d(new Error("Workflow must have at least one step"));let t=new Set;for(let r of e.steps){if(!r.id)return d(new Error("Step ID is required"));if(t.has(r.id))return d(new Error(`Duplicate step ID: ${r.id}`));if(t.add(r.id),!r.domain)return d(new Error(`Step ${r.id} must have a domain`));if(!A.includes(r.domain))return d(new Error(`Invalid domain for step ${r.id}: ${r.domain}`));if(!r.action)return d(new Error(`Step ${r.id} must have an action`));if(r.dependsOn){for(let n of r.dependsOn)if(!e.steps.some(o=>o.id===n))return d(new Error(`Step ${r.id} depends on unknown step: ${n}`))}}let i=this.detectCircularDependencies(e.steps);return i?d(new Error(`Circular dependency detected: ${i}`)):m(void 0)}detectCircularDependencies(e){let t=new Set,i=new Set,r=(n,o)=>{if(i.has(n))return[...o,n].join(" -> ");if(t.has(n))return null;t.add(n),i.add(n);let c=e.find(a=>a.id===n);if(c?.dependsOn)for(let a of c.dependsOn){let l=r(a,[...o,n]);if(l)return l}return i.delete(n),null};for(let n of e){let o=r(n.id,[]);if(o)return o}return null}setupEventTriggers(){let e=this.eventBus.subscribe("*",async t=>{await this.handleEventForTriggers(t)});this.eventSubscriptions.push(e)}registerWorkflowTriggers(e){}async handleEventForTriggers(e){for(let t of this.workflows.values())if(t.triggers)for(let i of t.triggers){if(i.eventType!==e.type||i.sourceDomain&&i.sourceDomain!==e.source)continue;if(i.condition){let n={input:{event:e.payload},results:{},metadata:{executionId:"",workflowId:t.id,startedAt:new Date}};if(!this.evaluateCondition(i.condition,n))continue}let r={};if(i.inputMapping)for(let[n,o]of Object.entries(i.inputMapping)){let c=this.getValueByPath({event:e.payload},o);c!==void 0&&(r[n]=c)}else r.triggerEvent=e.payload;await this.executeWorkflow(t.id,r,e.correlationId)}}registerBuiltInWorkflows(){let e=M();for(let t of e)this.registerWorkflow(t)}async loadPersistedWorkflows(){try{let e=await this.memory.search("workflow:definition:*",100);for(let t of e){let i=await this.memory.get(t);i&&!this.workflows.has(i.id)&&this.workflows.set(i.id,i)}}catch(e){console.error("Failed to load persisted workflows:",e)}}async persistWorkflows(){try{for(let e of this.workflows.values())P.includes(e.id)||await this.memory.set(`workflow:definition:${e.id}`,e,{namespace:"coordination",persist:!0})}catch(e){console.error("Failed to persist workflows:",e)}}async persistExecution(e){try{let t={...e,stepResults:Object.fromEntries(e.stepResults)};await this.memory.set(`workflow:execution:${e.executionId}`,t,{namespace:"coordination",ttl:86400*7})}catch(t){console.error("Failed to persist execution:",t)}}async waitForApproval(e,t){let i=typeof e.approval=="object"?e.approval:{},r=i.autoApproveAfter??3e5,n=i.message??`Awaiting approval for step: ${e.name}`,o=t.stepResults.get(e.id);o&&(o.status="awaiting_approval"),await this.publishEvent(w.StepAwaitingApproval,{executionId:t.executionId,workflowId:t.workflowId,stepId:e.id,stepName:e.name,domain:e.domain,message:n,autoApproveAfter:r>0?r:void 0},t.context.metadata.correlationId);let c=`${t.executionId}:${e.id}`;return new Promise(a=>{let l={resolve:a};if(this.approvalGates.set(c,l),r>0){let g=setTimeout(()=>{this.approvalGates.has(c)&&(this.approvalGates.delete(c),a({approved:!0}))},r),k=l.resolve;l.resolve=v=>{clearTimeout(g),k(v)}}})}delay(e){return new Promise(t=>setTimeout(t,e))}};function de(s,e,t,i){return new C(s,e,t,i)}export{w as a,E as b,C as c,de as d};
|
|
16
|
+
`).get();e=e??c?.total??0,t=t??c?.successful??0}catch{}}e=e??0,t=t??0,i=i??0;let n=e>0?Math.round(t/e*1e4)/100:0;return m({successRate:n,totalOutcomes:e,successfulOutcomes:t,confidenceCorrelation:i,source:r})}},$=[N,_,L,z];function R(s,e){return $.find(t=>t.domain===s&&t.action===e)}function M(){return[B(),U(),G(),j(),H(),Q()]}var P=["comprehensive-testing","defect-prevention","pre-release","continuous-learning","morning-sync","qcsd-ideation-swarm"];function B(){return{id:"comprehensive-testing",name:"Comprehensive Testing Workflow",description:"test-generation -> test-execution -> coverage-analysis -> quality-assessment",version:"1.0.0",tags:["testing","quality"],steps:[{id:"generate-tests",name:"Generate Tests",domain:"test-generation",action:"generateTests",inputMapping:{sourceFiles:"input.sourceFiles",framework:"input.framework"},outputMapping:{testFiles:"generatedTests.files",testCount:"generatedTests.count"},timeout:12e4,retry:{maxAttempts:2,backoffMs:1e3}},{id:"execute-tests",name:"Execute Tests",domain:"test-execution",action:"execute",dependsOn:["generate-tests"],inputMapping:{testFiles:"results.generatedTests.files"},outputMapping:{runId:"execution.runId",passed:"execution.passed",failed:"execution.failed"},timeout:3e5},{id:"analyze-coverage",name:"Analyze Coverage",domain:"coverage-analysis",action:"analyze",dependsOn:["execute-tests"],inputMapping:{runId:"results.execution.runId"},outputMapping:{line:"coverage.line",branch:"coverage.branch",overall:"coverage.overall"}},{id:"assess-quality",name:"Assess Quality",domain:"quality-assessment",action:"evaluateGate",dependsOn:["analyze-coverage"],inputMapping:{coverage:"results.coverage",testResults:"results.execution"},outputMapping:{passed:"quality.gatePassed",score:"quality.score"}},{id:"generate-more-tests",name:"Generate Additional Tests",domain:"test-generation",action:"generateTests",dependsOn:["analyze-coverage"],condition:{path:"results.coverage.overall",operator:"lt",value:80},inputMapping:{sourceFiles:"input.sourceFiles",targetCoverage:"input.targetCoverage"},continueOnFailure:!0}]}}function U(){return{id:"defect-prevention",name:"Defect Prevention Workflow",description:"code-intelligence (impact) -> defect-intelligence (predict) -> test-generation (for risky areas)",version:"1.0.0",tags:["defect","prevention","ai"],steps:[{id:"analyze-impact",name:"Analyze Code Impact",domain:"code-intelligence",action:"analyzeImpact",inputMapping:{changedFiles:"input.changedFiles"},outputMapping:{impactedFiles:"impact.files",impactedTests:"impact.tests",riskLevel:"impact.riskLevel"},timeout:6e4},{id:"predict-defects",name:"Predict Defects",domain:"defect-intelligence",action:"predictDefects",dependsOn:["analyze-impact"],inputMapping:{files:"results.impact.files"},outputMapping:{predictions:"defects.predictions",highRiskFiles:"defects.highRiskFiles"}},{id:"generate-targeted-tests",name:"Generate Targeted Tests",domain:"test-generation",action:"generateTests",dependsOn:["predict-defects"],condition:{path:"results.defects.highRiskFiles",operator:"exists",value:!0},inputMapping:{sourceFiles:"results.defects.highRiskFiles",priority:"input.priority"}}],triggers:[{eventType:"code-intelligence.ImpactAnalysisCompleted",inputMapping:{changedFiles:"event.changedFiles"}}]}}function G(){return{id:"pre-release",name:"Pre-Release Workflow",description:"security-audit -> quality-gate -> deployment-advisor",version:"1.0.0",tags:["release","security","deployment"],steps:[{id:"security-audit",name:"Security Audit",domain:"security-compliance",action:"runAudit",inputMapping:{targetFiles:"input.targetFiles",includeDependencies:"input.includeDependencies"},outputMapping:{vulnerabilities:"security.vulnerabilities",riskScore:"security.riskScore",passed:"security.passed"},timeout:18e4},{id:"quality-gate",name:"Quality Gate Evaluation",domain:"quality-assessment",action:"evaluateGate",dependsOn:["security-audit"],inputMapping:{securityResults:"results.security",releaseCandidate:"input.releaseCandidate"},outputMapping:{passed:"quality.gatePassed",checks:"quality.checks"}},{id:"deployment-advice",name:"Get Deployment Advice",domain:"quality-assessment",action:"getDeploymentAdvice",dependsOn:["quality-gate"],inputMapping:{releaseCandidate:"input.releaseCandidate",qualityResults:"results.quality",securityResults:"results.security"},outputMapping:{decision:"deployment.decision",recommendations:"deployment.recommendations",riskScore:"deployment.riskScore"}}],triggers:[{eventType:"quality-assessment.QualityGateEvaluated",condition:{path:"event.passed",operator:"eq",value:!0}}]}}function j(){return{id:"continuous-learning",name:"Continuous Learning Workflow",description:"Collect patterns -> consolidate -> transfer -> optimize",version:"1.0.0",tags:["learning","optimization","ai"],steps:[{id:"collect-patterns",name:"Collect Patterns",domain:"learning-optimization",action:"runLearningCycle",inputMapping:{domain:"input.targetDomain"},outputMapping:{patternsLearned:"learning.patterns",experiencesProcessed:"learning.experiences"}},{id:"consolidate-patterns",name:"Consolidate Patterns",domain:"learning-optimization",action:"shareCrossDomainLearnings",dependsOn:["collect-patterns"],condition:{path:"results.learning.patterns",operator:"gt",value:0},outputMapping:{knowledgeShared:"consolidation.shared",domainsUpdated:"consolidation.domains"}},{id:"transfer-knowledge",name:"Transfer Knowledge",domain:"learning-optimization",action:"shareCrossDomainLearnings",dependsOn:["consolidate-patterns"],outputMapping:{transferSuccessRate:"transfer.successRate",newPatternsCreated:"transfer.newPatterns"}},{id:"optimize-strategies",name:"Optimize Strategies",domain:"learning-optimization",action:"optimizeAllStrategies",dependsOn:["transfer-knowledge"],outputMapping:{domainsOptimized:"optimization.domains",avgImprovement:"optimization.improvement"}}]}}function H(){return{id:"morning-sync",name:"Morning Sync Protocol",description:"Daily quality synchronization across all domains",version:"1.0.0",tags:["protocol","daily","sync"],steps:[{id:"collect-metrics",name:"Collect Quality Metrics",domain:"quality-assessment",action:"analyzeQuality",inputMapping:{sourceFiles:"input.sourceFiles"},outputMapping:{score:"metrics.qualityScore"}},{id:"analyze-trends",name:"Analyze Coverage Trends",domain:"coverage-analysis",action:"getTrend",inputMapping:{timeRange:"input.timeRange",granularity:"input.granularity"},outputMapping:{trend:"trends.coverage",forecast:"trends.forecast"}},{id:"check-security",name:"Check Security Posture",domain:"security-compliance",action:"getSecurityPosture",outputMapping:{overallScore:"security.score",criticalIssues:"security.critical",recommendations:"security.recommendations"}},{id:"get-defect-predictions",name:"Get Defect Predictions",domain:"defect-intelligence",action:"predictDefects",inputMapping:{files:"input.changedFiles"},outputMapping:{predictions:"defects.predictions"}},{id:"generate-learning-report",name:"Generate Learning Dashboard",domain:"learning-optimization",action:"getLearningDashboard",dependsOn:["collect-metrics","analyze-trends","check-security","get-defect-predictions"],outputMapping:{learningRate:"learning.rate",topDomains:"learning.topDomains"}}]}}function Q(){return{id:"qcsd-ideation-swarm",name:"QCSD Ideation Swarm",description:"Quality Conscious Software Delivery ideation phase: [url-extraction] -> [flag-detection] -> quality-criteria (HTSM) -> [testability, risk, requirements, security*, accessibility*, qx*] in parallel -> aggregated report. Supports live website URLs with conditional agent spawning based on HAS_UI, HAS_SECURITY, HAS_UX flags.",version:"3.0.0",tags:["qcsd","ideation","quality-criteria","htsm","shift-left","url-analysis"],steps:[{id:"website-content-extraction",name:"Website Content Extraction",domain:"requirements-validation",action:"extractWebsiteContent",inputMapping:{url:"input.url"},outputMapping:{extractedDescription:"extraction.description",extractedFeatures:"extraction.features",extractedAcceptanceCriteria:"extraction.acceptanceCriteria",detectedFlags:"extraction.flags",isWebsite:"extraction.isWebsite"},timeout:6e4,continueOnFailure:!0},{id:"quality-criteria-analysis",name:"HTSM Quality Criteria Analysis",domain:"requirements-validation",action:"analyzeQualityCriteria",dependsOn:["website-content-extraction"],inputMapping:{targetId:"input.targetId",targetType:"input.targetType",description:"results.website-content-extraction.extractedDescription || input.description",acceptanceCriteria:"results.website-content-extraction.extractedAcceptanceCriteria || input.acceptanceCriteria"},outputMapping:{qualityCriteria:"qualityCriteria.criteria",qualityScore:"qualityCriteria.score"},timeout:18e4,retry:{maxAttempts:2,backoffMs:2e3}},{id:"testability-assessment",name:"Testability Scoring (10 Principles)",domain:"requirements-validation",action:"assessTestability",dependsOn:["quality-criteria-analysis"],inputMapping:{targetId:"input.targetId",description:"results.website-content-extraction.extractedDescription || input.description",acceptanceCriteria:"results.website-content-extraction.extractedAcceptanceCriteria || input.acceptanceCriteria"},outputMapping:{overallScore:"testability.overallScore",principles:"testability.principles",blockers:"testability.blockers",recommendations:"testability.recommendations"},timeout:12e4,continueOnFailure:!0},{id:"risk-assessment",name:"Quality Risk Assessment",domain:"requirements-validation",action:"assessRisks",dependsOn:["quality-criteria-analysis"],inputMapping:{targetId:"input.targetId",targetType:"input.targetType",description:"results.website-content-extraction.extractedDescription || input.description"},outputMapping:{overallRisk:"risks.overallRisk",riskScore:"risks.riskScore",factors:"risks.factors",mitigations:"risks.mitigations"},timeout:9e4,continueOnFailure:!0},{id:"requirements-validation",name:"Requirements & Acceptance Criteria Validation",domain:"requirements-validation",action:"validateRequirements",dependsOn:["quality-criteria-analysis"],inputMapping:{targetId:"input.targetId",description:"results.website-content-extraction.extractedDescription || input.description",acceptanceCriteria:"results.website-content-extraction.extractedAcceptanceCriteria || input.acceptanceCriteria"},outputMapping:{valid:"requirements.valid",issues:"requirements.issues",suggestions:"requirements.suggestions"},timeout:9e4,continueOnFailure:!0},{id:"security-threat-modeling",name:"Early Security Threat Modeling (STRIDE)",domain:"security-compliance",action:"modelSecurityThreats",dependsOn:["quality-criteria-analysis"],condition:{path:"results.website-content-extraction.detectedFlags.hasSecurity || input.securityCritical",operator:"eq",value:!0},inputMapping:{targetId:"input.targetId",description:"results.website-content-extraction.extractedDescription || input.description",securityCritical:"results.website-content-extraction.detectedFlags.hasSecurity || input.securityCritical"},outputMapping:{threats:"security.threats",overallRisk:"security.overallRisk",recommendations:"security.recommendations"},timeout:12e4,continueOnFailure:!0},{id:"accessibility-audit",name:"Accessibility Audit (WCAG 2.2)",domain:"visual-accessibility",action:"auditAccessibility",dependsOn:["quality-criteria-analysis"],condition:{path:"results.website-content-extraction.detectedFlags.hasUI || input.hasUI",operator:"eq",value:!0},inputMapping:{targetId:"input.targetId",url:"input.url",description:"results.website-content-extraction.extractedDescription || input.description",features:"results.website-content-extraction.extractedFeatures"},outputMapping:{wcagLevel:"accessibility.wcagLevel",violations:"accessibility.violations",recommendations:"accessibility.recommendations"},timeout:18e4,continueOnFailure:!0},{id:"quality-experience-analysis",name:"Quality Experience Analysis (QX Partner)",domain:"coordination",action:"analyzeQualityExperience",dependsOn:["quality-criteria-analysis"],condition:{path:"results.website-content-extraction.detectedFlags.hasUX || input.hasUX",operator:"eq",value:!0},inputMapping:{targetId:"input.targetId",url:"input.url",description:"results.website-content-extraction.extractedDescription || input.description",features:"results.website-content-extraction.extractedFeatures"},outputMapping:{journeys:"qx.journeys",frictionPoints:"qx.frictionPoints",recommendations:"qx.recommendations"},timeout:15e4,continueOnFailure:!0},{id:"aggregate-ideation-report",name:"Generate Ideation Report",domain:"requirements-validation",action:"generateIdeationReport",dependsOn:["quality-criteria-analysis","testability-assessment","risk-assessment","requirements-validation","security-threat-modeling","accessibility-audit","quality-experience-analysis"],inputMapping:{targetId:"input.targetId",targetType:"input.targetType"},outputMapping:{report:"ideation.report",readyForDevelopment:"ideation.readyForDevelopment",blockers:"ideation.blockers",recommendations:"ideation.recommendations",testStrategy:"ideation.testStrategy"},timeout:6e4},{id:"store-ideation-learnings",name:"Store Ideation Learnings",domain:"learning-optimization",action:"storeIdeationLearnings",dependsOn:["aggregate-ideation-report"],inputMapping:{targetId:"input.targetId",report:"results.ideation.report"},outputMapping:{stored:"learning.stored",patternId:"learning.patternId"},continueOnFailure:!0}],triggers:[{eventType:"requirements-validation.EpicCreated",inputMapping:{targetId:"event.epicId",targetType:"event.type",description:"event.description",acceptanceCriteria:"event.acceptanceCriteria"}},{eventType:"requirements-validation.SprintPlanningStarted",inputMapping:{targetId:"event.sprintId",targetType:"event.type",description:"event.description",acceptanceCriteria:"event.acceptanceCriteria"}}]}}var C=class{constructor(e,t,i,r={}){this.eventBus=e;this.memory=t;this.agentCoordinator=i;this.config={...E,...r}}eventBus;memory;agentCoordinator;config;workflows=new Map;executions=new Map;actionRegistry={};eventSubscriptions=[];approvalGates=new Map;initialized=!1;async initialize(){this.initialized||(this.registerBuiltInWorkflows(),this.config.enableEventTriggers&&this.setupEventTriggers(),await this.loadPersistedWorkflows(),this.initialized=!0)}async dispose(){for(let e of this.executions.values())e.status==="running"&&await this.cancelWorkflow(e.executionId);for(let e of this.eventSubscriptions)e.unsubscribe();await this.persistWorkflows(),this.initialized=!1}registerWorkflow(e){try{let t=this.validateWorkflowDefinition(e);return t.success?(this.workflows.set(e.id,e),this.config.enableEventTriggers&&e.triggers&&this.registerWorkflowTriggers(e),m(void 0)):t}catch(t){return d(W(t))}}unregisterWorkflow(e){if(!this.workflows.has(e))return d(new Error(`Workflow not found: ${e}`));let t=Array.from(this.executions.values()).filter(i=>i.workflowId===e&&i.status==="running");return t.length>0?d(new Error(`Cannot unregister workflow with ${t.length} active execution(s)`)):(this.workflows.delete(e),m(void 0))}async executeWorkflow(e,t={},i){let r=this.workflows.get(e);if(!r)return d(new Error(`Workflow not found: ${e}`));if(Array.from(this.executions.values()).filter(g=>g.status==="running").length>=this.config.maxConcurrentWorkflows)return d(new Error(`Maximum concurrent workflows (${this.config.maxConcurrentWorkflows}) reached`));let o=D(),c=new Date,a={input:t,results:{},metadata:{executionId:o,workflowId:e,correlationId:i||o,startedAt:c}},l={executionId:o,workflowId:e,workflowName:r.name,status:"running",startedAt:c,progress:0,currentSteps:[],completedSteps:[],failedSteps:[],skippedSteps:[],context:a,stepResults:new Map};return this.executions.set(o,l),await this.publishWorkflowStarted(l,r),this.runWorkflow(r,l).catch(async g=>{l.status="failed",l.error=String(g),l.completedAt=new Date,l.duration=l.completedAt.getTime()-c.getTime(),await this.publishWorkflowFailed(l,"unknown",String(g))}),m(o)}getWorkflowStatus(e){return this.executions.get(e)}async cancelWorkflow(e){let t=this.executions.get(e);if(!t)return d(new Error(`Execution not found: ${e}`));if(t.status!=="running"&&t.status!=="paused")return d(new Error(`Cannot cancel workflow in status: ${t.status}`));t.status="cancelled",t.completedAt=new Date,t.duration=t.completedAt.getTime()-t.startedAt.getTime();for(let[i,r]of this.approvalGates.entries())i.startsWith(`${e}:`)&&(r.resolve({approved:!1,reason:"Workflow cancelled"}),this.approvalGates.delete(i));return await this.publishEvent(w.WorkflowCancelled,{executionId:e,workflowId:t.workflowId,workflowName:t.workflowName},t.context.metadata.correlationId),m(void 0)}async pauseWorkflow(e){let t=this.executions.get(e);return t?t.status!=="running"?d(new Error(`Cannot pause workflow in status: ${t.status}`)):(t.status="paused",m(void 0)):d(new Error(`Execution not found: ${e}`))}async resumeWorkflow(e){let t=this.executions.get(e);if(!t)return d(new Error(`Execution not found: ${e}`));if(t.status!=="paused")return d(new Error(`Cannot resume workflow in status: ${t.status}`));let i=this.workflows.get(t.workflowId);return i?(t.status="running",this.runWorkflow(i,t).catch(async r=>{t.status="failed",t.error=String(r)}),m(void 0)):d(new Error(`Workflow definition not found: ${t.workflowId}`))}listWorkflows(){return Array.from(this.workflows.values()).map(e=>({id:e.id,name:e.name,description:e.description,version:e.version,stepCount:e.steps.length,tags:e.tags,triggers:e.triggers?.map(t=>t.eventType)}))}getActiveExecutions(){return Array.from(this.executions.values()).filter(e=>e.status==="running"||e.status==="paused")}getWorkflow(e){return this.workflows.get(e)}approveStep(e,t){let i=`${e}:${t}`,r=this.approvalGates.get(i);return r?(r.resolve({approved:!0}),this.approvalGates.delete(i),!0):!1}rejectStep(e,t,i){let r=`${e}:${t}`,n=this.approvalGates.get(r);return n?(n.resolve({approved:!1,reason:i}),this.approvalGates.delete(r),!0):!1}isActionRegistered(e,t){return!!this.actionRegistry[e]?.[t]}getRegisteredActions(e){return Object.keys(this.actionRegistry[e]||{})}getDomainsWithActions(){return Object.keys(this.actionRegistry)}async spawnWorkflowAgent(e,t,i){return this.agentCoordinator.canSpawn()?this.agentCoordinator.spawn({name:`workflow-agent-${e.slice(0,8)}-${t}`,domain:i,type:"coordinator",capabilities:["workflow-execution",t],config:{workflowId:e,stepId:t}}):d(new Error("Agent limit reached"))}async stopWorkflowAgent(e){return this.agentCoordinator.stop(e)}getAvailableAgentCapacity(){return this.agentCoordinator.canSpawn()?this.config.maxConcurrentWorkflows-this.getActiveExecutions().length:0}registerAction(e,t,i){let r=["__proto__","constructor","prototype"];if(r.includes(e)||r.includes(t))throw new Error("Invalid domain or action name: contains dangerous prototype key");this.actionRegistry[e]||(this.actionRegistry[e]={}),this.actionRegistry[e][t]=i}async executeFromBehaviorTree(e){let t=new Date;try{let i=await e.tick(),r=new Date,n=r.getTime()-t.getTime();return{status:i==="SUCCESS"?"completed":i==="RUNNING"?"running":"failed",startedAt:t,completedAt:r,duration:n,treeStatus:i,treeName:e.name}}catch(i){let r=new Date,n=r.getTime()-t.getTime();return{status:"failed",startedAt:t,completedAt:r,duration:n,treeStatus:"FAILURE",treeName:e.name,error:b(i)}}}async runWorkflow(e,t){let i=e.timeout||this.config.defaultWorkflowTimeout,r=new Promise((n,o)=>{setTimeout(()=>o(new Error(`Workflow timeout after ${i}ms`)),i)});try{await Promise.race([this.executeSteps(e,t),r]),t.status==="running"&&(t.status="completed",t.completedAt=new Date,t.duration=t.completedAt.getTime()-t.startedAt.getTime(),t.progress=100,await this.publishWorkflowCompleted(t))}catch(n){if(t.status==="running"){t.status="failed",t.error=String(n),t.completedAt=new Date,t.duration=t.completedAt.getTime()-t.startedAt.getTime();let o=t.currentSteps[0]||"unknown";await this.publishWorkflowFailed(t,o,String(n))}}this.config.persistExecutions&&await this.persistExecution(t)}async executeSteps(e,t){let i=e.steps,r=new Set(t.completedSteps),n=new Set(t.skippedSteps),o=new Set(t.failedSteps),c=i.filter(a=>!r.has(a.id)&&!n.has(a.id)&&!o.has(a.id));for(;c.length>0&&t.status==="running";){let a=c.filter(u=>(u.dependsOn||[]).every(p=>r.has(p)||n.has(p)));if(a.length===0)break;let l=a.filter(u=>!u.dependsOn?.length),g=a.filter(u=>u.dependsOn?.length);if(l.length>0){t.currentSteps=l.map(f=>f.id);let u=await Promise.allSettled(l.map(f=>this.executeStep(f,t,e)));for(let f=0;f<l.length;f++){let p=l[f],y=u[f];if(y.status==="fulfilled"){let h=y.value;if(h.status==="completed")r.add(p.id),t.completedSteps.push(p.id);else if(h.status==="skipped")n.add(p.id),t.skippedSteps.push(p.id);else if(h.status==="failed"&&(o.add(p.id),t.failedSteps.push(p.id),!p.continueOnFailure)){t.status="failed",t.error=h.error;return}}else if(o.add(p.id),t.failedSteps.push(p.id),!p.continueOnFailure){t.status="failed",t.error=y.reason?.message||"Unknown error";return}let x=c.indexOf(p);x!==-1&&c.splice(x,1)}}for(let u of g){if(t.status!=="running")break;t.currentSteps=[u.id];let f=await this.executeStep(u,t,e);if(f.status==="completed")r.add(u.id),t.completedSteps.push(u.id);else if(f.status==="skipped")n.add(u.id),t.skippedSteps.push(u.id);else if(f.status==="failed"&&(o.add(u.id),t.failedSteps.push(u.id),!u.continueOnFailure)){t.status="failed",t.error=f.error;return}let p=c.indexOf(u);p!==-1&&c.splice(p,1)}let k=i.length,v=r.size+n.size+o.size;t.progress=Math.round(v/k*100)}t.currentSteps=[]}async executeStep(e,t,i){let r=new Date,n={stepId:e.id,status:"pending",startedAt:r};try{if(e.skipCondition&&this.evaluateCondition(e.skipCondition,t.context))return n.status="skipped",n.completedAt=new Date,n.duration=n.completedAt.getTime()-r.getTime(),t.stepResults.set(e.id,n),await this.publishStepSkipped(t,e),n;if(e.condition&&!this.evaluateCondition(e.condition,t.context))return n.status="skipped",n.completedAt=new Date,n.duration=n.completedAt.getTime()-r.getTime(),t.stepResults.set(e.id,n),await this.publishStepSkipped(t,e),n;n.status="running",await this.publishStepStarted(t,e);let o=this.buildStepInput(e,t.context),c,a=e.retry?.maxAttempts||1,l=e.retry?.backoffMs||1e3,g=e.retry?.backoffMultiplier||2;for(let k=1;k<=a;k++){n.retryCount=k-1;try{let v=e.timeout||this.config.defaultStepTimeout,u=await this.executeStepAction(e,o,t.context,v);if(this.mapStepOutput(e,u,t.context),e.approval){let f=await this.waitForApproval(e,t);if(!f.approved)return n.status="failed",n.error=f.reason||"Step rejected at approval gate",n.output=u,n.completedAt=new Date,n.duration=n.completedAt.getTime()-r.getTime(),t.stepResults.set(e.id,n),await this.publishStepFailed(t,e,n.error),n}return n.status="completed",n.output=u,n.completedAt=new Date,n.duration=n.completedAt.getTime()-r.getTime(),t.stepResults.set(e.id,n),await this.publishStepCompleted(t,e,n),n}catch(v){c=W(v),k<a&&(await this.delay(l),l*=g)}}return n.status="failed",n.error=c?.message||"Unknown error",n.completedAt=new Date,n.duration=n.completedAt.getTime()-r.getTime(),t.stepResults.set(e.id,n),e.rollback&&await this.executeRollback(e.rollback,t.context),await this.publishStepFailed(t,e,n.error),n}catch(o){return n.status="failed",n.error=b(o),n.completedAt=new Date,n.duration=n.completedAt.getTime()-r.getTime(),t.stepResults.set(e.id,n),await this.publishStepFailed(t,e,n.error),n}}async executeStepAction(e,t,i,r){let n=new Promise((a,l)=>{setTimeout(()=>l(new Error(`Step timeout after ${r}ms`)),r)}),o=R(e.domain,e.action);if(o){let a=await Promise.race([o.execute(t,i),n]);if(!a.success)throw a.error;return a.value}let c=this.actionRegistry[e.domain];if(c?.[e.action]){let a=await Promise.race([c[e.action](t,i),n]);if(!a.success)throw a.error;return a.value}throw new Error(`Action '${e.action}' not registered for domain '${e.domain}'. Register it using orchestrator.registerAction('${e.domain}', '${e.action}', handler)`)}async executeRollback(e,t){try{let i=this.actionRegistry[e.domain];if(!i?.[e.action]){console.warn(`Rollback action '${e.action}' not registered for domain '${e.domain}'. Skipping rollback.`);return}let r=await i[e.action](e.input||{},t);r.success||console.error(`Rollback failed for ${e.domain}.${e.action}:`,r.error)}catch(i){console.error(`Rollback failed for ${e.domain}.${e.action}:`,i)}}buildStepInput(e,t){let i={};if(e.inputMapping)for(let[r,n]of Object.entries(e.inputMapping)){let o=this.getValueByPath(t,n);o!==void 0&&(i[r]=o)}return i}mapStepOutput(e,t,i){if(i.results[e.id]=t,e.outputMapping&&typeof t=="object"&&t!==null)for(let[r,n]of Object.entries(e.outputMapping)){let o=this.getValueByPath(t,r);o!==void 0&&this.setValueByPath(i.results,n,o)}}getValueByPath(e,t){let i=t.split("."),r=e;for(let n of i){if(r==null)return;if(typeof r=="object")r=r[n];else return}return r}setValueByPath(e,t,i){let r=t.split("."),n=new Set(["__proto__","constructor","prototype"]);for(let a of r)if(n.has(a))throw new Error("Invalid path: contains dangerous prototype key");let o=e;for(let a=0;a<r.length-1;a++){let l=r[a];Object.hasOwn(o,l)||Object.defineProperty(o,l,{value:Object.create(null),writable:!0,enumerable:!0,configurable:!0}),o=o[l]}let c=r[r.length-1];Object.defineProperty(o,c,{value:i,writable:!0,enumerable:!0,configurable:!0})}evaluateCondition(e,t){let i=this.getValueByPath(t,e.path);switch(e.operator){case"eq":return i===e.value;case"neq":return i!==e.value;case"gt":return typeof i=="number"&&i>e.value;case"gte":return typeof i=="number"&&i>=e.value;case"lt":return typeof i=="number"&&i<e.value;case"lte":return typeof i=="number"&&i<=e.value;case"contains":return Array.isArray(i)?i.includes(e.value):typeof i=="string"?i.includes(String(e.value)):!1;case"exists":return i!=null;default:return!1}}async publishEvent(e,t,i){let r=I(e,"learning-optimization",t,i);await this.eventBus.publish(r)}async publishWorkflowStarted(e,t){await this.publishEvent(w.WorkflowStarted,{executionId:e.executionId,workflowId:e.workflowId,workflowName:e.workflowName,stepCount:t.steps.length},e.context.metadata.correlationId)}async publishWorkflowCompleted(e){await this.publishEvent(w.WorkflowCompleted,{executionId:e.executionId,workflowId:e.workflowId,workflowName:e.workflowName,duration:e.duration||0,completedSteps:e.completedSteps.length,skippedSteps:e.skippedSteps.length},e.context.metadata.correlationId)}async publishWorkflowFailed(e,t,i){await this.publishEvent(w.WorkflowFailed,{executionId:e.executionId,workflowId:e.workflowId,workflowName:e.workflowName,failedStep:t,error:i},e.context.metadata.correlationId)}async publishStepStarted(e,t){await this.publishEvent(w.StepStarted,{executionId:e.executionId,workflowId:e.workflowId,stepId:t.id,stepName:t.name,domain:t.domain},e.context.metadata.correlationId)}async publishStepCompleted(e,t,i){await this.publishEvent(w.StepCompleted,{executionId:e.executionId,workflowId:e.workflowId,stepId:t.id,stepName:t.name,domain:t.domain,duration:i.duration},e.context.metadata.correlationId)}async publishStepFailed(e,t,i){await this.publishEvent(w.StepFailed,{executionId:e.executionId,workflowId:e.workflowId,stepId:t.id,stepName:t.name,domain:t.domain,error:i},e.context.metadata.correlationId)}async publishStepSkipped(e,t){await this.publishEvent(w.StepSkipped,{executionId:e.executionId,workflowId:e.workflowId,stepId:t.id,stepName:t.name,domain:t.domain},e.context.metadata.correlationId)}validateWorkflowDefinition(e){if(!e.id)return d(new Error("Workflow ID is required"));if(!e.name)return d(new Error("Workflow name is required"));if(!e.steps||e.steps.length===0)return d(new Error("Workflow must have at least one step"));let t=new Set;for(let r of e.steps){if(!r.id)return d(new Error("Step ID is required"));if(t.has(r.id))return d(new Error(`Duplicate step ID: ${r.id}`));if(t.add(r.id),!r.domain)return d(new Error(`Step ${r.id} must have a domain`));if(!A.includes(r.domain))return d(new Error(`Invalid domain for step ${r.id}: ${r.domain}`));if(!r.action)return d(new Error(`Step ${r.id} must have an action`));if(r.dependsOn){for(let n of r.dependsOn)if(!e.steps.some(o=>o.id===n))return d(new Error(`Step ${r.id} depends on unknown step: ${n}`))}}let i=this.detectCircularDependencies(e.steps);return i?d(new Error(`Circular dependency detected: ${i}`)):m(void 0)}detectCircularDependencies(e){let t=new Set,i=new Set,r=(n,o)=>{if(i.has(n))return[...o,n].join(" -> ");if(t.has(n))return null;t.add(n),i.add(n);let c=e.find(a=>a.id===n);if(c?.dependsOn)for(let a of c.dependsOn){let l=r(a,[...o,n]);if(l)return l}return i.delete(n),null};for(let n of e){let o=r(n.id,[]);if(o)return o}return null}setupEventTriggers(){let e=this.eventBus.subscribe("*",async t=>{await this.handleEventForTriggers(t)});this.eventSubscriptions.push(e)}registerWorkflowTriggers(e){}async handleEventForTriggers(e){for(let t of this.workflows.values())if(t.triggers)for(let i of t.triggers){if(i.eventType!==e.type||i.sourceDomain&&i.sourceDomain!==e.source)continue;if(i.condition){let n={input:{event:e.payload},results:{},metadata:{executionId:"",workflowId:t.id,startedAt:new Date}};if(!this.evaluateCondition(i.condition,n))continue}let r={};if(i.inputMapping)for(let[n,o]of Object.entries(i.inputMapping)){let c=this.getValueByPath({event:e.payload},o);c!==void 0&&(r[n]=c)}else r.triggerEvent=e.payload;await this.executeWorkflow(t.id,r,e.correlationId)}}registerBuiltInWorkflows(){let e=M();for(let t of e)this.registerWorkflow(t)}async loadPersistedWorkflows(){try{let e=await this.memory.search("workflow:definition:*",100);for(let t of e){let i=await this.memory.get(t);i&&!this.workflows.has(i.id)&&this.workflows.set(i.id,i)}}catch(e){console.error("Failed to load persisted workflows:",e)}}async persistWorkflows(){try{for(let e of this.workflows.values())P.includes(e.id)||await this.memory.set(`workflow:definition:${e.id}`,e,{namespace:"coordination",persist:!0})}catch(e){console.error("Failed to persist workflows:",e)}}async persistExecution(e){try{let t={...e,stepResults:Object.fromEntries(e.stepResults)};await this.memory.set(`workflow:execution:${e.executionId}`,t,{namespace:"coordination",ttl:86400*7})}catch(t){console.error("Failed to persist execution:",t)}}async waitForApproval(e,t){let i=typeof e.approval=="object"?e.approval:{},r=i.autoApproveAfter??3e5,n=i.message??`Awaiting approval for step: ${e.name}`,o=t.stepResults.get(e.id);o&&(o.status="awaiting_approval"),await this.publishEvent(w.StepAwaitingApproval,{executionId:t.executionId,workflowId:t.workflowId,stepId:e.id,stepName:e.name,domain:e.domain,message:n,autoApproveAfter:r>0?r:void 0},t.context.metadata.correlationId);let c=`${t.executionId}:${e.id}`;return new Promise(a=>{let l={resolve:a};if(this.approvalGates.set(c,l),r>0){let g=setTimeout(()=>{this.approvalGates.has(c)&&(this.approvalGates.delete(c),a({approved:!0}))},r),k=l.resolve;l.resolve=v=>{clearTimeout(g),k(v)}}})}delay(e){return new Promise(t=>setTimeout(t,e))}};function de(s,e,t,i){return new C(s,e,t,i)}export{w as a,E as b,C as c,de as d};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{a as M}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.15");process.exit(0)}
|
|
2
|
+
import{a as M}from"./chunk-MO4Q5ZGE.js";import{f as y,o as T}from"./chunk-LLVS3UYZ.js";import{a as p,c as S}from"./chunk-JJDHD7SC.js";import{f as b}from"./chunk-MBDX4OHD.js";T();S();import*as c from"path";import*as d from"fs";var m=null,u=null,l=null;function R(o){l=o}async function P(){return m||u||(u=(async()=>{let o=y(),e=c.join(o,".agentic-qe");d.existsSync(e)||d.mkdirSync(e,{recursive:!0});let r=new M({sqlite:{path:c.join(e,"memory.db"),walMode:!0,poolSize:3,busyTimeout:5e3},enableFallback:!0,defaultNamespace:"mcp-tools"});return await r.initialize(),m=r,r})(),u)}function $(){if(l)try{l()}catch{}m&&(m.dispose().catch(()=>{}),m=null),u=null}async function D(o){return o?.memory?o.memory:P()}var C={info:(o,e)=>console.log(`[MCP-TOOL] ${o}`,e||""),warn:(o,e)=>console.warn(`[MCP-TOOL] \u26A0\uFE0F ${o}`,e||""),error:(o,e)=>console.error(`[MCP-TOOL] \u274C ${o}`,e||"")},h=class{logger=C;currentDataSource="real";setLogger(e){this.logger=e}markAsDemoData(e,r){this.currentDataSource=e.demoMode?"demo":"fallback",this.logger.warn(`${this.config.name} returning ${this.currentDataSource} data`,{reason:r,requestId:e.requestId,demoMode:e.demoMode})}markAsRealData(){this.currentDataSource="real"}isDemoMode(e){return e.demoMode===!0}validate(e){let r=[];if(typeof e!="object"||e===null)return{valid:!1,errors:["Parameters must be an object"]};let t=e,{properties:a,required:n}=this.config.schema;if(n)for(let i of n)i in t||r.push(`Missing required field: ${i}`);for(let[i,s]of Object.entries(t)){let g=a[i];if(!g)continue;let f=this.validateType(i,s,g);f&&r.push(f)}return{valid:r.length===0,errors:r}}validateType(e,r,t){if(r==null)return null;let a=Array.isArray(r)?"array":typeof r;if(t.type==="array"&&!Array.isArray(r))return`${e} must be an array`;if(t.type!=="array"&&a!==t.type)return`${e} must be of type ${t.type}, got ${a}`;if(t.enum&&!t.enum.includes(r))return`${e} must be one of: ${t.enum.join(", ")}`;if(t.type==="number"){let n=r;if(t.minimum!==void 0&&n<t.minimum)return`${e} must be >= ${t.minimum}`;if(t.maximum!==void 0&&n>t.maximum)return`${e} must be <= ${t.maximum}`}if(t.type==="string"){let n=r;if(t.minLength!==void 0&&n.length<t.minLength)return`${e} must be at least ${t.minLength} characters`;if(t.maxLength!==void 0&&n.length>t.maxLength)return`${e} must be at most ${t.maxLength} characters`}return null}async invoke(e,r={}){let t=Date.now(),a=b();this.currentDataSource="real";let n=this.validate(e);if(!n.valid)return{success:!1,error:`Validation failed: ${n.errors.join("; ")}`,metadata:this.createMetadata(t,a)};let i={requestId:a,startTime:t,streaming:r.streaming,onStream:r.onStream,abortSignal:r.abortSignal,demoMode:r.demoMode};try{let s=await this.execute(e,i);return{...s,metadata:{...s.metadata,...this.createMetadata(t,a)}}}catch(s){return{success:!1,error:p(s),metadata:this.createMetadata(t,a)}}}createMetadata(e,r){return{executionTime:Date.now()-e,timestamp:new Date().toISOString(),requestId:r,domain:this.config.domain,toolName:this.config.name,dataSource:this.currentDataSource}}emitStream(e,r){e.streaming&&e.onStream&&e.onStream(r)}isAborted(e){return e.abortSignal?.aborted??!1}get name(){return this.config.name}get description(){return this.config.description}get domain(){return this.config.domain}getSchema(){return this.config.schema}get timeout(){return this.config.timeout??6e4}get supportsStreaming(){return this.config.streaming??!1}resetInstanceCache(){}};export{R as a,P as b,$ as c,D as d,C as e,h as f};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.15");process.exit(0)}
|
|
2
2
|
import{existsSync as _,readdirSync as d,statSync as w}from"fs";import{join as i,extname as E}from"path";var T=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".pyw",".go",".rs",".java",".kt",".kts",".rb",".cs",".php",".swift",".c",".h",".cpp",".hpp",".cc",".scala"]),v=[".test.",".spec.","_test.","_spec."],b=new Set(["node_modules","dist","build","coverage",".git","__pycache__",".venv","venv",".tox",".mypy_cache","target",".gradle","vendor",".bundle",".next",".nuxt",".output"]);function O(s,p={}){let{maxDepth:f=6,includeTests:m=!1,testsOnly:x=!1,extraExtensions:S=[]}=p;if(!_(s))return[];let o=w(s);if(o.isFile())return[s];if(!o.isDirectory())return[];let y=new Set(S.map(t=>t.startsWith(".")?t:`.${t}`)),n=[];function r(t,c){if(c>f)return;let a;try{a=d(t,{withFileTypes:!0})}catch{return}for(let e of a)if(e.isDirectory()){if(b.has(e.name))continue;r(i(t,e.name),c+1)}else if(e.isFile()){let u=E(e.name).toLowerCase();if(!(T.has(u)||y.has(u))||e.name.endsWith(".d.ts"))continue;let l=v.some(h=>e.name.includes(h))||e.name.startsWith("test_");x?l&&n.push(i(t,e.name)):(m||!l)&&n.push(i(t,e.name))}}return r(s,0),n}export{T as a,O as b};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{a as o,e as l}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.15");process.exit(0)}
|
|
2
|
+
import{a as o,e as l}from"./chunk-2BBKAX7X.js";import{a,d as u}from"./chunk-MS6T4VCU.js";u();l();var c=class{store=new Map;vectors=new Map;cleanupInterval;async initialize(){this.cleanupInterval=setInterval(()=>this.cleanup(),o.CLEANUP_INTERVAL_MS),this.cleanupInterval.unref&&this.cleanupInterval.unref()}async dispose(){this.cleanupInterval&&clearInterval(this.cleanupInterval),this.store.clear(),this.vectors.clear()}async set(t,r,e){let s={value:r,namespace:e?.namespace??"default",createdAt:Date.now()};e?.ttl&&(s.expiresAt=Date.now()+e.ttl*o.TTL_MULTIPLIER_MS);let n=this.buildKey(t,e?.namespace);this.store.set(n,s)}async get(t,r){let e=this.buildKey(t,r),s=this.store.get(e);if(s){if(s.expiresAt&&Date.now()>s.expiresAt){this.store.delete(e);return}return s.value}}async delete(t,r){let e=this.buildKey(t,r);return this.store.delete(e)}async has(t,r){return await this.get(t,r)!==void 0}async search(t,r=o.DEFAULT_SEARCH_LIMIT){let e=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&"),s=new RegExp(e.replace(/\*/g,".*")),n=[];for(let i of this.store.keys())if(s.test(i)&&(n.push(i),n.length>=r))break;return n}async vectorSearch(t,r){let e=[];for(let[s,n]of this.vectors.entries()){let i=a(t,n.embedding);e.push({key:s,score:i,metadata:n.metadata})}return e.sort((s,n)=>n.score-s.score).slice(0,r)}async storeVector(t,r,e){this.vectors.set(t,{embedding:r,metadata:e})}buildKey(t,r){return r?`${r}:${t}`:t}cleanup(){let t=Date.now();for(let[r,e]of this.store.entries())e.expiresAt&&t>e.expiresAt&&this.store.delete(r)}getStats(){return{entries:this.store.size,vectors:this.vectors.size}}async clear(t){if(t){let r=`${t}:`;for(let e of this.store.keys())e.startsWith(r)&&this.store.delete(e)}else this.store.clear()}async count(t){let r=0,e=`${t}:`;for(let s of this.store.keys())if(s.startsWith(e)){let n=this.store.get(s);n&&(!n.expiresAt||Date.now()<=n.expiresAt)&&r++}return r}async hasCodeIntelligenceIndex(){return await this.count("code-intelligence:kg")>0}};export{c as a};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
var u={0:{tier:0,name:"Agent Booster",description:"Mechanical code transforms via Rust/WASM",useCases:["var-to-const conversion","add-types","remove-console statements","promise-to-async","cjs-to-esm","func-to-arrow"],typicalLatencyMs:1,relativeCost:0,exampleModels:["agent-booster-wasm","agent-booster-typescript"],requiresNetwork:!1,complexityRange:[0,10]},1:{tier:1,name:"Haiku",description:"Fast, cost-effective for simple tasks",useCases:["Simple bug fixes","Code formatting","Documentation updates","Basic refactoring","Test generation (simple)"],typicalLatencyMs:500,relativeCost:1,exampleModels:["claude-haiku-4-5-20251001","gpt-4o-mini","gemini-flash"],requiresNetwork:!0,complexityRange:[10,35]},2:{tier:2,name:"Sonnet",description:"Balanced capability for complex reasoning",useCases:["Feature implementation","Complex refactoring","Security analysis","Performance optimization","Test generation (complex)"],typicalLatencyMs:3e3,relativeCost:2,exampleModels:["claude-sonnet-4-6","gpt-4o","gemini-pro"],requiresNetwork:!0,complexityRange:[35,70]},3:{tier:3,name:"Sonnet Extended",description:"Extended context for multi-step workflows",useCases:["Multi-file refactoring","Workflow orchestration","Cross-domain coordination","Large codebase analysis"],typicalLatencyMs:7e3,relativeCost:3,exampleModels:["claude-sonnet-4-6"],requiresNetwork:!0,complexityRange:[60,85]},4:{tier:4,name:"Opus",description:"Maximum capability for critical decisions",useCases:["Architecture design","Security audits","Complex algorithm design","Critical bug analysis","System-wide refactoring"],typicalLatencyMs:5e3,relativeCost:4,exampleModels:["claude-opus-4-7","gpt-4-turbo"],requiresNetwork:!0,complexityRange:[75,100]}},d={enabled:!0,tierBudgets:{0:{tier:0,maxCostPerRequest:0,maxRequestsPerHour:1e4,maxRequestsPerDay:1e5,maxDailyCostUsd:0,enabled:!0},1:{tier:1,maxCostPerRequest:.01,maxRequestsPerHour:100,maxRequestsPerDay:1e3,maxDailyCostUsd:5,enabled:!0},2:{tier:2,maxCostPerRequest:.1,maxRequestsPerHour:50,maxRequestsPerDay:500,maxDailyCostUsd:20,enabled:!0},3:{tier:3,maxCostPerRequest:.5,maxRequestsPerHour:20,maxRequestsPerDay:100,maxDailyCostUsd:30,enabled:!0},4:{tier:4,maxCostPerRequest:2,maxRequestsPerHour:10,maxRequestsPerDay:50,maxDailyCostUsd:50,enabled:!0}},maxDailyCostUsd:100,warningThreshold:.8,onBudgetExceeded:"downgrade",onBudgetWarning:"warn",allowCriticalOverrides:!0},y={budgetConfig:d,enableAgentBooster:!0,agentBoosterThreshold:.7,enableAutoRouting:!0,complexityThresholds:{0:10,1:35,2:70,3:85,4:100},allowManualOverrides:!0,enableDecisionCache:!0,decisionCacheTtlMs:300*1e3,enableMetrics:!0,maxDecisionTimeMs:10,fallbackTier:2,tierModels:{0:"agent-booster",1:"claude-haiku-4-5-20251001",2:"claude-sonnet-4-6",3:"claude-sonnet-4-6",4:"claude-opus-4-7"}},r=class extends Error{constructor(e,t,l){super(e);this.code=t;this.cause=l;this.name="ModelRouterError"}},a=class extends r{constructor(e,t,l){super(e,"BUDGET_EXCEEDED");this.tier=t;this.usage=l;this.name="BudgetExceededError"}},i=class extends r{constructor(o,e){super(o,"COMPLEXITY_ANALYSIS_ERROR",e),this.name="ComplexityAnalysisError"}},s=class extends r{constructor(e,t){super(e,"ROUTING_TIMEOUT");this.timeoutMs=t;this.name="RoutingTimeoutError"}};export{u as a,d as b,y as c,r as d,a as e,i as f,s as g};
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.15");process.exit(0)}
|
|
2
|
+
var u={0:{tier:0,name:"Agent Booster",description:"Mechanical code transforms via Rust/WASM",useCases:["var-to-const conversion","add-types","remove-console statements","promise-to-async","cjs-to-esm","func-to-arrow"],typicalLatencyMs:1,relativeCost:0,exampleModels:["agent-booster-wasm","agent-booster-typescript"],requiresNetwork:!1,complexityRange:[0,10]},1:{tier:1,name:"Haiku",description:"Fast, cost-effective for simple tasks",useCases:["Simple bug fixes","Code formatting","Documentation updates","Basic refactoring","Test generation (simple)"],typicalLatencyMs:500,relativeCost:1,exampleModels:["claude-haiku-4-5-20251001","gpt-4o-mini","gemini-flash"],requiresNetwork:!0,complexityRange:[10,35]},2:{tier:2,name:"Sonnet",description:"Balanced capability for complex reasoning",useCases:["Feature implementation","Complex refactoring","Security analysis","Performance optimization","Test generation (complex)"],typicalLatencyMs:3e3,relativeCost:2,exampleModels:["claude-sonnet-4-6","gpt-4o","gemini-pro"],requiresNetwork:!0,complexityRange:[35,70]},3:{tier:3,name:"Sonnet Extended",description:"Extended context for multi-step workflows",useCases:["Multi-file refactoring","Workflow orchestration","Cross-domain coordination","Large codebase analysis"],typicalLatencyMs:7e3,relativeCost:3,exampleModels:["claude-sonnet-4-6"],requiresNetwork:!0,complexityRange:[60,85]},4:{tier:4,name:"Opus",description:"Maximum capability for critical decisions",useCases:["Architecture design","Security audits","Complex algorithm design","Critical bug analysis","System-wide refactoring"],typicalLatencyMs:5e3,relativeCost:4,exampleModels:["claude-opus-4-7","gpt-4-turbo"],requiresNetwork:!0,complexityRange:[75,100]}},d={enabled:!0,tierBudgets:{0:{tier:0,maxCostPerRequest:0,maxRequestsPerHour:1e4,maxRequestsPerDay:1e5,maxDailyCostUsd:0,enabled:!0},1:{tier:1,maxCostPerRequest:.01,maxRequestsPerHour:100,maxRequestsPerDay:1e3,maxDailyCostUsd:5,enabled:!0},2:{tier:2,maxCostPerRequest:.1,maxRequestsPerHour:50,maxRequestsPerDay:500,maxDailyCostUsd:20,enabled:!0},3:{tier:3,maxCostPerRequest:.5,maxRequestsPerHour:20,maxRequestsPerDay:100,maxDailyCostUsd:30,enabled:!0},4:{tier:4,maxCostPerRequest:2,maxRequestsPerHour:10,maxRequestsPerDay:50,maxDailyCostUsd:50,enabled:!0}},maxDailyCostUsd:100,warningThreshold:.8,onBudgetExceeded:"downgrade",onBudgetWarning:"warn",allowCriticalOverrides:!0},y={budgetConfig:d,enableAgentBooster:!0,agentBoosterThreshold:.7,enableAutoRouting:!0,complexityThresholds:{0:10,1:35,2:70,3:85,4:100},allowManualOverrides:!0,enableDecisionCache:!0,decisionCacheTtlMs:300*1e3,enableMetrics:!0,maxDecisionTimeMs:10,fallbackTier:2,tierModels:{0:"agent-booster",1:"claude-haiku-4-5-20251001",2:"claude-sonnet-4-6",3:"claude-sonnet-4-6",4:"claude-opus-4-7"}},r=class extends Error{constructor(e,t,l){super(e);this.code=t;this.cause=l;this.name="ModelRouterError"}code;cause},a=class extends r{constructor(e,t,l){super(e,"BUDGET_EXCEEDED");this.tier=t;this.usage=l;this.name="BudgetExceededError"}tier;usage},i=class extends r{constructor(o,e){super(o,"COMPLEXITY_ANALYSIS_ERROR",e),this.name="ComplexityAnalysisError"}},s=class extends r{constructor(e,t){super(e,"ROUTING_TIMEOUT");this.timeoutMs=t;this.name="RoutingTimeoutError"}timeoutMs};export{u as a,d as b,y as c,r as d,a as e,i as f,s as g};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.15");process.exit(0)}
|
|
2
2
|
import{readFileSync as O,existsSync as x,readdirSync as A}from"fs";import{join as y,basename as v}from"path";function m(r){let e=[];if(!r||typeof r!="object")return e.push("Overlay must be a non-null object"),e;let t=r;if((!t.agent||typeof t.agent!="string")&&e.push('Overlay must have a string "agent" field'),t.replace!==void 0)if(typeof t.replace!="object"||t.replace===null)e.push('"replace" must be an object');else{let n=t.replace;n.description!==void 0&&typeof n.description!="string"&&e.push('"replace.description" must be a string'),n.domains!==void 0&&!Array.isArray(n.domains)&&e.push('"replace.domains" must be an array'),n.complexity!==void 0&&typeof n.complexity!="string"&&e.push('"replace.complexity" must be a string')}if(t.append!==void 0)if(typeof t.append!="object"||t.append===null)e.push('"append" must be an object');else{let n=t.append;n.instructions!==void 0&&typeof n.instructions!="string"&&e.push('"append.instructions" must be a string'),n.capabilities!==void 0&&!Array.isArray(n.capabilities)&&e.push('"append.capabilities" must be an array'),n.tags!==void 0&&!Array.isArray(n.tags)&&e.push('"append.tags" must be an array')}if(t.config!==void 0)if(typeof t.config!="object"||t.config===null)e.push('"config" must be an object');else{let n=t.config;n.minimumFindings!==void 0&&typeof n.minimumFindings!="number"&&e.push('"config.minimumFindings" must be a number'),n.maxParallelAgents!==void 0&&typeof n.maxParallelAgents!="number"&&e.push('"config.maxParallelAgents" must be a number'),n.preferredFrameworks!==void 0&&!Array.isArray(n.preferredFrameworks)&&e.push('"config.preferredFrameworks" must be an array'),n.needsContext!==void 0&&typeof n.needsContext!="boolean"&&e.push('"config.needsContext" must be a boolean')}return e}var w=".claude/agent-overrides";function $(r){let e={},t=r.split(`
|
|
3
3
|
`),n=null,i=null,s=null,a=null;for(let o of t){let l=o.replace(/\r$/,"");if(l.trim().startsWith("#")||l.trim()==="")continue;let u=l.length-l.trimStart().length,g=l.trim();if(g.startsWith("- ")){let c=g.slice(2).trim().replace(/^["']|["']$/g,"");s&&s.push(c);continue}if(s&&a){if(i&&n){let c=e[n]||{};c[a]=s,e[n]=c}else if(n){let c=e[n]||{};c[a]=s,e[n]=c}s=null,a=null}let f=g.match(/^(\w[\w.-]*)\s*:\s*(.*)$/);if(!f)continue;let[,p,b]=f,d=b.trim().replace(/^["']|["']$/g,"");if(u===0)d===""||d===void 0?(n=p,i=null,e[p]||(e[p]={})):(e[p]=h(d),n=null,i=null);else if(u<=4&&n)if(d===""||d===void 0)i=p,s=[],a=p;else{let c=e[n]||{};c[p]=h(d),e[n]=c}}if(s&&a&&n){let o=e[n]||{};o[a]=s,e[n]=o}return e}function h(r){if(r==="true")return!0;if(r==="false")return!1;if(r==="null")return null;let e=Number(r);return!isNaN(e)&&r!==""?e:r}function N(r){let e=y(r,w),t={overlays:[],warnings:[],errors:[]};if(!x(e))return t;let n;try{n=A(e).filter(i=>(i.endsWith(".yaml")||i.endsWith(".yml"))&&!i.startsWith("_"))}catch(i){return t.errors.push(`Failed to read overrides directory: ${i.message}`),t}for(let i of n){let s=y(e,i);try{let a=O(s,"utf-8"),o=$(a);if(!o.agent){let u=v(i).replace(/\.(override|customize)\.(yaml|yml)$/,"");o.agent=u}let l=m(o);if(l.length>0){t.warnings.push(`Overlay ${i} has validation issues: ${l.join("; ")}. Loading without overlay.`);continue}t.overlays.push(o)}catch(a){t.warnings.push(`Failed to parse overlay ${i}: ${a.message}. Agent loads without overlay.`)}}return t}function E(r,e){let t=r,n={agentName:e.agent,overlayFile:`${e.agent}.override.yaml`,replacedFields:[],appendedFields:[],configOverrides:[]};if(e.replace){if(e.replace.description){let i=/^(description:\s*).+$/m;i.test(t)&&(t=t.replace(i,`$1${e.replace.description}`),n.replacedFields.push("description"))}if(e.replace.domains){let i=/^(domain:\s*).+$/m;i.test(t)&&(t=t.replace(i,`$1${e.replace.domains.join(", ")}`),n.replacedFields.push("domains"))}if(e.replace.complexity){let i=/^(complexity:\s*).+$/m;i.test(t)&&(t=t.replace(i,`$1${e.replace.complexity}`),n.replacedFields.push("complexity"))}}if(e.append){if(e.append.instructions&&(t+=`
|
|
4
4
|
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.15");process.exit(0)}
|
|
2
|
+
import{a as f}from"./chunk-FEVTMHO6.js";import{c as p}from"./chunk-XALB3KRR.js";import{a as l,d as b}from"./chunk-D3ZUSXFY.js";import{a as d,c as g}from"./chunk-IPVKVPAF.js";f();g();b();var v={dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine",namespace:"coverage-hnsw",maxElements:1e5},S=p.create("coverage-analysis/hnsw-index"),u=class{constructor(e,t={}){this.memory=e;this.config={...v,...t},this.stats={vectorCount:0,searchOperations:0,insertOperations:0}}memory;config;stats;searchLatencies=[];backendType="ruvector-gnn";adapter=null;initialized=!1;metadataStore=new Map;async initialize(){if(this.initialized)return;let e=this.config.metric==="cosine"?"cosine":"euclidean",t=`coverage-${this.config.namespace}`;d.close(t),this.adapter=d.create(t,{dimensions:this.config.dimensions,M:this.config.M,efConstruction:this.config.efConstruction,efSearch:this.config.efSearch,metric:e}),S.info(`HnswAdapter initialized: dimension=${this.config.dimensions}, metric=${this.config.metric}, M=${this.config.M} (unified backend via ADR-071)`),this.initialized=!0}isNativeAvailable(){return this.initialized&&this.adapter!==null}getBackendType(){return this.backendType}isRuvectorAvailable(){return this.initialized&&this.adapter!==null&&this.adapter.isRuvectorAvailable()}async insert(e,t,a){this.initialized||await this.initialize(),t=this.validateVector(t),this.adapter.addByStringId(e,t),a&&this.metadataStore.set(e,a),this.stats.insertOperations++,this.stats.vectorCount=this.adapter.size()}async search(e,t){this.initialized||await this.initialize(),e=this.validateVector(e);let a=performance.now(),n=[];this.adapter.size()>0&&(n=this.adapter.searchByArray(e,t).map(({id:i,score:o})=>({key:i,score:o,distance:1-o,metadata:this.metadataStore.get(i)})));let s=performance.now()-a;return this.recordSearchLatency(s),this.stats.searchOperations++,n}async batchInsert(e){this.initialized||await this.initialize();let t=100;for(let a=0;a<e.length;a+=t){let n=e.slice(a,a+t);await Promise.all(n.map(r=>this.insert(r.key,r.vector,r.metadata)))}}async delete(e){if(!this.adapter)return!1;let t=this.adapter.removeByStringId(e);if(t){this.metadataStore.delete(e);let a=this.buildKey(e);await this.memory.delete(a),this.stats.vectorCount=this.adapter.size()}return t}async getStats(){return{nativeHNSW:this.initialized&&this.adapter!==null,backendType:this.backendType,vectorCount:this.stats.vectorCount,indexSizeBytes:this.stats.vectorCount*this.config.dimensions*4,avgSearchLatencyMs:this.calculateAvgLatency(),p95SearchLatencyMs:this.calculatePercentileLatency(95),p99SearchLatencyMs:this.calculatePercentileLatency(99),searchOperations:this.stats.searchOperations,insertOperations:this.stats.insertOperations}}async clear(){this.metadataStore.clear(),this.adapter&&this.adapter.clear(),this.stats.vectorCount=0,this.searchLatencies=[]}validateVector(e){if(e.length!==this.config.dimensions)return this.resizeVector(e,this.config.dimensions);for(let t=0;t<e.length;t++)if(!Number.isFinite(e[t]))throw new Error(`Invalid vector value at index ${t}: ${e[t]}`);return e}resizeVector(e,t){if(e.length===t)return e;if(e.length>t){let n=new Array(t).fill(0),r=e.length/t;for(let s=0;s<t;s++){let h=Math.floor(s*r),i=Math.floor((s+1)*r),o=0;for(let m=h;m<i;m++)o+=e[m];n[s]=o/(i-h)}return n}let a=new Array(t).fill(0);for(let n=0;n<e.length;n++)a[n]=e[n];return a}buildKey(e){return`${this.config.namespace}:${e}`}recordSearchLatency(e){this.searchLatencies.push(e);let t=1e3;this.searchLatencies.length>t&&(this.searchLatencies=this.searchLatencies.slice(-t))}calculateAvgLatency(){return this.searchLatencies.length===0?0:this.searchLatencies.reduce((t,a)=>t+a,0)/this.searchLatencies.length}calculatePercentileLatency(e){if(this.searchLatencies.length===0)return 0;let t=[...this.searchLatencies].sort((n,r)=>n-r),a=Math.ceil(e/100*t.length)-1;return t[Math.max(0,a)]}setEfSearch(e){this.config.efSearch=e}};function C(c,e){return new u(c,e)}async function H(c,e=1e4,t=1e3){let n=performance.now();for(let i=0;i<e;i++){let o=Array.from({length:384},()=>l());await c.insert(`bench-${i}`,o)}let r=performance.now()-n,s=performance.now();for(let i=0;i<t;i++){let o=Array.from({length:384},()=>l());await c.search(o,10)}let h=performance.now()-s;return{insertTimeMs:r,searchTimeMs:h,avgSearchLatencyMs:h/t,isNative:c.isNativeAvailable(),backendType:c.getBackendType()}}export{v as a,u as b,C as c,H as d};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.15");process.exit(0)}
|
|
2
2
|
var h=Object.create;var e=Object.defineProperty;var i=Object.getOwnPropertyDescriptor;var j=Object.getOwnPropertyNames;var k=Object.getPrototypeOf,l=Object.prototype.hasOwnProperty;var m=(a=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(a,{get:(b,c)=>(typeof require<"u"?require:b)[c]}):a)(function(a){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+a+'" is not supported')}),n=a=>b=>{var c=a[b];if(c)return c();throw new Error("Module not found in bundle: "+b)};var o=(a,b)=>()=>(a&&(b=a(a=0)),b);var p=(a,b)=>()=>(b||a((b={exports:{}}).exports,b),b.exports),q=(a,b)=>{for(var c in b)e(a,c,{get:b[c],enumerable:!0})},g=(a,b,c,f)=>{if(b&&typeof b=="object"||typeof b=="function")for(let d of j(b))!l.call(a,d)&&d!==c&&e(a,d,{get:()=>b[d],enumerable:!(f=i(b,d))||f.enumerable});return a};var r=(a,b,c)=>(c=a!=null?h(k(a)):{},g(b||!a||!a.__esModule?e(c,"default",{value:a,enumerable:!0}):c,a)),s=a=>g(e({},"__esModule",{value:!0}),a);export{m as a,n as b,o as c,p as d,q as e,r as f,s as g};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{h as s,k as o,m as c,o as m}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.15");process.exit(0)}
|
|
2
|
+
import{h as s,k as o,m as c,o as m}from"./chunk-LLVS3UYZ.js";import{a,c as d}from"./chunk-JJDHD7SC.js";import{a as r,e as l}from"./chunk-2BBKAX7X.js";d();m();l();var u={dbPath:s.dbPath,walMode:!0,mmapSize:r.MMAP_SIZE_BYTES,cacheSize:r.CACHE_SIZE_KB,busyTimeout:r.BUSY_TIMEOUT_MS},n=class e{static instance=null;static instancePromise=null;unifiedMemory=null;config;initialized=!1;initPromise=null;constructor(i){this.config={...u,...i}}static getInstance(i){return e.instance||(e.instance=new e(i)),e.instance}static async getInstanceAsync(i){return e.instance?.initialized?e.instance:(e.instancePromise||(e.instancePromise=(async()=>{let t=e.getInstance(i);return await t.initialize(),t})()),e.instancePromise)}static resetInstance(){e.instance&&(e.instance.close(),e.instance=null),e.instancePromise=null,c()}async initialize(){if(!this.initialized)return this.initPromise||(this.initPromise=this._doInitialize()),this.initPromise}async _doInitialize(){if(!this.initialized)try{let i={dbPath:this.config.dbPath,walMode:this.config.walMode,busyTimeout:this.config.busyTimeout,mmapSize:this.config.mmapSize,cacheSize:this.config.cacheSize};this.unifiedMemory=o(i),await this.unifiedMemory.initialize(),this.initialized=!0,console.log(`[UnifiedPersistence] Initialized via UnifiedMemoryManager: ${this.config.dbPath}`)}catch(i){throw this.initPromise=null,new Error(`Failed to initialize UnifiedPersistenceManager: ${a(i)}`)}}getDatabase(){if(!this.unifiedMemory||!this.initialized)throw new Error("UnifiedPersistenceManager not initialized");return this.unifiedMemory.getDatabase()}isInitialized(){return this.initialized}getDbPath(){return this.config.dbPath}prepare(i,t){if(!this.unifiedMemory)throw new Error("Database not initialized");return this.unifiedMemory.prepare(i,t)}transaction(i){if(!this.unifiedMemory)throw new Error("Database not initialized");return this.unifiedMemory.transaction(i)}getStats(){if(!this.unifiedMemory)throw new Error("Database not initialized");let i=this.unifiedMemory.getStats();return{tables:i.tables,fileSize:i.fileSize,walSize:i.walSize}}vacuum(){this.getDatabase().exec("VACUUM")}checkpoint(){this.getDatabase().pragma("wal_checkpoint(TRUNCATE)")}close(){this.initialized=!1,console.log("[UnifiedPersistence] Facade closed")}};function g(e){return n.getInstance(e)}async function U(e){let i=g(e);return await i.initialize(),i}function z(){n.resetInstance()}var f=!1;function h(){if(f)return;f=!0;let e=()=>{try{let i=n.instance;i&&i.close()}catch(i){console.debug("[UnifiedPersistence] Cleanup error:",i instanceof Error?i.message:i)}};process.on("beforeExit",e),process.on("SIGINT",()=>{e(),process.exit(0)}),process.on("SIGTERM",()=>{e(),process.exit(0)})}h();export{u as a,n as b,g as c,U as d,z as e};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{e as a}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.15");process.exit(0)}
|
|
2
|
+
import{e as a}from"./chunk-OMTYOIOS.js";import{b as w,d as y}from"./chunk-2XW36KDQ.js";import{a as f,c as P}from"./chunk-JJDHD7SC.js";import{randomUUID as v}from"crypto";import*as i from"fs";import*as n from"path";import*as c from"os";y();P();var k=".aqe",b="schedules.json",F="1.0.0",g=5e3,x=50,p=10*1024*1024,d=class{schedulesPath;debug;lockFile;initialized=!1;constructor(e={}){e.schedulesPath&&this.validateSchedulesPath(e.schedulesPath),this.schedulesPath=e.schedulesPath??this.getDefaultSchedulesPath(),this.lockFile=`${this.schedulesPath}.lock`,this.debug=e.debug??!1}validateSchedulesPath(e){let s=c.homedir(),t=n.resolve(e),r=n.resolve(s);if(t.startsWith(r+n.sep)||t===r)return;let l=process.cwd(),h=n.resolve(l);if(t.startsWith(h+n.sep)||t===h)return;let u=c.tmpdir(),S=n.resolve(u);if(!(t.startsWith(S+n.sep)||t===S))throw new Error(`Security: Custom schedulesPath must be within home directory (${s}), current working directory (${l}), or temp directory (${u}). Provided path: ${e}`)}getDefaultSchedulesPath(){let e=c.homedir();return n.join(e,k,b)}async initialize(){if(this.initialized)return;let e=n.dirname(this.schedulesPath);i.existsSync(e)||(i.mkdirSync(e,{recursive:!0}),this.log(`Created directory: ${e}`)),this.initialized=!0}async loadSchedules(){if(await this.initialize(),!i.existsSync(this.schedulesPath))return this.log("Schedules file does not exist, returning empty array"),[];try{let e=i.readFileSync(this.schedulesPath,"utf-8"),s=this.parseSchedulesFile(e);return this.log(`Loaded ${s.schedules.length} schedules`),s.schedules}catch(e){return await this.handleCorruptFile(e),[]}}async saveSchedule(e){await this.initialize(),await this.withFileLock(async()=>{let s=await this.loadSchedulesUnsafe(),t=s.findIndex(r=>r.id===e.id);t>=0?(s[t]=e,this.log(`Updated schedule: ${e.id}`)):(s.push(e),this.log(`Added schedule: ${e.id}`)),await this.writeSchedules(s)})}async removeSchedule(e){await this.initialize(),await this.withFileLock(async()=>{let s=await this.loadSchedulesUnsafe(),t=s.filter(r=>r.id!==e);if(t.length===s.length){this.log(`Schedule not found: ${e}`);return}await this.writeSchedules(t),this.log(`Removed schedule: ${e}`)})}async getSchedules(){return this.loadSchedules()}async getSchedule(e){return(await this.loadSchedules()).find(t=>t.id===e)}async getDueSchedules(){let e=await this.loadSchedules(),s=new Date;return e.filter(t=>t.enabled?new Date(t.nextRun)<=s:!1)}async markExecuted(e){await this.initialize(),await this.withFileLock(async()=>{let s=await this.loadSchedulesUnsafe(),t=s.find(l=>l.id===e);if(!t)throw new Error(`Schedule not found: ${e}`);let r=new Date;t.lastRun=r.toISOString(),t.nextRun=a(t.schedule,r).toISOString(),await this.writeSchedules(s),this.log(`Marked executed: ${e}, next run: ${t.nextRun}`)})}async setEnabled(e,s){await this.initialize(),await this.withFileLock(async()=>{let t=await this.loadSchedulesUnsafe(),r=t.find(l=>l.id===e);if(!r)throw new Error(`Schedule not found: ${e}`);r.enabled=s,s&&(r.nextRun=a(r.schedule,new Date).toISOString()),await this.writeSchedules(t),this.log(`Set enabled=${s}: ${e}`)})}async getEnabledSchedules(){return(await this.loadSchedules()).filter(s=>s.enabled)}async getSchedulesByWorkflow(e){return(await this.loadSchedules()).filter(t=>t.workflowId===e)}async clearAll(){await this.initialize(),await this.withFileLock(async()=>{await this.writeSchedules([]),this.log("Cleared all schedules")})}async getStats(){let e=await this.loadSchedules(),s=new Date;return{total:e.length,enabled:e.filter(t=>t.enabled).length,disabled:e.filter(t=>!t.enabled).length,due:e.filter(t=>t.enabled&&new Date(t.nextRun)<=s).length}}async loadSchedulesUnsafe(){if(!i.existsSync(this.schedulesPath))return[];try{let e=i.readFileSync(this.schedulesPath,"utf-8");return this.parseSchedulesFile(e).schedules}catch{return[]}}parseSchedulesFile(e){let s=Buffer.byteLength(e,"utf-8");if(s>p)throw new Error(`Schedules file exceeds maximum allowed size (${p/(1024*1024)}MB). File is ${(s/(1024*1024)).toFixed(2)}MB.`);let t=w(e);if(!t.schedules||!Array.isArray(t.schedules))throw new Error("Invalid schedules file: missing schedules array");for(let r of t.schedules)if(!r.id||!r.workflowId||!r.schedule)throw new Error("Invalid schedule entry: missing required fields");return t}async writeSchedules(e){let s={version:F,updatedAt:new Date().toISOString(),schedules:e},t=JSON.stringify(s,null,2);i.writeFileSync(this.schedulesPath,t,"utf-8"),this.log(`Wrote ${e.length} schedules to disk`)}async handleCorruptFile(e){let s=f(e);this.log(`Corrupt schedules file detected: ${s}`);let t=`${this.schedulesPath}.corrupt.${Date.now()}`;try{i.existsSync(this.schedulesPath)&&(i.copyFileSync(this.schedulesPath,t),this.log(`Backed up corrupt file to: ${t}`))}catch(r){this.log(`Failed to backup corrupt file: ${r}`)}try{i.existsSync(this.schedulesPath)&&(i.unlinkSync(this.schedulesPath),this.log("Removed corrupt schedules file"))}catch(r){this.log(`Failed to remove corrupt file: ${r}`)}}async withFileLock(e){await this.acquireLock();try{return await e()}finally{this.releaseLock()}}async acquireLock(){let e=Date.now();for(;i.existsSync(this.lockFile);){try{let s=i.statSync(this.lockFile);if(Date.now()-s.mtimeMs>g){i.unlinkSync(this.lockFile),this.log("Removed stale lock file");break}}catch{break}if(Date.now()-e>g)throw new Error("Timeout waiting for scheduler lock");await this.sleep(x)}try{i.writeFileSync(this.lockFile,`${process.pid}:${Date.now()}`,{flag:"wx"})}catch(s){if(s.code==="EEXIST")return this.acquireLock();throw s}}releaseLock(){try{i.existsSync(this.lockFile)&&i.unlinkSync(this.lockFile)}catch(e){console.debug("[PersistentScheduler] Lock release error:",e instanceof Error?e.message:e)}}sleep(e){return new Promise(s=>setTimeout(s,e))}log(e){this.debug&&console.log(`[PersistentScheduler] ${e}`)}};function E(o={}){return new d(o)}function m(){let o=Date.now().toString(36),e=v().slice(0,8);return`sched-${o}-${e}`}function $(o){let e=new Date;return{id:m(),workflowId:o.workflowId,pipelinePath:o.pipelinePath,schedule:o.schedule,scheduleDescription:o.scheduleDescription,nextRun:a(o.schedule,e).toISOString(),enabled:o.enabled??!0,createdAt:e.toISOString()}}export{d as a,E as b,m as c,$ as d};
|