agentic-qe 3.9.13 → 3.9.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude/skills/skills-manifest.json +1 -1
- package/CHANGELOG.md +24 -0
- package/assets/skills/skills-manifest.json +1 -1
- package/dist/cli/bundle.js +5 -5
- package/dist/cli/chunks/adapter-W2EM7ZQ7.js +2 -0
- package/dist/cli/chunks/{agent-booster-wasm-3RBPTJAU.js → agent-booster-wasm-O6EXMPMF.js} +2 -2
- package/dist/cli/chunks/{agent-handler-XV45GCWC.js → agent-handler-4LPJVTJU.js} +2 -2
- package/dist/cli/chunks/{agent-memory-branch-V6EXWWMY.js → agent-memory-branch-PRR323JZ.js} +2 -2
- package/dist/cli/chunks/aqe-learning-engine-JQMPNHQU.js +2 -0
- package/dist/cli/chunks/{audit-WXFI4AC4.js → audit-YCKXQOXD.js} +2 -2
- package/dist/cli/chunks/base-EOPYE6JR.js +2 -0
- package/dist/cli/chunks/{better-sqlite3-23MIVVHF.js → better-sqlite3-44RIH62G.js} +2 -2
- package/dist/cli/chunks/{brain-handler-LQUMAACV.js → brain-handler-IAYJBAFL.js} +3 -3
- package/dist/cli/chunks/{branch-enumerator-HE37VX7G.js → branch-enumerator-RVVS2UYR.js} +2 -2
- package/dist/cli/chunks/{browser-3VG5M7WM.js → browser-L6IKC4PR.js} +2 -2
- package/dist/cli/chunks/browser-workflow-CSARLAJD.js +2 -0
- package/dist/cli/chunks/chunk-2L3BCZ2F.js +2 -0
- package/dist/cli/chunks/{chunk-WQGP5ULD.js → chunk-36YZ2UF7.js} +2 -2
- package/dist/cli/chunks/{chunk-LHZLH6I4.js → chunk-3GIZRGX6.js} +2 -2
- package/dist/cli/chunks/{chunk-VJN7NQGI.js → chunk-3NUMJB3U.js} +10 -10
- package/dist/cli/chunks/{chunk-Q7TWE55T.js → chunk-3PZ2QLLR.js} +4 -4
- package/dist/cli/chunks/{chunk-4VETZICF.js → chunk-3ZKTPPIC.js} +1 -1
- package/dist/cli/chunks/{chunk-RYPUA6E2.js → chunk-4EQWK6P6.js} +2 -2
- package/dist/cli/chunks/{chunk-RURYOWWU.js → chunk-4JYLXYAH.js} +1 -1
- package/dist/cli/chunks/{chunk-WQIB5ERQ.js → chunk-4RDTR2OF.js} +2 -2
- package/dist/cli/chunks/chunk-53KLVMAT.js +18 -0
- package/dist/cli/chunks/{chunk-TPTKR5ZO.js → chunk-5DWTU2PN.js} +1 -1
- package/dist/cli/chunks/{chunk-W2YCNX4O.js → chunk-5HUAD4UU.js} +2 -2
- package/dist/cli/chunks/{chunk-Q3MQYATA.js → chunk-5MWNXDQW.js} +2 -2
- package/dist/cli/chunks/{chunk-LRHJOYKY.js → chunk-5U6M4XCP.js} +3 -3
- package/dist/cli/chunks/{chunk-OKCI6BNZ.js → chunk-6BK2S2WE.js} +2 -2
- package/dist/cli/chunks/chunk-6EZY2QVM.js +3021 -0
- package/dist/cli/chunks/{chunk-OJGR56BP.js → chunk-6GKXC6DE.js} +2 -2
- package/dist/cli/chunks/{chunk-YBKSENTJ.js → chunk-6J6GXRHX.js} +5 -5
- package/dist/cli/chunks/chunk-7732TLNA.js +5 -0
- package/dist/cli/chunks/{chunk-AXDGBI4Y.js → chunk-7IJBZGZY.js} +1 -1
- package/dist/cli/chunks/{chunk-Y7YSJD4I.js → chunk-A2TK52B2.js} +2 -2
- package/dist/cli/chunks/chunk-AEQMQVDJ.js +2 -0
- package/dist/cli/chunks/{chunk-ZN7KPIJW.js → chunk-AHVUILGE.js} +1 -1
- package/dist/cli/chunks/{chunk-4MZZMWF6.js → chunk-AOYN6XYJ.js} +1 -1
- package/dist/cli/chunks/{chunk-FEGITTAE.js → chunk-BFCMOMOF.js} +1 -1
- package/dist/cli/chunks/{chunk-D22MEX2U.js → chunk-BNPJMPM3.js} +2 -2
- package/dist/cli/chunks/{chunk-3IJ4NRJF.js → chunk-BOMJHE4I.js} +2 -2
- package/dist/cli/chunks/{chunk-TU3JIH3U.js → chunk-CGC63MGF.js} +4 -4
- package/dist/cli/chunks/{chunk-FS4TPAAA.js → chunk-D6APBW66.js} +1 -1
- package/dist/cli/chunks/chunk-DD4T7ZUM.js +3 -0
- package/dist/cli/chunks/{chunk-ERGY45RL.js → chunk-DGUAAG3T.js} +1 -1
- package/dist/cli/chunks/{chunk-JOCR5TWI.js → chunk-DJLRRCR6.js} +2 -2
- package/dist/cli/chunks/{chunk-VCJP7HQG.js → chunk-DMZ2XOEW.js} +2 -2
- package/dist/cli/chunks/{chunk-6GYMFSPA.js → chunk-DNFDSDKE.js} +2 -2
- package/dist/cli/chunks/{chunk-H53V7GI3.js → chunk-ERMIIRYN.js} +1 -1
- package/dist/cli/chunks/{chunk-RMNZSGTE.js → chunk-FFACJODG.js} +2 -2
- package/dist/cli/chunks/{chunk-AV23XNRL.js → chunk-FNKKENLS.js} +2 -2
- package/dist/cli/chunks/{chunk-UDIRBCZW.js → chunk-FWI7PK4X.js} +1 -1
- package/dist/cli/chunks/{chunk-QNUVC6OX.js → chunk-FYBTGEOV.js} +1 -1
- package/dist/cli/chunks/{chunk-ZUW3KVML.js → chunk-G2KQUEGY.js} +2 -2
- package/dist/cli/chunks/{chunk-IQGVQBVS.js → chunk-G7L5Y47C.js} +1 -1
- package/dist/cli/chunks/{chunk-OHG6SNIA.js → chunk-GALNZTYE.js} +2 -2
- package/dist/cli/chunks/chunk-GIUAY4KY.js +12 -0
- package/dist/cli/chunks/chunk-GM5LIYLQ.js +2 -0
- package/dist/cli/chunks/{chunk-DY5JRJXV.js → chunk-GOTVYSX5.js} +3 -3
- package/dist/cli/chunks/{chunk-HHRUXDLT.js → chunk-GUEK5DOK.js} +2 -2
- package/dist/cli/chunks/{chunk-AOTEEGQA.js → chunk-HEQ23HBE.js} +2 -2
- package/dist/cli/chunks/{chunk-MXT7YUOZ.js → chunk-HJJTLOWZ.js} +2 -2
- package/dist/cli/chunks/{chunk-KULWZMVC.js → chunk-I3P5RZX7.js} +4 -4
- package/dist/cli/chunks/{chunk-HJHFGPGP.js → chunk-I5U64MHU.js} +2 -2
- package/dist/cli/chunks/{chunk-VWEGO7BY.js → chunk-IH4OOAEP.js} +1 -1
- package/dist/cli/chunks/{chunk-SSZMISGC.js → chunk-IL3ESNHA.js} +2 -2
- package/dist/cli/chunks/{chunk-6HSHLSGU.js → chunk-IOHDE27P.js} +2 -2
- package/dist/cli/chunks/{chunk-OM7A3YC3.js → chunk-J3XLOHWB.js} +2 -2
- package/dist/cli/chunks/{chunk-OUNZPHTA.js → chunk-J5YOXLBD.js} +1 -1
- package/dist/cli/chunks/{chunk-V2CV6J2A.js → chunk-JLBUS4PR.js} +2 -2
- package/dist/cli/chunks/{chunk-77GZ7LXL.js → chunk-JN7MSUGK.js} +2 -2
- package/dist/cli/chunks/{chunk-YYQVSVBO.js → chunk-JNLKLC7G.js} +2 -2
- package/dist/cli/chunks/chunk-JOGKQTCU.js +24 -0
- package/dist/cli/chunks/{chunk-BUIMIUJA.js → chunk-JWR3NNFA.js} +1 -1
- package/dist/cli/chunks/chunk-KFAN5FZM.js +2 -0
- package/dist/cli/chunks/{chunk-6LDRSG7C.js → chunk-KHUFPJE4.js} +3 -3
- package/dist/cli/chunks/{chunk-TRJRRJV3.js → chunk-KJB6JJXT.js} +1 -1
- package/dist/cli/chunks/{chunk-W6LEOFA4.js → chunk-KVN4FTPT.js} +2 -2
- package/dist/cli/chunks/{chunk-V6UODTBP.js → chunk-L4IWZXSC.js} +1 -1
- package/dist/cli/chunks/{chunk-VHSDZEYF.js → chunk-LJ3WQIBN.js} +1 -1
- package/dist/cli/chunks/{chunk-AEKTVLLF.js → chunk-LKGLKX2A.js} +2 -2
- package/dist/cli/chunks/{chunk-CF5EJGOV.js → chunk-LWHM5BWD.js} +2 -2
- package/dist/cli/chunks/{chunk-I6O4MVEY.js → chunk-M2RO34V7.js} +4 -4
- package/dist/cli/chunks/{chunk-XV42SKJD.js → chunk-ME4LVBTT.js} +2 -2
- package/dist/cli/chunks/chunk-MFGYMNNY.js +2 -0
- package/dist/cli/chunks/{chunk-54A2LVKM.js → chunk-MXIFVOYA.js} +2 -2
- package/dist/cli/chunks/{chunk-TOS3PI5Q.js → chunk-NWGIQCCO.js} +1 -1
- package/dist/cli/chunks/chunk-NWZYULZE.js +65 -0
- package/dist/cli/chunks/{chunk-4PCHU2X7.js → chunk-OGLS6HB4.js} +1 -1
- package/dist/cli/chunks/{chunk-E7P6GAD7.js → chunk-ORHCO2I7.js} +2 -2
- package/dist/cli/chunks/{chunk-X3UVXJIK.js → chunk-OZBTC26R.js} +2 -2
- package/dist/cli/chunks/{chunk-ZXJNX5D2.js → chunk-P5YSBYZV.js} +1 -1
- package/dist/cli/chunks/{chunk-GHAEDZDE.js → chunk-PFSSI3YR.js} +2 -2
- package/dist/cli/chunks/{chunk-QIE76ERL.js → chunk-PZF5ISGS.js} +1 -1
- package/dist/cli/chunks/{chunk-3RM2VNYG.js → chunk-Q4DAYLH4.js} +2 -2
- package/dist/cli/chunks/{chunk-OGHIQCJU.js → chunk-QLWP7ZIT.js} +2 -2
- package/dist/cli/chunks/{chunk-Z6F4GRXY.js → chunk-QUK34CSU.js} +2 -2
- package/dist/cli/chunks/chunk-RQFC7Q33.js +2 -0
- package/dist/cli/chunks/{chunk-OBDM6OJL.js → chunk-S2KGZJHS.js} +1 -1
- package/dist/cli/chunks/{chunk-TNQBHQFH.js → chunk-S6SM7LJK.js} +2 -2
- package/dist/cli/chunks/chunk-STYNOKOM.js +2 -0
- package/dist/cli/chunks/{chunk-2RTGP76Y.js → chunk-SUXUCW5I.js} +2 -2
- package/dist/cli/chunks/chunk-SY74WSBN.js +2 -0
- package/dist/cli/chunks/{chunk-FLML5IT7.js → chunk-TJOZPPZR.js} +2 -2
- package/dist/cli/chunks/{chunk-JV7HKHQS.js → chunk-TOSFK4VG.js} +2 -2
- package/dist/cli/chunks/{chunk-VVVIRGO7.js → chunk-UAAJ3BSW.js} +2 -2
- package/dist/cli/chunks/{chunk-QHCOAG7D.js → chunk-UG2J5MTY.js} +1 -1
- package/dist/cli/chunks/{chunk-3AOWTHLS.js → chunk-UIYK4Y7K.js} +2 -2
- package/dist/cli/chunks/{chunk-XXQYSDLV.js → chunk-UUVTLYUK.js} +2 -2
- package/dist/cli/chunks/{chunk-HXLAXSEM.js → chunk-VDGWDDBC.js} +2 -2
- package/dist/cli/chunks/{chunk-GKRKCJ6D.js → chunk-VEAVDXXT.js} +2 -2
- package/dist/cli/chunks/{chunk-YCQ2GHFH.js → chunk-VQB5SLXZ.js} +2 -2
- package/dist/cli/chunks/{chunk-EC2CI3ZC.js → chunk-VU4QET3C.js} +2 -2
- package/dist/cli/chunks/{chunk-OP54A7C6.js → chunk-VUS4VRPQ.js} +2 -2
- package/dist/cli/chunks/{chunk-DHYJMGKC.js → chunk-VVKENR4I.js} +1 -1
- package/dist/cli/chunks/{chunk-ZS5BM2EE.js → chunk-WE7KIXR6.js} +2 -2
- package/dist/cli/chunks/{chunk-ES6CEZG2.js → chunk-WELNFHDN.js} +1 -1
- package/dist/cli/chunks/{chunk-TWRGM5TY.js → chunk-WSZVSDD5.js} +2 -2
- package/dist/cli/chunks/{chunk-SL66MHDM.js → chunk-WUYJYRBY.js} +1 -1
- package/dist/cli/chunks/{chunk-WVWB7K6H.js → chunk-WVN4YJSF.js} +2 -2
- package/dist/cli/chunks/{chunk-CPRYUCPC.js → chunk-XH774Q6Z.js} +1 -1
- package/dist/cli/chunks/{chunk-AZPDX4KS.js → chunk-XNXOW7BQ.js} +2 -2
- package/dist/cli/chunks/{chunk-7HX2PMBB.js → chunk-Y3X5OS5F.js} +2 -2
- package/dist/cli/chunks/chunk-YPMBD44A.js +2 -0
- package/dist/cli/chunks/{chunk-BE2DYHUB.js → chunk-YZBY4ZRF.js} +2 -2
- package/dist/cli/chunks/{chunk-VU7ENCSU.js → chunk-Z3PSKGBO.js} +2 -2
- package/dist/cli/chunks/{chunk-UCCNB75R.js → chunk-ZCRLZINE.js} +2 -2
- package/dist/cli/chunks/{chunk-EBQUXPIG.js → chunk-ZFZX2NA3.js} +2 -2
- package/dist/cli/chunks/{chunk-5TDHUYYF.js → chunk-ZU5VHW6P.js} +2 -2
- package/dist/cli/chunks/{ci-FEEIAOQN.js → ci-QQ4F5TYO.js} +2 -2
- package/dist/cli/chunks/{ci-output-2WMUTORB.js → ci-output-QC4WRENA.js} +2 -2
- package/dist/cli/chunks/{circuit-breaker-MFEE23XA.js → circuit-breaker-HFQUNYTK.js} +2 -2
- package/dist/cli/chunks/{claude-flow-setup-6D655INK.js → claude-flow-setup-XNSCWIUN.js} +2 -2
- package/dist/cli/chunks/client-3GECKJWB.js +2 -0
- package/dist/cli/chunks/{cline-installer-5PIYMPAG.js → cline-installer-S3CECBYL.js} +2 -2
- package/dist/cli/chunks/{code-ACS453WG.js → code-QHUELDUH.js} +2 -2
- package/dist/cli/chunks/{code-index-extractor-5SERI6TM.js → code-index-extractor-QLA5EQTE.js} +2 -2
- package/dist/cli/chunks/{codex-installer-WCUUWHP5.js → codex-installer-CQ7JNNOA.js} +2 -2
- package/dist/cli/chunks/{completions-6WFG3FPJ.js → completions-S33U3KIT.js} +2 -2
- package/dist/cli/chunks/{complexity-analyzer-IFZEFCB6.js → complexity-analyzer-J7IEW3EM.js} +2 -2
- package/dist/cli/chunks/{continuedev-installer-RW6FEEND.js → continuedev-installer-DVU24D37.js} +2 -2
- package/dist/cli/chunks/{copilot-installer-UZPE65RL.js → copilot-installer-DYISOPBC.js} +2 -2
- package/dist/cli/chunks/{cost-tracker-2R4FT6TY.js → cost-tracker-URJADKKS.js} +2 -2
- package/dist/cli/chunks/{coverage-ZUC5U47P.js → coverage-NGMKJNW6.js} +3 -3
- package/dist/cli/chunks/cross-domain-router-UYONX76U.js +2 -0
- package/dist/cli/chunks/{cursor-installer-7JBZT7JZ.js → cursor-installer-DFBJRDSY.js} +2 -2
- package/dist/cli/chunks/daemon-JSKKVVCV.js +19 -0
- package/dist/cli/chunks/{dag-attention-scheduler-MS7D2NFM.js → dag-attention-scheduler-YITFS6MR.js} +2 -2
- package/dist/cli/chunks/{detect-UHOSHYVB.js → detect-5APZP2D3.js} +2 -2
- package/dist/cli/chunks/{domain-handler-BVW4AX7O.js → domain-handler-WHH6XPSZ.js} +2 -2
- package/dist/cli/chunks/{domain-transfer-PA2ENF3D.js → domain-transfer-SERX53SS.js} +2 -2
- package/dist/cli/chunks/dream-Z5QDQJSM.js +2 -0
- package/dist/cli/chunks/esm-node-FOI5Y3O2.js +2 -0
- package/dist/cli/chunks/{eval-Y3ODM7JU.js → eval-FM3BLVFO.js} +2 -2
- package/dist/cli/chunks/{fast-paths-DYQ5NC4Y.js → fast-paths-4MSOOJVK.js} +2 -2
- package/dist/cli/chunks/{feature-flags-YMMGYWT3.js → feature-flags-564YFR65.js} +2 -2
- package/dist/cli/chunks/{feature-flags-V34UZPHG.js → feature-flags-WJT57IEJ.js} +2 -2
- package/dist/cli/chunks/{file-discovery-75ZHSK4G.js → file-discovery-5QVG65WF.js} +2 -2
- package/dist/cli/chunks/{fleet-DD2CFGJL.js → fleet-CF5JRK5B.js} +3 -3
- package/dist/cli/chunks/{gnn-wrapper-UXM3L5LV.js → gnn-wrapper-NYQ77563.js} +2 -2
- package/dist/cli/chunks/{heartbeat-handler-ANHRYXNS.js → heartbeat-handler-42QJPKHE.js} +4 -4
- package/dist/cli/chunks/heartbeat-scheduler-7XEAV74Y.js +2 -0
- package/dist/cli/chunks/hnsw-adapter-NOAQ76QF.js +2 -0
- package/dist/cli/chunks/hnsw-index-KDIZQRSB.js +2 -0
- package/dist/cli/chunks/{hnsw-legacy-bridge-IFUEUOVF.js → hnsw-legacy-bridge-ZRR6PGWN.js} +2 -2
- package/dist/cli/chunks/{hnswlib-node-GYVDPTWU.js → hnswlib-node-DY7NOW76.js} +2 -2
- package/dist/cli/chunks/{hooks-R3DQNG2F.js → hooks-IRRHEJLR.js} +6 -6
- package/dist/cli/chunks/{hybrid-router-MSCQ2XGU.js → hybrid-router-S4JXJLUY.js} +2 -2
- package/dist/cli/chunks/{hypergraph-engine-3TKB5O7T.js → hypergraph-engine-WFHZJMP2.js} +2 -2
- package/dist/cli/chunks/{hypergraph-handler-4APYID2S.js → hypergraph-handler-LHUKR7PT.js} +3 -3
- package/dist/cli/chunks/impact-analyzer-VDXJBWFG.js +2 -0
- package/dist/cli/chunks/{init-handler-E7B2GKH3.js → init-handler-ZBIW7PSB.js} +6 -6
- package/dist/cli/chunks/init-wizard-Q6DEACKX.js +2 -0
- package/dist/cli/chunks/kernel-YNQOGTM5.js +2 -0
- package/dist/cli/chunks/{kilocode-installer-WY6VTFSA.js → kilocode-installer-JYHA4NW7.js} +2 -2
- package/dist/cli/chunks/{kiro-installer-SCNF3JXD.js → kiro-installer-OBXTRK77.js} +2 -2
- package/dist/cli/chunks/knowledge-graph-GOZG3YOM.js +2 -0
- package/dist/cli/chunks/learning-OAEJHEJD.js +107 -0
- package/dist/cli/chunks/{llm-router-RBKYYHBJ.js → llm-router-NNEOZAVB.js} +4 -4
- package/dist/cli/chunks/{load-FY64UGHV.js → load-WIKLBESW.js} +2 -2
- package/dist/cli/chunks/load-test-UJLTMPXW.js +2 -0
- package/dist/cli/chunks/{mcp-6VMQOWMX.js → mcp-KR43GFGP.js} +2 -2
- package/dist/cli/chunks/{memory-Y5RO4PGM.js → memory-KQIYKAYU.js} +5 -5
- package/dist/cli/chunks/memory-backend-WJH6XER3.js +2 -0
- package/dist/cli/chunks/{memory-handlers-CMMVHHPG.js → memory-handlers-LAI4AO4O.js} +2 -2
- package/dist/cli/chunks/{multi-model-executor-JO3MNMPZ.js → multi-model-executor-NPS3VOAR.js} +3 -3
- package/dist/cli/chunks/{opencode-installer-WQBTY6JT.js → opencode-installer-FE475WME.js} +2 -2
- package/dist/cli/chunks/{orchestrator-4J7OSNSG.js → orchestrator-MW4MZ3RW.js} +5 -5
- package/dist/cli/chunks/{pipeline-63T6HN72.js → pipeline-R2TGZSUA.js} +2 -2
- package/dist/cli/chunks/{platform-UJMD4EPZ.js → platform-N2GZBCBP.js} +2 -2
- package/dist/cli/chunks/{plugin-NDOZ63JW.js → plugin-V2AQF23V.js} +2 -2
- package/dist/cli/chunks/{prime-radiant-advanced-wasm-ELGHVIFI.js → prime-radiant-advanced-wasm-ZQSYRLRS.js} +2 -2
- package/dist/cli/chunks/protocol-executor-LYYYHXAX.js +2 -0
- package/dist/cli/chunks/{protocol-handler-KYERIMVF.js → protocol-handler-V3U724F2.js} +2 -2
- package/dist/cli/chunks/{prove-ATSSBP4Z.js → prove-NCH56HZB.js} +2 -2
- package/dist/cli/chunks/{provider-manager-YYMIF23V.js → provider-manager-7NUHS3T5.js} +2 -2
- package/dist/cli/chunks/qe-reasoning-bank-JK4UKLYY.js +2 -0
- package/dist/cli/chunks/{quality-2AGJSJW6.js → quality-J3IVPPPW.js} +2 -2
- package/dist/cli/chunks/queen-coordinator-6OKLSCHV.js +2 -0
- package/dist/cli/chunks/{real-embeddings-H36GVXMI.js → real-embeddings-VURZXAEY.js} +2 -2
- package/dist/cli/chunks/{roocode-installer-PMRBAY7O.js → roocode-installer-STWFJGMR.js} +2 -2
- package/dist/cli/chunks/router-DDZHCGUD.js +2 -0
- package/dist/cli/chunks/routing-feedback-BA66F37P.js +2 -0
- package/dist/cli/chunks/{routing-handler-Z7VZSDXW.js → routing-handler-6GZT7EXM.js} +2 -2
- package/dist/cli/chunks/{ruvector-commands-N3FZ3ZEE.js → ruvector-commands-LCPAH6WH.js} +2 -2
- package/dist/cli/chunks/{rvf-dual-writer-L5DQHUF3.js → rvf-dual-writer-76LWFT5X.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-adapter-NPGFA3SL.js → rvf-migration-adapter-G7KFWJKY.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-coordinator-MCJDNKXG.js → rvf-migration-coordinator-3DXOUPWF.js} +2 -2
- package/dist/cli/chunks/rvf-native-adapter-TXTRJNPW.js +2 -0
- package/dist/cli/chunks/safe-db-IFBVWIGF.js +2 -0
- package/dist/cli/chunks/schedule-WMZLOPCW.js +2 -0
- package/dist/cli/chunks/scheduler-WBORWJD5.js +2 -0
- package/dist/cli/chunks/{security-TX7TXUGI.js → security-XDBPYA5T.js} +3 -3
- package/dist/cli/chunks/shared-rvf-adapter-SQQ27EEI.js +2 -0
- package/dist/cli/chunks/{shared-rvf-dual-writer-6K3ZAG7P.js → shared-rvf-dual-writer-UGXTS2XI.js} +2 -2
- package/dist/cli/chunks/sqlite-persistence-XH47B3BG.js +2 -0
- package/dist/cli/chunks/{status-handler-MIRLQRNN.js → status-handler-ZLXES3QL.js} +2 -2
- package/dist/cli/chunks/{structural-health-CIHASLUE.js → structural-health-4PFCOQ7T.js} +2 -2
- package/dist/cli/chunks/{sync-FGLAP7EK.js → sync-3DROIEZN.js} +2 -2
- package/dist/cli/chunks/{task-handler-7HMPRCHY.js → task-handler-4UGZ5VIE.js} +2 -2
- package/dist/cli/chunks/{task-handlers-DQLQCLCT.js → task-handlers-I5VVBTWI.js} +2 -2
- package/dist/cli/chunks/{test-JKDO5ZHU.js → test-Z2MM7O5A.js} +4 -4
- package/dist/cli/chunks/{test-scheduling-2YKZ7PVZ.js → test-scheduling-AP76GKN5.js} +4 -4
- package/dist/cli/chunks/{token-bootstrap-C7UUPMQN.js → token-bootstrap-P54N6PZV.js} +2 -2
- package/dist/cli/chunks/{token-usage-2RVIPCY4.js → token-usage-AXAZTPA6.js} +2 -2
- package/dist/cli/chunks/{transformers-UEMAGHQ5.js → transformers-VOZ2Z7FS.js} +2 -2
- package/dist/cli/chunks/{tree-sitter-wasm-parser-MELABICK.js → tree-sitter-wasm-parser-IYKLBTXB.js} +2 -2
- package/dist/cli/chunks/{types-5B4RD7ZV.js → types-TKDH5EBW.js} +2 -2
- package/dist/cli/chunks/unified-memory-NHJHPLIC.js +2 -0
- package/dist/cli/chunks/unified-memory-hnsw-IMMCI2XK.js +2 -0
- package/dist/cli/chunks/unified-persistence-JS6CEV35.js +2 -0
- package/dist/cli/chunks/{validate-CHDG7SC3.js → validate-ZGF5FVZE.js} +2 -2
- package/dist/cli/chunks/{validate-swarm-LB7GORKE.js → validate-swarm-OPWWUWYA.js} +2 -2
- package/dist/cli/chunks/{vibium-ZMC4G2YA.js → vibium-HEQUGRKJ.js} +2 -2
- package/dist/cli/chunks/visual-security-XLO5JBVP.js +2 -0
- package/dist/cli/chunks/{web-tree-sitter-THNO6S2V.js → web-tree-sitter-JZ7JCJJR.js} +2 -2
- package/dist/cli/chunks/{windsurf-installer-LRB43BPX.js → windsurf-installer-2SGRCS6C.js} +2 -2
- package/dist/cli/chunks/{witness-chain-JC5UBXPM.js → witness-chain-LJUYOCB5.js} +2 -2
- package/dist/cli/chunks/witness-chain-PPWPHYTY.js +2 -0
- package/dist/cli/chunks/{workflow-Q4IYQ6F2.js → workflow-QORI3KO7.js} +4 -4
- package/dist/cli/chunks/workflow-orchestrator-H4DKRHVP.js +2 -0
- package/dist/cli/chunks/{wrappers-WSSLMFSE.js → wrappers-3NR7LNB5.js} +2 -2
- package/dist/cli/commands/learning.js +28 -8
- package/dist/domains/chaos-resilience/services/chaos-engineer.js +1 -1
- package/dist/domains/constants.d.ts +1 -1
- package/dist/domains/constants.js +1 -1
- package/dist/domains/contract-testing/services/contract-validator.js +1 -1
- package/dist/domains/learning-optimization/services/learning-coordinator.js +1 -1
- package/dist/domains/test-execution/services/test-executor.js +1 -1
- package/dist/domains/test-generation/services/test-data-generator.d.ts +1 -0
- package/dist/domains/test-generation/services/test-data-generator.js +17 -3
- package/dist/domains/visual-accessibility/services/visual-tester.js +1 -1
- package/dist/mcp/bundle.js +1782 -1790
- package/dist/mcp/protocol-server.js +20 -10
- package/package.json +7 -5
- package/dist/cli/chunks/adapter-VP3WBXE5.js +0 -2
- package/dist/cli/chunks/aqe-learning-engine-ASPPEOKQ.js +0 -2
- package/dist/cli/chunks/base-SIAOYPTD.js +0 -2
- package/dist/cli/chunks/browser-workflow-BG3M3RZU.js +0 -2
- package/dist/cli/chunks/chunk-3I6KWFJT.js +0 -2
- package/dist/cli/chunks/chunk-4WJ3BHCN.js +0 -24
- package/dist/cli/chunks/chunk-67TMNSO3.js +0 -3
- package/dist/cli/chunks/chunk-APQYMAKG.js +0 -65
- package/dist/cli/chunks/chunk-BSTCXDVH.js +0 -2
- package/dist/cli/chunks/chunk-F74IVEON.js +0 -2
- package/dist/cli/chunks/chunk-FHWDVN65.js +0 -18
- package/dist/cli/chunks/chunk-HEHGQM2H.js +0 -3029
- package/dist/cli/chunks/chunk-HRD7LL7Q.js +0 -2
- package/dist/cli/chunks/chunk-QKTB5FZP.js +0 -2
- package/dist/cli/chunks/chunk-R4B2B6MZ.js +0 -5
- package/dist/cli/chunks/chunk-SI7AQK7I.js +0 -2
- package/dist/cli/chunks/chunk-TVASP2E6.js +0 -2
- package/dist/cli/chunks/chunk-VLZBQ3XN.js +0 -2
- package/dist/cli/chunks/chunk-Y2ONHWXI.js +0 -2
- package/dist/cli/chunks/chunk-YCTGWMCP.js +0 -12
- package/dist/cli/chunks/client-LMOHUGOA.js +0 -2
- package/dist/cli/chunks/cross-domain-router-IZB5ZMXO.js +0 -2
- package/dist/cli/chunks/daemon-YNF54UYB.js +0 -19
- package/dist/cli/chunks/dream-SAPSS25B.js +0 -2
- package/dist/cli/chunks/esm-node-FTBUMV4L.js +0 -2
- package/dist/cli/chunks/heartbeat-scheduler-HYVMXCXT.js +0 -2
- package/dist/cli/chunks/hnsw-adapter-CBDRZLXX.js +0 -2
- package/dist/cli/chunks/hnsw-index-EOJG4VF4.js +0 -2
- package/dist/cli/chunks/impact-analyzer-C2TXXYPC.js +0 -2
- package/dist/cli/chunks/init-wizard-IQV7SBMW.js +0 -2
- package/dist/cli/chunks/kernel-NJOPFGK7.js +0 -2
- package/dist/cli/chunks/knowledge-graph-EUMGCQPH.js +0 -2
- package/dist/cli/chunks/learning-Y4OZJFBV.js +0 -107
- package/dist/cli/chunks/load-test-LBYVVG35.js +0 -2
- package/dist/cli/chunks/memory-backend-NQMJKHCQ.js +0 -2
- package/dist/cli/chunks/protocol-executor-ZSWPG5SU.js +0 -2
- package/dist/cli/chunks/qe-reasoning-bank-4RLPRCGF.js +0 -2
- package/dist/cli/chunks/queen-coordinator-KQ673NYE.js +0 -2
- package/dist/cli/chunks/router-UBNV4H5S.js +0 -2
- package/dist/cli/chunks/routing-feedback-BMMGZ346.js +0 -2
- package/dist/cli/chunks/rvf-native-adapter-LXBCTTVF.js +0 -2
- package/dist/cli/chunks/safe-db-FFSPBUAK.js +0 -2
- package/dist/cli/chunks/schedule-2MOMNZ6B.js +0 -2
- package/dist/cli/chunks/scheduler-5VGVANFG.js +0 -2
- package/dist/cli/chunks/shared-rvf-adapter-6JWYF7WV.js +0 -2
- package/dist/cli/chunks/sqlite-persistence-LCOAORK7.js +0 -2
- package/dist/cli/chunks/unified-memory-CZCWZUFP.js +0 -2
- package/dist/cli/chunks/unified-memory-hnsw-QEOXVSOZ.js +0 -2
- package/dist/cli/chunks/unified-persistence-HGZAYZGP.js +0 -2
- package/dist/cli/chunks/visual-security-ITKF4E4Z.js +0 -2
- package/dist/cli/chunks/witness-chain-SYFYXQD3.js +0 -2
- package/dist/cli/chunks/workflow-orchestrator-GZS2O3KW.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.9.
|
|
2
|
-
import{a as ye}from"./chunk-Y2ONHWXI.js";import{c as oe,d as ce,e as fe}from"./chunk-HHRUXDLT.js";import{b as N,d as le}from"./chunk-VCJP7HQG.js";import{b as w,c as L}from"./chunk-QIE76ERL.js";import{a as j,b as D,c as V}from"./chunk-3AOWTHLS.js";ye();import{createRequire as be}from"module";var O;function W(){if(!O){let h=be(import.meta.url);try{O=h("typescript")}catch{try{O=h("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 p=new Proxy({},{get(h,e){return W()[e]},has(h,e){return e in W()},ownKeys(){return Object.keys(W())},getOwnPropertyDescriptor(h,e){let t=W()[e];if(t!==void 0)return{configurable:!0,enumerable:!0,value:t}}});var F=class{parseFile(e,t){return p.createSourceFile(e,t,p.ScriptTarget.Latest,!0,this.getScriptKind(e))}extractFunctions(e){let t=[],s=n=>{p.isFunctionDeclaration(n)&&n.name?t.push(this.extractFunctionDeclaration(n,e)):p.isVariableStatement(n)&&this.extractArrowFunctions(n,e,t),p.forEachChild(n,s)};return p.forEachChild(e,s),t}extractClasses(e){let t=[],s=n=>{p.isClassDeclaration(n)&&n.name&&t.push(this.extractClassDeclaration(n,e)),p.forEachChild(n,s)};return p.forEachChild(e,s),t}extractImports(e){let t=[],s=n=>{p.isImportDeclaration(n)&&t.push(this.extractImportDeclaration(n)),p.forEachChild(n,s)};return p.forEachChild(e,s),t}extractExports(e){let t=[],s=n=>{if(p.isExportDeclaration(n))this.extractExportDeclaration(n,t);else if(p.isExportAssignment(n))t.push({name:this.getExportAssignmentName(n),type:"unknown",isDefault:!0,isReexport:!1,sourceModule:void 0});else if(p.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(p.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(p.isVariableStatement(n)&&this.hasExportModifier(n))for(let r of n.declarationList.declarations)p.isIdentifier(r.name)&&t.push({name:r.name.text,type:"variable",isDefault:!1,isReexport:!1,sourceModule:void 0});else p.isInterfaceDeclaration(n)&&this.hasExportModifier(n)?t.push({name:n.name.text,type:"interface",isDefault:!1,isReexport:!1,sourceModule:void 0}):p.isTypeAliasDeclaration(n)&&this.hasExportModifier(n)?t.push({name:n.name.text,type:"type",isDefault:!1,isReexport:!1,sourceModule:void 0}):p.isEnumDeclaration(n)&&this.hasExportModifier(n)&&t.push({name:n.name.text,type:"enum",isDefault:!1,isReexport:!1,sourceModule:void 0});p.forEachChild(n,s)};return p.forEachChild(e,s),t}extractInterfaces(e){let t=[],s=n=>{p.isInterfaceDeclaration(n)&&t.push(this.extractInterfaceDeclaration(n,e)),p.forEachChild(n,s)};return p.forEachChild(e,s),t}extractEntities(e,t){let s=this.parseFile(t,e),n=[],r=this.extractFunctions(s);for(let a of r)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 i=this.extractInterfaces(s);for(let a of i)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")?p.ScriptKind.TSX:e.endsWith(".ts")?p.ScriptKind.TS:e.endsWith(".jsx")?p.ScriptKind.JSX:e.endsWith(".js")?p.ScriptKind.JS:p.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(p.isIdentifier(n.name)&&n.initializer&&p.isArrowFunction(n.initializer)){let r=n.initializer,{line:o}=t.getLineAndCharacterOfPosition(e.getStart()),{line:i}=t.getLineAndCharacterOfPosition(e.getEnd());s.push({name:n.name.text,parameters:this.extractParameters(r.parameters),returnType:r.type?r.type.getText(t):void 0,startLine:o+1,endLine:i+1,isAsync:this.hasAsyncModifier(r),isExported:this.hasExportModifier(e),isGenerator:!1,typeParameters:this.extractTypeParameters(r.typeParameters)})}}extractClassDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd()),r=[],o=[];for(let c of e.members)p.isMethodDeclaration(c)&&c.name?r.push(this.extractMethodDeclaration(c,t)):p.isPropertyDeclaration(c)&&c.name?o.push(this.extractPropertyDeclaration(c,t)):p.isConstructorDeclaration(c)&&(r.push(this.extractConstructor(c,t)),this.extractParameterProperties(c,o,t));let i,a=[];if(e.heritageClauses){for(let c of e.heritageClauses)if(c.token===p.SyntaxKind.ExtendsKeyword)i=c.types[0]?.expression.getText(t);else if(c.token===p.SyntaxKind.ImplementsKeyword)for(let l of c.types)a.push(l.expression.getText(t))}return{name:e.name?.text??"anonymous",methods:r,properties:o,extends:i,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:p.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===p.SyntaxKind.PublicKeyword||t.kind===p.SyntaxKind.PrivateKeyword||t.kind===p.SyntaxKind.ProtectedKeyword||t.kind===p.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,r,o=e.importClause?.isTypeOnly??!1;if(e.importClause&&(e.importClause.name&&(n=e.importClause.name.text),e.importClause.namedBindings)){if(p.isNamespaceImport(e.importClause.namedBindings))r=e.importClause.namedBindings.name.text;else if(p.isNamedImports(e.importClause.namedBindings))for(let i of e.importClause.namedBindings.elements)s.push({name:i.propertyName?.text??i.name.text,alias:i.propertyName?i.name.text:void 0})}return{module:t,namedImports:s,defaultImport:n,namespaceImport:r,isTypeOnly:o}}extractExportDeclaration(e,t){let s=e.moduleSpecifier?e.moduleSpecifier.text:void 0;if(e.exportClause&&p.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()),r=[],o=[];for(let a of e.members)p.isPropertySignature(a)&&a.name?r.push({name:this.getPropertyName(a.name,t),type:a.type?a.type.getText(t):void 0,isOptional:!!a.questionToken,isReadonly:this.hasReadonlyModifier(a)}):p.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 i=[];if(e.heritageClauses){for(let a of e.heritageClauses)if(a.token===p.SyntaxKind.ExtendsKeyword)for(let c of a.types)i.push(c.expression.getText(t))}return{name:e.name.text,properties:r,methods:o,extends:i,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:p.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 p.isIdentifier(e)||p.isStringLiteral(e)||p.isNumericLiteral(e)?e.text:e.getText(t)}getExportAssignmentName(e){return p.isIdentifier(e.expression)?e.expression.text:"default"}hasExportModifier(e){return p.canHaveModifiers(e)&&!!p.getModifiers(e)?.some(t=>t.kind===p.SyntaxKind.ExportKeyword)}hasDefaultModifier(e){return p.canHaveModifiers(e)&&!!p.getModifiers(e)?.some(t=>t.kind===p.SyntaxKind.DefaultKeyword)}hasAsyncModifier(e){return p.canHaveModifiers(e)&&!!p.getModifiers(e)?.some(t=>t.kind===p.SyntaxKind.AsyncKeyword)}hasStaticModifier(e){return p.canHaveModifiers(e)&&!!p.getModifiers(e)?.some(t=>t.kind===p.SyntaxKind.StaticKeyword)}hasAbstractModifier(e){return p.canHaveModifiers(e)&&!!p.getModifiers(e)?.some(t=>t.kind===p.SyntaxKind.AbstractKeyword)}hasReadonlyModifier(e){return p.canHaveModifiers(e)&&!!p.getModifiers(e)?.some(t=>t.kind===p.SyntaxKind.ReadonlyKeyword)}getVisibility(e){if(!p.canHaveModifiers(e))return"public";let t=p.getModifiers(e);return t?t.some(s=>s.kind===p.SyntaxKind.PrivateKeyword)?"private":t.some(s=>s.kind===p.SyntaxKind.ProtectedKeyword)?"protected":"public":"public"}},Me=new F,q=class{language="typescript";supportedExtensions=[".ts",".tsx",".js",".jsx",".mjs",".cjs"];parser=new F;async parseFile(e,t){let s=this.parser.parseFile(t,e),n=this.parser.extractFunctions(s),r=this.parser.extractClasses(s),o=this.parser.extractImports(s);return{functions:n.map(i=>this.mapFunction(i)),classes:r.map(i=>this.mapClass(i)),imports:o.map(i=>this.mapImport(i)),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}}},Se=new q;fe();var E=1e3;function I(h){let e=h.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.9.14");process.exit(0)}
|
|
2
|
+
import{a as ye}from"./chunk-STYNOKOM.js";import{c as oe,d as ce,e as fe}from"./chunk-GUEK5DOK.js";import{b as N,d as le}from"./chunk-DMZ2XOEW.js";import{b as w,c as L}from"./chunk-PZF5ISGS.js";import{a as j,b as D,c as V}from"./chunk-UIYK4Y7K.js";ye();import{createRequire as be}from"module";var O;function W(){if(!O){let h=be(import.meta.url);try{O=h("typescript")}catch{try{O=h("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 p=new Proxy({},{get(h,e){return W()[e]},has(h,e){return e in W()},ownKeys(){return Object.keys(W())},getOwnPropertyDescriptor(h,e){let t=W()[e];if(t!==void 0)return{configurable:!0,enumerable:!0,value:t}}});var F=class{parseFile(e,t){return p.createSourceFile(e,t,p.ScriptTarget.Latest,!0,this.getScriptKind(e))}extractFunctions(e){let t=[],s=n=>{p.isFunctionDeclaration(n)&&n.name?t.push(this.extractFunctionDeclaration(n,e)):p.isVariableStatement(n)&&this.extractArrowFunctions(n,e,t),p.forEachChild(n,s)};return p.forEachChild(e,s),t}extractClasses(e){let t=[],s=n=>{p.isClassDeclaration(n)&&n.name&&t.push(this.extractClassDeclaration(n,e)),p.forEachChild(n,s)};return p.forEachChild(e,s),t}extractImports(e){let t=[],s=n=>{p.isImportDeclaration(n)&&t.push(this.extractImportDeclaration(n)),p.forEachChild(n,s)};return p.forEachChild(e,s),t}extractExports(e){let t=[],s=n=>{if(p.isExportDeclaration(n))this.extractExportDeclaration(n,t);else if(p.isExportAssignment(n))t.push({name:this.getExportAssignmentName(n),type:"unknown",isDefault:!0,isReexport:!1,sourceModule:void 0});else if(p.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(p.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(p.isVariableStatement(n)&&this.hasExportModifier(n))for(let r of n.declarationList.declarations)p.isIdentifier(r.name)&&t.push({name:r.name.text,type:"variable",isDefault:!1,isReexport:!1,sourceModule:void 0});else p.isInterfaceDeclaration(n)&&this.hasExportModifier(n)?t.push({name:n.name.text,type:"interface",isDefault:!1,isReexport:!1,sourceModule:void 0}):p.isTypeAliasDeclaration(n)&&this.hasExportModifier(n)?t.push({name:n.name.text,type:"type",isDefault:!1,isReexport:!1,sourceModule:void 0}):p.isEnumDeclaration(n)&&this.hasExportModifier(n)&&t.push({name:n.name.text,type:"enum",isDefault:!1,isReexport:!1,sourceModule:void 0});p.forEachChild(n,s)};return p.forEachChild(e,s),t}extractInterfaces(e){let t=[],s=n=>{p.isInterfaceDeclaration(n)&&t.push(this.extractInterfaceDeclaration(n,e)),p.forEachChild(n,s)};return p.forEachChild(e,s),t}extractEntities(e,t){let s=this.parseFile(t,e),n=[],r=this.extractFunctions(s);for(let a of r)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 i=this.extractInterfaces(s);for(let a of i)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")?p.ScriptKind.TSX:e.endsWith(".ts")?p.ScriptKind.TS:e.endsWith(".jsx")?p.ScriptKind.JSX:e.endsWith(".js")?p.ScriptKind.JS:p.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(p.isIdentifier(n.name)&&n.initializer&&p.isArrowFunction(n.initializer)){let r=n.initializer,{line:o}=t.getLineAndCharacterOfPosition(e.getStart()),{line:i}=t.getLineAndCharacterOfPosition(e.getEnd());s.push({name:n.name.text,parameters:this.extractParameters(r.parameters),returnType:r.type?r.type.getText(t):void 0,startLine:o+1,endLine:i+1,isAsync:this.hasAsyncModifier(r),isExported:this.hasExportModifier(e),isGenerator:!1,typeParameters:this.extractTypeParameters(r.typeParameters)})}}extractClassDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd()),r=[],o=[];for(let c of e.members)p.isMethodDeclaration(c)&&c.name?r.push(this.extractMethodDeclaration(c,t)):p.isPropertyDeclaration(c)&&c.name?o.push(this.extractPropertyDeclaration(c,t)):p.isConstructorDeclaration(c)&&(r.push(this.extractConstructor(c,t)),this.extractParameterProperties(c,o,t));let i,a=[];if(e.heritageClauses){for(let c of e.heritageClauses)if(c.token===p.SyntaxKind.ExtendsKeyword)i=c.types[0]?.expression.getText(t);else if(c.token===p.SyntaxKind.ImplementsKeyword)for(let l of c.types)a.push(l.expression.getText(t))}return{name:e.name?.text??"anonymous",methods:r,properties:o,extends:i,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:p.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===p.SyntaxKind.PublicKeyword||t.kind===p.SyntaxKind.PrivateKeyword||t.kind===p.SyntaxKind.ProtectedKeyword||t.kind===p.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,r,o=e.importClause?.isTypeOnly??!1;if(e.importClause&&(e.importClause.name&&(n=e.importClause.name.text),e.importClause.namedBindings)){if(p.isNamespaceImport(e.importClause.namedBindings))r=e.importClause.namedBindings.name.text;else if(p.isNamedImports(e.importClause.namedBindings))for(let i of e.importClause.namedBindings.elements)s.push({name:i.propertyName?.text??i.name.text,alias:i.propertyName?i.name.text:void 0})}return{module:t,namedImports:s,defaultImport:n,namespaceImport:r,isTypeOnly:o}}extractExportDeclaration(e,t){let s=e.moduleSpecifier?e.moduleSpecifier.text:void 0;if(e.exportClause&&p.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()),r=[],o=[];for(let a of e.members)p.isPropertySignature(a)&&a.name?r.push({name:this.getPropertyName(a.name,t),type:a.type?a.type.getText(t):void 0,isOptional:!!a.questionToken,isReadonly:this.hasReadonlyModifier(a)}):p.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 i=[];if(e.heritageClauses){for(let a of e.heritageClauses)if(a.token===p.SyntaxKind.ExtendsKeyword)for(let c of a.types)i.push(c.expression.getText(t))}return{name:e.name.text,properties:r,methods:o,extends:i,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:p.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 p.isIdentifier(e)||p.isStringLiteral(e)||p.isNumericLiteral(e)?e.text:e.getText(t)}getExportAssignmentName(e){return p.isIdentifier(e.expression)?e.expression.text:"default"}hasExportModifier(e){return p.canHaveModifiers(e)&&!!p.getModifiers(e)?.some(t=>t.kind===p.SyntaxKind.ExportKeyword)}hasDefaultModifier(e){return p.canHaveModifiers(e)&&!!p.getModifiers(e)?.some(t=>t.kind===p.SyntaxKind.DefaultKeyword)}hasAsyncModifier(e){return p.canHaveModifiers(e)&&!!p.getModifiers(e)?.some(t=>t.kind===p.SyntaxKind.AsyncKeyword)}hasStaticModifier(e){return p.canHaveModifiers(e)&&!!p.getModifiers(e)?.some(t=>t.kind===p.SyntaxKind.StaticKeyword)}hasAbstractModifier(e){return p.canHaveModifiers(e)&&!!p.getModifiers(e)?.some(t=>t.kind===p.SyntaxKind.AbstractKeyword)}hasReadonlyModifier(e){return p.canHaveModifiers(e)&&!!p.getModifiers(e)?.some(t=>t.kind===p.SyntaxKind.ReadonlyKeyword)}getVisibility(e){if(!p.canHaveModifiers(e))return"public";let t=p.getModifiers(e);return t?t.some(s=>s.kind===p.SyntaxKind.PrivateKeyword)?"private":t.some(s=>s.kind===p.SyntaxKind.ProtectedKeyword)?"protected":"public":"public"}},Me=new F,q=class{language="typescript";supportedExtensions=[".ts",".tsx",".js",".jsx",".mjs",".cjs"];parser=new F;async parseFile(e,t){let s=this.parser.parseFile(t,e),n=this.parser.extractFunctions(s),r=this.parser.extractClasses(s),o=this.parser.extractImports(s);return{functions:n.map(i=>this.mapFunction(i)),classes:r.map(i=>this.mapClass(i)),imports:o.map(i=>this.mapImport(i)),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}}},Se=new q;fe();var E=1e3;function I(h){let e=h.split(`
|
|
3
3
|
`),t=[],s=[],n="",r=0,o=0,i=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||(r=c+1),n=n?n+" "+d:l;for(let u of d)u==="("?o++:u===")"?o=Math.max(0,o-1):u==="<"?i++:u===">"?i=Math.max(0,i-1):u==="["?a++:u==="]"&&(a=Math.max(0,a-1));o===0&&i===0&&a===0&&(t.push(n),s.push(r),n="")}return n&&(t.push(n),s.push(r)),{logicalLines:t,lineMap:s}}function G(h,e,t="<",s=">"){if(h[e]!==t)return;let n=1,r=e+1;for(;r<h.length&&n>0;)h[r]===t?n++:h[r]===s&&n--,r++;if(n===0)return h.substring(e+1,r-1)}function R(h,e,t){let s=[];for(let n=e-1;n>=0;n--){let r=h[n].trim();if(r.startsWith(t))s.unshift(r);else{if(r===""||r.startsWith("//")||r.startsWith("*")||r.startsWith("#"))continue;break}}return s}function S(h){let e=[],t=0,s="";for(let n of h)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 re(h){let e=0,t=!1,s="";for(let n=0;n<h.length;n++){let r=h[n];if(t){r===s&&h[n-1]!=="\\"&&(t=!1);continue}r==='"'||r==="'"||r==="`"?(t=!0,s=r):r==="{"?e++:r==="}"&&e--}return e}var H=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:r}=I(e),o=/^(\s*)(async\s+)?def\s+(\w+)\s*\(([^)]*)\)(?:\s*->\s*([^:]*\S))?\s*:/;for(let i=0;i<n.length;i++){if(n[i].length>E)continue;let a=n[i].match(o);if(a){let c=a[1].length,l=!!a[2],d=a[3],u=a[4],m=a[5]?.trim(),g=r[i]-1,f=g+1;for(let y=g+1;y<s.length;y++){let b=s[y];if(b.trim()===""||b.trim().startsWith("#"))continue;if((b.match(/^(\s*)/)?.[1].length??0)<=c&&b.trim()!==""){f=y;break}f=y+1}let x=R(s,g,"@");t.push({name:d,parameters:this.parseParams(u),returnType:m,isAsync:l,isPublic:!d.startsWith("_"),complexity:1,decorators:x,genericParams:[],startLine:r[i],endLine:f})}}return t}extractClasses(e){let t=[],s=e.split(`
|
|
5
5
|
`),{logicalLines:n,lineMap:r}=I(e),o=/^(\s*)class\s+(\w+)(?:\(([^)]*)\))?\s*:/;for(let i=0;i<n.length;i++){let a=n[i].match(o);if(a){let c=a[1].length,l=a[2],d=a[3]?a[3].split(",").map(y=>y.trim()):[],u=r[i]-1,m=u+1;for(let y=u+1;y<s.length;y++){let b=s[y];if(b.trim()===""||b.trim().startsWith("#"))continue;if((b.match(/^(\s*)/)?.[1].length??0)<=c&&b.trim()!==""){m=y;break}m=y+1}let g=s.slice(u+1,m).join(`
|
|
@@ -20,7 +20,7 @@ import{a as ye}from"./chunk-Y2ONHWXI.js";import{c as oe,d as ce,e as fe}from"./c
|
|
|
20
20
|
`),{logicalLines:n,lineMap:r}=I(e),o=/^\s*(public|private|protected|internal)?\s*(suspend)?\s*fun\s+(?:<[^{]*> +)?(\w+)\s*\(([^)]*)\)(?:\s*:\s*([^{=\s]+(?:\s+[^{=\s]+)*))?\s*/,i=0;for(let a=0;a<n.length;a++){let c=n[a];if(c.length>E){i+=(c.match(/\{/g)?.length??0)-(c.match(/\}/g)?.length??0);continue}let l=c.match(o);if(l&&i<=1){let d=l[1]||"public",u=!!l[2],m=l[3],g=l[4],f=l[5]?.trim();if(f&&f.includes("<")){let b=f.indexOf("<"),P=G(f,b);P!==void 0&&(f=f.substring(0,b)+"<"+P+">")}let x=r[a]-1,y=R(s,x,"@");t.push({name:m,parameters:this.parseParams(g),returnType:f,isAsync:u,isPublic:d==="public",complexity:1,decorators:y,genericParams:[],startLine:r[a],endLine:r[a]})}i+=re(c),i<0&&(i=0)}return t}extractClasses(e){let t=[],s=e.split(`
|
|
21
21
|
`),{logicalLines:n,lineMap:r}=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 i=0;i<n.length;i++){if(n[i].length>E)continue;let a=n[i].match(o);if(a){let c=a[3],l=a[4]?a[4].split(",").map(m=>m.trim().split("(")[0].trim()):[],d=r[i]-1,u=R(s,d,"@");t.push({name:c,methods:[],properties:[],isPublic:(a[1]||"public")==="public",implements:l.slice(1),extends:l[0]||void 0,decorators:u,startLine:r[i],endLine:r[i]})}}return t}extractImports(e){let t=[],s=e.split(`
|
|
22
22
|
`);for(let n of s){let r=n.match(/^\s*import\s+([^\s]+)/);r&&t.push({module:r[1],namedImports:[],isTypeOnly:!1})}return t}parseParams(e){return e.trim()?S(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(),r=t.substring(s+1).trim(),o=r.indexOf("="),i=o>=0?r.substring(0,o).trim():r,a=o>=0;return{name:n,type:i,isOptional:a||i?.endsWith("?")||!1,defaultValue:void 0}}):[]}},te=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),r=/^\s*([\w<>,.?]+(?:\s+[\w<>,.?]+)*)\s+(\w+)\s*\(([^)]*)\)(?:\s*(async))?\s*\{/;for(let o=0;o<s.length;o++){let i=s[o];if(i.includes(" class ")||i.length>E)continue;let a=i.match(r);if(a){let c=a[1].trim(),l=c;if(c&&c.includes("<")){let g=c.indexOf("<"),f=G(c,g);f!==void 0&&(l=c.substring(0,g)+"<"+f+">")}let d=a[2],u=a[3],m=!!a[4]||l.includes("Future");t.push({name:d,parameters:this.parseParams(u),returnType:l==="void"?void 0:l,isAsync:m,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),r=/^\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 i=s[o].match(r);if(i){let a=i[2],c=i[3],l=i[4]?i[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 r=n.match(/^\s*import\s+'([^']+)'/);r&&t.push({module:r[1],namedImports:[],isTypeOnly:!1})}return t}parseParams(e){if(!e.trim())return[];let t=e.replace(/[{}[\]]/g,"");return S(t).map(s=>s.trim()).filter(s=>s).map(s=>{let n=s.replace("required ","").trim().split(/\s+/),r=n[n.length-1]||"",o=n.slice(0,-1).join(" ")||void 0;return{name:r,type:o,isOptional:s.includes("?")||s.includes("{"),defaultValue:void 0}})}},$=ce("ParserRegistry"),de=["python","java","csharp","rust","swift"],se=class h{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<h.MAX_WASM_RETRIES)try{return await this.wasmParser.parseFile(e,t)}catch(s){this.wasmFailCount++;let n=s instanceof Error?s.message:String(s),r=this.wasmFailCount>=h.MAX_WASM_RETRIES;$.warn(`[${this.language}] tree-sitter WASM parser failed (attempt ${this.wasmFailCount}/${h.MAX_WASM_RETRIES}): ${n}. Falling back to regex parser (~97-98% accuracy). `+(r?"Set AQE_PARSER_REGEX_ONLY=1 to silence this warning.":"Will retry WASM on next parse."))}return this.regexParser.parseFile(e,t)}},ne=class{parsers=new Map;_wasmInitPromise=null;constructor(){this.register(new H),this.register(new J),this.register(new Q),this.register(new X),this.register(new Y),this.register(new Z),this.register(new ee),this.register(new te),this._wasmInitPromise=this._tryLoadWasmParsers()}async _tryLoadWasmParsers(){try{let e=await import("./tree-sitter-wasm-parser-MELABICK.js");if(!e.isWasmAvailable()){$.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 de){let n=t.get(s),r=this.parsers.get(s);n&&r&&this.parsers.set(s,new se(n,r))}$.info("tree-sitter WASM parsers available for: "+de.join(", "))}catch{$.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)}},De=new ne;import*as M from"node:fs/promises";import*as C from"node:path";var xe=[/\.\./,/%2e%2e/i,/%252e%252e/i,/\.\.%2f/i,/%2f\.\./i,/\.\.%5c/i,/\.\.\\/,/%c0%ae/i,/%c0%2f/i,/%c1%9c/i,/\0/,/%00/i],ve=[/^\/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],ie=class{name="path-traversal";getRiskLevel(){return"critical"}validate(e,t={}){let{basePath:s="",allowAbsolute:n=!1,allowedExtensions:r=[],deniedExtensions:o=[".exe",".bat",".cmd",".sh",".ps1",".dll",".so"],maxDepth:i=10,maxLength:a=4096}=t;if(e.length>a)return{valid:!1,error:`Path exceeds maximum length of ${a}`,riskLevel:"medium"};for(let g of xe)if(g.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 g of ve)if(g.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>i)return{valid:!1,error:`Path depth exceeds maximum of ${i}`,riskLevel:"low"};let d=this.getExtension(c);if(d){let g=`.${d.toLowerCase()}`,f=d.toLowerCase();if(o.length>0&&o.some(y=>y.toLowerCase()===g||y.toLowerCase()===f))return{valid:!1,error:`File extension '${d}' is not allowed`,riskLevel:"high"};if(r.length>0&&!r.some(y=>y.toLowerCase()===g||y.toLowerCase()===f))return{valid:!1,error:`File extension '${d}' is not in allowed list`,riskLevel:"medium"}}let u=s?this.joinPathsAbsolute(s,c):c,m=s.startsWith("/")?`/${this.normalizePath(s)}`:this.normalizePath(s);return s&&!u.startsWith(m)?{valid:!1,error:"Path escapes base directory",riskLevel:"critical"}:{valid:!0,normalizedPath:u,riskLevel:"none"}}normalizePath(e){let t=e.replace(/\\/g,"/");t=t.replace(/\/+/g,"/");let s=t.split("/"),n=[];for(let r of s)r==="."||r===""||(r===".."?n.length>0&&n[n.length-1]!==".."&&n.pop():n.push(r));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}},Ee=new ie,pe=(h,e)=>Ee.validate(h,e);le();var A=class extends Error{constructor(t,s,n,r){super(t);this.filePath=s;this.code=n;this.cause=r;this.name="FileReadError"}},z=class extends Error{constructor(t,s,n){super(t);this.filePath=s;this.cause=n;this.name="JsonParseError"}},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"}},ae=class{constructor(e,t){this.maxSize=e;this.ttlMs=t}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,r)=>{e-n.timestamp>this.ttlMs&&s.push(r)}),s.forEach(n=>{this.delete(n),t++}),t}};function Ie(h){let e="",t=0;for(;t<h.length;){let s=h[t],n=h[t+1];s==="*"&&n==="*"?h[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 ue(h,e,t,s){try{let n=await M.readdir(h,{withFileTypes:!0});for(let r of n){let o=C.join(h,r.name),i=C.relative(s,o);if(r.isDirectory())r.name!=="node_modules"&&!r.name.startsWith(".")&&await ue(o,e,t,s);else if(r.isFile()){let a=i.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 ae(e.maxCacheSize??100,e.cacheTtlMs??300*1e3)}resolvePath(e){let t=C.isAbsolute(e),s=pe(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=C.resolve(this.basePath),r=C.resolve(e);if(!r.startsWith(n))throw new T(e,["Path escapes base directory"],"critical");return r}return s.normalizedPath?s.normalizedPath:t?e:C.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(),w(s);this.stats.cacheMisses++}try{let s=await M.readFile(t,"utf-8");return this.enableCache&&(this.cache.set(t,s,Buffer.byteLength(s,"utf-8")),this.updateCacheStats()),w(s)}catch(s){let n=s,r;switch(n.code){case"ENOENT":r="File not found: "+t;break;case"EACCES":r="Permission denied: "+t;break;case"EISDIR":r="Path is a directory: "+t;break;default:r="Failed to read file: "+t}return L(new A(r,t,n.code,n))}}async readJSON(e){let t=await this.readFile(e);if(!t.success)return t;try{let s=N(t.value);return w(s)}catch(s){let n=s,r=e;try{r=this.resolvePath(e)}catch{}return L(new z("Invalid JSON in file: "+r+" - "+n.message,r,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 M.access(t,M.constants.F_OK),w(!0)}catch(s){let n=s;return n.code==="ENOENT"?w(!1):L(new A("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 M.stat(s)).isDirectory())return L(new A("Base path is not a directory: "+s,s,"ENOTDIR"));let r=Ie(e),o=[];return await ue(s,r,o,s),o.sort(),w(o)}catch(n){let r=n;return L(new A("Failed to list files in: "+s,s,r.code,r))}}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}};V();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 K=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 r=await this.fetchWithTimeout(`${this.baseUrl}/api/embeddings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)},this.timeoutMs);if(!r.ok){let i=await r.text();throw new Error(`Ollama API error (${r.status}): ${i}`)}let o=await r.json();if(o.embedding.length!==v.DIMENSIONS)throw new Error(`Invalid embedding dimensions: expected ${v.DIMENSIONS}, got ${o.embedding.length}`);return o.embedding}catch(r){if(s=D(r),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,r=setTimeout(()=>n.abort(),s);try{return await fetch(e,{...t,signal:n.signal})}finally{clearTimeout(r)}}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 Pe}from"crypto";var U=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 Pe("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 r={embedding:s,timestamp:Date.now(),model:t};this.cache.set(n,r)}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[r,o]of this.cache.entries())o.timestamp<s&&(this.cache.delete(r),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)}};V();var _=class{client;cache;batchSize;enableFallback;ollamaAvailable=null;constructor(e={}){this.client=new K(e.ollamaBaseUrl),this.cache=e.cache??new U(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,r=e.content.trim();if(s.length+r.length>n){let o=n-s.length-3;r=r.substring(0,o)+"..."}return s+r}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=[],r=0,o=0,i=await this.isOllamaAvailable();if(i)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,i);n.push(...d);for(let u of d)u.cached?r++:o++;if(t){let u=c+l.length,m=e.length,f=(Date.now()-s)/u,y=(m-u)*f;t({current:u,total:m,percentage:u/m*100,estimatedTimeRemainingMs:y})}}let a=Date.now()-s;return{results:n,stats:{totalChunks:e.length,cachedHits:r,computedNew:o,totalTimeMs:a,avgTimePerChunk:a/e.length}}}async processBatch(e,t){let s=[],n=e.map(async o=>{let i=this.formatForEmbedding(o),a=Date.now(),c=this.cache.get(i,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(i):l=this.generatePseudoEmbedding(i),this.cache.set(i,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}: ${j(l)}`)}}),r=await Promise.all(n);return s.push(...r),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 i=s[o];for(let a=0;a<i.length&&a<t.length;a++)t[(o+a)%t.length]+=i.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,i]of n)o.test(e)&&(t[i]+=.5);let r=Math.sqrt(t.reduce((o,i)=>o+i*i,0))||1;return t.map(o=>o/r)}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}}};V();le();var we={maxNodes:1e5,maxEdgesPerNode:500,namespace:"code-intelligence:kg",enableVectorEmbeddings:!0,embeddingDimension:384,enableLLMExtraction:!0,llmModelTier:2,llmMaxTokens:2048},me=oe.create("code-intelligence/knowledge-graph"),he=class{config;memory;nodeCache=new Map;edgeIndex=new Map;tsParser;fileReader;embedder;llmRouter;constructor(e,t={}){this.config={...we,...t},this.isKnowledgeGraphDependencies(e)?(this.memory=e.memory,this.llmRouter=e.llmRouter):(this.memory=e,this.llmRouter=void 0),this.tsParser=new F,this.fileReader=new k,this.embedder=new _({enableFallback:!0})}isKnowledgeGraphDependencies(e){return e.memory!==void 0}async index(e){let t=Date.now(),s=[],n=0,r=0;try{let{paths:o,incremental:i=!1,includeTests:a=!0,languages:c}=e;i||await this.clear();for(let d of o)try{if(c&&c.length>0){let m=this.getFileExtension(d);if(!this.matchesLanguage(m,c))continue}if(!a&&this.isTestFile(d))continue;let u=await this.indexFile(d);n+=u.nodes,r+=u.edges}catch(u){s.push({file:d,error:j(u)})}let l=Date.now()-t;return await this.storeIndexMetadata({filesIndexed:o.length-s.length,nodesCreated:n,edgesCreated:r,duration:l,indexedAt:new Date().toISOString()}),w({filesIndexed:o.length-s.length,nodesCreated:n,edgesCreated:r,duration:l,errors:s})}catch(o){return L(D(o))}}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(D(t))}}async mapDependencies(e){try{let{files:t,direction:s,depth:n=3}=e,r=[],o=[],i=new Set,a=[];for(let l of t)await this.traverseDependencies(l,s,n,i,r,o,[],a);let c=this.calculateDependencyMetrics(r,o);return w({nodes:r,edges:o,cycles:a,metrics:c})}catch(t){return L(D(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);return s&&this.nodeCache.set(e,s),s}async getEdges(e,t){let s=[],n=this.edgeIndex.get(e);if(n)return this.filterEdgesByDirection(n,e,t);let r=`${this.config.namespace}:edge:*`,o=await this.memory.search(r,this.config.maxEdgesPerNode*2);for(let i of o){let a=await this.memory.get(i);a&&(t!=="outgoing"&&a.target===e||t!=="incoming"&&a.source===e)&&s.push(a)}return s}async clear(){this.nodeCache.clear(),this.edgeIndex.clear()}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),r=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 r=n.match(/^\s*import\s+'([^']+)'/);r&&t.push({module:r[1],namedImports:[],isTypeOnly:!1})}return t}parseParams(e){if(!e.trim())return[];let t=e.replace(/[{}[\]]/g,"");return S(t).map(s=>s.trim()).filter(s=>s).map(s=>{let n=s.replace("required ","").trim().split(/\s+/),r=n[n.length-1]||"",o=n.slice(0,-1).join(" ")||void 0;return{name:r,type:o,isOptional:s.includes("?")||s.includes("{"),defaultValue:void 0}})}},$=ce("ParserRegistry"),de=["python","java","csharp","rust","swift"],se=class h{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<h.MAX_WASM_RETRIES)try{return await this.wasmParser.parseFile(e,t)}catch(s){this.wasmFailCount++;let n=s instanceof Error?s.message:String(s),r=this.wasmFailCount>=h.MAX_WASM_RETRIES;$.warn(`[${this.language}] tree-sitter WASM parser failed (attempt ${this.wasmFailCount}/${h.MAX_WASM_RETRIES}): ${n}. Falling back to regex parser (~97-98% accuracy). `+(r?"Set AQE_PARSER_REGEX_ONLY=1 to silence this warning.":"Will retry WASM on next parse."))}return this.regexParser.parseFile(e,t)}},ne=class{parsers=new Map;_wasmInitPromise=null;constructor(){this.register(new H),this.register(new J),this.register(new Q),this.register(new X),this.register(new Y),this.register(new Z),this.register(new ee),this.register(new te),this._wasmInitPromise=this._tryLoadWasmParsers()}async _tryLoadWasmParsers(){try{let e=await import("./tree-sitter-wasm-parser-IYKLBTXB.js");if(!e.isWasmAvailable()){$.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 de){let n=t.get(s),r=this.parsers.get(s);n&&r&&this.parsers.set(s,new se(n,r))}$.info("tree-sitter WASM parsers available for: "+de.join(", "))}catch{$.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)}},De=new ne;import*as M from"node:fs/promises";import*as C from"node:path";var xe=[/\.\./,/%2e%2e/i,/%252e%252e/i,/\.\.%2f/i,/%2f\.\./i,/\.\.%5c/i,/\.\.\\/,/%c0%ae/i,/%c0%2f/i,/%c1%9c/i,/\0/,/%00/i],ve=[/^\/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],ie=class{name="path-traversal";getRiskLevel(){return"critical"}validate(e,t={}){let{basePath:s="",allowAbsolute:n=!1,allowedExtensions:r=[],deniedExtensions:o=[".exe",".bat",".cmd",".sh",".ps1",".dll",".so"],maxDepth:i=10,maxLength:a=4096}=t;if(e.length>a)return{valid:!1,error:`Path exceeds maximum length of ${a}`,riskLevel:"medium"};for(let g of xe)if(g.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 g of ve)if(g.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>i)return{valid:!1,error:`Path depth exceeds maximum of ${i}`,riskLevel:"low"};let d=this.getExtension(c);if(d){let g=`.${d.toLowerCase()}`,f=d.toLowerCase();if(o.length>0&&o.some(y=>y.toLowerCase()===g||y.toLowerCase()===f))return{valid:!1,error:`File extension '${d}' is not allowed`,riskLevel:"high"};if(r.length>0&&!r.some(y=>y.toLowerCase()===g||y.toLowerCase()===f))return{valid:!1,error:`File extension '${d}' is not in allowed list`,riskLevel:"medium"}}let u=s?this.joinPathsAbsolute(s,c):c,m=s.startsWith("/")?`/${this.normalizePath(s)}`:this.normalizePath(s);return s&&!u.startsWith(m)?{valid:!1,error:"Path escapes base directory",riskLevel:"critical"}:{valid:!0,normalizedPath:u,riskLevel:"none"}}normalizePath(e){let t=e.replace(/\\/g,"/");t=t.replace(/\/+/g,"/");let s=t.split("/"),n=[];for(let r of s)r==="."||r===""||(r===".."?n.length>0&&n[n.length-1]!==".."&&n.pop():n.push(r));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}},Ee=new ie,pe=(h,e)=>Ee.validate(h,e);le();var A=class extends Error{constructor(t,s,n,r){super(t);this.filePath=s;this.code=n;this.cause=r;this.name="FileReadError"}filePath;code;cause},z=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},ae=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,r)=>{e-n.timestamp>this.ttlMs&&s.push(r)}),s.forEach(n=>{this.delete(n),t++}),t}};function Ie(h){let e="",t=0;for(;t<h.length;){let s=h[t],n=h[t+1];s==="*"&&n==="*"?h[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 ue(h,e,t,s){try{let n=await M.readdir(h,{withFileTypes:!0});for(let r of n){let o=C.join(h,r.name),i=C.relative(s,o);if(r.isDirectory())r.name!=="node_modules"&&!r.name.startsWith(".")&&await ue(o,e,t,s);else if(r.isFile()){let a=i.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 ae(e.maxCacheSize??100,e.cacheTtlMs??300*1e3)}resolvePath(e){let t=C.isAbsolute(e),s=pe(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=C.resolve(this.basePath),r=C.resolve(e);if(!r.startsWith(n))throw new T(e,["Path escapes base directory"],"critical");return r}return s.normalizedPath?s.normalizedPath:t?e:C.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(),w(s);this.stats.cacheMisses++}try{let s=await M.readFile(t,"utf-8");return this.enableCache&&(this.cache.set(t,s,Buffer.byteLength(s,"utf-8")),this.updateCacheStats()),w(s)}catch(s){let n=s,r;switch(n.code){case"ENOENT":r="File not found: "+t;break;case"EACCES":r="Permission denied: "+t;break;case"EISDIR":r="Path is a directory: "+t;break;default:r="Failed to read file: "+t}return L(new A(r,t,n.code,n))}}async readJSON(e){let t=await this.readFile(e);if(!t.success)return t;try{let s=N(t.value);return w(s)}catch(s){let n=s,r=e;try{r=this.resolvePath(e)}catch{}return L(new z("Invalid JSON in file: "+r+" - "+n.message,r,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 M.access(t,M.constants.F_OK),w(!0)}catch(s){let n=s;return n.code==="ENOENT"?w(!1):L(new A("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 M.stat(s)).isDirectory())return L(new A("Base path is not a directory: "+s,s,"ENOTDIR"));let r=Ie(e),o=[];return await ue(s,r,o,s),o.sort(),w(o)}catch(n){let r=n;return L(new A("Failed to list files in: "+s,s,r.code,r))}}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}};V();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 K=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 r=await this.fetchWithTimeout(`${this.baseUrl}/api/embeddings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)},this.timeoutMs);if(!r.ok){let i=await r.text();throw new Error(`Ollama API error (${r.status}): ${i}`)}let o=await r.json();if(o.embedding.length!==v.DIMENSIONS)throw new Error(`Invalid embedding dimensions: expected ${v.DIMENSIONS}, got ${o.embedding.length}`);return o.embedding}catch(r){if(s=D(r),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,r=setTimeout(()=>n.abort(),s);try{return await fetch(e,{...t,signal:n.signal})}finally{clearTimeout(r)}}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 Pe}from"crypto";var U=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 Pe("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 r={embedding:s,timestamp:Date.now(),model:t};this.cache.set(n,r)}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[r,o]of this.cache.entries())o.timestamp<s&&(this.cache.delete(r),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)}};V();var _=class{client;cache;batchSize;enableFallback;ollamaAvailable=null;constructor(e={}){this.client=new K(e.ollamaBaseUrl),this.cache=e.cache??new U(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,r=e.content.trim();if(s.length+r.length>n){let o=n-s.length-3;r=r.substring(0,o)+"..."}return s+r}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=[],r=0,o=0,i=await this.isOllamaAvailable();if(i)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,i);n.push(...d);for(let u of d)u.cached?r++:o++;if(t){let u=c+l.length,m=e.length,f=(Date.now()-s)/u,y=(m-u)*f;t({current:u,total:m,percentage:u/m*100,estimatedTimeRemainingMs:y})}}let a=Date.now()-s;return{results:n,stats:{totalChunks:e.length,cachedHits:r,computedNew:o,totalTimeMs:a,avgTimePerChunk:a/e.length}}}async processBatch(e,t){let s=[],n=e.map(async o=>{let i=this.formatForEmbedding(o),a=Date.now(),c=this.cache.get(i,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(i):l=this.generatePseudoEmbedding(i),this.cache.set(i,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}: ${j(l)}`)}}),r=await Promise.all(n);return s.push(...r),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 i=s[o];for(let a=0;a<i.length&&a<t.length;a++)t[(o+a)%t.length]+=i.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,i]of n)o.test(e)&&(t[i]+=.5);let r=Math.sqrt(t.reduce((o,i)=>o+i*i,0))||1;return t.map(o=>o/r)}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}}};V();le();var we={maxNodes:1e5,maxEdgesPerNode:500,namespace:"code-intelligence:kg",enableVectorEmbeddings:!0,embeddingDimension:384,enableLLMExtraction:!0,llmModelTier:2,llmMaxTokens:2048},me=oe.create("code-intelligence/knowledge-graph"),he=class{config;memory;nodeCache=new Map;edgeIndex=new Map;tsParser;fileReader;embedder;llmRouter;constructor(e,t={}){this.config={...we,...t},this.isKnowledgeGraphDependencies(e)?(this.memory=e.memory,this.llmRouter=e.llmRouter):(this.memory=e,this.llmRouter=void 0),this.tsParser=new F,this.fileReader=new k,this.embedder=new _({enableFallback:!0})}isKnowledgeGraphDependencies(e){return e.memory!==void 0}async index(e){let t=Date.now(),s=[],n=0,r=0;try{let{paths:o,incremental:i=!1,includeTests:a=!0,languages:c}=e;i||await this.clear();for(let d of o)try{if(c&&c.length>0){let m=this.getFileExtension(d);if(!this.matchesLanguage(m,c))continue}if(!a&&this.isTestFile(d))continue;let u=await this.indexFile(d);n+=u.nodes,r+=u.edges}catch(u){s.push({file:d,error:j(u)})}let l=Date.now()-t;return await this.storeIndexMetadata({filesIndexed:o.length-s.length,nodesCreated:n,edgesCreated:r,duration:l,indexedAt:new Date().toISOString()}),w({filesIndexed:o.length-s.length,nodesCreated:n,edgesCreated:r,duration:l,errors:s})}catch(o){return L(D(o))}}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(D(t))}}async mapDependencies(e){try{let{files:t,direction:s,depth:n=3}=e,r=[],o=[],i=new Set,a=[];for(let l of t)await this.traverseDependencies(l,s,n,i,r,o,[],a);let c=this.calculateDependencyMetrics(r,o);return w({nodes:r,edges:o,cycles:a,metrics:c})}catch(t){return L(D(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);return s&&this.nodeCache.set(e,s),s}async getEdges(e,t){let s=[],n=this.edgeIndex.get(e);if(n)return this.filterEdgesByDirection(n,e,t);let r=`${this.config.namespace}:edge:*`,o=await this.memory.search(r,this.config.maxEdgesPerNode*2);for(let i of o){let a=await this.memory.get(i);a&&(t!=="outgoing"&&a.target===e||t!=="incoming"&&a.source===e)&&s.push(a)}return s}async clear(){this.nodeCache.clear(),this.edgeIndex.clear()}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),r=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,3 +1,3 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{c}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.14");process.exit(0)}
|
|
2
|
+
import{c}from"./chunk-DGUAAG3T.js";function u(r){switch(r.toUpperCase()){case"DEBUG":return 0;case"INFO":return 1;case"WARN":case"WARNING":return 2;case"ERROR":return 3;case"SILENT":case"NONE":case"OFF":return 4;default:return 1}}var f,l=c(()=>{"use strict";f={0:"DEBUG",1:"INFO",2:"WARN",3:"ERROR",4:"SILENT"}});var a,s,g,d=c(()=>{"use strict";l();a={includeTimestamp:!0,includeLevel:!0,timestampFormat:"short",prettyPrint:!1,maxContextDepth:3},s=class r{domain;level;config;inheritedContext;constructor(e,n=1,o={},t={}){this.domain=e,this.level=n,this.config={...a,...o},this.inheritedContext=t}debug(e,n){this.level<=0&&this.output(0,e,n)}info(e,n){this.level<=1&&this.output(1,e,n)}warn(e,n){this.level<=2&&this.output(2,e,n)}error(e,n,o){if(this.level<=3){let t={...o};if(n){t.errorName=n.name,t.errorMessage=n.message,n.stack&&(t.stack=n.stack);let i=n;i.cause!==void 0&&(t.cause=String(i.cause))}this.output(3,e,t)}}isEnabled(e){return this.level<=e}getDomain(){return this.domain}child(e){return new r(this.domain,this.level,this.config,{...this.inheritedContext,...e})}output(e,n,o){let t=this.format(e,n,o);switch(e){case 0:console.debug(t);break;case 1:console.info(t);break;case 2:console.warn(t);break;case 3:console.error(t);break}}format(e,n,o){let t=[];this.config.includeTimestamp&&t.push(this.formatTimestamp()),this.config.includeLevel&&t.push(this.formatLevel(e)),t.push(`[${this.domain}]`),t.push(n);let i=this.mergeContext(o);return i&&Object.keys(i).length>0&&t.push(this.formatContext(i)),t.join(" ")}formatTimestamp(){let e=new Date;if(this.config.timestampFormat==="iso")return`[${e.toISOString()}]`;let n=String(e.getHours()).padStart(2,"0"),o=String(e.getMinutes()).padStart(2,"0"),t=String(e.getSeconds()).padStart(2,"0"),i=String(e.getMilliseconds()).padStart(3,"0");return`[${n}:${o}:${t}.${i}]`}formatLevel(e){return`[${f[e].padEnd(5)}]`}mergeContext(e){if(!(!e&&Object.keys(this.inheritedContext).length===0))return{...this.inheritedContext,...e}}formatContext(e){try{return this.config.prettyPrint?`
|
|
3
3
|
`+JSON.stringify(e,this.createReplacer(),2):JSON.stringify(e,this.createReplacer())}catch{return"[unserializable context]"}}createReplacer(){let e=new WeakSet,n=0;return(o,t)=>{if(typeof t=="object"&&t!==null){if(n>=this.config.maxContextDepth)return"[object]";if(e.has(t))return"[circular]";e.add(t),n++}return t instanceof Error?{name:t.name,message:t.message,stack:t.stack}:typeof t=="bigint"?t.toString():typeof t=="function"?"[function]":typeof t=="symbol"?t.toString():t}}},g=class{domain;constructor(e="null"){this.domain=e}debug(e,n){}info(e,n){}warn(e,n){}error(e,n,o){}isEnabled(e){return!1}getDomain(){return this.domain}child(e){return this}}});function F(r,e){return L.create(r,e)}var v,L,m=c(()=>{"use strict";l();d();v={defaultLevel:1,domainLevels:new Map,consoleConfig:a,silent:!1},L=class{static config={...v};static customProvider=null;static instances=new Map;static setLevel(e){this.config.defaultLevel=e,this.instances.clear()}static setLevelFromString(e){this.setLevel(u(e))}static getLevel(){return this.config.defaultLevel}static setDomainLevel(e,n){this.config.domainLevels.set(e,n),this.instances.delete(e)}static getDomainLevel(e){return this.config.domainLevels.get(e)??this.config.defaultLevel}static clearDomainLevel(e){this.config.domainLevels.delete(e),this.instances.delete(e)}static configure(e){this.config.consoleConfig={...this.config.consoleConfig,...e},this.instances.clear()}static setSilent(e){this.config.silent=e,this.instances.clear()}static isSilent(){return this.config.silent}static setProvider(e){this.customProvider=e,this.instances.clear()}static create(e,n){if(!n&&this.instances.has(e))return this.instances.get(e);let o=this.getDomainLevel(e),t;return this.config.silent?t=new g(e):this.customProvider?t=this.customProvider(e,o,n):t=new s(e,o,this.config.consoleConfig,n),n||this.instances.set(e,t),t}static getLogger(e,n){return this.create(e,n)}static reset(){this.config={defaultLevel:1,domainLevels:new Map,consoleConfig:{...a},silent:!1},this.customProvider=null,this.instances.clear()}static initFromEnv(){let e=process.env.LOG_LEVEL;e&&this.setLevelFromString(e);let n=process.env.LOG_TIMESTAMP;n!==void 0&&this.configure({includeTimestamp:n.toLowerCase()==="true"});let o=process.env.LOG_PRETTY;o!==void 0&&this.configure({prettyPrint:o.toLowerCase()==="true"})}static getStats(){return{cachedLoggers:this.instances.size,domains:Array.from(this.instances.keys()),domainOverrides:this.config.domainLevels.size,currentLevel:this.config.defaultLevel,silent:this.config.silent}}}});export{l as a,d as b,L as c,F as d,m as e};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{a as te,b as ne}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.14");process.exit(0)}
|
|
2
|
+
import{a as te,b as ne}from"./chunk-BFCMOMOF.js";import{a as k}from"./chunk-XH774Q6Z.js";import{b as ee}from"./chunk-L4IWZXSC.js";import{b as E,d as fe}from"./chunk-DMZ2XOEW.js";import{a as b,c as T}from"./chunk-UIYK4Y7K.js";var he={M:16,efConstruction:200,efSearch:100},P={enabled:!0,pretrainedPatterns:!0,hnswConfig:he,promotionThreshold:3,qualityThreshold:.7,embeddingModel:"auto"},_={mode:"hybrid",confidenceThreshold:.7,feedbackEnabled:!0,cacheEnabled:!0,cacheTTLMs:300*1e3},F={enabled:["pattern-consolidator","coverage-gap-scanner","flaky-test-detector","routing-accuracy-monitor"],intervals:{"pattern-consolidator":1800*1e3,"coverage-gap-scanner":3600*1e3,"flaky-test-detector":7200*1e3,"routing-accuracy-monitor":900*1e3},maxConcurrent:4,daemonAutoStart:!0},N={claudeCode:!0,preCommit:!1,ciIntegration:!1},$={install:!0,installV2:!0,installV3:!0,overwrite:!1},O={enabled:!0,parameters:["hnsw.efSearch","routing.confidenceThreshold","pattern.promotionThreshold","testGen.complexityLimit"],tuningIntervalMs:10080*60*1e3,evaluationPeriodMs:5e3};var L=["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","requirements-validation","code-intelligence","security-compliance","contract-testing","visual-accessibility","chaos-resilience","learning-optimization","enterprise-integration"];function M(){return"3.9.14"}function Fe(i,e){return{version:M(),project:{name:i,root:e,type:"single"},learning:P,routing:_,workers:F,hooks:N,skills:$,autoTuning:O,domains:{enabled:L,disabled:[]},agents:{maxConcurrent:15,defaultTimeout:6e4}}}fe();import{readFileSync as w,existsSync as p,statSync as ye,readdirSync as ve}from"fs";import{join as u,basename as ie,extname as re,relative as V}from"path";var be=[{name:"jest",detect:i=>{let e=["jest.config.js","jest.config.ts","jest.config.mjs","jest.config.cjs"];for(let n of e)if(p(u(i,n)))return{name:"jest",version:A(i,"jest"),configFile:n,confidence:1};let t=S(i);return t?.jest?{name:"jest",version:A(i,"jest"),configFile:"package.json",confidence:.9}:t?.devDependencies?.jest||t?.dependencies?.jest?{name:"jest",version:t.devDependencies?.jest||t.dependencies?.jest,confidence:.7}:null}},{name:"vitest",detect:i=>{let e=["vitest.config.ts","vitest.config.js","vitest.config.mts","vite.config.ts"];for(let n of e)if(p(u(i,n)))return{name:"vitest",version:A(i,"vitest"),configFile:n,confidence:1};let t=S(i);return t?.devDependencies?.vitest||t?.dependencies?.vitest?{name:"vitest",version:t.devDependencies?.vitest,confidence:.8}:null}},{name:"mocha",detect:i=>{let e=[".mocharc.js",".mocharc.json",".mocharc.yaml",".mocharc.yml"];for(let n of e)if(p(u(i,n)))return{name:"mocha",version:A(i,"mocha"),configFile:n,confidence:1};let t=S(i);return t?.devDependencies?.mocha?{name:"mocha",version:t.devDependencies?.mocha,confidence:.8}:null}},{name:"pytest",detect:i=>{let e=["pytest.ini","pyproject.toml","setup.cfg"];for(let n of e){let r=u(i,n);if(p(r))try{let s=w(r,"utf-8");if(s.includes("[pytest]")||s.includes("[tool.pytest]"))return{name:"pytest",configFile:n,confidence:1}}catch(s){console.debug("[ProjectAnalyzer] Config read failed:",s instanceof Error?s.message:s)}}let t=u(i,"requirements.txt");if(p(t))try{if(w(t,"utf-8").includes("pytest"))return{name:"pytest",configFile:"requirements.txt",confidence:.8}}catch(n){console.debug("[ProjectAnalyzer] requirements.txt read failed:",n instanceof Error?n.message:n)}return null}},{name:"playwright",detect:i=>{let e=["playwright.config.ts","playwright.config.js"];for(let n of e)if(p(u(i,n)))return{name:"playwright",version:A(i,"@playwright/test"),configFile:n,confidence:1};let t=S(i);return t?.devDependencies?.["@playwright/test"]?{name:"playwright",version:t.devDependencies["@playwright/test"],confidence:.8}:null}},{name:"cypress",detect:i=>{let e=["cypress.config.ts","cypress.config.js","cypress.json"];for(let t of e)if(p(u(i,t)))return{name:"cypress",version:A(i,"cypress"),configFile:t,confidence:1};return p(u(i,"cypress"))?{name:"cypress",configFile:"cypress/",confidence:.9}:null}}],ke=[{name:"typescript",extensions:[".ts",".tsx",".mts",".cts"]},{name:"javascript",extensions:[".js",".jsx",".mjs",".cjs"]},{name:"python",extensions:[".py",".pyw"]},{name:"java",extensions:[".java"]},{name:"go",extensions:[".go"]},{name:"rust",extensions:[".rs"]},{name:"csharp",extensions:[".cs"]},{name:"ruby",extensions:[".rb"]},{name:"php",extensions:[".php"]},{name:"kotlin",extensions:[".kt",".kts"]},{name:"swift",extensions:[".swift"]}];function S(i){let e=u(i,"package.json");if(!p(e))return null;try{return E(w(e,"utf-8"))}catch{return null}}function A(i,e){let t=S(i);if(t)return t.devDependencies?.[e]||t.dependencies?.[e]}function Q(i,e,t={}){let{maxDepth:n=10,exclude:r=["node_modules",".git","dist","build","coverage",".next","__pycache__"]}=t;function s(o,a){if(a>n)return;let l;try{l=ve(o)}catch{return}for(let g of l){if(r.includes(g))continue;let c=u(o,g),x;try{x=ye(c)}catch{continue}x.isDirectory()?s(c,a+1):x.isFile()&&e(c)}}s(i,0)}var W=class{projectRoot;constructor(e){this.projectRoot=e}async analyze(){let e=Date.now(),[t,n,r,s,o]=await Promise.all([this.detectFrameworks(),this.detectLanguages(),this.detectExistingTests(),this.analyzeComplexity(),this.measureCoverage()]);return{projectName:S(this.projectRoot)?.name||ie(this.projectRoot),projectRoot:this.projectRoot,projectType:this.detectProjectType(),frameworks:t,languages:n,existingTests:r,codeComplexity:s,coverage:o,packageManager:this.detectPackageManager(),hasTypeScript:p(u(this.projectRoot,"tsconfig.json")),hasCIConfig:this.detectCIConfig(),ciProvider:this.detectCIProvider(),analysisTimestamp:new Date,analysisDurationMs:Date.now()-e}}async detectFrameworks(){let e=[];for(let t of be){let n=t.detect(this.projectRoot);n&&e.push(n)}return e.sort((t,n)=>n.confidence-t.confidence)}async detectLanguages(){let e=new Map,t=0;Q(this.projectRoot,r=>{let s=re(r).toLowerCase();if(s){for(let o of ke)if(o.extensions.includes(s)){let a=e.get(o.name)||{count:0,extensions:new Set};a.count++,a.extensions.add(s),e.set(o.name,a),t++;break}}});let n=[];for(let[r,s]of e)n.push({name:r,percentage:t>0?Math.round(s.count/t*100):0,fileCount:s.count,extensions:Array.from(s.extensions)});return n.sort((r,s)=>s.fileCount-r.fileCount)}async detectExistingTests(){let e={totalCount:0,byFramework:{},byType:{unit:0,integration:0,e2e:0,unknown:0},directories:[]},t=new Set,n=[/\.test\.[jt]sx?$/,/\.spec\.[jt]sx?$/,/_test\.[jt]sx?$/,/test_.*\.py$/,/.*_test\.py$/,/.*_test\.go$/,/.*Test\.java$/];return Q(this.projectRoot,r=>{let s=ie(r);if(n.some(a=>a.test(s))){e.totalCount++;let a=V(this.projectRoot,r).toLowerCase();a.includes("e2e")||a.includes("cypress")||a.includes("playwright")?e.byType.e2e++:a.includes("integration")||a.includes("int-test")?e.byType.integration++:a.includes("unit")||a.includes("__tests__")||a.includes("test/")?e.byType.unit++:e.byType.unknown++;let l=V(this.projectRoot,u(r,".."));t.add(l)}}),e.directories=Array.from(t).slice(0,10),e}async analyzeComplexity(){let e=[],t=[],n=0,r=0;Q(this.projectRoot,a=>{let l=re(a);if([".ts",".tsx",".js",".jsx",".py",".java",".go"].includes(l))try{let g=w(a,"utf-8"),c=this.calculateFileComplexity(g,l);t.push(...c.functionComplexities),c.maxComplexity>n&&(n=c.maxComplexity),r++,c.maxComplexity>10&&e.push(V(this.projectRoot,a))}catch(g){console.debug("[ProjectAnalyzer] Complexity analysis read failed:",g instanceof Error?g.message:g)}});let s=t.reduce((a,l)=>a+l,0),o=t.length>0?s/t.length:0;return{averageCyclomatic:Math.round(o*10)/10,maxCyclomatic:n,totalFiles:r,complexFiles:e.slice(0,20),recommendation:o<5?"simple":o<15?"medium":"complex"}}calculateFileComplexity(e,t){let n=this.stripCommentsAndStrings(e,t),r=this.calculateComplexity(n);return{functionComplexities:[r],maxComplexity:r}}removeDelimitedBlocks(e,t,n){let r="",s=0;for(;s<e.length;){let o=e.indexOf(t,s);if(o===-1){r+=e.slice(s);break}r+=e.slice(s,o);let a=e.indexOf(n,o+t.length);if(a===-1)break;s=a+n.length}return r}stripCommentsAndStrings(e,t){let n=e;return[".ts",".tsx",".js",".jsx",".java",".go"].includes(t)?(n=n.split(`
|
|
3
3
|
`).map(r=>{let s=r.indexOf("//");return s>=0?r.slice(0,s):r}).join(`
|
|
4
4
|
`),n=this.removeDelimitedBlocks(n,"/*","*/"),n=this.removeDelimitedBlocks(n,"`","`"),n=this.removeDelimitedBlocks(n,'"','"'),n=this.removeDelimitedBlocks(n,"'","'")):t===".py"&&(n=n.split(`
|
|
5
5
|
`).map(r=>{let s=r.indexOf("#");return s>=0?r.slice(0,s):r}).join(`
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{i as c}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.14");process.exit(0)}
|
|
2
|
+
import{i as c}from"./chunk-NWGIQCCO.js";import{a as p}from"./chunk-STYNOKOM.js";import{c as m}from"./chunk-GUEK5DOK.js";import{b as g,d as E}from"./chunk-DMZ2XOEW.js";import{a as l,b as _}from"./chunk-LWHM5BWD.js";_();import b from"node:path";import{existsSync as h}from"node:fs";E();p();var T=m.create("metrics-tracker"),d=class{db=null;dbPath;initialized=!1;constructor(e=process.cwd()){this.dbPath=b.join(e,".agentic-qe","memory.db")}async initialize(){if(!this.initialized){if(!h(this.dbPath))throw new Error(`Database not found: ${this.dbPath}. Run "aqe init --auto" first.`);this.db=l(this.dbPath),this.ensureMetricsTable(),this.initialized=!0}}ensureMetricsTable(){this.db&&this.db.exec(`
|
|
3
3
|
CREATE TABLE IF NOT EXISTS learning_daily_snapshots (
|
|
4
4
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
5
5
|
snapshot_date TEXT NOT NULL UNIQUE,
|
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{a as E}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.14");process.exit(0)}
|
|
2
|
+
import{a as E}from"./chunk-NWGIQCCO.js";import{a as b}from"./chunk-STYNOKOM.js";import{c as y}from"./chunk-GUEK5DOK.js";import{a as f,c as k}from"./chunk-UIYK4Y7K.js";k();b();var l=y.create("qe-hooks"),u={PreTestGeneration:"qe:pre-test-generation",PostTestGeneration:"qe:post-test-generation",TestExecutionResult:"qe:test-execution-result",PreCoverageAnalysis:"qe:pre-coverage-analysis",PostCoverageAnalysis:"qe:post-coverage-analysis",CoverageGapIdentified:"qe:coverage-gap-identified",QEAgentRouting:"qe:agent-routing",QEAgentCompletion:"qe:agent-completion",QualityScoreCalculated:"qe:quality-score",RiskAssessmentComplete:"qe:risk-assessment",PatternLearned:"qe:pattern-learned",PatternApplied:"qe:pattern-applied",PatternPromoted:"qe:pattern-promoted",PreCompaction:"qe:pre-compaction"};function h(i){return{[u.PreTestGeneration]:async t=>{let{targetFile:s,testType:a,framework:e,language:r}=t.data,n=await i.routeTask({task:`Generate ${a} tests for ${s}`,taskType:"test-generation",context:{framework:e,language:r,testType:a}});if(!n.success)return{success:!1,error:n.error.message};let o=[];try{let{getUnifiedMemory:c}=await import("./unified-memory-NHJHPLIC.js");o=c().getDatabase().prepare(`
|
|
3
3
|
SELECT u.pattern_id, u.success, u.feedback
|
|
4
4
|
FROM qe_pattern_usage u
|
|
5
5
|
JOIN qe_patterns p ON u.pattern_id = p.id
|
|
6
6
|
WHERE p.qe_domain = 'test-generation'
|
|
7
7
|
ORDER BY u.created_at DESC
|
|
8
8
|
LIMIT 10
|
|
9
|
-
`).all()}catch{}return{success:!0,routing:n.value,guidance:n.value.guidance,data:{recommendedAgent:n.value.recommendedAgent,patterns:n.value.patterns.map(c=>c.id),recentExperiences:o}}},[u.PostTestGeneration]:async t=>{let{targetFile:s,generatedTests:a,testCount:e,framework:r,language:n,success:o,patternId:c}=t.data,p=0;if(c&&await i.recordOutcome({patternId:c,success:o,metrics:{testsPassed:0,testsFailed:0}}),o&&a&&e>0)try{(await i.storePattern({patternType:"test-template",name:`Generated tests for ${s.split("/").pop()}`,description:`Test template extracted from successful test generation for ${s}`,template:{type:"code",content:a,variables:[]},context:{framework:r,language:n,testType:"unit",tags:["generated","test-template",r,n]}})).success&&(p=1)}catch(d){l.debug("Pattern learning failed",{error:d instanceof Error?d.message:String(d)})}return{success:!0,patternsLearned:p,data:{learned:p>0}}},[u.TestExecutionResult]:async t=>{let{runId:s,patternId:a,passed:e,failed:r,duration:n,flaky:o}=t.data;if(a){let c=e+r>0?e/(e+r):0;await i.recordOutcome({patternId:a,success:c>.8&&!o,metrics:{testsPassed:e,testsFailed:r,executionTimeMs:n}})}return{success:!0,data:{runId:s,successRate:e+r>0?e/(e+r):0}}},[u.PreCoverageAnalysis]:async t=>{let{targetPath:s,currentCoverage:a}=t.data,e=await i.routeTask({task:`Analyze coverage gaps for ${s} (current: ${a}%)`,taskType:"analysis",domain:"coverage-analysis"});if(!e.success)return{success:!1,error:e.error.message};let r=[];try{let{getUnifiedMemory:n}=await import("./unified-memory-
|
|
9
|
+
`).all()}catch{}return{success:!0,routing:n.value,guidance:n.value.guidance,data:{recommendedAgent:n.value.recommendedAgent,patterns:n.value.patterns.map(c=>c.id),recentExperiences:o}}},[u.PostTestGeneration]:async t=>{let{targetFile:s,generatedTests:a,testCount:e,framework:r,language:n,success:o,patternId:c}=t.data,p=0;if(c&&await i.recordOutcome({patternId:c,success:o,metrics:{testsPassed:0,testsFailed:0}}),o&&a&&e>0)try{(await i.storePattern({patternType:"test-template",name:`Generated tests for ${s.split("/").pop()}`,description:`Test template extracted from successful test generation for ${s}`,template:{type:"code",content:a,variables:[]},context:{framework:r,language:n,testType:"unit",tags:["generated","test-template",r,n]}})).success&&(p=1)}catch(d){l.debug("Pattern learning failed",{error:d instanceof Error?d.message:String(d)})}return{success:!0,patternsLearned:p,data:{learned:p>0}}},[u.TestExecutionResult]:async t=>{let{runId:s,patternId:a,passed:e,failed:r,duration:n,flaky:o}=t.data;if(a){let c=e+r>0?e/(e+r):0;await i.recordOutcome({patternId:a,success:c>.8&&!o,metrics:{testsPassed:e,testsFailed:r,executionTimeMs:n}})}return{success:!0,data:{runId:s,successRate:e+r>0?e/(e+r):0}}},[u.PreCoverageAnalysis]:async t=>{let{targetPath:s,currentCoverage:a}=t.data,e=await i.routeTask({task:`Analyze coverage gaps for ${s} (current: ${a}%)`,taskType:"analysis",domain:"coverage-analysis"});if(!e.success)return{success:!1,error:e.error.message};let r=[];try{let{getUnifiedMemory:n}=await import("./unified-memory-NHJHPLIC.js");r=n().getDatabase().prepare(`
|
|
10
10
|
SELECT u.pattern_id, u.success, u.feedback
|
|
11
11
|
FROM qe_pattern_usage u
|
|
12
12
|
JOIN qe_patterns p ON u.pattern_id = p.id
|
|
@@ -17,4 +17,4 @@ import{a as E}from"./chunk-TOS3PI5Q.js";import{a as b}from"./chunk-Y2ONHWXI.js";
|
|
|
17
17
|
${n}`,variables:[]},context:{tags:["coverage-gap","high-risk","suggested-tests"]}})}catch(o){l.debug("Coverage gap pattern storage failed",{error:o instanceof Error?o.message:String(o)})}return{success:!0,data:{file:s,riskScore:r}}},[u.QEAgentRouting]:async t=>{let{task:s,taskType:a,capabilities:e,context:r}=t.data,n=await i.routeTask({task:s,taskType:a,capabilities:e,context:r});return n.success?{success:!0,routing:n.value,guidance:n.value.guidance,data:{agent:n.value.recommendedAgent,confidence:n.value.confidence}}:{success:!1,error:n.error.message}},[u.QEAgentCompletion]:async t=>{let{agentType:s,task:a,success:e,duration:r,patternId:n,feedback:o}=t.data,c=0,p=n;if(p){try{if(!await i.getPattern(p)){let g=s||"unknown",v=E(a||g)||"learning-optimization";await i.storePattern({patternType:"test-template",qeDomain:v,name:`Auto: ${g} completion`,description:`Auto-created pattern for ${g} task completion tracking`,template:{type:"prompt",content:`Agent ${g} task pattern`,variables:[]},context:{tags:["auto-created","agent-completion",g]},confidence:.5}),c=1}}catch(d){l.debug("Auto-create pattern failed",{error:d instanceof Error?d.message:String(d)})}await i.recordOutcome({patternId:p,success:e,metrics:{executionTimeMs:r},feedback:o})}return{success:!0,patternsLearned:c,data:{agentType:s,success:e,duration:r}}},[u.QualityScoreCalculated]:async t=>{let{score:s,components:a,threshold:e,passed:r}=t.data,n=[];return t.data.coverageScore&&t.data.coverageScore<.8&&n.push("Coverage is below target. Focus on critical paths."),t.data.testQualityScore&&t.data.testQualityScore<.7&&n.push("Test quality needs improvement. Review test assertions."),{success:!0,guidance:n,data:{score:s,passed:r}}},[u.RiskAssessmentComplete]:async t=>{let{file:s,riskScore:a,riskFactors:e}=t.data;if(a>.7&&e)try{await i.storePattern({patternType:"coverage-strategy",name:`High risk: ${s.split("/").pop()}`,description:`Risk factors: ${e.join(", ")}`,template:{type:"prompt",content:`Risk assessment for ${s}:
|
|
18
18
|
Score: ${a}
|
|
19
19
|
Factors: ${e.join(`
|
|
20
|
-
- `)}`,variables:[]},context:{tags:["risk","high-priority","assessment"]}})}catch(r){l.debug("Risk assessment pattern storage failed",{error:r instanceof Error?r.message:String(r)})}return{success:!0,data:{file:s,riskScore:a}}},[u.PatternLearned]:async t=>{let{patternId:s,patternType:a,domain:e,confidence:r}=t.data;return console.log(`[QEHooks] Pattern learned: ${s} (${a}, ${e}, confidence: ${r})`),{success:!0,patternsLearned:1,data:{patternId:s}}},[u.PatternApplied]:async t=>{let{patternId:s,success:a}=t.data;return await i.recordOutcome({patternId:s,success:a}),{success:!0,data:{patternId:s,success:a}}},[u.PatternPromoted]:async t=>{let{patternId:s,newTier:a,successfulUses:e}=t.data;return console.log(`[QEHooks] Pattern promoted: ${s} -> ${a} (${e} successful uses)`),{success:!0,data:{patternId:s,newTier:a}}},[u.PreCompaction]:async t=>{let s={experiencesFlushed:0,patternsPromoted:0};if(t.data?.experienceCaptureService){let a=t.data.experienceCaptureService,e=a.getPendingCount?.()??0;if(e>0){let r=await a.flushPending?.();s.experiencesFlushed=r??e}}if(t.data?.patternLifecycleManager){let e=t.data.patternLifecycleManager.runPromotionSweep?.();e&&(s.patternsPromoted=e.promoted??0)}return console.log("[QEHooks] Pre-compaction flush:",s),{success:!0,data:s}}}}var m=class{constructor(t){this.eventBus=t}handlers=new Map;reasoningBank;initialize(t){this.reasoningBank=t;let s=h(t);for(let[a,e]of Object.entries(s))this.register(a,e);if(this.eventBus)for(let a of Object.values(u))this.eventBus.subscribe(a,async e=>{await this.emit(a,e.payload)})}register(t,s){this.handlers.has(t)||this.handlers.set(t,[]),this.handlers.get(t).push(s)}unregister(t,s){let a=this.handlers.get(t);if(a){let e=a.indexOf(s);e!==-1&&a.splice(e,1)}}async emit(t,s){let a=this.handlers.get(t)||[],e=[],r={eventId:`${t}-${Date.now()}`,timestamp:new Date,data:s};for(let n of a)try{let o=await n(r);e.push(o),o.data&&Object.assign(r.data,o.data)}catch(o){e.push({success:!1,error:f(o)})}return e}getRegisteredEvents(){return Array.from(this.handlers.keys())}clear(){this.handlers.clear()}};function w(i,t){let s=new m(t);return s.initialize(i),s}export{u as a,m as b,w as c};
|
|
20
|
+
- `)}`,variables:[]},context:{tags:["risk","high-priority","assessment"]}})}catch(r){l.debug("Risk assessment pattern storage failed",{error:r instanceof Error?r.message:String(r)})}return{success:!0,data:{file:s,riskScore:a}}},[u.PatternLearned]:async t=>{let{patternId:s,patternType:a,domain:e,confidence:r}=t.data;return console.log(`[QEHooks] Pattern learned: ${s} (${a}, ${e}, confidence: ${r})`),{success:!0,patternsLearned:1,data:{patternId:s}}},[u.PatternApplied]:async t=>{let{patternId:s,success:a}=t.data;return await i.recordOutcome({patternId:s,success:a}),{success:!0,data:{patternId:s,success:a}}},[u.PatternPromoted]:async t=>{let{patternId:s,newTier:a,successfulUses:e}=t.data;return console.log(`[QEHooks] Pattern promoted: ${s} -> ${a} (${e} successful uses)`),{success:!0,data:{patternId:s,newTier:a}}},[u.PreCompaction]:async t=>{let s={experiencesFlushed:0,patternsPromoted:0};if(t.data?.experienceCaptureService){let a=t.data.experienceCaptureService,e=a.getPendingCount?.()??0;if(e>0){let r=await a.flushPending?.();s.experiencesFlushed=r??e}}if(t.data?.patternLifecycleManager){let e=t.data.patternLifecycleManager.runPromotionSweep?.();e&&(s.patternsPromoted=e.promoted??0)}return console.log("[QEHooks] Pre-compaction flush:",s),{success:!0,data:s}}}}var m=class{constructor(t){this.eventBus=t}eventBus;handlers=new Map;reasoningBank;initialize(t){this.reasoningBank=t;let s=h(t);for(let[a,e]of Object.entries(s))this.register(a,e);if(this.eventBus)for(let a of Object.values(u))this.eventBus.subscribe(a,async e=>{await this.emit(a,e.payload)})}register(t,s){this.handlers.has(t)||this.handlers.set(t,[]),this.handlers.get(t).push(s)}unregister(t,s){let a=this.handlers.get(t);if(a){let e=a.indexOf(s);e!==-1&&a.splice(e,1)}}async emit(t,s){let a=this.handlers.get(t)||[],e=[],r={eventId:`${t}-${Date.now()}`,timestamp:new Date,data:s};for(let n of a)try{let o=await n(r);e.push(o),o.data&&Object.assign(r.data,o.data)}catch(o){e.push({success:!1,error:f(o)})}return e}getRegisteredEvents(){return Array.from(this.handlers.keys())}clear(){this.handlers.clear()}};function w(i,t){let s=new m(t);return s.initialize(i),s}export{u as a,m as b,w as c};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{d as s}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.14");process.exit(0)}
|
|
2
|
+
import{d as s}from"./chunk-DMZ2XOEW.js";s();
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.14");process.exit(0)}
|
|
2
2
|
function c(r,e,o){let n=new Error(r);return n.name="LLMError",n.code=e,n.provider=o?.provider,n.model=o?.model,n.retryable=o?.retryable??!1,n.retryAfterMs=o?.retryAfterMs,n.cause=o?.cause,n}function p(r){return r instanceof Error&&"code"in r&&typeof r.code=="string"}var a={"claude-sonnet-4-5":{canonical:"Claude Sonnet 4.5",family:"claude",tier:"standard",providers:{anthropic:"claude-sonnet-4-5-20250929",openrouter:"anthropic/claude-sonnet-4.5",bedrock:"anthropic.claude-sonnet-4-5-v2:0"}},"claude-opus-4":{canonical:"Claude Opus 4",family:"claude",tier:"flagship",providers:{anthropic:"claude-opus-4-20250514",openrouter:"anthropic/claude-opus-4",bedrock:"anthropic.claude-opus-4-v1:0"}},"claude-opus-4-5":{canonical:"Claude Opus 4.5",family:"claude",tier:"flagship",providers:{anthropic:"claude-opus-4-5-20251101",openrouter:"anthropic/claude-opus-4.5",bedrock:"anthropic.claude-opus-4-5-v1:0"}},"claude-haiku-3-5":{canonical:"Claude Haiku 3.5",family:"claude",tier:"economy",providers:{anthropic:"claude-3-5-haiku-20241022",openrouter:"anthropic/claude-3.5-haiku",bedrock:"anthropic.claude-3-5-haiku-v1:0"}},"claude-sonnet-4":{canonical:"Claude Sonnet 4",family:"claude",tier:"standard",providers:{anthropic:"claude-sonnet-4-20250514",openrouter:"anthropic/claude-sonnet-4",bedrock:"anthropic.claude-sonnet-4-v1:0"}},"claude-opus-4-7":{canonical:"Claude Opus 4.7",family:"claude",tier:"flagship",providers:{anthropic:"claude-opus-4-7",openrouter:"anthropic/claude-opus-4.7",bedrock:"anthropic.claude-opus-4-7-v1:0"}},"claude-sonnet-4-6":{canonical:"Claude Sonnet 4.6",family:"claude",tier:"standard",providers:{anthropic:"claude-sonnet-4-6",openrouter:"anthropic/claude-sonnet-4.6",bedrock:"anthropic.claude-sonnet-4-6-v1:0"}},"claude-haiku-4-5":{canonical:"Claude Haiku 4.5",family:"claude",tier:"economy",providers:{anthropic:"claude-haiku-4-5-20251001",openrouter:"anthropic/claude-haiku-4.5",bedrock:"anthropic.claude-haiku-4-5-v1:0"}},"gpt-4o":{canonical:"GPT-4o",family:"gpt",tier:"standard",providers:{openai:"gpt-4o",azure:"gpt-4o",openrouter:"openai/gpt-4o"}},"gpt-4o-mini":{canonical:"GPT-4o Mini",family:"gpt",tier:"economy",providers:{openai:"gpt-4o-mini",azure:"gpt-4o-mini",openrouter:"openai/gpt-4o-mini"}},"gpt-4-turbo":{canonical:"GPT-4 Turbo",family:"gpt",tier:"premium",providers:{openai:"gpt-4-turbo",azure:"gpt-4-turbo",openrouter:"openai/gpt-4-turbo"}},"gpt-4":{canonical:"GPT-4",family:"gpt",tier:"premium",providers:{openai:"gpt-4",azure:"gpt-4",openrouter:"openai/gpt-4"}},o1:{canonical:"OpenAI o1",family:"gpt",tier:"flagship",providers:{openai:"o1",azure:"o1",openrouter:"openai/o1"}},"o1-mini":{canonical:"OpenAI o1 Mini",family:"gpt",tier:"standard",providers:{openai:"o1-mini",azure:"o1-mini",openrouter:"openai/o1-mini"}},"gemini-pro":{canonical:"Gemini Pro",family:"gemini",tier:"standard",providers:{gemini:"gemini-pro",openrouter:"google/gemini-pro"}},"gemini-pro-1.5":{canonical:"Gemini Pro 1.5",family:"gemini",tier:"standard",providers:{gemini:"gemini-1.5-pro",openrouter:"google/gemini-pro-1.5"}},"gemini-flash-1.5":{canonical:"Gemini Flash 1.5",family:"gemini",tier:"economy",providers:{gemini:"gemini-1.5-flash",openrouter:"google/gemini-flash-1.5"}},"gemini-ultra":{canonical:"Gemini Ultra",family:"gemini",tier:"flagship",providers:{gemini:"gemini-ultra",openrouter:"google/gemini-ultra"}},llama3:{canonical:"Llama 3",family:"llama",tier:"economy",providers:{ollama:"llama3",openrouter:"meta-llama/llama-3-8b-instruct"}},"llama3.1":{canonical:"Llama 3.1",family:"llama",tier:"economy",providers:{ollama:"llama3.1",openrouter:"meta-llama/llama-3.1-8b-instruct"}},codellama:{canonical:"CodeLlama",family:"llama",tier:"economy",providers:{ollama:"codellama",openrouter:"meta-llama/codellama-34b-instruct"}},mistral:{canonical:"Mistral",family:"mistral",tier:"economy",providers:{ollama:"mistral",openrouter:"mistralai/mistral-7b-instruct"}},mixtral:{canonical:"Mixtral",family:"mistral",tier:"standard",providers:{ollama:"mixtral",openrouter:"mistralai/mixtral-8x7b-instruct"}},phi3:{canonical:"Phi-3",family:"phi",tier:"economy",providers:{ollama:"phi3",azure:"phi-3-mini-128k-instruct"}},qwen2:{canonical:"Qwen 2",family:"qwen",tier:"economy",providers:{ollama:"qwen2",openrouter:"qwen/qwen-2-7b-instruct"}}};function l(){let r=new Map;for(let[e,o]of Object.entries(a)){r.set(e,e),r.set(e.toLowerCase(),e);for(let[n,t]of Object.entries(o.providers))t&&(r.set(t,e),r.set(t.toLowerCase(),e),r.set(`${n}/${t}`,e),r.set(`${n}/${t}`.toLowerCase(),e))}return r}var i=l();function m(r,e){let o=s(r),n=a[o];if(!n)throw new Error(`Unknown model: ${r}`);let t=n.providers[e];if(!t)throw new Error(`Model '${o}' (${n.canonical}) is not available on provider '${e}'`);return t}function s(r){let e=i.get(r);if(e||(e=i.get(r.toLowerCase()),e))return e;let o=[/^anthropic\//i,/^openai\//i,/^google\//i,/^meta-llama\//i,/^mistralai\//i,/^qwen\//i];for(let n of o){let t=r.replace(n,"");if(e=i.get(t),e||(e=i.get(t.toLowerCase()),e))return e}throw new Error(`Unknown model ID: ${r}`)}function d(r){try{let e=s(r);return a[e]}catch{return}}export{c as a,p as b,m as c,s as d,d as e};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{a as T}from"./chunk-Y2ONHWXI.js";import{c as S}from"./chunk-HHRUXDLT.js";import{b as C,d as P}from"./chunk-VCJP7HQG.js";import{a as w,c as $}from"./chunk-3AOWTHLS.js";import{a as b,d as M}from"./chunk-YYQVSVBO.js";$();M();import{randomUUID as D}from"crypto";var V={topology:"hierarchical",maxConcurrentSkills:10,maxConcurrentModels:3,timeout:3e5,continueOnFailure:!0,retry:{maxRetries:2,retryDelayMs:1e3}},R=class{config;learner;skillValidator=null;workers=new Map;taskQueue=[];isRunning=!1;constructor(e,t){this.config={...V,...e},this.learner=t}setSkillValidator(e){this.skillValidator=e}async validateSkillsParallel(e,t,i){let s=Date.now(),a=i?.trustTier??3,n=i?.validationLevel??"eval",c=this.determineTopology(e.length,t.length),r=this.createValidationTasks(e,t,a,n),o=await this.executeTasksParallel(r,c),l=new Map;for(let u of o){let p=l.get(u.skill)||[];p.push(u),l.set(u.skill,p)}return await this.recordOutcomesToLearner(o,a,n),l}async validateSkillCrossModel(e,t,i){return(await this.validateSkillsParallel([e],t,i)).get(e)||[]}getSummary(e){let t=[],i=new Map,s=new Map;for(let[c,r]of e){i.set(c,r);for(let o of r){t.push(o);let l=s.get(o.model)||[];l.push(o),s.set(o.model,l)}}let a=t.filter(c=>c.errors.length===0&&c.evalPassRate>=.9).length,n=t.reduce((c,r)=>c+r.durationMs,0);return{totalSkills:i.size,totalModels:s.size,successCount:a,failureCount:t.length-a,overallPassRate:t.length>0?a/t.length:0,totalDurationMs:n,avgDurationMs:t.length>0?n/t.length:0,topology:this.config.topology,bySkill:i,byModel:s,results:t}}determineTopology(e,t){if(this.config.topology){let i=e*t;return i>20&&this.config.topology==="mesh"&&console.warn(`[SwarmSkillValidator] Large workload (${i} tasks) may be more efficient with hierarchical topology`),this.config.topology}return e>5||e>t*2?"hierarchical":t>5&&e<=3?"mesh":"hierarchical"}createValidationTasks(e,t,i,s){let a=[];for(let n of e)for(let c of t)a.push({id:`${n}-${c}-${Date.now()}-${D().slice(0,8)}`,skill:n,model:c,trustTier:i,validationLevel:s,timeout:this.config.timeout,retryCount:0});return a}async executeTasksParallel(e,t){this.isRunning=!0,this.taskQueue=[...e];let i=[],s=t==="hierarchical"?this.config.maxConcurrentSkills:Math.min(this.config.maxConcurrentSkills*this.config.maxConcurrentModels,e.length),a=[];for(let n=0;n<Math.min(s,e.length);n++){let c=`worker-${n}`;this.workers.set(c,{id:c,task:null,status:"idle"}),a.push(this.runWorker(c,i))}return await Promise.all(a),this.isRunning=!1,this.workers.clear(),i}async runWorker(e,t){let i=this.workers.get(e);if(i){for(;this.taskQueue.length>0&&this.isRunning;){let s=this.taskQueue.shift();if(!s)break;i.task=s,i.status="running",i.startTime=Date.now();try{let a=await this.executeValidationTask(s);t.push(a),i.result=a,i.status="completed"}catch(a){let n=this.createErrorResult(s,a);this.config.retry&&s.retryCount<this.config.retry.maxRetries&&this.config.continueOnFailure?(s.retryCount++,this.taskQueue.push(s),await this.delay(this.config.retry.retryDelayMs)):(t.push(n),i.result=n,i.status="failed")}}i.task=null,i.status="idle"}}async executeValidationTask(e){let t=Date.now();if(!this.skillValidator)return this.createSimulatedResult(e,t);let i=new Promise((n,c)=>{setTimeout(()=>c(new Error(`Validation timeout after ${e.timeout}ms`)),e.timeout)}),s=await Promise.race([this.skillValidator(e.skill,e.model,{trustTier:e.trustTier,validationLevel:e.validationLevel,timeout:e.timeout}),i]),a=Date.now()-t;return this.outcomeToResult(s,e,a)}outcomeToResult(e,t,i){let s=e.testCaseResults.filter(c=>c.passed).length,a=e.testCaseResults.length,n=a>0?s/a:e.score;return{skill:t.skill,model:t.model,schemaValid:e.validationLevel!=="schema"||e.passed,validatorPassed:e.validationLevel!=="validator"||e.passed,evalPassRate:n,durationMs:i,errors:e.passed?[]:["Validation failed"],trustTier:t.trustTier,validationLevel:t.validationLevel,retryCount:t.retryCount,timestamp:new Date}}createSimulatedResult(e,t){let i=Date.now()-t+b()*100,s=.85+b()*.15;return{skill:e.skill,model:e.model,schemaValid:!0,validatorPassed:s>.8,evalPassRate:s,durationMs:i,errors:s>.8?[]:["Simulated validation failure"],trustTier:e.trustTier,validationLevel:e.validationLevel,retryCount:e.retryCount,timestamp:new Date}}createErrorResult(e,t){let i=w(t);return{skill:e.skill,model:e.model,schemaValid:!1,validatorPassed:!1,evalPassRate:0,durationMs:0,errors:[i],trustTier:e.trustTier,validationLevel:e.validationLevel,retryCount:e.retryCount,timestamp:new Date}}async recordOutcomesToLearner(e,t,i){for(let s of e){let a={skillName:s.skill,trustTier:s.trustTier||t,validationLevel:s.validationLevel||i,model:s.model,passed:s.errors.length===0&&s.evalPassRate>=.9,score:s.evalPassRate,testCaseResults:this.createTestCaseResults(s),timestamp:s.timestamp,runId:`swarm-${Date.now()}`,metadata:{duration:s.durationMs,retryCount:s.retryCount}};await this.learner.recordValidationOutcome(a)}}createTestCaseResults(e){return[{testId:`${e.skill}-${e.model}-aggregate`,passed:e.errors.length===0,expectedPatterns:["valid-output"],actualPatterns:e.errors.length===0?["valid-output"]:[],reasoningQuality:e.evalPassRate,executionTimeMs:e.durationMs,category:"swarm-validation",priority:"high",error:e.errors.length>0?e.errors.join("; "):void 0}]}delay(e){return new Promise(t=>setTimeout(t,e))}getConfig(){return{...this.config}}isValidationRunning(){return this.isRunning}getWorkerStatus(){return Array.from(this.workers.values())}cancel(){this.isRunning=!1,this.taskQueue=[]}};function A(y,e){return new R(y,e)}var F=["security-testing","accessibility-testing","api-testing","performance-testing","visual-regression-testing","mutation-testing","contract-testing","chaos-testing","compliance-testing","penetration-testing"],I=["claude-sonnet","claude-haiku","claude-opus"];P();import{readFileSync as L,writeFileSync as N,existsSync as E}from"fs";var O={varianceThreshold:.04,regressionThreshold:.1,minSamples:3,autoUpdateManifest:!1},k=class{constructor(e,t,i={}){this.learner=e;this.manifestPath=t;this.config={...O,...i}}config;async aggregateResults(e){let t=`agg-${Date.now()}`,i=new Date,s=this.buildSkillResultsMap(e),a=this.calculateSummary(s,e),n=await this.detectCrossModelAnomalies(e),c=await this.detectRegressions(e,this.config.regressionThreshold),r=this.generateRecommendations(s,n,c),o={timestamp:i,runId:t,summary:a,skillResults:s,crossModelAnalysis:n,regressions:c,recommendations:r,metadata:{version:"1.0.0",environment:e[0]?.metadata?.environment,generatedBy:"ValidationResultAggregator",inputs:{runIds:e.map(l=>l.runId),models:[...new Set(e.map(l=>l.model))]}}};return this.config.autoUpdateManifest&&await this.updateManifest(o),o}buildSkillResultsMap(e){let t=new Map;for(let i of e)for(let s of i.outcomes){let a=s.skillName;t.has(a)||t.set(a,{skill:a,trustTier:s.trustTier,passRateByModel:new Map,avgPassRate:0,schemaValid:!0,validatorPassed:!0,evalPassed:!0,issues:[],executionTimeMs:0,testCount:0,passedTests:0,failedTests:0});let n=t.get(a),c=s.testCaseResults.filter(r=>r.passed).length/(s.testCaseResults.length||1);n.passRateByModel.set(i.model,c),n.testCount+=s.testCaseResults.length,n.passedTests+=s.testCaseResults.filter(r=>r.passed).length,n.failedTests+=s.testCaseResults.filter(r=>!r.passed).length,n.executionTimeMs+=s.metadata?.duration||0,s.validationLevel==="schema"&&!s.passed&&(n.schemaValid=!1),s.validationLevel==="validator"&&!s.passed&&(n.validatorPassed=!1),s.validationLevel==="eval"&&!s.passed&&(n.evalPassed=!1);for(let r of s.testCaseResults)!r.passed&&r.error&&n.issues.push({skill:a,model:i.model,severity:r.priority==="critical"?"critical":r.priority==="high"?"high":r.priority==="medium"?"medium":"low",type:this.categorizeIssueType(s.validationLevel,r.error),message:r.error,testId:r.testId})}for(let i of t.values()){let s=Array.from(i.passRateByModel.values());i.avgPassRate=s.length>0?s.reduce((a,n)=>a+n,0)/s.length:0}return t}categorizeIssueType(e,t){return t.toLowerCase().includes("timeout")?"timeout":e==="schema"?"schema_failure":e==="validator"?"validator_failure":e==="eval"?"eval_failure":"error"}calculateSummary(e,t){let i=Array.from(e.values()),s=i.filter(n=>n.avgPassRate>=.9).length,a=i.length>0?i.reduce((n,c)=>n+c.avgPassRate,0)/i.length:0;return{totalSkills:i.length,passedSkills:s,failedSkills:i.length-s,avgPassRate:a,totalDurationMs:t.reduce((n,c)=>n+c.durationMs,0),totalTests:i.reduce((n,c)=>n+c.testCount,0),passedTests:i.reduce((n,c)=>n+c.passedTests,0),failedTests:i.reduce((n,c)=>n+c.failedTests,0),modelsUsed:[...new Set(t.map(n=>n.model))]}}async detectCrossModelAnomalies(e){let t=new Map,i=new Map,s=new Map;for(let d of e){t.has(d.model)||(t.set(d.model,[]),i.set(d.model,{totalTests:0,passedTests:0,skillCount:0}));for(let g of d.outcomes){let h=g.testCaseResults.filter(m=>m.passed).length/(g.testCaseResults.length||1);t.get(d.model).push(h);let f=i.get(d.model);f.totalTests+=g.testCaseResults.length,f.passedTests+=g.testCaseResults.filter(m=>m.passed).length,f.skillCount++,s.has(g.skillName)||s.set(g.skillName,{passRates:[],models:[]}),s.get(g.skillName).passRates.push(h),s.get(g.skillName).models.push(d.model)}}let a=[];for(let d of t.values())a.push(...d);let n=a.length>0?a.reduce((d,g)=>d+g,0)/a.length:0,c=a.length>1?a.reduce((d,g)=>d+Math.pow(g-n,2),0)/a.length:0,r=Math.sqrt(c),o=[],l=new Map;for(let[d,g]of t.entries()){let h=g.reduce((v,x)=>v+x,0)/g.length,f=h-n,m=i.get(d);l.set(d,{avgPassRate:h,skillCount:m.skillCount,totalTests:m.totalTests}),Math.abs(f)>this.config.varianceThreshold*2&&o.push({model:d,type:f<0?"low_performance":"high_variance",description:`Model ${d} has ${(f*100).toFixed(1)}% difference from average`,passRate:h,avgPassRate:n,deviation:Math.abs(f)})}let u=[],p=[];for(let[d,g]of s.entries()){if(g.passRates.length<2)continue;let h=g.passRates.reduce((m,v)=>m+v,0)/g.passRates.length;g.passRates.reduce((m,v)=>m+Math.pow(v-h,2),0)/g.passRates.length<this.config.varianceThreshold?u.push(d):p.push(d)}return{variance:c,stdDeviation:r,anomalies:o,consistentSkills:u,inconsistentSkills:p,modelPerformance:l}}async detectRegressions(e,t){let i=[],s=new Set;for(let a of e)for(let n of a.outcomes){let c=`${n.skillName}-${a.model}`;if(s.has(c))continue;s.add(c);let r=await this.learner.getValidationTrends(n.skillName);if(!r)continue;let o=n.testCaseResults.filter(p=>p.passed).length/(n.testCaseResults.length||1),l=r.recentPassRate,u=l-o;u>=t&&i.push({skill:n.skillName,model:a.model,previousPassRate:l,currentPassRate:o,regressionAmount:u,trend:r.overall,possibleCauses:this.analyzePossibleCauses(n,u),severity:this.categorizeRegressionSeverity(u)})}return i.sort((a,n)=>{let c={critical:0,high:1,medium:2,low:3},r=c[a.severity]-c[n.severity];return r!==0?r:n.regressionAmount-a.regressionAmount})}analyzePossibleCauses(e,t){let i=[],s=e.testCaseResults.filter(c=>!c.passed);if(s.length>0){let c=[...new Set(s.map(r=>r.category).filter(Boolean))];c.length>0&&i.push(`Failures in categories: ${c.join(", ")}`)}let a=s.filter(c=>c.priority==="critical");a.length>0&&i.push(`${a.length} critical test(s) failing`);let n=e.testCaseResults.reduce((c,r)=>c+r.reasoningQuality,0)/(e.testCaseResults.length||1);return n<.7&&i.push(`Low reasoning quality score: ${(n*100).toFixed(1)}%`),t>.3&&i.push("Possible model behavior change or prompt drift"),i.length===0&&i.push("No specific cause identified - review test details"),i}categorizeRegressionSeverity(e){return e>=.5?"critical":e>=.3?"high":e>=.15?"medium":"low"}generateRecommendations(e,t,i){let s=[];if(t.inconsistentSkills.length>0&&s.push(`Review ${t.inconsistentSkills.length} skills with inconsistent cross-model behavior: `+t.inconsistentSkills.slice(0,3).join(", ")+(t.inconsistentSkills.length>3?` and ${t.inconsistentSkills.length-3} more`:"")),t.anomalies.some(r=>r.type==="low_performance")){let r=t.anomalies.filter(o=>o.type==="low_performance").map(o=>o.model);s.push(`Investigate low performance on model(s): ${r.join(", ")}`)}let a=i.filter(r=>r.severity==="critical");a.length>0&&s.push(`URGENT: ${a.length} critical regression(s) detected - immediate review required`);let n=Array.from(e.values()).filter(r=>r.avgPassRate<.9);if(n.length>0){let r=n.filter(l=>!l.schemaValid),o=n.filter(l=>!l.validatorPassed);r.length>0&&s.push(`Fix schema validation for: ${r.map(l=>l.skill).slice(0,3).join(", ")}`),o.length>0&&s.push(`Review validator scripts for: ${o.map(l=>l.skill).slice(0,3).join(", ")}`)}return Array.from(e.values()).reduce((r,o)=>r+o.avgPassRate,0)/e.size<.8&&s.push("Overall pass rate below 80% - consider reviewing skill definitions and test expectations"),s.length===0&&s.push("All validations passing - no immediate action required"),s}async updateManifest(e){if(!E(this.manifestPath))throw new Error(`Manifest file not found: ${this.manifestPath}`);let t=C(L(this.manifestPath,"utf-8"));for(let[s,a]of e.skillResults.entries())if(t.skills&&t.skills[s]){let n=t.skills[s];n.validation||(n.validation={}),n.validation.passRate=a.avgPassRate,n.validation.lastValidated=e.timestamp.toISOString(),n.validation.status=a.avgPassRate>=.9?"passing":"failing",n.validation.passRateByModel=Object.fromEntries(a.passRateByModel)}let i=Array.from(e.skillResults.values());t.validationStatus={passing:i.filter(s=>s.avgPassRate>=.9).length,failing:i.filter(s=>s.avgPassRate<.9).length,unknown:0,skipped:t.summary?.tier0||0},t.generatedAt=new Date().toISOString(),t.lastValidationRun={runId:e.runId,timestamp:e.timestamp.toISOString(),avgPassRate:e.summary.avgPassRate,modelsUsed:e.summary.modelsUsed},N(this.manifestPath,JSON.stringify(t,null,2))}generateMarkdownReport(e){let{summary:t,crossModelAnalysis:i,regressions:s,recommendations:a,skillResults:n}=e,c=(t.avgPassRate>=.9||t.avgPassRate>=.7,"`"),r=[];if(r.push(`# Validation Report
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.14");process.exit(0)}
|
|
2
|
+
import{a as T}from"./chunk-STYNOKOM.js";import{c as S}from"./chunk-GUEK5DOK.js";import{b as C,d as P}from"./chunk-DMZ2XOEW.js";import{a as w,c as $}from"./chunk-UIYK4Y7K.js";import{a as b,d as M}from"./chunk-JNLKLC7G.js";$();M();import{randomUUID as D}from"crypto";var V={topology:"hierarchical",maxConcurrentSkills:10,maxConcurrentModels:3,timeout:3e5,continueOnFailure:!0,retry:{maxRetries:2,retryDelayMs:1e3}},R=class{config;learner;skillValidator=null;workers=new Map;taskQueue=[];isRunning=!1;constructor(e,t){this.config={...V,...e},this.learner=t}setSkillValidator(e){this.skillValidator=e}async validateSkillsParallel(e,t,i){let s=Date.now(),a=i?.trustTier??3,n=i?.validationLevel??"eval",c=this.determineTopology(e.length,t.length),r=this.createValidationTasks(e,t,a,n),o=await this.executeTasksParallel(r,c),l=new Map;for(let u of o){let p=l.get(u.skill)||[];p.push(u),l.set(u.skill,p)}return await this.recordOutcomesToLearner(o,a,n),l}async validateSkillCrossModel(e,t,i){return(await this.validateSkillsParallel([e],t,i)).get(e)||[]}getSummary(e){let t=[],i=new Map,s=new Map;for(let[c,r]of e){i.set(c,r);for(let o of r){t.push(o);let l=s.get(o.model)||[];l.push(o),s.set(o.model,l)}}let a=t.filter(c=>c.errors.length===0&&c.evalPassRate>=.9).length,n=t.reduce((c,r)=>c+r.durationMs,0);return{totalSkills:i.size,totalModels:s.size,successCount:a,failureCount:t.length-a,overallPassRate:t.length>0?a/t.length:0,totalDurationMs:n,avgDurationMs:t.length>0?n/t.length:0,topology:this.config.topology,bySkill:i,byModel:s,results:t}}determineTopology(e,t){if(this.config.topology){let i=e*t;return i>20&&this.config.topology==="mesh"&&console.warn(`[SwarmSkillValidator] Large workload (${i} tasks) may be more efficient with hierarchical topology`),this.config.topology}return e>5||e>t*2?"hierarchical":t>5&&e<=3?"mesh":"hierarchical"}createValidationTasks(e,t,i,s){let a=[];for(let n of e)for(let c of t)a.push({id:`${n}-${c}-${Date.now()}-${D().slice(0,8)}`,skill:n,model:c,trustTier:i,validationLevel:s,timeout:this.config.timeout,retryCount:0});return a}async executeTasksParallel(e,t){this.isRunning=!0,this.taskQueue=[...e];let i=[],s=t==="hierarchical"?this.config.maxConcurrentSkills:Math.min(this.config.maxConcurrentSkills*this.config.maxConcurrentModels,e.length),a=[];for(let n=0;n<Math.min(s,e.length);n++){let c=`worker-${n}`;this.workers.set(c,{id:c,task:null,status:"idle"}),a.push(this.runWorker(c,i))}return await Promise.all(a),this.isRunning=!1,this.workers.clear(),i}async runWorker(e,t){let i=this.workers.get(e);if(i){for(;this.taskQueue.length>0&&this.isRunning;){let s=this.taskQueue.shift();if(!s)break;i.task=s,i.status="running",i.startTime=Date.now();try{let a=await this.executeValidationTask(s);t.push(a),i.result=a,i.status="completed"}catch(a){let n=this.createErrorResult(s,a);this.config.retry&&s.retryCount<this.config.retry.maxRetries&&this.config.continueOnFailure?(s.retryCount++,this.taskQueue.push(s),await this.delay(this.config.retry.retryDelayMs)):(t.push(n),i.result=n,i.status="failed")}}i.task=null,i.status="idle"}}async executeValidationTask(e){let t=Date.now();if(!this.skillValidator)return this.createSimulatedResult(e,t);let i=new Promise((n,c)=>{setTimeout(()=>c(new Error(`Validation timeout after ${e.timeout}ms`)),e.timeout)}),s=await Promise.race([this.skillValidator(e.skill,e.model,{trustTier:e.trustTier,validationLevel:e.validationLevel,timeout:e.timeout}),i]),a=Date.now()-t;return this.outcomeToResult(s,e,a)}outcomeToResult(e,t,i){let s=e.testCaseResults.filter(c=>c.passed).length,a=e.testCaseResults.length,n=a>0?s/a:e.score;return{skill:t.skill,model:t.model,schemaValid:e.validationLevel!=="schema"||e.passed,validatorPassed:e.validationLevel!=="validator"||e.passed,evalPassRate:n,durationMs:i,errors:e.passed?[]:["Validation failed"],trustTier:t.trustTier,validationLevel:t.validationLevel,retryCount:t.retryCount,timestamp:new Date}}createSimulatedResult(e,t){let i=Date.now()-t+b()*100,s=.85+b()*.15;return{skill:e.skill,model:e.model,schemaValid:!0,validatorPassed:s>.8,evalPassRate:s,durationMs:i,errors:s>.8?[]:["Simulated validation failure"],trustTier:e.trustTier,validationLevel:e.validationLevel,retryCount:e.retryCount,timestamp:new Date}}createErrorResult(e,t){let i=w(t);return{skill:e.skill,model:e.model,schemaValid:!1,validatorPassed:!1,evalPassRate:0,durationMs:0,errors:[i],trustTier:e.trustTier,validationLevel:e.validationLevel,retryCount:e.retryCount,timestamp:new Date}}async recordOutcomesToLearner(e,t,i){for(let s of e){let a={skillName:s.skill,trustTier:s.trustTier||t,validationLevel:s.validationLevel||i,model:s.model,passed:s.errors.length===0&&s.evalPassRate>=.9,score:s.evalPassRate,testCaseResults:this.createTestCaseResults(s),timestamp:s.timestamp,runId:`swarm-${Date.now()}`,metadata:{duration:s.durationMs,retryCount:s.retryCount}};await this.learner.recordValidationOutcome(a)}}createTestCaseResults(e){return[{testId:`${e.skill}-${e.model}-aggregate`,passed:e.errors.length===0,expectedPatterns:["valid-output"],actualPatterns:e.errors.length===0?["valid-output"]:[],reasoningQuality:e.evalPassRate,executionTimeMs:e.durationMs,category:"swarm-validation",priority:"high",error:e.errors.length>0?e.errors.join("; "):void 0}]}delay(e){return new Promise(t=>setTimeout(t,e))}getConfig(){return{...this.config}}isValidationRunning(){return this.isRunning}getWorkerStatus(){return Array.from(this.workers.values())}cancel(){this.isRunning=!1,this.taskQueue=[]}};function A(y,e){return new R(y,e)}var F=["security-testing","accessibility-testing","api-testing","performance-testing","visual-regression-testing","mutation-testing","contract-testing","chaos-testing","compliance-testing","penetration-testing"],I=["claude-sonnet","claude-haiku","claude-opus"];P();import{readFileSync as L,writeFileSync as N,existsSync as E}from"fs";var O={varianceThreshold:.04,regressionThreshold:.1,minSamples:3,autoUpdateManifest:!1},k=class{constructor(e,t,i={}){this.learner=e;this.manifestPath=t;this.config={...O,...i}}learner;manifestPath;config;async aggregateResults(e){let t=`agg-${Date.now()}`,i=new Date,s=this.buildSkillResultsMap(e),a=this.calculateSummary(s,e),n=await this.detectCrossModelAnomalies(e),c=await this.detectRegressions(e,this.config.regressionThreshold),r=this.generateRecommendations(s,n,c),o={timestamp:i,runId:t,summary:a,skillResults:s,crossModelAnalysis:n,regressions:c,recommendations:r,metadata:{version:"1.0.0",environment:e[0]?.metadata?.environment,generatedBy:"ValidationResultAggregator",inputs:{runIds:e.map(l=>l.runId),models:[...new Set(e.map(l=>l.model))]}}};return this.config.autoUpdateManifest&&await this.updateManifest(o),o}buildSkillResultsMap(e){let t=new Map;for(let i of e)for(let s of i.outcomes){let a=s.skillName;t.has(a)||t.set(a,{skill:a,trustTier:s.trustTier,passRateByModel:new Map,avgPassRate:0,schemaValid:!0,validatorPassed:!0,evalPassed:!0,issues:[],executionTimeMs:0,testCount:0,passedTests:0,failedTests:0});let n=t.get(a),c=s.testCaseResults.filter(r=>r.passed).length/(s.testCaseResults.length||1);n.passRateByModel.set(i.model,c),n.testCount+=s.testCaseResults.length,n.passedTests+=s.testCaseResults.filter(r=>r.passed).length,n.failedTests+=s.testCaseResults.filter(r=>!r.passed).length,n.executionTimeMs+=s.metadata?.duration||0,s.validationLevel==="schema"&&!s.passed&&(n.schemaValid=!1),s.validationLevel==="validator"&&!s.passed&&(n.validatorPassed=!1),s.validationLevel==="eval"&&!s.passed&&(n.evalPassed=!1);for(let r of s.testCaseResults)!r.passed&&r.error&&n.issues.push({skill:a,model:i.model,severity:r.priority==="critical"?"critical":r.priority==="high"?"high":r.priority==="medium"?"medium":"low",type:this.categorizeIssueType(s.validationLevel,r.error),message:r.error,testId:r.testId})}for(let i of t.values()){let s=Array.from(i.passRateByModel.values());i.avgPassRate=s.length>0?s.reduce((a,n)=>a+n,0)/s.length:0}return t}categorizeIssueType(e,t){return t.toLowerCase().includes("timeout")?"timeout":e==="schema"?"schema_failure":e==="validator"?"validator_failure":e==="eval"?"eval_failure":"error"}calculateSummary(e,t){let i=Array.from(e.values()),s=i.filter(n=>n.avgPassRate>=.9).length,a=i.length>0?i.reduce((n,c)=>n+c.avgPassRate,0)/i.length:0;return{totalSkills:i.length,passedSkills:s,failedSkills:i.length-s,avgPassRate:a,totalDurationMs:t.reduce((n,c)=>n+c.durationMs,0),totalTests:i.reduce((n,c)=>n+c.testCount,0),passedTests:i.reduce((n,c)=>n+c.passedTests,0),failedTests:i.reduce((n,c)=>n+c.failedTests,0),modelsUsed:[...new Set(t.map(n=>n.model))]}}async detectCrossModelAnomalies(e){let t=new Map,i=new Map,s=new Map;for(let d of e){t.has(d.model)||(t.set(d.model,[]),i.set(d.model,{totalTests:0,passedTests:0,skillCount:0}));for(let g of d.outcomes){let h=g.testCaseResults.filter(m=>m.passed).length/(g.testCaseResults.length||1);t.get(d.model).push(h);let f=i.get(d.model);f.totalTests+=g.testCaseResults.length,f.passedTests+=g.testCaseResults.filter(m=>m.passed).length,f.skillCount++,s.has(g.skillName)||s.set(g.skillName,{passRates:[],models:[]}),s.get(g.skillName).passRates.push(h),s.get(g.skillName).models.push(d.model)}}let a=[];for(let d of t.values())a.push(...d);let n=a.length>0?a.reduce((d,g)=>d+g,0)/a.length:0,c=a.length>1?a.reduce((d,g)=>d+Math.pow(g-n,2),0)/a.length:0,r=Math.sqrt(c),o=[],l=new Map;for(let[d,g]of t.entries()){let h=g.reduce((v,x)=>v+x,0)/g.length,f=h-n,m=i.get(d);l.set(d,{avgPassRate:h,skillCount:m.skillCount,totalTests:m.totalTests}),Math.abs(f)>this.config.varianceThreshold*2&&o.push({model:d,type:f<0?"low_performance":"high_variance",description:`Model ${d} has ${(f*100).toFixed(1)}% difference from average`,passRate:h,avgPassRate:n,deviation:Math.abs(f)})}let u=[],p=[];for(let[d,g]of s.entries()){if(g.passRates.length<2)continue;let h=g.passRates.reduce((m,v)=>m+v,0)/g.passRates.length;g.passRates.reduce((m,v)=>m+Math.pow(v-h,2),0)/g.passRates.length<this.config.varianceThreshold?u.push(d):p.push(d)}return{variance:c,stdDeviation:r,anomalies:o,consistentSkills:u,inconsistentSkills:p,modelPerformance:l}}async detectRegressions(e,t){let i=[],s=new Set;for(let a of e)for(let n of a.outcomes){let c=`${n.skillName}-${a.model}`;if(s.has(c))continue;s.add(c);let r=await this.learner.getValidationTrends(n.skillName);if(!r)continue;let o=n.testCaseResults.filter(p=>p.passed).length/(n.testCaseResults.length||1),l=r.recentPassRate,u=l-o;u>=t&&i.push({skill:n.skillName,model:a.model,previousPassRate:l,currentPassRate:o,regressionAmount:u,trend:r.overall,possibleCauses:this.analyzePossibleCauses(n,u),severity:this.categorizeRegressionSeverity(u)})}return i.sort((a,n)=>{let c={critical:0,high:1,medium:2,low:3},r=c[a.severity]-c[n.severity];return r!==0?r:n.regressionAmount-a.regressionAmount})}analyzePossibleCauses(e,t){let i=[],s=e.testCaseResults.filter(c=>!c.passed);if(s.length>0){let c=[...new Set(s.map(r=>r.category).filter(Boolean))];c.length>0&&i.push(`Failures in categories: ${c.join(", ")}`)}let a=s.filter(c=>c.priority==="critical");a.length>0&&i.push(`${a.length} critical test(s) failing`);let n=e.testCaseResults.reduce((c,r)=>c+r.reasoningQuality,0)/(e.testCaseResults.length||1);return n<.7&&i.push(`Low reasoning quality score: ${(n*100).toFixed(1)}%`),t>.3&&i.push("Possible model behavior change or prompt drift"),i.length===0&&i.push("No specific cause identified - review test details"),i}categorizeRegressionSeverity(e){return e>=.5?"critical":e>=.3?"high":e>=.15?"medium":"low"}generateRecommendations(e,t,i){let s=[];if(t.inconsistentSkills.length>0&&s.push(`Review ${t.inconsistentSkills.length} skills with inconsistent cross-model behavior: `+t.inconsistentSkills.slice(0,3).join(", ")+(t.inconsistentSkills.length>3?` and ${t.inconsistentSkills.length-3} more`:"")),t.anomalies.some(r=>r.type==="low_performance")){let r=t.anomalies.filter(o=>o.type==="low_performance").map(o=>o.model);s.push(`Investigate low performance on model(s): ${r.join(", ")}`)}let a=i.filter(r=>r.severity==="critical");a.length>0&&s.push(`URGENT: ${a.length} critical regression(s) detected - immediate review required`);let n=Array.from(e.values()).filter(r=>r.avgPassRate<.9);if(n.length>0){let r=n.filter(l=>!l.schemaValid),o=n.filter(l=>!l.validatorPassed);r.length>0&&s.push(`Fix schema validation for: ${r.map(l=>l.skill).slice(0,3).join(", ")}`),o.length>0&&s.push(`Review validator scripts for: ${o.map(l=>l.skill).slice(0,3).join(", ")}`)}return Array.from(e.values()).reduce((r,o)=>r+o.avgPassRate,0)/e.size<.8&&s.push("Overall pass rate below 80% - consider reviewing skill definitions and test expectations"),s.length===0&&s.push("All validations passing - no immediate action required"),s}async updateManifest(e){if(!E(this.manifestPath))throw new Error(`Manifest file not found: ${this.manifestPath}`);let t=C(L(this.manifestPath,"utf-8"));for(let[s,a]of e.skillResults.entries())if(t.skills&&t.skills[s]){let n=t.skills[s];n.validation||(n.validation={}),n.validation.passRate=a.avgPassRate,n.validation.lastValidated=e.timestamp.toISOString(),n.validation.status=a.avgPassRate>=.9?"passing":"failing",n.validation.passRateByModel=Object.fromEntries(a.passRateByModel)}let i=Array.from(e.skillResults.values());t.validationStatus={passing:i.filter(s=>s.avgPassRate>=.9).length,failing:i.filter(s=>s.avgPassRate<.9).length,unknown:0,skipped:t.summary?.tier0||0},t.generatedAt=new Date().toISOString(),t.lastValidationRun={runId:e.runId,timestamp:e.timestamp.toISOString(),avgPassRate:e.summary.avgPassRate,modelsUsed:e.summary.modelsUsed},N(this.manifestPath,JSON.stringify(t,null,2))}generateMarkdownReport(e){let{summary:t,crossModelAnalysis:i,regressions:s,recommendations:a,skillResults:n}=e,c=(t.avgPassRate>=.9||t.avgPassRate>=.7,"`"),r=[];if(r.push(`# Validation Report
|
|
3
3
|
|
|
4
4
|
> ${c} Generated: ${e.timestamp.toISOString()}
|
|
5
5
|
> Run ID: ${e.runId}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{a as n}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.14");process.exit(0)}
|
|
2
|
+
import{a as n}from"./chunk-VQB5SLXZ.js";import{a as o}from"./chunk-A2TK52B2.js";import{a,e as c}from"./chunk-WE7KIXR6.js";c();var M=a.CLEANUP_INTERVAL_MS,y=".agentic-qe/memory.db";async function d(r,t=!0){let e;switch(r.type){case"memory":e=new o;break;case"sqlite":e=new n({sqlite:r.sqlite,enableFallback:!0});break;case"agentdb":e=new n({sqlite:{path:r.agentdb?.path??y},enableFallback:!0});break;case"hybrid":e=new n(r.hybrid);break;default:throw new Error(`Unknown memory backend type: ${r.type}`)}return t&&await e.initialize(),{backend:e,type:r.type,initialized:t}}async function u(r=!0){let t=process.env.AQE_MEMORY_BACKEND??"memory",e=process.env.AQE_MEMORY_PATH??".agentic-qe",i={type:t,sqlite:{path:`${e}/memory.db`,walMode:!0},agentdb:{path:`${e}/memory.db`},hybrid:{enableFallback:!0,sqlite:{path:`${e}/memory.db`}}};return d(i,r)}export{d as a,u as b};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{c as t,e as o}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.14");process.exit(0)}
|
|
2
|
+
import{c as t,e as o}from"./chunk-DGUAAG3T.js";var L={};o(L,{DotProductAttention:()=>d,FlashAttention:()=>u,HyperbolicAttention:()=>f,LinearAttention:()=>h,MoEAttention:()=>_,MultiHeadAttention:()=>A,RuvectorLayer:()=>a,SonaEngine:()=>b,TensorCompress:()=>c,default:()=>n,differentiableSearch:()=>l,getCompressionLevel:()=>p,hierarchicalForward:()=>s,init:()=>m,pipeline:()=>q});import{createRequire as r}from"module";var i,e,n,a,c,l,s,p,m,u,d,A,f,h,_,b,q,g=t(()=>{i=r(import.meta.url),e=i("better-sqlite3"),n=e,{RuvectorLayer:a,TensorCompress:c,differentiableSearch:l,hierarchicalForward:s,getCompressionLevel:p,init:m,FlashAttention:u,DotProductAttention:d,MultiHeadAttention:A,HyperbolicAttention:f,LinearAttention:h,MoEAttention:_,SonaEngine:b,pipeline:q}=e||{}});export{n as a,a as b,c,l as d,s as e,p as f,m as g,u as h,d as i,A as j,f as k,h as l,_ as m,b as n,q as o,L as p,g as q};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.14");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,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{a as ie,b as ae}from"./chunk-JOCR5TWI.js";import{S as oe,i as j,p as q}from"./chunk-W2YCNX4O.js";import{c as g,e as D,g as $}from"./chunk-ERGY45RL.js";var I,E=g(()=>{"use strict";I={dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"}});function se(){if(z)return A!==null;try{let i=(ae(),$(ie));if(A=i.differentiableSearch,P=i.init,P)try{P()}catch{}return z=!0,!0}catch{return z=!0,!1}}function B(i){let e=0;for(let r=0;r<i.length;r++)e+=i[r]*i[r];return Math.sqrt(e)}function ce(i,e,r,t){let n=r*t;if(n===0)return 0;let a=0,o=Math.min(i.length,e.length);for(let c=0;c<o;c++)a+=i[c]*e[c];return a/n}function U(i,e){let r=0,t=Math.min(i.length,e.length);for(let n=0;n<t;n++){let a=i[n]-e[n];r+=a*a}return Math.sqrt(r)}function le(i,e){if(i.length===e)return i;let r=new Float32Array(e);if(i.length>e){let t=i.length/e;for(let n=0;n<e;n++){let a=Math.floor(n*t),o=Math.floor((n+1)*t),c=0;for(let s=a;s<o;s++)c+=i[s];r[n]=c/(o-a)}}else for(let t=0;t<i.length;t++)r[t]=i[t];return r}var A,P,z,S,O=g(()=>{"use strict";E();A=null,P=null,z=!1;S=class{config;entries=[];idToIndex=new Map;hasRuvector=!1;loaded=!1;constructor(e){this.config={...I,...e}}ensureLoaded(){this.loaded||(this.hasRuvector=se(),this.loaded=!0)}normalizeVector(e){return e.length===this.config.dimensions?e:le(e,this.config.dimensions)}add(e,r,t){this.ensureLoaded();let n=this.normalizeVector(r),a=B(n);if(this.idToIndex.has(e)){let c=this.idToIndex.get(e);this.entries[c]={id:e,vector:n,norm:a,metadata:t};return}let o=this.entries.length;this.entries.push({id:e,vector:n,norm:a,metadata:t}),this.idToIndex.set(e,o)}search(e,r){if(this.ensureLoaded(),this.entries.length===0)return[];let t=this.normalizeVector(e),n=B(t),a=Math.min(r,this.entries.length),o=this.entries.length>0?this.entries[0].vector.length:0,c=t.length===o;if(this.config.metric==="cosine")return this.bruteForcSearch(t,n,a);if(this.hasRuvector&&c&&A)try{let s=this.entries.map(u=>u.vector),l=A(t,s,a,1).indices.map(u=>{let h=this.entries[u],m=-U(t,h.vector);return{id:h.id,score:m,metadata:h.metadata}});return l.sort((u,h)=>h.score-u.score),l}catch{}return this.bruteForcSearch(t,n,a)}bruteForcSearch(e,r,t){let n=[];for(let a of this.entries){let o;this.config.metric==="cosine"?o=ce(e,a.vector,r,a.norm):o=-U(e,a.vector),n.push({id:a.id,score:o,metadata:a.metadata})}return n.sort((a,o)=>o.score-a.score),n.slice(0,t)}remove(e){let r=this.idToIndex.get(e);if(r===void 0)return!1;let t=this.entries.length-1;if(r!==t){let n=this.entries[t];this.entries[r]=n,this.idToIndex.set(n.id,r)}return this.entries.pop(),this.idToIndex.delete(e),!0}size(){return this.entries.length}dimensions(){return this.config.dimensions}recall(){return this.hasRuvector,1}isRuvectorAvailable(){return this.ensureLoaded(),this.hasRuvector}getConfig(){return{...this.config}}clear(){this.entries=[],this.idToIndex.clear()}dispose(){this.clear()}}});import{createRequire as he}from"module";function de(){if(K){if(k)return k;throw new b(J??"Unknown load error")}K=!0;try{let i=ue("hnswlib-node");if(!i.HierarchicalNSW)throw new Error("hnswlib-node module missing HierarchicalNSW export");return k=i,k}catch(i){let e=i instanceof Error?i.message:String(i);throw J=e,new b(e)}}function me(i,e){if(i.length===e)return i;let r=new Float32Array(e);if(i.length>e){let t=i.length/e;for(let n=0;n<e;n++){let a=Math.floor(n*t),o=Math.floor((n+1)*t),c=0;for(let s=a;s<o;s++)c+=i[s];r[n]=c/(o-a)}}else for(let t=0;t<i.length;t++)r[t]=i[t];return r}function Q(i){let e=new Array(i.length);for(let r=0;r<i.length;r++)e[r]=i[r];return e}var ue,b,k,K,J,X,H,Y=g(()=>{"use strict";E();ue=he(import.meta.url),b=class extends Error{constructor(e){super(`Native HNSW backend unavailable: ${e}`),this.name="NativeHnswUnavailableError"}},k=null,K=!1,J=null;X=1e4,H=class{config;nativeIndex=null;currentMaxElements=X;liveIds=new Set;metadataStore=new Map;_metrics={totalSearches:0,totalAdds:0,totalRemoves:0,avgSearchLatencyMs:0,maxSearchLatencyMs:0,lastSearchLatencyMs:0,fallbackSearchCount:0,bruteForceSearchCount:0,nativeSearchCount:0,fallbackRate:0,allSearchesBruteForce:!1};constructor(e){this.config={...I,...e},this.nativeIndex=this.createFreshIndex()}createFreshIndex(){let e=de(),r=this.config.metric==="euclidean"?"l2":"cosine";try{let t=new e.HierarchicalNSW(r,this.config.dimensions);return t.initIndex(this.currentMaxElements,this.config.M,this.config.efConstruction,100,!0),t.setEf(this.config.efSearch),t}catch(t){let n=t instanceof Error?t.message:String(t);throw new b(`HierarchicalNSW init failed: ${n}`)}}add(e,r,t){if(!this.nativeIndex)throw new Error("NativeHnswBackend has been disposed");let n=this.normalizeVector(r);if(!this.liveIds.has(e)&&this.liveIds.size>=this.currentMaxElements){let a=this.currentMaxElements*2;this.nativeIndex.resizeIndex(a),this.currentMaxElements=a}this.nativeIndex.addPoint(Q(n),e,!0),this.liveIds.add(e),t?this.metadataStore.set(e,t):this.metadataStore.delete(e),this._metrics.totalAdds++}search(e,r){if(!this.nativeIndex)throw new Error("NativeHnswBackend has been disposed");if(this.liveIds.size===0||r<=0)return[];let t=performance.now(),n=this.normalizeVector(e),a=Math.min(r,this.liveIds.size),o=Math.min(a*2,this.liveIds.size),c=this.nativeIndex.searchKnn(Q(n),o),s=this.config.metric==="cosine",d=new Map;for(let h=0;h<c.neighbors.length;h++){let m=c.neighbors[h];if(!this.liveIds.has(m))continue;let x=c.distances[h],f=s?1-x:-x,W=d.get(m);(W===void 0||f>W.score)&&d.set(m,{id:m,score:f,metadata:this.metadataStore.get(m)})}let l=Array.from(d.values());l.sort((h,m)=>m.score-h.score),l.length>a&&(l.length=a);let u=performance.now()-t;return this.updateSearchMetrics(u),this._metrics.nativeSearchCount=this._metrics.totalSearches,u>50&&console.warn(`[NativeHNSW] search took ${u.toFixed(1)}ms (k=${r}, results=${l.length})`),l}remove(e){if(!this.nativeIndex||!this.liveIds.has(e))return!1;try{this.nativeIndex.markDelete(e)}catch{return!1}return this.liveIds.delete(e),this.metadataStore.delete(e),this._metrics.totalRemoves++,!0}size(){return this.liveIds.size}dimensions(){return this.config.dimensions}recall(){return .99}getMetrics(){return{...this._metrics}}get lastSearchLatencyMs(){return this._metrics.lastSearchLatencyMs}getConfig(){return{...this.config}}clear(){this.nativeIndex&&(this.liveIds.clear(),this.metadataStore.clear(),this.currentMaxElements=X,this.nativeIndex=this.createFreshIndex())}dispose(){this.liveIds.clear(),this.metadataStore.clear(),this.nativeIndex=null}isNativeAvailable(){return this.nativeIndex!==null}normalizeVector(e){return e.length===this.config.dimensions?e:me(e,this.config.dimensions)}updateSearchMetrics(e){this._metrics.totalSearches++,this._metrics.lastSearchLatencyMs=e,e>this._metrics.maxSearchLatencyMs&&(this._metrics.maxSearchLatencyMs=e);let r=this._metrics.totalSearches;this._metrics.avgSearchLatencyMs=this._metrics.avgSearchLatencyMs*((r-1)/r)+e/r}}});function Z(i,e){let r=Array.from({length:e},()=>new Float64Array(e));for(let t=0;t<e;t++){let n=i[t].length;r[t][t]=n;for(let a of i[t])r[t][a]=-1}return r}function N(i,e){let r=e.length,t=new Float64Array(r);for(let n=0;n<r;n++){let a=i[n].length;t[n]=a*e[n];for(let o of i[n])t[n]-=e[o]}return t}function w(i){let e=0;for(let r=0;r<i.length;r++)e+=i[r]*i[r];return Math.sqrt(e)}function R(i){let e=w(i);if(e>0)for(let r=0;r<i.length;r++)i[r]/=e}function v(i,e){let r=0;for(let t=0;t<i.length;t++)r+=i[t]*e[t];for(let t=0;t<i.length;t++)i[t]-=r*e[t]}function y(i,e,r=100,t=1e-6){if(e<=1)return 0;if(e===2)return i[0].includes(1)?2:0;let n=new Float64Array(e).fill(1/Math.sqrt(e)),a=new Float64Array(e);for(let l=0;l<e;l++)a[l]=Math.random()-.5;v(a,n),R(a);let o=0;for(let l=0;l<30;l++){let u=N(i,a);if(v(u,n),o=w(u),o>0)for(let h=0;h<e;h++)a[h]=u[h]/o}if(o<t)return 0;let c=new Float64Array(e);for(let l=0;l<e;l++)c[l]=Math.random()-.5;v(c,n),R(c);let s=0;for(let l=0;l<r;l++){let u=N(i,c),h=new Float64Array(e);for(let f=0;f<e;f++)h[f]=o*c[f]-u[f];v(h,n);let m=w(h);if(m<t)break;let x=m;for(let f=0;f<e;f++)c[f]=h[f]/m;if(Math.abs(x-s)<t)break;s=x}let d=o-s;return Math.max(0,d)}function F(i,e,r=100,t=1e-6){return y(i,e,r,t)}function C(i,e,r=50,t){if(e<=1)return 0;let n=t??y(i,e);if(n<1e-10)return 1/0;let o=2*Math.max(...i.map(d=>d.length),1),s=2*(Math.log(o/n)/(o-n));return Math.max(0,s)}function M(i,e,r){let t=1-Math.exp(-i/.05),n=1-Math.exp(-e/.5),a=r===1/0?0:1/(1+r/5),o=.4*t+.3*n+.3*a;return Math.max(0,Math.min(1,o))}var _=g(()=>{"use strict"});var re={};D(re,{ALERT_THRESHOLDS:()=>fe,DEFAULT_HNSW_HEALTH_CONFIG:()=>ee,HnswHealthMonitor:()=>L,_resetNativeLoader:()=>be,approximateFiedlerValue:()=>y,approximateSpectralGap:()=>F,buildAdjacencyFromIndex:()=>te,buildLaplacian:()=>Z,computeCoherenceScore:()=>M,createHnswHealthMonitor:()=>ge,deflateVector:()=>v,estimateEffectiveResistance:()=>C,laplacianMultiply:()=>N,normalizeInPlace:()=>R,vectorNorm:()=>w});function pe(){return V?T:(V=!0,T=null,null)}function be(){T=null,V=!1}function te(i,e=16,r){let t=i.size();if(t===0)return{adjacency:[],nodeCount:0,adjacencySource:"approximate"};let n=Array.from({length:t},()=>[]),a=Math.min(e,t-1);if(a===0)return{adjacency:n,nodeCount:t,adjacencySource:"approximate"};if(r&&r.size>0){let o=Array.from(r.keys()).slice(0,t),c=new Map;for(let s=0;s<o.length;s++)c.set(o[s],s);for(let s=0;s<o.length;s++){let d=r.get(o[s]);if(!d)continue;let l=i.search(d,a+1);for(let u of l){if(u.id===o[s])continue;let h=c.get(u.id);h!==void 0&&(n[s].includes(h)||n[s].push(h),n[h].includes(s)||n[h].push(s))}}return{adjacency:n,nodeCount:t,adjacencySource:"actual-search"}}console.warn("[HnswHealthMonitor] No stored vectors provided \u2014 using approximate circular adjacency. Pass stored vectors for accurate health metrics.");for(let o=0;o<t;o++)for(let c=0;c<a;c++){let s=(o+c+1)%t;n[o].includes(s)||n[o].push(s),n[s].includes(o)||n[s].push(o)}return{adjacency:n,nodeCount:t,adjacencySource:"approximate"}}function ge(i){return new L(i)}var ee,fe,T,V,L,ne=g(()=>{"use strict";_();_();ee={fiedlerThreshold:.01,spectralGapThreshold:.1,resistanceThreshold:10,coherenceThreshold:.3,maxPowerIterations:100,convergenceTolerance:1e-6,resistanceSampleSize:50,maxHistoryEntries:200,minIndexSize:3},fe={FragileIndex:.01,PoorExpansion:.1,HighResistance:10,LowCoherence:.3},T=null,V=!1;L=class{config;alerts=[];history=[];lastReport=null;useNative=!1;nativeChecked=!1;constructor(e){this.config={...ee,...e}}checkHealth(e){let r=performance.now(),t=e.size();if(t<this.config.minIndexSize)return this.createSmallIndexReport(t,performance.now()-r);this.nativeChecked||(this.nativeChecked=!0,this.useNative=pe()!==null);let{adjacency:n,nodeCount:a,adjacencySource:o}=te(e),c=this.useNative?this.computeNativeMetrics(n):this.computeApproximateMetrics(n,a),s=this.generateAlerts(c);this.alerts.length=0,this.alerts.push(...s);let d=performance.now()-r,l={healthy:s.length===0,metrics:c,alerts:s,indexSize:t,usedNativeBackend:this.useNative,adjacencySource:o,checkDurationMs:d,checkedAt:new Date};return this.addHistoryPoint({coherenceScore:c.coherenceScore,fiedlerValue:c.fiedlerValue,indexSize:t,healthy:l.healthy,timestamp:l.checkedAt}),this.lastReport=l,l}getAlerts(){return[...this.alerts]}getMetricsHistory(e){let r=[...this.history];return e!==void 0&&e<r.length?r.slice(-e):r}isHealthy(){return this.lastReport===null?!0:this.lastReport.healthy}getLastReport(){return this.lastReport}clearHistory(){this.history.length=0,this.alerts.length=0,this.lastReport=null}computeNativeMetrics(e){let r=T,t=r.computeFiedlerValue(e),n=r.computeSpectralGap(e),a=r.computeEffectiveResistance(e),o=M(t,n,a);return{fiedlerValue:t,spectralGap:n,effectiveResistance:a,coherenceScore:o}}computeApproximateMetrics(e,r){let t=y(e,r,this.config.maxPowerIterations,this.config.convergenceTolerance),n=F(e,r,this.config.maxPowerIterations,this.config.convergenceTolerance),a=C(e,r,this.config.resistanceSampleSize,t),o=M(t,n,a);return{fiedlerValue:t,spectralGap:n,effectiveResistance:a,coherenceScore:o}}generateAlerts(e){let r=[],t=new Date;return e.fiedlerValue<this.config.fiedlerThreshold&&r.push({type:"FragileIndex",message:`Fiedler value ${e.fiedlerValue.toFixed(6)} is below threshold ${this.config.fiedlerThreshold}. The index graph has weak algebraic connectivity.`,value:e.fiedlerValue,threshold:this.config.fiedlerThreshold,timestamp:t}),e.spectralGap<this.config.spectralGapThreshold&&r.push({type:"PoorExpansion",message:`Spectral gap ${e.spectralGap.toFixed(6)} is below threshold ${this.config.spectralGapThreshold}. The index graph has poor expansion properties.`,value:e.spectralGap,threshold:this.config.spectralGapThreshold,timestamp:t}),e.effectiveResistance>this.config.resistanceThreshold&&r.push({type:"HighResistance",message:`Average effective resistance ${e.effectiveResistance.toFixed(4)} exceeds threshold ${this.config.resistanceThreshold}. Nodes are poorly connected.`,value:e.effectiveResistance,threshold:this.config.resistanceThreshold,timestamp:t}),e.coherenceScore<this.config.coherenceThreshold&&r.push({type:"LowCoherence",message:`Coherence score ${e.coherenceScore.toFixed(4)} is below threshold ${this.config.coherenceThreshold}. Overall index health is degraded.`,value:e.coherenceScore,threshold:this.config.coherenceThreshold,timestamp:t}),r}createSmallIndexReport(e,r){let t={fiedlerValue:e>0?1:0,spectralGap:e>0?1:0,effectiveResistance:e>0?.5:0,coherenceScore:e>0?1:0},n={healthy:!0,metrics:t,alerts:[],indexSize:e,usedNativeBackend:!1,adjacencySource:"approximate",checkDurationMs:r,checkedAt:new Date};return this.addHistoryPoint({coherenceScore:t.coherenceScore,fiedlerValue:t.fiedlerValue,indexSize:e,healthy:!0,timestamp:n.checkedAt}),this.lastReport=n,n}addHistoryPoint(e){this.history.push(e),this.history.length>this.config.maxHistoryEntries&&this.history.splice(0,this.history.length-this.config.maxHistoryEntries)}}});var ye={};D(ye,{HnswAdapter:()=>G});var ve,p,G,xe=g(()=>{O();Y();oe();ve={patterns:{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"},"qe-memory":{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"},learning:{dimensions:384,M:16,efConstruction:200,efSearch:50,metric:"cosine"},coverage:{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"}},p=new Map,G=class i{backend;_isNativeBackend;indexName;stringToNumericId=new Map;numericToStringId=new Map;nextAutoId=0;healthMonitor=null;healthMonitorLoaded=!1;operationsSinceLastCheck=0;healthCheckFrequency=100;lastHealthReport=null;constructor(e,r){this.indexName=e;let n={...ve[e]??{},...r},{backend:a,isNative:o}=i.createBackend(n);this.backend=a,this._isNativeBackend=o}add(e,r,t){this.backend.add(e,r,t),this.maybeRunHealthCheck()}search(e,r){let t=performance.now(),n=this.backend.search(e,r),a=performance.now()-t;return a>50&&console.warn(`[HNSW] search took ${a.toFixed(1)}ms (k=${r}, results=${n.length})`),this._lastSearchLatencyMs=a,n}_lastSearchLatencyMs=0;get lastSearchLatencyMs(){return this._lastSearchLatencyMs}remove(e){return this.backend.remove(e)}size(){return this.backend.size()}dimensions(){return this.backend.dimensions()}recall(){return this.backend.recall()}addByStringId(e,r){let t=this.stringToNumericId.get(e);t!==void 0?this.backend.remove(t):(t=this.nextAutoId++,this.stringToNumericId.set(e,t),this.numericToStringId.set(t,e)),this.backend.add(t,new Float32Array(r))}searchByArray(e,r){return this.backend.search(new Float32Array(e),r).map(n=>({id:this.numericToStringId.get(n.id)??String(n.id),score:n.score}))}removeByStringId(e){let r=this.stringToNumericId.get(e);if(r===void 0)return!1;let t=this.backend.remove(r);return t&&(this.stringToNumericId.delete(e),this.numericToStringId.delete(r)),t}clear(){this.backend.clear?.(),this.stringToNumericId.clear(),this.numericToStringId.clear(),this.nextAutoId=0}dispose(){try{this.backend.dispose?.()}catch{}this.stringToNumericId.clear(),this.numericToStringId.clear(),this.nextAutoId=0}isRuvectorAvailable(){return this.backend instanceof S?this.backend.isRuvectorAvailable():this.backend instanceof H?this.backend.isNativeAvailable():!1}isNativeBackend(){return this._isNativeBackend}getName(){return this.indexName}setHealthCheckFrequency(e){this.healthCheckFrequency=Math.max(1,e)}getHealthCheckFrequency(){return this.healthCheckFrequency}getLastHealthReport(){return this.lastHealthReport}getHealthMonitor(){return this.healthMonitor}maybeRunHealthCheck(){if(q()&&(this.operationsSinceLastCheck++,!(this.operationsSinceLastCheck<this.healthCheckFrequency)&&(this.operationsSinceLastCheck=0,this.ensureHealthMonitor(),this.healthMonitor)))try{this.lastHealthReport=this.healthMonitor.checkHealth(this.backend),this.lastHealthReport.healthy||console.warn(`[HNSW-Health] Index "${this.indexName}" health check failed: ${this.lastHealthReport.alerts.length} alert(s). Coherence: ${this.lastHealthReport.metrics.coherenceScore.toFixed(3)}`)}catch(e){console.warn(`[HNSW-Health] Health check error for "${this.indexName}":`,e)}}ensureHealthMonitor(){if(!this.healthMonitorLoaded){this.healthMonitorLoaded=!0;try{let e=(ne(),$(re));this.healthMonitor=e.createHnswHealthMonitor()}catch(e){process.env.DEBUG&&console.debug("[HNSW-Health] Monitor module unavailable:",e instanceof Error?e.message:e),this.healthMonitor=null}}}static createBackend(e){if(j())try{return{backend:new H(e),isNative:!0}}catch(r){r instanceof b?console.info(`[HNSW] Native backend unavailable, falling back to JS: ${r.message}`):console.warn("[HNSW] Unexpected error creating native backend, falling back to JS:",r)}return{backend:new S(e),isNative:!1}}static create(e,r){let t=p.get(e);if(t instanceof i)return t;let n=new i(e,r);return p.set(e,n),n}static get(e){let r=p.get(e);return r instanceof i?r:void 0}static close(e){let r=p.get(e);r instanceof i&&r.dispose(),p.delete(e)}static closeAll(){for(let[e]of p)i.close(e);p.clear()}static listIndexes(){return Array.from(p.keys())}}});export{G as a,ye as b,xe as c};
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.14");process.exit(0)}
|
|
2
|
+
import{a as ie,b as ae}from"./chunk-DJLRRCR6.js";import{S as oe,i as j,p as q}from"./chunk-5HUAD4UU.js";import{c as g,e as D,g as $}from"./chunk-DGUAAG3T.js";var I,E=g(()=>{"use strict";I={dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"}});function se(){if(z)return A!==null;try{let i=(ae(),$(ie));if(A=i.differentiableSearch,P=i.init,P)try{P()}catch{}return z=!0,!0}catch{return z=!0,!1}}function B(i){let e=0;for(let r=0;r<i.length;r++)e+=i[r]*i[r];return Math.sqrt(e)}function ce(i,e,r,t){let n=r*t;if(n===0)return 0;let a=0,o=Math.min(i.length,e.length);for(let c=0;c<o;c++)a+=i[c]*e[c];return a/n}function U(i,e){let r=0,t=Math.min(i.length,e.length);for(let n=0;n<t;n++){let a=i[n]-e[n];r+=a*a}return Math.sqrt(r)}function le(i,e){if(i.length===e)return i;let r=new Float32Array(e);if(i.length>e){let t=i.length/e;for(let n=0;n<e;n++){let a=Math.floor(n*t),o=Math.floor((n+1)*t),c=0;for(let s=a;s<o;s++)c+=i[s];r[n]=c/(o-a)}}else for(let t=0;t<i.length;t++)r[t]=i[t];return r}var A,P,z,S,O=g(()=>{"use strict";E();A=null,P=null,z=!1;S=class{config;entries=[];idToIndex=new Map;hasRuvector=!1;loaded=!1;constructor(e){this.config={...I,...e}}ensureLoaded(){this.loaded||(this.hasRuvector=se(),this.loaded=!0)}normalizeVector(e){return e.length===this.config.dimensions?e:le(e,this.config.dimensions)}add(e,r,t){this.ensureLoaded();let n=this.normalizeVector(r),a=B(n);if(this.idToIndex.has(e)){let c=this.idToIndex.get(e);this.entries[c]={id:e,vector:n,norm:a,metadata:t};return}let o=this.entries.length;this.entries.push({id:e,vector:n,norm:a,metadata:t}),this.idToIndex.set(e,o)}search(e,r){if(this.ensureLoaded(),this.entries.length===0)return[];let t=this.normalizeVector(e),n=B(t),a=Math.min(r,this.entries.length),o=this.entries.length>0?this.entries[0].vector.length:0,c=t.length===o;if(this.config.metric==="cosine")return this.bruteForcSearch(t,n,a);if(this.hasRuvector&&c&&A)try{let s=this.entries.map(u=>u.vector),l=A(t,s,a,1).indices.map(u=>{let h=this.entries[u],m=-U(t,h.vector);return{id:h.id,score:m,metadata:h.metadata}});return l.sort((u,h)=>h.score-u.score),l}catch{}return this.bruteForcSearch(t,n,a)}bruteForcSearch(e,r,t){let n=[];for(let a of this.entries){let o;this.config.metric==="cosine"?o=ce(e,a.vector,r,a.norm):o=-U(e,a.vector),n.push({id:a.id,score:o,metadata:a.metadata})}return n.sort((a,o)=>o.score-a.score),n.slice(0,t)}remove(e){let r=this.idToIndex.get(e);if(r===void 0)return!1;let t=this.entries.length-1;if(r!==t){let n=this.entries[t];this.entries[r]=n,this.idToIndex.set(n.id,r)}return this.entries.pop(),this.idToIndex.delete(e),!0}size(){return this.entries.length}dimensions(){return this.config.dimensions}recall(){return this.hasRuvector,1}isRuvectorAvailable(){return this.ensureLoaded(),this.hasRuvector}getConfig(){return{...this.config}}clear(){this.entries=[],this.idToIndex.clear()}dispose(){this.clear()}}});import{createRequire as he}from"module";function de(){if(K){if(k)return k;throw new b(J??"Unknown load error")}K=!0;try{let i=ue("hnswlib-node");if(!i.HierarchicalNSW)throw new Error("hnswlib-node module missing HierarchicalNSW export");return k=i,k}catch(i){let e=i instanceof Error?i.message:String(i);throw J=e,new b(e)}}function me(i,e){if(i.length===e)return i;let r=new Float32Array(e);if(i.length>e){let t=i.length/e;for(let n=0;n<e;n++){let a=Math.floor(n*t),o=Math.floor((n+1)*t),c=0;for(let s=a;s<o;s++)c+=i[s];r[n]=c/(o-a)}}else for(let t=0;t<i.length;t++)r[t]=i[t];return r}function Q(i){let e=new Array(i.length);for(let r=0;r<i.length;r++)e[r]=i[r];return e}var ue,b,k,K,J,X,H,Y=g(()=>{"use strict";E();ue=he(import.meta.url),b=class extends Error{constructor(e){super(`Native HNSW backend unavailable: ${e}`),this.name="NativeHnswUnavailableError"}},k=null,K=!1,J=null;X=1e4,H=class{config;nativeIndex=null;currentMaxElements=X;liveIds=new Set;metadataStore=new Map;_metrics={totalSearches:0,totalAdds:0,totalRemoves:0,avgSearchLatencyMs:0,maxSearchLatencyMs:0,lastSearchLatencyMs:0,fallbackSearchCount:0,bruteForceSearchCount:0,nativeSearchCount:0,fallbackRate:0,allSearchesBruteForce:!1};constructor(e){this.config={...I,...e},this.nativeIndex=this.createFreshIndex()}createFreshIndex(){let e=de(),r=this.config.metric==="euclidean"?"l2":"cosine";try{let t=new e.HierarchicalNSW(r,this.config.dimensions);return t.initIndex(this.currentMaxElements,this.config.M,this.config.efConstruction,100,!0),t.setEf(this.config.efSearch),t}catch(t){let n=t instanceof Error?t.message:String(t);throw new b(`HierarchicalNSW init failed: ${n}`)}}add(e,r,t){if(!this.nativeIndex)throw new Error("NativeHnswBackend has been disposed");let n=this.normalizeVector(r);if(!this.liveIds.has(e)&&this.liveIds.size>=this.currentMaxElements){let a=this.currentMaxElements*2;this.nativeIndex.resizeIndex(a),this.currentMaxElements=a}this.nativeIndex.addPoint(Q(n),e,!0),this.liveIds.add(e),t?this.metadataStore.set(e,t):this.metadataStore.delete(e),this._metrics.totalAdds++}search(e,r){if(!this.nativeIndex)throw new Error("NativeHnswBackend has been disposed");if(this.liveIds.size===0||r<=0)return[];let t=performance.now(),n=this.normalizeVector(e),a=Math.min(r,this.liveIds.size),o=Math.min(a*2,this.liveIds.size),c=this.nativeIndex.searchKnn(Q(n),o),s=this.config.metric==="cosine",d=new Map;for(let h=0;h<c.neighbors.length;h++){let m=c.neighbors[h];if(!this.liveIds.has(m))continue;let x=c.distances[h],f=s?1-x:-x,W=d.get(m);(W===void 0||f>W.score)&&d.set(m,{id:m,score:f,metadata:this.metadataStore.get(m)})}let l=Array.from(d.values());l.sort((h,m)=>m.score-h.score),l.length>a&&(l.length=a);let u=performance.now()-t;return this.updateSearchMetrics(u),this._metrics.nativeSearchCount=this._metrics.totalSearches,u>50&&console.warn(`[NativeHNSW] search took ${u.toFixed(1)}ms (k=${r}, results=${l.length})`),l}remove(e){if(!this.nativeIndex||!this.liveIds.has(e))return!1;try{this.nativeIndex.markDelete(e)}catch{return!1}return this.liveIds.delete(e),this.metadataStore.delete(e),this._metrics.totalRemoves++,!0}size(){return this.liveIds.size}dimensions(){return this.config.dimensions}recall(){return .99}getMetrics(){return{...this._metrics}}get lastSearchLatencyMs(){return this._metrics.lastSearchLatencyMs}getConfig(){return{...this.config}}clear(){this.nativeIndex&&(this.liveIds.clear(),this.metadataStore.clear(),this.currentMaxElements=X,this.nativeIndex=this.createFreshIndex())}dispose(){this.liveIds.clear(),this.metadataStore.clear(),this.nativeIndex=null}isNativeAvailable(){return this.nativeIndex!==null}normalizeVector(e){return e.length===this.config.dimensions?e:me(e,this.config.dimensions)}updateSearchMetrics(e){this._metrics.totalSearches++,this._metrics.lastSearchLatencyMs=e,e>this._metrics.maxSearchLatencyMs&&(this._metrics.maxSearchLatencyMs=e);let r=this._metrics.totalSearches;this._metrics.avgSearchLatencyMs=this._metrics.avgSearchLatencyMs*((r-1)/r)+e/r}}});function Z(i,e){let r=Array.from({length:e},()=>new Float64Array(e));for(let t=0;t<e;t++){let n=i[t].length;r[t][t]=n;for(let a of i[t])r[t][a]=-1}return r}function N(i,e){let r=e.length,t=new Float64Array(r);for(let n=0;n<r;n++){let a=i[n].length;t[n]=a*e[n];for(let o of i[n])t[n]-=e[o]}return t}function w(i){let e=0;for(let r=0;r<i.length;r++)e+=i[r]*i[r];return Math.sqrt(e)}function R(i){let e=w(i);if(e>0)for(let r=0;r<i.length;r++)i[r]/=e}function v(i,e){let r=0;for(let t=0;t<i.length;t++)r+=i[t]*e[t];for(let t=0;t<i.length;t++)i[t]-=r*e[t]}function y(i,e,r=100,t=1e-6){if(e<=1)return 0;if(e===2)return i[0].includes(1)?2:0;let n=new Float64Array(e).fill(1/Math.sqrt(e)),a=new Float64Array(e);for(let l=0;l<e;l++)a[l]=Math.random()-.5;v(a,n),R(a);let o=0;for(let l=0;l<30;l++){let u=N(i,a);if(v(u,n),o=w(u),o>0)for(let h=0;h<e;h++)a[h]=u[h]/o}if(o<t)return 0;let c=new Float64Array(e);for(let l=0;l<e;l++)c[l]=Math.random()-.5;v(c,n),R(c);let s=0;for(let l=0;l<r;l++){let u=N(i,c),h=new Float64Array(e);for(let f=0;f<e;f++)h[f]=o*c[f]-u[f];v(h,n);let m=w(h);if(m<t)break;let x=m;for(let f=0;f<e;f++)c[f]=h[f]/m;if(Math.abs(x-s)<t)break;s=x}let d=o-s;return Math.max(0,d)}function F(i,e,r=100,t=1e-6){return y(i,e,r,t)}function C(i,e,r=50,t){if(e<=1)return 0;let n=t??y(i,e);if(n<1e-10)return 1/0;let o=2*Math.max(...i.map(d=>d.length),1),s=2*(Math.log(o/n)/(o-n));return Math.max(0,s)}function M(i,e,r){let t=1-Math.exp(-i/.05),n=1-Math.exp(-e/.5),a=r===1/0?0:1/(1+r/5),o=.4*t+.3*n+.3*a;return Math.max(0,Math.min(1,o))}var _=g(()=>{"use strict"});var re={};D(re,{ALERT_THRESHOLDS:()=>fe,DEFAULT_HNSW_HEALTH_CONFIG:()=>ee,HnswHealthMonitor:()=>L,_resetNativeLoader:()=>be,approximateFiedlerValue:()=>y,approximateSpectralGap:()=>F,buildAdjacencyFromIndex:()=>te,buildLaplacian:()=>Z,computeCoherenceScore:()=>M,createHnswHealthMonitor:()=>ge,deflateVector:()=>v,estimateEffectiveResistance:()=>C,laplacianMultiply:()=>N,normalizeInPlace:()=>R,vectorNorm:()=>w});function pe(){return V?T:(V=!0,T=null,null)}function be(){T=null,V=!1}function te(i,e=16,r){let t=i.size();if(t===0)return{adjacency:[],nodeCount:0,adjacencySource:"approximate"};let n=Array.from({length:t},()=>[]),a=Math.min(e,t-1);if(a===0)return{adjacency:n,nodeCount:t,adjacencySource:"approximate"};if(r&&r.size>0){let o=Array.from(r.keys()).slice(0,t),c=new Map;for(let s=0;s<o.length;s++)c.set(o[s],s);for(let s=0;s<o.length;s++){let d=r.get(o[s]);if(!d)continue;let l=i.search(d,a+1);for(let u of l){if(u.id===o[s])continue;let h=c.get(u.id);h!==void 0&&(n[s].includes(h)||n[s].push(h),n[h].includes(s)||n[h].push(s))}}return{adjacency:n,nodeCount:t,adjacencySource:"actual-search"}}console.warn("[HnswHealthMonitor] No stored vectors provided \u2014 using approximate circular adjacency. Pass stored vectors for accurate health metrics.");for(let o=0;o<t;o++)for(let c=0;c<a;c++){let s=(o+c+1)%t;n[o].includes(s)||n[o].push(s),n[s].includes(o)||n[s].push(o)}return{adjacency:n,nodeCount:t,adjacencySource:"approximate"}}function ge(i){return new L(i)}var ee,fe,T,V,L,ne=g(()=>{"use strict";_();_();ee={fiedlerThreshold:.01,spectralGapThreshold:.1,resistanceThreshold:10,coherenceThreshold:.3,maxPowerIterations:100,convergenceTolerance:1e-6,resistanceSampleSize:50,maxHistoryEntries:200,minIndexSize:3},fe={FragileIndex:.01,PoorExpansion:.1,HighResistance:10,LowCoherence:.3},T=null,V=!1;L=class{config;alerts=[];history=[];lastReport=null;useNative=!1;nativeChecked=!1;constructor(e){this.config={...ee,...e}}checkHealth(e){let r=performance.now(),t=e.size();if(t<this.config.minIndexSize)return this.createSmallIndexReport(t,performance.now()-r);this.nativeChecked||(this.nativeChecked=!0,this.useNative=pe()!==null);let{adjacency:n,nodeCount:a,adjacencySource:o}=te(e),c=this.useNative?this.computeNativeMetrics(n):this.computeApproximateMetrics(n,a),s=this.generateAlerts(c);this.alerts.length=0,this.alerts.push(...s);let d=performance.now()-r,l={healthy:s.length===0,metrics:c,alerts:s,indexSize:t,usedNativeBackend:this.useNative,adjacencySource:o,checkDurationMs:d,checkedAt:new Date};return this.addHistoryPoint({coherenceScore:c.coherenceScore,fiedlerValue:c.fiedlerValue,indexSize:t,healthy:l.healthy,timestamp:l.checkedAt}),this.lastReport=l,l}getAlerts(){return[...this.alerts]}getMetricsHistory(e){let r=[...this.history];return e!==void 0&&e<r.length?r.slice(-e):r}isHealthy(){return this.lastReport===null?!0:this.lastReport.healthy}getLastReport(){return this.lastReport}clearHistory(){this.history.length=0,this.alerts.length=0,this.lastReport=null}computeNativeMetrics(e){let r=T,t=r.computeFiedlerValue(e),n=r.computeSpectralGap(e),a=r.computeEffectiveResistance(e),o=M(t,n,a);return{fiedlerValue:t,spectralGap:n,effectiveResistance:a,coherenceScore:o}}computeApproximateMetrics(e,r){let t=y(e,r,this.config.maxPowerIterations,this.config.convergenceTolerance),n=F(e,r,this.config.maxPowerIterations,this.config.convergenceTolerance),a=C(e,r,this.config.resistanceSampleSize,t),o=M(t,n,a);return{fiedlerValue:t,spectralGap:n,effectiveResistance:a,coherenceScore:o}}generateAlerts(e){let r=[],t=new Date;return e.fiedlerValue<this.config.fiedlerThreshold&&r.push({type:"FragileIndex",message:`Fiedler value ${e.fiedlerValue.toFixed(6)} is below threshold ${this.config.fiedlerThreshold}. The index graph has weak algebraic connectivity.`,value:e.fiedlerValue,threshold:this.config.fiedlerThreshold,timestamp:t}),e.spectralGap<this.config.spectralGapThreshold&&r.push({type:"PoorExpansion",message:`Spectral gap ${e.spectralGap.toFixed(6)} is below threshold ${this.config.spectralGapThreshold}. The index graph has poor expansion properties.`,value:e.spectralGap,threshold:this.config.spectralGapThreshold,timestamp:t}),e.effectiveResistance>this.config.resistanceThreshold&&r.push({type:"HighResistance",message:`Average effective resistance ${e.effectiveResistance.toFixed(4)} exceeds threshold ${this.config.resistanceThreshold}. Nodes are poorly connected.`,value:e.effectiveResistance,threshold:this.config.resistanceThreshold,timestamp:t}),e.coherenceScore<this.config.coherenceThreshold&&r.push({type:"LowCoherence",message:`Coherence score ${e.coherenceScore.toFixed(4)} is below threshold ${this.config.coherenceThreshold}. Overall index health is degraded.`,value:e.coherenceScore,threshold:this.config.coherenceThreshold,timestamp:t}),r}createSmallIndexReport(e,r){let t={fiedlerValue:e>0?1:0,spectralGap:e>0?1:0,effectiveResistance:e>0?.5:0,coherenceScore:e>0?1:0},n={healthy:!0,metrics:t,alerts:[],indexSize:e,usedNativeBackend:!1,adjacencySource:"approximate",checkDurationMs:r,checkedAt:new Date};return this.addHistoryPoint({coherenceScore:t.coherenceScore,fiedlerValue:t.fiedlerValue,indexSize:e,healthy:!0,timestamp:n.checkedAt}),this.lastReport=n,n}addHistoryPoint(e){this.history.push(e),this.history.length>this.config.maxHistoryEntries&&this.history.splice(0,this.history.length-this.config.maxHistoryEntries)}}});var ye={};D(ye,{HnswAdapter:()=>G});var ve,p,G,xe=g(()=>{O();Y();oe();ve={patterns:{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"},"qe-memory":{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"},learning:{dimensions:384,M:16,efConstruction:200,efSearch:50,metric:"cosine"},coverage:{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"}},p=new Map,G=class i{backend;_isNativeBackend;indexName;stringToNumericId=new Map;numericToStringId=new Map;nextAutoId=0;healthMonitor=null;healthMonitorLoaded=!1;operationsSinceLastCheck=0;healthCheckFrequency=100;lastHealthReport=null;constructor(e,r){this.indexName=e;let n={...ve[e]??{},...r},{backend:a,isNative:o}=i.createBackend(n);this.backend=a,this._isNativeBackend=o}add(e,r,t){this.backend.add(e,r,t),this.maybeRunHealthCheck()}search(e,r){let t=performance.now(),n=this.backend.search(e,r),a=performance.now()-t;return a>50&&console.warn(`[HNSW] search took ${a.toFixed(1)}ms (k=${r}, results=${n.length})`),this._lastSearchLatencyMs=a,n}_lastSearchLatencyMs=0;get lastSearchLatencyMs(){return this._lastSearchLatencyMs}remove(e){return this.backend.remove(e)}size(){return this.backend.size()}dimensions(){return this.backend.dimensions()}recall(){return this.backend.recall()}addByStringId(e,r){let t=this.stringToNumericId.get(e);t!==void 0?this.backend.remove(t):(t=this.nextAutoId++,this.stringToNumericId.set(e,t),this.numericToStringId.set(t,e)),this.backend.add(t,new Float32Array(r))}searchByArray(e,r){return this.backend.search(new Float32Array(e),r).map(n=>({id:this.numericToStringId.get(n.id)??String(n.id),score:n.score}))}removeByStringId(e){let r=this.stringToNumericId.get(e);if(r===void 0)return!1;let t=this.backend.remove(r);return t&&(this.stringToNumericId.delete(e),this.numericToStringId.delete(r)),t}clear(){this.backend.clear?.(),this.stringToNumericId.clear(),this.numericToStringId.clear(),this.nextAutoId=0}dispose(){try{this.backend.dispose?.()}catch{}this.stringToNumericId.clear(),this.numericToStringId.clear(),this.nextAutoId=0}isRuvectorAvailable(){return this.backend instanceof S?this.backend.isRuvectorAvailable():this.backend instanceof H?this.backend.isNativeAvailable():!1}isNativeBackend(){return this._isNativeBackend}getName(){return this.indexName}setHealthCheckFrequency(e){this.healthCheckFrequency=Math.max(1,e)}getHealthCheckFrequency(){return this.healthCheckFrequency}getLastHealthReport(){return this.lastHealthReport}getHealthMonitor(){return this.healthMonitor}maybeRunHealthCheck(){if(q()&&(this.operationsSinceLastCheck++,!(this.operationsSinceLastCheck<this.healthCheckFrequency)&&(this.operationsSinceLastCheck=0,this.ensureHealthMonitor(),this.healthMonitor)))try{this.lastHealthReport=this.healthMonitor.checkHealth(this.backend),this.lastHealthReport.healthy||console.warn(`[HNSW-Health] Index "${this.indexName}" health check failed: ${this.lastHealthReport.alerts.length} alert(s). Coherence: ${this.lastHealthReport.metrics.coherenceScore.toFixed(3)}`)}catch(e){console.warn(`[HNSW-Health] Health check error for "${this.indexName}":`,e)}}ensureHealthMonitor(){if(!this.healthMonitorLoaded){this.healthMonitorLoaded=!0;try{let e=(ne(),$(re));this.healthMonitor=e.createHnswHealthMonitor()}catch(e){process.env.DEBUG&&console.debug("[HNSW-Health] Monitor module unavailable:",e instanceof Error?e.message:e),this.healthMonitor=null}}}static createBackend(e){if(j())try{return{backend:new H(e),isNative:!0}}catch(r){r instanceof b?console.info(`[HNSW] Native backend unavailable, falling back to JS: ${r.message}`):console.warn("[HNSW] Unexpected error creating native backend, falling back to JS:",r)}return{backend:new S(e),isNative:!1}}static create(e,r){let t=p.get(e);if(t instanceof i)return t;let n=new i(e,r);return p.set(e,n),n}static get(e){let r=p.get(e);return r instanceof i?r:void 0}static close(e){let r=p.get(e);r instanceof i&&r.dispose(),p.delete(e)}static closeAll(){for(let[e]of p)i.close(e);p.clear()}static listIndexes(){return Array.from(p.keys())}}});export{G as a,ye as b,xe as c};
|