agentic-qe 3.13.0 → 3.13.1
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/.agents/skills/aqe-plan-quality/SKILL.md +25 -0
- package/.agents/skills/aqe-plan-quality/agents/openai.yaml +4 -0
- package/.agents/skills/aqe-plan-quality/references/qe-routing.md +22 -0
- package/.agents/skills/aqe-review-quality/SKILL.md +24 -0
- package/.agents/skills/aqe-review-quality/agents/openai.yaml +4 -0
- package/.agents/skills/aqe-review-quality/references/quality-gates.md +20 -0
- package/.agents/skills/aqe-test-change/SKILL.md +26 -0
- package/.agents/skills/aqe-test-change/agents/openai.yaml +4 -0
- package/.agents/skills/aqe-test-change/references/test-specialties.md +23 -0
- package/.claude/helpers/ruflo-hook.cjs +5 -1
- package/.claude/skills/skills-manifest.json +1 -1
- package/.codex/hooks/aqe-codex-hook.cjs +69 -0
- package/.codex/hooks/ruflo-codex-hook.cjs +94 -0
- package/.codex/hooks.json +169 -0
- package/CHANGELOG.md +94 -0
- package/assets/skills/skills-manifest.json +1 -1
- package/dist/cli/bundle.js +5 -5
- package/dist/cli/chunks/adapter-VRZNL53W.js +2 -0
- package/dist/cli/chunks/{agent-booster-wasm-ACX2DK7Y.js → agent-booster-wasm-4VM3DE42.js} +2 -2
- package/dist/cli/chunks/{agent-handler-B45WP4ZJ.js → agent-handler-ZDLMZQQX.js} +2 -2
- package/dist/cli/chunks/{agent-memory-branch-QQLZDE56.js → agent-memory-branch-P72MDHHV.js} +2 -2
- package/dist/cli/chunks/aqe-learning-engine-XCNMNERX.js +2 -0
- package/dist/cli/chunks/{arena-G3IKZAG5.js → arena-55FZGKEV.js} +4 -4
- package/dist/cli/chunks/{arena-SDB7723R.js → arena-GCRBQ26R.js} +2 -2
- package/dist/cli/chunks/{audit-GY46XUZA.js → audit-VYAYVLIV.js} +3 -3
- package/dist/cli/chunks/base-VZZNR4UR.js +2 -0
- package/dist/cli/chunks/{hnswlib-node-RJPBJU2Q.js → better-sqlite3-JDDFYVCX.js} +2 -2
- package/dist/cli/chunks/{brain-handler-347CYMPN.js → brain-handler-IUKMRGWO.js} +3 -3
- package/dist/cli/chunks/{branch-enumerator-Z3ULBFSM.js → branch-enumerator-TUI3RWLX.js} +2 -2
- package/dist/cli/chunks/{browser-OYEIHD7F.js → browser-NBQTZYX2.js} +2 -2
- package/dist/cli/chunks/browser-workflow-5DZNIFUY.js +2 -0
- package/dist/cli/chunks/{chunk-2NRZYQSF.js → chunk-23MT7OBY.js} +2 -2
- package/dist/cli/chunks/{chunk-7UNY32PU.js → chunk-2CQAWYYE.js} +1 -1
- package/dist/cli/chunks/{chunk-ZLXBNNNT.js → chunk-2D2XFUKI.js} +2 -2
- package/dist/cli/chunks/{chunk-SHCTEXNH.js → chunk-2G2QWV7B.js} +2 -2
- package/dist/cli/chunks/{chunk-TZ73SXQ5.js → chunk-2ISLQU3G.js} +1 -1
- package/dist/cli/chunks/{chunk-VLNPJAVH.js → chunk-2OM3TDC4.js} +1 -1
- package/dist/cli/chunks/{chunk-JGM6XCCP.js → chunk-2XZ4BHWS.js} +1 -1
- package/dist/cli/chunks/{chunk-32ZGV4Q4.js → chunk-3F4XH4ZA.js} +1 -1
- package/dist/cli/chunks/{chunk-RDU4WTV2.js → chunk-3K4YC3GC.js} +2 -2
- package/dist/cli/chunks/chunk-3KGCBAUH.js +2 -0
- package/dist/cli/chunks/{chunk-DYUC7WFA.js → chunk-3Y6CHW67.js} +1 -1
- package/dist/cli/chunks/{chunk-3JVUWKCO.js → chunk-4QMWWYNU.js} +2 -2
- package/dist/cli/chunks/{chunk-L4LLA5U7.js → chunk-4WGSMODQ.js} +1 -1
- package/dist/cli/chunks/{chunk-KUA4HHU6.js → chunk-55WDVSCM.js} +2 -2
- package/dist/cli/chunks/{chunk-RVJPWRV6.js → chunk-5BB5DUL4.js} +2 -2
- package/dist/cli/chunks/{chunk-ZOXWASCC.js → chunk-6C3MZLYW.js} +2 -2
- package/dist/cli/chunks/{chunk-CFVEDUTW.js → chunk-6QKQFHS7.js} +2 -2
- package/dist/cli/chunks/{chunk-YFGAHNCG.js → chunk-6XZXMEK4.js} +3 -3
- package/dist/cli/chunks/{chunk-Z6QCOZ2H.js → chunk-7D7XFZZI.js} +2 -2
- package/dist/cli/chunks/{chunk-AO7AHX6K.js → chunk-7WEHZCSK.js} +2 -2
- package/dist/cli/chunks/{chunk-K5N6SLHO.js → chunk-A2MG3YXO.js} +1 -1
- package/dist/cli/chunks/{chunk-LXPB7H2P.js → chunk-AHTOWWSE.js} +1 -1
- package/dist/cli/chunks/{chunk-U2SW6KK5.js → chunk-AOMXMFDH.js} +2 -2
- package/dist/cli/chunks/{chunk-VSNRPMAZ.js → chunk-ARTLSAXO.js} +2 -2
- package/dist/cli/chunks/{chunk-FBBZHATF.js → chunk-AY7S7AWN.js} +1 -1
- package/dist/cli/chunks/{chunk-CYL2FV23.js → chunk-AYYDO52G.js} +2 -2
- package/dist/cli/chunks/chunk-BBLWZT5I.js +2 -0
- package/dist/cli/chunks/{chunk-QTU3CVOB.js → chunk-BF5BKSDU.js} +2 -2
- package/dist/cli/chunks/{chunk-CWUBOLKY.js → chunk-BOCEOLLJ.js} +2 -2
- package/dist/cli/chunks/{chunk-FL3BM54K.js → chunk-CE6LYEHT.js} +1 -1
- package/dist/cli/chunks/{chunk-THBTN7XB.js → chunk-CWP4RMOM.js} +2 -2
- package/dist/cli/chunks/{chunk-Q7PBGNUD.js → chunk-CWXDL7AH.js} +1 -1
- package/dist/cli/chunks/{chunk-RVRBTOWX.js → chunk-DTRFZD7N.js} +2 -2
- package/dist/cli/chunks/{chunk-IZRLIWFN.js → chunk-DVPGQG4W.js} +2 -2
- package/dist/cli/chunks/{chunk-3NOCK6ED.js → chunk-E4D47QTF.js} +2 -2
- package/dist/cli/chunks/{chunk-FQLWQWRU.js → chunk-EAKHU5YX.js} +3 -3
- package/dist/cli/chunks/{chunk-56WZFXTQ.js → chunk-EGMGOWCE.js} +2 -2
- package/dist/cli/chunks/{chunk-OXXMVQDF.js → chunk-ELMUHNXN.js} +2 -2
- package/dist/cli/chunks/{chunk-SNTUKW4Q.js → chunk-EVDYFGVH.js} +2 -2
- package/dist/cli/chunks/{chunk-RLCWR7TS.js → chunk-FDUSWM6O.js} +98 -88
- package/dist/cli/chunks/{chunk-D3MPV5G7.js → chunk-FM272B4O.js} +2 -2
- package/dist/cli/chunks/{chunk-DRIJYTSK.js → chunk-FQUUMC57.js} +2 -2
- package/dist/cli/chunks/{chunk-5KAT6WBQ.js → chunk-FQXQJMSF.js} +2 -2
- package/dist/cli/chunks/{chunk-BCKTBGDM.js → chunk-FRAGSKXQ.js} +3 -3
- package/dist/cli/chunks/{chunk-SRQ3CPJE.js → chunk-GASOBSNB.js} +4 -4
- package/dist/cli/chunks/{chunk-GTUFX7AR.js → chunk-GJEEPKAT.js} +2 -2
- package/dist/cli/chunks/{chunk-5EIOQCGN.js → chunk-GOV2MHLV.js} +2 -2
- package/dist/cli/chunks/{chunk-QI4CGJNK.js → chunk-GTPZVLL6.js} +1 -1
- package/dist/cli/chunks/chunk-H7YZ2YF2.js +3 -0
- package/dist/cli/chunks/{chunk-ANIDFJCT.js → chunk-HFI5PHG5.js} +3 -3
- package/dist/cli/chunks/{chunk-2VQVEQS4.js → chunk-HUMQU4ES.js} +2 -2
- package/dist/cli/chunks/{chunk-VHYMSZNF.js → chunk-HYIRFJDB.js} +2 -2
- package/dist/cli/chunks/{chunk-A4QLGPYO.js → chunk-IBSBOHUX.js} +2 -2
- package/dist/cli/chunks/{chunk-6SXKCIN5.js → chunk-IJA4WS7B.js} +1 -1
- package/dist/cli/chunks/{chunk-3GSYD5SL.js → chunk-IJP42OGW.js} +2 -2
- package/dist/cli/chunks/{chunk-PERJO2DY.js → chunk-IMQKEFW6.js} +1 -1
- package/dist/cli/chunks/{chunk-ZEIG5IQ4.js → chunk-INYS35DV.js} +2 -2
- package/dist/cli/chunks/{chunk-J3L52EA4.js → chunk-IV2VCR75.js} +5 -5
- package/dist/cli/chunks/{chunk-TVMFH5N2.js → chunk-IZO6TPGX.js} +2 -2
- package/dist/cli/chunks/{chunk-ZJG6N2OK.js → chunk-J45DX3IK.js} +1 -1
- package/dist/cli/chunks/{chunk-HL2QMM4M.js → chunk-J4T6D2OQ.js} +2 -2
- package/dist/cli/chunks/{chunk-5ICQL42E.js → chunk-JAPOMPFD.js} +2 -2
- package/dist/cli/chunks/{chunk-L2SFGFE6.js → chunk-JELNVHBF.js} +1 -1
- package/dist/cli/chunks/{chunk-RSFIOR2I.js → chunk-JOTNKZ7A.js} +87 -87
- package/dist/cli/chunks/{chunk-34PEINFS.js → chunk-KNWDXI3I.js} +2 -2
- package/dist/cli/chunks/{chunk-FUU32QY5.js → chunk-KW5NBORV.js} +2 -2
- package/dist/cli/chunks/{chunk-N5MMBA35.js → chunk-L7IOTWWY.js} +1 -1
- package/dist/cli/chunks/{chunk-RJZRWVL4.js → chunk-LJQ27PUE.js} +1 -1
- package/dist/cli/chunks/{chunk-QQB55ZJJ.js → chunk-LSKQUUUN.js} +2 -2
- package/dist/cli/chunks/{chunk-NETN3OUG.js → chunk-LSZZQ7H6.js} +1 -1
- package/dist/cli/chunks/{chunk-IYDYJ33J.js → chunk-LTKNCYMO.js} +2 -2
- package/dist/cli/chunks/{chunk-6DTOGSDV.js → chunk-LTWT4GZD.js} +4 -4
- package/dist/cli/chunks/{chunk-NQNKKVNO.js → chunk-LVHMXGDI.js} +3 -3
- package/dist/cli/chunks/{chunk-3UHEZ5HZ.js → chunk-M3T6FB54.js} +2 -2
- package/dist/cli/chunks/{chunk-ZJIX5FGQ.js → chunk-MAYZTGJ2.js} +2 -2
- package/dist/cli/chunks/{chunk-3K4SF57Q.js → chunk-MCIO7BDK.js} +1 -1
- package/dist/cli/chunks/{chunk-A7GLWWSE.js → chunk-MPD7RR4P.js} +1 -1
- package/dist/cli/chunks/{chunk-FAQLI3P5.js → chunk-MUFYDKVC.js} +2 -2
- package/dist/cli/chunks/{chunk-XFCWYQHW.js → chunk-MX5ZDKRR.js} +2 -2
- package/dist/cli/chunks/{chunk-MBCGI3M2.js → chunk-MXKHIZVM.js} +5 -5
- package/dist/cli/chunks/chunk-MY47CR27.js +2 -0
- package/dist/cli/chunks/chunk-N7WAZ2Y6.js +2 -0
- package/dist/cli/chunks/{chunk-VC6EXDGY.js → chunk-NHV4PTG6.js} +2 -2
- package/dist/cli/chunks/{chunk-LBE2P6UC.js → chunk-NP4CP3LR.js} +2 -2
- package/dist/cli/chunks/{chunk-6AOBLBR4.js → chunk-OCKTPTQ7.js} +2 -2
- package/dist/cli/chunks/{chunk-ES7WCYOU.js → chunk-OE4B6LDZ.js} +1 -1
- package/dist/cli/chunks/{chunk-IPHLXAMX.js → chunk-OPQY2333.js} +2 -2
- package/dist/cli/chunks/{chunk-7DMXCCSD.js → chunk-ORDH4VPL.js} +1 -1
- package/dist/cli/chunks/{chunk-HTPM3URI.js → chunk-P4Y3G6OB.js} +2 -2
- package/dist/cli/chunks/{chunk-TNRIGQ6U.js → chunk-PIOO2M4W.js} +2 -2
- package/dist/cli/chunks/{chunk-BGYLNCL6.js → chunk-PKMCZFET.js} +2 -2
- package/dist/cli/chunks/{chunk-G7FMYFTN.js → chunk-QES4QHQW.js} +1 -1
- package/dist/cli/chunks/{chunk-UIPPJKON.js → chunk-QG6BXSNJ.js} +2 -2
- package/dist/cli/chunks/{chunk-7YXT6BXN.js → chunk-QLOOW23R.js} +3 -3
- package/dist/cli/chunks/{chunk-CQFT7H3F.js → chunk-RSCGBHLM.js} +2 -2
- package/dist/cli/chunks/{chunk-QCEW4ZDW.js → chunk-RZ6CO3RZ.js} +2 -2
- package/dist/cli/chunks/{chunk-OETDMOOE.js → chunk-S6F3IJMK.js} +1 -1
- package/dist/cli/chunks/{chunk-KVL63BSU.js → chunk-S6VNPKHO.js} +1 -1
- package/dist/cli/chunks/{chunk-BUGWPTMF.js → chunk-SHWXADCI.js} +2 -2
- package/dist/cli/chunks/{chunk-FQY3UTGA.js → chunk-SPJQJWGK.js} +2 -2
- package/dist/cli/chunks/{chunk-BOVH6WSM.js → chunk-SS6K4FBH.js} +2 -2
- package/dist/cli/chunks/{chunk-4BESADKE.js → chunk-SXADKQJN.js} +2 -2
- package/dist/cli/chunks/{chunk-USMDIIHY.js → chunk-TBQTGQ75.js} +2 -2
- package/dist/cli/chunks/{chunk-4BDLD7V2.js → chunk-TDGE52HJ.js} +1 -1
- package/dist/cli/chunks/{chunk-JPIBPKBP.js → chunk-THFLRJT6.js} +3 -3
- package/dist/cli/chunks/{chunk-ZCFZ4USU.js → chunk-TQ2MA3SR.js} +1 -1
- package/dist/cli/chunks/{chunk-G5DFYX3J.js → chunk-UCQ66N6M.js} +2 -2
- package/dist/cli/chunks/{chunk-CPH5JP4L.js → chunk-UHGMS2PJ.js} +1 -1
- package/dist/cli/chunks/{chunk-ANYYTWOQ.js → chunk-UHKXKWMD.js} +2 -2
- package/dist/cli/chunks/{chunk-YRQLVGCI.js → chunk-UJ6TMZC6.js} +2 -2
- package/dist/cli/chunks/{chunk-EECM5XKY.js → chunk-UKBDH27A.js} +1 -1
- package/dist/cli/chunks/{chunk-VLBV2VL3.js → chunk-UMCEEXQN.js} +1 -1
- package/dist/cli/chunks/{chunk-LOXVVMS4.js → chunk-USUFTHHT.js} +3 -3
- package/dist/cli/chunks/{chunk-HOKON5EL.js → chunk-V32MDID3.js} +2 -2
- package/dist/cli/chunks/{chunk-KZTBNDNE.js → chunk-VAJT6QWX.js} +1 -1
- package/dist/cli/chunks/{chunk-UNIBND6A.js → chunk-VLUJWI56.js} +1 -1
- package/dist/cli/chunks/{chunk-QWYISZTN.js → chunk-WINA3XUT.js} +2 -2
- package/dist/cli/chunks/{chunk-YPTGE5NJ.js → chunk-WWCH5SSF.js} +2 -2
- package/dist/cli/chunks/{chunk-W5YEIHIO.js → chunk-WWP2VXYJ.js} +2 -2
- package/dist/cli/chunks/{chunk-GFBLWFRV.js → chunk-WZROSTQZ.js} +1 -1
- package/dist/cli/chunks/{chunk-UMG5URNV.js → chunk-XFUF654L.js} +1 -1
- package/dist/cli/chunks/{chunk-54MFKCLT.js → chunk-XN2CD5S6.js} +2 -2
- package/dist/cli/chunks/{chunk-IHQTXJAQ.js → chunk-XOQQGZFY.js} +1 -1
- package/dist/cli/chunks/{chunk-WRYT4HTZ.js → chunk-XSCOEY4C.js} +2 -2
- package/dist/cli/chunks/{chunk-R3GEXYO4.js → chunk-Y734CWHJ.js} +2 -2
- package/dist/cli/chunks/{chunk-NUQBJGGF.js → chunk-YBPCBFEE.js} +2 -2
- package/dist/cli/chunks/{chunk-GUEZQOHL.js → chunk-YLAEIS6F.js} +1 -1
- package/dist/cli/chunks/{chunk-EFRESRLB.js → chunk-YMMVCOPF.js} +3 -3
- package/dist/cli/chunks/{chunk-N7VOOI3U.js → chunk-YQCAXYBF.js} +2 -2
- package/dist/cli/chunks/{chunk-5FLTZ3KT.js → chunk-YRVUYM62.js} +2 -2
- package/dist/cli/chunks/{chunk-GJMZR7WU.js → chunk-YVKMHXQK.js} +3 -3
- package/dist/cli/chunks/{chunk-TZPKTRJB.js → chunk-ZCLFAOVT.js} +2 -2
- package/dist/cli/chunks/{chunk-L4S722JD.js → chunk-ZH6ZBDVV.js} +1 -1
- package/dist/cli/chunks/{chunk-KSYLRM4Q.js → chunk-ZHEKGB4A.js} +2 -2
- package/dist/cli/chunks/{chunk-E3B5XTXJ.js → chunk-ZIBW7CB4.js} +1 -1
- package/dist/cli/chunks/{chunk-2DIT5AUU.js → chunk-ZLCATRXI.js} +2 -2
- package/dist/cli/chunks/{chunk-LWYLW7RX.js → chunk-ZXX2VFMA.js} +2 -2
- package/dist/cli/chunks/{chunk-XKFE3FLI.js → chunk-ZYPESQ4M.js} +2 -2
- package/dist/cli/chunks/{ci-74ZUCO5V.js → ci-HHL5WQXQ.js} +2 -2
- package/dist/cli/chunks/{ci-output-HD6IZNJA.js → ci-output-HVOJC2KN.js} +2 -2
- package/dist/cli/chunks/{circuit-breaker-USZVMA42.js → circuit-breaker-HRXMIY2G.js} +2 -2
- package/dist/cli/chunks/{claude-flow-setup-S4XKNCD5.js → claude-flow-setup-3I7WVMZN.js} +2 -2
- package/dist/cli/chunks/client-EY2IYQDL.js +2 -0
- package/dist/cli/chunks/{cline-installer-6EW4CHAR.js → cline-installer-NBREL4QT.js} +2 -2
- package/dist/cli/chunks/{code-TOLWD2XL.js → code-TX4E2RWU.js} +2 -2
- package/dist/cli/chunks/{code-index-extractor-UA4QQ7B3.js → code-index-extractor-YELOFLSL.js} +2 -2
- package/dist/cli/chunks/codex-installer-HEX3KFRB.js +10 -0
- package/dist/cli/chunks/{completions-KVUMQQ4K.js → completions-72GGFRGG.js} +2 -2
- package/dist/cli/chunks/{complexity-analyzer-DFH6LMK2.js → complexity-analyzer-WRAKDYUK.js} +2 -2
- package/dist/cli/chunks/{continuedev-installer-LYDQSAU7.js → continuedev-installer-UGYKSKTI.js} +2 -2
- package/dist/cli/chunks/{copilot-installer-7USXLZHZ.js → copilot-installer-RPCRUKIJ.js} +2 -2
- package/dist/cli/chunks/core-handlers-G4GLA4DT.js +2 -0
- package/dist/cli/chunks/{cost-tracker-JBDIUMKZ.js → cost-tracker-CNHJ7G4M.js} +2 -2
- package/dist/cli/chunks/{coverage-RGO3K357.js → coverage-RHIQ4XEX.js} +3 -3
- package/dist/cli/chunks/cross-domain-router-P3K4IH5H.js +2 -0
- package/dist/cli/chunks/{cursor-installer-YEZGD37F.js → cursor-installer-KSRVA4V2.js} +2 -2
- package/dist/cli/chunks/{daemon-FVETQ3LL.js → daemon-IT4AAFBW.js} +3 -3
- package/dist/cli/chunks/{daemon-LPEXHNYG.js → daemon-QBXSJABV.js} +4 -4
- package/dist/cli/chunks/{dag-attention-scheduler-UKYE2FII.js → dag-attention-scheduler-F7WCQTLY.js} +2 -2
- package/dist/cli/chunks/{detect-WBG5P7ER.js → detect-2IYU332U.js} +2 -2
- package/dist/cli/chunks/{dist-node-YW6YRBCU.js → dist-node-CIYNYCYN.js} +2 -2
- package/dist/cli/chunks/{domain-handler-HH7J4A32.js → domain-handler-QRYQO2QK.js} +2 -2
- package/dist/cli/chunks/{domain-transfer-V34GXD5I.js → domain-transfer-2OQDOD3G.js} +2 -2
- package/dist/cli/chunks/dream-IT4ZQGEO.js +2 -0
- package/dist/cli/chunks/{embed-and-insert-pattern-WYLRS3CL.js → embed-and-insert-pattern-P2IFC7JL.js} +2 -2
- package/dist/cli/chunks/{eval-EIMVXY5J.js → eval-SBPK37IB.js} +2 -2
- package/dist/cli/chunks/{experience-capture-middleware-QMZHRUKM.js → experience-capture-middleware-3GMFND3F.js} +3 -3
- package/dist/cli/chunks/{fast-paths-NHLW6XS6.js → fast-paths-4OYYII2F.js} +2 -2
- package/dist/cli/chunks/{feature-flags-NE3MBL3P.js → feature-flags-BM6QTMMC.js} +2 -2
- package/dist/cli/chunks/{feature-flags-N3UHMSZ3.js → feature-flags-NFCAYUWO.js} +2 -2
- package/dist/cli/chunks/{file-discovery-SI44X4YS.js → file-discovery-2M3ZUAGC.js} +2 -2
- package/dist/cli/chunks/{fleet-MMYUXRRM.js → fleet-QMGGVIDV.js} +3 -3
- package/dist/cli/chunks/{gnn-wrapper-RLYXYU2Q.js → gnn-wrapper-WGMAGZMO.js} +2 -2
- package/dist/cli/chunks/{heartbeat-handler-6EDRUYLV.js → heartbeat-handler-5RSMEZGG.js} +4 -4
- package/dist/cli/chunks/heartbeat-scheduler-UUWSPHF2.js +2 -0
- package/dist/cli/chunks/hnsw-adapter-YUJVSFPD.js +2 -0
- package/dist/cli/chunks/hnsw-index-FQZ47RSJ.js +2 -0
- package/dist/cli/chunks/{hnsw-legacy-bridge-RVM7EAIH.js → hnsw-legacy-bridge-TYPQ2T6P.js} +2 -2
- package/dist/cli/chunks/{better-sqlite3-DUZ6FFAH.js → hnswlib-node-GMRPPMDM.js} +2 -2
- package/dist/cli/chunks/{hooks-ZF4VKHEO.js → hooks-NUC5P3OJ.js} +10 -10
- package/dist/cli/chunks/hybrid-router-T5MF73NF.js +2 -0
- package/dist/cli/chunks/{hypergraph-engine-YWS66PGO.js → hypergraph-engine-OIB7WK54.js} +2 -2
- package/dist/cli/chunks/{hypergraph-handler-OQHVRPWB.js → hypergraph-handler-XX2N75QC.js} +3 -3
- package/dist/cli/chunks/impact-analyzer-AEGELYMD.js +2 -0
- package/dist/cli/chunks/{init-handler-YW74YF2V.js → init-handler-AKSTJMZY.js} +6 -6
- package/dist/cli/chunks/init-wizard-WKX3OGWM.js +2 -0
- package/dist/cli/chunks/kernel-5CVWFIGR.js +2 -0
- package/dist/cli/chunks/{kilocode-installer-APWB2GMA.js → kilocode-installer-375V5ZZB.js} +2 -2
- package/dist/cli/chunks/{kiro-installer-DICKFVNC.js → kiro-installer-GKY5GB5Q.js} +2 -2
- package/dist/cli/chunks/knowledge-graph-EGPMNDMT.js +2 -0
- package/dist/cli/chunks/{learning-MXHNYW5D.js → learning-2CQE3QP6.js} +3 -3
- package/dist/cli/chunks/{llm-router-LTFIX7NY.js → llm-router-FTQNRF45.js} +4 -4
- package/dist/cli/chunks/llm-router-service-H4LXOARB.js +2 -0
- package/dist/cli/chunks/{load-JUMIQ4LZ.js → load-3DBAO5ZG.js} +2 -2
- package/dist/cli/chunks/load-test-OOOGITSN.js +2 -0
- package/dist/cli/chunks/{mcp-WHIARJGO.js → mcp-AWR6TDXM.js} +2 -2
- package/dist/cli/chunks/{memory-KAHS6Z5A.js → memory-GI4LCNXY.js} +5 -5
- package/dist/cli/chunks/memory-backend-O2YOT4LW.js +2 -0
- package/dist/cli/chunks/{memory-handlers-DG3RRXB6.js → memory-handlers-MALKG7GP.js} +2 -2
- package/dist/cli/chunks/{multi-model-executor-E3Y2RHMX.js → multi-model-executor-SWFT5U72.js} +2 -2
- package/dist/cli/chunks/{opencode-installer-3RKGNGGE.js → opencode-installer-EYXGYJX5.js} +2 -2
- package/dist/cli/chunks/{orchestrator-TXITUKWD.js → orchestrator-MP3EAZVC.js} +5 -5
- package/dist/cli/chunks/pattern-null-store-WBOHE2XL.js +2 -0
- package/dist/cli/chunks/{pattern-usage-recorder-EE2BUFZT.js → pattern-usage-recorder-25P3R3W7.js} +2 -2
- package/dist/cli/chunks/{pipeline-AXTT6KZB.js → pipeline-LSAFL25D.js} +2 -2
- package/dist/cli/chunks/{platform-TICPVKE2.js → platform-IJ6DJ2PG.js} +2 -2
- package/dist/cli/chunks/{plugin-VQKNV3EM.js → plugin-OXOZRZW2.js} +2 -2
- package/dist/cli/chunks/{prime-radiant-advanced-wasm-6GY5YY7D.js → prime-radiant-advanced-wasm-HJNJQQ3R.js} +2 -2
- package/dist/cli/chunks/protocol-executor-JCNTPW5J.js +2 -0
- package/dist/cli/chunks/{protocol-handler-YFWDR7UZ.js → protocol-handler-TCMUH2HL.js} +2 -2
- package/dist/cli/chunks/{prove-FUMRCXAA.js → prove-ADXQ2GOX.js} +2 -2
- package/dist/cli/chunks/provider-manager-LPGQ5GOO.js +2 -0
- package/dist/cli/chunks/qe-reasoning-bank-FWVYVSPP.js +2 -0
- package/dist/cli/chunks/{quality-2APISBW5.js → quality-EWP36ORX.js} +2 -2
- package/dist/cli/chunks/{quality-gate-MCC3E5TM.js → quality-gate-3BIG7PVU.js} +3 -3
- package/dist/cli/chunks/queen-coordinator-UXNALRVD.js +2 -0
- package/dist/cli/chunks/{real-embeddings-CC5TNOTI.js → real-embeddings-D4NBT7W5.js} +2 -2
- package/dist/cli/chunks/{roocode-installer-YAHTEVPI.js → roocode-installer-DOPWH6YV.js} +2 -2
- package/dist/cli/chunks/router-C6LUIQYY.js +2 -0
- package/dist/cli/chunks/routing-feedback-KMSGGDVD.js +2 -0
- package/dist/cli/chunks/{routing-handler-6NQBW4TQ.js → routing-handler-5ADEFOHS.js} +2 -2
- package/dist/cli/chunks/{ruvector-commands-ZHXLHUPG.js → ruvector-commands-PLMEIHSN.js} +2 -2
- package/dist/cli/chunks/{rvf-dual-writer-5KF2DGCW.js → rvf-dual-writer-EQWKVNQB.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-adapter-BBU57BGF.js → rvf-migration-adapter-2OWFUUCG.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-coordinator-VN4VRZA4.js → rvf-migration-coordinator-URAETAPU.js} +2 -2
- package/dist/cli/chunks/rvf-native-adapter-K54BELUE.js +2 -0
- package/dist/cli/chunks/{rvf-store-integrity-XCY2XQZA.js → rvf-store-integrity-4AWPW4TF.js} +2 -2
- package/dist/cli/chunks/safe-db-NGOZWF2D.js +2 -0
- package/dist/cli/chunks/schedule-B3Y5P64E.js +2 -0
- package/dist/cli/chunks/scheduler-Z6QVRMTB.js +2 -0
- package/dist/cli/chunks/{security-PYP4H3KN.js → security-HDLZVM62.js} +3 -3
- package/dist/cli/chunks/{shared-rvf-adapter-3CJHRNX6.js → shared-rvf-adapter-YQT7PF7X.js} +2 -2
- package/dist/cli/chunks/{shared-rvf-dual-writer-MKSLKWDI.js → shared-rvf-dual-writer-N5D3NSJ7.js} +2 -2
- package/dist/cli/chunks/sqlite-persistence-PLOUGATS.js +2 -0
- package/dist/cli/chunks/{status-handler-VYIZ3VJF.js → status-handler-KLYRJ2MR.js} +2 -2
- package/dist/cli/chunks/{structural-health-MVV4OWXP.js → structural-health-6LKVRP6Y.js} +2 -2
- package/dist/cli/chunks/{sync-VNX6L3TI.js → sync-7VMFPBVB.js} +2 -2
- package/dist/cli/chunks/{sync-G47OYIQ3.js → sync-YYOW6L6W.js} +2 -2
- package/dist/cli/chunks/{task-handler-GOWF2GEH.js → task-handler-RKQDGFN2.js} +2 -2
- package/dist/cli/chunks/{task-handlers-J2WC6J37.js → task-handlers-6YJ4QTEP.js} +3 -3
- package/dist/cli/chunks/{test-DMCJ3BXS.js → test-ASPUIUJH.js} +4 -4
- package/dist/cli/chunks/{test-scheduling-TRFHHKFM.js → test-scheduling-I7ABQBBU.js} +3 -3
- package/dist/cli/chunks/{token-bootstrap-KEQ7AHFF.js → token-bootstrap-2XZBTODN.js} +2 -2
- package/dist/cli/chunks/{token-usage-B54FOFOF.js → token-usage-TMUE6PTF.js} +2 -2
- package/dist/cli/chunks/{transformers-IACZG7IV.js → transformers-FDHHH4SL.js} +2 -2
- package/dist/cli/chunks/{tree-sitter-wasm-parser-N7H4X37E.js → tree-sitter-wasm-parser-G7PGZA5C.js} +2 -2
- package/dist/cli/chunks/{types-B3SHT4OD.js → types-JGT57UFP.js} +2 -2
- package/dist/cli/chunks/unified-memory-P5YVLMFI.js +2 -0
- package/dist/cli/chunks/unified-memory-hnsw-7HI43A2O.js +2 -0
- package/dist/cli/chunks/unified-persistence-U26YP3N3.js +2 -0
- package/dist/cli/chunks/{upgrade-A2PQ5EWK.js → upgrade-V6UQODJF.js} +2 -2
- package/dist/cli/chunks/{validate-UXV7UQUT.js → validate-UBZAE5RW.js} +2 -2
- package/dist/cli/chunks/{validate-swarm-MMBU4FPP.js → validate-swarm-TSO2MI5X.js} +2 -2
- package/dist/cli/chunks/{vibium-R4GUVADA.js → vibium-7G3VYSQA.js} +2 -2
- package/dist/cli/chunks/visual-security-6FCDY5FF.js +2 -0
- package/dist/cli/chunks/{web-tree-sitter-MP6E6CJB.js → web-tree-sitter-MIYJSF2L.js} +2 -2
- package/dist/cli/chunks/{windsurf-installer-Z6BWMUUO.js → windsurf-installer-5TLZSQIJ.js} +2 -2
- package/dist/cli/chunks/witness-chain-I3K3WQID.js +2 -0
- package/dist/cli/chunks/{witness-chain-EFLTABBA.js → witness-chain-LTV7H2HM.js} +2 -2
- package/dist/cli/chunks/{witness-key-manager-PN36TV43.js → witness-key-manager-PAJ2J4AL.js} +2 -2
- package/dist/cli/chunks/{workflow-A2AX3RJU.js → workflow-DL3ESR2H.js} +4 -4
- package/dist/cli/chunks/workflow-orchestrator-MAALP4WA.js +2 -0
- package/dist/cli/chunks/{wrappers-NA6FHA63.js → wrappers-5HSU665E.js} +2 -2
- package/dist/cli/handlers/init-handler.js +1 -1
- package/dist/coordination/handlers/coverage-collection.d.ts +161 -0
- package/dist/coordination/handlers/coverage-collection.js +639 -0
- package/dist/coordination/handlers/coverage-handlers.js +199 -146
- package/dist/coordination/handlers/handler-types.d.ts +6 -1
- package/dist/coordination/handlers/handler-utils.js +10 -3
- package/dist/coordination/handlers/security-handlers.js +17 -2
- package/dist/coordination/handlers/test-execution-handlers.js +16 -1
- package/dist/coordination/result-saver.js +119 -97
- package/dist/coordination/task-executor.d.ts +26 -1
- package/dist/coordination/task-executor.js +52 -4
- package/dist/domains/code-intelligence/services/knowledge-graph.js +8 -0
- package/dist/domains/coverage-analysis/services/coverage-analyzer.js +4 -0
- package/dist/domains/coverage-analysis/services/gap-detector.js +4 -0
- package/dist/domains/defect-intelligence/services/defect-predictor.js +4 -0
- package/dist/domains/defect-intelligence/services/root-cause-analyzer.js +4 -0
- package/dist/domains/quality-assessment/services/deployment-advisor.js +4 -0
- package/dist/domains/quality-assessment/services/quality-analyzer.js +4 -0
- package/dist/domains/security-compliance/services/scanners/sast-scanner.js +4 -0
- package/dist/domains/test-generation/index.js +17 -2
- package/dist/domains/test-generation/services/test-generator.js +31 -9
- package/dist/init/codex-installer.d.ts +13 -0
- package/dist/init/codex-installer.js +122 -1
- package/dist/init/phases/09-assets.js +4 -0
- package/dist/init/phases/phase-interface.d.ts +1 -1
- package/dist/learning/real-embeddings.js +15 -1
- package/dist/mcp/bundle.js +429 -419
- package/dist/mcp/handlers/domain-handler-configs.js +79 -14
- package/dist/mcp/types.d.ts +42 -4
- package/dist/optimization/session-cache.d.ts +13 -1
- package/dist/optimization/session-cache.js +27 -2
- package/dist/shared/llm/llm-router-service.js +59 -4
- package/dist/shared/llm/router/agent-router-config.d.ts +46 -2
- package/dist/shared/llm/router/agent-router-config.js +124 -2
- package/dist/shared/llm/router/config-store.d.ts +17 -1
- package/dist/shared/llm/router/config-store.js +103 -0
- package/dist/shared/llm/router/index.d.ts +2 -2
- package/dist/shared/llm/router/index.js +2 -0
- package/dist/shared/llm/router/types.d.ts +44 -0
- package/dist/shared/llm/router/types.js +1 -0
- package/package.json +9 -6
- package/dist/cli/chunks/adapter-CWIMFWAI.js +0 -2
- package/dist/cli/chunks/aqe-learning-engine-OTXT2DLN.js +0 -2
- package/dist/cli/chunks/base-O3SPSWBA.js +0 -2
- package/dist/cli/chunks/browser-workflow-MXS3ZKY2.js +0 -2
- package/dist/cli/chunks/chunk-G4GTE3RJ.js +0 -2
- package/dist/cli/chunks/chunk-HVB2L52I.js +0 -2
- package/dist/cli/chunks/chunk-MVI2QMRW.js +0 -2
- package/dist/cli/chunks/chunk-OZR25R7W.js +0 -2
- package/dist/cli/chunks/chunk-PP2RYSHT.js +0 -3
- package/dist/cli/chunks/client-33PGO5FA.js +0 -2
- package/dist/cli/chunks/codex-installer-C2CUP4FW.js +0 -8
- package/dist/cli/chunks/core-handlers-CSNZIM3A.js +0 -2
- package/dist/cli/chunks/cross-domain-router-DRIBR5L3.js +0 -2
- package/dist/cli/chunks/dream-WUNO723O.js +0 -2
- package/dist/cli/chunks/heartbeat-scheduler-VAFQDJLL.js +0 -2
- package/dist/cli/chunks/hnsw-adapter-TIRPA7XE.js +0 -2
- package/dist/cli/chunks/hnsw-index-SSQBRQCQ.js +0 -2
- package/dist/cli/chunks/hybrid-router-AKBWZOQ3.js +0 -2
- package/dist/cli/chunks/impact-analyzer-46FQIZ6Y.js +0 -2
- package/dist/cli/chunks/init-wizard-U3NHGYSS.js +0 -2
- package/dist/cli/chunks/kernel-ZDXHT6QF.js +0 -2
- package/dist/cli/chunks/knowledge-graph-6XTW6WO6.js +0 -2
- package/dist/cli/chunks/llm-router-service-3F4E64SY.js +0 -2
- package/dist/cli/chunks/load-test-SWZNGEIY.js +0 -2
- package/dist/cli/chunks/memory-backend-PR74ZPBA.js +0 -2
- package/dist/cli/chunks/pattern-null-store-EPE36BVT.js +0 -2
- package/dist/cli/chunks/protocol-executor-IELENNST.js +0 -2
- package/dist/cli/chunks/provider-manager-3R3KOBHG.js +0 -2
- package/dist/cli/chunks/qe-reasoning-bank-S2R2PCBS.js +0 -2
- package/dist/cli/chunks/queen-coordinator-2E23NEV4.js +0 -2
- package/dist/cli/chunks/router-3FVLWO6S.js +0 -2
- package/dist/cli/chunks/routing-feedback-ZQLRNNR7.js +0 -2
- package/dist/cli/chunks/rvf-native-adapter-YFGLQNEB.js +0 -2
- package/dist/cli/chunks/safe-db-4SBLBTW7.js +0 -2
- package/dist/cli/chunks/schedule-5Y3BGVAA.js +0 -2
- package/dist/cli/chunks/scheduler-DOID3QF3.js +0 -2
- package/dist/cli/chunks/sqlite-persistence-M4JEQO57.js +0 -2
- package/dist/cli/chunks/unified-memory-WNYWTGVX.js +0 -2
- package/dist/cli/chunks/unified-memory-hnsw-YPAV7U4E.js +0 -2
- package/dist/cli/chunks/unified-persistence-TJ252S7L.js +0 -2
- package/dist/cli/chunks/visual-security-VKYXEGJB.js +0 -2
- package/dist/cli/chunks/witness-chain-WVXRXKQP.js +0 -2
- package/dist/cli/chunks/workflow-orchestrator-GOWSPR3G.js +0 -2
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.
|
|
2
|
-
import{a as v,b as k}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.1");process.exit(0)}
|
|
2
|
+
import{a as v,b as k}from"./chunk-HUMQU4ES.js";import{i as g,m as P}from"./chunk-UCQ66N6M.js";import{a as d,b as y,c as R}from"./chunk-AYYDO52G.js";R();import{randomUUID as M}from"crypto";var p=class{constructor(e){this.config=e}config;_status="idle";_lastResult;_lastRunAt;_nextRunAt;_totalExecutions=0;_successfulExecutions=0;_failedExecutions=0;_executionDurations=[];_recentResults=[];get status(){return this._status}get lastResult(){return this._lastResult}get lastRunAt(){return this._lastRunAt}get nextRunAt(){return this._nextRunAt}async initialize(){this._status="idle",this._nextRunAt=new Date(Date.now()+this.config.intervalMs)}async execute(e){let r=Date.now();this._status="running",this._lastRunAt=new Date,this._totalExecutions++;let n,t;for(let a=0;a<=this.config.retryCount;a++)try{if(e.signal.aborted)throw new Error("Worker execution aborted");t=await this.executeWithTimeout(()=>this.doExecute(e),this.config.timeoutMs,e.signal);break}catch(u){n=y(u),e.logger.warn(`Worker ${this.config.id} attempt ${a+1} failed: ${n.message}`),a<this.config.retryCount&&await this.delay(this.config.retryDelayMs)}let o=Date.now()-r;return t?(this._successfulExecutions++,this._lastResult=t):(this._failedExecutions++,t=this.createErrorResult(n,o),this._lastResult=t),this._executionDurations.push(o),this._executionDurations.length>100&&this._executionDurations.shift(),this._recentResults.push({timestamp:new Date,success:t.success,durationMs:o}),this._recentResults.length>5&&this._recentResults.shift(),this._nextRunAt=new Date(Date.now()+this.config.intervalMs),this._status=t.success?"idle":"error",await e.eventBus.publish({type:"worker.executed",workerId:this.config.id,timestamp:new Date,payload:{success:t.success,durationMs:o,findingsCount:t.findings.length,healthScore:t.metrics.healthScore}}),t}pause(){this._status!=="stopped"&&(this._status="paused")}resume(){this._status==="paused"&&(this._status="idle")}async stop(){this._status="stopped"}getHealth(){let e=this._executionDurations.length>0?this._executionDurations.reduce((n,t)=>n+t,0)/this._executionDurations.length:0,r=this._totalExecutions>0?this._successfulExecutions/this._totalExecutions:1;return{status:this._status,healthScore:Math.round(r*100),totalExecutions:this._totalExecutions,successfulExecutions:this._successfulExecutions,failedExecutions:this._failedExecutions,avgDurationMs:Math.round(e),recentResults:[...this._recentResults]}}async executeWithTimeout(e,r,n){return new Promise((t,o)=>{let a=setTimeout(()=>{o(new Error(`Worker execution timed out after ${r}ms`))},r),u=()=>{clearTimeout(a),o(new Error("Worker execution aborted"))};n.addEventListener("abort",u,{once:!0}),e().then(c=>{clearTimeout(a),n.removeEventListener("abort",u),t(c)}).catch(c=>{clearTimeout(a),n.removeEventListener("abort",u),o(c)})})}createErrorResult(e,r){return{workerId:this.config.id,timestamp:new Date,durationMs:r,success:!1,error:e.message,metrics:{itemsAnalyzed:0,issuesFound:0,healthScore:0,trend:"degrading",domainMetrics:{}},findings:[],recommendations:[]}}createResult(e,r,n,t){return{workerId:this.config.id,timestamp:new Date,durationMs:e,success:!0,metrics:r,findings:n,recommendations:t}}delay(e){return new Promise(r=>setTimeout(r,e))}generateId(){return`${Date.now()}-${M().slice(0,9)}`}};P();R();var W={id:"heartbeat-scheduler",name:"Heartbeat Scheduler",description:"Token-free maintenance: pattern promotion, stale detection, experience buffer monitoring",intervalMs:1800*1e3,priority:"normal",targetDomains:["learning-optimization"],enabled:!0,timeoutMs:6e4,retryCount:1,retryDelayMs:5e3},b=class extends p{lifecycleManager=null;dailyLogger;lastRunTimestamp=0;constructor(){super(W),this.dailyLogger=new k}async getLifecycleManager(){if(this.lifecycleManager)return this.lifecycleManager;try{let e=g();await e.initialize();let r=e.getDatabase();return this.lifecycleManager=v(r,{promotionRewardThreshold:.7,promotionMinOccurrences:2,promotionMinSuccessRate:.7,deprecationFailureThreshold:3,staleDaysThreshold:30,confidenceDecayRate:.01,minActiveConfidence:.3}),this.lifecycleManager}catch{return null}}getPendingExperienceCount(){try{return g().getDatabase().prepare("SELECT COUNT(*) as pending FROM qe_pattern_usage WHERE created_at > datetime('now', '-1 day')").get()?.pending??0}catch{return 0}}async doExecute(e){let r=Date.now();e.logger.info("Heartbeat scheduler running (token-free maintenance)");let n=[],t=[],o=await this.getLifecycleManager();if(!o)return e.logger.warn("Unified memory unavailable \u2014 returning zero-metric heartbeat"),this.createResult(Date.now()-r,{itemsAnalyzed:0,issuesFound:0,healthScore:50,trend:"stable",domainMetrics:{promoted:0,deprecated:0,decayed:0,stalePatterns:0,pendingExperiences:0,avgConfidence:0,avgSuccessRate:0}},[],[]);let a=0,u=0;try{let s=o.promoteEligiblePatterns();a=s.promoted,u=s.checked,a>0&&n.push({type:"heartbeat-promotion",severity:"info",domain:"learning-optimization",title:"Patterns Promoted",description:`${a} of ${u} short-term patterns promoted to long-term`})}catch(s){e.logger.warn("Pattern promotion failed",{error:d(s)})}let c=0,h=0;try{let s=o.deprecateStalePatterns();c=s.deprecated,h=s.checked,c>0&&n.push({type:"heartbeat-deprecation",severity:"low",domain:"learning-optimization",title:"Stale Patterns Deprecated",description:`${c} of ${h} patterns deprecated (stale, failed, or low confidence)`})}catch(s){e.logger.warn("Stale pattern detection failed",{error:d(s)})}let l=0;try{let s=this.lastRunTimestamp>0?(Date.now()-this.lastRunTimestamp)/864e5:1;l=o.applyConfidenceDecay(Math.min(s,7)).decayed}catch(s){e.logger.warn("Confidence decay failed",{error:d(s)})}let m=this.getPendingExperienceCount(),i={totalPatterns:0,activePatterns:0,deprecatedPatterns:0,promotedPatterns:0,shortTermPatterns:0,longTermPatterns:0,avgConfidence:0,avgSuccessRate:0,patternsNearDeprecation:0};try{i=o.getStats()}catch(s){e.logger.warn("Stats retrieval failed",{error:d(s)})}try{this.dailyLogger.log({timestamp:new Date,type:"pattern-promoted",summary:`Heartbeat: ${a} promoted, ${c} deprecated, ${l} decayed, ${m} pending exp, ${i.activePatterns} active patterns (avg conf: ${i.avgConfidence.toFixed(2)})`,details:{promoted:a,deprecated:c,decayed:l,pendingExperiences:m,totalPatterns:i.totalPatterns,activePatterns:i.activePatterns,avgConfidence:i.avgConfidence,avgSuccessRate:i.avgSuccessRate}}),this.dailyLogger.flush()}catch(s){e.logger.warn("Daily log write failed",{error:d(s)})}this.lastRunTimestamp=Date.now(),i.activePatterns>0&&i.patternsNearDeprecation/i.activePatterns>.5&&t.push({priority:"p2",domain:"learning-optimization",action:"Review At-Risk Patterns",description:`${i.patternsNearDeprecation} of ${i.activePatterns} active patterns are near deprecation. Manual review recommended.`,estimatedImpact:"medium",effort:"low",autoFixable:!1});let f=this.calculateHealthScore(i,a,c),D=this.determineTrend(a,c,i.activePatterns),_=Math.max(u,h),x=a+c+i.patternsNearDeprecation;return e.logger.info("Heartbeat complete",{promoted:a,deprecated:c,decayed:l,pendingExperiences:m,healthScore:f}),this.createResult(Date.now()-r,{itemsAnalyzed:_,issuesFound:x,healthScore:f,trend:D,domainMetrics:{promoted:a,deprecated:c,decayed:l,stalePatterns:i.patternsNearDeprecation,pendingExperiences:m,avgConfidence:Number(i.avgConfidence.toFixed(3)),avgSuccessRate:Number(i.avgSuccessRate.toFixed(3))}},n,t)}calculateHealthScore(e,r,n){let t=70;if(t+=Math.min(15,r*5),e.avgConfidence>0&&(t+=Math.round((e.avgConfidence-.5)*30)),e.activePatterns>0){let o=n/e.activePatterns;t-=Math.round(o*20)}return e.activePatterns>0&&e.patternsNearDeprecation/e.activePatterns>.5&&(t-=10),Math.max(0,Math.min(100,Math.round(t)))}determineTrend(e,r,n){return n===0?"stable":e>r?"improving":r>e&&r/n>.1?"degrading":"stable"}};export{p as a,b};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.
|
|
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.13.1");process.exit(0)}
|
|
2
|
+
import{d as s}from"./chunk-ZLCATRXI.js";s();
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.
|
|
2
|
-
import{a as T}from"./chunk-HVB2L52I.js";import{c as S}from"./chunk-OXXMVQDF.js";import{b as C,d as P}from"./chunk-2DIT5AUU.js";import{a as b,c as $}from"./chunk-CYL2FV23.js";import{a as w,d as M}from"./chunk-RDU4WTV2.js";$();M();import{randomUUID as A}from"crypto";var x={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={...x,...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()}-${A().slice(0,8)}`,skill:n,model:c,trustTier:i,validationLevel:s,timeout:this.config.timeout,retryCount:0});return a}async executeTasksParallel(e,t){this.isRunning=!0,this.taskQueue=[...e];let i=[],s=t==="hierarchical"?this.config.maxConcurrentSkills:Math.min(this.config.maxConcurrentSkills*this.config.maxConcurrentModels,e.length),a=[];for(let n=0;n<Math.min(s,e.length);n++){let c=`worker-${n}`;this.workers.set(c,{id:c,task:null,status:"idle"}),a.push(this.runWorker(c,i))}return await Promise.all(a),this.isRunning=!1,this.workers.clear(),i}async runWorker(e,t){let i=this.workers.get(e);if(i){for(;this.taskQueue.length>0&&this.isRunning;){let s=this.taskQueue.shift();if(!s)break;i.task=s,i.status="running",i.startTime=Date.now();try{let a=await this.executeValidationTask(s);t.push(a),i.result=a,i.status="completed"}catch(a){let n=this.createErrorResult(s,a);this.config.retry&&s.retryCount<this.config.retry.maxRetries&&this.config.continueOnFailure?(s.retryCount++,this.taskQueue.push(s),await this.delay(this.config.retry.retryDelayMs)):(t.push(n),i.result=n,i.status="failed")}}i.task=null,i.status="idle"}}async executeValidationTask(e){let t=Date.now();if(!this.skillValidator)return this.createSimulatedResult(e,t);let i=new Promise((n,c)=>{setTimeout(()=>c(new Error(`Validation timeout after ${e.timeout}ms`)),e.timeout)}),s=await Promise.race([this.skillValidator(e.skill,e.model,{trustTier:e.trustTier,validationLevel:e.validationLevel,timeout:e.timeout}),i]),a=Date.now()-t;return this.outcomeToResult(s,e,a)}outcomeToResult(e,t,i){let s=e.testCaseResults.filter(c=>c.passed).length,a=e.testCaseResults.length,n=a>0?s/a:e.score;return{skill:t.skill,model:t.model,schemaValid:e.validationLevel!=="schema"||e.passed,validatorPassed:e.validationLevel!=="validator"||e.passed,evalPassRate:n,durationMs:i,errors:e.passed?[]:["Validation failed"],trustTier:t.trustTier,validationLevel:t.validationLevel,retryCount:t.retryCount,timestamp:new Date}}createSimulatedResult(e,t){let i=Date.now()-t+w()*100,s=.85+w()*.15;return{skill:e.skill,model:e.model,schemaValid:!0,validatorPassed:s>.8,evalPassRate:s,durationMs:i,errors:s>.8?[]:["Simulated validation failure"],trustTier:e.trustTier,validationLevel:e.validationLevel,retryCount:e.retryCount,timestamp:new Date}}createErrorResult(e,t){let i=b(t);return{skill:e.skill,model:e.model,schemaValid:!1,validatorPassed:!1,evalPassRate:0,durationMs:0,errors:[i],trustTier:e.trustTier,validationLevel:e.validationLevel,retryCount:e.retryCount,timestamp:new Date}}async recordOutcomesToLearner(e,t,i){for(let s of e){let a={skillName:s.skill,trustTier:s.trustTier||t,validationLevel:s.validationLevel||i,model:s.model,passed:s.errors.length===0&&s.evalPassRate>=.9,score:s.evalPassRate,testCaseResults:this.createTestCaseResults(s),timestamp:s.timestamp,runId:`swarm-${Date.now()}`,metadata:{duration:s.durationMs,retryCount:s.retryCount}};await this.learner.recordValidationOutcome(a)}}createTestCaseResults(e){return[{testId:`${e.skill}-${e.model}-aggregate`,passed:e.errors.length===0,expectedPatterns:["valid-output"],actualPatterns:e.errors.length===0?["valid-output"]:[],reasoningQuality:e.evalPassRate,executionTimeMs:e.durationMs,category:"swarm-validation",priority:"high",error:e.errors.length>0?e.errors.join("; "):void 0}]}delay(e){return new Promise(t=>setTimeout(t,e))}getConfig(){return{...this.config}}isValidationRunning(){return this.isRunning}getWorkerStatus(){return Array.from(this.workers.values())}cancel(){this.isRunning=!1,this.taskQueue=[]}};function D(y,e){return new R(y,e)}var F=["security-testing","accessibility-testing","api-testing","performance-testing","visual-regression-testing","mutation-testing","contract-testing","chaos-testing","compliance-testing","penetration-testing"],I=["claude-sonnet","claude-haiku","claude-opus"];P();import{readFileSync as E,writeFileSync as L,existsSync as N}from"fs";var O={varianceThreshold:.04,regressionThreshold:.1,minSamples:3,autoUpdateManifest:!1},k=class{constructor(e,t,i={}){this.learner=e;this.manifestPath=t;this.config={...O,...i}}learner;manifestPath;config;async aggregateResults(e){let t=`agg-${Date.now()}`,i=new Date,s=this.buildSkillResultsMap(e),a=this.calculateSummary(s,e),n=await this.detectCrossModelAnomalies(e),c=await this.detectRegressions(e,this.config.regressionThreshold),r=this.generateRecommendations(s,n,c),o={timestamp:i,runId:t,summary:a,skillResults:s,crossModelAnalysis:n,regressions:c,recommendations:r,metadata:{version:"1.0.0",environment:e[0]?.metadata?.environment,generatedBy:"ValidationResultAggregator",inputs:{runIds:e.map(l=>l.runId),models:[...new Set(e.map(l=>l.model))]}}};return this.config.autoUpdateManifest&&await this.updateManifest(o),o}buildSkillResultsMap(e){let t=new Map;for(let i of e)for(let s of i.outcomes){let a=s.skillName;t.has(a)||t.set(a,{skill:a,trustTier:s.trustTier,passRateByModel:new Map,avgPassRate:0,schemaValid:!0,validatorPassed:!0,evalPassed:!0,issues:[],executionTimeMs:0,testCount:0,passedTests:0,failedTests:0});let n=t.get(a),c=s.testCaseResults.filter(r=>r.passed).length/(s.testCaseResults.length||1);n.passRateByModel.set(i.model,c),n.testCount+=s.testCaseResults.length,n.passedTests+=s.testCaseResults.filter(r=>r.passed).length,n.failedTests+=s.testCaseResults.filter(r=>!r.passed).length,n.executionTimeMs+=s.metadata?.duration||0,s.validationLevel==="schema"&&!s.passed&&(n.schemaValid=!1),s.validationLevel==="validator"&&!s.passed&&(n.validatorPassed=!1),s.validationLevel==="eval"&&!s.passed&&(n.evalPassed=!1);for(let r of s.testCaseResults)!r.passed&&r.error&&n.issues.push({skill:a,model:i.model,severity:r.priority==="critical"?"critical":r.priority==="high"?"high":r.priority==="medium"?"medium":"low",type:this.categorizeIssueType(s.validationLevel,r.error),message:r.error,testId:r.testId})}for(let i of t.values()){let s=Array.from(i.passRateByModel.values());i.avgPassRate=s.length>0?s.reduce((a,n)=>a+n,0)/s.length:0}return t}categorizeIssueType(e,t){return t.toLowerCase().includes("timeout")?"timeout":e==="schema"?"schema_failure":e==="validator"?"validator_failure":e==="eval"?"eval_failure":"error"}calculateSummary(e,t){let i=Array.from(e.values()),s=i.filter(n=>n.avgPassRate>=.9).length,a=i.length>0?i.reduce((n,c)=>n+c.avgPassRate,0)/i.length:0;return{totalSkills:i.length,passedSkills:s,failedSkills:i.length-s,avgPassRate:a,totalDurationMs:t.reduce((n,c)=>n+c.durationMs,0),totalTests:i.reduce((n,c)=>n+c.testCount,0),passedTests:i.reduce((n,c)=>n+c.passedTests,0),failedTests:i.reduce((n,c)=>n+c.failedTests,0),modelsUsed:[...new Set(t.map(n=>n.model))]}}async detectCrossModelAnomalies(e){let t=new Map,i=new Map,s=new Map;for(let d of e){t.has(d.model)||(t.set(d.model,[]),i.set(d.model,{totalTests:0,passedTests:0,skillCount:0}));for(let g of d.outcomes){let h=g.testCaseResults.filter(m=>m.passed).length/(g.testCaseResults.length||1);t.get(d.model).push(h);let f=i.get(d.model);f.totalTests+=g.testCaseResults.length,f.passedTests+=g.testCaseResults.filter(m=>m.passed).length,f.skillCount++,s.has(g.skillName)||s.set(g.skillName,{passRates:[],models:[]}),s.get(g.skillName).passRates.push(h),s.get(g.skillName).models.push(d.model)}}let a=[];for(let d of t.values())a.push(...d);let n=a.length>0?a.reduce((d,g)=>d+g,0)/a.length:0,c=a.length>1?a.reduce((d,g)=>d+Math.pow(g-n,2),0)/a.length:0,r=Math.sqrt(c),o=[],l=new Map;for(let[d,g]of t.entries()){let h=g.reduce((v,V)=>v+V,0)/g.length,f=h-n,m=i.get(d);l.set(d,{avgPassRate:h,skillCount:m.skillCount,totalTests:m.totalTests}),Math.abs(f)>this.config.varianceThreshold*2&&o.push({model:d,type:f<0?"low_performance":"high_variance",description:`Model ${d} has ${(f*100).toFixed(1)}% difference from average`,passRate:h,avgPassRate:n,deviation:Math.abs(f)})}let u=[],p=[];for(let[d,g]of s.entries()){if(g.passRates.length<2)continue;let h=g.passRates.reduce((m,v)=>m+v,0)/g.passRates.length;g.passRates.reduce((m,v)=>m+Math.pow(v-h,2),0)/g.passRates.length<this.config.varianceThreshold?u.push(d):p.push(d)}return{variance:c,stdDeviation:r,anomalies:o,consistentSkills:u,inconsistentSkills:p,modelPerformance:l}}async detectRegressions(e,t){let i=[],s=new Set;for(let a of e)for(let n of a.outcomes){let c=`${n.skillName}-${a.model}`;if(s.has(c))continue;s.add(c);let r=await this.learner.getValidationTrends(n.skillName);if(!r)continue;let o=n.testCaseResults.filter(p=>p.passed).length/(n.testCaseResults.length||1),l=r.recentPassRate,u=l-o;u>=t&&i.push({skill:n.skillName,model:a.model,previousPassRate:l,currentPassRate:o,regressionAmount:u,trend:r.overall,possibleCauses:this.analyzePossibleCauses(n,u),severity:this.categorizeRegressionSeverity(u)})}return i.sort((a,n)=>{let c={critical:0,high:1,medium:2,low:3},r=c[a.severity]-c[n.severity];return r!==0?r:n.regressionAmount-a.regressionAmount})}analyzePossibleCauses(e,t){let i=[],s=e.testCaseResults.filter(c=>!c.passed);if(s.length>0){let c=[...new Set(s.map(r=>r.category).filter(Boolean))];c.length>0&&i.push(`Failures in categories: ${c.join(", ")}`)}let a=s.filter(c=>c.priority==="critical");a.length>0&&i.push(`${a.length} critical test(s) failing`);let n=e.testCaseResults.reduce((c,r)=>c+r.reasoningQuality,0)/(e.testCaseResults.length||1);return n<.7&&i.push(`Low reasoning quality score: ${(n*100).toFixed(1)}%`),t>.3&&i.push("Possible model behavior change or prompt drift"),i.length===0&&i.push("No specific cause identified - review test details"),i}categorizeRegressionSeverity(e){return e>=.5?"critical":e>=.3?"high":e>=.15?"medium":"low"}generateRecommendations(e,t,i){let s=[];if(t.inconsistentSkills.length>0&&s.push(`Review ${t.inconsistentSkills.length} skills with inconsistent cross-model behavior: `+t.inconsistentSkills.slice(0,3).join(", ")+(t.inconsistentSkills.length>3?` and ${t.inconsistentSkills.length-3} more`:"")),t.anomalies.some(r=>r.type==="low_performance")){let r=t.anomalies.filter(o=>o.type==="low_performance").map(o=>o.model);s.push(`Investigate low performance on model(s): ${r.join(", ")}`)}let a=i.filter(r=>r.severity==="critical");a.length>0&&s.push(`URGENT: ${a.length} critical regression(s) detected - immediate review required`);let n=Array.from(e.values()).filter(r=>r.avgPassRate<.9);if(n.length>0){let r=n.filter(l=>!l.schemaValid),o=n.filter(l=>!l.validatorPassed);r.length>0&&s.push(`Fix schema validation for: ${r.map(l=>l.skill).slice(0,3).join(", ")}`),o.length>0&&s.push(`Review validator scripts for: ${o.map(l=>l.skill).slice(0,3).join(", ")}`)}return Array.from(e.values()).reduce((r,o)=>r+o.avgPassRate,0)/e.size<.8&&s.push("Overall pass rate below 80% - consider reviewing skill definitions and test expectations"),s.length===0&&s.push("All validations passing - no immediate action required"),s}async updateManifest(e){if(!N(this.manifestPath))throw new Error(`Manifest file not found: ${this.manifestPath}`);let t=C(E(this.manifestPath,"utf-8"));for(let[s,a]of e.skillResults.entries())if(t.skills&&t.skills[s]){let n=t.skills[s];n.validation||(n.validation={}),n.validation.passRate=a.avgPassRate,n.validation.lastValidated=e.timestamp.toISOString(),n.validation.status=a.avgPassRate>=.9?"passing":"failing",n.validation.passRateByModel=Object.fromEntries(a.passRateByModel)}let i=Array.from(e.skillResults.values());t.validationStatus={passing:i.filter(s=>s.avgPassRate>=.9).length,failing:i.filter(s=>s.avgPassRate<.9).length,unknown:0,skipped:t.summary?.tier0||0},t.generatedAt=new Date().toISOString(),t.lastValidationRun={runId:e.runId,timestamp:e.timestamp.toISOString(),avgPassRate:e.summary.avgPassRate,modelsUsed:e.summary.modelsUsed},L(this.manifestPath,JSON.stringify(t,null,2))}generateMarkdownReport(e){let{summary:t,crossModelAnalysis:i,regressions:s,recommendations:a,skillResults:n}=e,c=(t.avgPassRate>=.9||t.avgPassRate>=.7,"`"),r=[];if(r.push(`# Validation Report
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.1");process.exit(0)}
|
|
2
|
+
import{a as T}from"./chunk-BBLWZT5I.js";import{c as S}from"./chunk-ELMUHNXN.js";import{b as C,d as P}from"./chunk-ZLCATRXI.js";import{a as b,c as $}from"./chunk-AYYDO52G.js";import{a as w,d as M}from"./chunk-3K4YC3GC.js";$();M();import{randomUUID as A}from"crypto";var x={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={...x,...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()}-${A().slice(0,8)}`,skill:n,model:c,trustTier:i,validationLevel:s,timeout:this.config.timeout,retryCount:0});return a}async executeTasksParallel(e,t){this.isRunning=!0,this.taskQueue=[...e];let i=[],s=t==="hierarchical"?this.config.maxConcurrentSkills:Math.min(this.config.maxConcurrentSkills*this.config.maxConcurrentModels,e.length),a=[];for(let n=0;n<Math.min(s,e.length);n++){let c=`worker-${n}`;this.workers.set(c,{id:c,task:null,status:"idle"}),a.push(this.runWorker(c,i))}return await Promise.all(a),this.isRunning=!1,this.workers.clear(),i}async runWorker(e,t){let i=this.workers.get(e);if(i){for(;this.taskQueue.length>0&&this.isRunning;){let s=this.taskQueue.shift();if(!s)break;i.task=s,i.status="running",i.startTime=Date.now();try{let a=await this.executeValidationTask(s);t.push(a),i.result=a,i.status="completed"}catch(a){let n=this.createErrorResult(s,a);this.config.retry&&s.retryCount<this.config.retry.maxRetries&&this.config.continueOnFailure?(s.retryCount++,this.taskQueue.push(s),await this.delay(this.config.retry.retryDelayMs)):(t.push(n),i.result=n,i.status="failed")}}i.task=null,i.status="idle"}}async executeValidationTask(e){let t=Date.now();if(!this.skillValidator)return this.createSimulatedResult(e,t);let i=new Promise((n,c)=>{setTimeout(()=>c(new Error(`Validation timeout after ${e.timeout}ms`)),e.timeout)}),s=await Promise.race([this.skillValidator(e.skill,e.model,{trustTier:e.trustTier,validationLevel:e.validationLevel,timeout:e.timeout}),i]),a=Date.now()-t;return this.outcomeToResult(s,e,a)}outcomeToResult(e,t,i){let s=e.testCaseResults.filter(c=>c.passed).length,a=e.testCaseResults.length,n=a>0?s/a:e.score;return{skill:t.skill,model:t.model,schemaValid:e.validationLevel!=="schema"||e.passed,validatorPassed:e.validationLevel!=="validator"||e.passed,evalPassRate:n,durationMs:i,errors:e.passed?[]:["Validation failed"],trustTier:t.trustTier,validationLevel:t.validationLevel,retryCount:t.retryCount,timestamp:new Date}}createSimulatedResult(e,t){let i=Date.now()-t+w()*100,s=.85+w()*.15;return{skill:e.skill,model:e.model,schemaValid:!0,validatorPassed:s>.8,evalPassRate:s,durationMs:i,errors:s>.8?[]:["Simulated validation failure"],trustTier:e.trustTier,validationLevel:e.validationLevel,retryCount:e.retryCount,timestamp:new Date}}createErrorResult(e,t){let i=b(t);return{skill:e.skill,model:e.model,schemaValid:!1,validatorPassed:!1,evalPassRate:0,durationMs:0,errors:[i],trustTier:e.trustTier,validationLevel:e.validationLevel,retryCount:e.retryCount,timestamp:new Date}}async recordOutcomesToLearner(e,t,i){for(let s of e){let a={skillName:s.skill,trustTier:s.trustTier||t,validationLevel:s.validationLevel||i,model:s.model,passed:s.errors.length===0&&s.evalPassRate>=.9,score:s.evalPassRate,testCaseResults:this.createTestCaseResults(s),timestamp:s.timestamp,runId:`swarm-${Date.now()}`,metadata:{duration:s.durationMs,retryCount:s.retryCount}};await this.learner.recordValidationOutcome(a)}}createTestCaseResults(e){return[{testId:`${e.skill}-${e.model}-aggregate`,passed:e.errors.length===0,expectedPatterns:["valid-output"],actualPatterns:e.errors.length===0?["valid-output"]:[],reasoningQuality:e.evalPassRate,executionTimeMs:e.durationMs,category:"swarm-validation",priority:"high",error:e.errors.length>0?e.errors.join("; "):void 0}]}delay(e){return new Promise(t=>setTimeout(t,e))}getConfig(){return{...this.config}}isValidationRunning(){return this.isRunning}getWorkerStatus(){return Array.from(this.workers.values())}cancel(){this.isRunning=!1,this.taskQueue=[]}};function D(y,e){return new R(y,e)}var F=["security-testing","accessibility-testing","api-testing","performance-testing","visual-regression-testing","mutation-testing","contract-testing","chaos-testing","compliance-testing","penetration-testing"],I=["claude-sonnet","claude-haiku","claude-opus"];P();import{readFileSync as E,writeFileSync as L,existsSync as N}from"fs";var O={varianceThreshold:.04,regressionThreshold:.1,minSamples:3,autoUpdateManifest:!1},k=class{constructor(e,t,i={}){this.learner=e;this.manifestPath=t;this.config={...O,...i}}learner;manifestPath;config;async aggregateResults(e){let t=`agg-${Date.now()}`,i=new Date,s=this.buildSkillResultsMap(e),a=this.calculateSummary(s,e),n=await this.detectCrossModelAnomalies(e),c=await this.detectRegressions(e,this.config.regressionThreshold),r=this.generateRecommendations(s,n,c),o={timestamp:i,runId:t,summary:a,skillResults:s,crossModelAnalysis:n,regressions:c,recommendations:r,metadata:{version:"1.0.0",environment:e[0]?.metadata?.environment,generatedBy:"ValidationResultAggregator",inputs:{runIds:e.map(l=>l.runId),models:[...new Set(e.map(l=>l.model))]}}};return this.config.autoUpdateManifest&&await this.updateManifest(o),o}buildSkillResultsMap(e){let t=new Map;for(let i of e)for(let s of i.outcomes){let a=s.skillName;t.has(a)||t.set(a,{skill:a,trustTier:s.trustTier,passRateByModel:new Map,avgPassRate:0,schemaValid:!0,validatorPassed:!0,evalPassed:!0,issues:[],executionTimeMs:0,testCount:0,passedTests:0,failedTests:0});let n=t.get(a),c=s.testCaseResults.filter(r=>r.passed).length/(s.testCaseResults.length||1);n.passRateByModel.set(i.model,c),n.testCount+=s.testCaseResults.length,n.passedTests+=s.testCaseResults.filter(r=>r.passed).length,n.failedTests+=s.testCaseResults.filter(r=>!r.passed).length,n.executionTimeMs+=s.metadata?.duration||0,s.validationLevel==="schema"&&!s.passed&&(n.schemaValid=!1),s.validationLevel==="validator"&&!s.passed&&(n.validatorPassed=!1),s.validationLevel==="eval"&&!s.passed&&(n.evalPassed=!1);for(let r of s.testCaseResults)!r.passed&&r.error&&n.issues.push({skill:a,model:i.model,severity:r.priority==="critical"?"critical":r.priority==="high"?"high":r.priority==="medium"?"medium":"low",type:this.categorizeIssueType(s.validationLevel,r.error),message:r.error,testId:r.testId})}for(let i of t.values()){let s=Array.from(i.passRateByModel.values());i.avgPassRate=s.length>0?s.reduce((a,n)=>a+n,0)/s.length:0}return t}categorizeIssueType(e,t){return t.toLowerCase().includes("timeout")?"timeout":e==="schema"?"schema_failure":e==="validator"?"validator_failure":e==="eval"?"eval_failure":"error"}calculateSummary(e,t){let i=Array.from(e.values()),s=i.filter(n=>n.avgPassRate>=.9).length,a=i.length>0?i.reduce((n,c)=>n+c.avgPassRate,0)/i.length:0;return{totalSkills:i.length,passedSkills:s,failedSkills:i.length-s,avgPassRate:a,totalDurationMs:t.reduce((n,c)=>n+c.durationMs,0),totalTests:i.reduce((n,c)=>n+c.testCount,0),passedTests:i.reduce((n,c)=>n+c.passedTests,0),failedTests:i.reduce((n,c)=>n+c.failedTests,0),modelsUsed:[...new Set(t.map(n=>n.model))]}}async detectCrossModelAnomalies(e){let t=new Map,i=new Map,s=new Map;for(let d of e){t.has(d.model)||(t.set(d.model,[]),i.set(d.model,{totalTests:0,passedTests:0,skillCount:0}));for(let g of d.outcomes){let h=g.testCaseResults.filter(m=>m.passed).length/(g.testCaseResults.length||1);t.get(d.model).push(h);let f=i.get(d.model);f.totalTests+=g.testCaseResults.length,f.passedTests+=g.testCaseResults.filter(m=>m.passed).length,f.skillCount++,s.has(g.skillName)||s.set(g.skillName,{passRates:[],models:[]}),s.get(g.skillName).passRates.push(h),s.get(g.skillName).models.push(d.model)}}let a=[];for(let d of t.values())a.push(...d);let n=a.length>0?a.reduce((d,g)=>d+g,0)/a.length:0,c=a.length>1?a.reduce((d,g)=>d+Math.pow(g-n,2),0)/a.length:0,r=Math.sqrt(c),o=[],l=new Map;for(let[d,g]of t.entries()){let h=g.reduce((v,V)=>v+V,0)/g.length,f=h-n,m=i.get(d);l.set(d,{avgPassRate:h,skillCount:m.skillCount,totalTests:m.totalTests}),Math.abs(f)>this.config.varianceThreshold*2&&o.push({model:d,type:f<0?"low_performance":"high_variance",description:`Model ${d} has ${(f*100).toFixed(1)}% difference from average`,passRate:h,avgPassRate:n,deviation:Math.abs(f)})}let u=[],p=[];for(let[d,g]of s.entries()){if(g.passRates.length<2)continue;let h=g.passRates.reduce((m,v)=>m+v,0)/g.passRates.length;g.passRates.reduce((m,v)=>m+Math.pow(v-h,2),0)/g.passRates.length<this.config.varianceThreshold?u.push(d):p.push(d)}return{variance:c,stdDeviation:r,anomalies:o,consistentSkills:u,inconsistentSkills:p,modelPerformance:l}}async detectRegressions(e,t){let i=[],s=new Set;for(let a of e)for(let n of a.outcomes){let c=`${n.skillName}-${a.model}`;if(s.has(c))continue;s.add(c);let r=await this.learner.getValidationTrends(n.skillName);if(!r)continue;let o=n.testCaseResults.filter(p=>p.passed).length/(n.testCaseResults.length||1),l=r.recentPassRate,u=l-o;u>=t&&i.push({skill:n.skillName,model:a.model,previousPassRate:l,currentPassRate:o,regressionAmount:u,trend:r.overall,possibleCauses:this.analyzePossibleCauses(n,u),severity:this.categorizeRegressionSeverity(u)})}return i.sort((a,n)=>{let c={critical:0,high:1,medium:2,low:3},r=c[a.severity]-c[n.severity];return r!==0?r:n.regressionAmount-a.regressionAmount})}analyzePossibleCauses(e,t){let i=[],s=e.testCaseResults.filter(c=>!c.passed);if(s.length>0){let c=[...new Set(s.map(r=>r.category).filter(Boolean))];c.length>0&&i.push(`Failures in categories: ${c.join(", ")}`)}let a=s.filter(c=>c.priority==="critical");a.length>0&&i.push(`${a.length} critical test(s) failing`);let n=e.testCaseResults.reduce((c,r)=>c+r.reasoningQuality,0)/(e.testCaseResults.length||1);return n<.7&&i.push(`Low reasoning quality score: ${(n*100).toFixed(1)}%`),t>.3&&i.push("Possible model behavior change or prompt drift"),i.length===0&&i.push("No specific cause identified - review test details"),i}categorizeRegressionSeverity(e){return e>=.5?"critical":e>=.3?"high":e>=.15?"medium":"low"}generateRecommendations(e,t,i){let s=[];if(t.inconsistentSkills.length>0&&s.push(`Review ${t.inconsistentSkills.length} skills with inconsistent cross-model behavior: `+t.inconsistentSkills.slice(0,3).join(", ")+(t.inconsistentSkills.length>3?` and ${t.inconsistentSkills.length-3} more`:"")),t.anomalies.some(r=>r.type==="low_performance")){let r=t.anomalies.filter(o=>o.type==="low_performance").map(o=>o.model);s.push(`Investigate low performance on model(s): ${r.join(", ")}`)}let a=i.filter(r=>r.severity==="critical");a.length>0&&s.push(`URGENT: ${a.length} critical regression(s) detected - immediate review required`);let n=Array.from(e.values()).filter(r=>r.avgPassRate<.9);if(n.length>0){let r=n.filter(l=>!l.schemaValid),o=n.filter(l=>!l.validatorPassed);r.length>0&&s.push(`Fix schema validation for: ${r.map(l=>l.skill).slice(0,3).join(", ")}`),o.length>0&&s.push(`Review validator scripts for: ${o.map(l=>l.skill).slice(0,3).join(", ")}`)}return Array.from(e.values()).reduce((r,o)=>r+o.avgPassRate,0)/e.size<.8&&s.push("Overall pass rate below 80% - consider reviewing skill definitions and test expectations"),s.length===0&&s.push("All validations passing - no immediate action required"),s}async updateManifest(e){if(!N(this.manifestPath))throw new Error(`Manifest file not found: ${this.manifestPath}`);let t=C(E(this.manifestPath,"utf-8"));for(let[s,a]of e.skillResults.entries())if(t.skills&&t.skills[s]){let n=t.skills[s];n.validation||(n.validation={}),n.validation.passRate=a.avgPassRate,n.validation.lastValidated=e.timestamp.toISOString(),n.validation.status=a.avgPassRate>=.9?"passing":"failing",n.validation.passRateByModel=Object.fromEntries(a.passRateByModel)}let i=Array.from(e.skillResults.values());t.validationStatus={passing:i.filter(s=>s.avgPassRate>=.9).length,failing:i.filter(s=>s.avgPassRate<.9).length,unknown:0,skipped:t.summary?.tier0||0},t.generatedAt=new Date().toISOString(),t.lastValidationRun={runId:e.runId,timestamp:e.timestamp.toISOString(),avgPassRate:e.summary.avgPassRate,modelsUsed:e.summary.modelsUsed},L(this.manifestPath,JSON.stringify(t,null,2))}generateMarkdownReport(e){let{summary:t,crossModelAnalysis:i,regressions:s,recommendations:a,skillResults:n}=e,c=(t.avgPassRate>=.9||t.avgPassRate>=.7,"`"),r=[];if(r.push(`# Validation Report
|
|
3
3
|
|
|
4
4
|
> ${c} Generated: ${e.timestamp.toISOString()}
|
|
5
5
|
> Run ID: ${e.runId}
|
|
@@ -1,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.13.
|
|
2
|
-
import{a as
|
|
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.13.1");process.exit(0)}
|
|
2
|
+
import{a as D,c as ee}from"./chunk-AYYDO52G.js";import{b as L,d as B}from"./chunk-DVPGQG4W.js";B();ee();B();import*as x from"node:http";import*as O from"node:https";import{createHash as te}from"node:crypto";import{URL as W}from"node:url";var T={model:"Xenova/all-MiniLM-L6-v2",expectedDim:384,connectTimeoutMs:5e3,requestTimeoutMs:3e4,failureThreshold:3,failureWindowMs:6e4},ne="AQE embedder endpoint identity canary v1",re="/v1/embeddings";function X(n){if(n.startsWith("unix:"))return n;try{let e=new W(n);return e.username||e.password?(e.username="",e.password="",e.toString().replace(/\/$/,"")):n}catch{return n}}function ie(n){if(n.startsWith("unix:")){let r=n.slice(5);if(!r.startsWith("/"))throw new Error(`unix endpoint must be an absolute path: ${n}`);return{transport:"unix",socketPath:r,safeUrl:n}}let e=new W(n);if(e.protocol!=="http:"&&e.protocol!=="https:")throw new Error(`unsupported embedder endpoint protocol: ${e.protocol}`);return(e.username||e.password)&&(console.warn("[EmbedderEndpointClient] endpoint URL contained userinfo; stripping. Use AQE_EMBEDDER_TOKEN env var for credentials."),e.username="",e.password=""),{transport:e.protocol==="https:"?"https":"http",host:e.hostname,port:e.port?Number(e.port):e.protocol==="https:"?443:80,protocol:e.protocol,safeUrl:e.toString().replace(/\/$/,"")}}var S=class{constructor(e,t,r=()=>{}){this.threshold=e;this.windowMs=t;this.onRecover=r}threshold;windowMs;onRecover;failures=[];trippedAt=null;recordSuccess(){this.failures=[],this.trippedAt=null}recordFailure(){let e=Date.now();this.failures=this.failures.filter(t=>e-t<this.windowMs),this.failures.push(e),this.failures.length>=this.threshold&&(this.trippedAt=e)}isOpen(){return this.trippedAt===null?!1:Date.now()-this.trippedAt>=this.windowMs?(this.failures=[],this.trippedAt=null,this.onRecover(),!1):!0}getState(){return{open:this.isOpen(),failures:this.failures.length,trippedAt:this.trippedAt}}},P=class{parsed;agent;breaker;opts;cachedIdentity=null;probeInFlight=null;constructor(e){if(this.opts={endpoint:e.endpoint,token:e.token,model:e.model??T.model,expectedDim:e.expectedDim??T.expectedDim,connectTimeoutMs:e.connectTimeoutMs??T.connectTimeoutMs,requestTimeoutMs:e.requestTimeoutMs??T.requestTimeoutMs,failureThreshold:e.failureThreshold??T.failureThreshold,failureWindowMs:e.failureWindowMs??T.failureWindowMs,tlsOptions:e.tlsOptions},this.parsed=ie(e.endpoint),this.parsed.transport==="https"){let t=e.tlsOptions??{};this.agent=new O.Agent({keepAlive:!0,ca:t.ca,cert:t.cert,key:t.key,rejectUnauthorized:t.rejectUnauthorized!==!1,servername:t.servername})}else this.agent=new x.Agent({keepAlive:!0});this.breaker=new S(this.opts.failureThreshold,this.opts.failureWindowMs,()=>{this.cachedIdentity=null})}getSafeEndpoint(){return this.parsed.safeUrl}async embed(e){if(e.length===0)return[];if(this.breaker.isOpen())throw new Error(`[EmbedderEndpointClient] circuit breaker open for ${this.parsed.safeUrl} \u2014 fast-failing`);this.cachedIdentity===null&&await this.ensureProbed();try{let t=await this.postEmbeddings(e),r=this.decodeAndNormalize(t,e.length);return this.breaker.recordSuccess(),r}catch(t){throw this.breaker.recordFailure(),t}}async probe(){return this.probeInFlight?this.probeInFlight:(this.probeInFlight=this.doProbe().finally(()=>{this.probeInFlight=null}),this.probeInFlight)}async ensureProbed(){return this.cachedIdentity?this.cachedIdentity:this.probe()}async doProbe(){let e;try{let s=await this.postEmbeddings([ne]);e=this.decodeAndNormalize(s,1)[0],this.breaker.recordSuccess()}catch(s){throw this.breaker.recordFailure(),s}if(!e||e.length!==this.opts.expectedDim)throw new Error(`[EmbedderEndpointClient] dim mismatch: expected ${this.opts.expectedDim}, got ${e?.length??0} from ${this.parsed.safeUrl}`);let t=Buffer.alloc(e.length*2);for(let s=0;s<e.length;s++){let o=Math.max(-32768,Math.min(32767,Math.round(e[s]*32767)));t.writeInt16LE(o,s*2)}let r=te("sha256").update(t).digest("hex").slice(0,16);return this.cachedIdentity={dim:e.length,fingerprint:r,endpoint:this.parsed.safeUrl},this.cachedIdentity}getCachedIdentity(){return this.cachedIdentity}getBreakerState(){return this.breaker.getState()}close(){this.agent.destroy()}decodeAndNormalize(e,t){if(!e||typeof e!="object"||!Array.isArray(e.data))throw new Error("[EmbedderEndpointClient] response missing data array");let r=e.data;if(r.length!==t)throw new Error(`[EmbedderEndpointClient] response count mismatch: expected ${t}, got ${r.length}`);let s=r.map((o,i)=>({idx:typeof o.index=="number"?o.index:i,embedding:o.embedding}));return s.sort((o,i)=>o.idx-i.idx),s.map(({embedding:o},i)=>{if(typeof o=="string")throw new Error(`[EmbedderEndpointClient] received base64 embedding at position ${i} \u2014 server ignored encoding_format=float. Configure the server to return float arrays.`);if(!Array.isArray(o))throw new Error(`[EmbedderEndpointClient] missing embedding at position ${i}`);if(o.length!==this.opts.expectedDim)throw new Error(`[EmbedderEndpointClient] dim mismatch at position ${i}: expected ${this.opts.expectedDim}, got ${o.length}`);return L(o)})}postEmbeddings(e){let t=JSON.stringify({model:this.opts.model,input:e,encoding_format:"float"});return this.request(re,t)}request(e,t){let r={"content-type":"application/json","content-length":Buffer.byteLength(t),accept:"application/json"};this.opts.token&&(r.authorization=`Bearer ${this.opts.token}`);let s={method:"POST",path:e,headers:r,agent:this.agent},o,i;this.parsed.transport==="unix"?(o={...s,socketPath:this.parsed.socketPath},i=x.request):(o={...s,host:this.parsed.host,port:this.parsed.port,protocol:this.parsed.protocol},i=this.parsed.transport==="https"?O.request:x.request);let l=this.parsed.safeUrl,c=this.opts.connectTimeoutMs,h=this.opts.requestTimeoutMs;return new Promise((N,I)=>{let E=!1,C=a=>{E||(E=!0,N(a))},y=a=>{E||(E=!0,I(a))},f=i(o,a=>{let g=[];a.on("data",u=>g.push(Buffer.from(u))),a.on("end",()=>{let u=Buffer.concat(g).toString("utf-8");if(!a.statusCode||a.statusCode<200||a.statusCode>=300){y(new Error(`[EmbedderEndpointClient] HTTP ${a.statusCode} from ${l}: ${u.slice(0,200)}`));return}try{let b=JSON.parse(u);C(b)}catch(b){y(new Error(`[EmbedderEndpointClient] invalid JSON from ${l}: ${b.message}`))}}),a.on("error",u=>y(u))});f.on("socket",a=>{a.setTimeout(c);let g=()=>{a.setTimeout(h)};a.connecting?a.once("connect",g):g(),a.on("timeout",()=>{let u=a.connecting?"connect":"request",b=a.connecting?c:h,M=new Error(`[EmbedderEndpointClient] ${u} timeout after ${b}ms`);y(M),f.destroy(M)})}),f.on("error",a=>y(a)),f.write(t),f.end()})}};import{join as H}from"node:path";import{existsSync as oe,mkdirSync as se}from"node:fs";import{createRequire as ae}from"node:module";var de=ae(import.meta.url);function le(){let n=process.env.AQE_MEMORY_PATH;return n&&n.length>0?n:H(process.cwd(),".agentic-qe","memory.db")}var j="_system",G="embedder_identity:",v=null,$=!1;function K(){if(v)return v;if($)return null;try{let n=de("better-sqlite3"),e=le(),t=H(e,"..");oe(t)||se(t,{recursive:!0});let r=new n(e);return r.pragma("journal_mode = WAL"),r.pragma("busy_timeout = 5000"),r.exec(`
|
|
3
3
|
CREATE TABLE IF NOT EXISTS kv_store (
|
|
4
4
|
key TEXT NOT NULL,
|
|
5
5
|
namespace TEXT NOT NULL,
|
|
@@ -9,4 +9,4 @@ import{a as N,c as ee}from"./chunk-CYL2FV23.js";import{b as L,d as B}from"./chun
|
|
|
9
9
|
PRIMARY KEY (namespace, key)
|
|
10
10
|
);
|
|
11
11
|
CREATE INDEX IF NOT EXISTS idx_kv_namespace ON kv_store(namespace);
|
|
12
|
-
`),v=r,r}catch{return $=!0,null}}function
|
|
12
|
+
`),v=r,r}catch{return $=!0,null}}function Q(n){let e=K();if(!e)return null;try{let t=e.prepare("SELECT value FROM kv_store WHERE namespace = ? AND key = ?").get(j,G+n);if(!t)return null;let r=JSON.parse(t.value);return!r.fingerprint||typeof r.dim!="number"?null:{fingerprint:r.fingerprint,dim:r.dim,endpoint:r.endpoint}}catch{return null}}function J(n){let e=K();if(!e)return;let t={fingerprint:n.fingerprint,dim:n.dim,endpoint:n.endpoint,updatedAt:Date.now()};e.prepare("INSERT OR REPLACE INTO kv_store (key, namespace, value) VALUES (?, ?, ?)").run(G+n.endpoint,j,JSON.stringify(t))}function Y(){if(v)try{v.close()}catch{}v=null,$=!1}var _=null,m=null,A=null,k=!1,R="",w=null,p=null,q={modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0,enableCache:!0,maxCacheSize:1e4,endpoint:process.env.AQE_EMBEDDER_ENDPOINT,endpointToken:process.env.AQE_EMBEDDER_TOKEN},d=new Map,V=36e5;function z(n){return p?`endpoint:${p.fingerprint}:${n}`:`inproc:${n}`}function pe(n){let e=n.trim();return!!(e.startsWith("{")&&/["']metrics["']/.test(e)||e.startsWith("[")&&e.endsWith("]")&&e.length>50||(e.match(/[a-zA-Z]/g)||[]).length/Math.max(e.length,1)<.3&&e.length>20)}async function Z(n={}){if(k)throw new Error(`Transformer initialization previously failed: ${R}`);if(A)return A;let e={...q,...n};return A=(async()=>{try{if(e.endpoint){let o=X(e.endpoint);console.log(`[RealEmbeddings] Using external embedder endpoint: ${o}`),w=new P({endpoint:e.endpoint,token:e.endpointToken,model:e.modelName,expectedDim:F()}),p=await w.probe(),console.log(`[RealEmbeddings] Endpoint identity: dim=${p.dim} fingerprint=${p.fingerprint}`);try{let i=Q(p.endpoint);i&&i.fingerprint!==p.fingerprint&&console.warn(`[RealEmbeddings] WARNING: endpoint identity changed since last run. Previous fingerprint=${i.fingerprint} dim=${i.dim}, current fingerprint=${p.fingerprint} dim=${p.dim}. Vectors written before this change may no longer be comparable.`),J(p)}catch(i){console.warn(`[RealEmbeddings] Could not persist endpoint identity: ${D(i)}`)}m=ce(w);return}let t;try{t=await import("./transformers-FDHHH4SL.js")}catch{throw new Error('In-process embeddings require the optional package "@huggingface/transformers", which is not installed. Either run `npm install @huggingface/transformers`, or configure an embedding endpoint (EmbeddingConfig.endpoint / AQE_EMBEDDING_ENDPOINT) so no local model is loaded.')}_=t.pipeline,console.log(`[RealEmbeddings] Loading model: ${e.modelName}`);let r=performance.now();m=await _("feature-extraction",e.modelName,{quantized:e.quantized});let s=performance.now()-r;console.log(`[RealEmbeddings] Model loaded in ${s.toFixed(0)}ms`)}catch(t){throw k=!0,R=D(t),new Error(`Failed to initialize transformer model: ${R}`)}})(),A}function ce(n){return async e=>{let t=Array.isArray(e)?e:[e],r=await n.embed(t),s=r[0]?.length??F(),o=new Float32Array(t.length*s);for(let i=0;i<r.length;i++)o.set(r[i],i*s);return{data:o,dims:[t.length,s]}}}async function Ae(n,e={}){let t={...q,...e};if(pe(n))return new Array(F()).fill(0);if(m||await Z(e),!m)throw new Error("Embedding model failed to initialize");let r=z(n);if(t.enableCache){let c=d.get(r);if(c&&Date.now()-c.timestamp<V)return c.embedding}let s=performance.now(),o=await m(n,{pooling:"mean",normalize:!0}),i=Array.from(o.data),l=performance.now()-s;if(l>500&&console.warn(`[RealEmbeddings] Slow embedding computation: ${l.toFixed(1)}ms for "${n.slice(0,50)}..."`),t.enableCache){if(d.size>=t.maxCacheSize){let c=d.keys().next().value;c&&d.delete(c)}d.set(r,{embedding:i,timestamp:Date.now()})}return i}async function Ie(n,e={}){let t={...q,...e},r=[],s=[],o=new Array(n.length).fill(null);if(m||await Z(e),!m)throw new Error("Embedding model failed to initialize");if(t.enableCache)for(let i=0;i<n.length;i++){let l=d.get(z(n[i]));l&&Date.now()-l.timestamp<V?o[i]=l.embedding:(r.push(n[i]),s.push(i))}else{r.push(...n);for(let i=0;i<n.length;i++)s.push(i)}if(r.length>0){let i=performance.now(),l=32;for(let h=0;h<r.length;h+=l){let N=Math.min(h+l,r.length),I=r.slice(h,N),E=await m(I,{pooling:"mean",normalize:!0}),C=E.dims||[I.length,384],y=C[0],f=C[1];for(let a=0;a<y;a++){let g=a*f,u=Array.from(E.data.slice(g,g+f)),b=h+a,M=s[b];if(o[M]=u,t.enableCache){if(d.size>=t.maxCacheSize){let U=d.keys().next().value;U&&d.delete(U)}d.set(z(r[b]),{embedding:u,timestamp:Date.now()})}}}let c=performance.now()-i;console.log(`[RealEmbeddings] Batch computed ${r.length} embeddings in ${c.toFixed(0)}ms`)}return o.filter(i=>i!==null)}function Ce(){d.clear(),console.log("[RealEmbeddings] Cache cleared")}function Me(){return{size:d.size,hitRate:0}}function Pe(){return!k&&m!==null}function F(){return 384}function Oe(){_=null,m=null,A=null,k=!1,R="",d.clear(),w&&w.close(),w=null,p=null,Y()}function Re(){return w!==null}function ke(){return p}export{q as a,Ae as b,Ie as c,Ce as d,Me as e,Pe as f,F as g,Oe as h,Re as i,ke as j};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.
|
|
2
|
-
import{d as J,e as B,f as te,g as j}from"./chunk-
|
|
3
|
-
`)}var Pt=(function(n){ft(e,n);function e(t,r,s,i,a){var c=this.constructor,u=n.call(this,qe(t,{name:r,index:s,operation:i,tree:a}))||this;return u.name=r,u.index=s,u.operation=i,u.tree=a,Object.setPrototypeOf(u,c.prototype),u.message=qe(t,{name:r,index:s,operation:i,tree:a}),u}return e})(Error);E.PatchError=Pt});var de=$(g=>{Object.defineProperty(g,"__esModule",{value:!0});var R=G();g.JsonPatchError=R.PatchError;g.deepClone=R._deepClone;var L={add:function(n,e,t){return n[e]=this.value,{newDocument:t}},remove:function(n,e,t){var r=n[e];return delete n[e],{newDocument:t,removed:r}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:function(n,e,t){var r=V(t,this.path);r&&(r=R._deepClone(r));var s=O(t,{op:"remove",path:this.from}).removed;return O(t,{op:"add",path:this.path,value:s}),{newDocument:t,removed:r}},copy:function(n,e,t){var r=V(t,this.from);return O(t,{op:"add",path:this.path,value:R._deepClone(r)}),{newDocument:t}},test:function(n,e,t){return{newDocument:t,test:z(n[e],this.value)}},_get:function(n,e,t){return this.value=n[e],{newDocument:t}}},wt={add:function(n,e,t){return R.isInteger(e)?n.splice(e,0,this.value):n[e]=this.value,{newDocument:t,index:e}},remove:function(n,e,t){var r=n.splice(e,1);return{newDocument:t,removed:r[0]}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:L.move,copy:L.copy,test:L.test,_get:L._get};function V(n,e){if(e=="")return n;var t={op:"_get",path:e};return O(n,t),t.value}g.getValueByPointer=V;function O(n,e,t,r,s,i){if(t===void 0&&(t=!1),r===void 0&&(r=!0),s===void 0&&(s=!0),i===void 0&&(i=0),t&&(typeof t=="function"?t(e,0,n,e.path):Y(e,0)),e.path===""){var a={newDocument:n};if(e.op==="add")return a.newDocument=e.value,a;if(e.op==="replace")return a.newDocument=e.value,a.removed=n,a;if(e.op==="move"||e.op==="copy")return a.newDocument=V(n,e.from),e.op==="move"&&(a.removed=n),a;if(e.op==="test"){if(a.test=z(n,e.value),a.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",i,e,n);return a.newDocument=n,a}else{if(e.op==="remove")return a.removed=n,a.newDocument=null,a;if(e.op==="_get")return e.value=n,a;if(t)throw new g.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",i,e,n);return a}}else{r||(n=R._deepClone(n));var c=e.path||"",u=c.split("/"),o=n,l=1,f=u.length,d=void 0,h=void 0,m=void 0;for(typeof t=="function"?m=t:m=Y;;){if(h=u[l],h&&h.indexOf("~")!=-1&&(h=R.unescapePathComponent(h)),s&&(h=="__proto__"||h=="prototype"&&l>0&&u[l-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(t&&d===void 0&&(o[h]===void 0?d=u.slice(0,l).join("/"):l==f-1&&(d=e.path),d!==void 0&&m(e,0,n,d)),l++,Array.isArray(o)){if(h==="-")h=o.length;else{if(t&&!R.isInteger(h))throw new g.JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",i,e,n);R.isInteger(h)&&(h=~~h)}if(l>=f){if(t&&e.op==="add"&&h>o.length)throw new g.JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",i,e,n);var a=wt[e.op].call(e,o,h,n);if(a.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",i,e,n);return a}}else if(l>=f){var a=L[e.op].call(e,o,h,n);if(a.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",i,e,n);return a}if(o=o[h],t&&l<f&&(!o||typeof o!="object"))throw new g.JsonPatchError("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",i,e,n)}}}g.applyOperation=O;function $e(n,e,t,r,s){if(r===void 0&&(r=!0),s===void 0&&(s=!0),t&&!Array.isArray(e))throw new g.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(n=R._deepClone(n));for(var i=new Array(e.length),a=0,c=e.length;a<c;a++)i[a]=O(n,e[a],t,!0,s,a),n=i[a].newDocument;return i.newDocument=n,i}g.applyPatch=$e;function St(n,e,t){var r=O(n,e);if(r.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",t,e,n);return r.newDocument}g.applyReducer=St;function Y(n,e,t,r){if(typeof n!="object"||n===null||Array.isArray(n))throw new g.JsonPatchError("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,n,t);if(L[n.op]){if(typeof n.path!="string")throw new g.JsonPatchError("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,n,t);if(n.path.indexOf("/")!==0&&n.path.length>0)throw new g.JsonPatchError('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,n,t);if((n.op==="move"||n.op==="copy")&&typeof n.from!="string")throw new g.JsonPatchError("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&n.value===void 0)throw new g.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&R.hasUndefined(n.value))throw new g.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,n,t);if(t){if(n.op=="add"){var s=n.path.split("/").length,i=r.split("/").length;if(s!==i+1&&s!==i)throw new g.JsonPatchError("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,n,t)}else if(n.op==="replace"||n.op==="remove"||n.op==="_get"){if(n.path!==r)throw new g.JsonPatchError("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,n,t)}else if(n.op==="move"||n.op==="copy"){var a={op:"_get",path:n.from,value:void 0},c=Je([a],t);if(c&&c.name==="OPERATION_PATH_UNRESOLVABLE")throw new g.JsonPatchError("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,n,t)}}}else throw new g.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,n,t)}g.validator=Y;function Je(n,e,t){try{if(!Array.isArray(n))throw new g.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)$e(R._deepClone(e),R._deepClone(n),t||!0);else{t=t||Y;for(var r=0;r<n.length;r++)t(n[r],r,e,void 0)}}catch(s){if(s instanceof g.JsonPatchError)return s;throw s}}g.validate=Je;function z(n,e){if(n===e)return!0;if(n&&e&&typeof n=="object"&&typeof e=="object"){var t=Array.isArray(n),r=Array.isArray(e),s,i,a;if(t&&r){if(i=n.length,i!=e.length)return!1;for(s=i;s--!==0;)if(!z(n[s],e[s]))return!1;return!0}if(t!=r)return!1;var c=Object.keys(n);if(i=c.length,i!==Object.keys(e).length)return!1;for(s=i;s--!==0;)if(!e.hasOwnProperty(c[s]))return!1;for(s=i;s--!==0;)if(a=c[s],!z(n[a],e[a]))return!1;return!0}return n!==n&&e!==e}g._areEquals=z});var Be=$(k=>{Object.defineProperty(k,"__esModule",{value:!0});var b=G(),bt=de(),me=new WeakMap,Et=(function(){function n(e){this.observers=new Map,this.obj=e}return n})(),Rt=(function(){function n(e,t){this.callback=e,this.observer=t}return n})();function At(n){return me.get(n)}function Tt(n,e){return n.observers.get(e)}function xt(n,e){n.observers.delete(e.callback)}function Ct(n,e){e.unobserve()}k.unobserve=Ct;function Dt(n,e){var t=[],r,s=At(n);if(!s)s=new Et(n),me.set(n,s);else{var i=Tt(s,e);r=i&&i.observer}if(r)return r;if(r={},s.value=b._deepClone(n),e){r.callback=e,r.next=null;var a=function(){fe(r)},c=function(){clearTimeout(r.next),r.next=setTimeout(a)};typeof window<"u"&&(window.addEventListener("mouseup",c),window.addEventListener("keyup",c),window.addEventListener("mousedown",c),window.addEventListener("keydown",c),window.addEventListener("change",c))}return r.patches=t,r.object=n,r.unobserve=function(){fe(r),clearTimeout(r.next),xt(s,r),typeof window<"u"&&(window.removeEventListener("mouseup",c),window.removeEventListener("keyup",c),window.removeEventListener("mousedown",c),window.removeEventListener("keydown",c),window.removeEventListener("change",c))},s.observers.set(e,new Rt(e,r)),r}k.observe=Dt;function fe(n,e){e===void 0&&(e=!1);var t=me.get(n.object);pe(t.value,n.object,n.patches,"",e),n.patches.length&&bt.applyPatch(t.value,n.patches);var r=n.patches;return r.length>0&&(n.patches=[],n.callback&&n.callback(r)),r}k.generate=fe;function pe(n,e,t,r,s){if(e!==n){typeof e.toJSON=="function"&&(e=e.toJSON());for(var i=b._objectKeys(e),a=b._objectKeys(n),c=!1,u=!1,o=a.length-1;o>=0;o--){var l=a[o],f=n[l];if(b.hasOwnProperty(e,l)&&!(e[l]===void 0&&f!==void 0&&Array.isArray(e)===!1)){var d=e[l];typeof f=="object"&&f!=null&&typeof d=="object"&&d!=null&&Array.isArray(f)===Array.isArray(d)?pe(f,d,t,r+"/"+b.escapePathComponent(l),s):f!==d&&(c=!0,s&&t.push({op:"test",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(f)}),t.push({op:"replace",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(d)}))}else Array.isArray(n)===Array.isArray(e)?(s&&t.push({op:"test",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(f)}),t.push({op:"remove",path:r+"/"+b.escapePathComponent(l)}),u=!0):(s&&t.push({op:"test",path:r,value:n}),t.push({op:"replace",path:r,value:e}),c=!0)}if(!(!u&&i.length==a.length))for(var o=0;o<i.length;o++){var l=i[o];!b.hasOwnProperty(n,l)&&e[l]!==void 0&&t.push({op:"add",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(e[l])})}}}function Ft(n,e,t){t===void 0&&(t=!1);var r=[];return pe(n,e,r,"",t),r}k.compare=Ft});var je=$(I=>{var Ot=de();Object.assign(I,Ot);var It=Be();Object.assign(I,It);var K=G();I.JsonPatchError=K.PatchError;I.deepClone=K._deepClone;I.escapePathComponent=K.escapePathComponent;I.unescapePathComponent=K.unescapePathComponent});nt();Ce();var q=class{constructor(e,t){this.createAdapter=e;this.config=t?.base??W,this.rvfPath=t?.rvfPath??".agentic-qe/patterns.rvf",this.skipCloseOnDispose=t?.skipCloseOnDispose??!1}createAdapter;config;rvfPath;skipCloseOnDispose;adapter=null;sqliteStore=null;initialized=!1;rvfInitError=null;searchOps=0;totalSearchMs=0;setSqliteStore(e){this.sqliteStore=e}getAdapter(){return this.adapter}async initialize(){if(!this.initialized){if(process.env.AQE_MEMORY_BACKEND==="memory"){this.adapter=null,this.initialized=!0;return}try{this.adapter=this.createAdapter(this.rvfPath,this.config.embeddingDimension),this.initialized=!0,console.log(`[RvfPatternStore] Initialized: ${this.rvfPath} (dim=${this.config.embeddingDimension})`)}catch(e){this.rvfInitError=v(e),console.error(`[RvfPatternStore] ERROR: RVF native init failed \u2014 vector search is DISABLED. Cause: ${this.rvfInitError}. Fix: install @ruvector/rvf-node native bindings, or set useRVFPatternStore=false to use SQLite HNSW.`),this.adapter=null,this.initialized=!0}if(!this.sqliteStore)try{let{createSQLitePatternStore:e}=await import("./sqlite-persistence-M4JEQO57.js"),t=e();await t.initialize(),this.sqliteStore=t}catch{}await this.purgeOrphanedVectors()}}async purgeOrphanedVectors(){if(!(!this.adapter||!this.sqliteStore))try{let e=this.adapter.status()?.totalVectors??0,t=this.sqliteStore.getStats()?.totalPatterns??0;if(e<=t)return;let{readFileSync:r,existsSync:s}=await import("node:fs"),i=`${this.rvfPath}.idmap.json`;if(!s(i))return;let a=JSON.parse(r(i,"utf-8")),c=new Set((a.entries??[]).map(l=>Array.isArray(l)?l[0]:void 0).filter(l=>typeof l=="string")),u=new Set(this.sqliteStore.getPatterns({limit:1e4}).map(l=>l.id)),o=[...c].filter(l=>!u.has(l));if(o.length===0)return;this.adapter.delete(o),console.log(`[RvfPatternStore] Removed ${o.length} ghost vectors (index ${e} > DB ${t})`)}catch(e){console.warn(`[RvfPatternStore] orphan purge skipped: ${v(e)}`)}}async dispose(){if(this.adapter&&!this.skipCloseOnDispose)try{this.adapter.close()}catch{}this.adapter=null,this.initialized=!1}async store(e){await this.ensureInitialized();let t=j(e);if(!t.valid)return w(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return w(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));if(this.sqliteStore)try{let r=this.sqliteStore.storePattern(e,e.embedding);r&&r!==e.id&&(e.id=r)}catch(r){console.warn(`[RvfPatternStore] SQLite persist failed for ${e.id}:`,v(r))}if(e.embedding&&this.adapter)try{let r=e.embedding instanceof Float32Array?e.embedding:new Float32Array(e.embedding);this.adapter.ingest([{id:e.id,vector:r}])}catch(r){console.warn(`[RvfPatternStore] RVF ingest failed for ${e.id}:`,v(r))}return P(e.id)}async create(e){let t=e.confidence??.5,r=e.qeDomain??"test-generation",s={id:C(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:t,usageCount:0,successRate:0,qualityScore:J({confidence:t,usageCount:0,successRate:0}),context:{tags:[],...e.context},template:{example:"",...e.template},embedding:e.embedding,tier:"short-term",createdAt:new Date,lastUsedAt:new Date,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},i=await this.store(s);return i.success?P(s):w(i.error)}async get(e){if(this.sqliteStore)try{return this.sqliteStore.getPattern(e)??null}catch{return null}return null}async search(e,t={}){await this.ensureInitialized();let r=performance.now(),s=t.limit??10,i=[];if(Array.isArray(e)&&this.adapter)try{let c=e instanceof Float32Array?e:new Float32Array(e),u=this.adapter.search(c,s*2);for(let o of u){let l=await this.get(o.id);if(l&&this.matchesFilters(l,t)){let f=this.calculateReuseInfo(l,o.score);i.push({pattern:l,score:o.score,matchType:"vector",similarity:o.score,canReuse:f.canReuse,estimatedTokenSavings:f.estimatedTokenSavings,reuseConfidence:f.reuseConfidence})}}}catch(c){console.warn("[RvfPatternStore] RVF search failed:",v(c))}if(Array.isArray(e)&&!this.adapter&&this.sqliteStore&&i.length===0)try{let c=this.sqliteStore.getPatterns({limit:s*4}),u=e,o=Math.sqrt(u.reduce((l,f)=>l+f*f,0));if(o>0)for(let l of c){if(!this.matchesFilters(l,t))continue;let f=this.sqliteStore.getPattern(l.id),d=f?.embedding;if(!d||d.length!==u.length)continue;let h=0,m=0;for(let S=0;S<u.length;S++)h+=u[S]*d[S],m+=d[S]*d[S];if(m=Math.sqrt(m),m===0)continue;let p=h/(o*m),y=this.calculateReuseInfo(f,p);i.push({pattern:f,score:p,matchType:"vector",similarity:p,canReuse:y.canReuse,estimatedTokenSavings:y.estimatedTokenSavings,reuseConfidence:y.reuseConfidence})}}catch{}if(typeof e=="string"&&!e.trim()&&this.sqliteStore)try{let c=this.sqliteStore.getPatterns({limit:s*2}),u=new Set(i.map(o=>o.pattern.id));for(let o of c){if(u.has(o.id)||!this.matchesFilters(o,t))continue;let l=this.calculateReuseInfo(o,o.confidence);i.push({pattern:o,score:o.confidence,matchType:"exact",similarity:o.confidence,canReuse:l.canReuse,estimatedTokenSavings:l.estimatedTokenSavings,reuseConfidence:l.reuseConfidence})}}catch{}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let c=this.sqliteStore.searchFTS(e,s*2),u=new Set(i.map(o=>o.pattern.id));for(let o of c){if(u.has(o.id))continue;let l=await this.get(o.id);if(l&&this.matchesFilters(l,t)){let f=this.calculateReuseInfo(l,o.ftsScore);i.push({pattern:l,score:.5*o.ftsScore,matchType:"exact",similarity:o.ftsScore,canReuse:f.canReuse,estimatedTokenSavings:f.estimatedTokenSavings,reuseConfidence:f.reuseConfidence})}}}catch{}i.sort((c,u)=>u.score-c.score);let a=performance.now()-r;return this.searchOps++,this.totalSearchMs+=a,P(i.slice(0,s))}async recordUsage(e,t,r,s){if(!this.sqliteStore)return w(new Error("No SQLite store attached"));try{return this.sqliteStore.recordUsage(e,t,r,s),P(void 0)}catch(i){return w(new Error(`recordUsage failed: ${v(i)}`))}}async promote(e){if(!this.sqliteStore)return w(new Error("No SQLite store attached"));try{return this.sqliteStore.promotePattern(e),P(void 0)}catch(t){return w(new Error(`promote failed: ${v(t)}`))}}async delete(e){if(this.adapter)try{this.adapter.delete([e])}catch(t){console.warn(`[RvfPatternStore] RVF delete failed for ${e}:`,v(t))}if(this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(t){return w(new Error(`SQLite delete failed: ${v(t)}`))}return P(void 0)}async getStats(){let e=this.adapter?.status(),t=0,r={},s={shortTerm:0,longTerm:0};if(this.sqliteStore)try{let i=this.sqliteStore.getStats();t=i.totalPatterns,r=i.byDomain,s={shortTerm:i.byTier["short-term"]??0,longTerm:i.byTier["long-term"]??0}}catch{}return{totalPatterns:t,byTier:s,byDomain:r,byType:{},avgConfidence:0,avgQualityScore:0,avgSuccessRate:0,searchOperations:this.searchOps,avgSearchLatencyMs:this.searchOps>0?this.totalSearchMs/this.searchOps:0,hnswStats:{nativeAvailable:this.adapter!==null,vectorCount:e?.totalVectors??0,indexSizeBytes:e?.fileSizeBytes??0,...this.rvfInitError?{rvfInitError:this.rvfInitError}:{}}}}async cleanup(){if(!this.sqliteStore)return{removed:0,promoted:0};let e=0,t=0;try{let r=this.sqliteStore.getPatterns({limit:1e4});for(let s of r)s.confidence<this.config.minConfidence&&s.usageCount>3?(await this.delete(s.id),e++):s.tier==="short-term"&&s.successfulUses>=B&&(await this.promote(s.id),t++)}catch(r){console.warn("[RvfPatternStore] Cleanup error:",v(r))}return{removed:e,promoted:t}}async ensureInitialized(){this.initialized||await this.initialize()}matchesFilters(e,t){return!(t.patternType&&e.patternType!==t.patternType||t.domain&&e.qeDomain!==t.domain||t.tier&&e.tier!==t.tier||t.minConfidence&&e.confidence<t.minConfidence||t.minQualityScore&&e.qualityScore<t.minQualityScore)}calculateReuseInfo(e,t){let r=this.config.reuseOptimization,s=r.enabled&&t>=r.minSimilarityForReuse&&e.successRate>=r.minSuccessRateForReuse;return{canReuse:s,estimatedTokenSavings:s?500:0,reuseConfidence:s?t*e.successRate:0}}};it();Ce();F();function at(n,e){let r=[n.pattern,n];for(let s of r){let i=e.split("."),a=s;for(let c of i){if(a==null)break;if(typeof a=="object")a=a[c];else{a=void 0;break}}if(a!==void 0)return a}}function ot(n,e,t){switch(e){case"eq":return n===t;case"gt":return typeof n=="number"&&typeof t=="number"&&n>t;case"lt":return typeof n=="number"&&typeof t=="number"&&n<t;case"gte":return typeof n=="number"&&typeof t=="number"&&n>=t;case"lte":return typeof n=="number"&&typeof t=="number"&&n<=t;case"in":return Array.isArray(t)?t.includes(n):!1;case"contains":return Array.isArray(n)||typeof n=="string"&&typeof t=="string"?n.includes(t):!1;case"between":{if(typeof n!="number"||!Array.isArray(t)||t.length!==2){if(n instanceof Date&&Array.isArray(t)&&t.length===2){let i=n.getTime(),a=t[0]instanceof Date?t[0].getTime():Number(t[0]),c=t[1]instanceof Date?t[1].getTime():Number(t[1]);return i>=a&&i<=c}return!1}let[r,s]=t;return n>=r&&n<=s}default:return!1}}function X(n,e){switch(e.type){case"AND":return(e.children??[]).every(r=>X(n,r));case"OR":{let t=e.children??[];return t.length===0?!0:t.some(r=>X(n,r))}case"NOT":return e.child?!X(n,e.child):!0;case"FIELD":{if(!e.field||!e.operator)return!0;let t=at(n,e.field);return ot(t,e.operator,e.value)}default:return!0}}function Ne(n,e){return e?n.filter(t=>X(t,e)):n}F();F();var Me=1e4,Le=2166136261;function ke(n){let e=2166136261;for(let t=0;t<n.length;t++)e^=n.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}var oe=new Uint8Array(256);for(let n=0;n<256;n++){let e=0,t=n;for(;t;)e++,t&=t-1;oe[n]=e}var He="0123456789abcdef";function ct(n){let e=Math.min(n.length,16),t="";for(let r=0;r<e;r++){let s=n[r];t+=He[s>>4]+He[s&15]}return t}function lt(n,e){if(n.length!==e.length)throw new Error(`Cannot bind vectors of different lengths: ${n.length} vs ${e.length}`);let t=new Uint8Array(n.length);for(let r=0;r<n.length;r++)t[r]=n[r]^e[r];return t}function ut(n){if(n.length===0)throw new Error("Cannot bundle zero vectors");let e=n[0].length;for(let s=1;s<n.length;s++)if(n[s].length!==e)throw new Error(`Vector length mismatch at index ${s}: expected ${e}, got ${n[s].length}`);let t=new Uint8Array(e),r=n.length/2;for(let s=0;s<e;s++){let i=0;for(let a=0;a<8;a++){let c=0,u=1<<a;for(let o=0;o<n.length;o++)n[o][s]&u&&c++;c>=r&&(i|=u)}t[s]=i}return t}function ht(n,e,t){if(n.length!==e.length)throw new Error(`Cannot compute Hamming distance for vectors of different lengths: ${n.length} vs ${e.length}`);let r=0;for(let i=0;i<n.length;i++)r+=oe[n[i]^e[i]];let s=t??n.length*8;return s>0?r/s:0}function dt(n,e,t){return 1-ht(n,e,t)}var se=class{dimensions;baseSeed;byteLen;tokenCache=new Map;constructor(e){if(this.dimensions=e?.dimensions??Me,this.baseSeed=e?.seed??Le,this.byteLen=Math.ceil(this.dimensions/8),this.dimensions<=0)throw new Error(`HDC dimensions must be positive, got ${this.dimensions}`)}tokenToHypervector(e){let t=this.tokenCache.get(e);if(t)return new Uint8Array(t);let r=ke(e)^this.baseSeed,s=this.generateSeededVector(r);return this.tokenCache.set(e,s),new Uint8Array(s)}fingerprintPattern(e){if(e.length===0)return new Uint8Array(this.byteLen);let t=this.tokenToHypervector(e[0]);for(let r=1;r<e.length;r++)t=lt(t,this.tokenToHypervector(e[r]));return t}fingerprintWithContext(e,t){let r=this.fingerprintPattern(e);if(t.length===0)return r;let s=this.fingerprintPattern(t);return ut([r,s])}similarity(e,t){return dt(e,t,this.dimensions)}generateSeededVector(e){let t=new Uint8Array(this.byteLen),r=new ne(e),s=0;for(;s<this.byteLen;){let a=r.next(),c=Math.min(4,this.byteLen-s);for(let u=0;u<c;u++)t[s++]=a>>>u*8&255}let i=this.dimensions%8;return i>0&&(t[this.byteLen-1]&=(1<<i)-1),t}},ae=class{dimensions;baseSeed;constructor(e){if(this.dimensions=e?.dimensions??Me,this.baseSeed=e?.seed??Le,this.dimensions<=0)throw new Error(`HDC dimensions must be positive, got ${this.dimensions}`)}fingerprint(e){let t=`${e.id}|${e.domain}|${e.type}|${e.content??""}`,r=ke(t)^this.baseSeed,s=this.generateVector(r);return{vector:s,dimensions:this.dimensions,hash:ct(s)}}compositionalBind(e,t){if(e.length!==t.length)throw new Error(`Cannot bind vectors of different lengths: ${e.length} vs ${t.length}`);let r=new Uint8Array(e.length);for(let s=0;s<e.length;s++)r[s]=e[s]^t[s];return r}hammingDistance(e,t){if(e.length!==t.length)throw new Error(`Cannot compute Hamming distance for vectors of different lengths: ${e.length} vs ${t.length}`);let r=0;for(let s=0;s<e.length;s++)r+=oe[e[s]^t[s]];return r}similarity(e,t){return 1-this.hammingDistance(e,t)/this.dimensions}batchFingerprint(e){return e.map(t=>this.fingerprint(t))}generateVector(e){let t=Math.ceil(this.dimensions/8),r=new Uint8Array(t),s=new ne(e),i=0;for(;i<t;){let c=s.next(),u=t-i,o=u<4?u:4;for(let l=0;l<o;l++)r[i++]=c>>>l*8&255}let a=this.dimensions%8;return a>0&&(r[t-1]&=(1<<a)-1),r}};function Ue(n){return new ae(n)}function Qe(n){return Q()?new se(n):null}var ye=rt(je(),1),ge=ye.default??ye,_t=`
|
|
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.13.1");process.exit(0)}
|
|
2
|
+
import{d as J,e as B,f as te,g as j}from"./chunk-2OM3TDC4.js";import{a as ne}from"./chunk-CWXDL7AH.js";import{b as _e}from"./chunk-MUFYDKVC.js";import{a as ie}from"./chunk-E4D47QTF.js";import{b as De,c as nt}from"./chunk-YBPCBFEE.js";import{a as re,b as Fe,d as Oe,f as it}from"./chunk-55WDVSCM.js";import{c as Ie}from"./chunk-QES4QHQW.js";import{b as P,c as w}from"./chunk-GTPZVLL6.js";import{a as v,b as xe,c as Ce}from"./chunk-AYYDO52G.js";import{i as C}from"./chunk-ZIBW7CB4.js";import{B as Q,D as H,G as ee,P as M,S as F,b as D}from"./chunk-IJP42OGW.js";import{a as Te,d as $,f as rt}from"./chunk-OE4B6LDZ.js";var G=$(E=>{var ft=E&&E.__extends||(function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var i in s)s.hasOwnProperty(i)&&(r[i]=s[i])},n(e,t)};return function(e,t){n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}})();Object.defineProperty(E,"__esModule",{value:!0});var mt=Object.prototype.hasOwnProperty;function ue(n,e){return mt.call(n,e)}E.hasOwnProperty=ue;function ze(n){if(Array.isArray(n)){for(var e=new Array(n.length),t=0;t<e.length;t++)e[t]=""+t;return e}if(Object.keys)return Object.keys(n);var r=[];for(var s in n)ue(n,s)&&r.push(s);return r}E._objectKeys=ze;function pt(n){switch(typeof n){case"object":return JSON.parse(JSON.stringify(n));case"undefined":return null;default:return n}}E._deepClone=pt;function gt(n){for(var e=0,t=n.length,r;e<t;){if(r=n.charCodeAt(e),r>=48&&r<=57){e++;continue}return!1}return!0}E.isInteger=gt;function ce(n){return n.indexOf("/")===-1&&n.indexOf("~")===-1?n:n.replace(/~/g,"~0").replace(/\//g,"~1")}E.escapePathComponent=ce;function yt(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}E.unescapePathComponent=yt;function he(n,e){var t;for(var r in n)if(ue(n,r)){if(n[r]===e)return ce(r)+"/";if(typeof n[r]=="object"&&(t=he(n[r],e),t!=""))return ce(r)+"/"+t}return""}E._getPathRecursive=he;function vt(n,e){if(n===e)return"/";var t=he(n,e);if(t==="")throw new Error("Object not found in root");return"/"+t}E.getPath=vt;function le(n){if(n===void 0)return!0;if(n){if(Array.isArray(n)){for(var e=0,t=n.length;e<t;e++)if(le(n[e]))return!0}else if(typeof n=="object"){for(var r=ze(n),s=r.length,i=0;i<s;i++)if(le(n[r[i]]))return!0}}return!1}E.hasUndefined=le;function qe(n,e){var t=[n];for(var r in e){var s=typeof e[r]=="object"?JSON.stringify(e[r],null,2):e[r];typeof s<"u"&&t.push(r+": "+s)}return t.join(`
|
|
3
|
+
`)}var Pt=(function(n){ft(e,n);function e(t,r,s,i,a){var c=this.constructor,u=n.call(this,qe(t,{name:r,index:s,operation:i,tree:a}))||this;return u.name=r,u.index=s,u.operation=i,u.tree=a,Object.setPrototypeOf(u,c.prototype),u.message=qe(t,{name:r,index:s,operation:i,tree:a}),u}return e})(Error);E.PatchError=Pt});var de=$(g=>{Object.defineProperty(g,"__esModule",{value:!0});var R=G();g.JsonPatchError=R.PatchError;g.deepClone=R._deepClone;var L={add:function(n,e,t){return n[e]=this.value,{newDocument:t}},remove:function(n,e,t){var r=n[e];return delete n[e],{newDocument:t,removed:r}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:function(n,e,t){var r=V(t,this.path);r&&(r=R._deepClone(r));var s=O(t,{op:"remove",path:this.from}).removed;return O(t,{op:"add",path:this.path,value:s}),{newDocument:t,removed:r}},copy:function(n,e,t){var r=V(t,this.from);return O(t,{op:"add",path:this.path,value:R._deepClone(r)}),{newDocument:t}},test:function(n,e,t){return{newDocument:t,test:z(n[e],this.value)}},_get:function(n,e,t){return this.value=n[e],{newDocument:t}}},wt={add:function(n,e,t){return R.isInteger(e)?n.splice(e,0,this.value):n[e]=this.value,{newDocument:t,index:e}},remove:function(n,e,t){var r=n.splice(e,1);return{newDocument:t,removed:r[0]}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:L.move,copy:L.copy,test:L.test,_get:L._get};function V(n,e){if(e=="")return n;var t={op:"_get",path:e};return O(n,t),t.value}g.getValueByPointer=V;function O(n,e,t,r,s,i){if(t===void 0&&(t=!1),r===void 0&&(r=!0),s===void 0&&(s=!0),i===void 0&&(i=0),t&&(typeof t=="function"?t(e,0,n,e.path):Y(e,0)),e.path===""){var a={newDocument:n};if(e.op==="add")return a.newDocument=e.value,a;if(e.op==="replace")return a.newDocument=e.value,a.removed=n,a;if(e.op==="move"||e.op==="copy")return a.newDocument=V(n,e.from),e.op==="move"&&(a.removed=n),a;if(e.op==="test"){if(a.test=z(n,e.value),a.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",i,e,n);return a.newDocument=n,a}else{if(e.op==="remove")return a.removed=n,a.newDocument=null,a;if(e.op==="_get")return e.value=n,a;if(t)throw new g.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",i,e,n);return a}}else{r||(n=R._deepClone(n));var c=e.path||"",u=c.split("/"),o=n,l=1,f=u.length,d=void 0,h=void 0,m=void 0;for(typeof t=="function"?m=t:m=Y;;){if(h=u[l],h&&h.indexOf("~")!=-1&&(h=R.unescapePathComponent(h)),s&&(h=="__proto__"||h=="prototype"&&l>0&&u[l-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(t&&d===void 0&&(o[h]===void 0?d=u.slice(0,l).join("/"):l==f-1&&(d=e.path),d!==void 0&&m(e,0,n,d)),l++,Array.isArray(o)){if(h==="-")h=o.length;else{if(t&&!R.isInteger(h))throw new g.JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",i,e,n);R.isInteger(h)&&(h=~~h)}if(l>=f){if(t&&e.op==="add"&&h>o.length)throw new g.JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",i,e,n);var a=wt[e.op].call(e,o,h,n);if(a.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",i,e,n);return a}}else if(l>=f){var a=L[e.op].call(e,o,h,n);if(a.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",i,e,n);return a}if(o=o[h],t&&l<f&&(!o||typeof o!="object"))throw new g.JsonPatchError("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",i,e,n)}}}g.applyOperation=O;function $e(n,e,t,r,s){if(r===void 0&&(r=!0),s===void 0&&(s=!0),t&&!Array.isArray(e))throw new g.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(n=R._deepClone(n));for(var i=new Array(e.length),a=0,c=e.length;a<c;a++)i[a]=O(n,e[a],t,!0,s,a),n=i[a].newDocument;return i.newDocument=n,i}g.applyPatch=$e;function St(n,e,t){var r=O(n,e);if(r.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",t,e,n);return r.newDocument}g.applyReducer=St;function Y(n,e,t,r){if(typeof n!="object"||n===null||Array.isArray(n))throw new g.JsonPatchError("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,n,t);if(L[n.op]){if(typeof n.path!="string")throw new g.JsonPatchError("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,n,t);if(n.path.indexOf("/")!==0&&n.path.length>0)throw new g.JsonPatchError('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,n,t);if((n.op==="move"||n.op==="copy")&&typeof n.from!="string")throw new g.JsonPatchError("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&n.value===void 0)throw new g.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&R.hasUndefined(n.value))throw new g.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,n,t);if(t){if(n.op=="add"){var s=n.path.split("/").length,i=r.split("/").length;if(s!==i+1&&s!==i)throw new g.JsonPatchError("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,n,t)}else if(n.op==="replace"||n.op==="remove"||n.op==="_get"){if(n.path!==r)throw new g.JsonPatchError("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,n,t)}else if(n.op==="move"||n.op==="copy"){var a={op:"_get",path:n.from,value:void 0},c=Je([a],t);if(c&&c.name==="OPERATION_PATH_UNRESOLVABLE")throw new g.JsonPatchError("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,n,t)}}}else throw new g.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,n,t)}g.validator=Y;function Je(n,e,t){try{if(!Array.isArray(n))throw new g.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)$e(R._deepClone(e),R._deepClone(n),t||!0);else{t=t||Y;for(var r=0;r<n.length;r++)t(n[r],r,e,void 0)}}catch(s){if(s instanceof g.JsonPatchError)return s;throw s}}g.validate=Je;function z(n,e){if(n===e)return!0;if(n&&e&&typeof n=="object"&&typeof e=="object"){var t=Array.isArray(n),r=Array.isArray(e),s,i,a;if(t&&r){if(i=n.length,i!=e.length)return!1;for(s=i;s--!==0;)if(!z(n[s],e[s]))return!1;return!0}if(t!=r)return!1;var c=Object.keys(n);if(i=c.length,i!==Object.keys(e).length)return!1;for(s=i;s--!==0;)if(!e.hasOwnProperty(c[s]))return!1;for(s=i;s--!==0;)if(a=c[s],!z(n[a],e[a]))return!1;return!0}return n!==n&&e!==e}g._areEquals=z});var Be=$(k=>{Object.defineProperty(k,"__esModule",{value:!0});var b=G(),bt=de(),me=new WeakMap,Et=(function(){function n(e){this.observers=new Map,this.obj=e}return n})(),Rt=(function(){function n(e,t){this.callback=e,this.observer=t}return n})();function At(n){return me.get(n)}function Tt(n,e){return n.observers.get(e)}function xt(n,e){n.observers.delete(e.callback)}function Ct(n,e){e.unobserve()}k.unobserve=Ct;function Dt(n,e){var t=[],r,s=At(n);if(!s)s=new Et(n),me.set(n,s);else{var i=Tt(s,e);r=i&&i.observer}if(r)return r;if(r={},s.value=b._deepClone(n),e){r.callback=e,r.next=null;var a=function(){fe(r)},c=function(){clearTimeout(r.next),r.next=setTimeout(a)};typeof window<"u"&&(window.addEventListener("mouseup",c),window.addEventListener("keyup",c),window.addEventListener("mousedown",c),window.addEventListener("keydown",c),window.addEventListener("change",c))}return r.patches=t,r.object=n,r.unobserve=function(){fe(r),clearTimeout(r.next),xt(s,r),typeof window<"u"&&(window.removeEventListener("mouseup",c),window.removeEventListener("keyup",c),window.removeEventListener("mousedown",c),window.removeEventListener("keydown",c),window.removeEventListener("change",c))},s.observers.set(e,new Rt(e,r)),r}k.observe=Dt;function fe(n,e){e===void 0&&(e=!1);var t=me.get(n.object);pe(t.value,n.object,n.patches,"",e),n.patches.length&&bt.applyPatch(t.value,n.patches);var r=n.patches;return r.length>0&&(n.patches=[],n.callback&&n.callback(r)),r}k.generate=fe;function pe(n,e,t,r,s){if(e!==n){typeof e.toJSON=="function"&&(e=e.toJSON());for(var i=b._objectKeys(e),a=b._objectKeys(n),c=!1,u=!1,o=a.length-1;o>=0;o--){var l=a[o],f=n[l];if(b.hasOwnProperty(e,l)&&!(e[l]===void 0&&f!==void 0&&Array.isArray(e)===!1)){var d=e[l];typeof f=="object"&&f!=null&&typeof d=="object"&&d!=null&&Array.isArray(f)===Array.isArray(d)?pe(f,d,t,r+"/"+b.escapePathComponent(l),s):f!==d&&(c=!0,s&&t.push({op:"test",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(f)}),t.push({op:"replace",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(d)}))}else Array.isArray(n)===Array.isArray(e)?(s&&t.push({op:"test",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(f)}),t.push({op:"remove",path:r+"/"+b.escapePathComponent(l)}),u=!0):(s&&t.push({op:"test",path:r,value:n}),t.push({op:"replace",path:r,value:e}),c=!0)}if(!(!u&&i.length==a.length))for(var o=0;o<i.length;o++){var l=i[o];!b.hasOwnProperty(n,l)&&e[l]!==void 0&&t.push({op:"add",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(e[l])})}}}function Ft(n,e,t){t===void 0&&(t=!1);var r=[];return pe(n,e,r,"",t),r}k.compare=Ft});var je=$(I=>{var Ot=de();Object.assign(I,Ot);var It=Be();Object.assign(I,It);var K=G();I.JsonPatchError=K.PatchError;I.deepClone=K._deepClone;I.escapePathComponent=K.escapePathComponent;I.unescapePathComponent=K.unescapePathComponent});nt();Ce();var q=class{constructor(e,t){this.createAdapter=e;this.config=t?.base??W,this.rvfPath=t?.rvfPath??".agentic-qe/patterns.rvf",this.skipCloseOnDispose=t?.skipCloseOnDispose??!1}createAdapter;config;rvfPath;skipCloseOnDispose;adapter=null;sqliteStore=null;initialized=!1;rvfInitError=null;searchOps=0;totalSearchMs=0;setSqliteStore(e){this.sqliteStore=e}getAdapter(){return this.adapter}async initialize(){if(!this.initialized){if(process.env.AQE_MEMORY_BACKEND==="memory"){this.adapter=null,this.initialized=!0;return}try{this.adapter=this.createAdapter(this.rvfPath,this.config.embeddingDimension),this.initialized=!0,console.log(`[RvfPatternStore] Initialized: ${this.rvfPath} (dim=${this.config.embeddingDimension})`)}catch(e){this.rvfInitError=v(e),console.error(`[RvfPatternStore] ERROR: RVF native init failed \u2014 vector search is DISABLED. Cause: ${this.rvfInitError}. Fix: install @ruvector/rvf-node native bindings, or set useRVFPatternStore=false to use SQLite HNSW.`),this.adapter=null,this.initialized=!0}if(!this.sqliteStore)try{let{createSQLitePatternStore:e}=await import("./sqlite-persistence-PLOUGATS.js"),t=e();await t.initialize(),this.sqliteStore=t}catch{}await this.purgeOrphanedVectors()}}async purgeOrphanedVectors(){if(!(!this.adapter||!this.sqliteStore))try{let e=this.adapter.status()?.totalVectors??0,t=this.sqliteStore.getStats()?.totalPatterns??0;if(e<=t)return;let{readFileSync:r,existsSync:s}=await import("node:fs"),i=`${this.rvfPath}.idmap.json`;if(!s(i))return;let a=JSON.parse(r(i,"utf-8")),c=new Set((a.entries??[]).map(l=>Array.isArray(l)?l[0]:void 0).filter(l=>typeof l=="string")),u=new Set(this.sqliteStore.getPatterns({limit:1e4}).map(l=>l.id)),o=[...c].filter(l=>!u.has(l));if(o.length===0)return;this.adapter.delete(o),console.log(`[RvfPatternStore] Removed ${o.length} ghost vectors (index ${e} > DB ${t})`)}catch(e){console.warn(`[RvfPatternStore] orphan purge skipped: ${v(e)}`)}}async dispose(){if(this.adapter&&!this.skipCloseOnDispose)try{this.adapter.close()}catch{}this.adapter=null,this.initialized=!1}async store(e){await this.ensureInitialized();let t=j(e);if(!t.valid)return w(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return w(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));if(this.sqliteStore)try{let r=this.sqliteStore.storePattern(e,e.embedding);r&&r!==e.id&&(e.id=r)}catch(r){console.warn(`[RvfPatternStore] SQLite persist failed for ${e.id}:`,v(r))}if(e.embedding&&this.adapter)try{let r=e.embedding instanceof Float32Array?e.embedding:new Float32Array(e.embedding);this.adapter.ingest([{id:e.id,vector:r}])}catch(r){console.warn(`[RvfPatternStore] RVF ingest failed for ${e.id}:`,v(r))}return P(e.id)}async create(e){let t=e.confidence??.5,r=e.qeDomain??"test-generation",s={id:C(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:t,usageCount:0,successRate:0,qualityScore:J({confidence:t,usageCount:0,successRate:0}),context:{tags:[],...e.context},template:{example:"",...e.template},embedding:e.embedding,tier:"short-term",createdAt:new Date,lastUsedAt:new Date,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},i=await this.store(s);return i.success?P(s):w(i.error)}async get(e){if(this.sqliteStore)try{return this.sqliteStore.getPattern(e)??null}catch{return null}return null}async search(e,t={}){await this.ensureInitialized();let r=performance.now(),s=t.limit??10,i=[];if(Array.isArray(e)&&this.adapter)try{let c=e instanceof Float32Array?e:new Float32Array(e),u=this.adapter.search(c,s*2);for(let o of u){let l=await this.get(o.id);if(l&&this.matchesFilters(l,t)){let f=this.calculateReuseInfo(l,o.score);i.push({pattern:l,score:o.score,matchType:"vector",similarity:o.score,canReuse:f.canReuse,estimatedTokenSavings:f.estimatedTokenSavings,reuseConfidence:f.reuseConfidence})}}}catch(c){console.warn("[RvfPatternStore] RVF search failed:",v(c))}if(Array.isArray(e)&&!this.adapter&&this.sqliteStore&&i.length===0)try{let c=this.sqliteStore.getPatterns({limit:s*4}),u=e,o=Math.sqrt(u.reduce((l,f)=>l+f*f,0));if(o>0)for(let l of c){if(!this.matchesFilters(l,t))continue;let f=this.sqliteStore.getPattern(l.id),d=f?.embedding;if(!d||d.length!==u.length)continue;let h=0,m=0;for(let S=0;S<u.length;S++)h+=u[S]*d[S],m+=d[S]*d[S];if(m=Math.sqrt(m),m===0)continue;let p=h/(o*m),y=this.calculateReuseInfo(f,p);i.push({pattern:f,score:p,matchType:"vector",similarity:p,canReuse:y.canReuse,estimatedTokenSavings:y.estimatedTokenSavings,reuseConfidence:y.reuseConfidence})}}catch{}if(typeof e=="string"&&!e.trim()&&this.sqliteStore)try{let c=this.sqliteStore.getPatterns({limit:s*2}),u=new Set(i.map(o=>o.pattern.id));for(let o of c){if(u.has(o.id)||!this.matchesFilters(o,t))continue;let l=this.calculateReuseInfo(o,o.confidence);i.push({pattern:o,score:o.confidence,matchType:"exact",similarity:o.confidence,canReuse:l.canReuse,estimatedTokenSavings:l.estimatedTokenSavings,reuseConfidence:l.reuseConfidence})}}catch{}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let c=this.sqliteStore.searchFTS(e,s*2),u=new Set(i.map(o=>o.pattern.id));for(let o of c){if(u.has(o.id))continue;let l=await this.get(o.id);if(l&&this.matchesFilters(l,t)){let f=this.calculateReuseInfo(l,o.ftsScore);i.push({pattern:l,score:.5*o.ftsScore,matchType:"exact",similarity:o.ftsScore,canReuse:f.canReuse,estimatedTokenSavings:f.estimatedTokenSavings,reuseConfidence:f.reuseConfidence})}}}catch{}i.sort((c,u)=>u.score-c.score);let a=performance.now()-r;return this.searchOps++,this.totalSearchMs+=a,P(i.slice(0,s))}async recordUsage(e,t,r,s){if(!this.sqliteStore)return w(new Error("No SQLite store attached"));try{return this.sqliteStore.recordUsage(e,t,r,s),P(void 0)}catch(i){return w(new Error(`recordUsage failed: ${v(i)}`))}}async promote(e){if(!this.sqliteStore)return w(new Error("No SQLite store attached"));try{return this.sqliteStore.promotePattern(e),P(void 0)}catch(t){return w(new Error(`promote failed: ${v(t)}`))}}async delete(e){if(this.adapter)try{this.adapter.delete([e])}catch(t){console.warn(`[RvfPatternStore] RVF delete failed for ${e}:`,v(t))}if(this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(t){return w(new Error(`SQLite delete failed: ${v(t)}`))}return P(void 0)}async getStats(){let e=this.adapter?.status(),t=0,r={},s={shortTerm:0,longTerm:0};if(this.sqliteStore)try{let i=this.sqliteStore.getStats();t=i.totalPatterns,r=i.byDomain,s={shortTerm:i.byTier["short-term"]??0,longTerm:i.byTier["long-term"]??0}}catch{}return{totalPatterns:t,byTier:s,byDomain:r,byType:{},avgConfidence:0,avgQualityScore:0,avgSuccessRate:0,searchOperations:this.searchOps,avgSearchLatencyMs:this.searchOps>0?this.totalSearchMs/this.searchOps:0,hnswStats:{nativeAvailable:this.adapter!==null,vectorCount:e?.totalVectors??0,indexSizeBytes:e?.fileSizeBytes??0,...this.rvfInitError?{rvfInitError:this.rvfInitError}:{}}}}async cleanup(){if(!this.sqliteStore)return{removed:0,promoted:0};let e=0,t=0;try{let r=this.sqliteStore.getPatterns({limit:1e4});for(let s of r)s.confidence<this.config.minConfidence&&s.usageCount>3?(await this.delete(s.id),e++):s.tier==="short-term"&&s.successfulUses>=B&&(await this.promote(s.id),t++)}catch(r){console.warn("[RvfPatternStore] Cleanup error:",v(r))}return{removed:e,promoted:t}}async ensureInitialized(){this.initialized||await this.initialize()}matchesFilters(e,t){return!(t.patternType&&e.patternType!==t.patternType||t.domain&&e.qeDomain!==t.domain||t.tier&&e.tier!==t.tier||t.minConfidence&&e.confidence<t.minConfidence||t.minQualityScore&&e.qualityScore<t.minQualityScore)}calculateReuseInfo(e,t){let r=this.config.reuseOptimization,s=r.enabled&&t>=r.minSimilarityForReuse&&e.successRate>=r.minSuccessRateForReuse;return{canReuse:s,estimatedTokenSavings:s?500:0,reuseConfidence:s?t*e.successRate:0}}};it();Ce();F();function at(n,e){let r=[n.pattern,n];for(let s of r){let i=e.split("."),a=s;for(let c of i){if(a==null)break;if(typeof a=="object")a=a[c];else{a=void 0;break}}if(a!==void 0)return a}}function ot(n,e,t){switch(e){case"eq":return n===t;case"gt":return typeof n=="number"&&typeof t=="number"&&n>t;case"lt":return typeof n=="number"&&typeof t=="number"&&n<t;case"gte":return typeof n=="number"&&typeof t=="number"&&n>=t;case"lte":return typeof n=="number"&&typeof t=="number"&&n<=t;case"in":return Array.isArray(t)?t.includes(n):!1;case"contains":return Array.isArray(n)||typeof n=="string"&&typeof t=="string"?n.includes(t):!1;case"between":{if(typeof n!="number"||!Array.isArray(t)||t.length!==2){if(n instanceof Date&&Array.isArray(t)&&t.length===2){let i=n.getTime(),a=t[0]instanceof Date?t[0].getTime():Number(t[0]),c=t[1]instanceof Date?t[1].getTime():Number(t[1]);return i>=a&&i<=c}return!1}let[r,s]=t;return n>=r&&n<=s}default:return!1}}function X(n,e){switch(e.type){case"AND":return(e.children??[]).every(r=>X(n,r));case"OR":{let t=e.children??[];return t.length===0?!0:t.some(r=>X(n,r))}case"NOT":return e.child?!X(n,e.child):!0;case"FIELD":{if(!e.field||!e.operator)return!0;let t=at(n,e.field);return ot(t,e.operator,e.value)}default:return!0}}function Ne(n,e){return e?n.filter(t=>X(t,e)):n}F();F();var Me=1e4,Le=2166136261;function ke(n){let e=2166136261;for(let t=0;t<n.length;t++)e^=n.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}var oe=new Uint8Array(256);for(let n=0;n<256;n++){let e=0,t=n;for(;t;)e++,t&=t-1;oe[n]=e}var He="0123456789abcdef";function ct(n){let e=Math.min(n.length,16),t="";for(let r=0;r<e;r++){let s=n[r];t+=He[s>>4]+He[s&15]}return t}function lt(n,e){if(n.length!==e.length)throw new Error(`Cannot bind vectors of different lengths: ${n.length} vs ${e.length}`);let t=new Uint8Array(n.length);for(let r=0;r<n.length;r++)t[r]=n[r]^e[r];return t}function ut(n){if(n.length===0)throw new Error("Cannot bundle zero vectors");let e=n[0].length;for(let s=1;s<n.length;s++)if(n[s].length!==e)throw new Error(`Vector length mismatch at index ${s}: expected ${e}, got ${n[s].length}`);let t=new Uint8Array(e),r=n.length/2;for(let s=0;s<e;s++){let i=0;for(let a=0;a<8;a++){let c=0,u=1<<a;for(let o=0;o<n.length;o++)n[o][s]&u&&c++;c>=r&&(i|=u)}t[s]=i}return t}function ht(n,e,t){if(n.length!==e.length)throw new Error(`Cannot compute Hamming distance for vectors of different lengths: ${n.length} vs ${e.length}`);let r=0;for(let i=0;i<n.length;i++)r+=oe[n[i]^e[i]];let s=t??n.length*8;return s>0?r/s:0}function dt(n,e,t){return 1-ht(n,e,t)}var se=class{dimensions;baseSeed;byteLen;tokenCache=new Map;constructor(e){if(this.dimensions=e?.dimensions??Me,this.baseSeed=e?.seed??Le,this.byteLen=Math.ceil(this.dimensions/8),this.dimensions<=0)throw new Error(`HDC dimensions must be positive, got ${this.dimensions}`)}tokenToHypervector(e){let t=this.tokenCache.get(e);if(t)return new Uint8Array(t);let r=ke(e)^this.baseSeed,s=this.generateSeededVector(r);return this.tokenCache.set(e,s),new Uint8Array(s)}fingerprintPattern(e){if(e.length===0)return new Uint8Array(this.byteLen);let t=this.tokenToHypervector(e[0]);for(let r=1;r<e.length;r++)t=lt(t,this.tokenToHypervector(e[r]));return t}fingerprintWithContext(e,t){let r=this.fingerprintPattern(e);if(t.length===0)return r;let s=this.fingerprintPattern(t);return ut([r,s])}similarity(e,t){return dt(e,t,this.dimensions)}generateSeededVector(e){let t=new Uint8Array(this.byteLen),r=new ne(e),s=0;for(;s<this.byteLen;){let a=r.next(),c=Math.min(4,this.byteLen-s);for(let u=0;u<c;u++)t[s++]=a>>>u*8&255}let i=this.dimensions%8;return i>0&&(t[this.byteLen-1]&=(1<<i)-1),t}},ae=class{dimensions;baseSeed;constructor(e){if(this.dimensions=e?.dimensions??Me,this.baseSeed=e?.seed??Le,this.dimensions<=0)throw new Error(`HDC dimensions must be positive, got ${this.dimensions}`)}fingerprint(e){let t=`${e.id}|${e.domain}|${e.type}|${e.content??""}`,r=ke(t)^this.baseSeed,s=this.generateVector(r);return{vector:s,dimensions:this.dimensions,hash:ct(s)}}compositionalBind(e,t){if(e.length!==t.length)throw new Error(`Cannot bind vectors of different lengths: ${e.length} vs ${t.length}`);let r=new Uint8Array(e.length);for(let s=0;s<e.length;s++)r[s]=e[s]^t[s];return r}hammingDistance(e,t){if(e.length!==t.length)throw new Error(`Cannot compute Hamming distance for vectors of different lengths: ${e.length} vs ${t.length}`);let r=0;for(let s=0;s<e.length;s++)r+=oe[e[s]^t[s]];return r}similarity(e,t){return 1-this.hammingDistance(e,t)/this.dimensions}batchFingerprint(e){return e.map(t=>this.fingerprint(t))}generateVector(e){let t=Math.ceil(this.dimensions/8),r=new Uint8Array(t),s=new ne(e),i=0;for(;i<t;){let c=s.next(),u=t-i,o=u<4?u:4;for(let l=0;l<o;l++)r[i++]=c>>>l*8&255}let a=this.dimensions%8;return a>0&&(r[t-1]&=(1<<a)-1),r}};function Ue(n){return new ae(n)}function Qe(n){return Q()?new se(n):null}var ye=rt(je(),1),ge=ye.default??ye,_t=`
|
|
4
4
|
CREATE TABLE IF NOT EXISTS pattern_deltas (
|
|
5
5
|
id TEXT PRIMARY KEY,
|
|
6
6
|
pattern_id TEXT NOT NULL,
|
|
@@ -46,7 +46,7 @@ import{d as J,e as B,f as te,g as j}from"./chunk-VLNPJAVH.js";import{a as ne}fro
|
|
|
46
46
|
WHERE pattern_id = ? AND version != 0
|
|
47
47
|
ORDER BY version ASC
|
|
48
48
|
LIMIT ?
|
|
49
|
-
)`).run(e,e,i)}}};F();var Ht={maxHistoryPerPattern:50,snapshotInterval:10,batchSize:20,epsilon:1e-7},ve=class{config;history=new Map;snapshots=new Map;versions=new Map;buffer=[];constructor(e){this.config={...Ht,...e}}recordGenesis(e,t,r){if(this.versions.has(e))throw new Error(`Genesis already exists for pattern ${e} (version ${this.versions.get(e)})`);let s=this.computeSparseChanges(new Array(t.length).fill(0),t),i={patternId:e,version:0,timestamp:Date.now(),deltaType:"genesis",sparseChanges:s,metadata:r,compressedSize:s.length},a={patternId:e,version:0,fullVector:[...t],timestamp:i.timestamp};return this.versions.set(e,0),this.getOrCreate(this.history,e).push(i),this.getOrCreate(this.snapshots,e).push(a),this.buffer.push(i),i}recordDelta(e,t,r,s){let i=this.versions.get(e);if(i===void 0)throw new Error(`No genesis found for pattern ${e}. Call recordGenesis() first.`);let a=i+1,c=this.computeSparseChanges(t,r),u={patternId:e,version:a,timestamp:Date.now(),deltaType:"update",sparseChanges:c,metadata:s,compressedSize:c.length};return this.versions.set(e,a),this.getOrCreate(this.history,e).push(u),this.buffer.push(u),a%this.config.snapshotInterval===0&&this.getOrCreate(this.snapshots,e).push({patternId:e,version:a,fullVector:[...r],timestamp:u.timestamp}),this.enforceRetention(e),u}getHistory(e,t){let r=this.history.get(e);if(!r||r.length===0)return[];let s=[...r].reverse();return t!==void 0&&t>0?s.slice(0,t):s}rollback(e,t){let r=this.reconstructAtVersion(e,t);return r===null?null:{patternId:e,version:t,fullVector:r,timestamp:Date.now()}}getVersion(e){return this.versions.get(e)??-1}reconstructAtVersion(e,t){let r=this.history.get(e);if(!r||r.length===0)return null;let s=this.versions.get(e);if(t<0||t>s)return null;let i=this.snapshots.get(e)||[],a=null;for(let o=i.length-1;o>=0;o--)if(i[o].version<=t){a=i[o];break}if(!a)return null;let c=[...a.fullVector],u=a.version+1;for(let o of r)if(!(o.version<u)){if(o.version>t)break;this.applySparseForward(c,o.sparseChanges)}return c}pruneHistory(e,t){let r=t??this.config.maxHistoryPerPattern,s=this.history.get(e);if(!s||s.length<=r)return 0;let i=s.length-r,a=s.slice(0,i),c=s.slice(i),u=a.findIndex(f=>f.deltaType==="genesis");u>=0&&(c.unshift(a[u]),a.splice(u,1)),this.history.set(e,c);let o=c[0]?.version??0,l=this.snapshots.get(e);return l&&this.snapshots.set(e,l.filter(f=>f.version===0||f.version>=o)),a.length}getStats(){let e=0;for(let r of this.history.values())e+=r.length;let t=this.history.size;return{totalPatterns:t,totalDeltas:e,avgDeltasPerPattern:t>0?e/t:0}}flush(){let e=[...this.buffer];return this.buffer.length=0,e}getBufferSize(){return this.buffer.length}clear(){this.history.clear(),this.snapshots.clear(),this.versions.clear(),this.buffer.length=0}computeSparseChanges(e,t){let r=[],s=Math.max(e.length,t.length);for(let i=0;i<s;i++){let a=i<e.length?e[i]:0,c=i<t.length?t[i]:0;Math.abs(a-c)>this.config.epsilon&&r.push({index:i,oldValue:a,newValue:c})}return r}applySparseForward(e,t){for(let r of t){for(;e.length<=r.index;)e.push(0);e[r.index]=r.newValue}}enforceRetention(e){this.pruneHistory(e,this.config.maxHistoryPerPattern)}getOrCreate(e,t){let r=e.get(t);return r||(r=[],e.set(t,r)),r}};function Ge(n){return H()?new ve(n):null}F();var Mt=128,Lt=8,kt=1e4,Pe=class{dimension;beta;maxPatterns;patterns;constructor(e){if(this.dimension=e?.dimension??Mt,this.beta=e?.beta??Lt,this.maxPatterns=e?.maxPatterns??kt,this.patterns=[],this.dimension<=0)throw new Error(`Hopfield dimension must be positive, got ${this.dimension}`);if(this.beta<=0)throw new Error(`Hopfield beta must be positive, got ${this.beta}`);if(this.maxPatterns<=0)throw new Error(`Hopfield maxPatterns must be positive, got ${this.maxPatterns}`)}store(e,t){if(this.assertEnabled(),e.length!==this.dimension)throw new Error(`Pattern dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(this.dotProduct(e,e)===0)throw new Error("Cannot store zero-magnitude pattern in Hopfield memory");let s=this.normalize(e);this.patterns.length>=this.maxPatterns&&this.patterns.shift(),this.patterns.push({pattern:s,metadata:t??{},storedAt:Date.now()})}recall(e){if(this.assertEnabled(),e.length!==this.dimension)throw new Error(`Query dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(this.patterns.length===0)return null;let t=this.normalize(e),r=new Float32Array(this.patterns.length);for(let l=0;l<this.patterns.length;l++)r[l]=this.beta*this.dotProduct(this.patterns[l].pattern,t);let s=this.softmax(r),i=0,a=s[0];for(let l=1;l<s.length;l++)s[l]>a&&(a=s[l],i=l);let c=this.patterns[i],u=this.getEnergy(t),o=this.cosineSimilarity(t,c.pattern);return{pattern:new Float32Array(c.pattern),metadata:{...c.metadata},energy:u,similarity:o}}batchRecall(e){return this.assertEnabled(),e.map(t=>this.recall(t))}getPatternCount(){return this.patterns.length}clear(){this.patterns.length=0}getEnergy(e){if(e.length!==this.dimension)throw new Error(`State dimension mismatch: expected ${this.dimension}, got ${e.length}`);let t=this.normalize(e);if(this.patterns.length===0)return .5*this.dotProduct(t,t);let r=new Float32Array(this.patterns.length);for(let o=0;o<this.patterns.length;o++)r[o]=this.dotProduct(this.patterns[o].pattern,t);let s=new Float32Array(this.patterns.length),i=-1/0;for(let o=0;o<this.patterns.length;o++)s[o]=this.beta*r[o],s[o]>i&&(i=s[o]);let a=0;for(let o=0;o<this.patterns.length;o++)a+=Math.exp(s[o]-i);let c=1/this.beta*(i+Math.log(a)),u=this.dotProduct(t,t);return-c+.5*u}softmax(e){let t=new Float32Array(e.length),r=-1/0;for(let i=0;i<e.length;i++)e[i]>r&&(r=e[i]);let s=0;for(let i=0;i<e.length;i++)t[i]=Math.exp(e[i]-r),s+=t[i];if(s>0)for(let i=0;i<t.length;i++)t[i]/=s;return t}dotProduct(e,t){let r=0;for(let s=0;s<e.length;s++)r+=e[s]*t[s];return r}cosineSimilarity(e,t){let r=this.dotProduct(e,t),s=Math.sqrt(this.dotProduct(e,e)),i=Math.sqrt(this.dotProduct(t,t));return s===0||i===0?0:r/(s*i)}normalize(e){let t=Math.sqrt(this.dotProduct(e,e)),r=new Float32Array(e.length);if(t>0)for(let s=0;s<e.length;s++)r[s]=e[s]/t;return r}assertEnabled(){if(!D().useHopfieldMemory)throw new Error("Hopfield memory is disabled (useHopfieldMemory feature flag is false)")}};function Ve(n){return new Pe(n)}F();var Ut={dimensions:32,curvature:-1,maxElements:1e4,efConstruction:200,M:16},_=1e-5,Ye=1-_;function Qt(n,e){let t=0;for(let r=0;r<n.length;r++)t+=n[r]*e[r];return t}function A(n){let e=0;for(let t=0;t<n.length;t++)e+=n[t]*n[t];return e}function qt(n,e){let t=new Float32Array(n.length);for(let r=0;r<n.length;r++)t[r]=n[r]-e[r];return t}var T=class n{static poincareDistance(e,t){let r=A(qt(e,t)),s=Math.max(_,1-A(e)),i=Math.max(_,1-A(t));return Math.acosh(Math.max(1,1+2*r/(s*i)))}static mobiusAdd(e,t){let r=Qt(e,t),s=A(e),i=A(t),a=Math.max(_,1+2*r+s*i),c=1+2*r+i,u=1-s,o=new Float32Array(e.length);for(let l=0;l<e.length;l++)o[l]=(c*e[l]+u*t[l])/a;return n.project(o)}static expMap(e,t){let r=2/Math.max(_,1-A(e)),s=Math.sqrt(A(t));if(s<_)return new Float32Array(e);let i=Math.tanh(r*s/2),a=new Float32Array(t.length);for(let c=0;c<t.length;c++)a[c]=i/s*t[c];return n.mobiusAdd(e,a)}static project(e){let t=Math.sqrt(A(e));if(t<=Ye)return new Float32Array(e);let r=Ye/t,s=new Float32Array(e.length);for(let i=0;i<e.length;i++)s[i]=e[i]*r;return s}static euclideanToHyperbolic(e){let t=Math.sqrt(A(e));if(t<_)return new Float32Array(e.length);let r=Math.tanh(t)/t,s=new Float32Array(e.length);for(let i=0;i<e.length;i++)s[i]=e[i]*r;return n.project(s)}},we=class{config;points=new Map;constructor(e){if(this.config={...Ut,...e},this.config.dimensions<=0)throw new Error(`dimensions must be positive, got ${this.config.dimensions}`);if(this.config.curvature>=0)throw new Error(`curvature must be negative for hyperbolic space, got ${this.config.curvature}`);if(this.config.maxElements<=0)throw new Error(`maxElements must be positive, got ${this.config.maxElements}`)}insert(e,t,r){if(t.length!==this.config.dimensions)throw new Error(`Dimension mismatch: expected ${this.config.dimensions}, got ${t.length}`);if(this.points.size>=this.config.maxElements)throw new Error(`Maximum elements (${this.config.maxElements}) reached`);this.points.set(e,{id:e,coordinates:T.project(t),metadata:r?{...r}:void 0})}search(e,t){if(e.length!==this.config.dimensions)throw new Error(`Query dimension mismatch: expected ${this.config.dimensions}, got ${e.length}`);let r=T.project(e),s=[];for(let i of this.points.values())s.push({id:i.id,distance:T.poincareDistance(r,i.coordinates),point:i});return s.sort((i,a)=>i.distance-a.distance),s.slice(0,Math.max(0,t))}embedHierarchy(e){let t=new Map;if(e.length===0)return t;let r=this.config.dimensions,s=new Map,i=new Map,a=[];for(let u of e)if(i.set(u.id,u),!u.parentId)a.push(u.id);else{let o=s.get(u.parentId);o||(o=[],s.set(u.parentId,o)),o.push(u.id)}let c=a.map((u,o)=>({id:u,depth:0,angOff:2*Math.PI*o/Math.max(1,a.length),angSpan:2*Math.PI/Math.max(1,a.length)}));for(;c.length>0;){let{id:u,depth:o,angOff:l,angSpan:f}=c.shift(),d=Math.tanh(.3*(o+.1)),h=l+f/2,m=new Float32Array(r);m[0]=d*Math.cos(h),m[1]=d*Math.sin(h);let p=i.get(u);if(p&&p.features.length>0){let N=d*.1;for(let x=2;x<r&&x-2<p.features.length;x++)m[x]=p.features[x-2]*N}let y=T.project(m);t.set(u,y),this.points.set(u,{id:u,coordinates:y,metadata:{depth:o,parentId:p?.parentId}});let S=s.get(u)??[];for(let N=0;N<S.length;N++){let x=f/Math.max(1,S.length);c.push({id:S[N],depth:o+1,angOff:l+N*x,angSpan:x})}}return t}getStats(){return{elementCount:this.points.size,dimensions:this.config.dimensions,curvature:this.config.curvature}}};function Ke(n){return zt()?new we(n):null}function zt(){return D().useHyperbolicHnsw}F();var Se=class{index=null;initialized=!1;config;constructor(e){this.config=e??{}}ensureInitialized(){if(this.initialized)return this.index!==null;if(this.initialized=!0,!M())return!1;try{return this.index=Ke(this.config),this.index!==null}catch(e){return console.warn("[HyperbolicPatternIndex] Failed to create HyperbolicHNSW:",e instanceof Error?e.message:e),this.index=null,!1}}get isAvailable(){return this.index!==null}indexPattern(e,t,r){if(!(!this.ensureInitialized()||!this.index))try{let s=t instanceof Float32Array?t:new Float32Array(t),i=T.euclideanToHyperbolic(s);this.index.insert(e,i,r)}catch(s){console.debug(`[HyperbolicPatternIndex] Failed to index pattern ${e}:`,s instanceof Error?s.message:s)}}search(e,t){if(!this.ensureInitialized()||!this.index)return[];try{let r=e instanceof Float32Array?e:new Float32Array(e),s=T.euclideanToHyperbolic(r);return this.index.search(s,t).map(a=>({patternId:a.id,distance:a.distance,metadata:a.point.metadata}))}catch(r){return console.warn("[HyperbolicPatternIndex] Search failed:",r instanceof Error?r.message:r),[]}}getStats(){return this.index?this.index.getStats():null}reset(){this.index=null,this.initialized=!1}};function Ze(n){return new Se(n)}var be=null;function et(){return be||(be=Ue({dimensions:1e4})),be}var Ee;function $t(){return Ee===void 0&&(Ee=Qe()),Ee}var U=null,Re=0;function tt(n){return(!U||Re!==n)&&(U=Ve({dimension:n,maxPatterns:1e4}),Re=n),U}var W={namespace:"qe-patterns",embeddingDimension:384,hnsw:{M:16,efConstruction:200,efSearch:100,maxElements:5e4},promotionThreshold:B,minConfidence:.3,maxPatternsPerDomain:5e3,autoCleanup:!0,cleanupIntervalMs:36e5,tokenTracking:{enabled:!0,trackInputOutput:!0,estimateCosts:!0,costPerInputToken:3e-6,costPerOutputToken:15e-6},reuseOptimization:{enabled:!0,minSimilarityForReuse:.85,minSuccessRateForReuse:.9,maxAgeForReuse:7}},Ae=class{constructor(e,t={}){this.memory=e;this.config={...W,...t}}memory;config;initialized=!1;cleanupTimer;sqliteStore=null;nullStore=null;loadingPromise=null;patternCache=new Map;domainIndex=new Map;typeIndex=new Map;tierIndex=new Map;hnswIndex=null;hnswAvailable=!1;hnswInitPromise=null;hdcCache=new Map;hdcTokenCache=new Map;deltaTracker=null;vectorDeltaTracker=void 0;hyperbolicIndex=null;stats={searchOperations:0,searchLatencies:[]};setSqliteStore(e){if(this.sqliteStore=e,H()&&!this.deltaTracker)try{let t=e.getDb();this.deltaTracker=new Z(t),this.deltaTracker.initialize(),console.log("[PatternStore] Delta event sourcing initialized")}catch(t){console.warn("[PatternStore] Delta tracker init failed:",t instanceof Error?t.message:t)}this.initialized&&(this.loadingPromise=this.loadPatterns().catch(t=>console.warn("[PatternStore] Failed to load patterns after setSqliteStore:",t)).finally(()=>{this.loadingPromise=null}))}async initialize(){this.initialized||(this.tierIndex.set("short-term",new Set),this.tierIndex.set("long-term",new Set),await this.loadPatterns(),this.config.autoCleanup&&(this.cleanupTimer=setInterval(()=>this.cleanup(),this.config.cleanupIntervalMs)),this.initialized=!0)}async ensureHNSW(){return this.hnswIndex!==null?this.hnswIndex:this.hnswAvailable===!1&&this.hnswInitPromise===null&&!(this.hnswIndex===null&&this.hnswAvailable===!1)?null:this.hnswInitPromise?(await this.hnswInitPromise,this.hnswIndex):(this.hnswInitPromise=this.initializeHNSWInternal(),await this.hnswInitPromise,this.hnswInitPromise=null,this.hnswIndex)}async initializeHNSWInternal(){try{if(D().useUnifiedHnsw)try{let{HnswLegacyBridge:a}=await import("./hnsw-legacy-bridge-RVM7EAIH.js"),{HnswAdapter:c}=await import("./hnsw-adapter-TIRPA7XE.js"),u=new c("patterns",{dimensions:this.config.embeddingDimension,M:this.config.hnsw.M,efConstruction:this.config.hnsw.efConstruction,efSearch:this.config.hnsw.efSearch,metric:"cosine"});this.hnswIndex=new a(u),this.hnswAvailable=!0,console.log("[PatternStore] Using unified HNSW via HnswLegacyBridge (ADR-071)"),await this.loadEmbeddingsIntoHNSW();return}catch(a){console.warn("[PatternStore] Unified HNSW bridge failed, falling back:",a)}let{HNSWIndex:t}=await import("./hnsw-index-SSQBRQCQ.js");this.hnswIndex=new t(this.memory,{dimensions:this.config.embeddingDimension,M:this.config.hnsw.M,efConstruction:this.config.hnsw.efConstruction,efSearch:this.config.hnsw.efSearch,maxElements:this.config.hnsw.maxElements,namespace:`${this.config.namespace}:hnsw`,metric:"cosine"});let r=5e3,s=this.hnswIndex.initialize(),i=new Promise((a,c)=>setTimeout(()=>c(new Error("HNSW init timeout")),r));await Promise.race([s,i]),this.hnswAvailable=this.hnswIndex.isNativeAvailable(),await this.loadEmbeddingsIntoHNSW(),console.log(`[PatternStore] HNSW lazy-initialized (native: ${this.hnswAvailable})`)}catch(e){console.warn("[PatternStore] HNSW not available, using memory backend search:",v(e)),this.hnswIndex=null,this.hnswAvailable=!1}}async loadEmbeddingsIntoHNSW(){if(!(!this.hnswIndex||!this.sqliteStore))try{let e=this.sqliteStore.getAllEmbeddings(),t=this.config.hnsw.maxElements,r=0,s=0;for(let{patternId:i,embedding:a}of e){if(r>=t)break;if(!a||a.length!==this.config.embeddingDimension){s++;continue}let c=this.patternCache.get(i);if(!c){s++;continue}try{await this.hnswIndex.insert(i,a,{filePath:c.patternType,lineCoverage:c.confidence*100,branchCoverage:c.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-c.confidence,lastUpdated:Date.now(),totalLines:0}),r++}catch{s++}}r>0&&console.log(`[PatternStore] Loaded ${r} embeddings into HNSW (skipped ${s})`)}catch(e){console.warn("[PatternStore] Failed to load SQLite embeddings into HNSW:",v(e))}}getVectorDeltaTracker(){return this.vectorDeltaTracker===void 0&&(this.vectorDeltaTracker=Ge()),this.vectorDeltaTracker}async loadPatterns(){if(this.sqliteStore)try{let e=this.sqliteStore.getPatterns({limit:5e4});for(let t of e)this.indexPattern(t);e.length>0&&console.log(`[PatternStore] Loaded ${e.length} patterns from SQLite into memory cache`)}catch(e){console.warn("[PatternStore] Failed to load patterns from SQLite:",v(e))}}indexPattern(e){this.patternCache.set(e.id,e),this.domainIndex.has(e.qeDomain)||this.domainIndex.set(e.qeDomain,new Set),this.domainIndex.get(e.qeDomain).add(e.id),this.typeIndex.has(e.patternType)||this.typeIndex.set(e.patternType,new Set),this.typeIndex.get(e.patternType).add(e.id);let t=e.tier==="long-term"?"long-term":"short-term";e.tier!==t&&(e.tier=t),this.tierIndex.get(t).add(e.id)}unindexPattern(e){this.patternCache.delete(e.id),this.domainIndex.get(e.qeDomain)?.delete(e.id),this.typeIndex.get(e.patternType)?.delete(e.id),this.tierIndex.get(e.tier)?.delete(e.id),this.hdcCache.delete(e.id),this.hdcTokenCache.delete(e.id)}async store(e){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let t=j(e);if(!t.valid)return w(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return w(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));(this.domainIndex.get(e.qeDomain)?.size||0)>=this.config.maxPatternsPerDomain&&await this.cleanupDomain(e.qeDomain);let s=this.patternCache.get(e.id)??null;if(this.indexPattern(e),this.sqliteStore)try{let i=this.sqliteStore.storePattern(e,e.embedding);i&&i!==e.id&&(this.unindexPattern(e),e.id=i,this.indexPattern(e))}catch(i){console.warn(`[PatternStore] SQLite persist failed for ${e.id}:`,v(i))}if(e.embedding){let i=await this.ensureHNSW();if(i)try{await i.insert(e.id,e.embedding,{filePath:e.patternType,lineCoverage:e.confidence*100,branchCoverage:e.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-e.confidence,lastUpdated:Date.now(),totalLines:0})}catch(a){console.warn(`[PatternStore] Failed to index embedding for ${e.id}:`,a)}}if(Q())try{let a=et().fingerprint({id:e.id,domain:e.qeDomain,type:e.patternType,content:e.description});this.hdcCache.set(e.id,a.vector)}catch(i){console.debug(`[PatternStore] HDC fingerprint failed for ${e.id}:`,v(i))}try{let i=$t();if(i){let a=[e.patternType,e.qeDomain];e.context?.tags&&a.push(...e.context.tags),e.name&&a.push(e.name);let c=i.fingerprintPattern(a);this.hdcTokenCache.set(e.id,c)}}catch(i){console.debug(`[PatternStore] HDC token fingerprint failed for ${e.id}:`,v(i))}if(ee()&&e.embedding)try{tt(e.embedding.length).store(new Float32Array(e.embedding),{id:e.id,name:e.name,domain:e.qeDomain})}catch(i){console.debug(`[PatternStore] Hopfield store failed for ${e.id}:`,v(i))}if(H()&&this.deltaTracker)try{let i={id:e.id,name:e.name,confidence:e.confidence,qualityScore:e.qualityScore,usageCount:e.usageCount,successRate:e.successRate,tier:e.tier};this.deltaTracker.createGenesis(e.id,i)}catch(i){console.debug(`[PatternStore] Delta genesis for ${e.id}:`,v(i))}if(e.embedding)try{let i=this.getVectorDeltaTracker();i&&(s?.embedding?i.recordDelta(e.id,s.embedding,e.embedding):i.getVersion(e.id)<0&&i.recordGenesis(e.id,e.embedding))}catch(i){console.debug(`[PatternStore] VectorDeltaTracker for ${e.id}:`,v(i))}try{M()&&e.embedding&&this.indexHyperbolic(e.id,e.embedding,{domain:e.qeDomain,type:e.patternType,name:e.name})}catch{}return P(e.id)}async create(e){let t=new Date,r=e.qeDomain||this.detectDomainFromType(e.patternType),s={id:C(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:e.confidence??.5,usageCount:0,successRate:0,qualityScore:.25,context:{...e.context,tags:e.context?.tags||[]},template:{...e.template,example:void 0},embedding:e.embedding,tier:"short-term",createdAt:t,lastUsedAt:t,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},i=await this.store(s);return i.success?P(s):w(i.error)}detectDomainFromType(e){return{"test-template":"test-generation","assertion-pattern":"test-generation","mock-pattern":"test-generation","coverage-strategy":"coverage-analysis","mutation-strategy":"test-generation","api-contract":"contract-testing","visual-baseline":"visual-accessibility","a11y-check":"visual-accessibility","perf-benchmark":"chaos-resilience","flaky-fix":"test-execution","refactor-safe":"code-intelligence","error-handling":"test-generation","meta-optimization":"learning-optimization"}[e]||"test-generation"}async get(e){return this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise,this.patternCache.get(e)??null}async search(e,t={}){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let r=performance.now(),s=t.limit||10,i=[];try{if(Array.isArray(e)&&ee())try{let d=tt(e.length);if(d.getPatternCount()>0){let h=d.recall(new Float32Array(e));if(h&&h.similarity>.98){let m=h.metadata.id,p=await this.get(m);if(p&&this.matchesFilters(p,t)){let y=this.calculateReuseInfo(p,h.similarity);i.push({pattern:p,score:h.similarity,matchType:"vector",similarity:h.similarity,canReuse:y.canReuse,estimatedTokenSavings:y.estimatedTokenSavings,reuseConfidence:y.reuseConfidence})}}}}catch(d){console.debug("[PatternStore] Hopfield recall failed:",v(d))}if(Array.isArray(e)&&t.useVectorSearch!==!1){let d=await this.ensureHNSW();if(d){let h=await d.search(e,s*2);for(let m of h){let p=await this.get(m.key);if(p&&this.matchesFilters(p,t)){let y=this.calculateReuseInfo(p,m.score);i.push({pattern:p,score:m.score,matchType:"vector",similarity:m.score,canReuse:y.canReuse,estimatedTokenSavings:y.estimatedTokenSavings,reuseConfidence:y.reuseConfidence})}}}}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let d=this.sqliteStore.searchFTS(e,s*2);if(d.length>0){let h=new Map(d.map(p=>[p.id,p.ftsScore])),m=new Set(i.map(p=>p.pattern.id));for(let p of i){let y=h.get(p.pattern.id);y!==void 0&&(p.score=.75*p.score+.25*y)}for(let p of d){if(m.has(p.id))continue;let y=await this.get(p.id);if(y&&this.matchesFilters(y,t)){let S=this.calculateReuseInfo(y,p.ftsScore);i.push({pattern:y,score:.5*p.ftsScore,matchType:"exact",similarity:p.ftsScore,canReuse:S.canReuse,estimatedTokenSavings:S.estimatedTokenSavings,reuseConfidence:S.reuseConfidence})}}}}catch{}if(typeof e=="string"||i.length<s){let d=await this.searchByText(typeof e=="string"?e:"",t,s-i.length),h=new Set(i.map(m=>m.pattern.id));for(let m of d)h.has(m.pattern.id)||i.push(m)}let a=720*60*60*1e3,c=Date.now();for(let d of i){let h=d.pattern.lastUsedAt?.getTime()??d.pattern.createdAt.getTime(),m=c-h,p=Math.pow(.5,m/a),y=d.pattern.usageCount>0?p:.5;d.score=d.score*(.7+.3*y)}let u=this.sqliteStore?.getDatabase();if(u&&i.length>0)try{this.nullStore||(this.nullStore=new ie(u));let d=this.nullStore.getNullSummaries(i.map(h=>h.pattern.id));for(let h of i){let m=d.get(h.pattern.id);m&&(h.nullSummary=m,h.score=ie.applyNullDiscount(h.score,m,t.contextFingerprint))}}catch(d){console.debug("[PatternStore] null discount skipped:",v(d))}i.sort((d,h)=>h.score-d.score);let o=i;t.filter&&(o=Ne(i,t.filter));let l=o.slice(0,s),f=performance.now()-r;return this.recordSearchLatency(f),P(l)}catch(a){return w(xe(a))}}async searchByText(e,t,r){let s=[],i=e.toLowerCase(),a;t.domain?a=this.domainIndex.get(t.domain)||new Set:t.patternType?a=this.typeIndex.get(t.patternType)||new Set:t.tier?a=this.tierIndex.get(t.tier)||new Set:a=new Set(this.patternCache.keys());let c=[...a];if(Q()&&i&&this.hdcCache.size>0)try{let u=et(),o=u.fingerprint({id:"query",domain:t.domain??"unknown",type:t.patternType??"unknown",content:e}),l=c.filter(h=>this.hdcCache.has(h)).map(h=>({id:h,similarity:u.similarity(o.vector,this.hdcCache.get(h))}));l.sort((h,m)=>m.similarity-h.similarity);let f=l.map(h=>h.id),d=c.filter(h=>!this.hdcCache.has(h));c=[...f,...d]}catch{}for(let u of c){if(s.length>=r)break;let o=this.patternCache.get(u);if(!o||!this.matchesFilters(o,t))continue;let l=0;if(i){let f=o.name.toLowerCase(),d=o.description.toLowerCase();f.includes(i)&&(l+=.5),d.includes(i)&&(i.length/d.length>.3?l+=.5:l+=.3);for(let h of o.context.tags)if(h.toLowerCase().includes(i)){l+=.2;break}l=Math.min(l,1)}else l=o.qualityScore;if(l>0||!i){let f=this.calculateReuseInfo(o,l);s.push({pattern:o,score:l||o.qualityScore,matchType:i?"exact":"context",similarity:l||o.qualityScore,canReuse:f.canReuse,estimatedTokenSavings:f.estimatedTokenSavings,reuseConfidence:f.reuseConfidence})}}return s}calculateReuseInfo(e,t){let{reuseOptimization:r}=this.config,s=t>=r.minSimilarityForReuse,i=e.successRate>=r.minSuccessRateForReuse,a=e.lastUsedAt instanceof Date?e.lastUsedAt.getTime():new Date(e.lastUsedAt).getTime(),u=(Date.now()-a)/(1e3*60*60*24)<=r.maxAgeForReuse,o=r.enabled&&e.reusable&&s&&i&&u,l=o?e.averageTokenSavings>0?e.averageTokenSavings:e.tokensUsed||0:0,f=t,d=e.successRate,h=Math.min(e.reuseCount/10,1),m=o?f*.4+d*.4+h*.2:0;return{canReuse:o,estimatedTokenSavings:l,reuseConfidence:m}}matchesFilters(e,t){if(t.patternType&&e.patternType!==t.patternType||t.domain&&e.qeDomain!==t.domain||t.tier&&e.tier!==t.tier||t.minConfidence!==void 0&&e.confidence<t.minConfidence||t.minQualityScore!==void 0&&e.qualityScore<t.minQualityScore)return!1;if(t.context){let r=t.context;if(r.language&&e.context.language!==r.language||r.framework&&e.context.framework!==r.framework||r.testType&&e.context.testType!==r.testType)return!1}return!0}async recordUsage(e,t,r,s){let i=await this.get(e);if(!i)return w(new Error(`Pattern not found: ${e}`));let a=new Date,c=i.usageCount+1,u=i.successfulUses+(t?1:0),o=u/c,l=t?.02:-.01,f=Math.max(.1,Math.min(1,i.confidence+l)),d=J({confidence:f,usageCount:c,successRate:o}),h={...i,usageCount:c,successfulUses:u,successRate:o,confidence:f,qualityScore:d,lastUsedAt:a};if(this.sqliteStore)try{this.sqliteStore.recordUsage(e,t,r,s)}catch(y){console.warn(`[PatternStore] SQLite recordUsage failed for ${e}:`,v(y))}if(H()&&this.deltaTracker)try{let y={id:i.id,name:i.name,confidence:i.confidence,qualityScore:i.qualityScore,usageCount:i.usageCount,successRate:i.successRate,tier:i.tier},S={id:h.id,name:h.name,confidence:h.confidence,qualityScore:h.qualityScore,usageCount:h.usageCount,successRate:h.successRate,tier:h.tier};this.deltaTracker.recordDelta(e,y,S,{success:t})}catch(y){console.debug(`[PatternStore] Delta recordDelta for ${e}:`,v(y))}let m=te(h);return m.meetsUsageCriteria&&m.meetsQualityCriteria&&m.meetsCoherenceCriteria&&h.tier==="short-term"?await this.promote(e):this.patternCache.set(e,h),P(void 0)}async promote(e){let t=await this.get(e);if(!t)return w(new Error(`Pattern not found: ${e}`));if(t.tier==="long-term")return P(void 0);let r={...t,tier:"long-term",confidence:Math.min(1,t.confidence+.1)};if(this.tierIndex.get("short-term")?.delete(e),this.tierIndex.get("long-term")?.add(e),this.patternCache.set(e,r),this.sqliteStore)try{this.sqliteStore.promotePattern(e)}catch(s){console.debug("[PatternStore] SQLite promotion error:",s instanceof Error?s.message:s)}return console.log(`[PatternStore] Promoted pattern ${e} (${t.name}) to long-term storage`),P(void 0)}async delete(e){let t=this.patternCache.get(e);if(!t)return w(new Error(`Pattern not found: ${e}`));if(this.unindexPattern(t),this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(r){console.debug("[PatternStore] SQLite deletion error:",r instanceof Error?r.message:r)}if(this.hnswIndex!==null)try{await this.hnswIndex.delete(e)}catch(r){console.debug("[PatternStore] HNSW deletion error:",r instanceof Error?r.message:r)}return P(void 0)}async getStats(){let e={},t={};for(let[o,l]of this.domainIndex)e[o]=l.size;for(let[o,l]of this.typeIndex)t[o]=l.size;let r=0,s=0,i=0,a=0;for(let o of this.patternCache.values())r+=o.confidence,s+=o.qualityScore,i+=o.successRate,a++;let c=await this.ensureHNSW(),u=c!==null?await c.getStats():{nativeHNSW:!1,vectorCount:0,indexSizeBytes:0,lazyLoaded:!0};return{totalPatterns:this.patternCache.size,byTier:{shortTerm:this.tierIndex.get("short-term")?.size||0,longTerm:this.tierIndex.get("long-term")?.size||0},byDomain:e,byType:t,avgConfidence:a>0?r/a:0,avgQualityScore:a>0?s/a:0,avgSuccessRate:a>0?i/a:0,searchOperations:this.stats.searchOperations,avgSearchLatencyMs:this.calculateAvgLatency(),hnswStats:{nativeAvailable:u.nativeHNSW,vectorCount:u.vectorCount,indexSizeBytes:u.indexSizeBytes}}}async cleanup(){let e=0,t=0,r=[],s=[];for(let i of this.patternCache.values()){let a=te(i);if(a.meetsUsageCriteria&&a.meetsQualityCriteria&&a.meetsCoherenceCriteria){s.push(i.id);continue}if(i.tier==="short-term"){let u=i.createdAt instanceof Date?i.createdAt.getTime():new Date(i.createdAt).getTime(),o=Date.now()-u,l=o>10080*60*1e3,f=i.qualityScore<.2,d=i.usageCount===0&&o>1440*60*1e3;(l&&f||d)&&r.push(i.id)}}for(let i of s)(await this.promote(i)).success&&t++;for(let i of r)(await this.delete(i)).success&&e++;return console.log(`[PatternStore] Cleanup: removed ${e}, promoted ${t}`),{removed:e,promoted:t}}async cleanupDomain(e){let t=this.domainIndex.get(e);if(!t||t.size<this.config.maxPatternsPerDomain)return;let r=[];for(let a of t){let c=this.patternCache.get(a);c&&r.push(c)}r.sort((a,c)=>a.qualityScore-c.qualityScore);let s=Math.ceil(r.length*.1),i=0;for(let a of r){if(i>=s)break;a.tier==="short-term"&&(await this.delete(a.id),i++)}}recordSearchLatency(e){this.stats.searchOperations++,this.stats.searchLatencies.push(e),this.stats.searchLatencies.length>1e3&&(this.stats.searchLatencies=this.stats.searchLatencies.slice(-1e3))}calculateAvgLatency(){return this.stats.searchLatencies.length===0?0:this.stats.searchLatencies.reduce((t,r)=>t+r,0)/this.stats.searchLatencies.length}async dispose(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0),this.patternCache.clear(),this.domainIndex.clear(),this.typeIndex.clear(),this.tierIndex.clear(),this.hdcCache.clear(),this.deltaTracker=null,this.hyperbolicIndex&&(this.hyperbolicIndex.reset(),this.hyperbolicIndex=null),U&&(U.clear(),U=null,Re=0),this.initialized=!1}indexHyperbolic(e,t,r){if(M())try{this.hyperbolicIndex||(this.hyperbolicIndex=Ze({dimensions:this.config.embeddingDimension,maxElements:this.config.hnsw.maxElements})),this.hyperbolicIndex.indexPattern(e,t,r)}catch(s){console.debug(`[PatternStore] Hyperbolic indexing failed for ${e}:`,s instanceof Error?s.message:s)}}async searchHyperbolic(e,t=10){if(!M()||!this.hyperbolicIndex)return P([]);try{let r=this.hyperbolicIndex.search(e,t),s=[];for(let i of r){let a=await this.get(i.patternId);if(!a)continue;let c=Math.exp(-i.distance),u=this.calculateReuseInfo(a,c);s.push({pattern:a,score:c,matchType:"vector",similarity:c,canReuse:u.canReuse,estimatedTokenSavings:u.estimatedTokenSavings,reuseConfidence:u.reuseConfidence})}return P(s)}catch(r){return console.warn("[PatternStore] Hyperbolic search failed, returning empty results:",r instanceof Error?r.message:r),P([])}}};function Jr(n,e){try{if(D().useRVFPatternStore&&Oe()){let{existsSync:r}=Te("fs"),{join:s}=Te("path"),i=process.env.AQE_PROJECT_ROOT??De(),a=s(i,".agentic-qe"),c=s(a,"patterns.rvf");if(r(a)){let u={...W,...e},o=!1;try{let l=_e(a,u.embeddingDimension);if(l){o=!0;let f=new q(()=>l,{rvfPath:c,base:u,skipCloseOnDispose:!0});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),f}}catch{}if(!o){let l=new q((f,d)=>{let h=()=>{try{return Fe(f)}catch{return null}},m=h();if(m){if(m.dimension()!==d){try{m.close()}catch{}throw new Error(`RVF dimension mismatch (file=${m.dimension()}, requested=${d})`)}return m}try{return re(f,d)}catch(p){if(m=h(),m&&m.dimension()===d)return m;if(Ie(f,p instanceof Error?p.message:String(p)))return re(f,d);throw p}},{rvfPath:c,base:u});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),l}}}}catch(t){console.warn("[PatternStore] RVF store unavailable, using in-memory HNSW:",t instanceof Error?t.message:t)}return new Ae(n,e)}export{Jr as a};
|
|
49
|
+
)`).run(e,e,i)}}};F();var Ht={maxHistoryPerPattern:50,snapshotInterval:10,batchSize:20,epsilon:1e-7},ve=class{config;history=new Map;snapshots=new Map;versions=new Map;buffer=[];constructor(e){this.config={...Ht,...e}}recordGenesis(e,t,r){if(this.versions.has(e))throw new Error(`Genesis already exists for pattern ${e} (version ${this.versions.get(e)})`);let s=this.computeSparseChanges(new Array(t.length).fill(0),t),i={patternId:e,version:0,timestamp:Date.now(),deltaType:"genesis",sparseChanges:s,metadata:r,compressedSize:s.length},a={patternId:e,version:0,fullVector:[...t],timestamp:i.timestamp};return this.versions.set(e,0),this.getOrCreate(this.history,e).push(i),this.getOrCreate(this.snapshots,e).push(a),this.buffer.push(i),i}recordDelta(e,t,r,s){let i=this.versions.get(e);if(i===void 0)throw new Error(`No genesis found for pattern ${e}. Call recordGenesis() first.`);let a=i+1,c=this.computeSparseChanges(t,r),u={patternId:e,version:a,timestamp:Date.now(),deltaType:"update",sparseChanges:c,metadata:s,compressedSize:c.length};return this.versions.set(e,a),this.getOrCreate(this.history,e).push(u),this.buffer.push(u),a%this.config.snapshotInterval===0&&this.getOrCreate(this.snapshots,e).push({patternId:e,version:a,fullVector:[...r],timestamp:u.timestamp}),this.enforceRetention(e),u}getHistory(e,t){let r=this.history.get(e);if(!r||r.length===0)return[];let s=[...r].reverse();return t!==void 0&&t>0?s.slice(0,t):s}rollback(e,t){let r=this.reconstructAtVersion(e,t);return r===null?null:{patternId:e,version:t,fullVector:r,timestamp:Date.now()}}getVersion(e){return this.versions.get(e)??-1}reconstructAtVersion(e,t){let r=this.history.get(e);if(!r||r.length===0)return null;let s=this.versions.get(e);if(t<0||t>s)return null;let i=this.snapshots.get(e)||[],a=null;for(let o=i.length-1;o>=0;o--)if(i[o].version<=t){a=i[o];break}if(!a)return null;let c=[...a.fullVector],u=a.version+1;for(let o of r)if(!(o.version<u)){if(o.version>t)break;this.applySparseForward(c,o.sparseChanges)}return c}pruneHistory(e,t){let r=t??this.config.maxHistoryPerPattern,s=this.history.get(e);if(!s||s.length<=r)return 0;let i=s.length-r,a=s.slice(0,i),c=s.slice(i),u=a.findIndex(f=>f.deltaType==="genesis");u>=0&&(c.unshift(a[u]),a.splice(u,1)),this.history.set(e,c);let o=c[0]?.version??0,l=this.snapshots.get(e);return l&&this.snapshots.set(e,l.filter(f=>f.version===0||f.version>=o)),a.length}getStats(){let e=0;for(let r of this.history.values())e+=r.length;let t=this.history.size;return{totalPatterns:t,totalDeltas:e,avgDeltasPerPattern:t>0?e/t:0}}flush(){let e=[...this.buffer];return this.buffer.length=0,e}getBufferSize(){return this.buffer.length}clear(){this.history.clear(),this.snapshots.clear(),this.versions.clear(),this.buffer.length=0}computeSparseChanges(e,t){let r=[],s=Math.max(e.length,t.length);for(let i=0;i<s;i++){let a=i<e.length?e[i]:0,c=i<t.length?t[i]:0;Math.abs(a-c)>this.config.epsilon&&r.push({index:i,oldValue:a,newValue:c})}return r}applySparseForward(e,t){for(let r of t){for(;e.length<=r.index;)e.push(0);e[r.index]=r.newValue}}enforceRetention(e){this.pruneHistory(e,this.config.maxHistoryPerPattern)}getOrCreate(e,t){let r=e.get(t);return r||(r=[],e.set(t,r)),r}};function Ge(n){return H()?new ve(n):null}F();var Mt=128,Lt=8,kt=1e4,Pe=class{dimension;beta;maxPatterns;patterns;constructor(e){if(this.dimension=e?.dimension??Mt,this.beta=e?.beta??Lt,this.maxPatterns=e?.maxPatterns??kt,this.patterns=[],this.dimension<=0)throw new Error(`Hopfield dimension must be positive, got ${this.dimension}`);if(this.beta<=0)throw new Error(`Hopfield beta must be positive, got ${this.beta}`);if(this.maxPatterns<=0)throw new Error(`Hopfield maxPatterns must be positive, got ${this.maxPatterns}`)}store(e,t){if(this.assertEnabled(),e.length!==this.dimension)throw new Error(`Pattern dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(this.dotProduct(e,e)===0)throw new Error("Cannot store zero-magnitude pattern in Hopfield memory");let s=this.normalize(e);this.patterns.length>=this.maxPatterns&&this.patterns.shift(),this.patterns.push({pattern:s,metadata:t??{},storedAt:Date.now()})}recall(e){if(this.assertEnabled(),e.length!==this.dimension)throw new Error(`Query dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(this.patterns.length===0)return null;let t=this.normalize(e),r=new Float32Array(this.patterns.length);for(let l=0;l<this.patterns.length;l++)r[l]=this.beta*this.dotProduct(this.patterns[l].pattern,t);let s=this.softmax(r),i=0,a=s[0];for(let l=1;l<s.length;l++)s[l]>a&&(a=s[l],i=l);let c=this.patterns[i],u=this.getEnergy(t),o=this.cosineSimilarity(t,c.pattern);return{pattern:new Float32Array(c.pattern),metadata:{...c.metadata},energy:u,similarity:o}}batchRecall(e){return this.assertEnabled(),e.map(t=>this.recall(t))}getPatternCount(){return this.patterns.length}clear(){this.patterns.length=0}getEnergy(e){if(e.length!==this.dimension)throw new Error(`State dimension mismatch: expected ${this.dimension}, got ${e.length}`);let t=this.normalize(e);if(this.patterns.length===0)return .5*this.dotProduct(t,t);let r=new Float32Array(this.patterns.length);for(let o=0;o<this.patterns.length;o++)r[o]=this.dotProduct(this.patterns[o].pattern,t);let s=new Float32Array(this.patterns.length),i=-1/0;for(let o=0;o<this.patterns.length;o++)s[o]=this.beta*r[o],s[o]>i&&(i=s[o]);let a=0;for(let o=0;o<this.patterns.length;o++)a+=Math.exp(s[o]-i);let c=1/this.beta*(i+Math.log(a)),u=this.dotProduct(t,t);return-c+.5*u}softmax(e){let t=new Float32Array(e.length),r=-1/0;for(let i=0;i<e.length;i++)e[i]>r&&(r=e[i]);let s=0;for(let i=0;i<e.length;i++)t[i]=Math.exp(e[i]-r),s+=t[i];if(s>0)for(let i=0;i<t.length;i++)t[i]/=s;return t}dotProduct(e,t){let r=0;for(let s=0;s<e.length;s++)r+=e[s]*t[s];return r}cosineSimilarity(e,t){let r=this.dotProduct(e,t),s=Math.sqrt(this.dotProduct(e,e)),i=Math.sqrt(this.dotProduct(t,t));return s===0||i===0?0:r/(s*i)}normalize(e){let t=Math.sqrt(this.dotProduct(e,e)),r=new Float32Array(e.length);if(t>0)for(let s=0;s<e.length;s++)r[s]=e[s]/t;return r}assertEnabled(){if(!D().useHopfieldMemory)throw new Error("Hopfield memory is disabled (useHopfieldMemory feature flag is false)")}};function Ve(n){return new Pe(n)}F();var Ut={dimensions:32,curvature:-1,maxElements:1e4,efConstruction:200,M:16},_=1e-5,Ye=1-_;function Qt(n,e){let t=0;for(let r=0;r<n.length;r++)t+=n[r]*e[r];return t}function A(n){let e=0;for(let t=0;t<n.length;t++)e+=n[t]*n[t];return e}function qt(n,e){let t=new Float32Array(n.length);for(let r=0;r<n.length;r++)t[r]=n[r]-e[r];return t}var T=class n{static poincareDistance(e,t){let r=A(qt(e,t)),s=Math.max(_,1-A(e)),i=Math.max(_,1-A(t));return Math.acosh(Math.max(1,1+2*r/(s*i)))}static mobiusAdd(e,t){let r=Qt(e,t),s=A(e),i=A(t),a=Math.max(_,1+2*r+s*i),c=1+2*r+i,u=1-s,o=new Float32Array(e.length);for(let l=0;l<e.length;l++)o[l]=(c*e[l]+u*t[l])/a;return n.project(o)}static expMap(e,t){let r=2/Math.max(_,1-A(e)),s=Math.sqrt(A(t));if(s<_)return new Float32Array(e);let i=Math.tanh(r*s/2),a=new Float32Array(t.length);for(let c=0;c<t.length;c++)a[c]=i/s*t[c];return n.mobiusAdd(e,a)}static project(e){let t=Math.sqrt(A(e));if(t<=Ye)return new Float32Array(e);let r=Ye/t,s=new Float32Array(e.length);for(let i=0;i<e.length;i++)s[i]=e[i]*r;return s}static euclideanToHyperbolic(e){let t=Math.sqrt(A(e));if(t<_)return new Float32Array(e.length);let r=Math.tanh(t)/t,s=new Float32Array(e.length);for(let i=0;i<e.length;i++)s[i]=e[i]*r;return n.project(s)}},we=class{config;points=new Map;constructor(e){if(this.config={...Ut,...e},this.config.dimensions<=0)throw new Error(`dimensions must be positive, got ${this.config.dimensions}`);if(this.config.curvature>=0)throw new Error(`curvature must be negative for hyperbolic space, got ${this.config.curvature}`);if(this.config.maxElements<=0)throw new Error(`maxElements must be positive, got ${this.config.maxElements}`)}insert(e,t,r){if(t.length!==this.config.dimensions)throw new Error(`Dimension mismatch: expected ${this.config.dimensions}, got ${t.length}`);if(this.points.size>=this.config.maxElements)throw new Error(`Maximum elements (${this.config.maxElements}) reached`);this.points.set(e,{id:e,coordinates:T.project(t),metadata:r?{...r}:void 0})}search(e,t){if(e.length!==this.config.dimensions)throw new Error(`Query dimension mismatch: expected ${this.config.dimensions}, got ${e.length}`);let r=T.project(e),s=[];for(let i of this.points.values())s.push({id:i.id,distance:T.poincareDistance(r,i.coordinates),point:i});return s.sort((i,a)=>i.distance-a.distance),s.slice(0,Math.max(0,t))}embedHierarchy(e){let t=new Map;if(e.length===0)return t;let r=this.config.dimensions,s=new Map,i=new Map,a=[];for(let u of e)if(i.set(u.id,u),!u.parentId)a.push(u.id);else{let o=s.get(u.parentId);o||(o=[],s.set(u.parentId,o)),o.push(u.id)}let c=a.map((u,o)=>({id:u,depth:0,angOff:2*Math.PI*o/Math.max(1,a.length),angSpan:2*Math.PI/Math.max(1,a.length)}));for(;c.length>0;){let{id:u,depth:o,angOff:l,angSpan:f}=c.shift(),d=Math.tanh(.3*(o+.1)),h=l+f/2,m=new Float32Array(r);m[0]=d*Math.cos(h),m[1]=d*Math.sin(h);let p=i.get(u);if(p&&p.features.length>0){let N=d*.1;for(let x=2;x<r&&x-2<p.features.length;x++)m[x]=p.features[x-2]*N}let y=T.project(m);t.set(u,y),this.points.set(u,{id:u,coordinates:y,metadata:{depth:o,parentId:p?.parentId}});let S=s.get(u)??[];for(let N=0;N<S.length;N++){let x=f/Math.max(1,S.length);c.push({id:S[N],depth:o+1,angOff:l+N*x,angSpan:x})}}return t}getStats(){return{elementCount:this.points.size,dimensions:this.config.dimensions,curvature:this.config.curvature}}};function Ke(n){return zt()?new we(n):null}function zt(){return D().useHyperbolicHnsw}F();var Se=class{index=null;initialized=!1;config;constructor(e){this.config=e??{}}ensureInitialized(){if(this.initialized)return this.index!==null;if(this.initialized=!0,!M())return!1;try{return this.index=Ke(this.config),this.index!==null}catch(e){return console.warn("[HyperbolicPatternIndex] Failed to create HyperbolicHNSW:",e instanceof Error?e.message:e),this.index=null,!1}}get isAvailable(){return this.index!==null}indexPattern(e,t,r){if(!(!this.ensureInitialized()||!this.index))try{let s=t instanceof Float32Array?t:new Float32Array(t),i=T.euclideanToHyperbolic(s);this.index.insert(e,i,r)}catch(s){console.debug(`[HyperbolicPatternIndex] Failed to index pattern ${e}:`,s instanceof Error?s.message:s)}}search(e,t){if(!this.ensureInitialized()||!this.index)return[];try{let r=e instanceof Float32Array?e:new Float32Array(e),s=T.euclideanToHyperbolic(r);return this.index.search(s,t).map(a=>({patternId:a.id,distance:a.distance,metadata:a.point.metadata}))}catch(r){return console.warn("[HyperbolicPatternIndex] Search failed:",r instanceof Error?r.message:r),[]}}getStats(){return this.index?this.index.getStats():null}reset(){this.index=null,this.initialized=!1}};function Ze(n){return new Se(n)}var be=null;function et(){return be||(be=Ue({dimensions:1e4})),be}var Ee;function $t(){return Ee===void 0&&(Ee=Qe()),Ee}var U=null,Re=0;function tt(n){return(!U||Re!==n)&&(U=Ve({dimension:n,maxPatterns:1e4}),Re=n),U}var W={namespace:"qe-patterns",embeddingDimension:384,hnsw:{M:16,efConstruction:200,efSearch:100,maxElements:5e4},promotionThreshold:B,minConfidence:.3,maxPatternsPerDomain:5e3,autoCleanup:!0,cleanupIntervalMs:36e5,tokenTracking:{enabled:!0,trackInputOutput:!0,estimateCosts:!0,costPerInputToken:3e-6,costPerOutputToken:15e-6},reuseOptimization:{enabled:!0,minSimilarityForReuse:.85,minSuccessRateForReuse:.9,maxAgeForReuse:7}},Ae=class{constructor(e,t={}){this.memory=e;this.config={...W,...t}}memory;config;initialized=!1;cleanupTimer;sqliteStore=null;nullStore=null;loadingPromise=null;patternCache=new Map;domainIndex=new Map;typeIndex=new Map;tierIndex=new Map;hnswIndex=null;hnswAvailable=!1;hnswInitPromise=null;hdcCache=new Map;hdcTokenCache=new Map;deltaTracker=null;vectorDeltaTracker=void 0;hyperbolicIndex=null;stats={searchOperations:0,searchLatencies:[]};setSqliteStore(e){if(this.sqliteStore=e,H()&&!this.deltaTracker)try{let t=e.getDb();this.deltaTracker=new Z(t),this.deltaTracker.initialize(),console.log("[PatternStore] Delta event sourcing initialized")}catch(t){console.warn("[PatternStore] Delta tracker init failed:",t instanceof Error?t.message:t)}this.initialized&&(this.loadingPromise=this.loadPatterns().catch(t=>console.warn("[PatternStore] Failed to load patterns after setSqliteStore:",t)).finally(()=>{this.loadingPromise=null}))}async initialize(){this.initialized||(this.tierIndex.set("short-term",new Set),this.tierIndex.set("long-term",new Set),await this.loadPatterns(),this.config.autoCleanup&&(this.cleanupTimer=setInterval(()=>this.cleanup(),this.config.cleanupIntervalMs)),this.initialized=!0)}async ensureHNSW(){return this.hnswIndex!==null?this.hnswIndex:this.hnswAvailable===!1&&this.hnswInitPromise===null&&!(this.hnswIndex===null&&this.hnswAvailable===!1)?null:this.hnswInitPromise?(await this.hnswInitPromise,this.hnswIndex):(this.hnswInitPromise=this.initializeHNSWInternal(),await this.hnswInitPromise,this.hnswInitPromise=null,this.hnswIndex)}async initializeHNSWInternal(){try{if(D().useUnifiedHnsw)try{let{HnswLegacyBridge:a}=await import("./hnsw-legacy-bridge-TYPQ2T6P.js"),{HnswAdapter:c}=await import("./hnsw-adapter-YUJVSFPD.js"),u=new c("patterns",{dimensions:this.config.embeddingDimension,M:this.config.hnsw.M,efConstruction:this.config.hnsw.efConstruction,efSearch:this.config.hnsw.efSearch,metric:"cosine"});this.hnswIndex=new a(u),this.hnswAvailable=!0,console.log("[PatternStore] Using unified HNSW via HnswLegacyBridge (ADR-071)"),await this.loadEmbeddingsIntoHNSW();return}catch(a){console.warn("[PatternStore] Unified HNSW bridge failed, falling back:",a)}let{HNSWIndex:t}=await import("./hnsw-index-FQZ47RSJ.js");this.hnswIndex=new t(this.memory,{dimensions:this.config.embeddingDimension,M:this.config.hnsw.M,efConstruction:this.config.hnsw.efConstruction,efSearch:this.config.hnsw.efSearch,maxElements:this.config.hnsw.maxElements,namespace:`${this.config.namespace}:hnsw`,metric:"cosine"});let r=5e3,s=this.hnswIndex.initialize(),i=new Promise((a,c)=>setTimeout(()=>c(new Error("HNSW init timeout")),r));await Promise.race([s,i]),this.hnswAvailable=this.hnswIndex.isNativeAvailable(),await this.loadEmbeddingsIntoHNSW(),console.log(`[PatternStore] HNSW lazy-initialized (native: ${this.hnswAvailable})`)}catch(e){console.warn("[PatternStore] HNSW not available, using memory backend search:",v(e)),this.hnswIndex=null,this.hnswAvailable=!1}}async loadEmbeddingsIntoHNSW(){if(!(!this.hnswIndex||!this.sqliteStore))try{let e=this.sqliteStore.getAllEmbeddings(),t=this.config.hnsw.maxElements,r=0,s=0;for(let{patternId:i,embedding:a}of e){if(r>=t)break;if(!a||a.length!==this.config.embeddingDimension){s++;continue}let c=this.patternCache.get(i);if(!c){s++;continue}try{await this.hnswIndex.insert(i,a,{filePath:c.patternType,lineCoverage:c.confidence*100,branchCoverage:c.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-c.confidence,lastUpdated:Date.now(),totalLines:0}),r++}catch{s++}}r>0&&console.log(`[PatternStore] Loaded ${r} embeddings into HNSW (skipped ${s})`)}catch(e){console.warn("[PatternStore] Failed to load SQLite embeddings into HNSW:",v(e))}}getVectorDeltaTracker(){return this.vectorDeltaTracker===void 0&&(this.vectorDeltaTracker=Ge()),this.vectorDeltaTracker}async loadPatterns(){if(this.sqliteStore)try{let e=this.sqliteStore.getPatterns({limit:5e4});for(let t of e)this.indexPattern(t);e.length>0&&console.log(`[PatternStore] Loaded ${e.length} patterns from SQLite into memory cache`)}catch(e){console.warn("[PatternStore] Failed to load patterns from SQLite:",v(e))}}indexPattern(e){this.patternCache.set(e.id,e),this.domainIndex.has(e.qeDomain)||this.domainIndex.set(e.qeDomain,new Set),this.domainIndex.get(e.qeDomain).add(e.id),this.typeIndex.has(e.patternType)||this.typeIndex.set(e.patternType,new Set),this.typeIndex.get(e.patternType).add(e.id);let t=e.tier==="long-term"?"long-term":"short-term";e.tier!==t&&(e.tier=t),this.tierIndex.get(t).add(e.id)}unindexPattern(e){this.patternCache.delete(e.id),this.domainIndex.get(e.qeDomain)?.delete(e.id),this.typeIndex.get(e.patternType)?.delete(e.id),this.tierIndex.get(e.tier)?.delete(e.id),this.hdcCache.delete(e.id),this.hdcTokenCache.delete(e.id)}async store(e){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let t=j(e);if(!t.valid)return w(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return w(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));(this.domainIndex.get(e.qeDomain)?.size||0)>=this.config.maxPatternsPerDomain&&await this.cleanupDomain(e.qeDomain);let s=this.patternCache.get(e.id)??null;if(this.indexPattern(e),this.sqliteStore)try{let i=this.sqliteStore.storePattern(e,e.embedding);i&&i!==e.id&&(this.unindexPattern(e),e.id=i,this.indexPattern(e))}catch(i){console.warn(`[PatternStore] SQLite persist failed for ${e.id}:`,v(i))}if(e.embedding){let i=await this.ensureHNSW();if(i)try{await i.insert(e.id,e.embedding,{filePath:e.patternType,lineCoverage:e.confidence*100,branchCoverage:e.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-e.confidence,lastUpdated:Date.now(),totalLines:0})}catch(a){console.warn(`[PatternStore] Failed to index embedding for ${e.id}:`,a)}}if(Q())try{let a=et().fingerprint({id:e.id,domain:e.qeDomain,type:e.patternType,content:e.description});this.hdcCache.set(e.id,a.vector)}catch(i){console.debug(`[PatternStore] HDC fingerprint failed for ${e.id}:`,v(i))}try{let i=$t();if(i){let a=[e.patternType,e.qeDomain];e.context?.tags&&a.push(...e.context.tags),e.name&&a.push(e.name);let c=i.fingerprintPattern(a);this.hdcTokenCache.set(e.id,c)}}catch(i){console.debug(`[PatternStore] HDC token fingerprint failed for ${e.id}:`,v(i))}if(ee()&&e.embedding)try{tt(e.embedding.length).store(new Float32Array(e.embedding),{id:e.id,name:e.name,domain:e.qeDomain})}catch(i){console.debug(`[PatternStore] Hopfield store failed for ${e.id}:`,v(i))}if(H()&&this.deltaTracker)try{let i={id:e.id,name:e.name,confidence:e.confidence,qualityScore:e.qualityScore,usageCount:e.usageCount,successRate:e.successRate,tier:e.tier};this.deltaTracker.createGenesis(e.id,i)}catch(i){console.debug(`[PatternStore] Delta genesis for ${e.id}:`,v(i))}if(e.embedding)try{let i=this.getVectorDeltaTracker();i&&(s?.embedding?i.recordDelta(e.id,s.embedding,e.embedding):i.getVersion(e.id)<0&&i.recordGenesis(e.id,e.embedding))}catch(i){console.debug(`[PatternStore] VectorDeltaTracker for ${e.id}:`,v(i))}try{M()&&e.embedding&&this.indexHyperbolic(e.id,e.embedding,{domain:e.qeDomain,type:e.patternType,name:e.name})}catch{}return P(e.id)}async create(e){let t=new Date,r=e.qeDomain||this.detectDomainFromType(e.patternType),s={id:C(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:e.confidence??.5,usageCount:0,successRate:0,qualityScore:.25,context:{...e.context,tags:e.context?.tags||[]},template:{...e.template,example:void 0},embedding:e.embedding,tier:"short-term",createdAt:t,lastUsedAt:t,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},i=await this.store(s);return i.success?P(s):w(i.error)}detectDomainFromType(e){return{"test-template":"test-generation","assertion-pattern":"test-generation","mock-pattern":"test-generation","coverage-strategy":"coverage-analysis","mutation-strategy":"test-generation","api-contract":"contract-testing","visual-baseline":"visual-accessibility","a11y-check":"visual-accessibility","perf-benchmark":"chaos-resilience","flaky-fix":"test-execution","refactor-safe":"code-intelligence","error-handling":"test-generation","meta-optimization":"learning-optimization"}[e]||"test-generation"}async get(e){return this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise,this.patternCache.get(e)??null}async search(e,t={}){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let r=performance.now(),s=t.limit||10,i=[];try{if(Array.isArray(e)&&ee())try{let d=tt(e.length);if(d.getPatternCount()>0){let h=d.recall(new Float32Array(e));if(h&&h.similarity>.98){let m=h.metadata.id,p=await this.get(m);if(p&&this.matchesFilters(p,t)){let y=this.calculateReuseInfo(p,h.similarity);i.push({pattern:p,score:h.similarity,matchType:"vector",similarity:h.similarity,canReuse:y.canReuse,estimatedTokenSavings:y.estimatedTokenSavings,reuseConfidence:y.reuseConfidence})}}}}catch(d){console.debug("[PatternStore] Hopfield recall failed:",v(d))}if(Array.isArray(e)&&t.useVectorSearch!==!1){let d=await this.ensureHNSW();if(d){let h=await d.search(e,s*2);for(let m of h){let p=await this.get(m.key);if(p&&this.matchesFilters(p,t)){let y=this.calculateReuseInfo(p,m.score);i.push({pattern:p,score:m.score,matchType:"vector",similarity:m.score,canReuse:y.canReuse,estimatedTokenSavings:y.estimatedTokenSavings,reuseConfidence:y.reuseConfidence})}}}}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let d=this.sqliteStore.searchFTS(e,s*2);if(d.length>0){let h=new Map(d.map(p=>[p.id,p.ftsScore])),m=new Set(i.map(p=>p.pattern.id));for(let p of i){let y=h.get(p.pattern.id);y!==void 0&&(p.score=.75*p.score+.25*y)}for(let p of d){if(m.has(p.id))continue;let y=await this.get(p.id);if(y&&this.matchesFilters(y,t)){let S=this.calculateReuseInfo(y,p.ftsScore);i.push({pattern:y,score:.5*p.ftsScore,matchType:"exact",similarity:p.ftsScore,canReuse:S.canReuse,estimatedTokenSavings:S.estimatedTokenSavings,reuseConfidence:S.reuseConfidence})}}}}catch{}if(typeof e=="string"||i.length<s){let d=await this.searchByText(typeof e=="string"?e:"",t,s-i.length),h=new Set(i.map(m=>m.pattern.id));for(let m of d)h.has(m.pattern.id)||i.push(m)}let a=720*60*60*1e3,c=Date.now();for(let d of i){let h=d.pattern.lastUsedAt?.getTime()??d.pattern.createdAt.getTime(),m=c-h,p=Math.pow(.5,m/a),y=d.pattern.usageCount>0?p:.5;d.score=d.score*(.7+.3*y)}let u=this.sqliteStore?.getDatabase();if(u&&i.length>0)try{this.nullStore||(this.nullStore=new ie(u));let d=this.nullStore.getNullSummaries(i.map(h=>h.pattern.id));for(let h of i){let m=d.get(h.pattern.id);m&&(h.nullSummary=m,h.score=ie.applyNullDiscount(h.score,m,t.contextFingerprint))}}catch(d){console.debug("[PatternStore] null discount skipped:",v(d))}i.sort((d,h)=>h.score-d.score);let o=i;t.filter&&(o=Ne(i,t.filter));let l=o.slice(0,s),f=performance.now()-r;return this.recordSearchLatency(f),P(l)}catch(a){return w(xe(a))}}async searchByText(e,t,r){let s=[],i=e.toLowerCase(),a;t.domain?a=this.domainIndex.get(t.domain)||new Set:t.patternType?a=this.typeIndex.get(t.patternType)||new Set:t.tier?a=this.tierIndex.get(t.tier)||new Set:a=new Set(this.patternCache.keys());let c=[...a];if(Q()&&i&&this.hdcCache.size>0)try{let u=et(),o=u.fingerprint({id:"query",domain:t.domain??"unknown",type:t.patternType??"unknown",content:e}),l=c.filter(h=>this.hdcCache.has(h)).map(h=>({id:h,similarity:u.similarity(o.vector,this.hdcCache.get(h))}));l.sort((h,m)=>m.similarity-h.similarity);let f=l.map(h=>h.id),d=c.filter(h=>!this.hdcCache.has(h));c=[...f,...d]}catch{}for(let u of c){if(s.length>=r)break;let o=this.patternCache.get(u);if(!o||!this.matchesFilters(o,t))continue;let l=0;if(i){let f=o.name.toLowerCase(),d=o.description.toLowerCase();f.includes(i)&&(l+=.5),d.includes(i)&&(i.length/d.length>.3?l+=.5:l+=.3);for(let h of o.context.tags)if(h.toLowerCase().includes(i)){l+=.2;break}l=Math.min(l,1)}else l=o.qualityScore;if(l>0||!i){let f=this.calculateReuseInfo(o,l);s.push({pattern:o,score:l||o.qualityScore,matchType:i?"exact":"context",similarity:l||o.qualityScore,canReuse:f.canReuse,estimatedTokenSavings:f.estimatedTokenSavings,reuseConfidence:f.reuseConfidence})}}return s}calculateReuseInfo(e,t){let{reuseOptimization:r}=this.config,s=t>=r.minSimilarityForReuse,i=e.successRate>=r.minSuccessRateForReuse,a=e.lastUsedAt instanceof Date?e.lastUsedAt.getTime():new Date(e.lastUsedAt).getTime(),u=(Date.now()-a)/(1e3*60*60*24)<=r.maxAgeForReuse,o=r.enabled&&e.reusable&&s&&i&&u,l=o?e.averageTokenSavings>0?e.averageTokenSavings:e.tokensUsed||0:0,f=t,d=e.successRate,h=Math.min(e.reuseCount/10,1),m=o?f*.4+d*.4+h*.2:0;return{canReuse:o,estimatedTokenSavings:l,reuseConfidence:m}}matchesFilters(e,t){if(t.patternType&&e.patternType!==t.patternType||t.domain&&e.qeDomain!==t.domain||t.tier&&e.tier!==t.tier||t.minConfidence!==void 0&&e.confidence<t.minConfidence||t.minQualityScore!==void 0&&e.qualityScore<t.minQualityScore)return!1;if(t.context){let r=t.context;if(r.language&&e.context.language!==r.language||r.framework&&e.context.framework!==r.framework||r.testType&&e.context.testType!==r.testType)return!1}return!0}async recordUsage(e,t,r,s){let i=await this.get(e);if(!i)return w(new Error(`Pattern not found: ${e}`));let a=new Date,c=i.usageCount+1,u=i.successfulUses+(t?1:0),o=u/c,l=t?.02:-.01,f=Math.max(.1,Math.min(1,i.confidence+l)),d=J({confidence:f,usageCount:c,successRate:o}),h={...i,usageCount:c,successfulUses:u,successRate:o,confidence:f,qualityScore:d,lastUsedAt:a};if(this.sqliteStore)try{this.sqliteStore.recordUsage(e,t,r,s)}catch(y){console.warn(`[PatternStore] SQLite recordUsage failed for ${e}:`,v(y))}if(H()&&this.deltaTracker)try{let y={id:i.id,name:i.name,confidence:i.confidence,qualityScore:i.qualityScore,usageCount:i.usageCount,successRate:i.successRate,tier:i.tier},S={id:h.id,name:h.name,confidence:h.confidence,qualityScore:h.qualityScore,usageCount:h.usageCount,successRate:h.successRate,tier:h.tier};this.deltaTracker.recordDelta(e,y,S,{success:t})}catch(y){console.debug(`[PatternStore] Delta recordDelta for ${e}:`,v(y))}let m=te(h);return m.meetsUsageCriteria&&m.meetsQualityCriteria&&m.meetsCoherenceCriteria&&h.tier==="short-term"?await this.promote(e):this.patternCache.set(e,h),P(void 0)}async promote(e){let t=await this.get(e);if(!t)return w(new Error(`Pattern not found: ${e}`));if(t.tier==="long-term")return P(void 0);let r={...t,tier:"long-term",confidence:Math.min(1,t.confidence+.1)};if(this.tierIndex.get("short-term")?.delete(e),this.tierIndex.get("long-term")?.add(e),this.patternCache.set(e,r),this.sqliteStore)try{this.sqliteStore.promotePattern(e)}catch(s){console.debug("[PatternStore] SQLite promotion error:",s instanceof Error?s.message:s)}return console.log(`[PatternStore] Promoted pattern ${e} (${t.name}) to long-term storage`),P(void 0)}async delete(e){let t=this.patternCache.get(e);if(!t)return w(new Error(`Pattern not found: ${e}`));if(this.unindexPattern(t),this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(r){console.debug("[PatternStore] SQLite deletion error:",r instanceof Error?r.message:r)}if(this.hnswIndex!==null)try{await this.hnswIndex.delete(e)}catch(r){console.debug("[PatternStore] HNSW deletion error:",r instanceof Error?r.message:r)}return P(void 0)}async getStats(){let e={},t={};for(let[o,l]of this.domainIndex)e[o]=l.size;for(let[o,l]of this.typeIndex)t[o]=l.size;let r=0,s=0,i=0,a=0;for(let o of this.patternCache.values())r+=o.confidence,s+=o.qualityScore,i+=o.successRate,a++;let c=await this.ensureHNSW(),u=c!==null?await c.getStats():{nativeHNSW:!1,vectorCount:0,indexSizeBytes:0,lazyLoaded:!0};return{totalPatterns:this.patternCache.size,byTier:{shortTerm:this.tierIndex.get("short-term")?.size||0,longTerm:this.tierIndex.get("long-term")?.size||0},byDomain:e,byType:t,avgConfidence:a>0?r/a:0,avgQualityScore:a>0?s/a:0,avgSuccessRate:a>0?i/a:0,searchOperations:this.stats.searchOperations,avgSearchLatencyMs:this.calculateAvgLatency(),hnswStats:{nativeAvailable:u.nativeHNSW,vectorCount:u.vectorCount,indexSizeBytes:u.indexSizeBytes}}}async cleanup(){let e=0,t=0,r=[],s=[];for(let i of this.patternCache.values()){let a=te(i);if(a.meetsUsageCriteria&&a.meetsQualityCriteria&&a.meetsCoherenceCriteria){s.push(i.id);continue}if(i.tier==="short-term"){let u=i.createdAt instanceof Date?i.createdAt.getTime():new Date(i.createdAt).getTime(),o=Date.now()-u,l=o>10080*60*1e3,f=i.qualityScore<.2,d=i.usageCount===0&&o>1440*60*1e3;(l&&f||d)&&r.push(i.id)}}for(let i of s)(await this.promote(i)).success&&t++;for(let i of r)(await this.delete(i)).success&&e++;return console.log(`[PatternStore] Cleanup: removed ${e}, promoted ${t}`),{removed:e,promoted:t}}async cleanupDomain(e){let t=this.domainIndex.get(e);if(!t||t.size<this.config.maxPatternsPerDomain)return;let r=[];for(let a of t){let c=this.patternCache.get(a);c&&r.push(c)}r.sort((a,c)=>a.qualityScore-c.qualityScore);let s=Math.ceil(r.length*.1),i=0;for(let a of r){if(i>=s)break;a.tier==="short-term"&&(await this.delete(a.id),i++)}}recordSearchLatency(e){this.stats.searchOperations++,this.stats.searchLatencies.push(e),this.stats.searchLatencies.length>1e3&&(this.stats.searchLatencies=this.stats.searchLatencies.slice(-1e3))}calculateAvgLatency(){return this.stats.searchLatencies.length===0?0:this.stats.searchLatencies.reduce((t,r)=>t+r,0)/this.stats.searchLatencies.length}async dispose(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0),this.patternCache.clear(),this.domainIndex.clear(),this.typeIndex.clear(),this.tierIndex.clear(),this.hdcCache.clear(),this.deltaTracker=null,this.hyperbolicIndex&&(this.hyperbolicIndex.reset(),this.hyperbolicIndex=null),U&&(U.clear(),U=null,Re=0),this.initialized=!1}indexHyperbolic(e,t,r){if(M())try{this.hyperbolicIndex||(this.hyperbolicIndex=Ze({dimensions:this.config.embeddingDimension,maxElements:this.config.hnsw.maxElements})),this.hyperbolicIndex.indexPattern(e,t,r)}catch(s){console.debug(`[PatternStore] Hyperbolic indexing failed for ${e}:`,s instanceof Error?s.message:s)}}async searchHyperbolic(e,t=10){if(!M()||!this.hyperbolicIndex)return P([]);try{let r=this.hyperbolicIndex.search(e,t),s=[];for(let i of r){let a=await this.get(i.patternId);if(!a)continue;let c=Math.exp(-i.distance),u=this.calculateReuseInfo(a,c);s.push({pattern:a,score:c,matchType:"vector",similarity:c,canReuse:u.canReuse,estimatedTokenSavings:u.estimatedTokenSavings,reuseConfidence:u.reuseConfidence})}return P(s)}catch(r){return console.warn("[PatternStore] Hyperbolic search failed, returning empty results:",r instanceof Error?r.message:r),P([])}}};function Jr(n,e){try{if(D().useRVFPatternStore&&Oe()){let{existsSync:r}=Te("fs"),{join:s}=Te("path"),i=process.env.AQE_PROJECT_ROOT??De(),a=s(i,".agentic-qe"),c=s(a,"patterns.rvf");if(r(a)){let u={...W,...e},o=!1;try{let l=_e(a,u.embeddingDimension);if(l){o=!0;let f=new q(()=>l,{rvfPath:c,base:u,skipCloseOnDispose:!0});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),f}}catch{}if(!o){let l=new q((f,d)=>{let h=()=>{try{return Fe(f)}catch{return null}},m=h();if(m){if(m.dimension()!==d){try{m.close()}catch{}throw new Error(`RVF dimension mismatch (file=${m.dimension()}, requested=${d})`)}return m}try{return re(f,d)}catch(p){if(m=h(),m&&m.dimension()===d)return m;if(Ie(f,p instanceof Error?p.message:String(p)))return re(f,d);throw p}},{rvfPath:c,base:u});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),l}}}}catch(t){console.warn("[PatternStore] RVF store unavailable, using in-memory HNSW:",t instanceof Error?t.message:t)}return new Ae(n,e)}export{Jr as a};
|
|
50
50
|
/*! Bundled license information:
|
|
51
51
|
|
|
52
52
|
fast-json-patch/commonjs/helpers.js:
|
|
@@ -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.13.
|
|
2
|
-
import{b as d,d as L}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.13.1");process.exit(0)}
|
|
2
|
+
import{b as d,d as L}from"./chunk-UCQ66N6M.js";import{createHash as m}from"crypto";import{existsSync as g,readFileSync as R,writeFileSync as A,openSync as X,writeSync as U,closeSync as f}from"fs";var p=[`CREATE TABLE IF NOT EXISTS qe_patterns (
|
|
3
3
|
id TEXT PRIMARY KEY, pattern_type TEXT NOT NULL, qe_domain TEXT NOT NULL,
|
|
4
4
|
domain TEXT NOT NULL, name TEXT NOT NULL, description TEXT,
|
|
5
5
|
confidence REAL DEFAULT 0.5, usage_count INTEGER DEFAULT 0,
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.
|
|
2
|
-
import{i as f,m as P}from"./chunk-G5DFYX3J.js";import{d as p,e as y}from"./chunk-OXXMVQDF.js";import{b as h,d as U}from"./chunk-2DIT5AUU.js";import{a as T,c as C}from"./chunk-CYL2FV23.js";P();C();U();y();import{randomUUID as v}from"crypto";var M=p("TokenTracker"),S={costPerInputToken:.003/1e3,costPerOutputToken:.015/1e3},I={filePath:".agentic-qe/token-metrics.json",autoSaveIntervalMs:6e4,maxMetricsInMemory:1e4},m=class u{taskMetrics=[];agentMetrics=new Map;domainMetrics=new Map;sessionId;sessionStartTime;costConfig;cacheHits=0;earlyExits=0;totalTokensSaved=0;totalPatternsReused=0;initialized=!1;persistenceConfig=I;autoSaveTimer=null;isDirty=!1;db=null;kvPersistCount=0;static KV_NAMESPACE="token-usage-metrics";static KV_KEY="token-tracker-snapshot";static KV_TTL=604800;static KV_PERSIST_INTERVAL=10;constructor(){this.sessionId=`session-${Date.now()}-${v().substring(0,8)}`,this.sessionStartTime=Date.now(),this.costConfig=S}initialize(t){this.initialized||(this.initialized=!0,t&&(this.costConfig={...S,...t}),this.initializeDb().catch(e=>{M.warn("DB initialization failed",{error:e instanceof Error?e.message:String(e)})}),this.startAutoSave())}setCostConfig(t){this.costConfig={...this.costConfig,...t}}recordTokenUsage(t,e,n,a,s,r){this.ensureInitialized();let c,d,i,o,l,k;typeof e=="object"?(c="default",d="unknown",i="unknown",o=e,l=!1,k=0):(c=e,d=n??"unknown",i=a??"unknown",o=s,l=r?.patternReused??!1,k=r?.tokensSaved??0),o.estimatedCostUsd===void 0&&(o.estimatedCostUsd=this.calculateCost(o));let g={taskId:t,agentId:c,domain:d,operation:i,timestamp:Date.now(),usage:o,patternReused:l,tokensSaved:k};this.taskMetrics.push(g),this.updateAgentMetrics(c,o,l,k),this.updateDomainMetrics(d,o),l&&this.totalPatternsReused++,k>0&&(this.totalTokensSaved+=k),this.isDirty=!0,this.maybePersistToKv()}recordPatternReuse(t,e){this.ensureInitialized(),this.totalPatternsReused++,this.totalTokensSaved+=e;let n={taskId:t,agentId:"pattern-cache",domain:"optimization",operation:"pattern-reuse",timestamp:Date.now(),usage:{inputTokens:0,outputTokens:0,totalTokens:0,estimatedCostUsd:0},patternReused:!0,tokensSaved:e};this.taskMetrics.push(n),this.isDirty=!0}recordCacheHit(t){this.cacheHits++,this.totalTokensSaved+=t,this.isDirty=!0}recordEarlyExit(t){this.earlyExits++,this.totalTokensSaved+=t,this.isDirty=!0}getSessionSummary(t){this.ensureInitialized();let e=this.filterByTimeframe(this.taskMetrics,t),n=this.aggregateTokenUsage(e),a=new Map;for(let i of e){let o=a.get(i.agentId);o?(o.totalInputTokens+=i.usage.inputTokens,o.totalOutputTokens+=i.usage.outputTokens,o.totalTokens+=i.usage.totalTokens,o.totalCost+=i.usage.estimatedCostUsd||0,o.tasksExecuted++,i.patternReused&&o.patternsReused++,o.estimatedTokensSaved+=i.tokensSaved||0):a.set(i.agentId,{agentId:i.agentId,totalInputTokens:i.usage.inputTokens,totalOutputTokens:i.usage.outputTokens,totalTokens:i.usage.totalTokens,totalCost:i.usage.estimatedCostUsd||0,tasksExecuted:1,patternsReused:i.patternReused?1:0,estimatedTokensSaved:i.tokensSaved||0})}let s=new Map;for(let i of e){let o=s.get(i.domain);o?(o.inputTokens+=i.usage.inputTokens,o.outputTokens+=i.usage.outputTokens,o.totalTokens+=i.usage.totalTokens,o.estimatedCostUsd=(o.estimatedCostUsd||0)+(i.usage.estimatedCostUsd||0)):s.set(i.domain,{...i.usage})}let r=n.totalTokens,c=this.totalTokensSaved,d=r+c>0?c/(r+c)*100:0;return{sessionId:this.sessionId,startTime:this.sessionStartTime,endTime:Date.now(),byAgent:a,byDomain:s,totalUsage:n,optimizationStats:{patternsReused:this.totalPatternsReused,cacheHits:this.cacheHits,earlyExits:this.earlyExits,tokensSaved:this.totalTokensSaved,savingsPercentage:Math.round(d*100)/100}}}getAgentMetrics(t,e){this.ensureInitialized();let n=this.filterByTimeframe(this.taskMetrics,e);if(t){let s=n.filter(r=>r.agentId===t);return this.aggregateAgentMetrics(t,s)}let a=new Map;for(let s of n){let r=a.get(s.agentId)||[];r.push(s),a.set(s.agentId,r)}return Array.from(a.entries()).map(([s,r])=>this.aggregateAgentMetrics(s,r))}getDomainMetrics(t,e){this.ensureInitialized();let n=this.filterByTimeframe(this.taskMetrics,e);if(t){let s=n.filter(r=>r.domain===t);return this.aggregateTokenUsage(s)}let a=new Map;for(let s of n){let r=a.get(s.domain);r?(r.inputTokens+=s.usage.inputTokens,r.outputTokens+=s.usage.outputTokens,r.totalTokens+=s.usage.totalTokens,r.estimatedCostUsd=(r.estimatedCostUsd||0)+(s.usage.estimatedCostUsd||0)):a.set(s.domain,{...s.usage})}return a}getTaskMetrics(t){return this.ensureInitialized(),this.filterByTimeframe(this.taskMetrics,t)}getEfficiencyReport(t){return this.getTokenEfficiency(t)}getTokenEfficiency(t){this.ensureInitialized();let e=this.filterByTimeframe(this.taskMetrics,t),a=this.aggregateTokenUsage(e).totalTokens,s=this.totalTokensSaved,r=a+s>0?s/(a+s)*100:0,c=e.length,d=c>0?e.filter(l=>l.patternReused).length/c:0,i=c>0?a/c:0,o=this.generateRecommendations(e);return{totalTokensUsed:a,totalTokensSaved:s,savingsPercentage:Math.round(r*100)/100,patternReuseRate:Math.round(d*100)/100,averageTokensPerTask:Math.round(i),recommendations:o}}reset(){this.stopAutoSave(),this.taskMetrics=[],this.agentMetrics.clear(),this.domainMetrics.clear(),this.sessionId=`session-${Date.now()}-${v().substring(0,8)}`,this.sessionStartTime=Date.now(),this.cacheHits=0,this.earlyExits=0,this.totalTokensSaved=0,this.totalPatternsReused=0,this.isDirty=!1}configurePersistence(t){this.persistenceConfig={...this.persistenceConfig,...t},t.autoSaveIntervalMs!==void 0&&(this.stopAutoSave(),t.autoSaveIntervalMs>0&&this.startAutoSave())}startAutoSave(){this.autoSaveTimer||this.persistenceConfig.autoSaveIntervalMs>0&&(this.autoSaveTimer=setInterval(()=>{this.isDirty&&this.save().catch(t=>{console.warn("[TokenMetricsCollector] Auto-save failed:",t)})},this.persistenceConfig.autoSaveIntervalMs))}stopAutoSave(){this.autoSaveTimer&&(clearInterval(this.autoSaveTimer),this.autoSaveTimer=null)}async save(){let t=await import("fs"),e=await import("path"),n={version:"1.0.0",sessionId:this.sessionId,sessionStartTime:this.sessionStartTime,taskMetrics:this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory),optimizationStats:{cacheHits:this.cacheHits,earlyExits:this.earlyExits,totalTokensSaved:this.totalTokensSaved,totalPatternsReused:this.totalPatternsReused},lastSavedAt:Date.now()},a=e.resolve(this.persistenceConfig.filePath),s=e.dirname(a);t.existsSync(s)||t.mkdirSync(s,{recursive:!0}),t.writeFileSync(a,JSON.stringify(n,null,2)),this.isDirty=!1}async load(){let t=await import("fs"),n=(await import("path")).resolve(this.persistenceConfig.filePath);if(!t.existsSync(n))return!1;try{let a=t.readFileSync(n,"utf-8"),s=h(a);if(!s.version||!s.version.startsWith("1."))return console.warn("[TokenMetricsCollector] Incompatible data version, skipping load"),!1;let r=s.taskMetrics||[];this.taskMetrics=[...r,...this.taskMetrics],this.cacheHits+=s.optimizationStats?.cacheHits||0,this.earlyExits+=s.optimizationStats?.earlyExits||0,this.totalTokensSaved+=s.optimizationStats?.totalTokensSaved||0,this.totalPatternsReused+=s.optimizationStats?.totalPatternsReused||0;for(let c of r)this.updateAgentMetrics(c.agentId,c.usage,c.patternReused,c.tokensSaved||0),this.updateDomainMetrics(c.domain,c.usage);return this.taskMetrics.length>this.persistenceConfig.maxMetricsInMemory&&(this.taskMetrics=this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory)),!0}catch(a){return console.warn("[TokenMetricsCollector] Failed to load persisted data:",a),!1}}getPersistenceFilePath(){return this.persistenceConfig.filePath}hasUnsavedChanges(){return this.isDirty}async initializeDb(){try{this.db=f(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(t){console.warn("[TokenMetricsCollector] DB init failed, using memory-only:",T(t)),this.db=null}}async persistToKv(){if(!this.db)return;let t={version:"1.0.0",sessionId:this.sessionId,sessionStartTime:this.sessionStartTime,taskMetrics:this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory),optimizationStats:{cacheHits:this.cacheHits,earlyExits:this.earlyExits,totalTokensSaved:this.totalTokensSaved,totalPatternsReused:this.totalPatternsReused},lastSavedAt:Date.now()};await this.db.kvSet(u.KV_KEY,t,u.KV_NAMESPACE,u.KV_TTL)}async loadFromKv(){if(!this.db)return!1;let t=await this.db.kvGet(u.KV_KEY,u.KV_NAMESPACE);if(!t)return!1;if(!t.version||!t.version.startsWith("1."))return console.warn("[TokenMetricsCollector] Incompatible kv_store data version, skipping load"),!1;let e=t.taskMetrics||[];this.taskMetrics=[...e,...this.taskMetrics],this.cacheHits+=t.optimizationStats?.cacheHits||0,this.earlyExits+=t.optimizationStats?.earlyExits||0,this.totalTokensSaved+=t.optimizationStats?.totalTokensSaved||0,this.totalPatternsReused+=t.optimizationStats?.totalPatternsReused||0;for(let n of e)this.updateAgentMetrics(n.agentId,n.usage,n.patternReused,n.tokensSaved||0),this.updateDomainMetrics(n.domain,n.usage);return this.taskMetrics.length>this.persistenceConfig.maxMetricsInMemory&&(this.taskMetrics=this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory)),!0}maybePersistToKv(){this.kvPersistCount++,this.kvPersistCount>=u.KV_PERSIST_INTERVAL&&(this.kvPersistCount=0,this.persistToKv().catch(t=>{M.warn("KV persist failed",{error:t instanceof Error?t.message:String(t)})}))}ensureInitialized(){this.initialized||this.initialize()}calculateCost(t){let e=t.inputTokens*this.costConfig.costPerInputToken,n=t.outputTokens*this.costConfig.costPerOutputToken;return Math.round((e+n)*1e5)/1e5}filterByTimeframe(t,e){if(!e)return t;let n=Date.now(),a;switch(e){case"1h":a=n-3600*1e3;break;case"24h":a=n-1440*60*1e3;break;case"7d":a=n-10080*60*1e3;break;case"30d":a=n-720*60*60*1e3;break;default:return t}return t.filter(s=>s.timestamp>=a)}aggregateTokenUsage(t){let e=0,n=0,a=0,s=0;for(let r of t)e+=r.usage.inputTokens,n+=r.usage.outputTokens,a+=r.usage.totalTokens,s+=r.usage.estimatedCostUsd||0;return{inputTokens:e,outputTokens:n,totalTokens:a,estimatedCostUsd:Math.round(s*1e5)/1e5}}aggregateAgentMetrics(t,e){let n=0,a=0,s=0,r=0,c=0,d=0;for(let i of e)n+=i.usage.inputTokens,a+=i.usage.outputTokens,s+=i.usage.totalTokens,r+=i.usage.estimatedCostUsd||0,i.patternReused&&c++,d+=i.tokensSaved||0;return{agentId:t,totalInputTokens:n,totalOutputTokens:a,totalTokens:s,totalCost:Math.round(r*1e5)/1e5,tasksExecuted:e.length,patternsReused:c,estimatedTokensSaved:d}}updateAgentMetrics(t,e,n,a){let s=this.agentMetrics.get(t);s?(s.totalInputTokens+=e.inputTokens,s.totalOutputTokens+=e.outputTokens,s.totalTokens+=e.totalTokens,s.totalCost+=e.estimatedCostUsd||0,s.tasksExecuted++,n&&s.patternsReused++,s.estimatedTokensSaved+=a):this.agentMetrics.set(t,{agentId:t,totalInputTokens:e.inputTokens,totalOutputTokens:e.outputTokens,totalTokens:e.totalTokens,totalCost:e.estimatedCostUsd||0,tasksExecuted:1,patternsReused:n?1:0,estimatedTokensSaved:a})}updateDomainMetrics(t,e){let n=this.domainMetrics.get(t);n?(n.inputTokens+=e.inputTokens,n.outputTokens+=e.outputTokens,n.totalTokens+=e.totalTokens,n.estimatedCostUsd=(n.estimatedCostUsd||0)+(e.estimatedCostUsd||0)):this.domainMetrics.set(t,{...e})}generateRecommendations(t){let e=[];if(t.length===0)return["No token usage data available yet. Start executing tasks to track consumption."];let n=t.filter(i=>i.patternReused).length/t.length;n<.2?e.push("Low pattern reuse rate detected. Consider enabling pattern caching for similar tasks."):n>.5&&e.push("Good pattern reuse rate. Continue leveraging cached patterns for token savings.");let a=new Map;for(let i of t){let o=a.get(i.domain)||0;a.set(i.domain,o+i.usage.totalTokens)}let s=Array.from(a.entries()).sort((i,o)=>o[1]-i[1]);if(s.length>0){let i=s[0];e.push(`Highest token consumer: ${i[0]} (${i[1].toLocaleString()} tokens). Consider optimizing prompts or increasing caching.`)}let r=t.reduce((i,o)=>i+o.usage.inputTokens,0);return t.reduce((i,o)=>i+o.usage.outputTokens,0)/(r||1)>2&&e.push("High output-to-input token ratio. Consider requesting more concise responses."),this.cacheHits===0&&t.length>10&&e.push("No cache hits detected. Enable response caching to reduce duplicate API calls."),this.earlyExits===0&&t.length>20&&e.push("Early exit optimization not utilized. Enable high-confidence pattern matching to skip unnecessary LLM calls."),e}};function b(u){return u.toLocaleString("en-US")}function z(u){if(process.env.AQE_TOKEN_DASHBOARD_ENABLED==="false")return"Token dashboard disabled (AQE_TOKEN_DASHBOARD_ENABLED=false)";if(!u){let d=E.getSessionSummary(),i=d.totalUsage.totalTokens,o=d.totalUsage.estimatedCostUsd??0,l=d.optimizationStats.tokensSaved,k=i>0?o/i:0,g=l*k;u={totalTokens:i,totalCostUsd:o,savedTokens:l,savedCostUsd:g}}let t=u.totalTokens??0,e=u.totalCostUsd??0,n=u.savedTokens??0,a=u.savedCostUsd??0,s=u.budgetLimitUsd;if(t===0&&n===0)return"Token Dashboard: No data available";let r=`Token Usage: ${b(t)} tokens ($${e.toFixed(2)})`;n>0&&(r+=` | Saved: ${b(n)} tokens ($${a.toFixed(2)}) via pattern reuse`);let c=[];if(s!==void 0&&s>0){let d=Math.round(e/s*100);c.push(`Budget: $${e.toFixed(2)} / $${s.toFixed(2)} (${d}%)`)}if(u.tierSplit&&Object.keys(u.tierSplit).length>0){let d=Object.entries(u.tierSplit).sort((i,o)=>o[1]-i[1]).map(([i,o])=>`${i} ${o}%`);c.push(`Tier split: ${d.join(" | ")}`)}return c.length===0?r:`${r}
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.1");process.exit(0)}
|
|
2
|
+
import{i as f,m as P}from"./chunk-UCQ66N6M.js";import{d as p,e as y}from"./chunk-ELMUHNXN.js";import{b as h,d as U}from"./chunk-ZLCATRXI.js";import{a as T,c as C}from"./chunk-AYYDO52G.js";P();C();U();y();import{randomUUID as v}from"crypto";var M=p("TokenTracker"),S={costPerInputToken:.003/1e3,costPerOutputToken:.015/1e3},I={filePath:".agentic-qe/token-metrics.json",autoSaveIntervalMs:6e4,maxMetricsInMemory:1e4},m=class u{taskMetrics=[];agentMetrics=new Map;domainMetrics=new Map;sessionId;sessionStartTime;costConfig;cacheHits=0;earlyExits=0;totalTokensSaved=0;totalPatternsReused=0;initialized=!1;persistenceConfig=I;autoSaveTimer=null;isDirty=!1;db=null;kvPersistCount=0;static KV_NAMESPACE="token-usage-metrics";static KV_KEY="token-tracker-snapshot";static KV_TTL=604800;static KV_PERSIST_INTERVAL=10;constructor(){this.sessionId=`session-${Date.now()}-${v().substring(0,8)}`,this.sessionStartTime=Date.now(),this.costConfig=S}initialize(t){this.initialized||(this.initialized=!0,t&&(this.costConfig={...S,...t}),this.initializeDb().catch(e=>{M.warn("DB initialization failed",{error:e instanceof Error?e.message:String(e)})}),this.startAutoSave())}setCostConfig(t){this.costConfig={...this.costConfig,...t}}recordTokenUsage(t,e,n,a,s,r){this.ensureInitialized();let c,d,i,o,l,k;typeof e=="object"?(c="default",d="unknown",i="unknown",o=e,l=!1,k=0):(c=e,d=n??"unknown",i=a??"unknown",o=s,l=r?.patternReused??!1,k=r?.tokensSaved??0),o.estimatedCostUsd===void 0&&(o.estimatedCostUsd=this.calculateCost(o));let g={taskId:t,agentId:c,domain:d,operation:i,timestamp:Date.now(),usage:o,patternReused:l,tokensSaved:k};this.taskMetrics.push(g),this.updateAgentMetrics(c,o,l,k),this.updateDomainMetrics(d,o),l&&this.totalPatternsReused++,k>0&&(this.totalTokensSaved+=k),this.isDirty=!0,this.maybePersistToKv()}recordPatternReuse(t,e){this.ensureInitialized(),this.totalPatternsReused++,this.totalTokensSaved+=e;let n={taskId:t,agentId:"pattern-cache",domain:"optimization",operation:"pattern-reuse",timestamp:Date.now(),usage:{inputTokens:0,outputTokens:0,totalTokens:0,estimatedCostUsd:0},patternReused:!0,tokensSaved:e};this.taskMetrics.push(n),this.isDirty=!0}recordCacheHit(t){this.cacheHits++,this.totalTokensSaved+=t,this.isDirty=!0}recordEarlyExit(t){this.earlyExits++,this.totalTokensSaved+=t,this.isDirty=!0}getSessionSummary(t){this.ensureInitialized();let e=this.filterByTimeframe(this.taskMetrics,t),n=this.aggregateTokenUsage(e),a=new Map;for(let i of e){let o=a.get(i.agentId);o?(o.totalInputTokens+=i.usage.inputTokens,o.totalOutputTokens+=i.usage.outputTokens,o.totalTokens+=i.usage.totalTokens,o.totalCost+=i.usage.estimatedCostUsd||0,o.tasksExecuted++,i.patternReused&&o.patternsReused++,o.estimatedTokensSaved+=i.tokensSaved||0):a.set(i.agentId,{agentId:i.agentId,totalInputTokens:i.usage.inputTokens,totalOutputTokens:i.usage.outputTokens,totalTokens:i.usage.totalTokens,totalCost:i.usage.estimatedCostUsd||0,tasksExecuted:1,patternsReused:i.patternReused?1:0,estimatedTokensSaved:i.tokensSaved||0})}let s=new Map;for(let i of e){let o=s.get(i.domain);o?(o.inputTokens+=i.usage.inputTokens,o.outputTokens+=i.usage.outputTokens,o.totalTokens+=i.usage.totalTokens,o.estimatedCostUsd=(o.estimatedCostUsd||0)+(i.usage.estimatedCostUsd||0)):s.set(i.domain,{...i.usage})}let r=n.totalTokens,c=this.totalTokensSaved,d=r+c>0?c/(r+c)*100:0;return{sessionId:this.sessionId,startTime:this.sessionStartTime,endTime:Date.now(),byAgent:a,byDomain:s,totalUsage:n,optimizationStats:{patternsReused:this.totalPatternsReused,cacheHits:this.cacheHits,earlyExits:this.earlyExits,tokensSaved:this.totalTokensSaved,savingsPercentage:Math.round(d*100)/100}}}getAgentMetrics(t,e){this.ensureInitialized();let n=this.filterByTimeframe(this.taskMetrics,e);if(t){let s=n.filter(r=>r.agentId===t);return this.aggregateAgentMetrics(t,s)}let a=new Map;for(let s of n){let r=a.get(s.agentId)||[];r.push(s),a.set(s.agentId,r)}return Array.from(a.entries()).map(([s,r])=>this.aggregateAgentMetrics(s,r))}getDomainMetrics(t,e){this.ensureInitialized();let n=this.filterByTimeframe(this.taskMetrics,e);if(t){let s=n.filter(r=>r.domain===t);return this.aggregateTokenUsage(s)}let a=new Map;for(let s of n){let r=a.get(s.domain);r?(r.inputTokens+=s.usage.inputTokens,r.outputTokens+=s.usage.outputTokens,r.totalTokens+=s.usage.totalTokens,r.estimatedCostUsd=(r.estimatedCostUsd||0)+(s.usage.estimatedCostUsd||0)):a.set(s.domain,{...s.usage})}return a}getTaskMetrics(t){return this.ensureInitialized(),this.filterByTimeframe(this.taskMetrics,t)}getEfficiencyReport(t){return this.getTokenEfficiency(t)}getTokenEfficiency(t){this.ensureInitialized();let e=this.filterByTimeframe(this.taskMetrics,t),a=this.aggregateTokenUsage(e).totalTokens,s=this.totalTokensSaved,r=a+s>0?s/(a+s)*100:0,c=e.length,d=c>0?e.filter(l=>l.patternReused).length/c:0,i=c>0?a/c:0,o=this.generateRecommendations(e);return{totalTokensUsed:a,totalTokensSaved:s,savingsPercentage:Math.round(r*100)/100,patternReuseRate:Math.round(d*100)/100,averageTokensPerTask:Math.round(i),recommendations:o}}reset(){this.stopAutoSave(),this.taskMetrics=[],this.agentMetrics.clear(),this.domainMetrics.clear(),this.sessionId=`session-${Date.now()}-${v().substring(0,8)}`,this.sessionStartTime=Date.now(),this.cacheHits=0,this.earlyExits=0,this.totalTokensSaved=0,this.totalPatternsReused=0,this.isDirty=!1}configurePersistence(t){this.persistenceConfig={...this.persistenceConfig,...t},t.autoSaveIntervalMs!==void 0&&(this.stopAutoSave(),t.autoSaveIntervalMs>0&&this.startAutoSave())}startAutoSave(){this.autoSaveTimer||this.persistenceConfig.autoSaveIntervalMs>0&&(this.autoSaveTimer=setInterval(()=>{this.isDirty&&this.save().catch(t=>{console.warn("[TokenMetricsCollector] Auto-save failed:",t)})},this.persistenceConfig.autoSaveIntervalMs))}stopAutoSave(){this.autoSaveTimer&&(clearInterval(this.autoSaveTimer),this.autoSaveTimer=null)}async save(){let t=await import("fs"),e=await import("path"),n={version:"1.0.0",sessionId:this.sessionId,sessionStartTime:this.sessionStartTime,taskMetrics:this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory),optimizationStats:{cacheHits:this.cacheHits,earlyExits:this.earlyExits,totalTokensSaved:this.totalTokensSaved,totalPatternsReused:this.totalPatternsReused},lastSavedAt:Date.now()},a=e.resolve(this.persistenceConfig.filePath),s=e.dirname(a);t.existsSync(s)||t.mkdirSync(s,{recursive:!0}),t.writeFileSync(a,JSON.stringify(n,null,2)),this.isDirty=!1}async load(){let t=await import("fs"),n=(await import("path")).resolve(this.persistenceConfig.filePath);if(!t.existsSync(n))return!1;try{let a=t.readFileSync(n,"utf-8"),s=h(a);if(!s.version||!s.version.startsWith("1."))return console.warn("[TokenMetricsCollector] Incompatible data version, skipping load"),!1;let r=s.taskMetrics||[];this.taskMetrics=[...r,...this.taskMetrics],this.cacheHits+=s.optimizationStats?.cacheHits||0,this.earlyExits+=s.optimizationStats?.earlyExits||0,this.totalTokensSaved+=s.optimizationStats?.totalTokensSaved||0,this.totalPatternsReused+=s.optimizationStats?.totalPatternsReused||0;for(let c of r)this.updateAgentMetrics(c.agentId,c.usage,c.patternReused,c.tokensSaved||0),this.updateDomainMetrics(c.domain,c.usage);return this.taskMetrics.length>this.persistenceConfig.maxMetricsInMemory&&(this.taskMetrics=this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory)),!0}catch(a){return console.warn("[TokenMetricsCollector] Failed to load persisted data:",a),!1}}getPersistenceFilePath(){return this.persistenceConfig.filePath}hasUnsavedChanges(){return this.isDirty}async initializeDb(){try{this.db=f(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(t){console.warn("[TokenMetricsCollector] DB init failed, using memory-only:",T(t)),this.db=null}}async persistToKv(){if(!this.db)return;let t={version:"1.0.0",sessionId:this.sessionId,sessionStartTime:this.sessionStartTime,taskMetrics:this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory),optimizationStats:{cacheHits:this.cacheHits,earlyExits:this.earlyExits,totalTokensSaved:this.totalTokensSaved,totalPatternsReused:this.totalPatternsReused},lastSavedAt:Date.now()};await this.db.kvSet(u.KV_KEY,t,u.KV_NAMESPACE,u.KV_TTL)}async loadFromKv(){if(!this.db)return!1;let t=await this.db.kvGet(u.KV_KEY,u.KV_NAMESPACE);if(!t)return!1;if(!t.version||!t.version.startsWith("1."))return console.warn("[TokenMetricsCollector] Incompatible kv_store data version, skipping load"),!1;let e=t.taskMetrics||[];this.taskMetrics=[...e,...this.taskMetrics],this.cacheHits+=t.optimizationStats?.cacheHits||0,this.earlyExits+=t.optimizationStats?.earlyExits||0,this.totalTokensSaved+=t.optimizationStats?.totalTokensSaved||0,this.totalPatternsReused+=t.optimizationStats?.totalPatternsReused||0;for(let n of e)this.updateAgentMetrics(n.agentId,n.usage,n.patternReused,n.tokensSaved||0),this.updateDomainMetrics(n.domain,n.usage);return this.taskMetrics.length>this.persistenceConfig.maxMetricsInMemory&&(this.taskMetrics=this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory)),!0}maybePersistToKv(){this.kvPersistCount++,this.kvPersistCount>=u.KV_PERSIST_INTERVAL&&(this.kvPersistCount=0,this.persistToKv().catch(t=>{M.warn("KV persist failed",{error:t instanceof Error?t.message:String(t)})}))}ensureInitialized(){this.initialized||this.initialize()}calculateCost(t){let e=t.inputTokens*this.costConfig.costPerInputToken,n=t.outputTokens*this.costConfig.costPerOutputToken;return Math.round((e+n)*1e5)/1e5}filterByTimeframe(t,e){if(!e)return t;let n=Date.now(),a;switch(e){case"1h":a=n-3600*1e3;break;case"24h":a=n-1440*60*1e3;break;case"7d":a=n-10080*60*1e3;break;case"30d":a=n-720*60*60*1e3;break;default:return t}return t.filter(s=>s.timestamp>=a)}aggregateTokenUsage(t){let e=0,n=0,a=0,s=0;for(let r of t)e+=r.usage.inputTokens,n+=r.usage.outputTokens,a+=r.usage.totalTokens,s+=r.usage.estimatedCostUsd||0;return{inputTokens:e,outputTokens:n,totalTokens:a,estimatedCostUsd:Math.round(s*1e5)/1e5}}aggregateAgentMetrics(t,e){let n=0,a=0,s=0,r=0,c=0,d=0;for(let i of e)n+=i.usage.inputTokens,a+=i.usage.outputTokens,s+=i.usage.totalTokens,r+=i.usage.estimatedCostUsd||0,i.patternReused&&c++,d+=i.tokensSaved||0;return{agentId:t,totalInputTokens:n,totalOutputTokens:a,totalTokens:s,totalCost:Math.round(r*1e5)/1e5,tasksExecuted:e.length,patternsReused:c,estimatedTokensSaved:d}}updateAgentMetrics(t,e,n,a){let s=this.agentMetrics.get(t);s?(s.totalInputTokens+=e.inputTokens,s.totalOutputTokens+=e.outputTokens,s.totalTokens+=e.totalTokens,s.totalCost+=e.estimatedCostUsd||0,s.tasksExecuted++,n&&s.patternsReused++,s.estimatedTokensSaved+=a):this.agentMetrics.set(t,{agentId:t,totalInputTokens:e.inputTokens,totalOutputTokens:e.outputTokens,totalTokens:e.totalTokens,totalCost:e.estimatedCostUsd||0,tasksExecuted:1,patternsReused:n?1:0,estimatedTokensSaved:a})}updateDomainMetrics(t,e){let n=this.domainMetrics.get(t);n?(n.inputTokens+=e.inputTokens,n.outputTokens+=e.outputTokens,n.totalTokens+=e.totalTokens,n.estimatedCostUsd=(n.estimatedCostUsd||0)+(e.estimatedCostUsd||0)):this.domainMetrics.set(t,{...e})}generateRecommendations(t){let e=[];if(t.length===0)return["No token usage data available yet. Start executing tasks to track consumption."];let n=t.filter(i=>i.patternReused).length/t.length;n<.2?e.push("Low pattern reuse rate detected. Consider enabling pattern caching for similar tasks."):n>.5&&e.push("Good pattern reuse rate. Continue leveraging cached patterns for token savings.");let a=new Map;for(let i of t){let o=a.get(i.domain)||0;a.set(i.domain,o+i.usage.totalTokens)}let s=Array.from(a.entries()).sort((i,o)=>o[1]-i[1]);if(s.length>0){let i=s[0];e.push(`Highest token consumer: ${i[0]} (${i[1].toLocaleString()} tokens). Consider optimizing prompts or increasing caching.`)}let r=t.reduce((i,o)=>i+o.usage.inputTokens,0);return t.reduce((i,o)=>i+o.usage.outputTokens,0)/(r||1)>2&&e.push("High output-to-input token ratio. Consider requesting more concise responses."),this.cacheHits===0&&t.length>10&&e.push("No cache hits detected. Enable response caching to reduce duplicate API calls."),this.earlyExits===0&&t.length>20&&e.push("Early exit optimization not utilized. Enable high-confidence pattern matching to skip unnecessary LLM calls."),e}};function b(u){return u.toLocaleString("en-US")}function z(u){if(process.env.AQE_TOKEN_DASHBOARD_ENABLED==="false")return"Token dashboard disabled (AQE_TOKEN_DASHBOARD_ENABLED=false)";if(!u){let d=E.getSessionSummary(),i=d.totalUsage.totalTokens,o=d.totalUsage.estimatedCostUsd??0,l=d.optimizationStats.tokensSaved,k=i>0?o/i:0,g=l*k;u={totalTokens:i,totalCostUsd:o,savedTokens:l,savedCostUsd:g}}let t=u.totalTokens??0,e=u.totalCostUsd??0,n=u.savedTokens??0,a=u.savedCostUsd??0,s=u.budgetLimitUsd;if(t===0&&n===0)return"Token Dashboard: No data available";let r=`Token Usage: ${b(t)} tokens ($${e.toFixed(2)})`;n>0&&(r+=` | Saved: ${b(n)} tokens ($${a.toFixed(2)}) via pattern reuse`);let c=[];if(s!==void 0&&s>0){let d=Math.round(e/s*100);c.push(`Budget: $${e.toFixed(2)} / $${s.toFixed(2)} (${d}%)`)}if(u.tierSplit&&Object.keys(u.tierSplit).length>0){let d=Object.entries(u.tierSplit).sort((i,o)=>o[1]-i[1]).map(([i,o])=>`${i} ${o}%`);c.push(`Tier split: ${d.join(" | ")}`)}return c.length===0?r:`${r}
|
|
3
3
|
${c.join(" | ")}`}var E=new m;function $(u){return`$${u.toFixed(2)}`}export{z as a,E as b,$ as c};
|