agentic-qe 3.10.3 → 3.10.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude/skills/qcsd-development-swarm/SKILL.md +27 -6
- package/.claude/skills/skills-manifest.json +1 -1
- package/CHANGELOG.md +104 -0
- package/assets/skills/skills-manifest.json +1 -1
- package/dist/arena/arena.d.ts +68 -0
- package/dist/arena/arena.js +169 -0
- package/dist/arena/mutator.d.ts +23 -0
- package/dist/arena/mutator.js +112 -0
- package/dist/arena/rng.d.ts +15 -0
- package/dist/arena/rng.js +34 -0
- package/dist/arena/runner.d.ts +44 -0
- package/dist/arena/runner.js +79 -0
- package/dist/cli/bundle.js +7 -7
- package/dist/cli/chunks/adapter-XZVL3DHO.js +2 -0
- package/dist/cli/chunks/{agent-booster-wasm-NGC6LSQP.js → agent-booster-wasm-3BC5LIEB.js} +2 -2
- package/dist/cli/chunks/{agent-handler-P2IJE4GK.js → agent-handler-QLXWVZZF.js} +2 -2
- package/dist/cli/chunks/{agent-memory-branch-JXRJ5GKQ.js → agent-memory-branch-3U5PDYW7.js} +2 -2
- package/dist/cli/chunks/aqe-learning-engine-YIL25K6W.js +2 -0
- package/dist/cli/chunks/arena-BMJQK4RD.js +18 -0
- package/dist/cli/chunks/arena-XENAGV4I.js +4 -0
- package/dist/cli/chunks/audit-WPIRUJNZ.js +3 -0
- package/dist/cli/chunks/base-YCYV23Q3.js +2 -0
- package/dist/cli/chunks/{hnswlib-node-64EGGWIC.js → better-sqlite3-6AGIBSVE.js} +2 -2
- package/dist/cli/chunks/{brain-handler-SACNDFSW.js → brain-handler-PHSWG5PR.js} +3 -3
- package/dist/cli/chunks/{branch-enumerator-LFOTVUDA.js → branch-enumerator-LNSYT34I.js} +2 -2
- package/dist/cli/chunks/{browser-FK7PRF3W.js → browser-M5BVQMBI.js} +2 -2
- package/dist/cli/chunks/browser-workflow-ALCOCRA2.js +2 -0
- package/dist/cli/chunks/{chunk-ZXQNE4QV.js → chunk-24A7KD3D.js} +1 -1
- package/dist/cli/chunks/{chunk-6Q2PPOOF.js → chunk-253TDTPH.js} +1 -1
- package/dist/cli/chunks/{chunk-MC7K44M4.js → chunk-2RLRPKCG.js} +2 -2
- package/dist/cli/chunks/{chunk-VRXY4T22.js → chunk-2UQWVF4P.js} +2 -2
- package/dist/cli/chunks/{chunk-UDV4YB42.js → chunk-2Z7HIT5I.js} +1 -1
- package/dist/cli/chunks/{chunk-CTDO2UB2.js → chunk-3BGGNHHZ.js} +1 -1
- package/dist/cli/chunks/{chunk-HWM2XJ3P.js → chunk-3JWV4GE6.js} +2 -2
- package/dist/cli/chunks/{chunk-BT3QLWII.js → chunk-3KGUP2SD.js} +2 -2
- package/dist/cli/chunks/{chunk-T63EK6GH.js → chunk-3WOQY6UL.js} +2 -2
- package/dist/cli/chunks/{chunk-QM65UGPV.js → chunk-4FTO3TPH.js} +2 -2
- package/dist/cli/chunks/{chunk-WWD5IWTV.js → chunk-4K7T6AKM.js} +1 -1
- package/dist/cli/chunks/{chunk-XTP2GHI7.js → chunk-4Z7XH4JE.js} +2 -2
- package/dist/cli/chunks/{chunk-FND6V2RV.js → chunk-54IPDQIZ.js} +8 -8
- package/dist/cli/chunks/{chunk-KTRB3L53.js → chunk-56RA6YPN.js} +2 -2
- package/dist/cli/chunks/{chunk-7YYTTWGY.js → chunk-5D7GLMT3.js} +1 -1
- package/dist/cli/chunks/{chunk-M5CDW2ZH.js → chunk-66LOFIBP.js} +2 -2
- package/dist/cli/chunks/{chunk-3X2ZQ55B.js → chunk-6SAU7GXO.js} +3 -3
- package/dist/cli/chunks/{chunk-DF3MJ2YL.js → chunk-75MP7JMV.js} +1 -1
- package/dist/cli/chunks/{chunk-RTDHWOAG.js → chunk-7DU35D4M.js} +1 -1
- package/dist/cli/chunks/{chunk-Q7EBD24B.js → chunk-7JZCEQFR.js} +1 -1
- package/dist/cli/chunks/{chunk-JXIPRMAY.js → chunk-A3BDPU5F.js} +4 -4
- package/dist/cli/chunks/{chunk-I42R57ON.js → chunk-A7HGS7FW.js} +2 -2
- package/dist/cli/chunks/{chunk-NNZMEYLT.js → chunk-AMBIOEMO.js} +1 -1
- package/dist/cli/chunks/{chunk-BO2OV2RH.js → chunk-AVQD7KEN.js} +2 -2
- package/dist/cli/chunks/{chunk-6GCOIIHY.js → chunk-AZCKTAUI.js} +2 -2
- package/dist/cli/chunks/{chunk-GL3HZN3O.js → chunk-B4F5EPNR.js} +1 -1
- package/dist/cli/chunks/{chunk-HAO3SPOE.js → chunk-BB7MEGXD.js} +2 -2
- package/dist/cli/chunks/{chunk-VDTFRMES.js → chunk-BSRCL6RU.js} +2 -2
- package/dist/cli/chunks/{chunk-RZCAA2PZ.js → chunk-CS3UB2OL.js} +1 -1
- package/dist/cli/chunks/{chunk-4OUAHZX2.js → chunk-CTG3GJIM.js} +2 -2
- package/dist/cli/chunks/{chunk-BWP3UVPE.js → chunk-CUAM34RQ.js} +3 -3
- package/dist/cli/chunks/chunk-CUY2EUSQ.js +2 -0
- package/dist/cli/chunks/{chunk-X2B7SANM.js → chunk-D3Q4443B.js} +1 -1
- package/dist/cli/chunks/{chunk-5IBJURYB.js → chunk-D4WDJ4ZF.js} +2 -2
- package/dist/cli/chunks/chunk-D7NKRCIL.js +2 -0
- package/dist/cli/chunks/{chunk-JP63XACW.js → chunk-DBR4TQPK.js} +2 -2
- package/dist/cli/chunks/{chunk-FLTPHVZ3.js → chunk-DIJ74M7V.js} +1 -1
- package/dist/cli/chunks/{chunk-PFCAMX6H.js → chunk-DJQYZ4RZ.js} +1 -1
- package/dist/cli/chunks/{chunk-5LON3MLI.js → chunk-DN65ILSI.js} +2 -2
- package/dist/cli/chunks/{chunk-6ZK24V2Y.js → chunk-DWLGFYXV.js} +2 -2
- package/dist/cli/chunks/{chunk-5EWWA4QP.js → chunk-EIL7FQC4.js} +6 -6
- package/dist/cli/chunks/{chunk-IRR7YA3Q.js → chunk-FE3FGMNB.js} +2 -2
- package/dist/cli/chunks/{chunk-ADV4DH3W.js → chunk-FLYFNNSN.js} +3 -3
- package/dist/cli/chunks/{chunk-SWOG3PBD.js → chunk-FNJZBIR3.js} +2 -2
- package/dist/cli/chunks/chunk-FPWA73N6.js +2 -0
- package/dist/cli/chunks/{chunk-NEYYLAYS.js → chunk-FW3C4LWU.js} +2 -2
- package/dist/cli/chunks/{chunk-5G5AAEFF.js → chunk-G4GX6YKX.js} +2 -2
- package/dist/cli/chunks/{chunk-NNVXHC74.js → chunk-G5UIGH4C.js} +3 -3
- package/dist/cli/chunks/{chunk-QEODION5.js → chunk-G6FP3S3G.js} +2 -2
- package/dist/cli/chunks/{chunk-ZG4P3DTL.js → chunk-GDUGW6FZ.js} +2 -2
- package/dist/cli/chunks/{chunk-GJUGSH7T.js → chunk-GKG6IQP6.js} +3 -3
- package/dist/cli/chunks/chunk-GMU7P5O3.js +2 -0
- package/dist/cli/chunks/{chunk-NRCL3WCP.js → chunk-GTVXVYKE.js} +2 -2
- package/dist/cli/chunks/{chunk-2ULVCLOW.js → chunk-HHEHGERJ.js} +2 -2
- package/dist/cli/chunks/{chunk-6FL3GN4T.js → chunk-HKJ3LG3N.js} +2 -2
- package/dist/cli/chunks/{chunk-E2BJT6A7.js → chunk-HNYSBE5J.js} +2 -2
- package/dist/cli/chunks/{chunk-JTZ3Q2QS.js → chunk-HPKYIK7R.js} +2 -2
- package/dist/cli/chunks/{chunk-GHNNJHH3.js → chunk-HRORJ352.js} +2 -2
- package/dist/cli/chunks/{chunk-5ER3COX3.js → chunk-IIFCTJOF.js} +2 -2
- package/dist/cli/chunks/{chunk-UIJFU4KD.js → chunk-IOE6LDPF.js} +2 -2
- package/dist/cli/chunks/{chunk-JD2PG4KS.js → chunk-IRS4HKAR.js} +1 -1
- package/dist/cli/chunks/{chunk-VIWIO27R.js → chunk-IT7CEHAJ.js} +2 -2
- package/dist/cli/chunks/{chunk-JE3C7JYN.js → chunk-IUKERFLT.js} +1 -1
- package/dist/cli/chunks/{chunk-YDKYLNKZ.js → chunk-IVKSZNMI.js} +1 -1
- package/dist/cli/chunks/{chunk-3RZL4QTT.js → chunk-IWRORKD7.js} +2 -2
- package/dist/cli/chunks/{chunk-NZHOKLII.js → chunk-J533CJUN.js} +3 -3
- package/dist/cli/chunks/{chunk-5SGEOO2F.js → chunk-JPOEI7CJ.js} +2 -2
- package/dist/cli/chunks/{chunk-MBSJ5G4I.js → chunk-JY7T2AQQ.js} +4 -4
- package/dist/cli/chunks/{chunk-4QFAUSWQ.js → chunk-K5KKZWED.js} +2 -2
- package/dist/cli/chunks/{chunk-L74CHKFR.js → chunk-KIMJPTHD.js} +2 -2
- package/dist/cli/chunks/{chunk-N7IBYDW5.js → chunk-MEN3UW7W.js} +1 -1
- package/dist/cli/chunks/{chunk-UHDBM7QS.js → chunk-MFQIJ3HV.js} +2 -2
- package/dist/cli/chunks/{chunk-SL6YZAT4.js → chunk-MGCW5FWH.js} +2 -2
- package/dist/cli/chunks/{chunk-U6UK3UMX.js → chunk-MIMJVKJJ.js} +3 -3
- package/dist/cli/chunks/{chunk-7ZSPCGTI.js → chunk-MJRYHHOG.js} +2 -2
- package/dist/cli/chunks/{chunk-FU77CDEM.js → chunk-MRXKIXVV.js} +2 -2
- package/dist/cli/chunks/{chunk-DY5KEOHX.js → chunk-MWPFUBXS.js} +2 -2
- package/dist/cli/chunks/{chunk-C6BBRM2J.js → chunk-N2TJXGHG.js} +1 -1
- package/dist/cli/chunks/{chunk-MQOFFRTA.js → chunk-NGSA53GC.js} +2 -2
- package/dist/cli/chunks/{chunk-YXH2CVAF.js → chunk-NKW7VOZV.js} +1 -1
- package/dist/cli/chunks/{chunk-YIYV2JB6.js → chunk-O5OOUMBB.js} +2 -2
- package/dist/cli/chunks/{chunk-HM523MTQ.js → chunk-OATHXZYW.js} +1 -1
- package/dist/cli/chunks/{chunk-WPVCSFDA.js → chunk-OJNG6ZXG.js} +2 -2
- package/dist/cli/chunks/{chunk-7SEHQTYD.js → chunk-PGNQR2VM.js} +1 -1
- package/dist/cli/chunks/{chunk-UZL366ZI.js → chunk-PPM5D7LH.js} +1 -1
- package/dist/cli/chunks/{chunk-ERYMAYJW.js → chunk-PYBVFG6T.js} +2 -2
- package/dist/cli/chunks/{chunk-FJGSEPFL.js → chunk-Q6BKJZTG.js} +2 -2
- package/dist/cli/chunks/chunk-QAW6RVAR.js +699 -0
- package/dist/cli/chunks/chunk-QTDZS4U6.js +2 -0
- package/dist/cli/chunks/{chunk-USFZ4IJD.js → chunk-R573V37S.js} +15 -15
- package/dist/cli/chunks/{chunk-Z2K5IZM6.js → chunk-RCAIOTIF.js} +2 -2
- package/dist/cli/chunks/{chunk-7RMZAVGO.js → chunk-RFNEEDPQ.js} +2 -2
- package/dist/cli/chunks/{chunk-IL2KOW5W.js → chunk-RFVZMNYX.js} +2 -2
- package/dist/cli/chunks/{chunk-B5MMDMH6.js → chunk-RLU7764Y.js} +2 -2
- package/dist/cli/chunks/chunk-RLZDXQNM.js +2 -0
- package/dist/cli/chunks/{chunk-QWG76RHA.js → chunk-RONMVGCT.js} +2 -2
- package/dist/cli/chunks/{chunk-X3RJ6SFC.js → chunk-RR55MLD4.js} +1 -1
- package/dist/cli/chunks/{chunk-PL5SLO2W.js → chunk-RUQV3BTV.js} +1 -1
- package/dist/cli/chunks/{chunk-NXPFGPHV.js → chunk-RZ7D5SHS.js} +1 -1
- package/dist/cli/chunks/{chunk-3LRK7PYN.js → chunk-S73KENCH.js} +2 -2
- package/dist/cli/chunks/{chunk-3HBWDG62.js → chunk-S7FGTHFE.js} +2 -2
- package/dist/cli/chunks/{chunk-CAMEFWRK.js → chunk-S7HQOGVD.js} +1 -1
- package/dist/cli/chunks/{chunk-PZHZPX3O.js → chunk-SK6YRNXI.js} +2 -2
- package/dist/cli/chunks/{chunk-JTF6D2RJ.js → chunk-SXQIH2QA.js} +2 -2
- package/dist/cli/chunks/{chunk-6B4S7PKP.js → chunk-TISBFSDJ.js} +1 -1
- package/dist/cli/chunks/{chunk-72LE6PHL.js → chunk-TMD6IC6D.js} +2 -2
- package/dist/cli/chunks/{chunk-YDDZJCKY.js → chunk-TMTLWSSA.js} +1 -1
- package/dist/cli/chunks/{chunk-HQJMCTWN.js → chunk-UOIT5JZ6.js} +2 -2
- package/dist/cli/chunks/{chunk-OPDTDKN3.js → chunk-UTORITJT.js} +2 -2
- package/dist/cli/chunks/{chunk-3JAOFKEU.js → chunk-VB7DZVCI.js} +1 -1
- package/dist/cli/chunks/{chunk-2L73WXA4.js → chunk-VC256KH2.js} +2 -2
- package/dist/cli/chunks/{chunk-SNTMAVPH.js → chunk-VESYE5YO.js} +3 -3
- package/dist/cli/chunks/{chunk-YYAPO3CU.js → chunk-VKWDMOR4.js} +2 -2
- package/dist/cli/chunks/{chunk-HRLXU4LH.js → chunk-VWN66V7U.js} +2 -2
- package/dist/cli/chunks/{chunk-CNEWYJKT.js → chunk-W5C7R2LS.js} +3 -3
- package/dist/cli/chunks/{chunk-JLL27IGU.js → chunk-W7KGHW4T.js} +2 -2
- package/dist/cli/chunks/{chunk-H56AROF2.js → chunk-WFZ4DRIC.js} +2 -2
- package/dist/cli/chunks/{chunk-4CYLSXA6.js → chunk-WFZUKXV5.js} +2 -2
- package/dist/cli/chunks/{chunk-AEJVOJPT.js → chunk-X4B3R3ZZ.js} +2 -2
- package/dist/cli/chunks/{chunk-KG5SM36Y.js → chunk-XI6ZZMX7.js} +1 -1
- package/dist/cli/chunks/{chunk-R5ONQAQL.js → chunk-YEO2Z3UX.js} +2 -2
- package/dist/cli/chunks/{chunk-D2FBUOAR.js → chunk-YZD4VIE5.js} +1 -1
- package/dist/cli/chunks/{chunk-U7NMPZE2.js → chunk-YZFNPTGN.js} +2 -2
- package/dist/cli/chunks/{chunk-OX4R55T3.js → chunk-ZCYKWEAM.js} +2 -2
- package/dist/cli/chunks/{chunk-OG7CWWFR.js → chunk-ZG3DSWUA.js} +1 -1
- package/dist/cli/chunks/{chunk-EETVN2OJ.js → chunk-ZS4BGJJV.js} +1 -1
- package/dist/cli/chunks/{chunk-LZ6TNTGO.js → chunk-ZT7JSFGT.js} +2 -2
- package/dist/cli/chunks/{chunk-HMFEPKAR.js → chunk-ZTC64OJE.js} +2 -2
- package/dist/cli/chunks/{chunk-RNF47IJ5.js → chunk-ZUBJBAUD.js} +15 -15
- package/dist/cli/chunks/{ci-AWZ3S5OT.js → ci-M2BSQBLL.js} +2 -2
- package/dist/cli/chunks/{ci-output-JLCYTIMT.js → ci-output-Z4TMK6GZ.js} +2 -2
- package/dist/cli/chunks/{circuit-breaker-BJDKBDIL.js → circuit-breaker-E3G4GGWB.js} +2 -2
- package/dist/cli/chunks/{claude-flow-setup-KKOP5ZMO.js → claude-flow-setup-MASRQU54.js} +2 -2
- package/dist/cli/chunks/client-RPB6RYVY.js +2 -0
- package/dist/cli/chunks/{cline-installer-7M525SEA.js → cline-installer-P3BWAKQA.js} +2 -2
- package/dist/cli/chunks/{code-27SUVJDO.js → code-7HY5HQAV.js} +2 -2
- package/dist/cli/chunks/{code-index-extractor-TTQQZLAK.js → code-index-extractor-MBVKLOEU.js} +2 -2
- package/dist/cli/chunks/{codex-installer-GHNGNPKP.js → codex-installer-WZ6QO2PH.js} +2 -2
- package/dist/cli/chunks/{completions-JPJD24DG.js → completions-TOJC2UFP.js} +2 -2
- package/dist/cli/chunks/{complexity-analyzer-Q74EJV33.js → complexity-analyzer-QYVDIAAW.js} +2 -2
- package/dist/cli/chunks/{continuedev-installer-ULTRDIML.js → continuedev-installer-J72CV7P4.js} +2 -2
- package/dist/cli/chunks/{copilot-installer-EK52X4CG.js → copilot-installer-ACDA3GEA.js} +2 -2
- package/dist/cli/chunks/core-handlers-QFJT5NX6.js +2 -0
- package/dist/cli/chunks/{cost-tracker-2GKBRYXL.js → cost-tracker-BAYQJELE.js} +2 -2
- package/dist/cli/chunks/{coverage-YCLC3W2A.js → coverage-QD3XJV6W.js} +3 -3
- package/dist/cli/chunks/cross-domain-router-5GJ7WZKX.js +2 -0
- package/dist/cli/chunks/{cursor-installer-B3ALFW5E.js → cursor-installer-SPGZ4TQM.js} +2 -2
- package/dist/cli/chunks/{daemon-ZKEBVLJA.js → daemon-3EVOL2UH.js} +3 -3
- package/dist/cli/chunks/daemon-N4JKD5SO.js +10 -0
- package/dist/cli/chunks/{dag-attention-scheduler-OQPJ6ULA.js → dag-attention-scheduler-3BVLL3L5.js} +2 -2
- package/dist/cli/chunks/{detect-YMYIQH3Q.js → detect-SWACKB45.js} +2 -2
- package/dist/cli/chunks/{dist-node-R4FAYQRY.js → dist-node-LU4E7PI6.js} +2 -2
- package/dist/cli/chunks/{domain-handler-IGWXLF2S.js → domain-handler-5AKKAC43.js} +2 -2
- package/dist/cli/chunks/{domain-transfer-A7YNO76C.js → domain-transfer-LB6H7RPX.js} +2 -2
- package/dist/cli/chunks/dream-C6VNLTON.js +2 -0
- package/dist/cli/chunks/{embed-and-insert-pattern-KODZAS7Y.js → embed-and-insert-pattern-7RBA5NDK.js} +2 -2
- package/dist/cli/chunks/{eval-ALQW7Q2S.js → eval-ZZFPRENX.js} +5 -5
- package/dist/cli/chunks/{experience-capture-middleware-3WK4RXWK.js → experience-capture-middleware-HRO3EGIW.js} +3 -3
- package/dist/cli/chunks/{fast-paths-PQWDFIJZ.js → fast-paths-IRRNQBTY.js} +2 -2
- package/dist/cli/chunks/{feature-flags-JRUAZCND.js → feature-flags-R5N5IWI2.js} +2 -2
- package/dist/cli/chunks/{feature-flags-6X33B3WX.js → feature-flags-W54ABAUA.js} +2 -2
- package/dist/cli/chunks/{file-discovery-SA3YU3IH.js → file-discovery-6CIDLVID.js} +2 -2
- package/dist/cli/chunks/{fleet-7TXCAOKQ.js → fleet-YTFN64WE.js} +3 -3
- package/dist/cli/chunks/{gnn-wrapper-ZKNYACEC.js → gnn-wrapper-RXMPLMV2.js} +2 -2
- package/dist/cli/chunks/{heartbeat-handler-KRZRZ23F.js → heartbeat-handler-HQQWEEQQ.js} +4 -4
- package/dist/cli/chunks/heartbeat-scheduler-4SBO27BG.js +2 -0
- package/dist/cli/chunks/hnsw-adapter-W7G6VNXW.js +2 -0
- package/dist/cli/chunks/hnsw-index-LENA5QML.js +2 -0
- package/dist/cli/chunks/{hnsw-legacy-bridge-LVHQ5SG7.js → hnsw-legacy-bridge-GPZIKYFD.js} +2 -2
- package/dist/cli/chunks/{better-sqlite3-HP4JZS6K.js → hnswlib-node-P6HSEFLW.js} +2 -2
- package/dist/cli/chunks/hooks-AYLAGFOK.js +285 -0
- package/dist/cli/chunks/hybrid-router-IXHIC45P.js +2 -0
- package/dist/cli/chunks/{hypergraph-engine-2EZBZMFK.js → hypergraph-engine-56FMXI3T.js} +2 -2
- package/dist/cli/chunks/{hypergraph-handler-GLPWYII2.js → hypergraph-handler-APEVT5IE.js} +3 -3
- package/dist/cli/chunks/impact-analyzer-DKGVMYU6.js +2 -0
- package/dist/cli/chunks/{init-handler-ZSDO5VMA.js → init-handler-5DWF4REQ.js} +6 -6
- package/dist/cli/chunks/init-wizard-BBY3LY3F.js +2 -0
- package/dist/cli/chunks/kernel-7CUW7G62.js +2 -0
- package/dist/cli/chunks/{kilocode-installer-ATYSDWIV.js → kilocode-installer-XKAUA5VA.js} +2 -2
- package/dist/cli/chunks/{kiro-installer-K66YT6PC.js → kiro-installer-NI2KIYJE.js} +2 -2
- package/dist/cli/chunks/knowledge-graph-Q5CP47IP.js +2 -0
- package/dist/cli/chunks/{learning-BVYCC4RI.js → learning-ZIUMUNXZ.js} +3 -3
- package/dist/cli/chunks/{llm-router-VBCXE6DN.js → llm-router-IL52EF2V.js} +4 -4
- package/dist/cli/chunks/llm-router-service-MTXCX7TO.js +2 -0
- package/dist/cli/chunks/{load-AREDQE2U.js → load-B5LFYD6O.js} +2 -2
- package/dist/cli/chunks/load-test-YBWXASBO.js +2 -0
- package/dist/cli/chunks/{mcp-NG6H6UC5.js → mcp-K6GZLWBC.js} +2 -2
- package/dist/cli/chunks/{memory-Y65EHG6N.js → memory-NCQRVSN6.js} +5 -5
- package/dist/cli/chunks/memory-backend-52LANEA3.js +2 -0
- package/dist/cli/chunks/memory-handlers-KFW3HYAP.js +2 -0
- package/dist/cli/chunks/{multi-model-executor-VRPRFUZT.js → multi-model-executor-R4LBSJWK.js} +2 -2
- package/dist/cli/chunks/{opencode-installer-CKQXPM5R.js → opencode-installer-I6CBR3PV.js} +2 -2
- package/dist/cli/chunks/{orchestrator-I7JBKD6G.js → orchestrator-5FXUCES6.js} +10 -10
- package/dist/cli/chunks/{pipeline-MV2RWCBI.js → pipeline-GDKCTXJH.js} +2 -2
- package/dist/cli/chunks/{platform-VU5P3SOG.js → platform-ZFY3F4T3.js} +2 -2
- package/dist/cli/chunks/{plugin-6TERLKCB.js → plugin-HQMEN3OS.js} +2 -2
- package/dist/cli/chunks/{prime-radiant-advanced-wasm-WIUIN2DL.js → prime-radiant-advanced-wasm-LSJGF4CV.js} +2 -2
- package/dist/cli/chunks/protocol-executor-TRYUS77M.js +2 -0
- package/dist/cli/chunks/{protocol-handler-HKWBGARO.js → protocol-handler-BMDNIGPP.js} +2 -2
- package/dist/cli/chunks/{prove-7CQPHBRJ.js → prove-ABVGAG4Z.js} +2 -2
- package/dist/cli/chunks/provider-manager-6XQQN7FX.js +2 -0
- package/dist/cli/chunks/qe-reasoning-bank-3IUPE4DJ.js +2 -0
- package/dist/cli/chunks/{quality-VLUVXKVG.js → quality-ENJXPNP5.js} +2 -2
- package/dist/cli/chunks/queen-coordinator-VWPH4XPX.js +2 -0
- package/dist/cli/chunks/{real-embeddings-JPZ64KK2.js → real-embeddings-W3GNAEJO.js} +2 -2
- package/dist/cli/chunks/{roocode-installer-NONVB3UE.js → roocode-installer-4FJNQ7PU.js} +2 -2
- package/dist/cli/chunks/router-OIB6ODHA.js +2 -0
- package/dist/cli/chunks/routing-feedback-EKYPCZYG.js +2 -0
- package/dist/cli/chunks/{routing-handler-YYXDT4J2.js → routing-handler-GFS5FA4F.js} +2 -2
- package/dist/cli/chunks/{ruvector-commands-5PFMNDLR.js → ruvector-commands-GBMYNJKN.js} +2 -2
- package/dist/cli/chunks/{rvf-dual-writer-TF6H7AXH.js → rvf-dual-writer-STUAQT6U.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-adapter-VNGIUZCO.js → rvf-migration-adapter-LO6DBNJH.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-coordinator-VA52YAIY.js → rvf-migration-coordinator-I5AD4VJ2.js} +2 -2
- package/dist/cli/chunks/rvf-native-adapter-7RXP2Q4Q.js +2 -0
- package/dist/cli/chunks/safe-db-MNKFEPBX.js +2 -0
- package/dist/cli/chunks/schedule-AJXABVXX.js +2 -0
- package/dist/cli/chunks/scheduler-LDWYHIAW.js +2 -0
- package/dist/cli/chunks/{security-62HEETBF.js → security-X3WCA5K5.js} +3 -3
- package/dist/cli/chunks/shared-rvf-adapter-Z4FSPWNP.js +2 -0
- package/dist/cli/chunks/{shared-rvf-dual-writer-JTZK7LRD.js → shared-rvf-dual-writer-QOPOIRIC.js} +2 -2
- package/dist/cli/chunks/sqlite-persistence-A6GKDMOJ.js +2 -0
- package/dist/cli/chunks/{status-handler-LSUPUKRF.js → status-handler-B2B5QBVK.js} +2 -2
- package/dist/cli/chunks/{structural-health-Z75A666N.js → structural-health-KT47LBVH.js} +2 -2
- package/dist/cli/chunks/sync-CKID22IW.js +2 -0
- package/dist/cli/chunks/{sync-M3O4T3A3.js → sync-VWD6OOUR.js} +2 -2
- package/dist/cli/chunks/{task-handler-AQBSZAQC.js → task-handler-X5JT5YBF.js} +2 -2
- package/dist/cli/chunks/{task-handlers-BOZP247V.js → task-handlers-IW4GQDW4.js} +3 -3
- package/dist/cli/chunks/{test-FTEGPNN2.js → test-MBZSUASD.js} +4 -4
- package/dist/cli/chunks/{test-scheduling-IGR4U2VQ.js → test-scheduling-E5KHKRZS.js} +3 -3
- package/dist/cli/chunks/token-bootstrap-TIDPJ5IG.js +2 -0
- package/dist/cli/chunks/{token-usage-VCHV47EO.js → token-usage-ECJSPOQB.js} +2 -2
- package/dist/cli/chunks/{transformers-M27QSNFH.js → transformers-UZJAQ7OZ.js} +2 -2
- package/dist/cli/chunks/{tree-sitter-wasm-parser-IIGEJYFU.js → tree-sitter-wasm-parser-H6BU2E5R.js} +2 -2
- package/dist/cli/chunks/{types-RQFPUUKA.js → types-PM7NT3MH.js} +2 -2
- package/dist/cli/chunks/unified-memory-27QJHABO.js +2 -0
- package/dist/cli/chunks/unified-memory-hnsw-76VUXR4H.js +2 -0
- package/dist/cli/chunks/unified-persistence-QRCGDEXH.js +2 -0
- package/dist/cli/chunks/{upgrade-VJMYX3AL.js → upgrade-FS2XYC2P.js} +2 -2
- package/dist/cli/chunks/{validate-ML7HUAU5.js → validate-4Y2BNN3A.js} +3 -3
- package/dist/cli/chunks/{validate-swarm-RCR6EYRC.js → validate-swarm-Z7QXZSUE.js} +4 -4
- package/dist/cli/chunks/{vibium-ZOOS3W5L.js → vibium-VZ6L3O2G.js} +2 -2
- package/dist/cli/chunks/visual-security-KB27O7BE.js +2 -0
- package/dist/cli/chunks/{web-tree-sitter-2YPGYLWK.js → web-tree-sitter-H7P37W5U.js} +2 -2
- package/dist/cli/chunks/{windsurf-installer-GOJWUWC5.js → windsurf-installer-IB2VHSZS.js} +2 -2
- package/dist/cli/chunks/{witness-chain-3MGSS3Q4.js → witness-chain-C4DISYJN.js} +2 -2
- package/dist/cli/chunks/witness-chain-EYPXHRDV.js +2 -0
- package/dist/cli/chunks/{workflow-B5Q77BI4.js → workflow-IGM7KVIO.js} +4 -4
- package/dist/cli/chunks/workflow-orchestrator-6AQZ3USU.js +2 -0
- package/dist/cli/chunks/wrappers-PQXC263L.js +2 -0
- package/dist/cli/commands/arena.d.ts +10 -0
- package/dist/cli/commands/arena.js +129 -0
- package/dist/cli/commands/hooks-handlers/command-hooks.js +38 -2
- package/dist/cli/commands/hooks-handlers/hooks-dream-learning.d.ts +4 -0
- package/dist/cli/commands/hooks-handlers/hooks-dream-learning.js +66 -3
- package/dist/cli/commands/hooks-handlers/nesting-provenance.d.ts +27 -0
- package/dist/cli/commands/hooks-handlers/nesting-provenance.js +46 -0
- package/dist/cli/commands/hooks-handlers/task-hooks.js +72 -1
- package/dist/cli/commands/hooks-handlers/tool-loop-guardrail.d.ts +71 -0
- package/dist/cli/commands/hooks-handlers/tool-loop-guardrail.js +142 -0
- package/dist/cli/index.js +17 -0
- package/dist/contracts/verdicts.d.ts +297 -0
- package/dist/contracts/verdicts.js +178 -0
- package/dist/coordination/queen-types.d.ts +4 -0
- package/dist/integrations/agentic-flow/reasoning-bank/experience-replay.js +15 -6
- package/dist/integrations/agentic-flow/reasoning-bank/trajectory-tracker.js +12 -0
- package/dist/integrations/ruvector/shared-rvf-adapter.js +12 -1
- package/dist/integrations/ruvector/shared-rvf-dual-writer.js +6 -2
- package/dist/kernel/project-root.d.ts +33 -0
- package/dist/kernel/project-root.js +86 -0
- package/dist/kernel/unified-memory.d.ts +2 -19
- package/dist/kernel/unified-memory.js +8 -64
- package/dist/learning/local-judge-client.d.ts +55 -0
- package/dist/learning/local-judge-client.js +127 -0
- package/dist/learning/nagual-client.d.ts +73 -0
- package/dist/learning/nagual-client.js +150 -0
- package/dist/learning/pattern-store.js +10 -3
- package/dist/mcp/bundle.js +393 -391
- package/dist/mcp/entry.js +44 -33
- package/dist/mcp/handlers/core-handlers.d.ts +20 -0
- package/dist/mcp/handlers/core-handlers.js +28 -0
- package/dist/mcp/handlers/domain-handler-configs.d.ts +3 -0
- package/dist/mcp/handlers/domain-handler-configs.js +22 -10
- package/dist/mcp/transport/stdio.d.ts +7 -0
- package/dist/mcp/transport/stdio.js +39 -2
- package/dist/shared/llm/cost-tracker.js +6 -2
- package/dist/shared/llm/interfaces.d.ts +4 -0
- package/dist/shared/llm/providers/claude.js +16 -2
- package/dist/shared/reasoning-scrub.d.ts +29 -0
- package/dist/shared/reasoning-scrub.js +75 -0
- package/dist/workers/daemon.js +2 -0
- package/dist/workers/quality-daemon/git-watcher.js +2 -0
- package/dist/workers/quality-daemon/index.js +2 -0
- package/dist/workers/worker-manager.js +4 -0
- package/package.json +1 -1
- package/dist/cli/chunks/adapter-BHPUKMJ5.js +0 -2
- package/dist/cli/chunks/aqe-learning-engine-JQ5WD2HM.js +0 -2
- package/dist/cli/chunks/audit-BMQ3VESB.js +0 -3
- package/dist/cli/chunks/base-E32WLGY2.js +0 -2
- package/dist/cli/chunks/browser-workflow-LNNXXAJG.js +0 -2
- package/dist/cli/chunks/chunk-2EQVYYBF.js +0 -2
- package/dist/cli/chunks/chunk-3VF3HCG4.js +0 -2
- package/dist/cli/chunks/chunk-GELF4ILR.js +0 -699
- package/dist/cli/chunks/chunk-JOLDCS6X.js +0 -2
- package/dist/cli/chunks/chunk-JSFYPLMQ.js +0 -2
- package/dist/cli/chunks/chunk-YX2HY4MX.js +0 -2
- package/dist/cli/chunks/client-2UKBYFX4.js +0 -2
- package/dist/cli/chunks/cross-domain-router-FPM3L27L.js +0 -2
- package/dist/cli/chunks/daemon-YWINEHG4.js +0 -10
- package/dist/cli/chunks/dream-XM33US3V.js +0 -2
- package/dist/cli/chunks/heartbeat-scheduler-GM3M2MTG.js +0 -2
- package/dist/cli/chunks/hnsw-adapter-K62GEHIL.js +0 -2
- package/dist/cli/chunks/hnsw-index-VCAK3TWN.js +0 -2
- package/dist/cli/chunks/hooks-6Y3UHYI2.js +0 -248
- package/dist/cli/chunks/hybrid-router-432QNCNG.js +0 -2
- package/dist/cli/chunks/impact-analyzer-VTSISNN4.js +0 -2
- package/dist/cli/chunks/init-wizard-COB5AH7Q.js +0 -2
- package/dist/cli/chunks/kernel-ROK7X5FM.js +0 -2
- package/dist/cli/chunks/knowledge-graph-YUWIDIWW.js +0 -2
- package/dist/cli/chunks/llm-router-service-7VLXJ7VE.js +0 -2
- package/dist/cli/chunks/load-test-32524DL3.js +0 -2
- package/dist/cli/chunks/memory-backend-BI2V5AAB.js +0 -2
- package/dist/cli/chunks/memory-handlers-NSOFWVFN.js +0 -2
- package/dist/cli/chunks/protocol-executor-2UPB7SPI.js +0 -2
- package/dist/cli/chunks/provider-manager-PDT37MIJ.js +0 -2
- package/dist/cli/chunks/qe-reasoning-bank-AQQ2BI4V.js +0 -2
- package/dist/cli/chunks/queen-coordinator-6DVDVEU4.js +0 -2
- package/dist/cli/chunks/router-O2G4KQ6L.js +0 -2
- package/dist/cli/chunks/routing-feedback-TAGTD3KQ.js +0 -2
- package/dist/cli/chunks/rvf-native-adapter-46GRWQJR.js +0 -2
- package/dist/cli/chunks/safe-db-LNIPXXHH.js +0 -2
- package/dist/cli/chunks/schedule-AUH3ZALY.js +0 -2
- package/dist/cli/chunks/scheduler-KK3OYPWW.js +0 -2
- package/dist/cli/chunks/shared-rvf-adapter-XWTQPGCT.js +0 -2
- package/dist/cli/chunks/sqlite-persistence-CYESP7NG.js +0 -2
- package/dist/cli/chunks/sync-VI37UHHH.js +0 -2
- package/dist/cli/chunks/token-bootstrap-2DFRVMBM.js +0 -2
- package/dist/cli/chunks/unified-memory-RISHEANP.js +0 -2
- package/dist/cli/chunks/unified-memory-hnsw-2IKXGMNZ.js +0 -2
- package/dist/cli/chunks/unified-persistence-ZTTUJNTU.js +0 -2
- package/dist/cli/chunks/visual-security-D66DTAO5.js +0 -2
- package/dist/cli/chunks/witness-chain-RHWHHDLV.js +0 -2
- package/dist/cli/chunks/workflow-orchestrator-OQMFW2TC.js +0 -2
- package/dist/cli/chunks/wrappers-MM5VLEPG.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.
|
|
2
|
-
import{d as be}from"./chunk-5LON3MLI.js";import{b as D,d as ye}from"./chunk-KTRB3L53.js";import{a as Le}from"./chunk-3VF3HCG4.js";import{c as fe,d as ge,e as Pe}from"./chunk-2L73WXA4.js";import{b as P,c as L}from"./chunk-JD2PG4KS.js";import{a as G,b as A,c as J}from"./chunk-3LRK7PYN.js";Le();import{createRequire as Ce}from"module";var O;function W(){if(!O){let u=Ce(import.meta.url);try{O=u("typescript")}catch{try{O=u("typescript/lib/typescript.js")}catch{O=new Proxy({},{get(e,t){if(!(t==="__esModule"||typeof t=="symbol"))throw new Error("TypeScript is required for code analysis. Install it: npm install -g typescript")}})}}}return O}var m=new Proxy({},{get(u,e){return W()[e]},has(u,e){return e in W()},ownKeys(){return Object.keys(W())},getOwnPropertyDescriptor(u,e){let t=W()[e];if(t!==void 0)return{configurable:!0,enumerable:!0,value:t}}});var N=class{parseFile(e,t){return m.createSourceFile(e,t,m.ScriptTarget.Latest,!0,this.getScriptKind(e))}extractFunctions(e){let t=[],s=n=>{m.isFunctionDeclaration(n)&&n.name?t.push(this.extractFunctionDeclaration(n,e)):m.isVariableStatement(n)&&this.extractArrowFunctions(n,e,t),m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractClasses(e){let t=[],s=n=>{m.isClassDeclaration(n)&&n.name&&t.push(this.extractClassDeclaration(n,e)),m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractImports(e){let t=[],s=n=>{m.isImportDeclaration(n)&&t.push(this.extractImportDeclaration(n)),m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractExports(e){let t=[],s=n=>{if(m.isExportDeclaration(n))this.extractExportDeclaration(n,t);else if(m.isExportAssignment(n))t.push({name:this.getExportAssignmentName(n),type:"unknown",isDefault:!0,isReexport:!1,sourceModule:void 0});else if(m.isFunctionDeclaration(n)&&n.name&&this.hasExportModifier(n))t.push({name:n.name.text,type:"function",isDefault:this.hasDefaultModifier(n),isReexport:!1,sourceModule:void 0});else if(m.isClassDeclaration(n)&&n.name&&this.hasExportModifier(n))t.push({name:n.name.text,type:"class",isDefault:this.hasDefaultModifier(n),isReexport:!1,sourceModule:void 0});else if(m.isVariableStatement(n)&&this.hasExportModifier(n))for(let i of n.declarationList.declarations)m.isIdentifier(i.name)&&t.push({name:i.name.text,type:"variable",isDefault:!1,isReexport:!1,sourceModule:void 0});else m.isInterfaceDeclaration(n)&&this.hasExportModifier(n)?t.push({name:n.name.text,type:"interface",isDefault:!1,isReexport:!1,sourceModule:void 0}):m.isTypeAliasDeclaration(n)&&this.hasExportModifier(n)?t.push({name:n.name.text,type:"type",isDefault:!1,isReexport:!1,sourceModule:void 0}):m.isEnumDeclaration(n)&&this.hasExportModifier(n)&&t.push({name:n.name.text,type:"enum",isDefault:!1,isReexport:!1,sourceModule:void 0});m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractInterfaces(e){let t=[],s=n=>{m.isInterfaceDeclaration(n)&&t.push(this.extractInterfaceDeclaration(n,e)),m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractEntities(e,t){let s=this.parseFile(t,e),n=[],i=this.extractFunctions(s);for(let a of i)n.push({name:a.name,type:"function",line:a.startLine,endLine:a.endLine,visibility:a.isExported?"public":"internal",isAsync:a.isAsync,isExported:a.isExported,parameters:a.parameters,returnType:a.returnType});let o=this.extractClasses(s);for(let a of o)n.push({name:a.name,type:"class",line:a.startLine,endLine:a.endLine,visibility:a.isExported?"public":"internal",isAsync:!1,isExported:a.isExported,extends:a.extends,implements:a.implements});let r=this.extractInterfaces(s);for(let a of r)n.push({name:a.name,type:"interface",line:a.startLine,endLine:a.endLine,visibility:a.isExported?"public":"internal",isAsync:!1,isExported:a.isExported});return n}getScriptKind(e){return e.endsWith(".tsx")?m.ScriptKind.TSX:e.endsWith(".ts")?m.ScriptKind.TS:e.endsWith(".jsx")?m.ScriptKind.JSX:e.endsWith(".js")?m.ScriptKind.JS:m.ScriptKind.TS}extractFunctionDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd());return{name:e.name?.text??"anonymous",parameters:this.extractParameters(e.parameters),returnType:e.type?e.type.getText(t):void 0,startLine:s+1,endLine:n+1,isAsync:this.hasAsyncModifier(e),isExported:this.hasExportModifier(e),isGenerator:!!e.asteriskToken,typeParameters:this.extractTypeParameters(e.typeParameters)}}extractArrowFunctions(e,t,s){for(let n of e.declarationList.declarations)if(m.isIdentifier(n.name)&&n.initializer&&m.isArrowFunction(n.initializer)){let i=n.initializer,{line:o}=t.getLineAndCharacterOfPosition(e.getStart()),{line:r}=t.getLineAndCharacterOfPosition(e.getEnd());s.push({name:n.name.text,parameters:this.extractParameters(i.parameters),returnType:i.type?i.type.getText(t):void 0,startLine:o+1,endLine:r+1,isAsync:this.hasAsyncModifier(i),isExported:this.hasExportModifier(e),isGenerator:!1,typeParameters:this.extractTypeParameters(i.typeParameters)})}}extractClassDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd()),i=[],o=[];for(let c of e.members)m.isMethodDeclaration(c)&&c.name?i.push(this.extractMethodDeclaration(c,t)):m.isPropertyDeclaration(c)&&c.name?o.push(this.extractPropertyDeclaration(c,t)):m.isConstructorDeclaration(c)&&(i.push(this.extractConstructor(c,t)),this.extractParameterProperties(c,o,t));let r,a=[];if(e.heritageClauses){for(let c of e.heritageClauses)if(c.token===m.SyntaxKind.ExtendsKeyword)r=c.types[0]?.expression.getText(t);else if(c.token===m.SyntaxKind.ImplementsKeyword)for(let l of c.types)a.push(l.expression.getText(t))}return{name:e.name?.text??"anonymous",methods:i,properties:o,extends:r,implements:a,isAbstract:this.hasAbstractModifier(e),isExported:this.hasExportModifier(e),startLine:s+1,endLine:n+1,typeParameters:this.extractTypeParameters(e.typeParameters)}}extractMethodDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd());return{name:this.getPropertyName(e.name,t),parameters:this.extractParameters(e.parameters),returnType:e.type?e.type.getText(t):void 0,isAsync:this.hasAsyncModifier(e),isStatic:this.hasStaticModifier(e),isAbstract:this.hasAbstractModifier(e),visibility:this.getVisibility(e),startLine:s+1,endLine:n+1}}extractConstructor(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd());return{name:"constructor",parameters:this.extractParameters(e.parameters),returnType:void 0,isAsync:!1,isStatic:!1,isAbstract:!1,visibility:"public",startLine:s+1,endLine:n+1}}extractParameterProperties(e,t,s){for(let n of e.parameters)this.isParameterProperty(n)&&t.push({name:m.isIdentifier(n.name)?n.name.text:n.name.getText(s),type:n.type?n.type.getText(s):void 0,isStatic:!1,isReadonly:this.hasReadonlyModifier(n),visibility:this.getVisibility(n),hasInitializer:!!n.initializer})}isParameterProperty(e){return!!e.modifiers?.some(t=>t.kind===m.SyntaxKind.PublicKeyword||t.kind===m.SyntaxKind.PrivateKeyword||t.kind===m.SyntaxKind.ProtectedKeyword||t.kind===m.SyntaxKind.ReadonlyKeyword)}extractPropertyDeclaration(e,t){return{name:this.getPropertyName(e.name,t),type:e.type?e.type.getText(t):void 0,isStatic:this.hasStaticModifier(e),isReadonly:this.hasReadonlyModifier(e),visibility:this.getVisibility(e),hasInitializer:!!e.initializer}}extractImportDeclaration(e){let t=e.moduleSpecifier.text,s=[],n,i,o=e.importClause?.isTypeOnly??!1;if(e.importClause&&(e.importClause.name&&(n=e.importClause.name.text),e.importClause.namedBindings)){if(m.isNamespaceImport(e.importClause.namedBindings))i=e.importClause.namedBindings.name.text;else if(m.isNamedImports(e.importClause.namedBindings))for(let r of e.importClause.namedBindings.elements)s.push({name:r.propertyName?.text??r.name.text,alias:r.propertyName?r.name.text:void 0})}return{module:t,namedImports:s,defaultImport:n,namespaceImport:i,isTypeOnly:o}}extractExportDeclaration(e,t){let s=e.moduleSpecifier?e.moduleSpecifier.text:void 0;if(e.exportClause&&m.isNamedExports(e.exportClause))for(let n of e.exportClause.elements)t.push({name:n.name.text,type:"unknown",isDefault:!1,isReexport:!!s,sourceModule:s});else!e.exportClause&&s&&t.push({name:"*",type:"unknown",isDefault:!1,isReexport:!0,sourceModule:s})}extractInterfaceDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd()),i=[],o=[];for(let a of e.members)m.isPropertySignature(a)&&a.name?i.push({name:this.getPropertyName(a.name,t),type:a.type?a.type.getText(t):void 0,isOptional:!!a.questionToken,isReadonly:this.hasReadonlyModifier(a)}):m.isMethodSignature(a)&&a.name&&o.push({name:this.getPropertyName(a.name,t),parameters:this.extractParameters(a.parameters),returnType:a.type?a.type.getText(t):void 0,isOptional:!!a.questionToken});let r=[];if(e.heritageClauses){for(let a of e.heritageClauses)if(a.token===m.SyntaxKind.ExtendsKeyword)for(let c of a.types)r.push(c.expression.getText(t))}return{name:e.name.text,properties:i,methods:o,extends:r,isExported:this.hasExportModifier(e),startLine:s+1,endLine:n+1,typeParameters:this.extractTypeParameters(e.typeParameters)}}extractParameters(e){return e.map(t=>{let s=t.getSourceFile();return{name:m.isIdentifier(t.name)?t.name.text:t.name.getText(s),type:t.type?t.type.getText(s):void 0,isOptional:!!t.questionToken||!!t.initializer,isRest:!!t.dotDotDotToken,defaultValue:t.initializer?t.initializer.getText(s):void 0}})}extractTypeParameters(e){return e?e.map(t=>t.name.text):[]}getPropertyName(e,t){return m.isIdentifier(e)||m.isStringLiteral(e)||m.isNumericLiteral(e)?e.text:e.getText(t)}getExportAssignmentName(e){return m.isIdentifier(e.expression)?e.expression.text:"default"}hasExportModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.ExportKeyword)}hasDefaultModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.DefaultKeyword)}hasAsyncModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.AsyncKeyword)}hasStaticModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.StaticKeyword)}hasAbstractModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.AbstractKeyword)}hasReadonlyModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.ReadonlyKeyword)}getVisibility(e){if(!m.canHaveModifiers(e))return"public";let t=m.getModifiers(e);return t?t.some(s=>s.kind===m.SyntaxKind.PrivateKeyword)?"private":t.some(s=>s.kind===m.SyntaxKind.ProtectedKeyword)?"protected":"public":"public"}},We=new N,Q=class{language="typescript";supportedExtensions=[".ts",".tsx",".js",".jsx",".mjs",".cjs"];parser=new N;async parseFile(e,t){let s=this.parser.parseFile(t,e),n=this.parser.extractFunctions(s),i=this.parser.extractClasses(s),o=this.parser.extractImports(s);return{functions:n.map(r=>this.mapFunction(r)),classes:i.map(r=>this.mapClass(r)),imports:o.map(r=>this.mapImport(r)),language:t.endsWith(".js")||t.endsWith(".jsx")||t.endsWith(".mjs")||t.endsWith(".cjs")?"javascript":"typescript",filePath:t}}mapFunction(e){return{name:e.name,parameters:e.parameters.map(t=>({name:t.name,type:t.type,isOptional:t.isOptional,defaultValue:t.defaultValue})),returnType:e.returnType,isAsync:e.isAsync,isPublic:e.isExported,complexity:1,decorators:[],genericParams:e.typeParameters,startLine:e.startLine,endLine:e.endLine}}mapClass(e){return{name:e.name,methods:e.methods.map(t=>({name:t.name,parameters:t.parameters.map(s=>({name:s.name,type:s.type,isOptional:s.isOptional,defaultValue:s.defaultValue})),returnType:t.returnType,isAsync:t.isAsync,isPublic:t.visibility==="public",complexity:1,decorators:[],genericParams:[],startLine:t.startLine,endLine:t.endLine})),properties:e.properties.map(t=>this.mapProperty(t)),isPublic:e.isExported,implements:e.implements,extends:e.extends,decorators:[],startLine:e.startLine,endLine:e.endLine}}mapProperty(e){return{name:e.name,type:e.type,isPublic:e.visibility==="public",isReadonly:e.isReadonly}}mapImport(e){return{module:e.module,namedImports:e.namedImports.map(t=>t.alias||t.name),isTypeOnly:e.isTypeOnly}}},ze=new Q;Pe();var E=1e3;function I(u){let e=u.split(`
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.5");process.exit(0)}
|
|
2
|
+
import{d as be}from"./chunk-DN65ILSI.js";import{b as D,d as ye}from"./chunk-56RA6YPN.js";import{a as Le}from"./chunk-RLZDXQNM.js";import{c as fe,d as ge,e as Pe}from"./chunk-VC256KH2.js";import{b as P,c as L}from"./chunk-IRS4HKAR.js";import{a as G,b as A,c as J}from"./chunk-S73KENCH.js";Le();import{createRequire as Ce}from"module";var O;function W(){if(!O){let u=Ce(import.meta.url);try{O=u("typescript")}catch{try{O=u("typescript/lib/typescript.js")}catch{O=new Proxy({},{get(e,t){if(!(t==="__esModule"||typeof t=="symbol"))throw new Error("TypeScript is required for code analysis. Install it: npm install -g typescript")}})}}}return O}var m=new Proxy({},{get(u,e){return W()[e]},has(u,e){return e in W()},ownKeys(){return Object.keys(W())},getOwnPropertyDescriptor(u,e){let t=W()[e];if(t!==void 0)return{configurable:!0,enumerable:!0,value:t}}});var N=class{parseFile(e,t){return m.createSourceFile(e,t,m.ScriptTarget.Latest,!0,this.getScriptKind(e))}extractFunctions(e){let t=[],s=n=>{m.isFunctionDeclaration(n)&&n.name?t.push(this.extractFunctionDeclaration(n,e)):m.isVariableStatement(n)&&this.extractArrowFunctions(n,e,t),m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractClasses(e){let t=[],s=n=>{m.isClassDeclaration(n)&&n.name&&t.push(this.extractClassDeclaration(n,e)),m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractImports(e){let t=[],s=n=>{m.isImportDeclaration(n)&&t.push(this.extractImportDeclaration(n)),m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractExports(e){let t=[],s=n=>{if(m.isExportDeclaration(n))this.extractExportDeclaration(n,t);else if(m.isExportAssignment(n))t.push({name:this.getExportAssignmentName(n),type:"unknown",isDefault:!0,isReexport:!1,sourceModule:void 0});else if(m.isFunctionDeclaration(n)&&n.name&&this.hasExportModifier(n))t.push({name:n.name.text,type:"function",isDefault:this.hasDefaultModifier(n),isReexport:!1,sourceModule:void 0});else if(m.isClassDeclaration(n)&&n.name&&this.hasExportModifier(n))t.push({name:n.name.text,type:"class",isDefault:this.hasDefaultModifier(n),isReexport:!1,sourceModule:void 0});else if(m.isVariableStatement(n)&&this.hasExportModifier(n))for(let i of n.declarationList.declarations)m.isIdentifier(i.name)&&t.push({name:i.name.text,type:"variable",isDefault:!1,isReexport:!1,sourceModule:void 0});else m.isInterfaceDeclaration(n)&&this.hasExportModifier(n)?t.push({name:n.name.text,type:"interface",isDefault:!1,isReexport:!1,sourceModule:void 0}):m.isTypeAliasDeclaration(n)&&this.hasExportModifier(n)?t.push({name:n.name.text,type:"type",isDefault:!1,isReexport:!1,sourceModule:void 0}):m.isEnumDeclaration(n)&&this.hasExportModifier(n)&&t.push({name:n.name.text,type:"enum",isDefault:!1,isReexport:!1,sourceModule:void 0});m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractInterfaces(e){let t=[],s=n=>{m.isInterfaceDeclaration(n)&&t.push(this.extractInterfaceDeclaration(n,e)),m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractEntities(e,t){let s=this.parseFile(t,e),n=[],i=this.extractFunctions(s);for(let a of i)n.push({name:a.name,type:"function",line:a.startLine,endLine:a.endLine,visibility:a.isExported?"public":"internal",isAsync:a.isAsync,isExported:a.isExported,parameters:a.parameters,returnType:a.returnType});let o=this.extractClasses(s);for(let a of o)n.push({name:a.name,type:"class",line:a.startLine,endLine:a.endLine,visibility:a.isExported?"public":"internal",isAsync:!1,isExported:a.isExported,extends:a.extends,implements:a.implements});let r=this.extractInterfaces(s);for(let a of r)n.push({name:a.name,type:"interface",line:a.startLine,endLine:a.endLine,visibility:a.isExported?"public":"internal",isAsync:!1,isExported:a.isExported});return n}getScriptKind(e){return e.endsWith(".tsx")?m.ScriptKind.TSX:e.endsWith(".ts")?m.ScriptKind.TS:e.endsWith(".jsx")?m.ScriptKind.JSX:e.endsWith(".js")?m.ScriptKind.JS:m.ScriptKind.TS}extractFunctionDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd());return{name:e.name?.text??"anonymous",parameters:this.extractParameters(e.parameters),returnType:e.type?e.type.getText(t):void 0,startLine:s+1,endLine:n+1,isAsync:this.hasAsyncModifier(e),isExported:this.hasExportModifier(e),isGenerator:!!e.asteriskToken,typeParameters:this.extractTypeParameters(e.typeParameters)}}extractArrowFunctions(e,t,s){for(let n of e.declarationList.declarations)if(m.isIdentifier(n.name)&&n.initializer&&m.isArrowFunction(n.initializer)){let i=n.initializer,{line:o}=t.getLineAndCharacterOfPosition(e.getStart()),{line:r}=t.getLineAndCharacterOfPosition(e.getEnd());s.push({name:n.name.text,parameters:this.extractParameters(i.parameters),returnType:i.type?i.type.getText(t):void 0,startLine:o+1,endLine:r+1,isAsync:this.hasAsyncModifier(i),isExported:this.hasExportModifier(e),isGenerator:!1,typeParameters:this.extractTypeParameters(i.typeParameters)})}}extractClassDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd()),i=[],o=[];for(let c of e.members)m.isMethodDeclaration(c)&&c.name?i.push(this.extractMethodDeclaration(c,t)):m.isPropertyDeclaration(c)&&c.name?o.push(this.extractPropertyDeclaration(c,t)):m.isConstructorDeclaration(c)&&(i.push(this.extractConstructor(c,t)),this.extractParameterProperties(c,o,t));let r,a=[];if(e.heritageClauses){for(let c of e.heritageClauses)if(c.token===m.SyntaxKind.ExtendsKeyword)r=c.types[0]?.expression.getText(t);else if(c.token===m.SyntaxKind.ImplementsKeyword)for(let l of c.types)a.push(l.expression.getText(t))}return{name:e.name?.text??"anonymous",methods:i,properties:o,extends:r,implements:a,isAbstract:this.hasAbstractModifier(e),isExported:this.hasExportModifier(e),startLine:s+1,endLine:n+1,typeParameters:this.extractTypeParameters(e.typeParameters)}}extractMethodDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd());return{name:this.getPropertyName(e.name,t),parameters:this.extractParameters(e.parameters),returnType:e.type?e.type.getText(t):void 0,isAsync:this.hasAsyncModifier(e),isStatic:this.hasStaticModifier(e),isAbstract:this.hasAbstractModifier(e),visibility:this.getVisibility(e),startLine:s+1,endLine:n+1}}extractConstructor(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd());return{name:"constructor",parameters:this.extractParameters(e.parameters),returnType:void 0,isAsync:!1,isStatic:!1,isAbstract:!1,visibility:"public",startLine:s+1,endLine:n+1}}extractParameterProperties(e,t,s){for(let n of e.parameters)this.isParameterProperty(n)&&t.push({name:m.isIdentifier(n.name)?n.name.text:n.name.getText(s),type:n.type?n.type.getText(s):void 0,isStatic:!1,isReadonly:this.hasReadonlyModifier(n),visibility:this.getVisibility(n),hasInitializer:!!n.initializer})}isParameterProperty(e){return!!e.modifiers?.some(t=>t.kind===m.SyntaxKind.PublicKeyword||t.kind===m.SyntaxKind.PrivateKeyword||t.kind===m.SyntaxKind.ProtectedKeyword||t.kind===m.SyntaxKind.ReadonlyKeyword)}extractPropertyDeclaration(e,t){return{name:this.getPropertyName(e.name,t),type:e.type?e.type.getText(t):void 0,isStatic:this.hasStaticModifier(e),isReadonly:this.hasReadonlyModifier(e),visibility:this.getVisibility(e),hasInitializer:!!e.initializer}}extractImportDeclaration(e){let t=e.moduleSpecifier.text,s=[],n,i,o=e.importClause?.isTypeOnly??!1;if(e.importClause&&(e.importClause.name&&(n=e.importClause.name.text),e.importClause.namedBindings)){if(m.isNamespaceImport(e.importClause.namedBindings))i=e.importClause.namedBindings.name.text;else if(m.isNamedImports(e.importClause.namedBindings))for(let r of e.importClause.namedBindings.elements)s.push({name:r.propertyName?.text??r.name.text,alias:r.propertyName?r.name.text:void 0})}return{module:t,namedImports:s,defaultImport:n,namespaceImport:i,isTypeOnly:o}}extractExportDeclaration(e,t){let s=e.moduleSpecifier?e.moduleSpecifier.text:void 0;if(e.exportClause&&m.isNamedExports(e.exportClause))for(let n of e.exportClause.elements)t.push({name:n.name.text,type:"unknown",isDefault:!1,isReexport:!!s,sourceModule:s});else!e.exportClause&&s&&t.push({name:"*",type:"unknown",isDefault:!1,isReexport:!0,sourceModule:s})}extractInterfaceDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd()),i=[],o=[];for(let a of e.members)m.isPropertySignature(a)&&a.name?i.push({name:this.getPropertyName(a.name,t),type:a.type?a.type.getText(t):void 0,isOptional:!!a.questionToken,isReadonly:this.hasReadonlyModifier(a)}):m.isMethodSignature(a)&&a.name&&o.push({name:this.getPropertyName(a.name,t),parameters:this.extractParameters(a.parameters),returnType:a.type?a.type.getText(t):void 0,isOptional:!!a.questionToken});let r=[];if(e.heritageClauses){for(let a of e.heritageClauses)if(a.token===m.SyntaxKind.ExtendsKeyword)for(let c of a.types)r.push(c.expression.getText(t))}return{name:e.name.text,properties:i,methods:o,extends:r,isExported:this.hasExportModifier(e),startLine:s+1,endLine:n+1,typeParameters:this.extractTypeParameters(e.typeParameters)}}extractParameters(e){return e.map(t=>{let s=t.getSourceFile();return{name:m.isIdentifier(t.name)?t.name.text:t.name.getText(s),type:t.type?t.type.getText(s):void 0,isOptional:!!t.questionToken||!!t.initializer,isRest:!!t.dotDotDotToken,defaultValue:t.initializer?t.initializer.getText(s):void 0}})}extractTypeParameters(e){return e?e.map(t=>t.name.text):[]}getPropertyName(e,t){return m.isIdentifier(e)||m.isStringLiteral(e)||m.isNumericLiteral(e)?e.text:e.getText(t)}getExportAssignmentName(e){return m.isIdentifier(e.expression)?e.expression.text:"default"}hasExportModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.ExportKeyword)}hasDefaultModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.DefaultKeyword)}hasAsyncModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.AsyncKeyword)}hasStaticModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.StaticKeyword)}hasAbstractModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.AbstractKeyword)}hasReadonlyModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.ReadonlyKeyword)}getVisibility(e){if(!m.canHaveModifiers(e))return"public";let t=m.getModifiers(e);return t?t.some(s=>s.kind===m.SyntaxKind.PrivateKeyword)?"private":t.some(s=>s.kind===m.SyntaxKind.ProtectedKeyword)?"protected":"public":"public"}},We=new N,Q=class{language="typescript";supportedExtensions=[".ts",".tsx",".js",".jsx",".mjs",".cjs"];parser=new N;async parseFile(e,t){let s=this.parser.parseFile(t,e),n=this.parser.extractFunctions(s),i=this.parser.extractClasses(s),o=this.parser.extractImports(s);return{functions:n.map(r=>this.mapFunction(r)),classes:i.map(r=>this.mapClass(r)),imports:o.map(r=>this.mapImport(r)),language:t.endsWith(".js")||t.endsWith(".jsx")||t.endsWith(".mjs")||t.endsWith(".cjs")?"javascript":"typescript",filePath:t}}mapFunction(e){return{name:e.name,parameters:e.parameters.map(t=>({name:t.name,type:t.type,isOptional:t.isOptional,defaultValue:t.defaultValue})),returnType:e.returnType,isAsync:e.isAsync,isPublic:e.isExported,complexity:1,decorators:[],genericParams:e.typeParameters,startLine:e.startLine,endLine:e.endLine}}mapClass(e){return{name:e.name,methods:e.methods.map(t=>({name:t.name,parameters:t.parameters.map(s=>({name:s.name,type:s.type,isOptional:s.isOptional,defaultValue:s.defaultValue})),returnType:t.returnType,isAsync:t.isAsync,isPublic:t.visibility==="public",complexity:1,decorators:[],genericParams:[],startLine:t.startLine,endLine:t.endLine})),properties:e.properties.map(t=>this.mapProperty(t)),isPublic:e.isExported,implements:e.implements,extends:e.extends,decorators:[],startLine:e.startLine,endLine:e.endLine}}mapProperty(e){return{name:e.name,type:e.type,isPublic:e.visibility==="public",isReadonly:e.isReadonly}}mapImport(e){return{module:e.module,namedImports:e.namedImports.map(t=>t.alias||t.name),isTypeOnly:e.isTypeOnly}}},ze=new Q;Pe();var E=1e3;function I(u){let e=u.split(`
|
|
3
3
|
`),t=[],s=[],n="",i=0,o=0,r=0,a=0;for(let c=0;c<e.length;c++){let l=e[c],d=l.trim();if(d===""||d.startsWith("//")||d.startsWith("#")||d.startsWith("*")){if(n){n+=" "+d;continue}t.push(l),s.push(c+1);continue}n||(i=c+1),n=n?n+" "+d:l;for(let p of d)p==="("?o++:p===")"?o=Math.max(0,o-1):p==="<"?r++:p===">"?r=Math.max(0,r-1):p==="["?a++:p==="]"&&(a=Math.max(0,a-1));o===0&&r===0&&a===0&&(t.push(n),s.push(i),n="")}return n&&(t.push(n),s.push(i)),{logicalLines:t,lineMap:s}}function B(u,e,t="<",s=">"){if(u[e]!==t)return;let n=1,i=e+1;for(;i<u.length&&n>0;)u[i]===t?n++:u[i]===s&&n--,i++;if(n===0)return u.substring(e+1,i-1)}function C(u,e,t){let s=[];for(let n=e-1;n>=0;n--){let i=u[n].trim();if(i.startsWith(t))s.unshift(i);else{if(i===""||i.startsWith("//")||i.startsWith("*")||i.startsWith("#"))continue;break}}return s}function M(u){let e=[],t=0,s="";for(let n of u)n==="<"||n==="("?t++:(n===">"||n===")")&&t--,n===","&&t===0?(e.push(s.trim()),s=""):s+=n;return s.trim()&&e.push(s.trim()),e}function ce(u){let e=0,t=!1,s="";for(let n=0;n<u.length;n++){let i=u[n];if(t){i===s&&u[n-1]!=="\\"&&(t=!1);continue}i==='"'||i==="'"||i==="`"?(t=!0,s=i):i==="{"?e++:i==="}"&&e--}return e}var Y=class{language="python";supportedExtensions=[".py"];async parseFile(e,t){return{functions:this.extractFunctions(e),classes:this.extractClasses(e),imports:this.extractImports(e),language:"python",filePath:t}}extractFunctions(e){let t=[],s=e.split(`
|
|
4
4
|
`),{logicalLines:n,lineMap:i}=I(e),o=/^(\s*)(async\s+)?def\s+(\w+)\s*\(([^)]*)\)(?:\s*->\s*([^:]*\S))?\s*:/;for(let r=0;r<n.length;r++){if(n[r].length>E)continue;let a=n[r].match(o);if(a){let c=a[1].length,l=!!a[2],d=a[3],p=a[4],h=a[5]?.trim(),f=i[r]-1,g=f+1;for(let y=f+1;y<s.length;y++){let x=s[y];if(x.trim()===""||x.trim().startsWith("#"))continue;if((x.match(/^(\s*)/)?.[1].length??0)<=c&&x.trim()!==""){g=y;break}g=y+1}let b=C(s,f,"@");t.push({name:d,parameters:this.parseParams(p),returnType:h,isAsync:l,isPublic:!d.startsWith("_"),complexity:1,decorators:b,genericParams:[],startLine:i[r],endLine:g})}}return t}extractClasses(e){let t=[],s=e.split(`
|
|
5
5
|
`),{logicalLines:n,lineMap:i}=I(e),o=/^(\s*)class\s+(\w+)(?:\(([^)]*)\))?\s*:/;for(let r=0;r<n.length;r++){let a=n[r].match(o);if(a){let c=a[1].length,l=a[2],d=a[3]?a[3].split(",").map(y=>y.trim()):[],p=i[r]-1,h=p+1;for(let y=p+1;y<s.length;y++){let x=s[y];if(x.trim()===""||x.trim().startsWith("#"))continue;if((x.match(/^(\s*)/)?.[1].length??0)<=c&&x.trim()!==""){h=y;break}h=y+1}let f=s.slice(p+1,h).join(`
|
|
@@ -20,7 +20,7 @@ import{d as be}from"./chunk-5LON3MLI.js";import{b as D,d as ye}from"./chunk-KTRB
|
|
|
20
20
|
`),{logicalLines:n,lineMap:i}=I(e),o=/^\s*(public|private|protected|internal)?\s*(suspend)?\s*fun\s+(?:<[^{]*> +)?(\w+)\s*\(([^)]*)\)(?:\s*:\s*([^{=\s]+(?:\s+[^{=\s]+)*))?\s*/,r=0;for(let a=0;a<n.length;a++){let c=n[a];if(c.length>E){r+=(c.match(/\{/g)?.length??0)-(c.match(/\}/g)?.length??0);continue}let l=c.match(o);if(l&&r<=1){let d=l[1]||"public",p=!!l[2],h=l[3],f=l[4],g=l[5]?.trim();if(g&&g.includes("<")){let x=g.indexOf("<"),w=B(g,x);w!==void 0&&(g=g.substring(0,x)+"<"+w+">")}let b=i[a]-1,y=C(s,b,"@");t.push({name:h,parameters:this.parseParams(f),returnType:g,isAsync:p,isPublic:d==="public",complexity:1,decorators:y,genericParams:[],startLine:i[a],endLine:i[a]})}r+=ce(c),r<0&&(r=0)}return t}extractClasses(e){let t=[],s=e.split(`
|
|
21
21
|
`),{logicalLines:n,lineMap:i}=I(e),o=/^\s*(public|private|protected|internal)?\s*(data|sealed|abstract|open)?\s*class\s+(\w+)(?:<[^{]*>)?(?:\s*(?:\([^)]*\))?\s*:\s*([^{\s]+(?:\s+[^{\s]+)*))?\s*\{?/;for(let r=0;r<n.length;r++){if(n[r].length>E)continue;let a=n[r].match(o);if(a){let c=a[3],l=a[4]?a[4].split(",").map(h=>h.trim().split("(")[0].trim()):[],d=i[r]-1,p=C(s,d,"@");t.push({name:c,methods:[],properties:[],isPublic:(a[1]||"public")==="public",implements:l.slice(1),extends:l[0]||void 0,decorators:p,startLine:i[r],endLine:i[r]})}}return t}extractImports(e){let t=[],s=e.split(`
|
|
22
22
|
`);for(let n of s){let i=n.match(/^\s*import\s+([^\s]+)/);i&&t.push({module:i[1],namedImports:[],isTypeOnly:!1})}return t}parseParams(e){return e.trim()?M(e).map(t=>{let s=t.indexOf(":");if(s===-1)return{name:t.replace("val ","").replace("var ","").trim(),type:void 0,isOptional:!1,defaultValue:void 0};let n=t.substring(0,s).replace("val ","").replace("var ","").trim(),i=t.substring(s+1).trim(),o=i.indexOf("="),r=o>=0?i.substring(0,o).trim():i,a=o>=0;return{name:n,type:r,isOptional:a||r?.endsWith("?")||!1,defaultValue:void 0}}):[]}},re=class{language="dart";supportedExtensions=[".dart"];async parseFile(e,t){return{functions:this.extractFunctions(e),classes:this.extractClasses(e),imports:this.extractImports(e),language:"dart",filePath:t}}extractFunctions(e){let t=[],{logicalLines:s,lineMap:n}=I(e),i=/^\s*([\w<>,.?]+(?:\s+[\w<>,.?]+)*)\s+(\w+)\s*\(([^)]*)\)(?:\s*(async))?\s*\{/;for(let o=0;o<s.length;o++){let r=s[o];if(r.includes(" class ")||r.length>E)continue;let a=r.match(i);if(a){let c=a[1].trim(),l=c;if(c&&c.includes("<")){let f=c.indexOf("<"),g=B(c,f);g!==void 0&&(l=c.substring(0,f)+"<"+g+">")}let d=a[2],p=a[3],h=!!a[4]||l.includes("Future");t.push({name:d,parameters:this.parseParams(p),returnType:l==="void"?void 0:l,isAsync:h,isPublic:!d.startsWith("_"),complexity:1,decorators:[],genericParams:[],startLine:n[o],endLine:n[o]})}}return t}extractClasses(e){let t=[],{logicalLines:s,lineMap:n}=I(e),i=/^\s*(abstract +)?class\s+(\w+)(?:<[^{]*>)?(?:\s+extends\s+(\w+))?(?:\s+(?:with|implements)\s+([^{\s]+(?:\s+[^{\s]+)*))?\s*\{/;for(let o=0;o<s.length;o++){if(s[o].length>E)continue;let r=s[o].match(i);if(r){let a=r[2],c=r[3],l=r[4]?r[4].split(",").map(d=>d.trim()):[];t.push({name:a,methods:[],properties:[],isPublic:!a.startsWith("_"),implements:l,extends:c,decorators:[],startLine:n[o],endLine:n[o]})}}return t}extractImports(e){let t=[],s=e.split(`
|
|
23
|
-
`);for(let n of s){let i=n.match(/^\s*import\s+'([^']+)'/);i&&t.push({module:i[1],namedImports:[],isTypeOnly:!1})}return t}parseParams(e){if(!e.trim())return[];let t=e.replace(/[{}[\]]/g,"");return M(t).map(s=>s.trim()).filter(s=>s).map(s=>{let n=s.replace("required ","").trim().split(/\s+/),i=n[n.length-1]||"",o=n.slice(0,-1).join(" ")||void 0;return{name:i,type:o,isOptional:s.includes("?")||s.includes("{"),defaultValue:void 0}})}},z=ge("ParserRegistry"),xe=["python","java","csharp","rust","swift"],ae=class u{language;supportedExtensions;wasmParser;regexParser;wasmFailCount=0;static MAX_WASM_RETRIES=3;constructor(e,t){this.wasmParser=e,this.regexParser=t,this.language=e.language,this.supportedExtensions=e.supportedExtensions}async parseFile(e,t){if(this.wasmFailCount<u.MAX_WASM_RETRIES)try{return await this.wasmParser.parseFile(e,t)}catch(s){this.wasmFailCount++;let n=s instanceof Error?s.message:String(s),i=this.wasmFailCount>=u.MAX_WASM_RETRIES;z.warn(`[${this.language}] tree-sitter WASM parser failed (attempt ${this.wasmFailCount}/${u.MAX_WASM_RETRIES}): ${n}. Falling back to regex parser (~97-98% accuracy). `+(i?"Set AQE_PARSER_REGEX_ONLY=1 to silence this warning.":"Will retry WASM on next parse."))}return this.regexParser.parseFile(e,t)}},oe=class{parsers=new Map;_wasmInitPromise=null;constructor(){this.register(new Y),this.register(new Z),this.register(new ee),this.register(new te),this.register(new se),this.register(new ne),this.register(new ie),this.register(new re),this._wasmInitPromise=this._tryLoadWasmParsers()}async _tryLoadWasmParsers(){try{let e=await import("./tree-sitter-wasm-parser-IIGEJYFU.js");if(!e.isWasmAvailable()){z.info("tree-sitter WASM parsers disabled or unavailable. Using regex parsers (~97-98% accuracy). Set AQE_PARSER_REGEX_ONLY=0 or ensure web-tree-sitter is installed to enable WASM.");return}let t=e.createWasmParsers();for(let s of xe){let n=t.get(s),i=this.parsers.get(s);n&&i&&this.parsers.set(s,new ae(n,i))}z.info("tree-sitter WASM parsers available for: "+xe.join(", "))}catch{z.info("tree-sitter WASM parser module not available. Using regex parsers for all languages.")}}register(e){this.parsers.set(e.language,e)}getParser(e){return this.parsers.get(e)}async parseFile(e,t,s){this._wasmInitPromise&&(await this._wasmInitPromise,this._wasmInitPromise=null);let n=this.parsers.get(s);if(n)return n.parseFile(e,t)}getSupportedLanguages(){return Array.from(this.parsers.keys())}supportsLanguage(e){return this.parsers.has(e)}},qe=new oe;import*as S from"node:fs/promises";import*as R from"node:path";var Re=[/\.\./,/%2e%2e/i,/%252e%252e/i,/\.\.%2f/i,/%2f\.\./i,/\.\.%5c/i,/\.\.\\/,/%c0%ae/i,/%c0%2f/i,/%c1%9c/i,/\0/,/%00/i],Se=[/^\/etc\//i,/^\/proc\//i,/^\/sys\//i,/^\/dev\//i,/^\/root\//i,/^\/home\/.+\/\./i,/^[A-Z]:\\Windows/i,/^[A-Z]:\\System/i,/^[A-Z]:\\Users\\.+\\AppData/i],le=class{name="path-traversal";getRiskLevel(){return"critical"}validate(e,t={}){let{basePath:s="",allowAbsolute:n=!1,allowedExtensions:i=[],deniedExtensions:o=[".exe",".bat",".cmd",".sh",".ps1",".dll",".so"],maxDepth:r=10,maxLength:a=4096}=t;if(e.length>a)return{valid:!1,error:`Path exceeds maximum length of ${a}`,riskLevel:"medium"};for(let f of Re)if(f.test(e))return{valid:!1,error:"Path traversal attempt detected",riskLevel:"critical"};if(!n&&(e.startsWith("/")||/^[A-Z]:/i.test(e)))return{valid:!1,error:"Absolute paths are not allowed",riskLevel:"high"};for(let f of Se)if(f.test(e))return{valid:!1,error:"Access to system paths is not allowed",riskLevel:"critical"};let c=this.normalizePath(e);if(c.includes(".."))return{valid:!1,error:"Path traversal detected after normalization",riskLevel:"critical"};if(c.split("/").filter(Boolean).length>r)return{valid:!1,error:`Path depth exceeds maximum of ${r}`,riskLevel:"low"};let d=this.getExtension(c);if(d){let f=`.${d.toLowerCase()}`,g=d.toLowerCase();if(o.length>0&&o.some(y=>y.toLowerCase()===f||y.toLowerCase()===g))return{valid:!1,error:`File extension '${d}' is not allowed`,riskLevel:"high"};if(i.length>0&&!i.some(y=>y.toLowerCase()===f||y.toLowerCase()===g))return{valid:!1,error:`File extension '${d}' is not in allowed list`,riskLevel:"medium"}}let p=s?this.joinPathsAbsolute(s,c):c,h=s.startsWith("/")?`/${this.normalizePath(s)}`:this.normalizePath(s);return s&&!p.startsWith(h)?{valid:!1,error:"Path escapes base directory",riskLevel:"critical"}:{valid:!0,normalizedPath:p,riskLevel:"none"}}normalizePath(e){let t=e.replace(/\\/g,"/");t=t.replace(/\/+/g,"/");let s=t.split("/"),n=[];for(let i of s)i==="."||i===""||(i===".."?n.length>0&&n[n.length-1]!==".."&&n.pop():n.push(i));return n.join("/")}joinPaths(...e){return e.length===0?"":e.map(t=>t.replace(/^\/+/,"").replace(/\/+$/,"")).filter(Boolean).join("/")}joinPathsAbsolute(...e){if(e.length===0)return"";let t=e[0].startsWith("/"),s=e.map(n=>{for(;n.startsWith("/");)n=n.slice(1);for(;n.endsWith("/");)n=n.slice(0,-1);return n}).filter(Boolean).join("/");return t?`/${s}`:s}getExtension(e){let t=e.match(/\.([^./\\]+)$/);return t?t[1]:null}},Me=new le,ve=(u,e)=>Me.validate(u,e);ye();var F=class extends Error{constructor(t,s,n,i){super(t);this.filePath=s;this.code=n;this.cause=i;this.name="FileReadError"}filePath;code;cause},V=class extends Error{constructor(t,s,n){super(t);this.filePath=s;this.cause=n;this.name="JsonParseError"}filePath;cause},T=class extends Error{constructor(t,s,n){super(`Path traversal detected: ${s.join(", ")}`);this.requestedPath=t;this.issues=s;this.riskLevel=n;this.name="PathTraversalError"}requestedPath;issues;riskLevel},de=class{constructor(e,t){this.maxSize=e;this.ttlMs=t}maxSize;ttlMs;cache=new Map;accessOrder=[];get(e){let t=this.cache.get(e);if(t){if(Date.now()-t.timestamp>this.ttlMs){this.delete(e);return}return this.updateAccessOrder(e),t.value}}set(e,t,s){for(this.cache.has(e)&&this.delete(e);this.cache.size>=this.maxSize&&this.accessOrder.length>0;){let n=this.accessOrder.shift();n&&this.cache.delete(n)}this.cache.set(e,{value:t,timestamp:Date.now(),size:s}),this.accessOrder.push(e)}delete(e){let t=this.cache.delete(e);if(t){let s=this.accessOrder.indexOf(e);s>-1&&this.accessOrder.splice(s,1)}return t}clear(){this.cache.clear(),this.accessOrder=[]}get size(){return this.cache.size}get totalBytes(){let e=0;return this.cache.forEach(t=>{e+=t.size}),e}updateAccessOrder(e){let t=this.accessOrder.indexOf(e);t>-1&&(this.accessOrder.splice(t,1),this.accessOrder.push(e))}prune(){let e=Date.now(),t=0,s=[];return this.cache.forEach((n,i)=>{e-n.timestamp>this.ttlMs&&s.push(i)}),s.forEach(n=>{this.delete(n),t++}),t}};function Te(u){let e="",t=0;for(;t<u.length;){let s=u[t],n=u[t+1];s==="*"&&n==="*"?u[t+2]==="/"?(e+="(?:.*/)?",t+=3):(e+=".*",t+=2):s==="*"?(e+="[^/]*",t++):s==="?"?(e+="[^/]",t++):".+^${}()|[]\\".includes(s)?(e+="\\"+s,t++):(e+=s,t++)}return new RegExp("^"+e+"$")}async function Ee(u,e,t,s){try{let n=await S.readdir(u,{withFileTypes:!0});for(let i of n){let o=R.join(u,i.name),r=R.relative(s,o);if(i.isDirectory())i.name!=="node_modules"&&!i.name.startsWith(".")&&await Ee(o,e,t,s);else if(i.isFile()){let a=r.replace(/\\/g,"/");e.test(a)&&t.push(o)}}}catch(n){console.debug("[FileReader] Directory read error:",n instanceof Error?n.message:n)}}var k=class{basePath;cache;enableCache;stats={cacheHits:0,cacheMisses:0,totalReads:0,cacheSize:0,cacheEntries:0};constructor(e={}){this.basePath=e.basePath??process.cwd(),this.enableCache=e.enableCache??!0,this.cache=new de(e.maxCacheSize??100,e.cacheTtlMs??300*1e3)}resolvePath(e){let t=R.isAbsolute(e),s=ve(e,{basePath:t?"":this.basePath,allowAbsolute:!0,deniedExtensions:[".exe",".bat",".cmd",".ps1",".dll",".so"]});if(!s.valid)throw new T(e,[s.error||"Path validation failed"],s.riskLevel);if(t&&this.basePath){let n=R.resolve(this.basePath),i=R.resolve(e);if(!i.startsWith(n))throw new T(e,["Path escapes base directory"],"critical");return i}return s.normalizedPath?s.normalizedPath:t?e:R.resolve(this.basePath,e)}async readFile(e){let t;try{t=this.resolvePath(e)}catch(s){if(s instanceof T)return L(s);throw s}if(this.stats.totalReads++,this.enableCache){let s=this.cache.get(t);if(s!==void 0)return this.stats.cacheHits++,this.updateCacheStats(),P(s);this.stats.cacheMisses++}try{let s=await S.readFile(t,"utf-8");return this.enableCache&&(this.cache.set(t,s,Buffer.byteLength(s,"utf-8")),this.updateCacheStats()),P(s)}catch(s){let n=s,i;switch(n.code){case"ENOENT":i="File not found: "+t;break;case"EACCES":i="Permission denied: "+t;break;case"EISDIR":i="Path is a directory: "+t;break;default:i="Failed to read file: "+t}return L(new F(i,t,n.code,n))}}async readJSON(e){let t=await this.readFile(e);if(!t.success)return t;try{let s=D(t.value);return P(s)}catch(s){let n=s,i=e;try{i=this.resolvePath(e)}catch{}return L(new V("Invalid JSON in file: "+i+" - "+n.message,i,n))}}async fileExists(e){let t;try{t=this.resolvePath(e)}catch(s){if(s instanceof T)return L(s);throw s}try{return await S.access(t,S.constants.F_OK),P(!0)}catch(s){let n=s;return n.code==="ENOENT"?P(!1):L(new F("Cannot check file existence: "+t,t,n.code,n))}}async listFiles(e,t){let s;try{s=t?this.resolvePath(t):this.basePath}catch(n){if(n instanceof T)return L(n);throw n}try{if(!(await S.stat(s)).isDirectory())return L(new F("Base path is not a directory: "+s,s,"ENOTDIR"));let i=Te(e),o=[];return await Ee(s,i,o,s),o.sort(),P(o)}catch(n){let i=n;return L(new F("Failed to list files in: "+s,s,i.code,i))}}invalidateCache(e){let t=this.resolvePath(e);this.cache.delete(t),this.updateCacheStats()}clearCache(){this.cache.clear(),this.updateCacheStats()}pruneCache(){let e=this.cache.prune();return this.updateCacheStats(),e}getStats(){return{...this.stats}}resetStats(){this.stats={cacheHits:0,cacheMisses:0,totalReads:0,cacheSize:this.cache.totalBytes,cacheEntries:this.cache.size}}updateCacheStats(){this.stats.cacheSize=this.cache.totalBytes,this.stats.cacheEntries=this.cache.size}};J();var v={MODEL:"all-MiniLM-L6-v2",DIMENSIONS:384,CONTEXT_WINDOW:8192,BATCH_SIZE:100,MAX_RETRIES:3,RETRY_DELAY_MS:1e3,TIMEOUT_MS:3e4,DEFAULT_OLLAMA_URL:"http://localhost:11434"};var _=class{baseUrl;maxRetries;retryDelayMs;timeoutMs;constructor(e=v.DEFAULT_OLLAMA_URL,t=v.MAX_RETRIES,s=v.RETRY_DELAY_MS,n=v.TIMEOUT_MS){this.baseUrl=e.replace(/\/$/,""),this.maxRetries=t,this.retryDelayMs=s,this.timeoutMs=n}async healthCheck(){try{let e=await this.fetchWithTimeout(`${this.baseUrl}/api/tags`,{method:"GET",headers:{"Content-Type":"application/json"}},5e3);if(!e.ok)return!1;let t=await e.json();return t.models?t.models.some(s=>s.name?.startsWith(v.MODEL)||s.model?.startsWith(v.MODEL)):!1}catch{return!1}}async generateEmbedding(e){let t={model:v.MODEL,prompt:e},s=null;for(let n=0;n<this.maxRetries;n++)try{let i=await this.fetchWithTimeout(`${this.baseUrl}/api/embeddings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)},this.timeoutMs);if(!i.ok){let r=await i.text();throw new Error(`Ollama API error (${i.status}): ${r}`)}let o=await i.json();if(o.embedding.length!==v.DIMENSIONS)throw new Error(`Invalid embedding dimensions: expected ${v.DIMENSIONS}, got ${o.embedding.length}`);return o.embedding}catch(i){if(s=A(i),s.message.includes("Invalid embedding dimensions"))throw s;if(n<this.maxRetries-1){let o=this.retryDelayMs*Math.pow(2,n);await this.sleep(o)}}throw new Error(`Failed to generate embedding after ${this.maxRetries} attempts: ${s?.message}`)}async fetchWithTimeout(e,t,s){let n=new AbortController,i=setTimeout(()=>n.abort(),s);try{return await fetch(e,{...t,signal:n.signal})}finally{clearTimeout(i)}}sleep(e){return new Promise(t=>setTimeout(t,e))}async getServerInfo(){try{let e=await this.fetchWithTimeout(`${this.baseUrl}/api/tags`,{method:"GET",headers:{"Content-Type":"application/json"}},5e3);return e.ok?await e.json():null}catch{return null}}async ensureModelAvailable(){if(!await this.healthCheck())throw new Error(`Ollama model '${v.MODEL}' is not available. Please run: ollama pull ${v.MODEL}`)}};import{createHash as Fe}from"crypto";var $=class{cache;maxSize;hits;misses;constructor(e=1e4){this.cache=new Map,this.maxSize=e,this.hits=0,this.misses=0}hashContent(e,t){return Fe("sha256").update(`${t}:${e}`).digest("hex")}get(e,t){let s=this.hashContent(e,t),n=this.cache.get(s);return n?(this.hits++,this.cache.delete(s),this.cache.set(s,n),n.embedding):(this.misses++,null)}set(e,t,s){let n=this.hashContent(e,t);if(this.cache.size>=this.maxSize&&!this.cache.has(n)){let o=this.cache.keys().next().value;o&&this.cache.delete(o)}let i={embedding:s,timestamp:Date.now(),model:t};this.cache.set(n,i)}has(e,t){let s=this.hashContent(e,t);return this.cache.has(s)}getStats(){let e=this.hits+this.misses,t=e>0?this.hits/e:0;return{size:this.cache.size,hitRate:t,hits:this.hits,misses:this.misses}}clear(){this.cache.clear(),this.hits=0,this.misses=0}evictOlderThan(e){let s=Date.now()-e,n=0;for(let[i,o]of this.cache.entries())o.timestamp<s&&(this.cache.delete(i),n++);return n}getMemoryUsageEstimate(){return this.cache.size*3172}export(){return Array.from(this.cache.entries()).map(([e,t])=>({key:e,entry:t}))}import(e){this.cache.clear();for(let{key:t,entry:s}of e)this.cache.size<this.maxSize&&this.cache.set(t,s)}};J();var K=class{client;cache;batchSize;enableFallback;ollamaAvailable=null;constructor(e={}){this.client=new _(e.ollamaBaseUrl),this.cache=e.cache??new $(e.maxCacheSize),this.batchSize=e.batchSize??v.BATCH_SIZE,this.enableFallback=e.enableFallback??!0}async embed(e){let t=this.cache.get(e,v.MODEL);if(t)return t;let s;if(await this.isOllamaAvailable())s=await this.client.generateEmbedding(e);else if(this.enableFallback)s=this.generatePseudoEmbedding(e);else throw new Error(`Ollama is not available and fallback is disabled. Please run: ollama pull ${v.MODEL}`);return this.cache.set(e,v.MODEL,s),s}formatForEmbedding(e){let t=[];e.language&&t.push(e.language),e.type&&t.push(e.type),e.name&&t.push(e.name);let s=t.length>0?`${t.join(" ")}: `:"",n=v.CONTEXT_WINDOW*4,i=e.content.trim();if(s.length+i.length>n){let o=n-s.length-3;i=i.substring(0,o)+"..."}return s+i}async embedBatch(e){let t=[];for(let s of e){let n=await this.embed(s);t.push(n)}return t}async embedCodeChunks(e,t){let s=Date.now(),n=[],i=0,o=0,r=await this.isOllamaAvailable();if(r)await this.client.ensureModelAvailable();else if(!this.enableFallback)throw new Error(`Ollama is not available and fallback is disabled. Please run: ollama pull ${v.MODEL}`);for(let c=0;c<e.length;c+=this.batchSize){let l=e.slice(c,Math.min(c+this.batchSize,e.length)),d=await this.processBatch(l,r);n.push(...d);for(let p of d)p.cached?i++:o++;if(t){let p=c+l.length,h=e.length,g=(Date.now()-s)/p,y=(h-p)*g;t({current:p,total:h,percentage:p/h*100,estimatedTimeRemainingMs:y})}}let a=Date.now()-s;return{results:n,stats:{totalChunks:e.length,cachedHits:i,computedNew:o,totalTimeMs:a,avgTimePerChunk:a/e.length}}}async processBatch(e,t){let s=[],n=e.map(async o=>{let r=this.formatForEmbedding(o),a=Date.now(),c=this.cache.get(r,v.MODEL);if(c)return{chunkId:o.id,embedding:c,model:v.MODEL,cached:!0,computeTimeMs:Date.now()-a};try{let l;return t?l=await this.client.generateEmbedding(r):l=this.generatePseudoEmbedding(r),this.cache.set(r,v.MODEL,l),{chunkId:o.id,embedding:l,model:t?v.MODEL:"pseudo-embedding",cached:!1,computeTimeMs:Date.now()-a}}catch(l){throw new Error(`Failed to generate embedding for chunk ${o.id}: ${G(l)}`)}}),i=await Promise.all(n);return s.push(...i),s}async isOllamaAvailable(){return this.ollamaAvailable!==null?this.ollamaAvailable:(this.ollamaAvailable=await this.client.healthCheck(),this.ollamaAvailable)}resetOllamaCheck(){this.ollamaAvailable=null}generatePseudoEmbedding(e){let t=new Array(v.DIMENSIONS).fill(0),s=e.split(/\s+|[^\w]+/).filter(o=>o.length>0);for(let o=0;o<s.length;o++){let r=s[o];for(let a=0;a<r.length&&a<t.length;a++)t[(o+a)%t.length]+=r.charCodeAt(a)/1e3}let n=[[/class\s+\w+/,0],[/function\s+\w+/,1],[/async\s+|await\s+|Promise/,2],[/interface\s+\w+/,3],[/export\s+/,4],[/import\s+/,5],[/try\s*{/,6],[/\.(map|filter|reduce)\(/,7]];for(let[o,r]of n)o.test(e)&&(t[r]+=.5);let i=Math.sqrt(t.reduce((o,r)=>o+r*r,0))||1;return t.map(o=>o/i)}clearCache(){this.cache.clear()}getCacheStats(){return this.cache.getStats()}async healthCheck(){return await this.client.healthCheck()}async getServerInfo(){return await this.client.getServerInfo()}getDimensions(){return v.DIMENSIONS}getConfig(){return{model:v.MODEL,dimensions:v.DIMENSIONS,contextWindow:v.CONTEXT_WINDOW,batchSize:this.batchSize,maxRetries:v.MAX_RETRIES,enableFallback:this.enableFallback}}};J();ye();import{existsSync as Oe,statSync as ke}from"fs";import{dirname as _e,resolve as $e,join as q}from"path";function Ae(u){switch(u){case"ts":case"mts":case"cts":return"tree-sitter-typescript.wasm";case"tsx":return"tree-sitter-tsx.wasm";case"js":case"jsx":case"mjs":case"cjs":return"tree-sitter-javascript.wasm";default:return null}}var U=u=>u.startPosition.row+1,j=(u,e)=>u.childForFieldName(e)?.text??"";function ue(u){for(let e=0;e<u.childCount;e++){let t=u.child(e);if(t){if(t.type==="async")return!0;if(t.type==="function"||t.type==="function_declaration")break}}return!1}function Ne(u){for(let e=0;e<u.childCount;e++)if(u.child(e)?.type==="accessibility_modifier"){let s=u.child(e).text;if(s==="private")return"private";if(s==="protected")return"protected"}return"public"}function De(u){let e=j(u,"name")||"(anonymous)",t=u.childForFieldName("body"),s=[];if(t)for(let n=0;n<t.childCount;n++){let i=t.child(n);i&&i.type==="method_definition"&&s.push({name:j(i,"name"),startLine:U(i),isAsync:ue(i),visibility:Ne(i)})}return{name:e,startLine:U(u),methods:s}}function pe(u){return u.replace(/^['"`]|['"`]$/g,"")}async function me(u,e){let t=Ae(e);if(!t)return null;let s=await be(t);if(!s)return null;let n=null;try{let i=s.parse(u);n=i;let o=i.rootNode;if(!o)return null;let r={functions:[],classes:[],interfaces:[],imports:[]},a=[o];for(;a.length;){let c=a.pop(),l=!0;switch(c.type){case"function_declaration":case"generator_function_declaration":r.functions.push({name:j(c,"name"),startLine:U(c),isAsync:ue(c),visibility:"public"}),l=!1;break;case"class_declaration":case"class":r.classes.push(De(c)),l=!1;break;case"interface_declaration":r.interfaces.push({name:j(c,"name"),startLine:U(c)}),l=!1;break;case"lexical_declaration":case"variable_declaration":{for(let d=0;d<c.childCount;d++){let p=c.child(d);if(!p||p.type!=="variable_declarator")continue;let h=p.childForFieldName("value");if(h&&(h.type==="arrow_function"||h.type==="function"||h.type==="function_expression"))r.functions.push({name:j(p,"name"),startLine:U(p),isAsync:ue(h),visibility:"public"});else if(h&&h.type==="call_expression"&&h.child(0)?.text==="require"){let f=h.childForFieldName("arguments")?.child(1);f&&f.type==="string"&&r.imports.push(pe(f.text))}}l=!1;break}case"import_statement":{let d=c.childForFieldName("source");d&&r.imports.push(pe(d.text)),l=!1;break}case"call_expression":{let d=c.child(0);if(d&&d.text==="require"){let h=c.childForFieldName("arguments")?.child(1);h&&h.type==="string"&&r.imports.push(pe(h.text))}break}}if(l)for(let d=c.childCount-1;d>=0;d--){let p=c.child(d);p&&a.push(p)}}return r}catch{return null}finally{n?.delete?.()}}var Ke={maxNodes:1e5,maxEdgesPerNode:500,namespace:"code-intelligence:kg",enableVectorEmbeddings:!0,embeddingDimension:384,enableLLMExtraction:!0,llmModelTier:2,llmMaxTokens:2048},he=fe.create("code-intelligence/knowledge-graph"),H=new Set(["ts","tsx","js","jsx"]),Ie=class{config;memory;nodeCache=new Map;edgeIndex=new Map;allEdgesCache;tsParser;fileReader;embedder;llmRouter;constructor(e,t={}){this.config={...Ke,...t},this.isKnowledgeGraphDependencies(e)?(this.memory=e.memory,this.llmRouter=e.llmRouter):(this.memory=e,this.llmRouter=void 0),this.tsParser=new N,this.fileReader=new k,this.embedder=new K({enableFallback:!0})}isKnowledgeGraphDependencies(e){return e.memory!==void 0}get nsOpts(){return{namespace:this.config.namespace}}async index(e){let t=Date.now(),s=[],n=0,i=0,o=new Map;try{let{paths:r,incremental:a=!1,includeTests:c=!0,languages:l}=e;a||await this.clear();for(let h of r)try{if(l&&l.length>0){let b=this.getFileExtension(h);if(!this.matchesLanguage(b,l))continue}if(!c&&this.isTestFile(h))continue;let f=this.getFileExtension(h);H.has(f)||o.set(f||"(none)",(o.get(f||"(none)")??0)+1);let g=await this.indexFile(h,a);n+=g.nodes,i+=g.edges}catch(f){s.push({file:h,error:G(f)})}let d=Date.now()-t,p=[];if(o.size>0){let h=Array.from(H).join(", ");for(let[f,g]of o){let b=`${g} file(s) with extension '.${f}' were indexed as plain nodes: no dependency extractor for this language, so 'deps'/'impact' will report 0 edges for them. Supported: ${h}.`;p.push(b),he.warn(b)}}return await this.storeIndexMetadata({filesIndexed:r.length-s.length,nodesCreated:n,edgesCreated:i,duration:d,indexedAt:new Date().toISOString()}),P({filesIndexed:r.length-s.length,nodesCreated:n,edgesCreated:i,duration:d,errors:s,warnings:p})}catch(r){return L(A(r))}}async query(e){try{let{query:t,type:s,limit:n=100}=e;return s==="cypher"?this.executeCypherQuery(t,n):this.executeNaturalLanguageQuery(t,n)}catch(t){return L(A(t))}}async mapDependencies(e){try{let{files:t,direction:s,depth:n=3}=e,i=[],o=[],r=new Set,a=[];for(let l of t)await this.traverseDependencies(l,s,n,r,i,o,[],a);let c=this.calculateDependencyMetrics(i,o);return P({nodes:i,edges:o,cycles:a,metrics:c})}catch(t){return L(A(t))}}async getNode(e){if(this.nodeCache.has(e))return this.nodeCache.get(e);let t=`${this.config.namespace}:node:${e}`,s=await this.memory.get(t,this.nsOpts);return s&&this.nodeCache.set(e,s),s}async getEdges(e,t){let s=await this.loadAllEdges();return this.filterEdgesByDirection(s,e,t)}async loadAllEdges(){if(this.allEdgesCache)return this.allEdgesCache;let e=[],t=`${this.config.namespace}:edge:*`,s=await this.memory.search(t,Number.MAX_SAFE_INTEGER,this.nsOpts);for(let n of s){let i=await this.memory.get(n,this.nsOpts);i&&e.push(i)}return this.allEdgesCache=e,e}async clear(){this.nodeCache.clear(),this.edgeIndex.clear(),this.allEdgesCache=void 0;for(let e of[`${this.config.namespace}:node:`,`${this.config.namespace}:edge:`]){let t=await this.memory.search(`${e}*`,Number.MAX_SAFE_INTEGER,this.nsOpts);for(let s of t)await this.memory.delete(s,this.nsOpts)}}async removeFileFromGraph(e){let t=this.pathToNodeId(e),s=this.config.namespace,n=await this.memory.search(`${s}:node:${t}*`,Number.MAX_SAFE_INTEGER,this.nsOpts);for(let o of n)await this.memory.delete(o,this.nsOpts),this.nodeCache.delete(o.slice(`${s}:node:`.length));let i=await this.memory.search(`${s}:edge:*`,Number.MAX_SAFE_INTEGER,this.nsOpts);for(let o of i){let r=await this.memory.get(o,this.nsOpts);r&&(r.source===t||r.source.startsWith(`${t}:`))&&await this.memory.delete(o,this.nsOpts)}this.edgeIndex.delete(t),this.allEdgesCache=void 0}isLLMExtractionAvailable(){return this.config.enableLLMExtraction===!0&&this.llmRouter!==void 0}getModelForTier(e){switch(e){case 1:return"claude-haiku-4-5-20251001";case 2:return"claude-sonnet-4-6";case 3:return"claude-sonnet-4-6";case 4:return"claude-opus-4-7";default:return"claude-sonnet-4-6"}}async extractRelationshipsWithLLM(e,t){if(!this.llmRouter)return{semanticRelationships:[],designPatterns:[],architecturalBoundaries:[],dependencyImpacts:[]};try{let s=this.buildRelationshipExtractionPrompt(e,t),n=this.getModelForTier(this.config.llmModelTier??2),i=await this.llmRouter.chat({messages:[{role:"system",content:`You are an expert software architect analyzing code structure. Extract:
|
|
23
|
+
`);for(let n of s){let i=n.match(/^\s*import\s+'([^']+)'/);i&&t.push({module:i[1],namedImports:[],isTypeOnly:!1})}return t}parseParams(e){if(!e.trim())return[];let t=e.replace(/[{}[\]]/g,"");return M(t).map(s=>s.trim()).filter(s=>s).map(s=>{let n=s.replace("required ","").trim().split(/\s+/),i=n[n.length-1]||"",o=n.slice(0,-1).join(" ")||void 0;return{name:i,type:o,isOptional:s.includes("?")||s.includes("{"),defaultValue:void 0}})}},z=ge("ParserRegistry"),xe=["python","java","csharp","rust","swift"],ae=class u{language;supportedExtensions;wasmParser;regexParser;wasmFailCount=0;static MAX_WASM_RETRIES=3;constructor(e,t){this.wasmParser=e,this.regexParser=t,this.language=e.language,this.supportedExtensions=e.supportedExtensions}async parseFile(e,t){if(this.wasmFailCount<u.MAX_WASM_RETRIES)try{return await this.wasmParser.parseFile(e,t)}catch(s){this.wasmFailCount++;let n=s instanceof Error?s.message:String(s),i=this.wasmFailCount>=u.MAX_WASM_RETRIES;z.warn(`[${this.language}] tree-sitter WASM parser failed (attempt ${this.wasmFailCount}/${u.MAX_WASM_RETRIES}): ${n}. Falling back to regex parser (~97-98% accuracy). `+(i?"Set AQE_PARSER_REGEX_ONLY=1 to silence this warning.":"Will retry WASM on next parse."))}return this.regexParser.parseFile(e,t)}},oe=class{parsers=new Map;_wasmInitPromise=null;constructor(){this.register(new Y),this.register(new Z),this.register(new ee),this.register(new te),this.register(new se),this.register(new ne),this.register(new ie),this.register(new re),this._wasmInitPromise=this._tryLoadWasmParsers()}async _tryLoadWasmParsers(){try{let e=await import("./tree-sitter-wasm-parser-H6BU2E5R.js");if(!e.isWasmAvailable()){z.info("tree-sitter WASM parsers disabled or unavailable. Using regex parsers (~97-98% accuracy). Set AQE_PARSER_REGEX_ONLY=0 or ensure web-tree-sitter is installed to enable WASM.");return}let t=e.createWasmParsers();for(let s of xe){let n=t.get(s),i=this.parsers.get(s);n&&i&&this.parsers.set(s,new ae(n,i))}z.info("tree-sitter WASM parsers available for: "+xe.join(", "))}catch{z.info("tree-sitter WASM parser module not available. Using regex parsers for all languages.")}}register(e){this.parsers.set(e.language,e)}getParser(e){return this.parsers.get(e)}async parseFile(e,t,s){this._wasmInitPromise&&(await this._wasmInitPromise,this._wasmInitPromise=null);let n=this.parsers.get(s);if(n)return n.parseFile(e,t)}getSupportedLanguages(){return Array.from(this.parsers.keys())}supportsLanguage(e){return this.parsers.has(e)}},qe=new oe;import*as S from"node:fs/promises";import*as R from"node:path";var Re=[/\.\./,/%2e%2e/i,/%252e%252e/i,/\.\.%2f/i,/%2f\.\./i,/\.\.%5c/i,/\.\.\\/,/%c0%ae/i,/%c0%2f/i,/%c1%9c/i,/\0/,/%00/i],Se=[/^\/etc\//i,/^\/proc\//i,/^\/sys\//i,/^\/dev\//i,/^\/root\//i,/^\/home\/.+\/\./i,/^[A-Z]:\\Windows/i,/^[A-Z]:\\System/i,/^[A-Z]:\\Users\\.+\\AppData/i],le=class{name="path-traversal";getRiskLevel(){return"critical"}validate(e,t={}){let{basePath:s="",allowAbsolute:n=!1,allowedExtensions:i=[],deniedExtensions:o=[".exe",".bat",".cmd",".sh",".ps1",".dll",".so"],maxDepth:r=10,maxLength:a=4096}=t;if(e.length>a)return{valid:!1,error:`Path exceeds maximum length of ${a}`,riskLevel:"medium"};for(let f of Re)if(f.test(e))return{valid:!1,error:"Path traversal attempt detected",riskLevel:"critical"};if(!n&&(e.startsWith("/")||/^[A-Z]:/i.test(e)))return{valid:!1,error:"Absolute paths are not allowed",riskLevel:"high"};for(let f of Se)if(f.test(e))return{valid:!1,error:"Access to system paths is not allowed",riskLevel:"critical"};let c=this.normalizePath(e);if(c.includes(".."))return{valid:!1,error:"Path traversal detected after normalization",riskLevel:"critical"};if(c.split("/").filter(Boolean).length>r)return{valid:!1,error:`Path depth exceeds maximum of ${r}`,riskLevel:"low"};let d=this.getExtension(c);if(d){let f=`.${d.toLowerCase()}`,g=d.toLowerCase();if(o.length>0&&o.some(y=>y.toLowerCase()===f||y.toLowerCase()===g))return{valid:!1,error:`File extension '${d}' is not allowed`,riskLevel:"high"};if(i.length>0&&!i.some(y=>y.toLowerCase()===f||y.toLowerCase()===g))return{valid:!1,error:`File extension '${d}' is not in allowed list`,riskLevel:"medium"}}let p=s?this.joinPathsAbsolute(s,c):c,h=s.startsWith("/")?`/${this.normalizePath(s)}`:this.normalizePath(s);return s&&!p.startsWith(h)?{valid:!1,error:"Path escapes base directory",riskLevel:"critical"}:{valid:!0,normalizedPath:p,riskLevel:"none"}}normalizePath(e){let t=e.replace(/\\/g,"/");t=t.replace(/\/+/g,"/");let s=t.split("/"),n=[];for(let i of s)i==="."||i===""||(i===".."?n.length>0&&n[n.length-1]!==".."&&n.pop():n.push(i));return n.join("/")}joinPaths(...e){return e.length===0?"":e.map(t=>t.replace(/^\/+/,"").replace(/\/+$/,"")).filter(Boolean).join("/")}joinPathsAbsolute(...e){if(e.length===0)return"";let t=e[0].startsWith("/"),s=e.map(n=>{for(;n.startsWith("/");)n=n.slice(1);for(;n.endsWith("/");)n=n.slice(0,-1);return n}).filter(Boolean).join("/");return t?`/${s}`:s}getExtension(e){let t=e.match(/\.([^./\\]+)$/);return t?t[1]:null}},Me=new le,ve=(u,e)=>Me.validate(u,e);ye();var F=class extends Error{constructor(t,s,n,i){super(t);this.filePath=s;this.code=n;this.cause=i;this.name="FileReadError"}filePath;code;cause},V=class extends Error{constructor(t,s,n){super(t);this.filePath=s;this.cause=n;this.name="JsonParseError"}filePath;cause},T=class extends Error{constructor(t,s,n){super(`Path traversal detected: ${s.join(", ")}`);this.requestedPath=t;this.issues=s;this.riskLevel=n;this.name="PathTraversalError"}requestedPath;issues;riskLevel},de=class{constructor(e,t){this.maxSize=e;this.ttlMs=t}maxSize;ttlMs;cache=new Map;accessOrder=[];get(e){let t=this.cache.get(e);if(t){if(Date.now()-t.timestamp>this.ttlMs){this.delete(e);return}return this.updateAccessOrder(e),t.value}}set(e,t,s){for(this.cache.has(e)&&this.delete(e);this.cache.size>=this.maxSize&&this.accessOrder.length>0;){let n=this.accessOrder.shift();n&&this.cache.delete(n)}this.cache.set(e,{value:t,timestamp:Date.now(),size:s}),this.accessOrder.push(e)}delete(e){let t=this.cache.delete(e);if(t){let s=this.accessOrder.indexOf(e);s>-1&&this.accessOrder.splice(s,1)}return t}clear(){this.cache.clear(),this.accessOrder=[]}get size(){return this.cache.size}get totalBytes(){let e=0;return this.cache.forEach(t=>{e+=t.size}),e}updateAccessOrder(e){let t=this.accessOrder.indexOf(e);t>-1&&(this.accessOrder.splice(t,1),this.accessOrder.push(e))}prune(){let e=Date.now(),t=0,s=[];return this.cache.forEach((n,i)=>{e-n.timestamp>this.ttlMs&&s.push(i)}),s.forEach(n=>{this.delete(n),t++}),t}};function Te(u){let e="",t=0;for(;t<u.length;){let s=u[t],n=u[t+1];s==="*"&&n==="*"?u[t+2]==="/"?(e+="(?:.*/)?",t+=3):(e+=".*",t+=2):s==="*"?(e+="[^/]*",t++):s==="?"?(e+="[^/]",t++):".+^${}()|[]\\".includes(s)?(e+="\\"+s,t++):(e+=s,t++)}return new RegExp("^"+e+"$")}async function Ee(u,e,t,s){try{let n=await S.readdir(u,{withFileTypes:!0});for(let i of n){let o=R.join(u,i.name),r=R.relative(s,o);if(i.isDirectory())i.name!=="node_modules"&&!i.name.startsWith(".")&&await Ee(o,e,t,s);else if(i.isFile()){let a=r.replace(/\\/g,"/");e.test(a)&&t.push(o)}}}catch(n){console.debug("[FileReader] Directory read error:",n instanceof Error?n.message:n)}}var k=class{basePath;cache;enableCache;stats={cacheHits:0,cacheMisses:0,totalReads:0,cacheSize:0,cacheEntries:0};constructor(e={}){this.basePath=e.basePath??process.cwd(),this.enableCache=e.enableCache??!0,this.cache=new de(e.maxCacheSize??100,e.cacheTtlMs??300*1e3)}resolvePath(e){let t=R.isAbsolute(e),s=ve(e,{basePath:t?"":this.basePath,allowAbsolute:!0,deniedExtensions:[".exe",".bat",".cmd",".ps1",".dll",".so"]});if(!s.valid)throw new T(e,[s.error||"Path validation failed"],s.riskLevel);if(t&&this.basePath){let n=R.resolve(this.basePath),i=R.resolve(e);if(!i.startsWith(n))throw new T(e,["Path escapes base directory"],"critical");return i}return s.normalizedPath?s.normalizedPath:t?e:R.resolve(this.basePath,e)}async readFile(e){let t;try{t=this.resolvePath(e)}catch(s){if(s instanceof T)return L(s);throw s}if(this.stats.totalReads++,this.enableCache){let s=this.cache.get(t);if(s!==void 0)return this.stats.cacheHits++,this.updateCacheStats(),P(s);this.stats.cacheMisses++}try{let s=await S.readFile(t,"utf-8");return this.enableCache&&(this.cache.set(t,s,Buffer.byteLength(s,"utf-8")),this.updateCacheStats()),P(s)}catch(s){let n=s,i;switch(n.code){case"ENOENT":i="File not found: "+t;break;case"EACCES":i="Permission denied: "+t;break;case"EISDIR":i="Path is a directory: "+t;break;default:i="Failed to read file: "+t}return L(new F(i,t,n.code,n))}}async readJSON(e){let t=await this.readFile(e);if(!t.success)return t;try{let s=D(t.value);return P(s)}catch(s){let n=s,i=e;try{i=this.resolvePath(e)}catch{}return L(new V("Invalid JSON in file: "+i+" - "+n.message,i,n))}}async fileExists(e){let t;try{t=this.resolvePath(e)}catch(s){if(s instanceof T)return L(s);throw s}try{return await S.access(t,S.constants.F_OK),P(!0)}catch(s){let n=s;return n.code==="ENOENT"?P(!1):L(new F("Cannot check file existence: "+t,t,n.code,n))}}async listFiles(e,t){let s;try{s=t?this.resolvePath(t):this.basePath}catch(n){if(n instanceof T)return L(n);throw n}try{if(!(await S.stat(s)).isDirectory())return L(new F("Base path is not a directory: "+s,s,"ENOTDIR"));let i=Te(e),o=[];return await Ee(s,i,o,s),o.sort(),P(o)}catch(n){let i=n;return L(new F("Failed to list files in: "+s,s,i.code,i))}}invalidateCache(e){let t=this.resolvePath(e);this.cache.delete(t),this.updateCacheStats()}clearCache(){this.cache.clear(),this.updateCacheStats()}pruneCache(){let e=this.cache.prune();return this.updateCacheStats(),e}getStats(){return{...this.stats}}resetStats(){this.stats={cacheHits:0,cacheMisses:0,totalReads:0,cacheSize:this.cache.totalBytes,cacheEntries:this.cache.size}}updateCacheStats(){this.stats.cacheSize=this.cache.totalBytes,this.stats.cacheEntries=this.cache.size}};J();var v={MODEL:"all-MiniLM-L6-v2",DIMENSIONS:384,CONTEXT_WINDOW:8192,BATCH_SIZE:100,MAX_RETRIES:3,RETRY_DELAY_MS:1e3,TIMEOUT_MS:3e4,DEFAULT_OLLAMA_URL:"http://localhost:11434"};var _=class{baseUrl;maxRetries;retryDelayMs;timeoutMs;constructor(e=v.DEFAULT_OLLAMA_URL,t=v.MAX_RETRIES,s=v.RETRY_DELAY_MS,n=v.TIMEOUT_MS){this.baseUrl=e.replace(/\/$/,""),this.maxRetries=t,this.retryDelayMs=s,this.timeoutMs=n}async healthCheck(){try{let e=await this.fetchWithTimeout(`${this.baseUrl}/api/tags`,{method:"GET",headers:{"Content-Type":"application/json"}},5e3);if(!e.ok)return!1;let t=await e.json();return t.models?t.models.some(s=>s.name?.startsWith(v.MODEL)||s.model?.startsWith(v.MODEL)):!1}catch{return!1}}async generateEmbedding(e){let t={model:v.MODEL,prompt:e},s=null;for(let n=0;n<this.maxRetries;n++)try{let i=await this.fetchWithTimeout(`${this.baseUrl}/api/embeddings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)},this.timeoutMs);if(!i.ok){let r=await i.text();throw new Error(`Ollama API error (${i.status}): ${r}`)}let o=await i.json();if(o.embedding.length!==v.DIMENSIONS)throw new Error(`Invalid embedding dimensions: expected ${v.DIMENSIONS}, got ${o.embedding.length}`);return o.embedding}catch(i){if(s=A(i),s.message.includes("Invalid embedding dimensions"))throw s;if(n<this.maxRetries-1){let o=this.retryDelayMs*Math.pow(2,n);await this.sleep(o)}}throw new Error(`Failed to generate embedding after ${this.maxRetries} attempts: ${s?.message}`)}async fetchWithTimeout(e,t,s){let n=new AbortController,i=setTimeout(()=>n.abort(),s);try{return await fetch(e,{...t,signal:n.signal})}finally{clearTimeout(i)}}sleep(e){return new Promise(t=>setTimeout(t,e))}async getServerInfo(){try{let e=await this.fetchWithTimeout(`${this.baseUrl}/api/tags`,{method:"GET",headers:{"Content-Type":"application/json"}},5e3);return e.ok?await e.json():null}catch{return null}}async ensureModelAvailable(){if(!await this.healthCheck())throw new Error(`Ollama model '${v.MODEL}' is not available. Please run: ollama pull ${v.MODEL}`)}};import{createHash as Fe}from"crypto";var $=class{cache;maxSize;hits;misses;constructor(e=1e4){this.cache=new Map,this.maxSize=e,this.hits=0,this.misses=0}hashContent(e,t){return Fe("sha256").update(`${t}:${e}`).digest("hex")}get(e,t){let s=this.hashContent(e,t),n=this.cache.get(s);return n?(this.hits++,this.cache.delete(s),this.cache.set(s,n),n.embedding):(this.misses++,null)}set(e,t,s){let n=this.hashContent(e,t);if(this.cache.size>=this.maxSize&&!this.cache.has(n)){let o=this.cache.keys().next().value;o&&this.cache.delete(o)}let i={embedding:s,timestamp:Date.now(),model:t};this.cache.set(n,i)}has(e,t){let s=this.hashContent(e,t);return this.cache.has(s)}getStats(){let e=this.hits+this.misses,t=e>0?this.hits/e:0;return{size:this.cache.size,hitRate:t,hits:this.hits,misses:this.misses}}clear(){this.cache.clear(),this.hits=0,this.misses=0}evictOlderThan(e){let s=Date.now()-e,n=0;for(let[i,o]of this.cache.entries())o.timestamp<s&&(this.cache.delete(i),n++);return n}getMemoryUsageEstimate(){return this.cache.size*3172}export(){return Array.from(this.cache.entries()).map(([e,t])=>({key:e,entry:t}))}import(e){this.cache.clear();for(let{key:t,entry:s}of e)this.cache.size<this.maxSize&&this.cache.set(t,s)}};J();var K=class{client;cache;batchSize;enableFallback;ollamaAvailable=null;constructor(e={}){this.client=new _(e.ollamaBaseUrl),this.cache=e.cache??new $(e.maxCacheSize),this.batchSize=e.batchSize??v.BATCH_SIZE,this.enableFallback=e.enableFallback??!0}async embed(e){let t=this.cache.get(e,v.MODEL);if(t)return t;let s;if(await this.isOllamaAvailable())s=await this.client.generateEmbedding(e);else if(this.enableFallback)s=this.generatePseudoEmbedding(e);else throw new Error(`Ollama is not available and fallback is disabled. Please run: ollama pull ${v.MODEL}`);return this.cache.set(e,v.MODEL,s),s}formatForEmbedding(e){let t=[];e.language&&t.push(e.language),e.type&&t.push(e.type),e.name&&t.push(e.name);let s=t.length>0?`${t.join(" ")}: `:"",n=v.CONTEXT_WINDOW*4,i=e.content.trim();if(s.length+i.length>n){let o=n-s.length-3;i=i.substring(0,o)+"..."}return s+i}async embedBatch(e){let t=[];for(let s of e){let n=await this.embed(s);t.push(n)}return t}async embedCodeChunks(e,t){let s=Date.now(),n=[],i=0,o=0,r=await this.isOllamaAvailable();if(r)await this.client.ensureModelAvailable();else if(!this.enableFallback)throw new Error(`Ollama is not available and fallback is disabled. Please run: ollama pull ${v.MODEL}`);for(let c=0;c<e.length;c+=this.batchSize){let l=e.slice(c,Math.min(c+this.batchSize,e.length)),d=await this.processBatch(l,r);n.push(...d);for(let p of d)p.cached?i++:o++;if(t){let p=c+l.length,h=e.length,g=(Date.now()-s)/p,y=(h-p)*g;t({current:p,total:h,percentage:p/h*100,estimatedTimeRemainingMs:y})}}let a=Date.now()-s;return{results:n,stats:{totalChunks:e.length,cachedHits:i,computedNew:o,totalTimeMs:a,avgTimePerChunk:a/e.length}}}async processBatch(e,t){let s=[],n=e.map(async o=>{let r=this.formatForEmbedding(o),a=Date.now(),c=this.cache.get(r,v.MODEL);if(c)return{chunkId:o.id,embedding:c,model:v.MODEL,cached:!0,computeTimeMs:Date.now()-a};try{let l;return t?l=await this.client.generateEmbedding(r):l=this.generatePseudoEmbedding(r),this.cache.set(r,v.MODEL,l),{chunkId:o.id,embedding:l,model:t?v.MODEL:"pseudo-embedding",cached:!1,computeTimeMs:Date.now()-a}}catch(l){throw new Error(`Failed to generate embedding for chunk ${o.id}: ${G(l)}`)}}),i=await Promise.all(n);return s.push(...i),s}async isOllamaAvailable(){return this.ollamaAvailable!==null?this.ollamaAvailable:(this.ollamaAvailable=await this.client.healthCheck(),this.ollamaAvailable)}resetOllamaCheck(){this.ollamaAvailable=null}generatePseudoEmbedding(e){let t=new Array(v.DIMENSIONS).fill(0),s=e.split(/\s+|[^\w]+/).filter(o=>o.length>0);for(let o=0;o<s.length;o++){let r=s[o];for(let a=0;a<r.length&&a<t.length;a++)t[(o+a)%t.length]+=r.charCodeAt(a)/1e3}let n=[[/class\s+\w+/,0],[/function\s+\w+/,1],[/async\s+|await\s+|Promise/,2],[/interface\s+\w+/,3],[/export\s+/,4],[/import\s+/,5],[/try\s*{/,6],[/\.(map|filter|reduce)\(/,7]];for(let[o,r]of n)o.test(e)&&(t[r]+=.5);let i=Math.sqrt(t.reduce((o,r)=>o+r*r,0))||1;return t.map(o=>o/i)}clearCache(){this.cache.clear()}getCacheStats(){return this.cache.getStats()}async healthCheck(){return await this.client.healthCheck()}async getServerInfo(){return await this.client.getServerInfo()}getDimensions(){return v.DIMENSIONS}getConfig(){return{model:v.MODEL,dimensions:v.DIMENSIONS,contextWindow:v.CONTEXT_WINDOW,batchSize:this.batchSize,maxRetries:v.MAX_RETRIES,enableFallback:this.enableFallback}}};J();ye();import{existsSync as Oe,statSync as ke}from"fs";import{dirname as _e,resolve as $e,join as q}from"path";function Ae(u){switch(u){case"ts":case"mts":case"cts":return"tree-sitter-typescript.wasm";case"tsx":return"tree-sitter-tsx.wasm";case"js":case"jsx":case"mjs":case"cjs":return"tree-sitter-javascript.wasm";default:return null}}var U=u=>u.startPosition.row+1,j=(u,e)=>u.childForFieldName(e)?.text??"";function ue(u){for(let e=0;e<u.childCount;e++){let t=u.child(e);if(t){if(t.type==="async")return!0;if(t.type==="function"||t.type==="function_declaration")break}}return!1}function Ne(u){for(let e=0;e<u.childCount;e++)if(u.child(e)?.type==="accessibility_modifier"){let s=u.child(e).text;if(s==="private")return"private";if(s==="protected")return"protected"}return"public"}function De(u){let e=j(u,"name")||"(anonymous)",t=u.childForFieldName("body"),s=[];if(t)for(let n=0;n<t.childCount;n++){let i=t.child(n);i&&i.type==="method_definition"&&s.push({name:j(i,"name"),startLine:U(i),isAsync:ue(i),visibility:Ne(i)})}return{name:e,startLine:U(u),methods:s}}function pe(u){return u.replace(/^['"`]|['"`]$/g,"")}async function me(u,e){let t=Ae(e);if(!t)return null;let s=await be(t);if(!s)return null;let n=null;try{let i=s.parse(u);n=i;let o=i.rootNode;if(!o)return null;let r={functions:[],classes:[],interfaces:[],imports:[]},a=[o];for(;a.length;){let c=a.pop(),l=!0;switch(c.type){case"function_declaration":case"generator_function_declaration":r.functions.push({name:j(c,"name"),startLine:U(c),isAsync:ue(c),visibility:"public"}),l=!1;break;case"class_declaration":case"class":r.classes.push(De(c)),l=!1;break;case"interface_declaration":r.interfaces.push({name:j(c,"name"),startLine:U(c)}),l=!1;break;case"lexical_declaration":case"variable_declaration":{for(let d=0;d<c.childCount;d++){let p=c.child(d);if(!p||p.type!=="variable_declarator")continue;let h=p.childForFieldName("value");if(h&&(h.type==="arrow_function"||h.type==="function"||h.type==="function_expression"))r.functions.push({name:j(p,"name"),startLine:U(p),isAsync:ue(h),visibility:"public"});else if(h&&h.type==="call_expression"&&h.child(0)?.text==="require"){let f=h.childForFieldName("arguments")?.child(1);f&&f.type==="string"&&r.imports.push(pe(f.text))}}l=!1;break}case"import_statement":{let d=c.childForFieldName("source");d&&r.imports.push(pe(d.text)),l=!1;break}case"call_expression":{let d=c.child(0);if(d&&d.text==="require"){let h=c.childForFieldName("arguments")?.child(1);h&&h.type==="string"&&r.imports.push(pe(h.text))}break}}if(l)for(let d=c.childCount-1;d>=0;d--){let p=c.child(d);p&&a.push(p)}}return r}catch{return null}finally{n?.delete?.()}}var Ke={maxNodes:1e5,maxEdgesPerNode:500,namespace:"code-intelligence:kg",enableVectorEmbeddings:!0,embeddingDimension:384,enableLLMExtraction:!0,llmModelTier:2,llmMaxTokens:2048},he=fe.create("code-intelligence/knowledge-graph"),H=new Set(["ts","tsx","js","jsx"]),Ie=class{config;memory;nodeCache=new Map;edgeIndex=new Map;allEdgesCache;tsParser;fileReader;embedder;llmRouter;constructor(e,t={}){this.config={...Ke,...t},this.isKnowledgeGraphDependencies(e)?(this.memory=e.memory,this.llmRouter=e.llmRouter):(this.memory=e,this.llmRouter=void 0),this.tsParser=new N,this.fileReader=new k,this.embedder=new K({enableFallback:!0})}isKnowledgeGraphDependencies(e){return e.memory!==void 0}get nsOpts(){return{namespace:this.config.namespace}}async index(e){let t=Date.now(),s=[],n=0,i=0,o=new Map;try{let{paths:r,incremental:a=!1,includeTests:c=!0,languages:l}=e;a||await this.clear();for(let h of r)try{if(l&&l.length>0){let b=this.getFileExtension(h);if(!this.matchesLanguage(b,l))continue}if(!c&&this.isTestFile(h))continue;let f=this.getFileExtension(h);H.has(f)||o.set(f||"(none)",(o.get(f||"(none)")??0)+1);let g=await this.indexFile(h,a);n+=g.nodes,i+=g.edges}catch(f){s.push({file:h,error:G(f)})}let d=Date.now()-t,p=[];if(o.size>0){let h=Array.from(H).join(", ");for(let[f,g]of o){let b=`${g} file(s) with extension '.${f}' were indexed as plain nodes: no dependency extractor for this language, so 'deps'/'impact' will report 0 edges for them. Supported: ${h}.`;p.push(b),he.warn(b)}}return await this.storeIndexMetadata({filesIndexed:r.length-s.length,nodesCreated:n,edgesCreated:i,duration:d,indexedAt:new Date().toISOString()}),P({filesIndexed:r.length-s.length,nodesCreated:n,edgesCreated:i,duration:d,errors:s,warnings:p})}catch(r){return L(A(r))}}async query(e){try{let{query:t,type:s,limit:n=100}=e;return s==="cypher"?this.executeCypherQuery(t,n):this.executeNaturalLanguageQuery(t,n)}catch(t){return L(A(t))}}async mapDependencies(e){try{let{files:t,direction:s,depth:n=3}=e,i=[],o=[],r=new Set,a=[];for(let l of t)await this.traverseDependencies(l,s,n,r,i,o,[],a);let c=this.calculateDependencyMetrics(i,o);return P({nodes:i,edges:o,cycles:a,metrics:c})}catch(t){return L(A(t))}}async getNode(e){if(this.nodeCache.has(e))return this.nodeCache.get(e);let t=`${this.config.namespace}:node:${e}`,s=await this.memory.get(t,this.nsOpts);return s&&this.nodeCache.set(e,s),s}async getEdges(e,t){let s=await this.loadAllEdges();return this.filterEdgesByDirection(s,e,t)}async loadAllEdges(){if(this.allEdgesCache)return this.allEdgesCache;let e=[],t=`${this.config.namespace}:edge:*`,s=await this.memory.search(t,Number.MAX_SAFE_INTEGER,this.nsOpts);for(let n of s){let i=await this.memory.get(n,this.nsOpts);i&&e.push(i)}return this.allEdgesCache=e,e}async clear(){this.nodeCache.clear(),this.edgeIndex.clear(),this.allEdgesCache=void 0;for(let e of[`${this.config.namespace}:node:`,`${this.config.namespace}:edge:`]){let t=await this.memory.search(`${e}*`,Number.MAX_SAFE_INTEGER,this.nsOpts);for(let s of t)await this.memory.delete(s,this.nsOpts)}}async removeFileFromGraph(e){let t=this.pathToNodeId(e),s=this.config.namespace,n=await this.memory.search(`${s}:node:${t}*`,Number.MAX_SAFE_INTEGER,this.nsOpts);for(let o of n)await this.memory.delete(o,this.nsOpts),this.nodeCache.delete(o.slice(`${s}:node:`.length));let i=await this.memory.search(`${s}:edge:*`,Number.MAX_SAFE_INTEGER,this.nsOpts);for(let o of i){let r=await this.memory.get(o,this.nsOpts);r&&(r.source===t||r.source.startsWith(`${t}:`))&&await this.memory.delete(o,this.nsOpts)}this.edgeIndex.delete(t),this.allEdgesCache=void 0}isLLMExtractionAvailable(){return this.config.enableLLMExtraction===!0&&this.llmRouter!==void 0}getModelForTier(e){switch(e){case 1:return"claude-haiku-4-5-20251001";case 2:return"claude-sonnet-4-6";case 3:return"claude-sonnet-4-6";case 4:return"claude-opus-4-7";default:return"claude-sonnet-4-6"}}async extractRelationshipsWithLLM(e,t){if(!this.llmRouter)return{semanticRelationships:[],designPatterns:[],architecturalBoundaries:[],dependencyImpacts:[]};try{let s=this.buildRelationshipExtractionPrompt(e,t),n=this.getModelForTier(this.config.llmModelTier??2),i=await this.llmRouter.chat({messages:[{role:"system",content:`You are an expert software architect analyzing code structure. Extract:
|
|
24
24
|
1. Semantic relationships between code entities (inheritance, composition, dependency, collaboration)
|
|
25
25
|
2. Design patterns used (Factory, Singleton, Observer, Strategy, etc.)
|
|
26
26
|
3. Architectural boundaries (layers, modules, domains)
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.
|
|
2
|
-
import{c as t}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.5");process.exit(0)}
|
|
2
|
+
import{c as t}from"./chunk-S7HQOGVD.js";import{randomInt as o}from"node:crypto";function a(){return Math.random()}function m(n,e){return o(n,e)}function c(n,e){return n+Math.random()*(e-n)}var r=t(()=>{"use strict"});export{a,m as b,c,r as d};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.
|
|
2
|
-
import{a as f}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.5");process.exit(0)}
|
|
2
|
+
import{a as f}from"./chunk-RLZDXQNM.js";import{c as p}from"./chunk-VC256KH2.js";import{a as l,d as b}from"./chunk-MJRYHHOG.js";import{a as d,c as g}from"./chunk-GTVXVYKE.js";f();g();b();var v={dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine",namespace:"coverage-hnsw",maxElements:1e5},S=p.create("coverage-analysis/hnsw-index"),u=class{constructor(e,t={}){this.memory=e;this.config={...v,...t},this.stats={vectorCount:0,searchOperations:0,insertOperations:0}}memory;config;stats;searchLatencies=[];backendType="ruvector-gnn";adapter=null;initialized=!1;metadataStore=new Map;async initialize(){if(this.initialized)return;let e=this.config.metric==="cosine"?"cosine":"euclidean",t=`coverage-${this.config.namespace}`;d.close(t),this.adapter=d.create(t,{dimensions:this.config.dimensions,M:this.config.M,efConstruction:this.config.efConstruction,efSearch:this.config.efSearch,metric:e}),S.info(`HnswAdapter initialized: dimension=${this.config.dimensions}, metric=${this.config.metric}, M=${this.config.M} (unified backend via ADR-071)`),this.initialized=!0}isNativeAvailable(){return this.initialized&&this.adapter!==null}getBackendType(){return this.backendType}isRuvectorAvailable(){return this.initialized&&this.adapter!==null&&this.adapter.isRuvectorAvailable()}async insert(e,t,a){this.initialized||await this.initialize(),t=this.validateVector(t),this.adapter.addByStringId(e,t),a&&this.metadataStore.set(e,a),this.stats.insertOperations++,this.stats.vectorCount=this.adapter.size()}async search(e,t){this.initialized||await this.initialize(),e=this.validateVector(e);let a=performance.now(),n=[];this.adapter.size()>0&&(n=this.adapter.searchByArray(e,t).map(({id:i,score:o})=>({key:i,score:o,distance:1-o,metadata:this.metadataStore.get(i)})));let s=performance.now()-a;return this.recordSearchLatency(s),this.stats.searchOperations++,n}async batchInsert(e){this.initialized||await this.initialize();let t=100;for(let a=0;a<e.length;a+=t){let n=e.slice(a,a+t);await Promise.all(n.map(r=>this.insert(r.key,r.vector,r.metadata)))}}async delete(e){if(!this.adapter)return!1;let t=this.adapter.removeByStringId(e);if(t){this.metadataStore.delete(e);let a=this.buildKey(e);await this.memory.delete(a),this.stats.vectorCount=this.adapter.size()}return t}async getStats(){return{nativeHNSW:this.initialized&&this.adapter!==null,backendType:this.backendType,vectorCount:this.stats.vectorCount,indexSizeBytes:this.stats.vectorCount*this.config.dimensions*4,avgSearchLatencyMs:this.calculateAvgLatency(),p95SearchLatencyMs:this.calculatePercentileLatency(95),p99SearchLatencyMs:this.calculatePercentileLatency(99),searchOperations:this.stats.searchOperations,insertOperations:this.stats.insertOperations}}async clear(){this.metadataStore.clear(),this.adapter&&this.adapter.clear(),this.stats.vectorCount=0,this.searchLatencies=[]}validateVector(e){if(e.length!==this.config.dimensions)return this.resizeVector(e,this.config.dimensions);for(let t=0;t<e.length;t++)if(!Number.isFinite(e[t]))throw new Error(`Invalid vector value at index ${t}: ${e[t]}`);return e}resizeVector(e,t){if(e.length===t)return e;if(e.length>t){let n=new Array(t).fill(0),r=e.length/t;for(let s=0;s<t;s++){let h=Math.floor(s*r),i=Math.floor((s+1)*r),o=0;for(let m=h;m<i;m++)o+=e[m];n[s]=o/(i-h)}return n}let a=new Array(t).fill(0);for(let n=0;n<e.length;n++)a[n]=e[n];return a}buildKey(e){return`${this.config.namespace}:${e}`}recordSearchLatency(e){this.searchLatencies.push(e);let t=1e3;this.searchLatencies.length>t&&(this.searchLatencies=this.searchLatencies.slice(-t))}calculateAvgLatency(){return this.searchLatencies.length===0?0:this.searchLatencies.reduce((t,a)=>t+a,0)/this.searchLatencies.length}calculatePercentileLatency(e){if(this.searchLatencies.length===0)return 0;let t=[...this.searchLatencies].sort((n,r)=>n-r),a=Math.ceil(e/100*t.length)-1;return t[Math.max(0,a)]}setEfSearch(e){this.config.efSearch=e}};function C(c,e){return new u(c,e)}async function H(c,e=1e4,t=1e3){let n=performance.now();for(let i=0;i<e;i++){let o=Array.from({length:384},()=>l());await c.insert(`bench-${i}`,o)}let r=performance.now()-n,s=performance.now();for(let i=0;i<t;i++){let o=Array.from({length:384},()=>l());await c.search(o,10)}let h=performance.now()-s;return{insertTimeMs:r,searchTimeMs:h,avgSearchLatencyMs:h/t,isNative:c.isNativeAvailable(),backendType:c.getBackendType()}}export{v as a,u as b,C as c,H as d};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.
|
|
2
|
-
import{randomUUID as v}from"crypto";var m={"claude-opus-4-7":{input:5,output:25,provider:"claude"},"claude-sonnet-4-6":{input:3,output:15,provider:"claude"},"claude-haiku-4-5-20251001":{input:1,output:5,provider:"claude"},"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(
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.5");process.exit(0)}
|
|
2
|
+
import{randomUUID as v}from"crypto";var m={"claude-opus-4-7":{input:5,output:25,provider:"claude"},"claude-sonnet-4-6":{input:3,output:15,provider:"claude"},"claude-haiku-4-5-20251001":{input:1,output:5,provider:"claude"},"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+(r.cacheReadTokens??0)/1e6*e.input*.1+(r.cacheCreationTokens??0)/1e6*e.input*1.25,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(a=>a.timestamp>=e&&a.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 a of o)u+=a.cost.totalCost,l+=a.usage.totalTokens,n[a.provider]+=a.cost.totalCost,p[a.model]=(p[a.model]||0)+a.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)}}}}},s;function h(){return s||(s=new d),s}function b(){s&&(s.dispose(),s=void 0)}export{m as a,d as b,h as c,b as d};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.5");process.exit(0)}
|
|
2
2
|
import{readFileSync as l,writeFileSync as c,mkdirSync as m,renameSync as u}from"node:fs";import{join as d,dirname as h}from"node:path";import{homedir as p}from"node:os";var C={maxCallsPerSession:10},S=d(p(),".agentic-qe","advisor","circuit-breaker.json"),x=1440*60*1e3,n=class{maxCalls;statePath;constructor(t){this.maxCalls=t?.maxCallsPerSession??C.maxCallsPerSession,this.statePath=t?.statePath??S}acquire(t){let e=this.load(),a=e.sessions[t]?.count??0;if(a>=this.maxCalls)throw new i(`Advisor circuit breaker tripped: ${a} calls in session "${t}" (max: ${this.maxCalls}). Do not retry \u2014 continue without the advisor.`,t,a,this.maxCalls);let r=a+1;return e.sessions[t]={count:r,lastUpdated:new Date().toISOString()},this.save(e),{sessionId:t,callCount:r,maxCalls:this.maxCalls,remaining:this.maxCalls-r,tripped:!1}}getState(t){let s=this.load().sessions[t]?.count??0;return{sessionId:t,callCount:s,maxCalls:this.maxCalls,remaining:this.maxCalls-s,tripped:s>=this.maxCalls}}reset(t){if(t){let e=this.load();delete e.sessions[t],this.save(e)}else this.save({sessions:{}})}load(){try{let t=l(this.statePath,"utf-8"),e=JSON.parse(t);return this.evictStale(e),e}catch{return{sessions:{}}}}save(t){try{m(h(this.statePath),{recursive:!0});let e=this.statePath+".tmp."+process.pid;c(e,JSON.stringify(t,null,2)),u(e,this.statePath)}catch{}}evictStale(t){let e=Date.now();for(let[s,a]of Object.entries(t.sessions))e-new Date(a.lastUpdated).getTime()>x&&delete t.sessions[s]}},i=class extends Error{constructor(e,s,a,r){super(e);this.sessionId=s;this.callCount=a;this.maxCalls=r;this.name="AdvisorCircuitBreakerError"}sessionId;callCount;maxCalls;exitCode=3};export{n as a,i as b};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.
|
|
2
|
-
import{a as w,b as A,c as O,e as D,f as z}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.5");process.exit(0)}
|
|
2
|
+
import{a as w,b as A,c as O,e as D,f as z}from"./chunk-YEO2Z3UX.js";import{b as S,d as $}from"./chunk-56RA6YPN.js";import{a as N,c as F}from"./chunk-S73KENCH.js";import{i as v}from"./chunk-7DU35D4M.js";import*as I from"node:path";z();$();var P=["function","module","test","file","class"],L=["calls","imports","tests","depends_on","covers"],b=class{ensureSchema(e){e.transaction(()=>{e.exec(w),e.exec(A),e.exec(O)})()}schemaExists(e){return D(e)}getNodeTypes(){return P}getEdgeTypes(){return L}isValidNodeType(e){return P.includes(e)}isValidEdgeType(e){return L.includes(e)}getStats(e){if(!this.schemaExists(e))return{nodeCount:0,edgeCount:0};let t=e.prepare("SELECT COUNT(*) as count FROM hypergraph_nodes").get().count,r=e.prepare("SELECT COUNT(*) as count FROM hypergraph_edges").get().count;return{nodeCount:t,edgeCount:r}}dropSchema(e){let t=e.prepare("SELECT COUNT(*) as cnt FROM hypergraph_nodes").get()?.cnt??0,r=e.prepare("SELECT COUNT(*) as cnt FROM hypergraph_edges").get()?.cnt??0;if(t>0||r>0)throw new Error(`REFUSING to drop hypergraph schema: tables contain data (${t} nodes, ${r} edges). Backup and manually drop if needed.`);e.transaction(()=>{e.exec("DROP TABLE IF EXISTS hypergraph_edges"),e.exec("DROP TABLE IF EXISTS hypergraph_nodes")})()}};function C(n){return{id:n.id,type:n.type,name:n.name,file_path:n.filePath??null,line_start:n.lineStart??null,line_end:n.lineEnd??null,complexity:n.complexity??null,coverage:n.coverage??null,metadata:n.metadata?JSON.stringify(n.metadata):null,embedding:n.embedding?U(n.embedding):null}}function T(n){return{id:n.id,type:n.type,name:n.name,filePath:n.file_path??void 0,lineStart:n.line_start??void 0,lineEnd:n.line_end??void 0,complexity:n.complexity??void 0,coverage:n.coverage??void 0,metadata:n.metadata?S(n.metadata):void 0,embedding:n.embedding?W(n.embedding):void 0,createdAt:n.created_at,updatedAt:n.updated_at}}function M(n){return{id:n.id,source_id:n.sourceId,target_id:n.targetId,type:n.type,weight:n.weight??1,properties:n.properties?JSON.stringify(n.properties):null}}function H(n){return{id:n.id,sourceId:n.source_id,targetId:n.target_id,type:n.type,weight:n.weight,properties:n.properties?S(n.properties):void 0,createdAt:n.created_at}}function x(n,e,t){return`${n}--${t}-->${e}`}function U(n){let e=Buffer.alloc(n.length*4);for(let t=0;t<n.length;t++)e.writeFloatLE(n[t],t*4);return e}function W(n){let e=[],t=n.length/4;for(let r=0;r<t;r++)e.push(n.readFloatLE(r*4));return e}F();var B={maxTraversalDepth:10,maxQueryResults:1e3,enableVectorSearch:!1},R=class{config;schemaManager;initialized=!1;constructor(e){this.config={...B,...e},this.schemaManager=new b}async initialize(){this.initialized||(this.schemaManager.ensureSchema(this.config.db),this.initialized=!0)}isInitialized(){return this.initialized}async addNode(e){this.ensureInitialized();let t=v(),r={id:t,...e},s=C(r);return this.config.db.prepare(`
|
|
3
3
|
INSERT INTO hypergraph_nodes (id, type, name, file_path, line_start, line_end, complexity, coverage, metadata, embedding)
|
|
4
4
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
5
5
|
`).run(s.id,s.type,s.name,s.file_path,s.line_start,s.line_end,s.complexity,s.coverage,s.metadata,s.embedding),t}async addEdge(e){this.ensureInitialized();let t=x(e.sourceId,e.targetId,e.type),r={id:t,...e},s=M(r);return this.config.db.prepare(`
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.5");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-haiku-4-5-20251001","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-6","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-6"],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-7","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-haiku-4-5-20251001",2:"claude-sonnet-4-6",3:"claude-sonnet-4-6",4:"claude-opus-4-7"}},r=class extends Error{constructor(e,t,l){super(e);this.code=t;this.cause=l;this.name="ModelRouterError"}code;cause},a=class extends r{constructor(e,t,l){super(e,"BUDGET_EXCEEDED");this.tier=t;this.usage=l;this.name="BudgetExceededError"}tier;usage},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"}timeoutMs};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.10.
|
|
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.10.5");process.exit(0)}
|
|
2
|
+
import{c as s,e as t}from"./chunk-S7HQOGVD.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,4 +1,4 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.5");process.exit(0)}
|
|
2
2
|
import*as h from"fs";import*as M from"path";var S=["coverage/coverage-final.json","coverage/coverage-summary.json",".coverage/coverage-final.json"];function x(s){for(let v of S){let i=M.join(s,v);if(h.existsSync(i))try{let n=JSON.parse(h.readFileSync(i,"utf-8"));if(n.total&&n.total.lines)return L(n,s);let o=new Map;for(let[r,C]of Object.entries(n)){let c=C,g=Object.keys(c.s),u=g.filter(a=>c.s[a]>0).length,b=Object.keys(c.b),p=0,m=0;for(let a of b)for(let y of c.b[a])p++,y>0&&m++;let e=Object.keys(c.f),t=e.filter(a=>c.f[a]>0).length,f=new Set,d=new Set;for(let a of g){let y=c.statementMap[a];for(let F=y.start.line;F<=y.end.line;F++)d.add(F),c.s[a]>0&&f.add(F)}let l=[...d].filter(a=>!f.has(a)).sort((a,y)=>a-y);o.set(r,{path:r,lines:{covered:f.size,total:d.size},branches:{covered:m,total:p},functions:{covered:t,total:e.length},statements:{covered:u,total:g.length},uncoveredLines:l,uncoveredBranches:l.slice(0,Math.floor(l.length/2))})}return o.size>0?o:null}catch{continue}}return null}function L(s,v){let i=new Map;for(let[n,o]of Object.entries(s)){if(n==="total")continue;let r=o;i.set(n,{path:n,lines:{covered:r.lines.covered,total:r.lines.total},branches:{covered:r.branches.covered,total:r.branches.total},functions:{covered:r.functions.covered,total:r.functions.total},statements:{covered:r.statements.covered,total:r.statements.total},uncoveredLines:[],uncoveredBranches:[]})}return i.size>0?i:null}function B(s,v){let n=v.split(`
|
|
3
3
|
`).length,r=[s.replace(".ts",".test.ts").replace("/src/","/tests/"),s.replace(".ts",".spec.ts").replace("/src/","/tests/"),s.replace(".ts",".test.ts"),s.replace("/src/","/test/").replace(".ts",".test.ts")].some(d=>h.existsSync(d)),C=(v.match(/\bexport\b/g)||[]).length,c=(v.match(/\b(function|=>)\b/g)||[]).length,g=(v.match(/\b(if|switch|case|\?\?|\|\|)\b/g)||[]).length,u;if(r){let d=Math.min(g*.005,.15),l=Math.min(n*1e-4,.1);u=.85-d-l}else u=.2+(C>5?.1:0);u=Math.max(.05,Math.min(.95,u));let b=Math.floor(n*u),p=Math.max(c,1),m=Math.max(g,1),e=Math.floor(b*.7),t=Math.floor(p*u*.9),f=Array.from({length:n-b},(d,l)=>l+b+1);return{path:s,lines:{covered:b,total:n},branches:{covered:Math.min(e,m),total:m},functions:{covered:Math.min(t,p),total:p},statements:{covered:b,total:n},uncoveredLines:f,uncoveredBranches:f.slice(0,Math.floor(f.length/2))}}function j(s,v){let i=v||process.cwd(),n=x(i),o=[],r=!1;if(n&&n.size>0){r=!0;for(let e of s){let t=M.resolve(e),f=n.get(t)||n.get(e)||n.get(M.relative(i,t));if(f)o.push({...f,path:e});else{let l=(h.existsSync(e)?h.readFileSync(e,"utf-8"):"").split(`
|
|
4
4
|
`).length;o.push({path:e,lines:{covered:0,total:l},branches:{covered:0,total:1},functions:{covered:0,total:1},statements:{covered:0,total:l},uncoveredLines:Array.from({length:l},(a,y)=>y+1),uncoveredBranches:[]})}}}else for(let e of s){let t=h.existsSync(e)?h.readFileSync(e,"utf-8"):"";o.push(B(e,t))}let C=o.reduce((e,t)=>e+t.lines.total,0),c=o.reduce((e,t)=>e+t.lines.covered,0),g=o.reduce((e,t)=>e+t.branches.total,0),u=o.reduce((e,t)=>e+t.branches.covered,0),b=o.reduce((e,t)=>e+t.functions.total,0),p=o.reduce((e,t)=>e+t.functions.covered,0),m=(e,t)=>t>0?Math.round(e/t*100):0;return{files:o,summary:{line:m(c,C),branch:m(u,g),function:m(p,b),statement:m(c,C),files:o.length},instrumented:r}}export{j as a};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.
|
|
2
|
-
import{a as v,b as k}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.5");process.exit(0)}
|
|
2
|
+
import{a as v,b as k}from"./chunk-PYBVFG6T.js";import{i as g,m as P}from"./chunk-R573V37S.js";import{a as d,b as y,c as R}from"./chunk-S73KENCH.js";R();import{randomUUID as M}from"crypto";var p=class{constructor(e){this.config=e}config;_status="idle";_lastResult;_lastRunAt;_nextRunAt;_totalExecutions=0;_successfulExecutions=0;_failedExecutions=0;_executionDurations=[];_recentResults=[];get status(){return this._status}get lastResult(){return this._lastResult}get lastRunAt(){return this._lastRunAt}get nextRunAt(){return this._nextRunAt}async initialize(){this._status="idle",this._nextRunAt=new Date(Date.now()+this.config.intervalMs)}async execute(e){let r=Date.now();this._status="running",this._lastRunAt=new Date,this._totalExecutions++;let n,t;for(let a=0;a<=this.config.retryCount;a++)try{if(e.signal.aborted)throw new Error("Worker execution aborted");t=await this.executeWithTimeout(()=>this.doExecute(e),this.config.timeoutMs,e.signal);break}catch(u){n=y(u),e.logger.warn(`Worker ${this.config.id} attempt ${a+1} failed: ${n.message}`),a<this.config.retryCount&&await this.delay(this.config.retryDelayMs)}let o=Date.now()-r;return t?(this._successfulExecutions++,this._lastResult=t):(this._failedExecutions++,t=this.createErrorResult(n,o),this._lastResult=t),this._executionDurations.push(o),this._executionDurations.length>100&&this._executionDurations.shift(),this._recentResults.push({timestamp:new Date,success:t.success,durationMs:o}),this._recentResults.length>5&&this._recentResults.shift(),this._nextRunAt=new Date(Date.now()+this.config.intervalMs),this._status=t.success?"idle":"error",await e.eventBus.publish({type:"worker.executed",workerId:this.config.id,timestamp:new Date,payload:{success:t.success,durationMs:o,findingsCount:t.findings.length,healthScore:t.metrics.healthScore}}),t}pause(){this._status!=="stopped"&&(this._status="paused")}resume(){this._status==="paused"&&(this._status="idle")}async stop(){this._status="stopped"}getHealth(){let e=this._executionDurations.length>0?this._executionDurations.reduce((n,t)=>n+t,0)/this._executionDurations.length:0,r=this._totalExecutions>0?this._successfulExecutions/this._totalExecutions:1;return{status:this._status,healthScore:Math.round(r*100),totalExecutions:this._totalExecutions,successfulExecutions:this._successfulExecutions,failedExecutions:this._failedExecutions,avgDurationMs:Math.round(e),recentResults:[...this._recentResults]}}async executeWithTimeout(e,r,n){return new Promise((t,o)=>{let a=setTimeout(()=>{o(new Error(`Worker execution timed out after ${r}ms`))},r),u=()=>{clearTimeout(a),o(new Error("Worker execution aborted"))};n.addEventListener("abort",u,{once:!0}),e().then(c=>{clearTimeout(a),n.removeEventListener("abort",u),t(c)}).catch(c=>{clearTimeout(a),n.removeEventListener("abort",u),o(c)})})}createErrorResult(e,r){return{workerId:this.config.id,timestamp:new Date,durationMs:r,success:!1,error:e.message,metrics:{itemsAnalyzed:0,issuesFound:0,healthScore:0,trend:"degrading",domainMetrics:{}},findings:[],recommendations:[]}}createResult(e,r,n,t){return{workerId:this.config.id,timestamp:new Date,durationMs:e,success:!0,metrics:r,findings:n,recommendations:t}}delay(e){return new Promise(r=>setTimeout(r,e))}generateId(){return`${Date.now()}-${M().slice(0,9)}`}};P();R();var W={id:"heartbeat-scheduler",name:"Heartbeat Scheduler",description:"Token-free maintenance: pattern promotion, stale detection, experience buffer monitoring",intervalMs:1800*1e3,priority:"normal",targetDomains:["learning-optimization"],enabled:!0,timeoutMs:6e4,retryCount:1,retryDelayMs:5e3},b=class extends p{lifecycleManager=null;dailyLogger;lastRunTimestamp=0;constructor(){super(W),this.dailyLogger=new k}async getLifecycleManager(){if(this.lifecycleManager)return this.lifecycleManager;try{let e=g();await e.initialize();let r=e.getDatabase();return this.lifecycleManager=v(r,{promotionRewardThreshold:.7,promotionMinOccurrences:2,promotionMinSuccessRate:.7,deprecationFailureThreshold:3,staleDaysThreshold:30,confidenceDecayRate:.01,minActiveConfidence:.3}),this.lifecycleManager}catch{return null}}getPendingExperienceCount(){try{return g().getDatabase().prepare("SELECT COUNT(*) as pending FROM qe_pattern_usage WHERE created_at > datetime('now', '-1 day')").get()?.pending??0}catch{return 0}}async doExecute(e){let r=Date.now();e.logger.info("Heartbeat scheduler running (token-free maintenance)");let n=[],t=[],o=await this.getLifecycleManager();if(!o)return e.logger.warn("Unified memory unavailable \u2014 returning zero-metric heartbeat"),this.createResult(Date.now()-r,{itemsAnalyzed:0,issuesFound:0,healthScore:50,trend:"stable",domainMetrics:{promoted:0,deprecated:0,decayed:0,stalePatterns:0,pendingExperiences:0,avgConfidence:0,avgSuccessRate:0}},[],[]);let a=0,u=0;try{let s=o.promoteEligiblePatterns();a=s.promoted,u=s.checked,a>0&&n.push({type:"heartbeat-promotion",severity:"info",domain:"learning-optimization",title:"Patterns Promoted",description:`${a} of ${u} short-term patterns promoted to long-term`})}catch(s){e.logger.warn("Pattern promotion failed",{error:d(s)})}let c=0,h=0;try{let s=o.deprecateStalePatterns();c=s.deprecated,h=s.checked,c>0&&n.push({type:"heartbeat-deprecation",severity:"low",domain:"learning-optimization",title:"Stale Patterns Deprecated",description:`${c} of ${h} patterns deprecated (stale, failed, or low confidence)`})}catch(s){e.logger.warn("Stale pattern detection failed",{error:d(s)})}let l=0;try{let s=this.lastRunTimestamp>0?(Date.now()-this.lastRunTimestamp)/864e5:1;l=o.applyConfidenceDecay(Math.min(s,7)).decayed}catch(s){e.logger.warn("Confidence decay failed",{error:d(s)})}let m=this.getPendingExperienceCount(),i={totalPatterns:0,activePatterns:0,deprecatedPatterns:0,promotedPatterns:0,shortTermPatterns:0,longTermPatterns:0,avgConfidence:0,avgSuccessRate:0,patternsNearDeprecation:0};try{i=o.getStats()}catch(s){e.logger.warn("Stats retrieval failed",{error:d(s)})}try{this.dailyLogger.log({timestamp:new Date,type:"pattern-promoted",summary:`Heartbeat: ${a} promoted, ${c} deprecated, ${l} decayed, ${m} pending exp, ${i.activePatterns} active patterns (avg conf: ${i.avgConfidence.toFixed(2)})`,details:{promoted:a,deprecated:c,decayed:l,pendingExperiences:m,totalPatterns:i.totalPatterns,activePatterns:i.activePatterns,avgConfidence:i.avgConfidence,avgSuccessRate:i.avgSuccessRate}}),this.dailyLogger.flush()}catch(s){e.logger.warn("Daily log write failed",{error:d(s)})}this.lastRunTimestamp=Date.now(),i.activePatterns>0&&i.patternsNearDeprecation/i.activePatterns>.5&&t.push({priority:"p2",domain:"learning-optimization",action:"Review At-Risk Patterns",description:`${i.patternsNearDeprecation} of ${i.activePatterns} active patterns are near deprecation. Manual review recommended.`,estimatedImpact:"medium",effort:"low",autoFixable:!1});let f=this.calculateHealthScore(i,a,c),D=this.determineTrend(a,c,i.activePatterns),_=Math.max(u,h),x=a+c+i.patternsNearDeprecation;return e.logger.info("Heartbeat complete",{promoted:a,deprecated:c,decayed:l,pendingExperiences:m,healthScore:f}),this.createResult(Date.now()-r,{itemsAnalyzed:_,issuesFound:x,healthScore:f,trend:D,domainMetrics:{promoted:a,deprecated:c,decayed:l,stalePatterns:i.patternsNearDeprecation,pendingExperiences:m,avgConfidence:Number(i.avgConfidence.toFixed(3)),avgSuccessRate:Number(i.avgSuccessRate.toFixed(3))}},n,t)}calculateHealthScore(e,r,n){let t=70;if(t+=Math.min(15,r*5),e.avgConfidence>0&&(t+=Math.round((e.avgConfidence-.5)*30)),e.activePatterns>0){let o=n/e.activePatterns;t-=Math.round(o*20)}return e.activePatterns>0&&e.patternsNearDeprecation/e.activePatterns>.5&&(t-=10),Math.max(0,Math.min(100,Math.round(t)))}determineTrend(e,r,n){return n===0?"stable":e>r?"improving":r>e&&r/n>.1?"degrading":"stable"}};export{p as a,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.10.
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.5");process.exit(0)}
|
|
2
2
|
var l=["ECONNREFUSED","ETIMEOUT","ENOMEM","ENOSPC"];var s={successRate:.1,failureRate:1,viabilityThreshold:.3,rehabilitationThreshold:10,maxQuarantineDurationMs:6048e5,domainOverrides:{"security-compliance":{successRate:.05,failureRate:1,viabilityThreshold:.5},"test-generation":{successRate:.15,failureRate:1,viabilityThreshold:.2},"quality-assessment":{successRate:.1,failureRate:1,viabilityThreshold:.4}}},a=class{config;_witnessChain=null;set witnessChain(e){this._witnessChain=e}constructor(e={}){this.config={...s,...e,domainOverrides:{...s.domainOverrides,...e.domainOverrides}}}computeConfidenceUpdate(e,r,i){let{successRate:u,failureRate:o}=this.getConfigForDomain(i),n=r==="success"?u:-o;if(r==="failure")try{this._witnessChain?.append("HEBBIAN_PENALTY",{previousConfidence:e,delta:n,domain:i},"asymmetric-learning")}catch{}return c(e+n,0,1)}shouldQuarantine(e,r){let{viabilityThreshold:i}=this.getConfigForDomain(r);return{shouldQuarantine:e<i,confidence:e,viabilityThreshold:i,domain:r}}classifyFailure(e){if(e.infrastructureHealthy===!1||e.durationMs!==void 0&&e.durationMs>3e4)return"infrastructure";if(e.errorMessage){let r=e.errorMessage.toUpperCase();for(let i of l)if(r.includes(i))return"infrastructure"}return e.failureCategory==="infrastructure"?"infrastructure":(e.failureCategory==="pattern","pattern")}checkRehabilitation(e,r){let i=this.config.rehabilitationThreshold;return{canRehabilitate:e>=i,consecutiveSuccesses:e,requiredSuccesses:i,domain:r}}getConfigForDomain(e){return e&&this.config.domainOverrides?.[e]?this.config.domainOverrides[e]:{successRate:this.config.successRate,failureRate:this.config.failureRate,viabilityThreshold:this.config.viabilityThreshold}}getAsymmetryRatio(e){let{successRate:r,failureRate:i}=this.getConfigForDomain(e);return r===0?1/0:i/r}};function c(t,e,r){return t<e?e:t>r?r:t}export{a};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.5");process.exit(0)}
|
|
2
2
|
function M(u){let e=u|0;return()=>{e=e+1831565813|0;let n=Math.imul(e^e>>>15,1|e);return n=n+Math.imul(n^n>>>7,61|n)^n,((n^n>>>14)>>>0)/4294967296}}var A=2,y=10,x=200,p=1e-8,b=class{epsilon;seed;constructor(e){if(this.epsilon=e?.epsilon??.3,this.seed=e?.seed,this.epsilon<=0||this.epsilon>=1)throw new Error("SparsifierConfig.epsilon must be in (0, 1)")}sparsify(e){if(e.nodeCount<=0||e.edges.length===0)return{nodeCount:e.nodeCount,edges:[]};let n=this.seed!==void 0?M(this.seed):Math.random,t=this.approximateEffectiveResistances(e),i=e.nodeCount,r=e.edges.length,o=Math.max(1,Math.log(i)),m=this.epsilon*this.epsilon,l=Math.min(r,Math.max(i-1,A*(i-1)*(1-this.epsilon))),s=new Float64Array(r),c=0;for(let a=0;a<r;a++){let d=e.edges[a][2];s[a]=d*t[a],c+=s[a]}if(c<=0)return{nodeCount:e.nodeCount,edges:[]};let f=[];for(let a=0;a<r;a++){let[d,C,E]=e.edges[a],g=Math.min(1,s[a]/c*l);if(n()<g){let w=E/g;f.push([d,C,w])}}return{nodeCount:e.nodeCount,edges:f}}validateSpectral(e,n){let t=Math.min(y,Math.max(1,e.nodeCount-1)),i=this.computeLaplacian(e),r=this.computeLaplacian(n),o=this.computeTopEigenvalues(i,t),m=this.computeTopEigenvalues(r,t),l=[],s=!0,c=this.epsilon;for(let f=0;f<o.length;f++){if(o[f]<1e-10)continue;let a=m[f]/o[f];l.push(a),(a<1-c||a>1+c)&&(s=!1)}return{isValid:s,eigenvalueRatios:l,originalEdgeCount:e.edges.length,sparsifiedEdgeCount:n.edges.length,compressionRatio:e.edges.length>0?n.edges.length/e.edges.length:0}}computeLaplacian(e){let n=e.nodeCount,t=Array.from({length:n},()=>new Array(n).fill(0));for(let[i,r,o]of e.edges)i<0||i>=n||r<0||r>=n||(t[i][i]+=o,t[r][r]+=o,t[i][r]-=o,t[r][i]-=o);return t}computeTopEigenvalues(e,n){let t=e.length;if(t===0)return[];let i=[],r=[],o=e.map(m=>[...m]);for(let m=0;m<Math.min(n,t);m++){let l=this.powerIteration(o,t,r);if(l===null)break;i.push(l.eigenvalue),r.push(l.eigenvector),V(o,l.eigenvalue,l.eigenvector)}return i}approximateEffectiveResistances(e){let n=e.nodeCount,t=new Float64Array(n);for(let[r,o,m]of e.edges)r>=0&&r<n&&(t[r]+=m),o>=0&&o<n&&(t[o]+=m);let i=new Array(e.edges.length);for(let r=0;r<e.edges.length;r++){let[o,m]=e.edges[r],l=t[o]||1,s=t[m]||1;i[r]=1/l+1/s}return i}powerIteration(e,n,t){let i=0;for(let s=0;s<n;s++)for(let c=0;c<n;c++)i+=e[s][c]*e[s][c];if(i<p*p)return null;let r=t.length,o=new Array(n);for(let s=0;s<n;s++)o[s]=Math.sin((s+1)*(r+1)*1.618033988749895)+.1*(s-n/2);for(let s of t)h(o,s);if(R(o)<p)return null;let l=0;for(let s=0;s<x;s++){let c=L(e,o);for(let d of t)h(c,d);let f=S(c,o),a=v(c);if(a<p)return{eigenvalue:0,eigenvector:o};for(let d=0;d<n;d++)o[d]=c[d]/a;if(Math.abs(f-l)<p){l=f;break}l=f}return{eigenvalue:Math.abs(l),eigenvector:o}}};function L(u,e){let n=u.length,t=new Array(n).fill(0);for(let i=0;i<n;i++){let r=0;for(let o=0;o<n;o++)r+=u[i][o]*e[o];t[i]=r}return t}function v(u){let e=0;for(let n=0;n<u.length;n++)e+=u[n]*u[n];return Math.sqrt(e)}function R(u){let e=v(u);if(e>0)for(let n=0;n<u.length;n++)u[n]/=e;return e}function S(u,e){let n=0;for(let t=0;t<u.length;t++)n+=u[t]*e[t];return n}function h(u,e){let n=S(u,e);for(let t=0;t<u.length;t++)u[t]-=n*e[t]}function V(u,e,n){let t=n.length;for(let i=0;i<t;i++)for(let r=0;r<t;r++)u[i][r]-=e*n[i]*n[r]}export{b as a};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.
|
|
2
|
-
import{a as _}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.5");process.exit(0)}
|
|
2
|
+
import{a as _}from"./chunk-PGNQR2VM.js";import{e as E}from"./chunk-RZ7D5SHS.js";import{b as p,d as S}from"./chunk-56RA6YPN.js";import{a as b}from"./chunk-RLZDXQNM.js";import{c as h}from"./chunk-VC256KH2.js";import{S as A,j as g}from"./chunk-O5OOUMBB.js";S();b();A();var d=h.create("pattern-lifecycle"),D={promotionRewardThreshold:.7,promotionMinOccurrences:E,promotionMinSuccessRate:.7,deprecationFailureThreshold:3,staleDaysThreshold:30,confidenceDecayRate:.01,minActiveConfidence:.3,maxAgeForActivePatterns:90,promotionActivityWindowDays:30,asymmetricLearning:{}},y=5,L=.9,R=2;function v(u,e){return e<y||!Number.isFinite(u)?0:Math.min(Math.max(u,0),1)}var f=class{constructor(e,t={}){this.db=e;this.config={...D,...t},this.asymmetricEngine=new _(this.config.asymmetricLearning),this.ensureSchema()}db;config;asymmetricEngine;_witnessChain=null;set witnessChain(e){this._witnessChain=e}_compressionService=null;set compressionService(e){this._compressionService=e}ensureSchema(){try{this.db.prepare(`
|
|
3
3
|
SELECT deprecated_at FROM qe_patterns LIMIT 1
|
|
4
4
|
`).get()}catch(e){d.debug("Adding missing deprecated_at column",{error:e instanceof Error?e.message:String(e)}),this.db.exec(`
|
|
5
5
|
ALTER TABLE qe_patterns ADD COLUMN deprecated_at TEXT DEFAULT NULL
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.
|
|
2
|
-
import{k as f,o as P}from"./chunk-USFZ4IJD.js";import{b as h,d as U}from"./chunk-KTRB3L53.js";import{d as p,e as y}from"./chunk-2L73WXA4.js";import{a as T,c as C}from"./chunk-3LRK7PYN.js";P();C();U();y();import{randomUUID as v}from"crypto";var M=p("TokenTracker"),S={costPerInputToken:.003/1e3,costPerOutputToken:.015/1e3},I={filePath:".agentic-qe/token-metrics.json",autoSaveIntervalMs:6e4,maxMetricsInMemory:1e4},m=class u{taskMetrics=[];agentMetrics=new Map;domainMetrics=new Map;sessionId;sessionStartTime;costConfig;cacheHits=0;earlyExits=0;totalTokensSaved=0;totalPatternsReused=0;initialized=!1;persistenceConfig=I;autoSaveTimer=null;isDirty=!1;db=null;kvPersistCount=0;static KV_NAMESPACE="token-usage-metrics";static KV_KEY="token-tracker-snapshot";static KV_TTL=604800;static KV_PERSIST_INTERVAL=10;constructor(){this.sessionId=`session-${Date.now()}-${v().substring(0,8)}`,this.sessionStartTime=Date.now(),this.costConfig=S}initialize(t){this.initialized||(this.initialized=!0,t&&(this.costConfig={...S,...t}),this.initializeDb().catch(e=>{M.warn("DB initialization failed",{error:e instanceof Error?e.message:String(e)})}),this.startAutoSave())}setCostConfig(t){this.costConfig={...this.costConfig,...t}}recordTokenUsage(t,e,n,a,s,r){this.ensureInitialized();let c,d,i,o,l,k;typeof e=="object"?(c="default",d="unknown",i="unknown",o=e,l=!1,k=0):(c=e,d=n??"unknown",i=a??"unknown",o=s,l=r?.patternReused??!1,k=r?.tokensSaved??0),o.estimatedCostUsd===void 0&&(o.estimatedCostUsd=this.calculateCost(o));let g={taskId:t,agentId:c,domain:d,operation:i,timestamp:Date.now(),usage:o,patternReused:l,tokensSaved:k};this.taskMetrics.push(g),this.updateAgentMetrics(c,o,l,k),this.updateDomainMetrics(d,o),l&&this.totalPatternsReused++,k>0&&(this.totalTokensSaved+=k),this.isDirty=!0,this.maybePersistToKv()}recordPatternReuse(t,e){this.ensureInitialized(),this.totalPatternsReused++,this.totalTokensSaved+=e;let n={taskId:t,agentId:"pattern-cache",domain:"optimization",operation:"pattern-reuse",timestamp:Date.now(),usage:{inputTokens:0,outputTokens:0,totalTokens:0,estimatedCostUsd:0},patternReused:!0,tokensSaved:e};this.taskMetrics.push(n),this.isDirty=!0}recordCacheHit(t){this.cacheHits++,this.totalTokensSaved+=t,this.isDirty=!0}recordEarlyExit(t){this.earlyExits++,this.totalTokensSaved+=t,this.isDirty=!0}getSessionSummary(t){this.ensureInitialized();let e=this.filterByTimeframe(this.taskMetrics,t),n=this.aggregateTokenUsage(e),a=new Map;for(let i of e){let o=a.get(i.agentId);o?(o.totalInputTokens+=i.usage.inputTokens,o.totalOutputTokens+=i.usage.outputTokens,o.totalTokens+=i.usage.totalTokens,o.totalCost+=i.usage.estimatedCostUsd||0,o.tasksExecuted++,i.patternReused&&o.patternsReused++,o.estimatedTokensSaved+=i.tokensSaved||0):a.set(i.agentId,{agentId:i.agentId,totalInputTokens:i.usage.inputTokens,totalOutputTokens:i.usage.outputTokens,totalTokens:i.usage.totalTokens,totalCost:i.usage.estimatedCostUsd||0,tasksExecuted:1,patternsReused:i.patternReused?1:0,estimatedTokensSaved:i.tokensSaved||0})}let s=new Map;for(let i of e){let o=s.get(i.domain);o?(o.inputTokens+=i.usage.inputTokens,o.outputTokens+=i.usage.outputTokens,o.totalTokens+=i.usage.totalTokens,o.estimatedCostUsd=(o.estimatedCostUsd||0)+(i.usage.estimatedCostUsd||0)):s.set(i.domain,{...i.usage})}let r=n.totalTokens,c=this.totalTokensSaved,d=r+c>0?c/(r+c)*100:0;return{sessionId:this.sessionId,startTime:this.sessionStartTime,endTime:Date.now(),byAgent:a,byDomain:s,totalUsage:n,optimizationStats:{patternsReused:this.totalPatternsReused,cacheHits:this.cacheHits,earlyExits:this.earlyExits,tokensSaved:this.totalTokensSaved,savingsPercentage:Math.round(d*100)/100}}}getAgentMetrics(t,e){this.ensureInitialized();let n=this.filterByTimeframe(this.taskMetrics,e);if(t){let s=n.filter(r=>r.agentId===t);return this.aggregateAgentMetrics(t,s)}let a=new Map;for(let s of n){let r=a.get(s.agentId)||[];r.push(s),a.set(s.agentId,r)}return Array.from(a.entries()).map(([s,r])=>this.aggregateAgentMetrics(s,r))}getDomainMetrics(t,e){this.ensureInitialized();let n=this.filterByTimeframe(this.taskMetrics,e);if(t){let s=n.filter(r=>r.domain===t);return this.aggregateTokenUsage(s)}let a=new Map;for(let s of n){let r=a.get(s.domain);r?(r.inputTokens+=s.usage.inputTokens,r.outputTokens+=s.usage.outputTokens,r.totalTokens+=s.usage.totalTokens,r.estimatedCostUsd=(r.estimatedCostUsd||0)+(s.usage.estimatedCostUsd||0)):a.set(s.domain,{...s.usage})}return a}getTaskMetrics(t){return this.ensureInitialized(),this.filterByTimeframe(this.taskMetrics,t)}getEfficiencyReport(t){return this.getTokenEfficiency(t)}getTokenEfficiency(t){this.ensureInitialized();let e=this.filterByTimeframe(this.taskMetrics,t),a=this.aggregateTokenUsage(e).totalTokens,s=this.totalTokensSaved,r=a+s>0?s/(a+s)*100:0,c=e.length,d=c>0?e.filter(l=>l.patternReused).length/c:0,i=c>0?a/c:0,o=this.generateRecommendations(e);return{totalTokensUsed:a,totalTokensSaved:s,savingsPercentage:Math.round(r*100)/100,patternReuseRate:Math.round(d*100)/100,averageTokensPerTask:Math.round(i),recommendations:o}}reset(){this.stopAutoSave(),this.taskMetrics=[],this.agentMetrics.clear(),this.domainMetrics.clear(),this.sessionId=`session-${Date.now()}-${v().substring(0,8)}`,this.sessionStartTime=Date.now(),this.cacheHits=0,this.earlyExits=0,this.totalTokensSaved=0,this.totalPatternsReused=0,this.isDirty=!1}configurePersistence(t){this.persistenceConfig={...this.persistenceConfig,...t},t.autoSaveIntervalMs!==void 0&&(this.stopAutoSave(),t.autoSaveIntervalMs>0&&this.startAutoSave())}startAutoSave(){this.autoSaveTimer||this.persistenceConfig.autoSaveIntervalMs>0&&(this.autoSaveTimer=setInterval(()=>{this.isDirty&&this.save().catch(t=>{console.warn("[TokenMetricsCollector] Auto-save failed:",t)})},this.persistenceConfig.autoSaveIntervalMs))}stopAutoSave(){this.autoSaveTimer&&(clearInterval(this.autoSaveTimer),this.autoSaveTimer=null)}async save(){let t=await import("fs"),e=await import("path"),n={version:"1.0.0",sessionId:this.sessionId,sessionStartTime:this.sessionStartTime,taskMetrics:this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory),optimizationStats:{cacheHits:this.cacheHits,earlyExits:this.earlyExits,totalTokensSaved:this.totalTokensSaved,totalPatternsReused:this.totalPatternsReused},lastSavedAt:Date.now()},a=e.resolve(this.persistenceConfig.filePath),s=e.dirname(a);t.existsSync(s)||t.mkdirSync(s,{recursive:!0}),t.writeFileSync(a,JSON.stringify(n,null,2)),this.isDirty=!1}async load(){let t=await import("fs"),n=(await import("path")).resolve(this.persistenceConfig.filePath);if(!t.existsSync(n))return!1;try{let a=t.readFileSync(n,"utf-8"),s=h(a);if(!s.version||!s.version.startsWith("1."))return console.warn("[TokenMetricsCollector] Incompatible data version, skipping load"),!1;let r=s.taskMetrics||[];this.taskMetrics=[...r,...this.taskMetrics],this.cacheHits+=s.optimizationStats?.cacheHits||0,this.earlyExits+=s.optimizationStats?.earlyExits||0,this.totalTokensSaved+=s.optimizationStats?.totalTokensSaved||0,this.totalPatternsReused+=s.optimizationStats?.totalPatternsReused||0;for(let c of r)this.updateAgentMetrics(c.agentId,c.usage,c.patternReused,c.tokensSaved||0),this.updateDomainMetrics(c.domain,c.usage);return this.taskMetrics.length>this.persistenceConfig.maxMetricsInMemory&&(this.taskMetrics=this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory)),!0}catch(a){return console.warn("[TokenMetricsCollector] Failed to load persisted data:",a),!1}}getPersistenceFilePath(){return this.persistenceConfig.filePath}hasUnsavedChanges(){return this.isDirty}async initializeDb(){try{this.db=f(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(t){console.warn("[TokenMetricsCollector] DB init failed, using memory-only:",T(t)),this.db=null}}async persistToKv(){if(!this.db)return;let t={version:"1.0.0",sessionId:this.sessionId,sessionStartTime:this.sessionStartTime,taskMetrics:this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory),optimizationStats:{cacheHits:this.cacheHits,earlyExits:this.earlyExits,totalTokensSaved:this.totalTokensSaved,totalPatternsReused:this.totalPatternsReused},lastSavedAt:Date.now()};await this.db.kvSet(u.KV_KEY,t,u.KV_NAMESPACE,u.KV_TTL)}async loadFromKv(){if(!this.db)return!1;let t=await this.db.kvGet(u.KV_KEY,u.KV_NAMESPACE);if(!t)return!1;if(!t.version||!t.version.startsWith("1."))return console.warn("[TokenMetricsCollector] Incompatible kv_store data version, skipping load"),!1;let e=t.taskMetrics||[];this.taskMetrics=[...e,...this.taskMetrics],this.cacheHits+=t.optimizationStats?.cacheHits||0,this.earlyExits+=t.optimizationStats?.earlyExits||0,this.totalTokensSaved+=t.optimizationStats?.totalTokensSaved||0,this.totalPatternsReused+=t.optimizationStats?.totalPatternsReused||0;for(let n of e)this.updateAgentMetrics(n.agentId,n.usage,n.patternReused,n.tokensSaved||0),this.updateDomainMetrics(n.domain,n.usage);return this.taskMetrics.length>this.persistenceConfig.maxMetricsInMemory&&(this.taskMetrics=this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory)),!0}maybePersistToKv(){this.kvPersistCount++,this.kvPersistCount>=u.KV_PERSIST_INTERVAL&&(this.kvPersistCount=0,this.persistToKv().catch(t=>{M.warn("KV persist failed",{error:t instanceof Error?t.message:String(t)})}))}ensureInitialized(){this.initialized||this.initialize()}calculateCost(t){let e=t.inputTokens*this.costConfig.costPerInputToken,n=t.outputTokens*this.costConfig.costPerOutputToken;return Math.round((e+n)*1e5)/1e5}filterByTimeframe(t,e){if(!e)return t;let n=Date.now(),a;switch(e){case"1h":a=n-3600*1e3;break;case"24h":a=n-1440*60*1e3;break;case"7d":a=n-10080*60*1e3;break;case"30d":a=n-720*60*60*1e3;break;default:return t}return t.filter(s=>s.timestamp>=a)}aggregateTokenUsage(t){let e=0,n=0,a=0,s=0;for(let r of t)e+=r.usage.inputTokens,n+=r.usage.outputTokens,a+=r.usage.totalTokens,s+=r.usage.estimatedCostUsd||0;return{inputTokens:e,outputTokens:n,totalTokens:a,estimatedCostUsd:Math.round(s*1e5)/1e5}}aggregateAgentMetrics(t,e){let n=0,a=0,s=0,r=0,c=0,d=0;for(let i of e)n+=i.usage.inputTokens,a+=i.usage.outputTokens,s+=i.usage.totalTokens,r+=i.usage.estimatedCostUsd||0,i.patternReused&&c++,d+=i.tokensSaved||0;return{agentId:t,totalInputTokens:n,totalOutputTokens:a,totalTokens:s,totalCost:Math.round(r*1e5)/1e5,tasksExecuted:e.length,patternsReused:c,estimatedTokensSaved:d}}updateAgentMetrics(t,e,n,a){let s=this.agentMetrics.get(t);s?(s.totalInputTokens+=e.inputTokens,s.totalOutputTokens+=e.outputTokens,s.totalTokens+=e.totalTokens,s.totalCost+=e.estimatedCostUsd||0,s.tasksExecuted++,n&&s.patternsReused++,s.estimatedTokensSaved+=a):this.agentMetrics.set(t,{agentId:t,totalInputTokens:e.inputTokens,totalOutputTokens:e.outputTokens,totalTokens:e.totalTokens,totalCost:e.estimatedCostUsd||0,tasksExecuted:1,patternsReused:n?1:0,estimatedTokensSaved:a})}updateDomainMetrics(t,e){let n=this.domainMetrics.get(t);n?(n.inputTokens+=e.inputTokens,n.outputTokens+=e.outputTokens,n.totalTokens+=e.totalTokens,n.estimatedCostUsd=(n.estimatedCostUsd||0)+(e.estimatedCostUsd||0)):this.domainMetrics.set(t,{...e})}generateRecommendations(t){let e=[];if(t.length===0)return["No token usage data available yet. Start executing tasks to track consumption."];let n=t.filter(i=>i.patternReused).length/t.length;n<.2?e.push("Low pattern reuse rate detected. Consider enabling pattern caching for similar tasks."):n>.5&&e.push("Good pattern reuse rate. Continue leveraging cached patterns for token savings.");let a=new Map;for(let i of t){let o=a.get(i.domain)||0;a.set(i.domain,o+i.usage.totalTokens)}let s=Array.from(a.entries()).sort((i,o)=>o[1]-i[1]);if(s.length>0){let i=s[0];e.push(`Highest token consumer: ${i[0]} (${i[1].toLocaleString()} tokens). Consider optimizing prompts or increasing caching.`)}let r=t.reduce((i,o)=>i+o.usage.inputTokens,0);return t.reduce((i,o)=>i+o.usage.outputTokens,0)/(r||1)>2&&e.push("High output-to-input token ratio. Consider requesting more concise responses."),this.cacheHits===0&&t.length>10&&e.push("No cache hits detected. Enable response caching to reduce duplicate API calls."),this.earlyExits===0&&t.length>20&&e.push("Early exit optimization not utilized. Enable high-confidence pattern matching to skip unnecessary LLM calls."),e}};function b(u){return u.toLocaleString("en-US")}function z(u){if(process.env.AQE_TOKEN_DASHBOARD_ENABLED==="false")return"Token dashboard disabled (AQE_TOKEN_DASHBOARD_ENABLED=false)";if(!u){let d=E.getSessionSummary(),i=d.totalUsage.totalTokens,o=d.totalUsage.estimatedCostUsd??0,l=d.optimizationStats.tokensSaved,k=i>0?o/i:0,g=l*k;u={totalTokens:i,totalCostUsd:o,savedTokens:l,savedCostUsd:g}}let t=u.totalTokens??0,e=u.totalCostUsd??0,n=u.savedTokens??0,a=u.savedCostUsd??0,s=u.budgetLimitUsd;if(t===0&&n===0)return"Token Dashboard: No data available";let r=`Token Usage: ${b(t)} tokens ($${e.toFixed(2)})`;n>0&&(r+=` | Saved: ${b(n)} tokens ($${a.toFixed(2)}) via pattern reuse`);let c=[];if(s!==void 0&&s>0){let d=Math.round(e/s*100);c.push(`Budget: $${e.toFixed(2)} / $${s.toFixed(2)} (${d}%)`)}if(u.tierSplit&&Object.keys(u.tierSplit).length>0){let d=Object.entries(u.tierSplit).sort((i,o)=>o[1]-i[1]).map(([i,o])=>`${i} ${o}%`);c.push(`Tier split: ${d.join(" | ")}`)}return c.length===0?r:`${r}
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.5");process.exit(0)}
|
|
2
|
+
import{i as f,m as P}from"./chunk-R573V37S.js";import{b as h,d as U}from"./chunk-56RA6YPN.js";import{d as p,e as y}from"./chunk-VC256KH2.js";import{a as T,c as C}from"./chunk-S73KENCH.js";P();C();U();y();import{randomUUID as v}from"crypto";var M=p("TokenTracker"),S={costPerInputToken:.003/1e3,costPerOutputToken:.015/1e3},I={filePath:".agentic-qe/token-metrics.json",autoSaveIntervalMs:6e4,maxMetricsInMemory:1e4},m=class u{taskMetrics=[];agentMetrics=new Map;domainMetrics=new Map;sessionId;sessionStartTime;costConfig;cacheHits=0;earlyExits=0;totalTokensSaved=0;totalPatternsReused=0;initialized=!1;persistenceConfig=I;autoSaveTimer=null;isDirty=!1;db=null;kvPersistCount=0;static KV_NAMESPACE="token-usage-metrics";static KV_KEY="token-tracker-snapshot";static KV_TTL=604800;static KV_PERSIST_INTERVAL=10;constructor(){this.sessionId=`session-${Date.now()}-${v().substring(0,8)}`,this.sessionStartTime=Date.now(),this.costConfig=S}initialize(t){this.initialized||(this.initialized=!0,t&&(this.costConfig={...S,...t}),this.initializeDb().catch(e=>{M.warn("DB initialization failed",{error:e instanceof Error?e.message:String(e)})}),this.startAutoSave())}setCostConfig(t){this.costConfig={...this.costConfig,...t}}recordTokenUsage(t,e,n,a,s,r){this.ensureInitialized();let c,d,i,o,l,k;typeof e=="object"?(c="default",d="unknown",i="unknown",o=e,l=!1,k=0):(c=e,d=n??"unknown",i=a??"unknown",o=s,l=r?.patternReused??!1,k=r?.tokensSaved??0),o.estimatedCostUsd===void 0&&(o.estimatedCostUsd=this.calculateCost(o));let g={taskId:t,agentId:c,domain:d,operation:i,timestamp:Date.now(),usage:o,patternReused:l,tokensSaved:k};this.taskMetrics.push(g),this.updateAgentMetrics(c,o,l,k),this.updateDomainMetrics(d,o),l&&this.totalPatternsReused++,k>0&&(this.totalTokensSaved+=k),this.isDirty=!0,this.maybePersistToKv()}recordPatternReuse(t,e){this.ensureInitialized(),this.totalPatternsReused++,this.totalTokensSaved+=e;let n={taskId:t,agentId:"pattern-cache",domain:"optimization",operation:"pattern-reuse",timestamp:Date.now(),usage:{inputTokens:0,outputTokens:0,totalTokens:0,estimatedCostUsd:0},patternReused:!0,tokensSaved:e};this.taskMetrics.push(n),this.isDirty=!0}recordCacheHit(t){this.cacheHits++,this.totalTokensSaved+=t,this.isDirty=!0}recordEarlyExit(t){this.earlyExits++,this.totalTokensSaved+=t,this.isDirty=!0}getSessionSummary(t){this.ensureInitialized();let e=this.filterByTimeframe(this.taskMetrics,t),n=this.aggregateTokenUsage(e),a=new Map;for(let i of e){let o=a.get(i.agentId);o?(o.totalInputTokens+=i.usage.inputTokens,o.totalOutputTokens+=i.usage.outputTokens,o.totalTokens+=i.usage.totalTokens,o.totalCost+=i.usage.estimatedCostUsd||0,o.tasksExecuted++,i.patternReused&&o.patternsReused++,o.estimatedTokensSaved+=i.tokensSaved||0):a.set(i.agentId,{agentId:i.agentId,totalInputTokens:i.usage.inputTokens,totalOutputTokens:i.usage.outputTokens,totalTokens:i.usage.totalTokens,totalCost:i.usage.estimatedCostUsd||0,tasksExecuted:1,patternsReused:i.patternReused?1:0,estimatedTokensSaved:i.tokensSaved||0})}let s=new Map;for(let i of e){let o=s.get(i.domain);o?(o.inputTokens+=i.usage.inputTokens,o.outputTokens+=i.usage.outputTokens,o.totalTokens+=i.usage.totalTokens,o.estimatedCostUsd=(o.estimatedCostUsd||0)+(i.usage.estimatedCostUsd||0)):s.set(i.domain,{...i.usage})}let r=n.totalTokens,c=this.totalTokensSaved,d=r+c>0?c/(r+c)*100:0;return{sessionId:this.sessionId,startTime:this.sessionStartTime,endTime:Date.now(),byAgent:a,byDomain:s,totalUsage:n,optimizationStats:{patternsReused:this.totalPatternsReused,cacheHits:this.cacheHits,earlyExits:this.earlyExits,tokensSaved:this.totalTokensSaved,savingsPercentage:Math.round(d*100)/100}}}getAgentMetrics(t,e){this.ensureInitialized();let n=this.filterByTimeframe(this.taskMetrics,e);if(t){let s=n.filter(r=>r.agentId===t);return this.aggregateAgentMetrics(t,s)}let a=new Map;for(let s of n){let r=a.get(s.agentId)||[];r.push(s),a.set(s.agentId,r)}return Array.from(a.entries()).map(([s,r])=>this.aggregateAgentMetrics(s,r))}getDomainMetrics(t,e){this.ensureInitialized();let n=this.filterByTimeframe(this.taskMetrics,e);if(t){let s=n.filter(r=>r.domain===t);return this.aggregateTokenUsage(s)}let a=new Map;for(let s of n){let r=a.get(s.domain);r?(r.inputTokens+=s.usage.inputTokens,r.outputTokens+=s.usage.outputTokens,r.totalTokens+=s.usage.totalTokens,r.estimatedCostUsd=(r.estimatedCostUsd||0)+(s.usage.estimatedCostUsd||0)):a.set(s.domain,{...s.usage})}return a}getTaskMetrics(t){return this.ensureInitialized(),this.filterByTimeframe(this.taskMetrics,t)}getEfficiencyReport(t){return this.getTokenEfficiency(t)}getTokenEfficiency(t){this.ensureInitialized();let e=this.filterByTimeframe(this.taskMetrics,t),a=this.aggregateTokenUsage(e).totalTokens,s=this.totalTokensSaved,r=a+s>0?s/(a+s)*100:0,c=e.length,d=c>0?e.filter(l=>l.patternReused).length/c:0,i=c>0?a/c:0,o=this.generateRecommendations(e);return{totalTokensUsed:a,totalTokensSaved:s,savingsPercentage:Math.round(r*100)/100,patternReuseRate:Math.round(d*100)/100,averageTokensPerTask:Math.round(i),recommendations:o}}reset(){this.stopAutoSave(),this.taskMetrics=[],this.agentMetrics.clear(),this.domainMetrics.clear(),this.sessionId=`session-${Date.now()}-${v().substring(0,8)}`,this.sessionStartTime=Date.now(),this.cacheHits=0,this.earlyExits=0,this.totalTokensSaved=0,this.totalPatternsReused=0,this.isDirty=!1}configurePersistence(t){this.persistenceConfig={...this.persistenceConfig,...t},t.autoSaveIntervalMs!==void 0&&(this.stopAutoSave(),t.autoSaveIntervalMs>0&&this.startAutoSave())}startAutoSave(){this.autoSaveTimer||this.persistenceConfig.autoSaveIntervalMs>0&&(this.autoSaveTimer=setInterval(()=>{this.isDirty&&this.save().catch(t=>{console.warn("[TokenMetricsCollector] Auto-save failed:",t)})},this.persistenceConfig.autoSaveIntervalMs))}stopAutoSave(){this.autoSaveTimer&&(clearInterval(this.autoSaveTimer),this.autoSaveTimer=null)}async save(){let t=await import("fs"),e=await import("path"),n={version:"1.0.0",sessionId:this.sessionId,sessionStartTime:this.sessionStartTime,taskMetrics:this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory),optimizationStats:{cacheHits:this.cacheHits,earlyExits:this.earlyExits,totalTokensSaved:this.totalTokensSaved,totalPatternsReused:this.totalPatternsReused},lastSavedAt:Date.now()},a=e.resolve(this.persistenceConfig.filePath),s=e.dirname(a);t.existsSync(s)||t.mkdirSync(s,{recursive:!0}),t.writeFileSync(a,JSON.stringify(n,null,2)),this.isDirty=!1}async load(){let t=await import("fs"),n=(await import("path")).resolve(this.persistenceConfig.filePath);if(!t.existsSync(n))return!1;try{let a=t.readFileSync(n,"utf-8"),s=h(a);if(!s.version||!s.version.startsWith("1."))return console.warn("[TokenMetricsCollector] Incompatible data version, skipping load"),!1;let r=s.taskMetrics||[];this.taskMetrics=[...r,...this.taskMetrics],this.cacheHits+=s.optimizationStats?.cacheHits||0,this.earlyExits+=s.optimizationStats?.earlyExits||0,this.totalTokensSaved+=s.optimizationStats?.totalTokensSaved||0,this.totalPatternsReused+=s.optimizationStats?.totalPatternsReused||0;for(let c of r)this.updateAgentMetrics(c.agentId,c.usage,c.patternReused,c.tokensSaved||0),this.updateDomainMetrics(c.domain,c.usage);return this.taskMetrics.length>this.persistenceConfig.maxMetricsInMemory&&(this.taskMetrics=this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory)),!0}catch(a){return console.warn("[TokenMetricsCollector] Failed to load persisted data:",a),!1}}getPersistenceFilePath(){return this.persistenceConfig.filePath}hasUnsavedChanges(){return this.isDirty}async initializeDb(){try{this.db=f(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(t){console.warn("[TokenMetricsCollector] DB init failed, using memory-only:",T(t)),this.db=null}}async persistToKv(){if(!this.db)return;let t={version:"1.0.0",sessionId:this.sessionId,sessionStartTime:this.sessionStartTime,taskMetrics:this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory),optimizationStats:{cacheHits:this.cacheHits,earlyExits:this.earlyExits,totalTokensSaved:this.totalTokensSaved,totalPatternsReused:this.totalPatternsReused},lastSavedAt:Date.now()};await this.db.kvSet(u.KV_KEY,t,u.KV_NAMESPACE,u.KV_TTL)}async loadFromKv(){if(!this.db)return!1;let t=await this.db.kvGet(u.KV_KEY,u.KV_NAMESPACE);if(!t)return!1;if(!t.version||!t.version.startsWith("1."))return console.warn("[TokenMetricsCollector] Incompatible kv_store data version, skipping load"),!1;let e=t.taskMetrics||[];this.taskMetrics=[...e,...this.taskMetrics],this.cacheHits+=t.optimizationStats?.cacheHits||0,this.earlyExits+=t.optimizationStats?.earlyExits||0,this.totalTokensSaved+=t.optimizationStats?.totalTokensSaved||0,this.totalPatternsReused+=t.optimizationStats?.totalPatternsReused||0;for(let n of e)this.updateAgentMetrics(n.agentId,n.usage,n.patternReused,n.tokensSaved||0),this.updateDomainMetrics(n.domain,n.usage);return this.taskMetrics.length>this.persistenceConfig.maxMetricsInMemory&&(this.taskMetrics=this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory)),!0}maybePersistToKv(){this.kvPersistCount++,this.kvPersistCount>=u.KV_PERSIST_INTERVAL&&(this.kvPersistCount=0,this.persistToKv().catch(t=>{M.warn("KV persist failed",{error:t instanceof Error?t.message:String(t)})}))}ensureInitialized(){this.initialized||this.initialize()}calculateCost(t){let e=t.inputTokens*this.costConfig.costPerInputToken,n=t.outputTokens*this.costConfig.costPerOutputToken;return Math.round((e+n)*1e5)/1e5}filterByTimeframe(t,e){if(!e)return t;let n=Date.now(),a;switch(e){case"1h":a=n-3600*1e3;break;case"24h":a=n-1440*60*1e3;break;case"7d":a=n-10080*60*1e3;break;case"30d":a=n-720*60*60*1e3;break;default:return t}return t.filter(s=>s.timestamp>=a)}aggregateTokenUsage(t){let e=0,n=0,a=0,s=0;for(let r of t)e+=r.usage.inputTokens,n+=r.usage.outputTokens,a+=r.usage.totalTokens,s+=r.usage.estimatedCostUsd||0;return{inputTokens:e,outputTokens:n,totalTokens:a,estimatedCostUsd:Math.round(s*1e5)/1e5}}aggregateAgentMetrics(t,e){let n=0,a=0,s=0,r=0,c=0,d=0;for(let i of e)n+=i.usage.inputTokens,a+=i.usage.outputTokens,s+=i.usage.totalTokens,r+=i.usage.estimatedCostUsd||0,i.patternReused&&c++,d+=i.tokensSaved||0;return{agentId:t,totalInputTokens:n,totalOutputTokens:a,totalTokens:s,totalCost:Math.round(r*1e5)/1e5,tasksExecuted:e.length,patternsReused:c,estimatedTokensSaved:d}}updateAgentMetrics(t,e,n,a){let s=this.agentMetrics.get(t);s?(s.totalInputTokens+=e.inputTokens,s.totalOutputTokens+=e.outputTokens,s.totalTokens+=e.totalTokens,s.totalCost+=e.estimatedCostUsd||0,s.tasksExecuted++,n&&s.patternsReused++,s.estimatedTokensSaved+=a):this.agentMetrics.set(t,{agentId:t,totalInputTokens:e.inputTokens,totalOutputTokens:e.outputTokens,totalTokens:e.totalTokens,totalCost:e.estimatedCostUsd||0,tasksExecuted:1,patternsReused:n?1:0,estimatedTokensSaved:a})}updateDomainMetrics(t,e){let n=this.domainMetrics.get(t);n?(n.inputTokens+=e.inputTokens,n.outputTokens+=e.outputTokens,n.totalTokens+=e.totalTokens,n.estimatedCostUsd=(n.estimatedCostUsd||0)+(e.estimatedCostUsd||0)):this.domainMetrics.set(t,{...e})}generateRecommendations(t){let e=[];if(t.length===0)return["No token usage data available yet. Start executing tasks to track consumption."];let n=t.filter(i=>i.patternReused).length/t.length;n<.2?e.push("Low pattern reuse rate detected. Consider enabling pattern caching for similar tasks."):n>.5&&e.push("Good pattern reuse rate. Continue leveraging cached patterns for token savings.");let a=new Map;for(let i of t){let o=a.get(i.domain)||0;a.set(i.domain,o+i.usage.totalTokens)}let s=Array.from(a.entries()).sort((i,o)=>o[1]-i[1]);if(s.length>0){let i=s[0];e.push(`Highest token consumer: ${i[0]} (${i[1].toLocaleString()} tokens). Consider optimizing prompts or increasing caching.`)}let r=t.reduce((i,o)=>i+o.usage.inputTokens,0);return t.reduce((i,o)=>i+o.usage.outputTokens,0)/(r||1)>2&&e.push("High output-to-input token ratio. Consider requesting more concise responses."),this.cacheHits===0&&t.length>10&&e.push("No cache hits detected. Enable response caching to reduce duplicate API calls."),this.earlyExits===0&&t.length>20&&e.push("Early exit optimization not utilized. Enable high-confidence pattern matching to skip unnecessary LLM calls."),e}};function b(u){return u.toLocaleString("en-US")}function z(u){if(process.env.AQE_TOKEN_DASHBOARD_ENABLED==="false")return"Token dashboard disabled (AQE_TOKEN_DASHBOARD_ENABLED=false)";if(!u){let d=E.getSessionSummary(),i=d.totalUsage.totalTokens,o=d.totalUsage.estimatedCostUsd??0,l=d.optimizationStats.tokensSaved,k=i>0?o/i:0,g=l*k;u={totalTokens:i,totalCostUsd:o,savedTokens:l,savedCostUsd:g}}let t=u.totalTokens??0,e=u.totalCostUsd??0,n=u.savedTokens??0,a=u.savedCostUsd??0,s=u.budgetLimitUsd;if(t===0&&n===0)return"Token Dashboard: No data available";let r=`Token Usage: ${b(t)} tokens ($${e.toFixed(2)})`;n>0&&(r+=` | Saved: ${b(n)} tokens ($${a.toFixed(2)}) via pattern reuse`);let c=[];if(s!==void 0&&s>0){let d=Math.round(e/s*100);c.push(`Budget: $${e.toFixed(2)} / $${s.toFixed(2)} (${d}%)`)}if(u.tierSplit&&Object.keys(u.tierSplit).length>0){let d=Object.entries(u.tierSplit).sort((i,o)=>o[1]-i[1]).map(([i,o])=>`${i} ${o}%`);c.push(`Tier split: ${d.join(" | ")}`)}return c.length===0?r:`${r}
|
|
3
3
|
${c.join(" | ")}`}var E=new m;function $(u){return`$${u.toFixed(2)}`}export{z as a,E as b,$ as c};
|