agentic-qe 3.10.7 → 3.10.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude/skills/skills-manifest.json +1 -1
- package/CHANGELOG.md +48 -0
- package/dist/cli/bundle.js +5 -5
- package/dist/cli/chunks/adapter-PAMPC2X7.js +2 -0
- package/dist/cli/chunks/{agent-booster-wasm-6I3JMU2M.js → agent-booster-wasm-4JSL6LF6.js} +2 -2
- package/dist/cli/chunks/{agent-handler-XWI7YM6R.js → agent-handler-6YOFH7KL.js} +2 -2
- package/dist/cli/chunks/{agent-memory-branch-QFZKQN2L.js → agent-memory-branch-O3IBK4BY.js} +2 -2
- package/dist/cli/chunks/aqe-learning-engine-DGKLEC6I.js +2 -0
- package/dist/cli/chunks/{arena-P4IUBKZP.js → arena-BLCAZNAY.js} +2 -2
- package/dist/cli/chunks/{arena-5HNPVTBZ.js → arena-KLGRZTTU.js} +4 -4
- package/dist/cli/chunks/{audit-PBSH25VZ.js → audit-FKKLR22S.js} +2 -2
- package/dist/cli/chunks/base-6HJR4VJT.js +2 -0
- package/dist/cli/chunks/{hnswlib-node-ILDTCGLZ.js → better-sqlite3-MROES2Y7.js} +2 -2
- package/dist/cli/chunks/{brain-handler-EVYRCKXI.js → brain-handler-YTGYC2QW.js} +3 -3
- package/dist/cli/chunks/{branch-enumerator-SUDGYJQJ.js → branch-enumerator-KIIBEJ5S.js} +2 -2
- package/dist/cli/chunks/{browser-4UKMW2RE.js → browser-7YZLTV2C.js} +2 -2
- package/dist/cli/chunks/browser-workflow-OWNU5XK7.js +2 -0
- package/dist/cli/chunks/chunk-2B2RLPK3.js +2 -0
- package/dist/cli/chunks/{chunk-AKL5A3IZ.js → chunk-2F4VRCT6.js} +1 -1
- package/dist/cli/chunks/{chunk-NKYMHEHY.js → chunk-2KP5TJS2.js} +2 -2
- package/dist/cli/chunks/{chunk-4MJQJQLY.js → chunk-2RDWYJJY.js} +2 -2
- package/dist/cli/chunks/{chunk-2J4ZUUU5.js → chunk-2UL4UK6V.js} +2 -2
- package/dist/cli/chunks/{chunk-QMGNYRR5.js → chunk-33CLP2NE.js} +3 -3
- package/dist/cli/chunks/{chunk-INI3AGF5.js → chunk-34LWJDCM.js} +2 -2
- package/dist/cli/chunks/{chunk-FK4JHBG4.js → chunk-3AG2MM7U.js} +2 -2
- package/dist/cli/chunks/{chunk-UVUVWA4B.js → chunk-474ZUVGP.js} +1 -1
- package/dist/cli/chunks/{chunk-LEZ2MGHM.js → chunk-4AG2TQEF.js} +3 -3
- package/dist/cli/chunks/{chunk-LFSQSLNP.js → chunk-4B676LUC.js} +2 -2
- package/dist/cli/chunks/{chunk-OPLLH67G.js → chunk-4G2GTX2V.js} +1 -1
- package/dist/cli/chunks/{chunk-K6IU2MV4.js → chunk-4IGSL7CX.js} +1 -1
- package/dist/cli/chunks/{chunk-Z44VJC5U.js → chunk-4OHLPG6B.js} +2 -2
- package/dist/cli/chunks/{chunk-DPT37UHR.js → chunk-54PBHRRW.js} +4 -4
- package/dist/cli/chunks/{chunk-AY4IEMRI.js → chunk-5GPOSKGP.js} +2 -2
- package/dist/cli/chunks/{chunk-BU2I77YW.js → chunk-5KUINS3D.js} +3 -3
- package/dist/cli/chunks/{chunk-BPC6X6VR.js → chunk-6B32USSC.js} +2 -2
- package/dist/cli/chunks/{chunk-SG6O3PXZ.js → chunk-6B3COND2.js} +2 -2
- package/dist/cli/chunks/{chunk-262F3EMN.js → chunk-6R6RC6YJ.js} +2 -2
- package/dist/cli/chunks/{chunk-LJHCPN4E.js → chunk-77BVW2CT.js} +2 -2
- package/dist/cli/chunks/{chunk-LSHUPEQQ.js → chunk-7LHN6WBX.js} +2 -2
- package/dist/cli/chunks/{chunk-L2ZSYIDA.js → chunk-7NKVEEXD.js} +1 -1
- package/dist/cli/chunks/{chunk-3IJS52OS.js → chunk-AGQIJWAD.js} +2 -2
- package/dist/cli/chunks/{chunk-V7WBNB2S.js → chunk-ALFF4AAM.js} +2 -2
- package/dist/cli/chunks/{chunk-HARYQMWN.js → chunk-B3B5QZYN.js} +2 -2
- package/dist/cli/chunks/{chunk-MMR23KAO.js → chunk-BALWMVCX.js} +2 -2
- package/dist/cli/chunks/{chunk-C5CY5NSW.js → chunk-BMSMDD72.js} +2 -2
- package/dist/cli/chunks/{chunk-J5ETX2DG.js → chunk-C6TUX7YJ.js} +2 -2
- package/dist/cli/chunks/{chunk-M7SO5KNJ.js → chunk-CCUUTTTJ.js} +2 -2
- package/dist/cli/chunks/{chunk-HELQ7CXL.js → chunk-CDNXXNQM.js} +1 -1
- package/dist/cli/chunks/{chunk-CJTDQJ7E.js → chunk-CHPL7TA4.js} +1 -1
- package/dist/cli/chunks/{chunk-OMDV6GFP.js → chunk-CO6UY7ZU.js} +1 -1
- package/dist/cli/chunks/{chunk-I7M574IO.js → chunk-CP4CSI5R.js} +2 -2
- package/dist/cli/chunks/{chunk-AW3LGLC3.js → chunk-D7IH2A3C.js} +2 -2
- package/dist/cli/chunks/{chunk-2MLISLRR.js → chunk-D7ZVIL3C.js} +1 -1
- package/dist/cli/chunks/{chunk-QBVFONWU.js → chunk-DDMKCHYT.js} +2 -2
- package/dist/cli/chunks/{chunk-B5ZJV7GZ.js → chunk-DI7REPYC.js} +2 -2
- package/dist/cli/chunks/{chunk-MK73CCKO.js → chunk-DNC27OP7.js} +2 -2
- package/dist/cli/chunks/{chunk-K6A3AWUI.js → chunk-DNEYBK7X.js} +1 -1
- package/dist/cli/chunks/{chunk-DYSRMAZP.js → chunk-DPSLJ6IW.js} +1 -1
- package/dist/cli/chunks/{chunk-S7FNTWFM.js → chunk-E5GUTKET.js} +2 -2
- package/dist/cli/chunks/{chunk-HDLF6LGO.js → chunk-FPEFIJQ6.js} +3 -3
- package/dist/cli/chunks/{chunk-YB4GXJJG.js → chunk-FWQZZ22V.js} +1 -1
- package/dist/cli/chunks/{chunk-EWNJK2BU.js → chunk-FXPAGKVS.js} +1 -1
- package/dist/cli/chunks/{chunk-PY3HWJRJ.js → chunk-G2J7WGOG.js} +2 -2
- package/dist/cli/chunks/{chunk-222ZQTL5.js → chunk-G73PIM7X.js} +2 -2
- package/dist/cli/chunks/{chunk-CW7JQVXV.js → chunk-GDHJZPNC.js} +2 -2
- package/dist/cli/chunks/{chunk-S423UHYM.js → chunk-GHIHW3IE.js} +2 -2
- package/dist/cli/chunks/{chunk-MRLGQX7Y.js → chunk-GXKCRIHK.js} +2 -2
- package/dist/cli/chunks/{chunk-SLASYVNX.js → chunk-H35FNLQJ.js} +2 -2
- package/dist/cli/chunks/{chunk-SFW6IDMR.js → chunk-H73AA2JI.js} +10 -10
- package/dist/cli/chunks/{chunk-76JYG426.js → chunk-HE3KLHNO.js} +2 -2
- package/dist/cli/chunks/{chunk-JJELOEIY.js → chunk-HEC2UWY3.js} +4 -4
- package/dist/cli/chunks/{chunk-4I6FK67T.js → chunk-HVE3EH36.js} +3 -3
- package/dist/cli/chunks/{chunk-6F5KPT6U.js → chunk-HVFHPDXV.js} +1 -1
- package/dist/cli/chunks/{chunk-MOI74MMX.js → chunk-HWJEHXPQ.js} +2 -2
- package/dist/cli/chunks/{chunk-BRYYQQUV.js → chunk-IFQPGBKQ.js} +1 -1
- package/dist/cli/chunks/{chunk-FWLXK6AH.js → chunk-JFTRHS5V.js} +2 -2
- package/dist/cli/chunks/{chunk-UPDPD43T.js → chunk-JITZAJJN.js} +2 -2
- package/dist/cli/chunks/{chunk-6RG7ZJ2H.js → chunk-JQBD4JO2.js} +2 -2
- package/dist/cli/chunks/{chunk-LUZH2IZY.js → chunk-JZYXYHEE.js} +2 -2
- package/dist/cli/chunks/{chunk-MWRKNBSY.js → chunk-K5Y64X2U.js} +2 -2
- package/dist/cli/chunks/{chunk-RLXCFURS.js → chunk-KTBBSOZG.js} +2 -2
- package/dist/cli/chunks/{chunk-MDVJVY4C.js → chunk-KTEWRRDZ.js} +4 -4
- package/dist/cli/chunks/{chunk-L5UUUSSB.js → chunk-KWKGROPS.js} +1 -1
- package/dist/cli/chunks/{chunk-X6OJFP7G.js → chunk-LBR5FXPD.js} +2 -2
- package/dist/cli/chunks/{chunk-X3HRJV65.js → chunk-LCDMB5SP.js} +1 -1
- package/dist/cli/chunks/{chunk-TIUC5LRA.js → chunk-LIOK7WBX.js} +2 -2
- package/dist/cli/chunks/{chunk-BLFZFKT6.js → chunk-LJEO5R32.js} +2 -2
- package/dist/cli/chunks/{chunk-4RGV6Z2H.js → chunk-LT4OZHMK.js} +2 -2
- package/dist/cli/chunks/{chunk-6QBD64W3.js → chunk-LZVKR7HV.js} +2 -2
- package/dist/cli/chunks/{chunk-YLXUF5KW.js → chunk-M5PBVK3V.js} +3 -3
- package/dist/cli/chunks/{chunk-IXAABYGS.js → chunk-MSWBVPVQ.js} +2 -2
- package/dist/cli/chunks/{chunk-XWPUCPYW.js → chunk-MTWBYHMS.js} +2 -2
- package/dist/cli/chunks/{chunk-WCXQA24H.js → chunk-MWAEUJDC.js} +8 -8
- package/dist/cli/chunks/{chunk-6OLPKIYU.js → chunk-NFZY6ZVY.js} +1 -1
- package/dist/cli/chunks/{chunk-5QMIVHFT.js → chunk-NKKDO5W4.js} +2 -2
- package/dist/cli/chunks/{chunk-34NT5NBZ.js → chunk-NL4EKO2J.js} +2 -2
- package/dist/cli/chunks/{chunk-U7EGKKN3.js → chunk-NOP5ZJ7E.js} +2 -2
- package/dist/cli/chunks/{chunk-LHZYTNOQ.js → chunk-NSI3WL6P.js} +2 -2
- package/dist/cli/chunks/{chunk-IYZWEYWJ.js → chunk-NWIKNQLJ.js} +1 -1
- package/dist/cli/chunks/chunk-O75ODKCX.js +2 -0
- package/dist/cli/chunks/{chunk-TTLAWPEN.js → chunk-OIU6PKLF.js} +2 -2
- package/dist/cli/chunks/{chunk-R7KIC6TL.js → chunk-OK6CSJOX.js} +1 -1
- package/dist/cli/chunks/{chunk-HBWAMCVB.js → chunk-OLOKPY5O.js} +14 -14
- package/dist/cli/chunks/chunk-ON6C2OYG.js +2 -0
- package/dist/cli/chunks/{chunk-AKSCYNFH.js → chunk-OV3ESWN4.js} +2 -2
- package/dist/cli/chunks/{chunk-7NK2H7H5.js → chunk-OZDRAKFF.js} +2 -2
- package/dist/cli/chunks/{chunk-ISLI6D4K.js → chunk-PG7KISET.js} +2 -2
- package/dist/cli/chunks/{chunk-TXXRBNOB.js → chunk-PRYSWF6F.js} +1 -1
- package/dist/cli/chunks/{chunk-QLVZEEPR.js → chunk-PTPGYUT2.js} +2 -2
- package/dist/cli/chunks/{chunk-3XEL7XCA.js → chunk-Q32LITZL.js} +1 -1
- package/dist/cli/chunks/{chunk-CGBEI7UH.js → chunk-Q7B7T4YK.js} +2 -2
- package/dist/cli/chunks/{chunk-GUDOOOO6.js → chunk-QHGHWATK.js} +1 -1
- package/dist/cli/chunks/{chunk-DYNO72WD.js → chunk-QHLENBGB.js} +2 -2
- package/dist/cli/chunks/{chunk-32E2OPIE.js → chunk-QNNH5TDV.js} +3 -3
- package/dist/cli/chunks/{chunk-F5RZSNHI.js → chunk-R2LWUBET.js} +2 -2
- package/dist/cli/chunks/{chunk-L6NB4UHR.js → chunk-RNJRKFMX.js} +2 -2
- package/dist/cli/chunks/{chunk-VPBXVZWE.js → chunk-RXWPYY6H.js} +1 -1
- package/dist/cli/chunks/{chunk-R2B6EQQF.js → chunk-S6PGWJDK.js} +2 -2
- package/dist/cli/chunks/chunk-SDGRU6SG.js +2 -0
- package/dist/cli/chunks/{chunk-O4B6FFC5.js → chunk-SDVL5TZK.js} +1 -1
- package/dist/cli/chunks/{chunk-JNQVPTOM.js → chunk-SSRMFU4P.js} +2 -2
- package/dist/cli/chunks/{chunk-S4NNQE4L.js → chunk-T2Z3M6HA.js} +1 -1
- package/dist/cli/chunks/{chunk-4W5QWFU4.js → chunk-TXLLF7XR.js} +1 -1
- package/dist/cli/chunks/{chunk-QDBFB4XD.js → chunk-UU422SST.js} +2 -2
- package/dist/cli/chunks/{chunk-L3EQQMFI.js → chunk-VKLPSPPI.js} +2 -2
- package/dist/cli/chunks/{chunk-RJBCIN2G.js → chunk-VL4MSE3J.js} +2 -2
- package/dist/cli/chunks/{chunk-3W6QASVB.js → chunk-VM5C4DIV.js} +2 -2
- package/dist/cli/chunks/{chunk-OAXDI4XM.js → chunk-W72CUJRB.js} +1 -1
- package/dist/cli/chunks/{chunk-3O4Q4GAX.js → chunk-WDZT344G.js} +1 -1
- package/dist/cli/chunks/{chunk-64BSODHA.js → chunk-WKLI5Z3L.js} +2 -2
- package/dist/cli/chunks/{chunk-YMBPKBKG.js → chunk-WYAHOUK2.js} +1 -1
- package/dist/cli/chunks/{chunk-UURGDFGU.js → chunk-X3NEQ3SL.js} +1 -1
- package/dist/cli/chunks/{chunk-DU7Y54JI.js → chunk-X4CHPEOQ.js} +1 -1
- package/dist/cli/chunks/{chunk-JNXPRDNV.js → chunk-XKIVOADM.js} +3 -3
- package/dist/cli/chunks/{chunk-G7ISGLKP.js → chunk-XLQX77KP.js} +1 -1
- package/dist/cli/chunks/{chunk-76SUEI7S.js → chunk-XNFYQRJ2.js} +1 -1
- package/dist/cli/chunks/{chunk-6A2HRMTD.js → chunk-XPAH7SEX.js} +2 -2
- package/dist/cli/chunks/{chunk-HI4DA7Z3.js → chunk-XRJH5KXF.js} +2 -2
- package/dist/cli/chunks/{chunk-TY7XPI6R.js → chunk-XYXRO7VP.js} +2 -2
- package/dist/cli/chunks/{chunk-OW4LJ5HE.js → chunk-Y4XTPEAC.js} +2 -2
- package/dist/cli/chunks/chunk-YATW2RWQ.js +2 -0
- package/dist/cli/chunks/{chunk-KXENXRZE.js → chunk-YMJ5AVVU.js} +1 -1
- package/dist/cli/chunks/{chunk-2JWFS2K2.js → chunk-YQYTQRTR.js} +2 -2
- package/dist/cli/chunks/{chunk-OSETFZVE.js → chunk-YUK4KU2B.js} +2 -2
- package/dist/cli/chunks/{chunk-V3KNHI5B.js → chunk-Z4WAJ647.js} +2 -2
- package/dist/cli/chunks/{chunk-FQBNPSV2.js → chunk-Z57UERQZ.js} +2 -2
- package/dist/cli/chunks/{chunk-YBM4LUSF.js → chunk-Z7FWPSOK.js} +2 -2
- package/dist/cli/chunks/{chunk-QBVS4CXM.js → chunk-ZSMHQENA.js} +1 -1
- package/dist/cli/chunks/{ci-OO42YBET.js → ci-2G4BBIQD.js} +2 -2
- package/dist/cli/chunks/{ci-output-YXMTEX7Q.js → ci-output-SI3ME52L.js} +2 -2
- package/dist/cli/chunks/{circuit-breaker-EHA4N643.js → circuit-breaker-KTICF3EC.js} +2 -2
- package/dist/cli/chunks/{claude-flow-setup-E6G6SLYI.js → claude-flow-setup-F44PULFU.js} +2 -2
- package/dist/cli/chunks/client-E6GK5NWT.js +2 -0
- package/dist/cli/chunks/{cline-installer-6JPWD64G.js → cline-installer-A7G7OXIS.js} +2 -2
- package/dist/cli/chunks/{code-Q3U6XDOO.js → code-EDLIBN77.js} +2 -2
- package/dist/cli/chunks/{code-index-extractor-BK2DC4MO.js → code-index-extractor-P4NBWGTV.js} +2 -2
- package/dist/cli/chunks/{codex-installer-DA3GBMLN.js → codex-installer-JB3ULDQP.js} +2 -2
- package/dist/cli/chunks/{completions-TZ5F33TA.js → completions-XPCXB5SR.js} +2 -2
- package/dist/cli/chunks/{complexity-analyzer-N7U4V7ID.js → complexity-analyzer-LAL5RSB7.js} +2 -2
- package/dist/cli/chunks/{continuedev-installer-DDDJGW26.js → continuedev-installer-GSYBLQV7.js} +2 -2
- package/dist/cli/chunks/{copilot-installer-JVFCE6GT.js → copilot-installer-7B56CNU2.js} +2 -2
- package/dist/cli/chunks/core-handlers-HJUORTFU.js +2 -0
- package/dist/cli/chunks/{cost-tracker-ZTIDLUFW.js → cost-tracker-EUJFKHGT.js} +2 -2
- package/dist/cli/chunks/{coverage-6G7T7TRQ.js → coverage-C75LPZYB.js} +3 -3
- package/dist/cli/chunks/cross-domain-router-35WVZFAZ.js +2 -0
- package/dist/cli/chunks/{cursor-installer-JFNYGSDD.js → cursor-installer-WXQFM4KJ.js} +2 -2
- package/dist/cli/chunks/{daemon-5A4GD6XA.js → daemon-BPVBZZQO.js} +3 -3
- package/dist/cli/chunks/{daemon-KTXGJJRI.js → daemon-JR2MSTSK.js} +4 -4
- package/dist/cli/chunks/{dag-attention-scheduler-4CUEQZD6.js → dag-attention-scheduler-I5H7DBNU.js} +2 -2
- package/dist/cli/chunks/{detect-I32JUSUE.js → detect-O5TMML24.js} +2 -2
- package/dist/cli/chunks/{dist-node-7ITNV6QS.js → dist-node-MDZ6UQ3V.js} +2 -2
- package/dist/cli/chunks/{domain-handler-LIFCXSZ4.js → domain-handler-BGBTZETG.js} +2 -2
- package/dist/cli/chunks/{domain-transfer-67UWLHSK.js → domain-transfer-C2D2IEYV.js} +2 -2
- package/dist/cli/chunks/dream-QTZDMP6D.js +2 -0
- package/dist/cli/chunks/{embed-and-insert-pattern-4WC5RUD6.js → embed-and-insert-pattern-UJREBJF5.js} +2 -2
- package/dist/cli/chunks/{eval-DLS2UAQ2.js → eval-BDD24HQC.js} +2 -2
- package/dist/cli/chunks/{experience-capture-middleware-VG5E6OJA.js → experience-capture-middleware-KLVXIIYH.js} +3 -3
- package/dist/cli/chunks/{fast-paths-262IVHDN.js → fast-paths-5HIKAQZ7.js} +2 -2
- package/dist/cli/chunks/{feature-flags-JJ3FHZGD.js → feature-flags-NM3S7OEW.js} +2 -2
- package/dist/cli/chunks/{feature-flags-L3K7DBN3.js → feature-flags-YE5SJPDS.js} +2 -2
- package/dist/cli/chunks/{file-discovery-Q3PBKVUW.js → file-discovery-PWRQZNJQ.js} +2 -2
- package/dist/cli/chunks/{fleet-LQ5S2YHG.js → fleet-UIPKNQX3.js} +3 -3
- package/dist/cli/chunks/{gnn-wrapper-I33Z537H.js → gnn-wrapper-GWGKZRTO.js} +2 -2
- package/dist/cli/chunks/{heartbeat-handler-RYIRAGZ7.js → heartbeat-handler-GQHJPNAY.js} +4 -4
- package/dist/cli/chunks/heartbeat-scheduler-N433NZCG.js +2 -0
- package/dist/cli/chunks/hnsw-adapter-MR6W2OA4.js +2 -0
- package/dist/cli/chunks/hnsw-index-XC6EMJA2.js +2 -0
- package/dist/cli/chunks/{hnsw-legacy-bridge-SSENBBPR.js → hnsw-legacy-bridge-NE5JIRG3.js} +2 -2
- package/dist/cli/chunks/{better-sqlite3-F262IAGH.js → hnswlib-node-PNPV64M3.js} +2 -2
- package/dist/cli/chunks/{hooks-LR5KQMN5.js → hooks-3NBBUOB6.js} +10 -10
- package/dist/cli/chunks/hybrid-router-SH4IEAJA.js +2 -0
- package/dist/cli/chunks/{hypergraph-engine-NDZA2DKP.js → hypergraph-engine-6NRFVDV7.js} +2 -2
- package/dist/cli/chunks/{hypergraph-handler-ADMWVHBT.js → hypergraph-handler-F3OOGTXF.js} +3 -3
- package/dist/cli/chunks/impact-analyzer-RUTVXE7P.js +2 -0
- package/dist/cli/chunks/init-handler-DOTXTVUI.js +73 -0
- package/dist/cli/chunks/init-wizard-56NY5BSP.js +2 -0
- package/dist/cli/chunks/kernel-7JAN7WCO.js +2 -0
- package/dist/cli/chunks/{kilocode-installer-DQVWZUKP.js → kilocode-installer-3AXYSZTO.js} +2 -2
- package/dist/cli/chunks/{kiro-installer-TINLYZ22.js → kiro-installer-WBJDXY7Q.js} +2 -2
- package/dist/cli/chunks/knowledge-graph-ST4LW3V4.js +2 -0
- package/dist/cli/chunks/{learning-KBT3S5WW.js → learning-BC5N4V3D.js} +3 -3
- package/dist/cli/chunks/{llm-router-2MX5LUAB.js → llm-router-T427WD6R.js} +4 -4
- package/dist/cli/chunks/llm-router-service-JNDF5MVJ.js +2 -0
- package/dist/cli/chunks/{load-IQWTGMLZ.js → load-M6SL2O3M.js} +2 -2
- package/dist/cli/chunks/load-test-I3P3DUS5.js +2 -0
- package/dist/cli/chunks/{mcp-GCTTJUBZ.js → mcp-F2V3KKG6.js} +2 -2
- package/dist/cli/chunks/{memory-XQVPI4UT.js → memory-FJAO3CSF.js} +5 -5
- package/dist/cli/chunks/memory-backend-27BBT57O.js +2 -0
- package/dist/cli/chunks/{memory-handlers-XD7MSFUN.js → memory-handlers-S3W6IQJL.js} +2 -2
- package/dist/cli/chunks/{multi-model-executor-JC63UCWG.js → multi-model-executor-FYOVZ4OH.js} +2 -2
- package/dist/cli/chunks/opencode-installer-APSBE4UR.js +15 -0
- package/dist/cli/chunks/{orchestrator-B75QWJUF.js → orchestrator-LN53EQ45.js} +16 -16
- package/dist/cli/chunks/pattern-null-store-SRBYJRNX.js +2 -0
- package/dist/cli/chunks/{pipeline-TCBQ2UTZ.js → pipeline-BYWXY2NO.js} +2 -2
- package/dist/cli/chunks/{platform-T43AYI3Z.js → platform-CZ774YPS.js} +2 -2
- package/dist/cli/chunks/{plugin-MSI3ZU3Z.js → plugin-72NXRX5Z.js} +2 -2
- package/dist/cli/chunks/{prime-radiant-advanced-wasm-V62CWI6M.js → prime-radiant-advanced-wasm-G4DE6YKJ.js} +2 -2
- package/dist/cli/chunks/protocol-executor-WJLJHWO2.js +2 -0
- package/dist/cli/chunks/{protocol-handler-OH2INET2.js → protocol-handler-UH6CV63V.js} +2 -2
- package/dist/cli/chunks/{prove-6PTMXMUL.js → prove-V7FAT5HF.js} +2 -2
- package/dist/cli/chunks/provider-manager-UKUHSHAL.js +2 -0
- package/dist/cli/chunks/qe-reasoning-bank-IMUECSFZ.js +2 -0
- package/dist/cli/chunks/{quality-PLNQN5GU.js → quality-N2K62FQM.js} +2 -2
- package/dist/cli/chunks/queen-coordinator-EC4SVNMB.js +2 -0
- package/dist/cli/chunks/{real-embeddings-OW4OKR77.js → real-embeddings-TKHUE2RL.js} +2 -2
- package/dist/cli/chunks/{roocode-installer-C32LCYAJ.js → roocode-installer-DFUA6FXW.js} +2 -2
- package/dist/cli/chunks/router-TVTOUQLL.js +2 -0
- package/dist/cli/chunks/routing-feedback-Y4WDXNXW.js +2 -0
- package/dist/cli/chunks/{routing-handler-CKFXXPMI.js → routing-handler-UUWD4IKG.js} +2 -2
- package/dist/cli/chunks/{ruvector-commands-GERRPTJL.js → ruvector-commands-B4WPTGCI.js} +2 -2
- package/dist/cli/chunks/{rvf-dual-writer-5FAB2QPA.js → rvf-dual-writer-MNRJGNIX.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-adapter-46COKWYB.js → rvf-migration-adapter-P2RDBFA4.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-coordinator-AJVRWSNC.js → rvf-migration-coordinator-DFESZQSS.js} +2 -2
- package/dist/cli/chunks/rvf-native-adapter-4YSC6QKO.js +2 -0
- package/dist/cli/chunks/safe-db-RGAY54O5.js +2 -0
- package/dist/cli/chunks/schedule-KJ4GWLPJ.js +2 -0
- package/dist/cli/chunks/scheduler-AONSLVA3.js +2 -0
- package/dist/cli/chunks/{security-Q622IVRB.js → security-MHLTNKFX.js} +3 -3
- package/dist/cli/chunks/{shared-rvf-adapter-EST24R3R.js → shared-rvf-adapter-LR7E2EQI.js} +2 -2
- package/dist/cli/chunks/{shared-rvf-dual-writer-CP6EXKBT.js → shared-rvf-dual-writer-RFFON2F3.js} +2 -2
- package/dist/cli/chunks/sqlite-persistence-7RZUEPM4.js +2 -0
- package/dist/cli/chunks/{status-handler-LLRQB4E2.js → status-handler-ROPTYGQC.js} +2 -2
- package/dist/cli/chunks/{structural-health-BUFWTNN2.js → structural-health-YGUFXGJ6.js} +2 -2
- package/dist/cli/chunks/{sync-JDG4SNT5.js → sync-6JTRTDL3.js} +2 -2
- package/dist/cli/chunks/{sync-RDL2RUOV.js → sync-NZZUMTKC.js} +2 -2
- package/dist/cli/chunks/{task-handler-KPP6ZXA6.js → task-handler-KYMV3AC6.js} +2 -2
- package/dist/cli/chunks/{task-handlers-MRK2BQWI.js → task-handlers-Z63YBQVU.js} +3 -3
- package/dist/cli/chunks/{test-7NYFTHRY.js → test-O6BQ7FGP.js} +4 -4
- package/dist/cli/chunks/{test-scheduling-LGPKDMWD.js → test-scheduling-T3IOXEFI.js} +3 -3
- package/dist/cli/chunks/{token-bootstrap-H5JHB7TD.js → token-bootstrap-CTI2ULJF.js} +2 -2
- package/dist/cli/chunks/{token-usage-TWPDS5U3.js → token-usage-TNQTNAVT.js} +2 -2
- package/dist/cli/chunks/{transformers-GRNPPUHM.js → transformers-CJQDNQER.js} +2 -2
- package/dist/cli/chunks/{tree-sitter-wasm-parser-DOH5F6TO.js → tree-sitter-wasm-parser-RBZWLEVQ.js} +2 -2
- package/dist/cli/chunks/{types-NYV3YKE3.js → types-OMFCO364.js} +2 -2
- package/dist/cli/chunks/unified-memory-G3BYQ3WU.js +2 -0
- package/dist/cli/chunks/unified-memory-hnsw-F7XUZMKW.js +2 -0
- package/dist/cli/chunks/unified-persistence-V35NXJSO.js +2 -0
- package/dist/cli/chunks/{upgrade-GDJMRYAT.js → upgrade-KRVOYWN3.js} +2 -2
- package/dist/cli/chunks/{validate-SIRFOPPM.js → validate-32FKHMKQ.js} +2 -2
- package/dist/cli/chunks/{validate-swarm-XGMJYR6X.js → validate-swarm-45RPBPPH.js} +2 -2
- package/dist/cli/chunks/{vibium-NP6ENRKV.js → vibium-LCTNDCKK.js} +2 -2
- package/dist/cli/chunks/visual-security-K47U7KUM.js +2 -0
- package/dist/cli/chunks/{web-tree-sitter-YDBWPYZD.js → web-tree-sitter-FX2EFCLH.js} +2 -2
- package/dist/cli/chunks/{windsurf-installer-MFI6EAPH.js → windsurf-installer-I3TSJCNL.js} +2 -2
- package/dist/cli/chunks/witness-chain-G6GJXZD3.js +2 -0
- package/dist/cli/chunks/{witness-chain-YHLBWQQ3.js → witness-chain-YG2UWTYZ.js} +2 -2
- package/dist/cli/chunks/{workflow-TA6RY7R5.js → workflow-AEJ37RNV.js} +4 -4
- package/dist/cli/chunks/workflow-orchestrator-SKF7GC5X.js +2 -0
- package/dist/cli/chunks/{wrappers-DS77IK4H.js → wrappers-GSU6VNU6.js} +2 -2
- package/dist/cli/handlers/init-handler.d.ts +2 -0
- package/dist/cli/handlers/init-handler.js +29 -1
- package/dist/coordination/result-saver.js +4 -0
- package/dist/domains/code-intelligence/coordinator-hypergraph.js +9 -4
- package/dist/domains/code-intelligence/coordinator.js +9 -4
- package/dist/init/opencode-installer.d.ts +39 -17
- package/dist/init/opencode-installer.js +166 -114
- package/dist/init/orchestrator.js +1 -0
- package/dist/init/phases/04-database.d.ts +5 -0
- package/dist/init/phases/04-database.js +7 -0
- package/dist/init/phases/05-learning.js +3 -0
- package/dist/init/phases/06-code-intelligence.js +6 -0
- package/dist/init/phases/09-assets.js +5 -1
- package/dist/init/phases/10-workers.js +4 -0
- package/dist/init/phases/12-verification.js +10 -5
- package/dist/init/phases/phase-interface.d.ts +6 -0
- package/dist/integrations/ruvector/rvf-native-adapter.js +8 -0
- package/dist/integrations/ruvector/shared-rvf-dual-writer.js +5 -0
- package/dist/kernel/kernel.js +4 -2
- package/dist/kernel/unified-memory.js +66 -48
- package/dist/learning/rvf-pattern-store.js +8 -0
- package/dist/mcp/bundle.js +327 -325
- package/dist/mcp/entry.js +42 -5
- package/dist/mcp/handlers/core-handlers.js +7 -2
- package/dist/mcp/protocol-server.js +10 -1
- package/dist/mcp/services/session-store.d.ts +1 -0
- package/dist/mcp/services/session-store.js +7 -0
- package/dist/mcp/tools/base.d.ts +6 -0
- package/dist/mcp/tools/base.js +16 -0
- package/package.json +6 -4
- package/dist/cli/chunks/adapter-TTIBYXH2.js +0 -2
- package/dist/cli/chunks/aqe-learning-engine-CTV5OLSN.js +0 -2
- package/dist/cli/chunks/base-ISNCJZ7A.js +0 -2
- package/dist/cli/chunks/browser-workflow-OD32QTTI.js +0 -2
- package/dist/cli/chunks/chunk-DF7V6X3N.js +0 -2
- package/dist/cli/chunks/chunk-I64BLAFS.js +0 -2
- package/dist/cli/chunks/chunk-LRRQEAP5.js +0 -2
- package/dist/cli/chunks/chunk-XCYPVJ34.js +0 -2
- package/dist/cli/chunks/chunk-XK7P7OXO.js +0 -2
- package/dist/cli/chunks/client-N4FQ6SMD.js +0 -2
- package/dist/cli/chunks/core-handlers-SFD5HCA3.js +0 -2
- package/dist/cli/chunks/cross-domain-router-7HGRUNLT.js +0 -2
- package/dist/cli/chunks/dream-HPGD5TLD.js +0 -2
- package/dist/cli/chunks/heartbeat-scheduler-O6TI5E4P.js +0 -2
- package/dist/cli/chunks/hnsw-adapter-TOVTN23J.js +0 -2
- package/dist/cli/chunks/hnsw-index-KCZ75V7K.js +0 -2
- package/dist/cli/chunks/hybrid-router-4JEPC4JZ.js +0 -2
- package/dist/cli/chunks/impact-analyzer-3MHIU3SE.js +0 -2
- package/dist/cli/chunks/init-handler-MGCYDX62.js +0 -70
- package/dist/cli/chunks/init-wizard-ERBO5JNA.js +0 -2
- package/dist/cli/chunks/kernel-XJPIIWET.js +0 -2
- package/dist/cli/chunks/knowledge-graph-NTJEG6ZE.js +0 -2
- package/dist/cli/chunks/llm-router-service-4T66BGB5.js +0 -2
- package/dist/cli/chunks/load-test-PM674TSK.js +0 -2
- package/dist/cli/chunks/memory-backend-53NQ5CG7.js +0 -2
- package/dist/cli/chunks/opencode-installer-6VJGEBIU.js +0 -3
- package/dist/cli/chunks/pattern-null-store-IF2RG2ON.js +0 -2
- package/dist/cli/chunks/protocol-executor-7AS75ZWT.js +0 -2
- package/dist/cli/chunks/provider-manager-AU2C4AET.js +0 -2
- package/dist/cli/chunks/qe-reasoning-bank-WATQRCFO.js +0 -2
- package/dist/cli/chunks/queen-coordinator-IOCC4VQH.js +0 -2
- package/dist/cli/chunks/router-SCJMX6WA.js +0 -2
- package/dist/cli/chunks/routing-feedback-RWC7F553.js +0 -2
- package/dist/cli/chunks/rvf-native-adapter-W2RT6PTO.js +0 -2
- package/dist/cli/chunks/safe-db-HO2LCAO3.js +0 -2
- package/dist/cli/chunks/schedule-XENCR4MR.js +0 -2
- package/dist/cli/chunks/scheduler-WKZ3O2SS.js +0 -2
- package/dist/cli/chunks/sqlite-persistence-IN6BOSCX.js +0 -2
- package/dist/cli/chunks/unified-memory-6MXOYRXZ.js +0 -2
- package/dist/cli/chunks/unified-memory-hnsw-HY3JJD5Z.js +0 -2
- package/dist/cli/chunks/unified-persistence-LKQNQYRY.js +0 -2
- package/dist/cli/chunks/visual-security-7TBWICHP.js +0 -2
- package/dist/cli/chunks/witness-chain-24SVOWQL.js +0 -2
- package/dist/cli/chunks/workflow-orchestrator-XBDXCTLY.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.10.
|
|
2
|
-
import{i as 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.10.8");process.exit(0)}
|
|
2
|
+
import{i as e}from"./chunk-NFZY6ZVY.js";function g(t,n,r,a){return{id:e(),type:t,timestamp:new Date,source:n,correlationId:a,payload:r}}var i={TestGenerated:"test-generation.TestGenerated",TestSuiteCreated:"test-generation.TestSuiteCreated",PatternLearned:"test-generation.PatternLearned",GenerationFailed:"test-generation.GenerationFailed"},o={TestRunStarted:"test-execution.TestRunStarted",TestRunCompleted:"test-execution.TestRunCompleted",FlakyTestDetected:"test-execution.FlakyTestDetected",RetryTriggered:"test-execution.RetryTriggered"},s={CoverageReportCreated:"coverage-analysis.CoverageReportCreated",CoverageGapDetected:"coverage-analysis.CoverageGapDetected",RiskZoneIdentified:"coverage-analysis.RiskZoneIdentified"},d={QualityGateEvaluated:"quality-assessment.QualityGateEvaluated",DeploymentApproved:"quality-assessment.DeploymentApproved",DeploymentBlocked:"quality-assessment.DeploymentBlocked"},l={DefectPredicted:"defect-intelligence.DefectPredicted",RootCauseIdentified:"defect-intelligence.RootCauseIdentified",RegressionRiskAnalyzed:"defect-intelligence.RegressionRiskAnalyzed"},c={KnowledgeGraphUpdated:"code-intelligence.KnowledgeGraphUpdated",ImpactAnalysisCompleted:"code-intelligence.ImpactAnalysisCompleted",SemanticSearchCompleted:"code-intelligence.SemanticSearchCompleted",C4DiagramsGenerated:"code-intelligence.C4DiagramsGenerated"},m={VulnerabilityDetected:"security-compliance.VulnerabilityDetected",ComplianceValidated:"security-compliance.ComplianceValidated",SecurityAuditCompleted:"security-compliance.SecurityAuditCompleted"},p={PatternConsolidated:"learning-optimization.PatternConsolidated",TransferCompleted:"learning-optimization.TransferCompleted",OptimizationApplied:"learning-optimization.OptimizationApplied",DreamCycleCompleted:"learning-optimization.dream.completed"},y={...i,...o,...s,...d,...l,...c,...m,...p};export{g as a,i as b,o as c,s as d,d as e,l as f,c as g,m as h,p as i};
|
|
@@ -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.10.
|
|
2
|
-
import{a as v}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.8");process.exit(0)}
|
|
2
|
+
import{a as v}from"./chunk-2B2RLPK3.js";import{c as l}from"./chunk-G73PIM7X.js";import{S as R,b as g}from"./chunk-HE3KLHNO.js";v();R();import{createHash as m,randomUUID as f}from"crypto";var a=l.create("witness-chain"),p=class{logLikelihoodRatio=0;upperBound;lowerBound;observations=0;constructor(t=.05,e=.05){this.upperBound=Math.log(1/t),this.lowerBound=Math.log(e)}addWeightedEvidence(t,e){return this.logLikelihoodRatio+=t?e:-e,this.observations++,this.logLikelihoodRatio>=this.upperBound?"PASS":this.logLikelihoodRatio<=this.lowerBound?"FAIL":"INCONCLUSIVE"}addEvidence(t){return this.addWeightedEvidence(t,.5)}getRatio(){return this.logLikelihoodRatio}getObservations(){return this.observations}getBounds(){return{upper:this.upperBound,lower:this.lowerBound}}reset(){this.logLikelihoodRatio=0,this.observations=0}},c="0".repeat(64),h=class{receipts=[];lastHash=c;sprtAccumulators=new Map;appendWitness(t){let e=f(),i=Date.now(),s=this.receipts.length,n=this.lastHash+JSON.stringify(t)+i,o=m("sha256").update(n).digest("hex"),u={id:e,timestamp:i,previousHash:this.lastHash,hash:o,decision:t,chainIndex:s};return this.receipts.push(u),this.lastHash=o,this.updateSPRT(t),a.debug("Witness appended",{chainIndex:s,type:t.type,decision:t.decision,hash:o.slice(0,16)+"..."}),u}verifyChain(){if(this.receipts.length===0)return{valid:!0,length:0,brokenAt:-1,message:"Chain is empty (valid)",lastHash:c};let t=c;for(let e=0;e<this.receipts.length;e++){let i=this.receipts[e];if(i.previousHash!==t)return{valid:!1,length:this.receipts.length,brokenAt:e,message:`Chain broken at index ${e}: previousHash mismatch`,lastHash:this.lastHash};let s=i.previousHash+JSON.stringify(i.decision)+i.timestamp,n=m("sha256").update(s).digest("hex");if(i.hash!==n)return{valid:!1,length:this.receipts.length,brokenAt:e,message:`Chain broken at index ${e}: hash mismatch (tamper detected)`,lastHash:this.lastHash};t=i.hash}return{valid:!0,length:this.receipts.length,brokenAt:-1,message:`Chain valid (${this.receipts.length} receipts)`,lastHash:this.lastHash}}getChain(t){return t!==void 0&&t>0?[...this.receipts.slice(-t)]:[...this.receipts]}getChainLength(){return this.receipts.length}getLastHash(){return this.lastHash}exportChain(){let t={version:"1.0.0",exportedAt:Date.now(),length:this.receipts.length,receipts:this.receipts};return JSON.stringify(t,null,2)}importChain(t){try{let e=JSON.parse(t);if(!e||e.version!=="1.0.0"||!Array.isArray(e.receipts))return a.warn("Import failed: invalid format"),!1;let i=this.receipts,s=this.lastHash;this.receipts=e.receipts,this.lastHash=e.receipts.length>0?e.receipts[e.receipts.length-1].hash:c;let n=this.verifyChain();return n.valid?(a.info("Chain imported successfully",{length:e.receipts.length}),!0):(this.receipts=i,this.lastHash=s,a.warn("Import failed: chain integrity check failed",{message:n.message}),!1)}catch(e){return a.warn("Import failed: parse error",{error:e instanceof Error?e.message:String(e)}),!1}}getSPRT(t,e,i){return this.sprtAccumulators.has(t)||this.sprtAccumulators.set(t,new p(e,i)),this.sprtAccumulators.get(t)}getReceipt(t){return this.receipts[t]}updateSPRT(t){let e=t.decision==="PASS"||t.decision==="PERMIT";this.getSPRT(t.type).addEvidence(e)}},d=class extends h{persistence;constructor(t){super(),this.persistence=t;let e=t.loadAllReceipts();if(e.length>0){let i={version:"1.0.0",exportedAt:Date.now(),length:e.length,receipts:e};this.importChain(JSON.stringify(i))?a.info("Witness chain restored from SQLite",{receipts:e.length}):a.warn("Failed to restore witness chain from SQLite \u2014 starting fresh")}}appendWitness(t){let e=super.appendWitness(t);try{this.persistence.insertReceipt(e)}catch(i){a.warn("Failed to persist witness receipt to SQLite",{chainIndex:e.chainIndex,error:i instanceof Error?i.message:String(i)})}return e}};function C(r){r.exec(`
|
|
3
3
|
CREATE TABLE IF NOT EXISTS witness_chain_receipts (
|
|
4
4
|
id TEXT PRIMARY KEY,
|
|
5
5
|
chain_index INTEGER NOT NULL,
|
|
@@ -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.10.
|
|
2
|
-
import{d as m}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.8");process.exit(0)}
|
|
2
|
+
import{d as m}from"./chunk-QHLENBGB.js";import{d as T}from"./chunk-UU422SST.js";T();function p(t,r,o){let e=0,n=t.length;for(;e<n;){let i=e+n>>>1;o(t[i],r)<=0?e=i+1:n=i}return e}function a(t,r,o){let e=p(t,r,o);return t.splice(e,0,r),e}function s(){return(t,r)=>t.createdAt.getTime()-r.createdAt.getTime()}m();export{a,s as b};
|
|
@@ -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.10.
|
|
2
|
-
import{a 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.10.8");process.exit(0)}
|
|
2
|
+
import{a as _}from"./chunk-TXLLF7XR.js";import{e as E}from"./chunk-HVFHPDXV.js";import{a as b}from"./chunk-2B2RLPK3.js";import{c as h}from"./chunk-G73PIM7X.js";import{b as p,d as S}from"./chunk-DDMKCHYT.js";import{S as A,j as g}from"./chunk-HE3KLHNO.js";S();b();A();var d=h.create("pattern-lifecycle"),D={promotionRewardThreshold:.7,promotionMinOccurrences:E,promotionMinSuccessRate:.7,deprecationFailureThreshold:3,staleDaysThreshold:30,confidenceDecayRate:.01,minActiveConfidence:.3,maxAgeForActivePatterns:90,promotionActivityWindowDays:30,asymmetricLearning:{}},y=5,L=.9,R=2;function v(u,e){return e<y||!Number.isFinite(u)?0:Math.min(Math.max(u,0),1)}var f=class{constructor(e,t={}){this.db=e;this.config={...D,...t},this.asymmetricEngine=new _(this.config.asymmetricLearning),this.ensureSchema()}db;config;asymmetricEngine;_witnessChain=null;set witnessChain(e){this._witnessChain=e}_compressionService=null;set compressionService(e){this._compressionService=e}ensureSchema(){try{this.db.prepare(`
|
|
3
3
|
SELECT deprecated_at FROM qe_patterns LIMIT 1
|
|
4
4
|
`).get()}catch(e){d.debug("Adding missing deprecated_at column",{error:e instanceof Error?e.message:String(e)}),this.db.exec(`
|
|
5
5
|
ALTER TABLE qe_patterns ADD COLUMN deprecated_at TEXT DEFAULT NULL
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.
|
|
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.10.8");process.exit(0)}
|
|
2
2
|
var h={0:"sqlite-only",1:"hybrid",2:"dual-write-sqlite-primary",3:"dual-write-rvf-primary",4:"rvf-primary"},g=class{config;db=null;rvfStore=null;totalWrites=0;totalReads=0;rvfWriteFailures=0;rvfReadFailures=0;fallbacksUsed=0;sqliteLatencies=[];rvfLatencies=[];sqliteWriteLatencies=[];rvfWriteLatencies=[];constructor(e){this.config={rvfPath:".agentic-qe/patterns.rvf",dimensions:384,enableFallback:!0,...e}}setSqliteDb(e){this.db=e}setRvfStore(e){this.rvfStore=e}get stage(){return this.config.stage}setStage(e){this.config={...this.config,stage:e}}write(e,t){this.totalWrites++;let s={sqliteSuccess:!1,rvfSuccess:!1,stage:this.config.stage,fallbackUsed:!1},n=this.config.stage<4,o=this.config.stage>=2;if(n&&this.db){let i=performance.now();try{let r=Buffer.from(t instanceof Float32Array?t.buffer:new Float32Array(t).buffer);this.db.prepare(`
|
|
3
3
|
INSERT INTO qe_pattern_embeddings (pattern_id, embedding, dimension, model, created_at)
|
|
4
4
|
VALUES (?, ?, ?, 'all-MiniLM-L6-v2', datetime('now'))
|
|
@@ -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.10.
|
|
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.10.8");process.exit(0)}
|
|
2
2
|
var i=class{s0;s1;s2;s3;constructor(s){this.s0=this.splitmix32(s),this.s1=this.splitmix32(this.s0),this.s2=this.splitmix32(this.s1),this.s3=this.splitmix32(this.s2)}splitmix32(s){return s=s+2654435769|0,s=Math.imul(s^s>>>16,2246822507),s=Math.imul(s^s>>>13,3266489909),(s^s>>>16)>>>0}next(){let s=this.s3,t=this.s0;return this.s3=this.s2,this.s2=this.s1,this.s1=t,t^=t<<11,t^=t>>>8,this.s0=t^s^s>>>19,this.s0>>>0}nextFloat(){return this.next()/4294967296}nextGaussian(){let s=this.nextFloat()||1e-10,t=this.nextFloat();return Math.sqrt(-2*Math.log(s))*Math.cos(2*Math.PI*t)}};export{i as a};
|
|
@@ -1,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.10.
|
|
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.10.8");process.exit(0)}
|
|
2
2
|
import r from"chalk";function s(e){switch(e){case"healthy":case"completed":return r.green(e);case"idle":return r.cyan(e);case"degraded":case"running":return r.yellow(e);case"unhealthy":case"failed":return r.red(e);default:return r.gray(e)}}function a(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:e<36e5?`${(e/6e4).toFixed(1)}m`:`${(e/36e5).toFixed(1)}h`}function l(e){let t=Math.floor(e/36e5),n=Math.floor(e%36e5/6e4),o=Math.floor(e%6e4/1e3);return`${t}h ${n}m ${o}s`}export{s as a,a as b,l as c};
|
|
@@ -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.10.
|
|
2
|
-
import{b as l,c}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.10.8");process.exit(0)}
|
|
2
|
+
import{b as l,c}from"./chunk-R2LWUBET.js";import{i}from"./chunk-NFZY6ZVY.js";c();var u=.15,d=.03,p=.25,s=class{constructor(t){this.db=t;l(t)}db;recordNull(t){this.db.prepare(`
|
|
3
3
|
INSERT INTO qe_pattern_nulls (id, pattern_id, context_fingerprint, failure_mode, trajectory_ref, evidence_class)
|
|
4
4
|
VALUES (?, ?, ?, ?, ?, ?)
|
|
5
5
|
ON CONFLICT(pattern_id, context_fingerprint) DO UPDATE SET
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.
|
|
2
|
-
import{a as C,f as x}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.10.8");process.exit(0)}
|
|
2
|
+
import{a as C,f as x}from"./chunk-YMJ5AVVU.js";import{a as h}from"./chunk-DNEYBK7X.js";var d={mechanical:["convert var to const","add types","remove console","convert to async","convert to esm","arrow function","rename variable","format code"],simple:["fix typo","update comment","fix simple bug","add documentation","format","rename","simple refactor","basic test"],moderate:["implement feature","implement","refactor","complex refactor","performance optimization","optimize","test generation","generate test","error handling","validation logic","api integration","code index","coverage analysis","quality assessment","defect prediction","predict defect","analyze coverage","analyze","assess","scan","detect"],complex:["multi-file refactor","orchestrate","coordinate","large codebase","migration","cross-domain","workflow","system design","analyze security","security scan","security analysis","vulnerability scan","chaos test","resilience test","contract validation"],critical:["architecture","security audit","critical bug","algorithm design","system-wide","vulnerability","cryptography","performance critical","hardcoded secret","cve","owasp","penetration test","exploit"]},f={architecture:/\b(architect|design|system design|overall structure|component design)\b/i,security:/\b(security|vulnerability|audit|xss|sql injection|csrf|encryption|auth|authentication|authorization)\b/i,multiStep:/\b(orchestrate|coordinate|workflow|pipeline|multi[- ]step)\b/i,crossDomain:/\b(cross[- ]domain|across (domains|modules)|integrate|coordination)\b/i},m=class{config;agentBoosterAdapter;constructor(e,t){this.config=e,this.agentBoosterAdapter=t}async collectSignals(e){let t=e.task.toLowerCase(),r=await this.checkAgentBoosterEligibility(e),o={simple:this.findKeywordMatches(t,d.simple),moderate:this.findKeywordMatches(t,d.moderate),complex:this.findKeywordMatches(t,d.complex),critical:this.findKeywordMatches(t,d.critical)},c=e.codeContext?e.codeContext.split(`
|
|
3
3
|
`).length:void 0,n=e.filePaths?e.filePaths.length:void 0,i=f.architecture.test(t),a=f.security.test(t),l=f.multiStep.test(t),g=f.crossDomain.test(t),b=this.detectCreativityRequirement(t),S=this.estimateLanguageComplexity(e.codeContext,e.filePaths),T=e.codeContext?this.estimateCyclomaticComplexity(e.codeContext):void 0;return{linesOfCode:c,fileCount:n,hasArchitectureScope:i,hasSecurityScope:a,requiresMultiStepReasoning:l,requiresCrossDomainCoordination:g,isMechanicalTransform:r.eligible,languageComplexity:S,cyclomaticComplexity:T,dependencyCount:this.countDependencies(e.codeContext),requiresCreativity:b,detectedTransformType:r.transformType,keywordMatches:o}}async checkAgentBoosterEligibility(e){if(!this.config.enableAgentBooster)return{eligible:!1,confidence:0,reason:"Agent Booster is disabled"};let t=e.task.toLowerCase(),r,o=0;for(let n of h){let i=this.getTransformKeywords(n),a=0;for(let l of i)t.includes(l.toLowerCase())&&(a=a===0?.5:a+.25);for(let l of d.mechanical)t.includes(l.toLowerCase())&&(a=Math.max(a,.6));a>o&&(o=a,r=n)}if(e.codeContext&&r&&this.agentBoosterAdapter)try{let i=(await this.agentBoosterAdapter.detectTransformOpportunities(e.codeContext)).opportunities.find(a=>a.type===r);if(i)return{eligible:i.confidence>=this.config.agentBoosterThreshold,transformType:r,confidence:i.confidence,reason:i.reason}}catch(n){console.debug("[SignalCollector] WASM analysis error:",n instanceof Error?n.message:n)}let c=o>=this.config.agentBoosterThreshold&&r!==void 0;return{eligible:c,transformType:r,confidence:Math.min(o,1),reason:c?`Detected ${r} transform pattern`:"No mechanical transform pattern detected"}}findKeywordMatches(e,t){let r=[];for(let o of t)e.includes(o.toLowerCase())&&r.push(o);return r}detectCreativityRequirement(e){return e.includes("design")||e.includes("creative")||e.includes("innovative")||e.includes("novel")}estimateLanguageComplexity(e,t){if(!e&&(!t||t.length===0))return;let r=[".ts",".tsx",".rs",".cpp",".c",".go"],o=[".js",".jsx",".py",".java"],c=[".json",".yaml",".md",".txt",".css",".html"];if(t){for(let n of t)if(r.some(i=>n.endsWith(i)))return"high";for(let n of t)if(o.some(i=>n.endsWith(i)))return"medium";for(let n of t)if(c.some(i=>n.endsWith(i)))return"low"}if(e){let n=/<[A-Z][^>]*>/.test(e),i=/\b(async|await)\b/.test(e),a=/\b(interface|type|class)\b/.test(e);return n&&a?"high":i||a?"medium":"low"}return"medium"}estimateCyclomaticComplexity(e){let t=[/\bif\b/g,/\bfor\b/g,/\bwhile\b/g,/\bcase\b/g,/\bcatch\b/g,/&&/g,/\|\|/g,/\?/g],r=1;for(let o of t){let c=e.match(o);c&&(r+=c.length)}return r}countDependencies(e){if(!e)return;let t=e.match(/\b(import|require|from)\b.*['"].*['"]/g);return t?t.length:0}getTransformKeywords(e){return{"var-to-const":["var to const","convert var","var declaration","var to let","convert var to const","change var to const"],"add-types":["add types","add type","typescript types","type annotations","type annotation","add type annotations"],"remove-console":["remove console","delete console","console.log","remove console.log","strip console"],"promise-to-async":["promise to async","async await",".then to async","convert to async","convert function to async"],"cjs-to-esm":["commonjs to esm","require to import","convert to esm","cjs to esm","module conversion"],"func-to-arrow":["arrow function","function to arrow","convert to arrow","convert function to arrow"]}[e]||[]}};function v(s,e){return new m(s,e)}var u=class{calculateCodeComplexity(e){let t=0;return t+=this.calculateLinesOfCodeContribution(e.linesOfCode),t+=this.calculateFileCountContribution(e.fileCount),t+=this.calculateCyclomaticContribution(e.cyclomaticComplexity),t+=this.calculateLanguageContribution(e.languageComplexity),Math.min(t,100)}calculateReasoningComplexity(e){let t=0;return t+=this.calculateKeywordScore(e.keywordMatches),e.requiresMultiStepReasoning&&(t+=20),e.requiresCreativity&&(t+=20),Math.min(t,100)}calculateScopeComplexity(e){let t=0;return e.hasArchitectureScope&&(t+=40),e.hasSecurityScope&&(t+=30),e.requiresCrossDomainCoordination&&(t+=20),t+=this.calculateDependencyContribution(e.dependencyCount),Math.min(t,100)}calculateOverallComplexity(e,t,r,o){if(o.isMechanicalTransform&&!o.hasSecurityScope&&!o.hasArchitectureScope&&!o.requiresMultiStepReasoning&&!o.requiresCrossDomainCoordination&&e===0&&t===0&&r===0)return 5;let c=e*.3+t*.4+r*.3,n=0;return o.hasSecurityScope&&(n=Math.max(n,50)),o.hasArchitectureScope&&(n=Math.max(n,55)),o.requiresCrossDomainCoordination&&(n=Math.max(n,35)),o.requiresMultiStepReasoning&&(n=Math.max(n,30)),o.keywordMatches.simple.length+o.keywordMatches.moderate.length+o.keywordMatches.complex.length+o.keywordMatches.critical.length===0&&!o.isMechanicalTransform&&c<15&&(n=Math.max(n,15)),Math.min(Math.max(Math.round(c),n),100)}calculateConfidence(e,t){let r=.5;return t.codeContext&&(r+=.2),t.filePaths&&t.filePaths.length>0&&(r+=.1),r+=this.calculateKeywordConfidenceBoost(e.keywordMatches),e.isMechanicalTransform&&(r+=.15),Math.min(r,1)}calculateLinesOfCodeContribution(e){return e===void 0||e<10?0:e<50?10:e<200?20:30}calculateFileCountContribution(e){return e===void 0||e===1?0:e<5?10:20}calculateCyclomaticContribution(e){return e===void 0||e<5?0:e<10?10:e<20?20:30}calculateLanguageContribution(e){return e==="low"?0:e==="medium"?10:e==="high"?20:0}calculateKeywordScore(e){let t=e.simple.length*5+e.moderate.length*15+e.complex.length*25+e.critical.length*35;return Math.min(t,60)}calculateDependencyContribution(e){return e===void 0||e<3?0:e<10?5:10}calculateKeywordConfidenceBoost(e){let t=e.simple.length+e.moderate.length+e.complex.length+e.critical.length;return t>=3?.1:t>=1?.05:0}};function M(){return new u}var p=class{getRecommendedTier(e){for(let t of[0,1,2,3,4]){let[r,o]=C[t].complexityRange;if(e>=r&&e<=o)return t}return 2}findAlternateTiers(e,t){let r=[];return t>0&&r.push(t-1),t<4&&r.push(t+1),t<3&&!r.includes(4)&&r.push(4),r}generateExplanation(e,t,r){let o=[];return o.push(`Complexity score: ${e}/100 (Tier ${t})`),r.isMechanicalTransform&&o.push(this.formatMechanicalTransformInfo(r.detectedTransformType)),o.push(...this.formatScopeExplanations(r)),o.push(...this.formatCodeMetricsExplanations(r)),o.join(". ")}formatMechanicalTransformInfo(e){return`Detected mechanical transform: ${e}`}formatScopeExplanations(e){let t=[];return e.hasArchitectureScope&&t.push("Architecture scope detected"),e.hasSecurityScope&&t.push("Security scope detected"),e.requiresMultiStepReasoning&&t.push("Multi-step reasoning required"),e.requiresCrossDomainCoordination&&t.push("Cross-domain coordination required"),t}formatCodeMetricsExplanations(e){let t=[];return e.linesOfCode!==void 0&&e.linesOfCode>100&&t.push(`Large code change: ${e.linesOfCode} lines`),e.fileCount!==void 0&&e.fileCount>3&&t.push(`Multi-file change: ${e.fileCount} files`),t}};function w(){return new p}var y=class{config;signalCollector;scoreCalculator;tierRecommender;constructor(e,t,r,o){this.config=e,this.signalCollector=t,this.scoreCalculator=r,this.tierRecommender=o}async analyze(e){try{let t=await this.signalCollector.collectSignals(e),r=this.scoreCalculator.calculateCodeComplexity(t),o=this.scoreCalculator.calculateReasoningComplexity(t),c=this.scoreCalculator.calculateScopeComplexity(t),n=this.scoreCalculator.calculateOverallComplexity(r,o,c,t),i=this.tierRecommender.getRecommendedTier(n),a=this.tierRecommender.findAlternateTiers(n,i),l=this.scoreCalculator.calculateConfidence(t,e),g=this.tierRecommender.generateExplanation(n,i,t);return{overall:n,codeComplexity:r,reasoningComplexity:o,scopeComplexity:c,confidence:l,signals:t,recommendedTier:i,alternateTiers:a,explanation:g}}catch(t){throw new x(`Failed to analyze task complexity: ${t instanceof Error?t.message:"Unknown error"}`,t instanceof Error?t:void 0)}}async checkAgentBoosterEligibility(e){return this.signalCollector.checkAgentBoosterEligibility(e)}getRecommendedTier(e){return this.tierRecommender.getRecommendedTier(e)}};function L(s,e){let t=new m(s,e),r=new u,o=new p;return new y(s,t,r,o)}function z(s,e,t,r){return new y(s,e,t,r)}export{m as a,v as b,u as c,M as d,p as e,w as f,y as g,L as h,z as i};
|
|
@@ -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.10.
|
|
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.10.8");process.exit(0)}
|
|
2
2
|
var n=["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","requirements-validation","code-intelligence","security-compliance","contract-testing","visual-accessibility","chaos-resilience","learning-optimization","enterprise-integration","coordination"];function t(e){return{success:!0,value:e}}function r(e){return{success:!1,error:e}}export{n as a,t as b,r as c};
|
|
@@ -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.10.
|
|
2
|
-
import{c as w,d as E,f as T}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.10.8");process.exit(0)}
|
|
2
|
+
import{c as w,d as E,f as T}from"./chunk-SDGRU6SG.js";var d=E((b,u)=>{"use strict";var _=typeof Buffer<"u",a=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,l=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function p(r,t,e){e==null&&t!==null&&typeof t=="object"&&(e=t,t=void 0),_&&Buffer.isBuffer(r)&&(r=r.toString()),r&&r.charCodeAt(0)===65279&&(r=r.slice(1));let o=JSON.parse(r,t);if(o===null||typeof o!="object")return o;let n=e&&e.protoAction||"error",c=e&&e.constructorAction||"error";if(n==="ignore"&&c==="ignore")return o;if(n!=="ignore"&&c!=="ignore"){if(a.test(r)===!1&&l.test(r)===!1)return o}else if(n!=="ignore"&&c==="ignore"){if(a.test(r)===!1)return o}else if(l.test(r)===!1)return o;return y(o,{protoAction:n,constructorAction:c,safe:e&&e.safe})}function y(r,{protoAction:t="error",constructorAction:e="error",safe:o}={}){let n=[r];for(;n.length;){let c=n;n=[];for(let s of c){if(t!=="ignore"&&Object.prototype.hasOwnProperty.call(s,"__proto__")){if(o===!0)return null;if(t==="error")throw new SyntaxError("Object contains forbidden prototype property");delete s.__proto__}if(e!=="ignore"&&Object.prototype.hasOwnProperty.call(s,"constructor")&&s.constructor!==null&&typeof s.constructor=="object"&&Object.prototype.hasOwnProperty.call(s.constructor,"prototype")){if(o===!0)return null;if(e==="error")throw new SyntaxError("Object contains forbidden prototype property");delete s.constructor}for(let h in s){let f=s[h];f&&typeof f=="object"&&n.push(f)}}}return r}function i(r,t,e){let{stackTraceLimit:o}=Error;Error.stackTraceLimit=0;try{return p(r,t,e)}finally{Error.stackTraceLimit=o}}function m(r,t){let{stackTraceLimit:e}=Error;Error.stackTraceLimit=0;try{return p(r,t,{safe:!0})}catch{return}finally{Error.stackTraceLimit=e}}u.exports=i;u.exports.default=i;u.exports.parse=i;u.exports.safeParse=m;u.exports.scan=y});function F(r){return g.default.parse(r,void 0,{protoAction:"remove",constructorAction:"remove"})}function j(r,t){try{return F(r)}catch(e){throw new Error(`Invalid JSON in --${t}: ${e instanceof Error?e.message:"Parse error"}`)}}var g,O=w(()=>{"use strict";g=T(d(),1)});export{d as a,F as b,j as c,O as d};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.
|
|
2
|
-
import{a as h}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.8");process.exit(0)}
|
|
2
|
+
import{a as h}from"./chunk-2B2RLPK3.js";import{c as m}from"./chunk-G73PIM7X.js";h();var g=m.create("regret-tracker"),l=50,R=.9,d=1.1;function f(o,t){let e=o.length;if(e<2)return 0;let n=0,r=0,i=0,a=0;for(let s=0;s<e;s++)n+=o[s],r+=t[s],i+=o[s]*t[s],a+=o[s]*o[s];let u=e*a-n*n;return Math.abs(u)<1e-10?0:(e*i-n*r)/u}var c=class{domains=new Map;alertCallbacks=[];alerts=[];maxAlerts;recentWindow;constructor(t){this.maxAlerts=t?.maxAlerts??100,this.recentWindow=t?.recentWindow??20}recordDecision(t,e,n){let r=this.getOrCreateDomainState(t),i=Math.max(0,n-e);if(r.cumulativeRegret+=i,r.decisionCount++,r.points.push({decisionCount:r.decisionCount,cumulativeRegret:r.cumulativeRegret,timestamp:Date.now()}),r.decisionCount>=l){let a=this.classifyGrowthRate(r.points);r.lastGrowthRate!=="insufficient_data"&&a!==r.lastGrowthRate&&this.emitAlert(t,r.lastGrowthRate,a),r.lastGrowthRate=a}}getCumulativeRegret(t){return this.domains.get(t)?.cumulativeRegret??0}getRegretCurve(t){let e=this.domains.get(t);return e?[...e.points]:[]}getRegretGrowthRate(t){let e=this.domains.get(t);return e?this.classifyGrowthRate(e.points):"insufficient_data"}detectStagnation(t){let e=this.getRegretGrowthRate(t);return e==="linear"||e==="superlinear"}getHealthSummary(){let t=[];for(let[e,n]of this.domains){let r=this.classifyGrowthRate(n.points),i=this.computeLogLogSlope(n.points),a=this.computeRecentAvgRegret(n);t.push({domain:e,totalDecisions:n.decisionCount,cumulativeRegret:n.cumulativeRegret,growthRate:r,stagnating:r==="linear"||r==="superlinear",slope:i,recentAvgRegret:a})}return t.sort((e,n)=>e.domain.localeCompare(n.domain)),t}onAlert(t){this.alertCallbacks.push(t)}getAlerts(){return[...this.alerts]}getTrackedDomains(){return[...this.domains.keys()].sort()}getTotalDecisions(){let t=0;for(let e of this.domains.values())t+=e.decisionCount;return t}reset(t){t?this.domains.delete(t):(this.domains.clear(),this.alerts=[])}getOrCreateDomainState(t){let e=this.domains.get(t);return e||(e={points:[],cumulativeRegret:0,decisionCount:0,lastGrowthRate:"insufficient_data"},this.domains.set(t,e)),e}classifyGrowthRate(t){if(t.length<l)return"insufficient_data";let e=this.computeLogLogSlope(t);return e===void 0?"insufficient_data":e<R?"sublinear":e<=d?"linear":"superlinear"}computeLogLogSlope(t){if(t.length<l)return;let e=t.filter(i=>i.cumulativeRegret>0&&i.decisionCount>0);if(e.length<2)return;let n=e.map(i=>Math.log(i.decisionCount)),r=e.map(i=>Math.log(i.cumulativeRegret));return f(n,r)}computeRecentAvgRegret(t){if(t.points.length<2)return 0;let e=Math.min(this.recentWindow,t.points.length),n=t.points.slice(-e),r=n[0],i=n[n.length-1],a=i.cumulativeRegret-r.cumulativeRegret,u=i.decisionCount-r.decisionCount;return u<=0?0:a/u}emitAlert(t,e,n){let r={domain:t,previousRate:e,newRate:n,timestamp:Date.now(),message:`Domain "${t}" regret growth changed from ${e} to ${n}`};this.alerts.push(r),this.alerts.length>this.maxAlerts&&this.alerts.shift(),g.info("Regret growth rate transition",{domain:t,previousRate:e,newRate:n});for(let i of this.alertCallbacks)try{i(r)}catch(a){g.error("Alert callback error",a instanceof Error?a:void 0)}}};function b(o){return new c(o)}export{b as a};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.
|
|
2
|
-
import{b as x,c as w,d as U,e as A}from"./chunk-QBVS4CXM.js";import{a as v,b as _}from"./chunk-X3HRJV65.js";import{a as b,b as B,c as k,d as O,e as F}from"./chunk-L2ZSYIDA.js";import{a as P}from"./chunk-GUDOOOO6.js";import{b as I,c as H}from"./chunk-XWPUCPYW.js";import{i as z}from"./chunk-6OLPKIYU.js";var h={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"}},V={security:h.heavyweight,"test-generation":h.standard,"code-analysis":h.standard,learning:h.standard,performance:{...h.lightweight,costSensitivity:"high"},coordination:h.lightweight,general:{...h.lightweight,requiresJsonMode:!1,latencySensitivity:"medium"},documentation:{...h.minimal,minContextSize:16e3},simple:h.minimal};var f=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}},D=[{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 $}from"crypto";var C=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()}-${$().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),s=o.outputTokens??i-n,a={timestamp:new Date,provider:e,model:t,latencyMs:r,inputTokens:n,outputTokens:s,totalTokens:i,success:o.success??!0,cost:o.cost,agentType:o.agentType};this.providerCalls.push(a),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),s=this.calculateAgentMetrics(r,i),a=r.map(m=>m.decisionTimeMs),c=r.length,l=this.countByMode(r),d=r.filter(m=>m.wasFallback).length,g=r.filter(m=>m.ruleId).length;return{byProvider:Object.fromEntries(n),byAgentType:s,totalDecisions:c,decisionsByMode:l,avgDecisionTimeMs:this.average(a),p95DecisionTimeMs:this.percentile(a,95),p99DecisionTimeMs:this.percentile(a,99),fallbackRate:c>0?d/c:0,ruleMatchRate:c>0?g/c:0,estimatedCostSavings:this.calculateCostSavings(r),ruleStats:{totalEvaluated:r.reduce((m,u)=>m+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(a=>a.provider===e),r=this.providerCalls.filter(a=>a.provider===e),i=r.map(a=>a.latencyMs),o=t.map(a=>a.decisionTimeMs),n=r.filter(a=>a.success),s=r.filter(a=>!a.success);return{provider:e,selectionCount:t.length,ruleMatchCount:t.filter(a=>a.ruleId).length,fallbackCount:t.filter(a=>a.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((a,c)=>a+(c.cost??0),0),totalTokens:r.reduce((a,c)=>a+c.totalTokens,0),totalInputTokens:r.reduce((a,c)=>a+c.inputTokens,0),totalOutputTokens:r.reduce((a,c)=>a+c.outputTokens,0),circuitState:"closed",latencyHistogram:i.slice(-100),decisionTimeHistogram:o.slice(-100),errorCount:s.length,lastError:s.length>0?s[s.length-1].timestamp:void 0,recentCalls:r.slice(-20)}}getMetricsByAgentType(e){let t=this.decisions.filter(c=>c.agentType===e),r=this.providerCalls.filter(c=>c.agentType===e),i=new Map,o=new Map;for(let c of t)i.set(c.provider,(i.get(c.provider)??0)+1),o.set(c.model,(o.get(c.model)??0)+1);let n=r.map(c=>c.latencyMs),s=t.filter(c=>c.wasFallback).length,a=t.filter(c=>c.success).length;return{agentType:e,totalDecisions:t.length,providerDistribution:i,modelDistribution:o,avgLatencyMs:this.average(n),totalCost:r.reduce((c,l)=>c+(l.cost??0),0),totalTokens:r.reduce((c,l)=>c+l.totalTokens,0),fallbackRate:t.length>0?s/t.length:0,successRate:t.length>0?a/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 v){let o=e.filter(l=>l.provider===i),n=t.filter(l=>l.provider===i);if(o.length===0&&n.length===0)continue;let s=n.map(l=>l.latencyMs),a=o.map(l=>l.decisionTimeMs),c=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(a),successRate:n.length>0?c.length/n.length:1,avgLatencyMs:this.average(s),p95LatencyMs:this.percentile(s,95),p99LatencyMs:this.percentile(s,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 E(p){return new C(p)}var R=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),s={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(s),this.trimRecords(),this.checkAlerts(),s}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 v){let n=r.filter(c=>c.provider===o);if(n.length===0)continue;let s=n.reduce((c,l)=>c+l.totalCost,0),a=n.reduce((c,l)=>c+l.inputTokens+l.outputTokens,0);i.set(o,{totalCost:s,totalTokens:a,totalRequests:n.length,avgCostPerRequest:s/n.length,avgCostPerToken:a>0?s/a:0})}return i}getCostByAgentType(e="all"){let t=this.getPeriodStart(e),r=this.filterByTime(t),i=new Set;r.forEach(s=>s.agentType&&i.add(s.agentType));let o=new Map;for(let s of i){let a=r.filter(d=>d.agentType===s),c=a.reduce((d,g)=>d+g.totalCost,0),l=a.reduce((d,g)=>d+g.inputTokens+g.outputTokens,0);o.set(s,{totalCost:c,totalTokens:l,totalRequests:a.length,avgCostPerRequest:a.length>0?c/a.length:0,avgCostPerToken:l>0?c/l:0})}let n=r.filter(s=>!s.agentType);if(n.length>0){let s=n.reduce((c,l)=>c+l.totalCost,0),a=n.reduce((c,l)=>c+l.inputTokens+l.outputTokens,0);o.set("unknown",{totalCost:s,totalTokens:a,totalRequests:n.length,avgCostPerRequest:s/n.length,avgCostPerToken:a>0?s/a: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 s=r.filter(l=>l.model===n),a=s.reduce((l,d)=>l+d.totalCost,0),c=s.reduce((l,d)=>l+d.inputTokens+d.outputTokens,0);o.set(n,{totalCost:a,totalTokens:c,totalRequests:s.length,avgCostPerRequest:s.length>0?a/s.length:0,avgCostPerToken:c>0?a/c: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 s=new Date(t.getTime()-n*i),a=new Date(s.getTime()-i),c=this.records.filter(l=>l.timestamp>=a&&l.timestamp<s);r.push({timestamp:s,cost:c.reduce((l,d)=>l+d.totalCost,0),tokens:c.reduce((l,d)=>l+d.inputTokens+d.outputTokens,0),requests:c.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,s]of t)P[n]&&s.totalCost>1&&(n.includes("opus")&&e.push({type:"model-switch",description:"Consider using Sonnet instead of Opus for non-critical tasks",estimatedSavings:s.totalCost*.5,currentCost:s.totalCost,suggestedModel:"claude-sonnet-4-6"}),n==="gpt-4o"&&e.push({type:"model-switch",description:"Consider using GPT-4o-mini for simpler tasks",estimatedSavings:s.totalCost*.7,currentCost:s.totalCost,suggestedModel:"gpt-4o-mini"}));let r=this.getCostByProvider("24h"),i=[...r.values()].reduce((n,s)=>n+s.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,s)=>n+s.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=P[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,s)=>n+s.inputTokens+s.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 q(p){return new R(p)}H();var T=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}}},M=class{config;providerManager;ruleEngine;decisionCache;metrics;routerMetrics;costMetrics;initialized=!1;constructor(e,t){this.providerManager=e,this.config={..._,...t};let r=this.config.rules.length>0?this.config.rules:D;this.ruleEngine=new f(r),this.decisionCache=new T(100,this.config.decisionCacheTtlMs),this.metrics=new S,this.routerMetrics=E(),this.costMetrics=q()}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 T(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=z(),r=await this.selectProvider(e),i=e.agentType??"";if(U(i)&&(w(r.model)||w(r.providerModelId))){let n=r.model,s=r.providerModelId;r.model=A(i,r.model,x),r.providerModelId=A(i,r.providerModelId,x),console.warn(`[aqe] ADR-093: ${i} pinned to ${r.model} (was ${n}/${s}); 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,s=o.action.provider,a=this.providerManager.getProvider(s);if(a){let c=this.createDecision(a,s,o.action.model,"rule-match",o);return c.metadata.rulesEvaluated=n,c}}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 s of t){let a=this.providerManager.getProvider(s);if(!a)continue;let{input:c,output:l}=a.getCostPerToken(),d=this.estimateCostValue(e,c,l);n.push({provider:s,model:a.getConfig().model,reason:`Estimated cost: $${d.toFixed(6)}`,estimatedCost:d,excluded:!1}),d<r&&(r=d,i=s,o=a)}if(o){let s=o.getConfig(),a=this.createDecision(o,i,s.model,"cost-optimization");return a.metadata.estimatedCost=this.createCostEstimate(e,o),a.metadata.alternativesConsidered=n,a}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,s=[];for(let a of t){let c=this.providerManager.getProvider(a);if(!c)continue;let d=r[a]?.avgLatencyMs??1/0;s.push({provider:a,model:c.getConfig().model,reason:`Avg latency: ${d}ms`,estimatedLatencyMs:d,excluded:!1}),d<i&&(i=d,o=a,n=c)}if(n){let a=n.getConfig(),c=this.createDecision(n,o,a.model,"performance-optimization");return c.metadata.estimatedLatencyMs=i,c.metadata.alternativesConsidered=s,c}return this.createFallbackDecision(e,"performance-optimized")}async executeWithFallback(e,t,r){let{fallbackChain:i,fallbackBehavior:o}=this.config,n,s=0,a=[{provider:t.providerType,model:t.providerModelId}],c=this.config.defaultProvider;c&&c!==t.providerType&&a.push({provider:c,model:this.config.defaultModel});for(let l of i.entries)if(l.enabled&&l.provider!==t.providerType)for(let d of l.models)a.push({provider:l.provider,model:d});for(let{provider:l,model:d}of a){if(s>=o.maxAttempts)break;let g=this.providerManager.getProvider(l);if(!g)continue;s++;let m=Date.now();try{let u=await g.generate(e.messages,{model:d,temperature:e.temperature,maxTokens:e.maxTokens,systemPrompt:e.systemPrompt,timeoutMs:e.timeoutMs,skipCache:e.skipCache,metadata:e.metadata}),y=Date.now()-m;return this.metrics.recordSuccess(l),this.routerMetrics.recordRoutingDecision(t,y,{agentType:e.agentType,success:!0,tokenUsage:u.usage,cost:u.cost}),this.routerMetrics.recordProviderCall(l,d,y,u.usage.totalTokens,{inputTokens:u.usage.promptTokens,outputTokens:u.usage.completionTokens,success:!0,cost:u.cost.totalCost,agentType:e.agentType}),this.costMetrics.recordCostFromInfo(l,d,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=I(u);let y=Date.now()-m;if(this.metrics.recordFailure(l),this.routerMetrics.recordProviderCall(l,d,y,0,{success:!1,agentType:e.agentType}),s<a.length){let L=a[s];L&&this.routerMetrics.recordFallback(l,L.provider,n.message,e.agentType)}!(B(u)&&!u.retryable)&&s<o.maxAttempts&&await this.delay(o.delayMs)}}throw b(`All providers failed after ${s} attempts: ${n?.message??"Unknown error"}`,"PROVIDER_UNAVAILABLE",{retryable:!1,cause:n})}createDecision(e,t,r,i,o){let{canonicalModel:n,providerModelId:s}=this.resolveModelIds(r,t);return{provider:e,providerType:t,model:n,providerModelId:s,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=k(o,i);return{canonicalModel:o,providerModelId:n}}catch{try{if(F(e)){let n=k(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 a of e.messages)o+=Math.ceil(a.content.length/4);let n=e.maxTokens??1e3,s=o*r+n*i;return{inputTokens:o,outputTokens:n,totalCostUsd:s,inputCostPer1M:r*1e6,outputCostPer1M:i*1e6}}delay(e){return new Promise(t=>setTimeout(t,e))}async ensureInitialized(){this.initialized||await this.initialize()}},S=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 M(p,e)}function Je(p){return new M(p,{mode:"rule-based",rules:D,defaultProvider:"claude",defaultModel:"claude-sonnet-4-6",enableMetrics:!0,cacheDecisions:!0})}export{M as a,je as b,Je as c};
|
|
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.10.8");process.exit(0)}
|
|
2
|
+
import{b as x,c as w,d as U,e as A}from"./chunk-ZSMHQENA.js";import{a as v,b as _}from"./chunk-LCDMB5SP.js";import{a as b,b as B,c as k,d as O,e as F}from"./chunk-7NKVEEXD.js";import{a as P}from"./chunk-QHGHWATK.js";import{b as I,c as H}from"./chunk-MTWBYHMS.js";import{i as z}from"./chunk-NFZY6ZVY.js";var h={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"}},V={security:h.heavyweight,"test-generation":h.standard,"code-analysis":h.standard,learning:h.standard,performance:{...h.lightweight,costSensitivity:"high"},coordination:h.lightweight,general:{...h.lightweight,requiresJsonMode:!1,latencySensitivity:"medium"},documentation:{...h.minimal,minContextSize:16e3},simple:h.minimal};var f=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}},D=[{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 $}from"crypto";var C=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()}-${$().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),s=o.outputTokens??i-n,a={timestamp:new Date,provider:e,model:t,latencyMs:r,inputTokens:n,outputTokens:s,totalTokens:i,success:o.success??!0,cost:o.cost,agentType:o.agentType};this.providerCalls.push(a),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),s=this.calculateAgentMetrics(r,i),a=r.map(m=>m.decisionTimeMs),c=r.length,l=this.countByMode(r),d=r.filter(m=>m.wasFallback).length,g=r.filter(m=>m.ruleId).length;return{byProvider:Object.fromEntries(n),byAgentType:s,totalDecisions:c,decisionsByMode:l,avgDecisionTimeMs:this.average(a),p95DecisionTimeMs:this.percentile(a,95),p99DecisionTimeMs:this.percentile(a,99),fallbackRate:c>0?d/c:0,ruleMatchRate:c>0?g/c:0,estimatedCostSavings:this.calculateCostSavings(r),ruleStats:{totalEvaluated:r.reduce((m,u)=>m+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(a=>a.provider===e),r=this.providerCalls.filter(a=>a.provider===e),i=r.map(a=>a.latencyMs),o=t.map(a=>a.decisionTimeMs),n=r.filter(a=>a.success),s=r.filter(a=>!a.success);return{provider:e,selectionCount:t.length,ruleMatchCount:t.filter(a=>a.ruleId).length,fallbackCount:t.filter(a=>a.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((a,c)=>a+(c.cost??0),0),totalTokens:r.reduce((a,c)=>a+c.totalTokens,0),totalInputTokens:r.reduce((a,c)=>a+c.inputTokens,0),totalOutputTokens:r.reduce((a,c)=>a+c.outputTokens,0),circuitState:"closed",latencyHistogram:i.slice(-100),decisionTimeHistogram:o.slice(-100),errorCount:s.length,lastError:s.length>0?s[s.length-1].timestamp:void 0,recentCalls:r.slice(-20)}}getMetricsByAgentType(e){let t=this.decisions.filter(c=>c.agentType===e),r=this.providerCalls.filter(c=>c.agentType===e),i=new Map,o=new Map;for(let c of t)i.set(c.provider,(i.get(c.provider)??0)+1),o.set(c.model,(o.get(c.model)??0)+1);let n=r.map(c=>c.latencyMs),s=t.filter(c=>c.wasFallback).length,a=t.filter(c=>c.success).length;return{agentType:e,totalDecisions:t.length,providerDistribution:i,modelDistribution:o,avgLatencyMs:this.average(n),totalCost:r.reduce((c,l)=>c+(l.cost??0),0),totalTokens:r.reduce((c,l)=>c+l.totalTokens,0),fallbackRate:t.length>0?s/t.length:0,successRate:t.length>0?a/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 v){let o=e.filter(l=>l.provider===i),n=t.filter(l=>l.provider===i);if(o.length===0&&n.length===0)continue;let s=n.map(l=>l.latencyMs),a=o.map(l=>l.decisionTimeMs),c=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(a),successRate:n.length>0?c.length/n.length:1,avgLatencyMs:this.average(s),p95LatencyMs:this.percentile(s,95),p99LatencyMs:this.percentile(s,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 E(p){return new C(p)}var R=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),s={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(s),this.trimRecords(),this.checkAlerts(),s}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 v){let n=r.filter(c=>c.provider===o);if(n.length===0)continue;let s=n.reduce((c,l)=>c+l.totalCost,0),a=n.reduce((c,l)=>c+l.inputTokens+l.outputTokens,0);i.set(o,{totalCost:s,totalTokens:a,totalRequests:n.length,avgCostPerRequest:s/n.length,avgCostPerToken:a>0?s/a:0})}return i}getCostByAgentType(e="all"){let t=this.getPeriodStart(e),r=this.filterByTime(t),i=new Set;r.forEach(s=>s.agentType&&i.add(s.agentType));let o=new Map;for(let s of i){let a=r.filter(d=>d.agentType===s),c=a.reduce((d,g)=>d+g.totalCost,0),l=a.reduce((d,g)=>d+g.inputTokens+g.outputTokens,0);o.set(s,{totalCost:c,totalTokens:l,totalRequests:a.length,avgCostPerRequest:a.length>0?c/a.length:0,avgCostPerToken:l>0?c/l:0})}let n=r.filter(s=>!s.agentType);if(n.length>0){let s=n.reduce((c,l)=>c+l.totalCost,0),a=n.reduce((c,l)=>c+l.inputTokens+l.outputTokens,0);o.set("unknown",{totalCost:s,totalTokens:a,totalRequests:n.length,avgCostPerRequest:s/n.length,avgCostPerToken:a>0?s/a: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 s=r.filter(l=>l.model===n),a=s.reduce((l,d)=>l+d.totalCost,0),c=s.reduce((l,d)=>l+d.inputTokens+d.outputTokens,0);o.set(n,{totalCost:a,totalTokens:c,totalRequests:s.length,avgCostPerRequest:s.length>0?a/s.length:0,avgCostPerToken:c>0?a/c: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 s=new Date(t.getTime()-n*i),a=new Date(s.getTime()-i),c=this.records.filter(l=>l.timestamp>=a&&l.timestamp<s);r.push({timestamp:s,cost:c.reduce((l,d)=>l+d.totalCost,0),tokens:c.reduce((l,d)=>l+d.inputTokens+d.outputTokens,0),requests:c.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,s]of t)P[n]&&s.totalCost>1&&(n.includes("opus")&&e.push({type:"model-switch",description:"Consider using Sonnet instead of Opus for non-critical tasks",estimatedSavings:s.totalCost*.5,currentCost:s.totalCost,suggestedModel:"claude-sonnet-4-6"}),n==="gpt-4o"&&e.push({type:"model-switch",description:"Consider using GPT-4o-mini for simpler tasks",estimatedSavings:s.totalCost*.7,currentCost:s.totalCost,suggestedModel:"gpt-4o-mini"}));let r=this.getCostByProvider("24h"),i=[...r.values()].reduce((n,s)=>n+s.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,s)=>n+s.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=P[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,s)=>n+s.inputTokens+s.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 q(p){return new R(p)}H();var T=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}}},M=class{config;providerManager;ruleEngine;decisionCache;metrics;routerMetrics;costMetrics;initialized=!1;constructor(e,t){this.providerManager=e,this.config={..._,...t};let r=this.config.rules.length>0?this.config.rules:D;this.ruleEngine=new f(r),this.decisionCache=new T(100,this.config.decisionCacheTtlMs),this.metrics=new S,this.routerMetrics=E(),this.costMetrics=q()}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 T(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=z(),r=await this.selectProvider(e),i=e.agentType??"";if(U(i)&&(w(r.model)||w(r.providerModelId))){let n=r.model,s=r.providerModelId;r.model=A(i,r.model,x),r.providerModelId=A(i,r.providerModelId,x),console.warn(`[aqe] ADR-093: ${i} pinned to ${r.model} (was ${n}/${s}); 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,s=o.action.provider,a=this.providerManager.getProvider(s);if(a){let c=this.createDecision(a,s,o.action.model,"rule-match",o);return c.metadata.rulesEvaluated=n,c}}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 s of t){let a=this.providerManager.getProvider(s);if(!a)continue;let{input:c,output:l}=a.getCostPerToken(),d=this.estimateCostValue(e,c,l);n.push({provider:s,model:a.getConfig().model,reason:`Estimated cost: $${d.toFixed(6)}`,estimatedCost:d,excluded:!1}),d<r&&(r=d,i=s,o=a)}if(o){let s=o.getConfig(),a=this.createDecision(o,i,s.model,"cost-optimization");return a.metadata.estimatedCost=this.createCostEstimate(e,o),a.metadata.alternativesConsidered=n,a}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,s=[];for(let a of t){let c=this.providerManager.getProvider(a);if(!c)continue;let d=r[a]?.avgLatencyMs??1/0;s.push({provider:a,model:c.getConfig().model,reason:`Avg latency: ${d}ms`,estimatedLatencyMs:d,excluded:!1}),d<i&&(i=d,o=a,n=c)}if(n){let a=n.getConfig(),c=this.createDecision(n,o,a.model,"performance-optimization");return c.metadata.estimatedLatencyMs=i,c.metadata.alternativesConsidered=s,c}return this.createFallbackDecision(e,"performance-optimized")}async executeWithFallback(e,t,r){let{fallbackChain:i,fallbackBehavior:o}=this.config,n,s=0,a=[{provider:t.providerType,model:t.providerModelId}],c=this.config.defaultProvider;c&&c!==t.providerType&&a.push({provider:c,model:this.config.defaultModel});for(let l of i.entries)if(l.enabled&&l.provider!==t.providerType)for(let d of l.models)a.push({provider:l.provider,model:d});for(let{provider:l,model:d}of a){if(s>=o.maxAttempts)break;let g=this.providerManager.getProvider(l);if(!g)continue;s++;let m=Date.now();try{let u=await g.generate(e.messages,{model:d,temperature:e.temperature,maxTokens:e.maxTokens,systemPrompt:e.systemPrompt,timeoutMs:e.timeoutMs,skipCache:e.skipCache,metadata:e.metadata}),y=Date.now()-m;return this.metrics.recordSuccess(l),this.routerMetrics.recordRoutingDecision(t,y,{agentType:e.agentType,success:!0,tokenUsage:u.usage,cost:u.cost}),this.routerMetrics.recordProviderCall(l,d,y,u.usage.totalTokens,{inputTokens:u.usage.promptTokens,outputTokens:u.usage.completionTokens,success:!0,cost:u.cost.totalCost,agentType:e.agentType}),this.costMetrics.recordCostFromInfo(l,d,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=I(u);let y=Date.now()-m;if(this.metrics.recordFailure(l),this.routerMetrics.recordProviderCall(l,d,y,0,{success:!1,agentType:e.agentType}),s<a.length){let L=a[s];L&&this.routerMetrics.recordFallback(l,L.provider,n.message,e.agentType)}!(B(u)&&!u.retryable)&&s<o.maxAttempts&&await this.delay(o.delayMs)}}throw b(`All providers failed after ${s} attempts: ${n?.message??"Unknown error"}`,"PROVIDER_UNAVAILABLE",{retryable:!1,cause:n})}createDecision(e,t,r,i,o){let{canonicalModel:n,providerModelId:s}=this.resolveModelIds(r,t);return{provider:e,providerType:t,model:n,providerModelId:s,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=k(o,i);return{canonicalModel:o,providerModelId:n}}catch{try{if(F(e)){let n=k(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 a of e.messages)o+=Math.ceil(a.content.length/4);let n=e.maxTokens??1e3,s=o*r+n*i;return{inputTokens:o,outputTokens:n,totalCostUsd:s,inputCostPer1M:r*1e6,outputCostPer1M:i*1e6}}delay(e){return new Promise(t=>setTimeout(t,e))}async ensureInitialized(){this.initialized||await this.initialize()}},S=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 M(p,e)}function Je(p){return new M(p,{mode:"rule-based",rules:D,defaultProvider:"claude",defaultModel:"claude-sonnet-4-6",enableMetrics:!0,cacheDecisions:!0})}export{M as a,je as b,Je as c};
|
|
@@ -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.10.
|
|
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.10.8");process.exit(0)}
|
|
2
2
|
var l=["var-to-const","add-types","remove-console","promise-to-async","cjs-to-esm","func-to-arrow"],p={"var-to-const":{type:"var-to-const",name:"Var to Const/Let",description:"Convert var declarations to const (if not reassigned) or let (if reassigned)",complexity:"simple",wasmAvailable:!0,typicalLatencyMs:1},"add-types":{type:"add-types",name:"Add TypeScript Types",description:"Add TypeScript type annotations to function parameters and return types",complexity:"moderate",wasmAvailable:!0,typicalLatencyMs:5},"remove-console":{type:"remove-console",name:"Remove Console Statements",description:"Remove all console.log, console.warn, console.error, etc. statements",complexity:"simple",wasmAvailable:!0,typicalLatencyMs:1},"promise-to-async":{type:"promise-to-async",name:"Promise to Async/Await",description:"Convert Promise .then()/.catch() chains to async/await syntax",complexity:"complex",wasmAvailable:!0,typicalLatencyMs:10},"cjs-to-esm":{type:"cjs-to-esm",name:"CommonJS to ES Modules",description:"Convert require() calls to import statements and module.exports to export",complexity:"moderate",wasmAvailable:!0,typicalLatencyMs:5},"func-to-arrow":{type:"func-to-arrow",name:"Function to Arrow",description:"Convert function declarations and expressions to arrow functions",complexity:"moderate",wasmAvailable:!0,typicalLatencyMs:3}},u={enabled:!0,fallbackToLLM:!0,confidenceThreshold:.7,transforms:[],maxFileSizeBytes:1024*1024,timeoutMs:5e3,cacheEnabled:!0,cacheTtlMs:300*1e3},t=class extends Error{constructor(e,s,o){super(e);this.code=s;this.cause=o;this.name="AgentBoosterError"}code;cause},a=class extends t{constructor(e,s,o){super(e,"TRANSFORM_ERROR",o);this.transformType=s;this.name="TransformError"}transformType},i=class extends t{constructor(r="WASM module is not available",e){super(r,"WASM_UNAVAILABLE",e),this.name="WasmUnavailableError"}},c=class extends t{constructor(e,s,o){super(e,"TRANSFORM_TIMEOUT");this.transformType=s;this.timeoutMs=o;this.name="TransformTimeoutError"}transformType;timeoutMs},m=class extends t{constructor(e,s,o){super(`File ${e} is too large (${s} bytes, max ${o} bytes)`,"FILE_TOO_LARGE");this.filePath=e;this.sizeBytes=s;this.maxSizeBytes=o;this.name="FileTooLargeError"}filePath;sizeBytes;maxSizeBytes};export{l as a,p as b,u as c,a as d,i as e,c as f,m as g};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.
|
|
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.10.8");process.exit(0)}
|
|
2
2
|
import a from"chalk";import{existsSync as m,statSync as S}from"fs";import{join as p,relative as P}from"path";var l=class{static prompt(t,e){return new Promise(r=>{t.question(e,s=>{r(s)})})}static printStepHeader(t,e,r){console.log(""),console.log(a.cyan(`Step ${t}: ${e}`)),r&&console.log(a.gray(r)),console.log("")}static printWizardHeader(t,e){console.log(""),console.log(a.blue("========================================")),console.log(a.blue.bold(` ${t}`)),console.log(a.blue("========================================")),e&&console.log(a.gray(e)),console.log(a.gray("Press Ctrl+C to cancel at any time")),console.log("")}static printSummaryHeader(){console.log(""),console.log(a.blue("========================================")),console.log(a.blue.bold(" Configuration Summary")),console.log(a.blue("========================================")),console.log("")}static printSummaryField(t,e,r){let s=r?.indent??" ",i=r?.maxItems??5,c=r?.formatValue??(o=>a.cyan(o));if(Array.isArray(e))e.length===0?console.log(a.white(`${s}${t}: ${a.gray("(none)")}`)):e.length<=i?console.log(a.white(`${s}${t}: ${c(e.join(", "))}`)):(console.log(a.white(`${s}${t}:`)),e.slice(0,i).forEach(o=>{console.log(a.gray(`${s} - ${o}`))}),console.log(a.gray(`${s} ... and ${e.length-i} more`)));else{let o=t.padEnd(16);console.log(a.white(`${s}${o}${c(e)}`))}}static printDerivedSettings(t,e=" "){console.log(""),console.log(a.gray(`${e}Derived settings:`));for(let[r,s]of Object.entries(t))console.log(a.gray(`${e} ${r}: ${s}`));console.log("")}};var h=class u{static getSourceDirectories(t){let e=[],r=["src","lib","app","packages","api"];for(let s of r){let i=p(t,s);m(i)&&S(i).isDirectory()&&e.push(s)}return e}static getCoverageTargets(t){let e=u.getSourceDirectories(t),r=["coverage","coverage/lcov.info","coverage/coverage-final.json",".nyc_output"];for(let s of r){let i=p(t,s);m(i)&&e.push(s)}return e}static getSecurityTargets(t){let e=u.getSourceDirectories(t),r=["package.json","package-lock.json","yarn.lock","pnpm-lock.yaml",".env",".env.example","docker-compose.yml","Dockerfile"];for(let s of r){let i=p(t,s);m(i)&&e.push(s)}return e}static getTestSourceFiles(t){let e=[],r=["src","lib","app","packages"];for(let s of r){let i=p(t,s);m(i)&&S(i).isDirectory()&&(e.push(`${s}/**/*.ts`),e.push(s))}return m(p(t,"src"))&&(e.push("src/services/**/*.ts"),e.push("src/utils/**/*.ts"),e.push("src/components/**/*.tsx")),e}static checkPatternsExist(t){return[p(t,".agentic-qe","patterns"),p(t,".agentic-qe","memory.db"),p(t,".aqe","patterns"),p(t,"data","patterns")].some(r=>m(r))}},f=class{static relativePath(t,e){return P(e,t)||"."}static yesNo(t){return t?"Yes":"No"}static enabledDisabled(t){return t?"Enabled":"Disabled"}static percentage(t){return`${t}%`}static truncatedList(t,e=5){return t.length===0?"(none)":t.length<=e?t.join(", "):`${t.slice(0,e).join(", ")}... and ${t.length-e} more`}};import n from"chalk";import{existsSync as w}from"fs";import{resolve as I}from"path";var d=class{constructor(t){this.defaultValue=t}defaultValue;description;getDefaultValue(){return this.defaultValue}success(t){return{value:t,continue:!0}}cancelled(){return{value:this.defaultValue,continue:!1}}error(t){return{value:this.defaultValue,continue:!1,error:t}}};var y=class extends d{id;stepNumber;title;description;options;validValues;constructor(t){super(t.defaultValue),this.id=t.id,this.stepNumber=t.stepNumber,this.title=t.title,this.description=t.description,this.options=t.options,this.validValues=t.validValues}async execute(t){if(t.nonInteractive)return this.success(this.defaultValue);l.printStepHeader(this.stepNumber,this.title,this.description),this.options.forEach(i=>{let c=[];i.isRecommended?c.push(n.green(" (recommended)")):(i.isDefault||i.value===this.defaultValue)&&c.push(n.green(" (default)")),console.log(n.white(` ${i.key}. ${i.label||i.value}${c.join("")}`)),i.description&&console.log(n.gray(` ${i.description}`))}),console.log("");let r=(await l.prompt(t.rl,`Select ${this.title.toLowerCase()} [${n.gray(String(this.defaultValue))}]: `)).trim();if(!r)return this.success(this.defaultValue);let s=parseInt(r,10);return s>=1&&s<=this.options.length?this.success(this.options[s-1].value):this.validValues.includes(r)?this.success(r):(console.log(n.yellow(` Invalid input, using default: ${this.defaultValue}`)),this.success(this.defaultValue))}},b=class extends d{id;stepNumber;title;description;options;validValues;instructions;allowEmpty;constructor(t){super(t.defaultValue),this.id=t.id,this.stepNumber=t.stepNumber,this.title=t.title,this.description=t.description,this.options=t.options,this.validValues=t.validValues,this.instructions=t.instructions,this.allowEmpty=t.allowEmpty??!1}async execute(t){if(t.nonInteractive)return this.success(this.defaultValue);l.printStepHeader(this.stepNumber,this.title,this.description),this.instructions&&(console.log(n.gray(this.instructions)),console.log("")),this.options.forEach(o=>{let N=o.isDefaultSelected||this.defaultValue.includes(o.value)?n.green(" *"):"";console.log(n.white(` ${o.key}. ${o.label||o.value}${N}`)),o.description&&console.log(n.gray(` ${o.description}`))}),console.log(""),console.log(n.gray(" * = included in default selection")),console.log("");let e=this.defaultValue.join(","),s=(await l.prompt(t.rl,`Select options [${n.gray(e)}]: `)).trim();if(!s)return this.success(this.defaultValue);let i=s.split(",").map(o=>o.trim().toLowerCase()).filter(o=>o.length>0),c=[];for(let o of i){let g=parseInt(o,10);g>=1&&g<=this.options.length?c.push(this.options[g-1].value):this.validValues.includes(o)&&c.push(o)}return c.length===0?this.allowEmpty?this.success([]):(console.log(n.yellow(` Invalid input, using default: ${e}`)),this.success(this.defaultValue)):this.success([...new Set(c)])}},v=class extends d{id;stepNumber;title;description;additionalInfo;constructor(t){super(t.defaultValue),this.id=t.id,this.stepNumber=t.stepNumber,this.title=t.title,this.description=t.description,this.additionalInfo=t.additionalInfo}async execute(t){if(t.nonInteractive)return this.success(this.defaultValue);l.printStepHeader(this.stepNumber,this.title,this.description),this.additionalInfo&&(console.log(n.gray(this.additionalInfo)),console.log(""));let e=this.defaultValue?"Y/n":"y/N",s=(await l.prompt(t.rl,`${this.title}? [${n.gray(e)}]: `)).trim().toLowerCase();return s===""?this.success(this.defaultValue):s==="n"||s==="no"?this.success(!1):s==="y"||s==="yes"?this.success(!0):this.success(this.defaultValue)}},x=class extends d{id;stepNumber;title;description;presets;min;max;constructor(t){super(t.defaultValue),this.id=t.id,this.stepNumber=t.stepNumber,this.title=t.title,this.description=t.description,this.presets=t.presets,this.min=t.min,this.max=t.max}async execute(t){if(t.nonInteractive)return this.success(this.defaultValue);l.printStepHeader(this.stepNumber,this.title,this.description),this.presets&&this.presets.length>0&&(this.presets.forEach(i=>{let c=i.value===this.defaultValue?n.green(" (default)"):"";console.log(n.gray(` ${i.key}. ${i.label}${c}`))}),this.min!==void 0&&this.max!==void 0&&console.log(n.gray(` Or enter a custom number (${this.min}-${this.max})`)),console.log(""));let r=(await l.prompt(t.rl,`${this.title} [${n.gray(String(this.defaultValue))}]: `)).trim();if(!r)return this.success(this.defaultValue);let s=parseInt(r,10);if(this.presets){let i=s;if(i>=1&&i<=this.presets.length)return this.success(this.presets[i-1].value)}return isNaN(s)?(console.log(n.yellow(` Invalid input, using default: ${this.defaultValue}`)),this.success(this.defaultValue)):this.min!==void 0&&s<this.min?(console.log(n.yellow(` Value too low, using minimum: ${this.min}`)),this.success(this.min)):this.max!==void 0&&s>this.max?(console.log(n.yellow(` Value too high, using maximum: ${this.max}`)),this.success(this.max)):this.success(s)}},C=class extends d{id;stepNumber;title;description;examples;suggestionsProvider;validatePath;constructor(t){super(t.defaultValue),this.id=t.id,this.stepNumber=t.stepNumber,this.title=t.title,this.description=t.description,this.examples=t.examples,this.suggestionsProvider=t.suggestionsProvider,this.validatePath=t.validatePath??!0}async execute(t){if(t.nonInteractive){let i=I(t.cwd,this.defaultValue);return this.success(w(i)?i:t.cwd)}if(l.printStepHeader(this.stepNumber,this.title,this.description),this.examples&&(console.log(n.gray(`Examples: ${this.examples}`)),console.log("")),this.suggestionsProvider){let i=this.suggestionsProvider(t.cwd);i.length>0&&(console.log(n.yellow("Detected directories:")),i.slice(0,5).forEach((c,o)=>{console.log(n.gray(` ${o+1}. ${c}`))}),console.log(""))}let r=(await l.prompt(t.rl,`${this.title} [${n.gray(this.defaultValue)}]: `)).trim()||this.defaultValue,s=I(t.cwd,r);return this.validatePath&&!w(s)?(console.log(n.yellow(` Warning: '${r}' does not exist, using current directory.`)),this.success(t.cwd)):this.success(s)}};var T=class extends d{id;stepNumber;title;description;constructor(t){super({}),this.id=t.id,this.stepNumber=t.stepNumber,this.title=t.title,this.description=t.description}async execute(t){if(t.nonInteractive)return this.success({});l.printStepHeader(this.stepNumber,this.title,this.description);let e=await l.prompt(t.rl,`Include patterns [${n.gray("e.g., src/**/*.ts")}]: `),r=await l.prompt(t.rl,`Exclude patterns [${n.gray("e.g., **/*.test.ts,dist/**")}]: `),s={};return e.trim()&&(s.include=e.split(",").map(i=>i.trim()).filter(i=>i.length>0)),r.trim()&&(s.exclude=r.split(",").map(i=>i.trim()).filter(i=>i.length>0)),this.success(s)}};import{createInterface as R}from"readline";import $ from"chalk";var V=class{options;cwd;constructor(t){this.options=t,this.cwd=process.cwd()}async run(){if(this.isNonInteractive())return this.getDefaults();let t=R({input:process.stdin,output:process.stdout});try{this.printHeader();let e={},r=this.getCommands();for(let c of r){let o={rl:t,cwd:this.cwd,results:e,nonInteractive:!1},g=await c.execute(o);if(!g.continue)return this.getCancelled();e[c.id]=g.value}let s=this.buildResult(e);return this.printSummary(s),await this.promptConfirmation(t)?s:this.getCancelled()}finally{t.close()}}printHeader(){l.printWizardHeader(this.getTitle(),this.getSubtitle())}async promptConfirmation(t){console.log("");let r=(await l.prompt(t,`${$.green(this.getConfirmationPrompt())} [${$.gray("Y/n")}]: `)).trim().toLowerCase();return r==="n"||r==="no"?(console.log($.yellow(`
|
|
3
3
|
Wizard cancelled.`)),!1):!0}};export{l as a,h as b,f as c,y as d,b as e,v as f,x as g,C as h,T as i,V as j};
|
|
@@ -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.10.
|
|
2
|
-
import{a as T}from"./chunk-DF7V6X3N.js";import{c as S}from"./chunk-222ZQTL5.js";import{b as C,d as P}from"./chunk-QBVFONWU.js";import{a as b,c as $}from"./chunk-XWPUCPYW.js";import{a as w,d as A}from"./chunk-DYNO72WD.js";$();A();import{randomUUID as M}from"crypto";var V={topology:"hierarchical",maxConcurrentSkills:10,maxConcurrentModels:3,timeout:3e5,continueOnFailure:!0,retry:{maxRetries:2,retryDelayMs:1e3}},R=class{config;learner;skillValidator=null;workers=new Map;taskQueue=[];isRunning=!1;constructor(e,t){this.config={...V,...e},this.learner=t}setSkillValidator(e){this.skillValidator=e}async validateSkillsParallel(e,t,i){let s=Date.now(),a=i?.trustTier??3,n=i?.validationLevel??"eval",c=this.determineTopology(e.length,t.length),r=this.createValidationTasks(e,t,a,n),o=await this.executeTasksParallel(r,c),l=new Map;for(let u of o){let p=l.get(u.skill)||[];p.push(u),l.set(u.skill,p)}return await this.recordOutcomesToLearner(o,a,n),l}async validateSkillCrossModel(e,t,i){return(await this.validateSkillsParallel([e],t,i)).get(e)||[]}getSummary(e){let t=[],i=new Map,s=new Map;for(let[c,r]of e){i.set(c,r);for(let o of r){t.push(o);let l=s.get(o.model)||[];l.push(o),s.set(o.model,l)}}let a=t.filter(c=>c.errors.length===0&&c.evalPassRate>=.9).length,n=t.reduce((c,r)=>c+r.durationMs,0);return{totalSkills:i.size,totalModels:s.size,successCount:a,failureCount:t.length-a,overallPassRate:t.length>0?a/t.length:0,totalDurationMs:n,avgDurationMs:t.length>0?n/t.length:0,topology:this.config.topology,bySkill:i,byModel:s,results:t}}determineTopology(e,t){if(this.config.topology){let i=e*t;return i>20&&this.config.topology==="mesh"&&console.warn(`[SwarmSkillValidator] Large workload (${i} tasks) may be more efficient with hierarchical topology`),this.config.topology}return e>5||e>t*2?"hierarchical":t>5&&e<=3?"mesh":"hierarchical"}createValidationTasks(e,t,i,s){let a=[];for(let n of e)for(let c of t)a.push({id:`${n}-${c}-${Date.now()}-${M().slice(0,8)}`,skill:n,model:c,trustTier:i,validationLevel:s,timeout:this.config.timeout,retryCount:0});return a}async executeTasksParallel(e,t){this.isRunning=!0,this.taskQueue=[...e];let i=[],s=t==="hierarchical"?this.config.maxConcurrentSkills:Math.min(this.config.maxConcurrentSkills*this.config.maxConcurrentModels,e.length),a=[];for(let n=0;n<Math.min(s,e.length);n++){let c=`worker-${n}`;this.workers.set(c,{id:c,task:null,status:"idle"}),a.push(this.runWorker(c,i))}return await Promise.all(a),this.isRunning=!1,this.workers.clear(),i}async runWorker(e,t){let i=this.workers.get(e);if(i){for(;this.taskQueue.length>0&&this.isRunning;){let s=this.taskQueue.shift();if(!s)break;i.task=s,i.status="running",i.startTime=Date.now();try{let a=await this.executeValidationTask(s);t.push(a),i.result=a,i.status="completed"}catch(a){let n=this.createErrorResult(s,a);this.config.retry&&s.retryCount<this.config.retry.maxRetries&&this.config.continueOnFailure?(s.retryCount++,this.taskQueue.push(s),await this.delay(this.config.retry.retryDelayMs)):(t.push(n),i.result=n,i.status="failed")}}i.task=null,i.status="idle"}}async executeValidationTask(e){let t=Date.now();if(!this.skillValidator)return this.createSimulatedResult(e,t);let i=new Promise((n,c)=>{setTimeout(()=>c(new Error(`Validation timeout after ${e.timeout}ms`)),e.timeout)}),s=await Promise.race([this.skillValidator(e.skill,e.model,{trustTier:e.trustTier,validationLevel:e.validationLevel,timeout:e.timeout}),i]),a=Date.now()-t;return this.outcomeToResult(s,e,a)}outcomeToResult(e,t,i){let s=e.testCaseResults.filter(c=>c.passed).length,a=e.testCaseResults.length,n=a>0?s/a:e.score;return{skill:t.skill,model:t.model,schemaValid:e.validationLevel!=="schema"||e.passed,validatorPassed:e.validationLevel!=="validator"||e.passed,evalPassRate:n,durationMs:i,errors:e.passed?[]:["Validation failed"],trustTier:t.trustTier,validationLevel:t.validationLevel,retryCount:t.retryCount,timestamp:new Date}}createSimulatedResult(e,t){let i=Date.now()-t+w()*100,s=.85+w()*.15;return{skill:e.skill,model:e.model,schemaValid:!0,validatorPassed:s>.8,evalPassRate:s,durationMs:i,errors:s>.8?[]:["Simulated validation failure"],trustTier:e.trustTier,validationLevel:e.validationLevel,retryCount:e.retryCount,timestamp:new Date}}createErrorResult(e,t){let i=b(t);return{skill:e.skill,model:e.model,schemaValid:!1,validatorPassed:!1,evalPassRate:0,durationMs:0,errors:[i],trustTier:e.trustTier,validationLevel:e.validationLevel,retryCount:e.retryCount,timestamp:new Date}}async recordOutcomesToLearner(e,t,i){for(let s of e){let a={skillName:s.skill,trustTier:s.trustTier||t,validationLevel:s.validationLevel||i,model:s.model,passed:s.errors.length===0&&s.evalPassRate>=.9,score:s.evalPassRate,testCaseResults:this.createTestCaseResults(s),timestamp:s.timestamp,runId:`swarm-${Date.now()}`,metadata:{duration:s.durationMs,retryCount:s.retryCount}};await this.learner.recordValidationOutcome(a)}}createTestCaseResults(e){return[{testId:`${e.skill}-${e.model}-aggregate`,passed:e.errors.length===0,expectedPatterns:["valid-output"],actualPatterns:e.errors.length===0?["valid-output"]:[],reasoningQuality:e.evalPassRate,executionTimeMs:e.durationMs,category:"swarm-validation",priority:"high",error:e.errors.length>0?e.errors.join("; "):void 0}]}delay(e){return new Promise(t=>setTimeout(t,e))}getConfig(){return{...this.config}}isValidationRunning(){return this.isRunning}getWorkerStatus(){return Array.from(this.workers.values())}cancel(){this.isRunning=!1,this.taskQueue=[]}};function D(y,e){return new R(y,e)}var F=["security-testing","accessibility-testing","api-testing","performance-testing","visual-regression-testing","mutation-testing","contract-testing","chaos-testing","compliance-testing","penetration-testing"],I=["claude-sonnet","claude-haiku","claude-opus"];P();import{readFileSync as E,writeFileSync as L,existsSync as N}from"fs";var O={varianceThreshold:.04,regressionThreshold:.1,minSamples:3,autoUpdateManifest:!1},k=class{constructor(e,t,i={}){this.learner=e;this.manifestPath=t;this.config={...O,...i}}learner;manifestPath;config;async aggregateResults(e){let t=`agg-${Date.now()}`,i=new Date,s=this.buildSkillResultsMap(e),a=this.calculateSummary(s,e),n=await this.detectCrossModelAnomalies(e),c=await this.detectRegressions(e,this.config.regressionThreshold),r=this.generateRecommendations(s,n,c),o={timestamp:i,runId:t,summary:a,skillResults:s,crossModelAnalysis:n,regressions:c,recommendations:r,metadata:{version:"1.0.0",environment:e[0]?.metadata?.environment,generatedBy:"ValidationResultAggregator",inputs:{runIds:e.map(l=>l.runId),models:[...new Set(e.map(l=>l.model))]}}};return this.config.autoUpdateManifest&&await this.updateManifest(o),o}buildSkillResultsMap(e){let t=new Map;for(let i of e)for(let s of i.outcomes){let a=s.skillName;t.has(a)||t.set(a,{skill:a,trustTier:s.trustTier,passRateByModel:new Map,avgPassRate:0,schemaValid:!0,validatorPassed:!0,evalPassed:!0,issues:[],executionTimeMs:0,testCount:0,passedTests:0,failedTests:0});let n=t.get(a),c=s.testCaseResults.filter(r=>r.passed).length/(s.testCaseResults.length||1);n.passRateByModel.set(i.model,c),n.testCount+=s.testCaseResults.length,n.passedTests+=s.testCaseResults.filter(r=>r.passed).length,n.failedTests+=s.testCaseResults.filter(r=>!r.passed).length,n.executionTimeMs+=s.metadata?.duration||0,s.validationLevel==="schema"&&!s.passed&&(n.schemaValid=!1),s.validationLevel==="validator"&&!s.passed&&(n.validatorPassed=!1),s.validationLevel==="eval"&&!s.passed&&(n.evalPassed=!1);for(let r of s.testCaseResults)!r.passed&&r.error&&n.issues.push({skill:a,model:i.model,severity:r.priority==="critical"?"critical":r.priority==="high"?"high":r.priority==="medium"?"medium":"low",type:this.categorizeIssueType(s.validationLevel,r.error),message:r.error,testId:r.testId})}for(let i of t.values()){let s=Array.from(i.passRateByModel.values());i.avgPassRate=s.length>0?s.reduce((a,n)=>a+n,0)/s.length:0}return t}categorizeIssueType(e,t){return t.toLowerCase().includes("timeout")?"timeout":e==="schema"?"schema_failure":e==="validator"?"validator_failure":e==="eval"?"eval_failure":"error"}calculateSummary(e,t){let i=Array.from(e.values()),s=i.filter(n=>n.avgPassRate>=.9).length,a=i.length>0?i.reduce((n,c)=>n+c.avgPassRate,0)/i.length:0;return{totalSkills:i.length,passedSkills:s,failedSkills:i.length-s,avgPassRate:a,totalDurationMs:t.reduce((n,c)=>n+c.durationMs,0),totalTests:i.reduce((n,c)=>n+c.testCount,0),passedTests:i.reduce((n,c)=>n+c.passedTests,0),failedTests:i.reduce((n,c)=>n+c.failedTests,0),modelsUsed:[...new Set(t.map(n=>n.model))]}}async detectCrossModelAnomalies(e){let t=new Map,i=new Map,s=new Map;for(let d of e){t.has(d.model)||(t.set(d.model,[]),i.set(d.model,{totalTests:0,passedTests:0,skillCount:0}));for(let g of d.outcomes){let h=g.testCaseResults.filter(m=>m.passed).length/(g.testCaseResults.length||1);t.get(d.model).push(h);let f=i.get(d.model);f.totalTests+=g.testCaseResults.length,f.passedTests+=g.testCaseResults.filter(m=>m.passed).length,f.skillCount++,s.has(g.skillName)||s.set(g.skillName,{passRates:[],models:[]}),s.get(g.skillName).passRates.push(h),s.get(g.skillName).models.push(d.model)}}let a=[];for(let d of t.values())a.push(...d);let n=a.length>0?a.reduce((d,g)=>d+g,0)/a.length:0,c=a.length>1?a.reduce((d,g)=>d+Math.pow(g-n,2),0)/a.length:0,r=Math.sqrt(c),o=[],l=new Map;for(let[d,g]of t.entries()){let h=g.reduce((v,x)=>v+x,0)/g.length,f=h-n,m=i.get(d);l.set(d,{avgPassRate:h,skillCount:m.skillCount,totalTests:m.totalTests}),Math.abs(f)>this.config.varianceThreshold*2&&o.push({model:d,type:f<0?"low_performance":"high_variance",description:`Model ${d} has ${(f*100).toFixed(1)}% difference from average`,passRate:h,avgPassRate:n,deviation:Math.abs(f)})}let u=[],p=[];for(let[d,g]of s.entries()){if(g.passRates.length<2)continue;let h=g.passRates.reduce((m,v)=>m+v,0)/g.passRates.length;g.passRates.reduce((m,v)=>m+Math.pow(v-h,2),0)/g.passRates.length<this.config.varianceThreshold?u.push(d):p.push(d)}return{variance:c,stdDeviation:r,anomalies:o,consistentSkills:u,inconsistentSkills:p,modelPerformance:l}}async detectRegressions(e,t){let i=[],s=new Set;for(let a of e)for(let n of a.outcomes){let c=`${n.skillName}-${a.model}`;if(s.has(c))continue;s.add(c);let r=await this.learner.getValidationTrends(n.skillName);if(!r)continue;let o=n.testCaseResults.filter(p=>p.passed).length/(n.testCaseResults.length||1),l=r.recentPassRate,u=l-o;u>=t&&i.push({skill:n.skillName,model:a.model,previousPassRate:l,currentPassRate:o,regressionAmount:u,trend:r.overall,possibleCauses:this.analyzePossibleCauses(n,u),severity:this.categorizeRegressionSeverity(u)})}return i.sort((a,n)=>{let c={critical:0,high:1,medium:2,low:3},r=c[a.severity]-c[n.severity];return r!==0?r:n.regressionAmount-a.regressionAmount})}analyzePossibleCauses(e,t){let i=[],s=e.testCaseResults.filter(c=>!c.passed);if(s.length>0){let c=[...new Set(s.map(r=>r.category).filter(Boolean))];c.length>0&&i.push(`Failures in categories: ${c.join(", ")}`)}let a=s.filter(c=>c.priority==="critical");a.length>0&&i.push(`${a.length} critical test(s) failing`);let n=e.testCaseResults.reduce((c,r)=>c+r.reasoningQuality,0)/(e.testCaseResults.length||1);return n<.7&&i.push(`Low reasoning quality score: ${(n*100).toFixed(1)}%`),t>.3&&i.push("Possible model behavior change or prompt drift"),i.length===0&&i.push("No specific cause identified - review test details"),i}categorizeRegressionSeverity(e){return e>=.5?"critical":e>=.3?"high":e>=.15?"medium":"low"}generateRecommendations(e,t,i){let s=[];if(t.inconsistentSkills.length>0&&s.push(`Review ${t.inconsistentSkills.length} skills with inconsistent cross-model behavior: `+t.inconsistentSkills.slice(0,3).join(", ")+(t.inconsistentSkills.length>3?` and ${t.inconsistentSkills.length-3} more`:"")),t.anomalies.some(r=>r.type==="low_performance")){let r=t.anomalies.filter(o=>o.type==="low_performance").map(o=>o.model);s.push(`Investigate low performance on model(s): ${r.join(", ")}`)}let a=i.filter(r=>r.severity==="critical");a.length>0&&s.push(`URGENT: ${a.length} critical regression(s) detected - immediate review required`);let n=Array.from(e.values()).filter(r=>r.avgPassRate<.9);if(n.length>0){let r=n.filter(l=>!l.schemaValid),o=n.filter(l=>!l.validatorPassed);r.length>0&&s.push(`Fix schema validation for: ${r.map(l=>l.skill).slice(0,3).join(", ")}`),o.length>0&&s.push(`Review validator scripts for: ${o.map(l=>l.skill).slice(0,3).join(", ")}`)}return Array.from(e.values()).reduce((r,o)=>r+o.avgPassRate,0)/e.size<.8&&s.push("Overall pass rate below 80% - consider reviewing skill definitions and test expectations"),s.length===0&&s.push("All validations passing - no immediate action required"),s}async updateManifest(e){if(!N(this.manifestPath))throw new Error(`Manifest file not found: ${this.manifestPath}`);let t=C(E(this.manifestPath,"utf-8"));for(let[s,a]of e.skillResults.entries())if(t.skills&&t.skills[s]){let n=t.skills[s];n.validation||(n.validation={}),n.validation.passRate=a.avgPassRate,n.validation.lastValidated=e.timestamp.toISOString(),n.validation.status=a.avgPassRate>=.9?"passing":"failing",n.validation.passRateByModel=Object.fromEntries(a.passRateByModel)}let i=Array.from(e.skillResults.values());t.validationStatus={passing:i.filter(s=>s.avgPassRate>=.9).length,failing:i.filter(s=>s.avgPassRate<.9).length,unknown:0,skipped:t.summary?.tier0||0},t.generatedAt=new Date().toISOString(),t.lastValidationRun={runId:e.runId,timestamp:e.timestamp.toISOString(),avgPassRate:e.summary.avgPassRate,modelsUsed:e.summary.modelsUsed},L(this.manifestPath,JSON.stringify(t,null,2))}generateMarkdownReport(e){let{summary:t,crossModelAnalysis:i,regressions:s,recommendations:a,skillResults:n}=e,c=(t.avgPassRate>=.9||t.avgPassRate>=.7,"`"),r=[];if(r.push(`# Validation Report
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.8");process.exit(0)}
|
|
2
|
+
import{a as T}from"./chunk-2B2RLPK3.js";import{c as S}from"./chunk-G73PIM7X.js";import{b as C,d as P}from"./chunk-DDMKCHYT.js";import{a as b,c as $}from"./chunk-MTWBYHMS.js";import{a as w,d as A}from"./chunk-QHLENBGB.js";$();A();import{randomUUID as M}from"crypto";var V={topology:"hierarchical",maxConcurrentSkills:10,maxConcurrentModels:3,timeout:3e5,continueOnFailure:!0,retry:{maxRetries:2,retryDelayMs:1e3}},R=class{config;learner;skillValidator=null;workers=new Map;taskQueue=[];isRunning=!1;constructor(e,t){this.config={...V,...e},this.learner=t}setSkillValidator(e){this.skillValidator=e}async validateSkillsParallel(e,t,i){let s=Date.now(),a=i?.trustTier??3,n=i?.validationLevel??"eval",c=this.determineTopology(e.length,t.length),r=this.createValidationTasks(e,t,a,n),o=await this.executeTasksParallel(r,c),l=new Map;for(let u of o){let p=l.get(u.skill)||[];p.push(u),l.set(u.skill,p)}return await this.recordOutcomesToLearner(o,a,n),l}async validateSkillCrossModel(e,t,i){return(await this.validateSkillsParallel([e],t,i)).get(e)||[]}getSummary(e){let t=[],i=new Map,s=new Map;for(let[c,r]of e){i.set(c,r);for(let o of r){t.push(o);let l=s.get(o.model)||[];l.push(o),s.set(o.model,l)}}let a=t.filter(c=>c.errors.length===0&&c.evalPassRate>=.9).length,n=t.reduce((c,r)=>c+r.durationMs,0);return{totalSkills:i.size,totalModels:s.size,successCount:a,failureCount:t.length-a,overallPassRate:t.length>0?a/t.length:0,totalDurationMs:n,avgDurationMs:t.length>0?n/t.length:0,topology:this.config.topology,bySkill:i,byModel:s,results:t}}determineTopology(e,t){if(this.config.topology){let i=e*t;return i>20&&this.config.topology==="mesh"&&console.warn(`[SwarmSkillValidator] Large workload (${i} tasks) may be more efficient with hierarchical topology`),this.config.topology}return e>5||e>t*2?"hierarchical":t>5&&e<=3?"mesh":"hierarchical"}createValidationTasks(e,t,i,s){let a=[];for(let n of e)for(let c of t)a.push({id:`${n}-${c}-${Date.now()}-${M().slice(0,8)}`,skill:n,model:c,trustTier:i,validationLevel:s,timeout:this.config.timeout,retryCount:0});return a}async executeTasksParallel(e,t){this.isRunning=!0,this.taskQueue=[...e];let i=[],s=t==="hierarchical"?this.config.maxConcurrentSkills:Math.min(this.config.maxConcurrentSkills*this.config.maxConcurrentModels,e.length),a=[];for(let n=0;n<Math.min(s,e.length);n++){let c=`worker-${n}`;this.workers.set(c,{id:c,task:null,status:"idle"}),a.push(this.runWorker(c,i))}return await Promise.all(a),this.isRunning=!1,this.workers.clear(),i}async runWorker(e,t){let i=this.workers.get(e);if(i){for(;this.taskQueue.length>0&&this.isRunning;){let s=this.taskQueue.shift();if(!s)break;i.task=s,i.status="running",i.startTime=Date.now();try{let a=await this.executeValidationTask(s);t.push(a),i.result=a,i.status="completed"}catch(a){let n=this.createErrorResult(s,a);this.config.retry&&s.retryCount<this.config.retry.maxRetries&&this.config.continueOnFailure?(s.retryCount++,this.taskQueue.push(s),await this.delay(this.config.retry.retryDelayMs)):(t.push(n),i.result=n,i.status="failed")}}i.task=null,i.status="idle"}}async executeValidationTask(e){let t=Date.now();if(!this.skillValidator)return this.createSimulatedResult(e,t);let i=new Promise((n,c)=>{setTimeout(()=>c(new Error(`Validation timeout after ${e.timeout}ms`)),e.timeout)}),s=await Promise.race([this.skillValidator(e.skill,e.model,{trustTier:e.trustTier,validationLevel:e.validationLevel,timeout:e.timeout}),i]),a=Date.now()-t;return this.outcomeToResult(s,e,a)}outcomeToResult(e,t,i){let s=e.testCaseResults.filter(c=>c.passed).length,a=e.testCaseResults.length,n=a>0?s/a:e.score;return{skill:t.skill,model:t.model,schemaValid:e.validationLevel!=="schema"||e.passed,validatorPassed:e.validationLevel!=="validator"||e.passed,evalPassRate:n,durationMs:i,errors:e.passed?[]:["Validation failed"],trustTier:t.trustTier,validationLevel:t.validationLevel,retryCount:t.retryCount,timestamp:new Date}}createSimulatedResult(e,t){let i=Date.now()-t+w()*100,s=.85+w()*.15;return{skill:e.skill,model:e.model,schemaValid:!0,validatorPassed:s>.8,evalPassRate:s,durationMs:i,errors:s>.8?[]:["Simulated validation failure"],trustTier:e.trustTier,validationLevel:e.validationLevel,retryCount:e.retryCount,timestamp:new Date}}createErrorResult(e,t){let i=b(t);return{skill:e.skill,model:e.model,schemaValid:!1,validatorPassed:!1,evalPassRate:0,durationMs:0,errors:[i],trustTier:e.trustTier,validationLevel:e.validationLevel,retryCount:e.retryCount,timestamp:new Date}}async recordOutcomesToLearner(e,t,i){for(let s of e){let a={skillName:s.skill,trustTier:s.trustTier||t,validationLevel:s.validationLevel||i,model:s.model,passed:s.errors.length===0&&s.evalPassRate>=.9,score:s.evalPassRate,testCaseResults:this.createTestCaseResults(s),timestamp:s.timestamp,runId:`swarm-${Date.now()}`,metadata:{duration:s.durationMs,retryCount:s.retryCount}};await this.learner.recordValidationOutcome(a)}}createTestCaseResults(e){return[{testId:`${e.skill}-${e.model}-aggregate`,passed:e.errors.length===0,expectedPatterns:["valid-output"],actualPatterns:e.errors.length===0?["valid-output"]:[],reasoningQuality:e.evalPassRate,executionTimeMs:e.durationMs,category:"swarm-validation",priority:"high",error:e.errors.length>0?e.errors.join("; "):void 0}]}delay(e){return new Promise(t=>setTimeout(t,e))}getConfig(){return{...this.config}}isValidationRunning(){return this.isRunning}getWorkerStatus(){return Array.from(this.workers.values())}cancel(){this.isRunning=!1,this.taskQueue=[]}};function D(y,e){return new R(y,e)}var F=["security-testing","accessibility-testing","api-testing","performance-testing","visual-regression-testing","mutation-testing","contract-testing","chaos-testing","compliance-testing","penetration-testing"],I=["claude-sonnet","claude-haiku","claude-opus"];P();import{readFileSync as E,writeFileSync as L,existsSync as N}from"fs";var O={varianceThreshold:.04,regressionThreshold:.1,minSamples:3,autoUpdateManifest:!1},k=class{constructor(e,t,i={}){this.learner=e;this.manifestPath=t;this.config={...O,...i}}learner;manifestPath;config;async aggregateResults(e){let t=`agg-${Date.now()}`,i=new Date,s=this.buildSkillResultsMap(e),a=this.calculateSummary(s,e),n=await this.detectCrossModelAnomalies(e),c=await this.detectRegressions(e,this.config.regressionThreshold),r=this.generateRecommendations(s,n,c),o={timestamp:i,runId:t,summary:a,skillResults:s,crossModelAnalysis:n,regressions:c,recommendations:r,metadata:{version:"1.0.0",environment:e[0]?.metadata?.environment,generatedBy:"ValidationResultAggregator",inputs:{runIds:e.map(l=>l.runId),models:[...new Set(e.map(l=>l.model))]}}};return this.config.autoUpdateManifest&&await this.updateManifest(o),o}buildSkillResultsMap(e){let t=new Map;for(let i of e)for(let s of i.outcomes){let a=s.skillName;t.has(a)||t.set(a,{skill:a,trustTier:s.trustTier,passRateByModel:new Map,avgPassRate:0,schemaValid:!0,validatorPassed:!0,evalPassed:!0,issues:[],executionTimeMs:0,testCount:0,passedTests:0,failedTests:0});let n=t.get(a),c=s.testCaseResults.filter(r=>r.passed).length/(s.testCaseResults.length||1);n.passRateByModel.set(i.model,c),n.testCount+=s.testCaseResults.length,n.passedTests+=s.testCaseResults.filter(r=>r.passed).length,n.failedTests+=s.testCaseResults.filter(r=>!r.passed).length,n.executionTimeMs+=s.metadata?.duration||0,s.validationLevel==="schema"&&!s.passed&&(n.schemaValid=!1),s.validationLevel==="validator"&&!s.passed&&(n.validatorPassed=!1),s.validationLevel==="eval"&&!s.passed&&(n.evalPassed=!1);for(let r of s.testCaseResults)!r.passed&&r.error&&n.issues.push({skill:a,model:i.model,severity:r.priority==="critical"?"critical":r.priority==="high"?"high":r.priority==="medium"?"medium":"low",type:this.categorizeIssueType(s.validationLevel,r.error),message:r.error,testId:r.testId})}for(let i of t.values()){let s=Array.from(i.passRateByModel.values());i.avgPassRate=s.length>0?s.reduce((a,n)=>a+n,0)/s.length:0}return t}categorizeIssueType(e,t){return t.toLowerCase().includes("timeout")?"timeout":e==="schema"?"schema_failure":e==="validator"?"validator_failure":e==="eval"?"eval_failure":"error"}calculateSummary(e,t){let i=Array.from(e.values()),s=i.filter(n=>n.avgPassRate>=.9).length,a=i.length>0?i.reduce((n,c)=>n+c.avgPassRate,0)/i.length:0;return{totalSkills:i.length,passedSkills:s,failedSkills:i.length-s,avgPassRate:a,totalDurationMs:t.reduce((n,c)=>n+c.durationMs,0),totalTests:i.reduce((n,c)=>n+c.testCount,0),passedTests:i.reduce((n,c)=>n+c.passedTests,0),failedTests:i.reduce((n,c)=>n+c.failedTests,0),modelsUsed:[...new Set(t.map(n=>n.model))]}}async detectCrossModelAnomalies(e){let t=new Map,i=new Map,s=new Map;for(let d of e){t.has(d.model)||(t.set(d.model,[]),i.set(d.model,{totalTests:0,passedTests:0,skillCount:0}));for(let g of d.outcomes){let h=g.testCaseResults.filter(m=>m.passed).length/(g.testCaseResults.length||1);t.get(d.model).push(h);let f=i.get(d.model);f.totalTests+=g.testCaseResults.length,f.passedTests+=g.testCaseResults.filter(m=>m.passed).length,f.skillCount++,s.has(g.skillName)||s.set(g.skillName,{passRates:[],models:[]}),s.get(g.skillName).passRates.push(h),s.get(g.skillName).models.push(d.model)}}let a=[];for(let d of t.values())a.push(...d);let n=a.length>0?a.reduce((d,g)=>d+g,0)/a.length:0,c=a.length>1?a.reduce((d,g)=>d+Math.pow(g-n,2),0)/a.length:0,r=Math.sqrt(c),o=[],l=new Map;for(let[d,g]of t.entries()){let h=g.reduce((v,x)=>v+x,0)/g.length,f=h-n,m=i.get(d);l.set(d,{avgPassRate:h,skillCount:m.skillCount,totalTests:m.totalTests}),Math.abs(f)>this.config.varianceThreshold*2&&o.push({model:d,type:f<0?"low_performance":"high_variance",description:`Model ${d} has ${(f*100).toFixed(1)}% difference from average`,passRate:h,avgPassRate:n,deviation:Math.abs(f)})}let u=[],p=[];for(let[d,g]of s.entries()){if(g.passRates.length<2)continue;let h=g.passRates.reduce((m,v)=>m+v,0)/g.passRates.length;g.passRates.reduce((m,v)=>m+Math.pow(v-h,2),0)/g.passRates.length<this.config.varianceThreshold?u.push(d):p.push(d)}return{variance:c,stdDeviation:r,anomalies:o,consistentSkills:u,inconsistentSkills:p,modelPerformance:l}}async detectRegressions(e,t){let i=[],s=new Set;for(let a of e)for(let n of a.outcomes){let c=`${n.skillName}-${a.model}`;if(s.has(c))continue;s.add(c);let r=await this.learner.getValidationTrends(n.skillName);if(!r)continue;let o=n.testCaseResults.filter(p=>p.passed).length/(n.testCaseResults.length||1),l=r.recentPassRate,u=l-o;u>=t&&i.push({skill:n.skillName,model:a.model,previousPassRate:l,currentPassRate:o,regressionAmount:u,trend:r.overall,possibleCauses:this.analyzePossibleCauses(n,u),severity:this.categorizeRegressionSeverity(u)})}return i.sort((a,n)=>{let c={critical:0,high:1,medium:2,low:3},r=c[a.severity]-c[n.severity];return r!==0?r:n.regressionAmount-a.regressionAmount})}analyzePossibleCauses(e,t){let i=[],s=e.testCaseResults.filter(c=>!c.passed);if(s.length>0){let c=[...new Set(s.map(r=>r.category).filter(Boolean))];c.length>0&&i.push(`Failures in categories: ${c.join(", ")}`)}let a=s.filter(c=>c.priority==="critical");a.length>0&&i.push(`${a.length} critical test(s) failing`);let n=e.testCaseResults.reduce((c,r)=>c+r.reasoningQuality,0)/(e.testCaseResults.length||1);return n<.7&&i.push(`Low reasoning quality score: ${(n*100).toFixed(1)}%`),t>.3&&i.push("Possible model behavior change or prompt drift"),i.length===0&&i.push("No specific cause identified - review test details"),i}categorizeRegressionSeverity(e){return e>=.5?"critical":e>=.3?"high":e>=.15?"medium":"low"}generateRecommendations(e,t,i){let s=[];if(t.inconsistentSkills.length>0&&s.push(`Review ${t.inconsistentSkills.length} skills with inconsistent cross-model behavior: `+t.inconsistentSkills.slice(0,3).join(", ")+(t.inconsistentSkills.length>3?` and ${t.inconsistentSkills.length-3} more`:"")),t.anomalies.some(r=>r.type==="low_performance")){let r=t.anomalies.filter(o=>o.type==="low_performance").map(o=>o.model);s.push(`Investigate low performance on model(s): ${r.join(", ")}`)}let a=i.filter(r=>r.severity==="critical");a.length>0&&s.push(`URGENT: ${a.length} critical regression(s) detected - immediate review required`);let n=Array.from(e.values()).filter(r=>r.avgPassRate<.9);if(n.length>0){let r=n.filter(l=>!l.schemaValid),o=n.filter(l=>!l.validatorPassed);r.length>0&&s.push(`Fix schema validation for: ${r.map(l=>l.skill).slice(0,3).join(", ")}`),o.length>0&&s.push(`Review validator scripts for: ${o.map(l=>l.skill).slice(0,3).join(", ")}`)}return Array.from(e.values()).reduce((r,o)=>r+o.avgPassRate,0)/e.size<.8&&s.push("Overall pass rate below 80% - consider reviewing skill definitions and test expectations"),s.length===0&&s.push("All validations passing - no immediate action required"),s}async updateManifest(e){if(!N(this.manifestPath))throw new Error(`Manifest file not found: ${this.manifestPath}`);let t=C(E(this.manifestPath,"utf-8"));for(let[s,a]of e.skillResults.entries())if(t.skills&&t.skills[s]){let n=t.skills[s];n.validation||(n.validation={}),n.validation.passRate=a.avgPassRate,n.validation.lastValidated=e.timestamp.toISOString(),n.validation.status=a.avgPassRate>=.9?"passing":"failing",n.validation.passRateByModel=Object.fromEntries(a.passRateByModel)}let i=Array.from(e.skillResults.values());t.validationStatus={passing:i.filter(s=>s.avgPassRate>=.9).length,failing:i.filter(s=>s.avgPassRate<.9).length,unknown:0,skipped:t.summary?.tier0||0},t.generatedAt=new Date().toISOString(),t.lastValidationRun={runId:e.runId,timestamp:e.timestamp.toISOString(),avgPassRate:e.summary.avgPassRate,modelsUsed:e.summary.modelsUsed},L(this.manifestPath,JSON.stringify(t,null,2))}generateMarkdownReport(e){let{summary:t,crossModelAnalysis:i,regressions:s,recommendations:a,skillResults:n}=e,c=(t.avgPassRate>=.9||t.avgPassRate>=.7,"`"),r=[];if(r.push(`# Validation Report
|
|
3
3
|
|
|
4
4
|
> ${c} Generated: ${e.timestamp.toISOString()}
|
|
5
5
|
> Run ID: ${e.runId}
|
|
@@ -1,6 +1,6 @@
|
|
|
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.10.
|
|
2
|
-
import{a as F}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.10.8");process.exit(0)}
|
|
2
|
+
import{a as F}from"./chunk-KTBBSOZG.js";import{a as b,b as E,c as z,d as M,e as C,f as P,g as B}from"./chunk-DNEYBK7X.js";function W(s,e){let n=s.slice(0,e).split(`
|
|
3
3
|
`),r=n.length,o=(n[n.length-1]||"").length;return{line:r,column:o,offset:e}}function p(s,e,n,r,o){return{start:W(s,e),end:W(s,n),oldText:s.slice(e,n),newText:r,description:o}}function _(s,e){let n=[...e].sort((o,t)=>t.start.offset-o.start.offset),r=s;for(let o of n)r=r.slice(0,o.start.offset)+o.newText+r.slice(o.end.offset);return r}function U(s,e){if(s.length===0)return 1;let n=s.reduce((t,a)=>t+Math.abs(a.newText.length-a.oldText.length),0)/s.length,r=Math.max(.5,1-n/1e3),o=Math.max(.7,1-s.length/100);return Math.min(1,e*r*o)}function T(s,e,n,r,o=.9){let t=_(s,n),a=Date.now()-r;return{success:!0,transformType:e,originalCode:s,transformedCode:t,edits:n,changeCount:n.length,confidence:U(n,o),durationMs:a,implementationUsed:"typescript",usedFallback:!1,warnings:[]}}function w(s,e,n,r){return{success:!1,transformType:e,originalCode:s,transformedCode:s,edits:[],changeCount:0,confidence:0,durationMs:Date.now()-r,implementationUsed:"typescript",usedFallback:!1,error:n,warnings:[]}}function Z(s,e={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}}){let n=Date.now(),r=[],o=[];try{let t=/\bvar\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g,a=/([a-zA-Z_$][a-zA-Z0-9_$]*)\s*(?:\+\+|--|[+\-*/%&|^]=|\?\?=|&&=|\|\|=|=(?!=))/g,i=[],l;for(;(l=t.exec(s))!==null;)i.push({name:l[1],offset:l.index});let m=new Set;for(;(l=a.exec(s))!==null;)m.add(l[1]);let u=/\bfor\s*\(\s*var\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g,c=new Set;for(;(l=u.exec(s))!==null;)c.add(l[1]);for(let g of i){let d=c.has(g.name)||m.has(g.name)?"let":"const";r.push(p(s,g.offset,g.offset+3,d,`Convert var ${g.name} to ${d}`))}e.debug("var-to-const transform completed",{declarations:i.length,reassigned:m.size,loopVars:c.size});let f=T(s,"var-to-const",r,n,.95);return f.warnings=o,f}catch(t){return e.error("var-to-const transform failed",t),w(s,"var-to-const",t instanceof Error?t.message:"Unknown error",n)}}function O(s,e={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}}){let n=Date.now(),r=[],o=[];try{let t=/function\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*\(([^)]*)\)/g,a=/(?:const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*\(([^)]*)\)\s*=>/g,i=/([a-zA-Z_$][a-zA-Z0-9_$]*)\s*\(([^)]*)\)\s*(?::\s*[^{]+)?\s*\{/g,l;for(;(l=t.exec(s))!==null;){let u=l[2].trim();if(u&&!u.includes(":")){let c=u.split(",").map(d=>{let h=d.trim().replace(/\s*=.*$/,"");return h&&!h.includes(":")?`${h}: unknown`:d.trim()}).join(", "),f=l.index+l[0].indexOf("(")+1,g=f+l[2].length;r.push(p(s,f,g,c,`Add types to function ${l[1]} parameters`))}}for(;(l=a.exec(s))!==null;){let u=l[2].trim();if(u&&!u.includes(":")){let c=u.split(",").map(d=>{let h=d.trim().replace(/\s*=.*$/,"");return h&&!h.includes(":")?`${h}: unknown`:d.trim()}).join(", "),f=l.index+l[0].indexOf("(")+1,g=f+l[2].length;r.push(p(s,f,g,c,`Add types to arrow function ${l[1]} parameters`))}}e.debug("add-types transform completed",{edits:r.length});let m=T(s,"add-types",r,n,.7);return m.warnings=o,r.length>0&&m.warnings.push('Type annotations use "unknown" - manual review recommended'),m}catch(t){return e.error("add-types transform failed",t),w(s,"add-types",t instanceof Error?t.message:"Unknown error",n)}}function I(s,e={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}}){let n=Date.now(),r=[],o=[];try{let t=/^\s*console\.(log|warn|error|info|debug|trace|dir|table|time|timeEnd|group|groupEnd|assert)\s*\([^)]*\);?\s*$/gm,a=/console\.(log|warn|error|info|debug|trace|dir|table|time|timeEnd|group|groupEnd|assert)\s*\([^)]*\)/g,i,l=new Set;for(;(i=t.exec(s))!==null;)l.has(i.index)||(l.add(i.index),r.push(p(s,i.index,i.index+i[0].length,"",`Remove console.${i[1]}() statement`)));for(;(i=a.exec(s))!==null;){if(l.has(i.index))continue;let u=s.lastIndexOf(`
|
|
4
4
|
`,i.index)+1,c=s.indexOf(`
|
|
5
5
|
`,i.index),f=s.slice(u,c===-1?void 0:c);/^\s*console\./.test(f)||(l.add(i.index),o.push(`Inline console.${i[1]}() at offset ${i.index} - consider manual review`))}e.debug("remove-console transform completed",{removed:r.length,warnings:o.length});let m=T(s,"remove-console",r,n,.95);return m.warnings=o,m}catch(t){return e.error("remove-console transform failed",t),w(s,"remove-console",t instanceof Error?t.message:"Unknown error",n)}}function j(s,e={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}}){let n=Date.now(),r=[],o=[];try{let t=/([a-zA-Z_$][a-zA-Z0-9_$]*(?:\([^)]*\))?)\s*\.then\s*\(\s*(?:async\s*)?\(?\s*([a-zA-Z_$][a-zA-Z0-9_$]*)\s*\)?\s*=>\s*([^)]+)\)/g,a;for(;(a=t.exec(s))!==null;){let[l,m,u,c]=a;if(c.includes(".then")||c.includes(".catch")){o.push(`Complex promise chain at offset ${a.index} - manual review recommended`);continue}let f=`const ${u} = await ${m};
|
|
6
|
-
${c.trim()}`;r.push(p(s,a.index,a.index+l.length,f,"Convert .then() to await"))}e.debug("promise-to-async transform completed",{converted:r.length,warnings:o.length});let i=T(s,"promise-to-async",r,n,.65);return i.warnings=o,r.length>0&&i.warnings.push("Promise chains converted to await - ensure containing function is async"),i}catch(t){return e.error("promise-to-async transform failed",t),w(s,"promise-to-async",t instanceof Error?t.message:"Unknown error",n)}}function N(s,e={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}}){let n=Date.now(),r=[],o=[];try{let t,a=/(?:const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*require\s*\(\s*(['"`][^'"`]+['"`])\s*\)\s*;?/g;for(;(t=a.exec(s))!==null;){let[c,f,g]=t,d=`import ${f} from ${g};`;r.push(p(s,t.index,t.index+c.length,d,"Convert require to import"))}let i=/(?:const|let|var)\s+\{\s*([^}]+)\s*\}\s*=\s*require\s*\(\s*(['"`][^'"`]+['"`])\s*\)\s*;?/g;for(;(t=i.exec(s))!==null;){let[c,f,g]=t,d=`import { ${f.trim()} } from ${g};`;r.push(p(s,t.index,t.index+c.length,d,"Convert destructured require to import"))}let l=/module\.exports\s*=\s*([^;]+);?/g;for(;(t=l.exec(s))!==null;){let[c,f]=t,g=`export default ${f.trim()};`;r.push(p(s,t.index,t.index+c.length,g,"Convert module.exports to export default"))}let m=/exports\.([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*([^;]+);?/g;for(;(t=m.exec(s))!==null;){let[c,f,g]=t,d=g.trim(),h;d.startsWith("function")||d.startsWith("class")?h=`export ${d}`:d.startsWith("async function")?h=`export ${d}`:h=`export const ${f} = ${d};`,r.push(p(s,t.index,t.index+c.length,h,`Convert exports.${f} to named export`))}e.debug("cjs-to-esm transform completed",{edits:r.length});let u=T(s,"cjs-to-esm",r,n,.85);return u.warnings=o,u}catch(t){return e.error("cjs-to-esm transform failed",t),w(s,"cjs-to-esm",t instanceof Error?t.message:"Unknown error",n)}}function H(s,e={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}}){let n=Date.now(),r=[],o=[];try{let t=/(const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*function\s*\(([^)]*)\)\s*\{/g,a;for(;(a=t.exec(s))!==null;){let[m,u,c,f]=a,g=a.index,d=1,h=g+m.length;for(;d>0&&h<s.length;)s[h]==="{"&&d++,s[h]==="}"&&d--,h++;let S=s.slice(g,h);if(/\bthis\b/.test(S)){o.push(`Function ${c} uses 'this' - skipping arrow conversion (would change binding)`);continue}if(/\barguments\b/.test(S)){o.push(`Function ${c} uses 'arguments' - skipping arrow conversion (not available in arrow functions)`);continue}let D=`${u} ${c} = (${f}) => {`;r.push(p(s,a.index,a.index+m.length,D,`Convert function ${c} to arrow function`))}let i=/function\s*\(([^)]*)\)\s*\{\s*return\s+([^;]+);\s*\}/g;for(;(a=i.exec(s))!==null;){let[m,u,c]=a;if(/\b(this|arguments)\b/.test(m))continue;let f=u.includes(",")||u.trim()===""?`(${u}) => ${c}`:`${u.trim()} => ${c}`;r.push(p(s,a.index,a.index+m.length,f,"Convert callback to arrow function"))}e.debug("func-to-arrow transform completed",{converted:r.length,warnings:o.length});let l=T(s,"func-to-arrow",r,n,.85);return l.warnings=o,l}catch(t){return e.error("func-to-arrow transform failed",t),w(s,"func-to-arrow",t instanceof Error?t.message:"Unknown error",n)}}var V={"var-to-const":Z,"add-types":O,"remove-console":I,"promise-to-async":j,"cjs-to-esm":N,"func-to-arrow":H};function $(s,e,n){let r=V[e];return r?r(s,n):{success:!1,transformType:e,originalCode:s,transformedCode:s,edits:[],changeCount:0,confidence:0,durationMs:0,implementationUsed:"typescript",usedFallback:!1,error:`Unknown transform type: ${e}`,warnings:[]}}var q={JavaScript:0,TypeScript:1,Python:2,Rust:3,Go:4,Java:5,C:6,Cpp:7},y=null,A=null,x=null,k=!1,R=null;async function G(){if(k)return R===null;if(R)return!1;try{let s=await import("./agent-booster-wasm-6I3JMU2M.js");return y=s.transform,A=s.warmup,x=s.isWasmAvailable,k=!0,!0}catch(s){return R=s,k=!0,!1}}function K(s){return q.TypeScript}var L=class{cache=new Map;ttlMs;enabled;constructor(e,n){this.enabled=e,this.ttlMs=n}generateKey(e,n){let r=0;for(let o=0;o<e.length;o++){let t=e.charCodeAt(o);r=(r<<5)-r+t,r=r&r}return`${n}:${r}:${e.length}`}get(e,n){if(!this.enabled)return null;let r=this.generateKey(e,n),o=this.cache.get(r);return o?Date.now()>o.expiresAt?(this.cache.delete(r),null):o.result:null}set(e,n,r){if(!this.enabled)return;let o=this.generateKey(e,n);this.cache.set(o,{result:r,expiresAt:Date.now()+this.ttlMs})}clear(){this.cache.clear()}getStats(){return{size:this.cache.size,hitRate:0}}},v=class{config;logger;cache;enabledTransforms;metricsTracker;initialized=!1;wasmAvailable=!1;wasmModule=null;patternsLoaded=!1;totalTransforms=0;successfulTransforms=0;totalDurationMs=0;cacheHits=0;cacheMisses=0;constructor(e={},n,r){this.config={...z,...e},this.logger=n||{debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},this.metricsTracker=r,this.cache=new L(this.config.cacheEnabled,this.config.cacheTtlMs),this.config.transforms.length===0?this.enabledTransforms=new Set(b):this.enabledTransforms=new Set(this.config.transforms)}setMetricsTracker(e){this.metricsTracker=e}async initialize(){this.initialized||(this.logger.info("Initializing Agent Booster adapter",{enabled:this.config.enabled,transforms:Array.from(this.enabledTransforms)}),this.config.transforms.length===0&&await this.loadEligibleTransformsFromPatterns(),this.config.enabled&&await this.tryLoadWasm(),this.initialized=!0,this.logger.info("Agent Booster adapter initialized",{wasmAvailable:this.wasmAvailable,enabledTransforms:Array.from(this.enabledTransforms),patternsLoaded:this.patternsLoaded}))}async loadEligibleTransformsFromPatterns(){try{let n=await F().getEligibleBoosterTransforms();if(n.length>0){let r=n.filter(o=>b.includes(o));if(r.length>0){this.enabledTransforms=new Set(r),this.patternsLoaded=!0,this.logger.info("Loaded eligible transforms from PatternLoader",{fromPatterns:r,invalidIgnored:n.length-r.length});return}}this.logger.debug("PatternLoader returned empty transforms, using defaults")}catch(e){this.logger.warn("Failed to load transforms from PatternLoader, using defaults",{error:e instanceof Error?e.message:"Unknown error"})}this.enabledTransforms=new Set(b),this.patternsLoaded=!1}async tryLoadWasm(){try{if(this.logger.debug("Loading WASM module"),!await G()||!x){this.logger.debug("WASM module could not be loaded, using TypeScript fallback"),this.wasmAvailable=!1;return}this.logger.debug("Checking WASM availability from local module"),await x()&&y&&A?(this.logger.debug("Warming up WASM module"),await A(),this.wasmModule={transform:y,warmup:A,isAvailable:x},this.wasmAvailable=!0,this.logger.info("WASM Agent Booster loaded and warmed up successfully",{source:"local-module"})):(this.logger.debug("WASM not available from local module, using TypeScript fallback"),this.wasmAvailable=!1)}catch(e){this.logger.warn("Failed to load WASM module",{error:e instanceof Error?e.message:"Unknown error"}),this.wasmAvailable=!1}}async dispose(){this.cache.clear(),this.wasmModule=null,this.wasmAvailable=!1,this.initialized=!1,this.logger.info("Agent Booster adapter disposed")}async transform(e,n){this.ensureInitialized(),this.ensureEnabled();let r=Date.now();if(this.totalTransforms++,!this.enabledTransforms.has(n))return this.createErrorResult(e,n,`Transform type '${n}' is not enabled`,r);let o=this.cache.get(e,n);if(o)return this.cacheHits++,this.logger.debug("Cache hit for transform",{type:n}),{...o,durationMs:Date.now()-r};this.cacheMisses++;let t;try{t=await this.executeWithFallback(e,n,r)}catch(a){return this.createErrorResult(e,n,a instanceof Error?a.message:"Unknown error",r)}return t.success&&(this.successfulTransforms++,this.cache.set(e,n,t)),this.totalDurationMs+=t.durationMs,await this.recordMetrics(t,n),t}async recordMetrics(e,n){if(this.metricsTracker)try{let r=`booster-${n}-${Date.now()}`;await this.metricsTracker.recordOutcome("booster",r,e.success,e.durationMs,{subType:n,confidence:e.confidence,usedFallback:e.usedFallback,implementationUsed:e.implementationUsed,itemCount:e.changeCount,errorMessage:e.error})}catch(r){this.logger.warn("Failed to record metrics",{error:r instanceof Error?r.message:"Unknown error"})}}async executeWithFallback(e,n,r){if(this.wasmAvailable)try{let t=await this.executeWasmTransform(e,n,r);if(t.success&&t.confidence>=this.config.confidenceThreshold)return t;this.logger.debug("WASM transform low confidence, trying TypeScript",{confidence:t.confidence,threshold:this.config.confidenceThreshold})}catch(t){this.logger.warn("WASM transform failed, falling back to TypeScript",{error:t instanceof Error?t.message:"Unknown error"})}let o=$(e,n,this.logger);return o.durationMs=Date.now()-r,this.config.fallbackToLLM&&o.confidence<this.config.confidenceThreshold&&(this.logger.debug("TypeScript transform low confidence, LLM fallback available",{confidence:o.confidence,threshold:this.config.confidenceThreshold}),o.warnings.push(`Confidence ${o.confidence.toFixed(2)} is below threshold ${this.config.confidenceThreshold}. LLM fallback recommended for review.`),o.usedFallback=!0),o}async executeWasmTransform(e,n,r){if(!this.wasmAvailable)throw new C;let o=K(n),t=$(e,n,this.logger);if(t.changeCount===0)return{...t,durationMs:Date.now()-r,implementationUsed:"wasm"};if(!y)throw new C("WASM transform function not loaded");let a=await Promise.race([y(e,t.transformedCode,o,{confidenceThreshold:this.config.confidenceThreshold,allowFallback:!0}),new Promise((m,u)=>setTimeout(()=>u(new P("WASM transform timed out",n,this.config.timeoutMs)),this.config.timeoutMs))]),i=Date.now()-r,l=a.success&&a.mergedCode!==e?t.changeCount:0;return{success:a.success,transformType:n,originalCode:e,transformedCode:a.mergedCode,edits:t.edits,changeCount:l,confidence:a.confidence,durationMs:i,implementationUsed:a.source==="wasm"?"wasm":"typescript",usedFallback:a.source!=="wasm",error:a.error,warnings:a.syntaxValid?[]:["WASM reported syntax may be invalid"]}}async batchTransform(e,n){this.ensureInitialized(),this.ensureEnabled();let r=Date.now(),o=[],t=[],a=0,i=0,l=0,m=0;for(let u of e){if(u.content.length>this.config.maxFileSizeBytes){let c=new B(u.path,u.content.length,this.config.maxFileSizeBytes);t.push({path:u.path,error:c.message}),i++;continue}try{let c=await this.transform(u.content,n);o.push({path:u.path,result:c}),c.success?c.changeCount>0?(a++,m+=c.changeCount):l++:(i++,c.error&&t.push({path:u.path,error:c.error}))}catch(c){i++,t.push({path:u.path,error:c instanceof Error?c.message:"Unknown error"})}}return{success:i===0,transformType:n,files:o,totalFiles:e.length,successCount:a,failureCount:i,noChangeCount:l,totalChanges:m,durationMs:Date.now()-r,errors:t}}async detectTransformOpportunities(e){this.ensureInitialized(),this.ensureEnabled();let n=Date.now(),r=[],o={},t=[];for(let a of b)o[a]=0;for(let a of Array.from(this.enabledTransforms))try{let i=await this.transform(e,a);if(i.changeCount>0)for(let l of i.edits){let m={type:a,confidence:i.confidence,location:l.start,codeSnippet:l.oldText.slice(0,100)+(l.oldText.length>100?"...":""),suggestedCode:l.newText.slice(0,100)+(l.newText.length>100?"...":""),reason:l.description,risk:this.confidenceToRisk(i.confidence),estimatedDurationMs:E[a].typicalLatencyMs};r.push(m),o[a]++}}catch(i){t.push(`Failed to analyze for ${a}: ${i instanceof Error?i.message:"Unknown error"}`)}return r.sort((a,i)=>i.confidence-a.confidence),{opportunities:r,totalCount:r.length,byType:o,durationMs:Date.now()-n,complete:t.length===0,warnings:t}}isTransformAvailable(e){return this.enabledTransforms.has(e)}getTransformMetadata(e){return E[e]}getAvailableTransforms(){return Array.from(this.enabledTransforms)}isWasmAvailable(){return this.wasmAvailable}getHealth(){let e=this.totalTransforms>0?this.totalDurationMs/this.totalTransforms:0,n=this.cacheHits+this.cacheMisses>0?this.cacheHits/(this.cacheHits+this.cacheMisses):0,r=[];return this.initialized||r.push("Adapter not initialized"),this.config.enabled||r.push("Adapter is disabled"),this.wasmAvailable||r.push("WASM module not loaded (using TypeScript fallback)"),this.patternsLoaded||r.push("Patterns not loaded from PatternLoader (using defaults)"),{ready:this.initialized&&this.config.enabled,wasmAvailable:this.wasmAvailable,patternsLoaded:this.patternsLoaded,availableTransforms:Array.from(this.enabledTransforms),lastChecked:new Date,issues:r,metrics:{totalTransforms:this.totalTransforms,successfulTransforms:this.successfulTransforms,averageDurationMs:e,cacheHitRate:n}}}ensureInitialized(){if(!this.initialized)throw new M("AgentBoosterAdapter not initialized. Call initialize() first.","var-to-const")}ensureEnabled(){if(!this.config.enabled)throw new M("AgentBoosterAdapter is disabled. Set enabled: true in config.","var-to-const")}createErrorResult(e,n,r,o){return{success:!1,transformType:n,originalCode:e,transformedCode:e,edits:[],changeCount:0,confidence:0,durationMs:Date.now()-o,implementationUsed:"typescript",usedFallback:!1,error:r,warnings:[]}}confidenceToRisk(e){return e>=.95?"info":e>=.85?"low":e>=.7?"medium":e>=.5?"high":"critical"}};async function ee(s={},e,n){let r=new v(s,e,n);return await r.initialize(),r}function re(s={},e,n){return new v(s,e,n)}export{v as a,ee as b,re as c};
|
|
6
|
+
${c.trim()}`;r.push(p(s,a.index,a.index+l.length,f,"Convert .then() to await"))}e.debug("promise-to-async transform completed",{converted:r.length,warnings:o.length});let i=T(s,"promise-to-async",r,n,.65);return i.warnings=o,r.length>0&&i.warnings.push("Promise chains converted to await - ensure containing function is async"),i}catch(t){return e.error("promise-to-async transform failed",t),w(s,"promise-to-async",t instanceof Error?t.message:"Unknown error",n)}}function N(s,e={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}}){let n=Date.now(),r=[],o=[];try{let t,a=/(?:const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*require\s*\(\s*(['"`][^'"`]+['"`])\s*\)\s*;?/g;for(;(t=a.exec(s))!==null;){let[c,f,g]=t,d=`import ${f} from ${g};`;r.push(p(s,t.index,t.index+c.length,d,"Convert require to import"))}let i=/(?:const|let|var)\s+\{\s*([^}]+)\s*\}\s*=\s*require\s*\(\s*(['"`][^'"`]+['"`])\s*\)\s*;?/g;for(;(t=i.exec(s))!==null;){let[c,f,g]=t,d=`import { ${f.trim()} } from ${g};`;r.push(p(s,t.index,t.index+c.length,d,"Convert destructured require to import"))}let l=/module\.exports\s*=\s*([^;]+);?/g;for(;(t=l.exec(s))!==null;){let[c,f]=t,g=`export default ${f.trim()};`;r.push(p(s,t.index,t.index+c.length,g,"Convert module.exports to export default"))}let m=/exports\.([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*([^;]+);?/g;for(;(t=m.exec(s))!==null;){let[c,f,g]=t,d=g.trim(),h;d.startsWith("function")||d.startsWith("class")?h=`export ${d}`:d.startsWith("async function")?h=`export ${d}`:h=`export const ${f} = ${d};`,r.push(p(s,t.index,t.index+c.length,h,`Convert exports.${f} to named export`))}e.debug("cjs-to-esm transform completed",{edits:r.length});let u=T(s,"cjs-to-esm",r,n,.85);return u.warnings=o,u}catch(t){return e.error("cjs-to-esm transform failed",t),w(s,"cjs-to-esm",t instanceof Error?t.message:"Unknown error",n)}}function H(s,e={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}}){let n=Date.now(),r=[],o=[];try{let t=/(const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*function\s*\(([^)]*)\)\s*\{/g,a;for(;(a=t.exec(s))!==null;){let[m,u,c,f]=a,g=a.index,d=1,h=g+m.length;for(;d>0&&h<s.length;)s[h]==="{"&&d++,s[h]==="}"&&d--,h++;let S=s.slice(g,h);if(/\bthis\b/.test(S)){o.push(`Function ${c} uses 'this' - skipping arrow conversion (would change binding)`);continue}if(/\barguments\b/.test(S)){o.push(`Function ${c} uses 'arguments' - skipping arrow conversion (not available in arrow functions)`);continue}let D=`${u} ${c} = (${f}) => {`;r.push(p(s,a.index,a.index+m.length,D,`Convert function ${c} to arrow function`))}let i=/function\s*\(([^)]*)\)\s*\{\s*return\s+([^;]+);\s*\}/g;for(;(a=i.exec(s))!==null;){let[m,u,c]=a;if(/\b(this|arguments)\b/.test(m))continue;let f=u.includes(",")||u.trim()===""?`(${u}) => ${c}`:`${u.trim()} => ${c}`;r.push(p(s,a.index,a.index+m.length,f,"Convert callback to arrow function"))}e.debug("func-to-arrow transform completed",{converted:r.length,warnings:o.length});let l=T(s,"func-to-arrow",r,n,.85);return l.warnings=o,l}catch(t){return e.error("func-to-arrow transform failed",t),w(s,"func-to-arrow",t instanceof Error?t.message:"Unknown error",n)}}var V={"var-to-const":Z,"add-types":O,"remove-console":I,"promise-to-async":j,"cjs-to-esm":N,"func-to-arrow":H};function $(s,e,n){let r=V[e];return r?r(s,n):{success:!1,transformType:e,originalCode:s,transformedCode:s,edits:[],changeCount:0,confidence:0,durationMs:0,implementationUsed:"typescript",usedFallback:!1,error:`Unknown transform type: ${e}`,warnings:[]}}var q={JavaScript:0,TypeScript:1,Python:2,Rust:3,Go:4,Java:5,C:6,Cpp:7},y=null,A=null,x=null,k=!1,R=null;async function G(){if(k)return R===null;if(R)return!1;try{let s=await import("./agent-booster-wasm-4JSL6LF6.js");return y=s.transform,A=s.warmup,x=s.isWasmAvailable,k=!0,!0}catch(s){return R=s,k=!0,!1}}function K(s){return q.TypeScript}var L=class{cache=new Map;ttlMs;enabled;constructor(e,n){this.enabled=e,this.ttlMs=n}generateKey(e,n){let r=0;for(let o=0;o<e.length;o++){let t=e.charCodeAt(o);r=(r<<5)-r+t,r=r&r}return`${n}:${r}:${e.length}`}get(e,n){if(!this.enabled)return null;let r=this.generateKey(e,n),o=this.cache.get(r);return o?Date.now()>o.expiresAt?(this.cache.delete(r),null):o.result:null}set(e,n,r){if(!this.enabled)return;let o=this.generateKey(e,n);this.cache.set(o,{result:r,expiresAt:Date.now()+this.ttlMs})}clear(){this.cache.clear()}getStats(){return{size:this.cache.size,hitRate:0}}},v=class{config;logger;cache;enabledTransforms;metricsTracker;initialized=!1;wasmAvailable=!1;wasmModule=null;patternsLoaded=!1;totalTransforms=0;successfulTransforms=0;totalDurationMs=0;cacheHits=0;cacheMisses=0;constructor(e={},n,r){this.config={...z,...e},this.logger=n||{debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},this.metricsTracker=r,this.cache=new L(this.config.cacheEnabled,this.config.cacheTtlMs),this.config.transforms.length===0?this.enabledTransforms=new Set(b):this.enabledTransforms=new Set(this.config.transforms)}setMetricsTracker(e){this.metricsTracker=e}async initialize(){this.initialized||(this.logger.info("Initializing Agent Booster adapter",{enabled:this.config.enabled,transforms:Array.from(this.enabledTransforms)}),this.config.transforms.length===0&&await this.loadEligibleTransformsFromPatterns(),this.config.enabled&&await this.tryLoadWasm(),this.initialized=!0,this.logger.info("Agent Booster adapter initialized",{wasmAvailable:this.wasmAvailable,enabledTransforms:Array.from(this.enabledTransforms),patternsLoaded:this.patternsLoaded}))}async loadEligibleTransformsFromPatterns(){try{let n=await F().getEligibleBoosterTransforms();if(n.length>0){let r=n.filter(o=>b.includes(o));if(r.length>0){this.enabledTransforms=new Set(r),this.patternsLoaded=!0,this.logger.info("Loaded eligible transforms from PatternLoader",{fromPatterns:r,invalidIgnored:n.length-r.length});return}}this.logger.debug("PatternLoader returned empty transforms, using defaults")}catch(e){this.logger.warn("Failed to load transforms from PatternLoader, using defaults",{error:e instanceof Error?e.message:"Unknown error"})}this.enabledTransforms=new Set(b),this.patternsLoaded=!1}async tryLoadWasm(){try{if(this.logger.debug("Loading WASM module"),!await G()||!x){this.logger.debug("WASM module could not be loaded, using TypeScript fallback"),this.wasmAvailable=!1;return}this.logger.debug("Checking WASM availability from local module"),await x()&&y&&A?(this.logger.debug("Warming up WASM module"),await A(),this.wasmModule={transform:y,warmup:A,isAvailable:x},this.wasmAvailable=!0,this.logger.info("WASM Agent Booster loaded and warmed up successfully",{source:"local-module"})):(this.logger.debug("WASM not available from local module, using TypeScript fallback"),this.wasmAvailable=!1)}catch(e){this.logger.warn("Failed to load WASM module",{error:e instanceof Error?e.message:"Unknown error"}),this.wasmAvailable=!1}}async dispose(){this.cache.clear(),this.wasmModule=null,this.wasmAvailable=!1,this.initialized=!1,this.logger.info("Agent Booster adapter disposed")}async transform(e,n){this.ensureInitialized(),this.ensureEnabled();let r=Date.now();if(this.totalTransforms++,!this.enabledTransforms.has(n))return this.createErrorResult(e,n,`Transform type '${n}' is not enabled`,r);let o=this.cache.get(e,n);if(o)return this.cacheHits++,this.logger.debug("Cache hit for transform",{type:n}),{...o,durationMs:Date.now()-r};this.cacheMisses++;let t;try{t=await this.executeWithFallback(e,n,r)}catch(a){return this.createErrorResult(e,n,a instanceof Error?a.message:"Unknown error",r)}return t.success&&(this.successfulTransforms++,this.cache.set(e,n,t)),this.totalDurationMs+=t.durationMs,await this.recordMetrics(t,n),t}async recordMetrics(e,n){if(this.metricsTracker)try{let r=`booster-${n}-${Date.now()}`;await this.metricsTracker.recordOutcome("booster",r,e.success,e.durationMs,{subType:n,confidence:e.confidence,usedFallback:e.usedFallback,implementationUsed:e.implementationUsed,itemCount:e.changeCount,errorMessage:e.error})}catch(r){this.logger.warn("Failed to record metrics",{error:r instanceof Error?r.message:"Unknown error"})}}async executeWithFallback(e,n,r){if(this.wasmAvailable)try{let t=await this.executeWasmTransform(e,n,r);if(t.success&&t.confidence>=this.config.confidenceThreshold)return t;this.logger.debug("WASM transform low confidence, trying TypeScript",{confidence:t.confidence,threshold:this.config.confidenceThreshold})}catch(t){this.logger.warn("WASM transform failed, falling back to TypeScript",{error:t instanceof Error?t.message:"Unknown error"})}let o=$(e,n,this.logger);return o.durationMs=Date.now()-r,this.config.fallbackToLLM&&o.confidence<this.config.confidenceThreshold&&(this.logger.debug("TypeScript transform low confidence, LLM fallback available",{confidence:o.confidence,threshold:this.config.confidenceThreshold}),o.warnings.push(`Confidence ${o.confidence.toFixed(2)} is below threshold ${this.config.confidenceThreshold}. LLM fallback recommended for review.`),o.usedFallback=!0),o}async executeWasmTransform(e,n,r){if(!this.wasmAvailable)throw new C;let o=K(n),t=$(e,n,this.logger);if(t.changeCount===0)return{...t,durationMs:Date.now()-r,implementationUsed:"wasm"};if(!y)throw new C("WASM transform function not loaded");let a=await Promise.race([y(e,t.transformedCode,o,{confidenceThreshold:this.config.confidenceThreshold,allowFallback:!0}),new Promise((m,u)=>setTimeout(()=>u(new P("WASM transform timed out",n,this.config.timeoutMs)),this.config.timeoutMs))]),i=Date.now()-r,l=a.success&&a.mergedCode!==e?t.changeCount:0;return{success:a.success,transformType:n,originalCode:e,transformedCode:a.mergedCode,edits:t.edits,changeCount:l,confidence:a.confidence,durationMs:i,implementationUsed:a.source==="wasm"?"wasm":"typescript",usedFallback:a.source!=="wasm",error:a.error,warnings:a.syntaxValid?[]:["WASM reported syntax may be invalid"]}}async batchTransform(e,n){this.ensureInitialized(),this.ensureEnabled();let r=Date.now(),o=[],t=[],a=0,i=0,l=0,m=0;for(let u of e){if(u.content.length>this.config.maxFileSizeBytes){let c=new B(u.path,u.content.length,this.config.maxFileSizeBytes);t.push({path:u.path,error:c.message}),i++;continue}try{let c=await this.transform(u.content,n);o.push({path:u.path,result:c}),c.success?c.changeCount>0?(a++,m+=c.changeCount):l++:(i++,c.error&&t.push({path:u.path,error:c.error}))}catch(c){i++,t.push({path:u.path,error:c instanceof Error?c.message:"Unknown error"})}}return{success:i===0,transformType:n,files:o,totalFiles:e.length,successCount:a,failureCount:i,noChangeCount:l,totalChanges:m,durationMs:Date.now()-r,errors:t}}async detectTransformOpportunities(e){this.ensureInitialized(),this.ensureEnabled();let n=Date.now(),r=[],o={},t=[];for(let a of b)o[a]=0;for(let a of Array.from(this.enabledTransforms))try{let i=await this.transform(e,a);if(i.changeCount>0)for(let l of i.edits){let m={type:a,confidence:i.confidence,location:l.start,codeSnippet:l.oldText.slice(0,100)+(l.oldText.length>100?"...":""),suggestedCode:l.newText.slice(0,100)+(l.newText.length>100?"...":""),reason:l.description,risk:this.confidenceToRisk(i.confidence),estimatedDurationMs:E[a].typicalLatencyMs};r.push(m),o[a]++}}catch(i){t.push(`Failed to analyze for ${a}: ${i instanceof Error?i.message:"Unknown error"}`)}return r.sort((a,i)=>i.confidence-a.confidence),{opportunities:r,totalCount:r.length,byType:o,durationMs:Date.now()-n,complete:t.length===0,warnings:t}}isTransformAvailable(e){return this.enabledTransforms.has(e)}getTransformMetadata(e){return E[e]}getAvailableTransforms(){return Array.from(this.enabledTransforms)}isWasmAvailable(){return this.wasmAvailable}getHealth(){let e=this.totalTransforms>0?this.totalDurationMs/this.totalTransforms:0,n=this.cacheHits+this.cacheMisses>0?this.cacheHits/(this.cacheHits+this.cacheMisses):0,r=[];return this.initialized||r.push("Adapter not initialized"),this.config.enabled||r.push("Adapter is disabled"),this.wasmAvailable||r.push("WASM module not loaded (using TypeScript fallback)"),this.patternsLoaded||r.push("Patterns not loaded from PatternLoader (using defaults)"),{ready:this.initialized&&this.config.enabled,wasmAvailable:this.wasmAvailable,patternsLoaded:this.patternsLoaded,availableTransforms:Array.from(this.enabledTransforms),lastChecked:new Date,issues:r,metrics:{totalTransforms:this.totalTransforms,successfulTransforms:this.successfulTransforms,averageDurationMs:e,cacheHitRate:n}}}ensureInitialized(){if(!this.initialized)throw new M("AgentBoosterAdapter not initialized. Call initialize() first.","var-to-const")}ensureEnabled(){if(!this.config.enabled)throw new M("AgentBoosterAdapter is disabled. Set enabled: true in config.","var-to-const")}createErrorResult(e,n,r,o){return{success:!1,transformType:n,originalCode:e,transformedCode:e,edits:[],changeCount:0,confidence:0,durationMs:Date.now()-o,implementationUsed:"typescript",usedFallback:!1,error:r,warnings:[]}}confidenceToRisk(e){return e>=.95?"info":e>=.85?"low":e>=.7?"medium":e>=.5?"high":"critical"}};async function ee(s={},e,n){let r=new v(s,e,n);return await r.initialize(),r}function re(s={},e,n){return new v(s,e,n)}export{v as a,ee as b,re as c};
|
|
@@ -1 +1 @@
|
|
|
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.10.
|
|
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.10.8");process.exit(0)}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.
|
|
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.10.8");process.exit(0)}
|
|
2
2
|
import{readFileSync as R,existsSync as v,readdirSync as y}from"fs";import{join as S}from"path";var M=100*1024,b=/mcp__([a-z][a-z0-9-]*)__([a-z][a-z0-9_]*)/g,x=/^```/;function w(e,r){let n=e.length>M?e.slice(0,M):e,o=[],i=n.split(`
|
|
3
3
|
`),a=!1;for(let s=0;s<i.length;s++){let p=i[s];if(x.test(p.trim())){a=!a;continue}let l,c=new RegExp(b.source,"g");for(;(l=c.exec(p))!==null;){let t=l[1],g=l[2],f=l[0],d=a?"code-block":"prose",u=d==="prose"?.9:.5;o.push({toolName:f,serverName:t,actionName:g,confidence:u,context:d,lineNumber:s+1})}}return o}function E(e){let r=new Map;for(let n of e)r.has(n.serverName)||r.set(n.serverName,[]),r.get(n.serverName).push(n);return r}function N(e){let r=[],n=[S(e,".claude","mcp.json"),S(e,".mcp.json")],o=process.env.HOME||process.env.USERPROFILE||"";o&&n.push(S(o,".claude","mcp.json"));for(let i of n)if(v(i))try{let a=R(i,"utf-8"),s=JSON.parse(a);s.mcpServers&&typeof s.mcpServers=="object"&&r.push(...Object.keys(s.mcpServers))}catch{}return[...new Set(r)]}function h(e,r,n){if(!v(e))return{agentName:r,references:[],requiredServers:[],availableServers:n,missingServers:[],warnings:[`Agent file not found: ${e}`],allSatisfied:!0};let o;try{o=R(e,"utf-8")}catch{return{agentName:r,references:[],requiredServers:[],availableServers:n,missingServers:[],warnings:[`Failed to read agent file: ${e}`],allSatisfied:!0}}let i=w(o,r),a=E(i),s=[...a.keys()],p=new Set(n),l=s.filter(t=>!p.has(t)),c=[];for(let t of l){let g=a.get(t)||[],f=Math.max(...g.map(m=>m.confidence)),d=g.length,u=[...new Set(g.map(m=>m.context))].join(", ");c.push(`[advisory] Agent "${r}" references MCP server "${t}" (${d} tool ref${d>1?"s":""}, confidence: ${f}, context: ${u}) but server is not configured. Agent may have reduced capabilities.`)}return{agentName:r,references:i,requiredServers:s,availableServers:n,missingServers:l,warnings:c,allSatisfied:l.length===0}}function C(e,r){let n=Date.now(),o=[],i=[],a=N(r);if(!v(e))return{agents:[],totalServersReferenced:0,globalMissingServers:[],agentsWithMissingDeps:[],warnings:[`Agents directory not found: ${e}`],durationMs:Date.now()-n};try{let c=y(e);for(let g of c){if(!g.endsWith(".md"))continue;let f=g.replace(".md",""),d=S(e,g),u=h(d,f,a);o.push(u),i.push(...u.warnings)}let t=S(e,"subagents");if(v(t)){let g=y(t);for(let f of g){if(!f.endsWith(".md"))continue;let d=f.replace(".md",""),u=S(t,f),m=h(u,d,a);o.push(m),i.push(...m.warnings)}}}catch(c){i.push(`Error scanning agents directory: ${c.message}`)}let s=new Set,p=new Set,l=[];for(let c of o){for(let t of c.requiredServers)s.add(t);for(let t of c.missingServers)p.add(t);c.missingServers.length>0&&l.push(c.agentName)}return{agents:o,totalServersReferenced:s.size,globalMissingServers:[...p],agentsWithMissingDeps:l,warnings:i,durationMs:Date.now()-n}}export{N as a,C as b};
|