agentic-qe 3.8.13 → 3.9.0
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 +48 -0
- package/dist/adapters/a2ui/integration/agui-sync.js +2 -1
- package/dist/audit/witness-chain.js +15 -3
- package/dist/boot/fast-paths.d.ts +24 -0
- package/dist/boot/fast-paths.js +43 -0
- package/dist/boot/parallel-prefetch.d.ts +26 -0
- package/dist/boot/parallel-prefetch.js +36 -0
- package/dist/cli/bundle.js +12 -9431
- package/dist/cli/chunks/adapter-WBR5NXS3.js +2 -0
- package/dist/cli/chunks/agent-booster-wasm-PQYB7VRU.js +2 -0
- package/dist/cli/chunks/agent-handler-QDAB5NQS.js +33 -0
- package/dist/cli/chunks/aqe-learning-engine-TK4JQCGT.js +2 -0
- package/dist/cli/chunks/audit-S7JUYYVP.js +3 -0
- package/dist/cli/chunks/base-2WXOSMBQ.js +2 -0
- package/dist/cli/chunks/better-sqlite3-7KY2RDXO.js +2 -0
- package/dist/cli/chunks/brain-handler-PPEGDCN4.js +68 -0
- package/dist/cli/chunks/branch-enumerator-XK4V5W7L.js +7 -0
- package/dist/cli/chunks/browser-PALA5PL3.js +4 -0
- package/dist/cli/chunks/browser-workflow-42F7GK5T.js +2 -0
- package/dist/cli/chunks/chunk-24FKIJNC.js +15 -0
- package/dist/cli/chunks/chunk-263XS447.js +2 -0
- package/dist/cli/chunks/chunk-2BZFNEN2.js +4 -0
- package/dist/cli/chunks/chunk-2E5NQNSU.js +180 -0
- package/dist/cli/chunks/chunk-2I7J3O6V.js +2 -0
- package/dist/cli/chunks/chunk-3ADGXLTM.js +14 -0
- package/dist/cli/chunks/chunk-3IHG3WOY.js +12 -0
- package/dist/cli/chunks/chunk-3IUNFTIF.js +2 -0
- package/dist/cli/chunks/chunk-3JPRUND5.js +2 -0
- package/dist/cli/chunks/chunk-3NZLZHJI.js +2 -0
- package/dist/cli/chunks/chunk-3THRQEZ2.js +95 -0
- package/dist/cli/chunks/chunk-3ZOONQG6.js +2 -0
- package/dist/cli/chunks/chunk-4B6NCELM.js +2 -0
- package/dist/cli/chunks/chunk-4I2IOUS4.js +2 -0
- package/dist/cli/chunks/chunk-4VBTXZRM.js +2 -0
- package/dist/cli/chunks/chunk-4VUPRTVX.js +3 -0
- package/dist/cli/chunks/chunk-4YOMLWEK.js +70 -0
- package/dist/cli/chunks/chunk-4YS3IJ45.js +2 -0
- package/dist/cli/chunks/chunk-5SKGFSKD.js +2 -0
- package/dist/cli/chunks/chunk-5T2ZQWKF.js +27 -0
- package/dist/cli/chunks/chunk-62ADTHV7.js +2 -0
- package/dist/cli/chunks/chunk-6EOS7KX2.js +2 -0
- package/dist/cli/chunks/chunk-6SVX4DJC.js +6 -0
- package/dist/cli/chunks/chunk-72WOAVK6.js +2 -0
- package/dist/cli/chunks/chunk-7R6YMLVS.js +3 -0
- package/dist/cli/chunks/chunk-7VDBAVTY.js +2 -0
- package/dist/cli/chunks/chunk-AFLLQ5PP.js +15 -0
- package/dist/cli/chunks/chunk-AKE543X2.js +2 -0
- package/dist/cli/chunks/chunk-B36CDR4U.js +2 -0
- package/dist/cli/chunks/chunk-B6LLWYQ6.js +2 -0
- package/dist/cli/chunks/chunk-BDIEMZ22.js +91 -0
- package/dist/cli/chunks/chunk-BGXNSCXX.js +4 -0
- package/dist/cli/chunks/chunk-BLBRY5UD.js +2 -0
- package/dist/cli/chunks/chunk-BPWXXEH2.js +3029 -0
- package/dist/cli/chunks/chunk-BR26T7ZS.js +180 -0
- package/dist/cli/chunks/chunk-BTREG4IW.js +2 -0
- package/dist/cli/chunks/chunk-BULKFVYX.js +2 -0
- package/dist/cli/chunks/chunk-BXAXGEFC.js +24 -0
- package/dist/cli/chunks/chunk-CL6POIX4.js +2 -0
- package/dist/cli/chunks/chunk-CS2KS7LP.js +2 -0
- package/dist/cli/chunks/chunk-CWFB6BSA.js +316 -0
- package/dist/cli/chunks/chunk-DRT3WKQW.js +2 -0
- package/dist/cli/chunks/chunk-EHDQJQ6Y.js +27 -0
- package/dist/cli/chunks/chunk-ESVQ6MEB.js +2 -0
- package/dist/cli/chunks/chunk-FEKY7T6Q.js +2 -0
- package/dist/cli/chunks/chunk-FGA7VIFR.js +7 -0
- package/dist/cli/chunks/chunk-FIA6X7UL.js +2 -0
- package/dist/cli/chunks/chunk-GAOJV3OX.js +2 -0
- package/dist/cli/chunks/chunk-GKNNSCLC.js +5 -0
- package/dist/cli/chunks/chunk-GPQ57KA4.js +2 -0
- package/dist/cli/chunks/chunk-GRUUQAR6.js +2 -0
- package/dist/cli/chunks/chunk-HRO6OZQD.js +2 -0
- package/dist/cli/chunks/chunk-HY6PMO5W.js +66 -0
- package/dist/cli/chunks/chunk-IAV2JMIX.js +167 -0
- package/dist/cli/chunks/chunk-IFNIIK34.js +21 -0
- package/dist/cli/chunks/chunk-IGJPMN4I.js +3 -0
- package/dist/cli/chunks/chunk-J3KWWR6Z.js +1 -0
- package/dist/cli/chunks/chunk-JBANAPWG.js +2 -0
- package/dist/cli/chunks/chunk-JJO7Y4H3.js +604 -0
- package/dist/cli/chunks/chunk-JRYGQO2W.js +2 -0
- package/dist/cli/chunks/chunk-JXM26HEE.js +2 -0
- package/dist/cli/chunks/chunk-JZSDOIXA.js +2 -0
- package/dist/cli/chunks/chunk-KP5NUODU.js +3 -0
- package/dist/cli/chunks/chunk-LHJQD2VU.js +750 -0
- package/dist/cli/chunks/chunk-LNQIY6BP.js +2 -0
- package/dist/cli/chunks/chunk-MDUHYUHF.js +2 -0
- package/dist/cli/chunks/chunk-MV6CMOJQ.js +65 -0
- package/dist/cli/chunks/chunk-MZOFWJTM.js +2 -0
- package/dist/cli/chunks/chunk-N2NS2PHA.js +45 -0
- package/dist/cli/chunks/chunk-N4TL73TH.js +314 -0
- package/dist/cli/chunks/chunk-N5UXCLFI.js +2 -0
- package/dist/cli/chunks/chunk-NZ2VCPN4.js +2 -0
- package/dist/cli/chunks/chunk-OF4D7MYI.js +2 -0
- package/dist/cli/chunks/chunk-OI5NGQO2.js +2 -0
- package/dist/cli/chunks/chunk-OLHKGP35.js +2 -0
- package/dist/cli/chunks/chunk-QOVHWZEP.js +1 -0
- package/dist/cli/chunks/chunk-RFSN6IDA.js +79 -0
- package/dist/cli/chunks/chunk-RTGGL7D7.js +4 -0
- package/dist/cli/chunks/chunk-RU5WAHB7.js +3 -0
- package/dist/cli/chunks/chunk-SUSEVMZT.js +2 -0
- package/dist/cli/chunks/chunk-TLHP5EII.js +2 -0
- package/dist/cli/chunks/chunk-TWUWL5EJ.js +2 -0
- package/dist/cli/chunks/chunk-U5RN7YQW.js +2 -0
- package/dist/cli/chunks/chunk-UFUVUO3J.js +2 -0
- package/dist/cli/chunks/chunk-UQHYFOBX.js +16 -0
- package/dist/cli/chunks/chunk-VOS4NQSF.js +2 -0
- package/dist/cli/chunks/chunk-VSVXUTJN.js +256 -0
- package/dist/cli/chunks/chunk-WBQSXPBI.js +2 -0
- package/dist/cli/chunks/chunk-WGMPEW2T.js +2 -0
- package/dist/cli/chunks/chunk-WIEC7VKK.js +2 -0
- package/dist/cli/chunks/chunk-WJ3DLOXF.js +14 -0
- package/dist/cli/chunks/chunk-X3KI6JOY.js +9 -0
- package/dist/cli/chunks/chunk-X5IJGWYG.js +2 -0
- package/dist/cli/chunks/chunk-XIBDETCS.js +146 -0
- package/dist/cli/chunks/chunk-XLRQYLWW.js +2 -0
- package/dist/cli/chunks/chunk-XO6PVK2P.js +3 -0
- package/dist/cli/chunks/chunk-XRE2HCWG.js +3 -0
- package/dist/cli/chunks/chunk-XT2V2322.js +2 -0
- package/dist/cli/chunks/chunk-Y7BHKZFJ.js +18 -0
- package/dist/cli/chunks/chunk-YAGODYIG.js +59 -0
- package/dist/cli/chunks/chunk-YANUP2RO.js +2 -0
- package/dist/cli/chunks/chunk-YPFOCNOE.js +30 -0
- package/dist/cli/chunks/chunk-YR6ZZGH7.js +81 -0
- package/dist/cli/chunks/chunk-YVA65UZL.js +2 -0
- package/dist/cli/chunks/chunk-YW2THB5Q.js +2 -0
- package/dist/cli/chunks/chunk-ZAPS3UGQ.js +20 -0
- package/dist/cli/chunks/chunk-ZDATDCYN.js +2 -0
- package/dist/cli/chunks/ci-J374KDLI.js +81 -0
- package/dist/cli/chunks/ci-output-7JN7F6CI.js +2 -0
- package/dist/cli/chunks/claude-flow-setup-245JLJCN.js +2 -0
- package/dist/cli/chunks/client-MCSNSH2C.js +2 -0
- package/dist/cli/chunks/cline-installer-LBA2M5N3.js +4 -0
- package/dist/cli/chunks/code-U4N4WONM.js +38 -0
- package/dist/cli/chunks/code-index-extractor-A57Z6BO4.js +3 -0
- package/dist/cli/chunks/codex-installer-UXMK2N4T.js +8 -0
- package/dist/cli/chunks/completions-W66BSCOE.js +1364 -0
- package/dist/cli/chunks/complexity-analyzer-AB4OZARV.js +2 -0
- package/dist/cli/chunks/continuedev-installer-LRFZ2SJM.js +14 -0
- package/dist/cli/chunks/copilot-installer-CQ3JYBIB.js +3 -0
- package/dist/cli/chunks/cost-tracker-4F723RB6.js +2 -0
- package/dist/cli/chunks/coverage-4PUEQXAY.js +27 -0
- package/dist/cli/chunks/cross-domain-router-OWR5IJ5G.js +2 -0
- package/dist/cli/chunks/cursor-installer-JZEDEDHA.js +3 -0
- package/dist/cli/chunks/daemon-B7TWGHXQ.js +19 -0
- package/dist/cli/chunks/dag-attention-scheduler-JWO6XI6A.js +2 -0
- package/dist/cli/chunks/detect-L6ZZHUSX.js +2 -0
- package/dist/cli/chunks/domain-handler-FT5FLZWL.js +25 -0
- package/dist/cli/chunks/domain-transfer-5Y4FGJAJ.js +2 -0
- package/dist/cli/chunks/dream-4TDBIYED.js +2 -0
- package/dist/cli/chunks/esm-node-2PKHKOTS.js +2 -0
- package/dist/cli/chunks/eval-GHMPFGWV.js +15 -0
- package/dist/cli/chunks/fast-paths-B3R647KN.js +2 -0
- package/dist/cli/chunks/feature-flags-DWS7ARSX.js +2 -0
- package/dist/cli/chunks/feature-flags-IVQ3AL4Q.js +2 -0
- package/dist/cli/chunks/file-discovery-QFPA6GMV.js +2 -0
- package/dist/cli/chunks/fleet-EKOKMOMW.js +43 -0
- package/dist/cli/chunks/gnn-wrapper-OYC55N5E.js +2 -0
- package/dist/cli/chunks/heartbeat-handler-MBBS4IBU.js +48 -0
- package/dist/cli/chunks/heartbeat-scheduler-XDGMOT7X.js +2 -0
- package/dist/cli/chunks/hnsw-index-YO7CT23I.js +2 -0
- package/dist/cli/chunks/hnswlib-node-56YWVXFE.js +2 -0
- package/dist/cli/chunks/hooks-L5VLZGEK.js +101 -0
- package/dist/cli/chunks/hypergraph-engine-A4Y2ZRAG.js +2 -0
- package/dist/cli/chunks/hypergraph-handler-3HDGB5SZ.js +35 -0
- package/dist/cli/chunks/impact-analyzer-UEIGXSZ4.js +2 -0
- package/dist/cli/chunks/init-handler-JDET6WUN.js +68 -0
- package/dist/cli/chunks/init-wizard-JWZUGIPJ.js +2 -0
- package/dist/cli/chunks/kernel-YNDTVKIW.js +2 -0
- package/dist/cli/chunks/kilocode-installer-GZZG5AFW.js +4 -0
- package/dist/cli/chunks/kiro-installer-IWNY5TKH.js +74 -0
- package/dist/cli/chunks/knowledge-graph-NGJKFTSN.js +2 -0
- package/dist/cli/chunks/learning-722ZNSZ6.js +107 -0
- package/dist/cli/chunks/llm-router-DNAV746L.js +30 -0
- package/dist/cli/chunks/load-Y3GCUFM4.js +2 -0
- package/dist/cli/chunks/load-test-GZUBXFF3.js +2 -0
- package/dist/cli/chunks/mcp-LKPIBZ3W.js +2 -0
- package/dist/cli/chunks/memory-L57MLFOP.js +32 -0
- package/dist/cli/chunks/memory-backend-3NQIZUXE.js +2 -0
- package/dist/cli/chunks/memory-handlers-MDZQ7HVW.js +2 -0
- package/dist/cli/chunks/opencode-installer-4HUB36H5.js +3 -0
- package/dist/cli/chunks/orchestrator-QHSBB2UC.js +371 -0
- package/dist/cli/chunks/pipeline-D3QER35Z.js +19 -0
- package/dist/cli/chunks/platform-T4E7Q3RD.js +2 -0
- package/dist/cli/chunks/plugin-JHW2YPRC.js +27 -0
- package/dist/cli/chunks/prime-radiant-advanced-wasm-G7CFNNQV.js +2 -0
- package/dist/cli/chunks/protocol-executor-SPUVRDWT.js +2 -0
- package/dist/cli/chunks/protocol-handler-2BQQ4HDM.js +20 -0
- package/dist/cli/chunks/prove-UQ6JFT73.js +3 -0
- package/dist/cli/chunks/qe-reasoning-bank-3HBK2FVD.js +2 -0
- package/dist/cli/chunks/quality-JRZYMC77.js +7 -0
- package/dist/cli/chunks/queen-coordinator-RW3NKO5A.js +2 -0
- package/dist/cli/chunks/real-embeddings-GK63VF35.js +2 -0
- package/dist/cli/chunks/roocode-installer-F4E2LAYR.js +4 -0
- package/dist/cli/chunks/router-RJGHWDQ3.js +2 -0
- package/dist/cli/chunks/routing-feedback-ZXBXFKX6.js +2 -0
- package/dist/cli/chunks/routing-handler-VNKFUUGB.js +20 -0
- package/dist/cli/chunks/ruvector-commands-2TLNHC3A.js +8 -0
- package/dist/cli/chunks/rvf-dual-writer-MQW2SJLT.js +2 -0
- package/dist/cli/chunks/rvf-native-adapter-LKFKTMUN.js +2 -0
- package/dist/cli/chunks/safe-db-G22E5ROA.js +2 -0
- package/dist/cli/chunks/schedule-Y7VVCPYV.js +2 -0
- package/dist/cli/chunks/scheduler-AUQIFQB7.js +2 -0
- package/dist/cli/chunks/security-EBEG2OPU.js +14 -0
- package/dist/cli/chunks/shared-rvf-dual-writer-BVSCQAFS.js +2 -0
- package/dist/cli/chunks/sqlite-persistence-JAVHUGGL.js +2 -0
- package/dist/cli/chunks/status-handler-VZ32M4G4.js +45 -0
- package/dist/cli/chunks/structural-health-K6LRCKV6.js +2 -0
- package/dist/cli/chunks/sync-MHSHNLIM.js +23 -0
- package/dist/cli/chunks/task-handler-JNOIBZ2G.js +49 -0
- package/dist/cli/chunks/task-handlers-P5DSUKND.js +2 -0
- package/dist/cli/chunks/test-DO22BNIL.js +33 -0
- package/dist/cli/chunks/test-scheduling-VLRQZEFL.js +15 -0
- package/dist/cli/chunks/token-bootstrap-4VJKGVMK.js +2 -0
- package/dist/cli/chunks/token-usage-LG3PXRXH.js +25 -0
- package/dist/cli/chunks/transformers-GY7SIKEU.js +2 -0
- package/dist/cli/chunks/tree-sitter-wasm-parser-FT2KB66N.js +2 -0
- package/dist/cli/chunks/types-QJGNBKP2.js +2 -0
- package/dist/cli/chunks/unified-memory-XYGENQUT.js +2 -0
- package/dist/cli/chunks/unified-memory-hnsw-MVEGQBF3.js +2 -0
- package/dist/cli/chunks/unified-persistence-PFRCWEUG.js +2 -0
- package/dist/cli/chunks/validate-VQCRSVNQ.js +21 -0
- package/dist/cli/chunks/validate-swarm-A5DHAWTP.js +14 -0
- package/dist/cli/chunks/vibium-RZBSL4EB.js +2 -0
- package/dist/cli/chunks/visual-security-V47BLGJM.js +2 -0
- package/dist/cli/chunks/web-tree-sitter-7C4NXEOF.js +2 -0
- package/dist/cli/chunks/windsurf-installer-ES3KPQG3.js +7 -0
- package/dist/cli/chunks/witness-chain-BR63P4A7.js +2 -0
- package/dist/cli/chunks/workflow-JETHX4ML.js +51 -0
- package/dist/cli/chunks/workflow-orchestrator-7PZMX3JZ.js +2 -0
- package/dist/cli/chunks/wrappers-WP5RH745.js +2 -0
- package/dist/cli/commands/daemon.d.ts +13 -0
- package/dist/cli/commands/daemon.js +224 -0
- package/dist/cli/commands/hooks-handlers/hooks-shared.js +2 -1
- package/dist/cli/commands/plugin.d.ts +12 -0
- package/dist/cli/commands/plugin.js +135 -0
- package/dist/cli/commands/workflow.d.ts +10 -0
- package/dist/cli/commands/workflow.js +587 -0
- package/dist/cli/handlers/brain-handler.js +13 -8
- package/dist/cli/handlers/heartbeat-handler.d.ts +1 -0
- package/dist/cli/handlers/heartbeat-handler.js +20 -10
- package/dist/cli/handlers/hypergraph-handler.js +3 -3
- package/dist/cli/handlers/init-handler.js +10 -9
- package/dist/cli/handlers/interfaces.d.ts +4 -4
- package/dist/cli/index.js +159 -638
- package/dist/cli/lazy-registry.d.ts +27 -0
- package/dist/cli/lazy-registry.js +70 -0
- package/dist/context/compaction/context-budget.d.ts +71 -0
- package/dist/context/compaction/context-budget.js +120 -0
- package/dist/context/compaction/index.d.ts +96 -0
- package/dist/context/compaction/index.js +259 -0
- package/dist/context/compaction/llm-caller-adapter.d.ts +14 -0
- package/dist/context/compaction/llm-caller-adapter.js +47 -0
- package/dist/context/compaction/tier1-microcompact.d.ts +33 -0
- package/dist/context/compaction/tier1-microcompact.js +47 -0
- package/dist/context/compaction/tier2-session-summary.d.ts +72 -0
- package/dist/context/compaction/tier2-session-summary.js +172 -0
- package/dist/context/compaction/tier3-llm-compact.d.ts +65 -0
- package/dist/context/compaction/tier3-llm-compact.js +166 -0
- package/dist/context/compaction/tier4-reactive.d.ts +54 -0
- package/dist/context/compaction/tier4-reactive.js +129 -0
- package/dist/coordination/consensus/providers/claude-provider.d.ts +1 -0
- package/dist/coordination/consensus/providers/claude-provider.js +23 -3
- package/dist/domains/test-generation/generators/base-test-generator.d.ts +1 -1
- package/dist/domains/test-generation/generators/base-test-generator.js +11 -11
- package/dist/domains/test-generation/generators/go-test-generator.js +12 -12
- package/dist/domains/test-generation/generators/junit5-generator.js +9 -9
- package/dist/domains/test-generation/generators/kotlin-junit-generator.js +10 -10
- package/dist/domains/test-generation/generators/pytest-generator.js +8 -8
- package/dist/domains/test-generation/generators/swift-testing-generator.js +8 -8
- package/dist/domains/test-generation/generators/test-value-helpers.d.ts +20 -0
- package/dist/domains/test-generation/generators/test-value-helpers.js +48 -0
- package/dist/domains/test-generation/generators/xunit-generator.js +11 -11
- package/dist/hooks/cross-phase-hooks.d.ts +11 -0
- package/dist/hooks/cross-phase-hooks.js +73 -9
- package/dist/hooks/security/config-snapshot.d.ts +21 -0
- package/dist/hooks/security/config-snapshot.js +33 -0
- package/dist/hooks/security/exit-codes.d.ts +28 -0
- package/dist/hooks/security/exit-codes.js +33 -0
- package/dist/hooks/security/index.d.ts +15 -0
- package/dist/hooks/security/index.js +15 -0
- package/dist/hooks/security/ssrf-guard.d.ts +25 -0
- package/dist/hooks/security/ssrf-guard.js +69 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -2
- package/dist/init/init-wizard-hooks.js +15 -1
- package/dist/init/phases/07-hooks.js +2 -2
- package/dist/init/settings-merge.js +3 -7
- package/dist/kernel/kernel.js +35 -0
- package/dist/kernel/memory-backend.js +3 -1
- package/dist/mcp/bundle.js +416 -362
- package/dist/mcp/entry.js +132 -77
- package/dist/mcp/http-server.js +4 -1
- package/dist/mcp/index.d.ts +2 -2
- package/dist/mcp/index.js +5 -4
- package/dist/mcp/middleware/batch-executor.d.ts +46 -0
- package/dist/mcp/middleware/batch-executor.js +150 -0
- package/dist/mcp/middleware/microcompact.d.ts +97 -0
- package/dist/mcp/middleware/microcompact.js +179 -0
- package/dist/mcp/middleware/middleware-chain.d.ts +37 -0
- package/dist/mcp/middleware/middleware-chain.js +60 -0
- package/dist/mcp/protocol-server.d.ts +16 -0
- package/dist/mcp/protocol-server.js +140 -36
- package/dist/mcp/services/session-durability-middleware.d.ts +22 -0
- package/dist/mcp/services/session-durability-middleware.js +64 -0
- package/dist/mcp/services/session-resume.d.ts +29 -0
- package/dist/mcp/services/session-resume.js +221 -0
- package/dist/mcp/services/session-store.d.ts +84 -0
- package/dist/mcp/services/session-store.js +163 -0
- package/dist/mcp/tool-registry.d.ts +9 -0
- package/dist/mcp/tool-registry.js +30 -1
- package/dist/mcp/types.d.ts +1 -0
- package/dist/plugins/cache.d.ts +44 -0
- package/dist/plugins/cache.js +149 -0
- package/dist/plugins/index.d.ts +15 -0
- package/dist/plugins/index.js +15 -0
- package/dist/plugins/lifecycle.d.ts +67 -0
- package/dist/plugins/lifecycle.js +175 -0
- package/dist/plugins/manifest.d.ts +45 -0
- package/dist/plugins/manifest.js +173 -0
- package/dist/plugins/resolver.d.ts +37 -0
- package/dist/plugins/resolver.js +80 -0
- package/dist/plugins/security.d.ts +23 -0
- package/dist/plugins/security.js +125 -0
- package/dist/plugins/sources/github.d.ts +17 -0
- package/dist/plugins/sources/github.js +77 -0
- package/dist/plugins/sources/local.d.ts +20 -0
- package/dist/plugins/sources/local.js +32 -0
- package/dist/plugins/sources/npm.d.ts +18 -0
- package/dist/plugins/sources/npm.js +82 -0
- package/dist/shared/llm/retry.d.ts +5 -2
- package/dist/shared/llm/retry.js +7 -3
- package/dist/shared/prompt-cache-latch.d.ts +41 -0
- package/dist/shared/prompt-cache-latch.js +63 -0
- package/dist/shared/retry-engine.d.ts +77 -0
- package/dist/shared/retry-engine.js +194 -0
- package/dist/workers/daemon.d.ts +8 -0
- package/dist/workers/daemon.js +13 -0
- package/dist/workers/quality-daemon/ci-monitor.d.ts +55 -0
- package/dist/workers/quality-daemon/ci-monitor.js +147 -0
- package/dist/workers/quality-daemon/coverage-delta.d.ts +72 -0
- package/dist/workers/quality-daemon/coverage-delta.js +135 -0
- package/dist/workers/quality-daemon/git-watcher.d.ts +51 -0
- package/dist/workers/quality-daemon/git-watcher.js +209 -0
- package/dist/workers/quality-daemon/index.d.ts +119 -0
- package/dist/workers/quality-daemon/index.js +343 -0
- package/dist/workers/quality-daemon/nightly-consolidation.d.ts +74 -0
- package/dist/workers/quality-daemon/nightly-consolidation.js +136 -0
- package/dist/workers/quality-daemon/notification-service.d.ts +67 -0
- package/dist/workers/quality-daemon/notification-service.js +178 -0
- package/dist/workers/quality-daemon/persistent-memory.d.ts +31 -0
- package/dist/workers/quality-daemon/persistent-memory.js +30 -0
- package/dist/workers/quality-daemon/priority-queue.d.ts +97 -0
- package/dist/workers/quality-daemon/priority-queue.js +126 -0
- package/dist/workers/quality-daemon/test-suggester.d.ts +50 -0
- package/dist/workers/quality-daemon/test-suggester.js +121 -0
- package/dist/workers/worker-manager.js +2 -1
- package/package.json +1 -1
- package/dist/mcp/server.d.ts +0 -46
- package/dist/mcp/server.js +0 -802
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.0");process.exit(0)}
|
|
2
|
+
import{i as l}from"./chunk-4YS3IJ45.js";import{a as p}from"./chunk-3JPRUND5.js";import{c as u}from"./chunk-4VUPRTVX.js";import{b as _,d as R}from"./chunk-WGMPEW2T.js";import{a as h,b}from"./chunk-263XS447.js";b();import f from"node:path";import{existsSync as v}from"node:fs";R();p();var T=u.create("metrics-tracker"),m=class{db=null;dbPath;initialized=!1;constructor(e=process.cwd()){this.dbPath=f.join(e,".agentic-qe","memory.db")}async initialize(){if(!this.initialized){if(!v(this.dbPath))throw new Error(`Database not found: ${this.dbPath}. Run "aqe init --auto" first.`);this.db=h(this.dbPath),this.ensureMetricsTable(),this.initialized=!0}}ensureMetricsTable(){this.db&&this.db.exec(`
|
|
3
|
+
CREATE TABLE IF NOT EXISTS learning_daily_snapshots (
|
|
4
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
5
|
+
snapshot_date TEXT NOT NULL UNIQUE,
|
|
6
|
+
total_patterns INTEGER DEFAULT 0,
|
|
7
|
+
patterns_created_today INTEGER DEFAULT 0,
|
|
8
|
+
total_experiences INTEGER DEFAULT 0,
|
|
9
|
+
experiences_today INTEGER DEFAULT 0,
|
|
10
|
+
total_q_values INTEGER DEFAULT 0,
|
|
11
|
+
avg_reward REAL DEFAULT 0.0,
|
|
12
|
+
avg_confidence REAL DEFAULT 0.0,
|
|
13
|
+
avg_quality_score REAL DEFAULT 0.0,
|
|
14
|
+
success_rate REAL DEFAULT 0.0,
|
|
15
|
+
pattern_reuse_count INTEGER DEFAULT 0,
|
|
16
|
+
short_term_patterns INTEGER DEFAULT 0,
|
|
17
|
+
long_term_patterns INTEGER DEFAULT 0,
|
|
18
|
+
domain_coverage_json TEXT,
|
|
19
|
+
created_at TEXT DEFAULT (datetime('now'))
|
|
20
|
+
);
|
|
21
|
+
CREATE INDEX IF NOT EXISTS idx_learning_daily_snapshots_date ON learning_daily_snapshots(snapshot_date DESC);
|
|
22
|
+
`)}async getCurrentMetrics(){if(this.initialized||await this.initialize(),!this.db)throw new Error("Database not initialized");let e=new Date().toISOString().split("T")[0],t=new Date(Date.now()-10080*60*1e3).toISOString().split("T")[0],a=this.getPatternStats(e),r=this.getExperienceStats(e),n=this.getQValueStats(),i=this.getDomainCoverage(),s=this.getHistoricalAvgReward(t);return{timestamp:new Date,totalPatterns:a.total,patternsCreatedToday:a.createdToday,totalExperiences:r.total,experiencesToday:r.recordedToday,totalQValues:n.total,avgReward:r.avgReward,avgRewardDelta:r.avgReward-s,domainCoverage:i,patternReuseCount:a.reuseCount,shortTermPatterns:a.shortTerm,longTermPatterns:a.longTerm,avgConfidence:a.avgConfidence,avgQualityScore:a.avgQualityScore,successRate:r.successRate}}getPatternStats(e){if(!this.db)return{total:0,createdToday:0,shortTerm:0,longTerm:0,avgConfidence:0,avgQualityScore:0,reuseCount:0};if(!this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='qe_patterns'").get())return{total:0,createdToday:0,shortTerm:0,longTerm:0,avgConfidence:0,avgQualityScore:0,reuseCount:0};let a=this.db.prepare(`
|
|
23
|
+
SELECT
|
|
24
|
+
COUNT(*) as total,
|
|
25
|
+
SUM(CASE WHEN date(created_at) = ? THEN 1 ELSE 0 END) as created_today,
|
|
26
|
+
SUM(CASE WHEN tier = 'short-term' THEN 1 ELSE 0 END) as short_term,
|
|
27
|
+
SUM(CASE WHEN tier = 'long-term' THEN 1 ELSE 0 END) as long_term,
|
|
28
|
+
AVG(confidence) as avg_confidence,
|
|
29
|
+
AVG(quality_score) as avg_quality_score,
|
|
30
|
+
SUM(usage_count) as total_usage
|
|
31
|
+
FROM qe_patterns
|
|
32
|
+
`).get(e);return{total:a.total||0,createdToday:a.created_today||0,shortTerm:a.short_term||0,longTerm:a.long_term||0,avgConfidence:a.avg_confidence||0,avgQualityScore:a.avg_quality_score||0,reuseCount:a.total_usage||0}}getExperienceStats(e){if(!this.db)return{total:0,recordedToday:0,avgReward:0,successRate:0};if(this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='captured_experiences'").get()){let r=this.db.prepare(`
|
|
33
|
+
SELECT
|
|
34
|
+
COUNT(*) as total,
|
|
35
|
+
SUM(CASE WHEN date(started_at) = ? THEN 1 ELSE 0 END) as recorded_today,
|
|
36
|
+
AVG(quality) as avg_reward,
|
|
37
|
+
AVG(CASE WHEN success = 1 THEN 1.0 ELSE 0.0 END) as success_rate
|
|
38
|
+
FROM captured_experiences
|
|
39
|
+
WHERE agent != 'cli-hook'
|
|
40
|
+
`).get(e);return{total:r.total||0,recordedToday:r.recorded_today||0,avgReward:r.avg_reward||0,successRate:r.success_rate||0}}if(this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='qe_pattern_usage'").get()){let r=this.db.prepare(`
|
|
41
|
+
SELECT
|
|
42
|
+
COUNT(*) as total,
|
|
43
|
+
SUM(CASE WHEN date(created_at) = ? THEN 1 ELSE 0 END) as recorded_today,
|
|
44
|
+
AVG(success) as success_rate
|
|
45
|
+
FROM qe_pattern_usage
|
|
46
|
+
`).get(e);return{total:r.total||0,recordedToday:r.recorded_today||0,avgReward:r.success_rate||0,successRate:r.success_rate||0}}return{total:0,recordedToday:0,avgReward:0,successRate:0}}getQValueStats(){return this.db?this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='rl_q_values'").get()?{total:this.db.prepare(`
|
|
47
|
+
SELECT COUNT(*) as total FROM rl_q_values
|
|
48
|
+
`).get().total||0}:{total:0}:{total:0}}getDomainCoverage(){let e={};for(let r of l)e[r]=0;if(!this.db||!this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='qe_patterns'").get())return e;let a=this.db.prepare(`
|
|
49
|
+
SELECT qe_domain, COUNT(*) as count
|
|
50
|
+
FROM qe_patterns
|
|
51
|
+
GROUP BY qe_domain
|
|
52
|
+
`).all();for(let r of a)l.includes(r.qe_domain)&&(e[r.qe_domain]=r.count);return e}getHistoricalAvgReward(e){return this.db&&this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='captured_experiences'").get()&&this.db.prepare(`
|
|
53
|
+
SELECT AVG(quality) as avg_reward
|
|
54
|
+
FROM captured_experiences
|
|
55
|
+
WHERE started_at <= datetime(?)
|
|
56
|
+
AND agent != 'cli-hook'
|
|
57
|
+
`).get(e+" 23:59:59")?.avg_reward||0}async getDashboardData(){this.initialized||await this.initialize();let e=await this.getCurrentMetrics(),t=await this.getMetricsHistory(7),a=t.map(s=>s.patternsCreatedToday),r=t.map(s=>s.experiencesToday),n=t.map(s=>s.avgReward),i=Object.entries(e.domainCoverage).filter(([s,o])=>o>0).sort((s,o)=>o[1]-s[1]).slice(0,5).map(([s,o])=>({domain:s,count:o}));return{current:e,history:t,trends:{patternsPerDay:a,experiencesPerDay:r,avgRewardPerDay:n},topDomains:i}}async getMetricsHistory(e){if(this.initialized||await this.initialize(),!this.db)return[];let t=[];if(!this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='learning_daily_snapshots'").get())return[];let r=this.db.prepare(`
|
|
58
|
+
SELECT *
|
|
59
|
+
FROM learning_daily_snapshots
|
|
60
|
+
ORDER BY snapshot_date DESC
|
|
61
|
+
LIMIT ?
|
|
62
|
+
`).all(e);for(let n of r){let i={};try{i=_(n.domain_coverage_json||"{}")}catch(s){T.debug("Domain coverage JSON parse failed",{error:s instanceof Error?s.message:String(s)});for(let o of l)i[o]=0}t.push({timestamp:new Date(n.snapshot_date),totalPatterns:n.total_patterns,patternsCreatedToday:n.patterns_created_today,totalExperiences:n.total_experiences,experiencesToday:n.experiences_today,totalQValues:n.total_q_values,avgReward:n.avg_reward,avgRewardDelta:0,domainCoverage:i,patternReuseCount:n.pattern_reuse_count,shortTermPatterns:n.short_term_patterns,longTermPatterns:n.long_term_patterns,avgConfidence:n.avg_confidence,avgQualityScore:n.avg_quality_score,successRate:n.success_rate})}return t}async saveSnapshot(){if(this.initialized||await this.initialize(),!this.db)throw new Error("Database not initialized");let e=await this.getCurrentMetrics(),t=new Date().toISOString().split("T")[0];this.db.prepare(`
|
|
63
|
+
INSERT OR REPLACE INTO learning_daily_snapshots (
|
|
64
|
+
snapshot_date,
|
|
65
|
+
total_patterns,
|
|
66
|
+
patterns_created_today,
|
|
67
|
+
total_experiences,
|
|
68
|
+
experiences_today,
|
|
69
|
+
total_q_values,
|
|
70
|
+
avg_reward,
|
|
71
|
+
avg_confidence,
|
|
72
|
+
avg_quality_score,
|
|
73
|
+
success_rate,
|
|
74
|
+
pattern_reuse_count,
|
|
75
|
+
short_term_patterns,
|
|
76
|
+
long_term_patterns,
|
|
77
|
+
domain_coverage_json
|
|
78
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
79
|
+
`).run(t,e.totalPatterns,e.patternsCreatedToday,e.totalExperiences,e.experiencesToday,e.totalQValues,e.avgReward,e.avgConfidence,e.avgQualityScore,e.successRate,e.patternReuseCount,e.shortTermPatterns,e.longTermPatterns,JSON.stringify(e.domainCoverage))}async getDashboardDataWithRegret(e){let t=await this.getDashboardData();return e&&e.length>0&&(t.regretHealth=e),t}close(){this.db&&(this.db.close(),this.db=null,this.initialized=!1)}};function M(c){return new m(c)}p();var E=u.create("regret-tracker"),d=50,y=.9,D=1.1;function S(c,e){let t=c.length;if(t<2)return 0;let a=0,r=0,n=0,i=0;for(let o=0;o<t;o++)a+=c[o],r+=e[o],n+=c[o]*e[o],i+=c[o]*c[o];let s=t*i-a*a;return Math.abs(s)<1e-10?0:(t*n-a*r)/s}var g=class{domains=new Map;alertCallbacks=[];alerts=[];maxAlerts;recentWindow;constructor(e){this.maxAlerts=e?.maxAlerts??100,this.recentWindow=e?.recentWindow??20}recordDecision(e,t,a){let r=this.getOrCreateDomainState(e),n=Math.max(0,a-t);if(r.cumulativeRegret+=n,r.decisionCount++,r.points.push({decisionCount:r.decisionCount,cumulativeRegret:r.cumulativeRegret,timestamp:Date.now()}),r.decisionCount>=d){let i=this.classifyGrowthRate(r.points);r.lastGrowthRate!=="insufficient_data"&&i!==r.lastGrowthRate&&this.emitAlert(e,r.lastGrowthRate,i),r.lastGrowthRate=i}}getCumulativeRegret(e){return this.domains.get(e)?.cumulativeRegret??0}getRegretCurve(e){let t=this.domains.get(e);return t?[...t.points]:[]}getRegretGrowthRate(e){let t=this.domains.get(e);return t?this.classifyGrowthRate(t.points):"insufficient_data"}detectStagnation(e){let t=this.getRegretGrowthRate(e);return t==="linear"||t==="superlinear"}getHealthSummary(){let e=[];for(let[t,a]of this.domains){let r=this.classifyGrowthRate(a.points),n=this.computeLogLogSlope(a.points),i=this.computeRecentAvgRegret(a);e.push({domain:t,totalDecisions:a.decisionCount,cumulativeRegret:a.cumulativeRegret,growthRate:r,stagnating:r==="linear"||r==="superlinear",slope:n,recentAvgRegret:i})}return e.sort((t,a)=>t.domain.localeCompare(a.domain)),e}onAlert(e){this.alertCallbacks.push(e)}getAlerts(){return[...this.alerts]}getTrackedDomains(){return[...this.domains.keys()].sort()}getTotalDecisions(){let e=0;for(let t of this.domains.values())e+=t.decisionCount;return e}reset(e){e?this.domains.delete(e):(this.domains.clear(),this.alerts=[])}getOrCreateDomainState(e){let t=this.domains.get(e);return t||(t={points:[],cumulativeRegret:0,decisionCount:0,lastGrowthRate:"insufficient_data"},this.domains.set(e,t)),t}classifyGrowthRate(e){if(e.length<d)return"insufficient_data";let t=this.computeLogLogSlope(e);return t===void 0?"insufficient_data":t<y?"sublinear":t<=D?"linear":"superlinear"}computeLogLogSlope(e){if(e.length<d)return;let t=e.filter(n=>n.cumulativeRegret>0&&n.decisionCount>0);if(t.length<2)return;let a=t.map(n=>Math.log(n.decisionCount)),r=t.map(n=>Math.log(n.cumulativeRegret));return S(a,r)}computeRecentAvgRegret(e){if(e.points.length<2)return 0;let t=Math.min(this.recentWindow,e.points.length),a=e.points.slice(-t),r=a[0],n=a[a.length-1],i=n.cumulativeRegret-r.cumulativeRegret,s=n.decisionCount-r.decisionCount;return s<=0?0:i/s}emitAlert(e,t,a){let r={domain:e,previousRate:t,newRate:a,timestamp:Date.now(),message:`Domain "${e}" regret growth changed from ${t} to ${a}`};this.alerts.push(r),this.alerts.length>this.maxAlerts&&this.alerts.shift(),E.info("Regret growth rate transition",{domain:e,previousRate:t,newRate:a});for(let n of this.alertCallbacks)try{n(r)}catch(i){E.error("Alert callback error",i instanceof Error?i:void 0)}}};function q(c){return new g(c)}export{M as a,q as b};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.0");process.exit(0)}
|
|
2
|
+
import{b as f,d as v}from"./chunk-WGMPEW2T.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
|
+
${this.options.title}
|
|
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};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.0");process.exit(0)}
|
|
2
|
+
import{a as L}from"./chunk-3ZOONQG6.js";import*as w from"fs";var R={"aqe test generate":{domain:"test-generation",action:"generateTests"},"aqe test execute":{domain:"test-execution",action:"execute"},"aqe coverage analyze":{domain:"coverage-analysis",action:"analyze"},"aqe coverage gaps":{domain:"coverage-analysis",action:"detectGaps"},"aqe quality gate":{domain:"quality-assessment",action:"evaluateGate"},"aqe quality assess":{domain:"quality-assessment",action:"analyzeQuality"},"aqe security scan":{domain:"security-compliance",action:"runSASTScan"},"aqe security audit":{domain:"security-compliance",action:"runAudit"},"aqe defect predict":{domain:"defect-intelligence",action:"predictDefects"},"aqe code index":{domain:"code-intelligence",action:"index"},"aqe code impact":{domain:"code-intelligence",action:"analyzeImpact"},"aqe contract validate":{domain:"contract-testing",action:"validateContract"},"aqe chaos test":{domain:"chaos-resilience",action:"runChaosTest"},"aqe requirements validate":{domain:"requirements-validation",action:"validateRequirements"},"aqe visual test":{domain:"visual-accessibility",action:"runVisualTest"},"aqe accessibility test":{domain:"visual-accessibility",action:"runAccessibilityTest"},"aqe learn optimize":{domain:"learning-optimization",action:"optimizeAllStrategies"}},D={daily:"0 0 * * *",weekly:"0 0 * * 0",hourly:"0 * * * *",minutely:"* * * * *"},S=1e4,x=20,M=1e4,W=["__proto__","constructor","prototype"];function v(t){return!W.includes(t)}function C(t){let n=t.split(`
|
|
3
|
+
`);if(n.length>S)throw new Error(`YAML content exceeds maximum allowed lines (${S}). File has ${n.length} lines.`);for(let i=0;i<n.length;i++)if(n[i].length>M)throw new Error(`YAML line ${i+1} exceeds maximum allowed length (${M} characters).`);let a={};for(let i=0;i<n.length;i++){let e=n[i];if(e.trim()===""||e.trim().startsWith("#")||e.search(/\S/)!==0)continue;let o=e.match(/^([\w_-]+):\s*(.+)$/);if(o){let[,c,u]=o;v(c)&&(a[c]=f(u))}}let r=["tags","stages","triggers"];for(let i of r){let e=new RegExp(`^${i}:\\s*$`),s=-1;for(let l=0;l<n.length;l++){let d=n[l];if(!(d.trim()===""||d.trim().startsWith("#"))&&e.test(d.trim())){s=l;break}}if(s===-1)continue;let o=[];a[i]=o;let c=n[s].search(/\S/),u=s+1;for(;u<n.length;){let l=n[u];if(l.trim()===""||l.trim().startsWith("#")){u++;continue}let d=l.search(/\S/),p=l.trim();if(d<=c&&!p.startsWith("-"))break;if(p.startsWith("- ")){let m=p.slice(2).trim();if(!m.includes(":")){o.push(f(m)),u++;continue}let g={},k=m.match(/^([\w_-]+):\s*(.*)$/);if(k){let[,h,y]=k;g[h]=f(y)}let T=d;for(u++;u<n.length;){let h=n[u];if(h.trim()===""||h.trim().startsWith("#")){u++;continue}let y=h.search(/\S/),q=h.trim();if(y<=T)break;let _=q.match(/^([\w_-]+):\s*(.*)$/);if(_){let[,A,$]=_;if($===""){let b=E(n,u+1,y,1);g[A]=b.value,u=b.nextLine;continue}else g[A]=f($)}u++}o.push(g)}else u++}}return a}function E(t,n,a,r=0){if(r>x)throw new Error(`YAML nesting exceeds maximum allowed depth (${x}).`);let i={},e=null,s=null,o=n;for(;o<t.length;){let u=t[o];if(u.trim()===""||u.trim().startsWith("#")){o++;continue}let l=u.search(/\S/),d=u.trim();if(l<=a)break;if(d.startsWith("- ")){let m=d.slice(2).trim();s&&!Array.isArray(i[s])&&(i[s]=[]),s?i[s].push(f(m)):(e||(e=[]),e.push(f(m))),o++;continue}let p=d.match(/^([\w_-]+):\s*(.*)$/);if(p){let[,m,g]=p;if(!v(m)){o++;continue}g===""?(s=m,i[m]=[]):(i[m]=f(g),s=null)}o++}if(e&&Object.keys(i).length===0)return{value:e,nextLine:o};let c=Object.keys(i);return c.length===1&&Array.isArray(i[c[0]])?{value:i[c[0]],nextLine:o}:{value:i,nextLine:o}}function f(t){if(t==="")return"";if(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))return t.slice(1,-1);if(t==="true")return!0;if(t==="false")return!1;if(t==="null"||t==="~")return null;let n=Number(t);return!isNaN(n)&&t!==""?n:t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1).split(",").map(r=>f(r.trim())):t}function K(t){let n=[];if(!w.existsSync(t))return{success:!1,errors:[`File not found: ${t}`]};let a;try{a=w.readFileSync(t,"utf-8")}catch(r){return{success:!1,errors:[`Failed to read file: ${r}`]}}return Y(a,t)}function Y(t,n){let a=[],r;try{r=C(t)}catch(s){return{success:!1,errors:[`Invalid YAML syntax: ${s}`]}}if((!r.name||typeof r.name!="string")&&a.push('Pipeline must have a "name" field'),(!r.stages||!Array.isArray(r.stages))&&a.push('Pipeline must have a "stages" array'),a.length>0)return{success:!1,errors:a};let i={name:r.name,description:r.description,version:r.version||"1.0.0",schedule:r.schedule,stages:r.stages.map((s,o)=>{let c=s;return{name:c.name||`stage-${o}`,command:c.command,params:c.params,depends_on:c.depends_on,condition:c.condition,timeout:c.timeout,retry:c.retry,continue_on_failure:c.continue_on_failure}}),triggers:r.triggers,tags:r.tags,timeout:r.timeout};for(let s=0;s<i.stages.length;s++){let o=i.stages[s];o.command||a.push(`Stage ${s+1} (${o.name}) must have a "command" field`)}if(a.length>0)return{success:!1,pipeline:i,errors:a};let e=O(i,n);return{success:!0,pipeline:i,workflow:e,errors:[]}}function O(t,n){let a=`pipeline-${t.name.replace(/\s+/g,"-").toLowerCase()}`,r=t.stages.map((e,s)=>{let o=P(e.command),c={};if(e.params)for(let[l,d]of Object.entries(e.params))v(l)&&(c[l]=`input.${l}`);let u={id:`stage-${e.name.replace(/\s+/g,"-").toLowerCase()}`,name:e.name,domain:o.domain,action:o.action,inputMapping:Object.keys(c).length>0?c:void 0,dependsOn:e.depends_on?.map(l=>`stage-${l.replace(/\s+/g,"-").toLowerCase()}`),timeout:e.timeout?e.timeout*1e3:void 0,continueOnFailure:e.continue_on_failure};return e.condition&&(u.condition={path:e.condition.path,operator:e.condition.operator,value:e.condition.value}),e.retry&&(u.retry={maxAttempts:e.retry.max_attempts||3,backoffMs:(e.retry.backoff_seconds||1)*1e3}),u}),i=t.triggers?.map(e=>{let s={eventType:I(e),sourceDomain:e.source_domain};return e.condition&&(s.condition={path:e.condition.path,operator:e.condition.operator,value:e.condition.value}),s});return{id:a,name:t.name,description:t.description||`Pipeline from ${n||"inline YAML"}`,version:t.version||"1.0.0",steps:r,triggers:i,tags:t.tags,timeout:t.timeout?t.timeout*1e3:void 0}}function P(t){let n=t.trim().replace(/\s+/g," ").toLowerCase();for(let[a,r]of Object.entries(R))if(n.startsWith(a.toLowerCase()))return r;return n.includes("test")&&n.includes("generate")?{domain:"test-generation",action:"generateTests"}:n.includes("test")&&(n.includes("execute")||n.includes("run"))?{domain:"test-execution",action:"execute"}:n.includes("coverage")?{domain:"coverage-analysis",action:"analyze"}:n.includes("quality")||n.includes("gate")?{domain:"quality-assessment",action:"evaluateGate"}:n.includes("security")||n.includes("scan")?{domain:"security-compliance",action:"runSASTScan"}:n.includes("defect")||n.includes("predict")?{domain:"defect-intelligence",action:"predictDefects"}:{domain:"learning-optimization",action:"runLearningCycle"}}function I(t){let n=t.event.toLowerCase();return n==="push"?"code-intelligence.CodePushed":n==="pull_request"||n==="pr"?"code-intelligence.PullRequestOpened":n==="schedule"?"workflow.ScheduleTrigger":n==="quality_gate"?"quality-assessment.QualityGateEvaluated":n==="test_complete"?"test-execution.TestRunCompleted":n}function F(t){let n=[],a=[];if(t.name||n.push({path:"name",message:"Pipeline name is required",severity:"error"}),!t.stages||t.stages.length===0)n.push({path:"stages",message:"Pipeline must have at least one stage",severity:"error"});else{let r=new Set;for(let e=0;e<t.stages.length;e++){let s=t.stages[e],o=`stages[${e}]`;if(r.has(s.name)&&n.push({path:`${o}.name`,message:`Duplicate stage name: ${s.name}`,severity:"error"}),r.add(s.name),s.command?P(s.command).domain==="learning-optimization"&&!s.command.toLowerCase().includes("learn")&&a.push({path:`${o}.command`,message:`Command "${s.command}" not recognized, will default to learning-optimization domain`,severity:"warning"}):n.push({path:`${o}.command`,message:"Stage must have a command",severity:"error"}),s.depends_on)for(let c of s.depends_on)t.stages.some(u=>u.name===c)||n.push({path:`${o}.depends_on`,message:`Unknown dependency: ${c}`,severity:"error"});s.timeout!==void 0&&s.timeout<=0&&n.push({path:`${o}.timeout`,message:"Timeout must be a positive number",severity:"error"}),s.retry&&s.retry.max_attempts!==void 0&&s.retry.max_attempts<1&&n.push({path:`${o}.retry.max_attempts`,message:"max_attempts must be at least 1",severity:"error"})}let i=N(t.stages);i&&n.push({path:"stages",message:`Circular dependency detected: ${i}`,severity:"error"})}if(t.schedule&&(z(t.schedule)||n.push({path:"schedule",message:`Invalid cron expression: ${t.schedule}`,severity:"error"})),t.triggers)for(let r=0;r<t.triggers.length;r++){let i=t.triggers[r],e=`triggers[${r}]`;i.event||n.push({path:`${e}.event`,message:"Trigger must have an event type",severity:"error"}),i.source_domain&&!L.includes(i.source_domain)&&a.push({path:`${e}.source_domain`,message:`Unknown domain: ${i.source_domain}`,severity:"warning"})}return{valid:n.length===0,errors:n,warnings:a}}function N(t){let n=new Set,a=new Set,r=(i,e)=>{if(a.has(i))return[...e,i].join(" -> ");if(n.has(i))return null;n.add(i),a.add(i);let s=t.find(o=>o.name===i);if(s?.depends_on)for(let o of s.depends_on){let c=r(o,[...e,i]);if(c)return c}return a.delete(i),null};for(let i of t){let e=r(i.name,[]);if(e)return e}return null}function z(t){if(Object.keys(D).includes(t))return!0;let n=t.trim().split(/\s+/);if(n.length!==5)return!1;let a=[/^(\*|[0-5]?\d)(-[0-5]?\d)?(\/\d+)?$/,/^(\*|1?\d|2[0-3])(-\d+)?(\/\d+)?$/,/^(\*|[1-9]|[12]\d|3[01])(-\d+)?(\/\d+)?$/,/^(\*|[1-9]|1[0-2])(-\d+)?(\/\d+)?$/,/^(\*|[0-7])(-[0-7])?(\/\d+)?$/];for(let r=0;r<5;r++){let i=n[r].split(",");for(let e of i)if(!a[r].test(e)&&e!=="*")return!1}return!0}function G(t){let n={"@daily":"Daily at midnight","@weekly":"Weekly on Sunday at midnight","@hourly":"Every hour","@minutely":"Every minute"};if(n[t])return n[t];if(Object.keys(D).includes(t))return{daily:"Daily at midnight",weekly:"Weekly on Sunday at midnight",hourly:"Every hour",minutely:"Every minute"}[t]||t;let a=t.trim().split(/\s+/);if(a.length!==5)return t;let[r,i,e,s,o]=a;return r==="0"&&i==="0"&&e==="*"&&s==="*"&&o==="*"?"Daily at midnight":r==="0"&&e==="*"&&s==="*"&&o==="*"?`Daily at ${i}:00`:r!=="*"&&i!=="*"&&e==="*"&&s==="*"?`Daily at ${i}:${r.padStart(2,"0")}`:i==="*"&&r==="0"?"Every hour":r!=="*"&&i==="*"?`Every hour at minute ${r}`:t}function H(t,n=new Date){let a=t.trim().split(/\s+/);if(a.length!==5)return new Date(n.getTime()+1440*60*1e3);let[r,i]=a,e=new Date(n);return i!=="*"&&r!=="*"?(e.setHours(parseInt(i,10),parseInt(r,10),0,0),e<=n&&e.setDate(e.getDate()+1)):i!=="*"?(e.setHours(parseInt(i,10),0,0,0),e<=n&&e.setDate(e.getDate()+1)):r!=="*"?(e.setMinutes(parseInt(r,10),0,0),e<=n&&e.setHours(e.getHours()+1)):(e.setSeconds(0,0),e.setMinutes(e.getMinutes()+1)),e}export{C as a,K as b,F as c,G as d,H as e};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.0");process.exit(0)}
|
|
2
|
+
import T from"crypto";var h=new Uint8Array(256),y=h.length;function s(){return y>h.length-16&&(T.randomFillSync(h),y=0),h.slice(y,y+=16)}var A=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function q(r){return typeof r=="string"&&A.test(r)}var u=q;var o=[];for(let r=0;r<256;++r)o.push((r+256).toString(16).slice(1));function p(r,e=0){return o[r[e+0]]+o[r[e+1]]+o[r[e+2]]+o[r[e+3]]+"-"+o[r[e+4]]+o[r[e+5]]+"-"+o[r[e+6]]+o[r[e+7]]+"-"+o[r[e+8]]+o[r[e+9]]+"-"+o[r[e+10]]+o[r[e+11]]+o[r[e+12]]+o[r[e+13]]+o[r[e+14]]+o[r[e+15]]}function N(r,e=0){let t=p(r,e);if(!u(t))throw TypeError("Stringified UUID is invalid");return t}var _=N;var E,U,I=0,w=0;function R(r,e,t){let n=e&&t||0,f=e||new Array(16);r=r||{};let d=r.node||E,l=r.clockseq!==void 0?r.clockseq:U;if(d==null||l==null){let a=r.random||(r.rng||s)();d==null&&(d=E=[a[0]|1,a[1],a[2],a[3],a[4],a[5]]),l==null&&(l=U=(a[6]<<8|a[7])&16383)}let c=r.msecs!==void 0?r.msecs:Date.now(),x=r.nsecs!==void 0?r.nsecs:w+1,i=c-I+(x-w)/1e4;if(i<0&&r.clockseq===void 0&&(l=l+1&16383),(i<0||c>I)&&r.nsecs===void 0&&(x=0),x>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");I=c,w=x,U=l,c+=122192928e5;let m=((c&268435455)*1e4+x)%4294967296;f[n++]=m>>>24&255,f[n++]=m>>>16&255,f[n++]=m>>>8&255,f[n++]=m&255;let v=c/4294967296*1e4&268435455;f[n++]=v>>>8&255,f[n++]=v&255,f[n++]=v>>>24&15|16,f[n++]=v>>>16&255,f[n++]=l>>>8|128,f[n++]=l&255;for(let a=0;a<6;++a)f[n+a]=d[a];return e||p(f)}var C=R;function H(r){if(!u(r))throw TypeError("Invalid UUID");let e,t=new Uint8Array(16);return t[0]=(e=parseInt(r.slice(0,8),16))>>>24,t[1]=e>>>16&255,t[2]=e>>>8&255,t[3]=e&255,t[4]=(e=parseInt(r.slice(9,13),16))>>>8,t[5]=e&255,t[6]=(e=parseInt(r.slice(14,18),16))>>>8,t[7]=e&255,t[8]=(e=parseInt(r.slice(19,23),16))>>>8,t[9]=e&255,t[10]=(e=parseInt(r.slice(24,36),16))/1099511627776&255,t[11]=e/4294967296&255,t[12]=e>>>24&255,t[13]=e>>>16&255,t[14]=e>>>8&255,t[15]=e&255,t}var D=H;function L(r){r=unescape(encodeURIComponent(r));let e=[];for(let t=0;t<r.length;++t)e.push(r.charCodeAt(t));return e}var M="6ba7b810-9dad-11d1-80b4-00c04fd430c8",P="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function g(r,e,t){function n(f,d,l,c){var x;if(typeof f=="string"&&(f=L(f)),typeof d=="string"&&(d=D(d)),((x=d)===null||x===void 0?void 0:x.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let i=new Uint8Array(16+f.length);if(i.set(d),i.set(f,d.length),i=t(i),i[6]=i[6]&15|e,i[8]=i[8]&63|128,l){c=c||0;for(let m=0;m<16;++m)l[c+m]=i[m];return l}return p(i)}try{n.name=r}catch{}return n.DNS=M,n.URL=P,n}import F from"crypto";function G(r){return Array.isArray(r)?r=Buffer.from(r):typeof r=="string"&&(r=Buffer.from(r,"utf8")),F.createHash("md5").update(r).digest()}var k=G;var X=g("v3",48,k),$=X;import j from"crypto";var S={randomUUID:j.randomUUID};function z(r,e,t){if(S.randomUUID&&!e&&!r)return S.randomUUID();r=r||{};let n=r.random||(r.rng||s)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){t=t||0;for(let f=0;f<16;++f)e[t+f]=n[f];return e}return p(n)}var J=z;import K from"crypto";function O(r){return Array.isArray(r)?r=Buffer.from(r):typeof r=="string"&&(r=Buffer.from(r,"utf8")),K.createHash("sha1").update(r).digest()}var B=O;var Q=g("v5",80,B),V=Q;var W="00000000-0000-0000-0000-000000000000";function Y(r){if(!u(r))throw TypeError("Invalid UUID");return parseInt(r.slice(14,15),16)}var Z=Y;export{u as a,_ as b,C as c,D as d,$ as e,J as f,V as g,W as h,Z as i};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.0");process.exit(0)}
|
|
2
|
+
var n=class{constructor(t){this.capacity=t;this.buffer=new Array(t)}buffer;head=0;tail=0;count=0;push(t){this.buffer[this.tail]=t,this.tail=(this.tail+1)%this.capacity,this.count<this.capacity?this.count++:this.head=(this.head+1)%this.capacity}toArray(){let t=[];for(let e=0;e<this.count;e++){let i=(this.head+e)%this.capacity;t.push(this.buffer[i])}return t}get length(){return this.count}get size(){return this.count}clear(){this.buffer=new Array(this.capacity),this.head=0,this.tail=0,this.count=0}last(t){let e=[],i=Math.max(0,this.count-t);for(let s=i;s<this.count;s++){let r=(this.head+s)%this.capacity;e.push(this.buffer[r])}return e}percentile(t){if(this.count===0)return;let e=this.toArray().sort((s,r)=>Number(s)-Number(r)),i=Math.floor(t/100*(e.length-1));return e[i]}reduce(t,e){let i=e;for(let s=0;s<this.count;s++){let r=(this.head+s)%this.capacity;i=t(i,this.buffer[r])}return i}average(){return this.count===0?0:this.reduce((e,i)=>e+i,0)/this.count}};export{n as a};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.0");process.exit(0)}
|
|
2
|
+
import{a as b}from"./chunk-3JPRUND5.js";import{c as k}from"./chunk-4VUPRTVX.js";import{b as p,d as C}from"./chunk-WGMPEW2T.js";C();b();var m=k.create("skill-validation-learner"),v=class{constructor(e){this.reasoningBank=e}memoryNamespace="skill-validation";feedbackLoop=null;connectFeedbackLoop(e){this.feedbackLoop=e}async recordValidationOutcome(e){await this.reasoningBank.storeQEPattern({patternType:"test-template",name:`${e.skillName}-validation-${e.validationLevel}`,description:`Validation outcome for ${e.skillName} at level ${e.validationLevel}`,context:{tags:["skill-validation",e.skillName,e.model,e.validationLevel],testType:"integration"},template:{type:"config",content:JSON.stringify({outcome:{skillName:e.skillName,trustTier:e.trustTier,validationLevel:e.validationLevel,model:e.model,passed:e.passed,score:e.score,testCaseCount:e.testCaseResults.length,passedTests:e.testCaseResults.filter(s=>s.passed).length,avgReasoningQuality:this.calculateAvgReasoningQuality(e.testCaseResults),timestamp:e.timestamp.toISOString(),runId:e.runId,metadata:e.metadata}}),variables:[]}}),await this.updateSkillConfidence(e),e.validationLevel==="eval"&&await this.trackCrossModelBehavior(e),this.feedbackLoop&&e.runId&&await this.recordToFeedbackLoop(e)}async updateSkillConfidence(e){let s=`skill-confidence-${e.skillName}`,n=await this.reasoningBank.searchQEPatterns(s,{limit:1}),t;if(n.success&&n.value.length>0)try{let r=n.value[0].pattern.template?.content;if(r){let i=p(r);i&&typeof i=="object"&&Array.isArray(i.outcomes)?t=i:t=this.createEmptyConfidence(e.skillName)}else t=this.createEmptyConfidence(e.skillName)}catch(a){m.debug("Confidence history parse failed",{skill:e.skillName,error:a instanceof Error?a.message:String(a)}),t=this.createEmptyConfidence(e.skillName)}else t=this.createEmptyConfidence(e.skillName);t.outcomes.push({score:e.score,timestamp:e.timestamp,model:e.model,validationLevel:e.validationLevel,passed:e.passed}),t.outcomes.length>100&&(t.outcomes=t.outcomes.slice(-100)),t.avgScore=t.outcomes.reduce((a,r)=>a+r.score,0)/t.outcomes.length,t.lastUpdated=new Date,t.trend=this.calculateTrend(t.outcomes),t.byLevel=this.calculateConfidenceByLevel(t.outcomes),await this.reasoningBank.storeQEPattern({patternType:"test-template",name:s,description:`Skill confidence tracking for ${e.skillName}`,context:{tags:["skill-confidence",e.skillName]},template:{type:"config",content:JSON.stringify(t),variables:[]}})}async trackCrossModelBehavior(e){let s=`cross-model-${e.skillName}`,n=await this.reasoningBank.searchQEPatterns(s,{limit:1}),t;if(n.success&&n.value.length>0)try{let c=n.value[0].pattern.template?.content;if(c){let l=p(c);l&&typeof l=="object"&&typeof l.models=="object"?t=l:t=this.createEmptyCrossModelAnalysis()}else t=this.createEmptyCrossModelAnalysis()}catch(o){m.debug("Cross-model analysis parse failed",{error:o instanceof Error?o.message:String(o)}),t=this.createEmptyCrossModelAnalysis()}else t=this.createEmptyCrossModelAnalysis();t.models||(t.models={}),t.models[e.model]||(t.models[e.model]={scores:[],passRate:0,avgReasoningQuality:0,sampleCount:0});let a=t.models[e.model];a.scores.push(e.score),a.sampleCount++,a.scores.length>50&&(a.scores=a.scores.slice(-50));let r=this.calculateAvgReasoningQuality(e.testCaseResults);a.passRate=a.scores.filter(o=>o>=.9).length/a.scores.length,a.avgReasoningQuality=(a.avgReasoningQuality*(a.sampleCount-1)+r)/a.sampleCount;let i=Object.values(t.models).map(o=>o.passRate);if(i.length>1){let o=i.reduce((l,d)=>l+d,0)/i.length,c=i.reduce((l,d)=>l+Math.pow(d-o,2),0)/i.length;t.variance=c,t.hasAnomalies=c>.04,t.anomalies=[];for(let[l,d]of Object.entries(t.models))Math.abs(d.passRate-o)>.2&&t.anomalies.push({model:l,type:d.passRate<o?"low_performance":"high_variance",description:`Model ${l} has ${((d.passRate-o)*100).toFixed(1)}% difference from average`})}t.lastUpdated=new Date,await this.reasoningBank.storeQEPattern({patternType:"test-template",name:s,description:`Cross-model behavior tracking for ${e.skillName}`,context:{tags:["cross-model",e.skillName]},template:{type:"config",content:JSON.stringify(t),variables:[]}})}async recordToFeedbackLoop(e){if(!this.feedbackLoop)return;let s={taskId:e.runId,taskDescription:`Skill validation: ${e.skillName} (${e.validationLevel})`,recommendedAgent:"skill-validator",usedAgent:"skill-validator",followedRecommendation:!0,success:e.passed,qualityScore:e.score,durationMs:e.metadata?.duration||0,timestamp:e.timestamp};await this.feedbackLoop.recordRoutingOutcome(s)}async getSkillConfidence(e){let s=`skill-confidence-${e}`,n=await this.reasoningBank.searchQEPatterns(s,{limit:1});if(n.success&&n.value.length>0)try{let t=n.value[0].pattern.template?.content;if(t)return p(t)}catch(t){m.debug("Skill confidence pattern content invalid",{skill:e,error:t instanceof Error?t.message:String(t)})}return null}async getCrossModelAnalysis(e){let s=`cross-model-${e}`,n=await this.reasoningBank.searchQEPatterns(s,{limit:1});if(n.success&&n.value.length>0)try{let t=n.value[0].pattern.template?.content;if(t)return p(t)}catch(t){m.debug("Cross-model pattern content invalid",{skill:e,error:t instanceof Error?t.message:String(t)})}return null}async queryValidationPatterns(e,s=10){let n=await this.reasoningBank.searchQEPatterns(`${e} validation`,{limit:s});return n.success?n.value.filter(t=>t.pattern.context?.tags?.includes("skill-validation")).map(t=>t.pattern):[]}async getValidationTrends(e){let s=await this.getSkillConfidence(e),n=await this.getCrossModelAnalysis(e);if(!s)return null;let t={};if(n)for(let i of Object.keys(n.models)){let o=s.outcomes.filter(c=>c.model===i).map(c=>({score:c.score}));t[i]=this.calculateTrend(o)}let a=s.outcomes.slice(-20),r=a.filter(i=>i.passed).length/a.length;return{overall:s.trend||"stable",byModel:t,recentPassRate:r}}async extractLearnedPatterns(e){let s=await this.queryValidationPatterns(e,50),n=[],t=new Map;for(let a of s)try{let i=p(a.template?.content||"{}").outcome?.metadata?.category||"general";t.has(i)||t.set(i,[]),t.get(i).push(a)}catch(r){m.debug("Invalid pattern during category grouping",{error:r instanceof Error?r.message:String(r)})}for(let[a,r]of Array.from(t.entries())){let i=new Set,o=new Set,c=new Set,l=0;for(let d of r)try{let f=p(d.template?.content||"{}").outcome;if(!f)continue;c.add(f.model),l+=f.score;let h=d.context?.tags||[];f.passed?h.filter(g=>!["skill-validation",e].includes(g)).forEach(g=>i.add(g)):h.filter(g=>!["skill-validation",e].includes(g)).forEach(g=>o.add(g))}catch(u){m.debug("Invalid pattern during category extraction",{error:u instanceof Error?u.message:String(u)})}r.length>0&&n.push({id:`${e}-${a}`,skillName:e,category:a,successIndicators:Array.from(i),failureIndicators:Array.from(o),models:Array.from(c),confidence:l/r.length,observationCount:r.length})}return n}createEmptyConfidence(e){return{skillName:e,avgScore:0,outcomes:[],lastUpdated:new Date}}createEmptyCrossModelAnalysis(){return{models:{},variance:0,hasAnomalies:!1,lastUpdated:new Date}}calculateAvgReasoningQuality(e){return e.length===0?0:e.reduce((s,n)=>s+n.reasoningQuality,0)/e.length}calculateTrend(e){if(e.length<5)return"stable";let s=e.slice(-10),n=e.slice(-20,-10);if(n.length===0)return"stable";let t=s.reduce((i,o)=>i+o.score,0)/s.length,a=n.reduce((i,o)=>i+o.score,0)/n.length,r=t-a;return r>.05?"improving":r<-.05?"declining":"stable"}calculateConfidenceByLevel(e){let s={schema:[],validator:[],eval:[]};for(let t of e)t.validationLevel&&s[t.validationLevel].push(t.score);let n={};for(let[t,a]of Object.entries(s))a.length>0&&(n[t]=a.reduce((r,i)=>r+i,0)/a.length);return n}};function L(y){return new v(y)}export{L as a};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.0");process.exit(0)}
|
|
2
|
+
import{f as d}from"./chunk-NZ2VCPN4.js";import{a as u,c as g}from"./chunk-JZSDOIXA.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};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.0");process.exit(0)}
|
|
2
|
+
import{c as t,e as o}from"./chunk-4I2IOUS4.js";var L={};o(L,{DotProductAttention:()=>d,FlashAttention:()=>m,HyperbolicAttention:()=>f,LinearAttention:()=>h,MoEAttention:()=>_,MultiHeadAttention:()=>A,RuvectorLayer:()=>a,SonaEngine:()=>g,TensorCompress:()=>c,default:()=>i,differentiableSearch:()=>l,getCompressionLevel:()=>s,hierarchicalForward:()=>p,init:()=>u,pipeline:()=>v});import{createRequire as n}from"module";var r,e,i,a,c,l,p,s,u,m,d,A,f,h,_,g,v,b=t(()=>{r=n(import.meta.url),e=r("@ruvector/gnn"),i=e,{RuvectorLayer:a,TensorCompress:c,differentiableSearch:l,hierarchicalForward:p,getCompressionLevel:s,init:u,FlashAttention:m,DotProductAttention:d,MultiHeadAttention:A,HyperbolicAttention:f,LinearAttention:h,MoEAttention:_,SonaEngine:g,pipeline:v}=e||{}});export{L as a,b};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.0");process.exit(0)}
|
|
2
|
+
import{a as I}from"./chunk-5SKGFSKD.js";import{a as A,b as m,c as d}from"./chunk-3ZOONQG6.js";import{f as D}from"./chunk-SUSEVMZT.js";import{n as F,o as q}from"./chunk-JJO7Y4H3.js";import{a as b,b as W,c as O}from"./chunk-JZSDOIXA.js";import{g as T}from"./chunk-4I2IOUS4.js";O();var w={WorkflowStarted:"workflow.WorkflowStarted",WorkflowCompleted:"workflow.WorkflowCompleted",WorkflowFailed:"workflow.WorkflowFailed",WorkflowCancelled:"workflow.WorkflowCancelled",StepStarted:"workflow.StepStarted",StepCompleted:"workflow.StepCompleted",StepFailed:"workflow.StepFailed",StepSkipped:"workflow.StepSkipped",StepAwaitingApproval:"workflow.StepAwaitingApproval",StepApproved:"workflow.StepApproved",StepRejected:"workflow.StepRejected"},E={maxConcurrentWorkflows:10,defaultStepTimeout:6e4,defaultWorkflowTimeout:6e5,enableEventTriggers:!0,persistExecutions:!0};function S(){try{let{getUnifiedMemory:s}=(q(),T(F)),e=s();return e.isInitialized()?e.getDatabase():null}catch{return null}}var N={id:"quality-gate-check",domain:"quality-assessment",action:"gate-check",async execute(s){let e=typeof s.coverageMin=="number"?s.coverageMin:80,t=typeof s.testsPassingMin=="number"?s.testsPassingMin:90,i=typeof s.maxBugs=="number"?s.maxBugs:5,r=typeof s.currentCoverage=="number"?s.currentCoverage:null,n=typeof s.currentTestsPassingRate=="number"?s.currentTestsPassingRate:null,o=typeof s.currentBugs=="number"?s.currentBugs:null;if(r===null||n===null||o===null){let p=S();if(p)try{if(r===null&&(r=p.prepare("SELECT after_lines FROM coverage_sessions ORDER BY created_at DESC LIMIT 1").get()?.after_lines??0),n===null){let y=p.prepare(`SELECT COUNT(*) as total,
|
|
3
|
+
SUM(CASE WHEN passed = 1 THEN 1 ELSE 0 END) as passed
|
|
4
|
+
FROM test_outcomes
|
|
5
|
+
WHERE created_at > datetime('now', '-7 days')`).get();n=y&&y.total>0?y.passed/y.total*100:0}o===null&&(o=p.prepare(`SELECT COUNT(*) as bugs FROM test_outcomes
|
|
6
|
+
WHERE passed = 0 AND flaky = 0
|
|
7
|
+
AND created_at > datetime('now', '-7 days')`).get()?.bugs??0)}catch{}}r=r??0,n=n??0,o=o??0;let c=r>=e,a=n>=t,l=o<=i,g=c&&a&&l,k=Math.min(r/e,1),v=Math.min(n/t,1),u=i>0?Math.max(0,1-o/i):o===0?1:0,f=(k+v+u)/3;return m({passed:g,score:Math.round(f*100)/100,source:typeof s.currentCoverage=="number"?"input":"database",details:{coverage:{current:r,threshold:e,passed:c},testsPassing:{current:n,threshold:t,passed:a},bugs:{current:o,threshold:i,passed:l}}})}},_={id:"coverage-threshold",domain:"coverage-analysis",action:"threshold-check",async execute(s){let e=typeof s.minCoverage=="number"?s.minCoverage:80,t=typeof s.currentCoverage=="number"?s.currentCoverage:null,i="input";if(t===null){i="database";let o=S();if(o)try{t=o.prepare("SELECT after_lines FROM coverage_sessions ORDER BY created_at DESC LIMIT 1").get()?.after_lines??0}catch{t=0}else t=0}let r=t>=e,n=r?0:Math.round((e-t)*100)/100;return m({currentCoverage:t,passed:r,gap:n,minCoverage:e,source:i})}},L={id:"pattern-health",domain:"learning-optimization",action:"health-check",async execute(s){let e=typeof s.totalPatterns=="number"?s.totalPatterns:null,t=typeof s.activePatterns=="number"?s.activePatterns:null,i=typeof s.avgConfidence=="number"?s.avgConfidence:null,r="input";if(e===null||t===null||i===null){r="database";let a=S();if(a)try{let l=a.prepare(`
|
|
8
|
+
SELECT COUNT(*) as total,
|
|
9
|
+
SUM(CASE WHEN deprecated_at IS NULL AND confidence >= 0.3 THEN 1 ELSE 0 END) as active,
|
|
10
|
+
AVG(confidence) as avg_conf
|
|
11
|
+
FROM qe_patterns
|
|
12
|
+
`).get();e=e??l?.total??0,t=t??l?.active??0,i=i??l?.avg_conf??0}catch{}}e=e??0,t=t??0,i=i??0;let n=Math.min(e/100,1),o=e>0?t/e:0,c=Math.round((n*.3+o*.3+i*.4)*100)/100;return m({totalPatterns:e,activePatterns:t,avgConfidence:i,healthScore:c,source:r})}},z={id:"routing-accuracy",domain:"learning-optimization",action:"routing-check",async execute(s){let e=typeof s.totalOutcomes=="number"?s.totalOutcomes:null,t=typeof s.successfulOutcomes=="number"?s.successfulOutcomes:null,i=typeof s.confidenceCorrelation=="number"?s.confidenceCorrelation:null,r="input";if(e===null||t===null){r="database";let o=S();if(o)try{let c=o.prepare(`
|
|
13
|
+
SELECT COUNT(*) as total,
|
|
14
|
+
SUM(CASE WHEN success = 1 THEN 1 ELSE 0 END) as successful
|
|
15
|
+
FROM routing_outcomes
|
|
16
|
+
`).get();e=e??c?.total??0,t=t??c?.successful??0}catch{}}e=e??0,t=t??0,i=i??0;let n=e>0?Math.round(t/e*1e4)/100:0;return m({successRate:n,totalOutcomes:e,successfulOutcomes:t,confidenceCorrelation:i,source:r})}},$=[N,_,L,z];function R(s,e){return $.find(t=>t.domain===s&&t.action===e)}function M(){return[B(),U(),G(),j(),H(),Q()]}var P=["comprehensive-testing","defect-prevention","pre-release","continuous-learning","morning-sync","qcsd-ideation-swarm"];function B(){return{id:"comprehensive-testing",name:"Comprehensive Testing Workflow",description:"test-generation -> test-execution -> coverage-analysis -> quality-assessment",version:"1.0.0",tags:["testing","quality"],steps:[{id:"generate-tests",name:"Generate Tests",domain:"test-generation",action:"generateTests",inputMapping:{sourceFiles:"input.sourceFiles",framework:"input.framework"},outputMapping:{testFiles:"generatedTests.files",testCount:"generatedTests.count"},timeout:12e4,retry:{maxAttempts:2,backoffMs:1e3}},{id:"execute-tests",name:"Execute Tests",domain:"test-execution",action:"execute",dependsOn:["generate-tests"],inputMapping:{testFiles:"results.generatedTests.files"},outputMapping:{runId:"execution.runId",passed:"execution.passed",failed:"execution.failed"},timeout:3e5},{id:"analyze-coverage",name:"Analyze Coverage",domain:"coverage-analysis",action:"analyze",dependsOn:["execute-tests"],inputMapping:{runId:"results.execution.runId"},outputMapping:{line:"coverage.line",branch:"coverage.branch",overall:"coverage.overall"}},{id:"assess-quality",name:"Assess Quality",domain:"quality-assessment",action:"evaluateGate",dependsOn:["analyze-coverage"],inputMapping:{coverage:"results.coverage",testResults:"results.execution"},outputMapping:{passed:"quality.gatePassed",score:"quality.score"}},{id:"generate-more-tests",name:"Generate Additional Tests",domain:"test-generation",action:"generateTests",dependsOn:["analyze-coverage"],condition:{path:"results.coverage.overall",operator:"lt",value:80},inputMapping:{sourceFiles:"input.sourceFiles",targetCoverage:"input.targetCoverage"},continueOnFailure:!0}]}}function U(){return{id:"defect-prevention",name:"Defect Prevention Workflow",description:"code-intelligence (impact) -> defect-intelligence (predict) -> test-generation (for risky areas)",version:"1.0.0",tags:["defect","prevention","ai"],steps:[{id:"analyze-impact",name:"Analyze Code Impact",domain:"code-intelligence",action:"analyzeImpact",inputMapping:{changedFiles:"input.changedFiles"},outputMapping:{impactedFiles:"impact.files",impactedTests:"impact.tests",riskLevel:"impact.riskLevel"},timeout:6e4},{id:"predict-defects",name:"Predict Defects",domain:"defect-intelligence",action:"predictDefects",dependsOn:["analyze-impact"],inputMapping:{files:"results.impact.files"},outputMapping:{predictions:"defects.predictions",highRiskFiles:"defects.highRiskFiles"}},{id:"generate-targeted-tests",name:"Generate Targeted Tests",domain:"test-generation",action:"generateTests",dependsOn:["predict-defects"],condition:{path:"results.defects.highRiskFiles",operator:"exists",value:!0},inputMapping:{sourceFiles:"results.defects.highRiskFiles",priority:"input.priority"}}],triggers:[{eventType:"code-intelligence.ImpactAnalysisCompleted",inputMapping:{changedFiles:"event.changedFiles"}}]}}function G(){return{id:"pre-release",name:"Pre-Release Workflow",description:"security-audit -> quality-gate -> deployment-advisor",version:"1.0.0",tags:["release","security","deployment"],steps:[{id:"security-audit",name:"Security Audit",domain:"security-compliance",action:"runAudit",inputMapping:{targetFiles:"input.targetFiles",includeDependencies:"input.includeDependencies"},outputMapping:{vulnerabilities:"security.vulnerabilities",riskScore:"security.riskScore",passed:"security.passed"},timeout:18e4},{id:"quality-gate",name:"Quality Gate Evaluation",domain:"quality-assessment",action:"evaluateGate",dependsOn:["security-audit"],inputMapping:{securityResults:"results.security",releaseCandidate:"input.releaseCandidate"},outputMapping:{passed:"quality.gatePassed",checks:"quality.checks"}},{id:"deployment-advice",name:"Get Deployment Advice",domain:"quality-assessment",action:"getDeploymentAdvice",dependsOn:["quality-gate"],inputMapping:{releaseCandidate:"input.releaseCandidate",qualityResults:"results.quality",securityResults:"results.security"},outputMapping:{decision:"deployment.decision",recommendations:"deployment.recommendations",riskScore:"deployment.riskScore"}}],triggers:[{eventType:"quality-assessment.QualityGateEvaluated",condition:{path:"event.passed",operator:"eq",value:!0}}]}}function j(){return{id:"continuous-learning",name:"Continuous Learning Workflow",description:"Collect patterns -> consolidate -> transfer -> optimize",version:"1.0.0",tags:["learning","optimization","ai"],steps:[{id:"collect-patterns",name:"Collect Patterns",domain:"learning-optimization",action:"runLearningCycle",inputMapping:{domain:"input.targetDomain"},outputMapping:{patternsLearned:"learning.patterns",experiencesProcessed:"learning.experiences"}},{id:"consolidate-patterns",name:"Consolidate Patterns",domain:"learning-optimization",action:"shareCrossDomainLearnings",dependsOn:["collect-patterns"],condition:{path:"results.learning.patterns",operator:"gt",value:0},outputMapping:{knowledgeShared:"consolidation.shared",domainsUpdated:"consolidation.domains"}},{id:"transfer-knowledge",name:"Transfer Knowledge",domain:"learning-optimization",action:"shareCrossDomainLearnings",dependsOn:["consolidate-patterns"],outputMapping:{transferSuccessRate:"transfer.successRate",newPatternsCreated:"transfer.newPatterns"}},{id:"optimize-strategies",name:"Optimize Strategies",domain:"learning-optimization",action:"optimizeAllStrategies",dependsOn:["transfer-knowledge"],outputMapping:{domainsOptimized:"optimization.domains",avgImprovement:"optimization.improvement"}}]}}function H(){return{id:"morning-sync",name:"Morning Sync Protocol",description:"Daily quality synchronization across all domains",version:"1.0.0",tags:["protocol","daily","sync"],steps:[{id:"collect-metrics",name:"Collect Quality Metrics",domain:"quality-assessment",action:"analyzeQuality",inputMapping:{sourceFiles:"input.sourceFiles"},outputMapping:{score:"metrics.qualityScore"}},{id:"analyze-trends",name:"Analyze Coverage Trends",domain:"coverage-analysis",action:"getTrend",inputMapping:{timeRange:"input.timeRange",granularity:"input.granularity"},outputMapping:{trend:"trends.coverage",forecast:"trends.forecast"}},{id:"check-security",name:"Check Security Posture",domain:"security-compliance",action:"getSecurityPosture",outputMapping:{overallScore:"security.score",criticalIssues:"security.critical",recommendations:"security.recommendations"}},{id:"get-defect-predictions",name:"Get Defect Predictions",domain:"defect-intelligence",action:"predictDefects",inputMapping:{files:"input.changedFiles"},outputMapping:{predictions:"defects.predictions"}},{id:"generate-learning-report",name:"Generate Learning Dashboard",domain:"learning-optimization",action:"getLearningDashboard",dependsOn:["collect-metrics","analyze-trends","check-security","get-defect-predictions"],outputMapping:{learningRate:"learning.rate",topDomains:"learning.topDomains"}}]}}function Q(){return{id:"qcsd-ideation-swarm",name:"QCSD Ideation Swarm",description:"Quality Conscious Software Delivery ideation phase: [url-extraction] -> [flag-detection] -> quality-criteria (HTSM) -> [testability, risk, requirements, security*, accessibility*, qx*] in parallel -> aggregated report. Supports live website URLs with conditional agent spawning based on HAS_UI, HAS_SECURITY, HAS_UX flags.",version:"3.0.0",tags:["qcsd","ideation","quality-criteria","htsm","shift-left","url-analysis"],steps:[{id:"website-content-extraction",name:"Website Content Extraction",domain:"requirements-validation",action:"extractWebsiteContent",inputMapping:{url:"input.url"},outputMapping:{extractedDescription:"extraction.description",extractedFeatures:"extraction.features",extractedAcceptanceCriteria:"extraction.acceptanceCriteria",detectedFlags:"extraction.flags",isWebsite:"extraction.isWebsite"},timeout:6e4,continueOnFailure:!0},{id:"quality-criteria-analysis",name:"HTSM Quality Criteria Analysis",domain:"requirements-validation",action:"analyzeQualityCriteria",dependsOn:["website-content-extraction"],inputMapping:{targetId:"input.targetId",targetType:"input.targetType",description:"results.website-content-extraction.extractedDescription || input.description",acceptanceCriteria:"results.website-content-extraction.extractedAcceptanceCriteria || input.acceptanceCriteria"},outputMapping:{qualityCriteria:"qualityCriteria.criteria",qualityScore:"qualityCriteria.score"},timeout:18e4,retry:{maxAttempts:2,backoffMs:2e3}},{id:"testability-assessment",name:"Testability Scoring (10 Principles)",domain:"requirements-validation",action:"assessTestability",dependsOn:["quality-criteria-analysis"],inputMapping:{targetId:"input.targetId",description:"results.website-content-extraction.extractedDescription || input.description",acceptanceCriteria:"results.website-content-extraction.extractedAcceptanceCriteria || input.acceptanceCriteria"},outputMapping:{overallScore:"testability.overallScore",principles:"testability.principles",blockers:"testability.blockers",recommendations:"testability.recommendations"},timeout:12e4,continueOnFailure:!0},{id:"risk-assessment",name:"Quality Risk Assessment",domain:"requirements-validation",action:"assessRisks",dependsOn:["quality-criteria-analysis"],inputMapping:{targetId:"input.targetId",targetType:"input.targetType",description:"results.website-content-extraction.extractedDescription || input.description"},outputMapping:{overallRisk:"risks.overallRisk",riskScore:"risks.riskScore",factors:"risks.factors",mitigations:"risks.mitigations"},timeout:9e4,continueOnFailure:!0},{id:"requirements-validation",name:"Requirements & Acceptance Criteria Validation",domain:"requirements-validation",action:"validateRequirements",dependsOn:["quality-criteria-analysis"],inputMapping:{targetId:"input.targetId",description:"results.website-content-extraction.extractedDescription || input.description",acceptanceCriteria:"results.website-content-extraction.extractedAcceptanceCriteria || input.acceptanceCriteria"},outputMapping:{valid:"requirements.valid",issues:"requirements.issues",suggestions:"requirements.suggestions"},timeout:9e4,continueOnFailure:!0},{id:"security-threat-modeling",name:"Early Security Threat Modeling (STRIDE)",domain:"security-compliance",action:"modelSecurityThreats",dependsOn:["quality-criteria-analysis"],condition:{path:"results.website-content-extraction.detectedFlags.hasSecurity || input.securityCritical",operator:"eq",value:!0},inputMapping:{targetId:"input.targetId",description:"results.website-content-extraction.extractedDescription || input.description",securityCritical:"results.website-content-extraction.detectedFlags.hasSecurity || input.securityCritical"},outputMapping:{threats:"security.threats",overallRisk:"security.overallRisk",recommendations:"security.recommendations"},timeout:12e4,continueOnFailure:!0},{id:"accessibility-audit",name:"Accessibility Audit (WCAG 2.2)",domain:"visual-accessibility",action:"auditAccessibility",dependsOn:["quality-criteria-analysis"],condition:{path:"results.website-content-extraction.detectedFlags.hasUI || input.hasUI",operator:"eq",value:!0},inputMapping:{targetId:"input.targetId",url:"input.url",description:"results.website-content-extraction.extractedDescription || input.description",features:"results.website-content-extraction.extractedFeatures"},outputMapping:{wcagLevel:"accessibility.wcagLevel",violations:"accessibility.violations",recommendations:"accessibility.recommendations"},timeout:18e4,continueOnFailure:!0},{id:"quality-experience-analysis",name:"Quality Experience Analysis (QX Partner)",domain:"coordination",action:"analyzeQualityExperience",dependsOn:["quality-criteria-analysis"],condition:{path:"results.website-content-extraction.detectedFlags.hasUX || input.hasUX",operator:"eq",value:!0},inputMapping:{targetId:"input.targetId",url:"input.url",description:"results.website-content-extraction.extractedDescription || input.description",features:"results.website-content-extraction.extractedFeatures"},outputMapping:{journeys:"qx.journeys",frictionPoints:"qx.frictionPoints",recommendations:"qx.recommendations"},timeout:15e4,continueOnFailure:!0},{id:"aggregate-ideation-report",name:"Generate Ideation Report",domain:"requirements-validation",action:"generateIdeationReport",dependsOn:["quality-criteria-analysis","testability-assessment","risk-assessment","requirements-validation","security-threat-modeling","accessibility-audit","quality-experience-analysis"],inputMapping:{targetId:"input.targetId",targetType:"input.targetType"},outputMapping:{report:"ideation.report",readyForDevelopment:"ideation.readyForDevelopment",blockers:"ideation.blockers",recommendations:"ideation.recommendations",testStrategy:"ideation.testStrategy"},timeout:6e4},{id:"store-ideation-learnings",name:"Store Ideation Learnings",domain:"learning-optimization",action:"storeIdeationLearnings",dependsOn:["aggregate-ideation-report"],inputMapping:{targetId:"input.targetId",report:"results.ideation.report"},outputMapping:{stored:"learning.stored",patternId:"learning.patternId"},continueOnFailure:!0}],triggers:[{eventType:"requirements-validation.EpicCreated",inputMapping:{targetId:"event.epicId",targetType:"event.type",description:"event.description",acceptanceCriteria:"event.acceptanceCriteria"}},{eventType:"requirements-validation.SprintPlanningStarted",inputMapping:{targetId:"event.sprintId",targetType:"event.type",description:"event.description",acceptanceCriteria:"event.acceptanceCriteria"}}]}}var C=class{constructor(e,t,i,r={}){this.eventBus=e;this.memory=t;this.agentCoordinator=i;this.config={...E,...r}}config;workflows=new Map;executions=new Map;actionRegistry={};eventSubscriptions=[];approvalGates=new Map;initialized=!1;async initialize(){this.initialized||(this.registerBuiltInWorkflows(),this.config.enableEventTriggers&&this.setupEventTriggers(),await this.loadPersistedWorkflows(),this.initialized=!0)}async dispose(){for(let e of this.executions.values())e.status==="running"&&await this.cancelWorkflow(e.executionId);for(let e of this.eventSubscriptions)e.unsubscribe();await this.persistWorkflows(),this.initialized=!1}registerWorkflow(e){try{let t=this.validateWorkflowDefinition(e);return t.success?(this.workflows.set(e.id,e),this.config.enableEventTriggers&&e.triggers&&this.registerWorkflowTriggers(e),m(void 0)):t}catch(t){return d(W(t))}}unregisterWorkflow(e){if(!this.workflows.has(e))return d(new Error(`Workflow not found: ${e}`));let t=Array.from(this.executions.values()).filter(i=>i.workflowId===e&&i.status==="running");return t.length>0?d(new Error(`Cannot unregister workflow with ${t.length} active execution(s)`)):(this.workflows.delete(e),m(void 0))}async executeWorkflow(e,t={},i){let r=this.workflows.get(e);if(!r)return d(new Error(`Workflow not found: ${e}`));if(Array.from(this.executions.values()).filter(g=>g.status==="running").length>=this.config.maxConcurrentWorkflows)return d(new Error(`Maximum concurrent workflows (${this.config.maxConcurrentWorkflows}) reached`));let o=D(),c=new Date,a={input:t,results:{},metadata:{executionId:o,workflowId:e,correlationId:i||o,startedAt:c}},l={executionId:o,workflowId:e,workflowName:r.name,status:"running",startedAt:c,progress:0,currentSteps:[],completedSteps:[],failedSteps:[],skippedSteps:[],context:a,stepResults:new Map};return this.executions.set(o,l),await this.publishWorkflowStarted(l,r),this.runWorkflow(r,l).catch(async g=>{l.status="failed",l.error=String(g),l.completedAt=new Date,l.duration=l.completedAt.getTime()-c.getTime(),await this.publishWorkflowFailed(l,"unknown",String(g))}),m(o)}getWorkflowStatus(e){return this.executions.get(e)}async cancelWorkflow(e){let t=this.executions.get(e);if(!t)return d(new Error(`Execution not found: ${e}`));if(t.status!=="running"&&t.status!=="paused")return d(new Error(`Cannot cancel workflow in status: ${t.status}`));t.status="cancelled",t.completedAt=new Date,t.duration=t.completedAt.getTime()-t.startedAt.getTime();for(let[i,r]of this.approvalGates.entries())i.startsWith(`${e}:`)&&(r.resolve({approved:!1,reason:"Workflow cancelled"}),this.approvalGates.delete(i));return await this.publishEvent(w.WorkflowCancelled,{executionId:e,workflowId:t.workflowId,workflowName:t.workflowName},t.context.metadata.correlationId),m(void 0)}async pauseWorkflow(e){let t=this.executions.get(e);return t?t.status!=="running"?d(new Error(`Cannot pause workflow in status: ${t.status}`)):(t.status="paused",m(void 0)):d(new Error(`Execution not found: ${e}`))}async resumeWorkflow(e){let t=this.executions.get(e);if(!t)return d(new Error(`Execution not found: ${e}`));if(t.status!=="paused")return d(new Error(`Cannot resume workflow in status: ${t.status}`));let i=this.workflows.get(t.workflowId);return i?(t.status="running",this.runWorkflow(i,t).catch(async r=>{t.status="failed",t.error=String(r)}),m(void 0)):d(new Error(`Workflow definition not found: ${t.workflowId}`))}listWorkflows(){return Array.from(this.workflows.values()).map(e=>({id:e.id,name:e.name,description:e.description,version:e.version,stepCount:e.steps.length,tags:e.tags,triggers:e.triggers?.map(t=>t.eventType)}))}getActiveExecutions(){return Array.from(this.executions.values()).filter(e=>e.status==="running"||e.status==="paused")}getWorkflow(e){return this.workflows.get(e)}approveStep(e,t){let i=`${e}:${t}`,r=this.approvalGates.get(i);return r?(r.resolve({approved:!0}),this.approvalGates.delete(i),!0):!1}rejectStep(e,t,i){let r=`${e}:${t}`,n=this.approvalGates.get(r);return n?(n.resolve({approved:!1,reason:i}),this.approvalGates.delete(r),!0):!1}isActionRegistered(e,t){return!!this.actionRegistry[e]?.[t]}getRegisteredActions(e){return Object.keys(this.actionRegistry[e]||{})}getDomainsWithActions(){return Object.keys(this.actionRegistry)}async spawnWorkflowAgent(e,t,i){return this.agentCoordinator.canSpawn()?this.agentCoordinator.spawn({name:`workflow-agent-${e.slice(0,8)}-${t}`,domain:i,type:"coordinator",capabilities:["workflow-execution",t],config:{workflowId:e,stepId:t}}):d(new Error("Agent limit reached"))}async stopWorkflowAgent(e){return this.agentCoordinator.stop(e)}getAvailableAgentCapacity(){return this.agentCoordinator.canSpawn()?this.config.maxConcurrentWorkflows-this.getActiveExecutions().length:0}registerAction(e,t,i){let r=["__proto__","constructor","prototype"];if(r.includes(e)||r.includes(t))throw new Error("Invalid domain or action name: contains dangerous prototype key");this.actionRegistry[e]||(this.actionRegistry[e]={}),this.actionRegistry[e][t]=i}async executeFromBehaviorTree(e){let t=new Date;try{let i=await e.tick(),r=new Date,n=r.getTime()-t.getTime();return{status:i==="SUCCESS"?"completed":i==="RUNNING"?"running":"failed",startedAt:t,completedAt:r,duration:n,treeStatus:i,treeName:e.name}}catch(i){let r=new Date,n=r.getTime()-t.getTime();return{status:"failed",startedAt:t,completedAt:r,duration:n,treeStatus:"FAILURE",treeName:e.name,error:b(i)}}}async runWorkflow(e,t){let i=e.timeout||this.config.defaultWorkflowTimeout,r=new Promise((n,o)=>{setTimeout(()=>o(new Error(`Workflow timeout after ${i}ms`)),i)});try{await Promise.race([this.executeSteps(e,t),r]),t.status==="running"&&(t.status="completed",t.completedAt=new Date,t.duration=t.completedAt.getTime()-t.startedAt.getTime(),t.progress=100,await this.publishWorkflowCompleted(t))}catch(n){if(t.status==="running"){t.status="failed",t.error=String(n),t.completedAt=new Date,t.duration=t.completedAt.getTime()-t.startedAt.getTime();let o=t.currentSteps[0]||"unknown";await this.publishWorkflowFailed(t,o,String(n))}}this.config.persistExecutions&&await this.persistExecution(t)}async executeSteps(e,t){let i=e.steps,r=new Set(t.completedSteps),n=new Set(t.skippedSteps),o=new Set(t.failedSteps),c=i.filter(a=>!r.has(a.id)&&!n.has(a.id)&&!o.has(a.id));for(;c.length>0&&t.status==="running";){let a=c.filter(u=>(u.dependsOn||[]).every(p=>r.has(p)||n.has(p)));if(a.length===0)break;let l=a.filter(u=>!u.dependsOn?.length),g=a.filter(u=>u.dependsOn?.length);if(l.length>0){t.currentSteps=l.map(f=>f.id);let u=await Promise.allSettled(l.map(f=>this.executeStep(f,t,e)));for(let f=0;f<l.length;f++){let p=l[f],y=u[f];if(y.status==="fulfilled"){let h=y.value;if(h.status==="completed")r.add(p.id),t.completedSteps.push(p.id);else if(h.status==="skipped")n.add(p.id),t.skippedSteps.push(p.id);else if(h.status==="failed"&&(o.add(p.id),t.failedSteps.push(p.id),!p.continueOnFailure)){t.status="failed",t.error=h.error;return}}else if(o.add(p.id),t.failedSteps.push(p.id),!p.continueOnFailure){t.status="failed",t.error=y.reason?.message||"Unknown error";return}let x=c.indexOf(p);x!==-1&&c.splice(x,1)}}for(let u of g){if(t.status!=="running")break;t.currentSteps=[u.id];let f=await this.executeStep(u,t,e);if(f.status==="completed")r.add(u.id),t.completedSteps.push(u.id);else if(f.status==="skipped")n.add(u.id),t.skippedSteps.push(u.id);else if(f.status==="failed"&&(o.add(u.id),t.failedSteps.push(u.id),!u.continueOnFailure)){t.status="failed",t.error=f.error;return}let p=c.indexOf(u);p!==-1&&c.splice(p,1)}let k=i.length,v=r.size+n.size+o.size;t.progress=Math.round(v/k*100)}t.currentSteps=[]}async executeStep(e,t,i){let r=new Date,n={stepId:e.id,status:"pending",startedAt:r};try{if(e.skipCondition&&this.evaluateCondition(e.skipCondition,t.context))return n.status="skipped",n.completedAt=new Date,n.duration=n.completedAt.getTime()-r.getTime(),t.stepResults.set(e.id,n),await this.publishStepSkipped(t,e),n;if(e.condition&&!this.evaluateCondition(e.condition,t.context))return n.status="skipped",n.completedAt=new Date,n.duration=n.completedAt.getTime()-r.getTime(),t.stepResults.set(e.id,n),await this.publishStepSkipped(t,e),n;n.status="running",await this.publishStepStarted(t,e);let o=this.buildStepInput(e,t.context),c,a=e.retry?.maxAttempts||1,l=e.retry?.backoffMs||1e3,g=e.retry?.backoffMultiplier||2;for(let k=1;k<=a;k++){n.retryCount=k-1;try{let v=e.timeout||this.config.defaultStepTimeout,u=await this.executeStepAction(e,o,t.context,v);if(this.mapStepOutput(e,u,t.context),e.approval){let f=await this.waitForApproval(e,t);if(!f.approved)return n.status="failed",n.error=f.reason||"Step rejected at approval gate",n.output=u,n.completedAt=new Date,n.duration=n.completedAt.getTime()-r.getTime(),t.stepResults.set(e.id,n),await this.publishStepFailed(t,e,n.error),n}return n.status="completed",n.output=u,n.completedAt=new Date,n.duration=n.completedAt.getTime()-r.getTime(),t.stepResults.set(e.id,n),await this.publishStepCompleted(t,e,n),n}catch(v){c=W(v),k<a&&(await this.delay(l),l*=g)}}return n.status="failed",n.error=c?.message||"Unknown error",n.completedAt=new Date,n.duration=n.completedAt.getTime()-r.getTime(),t.stepResults.set(e.id,n),e.rollback&&await this.executeRollback(e.rollback,t.context),await this.publishStepFailed(t,e,n.error),n}catch(o){return n.status="failed",n.error=b(o),n.completedAt=new Date,n.duration=n.completedAt.getTime()-r.getTime(),t.stepResults.set(e.id,n),await this.publishStepFailed(t,e,n.error),n}}async executeStepAction(e,t,i,r){let n=new Promise((a,l)=>{setTimeout(()=>l(new Error(`Step timeout after ${r}ms`)),r)}),o=R(e.domain,e.action);if(o){let a=await Promise.race([o.execute(t,i),n]);if(!a.success)throw a.error;return a.value}let c=this.actionRegistry[e.domain];if(c?.[e.action]){let a=await Promise.race([c[e.action](t,i),n]);if(!a.success)throw a.error;return a.value}throw new Error(`Action '${e.action}' not registered for domain '${e.domain}'. Register it using orchestrator.registerAction('${e.domain}', '${e.action}', handler)`)}async executeRollback(e,t){try{let i=this.actionRegistry[e.domain];if(!i?.[e.action]){console.warn(`Rollback action '${e.action}' not registered for domain '${e.domain}'. Skipping rollback.`);return}let r=await i[e.action](e.input||{},t);r.success||console.error(`Rollback failed for ${e.domain}.${e.action}:`,r.error)}catch(i){console.error(`Rollback failed for ${e.domain}.${e.action}:`,i)}}buildStepInput(e,t){let i={};if(e.inputMapping)for(let[r,n]of Object.entries(e.inputMapping)){let o=this.getValueByPath(t,n);o!==void 0&&(i[r]=o)}return i}mapStepOutput(e,t,i){if(i.results[e.id]=t,e.outputMapping&&typeof t=="object"&&t!==null)for(let[r,n]of Object.entries(e.outputMapping)){let o=this.getValueByPath(t,r);o!==void 0&&this.setValueByPath(i.results,n,o)}}getValueByPath(e,t){let i=t.split("."),r=e;for(let n of i){if(r==null)return;if(typeof r=="object")r=r[n];else return}return r}setValueByPath(e,t,i){let r=t.split("."),n=new Set(["__proto__","constructor","prototype"]);for(let a of r)if(n.has(a))throw new Error("Invalid path: contains dangerous prototype key");let o=e;for(let a=0;a<r.length-1;a++){let l=r[a];Object.hasOwn(o,l)||Object.defineProperty(o,l,{value:Object.create(null),writable:!0,enumerable:!0,configurable:!0}),o=o[l]}let c=r[r.length-1];Object.defineProperty(o,c,{value:i,writable:!0,enumerable:!0,configurable:!0})}evaluateCondition(e,t){let i=this.getValueByPath(t,e.path);switch(e.operator){case"eq":return i===e.value;case"neq":return i!==e.value;case"gt":return typeof i=="number"&&i>e.value;case"gte":return typeof i=="number"&&i>=e.value;case"lt":return typeof i=="number"&&i<e.value;case"lte":return typeof i=="number"&&i<=e.value;case"contains":return Array.isArray(i)?i.includes(e.value):typeof i=="string"?i.includes(String(e.value)):!1;case"exists":return i!=null;default:return!1}}async publishEvent(e,t,i){let r=I(e,"learning-optimization",t,i);await this.eventBus.publish(r)}async publishWorkflowStarted(e,t){await this.publishEvent(w.WorkflowStarted,{executionId:e.executionId,workflowId:e.workflowId,workflowName:e.workflowName,stepCount:t.steps.length},e.context.metadata.correlationId)}async publishWorkflowCompleted(e){await this.publishEvent(w.WorkflowCompleted,{executionId:e.executionId,workflowId:e.workflowId,workflowName:e.workflowName,duration:e.duration||0,completedSteps:e.completedSteps.length,skippedSteps:e.skippedSteps.length},e.context.metadata.correlationId)}async publishWorkflowFailed(e,t,i){await this.publishEvent(w.WorkflowFailed,{executionId:e.executionId,workflowId:e.workflowId,workflowName:e.workflowName,failedStep:t,error:i},e.context.metadata.correlationId)}async publishStepStarted(e,t){await this.publishEvent(w.StepStarted,{executionId:e.executionId,workflowId:e.workflowId,stepId:t.id,stepName:t.name,domain:t.domain},e.context.metadata.correlationId)}async publishStepCompleted(e,t,i){await this.publishEvent(w.StepCompleted,{executionId:e.executionId,workflowId:e.workflowId,stepId:t.id,stepName:t.name,domain:t.domain,duration:i.duration},e.context.metadata.correlationId)}async publishStepFailed(e,t,i){await this.publishEvent(w.StepFailed,{executionId:e.executionId,workflowId:e.workflowId,stepId:t.id,stepName:t.name,domain:t.domain,error:i},e.context.metadata.correlationId)}async publishStepSkipped(e,t){await this.publishEvent(w.StepSkipped,{executionId:e.executionId,workflowId:e.workflowId,stepId:t.id,stepName:t.name,domain:t.domain},e.context.metadata.correlationId)}validateWorkflowDefinition(e){if(!e.id)return d(new Error("Workflow ID is required"));if(!e.name)return d(new Error("Workflow name is required"));if(!e.steps||e.steps.length===0)return d(new Error("Workflow must have at least one step"));let t=new Set;for(let r of e.steps){if(!r.id)return d(new Error("Step ID is required"));if(t.has(r.id))return d(new Error(`Duplicate step ID: ${r.id}`));if(t.add(r.id),!r.domain)return d(new Error(`Step ${r.id} must have a domain`));if(!A.includes(r.domain))return d(new Error(`Invalid domain for step ${r.id}: ${r.domain}`));if(!r.action)return d(new Error(`Step ${r.id} must have an action`));if(r.dependsOn){for(let n of r.dependsOn)if(!e.steps.some(o=>o.id===n))return d(new Error(`Step ${r.id} depends on unknown step: ${n}`))}}let i=this.detectCircularDependencies(e.steps);return i?d(new Error(`Circular dependency detected: ${i}`)):m(void 0)}detectCircularDependencies(e){let t=new Set,i=new Set,r=(n,o)=>{if(i.has(n))return[...o,n].join(" -> ");if(t.has(n))return null;t.add(n),i.add(n);let c=e.find(a=>a.id===n);if(c?.dependsOn)for(let a of c.dependsOn){let l=r(a,[...o,n]);if(l)return l}return i.delete(n),null};for(let n of e){let o=r(n.id,[]);if(o)return o}return null}setupEventTriggers(){let e=this.eventBus.subscribe("*",async t=>{await this.handleEventForTriggers(t)});this.eventSubscriptions.push(e)}registerWorkflowTriggers(e){}async handleEventForTriggers(e){for(let t of this.workflows.values())if(t.triggers)for(let i of t.triggers){if(i.eventType!==e.type||i.sourceDomain&&i.sourceDomain!==e.source)continue;if(i.condition){let n={input:{event:e.payload},results:{},metadata:{executionId:"",workflowId:t.id,startedAt:new Date}};if(!this.evaluateCondition(i.condition,n))continue}let r={};if(i.inputMapping)for(let[n,o]of Object.entries(i.inputMapping)){let c=this.getValueByPath({event:e.payload},o);c!==void 0&&(r[n]=c)}else r.triggerEvent=e.payload;await this.executeWorkflow(t.id,r,e.correlationId)}}registerBuiltInWorkflows(){let e=M();for(let t of e)this.registerWorkflow(t)}async loadPersistedWorkflows(){try{let e=await this.memory.search("workflow:definition:*",100);for(let t of e){let i=await this.memory.get(t);i&&!this.workflows.has(i.id)&&this.workflows.set(i.id,i)}}catch(e){console.error("Failed to load persisted workflows:",e)}}async persistWorkflows(){try{for(let e of this.workflows.values())P.includes(e.id)||await this.memory.set(`workflow:definition:${e.id}`,e,{namespace:"coordination",persist:!0})}catch(e){console.error("Failed to persist workflows:",e)}}async persistExecution(e){try{let t={...e,stepResults:Object.fromEntries(e.stepResults)};await this.memory.set(`workflow:execution:${e.executionId}`,t,{namespace:"coordination",ttl:86400*7})}catch(t){console.error("Failed to persist execution:",t)}}async waitForApproval(e,t){let i=typeof e.approval=="object"?e.approval:{},r=i.autoApproveAfter??3e5,n=i.message??`Awaiting approval for step: ${e.name}`,o=t.stepResults.get(e.id);o&&(o.status="awaiting_approval"),await this.publishEvent(w.StepAwaitingApproval,{executionId:t.executionId,workflowId:t.workflowId,stepId:e.id,stepName:e.name,domain:e.domain,message:n,autoApproveAfter:r>0?r:void 0},t.context.metadata.correlationId);let c=`${t.executionId}:${e.id}`;return new Promise(a=>{let l={resolve:a};if(this.approvalGates.set(c,l),r>0){let g=setTimeout(()=>{this.approvalGates.has(c)&&(this.approvalGates.delete(c),a({approved:!0}))},r),k=l.resolve;l.resolve=v=>{clearTimeout(g),k(v)}}})}delay(e){return new Promise(t=>setTimeout(t,e))}};function de(s,e,t,i){return new C(s,e,t,i)}export{w as a,E as b,C as c,de as d};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.0");process.exit(0)}
|
|
2
|
+
import{a as y}from"./chunk-3IUNFTIF.js";import{a as g,c as h}from"./chunk-ZDATDCYN.js";import{M as b,b as p}from"./chunk-2I7J3O6V.js";b();var m=class{calculator;constructor(){this.calculator=new g}computeLambda(t){let n=this.maybeSparsify(t),e=this.toSwarmGraph(n);return this.calculator.getMinCutValue(e)}computeRoutingTier(t,n){let e=this.buildTaskGraphFromTopology(n),o=this.toSwarmGraph(e),s=this.calculator.getMinCutValue(o),r=Math.max(n.length-1,1),a=Math.min(s/r,1),{tier:i,label:d}=this.lambdaToTier(a),c=this.computeConfidence(o,a),l=this.buildRationale(t,a,i,n.length);return{tier:i,label:d,lambda:s,normalizedLambda:a,confidence:c,rationale:l}}getStructuralHealth(t){let n=this.maybeSparsify(t),e=this.toSwarmGraph(n);if(e.isEmpty())return this.emptyHealthReport();let o=this.calculator.getMinCutValue(e),s=e.getStats(),r=Math.max(s.vertexCount-1,1),a=Math.min(o/r,1),i=this.calculator.findWeakVertices(e),d=i.map(f=>f.vertexId),c=1-a,l=a>=.4,u=this.generateHealthSuggestions(a,i.length,s);return{lambda:o,normalizedLambda:a,healthy:l,weakPoints:d,riskScore:c,componentCount:s.componentCount,isConnected:s.isConnected,suggestions:u,analyzedAt:new Date}}maybeSparsify(t){if(!p().useSpectralSparsification||t.edges.length<=100)return t;let n=new Map;t.nodes.forEach((i,d)=>n.set(i.id,d));let e=[];for(let i of t.edges){let d=n.get(i.source),c=n.get(i.target);d!==void 0&&c!==void 0&&e.push([d,c,i.weight])}let o={nodeCount:t.nodes.length,edges:e},r=new y({epsilon:.3}).sparsify(o),a=[];for(let[i,d,c]of r.edges){let l=t.nodes[i],u=t.nodes[d];l&&u&&a.push({source:l.id,target:u.id,weight:c,edgeType:"coordination"})}return{nodes:t.nodes,edges:a}}toSwarmGraph(t){let n=new h;for(let e of t.nodes){let o={id:e.id,type:e.type==="task"||e.type==="agent"?"agent":"domain",domain:e.domain,weight:e.weight,createdAt:new Date,metadata:e.metadata};n.addVertex(o)}for(let e of t.edges)if(n.hasVertex(e.source)&&n.hasVertex(e.target)){let o={source:e.source,target:e.target,weight:e.weight,type:e.edgeType==="dependency"?"dependency":e.edgeType==="communication"?"communication":e.edgeType==="workflow"?"workflow":"coordination",bidirectional:e.edgeType!=="dependency"};n.addEdge(o)}return n}buildTaskGraphFromTopology(t){let n=t.map(r=>({id:r.id,label:r.name,type:"agent",domain:r.domain,weight:r.weight})),e=[],o=new Set(t.map(r=>r.id));for(let r of t)for(let a of r.dependsOn)o.has(a)&&e.push({source:r.id,target:a,weight:1,edgeType:"dependency"});let s=new Map;for(let r of t){let a=s.get(r.domain)||[];a.push(r.id),s.set(r.domain,a)}for(let[,r]of s)for(let a=0;a<r.length;a++)for(let i=a+1;i<r.length;i++)e.push({source:r[a],target:r[i],weight:.5,edgeType:"coordination"});return{nodes:n,edges:e}}lambdaToTier(t){return t>=.8?{tier:1,label:"Haiku"}:t>=.4?{tier:2,label:"Sonnet"}:{tier:3,label:"Opus"}}computeConfidence(t,n){let e=t.getStats();if(e.vertexCount<3)return .4;let o=Math.min(Math.abs(n-.4),Math.abs(n-.8)),s=Math.min(.95,.5+o*2.25),r=Math.min(1,e.density*2);return Math.min(.99,s*(.7+.3*r))}buildRationale(t,n,e,o){let s=t.slice(0,80),r=n>=.8?"highly connected":n>=.4?"moderately connected":"fragmented";return`Task "${s}" routed to ${e===1?"Haiku":e===2?"Sonnet":"Opus"} (Tier ${e}). Fleet topology is ${r} (lambda=${n.toFixed(3)}) across ${o} agents.`}generateHealthSuggestions(t,n,e){let o=[];return e.isConnected||o.push(`Graph has ${e.componentCount} disconnected components. Add cross-domain coordination edges to improve connectivity.`),t<.2?o.push("Critical: Fleet connectivity is very low. Consider spawning coordination agents."):t<.4&&o.push("Warning: Fleet connectivity is below healthy threshold. Reinforce weak connections."),n>0&&o.push(`${n} weak point(s) detected. Add redundant connections to these agents.`),e.vertexCount<3&&o.push("Fleet has fewer than 3 agents. MinCut analysis is most useful with larger topologies."),o}emptyHealthReport(){return{lambda:0,normalizedLambda:0,healthy:!1,weakPoints:[],riskScore:1,componentCount:0,isConnected:!0,suggestions:["No agents in fleet. Spawn agents to build a topology."],analyzedAt:new Date}}};function C(){return new m}export{C as a};
|
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.0");process.exit(0)}
|
|
2
|
+
import{c as R,g as L}from"./chunk-YW2THB5Q.js";import{f}from"./chunk-SUSEVMZT.js";import{k as N,o as w}from"./chunk-JJO7Y4H3.js";import{b,d as q}from"./chunk-WGMPEW2T.js";import{a as _,c as I}from"./chunk-JZSDOIXA.js";import{a as S,b as A}from"./chunk-263XS447.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
|
+
-- QE Patterns table
|
|
4
|
+
CREATE TABLE IF NOT EXISTS qe_patterns (
|
|
5
|
+
id TEXT PRIMARY KEY,
|
|
6
|
+
pattern_type TEXT NOT NULL,
|
|
7
|
+
qe_domain TEXT NOT NULL,
|
|
8
|
+
domain TEXT NOT NULL,
|
|
9
|
+
name TEXT NOT NULL,
|
|
10
|
+
description TEXT,
|
|
11
|
+
confidence REAL DEFAULT 0.5,
|
|
12
|
+
usage_count INTEGER DEFAULT 0,
|
|
13
|
+
success_rate REAL DEFAULT 0.0,
|
|
14
|
+
quality_score REAL DEFAULT 0.0,
|
|
15
|
+
tier TEXT DEFAULT 'short-term',
|
|
16
|
+
template_json TEXT,
|
|
17
|
+
context_json TEXT,
|
|
18
|
+
created_at TEXT DEFAULT (datetime('now')),
|
|
19
|
+
updated_at TEXT DEFAULT (datetime('now')),
|
|
20
|
+
last_used_at TEXT,
|
|
21
|
+
successful_uses INTEGER DEFAULT 0
|
|
22
|
+
);
|
|
23
|
+
|
|
24
|
+
-- Pattern embeddings table (BLOB storage for vectors)
|
|
25
|
+
CREATE TABLE IF NOT EXISTS qe_pattern_embeddings (
|
|
26
|
+
pattern_id TEXT PRIMARY KEY,
|
|
27
|
+
embedding BLOB NOT NULL,
|
|
28
|
+
dimension INTEGER NOT NULL,
|
|
29
|
+
model TEXT DEFAULT 'all-MiniLM-L6-v2',
|
|
30
|
+
created_at TEXT DEFAULT (datetime('now')),
|
|
31
|
+
FOREIGN KEY (pattern_id) REFERENCES qe_patterns(id) ON DELETE CASCADE
|
|
32
|
+
);
|
|
33
|
+
|
|
34
|
+
-- Pattern usage history
|
|
35
|
+
CREATE TABLE IF NOT EXISTS qe_pattern_usage (
|
|
36
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
37
|
+
pattern_id TEXT NOT NULL,
|
|
38
|
+
success INTEGER NOT NULL,
|
|
39
|
+
metrics_json TEXT,
|
|
40
|
+
feedback TEXT,
|
|
41
|
+
created_at TEXT DEFAULT (datetime('now'))
|
|
42
|
+
);
|
|
43
|
+
|
|
44
|
+
-- Learning trajectories
|
|
45
|
+
CREATE TABLE IF NOT EXISTS qe_trajectories (
|
|
46
|
+
id TEXT PRIMARY KEY,
|
|
47
|
+
task TEXT NOT NULL,
|
|
48
|
+
agent TEXT,
|
|
49
|
+
domain TEXT,
|
|
50
|
+
started_at TEXT DEFAULT (datetime('now')),
|
|
51
|
+
ended_at TEXT,
|
|
52
|
+
success INTEGER,
|
|
53
|
+
steps_json TEXT,
|
|
54
|
+
metadata_json TEXT
|
|
55
|
+
);
|
|
56
|
+
|
|
57
|
+
-- Pattern reuse tracking (ADR Phase 5.4)
|
|
58
|
+
CREATE TABLE IF NOT EXISTS qe_pattern_reuse (
|
|
59
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
60
|
+
pattern_id TEXT NOT NULL,
|
|
61
|
+
task_description TEXT NOT NULL,
|
|
62
|
+
similarity_score REAL NOT NULL,
|
|
63
|
+
was_reused INTEGER DEFAULT 0,
|
|
64
|
+
tokens_saved INTEGER DEFAULT 0,
|
|
65
|
+
routing_context_json TEXT,
|
|
66
|
+
created_at TEXT DEFAULT (datetime('now')),
|
|
67
|
+
FOREIGN KEY (pattern_id) REFERENCES qe_patterns(id) ON DELETE CASCADE
|
|
68
|
+
);
|
|
69
|
+
|
|
70
|
+
-- Agent co-execution tracking (Issue #342 Item 3)
|
|
71
|
+
CREATE TABLE IF NOT EXISTS qe_agent_co_execution (
|
|
72
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
73
|
+
agent_a TEXT NOT NULL,
|
|
74
|
+
agent_b TEXT NOT NULL,
|
|
75
|
+
domain TEXT NOT NULL,
|
|
76
|
+
success INTEGER NOT NULL DEFAULT 0,
|
|
77
|
+
task_description TEXT,
|
|
78
|
+
created_at TEXT DEFAULT (datetime('now'))
|
|
79
|
+
);
|
|
80
|
+
|
|
81
|
+
CREATE INDEX IF NOT EXISTS idx_co_exec_agents
|
|
82
|
+
ON qe_agent_co_execution(agent_a, agent_b);
|
|
83
|
+
CREATE INDEX IF NOT EXISTS idx_co_exec_domain
|
|
84
|
+
ON qe_agent_co_execution(domain);
|
|
85
|
+
|
|
86
|
+
-- Unique constraint to prevent duplicate patterns
|
|
87
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_patterns_unique_name_domain_type
|
|
88
|
+
ON qe_patterns(name, qe_domain, pattern_type);
|
|
89
|
+
|
|
90
|
+
-- FTS5 full-text search index for hybrid vector/text search
|
|
91
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS qe_patterns_fts USING fts5(
|
|
92
|
+
name, description, pattern_type, qe_domain,
|
|
93
|
+
content='qe_patterns',
|
|
94
|
+
content_rowid='rowid'
|
|
95
|
+
);
|
|
96
|
+
|
|
97
|
+
-- FTS5 triggers to keep index in sync
|
|
98
|
+
CREATE TRIGGER IF NOT EXISTS qe_patterns_fts_insert AFTER INSERT ON qe_patterns BEGIN
|
|
99
|
+
INSERT INTO qe_patterns_fts(rowid, name, description, pattern_type, qe_domain)
|
|
100
|
+
VALUES (new.rowid, new.name, new.description, new.pattern_type, new.qe_domain);
|
|
101
|
+
END;
|
|
102
|
+
|
|
103
|
+
CREATE TRIGGER IF NOT EXISTS qe_patterns_fts_delete AFTER DELETE ON qe_patterns BEGIN
|
|
104
|
+
INSERT INTO qe_patterns_fts(qe_patterns_fts, rowid, name, description, pattern_type, qe_domain)
|
|
105
|
+
VALUES ('delete', old.rowid, old.name, old.description, old.pattern_type, old.qe_domain);
|
|
106
|
+
END;
|
|
107
|
+
|
|
108
|
+
CREATE TRIGGER IF NOT EXISTS qe_patterns_fts_update AFTER UPDATE ON qe_patterns BEGIN
|
|
109
|
+
INSERT INTO qe_patterns_fts(qe_patterns_fts, rowid, name, description, pattern_type, qe_domain)
|
|
110
|
+
VALUES ('delete', old.rowid, old.name, old.description, old.pattern_type, old.qe_domain);
|
|
111
|
+
INSERT INTO qe_patterns_fts(rowid, name, description, pattern_type, qe_domain)
|
|
112
|
+
VALUES (new.rowid, new.name, new.description, new.pattern_type, new.qe_domain);
|
|
113
|
+
END;
|
|
114
|
+
|
|
115
|
+
-- Indexes for performance
|
|
116
|
+
CREATE INDEX IF NOT EXISTS idx_patterns_domain ON qe_patterns(qe_domain);
|
|
117
|
+
CREATE INDEX IF NOT EXISTS idx_patterns_type ON qe_patterns(pattern_type);
|
|
118
|
+
CREATE INDEX IF NOT EXISTS idx_patterns_tier ON qe_patterns(tier);
|
|
119
|
+
CREATE INDEX IF NOT EXISTS idx_patterns_quality ON qe_patterns(quality_score DESC);
|
|
120
|
+
CREATE INDEX IF NOT EXISTS idx_usage_pattern ON qe_pattern_usage(pattern_id);
|
|
121
|
+
CREATE INDEX IF NOT EXISTS idx_trajectories_domain ON qe_trajectories(domain);
|
|
122
|
+
CREATE INDEX IF NOT EXISTS idx_pattern_reuse_pattern ON qe_pattern_reuse(pattern_id);
|
|
123
|
+
CREATE INDEX IF NOT EXISTS idx_pattern_reuse_created ON qe_pattern_reuse(created_at);
|
|
124
|
+
`)}deduplicatePatterns(){if(this.db)try{if(this.db.prepare("SELECT name FROM sqlite_master WHERE type='index' AND name='idx_patterns_unique_name_domain_type'").get())return;if((this.db.prepare(`
|
|
125
|
+
SELECT COUNT(*) as cnt FROM (
|
|
126
|
+
SELECT name, qe_domain, pattern_type, COUNT(*) as c
|
|
127
|
+
FROM qe_patterns GROUP BY name, qe_domain, pattern_type HAVING c > 1
|
|
128
|
+
)
|
|
129
|
+
`).get()?.cnt||0)>0){let t=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns").get()?.cnt||0,r=this.db.prepare(`
|
|
130
|
+
SELECT COUNT(*) as cnt FROM (
|
|
131
|
+
SELECT MIN(rowid) FROM qe_patterns GROUP BY name, qe_domain, pattern_type
|
|
132
|
+
)
|
|
133
|
+
`).get()?.cnt||0,a=t-r;a>t*.1?console.warn(`[SQLitePatternStore] SKIPPING dedup: would delete ${a}/${t} patterns (>${Math.round(t*.1)} safety limit). Investigate manually.`):(this.db.exec(`
|
|
134
|
+
DELETE FROM qe_patterns WHERE rowid NOT IN (
|
|
135
|
+
SELECT MIN(rowid) FROM qe_patterns
|
|
136
|
+
GROUP BY name, qe_domain, pattern_type
|
|
137
|
+
)
|
|
138
|
+
`),console.log(`[SQLitePatternStore] Deduplicated: removed ${a} duplicates from ${t} patterns (${r} kept)`))}this.db.exec(`
|
|
139
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_patterns_unique_name_domain_type
|
|
140
|
+
ON qe_patterns(name, qe_domain, pattern_type)
|
|
141
|
+
`)}catch(e){console.debug("[SQLitePatternStore] Deduplication migration:",_(e))}}prepareStatements(){if(!this.db)throw new Error("Database not initialized");this.prepared.set("insertPattern",this.db.prepare(`
|
|
142
|
+
INSERT INTO qe_patterns (
|
|
143
|
+
id, pattern_type, qe_domain, domain, name, description,
|
|
144
|
+
confidence, tier, template_json, context_json
|
|
145
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
146
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
147
|
+
confidence = excluded.confidence,
|
|
148
|
+
tier = excluded.tier,
|
|
149
|
+
template_json = excluded.template_json,
|
|
150
|
+
context_json = excluded.context_json,
|
|
151
|
+
updated_at = datetime('now')
|
|
152
|
+
ON CONFLICT(name, qe_domain, pattern_type) DO UPDATE SET
|
|
153
|
+
confidence = excluded.confidence,
|
|
154
|
+
tier = excluded.tier,
|
|
155
|
+
template_json = excluded.template_json,
|
|
156
|
+
context_json = excluded.context_json,
|
|
157
|
+
updated_at = datetime('now')
|
|
158
|
+
`)),this.prepared.set("insertEmbedding",this.db.prepare(`
|
|
159
|
+
INSERT OR REPLACE INTO qe_pattern_embeddings (pattern_id, embedding, dimension, model)
|
|
160
|
+
VALUES (?, ?, ?, ?)
|
|
161
|
+
`)),this.prepared.set("getPattern",this.db.prepare(`
|
|
162
|
+
SELECT * FROM qe_patterns WHERE id = ?
|
|
163
|
+
`)),this.prepared.set("getPatternWithEmbedding",this.db.prepare(`
|
|
164
|
+
SELECT p.*, e.embedding, e.dimension
|
|
165
|
+
FROM qe_patterns p
|
|
166
|
+
LEFT JOIN qe_pattern_embeddings e ON p.id = e.pattern_id
|
|
167
|
+
WHERE p.id = ?
|
|
168
|
+
`)),this.prepared.set("updatePattern",this.db.prepare(`
|
|
169
|
+
UPDATE qe_patterns SET
|
|
170
|
+
usage_count = usage_count + 1,
|
|
171
|
+
successful_uses = successful_uses + ?,
|
|
172
|
+
success_rate = CAST(successful_uses + ? AS REAL) / CAST(usage_count + 1 AS REAL),
|
|
173
|
+
quality_score = ?,
|
|
174
|
+
last_used_at = datetime('now'),
|
|
175
|
+
updated_at = datetime('now')
|
|
176
|
+
WHERE id = ?
|
|
177
|
+
`)),this.prepared.set("promotePattern",this.db.prepare(`
|
|
178
|
+
UPDATE qe_patterns SET tier = 'long-term', updated_at = datetime('now')
|
|
179
|
+
WHERE id = ?
|
|
180
|
+
`)),this.prepared.set("insertUsage",this.db.prepare(`
|
|
181
|
+
INSERT INTO qe_pattern_usage (pattern_id, success, metrics_json, feedback)
|
|
182
|
+
VALUES (?, ?, ?, ?)
|
|
183
|
+
`)),this.prepared.set("getAllPatterns",this.db.prepare(`
|
|
184
|
+
SELECT * FROM qe_patterns ORDER BY quality_score DESC LIMIT ?
|
|
185
|
+
`)),this.prepared.set("getPatternsByDomain",this.db.prepare(`
|
|
186
|
+
SELECT * FROM qe_patterns WHERE qe_domain = ? ORDER BY quality_score DESC LIMIT ?
|
|
187
|
+
`)),this.prepared.set("getAllEmbeddings",this.db.prepare(`
|
|
188
|
+
SELECT pattern_id, embedding, dimension FROM qe_pattern_embeddings
|
|
189
|
+
`)),this.prepared.set("countPatterns",this.db.prepare(`
|
|
190
|
+
SELECT COUNT(*) as count FROM qe_patterns
|
|
191
|
+
`)),this.prepared.set("countByDomain",this.db.prepare(`
|
|
192
|
+
SELECT qe_domain, COUNT(*) as count FROM qe_patterns GROUP BY qe_domain
|
|
193
|
+
`))}storePattern(e,n){if(!this.db)throw new Error("Database not initialized");let t=e.id||f(),r=this.prepared.get("insertPattern"),a=this.prepared.get("insertEmbedding");if(!r||!a)throw new Error("Prepared statements not ready");return this.db.transaction(()=>{if(r.run(t,e.patternType,e.qeDomain,e.domain,e.name,e.description||"",e.confidence,e.tier||"short-term",JSON.stringify(e.template),JSON.stringify(e.context)),n){let s=Buffer.from(new Float32Array(n).buffer);a.run(t,s,n.length,"all-MiniLM-L6-v2")}})(),t}getPattern(e){if(!this.db)throw new Error("Database not initialized");let n=this.prepared.get("getPatternWithEmbedding");if(!n)throw new Error("Prepared statement not ready");let t=n.get(e);return t?this.rowToPattern(t):null}getPatterns(e={}){if(!this.db)throw new Error("Database not initialized");let n=e.limit||1e3,t,r;return e.domain?(t=this.prepared.get("getPatternsByDomain"),r=t.all(e.domain,n)):(t=this.prepared.get("getAllPatterns"),r=t.all(n)),r.map(a=>this.rowToPattern(a))}searchFTS(e,n=20){if(!this.db)throw new Error("Database not initialized");if(!e.trim())return[];let t='"'+e.replace(/"/g,'""')+'"',r=performance.now();try{let a=this.db.prepare(`
|
|
194
|
+
SELECT p.id, rank AS fts_score
|
|
195
|
+
FROM qe_patterns_fts fts
|
|
196
|
+
JOIN qe_patterns p ON p.rowid = fts.rowid
|
|
197
|
+
WHERE qe_patterns_fts MATCH ?
|
|
198
|
+
ORDER BY rank
|
|
199
|
+
LIMIT ?
|
|
200
|
+
`).all(t,n),i=performance.now()-r;i>50&&console.warn(`[FTS5] searchFTS took ${i.toFixed(1)}ms (results=${a.length})`),this._lastFtsLatencyMs=i;let s=Math.max(...a.map(o=>Math.abs(o.fts_score)),1);return a.map(o=>({id:o.id,ftsScore:Math.abs(o.fts_score)/s}))}catch{return[]}}_lastFtsLatencyMs=0;get lastFtsLatencyMs(){return this._lastFtsLatencyMs}getGhostPatternCount(){if(!this.db)throw new Error("Database not initialized");let e=this.db.prepare("SELECT COUNT(*) as c FROM qe_patterns WHERE id NOT LIKE 'bench-%'").get().c,n=this.db.prepare(`
|
|
201
|
+
SELECT COUNT(*) as c FROM qe_patterns p
|
|
202
|
+
WHERE p.id NOT LIKE 'bench-%'
|
|
203
|
+
AND p.id NOT IN (SELECT pattern_id FROM qe_pattern_embeddings)
|
|
204
|
+
`).get().c,t=this.db.prepare(`
|
|
205
|
+
SELECT p.id FROM qe_patterns p
|
|
206
|
+
WHERE p.id NOT LIKE 'bench-%'
|
|
207
|
+
AND p.id NOT IN (SELECT pattern_id FROM qe_pattern_embeddings)
|
|
208
|
+
LIMIT 10
|
|
209
|
+
`).all();return{total:e,withoutEmbeddings:n,sampleGhostIds:t.map(r=>r.id)}}getAllEmbeddings(){if(!this.db)throw new Error("Database not initialized");let e=this.prepared.get("getAllEmbeddings");if(!e)throw new Error("Prepared statement not ready");return e.all().map(t=>({patternId:t.pattern_id,embedding:Array.from(new Float32Array(t.embedding.buffer,t.embedding.byteOffset,t.dimension))}))}recordUsage(e,n,t,r){if(!this.db)throw new Error("Database not initialized");let a=this.prepared.get("insertUsage"),i=this.prepared.get("updatePattern");if(!a||!i)throw new Error("Prepared statements not ready");let s=this.getPattern(e);if(!s)throw new Error(`Pattern not found: ${e}`);let o=s.usageCount+1,u=(s.successfulUses+(n?1:0))/o,T=Math.min(1,o/100),p=s.confidence*.3+T*.2+u*.5;this.db.transaction(()=>{a.run(e,n?1:0,t?JSON.stringify(t):null,r||null),i.run(n?1:0,n?1:0,p,e)})()}deletePattern(e){if(!this.db)throw new Error("Database not initialized");this.db.transaction(()=>{this.db.prepare("DELETE FROM qe_pattern_embeddings WHERE pattern_id = ?").run(e),this.db.prepare("DELETE FROM qe_pattern_usage WHERE pattern_id = ?").run(e),this.db.prepare("DELETE FROM qe_patterns WHERE id = ?").run(e)})()}promotePattern(e){if(!this.db)throw new Error("Database not initialized");let n=this.prepared.get("promotePattern");if(!n)throw new Error("Prepared statement not ready");n.run(e)}getStats(){if(!this.db)throw new Error("Database not initialized");let e=this.prepared.get("countPatterns"),n=this.prepared.get("countByDomain");if(!e||!n)throw new Error("Prepared statements not ready");let t=e.get().count,r=n.all(),a={};for(let o of r)a[o.qe_domain]=o.count;let i=this.db.prepare(`
|
|
210
|
+
SELECT tier, COUNT(*) as count FROM qe_patterns GROUP BY tier
|
|
211
|
+
`).all(),s={};for(let o of i)s[o.tier]=o.count;return{totalPatterns:t,byDomain:a,byTier:s}}hasAnyHistoricalData(){if(!this.db)return!1;try{let e=["SELECT COUNT(*) as cnt FROM qe_pattern_embeddings","SELECT COUNT(*) as cnt FROM qe_pattern_usage","SELECT COUNT(*) as cnt FROM qe_trajectories"];for(let n of e)try{let t=this.db.prepare(n).get();if(t&&t.cnt>0)return!0}catch{}return!1}catch{return!1}}rowToPattern(e){let n;return e.embedding&&(n=Array.from(new Float32Array(e.embedding.buffer,e.embedding.byteOffset,e.dimension))),{id:e.id,patternType:e.pattern_type,qeDomain:e.qe_domain,domain:e.domain,name:e.name,description:e.description,confidence:e.confidence,usageCount:e.usage_count,successRate:e.success_rate,qualityScore:e.quality_score,tier:e.tier,template:b(e.template_json||"{}"),context:b(e.context_json||"{}"),createdAt:new Date(e.created_at),lastUsedAt:e.last_used_at?new Date(e.last_used_at):new Date(e.created_at),successfulUses:e.successful_uses,embedding:n,tokensUsed:e.tokens_used,inputTokens:e.input_tokens,outputTokens:e.output_tokens,latencyMs:e.latency_ms,reusable:e.reusable===1,reuseCount:e.reuse_count||0,averageTokenSavings:e.average_token_savings||0,totalTokensSaved:e.total_tokens_saved}}updatePattern(e,n){if(!this.db)throw new Error("Database not initialized");let t=[],r=[];if(n.usageCount!==void 0&&(t.push("usage_count = ?"),r.push(n.usageCount)),n.successfulUses!==void 0&&(t.push("successful_uses = ?"),r.push(n.successfulUses)),n.successRate!==void 0&&(t.push("success_rate = ?"),r.push(n.successRate)),n.qualityScore!==void 0&&(t.push("quality_score = ?"),r.push(n.qualityScore)),n.confidence!==void 0&&(t.push("confidence = ?"),r.push(n.confidence)),n.tier!==void 0&&(t.push("tier = ?"),r.push(n.tier)),t.length===0)return;t.push("updated_at = datetime('now')"),r.push(e);let a=`UPDATE qe_patterns SET ${t.join(", ")} WHERE id = ?`;this.db.prepare(a).run(...r)}storePatternEmbedding(e,n){if(!this.db)throw new Error("Database not initialized");let t=this.prepared.get("insertEmbedding");if(!t)throw new Error("Prepared statements not ready");let r=Buffer.from(new Float32Array(n).buffer);t.run(e,r,n.length,"all-MiniLM-L6-v2")}recordPatternReuse(e,n,t,r=!1,a=0,i){if(!this.db)throw new Error("Database not initialized");try{this.db.exec(`
|
|
212
|
+
CREATE TABLE IF NOT EXISTS qe_pattern_reuse (
|
|
213
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
214
|
+
pattern_id TEXT NOT NULL,
|
|
215
|
+
task_description TEXT NOT NULL,
|
|
216
|
+
similarity_score REAL NOT NULL,
|
|
217
|
+
was_reused INTEGER DEFAULT 0,
|
|
218
|
+
tokens_saved INTEGER DEFAULT 0,
|
|
219
|
+
routing_context_json TEXT,
|
|
220
|
+
created_at TEXT DEFAULT (datetime('now'))
|
|
221
|
+
);
|
|
222
|
+
CREATE INDEX IF NOT EXISTS idx_pattern_reuse_pattern ON qe_pattern_reuse(pattern_id);
|
|
223
|
+
CREATE INDEX IF NOT EXISTS idx_pattern_reuse_created ON qe_pattern_reuse(created_at);
|
|
224
|
+
`),this.db.prepare(`
|
|
225
|
+
INSERT INTO qe_pattern_reuse (
|
|
226
|
+
pattern_id, task_description, similarity_score, was_reused, tokens_saved, routing_context_json
|
|
227
|
+
) VALUES (?, ?, ?, ?, ?, ?)
|
|
228
|
+
`).run(e,n.slice(0,1e3),t,r?1:0,a,i?JSON.stringify(i):null)}catch(s){console.debug("[SQLitePatternStore] Failed to record pattern reuse:",_(s))}}getPatternReuseStats(e,n=7){if(!this.db)throw new Error("Database not initialized");try{if(!this.db.prepare(`
|
|
229
|
+
SELECT name FROM sqlite_master WHERE type='table' AND name='qe_pattern_reuse'
|
|
230
|
+
`).get())return{totalSearches:0,totalReused:0,reuseRate:0,totalTokensSaved:0,avgSimilarity:0,topPatterns:[]};let r=new Date(Date.now()-n*24*60*60*1e3).toISOString(),a=e?"WHERE pattern_id = ? AND created_at >= ?":"WHERE created_at >= ?",i=e?[e,r]:[r],s=this.db.prepare(`
|
|
231
|
+
SELECT
|
|
232
|
+
COUNT(*) as total_searches,
|
|
233
|
+
SUM(CASE WHEN was_reused = 1 THEN 1 ELSE 0 END) as total_reused,
|
|
234
|
+
SUM(tokens_saved) as total_tokens_saved,
|
|
235
|
+
AVG(similarity_score) as avg_similarity
|
|
236
|
+
FROM qe_pattern_reuse
|
|
237
|
+
${a}
|
|
238
|
+
`).get(...i),o=this.db.prepare(`
|
|
239
|
+
SELECT
|
|
240
|
+
pattern_id,
|
|
241
|
+
COUNT(*) as reuse_count,
|
|
242
|
+
AVG(similarity_score) as avg_similarity
|
|
243
|
+
FROM qe_pattern_reuse
|
|
244
|
+
WHERE created_at >= ?
|
|
245
|
+
GROUP BY pattern_id
|
|
246
|
+
ORDER BY reuse_count DESC
|
|
247
|
+
LIMIT 10
|
|
248
|
+
`).all(r);return{totalSearches:s.total_searches||0,totalReused:s.total_reused||0,reuseRate:s.total_searches>0?(s.total_reused||0)/s.total_searches:0,totalTokensSaved:s.total_tokens_saved||0,avgSimilarity:s.avg_similarity||0,topPatterns:o.map(E=>({patternId:E.pattern_id,reuseCount:E.reuse_count,avgSimilarity:E.avg_similarity}))}}catch(t){return console.debug("[SQLitePatternStore] Failed to get reuse stats:",_(t)),{totalSearches:0,totalReused:0,reuseRate:0,totalTokensSaved:0,avgSimilarity:0,topPatterns:[]}}}async backfillEmbeddings(e=32){if(!this.db)throw new Error("Database not initialized");let n=L(),t=this.db.prepare(`
|
|
249
|
+
SELECT p.id, p.name, p.description, p.pattern_type, p.qe_domain
|
|
250
|
+
FROM qe_patterns p
|
|
251
|
+
WHERE p.id NOT IN (SELECT pattern_id FROM qe_pattern_embeddings)
|
|
252
|
+
AND p.id NOT LIKE 'bench-%'
|
|
253
|
+
ORDER BY p.quality_score DESC
|
|
254
|
+
`).all(),r=this.db.prepare(`
|
|
255
|
+
SELECT COUNT(*) as c FROM qe_pattern_embeddings
|
|
256
|
+
`).get();if(t.length===0)return console.log(`[SQLitePatternStore] Backfill: all patterns already have embeddings (${r.c} total)`),{processed:0,skipped:0,errors:0,alreadyHad:r.c,method:"transformer"};console.log(`[SQLitePatternStore] Backfill: ${t.length} patterns need embeddings (${r.c} already have)`);let a=this.prepared.get("insertEmbedding");if(!a)throw new Error("Prepared statements not ready");let i=0,s=0,o=0,E="transformer";for(let u=0;u<t.length;u+=e){let T=t.slice(u,u+e),p=[];for(let d of T){let c=[d.name,d.description,d.pattern_type,d.qe_domain].filter(Boolean).join(" ");if(!c.trim()){s++;continue}p.push({id:d.id,text:c})}if(p.length===0)continue;let l;try{l=await R(p.map(d=>d.text))}catch(d){console.warn(`[SQLitePatternStore] Transformer unavailable, falling back to hash embeddings: ${_(d)}`),E="hash-fallback",l=p.map(c=>C(c.text,n))}let O=E==="transformer"?"transformer-backfill":"hash-backfill";this.db.transaction(()=>{for(let d=0;d<p.length;d++)try{let c=l[d];if(!c||c.length!==n){o++;continue}let y=Buffer.from(new Float32Array(c).buffer);a.run(p[d].id,y,n,O),i++}catch(c){o++,o<=3&&console.warn(`[SQLitePatternStore] Backfill error for ${p[d].id}:`,_(c))}})();let g=Math.min(u+e,t.length);(g%100===0||g>=t.length)&&console.log(`[SQLitePatternStore] Backfill progress: ${g}/${t.length}`)}return console.log(`[SQLitePatternStore] Backfill complete (${E}): ${i} processed, ${s} skipped, ${o} errors`),{processed:i,skipped:s,errors:o,alreadyHad:r.c,method:E}}close(){this.db&&(this.unifiedMemory?console.log("[SQLitePatternStore] Detached from unified storage (not closing shared connection)"):(this.db.close(),console.log("[SQLitePatternStore] Database closed")),this.db=null,this.unifiedMemory=null,this.initialized=!1,this.prepared.clear())}exec(e){if(!this.db)throw new Error("Database not initialized");this.db.exec(e)}getDb(){if(!this.db)throw new Error("Database not initialized");return this.db}};function k(m={}){return new h(m)}export{D as a,C as b,h as c,k as d};
|