agentic-qe 3.9.16 → 3.9.18
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 +34 -0
- package/README.md +65 -0
- package/assets/skills/skills-manifest.json +1 -1
- package/dist/cli/bundle.js +5 -5
- package/dist/cli/chunks/adapter-C7AKAAPC.js +2 -0
- package/dist/cli/chunks/{agent-booster-wasm-IECTFMRK.js → agent-booster-wasm-RJHBIG5V.js} +2 -2
- package/dist/cli/chunks/{agent-handler-HLLTKZ5G.js → agent-handler-CXS6EE2V.js} +2 -2
- package/dist/cli/chunks/{agent-memory-branch-WJUD3DS4.js → agent-memory-branch-7NV5DD5A.js} +2 -2
- package/dist/cli/chunks/aqe-learning-engine-7P3AXQNO.js +2 -0
- package/dist/cli/chunks/{audit-3DLZNWHO.js → audit-3NWGSPJW.js} +2 -2
- package/dist/cli/chunks/base-GIDVLEPA.js +2 -0
- package/dist/cli/chunks/{better-sqlite3-Q356NEQ6.js → better-sqlite3-NXOMSJDC.js} +2 -2
- package/dist/cli/chunks/{brain-handler-MX2HP7LO.js → brain-handler-6N5WWZVA.js} +3 -3
- package/dist/cli/chunks/{branch-enumerator-Z3TF3HVO.js → branch-enumerator-I7UTOCAW.js} +2 -2
- package/dist/cli/chunks/{browser-Z6PQ7FTO.js → browser-6VOFWA52.js} +2 -2
- package/dist/cli/chunks/browser-workflow-DAUS4Z5V.js +2 -0
- package/dist/cli/chunks/{chunk-2MJEAEOW.js → chunk-27MW2RFA.js} +2 -2
- package/dist/cli/chunks/{chunk-GP7IXB3E.js → chunk-2A4JCRAW.js} +2 -2
- package/dist/cli/chunks/{chunk-G5DMEEQQ.js → chunk-3DLD7OMF.js} +1 -1
- package/dist/cli/chunks/{chunk-TPRYLARW.js → chunk-3GA7M5NK.js} +2 -2
- package/dist/cli/chunks/{chunk-46K7ALFU.js → chunk-4666TC3P.js} +2 -2
- package/dist/cli/chunks/{chunk-LSA4XGSE.js → chunk-4BIWQLD3.js} +2 -2
- package/dist/cli/chunks/{chunk-HVAW64YW.js → chunk-4ELLGWTS.js} +2 -2
- package/dist/cli/chunks/{chunk-HFGCLV56.js → chunk-4U2JKV44.js} +1 -1
- package/dist/cli/chunks/chunk-4XYQJ4LQ.js +2 -0
- package/dist/cli/chunks/{chunk-WSKASZYC.js → chunk-54TOOHER.js} +2 -2
- package/dist/cli/chunks/{chunk-7NMLIJHL.js → chunk-5ROA7KOT.js} +1 -1
- package/dist/cli/chunks/{chunk-SMNOZEM7.js → chunk-5SZLQCFP.js} +2 -2
- package/dist/cli/chunks/{chunk-3ZGYB23S.js → chunk-6BGSH2YR.js} +1 -1
- package/dist/cli/chunks/{chunk-N5ZTPAX7.js → chunk-6G3RNT5H.js} +2 -2
- package/dist/cli/chunks/{chunk-MTF6ABUH.js → chunk-6IBFYVLK.js} +2 -2
- package/dist/cli/chunks/{chunk-KR7S4IZZ.js → chunk-6KTF7QB3.js} +2 -2
- package/dist/cli/chunks/{chunk-ZCE6JNRI.js → chunk-6QSB4XOL.js} +2 -2
- package/dist/cli/chunks/{chunk-4PFHQH4B.js → chunk-6ZMQL3U6.js} +2 -2
- package/dist/cli/chunks/{chunk-UT4CXF6C.js → chunk-7GGSUXVM.js} +2 -2
- package/dist/cli/chunks/{chunk-XQ6WIPDC.js → chunk-7OGUAZGJ.js} +1 -1
- package/dist/cli/chunks/{chunk-OP7X434R.js → chunk-7XLTLFP5.js} +2 -2
- package/dist/cli/chunks/{chunk-7DP2IQ6F.js → chunk-7ZIKFJ6X.js} +2 -2
- package/dist/cli/chunks/{chunk-TUPFBZKO.js → chunk-A26GU6YU.js} +1 -1
- package/dist/cli/chunks/{chunk-TWEBJWJI.js → chunk-AGPZVE6B.js} +2 -2
- package/dist/cli/chunks/{chunk-7MF6LVLH.js → chunk-AMRUZ6XG.js} +2 -2
- package/dist/cli/chunks/{chunk-FLWIEPAT.js → chunk-AZGESIFV.js} +1 -1
- package/dist/cli/chunks/{chunk-FKQV52TC.js → chunk-B6BAK2JI.js} +2 -2
- package/dist/cli/chunks/{chunk-CR7LLS26.js → chunk-BADBKGZE.js} +2 -2
- package/dist/cli/chunks/{chunk-WVHH3OQ4.js → chunk-BFM47L3X.js} +2 -2
- package/dist/cli/chunks/{chunk-MQHP65QB.js → chunk-BGSYFAEJ.js} +3 -3
- package/dist/cli/chunks/{chunk-JCQ5PXVM.js → chunk-BRWWIY6O.js} +2 -2
- package/dist/cli/chunks/{chunk-LWG7LKOK.js → chunk-BSQTOKNR.js} +1 -1
- package/dist/cli/chunks/{chunk-HON4X4Z3.js → chunk-BXTHB2A2.js} +2 -2
- package/dist/cli/chunks/{chunk-XAULPLOC.js → chunk-BY44ODHD.js} +4 -4
- package/dist/cli/chunks/{chunk-7IF4LRX2.js → chunk-CCM7MBLA.js} +2 -2
- package/dist/cli/chunks/{chunk-TFBEX7ED.js → chunk-CSYQKVZY.js} +1 -1
- package/dist/cli/chunks/{chunk-RVQXMMRO.js → chunk-D7SS56EG.js} +2 -2
- package/dist/cli/chunks/{chunk-NLU4XJBN.js → chunk-DC3PADV3.js} +1 -1
- package/dist/cli/chunks/{chunk-QEKZA2NJ.js → chunk-DCB2VUYM.js} +1 -1
- package/dist/cli/chunks/{chunk-HJUC2DE6.js → chunk-DOSDUAVZ.js} +2 -2
- package/dist/cli/chunks/{chunk-T36IXY5W.js → chunk-DQCWNCOT.js} +2 -2
- package/dist/cli/chunks/{chunk-FQTUUZVK.js → chunk-EN2A2CVT.js} +1 -1
- package/dist/cli/chunks/{chunk-IUQ6HE2J.js → chunk-ENYQUSSK.js} +2 -2
- package/dist/cli/chunks/{chunk-HN6GVQ4Q.js → chunk-EZN7QMOZ.js} +4 -4
- package/dist/cli/chunks/{chunk-VOAECU7B.js → chunk-F7XU7KZL.js} +2 -2
- package/dist/cli/chunks/{chunk-BEE5KXQT.js → chunk-FDDB7QTM.js} +1 -1
- package/dist/cli/chunks/{chunk-NOJVROCD.js → chunk-FKNYOKIK.js} +1 -1
- package/dist/cli/chunks/{chunk-W6TMZY5R.js → chunk-FTIHPDWV.js} +2 -2
- package/dist/cli/chunks/{chunk-NCXXXZGL.js → chunk-G2H4W7NN.js} +1 -1
- package/dist/cli/chunks/{chunk-666L7MC2.js → chunk-H5JZZH2C.js} +2 -2
- package/dist/cli/chunks/{chunk-H3JEGAFC.js → chunk-HLXPD4Y2.js} +39 -38
- package/dist/cli/chunks/{chunk-JZOMOYHZ.js → chunk-HZKY5KPB.js} +1 -1
- package/dist/cli/chunks/{chunk-3K4IX7L4.js → chunk-I3POPZT5.js} +2 -2
- package/dist/cli/chunks/{chunk-J2ERTUDX.js → chunk-IJPTWPXG.js} +1 -1
- package/dist/cli/chunks/{chunk-3CAPNE2H.js → chunk-IS2PMHB5.js} +2 -2
- package/dist/cli/chunks/{chunk-3SLFWPRE.js → chunk-J7BG55VG.js} +3 -3
- package/dist/cli/chunks/{chunk-NIXMFJJC.js → chunk-JBW2A2O6.js} +2 -2
- package/dist/cli/chunks/{chunk-7JFSMXIA.js → chunk-JD6KE6DJ.js} +2 -2
- package/dist/cli/chunks/{chunk-PNZADZSI.js → chunk-JGNVI5UB.js} +3 -3
- package/dist/cli/chunks/{chunk-KLVS6FT2.js → chunk-JMK5OCWL.js} +2 -2
- package/dist/cli/chunks/{chunk-JUKCBZCZ.js → chunk-JZG23IPV.js} +1 -1
- package/dist/cli/chunks/{chunk-BCT26J7X.js → chunk-JZTB35EQ.js} +1 -1
- package/dist/cli/chunks/{chunk-6XKZ62O7.js → chunk-K5NFP7B5.js} +2 -2
- package/dist/cli/chunks/{chunk-7PHYOV2X.js → chunk-KFITGSW3.js} +2 -2
- package/dist/cli/chunks/{chunk-LJINNQNN.js → chunk-KMHGQD76.js} +2 -2
- package/dist/cli/chunks/{chunk-4ZN4GM7W.js → chunk-KV6PIOHN.js} +1 -1
- package/dist/cli/chunks/{chunk-LVA53A5R.js → chunk-KYLE6ZSC.js} +4 -4
- package/dist/cli/chunks/chunk-LVABI4OA.js +2 -0
- package/dist/cli/chunks/{chunk-T7VIUEKI.js → chunk-MBGWDELE.js} +2 -2
- package/dist/cli/chunks/{chunk-MFRC267A.js → chunk-MDCTQOUJ.js} +1 -1
- package/dist/cli/chunks/chunk-MJ7UYPGY.js +15 -0
- package/dist/cli/chunks/{chunk-LVK2PDUW.js → chunk-MLVVYUFS.js} +1 -1
- package/dist/cli/chunks/{chunk-ZCZJYM42.js → chunk-NBQW7MXF.js} +1 -1
- package/dist/cli/chunks/{chunk-VK2GKQYI.js → chunk-NKOLFLXF.js} +2 -2
- package/dist/cli/chunks/{chunk-WVFLNGOK.js → chunk-ODGACHEZ.js} +2 -2
- package/dist/cli/chunks/{chunk-6V5P2VMQ.js → chunk-OXL6JSVR.js} +45 -44
- package/dist/cli/chunks/{chunk-5E7FVOOG.js → chunk-P6HIDCTQ.js} +1 -1
- package/dist/cli/chunks/{chunk-3H657FNU.js → chunk-PM77Z4PR.js} +2 -2
- package/dist/cli/chunks/{chunk-77OVXVN2.js → chunk-QGSELG75.js} +2 -2
- package/dist/cli/chunks/{chunk-PQLT3X6X.js → chunk-QTNDHCZ7.js} +3 -3
- package/dist/cli/chunks/{chunk-3EUA73H6.js → chunk-QTUTQLOY.js} +2 -2
- package/dist/cli/chunks/{chunk-AFLQFUXA.js → chunk-QW2RFI73.js} +2 -2
- package/dist/cli/chunks/{chunk-RYCAVZSD.js → chunk-R3U3ARVJ.js} +2 -2
- package/dist/cli/chunks/{chunk-7V2Z3PUJ.js → chunk-RGLCMGNZ.js} +2 -2
- package/dist/cli/chunks/{chunk-2KCMS4UW.js → chunk-RHYGRUNU.js} +3 -3
- package/dist/cli/chunks/{chunk-DF3DZP7H.js → chunk-RI3NTZ2I.js} +2 -2
- package/dist/cli/chunks/{chunk-H4BZJVKU.js → chunk-RPT7HCMH.js} +2 -2
- package/dist/cli/chunks/{chunk-P4IYRPCB.js → chunk-S2XBAOXE.js} +1 -1
- package/dist/cli/chunks/{chunk-PPUEXTH2.js → chunk-SQHM6WUF.js} +3 -3
- package/dist/cli/chunks/{chunk-GB6D3SSY.js → chunk-TFUWIKGZ.js} +2 -2
- package/dist/cli/chunks/{chunk-EFTK4ZVP.js → chunk-TPL3CBMS.js} +1 -1
- package/dist/cli/chunks/{chunk-RFLSJ7OL.js → chunk-UFGFV4BO.js} +2 -2
- package/dist/cli/chunks/{chunk-V2ELGHLG.js → chunk-UNPTSPAO.js} +2 -2
- package/dist/cli/chunks/{chunk-FEQ5RDQL.js → chunk-UPP5V7Y3.js} +2 -2
- package/dist/cli/chunks/{chunk-ZXLF3IKT.js → chunk-V2N7KWT7.js} +1 -1
- package/dist/cli/chunks/{chunk-4CFQZHUC.js → chunk-VRHKEJR6.js} +3 -3
- package/dist/cli/chunks/{chunk-MECDNFOJ.js → chunk-VW7FKTFO.js} +2 -2
- package/dist/cli/chunks/{chunk-VNAAXZGF.js → chunk-VXQK4GKV.js} +1 -1
- package/dist/cli/chunks/{chunk-DBCN7R63.js → chunk-VZO5I23B.js} +1 -1
- package/dist/cli/chunks/{chunk-XKMMFQSJ.js → chunk-WC5A7C5L.js} +1 -1
- package/dist/cli/chunks/{chunk-JNXIYHLI.js → chunk-WH7ZOJCF.js} +1 -1
- package/dist/cli/chunks/{chunk-TR4NPMRW.js → chunk-WKQSZTU6.js} +2 -2
- package/dist/cli/chunks/{chunk-OE7SGIX2.js → chunk-WMJCFDTA.js} +2 -2
- package/dist/cli/chunks/{chunk-66BUIFFH.js → chunk-X2T4TI7D.js} +2 -2
- package/dist/cli/chunks/{chunk-HXF4FUPY.js → chunk-XBWVHO6G.js} +2 -2
- package/dist/cli/chunks/{chunk-L2GANTQN.js → chunk-XSLKR2DM.js} +2 -2
- package/dist/cli/chunks/{chunk-5A5XANSD.js → chunk-XTCV5UOJ.js} +2 -2
- package/dist/cli/chunks/{chunk-BNDK7JRW.js → chunk-YNVVRND7.js} +2 -2
- package/dist/cli/chunks/{chunk-WKLSXJD4.js → chunk-YQL6JH2Y.js} +2 -2
- package/dist/cli/chunks/{chunk-AA6IUBCM.js → chunk-YZIOM7JL.js} +2 -2
- package/dist/cli/chunks/{chunk-UH7TV6BY.js → chunk-Z4YHL4JU.js} +1 -1
- package/dist/cli/chunks/{chunk-DJPS7H2M.js → chunk-ZHA5Z5V4.js} +1 -1
- package/dist/cli/chunks/{chunk-QKQAQPXY.js → chunk-ZJEVL5O3.js} +2 -2
- package/dist/cli/chunks/{chunk-MJKFU6A6.js → chunk-ZURHHRSA.js} +2 -2
- package/dist/cli/chunks/{chunk-W4ZV6LAJ.js → chunk-ZWR4PZ4Z.js} +2 -2
- package/dist/cli/chunks/{ci-TTP5HJSW.js → ci-LYAVZLM3.js} +2 -2
- package/dist/cli/chunks/{ci-output-TKESU45X.js → ci-output-L7TR2NCN.js} +2 -2
- package/dist/cli/chunks/{circuit-breaker-GFRV5R7E.js → circuit-breaker-AQOGJGKI.js} +2 -2
- package/dist/cli/chunks/{claude-flow-setup-LY6MADFA.js → claude-flow-setup-SO2ZN26K.js} +2 -2
- package/dist/cli/chunks/client-LIKTMSIP.js +2 -0
- package/dist/cli/chunks/{cline-installer-OSAILLDH.js → cline-installer-XCXFH4UR.js} +2 -2
- package/dist/cli/chunks/{code-ASRSOGYH.js → code-3Z2HMS5I.js} +2 -2
- package/dist/cli/chunks/{code-index-extractor-AMLGVHB7.js → code-index-extractor-KE362AJX.js} +2 -2
- package/dist/cli/chunks/{codex-installer-3CKH3WV4.js → codex-installer-GTD3GFTF.js} +2 -2
- package/dist/cli/chunks/{completions-MXNPWLOE.js → completions-EDCXRRJO.js} +2 -2
- package/dist/cli/chunks/{complexity-analyzer-2Z347PXF.js → complexity-analyzer-QMN3V6D3.js} +2 -2
- package/dist/cli/chunks/{continuedev-installer-LE7K745N.js → continuedev-installer-U6HN376C.js} +2 -2
- package/dist/cli/chunks/{copilot-installer-CHJL3275.js → copilot-installer-54PZIREM.js} +2 -2
- package/dist/cli/chunks/{cost-tracker-C3ZWNNSV.js → cost-tracker-33O475QA.js} +2 -2
- package/dist/cli/chunks/{coverage-6JOXBVDL.js → coverage-B7E545AJ.js} +3 -3
- package/dist/cli/chunks/cross-domain-router-SSBT32Q3.js +2 -0
- package/dist/cli/chunks/{cursor-installer-RKCNWO42.js → cursor-installer-LKKSPZUM.js} +2 -2
- package/dist/cli/chunks/{daemon-XXWOT6TM.js → daemon-DVOHWXUR.js} +3 -3
- package/dist/cli/chunks/{dag-attention-scheduler-37MG6XR4.js → dag-attention-scheduler-EQOHQBUG.js} +2 -2
- package/dist/cli/chunks/{detect-QOTL36CE.js → detect-OCB2XT6C.js} +2 -2
- package/dist/cli/chunks/dist-node-HSG4QK4G.js +2 -0
- package/dist/cli/chunks/{domain-handler-TJNLNJ7Z.js → domain-handler-USGF4CIG.js} +2 -2
- package/dist/cli/chunks/{domain-transfer-FDHC2MGH.js → domain-transfer-OUERZRGL.js} +2 -2
- package/dist/cli/chunks/dream-FAHB6BWB.js +2 -0
- package/dist/cli/chunks/{eval-JP7CLUTD.js → eval-LHYXXWFK.js} +2 -2
- package/dist/cli/chunks/{fast-paths-CWTVLIIC.js → fast-paths-UTK7BN63.js} +2 -2
- package/dist/cli/chunks/{feature-flags-H2UU53L4.js → feature-flags-XB6ALB3X.js} +2 -2
- package/dist/cli/chunks/{feature-flags-SKFBAHR3.js → feature-flags-XEP6B4GN.js} +2 -2
- package/dist/cli/chunks/{file-discovery-RWVGKIDB.js → file-discovery-O4DUCNHK.js} +2 -2
- package/dist/cli/chunks/{fleet-JOSUYRTZ.js → fleet-37NGGRJI.js} +3 -3
- package/dist/cli/chunks/{gnn-wrapper-WNOZFTDD.js → gnn-wrapper-5E7T3IQX.js} +2 -2
- package/dist/cli/chunks/{heartbeat-handler-73YSR6K7.js → heartbeat-handler-Q44PCI7K.js} +4 -4
- package/dist/cli/chunks/{heartbeat-scheduler-EN52JZUX.js → heartbeat-scheduler-6JPB2AQS.js} +2 -2
- package/dist/cli/chunks/hnsw-adapter-GQM3ONQE.js +2 -0
- package/dist/cli/chunks/hnsw-index-XF3NY4R4.js +2 -0
- package/dist/cli/chunks/{hnsw-legacy-bridge-PWD6DXS4.js → hnsw-legacy-bridge-B55GGQYA.js} +2 -2
- package/dist/cli/chunks/{hnswlib-node-VAZOCNY7.js → hnswlib-node-B3D2XIL5.js} +2 -2
- package/dist/cli/chunks/hooks-MOBQSJLJ.js +101 -0
- package/dist/cli/chunks/{hybrid-router-6W323WKW.js → hybrid-router-RV34PYQD.js} +2 -2
- package/dist/cli/chunks/{hypergraph-engine-R2N4C24I.js → hypergraph-engine-FT5YK5RF.js} +2 -2
- package/dist/cli/chunks/{hypergraph-handler-AY4YZDOG.js → hypergraph-handler-EUS6MIYW.js} +3 -3
- package/dist/cli/chunks/impact-analyzer-V6PBIMZH.js +2 -0
- package/dist/cli/chunks/{init-handler-UDBW4P3Z.js → init-handler-3MV32TKZ.js} +6 -6
- package/dist/cli/chunks/init-wizard-7ROJWLEO.js +2 -0
- package/dist/cli/chunks/kernel-AOUBGDXU.js +2 -0
- package/dist/cli/chunks/{kilocode-installer-J2NZUDEQ.js → kilocode-installer-RZPRXQI2.js} +2 -2
- package/dist/cli/chunks/{kiro-installer-AHOOKFQH.js → kiro-installer-BGDBNZHI.js} +2 -2
- package/dist/cli/chunks/knowledge-graph-SJA3YGMQ.js +2 -0
- package/dist/cli/chunks/{learning-VC7X2HKA.js → learning-KNEBWLEZ.js} +3 -3
- package/dist/cli/chunks/{llm-router-3PU7CH5P.js → llm-router-Q2VQPOQ3.js} +4 -4
- package/dist/cli/chunks/{load-WB4JD6X7.js → load-RL53SYBD.js} +2 -2
- package/dist/cli/chunks/load-test-NSHIGHCV.js +2 -0
- package/dist/cli/chunks/{mcp-QUU2DYYK.js → mcp-GTINFFUF.js} +2 -2
- package/dist/cli/chunks/{memory-UAEWPG34.js → memory-STPMUUAK.js} +5 -5
- package/dist/cli/chunks/memory-backend-SZAYMQVP.js +2 -0
- package/dist/cli/chunks/{memory-handlers-3FBXIZG4.js → memory-handlers-LWX3LPVF.js} +2 -2
- package/dist/cli/chunks/{multi-model-executor-CIUHXR43.js → multi-model-executor-36ZYYDA6.js} +2 -2
- package/dist/cli/chunks/{opencode-installer-VV6RIHNR.js → opencode-installer-KTCQKS2K.js} +2 -2
- package/dist/cli/chunks/{orchestrator-WV27PZZM.js → orchestrator-6EGOOXQG.js} +6 -6
- package/dist/cli/chunks/{pipeline-JRBCX2U3.js → pipeline-WSLAIOYC.js} +2 -2
- package/dist/cli/chunks/{platform-TUPMH4ND.js → platform-MNUN663B.js} +2 -2
- package/dist/cli/chunks/{plugin-H757CYQK.js → plugin-PLDTG4A2.js} +2 -2
- package/dist/cli/chunks/{prime-radiant-advanced-wasm-5BWO25RA.js → prime-radiant-advanced-wasm-B4UFONWB.js} +2 -2
- package/dist/cli/chunks/protocol-executor-22KKAYX2.js +2 -0
- package/dist/cli/chunks/{protocol-handler-Z6DCNTUU.js → protocol-handler-VAVLLAI2.js} +2 -2
- package/dist/cli/chunks/{prove-4OGWFOUM.js → prove-WVNPDWUC.js} +2 -2
- package/dist/cli/chunks/{provider-manager-K736L6LN.js → provider-manager-VJF4D6AW.js} +2 -2
- package/dist/cli/chunks/qe-reasoning-bank-N7ZXOAEN.js +2 -0
- package/dist/cli/chunks/{quality-YFLEATGZ.js → quality-LTMHVQBG.js} +2 -2
- package/dist/cli/chunks/queen-coordinator-BC54OCHH.js +2 -0
- package/dist/cli/chunks/{real-embeddings-5QUSL7J4.js → real-embeddings-6ACQACTM.js} +2 -2
- package/dist/cli/chunks/{roocode-installer-HDWE5XW3.js → roocode-installer-T5ZWC3SS.js} +2 -2
- package/dist/cli/chunks/router-YTQZRTIB.js +2 -0
- package/dist/cli/chunks/routing-feedback-AASAMEUY.js +2 -0
- package/dist/cli/chunks/{routing-handler-P6PP3FYW.js → routing-handler-Y2O2I2HM.js} +2 -2
- package/dist/cli/chunks/{ruvector-commands-VNMTRQML.js → ruvector-commands-F2V36B4W.js} +2 -2
- package/dist/cli/chunks/{rvf-dual-writer-A7VW5CAT.js → rvf-dual-writer-R6CNMPQD.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-adapter-QIPSNASM.js → rvf-migration-adapter-IDVOB3LN.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-coordinator-XT4XDLRZ.js → rvf-migration-coordinator-VM4AMFZG.js} +2 -2
- package/dist/cli/chunks/rvf-native-adapter-VHIHJOPA.js +2 -0
- package/dist/cli/chunks/safe-db-NVEBL662.js +2 -0
- package/dist/cli/chunks/schedule-KVUFE56T.js +2 -0
- package/dist/cli/chunks/scheduler-6GRLJZ2A.js +2 -0
- package/dist/cli/chunks/{security-E2XCP5CG.js → security-WQ7YMR6M.js} +3 -3
- package/dist/cli/chunks/shared-rvf-adapter-XORIDF3Q.js +2 -0
- package/dist/cli/chunks/{shared-rvf-dual-writer-NPWTXHUI.js → shared-rvf-dual-writer-HYI64CBX.js} +2 -2
- package/dist/cli/chunks/sqlite-persistence-25TDMX6G.js +2 -0
- package/dist/cli/chunks/{status-handler-MWVNDZSZ.js → status-handler-BH2WCMPA.js} +2 -2
- package/dist/cli/chunks/{structural-health-2KZO43IF.js → structural-health-XWX6FKVF.js} +2 -2
- package/dist/cli/chunks/{sync-C5BOK3WU.js → sync-PRDGCHE2.js} +2 -2
- package/dist/cli/chunks/{task-handler-KRVSHJGJ.js → task-handler-YFHFBMHO.js} +2 -2
- package/dist/cli/chunks/{task-handlers-CKOHD633.js → task-handlers-4OQRADMG.js} +2 -2
- package/dist/cli/chunks/{test-3B7FK6MJ.js → test-ZBTQ4Z66.js} +4 -4
- package/dist/cli/chunks/{test-scheduling-HZIMSTAX.js → test-scheduling-F47Y3KNO.js} +3 -3
- package/dist/cli/chunks/{token-bootstrap-JJCANIHJ.js → token-bootstrap-XOGAEQPG.js} +2 -2
- package/dist/cli/chunks/{token-usage-5VCMBZU7.js → token-usage-2KZ7WE5J.js} +2 -2
- package/dist/cli/chunks/{transformers-ETUTMOTF.js → transformers-KCJ7PWZ4.js} +2 -2
- package/dist/cli/chunks/{tree-sitter-wasm-parser-TMR44BKP.js → tree-sitter-wasm-parser-H6DL2DFA.js} +2 -2
- package/dist/cli/chunks/{types-GYT6373C.js → types-633TMIO3.js} +2 -2
- package/dist/cli/chunks/unified-memory-BTX45KY5.js +2 -0
- package/dist/cli/chunks/unified-memory-hnsw-MMHMQ4CP.js +2 -0
- package/dist/cli/chunks/unified-persistence-GA7HKYZC.js +2 -0
- package/dist/cli/chunks/{upgrade-534QLY7P.js → upgrade-CH742GRF.js} +2 -2
- package/dist/cli/chunks/{validate-UBVF3CSS.js → validate-44WH3CKE.js} +2 -2
- package/dist/cli/chunks/{validate-swarm-2XD45EVM.js → validate-swarm-W2A7CUM7.js} +2 -2
- package/dist/cli/chunks/{vibium-NMT6AQ4S.js → vibium-B25MIEBK.js} +2 -2
- package/dist/cli/chunks/visual-security-HPF5HCYF.js +2 -0
- package/dist/cli/chunks/{web-tree-sitter-RNG6NRDD.js → web-tree-sitter-B54K47HF.js} +2 -2
- package/dist/cli/chunks/{windsurf-installer-RVCDSJT3.js → windsurf-installer-EWL7COTI.js} +2 -2
- package/dist/cli/chunks/{witness-chain-YDFB22MT.js → witness-chain-DWNP7VR6.js} +2 -2
- package/dist/cli/chunks/witness-chain-LROQLFND.js +2 -0
- package/dist/cli/chunks/{workflow-MHW4KHNK.js → workflow-LT2J7U23.js} +4 -4
- package/dist/cli/chunks/workflow-orchestrator-VFRKGG5Y.js +2 -0
- package/dist/cli/chunks/{wrappers-SAZY3C2S.js → wrappers-OAZ6MKXO.js} +2 -2
- package/dist/cli/commands/hooks-handlers/routing-hooks.d.ts +6 -0
- package/dist/cli/commands/hooks-handlers/routing-hooks.js +80 -4
- package/dist/coordination/handlers/test-execution-handlers.d.ts +18 -0
- package/dist/coordination/handlers/test-execution-handlers.js +77 -9
- package/dist/domains/test-generation/generators/jest-vitest-generator.js +13 -3
- package/dist/domains/test-generation/interfaces.d.ts +12 -0
- package/dist/domains/test-generation/services/test-generator.js +5 -1
- package/dist/governance/continue-gate-integration.d.ts +13 -0
- package/dist/governance/continue-gate-integration.js +31 -8
- package/dist/init/init-wizard-hooks.js +4 -1
- package/dist/init/phases/07-hooks.js +4 -1
- package/dist/mcp/bundle.js +411 -409
- package/dist/mcp/protocol-server.js +6 -1
- package/dist/mcp/tools/coverage-analysis/index.js +11 -2
- package/package.json +2 -2
- package/dist/cli/chunks/adapter-XFJIW42U.js +0 -2
- package/dist/cli/chunks/aqe-learning-engine-UD4SXENM.js +0 -2
- package/dist/cli/chunks/base-ETEN7L2V.js +0 -2
- package/dist/cli/chunks/browser-workflow-KVHPOIBA.js +0 -2
- package/dist/cli/chunks/chunk-3ADFXSO2.js +0 -15
- package/dist/cli/chunks/chunk-5LDXAVDC.js +0 -2
- package/dist/cli/chunks/chunk-ED5OUSYZ.js +0 -2
- package/dist/cli/chunks/client-ZDVM5WFL.js +0 -2
- package/dist/cli/chunks/cross-domain-router-J5VK276J.js +0 -2
- package/dist/cli/chunks/dream-VCLN6RM4.js +0 -2
- package/dist/cli/chunks/esm-node-YZSRCH6T.js +0 -2
- package/dist/cli/chunks/hnsw-adapter-Y5HVTNJW.js +0 -2
- package/dist/cli/chunks/hnsw-index-NZTCPZA5.js +0 -2
- package/dist/cli/chunks/hooks-K7XGDF2Y.js +0 -101
- package/dist/cli/chunks/impact-analyzer-ROWLIS6H.js +0 -2
- package/dist/cli/chunks/init-wizard-MI76CUL5.js +0 -2
- package/dist/cli/chunks/kernel-5WVAV5RX.js +0 -2
- package/dist/cli/chunks/knowledge-graph-QXL3AWPV.js +0 -2
- package/dist/cli/chunks/load-test-2JOY7YH6.js +0 -2
- package/dist/cli/chunks/memory-backend-ZKGLAWQZ.js +0 -2
- package/dist/cli/chunks/protocol-executor-3Q4QY7G6.js +0 -2
- package/dist/cli/chunks/qe-reasoning-bank-SAMJF3NF.js +0 -2
- package/dist/cli/chunks/queen-coordinator-OFRH67Y2.js +0 -2
- package/dist/cli/chunks/router-UDHEENEY.js +0 -2
- package/dist/cli/chunks/routing-feedback-PBZRVFVL.js +0 -2
- package/dist/cli/chunks/rvf-native-adapter-CJFEDG74.js +0 -2
- package/dist/cli/chunks/safe-db-YMSZFHWP.js +0 -2
- package/dist/cli/chunks/schedule-B43N6CVB.js +0 -2
- package/dist/cli/chunks/scheduler-ITZH5YQM.js +0 -2
- package/dist/cli/chunks/shared-rvf-adapter-PV5ZBJ25.js +0 -2
- package/dist/cli/chunks/sqlite-persistence-RK5CKPHB.js +0 -2
- package/dist/cli/chunks/unified-memory-LIKELZVA.js +0 -2
- package/dist/cli/chunks/unified-memory-hnsw-VTN3MUB4.js +0 -2
- package/dist/cli/chunks/unified-persistence-MQVUY5WN.js +0 -2
- package/dist/cli/chunks/visual-security-HVJWGY7T.js +0 -2
- package/dist/cli/chunks/witness-chain-5R322YYF.js +0 -2
- package/dist/cli/chunks/workflow-orchestrator-637BCZI4.js +0 -2
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,S as R,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.18");process.exit(0)}
|
|
2
|
+
import{A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,S as R,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}from"./chunk-FTIHPDWV.js";import"./chunk-FKNYOKIK.js";R();export{a as DEFAULT_FEATURE_FLAGS,b as getRuVectorFeatureFlags,A as getRvfMigrationStage,Q as initFeatureFlagsFromEnv,y as isAgentMemoryBranchingEnabled,t as isCNNVisualRegressionEnabled,O as isCognitiveRoutingEnabled,v as isCoherenceActionGateEnabled,r as isCoherenceGateEnabled,H as isColdTierGNNEnabled,o as isCrossDomainTransferEnabled,C as isCusumDriftDetectionEnabled,u as isDAGAttentionEnabled,D as isDeltaEventSourcingEnabled,l as isDeterministicDitherEnabled,M as isEpropOnlineLearningEnabled,E as isEwcPlusPlusEnabled,f as isFlashAttentionEnabled,g as isGNNIndexEnabled,N as isGrangerCausalityEnabled,F as isGraphMAEEnabled,B as isHDCFingerprintingEnabled,p as isHnswHealthMonitorEnabled,G as isHopfieldMemoryEnabled,P as isHyperbolicHnswEnabled,I as isMetaLearningEnabled,k as isMetadataFilteringEnabled,i as isNativeHNSWEnabled,m as isNeuralRoutingEnabled,x as isRVFPatternStoreEnabled,w as isReasoningQECEnabled,q as isRegretTrackingEnabled,L as isReservoirReplayEnabled,e as isSONAEnabled,n as isSONAThreeLoopEnabled,K as isSpectralSparsificationEnabled,J as isSublinearSolverEnabled,j as isTemporalCompressionEnabled,z as isUnifiedHnswEnabled,s as isWitnessChainEnabled,d as resetRuVectorFeatureFlags,c as setRuVectorFeatureFlags,h as shouldLogMigrationMetrics};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{a,b}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.18");process.exit(0)}
|
|
2
|
+
import{a,b}from"./chunk-BSQTOKNR.js";import"./chunk-FKNYOKIK.js";export{a as SOURCE_EXTENSIONS,b as walkSourceFiles};
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{a as k,b as K,c as x,d as T,e as H,f as F,g as Q,j as _}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.18");process.exit(0)}
|
|
2
|
+
import{a as k,b as K,c as x,d as T,e as H,f as F,g as Q,j as _}from"./chunk-AZGESIFV.js";import{a as v,b as V}from"./chunk-VW7FKTFO.js";import{a as G}from"./chunk-BY44ODHD.js";import"./chunk-2A4JCRAW.js";import"./chunk-NBQW7MXF.js";import{c as C,d as S}from"./chunk-JZG23IPV.js";import"./chunk-WH7ZOJCF.js";import{v as q}from"./chunk-OXL6JSVR.js";import"./chunk-DC3PADV3.js";import"./chunk-CSYQKVZY.js";import"./chunk-VRHKEJR6.js";import"./chunk-P6HIDCTQ.js";import"./chunk-F7XU7KZL.js";import{c as L}from"./chunk-7XLTLFP5.js";import{a as W}from"./chunk-H5JZZH2C.js";import{a as E}from"./chunk-K5NFP7B5.js";import"./chunk-EN2A2CVT.js";import"./chunk-JD6KE6DJ.js";import{f as j}from"./chunk-QTNDHCZ7.js";import"./chunk-MDCTQOUJ.js";import"./chunk-ZWR4PZ4Z.js";import"./chunk-WC5A7C5L.js";import"./chunk-B6BAK2JI.js";import"./chunk-FDDB7QTM.js";import"./chunk-MJ7UYPGY.js";import"./chunk-V2N7KWT7.js";import{b as N}from"./chunk-5SZLQCFP.js";import"./chunk-I3POPZT5.js";import"./chunk-J7BG55VG.js";import"./chunk-KYLE6ZSC.js";import"./chunk-ENYQUSSK.js";import"./chunk-RHYGRUNU.js";import"./chunk-6IBFYVLK.js";import"./chunk-SQHM6WUF.js";import"./chunk-EZN7QMOZ.js";import"./chunk-JZTB35EQ.js";import"./chunk-VZO5I23B.js";import"./chunk-G2H4W7NN.js";import"./chunk-JMK5OCWL.js";import"./chunk-X2T4TI7D.js";import"./chunk-BFM47L3X.js";import"./chunk-QW2RFI73.js";import"./chunk-XSLKR2DM.js";import"./chunk-4666TC3P.js";import"./chunk-6G3RNT5H.js";import"./chunk-XBWVHO6G.js";import"./chunk-BXTHB2A2.js";import"./chunk-BADBKGZE.js";import"./chunk-YZIOM7JL.js";import"./chunk-JGNVI5UB.js";import"./chunk-NKOLFLXF.js";import"./chunk-WKQSZTU6.js";import"./chunk-3GA7M5NK.js";import"./chunk-D7SS56EG.js";import"./chunk-YQL6JH2Y.js";import"./chunk-RPT7HCMH.js";import"./chunk-AGPZVE6B.js";import"./chunk-DQCWNCOT.js";import"./chunk-4XYQJ4LQ.js";import"./chunk-6KTF7QB3.js";import"./chunk-AMRUZ6XG.js";import"./chunk-6ZMQL3U6.js";import{a as I}from"./chunk-TPL3CBMS.js";import{a as B,c as ee}from"./chunk-UNPTSPAO.js";import"./chunk-LVABI4OA.js";import"./chunk-YNVVRND7.js";import{a as z,b as te}from"./chunk-UFGFV4BO.js";import"./chunk-MBGWDELE.js";import"./chunk-IS2PMHB5.js";import{c as $,d as ne}from"./chunk-QGSELG75.js";import"./chunk-ZURHHRSA.js";import"./chunk-DOSDUAVZ.js";import"./chunk-TFUWIKGZ.js";import"./chunk-JBW2A2O6.js";import"./chunk-FTIHPDWV.js";import"./chunk-FKNYOKIK.js";ne();import{Command as ie}from"commander";import t from"chalk";ee();te();import h from"chalk";import{existsSync as oe}from"fs";import{join as P}from"path";var R=class{projectRoot;options;orchestrator;constructor(e){this.options=e,this.projectRoot=e.projectRoot}async checkCodeIntelligence(){if(this.options.skipCodeScan)return console.log(h.yellow(" Code intelligence scan skipped (--skip-code-scan flag)")),{codeIntelligence:{hasIndex:!1,entryCount:0,wasPrompted:!1,scanRequested:!1},shouldProceed:!0,skipReason:"skip-flag"};if(await this.hasCodeIntelligenceIndex()){let i=await this.getKGEntryCount();return console.log(h.green(` \u2713 Code intelligence index found (${i} entries)`)),{codeIntelligence:{hasIndex:!0,entryCount:i,wasPrompted:!1,scanRequested:!1},shouldProceed:!0}}return!this.options.nonInteractive&&(console.log(h.yellow(`
|
|
3
3
|
\u26A0 No code intelligence index found`)),console.log(h.gray(" Building a knowledge graph improves agent accuracy by 80%")),console.log(h.gray(" This is a one-time operation and can be run later with:")),console.log(h.cyan(` aqe code-intelligence index
|
|
4
4
|
`)),await this.promptScan())?{codeIntelligence:{hasIndex:!1,entryCount:0,wasPrompted:!0,scanRequested:!0},shouldProceed:!1,skipReason:"scan-requested"}:(console.log(h.gray(" Continuing without code intelligence index")),{codeIntelligence:{hasIndex:!1,entryCount:0,wasPrompted:!this.options.nonInteractive,scanRequested:!1},shouldProceed:!0})}async runCodeIntelligenceScan(){try{if(console.log(h.blue(`
|
|
5
|
-
Building code intelligence knowledge graph...`)),this.orchestrator||(this.orchestrator=new G({projectRoot:this.projectRoot,autoMode:!0,...this.options.initOptions})),await this.hasCodeIntelligenceIndex()){let s=await this.getKGEntryCount();return console.log(h.green(` \u2713 Index already exists (${s} entries)`)),{success:!0,entries:s}}let{KnowledgeGraphService:i}=await import("./knowledge-graph-
|
|
5
|
+
Building code intelligence knowledge graph...`)),this.orchestrator||(this.orchestrator=new G({projectRoot:this.projectRoot,autoMode:!0,...this.options.initOptions})),await this.hasCodeIntelligenceIndex()){let s=await this.getKGEntryCount();return console.log(h.green(` \u2713 Index already exists (${s} entries)`)),{success:!0,entries:s}}let{KnowledgeGraphService:i}=await import("./knowledge-graph-SJA3YGMQ.js"),{InMemoryBackend:c}=await import("./memory-backend-SZAYMQVP.js"),m=new c;await m.initialize();let n=new i(m,{namespace:"code-intelligence:kg",enableVectorEmbeddings:!0}),g=await(await import("fast-glob")).default(["**/*.ts","**/*.tsx","**/*.js","**/*.jsx","**/*.py"],{cwd:this.projectRoot,ignore:["node_modules/**","dist/**","coverage/**",".agentic-qe/**"]});console.log(h.gray(` Indexing ${g.length} files...`));let o=await n.index({paths:g.map(s=>P(this.projectRoot,s)),incremental:!1,includeTests:!0});if(n.destroy(),o.success){let s=o.value.nodesCreated+o.value.edgesCreated;return console.log(h.green(` \u2713 Indexed ${s} knowledge graph entries`)),{success:!0,entries:s}}return console.log(h.yellow(" \u26A0 Code intelligence scan completed with warnings")),{success:!1,entries:0}}catch(e){return console.error(h.red(" \u2717 Code intelligence scan failed:"),B(e)),{success:!1,entries:0}}}async getStatusForAgents(){let e=await this.hasCodeIntelligenceIndex(),i=e?await this.getKGEntryCount():0;return{codeIntelligenceAvailable:e,knowledgeGraphSize:i,recommendedCapabilities:e?["semantic-search","code-analysis","context-aware"]:["basic-analysis"]}}async hasCodeIntelligenceIndex(){let e=P(this.projectRoot,".agentic-qe","memory.db");if(!oe(e))return!1;try{let i=z(e),c=i.prepare(`
|
|
6
6
|
SELECT COUNT(*) as count FROM kv_store
|
|
7
7
|
WHERE namespace = 'code-intelligence:kg'
|
|
8
8
|
`).get();return i.close(),c.count>0}catch{return!1}}async getKGEntryCount(){let e=P(this.projectRoot,".agentic-qe","memory.db");try{let i=z(e),c=i.prepare(`
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.18");process.exit(0)}
|
|
2
|
+
import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p}from"./chunk-AMRUZ6XG.js";import"./chunk-6ZMQL3U6.js";import"./chunk-JBW2A2O6.js";import"./chunk-FTIHPDWV.js";import"./chunk-FKNYOKIK.js";export{e as GNNLayerFactory,c as QEGNNEmbeddingIndex,d as QEGNNIndexFactory,f as TensorCompressionFactory,p as batchDifferentiableSearch,i as getDifferentiableSearch,k as getGetCompressionLevel,j as getHierarchicalForward,l as getInit,g as getRuvectorLayer,h as getTensorCompress,b as initGNN,a as isGNNAvailable,m as toFloat32Array,o as toIEmbedding,n as toNumberArray};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{b as d}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.18");process.exit(0)}
|
|
2
|
+
import{b as d}from"./chunk-ZHA5Z5V4.js";import{a as c,c as f}from"./chunk-UNPTSPAO.js";import"./chunk-FKNYOKIK.js";import*as s from"fs";import*as l from"path";import e from"chalk";f();var h=class{name="heartbeat";description="Manage the token-free heartbeat scheduler";cleanupAndExit;worker;constructor(t){this.cleanupAndExit=t}async getWorker(){if(!this.worker){let{HeartbeatSchedulerWorker:t}=await import("./heartbeat-scheduler-6JPB2AQS.js");this.worker=new t}return this.worker}register(t,o){let a=t.command("heartbeat").description(this.description);a.command("status").description("Show heartbeat worker status, health, and schedule").action(async()=>{await this.executeStatus()}),a.command("run-now").description("Trigger an immediate heartbeat cycle").option("-t, --timeout <ms>","Timeout in milliseconds (default: worker built-in 60s)").action(async n=>{let i=n.timeout?parseInt(n.timeout,10):void 0;await this.executeRunNow(i)}),a.command("history").description("Show recent heartbeat results").option("-n, --count <count>","Number of entries to show","10").action(async n=>{await this.executeHistory(parseInt(n.count,10)||10)}),a.command("log").description("Show today's daily log entries").option("-d, --date <date>","Show log for specific date (YYYY-MM-DD)").action(async n=>{await this.executeLog(n.date)}),a.command("pause").description("Pause the heartbeat worker").action(async()=>{await this.executePause()}),a.command("resume").description("Resume the heartbeat worker").action(async()=>{await this.executeResume()})}async executeStatus(){try{this.worker=await this.getWorker(),await this.worker.initialize();let t=this.worker.getHealth(),o=this.worker.lastResult;if(console.log(e.blue(`
|
|
3
3
|
Heartbeat Scheduler Status`)),console.log(e.gray(" "+"\u2500".repeat(35))),console.log(` Status: ${x(t.status)}`),console.log(` Health Score: ${y(t.healthScore)}${e.gray("/100")}`),this.worker.lastRunAt){let n=p(this.worker.lastRunAt);console.log(` Last Run: ${e.cyan(this.worker.lastRunAt.toISOString().replace("T"," ").slice(0,19))} ${e.gray(`(${n})`)}`)}else console.log(` Last Run: ${e.gray("never")}`);if(this.worker.nextRunAt){let n=p(this.worker.nextRunAt,!0);console.log(` Next Run: ${e.cyan(this.worker.nextRunAt.toISOString().replace("T"," ").slice(0,19))} ${e.gray(`(${n})`)}`)}console.log(` Total Runs: ${e.cyan(String(t.totalExecutions))}`);let a=t.totalExecutions>0?(t.successfulExecutions/t.totalExecutions*100).toFixed(1):"100.0";if(console.log(` Success Rate: ${e.cyan(a+"%")}`),o?.metrics?.domainMetrics){let n=o.metrics.domainMetrics;console.log(""),console.log(e.blue(" Last Result:")),console.log(` Promoted: ${e.cyan(String(n.promoted??0))} patterns`),console.log(` Deprecated: ${e.cyan(String(n.deprecated??0))} patterns`),console.log(` Decayed: ${e.cyan(String(n.decayed??0))} patterns`),console.log(` Pending Exp: ${e.cyan(String(n.pendingExperiences??0))}`),console.log(` Avg Conf: ${e.cyan(String(n.avgConfidence??0))}`)}console.log(""),await this.cleanupAndExit(0)}catch(t){console.error(e.red(`
|
|
4
4
|
Failed to get heartbeat status:`),c(t)),await this.cleanupAndExit(1)}}async executeRunNow(t){try{this.worker=await this.getWorker(),console.log(e.blue(`
|
|
5
5
|
Triggering heartbeat cycle...
|
|
@@ -8,7 +8,7 @@ import{b as d}from"./chunk-DJPS7H2M.js";import{a as c,c as f}from"./chunk-V2ELGH
|
|
|
8
8
|
Heartbeat History (last ${o.length})`)),console.log(e.gray(" "+"\u2500".repeat(60)));for(let a of o){let n=a.success?e.green("OK"):e.red("FAIL"),i=a.timestamp.slice(0,19).replace("T"," "),u=a.domainMetrics||{};console.log(` ${e.gray(i)} ${n} score:${e.cyan(String(a.healthScore))} +${u.promoted??0}/-${u.deprecated??0} ${e.gray(d(a.durationMs))}`)}console.log(""),await this.cleanupAndExit(0)}catch(o){console.error(e.red(`
|
|
9
9
|
Failed to load history:`),c(o)),await this.cleanupAndExit(1)}}async executeLog(t){try{let o=t||new Date().toISOString().split("T")[0];if(!/^\d{4}-\d{2}-\d{2}$/.test(o)){console.error(e.red(`
|
|
10
10
|
Invalid date format: "${o}". Use YYYY-MM-DD.
|
|
11
|
-
`)),await this.cleanupAndExit(1);return}let{findProjectRoot:a}=await import("./unified-memory-
|
|
11
|
+
`)),await this.cleanupAndExit(1);return}let{findProjectRoot:a}=await import("./unified-memory-BTX45KY5.js"),n=l.join(a(),".agentic-qe","logs"),i=l.join(n,`${o}.md`);if(!s.existsSync(i)){console.log(e.yellow(`
|
|
12
12
|
No daily log found for ${o}.
|
|
13
13
|
`)),await this.cleanupAndExit(0);return}let u=s.readFileSync(i,"utf-8");console.log(e.blue(`
|
|
14
14
|
Daily Log \u2014 ${o}`)),console.log(e.gray(" "+"\u2500".repeat(40)));for(let g of u.split(`
|
|
@@ -45,4 +45,4 @@ Examples:
|
|
|
45
45
|
aqe heartbeat log --date 2026-03-25
|
|
46
46
|
aqe heartbeat pause
|
|
47
47
|
aqe heartbeat resume
|
|
48
|
-
`}},m=100;async function w(){let{findProjectRoot:r}=await import("./unified-memory-
|
|
48
|
+
`}},m=100;async function w(){let{findProjectRoot:r}=await import("./unified-memory-BTX45KY5.js");return l.join(r(),".agentic-qe","heartbeat-history.json")}async function b(r){try{let t=await w(),o=l.dirname(t);s.existsSync(o)||s.mkdirSync(o,{recursive:!0});let a=[];if(s.existsSync(t))try{a=JSON.parse(s.readFileSync(t,"utf-8"))}catch{a=[]}a.unshift({timestamp:r.timestamp.toISOString(),success:r.success,durationMs:r.durationMs,healthScore:r.metrics.healthScore,domainMetrics:r.metrics.domainMetrics}),a.length>m&&(a=a.slice(0,m)),s.writeFileSync(t,JSON.stringify(a,null,2))}catch{}}async function S(r){try{let t=await w();return s.existsSync(t)?JSON.parse(s.readFileSync(t,"utf-8")).slice(0,r):[]}catch{return[]}}function x(r){switch(r){case"idle":return e.cyan(r);case"running":return e.yellow(r);case"paused":return e.yellow(r);case"stopped":return e.gray(r);case"error":return e.red(r);default:return e.white(r)}}function y(r){return r>=80?e.green(String(r)):r>=50?e.yellow(String(r)):e.red(String(r))}function k(r){switch(r){case"improving":return e.green(r);case"stable":return e.cyan(r);case"degrading":return e.red(r);default:return e.gray(r)}}function p(r,t=!1){let o=t?r.getTime()-Date.now():Date.now()-r.getTime();return o<0?t?"now":"just now":o<6e4?`${Math.floor(o/1e3)}s ${t?"from now":"ago"}`:o<36e5?`${Math.floor(o/6e4)}m ${t?"from now":"ago"}`:`${Math.floor(o/36e5)}h ${t?"from now":"ago"}`}function A(r){return new h(r)}export{h as HeartbeatHandler,A as createHeartbeatHandler};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{a as v,b as k}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.18");process.exit(0)}
|
|
2
|
+
import{a as v,b as k}from"./chunk-27MW2RFA.js";import"./chunk-S2XBAOXE.js";import"./chunk-G2H4W7NN.js";import{k as g,o as P}from"./chunk-RPT7HCMH.js";import"./chunk-AGPZVE6B.js";import"./chunk-4XYQJ4LQ.js";import"./chunk-6KTF7QB3.js";import"./chunk-6ZMQL3U6.js";import{a as d,b as y,c as R}from"./chunk-UNPTSPAO.js";import"./chunk-UFGFV4BO.js";import"./chunk-MBGWDELE.js";import"./chunk-IS2PMHB5.js";import"./chunk-QGSELG75.js";import"./chunk-ZURHHRSA.js";import"./chunk-DOSDUAVZ.js";import"./chunk-TFUWIKGZ.js";import"./chunk-JBW2A2O6.js";import"./chunk-FTIHPDWV.js";import"./chunk-FKNYOKIK.js";R();import{randomUUID as M}from"crypto";var p=class{constructor(e){this.config=e}config;_status="idle";_lastResult;_lastRunAt;_nextRunAt;_totalExecutions=0;_successfulExecutions=0;_failedExecutions=0;_executionDurations=[];_recentResults=[];get status(){return this._status}get lastResult(){return this._lastResult}get lastRunAt(){return this._lastRunAt}get nextRunAt(){return this._nextRunAt}async initialize(){this._status="idle",this._nextRunAt=new Date(Date.now()+this.config.intervalMs)}async execute(e){let r=Date.now();this._status="running",this._lastRunAt=new Date,this._totalExecutions++;let n,t;for(let a=0;a<=this.config.retryCount;a++)try{if(e.signal.aborted)throw new Error("Worker execution aborted");t=await this.executeWithTimeout(()=>this.doExecute(e),this.config.timeoutMs,e.signal);break}catch(u){n=y(u),e.logger.warn(`Worker ${this.config.id} attempt ${a+1} failed: ${n.message}`),a<this.config.retryCount&&await this.delay(this.config.retryDelayMs)}let o=Date.now()-r;return t?(this._successfulExecutions++,this._lastResult=t):(this._failedExecutions++,t=this.createErrorResult(n,o),this._lastResult=t),this._executionDurations.push(o),this._executionDurations.length>100&&this._executionDurations.shift(),this._recentResults.push({timestamp:new Date,success:t.success,durationMs:o}),this._recentResults.length>5&&this._recentResults.shift(),this._nextRunAt=new Date(Date.now()+this.config.intervalMs),this._status=t.success?"idle":"error",await e.eventBus.publish({type:"worker.executed",workerId:this.config.id,timestamp:new Date,payload:{success:t.success,durationMs:o,findingsCount:t.findings.length,healthScore:t.metrics.healthScore}}),t}pause(){this._status!=="stopped"&&(this._status="paused")}resume(){this._status==="paused"&&(this._status="idle")}async stop(){this._status="stopped"}getHealth(){let e=this._executionDurations.length>0?this._executionDurations.reduce((n,t)=>n+t,0)/this._executionDurations.length:0,r=this._totalExecutions>0?this._successfulExecutions/this._totalExecutions:1;return{status:this._status,healthScore:Math.round(r*100),totalExecutions:this._totalExecutions,successfulExecutions:this._successfulExecutions,failedExecutions:this._failedExecutions,avgDurationMs:Math.round(e),recentResults:[...this._recentResults]}}async executeWithTimeout(e,r,n){return new Promise((t,o)=>{let a=setTimeout(()=>{o(new Error(`Worker execution timed out after ${r}ms`))},r),u=()=>{clearTimeout(a),o(new Error("Worker execution aborted"))};n.addEventListener("abort",u,{once:!0}),e().then(c=>{clearTimeout(a),n.removeEventListener("abort",u),t(c)}).catch(c=>{clearTimeout(a),n.removeEventListener("abort",u),o(c)})})}createErrorResult(e,r){return{workerId:this.config.id,timestamp:new Date,durationMs:r,success:!1,error:e.message,metrics:{itemsAnalyzed:0,issuesFound:0,healthScore:0,trend:"degrading",domainMetrics:{}},findings:[],recommendations:[]}}createResult(e,r,n,t){return{workerId:this.config.id,timestamp:new Date,durationMs:e,success:!0,metrics:r,findings:n,recommendations:t}}delay(e){return new Promise(r=>setTimeout(r,e))}generateId(){return`${Date.now()}-${M().slice(0,9)}`}};P();R();var W={id:"heartbeat-scheduler",name:"Heartbeat Scheduler",description:"Token-free maintenance: pattern promotion, stale detection, experience buffer monitoring",intervalMs:1800*1e3,priority:"normal",targetDomains:["learning-optimization"],enabled:!0,timeoutMs:6e4,retryCount:1,retryDelayMs:5e3},b=class extends p{lifecycleManager=null;dailyLogger;lastRunTimestamp=0;constructor(){super(W),this.dailyLogger=new k}async getLifecycleManager(){if(this.lifecycleManager)return this.lifecycleManager;try{let e=g();await e.initialize();let r=e.getDatabase();return this.lifecycleManager=v(r,{promotionRewardThreshold:.7,promotionMinOccurrences:2,promotionMinSuccessRate:.7,deprecationFailureThreshold:3,staleDaysThreshold:30,confidenceDecayRate:.01,minActiveConfidence:.3}),this.lifecycleManager}catch{return null}}getPendingExperienceCount(){try{return g().getDatabase().prepare("SELECT COUNT(*) as pending FROM qe_pattern_usage WHERE created_at > datetime('now', '-1 day')").get()?.pending??0}catch{return 0}}async doExecute(e){let r=Date.now();e.logger.info("Heartbeat scheduler running (token-free maintenance)");let n=[],t=[],o=await this.getLifecycleManager();if(!o)return e.logger.warn("Unified memory unavailable \u2014 returning zero-metric heartbeat"),this.createResult(Date.now()-r,{itemsAnalyzed:0,issuesFound:0,healthScore:50,trend:"stable",domainMetrics:{promoted:0,deprecated:0,decayed:0,stalePatterns:0,pendingExperiences:0,avgConfidence:0,avgSuccessRate:0}},[],[]);let a=0,u=0;try{let s=o.promoteEligiblePatterns();a=s.promoted,u=s.checked,a>0&&n.push({type:"heartbeat-promotion",severity:"info",domain:"learning-optimization",title:"Patterns Promoted",description:`${a} of ${u} short-term patterns promoted to long-term`})}catch(s){e.logger.warn("Pattern promotion failed",{error:d(s)})}let c=0,h=0;try{let s=o.deprecateStalePatterns();c=s.deprecated,h=s.checked,c>0&&n.push({type:"heartbeat-deprecation",severity:"low",domain:"learning-optimization",title:"Stale Patterns Deprecated",description:`${c} of ${h} patterns deprecated (stale, failed, or low confidence)`})}catch(s){e.logger.warn("Stale pattern detection failed",{error:d(s)})}let l=0;try{let s=this.lastRunTimestamp>0?(Date.now()-this.lastRunTimestamp)/864e5:1;l=o.applyConfidenceDecay(Math.min(s,7)).decayed}catch(s){e.logger.warn("Confidence decay failed",{error:d(s)})}let m=this.getPendingExperienceCount(),i={totalPatterns:0,activePatterns:0,deprecatedPatterns:0,promotedPatterns:0,shortTermPatterns:0,longTermPatterns:0,avgConfidence:0,avgSuccessRate:0,patternsNearDeprecation:0};try{i=o.getStats()}catch(s){e.logger.warn("Stats retrieval failed",{error:d(s)})}try{this.dailyLogger.log({timestamp:new Date,type:"pattern-promoted",summary:`Heartbeat: ${a} promoted, ${c} deprecated, ${l} decayed, ${m} pending exp, ${i.activePatterns} active patterns (avg conf: ${i.avgConfidence.toFixed(2)})`,details:{promoted:a,deprecated:c,decayed:l,pendingExperiences:m,totalPatterns:i.totalPatterns,activePatterns:i.activePatterns,avgConfidence:i.avgConfidence,avgSuccessRate:i.avgSuccessRate}}),this.dailyLogger.flush()}catch(s){e.logger.warn("Daily log write failed",{error:d(s)})}this.lastRunTimestamp=Date.now(),i.activePatterns>0&&i.patternsNearDeprecation/i.activePatterns>.5&&t.push({priority:"p2",domain:"learning-optimization",action:"Review At-Risk Patterns",description:`${i.patternsNearDeprecation} of ${i.activePatterns} active patterns are near deprecation. Manual review recommended.`,estimatedImpact:"medium",effort:"low",autoFixable:!1});let f=this.calculateHealthScore(i,a,c),D=this.determineTrend(a,c,i.activePatterns),_=Math.max(u,h),x=a+c+i.patternsNearDeprecation;return e.logger.info("Heartbeat complete",{promoted:a,deprecated:c,decayed:l,pendingExperiences:m,healthScore:f}),this.createResult(Date.now()-r,{itemsAnalyzed:_,issuesFound:x,healthScore:f,trend:D,domainMetrics:{promoted:a,deprecated:c,decayed:l,stalePatterns:i.patternsNearDeprecation,pendingExperiences:m,avgConfidence:Number(i.avgConfidence.toFixed(3)),avgSuccessRate:Number(i.avgSuccessRate.toFixed(3))}},n,t)}calculateHealthScore(e,r,n){let t=70;if(t+=Math.min(15,r*5),e.avgConfidence>0&&(t+=Math.round((e.avgConfidence-.5)*30)),e.activePatterns>0){let o=n/e.activePatterns;t-=Math.round(o*20)}return e.activePatterns>0&&e.patternsNearDeprecation/e.activePatterns>.5&&(t-=10),Math.max(0,Math.min(100,Math.round(t)))}determineTrend(e,r,n){return n===0?"stable":e>r?"improving":r>e&&r/n>.1?"degrading":"stable"}};export{b as HeartbeatSchedulerWorker};
|
|
@@ -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.18");process.exit(0)}
|
|
2
|
+
import{a,c as b}from"./chunk-TFUWIKGZ.js";import"./chunk-JBW2A2O6.js";import"./chunk-FTIHPDWV.js";import"./chunk-FKNYOKIK.js";b();export{a as HnswAdapter};
|
|
@@ -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.18");process.exit(0)}
|
|
2
|
+
import{a,b,c,d}from"./chunk-BXTHB2A2.js";import"./chunk-4XYQJ4LQ.js";import"./chunk-6KTF7QB3.js";import"./chunk-QGSELG75.js";import"./chunk-TFUWIKGZ.js";import"./chunk-JBW2A2O6.js";import"./chunk-FTIHPDWV.js";import"./chunk-FKNYOKIK.js";export{a as DEFAULT_HNSW_CONFIG,b as HNSWIndex,d as benchmarkHNSW,c as createHNSWIndex};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.18");process.exit(0)}
|
|
2
|
+
import"./chunk-FKNYOKIK.js";var s=class{adapter;metadataMap=new Map;insertCount=0;constructor(e){this.adapter=e}async initialize(){}async insert(e,t,r){this.adapter.addByStringId(e,t),this.insertCount++,r&&this.metadataMap.set(e,r)}async search(e,t){return this.adapter.searchByArray(e,t).map(a=>({key:a.id,score:a.score,distance:1-a.score,metadata:this.metadataMap.get(a.id)}))}async batchInsert(e){for(let t of e)await this.insert(t.key,t.vector,t.metadata)}async delete(e){let t=this.adapter.removeByStringId(e);return t&&this.metadataMap.delete(e),t}async getStats(){return{nativeHNSW:!0,backendType:"ruvector-gnn",vectorCount:this.adapter.size(),indexSizeBytes:this.adapter.size()*this.adapter.dimensions()*4,avgSearchLatencyMs:this.adapter.lastSearchLatencyMs,p95SearchLatencyMs:0,p99SearchLatencyMs:0,searchOperations:0,insertOperations:this.insertCount}}async clear(){this.adapter.clear(),this.metadataMap.clear(),this.insertCount=0}isNativeAvailable(){return!0}};export{s as HnswLegacyBridge};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.18");process.exit(0)}
|
|
2
|
+
import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o}from"./chunk-7OGUAZGJ.js";import"./chunk-FKNYOKIK.js";export{i as DotProductAttention,h as FlashAttention,k as HyperbolicAttention,l as LinearAttention,m as MoEAttention,j as MultiHeadAttention,b as RuvectorLayer,n as SonaEngine,c as TensorCompress,a as default,d as differentiableSearch,f as getCompressionLevel,e as hierarchicalForward,g as init,o as pipeline};
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
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.18");process.exit(0)}
|
|
3
|
+
import{a as S,b as z,c as F}from"./chunk-VRHKEJR6.js";import{a as U,b as J}from"./chunk-6IBFYVLK.js";import{g as j}from"./chunk-SQHM6WUF.js";import"./chunk-EZN7QMOZ.js";import"./chunk-JZTB35EQ.js";import"./chunk-VZO5I23B.js";import"./chunk-G2H4W7NN.js";import"./chunk-JMK5OCWL.js";import"./chunk-QW2RFI73.js";import{a as L}from"./chunk-XSLKR2DM.js";import"./chunk-BADBKGZE.js";import"./chunk-3GA7M5NK.js";import"./chunk-D7SS56EG.js";import{f as E,o as P}from"./chunk-RPT7HCMH.js";import"./chunk-AGPZVE6B.js";import"./chunk-4XYQJ4LQ.js";import"./chunk-6KTF7QB3.js";import{b as M,d as oe}from"./chunk-6ZMQL3U6.js";import"./chunk-TPL3CBMS.js";import"./chunk-UNPTSPAO.js";import"./chunk-LVABI4OA.js";import"./chunk-UFGFV4BO.js";import"./chunk-MBGWDELE.js";import"./chunk-IS2PMHB5.js";import"./chunk-QGSELG75.js";import"./chunk-ZURHHRSA.js";import"./chunk-DOSDUAVZ.js";import"./chunk-TFUWIKGZ.js";import"./chunk-JBW2A2O6.js";import"./chunk-FTIHPDWV.js";import"./chunk-FKNYOKIK.js";import{Command as fe}from"commander";import A from"chalk";import V from"node:path";P();import{randomUUID as se}from"crypto";import I from"chalk";var v="dream-scheduler:hook-state",Q=36e5,G=20,W=3e5;async function N(s){try{let e=await s.get(v);if(!e)return{triggered:!1,reason:"no-state"};let t=Date.now(),n=e.lastDreamTime?new Date(e.lastDreamTime).getTime():0,o=t-n;if(o<W)return{triggered:!1,reason:"too-soon"};let r=o>=Q,i=e.experienceCount>=G;if(!r&&!i)return{triggered:!1,reason:"conditions-not-met"};let c=r?"time-interval":"experience-threshold";console.log(I.dim(`[hooks] Dream trigger: ${c} (${e.experienceCount} experiences, ${Math.round(o/6e4)}min since last dream)`));let{createDreamEngine:a}=await import("./dream-FAHB6BWB.js"),{createQEReasoningBank:h}=await import("./qe-reasoning-bank-N7ZXOAEN.js"),u=a({maxDurationMs:1e4,minConceptsRequired:3});await u.initialize();let k=h(s,void 0,{enableLearning:!0,enableGuidance:!1,enableRouting:!1,embeddingDimension:384,useONNXEmbeddings:!0});await k.initialize();let p=await k.searchPatterns("",{limit:100,minConfidence:.3});if(p.success&&p.value.length>0){let R=p.value.map($=>({id:$.pattern.id,name:$.pattern.name,description:$.pattern.description||`${$.pattern.patternType} pattern`,domain:$.pattern.qeDomain||"learning-optimization",patternType:$.pattern.patternType,confidence:$.pattern.confidence,successRate:$.pattern.successRate||.5}));await u.loadPatternsAsConcepts(R)}let f=await u.dream(1e4);return e.lastDreamTime=new Date().toISOString(),e.experienceCount=0,e.totalDreamsThisSession++,await s.set(v,e),await u.close(),{triggered:!0,reason:c,insightsGenerated:f.insights.length}}catch(e){return console.error(I.dim(`[hooks] Dream trigger failed: ${e instanceof Error?e.message:"unknown"}`)),{triggered:!1,reason:"error"}}}async function D(s){try{let e=await s.get(v);return e||(e={lastDreamTime:null,experienceCount:0,sessionStartTime:new Date().toISOString(),totalDreamsThisSession:0}),e.experienceCount++,await s.set(v,e),e.experienceCount}catch{return 0}}async function O(s){try{let{getUnifiedMemory:e}=await import("./unified-memory-BTX45KY5.js"),t=e();t.isInitialized()||await t.initialize();let n=t.getDatabase(),o=`cli-${Date.now()}-${se().slice(0,8)}`,r=s.durationMs||0,i;if(s.success){let c=r>0&&r<5e3?.1:0,a=s.source.includes("post-task")?.1:s.source.includes("post-edit")?.05:0;i=Math.min(.95,.7+c+a)}else{let c=s.source.includes("post-task")?.15:s.source.includes("post-edit")?.1:0;i=Math.min(.6,.3+c)}n.prepare(`
|
|
4
|
+
INSERT OR REPLACE INTO captured_experiences
|
|
5
|
+
(id, task, agent, domain, success, quality, duration_ms,
|
|
6
|
+
started_at, completed_at, source)
|
|
7
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, datetime('now'), datetime('now'), ?)
|
|
8
|
+
`).run(o,s.task.slice(0,500),s.agent,s.domain,s.success?1:0,i,r,s.source)}catch(e){console.error(I.dim(`[hooks] persistCommandExperience: ${e instanceof Error?e.message:"unknown"}`))}}async function B(){let{getUnifiedMemory:s}=await import("./unified-memory-BTX45KY5.js"),e=s();e.isInitialized()||await e.initialize();let t=e.getDatabase(),n=new Set(t.prepare("PRAGMA table_info(captured_experiences)").all().map(a=>a.name)),o=[["consolidated_into","TEXT DEFAULT NULL"],["consolidation_count","INTEGER DEFAULT 1"],["quality_updated_at","TEXT DEFAULT NULL"],["reuse_success_count","INTEGER DEFAULT 0"],["reuse_failure_count","INTEGER DEFAULT 0"]];for(let[a,h]of o)n.has(a)||t.exec(`ALTER TABLE captured_experiences ADD COLUMN ${a} ${h}`);let r=t.prepare(`
|
|
9
|
+
SELECT
|
|
10
|
+
domain,
|
|
11
|
+
agent,
|
|
12
|
+
COUNT(*) as cnt,
|
|
13
|
+
AVG(quality) as avg_quality,
|
|
14
|
+
SUM(success) as successes,
|
|
15
|
+
CAST(SUM(success) AS REAL) / COUNT(*) as success_rate,
|
|
16
|
+
AVG(duration_ms) as avg_duration,
|
|
17
|
+
GROUP_CONCAT(DISTINCT source) as sources
|
|
18
|
+
FROM captured_experiences
|
|
19
|
+
WHERE application_count = 0
|
|
20
|
+
AND agent != 'cli-hook'
|
|
21
|
+
GROUP BY domain, agent
|
|
22
|
+
HAVING cnt >= 3 AND avg_quality >= 0.5 AND success_rate >= 0.6
|
|
23
|
+
ORDER BY avg_quality DESC
|
|
24
|
+
LIMIT 50
|
|
25
|
+
`).all();if(r.length===0)return 0;let{v4:i}=await import("./dist-node-HSG4QK4G.js"),c=0;for(let a of r)try{let h=new Date().toISOString().slice(0,7),u=`${a.agent}-${a.domain}-${h}`,k=t.prepare(`
|
|
26
|
+
SELECT id FROM qe_patterns
|
|
27
|
+
WHERE qe_domain = ? AND name = ?
|
|
28
|
+
LIMIT 1
|
|
29
|
+
`).get(a.domain,u);if(k)t.prepare(`
|
|
30
|
+
UPDATE qe_patterns
|
|
31
|
+
SET usage_count = usage_count + ?,
|
|
32
|
+
successful_uses = successful_uses + ?,
|
|
33
|
+
confidence = MIN(0.99, confidence + 0.01),
|
|
34
|
+
quality_score = MIN(0.99, quality_score + 0.005),
|
|
35
|
+
updated_at = datetime('now')
|
|
36
|
+
WHERE id = ?
|
|
37
|
+
`).run(a.cnt,a.successes,k.id);else{let p=i(),f=Math.min(.95,a.avg_quality*.8+a.success_rate*.2),R=f*.3+Math.min(a.cnt,100)/100*.2+a.success_rate*.5;t.prepare(`
|
|
38
|
+
INSERT INTO qe_patterns (
|
|
39
|
+
id, pattern_type, qe_domain, domain, name, description,
|
|
40
|
+
confidence, usage_count, success_rate, quality_score, tier,
|
|
41
|
+
template_json, context_json, created_at, successful_uses
|
|
42
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'), ?)
|
|
43
|
+
`).run(p,"workflow",a.domain,a.domain,u,`Auto-consolidated from ${a.cnt} experiences. Agent: ${a.agent}, success rate: ${(a.success_rate*100).toFixed(0)}%`,f,a.cnt,a.success_rate,R,"short-term",JSON.stringify({type:"workflow",content:`${a.agent} pattern for ${a.domain}`,variables:[]}),JSON.stringify({tags:(a.sources||"").split(","),sourceType:"session-consolidation",extractedAt:new Date().toISOString()}),a.successes),c++}t.prepare(`
|
|
44
|
+
UPDATE captured_experiences
|
|
45
|
+
SET application_count = application_count + 1
|
|
46
|
+
WHERE domain = ? AND agent = ? AND application_count = 0
|
|
47
|
+
`).run(a.domain,a.agent)}catch{}return c}var d={reasoningBank:null,hookRegistry:null,coherenceService:null,sessionId:null,initialized:!1,initializationPromise:null};async function g(){if(d.initializationPromise&&await d.initializationPromise,d.initialized&&d.reasoningBank&&d.hookRegistry)return{reasoningBank:d.reasoningBank,hookRegistry:d.hookRegistry};if(d.initializationPromise=re(),await d.initializationPromise,d.initializationPromise=null,!d.reasoningBank||!d.hookRegistry)throw new Error("Failed to initialize hooks system");return{reasoningBank:d.reasoningBank,hookRegistry:d.hookRegistry}}async function re(){if(!d.initialized)try{let s=E(),e=V.join(s,".agentic-qe"),t=await T(e);try{d.coherenceService=await U(J),console.log(A.dim("[hooks] CoherenceService initialized with WASM engines"))}catch(i){console.log(A.dim(`[hooks] CoherenceService WASM unavailable, using fallback: ${i instanceof Error?i.message:"unknown"}`))}d.reasoningBank=j(t,void 0,{enableLearning:!0,enableGuidance:!0,enableRouting:!0,embeddingDimension:384,useONNXEmbeddings:!0},d.coherenceService??void 0);let n=1e4,o=d.reasoningBank.initialize(),r=new Promise((i,c)=>setTimeout(()=>c(new Error("ReasoningBank init timeout")),n));await Promise.race([o,r]);try{let{getSharedRvfDualWriter:i}=await import("./shared-rvf-dual-writer-HYI64CBX.js"),c=await i();c&&d.reasoningBank.setRvfDualWriter(c)}catch(i){process.env.DEBUG&&console.debug("[hooks] RVF wiring skipped:",i instanceof Error?i.message:i)}d.hookRegistry=F(d.reasoningBank),d.initialized=!0,console.log(A.dim("[hooks] System initialized"))}catch(s){console.warn(A.yellow(`[hooks] Using fallback mode: ${s instanceof Error?s.message:"unknown error"}`));let e=ie();d.reasoningBank=j(e,void 0,{enableLearning:!0,enableGuidance:!0,enableRouting:!0}),d.hookRegistry=new z,d.hookRegistry.initialize(d.reasoningBank),d.initialized=!0}}async function T(s){let t=new L({sqlite:{path:V.join(s,"memory.db"),walMode:!0,poolSize:3,busyTimeout:5e3},enableFallback:!0,defaultNamespace:"qe-patterns"}),n=t.initialize(),o=new Promise((r,i)=>setTimeout(()=>i(new Error("Backend init timeout")),5e3));return await Promise.race([n,o]),t}function ie(){let s=new Map;return{initialize:async()=>{},dispose:async()=>{s.clear()},get:async e=>{let t=s.get(e);return t?t.value:void 0},set:async(e,t,n)=>{s.set(e,{value:t})},delete:async e=>s.delete(e),has:async e=>s.has(e),search:async(e,t)=>{let n=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(n.replace(/\*/g,".*"));return Array.from(s.keys()).filter(r=>o.test(r))},vectorSearch:async(e,t)=>[],storeVector:async(e,t,n)=>{},count:async e=>{let t=0,n=`${e}:`;for(let o of s.keys())o.startsWith(n)&&t++;return t},hasCodeIntelligenceIndex:async()=>{let e="code-intelligence:kg:";for(let t of s.keys())if(t.startsWith(e))return!0;return!1}}}function m(s){console.log(JSON.stringify(s,null,2))}function b(s){console.log(A.green("\u2713"),s)}function y(s){console.error(A.red("\u2717"),s)}function q(s){if(s.length===0){console.log(A.dim(" No specific guidance"));return}s.forEach((e,t)=>{console.log(A.cyan(` ${t+1}.`),e)})}import _ from"chalk";import ae from"node:path";P();function Z(s){s.command("pre-edit").description("Get context and guidance before editing a file").requiredOption("-f, --file <path>","File path to edit").option("-o, --operation <type>","Operation type: create, update, delete, refactor","update").option("--json","Output as JSON").action(async e=>{try{let{hookRegistry:t}=await g(),o=(await t.emit(S.PreTestGeneration,{targetFile:e.file,testType:"unit",operation:e.operation}))[0]||{success:!0,guidance:[],routing:null};if(e.json){let r=o.guidance||[],c=[o.routing?.recommendedAgent?`Recommended agent: ${o.routing.recommendedAgent} (${(o.routing.confidence*100).toFixed(0)}% confidence).`:"",...r.map(a=>a)].filter(Boolean).join(" ");m({hookSpecificOutput:{hookEventName:"PreToolUse",additionalContext:c||void 0},file:e.file,operation:e.operation,patterns:o.routing?.patterns?.length||0})}else console.log(_.bold(`
|
|
48
|
+
\u{1F4DD} Pre-Edit Analysis`)),console.log(_.dim(` File: ${e.file}`)),console.log(_.dim(` Operation: ${e.operation}`)),o.routing&&(console.log(_.bold(`
|
|
49
|
+
\u{1F3AF} Recommended Agent:`),_.cyan(o.routing.recommendedAgent)),console.log(_.dim(` Confidence: ${(o.routing.confidence*100).toFixed(1)}%`))),console.log(_.bold(`
|
|
50
|
+
\u{1F4A1} Guidance:`)),q(o.guidance||[]);return}catch(t){throw y(`pre-edit failed: ${t instanceof Error?t.message:"unknown"}`),t}}),s.command("post-edit").description("Record editing outcome for pattern learning").requiredOption("-f, --file <path>","File path that was edited").option("--success","Edit was successful").option("--failure","Edit failed").option("--pattern-id <id>","Pattern ID that was applied").option("--json","Output as JSON").action(async e=>{try{let{hookRegistry:t}=await g(),n=e.success||!e.failure,o=e.file||"",r=o.split("/").pop()||"unknown",c=/\.(test|spec)\.(ts|js|tsx|jsx)$/.test(r)?"test-generation":"code-intelligence",a=e.patternId||`edit:${c}:${r}`,u=(await t.emit(S.PostTestGeneration,{targetFile:e.file,success:n,patternId:a,generatedTests:null,testCount:0}))[0]||{success:!0,patternsLearned:0};try{let{reasoningBank:p}=await g();await p.recordOutcome({patternId:a,success:n,metrics:{executionTimeMs:0},feedback:`Edit ${n?"succeeded":"failed"}: ${o}`})}catch{}try{await O({task:`edit: ${o}`,agent:"cli-hook",domain:c,success:n,source:"cli-hook-post-edit"})}catch{}let k=!1;try{let p=E(),f=ae.join(p,".agentic-qe"),R=await T(f);await D(R)}catch{}e.json?m({success:!0,file:e.file,editSuccess:n,patternsLearned:u.patternsLearned||0,dreamTriggered:k}):(b(`Recorded edit outcome for ${e.file}`),u.patternsLearned&&console.log(_.green(` Patterns learned: ${u.patternsLearned}`)));return}catch(t){throw y(`post-edit failed: ${t instanceof Error?t.message:"unknown"}`),t}})}P();import{randomUUID as ce}from"crypto";import w from"chalk";import de from"node:path";async function me(s=500){return process.stdin.isTTY?"":new Promise(e=>{let t="",n=setTimeout(()=>{process.stdin.removeAllListeners(),process.stdin.pause(),e(t)},s);process.stdin.setEncoding("utf8"),process.stdin.on("data",o=>{t+=o}),process.stdin.on("end",()=>{clearTimeout(n),e(t)}),process.stdin.on("error",()=>{clearTimeout(n),e(t)}),process.stdin.resume()})}function le(s){if(!s.trim())return"";let e;try{e=JSON.parse(s)}catch{return s.trim()}let t=[e.prompt,e.user_prompt,e.command,e.tool_input?.prompt,e.tool_input?.description,e.toolInput?.prompt,e.toolInput?.description];for(let n of t)if(typeof n=="string"&&n.trim())return n;return""}function K(s){s.command("route").description("Route a task to the optimal QE agent").option("-t, --task <description>","Task description (falls back to stdin event JSON)").option("-d, --domain <domain>","Target QE domain hint").option("-c, --capabilities <caps...>","Required capabilities").option("--json","Output as JSON").action(async e=>{try{let t=e.task??"";if(!t.trim()){let c=await me();t=le(c)}if(!t.trim())throw new Error("No task provided. Pass --task <description> or pipe a Claude Code hook event JSON to stdin.");let{reasoningBank:n}=await g(),o={task:t,domain:e.domain,capabilities:e.capabilities},r=await n.routeTask(o);if(!r.success)throw new Error(r.error.message);let i=r.value;e.json?m({recommendedAgent:i.recommendedAgent,confidence:i.confidence,alternatives:i.alternatives,domains:i.domains,patternCount:i.patterns.length,guidance:i.guidance,reasoning:i.reasoning}):(console.log(w.bold(`
|
|
51
|
+
\u{1F3AF} Task Routing Result`)),console.log(w.dim(` Task: "${t}"`)),console.log(w.bold(`
|
|
52
|
+
\u{1F464} Recommended Agent:`),w.cyan(i.recommendedAgent)),console.log(w.dim(` Confidence: ${(i.confidence*100).toFixed(1)}%`)),i.alternatives.length>0&&(console.log(w.bold(`
|
|
53
|
+
\u{1F504} Alternatives:`)),i.alternatives.forEach(c=>{console.log(w.dim(` - ${c.agent}: ${(c.score*100).toFixed(1)}%`))})),console.log(w.bold(`
|
|
54
|
+
\u{1F4C2} Detected Domains:`),i.domains.join(", ")),console.log(w.bold(`
|
|
55
|
+
\u{1F4A1} Guidance:`)),q(i.guidance),console.log(w.bold(`
|
|
56
|
+
\u{1F4D6} Reasoning:`),w.dim(i.reasoning)));try{let{getUnifiedMemory:c}=await import("./unified-memory-BTX45KY5.js"),a=c();a.isInitialized()||await a.initialize();let h=a.getDatabase(),u=`route-${Date.now()}-${ce().slice(0,8)}`;h.prepare(`
|
|
57
|
+
INSERT OR REPLACE INTO routing_outcomes (
|
|
58
|
+
id, task_json, decision_json, used_agent,
|
|
59
|
+
followed_recommendation, success, quality_score,
|
|
60
|
+
duration_ms, error
|
|
61
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
62
|
+
`).run(u,JSON.stringify({description:t,domain:e.domain}),JSON.stringify({recommended:i.recommendedAgent,confidence:i.confidence,alternatives:i.alternatives}),i.recommendedAgent,1,1,i.confidence,0,null);let k=E(),p=de.join(k,".agentic-qe"),f=await T(p);await D(f)}catch(c){console.error(w.dim(`[hooks] route persist: ${c instanceof Error?c.message:"unknown"}`))}return}catch(t){throw y(`route failed: ${t instanceof Error?t.message:"unknown"}`),t}})}import l from"chalk";oe();function X(s){s.command("stats").description("Display hooks system statistics").option("--json","Output as JSON").action(async e=>{try{let{reasoningBank:t}=await g(),n=await t.getStats();if(e.json)m(n);else{console.log(l.bold(`
|
|
63
|
+
\u{1F4CA} Hooks System Statistics
|
|
64
|
+
`)),console.log(l.bold("Patterns:")),console.log(` Total: ${l.cyan(n.totalPatterns)}`),console.log(` Short-term: ${n.patternStoreStats.byTier.shortTerm}`),console.log(` Long-term: ${n.patternStoreStats.byTier.longTerm}`),console.log(l.bold(`
|
|
65
|
+
By Domain:`));for(let[o,r]of Object.entries(n.byDomain))r>0&&console.log(` ${o}: ${r}`);console.log(l.bold(`
|
|
66
|
+
Routing:`)),console.log(` Requests: ${n.routingRequests}`),console.log(` Avg Confidence: ${(n.avgRoutingConfidence*100).toFixed(1)}%`),console.log(l.bold(`
|
|
67
|
+
Learning:`)),console.log(` Outcomes: ${n.learningOutcomes}`),console.log(` Success Rate: ${(n.patternSuccessRate*100).toFixed(1)}%`),console.log(l.bold(`
|
|
68
|
+
Search Performance:`)),console.log(` Operations: ${n.patternStoreStats.searchOperations}`),console.log(` Avg Latency: ${n.patternStoreStats.avgSearchLatencyMs.toFixed(2)}ms`),console.log(` HNSW Native: ${n.patternStoreStats.hnswStats.nativeAvailable?"\u2713":"\u2717"}`)}}catch(t){throw y(`stats failed: ${t instanceof Error?t.message:"unknown"}`),t}}),s.command("list").description("List all registered QE hook events").option("--json","Output as JSON").action(async e=>{try{let{hookRegistry:t}=await g(),n=t.getRegisteredEvents();if(e.json)m({events:n,totalEvents:Object.keys(S).length,registeredEvents:n.length});else{console.log(l.bold(`
|
|
69
|
+
\u{1F4CB} Registered QE Hook Events
|
|
70
|
+
`)),console.log(l.bold("All Available Events:"));for(let[o,r]of Object.entries(S)){let c=n.includes(r)?l.green("\u2713"):l.dim("\u25CB");console.log(` ${c} ${o}: ${l.dim(r)}`)}console.log(l.dim(`
|
|
71
|
+
Registered: ${n.length}/${Object.keys(S).length}`))}}catch(t){throw y(`list failed: ${t instanceof Error?t.message:"unknown"}`),t}}),s.command("emit").description("Emit a QE hook event").requiredOption("-e, --event <name>","Event name (e.g., qe:pattern-applied)").option("-d, --data <json>","Event data as JSON","{}").option("--json","Output as JSON").action(async e=>{try{let{hookRegistry:t}=await g(),n;try{n=M(e.data)}catch{throw new Error(`Invalid JSON data: ${e.data}`)}let o=await t.emit(e.event,n);e.json?m({event:e.event,results:o}):(console.log(l.bold(`
|
|
72
|
+
\u{1F4E1} Hook Event Emitted`)),console.log(l.dim(` Event: ${e.event}`)),console.log(l.dim(` Handlers: ${o.length}`)),o.forEach((r,i)=>{let c=r.success?l.green("\u2713"):l.red("\u2717");console.log(` ${c} Handler ${i+1}: ${r.success?"success":r.error}`),r.patternsLearned&&console.log(l.green(` Patterns learned: ${r.patternsLearned}`))}))}catch(t){throw y(`emit failed: ${t instanceof Error?t.message:"unknown"}`),t}}),s.command("learn").description("Store a new pattern in the reasoning bank").requiredOption("-n, --name <name>","Pattern name").requiredOption("-d, --description <desc>","Pattern description").option("-t, --type <type>","Pattern type","test-template").option("--domain <domain>","QE domain").option("--tags <tags...>","Pattern tags").option("--json","Output as JSON").action(async e=>{try{let{reasoningBank:t}=await g(),n=await t.storePattern({patternType:e.type,name:e.name,description:e.description,template:{type:"prompt",content:e.description,variables:[]},context:{tags:e.tags||[]}});if(!n.success)throw new Error(n.error.message);let o=n.value;e.json?m({success:!0,pattern:{id:o.id,name:o.name,type:o.patternType,domain:o.qeDomain}}):(b(`Pattern stored: ${o.name}`),console.log(l.dim(` ID: ${o.id}`)),console.log(l.dim(` Domain: ${o.qeDomain}`)),console.log(l.dim(` Tier: ${o.tier}`)))}catch(t){throw y(`learn failed: ${t instanceof Error?t.message:"unknown"}`),t}}),s.command("search").description("Search for patterns in the reasoning bank").requiredOption("-q, --query <query>","Search query").option("-l, --limit <n>","Maximum results","10").option("-d, --domain <domain>","Filter by domain").option("--json","Output as JSON").action(async e=>{try{let{reasoningBank:t}=await g(),n=await t.searchPatterns(e.query,{limit:parseInt(e.limit,10),domain:e.domain});if(!n.success)throw new Error(n.error.message);let o=n.value;e.json?m({query:e.query,total:o.length,patterns:o.map(r=>({id:r.pattern.id,name:r.pattern.name,score:r.score,domain:r.pattern.qeDomain,matchType:r.matchType}))}):(console.log(l.bold(`
|
|
73
|
+
\u{1F50D} Search Results for "${e.query}"
|
|
74
|
+
`)),o.length===0?console.log(l.dim(" No patterns found")):o.forEach((r,i)=>{console.log(`${l.cyan(`${i+1}.`)} ${r.pattern.name} ${l.dim(`(${(r.score*100).toFixed(1)}%)`)}`),console.log(l.dim(` Domain: ${r.pattern.qeDomain}`)),console.log(l.dim(` Match: ${r.matchType}`)),console.log(l.dim(` ID: ${r.pattern.id}`)),console.log()}),console.log(l.dim(`Found ${o.length} pattern(s)`)))}catch(t){throw y(`search failed: ${t instanceof Error?t.message:"unknown"}`),t}})}P();import C from"chalk";import ue from"node:path";function Y(s){s.command("session-start").description("Initialize session state when Claude Code session starts").option("-s, --session-id <id>","Session ID").option("--json","Output as JSON").action(async e=>{try{let t=e.sessionId||`session-${Date.now()}`;d.sessionId=t;let{reasoningBank:n}=await g(),o=await n.getStats(),r=E(),i=ue.join(r,".agentic-qe"),c=await T(i),a=await c.get(v),h=!a||!a.sessionStartTime;a?(a.sessionStartTime=new Date().toISOString(),a.totalDreamsThisSession=0):a={lastDreamTime:null,experienceCount:0,sessionStartTime:new Date().toISOString(),totalDreamsThisSession:0},await c.set(v,a);let u=[];u.push(`AQE Learning: ${o.totalPatterns} patterns loaded`);let k=Object.entries(o.byDomain).filter(([,f])=>f>0).sort(([,f],[,R])=>R-f).slice(0,5);k.length>0&&u.push(`Top domains: ${k.map(([f,R])=>`${f}(${R})`).join(", ")}`),o.patternSuccessRate>0&&u.push(`Pattern success rate: ${(o.patternSuccessRate*100).toFixed(0)}%`),o.routingRequests>0&&u.push(`Routing confidence: ${(o.avgRoutingConfidence*100).toFixed(0)}% across ${o.routingRequests} requests`);let p=u.join(". ")+".";e.json?m({hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:p},sessionId:t,initialized:!0,patternsLoaded:o.totalPatterns,dreamScheduler:{enabled:!0,lastDreamTime:a.lastDreamTime,pendingExperiences:a.experienceCount}}):(b(`Session started: ${t}`),console.log(C.dim(` Patterns loaded: ${o.totalPatterns}`)),console.log(C.dim(` Dream scheduler: enabled (${a.experienceCount} pending experiences)`)));return}catch(t){e.json&&m({success:!1,error:t instanceof Error?t.message:"unknown"});return}}),s.command("session-end").description("Save session state when Claude Code session ends").option("--save-state","Save learning state to disk").option("--export-metrics","Export session metrics").option("--json","Output as JSON").action(async e=>{try{let t=d.sessionId||"unknown",n=null;if(d.initialized&&d.reasoningBank)try{n=await d.reasoningBank.getStats()}catch{}let o=0;try{o=await B()}catch{}if(e.json){let r=n?`Session complete: ${n.totalPatterns} patterns, ${n.routingRequests} routings, ${(n.patternSuccessRate*100).toFixed(0)}% success rate`:"Session complete";m({continue:!0,sessionId:t,stateSaved:e.saveState||!1,metricsExported:e.exportMetrics||!1,patternsConsolidated:o,finalStats:n?{patternsLearned:n.totalPatterns,routingRequests:n.routingRequests,successRate:n.patternSuccessRate}:null})}else b(`Session ended: ${t}`),n&&(console.log(C.dim(` Patterns: ${n.totalPatterns}`)),console.log(C.dim(` Routing requests: ${n.routingRequests}`))),o>0&&console.log(C.dim(` Patterns consolidated: ${o}`));return}catch(t){e.json&&m({success:!1,error:t instanceof Error?t.message:"unknown"});return}})}import x from"chalk";import ge from"node:path";P();function ee(s){s.command("pre-task").description("Get context and guidance before spawning a Task agent").option("--task-id <id>","Task identifier").option("-d, --description <desc>","Task description").option("--json","Output as JSON").action(async e=>{try{let{reasoningBank:t}=await g(),n=null;if(e.description){let o=await t.routeTask({task:e.description});o.success&&(n=o.value)}e.json?m({success:!0,taskId:e.taskId,description:e.description,recommendedAgent:n?.recommendedAgent,confidence:n?.confidence,guidance:n?.guidance||[]}):(console.log(x.bold(`
|
|
75
|
+
\u{1F680} Pre-Task Analysis`)),console.log(x.dim(` Task ID: ${e.taskId||"N/A"}`)),n&&(console.log(x.bold(`
|
|
76
|
+
\u{1F3AF} Recommended:`),x.cyan(n.recommendedAgent)),console.log(x.dim(` Confidence: ${(n.confidence*100).toFixed(1)}%`))));return}catch(t){e.json&&m({success:!1,error:t instanceof Error?t.message:"unknown"});return}}),s.command("post-task").description("Record task outcome for pattern learning").option("--task-id <id>","Task identifier").option("--success <bool>","Whether task succeeded","true").option("--agent <name>","Agent that executed the task").option("--duration <ms>","Task duration in milliseconds").option("--json","Output as JSON").action(async e=>{try{let t=e.success==="true"||e.success===!0,n=0,o={triggered:!1};try{let{hookRegistry:r,reasoningBank:i}=await g();if(n=(await r.emit(S.QEAgentCompletion,{taskId:e.taskId,success:t,agent:e.agent,duration:e.duration?parseInt(e.duration,10):void 0,timestamp:Date.now()})).reduce((p,f)=>p+(f.patternsLearned||0),0),e.taskId){let p=e.agent||"unknown";await i.recordOutcome({patternId:`task:${p}:${e.taskId}`,success:t,metrics:{executionTimeMs:e.duration?parseInt(e.duration,10):0},feedback:`Agent: ${p}, Task: ${e.taskId}`})}let a=E(),h=ge.join(a,".agentic-qe"),u=await T(h),k=await D(u);o=await N(u)}catch(r){console.error(x.dim(`[hooks] Learning init: ${r instanceof Error?r.message:"unknown"}`))}e.json?m({success:!0,taskId:e.taskId,taskSuccess:t,patternsLearned:n,dreamTriggered:o.triggered,dreamReason:o.reason,dreamInsights:o.insightsGenerated}):(b(`Task completed: ${e.taskId||"unknown"}`),console.log(x.dim(` Success: ${t}`)),n>0&&console.log(x.green(` Patterns learned: ${n}`)),o.triggered&&console.log(x.blue(` \u{1F319} Dream cycle triggered (${o.reason}): ${o.insightsGenerated} insights`)));return}catch(t){e.json&&m({success:!1,error:t instanceof Error?t.message:"unknown"});return}})}import H from"chalk";import pe from"node:path";P();function te(s){s.command("guard").description("File guardian - block edits to protected files").requiredOption("-f, --file <path>","File path to check").option("--json","Output as JSON (required for hook API)").action(async e=>{try{let t=e.file||"",n=t.replace(/\\/g,"/"),r=[{pattern:/^\.env($|\.)/,reason:"Environment file contains secrets"},{pattern:/\.env\.[a-zA-Z]+$/,reason:"Environment file contains secrets"},{pattern:/\.lock$/,reason:"Lock files are auto-generated"},{pattern:/(^|\/)node_modules\//,reason:"node_modules is managed by package manager"},{pattern:/(^|\/)\.agentic-qe\/memory\.db/,reason:"AQE memory database must not be directly edited"},{pattern:/(^|\/)\.agentic-qe\/memory\.db-wal$/,reason:"AQE WAL file must not be directly edited"},{pattern:/(^|\/)\.agentic-qe\/memory\.db-shm$/,reason:"AQE shared memory file must not be directly edited"}].find(i=>i.pattern.test(n));r?e.json?m({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`Protected file: ${r.reason} (${t})`}}):y(`Blocked: ${r.reason} (${t})`):e.json?m({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}}):b(`Allowed: ${t}`);return}catch{e.json&&m({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}});return}}),s.command("pre-command").description("Get context before executing a Bash command").option("-c, --command <cmd>","Command to be executed").option("--json","Output as JSON").action(async e=>{try{let t=e.command||"",n=[{pattern:/rm\s+(-[a-zA-Z]*f[a-zA-Z]*\s+)?-[a-zA-Z]*r[a-zA-Z]*\s+\/(?!\w)/,reason:"Recursive delete of root filesystem"},{pattern:/rm\s+(-[a-zA-Z]*r[a-zA-Z]*\s+)?-[a-zA-Z]*f[a-zA-Z]*\s+\/(?!\w)/,reason:"Recursive delete of root filesystem"},{pattern:/rm\s+-rf\s+~/,reason:"Recursive delete of home directory"},{pattern:/DROP\s+(TABLE|DATABASE|SCHEMA)/i,reason:"Destructive SQL operation"},{pattern:/git\s+push\s+.*--force(?!-)/,reason:"Force push can overwrite remote history"},{pattern:/git\s+reset\s+--hard/,reason:"Hard reset discards uncommitted changes"},{pattern:/>\s*\/dev\/sd[a-z]/,reason:"Direct write to block device"},{pattern:/dd\s+if=.*of=\/dev\/sd/,reason:"Direct disk write via dd"},{pattern:/chmod\s+777\s/,reason:"World-writable permissions are a security risk"},{pattern:/:\(\)\s*\{\s*:\|\s*:&\s*\}\s*;?\s*:/,reason:"Fork bomb detected"},{pattern:/mkfs\./,reason:"Filesystem format operation"},{pattern:/>\s*\/dev\/null\s*2>&1\s*&\s*disown/,reason:"Stealth background process"}],o=[{pattern:/\.agentic-qe.*rm/,reason:"Deleting AQE data files"},{pattern:/rm\s+-rf\s/,reason:"Recursive force delete"},{pattern:/git\s+clean\s+-[a-zA-Z]*f/,reason:"Force cleaning untracked files"}],r=n.find(c=>c.pattern.test(t)),i=o.filter(c=>c.pattern.test(t)).map(c=>c.reason);if(r)e.json?m({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`Dangerous command blocked: ${r.reason}`}}):y(`Blocked: ${r.reason}`);else if(e.json){let c={hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}};i.length>0&&(c.hookSpecificOutput.additionalContext=`Warnings: ${i.join("; ")}`),m(c)}else i.length>0&&(console.log(H.yellow(`
|
|
77
|
+
\u26A0\uFE0F Command Warnings:`)),i.forEach(c=>console.log(H.yellow(` - ${c}`))));return}catch{e.json&&m({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}});return}}),s.command("post-command").description("Record Bash command outcome").option("-c, --command <cmd>","Command that was executed").option("--success <bool>","Whether command succeeded","true").option("--exit-code <code>","Command exit code").option("--json","Output as JSON").action(async e=>{try{let t=e.success==="true"||e.success===!0,n=e.exitCode?parseInt(e.exitCode,10):t?0:1,o=(e.command||"").substring(0,200),r=/\b(test|vitest|jest|pytest|mocha)\b/i.test(o),i=/\b(build|compile|tsc)\b/i.test(o),c=/\b(lint|eslint|prettier)\b/i.test(o),a=0,h=!1;try{let{reasoningBank:u}=await g();if(r){let{hookRegistry:ne}=await g();await ne.emit(S.TestExecutionResult,{runId:`cmd-${Date.now()}`,patternId:`cmd:test:${o.split(/\s+/).slice(0,3).join("-")}`,passed:t?1:0,failed:t?0:1,duration:0,flaky:!1})}let k=o.replace(/[^a-zA-Z0-9]/g,"-").slice(0,80),p=r?"test-execution":i?"code-intelligence":c?"quality-assessment":"code-intelligence";await u.recordOutcome({patternId:`cmd:${k}`,success:t,metrics:{executionTimeMs:0},feedback:`Command: ${o}, exit: ${n}`}),a=1,await O({task:`bash: ${o}`,agent:"cli-hook",domain:p,success:t,source:"cli-hook-post-command"}),h=!0;let f=E(),R=pe.join(f,".agentic-qe"),$=await T(R);await D($)}catch(u){console.error(H.dim(`[hooks] post-command learning: ${u instanceof Error?u.message:"unknown"}`))}e.json&&m({success:!0,command:o.substring(0,100),commandSuccess:t,exitCode:n,patternsLearned:a,experienceRecorded:h});return}catch(t){e.json&&m({success:!1,error:t instanceof Error?t.message:"unknown"});return}})}function Et(){let s=new fe("hooks").description("Self-learning QE hooks for pattern recognition and guidance").addHelpText("after",`
|
|
78
|
+
Examples:
|
|
79
|
+
# File editing hooks (learning from edits)
|
|
80
|
+
aqe hooks pre-edit --file src/utils.ts --operation create
|
|
81
|
+
aqe hooks post-edit --file src/utils.ts --success
|
|
82
|
+
|
|
83
|
+
# Task routing and guidance
|
|
84
|
+
aqe hooks route --task "Generate tests for UserService"
|
|
85
|
+
aqe hooks pre-task --description "Generate tests" --json
|
|
86
|
+
aqe hooks post-task --task-id "task-123" --success true
|
|
87
|
+
|
|
88
|
+
# Bash command hooks
|
|
89
|
+
aqe hooks pre-command --command "npm test" --json
|
|
90
|
+
aqe hooks post-command --command "npm test" --success true
|
|
91
|
+
|
|
92
|
+
# Session lifecycle (Stop hook)
|
|
93
|
+
aqe hooks session-start --session-id "session-123"
|
|
94
|
+
aqe hooks session-end --save-state --json
|
|
95
|
+
|
|
96
|
+
# Pattern management
|
|
97
|
+
aqe hooks learn --name "test-pattern" --description "A test pattern"
|
|
98
|
+
aqe hooks search --query "authentication"
|
|
99
|
+
aqe hooks stats
|
|
100
|
+
aqe hooks list
|
|
101
|
+
`);return Z(s),K(s),X(s),Y(s),ee(s),te(s),s}export{S as QE_HOOK_EVENTS,Et as createHooksCommand,g as getHooksSystem,d as hooksState};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{a as h,b as z}from"./chunk-3ZGYB23S.js";import{a as b,b as B,c as P,d as O,e as F}from"./chunk-J2ERTUDX.js";import{b as k,c as x,d as _,e as w}from"./chunk-JZOMOYHZ.js";import{a as M}from"./chunk-LVK2PDUW.js";import{b as S,c as U}from"./chunk-V2ELGHLG.js";import{f as I}from"./chunk-ED5OUSYZ.js";import"./chunk-NOJVROCD.js";var m={heavyweight:{requiresReasoning:!0,requiresTools:!0,requiresVision:!1,requiresExtendedThinking:!0,requiresJsonMode:!0,minContextSize:1e5,costSensitivity:"low",latencySensitivity:"low"},standard:{requiresReasoning:!0,requiresTools:!0,requiresVision:!1,requiresExtendedThinking:!1,requiresJsonMode:!0,minContextSize:5e4,costSensitivity:"medium",latencySensitivity:"medium"},lightweight:{requiresReasoning:!1,requiresTools:!0,requiresVision:!1,requiresExtendedThinking:!1,requiresJsonMode:!0,minContextSize:16e3,costSensitivity:"medium",latencySensitivity:"high"},minimal:{requiresReasoning:!1,requiresTools:!1,requiresVision:!1,requiresExtendedThinking:!1,requiresJsonMode:!1,minContextSize:4e3,costSensitivity:"high",latencySensitivity:"medium"}},$={security:m.heavyweight,"test-generation":m.standard,"code-analysis":m.standard,learning:m.standard,performance:{...m.lightweight,costSensitivity:"high"},coordination:m.lightweight,general:{...m.lightweight,requiresJsonMode:!1,latencySensitivity:"medium"},documentation:{...m.minimal,minContextSize:16e3},simple:m.minimal};var v=class{rules=[];constructor(e=[]){this.setRules(e)}setRules(e){this.rules=[...e].filter(t=>t.enabled).sort((t,r)=>r.priority-t.priority)}getRules(){return[...this.rules]}addRule(e){this.rules.push(e),this.rules=this.rules.filter(t=>t.enabled).sort((t,r)=>r.priority-t.priority)}removeRule(e){let t=this.rules.findIndex(r=>r.id===e);return t>=0?(this.rules.splice(t,1),!0):!1}setRuleEnabled(e,t){let r=this.rules.find(i=>i.id===e);return r?(r.enabled=t,this.rules=this.rules.filter(i=>i.enabled).sort((i,o)=>o.priority-i.priority),!0):!1}evaluate(e){let t=0;for(let r of this.rules)if(t++,this.matchesCondition(e,r.condition))return{rule:r,rulesEvaluated:t};return null}evaluateAll(e){return this.rules.filter(t=>this.matchesCondition(e,t.condition))}matchesCondition(e,t){if(t.agentType!==void 0&&(!e.agentType||!t.agentType.includes(e.agentType))||t.requiresTools!==void 0&&!!e.requiresTools!==t.requiresTools)return!1;if(t.complexity!==void 0){let r=Array.isArray(t.complexity)?t.complexity:[t.complexity];if(!e.complexity||!r.includes(e.complexity))return!1}if(t.localOnly!==void 0&&t.localOnly){let r=["ollama","onnx"];if(e.preferredProvider&&!r.includes(e.preferredProvider))return!1}if(t.requiresReasoning!==void 0&&t.requiresReasoning&&e.complexity==="low")return!1;if(t.tokenRange!==void 0){let r=this.estimateTokens(e);if(t.tokenRange.min!==void 0&&r<t.tokenRange.min||t.tokenRange.max!==void 0&&r>t.tokenRange.max)return!1}return!(t.requiredCapabilities!==void 0&&t.requiredCapabilities.length>0&&(!e.requiredCapabilities||e.requiredCapabilities.length===0||!t.requiredCapabilities.every(i=>e.requiredCapabilities.includes(i)))||t.custom!==void 0&&!t.custom(e))}estimateTokens(e){let t=0;e.systemPrompt&&(t+=Math.ceil(e.systemPrompt.length/4));for(let r of e.messages)t+=Math.ceil(r.content.length/4);return t}},A=[{id:"security-agents-opus",name:"Security Agents to Claude Opus",description:"Route security-critical agents to Claude Opus for best security analysis",condition:{agentType:["security-auditor","security-architect","v3-qe-security-scanner"]},action:{provider:"claude",model:"claude-opus-4-7",temperature:.1},enabled:!0,priority:100},{id:"test-gen-with-tools",name:"Test Generation with Tools",description:"Route test generation requests that need tools to Claude Sonnet",condition:{agentType:["v3-qe-test-generator","tester"],requiresTools:!0},action:{provider:"claude",model:"claude-sonnet-4-6",temperature:.3},enabled:!0,priority:95},{id:"high-complexity-reasoning",name:"High Complexity Reasoning",description:"Route high complexity tasks requiring reasoning to advanced models",condition:{complexity:"high",requiresReasoning:!0},action:{provider:"claude",model:"claude-opus-4-7",temperature:.2},enabled:!0,priority:90},{id:"code-analysis-agents",name:"Code Analysis Agents",description:"Route code analysis to Claude Sonnet for balanced performance",condition:{agentType:["code-analyzer","v3-qe-code-intelligence","reviewer"]},action:{provider:"claude",model:"claude-sonnet-4-6",temperature:.2},enabled:!0,priority:85},{id:"coverage-analysis",name:"Coverage Analysis Agents",description:"Route coverage analysis to efficient models",condition:{agentType:["v3-qe-coverage-analyzer"]},action:{provider:"claude",model:"claude-sonnet-4-6",temperature:.1},enabled:!0,priority:80},{id:"defect-prediction",name:"Defect Prediction Agents",description:"Route defect prediction to capable models",condition:{agentType:["v3-qe-defect-predictor"]},action:{provider:"claude",model:"claude-sonnet-4-6",temperature:.3},enabled:!0,priority:75},{id:"medium-complexity",name:"Medium Complexity Tasks",description:"Route medium complexity to balanced Claude Sonnet",condition:{complexity:"medium"},action:{provider:"claude",model:"claude-sonnet-4-6",temperature:.3},enabled:!0,priority:60},{id:"low-complexity-haiku",name:"Low Complexity to Haiku",description:"Route low complexity tasks to Haiku for cost efficiency",condition:{complexity:"low"},action:{provider:"claude",model:"claude-haiku-4-5-20251001",temperature:.3},enabled:!0,priority:50},{id:"local-only-ollama",name:"Local Only Requests",description:"Route local-only requests to Ollama",condition:{localOnly:!0},action:{provider:"ollama",model:"llama3.1",temperature:.3},enabled:!0,priority:40},{id:"small-requests-haiku",name:"Small Token Requests",description:"Route small requests to Haiku for efficiency",condition:{tokenRange:{max:500}},action:{provider:"claude",model:"claude-haiku-4-5-20251001",temperature:.3},enabled:!0,priority:30}];import{randomUUID as H}from"crypto";var f=class{decisions=[];providerCalls=[];fallbacks=[];cacheHits=0;cacheMisses=0;startTime=new Date;maxRecords;maxCallRecords;constructor(e={}){this.maxRecords=e.maxRecords??1e4,this.maxCallRecords=e.maxCallRecords??5e3}recordRoutingDecision(e,t,r={}){let i={id:`rd-${Date.now()}-${H().slice(0,8)}`,timestamp:new Date,provider:e.providerType,model:e.model,mode:this.inferMode(e.reason),reason:e.reason,latencyMs:t,decisionTimeMs:e.metadata.decisionTimeMs,agentType:r.agentType,success:r.success??!0,tokenUsage:r.tokenUsage,cost:r.cost,wasFallback:e.reason==="fallback",ruleId:e.matchedRule?.id};this.decisions.push(i),this.trimRecords()}recordProviderCall(e,t,r,i,o={}){let n=o.inputTokens??Math.floor(i*.7),a=o.outputTokens??i-n,c={timestamp:new Date,provider:e,model:t,latencyMs:r,inputTokens:n,outputTokens:a,totalTokens:i,success:o.success??!0,cost:o.cost,agentType:o.agentType};this.providerCalls.push(c),this.trimCallRecords()}recordFallback(e,t,r,i){let o={timestamp:new Date,fromProvider:e,toProvider:t,reason:r,agentType:i};this.fallbacks.push(o),this.fallbacks.length>1e3&&(this.fallbacks=this.fallbacks.slice(-1e3))}recordCacheHit(){this.cacheHits++}recordCacheMiss(){this.cacheMisses++}getMetrics(e="all"){let t=this.getWindowStart(e),r=this.filterByTime(this.decisions,t),i=this.filterByTime(this.providerCalls,t),o=this.filterByTime(this.fallbacks,t),n=this.calculateProviderMetrics(r,i),a=this.calculateAgentMetrics(r,i),c=r.map(u=>u.decisionTimeMs),s=r.length,l=this.countByMode(r),d=r.filter(u=>u.wasFallback).length,g=r.filter(u=>u.ruleId).length;return{byProvider:Object.fromEntries(n),byAgentType:a,totalDecisions:s,decisionsByMode:l,avgDecisionTimeMs:this.average(c),p95DecisionTimeMs:this.percentile(c,95),p99DecisionTimeMs:this.percentile(c,99),fallbackRate:s>0?d/s:0,ruleMatchRate:s>0?g/s:0,estimatedCostSavings:this.calculateCostSavings(r),ruleStats:{totalEvaluated:r.reduce((u,y)=>u+1,0),matched:g,avgRulesPerDecision:1},cacheStats:{hits:this.cacheHits,misses:this.cacheMisses,hitRate:this.cacheHits+this.cacheMisses>0?this.cacheHits/(this.cacheHits+this.cacheMisses):0},period:{start:t,end:new Date},recentDecisions:r.slice(-50),fallbackStats:this.calculateFallbackStats(o)}}getMetricsByProvider(e){let t=this.decisions.filter(c=>c.provider===e),r=this.providerCalls.filter(c=>c.provider===e),i=r.map(c=>c.latencyMs),o=t.map(c=>c.decisionTimeMs),n=r.filter(c=>c.success),a=r.filter(c=>!c.success);return{provider:e,selectionCount:t.length,ruleMatchCount:t.filter(c=>c.ruleId).length,fallbackCount:t.filter(c=>c.wasFallback).length,avgDecisionTimeMs:this.average(o),successRate:r.length>0?n.length/r.length:1,avgLatencyMs:this.average(i),p95LatencyMs:this.percentile(i,95),p99LatencyMs:this.percentile(i,99),totalCost:r.reduce((c,s)=>c+(s.cost??0),0),totalTokens:r.reduce((c,s)=>c+s.totalTokens,0),totalInputTokens:r.reduce((c,s)=>c+s.inputTokens,0),totalOutputTokens:r.reduce((c,s)=>c+s.outputTokens,0),circuitState:"closed",latencyHistogram:i.slice(-100),decisionTimeHistogram:o.slice(-100),errorCount:a.length,lastError:a.length>0?a[a.length-1].timestamp:void 0,recentCalls:r.slice(-20)}}getMetricsByAgentType(e){let t=this.decisions.filter(s=>s.agentType===e),r=this.providerCalls.filter(s=>s.agentType===e),i=new Map,o=new Map;for(let s of t)i.set(s.provider,(i.get(s.provider)??0)+1),o.set(s.model,(o.get(s.model)??0)+1);let n=r.map(s=>s.latencyMs),a=t.filter(s=>s.wasFallback).length,c=t.filter(s=>s.success).length;return{agentType:e,totalDecisions:t.length,providerDistribution:i,modelDistribution:o,avgLatencyMs:this.average(n),totalCost:r.reduce((s,l)=>s+(l.cost??0),0),totalTokens:r.reduce((s,l)=>s+l.totalTokens,0),fallbackRate:t.length>0?a/t.length:0,successRate:t.length>0?c/t.length:1}}getAuditLog(e={}){let t=this.decisions;e.since&&(t=t.filter(i=>i.timestamp>=e.since)),e.provider&&(t=t.filter(i=>i.provider===e.provider)),e.agentType&&(t=t.filter(i=>i.agentType===e.agentType));let r=e.limit??100;return t.slice(-r).map(i=>({id:i.id,timestamp:i.timestamp,context:{agentType:i.agentType},decision:{providerType:i.provider,model:i.model,providerModelId:i.model,reason:i.reason,confidence:1,metadata:{decisionTimeMs:i.decisionTimeMs,timestamp:i.timestamp}},outcome:{success:i.success,latencyMs:i.latencyMs,tokenUsage:i.tokenUsage,cost:i.cost}}))}resetMetrics(){this.decisions=[],this.providerCalls=[],this.fallbacks=[],this.cacheHits=0,this.cacheMisses=0,this.startTime=new Date}inferMode(e){switch(e){case"manual":return"manual";case"rule-match":return"rule-based";case"cost-optimization":return"cost-optimized";case"performance-optimization":return"performance-optimized";default:return"rule-based"}}trimRecords(){this.decisions.length>this.maxRecords&&(this.decisions=this.decisions.slice(-this.maxRecords))}trimCallRecords(){this.providerCalls.length>this.maxCallRecords&&(this.providerCalls=this.providerCalls.slice(-this.maxCallRecords))}getWindowStart(e){let t=new Date;switch(e){case"1m":return new Date(t.getTime()-60*1e3);case"5m":return new Date(t.getTime()-300*1e3);case"15m":return new Date(t.getTime()-900*1e3);case"1h":return new Date(t.getTime()-3600*1e3);case"24h":return new Date(t.getTime()-1440*60*1e3);case"7d":return new Date(t.getTime()-10080*60*1e3);default:return this.startTime}}filterByTime(e,t){return e.filter(r=>r.timestamp>=t)}calculateProviderMetrics(e,t){let r=new Map;for(let i of h){let o=e.filter(l=>l.provider===i),n=t.filter(l=>l.provider===i);if(o.length===0&&n.length===0)continue;let a=n.map(l=>l.latencyMs),c=o.map(l=>l.decisionTimeMs),s=n.filter(l=>l.success);r.set(i,{provider:i,selectionCount:o.length,ruleMatchCount:o.filter(l=>l.ruleId).length,fallbackCount:o.filter(l=>l.wasFallback).length,avgDecisionTimeMs:this.average(c),successRate:n.length>0?s.length/n.length:1,avgLatencyMs:this.average(a),p95LatencyMs:this.percentile(a,95),p99LatencyMs:this.percentile(a,99),totalCost:n.reduce((l,d)=>l+(d.cost??0),0),totalTokens:n.reduce((l,d)=>l+d.totalTokens,0),circuitState:"closed"})}return r}calculateAgentMetrics(e,t){let r=new Set;e.forEach(o=>o.agentType&&r.add(o.agentType)),t.forEach(o=>o.agentType&&r.add(o.agentType));let i=new Map;for(let o of r)i.set(o,this.getMetricsByAgentType(o));return i}countByMode(e){let t={manual:0,"rule-based":0,"cost-optimized":0,"performance-optimized":0};for(let r of e)t[r.mode]++;return t}calculateFallbackStats(e){let t=new Map,r=new Map;for(let i of e)t.set(i.fromProvider,(t.get(i.fromProvider)??0)+1),r.set(i.reason,(r.get(i.reason)??0)+1);return{total:e.length,byProvider:t,byReason:r}}calculateCostSavings(e){return e.reduce((t,r)=>r.cost&&r.mode==="cost-optimized"?t+r.cost.totalCost*.2:t,0)}average(e){return e.length===0?0:e.reduce((t,r)=>t+r,0)/e.length}percentile(e,t){if(e.length===0)return 0;let r=[...e].sort((o,n)=>o-n),i=Math.ceil(t/100*r.length)-1;return r[Math.max(0,i)]}};function D(p){return new f(p)}var C=class{records=[];alerts=[];maxRecords;alertCheckInterval;constructor(e={}){this.maxRecords=e.maxRecords??1e4}recordCost(e,t,r,i,o={}){let n=this.calculateCost(t,r,i),a={timestamp:new Date,provider:e,model:t,inputTokens:r,outputTokens:i,inputCost:n.inputCost,outputCost:n.outputCost,totalCost:n.totalCost,agentType:o.agentType,requestId:o.requestId};return this.records.push(a),this.trimRecords(),this.checkAlerts(),a}recordCostFromInfo(e,t,r,i,o={}){let n={timestamp:new Date,provider:e,model:t,inputTokens:r.promptTokens,outputTokens:r.completionTokens,inputCost:i.inputCost,outputCost:i.outputCost,totalCost:i.totalCost,agentType:o.agentType,requestId:o.requestId};return this.records.push(n),this.trimRecords(),this.checkAlerts(),n}getCostByProvider(e="all"){let t=this.getPeriodStart(e),r=this.filterByTime(t),i=new Map;for(let o of h){let n=r.filter(s=>s.provider===o);if(n.length===0)continue;let a=n.reduce((s,l)=>s+l.totalCost,0),c=n.reduce((s,l)=>s+l.inputTokens+l.outputTokens,0);i.set(o,{totalCost:a,totalTokens:c,totalRequests:n.length,avgCostPerRequest:a/n.length,avgCostPerToken:c>0?a/c:0})}return i}getCostByAgentType(e="all"){let t=this.getPeriodStart(e),r=this.filterByTime(t),i=new Set;r.forEach(a=>a.agentType&&i.add(a.agentType));let o=new Map;for(let a of i){let c=r.filter(d=>d.agentType===a),s=c.reduce((d,g)=>d+g.totalCost,0),l=c.reduce((d,g)=>d+g.inputTokens+g.outputTokens,0);o.set(a,{totalCost:s,totalTokens:l,totalRequests:c.length,avgCostPerRequest:c.length>0?s/c.length:0,avgCostPerToken:l>0?s/l:0})}let n=r.filter(a=>!a.agentType);if(n.length>0){let a=n.reduce((s,l)=>s+l.totalCost,0),c=n.reduce((s,l)=>s+l.inputTokens+l.outputTokens,0);o.set("unknown",{totalCost:a,totalTokens:c,totalRequests:n.length,avgCostPerRequest:a/n.length,avgCostPerToken:c>0?a/c:0})}return o}getCostByModel(e="all"){let t=this.getPeriodStart(e),r=this.filterByTime(t),i=new Set;r.forEach(n=>i.add(n.model));let o=new Map;for(let n of i){let a=r.filter(l=>l.model===n),c=a.reduce((l,d)=>l+d.totalCost,0),s=a.reduce((l,d)=>l+d.inputTokens+d.outputTokens,0);o.set(n,{totalCost:c,totalTokens:s,totalRequests:a.length,avgCostPerRequest:a.length>0?c/a.length:0,avgCostPerToken:s>0?c/s:0})}return o}getTotalCost(e="all"){let t=this.getPeriodStart(e);return this.filterByTime(t).reduce((i,o)=>i+o.totalCost,0)}getCostTrend(e){let t=new Date,r=[],i,o;switch(e){case"1h":i=300*1e3,o=12;break;case"24h":i=3600*1e3,o=24;break;case"7d":i=1440*60*1e3,o=7;break}for(let n=o-1;n>=0;n--){let a=new Date(t.getTime()-n*i),c=new Date(a.getTime()-i),s=this.records.filter(l=>l.timestamp>=c&&l.timestamp<a);r.push({timestamp:a,cost:s.reduce((l,d)=>l+d.totalCost,0),tokens:s.reduce((l,d)=>l+d.inputTokens+d.outputTokens,0),requests:s.length})}return r}addBudgetAlert(e,t,r){let i={threshold:e,period:t,callback:r,active:!0};return this.alerts.push(i),this.alertCheckInterval||(this.alertCheckInterval=setInterval(()=>this.checkAlerts(),6e4)),`alert-${this.alerts.length-1}`}removeBudgetAlert(e){return e>=0&&e<this.alerts.length?(this.alerts.splice(e,1),this.alerts.length===0&&this.alertCheckInterval&&(clearInterval(this.alertCheckInterval),this.alertCheckInterval=void 0),!0):!1}getOptimizationSuggestions(){let e=[],t=this.getCostByModel("24h");for(let[n,a]of t)M[n]&&a.totalCost>1&&(n.includes("opus")&&e.push({type:"model-switch",description:"Consider using Sonnet instead of Opus for non-critical tasks",estimatedSavings:a.totalCost*.5,currentCost:a.totalCost,suggestedModel:"claude-sonnet-4-6"}),n==="gpt-4o"&&e.push({type:"model-switch",description:"Consider using GPT-4o-mini for simpler tasks",estimatedSavings:a.totalCost*.7,currentCost:a.totalCost,suggestedModel:"gpt-4o-mini"}));let r=this.getCostByProvider("24h"),i=[...r.values()].reduce((n,a)=>n+a.totalCost,0);return i>10&&!r.has("ollama")&&e.push({type:"provider-switch",description:"Consider using Ollama for development/testing workloads",estimatedSavings:i*.3,currentCost:i,suggestedProvider:"ollama"}),[...t.values()].reduce((n,a)=>n+a.totalRequests,0)>100&&e.push({type:"caching",description:"Enable response caching to reduce redundant API calls",estimatedSavings:i*.15,currentCost:i}),e}getRecords(){return[...this.records]}clear(){this.records=[]}reset(){this.records=[],this.alerts=[],this.alertCheckInterval&&(clearInterval(this.alertCheckInterval),this.alertCheckInterval=void 0)}dispose(){this.alertCheckInterval&&(clearInterval(this.alertCheckInterval),this.alertCheckInterval=void 0)}calculateCost(e,t,r){let i=M[e];if(!i)return{inputCost:0,outputCost:0,totalCost:0,currency:"USD"};let o=t/1e6*i.input,n=r/1e6*i.output;return{inputCost:o,outputCost:n,totalCost:o+n,currency:"USD"}}trimRecords(){this.records.length>this.maxRecords&&(this.records=this.records.slice(-this.maxRecords))}getPeriodStart(e){let t=new Date;switch(e){case"1h":return new Date(t.getTime()-3600*1e3);case"24h":return new Date(t.getTime()-1440*60*1e3);case"7d":return new Date(t.getTime()-10080*60*1e3);case"30d":return new Date(t.getTime()-720*60*60*1e3);default:return new Date(0)}}filterByTime(e){return this.records.filter(t=>t.timestamp>=e)}checkAlerts(){for(let e of this.alerts){if(!e.active)continue;let t=this.getTotalCost(e.period);if(t>=e.threshold){e.active=!1;let r=this.getPeriodStart(e.period),i=this.filterByTime(r),o=i.reduce((n,a)=>n+a.inputTokens+a.outputTokens,0);try{e.callback({totalCost:t,totalTokens:o,totalRequests:i.length,avgCostPerRequest:i.length>0?t/i.length:0,avgCostPerToken:o>0?t/o:0})}catch(n){console.error("Budget alert callback error:",n)}}}}};function E(p){return new C(p)}U();var R=class{cache=new Map;maxSize;ttlMs;constructor(e=100,t=6e4){this.maxSize=e,this.ttlMs=t}get(e){let t=this.cache.get(e);return t?Date.now()>t.expiresAt?(this.cache.delete(e),null):t.decision:null}set(e,t){if(this.cache.size>=this.maxSize){let r=this.cache.keys().next().value;r&&this.cache.delete(r)}this.cache.set(e,{decision:t,expiresAt:Date.now()+this.ttlMs})}clear(){this.cache.clear()}getStats(){return{hits:0,misses:0,size:this.cache.size}}},T=class{config;providerManager;ruleEngine;decisionCache;metrics;routerMetrics;costMetrics;initialized=!1;constructor(e,t){this.providerManager=e,this.config={...z,...t};let r=this.config.rules.length>0?this.config.rules:A;this.ruleEngine=new v(r),this.decisionCache=new R(100,this.config.decisionCacheTtlMs),this.metrics=new q,this.routerMetrics=D(),this.costMetrics=E()}async initialize(){this.initialized||(await this.providerManager.initialize(),this.initialized=!0)}getMode(){return this.config.mode}setMode(e){this.config.mode=e,this.decisionCache.clear()}getConfig(){return{...this.config}}updateConfig(e){this.config={...this.config,...e},e.rules&&this.ruleEngine.setRules(e.rules),e.decisionCacheTtlMs&&(this.decisionCache=new R(100,e.decisionCacheTtlMs))}async selectProvider(e){await this.ensureInitialized();let t=Date.now();if(this.config.cacheDecisions){let i=this.generateCacheKey(e),o=this.decisionCache.get(i);if(o)return this.metrics.recordCacheHit(),this.routerMetrics.recordCacheHit(),o;this.metrics.recordCacheMiss(),this.routerMetrics.recordCacheMiss()}let r;switch(this.config.mode){case"manual":r=await this.selectManual(e);break;case"rule-based":r=await this.selectRuleBased(e);break;case"cost-optimized":r=await this.selectCostOptimized(e);break;case"performance-optimized":r=await this.selectPerformanceOptimized(e);break;default:r=await this.selectRuleBased(e)}if(r.metadata.decisionTimeMs=Date.now()-t,this.config.cacheDecisions){let i=this.generateCacheKey(e);this.decisionCache.set(i,r)}return this.metrics.recordDecision(r,this.config.mode),r}async chat(e){await this.ensureInitialized();let t=I(),r=await this.selectProvider(e),i=e.agentType??"";if(_(i)&&(x(r.model)||x(r.providerModelId))){let n=r.model,a=r.providerModelId;r.model=w(i,r.model,k),r.providerModelId=w(i,r.providerModelId,k),console.warn(`[aqe] ADR-093: ${i} pinned to ${r.model} (was ${n}/${a}); set AQE_CYBER_VERIFIED=true after Cyber Verification Program approval`)}return await this.executeWithFallback(e,r,t)}async*stream(e){await this.ensureInitialized();let t=await this.selectProvider(e),r=await this.chat(e),i=100;for(let o=0;o<r.content.length;o+=i){let n=o+i>=r.content.length;yield{type:n?"done":"content",delta:r.content.slice(o,o+i),accumulated:r.content.slice(0,o+i),done:n,tokenCount:Math.ceil((o+i)/4),model:r.model,provider:t.providerType,usage:n?r.usage:void 0}}}getMetrics(){return this.metrics.getMetrics()}getEnhancedMetrics(e){return this.routerMetrics.getMetrics(e)}getProviderMetrics(e){return this.routerMetrics.getMetricsByProvider(e)}getAgentMetrics(e){return this.routerMetrics.getMetricsByAgentType(e)}getCostByProvider(e){return this.costMetrics.getCostByProvider(e)}getCostByAgentType(e){return this.costMetrics.getCostByAgentType(e)}getCostByModel(e){return this.costMetrics.getCostByModel(e)}getTotalCost(e){return this.costMetrics.getTotalCost(e)}getCostTrend(e){return this.costMetrics.getCostTrend(e)}getAuditLog(e){return this.routerMetrics.getAuditLog(e)}getOptimizationSuggestions(){return this.costMetrics.getOptimizationSuggestions()}resetMetrics(){this.metrics.reset(),this.routerMetrics.resetMetrics(),this.costMetrics.reset()}clearCache(){this.decisionCache.clear()}async selectManual(e){let t=e.preferredProvider??this.config.defaultProvider,r=e.model??this.config.defaultModel,i=this.providerManager.getProvider(t);return i?this.createDecision(i,t,r,"manual"):this.createFallbackDecision(e,"manual")}async selectRuleBased(e){let t=this.ruleEngine.evaluate(e);if(t){let{rule:o,rulesEvaluated:n}=t,a=o.action.provider,c=this.providerManager.getProvider(a);if(c){let s=this.createDecision(c,a,o.action.model,"rule-match",o);return s.metadata.rulesEvaluated=n,s}}let r=this.config.defaultProvider,i=this.providerManager.getProvider(r);return i?this.createDecision(i,r,this.config.defaultModel,"default"):this.createFallbackDecision(e,"rule-based")}async selectCostOptimized(e){let t=this.providerManager.getAvailableProviders();if(t.length===0)return this.createFallbackDecision(e,"cost-optimized");let r=1/0,i=t[0],o,n=[];for(let a of t){let c=this.providerManager.getProvider(a);if(!c)continue;let{input:s,output:l}=c.getCostPerToken(),d=this.estimateCostValue(e,s,l);n.push({provider:a,model:c.getConfig().model,reason:`Estimated cost: $${d.toFixed(6)}`,estimatedCost:d,excluded:!1}),d<r&&(r=d,i=a,o=c)}if(o){let a=o.getConfig(),c=this.createDecision(o,i,a.model,"cost-optimization");return c.metadata.estimatedCost=this.createCostEstimate(e,o),c.metadata.alternativesConsidered=n,c}return this.createFallbackDecision(e,"cost-optimized")}async selectPerformanceOptimized(e){let t=this.providerManager.getAvailableProviders(),r=this.providerManager.getMetrics();if(t.length===0)return this.createFallbackDecision(e,"performance-optimized");let i=1/0,o=t[0],n,a=[];for(let c of t){let s=this.providerManager.getProvider(c);if(!s)continue;let d=r[c]?.avgLatencyMs??1/0;a.push({provider:c,model:s.getConfig().model,reason:`Avg latency: ${d}ms`,estimatedLatencyMs:d,excluded:!1}),d<i&&(i=d,o=c,n=s)}if(n){let c=n.getConfig(),s=this.createDecision(n,o,c.model,"performance-optimization");return s.metadata.estimatedLatencyMs=i,s.metadata.alternativesConsidered=a,s}return this.createFallbackDecision(e,"performance-optimized")}async executeWithFallback(e,t,r){let{fallbackChain:i,fallbackBehavior:o}=this.config,n,a=0,c=[{provider:t.providerType,model:t.providerModelId}];for(let s of i.entries)if(!(!s.enabled||s.provider===t.providerType||!["claude","openai","ollama"].includes(s.provider)))for(let d of s.models)c.push({provider:s.provider,model:d});for(let{provider:s,model:l}of c){if(a>=o.maxAttempts)break;let d=this.providerManager.getProvider(s);if(!d)continue;a++;let g=Date.now();try{let u=await d.generate(e.messages,{model:l,temperature:e.temperature,maxTokens:e.maxTokens,systemPrompt:e.systemPrompt,timeoutMs:e.timeoutMs,skipCache:e.skipCache,metadata:e.metadata}),y=Date.now()-g;return this.metrics.recordSuccess(s),this.routerMetrics.recordRoutingDecision(t,y,{agentType:e.agentType,success:!0,tokenUsage:u.usage,cost:u.cost}),this.routerMetrics.recordProviderCall(s,l,y,u.usage.totalTokens,{inputTokens:u.usage.promptTokens,outputTokens:u.usage.completionTokens,success:!0,cost:u.cost.totalCost,agentType:e.agentType}),this.costMetrics.recordCostFromInfo(s,l,u.usage,u.cost,{agentType:e.agentType,requestId:u.requestId}),{content:u.content,model:u.model,providerModelId:u.model,provider:u.provider,usage:u.usage,cost:u.cost,latencyMs:u.latencyMs,finishReason:u.finishReason,cached:u.cached,requestId:u.requestId,routingDecision:t}}catch(u){n=S(u);let y=Date.now()-g;if(this.metrics.recordFailure(s),this.routerMetrics.recordProviderCall(s,l,y,0,{success:!1,agentType:e.agentType}),a<c.length){let L=c[a];L&&this.routerMetrics.recordFallback(s,L.provider,n.message,e.agentType)}if(B(u)&&!u.retryable)throw u;a<o.maxAttempts&&await this.delay(o.delayMs)}}throw b(`All providers failed after ${a} attempts: ${n?.message??"Unknown error"}`,"PROVIDER_UNAVAILABLE",{retryable:!1,cause:n})}createDecision(e,t,r,i,o){let{canonicalModel:n,providerModelId:a}=this.resolveModelIds(r,t);return{provider:e,providerType:t,model:n,providerModelId:a,reason:i,matchedRule:o,confidence:i==="rule-match"?.95:.8,metadata:{decisionTimeMs:0,timestamp:new Date}}}resolveModelIds(e,t){let i={claude:"anthropic",openai:"openai",ollama:"ollama",openrouter:"openrouter",gemini:"gemini","azure-openai":"azure",bedrock:"bedrock"}[t];if(!i)return{canonicalModel:e,providerModelId:e};try{let o=O(e),n=P(o,i);return{canonicalModel:o,providerModelId:n}}catch{try{if(F(e)){let n=P(e,i);return{canonicalModel:e,providerModelId:n}}}catch{}return{canonicalModel:e,providerModelId:e}}}createFallbackDecision(e,t){for(let i of this.config.fallbackChain.entries){if(!i.enabled||!["claude","openai","ollama"].includes(i.provider))continue;let n=this.providerManager.getProvider(i.provider);if(n)return this.createDecision(n,i.provider,i.models[0],"fallback")}let r=this.providerManager.getAvailableProviders();if(r.length>0){let i=r[0],o=this.providerManager.getProvider(i);return this.createDecision(o,i,o.getConfig().model,"fallback")}throw b(`No providers available for ${t} selection`,"PROVIDER_UNAVAILABLE",{retryable:!1})}generateCacheKey(e){return[this.config.mode,e.agentType??"default",e.complexity??"medium",e.requiresTools?"tools":"no-tools",e.preferredProvider??"any"].join(":")}estimateCostValue(e,t,r){let i=0;e.systemPrompt&&(i+=Math.ceil(e.systemPrompt.length/4));for(let n of e.messages)i+=Math.ceil(n.content.length/4);let o=e.maxTokens??1e3;return i*t+o*r}createCostEstimate(e,t){let{input:r,output:i}=t.getCostPerToken(),o=0;e.systemPrompt&&(o+=Math.ceil(e.systemPrompt.length/4));for(let c of e.messages)o+=Math.ceil(c.content.length/4);let n=e.maxTokens??1e3,a=o*r+n*i;return{inputTokens:o,outputTokens:n,totalCostUsd:a,inputCostPer1M:r*1e6,outputCostPer1M:i*1e6}}delay(e){return new Promise(t=>setTimeout(t,e))}async ensureInitialized(){this.initialized||await this.initialize()}},q=class{decisions=new Map;decisionsByMode={manual:0,"rule-based":0,"cost-optimized":0,"performance-optimized":0};totalDecisions=0;cacheHits=0;cacheMisses=0;totalRulesEvaluated=0;rulesMatched=0;fallbackCount=0;startTime=new Date;recordDecision(e,t){this.totalDecisions++,this.decisionsByMode[t]++,e.metadata.rulesEvaluated&&(this.totalRulesEvaluated+=e.metadata.rulesEvaluated),e.matchedRule&&this.rulesMatched++,e.reason==="fallback"&&this.fallbackCount++;let r=this.decisions.get(e.providerType);r||(r=this.createEmptyMetrics(e.providerType),this.decisions.set(e.providerType,r)),r.selectionCount++,e.reason==="rule-match"&&r.ruleMatchCount++,e.reason==="fallback"&&r.fallbackCount++}recordSuccess(e){let t=this.decisions.get(e);if(t){let r=t.successRate*t.selectionCount;t.successRate=(r+1)/t.selectionCount}}recordFailure(e){}recordCacheHit(){this.cacheHits++}recordCacheMiss(){this.cacheMisses++}getMetrics(){let e={};for(let[r,i]of this.decisions)e[r]={...i};let t=this.totalDecisions>0?this.rulesMatched/this.totalDecisions:0;return{byProvider:e,totalDecisions:this.totalDecisions,decisionsByMode:{...this.decisionsByMode},avgDecisionTimeMs:0,p95DecisionTimeMs:0,p99DecisionTimeMs:0,fallbackRate:this.totalDecisions>0?this.fallbackCount/this.totalDecisions:0,ruleMatchRate:t,estimatedCostSavings:0,ruleStats:{totalEvaluated:this.totalRulesEvaluated,matched:this.rulesMatched,avgRulesPerDecision:this.totalDecisions>0?this.totalRulesEvaluated/this.totalDecisions:0},cacheStats:{hits:this.cacheHits,misses:this.cacheMisses,hitRate:this.cacheHits+this.cacheMisses>0?this.cacheHits/(this.cacheHits+this.cacheMisses):0},period:{start:this.startTime,end:new Date}}}reset(){this.decisions.clear(),this.decisionsByMode={manual:0,"rule-based":0,"cost-optimized":0,"performance-optimized":0},this.totalDecisions=0,this.cacheHits=0,this.cacheMisses=0,this.totalRulesEvaluated=0,this.rulesMatched=0,this.fallbackCount=0,this.startTime=new Date}createEmptyMetrics(e){return{provider:e,selectionCount:0,ruleMatchCount:0,fallbackCount:0,avgDecisionTimeMs:0,successRate:1,avgLatencyMs:0,p95LatencyMs:0,p99LatencyMs:0,totalCost:0,totalTokens:0,circuitState:"closed"}}};function Je(p,e){return new T(p,e)}function Qe(p){return new T(p,{mode:"rule-based",rules:A,defaultProvider:"claude",defaultModel:"claude-sonnet-4-6",enableMetrics:!0,cacheDecisions:!0})}export{T as HybridRouter,Je as createHybridRouter,Qe as createQERouter};
|
|
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.18");process.exit(0)}
|
|
2
|
+
import{a as h,b as z}from"./chunk-6BGSH2YR.js";import{a as b,b as B,c as P,d as O,e as F}from"./chunk-IJPTWPXG.js";import{b as k,c as x,d as _,e as w}from"./chunk-HZKY5KPB.js";import{a as M}from"./chunk-MLVVYUFS.js";import{b as S,c as U}from"./chunk-UNPTSPAO.js";import{i as I}from"./chunk-LVABI4OA.js";import"./chunk-FKNYOKIK.js";var m={heavyweight:{requiresReasoning:!0,requiresTools:!0,requiresVision:!1,requiresExtendedThinking:!0,requiresJsonMode:!0,minContextSize:1e5,costSensitivity:"low",latencySensitivity:"low"},standard:{requiresReasoning:!0,requiresTools:!0,requiresVision:!1,requiresExtendedThinking:!1,requiresJsonMode:!0,minContextSize:5e4,costSensitivity:"medium",latencySensitivity:"medium"},lightweight:{requiresReasoning:!1,requiresTools:!0,requiresVision:!1,requiresExtendedThinking:!1,requiresJsonMode:!0,minContextSize:16e3,costSensitivity:"medium",latencySensitivity:"high"},minimal:{requiresReasoning:!1,requiresTools:!1,requiresVision:!1,requiresExtendedThinking:!1,requiresJsonMode:!1,minContextSize:4e3,costSensitivity:"high",latencySensitivity:"medium"}},$={security:m.heavyweight,"test-generation":m.standard,"code-analysis":m.standard,learning:m.standard,performance:{...m.lightweight,costSensitivity:"high"},coordination:m.lightweight,general:{...m.lightweight,requiresJsonMode:!1,latencySensitivity:"medium"},documentation:{...m.minimal,minContextSize:16e3},simple:m.minimal};var v=class{rules=[];constructor(e=[]){this.setRules(e)}setRules(e){this.rules=[...e].filter(t=>t.enabled).sort((t,r)=>r.priority-t.priority)}getRules(){return[...this.rules]}addRule(e){this.rules.push(e),this.rules=this.rules.filter(t=>t.enabled).sort((t,r)=>r.priority-t.priority)}removeRule(e){let t=this.rules.findIndex(r=>r.id===e);return t>=0?(this.rules.splice(t,1),!0):!1}setRuleEnabled(e,t){let r=this.rules.find(i=>i.id===e);return r?(r.enabled=t,this.rules=this.rules.filter(i=>i.enabled).sort((i,o)=>o.priority-i.priority),!0):!1}evaluate(e){let t=0;for(let r of this.rules)if(t++,this.matchesCondition(e,r.condition))return{rule:r,rulesEvaluated:t};return null}evaluateAll(e){return this.rules.filter(t=>this.matchesCondition(e,t.condition))}matchesCondition(e,t){if(t.agentType!==void 0&&(!e.agentType||!t.agentType.includes(e.agentType))||t.requiresTools!==void 0&&!!e.requiresTools!==t.requiresTools)return!1;if(t.complexity!==void 0){let r=Array.isArray(t.complexity)?t.complexity:[t.complexity];if(!e.complexity||!r.includes(e.complexity))return!1}if(t.localOnly!==void 0&&t.localOnly){let r=["ollama","onnx"];if(e.preferredProvider&&!r.includes(e.preferredProvider))return!1}if(t.requiresReasoning!==void 0&&t.requiresReasoning&&e.complexity==="low")return!1;if(t.tokenRange!==void 0){let r=this.estimateTokens(e);if(t.tokenRange.min!==void 0&&r<t.tokenRange.min||t.tokenRange.max!==void 0&&r>t.tokenRange.max)return!1}return!(t.requiredCapabilities!==void 0&&t.requiredCapabilities.length>0&&(!e.requiredCapabilities||e.requiredCapabilities.length===0||!t.requiredCapabilities.every(i=>e.requiredCapabilities.includes(i)))||t.custom!==void 0&&!t.custom(e))}estimateTokens(e){let t=0;e.systemPrompt&&(t+=Math.ceil(e.systemPrompt.length/4));for(let r of e.messages)t+=Math.ceil(r.content.length/4);return t}},A=[{id:"security-agents-opus",name:"Security Agents to Claude Opus",description:"Route security-critical agents to Claude Opus for best security analysis",condition:{agentType:["security-auditor","security-architect","v3-qe-security-scanner"]},action:{provider:"claude",model:"claude-opus-4-7",temperature:.1},enabled:!0,priority:100},{id:"test-gen-with-tools",name:"Test Generation with Tools",description:"Route test generation requests that need tools to Claude Sonnet",condition:{agentType:["v3-qe-test-generator","tester"],requiresTools:!0},action:{provider:"claude",model:"claude-sonnet-4-6",temperature:.3},enabled:!0,priority:95},{id:"high-complexity-reasoning",name:"High Complexity Reasoning",description:"Route high complexity tasks requiring reasoning to advanced models",condition:{complexity:"high",requiresReasoning:!0},action:{provider:"claude",model:"claude-opus-4-7",temperature:.2},enabled:!0,priority:90},{id:"code-analysis-agents",name:"Code Analysis Agents",description:"Route code analysis to Claude Sonnet for balanced performance",condition:{agentType:["code-analyzer","v3-qe-code-intelligence","reviewer"]},action:{provider:"claude",model:"claude-sonnet-4-6",temperature:.2},enabled:!0,priority:85},{id:"coverage-analysis",name:"Coverage Analysis Agents",description:"Route coverage analysis to efficient models",condition:{agentType:["v3-qe-coverage-analyzer"]},action:{provider:"claude",model:"claude-sonnet-4-6",temperature:.1},enabled:!0,priority:80},{id:"defect-prediction",name:"Defect Prediction Agents",description:"Route defect prediction to capable models",condition:{agentType:["v3-qe-defect-predictor"]},action:{provider:"claude",model:"claude-sonnet-4-6",temperature:.3},enabled:!0,priority:75},{id:"medium-complexity",name:"Medium Complexity Tasks",description:"Route medium complexity to balanced Claude Sonnet",condition:{complexity:"medium"},action:{provider:"claude",model:"claude-sonnet-4-6",temperature:.3},enabled:!0,priority:60},{id:"low-complexity-haiku",name:"Low Complexity to Haiku",description:"Route low complexity tasks to Haiku for cost efficiency",condition:{complexity:"low"},action:{provider:"claude",model:"claude-haiku-4-5-20251001",temperature:.3},enabled:!0,priority:50},{id:"local-only-ollama",name:"Local Only Requests",description:"Route local-only requests to Ollama",condition:{localOnly:!0},action:{provider:"ollama",model:"llama3.1",temperature:.3},enabled:!0,priority:40},{id:"small-requests-haiku",name:"Small Token Requests",description:"Route small requests to Haiku for efficiency",condition:{tokenRange:{max:500}},action:{provider:"claude",model:"claude-haiku-4-5-20251001",temperature:.3},enabled:!0,priority:30}];import{randomUUID as H}from"crypto";var f=class{decisions=[];providerCalls=[];fallbacks=[];cacheHits=0;cacheMisses=0;startTime=new Date;maxRecords;maxCallRecords;constructor(e={}){this.maxRecords=e.maxRecords??1e4,this.maxCallRecords=e.maxCallRecords??5e3}recordRoutingDecision(e,t,r={}){let i={id:`rd-${Date.now()}-${H().slice(0,8)}`,timestamp:new Date,provider:e.providerType,model:e.model,mode:this.inferMode(e.reason),reason:e.reason,latencyMs:t,decisionTimeMs:e.metadata.decisionTimeMs,agentType:r.agentType,success:r.success??!0,tokenUsage:r.tokenUsage,cost:r.cost,wasFallback:e.reason==="fallback",ruleId:e.matchedRule?.id};this.decisions.push(i),this.trimRecords()}recordProviderCall(e,t,r,i,o={}){let n=o.inputTokens??Math.floor(i*.7),a=o.outputTokens??i-n,c={timestamp:new Date,provider:e,model:t,latencyMs:r,inputTokens:n,outputTokens:a,totalTokens:i,success:o.success??!0,cost:o.cost,agentType:o.agentType};this.providerCalls.push(c),this.trimCallRecords()}recordFallback(e,t,r,i){let o={timestamp:new Date,fromProvider:e,toProvider:t,reason:r,agentType:i};this.fallbacks.push(o),this.fallbacks.length>1e3&&(this.fallbacks=this.fallbacks.slice(-1e3))}recordCacheHit(){this.cacheHits++}recordCacheMiss(){this.cacheMisses++}getMetrics(e="all"){let t=this.getWindowStart(e),r=this.filterByTime(this.decisions,t),i=this.filterByTime(this.providerCalls,t),o=this.filterByTime(this.fallbacks,t),n=this.calculateProviderMetrics(r,i),a=this.calculateAgentMetrics(r,i),c=r.map(u=>u.decisionTimeMs),s=r.length,l=this.countByMode(r),d=r.filter(u=>u.wasFallback).length,g=r.filter(u=>u.ruleId).length;return{byProvider:Object.fromEntries(n),byAgentType:a,totalDecisions:s,decisionsByMode:l,avgDecisionTimeMs:this.average(c),p95DecisionTimeMs:this.percentile(c,95),p99DecisionTimeMs:this.percentile(c,99),fallbackRate:s>0?d/s:0,ruleMatchRate:s>0?g/s:0,estimatedCostSavings:this.calculateCostSavings(r),ruleStats:{totalEvaluated:r.reduce((u,y)=>u+1,0),matched:g,avgRulesPerDecision:1},cacheStats:{hits:this.cacheHits,misses:this.cacheMisses,hitRate:this.cacheHits+this.cacheMisses>0?this.cacheHits/(this.cacheHits+this.cacheMisses):0},period:{start:t,end:new Date},recentDecisions:r.slice(-50),fallbackStats:this.calculateFallbackStats(o)}}getMetricsByProvider(e){let t=this.decisions.filter(c=>c.provider===e),r=this.providerCalls.filter(c=>c.provider===e),i=r.map(c=>c.latencyMs),o=t.map(c=>c.decisionTimeMs),n=r.filter(c=>c.success),a=r.filter(c=>!c.success);return{provider:e,selectionCount:t.length,ruleMatchCount:t.filter(c=>c.ruleId).length,fallbackCount:t.filter(c=>c.wasFallback).length,avgDecisionTimeMs:this.average(o),successRate:r.length>0?n.length/r.length:1,avgLatencyMs:this.average(i),p95LatencyMs:this.percentile(i,95),p99LatencyMs:this.percentile(i,99),totalCost:r.reduce((c,s)=>c+(s.cost??0),0),totalTokens:r.reduce((c,s)=>c+s.totalTokens,0),totalInputTokens:r.reduce((c,s)=>c+s.inputTokens,0),totalOutputTokens:r.reduce((c,s)=>c+s.outputTokens,0),circuitState:"closed",latencyHistogram:i.slice(-100),decisionTimeHistogram:o.slice(-100),errorCount:a.length,lastError:a.length>0?a[a.length-1].timestamp:void 0,recentCalls:r.slice(-20)}}getMetricsByAgentType(e){let t=this.decisions.filter(s=>s.agentType===e),r=this.providerCalls.filter(s=>s.agentType===e),i=new Map,o=new Map;for(let s of t)i.set(s.provider,(i.get(s.provider)??0)+1),o.set(s.model,(o.get(s.model)??0)+1);let n=r.map(s=>s.latencyMs),a=t.filter(s=>s.wasFallback).length,c=t.filter(s=>s.success).length;return{agentType:e,totalDecisions:t.length,providerDistribution:i,modelDistribution:o,avgLatencyMs:this.average(n),totalCost:r.reduce((s,l)=>s+(l.cost??0),0),totalTokens:r.reduce((s,l)=>s+l.totalTokens,0),fallbackRate:t.length>0?a/t.length:0,successRate:t.length>0?c/t.length:1}}getAuditLog(e={}){let t=this.decisions;e.since&&(t=t.filter(i=>i.timestamp>=e.since)),e.provider&&(t=t.filter(i=>i.provider===e.provider)),e.agentType&&(t=t.filter(i=>i.agentType===e.agentType));let r=e.limit??100;return t.slice(-r).map(i=>({id:i.id,timestamp:i.timestamp,context:{agentType:i.agentType},decision:{providerType:i.provider,model:i.model,providerModelId:i.model,reason:i.reason,confidence:1,metadata:{decisionTimeMs:i.decisionTimeMs,timestamp:i.timestamp}},outcome:{success:i.success,latencyMs:i.latencyMs,tokenUsage:i.tokenUsage,cost:i.cost}}))}resetMetrics(){this.decisions=[],this.providerCalls=[],this.fallbacks=[],this.cacheHits=0,this.cacheMisses=0,this.startTime=new Date}inferMode(e){switch(e){case"manual":return"manual";case"rule-match":return"rule-based";case"cost-optimization":return"cost-optimized";case"performance-optimization":return"performance-optimized";default:return"rule-based"}}trimRecords(){this.decisions.length>this.maxRecords&&(this.decisions=this.decisions.slice(-this.maxRecords))}trimCallRecords(){this.providerCalls.length>this.maxCallRecords&&(this.providerCalls=this.providerCalls.slice(-this.maxCallRecords))}getWindowStart(e){let t=new Date;switch(e){case"1m":return new Date(t.getTime()-60*1e3);case"5m":return new Date(t.getTime()-300*1e3);case"15m":return new Date(t.getTime()-900*1e3);case"1h":return new Date(t.getTime()-3600*1e3);case"24h":return new Date(t.getTime()-1440*60*1e3);case"7d":return new Date(t.getTime()-10080*60*1e3);default:return this.startTime}}filterByTime(e,t){return e.filter(r=>r.timestamp>=t)}calculateProviderMetrics(e,t){let r=new Map;for(let i of h){let o=e.filter(l=>l.provider===i),n=t.filter(l=>l.provider===i);if(o.length===0&&n.length===0)continue;let a=n.map(l=>l.latencyMs),c=o.map(l=>l.decisionTimeMs),s=n.filter(l=>l.success);r.set(i,{provider:i,selectionCount:o.length,ruleMatchCount:o.filter(l=>l.ruleId).length,fallbackCount:o.filter(l=>l.wasFallback).length,avgDecisionTimeMs:this.average(c),successRate:n.length>0?s.length/n.length:1,avgLatencyMs:this.average(a),p95LatencyMs:this.percentile(a,95),p99LatencyMs:this.percentile(a,99),totalCost:n.reduce((l,d)=>l+(d.cost??0),0),totalTokens:n.reduce((l,d)=>l+d.totalTokens,0),circuitState:"closed"})}return r}calculateAgentMetrics(e,t){let r=new Set;e.forEach(o=>o.agentType&&r.add(o.agentType)),t.forEach(o=>o.agentType&&r.add(o.agentType));let i=new Map;for(let o of r)i.set(o,this.getMetricsByAgentType(o));return i}countByMode(e){let t={manual:0,"rule-based":0,"cost-optimized":0,"performance-optimized":0};for(let r of e)t[r.mode]++;return t}calculateFallbackStats(e){let t=new Map,r=new Map;for(let i of e)t.set(i.fromProvider,(t.get(i.fromProvider)??0)+1),r.set(i.reason,(r.get(i.reason)??0)+1);return{total:e.length,byProvider:t,byReason:r}}calculateCostSavings(e){return e.reduce((t,r)=>r.cost&&r.mode==="cost-optimized"?t+r.cost.totalCost*.2:t,0)}average(e){return e.length===0?0:e.reduce((t,r)=>t+r,0)/e.length}percentile(e,t){if(e.length===0)return 0;let r=[...e].sort((o,n)=>o-n),i=Math.ceil(t/100*r.length)-1;return r[Math.max(0,i)]}};function D(p){return new f(p)}var C=class{records=[];alerts=[];maxRecords;alertCheckInterval;constructor(e={}){this.maxRecords=e.maxRecords??1e4}recordCost(e,t,r,i,o={}){let n=this.calculateCost(t,r,i),a={timestamp:new Date,provider:e,model:t,inputTokens:r,outputTokens:i,inputCost:n.inputCost,outputCost:n.outputCost,totalCost:n.totalCost,agentType:o.agentType,requestId:o.requestId};return this.records.push(a),this.trimRecords(),this.checkAlerts(),a}recordCostFromInfo(e,t,r,i,o={}){let n={timestamp:new Date,provider:e,model:t,inputTokens:r.promptTokens,outputTokens:r.completionTokens,inputCost:i.inputCost,outputCost:i.outputCost,totalCost:i.totalCost,agentType:o.agentType,requestId:o.requestId};return this.records.push(n),this.trimRecords(),this.checkAlerts(),n}getCostByProvider(e="all"){let t=this.getPeriodStart(e),r=this.filterByTime(t),i=new Map;for(let o of h){let n=r.filter(s=>s.provider===o);if(n.length===0)continue;let a=n.reduce((s,l)=>s+l.totalCost,0),c=n.reduce((s,l)=>s+l.inputTokens+l.outputTokens,0);i.set(o,{totalCost:a,totalTokens:c,totalRequests:n.length,avgCostPerRequest:a/n.length,avgCostPerToken:c>0?a/c:0})}return i}getCostByAgentType(e="all"){let t=this.getPeriodStart(e),r=this.filterByTime(t),i=new Set;r.forEach(a=>a.agentType&&i.add(a.agentType));let o=new Map;for(let a of i){let c=r.filter(d=>d.agentType===a),s=c.reduce((d,g)=>d+g.totalCost,0),l=c.reduce((d,g)=>d+g.inputTokens+g.outputTokens,0);o.set(a,{totalCost:s,totalTokens:l,totalRequests:c.length,avgCostPerRequest:c.length>0?s/c.length:0,avgCostPerToken:l>0?s/l:0})}let n=r.filter(a=>!a.agentType);if(n.length>0){let a=n.reduce((s,l)=>s+l.totalCost,0),c=n.reduce((s,l)=>s+l.inputTokens+l.outputTokens,0);o.set("unknown",{totalCost:a,totalTokens:c,totalRequests:n.length,avgCostPerRequest:a/n.length,avgCostPerToken:c>0?a/c:0})}return o}getCostByModel(e="all"){let t=this.getPeriodStart(e),r=this.filterByTime(t),i=new Set;r.forEach(n=>i.add(n.model));let o=new Map;for(let n of i){let a=r.filter(l=>l.model===n),c=a.reduce((l,d)=>l+d.totalCost,0),s=a.reduce((l,d)=>l+d.inputTokens+d.outputTokens,0);o.set(n,{totalCost:c,totalTokens:s,totalRequests:a.length,avgCostPerRequest:a.length>0?c/a.length:0,avgCostPerToken:s>0?c/s:0})}return o}getTotalCost(e="all"){let t=this.getPeriodStart(e);return this.filterByTime(t).reduce((i,o)=>i+o.totalCost,0)}getCostTrend(e){let t=new Date,r=[],i,o;switch(e){case"1h":i=300*1e3,o=12;break;case"24h":i=3600*1e3,o=24;break;case"7d":i=1440*60*1e3,o=7;break}for(let n=o-1;n>=0;n--){let a=new Date(t.getTime()-n*i),c=new Date(a.getTime()-i),s=this.records.filter(l=>l.timestamp>=c&&l.timestamp<a);r.push({timestamp:a,cost:s.reduce((l,d)=>l+d.totalCost,0),tokens:s.reduce((l,d)=>l+d.inputTokens+d.outputTokens,0),requests:s.length})}return r}addBudgetAlert(e,t,r){let i={threshold:e,period:t,callback:r,active:!0};return this.alerts.push(i),this.alertCheckInterval||(this.alertCheckInterval=setInterval(()=>this.checkAlerts(),6e4)),`alert-${this.alerts.length-1}`}removeBudgetAlert(e){return e>=0&&e<this.alerts.length?(this.alerts.splice(e,1),this.alerts.length===0&&this.alertCheckInterval&&(clearInterval(this.alertCheckInterval),this.alertCheckInterval=void 0),!0):!1}getOptimizationSuggestions(){let e=[],t=this.getCostByModel("24h");for(let[n,a]of t)M[n]&&a.totalCost>1&&(n.includes("opus")&&e.push({type:"model-switch",description:"Consider using Sonnet instead of Opus for non-critical tasks",estimatedSavings:a.totalCost*.5,currentCost:a.totalCost,suggestedModel:"claude-sonnet-4-6"}),n==="gpt-4o"&&e.push({type:"model-switch",description:"Consider using GPT-4o-mini for simpler tasks",estimatedSavings:a.totalCost*.7,currentCost:a.totalCost,suggestedModel:"gpt-4o-mini"}));let r=this.getCostByProvider("24h"),i=[...r.values()].reduce((n,a)=>n+a.totalCost,0);return i>10&&!r.has("ollama")&&e.push({type:"provider-switch",description:"Consider using Ollama for development/testing workloads",estimatedSavings:i*.3,currentCost:i,suggestedProvider:"ollama"}),[...t.values()].reduce((n,a)=>n+a.totalRequests,0)>100&&e.push({type:"caching",description:"Enable response caching to reduce redundant API calls",estimatedSavings:i*.15,currentCost:i}),e}getRecords(){return[...this.records]}clear(){this.records=[]}reset(){this.records=[],this.alerts=[],this.alertCheckInterval&&(clearInterval(this.alertCheckInterval),this.alertCheckInterval=void 0)}dispose(){this.alertCheckInterval&&(clearInterval(this.alertCheckInterval),this.alertCheckInterval=void 0)}calculateCost(e,t,r){let i=M[e];if(!i)return{inputCost:0,outputCost:0,totalCost:0,currency:"USD"};let o=t/1e6*i.input,n=r/1e6*i.output;return{inputCost:o,outputCost:n,totalCost:o+n,currency:"USD"}}trimRecords(){this.records.length>this.maxRecords&&(this.records=this.records.slice(-this.maxRecords))}getPeriodStart(e){let t=new Date;switch(e){case"1h":return new Date(t.getTime()-3600*1e3);case"24h":return new Date(t.getTime()-1440*60*1e3);case"7d":return new Date(t.getTime()-10080*60*1e3);case"30d":return new Date(t.getTime()-720*60*60*1e3);default:return new Date(0)}}filterByTime(e){return this.records.filter(t=>t.timestamp>=e)}checkAlerts(){for(let e of this.alerts){if(!e.active)continue;let t=this.getTotalCost(e.period);if(t>=e.threshold){e.active=!1;let r=this.getPeriodStart(e.period),i=this.filterByTime(r),o=i.reduce((n,a)=>n+a.inputTokens+a.outputTokens,0);try{e.callback({totalCost:t,totalTokens:o,totalRequests:i.length,avgCostPerRequest:i.length>0?t/i.length:0,avgCostPerToken:o>0?t/o:0})}catch(n){console.error("Budget alert callback error:",n)}}}}};function E(p){return new C(p)}U();var R=class{cache=new Map;maxSize;ttlMs;constructor(e=100,t=6e4){this.maxSize=e,this.ttlMs=t}get(e){let t=this.cache.get(e);return t?Date.now()>t.expiresAt?(this.cache.delete(e),null):t.decision:null}set(e,t){if(this.cache.size>=this.maxSize){let r=this.cache.keys().next().value;r&&this.cache.delete(r)}this.cache.set(e,{decision:t,expiresAt:Date.now()+this.ttlMs})}clear(){this.cache.clear()}getStats(){return{hits:0,misses:0,size:this.cache.size}}},T=class{config;providerManager;ruleEngine;decisionCache;metrics;routerMetrics;costMetrics;initialized=!1;constructor(e,t){this.providerManager=e,this.config={...z,...t};let r=this.config.rules.length>0?this.config.rules:A;this.ruleEngine=new v(r),this.decisionCache=new R(100,this.config.decisionCacheTtlMs),this.metrics=new q,this.routerMetrics=D(),this.costMetrics=E()}async initialize(){this.initialized||(await this.providerManager.initialize(),this.initialized=!0)}getMode(){return this.config.mode}setMode(e){this.config.mode=e,this.decisionCache.clear()}getConfig(){return{...this.config}}updateConfig(e){this.config={...this.config,...e},e.rules&&this.ruleEngine.setRules(e.rules),e.decisionCacheTtlMs&&(this.decisionCache=new R(100,e.decisionCacheTtlMs))}async selectProvider(e){await this.ensureInitialized();let t=Date.now();if(this.config.cacheDecisions){let i=this.generateCacheKey(e),o=this.decisionCache.get(i);if(o)return this.metrics.recordCacheHit(),this.routerMetrics.recordCacheHit(),o;this.metrics.recordCacheMiss(),this.routerMetrics.recordCacheMiss()}let r;switch(this.config.mode){case"manual":r=await this.selectManual(e);break;case"rule-based":r=await this.selectRuleBased(e);break;case"cost-optimized":r=await this.selectCostOptimized(e);break;case"performance-optimized":r=await this.selectPerformanceOptimized(e);break;default:r=await this.selectRuleBased(e)}if(r.metadata.decisionTimeMs=Date.now()-t,this.config.cacheDecisions){let i=this.generateCacheKey(e);this.decisionCache.set(i,r)}return this.metrics.recordDecision(r,this.config.mode),r}async chat(e){await this.ensureInitialized();let t=I(),r=await this.selectProvider(e),i=e.agentType??"";if(_(i)&&(x(r.model)||x(r.providerModelId))){let n=r.model,a=r.providerModelId;r.model=w(i,r.model,k),r.providerModelId=w(i,r.providerModelId,k),console.warn(`[aqe] ADR-093: ${i} pinned to ${r.model} (was ${n}/${a}); set AQE_CYBER_VERIFIED=true after Cyber Verification Program approval`)}return await this.executeWithFallback(e,r,t)}async*stream(e){await this.ensureInitialized();let t=await this.selectProvider(e),r=await this.chat(e),i=100;for(let o=0;o<r.content.length;o+=i){let n=o+i>=r.content.length;yield{type:n?"done":"content",delta:r.content.slice(o,o+i),accumulated:r.content.slice(0,o+i),done:n,tokenCount:Math.ceil((o+i)/4),model:r.model,provider:t.providerType,usage:n?r.usage:void 0}}}getMetrics(){return this.metrics.getMetrics()}getEnhancedMetrics(e){return this.routerMetrics.getMetrics(e)}getProviderMetrics(e){return this.routerMetrics.getMetricsByProvider(e)}getAgentMetrics(e){return this.routerMetrics.getMetricsByAgentType(e)}getCostByProvider(e){return this.costMetrics.getCostByProvider(e)}getCostByAgentType(e){return this.costMetrics.getCostByAgentType(e)}getCostByModel(e){return this.costMetrics.getCostByModel(e)}getTotalCost(e){return this.costMetrics.getTotalCost(e)}getCostTrend(e){return this.costMetrics.getCostTrend(e)}getAuditLog(e){return this.routerMetrics.getAuditLog(e)}getOptimizationSuggestions(){return this.costMetrics.getOptimizationSuggestions()}resetMetrics(){this.metrics.reset(),this.routerMetrics.resetMetrics(),this.costMetrics.reset()}clearCache(){this.decisionCache.clear()}async selectManual(e){let t=e.preferredProvider??this.config.defaultProvider,r=e.model??this.config.defaultModel,i=this.providerManager.getProvider(t);return i?this.createDecision(i,t,r,"manual"):this.createFallbackDecision(e,"manual")}async selectRuleBased(e){let t=this.ruleEngine.evaluate(e);if(t){let{rule:o,rulesEvaluated:n}=t,a=o.action.provider,c=this.providerManager.getProvider(a);if(c){let s=this.createDecision(c,a,o.action.model,"rule-match",o);return s.metadata.rulesEvaluated=n,s}}let r=this.config.defaultProvider,i=this.providerManager.getProvider(r);return i?this.createDecision(i,r,this.config.defaultModel,"default"):this.createFallbackDecision(e,"rule-based")}async selectCostOptimized(e){let t=this.providerManager.getAvailableProviders();if(t.length===0)return this.createFallbackDecision(e,"cost-optimized");let r=1/0,i=t[0],o,n=[];for(let a of t){let c=this.providerManager.getProvider(a);if(!c)continue;let{input:s,output:l}=c.getCostPerToken(),d=this.estimateCostValue(e,s,l);n.push({provider:a,model:c.getConfig().model,reason:`Estimated cost: $${d.toFixed(6)}`,estimatedCost:d,excluded:!1}),d<r&&(r=d,i=a,o=c)}if(o){let a=o.getConfig(),c=this.createDecision(o,i,a.model,"cost-optimization");return c.metadata.estimatedCost=this.createCostEstimate(e,o),c.metadata.alternativesConsidered=n,c}return this.createFallbackDecision(e,"cost-optimized")}async selectPerformanceOptimized(e){let t=this.providerManager.getAvailableProviders(),r=this.providerManager.getMetrics();if(t.length===0)return this.createFallbackDecision(e,"performance-optimized");let i=1/0,o=t[0],n,a=[];for(let c of t){let s=this.providerManager.getProvider(c);if(!s)continue;let d=r[c]?.avgLatencyMs??1/0;a.push({provider:c,model:s.getConfig().model,reason:`Avg latency: ${d}ms`,estimatedLatencyMs:d,excluded:!1}),d<i&&(i=d,o=c,n=s)}if(n){let c=n.getConfig(),s=this.createDecision(n,o,c.model,"performance-optimization");return s.metadata.estimatedLatencyMs=i,s.metadata.alternativesConsidered=a,s}return this.createFallbackDecision(e,"performance-optimized")}async executeWithFallback(e,t,r){let{fallbackChain:i,fallbackBehavior:o}=this.config,n,a=0,c=[{provider:t.providerType,model:t.providerModelId}];for(let s of i.entries)if(!(!s.enabled||s.provider===t.providerType||!["claude","openai","ollama"].includes(s.provider)))for(let d of s.models)c.push({provider:s.provider,model:d});for(let{provider:s,model:l}of c){if(a>=o.maxAttempts)break;let d=this.providerManager.getProvider(s);if(!d)continue;a++;let g=Date.now();try{let u=await d.generate(e.messages,{model:l,temperature:e.temperature,maxTokens:e.maxTokens,systemPrompt:e.systemPrompt,timeoutMs:e.timeoutMs,skipCache:e.skipCache,metadata:e.metadata}),y=Date.now()-g;return this.metrics.recordSuccess(s),this.routerMetrics.recordRoutingDecision(t,y,{agentType:e.agentType,success:!0,tokenUsage:u.usage,cost:u.cost}),this.routerMetrics.recordProviderCall(s,l,y,u.usage.totalTokens,{inputTokens:u.usage.promptTokens,outputTokens:u.usage.completionTokens,success:!0,cost:u.cost.totalCost,agentType:e.agentType}),this.costMetrics.recordCostFromInfo(s,l,u.usage,u.cost,{agentType:e.agentType,requestId:u.requestId}),{content:u.content,model:u.model,providerModelId:u.model,provider:u.provider,usage:u.usage,cost:u.cost,latencyMs:u.latencyMs,finishReason:u.finishReason,cached:u.cached,requestId:u.requestId,routingDecision:t}}catch(u){n=S(u);let y=Date.now()-g;if(this.metrics.recordFailure(s),this.routerMetrics.recordProviderCall(s,l,y,0,{success:!1,agentType:e.agentType}),a<c.length){let L=c[a];L&&this.routerMetrics.recordFallback(s,L.provider,n.message,e.agentType)}if(B(u)&&!u.retryable)throw u;a<o.maxAttempts&&await this.delay(o.delayMs)}}throw b(`All providers failed after ${a} attempts: ${n?.message??"Unknown error"}`,"PROVIDER_UNAVAILABLE",{retryable:!1,cause:n})}createDecision(e,t,r,i,o){let{canonicalModel:n,providerModelId:a}=this.resolveModelIds(r,t);return{provider:e,providerType:t,model:n,providerModelId:a,reason:i,matchedRule:o,confidence:i==="rule-match"?.95:.8,metadata:{decisionTimeMs:0,timestamp:new Date}}}resolveModelIds(e,t){let i={claude:"anthropic",openai:"openai",ollama:"ollama",openrouter:"openrouter",gemini:"gemini","azure-openai":"azure",bedrock:"bedrock"}[t];if(!i)return{canonicalModel:e,providerModelId:e};try{let o=O(e),n=P(o,i);return{canonicalModel:o,providerModelId:n}}catch{try{if(F(e)){let n=P(e,i);return{canonicalModel:e,providerModelId:n}}}catch{}return{canonicalModel:e,providerModelId:e}}}createFallbackDecision(e,t){for(let i of this.config.fallbackChain.entries){if(!i.enabled||!["claude","openai","ollama"].includes(i.provider))continue;let n=this.providerManager.getProvider(i.provider);if(n)return this.createDecision(n,i.provider,i.models[0],"fallback")}let r=this.providerManager.getAvailableProviders();if(r.length>0){let i=r[0],o=this.providerManager.getProvider(i);return this.createDecision(o,i,o.getConfig().model,"fallback")}throw b(`No providers available for ${t} selection`,"PROVIDER_UNAVAILABLE",{retryable:!1})}generateCacheKey(e){return[this.config.mode,e.agentType??"default",e.complexity??"medium",e.requiresTools?"tools":"no-tools",e.preferredProvider??"any"].join(":")}estimateCostValue(e,t,r){let i=0;e.systemPrompt&&(i+=Math.ceil(e.systemPrompt.length/4));for(let n of e.messages)i+=Math.ceil(n.content.length/4);let o=e.maxTokens??1e3;return i*t+o*r}createCostEstimate(e,t){let{input:r,output:i}=t.getCostPerToken(),o=0;e.systemPrompt&&(o+=Math.ceil(e.systemPrompt.length/4));for(let c of e.messages)o+=Math.ceil(c.content.length/4);let n=e.maxTokens??1e3,a=o*r+n*i;return{inputTokens:o,outputTokens:n,totalCostUsd:a,inputCostPer1M:r*1e6,outputCostPer1M:i*1e6}}delay(e){return new Promise(t=>setTimeout(t,e))}async ensureInitialized(){this.initialized||await this.initialize()}},q=class{decisions=new Map;decisionsByMode={manual:0,"rule-based":0,"cost-optimized":0,"performance-optimized":0};totalDecisions=0;cacheHits=0;cacheMisses=0;totalRulesEvaluated=0;rulesMatched=0;fallbackCount=0;startTime=new Date;recordDecision(e,t){this.totalDecisions++,this.decisionsByMode[t]++,e.metadata.rulesEvaluated&&(this.totalRulesEvaluated+=e.metadata.rulesEvaluated),e.matchedRule&&this.rulesMatched++,e.reason==="fallback"&&this.fallbackCount++;let r=this.decisions.get(e.providerType);r||(r=this.createEmptyMetrics(e.providerType),this.decisions.set(e.providerType,r)),r.selectionCount++,e.reason==="rule-match"&&r.ruleMatchCount++,e.reason==="fallback"&&r.fallbackCount++}recordSuccess(e){let t=this.decisions.get(e);if(t){let r=t.successRate*t.selectionCount;t.successRate=(r+1)/t.selectionCount}}recordFailure(e){}recordCacheHit(){this.cacheHits++}recordCacheMiss(){this.cacheMisses++}getMetrics(){let e={};for(let[r,i]of this.decisions)e[r]={...i};let t=this.totalDecisions>0?this.rulesMatched/this.totalDecisions:0;return{byProvider:e,totalDecisions:this.totalDecisions,decisionsByMode:{...this.decisionsByMode},avgDecisionTimeMs:0,p95DecisionTimeMs:0,p99DecisionTimeMs:0,fallbackRate:this.totalDecisions>0?this.fallbackCount/this.totalDecisions:0,ruleMatchRate:t,estimatedCostSavings:0,ruleStats:{totalEvaluated:this.totalRulesEvaluated,matched:this.rulesMatched,avgRulesPerDecision:this.totalDecisions>0?this.totalRulesEvaluated/this.totalDecisions:0},cacheStats:{hits:this.cacheHits,misses:this.cacheMisses,hitRate:this.cacheHits+this.cacheMisses>0?this.cacheHits/(this.cacheHits+this.cacheMisses):0},period:{start:this.startTime,end:new Date}}}reset(){this.decisions.clear(),this.decisionsByMode={manual:0,"rule-based":0,"cost-optimized":0,"performance-optimized":0},this.totalDecisions=0,this.cacheHits=0,this.cacheMisses=0,this.totalRulesEvaluated=0,this.rulesMatched=0,this.fallbackCount=0,this.startTime=new Date}createEmptyMetrics(e){return{provider:e,selectionCount:0,ruleMatchCount:0,fallbackCount:0,avgDecisionTimeMs:0,successRate:1,avgLatencyMs:0,p95LatencyMs:0,p99LatencyMs:0,totalCost:0,totalTokens:0,circuitState:"closed"}}};function Je(p,e){return new T(p,e)}function Qe(p){return new T(p,{mode:"rule-based",rules:A,defaultProvider:"claude",defaultModel:"claude-sonnet-4-6",enableMetrics:!0,cacheDecisions:!0})}export{T as HybridRouter,Je as createHybridRouter,Qe as createQERouter};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{a,b,c,d,e}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.18");process.exit(0)}
|
|
2
|
+
import{a,b,c,d,e}from"./chunk-NKOLFLXF.js";import"./chunk-AGPZVE6B.js";import"./chunk-6ZMQL3U6.js";import"./chunk-UNPTSPAO.js";import"./chunk-LVABI4OA.js";import"./chunk-FKNYOKIK.js";export{a as DEFAULT_HYPERGRAPH_ENGINE_CONFIG,b as HypergraphEngine,c as createHypergraphEngine,d as createHypergraphEngineSync,e as default};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.18");process.exit(0)}
|
|
2
|
+
import"./chunk-FKNYOKIK.js";import e from"chalk";import{join as m,resolve as h}from"path";import{existsSync as y}from"fs";var c=class{name="hypergraph";description="Query the code knowledge hypergraph";cleanupAndExit;ensureInitialized;constructor(n,r){this.cleanupAndExit=n,this.ensureInitialized=r}register(n,r){let s=n.command("hypergraph").alias("hg").description(this.description);s.command("stats").description("Show hypergraph statistics (node/edge counts by type)").option("--db <path>","Database path").action(async t=>{await this.executeStats(t)}),s.command("untested").description("Find functions with no test coverage").option("--db <path>","Database path").option("--limit <number>","Max results","20").action(async t=>{await this.executeUntested(t)}),s.command("impacted <files...>").description("Find tests impacted by changed files").option("--db <path>","Database path").action(async(t,i)=>{await this.executeImpacted(t,i)}),s.command("gaps").description("Find functions with low coverage").option("--db <path>","Database path").option("--max-coverage <number>","Coverage threshold (%)","50").option("--limit <number>","Max results","20").action(async t=>{await this.executeGaps(t)})}async executeStats(n){if(!await this.ensureInitialized())return;let{engine:r,close:s}=await this.openEngine(n.db);try{let t=await r.getStats();if(console.log(e.blue(`
|
|
3
3
|
Hypergraph Statistics
|
|
4
4
|
`)),console.log(e.white(` Total nodes: ${t.totalNodes}`)),console.log(e.white(` Total edges: ${t.totalEdges}`)),t.totalNodes>0){console.log(e.gray(`
|
|
5
5
|
Nodes by type:`));for(let[i,o]of Object.entries(t.nodesByType))o>0&&console.log(e.gray(` ${i}: ${o}`));console.log(e.gray(`
|
|
@@ -15,7 +15,7 @@ import"./chunk-NOJVROCD.js";import e from"chalk";import{join as m,resolve as h}f
|
|
|
15
15
|
`))}finally{i()}await this.cleanupAndExit(0)}async executeGaps(n){if(!await this.ensureInitialized())return;let{engine:r,close:s}=await this.openEngine(n.db);try{let t=parseInt(n.maxCoverage,10)||50,i=parseInt(n.limit,10)||20,o=await r.findCoverageGaps(t),a=o.slice(0,i);if(console.log(e.blue(`
|
|
16
16
|
Coverage Gaps (<= ${t}%) \u2014 ${o.length} total
|
|
17
17
|
`)),a.length===0)console.log(e.green(" No coverage gaps found!"));else{for(let l of a){let d=l.coverage!==void 0?e.red(` ${l.coverage}%`):"",p=l.complexity?e.yellow(` complexity=${l.complexity}`):"";console.log(e.white(` ${l.name}`)+d+e.gray(` ${l.filePath||""}`)+p)}o.length>i&&console.log(e.gray(`
|
|
18
|
-
... and ${o.length-i} more (use --limit to show more)`))}console.log("")}finally{s()}await this.cleanupAndExit(0)}async openEngine(n){let{findProjectRoot:r}=await import("./unified-memory-
|
|
18
|
+
... and ${o.length-i} more (use --limit to show more)`))}console.log("")}finally{s()}await this.cleanupAndExit(0)}async openEngine(n){let{findProjectRoot:r}=await import("./unified-memory-BTX45KY5.js"),{openDatabase:s}=await import("./safe-db-NVEBL662.js"),{createHypergraphEngine:t}=await import("./hypergraph-engine-FT5YK5RF.js"),i=r(),o=n||m(i,".agentic-qe","memory.db");if(!y(o))throw new Error(`Database not found: ${o}
|
|
19
19
|
Run "aqe init --auto" first.`);let a=s(o);try{return{engine:await t({db:a,maxTraversalDepth:10,maxQueryResults:1e3,enableVectorSearch:!1}),close:()=>{try{a.close()}catch{}}}}catch(l){try{a.close()}catch{}throw l}}getHelp(){return`
|
|
20
20
|
Query the code knowledge hypergraph for untested functions,
|
|
21
21
|
impacted tests, and coverage gaps.
|
|
@@ -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.18");process.exit(0)}
|
|
2
|
+
import{a}from"./chunk-YZIOM7JL.js";import"./chunk-JGNVI5UB.js";import"./chunk-4XYQJ4LQ.js";import"./chunk-6KTF7QB3.js";import"./chunk-6ZMQL3U6.js";import"./chunk-TPL3CBMS.js";import"./chunk-UNPTSPAO.js";import"./chunk-LVABI4OA.js";import"./chunk-FKNYOKIK.js";export{a as ImpactAnalyzerService};
|