agentic-qe 3.9.0 → 3.9.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude/skills/skills-manifest.json +1 -1
- package/CHANGELOG.md +43 -0
- package/dist/audit/witness-chain.d.ts +1 -1
- package/dist/cli/bundle.js +8 -8
- package/dist/cli/chunks/adapter-53WBPKXU.js +2 -0
- package/dist/cli/chunks/{agent-booster-wasm-PQYB7VRU.js → agent-booster-wasm-AKAOHSCX.js} +2 -2
- package/dist/cli/chunks/{agent-handler-QDAB5NQS.js → agent-handler-MTGPOUVP.js} +2 -2
- package/dist/cli/chunks/agent-memory-branch-UFPKWUFK.js +2 -0
- package/dist/cli/chunks/aqe-learning-engine-MV7NGY24.js +2 -0
- package/dist/cli/chunks/{audit-S7JUYYVP.js → audit-VBEZHNHO.js} +2 -2
- package/dist/cli/chunks/base-DZVGMQN2.js +2 -0
- package/dist/cli/chunks/better-sqlite3-IRPHIXRU.js +2 -0
- package/dist/cli/chunks/brain-handler-7EO3FFRZ.js +68 -0
- package/dist/cli/chunks/{branch-enumerator-XK4V5W7L.js → branch-enumerator-MZRGP35N.js} +2 -2
- package/dist/cli/chunks/{browser-PALA5PL3.js → browser-VSIWQE7J.js} +2 -2
- package/dist/cli/chunks/browser-workflow-3J5YNMEI.js +2 -0
- package/dist/cli/chunks/chunk-25LFUL2K.js +79 -0
- package/dist/cli/chunks/{chunk-LHJQD2VU.js → chunk-2EC5Z2J4.js} +68 -68
- package/dist/cli/chunks/{chunk-4YOMLWEK.js → chunk-2VVV73PW.js} +1 -1
- package/dist/cli/chunks/{chunk-BPWXXEH2.js → chunk-2WBCYSUN.js} +128 -128
- package/dist/cli/chunks/{chunk-X3KI6JOY.js → chunk-2Z2TFEOL.js} +2 -2
- package/dist/cli/chunks/chunk-34U7JDCN.js +2 -0
- package/dist/cli/chunks/{chunk-24FKIJNC.js → chunk-3GZKAORV.js} +2 -2
- package/dist/cli/chunks/{chunk-72WOAVK6.js → chunk-4D2ZG2QO.js} +1 -1
- package/dist/cli/chunks/{chunk-B36CDR4U.js → chunk-4DAOZQ3V.js} +2 -2
- package/dist/cli/chunks/{chunk-CL6POIX4.js → chunk-4FMHBBG5.js} +1 -1
- package/dist/cli/chunks/{chunk-BXAXGEFC.js → chunk-4FT3PND7.js} +5 -5
- package/dist/cli/chunks/{chunk-IGJPMN4I.js → chunk-4LA7IW3V.js} +1 -1
- package/dist/cli/chunks/{chunk-JRYGQO2W.js → chunk-4PKXIBX2.js} +1 -1
- package/dist/cli/chunks/{chunk-YPFOCNOE.js → chunk-4UH25U4O.js} +1 -1
- package/dist/cli/chunks/{chunk-U5RN7YQW.js → chunk-4Z27TRQF.js} +2 -2
- package/dist/cli/chunks/{chunk-YW2THB5Q.js → chunk-563PJBDM.js} +2 -2
- package/dist/cli/chunks/{chunk-BDIEMZ22.js → chunk-56IWS2KY.js} +2 -2
- package/dist/cli/chunks/chunk-5AUKULWO.js +2 -0
- package/dist/cli/chunks/{chunk-VSVXUTJN.js → chunk-5L6AU3QK.js} +2 -2
- package/dist/cli/chunks/{chunk-RTGGL7D7.js → chunk-5RL66XSH.js} +2 -2
- package/dist/cli/chunks/{chunk-YANUP2RO.js → chunk-65M7C6SH.js} +1 -1
- package/dist/cli/chunks/{chunk-ESVQ6MEB.js → chunk-6SOJVEU7.js} +2 -2
- package/dist/cli/chunks/{chunk-UFUVUO3J.js → chunk-727BDQ3K.js} +2 -2
- package/dist/cli/chunks/{chunk-TLHP5EII.js → chunk-7NOIIC7G.js} +1 -1
- package/dist/cli/chunks/{chunk-N4TL73TH.js → chunk-7SLN2JGP.js} +8 -8
- package/dist/cli/chunks/{chunk-NZ2VCPN4.js → chunk-AA33R5U4.js} +2 -2
- package/dist/cli/chunks/{chunk-Y7BHKZFJ.js → chunk-AKSJQ6B3.js} +2 -2
- package/dist/cli/chunks/{chunk-3ZOONQG6.js → chunk-BIVIPF4O.js} +1 -1
- package/dist/cli/chunks/{chunk-VOS4NQSF.js → chunk-BKCTNRC5.js} +2 -2
- package/dist/cli/chunks/{chunk-B6LLWYQ6.js → chunk-BOH22AKC.js} +2 -2
- package/dist/cli/chunks/{chunk-OI5NGQO2.js → chunk-BY47GV4T.js} +2 -2
- package/dist/cli/chunks/chunk-CCYMJKWX.js +2 -0
- package/dist/cli/chunks/chunk-CL3K5EJK.js +2 -0
- package/dist/cli/chunks/{chunk-GPQ57KA4.js → chunk-CQBSGYRA.js} +2 -2
- package/dist/cli/chunks/{chunk-MZOFWJTM.js → chunk-CQP7ZFME.js} +2 -2
- package/dist/cli/chunks/chunk-DBE34QES.js +2 -0
- package/dist/cli/chunks/chunk-DHE66JRR.js +12 -0
- package/dist/cli/chunks/{chunk-2BZFNEN2.js → chunk-DNLMZTE2.js} +1 -1
- package/dist/cli/chunks/{chunk-XLRQYLWW.js → chunk-DSE57A5N.js} +1 -1
- package/dist/cli/chunks/{chunk-SUSEVMZT.js → chunk-E25S5E2D.js} +1 -1
- package/dist/cli/chunks/{chunk-FEKY7T6Q.js → chunk-FAXVVLPL.js} +2 -2
- package/dist/cli/chunks/chunk-FRJLP7IB.js +2 -0
- package/dist/cli/chunks/{chunk-CS2KS7LP.js → chunk-FUIHWBVF.js} +1 -1
- package/dist/cli/chunks/{chunk-LNQIY6BP.js → chunk-GCMVJS5X.js} +2 -2
- package/dist/cli/chunks/{chunk-XT2V2322.js → chunk-GITD7SRQ.js} +2 -2
- package/dist/cli/chunks/{chunk-JJO7Y4H3.js → chunk-GK72GUHA.js} +3 -3
- package/dist/cli/chunks/{chunk-6EOS7KX2.js → chunk-GPLERTZU.js} +2 -2
- package/dist/cli/chunks/{chunk-2E5NQNSU.js → chunk-HW4ISY5B.js} +11 -11
- package/dist/cli/chunks/{chunk-HRO6OZQD.js → chunk-ICDXWIFZ.js} +1 -1
- package/dist/cli/chunks/{chunk-3NZLZHJI.js → chunk-J4BS6IWE.js} +1 -1
- package/dist/cli/chunks/{chunk-4VUPRTVX.js → chunk-JOVINE23.js} +2 -2
- package/dist/cli/chunks/chunk-JV7LX6OT.js +95 -0
- package/dist/cli/chunks/{chunk-6SVX4DJC.js → chunk-KBA7FBK3.js} +3 -3
- package/dist/cli/chunks/chunk-KDDZYXP4.js +2 -0
- package/dist/cli/chunks/{chunk-GAOJV3OX.js → chunk-KNVAAVHH.js} +2 -2
- package/dist/cli/chunks/{chunk-CWFB6BSA.js → chunk-KQTJ2YLI.js} +4 -4
- package/dist/cli/chunks/{chunk-FGA7VIFR.js → chunk-KTYUCZEM.js} +3 -3
- package/dist/cli/chunks/{chunk-RU5WAHB7.js → chunk-KZTO5EVM.js} +2 -2
- package/dist/cli/chunks/{chunk-IFNIIK34.js → chunk-KZUJBZ7B.js} +3 -3
- package/dist/cli/chunks/{chunk-GKNNSCLC.js → chunk-L5WZUPZF.js} +2 -2
- package/dist/cli/chunks/{chunk-MDUHYUHF.js → chunk-L5YEPSDU.js} +2 -2
- package/dist/cli/chunks/chunk-LCAA6H4J.js +2 -0
- package/dist/cli/chunks/{chunk-XRE2HCWG.js → chunk-LMMEUVE5.js} +1 -1
- package/dist/cli/chunks/{chunk-7VDBAVTY.js → chunk-MN742FIH.js} +2 -2
- package/dist/cli/chunks/chunk-MY4LMIG7.js +180 -0
- package/dist/cli/chunks/{chunk-WGMPEW2T.js → chunk-N3F3CX4V.js} +2 -2
- package/dist/cli/chunks/{chunk-YVA65UZL.js → chunk-NJY7ZA77.js} +1 -1
- package/dist/cli/chunks/{chunk-3IHG3WOY.js → chunk-NM6TIEJ3.js} +3 -3
- package/dist/cli/chunks/{chunk-KP5NUODU.js → chunk-NRCKGXJJ.js} +1 -1
- package/dist/cli/chunks/{chunk-3ADGXLTM.js → chunk-PFNFC43Q.js} +1 -1
- package/dist/cli/chunks/{chunk-4VBTXZRM.js → chunk-PJFLO37I.js} +2 -2
- package/dist/cli/chunks/{chunk-XIBDETCS.js → chunk-PNL5G6TE.js} +2 -2
- package/dist/cli/chunks/{chunk-AFLLQ5PP.js → chunk-Q4A72ZTV.js} +2 -2
- package/dist/cli/chunks/{chunk-EHDQJQ6Y.js → chunk-QEQTC4WQ.js} +5 -5
- package/dist/cli/chunks/{chunk-IAV2JMIX.js → chunk-QIH3E775.js} +2 -2
- package/dist/cli/chunks/{chunk-GRUUQAR6.js → chunk-QNBQBSAI.js} +2 -2
- package/dist/cli/chunks/{chunk-WIEC7VKK.js → chunk-QODE4LM6.js} +2 -2
- package/dist/cli/chunks/{chunk-HY6PMO5W.js → chunk-QPRVX4H2.js} +2 -2
- package/dist/cli/chunks/chunk-RC5CPXON.js +2 -0
- package/dist/cli/chunks/{chunk-TWUWL5EJ.js → chunk-RITN3XR4.js} +2 -2
- package/dist/cli/chunks/{chunk-WBQSXPBI.js → chunk-RJROC5M3.js} +2 -2
- package/dist/cli/chunks/chunk-RQGYJK7H.js +2 -0
- package/dist/cli/chunks/{chunk-XO6PVK2P.js → chunk-S3RDH5CI.js} +2 -2
- package/dist/cli/chunks/{chunk-3IUNFTIF.js → chunk-SCF7NRVE.js} +1 -1
- package/dist/cli/chunks/chunk-SDTVHR63.js +2 -0
- package/dist/cli/chunks/chunk-SGAW2WLI.js +65 -0
- package/dist/cli/chunks/{chunk-N2NS2PHA.js → chunk-SNVM4YJS.js} +2 -2
- package/dist/cli/chunks/{chunk-JXM26HEE.js → chunk-SRRFWTNF.js} +2 -2
- package/dist/cli/chunks/{chunk-UQHYFOBX.js → chunk-STE42EMB.js} +2 -2
- package/dist/cli/chunks/{chunk-WJ3DLOXF.js → chunk-T5GV6UIO.js} +2 -2
- package/dist/cli/chunks/{chunk-4YS3IJ45.js → chunk-TKF447CW.js} +1 -1
- package/dist/cli/chunks/{chunk-ZAPS3UGQ.js → chunk-TTOE336G.js} +3 -3
- package/dist/cli/chunks/{chunk-YAGODYIG.js → chunk-UKDOMLBI.js} +3 -3
- package/dist/cli/chunks/{chunk-JBANAPWG.js → chunk-V6XBAZNH.js} +1 -1
- package/dist/cli/chunks/{chunk-BULKFVYX.js → chunk-VHVWAXCF.js} +1 -1
- package/dist/cli/chunks/{chunk-5SKGFSKD.js → chunk-VL7YOOC2.js} +2 -2
- package/dist/cli/chunks/{chunk-AKE543X2.js → chunk-VUAO4VFC.js} +2 -2
- package/dist/cli/chunks/{chunk-7R6YMLVS.js → chunk-WG4GHAML.js} +2 -2
- package/dist/cli/chunks/{chunk-BTREG4IW.js → chunk-WXWY2GAF.js} +2 -2
- package/dist/cli/chunks/chunk-X35GP7TR.js +1 -0
- package/dist/cli/chunks/chunk-X6LCMOGC.js +2 -0
- package/dist/cli/chunks/{chunk-BGXNSCXX.js → chunk-XFMKJ3UD.js} +1 -1
- package/dist/cli/chunks/{chunk-BLBRY5UD.js → chunk-XH53ARZD.js} +2 -2
- package/dist/cli/chunks/chunk-XIBVVZGB.js +2 -0
- package/dist/cli/chunks/chunk-XYJL6DKI.js +2 -0
- package/dist/cli/chunks/{chunk-5T2ZQWKF.js → chunk-Y6O7CDLI.js} +2 -2
- package/dist/cli/chunks/{chunk-4I2IOUS4.js → chunk-YXCU4CJX.js} +1 -1
- package/dist/cli/chunks/{chunk-YR6ZZGH7.js → chunk-Z2IKNC5M.js} +1 -1
- package/dist/cli/chunks/{chunk-OLHKGP35.js → chunk-Z54EO6E6.js} +2 -2
- package/dist/cli/chunks/{chunk-ZDATDCYN.js → chunk-Z5HXGVXZ.js} +1 -1
- package/dist/cli/chunks/{ci-J374KDLI.js → ci-2BCOBWFG.js} +2 -2
- package/dist/cli/chunks/ci-output-FB4OJHAC.js +2 -0
- package/dist/cli/chunks/{claude-flow-setup-245JLJCN.js → claude-flow-setup-NEEFZTMB.js} +2 -2
- package/dist/cli/chunks/client-EF555KYW.js +2 -0
- package/dist/cli/chunks/{cline-installer-LBA2M5N3.js → cline-installer-ODO2PS4K.js} +2 -2
- package/dist/cli/chunks/{code-U4N4WONM.js → code-NSOF62VE.js} +2 -2
- package/dist/cli/chunks/{code-index-extractor-A57Z6BO4.js → code-index-extractor-YQL5XN52.js} +2 -2
- package/dist/cli/chunks/{codex-installer-UXMK2N4T.js → codex-installer-SPEY6VYT.js} +2 -2
- package/dist/cli/chunks/{completions-W66BSCOE.js → completions-OWKBUMBE.js} +2 -2
- package/dist/cli/chunks/complexity-analyzer-PGTXKP73.js +2 -0
- package/dist/cli/chunks/{continuedev-installer-LRFZ2SJM.js → continuedev-installer-KGOXAC7L.js} +2 -2
- package/dist/cli/chunks/{copilot-installer-CQ3JYBIB.js → copilot-installer-BF3UA3TG.js} +2 -2
- package/dist/cli/chunks/cost-tracker-2HDJ66E2.js +2 -0
- package/dist/cli/chunks/{coverage-4PUEQXAY.js → coverage-KPA2PHIN.js} +3 -3
- package/dist/cli/chunks/cross-domain-router-GXFNK5TS.js +2 -0
- package/dist/cli/chunks/{cursor-installer-JZEDEDHA.js → cursor-installer-7CDZFHTV.js} +2 -2
- package/dist/cli/chunks/{daemon-B7TWGHXQ.js → daemon-4BPGCKDJ.js} +3 -3
- package/dist/cli/chunks/dag-attention-scheduler-2MAVGSBB.js +2 -0
- package/dist/cli/chunks/detect-WRPWTGP5.js +2 -0
- package/dist/cli/chunks/{domain-handler-FT5FLZWL.js → domain-handler-JZVSJ7AG.js} +2 -2
- package/dist/cli/chunks/domain-transfer-XGIZOR2X.js +2 -0
- package/dist/cli/chunks/dream-3IKF5XH4.js +2 -0
- package/dist/cli/chunks/esm-node-DHAE52OW.js +2 -0
- package/dist/cli/chunks/{eval-GHMPFGWV.js → eval-T7YPAS4G.js} +2 -2
- package/dist/cli/chunks/{fast-paths-B3R647KN.js → fast-paths-QECJTKCQ.js} +2 -2
- package/dist/cli/chunks/{feature-flags-DWS7ARSX.js → feature-flags-LIFURSFZ.js} +2 -2
- package/dist/cli/chunks/feature-flags-R4QZYTIW.js +2 -0
- package/dist/cli/chunks/file-discovery-4W3K3W4C.js +2 -0
- package/dist/cli/chunks/{fleet-EKOKMOMW.js → fleet-NLLQWCI5.js} +3 -3
- package/dist/cli/chunks/gnn-wrapper-XEII72LN.js +2 -0
- package/dist/cli/chunks/{heartbeat-handler-MBBS4IBU.js → heartbeat-handler-DJ65RE5D.js} +4 -4
- package/dist/cli/chunks/{heartbeat-scheduler-XDGMOT7X.js → heartbeat-scheduler-H664265Q.js} +2 -2
- package/dist/cli/chunks/hnsw-adapter-DML5KXQR.js +2 -0
- package/dist/cli/chunks/hnsw-index-BUPPGVR6.js +2 -0
- package/dist/cli/chunks/hnsw-legacy-bridge-SQIDTWAA.js +2 -0
- package/dist/cli/chunks/hnswlib-node-WICYCU5U.js +2 -0
- package/dist/cli/chunks/{hooks-L5VLZGEK.js → hooks-GZUHUD63.js} +6 -6
- package/dist/cli/chunks/hypergraph-engine-MLCDZ6BL.js +2 -0
- package/dist/cli/chunks/{hypergraph-handler-3HDGB5SZ.js → hypergraph-handler-NNDDI4R3.js} +3 -3
- package/dist/cli/chunks/impact-analyzer-DPTMJRYS.js +2 -0
- package/dist/cli/chunks/{init-handler-JDET6WUN.js → init-handler-IJ6BHE6A.js} +6 -6
- package/dist/cli/chunks/init-wizard-35PUDJPW.js +2 -0
- package/dist/cli/chunks/kernel-2HZ44ZJ4.js +2 -0
- package/dist/cli/chunks/{kilocode-installer-GZZG5AFW.js → kilocode-installer-EPZFFPFE.js} +2 -2
- package/dist/cli/chunks/{kiro-installer-IWNY5TKH.js → kiro-installer-5VACG3HU.js} +2 -2
- package/dist/cli/chunks/knowledge-graph-JL62G72U.js +2 -0
- package/dist/cli/chunks/{learning-722ZNSZ6.js → learning-6FITK6XY.js} +3 -3
- package/dist/cli/chunks/{llm-router-DNAV746L.js → llm-router-4DDC6AKJ.js} +2 -2
- package/dist/cli/chunks/{load-Y3GCUFM4.js → load-KGDNVUBX.js} +2 -2
- package/dist/cli/chunks/load-test-LN245SSD.js +2 -0
- package/dist/cli/chunks/{mcp-LKPIBZ3W.js → mcp-4LETGVIV.js} +2 -2
- package/dist/cli/chunks/{memory-L57MLFOP.js → memory-II4I4QMO.js} +5 -5
- package/dist/cli/chunks/memory-backend-SVM7YRIE.js +2 -0
- package/dist/cli/chunks/memory-handlers-TQXTOJGQ.js +2 -0
- package/dist/cli/chunks/opencode-installer-EU6JCWBW.js +3 -0
- package/dist/cli/chunks/{orchestrator-QHSBB2UC.js → orchestrator-YLMGJVSP.js} +5 -5
- package/dist/cli/chunks/{pipeline-D3QER35Z.js → pipeline-MPZJWYKK.js} +2 -2
- package/dist/cli/chunks/{platform-T4E7Q3RD.js → platform-YH35ZZFZ.js} +2 -2
- package/dist/cli/chunks/{plugin-JHW2YPRC.js → plugin-B7JYZFNQ.js} +2 -2
- package/dist/cli/chunks/{prime-radiant-advanced-wasm-G7CFNNQV.js → prime-radiant-advanced-wasm-KTUK6UE2.js} +2 -2
- package/dist/cli/chunks/protocol-executor-IEN2XB4L.js +2 -0
- package/dist/cli/chunks/{protocol-handler-2BQQ4HDM.js → protocol-handler-3NXMVU34.js} +2 -2
- package/dist/cli/chunks/{prove-UQ6JFT73.js → prove-H5LMGSUC.js} +2 -2
- package/dist/cli/chunks/qe-reasoning-bank-Q3ZV3JRG.js +2 -0
- package/dist/cli/chunks/{quality-JRZYMC77.js → quality-RCWHY6GO.js} +2 -2
- package/dist/cli/chunks/queen-coordinator-E6ON3JUR.js +2 -0
- package/dist/cli/chunks/real-embeddings-NKH4VURF.js +2 -0
- package/dist/cli/chunks/{roocode-installer-F4E2LAYR.js → roocode-installer-SB7QJYM3.js} +2 -2
- package/dist/cli/chunks/router-WMC3LZ3C.js +2 -0
- package/dist/cli/chunks/routing-feedback-VKCZRCE3.js +2 -0
- package/dist/cli/chunks/{routing-handler-VNKFUUGB.js → routing-handler-SY7GKG2W.js} +2 -2
- package/dist/cli/chunks/ruvector-commands-HATTO3UQ.js +8 -0
- package/dist/cli/chunks/rvf-dual-writer-D57EXQUD.js +2 -0
- package/dist/cli/chunks/rvf-migration-adapter-OWDYN6KD.js +2 -0
- package/dist/cli/chunks/rvf-migration-coordinator-SIQVJB5S.js +2 -0
- package/dist/cli/chunks/rvf-native-adapter-C7NBH5UN.js +2 -0
- package/dist/cli/chunks/safe-db-5KLXCNXN.js +2 -0
- package/dist/cli/chunks/schedule-HAWWOXWB.js +2 -0
- package/dist/cli/chunks/scheduler-HTRDY5BC.js +2 -0
- package/dist/cli/chunks/{security-EBEG2OPU.js → security-DS3XLZWN.js} +3 -3
- package/dist/cli/chunks/shared-rvf-adapter-6I2Z5UGL.js +2 -0
- package/dist/cli/chunks/shared-rvf-dual-writer-YB7AH6XJ.js +2 -0
- package/dist/cli/chunks/sqlite-persistence-WNNRGTGG.js +2 -0
- package/dist/cli/chunks/{status-handler-VZ32M4G4.js → status-handler-TUYHE4FT.js} +2 -2
- package/dist/cli/chunks/{structural-health-K6LRCKV6.js → structural-health-XNGBNRRD.js} +2 -2
- package/dist/cli/chunks/{sync-MHSHNLIM.js → sync-K6CIRKBB.js} +2 -2
- package/dist/cli/chunks/{task-handler-JNOIBZ2G.js → task-handler-7PJY67DR.js} +2 -2
- package/dist/cli/chunks/task-handlers-WB5CDWUR.js +2 -0
- package/dist/cli/chunks/{test-DO22BNIL.js → test-WV5ALEBB.js} +4 -4
- package/dist/cli/chunks/{test-scheduling-VLRQZEFL.js → test-scheduling-N55ZGGA2.js} +3 -3
- package/dist/cli/chunks/token-bootstrap-SINWHAKR.js +2 -0
- package/dist/cli/chunks/{token-usage-LG3PXRXH.js → token-usage-R7TGEVGL.js} +2 -2
- package/dist/cli/chunks/transformers-6DBLXPV7.js +2 -0
- package/dist/cli/chunks/{tree-sitter-wasm-parser-FT2KB66N.js → tree-sitter-wasm-parser-7C7FKMQW.js} +2 -2
- package/dist/cli/chunks/types-VNPMOKQT.js +2 -0
- package/dist/cli/chunks/unified-memory-72SKVZ7Y.js +2 -0
- package/dist/cli/chunks/unified-memory-hnsw-TMN2L77W.js +2 -0
- package/dist/cli/chunks/unified-persistence-MDN3SRCR.js +2 -0
- package/dist/cli/chunks/{validate-VQCRSVNQ.js → validate-53MNIRAF.js} +2 -2
- package/dist/cli/chunks/{validate-swarm-A5DHAWTP.js → validate-swarm-ZY4RGUFO.js} +2 -2
- package/dist/cli/chunks/{vibium-RZBSL4EB.js → vibium-PBADBIV6.js} +2 -2
- package/dist/cli/chunks/visual-security-TRBCXPIB.js +2 -0
- package/dist/cli/chunks/{web-tree-sitter-7C4NXEOF.js → web-tree-sitter-O7VI6RLB.js} +2 -2
- package/dist/cli/chunks/{windsurf-installer-ES3KPQG3.js → windsurf-installer-HV3C3TAD.js} +2 -2
- package/dist/cli/chunks/witness-chain-4WIMYP4X.js +2 -0
- package/dist/cli/chunks/witness-chain-JOI2YYGK.js +2 -0
- package/dist/cli/chunks/{workflow-JETHX4ML.js → workflow-5RVAQ4TM.js} +4 -4
- package/dist/cli/chunks/workflow-orchestrator-2NQ72S3C.js +2 -0
- package/dist/cli/chunks/{wrappers-WP5RH745.js → wrappers-RRHCCA3E.js} +2 -2
- package/dist/cli/commands/ruvector-commands.js +14 -2
- package/dist/cli/index.js +10 -15
- package/dist/coordination/agent-memory-branch.d.ts +117 -0
- package/dist/coordination/agent-memory-branch.js +213 -0
- package/dist/coordination/agent-teams/mailbox.d.ts +43 -0
- package/dist/coordination/agent-teams/mailbox.js +130 -4
- package/dist/coordination/handlers/handler-utils.d.ts +1 -0
- package/dist/coordination/handlers/handler-utils.js +9 -2
- package/dist/coordination/handlers/quality-handlers.js +7 -1
- package/dist/domains/contract-testing/coordinator.js +11 -0
- package/dist/domains/quality-assessment/coherence/gate-controller.d.ts +20 -1
- package/dist/domains/quality-assessment/coherence/gate-controller.js +64 -0
- package/dist/domains/quality-assessment/coherence/index.d.ts +3 -3
- package/dist/domains/quality-assessment/coherence/index.js +2 -2
- package/dist/domains/quality-assessment/coherence/types.d.ts +39 -0
- package/dist/domains/quality-assessment/coherence/types.js +11 -0
- package/dist/domains/quality-assessment/coordinator.d.ts +14 -0
- package/dist/domains/quality-assessment/coordinator.js +92 -0
- package/dist/domains/test-execution/coordinator.d.ts +19 -0
- package/dist/domains/test-execution/coordinator.js +102 -5
- package/dist/domains/test-generation/coordinator.js +11 -0
- package/dist/domains/test-generation/interfaces.d.ts +2 -0
- package/dist/domains/test-generation/services/test-generator.d.ts +9 -0
- package/dist/domains/test-generation/services/test-generator.js +37 -0
- package/dist/init/agents-installer.d.ts +5 -3
- package/dist/init/agents-installer.js +17 -43
- package/dist/init/find-package-root.d.ts +22 -0
- package/dist/init/find-package-root.js +46 -0
- package/dist/init/n8n-installer.d.ts +4 -2
- package/dist/init/n8n-installer.js +23 -23
- package/dist/init/opencode-installer.d.ts +0 -5
- package/dist/init/opencode-installer.js +12 -39
- package/dist/init/skills-installer.d.ts +5 -2
- package/dist/init/skills-installer.js +15 -37
- package/dist/integrations/embeddings/index/HNSWIndex.d.ts +9 -2
- package/dist/integrations/embeddings/index/HNSWIndex.js +110 -35
- package/dist/integrations/ruvector/cognitive-routing.d.ts +67 -0
- package/dist/integrations/ruvector/cognitive-routing.js +208 -0
- package/dist/integrations/ruvector/feature-flags.d.ts +84 -0
- package/dist/integrations/ruvector/feature-flags.js +59 -0
- package/dist/integrations/ruvector/hdc-fingerprint.d.ts +76 -0
- package/dist/integrations/ruvector/hdc-fingerprint.js +217 -0
- package/dist/integrations/ruvector/hyperbolic-hnsw.d.ts +59 -0
- package/dist/integrations/ruvector/hyperbolic-hnsw.js +194 -0
- package/dist/integrations/ruvector/index.d.ts +5 -2
- package/dist/integrations/ruvector/index.js +13 -2
- package/dist/integrations/ruvector/shared-rvf-adapter.d.ts +24 -0
- package/dist/integrations/ruvector/shared-rvf-adapter.js +55 -0
- package/dist/integrations/ruvector/shared-rvf-dual-writer.d.ts +6 -0
- package/dist/integrations/ruvector/shared-rvf-dual-writer.js +38 -0
- package/dist/integrations/ruvector/sona-persistence.d.ts +8 -0
- package/dist/integrations/ruvector/sona-persistence.js +10 -0
- package/dist/integrations/ruvector/vector-delta-tracker.d.ts +96 -0
- package/dist/integrations/ruvector/vector-delta-tracker.js +226 -0
- package/dist/kernel/agent-coordinator.d.ts +75 -1
- package/dist/kernel/agent-coordinator.js +250 -1
- package/dist/kernel/hnsw-legacy-bridge.d.ts +38 -0
- package/dist/kernel/hnsw-legacy-bridge.js +88 -0
- package/dist/kernel/hnsw-shadow-validator.d.ts +91 -0
- package/dist/kernel/hnsw-shadow-validator.js +139 -0
- package/dist/kernel/index.d.ts +1 -1
- package/dist/kernel/index.js +1 -1
- package/dist/kernel/interfaces.d.ts +39 -0
- package/dist/kernel/kernel.d.ts +23 -0
- package/dist/kernel/kernel.js +106 -1
- package/dist/kernel/unified-memory.d.ts +1 -1
- package/dist/kernel/unified-memory.js +7 -3
- package/dist/learning/aqe-learning-engine.d.ts +65 -0
- package/dist/learning/aqe-learning-engine.js +134 -0
- package/dist/learning/dream/dream-engine.d.ts +6 -1
- package/dist/learning/dream/dream-engine.js +37 -2
- package/dist/learning/dream/dream-scheduler.d.ts +25 -0
- package/dist/learning/dream/dream-scheduler.js +120 -0
- package/dist/learning/dream/rvcow-branch-manager.d.ts +6 -3
- package/dist/learning/dream/rvcow-branch-manager.js +60 -5
- package/dist/learning/experience-capture.d.ts +3 -3
- package/dist/learning/hyperbolic-pattern-index.d.ts +82 -0
- package/dist/learning/hyperbolic-pattern-index.js +142 -0
- package/dist/learning/index.d.ts +3 -3
- package/dist/learning/index.js +1 -1
- package/dist/learning/metrics-tracker.d.ts +44 -0
- package/dist/learning/metrics-tracker.js +37 -0
- package/dist/learning/pattern-promotion.d.ts +3 -3
- package/dist/learning/pattern-store.d.ts +45 -2
- package/dist/learning/pattern-store.js +239 -4
- package/dist/learning/qe-patterns.d.ts +1 -1
- package/dist/learning/qe-reasoning-bank.js +1 -1
- package/dist/learning/rvf-pattern-migration.d.ts +50 -0
- package/dist/learning/rvf-pattern-migration.js +106 -0
- package/dist/learning/rvf-pattern-store.d.ts +69 -0
- package/dist/learning/rvf-pattern-store.js +449 -0
- package/dist/mcp/bundle.js +1894 -1804
- package/dist/mcp/handlers/index.d.ts +1 -0
- package/dist/mcp/handlers/index.js +2 -0
- package/dist/mcp/handlers/migration-handlers.d.ts +52 -0
- package/dist/mcp/handlers/migration-handlers.js +85 -0
- package/dist/mcp/protocol-server.d.ts +1 -0
- package/dist/mcp/protocol-server.js +63 -2
- package/dist/mcp/types.d.ts +1 -1
- package/dist/optimization/early-exit-token-optimizer.d.ts +7 -7
- package/dist/optimization/early-exit-token-optimizer.js +3 -3
- package/dist/persistence/rvf-consistency-validator.d.ts +85 -0
- package/dist/persistence/rvf-consistency-validator.js +182 -0
- package/dist/persistence/rvf-migration-adapter.d.ts +125 -0
- package/dist/persistence/rvf-migration-adapter.js +303 -0
- package/dist/persistence/rvf-migration-coordinator.d.ts +115 -0
- package/dist/persistence/rvf-migration-coordinator.js +224 -0
- package/dist/persistence/rvf-stage-gate.d.ts +70 -0
- package/dist/persistence/rvf-stage-gate.js +163 -0
- package/package.json +10 -10
- package/dist/cli/chunks/adapter-WBR5NXS3.js +0 -2
- package/dist/cli/chunks/aqe-learning-engine-TK4JQCGT.js +0 -2
- package/dist/cli/chunks/base-2WXOSMBQ.js +0 -2
- package/dist/cli/chunks/better-sqlite3-7KY2RDXO.js +0 -2
- package/dist/cli/chunks/brain-handler-PPEGDCN4.js +0 -68
- package/dist/cli/chunks/browser-workflow-42F7GK5T.js +0 -2
- package/dist/cli/chunks/chunk-263XS447.js +0 -2
- package/dist/cli/chunks/chunk-2I7J3O6V.js +0 -2
- package/dist/cli/chunks/chunk-3JPRUND5.js +0 -2
- package/dist/cli/chunks/chunk-3THRQEZ2.js +0 -95
- package/dist/cli/chunks/chunk-4B6NCELM.js +0 -2
- package/dist/cli/chunks/chunk-62ADTHV7.js +0 -2
- package/dist/cli/chunks/chunk-BR26T7ZS.js +0 -180
- package/dist/cli/chunks/chunk-DRT3WKQW.js +0 -2
- package/dist/cli/chunks/chunk-FIA6X7UL.js +0 -2
- package/dist/cli/chunks/chunk-J3KWWR6Z.js +0 -1
- package/dist/cli/chunks/chunk-JZSDOIXA.js +0 -2
- package/dist/cli/chunks/chunk-MV6CMOJQ.js +0 -65
- package/dist/cli/chunks/chunk-N5UXCLFI.js +0 -2
- package/dist/cli/chunks/chunk-OF4D7MYI.js +0 -2
- package/dist/cli/chunks/chunk-QOVHWZEP.js +0 -1
- package/dist/cli/chunks/chunk-RFSN6IDA.js +0 -79
- package/dist/cli/chunks/chunk-X5IJGWYG.js +0 -2
- package/dist/cli/chunks/ci-output-7JN7F6CI.js +0 -2
- package/dist/cli/chunks/client-MCSNSH2C.js +0 -2
- package/dist/cli/chunks/complexity-analyzer-AB4OZARV.js +0 -2
- package/dist/cli/chunks/cost-tracker-4F723RB6.js +0 -2
- package/dist/cli/chunks/cross-domain-router-OWR5IJ5G.js +0 -2
- package/dist/cli/chunks/dag-attention-scheduler-JWO6XI6A.js +0 -2
- package/dist/cli/chunks/detect-L6ZZHUSX.js +0 -2
- package/dist/cli/chunks/domain-transfer-5Y4FGJAJ.js +0 -2
- package/dist/cli/chunks/dream-4TDBIYED.js +0 -2
- package/dist/cli/chunks/esm-node-2PKHKOTS.js +0 -2
- package/dist/cli/chunks/feature-flags-IVQ3AL4Q.js +0 -2
- package/dist/cli/chunks/file-discovery-QFPA6GMV.js +0 -2
- package/dist/cli/chunks/gnn-wrapper-OYC55N5E.js +0 -2
- package/dist/cli/chunks/hnsw-index-YO7CT23I.js +0 -2
- package/dist/cli/chunks/hnswlib-node-56YWVXFE.js +0 -2
- package/dist/cli/chunks/hypergraph-engine-A4Y2ZRAG.js +0 -2
- package/dist/cli/chunks/impact-analyzer-UEIGXSZ4.js +0 -2
- package/dist/cli/chunks/init-wizard-JWZUGIPJ.js +0 -2
- package/dist/cli/chunks/kernel-YNDTVKIW.js +0 -2
- package/dist/cli/chunks/knowledge-graph-NGJKFTSN.js +0 -2
- package/dist/cli/chunks/load-test-GZUBXFF3.js +0 -2
- package/dist/cli/chunks/memory-backend-3NQIZUXE.js +0 -2
- package/dist/cli/chunks/memory-handlers-MDZQ7HVW.js +0 -2
- package/dist/cli/chunks/opencode-installer-4HUB36H5.js +0 -3
- package/dist/cli/chunks/protocol-executor-SPUVRDWT.js +0 -2
- package/dist/cli/chunks/qe-reasoning-bank-3HBK2FVD.js +0 -2
- package/dist/cli/chunks/queen-coordinator-RW3NKO5A.js +0 -2
- package/dist/cli/chunks/real-embeddings-GK63VF35.js +0 -2
- package/dist/cli/chunks/router-RJGHWDQ3.js +0 -2
- package/dist/cli/chunks/routing-feedback-ZXBXFKX6.js +0 -2
- package/dist/cli/chunks/ruvector-commands-2TLNHC3A.js +0 -8
- package/dist/cli/chunks/rvf-dual-writer-MQW2SJLT.js +0 -2
- package/dist/cli/chunks/rvf-native-adapter-LKFKTMUN.js +0 -2
- package/dist/cli/chunks/safe-db-G22E5ROA.js +0 -2
- package/dist/cli/chunks/schedule-Y7VVCPYV.js +0 -2
- package/dist/cli/chunks/scheduler-AUQIFQB7.js +0 -2
- package/dist/cli/chunks/shared-rvf-dual-writer-BVSCQAFS.js +0 -2
- package/dist/cli/chunks/sqlite-persistence-JAVHUGGL.js +0 -2
- package/dist/cli/chunks/task-handlers-P5DSUKND.js +0 -2
- package/dist/cli/chunks/token-bootstrap-4VJKGVMK.js +0 -2
- package/dist/cli/chunks/transformers-GY7SIKEU.js +0 -2
- package/dist/cli/chunks/types-QJGNBKP2.js +0 -2
- package/dist/cli/chunks/unified-memory-XYGENQUT.js +0 -2
- package/dist/cli/chunks/unified-memory-hnsw-MVEGQBF3.js +0 -2
- package/dist/cli/chunks/unified-persistence-PFRCWEUG.js +0 -2
- package/dist/cli/chunks/visual-security-V47BLGJM.js +0 -2
- package/dist/cli/chunks/witness-chain-BR63P4A7.js +0 -2
- package/dist/cli/chunks/workflow-orchestrator-7PZMX3JZ.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
function b(i,t){return{ingest(e){i.ingest(e)},search(e,r){return i.search(e,r).map(s=>({id:s.id,score:s.score}))},delete(e){i.delete(e)},status(){let e=i.status();return{totalVectors:e.totalVectors,dimensions:t,totalSegments:e.totalSegments,fileSizeBytes:e.fileSizeBytes,epoch:e.epoch,witnessValid:e.witnessValid,witnessEntries:e.witnessEntries}},close(){i.close()}}}function c(i,t){return(i.prepare("SELECT COUNT(*) as cnt FROM sqlite_master WHERE type='table' AND name=?").get(t)?.cnt??0)>0}var d=class{db;config;rvfStore=null;rvfAvailable=!1;constructor(t,e){this.db=t,this.config={...e,dimensions:e.dimensions??384}}async initialize(){if(this.config.mode==="sqlite-only"){this.rvfAvailable=!1;return}try{let t=await import("./rvf-native-adapter-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.2");process.exit(0)}
|
|
2
|
+
function b(i,t){return{ingest(e){i.ingest(e)},search(e,r){return i.search(e,r).map(s=>({id:s.id,score:s.score}))},delete(e){i.delete(e)},status(){let e=i.status();return{totalVectors:e.totalVectors,dimensions:t,totalSegments:e.totalSegments,fileSizeBytes:e.fileSizeBytes,epoch:e.epoch,witnessValid:e.witnessValid,witnessEntries:e.witnessEntries}},close(){i.close()}}}function c(i,t){return(i.prepare("SELECT COUNT(*) as cnt FROM sqlite_master WHERE type='table' AND name=?").get(t)?.cnt??0)>0}var d=class{db;config;rvfStore=null;rvfAvailable=!1;constructor(t,e){this.db=t,this.config={...e,dimensions:e.dimensions??384}}async initialize(){if(this.config.mode==="sqlite-only"){this.rvfAvailable=!1;return}try{let t=await import("./rvf-native-adapter-C7NBH5UN.js");if(!t.isRvfNativeAvailable()){this.rvfAvailable=!1;return}let e;try{e=t.openRvfStore(this.config.rvfPath)}catch{e=t.createRvfStore(this.config.rvfPath,this.config.dimensions)}this.rvfStore=b(e,this.config.dimensions),this.rvfAvailable=!0}catch{this.rvfAvailable=!1}}setRvfStore(t){this.rvfStore=t,this.rvfAvailable=!0}writePattern(t,e){let r={sqliteSuccess:!1,rvfSuccess:!1};try{this.writeSqliteEmbedding(t,e),r.sqliteSuccess=!0}catch{r.sqliteSuccess=!1}if(this.shouldWriteRvf())try{this.rvfStore.ingest([{id:t,vector:e instanceof Float32Array?Array.from(e):e}]),r.rvfSuccess=!0}catch{r.rvfSuccess=!1,r.divergence="rvf-write-failed"}return r}deletePattern(t){let e={sqliteSuccess:!1,rvfSuccess:!1};try{this.deleteSqliteEmbedding(t),e.sqliteSuccess=!0}catch{e.sqliteSuccess=!1}if(this.shouldWriteRvf())try{this.rvfStore.delete([t]),e.rvfSuccess=!0}catch{e.rvfSuccess=!1,e.divergence="rvf-delete-failed"}return e}search(t,e){if(this.config.mode==="rvf-primary"&&this.rvfAvailable&&this.rvfStore)try{return this.rvfStore.search(t,e)}catch{}return this.searchSqlite(t,e)}getDivergenceReport(){let t={totalChecked:0,divergences:0,details:[]},e=this.getSqliteEmbeddingCount();if(t.totalChecked=e,!this.rvfAvailable||!this.rvfStore)return this.config.mode!=="sqlite-only"&&e>0&&(t.divergences=1,t.details.push({patternId:"*",issue:"count-mismatch"})),t;let s=this.rvfStore.status().totalVectors;return e!==s&&(t.divergences=1,t.details.push({patternId:"*",issue:"count-mismatch"})),t}isPromotionSafe(){return this.getDivergenceReport().divergences===0}status(){let t=this.getSqlitePatternCount(),e=this.getSqliteEmbeddingCount(),r=null;if(this.rvfAvailable&&this.rvfStore)try{r=this.rvfStore.status()}catch{r=null}return{sqlite:{patternCount:t,vectorCount:e},rvf:r,mode:this.config.mode}}close(){if(this.rvfStore){try{this.rvfStore.close()}catch{}this.rvfStore=null,this.rvfAvailable=!1}}shouldWriteRvf(){return(this.config.mode==="dual-write"||this.config.mode==="rvf-primary")&&this.rvfAvailable&&this.rvfStore!==null}writeSqliteEmbedding(t,e){let r=Buffer.from(e instanceof Float32Array?e.buffer:new Float32Array(e).buffer),s=e.length;c(this.db,"qe_pattern_embeddings")&&this.db.prepare(`
|
|
3
3
|
INSERT INTO qe_pattern_embeddings (pattern_id, embedding, dimension, model, created_at)
|
|
4
4
|
VALUES (?, ?, ?, 'all-MiniLM-L6-v2', datetime('now'))
|
|
5
5
|
ON CONFLICT(pattern_id) DO UPDATE SET
|
|
@@ -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.2");process.exit(0)}
|
|
2
|
+
import{c as t}from"./chunk-YXCU4CJX.js";import{randomInt as o}from"node:crypto";function a(){return Math.random()}function m(n,e){return o(n,e)}function c(n,e){return n+Math.random()*(e-n)}var r=t(()=>{"use strict"});export{a,m as b,c,r as d};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{h as s,k as o,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.2");process.exit(0)}
|
|
2
|
+
import{h as s,k as o,o as m}from"./chunk-GK72GUHA.js";import{a as u}from"./chunk-XIBVVZGB.js";import{c as r}from"./chunk-JOVINE23.js";import{a,e as c}from"./chunk-MN742FIH.js";m();c();u();var l=r.create("hybrid-backend"),d=class{unifiedMemory=null;config;cleanupInterval;cleanupCount=0;initialized=!1;constructor(e){this.config={sqlite:{path:e?.sqlite?.path??".agentic-qe/memory.db",walMode:e?.sqlite?.walMode??!0,poolSize:e?.sqlite?.poolSize??5,busyTimeout:e?.sqlite?.busyTimeout??a.BUSY_TIMEOUT_MS,...e?.sqlite},agentdb:{path:e?.agentdb?.path??".agentic-qe/memory.db",...e?.agentdb},enableFallback:e?.enableFallback??!0,defaultNamespace:e?.defaultNamespace??"default",cleanupInterval:e?.cleanupInterval??a.CLEANUP_INTERVAL_MS}}async initialize(){if(this.initialized)return;let e={dbPath:this.config.sqlite.path??s.dbPath,walMode:this.config.sqlite.walMode??!0,busyTimeout:this.config.sqlite.busyTimeout??a.BUSY_TIMEOUT_MS};this.unifiedMemory=o(e),await this.unifiedMemory.initialize(),this.cleanupInterval=setInterval(()=>this.cleanup(),this.config.cleanupInterval),this.cleanupInterval.unref&&this.cleanupInterval.unref(),this.initialized=!0,console.log(`[HybridBackend] Initialized with unified memory: ${this.unifiedMemory.getDbPath()}`)}async dispose(){this.cleanupInterval&&clearInterval(this.cleanupInterval),this.initialized=!1}async set(e,i,t){this.ensureInitialized();let n=t?.namespace??this.config.defaultNamespace;await this.unifiedMemory.kvSet(e,i,n,t?.ttl)}async get(e){return this.ensureInitialized(),this.unifiedMemory.kvGet(e,this.config.defaultNamespace)}async delete(e){this.ensureInitialized();let i=await this.unifiedMemory.kvDelete(e,this.config.defaultNamespace),t=await this.unifiedMemory.vectorDelete(e);return i||t}async has(e){return this.ensureInitialized(),this.unifiedMemory.kvExists(e,this.config.defaultNamespace)}async search(e,i=100){return this.ensureInitialized(),this.unifiedMemory.kvSearch(e,this.config.defaultNamespace,i)}async vectorSearch(e,i){return this.ensureInitialized(),(await this.unifiedMemory.vectorSearch(e,i)).map(n=>({key:n.id,score:n.score,metadata:n.metadata}))}async storeVector(e,i,t){this.ensureInitialized(),await this.unifiedMemory.vectorStore(e,i,this.config.defaultNamespace,t)}getHealth(){return{sqlite:this.unifiedMemory?.isInitialized()?"healthy":"unavailable",sqlitePersistent:!0,agentdb:this.unifiedMemory?.isInitialized()?"healthy":"unavailable",fallback:"inactive"}}isPersistent(){return this.unifiedMemory?.isInitialized()??!1}getConfig(){return{...this.config}}async setWithBackend(e,i,t,n){await this.set(e,i,n)}async getVectorStats(){if(!this.unifiedMemory?.isInitialized())return null;let e=await this.unifiedMemory.vectorCount(),i=this.unifiedMemory.getStats();return{vectorCount:e,indexSize:i.vectorIndexSize}}getUnifiedMemory(){return this.unifiedMemory}async count(e){return this.ensureInitialized(),this.unifiedMemory.getDatabase().prepare(`
|
|
3
3
|
SELECT COUNT(*) as count FROM kv_store
|
|
4
4
|
WHERE namespace LIKE ?
|
|
5
5
|
AND (expires_at IS NULL OR expires_at > ?)
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
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.2");process.exit(0)}
|
|
2
2
|
var l=["var-to-const","add-types","remove-console","promise-to-async","cjs-to-esm","func-to-arrow"],p={"var-to-const":{type:"var-to-const",name:"Var to Const/Let",description:"Convert var declarations to const (if not reassigned) or let (if reassigned)",complexity:"simple",wasmAvailable:!0,typicalLatencyMs:1},"add-types":{type:"add-types",name:"Add TypeScript Types",description:"Add TypeScript type annotations to function parameters and return types",complexity:"moderate",wasmAvailable:!0,typicalLatencyMs:5},"remove-console":{type:"remove-console",name:"Remove Console Statements",description:"Remove all console.log, console.warn, console.error, etc. statements",complexity:"simple",wasmAvailable:!0,typicalLatencyMs:1},"promise-to-async":{type:"promise-to-async",name:"Promise to Async/Await",description:"Convert Promise .then()/.catch() chains to async/await syntax",complexity:"complex",wasmAvailable:!0,typicalLatencyMs:10},"cjs-to-esm":{type:"cjs-to-esm",name:"CommonJS to ES Modules",description:"Convert require() calls to import statements and module.exports to export",complexity:"moderate",wasmAvailable:!0,typicalLatencyMs:5},"func-to-arrow":{type:"func-to-arrow",name:"Function to Arrow",description:"Convert function declarations and expressions to arrow functions",complexity:"moderate",wasmAvailable:!0,typicalLatencyMs:3}},u={enabled:!0,fallbackToLLM:!0,confidenceThreshold:.7,transforms:[],maxFileSizeBytes:1024*1024,timeoutMs:5e3,cacheEnabled:!0,cacheTtlMs:300*1e3},t=class extends Error{constructor(e,s,o){super(e);this.code=s;this.cause=o;this.name="AgentBoosterError"}},a=class extends t{constructor(e,s,o){super(e,"TRANSFORM_ERROR",o);this.transformType=s;this.name="TransformError"}},i=class extends t{constructor(r="WASM module is not available",e){super(r,"WASM_UNAVAILABLE",e),this.name="WasmUnavailableError"}},c=class extends t{constructor(e,s,o){super(e,"TRANSFORM_TIMEOUT");this.transformType=s;this.timeoutMs=o;this.name="TransformTimeoutError"}},m=class extends t{constructor(e,s,o){super(`File ${e} is too large (${s} bytes, max ${o} bytes)`,"FILE_TOO_LARGE");this.filePath=e;this.sizeBytes=s;this.maxSizeBytes=o;this.name="FileTooLargeError"}};export{l as a,p as b,u as c,a as d,i as e,c as f,m as g};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{c as h}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.2");process.exit(0)}
|
|
2
|
+
import{c as h}from"./chunk-YXCU4CJX.js";function i(t,r){if(t.length!==r.length)throw new Error(`Vector length mismatch: ${t.length} vs ${r.length}`);let e=0,o=0,l=0;for(let n=0;n<t.length;n++)e+=t[n]*r[n],o+=t[n]*t[n],l+=r[n]*r[n];let u=Math.sqrt(o)*Math.sqrt(l);return u===0?0:e/u}function c(t){let r=Math.sqrt(t.reduce((e,o)=>e+o*o,0));return r===0?t.slice():t.map(e=>e/r)}function g(t){let r=0;for(let e=0;e<t.length;e++)r+=t[e]*t[e];return Math.sqrt(r)}var m=h(()=>{"use strict"});export{i as a,c as b,g as c,m as d};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
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.2");process.exit(0)}
|
|
2
2
|
import{createRequire as t}from"module";var o=t(import.meta.url),e=o("@xenova/transformers"),n=e,{RuvectorLayer:i,TensorCompress:a,differentiableSearch:s,hierarchicalForward:c,getCompressionLevel:l,init:p,FlashAttention:m,DotProductAttention:u,MultiHeadAttention:d,HyperbolicAttention:A,LinearAttention:f,MoEAttention:h,SonaEngine:_,pipeline:v}=e||{};export{n as a,i as b,a as c,s as d,c as e,l as f,p as g,m as h,u as i,d as j,A as k,f as l,h as m,_ as n,v as o};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{a as
|
|
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");process.exit(0)}
|
|
2
|
+
import{a as U,b as G}from"./chunk-L5WZUPZF.js";import{g as W}from"./chunk-7SLN2JGP.js";import{a as _}from"./chunk-SGAW2WLI.js";import{e as S}from"./chunk-TKF447CW.js";import{b as v,c as x}from"./chunk-S3RDH5CI.js";import{a as ne}from"./chunk-XIBVVZGB.js";import{c as z}from"./chunk-JOVINE23.js";import{b as k,d as q}from"./chunk-N3F3CX4V.js";import{b,c as E}from"./chunk-BIVIPF4O.js";import{a as y,c as I}from"./chunk-SDTVHR63.js";import{f as O}from"./chunk-E25S5E2D.js";import{S as ae,b as N}from"./chunk-DBE34QES.js";import{randomUUID as Z}from"crypto";I();q();import{randomUUID as se}from"node:crypto";var j=x(),P=class{constructor(e){this.options=e}claudeFlowAvailable=!1;localTrajectories=new Map;async initialize(){this.claudeFlowAvailable=await this.checkClaudeFlow()}async checkClaudeFlow(){return v(this.options.projectRoot).available}async startTrajectory(e,t){let i=`trajectory-${se()}`;if(this.claudeFlowAvailable)try{let{execFileSync:r}=await import("child_process"),n=["--no-install",j,"hooks","intelligence","trajectory-start","--task",e];t&&n.push("--agent",t);let s=r("npx",n,{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot}).match(/trajectoryId[:\s]+["']?([^"'\s,}]+)/i);if(s?.[1])return s[1]}catch(r){console.debug("[TrajectoryBridge] Claude Flow trajectory start failed:",r instanceof Error?r.message:r)}return this.localTrajectories.set(i,{id:i,task:e,agent:t,steps:[],startedAt:Date.now()}),i}async recordStep(e,t,i,r){if(this.claudeFlowAvailable)try{let{execFileSync:a}=await import("child_process"),s=["--no-install",j,"hooks","intelligence","trajectory-step","--trajectory-id",e,"--action",t];i&&s.push("--result",i),r!==void 0&&s.push("--quality",String(r)),a("npx",s,{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot});return}catch(a){console.debug("[TrajectoryBridge] Claude Flow trajectory step failed:",a instanceof Error?a.message:a)}let n=this.localTrajectories.get(e);n&&n.steps.push({id:`step-${n.steps.length+1}`,action:t,result:i,quality:r,timestamp:Date.now()})}async endTrajectory(e,t,i){if(this.claudeFlowAvailable)try{let{execFileSync:n}=await import("child_process"),a=["--no-install",j,"hooks","intelligence","trajectory-end","--trajectory-id",e,"--success",String(t)];i&&a.push("--feedback",i),n("npx",a,{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot})}catch{}let r=this.localTrajectories.get(e);if(r)return r.success=t,r.feedback=i,r.completedAt=Date.now(),await this.persistTrajectory(r),r}getTrajectory(e){return this.localTrajectories.get(e)}isClaudeFlowAvailable(){return this.claudeFlowAvailable}async persistTrajectory(e){try{let{join:t}=await import("path"),{existsSync:i,mkdirSync:r}=await import("fs"),{createRequire:n}=await import("module"),a=n(import.meta.url),{openDatabase:s}=a("../../shared/safe-db.js"),o=t(this.options.projectRoot,".agentic-qe","trajectories.db"),u=t(this.options.projectRoot,".agentic-qe");i(u)||r(u,{recursive:!0});let p=s(o);p.exec(`
|
|
3
3
|
CREATE TABLE IF NOT EXISTS trajectories (
|
|
4
4
|
id TEXT PRIMARY KEY,
|
|
5
5
|
task TEXT NOT NULL,
|
|
@@ -12,13 +12,13 @@ import{a as $,b as I}from"./chunk-GKNNSCLC.js";import{g as z}from"./chunk-N4TL73
|
|
|
12
12
|
created_at INTEGER DEFAULT (strftime('%s', 'now') * 1000)
|
|
13
13
|
);
|
|
14
14
|
CREATE INDEX IF NOT EXISTS idx_trajectories_success ON trajectories(success);
|
|
15
|
-
`),
|
|
15
|
+
`),p.prepare(`
|
|
16
16
|
INSERT OR REPLACE INTO trajectories (id, task, agent, steps, success, feedback, started_at, completed_at)
|
|
17
17
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
18
|
-
`).run(e.id,e.task,e.agent||null,JSON.stringify(e.steps),e.success?1:0,e.feedback||null,e.startedAt,e.completedAt||null),d.close()}catch(t){console.debug("[TrajectoryBridge] Trajectory persistence failed:",t instanceof Error?t.message:t)}}};var q=v(),W={low:[/simple/i,/basic/i,/fix typo/i,/rename/i,/format/i,/add comment/i,/lint/i,/minor/i,/quick/i],high:[/architect/i,/design/i,/complex/i,/security/i,/performance/i,/refactor.*large/i,/critical/i,/analysis/i,/multi.*file/i,/database.*migration/i,/distributed/i,/concurrent/i]},x=class{constructor(e){this.options=e}claudeFlowAvailable=!1;routingHistory=[];async initialize(){this.claudeFlowAvailable=await this.checkClaudeFlow()}async checkClaudeFlow(){return y(this.options.projectRoot).available}async routeTask(e){if(this.claudeFlowAvailable)try{let{execFileSync:t}=await import("child_process"),i=t("npx",["--no-install",q,"hooks","model-route","--task",e],{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot}),r=i.match(/model[:\s]+["']?(haiku|sonnet|opus)/i),n=i.match(/confidence[:\s]+([0-9.]+)/i),a=i.match(/reason(?:ing)?[:\s]+["']?([^"'\n]+)/i);if(r)return{model:r[1].toLowerCase(),confidence:n?parseFloat(n[1]):.7,reasoning:a?.[1]?.trim()}}catch(t){console.debug("[ModelRouterBridge] Claude Flow routing failed:",t instanceof Error?t.message:t)}return this.localRoute(e)}async recordOutcome(e){if(this.routingHistory.push(e),this.routingHistory.length>1e3&&(this.routingHistory=this.routingHistory.slice(-500)),this.claudeFlowAvailable)try{let{execFileSync:t}=await import("child_process");t("npx",["--no-install",q,"hooks","model-outcome","--task",e.task,"--model",e.model,"--outcome",e.outcome],{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot})}catch(t){console.debug("[ModelRouterBridge] Outcome recording failed:",t instanceof Error?t.message:t)}}getStats(){let e={totalRoutings:this.routingHistory.length,modelDistribution:{haiku:0,sonnet:0,opus:0},successRate:{haiku:0,sonnet:0,opus:0}},t={haiku:0,sonnet:0,opus:0};for(let i of this.routingHistory)e.modelDistribution[i.model]++,i.outcome==="success"&&t[i.model]++;for(let i of["haiku","sonnet","opus"]){let r=e.modelDistribution[i];e.successRate[i]=r>0?t[i]/r:0}return e}isClaudeFlowAvailable(){return this.claudeFlowAvailable}localRoute(e){let t=e.toLowerCase();for(let i of W.low)if(i.test(t))return{model:"haiku",confidence:.75,reasoning:"Low complexity task detected - using haiku for speed"};for(let i of W.high)if(i.test(t))return{model:"opus",confidence:.8,reasoning:"High complexity task detected - using opus for capability"};return e.length>500?{model:"opus",confidence:.65,reasoning:"Long task description - using opus for complex reasoning"}:e.length<50?{model:"haiku",confidence:.6,reasoning:"Short task description - using haiku for efficiency"}:{model:"sonnet",confidence:.7,reasoning:"Medium complexity task - using sonnet for balance"}}};L();B();var T=v(),C=class{constructor(e){this.options=e}claudeFlowAvailable=!1;analysisCache=new Map;async initialize(){this.claudeFlowAvailable=await this.checkClaudeFlow()}async checkClaudeFlow(){return y(this.options.projectRoot).available}async analyze(e,t="medium"){let i=e||this.options.projectRoot,r=`${i}:${t}`,n=this.analysisCache.get(r);if(n)return n;if(this.claudeFlowAvailable)try{let{execFileSync:a}=await import("child_process"),s=a("npx",["--no-install",T,"hooks","pretrain","--path",i,"--depth",t],{encoding:"utf-8",timeout:12e4,cwd:this.options.projectRoot});try{let o=E(s),c={success:!0,repositoryPath:i,depth:t,analysis:o.analysis||void 0,agentConfigs:o.agentConfigs};return this.analysisCache.set(r,c),c}catch{return{success:!0,repositoryPath:i,depth:t}}}catch(a){console.debug("[PretrainBridge] Claude Flow analyze failed, using local:",a instanceof Error?a.message:a)}return this.localAnalyze(i,t)}async generateAgentConfigs(e="yaml"){if(this.claudeFlowAvailable)try{let{execFileSync:t}=await import("child_process"),i=t("npx",["--no-install",T,"hooks","build-agents","--format",e],{encoding:"utf-8",timeout:6e4,cwd:this.options.projectRoot});try{return E(i)}catch(r){return console.debug("[PretrainBridge] Agent config parse error:",r instanceof Error?r.message:r),[]}}catch(t){console.debug("[PretrainBridge] Claude Flow generateAgentConfigs failed:",t instanceof Error?t.message:t)}return this.generateLocalAgentConfigs()}async transferPatterns(e,t=.7){if(this.claudeFlowAvailable)try{let{execFileSync:i}=await import("child_process"),r=i("npx",["--no-install",T,"hooks","transfer","--source-path",e,"--min-confidence",String(t)],{encoding:"utf-8",timeout:6e4,cwd:this.options.projectRoot}),n=r.match(/transferred[:\s]+(\d+)/i),a=r.match(/skipped[:\s]+(\d+)/i);return{transferred:n?parseInt(n[1]):0,skipped:a?parseInt(a[1]):0}}catch(i){console.debug("[PretrainBridge] Claude Flow transferPatterns failed:",i instanceof Error?i.message:i)}return{transferred:0,skipped:0}}isClaudeFlowAvailable(){return this.claudeFlowAvailable}async localAnalyze(e,t){try{let i=await import("fast-glob"),{existsSync:r,readFileSync:n}=await import("fs"),{join:a}=await import("path"),s=t==="shallow"?["*.ts","*.js","*.json"]:t==="medium"?["**/*.ts","**/*.js","**/*.json","**/*.py"]:["**/*"],o=["node_modules/**","dist/**","coverage/**",".git/**"],c=await i.default(s,{cwd:e,ignore:o,onlyFiles:!0}),d=new Set,m=new Set;for(let l of c.slice(0,100))(l.endsWith(".ts")||l.endsWith(".tsx"))&&d.add("typescript"),(l.endsWith(".js")||l.endsWith(".jsx"))&&d.add("javascript"),l.endsWith(".py")&&d.add("python"),l.endsWith(".go")&&d.add("go"),l.endsWith(".rs")&&d.add("rust");let k=a(e,"package.json");if(r(k))try{let l=E(n(k,"utf-8")),h={...l.dependencies,...l.devDependencies};h.react&&m.add("react"),h.vue&&m.add("vue"),h.angular&&m.add("angular"),h.vitest&&m.add("vitest"),h.jest&&m.add("jest"),h.playwright&&m.add("playwright"),h.express&&m.add("express"),h.fastify&&m.add("fastify")}catch(l){console.debug("[PretrainBridge] package.json parse error:",l instanceof Error?l.message:l)}let p={success:!0,repositoryPath:e,depth:t,analysis:{languages:Array.from(d),frameworks:Array.from(m),patterns:[],complexity:c.length>500?3:c.length>100?2:1}};return this.analysisCache.set(`${e}:${t}`,p),p}catch(i){return{success:!1,repositoryPath:e,depth:t,error:g(i)}}}generateLocalAgentConfigs(){return[{name:"qe-test-architect",type:"worker",capabilities:["test-generation","test-design"],model:"sonnet"},{name:"qe-coverage-specialist",type:"worker",capabilities:["coverage-analysis","gap-detection"],model:"haiku"},{name:"qe-quality-gate",type:"worker",capabilities:["quality-assessment","risk-scoring"],model:"sonnet"},{name:"qe-security-scanner",type:"worker",capabilities:["security-scanning","vulnerability-detection"],model:"opus"}]}};var S=class{constructor(e){this.options=e;this.trajectory=new b(e),this.modelRouter=new x(e),this.pretrain=new C(e)}trajectory;modelRouter;pretrain;initialized=!1;async initialize(){this.initialized||(await Promise.all([this.trajectory.initialize(),this.modelRouter.initialize(),this.pretrain.initialize()]),this.initialized=!0)}getStatus(){return{available:this.isAvailable(),features:{trajectories:this.trajectory.isClaudeFlowAvailable(),modelRouting:this.modelRouter.isClaudeFlowAvailable(),pretrain:this.pretrain.isClaudeFlowAvailable(),patternSearch:this.trajectory.isClaudeFlowAvailable()}}}isAvailable(){return this.trajectory.isClaudeFlowAvailable()||this.modelRouter.isClaudeFlowAvailable()||this.pretrain.isClaudeFlowAvailable()}};function N(u){return new S(u)}X();V();var F=Q.create("experience-capture"),_={"catches-bug":1,flaky:-1,"false-positive":-1,"new-coverage":.3,redundant:0,"code-smell":-.5,neutral:0},K=new Set(Object.keys(_));function U(u){return typeof u=="string"&&K.has(u)}function Y(u){if(U(u))return _[u]}var Z={namespace:"qe-experiences",minQualityForPatternExtraction:.7,similarityThreshold:.85,promotionThreshold:P,maxExperiencesPerDomain:1e3,enableCrossDomainSharing:!0,autoCleanup:!0,cleanupIntervalMs:864e5},j=class{constructor(e,t,i,r={}){this.memory=e;this.patternStore=t;this.eventBus=i;this.config={...Z,...r}}config;initialized=!1;cleanupTimer;activeExperiences=new Map;stats={totalCaptured:0,successfulCaptures:0,patternsExtracted:0,patternsPromoted:0,byDomain:new Map};sessionCaptureCount=0;witnessChain;setWitnessChain(e){this.witnessChain=e}async initialize(){this.initialized||(await this.loadStats(),this.config.autoCleanup&&(this.cleanupTimer=setInterval(()=>this.cleanup(),this.config.cleanupIntervalMs)),this.initialized=!0,console.log("[ExperienceCapture] Initialized"))}startCapture(e,t){let i=`exp-${Date.now()}-${D().slice(0,8)}`,r={id:i,task:e,agent:t?.agent,domain:t?.domain,model:t?.model,startedAt:Date.now(),completedAt:0,durationMs:0,steps:[],success:!1,quality:0,trajectoryId:t?.trajectoryId,metadata:t?.metadata};return this.activeExperiences.set(i,r),i}recordStep(e,t){let i=this.activeExperiences.get(e);if(!i){console.warn(`[ExperienceCapture] Experience not found: ${e}`);return}i.steps.push({...t,timestamp:Date.now()})}async completeCapture(e,t){let i=this.activeExperiences.get(e);if(!i)return f(new Error(`Experience not found: ${e}`));let r=Date.now();i.completedAt=r,i.durationMs=r-i.startedAt,i.success=t.success,i.feedback=t.feedback,t.quality!==void 0?i.quality=t.quality:i.quality=this.calculateQuality(i);let n=t.testOutcome??i.metadata?.testOutcome;if(n&&U(n)&&(i.testOutcome=n,i.reward=Y(n)),this.witnessChain&&M().useWitnessChain)try{let s=this.witnessChain.appendWitness({type:"experience-capture",decision:i.success?"PASS":"FAIL",context:{experienceId:i.id,task:i.task,quality:i.quality,domain:i.domain,reward:i.reward},evidence:i.reward});i.witnessHash=s.hash}catch(s){F.warn("Failed to create witness receipt for experience",{experienceId:i.id,error:s instanceof Error?s.message:String(s)})}this.activeExperiences.delete(e),await this.storeExperience(i),this.updateStats(i);let a=i.reward===void 0||i.reward>0;if(i.success&&i.quality>=this.config.minQualityForPatternExtraction&&a){let s=await this.extractPattern(i);(s.newPattern||s.reinforced)&&(i.patterns=[s.patternId])}return this.emitExperienceCaptured(i),w(i)}getActiveExperience(e){return this.activeExperiences.get(e)}getPendingCount(){return this.activeExperiences.size}async flushPending(){let e=Array.from(this.activeExperiences.entries());if(e.length===0)return 0;let t=0;for(let[i,r]of e){let n=Date.now();r.completedAt=n,r.durationMs=n-r.startedAt,r.quality=r.quality||this.calculateQuality(r),r.metadata={...r.metadata,flushedByCompaction:!0},await this.storeExperience(r),this.updateStats(r),this.activeExperiences.delete(i),t++}return F.info(`Flushed ${t} pending experiences before compaction`),t}async getExperience(e){let t=`${this.config.namespace}:experience:${e}`;return await this.memory.get(t)??null}async searchExperiences(e={}){let t=e.limit||100,i=[],r;e.domain?r=await this.memory.search(`${this.config.namespace}:index:domain:${e.domain}:*`,t*2):r=await this.memory.search(`${this.config.namespace}:experience:*`,t*2);for(let n of r){if(i.length>=t)break;let a=n.includes(":index:")?await this.memory.get(n):null,s=a?await this.getExperience(a):await this.memory.get(n);s&&(e.agent&&s.agent!==e.agent||e.success!==void 0&&s.success!==e.success||e.minQuality!==void 0&&s.quality<e.minQuality||i.push(s))}return i}async getStats(){let e={};for(let[t,i]of this.stats.byDomain)e[t]=i;return{totalExperiences:this.stats.totalCaptured,byDomain:e,successRate:this.stats.totalCaptured>0?this.stats.successfulCaptures/this.stats.totalCaptured:0,avgQuality:await this.calculateAvgQuality(),patternsExtracted:this.stats.patternsExtracted,patternsPromoted:this.stats.patternsPromoted}}async extractPattern(e){if(!this.patternStore)return{newPattern:!1,reinforced:!1,promoted:!1};let t=await this.patternStore.search(e.task,{limit:1,domain:e.domain,useVectorSearch:!0});if(t.success&&t.value.length>0){let n=t.value[0];if(n.similarity>=this.config.similarityThreshold){let a=await this.patternStore.recordUsage(n.pattern.id,e.success),s=await this.patternStore.get(n.pattern.id),o=!1;return s&&s.tier==="short-term"&&s.usageCount>=this.config.promotionThreshold&&(await this.patternStore.promote(n.pattern.id)).success&&(o=!0,this.stats.patternsPromoted++,console.log(`[ExperienceCapture] Pattern promoted: ${n.pattern.id} (${s.usageCount} uses)`)),{newPattern:!1,patternId:n.pattern.id,reinforced:a.success,promoted:o}}}let i=this.experienceToPatternOptions(e),r=await this.patternStore.create(i);return r.success?(this.stats.patternsExtracted++,await this.patternStore.recordUsage(r.value.id,e.success),{newPattern:!0,patternId:r.value.id,reinforced:!1,promoted:!1}):{newPattern:!1,reinforced:!1,promoted:!1}}async shareAcrossDomains(e){if(!this.config.enableCrossDomainSharing||!e.domain)return;let t=this.getRelatedDomains(e.domain);for(let i of t){let r=`${this.config.namespace}:shared:${i}:${e.id}`;await this.memory.set(r,{sourceExperience:e.id,sourceDomain:e.domain,sharedAt:Date.now()},{persist:!0})}}async cleanup(){let e=0,t=0;for(let i of this.stats.byDomain.keys()){let r=this.stats.byDomain.get(i)||0;if(r>this.config.maxExperiencesPerDomain){let n=await this.searchExperiences({domain:i,limit:r});n.sort((s,o)=>s.quality-o.quality||s.startedAt-o.startedAt);let a=r-this.config.maxExperiencesPerDomain;for(let s=0;s<Math.min(a,n.length);s++){let o=n[s];await this.softDeleteExperience(o.id),t++}}}return console.log(`[ExperienceCapture] Cleanup: ${t} archived (0 destroyed)`),{removed:0,consolidated:e,archived:t}}async dispose(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0),await this.saveStats(),this.sessionCaptureCount===0&&console.warn("[ExperienceCapture] WARNING: Zero experiences captured this session. Learning cannot improve without experience data. Ensure tasks call startCapture()/completeCapture() to feed the learning loop."),this.activeExperiences.clear(),this.initialized=!1}async storeExperience(e){let t=`${this.config.namespace}:experience:${e.id}`;if(await this.memory.set(t,e,{persist:!0}),e.domain){let i=`${this.config.namespace}:index:domain:${e.domain}:${e.id}`;await this.memory.set(i,e.id,{persist:!0})}if(e.agent){let i=`${this.config.namespace}:index:agent:${e.agent}:${e.id}`;await this.memory.set(i,e.id,{persist:!0})}}async deleteExperience(e){await this.softDeleteExperience(e)}async softDeleteExperience(e){let t=await this.getExperience(e);if(!t)return;let i=`${this.config.namespace}:experience:${e}`,r={...t,_archived:!0};await this.memory.set(i,r,{persist:!0})}calculateQuality(e){if(e.steps.length===0)return e.success?.5:.2;let t=e.steps.filter(r=>r.quality!==void 0);if(t.length===0)return e.success?.6:.3;let i=t.reduce((r,n)=>r+(n.quality||0),0)/t.length;return e.success?Math.min(1,i+.1):Math.max(0,i-.2)}updateStats(e){if(this.stats.totalCaptured++,this.sessionCaptureCount++,e.success&&this.stats.successfulCaptures++,e.domain){let t=this.stats.byDomain.get(e.domain)||0;this.stats.byDomain.set(e.domain,t+1)}}async calculateAvgQuality(){let e=await this.searchExperiences({limit:100});return e.length===0?0:e.reduce((i,r)=>i+r.quality,0)/e.length}experienceToPatternOptions(e){let t=this.detectPatternType(e.task),r=`Task: {{task}}
|
|
18
|
+
`).run(e.id,e.task,e.agent||null,JSON.stringify(e.steps),e.success?1:0,e.feedback||null,e.startedAt,e.completedAt||null),p.close()}catch(t){console.debug("[TrajectoryBridge] Trajectory persistence failed:",t instanceof Error?t.message:t)}}};var H=x(),X={low:[/simple/i,/basic/i,/fix typo/i,/rename/i,/format/i,/add comment/i,/lint/i,/minor/i,/quick/i],high:[/architect/i,/design/i,/complex/i,/security/i,/performance/i,/refactor.*large/i,/critical/i,/analysis/i,/multi.*file/i,/database.*migration/i,/distributed/i,/concurrent/i]},R=class{constructor(e){this.options=e}claudeFlowAvailable=!1;routingHistory=[];async initialize(){this.claudeFlowAvailable=await this.checkClaudeFlow()}async checkClaudeFlow(){return v(this.options.projectRoot).available}async routeTask(e){if(this.claudeFlowAvailable)try{let{execFileSync:t}=await import("child_process"),i=t("npx",["--no-install",H,"hooks","model-route","--task",e],{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot}),r=i.match(/model[:\s]+["']?(haiku|sonnet|opus)/i),n=i.match(/confidence[:\s]+([0-9.]+)/i),a=i.match(/reason(?:ing)?[:\s]+["']?([^"'\n]+)/i);if(r)return{model:r[1].toLowerCase(),confidence:n?parseFloat(n[1]):.7,reasoning:a?.[1]?.trim()}}catch(t){console.debug("[ModelRouterBridge] Claude Flow routing failed:",t instanceof Error?t.message:t)}return this.localRoute(e)}async recordOutcome(e){if(this.routingHistory.push(e),this.routingHistory.length>1e3&&(this.routingHistory=this.routingHistory.slice(-500)),this.claudeFlowAvailable)try{let{execFileSync:t}=await import("child_process");t("npx",["--no-install",H,"hooks","model-outcome","--task",e.task,"--model",e.model,"--outcome",e.outcome],{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot})}catch(t){console.debug("[ModelRouterBridge] Outcome recording failed:",t instanceof Error?t.message:t)}}getStats(){let e={totalRoutings:this.routingHistory.length,modelDistribution:{haiku:0,sonnet:0,opus:0},successRate:{haiku:0,sonnet:0,opus:0}},t={haiku:0,sonnet:0,opus:0};for(let i of this.routingHistory)e.modelDistribution[i.model]++,i.outcome==="success"&&t[i.model]++;for(let i of["haiku","sonnet","opus"]){let r=e.modelDistribution[i];e.successRate[i]=r>0?t[i]/r:0}return e}isClaudeFlowAvailable(){return this.claudeFlowAvailable}localRoute(e){let t=e.toLowerCase();for(let i of X.low)if(i.test(t))return{model:"haiku",confidence:.75,reasoning:"Low complexity task detected - using haiku for speed"};for(let i of X.high)if(i.test(t))return{model:"opus",confidence:.8,reasoning:"High complexity task detected - using opus for capability"};return e.length>500?{model:"opus",confidence:.65,reasoning:"Long task description - using opus for complex reasoning"}:e.length<50?{model:"haiku",confidence:.6,reasoning:"Short task description - using haiku for efficiency"}:{model:"sonnet",confidence:.7,reasoning:"Medium complexity task - using sonnet for balance"}}};q();I();var B=x(),T=class{constructor(e){this.options=e}claudeFlowAvailable=!1;analysisCache=new Map;async initialize(){this.claudeFlowAvailable=await this.checkClaudeFlow()}async checkClaudeFlow(){return v(this.options.projectRoot).available}async analyze(e,t="medium"){let i=e||this.options.projectRoot,r=`${i}:${t}`,n=this.analysisCache.get(r);if(n)return n;if(this.claudeFlowAvailable)try{let{execFileSync:a}=await import("child_process"),s=a("npx",["--no-install",B,"hooks","pretrain","--path",i,"--depth",t],{encoding:"utf-8",timeout:12e4,cwd:this.options.projectRoot});try{let o=k(s),u={success:!0,repositoryPath:i,depth:t,analysis:o.analysis||void 0,agentConfigs:o.agentConfigs};return this.analysisCache.set(r,u),u}catch{return{success:!0,repositoryPath:i,depth:t}}}catch(a){console.debug("[PretrainBridge] Claude Flow analyze failed, using local:",a instanceof Error?a.message:a)}return this.localAnalyze(i,t)}async generateAgentConfigs(e="yaml"){if(this.claudeFlowAvailable)try{let{execFileSync:t}=await import("child_process"),i=t("npx",["--no-install",B,"hooks","build-agents","--format",e],{encoding:"utf-8",timeout:6e4,cwd:this.options.projectRoot});try{return k(i)}catch(r){return console.debug("[PretrainBridge] Agent config parse error:",r instanceof Error?r.message:r),[]}}catch(t){console.debug("[PretrainBridge] Claude Flow generateAgentConfigs failed:",t instanceof Error?t.message:t)}return this.generateLocalAgentConfigs()}async transferPatterns(e,t=.7){if(this.claudeFlowAvailable)try{let{execFileSync:i}=await import("child_process"),r=i("npx",["--no-install",B,"hooks","transfer","--source-path",e,"--min-confidence",String(t)],{encoding:"utf-8",timeout:6e4,cwd:this.options.projectRoot}),n=r.match(/transferred[:\s]+(\d+)/i),a=r.match(/skipped[:\s]+(\d+)/i);return{transferred:n?parseInt(n[1]):0,skipped:a?parseInt(a[1]):0}}catch(i){console.debug("[PretrainBridge] Claude Flow transferPatterns failed:",i instanceof Error?i.message:i)}return{transferred:0,skipped:0}}isClaudeFlowAvailable(){return this.claudeFlowAvailable}async localAnalyze(e,t){try{let i=await import("fast-glob"),{existsSync:r,readFileSync:n}=await import("fs"),{join:a}=await import("path"),s=t==="shallow"?["*.ts","*.js","*.json"]:t==="medium"?["**/*.ts","**/*.js","**/*.json","**/*.py"]:["**/*"],o=["node_modules/**","dist/**","coverage/**",".git/**"],u=await i.default(s,{cwd:e,ignore:o,onlyFiles:!0}),p=new Set,g=new Set;for(let d of u.slice(0,100))(d.endsWith(".ts")||d.endsWith(".tsx"))&&p.add("typescript"),(d.endsWith(".js")||d.endsWith(".jsx"))&&p.add("javascript"),d.endsWith(".py")&&p.add("python"),d.endsWith(".go")&&p.add("go"),d.endsWith(".rs")&&p.add("rust");let w=a(e,"package.json");if(r(w))try{let d=k(n(w,"utf-8")),f={...d.dependencies,...d.devDependencies};f.react&&g.add("react"),f.vue&&g.add("vue"),f.angular&&g.add("angular"),f.vitest&&g.add("vitest"),f.jest&&g.add("jest"),f.playwright&&g.add("playwright"),f.express&&g.add("express"),f.fastify&&g.add("fastify")}catch(d){console.debug("[PretrainBridge] package.json parse error:",d instanceof Error?d.message:d)}let m={success:!0,repositoryPath:e,depth:t,analysis:{languages:Array.from(p),frameworks:Array.from(g),patterns:[],complexity:u.length>500?3:u.length>100?2:1}};return this.analysisCache.set(`${e}:${t}`,m),m}catch(i){return{success:!1,repositoryPath:e,depth:t,error:y(i)}}}generateLocalAgentConfigs(){return[{name:"qe-test-architect",type:"worker",capabilities:["test-generation","test-design"],model:"sonnet"},{name:"qe-coverage-specialist",type:"worker",capabilities:["coverage-analysis","gap-detection"],model:"haiku"},{name:"qe-quality-gate",type:"worker",capabilities:["quality-assessment","risk-scoring"],model:"sonnet"},{name:"qe-security-scanner",type:"worker",capabilities:["security-scanning","vulnerability-detection"],model:"opus"}]}};var D=class{constructor(e){this.options=e;this.trajectory=new P(e),this.modelRouter=new R(e),this.pretrain=new T(e)}trajectory;modelRouter;pretrain;initialized=!1;async initialize(){this.initialized||(await Promise.all([this.trajectory.initialize(),this.modelRouter.initialize(),this.pretrain.initialize()]),this.initialized=!0)}getStatus(){return{available:this.isAvailable(),features:{trajectories:this.trajectory.isClaudeFlowAvailable(),modelRouting:this.modelRouter.isClaudeFlowAvailable(),pretrain:this.pretrain.isClaudeFlowAvailable(),patternSearch:this.trajectory.isClaudeFlowAvailable()}}}isAvailable(){return this.trajectory.isClaudeFlowAvailable()||this.modelRouter.isClaudeFlowAvailable()||this.pretrain.isClaudeFlowAvailable()}};function V(l){return new D(l)}ne();ae();var M=z.create("experience-capture"),J={"catches-bug":1,flaky:-1,"false-positive":-1,"new-coverage":.3,redundant:0,"code-smell":-.5,neutral:0},oe=new Set(Object.keys(J));function K(l){return typeof l=="string"&&oe.has(l)}function ce(l){if(K(l))return J[l]}var le={namespace:"qe-experiences",minQualityForPatternExtraction:.7,similarityThreshold:.85,promotionThreshold:S,maxExperiencesPerDomain:1e3,enableCrossDomainSharing:!0,autoCleanup:!0,cleanupIntervalMs:864e5},Q=class{constructor(e,t,i,r={}){this.memory=e;this.patternStore=t;this.eventBus=i;this.config={...le,...r}}config;initialized=!1;cleanupTimer;activeExperiences=new Map;stats={totalCaptured:0,successfulCaptures:0,patternsExtracted:0,patternsPromoted:0,byDomain:new Map};sessionCaptureCount=0;witnessChain;setWitnessChain(e){this.witnessChain=e}async initialize(){this.initialized||(await this.loadStats(),this.config.autoCleanup&&(this.cleanupTimer=setInterval(()=>this.cleanup(),this.config.cleanupIntervalMs)),this.initialized=!0,console.log("[ExperienceCapture] Initialized"))}startCapture(e,t){let i=`exp-${Date.now()}-${O().slice(0,8)}`,r={id:i,task:e,agent:t?.agent,domain:t?.domain,model:t?.model,startedAt:Date.now(),completedAt:0,durationMs:0,steps:[],success:!1,quality:0,trajectoryId:t?.trajectoryId,metadata:t?.metadata};return this.activeExperiences.set(i,r),i}recordStep(e,t){let i=this.activeExperiences.get(e);if(!i){console.warn(`[ExperienceCapture] Experience not found: ${e}`);return}i.steps.push({...t,timestamp:Date.now()})}async completeCapture(e,t){let i=this.activeExperiences.get(e);if(!i)return E(new Error(`Experience not found: ${e}`));let r=Date.now();i.completedAt=r,i.durationMs=r-i.startedAt,i.success=t.success,i.feedback=t.feedback,t.quality!==void 0?i.quality=t.quality:i.quality=this.calculateQuality(i);let n=t.testOutcome??i.metadata?.testOutcome;if(n&&K(n)&&(i.testOutcome=n,i.reward=ce(n)),this.witnessChain&&N().useWitnessChain)try{let s=this.witnessChain.appendWitness({type:"experience-capture",decision:i.success?"PASS":"FAIL",context:{experienceId:i.id,task:i.task,quality:i.quality,domain:i.domain,reward:i.reward},evidence:i.reward});i.witnessHash=s.hash}catch(s){M.warn("Failed to create witness receipt for experience",{experienceId:i.id,error:s instanceof Error?s.message:String(s)})}this.activeExperiences.delete(e),await this.storeExperience(i),this.updateStats(i);let a=i.reward===void 0||i.reward>0;if(i.success&&i.quality>=this.config.minQualityForPatternExtraction&&a){let s=await this.extractPattern(i);(s.newPattern||s.reinforced)&&(i.patterns=[s.patternId])}return this.emitExperienceCaptured(i),b(i)}getActiveExperience(e){return this.activeExperiences.get(e)}getPendingCount(){return this.activeExperiences.size}async flushPending(){let e=Array.from(this.activeExperiences.entries());if(e.length===0)return 0;let t=0;for(let[i,r]of e){let n=Date.now();r.completedAt=n,r.durationMs=n-r.startedAt,r.quality=r.quality||this.calculateQuality(r),r.metadata={...r.metadata,flushedByCompaction:!0},await this.storeExperience(r),this.updateStats(r),this.activeExperiences.delete(i),t++}return M.info(`Flushed ${t} pending experiences before compaction`),t}async getExperience(e){let t=`${this.config.namespace}:experience:${e}`;return await this.memory.get(t)??null}async searchExperiences(e={}){let t=e.limit||100,i=[],r;e.domain?r=await this.memory.search(`${this.config.namespace}:index:domain:${e.domain}:*`,t*2):r=await this.memory.search(`${this.config.namespace}:experience:*`,t*2);for(let n of r){if(i.length>=t)break;let a=n.includes(":index:")?await this.memory.get(n):null,s=a?await this.getExperience(a):await this.memory.get(n);s&&(e.agent&&s.agent!==e.agent||e.success!==void 0&&s.success!==e.success||e.minQuality!==void 0&&s.quality<e.minQuality||i.push(s))}return i}async getStats(){let e={};for(let[t,i]of this.stats.byDomain)e[t]=i;return{totalExperiences:this.stats.totalCaptured,byDomain:e,successRate:this.stats.totalCaptured>0?this.stats.successfulCaptures/this.stats.totalCaptured:0,avgQuality:await this.calculateAvgQuality(),patternsExtracted:this.stats.patternsExtracted,patternsPromoted:this.stats.patternsPromoted}}async extractPattern(e){if(!this.patternStore)return{newPattern:!1,reinforced:!1,promoted:!1};let t=await this.patternStore.search(e.task,{limit:1,domain:e.domain,useVectorSearch:!0});if(t.success&&t.value.length>0){let n=t.value[0];if(n.similarity>=this.config.similarityThreshold){let a=await this.patternStore.recordUsage(n.pattern.id,e.success),s=await this.patternStore.get(n.pattern.id),o=!1;return s&&s.tier==="short-term"&&s.usageCount>=this.config.promotionThreshold&&(await this.patternStore.promote(n.pattern.id)).success&&(o=!0,this.stats.patternsPromoted++,console.log(`[ExperienceCapture] Pattern promoted: ${n.pattern.id} (${s.usageCount} uses)`)),{newPattern:!1,patternId:n.pattern.id,reinforced:a.success,promoted:o}}}let i=this.experienceToPatternOptions(e),r=await this.patternStore.create(i);return r.success?(this.stats.patternsExtracted++,await this.patternStore.recordUsage(r.value.id,e.success),{newPattern:!0,patternId:r.value.id,reinforced:!1,promoted:!1}):{newPattern:!1,reinforced:!1,promoted:!1}}async shareAcrossDomains(e){if(!this.config.enableCrossDomainSharing||!e.domain)return;let t=this.getRelatedDomains(e.domain);for(let i of t){let r=`${this.config.namespace}:shared:${i}:${e.id}`;await this.memory.set(r,{sourceExperience:e.id,sourceDomain:e.domain,sharedAt:Date.now()},{persist:!0})}}async cleanup(){let e=0,t=0;for(let i of this.stats.byDomain.keys()){let r=this.stats.byDomain.get(i)||0;if(r>this.config.maxExperiencesPerDomain){let n=await this.searchExperiences({domain:i,limit:r});n.sort((s,o)=>s.quality-o.quality||s.startedAt-o.startedAt);let a=r-this.config.maxExperiencesPerDomain;for(let s=0;s<Math.min(a,n.length);s++){let o=n[s];await this.softDeleteExperience(o.id),t++}}}return console.log(`[ExperienceCapture] Cleanup: ${t} archived (0 destroyed)`),{removed:0,consolidated:e,archived:t}}async dispose(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0),await this.saveStats(),this.sessionCaptureCount===0&&console.warn("[ExperienceCapture] WARNING: Zero experiences captured this session. Learning cannot improve without experience data. Ensure tasks call startCapture()/completeCapture() to feed the learning loop."),this.activeExperiences.clear(),this.initialized=!1}async storeExperience(e){let t=`${this.config.namespace}:experience:${e.id}`;if(await this.memory.set(t,e,{persist:!0}),e.domain){let i=`${this.config.namespace}:index:domain:${e.domain}:${e.id}`;await this.memory.set(i,e.id,{persist:!0})}if(e.agent){let i=`${this.config.namespace}:index:agent:${e.agent}:${e.id}`;await this.memory.set(i,e.id,{persist:!0})}}async deleteExperience(e){await this.softDeleteExperience(e)}async softDeleteExperience(e){let t=await this.getExperience(e);if(!t)return;let i=`${this.config.namespace}:experience:${e}`,r={...t,_archived:!0};await this.memory.set(i,r,{persist:!0})}calculateQuality(e){if(e.steps.length===0)return e.success?.5:.2;let t=e.steps.filter(r=>r.quality!==void 0);if(t.length===0)return e.success?.6:.3;let i=t.reduce((r,n)=>r+(n.quality||0),0)/t.length;return e.success?Math.min(1,i+.1):Math.max(0,i-.2)}updateStats(e){if(this.stats.totalCaptured++,this.sessionCaptureCount++,e.success&&this.stats.successfulCaptures++,e.domain){let t=this.stats.byDomain.get(e.domain)||0;this.stats.byDomain.set(e.domain,t+1)}}async calculateAvgQuality(){let e=await this.searchExperiences({limit:100});return e.length===0?0:e.reduce((i,r)=>i+r.quality,0)/e.length}experienceToPatternOptions(e){let t=this.detectPatternType(e.task),r=`Task: {{task}}
|
|
19
19
|
|
|
20
20
|
Steps:
|
|
21
21
|
${e.steps.map((n,a)=>`${a+1}. ${n.action}${n.result?` \u2192 ${n.result}`:""}`).join(`
|
|
22
22
|
`)}
|
|
23
23
|
|
|
24
|
-
Duration: ${e.durationMs}ms`;return{patternType:t,name:this.generatePatternName(e),description:`Pattern extracted from: ${e.task}`,context:{tags:this.extractTags(e),testType:this.detectTestType(e.task)},template:{type:"workflow",content:r,variables:[{name:"task",type:"string",description:"The task to execute",required:!0}]}}}detectPatternType(e){let t=e.toLowerCase();return t.includes("test")||t.includes("spec")?(t.includes("unit")||t.includes("integration")||t.includes("e2e"),"test-template"):t.includes("mock")||t.includes("stub")?"mock-pattern":t.includes("assert")||t.includes("expect")?"assertion-pattern":t.includes("coverage")?"coverage-strategy":t.includes("api")||t.includes("contract")?"api-contract":t.includes("visual")||t.includes("screenshot")?"visual-baseline":t.includes("accessibility")||t.includes("a11y")?"a11y-check":t.includes("performance")||t.includes("perf")?"perf-benchmark":t.includes("flaky")?"flaky-fix":t.includes("refactor")?"refactor-safe":t.includes("error")||t.includes("exception")?"error-handling":"test-template"}generatePatternName(e){let t=e.task.replace(/[^a-zA-Z0-9\s-]/g,"").slice(0,50).trim();return`${e.domain?`[${e.domain}] `:""}${t}`}extractTags(e){let t=[];e.domain&&t.push(e.domain),e.agent&&t.push(e.agent),e.model&&t.push(`model:${e.model}`);let i=e.task.toLowerCase().split(/\s+/),r=["unit","integration","e2e","api","mock","coverage","security"];for(let n of r)i.some(a=>a.includes(n))&&t.push(n);return t}detectTestType(e){let t=e.toLowerCase();if(t.includes("unit"))return"unit";if(t.includes("integration"))return"integration";if(t.includes("e2e")||t.includes("end-to-end"))return"e2e";if(t.includes("contract")||t.includes("api"))return"contract";if(t.includes("smoke"))return"smoke"}getRelatedDomains(e){return{"test-generation":["test-execution","coverage-analysis"],"test-execution":["test-generation","coverage-analysis","quality-assessment"],"coverage-analysis":["test-generation","test-execution"],"quality-assessment":["test-execution","defect-intelligence"],"defect-intelligence":["quality-assessment","code-intelligence"],"requirements-validation":["test-generation","quality-assessment"],"code-intelligence":["defect-intelligence","security-compliance"],"security-compliance":["code-intelligence","quality-assessment"],"contract-testing":["test-generation","test-execution"],"visual-accessibility":["quality-assessment","test-execution"],"chaos-resilience":["test-execution","quality-assessment"],"learning-optimization":[]}[e]||[]}emitExperienceCaptured(e){this.eventBus&&this.eventBus.publish({id:`exp-captured-${e.id}`,type:"learning.ExperienceCaptured",source:"learning-optimization",timestamp:new Date,payload:{experience:e,reward:e.reward,testOutcome:e.testOutcome}})}async loadStats(){try{let e=await this.memory.get(`${this.config.namespace}:stats`);e&&(this.stats.totalCaptured=e.totalCaptured,this.stats.successfulCaptures=e.successfulCaptures,this.stats.patternsExtracted=e.patternsExtracted,this.stats.patternsPromoted=e.patternsPromoted,this.stats.byDomain=new Map(e.byDomain))}catch(e){F.debug("Stats restoration failed, starting fresh",{error:e instanceof Error?e.message:String(e)})}}async saveStats(){try{await this.memory.set(`${this.config.namespace}:stats`,{totalCaptured:this.stats.totalCaptured,successfulCaptures:this.stats.successfulCaptures,patternsExtracted:this.stats.patternsExtracted,patternsPromoted:this.stats.patternsPromoted,byDomain:Array.from(this.stats.byDomain.entries())},{persist:!0})}catch(e){console.error("[ExperienceCapture] Failed to save stats:",e)}}};function G(u,e,t,i){return new j(u,e,t,i)}var ee={enableClaudeFlow:!0,enableExperienceCapture:!0,enablePatternPromotion:!0,promotionThreshold:P},A=class{constructor(e,t,i){this.memory=e;this.eventBus=i;this.config={...ee,...t}}config;reasoningBank;claudeFlowBridge;experienceCapture;patternStore;coherenceService;initialized=!1;_domainTransferEngine=null;_domainTransferInterval=null;activeTasks=new Map;completedTasks=0;claudeFlowErrors=0;async initialize(){if(!this.initialized){try{this.coherenceService=await $(I),this.coherenceService.isInitialized()&&console.log("[AQELearningEngine] CoherenceService initialized with WASM engines")}catch(e){console.log("[AQELearningEngine] CoherenceService WASM unavailable, using fallback:",g(e))}this.patternStore=O(this.memory,{promotionThreshold:this.config.promotionThreshold}),await this.patternStore.initialize(),this.reasoningBank=z(this.memory,this.eventBus,this.config.reasoningBank,this.coherenceService),await this.reasoningBank.initialize();try{let{getSharedRvfDualWriter:e}=await import("./shared-rvf-dual-writer-BVSCQAFS.js"),t=await e();t&&this.reasoningBank.setRvfDualWriter(t)}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] RVF wiring skipped:",e instanceof Error?e.message:e)}if(this.config.enableExperienceCapture){this.experienceCapture=G(this.memory,this.patternStore,this.eventBus,{promotionThreshold:this.config.promotionThreshold}),await this.experienceCapture.initialize();try{let{isWitnessChainFeatureEnabled:e}=await import("./witness-chain-BR63P4A7.js");if(e()){let{createPersistentWitnessChain:t,createWitnessChainSQLitePersistence:i}=await import("./witness-chain-BR63P4A7.js"),{getUnifiedPersistence:r}=await import("./unified-persistence-PFRCWEUG.js"),n=r();if(n.isInitialized()){let a=n.getDatabase(),s=i(a),o=t(s);this.experienceCapture.setWitnessChain(o)}}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Witness chain wiring skipped:",e instanceof Error?e.message:e)}}try{let{isCrossDomainTransferEnabled:e}=await import("./feature-flags-IVQ3AL4Q.js");if(e()&&this.patternStore){let{createDomainTransferEngine:t}=await import("./domain-transfer-5Y4FGJAJ.js"),i=t(),r=this.patternStore,n=await r.getStats();this._domainTransferInterval=setInterval(async()=>{try{n=await r.getStats()}catch(a){process.env.DEBUG&&console.debug("[AQELearningEngine] Stats refresh failed:",a instanceof Error?a.message:a)}},6e4),this._domainTransferInterval.unref?.(),i.setPerformanceProvider(a=>{let s=n.byDomain?.[a]??0,o=n.totalPatterns??0;return{domain:a,successRate:o>0?s/o:.5,avgConfidence:n.avgConfidence??.5,patternCount:s,timestamp:Date.now()}}),this._domainTransferEngine=i}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Domain transfer wiring skipped:",e instanceof Error?e.message:e)}if(this.config.enableClaudeFlow)try{this.claudeFlowBridge=N({projectRoot:this.config.projectRoot}),await this.claudeFlowBridge.initialize(),this.claudeFlowBridge.isAvailable()&&console.log("[AQELearningEngine] Claude Flow integration enabled")}catch(e){process.env.DEBUG&&console.log("[AQELearningEngine] Claude Flow not available, using standalone mode:",g(e))}this.initialized=!0,console.log("[AQELearningEngine] Initialized")}}getStatus(){let e=this.claudeFlowBridge?.getStatus();return{initialized:this.initialized,claudeFlowAvailable:e?.available??!1,features:{patternLearning:!0,vectorSearch:!0,taskRouting:!0,trajectories:e?.features.trajectories??!1,modelRouting:e?.features.modelRouting??!1,pretrain:e?.features.pretrain??!1}}}async getStats(){if(!this.initialized||!this.reasoningBank)throw new Error("Engine not initialized");let e=await this.reasoningBank.getStats(),t=this.experienceCapture?await this.experienceCapture.getStats():{totalExperiences:0,byDomain:{},successRate:0,avgQuality:0,patternsExtracted:0,patternsPromoted:0};return{...e,activeTasks:this.activeTasks.size,completedTasks:this.completedTasks,claudeFlowStatus:this.claudeFlowBridge?.getStatus()??{available:!1,features:{trajectories:!1,modelRouting:!1,pretrain:!1,patternSearch:!1}},claudeFlowErrors:this.claudeFlowErrors,experienceCapture:t}}async storePattern(e){return!this.initialized||!this.reasoningBank?f(new Error("Engine not initialized")):this.reasoningBank.storePattern(e)}async searchPatterns(e,t){return!this.initialized||!this.reasoningBank?f(new Error("Engine not initialized")):this.reasoningBank.searchPatterns(e,t)}async getPattern(e){return!this.initialized||!this.reasoningBank?null:this.reasoningBank.getPattern(e)}async recordOutcome(e){return!this.initialized||!this.reasoningBank?f(new Error("Engine not initialized")):this.reasoningBank.recordOutcome(e)}async routeTask(e){if(!this.initialized||!this.reasoningBank)return f(new Error("Engine not initialized"));let t=await this.searchPatternsForTask(e.task,{limit:5,minConfidence:.4,domain:e.domain});t.success&&t.value.length>0&&await this.trackPatternSearch(e.task,t.value);let i=await this.reasoningBank.routeTask(e);if(i.success&&this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable(),i.success&&t.success){let r=this.enhanceRoutingWithPatterns(i.value,t.value);return w(r)}return i}async route(e,t){let i=await this.routeTask({task:e,context:t});return i.success?i.value:null}async searchPatternsForTask(e,t={}){if(!this.reasoningBank)return w([]);try{return await this.reasoningBank.searchPatterns(e,{limit:t.limit||5,minConfidence:t.minConfidence||.4,domain:t.domain,useVectorSearch:!0})}catch(i){return console.warn("[AQELearningEngine] Pattern search failed:",g(i)),w([])}}async trackPatternSearch(e,t){let i={timestamp:Date.now(),task:e.slice(0,500),patternsFound:t.length,patternIds:t.map(r=>r.pattern.id),avgSimilarity:t.length>0?t.reduce((r,n)=>r+n.similarity,0)/t.length:0};try{let r=`pattern-usage:search:${Date.now()}-${H().slice(0,8)}`;await this.memory.set(r,i,{persist:!0,ttl:10080*60*1e3})}catch(r){console.debug("[AQELearningEngine] Failed to track pattern search:",g(r))}}enhanceRoutingWithPatterns(e,t){let i=t.filter(o=>o.similarity>=.5&&o.pattern.qualityScore>=.3);if(i.length===0)return e;let r=i.map(o=>{let c=o.pattern;return`[Pattern: ${c.name}] ${c.description} (confidence: ${(c.confidence*100).toFixed(0)}%, similarity: ${(o.similarity*100).toFixed(0)}%)`}),n=[...e.guidance,"--- Relevant Patterns ---",...r],a=[...e.patterns,...i.map(o=>o.pattern)],s=i.length>0?`; Found ${i.length} relevant pattern(s) with avg similarity ${(i.reduce((o,c)=>o+c.similarity,0)/i.length*100).toFixed(0)}%`:"";return{...e,patterns:a,guidance:n,reasoning:e.reasoning+s,confidence:Math.min(1,e.confidence+i.length*.02)}}async recommendModel(e){if(this.claudeFlowBridge?.modelRouter.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.modelRouter.routeTask(e)}catch(t){console.debug("[AQELearningEngine] Claude Flow model routing failed:",t instanceof Error?t.message:t)}return this.localModelRoute(e)}async recordModelOutcome(e,t,i){this.claudeFlowBridge?.modelRouter.isClaudeFlowAvailable()&&await this.claudeFlowBridge.modelRouter.recordOutcome({task:e,model:t,outcome:i})}localModelRoute(e){let t=e.toLowerCase(),i=[/simple/i,/basic/i,/fix typo/i,/rename/i,/format/i,/add comment/i,/lint/i,/minor/i,/quick/i,/small/i];for(let n of i)if(n.test(t))return{model:"haiku",confidence:.75,reasoning:"Low complexity task - using haiku for speed"};let r=[/architect/i,/design/i,/complex/i,/security/i,/performance/i,/refactor.*large/i,/critical/i,/analysis/i,/multi.*file/i,/distributed/i,/concurrent/i,/migration/i];for(let n of r)if(n.test(t))return{model:"opus",confidence:.8,reasoning:"High complexity task - using opus for capability"};return e.length>500?{model:"opus",confidence:.65,reasoning:"Long task description - using opus for complex reasoning"}:e.length<50?{model:"haiku",confidence:.6,reasoning:"Short task - using haiku for efficiency"}:{model:"sonnet",confidence:.7,reasoning:"Medium complexity - using sonnet for balance"}}async startTask(e,t,i){let r=`task-${Date.now()}-${H().slice(0,8)}`,n=r;if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{n=await this.claudeFlowBridge.trajectory.startTrajectory(e,t)}catch(o){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow startTrajectory failed (${this.claudeFlowErrors} total errors):`,g(o))}let a;this.experienceCapture&&(a=this.experienceCapture.startCapture(e,{agent:t,domain:i,trajectoryId:n!==r?n:void 0}));let s={id:a||n,task:e,agent:t,startedAt:Date.now(),steps:[]};return this.activeTasks.set(s.id,s),s.id}async recordStep(e,t,i,r){if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{await this.claudeFlowBridge.trajectory.recordStep(e,t,i,r)}catch(a){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow recordStep failed (${this.claudeFlowErrors} total errors):`,g(a))}this.experienceCapture&&this.experienceCapture.recordStep(e,{action:t,result:i,quality:r});let n=this.activeTasks.get(e);n&&n.steps.push({action:t,result:i,quality:r,timestamp:Date.now()})}async endTask(e,t,i){if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{await this.claudeFlowBridge.trajectory.endTrajectory(e,t,i)}catch(n){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow endTrajectory failed (${this.claudeFlowErrors} total errors):`,g(n))}let r=this.activeTasks.get(e);if(r)return this.activeTasks.delete(e),this.completedTasks++,this.config.enableExperienceCapture&&t&&await this.captureExperience(r),r}getTask(e){return this.activeTasks.get(e)}async analyzeCodebase(e,t="medium"){let i=e||this.config.projectRoot;if(this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.pretrain.analyze(i,t)}catch(r){console.debug("[AQELearningEngine] Claude Flow pretrain analyze failed:",r instanceof Error?r.message:r)}return this.localAnalyze(i,t)}async generateAgentConfigs(e="yaml"){if(this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.pretrain.generateAgentConfigs(e)}catch(t){console.debug("[AQELearningEngine] Claude Flow agent config failed:",t instanceof Error?t.message:t)}return[{name:"qe-test-architect",type:"worker",capabilities:["test-generation","test-design"],model:"sonnet"},{name:"qe-coverage-specialist",type:"worker",capabilities:["coverage-analysis","gap-detection"],model:"haiku"},{name:"qe-security-scanner",type:"worker",capabilities:["security-scanning","vulnerability-detection"],model:"opus"}]}async captureExperience(e){if(!this.experienceCapture||!this.config.enableExperienceCapture)return;let t=e.steps.length>0?e.steps.reduce((r,n)=>r+(n.quality??.5),0)/e.steps.length:.5;await this.experienceCapture.completeCapture(e.id,{success:!0,quality:t});let i=await this.experienceCapture.getExperience(e.id);i&&i.quality>=.7&&await this.experienceCapture.shareAcrossDomains(i)}startExperienceCapture(e,t){if(this.experienceCapture)return this.experienceCapture.startCapture(e,t)}getExperienceCaptureService(){return this.experienceCapture}async localAnalyze(e,t){try{let i=await import("fast-glob"),{existsSync:r,readFileSync:n}=await import("fs"),{join:a}=await import("path"),s=t==="shallow"?["*.ts","*.js","*.json"]:t==="medium"?["**/*.ts","**/*.js","**/*.json","**/*.py"]:["**/*"],o=["node_modules/**","dist/**","coverage/**",".git/**"],c=await i.default(s,{cwd:e,ignore:o,onlyFiles:!0}),d=new Set,m=new Set;for(let p of c.slice(0,100))(p.endsWith(".ts")||p.endsWith(".tsx"))&&d.add("typescript"),(p.endsWith(".js")||p.endsWith(".jsx"))&&d.add("javascript"),p.endsWith(".py")&&d.add("python"),p.endsWith(".go")&&d.add("go"),p.endsWith(".rs")&&d.add("rust");let k=a(e,"package.json");if(r(k))try{let p=E(n(k,"utf-8")),l={...p.dependencies,...p.devDependencies};l.react&&m.add("react"),l.vue&&m.add("vue"),l.vitest&&m.add("vitest"),l.jest&&m.add("jest"),l.playwright&&m.add("playwright")}catch(p){console.debug("[AQELearningEngine] package.json parse failed:",p instanceof Error?p.message:p)}return{success:!0,repositoryPath:e,depth:t,analysis:{languages:Array.from(d),frameworks:Array.from(m),patterns:[],complexity:c.length>500?3:c.length>100?2:1}}}catch(i){return{success:!1,repositoryPath:e,depth:t,error:g(i)}}}getGuidance(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.getGuidance(e,t)}generateContext(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.generateContext(e,t)}checkAntiPatterns(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.checkAntiPatterns(e,t)}async dispose(){this._domainTransferInterval&&(clearInterval(this._domainTransferInterval),this._domainTransferInterval=null),this._domainTransferEngine=null,this.experienceCapture&&await this.experienceCapture.dispose(),this.patternStore&&await this.patternStore.dispose(),this.reasoningBank&&await this.reasoningBank.dispose(),this.activeTasks.clear(),this.initialized=!1}};function te(u,e,t){return new A(u,e,t)}function Ne(u,e,t){return te(u,{projectRoot:e},t)}export{ee as a,A as b,te as c,Ne as d};
|
|
24
|
+
Duration: ${e.durationMs}ms`;return{patternType:t,name:this.generatePatternName(e),description:`Pattern extracted from: ${e.task}`,context:{tags:this.extractTags(e),testType:this.detectTestType(e.task)},template:{type:"workflow",content:r,variables:[{name:"task",type:"string",description:"The task to execute",required:!0}]}}}detectPatternType(e){let t=e.toLowerCase();return t.includes("test")||t.includes("spec")?(t.includes("unit")||t.includes("integration")||t.includes("e2e"),"test-template"):t.includes("mock")||t.includes("stub")?"mock-pattern":t.includes("assert")||t.includes("expect")?"assertion-pattern":t.includes("coverage")?"coverage-strategy":t.includes("api")||t.includes("contract")?"api-contract":t.includes("visual")||t.includes("screenshot")?"visual-baseline":t.includes("accessibility")||t.includes("a11y")?"a11y-check":t.includes("performance")||t.includes("perf")?"perf-benchmark":t.includes("flaky")?"flaky-fix":t.includes("refactor")?"refactor-safe":t.includes("error")||t.includes("exception")?"error-handling":"test-template"}generatePatternName(e){let t=e.task.replace(/[^a-zA-Z0-9\s-]/g,"").slice(0,50).trim();return`${e.domain?`[${e.domain}] `:""}${t}`}extractTags(e){let t=[];e.domain&&t.push(e.domain),e.agent&&t.push(e.agent),e.model&&t.push(`model:${e.model}`);let i=e.task.toLowerCase().split(/\s+/),r=["unit","integration","e2e","api","mock","coverage","security"];for(let n of r)i.some(a=>a.includes(n))&&t.push(n);return t}detectTestType(e){let t=e.toLowerCase();if(t.includes("unit"))return"unit";if(t.includes("integration"))return"integration";if(t.includes("e2e")||t.includes("end-to-end"))return"e2e";if(t.includes("contract")||t.includes("api"))return"contract";if(t.includes("smoke"))return"smoke"}getRelatedDomains(e){return{"test-generation":["test-execution","coverage-analysis"],"test-execution":["test-generation","coverage-analysis","quality-assessment"],"coverage-analysis":["test-generation","test-execution"],"quality-assessment":["test-execution","defect-intelligence"],"defect-intelligence":["quality-assessment","code-intelligence"],"requirements-validation":["test-generation","quality-assessment"],"code-intelligence":["defect-intelligence","security-compliance"],"security-compliance":["code-intelligence","quality-assessment"],"contract-testing":["test-generation","test-execution"],"visual-accessibility":["quality-assessment","test-execution"],"chaos-resilience":["test-execution","quality-assessment"],"learning-optimization":[]}[e]||[]}emitExperienceCaptured(e){this.eventBus&&this.eventBus.publish({id:`exp-captured-${e.id}`,type:"learning.ExperienceCaptured",source:"learning-optimization",timestamp:new Date,payload:{experience:e,reward:e.reward,testOutcome:e.testOutcome}})}async loadStats(){try{let e=await this.memory.get(`${this.config.namespace}:stats`);e&&(this.stats.totalCaptured=e.totalCaptured,this.stats.successfulCaptures=e.successfulCaptures,this.stats.patternsExtracted=e.patternsExtracted,this.stats.patternsPromoted=e.patternsPromoted,this.stats.byDomain=new Map(e.byDomain))}catch(e){M.debug("Stats restoration failed, starting fresh",{error:e instanceof Error?e.message:String(e)})}}async saveStats(){try{await this.memory.set(`${this.config.namespace}:stats`,{totalCaptured:this.stats.totalCaptured,successfulCaptures:this.stats.successfulCaptures,patternsExtracted:this.stats.patternsExtracted,patternsPromoted:this.stats.patternsPromoted,byDomain:Array.from(this.stats.byDomain.entries())},{persist:!0})}catch(e){console.error("[ExperienceCapture] Failed to save stats:",e)}}};function Y(l,e,t,i){return new Q(l,e,t,i)}var ue={enableClaudeFlow:!0,enableExperienceCapture:!0,enablePatternPromotion:!0,promotionThreshold:S},L=class{constructor(e,t,i){this.memory=e;this.eventBus=i;this.config={...ue,...t}}config;reasoningBank;claudeFlowBridge;experienceCapture;patternStore;coherenceService;initialized=!1;_domainTransferEngine=null;_domainTransferInterval=null;activeTasks=new Map;completedTasks=0;claudeFlowErrors=0;async initialize(){if(!this.initialized){try{this.coherenceService=await U(G),this.coherenceService.isInitialized()&&console.log("[AQELearningEngine] CoherenceService initialized with WASM engines")}catch(e){console.log("[AQELearningEngine] CoherenceService WASM unavailable, using fallback:",y(e))}this.patternStore=_(this.memory,{promotionThreshold:this.config.promotionThreshold}),await this.patternStore.initialize(),this.reasoningBank=W(this.memory,this.eventBus,this.config.reasoningBank,this.coherenceService),await this.reasoningBank.initialize();try{let{getSharedRvfDualWriter:e}=await import("./shared-rvf-dual-writer-YB7AH6XJ.js"),t=await e();t&&this.reasoningBank.setRvfDualWriter(t)}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] RVF wiring skipped:",e instanceof Error?e.message:e)}if(this.config.enableExperienceCapture){this.experienceCapture=Y(this.memory,this.patternStore,this.eventBus,{promotionThreshold:this.config.promotionThreshold}),await this.experienceCapture.initialize();try{let{isWitnessChainFeatureEnabled:e}=await import("./witness-chain-4WIMYP4X.js");if(e()){let{createPersistentWitnessChain:t,createWitnessChainSQLitePersistence:i}=await import("./witness-chain-4WIMYP4X.js"),{getUnifiedPersistence:r}=await import("./unified-persistence-MDN3SRCR.js"),n=r();if(n.isInitialized()){let a=n.getDatabase(),s=i(a),o=t(s);this.experienceCapture.setWitnessChain(o)}}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Witness chain wiring skipped:",e instanceof Error?e.message:e)}}try{let{isCrossDomainTransferEnabled:e}=await import("./feature-flags-R4QZYTIW.js");if(e()&&this.patternStore){let{createDomainTransferEngine:t}=await import("./domain-transfer-XGIZOR2X.js"),i=t(),r=this.patternStore,n=await r.getStats();this._domainTransferInterval=setInterval(async()=>{try{n=await r.getStats()}catch(a){process.env.DEBUG&&console.debug("[AQELearningEngine] Stats refresh failed:",a instanceof Error?a.message:a)}},6e4),this._domainTransferInterval.unref?.(),i.setPerformanceProvider(a=>{let s=n.byDomain?.[a]??0,o=n.totalPatterns??0;return{domain:a,successRate:o>0?s/o:.5,avgConfidence:n.avgConfidence??.5,patternCount:s,timestamp:Date.now()}}),this._domainTransferEngine=i}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Domain transfer wiring skipped:",e instanceof Error?e.message:e)}if(this.config.enableClaudeFlow)try{this.claudeFlowBridge=V({projectRoot:this.config.projectRoot}),await this.claudeFlowBridge.initialize(),this.claudeFlowBridge.isAvailable()&&console.log("[AQELearningEngine] Claude Flow integration enabled")}catch(e){process.env.DEBUG&&console.log("[AQELearningEngine] Claude Flow not available, using standalone mode:",y(e))}this.initialized=!0,console.log("[AQELearningEngine] Initialized")}}getStatus(){let e=this.claudeFlowBridge?.getStatus();return{initialized:this.initialized,claudeFlowAvailable:e?.available??!1,features:{patternLearning:!0,vectorSearch:!0,taskRouting:!0,trajectories:e?.features.trajectories??!1,modelRouting:e?.features.modelRouting??!1,pretrain:e?.features.pretrain??!1}}}async getStats(){if(!this.initialized||!this.reasoningBank)throw new Error("Engine not initialized");let e=await this.reasoningBank.getStats(),t=this.experienceCapture?await this.experienceCapture.getStats():{totalExperiences:0,byDomain:{},successRate:0,avgQuality:0,patternsExtracted:0,patternsPromoted:0};return{...e,activeTasks:this.activeTasks.size,completedTasks:this.completedTasks,claudeFlowStatus:this.claudeFlowBridge?.getStatus()??{available:!1,features:{trajectories:!1,modelRouting:!1,pretrain:!1,patternSearch:!1}},claudeFlowErrors:this.claudeFlowErrors,experienceCapture:t}}async storePattern(e){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.storePattern(e)}async searchPatterns(e,t){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.searchPatterns(e,t)}async getPattern(e){return!this.initialized||!this.reasoningBank?null:this.reasoningBank.getPattern(e)}async recordOutcome(e){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.recordOutcome(e)}async routeTask(e){if(!this.initialized||!this.reasoningBank)return E(new Error("Engine not initialized"));let t=await this.searchPatternsForTask(e.task,{limit:5,minConfidence:.4,domain:e.domain});t.success&&t.value.length>0&&await this.trackPatternSearch(e.task,t.value);let i=await this.reasoningBank.routeTask(e);if(i.success&&this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable(),i.success&&t.success){let r=this.enhanceRoutingWithPatterns(i.value,t.value);return b(r)}return i}async route(e,t){let i=await this.routeTask({task:e,context:t});return i.success?i.value:null}async searchPatternsForTask(e,t={}){if(!this.reasoningBank)return b([]);try{return await this.reasoningBank.searchPatterns(e,{limit:t.limit||5,minConfidence:t.minConfidence||.4,domain:t.domain,useVectorSearch:!0})}catch(i){return console.warn("[AQELearningEngine] Pattern search failed:",y(i)),b([])}}async trackPatternSearch(e,t){let i={timestamp:Date.now(),task:e.slice(0,500),patternsFound:t.length,patternIds:t.map(r=>r.pattern.id),avgSimilarity:t.length>0?t.reduce((r,n)=>r+n.similarity,0)/t.length:0};try{let r=`pattern-usage:search:${Date.now()}-${Z().slice(0,8)}`;await this.memory.set(r,i,{persist:!0,ttl:10080*60*1e3})}catch(r){console.debug("[AQELearningEngine] Failed to track pattern search:",y(r))}}enhanceRoutingWithPatterns(e,t){let i=t.filter(o=>o.similarity>=.5&&o.pattern.qualityScore>=.3);if(i.length===0)return e;let r=i.map(o=>{let u=o.pattern;return`[Pattern: ${u.name}] ${u.description} (confidence: ${(u.confidence*100).toFixed(0)}%, similarity: ${(o.similarity*100).toFixed(0)}%)`}),n=[...e.guidance,"--- Relevant Patterns ---",...r],a=[...e.patterns,...i.map(o=>o.pattern)],s=i.length>0?`; Found ${i.length} relevant pattern(s) with avg similarity ${(i.reduce((o,u)=>o+u.similarity,0)/i.length*100).toFixed(0)}%`:"";return{...e,patterns:a,guidance:n,reasoning:e.reasoning+s,confidence:Math.min(1,e.confidence+i.length*.02)}}async recommendModel(e){if(this.claudeFlowBridge?.modelRouter.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.modelRouter.routeTask(e)}catch(t){console.debug("[AQELearningEngine] Claude Flow model routing failed:",t instanceof Error?t.message:t)}return this.localModelRoute(e)}async recordModelOutcome(e,t,i){this.claudeFlowBridge?.modelRouter.isClaudeFlowAvailable()&&await this.claudeFlowBridge.modelRouter.recordOutcome({task:e,model:t,outcome:i})}localModelRoute(e){let t=e.toLowerCase(),i=[/simple/i,/basic/i,/fix typo/i,/rename/i,/format/i,/add comment/i,/lint/i,/minor/i,/quick/i,/small/i];for(let n of i)if(n.test(t))return{model:"haiku",confidence:.75,reasoning:"Low complexity task - using haiku for speed"};let r=[/architect/i,/design/i,/complex/i,/security/i,/performance/i,/refactor.*large/i,/critical/i,/analysis/i,/multi.*file/i,/distributed/i,/concurrent/i,/migration/i];for(let n of r)if(n.test(t))return{model:"opus",confidence:.8,reasoning:"High complexity task - using opus for capability"};return e.length>500?{model:"opus",confidence:.65,reasoning:"Long task description - using opus for complex reasoning"}:e.length<50?{model:"haiku",confidence:.6,reasoning:"Short task - using haiku for efficiency"}:{model:"sonnet",confidence:.7,reasoning:"Medium complexity - using sonnet for balance"}}async startTask(e,t,i){let r=`task-${Date.now()}-${Z().slice(0,8)}`,n=r;if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{n=await this.claudeFlowBridge.trajectory.startTrajectory(e,t)}catch(o){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow startTrajectory failed (${this.claudeFlowErrors} total errors):`,y(o))}let a;this.experienceCapture&&(a=this.experienceCapture.startCapture(e,{agent:t,domain:i,trajectoryId:n!==r?n:void 0}));let s={id:a||n,task:e,agent:t,startedAt:Date.now(),steps:[]};return this.activeTasks.set(s.id,s),s.id}async recordStep(e,t,i,r){if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{await this.claudeFlowBridge.trajectory.recordStep(e,t,i,r)}catch(a){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow recordStep failed (${this.claudeFlowErrors} total errors):`,y(a))}this.experienceCapture&&this.experienceCapture.recordStep(e,{action:t,result:i,quality:r});let n=this.activeTasks.get(e);n&&n.steps.push({action:t,result:i,quality:r,timestamp:Date.now()})}async endTask(e,t,i){if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{await this.claudeFlowBridge.trajectory.endTrajectory(e,t,i)}catch(n){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow endTrajectory failed (${this.claudeFlowErrors} total errors):`,y(n))}let r=this.activeTasks.get(e);if(r)return this.activeTasks.delete(e),this.completedTasks++,this.config.enableExperienceCapture&&t&&await this.captureExperience(r),r}getTask(e){return this.activeTasks.get(e)}async analyzeCodebase(e,t="medium"){let i=e||this.config.projectRoot;if(this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.pretrain.analyze(i,t)}catch(r){console.debug("[AQELearningEngine] Claude Flow pretrain analyze failed:",r instanceof Error?r.message:r)}return this.localAnalyze(i,t)}async generateAgentConfigs(e="yaml"){if(this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.pretrain.generateAgentConfigs(e)}catch(t){console.debug("[AQELearningEngine] Claude Flow agent config failed:",t instanceof Error?t.message:t)}return[{name:"qe-test-architect",type:"worker",capabilities:["test-generation","test-design"],model:"sonnet"},{name:"qe-coverage-specialist",type:"worker",capabilities:["coverage-analysis","gap-detection"],model:"haiku"},{name:"qe-security-scanner",type:"worker",capabilities:["security-scanning","vulnerability-detection"],model:"opus"}]}async captureExperience(e){if(!this.experienceCapture||!this.config.enableExperienceCapture)return;let t=e.steps.length>0?e.steps.reduce((r,n)=>r+(n.quality??.5),0)/e.steps.length:.5;await this.experienceCapture.completeCapture(e.id,{success:!0,quality:t});let i=await this.experienceCapture.getExperience(e.id);i&&i.quality>=.7&&await this.experienceCapture.shareAcrossDomains(i)}startExperienceCapture(e,t){if(this.experienceCapture)return this.experienceCapture.startCapture(e,t)}getExperienceCaptureService(){return this.experienceCapture}async localAnalyze(e,t){try{let i=await import("fast-glob"),{existsSync:r,readFileSync:n}=await import("fs"),{join:a}=await import("path"),s=t==="shallow"?["*.ts","*.js","*.json"]:t==="medium"?["**/*.ts","**/*.js","**/*.json","**/*.py"]:["**/*"],o=["node_modules/**","dist/**","coverage/**",".git/**"],u=await i.default(s,{cwd:e,ignore:o,onlyFiles:!0}),p=new Set,g=new Set;for(let m of u.slice(0,100))(m.endsWith(".ts")||m.endsWith(".tsx"))&&p.add("typescript"),(m.endsWith(".js")||m.endsWith(".jsx"))&&p.add("javascript"),m.endsWith(".py")&&p.add("python"),m.endsWith(".go")&&p.add("go"),m.endsWith(".rs")&&p.add("rust");let w=a(e,"package.json");if(r(w))try{let m=k(n(w,"utf-8")),d={...m.dependencies,...m.devDependencies};d.react&&g.add("react"),d.vue&&g.add("vue"),d.vitest&&g.add("vitest"),d.jest&&g.add("jest"),d.playwright&&g.add("playwright")}catch(m){console.debug("[AQELearningEngine] package.json parse failed:",m instanceof Error?m.message:m)}return{success:!0,repositoryPath:e,depth:t,analysis:{languages:Array.from(p),frameworks:Array.from(g),patterns:[],complexity:u.length>500?3:u.length>100?2:1}}}catch(i){return{success:!1,repositoryPath:e,depth:t,error:y(i)}}}getGuidance(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.getGuidance(e,t)}generateContext(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.generateContext(e,t)}checkAntiPatterns(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.checkAntiPatterns(e,t)}async dispose(){this._domainTransferInterval&&(clearInterval(this._domainTransferInterval),this._domainTransferInterval=null),this._domainTransferEngine=null,this.experienceCapture&&await this.experienceCapture.dispose(),this.patternStore&&await this.patternStore.dispose(),this.reasoningBank&&await this.reasoningBank.dispose(),this.activeTasks.clear(),this.initialized=!1}},de={enabled:!1,snapshotIntervalMs:3e5,minSnapshotsForAnalysis:5,autoApplyThreshold:.8},ee=class{config;constructor(e){this.config={...de,...e}}runMetaLearningCycle(e){if(process.env.AQE_META_LEARNING_ENABLED!=="true")return[];if(!this.config.enabled)return[];if(e.length<this.config.minSnapshotsForAnalysis)return[];let t=Math.floor(e.length/2),i=e.slice(0,t),r=e.slice(t),n=[],a=Date.now(),s=h(i.map(c=>c.tokenMetrics.costUsd)),o=h(r.map(c=>c.tokenMetrics.costUsd)),u=h(i.map(c=>c.tokenMetrics.savingsUsd)),p=h(r.map(c=>c.tokenMetrics.savingsUsd));if(o>s*1.1&&p<=u*1.05){let c=Math.min(1,(o-s)/(s||1));n.push({id:`meta-tw-${a}`,type:"token-waste",description:`Token cost increased by ${((o/(s||1)-1)*100).toFixed(1)}% while savings remained flat`,confidence:F(c),suggestedAction:"Review cache configuration and increase pattern reuse thresholds",detectedAt:a})}let g=h(i.map(c=>c.qualityMetrics.gatePassRate)),w=h(r.map(c=>c.qualityMetrics.gatePassRate));Math.abs(w-g)<.02&&e.length>=this.config.minSnapshotsForAnalysis&&n.push({id:`meta-qp-${a}`,type:"quality-plateau",description:`Gate pass rate has been flat at ${(w*100).toFixed(1)}% across ${e.length} snapshots`,confidence:F(.6+(e.length-this.config.minSnapshotsForAnalysis)*.05),suggestedAction:"Consider reviewing quality thresholds or adding new test coverage domains",detectedAt:a});let d=h(i.map(c=>c.learningMetrics.patternCount)),f=h(r.map(c=>c.learningMetrics.patternCount)),te=h(i.map(c=>c.learningMetrics.averageConfidence)),$=h(r.map(c=>c.learningMetrics.averageConfidence)),ie=Math.abs(f-d),re=Math.abs($-te);ie<1&&re<.02&&n.push({id:`meta-ls-${a}`,type:"learning-stall",description:`Pattern count (~${Math.round(f)}) and confidence (~${$.toFixed(2)}) have stagnated`,confidence:F(.65+(e.length-this.config.minSnapshotsForAnalysis)*.04),suggestedAction:"Expand to new QE domains or lower pattern creation thresholds to encourage exploration",detectedAt:a});let C=h(i.map(c=>c.performanceMetrics.p95LatencyMs)),A=h(r.map(c=>c.performanceMetrics.p95LatencyMs));if(A>C*1.2&&C>0){let c=Math.min(1,(A-C)/(C||1));n.push({id:`meta-pr-${a}`,type:"performance-regression",description:`P95 latency increased from ${C.toFixed(0)}ms to ${A.toFixed(0)}ms`,confidence:F(c),suggestedAction:"Profile hot paths and consider HNSW index tuning or batch size reduction",detectedAt:a})}return n}shouldAutoApply(e,t){let i=(t??this.config).autoApplyThreshold;return e.confidence>=i}};function h(l){return l.length===0?0:l.reduce((e,t)=>e+t,0)/l.length}function F(l){return Math.max(0,Math.min(1,l))}function pe(l,e,t){return new L(l,e,t)}function et(l,e,t){return pe(l,{projectRoot:e},t)}export{ue as a,L as b,de as c,ee as d,pe as e,et as f};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
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.2");process.exit(0)}
|
|
2
2
|
var p={"||":1,"&&":2,"===":3,"!==":3,"==":3,"!=":3,"<":4,">":4,"<=":4,">=":4,"+":5,"-":5,"*":6,"/":6,"%":6},l=new Set(Object.keys(p)),w=new Set(["!","-","+"]);function h(r){let n=[],e=0;for(;e<r.length;){let t=r[e];if(/\s/.test(t)){e++;continue}if(/\d/.test(t)||t==="."&&/\d/.test(r[e+1])){let s="";for(;e<r.length&&/[\d.]/.test(r[e]);)s+=r[e++];n.push({type:"NUMBER",value:parseFloat(s),raw:s});continue}if(t==='"'||t==="'"){let s=t,u="";for(e++;e<r.length&&r[e]!==s;){if(r[e]==="\\"&&e+1<r.length){e++;let c=r[e];switch(c){case"n":u+=`
|
|
3
3
|
`;break;case"t":u+=" ";break;case"r":u+="\r";break;default:u+=c}}else u+=r[e];e++}e++,n.push({type:"STRING",value:u,raw:`${s}${u}${s}`});continue}if(/[a-zA-Z_$]/.test(t)){let s="";for(;e<r.length&&/[a-zA-Z0-9_$]/.test(r[e]);)s+=r[e++];s==="true"?n.push({type:"BOOLEAN",value:!0,raw:s}):s==="false"?n.push({type:"BOOLEAN",value:!1,raw:s}):s==="null"?n.push({type:"NULL",value:null,raw:s}):s==="undefined"?n.push({type:"UNDEFINED",value:void 0,raw:s}):n.push({type:"IDENTIFIER",value:s,raw:s});continue}let a=r.slice(e,e+2),o=r.slice(e,e+3);if(o==="==="||o==="!=="){n.push({type:"OPERATOR",value:o,raw:o}),e+=3;continue}if(a==="=="||a==="!="||a==="<="||a===">="||a==="&&"||a==="||"){n.push({type:"OPERATOR",value:a,raw:a}),e+=2;continue}if(t==="("){n.push({type:"LPAREN",value:"(",raw:"("}),e++;continue}if(t===")"){n.push({type:"RPAREN",value:")",raw:")"}),e++;continue}if(t==="."){n.push({type:"DOT",value:".",raw:"."}),e++;continue}if("+-*/%<>!".includes(t)){n.push({type:"OPERATOR",value:t,raw:t}),e++;continue}throw new Error(`Unexpected character at position ${e}: ${t}`)}return n.push({type:"EOF",value:"",raw:""}),n}var i=class{tokens;pos=0;context;constructor(n,e){this.tokens=n,this.context=e}current(){return this.tokens[this.pos]}advance(){return this.tokens[this.pos++]}expect(n){let e=this.current();if(e.type!==n)throw new Error(`Expected ${n}, got ${e.type}`);return this.advance()}parse(){let n=this.parseExpression(0);if(this.current().type!=="EOF")throw new Error(`Unexpected token: ${this.current().raw}`);return n}parseExpression(n){let e=this.parseUnary();for(;;){let t=this.current();if(t.type!=="OPERATOR"||!l.has(t.value))break;let a=p[t.value];if(a<n)break;let o=this.advance().value,s=this.parseExpression(a+1);e=this.applyBinaryOperator(o,e,s)}return e}parseUnary(){let n=this.current();if(n.type==="OPERATOR"&&w.has(n.value)){let e=this.advance().value,t=this.parseUnary();return this.applyUnaryOperator(e,t)}return this.parsePrimary()}parsePrimary(){let n=this.current();switch(n.type){case"NUMBER":case"STRING":case"BOOLEAN":case"NULL":case"UNDEFINED":return this.advance(),n.value;case"IDENTIFIER":return this.parseIdentifier();case"LPAREN":this.advance();let e=this.parseExpression(0);return this.expect("RPAREN"),e;default:throw new Error(`Unexpected token: ${n.raw}`)}}parseIdentifier(){let n=this.context,e=this.advance().value;for(typeof n=="object"&&n!==null&&(e in n)?n=n[e]:n=void 0;this.current().type==="DOT";){this.advance();let t=this.expect("IDENTIFIER").value;n!=null&&typeof n=="object"?n=n[t]:n=void 0}return n}applyBinaryOperator(n,e,t){switch(n){case"===":return e===t;case"!==":return e!==t;case"==":return e==t;case"!=":return e!=t;case"<":return e<t;case">":return e>t;case"<=":return e<=t;case">=":return e>=t;case"&&":return e&&t;case"||":return e||t;case"+":return e+t;case"-":return e-t;case"*":return e*t;case"/":return e/t;case"%":return e%t;default:throw new Error(`Unknown operator: ${n}`)}}applyUnaryOperator(n,e){switch(n){case"!":return!e;case"-":return-e;case"+":return+e;default:throw new Error(`Unknown unary operator: ${n}`)}}};function E(r,n={}){if(!r||typeof r!="string")throw new Error("Expression must be a non-empty string");let e=[/\beval\b/i,/\bFunction\b/,/\bconstructor\b/,/\b__proto__\b/,/\bprototype\b/,/\bimport\b/,/\brequire\b/,/\bprocess\b/,/\bglobal\b/,/\bwindow\b/,/\bdocument\b/,/\[\s*['"`]/,/\[.*\]/];for(let o of e)if(o.test(r))throw new Error(`Expression contains potentially dangerous pattern: ${r}`);let t=h(r.trim());return new i(t,n).parse()}function b(r,n={},e=!1){try{return!!E(r,n)}catch(t){return console.warn(`[SafeEvaluator] Failed to evaluate expression: ${r}`,t),e}}export{b as a};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
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.2");process.exit(0)}
|
|
2
2
|
var i=class{s0;s1;s2;s3;constructor(s){this.s0=this.splitmix32(s),this.s1=this.splitmix32(this.s0),this.s2=this.splitmix32(this.s1),this.s3=this.splitmix32(this.s2)}splitmix32(s){return s=s+2654435769|0,s=Math.imul(s^s>>>16,2246822507),s=Math.imul(s^s>>>13,3266489909),(s^s>>>16)>>>0}next(){let s=this.s3,t=this.s0;return this.s3=this.s2,this.s2=this.s1,this.s1=t,t^=t<<11,t^=t>>>8,this.s0=t^s^s>>>19,this.s0>>>0}nextFloat(){return this.next()/4294967296}nextGaussian(){let s=this.nextFloat()||1e-10,t=this.nextFloat();return Math.sqrt(-2*Math.log(s))*Math.cos(2*Math.PI*t)}};export{i as a};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
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.2");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
|
-
if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{f as d}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.2");process.exit(0)}
|
|
2
|
+
import{f as d}from"./chunk-AA33R5U4.js";import{a as u,c as g}from"./chunk-SDTVHR63.js";g();var m=[{type:"email",pattern:/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,mask:n=>n[0]+"***@"+n.split("@")[1]},{type:"ssn",pattern:/\b\d{3}-\d{2}-\d{4}\b/g,mask:()=>"***-**-****"},{type:"credit-card",pattern:/\b(?:\d[ -]*?){13,19}\b/g,mask:n=>"****-****-****-"+n.replace(/\D/g,"").slice(-4)},{type:"phone",pattern:/\b(?:\+?1[-.\s]?)?(?:\(?\d{3}\)?[-.\s]?)?\d{3}[-.\s]?\d{4}\b/g,mask:n=>n.slice(0,3)+"***"+n.slice(-2)},{type:"api-key",pattern:/(?:key|token|api_key|apikey|secret|password|passwd|auth)=([A-Za-z0-9_\-]{16,})/gi,mask:()=>"***REDACTED***"}],y=class extends d{config={name:"qe/security/url-validate",description:"Validate URL security: checks for XSS/injection patterns, unsafe protocols, and scans URL query parameters for PII exposure (emails, SSNs, credit cards, API keys).",domain:"security-compliance",schema:this.buildSchema()};buildSchema(){return{type:"object",properties:{url:{type:"string",description:"URL to validate for security threats and PII exposure"},enablePII:{type:"boolean",description:"Enable PII exposure scanning in URL and query parameters",default:!0}},required:["url"]}}async execute(s,r){try{let e=this.validateURLSecurity(s.url),t=s.enablePII!==!1?this.scanForPII(s.url):{scanned:!1,found:!1,types:[],details:[]},c=e.issues.length+(t.found?t.types.length:0)===0?`URL passed all checks (security: clean, PII: ${t.scanned?"none found":"not scanned"})`:`URL has ${e.issues.length} security issue(s)${t.found?` and ${t.types.length} PII type(s) exposed in URL`:""}`;return{success:!0,data:{url:s.url,urlSecurity:e,piiExposure:t,summary:c}}}catch(e){return{success:!1,error:u(e)}}}validateURLSecurity(s){let r=[],e="none";try{let t=new URL(s);["http:","https:"].includes(t.protocol)||(r.push({type:"unsafe-protocol",description:`Protocol ${t.protocol} is not allowed`,severity:"high"}),e="high");let o=[/<script/i,/javascript:/i,/on\w+=/i,/data:text\/html/i];for(let i of o)if(i.test(s)){r.push({type:"xss",description:"Potential XSS pattern detected in URL",severity:"critical"}),e="critical";break}let c=[/'.*or.*'/i,/union.*select/i,/drop.*table/i,/;\s*--/i];for(let i of c)if(i.test(s)){r.push({type:"sql-injection",description:"Potential SQL injection pattern detected in URL",severity:"critical"}),e="critical";break}/\.\.[/\\]/.test(s)&&(r.push({type:"path-traversal",description:"Potential path traversal pattern (../) detected",severity:"high"}),e!=="critical"&&(e="high"));let a=["redirect","url","next","return","returnUrl","goto"];for(let i of a){let l=t.searchParams.get(i);l&&/^https?:\/\//.test(l)&&(r.push({type:"open-redirect",description:`Query parameter "${i}" contains an external URL \u2014 potential open redirect`,severity:"medium"}),e==="none"&&(e="medium"))}}catch{r.push({type:"invalid-url",description:"URL could not be parsed",severity:"critical"}),e="critical"}return{valid:r.length===0,riskLevel:e,issues:r}}scanForPII(s){let r=[],e=new Set,t;try{t=decodeURIComponent(s)}catch{t=s}let o="",c="";try{let a=new URL(t);o=a.search,c=a.pathname}catch{o=t}for(let{type:a,pattern:i,mask:l}of m){i.lastIndex=0;let p;for(;(p=i.exec(t))!==null;){e.add(a);let h=o.includes(p[0])?"query-parameter":c.includes(p[0])?"path":"url";r.push({type:a,location:h,masked:l(p[0])})}}return{scanned:!0,found:e.size>0,types:Array.from(e),details:r}}};export{y as a};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{a as F,c as D}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.2");process.exit(0)}
|
|
2
|
+
import{a as F,c as D}from"./chunk-SDTVHR63.js";import{d as $}from"./chunk-4DAOZQ3V.js";$();D();var b=null,l=null,d=null,g=!1,f="",h={modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0,enableCache:!0,maxCacheSize:1e4},o=new Map,P=36e5;function I(t){let e=t.trim();return!!(e.startsWith("{")&&/["']metrics["']/.test(e)||e.startsWith("[")&&e.endsWith("]")&&e.length>50||(e.match(/[a-zA-Z]/g)||[]).length/Math.max(e.length,1)<.3&&e.length>20)}async function A(t={}){if(g)throw new Error(`Transformer initialization previously failed: ${f}`);if(d)return d;let e={...h,...t};return d=(async()=>{try{b=(await import("./transformers-6DBLXPV7.js")).pipeline,console.log(`[RealEmbeddings] Loading model: ${e.modelName}`);let a=performance.now();l=await b("feature-extraction",e.modelName,{quantized:e.quantized});let s=performance.now()-a;console.log(`[RealEmbeddings] Model loaded in ${s.toFixed(0)}ms`)}catch(r){throw g=!0,f=F(r),new Error(`Failed to initialize transformer model: ${f}`)}})(),d}async function q(t,e={}){let r={...h,...e};if(I(t))return new Array(N()).fill(0);if(r.enableCache){let i=o.get(t);if(i&&Date.now()-i.timestamp<P)return i.embedding}if(l||await A(e),!l)throw new Error("Embedding model failed to initialize");let a=performance.now(),s=await l(t,{pooling:"mean",normalize:!0}),m=Array.from(s.data),n=performance.now()-a;if(n>500&&console.warn(`[RealEmbeddings] Slow embedding computation: ${n.toFixed(1)}ms for "${t.slice(0,50)}..."`),r.enableCache){if(o.size>=r.maxCacheSize){let i=o.keys().next().value;i&&o.delete(i)}o.set(t,{embedding:m,timestamp:Date.now()})}return m}async function B(t,e={}){let r={...h,...e},a=[],s=[],m=new Array(t.length).fill(null);if(r.enableCache)for(let n=0;n<t.length;n++){let i=o.get(t[n]);i&&Date.now()-i.timestamp<P?m[n]=i.embedding:(a.push(t[n]),s.push(n))}else{a.push(...t);for(let n=0;n<t.length;n++)s.push(n)}if(a.length>0){if(l||await A(e),!l)throw new Error("Embedding model failed to initialize");let n=performance.now(),i=32;for(let c=0;c<a.length;c+=i){let M=Math.min(c+i,a.length),p=a.slice(c,M),E=await l(p,{pooling:"mean",normalize:!0}),w=E.dims||[p.length,384],R=w[0],C=w[1];for(let u=0;u<R;u++){let z=u*C,x=Array.from(E.data.slice(z,z+C)),y=c+u,v=s[y];if(m[v]=x,r.enableCache){if(o.size>=r.maxCacheSize){let T=o.keys().next().value;T&&o.delete(T)}o.set(a[y],{embedding:x,timestamp:Date.now()})}}}let S=performance.now()-n;console.log(`[RealEmbeddings] Batch computed ${a.length} embeddings in ${S.toFixed(0)}ms`)}return m.filter(n=>n!==null)}function O(){o.clear(),console.log("[RealEmbeddings] Cache cleared")}function W(){return{size:o.size,hitRate:0}}function k(){return!g&&l!==null}function N(){return 384}function G(){b=null,l=null,d=null,g=!1,f="",o.clear()}export{h as a,q as b,B as c,O as d,W as e,k as f,N as g,G as h};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{a as T}from"./chunk-3JPRUND5.js";import{c as S}from"./chunk-4VUPRTVX.js";import{b as C,d as P}from"./chunk-WGMPEW2T.js";import{a as w,c as $}from"./chunk-JZSDOIXA.js";import{a as b,d as M}from"./chunk-DRT3WKQW.js";$();M();import{randomUUID as D}from"crypto";var V={topology:"hierarchical",maxConcurrentSkills:10,maxConcurrentModels:3,timeout:3e5,continueOnFailure:!0,retry:{maxRetries:2,retryDelayMs:1e3}},R=class{config;learner;skillValidator=null;workers=new Map;taskQueue=[];isRunning=!1;constructor(e,t){this.config={...V,...e},this.learner=t}setSkillValidator(e){this.skillValidator=e}async validateSkillsParallel(e,t,i){let s=Date.now(),a=i?.trustTier??3,n=i?.validationLevel??"eval",c=this.determineTopology(e.length,t.length),r=this.createValidationTasks(e,t,a,n),o=await this.executeTasksParallel(r,c),l=new Map;for(let u of o){let p=l.get(u.skill)||[];p.push(u),l.set(u.skill,p)}return await this.recordOutcomesToLearner(o,a,n),l}async validateSkillCrossModel(e,t,i){return(await this.validateSkillsParallel([e],t,i)).get(e)||[]}getSummary(e){let t=[],i=new Map,s=new Map;for(let[c,r]of e){i.set(c,r);for(let o of r){t.push(o);let l=s.get(o.model)||[];l.push(o),s.set(o.model,l)}}let a=t.filter(c=>c.errors.length===0&&c.evalPassRate>=.9).length,n=t.reduce((c,r)=>c+r.durationMs,0);return{totalSkills:i.size,totalModels:s.size,successCount:a,failureCount:t.length-a,overallPassRate:t.length>0?a/t.length:0,totalDurationMs:n,avgDurationMs:t.length>0?n/t.length:0,topology:this.config.topology,bySkill:i,byModel:s,results:t}}determineTopology(e,t){if(this.config.topology){let i=e*t;return i>20&&this.config.topology==="mesh"&&console.warn(`[SwarmSkillValidator] Large workload (${i} tasks) may be more efficient with hierarchical topology`),this.config.topology}return e>5||e>t*2?"hierarchical":t>5&&e<=3?"mesh":"hierarchical"}createValidationTasks(e,t,i,s){let a=[];for(let n of e)for(let c of t)a.push({id:`${n}-${c}-${Date.now()}-${D().slice(0,8)}`,skill:n,model:c,trustTier:i,validationLevel:s,timeout:this.config.timeout,retryCount:0});return a}async executeTasksParallel(e,t){this.isRunning=!0,this.taskQueue=[...e];let i=[],s=t==="hierarchical"?this.config.maxConcurrentSkills:Math.min(this.config.maxConcurrentSkills*this.config.maxConcurrentModels,e.length),a=[];for(let n=0;n<Math.min(s,e.length);n++){let c=`worker-${n}`;this.workers.set(c,{id:c,task:null,status:"idle"}),a.push(this.runWorker(c,i))}return await Promise.all(a),this.isRunning=!1,this.workers.clear(),i}async runWorker(e,t){let i=this.workers.get(e);if(i){for(;this.taskQueue.length>0&&this.isRunning;){let s=this.taskQueue.shift();if(!s)break;i.task=s,i.status="running",i.startTime=Date.now();try{let a=await this.executeValidationTask(s);t.push(a),i.result=a,i.status="completed"}catch(a){let n=this.createErrorResult(s,a);this.config.retry&&s.retryCount<this.config.retry.maxRetries&&this.config.continueOnFailure?(s.retryCount++,this.taskQueue.push(s),await this.delay(this.config.retry.retryDelayMs)):(t.push(n),i.result=n,i.status="failed")}}i.task=null,i.status="idle"}}async executeValidationTask(e){let t=Date.now();if(!this.skillValidator)return this.createSimulatedResult(e,t);let i=new Promise((n,c)=>{setTimeout(()=>c(new Error(`Validation timeout after ${e.timeout}ms`)),e.timeout)}),s=await Promise.race([this.skillValidator(e.skill,e.model,{trustTier:e.trustTier,validationLevel:e.validationLevel,timeout:e.timeout}),i]),a=Date.now()-t;return this.outcomeToResult(s,e,a)}outcomeToResult(e,t,i){let s=e.testCaseResults.filter(c=>c.passed).length,a=e.testCaseResults.length,n=a>0?s/a:e.score;return{skill:t.skill,model:t.model,schemaValid:e.validationLevel!=="schema"||e.passed,validatorPassed:e.validationLevel!=="validator"||e.passed,evalPassRate:n,durationMs:i,errors:e.passed?[]:["Validation failed"],trustTier:t.trustTier,validationLevel:t.validationLevel,retryCount:t.retryCount,timestamp:new Date}}createSimulatedResult(e,t){let i=Date.now()-t+b()*100,s=.85+b()*.15;return{skill:e.skill,model:e.model,schemaValid:!0,validatorPassed:s>.8,evalPassRate:s,durationMs:i,errors:s>.8?[]:["Simulated validation failure"],trustTier:e.trustTier,validationLevel:e.validationLevel,retryCount:e.retryCount,timestamp:new Date}}createErrorResult(e,t){let i=w(t);return{skill:e.skill,model:e.model,schemaValid:!1,validatorPassed:!1,evalPassRate:0,durationMs:0,errors:[i],trustTier:e.trustTier,validationLevel:e.validationLevel,retryCount:e.retryCount,timestamp:new Date}}async recordOutcomesToLearner(e,t,i){for(let s of e){let a={skillName:s.skill,trustTier:s.trustTier||t,validationLevel:s.validationLevel||i,model:s.model,passed:s.errors.length===0&&s.evalPassRate>=.9,score:s.evalPassRate,testCaseResults:this.createTestCaseResults(s),timestamp:s.timestamp,runId:`swarm-${Date.now()}`,metadata:{duration:s.durationMs,retryCount:s.retryCount}};await this.learner.recordValidationOutcome(a)}}createTestCaseResults(e){return[{testId:`${e.skill}-${e.model}-aggregate`,passed:e.errors.length===0,expectedPatterns:["valid-output"],actualPatterns:e.errors.length===0?["valid-output"]:[],reasoningQuality:e.evalPassRate,executionTimeMs:e.durationMs,category:"swarm-validation",priority:"high",error:e.errors.length>0?e.errors.join("; "):void 0}]}delay(e){return new Promise(t=>setTimeout(t,e))}getConfig(){return{...this.config}}isValidationRunning(){return this.isRunning}getWorkerStatus(){return Array.from(this.workers.values())}cancel(){this.isRunning=!1,this.taskQueue=[]}};function A(y,e){return new R(y,e)}var F=["security-testing","accessibility-testing","api-testing","performance-testing","visual-regression-testing","mutation-testing","contract-testing","chaos-testing","compliance-testing","penetration-testing"],I=["claude-sonnet","claude-haiku","claude-opus"];P();import{readFileSync as L,writeFileSync as N,existsSync as E}from"fs";var O={varianceThreshold:.04,regressionThreshold:.1,minSamples:3,autoUpdateManifest:!1},k=class{constructor(e,t,i={}){this.learner=e;this.manifestPath=t;this.config={...O,...i}}config;async aggregateResults(e){let t=`agg-${Date.now()}`,i=new Date,s=this.buildSkillResultsMap(e),a=this.calculateSummary(s,e),n=await this.detectCrossModelAnomalies(e),c=await this.detectRegressions(e,this.config.regressionThreshold),r=this.generateRecommendations(s,n,c),o={timestamp:i,runId:t,summary:a,skillResults:s,crossModelAnalysis:n,regressions:c,recommendations:r,metadata:{version:"1.0.0",environment:e[0]?.metadata?.environment,generatedBy:"ValidationResultAggregator",inputs:{runIds:e.map(l=>l.runId),models:[...new Set(e.map(l=>l.model))]}}};return this.config.autoUpdateManifest&&await this.updateManifest(o),o}buildSkillResultsMap(e){let t=new Map;for(let i of e)for(let s of i.outcomes){let a=s.skillName;t.has(a)||t.set(a,{skill:a,trustTier:s.trustTier,passRateByModel:new Map,avgPassRate:0,schemaValid:!0,validatorPassed:!0,evalPassed:!0,issues:[],executionTimeMs:0,testCount:0,passedTests:0,failedTests:0});let n=t.get(a),c=s.testCaseResults.filter(r=>r.passed).length/(s.testCaseResults.length||1);n.passRateByModel.set(i.model,c),n.testCount+=s.testCaseResults.length,n.passedTests+=s.testCaseResults.filter(r=>r.passed).length,n.failedTests+=s.testCaseResults.filter(r=>!r.passed).length,n.executionTimeMs+=s.metadata?.duration||0,s.validationLevel==="schema"&&!s.passed&&(n.schemaValid=!1),s.validationLevel==="validator"&&!s.passed&&(n.validatorPassed=!1),s.validationLevel==="eval"&&!s.passed&&(n.evalPassed=!1);for(let r of s.testCaseResults)!r.passed&&r.error&&n.issues.push({skill:a,model:i.model,severity:r.priority==="critical"?"critical":r.priority==="high"?"high":r.priority==="medium"?"medium":"low",type:this.categorizeIssueType(s.validationLevel,r.error),message:r.error,testId:r.testId})}for(let i of t.values()){let s=Array.from(i.passRateByModel.values());i.avgPassRate=s.length>0?s.reduce((a,n)=>a+n,0)/s.length:0}return t}categorizeIssueType(e,t){return t.toLowerCase().includes("timeout")?"timeout":e==="schema"?"schema_failure":e==="validator"?"validator_failure":e==="eval"?"eval_failure":"error"}calculateSummary(e,t){let i=Array.from(e.values()),s=i.filter(n=>n.avgPassRate>=.9).length,a=i.length>0?i.reduce((n,c)=>n+c.avgPassRate,0)/i.length:0;return{totalSkills:i.length,passedSkills:s,failedSkills:i.length-s,avgPassRate:a,totalDurationMs:t.reduce((n,c)=>n+c.durationMs,0),totalTests:i.reduce((n,c)=>n+c.testCount,0),passedTests:i.reduce((n,c)=>n+c.passedTests,0),failedTests:i.reduce((n,c)=>n+c.failedTests,0),modelsUsed:[...new Set(t.map(n=>n.model))]}}async detectCrossModelAnomalies(e){let t=new Map,i=new Map,s=new Map;for(let d of e){t.has(d.model)||(t.set(d.model,[]),i.set(d.model,{totalTests:0,passedTests:0,skillCount:0}));for(let g of d.outcomes){let h=g.testCaseResults.filter(m=>m.passed).length/(g.testCaseResults.length||1);t.get(d.model).push(h);let f=i.get(d.model);f.totalTests+=g.testCaseResults.length,f.passedTests+=g.testCaseResults.filter(m=>m.passed).length,f.skillCount++,s.has(g.skillName)||s.set(g.skillName,{passRates:[],models:[]}),s.get(g.skillName).passRates.push(h),s.get(g.skillName).models.push(d.model)}}let a=[];for(let d of t.values())a.push(...d);let n=a.length>0?a.reduce((d,g)=>d+g,0)/a.length:0,c=a.length>1?a.reduce((d,g)=>d+Math.pow(g-n,2),0)/a.length:0,r=Math.sqrt(c),o=[],l=new Map;for(let[d,g]of t.entries()){let h=g.reduce((v,x)=>v+x,0)/g.length,f=h-n,m=i.get(d);l.set(d,{avgPassRate:h,skillCount:m.skillCount,totalTests:m.totalTests}),Math.abs(f)>this.config.varianceThreshold*2&&o.push({model:d,type:f<0?"low_performance":"high_variance",description:`Model ${d} has ${(f*100).toFixed(1)}% difference from average`,passRate:h,avgPassRate:n,deviation:Math.abs(f)})}let u=[],p=[];for(let[d,g]of s.entries()){if(g.passRates.length<2)continue;let h=g.passRates.reduce((m,v)=>m+v,0)/g.passRates.length;g.passRates.reduce((m,v)=>m+Math.pow(v-h,2),0)/g.passRates.length<this.config.varianceThreshold?u.push(d):p.push(d)}return{variance:c,stdDeviation:r,anomalies:o,consistentSkills:u,inconsistentSkills:p,modelPerformance:l}}async detectRegressions(e,t){let i=[],s=new Set;for(let a of e)for(let n of a.outcomes){let c=`${n.skillName}-${a.model}`;if(s.has(c))continue;s.add(c);let r=await this.learner.getValidationTrends(n.skillName);if(!r)continue;let o=n.testCaseResults.filter(p=>p.passed).length/(n.testCaseResults.length||1),l=r.recentPassRate,u=l-o;u>=t&&i.push({skill:n.skillName,model:a.model,previousPassRate:l,currentPassRate:o,regressionAmount:u,trend:r.overall,possibleCauses:this.analyzePossibleCauses(n,u),severity:this.categorizeRegressionSeverity(u)})}return i.sort((a,n)=>{let c={critical:0,high:1,medium:2,low:3},r=c[a.severity]-c[n.severity];return r!==0?r:n.regressionAmount-a.regressionAmount})}analyzePossibleCauses(e,t){let i=[],s=e.testCaseResults.filter(c=>!c.passed);if(s.length>0){let c=[...new Set(s.map(r=>r.category).filter(Boolean))];c.length>0&&i.push(`Failures in categories: ${c.join(", ")}`)}let a=s.filter(c=>c.priority==="critical");a.length>0&&i.push(`${a.length} critical test(s) failing`);let n=e.testCaseResults.reduce((c,r)=>c+r.reasoningQuality,0)/(e.testCaseResults.length||1);return n<.7&&i.push(`Low reasoning quality score: ${(n*100).toFixed(1)}%`),t>.3&&i.push("Possible model behavior change or prompt drift"),i.length===0&&i.push("No specific cause identified - review test details"),i}categorizeRegressionSeverity(e){return e>=.5?"critical":e>=.3?"high":e>=.15?"medium":"low"}generateRecommendations(e,t,i){let s=[];if(t.inconsistentSkills.length>0&&s.push(`Review ${t.inconsistentSkills.length} skills with inconsistent cross-model behavior: `+t.inconsistentSkills.slice(0,3).join(", ")+(t.inconsistentSkills.length>3?` and ${t.inconsistentSkills.length-3} more`:"")),t.anomalies.some(r=>r.type==="low_performance")){let r=t.anomalies.filter(o=>o.type==="low_performance").map(o=>o.model);s.push(`Investigate low performance on model(s): ${r.join(", ")}`)}let a=i.filter(r=>r.severity==="critical");a.length>0&&s.push(`URGENT: ${a.length} critical regression(s) detected - immediate review required`);let n=Array.from(e.values()).filter(r=>r.avgPassRate<.9);if(n.length>0){let r=n.filter(l=>!l.schemaValid),o=n.filter(l=>!l.validatorPassed);r.length>0&&s.push(`Fix schema validation for: ${r.map(l=>l.skill).slice(0,3).join(", ")}`),o.length>0&&s.push(`Review validator scripts for: ${o.map(l=>l.skill).slice(0,3).join(", ")}`)}return Array.from(e.values()).reduce((r,o)=>r+o.avgPassRate,0)/e.size<.8&&s.push("Overall pass rate below 80% - consider reviewing skill definitions and test expectations"),s.length===0&&s.push("All validations passing - no immediate action required"),s}async updateManifest(e){if(!E(this.manifestPath))throw new Error(`Manifest file not found: ${this.manifestPath}`);let t=C(L(this.manifestPath,"utf-8"));for(let[s,a]of e.skillResults.entries())if(t.skills&&t.skills[s]){let n=t.skills[s];n.validation||(n.validation={}),n.validation.passRate=a.avgPassRate,n.validation.lastValidated=e.timestamp.toISOString(),n.validation.status=a.avgPassRate>=.9?"passing":"failing",n.validation.passRateByModel=Object.fromEntries(a.passRateByModel)}let i=Array.from(e.skillResults.values());t.validationStatus={passing:i.filter(s=>s.avgPassRate>=.9).length,failing:i.filter(s=>s.avgPassRate<.9).length,unknown:0,skipped:t.summary?.tier0||0},t.generatedAt=new Date().toISOString(),t.lastValidationRun={runId:e.runId,timestamp:e.timestamp.toISOString(),avgPassRate:e.summary.avgPassRate,modelsUsed:e.summary.modelsUsed},N(this.manifestPath,JSON.stringify(t,null,2))}generateMarkdownReport(e){let{summary:t,crossModelAnalysis:i,regressions:s,recommendations:a,skillResults:n}=e,c=(t.avgPassRate>=.9||t.avgPassRate>=.7,"`"),r=[];if(r.push(`# Validation Report
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.2");process.exit(0)}
|
|
2
|
+
import{a as T}from"./chunk-XIBVVZGB.js";import{c as S}from"./chunk-JOVINE23.js";import{b as C,d as P}from"./chunk-N3F3CX4V.js";import{a as w,c as $}from"./chunk-SDTVHR63.js";import{a as b,d as M}from"./chunk-34U7JDCN.js";$();M();import{randomUUID as D}from"crypto";var V={topology:"hierarchical",maxConcurrentSkills:10,maxConcurrentModels:3,timeout:3e5,continueOnFailure:!0,retry:{maxRetries:2,retryDelayMs:1e3}},R=class{config;learner;skillValidator=null;workers=new Map;taskQueue=[];isRunning=!1;constructor(e,t){this.config={...V,...e},this.learner=t}setSkillValidator(e){this.skillValidator=e}async validateSkillsParallel(e,t,i){let s=Date.now(),a=i?.trustTier??3,n=i?.validationLevel??"eval",c=this.determineTopology(e.length,t.length),r=this.createValidationTasks(e,t,a,n),o=await this.executeTasksParallel(r,c),l=new Map;for(let u of o){let p=l.get(u.skill)||[];p.push(u),l.set(u.skill,p)}return await this.recordOutcomesToLearner(o,a,n),l}async validateSkillCrossModel(e,t,i){return(await this.validateSkillsParallel([e],t,i)).get(e)||[]}getSummary(e){let t=[],i=new Map,s=new Map;for(let[c,r]of e){i.set(c,r);for(let o of r){t.push(o);let l=s.get(o.model)||[];l.push(o),s.set(o.model,l)}}let a=t.filter(c=>c.errors.length===0&&c.evalPassRate>=.9).length,n=t.reduce((c,r)=>c+r.durationMs,0);return{totalSkills:i.size,totalModels:s.size,successCount:a,failureCount:t.length-a,overallPassRate:t.length>0?a/t.length:0,totalDurationMs:n,avgDurationMs:t.length>0?n/t.length:0,topology:this.config.topology,bySkill:i,byModel:s,results:t}}determineTopology(e,t){if(this.config.topology){let i=e*t;return i>20&&this.config.topology==="mesh"&&console.warn(`[SwarmSkillValidator] Large workload (${i} tasks) may be more efficient with hierarchical topology`),this.config.topology}return e>5||e>t*2?"hierarchical":t>5&&e<=3?"mesh":"hierarchical"}createValidationTasks(e,t,i,s){let a=[];for(let n of e)for(let c of t)a.push({id:`${n}-${c}-${Date.now()}-${D().slice(0,8)}`,skill:n,model:c,trustTier:i,validationLevel:s,timeout:this.config.timeout,retryCount:0});return a}async executeTasksParallel(e,t){this.isRunning=!0,this.taskQueue=[...e];let i=[],s=t==="hierarchical"?this.config.maxConcurrentSkills:Math.min(this.config.maxConcurrentSkills*this.config.maxConcurrentModels,e.length),a=[];for(let n=0;n<Math.min(s,e.length);n++){let c=`worker-${n}`;this.workers.set(c,{id:c,task:null,status:"idle"}),a.push(this.runWorker(c,i))}return await Promise.all(a),this.isRunning=!1,this.workers.clear(),i}async runWorker(e,t){let i=this.workers.get(e);if(i){for(;this.taskQueue.length>0&&this.isRunning;){let s=this.taskQueue.shift();if(!s)break;i.task=s,i.status="running",i.startTime=Date.now();try{let a=await this.executeValidationTask(s);t.push(a),i.result=a,i.status="completed"}catch(a){let n=this.createErrorResult(s,a);this.config.retry&&s.retryCount<this.config.retry.maxRetries&&this.config.continueOnFailure?(s.retryCount++,this.taskQueue.push(s),await this.delay(this.config.retry.retryDelayMs)):(t.push(n),i.result=n,i.status="failed")}}i.task=null,i.status="idle"}}async executeValidationTask(e){let t=Date.now();if(!this.skillValidator)return this.createSimulatedResult(e,t);let i=new Promise((n,c)=>{setTimeout(()=>c(new Error(`Validation timeout after ${e.timeout}ms`)),e.timeout)}),s=await Promise.race([this.skillValidator(e.skill,e.model,{trustTier:e.trustTier,validationLevel:e.validationLevel,timeout:e.timeout}),i]),a=Date.now()-t;return this.outcomeToResult(s,e,a)}outcomeToResult(e,t,i){let s=e.testCaseResults.filter(c=>c.passed).length,a=e.testCaseResults.length,n=a>0?s/a:e.score;return{skill:t.skill,model:t.model,schemaValid:e.validationLevel!=="schema"||e.passed,validatorPassed:e.validationLevel!=="validator"||e.passed,evalPassRate:n,durationMs:i,errors:e.passed?[]:["Validation failed"],trustTier:t.trustTier,validationLevel:t.validationLevel,retryCount:t.retryCount,timestamp:new Date}}createSimulatedResult(e,t){let i=Date.now()-t+b()*100,s=.85+b()*.15;return{skill:e.skill,model:e.model,schemaValid:!0,validatorPassed:s>.8,evalPassRate:s,durationMs:i,errors:s>.8?[]:["Simulated validation failure"],trustTier:e.trustTier,validationLevel:e.validationLevel,retryCount:e.retryCount,timestamp:new Date}}createErrorResult(e,t){let i=w(t);return{skill:e.skill,model:e.model,schemaValid:!1,validatorPassed:!1,evalPassRate:0,durationMs:0,errors:[i],trustTier:e.trustTier,validationLevel:e.validationLevel,retryCount:e.retryCount,timestamp:new Date}}async recordOutcomesToLearner(e,t,i){for(let s of e){let a={skillName:s.skill,trustTier:s.trustTier||t,validationLevel:s.validationLevel||i,model:s.model,passed:s.errors.length===0&&s.evalPassRate>=.9,score:s.evalPassRate,testCaseResults:this.createTestCaseResults(s),timestamp:s.timestamp,runId:`swarm-${Date.now()}`,metadata:{duration:s.durationMs,retryCount:s.retryCount}};await this.learner.recordValidationOutcome(a)}}createTestCaseResults(e){return[{testId:`${e.skill}-${e.model}-aggregate`,passed:e.errors.length===0,expectedPatterns:["valid-output"],actualPatterns:e.errors.length===0?["valid-output"]:[],reasoningQuality:e.evalPassRate,executionTimeMs:e.durationMs,category:"swarm-validation",priority:"high",error:e.errors.length>0?e.errors.join("; "):void 0}]}delay(e){return new Promise(t=>setTimeout(t,e))}getConfig(){return{...this.config}}isValidationRunning(){return this.isRunning}getWorkerStatus(){return Array.from(this.workers.values())}cancel(){this.isRunning=!1,this.taskQueue=[]}};function A(y,e){return new R(y,e)}var F=["security-testing","accessibility-testing","api-testing","performance-testing","visual-regression-testing","mutation-testing","contract-testing","chaos-testing","compliance-testing","penetration-testing"],I=["claude-sonnet","claude-haiku","claude-opus"];P();import{readFileSync as L,writeFileSync as N,existsSync as E}from"fs";var O={varianceThreshold:.04,regressionThreshold:.1,minSamples:3,autoUpdateManifest:!1},k=class{constructor(e,t,i={}){this.learner=e;this.manifestPath=t;this.config={...O,...i}}config;async aggregateResults(e){let t=`agg-${Date.now()}`,i=new Date,s=this.buildSkillResultsMap(e),a=this.calculateSummary(s,e),n=await this.detectCrossModelAnomalies(e),c=await this.detectRegressions(e,this.config.regressionThreshold),r=this.generateRecommendations(s,n,c),o={timestamp:i,runId:t,summary:a,skillResults:s,crossModelAnalysis:n,regressions:c,recommendations:r,metadata:{version:"1.0.0",environment:e[0]?.metadata?.environment,generatedBy:"ValidationResultAggregator",inputs:{runIds:e.map(l=>l.runId),models:[...new Set(e.map(l=>l.model))]}}};return this.config.autoUpdateManifest&&await this.updateManifest(o),o}buildSkillResultsMap(e){let t=new Map;for(let i of e)for(let s of i.outcomes){let a=s.skillName;t.has(a)||t.set(a,{skill:a,trustTier:s.trustTier,passRateByModel:new Map,avgPassRate:0,schemaValid:!0,validatorPassed:!0,evalPassed:!0,issues:[],executionTimeMs:0,testCount:0,passedTests:0,failedTests:0});let n=t.get(a),c=s.testCaseResults.filter(r=>r.passed).length/(s.testCaseResults.length||1);n.passRateByModel.set(i.model,c),n.testCount+=s.testCaseResults.length,n.passedTests+=s.testCaseResults.filter(r=>r.passed).length,n.failedTests+=s.testCaseResults.filter(r=>!r.passed).length,n.executionTimeMs+=s.metadata?.duration||0,s.validationLevel==="schema"&&!s.passed&&(n.schemaValid=!1),s.validationLevel==="validator"&&!s.passed&&(n.validatorPassed=!1),s.validationLevel==="eval"&&!s.passed&&(n.evalPassed=!1);for(let r of s.testCaseResults)!r.passed&&r.error&&n.issues.push({skill:a,model:i.model,severity:r.priority==="critical"?"critical":r.priority==="high"?"high":r.priority==="medium"?"medium":"low",type:this.categorizeIssueType(s.validationLevel,r.error),message:r.error,testId:r.testId})}for(let i of t.values()){let s=Array.from(i.passRateByModel.values());i.avgPassRate=s.length>0?s.reduce((a,n)=>a+n,0)/s.length:0}return t}categorizeIssueType(e,t){return t.toLowerCase().includes("timeout")?"timeout":e==="schema"?"schema_failure":e==="validator"?"validator_failure":e==="eval"?"eval_failure":"error"}calculateSummary(e,t){let i=Array.from(e.values()),s=i.filter(n=>n.avgPassRate>=.9).length,a=i.length>0?i.reduce((n,c)=>n+c.avgPassRate,0)/i.length:0;return{totalSkills:i.length,passedSkills:s,failedSkills:i.length-s,avgPassRate:a,totalDurationMs:t.reduce((n,c)=>n+c.durationMs,0),totalTests:i.reduce((n,c)=>n+c.testCount,0),passedTests:i.reduce((n,c)=>n+c.passedTests,0),failedTests:i.reduce((n,c)=>n+c.failedTests,0),modelsUsed:[...new Set(t.map(n=>n.model))]}}async detectCrossModelAnomalies(e){let t=new Map,i=new Map,s=new Map;for(let d of e){t.has(d.model)||(t.set(d.model,[]),i.set(d.model,{totalTests:0,passedTests:0,skillCount:0}));for(let g of d.outcomes){let h=g.testCaseResults.filter(m=>m.passed).length/(g.testCaseResults.length||1);t.get(d.model).push(h);let f=i.get(d.model);f.totalTests+=g.testCaseResults.length,f.passedTests+=g.testCaseResults.filter(m=>m.passed).length,f.skillCount++,s.has(g.skillName)||s.set(g.skillName,{passRates:[],models:[]}),s.get(g.skillName).passRates.push(h),s.get(g.skillName).models.push(d.model)}}let a=[];for(let d of t.values())a.push(...d);let n=a.length>0?a.reduce((d,g)=>d+g,0)/a.length:0,c=a.length>1?a.reduce((d,g)=>d+Math.pow(g-n,2),0)/a.length:0,r=Math.sqrt(c),o=[],l=new Map;for(let[d,g]of t.entries()){let h=g.reduce((v,x)=>v+x,0)/g.length,f=h-n,m=i.get(d);l.set(d,{avgPassRate:h,skillCount:m.skillCount,totalTests:m.totalTests}),Math.abs(f)>this.config.varianceThreshold*2&&o.push({model:d,type:f<0?"low_performance":"high_variance",description:`Model ${d} has ${(f*100).toFixed(1)}% difference from average`,passRate:h,avgPassRate:n,deviation:Math.abs(f)})}let u=[],p=[];for(let[d,g]of s.entries()){if(g.passRates.length<2)continue;let h=g.passRates.reduce((m,v)=>m+v,0)/g.passRates.length;g.passRates.reduce((m,v)=>m+Math.pow(v-h,2),0)/g.passRates.length<this.config.varianceThreshold?u.push(d):p.push(d)}return{variance:c,stdDeviation:r,anomalies:o,consistentSkills:u,inconsistentSkills:p,modelPerformance:l}}async detectRegressions(e,t){let i=[],s=new Set;for(let a of e)for(let n of a.outcomes){let c=`${n.skillName}-${a.model}`;if(s.has(c))continue;s.add(c);let r=await this.learner.getValidationTrends(n.skillName);if(!r)continue;let o=n.testCaseResults.filter(p=>p.passed).length/(n.testCaseResults.length||1),l=r.recentPassRate,u=l-o;u>=t&&i.push({skill:n.skillName,model:a.model,previousPassRate:l,currentPassRate:o,regressionAmount:u,trend:r.overall,possibleCauses:this.analyzePossibleCauses(n,u),severity:this.categorizeRegressionSeverity(u)})}return i.sort((a,n)=>{let c={critical:0,high:1,medium:2,low:3},r=c[a.severity]-c[n.severity];return r!==0?r:n.regressionAmount-a.regressionAmount})}analyzePossibleCauses(e,t){let i=[],s=e.testCaseResults.filter(c=>!c.passed);if(s.length>0){let c=[...new Set(s.map(r=>r.category).filter(Boolean))];c.length>0&&i.push(`Failures in categories: ${c.join(", ")}`)}let a=s.filter(c=>c.priority==="critical");a.length>0&&i.push(`${a.length} critical test(s) failing`);let n=e.testCaseResults.reduce((c,r)=>c+r.reasoningQuality,0)/(e.testCaseResults.length||1);return n<.7&&i.push(`Low reasoning quality score: ${(n*100).toFixed(1)}%`),t>.3&&i.push("Possible model behavior change or prompt drift"),i.length===0&&i.push("No specific cause identified - review test details"),i}categorizeRegressionSeverity(e){return e>=.5?"critical":e>=.3?"high":e>=.15?"medium":"low"}generateRecommendations(e,t,i){let s=[];if(t.inconsistentSkills.length>0&&s.push(`Review ${t.inconsistentSkills.length} skills with inconsistent cross-model behavior: `+t.inconsistentSkills.slice(0,3).join(", ")+(t.inconsistentSkills.length>3?` and ${t.inconsistentSkills.length-3} more`:"")),t.anomalies.some(r=>r.type==="low_performance")){let r=t.anomalies.filter(o=>o.type==="low_performance").map(o=>o.model);s.push(`Investigate low performance on model(s): ${r.join(", ")}`)}let a=i.filter(r=>r.severity==="critical");a.length>0&&s.push(`URGENT: ${a.length} critical regression(s) detected - immediate review required`);let n=Array.from(e.values()).filter(r=>r.avgPassRate<.9);if(n.length>0){let r=n.filter(l=>!l.schemaValid),o=n.filter(l=>!l.validatorPassed);r.length>0&&s.push(`Fix schema validation for: ${r.map(l=>l.skill).slice(0,3).join(", ")}`),o.length>0&&s.push(`Review validator scripts for: ${o.map(l=>l.skill).slice(0,3).join(", ")}`)}return Array.from(e.values()).reduce((r,o)=>r+o.avgPassRate,0)/e.size<.8&&s.push("Overall pass rate below 80% - consider reviewing skill definitions and test expectations"),s.length===0&&s.push("All validations passing - no immediate action required"),s}async updateManifest(e){if(!E(this.manifestPath))throw new Error(`Manifest file not found: ${this.manifestPath}`);let t=C(L(this.manifestPath,"utf-8"));for(let[s,a]of e.skillResults.entries())if(t.skills&&t.skills[s]){let n=t.skills[s];n.validation||(n.validation={}),n.validation.passRate=a.avgPassRate,n.validation.lastValidated=e.timestamp.toISOString(),n.validation.status=a.avgPassRate>=.9?"passing":"failing",n.validation.passRateByModel=Object.fromEntries(a.passRateByModel)}let i=Array.from(e.skillResults.values());t.validationStatus={passing:i.filter(s=>s.avgPassRate>=.9).length,failing:i.filter(s=>s.avgPassRate<.9).length,unknown:0,skipped:t.summary?.tier0||0},t.generatedAt=new Date().toISOString(),t.lastValidationRun={runId:e.runId,timestamp:e.timestamp.toISOString(),avgPassRate:e.summary.avgPassRate,modelsUsed:e.summary.modelsUsed},N(this.manifestPath,JSON.stringify(t,null,2))}generateMarkdownReport(e){let{summary:t,crossModelAnalysis:i,regressions:s,recommendations:a,skillResults:n}=e,c=(t.avgPassRate>=.9||t.avgPassRate>=.7,"`"),r=[];if(r.push(`# Validation Report
|
|
3
3
|
|
|
4
4
|
> ${c} Generated: ${e.timestamp.toISOString()}
|
|
5
5
|
> Run ID: ${e.runId}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{c as R,g 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.2");process.exit(0)}
|
|
2
|
+
import{c as R,g as L}from"./chunk-563PJBDM.js";import{k as N,o as w}from"./chunk-GK72GUHA.js";import{b,d as q}from"./chunk-N3F3CX4V.js";import{a as _,c as I}from"./chunk-SDTVHR63.js";import{f}from"./chunk-E25S5E2D.js";import{a as S,b as A}from"./chunk-XYJL6DKI.js";A();q();I();w();var D={dbPath:".agentic-qe/memory.db",walMode:!0,mmapSize:256*1024*1024,cacheSize:-64e3,foreignKeys:!0,useUnified:!0};function C(m,e=384){let n=new Array(e).fill(0),t=m.toLowerCase().trim();for(let a=0;a<3;a++)for(let i=0;i<t.length;i++){let s=t.charCodeAt(i),o=s*(i+1)*(a+1)%e;n[o]+=Math.sin(s*(a+1))/(i+1)}let r=Math.sqrt(n.reduce((a,i)=>a+i*i,0));if(r>0)for(let a=0;a<e;a++)n[a]/=r;return n}var h=class{db=null;config;prepared=new Map;initialized=!1;unifiedMemory=null;constructor(e={}){this.config={...D,...e}}getDatabase(){return this.db}async initialize(){if(!this.initialized)try{if(this.config.useUnified)this.unifiedMemory=N(),await this.unifiedMemory.initialize(),this.db=this.unifiedMemory.getDatabase(),console.log(`[SQLitePatternStore] Using unified storage: ${this.unifiedMemory.getDbPath()}`);else{let e=await import("path"),n=await import("fs"),t=e.dirname(this.config.dbPath);n.existsSync(t)||n.mkdirSync(t,{recursive:!0}),this.db=S(this.config.dbPath),this.db.pragma(`mmap_size = ${this.config.mmapSize}`),this.db.pragma(`cache_size = ${this.config.cacheSize}`),this.config.foreignKeys&&this.db.pragma("foreign_keys = ON"),this.createSchema(),console.log(`[SQLitePatternStore] Initialized (legacy): ${this.config.dbPath}`)}this.deduplicatePatterns(),this.prepareStatements(),this.initialized=!0}catch(e){throw new Error(`Failed to initialize SQLite: ${_(e)}`)}}createSchema(){if(!this.db)throw new Error("Database not initialized");this.db.exec(`
|
|
3
3
|
-- QE Patterns table
|
|
4
4
|
CREATE TABLE IF NOT EXISTS qe_patterns (
|
|
5
5
|
id TEXT PRIMARY KEY,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{b as f,d as v}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.2");process.exit(0)}
|
|
2
|
+
import{b as f,d as v}from"./chunk-N3F3CX4V.js";import q,{MultiBar as F,Presets as k}from"cli-progress";import O from"ora";import o from"chalk";v();import{existsSync as w,readFileSync as y,writeFileSync as j,mkdirSync as W,unlinkSync as V}from"fs";import{join as p}from"path";import{homedir as C}from"os";var u={wizards:{enabled:!0,themes:["default","minimal","detailed"],defaultTheme:"default"},progress:{style:"multi-bar",updateIntervalMs:100,showETA:!0,colors:!0},completion:{maxSuggestions:10,historyWeight:.3,contextWeight:.7,fuzzyMatch:!0},streaming:{enabled:!0,bufferSize:100,updateIntervalMs:50}};function x(){return p(C(),".aqe")}function E(){return p(x(),"cli-config.json")}var g=null,d=0,T=5e3;function S(){return g?Date.now()-d<T:!1}function A(s){let e=[],t=s;if(typeof t.enabled!="boolean"&&t.enabled!==void 0&&e.push({path:"wizards.enabled",message:"must be a boolean"}),t.themes!==void 0)if(!Array.isArray(t.themes))e.push({path:"wizards.themes",message:"must be an array"});else{let r=["default","minimal","detailed"];for(let n of t.themes)r.includes(n)||e.push({path:"wizards.themes",message:`invalid theme: ${n}`})}return t.defaultTheme!==void 0&&(["default","minimal","detailed"].includes(t.defaultTheme)||e.push({path:"wizards.defaultTheme",message:`invalid theme: ${t.defaultTheme}`})),e}function P(s){let e=[],t=s;return t.style!==void 0&&(["multi-bar","single-bar","spinner"].includes(t.style)||e.push({path:"progress.style",message:`invalid style: ${t.style}`})),t.updateIntervalMs!==void 0&&(typeof t.updateIntervalMs!="number"||t.updateIntervalMs<10)&&e.push({path:"progress.updateIntervalMs",message:"must be a number >= 10"}),typeof t.showETA!="boolean"&&t.showETA!==void 0&&e.push({path:"progress.showETA",message:"must be a boolean"}),typeof t.colors!="boolean"&&t.colors!==void 0&&e.push({path:"progress.colors",message:"must be a boolean"}),e}function $(s){let e=[],t=s;return t.maxSuggestions!==void 0&&(typeof t.maxSuggestions!="number"||t.maxSuggestions<1)&&e.push({path:"completion.maxSuggestions",message:"must be a number >= 1"}),t.historyWeight!==void 0&&(typeof t.historyWeight!="number"||t.historyWeight<0||t.historyWeight>1)&&e.push({path:"completion.historyWeight",message:"must be a number between 0 and 1"}),t.contextWeight!==void 0&&(typeof t.contextWeight!="number"||t.contextWeight<0||t.contextWeight>1)&&e.push({path:"completion.contextWeight",message:"must be a number between 0 and 1"}),typeof t.fuzzyMatch!="boolean"&&t.fuzzyMatch!==void 0&&e.push({path:"completion.fuzzyMatch",message:"must be a boolean"}),e}function I(s){let e=[],t=s;return typeof t.enabled!="boolean"&&t.enabled!==void 0&&e.push({path:"streaming.enabled",message:"must be a boolean"}),t.bufferSize!==void 0&&(typeof t.bufferSize!="number"||t.bufferSize<1)&&e.push({path:"streaming.bufferSize",message:"must be a number >= 1"}),t.updateIntervalMs!==void 0&&(typeof t.updateIntervalMs!="number"||t.updateIntervalMs<10)&&e.push({path:"streaming.updateIntervalMs",message:"must be a number >= 10"}),e}function M(s){let e=[];if(typeof s!="object"||s===null)return{valid:!1,errors:[{path:"",message:"config must be an object"}]};let t=s;return t.wizards!==void 0&&(typeof t.wizards!="object"||t.wizards===null?e.push({path:"wizards",message:"must be an object"}):e.push(...A(t.wizards))),t.progress!==void 0&&(typeof t.progress!="object"||t.progress===null?e.push({path:"progress",message:"must be an object"}):e.push(...P(t.progress))),t.completion!==void 0&&(typeof t.completion!="object"||t.completion===null?e.push({path:"completion",message:"must be an object"}):e.push(...$(t.completion))),t.streaming!==void 0&&(typeof t.streaming!="object"||t.streaming===null?e.push({path:"streaming",message:"must be an object"}):e.push(...I(t.streaming))),{valid:e.length===0,errors:e}}var z=["__proto__","constructor","prototype"];function m(s,e){let t={...s};for(let r of Object.keys(e)){if(z.includes(r)){console.warn(`Security: Skipping forbidden key '${String(r)}' in configuration merge`);continue}let n=e[r],i=s[r];n!==void 0&&typeof n=="object"&&!Array.isArray(n)&&typeof i=="object"&&!Array.isArray(i)?t[r]=m(i,n):n!==void 0&&(t[r]=n)}return t}function D(){let s=E();if(!w(s))return{...u};try{let e=y(s,"utf-8"),t=f(e),r=M(t);return r.valid?m(u,t):(console.warn(`CLI config validation errors: ${r.errors.map(n=>`${n.path}: ${n.message}`).join(", ")}`),console.warn("Using default configuration"),{...u})}catch(e){return console.warn(`Failed to load CLI config: ${e instanceof Error?e.message:"Unknown error"}`),{...u}}}function c(){return S()||(g=D(),d=Date.now()),g}function B(){return process.stdout.isTTY===!0}function h(){let s=c();return process.env.NO_COLOR!==void 0?!1:process.env.FORCE_COLOR!==void 0?!0:s.progress.colors&&B()}var b=class{multiBar;agentBars=new Map;agentStates=new Map;fleetBar=null;startTime=Date.now();options;isActive=!1;constructor(e={}){let t=c(),r=h();this.options={title:"Fleet Progress",showEta:t.progress.showETA,showPercentage:!0,...e};let n=r?o.cyan("{bar}"):"{bar}",i=this.options.format||`{name} ${n} {percentage}% | {status} {eta}`;this.multiBar=new F({clearOnComplete:!1,hideCursor:!0,format:i,barCompleteChar:"\u2588",barIncompleteChar:"\u2591",forceRedraw:!0,fps:Math.round(1e3/t.progress.updateIntervalMs)},k.shades_classic)}start(e){this.isActive=!0,this.startTime=Date.now(),console.log(o.blue(`
|
|
3
3
|
${this.options.title}
|
|
4
4
|
`)),this.fleetBar=this.multiBar.create(100,0,{name:o.white("Fleet Progress".padEnd(30)),status:"",eta:""})}addAgent(e){if(!this.isActive)return;this.agentStates.set(e.id,e);let t=this.multiBar.create(100,e.progress,{name:o.gray(this.truncateName(e.name,30).padEnd(30)),status:this.getStatusIcon(e.status),eta:e.eta?this.formatEta(e.eta):""});this.agentBars.set(e.id,t),this.updateFleetProgress()}updateAgent(e,t,r){if(!this.isActive)return;let n=this.agentStates.get(e),i=this.agentBars.get(e);!n||!i||(n.progress=Math.min(100,Math.max(0,t)),r?.status&&(n.status=r.status),r?.message&&(n.message=r.message),r?.eta!==void 0&&(n.eta=r.eta),i.update(n.progress,{name:this.getAgentNameDisplay(n),status:this.getStatusIcon(n.status),eta:n.eta?this.formatEta(n.eta):""}),this.updateFleetProgress())}completeAgent(e,t=!0){if(!this.isActive)return;let r=this.agentStates.get(e),n=this.agentBars.get(e);!r||!n||(r.status=t?"completed":"failed",r.progress=t?100:r.progress,n.update(r.progress,{name:this.getAgentNameDisplay(r),status:this.getStatusIcon(r.status),eta:""}),this.updateFleetProgress())}stop(){if(!this.isActive)return;this.isActive=!1,this.multiBar.stop();let e=Array.from(this.agentStates.values()).filter(i=>i.status==="completed").length,t=Array.from(this.agentStates.values()).filter(i=>i.status==="failed").length,r=this.agentStates.size,n=Date.now()-this.startTime;console.log(""),console.log(t===0?o.green(`All ${e}/${r} agents completed successfully (${this.formatDuration(n)})`):o.yellow(`${e}/${r} agents completed, ${t} failed (${this.formatDuration(n)})`)),console.log("")}updateFleetProgress(){if(!this.fleetBar)return;let e=Array.from(this.agentStates.values()),t=e.reduce((a,l)=>a+l.progress,0),r=e.length>0?Math.round(t/e.length):0,n=e.filter(a=>a.status==="completed").length,i=e.filter(a=>a.status==="running").length;this.fleetBar.update(r,{status:o.gray(`${n}/${e.length} complete, ${i} running`),eta:this.options.showEta?this.estimateFleetEta(e):""})}getAgentNameDisplay(e){let t=this.truncateName(e.name,26);switch(e.status){case"completed":return o.green(t.padEnd(30));case"failed":return o.red(t.padEnd(30));case"running":return o.yellow(t.padEnd(30));default:return o.gray(t.padEnd(30))}}getStatusIcon(e){switch(e){case"completed":return o.green("\u2713");case"failed":return o.red("\u2717");case"running":return o.yellow("\u25B6");default:return o.gray("\u25CB")}}truncateName(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}formatEta(e){return e<=0?"":e<1e3?`${e}ms`:e<6e4?`${Math.round(e/1e3)}s`:e<36e5?`${Math.round(e/6e4)}m`:`${Math.round(e/36e5)}h`}formatDuration(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:e<36e5?`${(e/6e4).toFixed(1)}m`:`${(e/36e5).toFixed(1)}h`}estimateFleetEta(e){let t=e.filter(a=>a.status==="running"||a.status==="pending");if(t.length===0)return"";let r=t.map(a=>a.eta||0).filter(a=>a>0);if(r.length>0){let a=Math.max(...r);return o.gray(`ETA: ${this.formatEta(a)}`)}let n=Date.now()-this.startTime,i=t.reduce((a,l)=>a+l.progress,0)/t.length;if(i>0){let a=n/(i/100),l=Math.max(0,a-n);return o.gray(`ETA: ${this.formatEta(l)}`)}return""}};function X(s){let e=Date.now(),t=O({text:s,color:"cyan"}).start(),r=setInterval(()=>{let i=((Date.now()-e)/1e3).toFixed(1);t.text=`${s} (${i}s)`},100);r.unref?.();let n=()=>{clearInterval(r)};return{spinner:t,stop:()=>{n(),t.stop()},succeed:i=>{n();let a=((Date.now()-e)/1e3).toFixed(1);t.succeed(i||`${s} (${a}s)`)},fail:i=>{n();let a=((Date.now()-e)/1e3).toFixed(1);t.fail(i||`${s} failed (${a}s)`)}}}export{b as a,X as b};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
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.2");process.exit(0)}
|
|
2
2
|
import r from"chalk";function s(e){switch(e){case"healthy":case"completed":return r.green(e);case"idle":return r.cyan(e);case"degraded":case"running":return r.yellow(e);case"unhealthy":case"failed":return r.red(e);default:return r.gray(e)}}function a(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:e<36e5?`${(e/6e4).toFixed(1)}m`:`${(e/36e5).toFixed(1)}h`}function l(e){let t=Math.floor(e/36e5),n=Math.floor(e%36e5/6e4),o=Math.floor(e%6e4/1e3);return`${t}h ${n}m ${o}s`}export{s as a,a as b,l as c};
|