agentic-qe 3.8.14 → 3.9.1
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 +60 -0
- package/dist/adapters/a2ui/integration/agui-sync.js +2 -1
- package/dist/audit/witness-chain.d.ts +1 -1
- 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-NTM4ZH3P.js +2 -0
- package/dist/cli/chunks/agent-booster-wasm-UH2J6BNA.js +2 -0
- package/dist/cli/chunks/agent-handler-ZCBWQE3X.js +33 -0
- package/dist/cli/chunks/agent-memory-branch-2BAVI7UW.js +2 -0
- package/dist/cli/chunks/aqe-learning-engine-RVX6MPYK.js +2 -0
- package/dist/cli/chunks/audit-G5UIJBSQ.js +3 -0
- package/dist/cli/chunks/base-7HKNQ6UP.js +2 -0
- package/dist/cli/chunks/better-sqlite3-YHIAPPVT.js +2 -0
- package/dist/cli/chunks/brain-handler-5EE3J5PR.js +68 -0
- package/dist/cli/chunks/branch-enumerator-OV54PID5.js +7 -0
- package/dist/cli/chunks/browser-7RZGKOEO.js +4 -0
- package/dist/cli/chunks/browser-workflow-UOFSQK7X.js +2 -0
- package/dist/cli/chunks/chunk-24E47G3D.js +604 -0
- package/dist/cli/chunks/chunk-35H73OPP.js +2 -0
- package/dist/cli/chunks/chunk-36X2O3BL.js +3 -0
- package/dist/cli/chunks/chunk-3JESHZQM.js +2 -0
- package/dist/cli/chunks/chunk-3VAKR43Z.js +2 -0
- package/dist/cli/chunks/chunk-3WQNW6CH.js +2 -0
- package/dist/cli/chunks/chunk-43M6Y6VF.js +15 -0
- package/dist/cli/chunks/chunk-4BHOAQJH.js +2 -0
- package/dist/cli/chunks/chunk-4LWXZCSD.js +146 -0
- package/dist/cli/chunks/chunk-4TNXEANY.js +2 -0
- package/dist/cli/chunks/chunk-4XBY5JDT.js +4 -0
- package/dist/cli/chunks/chunk-4XREPCBZ.js +2 -0
- package/dist/cli/chunks/chunk-5GPTM2RV.js +2 -0
- package/dist/cli/chunks/chunk-5KBQQP3X.js +7 -0
- package/dist/cli/chunks/chunk-5LDBKZ6P.js +2 -0
- package/dist/cli/chunks/chunk-6BSJNG2S.js +2 -0
- package/dist/cli/chunks/chunk-6YC24TPL.js +27 -0
- package/dist/cli/chunks/chunk-7ATLJCSG.js +2 -0
- package/dist/cli/chunks/chunk-7JQTHPCD.js +2 -0
- package/dist/cli/chunks/chunk-7YUOUVN7.js +2 -0
- package/dist/cli/chunks/chunk-7ZNINH6J.js +59 -0
- package/dist/cli/chunks/chunk-A57BEPL7.js +3 -0
- package/dist/cli/chunks/chunk-AFPMCMVX.js +45 -0
- package/dist/cli/chunks/chunk-AREIP4FX.js +3 -0
- package/dist/cli/chunks/chunk-B2I7BJLL.js +3 -0
- package/dist/cli/chunks/chunk-BEHP3DEF.js +66 -0
- package/dist/cli/chunks/chunk-C24ZDUCM.js +30 -0
- package/dist/cli/chunks/chunk-D4PSFWND.js +2 -0
- package/dist/cli/chunks/chunk-D55PSO5D.js +81 -0
- package/dist/cli/chunks/chunk-DC3HPOOJ.js +2 -0
- package/dist/cli/chunks/chunk-DMGLX76J.js +180 -0
- package/dist/cli/chunks/chunk-E33KQBMW.js +2 -0
- package/dist/cli/chunks/chunk-EQFZQPFN.js +2 -0
- package/dist/cli/chunks/chunk-FPRL6UDF.js +2 -0
- package/dist/cli/chunks/chunk-FRNB4CH2.js +2 -0
- package/dist/cli/chunks/chunk-FWDKVTK4.js +2 -0
- package/dist/cli/chunks/chunk-GFNUESMU.js +2 -0
- package/dist/cli/chunks/chunk-GJW6V35N.js +2 -0
- package/dist/cli/chunks/chunk-GLIFZWV2.js +2 -0
- package/dist/cli/chunks/chunk-GNUUBTSX.js +14 -0
- package/dist/cli/chunks/chunk-HAUXLXKZ.js +2 -0
- package/dist/cli/chunks/chunk-HTXSUTWL.js +9 -0
- package/dist/cli/chunks/chunk-I5WZ2NM2.js +95 -0
- package/dist/cli/chunks/chunk-I7TA453K.js +2 -0
- package/dist/cli/chunks/chunk-IF6GW6IY.js +27 -0
- package/dist/cli/chunks/chunk-IHWSNYL2.js +5 -0
- package/dist/cli/chunks/chunk-IJKYJGJL.js +2 -0
- package/dist/cli/chunks/chunk-IQPXANCE.js +14 -0
- package/dist/cli/chunks/chunk-JCEY7RLP.js +2 -0
- package/dist/cli/chunks/chunk-JSOBRKMA.js +2 -0
- package/dist/cli/chunks/chunk-KIGRLIU4.js +2 -0
- package/dist/cli/chunks/chunk-L4H54Z27.js +21 -0
- package/dist/cli/chunks/chunk-LCOEBFAB.js +2 -0
- package/dist/cli/chunks/chunk-MZ54VM6A.js +2 -0
- package/dist/cli/chunks/chunk-NB47YT6A.js +167 -0
- package/dist/cli/chunks/chunk-NG3BKE7V.js +2 -0
- package/dist/cli/chunks/chunk-NG4TE3OW.js +2 -0
- package/dist/cli/chunks/chunk-O636JKJR.js +18 -0
- package/dist/cli/chunks/chunk-O6QQ4HLS.js +2 -0
- package/dist/cli/chunks/chunk-OFNIQCGX.js +2 -0
- package/dist/cli/chunks/chunk-OTSJU5LH.js +2 -0
- package/dist/cli/chunks/chunk-POLFT2PQ.js +15 -0
- package/dist/cli/chunks/chunk-QAYTL6KC.js +2 -0
- package/dist/cli/chunks/chunk-QMFP5OKH.js +2 -0
- package/dist/cli/chunks/chunk-RAJO7VML.js +2 -0
- package/dist/cli/chunks/chunk-RKIGOARX.js +2 -0
- package/dist/cli/chunks/chunk-RU6Q5HOC.js +3 -0
- package/dist/cli/chunks/chunk-RV6SGDET.js +2 -0
- package/dist/cli/chunks/chunk-RWXI7XAR.js +2 -0
- package/dist/cli/chunks/chunk-RXVYOXDB.js +2 -0
- package/dist/cli/chunks/chunk-SGRN6JFB.js +2 -0
- package/dist/cli/chunks/chunk-SVNX4UWR.js +3029 -0
- package/dist/cli/chunks/chunk-TL7ABIMP.js +2 -0
- package/dist/cli/chunks/chunk-TOLYWONQ.js +2 -0
- package/dist/cli/chunks/chunk-TPXYS3WG.js +3 -0
- package/dist/cli/chunks/chunk-U5JQGRHZ.js +2 -0
- package/dist/cli/chunks/chunk-UB7RGVKO.js +2 -0
- package/dist/cli/chunks/chunk-UBKK7KCR.js +70 -0
- package/dist/cli/chunks/chunk-UMGWGX7C.js +2 -0
- package/dist/cli/chunks/chunk-UN4PA4M2.js +2 -0
- package/dist/cli/chunks/chunk-US7INRP2.js +314 -0
- package/dist/cli/chunks/chunk-UWDBFPHQ.js +750 -0
- package/dist/cli/chunks/chunk-UZZCWWIG.js +2 -0
- package/dist/cli/chunks/chunk-V4HM4QAO.js +24 -0
- package/dist/cli/chunks/chunk-V4U3CTS2.js +180 -0
- package/dist/cli/chunks/chunk-VCCMCFDU.js +2 -0
- package/dist/cli/chunks/chunk-VEWIT6VN.js +4 -0
- package/dist/cli/chunks/chunk-VNYGVG4Y.js +2 -0
- package/dist/cli/chunks/chunk-VO3OVD5D.js +4 -0
- package/dist/cli/chunks/chunk-VY74OMGQ.js +6 -0
- package/dist/cli/chunks/chunk-WDJBGXC2.js +2 -0
- package/dist/cli/chunks/chunk-WDV6TN7E.js +65 -0
- package/dist/cli/chunks/chunk-WLXEDOG4.js +2 -0
- package/dist/cli/chunks/chunk-WXXAAXNS.js +12 -0
- package/dist/cli/chunks/chunk-X4MZYBOU.js +256 -0
- package/dist/cli/chunks/chunk-XE2YAYU5.js +12 -0
- package/dist/cli/chunks/chunk-XP6XKBNW.js +2 -0
- package/dist/cli/chunks/chunk-XPB6ZVQY.js +2 -0
- package/dist/cli/chunks/chunk-XRVUSKQV.js +1 -0
- package/dist/cli/chunks/chunk-XSITQBYB.js +20 -0
- package/dist/cli/chunks/chunk-XTLA4F5Z.js +91 -0
- package/dist/cli/chunks/chunk-XU6L2VJY.js +2 -0
- package/dist/cli/chunks/chunk-XUFHYPZK.js +2 -0
- package/dist/cli/chunks/chunk-Y2ZEDXTV.js +16 -0
- package/dist/cli/chunks/chunk-YQWB4QUP.js +316 -0
- package/dist/cli/chunks/chunk-YUQIXT3G.js +79 -0
- package/dist/cli/chunks/chunk-YYYB2JN5.js +2 -0
- package/dist/cli/chunks/chunk-ZEUVPLGX.js +2 -0
- package/dist/cli/chunks/chunk-ZSRQHJEW.js +3 -0
- package/dist/cli/chunks/ci-N4NTYAAI.js +81 -0
- package/dist/cli/chunks/ci-output-XYR2PSYH.js +2 -0
- package/dist/cli/chunks/claude-flow-setup-FX7PRBJV.js +2 -0
- package/dist/cli/chunks/client-CRRENRK4.js +2 -0
- package/dist/cli/chunks/cline-installer-GTHQOK7U.js +4 -0
- package/dist/cli/chunks/code-4G6ZHVNI.js +38 -0
- package/dist/cli/chunks/code-index-extractor-MKJTP5AK.js +3 -0
- package/dist/cli/chunks/codex-installer-UGS773DT.js +8 -0
- package/dist/cli/chunks/completions-B3BXNXAU.js +1364 -0
- package/dist/cli/chunks/complexity-analyzer-PMN77CUP.js +2 -0
- package/dist/cli/chunks/continuedev-installer-3DYKSIP3.js +14 -0
- package/dist/cli/chunks/copilot-installer-IUC5HDHD.js +3 -0
- package/dist/cli/chunks/cost-tracker-GSGQ7O5T.js +2 -0
- package/dist/cli/chunks/coverage-PO72QC3P.js +27 -0
- package/dist/cli/chunks/cross-domain-router-FSCGJG3B.js +2 -0
- package/dist/cli/chunks/cursor-installer-FK53S3ZL.js +3 -0
- package/dist/cli/chunks/daemon-4UIQTQ73.js +19 -0
- package/dist/cli/chunks/dag-attention-scheduler-ZGIMLECE.js +2 -0
- package/dist/cli/chunks/detect-XXHLTLL7.js +2 -0
- package/dist/cli/chunks/domain-handler-PPGFP7P4.js +25 -0
- package/dist/cli/chunks/domain-transfer-Q5UAE65W.js +2 -0
- package/dist/cli/chunks/dream-PONKQULG.js +2 -0
- package/dist/cli/chunks/esm-node-XLWDJRBX.js +2 -0
- package/dist/cli/chunks/eval-JVJKHSTQ.js +15 -0
- package/dist/cli/chunks/fast-paths-3KX4ZV66.js +2 -0
- package/dist/cli/chunks/feature-flags-2NOVE7DL.js +2 -0
- package/dist/cli/chunks/feature-flags-GKHHG2I2.js +2 -0
- package/dist/cli/chunks/file-discovery-XFSGQNM3.js +2 -0
- package/dist/cli/chunks/fleet-FOIDAXLR.js +43 -0
- package/dist/cli/chunks/gnn-wrapper-HPCQREKP.js +2 -0
- package/dist/cli/chunks/heartbeat-handler-HTR3EFFV.js +48 -0
- package/dist/cli/chunks/heartbeat-scheduler-NZQWN7CH.js +2 -0
- package/dist/cli/chunks/hnsw-adapter-BNA5WUAB.js +2 -0
- package/dist/cli/chunks/hnsw-index-RQIIAE7S.js +2 -0
- package/dist/cli/chunks/hnsw-legacy-bridge-H6OA3AA3.js +2 -0
- package/dist/cli/chunks/hnswlib-node-FF27BDMD.js +2 -0
- package/dist/cli/chunks/hooks-63NZQ7NH.js +101 -0
- package/dist/cli/chunks/hypergraph-engine-XMSLA4XH.js +2 -0
- package/dist/cli/chunks/hypergraph-handler-ID6J6GS2.js +35 -0
- package/dist/cli/chunks/impact-analyzer-FS2UNVP4.js +2 -0
- package/dist/cli/chunks/init-handler-CIKZGGAY.js +68 -0
- package/dist/cli/chunks/init-wizard-TUU5PPY6.js +2 -0
- package/dist/cli/chunks/kernel-XFG42WAG.js +2 -0
- package/dist/cli/chunks/kilocode-installer-N7NLISYY.js +4 -0
- package/dist/cli/chunks/kiro-installer-U6XIPAT3.js +74 -0
- package/dist/cli/chunks/knowledge-graph-XV7FPU2T.js +2 -0
- package/dist/cli/chunks/learning-NKOF7KDJ.js +107 -0
- package/dist/cli/chunks/llm-router-34WHT3PH.js +30 -0
- package/dist/cli/chunks/load-ZW4Z3YLT.js +2 -0
- package/dist/cli/chunks/load-test-F4L7RTXJ.js +2 -0
- package/dist/cli/chunks/mcp-6R7SVGKO.js +2 -0
- package/dist/cli/chunks/memory-OUYCBU4M.js +32 -0
- package/dist/cli/chunks/memory-backend-DTJD2DWF.js +2 -0
- package/dist/cli/chunks/memory-handlers-WNXKZRNM.js +2 -0
- package/dist/cli/chunks/opencode-installer-FR75GHFU.js +3 -0
- package/dist/cli/chunks/orchestrator-AK7ZMVNH.js +371 -0
- package/dist/cli/chunks/pipeline-CFOPG7EM.js +19 -0
- package/dist/cli/chunks/platform-NY3ULBR7.js +2 -0
- package/dist/cli/chunks/plugin-LRANQYUR.js +27 -0
- package/dist/cli/chunks/prime-radiant-advanced-wasm-6KEIU55P.js +2 -0
- package/dist/cli/chunks/protocol-executor-6W4PS2D4.js +2 -0
- package/dist/cli/chunks/protocol-handler-ESSZGJ7R.js +20 -0
- package/dist/cli/chunks/prove-EF2PPY65.js +3 -0
- package/dist/cli/chunks/qe-reasoning-bank-7G3TZLEA.js +2 -0
- package/dist/cli/chunks/quality-AYBXB635.js +7 -0
- package/dist/cli/chunks/queen-coordinator-NFPKGMQN.js +2 -0
- package/dist/cli/chunks/real-embeddings-QPBXE7MA.js +2 -0
- package/dist/cli/chunks/roocode-installer-UF6MMBH6.js +4 -0
- package/dist/cli/chunks/router-F4B7Q66G.js +2 -0
- package/dist/cli/chunks/routing-feedback-5CIDDW7P.js +2 -0
- package/dist/cli/chunks/routing-handler-5TVKFU7V.js +20 -0
- package/dist/cli/chunks/ruvector-commands-E33VXFIA.js +8 -0
- package/dist/cli/chunks/rvf-dual-writer-O3AZKD24.js +2 -0
- package/dist/cli/chunks/rvf-migration-adapter-IKEUZ2HX.js +2 -0
- package/dist/cli/chunks/rvf-migration-coordinator-M4H7W4RN.js +2 -0
- package/dist/cli/chunks/rvf-native-adapter-UX3WAPIP.js +2 -0
- package/dist/cli/chunks/safe-db-QBBNXEVK.js +2 -0
- package/dist/cli/chunks/schedule-GFT4NN6Z.js +2 -0
- package/dist/cli/chunks/scheduler-CQ56T7DB.js +2 -0
- package/dist/cli/chunks/security-ZLWT7IU3.js +14 -0
- package/dist/cli/chunks/shared-rvf-adapter-EXACQ2PT.js +2 -0
- package/dist/cli/chunks/shared-rvf-dual-writer-G43LQDIV.js +2 -0
- package/dist/cli/chunks/sqlite-persistence-JHSUZPAW.js +2 -0
- package/dist/cli/chunks/status-handler-7P23CXUI.js +45 -0
- package/dist/cli/chunks/structural-health-SCNBNL7K.js +2 -0
- package/dist/cli/chunks/sync-BYZBBH65.js +23 -0
- package/dist/cli/chunks/task-handler-DWJQXZ2K.js +49 -0
- package/dist/cli/chunks/task-handlers-35JIXVRW.js +2 -0
- package/dist/cli/chunks/test-2JSS4XW7.js +33 -0
- package/dist/cli/chunks/test-scheduling-TWJ5I7N3.js +15 -0
- package/dist/cli/chunks/token-bootstrap-LLLNJT5V.js +2 -0
- package/dist/cli/chunks/token-usage-EQ4HM4EZ.js +25 -0
- package/dist/cli/chunks/transformers-PBIR5U5S.js +2 -0
- package/dist/cli/chunks/tree-sitter-wasm-parser-X3L2GXUX.js +2 -0
- package/dist/cli/chunks/types-OD43K2NP.js +2 -0
- package/dist/cli/chunks/unified-memory-YPHONR2T.js +2 -0
- package/dist/cli/chunks/unified-memory-hnsw-HJS4OXWM.js +2 -0
- package/dist/cli/chunks/unified-persistence-EFZRO6AW.js +2 -0
- package/dist/cli/chunks/validate-POMLT2KU.js +21 -0
- package/dist/cli/chunks/validate-swarm-UOC4JGZT.js +14 -0
- package/dist/cli/chunks/vibium-5JF6LAXI.js +2 -0
- package/dist/cli/chunks/visual-security-7KWFLYNB.js +2 -0
- package/dist/cli/chunks/web-tree-sitter-R7WR7J7B.js +2 -0
- package/dist/cli/chunks/windsurf-installer-ZSPEUBKR.js +7 -0
- package/dist/cli/chunks/witness-chain-CFSPCXHG.js +2 -0
- package/dist/cli/chunks/witness-chain-RWU6WT37.js +2 -0
- package/dist/cli/chunks/workflow-YNQT3OW2.js +51 -0
- package/dist/cli/chunks/workflow-orchestrator-Z6TAVMQP.js +2 -0
- package/dist/cli/chunks/wrappers-BP4FODVH.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/ruvector-commands.js +14 -2
- 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/agent-memory-branch.d.ts +117 -0
- package/dist/coordination/agent-memory-branch.js +213 -0
- package/dist/coordination/agent-teams/mailbox.d.ts +43 -0
- package/dist/coordination/agent-teams/mailbox.js +130 -4
- package/dist/coordination/consensus/providers/claude-provider.d.ts +1 -0
- package/dist/coordination/consensus/providers/claude-provider.js +23 -3
- package/dist/coordination/handlers/handler-utils.d.ts +1 -0
- package/dist/coordination/handlers/handler-utils.js +9 -2
- package/dist/coordination/handlers/quality-handlers.js +7 -1
- package/dist/domains/contract-testing/coordinator.js +11 -0
- package/dist/domains/quality-assessment/coherence/gate-controller.d.ts +20 -1
- package/dist/domains/quality-assessment/coherence/gate-controller.js +64 -0
- package/dist/domains/quality-assessment/coherence/index.d.ts +3 -3
- package/dist/domains/quality-assessment/coherence/index.js +2 -2
- package/dist/domains/quality-assessment/coherence/types.d.ts +39 -0
- package/dist/domains/quality-assessment/coherence/types.js +11 -0
- package/dist/domains/quality-assessment/coordinator.d.ts +14 -0
- package/dist/domains/quality-assessment/coordinator.js +92 -0
- package/dist/domains/test-execution/coordinator.d.ts +19 -0
- package/dist/domains/test-execution/coordinator.js +102 -5
- package/dist/domains/test-generation/coordinator.js +11 -0
- package/dist/domains/test-generation/interfaces.d.ts +2 -0
- package/dist/domains/test-generation/services/test-generator.d.ts +9 -0
- package/dist/domains/test-generation/services/test-generator.js +37 -0
- package/dist/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/init/agents-installer.d.ts +5 -3
- package/dist/init/agents-installer.js +17 -43
- package/dist/init/find-package-root.d.ts +22 -0
- package/dist/init/find-package-root.js +46 -0
- package/dist/init/n8n-installer.d.ts +4 -2
- package/dist/init/n8n-installer.js +23 -23
- package/dist/init/opencode-installer.d.ts +0 -5
- package/dist/init/opencode-installer.js +12 -39
- package/dist/init/skills-installer.d.ts +5 -2
- package/dist/init/skills-installer.js +15 -37
- package/dist/integrations/embeddings/index/HNSWIndex.d.ts +9 -2
- package/dist/integrations/embeddings/index/HNSWIndex.js +110 -35
- package/dist/integrations/ruvector/cognitive-routing.d.ts +67 -0
- package/dist/integrations/ruvector/cognitive-routing.js +208 -0
- package/dist/integrations/ruvector/feature-flags.d.ts +84 -0
- package/dist/integrations/ruvector/feature-flags.js +59 -0
- package/dist/integrations/ruvector/hdc-fingerprint.d.ts +76 -0
- package/dist/integrations/ruvector/hdc-fingerprint.js +217 -0
- package/dist/integrations/ruvector/hyperbolic-hnsw.d.ts +59 -0
- package/dist/integrations/ruvector/hyperbolic-hnsw.js +194 -0
- package/dist/integrations/ruvector/index.d.ts +5 -2
- package/dist/integrations/ruvector/index.js +13 -2
- package/dist/integrations/ruvector/shared-rvf-adapter.d.ts +24 -0
- package/dist/integrations/ruvector/shared-rvf-adapter.js +55 -0
- package/dist/integrations/ruvector/shared-rvf-dual-writer.d.ts +6 -0
- package/dist/integrations/ruvector/shared-rvf-dual-writer.js +38 -0
- package/dist/integrations/ruvector/sona-persistence.d.ts +8 -0
- package/dist/integrations/ruvector/sona-persistence.js +10 -0
- package/dist/integrations/ruvector/vector-delta-tracker.d.ts +96 -0
- package/dist/integrations/ruvector/vector-delta-tracker.js +226 -0
- package/dist/kernel/agent-coordinator.d.ts +75 -1
- package/dist/kernel/agent-coordinator.js +250 -1
- package/dist/kernel/hnsw-legacy-bridge.d.ts +38 -0
- package/dist/kernel/hnsw-legacy-bridge.js +88 -0
- package/dist/kernel/hnsw-shadow-validator.d.ts +91 -0
- package/dist/kernel/hnsw-shadow-validator.js +139 -0
- package/dist/kernel/index.d.ts +1 -1
- package/dist/kernel/index.js +1 -1
- package/dist/kernel/interfaces.d.ts +39 -0
- package/dist/kernel/kernel.d.ts +23 -0
- package/dist/kernel/kernel.js +141 -1
- package/dist/kernel/memory-backend.js +3 -1
- package/dist/kernel/unified-memory.d.ts +1 -1
- package/dist/kernel/unified-memory.js +7 -3
- package/dist/learning/aqe-learning-engine.d.ts +65 -0
- package/dist/learning/aqe-learning-engine.js +134 -0
- package/dist/learning/dream/dream-engine.d.ts +6 -1
- package/dist/learning/dream/dream-engine.js +37 -2
- package/dist/learning/dream/dream-scheduler.d.ts +25 -0
- package/dist/learning/dream/dream-scheduler.js +120 -0
- package/dist/learning/dream/rvcow-branch-manager.d.ts +6 -3
- package/dist/learning/dream/rvcow-branch-manager.js +60 -5
- package/dist/learning/experience-capture.d.ts +3 -3
- package/dist/learning/hyperbolic-pattern-index.d.ts +82 -0
- package/dist/learning/hyperbolic-pattern-index.js +142 -0
- package/dist/learning/index.d.ts +3 -3
- package/dist/learning/index.js +1 -1
- package/dist/learning/metrics-tracker.d.ts +44 -0
- package/dist/learning/metrics-tracker.js +37 -0
- package/dist/learning/pattern-promotion.d.ts +3 -3
- package/dist/learning/pattern-store.d.ts +45 -2
- package/dist/learning/pattern-store.js +217 -4
- package/dist/learning/qe-patterns.d.ts +1 -1
- package/dist/learning/qe-reasoning-bank.js +1 -1
- package/dist/learning/rvf-pattern-migration.d.ts +50 -0
- package/dist/learning/rvf-pattern-migration.js +106 -0
- package/dist/learning/rvf-pattern-store.d.ts +66 -0
- package/dist/learning/rvf-pattern-store.js +447 -0
- package/dist/mcp/bundle.js +1937 -1793
- package/dist/mcp/entry.js +132 -77
- package/dist/mcp/handlers/index.d.ts +1 -0
- package/dist/mcp/handlers/index.js +2 -0
- package/dist/mcp/handlers/migration-handlers.d.ts +52 -0
- package/dist/mcp/handlers/migration-handlers.js +85 -0
- package/dist/mcp/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 +12 -0
- package/dist/mcp/protocol-server.js +192 -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 +2 -1
- package/dist/optimization/early-exit-token-optimizer.d.ts +7 -7
- package/dist/optimization/early-exit-token-optimizer.js +3 -3
- package/dist/persistence/rvf-consistency-validator.d.ts +85 -0
- package/dist/persistence/rvf-consistency-validator.js +182 -0
- package/dist/persistence/rvf-migration-adapter.d.ts +125 -0
- package/dist/persistence/rvf-migration-adapter.js +303 -0
- package/dist/persistence/rvf-migration-coordinator.d.ts +115 -0
- package/dist/persistence/rvf-migration-coordinator.js +224 -0
- package/dist/persistence/rvf-stage-gate.d.ts +70 -0
- package/dist/persistence/rvf-stage-gate.js +163 -0
- package/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 +10 -10
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.1");process.exit(0)}
|
|
2
|
+
import{a as h}from"./chunk-3VAKR43Z.js";import{a as C,f as x}from"./chunk-WDJBGXC2.js";var d={mechanical:["convert var to const","add types","remove console","convert to async","convert to esm","arrow function","rename variable","format code"],simple:["fix typo","update comment","fix simple bug","add documentation","format","rename","simple refactor","basic test"],moderate:["implement feature","implement","refactor","complex refactor","performance optimization","optimize","test generation","generate test","error handling","validation logic","api integration","code index","coverage analysis","quality assessment","defect prediction","predict defect","analyze coverage","analyze","assess","scan","detect"],complex:["multi-file refactor","orchestrate","coordinate","large codebase","migration","cross-domain","workflow","system design","analyze security","security scan","security analysis","vulnerability scan","chaos test","resilience test","contract validation"],critical:["architecture","security audit","critical bug","algorithm design","system-wide","vulnerability","cryptography","performance critical","hardcoded secret","cve","owasp","penetration test","exploit"]},f={architecture:/\b(architect|design|system design|overall structure|component design)\b/i,security:/\b(security|vulnerability|audit|xss|sql injection|csrf|encryption|auth|authentication|authorization)\b/i,multiStep:/\b(orchestrate|coordinate|workflow|pipeline|multi[- ]step)\b/i,crossDomain:/\b(cross[- ]domain|across (domains|modules)|integrate|coordination)\b/i},m=class{config;agentBoosterAdapter;constructor(e,t){this.config=e,this.agentBoosterAdapter=t}async collectSignals(e){let t=e.task.toLowerCase(),r=await this.checkAgentBoosterEligibility(e),o={simple:this.findKeywordMatches(t,d.simple),moderate:this.findKeywordMatches(t,d.moderate),complex:this.findKeywordMatches(t,d.complex),critical:this.findKeywordMatches(t,d.critical)},c=e.codeContext?e.codeContext.split(`
|
|
3
|
+
`).length:void 0,n=e.filePaths?e.filePaths.length:void 0,i=f.architecture.test(t),a=f.security.test(t),l=f.multiStep.test(t),g=f.crossDomain.test(t),b=this.detectCreativityRequirement(t),S=this.estimateLanguageComplexity(e.codeContext,e.filePaths),T=e.codeContext?this.estimateCyclomaticComplexity(e.codeContext):void 0;return{linesOfCode:c,fileCount:n,hasArchitectureScope:i,hasSecurityScope:a,requiresMultiStepReasoning:l,requiresCrossDomainCoordination:g,isMechanicalTransform:r.eligible,languageComplexity:S,cyclomaticComplexity:T,dependencyCount:this.countDependencies(e.codeContext),requiresCreativity:b,detectedTransformType:r.transformType,keywordMatches:o}}async checkAgentBoosterEligibility(e){if(!this.config.enableAgentBooster)return{eligible:!1,confidence:0,reason:"Agent Booster is disabled"};let t=e.task.toLowerCase(),r,o=0;for(let n of h){let i=this.getTransformKeywords(n),a=0;for(let l of i)t.includes(l.toLowerCase())&&(a=a===0?.5:a+.25);for(let l of d.mechanical)t.includes(l.toLowerCase())&&(a=Math.max(a,.6));a>o&&(o=a,r=n)}if(e.codeContext&&r&&this.agentBoosterAdapter)try{let i=(await this.agentBoosterAdapter.detectTransformOpportunities(e.codeContext)).opportunities.find(a=>a.type===r);if(i)return{eligible:i.confidence>=this.config.agentBoosterThreshold,transformType:r,confidence:i.confidence,reason:i.reason}}catch(n){console.debug("[SignalCollector] WASM analysis error:",n instanceof Error?n.message:n)}let c=o>=this.config.agentBoosterThreshold&&r!==void 0;return{eligible:c,transformType:r,confidence:Math.min(o,1),reason:c?`Detected ${r} transform pattern`:"No mechanical transform pattern detected"}}findKeywordMatches(e,t){let r=[];for(let o of t)e.includes(o.toLowerCase())&&r.push(o);return r}detectCreativityRequirement(e){return e.includes("design")||e.includes("creative")||e.includes("innovative")||e.includes("novel")}estimateLanguageComplexity(e,t){if(!e&&(!t||t.length===0))return;let r=[".ts",".tsx",".rs",".cpp",".c",".go"],o=[".js",".jsx",".py",".java"],c=[".json",".yaml",".md",".txt",".css",".html"];if(t){for(let n of t)if(r.some(i=>n.endsWith(i)))return"high";for(let n of t)if(o.some(i=>n.endsWith(i)))return"medium";for(let n of t)if(c.some(i=>n.endsWith(i)))return"low"}if(e){let n=/<[A-Z][^>]*>/.test(e),i=/\b(async|await)\b/.test(e),a=/\b(interface|type|class)\b/.test(e);return n&&a?"high":i||a?"medium":"low"}return"medium"}estimateCyclomaticComplexity(e){let t=[/\bif\b/g,/\bfor\b/g,/\bwhile\b/g,/\bcase\b/g,/\bcatch\b/g,/&&/g,/\|\|/g,/\?/g],r=1;for(let o of t){let c=e.match(o);c&&(r+=c.length)}return r}countDependencies(e){if(!e)return;let t=e.match(/\b(import|require|from)\b.*['"].*['"]/g);return t?t.length:0}getTransformKeywords(e){return{"var-to-const":["var to const","convert var","var declaration","var to let","convert var to const","change var to const"],"add-types":["add types","add type","typescript types","type annotations","type annotation","add type annotations"],"remove-console":["remove console","delete console","console.log","remove console.log","strip console"],"promise-to-async":["promise to async","async await",".then to async","convert to async","convert function to async"],"cjs-to-esm":["commonjs to esm","require to import","convert to esm","cjs to esm","module conversion"],"func-to-arrow":["arrow function","function to arrow","convert to arrow","convert function to arrow"]}[e]||[]}};function v(s,e){return new m(s,e)}var u=class{calculateCodeComplexity(e){let t=0;return t+=this.calculateLinesOfCodeContribution(e.linesOfCode),t+=this.calculateFileCountContribution(e.fileCount),t+=this.calculateCyclomaticContribution(e.cyclomaticComplexity),t+=this.calculateLanguageContribution(e.languageComplexity),Math.min(t,100)}calculateReasoningComplexity(e){let t=0;return t+=this.calculateKeywordScore(e.keywordMatches),e.requiresMultiStepReasoning&&(t+=20),e.requiresCreativity&&(t+=20),Math.min(t,100)}calculateScopeComplexity(e){let t=0;return e.hasArchitectureScope&&(t+=40),e.hasSecurityScope&&(t+=30),e.requiresCrossDomainCoordination&&(t+=20),t+=this.calculateDependencyContribution(e.dependencyCount),Math.min(t,100)}calculateOverallComplexity(e,t,r,o){if(o.isMechanicalTransform&&!o.hasSecurityScope&&!o.hasArchitectureScope&&!o.requiresMultiStepReasoning&&!o.requiresCrossDomainCoordination&&e===0&&t===0&&r===0)return 5;let c=e*.3+t*.4+r*.3,n=0;return o.hasSecurityScope&&(n=Math.max(n,50)),o.hasArchitectureScope&&(n=Math.max(n,55)),o.requiresCrossDomainCoordination&&(n=Math.max(n,35)),o.requiresMultiStepReasoning&&(n=Math.max(n,30)),o.keywordMatches.simple.length+o.keywordMatches.moderate.length+o.keywordMatches.complex.length+o.keywordMatches.critical.length===0&&!o.isMechanicalTransform&&c<15&&(n=Math.max(n,15)),Math.min(Math.max(Math.round(c),n),100)}calculateConfidence(e,t){let r=.5;return t.codeContext&&(r+=.2),t.filePaths&&t.filePaths.length>0&&(r+=.1),r+=this.calculateKeywordConfidenceBoost(e.keywordMatches),e.isMechanicalTransform&&(r+=.15),Math.min(r,1)}calculateLinesOfCodeContribution(e){return e===void 0||e<10?0:e<50?10:e<200?20:30}calculateFileCountContribution(e){return e===void 0||e===1?0:e<5?10:20}calculateCyclomaticContribution(e){return e===void 0||e<5?0:e<10?10:e<20?20:30}calculateLanguageContribution(e){return e==="low"?0:e==="medium"?10:e==="high"?20:0}calculateKeywordScore(e){let t=e.simple.length*5+e.moderate.length*15+e.complex.length*25+e.critical.length*35;return Math.min(t,60)}calculateDependencyContribution(e){return e===void 0||e<3?0:e<10?5:10}calculateKeywordConfidenceBoost(e){let t=e.simple.length+e.moderate.length+e.complex.length+e.critical.length;return t>=3?.1:t>=1?.05:0}};function M(){return new u}var p=class{getRecommendedTier(e){for(let t of[0,1,2,3,4]){let[r,o]=C[t].complexityRange;if(e>=r&&e<=o)return t}return 2}findAlternateTiers(e,t){let r=[];return t>0&&r.push(t-1),t<4&&r.push(t+1),t<3&&!r.includes(4)&&r.push(4),r}generateExplanation(e,t,r){let o=[];return o.push(`Complexity score: ${e}/100 (Tier ${t})`),r.isMechanicalTransform&&o.push(this.formatMechanicalTransformInfo(r.detectedTransformType)),o.push(...this.formatScopeExplanations(r)),o.push(...this.formatCodeMetricsExplanations(r)),o.join(". ")}formatMechanicalTransformInfo(e){return`Detected mechanical transform: ${e}`}formatScopeExplanations(e){let t=[];return e.hasArchitectureScope&&t.push("Architecture scope detected"),e.hasSecurityScope&&t.push("Security scope detected"),e.requiresMultiStepReasoning&&t.push("Multi-step reasoning required"),e.requiresCrossDomainCoordination&&t.push("Cross-domain coordination required"),t}formatCodeMetricsExplanations(e){let t=[];return e.linesOfCode!==void 0&&e.linesOfCode>100&&t.push(`Large code change: ${e.linesOfCode} lines`),e.fileCount!==void 0&&e.fileCount>3&&t.push(`Multi-file change: ${e.fileCount} files`),t}};function w(){return new p}var y=class{config;signalCollector;scoreCalculator;tierRecommender;constructor(e,t,r,o){this.config=e,this.signalCollector=t,this.scoreCalculator=r,this.tierRecommender=o}async analyze(e){try{let t=await this.signalCollector.collectSignals(e),r=this.scoreCalculator.calculateCodeComplexity(t),o=this.scoreCalculator.calculateReasoningComplexity(t),c=this.scoreCalculator.calculateScopeComplexity(t),n=this.scoreCalculator.calculateOverallComplexity(r,o,c,t),i=this.tierRecommender.getRecommendedTier(n),a=this.tierRecommender.findAlternateTiers(n,i),l=this.scoreCalculator.calculateConfidence(t,e),g=this.tierRecommender.generateExplanation(n,i,t);return{overall:n,codeComplexity:r,reasoningComplexity:o,scopeComplexity:c,confidence:l,signals:t,recommendedTier:i,alternateTiers:a,explanation:g}}catch(t){throw new x(`Failed to analyze task complexity: ${t instanceof Error?t.message:"Unknown error"}`,t instanceof Error?t:void 0)}}async checkAgentBoosterEligibility(e){return this.signalCollector.checkAgentBoosterEligibility(e)}getRecommendedTier(e){return this.tierRecommender.getRecommendedTier(e)}};function L(s,e){let t=new m(s,e),r=new u,o=new p;return new y(s,t,r,o)}function z(s,e,t,r){return new y(s,e,t,r)}export{m as a,v as b,u as c,M as d,p as e,w as f,y as g,L as h,z as i};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.1");process.exit(0)}
|
|
2
|
+
import{c as u}from"./chunk-UZZCWWIG.js";function t(){return{...e}}function o(r){e={...e,...r}}function i(){e={...s}}function a(){return e.useBrowserMode}function E(){return e.useScreenshotCapture}function l(){return e.useVisualRegression}function c(){return e.useE2EExecution}function f(){return e.defaultHeadless}function d(){return e.useAutoRetry}function _(){return e.logPerformanceMetrics}function I(){return e.useAxeCore}function p(){let r={};process.env.VIBIUM_USE_BROWSER_MODE!==void 0&&(r.useBrowserMode=process.env.VIBIUM_USE_BROWSER_MODE==="true"),process.env.VIBIUM_USE_SCREENSHOT_CAPTURE!==void 0&&(r.useScreenshotCapture=process.env.VIBIUM_USE_SCREENSHOT_CAPTURE==="true"),process.env.VIBIUM_USE_VISUAL_REGRESSION!==void 0&&(r.useVisualRegression=process.env.VIBIUM_USE_VISUAL_REGRESSION==="true"),process.env.VIBIUM_USE_E2E_EXECUTION!==void 0&&(r.useE2EExecution=process.env.VIBIUM_USE_E2E_EXECUTION==="true"),process.env.VIBIUM_DEFAULT_HEADLESS!==void 0&&(r.defaultHeadless=process.env.VIBIUM_DEFAULT_HEADLESS==="true"),process.env.VIBIUM_USE_AUTO_RETRY!==void 0&&(r.useAutoRetry=process.env.VIBIUM_USE_AUTO_RETRY==="true"),process.env.VIBIUM_LOG_PERFORMANCE_METRICS!==void 0&&(r.logPerformanceMetrics=process.env.VIBIUM_LOG_PERFORMANCE_METRICS==="true"),process.env.VIBIUM_USE_AXE_CORE!==void 0&&(r.useAxeCore=process.env.VIBIUM_USE_AXE_CORE==="true"),o(r)}function U(){o({defaultHeadless:!0,useAutoRetry:!0,logPerformanceMetrics:!0})}function R(){o({defaultHeadless:!1,logPerformanceMetrics:!0})}function S(){o({useBrowserMode:!1,useScreenshotCapture:!1,useVisualRegression:!1,useE2EExecution:!1,useAxeCore:!1})}var s,e,n=u(()=>{s={useBrowserMode:!0,useScreenshotCapture:!0,useVisualRegression:!0,useE2EExecution:!0,defaultHeadless:!1,useAutoRetry:!0,logPerformanceMetrics:!0,useAxeCore:!0},e={...s}});export{s as a,t as b,o as c,i as d,a as e,E as f,l as g,c as h,f as i,d as j,_ as k,I as l,p as m,U as n,R as o,S as p,n as q};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.1");process.exit(0)}
|
|
2
|
+
var l=["var-to-const","add-types","remove-console","promise-to-async","cjs-to-esm","func-to-arrow"],p={"var-to-const":{type:"var-to-const",name:"Var to Const/Let",description:"Convert var declarations to const (if not reassigned) or let (if reassigned)",complexity:"simple",wasmAvailable:!0,typicalLatencyMs:1},"add-types":{type:"add-types",name:"Add TypeScript Types",description:"Add TypeScript type annotations to function parameters and return types",complexity:"moderate",wasmAvailable:!0,typicalLatencyMs:5},"remove-console":{type:"remove-console",name:"Remove Console Statements",description:"Remove all console.log, console.warn, console.error, etc. statements",complexity:"simple",wasmAvailable:!0,typicalLatencyMs:1},"promise-to-async":{type:"promise-to-async",name:"Promise to Async/Await",description:"Convert Promise .then()/.catch() chains to async/await syntax",complexity:"complex",wasmAvailable:!0,typicalLatencyMs:10},"cjs-to-esm":{type:"cjs-to-esm",name:"CommonJS to ES Modules",description:"Convert require() calls to import statements and module.exports to export",complexity:"moderate",wasmAvailable:!0,typicalLatencyMs:5},"func-to-arrow":{type:"func-to-arrow",name:"Function to Arrow",description:"Convert function declarations and expressions to arrow functions",complexity:"moderate",wasmAvailable:!0,typicalLatencyMs:3}},u={enabled:!0,fallbackToLLM:!0,confidenceThreshold:.7,transforms:[],maxFileSizeBytes:1024*1024,timeoutMs:5e3,cacheEnabled:!0,cacheTtlMs:300*1e3},t=class extends Error{constructor(e,s,o){super(e);this.code=s;this.cause=o;this.name="AgentBoosterError"}},a=class extends t{constructor(e,s,o){super(e,"TRANSFORM_ERROR",o);this.transformType=s;this.name="TransformError"}},i=class extends t{constructor(r="WASM module is not available",e){super(r,"WASM_UNAVAILABLE",e),this.name="WasmUnavailableError"}},c=class extends t{constructor(e,s,o){super(e,"TRANSFORM_TIMEOUT");this.transformType=s;this.timeoutMs=o;this.name="TransformTimeoutError"}},m=class extends t{constructor(e,s,o){super(`File ${e} is too large (${s} bytes, max ${o} bytes)`,"FILE_TOO_LARGE");this.filePath=e;this.sizeBytes=s;this.maxSizeBytes=o;this.name="FileTooLargeError"}};export{l as a,p as b,u as c,a as d,i as e,c as f,m as g};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.1");process.exit(0)}
|
|
2
|
+
import{S as f,b as p}from"./chunk-MZ54VM6A.js";f();var y={predictionWindowSize:10,compressionThreshold:.3,maxConcurrentStreams:8,oscillationFrequencyMs:100};function d(s){try{return JSON.stringify(s).length}catch{return 0}}function w(s,t){let e={},n=!1;for(let r of Object.keys(t))JSON.stringify(s[r])!==JSON.stringify(t[r])&&(e[r]=t[r],n=!0);for(let r of Object.keys(s))r in t||(e[r]=void 0,n=!0);return n?e:null}function v(s,t){let e={...s};for(let[n,r]of Object.entries(t))r===void 0?delete e[n]:e[n]=r;return e}var l=class{windowSize;windows=new Map;constructor(t){this.windowSize=Math.max(1,t)}predict(t){let e=this.windows.get(t);if(!e||e.length===0)return null;let n=e[e.length-1];return typeof n!="object"||n===null||Array.isArray(n)?null:{...n}}record(t,e){let n=this.windows.get(t);n||(n=[],this.windows.set(t,n)),n.push(e),n.length>this.windowSize&&n.shift()}removeStream(t){this.windows.delete(t)}},h=class{maxStreams;cycleMs;streamIds=[];currentIndex=0;constructor(t,e){this.maxStreams=Math.max(1,t),this.cycleMs=Math.max(1,e)}addStream(t){return this.streamIds.includes(t)||this.streamIds.length>=this.maxStreams?!1:(this.streamIds.push(t),!0)}removeStream(t){let e=this.streamIds.indexOf(t);return e===-1?!1:(this.streamIds.splice(e,1),this.currentIndex>=this.streamIds.length&&(this.currentIndex=0),!0)}nextStream(){if(this.streamIds.length===0)return null;let t=this.streamIds[this.currentIndex];return this.currentIndex=(this.currentIndex+1)%this.streamIds.length,t}getActiveStreams(){return[...this.streamIds]}get activeCount(){return this.streamIds.length}},g=class{config;predictor;router;lastPayloads=new Map;totalMessages=0;compressedMessages=0;totalOriginalBytes=0;totalCompressedBytes=0;constructor(t){this.config={...y,...t},this.predictor=new l(this.config.predictionWindowSize),this.router=new h(this.config.maxConcurrentStreams,this.config.oscillationFrequencyMs)}send(t,e,n,r){this.totalMessages++;let i=d(r);this.totalOriginalBytes+=i;let c=!1,o=r,a=i;if(typeof r=="object"&&r!==null&&!Array.isArray(r)){let m=this.predictor.predict(t);if(m){let u=w(m,r);u?1-d(u)/Math.max(i,1)>=this.config.compressionThreshold&&(o={__delta:!0,__changes:u},a=d(o),c=!0,this.compressedMessages++):(o={__delta:!0,__changes:{}},a=d(o),c=!0,this.compressedMessages++)}}return this.totalCompressedBytes+=a,this.predictor.record(t,r),this.lastPayloads.set(t,r),{streamId:t,senderId:e,receiverId:n,payload:o,compressed:c,originalSize:i,compressedSize:a,timestamp:Date.now()}}receive(t){if(!t.compressed||typeof t.payload!="object"||t.payload===null)return this.lastPayloads.set(t.streamId,t.payload),this.predictor.record(t.streamId,t.payload),t.payload;let e=t.payload;if(!e.__delta)return this.lastPayloads.set(t.streamId,t.payload),this.predictor.record(t.streamId,t.payload),t.payload;let n=this.predictor.predict(t.streamId),r=e.__changes??{};if(!n)return r;let i=v(n,r);return this.predictor.record(t.streamId,i),this.lastPayloads.set(t.streamId,i),i}getStats(){let t=this.totalOriginalBytes-this.totalCompressedBytes;return{totalMessages:this.totalMessages,compressedMessages:this.compressedMessages,bandwidthSavedBytes:Math.max(0,t),bandwidthReductionPercent:this.totalOriginalBytes>0?Math.max(0,t)/this.totalOriginalBytes*100:0,activeStreams:this.router.activeCount}}addStream(t){this.router.addStream(t)}removeStream(t){this.router.removeStream(t),this.predictor.removeStream(t),this.lastPayloads.delete(t)}};function M(s){return S()?new g(s):null}function S(){return p().useCognitiveRouting}export{M as a,S as b};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.1");process.exit(0)}
|
|
2
|
+
import{h as s,k as o,o as m}from"./chunk-24E47G3D.js";import{a as u}from"./chunk-U5JQGRHZ.js";import{c as r}from"./chunk-A57BEPL7.js";import{a,e as c}from"./chunk-SGRN6JFB.js";m();c();u();var l=r.create("hybrid-backend"),d=class{unifiedMemory=null;config;cleanupInterval;cleanupCount=0;initialized=!1;constructor(e){this.config={sqlite:{path:e?.sqlite?.path??".agentic-qe/memory.db",walMode:e?.sqlite?.walMode??!0,poolSize:e?.sqlite?.poolSize??5,busyTimeout:e?.sqlite?.busyTimeout??a.BUSY_TIMEOUT_MS,...e?.sqlite},agentdb:{path:e?.agentdb?.path??".agentic-qe/memory.db",...e?.agentdb},enableFallback:e?.enableFallback??!0,defaultNamespace:e?.defaultNamespace??"default",cleanupInterval:e?.cleanupInterval??a.CLEANUP_INTERVAL_MS}}async initialize(){if(this.initialized)return;let e={dbPath:this.config.sqlite.path??s.dbPath,walMode:this.config.sqlite.walMode??!0,busyTimeout:this.config.sqlite.busyTimeout??a.BUSY_TIMEOUT_MS};this.unifiedMemory=o(e),await this.unifiedMemory.initialize(),this.cleanupInterval=setInterval(()=>this.cleanup(),this.config.cleanupInterval),this.cleanupInterval.unref&&this.cleanupInterval.unref(),this.initialized=!0,console.log(`[HybridBackend] Initialized with unified memory: ${this.unifiedMemory.getDbPath()}`)}async dispose(){this.cleanupInterval&&clearInterval(this.cleanupInterval),this.initialized=!1}async set(e,i,t){this.ensureInitialized();let n=t?.namespace??this.config.defaultNamespace;await this.unifiedMemory.kvSet(e,i,n,t?.ttl)}async get(e){return this.ensureInitialized(),this.unifiedMemory.kvGet(e,this.config.defaultNamespace)}async delete(e){this.ensureInitialized();let i=await this.unifiedMemory.kvDelete(e,this.config.defaultNamespace),t=await this.unifiedMemory.vectorDelete(e);return i||t}async has(e){return this.ensureInitialized(),this.unifiedMemory.kvExists(e,this.config.defaultNamespace)}async search(e,i=100){return this.ensureInitialized(),this.unifiedMemory.kvSearch(e,this.config.defaultNamespace,i)}async vectorSearch(e,i){return this.ensureInitialized(),(await this.unifiedMemory.vectorSearch(e,i)).map(n=>({key:n.id,score:n.score,metadata:n.metadata}))}async storeVector(e,i,t){this.ensureInitialized(),await this.unifiedMemory.vectorStore(e,i,this.config.defaultNamespace,t)}getHealth(){return{sqlite:this.unifiedMemory?.isInitialized()?"healthy":"unavailable",sqlitePersistent:!0,agentdb:this.unifiedMemory?.isInitialized()?"healthy":"unavailable",fallback:"inactive"}}isPersistent(){return this.unifiedMemory?.isInitialized()??!1}getConfig(){return{...this.config}}async setWithBackend(e,i,t,n){await this.set(e,i,n)}async getVectorStats(){if(!this.unifiedMemory?.isInitialized())return null;let e=await this.unifiedMemory.vectorCount(),i=this.unifiedMemory.getStats();return{vectorCount:e,indexSize:i.vectorIndexSize}}getUnifiedMemory(){return this.unifiedMemory}async count(e){return this.ensureInitialized(),this.unifiedMemory.getDatabase().prepare(`
|
|
3
|
+
SELECT COUNT(*) as count FROM kv_store
|
|
4
|
+
WHERE namespace LIKE ?
|
|
5
|
+
AND (expires_at IS NULL OR expires_at > ?)
|
|
6
|
+
`).get(`${e}%`,Date.now()).count}async hasCodeIntelligenceIndex(){return this.ensureInitialized(),this.unifiedMemory.getDatabase().prepare(`
|
|
7
|
+
SELECT 1 FROM kv_store
|
|
8
|
+
WHERE namespace = 'code-intelligence:kg'
|
|
9
|
+
AND (expires_at IS NULL OR expires_at > ?)
|
|
10
|
+
LIMIT 1
|
|
11
|
+
`).get(Date.now())!==void 0}ensureInitialized(){if(!this.initialized||!this.unifiedMemory)throw new Error("HybridMemoryBackend not initialized. Call initialize() first.")}async cleanup(){if(this.unifiedMemory?.isInitialized())try{await this.unifiedMemory.kvCleanupExpired();let e=this.unifiedMemory.getDatabase();try{let i=e.prepare("DELETE FROM kv_store WHERE expires_at IS NOT NULL AND expires_at < ?").run(Date.now());i.changes>0&&console.log(`[HybridBackend] Expired ${i.changes} kv_store entries`)}catch(i){l.debug("TTL expiration cleanup failed",{error:i instanceof Error?i.message:String(i)})}if(this.cleanupCount++,this.cleanupCount%10===0)try{if(e.prepare("SELECT COUNT(*) as cnt FROM kv_store").get().cnt>5e3){let t=e.prepare(`
|
|
12
|
+
DELETE FROM kv_store WHERE rowid NOT IN (
|
|
13
|
+
SELECT rowid FROM kv_store ORDER BY rowid DESC LIMIT 5000
|
|
14
|
+
)
|
|
15
|
+
`).run();t.changes>0&&console.log(`[HybridBackend] kv_store retention: pruned ${t.changes} rows (kept 5000)`)}}catch(i){l.debug("KV store retention pruning failed",{error:i instanceof Error?i.message:String(i)})}}catch(e){console.warn("[HybridBackend] Cleanup failed:",e)}}};export{d as a};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.1");process.exit(0)}
|
|
2
|
+
var l=class{approxMinCut(e){let t=Date.now();if(e.isEmpty())return this.emptyResult(t,"weighted-degree");let r=e.getVertexIds(),n=1/0,i=null;for(let o of r){let c=e.weightedDegree(o);c<n&&(n=c,i=o)}if(i===null||r.length===1)return this.emptyResult(t,"weighted-degree");let a=e.getEdgesForVertex(i);return{value:n,sourceSide:[i],targetSide:r.filter(o=>o!==i),cutEdges:a,calculatedAt:new Date,algorithm:"weighted-degree",durationMs:Date.now()-t}}findWeakVertices(e,t){if(e.isEmpty())return[];let r=e.getVertices(),n=[],i=new Map,a=0;for(let g of r){let h=e.weightedDegree(g.id);i.set(g.id,h),a+=h}let o=a/r.length,c=0;for(let g of i.values())c+=(g-o)**2;let s=Math.sqrt(c/r.length),d=1/0;for(let g of i.values())g<d&&(d=g);let u=t??o-s;for(let g of r){let h=i.get(g.id);if(h<=u){let w=this.calculateRiskScore(h,o,s,d),y=this.determineWeakReason(g,h,o,e),v=this.generateStrengtheningActions(g,e,h);n.push({vertexId:g.id,vertex:g,weightedDegree:h,riskScore:w,reason:y,suggestions:v})}}return n.sort((g,h)=>h.riskScore-g.riskScore),n}getMinCutValue(e){if(e.isEmpty())return 0;let t=1/0;for(let r of e.getVertexIds()){let n=e.weightedDegree(r);n<t&&(t=n)}return t===1/0?0:t}isConnectivityCritical(e,t){return this.getMinCutValue(e)<t}getMinDegreeVertex(e){if(e.isEmpty())return null;let t=1/0,r=null;for(let n of e.getVertexIds()){let i=e.weightedDegree(n);i<t&&(t=i,r=n)}return r?{vertexId:r,degree:t}:null}getLocalMinCut(e,t){return e.hasVertex(t)?e.weightedDegree(t):0}findPartitioningPoints(e){if(e.isEmpty()||e.vertexCount<2)return[];let t=this.findArticulationPoints(e),r=[];for(let n of e.getVertices()){let i=this.getLocalMinCut(e,n.id);r.push({vertexId:n.id,localMinCut:i,wouldDisconnect:t.has(n.id)&&e.vertexCount>2})}return r.sort((n,i)=>n.localMinCut-i.localMinCut),r}findArticulationPoints(e){let t=new Map,r=new Map,n=new Map,i=new Set,a=0,o=e.getVertexIds();for(let s of o)t.set(s,-1),r.set(s,-1),n.set(s,null);let c=s=>{let d=0;t.set(s,a),r.set(s,a),a++;for(let u of e.neighborIds(s))t.get(u)===-1?(d++,n.set(u,s),c(u),r.set(s,Math.min(r.get(s),r.get(u))),n.get(s)===null&&d>1&&i.add(s),n.get(s)!==null&&r.get(u)>=t.get(s)&&i.add(s)):u!==n.get(s)&&r.set(s,Math.min(r.get(s),t.get(u)))};for(let s of o)t.get(s)===-1&&c(s);return i}suggestEdgeAdditions(e,t){let r=this.findWeakVertices(e),n=[],i=0,a=e.getVertices().map(o=>({vertex:o,degree:e.weightedDegree(o.id)})).sort((o,c)=>c.degree-o.degree);for(let o of r){if(i>=t)break;let c=new Set(e.neighborIds(o.vertexId));for(let{vertex:s}of a){if(s.id===o.vertexId||c.has(s.id))continue;let d={source:o.vertexId,target:s.id,weight:1,type:"coordination",bidirectional:!0};n.push(d),i+=1;break}}return n}emptyResult(e,t){return{value:0,sourceSide:[],targetSide:[],cutEdges:[],calculatedAt:new Date,algorithm:t,durationMs:Date.now()-e}}calculateRiskScore(e,t,r,n){if(r===0)return .5;let i=(t-e)/r,a=1/(1+Math.exp(-i)),o=n>0?n/e:1;return Math.min(1,a*o)}determineWeakReason(e,t,r,n){return t===0?"Isolated vertex with no connections":n.degree(e.id)===1?"Single connection point (leaf node)":t<r*.5?`Low connectivity (${(t/r*100).toFixed(0)}% of average)`:"Below average connectivity threshold"}generateStrengtheningActions(e,t,r){let n=[],i=new Set(t.neighborIds(e.id)),a=t.getStats().averageDegree,o=Math.max(a,3),c=Math.ceil(o-r),s=t.getVertices().filter(d=>d.id!==e.id&&!i.has(d.id)).sort((d,u)=>t.weightedDegree(u.id)-t.weightedDegree(d.id)).slice(0,c);for(let d of s)n.push({type:"add_edge",targetVertex:d.id,priority:"high",estimatedImprovement:1});return e.type==="agent"&&e.domain&&r<1&&n.push({type:"spawn_agent",domain:e.domain,priority:"critical",estimatedImprovement:2}),i.size>0&&i.size<3&&n.push({type:"increase_weight",weightDelta:.5,priority:"medium",estimatedImprovement:.5*i.size}),n}};function p(){return new l}var f=class m{vertices=new Map;edges=new Map;adjacencyList=new Map;totalWeight=0;addVertex(e){if(this.vertices.has(e.id)){this.vertices.set(e.id,e);return}this.vertices.set(e.id,e),this.adjacencyList.set(e.id,[])}removeVertex(e){if(!this.vertices.has(e))return!1;let t=this.adjacencyList.get(e)||[];for(let r of t)this.removeEdge(e,r.neighborId);for(let[,r]of this.adjacencyList){let n=r.findIndex(i=>i.neighborId===e);n!==-1&&(this.totalWeight-=r[n].weight,r.splice(n,1))}return this.vertices.delete(e),this.adjacencyList.delete(e),!0}getVertex(e){return this.vertices.get(e)}hasVertex(e){return this.vertices.has(e)}getVertices(){return Array.from(this.vertices.values())}getVertexIds(){return Array.from(this.vertices.keys())}getVerticesByDomain(e){return this.getVertices().filter(t=>t.domain===e)}getVerticesByType(e){return this.getVertices().filter(t=>t.type===e)}addEdge(e){if(!this.vertices.has(e.source))throw new Error(`Source vertex ${e.source} does not exist`);if(!this.vertices.has(e.target))throw new Error(`Target vertex ${e.target} does not exist`);let t=this.edgeKey(e.source,e.target);if(this.edges.has(t)){let r=this.edges.get(t);this.totalWeight-=r.weight,this.removeFromAdjacency(e.source,e.target),r.bidirectional&&this.removeFromAdjacency(e.target,e.source)}this.edges.set(t,e),this.totalWeight+=e.weight,this.addToAdjacency(e.source,e.target,e.weight,e),e.bidirectional&&this.addToAdjacency(e.target,e.source,e.weight,e)}removeEdge(e,t){let r=this.edgeKey(e,t),n=this.edges.get(r);return n?(this.totalWeight-=n.weight,this.edges.delete(r),this.removeFromAdjacency(e,t),n.bidirectional&&this.removeFromAdjacency(t,e),!0):!1}getEdge(e,t){return this.edges.get(this.edgeKey(e,t))}hasEdge(e,t){return this.edges.has(this.edgeKey(e,t))}getEdges(){return Array.from(this.edges.values())}getEdgesForVertex(e){return(this.adjacencyList.get(e)||[]).map(r=>r.edge)}degree(e){return this.adjacencyList.get(e)?.length||0}weightedDegree(e){let t=this.adjacencyList.get(e);return t?t.reduce((r,n)=>r+n.weight,0):0}neighbors(e){return(this.adjacencyList.get(e)||[]).map(r=>({vertex:this.vertices.get(r.neighborId),weight:r.weight})).filter(r=>r.vertex!==void 0)}neighborIds(e){return(this.adjacencyList.get(e)||[]).map(r=>r.neighborId)}getStats(){let e=this.vertices.size,t=this.edges.size,r=0;for(let[,s]of this.adjacencyList)r+=s.length;let n=e>0?r/e:0,i=e>1?e*(e-1)/2:0,a=i>0?t/i:0,o=this.countConnectedComponents(),c=o===1&&e>0;return{vertexCount:e,edgeCount:t,totalWeight:this.totalWeight,averageDegree:n,density:a,isConnected:c,componentCount:o}}countConnectedComponents(){let e=new Set,t=0;for(let r of this.vertices.keys())e.has(r)||(this.dfs(r,e),t++);return t}dfs(e,t){t.add(e);let r=this.adjacencyList.get(e)||[];for(let n of r)t.has(n.neighborId)||this.dfs(n.neighborId,t)}isConnected(){if(this.vertices.size===0||this.vertices.size===1)return!0;let e=new Set,t=this.vertices.keys().next().value;return t===void 0?!0:(this.dfs(t,e),e.size===this.vertices.size)}getConnectedComponent(e){if(!this.vertices.has(e))return[];let t=new Set;return this.dfs(e,t),Array.from(t)}snapshot(){return{timestamp:new Date,vertices:this.getVertices(),edges:this.getEdges(),stats:this.getStats()}}clone(){let e=new m;for(let t of this.vertices.values())e.addVertex({...t});for(let t of this.edges.values())e.addEdge({...t});return e}static fromSnapshot(e){let t=new m;for(let r of e.vertices)t.addVertex(r);for(let r of e.edges)t.addEdge(r);return t}clear(){this.vertices.clear(),this.edges.clear(),this.adjacencyList.clear(),this.totalWeight=0}get vertexCount(){return this.vertices.size}get edgeCount(){return this.edges.size}isEmpty(){return this.vertices.size===0}edgeKey(e,t){return e<t?`${e}:${t}`:`${t}:${e}`}addToAdjacency(e,t,r,n){let i=this.adjacencyList.get(e);i&&(i.find(o=>o.neighborId===t)||i.push({neighborId:t,weight:r,edge:n}))}removeFromAdjacency(e,t){let r=this.adjacencyList.get(e);if(r){let n=r.findIndex(i=>i.neighborId===t);n!==-1&&r.splice(n,1)}}};function x(){return new f}export{l as a,p as b,f as c,x as d};
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.1");process.exit(0)}
|
|
2
|
+
import{a as _}from"./chunk-RXVYOXDB.js";import{e as E}from"./chunk-DC3HPOOJ.js";import{a as T}from"./chunk-U5JQGRHZ.js";import{c as h}from"./chunk-A57BEPL7.js";import{b as p,d as b}from"./chunk-JSOBRKMA.js";import{S,j as g}from"./chunk-MZ54VM6A.js";b();T();S();var o=h.create("pattern-lifecycle"),A={promotionRewardThreshold:.7,promotionMinOccurrences:E,promotionMinSuccessRate:.7,deprecationFailureThreshold:3,staleDaysThreshold:30,confidenceDecayRate:.01,minActiveConfidence:.3,maxAgeForActivePatterns:90,promotionActivityWindowDays:30,asymmetricLearning:{}},f=class{constructor(e,t={}){this.db=e;this.config={...A,...t},this.asymmetricEngine=new _(this.config.asymmetricLearning),this.ensureSchema()}config;asymmetricEngine;_witnessChain=null;set witnessChain(e){this._witnessChain=e}_compressionService=null;set compressionService(e){this._compressionService=e}ensureSchema(){try{this.db.prepare(`
|
|
3
|
+
SELECT deprecated_at FROM qe_patterns LIMIT 1
|
|
4
|
+
`).get()}catch(e){o.debug("Adding missing deprecated_at column",{error:e instanceof Error?e.message:String(e)}),this.db.exec(`
|
|
5
|
+
ALTER TABLE qe_patterns ADD COLUMN deprecated_at TEXT DEFAULT NULL
|
|
6
|
+
`),console.log("[PatternLifecycle] Added deprecated_at column to qe_patterns")}try{this.db.prepare(`
|
|
7
|
+
SELECT consecutive_failures FROM qe_patterns LIMIT 1
|
|
8
|
+
`).get()}catch(e){o.debug("Adding missing consecutive_failures column",{error:e instanceof Error?e.message:String(e)}),this.db.exec(`
|
|
9
|
+
ALTER TABLE qe_patterns ADD COLUMN consecutive_failures INTEGER DEFAULT 0
|
|
10
|
+
`),console.log("[PatternLifecycle] Added consecutive_failures column to qe_patterns")}try{this.db.prepare(`
|
|
11
|
+
SELECT promotion_date FROM qe_patterns LIMIT 1
|
|
12
|
+
`).get()}catch(e){o.debug("Adding missing promotion_date column",{error:e instanceof Error?e.message:String(e)}),this.db.exec(`
|
|
13
|
+
ALTER TABLE qe_patterns ADD COLUMN promotion_date TEXT DEFAULT NULL
|
|
14
|
+
`),console.log("[PatternLifecycle] Added promotion_date column to qe_patterns")}}getRecentExperiences(e={}){let t=e.minReward??this.config.promotionRewardThreshold,n=e.limit??100,r=e.sinceDays??7;if(!this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='captured_experiences'").get())return o.debug("captured_experiences table not found"),[];let a=new Date(Date.now()-r*864e5).toISOString().replace("T"," ").slice(0,19);return this.db.prepare(`
|
|
15
|
+
SELECT
|
|
16
|
+
domain as task_type,
|
|
17
|
+
COUNT(*) as count,
|
|
18
|
+
AVG(quality) as avg_reward,
|
|
19
|
+
MAX(quality) as max_reward,
|
|
20
|
+
MIN(quality) as min_reward,
|
|
21
|
+
SUM(CASE WHEN quality >= ? THEN 1 ELSE 0 END) as success_count,
|
|
22
|
+
GROUP_CONCAT(DISTINCT agent) as actions,
|
|
23
|
+
MAX(started_at) as latest_at
|
|
24
|
+
FROM captured_experiences
|
|
25
|
+
WHERE started_at >= ?
|
|
26
|
+
AND quality >= ?
|
|
27
|
+
AND agent != 'cli-hook'
|
|
28
|
+
GROUP BY domain
|
|
29
|
+
HAVING COUNT(*) >= ?
|
|
30
|
+
ORDER BY avg_reward DESC
|
|
31
|
+
LIMIT ?
|
|
32
|
+
`).all(t,a,t*.5,this.config.promotionMinOccurrences,n).map(i=>({taskType:i.task_type,domain:this.taskTypeToQEDomain(i.task_type),count:i.count,avgReward:i.avg_reward,maxReward:i.max_reward,minReward:i.min_reward,actions:i.actions?i.actions.split(",").filter(Boolean):[],successCount:i.success_count,latestAt:new Date(i.latest_at)}))}taskTypeToQEDomain(e){let t={generate:"test-generation","test-generation":"test-generation",test:"test-generation",analyze:"coverage-analysis",coverage:"coverage-analysis","coverage-analysis":"coverage-analysis",run:"test-execution",execute:"test-execution","test-execution":"test-execution",report:"quality-assessment",quality:"quality-assessment",assessment:"quality-assessment",security:"security-compliance",sast:"security-compliance",audit:"security-compliance",defect:"defect-intelligence",predict:"defect-intelligence",bug:"defect-intelligence",requirements:"requirements-validation",validation:"requirements-validation",code:"code-intelligence",complexity:"code-intelligence",contract:"contract-testing",api:"contract-testing",visual:"visual-accessibility",a11y:"visual-accessibility",accessibility:"visual-accessibility",chaos:"chaos-resilience",resilience:"chaos-resilience",flaky:"chaos-resilience",learning:"learning-optimization",optimize:"learning-optimization"},n=e.toLowerCase();for(let[r,s]of Object.entries(t))if(n.includes(r))return s;return null}taskTypeToPatternType(e){let t={generate:"test-template",test:"test-template",coverage:"coverage-strategy",analyze:"coverage-strategy",mock:"mock-pattern",stub:"mock-pattern",assert:"assertion-pattern",expect:"assertion-pattern",security:"assertion-pattern",contract:"api-contract",api:"api-contract",visual:"visual-baseline",screenshot:"visual-baseline",a11y:"a11y-check",accessibility:"a11y-check",perf:"perf-benchmark",load:"perf-benchmark",stress:"perf-benchmark",flaky:"flaky-fix",retry:"flaky-fix",refactor:"refactor-safe",error:"error-handling",exception:"error-handling"},n=e.toLowerCase();for(let[r,s]of Object.entries(t))if(n.includes(r))return s;return"test-template"}findPatternCandidates(e){let t=[];for(let n of e){let r=n.avgReward>=this.config.promotionRewardThreshold,s=n.count>=this.config.promotionMinOccurrences,a=n.successCount/n.count,c=a>=this.config.promotionMinSuccessRate;if(r&&s&&c){let i=n.domain||"code-intelligence",d=this.taskTypeToPatternType(n.taskType);if(this.findExistingPattern(n.taskType,i))continue;t.push({name:`${n.taskType}-success-pattern`,domain:i,patternType:d,confidence:Math.min(.95,n.avgReward*.9),sourceExperiences:n.count,avgReward:n.avgReward,successRate:a,actions:n.actions.slice(0,5),templateContent:this.generateTemplateContent(n)})}}return t}findExistingPattern(e,t){let n=this.db.prepare(`
|
|
33
|
+
SELECT * FROM qe_patterns
|
|
34
|
+
WHERE name LIKE ? AND qe_domain = ? AND deprecated_at IS NULL
|
|
35
|
+
LIMIT 1
|
|
36
|
+
`).get(`%${e}%`,t);return n?this.rowToPattern(n):null}generateTemplateContent(e){let t=e.actions.map((n,r)=>`${r+1}. ${n}`).join(`
|
|
37
|
+
`);return`Task Type: ${e.taskType}
|
|
38
|
+
Domain: ${e.domain||"general"}
|
|
39
|
+
Average Reward: ${e.avgReward.toFixed(3)}
|
|
40
|
+
Success Rate: ${(e.successCount/e.count*100).toFixed(1)}%
|
|
41
|
+
|
|
42
|
+
Typical Actions:
|
|
43
|
+
${t||"N/A"}
|
|
44
|
+
|
|
45
|
+
Pattern extracted from ${e.count} successful experiences.`}checkPromotion(e){let t=this.getPattern(e);if(!t)return{shouldPromote:!1,meetsRewardThreshold:!1,meetsOccurrenceThreshold:!1,meetsSuccessRateThreshold:!1,meetsActivityWindow:!1,currentReward:0,currentOccurrences:0,currentSuccessRate:0};let n=t.qualityScore,r=n>=this.config.promotionRewardThreshold,s=t.usageCount>=this.config.promotionMinOccurrences,a=t.successRate>=this.config.promotionMinSuccessRate,c=this.config.promotionActivityWindowDays*24*60*60*1e3,i=t.lastUsedAt?.getTime()??t.createdAt.getTime(),d=Date.now()-i<c;return{shouldPromote:t.tier==="short-term"&&r&&s&&a&&d,meetsRewardThreshold:r,meetsOccurrenceThreshold:s,meetsSuccessRateThreshold:a,meetsActivityWindow:d,currentReward:n,currentOccurrences:t.usageCount,currentSuccessRate:t.successRate}}promotePattern(e){return this.checkPromotion(e).shouldPromote?(this.db.prepare(`
|
|
46
|
+
UPDATE qe_patterns
|
|
47
|
+
SET tier = 'long-term',
|
|
48
|
+
promotion_date = datetime('now'),
|
|
49
|
+
confidence = MIN(1.0, confidence + 0.1),
|
|
50
|
+
updated_at = datetime('now')
|
|
51
|
+
WHERE id = ?
|
|
52
|
+
`).run(e),console.log(`[PatternLifecycle] Promoted pattern ${e} to long-term`),!0):!1}promoteEligiblePatterns(){let e=this.db.prepare(`
|
|
53
|
+
SELECT id FROM qe_patterns
|
|
54
|
+
WHERE tier = 'short-term' AND deprecated_at IS NULL
|
|
55
|
+
`).all(),t=0;for(let{id:n}of e)this.promotePattern(n)&&t++;return{promoted:t,checked:e.length}}runPromotionSweep(){return this.promoteEligiblePatterns()}checkDeprecation(e){let t=this.getPattern(e);if(!t)return{shouldDeprecate:!1,reason:null};if(t.deprecated_at)return{shouldDeprecate:!1,reason:null};let n=t.consecutive_failures||0;if(n>=this.config.deprecationFailureThreshold)return{shouldDeprecate:!0,reason:"failures",consecutiveFailures:n};let r=t.lastUsedAt instanceof Date?t.lastUsedAt.getTime():new Date(t.lastUsedAt).getTime(),s=(Date.now()-r)/(1e3*60*60*24);if(s>=this.config.staleDaysThreshold)return{shouldDeprecate:!0,reason:"stale",daysSinceLastUse:s};if(t.confidence<this.config.minActiveConfidence)return{shouldDeprecate:!0,reason:"low_confidence",currentConfidence:t.confidence};let a=t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime(),c=(Date.now()-a)/(1e3*60*60*24);return c>=this.config.maxAgeForActivePatterns&&t.usageCount<5?{shouldDeprecate:!0,reason:"age",ageInDays:c}:{shouldDeprecate:!1,reason:null}}deprecatePattern(e,t){let n=this.checkDeprecation(e);if(!n.shouldDeprecate&&!t)return!1;let r=t||n.reason||"manual";this.db.prepare(`
|
|
56
|
+
UPDATE qe_patterns
|
|
57
|
+
SET deprecated_at = datetime('now'),
|
|
58
|
+
updated_at = datetime('now')
|
|
59
|
+
WHERE id = ?
|
|
60
|
+
`).run(e);let s=this.getPattern(e);if(s){let a={deprecation_reason:r,deprecated_at:new Date().toISOString(),final_confidence:s.confidence,final_success_rate:s.successRate,total_usage:s.usageCount};this.db.prepare(`
|
|
61
|
+
UPDATE qe_patterns
|
|
62
|
+
SET context_json = json_patch(COALESCE(context_json, '{}'), ?)
|
|
63
|
+
WHERE id = ?
|
|
64
|
+
`).run(JSON.stringify({deprecation_metadata:a}),e)}return console.log(`[PatternLifecycle] Deprecated pattern ${e}: ${r}`),!0}deprecateStalePatterns(){let e=this.db.prepare(`
|
|
65
|
+
SELECT id FROM qe_patterns
|
|
66
|
+
WHERE deprecated_at IS NULL
|
|
67
|
+
`).all(),t=0;for(let{id:n}of e){let r=this.checkDeprecation(n);r.shouldDeprecate&&(this.deprecatePattern(n,r.reason||void 0),t++)}return{deprecated:t,checked:e.length}}applyConfidenceDecay(e=1){let t=1-this.config.confidenceDecayRate*e,n=Date.now()-e*24*60*60*1e3,r=this.db.prepare(`
|
|
68
|
+
UPDATE qe_patterns
|
|
69
|
+
SET confidence = MAX(?, confidence * ?),
|
|
70
|
+
updated_at = datetime('now')
|
|
71
|
+
WHERE deprecated_at IS NULL
|
|
72
|
+
AND (last_used_at IS NULL OR datetime(last_used_at) < datetime(?, 'unixepoch'))
|
|
73
|
+
`).run(this.config.minActiveConfidence,t,n/1e3);return{updated:r.changes,decayed:r.changes}}recordUsage(e,t){t?this.db.prepare(`
|
|
74
|
+
UPDATE qe_patterns
|
|
75
|
+
SET usage_count = usage_count + 1,
|
|
76
|
+
successful_uses = successful_uses + 1,
|
|
77
|
+
consecutive_failures = 0,
|
|
78
|
+
confidence = MIN(1.0, confidence + 0.02),
|
|
79
|
+
success_rate = CAST(successful_uses + 1 AS REAL) / CAST(usage_count + 1 AS REAL),
|
|
80
|
+
last_used_at = datetime('now'),
|
|
81
|
+
updated_at = datetime('now')
|
|
82
|
+
WHERE id = ?
|
|
83
|
+
`).run(e):this.db.prepare(`
|
|
84
|
+
UPDATE qe_patterns
|
|
85
|
+
SET usage_count = usage_count + 1,
|
|
86
|
+
consecutive_failures = consecutive_failures + 1,
|
|
87
|
+
confidence = MAX(0.1, confidence - 0.05),
|
|
88
|
+
success_rate = CAST(successful_uses AS REAL) / CAST(usage_count + 1 AS REAL),
|
|
89
|
+
last_used_at = datetime('now'),
|
|
90
|
+
updated_at = datetime('now')
|
|
91
|
+
WHERE id = ?
|
|
92
|
+
`).run(e),this.db.prepare(`
|
|
93
|
+
UPDATE qe_patterns
|
|
94
|
+
SET quality_score = confidence * 0.3 + (MIN(usage_count, 100) / 100.0) * 0.2 + success_rate * 0.5
|
|
95
|
+
WHERE id = ?
|
|
96
|
+
`).run(e)}recordAsymmetricOutcome(e,t,n){let r=this.getPattern(e);if(!r)return;let s=r.confidence,a=this.asymmetricEngine.computeConfidenceUpdate(s,t?"success":"failure",n);this.db.prepare(`
|
|
97
|
+
UPDATE qe_patterns
|
|
98
|
+
SET confidence = ?,
|
|
99
|
+
usage_count = usage_count + 1,
|
|
100
|
+
successful_uses = CASE WHEN ? THEN successful_uses + 1 ELSE successful_uses END,
|
|
101
|
+
consecutive_failures = CASE WHEN ? THEN 0 ELSE consecutive_failures + 1 END,
|
|
102
|
+
success_rate = CAST(CASE WHEN ? THEN successful_uses + 1 ELSE successful_uses END AS REAL) / CAST(usage_count + 1 AS REAL),
|
|
103
|
+
last_used_at = datetime('now'),
|
|
104
|
+
updated_at = datetime('now')
|
|
105
|
+
WHERE id = ?
|
|
106
|
+
`).run(a,t?1:0,t?1:0,t?1:0,e),this.asymmetricEngine.shouldQuarantine(a,n).shouldQuarantine&&this.quarantinePattern(e)}quarantinePattern(e){if(this.db.prepare(`
|
|
107
|
+
UPDATE qe_patterns
|
|
108
|
+
SET deprecated_at = datetime('now'),
|
|
109
|
+
updated_at = datetime('now')
|
|
110
|
+
WHERE id = ? AND deprecated_at IS NULL
|
|
111
|
+
`).run(e).changes>0){console.log(`[PatternLifecycle] Quarantined pattern ${e} (asymmetric confidence drop)`);try{this._witnessChain?.append("PATTERN_QUARANTINE",{patternId:e},"pattern-lifecycle")}catch{}return!0}return!1}checkRehabilitation(e,t){return this.asymmetricEngine.checkRehabilitation(t).canRehabilitate}rehabilitatePattern(e){return this.db.prepare(`
|
|
112
|
+
UPDATE qe_patterns
|
|
113
|
+
SET deprecated_at = NULL,
|
|
114
|
+
consecutive_failures = 0,
|
|
115
|
+
confidence = 0.5,
|
|
116
|
+
updated_at = datetime('now')
|
|
117
|
+
WHERE id = ?
|
|
118
|
+
`).run(e).changes>0?(console.log(`[PatternLifecycle] Rehabilitated pattern ${e} (10+ consecutive successes)`),!0):!1}getAsymmetricEngine(){return this.asymmetricEngine}compressPatternEmbedding(e){if(!g()||!this._compressionService)return null;let t=this.getPattern(e);if(!t||!t.embedding||t.embedding.length===0)return null;let n=t.lastUsedAt??t.createdAt,r=this._compressionService.classifyTier(n),s=new Float32Array(t.embedding),a=this._compressionService.compress(s,r);return o.debug("Compressed pattern embedding",{patternId:e,tier:r,ratio:(a.originalByteSize/a.compressedByteSize).toFixed(1)}),a}decompressPatternEmbedding(e){return this._compressionService?this._compressionService.decompress(e):null}compressAllPatternEmbeddings(){if(!g()||!this._compressionService)return 0;let e=this.db.prepare(`
|
|
119
|
+
SELECT id FROM qe_patterns
|
|
120
|
+
WHERE deprecated_at IS NULL
|
|
121
|
+
`).all(),t=0;for(let{id:n}of e)this.compressPatternEmbedding(n)&&t++;return o.info("Bulk pattern embedding compression complete",{total:e.length,compressed:t}),t}getStats(){let e=this.db.prepare(`
|
|
122
|
+
SELECT
|
|
123
|
+
COUNT(*) as total,
|
|
124
|
+
SUM(CASE WHEN deprecated_at IS NULL THEN 1 ELSE 0 END) as active,
|
|
125
|
+
SUM(CASE WHEN deprecated_at IS NOT NULL THEN 1 ELSE 0 END) as deprecated,
|
|
126
|
+
SUM(CASE WHEN tier = 'long-term' AND deprecated_at IS NULL THEN 1 ELSE 0 END) as promoted,
|
|
127
|
+
SUM(CASE WHEN tier = 'short-term' AND deprecated_at IS NULL THEN 1 ELSE 0 END) as short_term,
|
|
128
|
+
SUM(CASE WHEN tier = 'long-term' THEN 1 ELSE 0 END) as long_term,
|
|
129
|
+
AVG(CASE WHEN deprecated_at IS NULL THEN confidence ELSE NULL END) as avg_confidence,
|
|
130
|
+
AVG(CASE WHEN deprecated_at IS NULL THEN success_rate ELSE NULL END) as avg_success_rate
|
|
131
|
+
FROM qe_patterns
|
|
132
|
+
`).get(),t=this.db.prepare(`
|
|
133
|
+
SELECT COUNT(*) as count
|
|
134
|
+
FROM qe_patterns
|
|
135
|
+
WHERE deprecated_at IS NULL
|
|
136
|
+
AND (
|
|
137
|
+
consecutive_failures >= ?
|
|
138
|
+
OR confidence < ?
|
|
139
|
+
OR (julianday('now') - julianday(COALESCE(last_used_at, created_at))) >= ?
|
|
140
|
+
)
|
|
141
|
+
`).get(this.config.deprecationFailureThreshold-1,this.config.minActiveConfidence+.1,this.config.staleDaysThreshold-7);return{totalPatterns:e.total||0,activePatterns:e.active||0,deprecatedPatterns:e.deprecated||0,promotedPatterns:e.promoted||0,shortTermPatterns:e.short_term||0,longTermPatterns:e.long_term||0,avgConfidence:e.avg_confidence||0,avgSuccessRate:e.avg_success_rate||0,patternsNearDeprecation:t.count||0}}getPattern(e){let t=this.db.prepare(`
|
|
142
|
+
SELECT * FROM qe_patterns WHERE id = ?
|
|
143
|
+
`).get(e);return t?this.rowToPattern(t):null}rowToPattern(e){return{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:p(e.template_json||"{}"),context:p(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,reusable:e.reusable===1,reuseCount:e.reuse_count||0,averageTokenSavings:e.average_token_savings||0}}};function w(m,e){return new f(m,e)}import*as u from"fs";import*as l from"path";var D={"pattern-learned":"\u{1F9E0}","pattern-promoted":"\u2B06\uFE0F","pattern-quarantined":"\u{1F512}","experience-captured":"\u{1F4F8}","search-performed":"\u{1F50D}","reward-assigned":"\u{1F3AF}"},y=class{config;buffer=[];flushTimer=null;constructor(e){this.config={logDir:e?.logDir??l.join(process.cwd(),".agentic-qe","logs"),enabled:e?.enabled??!0,maxEntriesPerDay:e?.maxEntriesPerDay??500}}log(e){this.config.enabled&&(this.buffer.push(e),this.buffer.length>=10&&this.flush())}flush(){if(this.buffer.length===0)return;let e=new Date().toISOString().split("T")[0],t=l.join(this.config.logDir,`${e}.md`);try{u.mkdirSync(this.config.logDir,{recursive:!0});let n=this.buffer.splice(0,this.buffer.length),r=[];u.existsSync(t)||(r.push(`# AQE Daily Log \u2014 ${e}
|
|
144
|
+
`),r.push("| Time | Event | Summary |"),r.push("|------|-------|---------|"));for(let s of n){let a=s.timestamp.toISOString().split("T")[1]?.slice(0,8)??"00:00:00",c=D[s.type]??"\u{1F4DD}",i=s.summary.replace(/\\/g,"\\\\").replace(/\|/g,"\\|").replace(/\n/g," ");r.push(`| ${a} | ${c} ${s.type} | ${i} |`)}u.appendFileSync(t,r.join(`
|
|
145
|
+
`)+`
|
|
146
|
+
`)}catch(n){console.debug("[DailyLog] Write failed:",n)}}getTodayLogPath(){let e=new Date().toISOString().split("T")[0];return l.join(this.config.logDir,`${e}.md`)}dispose(){this.flush(),this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null)}};export{w as a,y as b};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.1");process.exit(0)}
|
|
2
|
+
function M(u){let e=u|0;return()=>{e=e+1831565813|0;let n=Math.imul(e^e>>>15,1|e);return n=n+Math.imul(n^n>>>7,61|n)^n,((n^n>>>14)>>>0)/4294967296}}var A=2,y=10,x=200,p=1e-8,b=class{epsilon;seed;constructor(e){if(this.epsilon=e?.epsilon??.3,this.seed=e?.seed,this.epsilon<=0||this.epsilon>=1)throw new Error("SparsifierConfig.epsilon must be in (0, 1)")}sparsify(e){if(e.nodeCount<=0||e.edges.length===0)return{nodeCount:e.nodeCount,edges:[]};let n=this.seed!==void 0?M(this.seed):Math.random,t=this.approximateEffectiveResistances(e),i=e.nodeCount,r=e.edges.length,o=Math.max(1,Math.log(i)),m=this.epsilon*this.epsilon,l=Math.min(r,Math.max(i-1,A*(i-1)*(1-this.epsilon))),s=new Float64Array(r),c=0;for(let a=0;a<r;a++){let d=e.edges[a][2];s[a]=d*t[a],c+=s[a]}if(c<=0)return{nodeCount:e.nodeCount,edges:[]};let f=[];for(let a=0;a<r;a++){let[d,C,E]=e.edges[a],g=Math.min(1,s[a]/c*l);if(n()<g){let w=E/g;f.push([d,C,w])}}return{nodeCount:e.nodeCount,edges:f}}validateSpectral(e,n){let t=Math.min(y,Math.max(1,e.nodeCount-1)),i=this.computeLaplacian(e),r=this.computeLaplacian(n),o=this.computeTopEigenvalues(i,t),m=this.computeTopEigenvalues(r,t),l=[],s=!0,c=this.epsilon;for(let f=0;f<o.length;f++){if(o[f]<1e-10)continue;let a=m[f]/o[f];l.push(a),(a<1-c||a>1+c)&&(s=!1)}return{isValid:s,eigenvalueRatios:l,originalEdgeCount:e.edges.length,sparsifiedEdgeCount:n.edges.length,compressionRatio:e.edges.length>0?n.edges.length/e.edges.length:0}}computeLaplacian(e){let n=e.nodeCount,t=Array.from({length:n},()=>new Array(n).fill(0));for(let[i,r,o]of e.edges)i<0||i>=n||r<0||r>=n||(t[i][i]+=o,t[r][r]+=o,t[i][r]-=o,t[r][i]-=o);return t}computeTopEigenvalues(e,n){let t=e.length;if(t===0)return[];let i=[],r=[],o=e.map(m=>[...m]);for(let m=0;m<Math.min(n,t);m++){let l=this.powerIteration(o,t,r);if(l===null)break;i.push(l.eigenvalue),r.push(l.eigenvector),V(o,l.eigenvalue,l.eigenvector)}return i}approximateEffectiveResistances(e){let n=e.nodeCount,t=new Float64Array(n);for(let[r,o,m]of e.edges)r>=0&&r<n&&(t[r]+=m),o>=0&&o<n&&(t[o]+=m);let i=new Array(e.edges.length);for(let r=0;r<e.edges.length;r++){let[o,m]=e.edges[r],l=t[o]||1,s=t[m]||1;i[r]=1/l+1/s}return i}powerIteration(e,n,t){let i=0;for(let s=0;s<n;s++)for(let c=0;c<n;c++)i+=e[s][c]*e[s][c];if(i<p*p)return null;let r=t.length,o=new Array(n);for(let s=0;s<n;s++)o[s]=Math.sin((s+1)*(r+1)*1.618033988749895)+.1*(s-n/2);for(let s of t)h(o,s);if(R(o)<p)return null;let l=0;for(let s=0;s<x;s++){let c=L(e,o);for(let d of t)h(c,d);let f=S(c,o),a=v(c);if(a<p)return{eigenvalue:0,eigenvector:o};for(let d=0;d<n;d++)o[d]=c[d]/a;if(Math.abs(f-l)<p){l=f;break}l=f}return{eigenvalue:Math.abs(l),eigenvector:o}}};function L(u,e){let n=u.length,t=new Array(n).fill(0);for(let i=0;i<n;i++){let r=0;for(let o=0;o<n;o++)r+=u[i][o]*e[o];t[i]=r}return t}function v(u){let e=0;for(let n=0;n<u.length;n++)e+=u[n]*u[n];return Math.sqrt(e)}function R(u){let e=v(u);if(e>0)for(let n=0;n<u.length;n++)u[n]/=e;return e}function S(u,e){let n=0;for(let t=0;t<u.length;t++)n+=u[t]*e[t];return n}function h(u,e){let n=S(u,e);for(let t=0;t<u.length;t++)u[t]-=n*e[t]}function V(u,e,n){let t=n.length;for(let i=0;i<t;i++)for(let r=0;r<t;r++)u[i][r]-=e*n[i]*n[r]}export{b as a};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.1");process.exit(0)}
|
|
2
|
+
import{b as f,d as v}from"./chunk-JSOBRKMA.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,2 @@
|
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.1");process.exit(0)}
|
|
2
|
+
import{a as oe,b as ae}from"./chunk-35H73OPP.js";import{S as ie,i as j,p as q}from"./chunk-MZ54VM6A.js";import{c as g,e as $,g as W}from"./chunk-UZZCWWIG.js";var R,E=g(()=>{"use strict";R={dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"}});function se(){if(V)return k!==null;try{let o=(ae(),W(oe));if(k=o.differentiableSearch,P=o.init,P)try{P()}catch{}return V=!0,!0}catch{return V=!0,!1}}function B(o){let e=0;for(let t=0;t<o.length;t++)e+=o[t]*o[t];return Math.sqrt(e)}function U(o,e,t,r){let n=t*r;if(n===0)return 0;let a=0,i=Math.min(o.length,e.length);for(let s=0;s<i;s++)a+=o[s]*e[s];return a/n}function O(o,e){let t=0,r=Math.min(o.length,e.length);for(let n=0;n<r;n++){let a=o[n]-e[n];t+=a*a}return Math.sqrt(t)}function ce(o,e){if(o.length===e)return o;let t=new Float32Array(e);if(o.length>e){let r=o.length/e;for(let n=0;n<e;n++){let a=Math.floor(n*r),i=Math.floor((n+1)*r),s=0;for(let c=a;c<i;c++)s+=o[c];t[n]=s/(i-a)}}else for(let r=0;r<o.length;r++)t[r]=o[r];return t}var k,P,V,w,K=g(()=>{"use strict";E();k=null,P=null,V=!1;w=class{config;entries=[];idToIndex=new Map;hasRuvector=!1;loaded=!1;constructor(e){this.config={...R,...e}}ensureLoaded(){this.loaded||(this.hasRuvector=se(),this.loaded=!0)}normalizeVector(e){return e.length===this.config.dimensions?e:ce(e,this.config.dimensions)}add(e,t,r){this.ensureLoaded();let n=this.normalizeVector(t),a=B(n);if(this.idToIndex.has(e)){let s=this.idToIndex.get(e);this.entries[s]={id:e,vector:n,norm:a,metadata:r};return}let i=this.entries.length;this.entries.push({id:e,vector:n,norm:a,metadata:r}),this.idToIndex.set(e,i)}search(e,t){if(this.ensureLoaded(),this.entries.length===0)return[];let r=this.normalizeVector(e),n=B(r),a=Math.min(t,this.entries.length),i=this.entries.length>0?this.entries[0].vector.length:0,s=r.length===i;if(this.hasRuvector&&s&&k)try{let c=this.entries.map(l=>l.vector);return k(r,c,a,1).indices.map(l=>{let h=this.entries[l],u=this.config.metric==="cosine"?U(r,h.vector,n,h.norm):-O(r,h.vector);return{id:h.id,score:u,metadata:h.metadata}})}catch{}return this.bruteForcSearch(r,n,a)}bruteForcSearch(e,t,r){let n=[];for(let a of this.entries){let i;this.config.metric==="cosine"?i=U(e,a.vector,t,a.norm):i=-O(e,a.vector),n.push({id:a.id,score:i,metadata:a.metadata})}return n.sort((a,i)=>i.score-a.score),n.slice(0,r)}remove(e){let t=this.idToIndex.get(e);if(t===void 0)return!1;let r=this.entries.length-1;if(t!==r){let n=this.entries[r];this.entries[t]=n,this.idToIndex.set(n.id,t)}return this.entries.pop(),this.idToIndex.delete(e),!0}size(){return this.entries.length}dimensions(){return this.config.dimensions}recall(){return this.hasRuvector,1}isRuvectorAvailable(){return this.ensureLoaded(),this.hasRuvector}getConfig(){return{...this.config}}clear(){this.entries=[],this.idToIndex.clear()}}});import{createRequire as le}from"module";function ue(){if(J){if(A)return A;throw new p(Q??"Unknown load error")}J=!0;try{let o=he("@ruvector/router");if(!o.VectorDb||!o.DistanceMetric)throw new Error("@ruvector/router module missing VectorDb or DistanceMetric exports");return A=o,A}catch(o){let e=o instanceof Error?o.message:String(o);throw Q=e,new p(e)}}function _(o){let e=0;for(let t=0;t<o.length;t++)e+=o[t]*o[t];return Math.sqrt(e)}function X(o,e,t,r){let n=t*r;if(n===0)return 0;let a=0,i=Math.min(o.length,e.length);for(let s=0;s<i;s++)a+=o[s]*e[s];return a/n}function de(o,e){if(o.length===e)return o;let t=new Float32Array(e);if(o.length>e){let r=o.length/e;for(let n=0;n<e;n++){let a=Math.floor(n*r),i=Math.floor((n+1)*r),s=0;for(let c=a;c<i;c++)s+=o[c];t[n]=s/(i-a)}}else for(let r=0;r<o.length;r++)t[r]=o[r];return t}var he,p,A,J,Q,H,Y=g(()=>{"use strict";E();he=le(import.meta.url),p=class extends Error{constructor(e){super(`Native HNSW backend unavailable: ${e}`),this.name="NativeHnswUnavailableError"}},A=null,J=!1,Q=null;H=class{config;nativeDb=null;metadataStore=new Map;vectorStore=new Map;normStore=new Map;operationLock=Promise.resolve();highFallbackWarningEmitted=!1;_metrics={totalSearches:0,totalAdds:0,totalRemoves:0,avgSearchLatencyMs:0,maxSearchLatencyMs:0,lastSearchLatencyMs:0,fallbackSearchCount:0,bruteForceSearchCount:0,nativeSearchCount:0,fallbackRate:0,allSearchesBruteForce:!1};constructor(e){this.config={...R,...e};let t=ue(),r=this.config.metric==="cosine"?t.DistanceMetric.Cosine:t.DistanceMetric.Euclidean;try{this.nativeDb=new t.VectorDb({dimensions:this.config.dimensions,distanceMetric:r,hnswM:this.config.M,hnswEfConstruction:this.config.efConstruction,hnswEfSearch:this.config.efSearch})}catch(n){let a=n instanceof Error?n.message:String(n);throw new p(`VectorDb creation failed: ${a}`)}}add(e,t,r){let n=this.normalizeVector(t),a=_(n);if(this.vectorStore.has(e))try{this.nativeDb.delete(String(e))}catch{}this.nativeDb.insert(String(e),n),this.vectorStore.set(e,n),this.normStore.set(e,a),r&&this.metadataStore.set(e,r),this._metrics.totalAdds++}search(e,t){let r=performance.now();if(this.vectorStore.size===0)return[];let n=this.normalizeVector(e),a=_(n),i=Math.min(t,this.vectorStore.size),s;try{s=this.nativeDb.search(n,i).map(l=>{let h=Number(l.id),u=this.vectorStore.get(h),S=this.normStore.get(h)??0,b;return this.config.metric==="cosine"&&u?b=X(n,u,a,S):b=-l.score,{id:h,score:b,metadata:this.metadataStore.get(h)}}),s.sort((l,h)=>h.score-l.score),this._metrics.nativeSearchCount++}catch{this._metrics.fallbackSearchCount++,this._metrics.bruteForceSearchCount++,console.warn(`[NativeHNSW] FALLBACK: Using brute-force linear scan (@ruvector/router search failed). Index size: ${this.vectorStore.size}`),s=this.bruteForceSearch(n,a,i)}let c=performance.now()-r;return this.updateSearchMetrics(c),this._metrics.fallbackRate=this._metrics.fallbackSearchCount/this._metrics.totalSearches,this._metrics.allSearchesBruteForce=this._metrics.nativeSearchCount===0&&this._metrics.totalSearches>0,!this.highFallbackWarningEmitted&&this._metrics.fallbackRate>.5&&this._metrics.totalSearches>=10&&(this.highFallbackWarningEmitted=!0,console.error(`[NativeHNSW] WARNING: ${(this._metrics.fallbackRate*100).toFixed(0)}% of searches are using brute-force fallback. Native HNSW may not be functioning correctly. Consider rebuilding the index or checking @ruvector/router installation.`)),c>50&&console.warn(`[NativeHNSW] search took ${c.toFixed(1)}ms (k=${t}, results=${s.length})`),s}remove(e){if(!this.vectorStore.has(e))return!1;try{this.nativeDb.delete(String(e))}catch{}return this.vectorStore.delete(e),this.normStore.delete(e),this.metadataStore.delete(e),this._metrics.totalRemoves++,!0}size(){return this.vectorStore.size}dimensions(){return this.config.dimensions}recall(){let e=this.config.efSearch/this.config.M;return e>=10?.99:e>=5?.97:e>=3?.95:.9}getMetrics(){return{...this._metrics}}get lastSearchLatencyMs(){return this._metrics.lastSearchLatencyMs}getConfig(){return{...this.config}}clear(){for(let e of this.vectorStore.keys())try{this.nativeDb.delete(String(e))}catch{}this.vectorStore.clear(),this.normStore.clear(),this.metadataStore.clear()}isNativeAvailable(){return this.nativeDb!==null}normalizeVector(e){return e.length===this.config.dimensions?e:de(e,this.config.dimensions)}updateSearchMetrics(e){this._metrics.totalSearches++,this._metrics.lastSearchLatencyMs=e,e>this._metrics.maxSearchLatencyMs&&(this._metrics.maxSearchLatencyMs=e);let t=this._metrics.totalSearches;this._metrics.avgSearchLatencyMs=this._metrics.avgSearchLatencyMs*((t-1)/t)+e/t}bruteForceSearch(e,t,r){let n=[];for(let[a,i]of this.vectorStore){let s=this.normStore.get(a)??_(i),c=this.config.metric==="cosine"?X(e,i,t,s):-(function(){let d=0,l=Math.min(e.length,i.length);for(let h=0;h<l;h++){let u=e[h]-i[h];d+=u*u}return Math.sqrt(d)})();n.push({id:a,score:c,metadata:this.metadataStore.get(a)})}return n.sort((a,i)=>i.score-a.score),n.slice(0,r)}}});function Z(o,e){let t=Array.from({length:e},()=>new Float64Array(e));for(let r=0;r<e;r++){let n=o[r].length;t[r][r]=n;for(let a of o[r])t[r][a]=-1}return t}function F(o,e){let t=e.length,r=new Float64Array(t);for(let n=0;n<t;n++){let a=o[n].length;r[n]=a*e[n];for(let i of o[n])r[n]-=e[i]}return r}function x(o){let e=0;for(let t=0;t<o.length;t++)e+=o[t]*o[t];return Math.sqrt(e)}function I(o){let e=x(o);if(e>0)for(let t=0;t<o.length;t++)o[t]/=e}function v(o,e){let t=0;for(let r=0;r<o.length;r++)t+=o[r]*e[r];for(let r=0;r<o.length;r++)o[r]-=t*e[r]}function y(o,e,t=100,r=1e-6){if(e<=1)return 0;if(e===2)return o[0].includes(1)?2:0;let n=new Float64Array(e).fill(1/Math.sqrt(e)),a=new Float64Array(e);for(let l=0;l<e;l++)a[l]=Math.random()-.5;v(a,n),I(a);let i=0;for(let l=0;l<30;l++){let h=F(o,a);if(v(h,n),i=x(h),i>0)for(let u=0;u<e;u++)a[u]=h[u]/i}if(i<r)return 0;let s=new Float64Array(e);for(let l=0;l<e;l++)s[l]=Math.random()-.5;v(s,n),I(s);let c=0;for(let l=0;l<t;l++){let h=F(o,s),u=new Float64Array(e);for(let m=0;m<e;m++)u[m]=i*s[m]-h[m];v(u,n);let S=x(u);if(S<r)break;let b=S;for(let m=0;m<e;m++)s[m]=u[m]/S;if(Math.abs(b-c)<r)break;c=b}let d=i-c;return Math.max(0,d)}function C(o,e,t=100,r=1e-6){return y(o,e,t,r)}function N(o,e,t=50,r){if(e<=1)return 0;let n=r??y(o,e);if(n<1e-10)return 1/0;let i=2*Math.max(...o.map(d=>d.length),1),c=2*(Math.log(i/n)/(i-n));return Math.max(0,c)}function M(o,e,t){let r=1-Math.exp(-o/.05),n=1-Math.exp(-e/.5),a=t===1/0?0:1/(1+t/5),i=.4*r+.3*n+.3*a;return Math.max(0,Math.min(1,i))}var D=g(()=>{"use strict"});var re={};$(re,{ALERT_THRESHOLDS:()=>me,DEFAULT_HNSW_HEALTH_CONFIG:()=>ee,HnswHealthMonitor:()=>T,_resetNativeLoader:()=>pe,approximateFiedlerValue:()=>y,approximateSpectralGap:()=>C,buildAdjacencyFromIndex:()=>te,buildLaplacian:()=>Z,computeCoherenceScore:()=>M,createHnswHealthMonitor:()=>be,deflateVector:()=>v,estimateEffectiveResistance:()=>N,laplacianMultiply:()=>F,normalizeInPlace:()=>I,vectorNorm:()=>x});function fe(){return z?L:(z=!0,L=null,null)}function pe(){L=null,z=!1}function te(o,e=16,t){let r=o.size();if(r===0)return{adjacency:[],nodeCount:0,adjacencySource:"approximate"};let n=Array.from({length:r},()=>[]),a=Math.min(e,r-1);if(a===0)return{adjacency:n,nodeCount:r,adjacencySource:"approximate"};if(t&&t.size>0){let i=Array.from(t.keys()).slice(0,r),s=new Map;for(let c=0;c<i.length;c++)s.set(i[c],c);for(let c=0;c<i.length;c++){let d=t.get(i[c]);if(!d)continue;let l=o.search(d,a+1);for(let h of l){if(h.id===i[c])continue;let u=s.get(h.id);u!==void 0&&(n[c].includes(u)||n[c].push(u),n[u].includes(c)||n[u].push(c))}}return{adjacency:n,nodeCount:r,adjacencySource:"actual-search"}}console.warn("[HnswHealthMonitor] No stored vectors provided \u2014 using approximate circular adjacency. Pass stored vectors for accurate health metrics.");for(let i=0;i<r;i++)for(let s=0;s<a;s++){let c=(i+s+1)%r;n[i].includes(c)||n[i].push(c),n[c].includes(i)||n[c].push(i)}return{adjacency:n,nodeCount:r,adjacencySource:"approximate"}}function be(o){return new T(o)}var ee,me,L,z,T,ne=g(()=>{"use strict";D();D();ee={fiedlerThreshold:.01,spectralGapThreshold:.1,resistanceThreshold:10,coherenceThreshold:.3,maxPowerIterations:100,convergenceTolerance:1e-6,resistanceSampleSize:50,maxHistoryEntries:200,minIndexSize:3},me={FragileIndex:.01,PoorExpansion:.1,HighResistance:10,LowCoherence:.3},L=null,z=!1;T=class{config;alerts=[];history=[];lastReport=null;useNative=!1;nativeChecked=!1;constructor(e){this.config={...ee,...e}}checkHealth(e){let t=performance.now(),r=e.size();if(r<this.config.minIndexSize)return this.createSmallIndexReport(r,performance.now()-t);this.nativeChecked||(this.nativeChecked=!0,this.useNative=fe()!==null);let{adjacency:n,nodeCount:a,adjacencySource:i}=te(e),s=this.useNative?this.computeNativeMetrics(n):this.computeApproximateMetrics(n,a),c=this.generateAlerts(s);this.alerts.length=0,this.alerts.push(...c);let d=performance.now()-t,l={healthy:c.length===0,metrics:s,alerts:c,indexSize:r,usedNativeBackend:this.useNative,adjacencySource:i,checkDurationMs:d,checkedAt:new Date};return this.addHistoryPoint({coherenceScore:s.coherenceScore,fiedlerValue:s.fiedlerValue,indexSize:r,healthy:l.healthy,timestamp:l.checkedAt}),this.lastReport=l,l}getAlerts(){return[...this.alerts]}getMetricsHistory(e){let t=[...this.history];return e!==void 0&&e<t.length?t.slice(-e):t}isHealthy(){return this.lastReport===null?!0:this.lastReport.healthy}getLastReport(){return this.lastReport}clearHistory(){this.history.length=0,this.alerts.length=0,this.lastReport=null}computeNativeMetrics(e){let t=L,r=t.computeFiedlerValue(e),n=t.computeSpectralGap(e),a=t.computeEffectiveResistance(e),i=M(r,n,a);return{fiedlerValue:r,spectralGap:n,effectiveResistance:a,coherenceScore:i}}computeApproximateMetrics(e,t){let r=y(e,t,this.config.maxPowerIterations,this.config.convergenceTolerance),n=C(e,t,this.config.maxPowerIterations,this.config.convergenceTolerance),a=N(e,t,this.config.resistanceSampleSize,r),i=M(r,n,a);return{fiedlerValue:r,spectralGap:n,effectiveResistance:a,coherenceScore:i}}generateAlerts(e){let t=[],r=new Date;return e.fiedlerValue<this.config.fiedlerThreshold&&t.push({type:"FragileIndex",message:`Fiedler value ${e.fiedlerValue.toFixed(6)} is below threshold ${this.config.fiedlerThreshold}. The index graph has weak algebraic connectivity.`,value:e.fiedlerValue,threshold:this.config.fiedlerThreshold,timestamp:r}),e.spectralGap<this.config.spectralGapThreshold&&t.push({type:"PoorExpansion",message:`Spectral gap ${e.spectralGap.toFixed(6)} is below threshold ${this.config.spectralGapThreshold}. The index graph has poor expansion properties.`,value:e.spectralGap,threshold:this.config.spectralGapThreshold,timestamp:r}),e.effectiveResistance>this.config.resistanceThreshold&&t.push({type:"HighResistance",message:`Average effective resistance ${e.effectiveResistance.toFixed(4)} exceeds threshold ${this.config.resistanceThreshold}. Nodes are poorly connected.`,value:e.effectiveResistance,threshold:this.config.resistanceThreshold,timestamp:r}),e.coherenceScore<this.config.coherenceThreshold&&t.push({type:"LowCoherence",message:`Coherence score ${e.coherenceScore.toFixed(4)} is below threshold ${this.config.coherenceThreshold}. Overall index health is degraded.`,value:e.coherenceScore,threshold:this.config.coherenceThreshold,timestamp:r}),t}createSmallIndexReport(e,t){let r={fiedlerValue:e>0?1:0,spectralGap:e>0?1:0,effectiveResistance:e>0?.5:0,coherenceScore:e>0?1:0},n={healthy:!0,metrics:r,alerts:[],indexSize:e,usedNativeBackend:!1,adjacencySource:"approximate",checkDurationMs:t,checkedAt:new Date};return this.addHistoryPoint({coherenceScore:r.coherenceScore,fiedlerValue:r.fiedlerValue,indexSize:e,healthy:!0,timestamp:n.checkedAt}),this.lastReport=n,n}addHistoryPoint(e){this.history.push(e),this.history.length>this.config.maxHistoryEntries&&this.history.splice(0,this.history.length-this.config.maxHistoryEntries)}}});var ve={};$(ve,{HnswAdapter:()=>G});var ge,f,G,ye=g(()=>{K();Y();ie();ge={patterns:{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"},"qe-memory":{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"},learning:{dimensions:384,M:16,efConstruction:200,efSearch:50,metric:"cosine"},coverage:{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"}},f=new Map,G=class o{backend;_isNativeBackend;indexName;stringToNumericId=new Map;numericToStringId=new Map;nextAutoId=0;healthMonitor=null;healthMonitorLoaded=!1;operationsSinceLastCheck=0;healthCheckFrequency=100;lastHealthReport=null;constructor(e,t){this.indexName=e;let n={...ge[e]??{},...t},{backend:a,isNative:i}=o.createBackend(n);this.backend=a,this._isNativeBackend=i}add(e,t,r){this.backend.add(e,t,r),this.maybeRunHealthCheck()}search(e,t){let r=performance.now(),n=this.backend.search(e,t),a=performance.now()-r;return a>50&&console.warn(`[HNSW] search took ${a.toFixed(1)}ms (k=${t}, results=${n.length})`),this._lastSearchLatencyMs=a,n}_lastSearchLatencyMs=0;get lastSearchLatencyMs(){return this._lastSearchLatencyMs}remove(e){return this.backend.remove(e)}size(){return this.backend.size()}dimensions(){return this.backend.dimensions()}recall(){return this.backend.recall()}addByStringId(e,t){let r=this.stringToNumericId.get(e);r!==void 0?this.backend.remove(r):(r=this.nextAutoId++,this.stringToNumericId.set(e,r),this.numericToStringId.set(r,e)),this.backend.add(r,new Float32Array(t))}searchByArray(e,t){return this.backend.search(new Float32Array(e),t).map(n=>({id:this.numericToStringId.get(n.id)??String(n.id),score:n.score}))}removeByStringId(e){let t=this.stringToNumericId.get(e);if(t===void 0)return!1;let r=this.backend.remove(t);return r&&(this.stringToNumericId.delete(e),this.numericToStringId.delete(t)),r}clear(){this.backend.clear?.(),this.stringToNumericId.clear(),this.numericToStringId.clear(),this.nextAutoId=0}isRuvectorAvailable(){return this.backend instanceof w?this.backend.isRuvectorAvailable():this.backend instanceof H?this.backend.isNativeAvailable():!1}isNativeBackend(){return this._isNativeBackend}getName(){return this.indexName}setHealthCheckFrequency(e){this.healthCheckFrequency=Math.max(1,e)}getHealthCheckFrequency(){return this.healthCheckFrequency}getLastHealthReport(){return this.lastHealthReport}getHealthMonitor(){return this.healthMonitor}maybeRunHealthCheck(){if(q()&&(this.operationsSinceLastCheck++,!(this.operationsSinceLastCheck<this.healthCheckFrequency)&&(this.operationsSinceLastCheck=0,this.ensureHealthMonitor(),this.healthMonitor)))try{this.lastHealthReport=this.healthMonitor.checkHealth(this.backend),this.lastHealthReport.healthy||console.warn(`[HNSW-Health] Index "${this.indexName}" health check failed: ${this.lastHealthReport.alerts.length} alert(s). Coherence: ${this.lastHealthReport.metrics.coherenceScore.toFixed(3)}`)}catch(e){console.warn(`[HNSW-Health] Health check error for "${this.indexName}":`,e)}}ensureHealthMonitor(){if(!this.healthMonitorLoaded){this.healthMonitorLoaded=!0;try{let e=(ne(),W(re));this.healthMonitor=e.createHnswHealthMonitor()}catch(e){process.env.DEBUG&&console.debug("[HNSW-Health] Monitor module unavailable:",e instanceof Error?e.message:e),this.healthMonitor=null}}}static createBackend(e){if(j())try{return{backend:new H(e),isNative:!0}}catch(t){t instanceof p?console.info(`[HNSW] Native backend unavailable, falling back to JS: ${t.message}`):console.warn("[HNSW] Unexpected error creating native backend, falling back to JS:",t)}return{backend:new w(e),isNative:!1}}static create(e,t){let r=f.get(e);if(r instanceof o)return r;let n=new o(e,t);return f.set(e,n),n}static get(e){let t=f.get(e);return t instanceof o?t:void 0}static close(e){let t=f.get(e);t instanceof o&&t.clear(),f.delete(e)}static closeAll(){for(let[e]of f)o.close(e);f.clear()}static listIndexes(){return Array.from(f.keys())}}});export{G as a,ve as b,ye as c};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.1");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,7 @@
|
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.1");process.exit(0)}
|
|
2
|
+
import{a as I}from"./chunk-WDV6TN7E.js";import{a as A}from"./chunk-DC3HPOOJ.js";import{k as _,n as B,o as U}from"./chunk-24E47G3D.js";import{d as P,e as K}from"./chunk-A57BEPL7.js";import{b as w,d as Q}from"./chunk-JSOBRKMA.js";import{a as g,c as R}from"./chunk-UN4PA4M2.js";import{g as N}from"./chunk-UZZCWWIG.js";U();R();Q();K();import{randomUUID as z}from"crypto";var D=P("TokenTracker"),O={costPerInputToken:.003/1e3,costPerOutputToken:.015/1e3},j={filePath:".agentic-qe/token-metrics.json",autoSaveIntervalMs:6e4,maxMetricsInMemory:1e4},S=class c{taskMetrics=[];agentMetrics=new Map;domainMetrics=new Map;sessionId;sessionStartTime;costConfig;cacheHits=0;earlyExits=0;totalTokensSaved=0;totalPatternsReused=0;initialized=!1;persistenceConfig=j;autoSaveTimer=null;isDirty=!1;db=null;kvPersistCount=0;static KV_NAMESPACE="token-usage-metrics";static KV_KEY="token-tracker-snapshot";static KV_TTL=604800;static KV_PERSIST_INTERVAL=10;constructor(){this.sessionId=`session-${Date.now()}-${z().substring(0,8)}`,this.sessionStartTime=Date.now(),this.costConfig=O}initialize(e){this.initialized||(this.initialized=!0,e&&(this.costConfig={...O,...e}),this.initializeDb().catch(t=>{D.warn("DB initialization failed",{error:t instanceof Error?t.message:String(t)})}),this.startAutoSave())}setCostConfig(e){this.costConfig={...this.costConfig,...e}}recordTokenUsage(e,t,i,n,s,o){this.ensureInitialized();let l,u,r,a,m,d;typeof t=="object"?(l="default",u="unknown",r="unknown",a=t,m=!1,d=0):(l=t,u=i??"unknown",r=n??"unknown",a=s,m=o?.patternReused??!1,d=o?.tokensSaved??0),a.estimatedCostUsd===void 0&&(a.estimatedCostUsd=this.calculateCost(a));let h={taskId:e,agentId:l,domain:u,operation:r,timestamp:Date.now(),usage:a,patternReused:m,tokensSaved:d};this.taskMetrics.push(h),this.updateAgentMetrics(l,a,m,d),this.updateDomainMetrics(u,a),m&&this.totalPatternsReused++,d>0&&(this.totalTokensSaved+=d),this.isDirty=!0,this.maybePersistToKv()}recordPatternReuse(e,t){this.ensureInitialized(),this.totalPatternsReused++,this.totalTokensSaved+=t;let i={taskId:e,agentId:"pattern-cache",domain:"optimization",operation:"pattern-reuse",timestamp:Date.now(),usage:{inputTokens:0,outputTokens:0,totalTokens:0,estimatedCostUsd:0},patternReused:!0,tokensSaved:t};this.taskMetrics.push(i),this.isDirty=!0}recordCacheHit(e){this.cacheHits++,this.totalTokensSaved+=e,this.isDirty=!0}recordEarlyExit(e){this.earlyExits++,this.totalTokensSaved+=e,this.isDirty=!0}getSessionSummary(e){this.ensureInitialized();let t=this.filterByTimeframe(this.taskMetrics,e),i=this.aggregateTokenUsage(t),n=new Map;for(let r of t){let a=n.get(r.agentId);a?(a.totalInputTokens+=r.usage.inputTokens,a.totalOutputTokens+=r.usage.outputTokens,a.totalTokens+=r.usage.totalTokens,a.totalCost+=r.usage.estimatedCostUsd||0,a.tasksExecuted++,r.patternReused&&a.patternsReused++,a.estimatedTokensSaved+=r.tokensSaved||0):n.set(r.agentId,{agentId:r.agentId,totalInputTokens:r.usage.inputTokens,totalOutputTokens:r.usage.outputTokens,totalTokens:r.usage.totalTokens,totalCost:r.usage.estimatedCostUsd||0,tasksExecuted:1,patternsReused:r.patternReused?1:0,estimatedTokensSaved:r.tokensSaved||0})}let s=new Map;for(let r of t){let a=s.get(r.domain);a?(a.inputTokens+=r.usage.inputTokens,a.outputTokens+=r.usage.outputTokens,a.totalTokens+=r.usage.totalTokens,a.estimatedCostUsd=(a.estimatedCostUsd||0)+(r.usage.estimatedCostUsd||0)):s.set(r.domain,{...r.usage})}let o=i.totalTokens,l=this.totalTokensSaved,u=o+l>0?l/(o+l)*100:0;return{sessionId:this.sessionId,startTime:this.sessionStartTime,endTime:Date.now(),byAgent:n,byDomain:s,totalUsage:i,optimizationStats:{patternsReused:this.totalPatternsReused,cacheHits:this.cacheHits,earlyExits:this.earlyExits,tokensSaved:this.totalTokensSaved,savingsPercentage:Math.round(u*100)/100}}}getAgentMetrics(e,t){this.ensureInitialized();let i=this.filterByTimeframe(this.taskMetrics,t);if(e){let s=i.filter(o=>o.agentId===e);return this.aggregateAgentMetrics(e,s)}let n=new Map;for(let s of i){let o=n.get(s.agentId)||[];o.push(s),n.set(s.agentId,o)}return Array.from(n.entries()).map(([s,o])=>this.aggregateAgentMetrics(s,o))}getDomainMetrics(e,t){this.ensureInitialized();let i=this.filterByTimeframe(this.taskMetrics,t);if(e){let s=i.filter(o=>o.domain===e);return this.aggregateTokenUsage(s)}let n=new Map;for(let s of i){let o=n.get(s.domain);o?(o.inputTokens+=s.usage.inputTokens,o.outputTokens+=s.usage.outputTokens,o.totalTokens+=s.usage.totalTokens,o.estimatedCostUsd=(o.estimatedCostUsd||0)+(s.usage.estimatedCostUsd||0)):n.set(s.domain,{...s.usage})}return n}getTaskMetrics(e){return this.ensureInitialized(),this.filterByTimeframe(this.taskMetrics,e)}getEfficiencyReport(e){return this.getTokenEfficiency(e)}getTokenEfficiency(e){this.ensureInitialized();let t=this.filterByTimeframe(this.taskMetrics,e),n=this.aggregateTokenUsage(t).totalTokens,s=this.totalTokensSaved,o=n+s>0?s/(n+s)*100:0,l=t.length,u=l>0?t.filter(m=>m.patternReused).length/l:0,r=l>0?n/l:0,a=this.generateRecommendations(t);return{totalTokensUsed:n,totalTokensSaved:s,savingsPercentage:Math.round(o*100)/100,patternReuseRate:Math.round(u*100)/100,averageTokensPerTask:Math.round(r),recommendations:a}}reset(){this.stopAutoSave(),this.taskMetrics=[],this.agentMetrics.clear(),this.domainMetrics.clear(),this.sessionId=`session-${Date.now()}-${z().substring(0,8)}`,this.sessionStartTime=Date.now(),this.cacheHits=0,this.earlyExits=0,this.totalTokensSaved=0,this.totalPatternsReused=0,this.isDirty=!1}configurePersistence(e){this.persistenceConfig={...this.persistenceConfig,...e},e.autoSaveIntervalMs!==void 0&&(this.stopAutoSave(),e.autoSaveIntervalMs>0&&this.startAutoSave())}startAutoSave(){this.autoSaveTimer||this.persistenceConfig.autoSaveIntervalMs>0&&(this.autoSaveTimer=setInterval(()=>{this.isDirty&&this.save().catch(e=>{console.warn("[TokenMetricsCollector] Auto-save failed:",e)})},this.persistenceConfig.autoSaveIntervalMs))}stopAutoSave(){this.autoSaveTimer&&(clearInterval(this.autoSaveTimer),this.autoSaveTimer=null)}async save(){let e=await import("fs"),t=await import("path"),i={version:"1.0.0",sessionId:this.sessionId,sessionStartTime:this.sessionStartTime,taskMetrics:this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory),optimizationStats:{cacheHits:this.cacheHits,earlyExits:this.earlyExits,totalTokensSaved:this.totalTokensSaved,totalPatternsReused:this.totalPatternsReused},lastSavedAt:Date.now()},n=t.resolve(this.persistenceConfig.filePath),s=t.dirname(n);e.existsSync(s)||e.mkdirSync(s,{recursive:!0}),e.writeFileSync(n,JSON.stringify(i,null,2)),this.isDirty=!1}async load(){let e=await import("fs"),i=(await import("path")).resolve(this.persistenceConfig.filePath);if(!e.existsSync(i))return!1;try{let n=e.readFileSync(i,"utf-8"),s=w(n);if(!s.version||!s.version.startsWith("1."))return console.warn("[TokenMetricsCollector] Incompatible data version, skipping load"),!1;let o=s.taskMetrics||[];this.taskMetrics=[...o,...this.taskMetrics],this.cacheHits+=s.optimizationStats?.cacheHits||0,this.earlyExits+=s.optimizationStats?.earlyExits||0,this.totalTokensSaved+=s.optimizationStats?.totalTokensSaved||0,this.totalPatternsReused+=s.optimizationStats?.totalPatternsReused||0;for(let l of o)this.updateAgentMetrics(l.agentId,l.usage,l.patternReused,l.tokensSaved||0),this.updateDomainMetrics(l.domain,l.usage);return this.taskMetrics.length>this.persistenceConfig.maxMetricsInMemory&&(this.taskMetrics=this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory)),!0}catch(n){return console.warn("[TokenMetricsCollector] Failed to load persisted data:",n),!1}}getPersistenceFilePath(){return this.persistenceConfig.filePath}hasUnsavedChanges(){return this.isDirty}async initializeDb(){try{this.db=_(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(e){console.warn("[TokenMetricsCollector] DB init failed, using memory-only:",g(e)),this.db=null}}async persistToKv(){if(!this.db)return;let e={version:"1.0.0",sessionId:this.sessionId,sessionStartTime:this.sessionStartTime,taskMetrics:this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory),optimizationStats:{cacheHits:this.cacheHits,earlyExits:this.earlyExits,totalTokensSaved:this.totalTokensSaved,totalPatternsReused:this.totalPatternsReused},lastSavedAt:Date.now()};await this.db.kvSet(c.KV_KEY,e,c.KV_NAMESPACE,c.KV_TTL)}async loadFromKv(){if(!this.db)return!1;let e=await this.db.kvGet(c.KV_KEY,c.KV_NAMESPACE);if(!e)return!1;if(!e.version||!e.version.startsWith("1."))return console.warn("[TokenMetricsCollector] Incompatible kv_store data version, skipping load"),!1;let t=e.taskMetrics||[];this.taskMetrics=[...t,...this.taskMetrics],this.cacheHits+=e.optimizationStats?.cacheHits||0,this.earlyExits+=e.optimizationStats?.earlyExits||0,this.totalTokensSaved+=e.optimizationStats?.totalTokensSaved||0,this.totalPatternsReused+=e.optimizationStats?.totalPatternsReused||0;for(let i of t)this.updateAgentMetrics(i.agentId,i.usage,i.patternReused,i.tokensSaved||0),this.updateDomainMetrics(i.domain,i.usage);return this.taskMetrics.length>this.persistenceConfig.maxMetricsInMemory&&(this.taskMetrics=this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory)),!0}maybePersistToKv(){this.kvPersistCount++,this.kvPersistCount>=c.KV_PERSIST_INTERVAL&&(this.kvPersistCount=0,this.persistToKv().catch(e=>{D.warn("KV persist failed",{error:e instanceof Error?e.message:String(e)})}))}ensureInitialized(){this.initialized||this.initialize()}calculateCost(e){let t=e.inputTokens*this.costConfig.costPerInputToken,i=e.outputTokens*this.costConfig.costPerOutputToken;return Math.round((t+i)*1e5)/1e5}filterByTimeframe(e,t){if(!t)return e;let i=Date.now(),n;switch(t){case"1h":n=i-3600*1e3;break;case"24h":n=i-1440*60*1e3;break;case"7d":n=i-10080*60*1e3;break;case"30d":n=i-720*60*60*1e3;break;default:return e}return e.filter(s=>s.timestamp>=n)}aggregateTokenUsage(e){let t=0,i=0,n=0,s=0;for(let o of e)t+=o.usage.inputTokens,i+=o.usage.outputTokens,n+=o.usage.totalTokens,s+=o.usage.estimatedCostUsd||0;return{inputTokens:t,outputTokens:i,totalTokens:n,estimatedCostUsd:Math.round(s*1e5)/1e5}}aggregateAgentMetrics(e,t){let i=0,n=0,s=0,o=0,l=0,u=0;for(let r of t)i+=r.usage.inputTokens,n+=r.usage.outputTokens,s+=r.usage.totalTokens,o+=r.usage.estimatedCostUsd||0,r.patternReused&&l++,u+=r.tokensSaved||0;return{agentId:e,totalInputTokens:i,totalOutputTokens:n,totalTokens:s,totalCost:Math.round(o*1e5)/1e5,tasksExecuted:t.length,patternsReused:l,estimatedTokensSaved:u}}updateAgentMetrics(e,t,i,n){let s=this.agentMetrics.get(e);s?(s.totalInputTokens+=t.inputTokens,s.totalOutputTokens+=t.outputTokens,s.totalTokens+=t.totalTokens,s.totalCost+=t.estimatedCostUsd||0,s.tasksExecuted++,i&&s.patternsReused++,s.estimatedTokensSaved+=n):this.agentMetrics.set(e,{agentId:e,totalInputTokens:t.inputTokens,totalOutputTokens:t.outputTokens,totalTokens:t.totalTokens,totalCost:t.estimatedCostUsd||0,tasksExecuted:1,patternsReused:i?1:0,estimatedTokensSaved:n})}updateDomainMetrics(e,t){let i=this.domainMetrics.get(e);i?(i.inputTokens+=t.inputTokens,i.outputTokens+=t.outputTokens,i.totalTokens+=t.totalTokens,i.estimatedCostUsd=(i.estimatedCostUsd||0)+(t.estimatedCostUsd||0)):this.domainMetrics.set(e,{...t})}generateRecommendations(e){let t=[];if(e.length===0)return["No token usage data available yet. Start executing tasks to track consumption."];let i=e.filter(r=>r.patternReused).length/e.length;i<.2?t.push("Low pattern reuse rate detected. Consider enabling pattern caching for similar tasks."):i>.5&&t.push("Good pattern reuse rate. Continue leveraging cached patterns for token savings.");let n=new Map;for(let r of e){let a=n.get(r.domain)||0;n.set(r.domain,a+r.usage.totalTokens)}let s=Array.from(n.entries()).sort((r,a)=>a[1]-r[1]);if(s.length>0){let r=s[0];t.push(`Highest token consumer: ${r[0]} (${r[1].toLocaleString()} tokens). Consider optimizing prompts or increasing caching.`)}let o=e.reduce((r,a)=>r+a.usage.inputTokens,0);return e.reduce((r,a)=>r+a.usage.outputTokens,0)/(o||1)>2&&t.push("High output-to-input token ratio. Consider requesting more concise responses."),this.cacheHits===0&&e.length>10&&t.push("No cache hits detected. Enable response caching to reduce duplicate API calls."),this.earlyExits===0&&e.length>20&&t.push("Early exit optimization not utilized. Enable high-confidence pattern matching to skip unnecessary LLM calls."),t}};function F(c){return c.toLocaleString("en-US")}function $(c){if(process.env.AQE_TOKEN_DASHBOARD_ENABLED==="false")return"Token dashboard disabled (AQE_TOKEN_DASHBOARD_ENABLED=false)";if(!c){let u=p.getSessionSummary(),r=u.totalUsage.totalTokens,a=u.totalUsage.estimatedCostUsd??0,m=u.optimizationStats.tokensSaved,d=r>0?a/r:0,h=m*d;c={totalTokens:r,totalCostUsd:a,savedTokens:m,savedCostUsd:h}}let e=c.totalTokens??0,t=c.totalCostUsd??0,i=c.savedTokens??0,n=c.savedCostUsd??0,s=c.budgetLimitUsd;if(e===0&&i===0)return"Token Dashboard: No data available";let o=`Token Usage: ${F(e)} tokens ($${t.toFixed(2)})`;i>0&&(o+=` | Saved: ${F(i)} tokens ($${n.toFixed(2)}) via pattern reuse`);let l=[];if(s!==void 0&&s>0){let u=Math.round(t/s*100);l.push(`Budget: $${t.toFixed(2)} / $${s.toFixed(2)} (${u}%)`)}if(c.tierSplit&&Object.keys(c.tierSplit).length>0){let u=Object.entries(c.tierSplit).sort((r,a)=>a[1]-r[1]).map(([r,a])=>`${r} ${a}%`);l.push(`Tier split: ${u.join(" | ")}`)}return l.length===0?o:`${o}
|
|
3
|
+
${l.join(" | ")}`}var p=new S;function te(c){return`$${c.toFixed(2)}`}import{createHash as V}from"crypto";var G={enabled:!0,maxEntries:500,ttlMs:3600*1e3,persistToDb:!0};function E(c){if(c==null||typeof c!="object")return JSON.stringify(c);if(Array.isArray(c))return"["+c.map(n=>E(n)).join(",")+"]";let e=c;return"{"+Object.keys(e).sort().map(n=>JSON.stringify(n)+":"+E(e[n])).join(",")+"}"}var b=class{cache=new Map;config;hits=0;misses=0;constructor(e){this.config={...G,...e}}computeFingerprint(e,t,i){let n=E({action:t,domain:e,input:i});return V("sha256").update(n).digest("hex").slice(0,16)}get(e){if(!this.config.enabled)return null;let t=this.cache.get(e);return t?Date.now()-t.cachedAt>this.config.ttlMs?(this.cache.delete(e),this.misses++,null):(t.hitCount++,t.lastHitAt=Date.now(),this.hits++,t):(this.misses++,null)}set(e,t,i,n,s){if(!this.config.enabled)return;this.cache.size>=this.config.maxEntries&&this.evictOldest();let o={fingerprint:e,domain:t,action:i,result:n,tokensSaved:s,cachedAt:Date.now(),hitCount:0,lastHitAt:0};this.cache.set(e,o),this.config.persistToDb&&this.persistEntry(o)}loadFromDb(){try{let e=H();if(!e)return;let t=Date.now()-this.config.ttlMs,i=e.prepare(`SELECT key, value FROM kv_store
|
|
4
|
+
WHERE namespace = 'session_cache'
|
|
5
|
+
AND created_at > ?
|
|
6
|
+
ORDER BY created_at DESC LIMIT ?`).all(t,this.config.maxEntries);for(let n of i)try{let s=JSON.parse(n.value);Date.now()-s.cachedAt<=this.config.ttlMs&&this.cache.set(s.fingerprint,s)}catch{}}catch{}}getStats(){let e=this.hits+this.misses,t=0;for(let i of this.cache.values())t+=i.tokensSaved*i.hitCount;return{size:this.cache.size,hits:this.hits,misses:this.misses,hitRate:e>0?this.hits/e:0,estimatedTokensSaved:t}}clear(){this.cache.clear(),this.hits=0,this.misses=0}evictOldest(){let e=null,t=1/0;for(let[i,n]of this.cache)n.cachedAt<t&&(t=n.cachedAt,e=i);e&&this.cache.delete(e)}persistEntry(e){try{let t=H();if(!t)return;t.prepare(`INSERT OR REPLACE INTO kv_store (key, namespace, value, created_at)
|
|
7
|
+
VALUES (?, 'session_cache', ?, ?)`).run(`session_cache:${e.fingerprint}`,JSON.stringify(e),Date.now())}catch{}}};function H(){try{let{getUnifiedMemory:c}=(U(),N(B)),e=c();return e.isInitialized()?e.getDatabase():null}catch{return null}}var f=null;function k(c){return f||(f=new b(c),f.loadFromDb()),f}import{randomUUID as q}from"crypto";R();var x={minConfidenceForExit:.85,minSuccessRate:.9,maxPatternAge:10080*60*1e3,minQualityScore:.7,minSuccessfulUses:2,maxSearchResults:5,similarityThreshold:.8,verbose:!1},ae={minConfidenceForExit:.75,minSuccessRate:.8,maxPatternAge:336*60*60*1e3,minQualityScore:.6,minSuccessfulUses:1,maxSearchResults:10,similarityThreshold:.7,verbose:!1},ce={minConfidenceForExit:.92,minSuccessRate:.95,maxPatternAge:4320*60*1e3,minQualityScore:.85,minSuccessfulUses:3,maxSearchResults:3,similarityThreshold:.9,verbose:!1},T=class{patternStore;config;reuseHistory=[];attemptHistory=[];constructor(e,t){this.patternStore=e,this.config={...x,...t}}async checkEarlyExit(e){let t=performance.now(),i=new Date;try{let n=e.domain??A(e.description)??void 0,s={limit:this.config.maxSearchResults*2,useVectorSearch:!!e.embedding};n&&(s.domain=n),e.context&&(s.context={language:e.context.language,framework:e.context.framework,testType:e.context.testType});let o=e.embedding??e.description,l=await this.patternStore.search(o,s),u=performance.now()-t;if(!l.success){let d="error"in l?l.error.message:"Unknown error",h=this.createResult(!1,"search_error",`Pattern search failed: ${d}`,u);return this.recordAttempt("search_error",n),h}let r=l.value;if(r.length===0){let d=this.createResult(!1,"no_matching_pattern","No matching patterns found in store",u);return this.recordAttempt("no_matching_pattern",n),d}let a=null;for(let{pattern:d,score:h}of r){let y=this.evaluatePatternEligibility(d,h,i);if(y.eligible){let v=this.estimateTokensSaved(d),L={canExit:!0,reusedPattern:d,estimatedTokensSaved:v,confidence:d.confidence,similarityScore:h,reason:"pattern_reused",explanation:`Reusing pattern "${d.name}" with ${(d.confidence*100).toFixed(1)}% confidence`,searchLatencyMs:u};return this.recordReuse(d.id,v,d.confidence,h,u,n),this.config.verbose&&console.log(`[EarlyExitTokenOptimizer] Pattern reuse: ${d.name} (confidence: ${d.confidence.toFixed(2)}, similarity: ${h.toFixed(2)}, tokens saved: ${v})`),L}a===null&&(a={reason:y.reason,explanation:y.explanation})}if(a){let d=this.createResult(!1,a.reason,a.explanation,u);return this.recordAttempt(a.reason,n),d}let m=this.createResult(!1,"no_matching_pattern",`Found ${r.length} patterns but none met eligibility criteria`,u);return this.recordAttempt("no_matching_pattern",n),m}catch(n){let s=performance.now()-t,o=this.createResult(!1,"search_error",`Error during pattern search: ${g(n)}`,s);return this.recordAttempt("search_error"),o}}evaluatePatternEligibility(e,t,i){if(t<this.config.similarityThreshold)return{eligible:!1,reason:"similarity_too_low",explanation:`Similarity ${(t*100).toFixed(1)}% < threshold ${(this.config.similarityThreshold*100).toFixed(1)}%`};if(e.confidence<this.config.minConfidenceForExit)return{eligible:!1,reason:"confidence_too_low",explanation:`Confidence ${(e.confidence*100).toFixed(1)}% < threshold ${(this.config.minConfidenceForExit*100).toFixed(1)}%`};if(e.successRate<this.config.minSuccessRate)return{eligible:!1,reason:"success_rate_too_low",explanation:`Success rate ${(e.successRate*100).toFixed(1)}% < threshold ${(this.config.minSuccessRate*100).toFixed(1)}%`};let n=i.getTime()-e.lastUsedAt.getTime();if(n>this.config.maxPatternAge){let s=Math.floor(n/864e5),o=Math.floor(this.config.maxPatternAge/(1440*60*1e3));return{eligible:!1,reason:"pattern_too_old",explanation:`Pattern age ${s} days > max ${o} days`}}return e.qualityScore<this.config.minQualityScore?{eligible:!1,reason:"quality_score_too_low",explanation:`Quality score ${(e.qualityScore*100).toFixed(1)}% < threshold ${(this.config.minQualityScore*100).toFixed(1)}%`}:e.successfulUses<this.config.minSuccessfulUses?{eligible:!1,reason:"insufficient_uses",explanation:`Successful uses ${e.successfulUses} < minimum ${this.config.minSuccessfulUses}`}:{eligible:!0,reason:"pattern_reused",explanation:"Pattern meets all eligibility criteria"}}estimateTokensSaved(e){let t=100,i=Math.ceil(e.template.content.length/4);t+=i,t+=50;let o={"test-template":1.5,"assertion-pattern":1,"mock-pattern":1.2,"coverage-strategy":1.3,"api-contract":1.4,"visual-baseline":1.1,"perf-benchmark":1.4,"flaky-fix":1.3,"error-handling":1.2}[e.patternType]??1;return Math.ceil(t*o)}createResult(e,t,i,n){return{canExit:e,reason:t,explanation:i,searchLatencyMs:n}}recordReuse(e,t,i,n,s,o){this.reuseHistory.push({patternId:e,tokensSaved:t,confidence:i,similarity:n,latencyMs:s,domain:o,timestamp:new Date}),this.attemptHistory.push({reason:"pattern_reused",domain:o,timestamp:new Date}),this.reuseHistory.length>1e4&&(this.reuseHistory=this.reuseHistory.slice(-1e4))}recordAttempt(e,t){this.attemptHistory.push({reason:e,domain:t,timestamp:new Date}),this.attemptHistory.length>1e4&&(this.attemptHistory=this.attemptHistory.slice(-1e4))}recordSuccessfulReuse(e){this.patternStore.recordUsage(e,!0).catch(t=>{console.warn(`[EarlyExitTokenOptimizer] Failed to record successful reuse for ${e}:`,t)})}recordFailedReuse(e){this.patternStore.recordUsage(e,!1).catch(t=>{console.warn(`[EarlyExitTokenOptimizer] Failed to record failed reuse for ${e}:`,t)})}getReuseStats(){let e=this.reuseHistory.length,t=this.attemptHistory.length,i=0,n=0,s=0,o=0;for(let r of this.reuseHistory)i+=r.tokensSaved,n+=r.confidence,s+=r.similarity,o+=r.latencyMs;let l={pattern_reused:0,no_matching_pattern:0,confidence_too_low:0,success_rate_too_low:0,pattern_too_old:0,quality_score_too_low:0,insufficient_uses:0,similarity_too_low:0,search_error:0};for(let r of this.attemptHistory)l[r.reason]++;let u={};for(let r of this.reuseHistory){let a=r.domain??"unknown";u[a]||(u[a]={reuses:0,tokens:0}),u[a].reuses++,u[a].tokens+=r.tokensSaved}return{totalReuses:e,tokensSaved:i,avgConfidence:e>0?n/e:0,avgSimilarity:e>0?s/e:0,avgSearchLatencyMs:e>0?o/e:0,totalAttempts:t,exitRate:t>0?e/t:0,reasonBreakdown:l,domainBreakdown:u}}resetStats(){this.reuseHistory=[],this.attemptHistory=[]}getConfig(){return{...this.config}}updateConfig(e){Object.assign(this.config,e)}};var C={enabled:!0,earlyExit:x,verbose:!1},M=class{optimizer=null;patternStore=null;config=C;initialized=!1;async initialize(e,t){if(!this.initialized){if(this.config={...C,...t},!this.config.enabled){this.config.verbose&&console.log("[TokenOptimizerService] Service disabled by configuration");return}try{this.patternStore=I(e),await this.patternStore.initialize(),this.optimizer=new T(this.patternStore,this.config.earlyExit),this.initialized=!0,this.config.verbose&&console.log("[TokenOptimizerService] Initialized with EarlyExitTokenOptimizer")}catch(i){console.warn("[TokenOptimizerService] Failed to initialize:",i)}}}async checkEarlyExit(e){if(!this.initialized||!this.optimizer)return{canExit:!1,reason:"no_matching_pattern",explanation:"Token optimizer service not initialized",searchLatencyMs:0};try{let i=k(),n=i.computeFingerprint(e.domain??"unknown",e.description,e.context??{}),s=i.get(n);if(s)return p.recordEarlyExit(s.tokensSaved),this.config.verbose&&console.log(`[TokenOptimizerService] Session cache hit: ${n.slice(0,8)}... (saved ${s.tokensSaved} tokens)`),{canExit:!0,estimatedTokensSaved:s.tokensSaved,confidence:1,similarityScore:1,reason:"pattern_reused",explanation:`Session cache exact match (fingerprint: ${n.slice(0,8)}...)`,searchLatencyMs:0}}catch{}let t=await this.optimizer.checkEarlyExit(e);return t.canExit&&t.estimatedTokensSaved&&(p.recordEarlyExit(t.estimatedTokensSaved),this.config.verbose&&console.log(`[TokenOptimizerService] Early exit: ${t.reusedPattern?.name} (saved ${t.estimatedTokensSaved} tokens)`)),t}async checkTaskEarlyExit(e,t){return this.checkEarlyExit({description:e,domain:t})}recordSuccessfulReuse(e){this.optimizer&&this.optimizer.recordSuccessfulReuse(e)}recordFailedReuse(e){this.optimizer&&this.optimizer.recordFailedReuse(e)}async storePattern(e){if(!this.patternStore)return null;try{let t=await this.patternStore.store({...e,id:`pattern-${Date.now()}-${q().slice(0,8)}`,createdAt:new Date,lastUsedAt:new Date});return t.success?t.value:null}catch(t){return console.warn("[TokenOptimizerService] Failed to store pattern:",t),null}}getReuseStats(){return this.optimizer?this.optimizer.getReuseStats():null}isEnabled(){return this.initialized&&this.config.enabled}getConfig(){return{...this.config}}getDashboardSummary(){return $()}cacheOperationResult(e,t,i,n,s){try{let o=k(),l=o.computeFingerprint(e,t,i);o.set(l,e,t,n,s)}catch{}}getSessionCacheStats(){try{return k().getStats()}catch{return{size:0,hits:0,misses:0,hitRate:0,estimatedTokensSaved:0}}}reset(){this.optimizer&&this.optimizer.resetStats(),this.optimizer=null,this.patternStore=null,this.initialized=!1,this.config=C}},J=new M;async function ye(c,e){await J.initialize(c,e)}export{$ as a,p as b,te as c,k as d,J as e,ye as f};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.1");process.exit(0)}
|
|
2
|
+
var n=["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","requirements-validation","code-intelligence","security-compliance","contract-testing","visual-accessibility","chaos-resilience","learning-optimization","enterprise-integration","coordination"];function t(e){return{success:!0,value:e}}function r(e){return{success:!1,error:e}}export{n as a,t as b,r as c};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.1");process.exit(0)}
|
|
2
|
+
import{g}from"./chunk-7ZNINH6J.js";import{b as p,c as d}from"./chunk-5LDBKZ6P.js";import{b as m,c as f}from"./chunk-UN4PA4M2.js";import{f as h}from"./chunk-UB7RGVKO.js";f();var I={maxDepth:5,riskWeights:{directImpact:.4,transitiveImpact:.2,testCoverage:.2,criticalPath:.15,dependencyCount:.05},testPatterns:["**/*.test.ts","**/*.test.tsx","**/*.spec.ts","**/*.spec.tsx","**/test_*.py","**/*_test.py","**/*_test.go"],criticalPaths:["**/auth/**","**/security/**","**/payment/**","**/api/**","**/core/**"],namespace:"code-intelligence:impact"},u=class{constructor(e,t,i={}){this.memory=e;this.config={...I,...i},this.knowledgeGraph=t||new g(e)}config;knowledgeGraph;async analyzeImpact(e){try{let{changedFiles:t,depth:i=this.config.maxDepth,includeTests:n=!0}=e;if(t.length===0)return p({directImpact:[],transitiveImpact:[],impactedTests:[],riskLevel:"info",recommendations:[]});let r=await this.analyzeDirectImpact(t),l=await this.analyzeTransitiveImpact(t,r,i),s=[];if(n){let a=await this.getImpactedTests(t);a.success&&(s=a.value)}let c={directImpact:r,transitiveImpact:l,impactedTests:s,riskLevel:"info",recommendations:[]};return c.riskLevel=this.calculateRiskLevel(c),c.recommendations=this.getRecommendations(c),await this.storeAnalysis(t,c),p(c)}catch(t){return d(m(t))}}async getImpactedTests(e){try{let t=new Set;for(let i of e){if(this.isTestFile(i)){t.add(i);continue}let n=await this.knowledgeGraph.mapDependencies({files:[i],direction:"incoming",depth:3});if(n.success)for(let s of n.value.nodes)this.isTestFile(s.path)&&t.add(s.path);let r=this.getBaseName(i),l=[`${r}.test`,`${r}.spec`,`test_${r}`,`${r}_test`];for(let s of l){let c=await this.memory.search(`code-intelligence:kg:node:*${s}*`,10);for(let a of c){let o=await this.memory.get(a);o?.properties?.path&&this.isTestFile(o.properties.path)&&t.add(o.properties.path)}}}return p(Array.from(t))}catch(t){return d(m(t))}}calculateRiskLevel(e){let t=this.config.riskWeights,i=0,n=Math.min(1,e.directImpact.length/10);i+=n*t.directImpact;let r=Math.min(1,e.transitiveImpact.length/20);i+=r*t.transitiveImpact;let l=e.impactedTests.length>0?Math.max(0,1-e.impactedTests.length/(e.directImpact.length||1)):1;i+=l*t.testCoverage;let s=this.countCriticalFiles([...e.directImpact.map(o=>o.file),...e.transitiveImpact.map(o=>o.file)]),c=Math.min(1,s/5);i+=c*t.criticalPath;let a=this.calculateAverageRiskScore([...e.directImpact,...e.transitiveImpact]);return i+=a*t.dependencyCount,i>=.8?"critical":i>=.6?"high":i>=.4?"medium":i>=.2?"low":"info"}getRecommendations(e){let t=[];(e.riskLevel==="critical"||e.riskLevel==="high")&&t.push("This change has significant impact - consider peer review before merging"),e.impactedTests.length===0&&e.directImpact.length>0?t.push("No tests found for impacted files - add test coverage"):e.impactedTests.length<e.directImpact.length/2&&t.push("Test coverage appears low for impacted files"),e.impactedTests.length>0&&(e.impactedTests.length<=10?t.push(`Run these ${e.impactedTests.length} tests: ${e.impactedTests.slice(0,3).join(", ")}${e.impactedTests.length>3?"...":""}`):t.push(`Run all ${e.impactedTests.length} impacted tests before deployment`));let i=[...e.directImpact,...e.transitiveImpact].filter(r=>this.isCriticalPath(r.file));i.length>0&&t.push(`${i.length} critical path files affected - extra scrutiny recommended`),e.transitiveImpact.length>10&&t.push("Large transitive impact - consider breaking down into smaller changes");let n=[...e.directImpact,...e.transitiveImpact].filter(r=>r.riskScore>=.7);return n.length>0&&t.push(`${n.length} high-risk files impacted: ${n.slice(0,2).map(r=>this.getFileName(r.file)).join(", ")}`),t}async analyzeDirectImpact(e){let t=[];for(let i of e){let n=await this.knowledgeGraph.mapDependencies({files:[i],direction:"incoming",depth:1});if(n.success){let{nodes:r,edges:l}=n.value;for(let s of r){if(s.path===i)continue;let c=l.find(o=>o.target===s.id||o.source===s.id),a=this.calculateFileRiskScore(s.path,s.inDegree,s.outDegree);t.push({file:s.path,reason:`Directly ${c?.type||"depends on"} ${this.getFileName(i)}`,distance:1,riskScore:a})}}}return this.deduplicateImpact(t)}async analyzeTransitiveImpact(e,t,i){let n=[],r=new Set([...e,...t.map(s=>s.file)]),l=t.map(s=>({file:s.file,distance:1}));for(;l.length>0;){let s=l.shift();if(s.distance>=i)continue;let c=await this.knowledgeGraph.mapDependencies({files:[s.file],direction:"incoming",depth:1});if(c.success)for(let a of c.value.nodes){if(r.has(a.path)||a.path===s.file)continue;r.add(a.path);let o=this.calculateFileRiskScore(a.path,a.inDegree,a.outDegree,s.distance+1);n.push({file:a.path,reason:`Transitively depends via ${this.getFileName(s.file)}`,distance:s.distance+1,riskScore:o}),l.push({file:a.path,distance:s.distance+1})}}return this.deduplicateImpact(n)}calculateFileRiskScore(e,t,i,n=1){let r=0;return r+=Math.min(.3,t/20),r+=Math.min(.2,i/30),this.isCriticalPath(e)&&(r+=.3),this.isEntryPoint(e)&&(r+=.2),r=r*Math.pow(.8,n-1),Math.min(1,Math.max(0,r))}calculateAverageRiskScore(e){return e.length===0?0:e.reduce((i,n)=>i+n.riskScore,0)/e.length}countCriticalFiles(e){return e.filter(t=>this.isCriticalPath(t)).length}isTestFile(e){return[/\.test\.[tj]sx?$/,/\.spec\.[tj]sx?$/,/_test\.[tj]sx?$/,/test_.*\.py$/,/.*_test\.py$/,/.*_test\.go$/].some(i=>i.test(e))}isCriticalPath(e){return this.config.criticalPaths.map(i=>i.replace(/\*\*/g,".*").replace(/\*/g,"[^/]*")).some(i=>new RegExp(i).test(e))}isEntryPoint(e){return[/\/index\.[tj]sx?$/,/\/main\.[tj]sx?$/,/\/app\.[tj]sx?$/,/^src\/[^/]+\.[tj]sx?$/,/\/server\.[tj]sx?$/,/\/__init__\.py$/,/\/main\.go$/].some(i=>i.test(e))}getBaseName(e){return this.getFileName(e).replace(/\.[^.]+$/,"")}getFileName(e){return e.split(/[/\\]/).pop()||e}deduplicateImpact(e){let t=new Map;for(let i of e){let n=t.get(i.file);(!n||i.distance<n.distance)&&t.set(i.file,i)}return Array.from(t.values()).sort((i,n)=>n.riskScore!==i.riskScore?n.riskScore-i.riskScore:i.distance-n.distance)}async storeAnalysis(e,t){let i=h();await this.memory.set(`${this.config.namespace}:analysis:${i}`,{id:i,changedFiles:e,analysis:t,timestamp:new Date().toISOString()},{namespace:this.config.namespace,persist:!0})}};export{u as a};
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.1");process.exit(0)}
|
|
2
|
+
import{k as p,o as N}from"./chunk-24E47G3D.js";N();import{createHash as y}from"crypto";var g="0".repeat(64);function m(s){return y("sha256").update(s,"utf-8").digest("hex")}function R(s){try{return y("shake256",{outputLength:32}).update(s,"utf-8").digest("hex")}catch{return m(s)}}function u(s,t){return s==="shake256"?R(t):m(t)}function f(s){return JSON.stringify({id:s.id,prev_hash:s.prev_hash,action_hash:s.action_hash,action_type:s.action_type,action_data:s.action_data,timestamp:s.timestamp,actor:s.actor})}var d=class{constructor(t,i){this.externalDb=t;this.keyManager=i??null}db=null;initialized=!1;keyManager=null;async initialize(){if(!this.initialized){if(this.externalDb)this.db=this.externalDb;else{let t=p();await t.initialize(),this.db=t.getDatabase()}this.ensureTable(),this.initialized=!0}}getDatabase(){return this.db}getKeyManager(){return this.keyManager}ensureTable(){if(!this.db)throw new Error("Database not initialized");this.db.exec(`
|
|
3
|
+
CREATE TABLE IF NOT EXISTS witness_chain (
|
|
4
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
5
|
+
prev_hash TEXT NOT NULL, action_hash TEXT NOT NULL, action_type TEXT NOT NULL,
|
|
6
|
+
action_data TEXT, timestamp TEXT NOT NULL, actor TEXT NOT NULL,
|
|
7
|
+
hash_algo TEXT DEFAULT 'sha256', signature TEXT, signer_key_id TEXT
|
|
8
|
+
);
|
|
9
|
+
CREATE INDEX IF NOT EXISTS idx_witness_action_type ON witness_chain(action_type);
|
|
10
|
+
CREATE INDEX IF NOT EXISTS idx_witness_timestamp ON witness_chain(timestamp);
|
|
11
|
+
CREATE INDEX IF NOT EXISTS idx_witness_actor ON witness_chain(actor);
|
|
12
|
+
`),this.addColumnIfMissing("hash_algo","TEXT DEFAULT 'sha256'"),this.addColumnIfMissing("signature","TEXT"),this.addColumnIfMissing("signer_key_id","TEXT"),this.db.exec(`
|
|
13
|
+
CREATE TABLE IF NOT EXISTS witness_chain_archive (
|
|
14
|
+
id INTEGER PRIMARY KEY,
|
|
15
|
+
prev_hash TEXT NOT NULL, action_hash TEXT NOT NULL, action_type TEXT NOT NULL,
|
|
16
|
+
action_data TEXT, timestamp TEXT NOT NULL, actor TEXT NOT NULL,
|
|
17
|
+
hash_algo TEXT DEFAULT 'sha256', signature TEXT, signer_key_id TEXT,
|
|
18
|
+
archived_at TEXT NOT NULL
|
|
19
|
+
);
|
|
20
|
+
`)}addColumnIfMissing(t,i){if(!this.db)return;this.db.prepare("SELECT name FROM pragma_table_info('witness_chain')").all().some(r=>r.name===t)||this.db.exec(`ALTER TABLE witness_chain ADD COLUMN ${t} ${i}`)}append(t,i,e){if(!this.db)throw new Error("WitnessChain not initialized");let r=new Date().toISOString(),o=JSON.stringify(i),a="shake256",n=R(o),h=this.db.prepare("SELECT * FROM witness_chain ORDER BY id DESC LIMIT 1").get(),c=h?u(a,f(h)):g,l=null,_=null;if(this.keyManager){let b=Buffer.from(c+n+t+r+e,"utf-8"),T=this.keyManager.sign(b);l=T.signature.toString("hex"),_=T.keyId}return{id:this.db.prepare(`INSERT INTO witness_chain
|
|
21
|
+
(prev_hash, action_hash, action_type, action_data, timestamp, actor, hash_algo, signature, signer_key_id)
|
|
22
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(c,n,t,o,r,e,a,l,_).lastInsertRowid,prev_hash:c,action_hash:n,action_type:t,action_data:o,timestamp:r,actor:e,hash_algo:a,signature:l,signer_key_id:_}}verify(t){if(!this.db)throw new Error("WitnessChain not initialized");let i=this.db.prepare("SELECT * FROM witness_chain ORDER BY id ASC").all();if(i.length===0)return{valid:!0,entriesChecked:0};let e=0,r=t?.checkSignatures===!0&&this.keyManager!==null;for(let a=0;a<i.length;a++){let n=i[a],h=n.hash_algo||"sha256";if(n.action_hash!==u(h,n.action_data))return{valid:!1,brokenAt:n.id,entriesChecked:a+1,signatureFailures:e};if(a===0){if(n.prev_hash!==g)return{valid:!1,brokenAt:n.id,entriesChecked:1,signatureFailures:e}}else{let c=u(h,f(i[a-1]));if(n.prev_hash!==c)return{valid:!1,brokenAt:n.id,entriesChecked:a+1,signatureFailures:e}}if(r&&n.signature&&n.signer_key_id){let c=Buffer.from(n.prev_hash+n.action_hash+n.action_type+n.timestamp+n.actor,"utf-8");this.keyManager.verify(Buffer.from(c),Buffer.from(n.signature,"hex"),n.signer_key_id)||e++}}return{valid:e===0,entriesChecked:i.length,signatureFailures:e,...e>0?{brokenAt:i[0].id}:{}}}getEntries(t){if(!this.db)throw new Error("WitnessChain not initialized");let i=[],e=[];t?.action_type&&(i.push("action_type = ?"),e.push(t.action_type)),t?.since&&(i.push("timestamp >= ?"),e.push(t.since)),t?.until&&(i.push("timestamp <= ?"),e.push(t.until)),t?.actor&&(i.push("actor = ?"),e.push(t.actor));let r=i.length>0?`WHERE ${i.join(" AND ")}`:"",o=t?.limit!=null,a=t?.offset!=null,n=o||a?"LIMIT ?":"",h=a?"OFFSET ?":"";return o?e.push(t.limit):a&&e.push(-1),a&&e.push(t.offset),this.db.prepare(`SELECT * FROM witness_chain ${r} ORDER BY id ASC ${n} ${h}`).all(...e)}getPatternLineage(t){if(!this.db)throw new Error("WitnessChain not initialized");return this.db.prepare(`SELECT * FROM witness_chain
|
|
23
|
+
WHERE json_extract(action_data, '$.patternId') = ? OR json_extract(action_data, '$.pattern_id') = ?
|
|
24
|
+
ORDER BY id ASC`).all(t,t)}getActorHistory(t,i){if(!this.db)throw new Error("WitnessChain not initialized");return i?this.db.prepare("SELECT * FROM witness_chain WHERE actor = ? AND timestamp >= ? ORDER BY id ASC").all(t,i):this.db.prepare("SELECT * FROM witness_chain WHERE actor = ? ORDER BY id ASC").all(t)}archiveEntries(t){if(!this.db)throw new Error("WitnessChain not initialized");let i=new Date().toISOString(),r=this.db.prepare(`INSERT INTO witness_chain_archive
|
|
25
|
+
(id, prev_hash, action_hash, action_type, action_data, timestamp, actor, hash_algo, signature, signer_key_id, archived_at)
|
|
26
|
+
SELECT id, prev_hash, action_hash, action_type, action_data, timestamp, actor, hash_algo, signature, signer_key_id, ?
|
|
27
|
+
FROM witness_chain WHERE timestamp < ? AND id > 1 AND id NOT IN (SELECT id FROM witness_chain_archive)`).run(i,t).changes;return r>0&&this.db.prepare("DELETE FROM witness_chain WHERE timestamp < ? AND id > 1").run(t),{archived:r}}crossVerifyWithRvf(t){let i=this.verify(),e=t.status(),r=e.witnessValid===!0,o=typeof e.witnessEntries=="number"?e.witnessEntries:0;return{sqliteValid:i.valid,rvfValid:r,rvfEntries:o,bothValid:i.valid&&r}}getChainLength(){if(!this.db)throw new Error("WitnessChain not initialized");return this.db.prepare("SELECT COUNT(*) as count FROM witness_chain").get().count}},E=null;async function L(){return E||(E=new d,await E.initialize()),E}function v(s,t){return new d(s,t)}export{g as a,m as b,R as c,u as d,f as e,d as f,L as g,v as h};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.1");process.exit(0)}
|
|
2
|
+
import{randomUUID as v}from"crypto";var m={"claude-opus-4-5-20251101":{input:15,output:75,provider:"claude"},"claude-sonnet-4-20250514":{input:3,output:15,provider:"claude"},"claude-3-5-haiku-20241022":{input:1,output:5,provider:"claude"},"claude-3-opus-20240229":{input:15,output:75,provider:"claude"},"claude-3-sonnet-20240229":{input:3,output:15,provider:"claude"},"claude-3-haiku-20240307":{input:.25,output:1.25,provider:"claude"},"gpt-4o":{input:5,output:15,provider:"openai"},"gpt-4o-mini":{input:.15,output:.6,provider:"openai"},"gpt-4-turbo":{input:10,output:30,provider:"openai"},"gpt-4":{input:30,output:60,provider:"openai"},"gpt-3.5-turbo":{input:.5,output:1.5,provider:"openai"},llama3:{input:0,output:0,provider:"ollama"},"llama3.1":{input:0,output:0,provider:"ollama"},codellama:{input:0,output:0,provider:"ollama"},mistral:{input:0,output:0,provider:"ollama"},mixtral:{input:0,output:0,provider:"ollama"},phi3:{input:0,output:0,provider:"ollama"},qwen2:{input:0,output:0,provider:"ollama"},"anthropic/claude-3.5-sonnet":{input:3,output:15,provider:"openrouter"},"anthropic/claude-3.5-sonnet:beta":{input:3,output:15,provider:"openrouter"},"anthropic/claude-3-opus":{input:15,output:75,provider:"openrouter"},"anthropic/claude-3-sonnet":{input:3,output:15,provider:"openrouter"},"anthropic/claude-3-haiku":{input:.25,output:1.25,provider:"openrouter"},"openai/gpt-4o":{input:5,output:15,provider:"openrouter"},"openai/gpt-4o-mini":{input:.15,output:.6,provider:"openrouter"},"openai/gpt-4-turbo":{input:10,output:30,provider:"openrouter"},"openai/gpt-3.5-turbo":{input:.5,output:1.5,provider:"openrouter"},"google/gemini-pro":{input:.125,output:.375,provider:"openrouter"},"google/gemini-pro-1.5":{input:3.5,output:10.5,provider:"openrouter"},"meta-llama/llama-3.1-70b-instruct":{input:.59,output:.79,provider:"openrouter"},"meta-llama/llama-3.1-8b-instruct":{input:.06,output:.06,provider:"openrouter"},"mistralai/mistral-large":{input:2,output:6,provider:"openrouter"},"mistralai/mixtral-8x7b-instruct":{input:.24,output:.24,provider:"openrouter"},"mistralai/mistral-7b-instruct":{input:.06,output:.06,provider:"openrouter"},"anthropic.claude-opus-4-5-v1:0":{input:15,output:75,provider:"bedrock"},"anthropic.claude-opus-4-v1:0":{input:15,output:75,provider:"bedrock"},"anthropic.claude-sonnet-4-5-v2:0":{input:3,output:15,provider:"bedrock"},"anthropic.claude-sonnet-4-v1:0":{input:3,output:15,provider:"bedrock"},"anthropic.claude-3-5-haiku-v1:0":{input:1,output:5,provider:"bedrock"},"anthropic.claude-3-opus-20240229-v1:0":{input:15,output:75,provider:"bedrock"},"anthropic.claude-3-sonnet-20240229-v1:0":{input:3,output:15,provider:"bedrock"},"anthropic.claude-3-haiku-20240307-v1:0":{input:.25,output:1.25,provider:"bedrock"},"anthropic.claude-3-5-sonnet-20241022-v2:0":{input:3,output:15,provider:"bedrock"},"azure/gpt-4o":{input:5,output:15,provider:"azure-openai"},"azure/gpt-4o-mini":{input:.15,output:.6,provider:"azure-openai"},"azure/gpt-4-turbo":{input:10,output:30,provider:"azure-openai"},"azure/gpt-4":{input:30,output:60,provider:"azure-openai"},"azure/gpt-35-turbo":{input:.5,output:1.5,provider:"azure-openai"},"azure/text-embedding-ada-002":{input:.1,output:0,provider:"azure-openai"},"azure/text-embedding-3-small":{input:.02,output:0,provider:"azure-openai"},"azure/text-embedding-3-large":{input:.13,output:0,provider:"azure-openai"},"gemini-pro":{input:.5,output:1.5,provider:"gemini"},"gemini-1.0-pro":{input:.5,output:1.5,provider:"gemini"},"gemini-1.5-pro":{input:3.5,output:10.5,provider:"gemini"},"gemini-1.5-pro-latest":{input:3.5,output:10.5,provider:"gemini"},"gemini-1.5-flash":{input:.075,output:.3,provider:"gemini"},"gemini-1.5-flash-latest":{input:.075,output:.3,provider:"gemini"},"gemini-2.0-flash-exp":{input:.075,output:.3,provider:"gemini"},"gemini-ultra":{input:7,output:21,provider:"gemini"},"gemini-1.0-ultra":{input:7,output:21,provider:"gemini"},"text-embedding-004":{input:.025,output:0,provider:"gemini"}},d=class c{records=[];alerts=[];maxRecords;alertCheckInterval;constructor(t=1e4){this.maxRecords=t}static calculateCost(t,r){let e=m[t];if(!e)return{inputCost:0,outputCost:0,totalCost:0,currency:"USD"};let i=r.promptTokens/1e6*e.input,o=r.completionTokens/1e6*e.output;return{inputCost:i,outputCost:o,totalCost:i+o,currency:"USD"}}static getCostPerToken(t){let r=m[t];return r?{input:r.input/1e6,output:r.output/1e6}:{input:0,output:0}}recordUsage(t,r,e,i,o){let n=c.calculateCost(r,e),p={timestamp:new Date,provider:t,model:r,usage:e,cost:n,requestId:i,metadata:o};return this.records.push(p),this.records.length>this.maxRecords&&(this.records=this.records.slice(-this.maxRecords)),this.checkAlerts(),n}getSummary(t){let r=new Date,e=this.getPeriodStart(r,t),i=r,o=this.records.filter(s=>s.timestamp>=e&&s.timestamp<=i),n={claude:0,openai:0,ollama:0,openrouter:0,bedrock:0,"azure-openai":0,gemini:0},p={},u=0,l=0;for(let s of o)u+=s.cost.totalCost,l+=s.usage.totalTokens,n[s.provider]+=s.cost.totalCost,p[s.model]=(p[s.model]||0)+s.cost.totalCost;return{period:t,periodStart:e,periodEnd:i,totalCost:u,byProvider:n,byModel:p,totalTokens:l,totalRequests:o.length}}getCurrentCost(t){return this.getSummary(t).totalCost}getTotalTokens(t){return this.getSummary(t).totalTokens}getUsageByProvider(t,r="all"){let e=this.getPeriodStart(new Date,r),i=this.records.filter(u=>u.provider===t&&u.timestamp>=e),o={},n=0,p=0;for(let u of i)n+=u.cost.totalCost,p+=u.usage.totalTokens,o[u.model]||(o[u.model]={cost:0,tokens:0,requests:0}),o[u.model].cost+=u.cost.totalCost,o[u.model].tokens+=u.usage.totalTokens,o[u.model].requests+=1;return{totalCost:n,totalTokens:p,totalRequests:i.length,models:o}}addAlert(t,r,e){let i=`alert-${Date.now()}-${v().slice(0,12)}`;return this.alerts.push({threshold:t,period:r,onThreshold:e,active:!0}),this.alertCheckInterval||(this.alertCheckInterval=setInterval(()=>this.checkAlerts(),6e4)),i}removeAlert(t){return t>=0&&t<this.alerts.length?(this.alerts.splice(t,1),this.alerts.length===0&&this.alertCheckInterval&&(clearInterval(this.alertCheckInterval),this.alertCheckInterval=void 0),!0):!1}getRecords(){return[...this.records]}importRecords(t){for(let r of t)r.timestamp=new Date(r.timestamp),this.records.push(r);this.records.length>this.maxRecords&&(this.records=this.records.slice(-this.maxRecords))}clear(){this.records=[]}getRecentRequests(t=10){return this.records.slice(-t)}estimateCost(t,r,e){return c.calculateCost(t,{promptTokens:r,completionTokens:e,totalTokens:r+e})}wouldExceedLimit(t,r,e,i,o){let n=this.getCurrentCost(o),p=this.estimateCost(t,r,e);return n+p.totalCost>i}dispose(){this.alertCheckInterval&&(clearInterval(this.alertCheckInterval),this.alertCheckInterval=void 0)}getPeriodStart(t,r){let e=new Date(t);switch(r){case"minute":e.setSeconds(0,0),e.setMinutes(e.getMinutes()-1);break;case"hour":e.setMinutes(0,0,0),e.setHours(e.getHours()-1);break;case"day":e.setHours(0,0,0,0);break;case"week":e.setHours(0,0,0,0),e.setDate(e.getDate()-7);break;case"month":e.setHours(0,0,0,0),e.setDate(1);break;case"all":return new Date(0)}return e}checkAlerts(){for(let t of this.alerts){if(!t.active)continue;let r=this.getSummary(t.period);if(r.totalCost>=t.threshold){t.active=!1;try{t.onThreshold(r)}catch(e){console.error("Cost alert callback error:",e)}}}}},a;function h(){return a||(a=new d),a}function b(){a&&(a.dispose(),a=void 0)}export{m as a,d as b,h as c,b as d};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.1");process.exit(0)}
|
|
2
|
+
import{f as d}from"./chunk-E33KQBMW.js";import{a as u,c as g}from"./chunk-UN4PA4M2.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
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.1");process.exit(0)}
|
|
2
|
+
import{a as S}from"./chunk-U5JQGRHZ.js";import{c as g}from"./chunk-A57BEPL7.js";import{S as T,b as l}from"./chunk-MZ54VM6A.js";S();T();import{createRequire as B}from"module";var G=B(import.meta.url),d=class{validateTransfer(e,t){return{approved:!0}}};function R(){if(l().useCoherenceGate)try{let{CoherenceGate:o}=G("./coherence-gate.js");return new o}catch{}return new d}S();var x=g.create("transfer-verification"),A={maxSourceRegression:.05,minTargetImprovement:0,maxSourceConfidenceRegression:.1},b=class{config;constructor(e={}){this.config={...A,...e}}verifyTransfer(e){let t=e.sourcePerformanceAfter.successRate-e.sourcePerformanceBefore.successRate,r=e.targetPerformanceAfter.successRate-e.targetPerformanceBefore.successRate,n=e.sourcePerformanceAfter.avgConfidence-e.sourcePerformanceBefore.avgConfidence,a=e.targetPerformanceAfter.avgConfidence-e.targetPerformanceBefore.avgConfidence,s=t>=-this.config.maxSourceRegression&&n>=-this.config.maxSourceConfidenceRegression,c=r>=this.config.minTargetImprovement,u=s&&c,m;if(!u){let i=[];s||i.push(`source domain regressed: successRate delta=${t.toFixed(4)}, confidence delta=${n.toFixed(4)}`),c||i.push(`target domain did not improve: successRate delta=${r.toFixed(4)}`),m=i.join("; ")}return u?x.debug("Transfer verification passed",{transferId:e.transferId,sourceDelta:t,targetDelta:r}):x.warn("Transfer verification failed",{transferId:e.transferId,sourceDomain:e.sourceDomain,targetDomain:e.targetDomain,sourceDelta:t,targetDelta:r,failureReason:m}),{passed:u,sourceStable:s,targetImproved:c,sourceDelta:t,targetDelta:r,sourceConfidenceDelta:n,targetConfidenceDelta:a,failureReason:m}}getConfig(){return{...this.config}}};function M(o){return new b(o)}T();var p=class{alphas=new Map;betas=new Map;sample(e){let t=this.alphas.get(e)??1,r=this.betas.get(e)??1;return this.sampleBeta(t,r)}update(e,t){t?this.alphas.set(e,(this.alphas.get(e)??1)+1):this.betas.set(e,(this.betas.get(e)??1)+1)}getMean(e){let t=this.alphas.get(e)??1,r=this.betas.get(e)??1;return t/(t+r)}getObservationCount(e){let t=this.alphas.get(e)??1,r=this.betas.get(e)??1;return t-1+(r-1)}getAlpha(e){return this.alphas.get(e)??1}getBeta(e){return this.betas.get(e)??1}sampleBeta(e,t){let r=this.sampleGamma(e),n=this.sampleGamma(t);return r+n===0?.5:r/(r+n)}sampleGamma(e){if(e<1){let n=Math.random();return this.sampleGamma(e+1)*Math.pow(n,1/e)}let t=e-1/3,r=1/Math.sqrt(9*t);for(;;){let n,a;do n=this.standardNormal(),a=1+r*n;while(a<=0);a=a*a*a;let s=Math.random();if(s<1-.0331*n*n*n*n||Math.log(s)<.5*n*n+t*(1-a+Math.log(a)))return t*a}}standardNormal(){let e=Math.random(),t=Math.random();return Math.sqrt(-2*Math.log(e||1e-10))*Math.cos(2*Math.PI*t)}};var I={threshold:5,slack:.5,resetOnAlarm:!0,warmupSamples:20},h=class{config;states=new Map;constructor(e={}){this.config={...I,...e}}update(e,t){let r=this.getOrCreateState(e);if(r.samplesSinceReset++,r.mu===null)return r.warmupSum+=t,r.warmupCount++,r.warmupCount>=this.config.warmupSamples&&(r.mu=r.warmupSum/r.warmupCount),{driftDetected:!1,cumulativeSum:0,direction:"none",samplesSinceReset:r.samplesSinceReset};r.sPlus=Math.max(0,r.sPlus+(t-r.mu-this.config.slack)),r.sMinus=Math.max(0,r.sMinus+(-t+r.mu-this.config.slack));let n=Math.max(r.sPlus,r.sMinus),a=!1,s="none";r.sPlus>this.config.threshold?(a=!0,s="positive"):r.sMinus>this.config.threshold&&(a=!0,s="negative");let c={driftDetected:a,cumulativeSum:n,direction:s,samplesSinceReset:r.samplesSinceReset};return a&&this.config.resetOnAlarm&&(r.sPlus=0,r.sMinus=0,r.samplesSinceReset=0),c}reset(e){e?this.states.delete(e):this.states.clear()}getState(e){let t=this.states.get(e);if(!t)return{driftDetected:!1,cumulativeSum:0,direction:"none",samplesSinceReset:0};let r=Math.max(t.sPlus,t.sMinus),n="none";return t.sPlus>this.config.threshold?n="positive":t.sMinus>this.config.threshold&&(n="negative"),{driftDetected:t.sPlus>this.config.threshold||t.sMinus>this.config.threshold,cumulativeSum:r,direction:n,samplesSinceReset:t.samplesSinceReset}}getOrCreateState(e){let t=this.states.get(e);return t||(t={sPlus:0,sMinus:0,samplesSinceReset:0,warmupSum:0,warmupCount:0,mu:null},this.states.set(e,t)),t}};var w=g.create("domain-transfer"),V={minTransferProbability:.3,explorationWarmup:5,verification:{},maxHistorySize:1e3,useMetaLearningEnhancements:!0},y=class{constructor(e=100){this.decayThreshold=e}getDecayMultiplier(e){return e<=0?1:Math.pow(.5,e/this.decayThreshold)}applyDecay(e,t,r){return t+(e-t)*this.getDecayMultiplier(r)}},v=class{cusum;outcomes=[];windowSize;constructor(e=20){this.windowSize=e,this.cusum=new h({threshold:3,slack:.1,resetOnAlarm:!1,warmupSamples:Math.min(10,Math.floor(e/2))})}record(e){this.outcomes.push(e),this.outcomes.length>this.windowSize*2&&this.outcomes.splice(0,this.outcomes.length-this.windowSize*2);let t=this.getCurrentRate();this.cusum.update("learn",t)}isPlateaued(){return this.outcomes.length<this.windowSize?!1:!this.cusum.getState("learn").driftDetected}getCurrentRate(){if(this.outcomes.length===0)return 0;let e=this.outcomes.slice(-this.windowSize);return e.filter(Boolean).length/e.length}getOutcomeCount(){return this.outcomes.length}getCusumState(){return this.cusum.getState("learn")}},D=class{front=[];dominates(e,t){let r=e.successRate>=t.successRate&&e.speed>=t.speed&&e.confidence>=t.confidence,n=e.successRate>t.successRate||e.speed>t.speed||e.confidence>t.confidence;return r&&n}add(e){for(let t=this.front.length-1;t>=0;t--)this.dominates(e,this.front[t])&&this.front.splice(t,1);this.front.some(t=>this.dominates(t,e))||this.front.push(e)}getFront(){return[...this.front]}isNonDominated(e){return!this.front.some(t=>this.dominates(t,e))}},C=class{constructor(e=.2){this.bonusScale=e}triedPairs=new Set;markTried(e){this.triedPairs.add(e)}isTried(e){return this.triedPairs.has(e)}getBonus(e){return this.triedPairs.has(e)?0:this.bonusScale}apply(e,t){return Math.min(1,e+this.getBonus(t))}getTriedCount(){return this.triedPairs.size}},P=class{config;sampler;verifier;coherenceGate;transferHistory=[];affinityScores=new Map;performanceProvider=null;transferExecutor=null;nativeModule=null;decayingBeta;plateauDetector;paretoFront;curiosityBonus;constructor(e={}){this.config={...V,...e},this.sampler=new p,this.verifier=M(this.config.verification),this.coherenceGate=R(),this.decayingBeta=new y,this.plateauDetector=new v,this.paretoFront=new D,this.curiosityBonus=new C,this.tryLoadNativeModule()}evaluateTransfer(e,t){if(!this.isEnabled())return this.createRejectedCandidate(e,t);let r=this.makePairKey(e,t),n=this.sampler.sample(r),s=this.sampler.getObservationCount(r)<this.config.explorationWarmup,c=this.getAffinityScore(e,t);if(this.isMetaLearningEnabled()){let u=this.sampler.getMean(r),m=this.sampler.getAlpha(r)-1;n=this.decayingBeta.applyDecay(n,u,m),n=this.curiosityBonus.apply(n,r)}return{sourceDomain:e,targetDomain:t,sampledProbability:n,affinityScore:c,isExploration:s,pairKey:r}}executeTransfer(e){let t=`transfer-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,r=this.coherenceGate.validateTransfer({domain:e.sourceDomain},e.targetDomain);if(!r.approved)return w.info("Transfer blocked by coherence gate",{transferId:t,source:e.sourceDomain,target:e.targetDomain,reason:r.rejectionReason}),this.createBlockedResult(t,e,r);let n=this.getPerformanceSnapshot(e.sourceDomain),a=this.getPerformanceSnapshot(e.targetDomain),s=this.computeSqrtDampening(e),c=this.doTransfer(e.sourceDomain,e.targetDomain,s),u=this.getPerformanceSnapshot(e.sourceDomain),m=this.getPerformanceSnapshot(e.targetDomain),i=this.verifier.verifyTransfer({transferId:t,sourceDomain:e.sourceDomain,targetDomain:e.targetDomain,sourcePerformanceBefore:n,sourcePerformanceAfter:u,targetPerformanceBefore:a,targetPerformanceAfter:m}),f=c&&i.passed;if(this.sampler.update(e.pairKey,f),this.updateAffinityScore(e.pairKey,f),this.isMetaLearningEnabled()){this.plateauDetector.record(f),this.curiosityBonus.markTried(e.pairKey);let F=this.sampler.getMean(e.pairKey);this.paretoFront.add({pairKey:e.pairKey,successRate:F,speed:1/(1+s),confidence:this.getAffinityScore(e.sourceDomain,e.targetDomain)})}return this.addToHistory({transferId:t,sourceDomain:e.sourceDomain,targetDomain:e.targetDomain,success:f,sampledProbability:e.sampledProbability,dampeningFactor:s,sourceDelta:i.sourceDelta,targetDelta:i.targetDelta,timestamp:Date.now()}),w.info("Transfer completed",{transferId:t,source:e.sourceDomain,target:e.targetDomain,success:f,dampeningFactor:s.toFixed(4),sourceDelta:i.sourceDelta.toFixed(4),targetDelta:i.targetDelta.toFixed(4)}),{transferId:t,candidate:e,success:f,dampeningFactor:s,verification:i,coherenceResult:r,sourcePerformanceBefore:n,sourcePerformanceAfter:u,targetPerformanceBefore:a,targetPerformanceAfter:m,timestamp:Date.now()}}getAffinityScore(e,t){return this.affinityScores.get(this.makePairKey(e,t))??.5}getTransferHistory(){return[...this.transferHistory]}getExpectedSuccessRate(e,t){return this.sampler.getMean(this.makePairKey(e,t))}getObservationCount(e,t){return this.sampler.getObservationCount(this.makePairKey(e,t))}setPerformanceProvider(e){this.performanceProvider=e}setTransferExecutor(e){this.transferExecutor=e}getSampler(){return this.sampler}getCoherenceGate(){return this.coherenceGate}getDecayingBeta(){return this.decayingBeta}getPlateauDetector(){return this.plateauDetector}getParetoFront(){return this.paretoFront}getCuriosityBonus(){return this.curiosityBonus}isLearningPlateaued(){return this.plateauDetector.isPlateaued()}isEnabled(){return l().useCrossDomainTransfer===!0}isMetaLearningEnabled(){return this.config.useMetaLearningEnhancements===!0&&l().useMetaLearningEnhancements!==!1}makePairKey(e,t){return`${e}->${t}`}computeSqrtDampening(e){let t=this.sampler.getObservationCount(e.pairKey);return Math.sqrt(t/(t+this.config.explorationWarmup))}doTransfer(e,t,r){return this.transferExecutor?this.transferExecutor(e,t,r):!0}getPerformanceSnapshot(e){return this.performanceProvider?this.performanceProvider(e):{domain:e,successRate:.5,avgConfidence:.5,patternCount:0,timestamp:Date.now()}}updateAffinityScore(e,t){let r=this.affinityScores.get(e)??.5;this.affinityScores.set(e,.2*(t?1:0)+.8*r)}addToHistory(e){for(this.transferHistory.push(e);this.transferHistory.length>this.config.maxHistorySize;)this.transferHistory.shift()}createBlockedResult(e,t,r){let n={domain:"",successRate:0,avgConfidence:0,patternCount:0,timestamp:Date.now()};return{transferId:e,candidate:t,success:!1,dampeningFactor:0,verification:{passed:!1,sourceStable:!1,targetImproved:!1,sourceDelta:0,targetDelta:0,sourceConfidenceDelta:0,targetConfidenceDelta:0,failureReason:`Coherence gate rejected: ${r.rejectionReason??"unknown"}`},coherenceResult:r,sourcePerformanceBefore:{...n,domain:t.sourceDomain},sourcePerformanceAfter:{...n,domain:t.sourceDomain},targetPerformanceBefore:{...n,domain:t.targetDomain},targetPerformanceAfter:{...n,domain:t.targetDomain},timestamp:Date.now()}}createRejectedCandidate(e,t){return{sourceDomain:e,targetDomain:t,sampledProbability:0,affinityScore:0,isExploration:!1,pairKey:this.makePairKey(e,t)}}tryLoadNativeModule(){this.nativeModule=null}};function J(o){return new P(o)}export{p as a,h as b,V as c,y as d,v as e,D as f,C as g,P as h,J as i};
|