agentic-qe 3.9.2 → 3.9.4
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/CHANGELOG.md +53 -0
- package/dist/cli/bundle.js +5 -5
- package/dist/cli/chunks/adapter-5ODIX6ZG.js +2 -0
- package/dist/cli/chunks/{agent-booster-wasm-AKAOHSCX.js → agent-booster-wasm-MGGEPROV.js} +2 -2
- package/dist/cli/chunks/{agent-handler-MTGPOUVP.js → agent-handler-AFHYFQXV.js} +2 -2
- package/dist/cli/chunks/{agent-memory-branch-UFPKWUFK.js → agent-memory-branch-SQ3KDIG6.js} +2 -2
- package/dist/cli/chunks/aqe-learning-engine-PWGRS6KK.js +2 -0
- package/dist/cli/chunks/{audit-VBEZHNHO.js → audit-SM5CK2K5.js} +2 -2
- package/dist/cli/chunks/base-TJGIYR7L.js +2 -0
- package/dist/cli/chunks/{better-sqlite3-IRPHIXRU.js → better-sqlite3-UGOYRNXI.js} +2 -2
- package/dist/cli/chunks/{brain-handler-7EO3FFRZ.js → brain-handler-SKXTB63O.js} +3 -3
- package/dist/cli/chunks/{branch-enumerator-MZRGP35N.js → branch-enumerator-77NSOLNK.js} +2 -2
- package/dist/cli/chunks/{browser-VSIWQE7J.js → browser-MCE5DWPV.js} +2 -2
- package/dist/cli/chunks/browser-workflow-GUR7RLFP.js +2 -0
- package/dist/cli/chunks/{chunk-5RL66XSH.js → chunk-27FNBMUC.js} +2 -2
- package/dist/cli/chunks/{chunk-FRJLP7IB.js → chunk-27P4VTCY.js} +2 -2
- package/dist/cli/chunks/{chunk-2VVV73PW.js → chunk-2JLKOGNU.js} +1 -1
- package/dist/cli/chunks/{chunk-PJFLO37I.js → chunk-2MQMXI7C.js} +2 -2
- package/dist/cli/chunks/{chunk-BKCTNRC5.js → chunk-3MN7E6HY.js} +2 -2
- package/dist/cli/chunks/{chunk-BY47GV4T.js → chunk-3MRFR534.js} +2 -2
- package/dist/cli/chunks/{chunk-563PJBDM.js → chunk-3RHIPCBG.js} +2 -2
- package/dist/cli/chunks/{chunk-WXWY2GAF.js → chunk-3SPYUOSS.js} +2 -2
- package/dist/cli/chunks/{chunk-5AUKULWO.js → chunk-4BQTEPAD.js} +2 -2
- package/dist/cli/chunks/{chunk-N3F3CX4V.js → chunk-4GJAYXB7.js} +2 -2
- package/dist/cli/chunks/{chunk-7NOIIC7G.js → chunk-4TZTGYBQ.js} +1 -1
- package/dist/cli/chunks/{chunk-VL7YOOC2.js → chunk-53M65YFH.js} +2 -2
- package/dist/cli/chunks/{chunk-QNBQBSAI.js → chunk-54OLXGXJ.js} +2 -2
- package/dist/cli/chunks/{chunk-HW4ISY5B.js → chunk-5UKAEBKC.js} +3 -3
- package/dist/cli/chunks/{chunk-CQP7ZFME.js → chunk-72EC26AS.js} +2 -2
- package/dist/cli/chunks/{chunk-J4BS6IWE.js → chunk-7EL65Y27.js} +1 -1
- package/dist/cli/chunks/{chunk-PFNFC43Q.js → chunk-7FJIIB4H.js} +1 -1
- package/dist/cli/chunks/{chunk-AKSJQ6B3.js → chunk-7ST2YENJ.js} +2 -2
- package/dist/cli/chunks/{chunk-SNVM4YJS.js → chunk-7ZXNJT4Q.js} +2 -2
- package/dist/cli/chunks/{chunk-BOH22AKC.js → chunk-A6ZBQCYB.js} +2 -2
- package/dist/cli/chunks/{chunk-VHVWAXCF.js → chunk-B252DDC5.js} +1 -1
- package/dist/cli/chunks/{chunk-2EC5Z2J4.js → chunk-B6HLXE3D.js} +9 -9
- package/dist/cli/chunks/{chunk-L5WZUPZF.js → chunk-BH5XPYA3.js} +2 -2
- package/dist/cli/chunks/{chunk-LMMEUVE5.js → chunk-BZ22GI4E.js} +1 -1
- package/dist/cli/chunks/{chunk-YXCU4CJX.js → chunk-C2HGOUEB.js} +1 -1
- package/dist/cli/chunks/{chunk-JV7LX6OT.js → chunk-C3BXT3ZC.js} +4 -4
- package/dist/cli/chunks/{chunk-3GZKAORV.js → chunk-C567IO5M.js} +2 -2
- package/dist/cli/chunks/{chunk-SCF7NRVE.js → chunk-COIRFVFO.js} +1 -1
- package/dist/cli/chunks/{chunk-RITN3XR4.js → chunk-DHJJJ24V.js} +2 -2
- package/dist/cli/chunks/{chunk-RC5CPXON.js → chunk-DLMEBVLF.js} +2 -2
- package/dist/cli/chunks/{chunk-XFMKJ3UD.js → chunk-DZHGYZJP.js} +1 -1
- package/dist/cli/chunks/{chunk-V6XBAZNH.js → chunk-EEARIB4C.js} +1 -1
- package/dist/cli/chunks/{chunk-NM6TIEJ3.js → chunk-EFD2J6GG.js} +3 -3
- package/dist/cli/chunks/{chunk-Z5HXGVXZ.js → chunk-EHGTXIT7.js} +1 -1
- package/dist/cli/chunks/{chunk-QODE4LM6.js → chunk-ENKPW6MA.js} +2 -2
- package/dist/cli/chunks/{chunk-4PKXIBX2.js → chunk-EZTUUOVI.js} +1 -1
- package/dist/cli/chunks/{chunk-SDTVHR63.js → chunk-F6AU2MAZ.js} +2 -2
- package/dist/cli/chunks/{chunk-GK72GUHA.js → chunk-G6RTCJFY.js} +2 -2
- package/dist/cli/chunks/{chunk-E25S5E2D.js → chunk-G72E5DL3.js} +1 -1
- package/dist/cli/chunks/{chunk-FUIHWBVF.js → chunk-GAG2P4I2.js} +1 -1
- package/dist/cli/chunks/{chunk-KDDZYXP4.js → chunk-GQ7DCSKS.js} +2 -2
- package/dist/cli/chunks/{chunk-WG4GHAML.js → chunk-GSKZL36U.js} +2 -2
- package/dist/cli/chunks/{chunk-Z2IKNC5M.js → chunk-GT35EJKR.js} +1 -1
- package/dist/cli/chunks/{chunk-56IWS2KY.js → chunk-GVFHRHXC.js} +2 -2
- package/dist/cli/chunks/{chunk-CCYMJKWX.js → chunk-GX7MEHQ2.js} +1 -1
- package/dist/cli/chunks/{chunk-4UH25U4O.js → chunk-HKTNFHWI.js} +1 -1
- package/dist/cli/chunks/{chunk-X6LCMOGC.js → chunk-IGJ472XJ.js} +2 -2
- package/dist/cli/chunks/{chunk-XH53ARZD.js → chunk-IQE6GOH6.js} +2 -2
- package/dist/cli/chunks/{chunk-RJROC5M3.js → chunk-J222JLZ6.js} +2 -2
- package/dist/cli/chunks/{chunk-DSE57A5N.js → chunk-J6KBI5NW.js} +1 -1
- package/dist/cli/chunks/{chunk-CQBSGYRA.js → chunk-J72Q6ERO.js} +2 -2
- package/dist/cli/chunks/{chunk-ICDXWIFZ.js → chunk-JMBUIVVE.js} +1 -1
- package/dist/cli/chunks/{chunk-6SOJVEU7.js → chunk-JVUNZBKX.js} +2 -2
- package/dist/cli/chunks/{chunk-MN742FIH.js → chunk-KELYPHMV.js} +2 -2
- package/dist/cli/chunks/{chunk-DHE66JRR.js → chunk-KSMQH2CV.js} +1 -1
- package/dist/cli/chunks/{chunk-GPLERTZU.js → chunk-LH3ZL2OK.js} +2 -2
- package/dist/cli/chunks/{chunk-GITD7SRQ.js → chunk-LW3DV23G.js} +2 -2
- package/dist/cli/chunks/chunk-MDFXPCBO.js +2 -0
- package/dist/cli/chunks/{chunk-KZUJBZ7B.js → chunk-MGRE767N.js} +2 -2
- package/dist/cli/chunks/{chunk-DBE34QES.js → chunk-MN2MYLVW.js} +2 -2
- package/dist/cli/chunks/{chunk-25LFUL2K.js → chunk-MR5I6UR2.js} +2 -2
- package/dist/cli/chunks/{chunk-S3RDH5CI.js → chunk-MS6LTE4L.js} +2 -2
- package/dist/cli/chunks/{chunk-QEQTC4WQ.js → chunk-MUX762XZ.js} +2 -2
- package/dist/cli/chunks/{chunk-4Z27TRQF.js → chunk-NEYZXYFH.js} +2 -2
- package/dist/cli/chunks/{chunk-7SLN2JGP.js → chunk-NRH2QE4X.js} +3 -3
- package/dist/cli/chunks/{chunk-CL3K5EJK.js → chunk-NS4CCCTZ.js} +2 -2
- package/dist/cli/chunks/{chunk-NJY7ZA77.js → chunk-NZ5LY2BT.js} +1 -1
- package/dist/cli/chunks/{chunk-UKDOMLBI.js → chunk-O6QAOPUA.js} +3 -3
- package/dist/cli/chunks/{chunk-QPRVX4H2.js → chunk-OHZ6RJLS.js} +2 -2
- package/dist/cli/chunks/{chunk-DNLMZTE2.js → chunk-ONOYANDX.js} +1 -1
- package/dist/cli/chunks/chunk-OZC42UMD.js +2 -0
- package/dist/cli/chunks/{chunk-34U7JDCN.js → chunk-P3EOWBME.js} +2 -2
- package/dist/cli/chunks/{chunk-4DAOZQ3V.js → chunk-Q2ZYUIS2.js} +2 -2
- package/dist/cli/chunks/{chunk-RQGYJK7H.js → chunk-Q6FSXNQP.js} +2 -2
- package/dist/cli/chunks/{chunk-X35GP7TR.js → chunk-QEYPK7KS.js} +1 -1
- package/dist/cli/chunks/{chunk-T5GV6UIO.js → chunk-QOU4R6AF.js} +2 -2
- package/dist/cli/chunks/{chunk-KZTO5EVM.js → chunk-QPC4STR6.js} +2 -2
- package/dist/cli/chunks/{chunk-4FT3PND7.js → chunk-QVZSIFSJ.js} +3 -3
- package/dist/cli/chunks/{chunk-GCMVJS5X.js → chunk-RAZ2PGZD.js} +2 -2
- package/dist/cli/chunks/{chunk-727BDQ3K.js → chunk-RE6XD6RI.js} +2 -2
- package/dist/cli/chunks/{chunk-STE42EMB.js → chunk-RGRYL4MG.js} +2 -2
- package/dist/cli/chunks/{chunk-XYJL6DKI.js → chunk-RN3SN4ZC.js} +2 -2
- package/dist/cli/chunks/{chunk-JOVINE23.js → chunk-RPYUKEAH.js} +2 -2
- package/dist/cli/chunks/{chunk-5L6AU3QK.js → chunk-RRQEIGLS.js} +2 -2
- package/dist/cli/chunks/{chunk-VUAO4VFC.js → chunk-RS7ZGWHV.js} +2 -2
- package/dist/cli/chunks/{chunk-KTYUCZEM.js → chunk-RTC3ZCPK.js} +5 -5
- package/dist/cli/chunks/{chunk-4LA7IW3V.js → chunk-RUJU5XEQ.js} +1 -1
- package/dist/cli/chunks/{chunk-SRRFWTNF.js → chunk-SHJZ3YNX.js} +2 -2
- package/dist/cli/chunks/{chunk-FAXVVLPL.js → chunk-SKWI5QBM.js} +2 -2
- package/dist/cli/chunks/{chunk-NRCKGXJJ.js → chunk-TNWTQWLL.js} +1 -1
- package/dist/cli/chunks/{chunk-KBA7FBK3.js → chunk-TT2TB6UF.js} +3 -3
- package/dist/cli/chunks/{chunk-Z54EO6E6.js → chunk-U7YC7VCM.js} +2 -2
- package/dist/cli/chunks/{chunk-TKF447CW.js → chunk-UJLSCJJS.js} +1 -1
- package/dist/cli/chunks/{chunk-MY4LMIG7.js → chunk-UPJZRDZK.js} +2 -2
- package/dist/cli/chunks/{chunk-KQTJ2YLI.js → chunk-UUL3D5HR.js} +4 -4
- package/dist/cli/chunks/{chunk-TTOE336G.js → chunk-V57PXZIK.js} +3 -3
- package/dist/cli/chunks/{chunk-SGAW2WLI.js → chunk-VBXJBXMG.js} +4 -4
- package/dist/cli/chunks/{chunk-BIVIPF4O.js → chunk-VBYREHZI.js} +1 -1
- package/dist/cli/chunks/{chunk-PNL5G6TE.js → chunk-VFXTZWNF.js} +2 -2
- package/dist/cli/chunks/{chunk-2WBCYSUN.js → chunk-VSNPI2NO.js} +8 -8
- package/dist/cli/chunks/{chunk-Y6O7CDLI.js → chunk-WHT46PJM.js} +2 -2
- package/dist/cli/chunks/{chunk-L5YEPSDU.js → chunk-XB5HXTL4.js} +2 -2
- package/dist/cli/chunks/{chunk-4FMHBBG5.js → chunk-XYVMKCSI.js} +1 -1
- package/dist/cli/chunks/{chunk-AA33R5U4.js → chunk-YDJKQKQH.js} +2 -2
- package/dist/cli/chunks/{chunk-4D2ZG2QO.js → chunk-YS6C2Q4F.js} +1 -1
- package/dist/cli/chunks/{chunk-65M7C6SH.js → chunk-Z75DMTMI.js} +1 -1
- package/dist/cli/chunks/{chunk-Q4A72ZTV.js → chunk-ZKWNZ3ZK.js} +2 -2
- package/dist/cli/chunks/{chunk-2Z2TFEOL.js → chunk-ZODUKKPC.js} +2 -2
- package/dist/cli/chunks/{chunk-KNVAAVHH.js → chunk-ZQSEPDIJ.js} +2 -2
- package/dist/cli/chunks/{chunk-QIH3E775.js → chunk-ZW5DRPZY.js} +2 -2
- package/dist/cli/chunks/{ci-2BCOBWFG.js → ci-THZEECIQ.js} +2 -2
- package/dist/cli/chunks/{ci-output-FB4OJHAC.js → ci-output-G6QLGL4S.js} +2 -2
- package/dist/cli/chunks/{claude-flow-setup-NEEFZTMB.js → claude-flow-setup-5MTYQM34.js} +2 -2
- package/dist/cli/chunks/client-IFMC3AYQ.js +2 -0
- package/dist/cli/chunks/{cline-installer-ODO2PS4K.js → cline-installer-E2LF2DQS.js} +2 -2
- package/dist/cli/chunks/{code-NSOF62VE.js → code-QRF7ZGXG.js} +2 -2
- package/dist/cli/chunks/{code-index-extractor-YQL5XN52.js → code-index-extractor-II6IRWU6.js} +2 -2
- package/dist/cli/chunks/{codex-installer-SPEY6VYT.js → codex-installer-LGOQ23ZS.js} +2 -2
- package/dist/cli/chunks/{completions-OWKBUMBE.js → completions-LB2RR2OQ.js} +2 -2
- package/dist/cli/chunks/{complexity-analyzer-PGTXKP73.js → complexity-analyzer-PUIPIRX3.js} +2 -2
- package/dist/cli/chunks/{continuedev-installer-KGOXAC7L.js → continuedev-installer-HQAEAQZU.js} +2 -2
- package/dist/cli/chunks/{copilot-installer-BF3UA3TG.js → copilot-installer-3PKCX5K5.js} +2 -2
- package/dist/cli/chunks/{cost-tracker-2HDJ66E2.js → cost-tracker-JG3SZ2Q3.js} +2 -2
- package/dist/cli/chunks/{coverage-KPA2PHIN.js → coverage-D3PZTOKT.js} +3 -3
- package/dist/cli/chunks/cross-domain-router-2LPBUUWY.js +2 -0
- package/dist/cli/chunks/{cursor-installer-7CDZFHTV.js → cursor-installer-UY6GWKTO.js} +2 -2
- package/dist/cli/chunks/{daemon-4BPGCKDJ.js → daemon-UNO3LRRN.js} +3 -3
- package/dist/cli/chunks/{dag-attention-scheduler-2MAVGSBB.js → dag-attention-scheduler-S2MXANYL.js} +2 -2
- package/dist/cli/chunks/{detect-WRPWTGP5.js → detect-DU2FTRKR.js} +2 -2
- package/dist/cli/chunks/{domain-handler-JZVSJ7AG.js → domain-handler-KPNO36LF.js} +2 -2
- package/dist/cli/chunks/{domain-transfer-XGIZOR2X.js → domain-transfer-6X3ZZF6A.js} +2 -2
- package/dist/cli/chunks/dream-NGRDMOTE.js +2 -0
- package/dist/cli/chunks/esm-node-3COTOSO3.js +2 -0
- package/dist/cli/chunks/{eval-T7YPAS4G.js → eval-6RXEDTBZ.js} +2 -2
- package/dist/cli/chunks/{fast-paths-QECJTKCQ.js → fast-paths-FYODFGZB.js} +2 -2
- package/dist/cli/chunks/{feature-flags-LIFURSFZ.js → feature-flags-YOULURDA.js} +2 -2
- package/dist/cli/chunks/{feature-flags-R4QZYTIW.js → feature-flags-ZJ42B4IL.js} +2 -2
- package/dist/cli/chunks/{file-discovery-4W3K3W4C.js → file-discovery-KOL7FSBQ.js} +2 -2
- package/dist/cli/chunks/{fleet-NLLQWCI5.js → fleet-22I74LGD.js} +3 -3
- package/dist/cli/chunks/{gnn-wrapper-XEII72LN.js → gnn-wrapper-DFHTHLIZ.js} +2 -2
- package/dist/cli/chunks/{heartbeat-handler-DJ65RE5D.js → heartbeat-handler-SQ6VYEAA.js} +4 -4
- package/dist/cli/chunks/{heartbeat-scheduler-H664265Q.js → heartbeat-scheduler-W6PQJ5SG.js} +2 -2
- package/dist/cli/chunks/hnsw-adapter-BASJNTEV.js +2 -0
- package/dist/cli/chunks/hnsw-index-NFN2AUIX.js +2 -0
- package/dist/cli/chunks/{hnsw-legacy-bridge-SQIDTWAA.js → hnsw-legacy-bridge-AYTRT54U.js} +2 -2
- package/dist/cli/chunks/{hnswlib-node-WICYCU5U.js → hnswlib-node-4IA56UH4.js} +2 -2
- package/dist/cli/chunks/{hooks-GZUHUD63.js → hooks-T6UMR72X.js} +6 -6
- package/dist/cli/chunks/{hypergraph-engine-MLCDZ6BL.js → hypergraph-engine-WVPYKMFY.js} +2 -2
- package/dist/cli/chunks/{hypergraph-handler-NNDDI4R3.js → hypergraph-handler-NB6GL4CR.js} +3 -3
- package/dist/cli/chunks/impact-analyzer-ZMQXHQDV.js +2 -0
- package/dist/cli/chunks/init-handler-UOFNBXEP.js +68 -0
- package/dist/cli/chunks/init-wizard-QHAA4GWF.js +2 -0
- package/dist/cli/chunks/kernel-SNJFYN3T.js +2 -0
- package/dist/cli/chunks/{kilocode-installer-EPZFFPFE.js → kilocode-installer-VWMNI4QX.js} +2 -2
- package/dist/cli/chunks/{kiro-installer-5VACG3HU.js → kiro-installer-RNM47FV5.js} +15 -15
- package/dist/cli/chunks/knowledge-graph-EP5UTODP.js +2 -0
- package/dist/cli/chunks/{learning-6FITK6XY.js → learning-L4RB5XYP.js} +3 -3
- package/dist/cli/chunks/{llm-router-4DDC6AKJ.js → llm-router-BZYZL3YI.js} +2 -2
- package/dist/cli/chunks/{load-KGDNVUBX.js → load-4UGEGRMO.js} +2 -2
- package/dist/cli/chunks/load-test-KMMRHABK.js +2 -0
- package/dist/cli/chunks/mcp-FWWZIWCI.js +2 -0
- package/dist/cli/chunks/{memory-II4I4QMO.js → memory-5OXPMXU6.js} +5 -5
- package/dist/cli/chunks/memory-backend-Q5MWPMDE.js +2 -0
- package/dist/cli/chunks/{memory-handlers-TQXTOJGQ.js → memory-handlers-JS7BTWJK.js} +2 -2
- package/dist/cli/chunks/{opencode-installer-EU6JCWBW.js → opencode-installer-BS5TQKHB.js} +2 -2
- package/dist/cli/chunks/orchestrator-G6BUZ6QE.js +370 -0
- package/dist/cli/chunks/{pipeline-MPZJWYKK.js → pipeline-3MZ5COPR.js} +2 -2
- package/dist/cli/chunks/{platform-YH35ZZFZ.js → platform-TKD4JCUG.js} +2 -2
- package/dist/cli/chunks/{plugin-B7JYZFNQ.js → plugin-XXJ7R6SY.js} +2 -2
- package/dist/cli/chunks/{prime-radiant-advanced-wasm-KTUK6UE2.js → prime-radiant-advanced-wasm-JLJ6NKIP.js} +2 -2
- package/dist/cli/chunks/protocol-executor-ORFR4WJ3.js +2 -0
- package/dist/cli/chunks/{protocol-handler-3NXMVU34.js → protocol-handler-ZLYGQPHG.js} +2 -2
- package/dist/cli/chunks/{prove-H5LMGSUC.js → prove-E2WZ335X.js} +2 -2
- package/dist/cli/chunks/qe-reasoning-bank-PLTOH4SG.js +2 -0
- package/dist/cli/chunks/{quality-RCWHY6GO.js → quality-6MHHBINU.js} +2 -2
- package/dist/cli/chunks/queen-coordinator-L3TRAX7H.js +2 -0
- package/dist/cli/chunks/{real-embeddings-NKH4VURF.js → real-embeddings-QN5BY3WS.js} +2 -2
- package/dist/cli/chunks/{roocode-installer-SB7QJYM3.js → roocode-installer-GTVII272.js} +2 -2
- package/dist/cli/chunks/router-3PBJJLRQ.js +2 -0
- package/dist/cli/chunks/routing-feedback-Q775MZ3Z.js +2 -0
- package/dist/cli/chunks/{routing-handler-SY7GKG2W.js → routing-handler-HYKZ3ISS.js} +2 -2
- package/dist/cli/chunks/{ruvector-commands-HATTO3UQ.js → ruvector-commands-LBWHPUTZ.js} +2 -2
- package/dist/cli/chunks/{rvf-dual-writer-D57EXQUD.js → rvf-dual-writer-TVCJ2Y6N.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-adapter-OWDYN6KD.js → rvf-migration-adapter-34ITXLU3.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-coordinator-SIQVJB5S.js → rvf-migration-coordinator-SX2C7777.js} +2 -2
- package/dist/cli/chunks/rvf-native-adapter-HLY2652E.js +2 -0
- package/dist/cli/chunks/safe-db-CCKCBZ5I.js +2 -0
- package/dist/cli/chunks/schedule-WZ5VV55N.js +2 -0
- package/dist/cli/chunks/scheduler-6PIKLCH7.js +2 -0
- package/dist/cli/chunks/{security-DS3XLZWN.js → security-7A4EW77M.js} +3 -3
- package/dist/cli/chunks/shared-rvf-adapter-VCJNSACZ.js +2 -0
- package/dist/cli/chunks/{shared-rvf-dual-writer-YB7AH6XJ.js → shared-rvf-dual-writer-27L4R5WK.js} +2 -2
- package/dist/cli/chunks/sqlite-persistence-HMXYD56G.js +2 -0
- package/dist/cli/chunks/{status-handler-TUYHE4FT.js → status-handler-JN6PRYLD.js} +2 -2
- package/dist/cli/chunks/{structural-health-XNGBNRRD.js → structural-health-JSY3DY7H.js} +2 -2
- package/dist/cli/chunks/{sync-K6CIRKBB.js → sync-ET3LYW2V.js} +10 -10
- package/dist/cli/chunks/{task-handler-7PJY67DR.js → task-handler-R24MR74L.js} +2 -2
- package/dist/cli/chunks/{task-handlers-WB5CDWUR.js → task-handlers-YNPEEPPZ.js} +2 -2
- package/dist/cli/chunks/{test-WV5ALEBB.js → test-7BZXFZCT.js} +4 -4
- package/dist/cli/chunks/{test-scheduling-N55ZGGA2.js → test-scheduling-EVIFD5EY.js} +3 -3
- package/dist/cli/chunks/{token-bootstrap-SINWHAKR.js → token-bootstrap-QYYQRXM5.js} +2 -2
- package/dist/cli/chunks/{token-usage-R7TGEVGL.js → token-usage-H4OZA77I.js} +2 -2
- package/dist/cli/chunks/{transformers-6DBLXPV7.js → transformers-ILQFO5HZ.js} +2 -2
- package/dist/cli/chunks/{tree-sitter-wasm-parser-7C7FKMQW.js → tree-sitter-wasm-parser-KTST5NWH.js} +2 -2
- package/dist/cli/chunks/{types-VNPMOKQT.js → types-4Z7XELU6.js} +2 -2
- package/dist/cli/chunks/unified-memory-RBHCTAWW.js +2 -0
- package/dist/cli/chunks/unified-memory-hnsw-UBF5PT6D.js +2 -0
- package/dist/cli/chunks/unified-persistence-ZIJDP6GW.js +2 -0
- package/dist/cli/chunks/{validate-53MNIRAF.js → validate-GSQCH6VN.js} +2 -2
- package/dist/cli/chunks/{validate-swarm-ZY4RGUFO.js → validate-swarm-SP2RPOYD.js} +2 -2
- package/dist/cli/chunks/{vibium-PBADBIV6.js → vibium-2SGOFYTF.js} +2 -2
- package/dist/cli/chunks/visual-security-WKIWOUTH.js +2 -0
- package/dist/cli/chunks/{web-tree-sitter-O7VI6RLB.js → web-tree-sitter-QSQ27UTH.js} +2 -2
- package/dist/cli/chunks/{windsurf-installer-HV3C3TAD.js → windsurf-installer-NIEH46E2.js} +2 -2
- package/dist/cli/chunks/witness-chain-4BRX3GGH.js +2 -0
- package/dist/cli/chunks/{witness-chain-4WIMYP4X.js → witness-chain-62GJTCT5.js} +2 -2
- package/dist/cli/chunks/{workflow-5RVAQ4TM.js → workflow-WZMV2MGW.js} +4 -4
- package/dist/cli/chunks/workflow-orchestrator-G6VU7QZ4.js +2 -0
- package/dist/cli/chunks/{wrappers-RRHCCA3E.js → wrappers-LNTV533I.js} +2 -2
- package/dist/cli/commands/init.js +2 -0
- package/dist/cli/commands/mcp.js +27 -17
- package/dist/cli/commands/sync.js +25 -8
- package/dist/cli/handlers/init-handler.d.ts +1 -0
- package/dist/cli/handlers/init-handler.js +2 -0
- package/dist/init/governance-installer.js +46 -14
- package/dist/init/kiro-installer.js +15 -2
- package/dist/init/orchestrator.js +1 -0
- package/dist/init/phases/06-code-intelligence.d.ts +46 -1
- package/dist/init/phases/06-code-intelligence.js +164 -10
- package/dist/init/phases/10-workers.d.ts +0 -14
- package/dist/init/phases/10-workers.js +19 -164
- package/dist/init/phases/phase-interface.d.ts +9 -0
- package/dist/kernel/hnsw-adapter.d.ts +14 -0
- package/dist/kernel/hnsw-adapter.js +25 -1
- package/dist/kernel/hnsw-index-provider.d.ts +16 -0
- package/dist/kernel/native-hnsw-backend.d.ts +11 -0
- package/dist/kernel/native-hnsw-backend.js +20 -0
- package/dist/kernel/progressive-hnsw-backend.d.ts +9 -0
- package/dist/kernel/progressive-hnsw-backend.js +41 -12
- package/dist/kernel/unified-memory.js +10 -0
- package/dist/mcp/bundle.js +216 -216
- package/dist/optimization/token-optimizer-service.d.ts +31 -2
- package/dist/optimization/token-optimizer-service.js +85 -23
- package/package.json +1 -1
- package/dist/cli/chunks/adapter-53WBPKXU.js +0 -2
- package/dist/cli/chunks/aqe-learning-engine-MV7NGY24.js +0 -2
- package/dist/cli/chunks/base-DZVGMQN2.js +0 -2
- package/dist/cli/chunks/browser-workflow-3J5YNMEI.js +0 -2
- package/dist/cli/chunks/chunk-LCAA6H4J.js +0 -2
- package/dist/cli/chunks/chunk-XIBVVZGB.js +0 -2
- package/dist/cli/chunks/client-EF555KYW.js +0 -2
- package/dist/cli/chunks/cross-domain-router-GXFNK5TS.js +0 -2
- package/dist/cli/chunks/dream-3IKF5XH4.js +0 -2
- package/dist/cli/chunks/esm-node-DHAE52OW.js +0 -2
- package/dist/cli/chunks/hnsw-adapter-DML5KXQR.js +0 -2
- package/dist/cli/chunks/hnsw-index-BUPPGVR6.js +0 -2
- package/dist/cli/chunks/impact-analyzer-DPTMJRYS.js +0 -2
- package/dist/cli/chunks/init-handler-IJ6BHE6A.js +0 -68
- package/dist/cli/chunks/init-wizard-35PUDJPW.js +0 -2
- package/dist/cli/chunks/kernel-2HZ44ZJ4.js +0 -2
- package/dist/cli/chunks/knowledge-graph-JL62G72U.js +0 -2
- package/dist/cli/chunks/load-test-LN245SSD.js +0 -2
- package/dist/cli/chunks/mcp-4LETGVIV.js +0 -2
- package/dist/cli/chunks/memory-backend-SVM7YRIE.js +0 -2
- package/dist/cli/chunks/orchestrator-YLMGJVSP.js +0 -371
- package/dist/cli/chunks/protocol-executor-IEN2XB4L.js +0 -2
- package/dist/cli/chunks/qe-reasoning-bank-Q3ZV3JRG.js +0 -2
- package/dist/cli/chunks/queen-coordinator-E6ON3JUR.js +0 -2
- package/dist/cli/chunks/router-WMC3LZ3C.js +0 -2
- package/dist/cli/chunks/routing-feedback-VKCZRCE3.js +0 -2
- package/dist/cli/chunks/rvf-native-adapter-C7NBH5UN.js +0 -2
- package/dist/cli/chunks/safe-db-5KLXCNXN.js +0 -2
- package/dist/cli/chunks/schedule-HAWWOXWB.js +0 -2
- package/dist/cli/chunks/scheduler-HTRDY5BC.js +0 -2
- package/dist/cli/chunks/shared-rvf-adapter-6I2Z5UGL.js +0 -2
- package/dist/cli/chunks/sqlite-persistence-WNNRGTGG.js +0 -2
- package/dist/cli/chunks/unified-memory-72SKVZ7Y.js +0 -2
- package/dist/cli/chunks/unified-memory-hnsw-TMN2L77W.js +0 -2
- package/dist/cli/chunks/unified-persistence-MDN3SRCR.js +0 -2
- package/dist/cli/chunks/visual-security-TRBCXPIB.js +0 -2
- package/dist/cli/chunks/witness-chain-JOI2YYGK.js +0 -2
- package/dist/cli/chunks/workflow-orchestrator-2NQ72S3C.js +0 -2
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{a as v}from"./chunk-BOH22AKC.js";import{h as U}from"./chunk-WG4GHAML.js";import{c as D,d as R,e as h,g as x}from"./chunk-ICDXWIFZ.js";var f=class{config;trackers;globalCostTodayUsd=0;lastGlobalReset=new Date;constructor(e){this.config=e,this.trackers=new Map;for(let t of[0,1,2,3,4])this.trackers.set(t,{tier:t,costSpentTodayUsd:0,requestsThisHour:0,requestsToday:0,lastHourlyReset:new Date,lastDailyReset:new Date,requestHistory:[]})}async checkBudget(e,t){if(!this.config.enabled)return this.createAllowedDecision(e,e,t,!1,[]);this.autoReset();let r=this.config.tierBudgets[e];if(!r||!r.enabled)return this.createAllowedDecision(e,e,t,!1,["Tier budget not configured or disabled"]);let s=this.getUsage(e),i=[],c=this.config.maxDailyCostUsd-this.globalCostTodayUsd;if(this.globalCostTodayUsd+t>this.config.maxDailyCostUsd)return this.handleBudgetExceeded(e,t,s,"Global daily budget would be exceeded");if(this.globalCostTodayUsd+t>=this.config.maxDailyCostUsd*this.config.warningThreshold&&(i.push(`Approaching global daily budget limit: $${this.globalCostTodayUsd.toFixed(2)}/$${this.config.maxDailyCostUsd.toFixed(2)}`),this.config.onBudgetWarning==="downgrade"))return this.downgradeTier(e,t,s,i);let a=[{exceeded:s.costSpentTodayUsd+t>r.maxDailyCostUsd,message:`Tier ${e} daily cost limit would be exceeded: $${s.costSpentTodayUsd.toFixed(2)}/$${r.maxDailyCostUsd.toFixed(2)}`},{exceeded:s.requestsThisHour>=r.maxRequestsPerHour,message:`Tier ${e} hourly request limit reached: ${s.requestsThisHour}/${r.maxRequestsPerHour}`},{exceeded:s.requestsToday>=r.maxRequestsPerDay,message:`Tier ${e} daily request limit reached: ${s.requestsToday}/${r.maxRequestsPerDay}`},{exceeded:t>r.maxCostPerRequest,message:`Tier ${e} per-request cost limit would be exceeded: $${t.toFixed(4)}/$${r.maxCostPerRequest.toFixed(4)}`}];for(let n of a)if(n.exceeded)return this.handleBudgetExceeded(e,t,s,n.message);return s.budgetUtilization>=this.config.warningThreshold&&(i.push(`Tier ${e} at ${(s.budgetUtilization*100).toFixed(1)}% of daily budget`),this.config.onBudgetWarning==="downgrade")?this.downgradeTier(e,t,s,i):this.createAllowedDecision(e,e,t,!1,i)}async recordCost(e,t){if(!this.config.enabled)return;let r=this.trackers.get(e);r&&(this.autoReset(),r.costSpentTodayUsd+=t,r.requestsThisHour++,r.requestsToday++,this.globalCostTodayUsd+=t,r.requestHistory.push({timestamp:new Date,costUsd:t}),r.requestHistory.length>1e3&&(r.requestHistory=r.requestHistory.slice(-1e3)))}getUsage(e){this.autoReset();let t=this.trackers.get(e);if(!t)return this.createEmptyUsage(e);let r=this.config.tierBudgets[e];if(!r)return this.createEmptyUsage(e);let s=r.maxDailyCostUsd>0?t.costSpentTodayUsd/r.maxDailyCostUsd:0,i=t.costSpentTodayUsd>=r.maxDailyCostUsd||t.requestsThisHour>=r.maxRequestsPerHour||t.requestsToday>=r.maxRequestsPerDay,c=s>=this.config.warningThreshold,a=new Date,n=new Date(a);return n.setUTCHours(24,0,0,0),{tier:e,costSpentTodayUsd:t.costSpentTodayUsd,requestsThisHour:t.requestsThisHour,requestsToday:t.requestsToday,budgetUtilization:s,isExceeded:i,isNearLimit:c,resetTime:n,remainingBudgetUsd:Math.max(0,r.maxDailyCostUsd-t.costSpentTodayUsd),remainingRequestsThisHour:Math.max(0,r.maxRequestsPerHour-t.requestsThisHour),remainingRequestsToday:Math.max(0,r.maxRequestsPerDay-t.requestsToday)}}getAllUsage(){let e={};for(let t of[0,1,2,3,4])e[t]=this.getUsage(t);return e}reset(){let e=new Date;for(let t of this.trackers.values())t.costSpentTodayUsd=0,t.requestsThisHour=0,t.requestsToday=0,t.lastHourlyReset=e,t.lastDailyReset=e,t.requestHistory=[];this.globalCostTodayUsd=0,this.lastGlobalReset=e}handleBudgetExceeded(e,t,r,s){switch(this.config.onBudgetExceeded){case"error":throw new h(`Budget exceeded: ${s}`,e,r);case"downgrade":return this.downgradeTier(e,t,r,[s]);case"queue":throw new h(`Budget exceeded (queueing not yet implemented): ${s}`,e,r);default:throw new h(`Budget exceeded: ${s}`,e,r)}}downgradeTier(e,t,r,s){for(let i=e-1;i>=0;i--){let c=this.config.tierBudgets[i];if(!c||!c.enabled)continue;let a=this.getUsage(i);if(!a.isExceeded){let n=t*.5;if(a.costSpentTodayUsd+n<=c.maxDailyCostUsd)return this.createAllowedDecision(e,i,n,!0,[...s,`Downgraded from Tier ${e} to Tier ${i} due to budget constraints`])}}throw new h(`Budget exceeded and no lower tier available: ${s.join("; ")}`,e,r)}createAllowedDecision(e,t,r,s,i){let c=this.getUsage(t);return{allowed:!0,reason:s?`Budget enforced: downgraded to Tier ${t}`:"Budget check passed",requestedTier:e,approvedTier:t,wasDowngraded:s,estimatedCostUsd:r,currentUsage:c,warnings:i}}createEmptyUsage(e){let t=new Date,r=new Date(t);return r.setUTCHours(24,0,0,0),{tier:e,costSpentTodayUsd:0,requestsThisHour:0,requestsToday:0,budgetUtilization:0,isExceeded:!1,isNearLimit:!1,resetTime:r,remainingBudgetUsd:0,remainingRequestsThisHour:0,remainingRequestsToday:0}}autoReset(){let e=new Date;this.shouldResetDaily(this.lastGlobalReset,e)&&(this.globalCostTodayUsd=0,this.lastGlobalReset=e);for(let t of this.trackers.values())this.shouldResetHourly(t.lastHourlyReset,e)&&(t.requestsThisHour=0,t.lastHourlyReset=e),this.shouldResetDaily(t.lastDailyReset,e)&&(t.costSpentTodayUsd=0,t.requestsToday=0,t.requestHistory=[],t.lastDailyReset=e)}shouldResetHourly(e,t){return(t.getTime()-e.getTime())/36e5>=1}shouldResetDaily(e,t){return t.getUTCDate()!==e.getUTCDate()||t.getUTCMonth()!==e.getUTCMonth()||t.getUTCFullYear()!==e.getUTCFullYear()}getSessionCostSummary(){this.autoReset();let e=this.config.maxDailyCostUsd,t=0,r={},s={0:"AgentBooster",1:"Haiku",2:"Sonnet",3:"SonnetExtended",4:"Opus"};for(let[c,a]of this.trackers.entries()){let n=this.config.tierBudgets[c],o=s[c]??`Tier${c}`;t+=a.costSpentTodayUsd,r[o]={spent:a.costSpentTodayUsd,limit:n?.maxDailyCostUsd??0,requests:a.requestsToday}}let i=e>0?Math.round(t/e*100):0;return{totalSpentUsd:t,dailyLimitUsd:e,utilizationPercent:i,byTier:r}}};var w=class{cache=new Map;maxSize;ttlMs;enabled;constructor(e,t,r){this.enabled=e,this.maxSize=t,this.ttlMs=r}generateKey(e){return`${e.agentType||"unknown"}:${e.domain||"unknown"}:${e.task.slice(0,100)}`}get(e){if(!this.enabled)return null;let t=this.generateKey(e),r=this.cache.get(t);return r?Date.now()>r.expiresAt?(this.cache.delete(t),null):{...r.decision,metadata:{...r.decision.metadata,fromCache:!0,decisionTimeMs:0}}:null}set(e,t){if(!this.enabled)return;let r=this.generateKey(e);if(this.cache.size>=this.maxSize){let s=this.cache.keys().next().value;s&&this.cache.delete(s)}this.cache.set(r,{decision:t,expiresAt:Date.now()+this.ttlMs})}clear(){this.cache.clear()}getStats(){return{size:this.cache.size,hitRate:0}}},M=class{events=[];enabled;maxEvents=1e4;constructor(e){this.enabled=e}record(e){this.enabled&&(this.events.push(e),this.events.length>this.maxEvents&&(this.events=this.events.slice(-this.maxEvents)))}getMetrics(){if(this.events.length===0)return this.createEmptyMetrics();let e=new Date,t={};for(let o of[0,1,2,3,4]){let d=this.events.filter(l=>l.tier===o);if(d.length===0)continue;let T=d.filter(l=>l.success),m=d.filter(l=>!l.wasManualOverride),b=d.filter(l=>l.wasDowngraded),y=d.map(l=>l.latencyMs).sort((l,g)=>l-g),B=Math.floor(y.length*.95);t[o]={tier:o,selectionCount:d.length,autoRouteCount:m.length,manualOverrideCount:d.length-m.length,budgetDowngradeCount:b.length,successRate:T.length/d.length,avgComplexity:d.reduce((l,g)=>l+g.complexity,0)/d.length,totalCostUsd:d.reduce((l,g)=>l+g.costUsd,0),avgLatencyMs:d.reduce((l,g)=>l+g.latencyMs,0)/d.length,p95LatencyMs:y[B]||0,budgetUtilization:0}}let r=this.events.map(o=>o.latencyMs).sort((o,d)=>o-d),s=Math.floor(r.length*.95),i=Math.floor(r.length*.99),c=this.events.filter(o=>o.agentBoosterEligible).length,a=this.events.filter(o=>o.tier===0).length,n=this.events.filter(o=>o.tier===0&&o.success).length;return{byTier:t,totalDecisions:this.events.length,avgDecisionTimeMs:this.events.reduce((o,d)=>o+d.latencyMs,0)/this.events.length,p95DecisionTimeMs:r[s]||0,p99DecisionTimeMs:r[i]||0,fallbackRate:this.events.filter(o=>o.wasDowngraded).length/this.events.length,ruleMatchRate:this.events.filter(o=>!o.wasManualOverride).length/this.events.length,estimatedCostSavings:0,agentBoosterStats:{eligible:c,used:a,fallbackToLLM:Math.max(0,c-a),successRate:a>0?n/a:0},budgetStats:{totalSpentUsd:this.events.reduce((o,d)=>o+d.costUsd,0),budgetUtilization:0,downgradeCount:this.events.filter(o=>o.wasDowngraded).length,overrideCount:this.events.filter(o=>o.wasManualOverride).length},period:{start:this.events[0]?.timestamp||e,end:this.events[this.events.length-1]?.timestamp||e}}}reset(){this.events=[]}createEmptyMetrics(){let e=new Date;return{byTier:{},totalDecisions:0,avgDecisionTimeMs:0,p95DecisionTimeMs:0,p99DecisionTimeMs:0,fallbackRate:0,ruleMatchRate:0,estimatedCostSavings:0,agentBoosterStats:{eligible:0,used:0,fallbackToLLM:0,successRate:0},budgetStats:{totalSpentUsd:0,budgetUtilization:0,downgradeCount:0,overrideCount:0},period:{start:e,end:e}}}},p=class{config;complexityAnalyzer;budgetEnforcer;agentBoosterAdapter;cache;metrics;persistentMetricsTracker;patternsLoaded=!1;tierHierarchyFromPatterns=null;constructor(e={},t,r){this.config={...D,...e},this.agentBoosterAdapter=t,this.persistentMetricsTracker=r,this.complexityAnalyzer=U(this.config,t),this.budgetEnforcer=new f(this.config.budgetConfig),this.cache=new w(this.config.enableDecisionCache,1e3,this.config.decisionCacheTtlMs),this.metrics=new M(this.config.enableMetrics)}setPersistentMetricsTracker(e){this.persistentMetricsTracker=e}async loadPatternsFromLoader(){try{let t=await v().getTierHierarchy();if(t){this.tierHierarchyFromPatterns=t,this.patternsLoaded=!0,console.info("[ModelRouter] Loaded tier hierarchy from PatternLoader",{tiers:Object.keys(t)});return}console.debug("[ModelRouter] PatternLoader returned no tier hierarchy, using defaults")}catch(e){console.warn("[ModelRouter] Failed to load patterns from PatternLoader, using defaults",{error:e instanceof Error?e.message:"Unknown error"})}this.patternsLoaded=!1}getPatternsLoaded(){return this.patternsLoaded}getTierHierarchyFromPatterns(){return this.tierHierarchyFromPatterns}async route(e){let t=Date.now(),r=e.metadata?.correlationId;try{let s=this.cache.get(e);if(s)return s;let i=await Promise.race([this.routeInternal(e,t,r),new Promise((c,a)=>setTimeout(()=>a(new x("Routing decision timed out",this.config.maxDecisionTimeMs)),this.config.maxDecisionTimeMs))]);return this.cache.set(e,i),this.recordMetrics(i,!0),i}catch(s){let i=await this.createFallbackDecision(e,t,r,s instanceof Error?s:new Error("Unknown error"));return this.recordMetrics(i,!1),i}}getMetrics(){return this.metrics.getMetrics()}async getAgentBoosterHealth(){if(!this.agentBoosterAdapter)throw new R("Agent Booster adapter not available","AGENT_BOOSTER_UNAVAILABLE");return this.agentBoosterAdapter.getHealth()}resetMetrics(){this.metrics.reset()}async dispose(){this.cache.clear(),this.metrics.reset(),this.agentBoosterAdapter&&await this.agentBoosterAdapter.dispose()}async routeInternal(e,t,r){let s=[];if(e.manualTier!==void 0&&this.config.allowManualOverrides)return this.handleManualOverride(e,e.manualTier,t,r);let i=await this.complexityAnalyzer.analyze(e),c=i.recommendedTier,a=this.estimateCost(c,e.task.length),n=await this.budgetEnforcer.checkBudget(c,a),o=n.approvedTier;s.push(...n.warnings);let d=o===0&&i.signals.isMechanicalTransform,T=this.getModelIdForTier(o),m=this.buildRationale(i,n,o),b=this.buildAlternatives(i,o),y=Date.now()-t;return{tier:o,modelId:T,complexityAnalysis:i,budgetDecision:n,confidence:i.confidence,rationale:m,agentBoosterEligible:d,agentBoosterTransform:d?i.signals.detectedTransformType:void 0,alternativeTiers:b,metadata:{timestamp:new Date,decisionTimeMs:y,fromCache:!1,correlationId:r},warnings:s}}async handleManualOverride(e,t,r,s){let i=await this.complexityAnalyzer.analyze(e),c=this.estimateCost(t,e.task.length),a=await this.budgetEnforcer.checkBudget(t,c);!a.allowed&&e.isCritical&&this.config.budgetConfig.allowCriticalOverrides&&(a={...a,allowed:!0,reason:"Critical task override",warnings:[...a.warnings,"Budget exceeded but allowed due to critical task override"]});let n=a.approvedTier,o=this.getModelIdForTier(n),d=Date.now()-r;return{tier:n,modelId:o,complexityAnalysis:i,budgetDecision:a,confidence:1,rationale:`Manual override to Tier ${n}${a.wasDowngraded?" (downgraded due to budget)":""}`,agentBoosterEligible:n===0,alternativeTiers:[],metadata:{timestamp:new Date,decisionTimeMs:d,fromCache:!1,correlationId:s},warnings:a.warnings}}async createFallbackDecision(e,t,r,s){let i=this.config.fallbackTier,c=this.getModelIdForTier(i),a={overall:50,codeComplexity:50,reasoningComplexity:50,scopeComplexity:50,confidence:.3,signals:{hasArchitectureScope:!1,hasSecurityScope:!1,requiresMultiStepReasoning:!1,requiresCrossDomainCoordination:!1,isMechanicalTransform:!1,requiresCreativity:!1,keywordMatches:{simple:[],moderate:[],complex:[],critical:[]}},recommendedTier:i,alternateTiers:[],explanation:`Fallback to Tier ${i} due to routing error`},n={allowed:!0,reason:"Fallback routing",requestedTier:i,approvedTier:i,wasDowngraded:!1,estimatedCostUsd:0,currentUsage:this.budgetEnforcer.getUsage(i),warnings:[]},o=Date.now()-t;return{tier:i,modelId:c,complexityAnalysis:a,budgetDecision:n,confidence:.3,rationale:`Fallback to Tier ${i} due to error: ${s.message}`,agentBoosterEligible:!1,alternativeTiers:[],metadata:{timestamp:new Date,decisionTimeMs:o,fromCache:!1,correlationId:r},warnings:[`Routing error: ${s.message}`,"Using fallback tier"]}}estimateCost(e,t){let r=[0,.001,.01,.05,.2],s=Math.max(1,t/1e3);return r[e]*s}getModelIdForTier(e){return this.config.tierModels[e]||`tier-${e}-default`}buildRationale(e,t,r){let s=[];return s.push(`Complexity: ${e.overall}/100`),s.push(`Tier ${r} selected`),t.wasDowngraded&&s.push(`Downgraded due to budget: ${t.reason}`),s.push(e.explanation),s.join(". ")}buildAlternatives(e,t){return e.alternateTiers.filter(r=>r!==t).map(r=>({tier:r,modelId:this.getModelIdForTier(r),reason:`Alternative tier ${r}`}))}recordMetrics(e,t){this.metrics.record({timestamp:e.metadata.timestamp,tier:e.tier,complexity:e.complexityAnalysis.overall,costUsd:e.budgetDecision.estimatedCostUsd,latencyMs:e.metadata.decisionTimeMs,wasDowngraded:e.budgetDecision.wasDowngraded,wasManualOverride:!1,agentBoosterEligible:e.agentBoosterEligible,success:t}),this.recordPersistentMetrics(e,t).catch(console.error)}async recordPersistentMetrics(e,t){if(this.persistentMetricsTracker)try{let r=`router-tier${e.tier}-${Date.now()}`;await this.persistentMetricsTracker.recordOutcome("router",r,t,e.metadata.decisionTimeMs,{subType:`tier-${e.tier}`,confidence:e.confidence,usedFallback:e.budgetDecision.wasDowngraded})}catch(r){console.warn("[ModelRouter] Failed to record persistent metrics:",r)}}};function $(u={},e,t){return new p(u,e,t)}async function I(u={},e){let{createAgentBoosterAdapter:t}=await import("./adapter-53WBPKXU.js"),r=await t({enabled:!0}),s=new p(u,r,e);return await s.loadPatternsFromLoader(),s}export{p as a,$ as b,I 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.9.4");process.exit(0)}
|
|
2
|
+
import{a as v}from"./chunk-A6ZBQCYB.js";import{h as U}from"./chunk-GSKZL36U.js";import{c as D,d as R,e as h,g as x}from"./chunk-JMBUIVVE.js";var f=class{config;trackers;globalCostTodayUsd=0;lastGlobalReset=new Date;constructor(e){this.config=e,this.trackers=new Map;for(let t of[0,1,2,3,4])this.trackers.set(t,{tier:t,costSpentTodayUsd:0,requestsThisHour:0,requestsToday:0,lastHourlyReset:new Date,lastDailyReset:new Date,requestHistory:[]})}async checkBudget(e,t){if(!this.config.enabled)return this.createAllowedDecision(e,e,t,!1,[]);this.autoReset();let r=this.config.tierBudgets[e];if(!r||!r.enabled)return this.createAllowedDecision(e,e,t,!1,["Tier budget not configured or disabled"]);let s=this.getUsage(e),i=[],c=this.config.maxDailyCostUsd-this.globalCostTodayUsd;if(this.globalCostTodayUsd+t>this.config.maxDailyCostUsd)return this.handleBudgetExceeded(e,t,s,"Global daily budget would be exceeded");if(this.globalCostTodayUsd+t>=this.config.maxDailyCostUsd*this.config.warningThreshold&&(i.push(`Approaching global daily budget limit: $${this.globalCostTodayUsd.toFixed(2)}/$${this.config.maxDailyCostUsd.toFixed(2)}`),this.config.onBudgetWarning==="downgrade"))return this.downgradeTier(e,t,s,i);let a=[{exceeded:s.costSpentTodayUsd+t>r.maxDailyCostUsd,message:`Tier ${e} daily cost limit would be exceeded: $${s.costSpentTodayUsd.toFixed(2)}/$${r.maxDailyCostUsd.toFixed(2)}`},{exceeded:s.requestsThisHour>=r.maxRequestsPerHour,message:`Tier ${e} hourly request limit reached: ${s.requestsThisHour}/${r.maxRequestsPerHour}`},{exceeded:s.requestsToday>=r.maxRequestsPerDay,message:`Tier ${e} daily request limit reached: ${s.requestsToday}/${r.maxRequestsPerDay}`},{exceeded:t>r.maxCostPerRequest,message:`Tier ${e} per-request cost limit would be exceeded: $${t.toFixed(4)}/$${r.maxCostPerRequest.toFixed(4)}`}];for(let n of a)if(n.exceeded)return this.handleBudgetExceeded(e,t,s,n.message);return s.budgetUtilization>=this.config.warningThreshold&&(i.push(`Tier ${e} at ${(s.budgetUtilization*100).toFixed(1)}% of daily budget`),this.config.onBudgetWarning==="downgrade")?this.downgradeTier(e,t,s,i):this.createAllowedDecision(e,e,t,!1,i)}async recordCost(e,t){if(!this.config.enabled)return;let r=this.trackers.get(e);r&&(this.autoReset(),r.costSpentTodayUsd+=t,r.requestsThisHour++,r.requestsToday++,this.globalCostTodayUsd+=t,r.requestHistory.push({timestamp:new Date,costUsd:t}),r.requestHistory.length>1e3&&(r.requestHistory=r.requestHistory.slice(-1e3)))}getUsage(e){this.autoReset();let t=this.trackers.get(e);if(!t)return this.createEmptyUsage(e);let r=this.config.tierBudgets[e];if(!r)return this.createEmptyUsage(e);let s=r.maxDailyCostUsd>0?t.costSpentTodayUsd/r.maxDailyCostUsd:0,i=t.costSpentTodayUsd>=r.maxDailyCostUsd||t.requestsThisHour>=r.maxRequestsPerHour||t.requestsToday>=r.maxRequestsPerDay,c=s>=this.config.warningThreshold,a=new Date,n=new Date(a);return n.setUTCHours(24,0,0,0),{tier:e,costSpentTodayUsd:t.costSpentTodayUsd,requestsThisHour:t.requestsThisHour,requestsToday:t.requestsToday,budgetUtilization:s,isExceeded:i,isNearLimit:c,resetTime:n,remainingBudgetUsd:Math.max(0,r.maxDailyCostUsd-t.costSpentTodayUsd),remainingRequestsThisHour:Math.max(0,r.maxRequestsPerHour-t.requestsThisHour),remainingRequestsToday:Math.max(0,r.maxRequestsPerDay-t.requestsToday)}}getAllUsage(){let e={};for(let t of[0,1,2,3,4])e[t]=this.getUsage(t);return e}reset(){let e=new Date;for(let t of this.trackers.values())t.costSpentTodayUsd=0,t.requestsThisHour=0,t.requestsToday=0,t.lastHourlyReset=e,t.lastDailyReset=e,t.requestHistory=[];this.globalCostTodayUsd=0,this.lastGlobalReset=e}handleBudgetExceeded(e,t,r,s){switch(this.config.onBudgetExceeded){case"error":throw new h(`Budget exceeded: ${s}`,e,r);case"downgrade":return this.downgradeTier(e,t,r,[s]);case"queue":throw new h(`Budget exceeded (queueing not yet implemented): ${s}`,e,r);default:throw new h(`Budget exceeded: ${s}`,e,r)}}downgradeTier(e,t,r,s){for(let i=e-1;i>=0;i--){let c=this.config.tierBudgets[i];if(!c||!c.enabled)continue;let a=this.getUsage(i);if(!a.isExceeded){let n=t*.5;if(a.costSpentTodayUsd+n<=c.maxDailyCostUsd)return this.createAllowedDecision(e,i,n,!0,[...s,`Downgraded from Tier ${e} to Tier ${i} due to budget constraints`])}}throw new h(`Budget exceeded and no lower tier available: ${s.join("; ")}`,e,r)}createAllowedDecision(e,t,r,s,i){let c=this.getUsage(t);return{allowed:!0,reason:s?`Budget enforced: downgraded to Tier ${t}`:"Budget check passed",requestedTier:e,approvedTier:t,wasDowngraded:s,estimatedCostUsd:r,currentUsage:c,warnings:i}}createEmptyUsage(e){let t=new Date,r=new Date(t);return r.setUTCHours(24,0,0,0),{tier:e,costSpentTodayUsd:0,requestsThisHour:0,requestsToday:0,budgetUtilization:0,isExceeded:!1,isNearLimit:!1,resetTime:r,remainingBudgetUsd:0,remainingRequestsThisHour:0,remainingRequestsToday:0}}autoReset(){let e=new Date;this.shouldResetDaily(this.lastGlobalReset,e)&&(this.globalCostTodayUsd=0,this.lastGlobalReset=e);for(let t of this.trackers.values())this.shouldResetHourly(t.lastHourlyReset,e)&&(t.requestsThisHour=0,t.lastHourlyReset=e),this.shouldResetDaily(t.lastDailyReset,e)&&(t.costSpentTodayUsd=0,t.requestsToday=0,t.requestHistory=[],t.lastDailyReset=e)}shouldResetHourly(e,t){return(t.getTime()-e.getTime())/36e5>=1}shouldResetDaily(e,t){return t.getUTCDate()!==e.getUTCDate()||t.getUTCMonth()!==e.getUTCMonth()||t.getUTCFullYear()!==e.getUTCFullYear()}getSessionCostSummary(){this.autoReset();let e=this.config.maxDailyCostUsd,t=0,r={},s={0:"AgentBooster",1:"Haiku",2:"Sonnet",3:"SonnetExtended",4:"Opus"};for(let[c,a]of this.trackers.entries()){let n=this.config.tierBudgets[c],o=s[c]??`Tier${c}`;t+=a.costSpentTodayUsd,r[o]={spent:a.costSpentTodayUsd,limit:n?.maxDailyCostUsd??0,requests:a.requestsToday}}let i=e>0?Math.round(t/e*100):0;return{totalSpentUsd:t,dailyLimitUsd:e,utilizationPercent:i,byTier:r}}};var w=class{cache=new Map;maxSize;ttlMs;enabled;constructor(e,t,r){this.enabled=e,this.maxSize=t,this.ttlMs=r}generateKey(e){return`${e.agentType||"unknown"}:${e.domain||"unknown"}:${e.task.slice(0,100)}`}get(e){if(!this.enabled)return null;let t=this.generateKey(e),r=this.cache.get(t);return r?Date.now()>r.expiresAt?(this.cache.delete(t),null):{...r.decision,metadata:{...r.decision.metadata,fromCache:!0,decisionTimeMs:0}}:null}set(e,t){if(!this.enabled)return;let r=this.generateKey(e);if(this.cache.size>=this.maxSize){let s=this.cache.keys().next().value;s&&this.cache.delete(s)}this.cache.set(r,{decision:t,expiresAt:Date.now()+this.ttlMs})}clear(){this.cache.clear()}getStats(){return{size:this.cache.size,hitRate:0}}},M=class{events=[];enabled;maxEvents=1e4;constructor(e){this.enabled=e}record(e){this.enabled&&(this.events.push(e),this.events.length>this.maxEvents&&(this.events=this.events.slice(-this.maxEvents)))}getMetrics(){if(this.events.length===0)return this.createEmptyMetrics();let e=new Date,t={};for(let o of[0,1,2,3,4]){let d=this.events.filter(l=>l.tier===o);if(d.length===0)continue;let T=d.filter(l=>l.success),m=d.filter(l=>!l.wasManualOverride),b=d.filter(l=>l.wasDowngraded),y=d.map(l=>l.latencyMs).sort((l,g)=>l-g),B=Math.floor(y.length*.95);t[o]={tier:o,selectionCount:d.length,autoRouteCount:m.length,manualOverrideCount:d.length-m.length,budgetDowngradeCount:b.length,successRate:T.length/d.length,avgComplexity:d.reduce((l,g)=>l+g.complexity,0)/d.length,totalCostUsd:d.reduce((l,g)=>l+g.costUsd,0),avgLatencyMs:d.reduce((l,g)=>l+g.latencyMs,0)/d.length,p95LatencyMs:y[B]||0,budgetUtilization:0}}let r=this.events.map(o=>o.latencyMs).sort((o,d)=>o-d),s=Math.floor(r.length*.95),i=Math.floor(r.length*.99),c=this.events.filter(o=>o.agentBoosterEligible).length,a=this.events.filter(o=>o.tier===0).length,n=this.events.filter(o=>o.tier===0&&o.success).length;return{byTier:t,totalDecisions:this.events.length,avgDecisionTimeMs:this.events.reduce((o,d)=>o+d.latencyMs,0)/this.events.length,p95DecisionTimeMs:r[s]||0,p99DecisionTimeMs:r[i]||0,fallbackRate:this.events.filter(o=>o.wasDowngraded).length/this.events.length,ruleMatchRate:this.events.filter(o=>!o.wasManualOverride).length/this.events.length,estimatedCostSavings:0,agentBoosterStats:{eligible:c,used:a,fallbackToLLM:Math.max(0,c-a),successRate:a>0?n/a:0},budgetStats:{totalSpentUsd:this.events.reduce((o,d)=>o+d.costUsd,0),budgetUtilization:0,downgradeCount:this.events.filter(o=>o.wasDowngraded).length,overrideCount:this.events.filter(o=>o.wasManualOverride).length},period:{start:this.events[0]?.timestamp||e,end:this.events[this.events.length-1]?.timestamp||e}}}reset(){this.events=[]}createEmptyMetrics(){let e=new Date;return{byTier:{},totalDecisions:0,avgDecisionTimeMs:0,p95DecisionTimeMs:0,p99DecisionTimeMs:0,fallbackRate:0,ruleMatchRate:0,estimatedCostSavings:0,agentBoosterStats:{eligible:0,used:0,fallbackToLLM:0,successRate:0},budgetStats:{totalSpentUsd:0,budgetUtilization:0,downgradeCount:0,overrideCount:0},period:{start:e,end:e}}}},p=class{config;complexityAnalyzer;budgetEnforcer;agentBoosterAdapter;cache;metrics;persistentMetricsTracker;patternsLoaded=!1;tierHierarchyFromPatterns=null;constructor(e={},t,r){this.config={...D,...e},this.agentBoosterAdapter=t,this.persistentMetricsTracker=r,this.complexityAnalyzer=U(this.config,t),this.budgetEnforcer=new f(this.config.budgetConfig),this.cache=new w(this.config.enableDecisionCache,1e3,this.config.decisionCacheTtlMs),this.metrics=new M(this.config.enableMetrics)}setPersistentMetricsTracker(e){this.persistentMetricsTracker=e}async loadPatternsFromLoader(){try{let t=await v().getTierHierarchy();if(t){this.tierHierarchyFromPatterns=t,this.patternsLoaded=!0,console.info("[ModelRouter] Loaded tier hierarchy from PatternLoader",{tiers:Object.keys(t)});return}console.debug("[ModelRouter] PatternLoader returned no tier hierarchy, using defaults")}catch(e){console.warn("[ModelRouter] Failed to load patterns from PatternLoader, using defaults",{error:e instanceof Error?e.message:"Unknown error"})}this.patternsLoaded=!1}getPatternsLoaded(){return this.patternsLoaded}getTierHierarchyFromPatterns(){return this.tierHierarchyFromPatterns}async route(e){let t=Date.now(),r=e.metadata?.correlationId;try{let s=this.cache.get(e);if(s)return s;let i=await Promise.race([this.routeInternal(e,t,r),new Promise((c,a)=>setTimeout(()=>a(new x("Routing decision timed out",this.config.maxDecisionTimeMs)),this.config.maxDecisionTimeMs))]);return this.cache.set(e,i),this.recordMetrics(i,!0),i}catch(s){let i=await this.createFallbackDecision(e,t,r,s instanceof Error?s:new Error("Unknown error"));return this.recordMetrics(i,!1),i}}getMetrics(){return this.metrics.getMetrics()}async getAgentBoosterHealth(){if(!this.agentBoosterAdapter)throw new R("Agent Booster adapter not available","AGENT_BOOSTER_UNAVAILABLE");return this.agentBoosterAdapter.getHealth()}resetMetrics(){this.metrics.reset()}async dispose(){this.cache.clear(),this.metrics.reset(),this.agentBoosterAdapter&&await this.agentBoosterAdapter.dispose()}async routeInternal(e,t,r){let s=[];if(e.manualTier!==void 0&&this.config.allowManualOverrides)return this.handleManualOverride(e,e.manualTier,t,r);let i=await this.complexityAnalyzer.analyze(e),c=i.recommendedTier,a=this.estimateCost(c,e.task.length),n=await this.budgetEnforcer.checkBudget(c,a),o=n.approvedTier;s.push(...n.warnings);let d=o===0&&i.signals.isMechanicalTransform,T=this.getModelIdForTier(o),m=this.buildRationale(i,n,o),b=this.buildAlternatives(i,o),y=Date.now()-t;return{tier:o,modelId:T,complexityAnalysis:i,budgetDecision:n,confidence:i.confidence,rationale:m,agentBoosterEligible:d,agentBoosterTransform:d?i.signals.detectedTransformType:void 0,alternativeTiers:b,metadata:{timestamp:new Date,decisionTimeMs:y,fromCache:!1,correlationId:r},warnings:s}}async handleManualOverride(e,t,r,s){let i=await this.complexityAnalyzer.analyze(e),c=this.estimateCost(t,e.task.length),a=await this.budgetEnforcer.checkBudget(t,c);!a.allowed&&e.isCritical&&this.config.budgetConfig.allowCriticalOverrides&&(a={...a,allowed:!0,reason:"Critical task override",warnings:[...a.warnings,"Budget exceeded but allowed due to critical task override"]});let n=a.approvedTier,o=this.getModelIdForTier(n),d=Date.now()-r;return{tier:n,modelId:o,complexityAnalysis:i,budgetDecision:a,confidence:1,rationale:`Manual override to Tier ${n}${a.wasDowngraded?" (downgraded due to budget)":""}`,agentBoosterEligible:n===0,alternativeTiers:[],metadata:{timestamp:new Date,decisionTimeMs:d,fromCache:!1,correlationId:s},warnings:a.warnings}}async createFallbackDecision(e,t,r,s){let i=this.config.fallbackTier,c=this.getModelIdForTier(i),a={overall:50,codeComplexity:50,reasoningComplexity:50,scopeComplexity:50,confidence:.3,signals:{hasArchitectureScope:!1,hasSecurityScope:!1,requiresMultiStepReasoning:!1,requiresCrossDomainCoordination:!1,isMechanicalTransform:!1,requiresCreativity:!1,keywordMatches:{simple:[],moderate:[],complex:[],critical:[]}},recommendedTier:i,alternateTiers:[],explanation:`Fallback to Tier ${i} due to routing error`},n={allowed:!0,reason:"Fallback routing",requestedTier:i,approvedTier:i,wasDowngraded:!1,estimatedCostUsd:0,currentUsage:this.budgetEnforcer.getUsage(i),warnings:[]},o=Date.now()-t;return{tier:i,modelId:c,complexityAnalysis:a,budgetDecision:n,confidence:.3,rationale:`Fallback to Tier ${i} due to error: ${s.message}`,agentBoosterEligible:!1,alternativeTiers:[],metadata:{timestamp:new Date,decisionTimeMs:o,fromCache:!1,correlationId:r},warnings:[`Routing error: ${s.message}`,"Using fallback tier"]}}estimateCost(e,t){let r=[0,.001,.01,.05,.2],s=Math.max(1,t/1e3);return r[e]*s}getModelIdForTier(e){return this.config.tierModels[e]||`tier-${e}-default`}buildRationale(e,t,r){let s=[];return s.push(`Complexity: ${e.overall}/100`),s.push(`Tier ${r} selected`),t.wasDowngraded&&s.push(`Downgraded due to budget: ${t.reason}`),s.push(e.explanation),s.join(". ")}buildAlternatives(e,t){return e.alternateTiers.filter(r=>r!==t).map(r=>({tier:r,modelId:this.getModelIdForTier(r),reason:`Alternative tier ${r}`}))}recordMetrics(e,t){this.metrics.record({timestamp:e.metadata.timestamp,tier:e.tier,complexity:e.complexityAnalysis.overall,costUsd:e.budgetDecision.estimatedCostUsd,latencyMs:e.metadata.decisionTimeMs,wasDowngraded:e.budgetDecision.wasDowngraded,wasManualOverride:!1,agentBoosterEligible:e.agentBoosterEligible,success:t}),this.recordPersistentMetrics(e,t).catch(console.error)}async recordPersistentMetrics(e,t){if(this.persistentMetricsTracker)try{let r=`router-tier${e.tier}-${Date.now()}`;await this.persistentMetricsTracker.recordOutcome("router",r,t,e.metadata.decisionTimeMs,{subType:`tier-${e.tier}`,confidence:e.confidence,usedFallback:e.budgetDecision.wasDowngraded})}catch(r){console.warn("[ModelRouter] Failed to record persistent metrics:",r)}}};function $(u={},e,t){return new p(u,e,t)}async function I(u={},e){let{createAgentBoosterAdapter:t}=await import("./adapter-5ODIX6ZG.js"),r=await t({enabled:!0}),s=new p(u,r,e);return await s.loadPatternsFromLoader(),s}export{p as a,$ as b,I 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.9.
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.4");process.exit(0)}
|
|
2
2
|
var u={0:{tier:0,name:"Agent Booster",description:"Mechanical code transforms via Rust/WASM",useCases:["var-to-const conversion","add-types","remove-console statements","promise-to-async","cjs-to-esm","func-to-arrow"],typicalLatencyMs:1,relativeCost:0,exampleModels:["agent-booster-wasm","agent-booster-typescript"],requiresNetwork:!1,complexityRange:[0,10]},1:{tier:1,name:"Haiku",description:"Fast, cost-effective for simple tasks",useCases:["Simple bug fixes","Code formatting","Documentation updates","Basic refactoring","Test generation (simple)"],typicalLatencyMs:500,relativeCost:1,exampleModels:["claude-3-5-haiku-20241022","gpt-4o-mini","gemini-flash"],requiresNetwork:!0,complexityRange:[10,35]},2:{tier:2,name:"Sonnet",description:"Balanced capability for complex reasoning",useCases:["Feature implementation","Complex refactoring","Security analysis","Performance optimization","Test generation (complex)"],typicalLatencyMs:3e3,relativeCost:2,exampleModels:["claude-sonnet-4-20250514","gpt-4o","gemini-pro"],requiresNetwork:!0,complexityRange:[35,70]},3:{tier:3,name:"Sonnet Extended",description:"Extended context for multi-step workflows",useCases:["Multi-file refactoring","Workflow orchestration","Cross-domain coordination","Large codebase analysis"],typicalLatencyMs:7e3,relativeCost:3,exampleModels:["claude-sonnet-4-20250514"],requiresNetwork:!0,complexityRange:[60,85]},4:{tier:4,name:"Opus",description:"Maximum capability for critical decisions",useCases:["Architecture design","Security audits","Complex algorithm design","Critical bug analysis","System-wide refactoring"],typicalLatencyMs:5e3,relativeCost:4,exampleModels:["claude-opus-4-5-20251101","gpt-4-turbo"],requiresNetwork:!0,complexityRange:[75,100]}},d={enabled:!0,tierBudgets:{0:{tier:0,maxCostPerRequest:0,maxRequestsPerHour:1e4,maxRequestsPerDay:1e5,maxDailyCostUsd:0,enabled:!0},1:{tier:1,maxCostPerRequest:.01,maxRequestsPerHour:100,maxRequestsPerDay:1e3,maxDailyCostUsd:5,enabled:!0},2:{tier:2,maxCostPerRequest:.1,maxRequestsPerHour:50,maxRequestsPerDay:500,maxDailyCostUsd:20,enabled:!0},3:{tier:3,maxCostPerRequest:.5,maxRequestsPerHour:20,maxRequestsPerDay:100,maxDailyCostUsd:30,enabled:!0},4:{tier:4,maxCostPerRequest:2,maxRequestsPerHour:10,maxRequestsPerDay:50,maxDailyCostUsd:50,enabled:!0}},maxDailyCostUsd:100,warningThreshold:.8,onBudgetExceeded:"downgrade",onBudgetWarning:"warn",allowCriticalOverrides:!0},y={budgetConfig:d,enableAgentBooster:!0,agentBoosterThreshold:.7,enableAutoRouting:!0,complexityThresholds:{0:10,1:35,2:70,3:85,4:100},allowManualOverrides:!0,enableDecisionCache:!0,decisionCacheTtlMs:300*1e3,enableMetrics:!0,maxDecisionTimeMs:10,fallbackTier:2,tierModels:{0:"agent-booster",1:"claude-3-5-haiku-20241022",2:"claude-sonnet-4-20250514",3:"claude-sonnet-4-20250514",4:"claude-opus-4-5-20251101"}},r=class extends Error{constructor(e,t,l){super(e);this.code=t;this.cause=l;this.name="ModelRouterError"}},a=class extends r{constructor(e,t,l){super(e,"BUDGET_EXCEEDED");this.tier=t;this.usage=l;this.name="BudgetExceededError"}},i=class extends r{constructor(o,e){super(o,"COMPLEXITY_ANALYSIS_ERROR",e),this.name="ComplexityAnalysisError"}},s=class extends r{constructor(e,t){super(e,"ROUTING_TIMEOUT");this.timeoutMs=t;this.name="RoutingTimeoutError"}};export{u as a,d as b,y as c,r as d,a as e,i as f,s as g};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{a as S}from"./chunk-XIBVVZGB.js";import{c as g}from"./chunk-JOVINE23.js";import{S as T,b as l}from"./chunk-DBE34QES.js";S();T();import{createRequire as B}from"module";var G=B(import.meta.url),d=class{validateTransfer(e,t){return{approved:!0}}};function R(){if(l().useCoherenceGate)try{let{CoherenceGate:o}=G("./coherence-gate.js");return new o}catch{}return new d}S();var x=g.create("transfer-verification"),A={maxSourceRegression:.05,minTargetImprovement:0,maxSourceConfidenceRegression:.1},b=class{config;constructor(e={}){this.config={...A,...e}}verifyTransfer(e){let t=e.sourcePerformanceAfter.successRate-e.sourcePerformanceBefore.successRate,r=e.targetPerformanceAfter.successRate-e.targetPerformanceBefore.successRate,n=e.sourcePerformanceAfter.avgConfidence-e.sourcePerformanceBefore.avgConfidence,a=e.targetPerformanceAfter.avgConfidence-e.targetPerformanceBefore.avgConfidence,s=t>=-this.config.maxSourceRegression&&n>=-this.config.maxSourceConfidenceRegression,c=r>=this.config.minTargetImprovement,u=s&&c,m;if(!u){let i=[];s||i.push(`source domain regressed: successRate delta=${t.toFixed(4)}, confidence delta=${n.toFixed(4)}`),c||i.push(`target domain did not improve: successRate delta=${r.toFixed(4)}`),m=i.join("; ")}return u?x.debug("Transfer verification passed",{transferId:e.transferId,sourceDelta:t,targetDelta:r}):x.warn("Transfer verification failed",{transferId:e.transferId,sourceDomain:e.sourceDomain,targetDomain:e.targetDomain,sourceDelta:t,targetDelta:r,failureReason:m}),{passed:u,sourceStable:s,targetImproved:c,sourceDelta:t,targetDelta:r,sourceConfidenceDelta:n,targetConfidenceDelta:a,failureReason:m}}getConfig(){return{...this.config}}};function M(o){return new b(o)}T();var p=class{alphas=new Map;betas=new Map;sample(e){let t=this.alphas.get(e)??1,r=this.betas.get(e)??1;return this.sampleBeta(t,r)}update(e,t){t?this.alphas.set(e,(this.alphas.get(e)??1)+1):this.betas.set(e,(this.betas.get(e)??1)+1)}getMean(e){let t=this.alphas.get(e)??1,r=this.betas.get(e)??1;return t/(t+r)}getObservationCount(e){let t=this.alphas.get(e)??1,r=this.betas.get(e)??1;return t-1+(r-1)}getAlpha(e){return this.alphas.get(e)??1}getBeta(e){return this.betas.get(e)??1}sampleBeta(e,t){let r=this.sampleGamma(e),n=this.sampleGamma(t);return r+n===0?.5:r/(r+n)}sampleGamma(e){if(e<1){let n=Math.random();return this.sampleGamma(e+1)*Math.pow(n,1/e)}let t=e-1/3,r=1/Math.sqrt(9*t);for(;;){let n,a;do n=this.standardNormal(),a=1+r*n;while(a<=0);a=a*a*a;let s=Math.random();if(s<1-.0331*n*n*n*n||Math.log(s)<.5*n*n+t*(1-a+Math.log(a)))return t*a}}standardNormal(){let e=Math.random(),t=Math.random();return Math.sqrt(-2*Math.log(e||1e-10))*Math.cos(2*Math.PI*t)}};var I={threshold:5,slack:.5,resetOnAlarm:!0,warmupSamples:20},h=class{config;states=new Map;constructor(e={}){this.config={...I,...e}}update(e,t){let r=this.getOrCreateState(e);if(r.samplesSinceReset++,r.mu===null)return r.warmupSum+=t,r.warmupCount++,r.warmupCount>=this.config.warmupSamples&&(r.mu=r.warmupSum/r.warmupCount),{driftDetected:!1,cumulativeSum:0,direction:"none",samplesSinceReset:r.samplesSinceReset};r.sPlus=Math.max(0,r.sPlus+(t-r.mu-this.config.slack)),r.sMinus=Math.max(0,r.sMinus+(-t+r.mu-this.config.slack));let n=Math.max(r.sPlus,r.sMinus),a=!1,s="none";r.sPlus>this.config.threshold?(a=!0,s="positive"):r.sMinus>this.config.threshold&&(a=!0,s="negative");let c={driftDetected:a,cumulativeSum:n,direction:s,samplesSinceReset:r.samplesSinceReset};return a&&this.config.resetOnAlarm&&(r.sPlus=0,r.sMinus=0,r.samplesSinceReset=0),c}reset(e){e?this.states.delete(e):this.states.clear()}getState(e){let t=this.states.get(e);if(!t)return{driftDetected:!1,cumulativeSum:0,direction:"none",samplesSinceReset:0};let r=Math.max(t.sPlus,t.sMinus),n="none";return t.sPlus>this.config.threshold?n="positive":t.sMinus>this.config.threshold&&(n="negative"),{driftDetected:t.sPlus>this.config.threshold||t.sMinus>this.config.threshold,cumulativeSum:r,direction:n,samplesSinceReset:t.samplesSinceReset}}getOrCreateState(e){let t=this.states.get(e);return t||(t={sPlus:0,sMinus:0,samplesSinceReset:0,warmupSum:0,warmupCount:0,mu:null},this.states.set(e,t)),t}};var w=g.create("domain-transfer"),V={minTransferProbability:.3,explorationWarmup:5,verification:{},maxHistorySize:1e3,useMetaLearningEnhancements:!0},y=class{constructor(e=100){this.decayThreshold=e}getDecayMultiplier(e){return e<=0?1:Math.pow(.5,e/this.decayThreshold)}applyDecay(e,t,r){return t+(e-t)*this.getDecayMultiplier(r)}},v=class{cusum;outcomes=[];windowSize;constructor(e=20){this.windowSize=e,this.cusum=new h({threshold:3,slack:.1,resetOnAlarm:!1,warmupSamples:Math.min(10,Math.floor(e/2))})}record(e){this.outcomes.push(e),this.outcomes.length>this.windowSize*2&&this.outcomes.splice(0,this.outcomes.length-this.windowSize*2);let t=this.getCurrentRate();this.cusum.update("learn",t)}isPlateaued(){return this.outcomes.length<this.windowSize?!1:!this.cusum.getState("learn").driftDetected}getCurrentRate(){if(this.outcomes.length===0)return 0;let e=this.outcomes.slice(-this.windowSize);return e.filter(Boolean).length/e.length}getOutcomeCount(){return this.outcomes.length}getCusumState(){return this.cusum.getState("learn")}},D=class{front=[];dominates(e,t){let r=e.successRate>=t.successRate&&e.speed>=t.speed&&e.confidence>=t.confidence,n=e.successRate>t.successRate||e.speed>t.speed||e.confidence>t.confidence;return r&&n}add(e){for(let t=this.front.length-1;t>=0;t--)this.dominates(e,this.front[t])&&this.front.splice(t,1);this.front.some(t=>this.dominates(t,e))||this.front.push(e)}getFront(){return[...this.front]}isNonDominated(e){return!this.front.some(t=>this.dominates(t,e))}},C=class{constructor(e=.2){this.bonusScale=e}triedPairs=new Set;markTried(e){this.triedPairs.add(e)}isTried(e){return this.triedPairs.has(e)}getBonus(e){return this.triedPairs.has(e)?0:this.bonusScale}apply(e,t){return Math.min(1,e+this.getBonus(t))}getTriedCount(){return this.triedPairs.size}},P=class{config;sampler;verifier;coherenceGate;transferHistory=[];affinityScores=new Map;performanceProvider=null;transferExecutor=null;nativeModule=null;decayingBeta;plateauDetector;paretoFront;curiosityBonus;constructor(e={}){this.config={...V,...e},this.sampler=new p,this.verifier=M(this.config.verification),this.coherenceGate=R(),this.decayingBeta=new y,this.plateauDetector=new v,this.paretoFront=new D,this.curiosityBonus=new C,this.tryLoadNativeModule()}evaluateTransfer(e,t){if(!this.isEnabled())return this.createRejectedCandidate(e,t);let r=this.makePairKey(e,t),n=this.sampler.sample(r),s=this.sampler.getObservationCount(r)<this.config.explorationWarmup,c=this.getAffinityScore(e,t);if(this.isMetaLearningEnabled()){let u=this.sampler.getMean(r),m=this.sampler.getAlpha(r)-1;n=this.decayingBeta.applyDecay(n,u,m),n=this.curiosityBonus.apply(n,r)}return{sourceDomain:e,targetDomain:t,sampledProbability:n,affinityScore:c,isExploration:s,pairKey:r}}executeTransfer(e){let t=`transfer-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,r=this.coherenceGate.validateTransfer({domain:e.sourceDomain},e.targetDomain);if(!r.approved)return w.info("Transfer blocked by coherence gate",{transferId:t,source:e.sourceDomain,target:e.targetDomain,reason:r.rejectionReason}),this.createBlockedResult(t,e,r);let n=this.getPerformanceSnapshot(e.sourceDomain),a=this.getPerformanceSnapshot(e.targetDomain),s=this.computeSqrtDampening(e),c=this.doTransfer(e.sourceDomain,e.targetDomain,s),u=this.getPerformanceSnapshot(e.sourceDomain),m=this.getPerformanceSnapshot(e.targetDomain),i=this.verifier.verifyTransfer({transferId:t,sourceDomain:e.sourceDomain,targetDomain:e.targetDomain,sourcePerformanceBefore:n,sourcePerformanceAfter:u,targetPerformanceBefore:a,targetPerformanceAfter:m}),f=c&&i.passed;if(this.sampler.update(e.pairKey,f),this.updateAffinityScore(e.pairKey,f),this.isMetaLearningEnabled()){this.plateauDetector.record(f),this.curiosityBonus.markTried(e.pairKey);let F=this.sampler.getMean(e.pairKey);this.paretoFront.add({pairKey:e.pairKey,successRate:F,speed:1/(1+s),confidence:this.getAffinityScore(e.sourceDomain,e.targetDomain)})}return this.addToHistory({transferId:t,sourceDomain:e.sourceDomain,targetDomain:e.targetDomain,success:f,sampledProbability:e.sampledProbability,dampeningFactor:s,sourceDelta:i.sourceDelta,targetDelta:i.targetDelta,timestamp:Date.now()}),w.info("Transfer completed",{transferId:t,source:e.sourceDomain,target:e.targetDomain,success:f,dampeningFactor:s.toFixed(4),sourceDelta:i.sourceDelta.toFixed(4),targetDelta:i.targetDelta.toFixed(4)}),{transferId:t,candidate:e,success:f,dampeningFactor:s,verification:i,coherenceResult:r,sourcePerformanceBefore:n,sourcePerformanceAfter:u,targetPerformanceBefore:a,targetPerformanceAfter:m,timestamp:Date.now()}}getAffinityScore(e,t){return this.affinityScores.get(this.makePairKey(e,t))??.5}getTransferHistory(){return[...this.transferHistory]}getExpectedSuccessRate(e,t){return this.sampler.getMean(this.makePairKey(e,t))}getObservationCount(e,t){return this.sampler.getObservationCount(this.makePairKey(e,t))}setPerformanceProvider(e){this.performanceProvider=e}setTransferExecutor(e){this.transferExecutor=e}getSampler(){return this.sampler}getCoherenceGate(){return this.coherenceGate}getDecayingBeta(){return this.decayingBeta}getPlateauDetector(){return this.plateauDetector}getParetoFront(){return this.paretoFront}getCuriosityBonus(){return this.curiosityBonus}isLearningPlateaued(){return this.plateauDetector.isPlateaued()}isEnabled(){return l().useCrossDomainTransfer===!0}isMetaLearningEnabled(){return this.config.useMetaLearningEnhancements===!0&&l().useMetaLearningEnhancements!==!1}makePairKey(e,t){return`${e}->${t}`}computeSqrtDampening(e){let t=this.sampler.getObservationCount(e.pairKey);return Math.sqrt(t/(t+this.config.explorationWarmup))}doTransfer(e,t,r){return this.transferExecutor?this.transferExecutor(e,t,r):!0}getPerformanceSnapshot(e){return this.performanceProvider?this.performanceProvider(e):{domain:e,successRate:.5,avgConfidence:.5,patternCount:0,timestamp:Date.now()}}updateAffinityScore(e,t){let r=this.affinityScores.get(e)??.5;this.affinityScores.set(e,.2*(t?1:0)+.8*r)}addToHistory(e){for(this.transferHistory.push(e);this.transferHistory.length>this.config.maxHistorySize;)this.transferHistory.shift()}createBlockedResult(e,t,r){let n={domain:"",successRate:0,avgConfidence:0,patternCount:0,timestamp:Date.now()};return{transferId:e,candidate:t,success:!1,dampeningFactor:0,verification:{passed:!1,sourceStable:!1,targetImproved:!1,sourceDelta:0,targetDelta:0,sourceConfidenceDelta:0,targetConfidenceDelta:0,failureReason:`Coherence gate rejected: ${r.rejectionReason??"unknown"}`},coherenceResult:r,sourcePerformanceBefore:{...n,domain:t.sourceDomain},sourcePerformanceAfter:{...n,domain:t.sourceDomain},targetPerformanceBefore:{...n,domain:t.targetDomain},targetPerformanceAfter:{...n,domain:t.targetDomain},timestamp:Date.now()}}createRejectedCandidate(e,t){return{sourceDomain:e,targetDomain:t,sampledProbability:0,affinityScore:0,isExploration:!1,pairKey:this.makePairKey(e,t)}}tryLoadNativeModule(){this.nativeModule=null}};function J(o){return new P(o)}export{p as a,h as b,V as c,y as d,v as e,D as f,C as g,P as h,J as i};
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.4");process.exit(0)}
|
|
2
|
+
import{a as S}from"./chunk-MDFXPCBO.js";import{c as g}from"./chunk-RPYUKEAH.js";import{S as T,b as l}from"./chunk-MN2MYLVW.js";S();T();import{createRequire as B}from"module";var G=B(import.meta.url),d=class{validateTransfer(e,t){return{approved:!0}}};function R(){if(l().useCoherenceGate)try{let{CoherenceGate:o}=G("./coherence-gate.js");return new o}catch{}return new d}S();var x=g.create("transfer-verification"),A={maxSourceRegression:.05,minTargetImprovement:0,maxSourceConfidenceRegression:.1},b=class{config;constructor(e={}){this.config={...A,...e}}verifyTransfer(e){let t=e.sourcePerformanceAfter.successRate-e.sourcePerformanceBefore.successRate,r=e.targetPerformanceAfter.successRate-e.targetPerformanceBefore.successRate,n=e.sourcePerformanceAfter.avgConfidence-e.sourcePerformanceBefore.avgConfidence,a=e.targetPerformanceAfter.avgConfidence-e.targetPerformanceBefore.avgConfidence,s=t>=-this.config.maxSourceRegression&&n>=-this.config.maxSourceConfidenceRegression,c=r>=this.config.minTargetImprovement,u=s&&c,m;if(!u){let i=[];s||i.push(`source domain regressed: successRate delta=${t.toFixed(4)}, confidence delta=${n.toFixed(4)}`),c||i.push(`target domain did not improve: successRate delta=${r.toFixed(4)}`),m=i.join("; ")}return u?x.debug("Transfer verification passed",{transferId:e.transferId,sourceDelta:t,targetDelta:r}):x.warn("Transfer verification failed",{transferId:e.transferId,sourceDomain:e.sourceDomain,targetDomain:e.targetDomain,sourceDelta:t,targetDelta:r,failureReason:m}),{passed:u,sourceStable:s,targetImproved:c,sourceDelta:t,targetDelta:r,sourceConfidenceDelta:n,targetConfidenceDelta:a,failureReason:m}}getConfig(){return{...this.config}}};function M(o){return new b(o)}T();var p=class{alphas=new Map;betas=new Map;sample(e){let t=this.alphas.get(e)??1,r=this.betas.get(e)??1;return this.sampleBeta(t,r)}update(e,t){t?this.alphas.set(e,(this.alphas.get(e)??1)+1):this.betas.set(e,(this.betas.get(e)??1)+1)}getMean(e){let t=this.alphas.get(e)??1,r=this.betas.get(e)??1;return t/(t+r)}getObservationCount(e){let t=this.alphas.get(e)??1,r=this.betas.get(e)??1;return t-1+(r-1)}getAlpha(e){return this.alphas.get(e)??1}getBeta(e){return this.betas.get(e)??1}sampleBeta(e,t){let r=this.sampleGamma(e),n=this.sampleGamma(t);return r+n===0?.5:r/(r+n)}sampleGamma(e){if(e<1){let n=Math.random();return this.sampleGamma(e+1)*Math.pow(n,1/e)}let t=e-1/3,r=1/Math.sqrt(9*t);for(;;){let n,a;do n=this.standardNormal(),a=1+r*n;while(a<=0);a=a*a*a;let s=Math.random();if(s<1-.0331*n*n*n*n||Math.log(s)<.5*n*n+t*(1-a+Math.log(a)))return t*a}}standardNormal(){let e=Math.random(),t=Math.random();return Math.sqrt(-2*Math.log(e||1e-10))*Math.cos(2*Math.PI*t)}};var I={threshold:5,slack:.5,resetOnAlarm:!0,warmupSamples:20},h=class{config;states=new Map;constructor(e={}){this.config={...I,...e}}update(e,t){let r=this.getOrCreateState(e);if(r.samplesSinceReset++,r.mu===null)return r.warmupSum+=t,r.warmupCount++,r.warmupCount>=this.config.warmupSamples&&(r.mu=r.warmupSum/r.warmupCount),{driftDetected:!1,cumulativeSum:0,direction:"none",samplesSinceReset:r.samplesSinceReset};r.sPlus=Math.max(0,r.sPlus+(t-r.mu-this.config.slack)),r.sMinus=Math.max(0,r.sMinus+(-t+r.mu-this.config.slack));let n=Math.max(r.sPlus,r.sMinus),a=!1,s="none";r.sPlus>this.config.threshold?(a=!0,s="positive"):r.sMinus>this.config.threshold&&(a=!0,s="negative");let c={driftDetected:a,cumulativeSum:n,direction:s,samplesSinceReset:r.samplesSinceReset};return a&&this.config.resetOnAlarm&&(r.sPlus=0,r.sMinus=0,r.samplesSinceReset=0),c}reset(e){e?this.states.delete(e):this.states.clear()}getState(e){let t=this.states.get(e);if(!t)return{driftDetected:!1,cumulativeSum:0,direction:"none",samplesSinceReset:0};let r=Math.max(t.sPlus,t.sMinus),n="none";return t.sPlus>this.config.threshold?n="positive":t.sMinus>this.config.threshold&&(n="negative"),{driftDetected:t.sPlus>this.config.threshold||t.sMinus>this.config.threshold,cumulativeSum:r,direction:n,samplesSinceReset:t.samplesSinceReset}}getOrCreateState(e){let t=this.states.get(e);return t||(t={sPlus:0,sMinus:0,samplesSinceReset:0,warmupSum:0,warmupCount:0,mu:null},this.states.set(e,t)),t}};var w=g.create("domain-transfer"),V={minTransferProbability:.3,explorationWarmup:5,verification:{},maxHistorySize:1e3,useMetaLearningEnhancements:!0},y=class{constructor(e=100){this.decayThreshold=e}getDecayMultiplier(e){return e<=0?1:Math.pow(.5,e/this.decayThreshold)}applyDecay(e,t,r){return t+(e-t)*this.getDecayMultiplier(r)}},v=class{cusum;outcomes=[];windowSize;constructor(e=20){this.windowSize=e,this.cusum=new h({threshold:3,slack:.1,resetOnAlarm:!1,warmupSamples:Math.min(10,Math.floor(e/2))})}record(e){this.outcomes.push(e),this.outcomes.length>this.windowSize*2&&this.outcomes.splice(0,this.outcomes.length-this.windowSize*2);let t=this.getCurrentRate();this.cusum.update("learn",t)}isPlateaued(){return this.outcomes.length<this.windowSize?!1:!this.cusum.getState("learn").driftDetected}getCurrentRate(){if(this.outcomes.length===0)return 0;let e=this.outcomes.slice(-this.windowSize);return e.filter(Boolean).length/e.length}getOutcomeCount(){return this.outcomes.length}getCusumState(){return this.cusum.getState("learn")}},D=class{front=[];dominates(e,t){let r=e.successRate>=t.successRate&&e.speed>=t.speed&&e.confidence>=t.confidence,n=e.successRate>t.successRate||e.speed>t.speed||e.confidence>t.confidence;return r&&n}add(e){for(let t=this.front.length-1;t>=0;t--)this.dominates(e,this.front[t])&&this.front.splice(t,1);this.front.some(t=>this.dominates(t,e))||this.front.push(e)}getFront(){return[...this.front]}isNonDominated(e){return!this.front.some(t=>this.dominates(t,e))}},C=class{constructor(e=.2){this.bonusScale=e}triedPairs=new Set;markTried(e){this.triedPairs.add(e)}isTried(e){return this.triedPairs.has(e)}getBonus(e){return this.triedPairs.has(e)?0:this.bonusScale}apply(e,t){return Math.min(1,e+this.getBonus(t))}getTriedCount(){return this.triedPairs.size}},P=class{config;sampler;verifier;coherenceGate;transferHistory=[];affinityScores=new Map;performanceProvider=null;transferExecutor=null;nativeModule=null;decayingBeta;plateauDetector;paretoFront;curiosityBonus;constructor(e={}){this.config={...V,...e},this.sampler=new p,this.verifier=M(this.config.verification),this.coherenceGate=R(),this.decayingBeta=new y,this.plateauDetector=new v,this.paretoFront=new D,this.curiosityBonus=new C,this.tryLoadNativeModule()}evaluateTransfer(e,t){if(!this.isEnabled())return this.createRejectedCandidate(e,t);let r=this.makePairKey(e,t),n=this.sampler.sample(r),s=this.sampler.getObservationCount(r)<this.config.explorationWarmup,c=this.getAffinityScore(e,t);if(this.isMetaLearningEnabled()){let u=this.sampler.getMean(r),m=this.sampler.getAlpha(r)-1;n=this.decayingBeta.applyDecay(n,u,m),n=this.curiosityBonus.apply(n,r)}return{sourceDomain:e,targetDomain:t,sampledProbability:n,affinityScore:c,isExploration:s,pairKey:r}}executeTransfer(e){let t=`transfer-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,r=this.coherenceGate.validateTransfer({domain:e.sourceDomain},e.targetDomain);if(!r.approved)return w.info("Transfer blocked by coherence gate",{transferId:t,source:e.sourceDomain,target:e.targetDomain,reason:r.rejectionReason}),this.createBlockedResult(t,e,r);let n=this.getPerformanceSnapshot(e.sourceDomain),a=this.getPerformanceSnapshot(e.targetDomain),s=this.computeSqrtDampening(e),c=this.doTransfer(e.sourceDomain,e.targetDomain,s),u=this.getPerformanceSnapshot(e.sourceDomain),m=this.getPerformanceSnapshot(e.targetDomain),i=this.verifier.verifyTransfer({transferId:t,sourceDomain:e.sourceDomain,targetDomain:e.targetDomain,sourcePerformanceBefore:n,sourcePerformanceAfter:u,targetPerformanceBefore:a,targetPerformanceAfter:m}),f=c&&i.passed;if(this.sampler.update(e.pairKey,f),this.updateAffinityScore(e.pairKey,f),this.isMetaLearningEnabled()){this.plateauDetector.record(f),this.curiosityBonus.markTried(e.pairKey);let F=this.sampler.getMean(e.pairKey);this.paretoFront.add({pairKey:e.pairKey,successRate:F,speed:1/(1+s),confidence:this.getAffinityScore(e.sourceDomain,e.targetDomain)})}return this.addToHistory({transferId:t,sourceDomain:e.sourceDomain,targetDomain:e.targetDomain,success:f,sampledProbability:e.sampledProbability,dampeningFactor:s,sourceDelta:i.sourceDelta,targetDelta:i.targetDelta,timestamp:Date.now()}),w.info("Transfer completed",{transferId:t,source:e.sourceDomain,target:e.targetDomain,success:f,dampeningFactor:s.toFixed(4),sourceDelta:i.sourceDelta.toFixed(4),targetDelta:i.targetDelta.toFixed(4)}),{transferId:t,candidate:e,success:f,dampeningFactor:s,verification:i,coherenceResult:r,sourcePerformanceBefore:n,sourcePerformanceAfter:u,targetPerformanceBefore:a,targetPerformanceAfter:m,timestamp:Date.now()}}getAffinityScore(e,t){return this.affinityScores.get(this.makePairKey(e,t))??.5}getTransferHistory(){return[...this.transferHistory]}getExpectedSuccessRate(e,t){return this.sampler.getMean(this.makePairKey(e,t))}getObservationCount(e,t){return this.sampler.getObservationCount(this.makePairKey(e,t))}setPerformanceProvider(e){this.performanceProvider=e}setTransferExecutor(e){this.transferExecutor=e}getSampler(){return this.sampler}getCoherenceGate(){return this.coherenceGate}getDecayingBeta(){return this.decayingBeta}getPlateauDetector(){return this.plateauDetector}getParetoFront(){return this.paretoFront}getCuriosityBonus(){return this.curiosityBonus}isLearningPlateaued(){return this.plateauDetector.isPlateaued()}isEnabled(){return l().useCrossDomainTransfer===!0}isMetaLearningEnabled(){return this.config.useMetaLearningEnhancements===!0&&l().useMetaLearningEnhancements!==!1}makePairKey(e,t){return`${e}->${t}`}computeSqrtDampening(e){let t=this.sampler.getObservationCount(e.pairKey);return Math.sqrt(t/(t+this.config.explorationWarmup))}doTransfer(e,t,r){return this.transferExecutor?this.transferExecutor(e,t,r):!0}getPerformanceSnapshot(e){return this.performanceProvider?this.performanceProvider(e):{domain:e,successRate:.5,avgConfidence:.5,patternCount:0,timestamp:Date.now()}}updateAffinityScore(e,t){let r=this.affinityScores.get(e)??.5;this.affinityScores.set(e,.2*(t?1:0)+.8*r)}addToHistory(e){for(this.transferHistory.push(e);this.transferHistory.length>this.config.maxHistorySize;)this.transferHistory.shift()}createBlockedResult(e,t,r){let n={domain:"",successRate:0,avgConfidence:0,patternCount:0,timestamp:Date.now()};return{transferId:e,candidate:t,success:!1,dampeningFactor:0,verification:{passed:!1,sourceStable:!1,targetImproved:!1,sourceDelta:0,targetDelta:0,sourceConfidenceDelta:0,targetConfidenceDelta:0,failureReason:`Coherence gate rejected: ${r.rejectionReason??"unknown"}`},coherenceResult:r,sourcePerformanceBefore:{...n,domain:t.sourceDomain},sourcePerformanceAfter:{...n,domain:t.sourceDomain},targetPerformanceBefore:{...n,domain:t.targetDomain},targetPerformanceAfter:{...n,domain:t.targetDomain},timestamp:Date.now()}}createRejectedCandidate(e,t){return{sourceDomain:e,targetDomain:t,sampledProbability:0,affinityScore:0,isExploration:!1,pairKey:this.makePairKey(e,t)}}tryLoadNativeModule(){this.nativeModule=null}};function J(o){return new P(o)}export{p as a,h as b,V as c,y as d,v as e,D as f,C as g,P as h,J as i};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{c 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.9.4");process.exit(0)}
|
|
2
|
+
import{c as T}from"./chunk-C2HGOUEB.js";var S,E,t,N,_=T(()=>{"use strict";S={MMAP_SIZE_BYTES:67108864,CACHE_SIZE_KB:-32e3,BUSY_TIMEOUT_MS:5e3,DEFAULT_VECTOR_DIMENSIONS:384,DEFAULT_SEARCH_LIMIT:100,CLEANUP_INTERVAL_MS:6e4,TTL_MULTIPLIER_MS:1e3},E={M_CONNECTIONS:16,EF_CONSTRUCTION:200,EF_SEARCH:100,DEFAULT_K_NEIGHBORS:10,COVERAGE_VECTOR_DIMENSION:384},t={MAX_CONCURRENT_AGENTS:15,DEFAULT_AGENT_TTL_MS:36e5,DEFAULT_AGENT_TIMEOUT_MS:12e4,MAX_POOL_SIZE:10},N={MAX_HISTORY_SIZE:1e4}});export{S as a,E as b,t as c,N as d,_ as e};
|
|
@@ -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.9.
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.4");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.9.
|
|
2
|
-
import{a as n}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.4");process.exit(0)}
|
|
2
|
+
import{a as n}from"./chunk-C567IO5M.js";import{a as o}from"./chunk-RS7ZGWHV.js";import{a,e as c}from"./chunk-KELYPHMV.js";c();var M=a.CLEANUP_INTERVAL_MS,y=".agentic-qe/memory.db";async function d(r,t=!0){let e;switch(r.type){case"memory":e=new o;break;case"sqlite":e=new n({sqlite:r.sqlite,enableFallback:!0});break;case"agentdb":e=new n({sqlite:{path:r.agentdb?.path??y},enableFallback:!0});break;case"hybrid":e=new n(r.hybrid);break;default:throw new Error(`Unknown memory backend type: ${r.type}`)}return t&&await e.initialize(),{backend:e,type:r.type,initialized:t}}async function u(r=!0){let t=process.env.AQE_MEMORY_BACKEND??"memory",e=process.env.AQE_MEMORY_PATH??".agentic-qe",i={type:t,sqlite:{path:`${e}/memory.db`,walMode:!0},agentdb:{path:`${e}/memory.db`},hybrid:{enableFallback:!0,sqlite:{path:`${e}/memory.db`}}};return d(i,r)}export{d as a,u as b};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{k as K,o as ot}from"./chunk-GK72GUHA.js";import{a as rt}from"./chunk-XIBVVZGB.js";import{c as U}from"./chunk-JOVINE23.js";import{a as j,c as et}from"./chunk-SDTVHR63.js";import{a as G,d as at}from"./chunk-34U7JDCN.js";import{a as nt,b as it}from"./chunk-727BDQ3K.js";import{c as H,e as V,g as w}from"./chunk-YXCU4CJX.js";var Z={};V(Z,{DotProductAttention:()=>yt,FlashAttention:()=>ft,HyperbolicAttention:()=>bt,LinearAttention:()=>vt,MoEAttention:()=>Et,MultiHeadAttention:()=>At,RuvectorLayer:()=>ut,SonaEngine:()=>P,TensorCompress:()=>mt,default:()=>ct,differentiableSearch:()=>ht,getCompressionLevel:()=>pt,hierarchicalForward:()=>dt,init:()=>gt,pipeline:()=>Ft});import{createRequire as st}from"module";var lt,$,ct,ut,mt,ht,dt,pt,gt,ft,yt,At,bt,vt,Et,P,Ft,k=H(()=>{lt=st(import.meta.url),$=lt("@ruvector/sona"),ct=$,{RuvectorLayer:ut,TensorCompress:mt,differentiableSearch:ht,hierarchicalForward:dt,getCompressionLevel:pt,init:gt,FlashAttention:ft,DotProductAttention:yt,MultiHeadAttention:At,HyperbolicAttention:bt,LinearAttention:vt,MoEAttention:Et,SonaEngine:P,pipeline:Ft}=$||{}});var N={};V(N,{DotProductAttention:()=>It,FlashAttention:()=>zt,HyperbolicAttention:()=>_t,LinearAttention:()=>Ht,MoEAttention:()=>Vt,MultiHeadAttention:()=>qt,RuvectorLayer:()=>Qt,SonaEngine:()=>jt,TensorCompress:()=>Nt,default:()=>xt,differentiableSearch:()=>Ot,getCompressionLevel:()=>Wt,hierarchicalForward:()=>Dt,init:()=>Bt,pipeline:()=>Ut});import{createRequire as kt}from"module";var Rt,X,xt,Qt,Nt,Ot,Dt,Wt,Bt,zt,It,qt,_t,Ht,Vt,jt,Ut,O=H(()=>{Rt=kt(import.meta.url),X=Rt("@ruvector/attention"),xt=X,{RuvectorLayer:Qt,TensorCompress:Nt,differentiableSearch:Ot,hierarchicalForward:Dt,getCompressionLevel:Wt,init:Bt,FlashAttention:zt,DotProductAttention:It,MultiHeadAttention:qt,HyperbolicAttention:_t,LinearAttention:Ht,MoEAttention:Vt,SonaEngine:jt,pipeline:Ut}=X||{}});k();at();import{randomUUID as Ct}from"crypto";rt();import{createRequire as wt}from"module";var f=U.create("sona-three-loop"),S=wt(import.meta.url),M=null,J=!1;function St(){if(J)return M;J=!0;try{let l=S("@ruvector/learning-wasm"),t=S("fs"),e=S("path"),r=e.join(e.dirname(S.resolve("@ruvector/learning-wasm")),"ruvector_learning_wasm_bg.wasm");l.initSync({module:t.readFileSync(r)}),M=l,f.info("WASM MicroLoRA loaded from @ruvector/learning-wasm (6.4x faster than TS)")}catch{M=null,f.debug("@ruvector/learning-wasm not available, using TypeScript MicroLoRA")}return M}var Mt={dimension:384,microLoraLr:.001,consolidationInterval:100,ewcLambda:1e3,taskBoundaryZScoreThreshold:2.5,fisherDecay:.9,fisherSampleSize:200,importanceThreshold:.01},R=class{adaptationVector;baseWeights;lr;adaptationCount=0;constructor(t,e=.001){this.adaptationVector=new Float32Array(t),this.baseWeights=new Float32Array(t),this.lr=e}adapt(t){let e=this.baseWeights.length,r=new Float32Array(e),a=Math.min(t.length,e);for(let n=0;n<e;n++){let o=n<a?t[n]:0;r[n]=this.baseWeights[n]+this.adaptationVector[n]+this.lr*o}for(let n=0;n<a;n++)this.adaptationVector[n]+=this.lr*t[n];return this.adaptationCount++,r}consolidate(){let t=this.adaptationCount,e=this.baseWeights.length;for(let r=0;r<e;r++)this.baseWeights[r]+=this.adaptationVector[r],this.adaptationVector[r]=0;return this.adaptationCount=0,t}getAdaptationCount(){return this.adaptationCount}getEffectiveWeights(){let t=this.baseWeights.length,e=new Float32Array(t);for(let r=0;r<t;r++)e[r]=this.baseWeights[r]+this.adaptationVector[r];return e}getAdaptationMagnitude(){let t=0;for(let e=0;e<this.adaptationVector.length;e++)t+=this.adaptationVector[e]*this.adaptationVector[e];return Math.sqrt(t)}resetAdaptation(){this.adaptationVector.fill(0),this.adaptationCount=0}},x=class{fisherMatrix;optimalParams;lambda;fisherDecay;zScoreThreshold;importanceThreshold;gradientHistory=[];gradientMean=0;gradientVariance=0;taskBoundaryCount=0;consolidationCount=0;constructor(t,e=1e3,r=.9,a=2.5,n=.01){this.fisherMatrix=new Float32Array(t),this.optimalParams=new Float32Array(t),this.lambda=e,this.fisherDecay=r,this.zScoreThreshold=a,this.importanceThreshold=n}detectTaskBoundary(t){let e=0;for(let i=0;i<t.length;i++)e+=t[i]*t[i];if(e=Math.sqrt(e),this.gradientHistory.length<5)return this.gradientHistory.push(e),this.updateGradientStats(),!1;let r=Math.sqrt(this.gradientVariance),a=0,n=Math.abs(e-this.gradientMean);return r>1e-10?a=n/r:n>1e-10&&this.gradientMean>1e-10&&(a=n/(this.gradientMean*.01+1e-10)),this.gradientHistory.push(e),this.gradientHistory.length>100&&this.gradientHistory.shift(),this.updateGradientStats(),a>this.zScoreThreshold?(this.taskBoundaryCount++,!0):!1}computeLoss(t){let e=0,r=Math.min(t.length,this.fisherMatrix.length,this.optimalParams.length);for(let a=0;a<r;a++){let n=t[a]-this.optimalParams[a];e+=this.fisherMatrix[a]*n*n}return this.lambda/2*e}updateFisher(t,e){if(t.length===0)return;let r=this.fisherMatrix.length,a=new Float32Array(r);for(let s of t){let u=Math.min(s.length,r);for(let c=0;c<u;c++)a[c]+=s[c]*s[c]}let n=t.length;for(let s=0;s<r;s++)a[s]/=n;let o=this.fisherDecay;for(let s=0;s<r;s++)this.fisherMatrix[s]=o*this.fisherMatrix[s]+(1-o)*a[s];let i=Math.min(e.length,r);for(let s=0;s<i;s++)this.optimalParams[s]=e[s];this.consolidationCount++}getMetrics(){let t=this.fisherMatrix.length,e=0,r=0,a=0;for(let n=0;n<t;n++)e+=this.fisherMatrix[n],this.fisherMatrix[n]>r&&(r=this.fisherMatrix[n]),this.fisherMatrix[n]>this.importanceThreshold&&a++;return{regularizationLoss:0,taskBoundariesDetected:this.taskBoundaryCount,fisherTrace:e,avgFisherImportance:t>0?e/t:0,maxFisherImportance:r,protectedParams:a,consolidationCycles:this.consolidationCount,lambda:this.lambda}}getTaskBoundaryCount(){return this.taskBoundaryCount}getFisherDiagonal(){return new Float32Array(this.fisherMatrix)}getOptimalParams(){return new Float32Array(this.optimalParams)}loadFisher(t,e){let r=this.fisherMatrix.length,a=Math.min(t.length,r),n=Math.min(e.length,r);for(let o=0;o<a;o++)this.fisherMatrix[o]=t[o];for(let o=0;o<n;o++)this.optimalParams[o]=e[o]}updateGradientStats(){let t=this.gradientHistory.length;if(t===0)return;let e=0;for(let a of this.gradientHistory)e+=a;e/=t;let r=0;for(let a of this.gradientHistory){let n=a-e;r+=n*n}r=t>1?r/(t-1):0,this.gradientMean=e,this.gradientVariance=r}},C=class{config;microLora;ewc;nativeEngine;wasmLora=null;requestCount=0;lastConsolidationRequest=0;peerStates=new Map;gradientBuffer=[];lastFeatures=null;constructor(t={},e){this.config={...Mt,...t},this.nativeEngine=e??null,this.microLora=new R(this.config.dimension,this.config.microLoraLr),this.ewc=new x(this.config.dimension,this.config.ewcLambda,this.config.fisherDecay,this.config.taskBoundaryZScoreThreshold,this.config.importanceThreshold);let r=St();if(r)try{this.wasmLora=new r.WasmMicroLoRA(this.config.dimension,1,this.config.microLoraLr),f.info("SONA Three-Loop using WASM MicroLoRA (0.07us/adapt)")}catch(a){f.debug("WASM MicroLoRA creation failed, falling back",{error:String(a)}),this.wasmLora=null}!this.wasmLora&&this.nativeEngine&&f.info("SONA Three-Loop using native @ruvector/sona engine for MicroLoRA delegation")}instantAdapt(t){let e=performance.now(),r;if(this.wasmLora)try{let o=new Float32Array(t),i=this.wasmLora.adapt(o);i&&i.length>0?(r=i,this.microLora.adapt(t)):r=this.microLora.adapt(t)}catch{r=this.microLora.adapt(t)}else if(this.nativeEngine)try{let o=this.nativeEngine.applyMicroLora(t);r=new Float32Array(o),this.microLora.adapt(t)}catch{r=this.microLora.adapt(t)}else r=this.microLora.adapt(t);let a=this.microLora.getAdaptationMagnitude();this.requestCount++,this.lastFeatures=[...t];let n=(performance.now()-e)*1e3;return{adaptedWeights:r,latencyUs:n,applied:!0,magnitude:a,requestIndex:this.requestCount}}recordOutcome(t,e){if(this.lastFeatures===null){f.warn("recordOutcome called without a preceding instantAdapt()");return}let r=this.lastFeatures.length,a=new Float32Array(r);for(let n=0;n<r;n++)a[n]=t*this.lastFeatures[n];this.gradientBuffer.push(a),this.gradientBuffer.length>this.config.fisherSampleSize&&this.gradientBuffer.shift(),this.lastFeatures=null}backgroundConsolidate(){let t=performance.now();if(this.nativeEngine)try{this.nativeEngine.forceLearn(),this.nativeEngine.tick()}catch(i){f.warn("Native SONA background learning failed, continuing with TypeScript",{error:String(i)})}let e=this.ewc.computeLoss(this.microLora.getEffectiveWeights()),r=!1;if(this.gradientBuffer.length>0){let i=this.gradientBuffer[this.gradientBuffer.length-1];r=this.ewc.detectTaskBoundary(i)}if(r&&this.gradientBuffer.length>0&&(this.ewc.updateFisher(this.gradientBuffer,this.microLora.getEffectiveWeights()),f.info("Task boundary detected, Fisher updated",{boundaries:this.ewc.getTaskBoundaryCount(),requestCount:this.requestCount})),this.gradientBuffer.length>1){let i=!1,s=this.gradientBuffer[0];for(let u=1;u<this.gradientBuffer.length&&!i;u++)for(let c=0;c<s.length;c++)if(Math.abs(this.gradientBuffer[u][c]-s[c])>1e-8){i=!0;break}i||f.warn("All gradient samples identical \u2014 Fisher estimate may be poor. Ensure recordOutcome() is called with diverse rewards.")}let a=this.microLora.consolidate();this.applyEWCRegularization();let n=this.ewc.computeLoss(this.microLora.getEffectiveWeights());this.lastConsolidationRequest=this.requestCount,this.gradientBuffer=[];let o=performance.now()-t;return{consolidated:a>0||r,adaptationsMerged:a,ewcLossBefore:e,ewcLossAfter:n,taskBoundaryDetected:r,durationMs:o}}shouldConsolidate(){return this.requestCount-this.lastConsolidationRequest>=this.config.consolidationInterval}syncWithPeers(t){if(t.length===0)return;for(let i of t)this.peerStates.set(i.peerId,i);let e=this.config.dimension,r=new Float32Array(e),a=new Float32Array(e),n=this.ewc.getFisherDiagonal(),o=this.microLora.adaptationVector;for(let i=0;i<e;i++){let s=n[i]+1e-10;r[i]+=s*o[i],a[i]+=s}for(let i of t){let s=Math.min(i.adaptationVector.length,e);for(let u=0;u<s;u++){let c=(u<i.fisherDiagonal.length?i.fisherDiagonal[u]:0)+1e-10;r[u]+=c*i.adaptationVector[u],a[u]+=c}}for(let i=0;i<e;i++)this.microLora.adaptationVector[i]=r[i]/a[i];f.debug("Synced with peers",{peerCount:t.length,peersStored:this.peerStates.size})}getLocalPeerState(t,e){return{peerId:t,domain:e,adaptationVector:new Float32Array(this.microLora.adaptationVector),fisherDiagonal:this.ewc.getFisherDiagonal(),requestCount:this.requestCount,lastUpdateMs:Date.now()}}getEWCMetrics(){let t=this.ewc.getMetrics();return t.regularizationLoss=this.ewc.computeLoss(this.microLora.getEffectiveWeights()),t}getFisherDiagonal(){return this.ewc.getFisherDiagonal()}getOptimalParams(){return this.ewc.getOptimalParams()}loadFisher(t,e){this.ewc.loadFisher(t,e)}getBaseWeights(){return new Float32Array(this.microLora.baseWeights)}setBaseWeights(t){let e=Math.min(t.length,this.microLora.baseWeights.length);for(let r=0;r<e;r++)this.microLora.baseWeights[r]=t[r]}getEffectiveWeights(){return this.microLora.getEffectiveWeights()}getRequestCount(){return this.requestCount}getConfig(){return{...this.config}}getPeerStates(){return new Map(this.peerStates)}getMicroLoRA(){return this.microLora}getEWC(){return this.ewc}applyEWCRegularization(){let t=this.config.dimension,e=this.ewc.fisherMatrix,r=this.ewc.optimalParams,a=this.microLora.baseWeights,n=.01;for(let o=0;o<t;o++)if(e[o]>this.config.importanceThreshold){let i=a[o]-r[o];a[o]-=n*e[o]*i}}persistFisher(t,e){let r=this.ewc.getMetrics();t(e,this.ewc.getFisherDiagonal(),this.ewc.getOptimalParams(),this.getBaseWeights(),{taskBoundaries:r.taskBoundariesDetected,consolidationCycles:r.consolidationCycles,requestCount:this.requestCount,ewcLambda:r.lambda}),f.info("Fisher matrix persisted to SQLite",{domain:e,requestCount:this.requestCount,taskBoundaries:r.taskBoundariesDetected})}restoreFisher(t){this.ewc.loadFisher(t.fisherDiagonal,t.optimalParams),t.baseWeights&&this.setBaseWeights(t.baseWeights),this.requestCount=t.requestCount,f.info("Fisher matrix restored from SQLite",{requestCount:t.requestCount,dimension:t.fisherDiagonal.length})}};var Lt={hiddenDim:256,embeddingDim:384,microLoraRank:1,baseLoraRank:8,microLoraLr:.001,baseLoraLr:1e-4,ewcLambda:1e3,patternClusters:50,trajectoryCapacity:1e4,backgroundIntervalMs:36e5,qualityThreshold:.5,enableSimd:!0,minConfidence:.5,maxPatterns:1e4},Q=class{patterns;trajectoryMap;maxPatterns;constructor(t=1e4){this.patterns=new Map,this.trajectoryMap=new Map,this.maxPatterns=t}register(t){if(this.patterns.size>=this.maxPatterns&&!this.patterns.has(t.id)){let e=Array.from(this.patterns.entries()).sort(([,r],[,a])=>(r.lastUsedAt?.getTime()??r.createdAt.getTime())-(a.lastUsedAt?.getTime()??a.createdAt.getTime()))[0];e&&this.patterns.delete(e[0])}this.patterns.set(t.id,t)}get(t){return this.patterns.get(t)}getByTrajectory(t){let e=this.trajectoryMap.get(t);return e?this.patterns.get(e):void 0}associateTrajectory(t,e){this.trajectoryMap.set(t,e)}update(t,e){let r=this.patterns.get(t);return r?(this.patterns.set(t,{...r,...e}),!0):!1}getAll(){return Array.from(this.patterns.values())}getByType(t){return Array.from(this.patterns.values()).filter(e=>e.type===t)}getByDomain(t){return Array.from(this.patterns.values()).filter(e=>e.domain===t)}clear(){this.patterns.clear(),this.trajectoryMap.clear()}size(){return this.patterns.size}},v=class{engine;registry;config;adaptationTimes=[];cacheHits=0;totalAdaptations=0;threeLoopEngine=null;fisherPersistFn=null;fisherDomain="default";constructor(t={}){this.config={...Lt,...t};let e={hiddenDim:this.config.hiddenDim,embeddingDim:this.config.embeddingDim,microLoraRank:this.config.microLoraRank,baseLoraRank:this.config.baseLoraRank,microLoraLr:this.config.microLoraLr,baseLoraLr:this.config.baseLoraLr,ewcLambda:this.config.ewcLambda,patternClusters:this.config.patternClusters,trajectoryCapacity:this.config.trajectoryCapacity,backgroundIntervalMs:this.config.backgroundIntervalMs,qualityThreshold:this.config.qualityThreshold,enableSimd:this.config.enableSimd};this.engine=P.withConfig(e),this.registry=new Q(this.config.maxPatterns??1e4)}async adaptPattern(t,e,r){let a=performance.now();try{let n=this.createStateEmbedding(t),o=this.engine.findPatterns(n,5),i=[];for(let m of o){let g=this.findByRawPattern(m);if(g||(g=this.createQEPatternFromRaw(m,e,r)),g.type===e&&g.domain===r&&g.confidence>=(this.config.minConfidence??.5)){let h=this.calculateSimilarity(n,m.centroid);i.push({pattern:g,similarity:h})}}if(i.length===0){let m=performance.now()-a;return this.recordAdaptation(m),{success:!1,pattern:null,adaptationTimeMs:m,similarity:0,reasoning:"No suitable pattern found"}}let s=i[0],u={...s.pattern,usageCount:s.pattern.usageCount+1,lastUsedAt:new Date};this.registry.update(u.id,u);let c=performance.now()-a;return this.recordAdaptation(c),{success:!0,pattern:u,adaptationTimeMs:c,similarity:s.similarity,reasoning:`Pattern adapted from @ruvector/sona with ${s.similarity.toFixed(3)} similarity`}}catch(n){let o=performance.now()-a;return this.recordAdaptation(o),{success:!1,pattern:null,adaptationTimeMs:o,similarity:0,reasoning:`Adaptation failed: ${n.message}`}}}recallPattern(t,e,r){let a=this.createStateEmbedding(t),n=this.engine.findPatterns(a,1);for(let o of n){let i=this.findByRawPattern(o);if(i&&i.type===e&&i.domain===r)return i}return null}storePattern(t){this.registry.register(t);let e=this.engine.beginTrajectory(t.stateEmbedding),r=this.createActionEmbedding(t.action),a=new Array(r.length).fill(1),n=t.outcome.success?t.outcome.quality:-t.outcome.quality;this.engine.addTrajectoryStep(e,r,a,n),this.engine.endTrajectory(e,t.outcome.quality),this.registry.associateTrajectory(e,t.id)}storePatternsBatch(t){for(let e of t)this.storePattern(e)}createPattern(t,e,r,a,n,o){let i={id:`qesona-${Date.now()}-${Ct().slice(0,7)}`,type:a,domain:n,stateEmbedding:this.createStateEmbedding(t),action:e,outcome:r,confidence:.5,usageCount:0,createdAt:new Date,metadata:o};return this.storePattern(i),i}updatePattern(t,e,r){let a=this.registry.get(t);if(!a)return!1;let n=e?r:-r,i=a.confidence+.1*(n-a.confidence),s={...a,confidence:Math.max(0,Math.min(1,i)),usageCount:a.usageCount+1,lastUsedAt:new Date};return this.registry.update(t,s)}applyMicroLora(t){return this.engine.applyMicroLora(t)}applyBaseLora(t,e){return this.engine.applyBaseLora(t,e)}forceLearn(){return this.engine.forceLearn()}tick(){return this.engine.tick()}getAllPatterns(){return this.registry.getAll()}getPatternsByType(t){return this.registry.getByType(t)}getPatternsByDomain(t){return this.registry.getByDomain(t)}getStats(){let t=this.registry.getAll(),e=this.engine.getStats(),r={"test-generation":0,"defect-prediction":0,"coverage-optimization":0,"quality-assessment":0,"resource-allocation":0};for(let a of t)r[a.type]++;return{totalPatterns:t.length,patternsByType:r,avgAdaptationTimeMs:this.avgAdaptationTime(),minAdaptationTimeMs:this.minAdaptationTime(),maxAdaptationTimeMs:this.maxAdaptationTime(),totalAdaptations:this.totalAdaptations,cacheHitRate:this.totalAdaptations>0?this.cacheHits/this.totalAdaptations:0,engineStats:e}}clear(){this.registry.clear(),this.adaptationTimes=[],this.cacheHits=0,this.totalAdaptations=0}exportPatterns(){return this.registry.getAll()}importPatterns(t){this.clear(),this.storePatternsBatch(t)}getConfig(){return{...this.config}}setEnabled(t){this.engine.setEnabled(t)}isEnabled(){return this.engine.isEnabled()}createStateEmbedding(t){let e=t.features;if(e.length===0)return new Array(this.config.embeddingDim??384).fill(0);let r=Math.max(...e.map(Math.abs));if(r===0)return[...e];let a=e.map(o=>o/r),n=this.config.embeddingDim??384;return a.length>=n?a.slice(0,n):[...a,...new Array(n-a.length).fill(0)]}createActionEmbedding(t){let e=[],r=this.hashCode(t.type);if(e.push(r%1e3/1e3),typeof t.value=="number")e.push(Math.min(1,Math.max(-1,t.value)));else if(typeof t.value=="string"){let n=this.hashCode(t.value);e.push(n%1e3/1e3)}else if(Array.isArray(t.value))for(let n of t.value.slice(0,10))typeof n=="number"&&e.push(Math.min(1,Math.max(-1,n)));let a=this.config.embeddingDim??384;for(;e.length<a;)e.push(0);return e.slice(0,a)}findByRawPattern(t){let e=this.registry.getAll();for(let r of e)if(r.rawPattern?.patternType===t.id)return r}createQEPatternFromRaw(t,e,r){let a={centroid:t.centroid,clusterSize:1,totalWeight:1,avgQuality:t.avgQuality,createdAt:new Date().toISOString(),lastAccessed:new Date().toISOString(),accessCount:0,patternType:t.patternType};return{id:`qesona-${t.id}`,type:e,domain:r,stateEmbedding:t.centroid,action:{type:"learned",value:t.patternType},outcome:{reward:t.avgQuality,success:t.avgQuality>.5,quality:t.avgQuality},confidence:t.avgQuality,usageCount:0,createdAt:new Date,rawPattern:a}}calculateSimilarity(t,e){let r=Math.min(t.length,e.length),a=0,n=0,o=0;for(let s=0;s<r;s++)a+=t[s]*e[s],n+=t[s]*t[s],o+=e[s]*e[s];return(a/(Math.sqrt(n)*Math.sqrt(o)+1e-10)+1)/2}hashCode(t){let e=0;for(let r=0;r<t.length;r++)e=(e<<5)-e+t.charCodeAt(r),e=e|0;return Math.abs(e)}recordAdaptation(t){this.adaptationTimes.push(t),this.totalAdaptations++,this.adaptationTimes.length>1e3&&this.adaptationTimes.shift()}avgAdaptationTime(){return this.adaptationTimes.length===0?0:this.adaptationTimes.reduce((e,r)=>e+r,0)/this.adaptationTimes.length}minAdaptationTime(){return this.adaptationTimes.length===0?0:Math.min(...this.adaptationTimes)}maxAdaptationTime(){return this.adaptationTimes.length===0?0:Math.max(...this.adaptationTimes)}initThreeLoopEngine(t){this.threeLoopEngine=new C({dimension:this.config.embeddingDim??384,microLoraLr:this.config.microLoraLr??.001,ewcLambda:this.config.ewcLambda??1e3,...t},this.engine)}getThreeLoopEngine(){return this.threeLoopEngine}instantAdapt(t){return this.threeLoopEngine?this.threeLoopEngine.instantAdapt(t):null}recordOutcome(t,e){this.threeLoopEngine&&this.threeLoopEngine.recordOutcome(t,e)}backgroundConsolidate(){if(!this.threeLoopEngine)return null;let t=this.threeLoopEngine.backgroundConsolidate();if(t&&(t.consolidated||t.taskBoundaryDetected)&&this.fisherPersistFn)try{this.threeLoopEngine.persistFisher(this.fisherPersistFn,this.fisherDomain)}catch(e){console.warn("[QESONA] Fisher persistence failed:",e instanceof Error?e.message:e)}return t}setFisherPersistence(t,e){this.fisherPersistFn=t,this.fisherDomain=e}syncWithPeers(t){this.threeLoopEngine&&this.threeLoopEngine.syncWithPeers(t)}getEWCMetrics(){return this.threeLoopEngine?this.threeLoopEngine.getEWCMetrics():null}shouldConsolidate(){return this.threeLoopEngine?this.threeLoopEngine.shouldConsolidate():!1}getLocalPeerState(t,e){return this.threeLoopEngine?this.threeLoopEngine.getLocalPeerState(t,e):null}isThreeLoopEnabled(){return this.threeLoopEngine!==null}async verifyPerformance(t=1e3){let e=[],r={id:"test-state",features:new Array(384).fill(0).map(()=>G())};for(let s=0;s<t;s++){let u=performance.now();await this.adaptPattern(r,"test-generation","test-generation");let c=performance.now();e.push({iteration:s,timeMs:c-u})}let a=e.map(s=>s.timeMs),n=a.reduce((s,u)=>s+u,0)/a.length,o=Math.min(...a),i=Math.max(...a);return{targetMet:n<.05,avgTimeMs:n,minTimeMs:o,maxTimeMs:i,details:e}}};function Tt(l){return new v(l)}function Pt(l,t){return new v({...t,maxPatterns:t?.maxPatterns||5e3})}ot();et();var F=null,D=null,W=null,B=null,z=null,I=null,q=!1;try{let l=(O(),w(N));F=l.FlashAttention,D=l.DotProductAttention,W=l.MultiHeadAttention,B=l.HyperbolicAttention,z=l.LinearAttention,I=l.MoEAttention,q=!0}catch{}function Gt(){return q}function A(){if(!q)throw new Error("@ruvector/attention native module is not available on this platform. Install the appropriate optional dependency for your platform, or use a platform where pre-built binaries are available.")}var T={"test-similarity":{dim:384,strategy:"flash",blockSize:64},"code-embedding":{dim:512,strategy:"flash",blockSize:128},"defect-matching":{dim:384,strategy:"flash",blockSize:64},"coverage-analysis":{dim:384,strategy:"flash",blockSize:256},"pattern-adaptation":{dim:256,strategy:"flash",blockSize:32}},Kt={"test-similarity":{enabled:!0,microLoRARank:4,targetAdaptationMs:.05,patternCacheSize:1e3},"code-embedding":{enabled:!0,microLoRARank:2,targetAdaptationMs:.03,patternCacheSize:5e3},"defect-matching":{enabled:!0,microLoRARank:8,targetAdaptationMs:.05,patternCacheSize:2e3},"coverage-analysis":{enabled:!1,microLoRARank:2,targetAdaptationMs:.01,patternCacheSize:100},"pattern-adaptation":{enabled:!0,microLoRARank:2,targetAdaptationMs:.05,patternCacheSize:1e4}},$t={"test-similarity":{latency:{before:50,after:15},memory:{before:200,after:80},throughput:{min:1e3}},"code-embedding":{latency:{before:50,after:15},memory:{before:200,after:80},throughput:{min:2e3}},"defect-matching":{latency:{before:20,after:5},memory:{before:150,after:50},throughput:{min:500}},"coverage-analysis":{latency:{before:100,after:1},memory:{before:100,after:30},throughput:{min:1e4}},"pattern-adaptation":{latency:{before:2,after:.05},memory:{before:50,after:20},throughput:{min:2e4}}};function Zt(l){return l<=128?{queryChunkSize:128,kvChunkSize:128}:l<=256?{queryChunkSize:256,kvChunkSize:256}:l<=512?{queryChunkSize:512,kvChunkSize:512}:l<=1024?{queryChunkSize:1024,kvChunkSize:1024}:{queryChunkSize:1024,kvChunkSize:2048}}var E=class{static create(t){switch(A(),t.strategy){case"flash":return new F(t.dim,t.blockSize);case"dot-product":return new D(t.dim);case"multi-head":return new W(t.dim,t.numHeads??8);case"hyperbolic":return new B(t.dim,t.curvature);case"linear":return new z(t.dim,t.features);case"moe":return I.simple(t.dim,t.moeConfig?.numExperts??8,t.moeConfig?.topK??2);default:return new F(t.dim,t.blockSize)}}},L=class l{attention;config;workload;metrics=[];db=null;persistCount=0;static KV_NAMESPACE="attention-metrics";static KV_TTL=3600;static PERSIST_INTERVAL=10;constructor(t,e){this.workload=t;let r=T[t];this.config={...r,...e},this.attention=E.create(this.config)}async initialize(){try{this.db=K(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(t){console.warn("[QEFlashAttention] DB init failed, using memory-only:",j(t)),this.db=null}}async computeFlashAttention(t,e,r,a,n){let o=performance.now(),i=process.memoryUsage().heapUsed/1024/1024,s=this.toFloat32Array(t,a,n),u=this.splitMatrix(e,a,n),c=this.splitMatrix(r,a,n),m,g=this.attention;typeof g.compute=="function"?m=g.compute(s,u,c):(A(),m=new F(this.config.dim).compute(s,u,c));let h=performance.now(),d=process.memoryUsage().heapUsed/1024/1024;return this.metrics.push({timeMs:h-o,memoryMB:d-i,speedup:1,throughput:a*a/((h-o)/1e3),peakMemoryMB:d}),this.maybePersistToKv(),m}async computeBaselineAttention(t,e,r,a,n){let o=performance.now(),i=process.memoryUsage().heapUsed/1024/1024,s=new Float32Array(a*a),u=1/Math.sqrt(n);for(let h=0;h<a;h++)for(let d=0;d<a;d++){let b=0;for(let p=0;p<n;p++)b+=t[h*n+p]*e[d*n+p];s[h*a+d]=b*u}for(let h=0;h<a;h++){let d=h*a,b=d+a,p=s.subarray(d,b),tt=Math.max(...p),_=0;for(let y=0;y<a;y++)p[y]=Math.exp(p[y]-tt),_+=p[y];for(let y=0;y<a;y++)p[y]/=_}let c=new Float32Array(a*n);for(let h=0;h<a;h++)for(let d=0;d<a;d++){let b=s[h*a+d];for(let p=0;p<n;p++)c[h*n+p]+=b*r[d*n+p]}let m=performance.now(),g=process.memoryUsage().heapUsed/1024/1024;return c}async computeTestSimilarity(t,e,r=5){let a=e.length,n=t.length,o=new Float32Array(a*n),i=new Float32Array(a*n);for(let m=0;m<a;m++)o.set(t,m*n),i.set(e[m],m*n);let s=new Float32Array(a*n),u=await this.computeFlashAttention(o,i,s,a,n),c=[];for(let m=0;m<a;m++)c.push({index:m,similarity:u[m*n]});return c.sort((m,g)=>g.similarity-m.similarity),c.slice(0,r)}async generateCodeEmbedding(t,e){let r=t.length/e.length,a=e.length;return await this.computeFlashAttention(t,e,t,r,a)}async matchDefectPattern(t,e){let r=e.length,a=t.length,n=new Float32Array(r*a),o=new Float32Array(r*a);for(let c=0;c<r;c++)n.set(t,c*a),o.set(e[c],c*a);let i=new Float32Array(r*a),s=await this.computeFlashAttention(n,o,i,r,a),u=[];for(let c=0;c<r;c++)u.push({pattern:c,score:s[c*a]});return u.sort((c,m)=>m.score-c.score),u}getMetrics(){return[...this.metrics]}getAverageSpeedup(){return this.metrics.length===0?1:this.metrics.reduce((t,e)=>t+e.speedup,0)/this.metrics.length}getConfig(){return{...this.config}}updateConfig(t){this.config={...this.config,...t},this.attention=E.create(this.config)}changeStrategy(t){this.config.strategy=t,this.attention=E.create(this.config)}resetMetrics(){this.metrics=[]}getWorkload(){return this.workload}dispose(){this.metrics=[]}async persistToKv(){if(!this.db)return;let t=`attention-metrics-${this.workload}`,e={workload:this.workload,metrics:this.metrics.slice(-50),savedAt:Date.now()};await this.db.kvSet(t,e,l.KV_NAMESPACE,l.KV_TTL)}async loadFromKv(){if(!this.db)return;let t=`attention-metrics-${this.workload}`,e=await this.db.kvGet(t,l.KV_NAMESPACE);e?.metrics?.length&&(this.metrics=e.metrics)}maybePersistToKv(){this.persistCount++,this.persistCount>=l.PERSIST_INTERVAL&&(this.persistCount=0,this.persistToKv().catch(()=>{}))}toFloat32Array(t,e,r){return t.slice(0,r)}splitMatrix(t,e,r){let a=[];for(let n=0;n<e;n++)a.push(t.slice(n*r,(n+1)*r));return a}};async function Y(l,t){let e=new L(l,t);return await e.initialize(),e}function Jt(l){return{...T[l]}}function Xt(){return Object.keys(T)}function Yt(){return A(),F}function te(){return A(),D}function ee(){return A(),W}function re(){return A(),B}function ae(){return A(),z}function ne(){return A(),I}function ie(l){return l instanceof Float32Array?l:new Float32Array(l)}function oe(l){return Array.from(l)}async function se(l,t,e,r){let a=await Y(l),n=[],o=t[0].length,i=e.length;for(let s of t){let u=new Float32Array(i*o),c=new Float32Array(i*o),m=new Float32Array(i*o);u.set(s,0);for(let h=0;h<i;h++)c.set(e[h],h*o),m.set(r[h],h*o);let g=await a.computeFlashAttention(u,c,m,i,o);n.push(g.slice(0,o))}return a.dispose(),n}function We(){return{"@ruvector/sona":"^0.1.5","@ruvector/attention":"^0.1.4","@ruvector/gnn":"^0.1.22"}}function Be(){let l={sona:!1,attention:!1,gnn:!1,all:!1};try{k(),l.sona=!0}catch{}try{O(),l.attention=!0}catch{}try{let t=(it(),w(nt));t.init();let e=new Float32Array([.1,.2,.3]),r=[new Float32Array([.1,.2,.3]),new Float32Array([.4,.5,.6])],a=t.differentiableSearch(e,r,1,1);a&&Array.isArray(a.indices)&&Array.isArray(a.weights)&&(l.gnn=!0)}catch{}return l.all=l.sona&&l.attention&&l.gnn,l}async function ze(){let{initGNN:l}=await import("./gnn-wrapper-XEII72LN.js");return[l(),"SONA: Ready (no initialization required)","Attention: Ready (no initialization required)"]}export{v as a,Tt as b,Pt as c,Gt as d,T as e,Kt as f,$t as g,Zt as h,L as i,Y as j,Jt as k,Xt as l,Yt as m,te as n,ee as o,re as p,ae as q,ne as r,ie as s,oe as t,se as u,We as v,Be as w,ze as x};
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.4");process.exit(0)}
|
|
2
|
+
import{k as K,o as ot}from"./chunk-G6RTCJFY.js";import{a as rt}from"./chunk-MDFXPCBO.js";import{c as U}from"./chunk-RPYUKEAH.js";import{a as j,c as et}from"./chunk-F6AU2MAZ.js";import{a as G,d as at}from"./chunk-P3EOWBME.js";import{a as nt,b as it}from"./chunk-RE6XD6RI.js";import{c as H,e as V,g as w}from"./chunk-C2HGOUEB.js";var Z={};V(Z,{DotProductAttention:()=>yt,FlashAttention:()=>ft,HyperbolicAttention:()=>bt,LinearAttention:()=>vt,MoEAttention:()=>Et,MultiHeadAttention:()=>At,RuvectorLayer:()=>ut,SonaEngine:()=>P,TensorCompress:()=>mt,default:()=>ct,differentiableSearch:()=>ht,getCompressionLevel:()=>pt,hierarchicalForward:()=>dt,init:()=>gt,pipeline:()=>Ft});import{createRequire as st}from"module";var lt,$,ct,ut,mt,ht,dt,pt,gt,ft,yt,At,bt,vt,Et,P,Ft,k=H(()=>{lt=st(import.meta.url),$=lt("@ruvector/sona"),ct=$,{RuvectorLayer:ut,TensorCompress:mt,differentiableSearch:ht,hierarchicalForward:dt,getCompressionLevel:pt,init:gt,FlashAttention:ft,DotProductAttention:yt,MultiHeadAttention:At,HyperbolicAttention:bt,LinearAttention:vt,MoEAttention:Et,SonaEngine:P,pipeline:Ft}=$||{}});var N={};V(N,{DotProductAttention:()=>It,FlashAttention:()=>zt,HyperbolicAttention:()=>_t,LinearAttention:()=>Ht,MoEAttention:()=>Vt,MultiHeadAttention:()=>qt,RuvectorLayer:()=>Qt,SonaEngine:()=>jt,TensorCompress:()=>Nt,default:()=>xt,differentiableSearch:()=>Ot,getCompressionLevel:()=>Wt,hierarchicalForward:()=>Dt,init:()=>Bt,pipeline:()=>Ut});import{createRequire as kt}from"module";var Rt,X,xt,Qt,Nt,Ot,Dt,Wt,Bt,zt,It,qt,_t,Ht,Vt,jt,Ut,O=H(()=>{Rt=kt(import.meta.url),X=Rt("@ruvector/attention"),xt=X,{RuvectorLayer:Qt,TensorCompress:Nt,differentiableSearch:Ot,hierarchicalForward:Dt,getCompressionLevel:Wt,init:Bt,FlashAttention:zt,DotProductAttention:It,MultiHeadAttention:qt,HyperbolicAttention:_t,LinearAttention:Ht,MoEAttention:Vt,SonaEngine:jt,pipeline:Ut}=X||{}});k();at();import{randomUUID as Ct}from"crypto";rt();import{createRequire as wt}from"module";var f=U.create("sona-three-loop"),S=wt(import.meta.url),M=null,J=!1;function St(){if(J)return M;J=!0;try{let l=S("@ruvector/learning-wasm"),t=S("fs"),e=S("path"),r=e.join(e.dirname(S.resolve("@ruvector/learning-wasm")),"ruvector_learning_wasm_bg.wasm");l.initSync({module:t.readFileSync(r)}),M=l,f.info("WASM MicroLoRA loaded from @ruvector/learning-wasm (6.4x faster than TS)")}catch{M=null,f.debug("@ruvector/learning-wasm not available, using TypeScript MicroLoRA")}return M}var Mt={dimension:384,microLoraLr:.001,consolidationInterval:100,ewcLambda:1e3,taskBoundaryZScoreThreshold:2.5,fisherDecay:.9,fisherSampleSize:200,importanceThreshold:.01},R=class{adaptationVector;baseWeights;lr;adaptationCount=0;constructor(t,e=.001){this.adaptationVector=new Float32Array(t),this.baseWeights=new Float32Array(t),this.lr=e}adapt(t){let e=this.baseWeights.length,r=new Float32Array(e),a=Math.min(t.length,e);for(let n=0;n<e;n++){let o=n<a?t[n]:0;r[n]=this.baseWeights[n]+this.adaptationVector[n]+this.lr*o}for(let n=0;n<a;n++)this.adaptationVector[n]+=this.lr*t[n];return this.adaptationCount++,r}consolidate(){let t=this.adaptationCount,e=this.baseWeights.length;for(let r=0;r<e;r++)this.baseWeights[r]+=this.adaptationVector[r],this.adaptationVector[r]=0;return this.adaptationCount=0,t}getAdaptationCount(){return this.adaptationCount}getEffectiveWeights(){let t=this.baseWeights.length,e=new Float32Array(t);for(let r=0;r<t;r++)e[r]=this.baseWeights[r]+this.adaptationVector[r];return e}getAdaptationMagnitude(){let t=0;for(let e=0;e<this.adaptationVector.length;e++)t+=this.adaptationVector[e]*this.adaptationVector[e];return Math.sqrt(t)}resetAdaptation(){this.adaptationVector.fill(0),this.adaptationCount=0}},x=class{fisherMatrix;optimalParams;lambda;fisherDecay;zScoreThreshold;importanceThreshold;gradientHistory=[];gradientMean=0;gradientVariance=0;taskBoundaryCount=0;consolidationCount=0;constructor(t,e=1e3,r=.9,a=2.5,n=.01){this.fisherMatrix=new Float32Array(t),this.optimalParams=new Float32Array(t),this.lambda=e,this.fisherDecay=r,this.zScoreThreshold=a,this.importanceThreshold=n}detectTaskBoundary(t){let e=0;for(let i=0;i<t.length;i++)e+=t[i]*t[i];if(e=Math.sqrt(e),this.gradientHistory.length<5)return this.gradientHistory.push(e),this.updateGradientStats(),!1;let r=Math.sqrt(this.gradientVariance),a=0,n=Math.abs(e-this.gradientMean);return r>1e-10?a=n/r:n>1e-10&&this.gradientMean>1e-10&&(a=n/(this.gradientMean*.01+1e-10)),this.gradientHistory.push(e),this.gradientHistory.length>100&&this.gradientHistory.shift(),this.updateGradientStats(),a>this.zScoreThreshold?(this.taskBoundaryCount++,!0):!1}computeLoss(t){let e=0,r=Math.min(t.length,this.fisherMatrix.length,this.optimalParams.length);for(let a=0;a<r;a++){let n=t[a]-this.optimalParams[a];e+=this.fisherMatrix[a]*n*n}return this.lambda/2*e}updateFisher(t,e){if(t.length===0)return;let r=this.fisherMatrix.length,a=new Float32Array(r);for(let s of t){let u=Math.min(s.length,r);for(let c=0;c<u;c++)a[c]+=s[c]*s[c]}let n=t.length;for(let s=0;s<r;s++)a[s]/=n;let o=this.fisherDecay;for(let s=0;s<r;s++)this.fisherMatrix[s]=o*this.fisherMatrix[s]+(1-o)*a[s];let i=Math.min(e.length,r);for(let s=0;s<i;s++)this.optimalParams[s]=e[s];this.consolidationCount++}getMetrics(){let t=this.fisherMatrix.length,e=0,r=0,a=0;for(let n=0;n<t;n++)e+=this.fisherMatrix[n],this.fisherMatrix[n]>r&&(r=this.fisherMatrix[n]),this.fisherMatrix[n]>this.importanceThreshold&&a++;return{regularizationLoss:0,taskBoundariesDetected:this.taskBoundaryCount,fisherTrace:e,avgFisherImportance:t>0?e/t:0,maxFisherImportance:r,protectedParams:a,consolidationCycles:this.consolidationCount,lambda:this.lambda}}getTaskBoundaryCount(){return this.taskBoundaryCount}getFisherDiagonal(){return new Float32Array(this.fisherMatrix)}getOptimalParams(){return new Float32Array(this.optimalParams)}loadFisher(t,e){let r=this.fisherMatrix.length,a=Math.min(t.length,r),n=Math.min(e.length,r);for(let o=0;o<a;o++)this.fisherMatrix[o]=t[o];for(let o=0;o<n;o++)this.optimalParams[o]=e[o]}updateGradientStats(){let t=this.gradientHistory.length;if(t===0)return;let e=0;for(let a of this.gradientHistory)e+=a;e/=t;let r=0;for(let a of this.gradientHistory){let n=a-e;r+=n*n}r=t>1?r/(t-1):0,this.gradientMean=e,this.gradientVariance=r}},C=class{config;microLora;ewc;nativeEngine;wasmLora=null;requestCount=0;lastConsolidationRequest=0;peerStates=new Map;gradientBuffer=[];lastFeatures=null;constructor(t={},e){this.config={...Mt,...t},this.nativeEngine=e??null,this.microLora=new R(this.config.dimension,this.config.microLoraLr),this.ewc=new x(this.config.dimension,this.config.ewcLambda,this.config.fisherDecay,this.config.taskBoundaryZScoreThreshold,this.config.importanceThreshold);let r=St();if(r)try{this.wasmLora=new r.WasmMicroLoRA(this.config.dimension,1,this.config.microLoraLr),f.info("SONA Three-Loop using WASM MicroLoRA (0.07us/adapt)")}catch(a){f.debug("WASM MicroLoRA creation failed, falling back",{error:String(a)}),this.wasmLora=null}!this.wasmLora&&this.nativeEngine&&f.info("SONA Three-Loop using native @ruvector/sona engine for MicroLoRA delegation")}instantAdapt(t){let e=performance.now(),r;if(this.wasmLora)try{let o=new Float32Array(t),i=this.wasmLora.adapt(o);i&&i.length>0?(r=i,this.microLora.adapt(t)):r=this.microLora.adapt(t)}catch{r=this.microLora.adapt(t)}else if(this.nativeEngine)try{let o=this.nativeEngine.applyMicroLora(t);r=new Float32Array(o),this.microLora.adapt(t)}catch{r=this.microLora.adapt(t)}else r=this.microLora.adapt(t);let a=this.microLora.getAdaptationMagnitude();this.requestCount++,this.lastFeatures=[...t];let n=(performance.now()-e)*1e3;return{adaptedWeights:r,latencyUs:n,applied:!0,magnitude:a,requestIndex:this.requestCount}}recordOutcome(t,e){if(this.lastFeatures===null){f.warn("recordOutcome called without a preceding instantAdapt()");return}let r=this.lastFeatures.length,a=new Float32Array(r);for(let n=0;n<r;n++)a[n]=t*this.lastFeatures[n];this.gradientBuffer.push(a),this.gradientBuffer.length>this.config.fisherSampleSize&&this.gradientBuffer.shift(),this.lastFeatures=null}backgroundConsolidate(){let t=performance.now();if(this.nativeEngine)try{this.nativeEngine.forceLearn(),this.nativeEngine.tick()}catch(i){f.warn("Native SONA background learning failed, continuing with TypeScript",{error:String(i)})}let e=this.ewc.computeLoss(this.microLora.getEffectiveWeights()),r=!1;if(this.gradientBuffer.length>0){let i=this.gradientBuffer[this.gradientBuffer.length-1];r=this.ewc.detectTaskBoundary(i)}if(r&&this.gradientBuffer.length>0&&(this.ewc.updateFisher(this.gradientBuffer,this.microLora.getEffectiveWeights()),f.info("Task boundary detected, Fisher updated",{boundaries:this.ewc.getTaskBoundaryCount(),requestCount:this.requestCount})),this.gradientBuffer.length>1){let i=!1,s=this.gradientBuffer[0];for(let u=1;u<this.gradientBuffer.length&&!i;u++)for(let c=0;c<s.length;c++)if(Math.abs(this.gradientBuffer[u][c]-s[c])>1e-8){i=!0;break}i||f.warn("All gradient samples identical \u2014 Fisher estimate may be poor. Ensure recordOutcome() is called with diverse rewards.")}let a=this.microLora.consolidate();this.applyEWCRegularization();let n=this.ewc.computeLoss(this.microLora.getEffectiveWeights());this.lastConsolidationRequest=this.requestCount,this.gradientBuffer=[];let o=performance.now()-t;return{consolidated:a>0||r,adaptationsMerged:a,ewcLossBefore:e,ewcLossAfter:n,taskBoundaryDetected:r,durationMs:o}}shouldConsolidate(){return this.requestCount-this.lastConsolidationRequest>=this.config.consolidationInterval}syncWithPeers(t){if(t.length===0)return;for(let i of t)this.peerStates.set(i.peerId,i);let e=this.config.dimension,r=new Float32Array(e),a=new Float32Array(e),n=this.ewc.getFisherDiagonal(),o=this.microLora.adaptationVector;for(let i=0;i<e;i++){let s=n[i]+1e-10;r[i]+=s*o[i],a[i]+=s}for(let i of t){let s=Math.min(i.adaptationVector.length,e);for(let u=0;u<s;u++){let c=(u<i.fisherDiagonal.length?i.fisherDiagonal[u]:0)+1e-10;r[u]+=c*i.adaptationVector[u],a[u]+=c}}for(let i=0;i<e;i++)this.microLora.adaptationVector[i]=r[i]/a[i];f.debug("Synced with peers",{peerCount:t.length,peersStored:this.peerStates.size})}getLocalPeerState(t,e){return{peerId:t,domain:e,adaptationVector:new Float32Array(this.microLora.adaptationVector),fisherDiagonal:this.ewc.getFisherDiagonal(),requestCount:this.requestCount,lastUpdateMs:Date.now()}}getEWCMetrics(){let t=this.ewc.getMetrics();return t.regularizationLoss=this.ewc.computeLoss(this.microLora.getEffectiveWeights()),t}getFisherDiagonal(){return this.ewc.getFisherDiagonal()}getOptimalParams(){return this.ewc.getOptimalParams()}loadFisher(t,e){this.ewc.loadFisher(t,e)}getBaseWeights(){return new Float32Array(this.microLora.baseWeights)}setBaseWeights(t){let e=Math.min(t.length,this.microLora.baseWeights.length);for(let r=0;r<e;r++)this.microLora.baseWeights[r]=t[r]}getEffectiveWeights(){return this.microLora.getEffectiveWeights()}getRequestCount(){return this.requestCount}getConfig(){return{...this.config}}getPeerStates(){return new Map(this.peerStates)}getMicroLoRA(){return this.microLora}getEWC(){return this.ewc}applyEWCRegularization(){let t=this.config.dimension,e=this.ewc.fisherMatrix,r=this.ewc.optimalParams,a=this.microLora.baseWeights,n=.01;for(let o=0;o<t;o++)if(e[o]>this.config.importanceThreshold){let i=a[o]-r[o];a[o]-=n*e[o]*i}}persistFisher(t,e){let r=this.ewc.getMetrics();t(e,this.ewc.getFisherDiagonal(),this.ewc.getOptimalParams(),this.getBaseWeights(),{taskBoundaries:r.taskBoundariesDetected,consolidationCycles:r.consolidationCycles,requestCount:this.requestCount,ewcLambda:r.lambda}),f.info("Fisher matrix persisted to SQLite",{domain:e,requestCount:this.requestCount,taskBoundaries:r.taskBoundariesDetected})}restoreFisher(t){this.ewc.loadFisher(t.fisherDiagonal,t.optimalParams),t.baseWeights&&this.setBaseWeights(t.baseWeights),this.requestCount=t.requestCount,f.info("Fisher matrix restored from SQLite",{requestCount:t.requestCount,dimension:t.fisherDiagonal.length})}};var Lt={hiddenDim:256,embeddingDim:384,microLoraRank:1,baseLoraRank:8,microLoraLr:.001,baseLoraLr:1e-4,ewcLambda:1e3,patternClusters:50,trajectoryCapacity:1e4,backgroundIntervalMs:36e5,qualityThreshold:.5,enableSimd:!0,minConfidence:.5,maxPatterns:1e4},Q=class{patterns;trajectoryMap;maxPatterns;constructor(t=1e4){this.patterns=new Map,this.trajectoryMap=new Map,this.maxPatterns=t}register(t){if(this.patterns.size>=this.maxPatterns&&!this.patterns.has(t.id)){let e=Array.from(this.patterns.entries()).sort(([,r],[,a])=>(r.lastUsedAt?.getTime()??r.createdAt.getTime())-(a.lastUsedAt?.getTime()??a.createdAt.getTime()))[0];e&&this.patterns.delete(e[0])}this.patterns.set(t.id,t)}get(t){return this.patterns.get(t)}getByTrajectory(t){let e=this.trajectoryMap.get(t);return e?this.patterns.get(e):void 0}associateTrajectory(t,e){this.trajectoryMap.set(t,e)}update(t,e){let r=this.patterns.get(t);return r?(this.patterns.set(t,{...r,...e}),!0):!1}getAll(){return Array.from(this.patterns.values())}getByType(t){return Array.from(this.patterns.values()).filter(e=>e.type===t)}getByDomain(t){return Array.from(this.patterns.values()).filter(e=>e.domain===t)}clear(){this.patterns.clear(),this.trajectoryMap.clear()}size(){return this.patterns.size}},v=class{engine;registry;config;adaptationTimes=[];cacheHits=0;totalAdaptations=0;threeLoopEngine=null;fisherPersistFn=null;fisherDomain="default";constructor(t={}){this.config={...Lt,...t};let e={hiddenDim:this.config.hiddenDim,embeddingDim:this.config.embeddingDim,microLoraRank:this.config.microLoraRank,baseLoraRank:this.config.baseLoraRank,microLoraLr:this.config.microLoraLr,baseLoraLr:this.config.baseLoraLr,ewcLambda:this.config.ewcLambda,patternClusters:this.config.patternClusters,trajectoryCapacity:this.config.trajectoryCapacity,backgroundIntervalMs:this.config.backgroundIntervalMs,qualityThreshold:this.config.qualityThreshold,enableSimd:this.config.enableSimd};this.engine=P.withConfig(e),this.registry=new Q(this.config.maxPatterns??1e4)}async adaptPattern(t,e,r){let a=performance.now();try{let n=this.createStateEmbedding(t),o=this.engine.findPatterns(n,5),i=[];for(let m of o){let g=this.findByRawPattern(m);if(g||(g=this.createQEPatternFromRaw(m,e,r)),g.type===e&&g.domain===r&&g.confidence>=(this.config.minConfidence??.5)){let h=this.calculateSimilarity(n,m.centroid);i.push({pattern:g,similarity:h})}}if(i.length===0){let m=performance.now()-a;return this.recordAdaptation(m),{success:!1,pattern:null,adaptationTimeMs:m,similarity:0,reasoning:"No suitable pattern found"}}let s=i[0],u={...s.pattern,usageCount:s.pattern.usageCount+1,lastUsedAt:new Date};this.registry.update(u.id,u);let c=performance.now()-a;return this.recordAdaptation(c),{success:!0,pattern:u,adaptationTimeMs:c,similarity:s.similarity,reasoning:`Pattern adapted from @ruvector/sona with ${s.similarity.toFixed(3)} similarity`}}catch(n){let o=performance.now()-a;return this.recordAdaptation(o),{success:!1,pattern:null,adaptationTimeMs:o,similarity:0,reasoning:`Adaptation failed: ${n.message}`}}}recallPattern(t,e,r){let a=this.createStateEmbedding(t),n=this.engine.findPatterns(a,1);for(let o of n){let i=this.findByRawPattern(o);if(i&&i.type===e&&i.domain===r)return i}return null}storePattern(t){this.registry.register(t);let e=this.engine.beginTrajectory(t.stateEmbedding),r=this.createActionEmbedding(t.action),a=new Array(r.length).fill(1),n=t.outcome.success?t.outcome.quality:-t.outcome.quality;this.engine.addTrajectoryStep(e,r,a,n),this.engine.endTrajectory(e,t.outcome.quality),this.registry.associateTrajectory(e,t.id)}storePatternsBatch(t){for(let e of t)this.storePattern(e)}createPattern(t,e,r,a,n,o){let i={id:`qesona-${Date.now()}-${Ct().slice(0,7)}`,type:a,domain:n,stateEmbedding:this.createStateEmbedding(t),action:e,outcome:r,confidence:.5,usageCount:0,createdAt:new Date,metadata:o};return this.storePattern(i),i}updatePattern(t,e,r){let a=this.registry.get(t);if(!a)return!1;let n=e?r:-r,i=a.confidence+.1*(n-a.confidence),s={...a,confidence:Math.max(0,Math.min(1,i)),usageCount:a.usageCount+1,lastUsedAt:new Date};return this.registry.update(t,s)}applyMicroLora(t){return this.engine.applyMicroLora(t)}applyBaseLora(t,e){return this.engine.applyBaseLora(t,e)}forceLearn(){return this.engine.forceLearn()}tick(){return this.engine.tick()}getAllPatterns(){return this.registry.getAll()}getPatternsByType(t){return this.registry.getByType(t)}getPatternsByDomain(t){return this.registry.getByDomain(t)}getStats(){let t=this.registry.getAll(),e=this.engine.getStats(),r={"test-generation":0,"defect-prediction":0,"coverage-optimization":0,"quality-assessment":0,"resource-allocation":0};for(let a of t)r[a.type]++;return{totalPatterns:t.length,patternsByType:r,avgAdaptationTimeMs:this.avgAdaptationTime(),minAdaptationTimeMs:this.minAdaptationTime(),maxAdaptationTimeMs:this.maxAdaptationTime(),totalAdaptations:this.totalAdaptations,cacheHitRate:this.totalAdaptations>0?this.cacheHits/this.totalAdaptations:0,engineStats:e}}clear(){this.registry.clear(),this.adaptationTimes=[],this.cacheHits=0,this.totalAdaptations=0}exportPatterns(){return this.registry.getAll()}importPatterns(t){this.clear(),this.storePatternsBatch(t)}getConfig(){return{...this.config}}setEnabled(t){this.engine.setEnabled(t)}isEnabled(){return this.engine.isEnabled()}createStateEmbedding(t){let e=t.features;if(e.length===0)return new Array(this.config.embeddingDim??384).fill(0);let r=Math.max(...e.map(Math.abs));if(r===0)return[...e];let a=e.map(o=>o/r),n=this.config.embeddingDim??384;return a.length>=n?a.slice(0,n):[...a,...new Array(n-a.length).fill(0)]}createActionEmbedding(t){let e=[],r=this.hashCode(t.type);if(e.push(r%1e3/1e3),typeof t.value=="number")e.push(Math.min(1,Math.max(-1,t.value)));else if(typeof t.value=="string"){let n=this.hashCode(t.value);e.push(n%1e3/1e3)}else if(Array.isArray(t.value))for(let n of t.value.slice(0,10))typeof n=="number"&&e.push(Math.min(1,Math.max(-1,n)));let a=this.config.embeddingDim??384;for(;e.length<a;)e.push(0);return e.slice(0,a)}findByRawPattern(t){let e=this.registry.getAll();for(let r of e)if(r.rawPattern?.patternType===t.id)return r}createQEPatternFromRaw(t,e,r){let a={centroid:t.centroid,clusterSize:1,totalWeight:1,avgQuality:t.avgQuality,createdAt:new Date().toISOString(),lastAccessed:new Date().toISOString(),accessCount:0,patternType:t.patternType};return{id:`qesona-${t.id}`,type:e,domain:r,stateEmbedding:t.centroid,action:{type:"learned",value:t.patternType},outcome:{reward:t.avgQuality,success:t.avgQuality>.5,quality:t.avgQuality},confidence:t.avgQuality,usageCount:0,createdAt:new Date,rawPattern:a}}calculateSimilarity(t,e){let r=Math.min(t.length,e.length),a=0,n=0,o=0;for(let s=0;s<r;s++)a+=t[s]*e[s],n+=t[s]*t[s],o+=e[s]*e[s];return(a/(Math.sqrt(n)*Math.sqrt(o)+1e-10)+1)/2}hashCode(t){let e=0;for(let r=0;r<t.length;r++)e=(e<<5)-e+t.charCodeAt(r),e=e|0;return Math.abs(e)}recordAdaptation(t){this.adaptationTimes.push(t),this.totalAdaptations++,this.adaptationTimes.length>1e3&&this.adaptationTimes.shift()}avgAdaptationTime(){return this.adaptationTimes.length===0?0:this.adaptationTimes.reduce((e,r)=>e+r,0)/this.adaptationTimes.length}minAdaptationTime(){return this.adaptationTimes.length===0?0:Math.min(...this.adaptationTimes)}maxAdaptationTime(){return this.adaptationTimes.length===0?0:Math.max(...this.adaptationTimes)}initThreeLoopEngine(t){this.threeLoopEngine=new C({dimension:this.config.embeddingDim??384,microLoraLr:this.config.microLoraLr??.001,ewcLambda:this.config.ewcLambda??1e3,...t},this.engine)}getThreeLoopEngine(){return this.threeLoopEngine}instantAdapt(t){return this.threeLoopEngine?this.threeLoopEngine.instantAdapt(t):null}recordOutcome(t,e){this.threeLoopEngine&&this.threeLoopEngine.recordOutcome(t,e)}backgroundConsolidate(){if(!this.threeLoopEngine)return null;let t=this.threeLoopEngine.backgroundConsolidate();if(t&&(t.consolidated||t.taskBoundaryDetected)&&this.fisherPersistFn)try{this.threeLoopEngine.persistFisher(this.fisherPersistFn,this.fisherDomain)}catch(e){console.warn("[QESONA] Fisher persistence failed:",e instanceof Error?e.message:e)}return t}setFisherPersistence(t,e){this.fisherPersistFn=t,this.fisherDomain=e}syncWithPeers(t){this.threeLoopEngine&&this.threeLoopEngine.syncWithPeers(t)}getEWCMetrics(){return this.threeLoopEngine?this.threeLoopEngine.getEWCMetrics():null}shouldConsolidate(){return this.threeLoopEngine?this.threeLoopEngine.shouldConsolidate():!1}getLocalPeerState(t,e){return this.threeLoopEngine?this.threeLoopEngine.getLocalPeerState(t,e):null}isThreeLoopEnabled(){return this.threeLoopEngine!==null}async verifyPerformance(t=1e3){let e=[],r={id:"test-state",features:new Array(384).fill(0).map(()=>G())};for(let s=0;s<t;s++){let u=performance.now();await this.adaptPattern(r,"test-generation","test-generation");let c=performance.now();e.push({iteration:s,timeMs:c-u})}let a=e.map(s=>s.timeMs),n=a.reduce((s,u)=>s+u,0)/a.length,o=Math.min(...a),i=Math.max(...a);return{targetMet:n<.05,avgTimeMs:n,minTimeMs:o,maxTimeMs:i,details:e}}};function Tt(l){return new v(l)}function Pt(l,t){return new v({...t,maxPatterns:t?.maxPatterns||5e3})}ot();et();var F=null,D=null,W=null,B=null,z=null,I=null,q=!1;try{let l=(O(),w(N));F=l.FlashAttention,D=l.DotProductAttention,W=l.MultiHeadAttention,B=l.HyperbolicAttention,z=l.LinearAttention,I=l.MoEAttention,q=!0}catch{}function Gt(){return q}function A(){if(!q)throw new Error("@ruvector/attention native module is not available on this platform. Install the appropriate optional dependency for your platform, or use a platform where pre-built binaries are available.")}var T={"test-similarity":{dim:384,strategy:"flash",blockSize:64},"code-embedding":{dim:512,strategy:"flash",blockSize:128},"defect-matching":{dim:384,strategy:"flash",blockSize:64},"coverage-analysis":{dim:384,strategy:"flash",blockSize:256},"pattern-adaptation":{dim:256,strategy:"flash",blockSize:32}},Kt={"test-similarity":{enabled:!0,microLoRARank:4,targetAdaptationMs:.05,patternCacheSize:1e3},"code-embedding":{enabled:!0,microLoRARank:2,targetAdaptationMs:.03,patternCacheSize:5e3},"defect-matching":{enabled:!0,microLoRARank:8,targetAdaptationMs:.05,patternCacheSize:2e3},"coverage-analysis":{enabled:!1,microLoRARank:2,targetAdaptationMs:.01,patternCacheSize:100},"pattern-adaptation":{enabled:!0,microLoRARank:2,targetAdaptationMs:.05,patternCacheSize:1e4}},$t={"test-similarity":{latency:{before:50,after:15},memory:{before:200,after:80},throughput:{min:1e3}},"code-embedding":{latency:{before:50,after:15},memory:{before:200,after:80},throughput:{min:2e3}},"defect-matching":{latency:{before:20,after:5},memory:{before:150,after:50},throughput:{min:500}},"coverage-analysis":{latency:{before:100,after:1},memory:{before:100,after:30},throughput:{min:1e4}},"pattern-adaptation":{latency:{before:2,after:.05},memory:{before:50,after:20},throughput:{min:2e4}}};function Zt(l){return l<=128?{queryChunkSize:128,kvChunkSize:128}:l<=256?{queryChunkSize:256,kvChunkSize:256}:l<=512?{queryChunkSize:512,kvChunkSize:512}:l<=1024?{queryChunkSize:1024,kvChunkSize:1024}:{queryChunkSize:1024,kvChunkSize:2048}}var E=class{static create(t){switch(A(),t.strategy){case"flash":return new F(t.dim,t.blockSize);case"dot-product":return new D(t.dim);case"multi-head":return new W(t.dim,t.numHeads??8);case"hyperbolic":return new B(t.dim,t.curvature);case"linear":return new z(t.dim,t.features);case"moe":return I.simple(t.dim,t.moeConfig?.numExperts??8,t.moeConfig?.topK??2);default:return new F(t.dim,t.blockSize)}}},L=class l{attention;config;workload;metrics=[];db=null;persistCount=0;static KV_NAMESPACE="attention-metrics";static KV_TTL=3600;static PERSIST_INTERVAL=10;constructor(t,e){this.workload=t;let r=T[t];this.config={...r,...e},this.attention=E.create(this.config)}async initialize(){try{this.db=K(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(t){console.warn("[QEFlashAttention] DB init failed, using memory-only:",j(t)),this.db=null}}async computeFlashAttention(t,e,r,a,n){let o=performance.now(),i=process.memoryUsage().heapUsed/1024/1024,s=this.toFloat32Array(t,a,n),u=this.splitMatrix(e,a,n),c=this.splitMatrix(r,a,n),m,g=this.attention;typeof g.compute=="function"?m=g.compute(s,u,c):(A(),m=new F(this.config.dim).compute(s,u,c));let h=performance.now(),d=process.memoryUsage().heapUsed/1024/1024;return this.metrics.push({timeMs:h-o,memoryMB:d-i,speedup:1,throughput:a*a/((h-o)/1e3),peakMemoryMB:d}),this.maybePersistToKv(),m}async computeBaselineAttention(t,e,r,a,n){let o=performance.now(),i=process.memoryUsage().heapUsed/1024/1024,s=new Float32Array(a*a),u=1/Math.sqrt(n);for(let h=0;h<a;h++)for(let d=0;d<a;d++){let b=0;for(let p=0;p<n;p++)b+=t[h*n+p]*e[d*n+p];s[h*a+d]=b*u}for(let h=0;h<a;h++){let d=h*a,b=d+a,p=s.subarray(d,b),tt=Math.max(...p),_=0;for(let y=0;y<a;y++)p[y]=Math.exp(p[y]-tt),_+=p[y];for(let y=0;y<a;y++)p[y]/=_}let c=new Float32Array(a*n);for(let h=0;h<a;h++)for(let d=0;d<a;d++){let b=s[h*a+d];for(let p=0;p<n;p++)c[h*n+p]+=b*r[d*n+p]}let m=performance.now(),g=process.memoryUsage().heapUsed/1024/1024;return c}async computeTestSimilarity(t,e,r=5){let a=e.length,n=t.length,o=new Float32Array(a*n),i=new Float32Array(a*n);for(let m=0;m<a;m++)o.set(t,m*n),i.set(e[m],m*n);let s=new Float32Array(a*n),u=await this.computeFlashAttention(o,i,s,a,n),c=[];for(let m=0;m<a;m++)c.push({index:m,similarity:u[m*n]});return c.sort((m,g)=>g.similarity-m.similarity),c.slice(0,r)}async generateCodeEmbedding(t,e){let r=t.length/e.length,a=e.length;return await this.computeFlashAttention(t,e,t,r,a)}async matchDefectPattern(t,e){let r=e.length,a=t.length,n=new Float32Array(r*a),o=new Float32Array(r*a);for(let c=0;c<r;c++)n.set(t,c*a),o.set(e[c],c*a);let i=new Float32Array(r*a),s=await this.computeFlashAttention(n,o,i,r,a),u=[];for(let c=0;c<r;c++)u.push({pattern:c,score:s[c*a]});return u.sort((c,m)=>m.score-c.score),u}getMetrics(){return[...this.metrics]}getAverageSpeedup(){return this.metrics.length===0?1:this.metrics.reduce((t,e)=>t+e.speedup,0)/this.metrics.length}getConfig(){return{...this.config}}updateConfig(t){this.config={...this.config,...t},this.attention=E.create(this.config)}changeStrategy(t){this.config.strategy=t,this.attention=E.create(this.config)}resetMetrics(){this.metrics=[]}getWorkload(){return this.workload}dispose(){this.metrics=[]}async persistToKv(){if(!this.db)return;let t=`attention-metrics-${this.workload}`,e={workload:this.workload,metrics:this.metrics.slice(-50),savedAt:Date.now()};await this.db.kvSet(t,e,l.KV_NAMESPACE,l.KV_TTL)}async loadFromKv(){if(!this.db)return;let t=`attention-metrics-${this.workload}`,e=await this.db.kvGet(t,l.KV_NAMESPACE);e?.metrics?.length&&(this.metrics=e.metrics)}maybePersistToKv(){this.persistCount++,this.persistCount>=l.PERSIST_INTERVAL&&(this.persistCount=0,this.persistToKv().catch(()=>{}))}toFloat32Array(t,e,r){return t.slice(0,r)}splitMatrix(t,e,r){let a=[];for(let n=0;n<e;n++)a.push(t.slice(n*r,(n+1)*r));return a}};async function Y(l,t){let e=new L(l,t);return await e.initialize(),e}function Jt(l){return{...T[l]}}function Xt(){return Object.keys(T)}function Yt(){return A(),F}function te(){return A(),D}function ee(){return A(),W}function re(){return A(),B}function ae(){return A(),z}function ne(){return A(),I}function ie(l){return l instanceof Float32Array?l:new Float32Array(l)}function oe(l){return Array.from(l)}async function se(l,t,e,r){let a=await Y(l),n=[],o=t[0].length,i=e.length;for(let s of t){let u=new Float32Array(i*o),c=new Float32Array(i*o),m=new Float32Array(i*o);u.set(s,0);for(let h=0;h<i;h++)c.set(e[h],h*o),m.set(r[h],h*o);let g=await a.computeFlashAttention(u,c,m,i,o);n.push(g.slice(0,o))}return a.dispose(),n}function We(){return{"@ruvector/sona":"^0.1.5","@ruvector/attention":"^0.1.4","@ruvector/gnn":"^0.1.22"}}function Be(){let l={sona:!1,attention:!1,gnn:!1,all:!1};try{k(),l.sona=!0}catch{}try{O(),l.attention=!0}catch{}try{let t=(it(),w(nt));t.init();let e=new Float32Array([.1,.2,.3]),r=[new Float32Array([.1,.2,.3]),new Float32Array([.4,.5,.6])],a=t.differentiableSearch(e,r,1,1);a&&Array.isArray(a.indices)&&Array.isArray(a.weights)&&(l.gnn=!0)}catch{}return l.all=l.sona&&l.attention&&l.gnn,l}async function ze(){let{initGNN:l}=await import("./gnn-wrapper-DFHTHLIZ.js");return[l(),"SONA: Ready (no initialization required)","Attention: Ready (no initialization required)"]}export{v as a,Tt as b,Pt as c,Gt as d,T as e,Kt as f,$t as g,Zt as h,L as i,Y as j,Jt as k,Xt as l,Yt as m,te as n,ee as o,re as p,ae as q,ne as r,ie as s,oe as t,se as u,We as v,Be as w,ze as x};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.4");process.exit(0)}
|
|
2
|
+
import{a as e,b as g,e as r}from"./chunk-RPYUKEAH.js";import{c as o}from"./chunk-C2HGOUEB.js";var L=o(()=>{"use strict";e();g();r()});export{L as a};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{a as G}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.4");process.exit(0)}
|
|
2
|
+
import{a as G}from"./chunk-7EL65Y27.js";import{a as q,e as C,f as z}from"./chunk-ZKWNZ3ZK.js";import{a as I}from"./chunk-4TZTGYBQ.js";import{a as H,b as _,c as U,d as j}from"./chunk-HKTNFHWI.js";import{a as A,b as W,f as N,i as O}from"./chunk-UJLSCJJS.js";import{d as B}from"./chunk-RRQEIGLS.js";import{b as v,d as L,f as M,g as P}from"./chunk-3RHIPCBG.js";import{a as K}from"./chunk-MDFXPCBO.js";import{c as D}from"./chunk-RPYUKEAH.js";import{b as w,d as Y}from"./chunk-4GJAYXB7.js";import{b as f,c as h}from"./chunk-VBYREHZI.js";import{a as Q,b,c as J}from"./chunk-F6AU2MAZ.js";import{f as T}from"./chunk-G72E5DL3.js";K();J();Y();var o=D.create("RealQEReasoningBank"),V={sqlite:{dbPath:".agentic-qe/memory.db",walMode:!0,useUnified:!0},embeddings:{modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0,enableCache:!0},enableLearning:!0,enableRouting:!0,enableGuidance:!0,hnsw:{M:16,efConstruction:200,efSearch:100},routingWeights:{similarity:.3,performance:.4,capabilities:.3},coherenceThreshold:.4},R=class{constructor(e={},t){this.coherenceService=t;this.qeConfig={...V,...e},this.sqliteStore=B(this.qeConfig.sqlite),this.asymmetricEngine=new G}qeConfig;sqliteStore;hnswIndex=null;patternIdMap=new Map;initialized=!1;stats={routingRequests:0,totalRoutingLatency:0,learningOutcomes:0,successfulOutcomes:0};routingLatencies=new I(1e3);asymmetricEngine;agentCapabilities={"qe-test-generator":{domains:["test-generation"],capabilities:["test-generation","tdd","bdd","unit-test","integration-test"],performanceScore:.85},"qe-coverage-analyzer":{domains:["coverage-analysis"],capabilities:["coverage-analysis","gap-detection","risk-scoring"],performanceScore:.92},"qe-coverage-specialist":{domains:["coverage-analysis"],capabilities:["sublinear-analysis","branch-coverage","mutation-testing"],performanceScore:.88},"qe-test-architect":{domains:["test-generation","coverage-analysis"],capabilities:["test-strategy","test-pyramid","architecture"],performanceScore:.9},"qe-api-contract-validator":{domains:["contract-testing"],capabilities:["contract-testing","openapi","graphql","pact"],performanceScore:.87},"qe-security-auditor":{domains:["security-compliance"],capabilities:["sast","dast","vulnerability","owasp"],performanceScore:.82},"qe-visual-tester":{domains:["visual-accessibility"],capabilities:["screenshot","visual-regression","percy","chromatic"],performanceScore:.8},"qe-a11y-ally":{domains:["visual-accessibility"],capabilities:["wcag","aria","screen-reader","contrast"],performanceScore:.85},"qe-performance-tester":{domains:["chaos-resilience"],capabilities:["load-testing","stress-testing","k6","artillery"],performanceScore:.83},"qe-flaky-investigator":{domains:["test-execution"],capabilities:["flaky-detection","test-stability","retry"],performanceScore:.78},"qe-chaos-engineer":{domains:["chaos-resilience"],capabilities:["chaos-testing","resilience","fault-injection"],performanceScore:.75}};async initialize(){if(this.initialized)return;let e=performance.now();await this.sqliteStore.initialize(),o.info("SQLite persistence initialized"),await this.initializeHNSW(),o.info("HNSW index initialized"),await this.loadPatternsIntoHNSW(),this.sqliteStore.getStats().totalPatterns===0&&(this.sqliteStore.hasAnyHistoricalData?.()??!1?o.error("qe_patterns table is EMPTY but historical data exists \u2014 possible data loss! Restore from backup instead of loading seed patterns. Skipping foundational pattern load to avoid masking data loss."):await this.loadFoundationalPatterns()),this.initialized=!0;let i=performance.now()-e;o.info("Fully initialized",{durationMs:Math.round(i)})}async initializeHNSW(){try{let e=await import("./hnswlib-node-4IA56UH4.js"),i=e.default?.HierarchicalNSW||e.HierarchicalNSW;if(typeof i!="function")throw new Error("HierarchicalNSW not found in hnswlib-node module");let n=i,a=P();this.hnswIndex=new n("cosine",a),this.hnswIndex.initIndex(1e5,this.qeConfig.hnsw.M,this.qeConfig.hnsw.efConstruction),this.hnswIndex.setEf(this.qeConfig.hnsw.efSearch),o.info("HNSW initialized",{dimension:a,M:this.qeConfig.hnsw.M})}catch(e){throw o.error("HNSW initialization failed",e instanceof Error?e:void 0),e}}async loadPatternsIntoHNSW(){if(!this.hnswIndex)return;let e=this.sqliteStore.getAllEmbeddings(),t=P(),i=0,n=0;for(let{patternId:a,embedding:s}of e){if(!s||!Array.isArray(s)||s.length!==t){n++;continue}let r=this.hnswIndex.getCurrentCount();this.hnswIndex.addPoint(s,r),this.patternIdMap.set(r,a),i++}n>0&&o.warn("Skipped invalid embeddings",{skipped:n,expectedDim:t}),o.info("Loaded patterns into HNSW index",{count:i})}async loadFoundationalPatterns(){let e=[{patternType:"test-template",name:"AAA Unit Test",description:"Arrange-Act-Assert pattern for clear, maintainable unit tests",template:{type:"code",content:`describe('{{className}}', () => {
|
|
3
3
|
describe('{{methodName}}', () => {
|
|
4
4
|
it('should {{expectedBehavior}}', {{async}} () => {
|
|
5
5
|
// Arrange
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{c as s,e 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.9.4");process.exit(0)}
|
|
2
|
+
import{c as s,e as t}from"./chunk-C2HGOUEB.js";var K={};t(K,{DEFAULT_FEATURE_FLAGS:()=>r,getRuVectorFeatureFlags:()=>i,getRvfMigrationStage:()=>H,initFeatureFlagsFromEnv:()=>z,isAgentMemoryBranchingEnabled:()=>I,isCNNVisualRegressionEnabled:()=>b,isCognitiveRoutingEnabled:()=>Y,isCoherenceActionGateEnabled:()=>A,isCoherenceGateEnabled:()=>f,isColdTierGNNEnabled:()=>m,isCrossDomainTransferEnabled:()=>N,isCusumDriftDetectionEnabled:()=>M,isDAGAttentionEnabled:()=>g,isDeltaEventSourcingEnabled:()=>F,isDeterministicDitherEnabled:()=>C,isEpropOnlineLearningEnabled:()=>Q,isEwcPlusPlusEnabled:()=>L,isFlashAttentionEnabled:()=>E,isGNNIndexEnabled:()=>R,isGrangerCausalityEnabled:()=>B,isGraphMAEEnabled:()=>x,isHDCFingerprintingEnabled:()=>D,isHnswHealthMonitorEnabled:()=>U,isHopfieldMemoryEnabled:()=>h,isHyperbolicHnswEnabled:()=>k,isMetaLearningEnabled:()=>P,isMetadataFilteringEnabled:()=>S,isNativeHNSWEnabled:()=>_,isNeuralRoutingEnabled:()=>T,isRVFPatternStoreEnabled:()=>V,isReasoningQECEnabled:()=>v,isRegretTrackingEnabled:()=>O,isReservoirReplayEnabled:()=>w,isSONAEnabled:()=>a,isSONAThreeLoopEnabled:()=>p,isSpectralSparsificationEnabled:()=>W,isSublinearSolverEnabled:()=>y,isTemporalCompressionEnabled:()=>c,isUnifiedHnswEnabled:()=>G,isWitnessChainEnabled:()=>d,resetRuVectorFeatureFlags:()=>u,setRuVectorFeatureFlags:()=>o,shouldLogMigrationMetrics:()=>l});function i(){return{...e}}function o(n){e={...e,...n}}function u(){e={...r}}function a(){return e.useQESONA}function E(){return e.useQEFlashAttention}function R(){return e.useQEGNNIndex}function l(){return e.logMigrationMetrics}function _(){return e.useNativeHNSW}function c(){return e.useTemporalCompression}function S(){return e.useMetadataFiltering}function C(){return e.useDeterministicDither}function T(){return e.useNeuralRouting}function p(){return e.useSONAThreeLoop}function N(){return e.useCrossDomainTransfer}function U(){return e.useHnswHealthMonitor}function O(){return e.useRegretTracking}function f(){return e.useCoherenceGate}function d(){return e.useWitnessChain}function b(){return e.useCNNVisualRegression}function g(){return e.useDAGAttention}function A(){return e.useCoherenceActionGate}function v(){return e.useReasoningQEC}function V(){return e.useRVFPatternStore}function I(){return e.useAgentMemoryBranching}function G(){return e.useUnifiedHnsw}function H(){return e.rvfMigrationStage}function D(){return e.useHDCFingerprinting}function M(){return e.useCusumDriftDetection}function F(){return e.useDeltaEventSourcing}function L(){return e.useEwcPlusPlusRegularization}function x(){return e.useGraphMAEEmbeddings}function h(){return e.useHopfieldMemory}function m(){return e.useColdTierGNN}function P(){return e.useMetaLearningEnhancements}function y(){return e.useSublinearSolver}function W(){return e.useSpectralSparsification}function w(){return e.useReservoirReplay}function Q(){return e.useEpropOnlineLearning}function B(){return e.useGrangerCausality}function Y(){return e.useCognitiveRouting}function k(){return e.useHyperbolicHnsw}function z(){let n={};process.env.RUVECTOR_USE_SONA!==void 0&&(n.useQESONA=process.env.RUVECTOR_USE_SONA==="true"),process.env.RUVECTOR_USE_FLASH_ATTENTION!==void 0&&(n.useQEFlashAttention=process.env.RUVECTOR_USE_FLASH_ATTENTION==="true"),process.env.RUVECTOR_USE_GNN_INDEX!==void 0&&(n.useQEGNNIndex=process.env.RUVECTOR_USE_GNN_INDEX==="true"),process.env.RUVECTOR_LOG_MIGRATION_METRICS!==void 0&&(n.logMigrationMetrics=process.env.RUVECTOR_LOG_MIGRATION_METRICS==="true"),process.env.RUVECTOR_USE_NATIVE_HNSW!==void 0&&(n.useNativeHNSW=process.env.RUVECTOR_USE_NATIVE_HNSW==="true"),process.env.RUVECTOR_USE_TEMPORAL_COMPRESSION!==void 0&&(n.useTemporalCompression=process.env.RUVECTOR_USE_TEMPORAL_COMPRESSION==="true"),process.env.RUVECTOR_USE_METADATA_FILTERING!==void 0&&(n.useMetadataFiltering=process.env.RUVECTOR_USE_METADATA_FILTERING==="true"),process.env.RUVECTOR_USE_DETERMINISTIC_DITHER!==void 0&&(n.useDeterministicDither=process.env.RUVECTOR_USE_DETERMINISTIC_DITHER==="true"),process.env.RUVECTOR_USE_NEURAL_ROUTING!==void 0&&(n.useNeuralRouting=process.env.RUVECTOR_USE_NEURAL_ROUTING==="true"),process.env.RUVECTOR_USE_SONA_THREE_LOOP!==void 0&&(n.useSONAThreeLoop=process.env.RUVECTOR_USE_SONA_THREE_LOOP==="true"),process.env.RUVECTOR_USE_CROSS_DOMAIN_TRANSFER!==void 0&&(n.useCrossDomainTransfer=process.env.RUVECTOR_USE_CROSS_DOMAIN_TRANSFER==="true"),process.env.RUVECTOR_USE_HNSW_HEALTH_MONITOR!==void 0&&(n.useHnswHealthMonitor=process.env.RUVECTOR_USE_HNSW_HEALTH_MONITOR==="true"),process.env.RUVECTOR_USE_REGRET_TRACKING!==void 0&&(n.useRegretTracking=process.env.RUVECTOR_USE_REGRET_TRACKING==="true"),process.env.RUVECTOR_USE_COHERENCE_GATE!==void 0&&(n.useCoherenceGate=process.env.RUVECTOR_USE_COHERENCE_GATE==="true"),process.env.RUVECTOR_USE_WITNESS_CHAIN!==void 0&&(n.useWitnessChain=process.env.RUVECTOR_USE_WITNESS_CHAIN==="true"),process.env.RUVECTOR_USE_CNN_VISUAL_REGRESSION!==void 0&&(n.useCNNVisualRegression=process.env.RUVECTOR_USE_CNN_VISUAL_REGRESSION==="true"),process.env.RUVECTOR_USE_DAG_ATTENTION!==void 0&&(n.useDAGAttention=process.env.RUVECTOR_USE_DAG_ATTENTION==="true"),process.env.RUVECTOR_USE_COHERENCE_ACTION_GATE!==void 0&&(n.useCoherenceActionGate=process.env.RUVECTOR_USE_COHERENCE_ACTION_GATE==="true"),process.env.RUVECTOR_USE_REASONING_QEC!==void 0&&(n.useReasoningQEC=process.env.RUVECTOR_USE_REASONING_QEC==="true"),process.env.RUVECTOR_USE_HDC_FINGERPRINTING!==void 0&&(n.useHDCFingerprinting=process.env.RUVECTOR_USE_HDC_FINGERPRINTING==="true"),process.env.RUVECTOR_USE_CUSUM_DRIFT_DETECTION!==void 0&&(n.useCusumDriftDetection=process.env.RUVECTOR_USE_CUSUM_DRIFT_DETECTION==="true"),process.env.RUVECTOR_USE_DELTA_EVENT_SOURCING!==void 0&&(n.useDeltaEventSourcing=process.env.RUVECTOR_USE_DELTA_EVENT_SOURCING==="true"),process.env.RUVECTOR_USE_EWC_PLUS_PLUS!==void 0&&(n.useEwcPlusPlusRegularization=process.env.RUVECTOR_USE_EWC_PLUS_PLUS==="true"),process.env.RUVECTOR_USE_META_LEARNING!==void 0&&(n.useMetaLearningEnhancements=process.env.RUVECTOR_USE_META_LEARNING==="true"),process.env.RUVECTOR_USE_SUBLINEAR_SOLVER!==void 0&&(n.useSublinearSolver=process.env.RUVECTOR_USE_SUBLINEAR_SOLVER==="true"),process.env.RUVECTOR_USE_SPECTRAL_SPARSIFICATION!==void 0&&(n.useSpectralSparsification=process.env.RUVECTOR_USE_SPECTRAL_SPARSIFICATION==="true"),process.env.RUVECTOR_USE_RESERVOIR_REPLAY!==void 0&&(n.useReservoirReplay=process.env.RUVECTOR_USE_RESERVOIR_REPLAY==="true"),process.env.RUVECTOR_USE_EPROP_ONLINE_LEARNING!==void 0&&(n.useEpropOnlineLearning=process.env.RUVECTOR_USE_EPROP_ONLINE_LEARNING==="true"),process.env.RUVECTOR_USE_GRANGER_CAUSALITY!==void 0&&(n.useGrangerCausality=process.env.RUVECTOR_USE_GRANGER_CAUSALITY==="true"),process.env.RUVECTOR_USE_COGNITIVE_ROUTING!==void 0&&(n.useCognitiveRouting=process.env.RUVECTOR_USE_COGNITIVE_ROUTING==="true"),process.env.RUVECTOR_USE_HYPERBOLIC_HNSW!==void 0&&(n.useHyperbolicHnsw=process.env.RUVECTOR_USE_HYPERBOLIC_HNSW==="true"),o(n)}var r,e,X=s(()=>{r={useQESONA:!0,useQEFlashAttention:!0,useQEGNNIndex:!0,logMigrationMetrics:!0,useNativeHNSW:!0,useTemporalCompression:!0,useMetadataFiltering:!0,useDeterministicDither:!0,useNeuralRouting:!0,useSONAThreeLoop:!0,useCrossDomainTransfer:!0,useHnswHealthMonitor:!0,useRegretTracking:!0,useCoherenceGate:!0,useWitnessChain:!0,useCNNVisualRegression:!0,useDAGAttention:!0,useCoherenceActionGate:!0,useReasoningQEC:!0,useRVFPatternStore:!0,useAgentMemoryBranching:!0,useUnifiedHnsw:!0,rvfMigrationStage:2,useHDCFingerprinting:!0,useCusumDriftDetection:!0,useDeltaEventSourcing:!0,useEwcPlusPlusRegularization:!0,useGraphMAEEmbeddings:!0,useHopfieldMemory:!0,useColdTierGNN:!0,useMetaLearningEnhancements:!0,useSublinearSolver:!0,useSpectralSparsification:!0,useReservoirReplay:!0,useEpropOnlineLearning:!0,useGrangerCausality:!0,useCognitiveRouting:!1,useHyperbolicHnsw:!1},e={...r}});export{r as a,i as b,o as c,u as d,a as e,E as f,R as g,l as h,_ as i,c as j,S as k,C as l,T as m,p as n,N as o,U as p,O as q,f as r,d as s,b as t,g as u,A as v,v as w,V as x,I as y,G as z,H as A,D as B,M as C,F as D,L as E,x as F,h as G,m as H,P as I,y as J,W as K,w as L,Q as M,B as N,Y as O,k as P,z as Q,K as R,X as S};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{i as 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.9.4");process.exit(0)}
|
|
2
|
+
import{i as c}from"./chunk-UJLSCJJS.js";import{a as p}from"./chunk-MDFXPCBO.js";import{c as m}from"./chunk-RPYUKEAH.js";import{b as g,d as E}from"./chunk-4GJAYXB7.js";import{a as l,b as _}from"./chunk-RN3SN4ZC.js";_();import b from"node:path";import{existsSync as h}from"node:fs";E();p();var T=m.create("metrics-tracker"),d=class{db=null;dbPath;initialized=!1;constructor(e=process.cwd()){this.dbPath=b.join(e,".agentic-qe","memory.db")}async initialize(){if(!this.initialized){if(!h(this.dbPath))throw new Error(`Database not found: ${this.dbPath}. Run "aqe init --auto" first.`);this.db=l(this.dbPath),this.ensureMetricsTable(),this.initialized=!0}}ensureMetricsTable(){this.db&&this.db.exec(`
|
|
3
3
|
CREATE TABLE IF NOT EXISTS learning_daily_snapshots (
|
|
4
4
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
5
5
|
snapshot_date TEXT NOT NULL UNIQUE,
|
|
@@ -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.9.
|
|
2
|
-
import{b as r,d 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.9.4");process.exit(0)}
|
|
2
|
+
import{b as r,d as f}from"./chunk-4GJAYXB7.js";import{a as d}from"./chunk-C2HGOUEB.js";f();import{existsSync as i,readFileSync as a}from"node:fs";import{join as s}from"node:path";import{execSync as p}from"node:child_process";var c=null,u=0,g=6e4;function F(){c=null,u=0}function x(e){if(c&&Date.now()-u<g)return c;let n=m(e);return c=n,u=Date.now(),n}function m(e){let n=w(e);if(n)return n;let o=h(e);if(o)return o;let t=v(e);return t||{available:!1}}function w(e){let n=s(e,".claude","mcp.json");if(i(n))try{let t=r(a(n,"utf-8"));if(t.mcpServers?.ruflo||t.mcpServers?.["claude-flow"])return{available:!0,method:"mcp-config"}}catch{}let o=s(e,".claude","settings.json");if(i(o))try{let t=r(a(o,"utf-8")),l=t.mcpServers||t.mcp?.servers||{};if(l.ruflo||l["claude-flow"]||l["@anthropic/claude-flow"])return{available:!0,method:"mcp-config"}}catch{}return null}function h(e){let n=s(e,"package.json");if(!i(n))return null;try{let o=r(a(n,"utf-8")),t={...o.dependencies,...o.devDependencies};if(t.ruflo||t["@claude-flow/cli"]||t["claude-flow"])return{available:!0,method:"npm-dependency"}}catch{}return null}function v(e){for(let n of["ruflo","@claude-flow/cli"])try{return{available:!0,method:"npx-cached",version:p(`npx --no-install ${n} --version`,{encoding:"utf-8",timeout:5e3,cwd:e,stdio:["pipe","pipe","pipe"]}).trim().match(/\d+\.\d+\.\d+[\w.-]*/)?.[0]}}catch{}return null}function b(){for(let e of["ruflo","@claude-flow/cli"])try{return d.resolve(`${e}/package.json`),e}catch{}return"ruflo"}function S(){return[" Claude Flow not found \u2014 running in standalone mode.",""," Claude Flow adds optional features:"," - SONA trajectory tracking (reinforcement learning)"," - 3-tier model routing (haiku / sonnet / opus)"," - Codebase pretrain analysis",""," To install later:"," npm install -g ruflo"," claude mcp add ruflo -- npx -y ruflo@3.5.18"," aqe init --auto --with-claude-flow"].join(`
|
|
3
3
|
`)}export{F as a,x as b,b as c,S as d};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{k as p,o as N}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.4");process.exit(0)}
|
|
2
|
+
import{k as p,o as N}from"./chunk-G6RTCJFY.js";N();import{createHash as y}from"crypto";var g="0".repeat(64);function m(s){return y("sha256").update(s,"utf-8").digest("hex")}function R(s){try{return y("shake256",{outputLength:32}).update(s,"utf-8").digest("hex")}catch{return m(s)}}function u(s,t){return s==="shake256"?R(t):m(t)}function f(s){return JSON.stringify({id:s.id,prev_hash:s.prev_hash,action_hash:s.action_hash,action_type:s.action_type,action_data:s.action_data,timestamp:s.timestamp,actor:s.actor})}var d=class{constructor(t,i){this.externalDb=t;this.keyManager=i??null}db=null;initialized=!1;keyManager=null;async initialize(){if(!this.initialized){if(this.externalDb)this.db=this.externalDb;else{let t=p();await t.initialize(),this.db=t.getDatabase()}this.ensureTable(),this.initialized=!0}}getDatabase(){return this.db}getKeyManager(){return this.keyManager}ensureTable(){if(!this.db)throw new Error("Database not initialized");this.db.exec(`
|
|
3
3
|
CREATE TABLE IF NOT EXISTS witness_chain (
|
|
4
4
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
5
5
|
prev_hash TEXT NOT NULL, action_hash TEXT NOT NULL, action_type TEXT 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.9.
|
|
2
|
-
import{f as d}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.4");process.exit(0)}
|
|
2
|
+
import{f as d}from"./chunk-YDJKQKQH.js";import{a as u,c as g}from"./chunk-F6AU2MAZ.js";g();var m=[{type:"email",pattern:/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,mask:n=>n[0]+"***@"+n.split("@")[1]},{type:"ssn",pattern:/\b\d{3}-\d{2}-\d{4}\b/g,mask:()=>"***-**-****"},{type:"credit-card",pattern:/\b(?:\d[ -]*?){13,19}\b/g,mask:n=>"****-****-****-"+n.replace(/\D/g,"").slice(-4)},{type:"phone",pattern:/\b(?:\+?1[-.\s]?)?(?:\(?\d{3}\)?[-.\s]?)?\d{3}[-.\s]?\d{4}\b/g,mask:n=>n.slice(0,3)+"***"+n.slice(-2)},{type:"api-key",pattern:/(?:key|token|api_key|apikey|secret|password|passwd|auth)=([A-Za-z0-9_\-]{16,})/gi,mask:()=>"***REDACTED***"}],y=class extends d{config={name:"qe/security/url-validate",description:"Validate URL security: checks for XSS/injection patterns, unsafe protocols, and scans URL query parameters for PII exposure (emails, SSNs, credit cards, API keys).",domain:"security-compliance",schema:this.buildSchema()};buildSchema(){return{type:"object",properties:{url:{type:"string",description:"URL to validate for security threats and PII exposure"},enablePII:{type:"boolean",description:"Enable PII exposure scanning in URL and query parameters",default:!0}},required:["url"]}}async execute(s,r){try{let e=this.validateURLSecurity(s.url),t=s.enablePII!==!1?this.scanForPII(s.url):{scanned:!1,found:!1,types:[],details:[]},c=e.issues.length+(t.found?t.types.length:0)===0?`URL passed all checks (security: clean, PII: ${t.scanned?"none found":"not scanned"})`:`URL has ${e.issues.length} security issue(s)${t.found?` and ${t.types.length} PII type(s) exposed in URL`:""}`;return{success:!0,data:{url:s.url,urlSecurity:e,piiExposure:t,summary:c}}}catch(e){return{success:!1,error:u(e)}}}validateURLSecurity(s){let r=[],e="none";try{let t=new URL(s);["http:","https:"].includes(t.protocol)||(r.push({type:"unsafe-protocol",description:`Protocol ${t.protocol} is not allowed`,severity:"high"}),e="high");let o=[/<script/i,/javascript:/i,/on\w+=/i,/data:text\/html/i];for(let i of o)if(i.test(s)){r.push({type:"xss",description:"Potential XSS pattern detected in URL",severity:"critical"}),e="critical";break}let c=[/'.*or.*'/i,/union.*select/i,/drop.*table/i,/;\s*--/i];for(let i of c)if(i.test(s)){r.push({type:"sql-injection",description:"Potential SQL injection pattern detected in URL",severity:"critical"}),e="critical";break}/\.\.[/\\]/.test(s)&&(r.push({type:"path-traversal",description:"Potential path traversal pattern (../) detected",severity:"high"}),e!=="critical"&&(e="high"));let a=["redirect","url","next","return","returnUrl","goto"];for(let i of a){let l=t.searchParams.get(i);l&&/^https?:\/\//.test(l)&&(r.push({type:"open-redirect",description:`Query parameter "${i}" contains an external URL \u2014 potential open redirect`,severity:"medium"}),e==="none"&&(e="medium"))}}catch{r.push({type:"invalid-url",description:"URL could not be parsed",severity:"critical"}),e="critical"}return{valid:r.length===0,riskLevel:e,issues:r}}scanForPII(s){let r=[],e=new Set,t;try{t=decodeURIComponent(s)}catch{t=s}let o="",c="";try{let a=new URL(t);o=a.search,c=a.pathname}catch{o=t}for(let{type:a,pattern:i,mask:l}of m){i.lastIndex=0;let p;for(;(p=i.exec(t))!==null;){e.add(a);let h=o.includes(p[0])?"query-parameter":c.includes(p[0])?"path":"url";r.push({type:a,location:h,masked:l(p[0])})}}return{scanned:!0,found:e.size>0,types:Array.from(e),details:r}}};export{y as a};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{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.9.4");process.exit(0)}
|
|
2
|
+
import{a as V}from"./chunk-VBXJBXMG.js";import{a as k,b as A,c as W,d as q}from"./chunk-HKTNFHWI.js";import{b as x,f as z,i as j}from"./chunk-UJLSCJJS.js";import{d as G}from"./chunk-RRQEIGLS.js";import{g as P}from"./chunk-MUX762XZ.js";import{a as M}from"./chunk-MDFXPCBO.js";import{c as E}from"./chunk-RPYUKEAH.js";import{b as T,c as S}from"./chunk-VBYREHZI.js";import{a as h,b as L,c as F}from"./chunk-F6AU2MAZ.js";import{S as Y,b as B}from"./chunk-MN2MYLVW.js";M();F();var C={enableLearning:!0,enableGuidance:!0,enableRouting:!0,embeddingDimension:384,useONNXEmbeddings:!0,maxRoutingCandidates:10,routingWeights:{similarity:.3,performance:.4,capabilities:.3},coherenceThreshold:.4};var w=[{patternType:"test-template",name:"AAA Unit Test",description:"Arrange-Act-Assert pattern for clear, maintainable unit tests",template:{type:"code",content:`describe('{{className}}', () => {
|
|
3
3
|
describe('{{methodName}}', () => {
|
|
4
4
|
it('should {{expectedBehavior}}', {{async}} () => {
|
|
5
5
|
// Arrange
|
|
@@ -311,4 +311,4 @@ On promotion:
|
|
|
311
311
|
`).all(),o=this.db.prepare(`
|
|
312
312
|
INSERT OR IGNORE INTO pattern_citations (source_pattern_id, target_pattern_id, weight, relationship)
|
|
313
313
|
VALUES (?, ?, 2.0, 'derivation')
|
|
314
|
-
`);for(let l of c)o.run(l.source_pattern_id,l.target_pattern_id).changes>0&&e++;return e}getEdgeCount(){return this.ensureSchema(),this.db.prepare("SELECT COUNT(*) as cnt FROM pattern_citations").get().cnt}};var g=E.create("QEReasoningBank"),Q=class{constructor(e,r,t={},a){this.memory=e;this.eventBus=r;this.coherenceService=a;this.config={...C,...t},t.rvfDualWriter&&(this.rvfDualWriter=t.rvfDualWriter),this.patternStore=V(e,{embeddingDimension:this.config.embeddingDimension,...t.patternStore})}config;patternStore;initialized=!1;sqliteStore=null;rvfDualWriter=null;getSqliteStore(){return this.sqliteStore||(this.sqliteStore=G(),this.sqliteStore.initialize().catch(e=>{g.warn("SQLitePatternStore init failed",{error:h(e)})})),this.sqliteStore}setRvfDualWriter(e){this.rvfDualWriter=e}stats={routingRequests:0,totalRoutingConfidence:0,learningOutcomes:0,successfulOutcomes:0};async initialize(){if(!this.initialized){await this.patternStore.initialize();try{let e=this.getSqliteStore();await e.initialize(),this.patternStore.setSqliteStore?.(e)}catch(e){g.warn("Failed to wire SQLitePatternStore into PatternStore",{error:h(e)})}await this.loadPretrainedPatterns(),this.initialized=!0;try{let e="reasoning-bank:cross-domain-seeded";if(!await this.memory.get(e))await this.memory.set(e,!0),await this.seedCrossDomainPatterns();else{let t=await this.patternStore.getStats();g.info("Cross-domain transfer already complete",{totalPatterns:t.totalPatterns})}}catch(e){g.warn("Cross-domain seeding failed (non-fatal)",{error:e})}g.info("Initialized")}}async loadPretrainedPatterns(){let e=await this.patternStore.getStats();if(e.totalPatterns>0){g.info("Found existing patterns",{totalPatterns:e.totalPatterns});return}for(let r of w)try{await this.patternStore.create(r)}catch(t){g.warn("Failed to load pattern",{name:r.name,error:t})}g.info("Loaded foundational patterns",{count:w.length})}async seedCrossDomainPatterns(){return this.initialized||await this.initialize(),K({searchPatterns:this.searchPatterns.bind(this),storePattern:this.storePattern.bind(this),patternStore:this.patternStore})}async storePattern(e){if(this.initialized||await this.initialize(),!this.config.enableLearning)return S(new Error("Pattern learning is disabled"));if(!e.embedding){let t=await this.embed(`${e.name} ${e.description} ${e.context?.tags?.join(" ")||""}`);e={...e,embedding:t}}let r=await this.patternStore.create(e);if(r.success&&(P().then(t=>t.append("PATTERN_CREATE",{patternId:r.value.id,domain:r.value.qeDomain,confidence:r.value.confidence,name:r.value.name},"reasoning-bank")).catch(t=>{g.warn("Witness chain PATTERN_CREATE failed",{error:h(t)})}),this.rvfDualWriter&&r.value.embedding&&r.value.embedding.length>0))try{this.rvfDualWriter.writePattern(r.value.id,r.value.embedding)}catch(t){g.warn("RVF dual-write failed (non-fatal)",{patternId:r.value.id,error:h(t)})}return r}async searchPatterns(e,r){this.initialized||await this.initialize();let t=e,a=!0;return typeof e=="string"&&(e.trim()===""?(a=!1,t=""):t=await this.embed(e)),this.patternStore.search(t,{...r,useVectorSearch:a})}async getPattern(e){return this.initialized||await this.initialize(),this.patternStore.get(e)}async recordOutcome(e){if(this.initialized||await this.initialize(),!this.config.enableLearning)return T(void 0);let r=await this.patternStore.recordUsage(e.patternId,e.success);try{this.getSqliteStore().recordUsage(e.patternId,e.success,e.metrics,e.feedback)}catch(t){g.warn("SQLite pattern usage persist failed",{error:h(t)})}if(r.success){this.stats.learningOutcomes++,e.success&&this.stats.successfulOutcomes++,P().then(s=>s.append("PATTERN_UPDATE",{patternId:e.patternId,success:e.success},"reasoning-bank")).catch(s=>{g.warn("Witness chain PATTERN_UPDATE failed",{error:h(s)})});let t=await this.getPattern(e.patternId),a=this.getPromotionDeps();t&&await X(t,a)&&(await H(e.patternId,a),g.info("Pattern promoted to long-term",{name:t.name}))}return r}getPromotionDeps(){return{patternStore:this.patternStore,coherenceService:this.coherenceService,eventBus:this.eventBus,coherenceThreshold:this.config.coherenceThreshold||.4,getSqliteStore:this.getSqliteStore.bind(this),rvfDualWriter:this.rvfDualWriter,searchPatterns:this.searchPatterns.bind(this),getPattern:this.getPattern.bind(this)}}async routeTask(e){if(this.initialized||await this.initialize(),!this.config.enableRouting)return S(new Error("Task routing is disabled"));this.stats.routingRequests++;try{let r=e.domain?[e.domain]:x(e.task);r.length===0&&r.push("test-generation");let t=await this.embed(e.task),a=await this.patternStore.search(t,{limit:this.config.maxRoutingCandidates,domain:r[0],useVectorSearch:!0}),s=a.success?a.value.map(d=>d.pattern):[],i=new Map;for(let[d,f]of Object.entries(R)){let m=s.filter(y=>f.domains.includes(y.qeDomain)).length;m>0&&i.set(d,m)}let c=D(r,e.capabilities,i,this.config.routingWeights),o=c[0],l=c.slice(1,4),p=[];if(this.config.enableGuidance&&r.length>0){let d=A(r[0],{framework:e.context?.framework,language:e.context?.language,includeAntiPatterns:!0});p.push(...d.slice(0,5))}this.stats.totalRoutingConfidence+=o.score;let u={recommendedAgent:o.agent,confidence:o.score,alternatives:l.map(d=>({agent:d.agent,score:d.score})),domains:r,patterns:s,guidance:p,reasoning:o.reasoning.join("; ")};return T(u)}catch(r){return S(L(r))}}getGuidance(e,r){return k(e)}generateContext(e,r){return q(e,r||{})}checkAntiPatterns(e,r){return W(e,r)}async embed(e){if(this.config.useONNXEmbeddings)try{let{computeRealEmbedding:r}=await import("./real-embeddings-
|
|
314
|
+
`);for(let l of c)o.run(l.source_pattern_id,l.target_pattern_id).changes>0&&e++;return e}getEdgeCount(){return this.ensureSchema(),this.db.prepare("SELECT COUNT(*) as cnt FROM pattern_citations").get().cnt}};var g=E.create("QEReasoningBank"),Q=class{constructor(e,r,t={},a){this.memory=e;this.eventBus=r;this.coherenceService=a;this.config={...C,...t},t.rvfDualWriter&&(this.rvfDualWriter=t.rvfDualWriter),this.patternStore=V(e,{embeddingDimension:this.config.embeddingDimension,...t.patternStore})}config;patternStore;initialized=!1;sqliteStore=null;rvfDualWriter=null;getSqliteStore(){return this.sqliteStore||(this.sqliteStore=G(),this.sqliteStore.initialize().catch(e=>{g.warn("SQLitePatternStore init failed",{error:h(e)})})),this.sqliteStore}setRvfDualWriter(e){this.rvfDualWriter=e}stats={routingRequests:0,totalRoutingConfidence:0,learningOutcomes:0,successfulOutcomes:0};async initialize(){if(!this.initialized){await this.patternStore.initialize();try{let e=this.getSqliteStore();await e.initialize(),this.patternStore.setSqliteStore?.(e)}catch(e){g.warn("Failed to wire SQLitePatternStore into PatternStore",{error:h(e)})}await this.loadPretrainedPatterns(),this.initialized=!0;try{let e="reasoning-bank:cross-domain-seeded";if(!await this.memory.get(e))await this.memory.set(e,!0),await this.seedCrossDomainPatterns();else{let t=await this.patternStore.getStats();g.info("Cross-domain transfer already complete",{totalPatterns:t.totalPatterns})}}catch(e){g.warn("Cross-domain seeding failed (non-fatal)",{error:e})}g.info("Initialized")}}async loadPretrainedPatterns(){let e=await this.patternStore.getStats();if(e.totalPatterns>0){g.info("Found existing patterns",{totalPatterns:e.totalPatterns});return}for(let r of w)try{await this.patternStore.create(r)}catch(t){g.warn("Failed to load pattern",{name:r.name,error:t})}g.info("Loaded foundational patterns",{count:w.length})}async seedCrossDomainPatterns(){return this.initialized||await this.initialize(),K({searchPatterns:this.searchPatterns.bind(this),storePattern:this.storePattern.bind(this),patternStore:this.patternStore})}async storePattern(e){if(this.initialized||await this.initialize(),!this.config.enableLearning)return S(new Error("Pattern learning is disabled"));if(!e.embedding){let t=await this.embed(`${e.name} ${e.description} ${e.context?.tags?.join(" ")||""}`);e={...e,embedding:t}}let r=await this.patternStore.create(e);if(r.success&&(P().then(t=>t.append("PATTERN_CREATE",{patternId:r.value.id,domain:r.value.qeDomain,confidence:r.value.confidence,name:r.value.name},"reasoning-bank")).catch(t=>{g.warn("Witness chain PATTERN_CREATE failed",{error:h(t)})}),this.rvfDualWriter&&r.value.embedding&&r.value.embedding.length>0))try{this.rvfDualWriter.writePattern(r.value.id,r.value.embedding)}catch(t){g.warn("RVF dual-write failed (non-fatal)",{patternId:r.value.id,error:h(t)})}return r}async searchPatterns(e,r){this.initialized||await this.initialize();let t=e,a=!0;return typeof e=="string"&&(e.trim()===""?(a=!1,t=""):t=await this.embed(e)),this.patternStore.search(t,{...r,useVectorSearch:a})}async getPattern(e){return this.initialized||await this.initialize(),this.patternStore.get(e)}async recordOutcome(e){if(this.initialized||await this.initialize(),!this.config.enableLearning)return T(void 0);let r=await this.patternStore.recordUsage(e.patternId,e.success);try{this.getSqliteStore().recordUsage(e.patternId,e.success,e.metrics,e.feedback)}catch(t){g.warn("SQLite pattern usage persist failed",{error:h(t)})}if(r.success){this.stats.learningOutcomes++,e.success&&this.stats.successfulOutcomes++,P().then(s=>s.append("PATTERN_UPDATE",{patternId:e.patternId,success:e.success},"reasoning-bank")).catch(s=>{g.warn("Witness chain PATTERN_UPDATE failed",{error:h(s)})});let t=await this.getPattern(e.patternId),a=this.getPromotionDeps();t&&await X(t,a)&&(await H(e.patternId,a),g.info("Pattern promoted to long-term",{name:t.name}))}return r}getPromotionDeps(){return{patternStore:this.patternStore,coherenceService:this.coherenceService,eventBus:this.eventBus,coherenceThreshold:this.config.coherenceThreshold||.4,getSqliteStore:this.getSqliteStore.bind(this),rvfDualWriter:this.rvfDualWriter,searchPatterns:this.searchPatterns.bind(this),getPattern:this.getPattern.bind(this)}}async routeTask(e){if(this.initialized||await this.initialize(),!this.config.enableRouting)return S(new Error("Task routing is disabled"));this.stats.routingRequests++;try{let r=e.domain?[e.domain]:x(e.task);r.length===0&&r.push("test-generation");let t=await this.embed(e.task),a=await this.patternStore.search(t,{limit:this.config.maxRoutingCandidates,domain:r[0],useVectorSearch:!0}),s=a.success?a.value.map(d=>d.pattern):[],i=new Map;for(let[d,f]of Object.entries(R)){let m=s.filter(y=>f.domains.includes(y.qeDomain)).length;m>0&&i.set(d,m)}let c=D(r,e.capabilities,i,this.config.routingWeights),o=c[0],l=c.slice(1,4),p=[];if(this.config.enableGuidance&&r.length>0){let d=A(r[0],{framework:e.context?.framework,language:e.context?.language,includeAntiPatterns:!0});p.push(...d.slice(0,5))}this.stats.totalRoutingConfidence+=o.score;let u={recommendedAgent:o.agent,confidence:o.score,alternatives:l.map(d=>({agent:d.agent,score:d.score})),domains:r,patterns:s,guidance:p,reasoning:o.reasoning.join("; ")};return T(u)}catch(r){return S(L(r))}}getGuidance(e,r){return k(e)}generateContext(e,r){return q(e,r||{})}checkAntiPatterns(e,r){return W(e,r)}async embed(e){if(this.config.useONNXEmbeddings)try{let{computeRealEmbedding:r}=await import("./real-embeddings-QN5BY3WS.js"),t=await r(e);return t.length!==this.config.embeddingDimension?U(t,this.config.embeddingDimension):t}catch(r){process.env.DEBUG&&g.warn("ONNX embeddings unavailable, using hash fallback",{error:h(r)})}return $(e,this.config.embeddingDimension)}async getStats(){this.initialized||await this.initialize();let e=await this.patternStore.getStats(),r={};for(let t of j)r[t]=e.byDomain[t]||0;return{totalPatterns:e.totalPatterns,byDomain:r,routingRequests:this.stats.routingRequests,avgRoutingConfidence:this.stats.routingRequests>0?this.stats.totalRoutingConfidence/this.stats.routingRequests:0,learningOutcomes:this.stats.learningOutcomes,patternSuccessRate:this.stats.learningOutcomes>0?this.stats.successfulOutcomes/this.stats.learningOutcomes:0,patternStoreStats:e}}async dispose(){if(await this.patternStore.dispose(),this.sqliteStore&&(this.sqliteStore.close(),this.sqliteStore=null),this.rvfDualWriter){try{this.rvfDualWriter.close()}catch{}this.rvfDualWriter=null}this.initialized=!1}};function Ge(n,e,r,t){return new Q(n,e,r,t)}export{C as a,w as b,R as c,D as d,_ as e,Q as f,Ge as g};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{a as h}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.4");process.exit(0)}
|
|
2
|
+
import{a as h}from"./chunk-MDFXPCBO.js";import{c as m}from"./chunk-RPYUKEAH.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.9.
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.4");process.exit(0)}
|
|
2
2
|
import{randomUUID as v}from"crypto";var m={"claude-opus-4-5-20251101":{input:15,output:75,provider:"claude"},"claude-sonnet-4-20250514":{input:3,output:15,provider:"claude"},"claude-3-5-haiku-20241022":{input:1,output:5,provider:"claude"},"claude-3-opus-20240229":{input:15,output:75,provider:"claude"},"claude-3-sonnet-20240229":{input:3,output:15,provider:"claude"},"claude-3-haiku-20240307":{input:.25,output:1.25,provider:"claude"},"gpt-4o":{input:5,output:15,provider:"openai"},"gpt-4o-mini":{input:.15,output:.6,provider:"openai"},"gpt-4-turbo":{input:10,output:30,provider:"openai"},"gpt-4":{input:30,output:60,provider:"openai"},"gpt-3.5-turbo":{input:.5,output:1.5,provider:"openai"},llama3:{input:0,output:0,provider:"ollama"},"llama3.1":{input:0,output:0,provider:"ollama"},codellama:{input:0,output:0,provider:"ollama"},mistral:{input:0,output:0,provider:"ollama"},mixtral:{input:0,output:0,provider:"ollama"},phi3:{input:0,output:0,provider:"ollama"},qwen2:{input:0,output:0,provider:"ollama"},"anthropic/claude-3.5-sonnet":{input:3,output:15,provider:"openrouter"},"anthropic/claude-3.5-sonnet:beta":{input:3,output:15,provider:"openrouter"},"anthropic/claude-3-opus":{input:15,output:75,provider:"openrouter"},"anthropic/claude-3-sonnet":{input:3,output:15,provider:"openrouter"},"anthropic/claude-3-haiku":{input:.25,output:1.25,provider:"openrouter"},"openai/gpt-4o":{input:5,output:15,provider:"openrouter"},"openai/gpt-4o-mini":{input:.15,output:.6,provider:"openrouter"},"openai/gpt-4-turbo":{input:10,output:30,provider:"openrouter"},"openai/gpt-3.5-turbo":{input:.5,output:1.5,provider:"openrouter"},"google/gemini-pro":{input:.125,output:.375,provider:"openrouter"},"google/gemini-pro-1.5":{input:3.5,output:10.5,provider:"openrouter"},"meta-llama/llama-3.1-70b-instruct":{input:.59,output:.79,provider:"openrouter"},"meta-llama/llama-3.1-8b-instruct":{input:.06,output:.06,provider:"openrouter"},"mistralai/mistral-large":{input:2,output:6,provider:"openrouter"},"mistralai/mixtral-8x7b-instruct":{input:.24,output:.24,provider:"openrouter"},"mistralai/mistral-7b-instruct":{input:.06,output:.06,provider:"openrouter"},"anthropic.claude-opus-4-5-v1:0":{input:15,output:75,provider:"bedrock"},"anthropic.claude-opus-4-v1:0":{input:15,output:75,provider:"bedrock"},"anthropic.claude-sonnet-4-5-v2:0":{input:3,output:15,provider:"bedrock"},"anthropic.claude-sonnet-4-v1:0":{input:3,output:15,provider:"bedrock"},"anthropic.claude-3-5-haiku-v1:0":{input:1,output:5,provider:"bedrock"},"anthropic.claude-3-opus-20240229-v1:0":{input:15,output:75,provider:"bedrock"},"anthropic.claude-3-sonnet-20240229-v1:0":{input:3,output:15,provider:"bedrock"},"anthropic.claude-3-haiku-20240307-v1:0":{input:.25,output:1.25,provider:"bedrock"},"anthropic.claude-3-5-sonnet-20241022-v2:0":{input:3,output:15,provider:"bedrock"},"azure/gpt-4o":{input:5,output:15,provider:"azure-openai"},"azure/gpt-4o-mini":{input:.15,output:.6,provider:"azure-openai"},"azure/gpt-4-turbo":{input:10,output:30,provider:"azure-openai"},"azure/gpt-4":{input:30,output:60,provider:"azure-openai"},"azure/gpt-35-turbo":{input:.5,output:1.5,provider:"azure-openai"},"azure/text-embedding-ada-002":{input:.1,output:0,provider:"azure-openai"},"azure/text-embedding-3-small":{input:.02,output:0,provider:"azure-openai"},"azure/text-embedding-3-large":{input:.13,output:0,provider:"azure-openai"},"gemini-pro":{input:.5,output:1.5,provider:"gemini"},"gemini-1.0-pro":{input:.5,output:1.5,provider:"gemini"},"gemini-1.5-pro":{input:3.5,output:10.5,provider:"gemini"},"gemini-1.5-pro-latest":{input:3.5,output:10.5,provider:"gemini"},"gemini-1.5-flash":{input:.075,output:.3,provider:"gemini"},"gemini-1.5-flash-latest":{input:.075,output:.3,provider:"gemini"},"gemini-2.0-flash-exp":{input:.075,output:.3,provider:"gemini"},"gemini-ultra":{input:7,output:21,provider:"gemini"},"gemini-1.0-ultra":{input:7,output:21,provider:"gemini"},"text-embedding-004":{input:.025,output:0,provider:"gemini"}},d=class c{records=[];alerts=[];maxRecords;alertCheckInterval;constructor(t=1e4){this.maxRecords=t}static calculateCost(t,r){let e=m[t];if(!e)return{inputCost:0,outputCost:0,totalCost:0,currency:"USD"};let i=r.promptTokens/1e6*e.input,o=r.completionTokens/1e6*e.output;return{inputCost:i,outputCost:o,totalCost:i+o,currency:"USD"}}static getCostPerToken(t){let r=m[t];return r?{input:r.input/1e6,output:r.output/1e6}:{input:0,output:0}}recordUsage(t,r,e,i,o){let n=c.calculateCost(r,e),p={timestamp:new Date,provider:t,model:r,usage:e,cost:n,requestId:i,metadata:o};return this.records.push(p),this.records.length>this.maxRecords&&(this.records=this.records.slice(-this.maxRecords)),this.checkAlerts(),n}getSummary(t){let r=new Date,e=this.getPeriodStart(r,t),i=r,o=this.records.filter(s=>s.timestamp>=e&&s.timestamp<=i),n={claude:0,openai:0,ollama:0,openrouter:0,bedrock:0,"azure-openai":0,gemini:0},p={},u=0,l=0;for(let s of o)u+=s.cost.totalCost,l+=s.usage.totalTokens,n[s.provider]+=s.cost.totalCost,p[s.model]=(p[s.model]||0)+s.cost.totalCost;return{period:t,periodStart:e,periodEnd:i,totalCost:u,byProvider:n,byModel:p,totalTokens:l,totalRequests:o.length}}getCurrentCost(t){return this.getSummary(t).totalCost}getTotalTokens(t){return this.getSummary(t).totalTokens}getUsageByProvider(t,r="all"){let e=this.getPeriodStart(new Date,r),i=this.records.filter(u=>u.provider===t&&u.timestamp>=e),o={},n=0,p=0;for(let u of i)n+=u.cost.totalCost,p+=u.usage.totalTokens,o[u.model]||(o[u.model]={cost:0,tokens:0,requests:0}),o[u.model].cost+=u.cost.totalCost,o[u.model].tokens+=u.usage.totalTokens,o[u.model].requests+=1;return{totalCost:n,totalTokens:p,totalRequests:i.length,models:o}}addAlert(t,r,e){let i=`alert-${Date.now()}-${v().slice(0,12)}`;return this.alerts.push({threshold:t,period:r,onThreshold:e,active:!0}),this.alertCheckInterval||(this.alertCheckInterval=setInterval(()=>this.checkAlerts(),6e4)),i}removeAlert(t){return t>=0&&t<this.alerts.length?(this.alerts.splice(t,1),this.alerts.length===0&&this.alertCheckInterval&&(clearInterval(this.alertCheckInterval),this.alertCheckInterval=void 0),!0):!1}getRecords(){return[...this.records]}importRecords(t){for(let r of t)r.timestamp=new Date(r.timestamp),this.records.push(r);this.records.length>this.maxRecords&&(this.records=this.records.slice(-this.maxRecords))}clear(){this.records=[]}getRecentRequests(t=10){return this.records.slice(-t)}estimateCost(t,r,e){return c.calculateCost(t,{promptTokens:r,completionTokens:e,totalTokens:r+e})}wouldExceedLimit(t,r,e,i,o){let n=this.getCurrentCost(o),p=this.estimateCost(t,r,e);return n+p.totalCost>i}dispose(){this.alertCheckInterval&&(clearInterval(this.alertCheckInterval),this.alertCheckInterval=void 0)}getPeriodStart(t,r){let e=new Date(t);switch(r){case"minute":e.setSeconds(0,0),e.setMinutes(e.getMinutes()-1);break;case"hour":e.setMinutes(0,0,0),e.setHours(e.getHours()-1);break;case"day":e.setHours(0,0,0,0);break;case"week":e.setHours(0,0,0,0),e.setDate(e.getDate()-7);break;case"month":e.setHours(0,0,0,0),e.setDate(1);break;case"all":return new Date(0)}return e}checkAlerts(){for(let t of this.alerts){if(!t.active)continue;let r=this.getSummary(t.period);if(r.totalCost>=t.threshold){t.active=!1;try{t.onThreshold(r)}catch(e){console.error("Cost alert callback error:",e)}}}}},a;function h(){return a||(a=new d),a}function b(){a&&(a.dispose(),a=void 0)}export{m as a,d as b,h as c,b as d};
|